VirtualBox

source: vbox/trunk/src/VBox/Devices/Audio/HDAStream.cpp@ 74067

Last change on this file since 74067 was 74037, checked in by vboxsync, 6 years ago

Audio/HDAStream: Renaming nit.

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 63.9 KB
Line 
1/* $Id: HDAStream.cpp 74037 2018-09-03 09:51:51Z vboxsync $ */
2/** @file
3 * HDAStream.cpp - Stream functions for HD Audio.
4 */
5
6/*
7 * Copyright (C) 2017-2018 Oracle Corporation
8 *
9 * This file is part of VirtualBox Open Source Edition (OSE), as
10 * available from http://www.virtualbox.org. This file is free software;
11 * you can redistribute it and/or modify it under the terms of the GNU
12 * General Public License (GPL) as published by the Free Software
13 * Foundation, in version 2 as it comes in the "COPYING" file of the
14 * VirtualBox OSE distribution. VirtualBox OSE is distributed in the
15 * hope that it will be useful, but WITHOUT ANY WARRANTY of any kind.
16 */
17
18
19/*********************************************************************************************************************************
20* Header Files *
21*********************************************************************************************************************************/
22#define LOG_GROUP LOG_GROUP_DEV_HDA
23#include <VBox/log.h>
24
25#include <iprt/mem.h>
26#include <iprt/semaphore.h>
27
28#include <VBox/vmm/pdmdev.h>
29#include <VBox/vmm/pdmaudioifs.h>
30
31#include "DrvAudio.h"
32
33#include "DevHDA.h"
34#include "HDAStream.h"
35
36
37#ifdef IN_RING3
38
39/**
40 * Creates an HDA stream.
41 *
42 * @returns IPRT status code.
43 * @param pStream HDA stream to create.
44 * @param pThis HDA state to assign the HDA stream to.
45 * @param u8SD Stream descriptor number to assign.
46 */
47int hdaR3StreamCreate(PHDASTREAM pStream, PHDASTATE pThis, uint8_t u8SD)
48{
49 RT_NOREF(pThis);
50 AssertPtrReturn(pStream, VERR_INVALID_POINTER);
51
52 pStream->u8SD = u8SD;
53 pStream->pMixSink = NULL;
54 pStream->pHDAState = pThis;
55 pStream->pTimer = pThis->pTimer[u8SD];
56 AssertPtr(pStream->pTimer);
57
58 pStream->State.fInReset = false;
59 pStream->State.fRunning = false;
60#ifdef HDA_USE_DMA_ACCESS_HANDLER
61 RTListInit(&pStream->State.lstDMAHandlers);
62#endif
63
64 int rc = RTCritSectInit(&pStream->CritSect);
65 AssertRCReturn(rc, rc);
66
67 rc = hdaR3StreamPeriodCreate(&pStream->State.Period);
68 AssertRCReturn(rc, rc);
69
70 pStream->State.tsLastUpdateNs = 0;
71
72#ifdef DEBUG
73 rc = RTCritSectInit(&pStream->Dbg.CritSect);
74 AssertRCReturn(rc, rc);
75#endif
76
77 pStream->Dbg.Runtime.fEnabled = pThis->Dbg.fEnabled;
78
79 if (pStream->Dbg.Runtime.fEnabled)
80 {
81 char szFile[64];
82
83 if (hdaGetDirFromSD(pStream->u8SD) == PDMAUDIODIR_IN)
84 RTStrPrintf(szFile, sizeof(szFile), "hdaStreamWriteSD%RU8", pStream->u8SD);
85 else
86 RTStrPrintf(szFile, sizeof(szFile), "hdaStreamReadSD%RU8", pStream->u8SD);
87
88 char szPath[RTPATH_MAX + 1];
89 int rc2 = DrvAudioHlpFileNameGet(szPath, sizeof(szPath), pThis->Dbg.szOutPath, szFile,
90 0 /* uInst */, PDMAUDIOFILETYPE_WAV, PDMAUDIOFILENAME_FLAG_NONE);
91 AssertRC(rc2);
92 rc2 = DrvAudioHlpFileCreate(PDMAUDIOFILETYPE_WAV, szPath, PDMAUDIOFILE_FLAG_NONE, &pStream->Dbg.Runtime.pFileStream);
93 AssertRC(rc2);
94
95 if (hdaGetDirFromSD(pStream->u8SD) == PDMAUDIODIR_IN)
96 RTStrPrintf(szFile, sizeof(szFile), "hdaDMAWriteSD%RU8", pStream->u8SD);
97 else
98 RTStrPrintf(szFile, sizeof(szFile), "hdaDMAReadSD%RU8", pStream->u8SD);
99
100 rc2 = DrvAudioHlpFileNameGet(szPath, sizeof(szPath), pThis->Dbg.szOutPath, szFile,
101 0 /* uInst */, PDMAUDIOFILETYPE_WAV, PDMAUDIOFILENAME_FLAG_NONE);
102 AssertRC(rc2);
103
104 rc2 = DrvAudioHlpFileCreate(PDMAUDIOFILETYPE_WAV, szPath, PDMAUDIOFILE_FLAG_NONE, &pStream->Dbg.Runtime.pFileDMA);
105 AssertRC(rc2);
106
107 /* Delete stale debugging files from a former run. */
108 DrvAudioHlpFileDelete(pStream->Dbg.Runtime.pFileStream);
109 DrvAudioHlpFileDelete(pStream->Dbg.Runtime.pFileDMA);
110 }
111
112 return rc;
113}
114
115/**
116 * Destroys an HDA stream.
117 *
118 * @param pStream HDA stream to destroy.
119 */
120void hdaR3StreamDestroy(PHDASTREAM pStream)
121{
122 AssertPtrReturnVoid(pStream);
123
124 LogFlowFunc(("[SD%RU8]: Destroying ...\n", pStream->u8SD));
125
126 hdaR3StreamMapDestroy(&pStream->State.Mapping);
127
128 int rc2;
129
130#ifdef VBOX_WITH_AUDIO_HDA_ASYNC_IO
131 rc2 = hdaR3StreamAsyncIODestroy(pStream);
132 AssertRC(rc2);
133#endif
134
135 if (RTCritSectIsInitialized(&pStream->CritSect))
136 {
137 rc2 = RTCritSectDelete(&pStream->CritSect);
138 AssertRC(rc2);
139 }
140
141 if (pStream->State.pCircBuf)
142 {
143 RTCircBufDestroy(pStream->State.pCircBuf);
144 pStream->State.pCircBuf = NULL;
145 }
146
147 hdaR3StreamPeriodDestroy(&pStream->State.Period);
148
149#ifdef DEBUG
150 if (RTCritSectIsInitialized(&pStream->Dbg.CritSect))
151 {
152 rc2 = RTCritSectDelete(&pStream->Dbg.CritSect);
153 AssertRC(rc2);
154 }
155#endif
156
157 if (pStream->Dbg.Runtime.fEnabled)
158 {
159 DrvAudioHlpFileDestroy(pStream->Dbg.Runtime.pFileStream);
160 pStream->Dbg.Runtime.pFileStream = NULL;
161
162 DrvAudioHlpFileDestroy(pStream->Dbg.Runtime.pFileDMA);
163 pStream->Dbg.Runtime.pFileDMA = NULL;
164 }
165
166 LogFlowFuncLeave();
167}
168
169/**
170 * Initializes an HDA stream.
171 *
172 * @returns IPRT status code.
173 * @param pStream HDA stream to initialize.
174 * @param uSD SD (stream descriptor) number to assign the HDA stream to.
175 */
176int hdaR3StreamInit(PHDASTREAM pStream, uint8_t uSD)
177{
178 AssertPtrReturn(pStream, VERR_INVALID_POINTER);
179
180 PHDASTATE pThis = pStream->pHDAState;
181 AssertPtr(pThis);
182
183 pStream->u8SD = uSD;
184 pStream->u64BDLBase = RT_MAKE_U64(HDA_STREAM_REG(pThis, BDPL, pStream->u8SD),
185 HDA_STREAM_REG(pThis, BDPU, pStream->u8SD));
186 pStream->u16LVI = HDA_STREAM_REG(pThis, LVI, pStream->u8SD);
187 pStream->u32CBL = HDA_STREAM_REG(pThis, CBL, pStream->u8SD);
188 pStream->u16FIFOS = HDA_STREAM_REG(pThis, FIFOS, pStream->u8SD) + 1;
189
190 PPDMAUDIOSTREAMCFG pCfg = &pStream->State.Cfg;
191
192 int rc = hdaR3SDFMTToPCMProps(HDA_STREAM_REG(pThis, FMT, uSD), &pCfg->Props);
193 if (RT_FAILURE(rc))
194 {
195 LogRel(("HDA: Warning: Format 0x%x for stream #%RU8 not supported\n", HDA_STREAM_REG(pThis, FMT, uSD), uSD));
196 return rc;
197 }
198
199 /* Set scheduling hint (if available). */
200 if (pThis->u16TimerHz)
201 pCfg->Device.uSchedulingHintMs = 1000 /* ms */ / pThis->u16TimerHz;
202
203 /* (Re-)Allocate the stream's internal DMA buffer, based on the PCM properties we just got above. */
204 if (pStream->State.pCircBuf)
205 {
206 RTCircBufDestroy(pStream->State.pCircBuf);
207 pStream->State.pCircBuf = NULL;
208 }
209
210 /* By default we allocate an internal buffer of 100ms. */
211 rc = RTCircBufCreate(&pStream->State.pCircBuf, DrvAudioHlpMilliToBytes(100 /* ms */, &pCfg->Props)); /** @todo Make this configurable. */
212 AssertRCReturn(rc, rc);
213
214 /* Set the stream's direction. */
215 pCfg->enmDir = hdaGetDirFromSD(pStream->u8SD);
216
217 /* The the stream's name, based on the direction. */
218 switch (pCfg->enmDir)
219 {
220 case PDMAUDIODIR_IN:
221# ifdef VBOX_WITH_AUDIO_HDA_MIC_IN
222# error "Implement me!"
223# else
224 pCfg->DestSource.Source = PDMAUDIORECSOURCE_LINE;
225 pCfg->enmLayout = PDMAUDIOSTREAMLAYOUT_NON_INTERLEAVED;
226 RTStrCopy(pCfg->szName, sizeof(pCfg->szName), "Line In");
227# endif
228 break;
229
230 case PDMAUDIODIR_OUT:
231 /* Destination(s) will be set in hdaAddStreamOut(),
232 * based on the channels / stream layout. */
233 break;
234
235 default:
236 rc = VERR_NOT_SUPPORTED;
237 break;
238 }
239
240 if ( !pStream->u32CBL
241 || !pStream->u16LVI
242 || !pStream->u64BDLBase
243 || !pStream->u16FIFOS)
244 {
245 return VINF_SUCCESS;
246 }
247
248 /* Set the stream's frame size. */
249 pStream->State.cbFrameSize = pCfg->Props.cChannels * pCfg->Props.cBytes;
250 LogFunc(("[SD%RU8] cChannels=%RU8, cBytes=%RU8 -> cbFrameSize=%RU32\n",
251 pStream->u8SD, pCfg->Props.cChannels, pCfg->Props.cBytes, pStream->State.cbFrameSize));
252 Assert(pStream->State.cbFrameSize); /* Frame size must not be 0. */
253
254 /*
255 * Initialize the stream mapping in any case, regardless if
256 * we support surround audio or not. This is needed to handle
257 * the supported channels within a single audio stream, e.g. mono/stereo.
258 *
259 * In other words, the stream mapping *always* knows the real
260 * number of channels in a single audio stream.
261 */
262 rc = hdaR3StreamMapInit(&pStream->State.Mapping, &pCfg->Props);
263 AssertRCReturn(rc, rc);
264
265 LogFunc(("[SD%RU8] DMA @ 0x%x (%RU32 bytes), LVI=%RU16, FIFOS=%RU16, Hz=%RU32, rc=%Rrc\n",
266 pStream->u8SD, pStream->u64BDLBase, pStream->u32CBL, pStream->u16LVI, pStream->u16FIFOS,
267 pStream->State.Cfg.Props.uHz, rc));
268
269 /* Make sure that mandatory parameters are set up correctly. */
270 AssertStmt(pStream->u32CBL % pStream->State.cbFrameSize == 0, rc = VERR_INVALID_PARAMETER);
271 AssertStmt(pStream->u16LVI >= 1, rc = VERR_INVALID_PARAMETER);
272
273 if (RT_SUCCESS(rc))
274 {
275 /* Make sure that the chosen Hz rate dividable by the stream's rate. */
276 if (pStream->State.Cfg.Props.uHz % pThis->u16TimerHz != 0)
277 LogRel(("HDA: Device timer (%RU32) does not fit to stream #RU8 timing (%RU32)\n",
278 pThis->u16TimerHz, pStream->State.Cfg.Props.uHz));
279
280 /* Figure out how many transfer fragments we're going to use for this stream. */
281 /** @todo Use a more dynamic fragment size? */
282 Assert(pStream->u16LVI <= UINT8_MAX - 1);
283 uint8_t cFragments = pStream->u16LVI + 1;
284 if (cFragments <= 1)
285 cFragments = 2; /* At least two fragments (BDLEs) must be present. */
286
287 /*
288 * Handle the stream's position adjustment.
289 */
290 uint32_t cfPosAdjust = 0;
291
292 LogFunc(("[SD%RU8] fPosAdjustEnabled=%RTbool, cPosAdjustFrames=%RU16\n",
293 pStream->u8SD, pThis->fPosAdjustEnabled, pThis->cPosAdjustFrames));
294
295 if (pThis->fPosAdjustEnabled) /* Is the position adjustment enabled at all? */
296 {
297 HDABDLE BDLE;
298 RT_ZERO(BDLE);
299
300 int rc2 = hdaR3BDLEFetch(pThis, &BDLE, pStream->u64BDLBase, 0 /* Entry */);
301 AssertRC(rc2);
302
303 /* Note: Do *not* check if this BDLE aligns to the stream's frame size.
304 * It can happen that this isn't the case on some guests, e.g.
305 * on Windows with a 5.1 speaker setup.
306 *
307 * The only thing which counts is that the stream's CBL value
308 * properly aligns to the stream's frame size.
309 */
310
311 /* If no custom set position adjustment is set, apply some
312 * simple heuristics to detect the appropriate position adjustment. */
313 if ( !pThis->cPosAdjustFrames
314 /* Position adjustmenet buffer *must* have the IOC bit set! */
315 && hdaR3BDLENeedsInterrupt(&BDLE))
316 {
317 /** @todo Implement / use a (dynamic) table once this gets more complicated. */
318#ifdef VBOX_WITH_INTEL_HDA
319 /* Intel ICH / PCH: 1 frame. */
320 if (BDLE.Desc.u32BufSize == 1 * pStream->State.cbFrameSize)
321 {
322 cfPosAdjust = 1;
323 }
324 /* Intel Baytrail / Braswell: 32 frames. */
325 else if (BDLE.Desc.u32BufSize == 32 * pStream->State.cbFrameSize)
326 {
327 cfPosAdjust = 32;
328 }
329#endif
330 }
331 else /* Go with the set default. */
332 cfPosAdjust = pThis->cPosAdjustFrames;
333
334 if (cfPosAdjust)
335 {
336 /* Also adjust the number of fragments, as the position adjustment buffer
337 * does not count as an own fragment as such.
338 *
339 * This e.g. can happen on (newer) Ubuntu guests which use
340 * 4 (IOC) + 4408 (IOC) + 4408 (IOC) + 4408 (IOC) + 4404 (= 17632) bytes,
341 * where the first buffer (4) is used as position adjustment.
342 *
343 * Only skip a fragment if the whole buffer fragment is used for
344 * position adjustment.
345 */
346 if ( (cfPosAdjust * pStream->State.cbFrameSize) == BDLE.Desc.u32BufSize
347 && cFragments)
348 {
349 cFragments--;
350 }
351
352 /* Initialize position adjustment counter. */
353 pStream->State.cPosAdjustFramesLeft = cfPosAdjust;
354 LogRel2(("HDA: Position adjustment for stream #%RU8 active (%RU32 frames)\n", pStream->u8SD, cfPosAdjust));
355 }
356 }
357
358 LogFunc(("[SD%RU8] cfPosAdjust=%RU32, cFragments=%RU8\n", pStream->u8SD, cfPosAdjust, cFragments));
359
360 /*
361 * Set up data transfer transfer stuff.
362 */
363
364 /* Calculate the fragment size the guest OS expects interrupt delivery at. */
365 pStream->State.cbTransferSize = pStream->u32CBL / cFragments;
366 Assert(pStream->State.cbTransferSize);
367 Assert(pStream->State.cbTransferSize % pStream->State.cbFrameSize == 0);
368
369 /* Calculate the bytes we need to transfer to / from the stream's DMA per iteration.
370 * This is bound to the device's Hz rate and thus to the (virtual) timing the device expects. */
371 pStream->State.cbTransferChunk = (pStream->State.Cfg.Props.uHz / pThis->u16TimerHz) * pStream->State.cbFrameSize;
372 Assert(pStream->State.cbTransferChunk);
373 Assert(pStream->State.cbTransferChunk % pStream->State.cbFrameSize == 0);
374
375 /* Make sure that the transfer chunk does not exceed the overall transfer size. */
376 if (pStream->State.cbTransferChunk > pStream->State.cbTransferSize)
377 pStream->State.cbTransferChunk = pStream->State.cbTransferSize;
378
379 pStream->State.cbTransferProcessed = 0;
380 pStream->State.cTransferPendingInterrupts = 0;
381 pStream->State.cbDMALeft = 0;
382 pStream->State.tsLastUpdateNs = 0;
383
384 const uint64_t cTicksPerHz = TMTimerGetFreq(pStream->pTimer) / pThis->u16TimerHz;
385
386 /* Calculate the timer ticks per byte for this stream. */
387 pStream->State.cTicksPerByte = cTicksPerHz / pStream->State.cbTransferChunk;
388 Assert(pStream->State.cTicksPerByte);
389
390 /* Calculate timer ticks per transfer. */
391 pStream->State.cTransferTicks = pStream->State.cbTransferChunk * pStream->State.cTicksPerByte;
392 Assert(pStream->State.cTransferTicks);
393
394 /* Initialize the transfer timestamps. */
395 pStream->State.tsTransferLast = 0;
396 pStream->State.tsTransferNext = 0;
397
398 LogFunc(("[SD%RU8] Timer %uHz (%RU64 ticks per Hz), cTicksPerByte=%RU64, cbTransferChunk=%RU32, cTransferTicks=%RU64, " \
399 "cbTransferSize=%RU32\n",
400 pStream->u8SD, pThis->u16TimerHz, cTicksPerHz, pStream->State.cTicksPerByte,
401 pStream->State.cbTransferChunk, pStream->State.cTransferTicks, pStream->State.cbTransferSize));
402
403 /* Make sure to also update the stream's DMA counter (based on its current LPIB value). */
404 hdaR3StreamSetPosition(pStream, HDA_STREAM_REG(pThis, LPIB, pStream->u8SD));
405
406#ifdef LOG_ENABLED
407 hdaR3BDLEDumpAll(pThis, pStream->u64BDLBase, pStream->u16LVI + 1);
408#endif
409 }
410
411 if (RT_FAILURE(rc))
412 LogRel(("HDA: Initializing stream #%RU8 failed with %Rrc\n", pStream->u8SD, rc));
413
414 return rc;
415}
416
417/**
418 * Resets an HDA stream.
419 *
420 * @param pThis HDA state.
421 * @param pStream HDA stream to reset.
422 * @param uSD Stream descriptor (SD) number to use for this stream.
423 */
424void hdaR3StreamReset(PHDASTATE pThis, PHDASTREAM pStream, uint8_t uSD)
425{
426 AssertPtrReturnVoid(pThis);
427 AssertPtrReturnVoid(pStream);
428 AssertReturnVoid(uSD < HDA_MAX_STREAMS);
429
430# ifdef VBOX_STRICT
431 AssertReleaseMsg(!pStream->State.fRunning, ("[SD%RU8] Cannot reset stream while in running state\n", uSD));
432# endif
433
434 LogFunc(("[SD%RU8]: Reset\n", uSD));
435
436 /*
437 * Set reset state.
438 */
439 Assert(ASMAtomicReadBool(&pStream->State.fInReset) == false); /* No nested calls. */
440 ASMAtomicXchgBool(&pStream->State.fInReset, true);
441
442 /*
443 * Second, initialize the registers.
444 */
445 HDA_STREAM_REG(pThis, STS, uSD) = HDA_SDSTS_FIFORDY;
446 /* According to the ICH6 datasheet, 0x40000 is the default value for stream descriptor register 23:20
447 * bits are reserved for stream number 18.2.33, resets SDnCTL except SRST bit. */
448 HDA_STREAM_REG(pThis, CTL, uSD) = 0x40000 | (HDA_STREAM_REG(pThis, CTL, uSD) & HDA_SDCTL_SRST);
449 /* ICH6 defines default values (120 bytes for input and 192 bytes for output descriptors) of FIFO size. 18.2.39. */
450 HDA_STREAM_REG(pThis, FIFOS, uSD) = hdaGetDirFromSD(uSD) == PDMAUDIODIR_IN ? HDA_SDIFIFO_120B : HDA_SDOFIFO_192B;
451 /* See 18.2.38: Always defaults to 0x4 (32 bytes). */
452 HDA_STREAM_REG(pThis, FIFOW, uSD) = HDA_SDFIFOW_32B;
453 HDA_STREAM_REG(pThis, LPIB, uSD) = 0;
454 HDA_STREAM_REG(pThis, CBL, uSD) = 0;
455 HDA_STREAM_REG(pThis, LVI, uSD) = 0;
456 HDA_STREAM_REG(pThis, FMT, uSD) = 0;
457 HDA_STREAM_REG(pThis, BDPU, uSD) = 0;
458 HDA_STREAM_REG(pThis, BDPL, uSD) = 0;
459
460#ifdef HDA_USE_DMA_ACCESS_HANDLER
461 hdaR3StreamUnregisterDMAHandlers(pThis, pStream);
462#endif
463
464 /* Assign the default mixer sink to the stream. */
465 pStream->pMixSink = hdaR3GetDefaultSink(pThis, uSD);
466
467 pStream->State.tsTransferLast = 0;
468 pStream->State.tsTransferNext = 0;
469
470 RT_ZERO(pStream->State.BDLE);
471 pStream->State.uCurBDLE = 0;
472
473 if (pStream->State.pCircBuf)
474 RTCircBufReset(pStream->State.pCircBuf);
475
476 /* Reset stream map. */
477 hdaR3StreamMapReset(&pStream->State.Mapping);
478
479 /* (Re-)initialize the stream with current values. */
480 int rc2 = hdaR3StreamInit(pStream, uSD);
481 AssertRC(rc2);
482
483 /* Reset the stream's period. */
484 hdaR3StreamPeriodReset(&pStream->State.Period);
485
486#ifdef DEBUG
487 pStream->Dbg.cReadsTotal = 0;
488 pStream->Dbg.cbReadTotal = 0;
489 pStream->Dbg.tsLastReadNs = 0;
490 pStream->Dbg.cWritesTotal = 0;
491 pStream->Dbg.cbWrittenTotal = 0;
492 pStream->Dbg.cWritesHz = 0;
493 pStream->Dbg.cbWrittenHz = 0;
494 pStream->Dbg.tsWriteSlotBegin = 0;
495#endif
496
497 /* Report that we're done resetting this stream. */
498 HDA_STREAM_REG(pThis, CTL, uSD) = 0;
499
500 LogFunc(("[SD%RU8] Reset\n", uSD));
501
502 /* Exit reset mode. */
503 ASMAtomicXchgBool(&pStream->State.fInReset, false);
504}
505
506/**
507 * Enables or disables an HDA audio stream.
508 *
509 * @returns IPRT status code.
510 * @param pStream HDA stream to enable or disable.
511 * @param fEnable Whether to enable or disble the stream.
512 */
513int hdaR3StreamEnable(PHDASTREAM pStream, bool fEnable)
514{
515 AssertPtrReturn(pStream, VERR_INVALID_POINTER);
516
517 LogFunc(("[SD%RU8]: fEnable=%RTbool, pMixSink=%p\n", pStream->u8SD, fEnable, pStream->pMixSink));
518
519 int rc = VINF_SUCCESS;
520
521 AUDMIXSINKCMD enmCmd = fEnable
522 ? AUDMIXSINKCMD_ENABLE : AUDMIXSINKCMD_DISABLE;
523
524 /* First, enable or disable the stream and the stream's sink, if any. */
525 if ( pStream->pMixSink
526 && pStream->pMixSink->pMixSink)
527 rc = AudioMixerSinkCtl(pStream->pMixSink->pMixSink, enmCmd);
528
529 if ( RT_SUCCESS(rc)
530 && fEnable
531 && pStream->Dbg.Runtime.fEnabled)
532 {
533 Assert(DrvAudioHlpPCMPropsAreValid(&pStream->State.Cfg.Props));
534
535 if (fEnable)
536 {
537 if (!DrvAudioHlpFileIsOpen(pStream->Dbg.Runtime.pFileStream))
538 {
539 int rc2 = DrvAudioHlpFileOpen(pStream->Dbg.Runtime.pFileStream, PDMAUDIOFILE_DEFAULT_OPEN_FLAGS,
540 &pStream->State.Cfg.Props);
541 AssertRC(rc2);
542 }
543
544 if (!DrvAudioHlpFileIsOpen(pStream->Dbg.Runtime.pFileDMA))
545 {
546 int rc2 = DrvAudioHlpFileOpen(pStream->Dbg.Runtime.pFileDMA, PDMAUDIOFILE_DEFAULT_OPEN_FLAGS,
547 &pStream->State.Cfg.Props);
548 AssertRC(rc2);
549 }
550 }
551 }
552
553 if (RT_SUCCESS(rc))
554 {
555 pStream->State.fRunning = fEnable;
556 }
557
558 LogFunc(("[SD%RU8] rc=%Rrc\n", pStream->u8SD, rc));
559 return rc;
560}
561
562uint32_t hdaR3StreamGetPosition(PHDASTATE pThis, PHDASTREAM pStream)
563{
564 return HDA_STREAM_REG(pThis, LPIB, pStream->u8SD);
565}
566
567/**
568 * Updates an HDA stream's current read or write buffer position (depending on the stream type) by
569 * updating its associated LPIB register and DMA position buffer (if enabled).
570 *
571 * @param pStream HDA stream to update read / write position for.
572 * @param u32LPIB Absolute position (in bytes) to set current read / write position to.
573 */
574void hdaR3StreamSetPosition(PHDASTREAM pStream, uint32_t u32LPIB)
575{
576 AssertPtrReturnVoid(pStream);
577
578 Log3Func(("[SD%RU8] LPIB=%RU32 (DMA Position Buffer Enabled: %RTbool)\n",
579 pStream->u8SD, u32LPIB, pStream->pHDAState->fDMAPosition));
580
581 /* Update LPIB in any case. */
582 HDA_STREAM_REG(pStream->pHDAState, LPIB, pStream->u8SD) = u32LPIB;
583
584 /* Do we need to tell the current DMA position? */
585 if (pStream->pHDAState->fDMAPosition)
586 {
587 int rc2 = PDMDevHlpPCIPhysWrite(pStream->pHDAState->CTX_SUFF(pDevIns),
588 pStream->pHDAState->u64DPBase + (pStream->u8SD * 2 * sizeof(uint32_t)),
589 (void *)&u32LPIB, sizeof(uint32_t));
590 AssertRC(rc2);
591 }
592}
593
594/**
595 * Retrieves the available size of (buffered) audio data (in bytes) of a given HDA stream.
596 *
597 * @returns Available data (in bytes).
598 * @param pStream HDA stream to retrieve size for.
599 */
600uint32_t hdaR3StreamGetUsed(PHDASTREAM pStream)
601{
602 AssertPtrReturn(pStream, 0);
603
604 if (!pStream->State.pCircBuf)
605 return 0;
606
607 return (uint32_t)RTCircBufUsed(pStream->State.pCircBuf);
608}
609
610/**
611 * Retrieves the free size of audio data (in bytes) of a given HDA stream.
612 *
613 * @returns Free data (in bytes).
614 * @param pStream HDA stream to retrieve size for.
615 */
616uint32_t hdaR3StreamGetFree(PHDASTREAM pStream)
617{
618 AssertPtrReturn(pStream, 0);
619
620 if (!pStream->State.pCircBuf)
621 return 0;
622
623 return (uint32_t)RTCircBufFree(pStream->State.pCircBuf);
624}
625
626/**
627 * Returns whether a next transfer for a given stream is scheduled or not.
628 * This takes pending stream interrupts into account as well as the next scheduled
629 * transfer timestamp.
630 *
631 * @returns True if a next transfer is scheduled, false if not.
632 * @param pStream HDA stream to retrieve schedule status for.
633 */
634bool hdaR3StreamTransferIsScheduled(PHDASTREAM pStream)
635{
636 if (pStream)
637 {
638 AssertPtrReturn(pStream->pHDAState, false);
639
640 if (pStream->State.fRunning)
641 {
642 if (pStream->State.cTransferPendingInterrupts)
643 {
644 Log3Func(("[SD%RU8] Scheduled (%RU8 IRQs pending)\n", pStream->u8SD, pStream->State.cTransferPendingInterrupts));
645 return true;
646 }
647
648 const uint64_t tsNow = TMTimerGet(pStream->pTimer);
649 if (pStream->State.tsTransferNext > tsNow)
650 {
651 Log3Func(("[SD%RU8] Scheduled in %RU64\n", pStream->u8SD, pStream->State.tsTransferNext - tsNow));
652 return true;
653 }
654 }
655 }
656 return false;
657}
658
659/**
660 * Returns the (virtual) clock timestamp of the next transfer, if any.
661 * Will return 0 if no new transfer is scheduled.
662 *
663 * @returns The (virtual) clock timestamp of the next transfer.
664 * @param pStream HDA stream to retrieve timestamp for.
665 */
666uint64_t hdaR3StreamTransferGetNext(PHDASTREAM pStream)
667{
668 return pStream->State.tsTransferNext;
669}
670
671/**
672 * Writes audio data from a mixer sink into an HDA stream's DMA buffer.
673 *
674 * @returns IPRT status code.
675 * @param pStream HDA stream to write to.
676 * @param pvBuf Data buffer to write.
677 * If NULL, silence will be written.
678 * @param cbBuf Number of bytes of data buffer to write.
679 * @param pcbWritten Number of bytes written. Optional.
680 */
681int hdaR3StreamWrite(PHDASTREAM pStream, const void *pvBuf, uint32_t cbBuf, uint32_t *pcbWritten)
682{
683 AssertPtrReturn(pStream, VERR_INVALID_POINTER);
684 /* pvBuf is optional. */
685 AssertReturn(cbBuf, VERR_INVALID_PARAMETER);
686 /* pcbWritten is optional. */
687
688 PRTCIRCBUF pCircBuf = pStream->State.pCircBuf;
689 AssertPtr(pCircBuf);
690
691 int rc = VINF_SUCCESS;
692
693 uint32_t cbWrittenTotal = 0;
694 uint32_t cbLeft = RT_MIN(cbBuf, (uint32_t)RTCircBufFree(pCircBuf));
695
696 while (cbLeft)
697 {
698 void *pvDst;
699 size_t cbDst;
700
701 RTCircBufAcquireWriteBlock(pCircBuf, cbLeft, &pvDst, &cbDst);
702
703 if (cbDst)
704 {
705 if (pvBuf)
706 {
707 memcpy(pvDst, (uint8_t *)pvBuf + cbWrittenTotal, cbDst);
708 }
709 else /* Send silence. */
710 {
711 /** @todo Use a sample spec for "silence" based on the PCM parameters.
712 * For now we ASSUME that silence equals NULLing the data. */
713 RT_BZERO(pvDst, cbDst);
714 }
715
716 if (pStream->Dbg.Runtime.fEnabled)
717 DrvAudioHlpFileWrite(pStream->Dbg.Runtime.pFileStream, pvDst, cbDst, 0 /* fFlags */);
718 }
719
720 RTCircBufReleaseWriteBlock(pCircBuf, cbDst);
721
722 if (RT_FAILURE(rc))
723 break;
724
725 Assert(cbLeft >= (uint32_t)cbDst);
726 cbLeft -= (uint32_t)cbDst;
727
728 cbWrittenTotal += (uint32_t)cbDst;
729 }
730
731 Log3Func(("cbWrittenTotal=%RU32\n", cbWrittenTotal));
732
733 if (pcbWritten)
734 *pcbWritten = cbWrittenTotal;
735
736 return rc;
737}
738
739
740/**
741 * Reads audio data from an HDA stream's DMA buffer and writes into a specified mixer sink.
742 *
743 * @returns IPRT status code.
744 * @param pStream HDA stream to read audio data from.
745 * @param cbToRead Number of bytes to read.
746 * @param pcbRead Number of bytes read. Optional.
747 */
748int hdaR3StreamRead(PHDASTREAM pStream, uint32_t cbToRead, uint32_t *pcbRead)
749{
750 AssertPtrReturn(pStream, VERR_INVALID_POINTER);
751 AssertReturn(cbToRead, VERR_INVALID_PARAMETER);
752 /* pcbWritten is optional. */
753
754 PHDAMIXERSINK pSink = pStream->pMixSink;
755 if (!pSink)
756 {
757 AssertMsgFailed(("[SD%RU8]: Can't read from a stream with no sink attached\n", pStream->u8SD));
758
759 if (pcbRead)
760 *pcbRead = 0;
761 return VINF_SUCCESS;
762 }
763
764 PRTCIRCBUF pCircBuf = pStream->State.pCircBuf;
765 AssertPtr(pCircBuf);
766
767 int rc = VINF_SUCCESS;
768
769 uint32_t cbReadTotal = 0;
770 uint32_t cbLeft = RT_MIN(cbToRead, (uint32_t)RTCircBufUsed(pCircBuf));
771
772 while (cbLeft)
773 {
774 void *pvSrc;
775 size_t cbSrc;
776
777 uint32_t cbWritten = 0;
778
779 RTCircBufAcquireReadBlock(pCircBuf, cbLeft, &pvSrc, &cbSrc);
780
781 if (cbSrc)
782 {
783 if (pStream->Dbg.Runtime.fEnabled)
784 DrvAudioHlpFileWrite(pStream->Dbg.Runtime.pFileStream, pvSrc, cbSrc, 0 /* fFlags */);
785
786 rc = AudioMixerSinkWrite(pSink->pMixSink, AUDMIXOP_COPY, pvSrc, (uint32_t)cbSrc, &cbWritten);
787 AssertRC(rc);
788
789 Assert(cbSrc >= cbWritten);
790 Log2Func(("[SD%RU8]: %RU32/%zu bytes read\n", pStream->u8SD, cbWritten, cbSrc));
791 }
792
793 RTCircBufReleaseReadBlock(pCircBuf, cbWritten);
794
795 if (RT_FAILURE(rc))
796 break;
797
798 Assert(cbLeft >= cbWritten);
799 cbLeft -= cbWritten;
800
801 cbReadTotal += cbWritten;
802 }
803
804 if (pcbRead)
805 *pcbRead = cbReadTotal;
806
807 return rc;
808}
809
810/**
811 * Transfers data of an HDA stream according to its usage (input / output).
812 *
813 * For an SDO (output) stream this means reading DMA data from the device to
814 * the HDA stream's internal FIFO buffer.
815 *
816 * For an SDI (input) stream this is reading audio data from the HDA stream's
817 * internal FIFO buffer and writing it as DMA data to the device.
818 *
819 * @returns IPRT status code.
820 * @param pStream HDA stream to update.
821 * @param cbToProcessMax How much data (in bytes) to process as maximum.
822 */
823int hdaR3StreamTransfer(PHDASTREAM pStream, uint32_t cbToProcessMax)
824{
825 AssertPtrReturn(pStream, VERR_INVALID_POINTER);
826
827 hdaR3StreamLock(pStream);
828
829 PHDASTATE pThis = pStream->pHDAState;
830 AssertPtr(pThis);
831
832 PHDASTREAMPERIOD pPeriod = &pStream->State.Period;
833 if (!hdaR3StreamPeriodLock(pPeriod))
834 return VERR_ACCESS_DENIED;
835
836 bool fProceed = true;
837
838 /* Stream not running? */
839 if (!pStream->State.fRunning)
840 {
841 Log3Func(("[SD%RU8] Not running\n", pStream->u8SD));
842 fProceed = false;
843 }
844 else if (HDA_STREAM_REG(pThis, STS, pStream->u8SD) & HDA_SDSTS_BCIS)
845 {
846 Log3Func(("[SD%RU8] BCIS bit set\n", pStream->u8SD));
847 fProceed = false;
848 }
849
850 if (!fProceed)
851 {
852 hdaR3StreamPeriodUnlock(pPeriod);
853 hdaR3StreamUnlock(pStream);
854 return VINF_SUCCESS;
855 }
856
857 const uint64_t tsNow = TMTimerGet(pStream->pTimer);
858
859 if (!pStream->State.tsTransferLast)
860 pStream->State.tsTransferLast = tsNow;
861
862#ifdef DEBUG
863 const int64_t iTimerDelta = tsNow - pStream->State.tsTransferLast;
864 Log3Func(("[SD%RU8] Time now=%RU64, last=%RU64 -> %RI64 ticks delta\n",
865 pStream->u8SD, tsNow, pStream->State.tsTransferLast, iTimerDelta));
866#endif
867
868 pStream->State.tsTransferLast = tsNow;
869
870 /* Sanity checks. */
871 Assert(pStream->u8SD < HDA_MAX_STREAMS);
872 Assert(pStream->u64BDLBase);
873 Assert(pStream->u32CBL);
874 Assert(pStream->u16FIFOS);
875
876 /* State sanity checks. */
877 Assert(ASMAtomicReadBool(&pStream->State.fInReset) == false);
878
879 int rc = VINF_SUCCESS;
880
881 /* Fetch first / next BDL entry. */
882 PHDABDLE pBDLE = &pStream->State.BDLE;
883 if (hdaR3BDLEIsComplete(pBDLE))
884 {
885 rc = hdaR3BDLEFetch(pThis, pBDLE, pStream->u64BDLBase, pStream->State.uCurBDLE);
886 AssertRC(rc);
887 }
888
889 uint32_t cbToProcess = RT_MIN(pStream->State.cbTransferSize - pStream->State.cbTransferProcessed,
890 pStream->State.cbTransferChunk);
891
892 Log3Func(("[SD%RU8] cbToProcess=%RU32, cbToProcessMax=%RU32\n", pStream->u8SD, cbToProcess, cbToProcessMax));
893
894 if (cbToProcess > cbToProcessMax)
895 {
896 LogFunc(("[SD%RU8] Limiting transfer (cbToProcess=%RU32, cbToProcessMax=%RU32)\n",
897 pStream->u8SD, cbToProcess, cbToProcessMax));
898
899 /* Never process more than a stream currently can handle. */
900 cbToProcess = cbToProcessMax;
901 }
902
903 uint32_t cbProcessed = 0;
904 uint32_t cbLeft = cbToProcess;
905
906 uint8_t abChunk[HDA_FIFO_MAX + 1];
907 while (cbLeft)
908 {
909 /* Limit the chunk to the stream's FIFO size and what's left to process. */
910 uint32_t cbChunk = RT_MIN(cbLeft, pStream->u16FIFOS);
911
912 /* Limit the chunk to the remaining data of the current BDLE. */
913 cbChunk = RT_MIN(cbChunk, pBDLE->Desc.u32BufSize - pBDLE->State.u32BufOff);
914
915 /* If there are position adjustment frames left to be processed,
916 * make sure that we process them first as a whole. */
917 if (pStream->State.cPosAdjustFramesLeft)
918 cbChunk = RT_MIN(cbChunk, uint32_t(pStream->State.cPosAdjustFramesLeft * pStream->State.cbFrameSize));
919
920 Log3Func(("[SD%RU8] cbChunk=%RU32, cPosAdjustFramesLeft=%RU16\n",
921 pStream->u8SD, cbChunk, pStream->State.cPosAdjustFramesLeft));
922
923 if (!cbChunk)
924 break;
925
926 uint32_t cbDMA = 0;
927 PRTCIRCBUF pCircBuf = pStream->State.pCircBuf;
928
929 if (hdaGetDirFromSD(pStream->u8SD) == PDMAUDIODIR_IN) /* Input (SDI). */
930 {
931 STAM_PROFILE_START(&pThis->StatIn, a);
932
933 uint32_t cbDMAWritten = 0;
934 uint32_t cbDMAToWrite = cbChunk;
935
936 /** @todo Do we need interleaving streams support here as well?
937 * Never saw anything else besides mono/stereo mics (yet). */
938 while (cbDMAToWrite)
939 {
940 void *pvBuf; size_t cbBuf;
941 RTCircBufAcquireReadBlock(pCircBuf, cbDMAToWrite, &pvBuf, &cbBuf);
942
943 if ( !cbBuf
944 && !RTCircBufUsed(pCircBuf))
945 break;
946
947 memcpy(abChunk + cbDMAWritten, pvBuf, cbBuf);
948
949 RTCircBufReleaseReadBlock(pCircBuf, cbBuf);
950
951 Assert(cbDMAToWrite >= cbBuf);
952 cbDMAToWrite -= (uint32_t)cbBuf;
953 cbDMAWritten += (uint32_t)cbBuf;
954 Assert(cbDMAWritten <= cbChunk);
955 }
956
957 if (cbDMAToWrite)
958 {
959 LogRel2(("HDA: FIFO underflow for stream #%RU8 (%RU32 bytes outstanding)\n", pStream->u8SD, cbDMAToWrite));
960
961 Assert(cbChunk == cbDMAWritten + cbDMAToWrite);
962 memset((uint8_t *)abChunk + cbDMAWritten, 0, cbDMAToWrite);
963 cbDMAWritten = cbChunk;
964 }
965
966 rc = hdaR3DMAWrite(pThis, pStream, abChunk, cbDMAWritten, &cbDMA /* pcbWritten */);
967 if (RT_FAILURE(rc))
968 LogRel(("HDA: Writing to stream #%RU8 DMA failed with %Rrc\n", pStream->u8SD, rc));
969
970 STAM_PROFILE_STOP(&pThis->StatIn, a);
971 }
972 else if (hdaGetDirFromSD(pStream->u8SD) == PDMAUDIODIR_OUT) /* Output (SDO). */
973 {
974 STAM_PROFILE_START(&pThis->StatOut, a);
975
976 rc = hdaR3DMARead(pThis, pStream, abChunk, cbChunk, &cbDMA /* pcbRead */);
977 if (RT_SUCCESS(rc))
978 {
979 const uint32_t cbDMAFree = (uint32_t)RTCircBufFree(pCircBuf);
980 Assert(cbDMAFree >= cbDMA); /* This must always hold. */
981
982#ifndef VBOX_WITH_HDA_AUDIO_INTERLEAVING_STREAMS_SUPPORT
983 /*
984 * Most guests don't use different stream frame sizes than
985 * the default one, so save a bit of CPU time and don't go into
986 * the frame extraction code below.
987 *
988 * Only macOS guests need the frame extraction branch below at the moment AFAIK.
989 */
990 if (pStream->State.cbFrameSize == HDA_FRAME_SIZE)
991 {
992 uint32_t cbDMARead = 0;
993 uint32_t cbDMALeft = RT_MIN(cbDMA, cbDMAFree);
994
995 while (cbDMALeft)
996 {
997 void *pvBuf; size_t cbBuf;
998 RTCircBufAcquireWriteBlock(pCircBuf, cbDMALeft, &pvBuf, &cbBuf);
999
1000 if (cbBuf)
1001 {
1002 memcpy(pvBuf, abChunk + cbDMARead, cbBuf);
1003 cbDMARead += (uint32_t)cbBuf;
1004 cbDMALeft -= (uint32_t)cbBuf;
1005 }
1006
1007 RTCircBufReleaseWriteBlock(pCircBuf, cbBuf);
1008 }
1009 }
1010 else
1011 {
1012 /*
1013 * The following code extracts the required audio stream (channel) data
1014 * of non-interleaved *and* interleaved audio streams.
1015 *
1016 * We by default only support 2 channels with 16-bit samples (HDA_FRAME_SIZE),
1017 * but an HDA audio stream can have interleaved audio data of multiple audio
1018 * channels in such a single stream ("AA,AA,AA vs. AA,BB,AA,BB").
1019 *
1020 * So take this into account by just handling the first channel in such a stream ("A")
1021 * and just discard the other channel's data.
1022 *
1023 */
1024 /** @todo Optimize this stuff -- copying only one frame a time is expensive. */
1025 uint32_t cbDMARead = pStream->State.cbDMALeft ? pStream->State.cbFrameSize - pStream->State.cbDMALeft : 0;
1026 uint32_t cbDMALeft = RT_MIN(cbDMA, cbDMAFree);
1027
1028 while (cbDMALeft >= pStream->State.cbFrameSize)
1029 {
1030 void *pvBuf; size_t cbBuf;
1031 RTCircBufAcquireWriteBlock(pCircBuf, HDA_FRAME_SIZE, &pvBuf, &cbBuf);
1032
1033 AssertBreak(cbDMARead <= sizeof(abChunk));
1034
1035 if (cbBuf)
1036 memcpy(pvBuf, abChunk + cbDMARead, cbBuf);
1037
1038 RTCircBufReleaseWriteBlock(pCircBuf, cbBuf);
1039
1040 Assert(cbDMALeft >= pStream->State.cbFrameSize);
1041 cbDMALeft -= pStream->State.cbFrameSize;
1042 cbDMARead += pStream->State.cbFrameSize;
1043 }
1044
1045 pStream->State.cbDMALeft = cbDMALeft;
1046 Assert(pStream->State.cbDMALeft < pStream->State.cbFrameSize);
1047 }
1048#else
1049 /** @todo This needs making use of HDAStreamMap + HDAStreamChannel. */
1050# error "Implement reading interleaving streams support here."
1051#endif
1052 }
1053 else
1054 LogRel(("HDA: Reading from stream #%RU8 DMA failed with %Rrc\n", pStream->u8SD, rc));
1055
1056 STAM_PROFILE_STOP(&pThis->StatOut, a);
1057 }
1058
1059 else /** @todo Handle duplex streams? */
1060 AssertFailed();
1061
1062 if (cbDMA)
1063 {
1064 /* We always increment the position of DMA buffer counter because we're always reading
1065 * into an intermediate DMA buffer. */
1066 pBDLE->State.u32BufOff += (uint32_t)cbDMA;
1067 Assert(pBDLE->State.u32BufOff <= pBDLE->Desc.u32BufSize);
1068
1069 /* Are we done doing the position adjustment?
1070 * Only then do the transfer accounting .*/
1071 if (pStream->State.cPosAdjustFramesLeft == 0)
1072 {
1073 Assert(cbLeft >= cbDMA);
1074 cbLeft -= cbDMA;
1075
1076 cbProcessed += cbDMA;
1077 }
1078
1079 /*
1080 * Update the stream's current position.
1081 * Do this as accurate and close to the actual data transfer as possible.
1082 * All guetsts rely on this, depending on the mechanism they use (LPIB register or DMA counters).
1083 */
1084 uint32_t cbStreamPos = hdaR3StreamGetPosition(pThis, pStream);
1085 if (cbStreamPos == pStream->u32CBL)
1086 cbStreamPos = 0;
1087
1088 hdaR3StreamSetPosition(pStream, cbStreamPos + cbDMA);
1089 }
1090
1091 if (hdaR3BDLEIsComplete(pBDLE))
1092 {
1093 Log3Func(("[SD%RU8] Complete: %R[bdle]\n", pStream->u8SD, pBDLE));
1094
1095 /* Does the current BDLE require an interrupt to be sent? */
1096 if ( hdaR3BDLENeedsInterrupt(pBDLE)
1097 /* Are we done doing the position adjustment?
1098 * It can happen that a BDLE which is handled while doing the
1099 * position adjustment requires an interrupt on completion (IOC) being set.
1100 *
1101 * In such a case we need to skip such an interrupt and just move on. */
1102 && pStream->State.cPosAdjustFramesLeft == 0)
1103 {
1104 /* If the IOCE ("Interrupt On Completion Enable") bit of the SDCTL register is set
1105 * we need to generate an interrupt.
1106 */
1107 if (HDA_STREAM_REG(pThis, CTL, pStream->u8SD) & HDA_SDCTL_IOCE)
1108 {
1109 pStream->State.cTransferPendingInterrupts++;
1110
1111 AssertMsg(pStream->State.cTransferPendingInterrupts <= 32,
1112 ("Too many pending interrupts (%RU8) for stream #%RU8\n",
1113 pStream->State.cTransferPendingInterrupts, pStream->u8SD));
1114 }
1115 }
1116
1117 if (pStream->State.uCurBDLE == pStream->u16LVI)
1118 {
1119 pStream->State.uCurBDLE = 0;
1120 }
1121 else
1122 pStream->State.uCurBDLE++;
1123
1124 /* Fetch the next BDLE entry. */
1125 hdaR3BDLEFetch(pThis, pBDLE, pStream->u64BDLBase, pStream->State.uCurBDLE);
1126 }
1127
1128 /* Do the position adjustment accounting. */
1129 pStream->State.cPosAdjustFramesLeft -= RT_MIN(pStream->State.cPosAdjustFramesLeft, cbDMA / pStream->State.cbFrameSize);
1130
1131 if (RT_FAILURE(rc))
1132 break;
1133 }
1134
1135 Log3Func(("[SD%RU8] cbToProcess=%RU32, cbProcessed=%RU32, cbLeft=%RU32, %R[bdle], rc=%Rrc\n",
1136 pStream->u8SD, cbToProcess, cbProcessed, cbLeft, pBDLE, rc));
1137
1138 /* Sanity. */
1139 Assert(cbProcessed == cbToProcess);
1140 Assert(cbLeft == 0);
1141
1142 /* Only do the data accounting if we don't have to do any position
1143 * adjustment anymore. */
1144 if (pStream->State.cPosAdjustFramesLeft == 0)
1145 {
1146 hdaR3StreamPeriodInc(pPeriod, RT_MIN(cbProcessed / pStream->State.cbFrameSize,
1147 hdaR3StreamPeriodGetRemainingFrames(pPeriod)));
1148
1149 pStream->State.cbTransferProcessed += cbProcessed;
1150 }
1151
1152 /* Make sure that we never report more stuff processed than initially announced. */
1153 if (pStream->State.cbTransferProcessed > pStream->State.cbTransferSize)
1154 pStream->State.cbTransferProcessed = pStream->State.cbTransferSize;
1155
1156 uint32_t cbTransferLeft = pStream->State.cbTransferSize - pStream->State.cbTransferProcessed;
1157 bool fTransferComplete = !cbTransferLeft;
1158 uint64_t tsTransferNext = 0;
1159
1160 if (fTransferComplete)
1161 {
1162 /*
1163 * Try updating the wall clock.
1164 *
1165 * Note 1) Only certain guests (like Linux' snd_hda_intel) rely on the WALCLK register
1166 * in order to determine the correct timing of the sound device. Other guests
1167 * like Windows 7 + 10 (or even more exotic ones like Haiku) will completely
1168 * ignore this.
1169 *
1170 * Note 2) When updating the WALCLK register too often / early (or even in a non-monotonic
1171 * fashion) this *will* upset guest device drivers and will completely fuck up the
1172 * sound output. Running VLC on the guest will tell!
1173 */
1174 const bool fWalClkSet = hdaR3WalClkSet(pThis,
1175 hdaWalClkGetCurrent(pThis)
1176 + hdaR3StreamPeriodFramesToWalClk(pPeriod,
1177 pStream->State.cbTransferProcessed
1178 / pStream->State.cbFrameSize),
1179 false /* fForce */);
1180 RT_NOREF(fWalClkSet);
1181 }
1182
1183 /* Does the period have any interrupts outstanding? */
1184 if (pStream->State.cTransferPendingInterrupts)
1185 {
1186 Log3Func(("[SD%RU8] Scheduling interrupt\n", pStream->u8SD));
1187
1188 /*
1189 * Set the stream's BCIS bit.
1190 *
1191 * Note: This only must be done if the whole period is complete, and not if only
1192 * one specific BDL entry is complete (if it has the IOC bit set).
1193 *
1194 * This will otherwise confuses the guest when it 1) deasserts the interrupt,
1195 * 2) reads SDSTS (with BCIS set) and then 3) too early reads a (wrong) WALCLK value.
1196 *
1197 * snd_hda_intel on Linux will tell.
1198 */
1199 HDA_STREAM_REG(pThis, STS, pStream->u8SD) |= HDA_SDSTS_BCIS;
1200
1201 /* Trigger an interrupt first and let hdaRegWriteSDSTS() deal with
1202 * ending / beginning a period. */
1203#ifndef LOG_ENABLED
1204 hdaProcessInterrupt(pThis);
1205#else
1206 hdaProcessInterrupt(pThis, __FUNCTION__);
1207#endif
1208 }
1209 else /* Transfer still in-flight -- schedule the next timing slot. */
1210 {
1211 uint32_t cbTransferNext = cbTransferLeft;
1212
1213 /* No data left to transfer anymore or do we have more data left
1214 * than we can transfer per timing slot? Clamp. */
1215 if ( !cbTransferNext
1216 || cbTransferNext > pStream->State.cbTransferChunk)
1217 {
1218 cbTransferNext = pStream->State.cbTransferChunk;
1219 }
1220
1221 tsTransferNext = tsNow + (cbTransferNext * pStream->State.cTicksPerByte);
1222
1223 /*
1224 * If the current transfer is complete, reset our counter.
1225 *
1226 * This can happen for examlpe if the guest OS (like macOS) sets up
1227 * big BDLEs without IOC bits set (but for the last one) and the
1228 * transfer is complete before we reach such a BDL entry.
1229 */
1230 if (fTransferComplete)
1231 pStream->State.cbTransferProcessed = 0;
1232 }
1233
1234 /* If we need to do another transfer, (re-)arm the device timer. */
1235 if (tsTransferNext) /* Can be 0 if no next transfer is needed. */
1236 {
1237 Log3Func(("[SD%RU8] Scheduling timer\n", pStream->u8SD));
1238
1239 TMTimerUnlock(pStream->pTimer);
1240
1241 LogFunc(("Timer set SD%RU8\n", pStream->u8SD));
1242 hdaR3TimerSet(pStream->pHDAState, pStream, tsTransferNext, false /* fForce */);
1243
1244 TMTimerLock(pStream->pTimer, VINF_SUCCESS);
1245
1246 pStream->State.tsTransferNext = tsTransferNext;
1247 }
1248
1249 pStream->State.tsTransferLast = tsNow;
1250
1251 Log3Func(("[SD%RU8] cbTransferLeft=%RU32 -- %RU32/%RU32\n",
1252 pStream->u8SD, cbTransferLeft, pStream->State.cbTransferProcessed, pStream->State.cbTransferSize));
1253 Log3Func(("[SD%RU8] fTransferComplete=%RTbool, cTransferPendingInterrupts=%RU8\n",
1254 pStream->u8SD, fTransferComplete, pStream->State.cTransferPendingInterrupts));
1255 Log3Func(("[SD%RU8] tsNow=%RU64, tsTransferNext=%RU64 (in %RU64 ticks)\n",
1256 pStream->u8SD, tsNow, tsTransferNext, tsTransferNext - tsNow));
1257
1258 hdaR3StreamPeriodUnlock(pPeriod);
1259 hdaR3StreamUnlock(pStream);
1260
1261 return VINF_SUCCESS;
1262}
1263
1264/**
1265 * Updates a HDA stream by doing its required data transfers.
1266 * The host sink(s) set the overall pace.
1267 *
1268 * This routine is called by both, the synchronous and the asynchronous, implementations.
1269 *
1270 * This routine is called by both, the synchronous and the asynchronous
1271 * (VBOX_WITH_AUDIO_HDA_ASYNC_IO), implementations.
1272 *
1273 * When running synchronously, the device DMA transfers *and* the mixer sink
1274 * processing is within the device timer.
1275 *
1276 * When running asynchronously, only the device DMA transfers are done in the
1277 * device timer, whereas the mixer sink processing then is done in the stream's
1278 * own async I/O thread. This thread also will call this function
1279 * (with fInTimer set to @c false).
1280 *
1281 * @param pStream HDA stream to update.
1282 * @param fInTimer Whether to this function was called from the timer
1283 * context or an asynchronous I/O stream thread (if supported).
1284 */
1285void hdaR3StreamUpdate(PHDASTREAM pStream, bool fInTimer)
1286{
1287 if (!pStream)
1288 return;
1289
1290 PAUDMIXSINK pSink = NULL;
1291 if ( pStream->pMixSink
1292 && pStream->pMixSink->pMixSink)
1293 {
1294 pSink = pStream->pMixSink->pMixSink;
1295 }
1296
1297 if (!AudioMixerSinkIsActive(pSink)) /* No sink available? Bail out. */
1298 return;
1299
1300 int rc2;
1301
1302 if (hdaGetDirFromSD(pStream->u8SD) == PDMAUDIODIR_OUT) /* Output (SDO). */
1303 {
1304 bool fDoRead = false; /* Whether to read from the HDA stream or not. */
1305
1306# ifdef VBOX_WITH_AUDIO_HDA_ASYNC_IO
1307 if (fInTimer)
1308# endif
1309 {
1310 const uint32_t cbStreamFree = hdaR3StreamGetFree(pStream);
1311 if (cbStreamFree)
1312 {
1313 /* Do the DMA transfer. */
1314 rc2 = hdaR3StreamTransfer(pStream, cbStreamFree);
1315 AssertRC(rc2);
1316 }
1317
1318 /* Only read from the HDA stream at the given scheduling rate. */
1319 const uint64_t tsNowNs = RTTimeNanoTS();
1320 if (tsNowNs - pStream->State.tsLastUpdateNs >= pStream->State.Cfg.Device.uSchedulingHintMs * RT_NS_1MS)
1321 {
1322 fDoRead = true;
1323 pStream->State.tsLastUpdateNs = tsNowNs;
1324 }
1325 }
1326
1327 Log3Func(("[SD%RU8] fInTimer=%RTbool, fDoRead=%RTbool\n", pStream->u8SD, fInTimer, fDoRead));
1328
1329# ifdef VBOX_WITH_AUDIO_HDA_ASYNC_IO
1330 if (fDoRead)
1331 {
1332 rc2 = hdaR3StreamAsyncIONotify(pStream);
1333 AssertRC(rc2);
1334 }
1335# endif
1336
1337# ifdef VBOX_WITH_AUDIO_HDA_ASYNC_IO
1338 if (!fInTimer) /* In async I/O thread */
1339 {
1340# else
1341 if (fDoRead)
1342 {
1343# endif
1344 const uint32_t cbSinkWritable = AudioMixerSinkGetWritable(pSink);
1345 const uint32_t cbStreamReadable = hdaR3StreamGetUsed(pStream);
1346 const uint32_t cbToReadFromStream = RT_MIN(cbStreamReadable, cbSinkWritable);
1347
1348 Log3Func(("[SD%RU8] cbSinkWritable=%RU32, cbStreamReadable=%RU32\n", pStream->u8SD, cbSinkWritable, cbStreamReadable));
1349
1350 if (cbToReadFromStream)
1351 {
1352 /* Read (guest output) data and write it to the stream's sink. */
1353 rc2 = hdaR3StreamRead(pStream, cbToReadFromStream, NULL);
1354 AssertRC(rc2);
1355 }
1356
1357 /* When running synchronously, update the associated sink here.
1358 * Otherwise this will be done in the async I/O thread. */
1359 rc2 = AudioMixerSinkUpdate(pSink);
1360 AssertRC(rc2);
1361 }
1362 }
1363 else /* Input (SDI). */
1364 {
1365# ifdef VBOX_WITH_AUDIO_HDA_ASYNC_IO
1366 if (!fInTimer)
1367 {
1368# endif
1369 rc2 = AudioMixerSinkUpdate(pSink);
1370 AssertRC(rc2);
1371
1372 /* Is the sink ready to be read (host input data) from? If so, by how much? */
1373 uint32_t cbSinkReadable = AudioMixerSinkGetReadable(pSink);
1374
1375 /* How much (guest input) data is available for writing at the moment for the HDA stream? */
1376 const uint32_t cbStreamFree = hdaR3StreamGetFree(pStream);
1377
1378 Log3Func(("[SD%RU8] cbSinkReadable=%RU32, cbStreamFree=%RU32\n", pStream->u8SD, cbSinkReadable, cbStreamFree));
1379
1380 /* Do not read more than the HDA stream can hold at the moment.
1381 * The host sets the overall pace. */
1382 if (cbSinkReadable > cbStreamFree)
1383 cbSinkReadable = cbStreamFree;
1384
1385 if (cbSinkReadable)
1386 {
1387 uint8_t abFIFO[HDA_FIFO_MAX + 1];
1388 while (cbSinkReadable)
1389 {
1390 uint32_t cbRead;
1391 rc2 = AudioMixerSinkRead(pSink, AUDMIXOP_COPY,
1392 abFIFO, RT_MIN(cbSinkReadable, (uint32_t)sizeof(abFIFO)), &cbRead);
1393 AssertRCBreak(rc2);
1394
1395 if (!cbRead)
1396 {
1397 AssertMsgFailed(("Nothing read from sink, even if %RU32 bytes were (still) announced\n", cbSinkReadable));
1398 break;
1399 }
1400
1401 /* Write (guest input) data to the stream which was read from stream's sink before. */
1402 uint32_t cbWritten;
1403 rc2 = hdaR3StreamWrite(pStream, abFIFO, cbRead, &cbWritten);
1404 AssertRCBreak(rc2);
1405
1406 if (!cbWritten)
1407 {
1408 AssertFailed(); /* Should never happen, as we know how much we can write. */
1409 break;
1410 }
1411
1412 Assert(cbSinkReadable >= cbRead);
1413 cbSinkReadable -= cbRead;
1414 }
1415 }
1416# ifdef VBOX_WITH_AUDIO_HDA_ASYNC_IO
1417 }
1418 else /* fInTimer */
1419 {
1420# endif
1421
1422# ifdef VBOX_WITH_AUDIO_HDA_ASYNC_IO
1423 const uint64_t tsNowNs = RTTimeNanoTS();
1424 if (tsNowNs - pStream->State.tsLastUpdateNs >= pStream->State.Cfg.Device.uSchedulingHintMs * RT_NS_1MS)
1425 {
1426 rc2 = hdaR3StreamAsyncIONotify(pStream);
1427 AssertRC(rc2);
1428
1429 pStream->State.tsLastUpdateNs = tsNowNs;
1430 }
1431# endif
1432 const uint32_t cbStreamUsed = hdaR3StreamGetUsed(pStream);
1433 if (cbStreamUsed)
1434 {
1435 rc2 = hdaR3StreamTransfer(pStream, cbStreamUsed);
1436 AssertRC(rc2);
1437 }
1438# ifdef VBOX_WITH_AUDIO_HDA_ASYNC_IO
1439 }
1440# endif
1441 }
1442}
1443
1444/**
1445 * Locks an HDA stream for serialized access.
1446 *
1447 * @returns IPRT status code.
1448 * @param pStream HDA stream to lock.
1449 */
1450void hdaR3StreamLock(PHDASTREAM pStream)
1451{
1452 AssertPtrReturnVoid(pStream);
1453 int rc2 = RTCritSectEnter(&pStream->CritSect);
1454 AssertRC(rc2);
1455}
1456
1457/**
1458 * Unlocks a formerly locked HDA stream.
1459 *
1460 * @returns IPRT status code.
1461 * @param pStream HDA stream to unlock.
1462 */
1463void hdaR3StreamUnlock(PHDASTREAM pStream)
1464{
1465 AssertPtrReturnVoid(pStream);
1466 int rc2 = RTCritSectLeave(&pStream->CritSect);
1467 AssertRC(rc2);
1468}
1469
1470/**
1471 * Updates an HDA stream's current read or write buffer position (depending on the stream type) by
1472 * updating its associated LPIB register and DMA position buffer (if enabled).
1473 *
1474 * @returns Set LPIB value.
1475 * @param pStream HDA stream to update read / write position for.
1476 * @param u32LPIB New LPIB (position) value to set.
1477 */
1478uint32_t hdaR3StreamUpdateLPIB(PHDASTREAM pStream, uint32_t u32LPIB)
1479{
1480 AssertPtrReturn(pStream, 0);
1481
1482 AssertMsg(u32LPIB <= pStream->u32CBL,
1483 ("[SD%RU8] New LPIB (%RU32) exceeds CBL (%RU32)\n", pStream->u8SD, u32LPIB, pStream->u32CBL));
1484
1485 const PHDASTATE pThis = pStream->pHDAState;
1486
1487 u32LPIB = RT_MIN(u32LPIB, pStream->u32CBL);
1488
1489 LogFlowFunc(("[SD%RU8]: LPIB=%RU32 (DMA Position Buffer Enabled: %RTbool)\n",
1490 pStream->u8SD, u32LPIB, pThis->fDMAPosition));
1491
1492 /* Update LPIB in any case. */
1493 HDA_STREAM_REG(pThis, LPIB, pStream->u8SD) = u32LPIB;
1494
1495 /* Do we need to tell the current DMA position? */
1496 if (pThis->fDMAPosition)
1497 {
1498 int rc2 = PDMDevHlpPCIPhysWrite(pThis->CTX_SUFF(pDevIns),
1499 pThis->u64DPBase + (pStream->u8SD * 2 * sizeof(uint32_t)),
1500 (void *)&u32LPIB, sizeof(uint32_t));
1501 AssertRC(rc2);
1502 }
1503
1504 return u32LPIB;
1505}
1506
1507# ifdef HDA_USE_DMA_ACCESS_HANDLER
1508/**
1509 * Registers access handlers for a stream's BDLE DMA accesses.
1510 *
1511 * @returns true if registration was successful, false if not.
1512 * @param pStream HDA stream to register BDLE access handlers for.
1513 */
1514bool hdaR3StreamRegisterDMAHandlers(PHDASTREAM pStream)
1515{
1516 /* At least LVI and the BDL base must be set. */
1517 if ( !pStream->u16LVI
1518 || !pStream->u64BDLBase)
1519 {
1520 return false;
1521 }
1522
1523 hdaR3StreamUnregisterDMAHandlers(pStream);
1524
1525 LogFunc(("Registering ...\n"));
1526
1527 int rc = VINF_SUCCESS;
1528
1529 /*
1530 * Create BDLE ranges.
1531 */
1532
1533 struct BDLERANGE
1534 {
1535 RTGCPHYS uAddr;
1536 uint32_t uSize;
1537 } arrRanges[16]; /** @todo Use a define. */
1538
1539 size_t cRanges = 0;
1540
1541 for (uint16_t i = 0; i < pStream->u16LVI + 1; i++)
1542 {
1543 HDABDLE BDLE;
1544 rc = hdaR3BDLEFetch(pThis, &BDLE, pStream->u64BDLBase, i /* Index */);
1545 if (RT_FAILURE(rc))
1546 break;
1547
1548 bool fAddRange = true;
1549 BDLERANGE *pRange;
1550
1551 if (cRanges)
1552 {
1553 pRange = &arrRanges[cRanges - 1];
1554
1555 /* Is the current range a direct neighbor of the current BLDE? */
1556 if ((pRange->uAddr + pRange->uSize) == BDLE.Desc.u64BufAdr)
1557 {
1558 /* Expand the current range by the current BDLE's size. */
1559 pRange->uSize += BDLE.Desc.u32BufSize;
1560
1561 /* Adding a new range in this case is not needed anymore. */
1562 fAddRange = false;
1563
1564 LogFunc(("Expanding range %zu by %RU32 (%RU32 total now)\n", cRanges - 1, BDLE.Desc.u32BufSize, pRange->uSize));
1565 }
1566 }
1567
1568 /* Do we need to add a new range? */
1569 if ( fAddRange
1570 && cRanges < RT_ELEMENTS(arrRanges))
1571 {
1572 pRange = &arrRanges[cRanges];
1573
1574 pRange->uAddr = BDLE.Desc.u64BufAdr;
1575 pRange->uSize = BDLE.Desc.u32BufSize;
1576
1577 LogFunc(("Adding range %zu - 0x%x (%RU32)\n", cRanges, pRange->uAddr, pRange->uSize));
1578
1579 cRanges++;
1580 }
1581 }
1582
1583 LogFunc(("%zu ranges total\n", cRanges));
1584
1585 /*
1586 * Register all ranges as DMA access handlers.
1587 */
1588
1589 for (size_t i = 0; i < cRanges; i++)
1590 {
1591 BDLERANGE *pRange = &arrRanges[i];
1592
1593 PHDADMAACCESSHANDLER pHandler = (PHDADMAACCESSHANDLER)RTMemAllocZ(sizeof(HDADMAACCESSHANDLER));
1594 if (!pHandler)
1595 {
1596 rc = VERR_NO_MEMORY;
1597 break;
1598 }
1599
1600 RTListAppend(&pStream->State.lstDMAHandlers, &pHandler->Node);
1601
1602 pHandler->pStream = pStream; /* Save a back reference to the owner. */
1603
1604 char szDesc[32];
1605 RTStrPrintf(szDesc, sizeof(szDesc), "HDA[SD%RU8 - RANGE%02zu]", pStream->u8SD, i);
1606
1607 int rc2 = PGMR3HandlerPhysicalTypeRegister(PDMDevHlpGetVM(pStream->pHDAState->pDevInsR3), PGMPHYSHANDLERKIND_WRITE,
1608 hdaDMAAccessHandler,
1609 NULL, NULL, NULL,
1610 NULL, NULL, NULL,
1611 szDesc, &pHandler->hAccessHandlerType);
1612 AssertRCBreak(rc2);
1613
1614 pHandler->BDLEAddr = pRange->uAddr;
1615 pHandler->BDLESize = pRange->uSize;
1616
1617 /* Get first and last pages of the BDLE range. */
1618 RTGCPHYS pgFirst = pRange->uAddr & ~PAGE_OFFSET_MASK;
1619 RTGCPHYS pgLast = RT_ALIGN(pgFirst + pRange->uSize, PAGE_SIZE);
1620
1621 /* Calculate the region size (in pages). */
1622 RTGCPHYS regionSize = RT_ALIGN(pgLast - pgFirst, PAGE_SIZE);
1623
1624 pHandler->GCPhysFirst = pgFirst;
1625 pHandler->GCPhysLast = pHandler->GCPhysFirst + (regionSize - 1);
1626
1627 LogFunc(("\tRegistering region '%s': 0x%x - 0x%x (region size: %zu)\n",
1628 szDesc, pHandler->GCPhysFirst, pHandler->GCPhysLast, regionSize));
1629 LogFunc(("\tBDLE @ 0x%x - 0x%x (%RU32)\n",
1630 pHandler->BDLEAddr, pHandler->BDLEAddr + pHandler->BDLESize, pHandler->BDLESize));
1631
1632 rc2 = PGMHandlerPhysicalRegister(PDMDevHlpGetVM(pStream->pHDAState->pDevInsR3),
1633 pHandler->GCPhysFirst, pHandler->GCPhysLast,
1634 pHandler->hAccessHandlerType, pHandler, NIL_RTR0PTR, NIL_RTRCPTR,
1635 szDesc);
1636 AssertRCBreak(rc2);
1637
1638 pHandler->fRegistered = true;
1639 }
1640
1641 LogFunc(("Registration ended with rc=%Rrc\n", rc));
1642
1643 return RT_SUCCESS(rc);
1644}
1645
1646/**
1647 * Unregisters access handlers of a stream's BDLEs.
1648 *
1649 * @param pStream HDA stream to unregister BDLE access handlers for.
1650 */
1651void hdaR3StreamUnregisterDMAHandlers(PHDASTREAM pStream)
1652{
1653 LogFunc(("\n"));
1654
1655 PHDADMAACCESSHANDLER pHandler, pHandlerNext;
1656 RTListForEachSafe(&pStream->State.lstDMAHandlers, pHandler, pHandlerNext, HDADMAACCESSHANDLER, Node)
1657 {
1658 if (!pHandler->fRegistered) /* Handler not registered? Skip. */
1659 continue;
1660
1661 LogFunc(("Unregistering 0x%x - 0x%x (%zu)\n",
1662 pHandler->GCPhysFirst, pHandler->GCPhysLast, pHandler->GCPhysLast - pHandler->GCPhysFirst));
1663
1664 int rc2 = PGMHandlerPhysicalDeregister(PDMDevHlpGetVM(pStream->pHDAState->pDevInsR3),
1665 pHandler->GCPhysFirst);
1666 AssertRC(rc2);
1667
1668 RTListNodeRemove(&pHandler->Node);
1669
1670 RTMemFree(pHandler);
1671 pHandler = NULL;
1672 }
1673
1674 Assert(RTListIsEmpty(&pStream->State.lstDMAHandlers));
1675}
1676# endif /* HDA_USE_DMA_ACCESS_HANDLER */
1677
1678# ifdef VBOX_WITH_AUDIO_HDA_ASYNC_IO
1679/**
1680 * Asynchronous I/O thread for a HDA stream.
1681 * This will do the heavy lifting work for us as soon as it's getting notified by another thread.
1682 *
1683 * @returns IPRT status code.
1684 * @param hThreadSelf Thread handle.
1685 * @param pvUser User argument. Must be of type PHDASTREAMTHREADCTX.
1686 */
1687DECLCALLBACK(int) hdaR3StreamAsyncIOThread(RTTHREAD hThreadSelf, void *pvUser)
1688{
1689 PHDASTREAMTHREADCTX pCtx = (PHDASTREAMTHREADCTX)pvUser;
1690 AssertPtr(pCtx);
1691
1692 PHDASTREAM pStream = pCtx->pStream;
1693 AssertPtr(pStream);
1694
1695 PHDASTREAMSTATEAIO pAIO = &pCtx->pStream->State.AIO;
1696
1697 ASMAtomicXchgBool(&pAIO->fStarted, true);
1698
1699 RTThreadUserSignal(hThreadSelf);
1700
1701 LogFunc(("[SD%RU8]: Started\n", pStream->u8SD));
1702
1703 for (;;)
1704 {
1705 int rc2 = RTSemEventWait(pAIO->Event, RT_INDEFINITE_WAIT);
1706 if (RT_FAILURE(rc2))
1707 break;
1708
1709 if (ASMAtomicReadBool(&pAIO->fShutdown))
1710 break;
1711
1712 rc2 = RTCritSectEnter(&pAIO->CritSect);
1713 if (RT_SUCCESS(rc2))
1714 {
1715 if (!pAIO->fEnabled)
1716 {
1717 RTCritSectLeave(&pAIO->CritSect);
1718 continue;
1719 }
1720
1721 hdaR3StreamUpdate(pStream, false /* fInTimer */);
1722
1723 int rc3 = RTCritSectLeave(&pAIO->CritSect);
1724 AssertRC(rc3);
1725 }
1726
1727 AssertRC(rc2);
1728 }
1729
1730 LogFunc(("[SD%RU8]: Ended\n", pStream->u8SD));
1731
1732 ASMAtomicXchgBool(&pAIO->fStarted, false);
1733
1734 return VINF_SUCCESS;
1735}
1736
1737/**
1738 * Creates the async I/O thread for a specific HDA audio stream.
1739 *
1740 * @returns IPRT status code.
1741 * @param pStream HDA audio stream to create the async I/O thread for.
1742 */
1743int hdaR3StreamAsyncIOCreate(PHDASTREAM pStream)
1744{
1745 PHDASTREAMSTATEAIO pAIO = &pStream->State.AIO;
1746
1747 int rc;
1748
1749 if (!ASMAtomicReadBool(&pAIO->fStarted))
1750 {
1751 pAIO->fShutdown = false;
1752 pAIO->fEnabled = true; /* Enabled by default. */
1753
1754 rc = RTSemEventCreate(&pAIO->Event);
1755 if (RT_SUCCESS(rc))
1756 {
1757 rc = RTCritSectInit(&pAIO->CritSect);
1758 if (RT_SUCCESS(rc))
1759 {
1760 HDASTREAMTHREADCTX Ctx = { pStream->pHDAState, pStream };
1761
1762 char szThreadName[64];
1763 RTStrPrintf2(szThreadName, sizeof(szThreadName), "hdaAIO%RU8", pStream->u8SD);
1764
1765 rc = RTThreadCreate(&pAIO->Thread, hdaR3StreamAsyncIOThread, &Ctx,
1766 0, RTTHREADTYPE_IO, RTTHREADFLAGS_WAITABLE, szThreadName);
1767 if (RT_SUCCESS(rc))
1768 rc = RTThreadUserWait(pAIO->Thread, 10 * 1000 /* 10s timeout */);
1769 }
1770 }
1771 }
1772 else
1773 rc = VINF_SUCCESS;
1774
1775 LogFunc(("[SD%RU8]: Returning %Rrc\n", pStream->u8SD, rc));
1776 return rc;
1777}
1778
1779/**
1780 * Destroys the async I/O thread of a specific HDA audio stream.
1781 *
1782 * @returns IPRT status code.
1783 * @param pStream HDA audio stream to destroy the async I/O thread for.
1784 */
1785int hdaR3StreamAsyncIODestroy(PHDASTREAM pStream)
1786{
1787 PHDASTREAMSTATEAIO pAIO = &pStream->State.AIO;
1788
1789 if (!ASMAtomicReadBool(&pAIO->fStarted))
1790 return VINF_SUCCESS;
1791
1792 ASMAtomicWriteBool(&pAIO->fShutdown, true);
1793
1794 int rc = hdaR3StreamAsyncIONotify(pStream);
1795 AssertRC(rc);
1796
1797 int rcThread;
1798 rc = RTThreadWait(pAIO->Thread, 30 * 1000 /* 30s timeout */, &rcThread);
1799 LogFunc(("Async I/O thread ended with %Rrc (%Rrc)\n", rc, rcThread));
1800
1801 if (RT_SUCCESS(rc))
1802 {
1803 rc = RTCritSectDelete(&pAIO->CritSect);
1804 AssertRC(rc);
1805
1806 rc = RTSemEventDestroy(pAIO->Event);
1807 AssertRC(rc);
1808
1809 pAIO->fStarted = false;
1810 pAIO->fShutdown = false;
1811 pAIO->fEnabled = false;
1812 }
1813
1814 LogFunc(("[SD%RU8]: Returning %Rrc\n", pStream->u8SD, rc));
1815 return rc;
1816}
1817
1818/**
1819 * Lets the stream's async I/O thread know that there is some data to process.
1820 *
1821 * @returns IPRT status code.
1822 * @param pStream HDA stream to notify async I/O thread for.
1823 */
1824int hdaR3StreamAsyncIONotify(PHDASTREAM pStream)
1825{
1826 return RTSemEventSignal(pStream->State.AIO.Event);
1827}
1828
1829/**
1830 * Locks the async I/O thread of a specific HDA audio stream.
1831 *
1832 * @param pStream HDA stream to lock async I/O thread for.
1833 */
1834void hdaR3StreamAsyncIOLock(PHDASTREAM pStream)
1835{
1836 PHDASTREAMSTATEAIO pAIO = &pStream->State.AIO;
1837
1838 if (!ASMAtomicReadBool(&pAIO->fStarted))
1839 return;
1840
1841 int rc2 = RTCritSectEnter(&pAIO->CritSect);
1842 AssertRC(rc2);
1843}
1844
1845/**
1846 * Unlocks the async I/O thread of a specific HDA audio stream.
1847 *
1848 * @param pStream HDA stream to unlock async I/O thread for.
1849 */
1850void hdaR3StreamAsyncIOUnlock(PHDASTREAM pStream)
1851{
1852 PHDASTREAMSTATEAIO pAIO = &pStream->State.AIO;
1853
1854 if (!ASMAtomicReadBool(&pAIO->fStarted))
1855 return;
1856
1857 int rc2 = RTCritSectLeave(&pAIO->CritSect);
1858 AssertRC(rc2);
1859}
1860
1861/**
1862 * Enables (resumes) or disables (pauses) the async I/O thread.
1863 *
1864 * @param pStream HDA stream to enable/disable async I/O thread for.
1865 * @param fEnable Whether to enable or disable the I/O thread.
1866 *
1867 * @remarks Does not do locking.
1868 */
1869void hdaR3StreamAsyncIOEnable(PHDASTREAM pStream, bool fEnable)
1870{
1871 PHDASTREAMSTATEAIO pAIO = &pStream->State.AIO;
1872 ASMAtomicXchgBool(&pAIO->fEnabled, fEnable);
1873}
1874# endif /* VBOX_WITH_AUDIO_HDA_ASYNC_IO */
1875
1876#endif /* IN_RING3 */
1877
Note: See TracBrowser for help on using the repository browser.

© 2024 Oracle Support Privacy / Do Not Sell My Info Terms of Use Trademark Policy Automated Access Etiquette