VirtualBox

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

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

DevHda: Made VBOX_WITH_AUDIO_HDA_ASYNC_IO non-optional. bugref:9890

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

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