VirtualBox

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

最後變更 在這個檔案從98405是 98405,由 vboxsync 提交於 2 年 前

Audio: Fixed race condition between announcing remaining device DMA data on draining and fetching it in the async I/O mixer thread via AudioMixerSinkTransferFromCircBuf(). This is due to the device's DMA buffer being reset via its device-specific functions (i.e. ichac97R3StreamReset()) immediately after disabling the stream (i.e. ichac97R3StreamDisable()). See comment 2 for more details. bugref:10354

  • 屬性 svn:eol-style 設為 native
  • 屬性 svn:keywords 設為 Author Date Id Revision
檔案大小: 103.7 KB
 
1/* $Id: DevHdaStream.cpp 98405 2023-02-01 15:13:23Z vboxsync $ */
2/** @file
3 * Intel HD Audio Controller Emulation - Streams.
4 */
5
6/*
7 * Copyright (C) 2017-2023 Oracle and/or its affiliates.
8 *
9 * This file is part of VirtualBox base platform packages, as
10 * available from https://www.alldomusa.eu.org.
11 *
12 * This program is free software; you can redistribute it and/or
13 * modify it under the terms of the GNU General Public License
14 * as published by the Free Software Foundation, in version 3 of the
15 * License.
16 *
17 * This program is distributed in the hope that it will be useful, but
18 * WITHOUT ANY WARRANTY; without even the implied warranty of
19 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
20 * General Public License for more details.
21 *
22 * You should have received a copy of the GNU General Public License
23 * along with this program; if not, see <https://www.gnu.org/licenses>.
24 *
25 * SPDX-License-Identifier: GPL-3.0-only
26 */
27
28
29/*********************************************************************************************************************************
30* Header Files *
31*********************************************************************************************************************************/
32#define LOG_GROUP LOG_GROUP_DEV_HDA
33#include <VBox/log.h>
34
35#include <iprt/mem.h>
36#include <iprt/semaphore.h>
37#include <iprt/zero.h>
38
39#include <VBox/AssertGuest.h>
40#include <VBox/vmm/pdmdev.h>
41#include <VBox/vmm/pdmaudioifs.h>
42#include <VBox/vmm/pdmaudioinline.h>
43
44#include "AudioHlp.h"
45
46#include "DevHda.h"
47
48#ifdef VBOX_WITH_DTRACE
49# include "dtrace/VBoxDD.h"
50#endif
51
52
53/*********************************************************************************************************************************
54* Internal Functions *
55*********************************************************************************************************************************/
56#if defined(IN_RING3) || defined(VBOX_HDA_WITH_ON_REG_ACCESS_DMA)
57static void hdaStreamSetPositionAbs(PHDASTREAM pStreamShared, PPDMDEVINS pDevIns, PHDASTATE pThis, uint32_t uLPIB);
58#endif
59#ifdef IN_RING3
60# ifdef VBOX_HDA_WITH_ON_REG_ACCESS_DMA
61static void hdaR3StreamFlushDmaBounceBufferOutput(PHDASTREAM pStreamShared, PHDASTREAMR3 pStreamR3);
62# endif
63static uint32_t hdaR3StreamHandleDmaBufferOverrun(PHDASTREAM pStreamShared, PHDASTREAMR3 pStreamR3, PAUDMIXSINK pSink,
64 uint32_t cbNeeded, uint64_t nsNow,
65 const char *pszCaller, uint32_t const cbStreamFree);
66static void hdaR3StreamUpdateDma(PPDMDEVINS pDevIns, PHDASTATE pThis, PHDASTATER3 pThisCC,
67 PHDASTREAM pStreamShared, PHDASTREAMR3 pStreamR3);
68#endif
69
70
71#ifdef IN_RING3
72
73/**
74 * Creates an HDA stream.
75 *
76 * @returns VBox status code.
77 * @param pStreamShared The HDA stream to construct - shared bits.
78 * @param pStreamR3 The HDA stream to construct - ring-3 bits.
79 * @param pThis The shared HDA device instance.
80 * @param pThisCC The ring-3 HDA device instance.
81 * @param uSD Stream descriptor number to assign.
82 */
83int hdaR3StreamConstruct(PHDASTREAM pStreamShared, PHDASTREAMR3 pStreamR3, PHDASTATE pThis, PHDASTATER3 pThisCC, uint8_t uSD)
84{
85 pStreamR3->u8SD = uSD;
86 pStreamShared->u8SD = uSD;
87 pStreamR3->pMixSink = NULL;
88 pStreamR3->pHDAStateShared = pThis;
89 pStreamR3->pHDAStateR3 = pThisCC;
90 Assert(pStreamShared->hTimer != NIL_TMTIMERHANDLE); /* hdaR3Construct initalized this one already. */
91
92 pStreamShared->State.fInReset = false;
93 pStreamShared->State.fRunning = false;
94
95 AssertPtr(pStreamR3->pHDAStateR3);
96 AssertPtr(pStreamR3->pHDAStateR3->pDevIns);
97
98 const bool fIsInput = hdaGetDirFromSD(uSD) == PDMAUDIODIR_IN;
99
100 if (fIsInput)
101 {
102 pStreamShared->State.Cfg.enmPath = PDMAUDIOPATH_UNKNOWN;
103 pStreamShared->State.Cfg.enmDir = PDMAUDIODIR_IN;
104 }
105 else
106 {
107 pStreamShared->State.Cfg.enmPath = PDMAUDIOPATH_UNKNOWN;
108 pStreamShared->State.Cfg.enmDir = PDMAUDIODIR_OUT;
109 }
110
111 pStreamR3->Dbg.Runtime.fEnabled = pThisCC->Dbg.fEnabled;
112
113 if (pStreamR3->Dbg.Runtime.fEnabled)
114 {
115 int rc2 = AudioHlpFileCreateF(&pStreamR3->Dbg.Runtime.pFileStream, AUDIOHLPFILE_FLAGS_NONE, AUDIOHLPFILETYPE_WAV,
116 pThisCC->Dbg.pszOutPath, AUDIOHLPFILENAME_FLAGS_NONE, 0 /*uInstance*/,
117 fIsInput ? "hdaStreamWriteSD%RU8" : "hdaStreamReadSD%RU8", uSD);
118 AssertRC(rc2);
119
120 /* pFileDMARaw */
121 rc2 = AudioHlpFileCreateF(&pStreamR3->Dbg.Runtime.pFileDMARaw, AUDIOHLPFILE_FLAGS_NONE, AUDIOHLPFILETYPE_WAV,
122 pThisCC->Dbg.pszOutPath, AUDIOHLPFILENAME_FLAGS_NONE, 0 /*uInstance*/,
123 fIsInput ? "hdaDMARawWriteSD%RU8" : "hdaDMARawReadSD%RU8", uSD);
124 AssertRC(rc2);
125
126 /* pFileDMAMapped */
127 rc2 = AudioHlpFileCreateF(&pStreamR3->Dbg.Runtime.pFileDMAMapped, AUDIOHLPFILE_FLAGS_NONE, AUDIOHLPFILETYPE_WAV,
128 pThisCC->Dbg.pszOutPath, AUDIOHLPFILENAME_FLAGS_NONE, 0 /*uInstance*/,
129 fIsInput ? "hdaDMAWriteMappedSD%RU8" : "hdaDMAReadMappedSD%RU8", uSD);
130 AssertRC(rc2);
131
132 /* Delete stale debugging files from a former run. */
133 AudioHlpFileDelete(pStreamR3->Dbg.Runtime.pFileStream);
134 AudioHlpFileDelete(pStreamR3->Dbg.Runtime.pFileDMARaw);
135 AudioHlpFileDelete(pStreamR3->Dbg.Runtime.pFileDMAMapped);
136 }
137
138 return VINF_SUCCESS;
139}
140
141/**
142 * Destroys an HDA stream.
143 *
144 * @param pStreamR3 The HDA stream to destroy - ring-3 bits.
145 */
146void hdaR3StreamDestroy(PHDASTREAMR3 pStreamR3)
147{
148 LogFlowFunc(("[SD%RU8] Destroying ...\n", pStreamR3->u8SD));
149 int rc2;
150
151 if (pStreamR3->State.pAioRegSink)
152 {
153 rc2 = AudioMixerSinkRemoveUpdateJob(pStreamR3->State.pAioRegSink, hdaR3StreamUpdateAsyncIoJob, pStreamR3);
154 AssertRC(rc2);
155 pStreamR3->State.pAioRegSink = NULL;
156 }
157
158 if (pStreamR3->State.pCircBuf)
159 {
160 RTCircBufDestroy(pStreamR3->State.pCircBuf);
161 pStreamR3->State.pCircBuf = NULL;
162 pStreamR3->State.StatDmaBufSize = 0;
163 pStreamR3->State.StatDmaBufUsed = 0;
164 }
165
166 if (pStreamR3->Dbg.Runtime.fEnabled)
167 {
168 AudioHlpFileDestroy(pStreamR3->Dbg.Runtime.pFileStream);
169 pStreamR3->Dbg.Runtime.pFileStream = NULL;
170
171 AudioHlpFileDestroy(pStreamR3->Dbg.Runtime.pFileDMARaw);
172 pStreamR3->Dbg.Runtime.pFileDMARaw = NULL;
173
174 AudioHlpFileDestroy(pStreamR3->Dbg.Runtime.pFileDMAMapped);
175 pStreamR3->Dbg.Runtime.pFileDMAMapped = NULL;
176 }
177
178 LogFlowFuncLeave();
179}
180
181
182/**
183 * Converts an HDA stream's SDFMT register into a given PCM properties structure.
184 *
185 * @returns VBox status code.
186 * @param u16SDFMT The HDA stream's SDFMT value to convert.
187 * @param pProps PCM properties structure to hold converted result on success.
188 */
189int hdaR3SDFMTToPCMProps(uint16_t u16SDFMT, PPDMAUDIOPCMPROPS pProps)
190{
191 AssertPtrReturn(pProps, VERR_INVALID_POINTER);
192
193# define EXTRACT_VALUE(v, mask, shift) ((v & ((mask) << (shift))) >> (shift))
194
195 int rc = VINF_SUCCESS;
196
197 uint32_t u32Hz = EXTRACT_VALUE(u16SDFMT, HDA_SDFMT_BASE_RATE_MASK, HDA_SDFMT_BASE_RATE_SHIFT)
198 ? 44100 : 48000;
199 uint32_t u32HzMult = 1;
200 uint32_t u32HzDiv = 1;
201
202 switch (EXTRACT_VALUE(u16SDFMT, HDA_SDFMT_MULT_MASK, HDA_SDFMT_MULT_SHIFT))
203 {
204 case 0: u32HzMult = 1; break;
205 case 1: u32HzMult = 2; break;
206 case 2: u32HzMult = 3; break;
207 case 3: u32HzMult = 4; break;
208 default:
209 LogFunc(("Unsupported multiplier %x\n",
210 EXTRACT_VALUE(u16SDFMT, HDA_SDFMT_MULT_MASK, HDA_SDFMT_MULT_SHIFT)));
211 rc = VERR_NOT_SUPPORTED;
212 break;
213 }
214 switch (EXTRACT_VALUE(u16SDFMT, HDA_SDFMT_DIV_MASK, HDA_SDFMT_DIV_SHIFT))
215 {
216 case 0: u32HzDiv = 1; break;
217 case 1: u32HzDiv = 2; break;
218 case 2: u32HzDiv = 3; break;
219 case 3: u32HzDiv = 4; break;
220 case 4: u32HzDiv = 5; break;
221 case 5: u32HzDiv = 6; break;
222 case 6: u32HzDiv = 7; break;
223 case 7: u32HzDiv = 8; break;
224 default:
225 LogFunc(("Unsupported divisor %x\n",
226 EXTRACT_VALUE(u16SDFMT, HDA_SDFMT_DIV_MASK, HDA_SDFMT_DIV_SHIFT)));
227 rc = VERR_NOT_SUPPORTED;
228 break;
229 }
230
231 uint8_t cbSample = 0;
232 switch (EXTRACT_VALUE(u16SDFMT, HDA_SDFMT_BITS_MASK, HDA_SDFMT_BITS_SHIFT))
233 {
234 case 0:
235 cbSample = 1;
236 break;
237 case 1:
238 cbSample = 2;
239 break;
240 case 4:
241 cbSample = 4;
242 break;
243 default:
244 AssertMsgFailed(("Unsupported bits per sample %x\n",
245 EXTRACT_VALUE(u16SDFMT, HDA_SDFMT_BITS_MASK, HDA_SDFMT_BITS_SHIFT)));
246 rc = VERR_NOT_SUPPORTED;
247 break;
248 }
249
250 if (RT_SUCCESS(rc))
251 {
252 PDMAudioPropsInit(pProps, cbSample, true /*fSigned*/, (u16SDFMT & 0xf) + 1 /*cChannels*/, u32Hz * u32HzMult / u32HzDiv);
253 /** @todo is there anything we need to / can do about channel assignments? */
254 }
255
256# undef EXTRACT_VALUE
257 return rc;
258}
259
260# ifdef LOG_ENABLED
261void hdaR3BDLEDumpAll(PPDMDEVINS pDevIns, PHDASTATE pThis, uint64_t u64BDLBase, uint16_t cBDLE)
262{
263 LogFlowFunc(("BDLEs @ 0x%x (%RU16):\n", u64BDLBase, cBDLE));
264 if (!u64BDLBase)
265 return;
266
267 uint32_t cbBDLE = 0;
268 for (uint16_t i = 0; i < cBDLE; i++)
269 {
270 HDABDLEDESC bd;
271 PDMDevHlpPhysRead(pDevIns, u64BDLBase + i * sizeof(HDABDLEDESC), &bd, sizeof(bd));
272
273 LogFunc(("\t#%03d BDLE(adr:0x%llx, size:%RU32, ioc:%RTbool)\n",
274 i, bd.u64BufAddr, bd.u32BufSize, bd.fFlags & HDA_BDLE_F_IOC));
275
276 cbBDLE += bd.u32BufSize;
277 }
278
279 LogFlowFunc(("Total: %RU32 bytes\n", cbBDLE));
280
281 if (!pThis->u64DPBase) /* No DMA base given? Bail out. */
282 return;
283
284 LogFlowFunc(("DMA counters:\n"));
285
286 for (int i = 0; i < cBDLE; i++)
287 {
288 uint32_t uDMACnt;
289 PDMDevHlpPhysRead(pDevIns, (pThis->u64DPBase & DPBASE_ADDR_MASK) + (i * 2 * sizeof(uint32_t)),
290 &uDMACnt, sizeof(uDMACnt));
291
292 LogFlowFunc(("\t#%03d DMA @ 0x%x\n", i , uDMACnt));
293 }
294}
295# endif /* LOG_ENABLED */
296
297
298/**
299 * Appends a item to the scheduler.
300 *
301 * @returns VBox status code.
302 * @param pStreamShared The stream which scheduler should be modified.
303 * @param cbCur The period length in guest bytes.
304 * @param cbMaxPeriod The max period in guest bytes.
305 * @param idxLastBdle The last BDLE in the period.
306 * @param pProps The PCM properties.
307 * @param pcbBorrow Where to account for bytes borrowed across buffers
308 * to align scheduling items on frame boundraries.
309 */
310static int hdaR3StreamAddScheduleItem(PHDASTREAM pStreamShared, uint32_t cbCur, uint32_t cbMaxPeriod,
311 uint32_t idxLastBdle, PCPDMAUDIOPCMPROPS pProps, uint32_t *pcbBorrow)
312{
313 /* Check that we've got room (shouldn't ever be a problem). */
314 size_t idx = pStreamShared->State.cSchedule;
315 AssertLogRelReturn(idx + 1 < RT_ELEMENTS(pStreamShared->State.aSchedule), VERR_INTERNAL_ERROR_5);
316
317 /* Figure out the BDLE range for this period. */
318 uint32_t const idxFirstBdle = idx == 0 ? 0
319 : RT_MIN((uint32_t)( pStreamShared->State.aSchedule[idx - 1].idxFirst
320 + pStreamShared->State.aSchedule[idx - 1].cEntries),
321 idxLastBdle);
322
323 pStreamShared->State.aSchedule[idx].idxFirst = (uint8_t)idxFirstBdle;
324 pStreamShared->State.aSchedule[idx].cEntries = idxLastBdle >= idxFirstBdle
325 ? idxLastBdle - idxFirstBdle + 1
326 : pStreamShared->State.cBdles - idxFirstBdle + idxLastBdle + 1;
327
328 /* Deal with borrowing due to unaligned IOC buffers. */
329 uint32_t const cbBorrowed = *pcbBorrow;
330 if (cbBorrowed < cbCur)
331 cbCur -= cbBorrowed;
332 else
333 {
334 /* 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. */
335 ASSERT_GUEST_MSG_FAILED(("#%u: cbBorrow=%#x cbCur=%#x BDLE[%u..%u]\n",
336 pStreamShared->u8SD, cbBorrowed, cbCur, idxFirstBdle, idxLastBdle));
337 LogRelMax(32, ("HDA: Stream #%u has a scheduling error: cbBorrow=%#x cbCur=%#x BDLE[%u..%u]\n",
338 pStreamShared->u8SD, cbBorrowed, cbCur, idxFirstBdle, idxLastBdle));
339 return VERR_OUT_OF_RANGE;
340 }
341
342 uint32_t cbCurAligned = PDMAudioPropsRoundUpBytesToFrame(pProps, cbCur);
343 *pcbBorrow = cbCurAligned - cbCur;
344
345 /* Do we need to split up the period? */
346 if (cbCurAligned <= cbMaxPeriod)
347 {
348 pStreamShared->State.aSchedule[idx].cbPeriod = cbCurAligned;
349 pStreamShared->State.aSchedule[idx].cLoops = 1;
350 }
351 else
352 {
353 /* Reduce till we've below the threshold. */
354 uint32_t cbLoop = cbCurAligned;
355 do
356 cbLoop = cbLoop / 2;
357 while (cbLoop > cbMaxPeriod);
358 cbLoop = PDMAudioPropsRoundUpBytesToFrame(pProps, cbLoop);
359
360 /* Complete the scheduling item. */
361 pStreamShared->State.aSchedule[idx].cbPeriod = cbLoop;
362 pStreamShared->State.aSchedule[idx].cLoops = cbCurAligned / cbLoop;
363
364 /* If there is a remainder, add it as a separate entry (this is
365 why the schedule must be more than twice the size of the BDL).*/
366 cbCurAligned %= cbLoop;
367 if (cbCurAligned)
368 {
369 pStreamShared->State.aSchedule[idx + 1] = pStreamShared->State.aSchedule[idx];
370 idx++;
371 pStreamShared->State.aSchedule[idx].cbPeriod = cbCurAligned;
372 pStreamShared->State.aSchedule[idx].cLoops = 1;
373 }
374 }
375
376 /* Done. */
377 pStreamShared->State.cSchedule = (uint16_t)(idx + 1);
378
379 return VINF_SUCCESS;
380}
381
382/**
383 * Creates the DMA timer schedule for the stream
384 *
385 * This is called from the stream setup code.
386 *
387 * @returns VBox status code.
388 * @param pStreamShared The stream to create a schedule for. The BDL
389 * must be loaded.
390 * @param cSegments Number of BDL segments.
391 * @param cBufferIrqs Number of the BDLEs with IOC=1.
392 * @param cbTotal The total BDL length in guest bytes.
393 * @param cbMaxPeriod Max period in guest bytes. This is in case the
394 * guest want to play the whole "Der Ring des
395 * Nibelungen" cycle in one go.
396 * @param cTimerTicksPerSec The DMA timer frequency.
397 * @param pProps The PCM properties.
398 */
399static int hdaR3StreamCreateSchedule(PHDASTREAM pStreamShared, uint32_t cSegments, uint32_t cBufferIrqs, uint32_t cbTotal,
400 uint32_t cbMaxPeriod, uint64_t cTimerTicksPerSec, PCPDMAUDIOPCMPROPS pProps)
401{
402 int rc;
403
404 /*
405 * Reset scheduling state.
406 */
407 RT_ZERO(pStreamShared->State.aSchedule);
408 pStreamShared->State.cSchedule = 0;
409 pStreamShared->State.cSchedulePrologue = 0;
410 pStreamShared->State.idxSchedule = 0;
411 pStreamShared->State.idxScheduleLoop = 0;
412
413 /*
414 * Do the basic schedule compilation.
415 */
416 uint32_t cPotentialPrologue = 0;
417 uint32_t cbBorrow = 0;
418 uint32_t cbCur = 0;
419 uint32_t cbMin = UINT32_MAX;
420 pStreamShared->State.aSchedule[0].idxFirst = 0;
421 for (uint32_t i = 0; i < cSegments; i++)
422 {
423 cbCur += pStreamShared->State.aBdl[i].cb;
424 if (pStreamShared->State.aBdl[i].cb < cbMin)
425 cbMin = pStreamShared->State.aBdl[i].cb;
426 if (pStreamShared->State.aBdl[i].fFlags & HDA_BDLE_F_IOC)
427 {
428 rc = hdaR3StreamAddScheduleItem(pStreamShared, cbCur, cbMaxPeriod, i, pProps, &cbBorrow);
429 ASSERT_GUEST_RC_RETURN(rc, rc);
430
431 if (cPotentialPrologue == 0)
432 cPotentialPrologue = pStreamShared->State.cSchedule;
433 cbCur = 0;
434 }
435 }
436
437 /*
438 * Deal with any loose ends.
439 */
440 if (cbCur && cBufferIrqs == 0)
441 {
442 /*
443 * No IOC. Vista ends up here, typically with three buffers configured.
444 *
445 * The perferred option here is to aim at processing one average BDLE with
446 * each DMA timer period, since that best matches how we update LPIB at
447 * present.
448 *
449 * The second alternative is to divide the whole span up into 3-4 periods
450 * to try increase our chances of keeping ahead of the guest. We may need
451 * to pick this if there are too few buffer descriptor or they are too small.
452 *
453 * However, what we probably should be doing is to do real DMA work whenever
454 * the guest reads a DMA related register (like LPIB) and just do 3-4 DMA
455 * timer periods, however we'll be postponing the DMA timer every time we
456 * return to ring-3 and signal the AIO, so in the end we'd probably not use
457 * the timer callback at all. (This is assuming a small shared per-stream
458 * buffer for keeping the DMA data in and that it's size will force a return
459 * to ring-3 often enough to keep the AIO thread going at a reasonable rate.)
460 */
461 Assert(cbCur == cbTotal);
462
463 /* Match the BDLEs 1:1 if there are 3 or more and that the smallest one
464 is at least 5ms big. */
465 if (cSegments >= 3 && PDMAudioPropsBytesToMilli(pProps, cbMin) >= 5 /*ms*/)
466 {
467 for (uint32_t i = 0; i < cSegments; i++)
468 {
469 rc = hdaR3StreamAddScheduleItem(pStreamShared, pStreamShared->State.aBdl[i].cb, cbMaxPeriod, i, pProps, &cbBorrow);
470 ASSERT_GUEST_RC_RETURN(rc, rc);
471 }
472 }
473 /* Otherwise, just divide the work into 3 or 4 portions and hope for the best.
474 It seems, though, that this only really work for windows vista if we avoid
475 working accross buffer lines. */
476 /** @todo This can be simplified/relaxed/uncluttered if we do DMA work when LPIB
477 * is read, assuming ofc that LPIB is read before each buffer update. */
478 else
479 {
480 uint32_t const cPeriods = cSegments != 3 && PDMAudioPropsBytesToMilli(pProps, cbCur) >= 4 * 5 /*ms*/
481 ? 4 : cSegments != 2 ? 3 : 2;
482 uint32_t const cbPeriod = PDMAudioPropsFloorBytesToFrame(pProps, cbCur / cPeriods);
483 uint32_t iBdle = 0;
484 uint32_t offBdle = 0;
485 for (uint32_t iPeriod = 0; iPeriod < cPeriods; iPeriod++)
486 {
487 if (iPeriod + 1 < cPeriods)
488 {
489 offBdle += cbPeriod;
490 while (iBdle < cSegments && offBdle >= pStreamShared->State.aBdl[iBdle].cb)
491 offBdle -= pStreamShared->State.aBdl[iBdle++].cb;
492 rc = hdaR3StreamAddScheduleItem(pStreamShared, cbPeriod, cbMaxPeriod, offBdle != 0 ? iBdle : iBdle - 1,
493 pProps, &cbBorrow);
494 }
495 else
496 rc = hdaR3StreamAddScheduleItem(pStreamShared, cbCur - iPeriod * cbPeriod, cbMaxPeriod, cSegments - 1,
497 pProps, &cbBorrow);
498 ASSERT_GUEST_RC_RETURN(rc, rc);
499 }
500
501 }
502 }
503 else if (cbCur)
504 {
505 /* The last BDLE didn't have IOC set, so we must continue processing
506 from the start till we hit one that has. */
507 uint32_t i;
508 for (i = 0; i < cSegments; i++)
509 {
510 cbCur += pStreamShared->State.aBdl[i].cb;
511 if (pStreamShared->State.aBdl[i].fFlags & HDA_BDLE_F_IOC)
512 break;
513 }
514 rc = hdaR3StreamAddScheduleItem(pStreamShared, cbCur, cbMaxPeriod, i, pProps, &cbBorrow);
515 ASSERT_GUEST_RC_RETURN(rc, rc);
516
517 /* The initial scheduling items covering the wrap around area are
518 considered a prologue and must not repeated later. */
519 Assert(cPotentialPrologue);
520 pStreamShared->State.cSchedulePrologue = (uint8_t)cPotentialPrologue;
521 }
522
523 AssertLogRelMsgReturn(cbBorrow == 0, ("HDA: Internal scheduling error on stream #%u: cbBorrow=%#x cbTotal=%#x cbCur=%#x\n",
524 pStreamShared->u8SD, cbBorrow, cbTotal, cbCur),
525 VERR_INTERNAL_ERROR_3);
526
527 /*
528 * If there is just one BDLE with IOC set, we have to make sure
529 * we've got at least two periods scheduled, otherwise there is
530 * a very good chance the guest will overwrite the start of the
531 * buffer before we ever get around to reading it.
532 */
533 if (cBufferIrqs == 1)
534 {
535 uint32_t i = pStreamShared->State.cSchedulePrologue;
536 Assert(i < pStreamShared->State.cSchedule);
537 if ( i + 1 == pStreamShared->State.cSchedule
538 && pStreamShared->State.aSchedule[i].cLoops == 1)
539 {
540 uint32_t const cbFirstHalf = PDMAudioPropsFloorBytesToFrame(pProps, pStreamShared->State.aSchedule[i].cbPeriod / 2);
541 uint32_t const cbOtherHalf = pStreamShared->State.aSchedule[i].cbPeriod - cbFirstHalf;
542 pStreamShared->State.aSchedule[i].cbPeriod = cbFirstHalf;
543 if (cbFirstHalf == cbOtherHalf)
544 pStreamShared->State.aSchedule[i].cLoops = 2;
545 else
546 {
547 pStreamShared->State.aSchedule[i + 1] = pStreamShared->State.aSchedule[i];
548 pStreamShared->State.aSchedule[i].cbPeriod = cbOtherHalf;
549 pStreamShared->State.cSchedule++;
550 }
551 }
552 }
553
554 /*
555 * Go over the schduling entries and calculate the timer ticks for each period.
556 */
557 LogRel2(("HDA: Stream #%u schedule: %u items, %u prologue\n",
558 pStreamShared->u8SD, pStreamShared->State.cSchedule, pStreamShared->State.cSchedulePrologue));
559 uint64_t const cbPerSec = PDMAudioPropsFramesToBytes(pProps, pProps->uHz);
560 for (uint32_t i = 0; i < pStreamShared->State.cSchedule; i++)
561 {
562 uint64_t const cTicks = ASMMultU64ByU32DivByU32(cTimerTicksPerSec, pStreamShared->State.aSchedule[i].cbPeriod, cbPerSec);
563 AssertLogRelMsgReturn((uint32_t)cTicks == cTicks, ("cTicks=%RU64 (%#RX64)\n", cTicks, cTicks), VERR_INTERNAL_ERROR_4);
564 pStreamShared->State.aSchedule[i].cPeriodTicks = RT_MAX((uint32_t)cTicks, 16);
565 LogRel2(("HDA: #%u: %u ticks / %u bytes, %u loops, BDLE%u L %u\n", i, pStreamShared->State.aSchedule[i].cPeriodTicks,
566 pStreamShared->State.aSchedule[i].cbPeriod, pStreamShared->State.aSchedule[i].cLoops,
567 pStreamShared->State.aSchedule[i].idxFirst, pStreamShared->State.aSchedule[i].cEntries));
568 }
569
570 return VINF_SUCCESS;
571}
572
573
574/**
575 * Sets up ((re-)iniitalizes) an HDA stream.
576 *
577 * @returns VBox status code. VINF_NO_CHANGE if the stream does not need
578 * be set-up again because the stream's (hardware) parameters did
579 * not change.
580 * @param pDevIns The device instance.
581 * @param pThis The shared HDA device state (for HW register
582 * parameters).
583 * @param pStreamShared HDA stream to set up, shared portion.
584 * @param pStreamR3 HDA stream to set up, ring-3 portion.
585 * @param uSD Stream descriptor number to assign it.
586 */
587int hdaR3StreamSetUp(PPDMDEVINS pDevIns, PHDASTATE pThis, PHDASTREAM pStreamShared, PHDASTREAMR3 pStreamR3, uint8_t uSD)
588{
589 /* This must be valid all times. */
590 AssertReturn(uSD < HDA_MAX_STREAMS, VERR_INVALID_PARAMETER);
591
592 /* These member can only change on data corruption, despite what the code does further down (bird). */
593 AssertReturn(pStreamShared->u8SD == uSD, VERR_WRONG_ORDER);
594 AssertReturn(pStreamR3->u8SD == uSD, VERR_WRONG_ORDER);
595
596 const uint64_t u64BDLBase = RT_MAKE_U64(HDA_STREAM_REG(pThis, BDPL, uSD),
597 HDA_STREAM_REG(pThis, BDPU, uSD));
598 const uint16_t u16LVI = HDA_STREAM_REG(pThis, LVI, uSD);
599 const uint32_t u32CBL = HDA_STREAM_REG(pThis, CBL, uSD);
600 const uint8_t u8FIFOS = HDA_STREAM_REG(pThis, FIFOS, uSD) + 1;
601 uint8_t u8FIFOW = hdaSDFIFOWToBytes(HDA_STREAM_REG(pThis, FIFOW, uSD));
602 const uint16_t u16FMT = HDA_STREAM_REG(pThis, FMT, uSD);
603
604 /* Is the bare minimum set of registers configured for the stream?
605 * If not, bail out early, as there's nothing to do here for us (yet). */
606 if ( !u64BDLBase
607 || !u16LVI
608 || !u32CBL
609 || !u8FIFOS
610 || !u8FIFOW
611 || !u16FMT)
612 {
613 LogFunc(("[SD%RU8] Registers not set up yet, skipping (re-)initialization\n", uSD));
614 return VINF_SUCCESS;
615 }
616
617 /*
618 * Convert the config to PDM PCM properties and configure the stream.
619 */
620 PPDMAUDIOSTREAMCFG pCfg = &pStreamShared->State.Cfg;
621 int rc = hdaR3SDFMTToPCMProps(u16FMT, &pCfg->Props);
622 if (RT_SUCCESS(rc))
623 pCfg->enmDir = hdaGetDirFromSD(uSD);
624 else
625 {
626 LogRelMax(32, ("HDA: Warning: Format 0x%x for stream #%RU8 not supported\n", HDA_STREAM_REG(pThis, FMT, uSD), uSD));
627 return rc;
628 }
629
630 ASSERT_GUEST_LOGREL_MSG_RETURN( PDMAudioPropsFrameSize(&pCfg->Props) > 0
631 && u32CBL % PDMAudioPropsFrameSize(&pCfg->Props) == 0,
632 ("CBL for stream #%RU8 does not align to frame size (u32CBL=%u cbFrameSize=%u)\n",
633 uSD, u32CBL, PDMAudioPropsFrameSize(&pCfg->Props)),
634 VERR_INVALID_PARAMETER);
635
636 /* Make sure the guest behaves regarding the stream's FIFO. */
637 ASSERT_GUEST_LOGREL_MSG_STMT(u8FIFOW <= u8FIFOS,
638 ("Guest tried setting a bigger FIFOW (%RU8) than FIFOS (%RU8), limiting\n", u8FIFOW, u8FIFOS),
639 u8FIFOW = u8FIFOS /* ASSUMES that u8FIFOS has been validated. */);
640
641 pStreamShared->u8SD = uSD;
642
643 /* Update all register copies so that we later know that something has changed. */
644 pStreamShared->u64BDLBase = u64BDLBase;
645 pStreamShared->u16LVI = u16LVI;
646 pStreamShared->u32CBL = u32CBL;
647 pStreamShared->u8FIFOS = u8FIFOS;
648 pStreamShared->u8FIFOW = u8FIFOW;
649 pStreamShared->u16FMT = u16FMT;
650
651 /* The the stream's name, based on the direction. */
652 switch (pCfg->enmDir)
653 {
654 case PDMAUDIODIR_IN:
655# ifdef VBOX_WITH_AUDIO_HDA_MIC_IN
656# error "Implement me!"
657# else
658 pCfg->enmPath = PDMAUDIOPATH_IN_LINE;
659 RTStrCopy(pCfg->szName, sizeof(pCfg->szName), "Line In");
660# endif
661 break;
662
663 case PDMAUDIODIR_OUT:
664 /* Destination(s) will be set in hdaR3AddStreamOut(),
665 * based on the channels / stream layout. */
666 break;
667
668 default:
669 AssertFailedReturn(VERR_NOT_SUPPORTED);
670 break;
671 }
672
673 LogRel2(("HDA: Stream #%RU8 DMA @ 0x%x (%RU32 bytes = %RU64ms total)\n", uSD, pStreamShared->u64BDLBase,
674 pStreamShared->u32CBL, PDMAudioPropsBytesToMilli(&pCfg->Props, pStreamShared->u32CBL)));
675
676 /*
677 * Load the buffer descriptor list.
678 *
679 * Section 3.6.2 states that "the BDL should not be modified unless the RUN
680 * bit is 0", so it should be within the specs to read it once here and not
681 * re-read any BDLEs later.
682 */
683 /* Reset BDL state. */
684 RT_ZERO(pStreamShared->State.aBdl);
685 pStreamShared->State.offCurBdle = 0;
686 pStreamShared->State.idxCurBdle = 0;
687
688 uint32_t /*const*/ cTransferFragments = (pStreamShared->u16LVI & 0xff) + 1;
689 if (cTransferFragments <= 1)
690 LogRel(("HDA: Warning: Stream #%RU8 transfer buffer count invalid: (%RU16)! Buggy guest audio driver!\n", uSD, pStreamShared->u16LVI));
691 AssertLogRelReturn(cTransferFragments <= RT_ELEMENTS(pStreamShared->State.aBdl), VERR_INTERNAL_ERROR_5);
692 pStreamShared->State.cBdles = cTransferFragments;
693
694 /* Load them. */
695 rc = PDMDevHlpPCIPhysRead(pDevIns, u64BDLBase, pStreamShared->State.aBdl,
696 sizeof(pStreamShared->State.aBdl[0]) * cTransferFragments);
697 AssertRC(rc);
698
699 /* Check what we just loaded. Refuse overly large buffer lists. */
700 uint64_t cbTotal = 0;
701 uint32_t cBufferIrqs = 0;
702 for (uint32_t i = 0; i < cTransferFragments; i++)
703 {
704 if (pStreamShared->State.aBdl[i].fFlags & HDA_BDLE_F_IOC)
705 cBufferIrqs++;
706 cbTotal += pStreamShared->State.aBdl[i].cb;
707 }
708 ASSERT_GUEST_STMT_RETURN(cbTotal < _2G,
709 LogRelMax(32, ("HDA: Error: Stream #%u is configured with an insane amount of buffer space - refusing do work with it: %RU64 (%#RX64) bytes.\n",
710 uSD, cbTotal, cbTotal)),
711 VERR_NOT_SUPPORTED);
712 ASSERT_GUEST_STMT_RETURN(cbTotal == u32CBL,
713 LogRelMax(32, ("HDA: Warning: Stream #%u has a mismatch between CBL and configured buffer space: %RU32 (%#RX32) vs %RU64 (%#RX64)\n",
714 uSD, u32CBL, u32CBL, cbTotal, cbTotal)),
715 VERR_NOT_SUPPORTED);
716
717 /*
718 * Create a DMA timer schedule.
719 */
720 rc = hdaR3StreamCreateSchedule(pStreamShared, cTransferFragments, cBufferIrqs, (uint32_t)cbTotal,
721 PDMAudioPropsMilliToBytes(&pCfg->Props, 100 /** @todo make configurable */),
722 PDMDevHlpTimerGetFreq(pDevIns, pStreamShared->hTimer), &pCfg->Props);
723 if (RT_FAILURE(rc))
724 return rc;
725
726 pStreamShared->State.cbCurDmaPeriod = pStreamShared->State.aSchedule[0].cbPeriod;
727
728 /*
729 * Calculate the transfer Hz for use in the circular buffer calculation
730 * and the average period for the scheduling hint.
731 */
732 uint32_t cbMaxPeriod = 0;
733 uint32_t cbMinPeriod = UINT32_MAX;
734 uint64_t cTicks = 0;
735 uint32_t cPeriods = 0;
736 for (uint32_t i = pStreamShared->State.cSchedulePrologue; i < pStreamShared->State.cSchedule; i++)
737 {
738 uint32_t cbPeriod = pStreamShared->State.aSchedule[i].cbPeriod;
739 cbMaxPeriod = RT_MAX(cbMaxPeriod, cbPeriod);
740 cbMinPeriod = RT_MIN(cbMinPeriod, cbPeriod);
741 cPeriods += pStreamShared->State.aSchedule[i].cLoops;
742 cTicks += pStreamShared->State.aSchedule[i].cPeriodTicks * pStreamShared->State.aSchedule[i].cLoops;
743 }
744 /* Only consider the prologue in relation to the max period. */
745 for (uint32_t i = 0; i < pStreamShared->State.cSchedulePrologue; i++)
746 cbMaxPeriod = RT_MAX(cbMaxPeriod, pStreamShared->State.aSchedule[i].cbPeriod);
747
748 AssertLogRelReturn(cPeriods > 0, VERR_INTERNAL_ERROR_3);
749 uint64_t const cbTransferPerSec = RT_MAX(PDMAudioPropsFramesToBytes(&pCfg->Props, pCfg->Props.uHz),
750 4096 /* zero div prevention: min is 6kHz, picked 4k in case I'm mistaken */);
751 unsigned uTransferHz = cbTransferPerSec * 1000 / cbMaxPeriod;
752 LogRel2(("HDA: Stream #%RU8 needs a %u.%03u Hz timer rate (period: %u..%u host bytes)\n",
753 uSD, uTransferHz / 1000, uTransferHz % 1000, cbMinPeriod, cbMaxPeriod));
754 uTransferHz /= 1000;
755
756 if (uTransferHz > 400) /* Anything above 400 Hz looks fishy -- tell the user. */
757 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",
758 uSD, uTransferHz));
759
760 pStreamShared->State.cbAvgTransfer = (uint32_t)(cbTotal + cPeriods - 1) / cPeriods;
761
762 /* Calculate the average scheduling period length in nanoseconds. */
763 uint64_t const cTimerResolution = PDMDevHlpTimerGetFreq(pDevIns, pStreamShared->hTimer);
764 Assert(cTimerResolution <= UINT32_MAX);
765 uint64_t const cNsPerPeriod = ASMMultU64ByU32DivByU32(cTicks / cPeriods, RT_NS_1SEC, cTimerResolution);
766 AssertLogRelReturn(cNsPerPeriod > 0, VERR_INTERNAL_ERROR_3);
767
768 /* For input streams we must determin a pre-buffering requirement.
769 We use the initial delay as a basis here, though we must have at
770 least two max periods worth of data queued up due to the way we
771 work the AIO thread. */
772 pStreamShared->State.fInputPreBuffered = false;
773 pStreamShared->State.cbInputPreBuffer = cbMaxPeriod * 2;
774
775 /*
776 * Set up data transfer stuff.
777 */
778 /* Set I/O scheduling hint for the backends. */
779 pCfg->Device.cMsSchedulingHint = cNsPerPeriod > RT_NS_1MS ? (cNsPerPeriod + RT_NS_1MS / 2) / RT_NS_1MS : 1;
780 LogRel2(("HDA: Stream #%RU8 set scheduling hint for the backends to %RU32ms\n", uSD, pCfg->Device.cMsSchedulingHint));
781
782 /* Make sure to also update the stream's DMA counter (based on its current LPIB value). */
783 /** @todo r=bird: We use LPIB as-is here, so if it's not zero we have to
784 * locate the right place in the schedule and whatnot...
785 *
786 * This is a similar scenario as when loading state saved, btw.
787 */
788 if (HDA_STREAM_REG(pThis, LPIB, uSD) != 0)
789 LogRel2(("HDA: Warning! Stream #%RU8 is set up with LPIB=%#RX32 instead of zero!\n", uSD, HDA_STREAM_REG(pThis, LPIB, uSD)));
790 hdaStreamSetPositionAbs(pStreamShared, pDevIns, pThis, HDA_STREAM_REG(pThis, LPIB, uSD));
791
792# ifdef LOG_ENABLED
793 hdaR3BDLEDumpAll(pDevIns, pThis, pStreamShared->u64BDLBase, pStreamShared->u16LVI + 1);
794# endif
795
796 /*
797 * Set up internal ring buffer.
798 */
799
800 /* (Re-)Allocate the stream's internal DMA buffer,
801 * based on the timing *and* PCM properties we just got above. */
802 if (pStreamR3->State.pCircBuf)
803 {
804 RTCircBufDestroy(pStreamR3->State.pCircBuf);
805 pStreamR3->State.pCircBuf = NULL;
806 pStreamR3->State.StatDmaBufSize = 0;
807 pStreamR3->State.StatDmaBufUsed = 0;
808 }
809 pStreamShared->State.offWrite = 0;
810 pStreamShared->State.offRead = 0;
811
812 /*
813 * The default internal ring buffer size must be:
814 *
815 * - Large enough for at least three periodic DMA transfers.
816 *
817 * It is critically important that we don't experience underruns
818 * in the DMA OUT code, because it will cause the buffer processing
819 * to get skewed and possibly overlap with what the guest is updating.
820 * At the time of writing (2021-03-05) there is no code for getting
821 * back into sync there.
822 *
823 * - Large enough for at least three I/O scheduling hints.
824 *
825 * We want to lag behind a DMA period or two, but there must be
826 * sufficent space for the AIO thread to get schedule and shuffle
827 * data thru the mixer and onto the host audio hardware.
828 *
829 * - Both above with plenty to spare.
830 *
831 * So, just take the longest of the two periods and multipling it by 6.
832 * We aren't not talking about very large base buffers heres, so size isn't
833 * an issue.
834 *
835 * Note: Use pCfg->Props as PCM properties here, as we only want to store the
836 * samples we actually need, in other words, skipping the interleaved
837 * channels we don't support / need to save space.
838 */
839 uint32_t cbCircBuf = PDMAudioPropsMilliToBytes(&pCfg->Props, RT_MS_1SEC * 6 / uTransferHz);
840 LogRel2(("HDA: Stream #%RU8 default ring buffer size is %RU32 bytes / %RU64 ms\n",
841 uSD, cbCircBuf, PDMAudioPropsBytesToMilli(&pCfg->Props, cbCircBuf)));
842
843 uint32_t msCircBufCfg = hdaGetDirFromSD(uSD) == PDMAUDIODIR_IN ? pThis->cMsCircBufIn : pThis->cMsCircBufOut;
844 if (msCircBufCfg) /* Anything set via CFGM? */
845 {
846 cbCircBuf = PDMAudioPropsMilliToBytes(&pCfg->Props, msCircBufCfg);
847 LogRel2(("HDA: Stream #%RU8 is using a custom ring buffer size of %RU32 bytes / %RU64 ms\n",
848 uSD, cbCircBuf, PDMAudioPropsBytesToMilli(&pCfg->Props, cbCircBuf)));
849 }
850
851 /* Serious paranoia: */
852 ASSERT_GUEST_LOGREL_MSG_STMT(cbCircBuf % PDMAudioPropsFrameSize(&pCfg->Props) == 0,
853 ("Ring buffer size (%RU32) for stream #%RU8 not aligned to the (host) frame size (%RU8)\n",
854 cbCircBuf, uSD, PDMAudioPropsFrameSize(&pCfg->Props)),
855 rc = VERR_INVALID_PARAMETER);
856 ASSERT_GUEST_LOGREL_MSG_STMT(cbCircBuf, ("Ring buffer size for stream #%RU8 is invalid\n", uSD),
857 rc = VERR_INVALID_PARAMETER);
858 if (RT_SUCCESS(rc))
859 {
860 rc = RTCircBufCreate(&pStreamR3->State.pCircBuf, cbCircBuf);
861 if (RT_SUCCESS(rc))
862 {
863 pStreamR3->State.StatDmaBufSize = cbCircBuf;
864
865 /*
866 * Forward the timer frequency hint to TM as well for better accuracy on
867 * systems w/o preemption timers (also good for 'info timers').
868 */
869 PDMDevHlpTimerSetFrequencyHint(pDevIns, pStreamShared->hTimer, uTransferHz);
870 }
871 }
872
873 if (RT_FAILURE(rc))
874 LogRelMax(32, ("HDA: Initializing stream #%RU8 failed with %Rrc\n", uSD, rc));
875
876# ifdef VBOX_WITH_DTRACE
877 VBOXDD_HDA_STREAM_SETUP((uint32_t)uSD, rc, pStreamShared->State.Cfg.Props.uHz,
878 pStreamShared->State.aSchedule[pStreamShared->State.cSchedule - 1].cPeriodTicks,
879 pStreamShared->State.aSchedule[pStreamShared->State.cSchedule - 1].cbPeriod);
880# endif
881 return rc;
882}
883
884
885/**
886 * Worker for hdaR3StreamReset().
887 *
888 * @returns The default mixer sink, NULL if none found.
889 * @param pThisCC The ring-3 HDA device state.
890 * @param uSD SD# to return mixer sink for.
891 * NULL if not found / handled.
892 */
893static PHDAMIXERSINK hdaR3GetDefaultSink(PHDASTATER3 pThisCC, uint8_t uSD)
894{
895 if (hdaGetDirFromSD(uSD) == PDMAUDIODIR_IN)
896 {
897 const uint8_t uFirstSDI = 0;
898
899 if (uSD == uFirstSDI) /* First SDI. */
900 return &pThisCC->SinkLineIn;
901# ifdef VBOX_WITH_AUDIO_HDA_MIC_IN
902 if (uSD == uFirstSDI + 1)
903 return &pThisCC->SinkMicIn;
904# else
905 /* If we don't have a dedicated Mic-In sink, use the always present Line-In sink. */
906 return &pThisCC->SinkLineIn;
907# endif
908 }
909 else
910 {
911 const uint8_t uFirstSDO = HDA_MAX_SDI;
912
913 if (uSD == uFirstSDO)
914 return &pThisCC->SinkFront;
915# ifdef VBOX_WITH_AUDIO_HDA_51_SURROUND
916 if (uSD == uFirstSDO + 1)
917 return &pThisCC->SinkCenterLFE;
918 if (uSD == uFirstSDO + 2)
919 return &pThisCC->SinkRear;
920# endif
921 }
922
923 return NULL;
924}
925
926
927/**
928 * Resets an HDA stream.
929 *
930 * @param pThis The shared HDA device state.
931 * @param pThisCC The ring-3 HDA device state.
932 * @param pStreamShared HDA stream to reset (shared).
933 * @param pStreamR3 HDA stream to reset (ring-3).
934 * @param uSD Stream descriptor (SD) number to use for this stream.
935 */
936void hdaR3StreamReset(PHDASTATE pThis, PHDASTATER3 pThisCC, PHDASTREAM pStreamShared, PHDASTREAMR3 pStreamR3, uint8_t uSD)
937{
938 LogFunc(("[SD%RU8] Reset\n", uSD));
939
940 /*
941 * Assert some sanity.
942 */
943 AssertPtr(pThis);
944 AssertPtr(pStreamShared);
945 AssertPtr(pStreamR3);
946 Assert(uSD < HDA_MAX_STREAMS);
947 Assert(pStreamShared->u8SD == uSD);
948 Assert(pStreamR3->u8SD == uSD);
949 AssertMsg(!pStreamShared->State.fRunning, ("[SD%RU8] Cannot reset stream while in running state\n", uSD));
950
951 /*
952 * Set reset state.
953 */
954 Assert(ASMAtomicReadBool(&pStreamShared->State.fInReset) == false); /* No nested calls. */
955 ASMAtomicXchgBool(&pStreamShared->State.fInReset, true);
956
957 /*
958 * Second, initialize the registers.
959 */
960 /* See 6.2.33: Clear on reset. */
961 HDA_STREAM_REG(pThis, STS, uSD) = 0;
962 /* According to the ICH6 datasheet, 0x40000 is the default value for stream descriptor register 23:20
963 * bits are reserved for stream number 18.2.33, resets SDnCTL except SRST bit. */
964 HDA_STREAM_REG(pThis, CTL, uSD) = HDA_SDCTL_TP | (HDA_STREAM_REG(pThis, CTL, uSD) & HDA_SDCTL_SRST);
965 /* ICH6 defines default values (120 bytes for input and 192 bytes for output descriptors) of FIFO size. 18.2.39. */
966 HDA_STREAM_REG(pThis, FIFOS, uSD) = hdaGetDirFromSD(uSD) == PDMAUDIODIR_IN ? HDA_SDIFIFO_120B : HDA_SDOFIFO_192B;
967 /* See 18.2.38: Always defaults to 0x4 (32 bytes). */
968 HDA_STREAM_REG(pThis, FIFOW, uSD) = HDA_SDFIFOW_32B;
969 HDA_STREAM_REG(pThis, LPIB, uSD) = 0;
970 HDA_STREAM_REG(pThis, CBL, uSD) = 0;
971 HDA_STREAM_REG(pThis, LVI, uSD) = 0;
972 HDA_STREAM_REG(pThis, FMT, uSD) = 0;
973 HDA_STREAM_REG(pThis, BDPU, uSD) = 0;
974 HDA_STREAM_REG(pThis, BDPL, uSD) = 0;
975
976 /* Assign the default mixer sink to the stream. */
977 pStreamR3->pMixSink = hdaR3GetDefaultSink(pThisCC, uSD);
978 if (pStreamR3->State.pAioRegSink)
979 {
980 int rc2 = AudioMixerSinkRemoveUpdateJob(pStreamR3->State.pAioRegSink, hdaR3StreamUpdateAsyncIoJob, pStreamR3);
981 AssertRC(rc2);
982 pStreamR3->State.pAioRegSink = NULL;
983 }
984
985 /* Reset transfer stuff. */
986 pStreamShared->State.cTransferPendingInterrupts = 0;
987 pStreamShared->State.tsTransferLast = 0;
988 pStreamShared->State.tsTransferNext = 0;
989
990 /* Initialize timestamps. */
991 pStreamShared->State.tsLastTransferNs = 0;
992 pStreamShared->State.tsLastReadNs = 0;
993 pStreamShared->State.tsStart = 0;
994
995 RT_ZERO(pStreamShared->State.aBdl);
996 RT_ZERO(pStreamShared->State.aSchedule);
997 pStreamShared->State.offCurBdle = 0;
998 pStreamShared->State.cBdles = 0;
999 pStreamShared->State.idxCurBdle = 0;
1000 pStreamShared->State.cSchedulePrologue = 0;
1001 pStreamShared->State.cSchedule = 0;
1002 pStreamShared->State.idxSchedule = 0;
1003 pStreamShared->State.idxScheduleLoop = 0;
1004 pStreamShared->State.fInputPreBuffered = false;
1005
1006 if (pStreamR3->State.pCircBuf)
1007 RTCircBufReset(pStreamR3->State.pCircBuf);
1008 pStreamShared->State.offWrite = 0;
1009 pStreamShared->State.offRead = 0;
1010
1011 /* Report that we're done resetting this stream. */
1012 HDA_STREAM_REG(pThis, CTL, uSD) = 0;
1013
1014# ifdef VBOX_WITH_DTRACE
1015 VBOXDD_HDA_STREAM_RESET((uint32_t)uSD);
1016# endif
1017 LogFunc(("[SD%RU8] Reset\n", uSD));
1018
1019 /* Exit reset mode. */
1020 ASMAtomicXchgBool(&pStreamShared->State.fInReset, false);
1021}
1022
1023/**
1024 * Enables or disables an HDA audio stream.
1025 *
1026 * @returns VBox status code.
1027 * @param pThis The shared HDA device state.
1028 * @param pStreamShared HDA stream to enable or disable - shared bits.
1029 * @param pStreamR3 HDA stream to enable or disable - ring-3 bits.
1030 * @param fEnable Whether to enable or disble the stream.
1031 */
1032int hdaR3StreamEnable(PHDASTATE pThis, PHDASTREAM pStreamShared, PHDASTREAMR3 pStreamR3, bool fEnable)
1033{
1034 AssertPtr(pStreamR3);
1035 AssertPtr(pStreamShared);
1036
1037 LogFunc(("[SD%RU8] fEnable=%RTbool, pMixSink=%p\n", pStreamShared->u8SD, fEnable, pStreamR3->pMixSink));
1038
1039 /* First, enable or disable the stream and the stream's sink, if any. */
1040 int rc = VINF_SUCCESS;
1041 PAUDMIXSINK const pSink = pStreamR3->pMixSink ? pStreamR3->pMixSink->pMixSink : NULL;
1042 if (pSink)
1043 {
1044 if (fEnable)
1045 {
1046 if (pStreamR3->State.pAioRegSink != pSink)
1047 {
1048 if (pStreamR3->State.pAioRegSink)
1049 {
1050 rc = AudioMixerSinkRemoveUpdateJob(pStreamR3->State.pAioRegSink, hdaR3StreamUpdateAsyncIoJob, pStreamR3);
1051 AssertRC(rc);
1052 }
1053 rc = AudioMixerSinkAddUpdateJob(pSink, hdaR3StreamUpdateAsyncIoJob, pStreamR3,
1054 pStreamShared->State.Cfg.Device.cMsSchedulingHint);
1055 AssertLogRelRC(rc);
1056 pStreamR3->State.pAioRegSink = RT_SUCCESS(rc) ? pSink : NULL;
1057 }
1058 rc = AudioMixerSinkStart(pSink);
1059 }
1060 else
1061 rc = AudioMixerSinkDrainAndStopEx(pSink,
1062 pStreamR3->State.pCircBuf ? (uint32_t)RTCircBufUsed(pStreamR3->State.pCircBuf) : 0,
1063 RT_MS_5SEC);
1064 }
1065 if ( RT_SUCCESS(rc)
1066 && fEnable
1067 && pStreamR3->Dbg.Runtime.fEnabled)
1068 {
1069 Assert(AudioHlpPcmPropsAreValidAndSupported(&pStreamShared->State.Cfg.Props));
1070
1071 if (fEnable)
1072 {
1073 if (!AudioHlpFileIsOpen(pStreamR3->Dbg.Runtime.pFileStream))
1074 {
1075 int rc2 = AudioHlpFileOpen(pStreamR3->Dbg.Runtime.pFileStream, AUDIOHLPFILE_DEFAULT_OPEN_FLAGS,
1076 &pStreamShared->State.Cfg.Props);
1077 AssertRC(rc2);
1078 }
1079
1080 if (!AudioHlpFileIsOpen(pStreamR3->Dbg.Runtime.pFileDMARaw))
1081 {
1082 int rc2 = AudioHlpFileOpen(pStreamR3->Dbg.Runtime.pFileDMARaw, AUDIOHLPFILE_DEFAULT_OPEN_FLAGS,
1083 &pStreamShared->State.Cfg.Props);
1084 AssertRC(rc2);
1085 }
1086
1087 if (!AudioHlpFileIsOpen(pStreamR3->Dbg.Runtime.pFileDMAMapped))
1088 {
1089 int rc2 = AudioHlpFileOpen(pStreamR3->Dbg.Runtime.pFileDMAMapped, AUDIOHLPFILE_DEFAULT_OPEN_FLAGS,
1090 &pStreamShared->State.Cfg.Props);
1091 AssertRC(rc2);
1092 }
1093 }
1094 }
1095
1096 if (RT_SUCCESS(rc))
1097 {
1098 if (fEnable)
1099 pStreamShared->State.tsTransferLast = 0; /* Make sure it's not stale and messes up WALCLK calculations. */
1100 pStreamShared->State.fRunning = fEnable;
1101
1102 /*
1103 * Set the FIFORDY bit when we start running and clear it when stopping.
1104 *
1105 * This prevents Linux from timing out in snd_hdac_stream_sync when starting
1106 * a stream. Technically, Linux also uses the SSYNC feature there, but we
1107 * can get away with just setting the FIFORDY bit for now.
1108 */
1109 if (fEnable)
1110 HDA_STREAM_REG(pThis, STS, pStreamShared->u8SD) |= HDA_SDSTS_FIFORDY;
1111 else
1112 HDA_STREAM_REG(pThis, STS, pStreamShared->u8SD) &= ~HDA_SDSTS_FIFORDY;
1113 }
1114
1115 LogFunc(("[SD%RU8] rc=%Rrc\n", pStreamShared->u8SD, rc));
1116 return rc;
1117}
1118
1119/**
1120 * Marks the stream as started.
1121 *
1122 * Used after the stream has been enabled and the DMA timer has been armed.
1123 */
1124void hdaR3StreamMarkStarted(PPDMDEVINS pDevIns, PHDASTATE pThis, PHDASTREAM pStreamShared, uint64_t tsNow)
1125{
1126 pStreamShared->State.tsLastReadNs = RTTimeNanoTS();
1127 pStreamShared->State.tsStart = tsNow;
1128 Log3Func(("#%u: tsStart=%RU64 tsLastReadNs=%RU64\n",
1129 pStreamShared->u8SD, pStreamShared->State.tsStart, pStreamShared->State.tsLastReadNs));
1130 RT_NOREF(pDevIns, pThis);
1131}
1132
1133/**
1134 * Marks the stream as stopped.
1135 */
1136void hdaR3StreamMarkStopped(PHDASTREAM pStreamShared)
1137{
1138 Log3Func(("#%u\n", pStreamShared->u8SD));
1139 RT_NOREF(pStreamShared);
1140}
1141
1142#endif /* IN_RING3 */
1143#if defined(IN_RING3) || defined(VBOX_HDA_WITH_ON_REG_ACCESS_DMA)
1144
1145/**
1146 * Updates an HDA stream's current read or write buffer position (depending on the stream type) by
1147 * setting its associated LPIB register and DMA position buffer (if enabled) to an absolute value.
1148 *
1149 * @param pStreamShared HDA stream to update read / write position for (shared).
1150 * @param pDevIns The device instance.
1151 * @param pThis The shared HDA device state.
1152 * @param uLPIB Absolute position (in bytes) to set current read / write position to.
1153 */
1154static void hdaStreamSetPositionAbs(PHDASTREAM pStreamShared, PPDMDEVINS pDevIns, PHDASTATE pThis, uint32_t uLPIB)
1155{
1156 AssertPtrReturnVoid(pStreamShared);
1157 AssertMsgStmt(uLPIB <= pStreamShared->u32CBL, ("%#x\n", uLPIB), uLPIB = pStreamShared->u32CBL);
1158
1159 Log3Func(("[SD%RU8] LPIB=%RU32 (DMA Position Buffer Enabled: %RTbool)\n", pStreamShared->u8SD, uLPIB, pThis->fDMAPosition));
1160
1161 /* Update LPIB in any case. */
1162 HDA_STREAM_REG(pThis, LPIB, pStreamShared->u8SD) = uLPIB;
1163
1164 /* Do we need to tell the current DMA position? */
1165 if (pThis->fDMAPosition)
1166 {
1167 /*
1168 * Linux switched to using the position buffers some time during 2.6.x.
1169 * 2.6.12 used LPIB, 2.6.17 defaulted to DMA position buffers, between
1170 * the two version things were being changing quite a bit.
1171 *
1172 * Since 2.6.17, they will treat a zero DMA position value during the first
1173 * period/IRQ as reason to fall back to LPIB mode (see azx_position_ok in
1174 * 2.6.27+, and azx_pcm_pointer before that). They later also added
1175 * UINT32_MAX to the values causing same.
1176 *
1177 * Since 2.6.35 azx_position_ok will read the wall clock register before
1178 * determining the position.
1179 */
1180 int rc2 = PDMDevHlpPCIPhysWrite(pDevIns,
1181 pThis->u64DPBase + (pStreamShared->u8SD * 2 * sizeof(uint32_t)),
1182 (void *)&uLPIB, sizeof(uint32_t));
1183 AssertRC(rc2);
1184 }
1185}
1186
1187
1188/**
1189 * Updates an HDA stream's current read or write buffer position (depending on the stream type) by
1190 * adding a value to its associated LPIB register and DMA position buffer (if enabled).
1191 *
1192 * @note Handles automatic CBL wrap-around.
1193 *
1194 * @param pStreamShared HDA stream to update read / write position for (shared).
1195 * @param pDevIns The device instance.
1196 * @param pThis The shared HDA device state.
1197 * @param cbToAdd Position (in bytes) to add to the current read / write position.
1198 */
1199static void hdaStreamSetPositionAdd(PHDASTREAM pStreamShared, PPDMDEVINS pDevIns, PHDASTATE pThis, uint32_t cbToAdd)
1200{
1201 if (cbToAdd) /* No need to update anything if 0. */
1202 {
1203 uint32_t const uCBL = pStreamShared->u32CBL;
1204 if (uCBL) /* paranoia */
1205 {
1206 uint32_t uNewLpid = HDA_STREAM_REG(pThis, LPIB, pStreamShared->u8SD) + cbToAdd;
1207# if 1 /** @todo r=bird: this is wrong according to the spec */
1208 uNewLpid %= uCBL;
1209# else
1210 /* The spec says it goes to CBL then wraps arpimd to 1, not back to zero. See 3.3.37. */
1211 if (uNewLpid > uCBL)
1212 uNewLpid %= uCBL;
1213# endif
1214 hdaStreamSetPositionAbs(pStreamShared, pDevIns, pThis, uNewLpid);
1215 }
1216 }
1217}
1218
1219#endif /* IN_RING3 || VBOX_HDA_WITH_ON_REG_ACCESS_DMA */
1220#ifdef IN_RING3
1221
1222/**
1223 * Retrieves the available size of (buffered) audio data (in bytes) of a given HDA stream.
1224 *
1225 * @returns Available data (in bytes).
1226 * @param pStreamR3 HDA stream to retrieve size for (ring-3).
1227 */
1228static uint32_t hdaR3StreamGetUsed(PHDASTREAMR3 pStreamR3)
1229{
1230 AssertPtrReturn(pStreamR3, 0);
1231
1232 if (pStreamR3->State.pCircBuf)
1233 return (uint32_t)RTCircBufUsed(pStreamR3->State.pCircBuf);
1234 return 0;
1235}
1236
1237/**
1238 * Retrieves the free size of audio data (in bytes) of a given HDA stream.
1239 *
1240 * @returns Free data (in bytes).
1241 * @param pStreamR3 HDA stream to retrieve size for (ring-3).
1242 */
1243static uint32_t hdaR3StreamGetFree(PHDASTREAMR3 pStreamR3)
1244{
1245 AssertPtrReturn(pStreamR3, 0);
1246
1247 if (pStreamR3->State.pCircBuf)
1248 return (uint32_t)RTCircBufFree(pStreamR3->State.pCircBuf);
1249 return 0;
1250}
1251
1252#endif /* IN_RING3 */
1253#if defined(IN_RING3) || defined(VBOX_HDA_WITH_ON_REG_ACCESS_DMA)
1254
1255/**
1256 * Get the current address and number of bytes left in the current BDLE.
1257 *
1258 * @returns The current physical address.
1259 * @param pStreamShared The stream to check.
1260 * @param pcbLeft The number of bytes left at the returned address.
1261 */
1262DECLINLINE(RTGCPHYS) hdaStreamDmaBufGet(PHDASTREAM pStreamShared, uint32_t *pcbLeft)
1263{
1264 uint8_t idxBdle = pStreamShared->State.idxCurBdle;
1265 AssertStmt(idxBdle < pStreamShared->State.cBdles, idxBdle = 0);
1266
1267 uint32_t const cbCurBdl = pStreamShared->State.aBdl[idxBdle].cb;
1268 uint32_t offCurBdle = pStreamShared->State.offCurBdle;
1269 AssertStmt(pStreamShared->State.offCurBdle <= cbCurBdl, offCurBdle = cbCurBdl);
1270
1271 *pcbLeft = cbCurBdl - offCurBdle;
1272 return pStreamShared->State.aBdl[idxBdle].GCPhys + offCurBdle;
1273}
1274
1275/**
1276 * Checks if the current BDLE is completed.
1277 *
1278 * @retval true if complete
1279 * @retval false if not.
1280 * @param pStreamShared The stream to check.
1281 */
1282DECLINLINE(bool) hdaStreamDmaBufIsComplete(PHDASTREAM pStreamShared)
1283{
1284 uint8_t const idxBdle = pStreamShared->State.idxCurBdle;
1285 AssertReturn(idxBdle < pStreamShared->State.cBdles, true);
1286
1287 uint32_t const cbCurBdl = pStreamShared->State.aBdl[idxBdle].cb;
1288 uint32_t const offCurBdle = pStreamShared->State.offCurBdle;
1289 Assert(offCurBdle <= cbCurBdl);
1290 return offCurBdle >= cbCurBdl;
1291}
1292
1293/**
1294 * Checks if the current BDLE needs a completion IRQ.
1295 *
1296 * @retval true if IRQ is needed.
1297 * @retval false if not.
1298 * @param pStreamShared The stream to check.
1299 */
1300DECLINLINE(bool) hdaStreamDmaBufNeedsIrq(PHDASTREAM pStreamShared)
1301{
1302 uint8_t const idxBdle = pStreamShared->State.idxCurBdle;
1303 AssertReturn(idxBdle < pStreamShared->State.cBdles, false);
1304 return (pStreamShared->State.aBdl[idxBdle].fFlags & HDA_BDLE_F_IOC) != 0;
1305}
1306
1307/**
1308 * Advances the DMA engine to the next BDLE.
1309 *
1310 * @param pStreamShared The stream which DMA engine is to be updated.
1311 */
1312DECLINLINE(void) hdaStreamDmaBufAdvanceToNext(PHDASTREAM pStreamShared)
1313{
1314 uint8_t idxBdle = pStreamShared->State.idxCurBdle;
1315 Assert(pStreamShared->State.offCurBdle == pStreamShared->State.aBdl[idxBdle].cb);
1316
1317 if (idxBdle < pStreamShared->State.cBdles - 1)
1318 idxBdle++;
1319 else
1320 idxBdle = 0;
1321 pStreamShared->State.idxCurBdle = idxBdle;
1322 pStreamShared->State.offCurBdle = 0;
1323}
1324
1325#endif /* defined(IN_RING3) || defined(VBOX_HDA_WITH_ON_REG_ACCESS_DMA) */
1326#ifdef IN_RING3
1327
1328/**
1329 * Common do-DMA prologue code.
1330 *
1331 * @retval true if DMA processing can take place
1332 * @retval false if caller should return immediately.
1333 * @param pThis The shared HDA device state.
1334 * @param pStreamShared HDA stream to update (shared).
1335 * @param pStreamR3 HDA stream to update (ring-3).
1336 * @param uSD The stream ID (for asserting).
1337 * @param tsNowNs The current RTTimeNano() value.
1338 * @param pszFunction The function name (for logging).
1339 */
1340DECLINLINE(bool) hdaR3StreamDoDmaPrologue(PHDASTATE pThis, PHDASTREAM pStreamShared, PHDASTREAMR3 pStreamR3, uint8_t uSD,
1341 uint64_t tsNowNs, const char *pszFunction)
1342{
1343 RT_NOREF(uSD, pszFunction);
1344
1345 /*
1346 * Check if we should skip town...
1347 */
1348 /* Stream not running (anymore)? */
1349 if (pStreamShared->State.fRunning)
1350 { /* likely */ }
1351 else
1352 {
1353 Log3(("%s: [SD%RU8] Not running, skipping transfer\n", pszFunction, uSD));
1354 return false;
1355 }
1356
1357 if (!(HDA_STREAM_REG(pThis, STS, uSD) & HDA_SDSTS_BCIS))
1358 { /* likely */ }
1359 else
1360 {
1361 /** @todo r=bird: This is a bit fishy. We should make effort the reschedule
1362 * the transfer immediately after the guest clears the interrupt.
1363 * The same fishy code is present in AC'97 with just a little
1364 * explanation as here, see @bugref{9890#c95}.
1365 *
1366 * The reasoning is probably that the developer noticed some windows
1367 * versions don't like having their BCIS interrupts bundled. There were
1368 * comments to that effect elsewhere, probably as a result of a fixed
1369 * uTimerHz approach to DMA scheduling. However, pausing DMA for a
1370 * period isn't going to help us with the host backends, as they don't
1371 * pause and will want samples ASAP. So, we should at least unpause
1372 * DMA as quickly as we possible when BCIS is cleared. We might even
1373 * not skip it iff the DMA work here doesn't involve raising any IOC,
1374 * which is possible although unlikely. */
1375 Log3(("%s: [SD%RU8] BCIS bit set, skipping transfer\n", pszFunction, uSD));
1376 STAM_REL_COUNTER_INC(&pStreamR3->State.StatDmaSkippedPendingBcis);
1377 Log(("%s: [SD%RU8] BCIS bit set, skipping transfer\n", pszFunction, uSD));
1378# ifdef HDA_STRICT
1379 /* Timing emulation bug or guest is misbehaving -- let me know. */
1380 AssertMsgFailed(("%s: BCIS bit for stream #%RU8 still set when it shouldn't\n", pszFunction, uSD));
1381# endif
1382 return false;
1383 }
1384
1385 /*
1386 * Stream sanity checks.
1387 */
1388 /* Register sanity checks. */
1389 Assert(uSD < HDA_MAX_STREAMS);
1390 Assert(pStreamShared->u64BDLBase);
1391 Assert(pStreamShared->u32CBL);
1392 Assert(pStreamShared->u8FIFOS);
1393
1394 /* State sanity checks. */
1395 Assert(ASMAtomicReadBool(&pStreamShared->State.fInReset) == false);
1396 Assert(ASMAtomicReadBool(&pStreamShared->State.fRunning));
1397
1398 /*
1399 * Some timestamp stuff for logging/debugging.
1400 */
1401 /*const uint64_t tsNowNs = RTTimeNanoTS();*/
1402 Log3(("%s: [SD%RU8] tsDeltaNs=%'RU64 ns\n", pszFunction, uSD, tsNowNs - pStreamShared->State.tsLastTransferNs));
1403 pStreamShared->State.tsLastTransferNs = tsNowNs;
1404
1405 return true;
1406}
1407
1408/**
1409 * Common do-DMA epilogue.
1410 *
1411 * @param pDevIns The device instance.
1412 * @param pStreamShared The HDA stream (shared).
1413 * @param pStreamR3 The HDA stream (ring-3).
1414 */
1415DECLINLINE(void) hdaR3StreamDoDmaEpilogue(PPDMDEVINS pDevIns, PHDASTREAM pStreamShared, PHDASTREAMR3 pStreamR3)
1416{
1417 /*
1418 * We must update this in the epilogue rather than in the prologue
1419 * as it is used for WALCLK calculation and we must make sure the
1420 * guest doesn't think we've processed the current period till we
1421 * actually have.
1422 */
1423 pStreamShared->State.tsTransferLast = PDMDevHlpTimerGet(pDevIns, pStreamShared->hTimer);
1424
1425 /*
1426 * Update the buffer statistics.
1427 */
1428 pStreamR3->State.StatDmaBufUsed = (uint32_t)RTCircBufUsed(pStreamR3->State.pCircBuf);
1429}
1430
1431#endif /* IN_RING3 */
1432
1433#if defined(IN_RING3) || defined(VBOX_HDA_WITH_ON_REG_ACCESS_DMA)
1434/**
1435 * Completes a BDLE at the end of a DMA loop iteration, if possible.
1436 *
1437 * @retval true if buffer completed and new loaded.
1438 * @retval false if buffer not completed.
1439 * @param pDevIns The device instance.
1440 * @param pThis The shared HDA device state.
1441 * @param pStreamShared HDA stream to update (shared).
1442 * @param pszFunction The function name (for logging).
1443 */
1444DECLINLINE(bool) hdaStreamDoDmaMaybeCompleteBuffer(PPDMDEVINS pDevIns, PHDASTATE pThis,
1445 PHDASTREAM pStreamShared, const char *pszFunction)
1446{
1447 RT_NOREF(pszFunction);
1448
1449 /*
1450 * Is the buffer descriptor complete.
1451 */
1452 if (hdaStreamDmaBufIsComplete(pStreamShared))
1453 {
1454 Log3(("%s: [SD%RU8] Completed BDLE%u %#RX64 LB %#RX32 fFlags=%#x\n", pszFunction, pStreamShared->u8SD,
1455 pStreamShared->State.idxCurBdle, pStreamShared->State.aBdl[pStreamShared->State.idxCurBdle].GCPhys,
1456 pStreamShared->State.aBdl[pStreamShared->State.idxCurBdle].cb,
1457 pStreamShared->State.aBdl[pStreamShared->State.idxCurBdle].fFlags));
1458
1459 /* Does the current BDLE require an interrupt to be sent? */
1460 if (hdaStreamDmaBufNeedsIrq(pStreamShared))
1461 {
1462 /* If the IOCE ("Interrupt On Completion Enable") bit of the SDCTL
1463 register is set we need to generate an interrupt. */
1464 if (HDA_STREAM_REG(pThis, CTL, pStreamShared->u8SD) & HDA_SDCTL_IOCE)
1465 {
1466 /* Assert the interrupt before actually fetching the next BDLE below. */
1467 pStreamShared->State.cTransferPendingInterrupts = 1;
1468 Log3(("%s: [SD%RU8] Scheduling interrupt\n", pszFunction, pStreamShared->u8SD));
1469
1470 /* Trigger an interrupt first and let hdaRegWriteSDSTS() deal with
1471 * ending / beginning of a period. */
1472 /** @todo r=bird: What does the above comment mean? */
1473 HDA_STREAM_REG(pThis, STS, pStreamShared->u8SD) |= HDA_SDSTS_BCIS;
1474 HDA_PROCESS_INTERRUPT(pDevIns, pThis);
1475 }
1476 }
1477
1478 /*
1479 * Advance to the next BDLE.
1480 */
1481 hdaStreamDmaBufAdvanceToNext(pStreamShared);
1482 return true;
1483 }
1484
1485 Log3(("%s: [SD%RU8] Incomplete BDLE%u %#RX64 LB %#RX32 fFlags=%#x: off=%#RX32\n", pszFunction, pStreamShared->u8SD,
1486 pStreamShared->State.idxCurBdle, pStreamShared->State.aBdl[pStreamShared->State.idxCurBdle].GCPhys,
1487 pStreamShared->State.aBdl[pStreamShared->State.idxCurBdle].cb,
1488 pStreamShared->State.aBdl[pStreamShared->State.idxCurBdle].fFlags, pStreamShared->State.offCurBdle));
1489 return false;
1490}
1491#endif /* IN_RING3 || VBOX_HDA_WITH_ON_REG_ACCESS_DMA */
1492
1493#ifdef IN_RING3
1494
1495/**
1496 * Does DMA transfer for an HDA input stream.
1497 *
1498 * Reads audio data from the HDA stream's internal DMA buffer and writing to
1499 * guest memory.
1500 *
1501 * @param pDevIns The device instance.
1502 * @param pThis The shared HDA device state.
1503 * @param pStreamShared HDA stream to update (shared).
1504 * @param pStreamR3 HDA stream to update (ring-3).
1505 * @param cbToConsume The max amount of data to consume from the
1506 * internal DMA buffer. The caller will make sure
1507 * this is always the transfer size fo the current
1508 * period (unless something is seriously wrong).
1509 * @param fWriteSilence Whether to feed the guest silence rather than
1510 * fetching bytes from the internal DMA buffer.
1511 * This is set initially while we pre-buffer a
1512 * little bit of input, so we can better handle
1513 * time catch-ups and other schduling fun.
1514 * @param tsNowNs The current RTTimeNano() value.
1515 *
1516 * @remarks Caller owns the stream lock.
1517 */
1518static void hdaR3StreamDoDmaInput(PPDMDEVINS pDevIns, PHDASTATE pThis, PHDASTREAM pStreamShared,
1519 PHDASTREAMR3 pStreamR3, uint32_t const cbToConsume, bool fWriteSilence, uint64_t tsNowNs)
1520{
1521 uint8_t const uSD = pStreamShared->u8SD;
1522 LogFlowFunc(("ENTER - #%u cbToConsume=%#x%s\n", uSD, cbToConsume, fWriteSilence ? " silence" : ""));
1523
1524 /*
1525 * Common prologue.
1526 */
1527 if (hdaR3StreamDoDmaPrologue(pThis, pStreamShared, pStreamR3, uSD, tsNowNs, "hdaR3StreamDoDmaInput"))
1528 { /* likely */ }
1529 else
1530 return;
1531
1532 /*
1533 *
1534 * The DMA copy loop.
1535 *
1536 * Note! Unaligned BDLEs shouldn't be a problem since the circular buffer
1537 * doesn't care about alignment. Only, we have to read the rest
1538 * of the incomplete frame from it ASAP.
1539 */
1540 PRTCIRCBUF pCircBuf = pStreamR3->State.pCircBuf;
1541 uint32_t cbLeft = cbToConsume;
1542 Assert(cbLeft == pStreamShared->State.cbCurDmaPeriod);
1543 Assert(PDMAudioPropsIsSizeAligned(&pStreamShared->State.Cfg.Props, cbLeft));
1544
1545 while (cbLeft > 0)
1546 {
1547 STAM_PROFILE_START(&pThis->StatIn, a);
1548
1549 /*
1550 * Figure out how much we can read & write in this iteration.
1551 */
1552 uint32_t cbChunk = 0;
1553 RTGCPHYS GCPhys = hdaStreamDmaBufGet(pStreamShared, &cbChunk);
1554
1555 if (cbChunk <= cbLeft)
1556 { /* very likely */ }
1557 else
1558 cbChunk = cbLeft;
1559
1560 uint32_t cbWritten = 0;
1561 if (!fWriteSilence)
1562 {
1563 /*
1564 * Write the host data directly into the guest buffers.
1565 */
1566 while (cbChunk > 0)
1567 {
1568 /* Grab internal DMA buffer space and read into it. */
1569 void /*const*/ *pvBufSrc;
1570 size_t cbBufSrc;
1571 RTCircBufAcquireReadBlock(pCircBuf, cbChunk, &pvBufSrc, &cbBufSrc);
1572 AssertBreakStmt(cbBufSrc, RTCircBufReleaseReadBlock(pCircBuf, 0));
1573
1574 int rc2 = PDMDevHlpPCIPhysWrite(pDevIns, GCPhys, pvBufSrc, cbBufSrc);
1575 AssertRC(rc2);
1576
1577# ifdef HDA_DEBUG_SILENCE
1578 fix me if relevant;
1579# endif
1580 if (RT_LIKELY(!pStreamR3->Dbg.Runtime.pFileDMARaw))
1581 { /* likely */ }
1582 else
1583 AudioHlpFileWrite(pStreamR3->Dbg.Runtime.pFileDMARaw, pvBufSrc, cbBufSrc);
1584
1585# ifdef VBOX_WITH_DTRACE
1586 VBOXDD_HDA_STREAM_DMA_IN((uint32_t)uSD, (uint32_t)cbBufSrc, pStreamShared->State.offRead);
1587# endif
1588 pStreamShared->State.offRead += cbBufSrc;
1589 RTCircBufReleaseReadBlock(pCircBuf, cbBufSrc);
1590 STAM_COUNTER_ADD(&pThis->StatBytesWritten, cbBufSrc);
1591
1592 /* advance */
1593 cbChunk -= (uint32_t)cbBufSrc;
1594 cbWritten += (uint32_t)cbBufSrc;
1595 GCPhys += cbBufSrc;
1596 pStreamShared->State.offCurBdle += (uint32_t)cbBufSrc;
1597 }
1598 }
1599 /*
1600 * Write silence. Since we only do signed formats, we can use the zero
1601 * buffers from IPRT as source here.
1602 */
1603 else
1604 {
1605 Assert(PDMAudioPropsIsSigned(&pStreamShared->State.Cfg.Props));
1606 while (cbChunk > 0)
1607 {
1608 /* Write it to the guest buffer. */
1609 uint32_t cbToWrite = RT_MIN(sizeof(g_abRTZero64K), cbChunk);
1610 int rc2 = PDMDevHlpPCIPhysWrite(pDevIns, GCPhys, g_abRTZero64K, cbToWrite);
1611 AssertRC(rc2);
1612 STAM_COUNTER_ADD(&pThis->StatBytesWritten, cbToWrite);
1613
1614 /* advance */
1615 cbWritten += cbToWrite;
1616 cbChunk -= cbToWrite;
1617 GCPhys += cbToWrite;
1618 pStreamShared->State.offCurBdle += cbToWrite;
1619 }
1620 }
1621
1622 cbLeft -= cbWritten;
1623 STAM_PROFILE_STOP(&pThis->StatIn, a);
1624
1625 /*
1626 * Complete the buffer if necessary (common with the output DMA code).
1627 *
1628 * Must update the DMA position before we do this as the buffer IRQ may
1629 * fire on another vCPU and run in parallel to us, although it is very
1630 * unlikely it can make much progress as long as we're sitting on the
1631 * lock, it could still read the DMA position (Linux won't, as it reads
1632 * WALCLK and possibly SDnSTS before the DMA position).
1633 */
1634 hdaStreamSetPositionAdd(pStreamShared, pDevIns, pThis, cbWritten);
1635 hdaStreamDoDmaMaybeCompleteBuffer(pDevIns, pThis, pStreamShared, "hdaR3StreamDoDmaInput");
1636 }
1637
1638 Assert(cbLeft == 0); /* There shall be no break statements in the above loop, so cbLeft is always zero here! */
1639
1640 /*
1641 * Common epilogue.
1642 */
1643 hdaR3StreamDoDmaEpilogue(pDevIns, pStreamShared, pStreamR3);
1644
1645 /*
1646 * Log and leave.
1647 */
1648 Log3Func(("LEAVE - [SD%RU8] %#RX32/%#RX32 @ %#RX64 - cTransferPendingInterrupts=%RU8\n",
1649 uSD, cbToConsume, pStreamShared->State.cbCurDmaPeriod, pStreamShared->State.offRead - cbToConsume,
1650 pStreamShared->State.cTransferPendingInterrupts));
1651}
1652
1653
1654/**
1655 * Input streams: Pulls data from the mixer, putting it in the internal DMA
1656 * buffer.
1657 *
1658 * @param pStreamShared HDA stream to update (shared).
1659 * @param pStreamR3 HDA stream to update (ring-3 bits).
1660 * @param pSink The mixer sink to pull from.
1661 */
1662static void hdaR3StreamPullFromMixer(PHDASTREAM pStreamShared, PHDASTREAMR3 pStreamR3, PAUDMIXSINK pSink)
1663{
1664# ifdef LOG_ENABLED
1665 uint64_t const offWriteOld = pStreamShared->State.offWrite;
1666# endif
1667 pStreamShared->State.offWrite = AudioMixerSinkTransferToCircBuf(pSink,
1668 pStreamR3->State.pCircBuf,
1669 pStreamShared->State.offWrite,
1670 pStreamR3->u8SD,
1671 pStreamR3->Dbg.Runtime.fEnabled
1672 ? pStreamR3->Dbg.Runtime.pFileStream : NULL);
1673
1674 Log3Func(("[SD%RU8] transferred=%#RX64 bytes -> @%#RX64\n", pStreamR3->u8SD,
1675 pStreamShared->State.offWrite - offWriteOld, pStreamShared->State.offWrite));
1676
1677 /* Update buffer stats. */
1678 pStreamR3->State.StatDmaBufUsed = (uint32_t)RTCircBufUsed(pStreamR3->State.pCircBuf);
1679}
1680
1681
1682/**
1683 * Does DMA transfer for an HDA output stream.
1684 *
1685 * This transfers one DMA timer period worth of data from the guest and into the
1686 * internal DMA buffer.
1687 *
1688 * @param pDevIns The device instance.
1689 * @param pThis The shared HDA device state.
1690 * @param pStreamShared HDA stream to update (shared).
1691 * @param pStreamR3 HDA stream to update (ring-3).
1692 * @param cbToProduce The max amount of data to produce (i.e. put into
1693 * the circular buffer). Unless something is going
1694 * seriously wrong, this will always be transfer
1695 * size for the current period.
1696 * @param tsNowNs The current RTTimeNano() value.
1697 *
1698 * @remarks Caller owns the stream lock.
1699 */
1700static void hdaR3StreamDoDmaOutput(PPDMDEVINS pDevIns, PHDASTATE pThis, PHDASTREAM pStreamShared,
1701 PHDASTREAMR3 pStreamR3, uint32_t const cbToProduce, uint64_t tsNowNs)
1702{
1703 uint8_t const uSD = pStreamShared->u8SD;
1704 LogFlowFunc(("ENTER - #%u cbToProduce=%#x\n", uSD, cbToProduce));
1705
1706 /*
1707 * Common prologue.
1708 */
1709 if (hdaR3StreamDoDmaPrologue(pThis, pStreamShared, pStreamR3, uSD, tsNowNs, "hdaR3StreamDoDmaOutput"))
1710 { /* likely */ }
1711 else
1712 return;
1713
1714 /*
1715 *
1716 * The DMA copy loop.
1717 *
1718 * Note! Unaligned BDLEs shouldn't be a problem since the circular buffer
1719 * doesn't care about alignment. Only, we have to write the rest
1720 * of the incomplete frame to it ASAP.
1721 */
1722 PRTCIRCBUF pCircBuf = pStreamR3->State.pCircBuf;
1723 uint32_t cbLeft = cbToProduce;
1724# ifdef VBOX_HDA_WITH_ON_REG_ACCESS_DMA
1725 Assert(cbLeft <= pStreamShared->State.cbCurDmaPeriod); /* a little pointless with the DMA'ing on LPIB read. */
1726# else
1727 Assert(cbLeft == pStreamShared->State.cbCurDmaPeriod);
1728# endif
1729 Assert(PDMAudioPropsIsSizeAligned(&pStreamShared->State.Cfg.Props, cbLeft));
1730
1731 while (cbLeft > 0)
1732 {
1733 STAM_PROFILE_START(&pThis->StatOut, a);
1734
1735 /*
1736 * Figure out how much we can read & write in this iteration.
1737 */
1738 uint32_t cbChunk = 0;
1739 RTGCPHYS GCPhys = hdaStreamDmaBufGet(pStreamShared, &cbChunk);
1740
1741 if (cbChunk <= cbLeft)
1742 { /* very likely */ }
1743 else
1744 cbChunk = cbLeft;
1745
1746 /*
1747 * Read the guest data directly into the internal DMA buffer.
1748 */
1749 uint32_t cbRead = 0;
1750 while (cbChunk > 0)
1751 {
1752 /* Grab internal DMA buffer space and read into it. */
1753 void *pvBufDst;
1754 size_t cbBufDst;
1755 RTCircBufAcquireWriteBlock(pCircBuf, cbChunk, &pvBufDst, &cbBufDst);
1756 AssertBreakStmt(cbBufDst, RTCircBufReleaseWriteBlock(pCircBuf, 0));
1757
1758 int rc2 = PDMDevHlpPCIPhysRead(pDevIns, GCPhys, pvBufDst, cbBufDst);
1759 AssertRC(rc2);
1760
1761# ifdef HDA_DEBUG_SILENCE
1762 fix me if relevant;
1763# endif
1764 if (RT_LIKELY(!pStreamR3->Dbg.Runtime.pFileDMARaw))
1765 { /* likely */ }
1766 else
1767 AudioHlpFileWrite(pStreamR3->Dbg.Runtime.pFileDMARaw, pvBufDst, cbBufDst);
1768
1769# ifdef VBOX_WITH_DTRACE
1770 VBOXDD_HDA_STREAM_DMA_OUT((uint32_t)uSD, (uint32_t)cbBufDst, pStreamShared->State.offWrite);
1771# endif
1772 pStreamShared->State.offWrite += cbBufDst;
1773 RTCircBufReleaseWriteBlock(pCircBuf, cbBufDst);
1774 STAM_COUNTER_ADD(&pThis->StatBytesRead, cbBufDst);
1775
1776 /* advance */
1777 cbChunk -= (uint32_t)cbBufDst;
1778 cbRead += (uint32_t)cbBufDst;
1779 GCPhys += cbBufDst;
1780 pStreamShared->State.offCurBdle += (uint32_t)cbBufDst;
1781 }
1782
1783 cbLeft -= cbRead;
1784 STAM_PROFILE_STOP(&pThis->StatOut, a);
1785
1786 /*
1787 * Complete the buffer if necessary (common with the input DMA code).
1788 *
1789 * Must update the DMA position before we do this as the buffer IRQ may
1790 * fire on another vCPU and run in parallel to us, although it is very
1791 * unlikely it can make much progress as long as we're sitting on the
1792 * lock, it could still read the DMA position (Linux won't, as it reads
1793 * WALCLK and possibly SDnSTS before the DMA position).
1794 */
1795 hdaStreamSetPositionAdd(pStreamShared, pDevIns, pThis, cbRead);
1796 hdaStreamDoDmaMaybeCompleteBuffer(pDevIns, pThis, pStreamShared, "hdaR3StreamDoDmaOutput");
1797 }
1798
1799 Assert(cbLeft == 0); /* There shall be no break statements in the above loop, so cbLeft is always zero here! */
1800
1801 /*
1802 * Common epilogue.
1803 */
1804 hdaR3StreamDoDmaEpilogue(pDevIns, pStreamShared, pStreamR3);
1805
1806 /*
1807 * Log and leave.
1808 */
1809 Log3Func(("LEAVE - [SD%RU8] %#RX32/%#RX32 @ %#RX64 - cTransferPendingInterrupts=%RU8\n",
1810 uSD, cbToProduce, pStreamShared->State.cbCurDmaPeriod, pStreamShared->State.offWrite - cbToProduce,
1811 pStreamShared->State.cTransferPendingInterrupts));
1812}
1813
1814#endif /* IN_RING3 */
1815#ifdef VBOX_HDA_WITH_ON_REG_ACCESS_DMA
1816
1817/**
1818 * Do DMA output transfer on LPIB/WALCLK register access.
1819 *
1820 * @returns VINF_SUCCESS or VINF_IOM_R3_MMIO_READ.
1821 * @param pDevIns The device instance.
1822 * @param pThis The shared instance data.
1823 * @param pStreamShared The shared stream data.
1824 * @param tsNow The current time on the timer clock.
1825 * @param cbToTransfer How much to transfer.
1826 */
1827VBOXSTRICTRC hdaStreamDoOnAccessDmaOutput(PPDMDEVINS pDevIns, PHDASTATE pThis, PHDASTREAM pStreamShared,
1828 uint64_t tsNow, uint32_t cbToTransfer)
1829{
1830 AssertReturn(cbToTransfer > 0, VINF_SUCCESS);
1831 int rc = VINF_SUCCESS;
1832
1833 /*
1834 * Check if we're exceeding the available buffer, go to ring-3 to
1835 * handle that (we would perhaps always take this path when in ring-3).
1836 */
1837 uint32_t cbDma = pStreamShared->State.cbDma;
1838 ASMCompilerBarrier();
1839 if ( cbDma >= sizeof(pStreamShared->State.abDma) /* paranoia */
1840 || cbToTransfer >= sizeof(pStreamShared->State.abDma) /* paranoia */
1841 || cbDma + cbToTransfer > sizeof(pStreamShared->State.abDma))
1842 {
1843# ifndef IN_RING3
1844 STAM_REL_COUNTER_INC(&pThis->StatAccessDmaOutputToR3);
1845 LogFlowFunc(("[SD%RU8] out of DMA buffer space (%#x, need %#x) -> VINF_IOM_R3_MMIO_READ\n",
1846 pStreamShared->u8SD, sizeof(pStreamShared->State.abDma) - pStreamShared->State.cbDma, cbToTransfer));
1847 return VINF_IOM_R3_MMIO_READ;
1848# else /* IN_RING3 */
1849 /*
1850 * Flush the bounce buffer, then do direct transfers to the
1851 * internal DMA buffer (updates LPIB).
1852 */
1853 PHDASTATER3 const pThisCC = PDMDEVINS_2_DATA_CC(pDevIns, PHDASTATER3);
1854 uintptr_t const idxStream = pStreamShared->u8SD;
1855 AssertReturn(idxStream < RT_ELEMENTS(pThisCC->aStreams), VERR_INTERNAL_ERROR_4);
1856 PHDASTREAMR3 const pStreamR3 = &pThisCC->aStreams[idxStream];
1857
1858 hdaR3StreamFlushDmaBounceBufferOutput(pStreamShared, pStreamR3);
1859
1860 uint32_t cbStreamFree = hdaR3StreamGetFree(pStreamR3);
1861 if (cbStreamFree >= cbToTransfer)
1862 { /* likely */ }
1863 else
1864 {
1865 PAUDMIXSINK pSink = pStreamR3->pMixSink ? pStreamR3->pMixSink->pMixSink : NULL;
1866 if (pSink)
1867 cbStreamFree = hdaR3StreamHandleDmaBufferOverrun(pStreamShared, pStreamR3, pSink, cbToTransfer, RTTimeNanoTS(),
1868 "hdaStreamDoOnAccessDmaOutput", cbStreamFree);
1869 else
1870 {
1871 LogFunc(("[SD%RU8] No sink and insufficient internal DMA buffer space (%#x) - won't do anything\n",
1872 pStreamShared->u8SD, cbStreamFree));
1873 return VINF_SUCCESS;
1874 }
1875 cbToTransfer = RT_MIN(cbToTransfer, cbStreamFree);
1876 if (cbToTransfer < PDMAudioPropsFrameSize(&pStreamShared->State.Cfg.Props))
1877 {
1878 LogFunc(("[SD%RU8] No internal DMA buffer space (%#x) - won't do anything\n", pStreamShared->u8SD, cbStreamFree));
1879 return VINF_SUCCESS;
1880 }
1881 }
1882 hdaR3StreamDoDmaOutput(pDevIns, pThis, pStreamShared, pStreamR3, cbToTransfer, RTTimeNanoTS());
1883 pStreamShared->State.cbDmaTotal += cbToTransfer;
1884# endif /* IN_RING3 */
1885 }
1886 else
1887 {
1888 /*
1889 * Transfer into the DMA bounce buffer.
1890 */
1891 LogFlowFunc(("[SD%RU8] Transfering %#x bytes to DMA bounce buffer (cbDma=%#x cbDmaTotal=%#x) (%p/%u)\n",
1892 pStreamShared->u8SD, cbToTransfer, cbDma, pStreamShared->State.cbDmaTotal, pStreamShared, pStreamShared->u8SD));
1893 uint32_t cbLeft = cbToTransfer;
1894 do
1895 {
1896 uint32_t cbChunk = 0;
1897 RTGCPHYS GCPhys = hdaStreamDmaBufGet(pStreamShared, &cbChunk);
1898
1899 bool fMustAdvanceBuffer;
1900 if (cbLeft < cbChunk)
1901 {
1902 fMustAdvanceBuffer = false;
1903 cbChunk = cbLeft;
1904 }
1905 else
1906 fMustAdvanceBuffer = true;
1907
1908 /* Read the guest data directly into the DMA bounce buffer. */
1909 int rc2 = PDMDevHlpPCIPhysRead(pDevIns, GCPhys, &pStreamShared->State.abDma[cbDma], cbChunk);
1910 AssertRC(rc2);
1911
1912 /* We update offWrite and StatBytesRead here even if we haven't moved the data
1913 to the internal DMA buffer yet, because we want the dtrace even to fire here. */
1914# ifdef VBOX_WITH_DTRACE
1915 VBOXDD_HDA_STREAM_DMA_OUT((uint32_t)pStreamShared->u8SD, cbChunk, pStreamShared->State.offWrite);
1916# endif
1917 pStreamShared->State.offWrite += cbChunk;
1918 STAM_COUNTER_ADD(&pThis->StatBytesRead, cbChunk);
1919
1920 /* advance */
1921 pStreamShared->State.offCurBdle += cbChunk;
1922 pStreamShared->State.cbDmaTotal += cbChunk;
1923 cbDma += cbChunk;
1924 pStreamShared->State.cbDma = cbDma;
1925 cbLeft -= cbChunk;
1926 Log6Func(("cbLeft=%#x cbDma=%#x cbDmaTotal=%#x offCurBdle=%#x idxCurBdle=%#x (%p/%u)\n",
1927 cbLeft, cbDma, pStreamShared->State.cbDmaTotal, pStreamShared->State.offCurBdle,
1928 pStreamShared->State.idxCurBdle, pStreamShared, pStreamShared->u8SD));
1929
1930 /* Next buffer. */
1931 bool fAdvanced = hdaStreamDoDmaMaybeCompleteBuffer(pDevIns, pThis, pStreamShared, "hdaStreamDoOnAccessDmaOutput");
1932 AssertMsgStmt(fMustAdvanceBuffer == fAdvanced, ("%d %d\n", fMustAdvanceBuffer, fAdvanced), rc = VERR_INTERNAL_ERROR_3);
1933 } while (cbLeft > 0);
1934
1935 /*
1936 * Advance LPIB and update the last transfer time (for WALCLK).
1937 */
1938 pStreamShared->State.tsTransferLast = tsNow;
1939 hdaStreamSetPositionAdd(pStreamShared, pDevIns, pThis, cbToTransfer - cbLeft);
1940 }
1941
1942# ifdef VBOX_STRICT
1943 uint32_t idxSched = pStreamShared->State.idxSchedule;
1944 AssertStmt(idxSched < RT_MIN(RT_ELEMENTS(pStreamShared->State.aSchedule), pStreamShared->State.cSchedule), idxSched = 0);
1945 uint32_t const cbPeriod = pStreamShared->State.aSchedule[idxSched].cbPeriod;
1946 AssertMsg(pStreamShared->State.cbDmaTotal < cbPeriod, ("%#x vs %#x\n", pStreamShared->State.cbDmaTotal, cbPeriod));
1947# endif
1948
1949 STAM_REL_COUNTER_INC(&pThis->StatAccessDmaOutput);
1950 return rc;
1951}
1952
1953
1954/**
1955 * Consider doing DMA output transfer on LPIB/WALCLK register access.
1956 *
1957 * @returns VINF_SUCCESS or VINF_IOM_R3_MMIO_READ.
1958 * @param pDevIns The device instance.
1959 * @param pThis The shared instance data.
1960 * @param pStreamShared The shared stream data.
1961 * @param tsNow The current time on the timer clock. Used to do the
1962 * calculation.
1963 */
1964VBOXSTRICTRC hdaStreamMaybeDoOnAccessDmaOutput(PPDMDEVINS pDevIns, PHDASTATE pThis, PHDASTREAM pStreamShared, uint64_t tsNow)
1965{
1966 Assert(pStreamShared->State.fRunning); /* caller should check this */
1967
1968 /*
1969 * Calculate where the DMA engine should be according to the clock, if we can.
1970 */
1971 uint32_t const cbFrame = PDMAudioPropsFrameSize(&pStreamShared->State.Cfg.Props);
1972 uint32_t const cbPeriod = pStreamShared->State.cbCurDmaPeriod;
1973 if (cbPeriod > cbFrame)
1974 {
1975 AssertMsg(pStreamShared->State.cbDmaTotal < cbPeriod, ("%#x vs %#x\n", pStreamShared->State.cbDmaTotal, cbPeriod));
1976 uint64_t const tsTransferNext = pStreamShared->State.tsTransferNext;
1977 uint32_t cbFuture;
1978 if (tsNow < tsTransferNext)
1979 {
1980 /** @todo ASSUMES nanosecond clock ticks, need to make this
1981 * resolution independent. */
1982 cbFuture = PDMAudioPropsNanoToBytes(&pStreamShared->State.Cfg.Props, tsTransferNext - tsNow);
1983 cbFuture = RT_MIN(cbFuture, cbPeriod - cbFrame);
1984 }
1985 else
1986 {
1987 /* We've hit/overshot the timer deadline. Return to ring-3 if we're
1988 not already there to increase the chance that we'll help expidite
1989 the timer. If we're already in ring-3, do all but the last frame. */
1990# ifndef IN_RING3
1991 LogFunc(("[SD%RU8] DMA period expired: tsNow=%RU64 >= tsTransferNext=%RU64 -> VINF_IOM_R3_MMIO_READ\n",
1992 tsNow, tsTransferNext));
1993 return VINF_IOM_R3_MMIO_READ;
1994# else
1995 cbFuture = cbPeriod - cbFrame;
1996 LogFunc(("[SD%RU8] DMA period expired: tsNow=%RU64 >= tsTransferNext=%RU64 -> cbFuture=%#x (cbPeriod=%#x - cbFrame=%#x)\n",
1997 tsNow, tsTransferNext, cbFuture, cbPeriod, cbFrame));
1998# endif
1999 }
2000 uint32_t const offNow = PDMAudioPropsFloorBytesToFrame(&pStreamShared->State.Cfg.Props, cbPeriod - cbFuture);
2001
2002 /*
2003 * Should we transfer a little? Minimum is 64 bytes (semi-random,
2004 * suspect real hardware might be doing some cache aligned stuff,
2005 * which might soon get complicated if you take unaligned buffers
2006 * into consideration and which cache line size (128 bytes is just
2007 * as likely as 64 or 32 bytes)).
2008 */
2009 uint32_t cbDmaTotal = pStreamShared->State.cbDmaTotal;
2010 if (cbDmaTotal + 64 <= offNow)
2011 {
2012# ifdef LOG_ENABLED
2013 uint32_t const uOldLpib = HDA_STREAM_REG(pThis, CBL, pStreamShared->u8SD);
2014# endif
2015 VBOXSTRICTRC rcStrict = hdaStreamDoOnAccessDmaOutput(pDevIns, pThis, pStreamShared, tsNow, offNow - cbDmaTotal);
2016 LogFlowFunc(("[SD%RU8] LPIB=%#RX32 -> LPIB=%#RX32 offNow=%#x rcStrict=%Rrc\n", pStreamShared->u8SD,
2017 uOldLpib, HDA_STREAM_REG(pThis, LPIB, pStreamShared->u8SD), offNow, VBOXSTRICTRC_VAL(rcStrict) ));
2018 return rcStrict;
2019 }
2020
2021 /*
2022 * Do nothing.
2023 */
2024 LogFlowFunc(("[SD%RU8] Skipping DMA transfer: cbDmaTotal=%#x offNow=%#x\n", pStreamShared->u8SD, cbDmaTotal, offNow));
2025 }
2026 else
2027 LogFunc(("[SD%RU8] cbPeriod=%#x <= cbFrame=%#x\n", pStreamShared->u8SD, cbPeriod, cbFrame));
2028 return VINF_SUCCESS;
2029}
2030
2031#endif /* VBOX_HDA_WITH_ON_REG_ACCESS_DMA */
2032#ifdef IN_RING3
2033
2034/**
2035 * Output streams: Pushes data to the mixer.
2036 *
2037 * @param pStreamShared HDA stream to update (shared bits).
2038 * @param pStreamR3 HDA stream to update (ring-3 bits).
2039 * @param pSink The mixer sink to push to.
2040 * @param nsNow The current RTTimeNanoTS() value.
2041 */
2042static void hdaR3StreamPushToMixer(PHDASTREAM pStreamShared, PHDASTREAMR3 pStreamR3, PAUDMIXSINK pSink, uint64_t nsNow)
2043{
2044# ifdef LOG_ENABLED
2045 uint64_t const offReadOld = pStreamShared->State.offRead;
2046# endif
2047 pStreamShared->State.offRead = AudioMixerSinkTransferFromCircBuf(pSink,
2048 pStreamR3->State.pCircBuf,
2049 pStreamShared->State.offRead,
2050 pStreamR3->u8SD,
2051 pStreamR3->Dbg.Runtime.fEnabled
2052 ? pStreamR3->Dbg.Runtime.pFileStream : NULL);
2053
2054 Assert(nsNow >= pStreamShared->State.tsLastReadNs);
2055 Log3Func(("[SD%RU8] nsDeltaLastRead=%RI64 transferred=%#RX64 bytes -> @%#RX64\n", pStreamR3->u8SD,
2056 nsNow - pStreamShared->State.tsLastReadNs, pStreamShared->State.offRead - offReadOld, pStreamShared->State.offRead));
2057 RT_NOREF(pStreamShared, nsNow);
2058
2059 /* Update buffer stats. */
2060 pStreamR3->State.StatDmaBufUsed = (uint32_t)RTCircBufUsed(pStreamR3->State.pCircBuf);
2061}
2062
2063
2064/**
2065 * Deals with a DMA buffer overrun.
2066 *
2067 * Makes sure we return with @a cbNeeded bytes of free space in pCircBuf.
2068 *
2069 * @returns Number of bytes free in the internal DMA buffer.
2070 * @param pStreamShared The shared data for the HDA stream.
2071 * @param pStreamR3 The ring-3 data for the HDA stream.
2072 * @param pSink The mixer sink (valid).
2073 * @param cbNeeded How much space we need (in bytes).
2074 * @param nsNow Current RTNanoTimeTS() timestamp.
2075 * @param cbStreamFree The current amount of free buffer space.
2076 * @param pszCaller The caller (for logging).
2077 */
2078static uint32_t hdaR3StreamHandleDmaBufferOverrun(PHDASTREAM pStreamShared, PHDASTREAMR3 pStreamR3, PAUDMIXSINK pSink,
2079 uint32_t cbNeeded, uint64_t nsNow,
2080 const char *pszCaller, uint32_t const cbStreamFree)
2081{
2082 STAM_REL_COUNTER_INC(&pStreamR3->State.StatDmaFlowProblems);
2083 Log(("%s: Warning! Stream #%u has insufficient space free: %#x bytes, need %#x. Will try move data out of the buffer...\n",
2084 pszCaller, pStreamShared->u8SD, cbStreamFree, cbNeeded));
2085 RT_NOREF(pszCaller, cbStreamFree);
2086
2087 int rc = AudioMixerSinkTryLock(pSink);
2088 if (RT_SUCCESS(rc))
2089 {
2090 hdaR3StreamPushToMixer(pStreamShared, pStreamR3, pSink, nsNow);
2091 AudioMixerSinkUpdate(pSink, 0, 0);
2092 AudioMixerSinkUnlock(pSink);
2093 }
2094 else
2095 RTThreadYield();
2096
2097 uint32_t const cbRet = hdaR3StreamGetFree(pStreamR3);
2098 Log(("%s: Gained %u bytes.\n", pszCaller, cbRet - cbStreamFree));
2099 if (cbRet >= cbNeeded)
2100 return cbRet;
2101
2102 /*
2103 * Unable to make sufficient space. Drop the whole buffer content.
2104 *
2105 * This is needed in order to keep the device emulation running at a
2106 * constant rate, at the cost of losing valid (but too much) data.
2107 */
2108 STAM_REL_COUNTER_INC(&pStreamR3->State.StatDmaFlowErrors);
2109 LogRel2(("HDA: Warning: Hit stream #%RU8 overflow, dropping %u bytes of audio data (%s)\n",
2110 pStreamShared->u8SD, hdaR3StreamGetUsed(pStreamR3), pszCaller));
2111# ifdef HDA_STRICT
2112 AssertMsgFailed(("Hit stream #%RU8 overflow -- timing bug?\n", pStreamShared->u8SD));
2113# endif
2114/**
2115 *
2116 * @todo r=bird: I don't think RTCircBufReset is entirely safe w/o
2117 * owning the AIO lock. See the note in the documentation about it not being
2118 * multi-threading aware (safe). Wish I'd verified this code much earlier.
2119 * Sigh^3!
2120 *
2121 */
2122 RTCircBufReset(pStreamR3->State.pCircBuf);
2123 pStreamShared->State.offWrite = 0;
2124 pStreamShared->State.offRead = 0;
2125 return hdaR3StreamGetFree(pStreamR3);
2126}
2127
2128
2129# ifdef VBOX_HDA_WITH_ON_REG_ACCESS_DMA
2130/**
2131 * Flushes the DMA bounce buffer content to the internal DMA buffer.
2132 *
2133 * @param pStreamShared The shared data of the stream to have its DMA bounce
2134 * buffer flushed.
2135 * @param pStreamR3 The ring-3 stream data for same.
2136 */
2137static void hdaR3StreamFlushDmaBounceBufferOutput(PHDASTREAM pStreamShared, PHDASTREAMR3 pStreamR3)
2138{
2139 uint32_t cbDma = pStreamShared->State.cbDma;
2140 LogFlowFunc(("cbDma=%#x\n", cbDma));
2141 if (cbDma)
2142 {
2143 AssertReturnVoid(cbDma <= sizeof(pStreamShared->State.abDma));
2144 PRTCIRCBUF const pCircBuf = pStreamR3->State.pCircBuf;
2145 if (pCircBuf)
2146 {
2147 uint32_t offDma = 0;
2148 while (offDma < cbDma)
2149 {
2150 uint32_t const cbSrcLeft = cbDma - offDma;
2151
2152 /*
2153 * Grab a chunk of the internal DMA buffer.
2154 */
2155 void *pvBufDst = NULL;
2156 size_t cbBufDst = 0;
2157 RTCircBufAcquireWriteBlock(pCircBuf, cbSrcLeft, &pvBufDst, &cbBufDst);
2158 if (cbBufDst > 0)
2159 { /* likely */ }
2160 else
2161 {
2162 /* We've got buffering trouble. */
2163 RTCircBufReleaseWriteBlock(pCircBuf, 0);
2164
2165 PAUDMIXSINK pSink = pStreamR3->pMixSink ? pStreamR3->pMixSink->pMixSink : NULL;
2166 if (pSink)
2167 hdaR3StreamHandleDmaBufferOverrun(pStreamShared, pStreamR3, pSink, cbSrcLeft, RTTimeNanoTS(),
2168 "hdaR3StreamFlushDmaBounceBufferOutput", 0 /*cbStreamFree*/);
2169 else
2170 {
2171 LogFunc(("Stream #%u has no sink. Dropping the rest of the data\n", pStreamR3->u8SD));
2172 break;
2173 }
2174
2175 RTCircBufAcquireWriteBlock(pCircBuf, cbSrcLeft, &pvBufDst, &cbBufDst);
2176 AssertBreakStmt(cbBufDst, RTCircBufReleaseWriteBlock(pCircBuf, 0));
2177 }
2178
2179 /*
2180 * Copy the samples into it and write it to the debug file if open.
2181 *
2182 * We do not fire the dtrace probe here nor update offRead as that was
2183 * done already (not sure that was a good idea?).
2184 */
2185 memcpy(pvBufDst, &pStreamShared->State.abDma[offDma], cbBufDst);
2186
2187 if (RT_LIKELY(!pStreamR3->Dbg.Runtime.pFileDMARaw))
2188 { /* likely */ }
2189 else
2190 AudioHlpFileWrite(pStreamR3->Dbg.Runtime.pFileDMARaw, pvBufDst, cbBufDst);
2191
2192 RTCircBufReleaseWriteBlock(pCircBuf, cbBufDst);
2193
2194 offDma += (uint32_t)cbBufDst;
2195 }
2196 }
2197
2198 /*
2199 * Mark the buffer empty.
2200 */
2201 pStreamShared->State.cbDma = 0;
2202 }
2203}
2204# endif /* VBOX_HDA_WITH_ON_REG_ACCESS_DMA */
2205
2206
2207/**
2208 * The stream's main function when called by the timer.
2209 *
2210 * @note This function also will be called without timer invocation when
2211 * starting (enabling) the stream to minimize startup latency.
2212 *
2213 * @returns Current timer time if the timer is enabled, otherwise zero.
2214 * @param pDevIns The device instance.
2215 * @param pThis The shared HDA device state.
2216 * @param pThisCC The ring-3 HDA device state.
2217 * @param pStreamShared HDA stream to update (shared bits).
2218 * @param pStreamR3 HDA stream to update (ring-3 bits).
2219 */
2220uint64_t hdaR3StreamTimerMain(PPDMDEVINS pDevIns, PHDASTATE pThis, PHDASTATER3 pThisCC,
2221 PHDASTREAM pStreamShared, PHDASTREAMR3 pStreamR3)
2222{
2223 Assert(PDMDevHlpCritSectIsOwner(pDevIns, &pThis->CritSect));
2224 Assert(PDMDevHlpTimerIsLockOwner(pDevIns, pStreamShared->hTimer));
2225
2226 /* Do the work: */
2227 hdaR3StreamUpdateDma(pDevIns, pThis, pThisCC, pStreamShared, pStreamR3);
2228
2229 /* Re-arm the timer if the sink is still active: */
2230 if ( pStreamShared->State.fRunning
2231 && pStreamR3->pMixSink
2232 && AudioMixerSinkIsActive(pStreamR3->pMixSink->pMixSink))
2233 {
2234 /* Advance the schduling: */
2235 uint32_t idxSched = pStreamShared->State.idxSchedule;
2236 AssertStmt(idxSched < RT_ELEMENTS(pStreamShared->State.aSchedule), idxSched = 0);
2237 uint32_t idxLoop = pStreamShared->State.idxScheduleLoop + 1;
2238 if (idxLoop >= pStreamShared->State.aSchedule[idxSched].cLoops)
2239 {
2240 idxSched += 1;
2241 if ( idxSched >= pStreamShared->State.cSchedule
2242 || idxSched >= RT_ELEMENTS(pStreamShared->State.aSchedule) /*paranoia^2*/)
2243 {
2244 idxSched = pStreamShared->State.cSchedulePrologue;
2245 AssertStmt(idxSched < RT_ELEMENTS(pStreamShared->State.aSchedule), idxSched = 0);
2246 }
2247 pStreamShared->State.idxSchedule = idxSched;
2248 idxLoop = 0;
2249 }
2250 pStreamShared->State.idxScheduleLoop = (uint16_t)idxLoop;
2251
2252 /* Do the actual timer re-arming. */
2253 uint64_t const tsNow = PDMDevHlpTimerGet(pDevIns, pStreamShared->hTimer); /* (For virtual sync this remains the same for the whole callout IIRC) */
2254 uint64_t const tsTransferNext = tsNow + pStreamShared->State.aSchedule[idxSched].cPeriodTicks;
2255 Log3Func(("[SD%RU8] fSinkActive=true, tsTransferNext=%RU64 (in %RU64)\n",
2256 pStreamShared->u8SD, tsTransferNext, tsTransferNext - tsNow));
2257 int rc = PDMDevHlpTimerSet(pDevIns, pStreamShared->hTimer, tsTransferNext);
2258 AssertRC(rc);
2259
2260 /* Some legacy stuff: */
2261 pStreamShared->State.tsTransferNext = tsTransferNext;
2262 pStreamShared->State.cbCurDmaPeriod = pStreamShared->State.aSchedule[idxSched].cbPeriod;
2263
2264 return tsNow;
2265 }
2266
2267 Log3Func(("[SD%RU8] fSinkActive=false\n", pStreamShared->u8SD));
2268 return 0;
2269}
2270
2271
2272/**
2273 * Updates a HDA stream by doing DMA transfers.
2274 *
2275 * Will do mixer transfers too to try fix an overrun/underrun situation.
2276 *
2277 * The host sink(s) set the overall pace (bird: no it doesn't, the DMA timer
2278 * does - we just hope like heck it matches the speed at which the *backend*
2279 * host audio driver processes samples).
2280 *
2281 * @param pDevIns The device instance.
2282 * @param pThis The shared HDA device state.
2283 * @param pThisCC The ring-3 HDA device state.
2284 * @param pStreamShared HDA stream to update (shared bits).
2285 * @param pStreamR3 HDA stream to update (ring-3 bits).
2286 */
2287static void hdaR3StreamUpdateDma(PPDMDEVINS pDevIns, PHDASTATE pThis, PHDASTATER3 pThisCC,
2288 PHDASTREAM pStreamShared, PHDASTREAMR3 pStreamR3)
2289{
2290 RT_NOREF(pThisCC);
2291 int rc2;
2292
2293 /*
2294 * Make sure we're running and got an active mixer sink.
2295 */
2296 if (RT_LIKELY(pStreamShared->State.fRunning))
2297 { /* likely */ }
2298 else
2299 return;
2300
2301 PAUDMIXSINK pSink = NULL;
2302 if (pStreamR3->pMixSink)
2303 pSink = pStreamR3->pMixSink->pMixSink;
2304 if (RT_LIKELY(AudioMixerSinkIsActive(pSink)))
2305 { /* likely */ }
2306 else
2307 return;
2308
2309 /*
2310 * Get scheduling info common to both input and output streams.
2311 */
2312 const uint64_t tsNowNs = RTTimeNanoTS();
2313 uint32_t idxSched = pStreamShared->State.idxSchedule;
2314 AssertStmt(idxSched < RT_MIN(RT_ELEMENTS(pStreamShared->State.aSchedule), pStreamShared->State.cSchedule), idxSched = 0);
2315 uint32_t cbPeriod = pStreamShared->State.aSchedule[idxSched].cbPeriod;
2316
2317 /*
2318 * Output streams (SDO).
2319 */
2320 if (hdaGetDirFromSD(pStreamShared->u8SD) == PDMAUDIODIR_OUT)
2321 {
2322# ifdef VBOX_HDA_WITH_ON_REG_ACCESS_DMA
2323 /* Subtract already transferred bytes and flush the DMA bounce buffer. */
2324 uint32_t cbDmaTotal = pStreamShared->State.cbDmaTotal;
2325 if (cbDmaTotal > 0)
2326 {
2327 AssertStmt(cbDmaTotal < cbPeriod, cbDmaTotal = cbPeriod);
2328 cbPeriod -= cbDmaTotal;
2329 pStreamShared->State.cbDmaTotal = 0;
2330 hdaR3StreamFlushDmaBounceBufferOutput(pStreamShared, pStreamR3);
2331 }
2332 else
2333 Assert(pStreamShared->State.cbDma == 0);
2334# endif
2335
2336 /*
2337 * Check how much room we have in our DMA buffer. There should be at
2338 * least one period worth of space there or we're in an overflow situation.
2339 */
2340 uint32_t cbStreamFree = hdaR3StreamGetFree(pStreamR3);
2341 if (cbStreamFree >= cbPeriod)
2342 { /* likely */ }
2343 else
2344 cbStreamFree = hdaR3StreamHandleDmaBufferOverrun(pStreamShared, pStreamR3, pSink, cbPeriod, tsNowNs,
2345 "hdaR3StreamUpdateDma", cbStreamFree);
2346
2347 /*
2348 * Do the DMA transfer.
2349 */
2350 uint64_t const offWriteBefore = pStreamShared->State.offWrite;
2351 hdaR3StreamDoDmaOutput(pDevIns, pThis, pStreamShared, pStreamR3, RT_MIN(cbStreamFree, cbPeriod), tsNowNs);
2352
2353 /*
2354 * Should we push data to down thru the mixer to and to the host drivers?
2355 */
2356 bool fKickAioThread = pStreamShared->State.offWrite > offWriteBefore
2357 || hdaR3StreamGetFree(pStreamR3) < pStreamShared->State.cbAvgTransfer * 2;
2358
2359 Log3Func(("msDelta=%RU64 (vs %u) cbStreamFree=%#x (vs %#x) => fKickAioThread=%RTbool\n",
2360 (tsNowNs - pStreamShared->State.tsLastReadNs) / RT_NS_1MS,
2361 pStreamShared->State.Cfg.Device.cMsSchedulingHint, cbStreamFree,
2362 pStreamShared->State.cbAvgTransfer * 2, fKickAioThread));
2363
2364 if (fKickAioThread)
2365 {
2366 /* Notify the async I/O worker thread that there's work to do. */
2367 Log5Func(("Notifying AIO thread\n"));
2368 rc2 = AudioMixerSinkSignalUpdateJob(pSink);
2369 AssertRC(rc2);
2370 /* Update last read timestamp for logging/debugging. */
2371 pStreamShared->State.tsLastReadNs = tsNowNs;
2372 }
2373 }
2374 /*
2375 * Input stream (SDI).
2376 */
2377 else
2378 {
2379 Assert(hdaGetDirFromSD(pStreamShared->u8SD) == PDMAUDIODIR_IN);
2380
2381 /*
2382 * See how much data we've got buffered...
2383 */
2384 bool fWriteSilence = false;
2385 uint32_t cbStreamUsed = hdaR3StreamGetUsed(pStreamR3);
2386 if (pStreamShared->State.fInputPreBuffered && cbStreamUsed >= cbPeriod)
2387 { /*likely*/ }
2388 /*
2389 * Because it may take a while for the input stream to get going (at
2390 * least with pulseaudio), we feed the guest silence till we've
2391 * pre-buffer a reasonable amount of audio.
2392 */
2393 else if (!pStreamShared->State.fInputPreBuffered)
2394 {
2395 if (cbStreamUsed < pStreamShared->State.cbInputPreBuffer)
2396 {
2397 Log3(("hdaR3StreamUpdateDma: Pre-buffering (got %#x out of %#x bytes)...\n",
2398 cbStreamUsed, pStreamShared->State.cbInputPreBuffer));
2399 fWriteSilence = true;
2400 }
2401 else
2402 {
2403 Log3(("hdaR3StreamUpdateDma: Completed pre-buffering (got %#x, needed %#x bytes).\n",
2404 cbStreamUsed, pStreamShared->State.cbInputPreBuffer));
2405 pStreamShared->State.fInputPreBuffered = true;
2406 fWriteSilence = true; /* For now, just do the most conservative thing. */
2407 }
2408 cbStreamUsed = cbPeriod;
2409 }
2410 /*
2411 * When we're low on data, we must really try fetch some ourselves
2412 * as buffer underruns must not happen.
2413 */
2414 else
2415 {
2416 /** @todo We're ending up here to frequently with pulse audio at least (just
2417 * watch the stream stats in the statistcs viewer, and way to often we
2418 * have to inject silence bytes. I suspect part of the problem is
2419 * that the HDA device require a much better latency than what the
2420 * pulse audio is configured for by default (10 ms vs 150ms). */
2421 STAM_REL_COUNTER_INC(&pStreamR3->State.StatDmaFlowProblems);
2422 Log(("hdaR3StreamUpdateDma: Warning! Stream #%u has insufficient data available: %u bytes, need %u. Will try move pull more data into the buffer...\n",
2423 pStreamShared->u8SD, cbStreamUsed, cbPeriod));
2424 int rc = AudioMixerSinkTryLock(pSink);
2425 if (RT_SUCCESS(rc))
2426 {
2427 AudioMixerSinkUpdate(pSink, cbStreamUsed, cbPeriod);
2428 hdaR3StreamPullFromMixer(pStreamShared, pStreamR3, pSink);
2429 AudioMixerSinkUnlock(pSink);
2430 }
2431 else
2432 RTThreadYield();
2433 Log(("hdaR3StreamUpdateDma: Gained %u bytes.\n", hdaR3StreamGetUsed(pStreamR3) - cbStreamUsed));
2434 cbStreamUsed = hdaR3StreamGetUsed(pStreamR3);
2435 if (cbStreamUsed < cbPeriod)
2436 {
2437 /* Unable to find sufficient input data by simple prodding.
2438 In order to keep a constant byte stream following thru the DMA
2439 engine into the guest, we will try again and then fall back on
2440 filling the gap with silence. */
2441 uint32_t cbSilence = 0;
2442 do
2443 {
2444 AudioMixerSinkLock(pSink);
2445
2446 cbStreamUsed = hdaR3StreamGetUsed(pStreamR3);
2447 if (cbStreamUsed < cbPeriod)
2448 {
2449 hdaR3StreamPullFromMixer(pStreamShared, pStreamR3, pSink);
2450 cbStreamUsed = hdaR3StreamGetUsed(pStreamR3);
2451 while (cbStreamUsed < cbPeriod)
2452 {
2453 void *pvDstBuf;
2454 size_t cbDstBuf;
2455 RTCircBufAcquireWriteBlock(pStreamR3->State.pCircBuf, cbPeriod - cbStreamUsed,
2456 &pvDstBuf, &cbDstBuf);
2457 RT_BZERO(pvDstBuf, cbDstBuf);
2458 RTCircBufReleaseWriteBlock(pStreamR3->State.pCircBuf, cbDstBuf);
2459 cbSilence += (uint32_t)cbDstBuf;
2460 cbStreamUsed += (uint32_t)cbDstBuf;
2461 }
2462 }
2463
2464 AudioMixerSinkUnlock(pSink);
2465 } while (cbStreamUsed < cbPeriod);
2466 if (cbSilence > 0)
2467 {
2468 STAM_REL_COUNTER_INC(&pStreamR3->State.StatDmaFlowErrors);
2469 STAM_REL_COUNTER_ADD(&pStreamR3->State.StatDmaFlowErrorBytes, cbSilence);
2470 LogRel2(("HDA: Warning: Stream #%RU8 underrun, added %u bytes of silence (%u us)\n", pStreamShared->u8SD,
2471 cbSilence, PDMAudioPropsBytesToMicro(&pStreamShared->State.Cfg.Props, cbSilence)));
2472 }
2473 }
2474 }
2475
2476 /*
2477 * Do the DMA'ing.
2478 */
2479 if (cbStreamUsed)
2480 hdaR3StreamDoDmaInput(pDevIns, pThis, pStreamShared, pStreamR3,
2481 RT_MIN(cbStreamUsed, cbPeriod), fWriteSilence, tsNowNs);
2482
2483 /*
2484 * We should always kick the AIO thread.
2485 */
2486 /** @todo This isn't entirely ideal. If we get into an underrun situation,
2487 * we ideally want the AIO thread to run right before the DMA timer
2488 * rather than right after it ran. */
2489 Log5Func(("Notifying AIO thread\n"));
2490 rc2 = AudioMixerSinkSignalUpdateJob(pSink);
2491 AssertRC(rc2);
2492 pStreamShared->State.tsLastReadNs = tsNowNs;
2493 }
2494}
2495
2496
2497/**
2498 * @callback_method_impl{FNAUDMIXSINKUPDATE}
2499 *
2500 * For output streams this moves data from the internal DMA buffer (in which
2501 * hdaR3StreamUpdateDma put it), thru the mixer and to the various backend audio
2502 * devices.
2503 *
2504 * For input streams this pulls data from the backend audio device(s), thru the
2505 * mixer and puts it in the internal DMA buffer ready for hdaR3StreamUpdateDma
2506 * to pump into guest memory.
2507 */
2508DECLCALLBACK(void) hdaR3StreamUpdateAsyncIoJob(PPDMDEVINS pDevIns, PAUDMIXSINK pSink, void *pvUser)
2509{
2510 PHDASTATE const pThis = PDMDEVINS_2_DATA(pDevIns, PHDASTATE);
2511 PHDASTATER3 const pThisCC = PDMDEVINS_2_DATA_CC(pDevIns, PHDASTATER3);
2512 PHDASTREAMR3 const pStreamR3 = (PHDASTREAMR3)pvUser;
2513 PHDASTREAM const pStreamShared = &pThis->aStreams[pStreamR3 - &pThisCC->aStreams[0]];
2514 Assert(pStreamR3 - &pThisCC->aStreams[0] == pStreamR3->u8SD);
2515 Assert(pStreamShared->u8SD == pStreamR3->u8SD);
2516 RT_NOREF(pSink);
2517
2518 /*
2519 * Make sure we haven't change sink and that it's still active (it
2520 * should be or we wouldn't have been called).
2521 */
2522 AssertReturnVoid(pStreamR3->pMixSink && pSink == pStreamR3->pMixSink->pMixSink);
2523 AssertReturnVoid(AudioMixerSinkIsActive(pSink));
2524
2525 /*
2526 * Output streams (SDO).
2527 */
2528 if (hdaGetDirFromSD(pStreamShared->u8SD) == PDMAUDIODIR_OUT)
2529 hdaR3StreamPushToMixer(pStreamShared, pStreamR3, pSink, RTTimeNanoTS());
2530 /*
2531 * Input stream (SDI).
2532 */
2533 else
2534 {
2535 Assert(hdaGetDirFromSD(pStreamShared->u8SD) == PDMAUDIODIR_IN);
2536 hdaR3StreamPullFromMixer(pStreamShared, pStreamR3, pSink);
2537 }
2538}
2539
2540#endif /* IN_RING3 */
2541
注意: 瀏覽 TracBrowser 來幫助您使用儲存庫瀏覽器

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