VirtualBox

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

Last change on this file since 87875 was 87863, checked in by vboxsync, 4 years ago

Audio/HDA: Experimental change to lower more DPC calls within the guest by avoiding re-scheduling to R3 when the guest acknowledges an interrupt via hdaRegWriteSDSTS(). Only tested on Ubuntu 20.10, Win7 + Win10 20H2 so far. ticketoem2ref:36

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 84.9 KB
Line 
1/* $Id: HDAStream.cpp 87863 2021-02-24 17:25:23Z 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.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/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 LogRel2(("HDA: 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 * @param fInTimer Set if we're in the timer callout.
1095 */
1096static int hdaR3StreamTransfer(PPDMDEVINS pDevIns, PHDASTATE pThis, PHDASTATER3 pThisCC, PHDASTREAM pStreamShared,
1097 PHDASTREAMR3 pStreamR3, uint32_t cbToProcessMax, bool fInTimer)
1098{
1099 LogFlowFuncEnter();
1100
1101 uint8_t const uSD = pStreamShared->u8SD;
1102 hdaStreamLock(pStreamShared);
1103
1104 PHDASTREAMPERIOD pPeriod = &pStreamShared->State.Period;
1105
1106 bool fProceed = true;
1107
1108 /* Stream not running (anymore)? */
1109 if (!pStreamShared->State.fRunning)
1110 {
1111 Log3Func(("[SD%RU8] Not running, skipping transfer\n", uSD));
1112 fProceed = false;
1113 }
1114
1115 else if (HDA_STREAM_REG(pThis, STS, uSD) & HDA_SDSTS_BCIS)
1116 {
1117 Log3Func(("[SD%RU8] BCIS bit set, skipping transfer\n", uSD));
1118#ifdef HDA_STRICT
1119 /* Timing emulation bug or guest is misbehaving -- let me know. */
1120 AssertMsgFailed(("BCIS bit for stream #%RU8 still set when it shouldn't\n", uSD));
1121#endif
1122 fProceed = false;
1123 }
1124
1125 if (!fProceed)
1126 {
1127 hdaStreamUnlock(pStreamShared);
1128 return VINF_SUCCESS;
1129 }
1130
1131 /* Update real-time timestamp. */
1132 const uint64_t tsNowNs = RTTimeNanoTS();
1133#ifdef LOG_ENABLED
1134 const uint64_t tsDeltaMs = (tsNowNs - pStreamShared->State.tsLastTransferNs) / RT_NS_1MS;
1135 Log3Func(("[SD%RU8] tsDeltaNs=%RU64ms\n", uSD, tsDeltaMs));
1136#endif
1137 pStreamShared->State.tsLastTransferNs = tsNowNs;
1138
1139 const uint64_t tsNow = PDMDevHlpTimerGet(pDevIns, pStreamShared->hTimer);
1140
1141 if (!pStreamShared->State.tsTransferLast)
1142 pStreamShared->State.tsTransferLast = tsNow;
1143
1144 pStreamShared->State.tsTransferLast = tsNow;
1145
1146 /* Register sanity checks. */
1147 Assert(uSD < HDA_MAX_STREAMS);
1148 Assert(pStreamShared->u64BDLBase);
1149 Assert(pStreamShared->u32CBL);
1150 Assert(pStreamShared->u8FIFOS);
1151
1152 /* State sanity checks. */
1153 Assert(ASMAtomicReadBool(&pStreamShared->State.fInReset) == false);
1154 Assert(ASMAtomicReadBool(&pStreamShared->State.fRunning));
1155
1156 /* Transfer sanity checks. */
1157 Assert(pStreamShared->State.cbTransferSize);
1158 Assert(pStreamShared->State.cbTransferChunk <= pStreamShared->State.cbTransferSize);
1159
1160 int rc = VINF_SUCCESS;
1161
1162 /* Fetch first / next BDL entry. */
1163 PHDABDLE pBDLE = &pStreamShared->State.BDLE;
1164 if (hdaR3BDLEIsComplete(pBDLE))
1165 {
1166 rc = hdaR3BDLEFetch(pDevIns, pBDLE, pStreamShared->u64BDLBase, pStreamShared->State.uCurBDLE);
1167 AssertRC(rc);
1168 }
1169
1170 uint32_t cbToProcess = RT_MIN(pStreamShared->State.cbTransferSize, pStreamShared->State.cbTransferChunk);
1171
1172 Assert(cbToProcess); /* Nothing to process when there should be data. Accounting bug? */
1173
1174 /* More data to process than maximum allowed? */
1175#ifdef HDA_STRICT
1176 AssertStmt(cbToProcess <= cbToProcessMax, cbToProcess = cbToProcessMax);
1177#else
1178 if (cbToProcess > cbToProcessMax)
1179 cbToProcess = cbToProcessMax;
1180#endif
1181
1182 uint32_t cbProcessed = 0;
1183 uint32_t cbLeft = cbToProcess;
1184
1185 /* Whether an interrupt has been sent (asserted) for this transfer period already or not.
1186 *
1187 * Note: Windows 10 relies on this, e.g. sending more than one interrupt per transfer period
1188 * confuses the Windows' audio driver and will screw up the audio data. So only send
1189 * one interrupt per transfer period.
1190 */
1191 bool fInterruptSent = false;
1192
1193 /* Set the FIFORDY bit on the stream while doing the transfer. */
1194 HDA_STREAM_REG(pThis, STS, uSD) |= HDA_SDSTS_FIFORDY;
1195
1196 while (cbLeft)
1197 {
1198 /* Limit the chunk to the stream's FIFO size and what's left to process. */
1199 uint32_t cbChunk = RT_MIN(cbLeft, pStreamShared->u8FIFOS);
1200
1201 /* Limit the chunk to the remaining data of the current BDLE. */
1202 cbChunk = RT_MIN(cbChunk, pBDLE->Desc.u32BufSize - pBDLE->State.u32BufOff);
1203
1204 /* If there are position adjustment frames left to be processed,
1205 * make sure that we process them first as a whole. */
1206 if (pStreamShared->State.cfPosAdjustLeft)
1207 cbChunk = RT_MIN(cbChunk, uint32_t(pStreamShared->State.cfPosAdjustLeft * pStreamR3->State.Mapping.cbFrameSize));
1208
1209 if (!cbChunk)
1210 break;
1211
1212 uint32_t cbDMA = 0;
1213 PRTCIRCBUF pCircBuf = pStreamR3->State.pCircBuf;
1214 uint8_t *pabFIFO = pStreamShared->abFIFO;
1215
1216 if (hdaGetDirFromSD(uSD) == PDMAUDIODIR_IN) /* Input (SDI). */
1217 {
1218 STAM_PROFILE_START(&pThis->StatIn, a);
1219
1220 uint32_t cbDMAWritten = 0;
1221 uint32_t cbDMAToWrite = cbChunk;
1222
1223 /** @todo Do we need interleaving streams support here as well?
1224 * Never saw anything else besides mono/stereo mics (yet). */
1225 while (cbDMAToWrite)
1226 {
1227 void *pvBuf; size_t cbBuf;
1228 RTCircBufAcquireReadBlock(pCircBuf, cbDMAToWrite, &pvBuf, &cbBuf);
1229
1230 if ( !cbBuf
1231 && !RTCircBufUsed(pCircBuf))
1232 break;
1233
1234 memcpy(pabFIFO + cbDMAWritten, pvBuf, cbBuf);
1235
1236 RTCircBufReleaseReadBlock(pCircBuf, cbBuf);
1237
1238 Assert(cbDMAToWrite >= cbBuf);
1239 cbDMAToWrite -= (uint32_t)cbBuf;
1240 cbDMAWritten += (uint32_t)cbBuf;
1241 Assert(cbDMAWritten <= cbChunk);
1242 }
1243
1244 if (cbDMAToWrite)
1245 {
1246 LogRel2(("HDA: FIFO underflow for stream #%RU8 (%RU32 bytes outstanding)\n", uSD, cbDMAToWrite));
1247
1248 Assert(cbChunk == cbDMAWritten + cbDMAToWrite);
1249 memset((uint8_t *)pabFIFO + cbDMAWritten, 0, cbDMAToWrite);
1250 cbDMAWritten = cbChunk;
1251 }
1252
1253 rc = hdaR3DMAWrite(pDevIns, pThis, pStreamShared, pStreamR3, pabFIFO, cbDMAWritten, &cbDMA /* pcbWritten */);
1254 if (RT_FAILURE(rc))
1255 LogRel(("HDA: Writing to stream #%RU8 DMA failed with %Rrc\n", uSD, rc));
1256
1257 STAM_PROFILE_STOP(&pThis->StatIn, a);
1258 }
1259 else if (hdaGetDirFromSD(uSD) == PDMAUDIODIR_OUT) /* Output (SDO). */
1260 {
1261 STAM_PROFILE_START(&pThis->StatOut, a);
1262
1263 rc = hdaR3DMARead(pDevIns, pThis, pStreamShared, pStreamR3, pabFIFO, cbChunk, &cbDMA /* pcbRead */);
1264 if (RT_SUCCESS(rc))
1265 {
1266 const uint32_t cbFree = (uint32_t)RTCircBufFree(pCircBuf);
1267
1268 /*
1269 * Most guests don't use different stream frame sizes than
1270 * the default one, so save a bit of CPU time and don't go into
1271 * the frame extraction code below.
1272 *
1273 * Only macOS guests need the frame extraction branch below at the moment AFAIK.
1274 */
1275 if (pStreamR3->State.Mapping.cbFrameSize == HDA_FRAME_SIZE_DEFAULT)
1276 {
1277 uint32_t cbDMARead = 0;
1278 uint32_t cbDMALeft = RT_MIN(cbDMA, cbFree);
1279
1280 while (cbDMALeft)
1281 {
1282 void *pvBuf; size_t cbBuf;
1283 RTCircBufAcquireWriteBlock(pCircBuf, cbDMALeft, &pvBuf, &cbBuf);
1284
1285 if (cbBuf)
1286 {
1287 memcpy(pvBuf, pabFIFO + cbDMARead, cbBuf);
1288 cbDMARead += (uint32_t)cbBuf;
1289 cbDMALeft -= (uint32_t)cbBuf;
1290 }
1291
1292 RTCircBufReleaseWriteBlock(pCircBuf, cbBuf);
1293 }
1294 }
1295 else
1296 {
1297 /*
1298 * The following code extracts the required audio stream (channel) data
1299 * of non-interleaved *and* interleaved audio streams.
1300 *
1301 * We by default only support 2 channels with 16-bit samples (HDA_FRAME_SIZE),
1302 * but an HDA audio stream can have interleaved audio data of multiple audio
1303 * channels in such a single stream ("AA,AA,AA vs. AA,BB,AA,BB").
1304 *
1305 * So take this into account by just handling the first channel in such a stream ("A")
1306 * and just discard the other channel's data.
1307 *
1308 * I know, the following code is horribly slow, but seems to work for now.
1309 */
1310 /** @todo Optimize channel data extraction! Use some SSE(3) / intrinsics? */
1311 for (unsigned m = 0; m < pStreamR3->State.Mapping.cMappings; m++)
1312 {
1313 const uint32_t cbFrame = pStreamR3->State.Mapping.cbFrameSize;
1314
1315 Assert(cbFree >= cbDMA);
1316
1317 PPDMAUDIOSTREAMMAP pMap = &pStreamR3->State.Mapping.paMappings[m];
1318 AssertPtr(pMap);
1319
1320 Log3Func(("Mapping #%u: Start (cbDMA=%RU32, cbFrame=%RU32, offNext=%RU32)\n",
1321 m, cbDMA, cbFrame, pMap->offNext));
1322
1323
1324 /* Skip the current DMA chunk if the chunk is smaller than what the current stream mapping needs to read
1325 * the next associated frame (pointed to at pMap->cbOff).
1326 *
1327 * This can happen if the guest did not come up with enough data within a certain time period, especially
1328 * when using multi-channel speaker (> 2 channels [stereo]) setups. */
1329 if (pMap->offNext > cbChunk)
1330 {
1331 Log2Func(("Mapping #%u: Skipped (cbChunk=%RU32, cbMapOff=%RU32)\n", m, cbChunk, pMap->offNext));
1332 continue;
1333 }
1334
1335 uint8_t *pbSrcBuf = pabFIFO;
1336 size_t cbSrcOff = pMap->offNext;
1337
1338 for (unsigned i = 0; i < cbDMA / cbFrame; i++)
1339 {
1340 void *pvDstBuf; size_t cbDstBuf;
1341 RTCircBufAcquireWriteBlock(pCircBuf, pMap->cbStep, &pvDstBuf, &cbDstBuf);
1342
1343 Assert(cbDstBuf >= pMap->cbStep);
1344
1345 if (cbDstBuf)
1346 {
1347 Log3Func(("Mapping #%u: Frame #%02u: cbStep=%u, offFirst=%u, offNext=%u, cbDstBuf=%u, cbSrcOff=%u\n",
1348 m, i, pMap->cbStep, pMap->offFirst, pMap->offNext, cbDstBuf, cbSrcOff));
1349
1350 memcpy(pvDstBuf, pbSrcBuf + cbSrcOff, cbDstBuf);
1351
1352#if 0 /* Too slow, even for release builds, so disabled it. */
1353 if (pStreamR3->Dbg.Runtime.fEnabled)
1354 DrvAudioHlpFileWrite(pStreamR3->Dbg.Runtime.pFileDMAMapped, pvDstBuf, cbDstBuf,
1355 0 /* fFlags */);
1356#endif
1357 Assert(cbSrcOff <= cbDMA);
1358 if (cbSrcOff + cbFrame + pMap->offFirst<= cbDMA)
1359 cbSrcOff += cbFrame + pMap->offFirst;
1360
1361 Log3Func(("Mapping #%u: Frame #%02u: -> cbSrcOff=%zu\n", m, i, cbSrcOff));
1362 }
1363
1364 RTCircBufReleaseWriteBlock(pCircBuf, cbDstBuf);
1365 }
1366
1367 Log3Func(("Mapping #%u: End cbSize=%u, cbDMA=%RU32, cbSrcOff=%zu\n",
1368 m, pMap->cbStep, cbDMA, cbSrcOff));
1369
1370 Assert(cbSrcOff <= cbDMA);
1371
1372 const uint32_t cbSrcLeft = cbDMA - (uint32_t)cbSrcOff;
1373 if (cbSrcLeft)
1374 {
1375 Log3Func(("Mapping #%u: cbSrcLeft=%RU32\n", m, cbSrcLeft));
1376
1377 if (cbSrcLeft >= pMap->cbStep)
1378 {
1379 void *pvDstBuf; size_t cbDstBuf;
1380 RTCircBufAcquireWriteBlock(pCircBuf, pMap->cbStep, &pvDstBuf, &cbDstBuf);
1381
1382 Assert(cbDstBuf >= pMap->cbStep);
1383
1384 if (cbDstBuf)
1385 {
1386 memcpy(pvDstBuf, pbSrcBuf + cbSrcOff, cbDstBuf);
1387 }
1388
1389 RTCircBufReleaseWriteBlock(pCircBuf, cbDstBuf);
1390 }
1391
1392 Assert(pMap->cbFrame >= cbSrcLeft);
1393 pMap->offNext = pMap->cbFrame - cbSrcLeft;
1394 }
1395 else
1396 pMap->offNext = 0;
1397
1398 Log3Func(("Mapping #%u finish (cbSrcOff=%zu, offNext=%zu)\n", m, cbSrcOff, pMap->offNext));
1399 }
1400 }
1401 }
1402 else
1403 LogRel(("HDA: Reading from stream #%RU8 DMA failed with %Rrc\n", uSD, rc));
1404
1405 STAM_PROFILE_STOP(&pThis->StatOut, a);
1406 }
1407
1408 else /** @todo Handle duplex streams? */
1409 AssertFailed();
1410
1411 if (cbDMA)
1412 {
1413 /* We always increment the position of DMA buffer counter because we're always reading
1414 * into an intermediate DMA buffer. */
1415 pBDLE->State.u32BufOff += (uint32_t)cbDMA;
1416 Assert(pBDLE->State.u32BufOff <= pBDLE->Desc.u32BufSize);
1417
1418 /* Are we done doing the position adjustment?
1419 * Only then do the transfer accounting .*/
1420 if (pStreamShared->State.cfPosAdjustLeft == 0)
1421 {
1422 Assert(cbLeft >= cbDMA);
1423 cbLeft -= cbDMA;
1424
1425 cbProcessed += cbDMA;
1426 }
1427
1428 Log3Func(("[SD%RU8] cbDMA=%RU32 -> %R[bdle]\n", uSD, cbDMA, pBDLE));
1429 }
1430
1431 if (hdaR3BDLEIsComplete(pBDLE))
1432 {
1433 Log3Func(("[SD%RU8] Completed %R[bdle]\n", uSD, pBDLE));
1434
1435 /* Make sure to also update the wall clock when a BDLE is complete.
1436 * Needed for Windows 10 guests. */
1437 hdaR3WalClkSet(pThis, pThisCC,
1438 hdaWalClkGetCurrent(pThis)
1439 + hdaR3StreamPeriodFramesToWalClk(pPeriod,
1440 pBDLE->Desc.u32BufSize
1441 / pStreamR3->State.Mapping.cbFrameSize),
1442 false /* fForce */);
1443
1444 /*
1445 * Update the stream's current position.
1446 * Do this as accurate and close to the actual data transfer as possible.
1447 * All guetsts rely on this, depending on the mechanism they use (LPIB register or DMA counters).
1448 *
1449 * Note for Windows 10: The OS' driver is *very* picky about *when* the (DMA) positions get updated!
1450 * Not doing this at the right time will result in ugly sound crackles!
1451 */
1452 hdaR3StreamSetPositionAdd(pStreamShared, pDevIns, pThis, pBDLE->Desc.u32BufSize);
1453
1454 /* Does the current BDLE require an interrupt to be sent? */
1455 if ( hdaR3BDLENeedsInterrupt(pBDLE)
1456 /* Are we done doing the position adjustment?
1457 * It can happen that a BDLE which is handled while doing the
1458 * position adjustment requires an interrupt on completion (IOC) being set.
1459 *
1460 * In such a case we need to skip such an interrupt and just move on. */
1461 && pStreamShared->State.cfPosAdjustLeft == 0)
1462 {
1463 /* If the IOCE ("Interrupt On Completion Enable") bit of the SDCTL register is set
1464 * we need to generate an interrupt.
1465 */
1466 if (HDA_STREAM_REG(pThis, CTL, uSD) & HDA_SDCTL_IOCE)
1467 {
1468 /* Assert the interrupt before actually fetching the next BDLE below. */
1469 if (!fInterruptSent)
1470 {
1471 pStreamShared->State.cTransferPendingInterrupts = 1;
1472
1473 AssertMsg(pStreamShared->State.cTransferPendingInterrupts <= 32,
1474 ("Too many pending interrupts (%RU8) for stream #%RU8\n",
1475 pStreamShared->State.cTransferPendingInterrupts, uSD));
1476
1477 Log3Func(("[SD%RU8] Scheduling interrupt (now %RU8 total)\n", uSD, pStreamShared->State.cTransferPendingInterrupts));
1478
1479 /*
1480 * Set the stream's BCIS bit.
1481 *
1482 * Note: This only must be done if the whole period is complete, and not if only
1483 * one specific BDL entry is complete (if it has the IOC bit set).
1484 *
1485 * This will otherwise confuses the guest when it 1) deasserts the interrupt,
1486 * 2) reads SDSTS (with BCIS set) and then 3) too early reads a (wrong) WALCLK value.
1487 *
1488 * snd_hda_intel on Linux will tell.
1489 */
1490 HDA_STREAM_REG(pThis, STS, uSD) |= HDA_SDSTS_BCIS;
1491
1492 /* Trigger an interrupt first and let hdaRegWriteSDSTS() deal with
1493 * ending / beginning a period. */
1494 HDA_PROCESS_INTERRUPT(pDevIns, pThis);
1495
1496 fInterruptSent = true;
1497 }
1498 }
1499 }
1500
1501 if (pStreamShared->State.uCurBDLE == pStreamShared->u16LVI)
1502 {
1503 pStreamShared->State.uCurBDLE = 0;
1504 }
1505 else
1506 pStreamShared->State.uCurBDLE++;
1507
1508 /* Fetch the next BDLE entry. */
1509 hdaR3BDLEFetch(pDevIns, pBDLE, pStreamShared->u64BDLBase, pStreamShared->State.uCurBDLE);
1510 }
1511
1512 /* Do the position adjustment accounting. */
1513 pStreamShared->State.cfPosAdjustLeft -=
1514 RT_MIN(pStreamShared->State.cfPosAdjustLeft, cbDMA / pStreamR3->State.Mapping.cbFrameSize);
1515
1516 if (RT_FAILURE(rc))
1517 break;
1518 }
1519
1520 /* Remove the FIFORDY bit again. */
1521 HDA_STREAM_REG(pThis, STS, uSD) &= ~HDA_SDSTS_FIFORDY;
1522
1523 /* Sanity. */
1524 Assert(cbProcessed == cbToProcess);
1525 Assert(cbLeft == 0);
1526
1527 /* Only do the data accounting if we don't have to do any position
1528 * adjustment anymore. */
1529 if (pStreamShared->State.cfPosAdjustLeft == 0)
1530 {
1531 hdaR3StreamPeriodInc(pPeriod, RT_MIN(cbProcessed / pStreamR3->State.Mapping.cbFrameSize,
1532 hdaR3StreamPeriodGetRemainingFrames(pPeriod)));
1533 }
1534
1535 const bool fTransferComplete = cbLeft == 0;
1536 uint64_t tsTransferNext = 0;
1537
1538 if (fTransferComplete)
1539 {
1540 /*
1541 * Try updating the wall clock.
1542 *
1543 * Note 1) Only certain guests (like Linux' snd_hda_intel) rely on the WALCLK register
1544 * in order to determine the correct timing of the sound device. Other guests
1545 * like Windows 7 + 10 (or even more exotic ones like Haiku) will completely
1546 * ignore this.
1547 *
1548 * Note 2) When updating the WALCLK register too often / early (or even in a non-monotonic
1549 * fashion) this *will* upset guest device drivers and will completely fuck up the
1550 * sound output. Running VLC on the guest will tell!
1551 */
1552 const bool fWalClkSet = hdaR3WalClkSet(pThis, pThisCC,
1553 RT_MIN( hdaWalClkGetCurrent(pThis)
1554 + hdaR3StreamPeriodFramesToWalClk(pPeriod,
1555 cbProcessed
1556 / pStreamR3->State.Mapping.cbFrameSize),
1557 hdaR3WalClkGetMax(pThis, pThisCC)),
1558 false /* fForce */);
1559 RT_NOREF(fWalClkSet);
1560 }
1561
1562 /* Set the next transfer timing slot.
1563 * This must happen at a constant rate. */
1564 tsTransferNext = tsNow + pStreamShared->State.cTransferTicks;
1565
1566 /* If we need to do another transfer, (re-)arm the device timer. */
1567 if (tsTransferNext) /* Can be 0 if no next transfer is needed. */
1568 {
1569 Log3Func(("[SD%RU8] Scheduling timer @ %RU64 (in %RU64 ticks)\n", uSD, tsTransferNext, tsTransferNext - tsNow));
1570
1571 /* Make sure to assign next transfer timestamp before setting the timer. */
1572 Assert(tsTransferNext > tsNow);
1573 pStreamShared->State.tsTransferNext = tsTransferNext;
1574
1575 Assert(!fInTimer || tsNow == PDMDevHlpTimerGet(pDevIns, pStreamShared->hTimer));
1576 hdaR3TimerSet(pDevIns, pStreamShared, tsTransferNext,
1577 true /* fForce - skip tsTransferNext check */, fInTimer ? tsNow : 0);
1578 }
1579
1580 /* Always update this timestamp, no matter what pStreamShared->State.tsTransferNext is. */
1581 pStreamShared->State.tsTransferLast = tsNow;
1582
1583 Log3Func(("[SD%RU8] %R[bdle] -- %RU32/%RU32\n",
1584 uSD, pBDLE, cbProcessed, pStreamShared->State.cbTransferSize));
1585 Log3Func(("[SD%RU8] fTransferComplete=%RTbool, cTransferPendingInterrupts=%RU8\n",
1586 uSD, fTransferComplete, pStreamShared->State.cTransferPendingInterrupts));
1587 Log3Func(("[SD%RU8] tsNow=%RU64, tsTransferNext=%RU64 (in %RU64 ticks)\n",
1588 uSD, tsNow, tsTransferNext, tsTransferNext ? tsTransferNext - tsNow : 0));
1589
1590 LogFlowFuncLeave();
1591
1592 hdaStreamUnlock(pStreamShared);
1593
1594 return VINF_SUCCESS;
1595}
1596
1597/**
1598 * Updates a HDA stream by doing its required data transfers.
1599 *
1600 * The host sink(s) set the overall pace.
1601 *
1602 * This routine is called by both, the synchronous and the asynchronous
1603 * (VBOX_WITH_AUDIO_HDA_ASYNC_IO), implementations.
1604 *
1605 * When running synchronously, the device DMA transfers *and* the mixer sink
1606 * processing is within the device timer.
1607 *
1608 * When running asynchronously, only the device DMA transfers are done in the
1609 * device timer, whereas the mixer sink processing then is done in the stream's
1610 * own async I/O thread. This thread also will call this function
1611 * (with fInTimer set to @c false).
1612 *
1613 * @param pDevIns The device instance.
1614 * @param pThis The shared HDA device state.
1615 * @param pThisCC The ring-3 HDA device state.
1616 * @param pStreamShared HDA stream to update (shared bits).
1617 * @param pStreamR3 HDA stream to update (ring-3 bits).
1618 * @param fInTimer Whether to this function was called from the timer
1619 * context or an asynchronous I/O stream thread (if supported).
1620 */
1621void hdaR3StreamUpdate(PPDMDEVINS pDevIns, PHDASTATE pThis, PHDASTATER3 pThisCC,
1622 PHDASTREAM pStreamShared, PHDASTREAMR3 pStreamR3, bool fInTimer)
1623{
1624 if (!pStreamShared)
1625 return;
1626
1627 PAUDMIXSINK pSink = NULL;
1628 if (pStreamR3->pMixSink)
1629 pSink = pStreamR3->pMixSink->pMixSink;
1630
1631 if (!AudioMixerSinkIsActive(pSink)) /* No sink available? Bail out. */
1632 return;
1633
1634 const uint64_t tsNowNs = RTTimeNanoTS();
1635
1636 int rc2;
1637
1638 if (hdaGetDirFromSD(pStreamShared->u8SD) == PDMAUDIODIR_OUT) /* Output (SDO). */
1639 {
1640 bool fDoRead = false; /* Whether to read from the HDA stream or not. */
1641
1642# ifdef VBOX_WITH_AUDIO_HDA_ASYNC_IO
1643 if (fInTimer)
1644# endif
1645 {
1646 uint32_t cbStreamFree = hdaR3StreamGetFree(pStreamR3);
1647 if (!cbStreamFree)
1648 {
1649 LogRel2(("HDA: Warning: Hit stream #%RU8 overflow, dropping audio data\n", pStreamShared->u8SD));
1650# ifdef HDA_STRICT
1651 AssertMsgFailed(("Hit stream #%RU8 overflow -- timing bug?\n", pStreamShared->u8SD));
1652# endif
1653 /* When hitting an overflow, drop all remaining data to make space for current data.
1654 * This is needed in order to keep the device emulation running at a constant rate,
1655 * at the cost of losing valid (but too much) data. */
1656 RTCircBufReset(pStreamR3->State.pCircBuf);
1657 cbStreamFree = hdaR3StreamGetFree(pStreamR3);
1658 }
1659
1660 /* Do the DMA transfer. */
1661 rc2 = hdaR3StreamTransfer(pDevIns, pThis, pThisCC, pStreamShared, pStreamR3, cbStreamFree, fInTimer);
1662 AssertRC(rc2);
1663
1664 /* Never read yet? Set initial timestamp. */
1665 if (pStreamShared->State.tsLastReadNs == 0)
1666 pStreamShared->State.tsLastReadNs = tsNowNs;
1667
1668 /* Only read from the HDA stream at the given scheduling rate. */
1669 Assert(tsNowNs >= pStreamShared->State.tsLastReadNs);
1670 const uint64_t tsDeltaMs = (tsNowNs - pStreamShared->State.tsLastReadNs) / RT_NS_1MS;
1671 if (tsDeltaMs >= pStreamShared->State.Cfg.Device.cMsSchedulingHint)
1672 fDoRead = true;
1673
1674 Log3Func(("tsDeltaMs=%RU64, fDoRead=%RTbool\n", tsDeltaMs, fDoRead));
1675 }
1676
1677 if (fDoRead)
1678 {
1679# ifdef VBOX_WITH_AUDIO_HDA_ASYNC_IO
1680 /* Notify the async I/O worker thread that there's work to do. */
1681 rc2 = hdaR3StreamAsyncIONotify(pStreamR3);
1682 AssertRC(rc2);
1683# endif
1684 /* Update last read timestamp so that we know when to run next. */
1685 pStreamShared->State.tsLastReadNs = tsNowNs;
1686 }
1687
1688# ifdef VBOX_WITH_AUDIO_HDA_ASYNC_IO
1689 if (!fInTimer) /* In async I/O thread */
1690# else
1691 if (fDoRead)
1692# endif
1693 {
1694 const uint32_t cbSinkWritable = AudioMixerSinkGetWritable(pSink);
1695 const uint32_t cbStreamReadable = hdaR3StreamGetUsed(pStreamR3);
1696 uint32_t cbToReadFromStream = RT_MIN(cbStreamReadable, cbSinkWritable);
1697 /* Make sure that we always align the number of bytes when reading to the stream's PCM properties. */
1698 cbToReadFromStream = DrvAudioHlpBytesAlign(cbToReadFromStream, &pStreamShared->State.Cfg.Props);
1699
1700#ifdef LOG_ENABLED
1701 Assert(tsNowNs >= pStreamShared->State.tsLastReadNs);
1702 const uint64_t deltaLastReadMs = (tsNowNs - pStreamShared->State.tsLastReadNs) / RT_NS_1MS;
1703 Log3Func(("[SD%RU8] deltaLastReadMs=%RU64\n",
1704 pStreamShared->u8SD, deltaLastReadMs));
1705#endif
1706 Log3Func(("[SD%RU8] cbSinkWritable=%RU32, cbStreamReadable=%RU32 -> cbToReadFromStream=%RU32\n",
1707 pStreamShared->u8SD, cbSinkWritable, cbStreamReadable, cbToReadFromStream));
1708
1709 if (cbToReadFromStream)
1710 {
1711 /* Read (guest output) data and write it to the stream's sink. */
1712 rc2 = hdaR3StreamRead(pStreamR3, cbToReadFromStream, NULL /* pcbRead */);
1713 AssertRC(rc2);
1714 }
1715
1716 /* When running synchronously, update the associated sink here.
1717 * Otherwise this will be done in the async I/O thread. */
1718 rc2 = AudioMixerSinkUpdate(pSink);
1719 AssertRC(rc2);
1720 }
1721 }
1722 else /* Input (SDI). */
1723 {
1724# ifdef VBOX_WITH_AUDIO_HDA_ASYNC_IO
1725 if (!fInTimer)
1726# endif
1727 {
1728 rc2 = AudioMixerSinkUpdate(pSink);
1729 AssertRC(rc2);
1730
1731 /* Is the sink ready to be read (host input data) from? If so, by how much? */
1732 uint32_t cbSinkReadable = AudioMixerSinkGetReadable(pSink);
1733
1734 /* How much (guest input) data is available for writing at the moment for the HDA stream? */
1735 const uint32_t cbStreamFree = hdaR3StreamGetFree(pStreamR3);
1736
1737 Log3Func(("[SD%RU8] cbSinkReadable=%RU32, cbStreamFree=%RU32\n", pStreamShared->u8SD, cbSinkReadable, cbStreamFree));
1738
1739 /* Do not read more than the HDA stream can hold at the moment.
1740 * The host sets the overall pace. */
1741 if (cbSinkReadable > cbStreamFree)
1742 cbSinkReadable = cbStreamFree;
1743
1744 if (cbSinkReadable)
1745 {
1746 void *pvFIFO = &pStreamShared->abFIFO[0];
1747 uint32_t cbFIFO = (uint32_t)sizeof(pStreamShared->abFIFO);
1748
1749 while (cbSinkReadable)
1750 {
1751 uint32_t cbRead;
1752 rc2 = AudioMixerSinkRead(pSink, AUDMIXOP_COPY,
1753 pvFIFO, RT_MIN(cbSinkReadable, cbFIFO), &cbRead);
1754 AssertRCBreak(rc2);
1755
1756 if (!cbRead)
1757 {
1758 AssertMsgFailed(("Nothing read from sink, even if %RU32 bytes were (still) announced\n", cbSinkReadable));
1759 break;
1760 }
1761
1762 /* Write (guest input) data to the stream which was read from stream's sink before. */
1763 uint32_t cbWritten;
1764 rc2 = hdaR3StreamWrite(pStreamR3, pvFIFO, cbRead, &cbWritten);
1765 AssertRCBreak(rc2);
1766 AssertBreak(cbWritten > 0); /* Should never happen, as we know how much we can write. */
1767
1768 Assert(cbSinkReadable >= cbRead);
1769 cbSinkReadable -= cbRead;
1770 }
1771 }
1772 }
1773# ifdef VBOX_WITH_AUDIO_HDA_ASYNC_IO
1774 else /* fInTimer */
1775# endif
1776 {
1777# ifdef VBOX_WITH_AUDIO_HDA_ASYNC_IO
1778 if (tsNowNs - pStreamShared->State.tsLastReadNs >= pStreamShared->State.Cfg.Device.cMsSchedulingHint * RT_NS_1MS)
1779 {
1780 rc2 = hdaR3StreamAsyncIONotify(pStreamR3);
1781 AssertRC(rc2);
1782
1783 pStreamShared->State.tsLastReadNs = tsNowNs;
1784 }
1785# endif
1786 const uint32_t cbStreamUsed = hdaR3StreamGetUsed(pStreamR3);
1787 if (cbStreamUsed)
1788 {
1789 rc2 = hdaR3StreamTransfer(pDevIns, pThis, pThisCC, pStreamShared, pStreamR3, cbStreamUsed, fInTimer);
1790 AssertRC(rc2);
1791 }
1792 }
1793 }
1794}
1795
1796/**
1797 * Locks an HDA stream for serialized access.
1798 *
1799 * @returns IPRT status code.
1800 * @param pStreamShared HDA stream to lock (shared bits).
1801 */
1802void hdaStreamLock(PHDASTREAM pStreamShared)
1803{
1804 AssertPtrReturnVoid(pStreamShared);
1805# ifdef VBOX_WITH_AUDIO_HDA_ASYNC_IO
1806 int rc2 = PDMCritSectEnter(&pStreamShared->CritSect, VINF_SUCCESS);
1807 AssertRC(rc2);
1808#endif
1809}
1810
1811/**
1812 * Unlocks a formerly locked HDA stream.
1813 *
1814 * @returns IPRT status code.
1815 * @param pStreamShared HDA stream to unlock (shared bits).
1816 */
1817void hdaStreamUnlock(PHDASTREAM pStreamShared)
1818{
1819 AssertPtrReturnVoid(pStreamShared);
1820# ifdef VBOX_WITH_AUDIO_HDA_ASYNC_IO
1821 int rc2 = PDMCritSectLeave(&pStreamShared->CritSect);
1822 AssertRC(rc2);
1823# endif
1824}
1825
1826#if 0 /* unused - no prototype even */
1827/**
1828 * Updates an HDA stream's current read or write buffer position (depending on the stream type) by
1829 * updating its associated LPIB register and DMA position buffer (if enabled).
1830 *
1831 * @returns Set LPIB value.
1832 * @param pDevIns The device instance.
1833 * @param pStream HDA stream to update read / write position for.
1834 * @param u32LPIB New LPIB (position) value to set.
1835 */
1836uint32_t hdaR3StreamUpdateLPIB(PPDMDEVINS pDevIns, PHDASTATE pThis, PHDASTREAM pStreamShared, uint32_t u32LPIB)
1837{
1838 AssertMsg(u32LPIB <= pStreamShared->u32CBL,
1839 ("[SD%RU8] New LPIB (%RU32) exceeds CBL (%RU32)\n", pStreamShared->u8SD, u32LPIB, pStreamShared->u32CBL));
1840
1841 u32LPIB = RT_MIN(u32LPIB, pStreamShared->u32CBL);
1842
1843 LogFlowFunc(("[SD%RU8] LPIB=%RU32 (DMA Position Buffer Enabled: %RTbool)\n",
1844 pStreamShared->u8SD, u32LPIB, pThis->fDMAPosition));
1845
1846 /* Update LPIB in any case. */
1847 HDA_STREAM_REG(pThis, LPIB, pStreamShared->u8SD) = u32LPIB;
1848
1849 /* Do we need to tell the current DMA position? */
1850 if (pThis->fDMAPosition)
1851 {
1852 int rc2 = PDMDevHlpPCIPhysWrite(pDevIns,
1853 pThis->u64DPBase + (pStreamShared->u8SD * 2 * sizeof(uint32_t)),
1854 (void *)&u32LPIB, sizeof(uint32_t));
1855 AssertRC(rc2);
1856 }
1857
1858 return u32LPIB;
1859}
1860#endif
1861
1862# ifdef HDA_USE_DMA_ACCESS_HANDLER
1863/**
1864 * Registers access handlers for a stream's BDLE DMA accesses.
1865 *
1866 * @returns true if registration was successful, false if not.
1867 * @param pStream HDA stream to register BDLE access handlers for.
1868 */
1869bool hdaR3StreamRegisterDMAHandlers(PHDASTREAM pStream)
1870{
1871 /* At least LVI and the BDL base must be set. */
1872 if ( !pStreamShared->u16LVI
1873 || !pStreamShared->u64BDLBase)
1874 {
1875 return false;
1876 }
1877
1878 hdaR3StreamUnregisterDMAHandlers(pStream);
1879
1880 LogFunc(("Registering ...\n"));
1881
1882 int rc = VINF_SUCCESS;
1883
1884 /*
1885 * Create BDLE ranges.
1886 */
1887
1888 struct BDLERANGE
1889 {
1890 RTGCPHYS uAddr;
1891 uint32_t uSize;
1892 } arrRanges[16]; /** @todo Use a define. */
1893
1894 size_t cRanges = 0;
1895
1896 for (uint16_t i = 0; i < pStreamShared->u16LVI + 1; i++)
1897 {
1898 HDABDLE BDLE;
1899 rc = hdaR3BDLEFetch(pDevIns, &BDLE, pStreamShared->u64BDLBase, i /* Index */);
1900 if (RT_FAILURE(rc))
1901 break;
1902
1903 bool fAddRange = true;
1904 BDLERANGE *pRange;
1905
1906 if (cRanges)
1907 {
1908 pRange = &arrRanges[cRanges - 1];
1909
1910 /* Is the current range a direct neighbor of the current BLDE? */
1911 if ((pRange->uAddr + pRange->uSize) == BDLE.Desc.u64BufAddr)
1912 {
1913 /* Expand the current range by the current BDLE's size. */
1914 pRange->uSize += BDLE.Desc.u32BufSize;
1915
1916 /* Adding a new range in this case is not needed anymore. */
1917 fAddRange = false;
1918
1919 LogFunc(("Expanding range %zu by %RU32 (%RU32 total now)\n", cRanges - 1, BDLE.Desc.u32BufSize, pRange->uSize));
1920 }
1921 }
1922
1923 /* Do we need to add a new range? */
1924 if ( fAddRange
1925 && cRanges < RT_ELEMENTS(arrRanges))
1926 {
1927 pRange = &arrRanges[cRanges];
1928
1929 pRange->uAddr = BDLE.Desc.u64BufAddr;
1930 pRange->uSize = BDLE.Desc.u32BufSize;
1931
1932 LogFunc(("Adding range %zu - 0x%x (%RU32)\n", cRanges, pRange->uAddr, pRange->uSize));
1933
1934 cRanges++;
1935 }
1936 }
1937
1938 LogFunc(("%zu ranges total\n", cRanges));
1939
1940 /*
1941 * Register all ranges as DMA access handlers.
1942 */
1943
1944 for (size_t i = 0; i < cRanges; i++)
1945 {
1946 BDLERANGE *pRange = &arrRanges[i];
1947
1948 PHDADMAACCESSHANDLER pHandler = (PHDADMAACCESSHANDLER)RTMemAllocZ(sizeof(HDADMAACCESSHANDLER));
1949 if (!pHandler)
1950 {
1951 rc = VERR_NO_MEMORY;
1952 break;
1953 }
1954
1955 RTListAppend(&pStream->State.lstDMAHandlers, &pHandler->Node);
1956
1957 pHandler->pStream = pStream; /* Save a back reference to the owner. */
1958
1959 char szDesc[32];
1960 RTStrPrintf(szDesc, sizeof(szDesc), "HDA[SD%RU8 - RANGE%02zu]", pStream->u8SD, i);
1961
1962 int rc2 = PGMR3HandlerPhysicalTypeRegister(PDMDevHlpGetVM(pStream->pHDAState->pDevInsR3), PGMPHYSHANDLERKIND_WRITE,
1963 hdaDMAAccessHandler,
1964 NULL, NULL, NULL,
1965 NULL, NULL, NULL,
1966 szDesc, &pHandler->hAccessHandlerType);
1967 AssertRCBreak(rc2);
1968
1969 pHandler->BDLEAddr = pRange->uAddr;
1970 pHandler->BDLESize = pRange->uSize;
1971
1972 /* Get first and last pages of the BDLE range. */
1973 RTGCPHYS pgFirst = pRange->uAddr & ~PAGE_OFFSET_MASK;
1974 RTGCPHYS pgLast = RT_ALIGN(pgFirst + pRange->uSize, PAGE_SIZE);
1975
1976 /* Calculate the region size (in pages). */
1977 RTGCPHYS regionSize = RT_ALIGN(pgLast - pgFirst, PAGE_SIZE);
1978
1979 pHandler->GCPhysFirst = pgFirst;
1980 pHandler->GCPhysLast = pHandler->GCPhysFirst + (regionSize - 1);
1981
1982 LogFunc(("\tRegistering region '%s': 0x%x - 0x%x (region size: %zu)\n",
1983 szDesc, pHandler->GCPhysFirst, pHandler->GCPhysLast, regionSize));
1984 LogFunc(("\tBDLE @ 0x%x - 0x%x (%RU32)\n",
1985 pHandler->BDLEAddr, pHandler->BDLEAddr + pHandler->BDLESize, pHandler->BDLESize));
1986
1987 rc2 = PGMHandlerPhysicalRegister(PDMDevHlpGetVM(pStream->pHDAState->pDevInsR3),
1988 pHandler->GCPhysFirst, pHandler->GCPhysLast,
1989 pHandler->hAccessHandlerType, pHandler, NIL_RTR0PTR, NIL_RTRCPTR,
1990 szDesc);
1991 AssertRCBreak(rc2);
1992
1993 pHandler->fRegistered = true;
1994 }
1995
1996 LogFunc(("Registration ended with rc=%Rrc\n", rc));
1997
1998 return RT_SUCCESS(rc);
1999}
2000
2001/**
2002 * Unregisters access handlers of a stream's BDLEs.
2003 *
2004 * @param pStream HDA stream to unregister BDLE access handlers for.
2005 */
2006void hdaR3StreamUnregisterDMAHandlers(PHDASTREAM pStream)
2007{
2008 LogFunc(("\n"));
2009
2010 PHDADMAACCESSHANDLER pHandler, pHandlerNext;
2011 RTListForEachSafe(&pStream->State.lstDMAHandlers, pHandler, pHandlerNext, HDADMAACCESSHANDLER, Node)
2012 {
2013 if (!pHandler->fRegistered) /* Handler not registered? Skip. */
2014 continue;
2015
2016 LogFunc(("Unregistering 0x%x - 0x%x (%zu)\n",
2017 pHandler->GCPhysFirst, pHandler->GCPhysLast, pHandler->GCPhysLast - pHandler->GCPhysFirst));
2018
2019 int rc2 = PGMHandlerPhysicalDeregister(PDMDevHlpGetVM(pStream->pHDAState->pDevInsR3),
2020 pHandler->GCPhysFirst);
2021 AssertRC(rc2);
2022
2023 RTListNodeRemove(&pHandler->Node);
2024
2025 RTMemFree(pHandler);
2026 pHandler = NULL;
2027 }
2028
2029 Assert(RTListIsEmpty(&pStream->State.lstDMAHandlers));
2030}
2031# endif /* HDA_USE_DMA_ACCESS_HANDLER */
2032
2033# ifdef VBOX_WITH_AUDIO_HDA_ASYNC_IO
2034/**
2035 * @callback_method_impl{FNRTTHREAD,
2036 * Asynchronous I/O thread for a HDA stream.
2037 *
2038 * This will do the heavy lifting work for us as soon as it's getting notified
2039 * by another thread.}
2040 */
2041static DECLCALLBACK(int) hdaR3StreamAsyncIOThread(RTTHREAD hThreadSelf, void *pvUser)
2042{
2043 PHDASTREAMR3 const pStreamR3 = (PHDASTREAMR3)pvUser;
2044 PHDASTREAMSTATEAIO const pAIO = &pStreamR3->State.AIO;
2045 PHDASTATE const pThis = pStreamR3->pHDAStateShared;
2046 PHDASTATER3 const pThisCC = pStreamR3->pHDAStateR3;
2047 PPDMDEVINS const pDevIns = pThisCC->pDevIns;
2048 PHDASTREAM const pStreamShared = &pThis->aStreams[pStreamR3 - &pThisCC->aStreams[0]];
2049 Assert(pStreamR3 - &pThisCC->aStreams[0] == pStreamR3->u8SD);
2050 Assert(pStreamShared->u8SD == pStreamR3->u8SD);
2051
2052 /* Signal parent thread that we've started */
2053 ASMAtomicXchgBool(&pAIO->fStarted, true);
2054 RTThreadUserSignal(hThreadSelf);
2055
2056 LogFunc(("[SD%RU8] Started\n", pStreamShared->u8SD));
2057
2058 for (;;)
2059 {
2060 int rc2 = RTSemEventWait(pAIO->hEvent, RT_INDEFINITE_WAIT);
2061 if (RT_FAILURE(rc2))
2062 break;
2063
2064 if (ASMAtomicReadBool(&pAIO->fShutdown))
2065 break;
2066
2067 rc2 = RTCritSectEnter(&pAIO->CritSect);
2068 AssertRC(rc2);
2069 if (RT_SUCCESS(rc2))
2070 {
2071 if (!pAIO->fEnabled)
2072 {
2073 RTCritSectLeave(&pAIO->CritSect);
2074 continue;
2075 }
2076
2077 hdaR3StreamUpdate(pDevIns, pThis, pThisCC, pStreamShared, pStreamR3, false /* fInTimer */);
2078
2079 int rc3 = RTCritSectLeave(&pAIO->CritSect);
2080 AssertRC(rc3);
2081 }
2082 }
2083
2084 LogFunc(("[SD%RU8] Ended\n", pStreamShared->u8SD));
2085 ASMAtomicXchgBool(&pAIO->fStarted, false);
2086
2087 return VINF_SUCCESS;
2088}
2089
2090/**
2091 * Creates the async I/O thread for a specific HDA audio stream.
2092 *
2093 * @returns IPRT status code.
2094 * @param pStreamR3 HDA audio stream to create the async I/O thread for.
2095 */
2096int hdaR3StreamAsyncIOCreate(PHDASTREAMR3 pStreamR3)
2097{
2098 PHDASTREAMSTATEAIO pAIO = &pStreamR3->State.AIO;
2099
2100 int rc;
2101
2102 if (!ASMAtomicReadBool(&pAIO->fStarted))
2103 {
2104 pAIO->fShutdown = false;
2105 pAIO->fEnabled = true; /* Enabled by default. */
2106
2107 rc = RTSemEventCreate(&pAIO->hEvent);
2108 if (RT_SUCCESS(rc))
2109 {
2110 rc = RTCritSectInit(&pAIO->CritSect);
2111 if (RT_SUCCESS(rc))
2112 {
2113 rc = RTThreadCreateF(&pAIO->hThread, hdaR3StreamAsyncIOThread, pStreamR3, 0 /*cbStack*/,
2114 RTTHREADTYPE_IO, RTTHREADFLAGS_WAITABLE, "hdaAIO%RU8", pStreamR3->u8SD);
2115 if (RT_SUCCESS(rc))
2116 rc = RTThreadUserWait(pAIO->hThread, 10 * 1000 /* 10s timeout */);
2117 }
2118 }
2119 }
2120 else
2121 rc = VINF_SUCCESS;
2122
2123 LogFunc(("[SD%RU8] Returning %Rrc\n", pStreamR3->u8SD, rc));
2124 return rc;
2125}
2126
2127/**
2128 * Destroys the async I/O thread of a specific HDA audio stream.
2129 *
2130 * @returns IPRT status code.
2131 * @param pStreamR3 HDA audio stream to destroy the async I/O thread for.
2132 */
2133static int hdaR3StreamAsyncIODestroy(PHDASTREAMR3 pStreamR3)
2134{
2135 PHDASTREAMSTATEAIO pAIO = &pStreamR3->State.AIO;
2136
2137 if (!ASMAtomicReadBool(&pAIO->fStarted))
2138 return VINF_SUCCESS;
2139
2140 ASMAtomicWriteBool(&pAIO->fShutdown, true);
2141
2142 int rc = hdaR3StreamAsyncIONotify(pStreamR3);
2143 AssertRC(rc);
2144
2145 int rcThread;
2146 rc = RTThreadWait(pAIO->hThread, 30 * 1000 /* 30s timeout */, &rcThread);
2147 LogFunc(("Async I/O thread ended with %Rrc (%Rrc)\n", rc, rcThread));
2148
2149 if (RT_SUCCESS(rc))
2150 {
2151 pAIO->hThread = NIL_RTTHREAD;
2152
2153 rc = RTCritSectDelete(&pAIO->CritSect);
2154 AssertRC(rc);
2155
2156 rc = RTSemEventDestroy(pAIO->hEvent);
2157 AssertRC(rc);
2158 pAIO->hEvent = NIL_RTSEMEVENT;
2159
2160 pAIO->fStarted = false;
2161 pAIO->fShutdown = false;
2162 pAIO->fEnabled = false;
2163 }
2164
2165 LogFunc(("[SD%RU8] Returning %Rrc\n", pStreamR3->u8SD, rc));
2166 return rc;
2167}
2168
2169/**
2170 * Lets the stream's async I/O thread know that there is some data to process.
2171 *
2172 * @returns IPRT status code.
2173 * @param pStreamR3 HDA stream to notify async I/O thread for.
2174 */
2175static int hdaR3StreamAsyncIONotify(PHDASTREAMR3 pStreamR3)
2176{
2177 return RTSemEventSignal(pStreamR3->State.AIO.hEvent);
2178}
2179
2180/**
2181 * Locks the async I/O thread of a specific HDA audio stream.
2182 *
2183 * @param pStreamR3 HDA stream to lock async I/O thread for.
2184 */
2185void hdaR3StreamAsyncIOLock(PHDASTREAMR3 pStreamR3)
2186{
2187 PHDASTREAMSTATEAIO pAIO = &pStreamR3->State.AIO;
2188
2189 if (!ASMAtomicReadBool(&pAIO->fStarted))
2190 return;
2191
2192 int rc2 = RTCritSectEnter(&pAIO->CritSect);
2193 AssertRC(rc2);
2194}
2195
2196/**
2197 * Unlocks the async I/O thread of a specific HDA audio stream.
2198 *
2199 * @param pStreamR3 HDA stream to unlock async I/O thread for.
2200 */
2201void hdaR3StreamAsyncIOUnlock(PHDASTREAMR3 pStreamR3)
2202{
2203 PHDASTREAMSTATEAIO pAIO = &pStreamR3->State.AIO;
2204
2205 if (!ASMAtomicReadBool(&pAIO->fStarted))
2206 return;
2207
2208 int rc2 = RTCritSectLeave(&pAIO->CritSect);
2209 AssertRC(rc2);
2210}
2211
2212/**
2213 * Enables (resumes) or disables (pauses) the async I/O thread.
2214 *
2215 * @param pStreamR3 HDA stream to enable/disable async I/O thread for.
2216 * @param fEnable Whether to enable or disable the I/O thread.
2217 *
2218 * @remarks Does not do locking.
2219 */
2220void hdaR3StreamAsyncIOEnable(PHDASTREAMR3 pStreamR3, bool fEnable)
2221{
2222 PHDASTREAMSTATEAIO pAIO = &pStreamR3->State.AIO;
2223 ASMAtomicXchgBool(&pAIO->fEnabled, fEnable);
2224}
2225# endif /* VBOX_WITH_AUDIO_HDA_ASYNC_IO */
2226
2227#endif /* IN_RING3 */
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