VirtualBox

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

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

DevHda: Start the AIO thread with RTTHREADFLAGS_COM_MTA. bugref:9890

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 107.8 KB
Line 
1/* $Id: DevHdaStream.cpp 88690 2021-04-23 19:25:40Z 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 pThis The shared HDA device state.
888 * @param pStreamShared HDA stream to enable or disable - shared bits.
889 * @param pStreamR3 HDA stream to enable or disable - ring-3 bits.
890 * @param fEnable Whether to enable or disble the stream.
891 */
892int hdaR3StreamEnable(PHDASTATE pThis, PHDASTREAM pStreamShared, PHDASTREAMR3 pStreamR3, bool fEnable)
893{
894 AssertPtr(pStreamR3);
895 AssertPtr(pStreamShared);
896
897 LogFunc(("[SD%RU8] fEnable=%RTbool, pMixSink=%p\n", pStreamShared->u8SD, fEnable, pStreamR3->pMixSink));
898
899 int rc = VINF_SUCCESS;
900
901 AUDMIXSINKCMD enmCmd = fEnable
902 ? AUDMIXSINKCMD_ENABLE : AUDMIXSINKCMD_DISABLE;
903
904 /* First, enable or disable the stream and the stream's sink, if any. */
905 if ( pStreamR3->pMixSink
906 && pStreamR3->pMixSink->pMixSink)
907 rc = AudioMixerSinkCtl(pStreamR3->pMixSink->pMixSink, enmCmd);
908
909 if ( RT_SUCCESS(rc)
910 && fEnable
911 && pStreamR3->Dbg.Runtime.fEnabled)
912 {
913 Assert(AudioHlpPcmPropsAreValid(&pStreamShared->State.Cfg.Props));
914
915 if (fEnable)
916 {
917 if (!AudioHlpFileIsOpen(pStreamR3->Dbg.Runtime.pFileStream))
918 {
919 int rc2 = AudioHlpFileOpen(pStreamR3->Dbg.Runtime.pFileStream, AUDIOHLPFILE_DEFAULT_OPEN_FLAGS,
920 &pStreamShared->State.Cfg.Props);
921 AssertRC(rc2);
922 }
923
924 if (!AudioHlpFileIsOpen(pStreamR3->Dbg.Runtime.pFileDMARaw))
925 {
926 int rc2 = AudioHlpFileOpen(pStreamR3->Dbg.Runtime.pFileDMARaw, AUDIOHLPFILE_DEFAULT_OPEN_FLAGS,
927 &pStreamShared->State.Cfg.Props);
928 AssertRC(rc2);
929 }
930
931 if (!AudioHlpFileIsOpen(pStreamR3->Dbg.Runtime.pFileDMAMapped))
932 {
933 int rc2 = AudioHlpFileOpen(pStreamR3->Dbg.Runtime.pFileDMAMapped, AUDIOHLPFILE_DEFAULT_OPEN_FLAGS,
934 &pStreamShared->State.Cfg.Props);
935 AssertRC(rc2);
936 }
937 }
938 }
939
940 if (RT_SUCCESS(rc))
941 {
942 if (fEnable)
943 pStreamShared->State.tsTransferLast = 0; /* Make sure it's not stale and messes up WALCLK calculations. */
944 pStreamShared->State.fRunning = fEnable;
945
946 /*
947 * Set the FIFORDY bit when we start running and clear it when stopping.
948 *
949 * This prevents Linux from timing out in snd_hdac_stream_sync when starting
950 * a stream. Technically, Linux also uses the SSYNC feature there, but we
951 * can get away with just setting the FIFORDY bit for now.
952 */
953 if (fEnable)
954 HDA_STREAM_REG(pThis, STS, pStreamShared->u8SD) |= HDA_SDSTS_FIFORDY;
955 else
956 HDA_STREAM_REG(pThis, STS, pStreamShared->u8SD) &= ~HDA_SDSTS_FIFORDY;
957 }
958
959 LogFunc(("[SD%RU8] rc=%Rrc\n", pStreamShared->u8SD, rc));
960 return rc;
961}
962
963/**
964 * Marks the stream as started.
965 *
966 * Used after the stream has been enabled and the DMA timer has been armed.
967 */
968void hdaR3StreamMarkStarted(PPDMDEVINS pDevIns, PHDASTATE pThis, PHDASTREAM pStreamShared, uint64_t tsNow)
969{
970 pStreamShared->State.tsLastReadNs = RTTimeNanoTS();
971 pStreamShared->State.tsStart = tsNow;
972 pStreamShared->State.tsAioDelayEnd = tsNow + PDMDevHlpTimerFromMilli(pDevIns, pStreamShared->hTimer, pThis->msInitialDelay);
973 Log3Func(("#%u: tsStart=%RU64 tsAioDelayEnd=%RU64 tsLastReadNs=%RU64\n", pStreamShared->u8SD,
974 pStreamShared->State.tsStart, pStreamShared->State.tsAioDelayEnd, pStreamShared->State.tsLastReadNs));
975
976}
977
978/**
979 * Marks the stream as stopped.
980 */
981void hdaR3StreamMarkStopped(PHDASTREAM pStreamShared)
982{
983 Log3Func(("#%u\n", pStreamShared->u8SD));
984 pStreamShared->State.tsAioDelayEnd = UINT64_MAX;
985}
986
987
988#if 0 /* Not used atm. */
989static uint32_t hdaR3StreamGetPosition(PHDASTATE pThis, PHDASTREAM pStreamShared)
990{
991 return HDA_STREAM_REG(pThis, LPIB, pStreamShared->u8SD);
992}
993#endif
994
995/**
996 * Updates an HDA stream's current read or write buffer position (depending on the stream type) by
997 * setting its associated LPIB register and DMA position buffer (if enabled) to an absolute value.
998 *
999 * @param pStreamShared HDA stream to update read / write position for (shared).
1000 * @param pDevIns The device instance.
1001 * @param pThis The shared HDA device state.
1002 * @param uLPIB Absolute position (in bytes) to set current read / write position to.
1003 */
1004static void hdaR3StreamSetPositionAbs(PHDASTREAM pStreamShared, PPDMDEVINS pDevIns, PHDASTATE pThis, uint32_t uLPIB)
1005{
1006 AssertPtrReturnVoid(pStreamShared);
1007 AssertReturnVoid (uLPIB <= pStreamShared->u32CBL); /* Make sure that we don't go out-of-bounds. */
1008
1009 Log3Func(("[SD%RU8] LPIB=%RU32 (DMA Position Buffer Enabled: %RTbool)\n", pStreamShared->u8SD, uLPIB, pThis->fDMAPosition));
1010
1011 /* Update LPIB in any case. */
1012 HDA_STREAM_REG(pThis, LPIB, pStreamShared->u8SD) = uLPIB;
1013
1014 /* Do we need to tell the current DMA position? */
1015 if (pThis->fDMAPosition)
1016 {
1017 int rc2 = PDMDevHlpPCIPhysWrite(pDevIns,
1018 pThis->u64DPBase + (pStreamShared->u8SD * 2 * sizeof(uint32_t)),
1019 (void *)&uLPIB, sizeof(uint32_t));
1020 AssertRC(rc2);
1021 }
1022}
1023
1024/**
1025 * Updates an HDA stream's current read or write buffer position (depending on the stream type) by
1026 * adding a value to its associated LPIB register and DMA position buffer (if enabled).
1027 *
1028 * @note Handles automatic CBL wrap-around.
1029 *
1030 * @param pStreamShared HDA stream to update read / write position for (shared).
1031 * @param pDevIns The device instance.
1032 * @param pThis The shared HDA device state.
1033 * @param cbToAdd Position (in bytes) to add to the current read / write position.
1034 */
1035void hdaR3StreamSetPositionAdd(PHDASTREAM pStreamShared, PPDMDEVINS pDevIns, PHDASTATE pThis, uint32_t cbToAdd)
1036{
1037 if (cbToAdd) /* No need to update anything if 0. */
1038 {
1039 uint32_t const uCBL = pStreamShared->u32CBL;
1040 if (uCBL) /* paranoia */
1041 hdaR3StreamSetPositionAbs(pStreamShared, pDevIns, pThis,
1042 (HDA_STREAM_REG(pThis, LPIB, pStreamShared->u8SD) + cbToAdd) % uCBL);
1043 }
1044}
1045
1046/**
1047 * Retrieves the available size of (buffered) audio data (in bytes) of a given HDA stream.
1048 *
1049 * @returns Available data (in bytes).
1050 * @param pStreamR3 HDA stream to retrieve size for (ring-3).
1051 */
1052static uint32_t hdaR3StreamGetUsed(PHDASTREAMR3 pStreamR3)
1053{
1054 AssertPtrReturn(pStreamR3, 0);
1055
1056 if (pStreamR3->State.pCircBuf)
1057 return (uint32_t)RTCircBufUsed(pStreamR3->State.pCircBuf);
1058 return 0;
1059}
1060
1061/**
1062 * Retrieves the free size of audio data (in bytes) of a given HDA stream.
1063 *
1064 * @returns Free data (in bytes).
1065 * @param pStreamR3 HDA stream to retrieve size for (ring-3).
1066 */
1067static uint32_t hdaR3StreamGetFree(PHDASTREAMR3 pStreamR3)
1068{
1069 AssertPtrReturn(pStreamR3, 0);
1070
1071 if (pStreamR3->State.pCircBuf)
1072 return (uint32_t)RTCircBufFree(pStreamR3->State.pCircBuf);
1073 return 0;
1074}
1075
1076/**
1077 * Get the current address and number of bytes left in the current BDLE.
1078 *
1079 * @returns The current physical address.
1080 * @param pStreamShared The stream to check.
1081 * @param pcbLeft The number of bytes left at the returned address.
1082 */
1083DECLINLINE(RTGCPHYS) hdaR3StreamDmaBufGet(PHDASTREAM pStreamShared, uint32_t *pcbLeft)
1084{
1085 uint8_t idxBdle = pStreamShared->State.idxCurBdle;
1086 AssertStmt(idxBdle < pStreamShared->State.cBdles, idxBdle = 0);
1087
1088 uint32_t const cbCurBdl = pStreamShared->State.aBdl[idxBdle].cb;
1089 uint32_t offCurBdle = pStreamShared->State.offCurBdle;
1090 AssertStmt(pStreamShared->State.offCurBdle <= cbCurBdl, offCurBdle = cbCurBdl);
1091
1092 *pcbLeft = cbCurBdl - offCurBdle;
1093 return pStreamShared->State.aBdl[idxBdle].GCPhys + offCurBdle;
1094}
1095
1096/**
1097 * Get the size of the current BDLE.
1098 *
1099 * @returns The size (in bytes).
1100 * @param pStreamShared The stream to check.
1101 */
1102DECLINLINE(RTGCPHYS) hdaR3StreamDmaBufGetSize(PHDASTREAM pStreamShared)
1103{
1104 uint8_t idxBdle = pStreamShared->State.idxCurBdle;
1105 AssertStmt(idxBdle < pStreamShared->State.cBdles, idxBdle = 0);
1106 return pStreamShared->State.aBdl[idxBdle].cb;
1107}
1108
1109/**
1110 * Checks if the current BDLE is completed.
1111 *
1112 * @retval true if complete
1113 * @retval false if not.
1114 * @param pStreamShared The stream to check.
1115 */
1116DECLINLINE(bool) hdaR3StreamDmaBufIsComplete(PHDASTREAM pStreamShared)
1117{
1118 uint8_t const idxBdle = pStreamShared->State.idxCurBdle;
1119 AssertReturn(idxBdle < pStreamShared->State.cBdles, true);
1120
1121 uint32_t const cbCurBdl = pStreamShared->State.aBdl[idxBdle].cb;
1122 uint32_t const offCurBdle = pStreamShared->State.offCurBdle;
1123 Assert(offCurBdle <= cbCurBdl);
1124 return offCurBdle >= cbCurBdl;
1125}
1126
1127/**
1128 * Checks if the current BDLE needs a completion IRQ.
1129 *
1130 * @retval true if IRQ is needed.
1131 * @retval false if not.
1132 * @param pStreamShared The stream to check.
1133 */
1134DECLINLINE(bool) hdaR3StreamDmaBufNeedsIrq(PHDASTREAM pStreamShared)
1135{
1136 uint8_t const idxBdle = pStreamShared->State.idxCurBdle;
1137 AssertReturn(idxBdle < pStreamShared->State.cBdles, false);
1138 return (pStreamShared->State.aBdl[idxBdle].fFlags & HDA_BDLE_F_IOC) != 0;
1139}
1140
1141/**
1142 * Advances the DMA engine to the next BDLE.
1143 *
1144 * @param pStreamShared The stream which DMA engine is to be updated.
1145 */
1146DECLINLINE(void) hdaR3StreamDmaBufAdvanceToNext(PHDASTREAM pStreamShared)
1147{
1148 uint8_t idxBdle = pStreamShared->State.idxCurBdle;
1149 Assert(pStreamShared->State.offCurBdle == pStreamShared->State.aBdl[idxBdle].cb);
1150
1151 if (idxBdle < pStreamShared->State.cBdles - 1)
1152 idxBdle++;
1153 else
1154 idxBdle = 0;
1155 pStreamShared->State.idxCurBdle = idxBdle;
1156 pStreamShared->State.offCurBdle = 0;
1157}
1158
1159/**
1160 * Common do-DMA prologue code.
1161 *
1162 * @retval true if DMA processing can take place
1163 * @retval false if caller should return immediately.
1164 * @param pThis The shared HDA device state.
1165 * @param pStreamShared HDA stream to update (shared).
1166 * @param uSD The stream ID (for asserting).
1167 * @param tsNowNs The current RTTimeNano() value.
1168 * @param pszFunction The function name (for logging).
1169 */
1170DECLINLINE(bool) hdaR3StreamDoDmaPrologue(PHDASTATE pThis, PHDASTREAM pStreamShared, uint8_t uSD,
1171 uint64_t tsNowNs, const char *pszFunction)
1172{
1173 RT_NOREF(uSD, pszFunction);
1174
1175 /*
1176 * Check if we should skip town...
1177 */
1178 /* Stream not running (anymore)? */
1179 if (pStreamShared->State.fRunning)
1180 { /* likely */ }
1181 else
1182 {
1183 Log3(("%s: [SD%RU8] Not running, skipping transfer\n", pszFunction, uSD));
1184 return false;
1185 }
1186
1187 if (!(HDA_STREAM_REG(pThis, STS, uSD) & HDA_SDSTS_BCIS))
1188 { /* likely */ }
1189 else
1190 {
1191 Log3(("%s: [SD%RU8] BCIS bit set, skipping transfer\n", pszFunction, uSD));
1192#ifdef HDA_STRICT
1193 /* Timing emulation bug or guest is misbehaving -- let me know. */
1194 AssertMsgFailed(("%s: BCIS bit for stream #%RU8 still set when it shouldn't\n", pszFunction, uSD));
1195#endif
1196 return false;
1197 }
1198
1199 /*
1200 * Stream sanity checks.
1201 */
1202 /* Register sanity checks. */
1203 Assert(uSD < HDA_MAX_STREAMS);
1204 Assert(pStreamShared->u64BDLBase);
1205 Assert(pStreamShared->u32CBL);
1206 Assert(pStreamShared->u8FIFOS);
1207
1208 /* State sanity checks. */
1209 Assert(ASMAtomicReadBool(&pStreamShared->State.fInReset) == false);
1210 Assert(ASMAtomicReadBool(&pStreamShared->State.fRunning));
1211
1212 /*
1213 * Some timestamp stuff for logging/debugging.
1214 */
1215 /*const uint64_t tsNowNs = RTTimeNanoTS();*/
1216 Log3(("%s: [SD%RU8] tsDeltaNs=%'RU64 ns\n", pszFunction, uSD, tsNowNs - pStreamShared->State.tsLastTransferNs));
1217 pStreamShared->State.tsLastTransferNs = tsNowNs;
1218
1219 return true;
1220}
1221
1222/**
1223 * Common do-DMA epilogue.
1224 *
1225 * @param pDevIns The device instance.
1226 * @param pStreamShared The HDA stream (shared).
1227 * @param pStreamR3 The HDA stream (ring-3).
1228 */
1229DECLINLINE(void) hdaR3StreamDoDmaEpilogue(PPDMDEVINS pDevIns, PHDASTREAM pStreamShared, PHDASTREAMR3 pStreamR3)
1230{
1231 /*
1232 * We must update this in the epilogue rather than in the prologue
1233 * as it is used for WALCLK calculation and we must make sure the
1234 * guest doesn't think we've processed the current period till we
1235 * actually have.
1236 */
1237 pStreamShared->State.tsTransferLast = PDMDevHlpTimerGet(pDevIns, pStreamShared->hTimer);
1238
1239 /*
1240 * Update the buffer statistics.
1241 */
1242 pStreamR3->State.StatDmaBufUsed = (uint32_t)RTCircBufUsed(pStreamR3->State.pCircBuf);
1243}
1244
1245/**
1246 * Completes a BDLE at the end of a DMA loop iteration, if possible.
1247 *
1248 * @param pDevIns The device instance.
1249 * @param pThis The shared HDA device state.
1250 * @param pStreamShared HDA stream to update (shared).
1251 * @param pszFunction The function name (for logging).
1252 */
1253DECLINLINE(void) hdaR3StreamDoDmaMaybeCompleteBuffer(PPDMDEVINS pDevIns, PHDASTATE pThis,
1254 PHDASTREAM pStreamShared, const char *pszFunction)
1255{
1256 RT_NOREF(pszFunction);
1257
1258 /*
1259 * Is the buffer descriptor complete.
1260 */
1261 if (hdaR3StreamDmaBufIsComplete(pStreamShared))
1262 {
1263 Log3(("%s: [SD%RU8] Completed BDLE%u %#RX64 LB %#RX32 fFlags=%#x\n", pszFunction, pStreamShared->u8SD,
1264 pStreamShared->State.idxCurBdle, pStreamShared->State.aBdl[pStreamShared->State.idxCurBdle].GCPhys,
1265 pStreamShared->State.aBdl[pStreamShared->State.idxCurBdle].cb,
1266 pStreamShared->State.aBdl[pStreamShared->State.idxCurBdle].fFlags));
1267
1268 /*
1269 * Update the stream's current position.
1270 *
1271 * Do this as accurate and close to the actual data transfer as possible.
1272 * All guetsts rely on this, depending on the mechanism they use (LPIB register or DMA counters).
1273 *
1274 * Note for Windows 10: The OS' driver is *very* picky about *when* the (DMA) positions get updated!
1275 * Not doing this at the right time will result in ugly sound crackles!
1276 */
1277 hdaR3StreamSetPositionAdd(pStreamShared, pDevIns, pThis, hdaR3StreamDmaBufGetSize(pStreamShared));
1278
1279 /* Does the current BDLE require an interrupt to be sent? */
1280 if (hdaR3StreamDmaBufNeedsIrq(pStreamShared))
1281 {
1282 /* If the IOCE ("Interrupt On Completion Enable") bit of the SDCTL
1283 register is set we need to generate an interrupt. */
1284 if (HDA_STREAM_REG(pThis, CTL, pStreamShared->u8SD) & HDA_SDCTL_IOCE)
1285 {
1286 /* Assert the interrupt before actually fetching the next BDLE below. */
1287 pStreamShared->State.cTransferPendingInterrupts = 1;
1288 Log3(("%s: [SD%RU8] Scheduling interrupt\n", pszFunction, pStreamShared->u8SD));
1289
1290 /* Trigger an interrupt first and let hdaRegWriteSDSTS() deal with
1291 * ending / beginning of a period. */
1292 /** @todo r=bird: What does the above comment mean? */
1293 HDA_STREAM_REG(pThis, STS, pStreamShared->u8SD) |= HDA_SDSTS_BCIS;
1294 HDA_PROCESS_INTERRUPT(pDevIns, pThis);
1295 }
1296 }
1297
1298 /*
1299 * Advance to the next BDLE.
1300 */
1301 hdaR3StreamDmaBufAdvanceToNext(pStreamShared);
1302 }
1303 else
1304 Log3(("%s: [SD%RU8] Not completed BDLE%u %#RX64 LB %#RX32 fFlags=%#x: off=%#RX32\n", pszFunction, pStreamShared->u8SD,
1305 pStreamShared->State.idxCurBdle, pStreamShared->State.aBdl[pStreamShared->State.idxCurBdle].GCPhys,
1306 pStreamShared->State.aBdl[pStreamShared->State.idxCurBdle].cb,
1307 pStreamShared->State.aBdl[pStreamShared->State.idxCurBdle].fFlags, pStreamShared->State.offCurBdle));
1308}
1309
1310/**
1311 * Does DMA transfer for an HDA input stream.
1312 *
1313 * Reads audio data from the HDA stream's internal DMA buffer and writing to
1314 * guest memory.
1315 *
1316 * @param pDevIns The device instance.
1317 * @param pThis The shared HDA device state.
1318 * @param pStreamShared HDA stream to update (shared).
1319 * @param pStreamR3 HDA stream to update (ring-3).
1320 * @param cbToConsume The max amount of data to consume from the
1321 * internal DMA buffer. The caller will make sure
1322 * this is always the transfer size fo the current
1323 * period (unless something is seriously wrong).
1324 * @param fWriteSilence Whether to feed the guest silence rather than
1325 * fetching bytes from the internal DMA buffer.
1326 * This is set initially while we pre-buffer a
1327 * little bit of input, so we can better handle
1328 * time catch-ups and other schduling fun.
1329 * @param tsNowNs The current RTTimeNano() value.
1330 *
1331 * @remarks Caller owns the stream lock.
1332 */
1333static void hdaR3StreamDoDmaInput(PPDMDEVINS pDevIns, PHDASTATE pThis, PHDASTREAM pStreamShared,
1334 PHDASTREAMR3 pStreamR3, uint32_t cbToConsume, bool fWriteSilence, uint64_t tsNowNs)
1335{
1336 uint8_t const uSD = pStreamShared->u8SD;
1337 LogFlowFunc(("ENTER - #%u cbToConsume=%#x%s\n", uSD, cbToConsume, fWriteSilence ? " silence" : ""));
1338
1339 /*
1340 * Common prologue.
1341 */
1342 if (hdaR3StreamDoDmaPrologue(pThis, pStreamShared, uSD, tsNowNs, "hdaR3StreamDoDmaInput"))
1343 { /* likely */ }
1344 else
1345 return;
1346
1347 /*
1348 *
1349 * The DMA copy loop.
1350 *
1351 */
1352 uint8_t abBounce[4096 + 128]; /* Most guest does at most 4KB BDLE. So, 4KB + space for a partial frame to reduce loops. */
1353 uint32_t cbBounce = 0; /* in case of incomplete frames between buffer segments */
1354 PRTCIRCBUF pCircBuf = pStreamR3->State.pCircBuf;
1355 uint32_t cbLeft = cbToConsume;
1356 Assert(cbLeft == pStreamShared->State.cbTransferSize);
1357 Assert(PDMAudioPropsIsSizeAligned(&pStreamShared->State.Cfg.Props, cbLeft));
1358
1359 while (cbLeft > 0)
1360 {
1361 STAM_PROFILE_START(&pThis->StatIn, a);
1362
1363 /*
1364 * Figure out how much we can read & write in this iteration.
1365 */
1366 uint32_t cbChunk = 0;
1367 RTGCPHYS GCPhys = hdaR3StreamDmaBufGet(pStreamShared, &cbChunk);
1368
1369 /* Need to diverge if the frame format differs or if we're writing silence. */
1370 if ( !pStreamR3->State.Mapping.fMappingNeeded
1371 && !fWriteSilence)
1372 {
1373 if (cbChunk <= cbLeft)
1374 { /* very likely */ }
1375 else
1376 cbChunk = cbLeft;
1377
1378 /*
1379 * Write the host data directly into the guest buffers.
1380 */
1381 while (cbChunk > 0)
1382 {
1383 /* Grab internal DMA buffer space and read into it. */
1384 void /*const*/ *pvBufSrc;
1385 size_t cbBufSrc;
1386 RTCircBufAcquireReadBlock(pCircBuf, cbChunk, &pvBufSrc, &cbBufSrc);
1387 AssertBreakStmt(cbBufSrc, RTCircBufReleaseReadBlock(pCircBuf, 0));
1388
1389 int rc2 = PDMDevHlpPCIPhysWrite(pDevIns, GCPhys, pvBufSrc, cbBufSrc);
1390 AssertRC(rc2);
1391
1392#ifdef HDA_DEBUG_SILENCE
1393 fix me if relevant;
1394#endif
1395 if (RT_LIKELY(!pStreamR3->Dbg.Runtime.fEnabled))
1396 { /* likely */ }
1397 else
1398 AudioHlpFileWrite(pStreamR3->Dbg.Runtime.pFileDMARaw, pvBufSrc, cbBufSrc, 0 /* fFlags */);
1399
1400#ifdef VBOX_WITH_DTRACE
1401 VBOXDD_HDA_STREAM_DMA_IN((uint32_t)uSD, (uint32_t)cbBufSrc, pStreamR3->State.offRead);
1402#endif
1403 pStreamR3->State.offRead += cbBufSrc;
1404 RTCircBufReleaseReadBlock(pCircBuf, cbBufSrc);
1405 STAM_COUNTER_ADD(&pThis->StatBytesRead, cbBufSrc);
1406
1407 /* advance */
1408 cbChunk -= (uint32_t)cbBufSrc;
1409 GCPhys += cbBufSrc;
1410 cbLeft -= (uint32_t)cbBufSrc;
1411 pStreamShared->State.offCurBdle += (uint32_t)cbBufSrc;
1412 }
1413 }
1414 /*
1415 * Either we've got some initial silence to write, or we need to do
1416 * channel mapping. Both produces guest output into the bounce buffer,
1417 * which is then copied into guest memory. The bounce buffer may keep
1418 * partial frames there for the next BDLE, if an BDLE isn't frame aligned.
1419 *
1420 * Note! cbLeft is relative to the input (host) frame size.
1421 * cbChunk OTOH is relative to output (guest) size.
1422 */
1423 else
1424 {
1425 Assert(PDMAudioPropsIsSizeAligned(&pStreamShared->State.Cfg.Props, cbLeft));
1426 uint32_t const cbLeftGuest = PDMAudioPropsFramesToBytes(&pStreamR3->State.Mapping.GuestProps,
1427 PDMAudioPropsBytesToFrames(&pStreamShared->State.Cfg.Props,
1428 cbLeft));
1429 if (cbChunk <= cbLeftGuest)
1430 { /* very likely */ }
1431 else
1432 cbChunk = cbLeftGuest;
1433
1434 /*
1435 * Work till we've covered the chunk.
1436 */
1437 Log5Func(("loop0: GCPhys=%RGp cbChunk=%#x + cbBounce=%#x\n", GCPhys, cbChunk, cbBounce));
1438 while (cbChunk > 0)
1439 {
1440 /* Figure out how much we need to convert into the bounce buffer: */
1441 uint32_t cbGuest = PDMAudioPropsRoundUpBytesToFrame(&pStreamR3->State.Mapping.GuestProps, cbChunk - cbBounce);
1442 uint32_t cFrames = PDMAudioPropsBytesToFrames(&pStreamR3->State.Mapping.GuestProps,
1443 RT_MIN(cbGuest, sizeof(abBounce) - cbBounce));
1444 size_t cbBufSrc;
1445 if (!fWriteSilence)
1446 {
1447 /** @todo we could loop here to optimize buffer wrap around. Not important now though. */
1448 void /*const*/ *pvBufSrc;
1449 RTCircBufAcquireReadBlock(pCircBuf, PDMAudioPropsFramesToBytes(&pStreamShared->State.Cfg.Props, cFrames),
1450 &pvBufSrc, &cbBufSrc);
1451
1452 uint32_t const cFramesToConvert = PDMAudioPropsBytesToFrames(&pStreamShared->State.Cfg.Props,
1453 (uint32_t)cbBufSrc);
1454 Assert(PDMAudioPropsFramesToBytes(&pStreamShared->State.Cfg.Props, cFramesToConvert) == cbBufSrc);
1455 Assert(cFramesToConvert > 0);
1456 Assert(cFramesToConvert <= cFrames);
1457
1458 pStreamR3->State.Mapping.pfnHostToGuest(&abBounce[cbBounce], pvBufSrc, cFramesToConvert,
1459 &pStreamR3->State.Mapping);
1460 Log5Func((" loop1: cbBounce=%#05x cFramesToConvert=%#05x cbBufSrc=%#x%s\n",
1461 cbBounce, cFramesToConvert, cbBufSrc, ASMMemIsZero(pvBufSrc, cbBufSrc) ? " all zero" : ""));
1462#ifdef HDA_DEBUG_SILENCE
1463 fix me if relevant;
1464#endif
1465 if (RT_LIKELY(!pStreamR3->Dbg.Runtime.fEnabled))
1466 { /* likely */ }
1467 else
1468 AudioHlpFileWrite(pStreamR3->Dbg.Runtime.pFileDMARaw, pvBufSrc, cbBufSrc, 0 /* fFlags */);
1469
1470#ifdef VBOX_WITH_DTRACE
1471 VBOXDD_HDA_STREAM_DMA_IN((uint32_t)uSD, (uint32_t)cbBufSrc, pStreamR3->State.offRead);
1472#endif
1473
1474 pStreamR3->State.offRead += cbBufSrc;
1475 RTCircBufReleaseReadBlock(pCircBuf, cbBufSrc);
1476
1477 cFrames = cFramesToConvert;
1478 cbGuest = cbBounce + PDMAudioPropsFramesToBytes(&pStreamR3->State.Mapping.GuestProps, cFrames);
1479 }
1480 else
1481 {
1482 cbBufSrc = PDMAudioPropsFramesToBytes(&pStreamShared->State.Cfg.Props, cFrames);
1483 cbGuest = PDMAudioPropsFramesToBytes(&pStreamR3->State.Mapping.GuestProps, cFrames);
1484 PDMAudioPropsClearBuffer(&pStreamR3->State.Mapping.GuestProps,
1485 &abBounce[cbBounce], cbGuest, cFrames);
1486 cbGuest += cbBounce;
1487 }
1488
1489 /* Write it to the guest buffer. */
1490 uint32_t cbGuestActual = RT_MIN(cbGuest, cbChunk);
1491 int rc2 = PDMDevHlpPCIPhysWrite(pDevIns, GCPhys, abBounce, cbGuestActual);
1492 AssertRC(rc2);
1493 STAM_COUNTER_ADD(&pThis->StatBytesRead, cbGuestActual);
1494
1495 /* advance */
1496 cbLeft -= (uint32_t)cbBufSrc;
1497 cbChunk -= cbGuestActual;
1498 GCPhys += cbGuestActual;
1499 pStreamShared->State.offCurBdle += cbGuestActual;
1500
1501 cbBounce = cbGuest - cbGuestActual;
1502 if (cbBounce)
1503 memmove(abBounce, &abBounce[cbGuestActual], cbBounce);
1504
1505 Log5Func((" loop1: GCPhys=%RGp cbGuestActual=%#x cbBounce=%#x cFrames=%#x\n", GCPhys, cbGuestActual, cbBounce, cFrames));
1506 }
1507 Log5Func(("loop0: GCPhys=%RGp cbBounce=%#x cbLeft=%#x\n", GCPhys, cbBounce, cbLeft));
1508 }
1509
1510 STAM_PROFILE_STOP(&pThis->StatIn, a);
1511
1512 /*
1513 * Complete the buffer if necessary (common with the output DMA code).
1514 */
1515 hdaR3StreamDoDmaMaybeCompleteBuffer(pDevIns, pThis, pStreamShared, "hdaR3StreamDoDmaInput");
1516 }
1517
1518 Assert(cbLeft == 0); /* There shall be no break statements in the above loop, so cbLeft is always zero here! */
1519 AssertMsg(cbBounce == 0, ("%#x\n", cbBounce));
1520
1521 /*
1522 * Common epilogue.
1523 */
1524 hdaR3StreamDoDmaEpilogue(pDevIns, pStreamShared, pStreamR3);
1525
1526 /*
1527 * Log and leave.
1528 */
1529 Log3Func(("LEAVE - [SD%RU8] %#RX32/%#RX32 @ %#RX64 - cTransferPendingInterrupts=%RU8\n",
1530 uSD, cbToConsume, pStreamShared->State.cbTransferSize, pStreamR3->State.offRead - cbToConsume,
1531 pStreamShared->State.cTransferPendingInterrupts));
1532}
1533
1534
1535/**
1536 * Input streams: Pulls data from to the host device thru the mixer, putting it
1537 * in the internal DMA buffer.
1538 *
1539 * @param pStreamShared HDA stream to update (shared bits).
1540 * @param pStreamR3 HDA stream to update (ring-3 bits).
1541 * @param pSink The mixer sink to pull from.
1542 */
1543static void hdaR3StreamPullFromMixer(PHDASTREAM pStreamShared, PHDASTREAMR3 pStreamR3, PAUDMIXSINK pSink)
1544{
1545 RT_NOREF(pStreamShared);
1546 int rc = AudioMixerSinkUpdate(pSink);
1547 AssertRC(rc);
1548
1549 /* Is the sink ready to be read (host input data) from? If so, by how much? */
1550 uint32_t cbSinkReadable = AudioMixerSinkGetReadable(pSink);
1551
1552 /* How much (guest input) data is available for writing at the moment for the HDA stream? */
1553 const uint32_t cbStreamFree = hdaR3StreamGetFree(pStreamR3);
1554
1555 Log3Func(("[SD%RU8] cbSinkReadable=%RU32, cbStreamFree=%RU32\n", pStreamShared->u8SD, cbSinkReadable, cbStreamFree));
1556
1557 /* Do not read more than the HDA stream can hold at the moment.
1558 * The host sets the overall pace. */
1559 if (cbSinkReadable > cbStreamFree)
1560 cbSinkReadable = cbStreamFree;
1561
1562 /** @todo should we throttle (read less) this if we're far ahead? */
1563
1564 /*
1565 * Copy loop.
1566 */
1567 while (cbSinkReadable)
1568 {
1569 /* Read a chunk of data. */
1570 uint8_t abBuf[4096];
1571 uint32_t cbRead = 0;
1572 rc = AudioMixerSinkRead(pSink, AUDMIXOP_COPY, abBuf, RT_MIN(cbSinkReadable, sizeof(abBuf)), &cbRead);
1573 AssertRCBreak(rc);
1574 AssertMsg(cbRead > 0, ("Nothing read from sink, even if %RU32 bytes were (still) announced\n", cbSinkReadable));
1575
1576 /* Write it to the internal DMA buffer. */
1577 uint32_t off = 0;
1578 while (off < cbRead)
1579 {
1580 void *pvDstBuf;
1581 size_t cbDstBuf;
1582 RTCircBufAcquireWriteBlock(pStreamR3->State.pCircBuf, cbRead - off, &pvDstBuf, &cbDstBuf);
1583
1584 memcpy(pvDstBuf, &abBuf[off], cbDstBuf);
1585
1586#ifdef VBOX_WITH_DTRACE
1587 VBOXDD_HDA_STREAM_AIO_IN((uint32_t)pStreamR3->u8SD, (uint32_t)cbDstBuf, pStreamR3->State.offWrite);
1588#endif
1589 pStreamR3->State.offWrite += cbDstBuf;
1590
1591 RTCircBufReleaseWriteBlock(pStreamR3->State.pCircBuf, cbDstBuf);
1592
1593 off += (uint32_t)cbDstBuf;
1594 }
1595 Assert(off == cbRead);
1596
1597 /* Write to debug file? */
1598 if (RT_LIKELY(!pStreamR3->Dbg.Runtime.fEnabled))
1599 { /* likely */ }
1600 else
1601 AudioHlpFileWrite(pStreamR3->Dbg.Runtime.pFileStream, abBuf, cbRead, 0 /* fFlags */);
1602
1603 /* Advance. */
1604 Assert(cbRead <= cbSinkReadable);
1605 cbSinkReadable -= cbRead;
1606 }
1607
1608 /* Update buffer stats. */
1609 pStreamR3->State.StatDmaBufUsed = (uint32_t)RTCircBufUsed(pStreamR3->State.pCircBuf);
1610}
1611
1612/**
1613 * Does DMA transfer for an HDA output stream.
1614 *
1615 * This transfers one DMA timer period worth of data from the guest and into the
1616 * internal DMA buffer.
1617 *
1618 * @param pDevIns The device instance.
1619 * @param pThis The shared HDA device state.
1620 * @param pStreamShared HDA stream to update (shared).
1621 * @param pStreamR3 HDA stream to update (ring-3).
1622 * @param cbToProduce The max amount of data to produce (i.e. put into
1623 * the circular buffer). Unless something is going
1624 * seriously wrong, this will always be transfer
1625 * size for the current period.
1626 * @param tsNowNs The current RTTimeNano() value.
1627 *
1628 * @remarks Caller owns the stream lock.
1629 */
1630static void hdaR3StreamDoDmaOutput(PPDMDEVINS pDevIns, PHDASTATE pThis, PHDASTREAM pStreamShared,
1631 PHDASTREAMR3 pStreamR3, uint32_t cbToProduce, uint64_t tsNowNs)
1632{
1633 uint8_t const uSD = pStreamShared->u8SD;
1634 LogFlowFunc(("ENTER - #%u cbToProduce=%#x\n", uSD, cbToProduce));
1635
1636 /*
1637 * Common prologue.
1638 */
1639 if (hdaR3StreamDoDmaPrologue(pThis, pStreamShared, uSD, tsNowNs, "hdaR3StreamDoDmaOutput"))
1640 { /* likely */ }
1641 else
1642 return;
1643
1644 /*
1645 *
1646 * The DMA copy loop.
1647 *
1648 */
1649 uint8_t abBounce[4096 + 128]; /* Most guest does at most 4KB BDLE. So, 4KB + space for a partial frame to reduce loops. */
1650 uint32_t cbBounce = 0; /* in case of incomplete frames between buffer segments */
1651 PRTCIRCBUF pCircBuf = pStreamR3->State.pCircBuf;
1652 uint32_t cbLeft = cbToProduce;
1653 Assert(cbLeft == pStreamShared->State.cbTransferSize);
1654 Assert(PDMAudioPropsIsSizeAligned(&pStreamShared->State.Cfg.Props, cbLeft));
1655
1656 while (cbLeft > 0)
1657 {
1658 STAM_PROFILE_START(&pThis->StatOut, a);
1659
1660 /*
1661 * Figure out how much we can read & write in this iteration.
1662 */
1663 uint32_t cbChunk = 0;
1664 RTGCPHYS GCPhys = hdaR3StreamDmaBufGet(pStreamShared, &cbChunk);
1665
1666 /* Need to diverge if the frame format differs. */
1667 if ( !pStreamR3->State.Mapping.fMappingNeeded
1668 /** @todo && pStreamShared->State.fFrameAlignedBuffers */)
1669 {
1670 if (cbChunk <= cbLeft)
1671 { /* very likely */ }
1672 else
1673 cbChunk = cbLeft;
1674
1675 /*
1676 * Read the guest data directly into the internal DMA buffer.
1677 */
1678 while (cbChunk > 0)
1679 {
1680 /* Grab internal DMA buffer space and read into it. */
1681 void *pvBufDst;
1682 size_t cbBufDst;
1683 RTCircBufAcquireWriteBlock(pCircBuf, cbChunk, &pvBufDst, &cbBufDst);
1684 AssertBreakStmt(cbBufDst, RTCircBufReleaseWriteBlock(pCircBuf, 0));
1685
1686 int rc2 = PDMDevHlpPhysRead(pDevIns, GCPhys, pvBufDst, cbBufDst);
1687 AssertRC(rc2);
1688
1689#ifdef HDA_DEBUG_SILENCE
1690 fix me if relevant;
1691#endif
1692 if (RT_LIKELY(!pStreamR3->Dbg.Runtime.fEnabled))
1693 { /* likely */ }
1694 else
1695 AudioHlpFileWrite(pStreamR3->Dbg.Runtime.pFileDMARaw, pvBufDst, cbBufDst, 0 /* fFlags */);
1696
1697#ifdef VBOX_WITH_DTRACE
1698 VBOXDD_HDA_STREAM_DMA_OUT((uint32_t)uSD, (uint32_t)cbBufDst, pStreamR3->State.offWrite);
1699#endif
1700 pStreamR3->State.offWrite += cbBufDst;
1701 RTCircBufReleaseWriteBlock(pCircBuf, cbBufDst);
1702 STAM_COUNTER_ADD(&pThis->StatBytesRead, cbBufDst);
1703
1704 /* advance */
1705 cbChunk -= (uint32_t)cbBufDst;
1706 GCPhys += cbBufDst;
1707 cbLeft -= (uint32_t)cbBufDst;
1708 pStreamShared->State.offCurBdle += (uint32_t)cbBufDst;
1709 }
1710 }
1711 /*
1712 * Need to map the frame content, so we need to read the guest data
1713 * into a temporary buffer, though the output can be directly written
1714 * into the internal buffer as it is assumed to be frame aligned.
1715 *
1716 * Note! cbLeft is relative to the output frame size.
1717 * cbChunk OTOH is relative to input size.
1718 */
1719 else
1720 {
1721 Assert(PDMAudioPropsIsSizeAligned(&pStreamShared->State.Cfg.Props, cbLeft));
1722 uint32_t const cbLeftGuest = PDMAudioPropsFramesToBytes(&pStreamR3->State.Mapping.GuestProps,
1723 PDMAudioPropsBytesToFrames(&pStreamShared->State.Cfg.Props,
1724 cbLeft));
1725 if (cbChunk <= cbLeftGuest)
1726 { /* very likely */ }
1727 else
1728 cbChunk = cbLeftGuest;
1729
1730 /*
1731 * Loop till we've covered the chunk.
1732 */
1733 Log5Func(("loop0: GCPhys=%RGp cbChunk=%#x + cbBounce=%#x\n", GCPhys, cbChunk, cbBounce));
1734 while (cbChunk > 0)
1735 {
1736 /* Read into the bounce buffer. */
1737 uint32_t const cbToRead = RT_MIN(cbChunk, sizeof(abBounce) - cbBounce);
1738 int rc2 = PDMDevHlpPhysRead(pDevIns, GCPhys, &abBounce[cbBounce], cbToRead);
1739 AssertRC(rc2);
1740 cbBounce += cbToRead;
1741
1742 /* Convert the size to whole frames and a remainder. */
1743 uint32_t cFrames = PDMAudioPropsBytesToFrames(&pStreamR3->State.Mapping.GuestProps, cbBounce);
1744 uint32_t const cbRemainder = cbBounce - PDMAudioPropsFramesToBytes(&pStreamR3->State.Mapping.GuestProps, cFrames);
1745 Log5Func((" loop1: GCPhys=%RGp cbToRead=%#x cbBounce=%#x cFrames=%#x\n", GCPhys, cbToRead, cbBounce, cFrames));
1746
1747 /*
1748 * Convert from the bounce buffer and into the internal DMA buffer.
1749 */
1750 uint32_t offBounce = 0;
1751 while (cFrames > 0)
1752 {
1753 void *pvBufDst;
1754 size_t cbBufDst;
1755 RTCircBufAcquireWriteBlock(pCircBuf, PDMAudioPropsFramesToBytes(&pStreamShared->State.Cfg.Props, cFrames),
1756 &pvBufDst, &cbBufDst);
1757
1758 uint32_t const cFramesToConvert = PDMAudioPropsBytesToFrames(&pStreamShared->State.Cfg.Props, (uint32_t)cbBufDst);
1759 Assert(PDMAudioPropsFramesToBytes(&pStreamShared->State.Cfg.Props, cFramesToConvert) == cbBufDst);
1760 Assert(cFramesToConvert > 0);
1761 Assert(cFramesToConvert <= cFrames);
1762
1763 pStreamR3->State.Mapping.pfnGuestToHost(pvBufDst, &abBounce[offBounce], cFramesToConvert,
1764 &pStreamR3->State.Mapping);
1765 Log5Func((" loop2: offBounce=%#05x cFramesToConvert=%#05x cbBufDst=%#x%s\n",
1766 offBounce, cFramesToConvert, cbBufDst, ASMMemIsZero(pvBufDst, cbBufDst) ? " all zero" : ""));
1767
1768# ifdef HDA_DEBUG_SILENCE
1769 fix me if relevant;
1770# endif
1771 if (RT_LIKELY(!pStreamR3->Dbg.Runtime.fEnabled))
1772 { /* likely */ }
1773 else
1774 AudioHlpFileWrite(pStreamR3->Dbg.Runtime.pFileDMARaw, pvBufDst, cbBufDst, 0 /* fFlags */);
1775
1776 pStreamR3->State.offWrite += cbBufDst;
1777 RTCircBufReleaseWriteBlock(pCircBuf, cbBufDst);
1778 STAM_COUNTER_ADD(&pThis->StatBytesRead, cbBufDst);
1779
1780 /* advance */
1781 cbLeft -= (uint32_t)cbBufDst;
1782 cFrames -= cFramesToConvert;
1783 offBounce += PDMAudioPropsFramesToBytes(&pStreamR3->State.Mapping.GuestProps, cFramesToConvert);
1784 }
1785
1786 /* advance */
1787 cbChunk -= cbToRead;
1788 GCPhys += cbToRead;
1789 pStreamShared->State.offCurBdle += cbToRead;
1790 if (cbRemainder)
1791 memmove(&abBounce[0], &abBounce[cbBounce - cbRemainder], cbRemainder);
1792 cbBounce = cbRemainder;
1793 }
1794 Log5Func(("loop0: GCPhys=%RGp cbBounce=%#x cbLeft=%#x\n", GCPhys, cbBounce, cbLeft));
1795 }
1796
1797 STAM_PROFILE_STOP(&pThis->StatOut, a);
1798
1799 /*
1800 * Complete the buffer if necessary (common with the output DMA code).
1801 */
1802 hdaR3StreamDoDmaMaybeCompleteBuffer(pDevIns, pThis, pStreamShared, "hdaR3StreamDoDmaOutput");
1803 }
1804
1805 Assert(cbLeft == 0); /* There shall be no break statements in the above loop, so cbLeft is always zero here! */
1806 AssertMsg(cbBounce == 0, ("%#x\n", cbBounce));
1807
1808 /*
1809 * Common epilogue.
1810 */
1811 hdaR3StreamDoDmaEpilogue(pDevIns, pStreamShared, pStreamR3);
1812
1813 /*
1814 * Log and leave.
1815 */
1816 Log3Func(("LEAVE - [SD%RU8] %#RX32/%#RX32 @ %#RX64 - cTransferPendingInterrupts=%RU8\n",
1817 uSD, cbToProduce, pStreamShared->State.cbTransferSize, pStreamR3->State.offWrite - cbToProduce,
1818 pStreamShared->State.cTransferPendingInterrupts));
1819}
1820
1821/**
1822 * Output streams: Pushes data from to the mixer and host device.
1823 *
1824 * @param pStreamShared HDA stream to update (shared bits).
1825 * @param pStreamR3 HDA stream to update (ring-3 bits).
1826 * @param pSink The mixer sink to push to.
1827 * @param nsNow The current RTTimeNanoTS() value.
1828 */
1829static void hdaR3StreamPushToMixer(PHDASTREAM pStreamShared, PHDASTREAMR3 pStreamR3, PAUDMIXSINK pSink, uint64_t nsNow)
1830{
1831 /*
1832 * Figure how much that we can push down.
1833 */
1834 uint32_t const cbSinkWritable = AudioMixerSinkGetWritable(pSink);
1835 uint32_t const cbStreamReadable = hdaR3StreamGetUsed(pStreamR3);
1836 uint32_t cbToReadFromStream = RT_MIN(cbStreamReadable, cbSinkWritable);
1837 /* Make sure that we always align the number of bytes when reading to the stream's PCM properties. */
1838 cbToReadFromStream = PDMAudioPropsFloorBytesToFrame(&pStreamShared->State.Cfg.Props, cbToReadFromStream);
1839
1840 Assert(nsNow >= pStreamShared->State.tsLastReadNs);
1841 Log3Func(("[SD%RU8] nsDeltaLastRead=%RI64 cbSinkWritable=%RU32 cbStreamReadable=%RU32 -> cbToReadFromStream=%RU32\n",
1842 pStreamShared->u8SD, nsNow - pStreamShared->State.tsLastReadNs, cbSinkWritable, cbStreamReadable, cbToReadFromStream));
1843 RT_NOREF(pStreamShared, nsNow);
1844
1845 /*
1846 * Do the pushing.
1847 */
1848 Assert(pStreamR3->State.pCircBuf);
1849 while (cbToReadFromStream > 0)
1850 {
1851 void /*const*/ *pvSrcBuf;
1852 size_t cbSrcBuf;
1853 RTCircBufAcquireReadBlock(pStreamR3->State.pCircBuf, cbToReadFromStream, &pvSrcBuf, &cbSrcBuf);
1854
1855 if (!pStreamR3->Dbg.Runtime.fEnabled)
1856 { /* likely */ }
1857 else
1858 AudioHlpFileWrite(pStreamR3->Dbg.Runtime.pFileStream, pvSrcBuf, cbSrcBuf, 0 /* fFlags */);
1859
1860 uint32_t cbWritten = 0;
1861 int rc = AudioMixerSinkWrite(pSink, AUDMIXOP_COPY, pvSrcBuf, (uint32_t)cbSrcBuf, &cbWritten);
1862 AssertRC(rc);
1863 Assert(cbWritten <= cbSrcBuf);
1864
1865 Log2Func(("[SD%RU8] %#RX32/%#zx bytes read @ %#RX64\n", pStreamR3->u8SD, cbWritten, cbSrcBuf, pStreamR3->State.offRead));
1866#ifdef VBOX_WITH_DTRACE
1867 VBOXDD_HDA_STREAM_AIO_OUT(pStreamR3->u8SD, cbWritten, pStreamR3->State.offRead);
1868#endif
1869 pStreamR3->State.offRead += cbWritten;
1870
1871 RTCircBufReleaseReadBlock(pStreamR3->State.pCircBuf, cbWritten);
1872
1873 /* advance */
1874 cbToReadFromStream -= cbWritten;
1875 }
1876
1877 /* Update buffer stats. */
1878 pStreamR3->State.StatDmaBufUsed = (uint32_t)RTCircBufUsed(pStreamR3->State.pCircBuf);
1879
1880 /*
1881 * Push the stuff thru the mixer jungle and down the host audio driver (backend).
1882 */
1883 int rc2 = AudioMixerSinkUpdate(pSink);
1884 AssertRC(rc2);
1885}
1886
1887/**
1888 * The stream's main function when called by the timer.
1889 *
1890 * @note This function also will be called without timer invocation when
1891 * starting (enabling) the stream to minimize startup latency.
1892 *
1893 * @returns Current timer time if the timer is enabled, otherwise zero.
1894 * @param pDevIns The device instance.
1895 * @param pThis The shared HDA device state.
1896 * @param pThisCC The ring-3 HDA device state.
1897 * @param pStreamShared HDA stream to update (shared bits).
1898 * @param pStreamR3 HDA stream to update (ring-3 bits).
1899 */
1900uint64_t hdaR3StreamTimerMain(PPDMDEVINS pDevIns, PHDASTATE pThis, PHDASTATER3 pThisCC,
1901 PHDASTREAM pStreamShared, PHDASTREAMR3 pStreamR3)
1902{
1903 Assert(PDMDevHlpCritSectIsOwner(pDevIns, &pThis->CritSect));
1904 Assert(PDMDevHlpTimerIsLockOwner(pDevIns, pStreamShared->hTimer));
1905
1906 /* Do the work: */
1907 hdaR3StreamUpdate(pDevIns, pThis, pThisCC, pStreamShared, pStreamR3, true /* fInTimer */);
1908
1909 /* Re-arm the timer if the sink is still active: */
1910 if ( pStreamShared->State.fRunning
1911 && pStreamR3->pMixSink
1912 && AudioMixerSinkIsActive(pStreamR3->pMixSink->pMixSink))
1913 {
1914 /* Advance the schduling: */
1915 uint32_t idxSched = pStreamShared->State.idxSchedule;
1916 AssertStmt(idxSched < RT_ELEMENTS(pStreamShared->State.aSchedule), idxSched = 0);
1917 uint32_t idxLoop = pStreamShared->State.idxScheduleLoop + 1;
1918 if (idxLoop >= pStreamShared->State.aSchedule[idxSched].cLoops)
1919 {
1920 idxSched += 1;
1921 if ( idxSched >= pStreamShared->State.cSchedule
1922 || idxSched >= RT_ELEMENTS(pStreamShared->State.aSchedule) /*paranoia^2*/)
1923 {
1924 idxSched = pStreamShared->State.cSchedulePrologue;
1925 AssertStmt(idxSched < RT_ELEMENTS(pStreamShared->State.aSchedule), idxSched = 0);
1926 }
1927 pStreamShared->State.idxSchedule = idxSched;
1928 idxLoop = 0;
1929 }
1930 pStreamShared->State.idxScheduleLoop = (uint16_t)idxLoop;
1931
1932 /* Do the actual timer re-arming. */
1933 uint64_t const tsNow = PDMDevHlpTimerGet(pDevIns, pStreamShared->hTimer); /* (For virtual sync this remains the same for the whole callout IIRC) */
1934 uint64_t const tsTransferNext = tsNow + pStreamShared->State.aSchedule[idxSched].cPeriodTicks;
1935 Log3Func(("[SD%RU8] fSinkActive=true, tsTransferNext=%RU64 (in %RU64)\n",
1936 pStreamShared->u8SD, tsTransferNext, tsTransferNext - tsNow));
1937 int rc = PDMDevHlpTimerSet(pDevIns, pStreamShared->hTimer, tsTransferNext);
1938 AssertRC(rc);
1939
1940 /* Some legacy stuff: */
1941 pStreamShared->State.tsTransferNext = tsTransferNext;
1942 pStreamShared->State.cbTransferSize = pStreamShared->State.aSchedule[idxSched].cbPeriod;
1943
1944 return tsNow;
1945 }
1946
1947 Log3Func(("[SD%RU8] fSinkActive=false\n", pStreamShared->u8SD));
1948 return 0;
1949}
1950
1951/**
1952 * Updates a HDA stream by doing its required data transfers.
1953 *
1954 * The host sink(s) set the overall pace.
1955 *
1956 * This routine is called by both, the synchronous and the asynchronous
1957 * (VBOX_WITH_AUDIO_HDA_ASYNC_IO), implementations.
1958 *
1959 * When running synchronously, the device DMA transfers *and* the mixer sink
1960 * processing is within the device timer.
1961 *
1962 * When running asynchronously, only the device DMA transfers are done in the
1963 * device timer, whereas the mixer sink processing then is done in the stream's
1964 * own async I/O thread. This thread also will call this function
1965 * (with fInTimer set to @c false).
1966 *
1967 * @param pDevIns The device instance.
1968 * @param pThis The shared HDA device state.
1969 * @param pThisCC The ring-3 HDA device state.
1970 * @param pStreamShared HDA stream to update (shared bits).
1971 * @param pStreamR3 HDA stream to update (ring-3 bits).
1972 * @param fInTimer Whether to this function was called from the timer
1973 * context or an asynchronous I/O stream thread (if supported).
1974 */
1975void hdaR3StreamUpdate(PPDMDEVINS pDevIns, PHDASTATE pThis, PHDASTATER3 pThisCC,
1976 PHDASTREAM pStreamShared, PHDASTREAMR3 pStreamR3, bool fInTimer)
1977{
1978 RT_NOREF(pThisCC);
1979 int rc2;
1980
1981 /*
1982 * Make sure we're running and got an active mixer sink.
1983 */
1984 if (RT_LIKELY(pStreamShared->State.fRunning))
1985 { /* likely */ }
1986 else
1987 return;
1988
1989 PAUDMIXSINK pSink = NULL;
1990 if (pStreamR3->pMixSink)
1991 pSink = pStreamR3->pMixSink->pMixSink;
1992 if (RT_LIKELY(AudioMixerSinkIsActive(pSink)))
1993 { /* likely */ }
1994 else
1995 return;
1996
1997 /*
1998 * Get scheduling info common to both input and output streams.
1999 */
2000 const uint64_t tsNowNs = RTTimeNanoTS();
2001 uint32_t idxSched = pStreamShared->State.idxSchedule;
2002 AssertStmt(idxSched < RT_MIN(RT_ELEMENTS(pStreamShared->State.aSchedule), pStreamShared->State.cSchedule), idxSched = 0);
2003 uint32_t const cbPeriod = pStreamShared->State.aSchedule[idxSched].cbPeriod;
2004
2005 /*
2006 * Output streams (SDO).
2007 */
2008 if (hdaGetDirFromSD(pStreamShared->u8SD) == PDMAUDIODIR_OUT)
2009 {
2010 bool fDoRead; /* Whether to push data down the driver stack or not. */
2011# ifdef VBOX_WITH_AUDIO_HDA_ASYNC_IO
2012 if (fInTimer)
2013# endif
2014 {
2015 /*
2016 * Check how much room we have in our DMA buffer. There should be at
2017 * least one period worth of space there or we're in an overflow situation.
2018 */
2019 uint32_t cbStreamFree = hdaR3StreamGetFree(pStreamR3);
2020 if (cbStreamFree >= cbPeriod)
2021 { /* likely */ }
2022 else
2023 {
2024 STAM_REL_COUNTER_INC(&pStreamR3->State.StatDmaFlowProblems);
2025 Log(("hdaR3StreamUpdate: Warning! Stream #%u has insufficient space free: %u bytes, need %u. Will try move data out of the buffer...\n",
2026 pStreamShared->u8SD, cbStreamFree, cbPeriod));
2027# ifdef VBOX_WITH_AUDIO_HDA_ASYNC_IO
2028 int rc = RTCritSectTryEnter(&pStreamR3->State.AIO.CritSect);
2029 if (RT_SUCCESS(rc))
2030 {
2031 hdaR3StreamPushToMixer(pStreamShared, pStreamR3, pSink, tsNowNs);
2032 RTCritSectLeave(&pStreamR3->State.AIO.CritSect);
2033 }
2034 else
2035 RTThreadYield();
2036#else
2037 hdaR3StreamPushToMixer(pStreamShared, pStreamR3, pSink, tsNowNs);
2038#endif
2039 Log(("hdaR3StreamUpdate: Gained %u bytes.\n", hdaR3StreamGetFree(pStreamR3) - cbStreamFree));
2040
2041 cbStreamFree = hdaR3StreamGetFree(pStreamR3);
2042 if (cbStreamFree < cbPeriod)
2043 {
2044 /* Unable to make sufficient space. Drop the whole buffer content.
2045 * This is needed in order to keep the device emulation running at a constant rate,
2046 * at the cost of losing valid (but too much) data. */
2047 STAM_REL_COUNTER_INC(&pStreamR3->State.StatDmaFlowErrors);
2048 LogRel2(("HDA: Warning: Hit stream #%RU8 overflow, dropping %u bytes of audio data\n",
2049 pStreamShared->u8SD, hdaR3StreamGetUsed(pStreamR3)));
2050# ifdef HDA_STRICT
2051 AssertMsgFailed(("Hit stream #%RU8 overflow -- timing bug?\n", pStreamShared->u8SD));
2052# endif
2053 RTCircBufReset(pStreamR3->State.pCircBuf);
2054 pStreamR3->State.offWrite = 0;
2055 pStreamR3->State.offRead = 0;
2056 cbStreamFree = hdaR3StreamGetFree(pStreamR3);
2057 }
2058 }
2059
2060 /*
2061 * Do the DMA transfer.
2062 */
2063# ifdef VBOX_WITH_AUDIO_HDA_ASYNC_IO
2064 rc2 = PDMDevHlpCritSectEnter(pDevIns, &pStreamShared->CritSect, VERR_IGNORED);
2065 AssertRC(rc2);
2066# endif
2067
2068 uint64_t const offWriteBefore = pStreamR3->State.offWrite;
2069 hdaR3StreamDoDmaOutput(pDevIns, pThis, pStreamShared, pStreamR3, RT_MIN(cbStreamFree, cbPeriod), tsNowNs);
2070
2071# ifdef VBOX_WITH_AUDIO_HDA_ASYNC_IO
2072 rc2 = PDMDevHlpCritSectLeave(pDevIns, &pStreamShared->CritSect);
2073 AssertRC(rc2);
2074# endif
2075
2076 /*
2077 * Should we push data to down thru the mixer to and to the host drivers?
2078 *
2079 * We initially delay this by pThis->msInitialDelay, but after than we'll
2080 * kick the AIO thread every time we've put more data in the buffer (which is
2081 * every time) as the host audio device needs to get data in a timely manner.
2082 *
2083 * (We used to try only wake up the AIO thread according to pThis->uIoTimer
2084 * and host wall clock, but that meant we would miss a wakup after the DMA
2085 * timer was called a little late or if TM entered into catch-up mode.)
2086 */
2087 if (!pStreamShared->State.tsAioDelayEnd)
2088 fDoRead = pStreamR3->State.offWrite > offWriteBefore
2089 || hdaR3StreamGetFree(pStreamR3) < pStreamShared->State.cbAvgTransfer * 2;
2090 else if (PDMDevHlpTimerGet(pDevIns, pStreamShared->hTimer) >= pStreamShared->State.tsAioDelayEnd)
2091 {
2092 Log3Func(("Initial delay done: Passed tsAioDelayEnd.\n"));
2093 pStreamShared->State.tsAioDelayEnd = 0;
2094 fDoRead = true;
2095 }
2096 else if (hdaR3StreamGetFree(pStreamR3) < pStreamShared->State.cbAvgTransfer * 2)
2097 {
2098 Log3Func(("Initial delay done: Passed running short on buffer.\n"));
2099 pStreamShared->State.tsAioDelayEnd = 0;
2100 fDoRead = true;
2101 }
2102 else
2103 {
2104 Log3Func(("Initial delay pending...\n"));
2105 fDoRead = false;
2106 }
2107
2108 Log3Func(("msDelta=%RU64 (vs %u) cbStreamFree=%#x (vs %#x) => fDoRead=%RTbool\n",
2109 (tsNowNs - pStreamShared->State.tsLastReadNs) / RT_NS_1MS,
2110 pStreamShared->State.Cfg.Device.cMsSchedulingHint, cbStreamFree,
2111 pStreamShared->State.cbAvgTransfer * 2, fDoRead));
2112
2113 if (fDoRead)
2114 {
2115# ifdef VBOX_WITH_AUDIO_HDA_ASYNC_IO
2116 /* Notify the async I/O worker thread that there's work to do. */
2117 Log5Func(("Notifying AIO thread\n"));
2118 rc2 = hdaR3StreamAsyncIONotify(pStreamR3);
2119 AssertRC(rc2);
2120# endif
2121 /* Update last read timestamp for logging/debugging. */
2122 pStreamShared->State.tsLastReadNs = tsNowNs;
2123 }
2124 }
2125
2126 /*
2127 * Move data out of the pStreamR3->State.pCircBuf buffer and to
2128 * the mixer and in direction of the host audio devices.
2129 */
2130# ifdef VBOX_WITH_AUDIO_HDA_ASYNC_IO
2131 else
2132# else
2133 if (fDoRead)
2134# endif
2135 hdaR3StreamPushToMixer(pStreamShared, pStreamR3, pSink, tsNowNs);
2136 }
2137 /*
2138 * Input stream (SDI).
2139 */
2140 else
2141 {
2142 Assert(hdaGetDirFromSD(pStreamShared->u8SD) == PDMAUDIODIR_IN);
2143
2144 /*
2145 * If we're the async I/O worker, or not using AIO, pull bytes
2146 * from the mixer and into our internal DMA buffer.
2147 */
2148# ifdef VBOX_WITH_AUDIO_HDA_ASYNC_IO
2149 if (!fInTimer)
2150# endif
2151 hdaR3StreamPullFromMixer(pStreamShared, pStreamR3, pSink);
2152# ifdef VBOX_WITH_AUDIO_HDA_ASYNC_IO
2153 else /* fInTimer */
2154# endif
2155 {
2156 /*
2157 * See how much data we've got buffered...
2158 */
2159 bool fWriteSilence = false;
2160 uint32_t cbStreamUsed = hdaR3StreamGetUsed(pStreamR3);
2161 if (pStreamShared->State.fInputPreBuffered && cbStreamUsed >= cbPeriod)
2162 { /*likely*/ }
2163 /*
2164 * Because it may take a while for the input stream to get going (at
2165 * least with pulseaudio), we feed the guest silence till we've
2166 * pre-buffer a reasonable amount of audio.
2167 */
2168 else if (!pStreamShared->State.fInputPreBuffered)
2169 {
2170 if (cbStreamUsed < pStreamShared->State.cbInputPreBuffer)
2171 {
2172 Log3(("hdaR3StreamUpdate: Pre-buffering (got %#x out of %#x bytes)...\n",
2173 cbStreamUsed, pStreamShared->State.cbInputPreBuffer));
2174 fWriteSilence = true;
2175 }
2176 else
2177 {
2178 Log3(("hdaR3StreamUpdate: Completed pre-buffering (got %#x, needed %#x bytes).\n",
2179 cbStreamUsed, pStreamShared->State.cbInputPreBuffer));
2180 pStreamShared->State.fInputPreBuffered = true;
2181 fWriteSilence = true; /* For now, just do the most conservative thing. */
2182 }
2183 cbStreamUsed = cbPeriod;
2184 }
2185 /*
2186 * When we're low on data, we must really try fetch some ourselves
2187 * as buffer underruns must not happen.
2188 */
2189 else
2190 {
2191 /** @todo We're ending up here to frequently with pulse audio at least (just
2192 * watch the stream stats in the statistcs viewer, and way to often we
2193 * have to inject silence bytes. I suspect part of the problem is
2194 * that the HDA device require a much better latency than what the
2195 * pulse audio is configured for by default (10 ms vs 150ms). */
2196 STAM_REL_COUNTER_INC(&pStreamR3->State.StatDmaFlowProblems);
2197 Log(("hdaR3StreamUpdate: Warning! Stream #%u has insufficient data available: %u bytes, need %u. Will try move pull more data into the buffer...\n",
2198 pStreamShared->u8SD, cbStreamUsed, cbPeriod));
2199# ifdef VBOX_WITH_AUDIO_HDA_ASYNC_IO
2200 int rc = RTCritSectTryEnter(&pStreamR3->State.AIO.CritSect);
2201 if (RT_SUCCESS(rc))
2202 {
2203 hdaR3StreamPullFromMixer(pStreamShared, pStreamR3, pSink);
2204 RTCritSectLeave(&pStreamR3->State.AIO.CritSect);
2205 }
2206 else
2207 RTThreadYield();
2208#else
2209 hdaR3StreamPullFromMixer(pStreamShared, pStreamR3, pSink);
2210#endif
2211 Log(("hdaR3StreamUpdate: Gained %u bytes.\n", hdaR3StreamGetUsed(pStreamR3) - cbStreamUsed));
2212 cbStreamUsed = hdaR3StreamGetUsed(pStreamR3);
2213 if (cbStreamUsed < cbPeriod)
2214 {
2215 /* Unable to find sufficient input data by simple prodding.
2216 In order to keep a constant byte stream following thru the DMA
2217 engine into the guest, we will try again and then fall back on
2218 filling the gap with silence. */
2219 uint32_t cbSilence = 0;
2220 do
2221 {
2222#ifdef VBOX_WITH_AUDIO_HDA_ASYNC_IO
2223 RTCritSectEnter(&pStreamR3->State.AIO.CritSect);
2224#endif
2225 cbStreamUsed = hdaR3StreamGetUsed(pStreamR3);
2226 if (cbStreamUsed < cbPeriod)
2227 {
2228 hdaR3StreamPullFromMixer(pStreamShared, pStreamR3, pSink);
2229 cbStreamUsed = hdaR3StreamGetUsed(pStreamR3);
2230 while (cbStreamUsed < cbPeriod)
2231 {
2232 void *pvDstBuf;
2233 size_t cbDstBuf;
2234 RTCircBufAcquireWriteBlock(pStreamR3->State.pCircBuf, cbPeriod - cbStreamUsed,
2235 &pvDstBuf, &cbDstBuf);
2236 RT_BZERO(pvDstBuf, cbDstBuf);
2237 RTCircBufReleaseWriteBlock(pStreamR3->State.pCircBuf, cbDstBuf);
2238 cbSilence += (uint32_t)cbDstBuf;
2239 cbStreamUsed += (uint32_t)cbDstBuf;
2240 }
2241 }
2242
2243#ifdef VBOX_WITH_AUDIO_HDA_ASYNC_IO
2244 RTCritSectLeave(&pStreamR3->State.AIO.CritSect);
2245#endif
2246 } while (cbStreamUsed < cbPeriod);
2247 if (cbSilence > 0)
2248 {
2249 STAM_REL_COUNTER_INC(&pStreamR3->State.StatDmaFlowErrors);
2250 STAM_REL_COUNTER_ADD(&pStreamR3->State.StatDmaFlowErrorBytes, cbSilence);
2251 LogRel2(("HDA: Warning: Stream #%RU8 underrun, added %u bytes of silence (%u us)\n", pStreamShared->u8SD,
2252 cbSilence, PDMAudioPropsBytesToMicro(&pStreamR3->State.Mapping.GuestProps, cbSilence)));
2253 }
2254 }
2255 }
2256
2257 /*
2258 * Do the DMA'ing.
2259 */
2260 if (cbStreamUsed)
2261 {
2262# ifdef VBOX_WITH_AUDIO_HDA_ASYNC_IO
2263 rc2 = PDMDevHlpCritSectEnter(pDevIns, &pStreamShared->CritSect, VERR_IGNORED);
2264 AssertRC(rc2);
2265# endif
2266
2267 hdaR3StreamDoDmaInput(pDevIns, pThis, pStreamShared, pStreamR3,
2268 RT_MIN(cbStreamUsed, cbPeriod), fWriteSilence, tsNowNs);
2269
2270# ifdef VBOX_WITH_AUDIO_HDA_ASYNC_IO
2271 rc2 = PDMDevHlpCritSectLeave(pDevIns, &pStreamShared->CritSect);
2272 AssertRC(rc2);
2273# endif
2274 }
2275
2276# ifdef VBOX_WITH_AUDIO_HDA_ASYNC_IO
2277 /*
2278 * We should always kick the AIO thread.
2279 */
2280 /** @todo This isn't entirely ideal. If we get into an underrun situation,
2281 * we ideally want the AIO thread to run right before the DMA timer
2282 * rather than right after it ran. */
2283 Log5Func(("Notifying AIO thread\n"));
2284 rc2 = hdaR3StreamAsyncIONotify(pStreamR3);
2285 AssertRC(rc2);
2286 pStreamShared->State.tsLastReadNs = tsNowNs;
2287# endif
2288 }
2289 }
2290}
2291
2292#endif /* IN_RING3 */
2293
2294/**
2295 * Locks an HDA stream for serialized access.
2296 *
2297 * @returns VBox status code.
2298 * @param pStreamShared HDA stream to lock (shared bits).
2299 */
2300void hdaStreamLock(PHDASTREAM pStreamShared)
2301{
2302 AssertPtrReturnVoid(pStreamShared);
2303# ifdef VBOX_WITH_AUDIO_HDA_ASYNC_IO
2304 int rc2 = PDMCritSectEnter(&pStreamShared->CritSect, VINF_SUCCESS);
2305 AssertRC(rc2);
2306#endif
2307}
2308
2309/**
2310 * Unlocks a formerly locked HDA stream.
2311 *
2312 * @returns VBox status code.
2313 * @param pStreamShared HDA stream to unlock (shared bits).
2314 */
2315void hdaStreamUnlock(PHDASTREAM pStreamShared)
2316{
2317 AssertPtrReturnVoid(pStreamShared);
2318# ifdef VBOX_WITH_AUDIO_HDA_ASYNC_IO
2319 int rc2 = PDMCritSectLeave(&pStreamShared->CritSect);
2320 AssertRC(rc2);
2321# endif
2322}
2323
2324#ifdef IN_RING3
2325
2326#if 0 /* unused - no prototype even */
2327/**
2328 * Updates an HDA stream's current read or write buffer position (depending on the stream type) by
2329 * updating its associated LPIB register and DMA position buffer (if enabled).
2330 *
2331 * @returns Set LPIB value.
2332 * @param pDevIns The device instance.
2333 * @param pStream HDA stream to update read / write position for.
2334 * @param u32LPIB New LPIB (position) value to set.
2335 */
2336uint32_t hdaR3StreamUpdateLPIB(PPDMDEVINS pDevIns, PHDASTATE pThis, PHDASTREAM pStreamShared, uint32_t u32LPIB)
2337{
2338 AssertMsg(u32LPIB <= pStreamShared->u32CBL,
2339 ("[SD%RU8] New LPIB (%RU32) exceeds CBL (%RU32)\n", pStreamShared->u8SD, u32LPIB, pStreamShared->u32CBL));
2340
2341 u32LPIB = RT_MIN(u32LPIB, pStreamShared->u32CBL);
2342
2343 LogFlowFunc(("[SD%RU8] LPIB=%RU32 (DMA Position Buffer Enabled: %RTbool)\n",
2344 pStreamShared->u8SD, u32LPIB, pThis->fDMAPosition));
2345
2346 /* Update LPIB in any case. */
2347 HDA_STREAM_REG(pThis, LPIB, pStreamShared->u8SD) = u32LPIB;
2348
2349 /* Do we need to tell the current DMA position? */
2350 if (pThis->fDMAPosition)
2351 {
2352 int rc2 = PDMDevHlpPCIPhysWrite(pDevIns,
2353 pThis->u64DPBase + (pStreamShared->u8SD * 2 * sizeof(uint32_t)),
2354 (void *)&u32LPIB, sizeof(uint32_t));
2355 AssertRC(rc2);
2356 }
2357
2358 return u32LPIB;
2359}
2360#endif
2361
2362# ifdef HDA_USE_DMA_ACCESS_HANDLER
2363/**
2364 * Registers access handlers for a stream's BDLE DMA accesses.
2365 *
2366 * @returns true if registration was successful, false if not.
2367 * @param pStream HDA stream to register BDLE access handlers for.
2368 */
2369bool hdaR3StreamRegisterDMAHandlers(PHDASTREAM pStream)
2370{
2371 /* At least LVI and the BDL base must be set. */
2372 if ( !pStreamShared->u16LVI
2373 || !pStreamShared->u64BDLBase)
2374 {
2375 return false;
2376 }
2377
2378 hdaR3StreamUnregisterDMAHandlers(pStream);
2379
2380 LogFunc(("Registering ...\n"));
2381
2382 int rc = VINF_SUCCESS;
2383
2384 /*
2385 * Create BDLE ranges.
2386 */
2387
2388 struct BDLERANGE
2389 {
2390 RTGCPHYS uAddr;
2391 uint32_t uSize;
2392 } arrRanges[16]; /** @todo Use a define. */
2393
2394 size_t cRanges = 0;
2395
2396 for (uint16_t i = 0; i < pStreamShared->u16LVI + 1; i++)
2397 {
2398 HDABDLE BDLE;
2399 rc = hdaR3BDLEFetch(pDevIns, &BDLE, pStreamShared->u64BDLBase, i /* Index */);
2400 if (RT_FAILURE(rc))
2401 break;
2402
2403 bool fAddRange = true;
2404 BDLERANGE *pRange;
2405
2406 if (cRanges)
2407 {
2408 pRange = &arrRanges[cRanges - 1];
2409
2410 /* Is the current range a direct neighbor of the current BLDE? */
2411 if ((pRange->uAddr + pRange->uSize) == BDLE.Desc.u64BufAddr)
2412 {
2413 /* Expand the current range by the current BDLE's size. */
2414 pRange->uSize += BDLE.Desc.u32BufSize;
2415
2416 /* Adding a new range in this case is not needed anymore. */
2417 fAddRange = false;
2418
2419 LogFunc(("Expanding range %zu by %RU32 (%RU32 total now)\n", cRanges - 1, BDLE.Desc.u32BufSize, pRange->uSize));
2420 }
2421 }
2422
2423 /* Do we need to add a new range? */
2424 if ( fAddRange
2425 && cRanges < RT_ELEMENTS(arrRanges))
2426 {
2427 pRange = &arrRanges[cRanges];
2428
2429 pRange->uAddr = BDLE.Desc.u64BufAddr;
2430 pRange->uSize = BDLE.Desc.u32BufSize;
2431
2432 LogFunc(("Adding range %zu - 0x%x (%RU32)\n", cRanges, pRange->uAddr, pRange->uSize));
2433
2434 cRanges++;
2435 }
2436 }
2437
2438 LogFunc(("%zu ranges total\n", cRanges));
2439
2440 /*
2441 * Register all ranges as DMA access handlers.
2442 */
2443
2444 for (size_t i = 0; i < cRanges; i++)
2445 {
2446 BDLERANGE *pRange = &arrRanges[i];
2447
2448 PHDADMAACCESSHANDLER pHandler = (PHDADMAACCESSHANDLER)RTMemAllocZ(sizeof(HDADMAACCESSHANDLER));
2449 if (!pHandler)
2450 {
2451 rc = VERR_NO_MEMORY;
2452 break;
2453 }
2454
2455 RTListAppend(&pStream->State.lstDMAHandlers, &pHandler->Node);
2456
2457 pHandler->pStream = pStream; /* Save a back reference to the owner. */
2458
2459 char szDesc[32];
2460 RTStrPrintf(szDesc, sizeof(szDesc), "HDA[SD%RU8 - RANGE%02zu]", pStream->u8SD, i);
2461
2462 int rc2 = PGMR3HandlerPhysicalTypeRegister(PDMDevHlpGetVM(pStream->pHDAState->pDevInsR3), PGMPHYSHANDLERKIND_WRITE,
2463 hdaDMAAccessHandler,
2464 NULL, NULL, NULL,
2465 NULL, NULL, NULL,
2466 szDesc, &pHandler->hAccessHandlerType);
2467 AssertRCBreak(rc2);
2468
2469 pHandler->BDLEAddr = pRange->uAddr;
2470 pHandler->BDLESize = pRange->uSize;
2471
2472 /* Get first and last pages of the BDLE range. */
2473 RTGCPHYS pgFirst = pRange->uAddr & ~PAGE_OFFSET_MASK;
2474 RTGCPHYS pgLast = RT_ALIGN(pgFirst + pRange->uSize, PAGE_SIZE);
2475
2476 /* Calculate the region size (in pages). */
2477 RTGCPHYS regionSize = RT_ALIGN(pgLast - pgFirst, PAGE_SIZE);
2478
2479 pHandler->GCPhysFirst = pgFirst;
2480 pHandler->GCPhysLast = pHandler->GCPhysFirst + (regionSize - 1);
2481
2482 LogFunc(("\tRegistering region '%s': 0x%x - 0x%x (region size: %zu)\n",
2483 szDesc, pHandler->GCPhysFirst, pHandler->GCPhysLast, regionSize));
2484 LogFunc(("\tBDLE @ 0x%x - 0x%x (%RU32)\n",
2485 pHandler->BDLEAddr, pHandler->BDLEAddr + pHandler->BDLESize, pHandler->BDLESize));
2486
2487 rc2 = PGMHandlerPhysicalRegister(PDMDevHlpGetVM(pStream->pHDAState->pDevInsR3),
2488 pHandler->GCPhysFirst, pHandler->GCPhysLast,
2489 pHandler->hAccessHandlerType, pHandler, NIL_RTR0PTR, NIL_RTRCPTR,
2490 szDesc);
2491 AssertRCBreak(rc2);
2492
2493 pHandler->fRegistered = true;
2494 }
2495
2496 LogFunc(("Registration ended with rc=%Rrc\n", rc));
2497
2498 return RT_SUCCESS(rc);
2499}
2500
2501/**
2502 * Unregisters access handlers of a stream's BDLEs.
2503 *
2504 * @param pStream HDA stream to unregister BDLE access handlers for.
2505 */
2506void hdaR3StreamUnregisterDMAHandlers(PHDASTREAM pStream)
2507{
2508 LogFunc(("\n"));
2509
2510 PHDADMAACCESSHANDLER pHandler, pHandlerNext;
2511 RTListForEachSafe(&pStream->State.lstDMAHandlers, pHandler, pHandlerNext, HDADMAACCESSHANDLER, Node)
2512 {
2513 if (!pHandler->fRegistered) /* Handler not registered? Skip. */
2514 continue;
2515
2516 LogFunc(("Unregistering 0x%x - 0x%x (%zu)\n",
2517 pHandler->GCPhysFirst, pHandler->GCPhysLast, pHandler->GCPhysLast - pHandler->GCPhysFirst));
2518
2519 int rc2 = PGMHandlerPhysicalDeregister(PDMDevHlpGetVM(pStream->pHDAState->pDevInsR3),
2520 pHandler->GCPhysFirst);
2521 AssertRC(rc2);
2522
2523 RTListNodeRemove(&pHandler->Node);
2524
2525 RTMemFree(pHandler);
2526 pHandler = NULL;
2527 }
2528
2529 Assert(RTListIsEmpty(&pStream->State.lstDMAHandlers));
2530}
2531
2532# endif /* HDA_USE_DMA_ACCESS_HANDLER */
2533# ifdef VBOX_WITH_AUDIO_HDA_ASYNC_IO
2534
2535/**
2536 * @callback_method_impl{FNRTTHREAD,
2537 * Asynchronous I/O thread for a HDA stream.
2538 *
2539 * This will do the heavy lifting work for us as soon as it's getting notified
2540 * by another thread.}
2541 */
2542static DECLCALLBACK(int) hdaR3StreamAsyncIOThread(RTTHREAD hThreadSelf, void *pvUser)
2543{
2544 PHDASTREAMR3 const pStreamR3 = (PHDASTREAMR3)pvUser;
2545 PHDASTREAMSTATEAIO const pAIO = &pStreamR3->State.AIO;
2546 PHDASTATE const pThis = pStreamR3->pHDAStateShared;
2547 PHDASTATER3 const pThisCC = pStreamR3->pHDAStateR3;
2548 PPDMDEVINS const pDevIns = pThisCC->pDevIns;
2549 PHDASTREAM const pStreamShared = &pThis->aStreams[pStreamR3 - &pThisCC->aStreams[0]];
2550 Assert(pStreamR3 - &pThisCC->aStreams[0] == pStreamR3->u8SD);
2551 Assert(pStreamShared->u8SD == pStreamR3->u8SD);
2552
2553 /* Signal parent thread that we've started */
2554 ASMAtomicWriteBool(&pAIO->fStarted, true);
2555 RTThreadUserSignal(hThreadSelf);
2556
2557 LogFunc(("[SD%RU8] Started\n", pStreamShared->u8SD));
2558
2559 while (!ASMAtomicReadBool(&pAIO->fShutdown))
2560 {
2561 int rc2 = RTSemEventWait(pAIO->hEvent, RT_INDEFINITE_WAIT);
2562 if (RT_SUCCESS(rc2))
2563 { /* likely */ }
2564 else
2565 break;
2566
2567 if (!ASMAtomicReadBool(&pAIO->fShutdown))
2568 { /* likely */ }
2569 else
2570 break;
2571
2572 rc2 = RTCritSectEnter(&pAIO->CritSect);
2573 AssertRC(rc2);
2574 if (RT_SUCCESS(rc2))
2575 {
2576 if (pAIO->fEnabled)
2577 hdaR3StreamUpdate(pDevIns, pThis, pThisCC, pStreamShared, pStreamR3, false /* fInTimer */);
2578
2579 int rc3 = RTCritSectLeave(&pAIO->CritSect);
2580 AssertRC(rc3);
2581 }
2582 }
2583
2584 LogFunc(("[SD%RU8] Ended\n", pStreamShared->u8SD));
2585 ASMAtomicWriteBool(&pAIO->fStarted, false);
2586
2587 return VINF_SUCCESS;
2588}
2589
2590/**
2591 * Creates the async I/O thread for a specific HDA audio stream.
2592 *
2593 * @returns VBox status code.
2594 * @param pStreamR3 HDA audio stream to create the async I/O thread for.
2595 */
2596int hdaR3StreamAsyncIOCreate(PHDASTREAMR3 pStreamR3)
2597{
2598 PHDASTREAMSTATEAIO pAIO = &pStreamR3->State.AIO;
2599
2600 int rc;
2601
2602 if (!ASMAtomicReadBool(&pAIO->fStarted))
2603 {
2604 pAIO->fShutdown = false;
2605 pAIO->fEnabled = true; /* Enabled by default. */
2606
2607 rc = RTSemEventCreate(&pAIO->hEvent);
2608 if (RT_SUCCESS(rc))
2609 {
2610 rc = RTCritSectInit(&pAIO->CritSect);
2611 if (RT_SUCCESS(rc))
2612 {
2613 rc = RTThreadCreateF(&pAIO->hThread, hdaR3StreamAsyncIOThread, pStreamR3, 0 /*cbStack*/, RTTHREADTYPE_IO,
2614 RTTHREADFLAGS_WAITABLE | RTTHREADFLAGS_COM_MTA, "hdaAIO%RU8", pStreamR3->u8SD);
2615 if (RT_SUCCESS(rc))
2616 rc = RTThreadUserWait(pAIO->hThread, 10 * 1000 /* 10s timeout */);
2617 }
2618 }
2619 }
2620 else
2621 rc = VINF_SUCCESS;
2622
2623 LogFunc(("[SD%RU8] Returning %Rrc\n", pStreamR3->u8SD, rc));
2624 return rc;
2625}
2626
2627/**
2628 * Destroys the async I/O thread of a specific HDA audio stream.
2629 *
2630 * @returns VBox status code.
2631 * @param pStreamR3 HDA audio stream to destroy the async I/O thread for.
2632 */
2633static int hdaR3StreamAsyncIODestroy(PHDASTREAMR3 pStreamR3)
2634{
2635 PHDASTREAMSTATEAIO pAIO = &pStreamR3->State.AIO;
2636
2637 if (!ASMAtomicReadBool(&pAIO->fStarted))
2638 return VINF_SUCCESS;
2639
2640 ASMAtomicWriteBool(&pAIO->fShutdown, true);
2641
2642 int rc = hdaR3StreamAsyncIONotify(pStreamR3);
2643 AssertRC(rc);
2644
2645 int rcThread;
2646 rc = RTThreadWait(pAIO->hThread, 30 * 1000 /* 30s timeout */, &rcThread);
2647 LogFunc(("Async I/O thread ended with %Rrc (%Rrc)\n", rc, rcThread));
2648
2649 if (RT_SUCCESS(rc))
2650 {
2651 pAIO->hThread = NIL_RTTHREAD;
2652
2653 rc = RTCritSectDelete(&pAIO->CritSect);
2654 AssertRC(rc);
2655
2656 rc = RTSemEventDestroy(pAIO->hEvent);
2657 AssertRC(rc);
2658 pAIO->hEvent = NIL_RTSEMEVENT;
2659
2660 pAIO->fStarted = false;
2661 pAIO->fShutdown = false;
2662 pAIO->fEnabled = false;
2663 }
2664
2665 LogFunc(("[SD%RU8] Returning %Rrc\n", pStreamR3->u8SD, rc));
2666 return rc;
2667}
2668
2669/**
2670 * Lets the stream's async I/O thread know that there is some data to process.
2671 *
2672 * @returns VBox status code.
2673 * @param pStreamR3 HDA stream to notify async I/O thread for.
2674 */
2675int hdaR3StreamAsyncIONotify(PHDASTREAMR3 pStreamR3)
2676{
2677 return RTSemEventSignal(pStreamR3->State.AIO.hEvent);
2678}
2679
2680/**
2681 * Locks the async I/O thread of a specific HDA audio stream.
2682 *
2683 * @param pStreamR3 HDA stream to lock async I/O thread for.
2684 */
2685void hdaR3StreamAsyncIOLock(PHDASTREAMR3 pStreamR3)
2686{
2687 PHDASTREAMSTATEAIO pAIO = &pStreamR3->State.AIO;
2688
2689 if (!ASMAtomicReadBool(&pAIO->fStarted))
2690 return;
2691
2692 int rc2 = RTCritSectEnter(&pAIO->CritSect);
2693 AssertRC(rc2);
2694}
2695
2696/**
2697 * Unlocks the async I/O thread of a specific HDA audio stream.
2698 *
2699 * @param pStreamR3 HDA stream to unlock async I/O thread for.
2700 */
2701void hdaR3StreamAsyncIOUnlock(PHDASTREAMR3 pStreamR3)
2702{
2703 PHDASTREAMSTATEAIO pAIO = &pStreamR3->State.AIO;
2704
2705 if (!ASMAtomicReadBool(&pAIO->fStarted))
2706 return;
2707
2708 int rc2 = RTCritSectLeave(&pAIO->CritSect);
2709 AssertRC(rc2);
2710}
2711
2712/**
2713 * Enables (resumes) or disables (pauses) the async I/O thread.
2714 *
2715 * @param pStreamR3 HDA stream to enable/disable async I/O thread for.
2716 * @param fEnable Whether to enable or disable the I/O thread.
2717 *
2718 * @remarks Does not do locking.
2719 */
2720void hdaR3StreamAsyncIOEnable(PHDASTREAMR3 pStreamR3, bool fEnable)
2721{
2722 PHDASTREAMSTATEAIO pAIO = &pStreamR3->State.AIO;
2723 ASMAtomicXchgBool(&pAIO->fEnabled, fEnable);
2724}
2725
2726# endif /* VBOX_WITH_AUDIO_HDA_ASYNC_IO */
2727#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