VirtualBox

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

最後變更 在這個檔案從89382是 89379,由 vboxsync 提交於 4 年 前

Audio: Removed PDMAUDIOSTREAMCFG::enmLayout and PDMAUDIOSTREAMLAYOUT. bugref:9890

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

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