VirtualBox

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

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

Audio/HDA: Implemented adaptive stream timer Hz rates, based on the stream's channel count.

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