VirtualBox

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

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

Audio/HDA: Make sure that we always align the number of bytes when reading to the stream's PCM properties. ticketoem2ref:36

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