VirtualBox

source: vbox/trunk/src/VBox/Devices/Audio/DevHdaStream.cpp@ 88466

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

Audio: Moved PDMAUDIOFILE and associated stuff out of pdmaudioifs.h and into AudioHlp.h, renaming the typedefs & defines. bugref:9890

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