VirtualBox

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

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

Audio/HDA: When starting / resuming (via saved state) stream transfers, call hdaR3StreamTimerMain() directly to avoid going through the timer to speed up startup time. ticketoem2ref:36

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