VirtualBox

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

Last change on this file since 79756 was 78506, checked in by vboxsync, 6 years ago

Audio: Try to fix a hang w/ VRDE audio driver enabled.

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