VirtualBox

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

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

Audio/HDA: Doxygen fix (it doesn't have VBOX_WITH_AUDIO_HDA_ASYNC_IO defined and got confused by unbalanced {} #ifdefs).

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