VirtualBox

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

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

DevHDA: Doxygen fix. bugref:9890

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 107.1 KB
Line 
1/* $Id: HDAStream.cpp 88172 2021-03-18 01:50:11Z 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#include <VBox/vmm/pdmaudioinline.h>
32
33#include "DrvAudio.h"
34
35#include "DevHDA.h"
36#include "HDAStream.h"
37
38#ifdef VBOX_WITH_DTRACE
39# include "dtrace/VBoxDD.h"
40#endif
41
42#ifdef IN_RING3 /* whole file */
43
44
45/*********************************************************************************************************************************
46* Internal Functions *
47*********************************************************************************************************************************/
48static void hdaR3StreamSetPositionAbs(PHDASTREAM pStreamShared, PPDMDEVINS pDevIns, PHDASTATE pThis, uint32_t uLPIB);
49
50static int hdaR3StreamAsyncIODestroy(PHDASTREAMR3 pStreamR3);
51
52
53
54/**
55 * Creates an HDA stream.
56 *
57 * @returns IPRT status code.
58 * @param pStreamShared The HDA stream to construct - shared bits.
59 * @param pStreamR3 The HDA stream to construct - ring-3 bits.
60 * @param pThis The shared HDA device instance.
61 * @param pThisCC The ring-3 HDA device instance.
62 * @param uSD Stream descriptor number to assign.
63 */
64int hdaR3StreamConstruct(PHDASTREAM pStreamShared, PHDASTREAMR3 pStreamR3, PHDASTATE pThis, PHDASTATER3 pThisCC, uint8_t uSD)
65{
66 int rc;
67
68 pStreamR3->u8SD = uSD;
69 pStreamShared->u8SD = uSD;
70 pStreamR3->pMixSink = NULL;
71 pStreamR3->pHDAStateShared = pThis;
72 pStreamR3->pHDAStateR3 = pThisCC;
73 Assert(pStreamShared->hTimer != NIL_TMTIMERHANDLE); /* hdaR3Construct initalized this one already. */
74
75 pStreamShared->State.fInReset = false;
76 pStreamShared->State.fRunning = false;
77#ifdef HDA_USE_DMA_ACCESS_HANDLER
78 RTListInit(&pStreamR3->State.lstDMAHandlers);
79#endif
80
81#ifdef VBOX_WITH_AUDIO_HDA_ASYNC_IO
82 AssertPtr(pStreamR3->pHDAStateR3);
83 AssertPtr(pStreamR3->pHDAStateR3->pDevIns);
84 rc = PDMDevHlpCritSectInit(pStreamR3->pHDAStateR3->pDevIns, &pStreamShared->CritSect,
85 RT_SRC_POS, "hda_sd#%RU8", pStreamShared->u8SD);
86 AssertRCReturn(rc, rc);
87#endif
88
89#ifdef DEBUG
90 rc = RTCritSectInit(&pStreamR3->Dbg.CritSect);
91 AssertRCReturn(rc, rc);
92#endif
93
94 const bool fIsInput = hdaGetDirFromSD(uSD) == PDMAUDIODIR_IN;
95
96 if (fIsInput)
97 {
98 pStreamShared->State.Cfg.u.enmSrc = PDMAUDIORECSRC_UNKNOWN;
99 pStreamShared->State.Cfg.enmDir = PDMAUDIODIR_IN;
100 }
101 else
102 {
103 pStreamShared->State.Cfg.u.enmDst = PDMAUDIOPLAYBACKDST_UNKNOWN;
104 pStreamShared->State.Cfg.enmDir = PDMAUDIODIR_OUT;
105 }
106
107 pStreamR3->Dbg.Runtime.fEnabled = pThisCC->Dbg.fEnabled;
108
109 if (pStreamR3->Dbg.Runtime.fEnabled)
110 {
111 char szFile[64];
112 char szPath[RTPATH_MAX];
113
114 /* pFileStream */
115 if (fIsInput)
116 RTStrPrintf(szFile, sizeof(szFile), "hdaStreamWriteSD%RU8", uSD);
117 else
118 RTStrPrintf(szFile, sizeof(szFile), "hdaStreamReadSD%RU8", uSD);
119
120 int rc2 = DrvAudioHlpFileNameGet(szPath, sizeof(szPath), pThisCC->Dbg.pszOutPath, szFile,
121 0 /* uInst */, PDMAUDIOFILETYPE_WAV, PDMAUDIOFILENAME_FLAGS_NONE);
122 AssertRC(rc2);
123
124 rc2 = DrvAudioHlpFileCreate(PDMAUDIOFILETYPE_WAV, szPath, PDMAUDIOFILE_FLAGS_NONE, &pStreamR3->Dbg.Runtime.pFileStream);
125 AssertRC(rc2);
126
127 /* pFileDMARaw */
128 if (fIsInput)
129 RTStrPrintf(szFile, sizeof(szFile), "hdaDMARawWriteSD%RU8", uSD);
130 else
131 RTStrPrintf(szFile, sizeof(szFile), "hdaDMARawReadSD%RU8", uSD);
132
133 rc2 = DrvAudioHlpFileNameGet(szPath, sizeof(szPath), pThisCC->Dbg.pszOutPath, szFile,
134 0 /* uInst */, PDMAUDIOFILETYPE_WAV, PDMAUDIOFILENAME_FLAGS_NONE);
135 AssertRC(rc2);
136
137 rc2 = DrvAudioHlpFileCreate(PDMAUDIOFILETYPE_WAV, szPath, PDMAUDIOFILE_FLAGS_NONE, &pStreamR3->Dbg.Runtime.pFileDMARaw);
138 AssertRC(rc2);
139
140 /* pFileDMAMapped */
141 if (fIsInput)
142 RTStrPrintf(szFile, sizeof(szFile), "hdaDMAWriteMappedSD%RU8", uSD);
143 else
144 RTStrPrintf(szFile, sizeof(szFile), "hdaDMAReadMappedSD%RU8", uSD);
145
146 rc2 = DrvAudioHlpFileNameGet(szPath, sizeof(szPath), pThisCC->Dbg.pszOutPath, szFile,
147 0 /* uInst */, PDMAUDIOFILETYPE_WAV, PDMAUDIOFILENAME_FLAGS_NONE);
148 AssertRC(rc2);
149
150 rc2 = DrvAudioHlpFileCreate(PDMAUDIOFILETYPE_WAV, szPath, PDMAUDIOFILE_FLAGS_NONE, &pStreamR3->Dbg.Runtime.pFileDMAMapped);
151 AssertRC(rc2);
152
153 /* Delete stale debugging files from a former run. */
154 DrvAudioHlpFileDelete(pStreamR3->Dbg.Runtime.pFileStream);
155 DrvAudioHlpFileDelete(pStreamR3->Dbg.Runtime.pFileDMARaw);
156 DrvAudioHlpFileDelete(pStreamR3->Dbg.Runtime.pFileDMAMapped);
157 }
158
159 return rc;
160}
161
162/**
163 * Destroys an HDA stream.
164 *
165 * @param pStreamShared The HDA stream to destroy - shared bits.
166 * @param pStreamR3 The HDA stream to destroy - ring-3 bits.
167 */
168void hdaR3StreamDestroy(PHDASTREAM pStreamShared, PHDASTREAMR3 pStreamR3)
169{
170 LogFlowFunc(("[SD%RU8] Destroying ...\n", pStreamShared->u8SD));
171
172 hdaR3StreamMapDestroy(&pStreamR3->State.Mapping);
173
174 int rc2;
175
176#ifdef VBOX_WITH_AUDIO_HDA_ASYNC_IO
177 rc2 = hdaR3StreamAsyncIODestroy(pStreamR3);
178 AssertRC(rc2);
179#endif
180
181#ifdef VBOX_WITH_AUDIO_HDA_ASYNC_IO
182 if (PDMCritSectIsInitialized(&pStreamShared->CritSect))
183 {
184 rc2 = PDMR3CritSectDelete(&pStreamShared->CritSect);
185 AssertRC(rc2);
186 }
187#endif
188
189 if (pStreamR3->State.pCircBuf)
190 {
191 RTCircBufDestroy(pStreamR3->State.pCircBuf);
192 pStreamR3->State.pCircBuf = NULL;
193 }
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/**
220 * Appends a item to the scheduler.
221 *
222 * @returns VBox status code.
223 * @param pStreamShared The stream which scheduler should be modified.
224 * @param cbCur The period length in guest bytes.
225 * @param cbMaxPeriod The max period in guest bytes.
226 * @param idxLastBdle The last BDLE in the period.
227 * @param pHostProps The host PCM properties.
228 * @param pGuestProps The guest PCM properties.
229 * @param pcbBorrow Where to account for bytes borrowed across buffers
230 * to align scheduling items on frame boundraries.
231 */
232static int hdaR3StreamAddScheduleItem(PHDASTREAM pStreamShared, uint32_t cbCur, uint32_t cbMaxPeriod, uint32_t idxLastBdle,
233 PCPDMAUDIOPCMPROPS pHostProps, PCPDMAUDIOPCMPROPS pGuestProps, uint32_t *pcbBorrow)
234{
235 /* Check that we've got room (shouldn't ever be a problem). */
236 size_t idx = pStreamShared->State.cSchedule;
237 AssertLogRelReturn(idx + 1 < RT_ELEMENTS(pStreamShared->State.aSchedule), VERR_INTERNAL_ERROR_5);
238
239 /* Figure out the BDLE range for this period. */
240 uint32_t const idxFirstBdle = idx == 0 ? 0
241 : pStreamShared->State.aSchedule[idx - 1].idxFirst
242 + pStreamShared->State.aSchedule[idx - 1].cEntries;
243
244 pStreamShared->State.aSchedule[idx].idxFirst = (uint8_t)idxFirstBdle;
245 pStreamShared->State.aSchedule[idx].cEntries = idxLastBdle >= idxFirstBdle
246 ? idxLastBdle - idxFirstBdle + 1
247 : pStreamShared->State.cBdles - idxFirstBdle + idxLastBdle + 1;
248
249 /* Deal with borrowing due to unaligned IOC buffers. */
250 uint32_t const cbBorrowed = *pcbBorrow;
251 if (cbBorrowed < cbCur)
252 cbCur -= cbBorrowed;
253 else
254 {
255 /* Note. We can probably gloss over this, but it's not a situation a sane guest would put us, so don't bother for now. */
256 ASSERT_GUEST_MSG_FAILED(("#%u: cbBorrow=%#x cbCur=%#x BDLE[%u..%u]\n",
257 pStreamShared->u8SD, cbBorrowed, cbCur, idxFirstBdle, idxLastBdle));
258 LogRelMax(32, ("HDA: Stream #%u has a scheduling error: cbBorrow=%#x cbCur=%#x BDLE[%u..%u]\n",
259 pStreamShared->u8SD, cbBorrowed, cbCur, idxFirstBdle, idxLastBdle));
260 return VERR_OUT_OF_RANGE;
261 }
262
263 uint32_t cbCurAligned = PDMAudioPropsRoundUpBytesToFrame(pGuestProps, cbCur);
264 *pcbBorrow = cbCurAligned - cbCur;
265
266 /* Do we need to split up the period? */
267 if (cbCurAligned <= cbMaxPeriod)
268 {
269 uint32_t cbHost = PDMAudioPropsFramesToBytes(pHostProps, PDMAudioPropsBytesToFrames(pGuestProps, cbCurAligned));
270 pStreamShared->State.aSchedule[idx].cbPeriod = cbHost;
271 pStreamShared->State.aSchedule[idx].cLoops = 1;
272 }
273 else
274 {
275 /* Reduce till we've below the threshold. */
276 uint32_t cbLoop = cbCurAligned;
277 do
278 cbLoop = cbCurAligned / 2;
279 while (cbLoop > cbMaxPeriod);
280 cbLoop = PDMAudioPropsRoundUpBytesToFrame(pGuestProps, cbLoop);
281
282 /* Complete the scheduling item. */
283 uint32_t cbHost = PDMAudioPropsFramesToBytes(pHostProps, PDMAudioPropsBytesToFrames(pGuestProps, cbLoop));
284 pStreamShared->State.aSchedule[idx].cbPeriod = cbHost;
285 pStreamShared->State.aSchedule[idx].cLoops = cbCurAligned / cbLoop;
286
287 /* If there is a remainder, add it as a separate entry (this is
288 why the schedule must be more than twice the size of the BDL).*/
289 cbCurAligned %= cbLoop;
290 if (cbCurAligned)
291 {
292 pStreamShared->State.aSchedule[idx + 1] = pStreamShared->State.aSchedule[idx];
293 idx++;
294 cbHost = PDMAudioPropsFramesToBytes(pHostProps, PDMAudioPropsBytesToFrames(pGuestProps, cbCurAligned));
295 pStreamShared->State.aSchedule[idx].cbPeriod = cbHost;
296 pStreamShared->State.aSchedule[idx].cLoops = 1;
297 }
298 }
299
300 /* Done. */
301 pStreamShared->State.cSchedule = (uint16_t)(idx + 1);
302
303 return VINF_SUCCESS;
304}
305
306/**
307 * Creates the DMA timer schedule for the stream
308 *
309 * This is called from the stream setup code.
310 *
311 * @returns VBox status code.
312 * @param pStreamShared The stream to create a schedule for. The BDL
313 * must be loaded.
314 * @param cSegments Number of BDL segments.
315 * @param cBufferIrqs Number of the BDLEs with IOC=1.
316 * @param cbTotal The total BDL length in guest bytes.
317 * @param cbMaxPeriod Max period in guest bytes. This is in case the
318 * guest want to play the whole "Der Ring des
319 * Nibelungen" cycle in one go.
320 * @param cTimerTicksPerSec The DMA timer frequency.
321 * @param pHostProps The host PCM properties.
322 * @param pGuestProps The guest PCM properties.
323 */
324static int hdaR3StreamCreateSchedule(PHDASTREAM pStreamShared, uint32_t cSegments, uint32_t cBufferIrqs, uint32_t cbTotal,
325 uint32_t cbMaxPeriod, uint64_t cTimerTicksPerSec,
326 PCPDMAUDIOPCMPROPS pHostProps, PCPDMAUDIOPCMPROPS pGuestProps)
327{
328 int rc;
329
330 /*
331 * Reset scheduling state.
332 */
333 RT_ZERO(pStreamShared->State.aSchedule);
334 pStreamShared->State.cSchedule = 0;
335 pStreamShared->State.cSchedulePrologue = 0;
336 pStreamShared->State.idxSchedule = 0;
337 pStreamShared->State.idxScheduleLoop = 0;
338
339 /*
340 * Do the basic schedule compilation.
341 */
342 uint32_t cPotentialPrologue = 0;
343 uint32_t cbBorrow = 0;
344 uint32_t cbCur = 0;
345 pStreamShared->State.aSchedule[0].idxFirst = 0;
346 for (uint32_t i = 0; i < cSegments; i++)
347 {
348 cbCur += pStreamShared->State.aBdl[i].cb;
349 if (pStreamShared->State.aBdl[i].fFlags & HDA_BDLE_F_IOC)
350 {
351 rc = hdaR3StreamAddScheduleItem(pStreamShared, cbCur, cbMaxPeriod, i, pHostProps, pGuestProps, &cbBorrow);
352 ASSERT_GUEST_RC_RETURN(rc, rc);
353
354 if (cPotentialPrologue == 0)
355 cPotentialPrologue = pStreamShared->State.cSchedule;
356 cbCur = 0;
357 }
358 }
359 AssertLogRelMsgReturn(cbBorrow == 0, ("HDA: Internal scheduling error on stream #%u: cbBorrow=%#x cbTotal=%#x cbCur=%#x\n",
360 pStreamShared->u8SD, cbBorrow, cbTotal, cbCur),
361 VERR_INTERNAL_ERROR_3);
362
363 /*
364 * Deal with any loose ends.
365 */
366 if (cbCur && cBufferIrqs == 0)
367 {
368 /* No IOC. Split the period in two. */
369 Assert(cbCur == cbTotal);
370 cbCur = PDMAudioPropsFloorBytesToFrame(pGuestProps, cbCur / 2);
371 rc = hdaR3StreamAddScheduleItem(pStreamShared, cbCur, cbMaxPeriod, cSegments, pHostProps, pGuestProps, &cbBorrow);
372 ASSERT_GUEST_RC_RETURN(rc, rc);
373
374 rc = hdaR3StreamAddScheduleItem(pStreamShared, cbTotal - cbCur, cbMaxPeriod, cSegments,
375 pHostProps, pGuestProps, &cbBorrow);
376 ASSERT_GUEST_RC_RETURN(rc, rc);
377 Assert(cbBorrow == 0);
378 }
379 else if (cbCur)
380 {
381 /* The last BDLE didn't have IOC set, so we must continue processing
382 from the start till we hit one that has. */
383 uint32_t i;
384 for (i = 0; i < cSegments; i++)
385 {
386 cbCur += pStreamShared->State.aBdl[i].cb;
387 if (pStreamShared->State.aBdl[i].fFlags & HDA_BDLE_F_IOC)
388 break;
389 }
390 rc = hdaR3StreamAddScheduleItem(pStreamShared, cbCur, cbMaxPeriod, i, pHostProps, pGuestProps, &cbBorrow);
391 ASSERT_GUEST_RC_RETURN(rc, rc);
392
393 /* The initial scheduling items covering the wrap around area are
394 considered a prologue and must not repeated later. */
395 Assert(cPotentialPrologue);
396 pStreamShared->State.cSchedulePrologue = (uint8_t)cPotentialPrologue;
397 }
398
399 /*
400 * If there is just one BDLE with IOC set, we have to make sure
401 * we've got at least two periods scheduled, otherwise there is
402 * a very good chance the guest will overwrite the start of the
403 * buffer before we ever get around to reading it.
404 */
405 if (cBufferIrqs == 1)
406 {
407 uint32_t i = pStreamShared->State.cSchedulePrologue;
408 Assert(i < pStreamShared->State.cSchedule);
409 if ( i + 1 == pStreamShared->State.cSchedule
410 && pStreamShared->State.aSchedule[i].cLoops == 1)
411 {
412 uint32_t const cbFirstHalf = PDMAudioPropsFloorBytesToFrame(pHostProps, pStreamShared->State.aSchedule[i].cbPeriod / 2);
413 uint32_t const cbOtherHalf = pStreamShared->State.aSchedule[i].cbPeriod - cbFirstHalf;
414 pStreamShared->State.aSchedule[i].cbPeriod = cbFirstHalf;
415 if (cbFirstHalf == cbOtherHalf)
416 pStreamShared->State.aSchedule[i].cLoops = 2;
417 else
418 {
419 pStreamShared->State.aSchedule[i + 1] = pStreamShared->State.aSchedule[i];
420 pStreamShared->State.aSchedule[i].cbPeriod = cbOtherHalf;
421 pStreamShared->State.cSchedule++;
422 }
423 }
424 }
425
426 /*
427 * Go over the schduling entries and calculate the timer ticks for each period.
428 */
429 LogRel2(("HDA: Stream #%u schedule: %u items, %u prologue\n",
430 pStreamShared->u8SD, pStreamShared->State.cSchedule, pStreamShared->State.cSchedulePrologue));
431 uint64_t const cbHostPerSec = PDMAudioPropsFramesToBytes(pHostProps, pHostProps->uHz);
432 for (uint32_t i = 0; i < pStreamShared->State.cSchedule; i++)
433 {
434 uint64_t const cTicks = ASMMultU64ByU32DivByU32(cTimerTicksPerSec, pStreamShared->State.aSchedule[i].cbPeriod,
435 cbHostPerSec);
436 AssertLogRelMsgReturn((uint32_t)cTicks == cTicks, ("cTicks=%RU64 (%#RX64)\n", cTicks, cTicks), VERR_INTERNAL_ERROR_4);
437 pStreamShared->State.aSchedule[i].cPeriodTicks = RT_MAX((uint32_t)cTicks, 16);
438 LogRel2(("HDA: #%u: %u ticks / %u bytes, %u loops, BDLE%u L %u\n", i, pStreamShared->State.aSchedule[i].cPeriodTicks,
439 pStreamShared->State.aSchedule[i].cbPeriod, pStreamShared->State.aSchedule[i].cLoops,
440 pStreamShared->State.aSchedule[i].idxFirst, pStreamShared->State.aSchedule[i].cEntries));
441 }
442
443 return VINF_SUCCESS;
444}
445
446
447/**
448 * Sets up ((re-)iniitalizes) an HDA stream.
449 *
450 * @returns IPRT status code. VINF_NO_CHANGE if the stream does not need
451 * be set-up again because the stream's (hardware) parameters did
452 * not change.
453 * @param pDevIns The device instance.
454 * @param pThis The shared HDA device state (for HW register
455 * parameters).
456 * @param pStreamShared HDA stream to set up, shared portion.
457 * @param pStreamR3 HDA stream to set up, ring-3 portion.
458 * @param uSD Stream descriptor number to assign it.
459 */
460int hdaR3StreamSetUp(PPDMDEVINS pDevIns, PHDASTATE pThis, PHDASTREAM pStreamShared, PHDASTREAMR3 pStreamR3, uint8_t uSD)
461{
462 /* This must be valid all times. */
463 AssertReturn(uSD < HDA_MAX_STREAMS, VERR_INVALID_PARAMETER);
464
465 /* These member can only change on data corruption, despite what the code does further down (bird). */
466 AssertReturn(pStreamShared->u8SD == uSD, VERR_WRONG_ORDER);
467 AssertReturn(pStreamR3->u8SD == uSD, VERR_WRONG_ORDER);
468
469 const uint64_t u64BDLBase = RT_MAKE_U64(HDA_STREAM_REG(pThis, BDPL, uSD),
470 HDA_STREAM_REG(pThis, BDPU, uSD));
471 const uint16_t u16LVI = HDA_STREAM_REG(pThis, LVI, uSD);
472 const uint32_t u32CBL = HDA_STREAM_REG(pThis, CBL, uSD);
473 const uint8_t u8FIFOS = HDA_STREAM_REG(pThis, FIFOS, uSD) + 1;
474 uint8_t u8FIFOW = hdaSDFIFOWToBytes(HDA_STREAM_REG(pThis, FIFOW, uSD));
475 const uint16_t u16FMT = HDA_STREAM_REG(pThis, FMT, uSD);
476
477 /* Is the bare minimum set of registers configured for the stream?
478 * If not, bail out early, as there's nothing to do here for us (yet). */
479 if ( !u64BDLBase
480 || !u16LVI
481 || !u32CBL
482 || !u8FIFOS
483 || !u8FIFOW
484 || !u16FMT)
485 {
486 LogFunc(("[SD%RU8] Registers not set up yet, skipping (re-)initialization\n", uSD));
487 return VINF_SUCCESS;
488 }
489
490 PDMAUDIOPCMPROPS HostProps;
491 int rc = hdaR3SDFMTToPCMProps(u16FMT, &HostProps);
492 if (RT_FAILURE(rc))
493 {
494 LogRelMax(32, ("HDA: Warning: Format 0x%x for stream #%RU8 not supported\n", HDA_STREAM_REG(pThis, FMT, uSD), uSD));
495 return rc;
496 }
497
498 /*
499 * Initialize the stream mapping in any case, regardless if
500 * we support surround audio or not. This is needed to handle
501 * the supported channels within a single audio stream, e.g. mono/stereo.
502 *
503 * In other words, the stream mapping *always* knows the real
504 * number of channels in a single audio stream.
505 */
506 /** @todo r=bird: this is not done at the wrong time. We don't have the host
507 * output side set up yet, so we cannot really do proper mapping setup.
508 * However, we really need this further down when we configure the internal DMA
509 * buffer size. For now we just assume it's all stereo on the host side.
510 * This is not compatible with microphone support. */
511# ifdef VBOX_WITH_AUDIO_HDA_MIC_IN
512# error "Implement me!"
513# endif
514 rc = hdaR3StreamMapInit(&pStreamR3->State.Mapping, 2 /*cHostChannels*/, &HostProps);
515 AssertRCReturn(rc, rc);
516
517 ASSERT_GUEST_LOGREL_MSG_RETURN( pStreamR3->State.Mapping.cbGuestFrame > 0
518 && u32CBL % pStreamR3->State.Mapping.cbGuestFrame == 0,
519 ("CBL for stream #%RU8 does not align to frame size (u32CBL=%u cbFrameSize=%u)\n",
520 uSD, u32CBL, pStreamR3->State.Mapping.cbGuestFrame),
521 VERR_INVALID_PARAMETER);
522
523 /* Make sure the guest behaves regarding the stream's FIFO. */
524 ASSERT_GUEST_LOGREL_MSG_STMT(u8FIFOW <= u8FIFOS,
525 ("Guest tried setting a bigger FIFOW (%RU8) than FIFOS (%RU8), limiting\n", u8FIFOW, u8FIFOS),
526 u8FIFOW = u8FIFOS /* ASSUMES that u8FIFOS has been validated. */);
527
528 pStreamShared->u8SD = uSD;
529
530 /* Update all register copies so that we later know that something has changed. */
531 pStreamShared->u64BDLBase = u64BDLBase;
532 pStreamShared->u16LVI = u16LVI;
533 pStreamShared->u32CBL = u32CBL;
534 pStreamShared->u8FIFOS = u8FIFOS;
535 pStreamShared->u8FIFOW = u8FIFOW;
536 pStreamShared->u16FMT = u16FMT;
537
538 PPDMAUDIOSTREAMCFG pCfg = &pStreamShared->State.Cfg;
539 pCfg->Props = HostProps;
540
541 /* Set the stream's direction. */
542 pCfg->enmDir = hdaGetDirFromSD(uSD);
543
544 /* The the stream's name, based on the direction. */
545 switch (pCfg->enmDir)
546 {
547 case PDMAUDIODIR_IN:
548# ifdef VBOX_WITH_AUDIO_HDA_MIC_IN
549# error "Implement me!"
550# else
551 pCfg->u.enmSrc = PDMAUDIORECSRC_LINE;
552 pCfg->enmLayout = PDMAUDIOSTREAMLAYOUT_NON_INTERLEAVED;
553 RTStrCopy(pCfg->szName, sizeof(pCfg->szName), "Line In");
554# endif
555 break;
556
557 case PDMAUDIODIR_OUT:
558 /* Destination(s) will be set in hdaR3AddStreamOut(),
559 * based on the channels / stream layout. */
560 break;
561
562 default:
563 AssertFailedReturn(VERR_NOT_SUPPORTED);
564 break;
565 }
566
567 LogRel2(("HDA: Stream #%RU8 DMA @ 0x%x (%RU32 bytes = %RU64ms total)\n",
568 uSD, pStreamShared->u64BDLBase, pStreamShared->u32CBL,
569 PDMAudioPropsBytesToMilli(&pStreamR3->State.Mapping.GuestProps, pStreamShared->u32CBL)));
570
571
572 /*
573 * Load the buffer descriptor list.
574 *
575 * Section 3.6.2 states that "the BDL should not be modified unless the RUN
576 * bit is 0", so it should be within the specs to read it once here and not
577 * re-read any BDLEs later.
578 */
579 /* Reset BDL state. */
580 RT_ZERO(pStreamShared->State.aBdl);
581 pStreamShared->State.offCurBdle = 0;
582 pStreamShared->State.idxCurBdle = 0;
583
584 uint32_t /*const*/ cTransferFragments = (pStreamShared->u16LVI & 0xff) + 1;
585 if (cTransferFragments <= 1)
586 LogRel(("HDA: Warning: Stream #%RU8 transfer buffer count invalid: (%RU16)! Buggy guest audio driver!\n", uSD, pStreamShared->u16LVI));
587 AssertLogRelReturn(cTransferFragments <= RT_ELEMENTS(pStreamShared->State.aBdl), VERR_INTERNAL_ERROR_5);
588 pStreamShared->State.cBdles = cTransferFragments;
589
590 /* Load them. */
591 rc = PDMDevHlpPCIPhysRead(pDevIns, u64BDLBase, pStreamShared->State.aBdl,
592 sizeof(pStreamShared->State.aBdl[0]) * cTransferFragments);
593 AssertRC(rc);
594
595 /* Check what we just loaded. Refuse overly large buffer lists. */
596 uint64_t cbTotal = 0;
597 uint32_t cBufferIrqs = 0;
598 for (uint32_t i = 0; i < cTransferFragments; i++)
599 {
600 if (pStreamShared->State.aBdl[i].fFlags & HDA_BDLE_F_IOC)
601 cBufferIrqs++;
602 cbTotal += pStreamShared->State.aBdl[i].cb;
603 }
604 ASSERT_GUEST_STMT_RETURN(cbTotal < _2G,
605 LogRelMax(32, ("HDA: Error: Stream #%u is configured with an insane amount of buffer space - refusing do work with it: %RU64 (%#RX64) bytes.\n",
606 uSD, cbTotal, cbTotal)),
607 VERR_NOT_SUPPORTED);
608 ASSERT_GUEST_STMT_RETURN(cbTotal == u32CBL,
609 LogRelMax(32, ("HDA: Warning: Stream #%u has a mismatch between CBL and configured buffer space: %RU32 (%#RX32) vs %RU64 (%#RX64)\n",
610 uSD, u32CBL, u32CBL, cbTotal, cbTotal)),
611 VERR_NOT_SUPPORTED);
612
613 /*
614 * Create a DMA timer schedule.
615 */
616 rc = hdaR3StreamCreateSchedule(pStreamShared, cTransferFragments, cBufferIrqs, (uint32_t)cbTotal,
617 PDMAudioPropsMilliToBytes(&pStreamR3->State.Mapping.GuestProps, 100 /** @todo make configurable */),
618 PDMDevHlpTimerGetFreq(pDevIns, pStreamShared->hTimer),
619 &HostProps, &pStreamR3->State.Mapping.GuestProps);
620 if (RT_FAILURE(rc))
621 return rc;
622
623 pStreamShared->State.cbTransferSize = pStreamShared->State.aSchedule[0].cbPeriod;
624
625 /*
626 * Calculate the transfer Hz for use in the circular buffer calculation.
627 */
628 uint32_t cbMaxPeriod = 0;
629 uint32_t cbMinPeriod = UINT32_MAX;
630 uint32_t cPeriods = 0;
631 for (uint32_t i = 0; i < pStreamShared->State.cSchedule; i++)
632 {
633 uint32_t cbPeriod = pStreamShared->State.aSchedule[i].cbPeriod;
634 cbMaxPeriod = RT_MAX(cbMaxPeriod, cbPeriod);
635 cbMinPeriod = RT_MIN(cbMinPeriod, cbPeriod);
636 cPeriods += pStreamShared->State.aSchedule[i].cLoops;
637 }
638 uint64_t const cbTransferPerSec = RT_MAX(PDMAudioPropsFramesToBytes(&pCfg->Props, pCfg->Props.uHz),
639 4096 /* zero div prevention: min is 6kHz, picked 4k in case I'm mistaken */);
640 unsigned uTransferHz = cbTransferPerSec * 1000 / cbMaxPeriod;
641 LogRel2(("HDA: Stream #%RU8 needs a %u.%03u Hz timer rate (period: %u..%u host bytes)\n",
642 uSD, uTransferHz / 1000, uTransferHz % 1000, cbMinPeriod, cbMaxPeriod));
643 uTransferHz /= 1000;
644
645 if (uTransferHz > 400) /* Anything above 400 Hz looks fishy -- tell the user. */
646 LogRelMax(32, ("HDA: Warning: Calculated transfer Hz rate for stream #%RU8 looks incorrect (%u), please re-run with audio debug mode and report a bug\n",
647 uSD, uTransferHz));
648
649 pStreamShared->State.cbAvgTransfer = (uint32_t)(cbTotal + cPeriods - 1) / cPeriods;
650
651 /* For input streams we must determin a pre-buffering requirement.
652 We use the initial delay as a basis here, though we must have at
653 least two max periods worth of data queued up due to the way we
654 work the AIO thread. */
655 pStreamShared->State.fInputPreBuffered = false;
656 pStreamShared->State.cbInputPreBuffer = PDMAudioPropsMilliToBytes(&pCfg->Props, pThis->msInitialDelay);
657 pStreamShared->State.cbInputPreBuffer = RT_MIN(cbMaxPeriod * 2, pStreamShared->State.cbInputPreBuffer);
658
659 /*
660 * Set up data transfer stuff.
661 */
662
663 /* Assign the global device rate to the stream I/O timer as default. */
664 pStreamShared->State.uTimerIoHz = pThis->uTimerHz;
665 ASSERT_GUEST_LOGREL_MSG_STMT(pStreamShared->State.uTimerIoHz,
666 ("I/O timer Hz rate for stream #%RU8 is invalid\n", uSD),
667 pStreamShared->State.uTimerIoHz = HDA_TIMER_HZ_DEFAULT);
668
669 /* Set I/O scheduling hint for the backends. */
670 /** @todo r=bird: This is in the 'Device' portion, yet it's used by the
671 * audio driver. You would think stuff in the 'Device' part is
672 * private to the device. */
673 pCfg->Device.cMsSchedulingHint = RT_MS_1SEC / pStreamShared->State.uTimerIoHz;
674 LogRel2(("HDA: Stream #%RU8 set scheduling hint for the backends to %RU32ms\n", uSD, pCfg->Device.cMsSchedulingHint));
675
676
677 /* Make sure to also update the stream's DMA counter (based on its current LPIB value). */
678 hdaR3StreamSetPositionAbs(pStreamShared, pDevIns, pThis, HDA_STREAM_REG(pThis, LPIB, uSD));
679
680#ifdef LOG_ENABLED
681 hdaR3BDLEDumpAll(pDevIns, pThis, pStreamShared->u64BDLBase, pStreamShared->u16LVI + 1);
682#endif
683
684 /*
685 * Set up internal ring buffer.
686 */
687
688 /* (Re-)Allocate the stream's internal DMA buffer,
689 * based on the timing *and* PCM properties we just got above. */
690 if (pStreamR3->State.pCircBuf)
691 {
692 RTCircBufDestroy(pStreamR3->State.pCircBuf);
693 pStreamR3->State.pCircBuf = NULL;
694 }
695 pStreamR3->State.offWrite = 0;
696 pStreamR3->State.offRead = 0;
697
698 /*
699 * The default internal ring buffer size must be:
700 *
701 * - Large enough for at least three periodic DMA transfers.
702 *
703 * It is critically important that we don't experience underruns
704 * in the DMA OUT code, because it will cause the buffer processing
705 * to get skewed and possibly overlap with what the guest is updating.
706 * At the time of writing (2021-03-05) there is no code for getting
707 * back into sync there.
708 *
709 * - Large enough for at least three I/O scheduling hints.
710 *
711 * We want to lag behind a DMA period or two, but there must be
712 * sufficent space for the AIO thread to get schedule and shuffle
713 * data thru the mixer and onto the host audio hardware.
714 *
715 * - Both above with plenty to spare.
716 *
717 * So, just take the longest of the two periods and multipling it by 6.
718 * We aren't not talking about very large base buffers heres, so size isn't
719 * an issue.
720 *
721 * Note: Use pCfg->Props as PCM properties here, as we only want to store the
722 * samples we actually need, in other words, skipping the interleaved
723 * channels we don't support / need to save space.
724 */
725 uint32_t msCircBuf = RT_MS_1SEC * 6 / RT_MIN(uTransferHz, pStreamShared->State.uTimerIoHz);
726 msCircBuf = RT_MAX(msCircBuf, pThis->msInitialDelay + RT_MS_1SEC * 6 / uTransferHz);
727
728 uint32_t cbCircBuf = PDMAudioPropsMilliToBytes(&pCfg->Props, msCircBuf);
729 LogRel2(("HDA: Stream #%RU8 default ring buffer size is %RU32 bytes / %RU64 ms\n",
730 uSD, cbCircBuf, PDMAudioPropsBytesToMilli(&pCfg->Props, cbCircBuf)));
731
732 uint32_t msCircBufCfg = hdaGetDirFromSD(uSD) == PDMAUDIODIR_IN ? pThis->cbCircBufInMs : pThis->cbCircBufOutMs;
733 if (msCircBufCfg) /* Anything set via CFGM? */
734 {
735 cbCircBuf = PDMAudioPropsMilliToBytes(&pCfg->Props, msCircBufCfg);
736 LogRel2(("HDA: Stream #%RU8 is using a custom ring buffer size of %RU32 bytes / %RU64 ms\n",
737 uSD, cbCircBuf, PDMAudioPropsBytesToMilli(&pCfg->Props, cbCircBuf)));
738 }
739
740 /* Serious paranoia: */
741 ASSERT_GUEST_LOGREL_MSG_STMT(cbCircBuf % (pCfg->Props.cbSample * pCfg->Props.cChannels) == 0,
742 ("Ring buffer size (%RU32) for stream #%RU8 not aligned to the (host) frame size (%RU8)\n",
743 cbCircBuf, uSD, pCfg->Props.cbSample * pCfg->Props.cChannels),
744 rc = VERR_INVALID_PARAMETER);
745 ASSERT_GUEST_LOGREL_MSG_STMT(cbCircBuf, ("Ring buffer size for stream #%RU8 is invalid\n", uSD),
746 rc = VERR_INVALID_PARAMETER);
747 if (RT_SUCCESS(rc))
748 {
749 rc = RTCircBufCreate(&pStreamR3->State.pCircBuf, cbCircBuf);
750 if (RT_SUCCESS(rc))
751 {
752 /*
753 * Forward the timer frequency hint to TM as well for better accuracy on
754 * systems w/o preemption timers (also good for 'info timers').
755 */
756 PDMDevHlpTimerSetFrequencyHint(pDevIns, pStreamShared->hTimer, uTransferHz);
757 }
758 }
759
760 if (RT_FAILURE(rc))
761 LogRelMax(32, ("HDA: Initializing stream #%RU8 failed with %Rrc\n", uSD, rc));
762
763#ifdef VBOX_WITH_DTRACE
764 VBOXDD_HDA_STREAM_SETUP((uint32_t)uSD, rc, pStreamShared->State.Cfg.Props.uHz,
765 pStreamShared->State.aSchedule[pStreamShared->State.cSchedule - 1].cPeriodTicks,
766 pStreamShared->State.aSchedule[pStreamShared->State.cSchedule - 1].cbPeriod);
767#endif
768 return rc;
769}
770
771/**
772 * Resets an HDA stream.
773 *
774 * @param pThis The shared HDA device state.
775 * @param pThisCC The ring-3 HDA device state.
776 * @param pStreamShared HDA stream to reset (shared).
777 * @param pStreamR3 HDA stream to reset (ring-3).
778 * @param uSD Stream descriptor (SD) number to use for this stream.
779 */
780void hdaR3StreamReset(PHDASTATE pThis, PHDASTATER3 pThisCC, PHDASTREAM pStreamShared, PHDASTREAMR3 pStreamR3, uint8_t uSD)
781{
782 AssertPtr(pThis);
783 AssertPtr(pStreamShared);
784 AssertPtr(pStreamR3);
785 Assert(uSD < HDA_MAX_STREAMS);
786 AssertMsg(!pStreamShared->State.fRunning, ("[SD%RU8] Cannot reset stream while in running state\n", uSD));
787
788 LogFunc(("[SD%RU8] Reset\n", uSD));
789
790 /*
791 * Set reset state.
792 */
793 Assert(ASMAtomicReadBool(&pStreamShared->State.fInReset) == false); /* No nested calls. */
794 ASMAtomicXchgBool(&pStreamShared->State.fInReset, true);
795
796 /*
797 * Second, initialize the registers.
798 */
799 /* See 6.2.33: Clear on reset. */
800 HDA_STREAM_REG(pThis, STS, uSD) = 0;
801 /* According to the ICH6 datasheet, 0x40000 is the default value for stream descriptor register 23:20
802 * bits are reserved for stream number 18.2.33, resets SDnCTL except SRST bit. */
803 HDA_STREAM_REG(pThis, CTL, uSD) = 0x40000 | (HDA_STREAM_REG(pThis, CTL, uSD) & HDA_SDCTL_SRST);
804 /* ICH6 defines default values (120 bytes for input and 192 bytes for output descriptors) of FIFO size. 18.2.39. */
805 HDA_STREAM_REG(pThis, FIFOS, uSD) = hdaGetDirFromSD(uSD) == PDMAUDIODIR_IN ? HDA_SDIFIFO_120B : HDA_SDOFIFO_192B;
806 /* See 18.2.38: Always defaults to 0x4 (32 bytes). */
807 HDA_STREAM_REG(pThis, FIFOW, uSD) = HDA_SDFIFOW_32B;
808 HDA_STREAM_REG(pThis, LPIB, uSD) = 0;
809 HDA_STREAM_REG(pThis, CBL, uSD) = 0;
810 HDA_STREAM_REG(pThis, LVI, uSD) = 0;
811 HDA_STREAM_REG(pThis, FMT, uSD) = 0;
812 HDA_STREAM_REG(pThis, BDPU, uSD) = 0;
813 HDA_STREAM_REG(pThis, BDPL, uSD) = 0;
814
815#ifdef HDA_USE_DMA_ACCESS_HANDLER
816 hdaR3StreamUnregisterDMAHandlers(pThis, pStream);
817#endif
818
819 /* Assign the default mixer sink to the stream. */
820 pStreamR3->pMixSink = hdaR3GetDefaultSink(pThisCC, uSD);
821
822 /* Reset transfer stuff. */
823 pStreamShared->State.cTransferPendingInterrupts = 0;
824 pStreamShared->State.tsTransferLast = 0;
825 pStreamShared->State.tsTransferNext = 0;
826
827 /* Initialize timestamps. */
828 pStreamShared->State.tsLastTransferNs = 0;
829 pStreamShared->State.tsLastReadNs = 0;
830 pStreamShared->State.tsAioDelayEnd = UINT64_MAX;
831 pStreamShared->State.tsStart = 0;
832
833 RT_ZERO(pStreamShared->State.aBdl);
834 RT_ZERO(pStreamShared->State.aSchedule);
835 pStreamShared->State.offCurBdle = 0;
836 pStreamShared->State.cBdles = 0;
837 pStreamShared->State.idxCurBdle = 0;
838 pStreamShared->State.cSchedulePrologue = 0;
839 pStreamShared->State.cSchedule = 0;
840 pStreamShared->State.idxSchedule = 0;
841 pStreamShared->State.idxScheduleLoop = 0;
842 pStreamShared->State.fInputPreBuffered = false;
843
844 if (pStreamR3->State.pCircBuf)
845 RTCircBufReset(pStreamR3->State.pCircBuf);
846 pStreamR3->State.offWrite = 0;
847 pStreamR3->State.offRead = 0;
848
849#ifdef DEBUG
850 pStreamR3->Dbg.cReadsTotal = 0;
851 pStreamR3->Dbg.cbReadTotal = 0;
852 pStreamR3->Dbg.tsLastReadNs = 0;
853 pStreamR3->Dbg.cWritesTotal = 0;
854 pStreamR3->Dbg.cbWrittenTotal = 0;
855 pStreamR3->Dbg.cWritesHz = 0;
856 pStreamR3->Dbg.cbWrittenHz = 0;
857 pStreamR3->Dbg.tsWriteSlotBegin = 0;
858#endif
859
860 /* Report that we're done resetting this stream. */
861 HDA_STREAM_REG(pThis, CTL, uSD) = 0;
862
863#ifdef VBOX_WITH_DTRACE
864 VBOXDD_HDA_STREAM_RESET((uint32_t)uSD);
865#endif
866 LogFunc(("[SD%RU8] Reset\n", uSD));
867
868 /* Exit reset mode. */
869 ASMAtomicXchgBool(&pStreamShared->State.fInReset, false);
870}
871
872/**
873 * Enables or disables an HDA audio stream.
874 *
875 * @returns IPRT status code.
876 * @param pStreamShared HDA stream to enable or disable - shared bits.
877 * @param pStreamR3 HDA stream to enable or disable - ring-3 bits.
878 * @param fEnable Whether to enable or disble the stream.
879 */
880int hdaR3StreamEnable(PHDASTREAM pStreamShared, PHDASTREAMR3 pStreamR3, bool fEnable)
881{
882 AssertPtr(pStreamR3);
883 AssertPtr(pStreamShared);
884
885 LogFunc(("[SD%RU8] fEnable=%RTbool, pMixSink=%p\n", pStreamShared->u8SD, fEnable, pStreamR3->pMixSink));
886
887 int rc = VINF_SUCCESS;
888
889 AUDMIXSINKCMD enmCmd = fEnable
890 ? AUDMIXSINKCMD_ENABLE : AUDMIXSINKCMD_DISABLE;
891
892 /* First, enable or disable the stream and the stream's sink, if any. */
893 if ( pStreamR3->pMixSink
894 && pStreamR3->pMixSink->pMixSink)
895 rc = AudioMixerSinkCtl(pStreamR3->pMixSink->pMixSink, enmCmd);
896
897 if ( RT_SUCCESS(rc)
898 && fEnable
899 && pStreamR3->Dbg.Runtime.fEnabled)
900 {
901 Assert(DrvAudioHlpPcmPropsAreValid(&pStreamShared->State.Cfg.Props));
902
903 if (fEnable)
904 {
905 if (!DrvAudioHlpFileIsOpen(pStreamR3->Dbg.Runtime.pFileStream))
906 {
907 int rc2 = DrvAudioHlpFileOpen(pStreamR3->Dbg.Runtime.pFileStream, PDMAUDIOFILE_DEFAULT_OPEN_FLAGS,
908 &pStreamShared->State.Cfg.Props);
909 AssertRC(rc2);
910 }
911
912 if (!DrvAudioHlpFileIsOpen(pStreamR3->Dbg.Runtime.pFileDMARaw))
913 {
914 int rc2 = DrvAudioHlpFileOpen(pStreamR3->Dbg.Runtime.pFileDMARaw, PDMAUDIOFILE_DEFAULT_OPEN_FLAGS,
915 &pStreamShared->State.Cfg.Props);
916 AssertRC(rc2);
917 }
918
919 if (!DrvAudioHlpFileIsOpen(pStreamR3->Dbg.Runtime.pFileDMAMapped))
920 {
921 int rc2 = DrvAudioHlpFileOpen(pStreamR3->Dbg.Runtime.pFileDMAMapped, PDMAUDIOFILE_DEFAULT_OPEN_FLAGS,
922 &pStreamShared->State.Cfg.Props);
923 AssertRC(rc2);
924 }
925 }
926 }
927
928 if (RT_SUCCESS(rc))
929 {
930 if (fEnable)
931 pStreamShared->State.tsTransferLast = 0; /* Make sure it's not stale and messes up WALCLK calculations. */
932 pStreamShared->State.fRunning = fEnable;
933 }
934
935 LogFunc(("[SD%RU8] rc=%Rrc\n", pStreamShared->u8SD, rc));
936 return rc;
937}
938
939/**
940 * Marks the stream as started.
941 *
942 * Used after the stream has been enabled and the DMA timer has been armed.
943 */
944void hdaR3StreamMarkStarted(PPDMDEVINS pDevIns, PHDASTATE pThis, PHDASTREAM pStreamShared, uint64_t tsNow)
945{
946 pStreamShared->State.tsLastReadNs = RTTimeNanoTS();
947 pStreamShared->State.tsStart = tsNow;
948 pStreamShared->State.tsAioDelayEnd = tsNow + PDMDevHlpTimerFromMilli(pDevIns, pStreamShared->hTimer, pThis->msInitialDelay);
949 Log3Func(("#%u: tsStart=%RU64 tsAioDelayEnd=%RU64 tsLastReadNs=%RU64\n", pStreamShared->u8SD,
950 pStreamShared->State.tsStart, pStreamShared->State.tsAioDelayEnd, pStreamShared->State.tsLastReadNs));
951
952}
953
954/**
955 * Marks the stream as stopped.
956 */
957void hdaR3StreamMarkStopped(PHDASTREAM pStreamShared)
958{
959 Log3Func(("#%u\n", pStreamShared->u8SD));
960 pStreamShared->State.tsAioDelayEnd = UINT64_MAX;
961}
962
963
964#if 0 /* Not used atm. */
965static uint32_t hdaR3StreamGetPosition(PHDASTATE pThis, PHDASTREAM pStreamShared)
966{
967 return HDA_STREAM_REG(pThis, LPIB, pStreamShared->u8SD);
968}
969#endif
970
971/**
972 * Updates an HDA stream's current read or write buffer position (depending on the stream type) by
973 * setting its associated LPIB register and DMA position buffer (if enabled) to an absolute value.
974 *
975 * @param pStreamShared HDA stream to update read / write position for (shared).
976 * @param pDevIns The device instance.
977 * @param pThis The shared HDA device state.
978 * @param uLPIB Absolute position (in bytes) to set current read / write position to.
979 */
980static void hdaR3StreamSetPositionAbs(PHDASTREAM pStreamShared, PPDMDEVINS pDevIns, PHDASTATE pThis, uint32_t uLPIB)
981{
982 AssertPtrReturnVoid(pStreamShared);
983 AssertReturnVoid (uLPIB <= pStreamShared->u32CBL); /* Make sure that we don't go out-of-bounds. */
984
985 Log3Func(("[SD%RU8] LPIB=%RU32 (DMA Position Buffer Enabled: %RTbool)\n", pStreamShared->u8SD, uLPIB, pThis->fDMAPosition));
986
987 /* Update LPIB in any case. */
988 HDA_STREAM_REG(pThis, LPIB, pStreamShared->u8SD) = uLPIB;
989
990 /* Do we need to tell the current DMA position? */
991 if (pThis->fDMAPosition)
992 {
993 int rc2 = PDMDevHlpPCIPhysWrite(pDevIns,
994 pThis->u64DPBase + (pStreamShared->u8SD * 2 * sizeof(uint32_t)),
995 (void *)&uLPIB, sizeof(uint32_t));
996 AssertRC(rc2);
997 }
998}
999
1000/**
1001 * Updates an HDA stream's current read or write buffer position (depending on the stream type) by
1002 * adding a value to its associated LPIB register and DMA position buffer (if enabled).
1003 *
1004 * @note Handles automatic CBL wrap-around.
1005 *
1006 * @param pStreamShared HDA stream to update read / write position for (shared).
1007 * @param pDevIns The device instance.
1008 * @param pThis The shared HDA device state.
1009 * @param cbToAdd Position (in bytes) to add to the current read / write position.
1010 */
1011void hdaR3StreamSetPositionAdd(PHDASTREAM pStreamShared, PPDMDEVINS pDevIns, PHDASTATE pThis, uint32_t cbToAdd)
1012{
1013 if (cbToAdd) /* No need to update anything if 0. */
1014 {
1015 uint32_t const uCBL = pStreamShared->u32CBL;
1016 if (uCBL) /* paranoia */
1017 hdaR3StreamSetPositionAbs(pStreamShared, pDevIns, pThis,
1018 (HDA_STREAM_REG(pThis, LPIB, pStreamShared->u8SD) + cbToAdd) % uCBL);
1019 }
1020}
1021
1022/**
1023 * Retrieves the available size of (buffered) audio data (in bytes) of a given HDA stream.
1024 *
1025 * @returns Available data (in bytes).
1026 * @param pStreamR3 HDA stream to retrieve size for (ring-3).
1027 */
1028static uint32_t hdaR3StreamGetUsed(PHDASTREAMR3 pStreamR3)
1029{
1030 AssertPtrReturn(pStreamR3, 0);
1031
1032 if (pStreamR3->State.pCircBuf)
1033 return (uint32_t)RTCircBufUsed(pStreamR3->State.pCircBuf);
1034 return 0;
1035}
1036
1037/**
1038 * Retrieves the free size of audio data (in bytes) of a given HDA stream.
1039 *
1040 * @returns Free data (in bytes).
1041 * @param pStreamR3 HDA stream to retrieve size for (ring-3).
1042 */
1043static uint32_t hdaR3StreamGetFree(PHDASTREAMR3 pStreamR3)
1044{
1045 AssertPtrReturn(pStreamR3, 0);
1046
1047 if (pStreamR3->State.pCircBuf)
1048 return (uint32_t)RTCircBufFree(pStreamR3->State.pCircBuf);
1049 return 0;
1050}
1051
1052/**
1053 * Get the current address and number of bytes left in the current BDLE.
1054 *
1055 * @returns The current physical address.
1056 * @param pStreamShared The stream to check.
1057 * @param pcbLeft The number of bytes left at the returned address.
1058 */
1059DECLINLINE(RTGCPHYS) hdaR3StreamDmaBufGet(PHDASTREAM pStreamShared, uint32_t *pcbLeft)
1060{
1061 uint8_t idxBdle = pStreamShared->State.idxCurBdle;
1062 AssertStmt(idxBdle < pStreamShared->State.cBdles, idxBdle = 0);
1063
1064 uint32_t const cbCurBdl = pStreamShared->State.aBdl[idxBdle].cb;
1065 uint32_t offCurBdle = pStreamShared->State.offCurBdle;
1066 AssertStmt(pStreamShared->State.offCurBdle <= cbCurBdl, offCurBdle = cbCurBdl);
1067
1068 *pcbLeft = cbCurBdl - offCurBdle;
1069 return pStreamShared->State.aBdl[idxBdle].GCPhys + offCurBdle;
1070}
1071
1072/**
1073 * Get the size of the current BDLE.
1074 *
1075 * @returns The size (in bytes).
1076 * @param pStreamShared The stream to check.
1077 */
1078DECLINLINE(RTGCPHYS) hdaR3StreamDmaBufGetSize(PHDASTREAM pStreamShared)
1079{
1080 uint8_t idxBdle = pStreamShared->State.idxCurBdle;
1081 AssertStmt(idxBdle < pStreamShared->State.cBdles, idxBdle = 0);
1082 return pStreamShared->State.aBdl[idxBdle].cb;
1083}
1084
1085/**
1086 * Checks if the current BDLE is completed.
1087 *
1088 * @retval true if complete
1089 * @retval false if not.
1090 * @param pStreamShared The stream to check.
1091 */
1092DECLINLINE(bool) hdaR3StreamDmaBufIsComplete(PHDASTREAM pStreamShared)
1093{
1094 uint8_t const idxBdle = pStreamShared->State.idxCurBdle;
1095 AssertReturn(idxBdle < pStreamShared->State.cBdles, true);
1096
1097 uint32_t const cbCurBdl = pStreamShared->State.aBdl[idxBdle].cb;
1098 uint32_t const offCurBdle = pStreamShared->State.offCurBdle;
1099 Assert(offCurBdle <= cbCurBdl);
1100 return offCurBdle >= cbCurBdl;
1101}
1102
1103/**
1104 * Checks if the current BDLE needs a completion IRQ.
1105 *
1106 * @retval true if IRQ is needed.
1107 * @retval false if not.
1108 * @param pStreamShared The stream to check.
1109 */
1110DECLINLINE(bool) hdaR3StreamDmaBufNeedsIrq(PHDASTREAM pStreamShared)
1111{
1112 uint8_t const idxBdle = pStreamShared->State.idxCurBdle;
1113 AssertReturn(idxBdle < pStreamShared->State.cBdles, false);
1114 return (pStreamShared->State.aBdl[idxBdle].fFlags & HDA_BDLE_F_IOC) != 0;
1115}
1116
1117/**
1118 * Advances the DMA engine to the next BDLE.
1119 *
1120 * @param pStreamShared The stream which DMA engine is to be updated.
1121 */
1122DECLINLINE(void) hdaR3StreamDmaBufAdvanceToNext(PHDASTREAM pStreamShared)
1123{
1124 uint8_t idxBdle = pStreamShared->State.idxCurBdle;
1125 Assert(pStreamShared->State.offCurBdle == pStreamShared->State.aBdl[idxBdle].cb);
1126
1127 if (idxBdle < pStreamShared->State.cBdles - 1)
1128 idxBdle++;
1129 else
1130 idxBdle = 0;
1131 pStreamShared->State.idxCurBdle = idxBdle;
1132 pStreamShared->State.offCurBdle = 0;
1133}
1134
1135/**
1136 * Common do-DMA prologue code.
1137 *
1138 * @retval true if DMA processing can take place
1139 * @retval false if caller should return immediately.
1140 * @param pThis The shared HDA device state.
1141 * @param pStreamShared HDA stream to update (shared).
1142 * @param uSD The stream ID (for asserting).
1143 * @param tsNowNs The current RTTimeNano() value.
1144 * @param pszFunction The function name (for logging).
1145 */
1146DECLINLINE(bool) hdaR3StreamDoDmaPrologue(PHDASTATE pThis, PHDASTREAM pStreamShared, uint8_t uSD,
1147 uint64_t tsNowNs, const char *pszFunction)
1148{
1149 RT_NOREF(uSD, pszFunction);
1150
1151 /*
1152 * Check if we should skip town...
1153 */
1154 /* Stream not running (anymore)? */
1155 if (pStreamShared->State.fRunning)
1156 { /* likely */ }
1157 else
1158 {
1159 Log3(("%s: [SD%RU8] Not running, skipping transfer\n", pszFunction, uSD));
1160 return false;
1161 }
1162
1163 if (!(HDA_STREAM_REG(pThis, STS, uSD) & HDA_SDSTS_BCIS))
1164 { /* likely */ }
1165 else
1166 {
1167 Log3(("%s: [SD%RU8] BCIS bit set, skipping transfer\n", pszFunction, uSD));
1168#ifdef HDA_STRICT
1169 /* Timing emulation bug or guest is misbehaving -- let me know. */
1170 AssertMsgFailed(("%s: BCIS bit for stream #%RU8 still set when it shouldn't\n", pszFunction, uSD));
1171#endif
1172 return false;
1173 }
1174
1175 /*
1176 * Stream sanity checks.
1177 */
1178 /* Register sanity checks. */
1179 Assert(uSD < HDA_MAX_STREAMS);
1180 Assert(pStreamShared->u64BDLBase);
1181 Assert(pStreamShared->u32CBL);
1182 Assert(pStreamShared->u8FIFOS);
1183
1184 /* State sanity checks. */
1185 Assert(ASMAtomicReadBool(&pStreamShared->State.fInReset) == false);
1186 Assert(ASMAtomicReadBool(&pStreamShared->State.fRunning));
1187
1188 /*
1189 * Some timestamp stuff for logging/debugging.
1190 */
1191 /*const uint64_t tsNowNs = RTTimeNanoTS();*/
1192 Log3(("%s: [SD%RU8] tsDeltaNs=%'RU64 ns\n", pszFunction, uSD, tsNowNs - pStreamShared->State.tsLastTransferNs));
1193 pStreamShared->State.tsLastTransferNs = tsNowNs;
1194
1195 /*
1196 * Set the FIFORDY bit on the stream while doing the transfer.
1197 */
1198 /** @todo r=bird: I don't get the HDA_SDSTS_FIFORDY logic. Unless we're
1199 * assuming SMP guest and that it can get stream registers while we're
1200 * here. Only it cannot do the later because we're sitting on the big
1201 * HDA device lock, see assertions in hdaR3Timer(). So, this is an
1202 * pointless guesture given that we clear it again after the loop. */
1203 HDA_STREAM_REG(pThis, STS, uSD) |= HDA_SDSTS_FIFORDY;
1204
1205 return true;
1206}
1207
1208/**
1209 * Common do-DMA epilogue.
1210 *
1211 * @param pDevIns The device instance.
1212 * @param pThis The shared HDA device state.
1213 * @param pStreamShared HDA stream to update (shared).
1214 */
1215DECLINLINE(void) hdaR3StreamDoDmaEpilogue(PPDMDEVINS pDevIns, PHDASTATE pThis, PHDASTREAM pStreamShared)
1216{
1217 /*
1218 * Clear the (pointless) FIFORDY bit again.
1219 */
1220 HDA_STREAM_REG(pThis, STS, pStreamShared->u8SD) &= ~HDA_SDSTS_FIFORDY;
1221
1222 /*
1223 * We must update this in the epilogue rather than in the prologue
1224 * as it is used for WALCLK calculation and we must make sure the
1225 * guest doesn't think we've processed the current period till we
1226 * actually have.
1227 */
1228 pStreamShared->State.tsTransferLast = PDMDevHlpTimerGet(pDevIns, pStreamShared->hTimer);
1229}
1230
1231/**
1232 * Completes a BDLE at the end of a DMA loop iteration, if possible.
1233 *
1234 * @param pDevIns The device instance.
1235 * @param pThis The shared HDA device state.
1236 * @param pStreamShared HDA stream to update (shared).
1237 * @param pszFunction The function name (for logging).
1238 */
1239DECLINLINE(void) hdaR3StreamDoDmaMaybeCompleteBuffer(PPDMDEVINS pDevIns, PHDASTATE pThis,
1240 PHDASTREAM pStreamShared, const char *pszFunction)
1241{
1242 RT_NOREF(pszFunction);
1243
1244 /*
1245 * Is the buffer descriptor complete.
1246 */
1247 if (hdaR3StreamDmaBufIsComplete(pStreamShared))
1248 {
1249 Log3(("%s: [SD%RU8] Completed BDLE%u %#RX64 LB %#RX32 fFlags=%#x\n", pszFunction, pStreamShared->u8SD,
1250 pStreamShared->State.idxCurBdle, pStreamShared->State.aBdl[pStreamShared->State.idxCurBdle].GCPhys,
1251 pStreamShared->State.aBdl[pStreamShared->State.idxCurBdle].cb,
1252 pStreamShared->State.aBdl[pStreamShared->State.idxCurBdle].fFlags));
1253
1254 /*
1255 * Update the stream's current position.
1256 *
1257 * Do this as accurate and close to the actual data transfer as possible.
1258 * All guetsts rely on this, depending on the mechanism they use (LPIB register or DMA counters).
1259 *
1260 * Note for Windows 10: The OS' driver is *very* picky about *when* the (DMA) positions get updated!
1261 * Not doing this at the right time will result in ugly sound crackles!
1262 */
1263 hdaR3StreamSetPositionAdd(pStreamShared, pDevIns, pThis, hdaR3StreamDmaBufGetSize(pStreamShared));
1264
1265 /* Does the current BDLE require an interrupt to be sent? */
1266 if (hdaR3StreamDmaBufNeedsIrq(pStreamShared))
1267 {
1268 /* If the IOCE ("Interrupt On Completion Enable") bit of the SDCTL
1269 register is set we need to generate an interrupt. */
1270 if (HDA_STREAM_REG(pThis, CTL, pStreamShared->u8SD) & HDA_SDCTL_IOCE)
1271 {
1272 /* Assert the interrupt before actually fetching the next BDLE below. */
1273 pStreamShared->State.cTransferPendingInterrupts = 1;
1274 Log3(("%s: [SD%RU8] Scheduling interrupt\n", pszFunction, pStreamShared->u8SD));
1275
1276 /* Trigger an interrupt first and let hdaRegWriteSDSTS() deal with
1277 * ending / beginning of a period. */
1278 /** @todo r=bird: What does the above comment mean? */
1279 HDA_STREAM_REG(pThis, STS, pStreamShared->u8SD) |= HDA_SDSTS_BCIS;
1280 HDA_PROCESS_INTERRUPT(pDevIns, pThis);
1281 }
1282 }
1283
1284 /*
1285 * Advance to the next BDLE.
1286 */
1287 hdaR3StreamDmaBufAdvanceToNext(pStreamShared);
1288 }
1289 else
1290 Log3(("%s: [SD%RU8] Not completed BDLE%u %#RX64 LB %#RX32 fFlags=%#x: off=%#RX32\n", pszFunction, pStreamShared->u8SD,
1291 pStreamShared->State.idxCurBdle, pStreamShared->State.aBdl[pStreamShared->State.idxCurBdle].GCPhys,
1292 pStreamShared->State.aBdl[pStreamShared->State.idxCurBdle].cb,
1293 pStreamShared->State.aBdl[pStreamShared->State.idxCurBdle].fFlags, pStreamShared->State.offCurBdle));
1294}
1295
1296/**
1297 * Does DMA transfer for an HDA input stream.
1298 *
1299 * Reads audio data from the HDA stream's internal DMA buffer and writing to
1300 * guest memory.
1301 *
1302 * @param pDevIns The device instance.
1303 * @param pThis The shared HDA device state.
1304 * @param pStreamShared HDA stream to update (shared).
1305 * @param pStreamR3 HDA stream to update (ring-3).
1306 * @param cbToConsume The max amount of data to consume from the
1307 * internal DMA buffer. The caller will make sure
1308 * this is always the transfer size fo the current
1309 * period (unless something is seriously wrong).
1310 * @param fWriteSilence Whether to feed the guest silence rather than
1311 * fetching bytes from the internal DMA buffer.
1312 * This is set initially while we pre-buffer a
1313 * little bit of input, so we can better handle
1314 * time catch-ups and other schduling fun.
1315 * @param tsNowNs The current RTTimeNano() value.
1316 *
1317 * @remarks Caller owns the stream lock.
1318 */
1319static void hdaR3StreamDoDmaInput(PPDMDEVINS pDevIns, PHDASTATE pThis, PHDASTREAM pStreamShared,
1320 PHDASTREAMR3 pStreamR3, uint32_t cbToConsume, bool fWriteSilence, uint64_t tsNowNs)
1321{
1322 uint8_t const uSD = pStreamShared->u8SD;
1323 LogFlowFunc(("ENTER - #%u cbToConsume=%#x%s\n", uSD, cbToConsume, fWriteSilence ? " silence" : ""));
1324
1325 /*
1326 * Common prologue.
1327 */
1328 if (hdaR3StreamDoDmaPrologue(pThis, pStreamShared, uSD, tsNowNs, "hdaR3StreamDoDmaInput"))
1329 { /* likely */ }
1330 else
1331 return;
1332
1333 /*
1334 *
1335 * The DMA copy loop.
1336 *
1337 */
1338 uint8_t abBounce[4096 + 128]; /* Most guest does at most 4KB BDLE. So, 4KB + space for a partial frame to reduce loops. */
1339 uint32_t cbBounce = 0; /* in case of incomplete frames between buffer segments */
1340 PRTCIRCBUF pCircBuf = pStreamR3->State.pCircBuf;
1341 uint32_t cbLeft = cbToConsume;
1342 Assert(cbLeft == pStreamShared->State.cbTransferSize);
1343 Assert(PDMAudioPropsIsSizeAligned(&pStreamShared->State.Cfg.Props, cbLeft));
1344
1345 while (cbLeft > 0)
1346 {
1347 STAM_PROFILE_START(&pThis->StatIn, a);
1348
1349 /*
1350 * Figure out how much we can read & write in this iteration.
1351 */
1352 uint32_t cbChunk = 0;
1353 RTGCPHYS GCPhys = hdaR3StreamDmaBufGet(pStreamShared, &cbChunk);
1354
1355 /* Need to diverge if the frame format differs or if we're writing silence. */
1356 if ( !pStreamR3->State.Mapping.fMappingNeeded
1357 && !fWriteSilence)
1358 {
1359 if (cbChunk <= cbLeft)
1360 { /* very likely */ }
1361 else
1362 cbChunk = cbLeft;
1363
1364 /*
1365 * Write the host data directly into the guest buffers.
1366 */
1367 while (cbChunk > 0)
1368 {
1369 /* Grab internal DMA buffer space and read into it. */
1370 void /*const*/ *pvBufSrc;
1371 size_t cbBufSrc;
1372 RTCircBufAcquireReadBlock(pCircBuf, cbChunk, &pvBufSrc, &cbBufSrc);
1373 AssertBreakStmt(cbBufSrc, RTCircBufReleaseReadBlock(pCircBuf, 0));
1374
1375 int rc2 = PDMDevHlpPCIPhysWrite(pDevIns, GCPhys, pvBufSrc, cbBufSrc);
1376 AssertRC(rc2);
1377
1378#ifdef HDA_DEBUG_SILENCE
1379 fix me if relevant;
1380#endif
1381 if (RT_LIKELY(!pStreamR3->Dbg.Runtime.fEnabled))
1382 { /* likely */ }
1383 else
1384 DrvAudioHlpFileWrite(pStreamR3->Dbg.Runtime.pFileDMARaw, pvBufSrc, cbBufSrc, 0 /* fFlags */);
1385
1386#ifdef VBOX_WITH_DTRACE
1387 VBOXDD_HDA_STREAM_DMA_IN((uint32_t)uSD, (uint32_t)cbBufSrc, pStreamR3->State.offRead);
1388#endif
1389 pStreamR3->State.offRead += cbBufSrc;
1390 RTCircBufReleaseReadBlock(pCircBuf, cbBufSrc);
1391 STAM_COUNTER_ADD(&pThis->StatBytesRead, cbBufSrc);
1392
1393 /* advance */
1394 cbChunk -= (uint32_t)cbBufSrc;
1395 GCPhys += cbBufSrc;
1396 cbLeft -= (uint32_t)cbBufSrc;
1397 pStreamShared->State.offCurBdle += (uint32_t)cbBufSrc;
1398 }
1399 }
1400 /*
1401 * Either we've got some initial silence to write, or we need to do
1402 * channel mapping. Both produces guest output into the bounce buffer,
1403 * which is then copied into guest memory. The bounce buffer may keep
1404 * partial frames there for the next BDLE, if an BDLE isn't frame aligned.
1405 *
1406 * Note! cbLeft is relative to the input (host) frame size.
1407 * cbChunk OTOH is relative to output (guest) size.
1408 */
1409 else
1410 {
1411 Assert(PDMAudioPropsIsSizeAligned(&pStreamShared->State.Cfg.Props, cbLeft));
1412 uint32_t const cbLeftGuest = PDMAudioPropsFramesToBytes(&pStreamR3->State.Mapping.GuestProps,
1413 PDMAudioPropsBytesToFrames(&pStreamShared->State.Cfg.Props,
1414 cbLeft));
1415 if (cbChunk <= cbLeftGuest)
1416 { /* very likely */ }
1417 else
1418 cbChunk = cbLeftGuest;
1419
1420 /*
1421 * Work till we've covered the chunk.
1422 */
1423 Log5Func(("loop0: GCPhys=%RGp cbChunk=%#x + cbBounce=%#x\n", GCPhys, cbChunk, cbBounce));
1424 while (cbChunk > 0)
1425 {
1426 /* Figure out how much we need to convert into the bounce buffer: */
1427 uint32_t cbGuest = PDMAudioPropsRoundUpBytesToFrame(&pStreamR3->State.Mapping.GuestProps, cbChunk - cbBounce);
1428 uint32_t cFrames = PDMAudioPropsBytesToFrames(&pStreamR3->State.Mapping.GuestProps,
1429 RT_MIN(cbGuest, sizeof(abBounce) - cbBounce));
1430 size_t cbBufSrc;
1431 if (!fWriteSilence)
1432 {
1433 /** @todo we could loop here to optimize buffer wrap around. Not important now though. */
1434 void /*const*/ *pvBufSrc;
1435 RTCircBufAcquireReadBlock(pCircBuf, PDMAudioPropsFramesToBytes(&pStreamShared->State.Cfg.Props, cFrames),
1436 &pvBufSrc, &cbBufSrc);
1437
1438 uint32_t const cFramesToConvert = PDMAudioPropsBytesToFrames(&pStreamShared->State.Cfg.Props,
1439 (uint32_t)cbBufSrc);
1440 Assert(PDMAudioPropsFramesToBytes(&pStreamShared->State.Cfg.Props, cFramesToConvert) == cbBufSrc);
1441 Assert(cFramesToConvert > 0);
1442 Assert(cFramesToConvert <= cFrames);
1443
1444 pStreamR3->State.Mapping.pfnHostToGuest(&abBounce[cbBounce], pvBufSrc, cFramesToConvert,
1445 &pStreamR3->State.Mapping);
1446 Log5Func((" loop1: cbBounce=%#05x cFramesToConvert=%#05x cbBufSrc=%#x%s\n",
1447 cbBounce, cFramesToConvert, cbBufSrc, ASMMemIsZero(pvBufSrc, cbBufSrc) ? " all zero" : ""));
1448#ifdef HDA_DEBUG_SILENCE
1449 fix me if relevant;
1450#endif
1451 if (RT_LIKELY(!pStreamR3->Dbg.Runtime.fEnabled))
1452 { /* likely */ }
1453 else
1454 DrvAudioHlpFileWrite(pStreamR3->Dbg.Runtime.pFileDMARaw, pvBufSrc, cbBufSrc, 0 /* fFlags */);
1455
1456#ifdef VBOX_WITH_DTRACE
1457 VBOXDD_HDA_STREAM_DMA_IN((uint32_t)uSD, (uint32_t)cbBufSrc, pStreamR3->State.offRead);
1458#endif
1459
1460 pStreamR3->State.offRead += cbBufSrc;
1461 RTCircBufReleaseReadBlock(pCircBuf, cbBufSrc);
1462
1463 cFrames = cFramesToConvert;
1464 cbGuest = cbBounce + PDMAudioPropsFramesToBytes(&pStreamR3->State.Mapping.GuestProps, cFrames);
1465 }
1466 else
1467 {
1468 cbBufSrc = PDMAudioPropsFramesToBytes(&pStreamShared->State.Cfg.Props, cFrames);
1469 cbGuest = PDMAudioPropsFramesToBytes(&pStreamR3->State.Mapping.GuestProps, cFrames);
1470 PDMAudioPropsClearBuffer(&pStreamR3->State.Mapping.GuestProps,
1471 &abBounce[cbBounce], cbGuest, cFrames);
1472 cbGuest += cbBounce;
1473 }
1474
1475 /* Write it to the guest buffer. */
1476 uint32_t cbGuestActual = RT_MIN(cbGuest, cbChunk);
1477 int rc2 = PDMDevHlpPCIPhysWrite(pDevIns, GCPhys, abBounce, cbGuestActual);
1478 AssertRC(rc2);
1479 STAM_COUNTER_ADD(&pThis->StatBytesRead, cbGuestActual);
1480
1481 /* advance */
1482 cbLeft -= (uint32_t)cbBufSrc;
1483 cbChunk -= cbGuestActual;
1484 GCPhys += cbGuestActual;
1485 pStreamShared->State.offCurBdle += cbGuestActual;
1486
1487 cbBounce = cbGuest - cbGuestActual;
1488 if (cbBounce)
1489 memmove(abBounce, &abBounce[cbGuestActual], cbBounce);
1490
1491 Log5Func((" loop1: GCPhys=%RGp cbGuestActual=%#x cbBounce=%#x cFrames=%#x\n", GCPhys, cbGuestActual, cbBounce, cFrames));
1492 }
1493 Log5Func(("loop0: GCPhys=%RGp cbBounce=%#x cbLeft=%#x\n", GCPhys, cbBounce, cbLeft));
1494 }
1495
1496 STAM_PROFILE_STOP(&pThis->StatIn, a);
1497
1498 /*
1499 * Complete the buffer if necessary (common with the output DMA code).
1500 */
1501 hdaR3StreamDoDmaMaybeCompleteBuffer(pDevIns, pThis, pStreamShared, "hdaR3StreamDoDmaInput");
1502 }
1503
1504 Assert(cbLeft == 0); /* There shall be no break statements in the above loop, so cbLeft is always zero here! */
1505 AssertMsg(cbBounce == 0, ("%#x\n", cbBounce));
1506
1507 /*
1508 * Common epilogue.
1509 */
1510 hdaR3StreamDoDmaEpilogue(pDevIns, pThis, pStreamShared);
1511
1512 /*
1513 * Log and leave.
1514 */
1515 Log3Func(("LEAVE - [SD%RU8] %#RX32/%#RX32 @ %#RX64 - cTransferPendingInterrupts=%RU8\n",
1516 uSD, cbToConsume, pStreamShared->State.cbTransferSize, pStreamR3->State.offRead - cbToConsume,
1517 pStreamShared->State.cTransferPendingInterrupts));
1518}
1519
1520
1521/**
1522 * Input streams: Pulls data from to the host device thru the mixer, putting it
1523 * in the internal DMA buffer.
1524 *
1525 * @param pStreamShared HDA stream to update (shared bits).
1526 * @param pStreamR3 HDA stream to update (ring-3 bits).
1527 * @param pSink The mixer sink to push to.
1528 */
1529static void hdaR3StreamPullFromMixer(PHDASTREAM pStreamShared, PHDASTREAMR3 pStreamR3, PAUDMIXSINK pSink)
1530{
1531 RT_NOREF(pStreamShared);
1532 int rc = AudioMixerSinkUpdate(pSink);
1533 AssertRC(rc);
1534
1535 /* Is the sink ready to be read (host input data) from? If so, by how much? */
1536 uint32_t cbSinkReadable = AudioMixerSinkGetReadable(pSink);
1537
1538 /* How much (guest input) data is available for writing at the moment for the HDA stream? */
1539 const uint32_t cbStreamFree = hdaR3StreamGetFree(pStreamR3);
1540
1541 Log3Func(("[SD%RU8] cbSinkReadable=%RU32, cbStreamFree=%RU32\n", pStreamShared->u8SD, cbSinkReadable, cbStreamFree));
1542
1543 /* Do not read more than the HDA stream can hold at the moment.
1544 * The host sets the overall pace. */
1545 if (cbSinkReadable > cbStreamFree)
1546 cbSinkReadable = cbStreamFree;
1547
1548 /** @todo should we throttle (read less) this if we're far ahead? */
1549
1550 /*
1551 * Copy loop.
1552 */
1553 while (cbSinkReadable)
1554 {
1555 /* Read a chunk of data. */
1556 uint8_t abBuf[4096];
1557 uint32_t cbRead = 0;
1558 rc = AudioMixerSinkRead(pSink, AUDMIXOP_COPY, abBuf, RT_MIN(cbSinkReadable, sizeof(abBuf)), &cbRead);
1559 AssertRCBreak(rc);
1560 AssertMsg(cbRead > 0, ("Nothing read from sink, even if %RU32 bytes were (still) announced\n", cbSinkReadable));
1561
1562 /* Write it to the internal DMA buffer. */
1563 uint32_t off = 0;
1564 while (off < cbRead)
1565 {
1566 void *pvDstBuf;
1567 size_t cbDstBuf;
1568 RTCircBufAcquireWriteBlock(pStreamR3->State.pCircBuf, cbRead - off, &pvDstBuf, &cbDstBuf);
1569
1570 memcpy(pvDstBuf, &abBuf[off], cbDstBuf);
1571
1572#ifdef VBOX_WITH_DTRACE
1573 VBOXDD_HDA_STREAM_AIO_IN((uint32_t)pStreamR3->u8SD, (uint32_t)cbDstBuf, pStreamR3->State.offWrite);
1574#endif
1575 pStreamR3->State.offWrite += cbDstBuf;
1576
1577 RTCircBufReleaseWriteBlock(pStreamR3->State.pCircBuf, cbDstBuf);
1578
1579 off += (uint32_t)cbDstBuf;
1580 }
1581 Assert(off == cbRead);
1582
1583 /* Write to debug file? */
1584 if (RT_LIKELY(!pStreamR3->Dbg.Runtime.fEnabled))
1585 { /* likely */ }
1586 else
1587 DrvAudioHlpFileWrite(pStreamR3->Dbg.Runtime.pFileStream, abBuf, cbRead, 0 /* fFlags */);
1588
1589 /* Advance. */
1590 Assert(cbRead <= cbSinkReadable);
1591 cbSinkReadable -= cbRead;
1592 }
1593}
1594
1595/**
1596 * Does DMA transfer for an HDA output stream.
1597 *
1598 * This transfers one DMA timer period worth of data from the guest and into the
1599 * internal DMA buffer.
1600 *
1601 * @param pDevIns The device instance.
1602 * @param pThis The shared HDA device state.
1603 * @param pStreamShared HDA stream to update (shared).
1604 * @param pStreamR3 HDA stream to update (ring-3).
1605 * @param cbToProduce The max amount of data to produce (i.e. put into
1606 * the circular buffer). Unless something is going
1607 * seriously wrong, this will always be transfer
1608 * size for the current period.
1609 * @param tsNowNs The current RTTimeNano() value.
1610 *
1611 * @remarks Caller owns the stream lock.
1612 */
1613static void hdaR3StreamDoDmaOutput(PPDMDEVINS pDevIns, PHDASTATE pThis, PHDASTREAM pStreamShared,
1614 PHDASTREAMR3 pStreamR3, uint32_t cbToProduce, uint64_t tsNowNs)
1615{
1616 uint8_t const uSD = pStreamShared->u8SD;
1617 LogFlowFunc(("ENTER - #%u cbToProduce=%#x\n", uSD, cbToProduce));
1618
1619 /*
1620 * Common prologue.
1621 */
1622 if (hdaR3StreamDoDmaPrologue(pThis, pStreamShared, uSD, tsNowNs, "hdaR3StreamDoDmaOutput"))
1623 { /* likely */ }
1624 else
1625 return;
1626
1627 /*
1628 *
1629 * The DMA copy loop.
1630 *
1631 */
1632 uint8_t abBounce[4096 + 128]; /* Most guest does at most 4KB BDLE. So, 4KB + space for a partial frame to reduce loops. */
1633 uint32_t cbBounce = 0; /* in case of incomplete frames between buffer segments */
1634 PRTCIRCBUF pCircBuf = pStreamR3->State.pCircBuf;
1635 uint32_t cbLeft = cbToProduce;
1636 Assert(cbLeft == pStreamShared->State.cbTransferSize);
1637 Assert(PDMAudioPropsIsSizeAligned(&pStreamShared->State.Cfg.Props, cbLeft));
1638
1639 while (cbLeft > 0)
1640 {
1641 STAM_PROFILE_START(&pThis->StatOut, a);
1642
1643 /*
1644 * Figure out how much we can read & write in this iteration.
1645 */
1646 uint32_t cbChunk = 0;
1647 RTGCPHYS GCPhys = hdaR3StreamDmaBufGet(pStreamShared, &cbChunk);
1648
1649 /* Need to diverge if the frame format differs. */
1650 if ( !pStreamR3->State.Mapping.fMappingNeeded
1651 /** @todo && pStreamShared->State.fFrameAlignedBuffers */)
1652 {
1653 if (cbChunk <= cbLeft)
1654 { /* very likely */ }
1655 else
1656 cbChunk = cbLeft;
1657
1658 /*
1659 * Read the guest data directly into the internal DMA buffer.
1660 */
1661 while (cbChunk > 0)
1662 {
1663 /* Grab internal DMA buffer space and read into it. */
1664 void *pvBufDst;
1665 size_t cbBufDst;
1666 RTCircBufAcquireWriteBlock(pCircBuf, cbChunk, &pvBufDst, &cbBufDst);
1667 AssertBreakStmt(cbBufDst, RTCircBufReleaseWriteBlock(pCircBuf, 0));
1668
1669 int rc2 = PDMDevHlpPhysRead(pDevIns, GCPhys, pvBufDst, cbBufDst);
1670 AssertRC(rc2);
1671
1672#ifdef HDA_DEBUG_SILENCE
1673 fix me if relevant;
1674#endif
1675 if (RT_LIKELY(!pStreamR3->Dbg.Runtime.fEnabled))
1676 { /* likely */ }
1677 else
1678 DrvAudioHlpFileWrite(pStreamR3->Dbg.Runtime.pFileDMARaw, pvBufDst, cbBufDst, 0 /* fFlags */);
1679
1680#ifdef VBOX_WITH_DTRACE
1681 VBOXDD_HDA_STREAM_DMA_OUT((uint32_t)uSD, (uint32_t)cbBufDst, pStreamR3->State.offWrite);
1682#endif
1683 pStreamR3->State.offWrite += cbBufDst;
1684 RTCircBufReleaseWriteBlock(pCircBuf, cbBufDst);
1685 STAM_COUNTER_ADD(&pThis->StatBytesRead, cbBufDst);
1686
1687 /* advance */
1688 cbChunk -= (uint32_t)cbBufDst;
1689 GCPhys += cbBufDst;
1690 cbLeft -= (uint32_t)cbBufDst;
1691 pStreamShared->State.offCurBdle += (uint32_t)cbBufDst;
1692 }
1693 }
1694 /*
1695 * Need to map the frame content, so we need to read the guest data
1696 * into a temporary buffer, though the output can be directly written
1697 * into the internal buffer as it is assumed to be frame aligned.
1698 *
1699 * Note! cbLeft is relative to the output frame size.
1700 * cbChunk OTOH is relative to input size.
1701 */
1702 else
1703 {
1704 Assert(PDMAudioPropsIsSizeAligned(&pStreamShared->State.Cfg.Props, cbLeft));
1705 uint32_t const cbLeftGuest = PDMAudioPropsFramesToBytes(&pStreamR3->State.Mapping.GuestProps,
1706 PDMAudioPropsBytesToFrames(&pStreamShared->State.Cfg.Props,
1707 cbLeft));
1708 if (cbChunk <= cbLeftGuest)
1709 { /* very likely */ }
1710 else
1711 cbChunk = cbLeftGuest;
1712
1713 /*
1714 * Loop till we've covered the chunk.
1715 */
1716 Log5Func(("loop0: GCPhys=%RGp cbChunk=%#x + cbBounce=%#x\n", GCPhys, cbChunk, cbBounce));
1717 while (cbChunk > 0)
1718 {
1719 /* Read into the bounce buffer. */
1720 uint32_t const cbToRead = RT_MIN(cbChunk, sizeof(abBounce) - cbBounce);
1721 int rc2 = PDMDevHlpPhysRead(pDevIns, GCPhys, &abBounce[cbBounce], cbToRead);
1722 AssertRC(rc2);
1723 cbBounce += cbToRead;
1724
1725 /* Convert the size to whole frames and a remainder. */
1726 uint32_t cFrames = PDMAudioPropsBytesToFrames(&pStreamR3->State.Mapping.GuestProps, cbBounce);
1727 uint32_t const cbRemainder = cbBounce - PDMAudioPropsFramesToBytes(&pStreamR3->State.Mapping.GuestProps, cFrames);
1728 Log5Func((" loop1: GCPhys=%RGp cbToRead=%#x cbBounce=%#x cFrames=%#x\n", GCPhys, cbToRead, cbBounce, cFrames));
1729
1730 /*
1731 * Convert from the bounce buffer and into the internal DMA buffer.
1732 */
1733 uint32_t offBounce = 0;
1734 while (cFrames > 0)
1735 {
1736 void *pvBufDst;
1737 size_t cbBufDst;
1738 RTCircBufAcquireWriteBlock(pCircBuf, PDMAudioPropsFramesToBytes(&pStreamShared->State.Cfg.Props, cFrames),
1739 &pvBufDst, &cbBufDst);
1740
1741 uint32_t const cFramesToConvert = PDMAudioPropsBytesToFrames(&pStreamShared->State.Cfg.Props, (uint32_t)cbBufDst);
1742 Assert(PDMAudioPropsFramesToBytes(&pStreamShared->State.Cfg.Props, cFramesToConvert) == cbBufDst);
1743 Assert(cFramesToConvert > 0);
1744 Assert(cFramesToConvert <= cFrames);
1745
1746 pStreamR3->State.Mapping.pfnGuestToHost(pvBufDst, &abBounce[offBounce], cFramesToConvert,
1747 &pStreamR3->State.Mapping);
1748 Log5Func((" loop2: offBounce=%#05x cFramesToConvert=%#05x cbBufDst=%#x%s\n",
1749 offBounce, cFramesToConvert, cbBufDst, ASMMemIsZero(pvBufDst, cbBufDst) ? " all zero" : ""));
1750
1751# ifdef HDA_DEBUG_SILENCE
1752 fix me if relevant;
1753# endif
1754 if (RT_LIKELY(!pStreamR3->Dbg.Runtime.fEnabled))
1755 { /* likely */ }
1756 else
1757 DrvAudioHlpFileWrite(pStreamR3->Dbg.Runtime.pFileDMARaw, pvBufDst, cbBufDst, 0 /* fFlags */);
1758
1759 pStreamR3->State.offWrite += cbBufDst;
1760 RTCircBufReleaseWriteBlock(pCircBuf, cbBufDst);
1761 STAM_COUNTER_ADD(&pThis->StatBytesRead, cbBufDst);
1762
1763 /* advance */
1764 cbLeft -= (uint32_t)cbBufDst;
1765 cFrames -= cFramesToConvert;
1766 offBounce += PDMAudioPropsFramesToBytes(&pStreamR3->State.Mapping.GuestProps, cFramesToConvert);
1767 }
1768
1769 /* advance */
1770 cbChunk -= cbToRead;
1771 GCPhys += cbToRead;
1772 pStreamShared->State.offCurBdle += cbToRead;
1773 if (cbRemainder)
1774 memmove(&abBounce[0], &abBounce[cbBounce - cbRemainder], cbRemainder);
1775 cbBounce = cbRemainder;
1776 }
1777 Log5Func(("loop0: GCPhys=%RGp cbBounce=%#x cbLeft=%#x\n", GCPhys, cbBounce, cbLeft));
1778 }
1779
1780 STAM_PROFILE_STOP(&pThis->StatOut, a);
1781
1782 /*
1783 * Complete the buffer if necessary (common with the output DMA code).
1784 */
1785 hdaR3StreamDoDmaMaybeCompleteBuffer(pDevIns, pThis, pStreamShared, "hdaR3StreamDoDmaOutput");
1786 }
1787
1788 Assert(cbLeft == 0); /* There shall be no break statements in the above loop, so cbLeft is always zero here! */
1789 AssertMsg(cbBounce == 0, ("%#x\n", cbBounce));
1790
1791 /*
1792 * Common epilogue.
1793 */
1794 hdaR3StreamDoDmaEpilogue(pDevIns, pThis, pStreamShared);
1795
1796 /*
1797 * Log and leave.
1798 */
1799 Log3Func(("LEAVE - [SD%RU8] %#RX32/%#RX32 @ %#RX64 - cTransferPendingInterrupts=%RU8\n",
1800 uSD, cbToProduce, pStreamShared->State.cbTransferSize, pStreamR3->State.offWrite - cbToProduce,
1801 pStreamShared->State.cTransferPendingInterrupts));
1802}
1803
1804/**
1805 * Output streams: Pushes data from to the mixer and host device.
1806 *
1807 * @param pStreamShared HDA stream to update (shared bits).
1808 * @param pStreamR3 HDA stream to update (ring-3 bits).
1809 * @param pSink The mixer sink to push to.
1810 * @param nsNow The current RTTimeNanoTS() value.
1811 */
1812static void hdaR3StreamPushToMixer(PHDASTREAM pStreamShared, PHDASTREAMR3 pStreamR3, PAUDMIXSINK pSink, uint64_t nsNow)
1813{
1814 /*
1815 * Figure how much that we can push down.
1816 */
1817 uint32_t const cbSinkWritable = AudioMixerSinkGetWritable(pSink);
1818 uint32_t const cbStreamReadable = hdaR3StreamGetUsed(pStreamR3);
1819 uint32_t cbToReadFromStream = RT_MIN(cbStreamReadable, cbSinkWritable);
1820 /* Make sure that we always align the number of bytes when reading to the stream's PCM properties. */
1821 cbToReadFromStream = PDMAudioPropsFloorBytesToFrame(&pStreamShared->State.Cfg.Props, cbToReadFromStream);
1822
1823 Assert(nsNow >= pStreamShared->State.tsLastReadNs);
1824 Log3Func(("[SD%RU8] nsDeltaLastRead=%RI64 cbSinkWritable=%RU32 cbStreamReadable=%RU32 -> cbToReadFromStream=%RU32\n",
1825 pStreamShared->u8SD, nsNow - pStreamShared->State.tsLastReadNs, cbSinkWritable, cbStreamReadable, cbToReadFromStream));
1826 RT_NOREF(pStreamShared, nsNow);
1827
1828 /*
1829 * Do the pushing.
1830 */
1831 Assert(pStreamR3->State.pCircBuf);
1832 while (cbToReadFromStream > 0)
1833 {
1834 void /*const*/ *pvSrcBuf;
1835 size_t cbSrcBuf;
1836 RTCircBufAcquireReadBlock(pStreamR3->State.pCircBuf, cbToReadFromStream, &pvSrcBuf, &cbSrcBuf);
1837
1838 if (!pStreamR3->Dbg.Runtime.fEnabled)
1839 { /* likely */ }
1840 else
1841 DrvAudioHlpFileWrite(pStreamR3->Dbg.Runtime.pFileStream, pvSrcBuf, cbSrcBuf, 0 /* fFlags */);
1842
1843 uint32_t cbWritten = 0;
1844 int rc = AudioMixerSinkWrite(pSink, AUDMIXOP_COPY, pvSrcBuf, (uint32_t)cbSrcBuf, &cbWritten);
1845 AssertRC(rc);
1846 Assert(cbWritten <= cbSrcBuf);
1847
1848 Log2Func(("[SD%RU8] %#RX32/%#zx bytes read @ %#RX64\n", pStreamR3->u8SD, cbWritten, cbSrcBuf, pStreamR3->State.offRead));
1849#ifdef VBOX_WITH_DTRACE
1850 VBOXDD_HDA_STREAM_AIO_OUT(pStreamR3->u8SD, cbWritten, pStreamR3->State.offRead);
1851#endif
1852 pStreamR3->State.offRead += cbWritten;
1853
1854 RTCircBufReleaseReadBlock(pStreamR3->State.pCircBuf, cbWritten);
1855
1856 /* advance */
1857 cbToReadFromStream -= cbWritten;
1858 }
1859
1860 int rc2 = AudioMixerSinkUpdate(pSink);
1861 AssertRC(rc2);
1862}
1863
1864/**
1865 * The stream's main function when called by the timer.
1866 *
1867 * @note This function also will be called without timer invocation when
1868 * starting (enabling) the stream to minimize startup latency.
1869 *
1870 * @returns Current timer time if the timer is enabled, otherwise zero.
1871 * @param pDevIns The device instance.
1872 * @param pThis The shared HDA device state.
1873 * @param pThisCC The ring-3 HDA device state.
1874 * @param pStreamShared HDA stream to update (shared bits).
1875 * @param pStreamR3 HDA stream to update (ring-3 bits).
1876 */
1877uint64_t hdaR3StreamTimerMain(PPDMDEVINS pDevIns, PHDASTATE pThis, PHDASTATER3 pThisCC,
1878 PHDASTREAM pStreamShared, PHDASTREAMR3 pStreamR3)
1879{
1880 Assert(PDMDevHlpCritSectIsOwner(pDevIns, &pThis->CritSect));
1881 Assert(PDMDevHlpTimerIsLockOwner(pDevIns, pStreamShared->hTimer));
1882
1883 /* Do the work: */
1884 hdaR3StreamUpdate(pDevIns, pThis, pThisCC, pStreamShared, pStreamR3, true /* fInTimer */);
1885
1886 /* Re-arm the timer if the sink is still active: */
1887 if ( pStreamShared->State.fRunning
1888 && pStreamR3->pMixSink
1889 && AudioMixerSinkIsActive(pStreamR3->pMixSink->pMixSink))
1890 {
1891 /* Advance the schduling: */
1892 uint32_t idxSched = pStreamShared->State.idxSchedule;
1893 AssertStmt(idxSched < RT_ELEMENTS(pStreamShared->State.aSchedule), idxSched = 0);
1894 uint32_t idxLoop = pStreamShared->State.idxScheduleLoop + 1;
1895 if (idxLoop >= pStreamShared->State.aSchedule[idxSched].cLoops)
1896 {
1897 idxSched += 1;
1898 if ( idxSched >= pStreamShared->State.cSchedule
1899 || idxSched >= RT_ELEMENTS(pStreamShared->State.aSchedule) /*paranoia^2*/)
1900 {
1901 idxSched = pStreamShared->State.cSchedulePrologue;
1902 AssertStmt(idxSched < RT_ELEMENTS(pStreamShared->State.aSchedule), idxSched = 0);
1903 }
1904 pStreamShared->State.idxSchedule = idxSched;
1905 idxLoop = 0;
1906 }
1907 pStreamShared->State.idxScheduleLoop = (uint16_t)idxLoop;
1908
1909 /* Do the actual timer re-arming. */
1910 uint64_t const tsNow = PDMDevHlpTimerGet(pDevIns, pStreamShared->hTimer); /* (For virtual sync this remains the same for the whole callout IIRC) */
1911 uint64_t const tsTransferNext = tsNow + pStreamShared->State.aSchedule[idxSched].cPeriodTicks;
1912 Log3Func(("[SD%RU8] fSinkActive=true, tsTransferNext=%RU64 (in %RU64)\n",
1913 pStreamShared->u8SD, tsTransferNext, tsTransferNext - tsNow));
1914 int rc = PDMDevHlpTimerSet(pDevIns, pStreamShared->hTimer, tsTransferNext);
1915 AssertRC(rc);
1916
1917 /* Some legacy stuff: */
1918 pStreamShared->State.tsTransferNext = tsTransferNext;
1919 pStreamShared->State.cbTransferSize = pStreamShared->State.aSchedule[idxSched].cbPeriod;
1920
1921 return tsNow;
1922 }
1923
1924 Log3Func(("[SD%RU8] fSinkActive=false\n", pStreamShared->u8SD));
1925 return 0;
1926}
1927
1928/**
1929 * Updates a HDA stream by doing its required data transfers.
1930 *
1931 * The host sink(s) set the overall pace.
1932 *
1933 * This routine is called by both, the synchronous and the asynchronous
1934 * (VBOX_WITH_AUDIO_HDA_ASYNC_IO), implementations.
1935 *
1936 * When running synchronously, the device DMA transfers *and* the mixer sink
1937 * processing is within the device timer.
1938 *
1939 * When running asynchronously, only the device DMA transfers are done in the
1940 * device timer, whereas the mixer sink processing then is done in the stream's
1941 * own async I/O thread. This thread also will call this function
1942 * (with fInTimer set to @c false).
1943 *
1944 * @param pDevIns The device instance.
1945 * @param pThis The shared HDA device state.
1946 * @param pThisCC The ring-3 HDA device state.
1947 * @param pStreamShared HDA stream to update (shared bits).
1948 * @param pStreamR3 HDA stream to update (ring-3 bits).
1949 * @param fInTimer Whether to this function was called from the timer
1950 * context or an asynchronous I/O stream thread (if supported).
1951 */
1952void hdaR3StreamUpdate(PPDMDEVINS pDevIns, PHDASTATE pThis, PHDASTATER3 pThisCC,
1953 PHDASTREAM pStreamShared, PHDASTREAMR3 pStreamR3, bool fInTimer)
1954{
1955 RT_NOREF(pThisCC);
1956 int rc2;
1957
1958 /*
1959 * Make sure we're running and got an active mixer sink.
1960 */
1961 if (RT_LIKELY(pStreamShared->State.fRunning))
1962 { /* likely */ }
1963 else
1964 return;
1965
1966 PAUDMIXSINK pSink = NULL;
1967 if (pStreamR3->pMixSink)
1968 pSink = pStreamR3->pMixSink->pMixSink;
1969 if (RT_LIKELY(AudioMixerSinkIsActive(pSink)))
1970 { /* likely */ }
1971 else
1972 return;
1973
1974 /*
1975 * Get scheduling info common to both input and output streams.
1976 */
1977 const uint64_t tsNowNs = RTTimeNanoTS();
1978 uint32_t idxSched = pStreamShared->State.idxSchedule;
1979 AssertStmt(idxSched < RT_MIN(RT_ELEMENTS(pStreamShared->State.aSchedule), pStreamShared->State.cSchedule), idxSched = 0);
1980 uint32_t const cbPeriod = pStreamShared->State.aSchedule[idxSched].cbPeriod;
1981
1982 /*
1983 * Output streams (SDO).
1984 */
1985 if (hdaGetDirFromSD(pStreamShared->u8SD) == PDMAUDIODIR_OUT)
1986 {
1987 bool fDoRead; /* Whether to push data down the driver stack or not. */
1988# ifdef VBOX_WITH_AUDIO_HDA_ASYNC_IO
1989 if (fInTimer)
1990# endif
1991 {
1992 /*
1993 * Check how much room we have in our DMA buffer. There should be at
1994 * least one period worth of space there or we're in an overflow situation.
1995 */
1996 uint32_t cbStreamFree = hdaR3StreamGetFree(pStreamR3);
1997 if (cbStreamFree >= cbPeriod)
1998 { /* likely */ }
1999 else
2000 {
2001 STAM_REL_COUNTER_INC(&pStreamR3->State.StatDmaFlowProblems);
2002 Log(("hdaR3StreamUpdate: Warning! Stream #%u has insufficient space free: %u bytes, need %u. Will try move data out of the buffer...\n",
2003 pStreamShared->u8SD, cbStreamFree, cbPeriod));
2004# ifdef VBOX_WITH_AUDIO_HDA_ASYNC_IO
2005 int rc = RTCritSectTryEnter(&pStreamR3->State.AIO.CritSect);
2006 if (RT_SUCCESS(rc))
2007 {
2008 hdaR3StreamPushToMixer(pStreamShared, pStreamR3, pSink, tsNowNs);
2009 RTCritSectLeave(&pStreamR3->State.AIO.CritSect);
2010 }
2011 else
2012 RTThreadYield();
2013#else
2014 hdaR3StreamPushToMixer(pStreamShared, pStreamR3, pSink, tsNowNs);
2015#endif
2016 Log(("hdaR3StreamUpdate: Gained %u bytes.\n", hdaR3StreamGetFree(pStreamR3) - cbStreamFree));
2017
2018 cbStreamFree = hdaR3StreamGetFree(pStreamR3);
2019 if (cbStreamFree < cbPeriod)
2020 {
2021 /* Unable to make sufficient space. Drop the whole buffer content.
2022 * This is needed in order to keep the device emulation running at a constant rate,
2023 * at the cost of losing valid (but too much) data. */
2024 STAM_REL_COUNTER_INC(&pStreamR3->State.StatDmaFlowErrors);
2025 LogRel2(("HDA: Warning: Hit stream #%RU8 overflow, dropping %u bytes of audio data\n",
2026 pStreamShared->u8SD, hdaR3StreamGetUsed(pStreamR3)));
2027# ifdef HDA_STRICT
2028 AssertMsgFailed(("Hit stream #%RU8 overflow -- timing bug?\n", pStreamShared->u8SD));
2029# endif
2030 RTCircBufReset(pStreamR3->State.pCircBuf);
2031 pStreamR3->State.offWrite = 0;
2032 pStreamR3->State.offRead = 0;
2033 cbStreamFree = hdaR3StreamGetFree(pStreamR3);
2034 }
2035 }
2036
2037 /*
2038 * Do the DMA transfer.
2039 */
2040# ifdef VBOX_WITH_AUDIO_HDA_ASYNC_IO
2041 rc2 = PDMDevHlpCritSectEnter(pDevIns, &pStreamShared->CritSect, VERR_IGNORED);
2042 AssertRC(rc2);
2043# endif
2044
2045 uint64_t const offWriteBefore = pStreamR3->State.offWrite;
2046 hdaR3StreamDoDmaOutput(pDevIns, pThis, pStreamShared, pStreamR3, RT_MIN(cbStreamFree, cbPeriod), tsNowNs);
2047
2048# ifdef VBOX_WITH_AUDIO_HDA_ASYNC_IO
2049 rc2 = PDMDevHlpCritSectLeave(pDevIns, &pStreamShared->CritSect);
2050 AssertRC(rc2);
2051# endif
2052
2053 /*
2054 * Should we push data to down thru the mixer to and to the host drivers?
2055 *
2056 * We initially delay this by pThis->msInitialDelay, but after than we'll
2057 * kick the AIO thread every time we've put more data in the buffer (which is
2058 * every time) as the host audio device needs to get data in a timely manner.
2059 *
2060 * (We used to try only wake up the AIO thread according to pThis->uIoTimer
2061 * and host wall clock, but that meant we would miss a wakup after the DMA
2062 * timer was called a little late or if TM entered into catch-up mode.)
2063 */
2064 if (!pStreamShared->State.tsAioDelayEnd)
2065 fDoRead = pStreamR3->State.offWrite > offWriteBefore
2066 || hdaR3StreamGetFree(pStreamR3) < pStreamShared->State.cbAvgTransfer * 2;
2067 else if (PDMDevHlpTimerGet(pDevIns, pStreamShared->hTimer) >= pStreamShared->State.tsAioDelayEnd)
2068 {
2069 Log3Func(("Initial delay done: Passed tsAioDelayEnd.\n"));
2070 pStreamShared->State.tsAioDelayEnd = 0;
2071 fDoRead = true;
2072 }
2073 else if (hdaR3StreamGetFree(pStreamR3) < pStreamShared->State.cbAvgTransfer * 2)
2074 {
2075 Log3Func(("Initial delay done: Passed running short on buffer.\n"));
2076 pStreamShared->State.tsAioDelayEnd = 0;
2077 fDoRead = true;
2078 }
2079 else
2080 {
2081 Log3Func(("Initial delay pending...\n"));
2082 fDoRead = false;
2083 }
2084
2085 Log3Func(("msDelta=%RU64 (vs %u) cbStreamFree=%#x (vs %#x) => fDoRead=%RTbool\n",
2086 (tsNowNs - pStreamShared->State.tsLastReadNs) / RT_NS_1MS,
2087 pStreamShared->State.Cfg.Device.cMsSchedulingHint, cbStreamFree,
2088 pStreamShared->State.cbAvgTransfer * 2, fDoRead));
2089
2090 if (fDoRead)
2091 {
2092# ifdef VBOX_WITH_AUDIO_HDA_ASYNC_IO
2093 /* Notify the async I/O worker thread that there's work to do. */
2094 Log5Func(("Notifying AIO thread\n"));
2095 rc2 = hdaR3StreamAsyncIONotify(pStreamR3);
2096 AssertRC(rc2);
2097# endif
2098 /* Update last read timestamp for logging/debugging. */
2099 pStreamShared->State.tsLastReadNs = tsNowNs;
2100 }
2101 }
2102
2103 /*
2104 * Move data out of the pStreamR3->State.pCircBuf buffer and to
2105 * the mixer and in direction of the host audio devices.
2106 */
2107# ifdef VBOX_WITH_AUDIO_HDA_ASYNC_IO
2108 else
2109# else
2110 if (fDoRead)
2111# endif
2112 hdaR3StreamPushToMixer(pStreamShared, pStreamR3, pSink, tsNowNs);
2113 }
2114 /*
2115 * Input stream (SDI).
2116 */
2117 else
2118 {
2119 Assert(hdaGetDirFromSD(pStreamShared->u8SD) == PDMAUDIODIR_IN);
2120
2121 /*
2122 * If we're the async I/O worker, or not using AIO, pull bytes
2123 * from the mixer and into our internal DMA buffer.
2124 */
2125# ifdef VBOX_WITH_AUDIO_HDA_ASYNC_IO
2126 if (!fInTimer)
2127# endif
2128 hdaR3StreamPullFromMixer(pStreamShared, pStreamR3, pSink);
2129# ifdef VBOX_WITH_AUDIO_HDA_ASYNC_IO
2130 else /* fInTimer */
2131# endif
2132 {
2133 /*
2134 * See how much data we've got buffered...
2135 */
2136 bool fWriteSilence = false;
2137 uint32_t cbStreamUsed = hdaR3StreamGetUsed(pStreamR3);
2138 if (pStreamShared->State.fInputPreBuffered && cbStreamUsed >= cbPeriod)
2139 { /*likely*/ }
2140 /*
2141 * Because it may take a while for the input stream to get going (at
2142 * least with pulseaudio), we feed the guest silence till we've
2143 * pre-buffer a reasonable amount of audio.
2144 */
2145 else if (!pStreamShared->State.fInputPreBuffered)
2146 {
2147 if (cbStreamUsed < pStreamShared->State.cbInputPreBuffer)
2148 {
2149 Log3(("hdaR3StreamUpdate: Pre-buffering (got %#x out of %#x bytes)...\n",
2150 cbStreamUsed, pStreamShared->State.cbInputPreBuffer));
2151 fWriteSilence = true;
2152 }
2153 else
2154 {
2155 Log3(("hdaR3StreamUpdate: Completed pre-buffering (got %#x, needed %#x bytes).\n",
2156 cbStreamUsed, pStreamShared->State.cbInputPreBuffer));
2157 pStreamShared->State.fInputPreBuffered = true;
2158 fWriteSilence = true; /* For now, just do the most conservative thing. */
2159 }
2160 cbStreamUsed = cbPeriod;
2161 }
2162 /*
2163 * When we're low on data, we must really try fetch some ourselves
2164 * as buffer underruns must not happen.
2165 */
2166 else
2167 {
2168 /** @todo We're ending up here to frequently with pulse audio at least (just
2169 * watch the stream stats in the statistcs viewer, and way to often we
2170 * have to inject silence bytes. I suspect part of the problem is
2171 * that the HDA device require a much better latency than what the
2172 * pulse audio is configured for by default (10 ms vs 150ms). */
2173 STAM_REL_COUNTER_INC(&pStreamR3->State.StatDmaFlowProblems);
2174 Log(("hdaR3StreamUpdate: Warning! Stream #%u has insufficient data available: %u bytes, need %u. Will try move pull more data into the buffer...\n",
2175 pStreamShared->u8SD, cbStreamUsed, cbPeriod));
2176# ifdef VBOX_WITH_AUDIO_HDA_ASYNC_IO
2177 int rc = RTCritSectTryEnter(&pStreamR3->State.AIO.CritSect);
2178 if (RT_SUCCESS(rc))
2179 {
2180 hdaR3StreamPullFromMixer(pStreamShared, pStreamR3, pSink);
2181 RTCritSectLeave(&pStreamR3->State.AIO.CritSect);
2182 }
2183 else
2184 RTThreadYield();
2185#else
2186 hdaR3StreamPullFromMixer(pStreamShared, pStreamR3, pSink);
2187#endif
2188 Log(("hdaR3StreamUpdate: Gained %u bytes.\n", hdaR3StreamGetUsed(pStreamR3) - cbStreamUsed));
2189 cbStreamUsed = hdaR3StreamGetUsed(pStreamR3);
2190 if (cbStreamUsed < cbPeriod)
2191 {
2192 /* Unable to find sufficient input data by simple prodding.
2193 In order to keep a constant byte stream following thru the DMA
2194 engine into the guest, we will try again and then fall back on
2195 filling the gap with silence. */
2196 uint32_t cbSilence = 0;
2197 do
2198 {
2199#ifdef VBOX_WITH_AUDIO_HDA_ASYNC_IO
2200 RTCritSectEnter(&pStreamR3->State.AIO.CritSect);
2201#endif
2202 cbStreamUsed = hdaR3StreamGetUsed(pStreamR3);
2203 if (cbStreamUsed < cbPeriod)
2204 {
2205 hdaR3StreamPullFromMixer(pStreamShared, pStreamR3, pSink);
2206 cbStreamUsed = hdaR3StreamGetUsed(pStreamR3);
2207 while (cbStreamUsed < cbPeriod)
2208 {
2209 void *pvDstBuf;
2210 size_t cbDstBuf;
2211 RTCircBufAcquireWriteBlock(pStreamR3->State.pCircBuf, cbPeriod - cbStreamUsed,
2212 &pvDstBuf, &cbDstBuf);
2213 RT_BZERO(pvDstBuf, cbDstBuf);
2214 RTCircBufReleaseWriteBlock(pStreamR3->State.pCircBuf, cbDstBuf);
2215 cbSilence += (uint32_t)cbDstBuf;
2216 cbStreamUsed += (uint32_t)cbDstBuf;
2217 }
2218 }
2219
2220#ifdef VBOX_WITH_AUDIO_HDA_ASYNC_IO
2221 RTCritSectLeave(&pStreamR3->State.AIO.CritSect);
2222#endif
2223 } while (cbStreamUsed < cbPeriod);
2224 if (cbSilence > 0)
2225 {
2226 STAM_REL_COUNTER_INC(&pStreamR3->State.StatDmaFlowErrors);
2227 STAM_REL_COUNTER_ADD(&pStreamR3->State.StatDmaFlowErrorBytes, cbSilence);
2228 LogRel2(("HDA: Warning: Stream #%RU8 underrun, added %u bytes of silence (%u us)\n", pStreamShared->u8SD,
2229 cbSilence, PDMAudioPropsBytesToMicro(&pStreamR3->State.Mapping.GuestProps, cbSilence)));
2230 }
2231 }
2232 }
2233
2234 /*
2235 * Do the DMA'ing.
2236 */
2237 if (cbStreamUsed)
2238 {
2239# ifdef VBOX_WITH_AUDIO_HDA_ASYNC_IO
2240 rc2 = PDMDevHlpCritSectEnter(pDevIns, &pStreamShared->CritSect, VERR_IGNORED);
2241 AssertRC(rc2);
2242# endif
2243
2244 hdaR3StreamDoDmaInput(pDevIns, pThis, pStreamShared, pStreamR3,
2245 RT_MIN(cbStreamUsed, cbPeriod), fWriteSilence, tsNowNs);
2246
2247# ifdef VBOX_WITH_AUDIO_HDA_ASYNC_IO
2248 rc2 = PDMDevHlpCritSectLeave(pDevIns, &pStreamShared->CritSect);
2249 AssertRC(rc2);
2250# endif
2251 }
2252
2253# ifdef VBOX_WITH_AUDIO_HDA_ASYNC_IO
2254 /*
2255 * We should always kick the AIO thread.
2256 */
2257 /** @todo This isn't entirely ideal. If we get into an underrun situation,
2258 * we ideally want the AIO thread to run right before the DMA timer
2259 * rather than right after it ran. */
2260 Log5Func(("Notifying AIO thread\n"));
2261 rc2 = hdaR3StreamAsyncIONotify(pStreamR3);
2262 AssertRC(rc2);
2263 pStreamShared->State.tsLastReadNs = tsNowNs;
2264# endif
2265 }
2266 }
2267}
2268
2269#endif /* IN_RING3 */
2270
2271/**
2272 * Locks an HDA stream for serialized access.
2273 *
2274 * @returns IPRT status code.
2275 * @param pStreamShared HDA stream to lock (shared bits).
2276 */
2277void hdaStreamLock(PHDASTREAM pStreamShared)
2278{
2279 AssertPtrReturnVoid(pStreamShared);
2280# ifdef VBOX_WITH_AUDIO_HDA_ASYNC_IO
2281 int rc2 = PDMCritSectEnter(&pStreamShared->CritSect, VINF_SUCCESS);
2282 AssertRC(rc2);
2283#endif
2284}
2285
2286/**
2287 * Unlocks a formerly locked HDA stream.
2288 *
2289 * @returns IPRT status code.
2290 * @param pStreamShared HDA stream to unlock (shared bits).
2291 */
2292void hdaStreamUnlock(PHDASTREAM pStreamShared)
2293{
2294 AssertPtrReturnVoid(pStreamShared);
2295# ifdef VBOX_WITH_AUDIO_HDA_ASYNC_IO
2296 int rc2 = PDMCritSectLeave(&pStreamShared->CritSect);
2297 AssertRC(rc2);
2298# endif
2299}
2300
2301#ifdef IN_RING3
2302
2303#if 0 /* unused - no prototype even */
2304/**
2305 * Updates an HDA stream's current read or write buffer position (depending on the stream type) by
2306 * updating its associated LPIB register and DMA position buffer (if enabled).
2307 *
2308 * @returns Set LPIB value.
2309 * @param pDevIns The device instance.
2310 * @param pStream HDA stream to update read / write position for.
2311 * @param u32LPIB New LPIB (position) value to set.
2312 */
2313uint32_t hdaR3StreamUpdateLPIB(PPDMDEVINS pDevIns, PHDASTATE pThis, PHDASTREAM pStreamShared, uint32_t u32LPIB)
2314{
2315 AssertMsg(u32LPIB <= pStreamShared->u32CBL,
2316 ("[SD%RU8] New LPIB (%RU32) exceeds CBL (%RU32)\n", pStreamShared->u8SD, u32LPIB, pStreamShared->u32CBL));
2317
2318 u32LPIB = RT_MIN(u32LPIB, pStreamShared->u32CBL);
2319
2320 LogFlowFunc(("[SD%RU8] LPIB=%RU32 (DMA Position Buffer Enabled: %RTbool)\n",
2321 pStreamShared->u8SD, u32LPIB, pThis->fDMAPosition));
2322
2323 /* Update LPIB in any case. */
2324 HDA_STREAM_REG(pThis, LPIB, pStreamShared->u8SD) = u32LPIB;
2325
2326 /* Do we need to tell the current DMA position? */
2327 if (pThis->fDMAPosition)
2328 {
2329 int rc2 = PDMDevHlpPCIPhysWrite(pDevIns,
2330 pThis->u64DPBase + (pStreamShared->u8SD * 2 * sizeof(uint32_t)),
2331 (void *)&u32LPIB, sizeof(uint32_t));
2332 AssertRC(rc2);
2333 }
2334
2335 return u32LPIB;
2336}
2337#endif
2338
2339# ifdef HDA_USE_DMA_ACCESS_HANDLER
2340/**
2341 * Registers access handlers for a stream's BDLE DMA accesses.
2342 *
2343 * @returns true if registration was successful, false if not.
2344 * @param pStream HDA stream to register BDLE access handlers for.
2345 */
2346bool hdaR3StreamRegisterDMAHandlers(PHDASTREAM pStream)
2347{
2348 /* At least LVI and the BDL base must be set. */
2349 if ( !pStreamShared->u16LVI
2350 || !pStreamShared->u64BDLBase)
2351 {
2352 return false;
2353 }
2354
2355 hdaR3StreamUnregisterDMAHandlers(pStream);
2356
2357 LogFunc(("Registering ...\n"));
2358
2359 int rc = VINF_SUCCESS;
2360
2361 /*
2362 * Create BDLE ranges.
2363 */
2364
2365 struct BDLERANGE
2366 {
2367 RTGCPHYS uAddr;
2368 uint32_t uSize;
2369 } arrRanges[16]; /** @todo Use a define. */
2370
2371 size_t cRanges = 0;
2372
2373 for (uint16_t i = 0; i < pStreamShared->u16LVI + 1; i++)
2374 {
2375 HDABDLE BDLE;
2376 rc = hdaR3BDLEFetch(pDevIns, &BDLE, pStreamShared->u64BDLBase, i /* Index */);
2377 if (RT_FAILURE(rc))
2378 break;
2379
2380 bool fAddRange = true;
2381 BDLERANGE *pRange;
2382
2383 if (cRanges)
2384 {
2385 pRange = &arrRanges[cRanges - 1];
2386
2387 /* Is the current range a direct neighbor of the current BLDE? */
2388 if ((pRange->uAddr + pRange->uSize) == BDLE.Desc.u64BufAddr)
2389 {
2390 /* Expand the current range by the current BDLE's size. */
2391 pRange->uSize += BDLE.Desc.u32BufSize;
2392
2393 /* Adding a new range in this case is not needed anymore. */
2394 fAddRange = false;
2395
2396 LogFunc(("Expanding range %zu by %RU32 (%RU32 total now)\n", cRanges - 1, BDLE.Desc.u32BufSize, pRange->uSize));
2397 }
2398 }
2399
2400 /* Do we need to add a new range? */
2401 if ( fAddRange
2402 && cRanges < RT_ELEMENTS(arrRanges))
2403 {
2404 pRange = &arrRanges[cRanges];
2405
2406 pRange->uAddr = BDLE.Desc.u64BufAddr;
2407 pRange->uSize = BDLE.Desc.u32BufSize;
2408
2409 LogFunc(("Adding range %zu - 0x%x (%RU32)\n", cRanges, pRange->uAddr, pRange->uSize));
2410
2411 cRanges++;
2412 }
2413 }
2414
2415 LogFunc(("%zu ranges total\n", cRanges));
2416
2417 /*
2418 * Register all ranges as DMA access handlers.
2419 */
2420
2421 for (size_t i = 0; i < cRanges; i++)
2422 {
2423 BDLERANGE *pRange = &arrRanges[i];
2424
2425 PHDADMAACCESSHANDLER pHandler = (PHDADMAACCESSHANDLER)RTMemAllocZ(sizeof(HDADMAACCESSHANDLER));
2426 if (!pHandler)
2427 {
2428 rc = VERR_NO_MEMORY;
2429 break;
2430 }
2431
2432 RTListAppend(&pStream->State.lstDMAHandlers, &pHandler->Node);
2433
2434 pHandler->pStream = pStream; /* Save a back reference to the owner. */
2435
2436 char szDesc[32];
2437 RTStrPrintf(szDesc, sizeof(szDesc), "HDA[SD%RU8 - RANGE%02zu]", pStream->u8SD, i);
2438
2439 int rc2 = PGMR3HandlerPhysicalTypeRegister(PDMDevHlpGetVM(pStream->pHDAState->pDevInsR3), PGMPHYSHANDLERKIND_WRITE,
2440 hdaDMAAccessHandler,
2441 NULL, NULL, NULL,
2442 NULL, NULL, NULL,
2443 szDesc, &pHandler->hAccessHandlerType);
2444 AssertRCBreak(rc2);
2445
2446 pHandler->BDLEAddr = pRange->uAddr;
2447 pHandler->BDLESize = pRange->uSize;
2448
2449 /* Get first and last pages of the BDLE range. */
2450 RTGCPHYS pgFirst = pRange->uAddr & ~PAGE_OFFSET_MASK;
2451 RTGCPHYS pgLast = RT_ALIGN(pgFirst + pRange->uSize, PAGE_SIZE);
2452
2453 /* Calculate the region size (in pages). */
2454 RTGCPHYS regionSize = RT_ALIGN(pgLast - pgFirst, PAGE_SIZE);
2455
2456 pHandler->GCPhysFirst = pgFirst;
2457 pHandler->GCPhysLast = pHandler->GCPhysFirst + (regionSize - 1);
2458
2459 LogFunc(("\tRegistering region '%s': 0x%x - 0x%x (region size: %zu)\n",
2460 szDesc, pHandler->GCPhysFirst, pHandler->GCPhysLast, regionSize));
2461 LogFunc(("\tBDLE @ 0x%x - 0x%x (%RU32)\n",
2462 pHandler->BDLEAddr, pHandler->BDLEAddr + pHandler->BDLESize, pHandler->BDLESize));
2463
2464 rc2 = PGMHandlerPhysicalRegister(PDMDevHlpGetVM(pStream->pHDAState->pDevInsR3),
2465 pHandler->GCPhysFirst, pHandler->GCPhysLast,
2466 pHandler->hAccessHandlerType, pHandler, NIL_RTR0PTR, NIL_RTRCPTR,
2467 szDesc);
2468 AssertRCBreak(rc2);
2469
2470 pHandler->fRegistered = true;
2471 }
2472
2473 LogFunc(("Registration ended with rc=%Rrc\n", rc));
2474
2475 return RT_SUCCESS(rc);
2476}
2477
2478/**
2479 * Unregisters access handlers of a stream's BDLEs.
2480 *
2481 * @param pStream HDA stream to unregister BDLE access handlers for.
2482 */
2483void hdaR3StreamUnregisterDMAHandlers(PHDASTREAM pStream)
2484{
2485 LogFunc(("\n"));
2486
2487 PHDADMAACCESSHANDLER pHandler, pHandlerNext;
2488 RTListForEachSafe(&pStream->State.lstDMAHandlers, pHandler, pHandlerNext, HDADMAACCESSHANDLER, Node)
2489 {
2490 if (!pHandler->fRegistered) /* Handler not registered? Skip. */
2491 continue;
2492
2493 LogFunc(("Unregistering 0x%x - 0x%x (%zu)\n",
2494 pHandler->GCPhysFirst, pHandler->GCPhysLast, pHandler->GCPhysLast - pHandler->GCPhysFirst));
2495
2496 int rc2 = PGMHandlerPhysicalDeregister(PDMDevHlpGetVM(pStream->pHDAState->pDevInsR3),
2497 pHandler->GCPhysFirst);
2498 AssertRC(rc2);
2499
2500 RTListNodeRemove(&pHandler->Node);
2501
2502 RTMemFree(pHandler);
2503 pHandler = NULL;
2504 }
2505
2506 Assert(RTListIsEmpty(&pStream->State.lstDMAHandlers));
2507}
2508
2509# endif /* HDA_USE_DMA_ACCESS_HANDLER */
2510# ifdef VBOX_WITH_AUDIO_HDA_ASYNC_IO
2511
2512/**
2513 * @callback_method_impl{FNRTTHREAD,
2514 * Asynchronous I/O thread for a HDA stream.
2515 *
2516 * This will do the heavy lifting work for us as soon as it's getting notified
2517 * by another thread.}
2518 */
2519static DECLCALLBACK(int) hdaR3StreamAsyncIOThread(RTTHREAD hThreadSelf, void *pvUser)
2520{
2521 PHDASTREAMR3 const pStreamR3 = (PHDASTREAMR3)pvUser;
2522 PHDASTREAMSTATEAIO const pAIO = &pStreamR3->State.AIO;
2523 PHDASTATE const pThis = pStreamR3->pHDAStateShared;
2524 PHDASTATER3 const pThisCC = pStreamR3->pHDAStateR3;
2525 PPDMDEVINS const pDevIns = pThisCC->pDevIns;
2526 PHDASTREAM const pStreamShared = &pThis->aStreams[pStreamR3 - &pThisCC->aStreams[0]];
2527 Assert(pStreamR3 - &pThisCC->aStreams[0] == pStreamR3->u8SD);
2528 Assert(pStreamShared->u8SD == pStreamR3->u8SD);
2529
2530 /* Signal parent thread that we've started */
2531 ASMAtomicWriteBool(&pAIO->fStarted, true);
2532 RTThreadUserSignal(hThreadSelf);
2533
2534 LogFunc(("[SD%RU8] Started\n", pStreamShared->u8SD));
2535
2536 while (!ASMAtomicReadBool(&pAIO->fShutdown))
2537 {
2538 int rc2 = RTSemEventWait(pAIO->hEvent, RT_INDEFINITE_WAIT);
2539 if (RT_SUCCESS(rc2))
2540 { /* likely */ }
2541 else
2542 break;
2543
2544 if (!ASMAtomicReadBool(&pAIO->fShutdown))
2545 { /* likely */ }
2546 else
2547 break;
2548
2549 rc2 = RTCritSectEnter(&pAIO->CritSect);
2550 AssertRC(rc2);
2551 if (RT_SUCCESS(rc2))
2552 {
2553 if (pAIO->fEnabled)
2554 hdaR3StreamUpdate(pDevIns, pThis, pThisCC, pStreamShared, pStreamR3, false /* fInTimer */);
2555
2556 int rc3 = RTCritSectLeave(&pAIO->CritSect);
2557 AssertRC(rc3);
2558 }
2559 }
2560
2561 LogFunc(("[SD%RU8] Ended\n", pStreamShared->u8SD));
2562 ASMAtomicWriteBool(&pAIO->fStarted, false);
2563
2564 return VINF_SUCCESS;
2565}
2566
2567/**
2568 * Creates the async I/O thread for a specific HDA audio stream.
2569 *
2570 * @returns IPRT status code.
2571 * @param pStreamR3 HDA audio stream to create the async I/O thread for.
2572 */
2573int hdaR3StreamAsyncIOCreate(PHDASTREAMR3 pStreamR3)
2574{
2575 PHDASTREAMSTATEAIO pAIO = &pStreamR3->State.AIO;
2576
2577 int rc;
2578
2579 if (!ASMAtomicReadBool(&pAIO->fStarted))
2580 {
2581 pAIO->fShutdown = false;
2582 pAIO->fEnabled = true; /* Enabled by default. */
2583
2584 rc = RTSemEventCreate(&pAIO->hEvent);
2585 if (RT_SUCCESS(rc))
2586 {
2587 rc = RTCritSectInit(&pAIO->CritSect);
2588 if (RT_SUCCESS(rc))
2589 {
2590 rc = RTThreadCreateF(&pAIO->hThread, hdaR3StreamAsyncIOThread, pStreamR3, 0 /*cbStack*/,
2591 RTTHREADTYPE_IO, RTTHREADFLAGS_WAITABLE, "hdaAIO%RU8", pStreamR3->u8SD);
2592 if (RT_SUCCESS(rc))
2593 rc = RTThreadUserWait(pAIO->hThread, 10 * 1000 /* 10s timeout */);
2594 }
2595 }
2596 }
2597 else
2598 rc = VINF_SUCCESS;
2599
2600 LogFunc(("[SD%RU8] Returning %Rrc\n", pStreamR3->u8SD, rc));
2601 return rc;
2602}
2603
2604/**
2605 * Destroys the async I/O thread of a specific HDA audio stream.
2606 *
2607 * @returns IPRT status code.
2608 * @param pStreamR3 HDA audio stream to destroy the async I/O thread for.
2609 */
2610static int hdaR3StreamAsyncIODestroy(PHDASTREAMR3 pStreamR3)
2611{
2612 PHDASTREAMSTATEAIO pAIO = &pStreamR3->State.AIO;
2613
2614 if (!ASMAtomicReadBool(&pAIO->fStarted))
2615 return VINF_SUCCESS;
2616
2617 ASMAtomicWriteBool(&pAIO->fShutdown, true);
2618
2619 int rc = hdaR3StreamAsyncIONotify(pStreamR3);
2620 AssertRC(rc);
2621
2622 int rcThread;
2623 rc = RTThreadWait(pAIO->hThread, 30 * 1000 /* 30s timeout */, &rcThread);
2624 LogFunc(("Async I/O thread ended with %Rrc (%Rrc)\n", rc, rcThread));
2625
2626 if (RT_SUCCESS(rc))
2627 {
2628 pAIO->hThread = NIL_RTTHREAD;
2629
2630 rc = RTCritSectDelete(&pAIO->CritSect);
2631 AssertRC(rc);
2632
2633 rc = RTSemEventDestroy(pAIO->hEvent);
2634 AssertRC(rc);
2635 pAIO->hEvent = NIL_RTSEMEVENT;
2636
2637 pAIO->fStarted = false;
2638 pAIO->fShutdown = false;
2639 pAIO->fEnabled = false;
2640 }
2641
2642 LogFunc(("[SD%RU8] Returning %Rrc\n", pStreamR3->u8SD, rc));
2643 return rc;
2644}
2645
2646/**
2647 * Lets the stream's async I/O thread know that there is some data to process.
2648 *
2649 * @returns IPRT status code.
2650 * @param pStreamR3 HDA stream to notify async I/O thread for.
2651 */
2652int hdaR3StreamAsyncIONotify(PHDASTREAMR3 pStreamR3)
2653{
2654 return RTSemEventSignal(pStreamR3->State.AIO.hEvent);
2655}
2656
2657/**
2658 * Locks the async I/O thread of a specific HDA audio stream.
2659 *
2660 * @param pStreamR3 HDA stream to lock async I/O thread for.
2661 */
2662void hdaR3StreamAsyncIOLock(PHDASTREAMR3 pStreamR3)
2663{
2664 PHDASTREAMSTATEAIO pAIO = &pStreamR3->State.AIO;
2665
2666 if (!ASMAtomicReadBool(&pAIO->fStarted))
2667 return;
2668
2669 int rc2 = RTCritSectEnter(&pAIO->CritSect);
2670 AssertRC(rc2);
2671}
2672
2673/**
2674 * Unlocks the async I/O thread of a specific HDA audio stream.
2675 *
2676 * @param pStreamR3 HDA stream to unlock async I/O thread for.
2677 */
2678void hdaR3StreamAsyncIOUnlock(PHDASTREAMR3 pStreamR3)
2679{
2680 PHDASTREAMSTATEAIO pAIO = &pStreamR3->State.AIO;
2681
2682 if (!ASMAtomicReadBool(&pAIO->fStarted))
2683 return;
2684
2685 int rc2 = RTCritSectLeave(&pAIO->CritSect);
2686 AssertRC(rc2);
2687}
2688
2689/**
2690 * Enables (resumes) or disables (pauses) the async I/O thread.
2691 *
2692 * @param pStreamR3 HDA stream to enable/disable async I/O thread for.
2693 * @param fEnable Whether to enable or disable the I/O thread.
2694 *
2695 * @remarks Does not do locking.
2696 */
2697void hdaR3StreamAsyncIOEnable(PHDASTREAMR3 pStreamR3, bool fEnable)
2698{
2699 PHDASTREAMSTATEAIO pAIO = &pStreamR3->State.AIO;
2700 ASMAtomicXchgBool(&pAIO->fEnabled, fEnable);
2701}
2702
2703# endif /* VBOX_WITH_AUDIO_HDA_ASYNC_IO */
2704#endif /* IN_RING3 */
Note: See TracBrowser for help on using the repository browser.

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