VirtualBox

source: vbox/trunk/src/VBox/Devices/Audio/HDAStream.cpp@ 86405

Last change on this file since 86405 was 83298, checked in by vboxsync, 5 years ago

Audio/HDA: Added some more stream ID checks.

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 75.6 KB
Line 
1/* $Id: HDAStream.cpp 83298 2020-03-16 13:10:10Z vboxsync $ */
2/** @file
3 * HDAStream.cpp - Stream functions for HD Audio.
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
32#include "DrvAudio.h"
33
34#include "DevHDA.h"
35#include "HDAStream.h"
36
37#ifdef IN_RING3 /* whole file */
38
39
40/*********************************************************************************************************************************
41* Internal Functions *
42*********************************************************************************************************************************/
43static void hdaR3StreamSetPosition(PHDASTREAM pStreamShared, PPDMDEVINS pDevIns, PHDASTATE pThis, uint32_t u32LPIB);
44
45static int hdaR3StreamAsyncIODestroy(PHDASTREAMR3 pStreamR3);
46static int hdaR3StreamAsyncIONotify(PHDASTREAMR3 pStreamR3);
47
48
49
50/**
51 * Creates an HDA stream.
52 *
53 * @returns IPRT status code.
54 * @param pStreamShared The HDA stream to construct - shared bits.
55 * @param pStreamR3 The HDA stream to construct - ring-3 bits.
56 * @param pThis The shared HDA device instance.
57 * @param pThisCC The ring-3 HDA device instance.
58 * @param uSD Stream descriptor number to assign.
59 */
60int hdaR3StreamConstruct(PHDASTREAM pStreamShared, PHDASTREAMR3 pStreamR3, PHDASTATE pThis, PHDASTATER3 pThisCC, uint8_t uSD)
61{
62 int rc;
63
64 pStreamR3->u8SD = uSD;
65 pStreamShared->u8SD = uSD;
66 pStreamR3->pMixSink = NULL;
67 pStreamR3->pHDAStateShared = pThis;
68 pStreamR3->pHDAStateR3 = pThisCC;
69 Assert(pStreamShared->hTimer != NIL_TMTIMERHANDLE); /* hdaR3Construct initalized this one already. */
70
71 pStreamShared->State.fInReset = false;
72 pStreamShared->State.fRunning = false;
73#ifdef HDA_USE_DMA_ACCESS_HANDLER
74 RTListInit(&pStreamR3->State.lstDMAHandlers);
75#endif
76
77# ifdef VBOX_WITH_AUDIO_HDA_ASYNC_IO
78 rc = RTCritSectInit(&pStreamR3->CritSect);
79 AssertRCReturn(rc, rc);
80# endif
81
82 rc = hdaR3StreamPeriodCreate(&pStreamShared->State.Period);
83 AssertRCReturn(rc, rc);
84
85 pStreamShared->State.tsLastUpdateNs = 0;
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 = DrvAudioHlpFileNameGet(szPath, sizeof(szPath), pThisCC->Dbg.pszOutPath, szFile,
119 0 /* uInst */, PDMAUDIOFILETYPE_WAV, PDMAUDIOFILENAME_FLAGS_NONE);
120 AssertRC(rc2);
121
122 rc2 = DrvAudioHlpFileCreate(PDMAUDIOFILETYPE_WAV, szPath, PDMAUDIOFILE_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 = DrvAudioHlpFileNameGet(szPath, sizeof(szPath), pThisCC->Dbg.pszOutPath, szFile,
132 0 /* uInst */, PDMAUDIOFILETYPE_WAV, PDMAUDIOFILENAME_FLAGS_NONE);
133 AssertRC(rc2);
134
135 rc2 = DrvAudioHlpFileCreate(PDMAUDIOFILETYPE_WAV, szPath, PDMAUDIOFILE_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 = DrvAudioHlpFileNameGet(szPath, sizeof(szPath), pThisCC->Dbg.pszOutPath, szFile,
145 0 /* uInst */, PDMAUDIOFILETYPE_WAV, PDMAUDIOFILENAME_FLAGS_NONE);
146 AssertRC(rc2);
147
148 rc2 = DrvAudioHlpFileCreate(PDMAUDIOFILETYPE_WAV, szPath, PDMAUDIOFILE_FLAGS_NONE, &pStreamR3->Dbg.Runtime.pFileDMAMapped);
149 AssertRC(rc2);
150
151 /* Delete stale debugging files from a former run. */
152 DrvAudioHlpFileDelete(pStreamR3->Dbg.Runtime.pFileStream);
153 DrvAudioHlpFileDelete(pStreamR3->Dbg.Runtime.pFileDMARaw);
154 DrvAudioHlpFileDelete(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#ifdef VBOX_WITH_AUDIO_HDA_ASYNC_IO
175 rc2 = hdaR3StreamAsyncIODestroy(pStreamR3);
176 AssertRC(rc2);
177#endif
178
179# ifdef VBOX_WITH_AUDIO_HDA_ASYNC_IO
180 if (RTCritSectIsInitialized(&pStreamR3->CritSect))
181 {
182 rc2 = RTCritSectDelete(&pStreamR3->CritSect);
183 AssertRC(rc2);
184 }
185# endif
186
187 if (pStreamR3->State.pCircBuf)
188 {
189 RTCircBufDestroy(pStreamR3->State.pCircBuf);
190 pStreamR3->State.pCircBuf = NULL;
191 }
192
193 hdaR3StreamPeriodDestroy(&pStreamShared->State.Period);
194
195#ifdef DEBUG
196 if (RTCritSectIsInitialized(&pStreamR3->Dbg.CritSect))
197 {
198 rc2 = RTCritSectDelete(&pStreamR3->Dbg.CritSect);
199 AssertRC(rc2);
200 }
201#endif
202
203 if (pStreamR3->Dbg.Runtime.fEnabled)
204 {
205 DrvAudioHlpFileDestroy(pStreamR3->Dbg.Runtime.pFileStream);
206 pStreamR3->Dbg.Runtime.pFileStream = NULL;
207
208 DrvAudioHlpFileDestroy(pStreamR3->Dbg.Runtime.pFileDMARaw);
209 pStreamR3->Dbg.Runtime.pFileDMARaw = NULL;
210
211 DrvAudioHlpFileDestroy(pStreamR3->Dbg.Runtime.pFileDMAMapped);
212 pStreamR3->Dbg.Runtime.pFileDMAMapped = NULL;
213 }
214
215 LogFlowFuncLeave();
216}
217
218/**
219 * Sets up ((re-)iniitalizes) an HDA stream.
220 *
221 * @returns IPRT status code. VINF_NO_CHANGE if the stream does not need
222 * be set-up again because the stream's (hardware) parameters did
223 * not change.
224 * @param pDevIns The device instance.
225 * @param pThis The shared HDA device state (for HW register
226 * parameters).
227 * @param pStreamShared HDA stream to set up, shared portion.
228 * @param pStreamR3 HDA stream to set up, ring-3 portion.
229 * @param uSD Stream descriptor number to assign it.
230 */
231int hdaR3StreamSetUp(PPDMDEVINS pDevIns, PHDASTATE pThis, PHDASTREAM pStreamShared, PHDASTREAMR3 pStreamR3, uint8_t uSD)
232{
233 /* This must be valid all times. */
234 AssertReturn(uSD < HDA_MAX_STREAMS, VERR_INVALID_PARAMETER);
235
236 /* These member can only change on data corruption, despite what the code does further down (bird). */
237 AssertReturn(pStreamShared->u8SD == uSD, VERR_WRONG_ORDER);
238 AssertReturn(pStreamR3->u8SD == uSD, VERR_WRONG_ORDER);
239
240 const uint64_t u64BDLBase = RT_MAKE_U64(HDA_STREAM_REG(pThis, BDPL, uSD),
241 HDA_STREAM_REG(pThis, BDPU, uSD));
242 const uint16_t u16LVI = HDA_STREAM_REG(pThis, LVI, uSD);
243 const uint32_t u32CBL = HDA_STREAM_REG(pThis, CBL, uSD);
244 const uint16_t u16FIFOS = HDA_STREAM_REG(pThis, FIFOS, uSD) + 1;
245 const uint16_t u16FMT = HDA_STREAM_REG(pThis, FMT, uSD);
246
247 /* Is the bare minimum set of registers configured for the stream?
248 * If not, bail out early, as there's nothing to do here for us (yet). */
249 if ( !u64BDLBase
250 || !u16LVI
251 || !u32CBL
252 || !u16FIFOS
253 || !u16FMT)
254 {
255 LogFunc(("[SD%RU8] Registers not set up yet, skipping (re-)initialization\n", uSD));
256 return VINF_SUCCESS;
257 }
258
259 PDMAUDIOPCMPROPS Props;
260 int rc = hdaR3SDFMTToPCMProps(u16FMT, &Props);
261 if (RT_FAILURE(rc))
262 {
263 LogRel(("HDA: Warning: Format 0x%x for stream #%RU8 not supported\n", HDA_STREAM_REG(pThis, FMT, uSD), uSD));
264 return rc;
265 }
266
267 /* Reset (any former) stream map. */
268 hdaR3StreamMapReset(&pStreamR3->State.Mapping);
269
270 /*
271 * Initialize the stream mapping in any case, regardless if
272 * we support surround audio or not. This is needed to handle
273 * the supported channels within a single audio stream, e.g. mono/stereo.
274 *
275 * In other words, the stream mapping *always* knows the real
276 * number of channels in a single audio stream.
277 */
278 rc = hdaR3StreamMapInit(&pStreamR3->State.Mapping, &Props);
279 AssertRCReturn(rc, rc);
280
281 ASSERT_GUEST_LOGREL_MSG_RETURN( pStreamR3->State.Mapping.cbFrameSize > 0
282 && u32CBL % pStreamR3->State.Mapping.cbFrameSize == 0,
283 ("CBL for stream #%RU8 does not align to frame size (u32CBL=%u cbFrameSize=%u)\n",
284 uSD, u32CBL, pStreamR3->State.Mapping.cbFrameSize),
285 VERR_INVALID_PARAMETER);
286
287 /*
288 * Set the stream's timer Hz rate, based on the stream channel count.
289 * Currently this is just a rough guess and we might want to optimize this further.
290 *
291 * In any case, more channels per SDI/SDO means that we have to drive data more frequently.
292 */
293 if (pThis->uTimerHz == HDA_TIMER_HZ_DEFAULT) /* Make sure that we don't have any custom Hz rate set we want to enforce */
294 {
295 if (Props.cChannels >= 5)
296 pStreamShared->State.uTimerHz = 300;
297 else if (Props.cChannels == 4)
298 pStreamShared->State.uTimerHz = 150;
299 else
300 pStreamShared->State.uTimerHz = 100;
301 }
302 else
303 pStreamShared->State.uTimerHz = pThis->uTimerHz;
304
305#ifndef VBOX_WITH_AUDIO_HDA_51_SURROUND
306 if (Props.cChannels > 2)
307 {
308 /*
309 * When not running with surround support enabled, override the audio channel count
310 * with stereo (2) channels so that we at least can properly work with those.
311 *
312 * Note: This also involves dealing with surround setups the guest might has set up for us.
313 */
314 LogRel2(("HDA: More than stereo (2) channels are not supported (%RU8 requested), "
315 "falling back to stereo channels for stream #%RU8\n", Props.cChannels, uSD));
316 Props.cChannels = 2;
317 Props.cShift = PDMAUDIOPCMPROPS_MAKE_SHIFT_PARMS(Props.cbSample, Props.cChannels);
318 }
319#endif
320
321 /* Did some of the vital / critical parameters change?
322 * If not, we can skip a lot of the (re-)initialization and just (re-)use the existing stuff.
323 * Also, tell the caller so that further actions can be taken. */
324 if ( uSD == pStreamShared->u8SD /* paranoia OFC */
325 && u64BDLBase == pStreamShared->u64BDLBase
326 && u16LVI == pStreamShared->u16LVI
327 && u32CBL == pStreamShared->u32CBL
328 && u16FIFOS == pStreamShared->u16FIFOS
329 && u16FMT == pStreamShared->u16FMT)
330 {
331 LogFunc(("[SD%RU8] No format change, skipping (re-)initialization\n", uSD));
332 return VINF_NO_CHANGE;
333 }
334
335 pStreamShared->u8SD = uSD;
336
337 /* Update all register copies so that we later know that something has changed. */
338 pStreamShared->u64BDLBase = u64BDLBase;
339 pStreamShared->u16LVI = u16LVI;
340 pStreamShared->u32CBL = u32CBL;
341 pStreamShared->u16FIFOS = u16FIFOS;
342 pStreamShared->u16FMT = u16FMT;
343
344 PPDMAUDIOSTREAMCFG pCfg = &pStreamShared->State.Cfg;
345 pCfg->Props = Props;
346
347 /* (Re-)Allocate the stream's internal DMA buffer, based on the PCM properties we just got above. */
348 if (pStreamR3->State.pCircBuf)
349 {
350 RTCircBufDestroy(pStreamR3->State.pCircBuf);
351 pStreamR3->State.pCircBuf = NULL;
352 }
353
354 /* By default we allocate an internal buffer of 100ms. */
355 rc = RTCircBufCreate(&pStreamR3->State.pCircBuf,
356 DrvAudioHlpMilliToBytes(100 /* ms */, &pCfg->Props)); /** @todo Make this configurable. */
357 AssertRCReturn(rc, rc);
358
359 /* Set the stream's direction. */
360 pCfg->enmDir = hdaGetDirFromSD(uSD);
361
362 /* The the stream's name, based on the direction. */
363 switch (pCfg->enmDir)
364 {
365 case PDMAUDIODIR_IN:
366# ifdef VBOX_WITH_AUDIO_HDA_MIC_IN
367# error "Implement me!"
368# else
369 pCfg->u.enmSrc = PDMAUDIORECSRC_LINE;
370 pCfg->enmLayout = PDMAUDIOSTREAMLAYOUT_NON_INTERLEAVED;
371 RTStrCopy(pCfg->szName, sizeof(pCfg->szName), "Line In");
372# endif
373 break;
374
375 case PDMAUDIODIR_OUT:
376 /* Destination(s) will be set in hdaAddStreamOut(),
377 * based on the channels / stream layout. */
378 break;
379
380 default:
381 rc = VERR_NOT_SUPPORTED;
382 break;
383 }
384
385 /* Set scheduling hint (if available). */
386 if (pStreamShared->State.uTimerHz)
387 pCfg->Device.cMsSchedulingHint = 1000 /* ms */ / pStreamShared->State.uTimerHz;
388
389 LogFunc(("[SD%RU8] DMA @ 0x%x (%RU32 bytes), LVI=%RU16, FIFOS=%RU16\n",
390 uSD, pStreamShared->u64BDLBase, pStreamShared->u32CBL, pStreamShared->u16LVI, pStreamShared->u16FIFOS));
391
392 if (RT_SUCCESS(rc))
393 {
394 /* Make sure that the chosen Hz rate dividable by the stream's rate. */
395 if (pStreamShared->State.Cfg.Props.uHz % pStreamShared->State.uTimerHz != 0)
396 LogRel(("HDA: Stream timer Hz rate (%RU32) does not fit to stream #%RU8 timing (%RU32)\n",
397 pStreamShared->State.uTimerHz, uSD, pStreamShared->State.Cfg.Props.uHz));
398
399 /* Figure out how many transfer fragments we're going to use for this stream. */
400 /** @todo Use a more dynamic fragment size? */
401 uint8_t cFragments = pStreamShared->u16LVI + 1;
402 if (cFragments <= 1)
403 cFragments = 2; /* At least two fragments (BDLEs) must be present. */
404
405 /*
406 * Handle the stream's position adjustment.
407 */
408 uint32_t cfPosAdjust = 0;
409
410 LogFunc(("[SD%RU8] fPosAdjustEnabled=%RTbool, cPosAdjustFrames=%RU16\n",
411 uSD, pThis->fPosAdjustEnabled, pThis->cPosAdjustFrames));
412
413 if (pThis->fPosAdjustEnabled) /* Is the position adjustment enabled at all? */
414 {
415 HDABDLE BDLE;
416 RT_ZERO(BDLE);
417
418 int rc2 = hdaR3BDLEFetch(pDevIns, &BDLE, pStreamShared->u64BDLBase, 0 /* Entry */);
419 AssertRC(rc2);
420
421 /* Note: Do *not* check if this BDLE aligns to the stream's frame size.
422 * It can happen that this isn't the case on some guests, e.g.
423 * on Windows with a 5.1 speaker setup.
424 *
425 * The only thing which counts is that the stream's CBL value
426 * properly aligns to the stream's frame size.
427 */
428
429 /* If no custom set position adjustment is set, apply some
430 * simple heuristics to detect the appropriate position adjustment. */
431 if ( !pThis->cPosAdjustFrames
432 /* Position adjustmenet buffer *must* have the IOC bit set! */
433 && hdaR3BDLENeedsInterrupt(&BDLE))
434 {
435 /** @todo Implement / use a (dynamic) table once this gets more complicated. */
436#ifdef VBOX_WITH_INTEL_HDA
437 /* Intel ICH / PCH: 1 frame. */
438 if (BDLE.Desc.u32BufSize == (uint32_t)(1 * pStreamR3->State.Mapping.cbFrameSize))
439 {
440 cfPosAdjust = 1;
441 }
442 /* Intel Baytrail / Braswell: 32 frames. */
443 else if (BDLE.Desc.u32BufSize == (uint32_t)(32 * pStreamR3->State.Mapping.cbFrameSize))
444 {
445 cfPosAdjust = 32;
446 }
447#endif
448 }
449 else /* Go with the set default. */
450 cfPosAdjust = pThis->cPosAdjustFrames;
451
452 if (cfPosAdjust)
453 {
454 /* Also adjust the number of fragments, as the position adjustment buffer
455 * does not count as an own fragment as such.
456 *
457 * This e.g. can happen on (newer) Ubuntu guests which use
458 * 4 (IOC) + 4408 (IOC) + 4408 (IOC) + 4408 (IOC) + 4404 (= 17632) bytes,
459 * where the first buffer (4) is used as position adjustment.
460 *
461 * Only skip a fragment if the whole buffer fragment is used for
462 * position adjustment.
463 */
464 if ( (cfPosAdjust * pStreamR3->State.Mapping.cbFrameSize) == BDLE.Desc.u32BufSize
465 && cFragments)
466 {
467 cFragments--;
468 }
469
470 /* Initialize position adjustment counter. */
471 pStreamShared->State.cfPosAdjustDefault = cfPosAdjust;
472 pStreamShared->State.cfPosAdjustLeft = pStreamShared->State.cfPosAdjustDefault;
473
474 LogRel2(("HDA: Position adjustment for stream #%RU8 active (%RU32 frames)\n",
475 uSD, pStreamShared->State.cfPosAdjustDefault));
476 }
477 }
478
479 LogFunc(("[SD%RU8] cfPosAdjust=%RU32, cFragments=%RU8\n", uSD, cfPosAdjust, cFragments));
480
481 /*
482 * Set up data transfer stuff.
483 */
484
485 /* Calculate the fragment size the guest OS expects interrupt delivery at. */
486 pStreamShared->State.cbTransferSize = pStreamShared->u32CBL / cFragments;
487 Assert(pStreamShared->State.cbTransferSize);
488 Assert(pStreamShared->State.cbTransferSize % pStreamR3->State.Mapping.cbFrameSize == 0);
489 ASSERT_GUEST_LOGREL_MSG_STMT(pStreamShared->State.cbTransferSize,
490 ("Transfer size for stream #%RU8 is invalid\n", uSD), rc = VERR_INVALID_PARAMETER);
491 if (RT_SUCCESS(rc))
492 {
493 /* Calculate the bytes we need to transfer to / from the stream's DMA per iteration.
494 * This is bound to the device's Hz rate and thus to the (virtual) timing the device expects. */
495 pStreamShared->State.cbTransferChunk = (pStreamShared->State.Cfg.Props.uHz / pStreamShared->State.uTimerHz) * pStreamR3->State.Mapping.cbFrameSize;
496 Assert(pStreamShared->State.cbTransferChunk);
497 Assert(pStreamShared->State.cbTransferChunk % pStreamR3->State.Mapping.cbFrameSize == 0);
498 ASSERT_GUEST_LOGREL_MSG_STMT(pStreamShared->State.cbTransferChunk,
499 ("Transfer chunk for stream #%RU8 is invalid\n", uSD),
500 rc = VERR_INVALID_PARAMETER);
501 if (RT_SUCCESS(rc))
502 {
503 /* Make sure that the transfer chunk does not exceed the overall transfer size. */
504 if (pStreamShared->State.cbTransferChunk > pStreamShared->State.cbTransferSize)
505 pStreamShared->State.cbTransferChunk = pStreamShared->State.cbTransferSize;
506
507 const uint64_t cTicksPerHz = PDMDevHlpTimerGetFreq(pDevIns, pStreamShared->hTimer) / pStreamShared->State.uTimerHz;
508
509 /* Calculate the timer ticks per byte for this stream. */
510 pStreamShared->State.cTicksPerByte = cTicksPerHz / pStreamShared->State.cbTransferChunk;
511 Assert(pStreamShared->State.cTicksPerByte);
512
513 /* Calculate timer ticks per transfer. */
514 pStreamShared->State.cTransferTicks = pStreamShared->State.cbTransferChunk * pStreamShared->State.cTicksPerByte;
515 Assert(pStreamShared->State.cTransferTicks);
516
517 LogFunc(("[SD%RU8] Timer %uHz (%RU64 ticks per Hz), cTicksPerByte=%RU64, cbTransferChunk=%RU32, " \
518 "cTransferTicks=%RU64, cbTransferSize=%RU32\n",
519 uSD, pStreamShared->State.uTimerHz, cTicksPerHz, pStreamShared->State.cTicksPerByte,
520 pStreamShared->State.cbTransferChunk, pStreamShared->State.cTransferTicks, pStreamShared->State.cbTransferSize));
521
522 /* Make sure to also update the stream's DMA counter (based on its current LPIB value). */
523 hdaR3StreamSetPosition(pStreamShared, pDevIns, pThis, HDA_STREAM_REG(pThis, LPIB, uSD));
524
525#ifdef LOG_ENABLED
526 hdaR3BDLEDumpAll(pDevIns, pThis, pStreamShared->u64BDLBase, pStreamShared->u16LVI + 1);
527#endif
528 }
529 }
530 }
531
532 if (RT_FAILURE(rc))
533 LogRel(("HDA: Initializing stream #%RU8 failed with %Rrc\n", uSD, rc));
534
535 return rc;
536}
537
538/**
539 * Resets an HDA stream.
540 *
541 * @param pThis The shared HDA device state.
542 * @param pThisCC The ring-3 HDA device state.
543 * @param pStreamShared HDA stream to reset (shared).
544 * @param pStreamR3 HDA stream to reset (ring-3).
545 * @param uSD Stream descriptor (SD) number to use for this stream.
546 */
547void hdaR3StreamReset(PHDASTATE pThis, PHDASTATER3 pThisCC, PHDASTREAM pStreamShared, PHDASTREAMR3 pStreamR3, uint8_t uSD)
548{
549 AssertPtr(pThis);
550 AssertPtr(pStreamShared);
551 AssertPtr(pStreamR3);
552 Assert(uSD < HDA_MAX_STREAMS);
553 AssertMsg(!pStreamShared->State.fRunning, ("[SD%RU8] Cannot reset stream while in running state\n", uSD));
554
555 LogFunc(("[SD%RU8] Reset\n", uSD));
556
557 /*
558 * Set reset state.
559 */
560 Assert(ASMAtomicReadBool(&pStreamShared->State.fInReset) == false); /* No nested calls. */
561 ASMAtomicXchgBool(&pStreamShared->State.fInReset, true);
562
563 /*
564 * Second, initialize the registers.
565 */
566 HDA_STREAM_REG(pThis, STS, uSD) = HDA_SDSTS_FIFORDY;
567 /* According to the ICH6 datasheet, 0x40000 is the default value for stream descriptor register 23:20
568 * bits are reserved for stream number 18.2.33, resets SDnCTL except SRST bit. */
569 HDA_STREAM_REG(pThis, CTL, uSD) = 0x40000 | (HDA_STREAM_REG(pThis, CTL, uSD) & HDA_SDCTL_SRST);
570 /* ICH6 defines default values (120 bytes for input and 192 bytes for output descriptors) of FIFO size. 18.2.39. */
571 HDA_STREAM_REG(pThis, FIFOS, uSD) = hdaGetDirFromSD(uSD) == PDMAUDIODIR_IN ? HDA_SDIFIFO_120B : HDA_SDOFIFO_192B;
572 /* See 18.2.38: Always defaults to 0x4 (32 bytes). */
573 HDA_STREAM_REG(pThis, FIFOW, uSD) = HDA_SDFIFOW_32B;
574 HDA_STREAM_REG(pThis, LPIB, uSD) = 0;
575 HDA_STREAM_REG(pThis, CBL, uSD) = 0;
576 HDA_STREAM_REG(pThis, LVI, uSD) = 0;
577 HDA_STREAM_REG(pThis, FMT, uSD) = 0;
578 HDA_STREAM_REG(pThis, BDPU, uSD) = 0;
579 HDA_STREAM_REG(pThis, BDPL, uSD) = 0;
580
581#ifdef HDA_USE_DMA_ACCESS_HANDLER
582 hdaR3StreamUnregisterDMAHandlers(pThis, pStream);
583#endif
584
585 /* Assign the default mixer sink to the stream. */
586 pStreamR3->pMixSink = hdaR3GetDefaultSink(pThisCC, uSD);
587
588 /* Reset position adjustment counter. */
589 pStreamShared->State.cfPosAdjustLeft = pStreamShared->State.cfPosAdjustDefault;
590
591 /* Reset transfer stuff. */
592 pStreamShared->State.cbTransferProcessed = 0;
593 pStreamShared->State.cTransferPendingInterrupts = 0;
594 pStreamShared->State.tsTransferLast = 0;
595 pStreamShared->State.tsTransferNext = 0;
596
597 /* Initialize other timestamps. */
598 pStreamShared->State.tsLastUpdateNs = 0;
599
600 RT_ZERO(pStreamShared->State.BDLE);
601 pStreamShared->State.uCurBDLE = 0;
602
603 if (pStreamR3->State.pCircBuf)
604 RTCircBufReset(pStreamR3->State.pCircBuf);
605
606 /* Reset the stream's period. */
607 hdaR3StreamPeriodReset(&pStreamShared->State.Period);
608
609#ifdef DEBUG
610 pStreamR3->Dbg.cReadsTotal = 0;
611 pStreamR3->Dbg.cbReadTotal = 0;
612 pStreamR3->Dbg.tsLastReadNs = 0;
613 pStreamR3->Dbg.cWritesTotal = 0;
614 pStreamR3->Dbg.cbWrittenTotal = 0;
615 pStreamR3->Dbg.cWritesHz = 0;
616 pStreamR3->Dbg.cbWrittenHz = 0;
617 pStreamR3->Dbg.tsWriteSlotBegin = 0;
618#endif
619
620 /* Report that we're done resetting this stream. */
621 HDA_STREAM_REG(pThis, CTL, uSD) = 0;
622
623 LogFunc(("[SD%RU8] Reset\n", uSD));
624
625 /* Exit reset mode. */
626 ASMAtomicXchgBool(&pStreamShared->State.fInReset, false);
627}
628
629/**
630 * Enables or disables an HDA audio stream.
631 *
632 * @returns IPRT status code.
633 * @param pStreamShared HDA stream to enable or disable - shared bits.
634 * @param pStreamR3 HDA stream to enable or disable - ring-3 bits.
635 * @param fEnable Whether to enable or disble the stream.
636 */
637int hdaR3StreamEnable(PHDASTREAM pStreamShared, PHDASTREAMR3 pStreamR3, bool fEnable)
638{
639 AssertPtr(pStreamR3);
640 AssertPtr(pStreamShared);
641
642 LogFunc(("[SD%RU8] fEnable=%RTbool, pMixSink=%p\n", pStreamShared->u8SD, fEnable, pStreamR3->pMixSink));
643
644 int rc = VINF_SUCCESS;
645
646 AUDMIXSINKCMD enmCmd = fEnable
647 ? AUDMIXSINKCMD_ENABLE : AUDMIXSINKCMD_DISABLE;
648
649 /* First, enable or disable the stream and the stream's sink, if any. */
650 if ( pStreamR3->pMixSink
651 && pStreamR3->pMixSink->pMixSink)
652 rc = AudioMixerSinkCtl(pStreamR3->pMixSink->pMixSink, enmCmd);
653
654 if ( RT_SUCCESS(rc)
655 && fEnable
656 && pStreamR3->Dbg.Runtime.fEnabled)
657 {
658 Assert(DrvAudioHlpPCMPropsAreValid(&pStreamShared->State.Cfg.Props));
659
660 if (fEnable)
661 {
662 if (!DrvAudioHlpFileIsOpen(pStreamR3->Dbg.Runtime.pFileStream))
663 {
664 int rc2 = DrvAudioHlpFileOpen(pStreamR3->Dbg.Runtime.pFileStream, PDMAUDIOFILE_DEFAULT_OPEN_FLAGS,
665 &pStreamShared->State.Cfg.Props);
666 AssertRC(rc2);
667 }
668
669 if (!DrvAudioHlpFileIsOpen(pStreamR3->Dbg.Runtime.pFileDMARaw))
670 {
671 int rc2 = DrvAudioHlpFileOpen(pStreamR3->Dbg.Runtime.pFileDMARaw, PDMAUDIOFILE_DEFAULT_OPEN_FLAGS,
672 &pStreamShared->State.Cfg.Props);
673 AssertRC(rc2);
674 }
675
676 if (!DrvAudioHlpFileIsOpen(pStreamR3->Dbg.Runtime.pFileDMAMapped))
677 {
678 int rc2 = DrvAudioHlpFileOpen(pStreamR3->Dbg.Runtime.pFileDMAMapped, PDMAUDIOFILE_DEFAULT_OPEN_FLAGS,
679 &pStreamShared->State.Cfg.Props);
680 AssertRC(rc2);
681 }
682 }
683 }
684
685 if (RT_SUCCESS(rc))
686 {
687 pStreamShared->State.fRunning = fEnable;
688 }
689
690 LogFunc(("[SD%RU8] rc=%Rrc\n", pStreamShared->u8SD, rc));
691 return rc;
692}
693
694static uint32_t hdaR3StreamGetPosition(PHDASTATE pThis, PHDASTREAM pStreamShared)
695{
696 return HDA_STREAM_REG(pThis, LPIB, pStreamShared->u8SD);
697}
698
699/*
700 * Updates an HDA stream's current read or write buffer position (depending on the stream type) by
701 * updating its associated LPIB register and DMA position buffer (if enabled).
702 *
703 * @param pStreamShared HDA stream to update read / write position for (shared).
704 * @param pDevIns The device instance.
705 * @param pThis The shared HDA device state.
706 * @param u32LPIB Absolute position (in bytes) to set current read / write position to.
707 */
708static void hdaR3StreamSetPosition(PHDASTREAM pStreamShared, PPDMDEVINS pDevIns, PHDASTATE pThis, uint32_t u32LPIB)
709{
710 AssertPtrReturnVoid(pStreamShared);
711
712 Log3Func(("[SD%RU8] LPIB=%RU32 (DMA Position Buffer Enabled: %RTbool)\n", pStreamShared->u8SD, u32LPIB, pThis->fDMAPosition));
713
714 /* Update LPIB in any case. */
715 HDA_STREAM_REG(pThis, LPIB, pStreamShared->u8SD) = u32LPIB;
716
717 /* Do we need to tell the current DMA position? */
718 if (pThis->fDMAPosition)
719 {
720 int rc2 = PDMDevHlpPCIPhysWrite(pDevIns,
721 pThis->u64DPBase + (pStreamShared->u8SD * 2 * sizeof(uint32_t)),
722 (void *)&u32LPIB, sizeof(uint32_t));
723 AssertRC(rc2);
724 }
725}
726
727/**
728 * Retrieves the available size of (buffered) audio data (in bytes) of a given HDA stream.
729 *
730 * @returns Available data (in bytes).
731 * @param pStreamR3 HDA stream to retrieve size for (ring-3).
732 */
733static uint32_t hdaR3StreamGetUsed(PHDASTREAMR3 pStreamR3)
734{
735 AssertPtrReturn(pStreamR3, 0);
736
737 if (pStreamR3->State.pCircBuf)
738 return (uint32_t)RTCircBufUsed(pStreamR3->State.pCircBuf);
739 return 0;
740}
741
742/**
743 * Retrieves the free size of audio data (in bytes) of a given HDA stream.
744 *
745 * @returns Free data (in bytes).
746 * @param pStreamR3 HDA stream to retrieve size for (ring-3).
747 */
748static uint32_t hdaR3StreamGetFree(PHDASTREAMR3 pStreamR3)
749{
750 AssertPtrReturn(pStreamR3, 0);
751
752 if (pStreamR3->State.pCircBuf)
753 return (uint32_t)RTCircBufFree(pStreamR3->State.pCircBuf);
754 return 0;
755}
756
757/**
758 * Returns whether a next transfer for a given stream is scheduled or not.
759 *
760 * This takes pending stream interrupts into account as well as the next scheduled
761 * transfer timestamp.
762 *
763 * @returns True if a next transfer is scheduled, false if not.
764 * @param pStreamShared HDA stream to retrieve schedule status for (shared).
765 * @param tsNow The current time.
766 */
767bool hdaR3StreamTransferIsScheduled(PHDASTREAM pStreamShared, uint64_t tsNow)
768{
769 if (pStreamShared)
770 {
771 if (pStreamShared->State.fRunning)
772 {
773 if (pStreamShared->State.cTransferPendingInterrupts)
774 {
775 Log3Func(("[SD%RU8] Scheduled (%RU8 IRQs pending)\n", pStreamShared->u8SD, pStreamShared->State.cTransferPendingInterrupts));
776 return true;
777 }
778
779 if (pStreamShared->State.tsTransferNext > tsNow)
780 {
781 Log3Func(("[SD%RU8] Scheduled in %RU64\n", pStreamShared->u8SD, pStreamShared->State.tsTransferNext - tsNow));
782 return true;
783 }
784 }
785 }
786 return false;
787}
788
789/**
790 * Returns the (virtual) clock timestamp of the next transfer, if any.
791 * Will return 0 if no new transfer is scheduled.
792 *
793 * @returns The (virtual) clock timestamp of the next transfer.
794 * @param pStreamShared HDA stream to retrieve timestamp for (shared).
795 */
796uint64_t hdaR3StreamTransferGetNext(PHDASTREAM pStreamShared)
797{
798 return pStreamShared->State.tsTransferNext;
799}
800
801/**
802 * Writes audio data from a mixer sink into an HDA stream's DMA buffer.
803 *
804 * @returns IPRT status code.
805 * @param pStreamR3 HDA stream to write to (ring-3).
806 * @param pvBuf Data buffer to write.
807 * If NULL, silence will be written.
808 * @param cbBuf Number of bytes of data buffer to write.
809 * @param pcbWritten Number of bytes written. Optional.
810 */
811static int hdaR3StreamWrite(PHDASTREAMR3 pStreamR3, const void *pvBuf, uint32_t cbBuf, uint32_t *pcbWritten)
812{
813 Assert(cbBuf);
814
815 PRTCIRCBUF pCircBuf = pStreamR3->State.pCircBuf;
816 AssertPtr(pCircBuf);
817
818 uint32_t cbWrittenTotal = 0;
819 uint32_t cbLeft = RT_MIN(cbBuf, (uint32_t)RTCircBufFree(pCircBuf));
820
821 while (cbLeft)
822 {
823 void *pvDst;
824 size_t cbDst;
825 RTCircBufAcquireWriteBlock(pCircBuf, cbLeft, &pvDst, &cbDst);
826
827 if (cbDst)
828 {
829 if (pvBuf)
830 memcpy(pvDst, (uint8_t *)pvBuf + cbWrittenTotal, cbDst);
831 else /* Send silence. */
832 {
833 /** @todo Use a sample spec for "silence" based on the PCM parameters.
834 * For now we ASSUME that silence equals NULLing the data. */
835 RT_BZERO(pvDst, cbDst);
836 }
837
838 if (RT_LIKELY(!pStreamR3->Dbg.Runtime.fEnabled))
839 { /* likely */ }
840 else
841 DrvAudioHlpFileWrite(pStreamR3->Dbg.Runtime.pFileStream, pvDst, cbDst, 0 /* fFlags */);
842 }
843
844 RTCircBufReleaseWriteBlock(pCircBuf, cbDst);
845
846 Assert(cbLeft >= (uint32_t)cbDst);
847 cbLeft -= (uint32_t)cbDst;
848 cbWrittenTotal += (uint32_t)cbDst;
849 }
850
851 Log3Func(("cbWrittenTotal=%RU32\n", cbWrittenTotal));
852
853 if (pcbWritten)
854 *pcbWritten = cbWrittenTotal;
855
856 return VINF_SUCCESS;
857}
858
859
860/**
861 * Reads audio data from an HDA stream's DMA buffer and writes into a specified mixer sink.
862 *
863 * @returns IPRT status code.
864 * @param pStreamR3 HDA stream to read audio data from (ring-3).
865 * @param cbToRead Number of bytes to read.
866 * @param pcbRead Number of bytes read. Optional.
867 */
868static int hdaR3StreamRead(PHDASTREAMR3 pStreamR3, uint32_t cbToRead, uint32_t *pcbRead)
869{
870 Assert(cbToRead);
871
872 PHDAMIXERSINK pSink = pStreamR3->pMixSink;
873 AssertMsgReturnStmt(pSink, ("[SD%RU8] Can't read from a stream with no sink attached\n", pStreamR3->u8SD),
874 if (pcbRead) *pcbRead = 0,
875 VINF_SUCCESS);
876
877 PRTCIRCBUF pCircBuf = pStreamR3->State.pCircBuf;
878 AssertPtr(pCircBuf);
879
880 int rc = VINF_SUCCESS;
881
882 uint32_t cbReadTotal = 0;
883 uint32_t cbLeft = RT_MIN(cbToRead, (uint32_t)RTCircBufUsed(pCircBuf));
884
885 while (cbLeft)
886 {
887 void *pvSrc;
888 size_t cbSrc;
889
890 uint32_t cbWritten = 0;
891
892 RTCircBufAcquireReadBlock(pCircBuf, cbLeft, &pvSrc, &cbSrc);
893
894 if (cbSrc)
895 {
896 if (pStreamR3->Dbg.Runtime.fEnabled)
897 DrvAudioHlpFileWrite(pStreamR3->Dbg.Runtime.pFileStream, pvSrc, cbSrc, 0 /* fFlags */);
898
899 rc = AudioMixerSinkWrite(pSink->pMixSink, AUDMIXOP_COPY, pvSrc, (uint32_t)cbSrc, &cbWritten);
900 AssertRC(rc);
901
902 Assert(cbSrc >= cbWritten);
903 Log2Func(("[SD%RU8] %RU32/%zu bytes read\n", pStreamR3->u8SD, cbWritten, cbSrc));
904 }
905
906 RTCircBufReleaseReadBlock(pCircBuf, cbWritten);
907
908 if ( !cbWritten /* Nothing written? */
909 || RT_FAILURE(rc))
910 break;
911
912 Assert(cbLeft >= cbWritten);
913 cbLeft -= cbWritten;
914
915 cbReadTotal += cbWritten;
916 }
917
918 if (pcbRead)
919 *pcbRead = cbReadTotal;
920
921 return rc;
922}
923
924/**
925 * Transfers data of an HDA stream according to its usage (input / output).
926 *
927 * For an SDO (output) stream this means reading DMA data from the device to
928 * the HDA stream's internal FIFO buffer.
929 *
930 * For an SDI (input) stream this is reading audio data from the HDA stream's
931 * internal FIFO buffer and writing it as DMA data to the device.
932 *
933 * @returns IPRT status code.
934 * @param pDevIns The device instance.
935 * @param pThis The shared HDA device state.
936 * @param pThisCC The ring-3 HDA device state.
937 * @param pStreamShared HDA stream to update (shared).
938 * @param pStreamR3 HDA stream to update (ring-3).
939 * @param cbToProcessMax How much data (in bytes) to process as maximum.
940 * @param fInTimer Set if we're in the timer callout.
941 */
942static int hdaR3StreamTransfer(PPDMDEVINS pDevIns, PHDASTATE pThis, PHDASTATER3 pThisCC, PHDASTREAM pStreamShared,
943 PHDASTREAMR3 pStreamR3, uint32_t cbToProcessMax, bool fInTimer)
944{
945 uint8_t const uSD = pStreamShared->u8SD;
946 hdaR3StreamLock(pStreamR3);
947
948 PHDASTREAMPERIOD pPeriod = &pStreamShared->State.Period;
949 hdaR3StreamPeriodLock(pPeriod);
950
951 bool fProceed = true;
952
953 /* Stream not running? */
954 if (!pStreamShared->State.fRunning)
955 {
956 Log3Func(("[SD%RU8] Not running\n", uSD));
957 fProceed = false;
958 }
959 else if (HDA_STREAM_REG(pThis, STS, uSD) & HDA_SDSTS_BCIS)
960 {
961 Log3Func(("[SD%RU8] BCIS bit set\n", uSD));
962 fProceed = false;
963 }
964
965 if (!fProceed)
966 {
967 hdaR3StreamPeriodUnlock(pPeriod);
968 hdaR3StreamUnlock(pStreamR3);
969 return VINF_SUCCESS;
970 }
971
972 const uint64_t tsNow = PDMDevHlpTimerGet(pDevIns, pStreamShared->hTimer);
973
974 if (!pStreamShared->State.tsTransferLast)
975 pStreamShared->State.tsTransferLast = tsNow;
976
977#ifdef DEBUG
978 const int64_t iTimerDelta = tsNow - pStreamShared->State.tsTransferLast;
979 Log3Func(("[SD%RU8] Time now=%RU64, last=%RU64 -> %RI64 ticks delta\n",
980 uSD, tsNow, pStreamShared->State.tsTransferLast, iTimerDelta));
981#endif
982
983 pStreamShared->State.tsTransferLast = tsNow;
984
985 /* Sanity checks. */
986 Assert(uSD < HDA_MAX_STREAMS);
987 Assert(pStreamShared->u64BDLBase);
988 Assert(pStreamShared->u32CBL);
989 Assert(pStreamShared->u16FIFOS);
990
991 /* State sanity checks. */
992 Assert(ASMAtomicReadBool(&pStreamShared->State.fInReset) == false);
993
994 int rc = VINF_SUCCESS;
995
996 /* Fetch first / next BDL entry. */
997 PHDABDLE pBDLE = &pStreamShared->State.BDLE;
998 if (hdaR3BDLEIsComplete(pBDLE))
999 {
1000 rc = hdaR3BDLEFetch(pDevIns, pBDLE, pStreamShared->u64BDLBase, pStreamShared->State.uCurBDLE);
1001 AssertRC(rc);
1002 }
1003
1004 uint32_t cbToProcess = RT_MIN(pStreamShared->State.cbTransferSize - pStreamShared->State.cbTransferProcessed,
1005 pStreamShared->State.cbTransferChunk);
1006
1007 Log3Func(("[SD%RU8] cbToProcess=%RU32, cbToProcessMax=%RU32\n", uSD, cbToProcess, cbToProcessMax));
1008
1009 if (cbToProcess > cbToProcessMax)
1010 {
1011 LogFunc(("[SD%RU8] Limiting transfer (cbToProcess=%RU32, cbToProcessMax=%RU32)\n", uSD, cbToProcess, cbToProcessMax));
1012
1013 /* Never process more than a stream currently can handle. */
1014 cbToProcess = cbToProcessMax;
1015 }
1016
1017 uint32_t cbProcessed = 0;
1018 uint32_t cbLeft = cbToProcess;
1019
1020 uint8_t abChunk[HDA_FIFO_MAX + 1];
1021 while (cbLeft)
1022 {
1023 /* Limit the chunk to the stream's FIFO size and what's left to process. */
1024 uint32_t cbChunk = RT_MIN(cbLeft, pStreamShared->u16FIFOS);
1025
1026 /* Limit the chunk to the remaining data of the current BDLE. */
1027 cbChunk = RT_MIN(cbChunk, pBDLE->Desc.u32BufSize - pBDLE->State.u32BufOff);
1028
1029 /* If there are position adjustment frames left to be processed,
1030 * make sure that we process them first as a whole. */
1031 if (pStreamShared->State.cfPosAdjustLeft)
1032 cbChunk = RT_MIN(cbChunk, uint32_t(pStreamShared->State.cfPosAdjustLeft * pStreamR3->State.Mapping.cbFrameSize));
1033
1034 Log3Func(("[SD%RU8] cbChunk=%RU32, cPosAdjustFramesLeft=%RU16\n",
1035 uSD, cbChunk, pStreamShared->State.cfPosAdjustLeft));
1036
1037 if (!cbChunk)
1038 break;
1039
1040 uint32_t cbDMA = 0;
1041 PRTCIRCBUF pCircBuf = pStreamR3->State.pCircBuf;
1042
1043 if (hdaGetDirFromSD(uSD) == PDMAUDIODIR_IN) /* Input (SDI). */
1044 {
1045 STAM_PROFILE_START(&pThis->StatIn, a);
1046
1047 uint32_t cbDMAWritten = 0;
1048 uint32_t cbDMAToWrite = cbChunk;
1049
1050 /** @todo Do we need interleaving streams support here as well?
1051 * Never saw anything else besides mono/stereo mics (yet). */
1052 while (cbDMAToWrite)
1053 {
1054 void *pvBuf; size_t cbBuf;
1055 RTCircBufAcquireReadBlock(pCircBuf, cbDMAToWrite, &pvBuf, &cbBuf);
1056
1057 if ( !cbBuf
1058 && !RTCircBufUsed(pCircBuf))
1059 break;
1060
1061 memcpy(abChunk + cbDMAWritten, pvBuf, cbBuf);
1062
1063 RTCircBufReleaseReadBlock(pCircBuf, cbBuf);
1064
1065 Assert(cbDMAToWrite >= cbBuf);
1066 cbDMAToWrite -= (uint32_t)cbBuf;
1067 cbDMAWritten += (uint32_t)cbBuf;
1068 Assert(cbDMAWritten <= cbChunk);
1069 }
1070
1071 if (cbDMAToWrite)
1072 {
1073 LogRel2(("HDA: FIFO underflow for stream #%RU8 (%RU32 bytes outstanding)\n", uSD, cbDMAToWrite));
1074
1075 Assert(cbChunk == cbDMAWritten + cbDMAToWrite);
1076 memset((uint8_t *)abChunk + cbDMAWritten, 0, cbDMAToWrite);
1077 cbDMAWritten = cbChunk;
1078 }
1079
1080 rc = hdaR3DMAWrite(pDevIns, pThis, pStreamShared, pStreamR3, abChunk, cbDMAWritten, &cbDMA /* pcbWritten */);
1081 if (RT_FAILURE(rc))
1082 LogRel(("HDA: Writing to stream #%RU8 DMA failed with %Rrc\n", uSD, rc));
1083
1084 STAM_PROFILE_STOP(&pThis->StatIn, a);
1085 }
1086 else if (hdaGetDirFromSD(uSD) == PDMAUDIODIR_OUT) /* Output (SDO). */
1087 {
1088 STAM_PROFILE_START(&pThis->StatOut, a);
1089
1090 rc = hdaR3DMARead(pDevIns, pThis, pStreamShared, pStreamR3, abChunk, cbChunk, &cbDMA /* pcbRead */);
1091 if (RT_SUCCESS(rc))
1092 {
1093 const uint32_t cbFree = (uint32_t)RTCircBufFree(pCircBuf);
1094
1095 /*
1096 * Most guests don't use different stream frame sizes than
1097 * the default one, so save a bit of CPU time and don't go into
1098 * the frame extraction code below.
1099 *
1100 * Only macOS guests need the frame extraction branch below at the moment AFAIK.
1101 */
1102 if (pStreamR3->State.Mapping.cbFrameSize == HDA_FRAME_SIZE_DEFAULT)
1103 {
1104 uint32_t cbDMARead = 0;
1105 uint32_t cbDMALeft = RT_MIN(cbDMA, cbFree);
1106
1107 while (cbDMALeft)
1108 {
1109 void *pvBuf; size_t cbBuf;
1110 RTCircBufAcquireWriteBlock(pCircBuf, cbDMALeft, &pvBuf, &cbBuf);
1111
1112 if (cbBuf)
1113 {
1114 memcpy(pvBuf, abChunk + cbDMARead, cbBuf);
1115 cbDMARead += (uint32_t)cbBuf;
1116 cbDMALeft -= (uint32_t)cbBuf;
1117 }
1118
1119 RTCircBufReleaseWriteBlock(pCircBuf, cbBuf);
1120 }
1121 }
1122 else
1123 {
1124 /*
1125 * The following code extracts the required audio stream (channel) data
1126 * of non-interleaved *and* interleaved audio streams.
1127 *
1128 * We by default only support 2 channels with 16-bit samples (HDA_FRAME_SIZE),
1129 * but an HDA audio stream can have interleaved audio data of multiple audio
1130 * channels in such a single stream ("AA,AA,AA vs. AA,BB,AA,BB").
1131 *
1132 * So take this into account by just handling the first channel in such a stream ("A")
1133 * and just discard the other channel's data.
1134 *
1135 * I know, the following code is horribly slow, but seems to work for now.
1136 */
1137 /** @todo Optimize channel data extraction! Use some SSE(3) / intrinsics? */
1138 for (unsigned m = 0; m < pStreamR3->State.Mapping.cMappings; m++)
1139 {
1140 const uint32_t cbFrame = pStreamR3->State.Mapping.cbFrameSize;
1141
1142 Assert(cbFree >= cbDMA);
1143
1144 PPDMAUDIOSTREAMMAP pMap = &pStreamR3->State.Mapping.paMappings[m];
1145 AssertPtr(pMap);
1146
1147 Log3Func(("Mapping #%u: Start (cbDMA=%RU32, cbFrame=%RU32, offNext=%RU32)\n",
1148 m, cbDMA, cbFrame, pMap->offNext));
1149
1150
1151 /* Skip the current DMA chunk if the chunk is smaller than what the current stream mapping needs to read
1152 * the next associated frame (pointed to at pMap->cbOff).
1153 *
1154 * This can happen if the guest did not come up with enough data within a certain time period, especially
1155 * when using multi-channel speaker (> 2 channels [stereo]) setups. */
1156 if (pMap->offNext > cbChunk)
1157 {
1158 Log2Func(("Mapping #%u: Skipped (cbChunk=%RU32, cbMapOff=%RU32)\n", m, cbChunk, pMap->offNext));
1159 continue;
1160 }
1161
1162 uint8_t *pbSrcBuf = abChunk;
1163 size_t cbSrcOff = pMap->offNext;
1164
1165 for (unsigned i = 0; i < cbDMA / cbFrame; i++)
1166 {
1167 void *pvDstBuf; size_t cbDstBuf;
1168 RTCircBufAcquireWriteBlock(pCircBuf, pMap->cbStep, &pvDstBuf, &cbDstBuf);
1169
1170 Assert(cbDstBuf >= pMap->cbStep);
1171
1172 if (cbDstBuf)
1173 {
1174 Log3Func(("Mapping #%u: Frame #%02u: cbStep=%u, offFirst=%u, offNext=%u, cbDstBuf=%u, cbSrcOff=%u\n",
1175 m, i, pMap->cbStep, pMap->offFirst, pMap->offNext, cbDstBuf, cbSrcOff));
1176
1177 memcpy(pvDstBuf, pbSrcBuf + cbSrcOff, cbDstBuf);
1178
1179#if 0 /* Too slow, even for release builds, so disabled it. */
1180 if (pStreamR3->Dbg.Runtime.fEnabled)
1181 DrvAudioHlpFileWrite(pStreamR3->Dbg.Runtime.pFileDMAMapped, pvDstBuf, cbDstBuf,
1182 0 /* fFlags */);
1183#endif
1184 Assert(cbSrcOff <= cbDMA);
1185 if (cbSrcOff + cbFrame + pMap->offFirst<= cbDMA)
1186 cbSrcOff += cbFrame + pMap->offFirst;
1187
1188 Log3Func(("Mapping #%u: Frame #%02u: -> cbSrcOff=%zu\n", m, i, cbSrcOff));
1189 }
1190
1191 RTCircBufReleaseWriteBlock(pCircBuf, cbDstBuf);
1192 }
1193
1194 Log3Func(("Mapping #%u: End cbSize=%u, cbDMA=%RU32, cbSrcOff=%zu\n",
1195 m, pMap->cbStep, cbDMA, cbSrcOff));
1196
1197 Assert(cbSrcOff <= cbDMA);
1198
1199 const uint32_t cbSrcLeft = cbDMA - (uint32_t)cbSrcOff;
1200 if (cbSrcLeft)
1201 {
1202 Log3Func(("Mapping #%u: cbSrcLeft=%RU32\n", m, cbSrcLeft));
1203
1204 if (cbSrcLeft >= pMap->cbStep)
1205 {
1206 void *pvDstBuf; size_t cbDstBuf;
1207 RTCircBufAcquireWriteBlock(pCircBuf, pMap->cbStep, &pvDstBuf, &cbDstBuf);
1208
1209 Assert(cbDstBuf >= pMap->cbStep);
1210
1211 if (cbDstBuf)
1212 {
1213 memcpy(pvDstBuf, pbSrcBuf + cbSrcOff, cbDstBuf);
1214 }
1215
1216 RTCircBufReleaseWriteBlock(pCircBuf, cbDstBuf);
1217 }
1218
1219 Assert(pMap->cbFrame >= cbSrcLeft);
1220 pMap->offNext = pMap->cbFrame - cbSrcLeft;
1221 }
1222 else
1223 pMap->offNext = 0;
1224
1225 Log3Func(("Mapping #%u finish (cbSrcOff=%zu, offNext=%zu)\n", m, cbSrcOff, pMap->offNext));
1226 }
1227 }
1228 }
1229 else
1230 LogRel(("HDA: Reading from stream #%RU8 DMA failed with %Rrc\n", uSD, rc));
1231
1232 STAM_PROFILE_STOP(&pThis->StatOut, a);
1233 }
1234
1235 else /** @todo Handle duplex streams? */
1236 AssertFailed();
1237
1238 if (cbDMA)
1239 {
1240 /* We always increment the position of DMA buffer counter because we're always reading
1241 * into an intermediate DMA buffer. */
1242 pBDLE->State.u32BufOff += (uint32_t)cbDMA;
1243 Assert(pBDLE->State.u32BufOff <= pBDLE->Desc.u32BufSize);
1244
1245 /* Are we done doing the position adjustment?
1246 * Only then do the transfer accounting .*/
1247 if (pStreamShared->State.cfPosAdjustLeft == 0)
1248 {
1249 Assert(cbLeft >= cbDMA);
1250 cbLeft -= cbDMA;
1251
1252 cbProcessed += cbDMA;
1253 }
1254
1255 /*
1256 * Update the stream's current position.
1257 * Do this as accurate and close to the actual data transfer as possible.
1258 * All guetsts rely on this, depending on the mechanism they use (LPIB register or DMA counters).
1259 */
1260 uint32_t cbStreamPos = hdaR3StreamGetPosition(pThis, pStreamShared);
1261 if (cbStreamPos == pStreamShared->u32CBL)
1262 cbStreamPos = 0;
1263
1264 hdaR3StreamSetPosition(pStreamShared, pDevIns, pThis, cbStreamPos + cbDMA);
1265 }
1266
1267 if (hdaR3BDLEIsComplete(pBDLE))
1268 {
1269 Log3Func(("[SD%RU8] Complete: %R[bdle]\n", uSD, pBDLE));
1270
1271 /* Does the current BDLE require an interrupt to be sent? */
1272 if ( hdaR3BDLENeedsInterrupt(pBDLE)
1273 /* Are we done doing the position adjustment?
1274 * It can happen that a BDLE which is handled while doing the
1275 * position adjustment requires an interrupt on completion (IOC) being set.
1276 *
1277 * In such a case we need to skip such an interrupt and just move on. */
1278 && pStreamShared->State.cfPosAdjustLeft == 0)
1279 {
1280 /* If the IOCE ("Interrupt On Completion Enable") bit of the SDCTL register is set
1281 * we need to generate an interrupt.
1282 */
1283 if (HDA_STREAM_REG(pThis, CTL, uSD) & HDA_SDCTL_IOCE)
1284 {
1285 pStreamShared->State.cTransferPendingInterrupts++;
1286
1287 AssertMsg(pStreamShared->State.cTransferPendingInterrupts <= 32,
1288 ("Too many pending interrupts (%RU8) for stream #%RU8\n",
1289 pStreamShared->State.cTransferPendingInterrupts, uSD));
1290 }
1291 }
1292
1293 if (pStreamShared->State.uCurBDLE == pStreamShared->u16LVI)
1294 {
1295 pStreamShared->State.uCurBDLE = 0;
1296 }
1297 else
1298 pStreamShared->State.uCurBDLE++;
1299
1300 /* Fetch the next BDLE entry. */
1301 hdaR3BDLEFetch(pDevIns, pBDLE, pStreamShared->u64BDLBase, pStreamShared->State.uCurBDLE);
1302 }
1303
1304 /* Do the position adjustment accounting. */
1305 pStreamShared->State.cfPosAdjustLeft -=
1306 RT_MIN(pStreamShared->State.cfPosAdjustLeft, cbDMA / pStreamR3->State.Mapping.cbFrameSize);
1307
1308 if (RT_FAILURE(rc))
1309 break;
1310 }
1311
1312 Log3Func(("[SD%RU8] cbToProcess=%RU32, cbProcessed=%RU32, cbLeft=%RU32, %R[bdle], rc=%Rrc\n",
1313 uSD, cbToProcess, cbProcessed, cbLeft, pBDLE, rc));
1314
1315 /* Sanity. */
1316 Assert(cbProcessed == cbToProcess);
1317 Assert(cbLeft == 0);
1318
1319 /* Only do the data accounting if we don't have to do any position
1320 * adjustment anymore. */
1321 if (pStreamShared->State.cfPosAdjustLeft == 0)
1322 {
1323 hdaR3StreamPeriodInc(pPeriod, RT_MIN(cbProcessed / pStreamR3->State.Mapping.cbFrameSize,
1324 hdaR3StreamPeriodGetRemainingFrames(pPeriod)));
1325
1326 pStreamShared->State.cbTransferProcessed += cbProcessed;
1327 }
1328
1329 /* Make sure that we never report more stuff processed than initially announced. */
1330 if (pStreamShared->State.cbTransferProcessed > pStreamShared->State.cbTransferSize)
1331 pStreamShared->State.cbTransferProcessed = pStreamShared->State.cbTransferSize;
1332
1333 uint32_t cbTransferLeft = pStreamShared->State.cbTransferSize - pStreamShared->State.cbTransferProcessed;
1334 bool fTransferComplete = !cbTransferLeft;
1335 uint64_t tsTransferNext = 0;
1336
1337 if (fTransferComplete)
1338 {
1339 /*
1340 * Try updating the wall clock.
1341 *
1342 * Note 1) Only certain guests (like Linux' snd_hda_intel) rely on the WALCLK register
1343 * in order to determine the correct timing of the sound device. Other guests
1344 * like Windows 7 + 10 (or even more exotic ones like Haiku) will completely
1345 * ignore this.
1346 *
1347 * Note 2) When updating the WALCLK register too often / early (or even in a non-monotonic
1348 * fashion) this *will* upset guest device drivers and will completely fuck up the
1349 * sound output. Running VLC on the guest will tell!
1350 */
1351 const bool fWalClkSet = hdaR3WalClkSet(pThis, pThisCC,
1352 hdaWalClkGetCurrent(pThis)
1353 + hdaR3StreamPeriodFramesToWalClk(pPeriod,
1354 pStreamShared->State.cbTransferProcessed
1355 / pStreamR3->State.Mapping.cbFrameSize),
1356 false /* fForce */);
1357 RT_NOREF(fWalClkSet);
1358 }
1359
1360 /* Does the period have any interrupts outstanding? */
1361 if (pStreamShared->State.cTransferPendingInterrupts)
1362 {
1363 Log3Func(("[SD%RU8] Scheduling interrupt\n", uSD));
1364
1365 /*
1366 * Set the stream's BCIS bit.
1367 *
1368 * Note: This only must be done if the whole period is complete, and not if only
1369 * one specific BDL entry is complete (if it has the IOC bit set).
1370 *
1371 * This will otherwise confuses the guest when it 1) deasserts the interrupt,
1372 * 2) reads SDSTS (with BCIS set) and then 3) too early reads a (wrong) WALCLK value.
1373 *
1374 * snd_hda_intel on Linux will tell.
1375 */
1376 HDA_STREAM_REG(pThis, STS, uSD) |= HDA_SDSTS_BCIS;
1377
1378 /* Trigger an interrupt first and let hdaRegWriteSDSTS() deal with
1379 * ending / beginning a period. */
1380 HDA_PROCESS_INTERRUPT(pDevIns, pThis);
1381 }
1382 else /* Transfer still in-flight -- schedule the next timing slot. */
1383 {
1384 uint32_t cbTransferNext = cbTransferLeft;
1385
1386 /* No data left to transfer anymore or do we have more data left
1387 * than we can transfer per timing slot? Clamp. */
1388 if ( !cbTransferNext
1389 || cbTransferNext > pStreamShared->State.cbTransferChunk)
1390 {
1391 cbTransferNext = pStreamShared->State.cbTransferChunk;
1392 }
1393
1394 tsTransferNext = tsNow + (cbTransferNext * pStreamShared->State.cTicksPerByte);
1395
1396 /*
1397 * If the current transfer is complete, reset our counter.
1398 *
1399 * This can happen for examlpe if the guest OS (like macOS) sets up
1400 * big BDLEs without IOC bits set (but for the last one) and the
1401 * transfer is complete before we reach such a BDL entry.
1402 */
1403 if (fTransferComplete)
1404 pStreamShared->State.cbTransferProcessed = 0;
1405 }
1406
1407 /* If we need to do another transfer, (re-)arm the device timer. */
1408 if (tsTransferNext) /* Can be 0 if no next transfer is needed. */
1409 {
1410 Log3Func(("[SD%RU8] Scheduling timer\n", uSD));
1411
1412 LogFunc(("Timer set SD%RU8\n", uSD));
1413 Assert(!fInTimer || tsNow == PDMDevHlpTimerGet(pDevIns, pStreamShared->hTimer));
1414 hdaR3TimerSet(pDevIns, pStreamShared, tsTransferNext,
1415 true /* fForce - skip tsTransferNext check */, fInTimer ? tsNow : 0);
1416
1417 pStreamShared->State.tsTransferNext = tsTransferNext;
1418 }
1419
1420 pStreamShared->State.tsTransferLast = tsNow;
1421
1422 Log3Func(("[SD%RU8] cbTransferLeft=%RU32 -- %RU32/%RU32\n",
1423 uSD, cbTransferLeft, pStreamShared->State.cbTransferProcessed, pStreamShared->State.cbTransferSize));
1424 Log3Func(("[SD%RU8] fTransferComplete=%RTbool, cTransferPendingInterrupts=%RU8\n",
1425 uSD, fTransferComplete, pStreamShared->State.cTransferPendingInterrupts));
1426 Log3Func(("[SD%RU8] tsNow=%RU64, tsTransferNext=%RU64 (in %RU64 ticks)\n",
1427 uSD, tsNow, tsTransferNext, tsTransferNext - tsNow));
1428
1429 hdaR3StreamPeriodUnlock(pPeriod);
1430 hdaR3StreamUnlock(pStreamR3);
1431
1432 return VINF_SUCCESS;
1433}
1434
1435/**
1436 * Updates a HDA stream by doing its required data transfers.
1437 * The host sink(s) set the overall pace.
1438 *
1439 * This routine is called by both, the synchronous and the asynchronous, implementations.
1440 *
1441 * This routine is called by both, the synchronous and the asynchronous
1442 * (VBOX_WITH_AUDIO_HDA_ASYNC_IO), implementations.
1443 *
1444 * When running synchronously, the device DMA transfers *and* the mixer sink
1445 * processing is within the device timer.
1446 *
1447 * When running asynchronously, only the device DMA transfers are done in the
1448 * device timer, whereas the mixer sink processing then is done in the stream's
1449 * own async I/O thread. This thread also will call this function
1450 * (with fInTimer set to @c false).
1451 *
1452 * @param pDevIns The device instance.
1453 * @param pThis The shared HDA device state.
1454 * @param pThisCC The ring-3 HDA device state.
1455 * @param pStreamShared HDA stream to update (shared bits).
1456 * @param pStreamR3 HDA stream to update (ring-3 bits).
1457 * @param fInTimer Whether to this function was called from the timer
1458 * context or an asynchronous I/O stream thread (if supported).
1459 */
1460void hdaR3StreamUpdate(PPDMDEVINS pDevIns, PHDASTATE pThis, PHDASTATER3 pThisCC,
1461 PHDASTREAM pStreamShared, PHDASTREAMR3 pStreamR3, bool fInTimer)
1462{
1463 if (!pStreamShared)
1464 return;
1465
1466 PAUDMIXSINK pSink = NULL;
1467 if (pStreamR3->pMixSink)
1468 pSink = pStreamR3->pMixSink->pMixSink;
1469
1470 if (!AudioMixerSinkIsActive(pSink)) /* No sink available? Bail out. */
1471 return;
1472
1473 int rc2;
1474
1475 if (hdaGetDirFromSD(pStreamShared->u8SD) == PDMAUDIODIR_OUT) /* Output (SDO). */
1476 {
1477 bool fDoRead = false; /* Whether to read from the HDA stream or not. */
1478
1479# ifdef VBOX_WITH_AUDIO_HDA_ASYNC_IO
1480 if (fInTimer)
1481# endif
1482 {
1483 const uint32_t cbStreamFree = hdaR3StreamGetFree(pStreamR3);
1484 if (cbStreamFree)
1485 {
1486 /* Do the DMA transfer. */
1487 rc2 = hdaR3StreamTransfer(pDevIns, pThis, pThisCC, pStreamShared, pStreamR3, cbStreamFree, fInTimer);
1488 AssertRC(rc2);
1489 }
1490
1491 /* Only read from the HDA stream at the given scheduling rate. */
1492 const uint64_t tsNowNs = RTTimeNanoTS();
1493 if (tsNowNs - pStreamShared->State.tsLastUpdateNs >= pStreamShared->State.Cfg.Device.cMsSchedulingHint * RT_NS_1MS)
1494 {
1495 fDoRead = true;
1496 pStreamShared->State.tsLastUpdateNs = tsNowNs;
1497 }
1498 }
1499
1500 Log3Func(("[SD%RU8] fInTimer=%RTbool, fDoRead=%RTbool\n", pStreamShared->u8SD, fInTimer, fDoRead));
1501
1502# ifdef VBOX_WITH_AUDIO_HDA_ASYNC_IO
1503 if (fDoRead)
1504 {
1505 rc2 = hdaR3StreamAsyncIONotify(pStreamR3);
1506 AssertRC(rc2);
1507 }
1508# endif
1509
1510# ifdef VBOX_WITH_AUDIO_HDA_ASYNC_IO
1511 if (!fInTimer) /* In async I/O thread */
1512 {
1513# else
1514 if (fDoRead)
1515 {
1516# endif
1517 const uint32_t cbSinkWritable = AudioMixerSinkGetWritable(pSink);
1518 const uint32_t cbStreamReadable = hdaR3StreamGetUsed(pStreamR3);
1519 const uint32_t cbToReadFromStream = RT_MIN(cbStreamReadable, cbSinkWritable);
1520
1521 Log3Func(("[SD%RU8] cbSinkWritable=%RU32, cbStreamReadable=%RU32\n", pStreamShared->u8SD, cbSinkWritable, cbStreamReadable));
1522
1523 if (cbToReadFromStream)
1524 {
1525 /* Read (guest output) data and write it to the stream's sink. */
1526 rc2 = hdaR3StreamRead(pStreamR3, cbToReadFromStream, NULL /* pcbRead */);
1527 AssertRC(rc2);
1528 }
1529
1530 /* When running synchronously, update the associated sink here.
1531 * Otherwise this will be done in the async I/O thread. */
1532 rc2 = AudioMixerSinkUpdate(pSink);
1533 AssertRC(rc2);
1534 }
1535 }
1536 else /* Input (SDI). */
1537 {
1538# ifdef VBOX_WITH_AUDIO_HDA_ASYNC_IO
1539 if (!fInTimer)
1540 {
1541# endif
1542 rc2 = AudioMixerSinkUpdate(pSink);
1543 AssertRC(rc2);
1544
1545 /* Is the sink ready to be read (host input data) from? If so, by how much? */
1546 uint32_t cbSinkReadable = AudioMixerSinkGetReadable(pSink);
1547
1548 /* How much (guest input) data is available for writing at the moment for the HDA stream? */
1549 const uint32_t cbStreamFree = hdaR3StreamGetFree(pStreamR3);
1550
1551 Log3Func(("[SD%RU8] cbSinkReadable=%RU32, cbStreamFree=%RU32\n", pStreamShared->u8SD, cbSinkReadable, cbStreamFree));
1552
1553 /* Do not read more than the HDA stream can hold at the moment.
1554 * The host sets the overall pace. */
1555 if (cbSinkReadable > cbStreamFree)
1556 cbSinkReadable = cbStreamFree;
1557
1558 if (cbSinkReadable)
1559 {
1560 uint8_t abFIFO[HDA_FIFO_MAX + 1];
1561 while (cbSinkReadable)
1562 {
1563 uint32_t cbRead;
1564 rc2 = AudioMixerSinkRead(pSink, AUDMIXOP_COPY,
1565 abFIFO, RT_MIN(cbSinkReadable, (uint32_t)sizeof(abFIFO)), &cbRead);
1566 AssertRCBreak(rc2);
1567
1568 if (!cbRead)
1569 {
1570 AssertMsgFailed(("Nothing read from sink, even if %RU32 bytes were (still) announced\n", cbSinkReadable));
1571 break;
1572 }
1573
1574 /* Write (guest input) data to the stream which was read from stream's sink before. */
1575 uint32_t cbWritten;
1576 rc2 = hdaR3StreamWrite(pStreamR3, abFIFO, cbRead, &cbWritten);
1577 AssertRCBreak(rc2);
1578 AssertBreak(cbWritten > 0); /* Should never happen, as we know how much we can write. */
1579
1580 Assert(cbSinkReadable >= cbRead);
1581 cbSinkReadable -= cbRead;
1582 }
1583 }
1584# ifdef VBOX_WITH_AUDIO_HDA_ASYNC_IO
1585 }
1586 else /* fInTimer */
1587 {
1588# endif
1589
1590# ifdef VBOX_WITH_AUDIO_HDA_ASYNC_IO
1591 const uint64_t tsNowNs = RTTimeNanoTS();
1592 if (tsNowNs - pStreamShared->State.tsLastUpdateNs >= pStreamShared->State.Cfg.Device.cMsSchedulingHint * RT_NS_1MS)
1593 {
1594 rc2 = hdaR3StreamAsyncIONotify(pStreamR3);
1595 AssertRC(rc2);
1596
1597 pStreamShared->State.tsLastUpdateNs = tsNowNs;
1598 }
1599# endif
1600 const uint32_t cbStreamUsed = hdaR3StreamGetUsed(pStreamR3);
1601 if (cbStreamUsed)
1602 {
1603 rc2 = hdaR3StreamTransfer(pDevIns, pThis, pThisCC, pStreamShared, pStreamR3, cbStreamUsed, fInTimer);
1604 AssertRC(rc2);
1605 }
1606# ifdef VBOX_WITH_AUDIO_HDA_ASYNC_IO
1607 }
1608# endif
1609 }
1610}
1611
1612/**
1613 * Locks an HDA stream for serialized access.
1614 *
1615 * @returns IPRT status code.
1616 * @param pStreamR3 HDA stream to lock (ring-3 bits).
1617 */
1618void hdaR3StreamLock(PHDASTREAMR3 pStreamR3)
1619{
1620 AssertPtrReturnVoid(pStreamR3);
1621# ifdef VBOX_WITH_AUDIO_HDA_ASYNC_IO
1622 int rc2 = RTCritSectEnter(&pStreamR3->CritSect);
1623 AssertRC(rc2);
1624# else
1625 Assert(PDMDevHlpCritSectIsOwner(pStream->pHDAState->pDevInsR3, pStream->pHDAState->CritSect));
1626# endif
1627}
1628
1629/**
1630 * Unlocks a formerly locked HDA stream.
1631 *
1632 * @returns IPRT status code.
1633 * @param pStreamR3 HDA stream to unlock (ring-3 bits).
1634 */
1635void hdaR3StreamUnlock(PHDASTREAMR3 pStreamR3)
1636{
1637 AssertPtrReturnVoid(pStreamR3);
1638# ifdef VBOX_WITH_AUDIO_HDA_ASYNC_IO
1639 int rc2 = RTCritSectLeave(&pStreamR3->CritSect);
1640 AssertRC(rc2);
1641# endif
1642}
1643
1644#if 0 /* unused - no prototype even */
1645/**
1646 * Updates an HDA stream's current read or write buffer position (depending on the stream type) by
1647 * updating its associated LPIB register and DMA position buffer (if enabled).
1648 *
1649 * @returns Set LPIB value.
1650 * @param pDevIns The device instance.
1651 * @param pStream HDA stream to update read / write position for.
1652 * @param u32LPIB New LPIB (position) value to set.
1653 */
1654uint32_t hdaR3StreamUpdateLPIB(PPDMDEVINS pDevIns, PHDASTATE pThis, PHDASTREAM pStreamShared, uint32_t u32LPIB)
1655{
1656 AssertMsg(u32LPIB <= pStreamShared->u32CBL,
1657 ("[SD%RU8] New LPIB (%RU32) exceeds CBL (%RU32)\n", pStreamShared->u8SD, u32LPIB, pStreamShared->u32CBL));
1658
1659 u32LPIB = RT_MIN(u32LPIB, pStreamShared->u32CBL);
1660
1661 LogFlowFunc(("[SD%RU8] LPIB=%RU32 (DMA Position Buffer Enabled: %RTbool)\n",
1662 pStreamShared->u8SD, u32LPIB, pThis->fDMAPosition));
1663
1664 /* Update LPIB in any case. */
1665 HDA_STREAM_REG(pThis, LPIB, pStreamShared->u8SD) = u32LPIB;
1666
1667 /* Do we need to tell the current DMA position? */
1668 if (pThis->fDMAPosition)
1669 {
1670 int rc2 = PDMDevHlpPCIPhysWrite(pDevIns,
1671 pThis->u64DPBase + (pStreamShared->u8SD * 2 * sizeof(uint32_t)),
1672 (void *)&u32LPIB, sizeof(uint32_t));
1673 AssertRC(rc2);
1674 }
1675
1676 return u32LPIB;
1677}
1678#endif
1679
1680# ifdef HDA_USE_DMA_ACCESS_HANDLER
1681/**
1682 * Registers access handlers for a stream's BDLE DMA accesses.
1683 *
1684 * @returns true if registration was successful, false if not.
1685 * @param pStream HDA stream to register BDLE access handlers for.
1686 */
1687bool hdaR3StreamRegisterDMAHandlers(PHDASTREAM pStream)
1688{
1689 /* At least LVI and the BDL base must be set. */
1690 if ( !pStreamShared->u16LVI
1691 || !pStreamShared->u64BDLBase)
1692 {
1693 return false;
1694 }
1695
1696 hdaR3StreamUnregisterDMAHandlers(pStream);
1697
1698 LogFunc(("Registering ...\n"));
1699
1700 int rc = VINF_SUCCESS;
1701
1702 /*
1703 * Create BDLE ranges.
1704 */
1705
1706 struct BDLERANGE
1707 {
1708 RTGCPHYS uAddr;
1709 uint32_t uSize;
1710 } arrRanges[16]; /** @todo Use a define. */
1711
1712 size_t cRanges = 0;
1713
1714 for (uint16_t i = 0; i < pStreamShared->u16LVI + 1; i++)
1715 {
1716 HDABDLE BDLE;
1717 rc = hdaR3BDLEFetch(pDevIns, &BDLE, pStreamShared->u64BDLBase, i /* Index */);
1718 if (RT_FAILURE(rc))
1719 break;
1720
1721 bool fAddRange = true;
1722 BDLERANGE *pRange;
1723
1724 if (cRanges)
1725 {
1726 pRange = &arrRanges[cRanges - 1];
1727
1728 /* Is the current range a direct neighbor of the current BLDE? */
1729 if ((pRange->uAddr + pRange->uSize) == BDLE.Desc.u64BufAddr)
1730 {
1731 /* Expand the current range by the current BDLE's size. */
1732 pRange->uSize += BDLE.Desc.u32BufSize;
1733
1734 /* Adding a new range in this case is not needed anymore. */
1735 fAddRange = false;
1736
1737 LogFunc(("Expanding range %zu by %RU32 (%RU32 total now)\n", cRanges - 1, BDLE.Desc.u32BufSize, pRange->uSize));
1738 }
1739 }
1740
1741 /* Do we need to add a new range? */
1742 if ( fAddRange
1743 && cRanges < RT_ELEMENTS(arrRanges))
1744 {
1745 pRange = &arrRanges[cRanges];
1746
1747 pRange->uAddr = BDLE.Desc.u64BufAddr;
1748 pRange->uSize = BDLE.Desc.u32BufSize;
1749
1750 LogFunc(("Adding range %zu - 0x%x (%RU32)\n", cRanges, pRange->uAddr, pRange->uSize));
1751
1752 cRanges++;
1753 }
1754 }
1755
1756 LogFunc(("%zu ranges total\n", cRanges));
1757
1758 /*
1759 * Register all ranges as DMA access handlers.
1760 */
1761
1762 for (size_t i = 0; i < cRanges; i++)
1763 {
1764 BDLERANGE *pRange = &arrRanges[i];
1765
1766 PHDADMAACCESSHANDLER pHandler = (PHDADMAACCESSHANDLER)RTMemAllocZ(sizeof(HDADMAACCESSHANDLER));
1767 if (!pHandler)
1768 {
1769 rc = VERR_NO_MEMORY;
1770 break;
1771 }
1772
1773 RTListAppend(&pStream->State.lstDMAHandlers, &pHandler->Node);
1774
1775 pHandler->pStream = pStream; /* Save a back reference to the owner. */
1776
1777 char szDesc[32];
1778 RTStrPrintf(szDesc, sizeof(szDesc), "HDA[SD%RU8 - RANGE%02zu]", pStream->u8SD, i);
1779
1780 int rc2 = PGMR3HandlerPhysicalTypeRegister(PDMDevHlpGetVM(pStream->pHDAState->pDevInsR3), PGMPHYSHANDLERKIND_WRITE,
1781 hdaDMAAccessHandler,
1782 NULL, NULL, NULL,
1783 NULL, NULL, NULL,
1784 szDesc, &pHandler->hAccessHandlerType);
1785 AssertRCBreak(rc2);
1786
1787 pHandler->BDLEAddr = pRange->uAddr;
1788 pHandler->BDLESize = pRange->uSize;
1789
1790 /* Get first and last pages of the BDLE range. */
1791 RTGCPHYS pgFirst = pRange->uAddr & ~PAGE_OFFSET_MASK;
1792 RTGCPHYS pgLast = RT_ALIGN(pgFirst + pRange->uSize, PAGE_SIZE);
1793
1794 /* Calculate the region size (in pages). */
1795 RTGCPHYS regionSize = RT_ALIGN(pgLast - pgFirst, PAGE_SIZE);
1796
1797 pHandler->GCPhysFirst = pgFirst;
1798 pHandler->GCPhysLast = pHandler->GCPhysFirst + (regionSize - 1);
1799
1800 LogFunc(("\tRegistering region '%s': 0x%x - 0x%x (region size: %zu)\n",
1801 szDesc, pHandler->GCPhysFirst, pHandler->GCPhysLast, regionSize));
1802 LogFunc(("\tBDLE @ 0x%x - 0x%x (%RU32)\n",
1803 pHandler->BDLEAddr, pHandler->BDLEAddr + pHandler->BDLESize, pHandler->BDLESize));
1804
1805 rc2 = PGMHandlerPhysicalRegister(PDMDevHlpGetVM(pStream->pHDAState->pDevInsR3),
1806 pHandler->GCPhysFirst, pHandler->GCPhysLast,
1807 pHandler->hAccessHandlerType, pHandler, NIL_RTR0PTR, NIL_RTRCPTR,
1808 szDesc);
1809 AssertRCBreak(rc2);
1810
1811 pHandler->fRegistered = true;
1812 }
1813
1814 LogFunc(("Registration ended with rc=%Rrc\n", rc));
1815
1816 return RT_SUCCESS(rc);
1817}
1818
1819/**
1820 * Unregisters access handlers of a stream's BDLEs.
1821 *
1822 * @param pStream HDA stream to unregister BDLE access handlers for.
1823 */
1824void hdaR3StreamUnregisterDMAHandlers(PHDASTREAM pStream)
1825{
1826 LogFunc(("\n"));
1827
1828 PHDADMAACCESSHANDLER pHandler, pHandlerNext;
1829 RTListForEachSafe(&pStream->State.lstDMAHandlers, pHandler, pHandlerNext, HDADMAACCESSHANDLER, Node)
1830 {
1831 if (!pHandler->fRegistered) /* Handler not registered? Skip. */
1832 continue;
1833
1834 LogFunc(("Unregistering 0x%x - 0x%x (%zu)\n",
1835 pHandler->GCPhysFirst, pHandler->GCPhysLast, pHandler->GCPhysLast - pHandler->GCPhysFirst));
1836
1837 int rc2 = PGMHandlerPhysicalDeregister(PDMDevHlpGetVM(pStream->pHDAState->pDevInsR3),
1838 pHandler->GCPhysFirst);
1839 AssertRC(rc2);
1840
1841 RTListNodeRemove(&pHandler->Node);
1842
1843 RTMemFree(pHandler);
1844 pHandler = NULL;
1845 }
1846
1847 Assert(RTListIsEmpty(&pStream->State.lstDMAHandlers));
1848}
1849# endif /* HDA_USE_DMA_ACCESS_HANDLER */
1850
1851# ifdef VBOX_WITH_AUDIO_HDA_ASYNC_IO
1852/**
1853 * @callback_method_impl{FNRTTHREAD,
1854 * Asynchronous I/O thread for a HDA stream.
1855 *
1856 * This will do the heavy lifting work for us as soon as it's getting notified
1857 * by another thread.}
1858 */
1859static DECLCALLBACK(int) hdaR3StreamAsyncIOThread(RTTHREAD hThreadSelf, void *pvUser)
1860{
1861 PHDASTREAMR3 const pStreamR3 = (PHDASTREAMR3)pvUser;
1862 PHDASTREAMSTATEAIO const pAIO = &pStreamR3->State.AIO;
1863 PHDASTATE const pThis = pStreamR3->pHDAStateShared;
1864 PHDASTATER3 const pThisCC = pStreamR3->pHDAStateR3;
1865 PPDMDEVINS const pDevIns = pThisCC->pDevIns;
1866 PHDASTREAM const pStreamShared = &pThis->aStreams[pStreamR3 - &pThisCC->aStreams[0]];
1867 Assert(pStreamR3 - &pThisCC->aStreams[0] == pStreamR3->u8SD);
1868 Assert(pStreamShared->u8SD == pStreamR3->u8SD);
1869
1870 /* Signal parent thread that we've started */
1871 ASMAtomicXchgBool(&pAIO->fStarted, true);
1872 RTThreadUserSignal(hThreadSelf);
1873
1874 LogFunc(("[SD%RU8] Started\n", pStreamShared->u8SD));
1875
1876 for (;;)
1877 {
1878 int rc2 = RTSemEventWait(pAIO->hEvent, RT_INDEFINITE_WAIT);
1879 if (RT_FAILURE(rc2))
1880 break;
1881
1882 if (ASMAtomicReadBool(&pAIO->fShutdown))
1883 break;
1884
1885 rc2 = RTCritSectEnter(&pAIO->CritSect);
1886 AssertRC(rc2);
1887 if (RT_SUCCESS(rc2))
1888 {
1889 if (!pAIO->fEnabled)
1890 {
1891 RTCritSectLeave(&pAIO->CritSect);
1892 continue;
1893 }
1894
1895 hdaR3StreamUpdate(pDevIns, pThis, pThisCC, pStreamShared, pStreamR3, false /* fInTimer */);
1896
1897 int rc3 = RTCritSectLeave(&pAIO->CritSect);
1898 AssertRC(rc3);
1899 }
1900 }
1901
1902 LogFunc(("[SD%RU8] Ended\n", pStreamShared->u8SD));
1903 ASMAtomicXchgBool(&pAIO->fStarted, false);
1904
1905 return VINF_SUCCESS;
1906}
1907
1908/**
1909 * Creates the async I/O thread for a specific HDA audio stream.
1910 *
1911 * @returns IPRT status code.
1912 * @param pStreamR3 HDA audio stream to create the async I/O thread for.
1913 */
1914int hdaR3StreamAsyncIOCreate(PHDASTREAMR3 pStreamR3)
1915{
1916 PHDASTREAMSTATEAIO pAIO = &pStreamR3->State.AIO;
1917
1918 int rc;
1919
1920 if (!ASMAtomicReadBool(&pAIO->fStarted))
1921 {
1922 pAIO->fShutdown = false;
1923 pAIO->fEnabled = true; /* Enabled by default. */
1924
1925 rc = RTSemEventCreate(&pAIO->hEvent);
1926 if (RT_SUCCESS(rc))
1927 {
1928 rc = RTCritSectInit(&pAIO->CritSect);
1929 if (RT_SUCCESS(rc))
1930 {
1931 rc = RTThreadCreateF(&pAIO->hThread, hdaR3StreamAsyncIOThread, pStreamR3, 0 /*cbStack*/,
1932 RTTHREADTYPE_IO, RTTHREADFLAGS_WAITABLE, "hdaAIO%RU8", pStreamR3->u8SD);
1933 if (RT_SUCCESS(rc))
1934 rc = RTThreadUserWait(pAIO->hThread, 10 * 1000 /* 10s timeout */);
1935 }
1936 }
1937 }
1938 else
1939 rc = VINF_SUCCESS;
1940
1941 LogFunc(("[SD%RU8] Returning %Rrc\n", pStreamR3->u8SD, rc));
1942 return rc;
1943}
1944
1945/**
1946 * Destroys the async I/O thread of a specific HDA audio stream.
1947 *
1948 * @returns IPRT status code.
1949 * @param pStreamR3 HDA audio stream to destroy the async I/O thread for.
1950 */
1951static int hdaR3StreamAsyncIODestroy(PHDASTREAMR3 pStreamR3)
1952{
1953 PHDASTREAMSTATEAIO pAIO = &pStreamR3->State.AIO;
1954
1955 if (!ASMAtomicReadBool(&pAIO->fStarted))
1956 return VINF_SUCCESS;
1957
1958 ASMAtomicWriteBool(&pAIO->fShutdown, true);
1959
1960 int rc = hdaR3StreamAsyncIONotify(pStreamR3);
1961 AssertRC(rc);
1962
1963 int rcThread;
1964 rc = RTThreadWait(pAIO->hThread, 30 * 1000 /* 30s timeout */, &rcThread);
1965 LogFunc(("Async I/O thread ended with %Rrc (%Rrc)\n", rc, rcThread));
1966
1967 if (RT_SUCCESS(rc))
1968 {
1969 pAIO->hThread = NIL_RTTHREAD;
1970
1971 rc = RTCritSectDelete(&pAIO->CritSect);
1972 AssertRC(rc);
1973
1974 rc = RTSemEventDestroy(pAIO->hEvent);
1975 AssertRC(rc);
1976 pAIO->hEvent = NIL_RTSEMEVENT;
1977
1978 pAIO->fStarted = false;
1979 pAIO->fShutdown = false;
1980 pAIO->fEnabled = false;
1981 }
1982
1983 LogFunc(("[SD%RU8] Returning %Rrc\n", pStreamR3->u8SD, rc));
1984 return rc;
1985}
1986
1987/**
1988 * Lets the stream's async I/O thread know that there is some data to process.
1989 *
1990 * @returns IPRT status code.
1991 * @param pStreamR3 HDA stream to notify async I/O thread for.
1992 */
1993static int hdaR3StreamAsyncIONotify(PHDASTREAMR3 pStreamR3)
1994{
1995 return RTSemEventSignal(pStreamR3->State.AIO.hEvent);
1996}
1997
1998/**
1999 * Locks the async I/O thread of a specific HDA audio stream.
2000 *
2001 * @param pStreamR3 HDA stream to lock async I/O thread for.
2002 */
2003void hdaR3StreamAsyncIOLock(PHDASTREAMR3 pStreamR3)
2004{
2005 PHDASTREAMSTATEAIO pAIO = &pStreamR3->State.AIO;
2006
2007 if (!ASMAtomicReadBool(&pAIO->fStarted))
2008 return;
2009
2010 int rc2 = RTCritSectEnter(&pAIO->CritSect);
2011 AssertRC(rc2);
2012}
2013
2014/**
2015 * Unlocks the async I/O thread of a specific HDA audio stream.
2016 *
2017 * @param pStreamR3 HDA stream to unlock async I/O thread for.
2018 */
2019void hdaR3StreamAsyncIOUnlock(PHDASTREAMR3 pStreamR3)
2020{
2021 PHDASTREAMSTATEAIO pAIO = &pStreamR3->State.AIO;
2022
2023 if (!ASMAtomicReadBool(&pAIO->fStarted))
2024 return;
2025
2026 int rc2 = RTCritSectLeave(&pAIO->CritSect);
2027 AssertRC(rc2);
2028}
2029
2030/**
2031 * Enables (resumes) or disables (pauses) the async I/O thread.
2032 *
2033 * @param pStreamR3 HDA stream to enable/disable async I/O thread for.
2034 * @param fEnable Whether to enable or disable the I/O thread.
2035 *
2036 * @remarks Does not do locking.
2037 */
2038void hdaR3StreamAsyncIOEnable(PHDASTREAMR3 pStreamR3, bool fEnable)
2039{
2040 PHDASTREAMSTATEAIO pAIO = &pStreamR3->State.AIO;
2041 ASMAtomicXchgBool(&pAIO->fEnabled, fEnable);
2042}
2043# endif /* VBOX_WITH_AUDIO_HDA_ASYNC_IO */
2044
2045#endif /* IN_RING3 */
2046
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