VirtualBox

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

最後變更 在這個檔案從87936是 87934,由 vboxsync 提交於 4 年 前

hdaR3StreamAsyncIOThread should check the shutdown flag before going to sleep too; give the compiler some predicition hints; eliminated continue and extra cs leave.

  • 屬性 svn:eol-style 設為 native
  • 屬性 svn:keywords 設為 Author Date Id Revision
檔案大小: 84.2 KB
 
1/* $Id: HDAStream.cpp 87934 2021-03-03 12:17:39Z vboxsync $ */
2/** @file
3 * HDAStream.cpp - Stream functions for HD Audio.
4 */
5
6/*
7 * Copyright (C) 2017-2020 Oracle Corporation
8 *
9 * This file is part of VirtualBox Open Source Edition (OSE), as
10 * available from http://www.alldomusa.eu.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/AssertGuest.h>
29#include <VBox/vmm/pdmdev.h>
30#include <VBox/vmm/pdmaudioifs.h>
31
32#include "DrvAudio.h"
33
34#include "DevHDA.h"
35#include "HDAStream.h"
36
37#ifdef IN_RING3 /* whole file */
38
39
40/*********************************************************************************************************************************
41* Internal Functions *
42*********************************************************************************************************************************/
43static void hdaR3StreamSetPositionAbs(PHDASTREAM pStreamShared, PPDMDEVINS pDevIns, PHDASTATE pThis, uint32_t uLPIB);
44
45static int hdaR3StreamAsyncIODestroy(PHDASTREAMR3 pStreamR3);
46static int hdaR3StreamAsyncIONotify(PHDASTREAMR3 pStreamR3);
47
48
49
50/**
51 * Creates an HDA stream.
52 *
53 * @returns IPRT status code.
54 * @param pStreamShared The HDA stream to construct - shared bits.
55 * @param pStreamR3 The HDA stream to construct - ring-3 bits.
56 * @param pThis The shared HDA device instance.
57 * @param pThisCC The ring-3 HDA device instance.
58 * @param uSD Stream descriptor number to assign.
59 */
60int hdaR3StreamConstruct(PHDASTREAM pStreamShared, PHDASTREAMR3 pStreamR3, PHDASTATE pThis, PHDASTATER3 pThisCC, uint8_t uSD)
61{
62 int rc;
63
64 pStreamR3->u8SD = uSD;
65 pStreamShared->u8SD = uSD;
66 pStreamR3->pMixSink = NULL;
67 pStreamR3->pHDAStateShared = pThis;
68 pStreamR3->pHDAStateR3 = pThisCC;
69 Assert(pStreamShared->hTimer != NIL_TMTIMERHANDLE); /* hdaR3Construct initalized this one already. */
70
71 pStreamShared->State.fInReset = false;
72 pStreamShared->State.fRunning = false;
73#ifdef HDA_USE_DMA_ACCESS_HANDLER
74 RTListInit(&pStreamR3->State.lstDMAHandlers);
75#endif
76
77#ifdef VBOX_WITH_AUDIO_HDA_ASYNC_IO
78 AssertPtr(pStreamR3->pHDAStateR3);
79 AssertPtr(pStreamR3->pHDAStateR3->pDevIns);
80 rc = PDMDevHlpCritSectInit(pStreamR3->pHDAStateR3->pDevIns, &pStreamShared->CritSect,
81 RT_SRC_POS, "hda_sd#%RU8", pStreamShared->u8SD);
82 AssertRCReturn(rc, rc);
83#endif
84
85 rc = hdaR3StreamPeriodCreate(&pStreamShared->State.Period);
86 AssertRCReturn(rc, rc);
87
88#ifdef DEBUG
89 rc = RTCritSectInit(&pStreamR3->Dbg.CritSect);
90 AssertRCReturn(rc, rc);
91#endif
92
93 const bool fIsInput = hdaGetDirFromSD(uSD) == PDMAUDIODIR_IN;
94
95 if (fIsInput)
96 {
97 pStreamShared->State.Cfg.u.enmSrc = PDMAUDIORECSRC_UNKNOWN;
98 pStreamShared->State.Cfg.enmDir = PDMAUDIODIR_IN;
99 }
100 else
101 {
102 pStreamShared->State.Cfg.u.enmDst = PDMAUDIOPLAYBACKDST_UNKNOWN;
103 pStreamShared->State.Cfg.enmDir = PDMAUDIODIR_OUT;
104 }
105
106 pStreamR3->Dbg.Runtime.fEnabled = pThisCC->Dbg.fEnabled;
107
108 if (pStreamR3->Dbg.Runtime.fEnabled)
109 {
110 char szFile[64];
111 char szPath[RTPATH_MAX];
112
113 /* pFileStream */
114 if (fIsInput)
115 RTStrPrintf(szFile, sizeof(szFile), "hdaStreamWriteSD%RU8", uSD);
116 else
117 RTStrPrintf(szFile, sizeof(szFile), "hdaStreamReadSD%RU8", uSD);
118
119 int rc2 = DrvAudioHlpFileNameGet(szPath, sizeof(szPath), pThisCC->Dbg.pszOutPath, szFile,
120 0 /* uInst */, PDMAUDIOFILETYPE_WAV, PDMAUDIOFILENAME_FLAGS_NONE);
121 AssertRC(rc2);
122
123 rc2 = DrvAudioHlpFileCreate(PDMAUDIOFILETYPE_WAV, szPath, PDMAUDIOFILE_FLAGS_NONE, &pStreamR3->Dbg.Runtime.pFileStream);
124 AssertRC(rc2);
125
126 /* pFileDMARaw */
127 if (fIsInput)
128 RTStrPrintf(szFile, sizeof(szFile), "hdaDMARawWriteSD%RU8", uSD);
129 else
130 RTStrPrintf(szFile, sizeof(szFile), "hdaDMARawReadSD%RU8", uSD);
131
132 rc2 = DrvAudioHlpFileNameGet(szPath, sizeof(szPath), pThisCC->Dbg.pszOutPath, szFile,
133 0 /* uInst */, PDMAUDIOFILETYPE_WAV, PDMAUDIOFILENAME_FLAGS_NONE);
134 AssertRC(rc2);
135
136 rc2 = DrvAudioHlpFileCreate(PDMAUDIOFILETYPE_WAV, szPath, PDMAUDIOFILE_FLAGS_NONE, &pStreamR3->Dbg.Runtime.pFileDMARaw);
137 AssertRC(rc2);
138
139 /* pFileDMAMapped */
140 if (fIsInput)
141 RTStrPrintf(szFile, sizeof(szFile), "hdaDMAWriteMappedSD%RU8", uSD);
142 else
143 RTStrPrintf(szFile, sizeof(szFile), "hdaDMAReadMappedSD%RU8", uSD);
144
145 rc2 = DrvAudioHlpFileNameGet(szPath, sizeof(szPath), pThisCC->Dbg.pszOutPath, szFile,
146 0 /* uInst */, PDMAUDIOFILETYPE_WAV, PDMAUDIOFILENAME_FLAGS_NONE);
147 AssertRC(rc2);
148
149 rc2 = DrvAudioHlpFileCreate(PDMAUDIOFILETYPE_WAV, szPath, PDMAUDIOFILE_FLAGS_NONE, &pStreamR3->Dbg.Runtime.pFileDMAMapped);
150 AssertRC(rc2);
151
152 /* Delete stale debugging files from a former run. */
153 DrvAudioHlpFileDelete(pStreamR3->Dbg.Runtime.pFileStream);
154 DrvAudioHlpFileDelete(pStreamR3->Dbg.Runtime.pFileDMARaw);
155 DrvAudioHlpFileDelete(pStreamR3->Dbg.Runtime.pFileDMAMapped);
156 }
157
158 return rc;
159}
160
161/**
162 * Destroys an HDA stream.
163 *
164 * @param pStreamShared The HDA stream to destroy - shared bits.
165 * @param pStreamR3 The HDA stream to destroy - ring-3 bits.
166 */
167void hdaR3StreamDestroy(PHDASTREAM pStreamShared, PHDASTREAMR3 pStreamR3)
168{
169 LogFlowFunc(("[SD%RU8] Destroying ...\n", pStreamShared->u8SD));
170
171 hdaR3StreamMapDestroy(&pStreamR3->State.Mapping);
172
173 int rc2;
174
175#ifdef VBOX_WITH_AUDIO_HDA_ASYNC_IO
176 rc2 = hdaR3StreamAsyncIODestroy(pStreamR3);
177 AssertRC(rc2);
178#endif
179
180#ifdef VBOX_WITH_AUDIO_HDA_ASYNC_IO
181 if (PDMCritSectIsInitialized(&pStreamShared->CritSect))
182 {
183 rc2 = PDMR3CritSectDelete(&pStreamShared->CritSect);
184 AssertRC(rc2);
185 }
186#endif
187
188 if (pStreamR3->State.pCircBuf)
189 {
190 RTCircBufDestroy(pStreamR3->State.pCircBuf);
191 pStreamR3->State.pCircBuf = NULL;
192 }
193
194 hdaR3StreamPeriodDestroy(&pStreamShared->State.Period);
195
196#ifdef DEBUG
197 if (RTCritSectIsInitialized(&pStreamR3->Dbg.CritSect))
198 {
199 rc2 = RTCritSectDelete(&pStreamR3->Dbg.CritSect);
200 AssertRC(rc2);
201 }
202#endif
203
204 if (pStreamR3->Dbg.Runtime.fEnabled)
205 {
206 DrvAudioHlpFileDestroy(pStreamR3->Dbg.Runtime.pFileStream);
207 pStreamR3->Dbg.Runtime.pFileStream = NULL;
208
209 DrvAudioHlpFileDestroy(pStreamR3->Dbg.Runtime.pFileDMARaw);
210 pStreamR3->Dbg.Runtime.pFileDMARaw = NULL;
211
212 DrvAudioHlpFileDestroy(pStreamR3->Dbg.Runtime.pFileDMAMapped);
213 pStreamR3->Dbg.Runtime.pFileDMAMapped = NULL;
214 }
215
216 LogFlowFuncLeave();
217}
218
219/**
220 * Sets up ((re-)iniitalizes) an HDA stream.
221 *
222 * @returns IPRT status code. VINF_NO_CHANGE if the stream does not need
223 * be set-up again because the stream's (hardware) parameters did
224 * not change.
225 * @param pDevIns The device instance.
226 * @param pThis The shared HDA device state (for HW register
227 * parameters).
228 * @param pStreamShared HDA stream to set up, shared portion.
229 * @param pStreamR3 HDA stream to set up, ring-3 portion.
230 * @param uSD Stream descriptor number to assign it.
231 */
232int hdaR3StreamSetUp(PPDMDEVINS pDevIns, PHDASTATE pThis, PHDASTREAM pStreamShared, PHDASTREAMR3 pStreamR3, uint8_t uSD)
233{
234 /* This must be valid all times. */
235 AssertReturn(uSD < HDA_MAX_STREAMS, VERR_INVALID_PARAMETER);
236
237 /* These member can only change on data corruption, despite what the code does further down (bird). */
238 AssertReturn(pStreamShared->u8SD == uSD, VERR_WRONG_ORDER);
239 AssertReturn(pStreamR3->u8SD == uSD, VERR_WRONG_ORDER);
240
241 const uint64_t u64BDLBase = RT_MAKE_U64(HDA_STREAM_REG(pThis, BDPL, uSD),
242 HDA_STREAM_REG(pThis, BDPU, uSD));
243 const uint16_t u16LVI = HDA_STREAM_REG(pThis, LVI, uSD);
244 const uint32_t u32CBL = HDA_STREAM_REG(pThis, CBL, uSD);
245 const uint8_t u8FIFOS = HDA_STREAM_REG(pThis, FIFOS, uSD) + 1;
246 uint8_t u8FIFOW = hdaSDFIFOWToBytes(HDA_STREAM_REG(pThis, FIFOW, uSD));
247 const uint16_t u16FMT = HDA_STREAM_REG(pThis, FMT, uSD);
248
249 /* Is the bare minimum set of registers configured for the stream?
250 * If not, bail out early, as there's nothing to do here for us (yet). */
251 if ( !u64BDLBase
252 || !u16LVI
253 || !u32CBL
254 || !u8FIFOS
255 || !u8FIFOW
256 || !u16FMT)
257 {
258 LogFunc(("[SD%RU8] Registers not set up yet, skipping (re-)initialization\n", uSD));
259 return VINF_SUCCESS;
260 }
261
262 PDMAUDIOPCMPROPS Props;
263 int rc = hdaR3SDFMTToPCMProps(u16FMT, &Props);
264 if (RT_FAILURE(rc))
265 {
266 LogRel(("HDA: Warning: Format 0x%x for stream #%RU8 not supported\n", HDA_STREAM_REG(pThis, FMT, uSD), uSD));
267 return rc;
268 }
269
270 /* Reset (any former) stream map. */
271 hdaR3StreamMapReset(&pStreamR3->State.Mapping);
272
273 /*
274 * Initialize the stream mapping in any case, regardless if
275 * we support surround audio or not. This is needed to handle
276 * the supported channels within a single audio stream, e.g. mono/stereo.
277 *
278 * In other words, the stream mapping *always* knows the real
279 * number of channels in a single audio stream.
280 */
281 rc = hdaR3StreamMapInit(&pStreamR3->State.Mapping, &Props);
282 AssertRCReturn(rc, rc);
283
284 ASSERT_GUEST_LOGREL_MSG_RETURN( pStreamR3->State.Mapping.cbFrameSize > 0
285 && u32CBL % pStreamR3->State.Mapping.cbFrameSize == 0,
286 ("CBL for stream #%RU8 does not align to frame size (u32CBL=%u cbFrameSize=%u)\n",
287 uSD, u32CBL, pStreamR3->State.Mapping.cbFrameSize),
288 VERR_INVALID_PARAMETER);
289
290#ifndef VBOX_WITH_AUDIO_HDA_51_SURROUND
291 if (Props.cChannels > 2)
292 {
293 /*
294 * When not running with surround support enabled, override the audio channel count
295 * with stereo (2) channels so that we at least can properly work with those.
296 *
297 * Note: This also involves dealing with surround setups the guest might has set up for us.
298 */
299 LogRel(("HDA: Warning: More than stereo (2) channels are not supported (%RU8 requested), "
300 "falling back to stereo channels for stream #%RU8\n", Props.cChannels, uSD));
301 Props.cChannels = 2;
302 Props.cShift = PDMAUDIOPCMPROPS_MAKE_SHIFT_PARMS(Props.cbSample, Props.cChannels);
303 }
304#endif
305
306 /* Make sure the guest behaves regarding the stream's FIFO. */
307 ASSERT_GUEST_LOGREL_MSG_STMT(u8FIFOW <= u8FIFOS,
308 ("Guest tried setting a bigger FIFOW (%RU8) than FIFOS (%RU8), limiting\n", u8FIFOW, u8FIFOS),
309 u8FIFOW = u8FIFOS /* ASSUMES that u8FIFOS has been validated. */);
310
311 pStreamShared->u8SD = uSD;
312
313 /* Update all register copies so that we later know that something has changed. */
314 pStreamShared->u64BDLBase = u64BDLBase;
315 pStreamShared->u16LVI = u16LVI;
316 pStreamShared->u32CBL = u32CBL;
317 pStreamShared->u8FIFOS = u8FIFOS;
318 pStreamShared->u8FIFOW = u8FIFOW;
319 pStreamShared->u16FMT = u16FMT;
320
321 PPDMAUDIOSTREAMCFG pCfg = &pStreamShared->State.Cfg;
322 pCfg->Props = Props;
323
324 /* Set the stream's direction. */
325 pCfg->enmDir = hdaGetDirFromSD(uSD);
326
327 /* The the stream's name, based on the direction. */
328 switch (pCfg->enmDir)
329 {
330 case PDMAUDIODIR_IN:
331# ifdef VBOX_WITH_AUDIO_HDA_MIC_IN
332# error "Implement me!"
333# else
334 pCfg->u.enmSrc = PDMAUDIORECSRC_LINE;
335 pCfg->enmLayout = PDMAUDIOSTREAMLAYOUT_NON_INTERLEAVED;
336 RTStrCopy(pCfg->szName, sizeof(pCfg->szName), "Line In");
337# endif
338 break;
339
340 case PDMAUDIODIR_OUT:
341 /* Destination(s) will be set in hdaAddStreamOut(),
342 * based on the channels / stream layout. */
343 break;
344
345 default:
346 AssertFailedReturn(VERR_NOT_SUPPORTED);
347 break;
348 }
349
350 /* Assign the global device rate to the stream. */
351 pStreamShared->State.uTimerIoHz = pThis->uTimerHz;
352
353 /* Set scheduling hint (if available). */
354 if (pStreamShared->State.uTimerIoHz)
355 pCfg->Device.cMsSchedulingHint = RT_MS_1SEC / pStreamShared->State.uTimerIoHz;
356
357 LogRel2(("HDA: Stream #%RU8 DMA @ 0x%x (%RU32 bytes = %RU64ms total)\n",
358 uSD, pStreamShared->u64BDLBase, pStreamShared->u32CBL,
359 DrvAudioHlpBytesToMilli(pStreamShared->u32CBL, &pStreamShared->State.Cfg.Props)));
360
361 /* Make sure that the chosen Hz rate dividable by the stream's rate. */
362 if (pStreamShared->State.Cfg.Props.uHz % pStreamShared->State.uTimerIoHz != 0)
363 LogRel(("HDA: Stream #%RU8 timer Hz rate (%RU32) does not fit to stream #%RU8 timing (%RU32)\n",
364 uSD, pStreamShared->State.uTimerIoHz, uSD, pStreamShared->State.Cfg.Props.uHz));
365
366 /* Figure out how many transfer fragments we're going to use for this stream. */
367 uint8_t cTransferFragments = pStreamShared->u16LVI + 1;
368 if (cTransferFragments <= 1)
369 LogRel(("HDA: Warning: Stream #%RU8 transfer fragments (%RU8) invalid -- buggy guest audio driver!\n",
370 uSD, pStreamShared->u16LVI));
371
372 /*
373 * Handle the stream's position adjustment.
374 */
375 uint32_t cfPosAdjust = 0;
376
377 LogFunc(("[SD%RU8] fPosAdjustEnabled=%RTbool, cPosAdjustFrames=%RU16\n",
378 uSD, pThis->fPosAdjustEnabled, pThis->cPosAdjustFrames));
379
380 if (pThis->fPosAdjustEnabled) /* Is the position adjustment enabled at all? */
381 {
382 HDABDLE BDLE;
383 RT_ZERO(BDLE);
384
385 int rc2 = hdaR3BDLEFetch(pDevIns, &BDLE, pStreamShared->u64BDLBase, 0 /* Entry */);
386 AssertRC(rc2);
387
388 /* Note: Do *not* check if this BDLE aligns to the stream's frame size.
389 * It can happen that this isn't the case on some guests, e.g.
390 * on Windows with a 5.1 speaker setup.
391 *
392 * The only thing which counts is that the stream's CBL value
393 * properly aligns to the stream's frame size.
394 */
395
396 /* If no custom set position adjustment is set, apply some
397 * simple heuristics to detect the appropriate position adjustment. */
398 if ( !pThis->cPosAdjustFrames
399 /* Position adjustmenet buffer *must* have the IOC bit set! */
400 && hdaR3BDLENeedsInterrupt(&BDLE))
401 {
402 /** @todo Implement / use a (dynamic) table once this gets more complicated. */
403#ifdef VBOX_WITH_INTEL_HDA
404 /* Intel ICH / PCH: 1 frame. */
405 if (BDLE.Desc.u32BufSize == (uint32_t)(1 * pStreamR3->State.Mapping.cbFrameSize))
406 {
407 cfPosAdjust = 1;
408 }
409 /* Intel Baytrail / Braswell: 32 frames. */
410 else if (BDLE.Desc.u32BufSize == (uint32_t)(32 * pStreamR3->State.Mapping.cbFrameSize))
411 {
412 cfPosAdjust = 32;
413 }
414#endif
415 }
416 else /* Go with the set default. */
417 cfPosAdjust = pThis->cPosAdjustFrames;
418
419 if (cfPosAdjust)
420 {
421 /* Also adjust the number of fragments, as the position adjustment buffer
422 * does not count as an own fragment as such.
423 *
424 * This e.g. can happen on (newer) Ubuntu guests which use
425 * 4 (IOC) + 4408 (IOC) + 4408 (IOC) + 4408 (IOC) + 4404 (= 17632) bytes,
426 * where the first buffer (4) is used as position adjustment.
427 *
428 * Only skip a fragment if the whole buffer fragment is used for
429 * position adjustment.
430 */
431 if ((cfPosAdjust * pStreamR3->State.Mapping.cbFrameSize) == BDLE.Desc.u32BufSize)
432 cTransferFragments--;
433
434 /* Initialize position adjustment counter. */
435 pStreamShared->State.cfPosAdjustDefault = cfPosAdjust;
436 pStreamShared->State.cfPosAdjustLeft = pStreamShared->State.cfPosAdjustDefault;
437
438 LogRel2(("HDA: Position adjustment for stream #%RU8 active (%RU32 frames)\n",
439 uSD, pStreamShared->State.cfPosAdjustDefault));
440 }
441 }
442
443 Log3Func(("[SD%RU8] cfPosAdjust=%RU32, cFragments=%RU8\n", uSD, cfPosAdjust, cTransferFragments));
444
445 /*
446 * Set up data transfer stuff.
447 */
448
449 /* Prevent division by zero. */
450 ASSERT_GUEST_LOGREL_MSG_STMT(pStreamShared->State.uTimerIoHz,
451 ("Timer Hz rate for stream #%RU8 is invalid\n", uSD),
452 pStreamShared->State.uTimerIoHz = HDA_TIMER_HZ_DEFAULT);
453 /*
454 * Determine the transfer Hz the guest OS expects data transfer at.
455 *
456 * Guests also expect a very extact DMA timing for reading / writing audio data, so we run on a constant
457 * (virtual) rate which we expose to the guest.
458 *
459 * Data rate examples:
460 * * Windows 10 @ 44,1kHz / 16-bit stereo
461 * * Default mode: 448 audio frames -> ~10.15ms) = 1792 byte every ~10ms.
462 * * Fast mode: 128 audio frames -> ~ 2.90ms) = 512 byte every ~3ms.
463 */
464
465 /* The transfer Hz depend on the heuristics above, that is,
466 how often the guest expects to see a new data transfer. */
467 unsigned uTransferHz;
468
469 if (pThis->fTransferHeuristicsEnabled) /* Are data transfer heuristics enabled? */
470 {
471
472 /* Use the whole CBL as a starting point.
473 * This basically ASSUMES that we have one consequtive buffer with only one interrupt at the end. */
474 uint32_t cbTransferHeuristicsMin = pStreamShared->u32CBL;
475
476 /* Don't take frames (as bytes) into account which are part of the position adjustment. */
477 uint32_t cbTransferHeuristicsPosAdjust = pStreamShared->State.cfPosAdjustDefault * pStreamR3->State.Mapping.cbFrameSize;
478
479 HDABDLEDESC bd;
480 uint32_t cbTransferHeuristicsCur = 0;
481 for (uint8_t i = 0; i < cTransferFragments; i++)
482 {
483 PDMDevHlpPhysRead(pDevIns, u64BDLBase + i * sizeof(HDABDLEDESC), &bd, sizeof(bd));
484
485 /* Position adjustment (still) needed / active? */
486 if (cbTransferHeuristicsPosAdjust)
487 {
488 const uint32_t cbTransferHeuristicsPosAdjustMin = RT_MIN(cbTransferHeuristicsPosAdjust, bd.u32BufSize);
489
490 bd.u32BufSize -= cbTransferHeuristicsPosAdjustMin;
491 cbTransferHeuristicsPosAdjust -= cbTransferHeuristicsPosAdjustMin;
492 }
493
494 /* Anything left to process for the current BDLE after doing the position adjustment? */
495 if (bd.u32BufSize == 0)
496 continue;
497
498 /* Is an interrupt expected for the current BDLE? */
499 if (bd.fFlags & HDA_BDLE_F_IOC)
500 {
501 cbTransferHeuristicsCur += bd.u32BufSize;
502 cbTransferHeuristicsMin = RT_MIN(cbTransferHeuristicsCur, cbTransferHeuristicsMin);
503 cbTransferHeuristicsCur = 0;
504 }
505 else /* No interrupt expected -> add it to the former BDLE size. */
506 cbTransferHeuristicsCur += bd.u32BufSize;
507 }
508
509 /* !!! HACK ALERT BEGIN !!! */
510
511 /* Windows 10's audio driver expects a transfer all ~10.1ms (~1764 bytes), although
512 * it sets up 1792 bytes per BDLE.
513 *
514 * I currently don't have any clue why it does this that way, so try to simply detect this
515 * and alter the value so that we get a somewhat proper audio output. */
516 if (cbTransferHeuristicsMin == 1792)
517 {
518 LogRel2(("HDA: Guest seems to be Windows 10 -- setting a fixed transfer minimum size\n"));
519 cbTransferHeuristicsMin = 1764;
520 }
521
522 /* !!! HACK ALERT END !!! */
523
524 uint32_t msTransferHeuristicsMin = DrvAudioHlpBytesToMilli(cbTransferHeuristicsMin, &pCfg->Props);
525
526 /* Prevent division by zero. */
527 ASSERT_GUEST_LOGREL_MSG_STMT(msTransferHeuristicsMin,
528 ("Transfer heuristics for stream #%RU8 buggy\n", uSD),
529 msTransferHeuristicsMin = 10 /* ms, equals 100 Hz */);
530
531 uTransferHz = RT_MS_1SEC / msTransferHeuristicsMin;
532
533 LogRel2(("HDA: Stream #%RU8 needs a data transfer at least every %RU64ms (%RU32 bytes) -- transfers run at %u Hz\n",
534 uSD, msTransferHeuristicsMin, cbTransferHeuristicsMin, uTransferHz));
535 }
536 else
537 {
538 /* Use I/O timing rate instead. */
539 uTransferHz = pStreamShared->State.uTimerIoHz;
540 }
541
542 if (uTransferHz > 400) /* Anything above 400 Hz looks fishy -- tell the user. */
543 LogRel(("HDA: Calculated transfer Hz rate for stream #%RU8 looks incorrect (%u), please re-run with audio debug mode and report a bug\n",
544 uSD, uTransferHz));
545
546 pStreamShared->State.cbTransferSize =
547 (pStreamShared->State.Cfg.Props.uHz * pStreamR3->State.Mapping.cbFrameSize) / uTransferHz;
548 ASSERT_GUEST_LOGREL_MSG_STMT(pStreamShared->State.cbTransferSize,
549 ("Transfer size for stream #%RU8 is invalid\n", uSD), rc = VERR_INVALID_PARAMETER);
550 if (RT_SUCCESS(rc))
551 {
552 /*
553 * Calculate the bytes we need to transfer to / from the stream's DMA per iteration.
554 * This is bound to the device's Hz rate and thus to the (virtual) timing the device expects.
555 *
556 * As we don't do chunked transfers the moment, the chunk size equals the overall transfer size.
557 */
558 pStreamShared->State.cbTransferChunk = pStreamShared->State.cbTransferSize;
559 ASSERT_GUEST_LOGREL_MSG_STMT(pStreamShared->State.cbTransferChunk,
560 ("Transfer chunk for stream #%RU8 is invalid\n", uSD),
561 rc = VERR_INVALID_PARAMETER);
562 if (RT_SUCCESS(rc))
563 {
564 /* Make sure that the transfer chunk does not exceed the overall transfer size. */
565 AssertStmt(pStreamShared->State.cbTransferChunk <= pStreamShared->State.cbTransferSize,
566 pStreamShared->State.cbTransferChunk = pStreamShared->State.cbTransferSize);
567
568 const uint64_t uTimerFreq = PDMDevHlpTimerGetFreq(pDevIns, pStreamShared->hTimer);
569
570 const double cTicksPerHz = uTimerFreq / pStreamShared->State.uTimerIoHz;
571 double cTicksPerByte = cTicksPerHz / (double)pStreamShared->State.cbTransferChunk;
572
573 if (pStreamShared->State.uTimerIoHz < uTransferHz)
574 cTicksPerByte /= uTransferHz / pStreamShared->State.uTimerIoHz;
575 else
576 cTicksPerByte *= pStreamShared->State.uTimerIoHz / uTransferHz;
577
578 Assert(cTicksPerByte);
579
580#define HDA_ROUND_NEAREST(a_X) ((a_X) >= 0 ? (uint32_t)((a_X) + 0.5) : (uint32_t)((a_X) - 0.5)) /** @todo r=andy Do we have rounding in IPRT? */
581
582 /* Calculate the timer ticks per byte for this stream. */
583 pStreamShared->State.cTicksPerByte = HDA_ROUND_NEAREST(cTicksPerByte);
584 Assert(pStreamShared->State.cTicksPerByte);
585
586 const double cTransferTicks = pStreamShared->State.cbTransferChunk * cTicksPerByte;
587
588 /* Calculate timer ticks per transfer. */
589 pStreamShared->State.cTransferTicks = HDA_ROUND_NEAREST(cTransferTicks);
590 Assert(pStreamShared->State.cTransferTicks);
591
592#undef HDA_ROUND_NEAREST
593
594 LogRel2(("HDA: Stream #%RU8 is using %uHz I/O timer (%RU64 virtual ticks / Hz), stream Hz=%RU32, "
595 "cTicksPerByte=%RU64, cTransferTicks=%RU64 -> cbTransferChunk=%RU32 (%RU64ms), cbTransferSize=%RU32 (%RU64ms)\n",
596 uSD, pStreamShared->State.uTimerIoHz, (uint64_t)cTicksPerHz, pStreamShared->State.Cfg.Props.uHz,
597 pStreamShared->State.cTicksPerByte, pStreamShared->State.cTransferTicks,
598 pStreamShared->State.cbTransferChunk, DrvAudioHlpBytesToMilli(pStreamShared->State.cbTransferChunk, &pCfg->Props),
599 pStreamShared->State.cbTransferSize, DrvAudioHlpBytesToMilli(pStreamShared->State.cbTransferSize, &pCfg->Props)));
600
601 /* Make sure to also update the stream's DMA counter (based on its current LPIB value). */
602 hdaR3StreamSetPositionAbs(pStreamShared, pDevIns, pThis, HDA_STREAM_REG(pThis, LPIB, uSD));
603
604#ifdef LOG_ENABLED
605 hdaR3BDLEDumpAll(pDevIns, pThis, pStreamShared->u64BDLBase, pStreamShared->u16LVI + 1);
606#endif
607 }
608 }
609
610 /*
611 * Set up internal ring buffer.
612 */
613 if (RT_SUCCESS(rc))
614 {
615 /* (Re-)Allocate the stream's internal DMA buffer,
616 * based on the timing *and* PCM properties we just got above. */
617 if (pStreamR3->State.pCircBuf)
618 {
619 RTCircBufDestroy(pStreamR3->State.pCircBuf);
620 pStreamR3->State.pCircBuf = NULL;
621 }
622
623 /*
624 * The default size of our internal ring buffer depends on the transfer timing
625 * we have to reach in order to make the guest driver happy *and* on the I/O timing.
626 *
627 * We always use triple the minimum timing of both timings for safety (triple buffering),
628 * otherwise we risk running into buffer overflows.
629 */
630 const unsigned uTransferHzMin = RT_MIN(uTransferHz, pStreamShared->State.uTimerIoHz);
631
632 uint32_t cbCircBuf;
633 const uint32_t cbCircBufDefault = DrvAudioHlpMilliToBytes((RT_MS_1SEC / uTransferHzMin) * 3, &pCfg->Props);
634
635 LogRel2(("HDA: Stream #%RU8 default ring buffer size is %RU64ms (%RU32 bytes)\n",
636 uSD, DrvAudioHlpBytesToMilli(cbCircBufDefault, &pCfg->Props), cbCircBufDefault));
637
638 uint32_t cbCircBufGlobal = DrvAudioHlpMilliToBytes( hdaGetDirFromSD(uSD) == PDMAUDIODIR_IN
639 ? pThis->cbCircBufInMs : pThis->cbCircBufOutMs, &pCfg->Props);
640 if (cbCircBufGlobal) /* Anything set via CFGM? */
641 {
642
643 ASSERT_GUEST_LOGREL_MSG_STMT(DrvAudioHlpBytesIsAligned(cbCircBufGlobal, &pCfg->Props),
644 ("Ring buffer size for stream #%RU8 is misaligned (%zu), setting to default\n", uSD, cbCircBufGlobal),
645 cbCircBufGlobal = cbCircBufDefault);
646
647 LogRel2(("HDA: Stream #%RU8 is using a custom ring buffer size of %RU64ms (%RU32 bytes)\n",
648 uSD, DrvAudioHlpBytesToMilli(cbCircBufGlobal, &pCfg->Props), cbCircBufGlobal));
649
650 cbCircBuf = cbCircBufGlobal;
651 }
652 else
653 cbCircBuf = cbCircBufDefault;
654
655 ASSERT_GUEST_LOGREL_MSG_STMT(cbCircBuf,
656 ("Ring buffer size for stream #%RU8 is invalid\n", uSD),
657 rc = VERR_INVALID_PARAMETER);
658 if (RT_SUCCESS(rc))
659 rc = RTCircBufCreate(&pStreamR3->State.pCircBuf, cbCircBuf);
660 }
661
662 if (RT_FAILURE(rc))
663 LogRel(("HDA: Initializing stream #%RU8 failed with %Rrc\n", uSD, rc));
664
665 return rc;
666}
667
668/**
669 * Resets an HDA stream.
670 *
671 * @param pThis The shared HDA device state.
672 * @param pThisCC The ring-3 HDA device state.
673 * @param pStreamShared HDA stream to reset (shared).
674 * @param pStreamR3 HDA stream to reset (ring-3).
675 * @param uSD Stream descriptor (SD) number to use for this stream.
676 */
677void hdaR3StreamReset(PHDASTATE pThis, PHDASTATER3 pThisCC, PHDASTREAM pStreamShared, PHDASTREAMR3 pStreamR3, uint8_t uSD)
678{
679 AssertPtr(pThis);
680 AssertPtr(pStreamShared);
681 AssertPtr(pStreamR3);
682 Assert(uSD < HDA_MAX_STREAMS);
683 AssertMsg(!pStreamShared->State.fRunning, ("[SD%RU8] Cannot reset stream while in running state\n", uSD));
684
685 LogFunc(("[SD%RU8] Reset\n", uSD));
686
687 /*
688 * Set reset state.
689 */
690 Assert(ASMAtomicReadBool(&pStreamShared->State.fInReset) == false); /* No nested calls. */
691 ASMAtomicXchgBool(&pStreamShared->State.fInReset, true);
692
693 /*
694 * Second, initialize the registers.
695 */
696 /* See 6.2.33: Clear on reset. */
697 HDA_STREAM_REG(pThis, STS, uSD) = 0;
698 /* According to the ICH6 datasheet, 0x40000 is the default value for stream descriptor register 23:20
699 * bits are reserved for stream number 18.2.33, resets SDnCTL except SRST bit. */
700 HDA_STREAM_REG(pThis, CTL, uSD) = 0x40000 | (HDA_STREAM_REG(pThis, CTL, uSD) & HDA_SDCTL_SRST);
701 /* ICH6 defines default values (120 bytes for input and 192 bytes for output descriptors) of FIFO size. 18.2.39. */
702 HDA_STREAM_REG(pThis, FIFOS, uSD) = hdaGetDirFromSD(uSD) == PDMAUDIODIR_IN ? HDA_SDIFIFO_120B : HDA_SDOFIFO_192B;
703 /* See 18.2.38: Always defaults to 0x4 (32 bytes). */
704 HDA_STREAM_REG(pThis, FIFOW, uSD) = HDA_SDFIFOW_32B;
705 HDA_STREAM_REG(pThis, LPIB, uSD) = 0;
706 HDA_STREAM_REG(pThis, CBL, uSD) = 0;
707 HDA_STREAM_REG(pThis, LVI, uSD) = 0;
708 HDA_STREAM_REG(pThis, FMT, uSD) = 0;
709 HDA_STREAM_REG(pThis, BDPU, uSD) = 0;
710 HDA_STREAM_REG(pThis, BDPL, uSD) = 0;
711
712#ifdef HDA_USE_DMA_ACCESS_HANDLER
713 hdaR3StreamUnregisterDMAHandlers(pThis, pStream);
714#endif
715
716 /* Assign the default mixer sink to the stream. */
717 pStreamR3->pMixSink = hdaR3GetDefaultSink(pThisCC, uSD);
718
719 /* Reset position adjustment counter. */
720 pStreamShared->State.cfPosAdjustLeft = pStreamShared->State.cfPosAdjustDefault;
721
722 /* Reset transfer stuff. */
723 pStreamShared->State.cTransferPendingInterrupts = 0;
724 pStreamShared->State.tsTransferLast = 0;
725 pStreamShared->State.tsTransferNext = 0;
726
727 /* Initialize timestamps. */
728 pStreamShared->State.tsLastTransferNs = 0;
729 pStreamShared->State.tsLastReadNs = 0;
730
731 RT_ZERO(pStreamShared->State.BDLE);
732 pStreamShared->State.uCurBDLE = 0;
733
734 if (pStreamR3->State.pCircBuf)
735 RTCircBufReset(pStreamR3->State.pCircBuf);
736
737 /* Reset the stream's period. */
738 hdaR3StreamPeriodReset(&pStreamShared->State.Period);
739
740#ifdef DEBUG
741 pStreamR3->Dbg.cReadsTotal = 0;
742 pStreamR3->Dbg.cbReadTotal = 0;
743 pStreamR3->Dbg.tsLastReadNs = 0;
744 pStreamR3->Dbg.cWritesTotal = 0;
745 pStreamR3->Dbg.cbWrittenTotal = 0;
746 pStreamR3->Dbg.cWritesHz = 0;
747 pStreamR3->Dbg.cbWrittenHz = 0;
748 pStreamR3->Dbg.tsWriteSlotBegin = 0;
749#endif
750
751 /* Report that we're done resetting this stream. */
752 HDA_STREAM_REG(pThis, CTL, uSD) = 0;
753
754 LogFunc(("[SD%RU8] Reset\n", uSD));
755
756 /* Exit reset mode. */
757 ASMAtomicXchgBool(&pStreamShared->State.fInReset, false);
758}
759
760/**
761 * Enables or disables an HDA audio stream.
762 *
763 * @returns IPRT status code.
764 * @param pStreamShared HDA stream to enable or disable - shared bits.
765 * @param pStreamR3 HDA stream to enable or disable - ring-3 bits.
766 * @param fEnable Whether to enable or disble the stream.
767 */
768int hdaR3StreamEnable(PHDASTREAM pStreamShared, PHDASTREAMR3 pStreamR3, bool fEnable)
769{
770 AssertPtr(pStreamR3);
771 AssertPtr(pStreamShared);
772
773 LogFunc(("[SD%RU8] fEnable=%RTbool, pMixSink=%p\n", pStreamShared->u8SD, fEnable, pStreamR3->pMixSink));
774
775 int rc = VINF_SUCCESS;
776
777 AUDMIXSINKCMD enmCmd = fEnable
778 ? AUDMIXSINKCMD_ENABLE : AUDMIXSINKCMD_DISABLE;
779
780 /* First, enable or disable the stream and the stream's sink, if any. */
781 if ( pStreamR3->pMixSink
782 && pStreamR3->pMixSink->pMixSink)
783 rc = AudioMixerSinkCtl(pStreamR3->pMixSink->pMixSink, enmCmd);
784
785 if ( RT_SUCCESS(rc)
786 && fEnable
787 && pStreamR3->Dbg.Runtime.fEnabled)
788 {
789 Assert(DrvAudioHlpPCMPropsAreValid(&pStreamShared->State.Cfg.Props));
790
791 if (fEnable)
792 {
793 if (!DrvAudioHlpFileIsOpen(pStreamR3->Dbg.Runtime.pFileStream))
794 {
795 int rc2 = DrvAudioHlpFileOpen(pStreamR3->Dbg.Runtime.pFileStream, PDMAUDIOFILE_DEFAULT_OPEN_FLAGS,
796 &pStreamShared->State.Cfg.Props);
797 AssertRC(rc2);
798 }
799
800 if (!DrvAudioHlpFileIsOpen(pStreamR3->Dbg.Runtime.pFileDMARaw))
801 {
802 int rc2 = DrvAudioHlpFileOpen(pStreamR3->Dbg.Runtime.pFileDMARaw, PDMAUDIOFILE_DEFAULT_OPEN_FLAGS,
803 &pStreamShared->State.Cfg.Props);
804 AssertRC(rc2);
805 }
806
807 if (!DrvAudioHlpFileIsOpen(pStreamR3->Dbg.Runtime.pFileDMAMapped))
808 {
809 int rc2 = DrvAudioHlpFileOpen(pStreamR3->Dbg.Runtime.pFileDMAMapped, PDMAUDIOFILE_DEFAULT_OPEN_FLAGS,
810 &pStreamShared->State.Cfg.Props);
811 AssertRC(rc2);
812 }
813 }
814 }
815
816 if (RT_SUCCESS(rc))
817 {
818 pStreamShared->State.fRunning = fEnable;
819 }
820
821 LogFunc(("[SD%RU8] rc=%Rrc\n", pStreamShared->u8SD, rc));
822 return rc;
823}
824
825#if 0 /* Not used atm. */
826static uint32_t hdaR3StreamGetPosition(PHDASTATE pThis, PHDASTREAM pStreamShared)
827{
828 return HDA_STREAM_REG(pThis, LPIB, pStreamShared->u8SD);
829}
830#endif
831
832/**
833 * Updates an HDA stream's current read or write buffer position (depending on the stream type) by
834 * setting its associated LPIB register and DMA position buffer (if enabled) to an absolute value.
835 *
836 * @param pStreamShared HDA stream to update read / write position for (shared).
837 * @param pDevIns The device instance.
838 * @param pThis The shared HDA device state.
839 * @param uLPIB Absolute position (in bytes) to set current read / write position to.
840 */
841static void hdaR3StreamSetPositionAbs(PHDASTREAM pStreamShared, PPDMDEVINS pDevIns, PHDASTATE pThis, uint32_t uLPIB)
842{
843 AssertPtrReturnVoid(pStreamShared);
844 AssertReturnVoid (uLPIB <= pStreamShared->u32CBL); /* Make sure that we don't go out-of-bounds. */
845
846 Log3Func(("[SD%RU8] LPIB=%RU32 (DMA Position Buffer Enabled: %RTbool)\n", pStreamShared->u8SD, uLPIB, pThis->fDMAPosition));
847
848 /* Update LPIB in any case. */
849 HDA_STREAM_REG(pThis, LPIB, pStreamShared->u8SD) = uLPIB;
850
851 /* Do we need to tell the current DMA position? */
852 if (pThis->fDMAPosition)
853 {
854 int rc2 = PDMDevHlpPCIPhysWrite(pDevIns,
855 pThis->u64DPBase + (pStreamShared->u8SD * 2 * sizeof(uint32_t)),
856 (void *)&uLPIB, sizeof(uint32_t));
857 AssertRC(rc2);
858 }
859}
860
861/**
862 * Updates an HDA stream's current read or write buffer position (depending on the stream type) by
863 * adding a value to its associated LPIB register and DMA position buffer (if enabled).
864 *
865 * @note Handles automatic CBL wrap-around.
866 *
867 * @param pStreamShared HDA stream to update read / write position for (shared).
868 * @param pDevIns The device instance.
869 * @param pThis The shared HDA device state.
870 * @param uToAdd Position (in bytes) to add to the current read / write position.
871 */
872void hdaR3StreamSetPositionAdd(PHDASTREAM pStreamShared, PPDMDEVINS pDevIns, PHDASTATE pThis, uint32_t uToAdd)
873{
874 if (!uToAdd) /* No need to update anything if 0. */
875 return;
876
877 hdaR3StreamSetPositionAbs(pStreamShared, pDevIns, pThis,
878 (HDA_STREAM_REG(pThis, LPIB, pStreamShared->u8SD) + uToAdd) % pStreamShared->u32CBL);
879}
880
881/**
882 * Retrieves the available size of (buffered) audio data (in bytes) of a given HDA stream.
883 *
884 * @returns Available data (in bytes).
885 * @param pStreamR3 HDA stream to retrieve size for (ring-3).
886 */
887static uint32_t hdaR3StreamGetUsed(PHDASTREAMR3 pStreamR3)
888{
889 AssertPtrReturn(pStreamR3, 0);
890
891 if (pStreamR3->State.pCircBuf)
892 return (uint32_t)RTCircBufUsed(pStreamR3->State.pCircBuf);
893 return 0;
894}
895
896/**
897 * Retrieves the free size of audio data (in bytes) of a given HDA stream.
898 *
899 * @returns Free data (in bytes).
900 * @param pStreamR3 HDA stream to retrieve size for (ring-3).
901 */
902static uint32_t hdaR3StreamGetFree(PHDASTREAMR3 pStreamR3)
903{
904 AssertPtrReturn(pStreamR3, 0);
905
906 if (pStreamR3->State.pCircBuf)
907 return (uint32_t)RTCircBufFree(pStreamR3->State.pCircBuf);
908 return 0;
909}
910
911/**
912 * Returns whether a next transfer for a given stream is scheduled or not.
913 *
914 * This takes pending stream interrupts into account as well as the next scheduled
915 * transfer timestamp.
916 *
917 * @returns True if a next transfer is scheduled, false if not.
918 * @param pStreamShared HDA stream to retrieve schedule status for (shared).
919 * @param tsNow The current time.
920 */
921bool hdaR3StreamTransferIsScheduled(PHDASTREAM pStreamShared, uint64_t tsNow)
922{
923 if (pStreamShared)
924 {
925 if (pStreamShared->State.fRunning)
926 {
927 if (pStreamShared->State.cTransferPendingInterrupts)
928 {
929 Log3Func(("[SD%RU8] Scheduled (%RU8 IRQs pending)\n", pStreamShared->u8SD, pStreamShared->State.cTransferPendingInterrupts));
930 return true;
931 }
932
933 if (pStreamShared->State.tsTransferNext > tsNow)
934 {
935 Log3Func(("[SD%RU8] Scheduled in %RU64\n", pStreamShared->u8SD, pStreamShared->State.tsTransferNext - tsNow));
936 return true;
937 }
938 }
939 }
940 return false;
941}
942
943/**
944 * Returns the (virtual) clock timestamp of the next transfer, if any.
945 * Will return 0 if no new transfer is scheduled.
946 *
947 * @returns The (virtual) clock timestamp of the next transfer.
948 * @param pStreamShared HDA stream to retrieve timestamp for (shared).
949 */
950uint64_t hdaR3StreamTransferGetNext(PHDASTREAM pStreamShared)
951{
952 return pStreamShared->State.tsTransferNext;
953}
954
955/**
956 * Writes audio data from a mixer sink into an HDA stream's DMA buffer.
957 *
958 * @returns IPRT status code.
959 * @param pStreamR3 HDA stream to write to (ring-3).
960 * @param pvBuf Data buffer to write.
961 * If NULL, silence will be written.
962 * @param cbBuf Number of bytes of data buffer to write.
963 * @param pcbWritten Number of bytes written. Optional.
964 */
965static int hdaR3StreamWrite(PHDASTREAMR3 pStreamR3, const void *pvBuf, uint32_t cbBuf, uint32_t *pcbWritten)
966{
967 Assert(cbBuf);
968
969 PRTCIRCBUF pCircBuf = pStreamR3->State.pCircBuf;
970 AssertPtr(pCircBuf);
971
972 uint32_t cbWrittenTotal = 0;
973 uint32_t cbLeft = RT_MIN(cbBuf, (uint32_t)RTCircBufFree(pCircBuf));
974
975 while (cbLeft)
976 {
977 void *pvDst;
978 size_t cbDst;
979 RTCircBufAcquireWriteBlock(pCircBuf, cbLeft, &pvDst, &cbDst);
980
981 if (cbDst)
982 {
983 if (pvBuf)
984 memcpy(pvDst, (uint8_t *)pvBuf + cbWrittenTotal, cbDst);
985 else /* Send silence. */
986 {
987 /** @todo Use a sample spec for "silence" based on the PCM parameters.
988 * For now we ASSUME that silence equals NULLing the data. */
989 RT_BZERO(pvDst, cbDst);
990 }
991
992 if (RT_LIKELY(!pStreamR3->Dbg.Runtime.fEnabled))
993 { /* likely */ }
994 else
995 DrvAudioHlpFileWrite(pStreamR3->Dbg.Runtime.pFileStream, pvDst, cbDst, 0 /* fFlags */);
996 }
997
998 RTCircBufReleaseWriteBlock(pCircBuf, cbDst);
999
1000 Assert(cbLeft >= (uint32_t)cbDst);
1001 cbLeft -= (uint32_t)cbDst;
1002 cbWrittenTotal += (uint32_t)cbDst;
1003 }
1004
1005 Log3Func(("cbWrittenTotal=%RU32\n", cbWrittenTotal));
1006
1007 if (pcbWritten)
1008 *pcbWritten = cbWrittenTotal;
1009
1010 return VINF_SUCCESS;
1011}
1012
1013
1014/**
1015 * Reads audio data from an HDA stream's DMA buffer and writes into a specified mixer sink.
1016 *
1017 * @returns IPRT status code.
1018 * @param pStreamR3 HDA stream to read audio data from (ring-3).
1019 * @param cbToRead Number of bytes to read.
1020 * @param pcbRead Number of bytes read. Optional.
1021 */
1022static int hdaR3StreamRead(PHDASTREAMR3 pStreamR3, uint32_t cbToRead, uint32_t *pcbRead)
1023{
1024 Assert(cbToRead);
1025
1026 PHDAMIXERSINK pSink = pStreamR3->pMixSink;
1027 AssertMsgReturnStmt(pSink, ("[SD%RU8] Can't read from a stream with no sink attached\n", pStreamR3->u8SD),
1028 if (pcbRead) *pcbRead = 0,
1029 VINF_SUCCESS);
1030
1031 PRTCIRCBUF pCircBuf = pStreamR3->State.pCircBuf;
1032 AssertPtr(pCircBuf);
1033
1034 int rc = VINF_SUCCESS;
1035
1036 uint32_t cbReadTotal = 0;
1037 uint32_t cbLeft = RT_MIN(cbToRead, (uint32_t)RTCircBufUsed(pCircBuf));
1038
1039 while (cbLeft)
1040 {
1041 void *pvSrc;
1042 size_t cbSrc;
1043
1044 uint32_t cbWritten = 0;
1045
1046 RTCircBufAcquireReadBlock(pCircBuf, cbLeft, &pvSrc, &cbSrc);
1047
1048 if (cbSrc)
1049 {
1050 if (pStreamR3->Dbg.Runtime.fEnabled)
1051 DrvAudioHlpFileWrite(pStreamR3->Dbg.Runtime.pFileStream, pvSrc, cbSrc, 0 /* fFlags */);
1052
1053 rc = AudioMixerSinkWrite(pSink->pMixSink, AUDMIXOP_COPY, pvSrc, (uint32_t)cbSrc, &cbWritten);
1054 AssertRC(rc);
1055
1056 Assert(cbSrc >= cbWritten);
1057 Log2Func(("[SD%RU8] %RU32/%zu bytes read\n", pStreamR3->u8SD, cbWritten, cbSrc));
1058 }
1059
1060 RTCircBufReleaseReadBlock(pCircBuf, cbWritten);
1061
1062 if ( !cbWritten /* Nothing written? */
1063 || RT_FAILURE(rc))
1064 break;
1065
1066 Assert(cbLeft >= cbWritten);
1067 cbLeft -= cbWritten;
1068
1069 cbReadTotal += cbWritten;
1070 }
1071
1072 if (pcbRead)
1073 *pcbRead = cbReadTotal;
1074
1075 return rc;
1076}
1077
1078/**
1079 * Transfers data of an HDA stream according to its usage (input / output).
1080 *
1081 * For an SDO (output) stream this means reading DMA data from the device to
1082 * the HDA stream's internal FIFO buffer.
1083 *
1084 * For an SDI (input) stream this is reading audio data from the HDA stream's
1085 * internal FIFO buffer and writing it as DMA data to the device.
1086 *
1087 * @returns IPRT status code.
1088 * @param pDevIns The device instance.
1089 * @param pThis The shared HDA device state.
1090 * @param pThisCC The ring-3 HDA device state.
1091 * @param pStreamShared HDA stream to update (shared).
1092 * @param pStreamR3 HDA stream to update (ring-3).
1093 * @param cbToProcessMax How much data (in bytes) to process as maximum.
1094 */
1095static int hdaR3StreamTransfer(PPDMDEVINS pDevIns, PHDASTATE pThis, PHDASTATER3 pThisCC, PHDASTREAM pStreamShared,
1096 PHDASTREAMR3 pStreamR3, uint32_t cbToProcessMax)
1097{
1098 LogFlowFuncEnter();
1099
1100 uint8_t const uSD = pStreamShared->u8SD;
1101 hdaStreamLock(pStreamShared);
1102
1103 PHDASTREAMPERIOD pPeriod = &pStreamShared->State.Period;
1104
1105 bool fProceed = true;
1106
1107 /* Stream not running (anymore)? */
1108 if (!pStreamShared->State.fRunning)
1109 {
1110 Log3Func(("[SD%RU8] Not running, skipping transfer\n", uSD));
1111 fProceed = false;
1112 }
1113
1114 else if (HDA_STREAM_REG(pThis, STS, uSD) & HDA_SDSTS_BCIS)
1115 {
1116 Log3Func(("[SD%RU8] BCIS bit set, skipping transfer\n", uSD));
1117#ifdef HDA_STRICT
1118 /* Timing emulation bug or guest is misbehaving -- let me know. */
1119 AssertMsgFailed(("BCIS bit for stream #%RU8 still set when it shouldn't\n", uSD));
1120#endif
1121 fProceed = false;
1122 }
1123
1124 if (!fProceed)
1125 {
1126 hdaStreamUnlock(pStreamShared);
1127 return VINF_SUCCESS;
1128 }
1129
1130 /* Update real-time timestamp. */
1131 const uint64_t tsNowNs = RTTimeNanoTS();
1132#ifdef LOG_ENABLED
1133 const uint64_t tsDeltaMs = (tsNowNs - pStreamShared->State.tsLastTransferNs) / RT_NS_1MS;
1134 Log3Func(("[SD%RU8] tsDeltaNs=%RU64ms\n", uSD, tsDeltaMs));
1135#endif
1136 pStreamShared->State.tsLastTransferNs = tsNowNs;
1137
1138 const uint64_t tsNow = PDMDevHlpTimerGet(pDevIns, pStreamShared->hTimer);
1139
1140 if (!pStreamShared->State.tsTransferLast)
1141 pStreamShared->State.tsTransferLast = tsNow;
1142
1143 pStreamShared->State.tsTransferLast = tsNow;
1144
1145 /* Register sanity checks. */
1146 Assert(uSD < HDA_MAX_STREAMS);
1147 Assert(pStreamShared->u64BDLBase);
1148 Assert(pStreamShared->u32CBL);
1149 Assert(pStreamShared->u8FIFOS);
1150
1151 /* State sanity checks. */
1152 Assert(ASMAtomicReadBool(&pStreamShared->State.fInReset) == false);
1153 Assert(ASMAtomicReadBool(&pStreamShared->State.fRunning));
1154
1155 /* Transfer sanity checks. */
1156 Assert(pStreamShared->State.cbTransferSize);
1157 Assert(pStreamShared->State.cbTransferChunk <= pStreamShared->State.cbTransferSize);
1158
1159 int rc = VINF_SUCCESS;
1160
1161 /* Fetch first / next BDL entry. */
1162 PHDABDLE pBDLE = &pStreamShared->State.BDLE;
1163 if (hdaR3BDLEIsComplete(pBDLE))
1164 {
1165 rc = hdaR3BDLEFetch(pDevIns, pBDLE, pStreamShared->u64BDLBase, pStreamShared->State.uCurBDLE);
1166 AssertRC(rc);
1167 }
1168
1169 uint32_t cbToProcess = RT_MIN(pStreamShared->State.cbTransferSize, pStreamShared->State.cbTransferChunk);
1170
1171 Assert(cbToProcess); /* Nothing to process when there should be data. Accounting bug? */
1172
1173 /* More data to process than maximum allowed? */
1174#ifdef HDA_STRICT
1175 AssertStmt(cbToProcess <= cbToProcessMax, cbToProcess = cbToProcessMax);
1176#else
1177 if (cbToProcess > cbToProcessMax)
1178 cbToProcess = cbToProcessMax;
1179#endif
1180
1181 uint32_t cbProcessed = 0;
1182 uint32_t cbLeft = cbToProcess;
1183
1184 /* Whether an interrupt has been sent (asserted) for this transfer period already or not.
1185 *
1186 * Note: Windows 10 relies on this, e.g. sending more than one interrupt per transfer period
1187 * confuses the Windows' audio driver and will screw up the audio data. So only send
1188 * one interrupt per transfer period.
1189 */
1190 bool fInterruptSent = false;
1191
1192 /* Set the FIFORDY bit on the stream while doing the transfer. */
1193 HDA_STREAM_REG(pThis, STS, uSD) |= HDA_SDSTS_FIFORDY;
1194
1195 while (cbLeft)
1196 {
1197 /* Limit the chunk to the stream's FIFO size and what's left to process. */
1198 uint32_t cbChunk = RT_MIN(cbLeft, pStreamShared->u8FIFOS);
1199
1200 /* Limit the chunk to the remaining data of the current BDLE. */
1201 cbChunk = RT_MIN(cbChunk, pBDLE->Desc.u32BufSize - pBDLE->State.u32BufOff);
1202
1203 /* If there are position adjustment frames left to be processed,
1204 * make sure that we process them first as a whole. */
1205 if (pStreamShared->State.cfPosAdjustLeft)
1206 cbChunk = RT_MIN(cbChunk, uint32_t(pStreamShared->State.cfPosAdjustLeft * pStreamR3->State.Mapping.cbFrameSize));
1207
1208 if (!cbChunk)
1209 break;
1210
1211 uint32_t cbDMA = 0;
1212 PRTCIRCBUF pCircBuf = pStreamR3->State.pCircBuf;
1213 uint8_t *pabFIFO = pStreamShared->abFIFO;
1214
1215 if (hdaGetDirFromSD(uSD) == PDMAUDIODIR_IN) /* Input (SDI). */
1216 {
1217 STAM_PROFILE_START(&pThis->StatIn, a);
1218
1219 uint32_t cbDMAWritten = 0;
1220 uint32_t cbDMAToWrite = cbChunk;
1221
1222 /** @todo Do we need interleaving streams support here as well?
1223 * Never saw anything else besides mono/stereo mics (yet). */
1224 while (cbDMAToWrite)
1225 {
1226 void *pvBuf; size_t cbBuf;
1227 RTCircBufAcquireReadBlock(pCircBuf, cbDMAToWrite, &pvBuf, &cbBuf);
1228
1229 if ( !cbBuf
1230 && !RTCircBufUsed(pCircBuf))
1231 break;
1232
1233 memcpy(pabFIFO + cbDMAWritten, pvBuf, cbBuf);
1234
1235 RTCircBufReleaseReadBlock(pCircBuf, cbBuf);
1236
1237 Assert(cbDMAToWrite >= cbBuf);
1238 cbDMAToWrite -= (uint32_t)cbBuf;
1239 cbDMAWritten += (uint32_t)cbBuf;
1240 Assert(cbDMAWritten <= cbChunk);
1241 }
1242
1243 if (cbDMAToWrite)
1244 {
1245 LogRel2(("HDA: FIFO underflow for stream #%RU8 (%RU32 bytes outstanding)\n", uSD, cbDMAToWrite));
1246
1247 Assert(cbChunk == cbDMAWritten + cbDMAToWrite);
1248 memset((uint8_t *)pabFIFO + cbDMAWritten, 0, cbDMAToWrite);
1249 cbDMAWritten = cbChunk;
1250 }
1251
1252 rc = hdaR3DMAWrite(pDevIns, pThis, pStreamShared, pStreamR3, pabFIFO, cbDMAWritten, &cbDMA /* pcbWritten */);
1253 if (RT_FAILURE(rc))
1254 LogRel(("HDA: Writing to stream #%RU8 DMA failed with %Rrc\n", uSD, rc));
1255
1256 STAM_PROFILE_STOP(&pThis->StatIn, a);
1257 }
1258 else if (hdaGetDirFromSD(uSD) == PDMAUDIODIR_OUT) /* Output (SDO). */
1259 {
1260 STAM_PROFILE_START(&pThis->StatOut, a);
1261
1262 rc = hdaR3DMARead(pDevIns, pThis, pStreamShared, pStreamR3, pabFIFO, cbChunk, &cbDMA /* pcbRead */);
1263 if (RT_SUCCESS(rc))
1264 {
1265 const uint32_t cbFree = (uint32_t)RTCircBufFree(pCircBuf);
1266
1267 /*
1268 * Most guests don't use different stream frame sizes than
1269 * the default one, so save a bit of CPU time and don't go into
1270 * the frame extraction code below.
1271 *
1272 * Only macOS guests need the frame extraction branch below at the moment AFAIK.
1273 */
1274 if (pStreamR3->State.Mapping.cbFrameSize == HDA_FRAME_SIZE_DEFAULT)
1275 {
1276 uint32_t cbDMARead = 0;
1277 uint32_t cbDMALeft = RT_MIN(cbDMA, cbFree);
1278
1279 while (cbDMALeft)
1280 {
1281 void *pvBuf; size_t cbBuf;
1282 RTCircBufAcquireWriteBlock(pCircBuf, cbDMALeft, &pvBuf, &cbBuf);
1283
1284 if (cbBuf)
1285 {
1286 memcpy(pvBuf, pabFIFO + cbDMARead, cbBuf);
1287 cbDMARead += (uint32_t)cbBuf;
1288 cbDMALeft -= (uint32_t)cbBuf;
1289 }
1290
1291 RTCircBufReleaseWriteBlock(pCircBuf, cbBuf);
1292 }
1293 }
1294 else
1295 {
1296 /*
1297 * The following code extracts the required audio stream (channel) data
1298 * of non-interleaved *and* interleaved audio streams.
1299 *
1300 * We by default only support 2 channels with 16-bit samples (HDA_FRAME_SIZE),
1301 * but an HDA audio stream can have interleaved audio data of multiple audio
1302 * channels in such a single stream ("AA,AA,AA vs. AA,BB,AA,BB").
1303 *
1304 * So take this into account by just handling the first channel in such a stream ("A")
1305 * and just discard the other channel's data.
1306 *
1307 * I know, the following code is horribly slow, but seems to work for now.
1308 */
1309 /** @todo Optimize channel data extraction! Use some SSE(3) / intrinsics? */
1310 for (unsigned m = 0; m < pStreamR3->State.Mapping.cMappings; m++)
1311 {
1312 const uint32_t cbFrame = pStreamR3->State.Mapping.cbFrameSize;
1313
1314 Assert(cbFree >= cbDMA);
1315
1316 PPDMAUDIOSTREAMMAP pMap = &pStreamR3->State.Mapping.paMappings[m];
1317 AssertPtr(pMap);
1318
1319 Log3Func(("Mapping #%u: Start (cbDMA=%RU32, cbFrame=%RU32, offNext=%RU32)\n",
1320 m, cbDMA, cbFrame, pMap->offNext));
1321
1322
1323 /* Skip the current DMA chunk if the chunk is smaller than what the current stream mapping needs to read
1324 * the next associated frame (pointed to at pMap->cbOff).
1325 *
1326 * This can happen if the guest did not come up with enough data within a certain time period, especially
1327 * when using multi-channel speaker (> 2 channels [stereo]) setups. */
1328 if (pMap->offNext > cbChunk)
1329 {
1330 Log2Func(("Mapping #%u: Skipped (cbChunk=%RU32, cbMapOff=%RU32)\n", m, cbChunk, pMap->offNext));
1331 continue;
1332 }
1333
1334 uint8_t *pbSrcBuf = pabFIFO;
1335 size_t cbSrcOff = pMap->offNext;
1336
1337 for (unsigned i = 0; i < cbDMA / cbFrame; i++)
1338 {
1339 void *pvDstBuf; size_t cbDstBuf;
1340 RTCircBufAcquireWriteBlock(pCircBuf, pMap->cbStep, &pvDstBuf, &cbDstBuf);
1341
1342 Assert(cbDstBuf >= pMap->cbStep);
1343
1344 if (cbDstBuf)
1345 {
1346 Log3Func(("Mapping #%u: Frame #%02u: cbStep=%u, offFirst=%u, offNext=%u, cbDstBuf=%u, cbSrcOff=%u\n",
1347 m, i, pMap->cbStep, pMap->offFirst, pMap->offNext, cbDstBuf, cbSrcOff));
1348
1349 memcpy(pvDstBuf, pbSrcBuf + cbSrcOff, cbDstBuf);
1350
1351#if 0 /* Too slow, even for release builds, so disabled it. */
1352 if (pStreamR3->Dbg.Runtime.fEnabled)
1353 DrvAudioHlpFileWrite(pStreamR3->Dbg.Runtime.pFileDMAMapped, pvDstBuf, cbDstBuf,
1354 0 /* fFlags */);
1355#endif
1356 Assert(cbSrcOff <= cbDMA);
1357 if (cbSrcOff + cbFrame + pMap->offFirst<= cbDMA)
1358 cbSrcOff += cbFrame + pMap->offFirst;
1359
1360 Log3Func(("Mapping #%u: Frame #%02u: -> cbSrcOff=%zu\n", m, i, cbSrcOff));
1361 }
1362
1363 RTCircBufReleaseWriteBlock(pCircBuf, cbDstBuf);
1364 }
1365
1366 Log3Func(("Mapping #%u: End cbSize=%u, cbDMA=%RU32, cbSrcOff=%zu\n",
1367 m, pMap->cbStep, cbDMA, cbSrcOff));
1368
1369 Assert(cbSrcOff <= cbDMA);
1370
1371 const uint32_t cbSrcLeft = cbDMA - (uint32_t)cbSrcOff;
1372 if (cbSrcLeft)
1373 {
1374 Log3Func(("Mapping #%u: cbSrcLeft=%RU32\n", m, cbSrcLeft));
1375
1376 if (cbSrcLeft >= pMap->cbStep)
1377 {
1378 void *pvDstBuf; size_t cbDstBuf;
1379 RTCircBufAcquireWriteBlock(pCircBuf, pMap->cbStep, &pvDstBuf, &cbDstBuf);
1380
1381 Assert(cbDstBuf >= pMap->cbStep);
1382
1383 if (cbDstBuf)
1384 {
1385 memcpy(pvDstBuf, pbSrcBuf + cbSrcOff, cbDstBuf);
1386 }
1387
1388 RTCircBufReleaseWriteBlock(pCircBuf, cbDstBuf);
1389 }
1390
1391 Assert(pMap->cbFrame >= cbSrcLeft);
1392 pMap->offNext = pMap->cbFrame - cbSrcLeft;
1393 }
1394 else
1395 pMap->offNext = 0;
1396
1397 Log3Func(("Mapping #%u finish (cbSrcOff=%zu, offNext=%zu)\n", m, cbSrcOff, pMap->offNext));
1398 }
1399 }
1400 }
1401 else
1402 LogRel(("HDA: Reading from stream #%RU8 DMA failed with %Rrc\n", uSD, rc));
1403
1404 STAM_PROFILE_STOP(&pThis->StatOut, a);
1405 }
1406
1407 else /** @todo Handle duplex streams? */
1408 AssertFailed();
1409
1410 if (cbDMA)
1411 {
1412 /* We always increment the position of DMA buffer counter because we're always reading
1413 * into an intermediate DMA buffer. */
1414 pBDLE->State.u32BufOff += (uint32_t)cbDMA;
1415 Assert(pBDLE->State.u32BufOff <= pBDLE->Desc.u32BufSize);
1416
1417 /* Are we done doing the position adjustment?
1418 * Only then do the transfer accounting .*/
1419 if (pStreamShared->State.cfPosAdjustLeft == 0)
1420 {
1421 Assert(cbLeft >= cbDMA);
1422 cbLeft -= cbDMA;
1423
1424 cbProcessed += cbDMA;
1425 }
1426
1427 Log3Func(("[SD%RU8] cbDMA=%RU32 -> %R[bdle]\n", uSD, cbDMA, pBDLE));
1428 }
1429
1430 if (hdaR3BDLEIsComplete(pBDLE))
1431 {
1432 Log3Func(("[SD%RU8] Completed %R[bdle]\n", uSD, pBDLE));
1433
1434 /* Make sure to also update the wall clock when a BDLE is complete.
1435 * Needed for Windows 10 guests. */
1436 hdaR3WalClkSet(pThis, pThisCC,
1437 hdaWalClkGetCurrent(pThis)
1438 + hdaR3StreamPeriodFramesToWalClk(pPeriod,
1439 pBDLE->Desc.u32BufSize
1440 / pStreamR3->State.Mapping.cbFrameSize),
1441 false /* fForce */);
1442
1443 /*
1444 * Update the stream's current position.
1445 * Do this as accurate and close to the actual data transfer as possible.
1446 * All guetsts rely on this, depending on the mechanism they use (LPIB register or DMA counters).
1447 *
1448 * Note for Windows 10: The OS' driver is *very* picky about *when* the (DMA) positions get updated!
1449 * Not doing this at the right time will result in ugly sound crackles!
1450 */
1451 hdaR3StreamSetPositionAdd(pStreamShared, pDevIns, pThis, pBDLE->Desc.u32BufSize);
1452
1453 /* Does the current BDLE require an interrupt to be sent? */
1454 if ( hdaR3BDLENeedsInterrupt(pBDLE)
1455 /* Are we done doing the position adjustment?
1456 * It can happen that a BDLE which is handled while doing the
1457 * position adjustment requires an interrupt on completion (IOC) being set.
1458 *
1459 * In such a case we need to skip such an interrupt and just move on. */
1460 && pStreamShared->State.cfPosAdjustLeft == 0)
1461 {
1462 /* If the IOCE ("Interrupt On Completion Enable") bit of the SDCTL register is set
1463 * we need to generate an interrupt.
1464 */
1465 if (HDA_STREAM_REG(pThis, CTL, uSD) & HDA_SDCTL_IOCE)
1466 {
1467 /* Assert the interrupt before actually fetching the next BDLE below. */
1468 if (!fInterruptSent)
1469 {
1470 pStreamShared->State.cTransferPendingInterrupts = 1;
1471
1472 AssertMsg(pStreamShared->State.cTransferPendingInterrupts <= 32,
1473 ("Too many pending interrupts (%RU8) for stream #%RU8\n",
1474 pStreamShared->State.cTransferPendingInterrupts, uSD));
1475
1476 Log3Func(("[SD%RU8] Scheduling interrupt (now %RU8 total)\n", uSD, pStreamShared->State.cTransferPendingInterrupts));
1477
1478 /*
1479 * Set the stream's BCIS bit.
1480 *
1481 * Note: This only must be done if the whole period is complete, and not if only
1482 * one specific BDL entry is complete (if it has the IOC bit set).
1483 *
1484 * This will otherwise confuses the guest when it 1) deasserts the interrupt,
1485 * 2) reads SDSTS (with BCIS set) and then 3) too early reads a (wrong) WALCLK value.
1486 *
1487 * snd_hda_intel on Linux will tell.
1488 */
1489 HDA_STREAM_REG(pThis, STS, uSD) |= HDA_SDSTS_BCIS;
1490
1491 /* Trigger an interrupt first and let hdaRegWriteSDSTS() deal with
1492 * ending / beginning a period. */
1493 HDA_PROCESS_INTERRUPT(pDevIns, pThis);
1494
1495 fInterruptSent = true;
1496 }
1497 }
1498 }
1499
1500 if (pStreamShared->State.uCurBDLE == pStreamShared->u16LVI)
1501 {
1502 pStreamShared->State.uCurBDLE = 0;
1503 }
1504 else
1505 pStreamShared->State.uCurBDLE++;
1506
1507 /* Fetch the next BDLE entry. */
1508 hdaR3BDLEFetch(pDevIns, pBDLE, pStreamShared->u64BDLBase, pStreamShared->State.uCurBDLE);
1509 }
1510
1511 /* Do the position adjustment accounting. */
1512 pStreamShared->State.cfPosAdjustLeft -=
1513 RT_MIN(pStreamShared->State.cfPosAdjustLeft, cbDMA / pStreamR3->State.Mapping.cbFrameSize);
1514
1515 if (RT_FAILURE(rc))
1516 break;
1517 }
1518
1519 /* Remove the FIFORDY bit again. */
1520 HDA_STREAM_REG(pThis, STS, uSD) &= ~HDA_SDSTS_FIFORDY;
1521
1522 /* Sanity. */
1523 Assert(cbProcessed == cbToProcess);
1524 Assert(cbLeft == 0);
1525
1526 /* Only do the data accounting if we don't have to do any position
1527 * adjustment anymore. */
1528 if (pStreamShared->State.cfPosAdjustLeft == 0)
1529 {
1530 hdaR3StreamPeriodInc(pPeriod, RT_MIN(cbProcessed / pStreamR3->State.Mapping.cbFrameSize,
1531 hdaR3StreamPeriodGetRemainingFrames(pPeriod)));
1532 }
1533
1534 const bool fTransferComplete = cbLeft == 0;
1535 if (fTransferComplete)
1536 {
1537 /*
1538 * Try updating the wall clock.
1539 *
1540 * Note 1) Only certain guests (like Linux' snd_hda_intel) rely on the WALCLK register
1541 * in order to determine the correct timing of the sound device. Other guests
1542 * like Windows 7 + 10 (or even more exotic ones like Haiku) will completely
1543 * ignore this.
1544 *
1545 * Note 2) When updating the WALCLK register too often / early (or even in a non-monotonic
1546 * fashion) this *will* upset guest device drivers and will completely fuck up the
1547 * sound output. Running VLC on the guest will tell!
1548 */
1549 const bool fWalClkSet = hdaR3WalClkSet(pThis, pThisCC,
1550 RT_MIN( hdaWalClkGetCurrent(pThis)
1551 + hdaR3StreamPeriodFramesToWalClk(pPeriod,
1552 cbProcessed
1553 / pStreamR3->State.Mapping.cbFrameSize),
1554 hdaR3WalClkGetMax(pThis, pThisCC)),
1555 false /* fForce */);
1556 RT_NOREF(fWalClkSet);
1557 }
1558
1559 /* Set the next transfer timing slot.
1560 * This must happen at a constant rate. */
1561 pStreamShared->State.tsTransferNext = tsNow + pStreamShared->State.cTransferTicks;
1562
1563 /* Always update this timestamp, no matter what pStreamShared->State.tsTransferNext is. */
1564 pStreamShared->State.tsTransferLast = tsNow;
1565
1566 Log3Func(("[SD%RU8] %R[bdle] -- %RU32/%RU32\n",
1567 uSD, pBDLE, cbProcessed, pStreamShared->State.cbTransferSize));
1568 Log3Func(("[SD%RU8] fTransferComplete=%RTbool, cTransferPendingInterrupts=%RU8\n",
1569 uSD, fTransferComplete, pStreamShared->State.cTransferPendingInterrupts));
1570 Log3Func(("[SD%RU8] tsNow=%RU64, tsTransferNext=%RU64 (in %RU64 ticks)\n",
1571 uSD, tsNow, pStreamShared->State.tsTransferNext,
1572 pStreamShared->State.tsTransferNext ? pStreamShared->State.tsTransferNext - tsNow : 0));
1573
1574 LogFlowFuncLeave();
1575
1576 hdaStreamUnlock(pStreamShared);
1577
1578 return VINF_SUCCESS;
1579}
1580
1581/**
1582 * Updates a HDA stream by doing its required data transfers.
1583 *
1584 * The host sink(s) set the overall pace.
1585 *
1586 * This routine is called by both, the synchronous and the asynchronous
1587 * (VBOX_WITH_AUDIO_HDA_ASYNC_IO), implementations.
1588 *
1589 * When running synchronously, the device DMA transfers *and* the mixer sink
1590 * processing is within the device timer.
1591 *
1592 * When running asynchronously, only the device DMA transfers are done in the
1593 * device timer, whereas the mixer sink processing then is done in the stream's
1594 * own async I/O thread. This thread also will call this function
1595 * (with fInTimer set to @c false).
1596 *
1597 * @param pDevIns The device instance.
1598 * @param pThis The shared HDA device state.
1599 * @param pThisCC The ring-3 HDA device state.
1600 * @param pStreamShared HDA stream to update (shared bits).
1601 * @param pStreamR3 HDA stream to update (ring-3 bits).
1602 * @param fInTimer Whether to this function was called from the timer
1603 * context or an asynchronous I/O stream thread (if supported).
1604 */
1605void hdaR3StreamUpdate(PPDMDEVINS pDevIns, PHDASTATE pThis, PHDASTATER3 pThisCC,
1606 PHDASTREAM pStreamShared, PHDASTREAMR3 pStreamR3, bool fInTimer)
1607{
1608 if (!pStreamShared)
1609 return;
1610
1611 PAUDMIXSINK pSink = NULL;
1612 if (pStreamR3->pMixSink)
1613 pSink = pStreamR3->pMixSink->pMixSink;
1614
1615 if (!AudioMixerSinkIsActive(pSink)) /* No sink available? Bail out. */
1616 return;
1617
1618 const uint64_t tsNowNs = RTTimeNanoTS();
1619
1620 int rc2;
1621
1622 if (hdaGetDirFromSD(pStreamShared->u8SD) == PDMAUDIODIR_OUT) /* Output (SDO). */
1623 {
1624 bool fDoRead = false; /* Whether to read from the HDA stream or not. */
1625
1626# ifdef VBOX_WITH_AUDIO_HDA_ASYNC_IO
1627 if (fInTimer)
1628# endif
1629 {
1630 uint32_t cbStreamFree = hdaR3StreamGetFree(pStreamR3);
1631 if (!cbStreamFree)
1632 {
1633 LogRel2(("HDA: Warning: Hit stream #%RU8 overflow, dropping audio data\n", pStreamShared->u8SD));
1634# ifdef HDA_STRICT
1635 AssertMsgFailed(("Hit stream #%RU8 overflow -- timing bug?\n", pStreamShared->u8SD));
1636# endif
1637 /* When hitting an overflow, drop all remaining data to make space for current data.
1638 * This is needed in order to keep the device emulation running at a constant rate,
1639 * at the cost of losing valid (but too much) data. */
1640 RTCircBufReset(pStreamR3->State.pCircBuf);
1641 cbStreamFree = hdaR3StreamGetFree(pStreamR3);
1642 }
1643
1644 /* Do the DMA transfer. */
1645 rc2 = hdaR3StreamTransfer(pDevIns, pThis, pThisCC, pStreamShared, pStreamR3, cbStreamFree);
1646 AssertRC(rc2);
1647
1648 /* Never read yet? Set initial timestamp. */
1649 if (pStreamShared->State.tsLastReadNs == 0)
1650 pStreamShared->State.tsLastReadNs = tsNowNs;
1651
1652 /* Only read from the HDA stream at the given scheduling rate. */
1653 Assert(tsNowNs >= pStreamShared->State.tsLastReadNs);
1654 const uint64_t tsDeltaMs = (tsNowNs - pStreamShared->State.tsLastReadNs) / RT_NS_1MS;
1655 if (tsDeltaMs >= pStreamShared->State.Cfg.Device.cMsSchedulingHint)
1656 fDoRead = true;
1657
1658 Log3Func(("tsDeltaMs=%RU64, fDoRead=%RTbool\n", tsDeltaMs, fDoRead));
1659 }
1660
1661 if (fDoRead)
1662 {
1663# ifdef VBOX_WITH_AUDIO_HDA_ASYNC_IO
1664 /* Notify the async I/O worker thread that there's work to do. */
1665 rc2 = hdaR3StreamAsyncIONotify(pStreamR3);
1666 AssertRC(rc2);
1667# endif
1668 /* Update last read timestamp so that we know when to run next. */
1669 pStreamShared->State.tsLastReadNs = tsNowNs;
1670 }
1671
1672# ifdef VBOX_WITH_AUDIO_HDA_ASYNC_IO
1673 if (!fInTimer) /* In async I/O thread */
1674# else
1675 if (fDoRead)
1676# endif
1677 {
1678 const uint32_t cbSinkWritable = AudioMixerSinkGetWritable(pSink);
1679 const uint32_t cbStreamReadable = hdaR3StreamGetUsed(pStreamR3);
1680 uint32_t cbToReadFromStream = RT_MIN(cbStreamReadable, cbSinkWritable);
1681 /* Make sure that we always align the number of bytes when reading to the stream's PCM properties. */
1682 cbToReadFromStream = DrvAudioHlpBytesAlign(cbToReadFromStream, &pStreamShared->State.Cfg.Props);
1683
1684#ifdef LOG_ENABLED
1685 Assert(tsNowNs >= pStreamShared->State.tsLastReadNs);
1686 const uint64_t deltaLastReadMs = (tsNowNs - pStreamShared->State.tsLastReadNs) / RT_NS_1MS;
1687 Log3Func(("[SD%RU8] deltaLastReadMs=%RU64\n",
1688 pStreamShared->u8SD, deltaLastReadMs));
1689#endif
1690 Log3Func(("[SD%RU8] cbSinkWritable=%RU32, cbStreamReadable=%RU32 -> cbToReadFromStream=%RU32\n",
1691 pStreamShared->u8SD, cbSinkWritable, cbStreamReadable, cbToReadFromStream));
1692
1693 if (cbToReadFromStream)
1694 {
1695 /* Read (guest output) data and write it to the stream's sink. */
1696 rc2 = hdaR3StreamRead(pStreamR3, cbToReadFromStream, NULL /* pcbRead */);
1697 AssertRC(rc2);
1698 }
1699
1700 /* When running synchronously, update the associated sink here.
1701 * Otherwise this will be done in the async I/O thread. */
1702 rc2 = AudioMixerSinkUpdate(pSink);
1703 AssertRC(rc2);
1704 }
1705 }
1706 else /* Input (SDI). */
1707 {
1708# ifdef VBOX_WITH_AUDIO_HDA_ASYNC_IO
1709 if (!fInTimer)
1710# endif
1711 {
1712 rc2 = AudioMixerSinkUpdate(pSink);
1713 AssertRC(rc2);
1714
1715 /* Is the sink ready to be read (host input data) from? If so, by how much? */
1716 uint32_t cbSinkReadable = AudioMixerSinkGetReadable(pSink);
1717
1718 /* How much (guest input) data is available for writing at the moment for the HDA stream? */
1719 const uint32_t cbStreamFree = hdaR3StreamGetFree(pStreamR3);
1720
1721 Log3Func(("[SD%RU8] cbSinkReadable=%RU32, cbStreamFree=%RU32\n", pStreamShared->u8SD, cbSinkReadable, cbStreamFree));
1722
1723 /* Do not read more than the HDA stream can hold at the moment.
1724 * The host sets the overall pace. */
1725 if (cbSinkReadable > cbStreamFree)
1726 cbSinkReadable = cbStreamFree;
1727
1728 if (cbSinkReadable)
1729 {
1730 void *pvFIFO = &pStreamShared->abFIFO[0];
1731 uint32_t cbFIFO = (uint32_t)sizeof(pStreamShared->abFIFO);
1732
1733 while (cbSinkReadable)
1734 {
1735 uint32_t cbRead;
1736 rc2 = AudioMixerSinkRead(pSink, AUDMIXOP_COPY,
1737 pvFIFO, RT_MIN(cbSinkReadable, cbFIFO), &cbRead);
1738 AssertRCBreak(rc2);
1739
1740 if (!cbRead)
1741 {
1742 AssertMsgFailed(("Nothing read from sink, even if %RU32 bytes were (still) announced\n", cbSinkReadable));
1743 break;
1744 }
1745
1746 /* Write (guest input) data to the stream which was read from stream's sink before. */
1747 uint32_t cbWritten;
1748 rc2 = hdaR3StreamWrite(pStreamR3, pvFIFO, cbRead, &cbWritten);
1749 AssertRCBreak(rc2);
1750 AssertBreak(cbWritten > 0); /* Should never happen, as we know how much we can write. */
1751
1752 Assert(cbSinkReadable >= cbRead);
1753 cbSinkReadable -= cbRead;
1754 }
1755 }
1756 }
1757# ifdef VBOX_WITH_AUDIO_HDA_ASYNC_IO
1758 else /* fInTimer */
1759# endif
1760 {
1761# ifdef VBOX_WITH_AUDIO_HDA_ASYNC_IO
1762 if (tsNowNs - pStreamShared->State.tsLastReadNs >= pStreamShared->State.Cfg.Device.cMsSchedulingHint * RT_NS_1MS)
1763 {
1764 rc2 = hdaR3StreamAsyncIONotify(pStreamR3);
1765 AssertRC(rc2);
1766
1767 pStreamShared->State.tsLastReadNs = tsNowNs;
1768 }
1769# endif
1770 const uint32_t cbStreamUsed = hdaR3StreamGetUsed(pStreamR3);
1771 if (cbStreamUsed)
1772 {
1773 rc2 = hdaR3StreamTransfer(pDevIns, pThis, pThisCC, pStreamShared, pStreamR3, cbStreamUsed);
1774 AssertRC(rc2);
1775 }
1776 }
1777 }
1778}
1779
1780/**
1781 * Locks an HDA stream for serialized access.
1782 *
1783 * @returns IPRT status code.
1784 * @param pStreamShared HDA stream to lock (shared bits).
1785 */
1786void hdaStreamLock(PHDASTREAM pStreamShared)
1787{
1788 AssertPtrReturnVoid(pStreamShared);
1789# ifdef VBOX_WITH_AUDIO_HDA_ASYNC_IO
1790 int rc2 = PDMCritSectEnter(&pStreamShared->CritSect, VINF_SUCCESS);
1791 AssertRC(rc2);
1792#endif
1793}
1794
1795/**
1796 * Unlocks a formerly locked HDA stream.
1797 *
1798 * @returns IPRT status code.
1799 * @param pStreamShared HDA stream to unlock (shared bits).
1800 */
1801void hdaStreamUnlock(PHDASTREAM pStreamShared)
1802{
1803 AssertPtrReturnVoid(pStreamShared);
1804# ifdef VBOX_WITH_AUDIO_HDA_ASYNC_IO
1805 int rc2 = PDMCritSectLeave(&pStreamShared->CritSect);
1806 AssertRC(rc2);
1807# endif
1808}
1809
1810#if 0 /* unused - no prototype even */
1811/**
1812 * Updates an HDA stream's current read or write buffer position (depending on the stream type) by
1813 * updating its associated LPIB register and DMA position buffer (if enabled).
1814 *
1815 * @returns Set LPIB value.
1816 * @param pDevIns The device instance.
1817 * @param pStream HDA stream to update read / write position for.
1818 * @param u32LPIB New LPIB (position) value to set.
1819 */
1820uint32_t hdaR3StreamUpdateLPIB(PPDMDEVINS pDevIns, PHDASTATE pThis, PHDASTREAM pStreamShared, uint32_t u32LPIB)
1821{
1822 AssertMsg(u32LPIB <= pStreamShared->u32CBL,
1823 ("[SD%RU8] New LPIB (%RU32) exceeds CBL (%RU32)\n", pStreamShared->u8SD, u32LPIB, pStreamShared->u32CBL));
1824
1825 u32LPIB = RT_MIN(u32LPIB, pStreamShared->u32CBL);
1826
1827 LogFlowFunc(("[SD%RU8] LPIB=%RU32 (DMA Position Buffer Enabled: %RTbool)\n",
1828 pStreamShared->u8SD, u32LPIB, pThis->fDMAPosition));
1829
1830 /* Update LPIB in any case. */
1831 HDA_STREAM_REG(pThis, LPIB, pStreamShared->u8SD) = u32LPIB;
1832
1833 /* Do we need to tell the current DMA position? */
1834 if (pThis->fDMAPosition)
1835 {
1836 int rc2 = PDMDevHlpPCIPhysWrite(pDevIns,
1837 pThis->u64DPBase + (pStreamShared->u8SD * 2 * sizeof(uint32_t)),
1838 (void *)&u32LPIB, sizeof(uint32_t));
1839 AssertRC(rc2);
1840 }
1841
1842 return u32LPIB;
1843}
1844#endif
1845
1846# ifdef HDA_USE_DMA_ACCESS_HANDLER
1847/**
1848 * Registers access handlers for a stream's BDLE DMA accesses.
1849 *
1850 * @returns true if registration was successful, false if not.
1851 * @param pStream HDA stream to register BDLE access handlers for.
1852 */
1853bool hdaR3StreamRegisterDMAHandlers(PHDASTREAM pStream)
1854{
1855 /* At least LVI and the BDL base must be set. */
1856 if ( !pStreamShared->u16LVI
1857 || !pStreamShared->u64BDLBase)
1858 {
1859 return false;
1860 }
1861
1862 hdaR3StreamUnregisterDMAHandlers(pStream);
1863
1864 LogFunc(("Registering ...\n"));
1865
1866 int rc = VINF_SUCCESS;
1867
1868 /*
1869 * Create BDLE ranges.
1870 */
1871
1872 struct BDLERANGE
1873 {
1874 RTGCPHYS uAddr;
1875 uint32_t uSize;
1876 } arrRanges[16]; /** @todo Use a define. */
1877
1878 size_t cRanges = 0;
1879
1880 for (uint16_t i = 0; i < pStreamShared->u16LVI + 1; i++)
1881 {
1882 HDABDLE BDLE;
1883 rc = hdaR3BDLEFetch(pDevIns, &BDLE, pStreamShared->u64BDLBase, i /* Index */);
1884 if (RT_FAILURE(rc))
1885 break;
1886
1887 bool fAddRange = true;
1888 BDLERANGE *pRange;
1889
1890 if (cRanges)
1891 {
1892 pRange = &arrRanges[cRanges - 1];
1893
1894 /* Is the current range a direct neighbor of the current BLDE? */
1895 if ((pRange->uAddr + pRange->uSize) == BDLE.Desc.u64BufAddr)
1896 {
1897 /* Expand the current range by the current BDLE's size. */
1898 pRange->uSize += BDLE.Desc.u32BufSize;
1899
1900 /* Adding a new range in this case is not needed anymore. */
1901 fAddRange = false;
1902
1903 LogFunc(("Expanding range %zu by %RU32 (%RU32 total now)\n", cRanges - 1, BDLE.Desc.u32BufSize, pRange->uSize));
1904 }
1905 }
1906
1907 /* Do we need to add a new range? */
1908 if ( fAddRange
1909 && cRanges < RT_ELEMENTS(arrRanges))
1910 {
1911 pRange = &arrRanges[cRanges];
1912
1913 pRange->uAddr = BDLE.Desc.u64BufAddr;
1914 pRange->uSize = BDLE.Desc.u32BufSize;
1915
1916 LogFunc(("Adding range %zu - 0x%x (%RU32)\n", cRanges, pRange->uAddr, pRange->uSize));
1917
1918 cRanges++;
1919 }
1920 }
1921
1922 LogFunc(("%zu ranges total\n", cRanges));
1923
1924 /*
1925 * Register all ranges as DMA access handlers.
1926 */
1927
1928 for (size_t i = 0; i < cRanges; i++)
1929 {
1930 BDLERANGE *pRange = &arrRanges[i];
1931
1932 PHDADMAACCESSHANDLER pHandler = (PHDADMAACCESSHANDLER)RTMemAllocZ(sizeof(HDADMAACCESSHANDLER));
1933 if (!pHandler)
1934 {
1935 rc = VERR_NO_MEMORY;
1936 break;
1937 }
1938
1939 RTListAppend(&pStream->State.lstDMAHandlers, &pHandler->Node);
1940
1941 pHandler->pStream = pStream; /* Save a back reference to the owner. */
1942
1943 char szDesc[32];
1944 RTStrPrintf(szDesc, sizeof(szDesc), "HDA[SD%RU8 - RANGE%02zu]", pStream->u8SD, i);
1945
1946 int rc2 = PGMR3HandlerPhysicalTypeRegister(PDMDevHlpGetVM(pStream->pHDAState->pDevInsR3), PGMPHYSHANDLERKIND_WRITE,
1947 hdaDMAAccessHandler,
1948 NULL, NULL, NULL,
1949 NULL, NULL, NULL,
1950 szDesc, &pHandler->hAccessHandlerType);
1951 AssertRCBreak(rc2);
1952
1953 pHandler->BDLEAddr = pRange->uAddr;
1954 pHandler->BDLESize = pRange->uSize;
1955
1956 /* Get first and last pages of the BDLE range. */
1957 RTGCPHYS pgFirst = pRange->uAddr & ~PAGE_OFFSET_MASK;
1958 RTGCPHYS pgLast = RT_ALIGN(pgFirst + pRange->uSize, PAGE_SIZE);
1959
1960 /* Calculate the region size (in pages). */
1961 RTGCPHYS regionSize = RT_ALIGN(pgLast - pgFirst, PAGE_SIZE);
1962
1963 pHandler->GCPhysFirst = pgFirst;
1964 pHandler->GCPhysLast = pHandler->GCPhysFirst + (regionSize - 1);
1965
1966 LogFunc(("\tRegistering region '%s': 0x%x - 0x%x (region size: %zu)\n",
1967 szDesc, pHandler->GCPhysFirst, pHandler->GCPhysLast, regionSize));
1968 LogFunc(("\tBDLE @ 0x%x - 0x%x (%RU32)\n",
1969 pHandler->BDLEAddr, pHandler->BDLEAddr + pHandler->BDLESize, pHandler->BDLESize));
1970
1971 rc2 = PGMHandlerPhysicalRegister(PDMDevHlpGetVM(pStream->pHDAState->pDevInsR3),
1972 pHandler->GCPhysFirst, pHandler->GCPhysLast,
1973 pHandler->hAccessHandlerType, pHandler, NIL_RTR0PTR, NIL_RTRCPTR,
1974 szDesc);
1975 AssertRCBreak(rc2);
1976
1977 pHandler->fRegistered = true;
1978 }
1979
1980 LogFunc(("Registration ended with rc=%Rrc\n", rc));
1981
1982 return RT_SUCCESS(rc);
1983}
1984
1985/**
1986 * Unregisters access handlers of a stream's BDLEs.
1987 *
1988 * @param pStream HDA stream to unregister BDLE access handlers for.
1989 */
1990void hdaR3StreamUnregisterDMAHandlers(PHDASTREAM pStream)
1991{
1992 LogFunc(("\n"));
1993
1994 PHDADMAACCESSHANDLER pHandler, pHandlerNext;
1995 RTListForEachSafe(&pStream->State.lstDMAHandlers, pHandler, pHandlerNext, HDADMAACCESSHANDLER, Node)
1996 {
1997 if (!pHandler->fRegistered) /* Handler not registered? Skip. */
1998 continue;
1999
2000 LogFunc(("Unregistering 0x%x - 0x%x (%zu)\n",
2001 pHandler->GCPhysFirst, pHandler->GCPhysLast, pHandler->GCPhysLast - pHandler->GCPhysFirst));
2002
2003 int rc2 = PGMHandlerPhysicalDeregister(PDMDevHlpGetVM(pStream->pHDAState->pDevInsR3),
2004 pHandler->GCPhysFirst);
2005 AssertRC(rc2);
2006
2007 RTListNodeRemove(&pHandler->Node);
2008
2009 RTMemFree(pHandler);
2010 pHandler = NULL;
2011 }
2012
2013 Assert(RTListIsEmpty(&pStream->State.lstDMAHandlers));
2014}
2015
2016# endif /* HDA_USE_DMA_ACCESS_HANDLER */
2017# ifdef VBOX_WITH_AUDIO_HDA_ASYNC_IO
2018
2019/**
2020 * @callback_method_impl{FNRTTHREAD,
2021 * Asynchronous I/O thread for a HDA stream.
2022 *
2023 * This will do the heavy lifting work for us as soon as it's getting notified
2024 * by another thread.}
2025 */
2026static DECLCALLBACK(int) hdaR3StreamAsyncIOThread(RTTHREAD hThreadSelf, void *pvUser)
2027{
2028 PHDASTREAMR3 const pStreamR3 = (PHDASTREAMR3)pvUser;
2029 PHDASTREAMSTATEAIO const pAIO = &pStreamR3->State.AIO;
2030 PHDASTATE const pThis = pStreamR3->pHDAStateShared;
2031 PHDASTATER3 const pThisCC = pStreamR3->pHDAStateR3;
2032 PPDMDEVINS const pDevIns = pThisCC->pDevIns;
2033 PHDASTREAM const pStreamShared = &pThis->aStreams[pStreamR3 - &pThisCC->aStreams[0]];
2034 Assert(pStreamR3 - &pThisCC->aStreams[0] == pStreamR3->u8SD);
2035 Assert(pStreamShared->u8SD == pStreamR3->u8SD);
2036
2037 /* Signal parent thread that we've started */
2038 ASMAtomicWriteBool(&pAIO->fStarted, true);
2039 RTThreadUserSignal(hThreadSelf);
2040
2041 LogFunc(("[SD%RU8] Started\n", pStreamShared->u8SD));
2042
2043 while (!ASMAtomicReadBool(&pAIO->fShutdown))
2044 {
2045 int rc2 = RTSemEventWait(pAIO->hEvent, RT_INDEFINITE_WAIT);
2046 if (RT_SUCCESS(rc2))
2047 { /* likely */ }
2048 else
2049 break;
2050
2051 if (!ASMAtomicReadBool(&pAIO->fShutdown))
2052 { /* likely */ }
2053 else
2054 break;
2055
2056 rc2 = RTCritSectEnter(&pAIO->CritSect);
2057 AssertRC(rc2);
2058 if (RT_SUCCESS(rc2))
2059 {
2060 if (pAIO->fEnabled)
2061 hdaR3StreamUpdate(pDevIns, pThis, pThisCC, pStreamShared, pStreamR3, false /* fInTimer */);
2062
2063 int rc3 = RTCritSectLeave(&pAIO->CritSect);
2064 AssertRC(rc3);
2065 }
2066 }
2067
2068 LogFunc(("[SD%RU8] Ended\n", pStreamShared->u8SD));
2069 ASMAtomicWriteBool(&pAIO->fStarted, false);
2070
2071 return VINF_SUCCESS;
2072}
2073
2074/**
2075 * Creates the async I/O thread for a specific HDA audio stream.
2076 *
2077 * @returns IPRT status code.
2078 * @param pStreamR3 HDA audio stream to create the async I/O thread for.
2079 */
2080int hdaR3StreamAsyncIOCreate(PHDASTREAMR3 pStreamR3)
2081{
2082 PHDASTREAMSTATEAIO pAIO = &pStreamR3->State.AIO;
2083
2084 int rc;
2085
2086 if (!ASMAtomicReadBool(&pAIO->fStarted))
2087 {
2088 pAIO->fShutdown = false;
2089 pAIO->fEnabled = true; /* Enabled by default. */
2090
2091 rc = RTSemEventCreate(&pAIO->hEvent);
2092 if (RT_SUCCESS(rc))
2093 {
2094 rc = RTCritSectInit(&pAIO->CritSect);
2095 if (RT_SUCCESS(rc))
2096 {
2097 rc = RTThreadCreateF(&pAIO->hThread, hdaR3StreamAsyncIOThread, pStreamR3, 0 /*cbStack*/,
2098 RTTHREADTYPE_IO, RTTHREADFLAGS_WAITABLE, "hdaAIO%RU8", pStreamR3->u8SD);
2099 if (RT_SUCCESS(rc))
2100 rc = RTThreadUserWait(pAIO->hThread, 10 * 1000 /* 10s timeout */);
2101 }
2102 }
2103 }
2104 else
2105 rc = VINF_SUCCESS;
2106
2107 LogFunc(("[SD%RU8] Returning %Rrc\n", pStreamR3->u8SD, rc));
2108 return rc;
2109}
2110
2111/**
2112 * Destroys the async I/O thread of a specific HDA audio stream.
2113 *
2114 * @returns IPRT status code.
2115 * @param pStreamR3 HDA audio stream to destroy the async I/O thread for.
2116 */
2117static int hdaR3StreamAsyncIODestroy(PHDASTREAMR3 pStreamR3)
2118{
2119 PHDASTREAMSTATEAIO pAIO = &pStreamR3->State.AIO;
2120
2121 if (!ASMAtomicReadBool(&pAIO->fStarted))
2122 return VINF_SUCCESS;
2123
2124 ASMAtomicWriteBool(&pAIO->fShutdown, true);
2125
2126 int rc = hdaR3StreamAsyncIONotify(pStreamR3);
2127 AssertRC(rc);
2128
2129 int rcThread;
2130 rc = RTThreadWait(pAIO->hThread, 30 * 1000 /* 30s timeout */, &rcThread);
2131 LogFunc(("Async I/O thread ended with %Rrc (%Rrc)\n", rc, rcThread));
2132
2133 if (RT_SUCCESS(rc))
2134 {
2135 pAIO->hThread = NIL_RTTHREAD;
2136
2137 rc = RTCritSectDelete(&pAIO->CritSect);
2138 AssertRC(rc);
2139
2140 rc = RTSemEventDestroy(pAIO->hEvent);
2141 AssertRC(rc);
2142 pAIO->hEvent = NIL_RTSEMEVENT;
2143
2144 pAIO->fStarted = false;
2145 pAIO->fShutdown = false;
2146 pAIO->fEnabled = false;
2147 }
2148
2149 LogFunc(("[SD%RU8] Returning %Rrc\n", pStreamR3->u8SD, rc));
2150 return rc;
2151}
2152
2153/**
2154 * Lets the stream's async I/O thread know that there is some data to process.
2155 *
2156 * @returns IPRT status code.
2157 * @param pStreamR3 HDA stream to notify async I/O thread for.
2158 */
2159static int hdaR3StreamAsyncIONotify(PHDASTREAMR3 pStreamR3)
2160{
2161 return RTSemEventSignal(pStreamR3->State.AIO.hEvent);
2162}
2163
2164/**
2165 * Locks the async I/O thread of a specific HDA audio stream.
2166 *
2167 * @param pStreamR3 HDA stream to lock async I/O thread for.
2168 */
2169void hdaR3StreamAsyncIOLock(PHDASTREAMR3 pStreamR3)
2170{
2171 PHDASTREAMSTATEAIO pAIO = &pStreamR3->State.AIO;
2172
2173 if (!ASMAtomicReadBool(&pAIO->fStarted))
2174 return;
2175
2176 int rc2 = RTCritSectEnter(&pAIO->CritSect);
2177 AssertRC(rc2);
2178}
2179
2180/**
2181 * Unlocks the async I/O thread of a specific HDA audio stream.
2182 *
2183 * @param pStreamR3 HDA stream to unlock async I/O thread for.
2184 */
2185void hdaR3StreamAsyncIOUnlock(PHDASTREAMR3 pStreamR3)
2186{
2187 PHDASTREAMSTATEAIO pAIO = &pStreamR3->State.AIO;
2188
2189 if (!ASMAtomicReadBool(&pAIO->fStarted))
2190 return;
2191
2192 int rc2 = RTCritSectLeave(&pAIO->CritSect);
2193 AssertRC(rc2);
2194}
2195
2196/**
2197 * Enables (resumes) or disables (pauses) the async I/O thread.
2198 *
2199 * @param pStreamR3 HDA stream to enable/disable async I/O thread for.
2200 * @param fEnable Whether to enable or disable the I/O thread.
2201 *
2202 * @remarks Does not do locking.
2203 */
2204void hdaR3StreamAsyncIOEnable(PHDASTREAMR3 pStreamR3, bool fEnable)
2205{
2206 PHDASTREAMSTATEAIO pAIO = &pStreamR3->State.AIO;
2207 ASMAtomicXchgBool(&pAIO->fEnabled, fEnable);
2208}
2209
2210# endif /* VBOX_WITH_AUDIO_HDA_ASYNC_IO */
2211#endif /* IN_RING3 */
注意: 瀏覽 TracBrowser 來幫助您使用儲存庫瀏覽器

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