VirtualBox

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

Last change on this file since 82453 was 82452, checked in by vboxsync, 5 years ago

DevHDA: Put debug path on the heap rather than always grabbing ~4KB of state data for it. doxygen and scm fixes. bugref:9218

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