VirtualBox

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

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

Audio/HDA: Also set device schedule hint on stream initialization (like for AC'97 and SB16), useful for debugging.

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 69.8 KB
Line 
1/* $Id: HDAStream.cpp 76672 2019-01-07 12:19:53Z 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 (RT_FAILURE(rc))
876 break;
877
878 Assert(cbLeft >= cbWritten);
879 cbLeft -= cbWritten;
880
881 cbReadTotal += cbWritten;
882 }
883
884 if (pcbRead)
885 *pcbRead = cbReadTotal;
886
887 return rc;
888}
889
890/**
891 * Transfers data of an HDA stream according to its usage (input / output).
892 *
893 * For an SDO (output) stream this means reading DMA data from the device to
894 * the HDA stream's internal FIFO buffer.
895 *
896 * For an SDI (input) stream this is reading audio data from the HDA stream's
897 * internal FIFO buffer and writing it as DMA data to the device.
898 *
899 * @returns IPRT status code.
900 * @param pStream HDA stream to update.
901 * @param cbToProcessMax How much data (in bytes) to process as maximum.
902 */
903int hdaR3StreamTransfer(PHDASTREAM pStream, uint32_t cbToProcessMax)
904{
905 AssertPtrReturn(pStream, VERR_INVALID_POINTER);
906
907 hdaR3StreamLock(pStream);
908
909 PHDASTATE pThis = pStream->pHDAState;
910 AssertPtr(pThis);
911
912 PHDASTREAMPERIOD pPeriod = &pStream->State.Period;
913 if (!hdaR3StreamPeriodLock(pPeriod))
914 return VERR_ACCESS_DENIED;
915
916 bool fProceed = true;
917
918 /* Stream not running? */
919 if (!pStream->State.fRunning)
920 {
921 Log3Func(("[SD%RU8] Not running\n", pStream->u8SD));
922 fProceed = false;
923 }
924 else if (HDA_STREAM_REG(pThis, STS, pStream->u8SD) & HDA_SDSTS_BCIS)
925 {
926 Log3Func(("[SD%RU8] BCIS bit set\n", pStream->u8SD));
927 fProceed = false;
928 }
929
930 if (!fProceed)
931 {
932 hdaR3StreamPeriodUnlock(pPeriod);
933 hdaR3StreamUnlock(pStream);
934 return VINF_SUCCESS;
935 }
936
937 const uint64_t tsNow = TMTimerGet(pStream->pTimer);
938
939 if (!pStream->State.tsTransferLast)
940 pStream->State.tsTransferLast = tsNow;
941
942#ifdef DEBUG
943 const int64_t iTimerDelta = tsNow - pStream->State.tsTransferLast;
944 Log3Func(("[SD%RU8] Time now=%RU64, last=%RU64 -> %RI64 ticks delta\n",
945 pStream->u8SD, tsNow, pStream->State.tsTransferLast, iTimerDelta));
946#endif
947
948 pStream->State.tsTransferLast = tsNow;
949
950 /* Sanity checks. */
951 Assert(pStream->u8SD < HDA_MAX_STREAMS);
952 Assert(pStream->u64BDLBase);
953 Assert(pStream->u32CBL);
954 Assert(pStream->u16FIFOS);
955
956 /* State sanity checks. */
957 Assert(ASMAtomicReadBool(&pStream->State.fInReset) == false);
958
959 int rc = VINF_SUCCESS;
960
961 /* Fetch first / next BDL entry. */
962 PHDABDLE pBDLE = &pStream->State.BDLE;
963 if (hdaR3BDLEIsComplete(pBDLE))
964 {
965 rc = hdaR3BDLEFetch(pThis, pBDLE, pStream->u64BDLBase, pStream->State.uCurBDLE);
966 AssertRC(rc);
967 }
968
969 uint32_t cbToProcess = RT_MIN(pStream->State.cbTransferSize - pStream->State.cbTransferProcessed,
970 pStream->State.cbTransferChunk);
971
972 Log3Func(("[SD%RU8] cbToProcess=%RU32, cbToProcessMax=%RU32\n", pStream->u8SD, cbToProcess, cbToProcessMax));
973
974 if (cbToProcess > cbToProcessMax)
975 {
976 LogFunc(("[SD%RU8] Limiting transfer (cbToProcess=%RU32, cbToProcessMax=%RU32)\n",
977 pStream->u8SD, cbToProcess, cbToProcessMax));
978
979 /* Never process more than a stream currently can handle. */
980 cbToProcess = cbToProcessMax;
981 }
982
983 uint32_t cbProcessed = 0;
984 uint32_t cbLeft = cbToProcess;
985
986 uint8_t abChunk[HDA_FIFO_MAX + 1];
987 while (cbLeft)
988 {
989 /* Limit the chunk to the stream's FIFO size and what's left to process. */
990 uint32_t cbChunk = RT_MIN(cbLeft, pStream->u16FIFOS);
991
992 /* Limit the chunk to the remaining data of the current BDLE. */
993 cbChunk = RT_MIN(cbChunk, pBDLE->Desc.u32BufSize - pBDLE->State.u32BufOff);
994
995 /* If there are position adjustment frames left to be processed,
996 * make sure that we process them first as a whole. */
997 if (pStream->State.cfPosAdjustLeft)
998 cbChunk = RT_MIN(cbChunk, uint32_t(pStream->State.cfPosAdjustLeft * pStream->State.Mapping.cbFrameSize));
999
1000 Log3Func(("[SD%RU8] cbChunk=%RU32, cPosAdjustFramesLeft=%RU16\n",
1001 pStream->u8SD, cbChunk, pStream->State.cfPosAdjustLeft));
1002
1003 if (!cbChunk)
1004 break;
1005
1006 uint32_t cbDMA = 0;
1007 PRTCIRCBUF pCircBuf = pStream->State.pCircBuf;
1008
1009 if (hdaGetDirFromSD(pStream->u8SD) == PDMAUDIODIR_IN) /* Input (SDI). */
1010 {
1011 STAM_PROFILE_START(&pThis->StatIn, a);
1012
1013 uint32_t cbDMAWritten = 0;
1014 uint32_t cbDMAToWrite = cbChunk;
1015
1016 /** @todo Do we need interleaving streams support here as well?
1017 * Never saw anything else besides mono/stereo mics (yet). */
1018 while (cbDMAToWrite)
1019 {
1020 void *pvBuf; size_t cbBuf;
1021 RTCircBufAcquireReadBlock(pCircBuf, cbDMAToWrite, &pvBuf, &cbBuf);
1022
1023 if ( !cbBuf
1024 && !RTCircBufUsed(pCircBuf))
1025 break;
1026
1027 memcpy(abChunk + cbDMAWritten, pvBuf, cbBuf);
1028
1029 RTCircBufReleaseReadBlock(pCircBuf, cbBuf);
1030
1031 Assert(cbDMAToWrite >= cbBuf);
1032 cbDMAToWrite -= (uint32_t)cbBuf;
1033 cbDMAWritten += (uint32_t)cbBuf;
1034 Assert(cbDMAWritten <= cbChunk);
1035 }
1036
1037 if (cbDMAToWrite)
1038 {
1039 LogRel2(("HDA: FIFO underflow for stream #%RU8 (%RU32 bytes outstanding)\n", pStream->u8SD, cbDMAToWrite));
1040
1041 Assert(cbChunk == cbDMAWritten + cbDMAToWrite);
1042 memset((uint8_t *)abChunk + cbDMAWritten, 0, cbDMAToWrite);
1043 cbDMAWritten = cbChunk;
1044 }
1045
1046 rc = hdaR3DMAWrite(pThis, pStream, abChunk, cbDMAWritten, &cbDMA /* pcbWritten */);
1047 if (RT_FAILURE(rc))
1048 LogRel(("HDA: Writing to stream #%RU8 DMA failed with %Rrc\n", pStream->u8SD, rc));
1049
1050 STAM_PROFILE_STOP(&pThis->StatIn, a);
1051 }
1052 else if (hdaGetDirFromSD(pStream->u8SD) == PDMAUDIODIR_OUT) /* Output (SDO). */
1053 {
1054 STAM_PROFILE_START(&pThis->StatOut, a);
1055
1056 rc = hdaR3DMARead(pThis, pStream, abChunk, cbChunk, &cbDMA /* pcbRead */);
1057 if (RT_SUCCESS(rc))
1058 {
1059 const uint32_t cbFree = (uint32_t)RTCircBufFree(pCircBuf);
1060
1061 /*
1062 * Most guests don't use different stream frame sizes than
1063 * the default one, so save a bit of CPU time and don't go into
1064 * the frame extraction code below.
1065 *
1066 * Only macOS guests need the frame extraction branch below at the moment AFAIK.
1067 */
1068 if (pStream->State.Mapping.cbFrameSize == HDA_FRAME_SIZE_DEFAULT)
1069 {
1070 uint32_t cbDMARead = 0;
1071 uint32_t cbDMALeft = RT_MIN(cbDMA, cbFree);
1072
1073 while (cbDMALeft)
1074 {
1075 void *pvBuf; size_t cbBuf;
1076 RTCircBufAcquireWriteBlock(pCircBuf, cbDMALeft, &pvBuf, &cbBuf);
1077
1078 if (cbBuf)
1079 {
1080 memcpy(pvBuf, abChunk + cbDMARead, cbBuf);
1081 cbDMARead += (uint32_t)cbBuf;
1082 cbDMALeft -= (uint32_t)cbBuf;
1083 }
1084
1085 RTCircBufReleaseWriteBlock(pCircBuf, cbBuf);
1086 }
1087 }
1088 else
1089 {
1090 /*
1091 * The following code extracts the required audio stream (channel) data
1092 * of non-interleaved *and* interleaved audio streams.
1093 *
1094 * We by default only support 2 channels with 16-bit samples (HDA_FRAME_SIZE),
1095 * but an HDA audio stream can have interleaved audio data of multiple audio
1096 * channels in such a single stream ("AA,AA,AA vs. AA,BB,AA,BB").
1097 *
1098 * So take this into account by just handling the first channel in such a stream ("A")
1099 * and just discard the other channel's data.
1100 *
1101 * I know, the following code is horribly slow, but seems to work for now.
1102 ** @todo Optimize channel data extraction! Use some SSE(3) / intrinsics?
1103 */
1104 for (unsigned m = 0; m < pStream->State.Mapping.cMappings; m++)
1105 {
1106 const uint32_t cbFrame = pStream->State.Mapping.cbFrameSize;
1107
1108 Assert(cbFree >= cbDMA);
1109
1110 PPDMAUDIOSTREAMMAP pMap = &pStream->State.Mapping.paMappings[m];
1111 AssertPtr(pMap);
1112
1113 Log3Func(("Mapping #%u: Start (cbDMA=%RU32, cbFrame=%RU32, cbOff=%RU32)\n",
1114 m, cbDMA, cbFrame, pMap->cbOff));
1115
1116 uint8_t *pbSrcBuf = abChunk;
1117 size_t cbSrcOff = pMap->cbOff;
1118 Assert(cbChunk >= cbSrcOff);
1119
1120 for (unsigned i = 0; i < cbDMA / cbFrame; i++)
1121 {
1122 void *pvDstBuf; size_t cbDstBuf;
1123 RTCircBufAcquireWriteBlock(pCircBuf, pMap->cbSize, &pvDstBuf, &cbDstBuf);
1124
1125 Assert(cbDstBuf >= pMap->cbSize);
1126
1127 if (cbDstBuf)
1128 {
1129 Log3Func(("Mapping #%u: Frame #%02u: cbSize=%zu, cbFirst=%zu, cbOff=%zu, cbDstBuf=%zu, cbSrcOff=%zu\n",
1130 m, i, pMap->cbSize, pMap->cbFirst, pMap->cbOff, cbDstBuf, cbSrcOff));
1131
1132 memcpy(pvDstBuf, pbSrcBuf + cbSrcOff, cbDstBuf);
1133
1134#if 0 /* Too slow, even for release builds, so disabled it. */
1135 if (pStream->Dbg.Runtime.fEnabled)
1136 DrvAudioHlpFileWrite(pStream->Dbg.Runtime.pFileDMAMapped, pvDstBuf, cbDstBuf,
1137 0 /* fFlags */);
1138#endif
1139 Assert(cbSrcOff <= cbDMA);
1140 if (cbSrcOff + cbFrame + pMap->cbFirst <= cbDMA)
1141 cbSrcOff += cbFrame + pMap->cbFirst;
1142
1143 Log3Func(("Mapping #%u: Frame #%02u: -> cbSrcOff=%zu\n", m, i, cbSrcOff));
1144 }
1145
1146 RTCircBufReleaseWriteBlock(pCircBuf, cbDstBuf);
1147 }
1148
1149 Log3Func(("Mapping #%u: End cbSize=%zu, cbDMA=%RU32, cbSrcOff=%zu\n",
1150 m, pMap->cbSize, cbDMA, cbSrcOff));
1151
1152 Assert(cbSrcOff <= cbDMA);
1153
1154 const uint32_t cbSrcLeft = cbDMA - (uint32_t)cbSrcOff;
1155 if (cbSrcLeft)
1156 {
1157 Log3Func(("Mapping #%u: cbSrcLeft=%RU32\n", m, cbSrcLeft));
1158
1159 if (cbSrcLeft >= pMap->cbSize)
1160 {
1161 void *pvDstBuf; size_t cbDstBuf;
1162 RTCircBufAcquireWriteBlock(pCircBuf, pMap->cbSize, &pvDstBuf, &cbDstBuf);
1163
1164 Assert(cbDstBuf >= pMap->cbSize);
1165
1166 if (cbDstBuf)
1167 {
1168 memcpy(pvDstBuf, pbSrcBuf + cbSrcOff, cbDstBuf);
1169 }
1170
1171 RTCircBufReleaseWriteBlock(pCircBuf, cbDstBuf);
1172 }
1173
1174 Assert(pMap->cbFrame >= cbSrcLeft);
1175 pMap->cbOff = pMap->cbFrame - cbSrcLeft;
1176 }
1177 else
1178 pMap->cbOff = 0;
1179
1180 Log3Func(("Mapping #%u finish (cbSrcOff=%zu, cbOff=%zu)\n", m, cbSrcOff, pMap->cbOff));
1181 }
1182 }
1183 }
1184 else
1185 LogRel(("HDA: Reading from stream #%RU8 DMA failed with %Rrc\n", pStream->u8SD, rc));
1186
1187 STAM_PROFILE_STOP(&pThis->StatOut, a);
1188 }
1189
1190 else /** @todo Handle duplex streams? */
1191 AssertFailed();
1192
1193 if (cbDMA)
1194 {
1195 /* We always increment the position of DMA buffer counter because we're always reading
1196 * into an intermediate DMA buffer. */
1197 pBDLE->State.u32BufOff += (uint32_t)cbDMA;
1198 Assert(pBDLE->State.u32BufOff <= pBDLE->Desc.u32BufSize);
1199
1200 /* Are we done doing the position adjustment?
1201 * Only then do the transfer accounting .*/
1202 if (pStream->State.cfPosAdjustLeft == 0)
1203 {
1204 Assert(cbLeft >= cbDMA);
1205 cbLeft -= cbDMA;
1206
1207 cbProcessed += cbDMA;
1208 }
1209
1210 /*
1211 * Update the stream's current position.
1212 * Do this as accurate and close to the actual data transfer as possible.
1213 * All guetsts rely on this, depending on the mechanism they use (LPIB register or DMA counters).
1214 */
1215 uint32_t cbStreamPos = hdaR3StreamGetPosition(pThis, pStream);
1216 if (cbStreamPos == pStream->u32CBL)
1217 cbStreamPos = 0;
1218
1219 hdaR3StreamSetPosition(pStream, cbStreamPos + cbDMA);
1220 }
1221
1222 if (hdaR3BDLEIsComplete(pBDLE))
1223 {
1224 Log3Func(("[SD%RU8] Complete: %R[bdle]\n", pStream->u8SD, pBDLE));
1225
1226 /* Does the current BDLE require an interrupt to be sent? */
1227 if ( hdaR3BDLENeedsInterrupt(pBDLE)
1228 /* Are we done doing the position adjustment?
1229 * It can happen that a BDLE which is handled while doing the
1230 * position adjustment requires an interrupt on completion (IOC) being set.
1231 *
1232 * In such a case we need to skip such an interrupt and just move on. */
1233 && pStream->State.cfPosAdjustLeft == 0)
1234 {
1235 /* If the IOCE ("Interrupt On Completion Enable") bit of the SDCTL register is set
1236 * we need to generate an interrupt.
1237 */
1238 if (HDA_STREAM_REG(pThis, CTL, pStream->u8SD) & HDA_SDCTL_IOCE)
1239 {
1240 pStream->State.cTransferPendingInterrupts++;
1241
1242 AssertMsg(pStream->State.cTransferPendingInterrupts <= 32,
1243 ("Too many pending interrupts (%RU8) for stream #%RU8\n",
1244 pStream->State.cTransferPendingInterrupts, pStream->u8SD));
1245 }
1246 }
1247
1248 if (pStream->State.uCurBDLE == pStream->u16LVI)
1249 {
1250 pStream->State.uCurBDLE = 0;
1251 }
1252 else
1253 pStream->State.uCurBDLE++;
1254
1255 /* Fetch the next BDLE entry. */
1256 hdaR3BDLEFetch(pThis, pBDLE, pStream->u64BDLBase, pStream->State.uCurBDLE);
1257 }
1258
1259 /* Do the position adjustment accounting. */
1260 pStream->State.cfPosAdjustLeft -=
1261 RT_MIN(pStream->State.cfPosAdjustLeft, cbDMA / pStream->State.Mapping.cbFrameSize);
1262
1263 if (RT_FAILURE(rc))
1264 break;
1265 }
1266
1267 Log3Func(("[SD%RU8] cbToProcess=%RU32, cbProcessed=%RU32, cbLeft=%RU32, %R[bdle], rc=%Rrc\n",
1268 pStream->u8SD, cbToProcess, cbProcessed, cbLeft, pBDLE, rc));
1269
1270 /* Sanity. */
1271 Assert(cbProcessed == cbToProcess);
1272 Assert(cbLeft == 0);
1273
1274 /* Only do the data accounting if we don't have to do any position
1275 * adjustment anymore. */
1276 if (pStream->State.cfPosAdjustLeft == 0)
1277 {
1278 hdaR3StreamPeriodInc(pPeriod, RT_MIN(cbProcessed / pStream->State.Mapping.cbFrameSize,
1279 hdaR3StreamPeriodGetRemainingFrames(pPeriod)));
1280
1281 pStream->State.cbTransferProcessed += cbProcessed;
1282 }
1283
1284 /* Make sure that we never report more stuff processed than initially announced. */
1285 if (pStream->State.cbTransferProcessed > pStream->State.cbTransferSize)
1286 pStream->State.cbTransferProcessed = pStream->State.cbTransferSize;
1287
1288 uint32_t cbTransferLeft = pStream->State.cbTransferSize - pStream->State.cbTransferProcessed;
1289 bool fTransferComplete = !cbTransferLeft;
1290 uint64_t tsTransferNext = 0;
1291
1292 if (fTransferComplete)
1293 {
1294 /*
1295 * Try updating the wall clock.
1296 *
1297 * Note 1) Only certain guests (like Linux' snd_hda_intel) rely on the WALCLK register
1298 * in order to determine the correct timing of the sound device. Other guests
1299 * like Windows 7 + 10 (or even more exotic ones like Haiku) will completely
1300 * ignore this.
1301 *
1302 * Note 2) When updating the WALCLK register too often / early (or even in a non-monotonic
1303 * fashion) this *will* upset guest device drivers and will completely fuck up the
1304 * sound output. Running VLC on the guest will tell!
1305 */
1306 const bool fWalClkSet = hdaR3WalClkSet(pThis,
1307 hdaWalClkGetCurrent(pThis)
1308 + hdaR3StreamPeriodFramesToWalClk(pPeriod,
1309 pStream->State.cbTransferProcessed
1310 / pStream->State.Mapping.cbFrameSize),
1311 false /* fForce */);
1312 RT_NOREF(fWalClkSet);
1313 }
1314
1315 /* Does the period have any interrupts outstanding? */
1316 if (pStream->State.cTransferPendingInterrupts)
1317 {
1318 Log3Func(("[SD%RU8] Scheduling interrupt\n", pStream->u8SD));
1319
1320 /*
1321 * Set the stream's BCIS bit.
1322 *
1323 * Note: This only must be done if the whole period is complete, and not if only
1324 * one specific BDL entry is complete (if it has the IOC bit set).
1325 *
1326 * This will otherwise confuses the guest when it 1) deasserts the interrupt,
1327 * 2) reads SDSTS (with BCIS set) and then 3) too early reads a (wrong) WALCLK value.
1328 *
1329 * snd_hda_intel on Linux will tell.
1330 */
1331 HDA_STREAM_REG(pThis, STS, pStream->u8SD) |= HDA_SDSTS_BCIS;
1332
1333 /* Trigger an interrupt first and let hdaRegWriteSDSTS() deal with
1334 * ending / beginning a period. */
1335#ifndef LOG_ENABLED
1336 hdaProcessInterrupt(pThis);
1337#else
1338 hdaProcessInterrupt(pThis, __FUNCTION__);
1339#endif
1340 }
1341 else /* Transfer still in-flight -- schedule the next timing slot. */
1342 {
1343 uint32_t cbTransferNext = cbTransferLeft;
1344
1345 /* No data left to transfer anymore or do we have more data left
1346 * than we can transfer per timing slot? Clamp. */
1347 if ( !cbTransferNext
1348 || cbTransferNext > pStream->State.cbTransferChunk)
1349 {
1350 cbTransferNext = pStream->State.cbTransferChunk;
1351 }
1352
1353 tsTransferNext = tsNow + (cbTransferNext * pStream->State.cTicksPerByte);
1354
1355 /*
1356 * If the current transfer is complete, reset our counter.
1357 *
1358 * This can happen for examlpe if the guest OS (like macOS) sets up
1359 * big BDLEs without IOC bits set (but for the last one) and the
1360 * transfer is complete before we reach such a BDL entry.
1361 */
1362 if (fTransferComplete)
1363 pStream->State.cbTransferProcessed = 0;
1364 }
1365
1366 /* If we need to do another transfer, (re-)arm the device timer. */
1367 if (tsTransferNext) /* Can be 0 if no next transfer is needed. */
1368 {
1369 Log3Func(("[SD%RU8] Scheduling timer\n", pStream->u8SD));
1370
1371 TMTimerUnlock(pStream->pTimer);
1372
1373 LogFunc(("Timer set SD%RU8\n", pStream->u8SD));
1374 hdaR3TimerSet(pStream->pHDAState, pStream, tsTransferNext, false /* fForce */);
1375
1376 TMTimerLock(pStream->pTimer, VINF_SUCCESS);
1377
1378 pStream->State.tsTransferNext = tsTransferNext;
1379 }
1380
1381 pStream->State.tsTransferLast = tsNow;
1382
1383 Log3Func(("[SD%RU8] cbTransferLeft=%RU32 -- %RU32/%RU32\n",
1384 pStream->u8SD, cbTransferLeft, pStream->State.cbTransferProcessed, pStream->State.cbTransferSize));
1385 Log3Func(("[SD%RU8] fTransferComplete=%RTbool, cTransferPendingInterrupts=%RU8\n",
1386 pStream->u8SD, fTransferComplete, pStream->State.cTransferPendingInterrupts));
1387 Log3Func(("[SD%RU8] tsNow=%RU64, tsTransferNext=%RU64 (in %RU64 ticks)\n",
1388 pStream->u8SD, tsNow, tsTransferNext, tsTransferNext - tsNow));
1389
1390 hdaR3StreamPeriodUnlock(pPeriod);
1391 hdaR3StreamUnlock(pStream);
1392
1393 return VINF_SUCCESS;
1394}
1395
1396/**
1397 * Updates a HDA stream by doing its required data transfers.
1398 * The host sink(s) set the overall pace.
1399 *
1400 * This routine is called by both, the synchronous and the asynchronous, implementations.
1401 *
1402 * This routine is called by both, the synchronous and the asynchronous
1403 * (VBOX_WITH_AUDIO_HDA_ASYNC_IO), implementations.
1404 *
1405 * When running synchronously, the device DMA transfers *and* the mixer sink
1406 * processing is within the device timer.
1407 *
1408 * When running asynchronously, only the device DMA transfers are done in the
1409 * device timer, whereas the mixer sink processing then is done in the stream's
1410 * own async I/O thread. This thread also will call this function
1411 * (with fInTimer set to @c false).
1412 *
1413 * @param pStream HDA stream to update.
1414 * @param fInTimer Whether to this function was called from the timer
1415 * context or an asynchronous I/O stream thread (if supported).
1416 */
1417void hdaR3StreamUpdate(PHDASTREAM pStream, bool fInTimer)
1418{
1419 if (!pStream)
1420 return;
1421
1422 PAUDMIXSINK pSink = NULL;
1423 if ( pStream->pMixSink
1424 && pStream->pMixSink->pMixSink)
1425 {
1426 pSink = pStream->pMixSink->pMixSink;
1427 }
1428
1429 if (!AudioMixerSinkIsActive(pSink)) /* No sink available? Bail out. */
1430 return;
1431
1432 int rc2;
1433
1434 if (hdaGetDirFromSD(pStream->u8SD) == PDMAUDIODIR_OUT) /* Output (SDO). */
1435 {
1436 bool fDoRead = false; /* Whether to read from the HDA stream or not. */
1437
1438# ifdef VBOX_WITH_AUDIO_HDA_ASYNC_IO
1439 if (fInTimer)
1440# endif
1441 {
1442 const uint32_t cbStreamFree = hdaR3StreamGetFree(pStream);
1443 if (cbStreamFree)
1444 {
1445 /* Do the DMA transfer. */
1446 rc2 = hdaR3StreamTransfer(pStream, cbStreamFree);
1447 AssertRC(rc2);
1448 }
1449
1450 /* Only read from the HDA stream at the given scheduling rate. */
1451 const uint64_t tsNowNs = RTTimeNanoTS();
1452 if (tsNowNs - pStream->State.tsLastUpdateNs >= pStream->State.Cfg.Device.uSchedulingHintMs * RT_NS_1MS)
1453 {
1454 fDoRead = true;
1455 pStream->State.tsLastUpdateNs = tsNowNs;
1456 }
1457 }
1458
1459 Log3Func(("[SD%RU8] fInTimer=%RTbool, fDoRead=%RTbool\n", pStream->u8SD, fInTimer, fDoRead));
1460
1461# ifdef VBOX_WITH_AUDIO_HDA_ASYNC_IO
1462 if (fDoRead)
1463 {
1464 rc2 = hdaR3StreamAsyncIONotify(pStream);
1465 AssertRC(rc2);
1466 }
1467# endif
1468
1469# ifdef VBOX_WITH_AUDIO_HDA_ASYNC_IO
1470 if (!fInTimer) /* In async I/O thread */
1471 {
1472# else
1473 if (fDoRead)
1474 {
1475# endif
1476 const uint32_t cbSinkWritable = AudioMixerSinkGetWritable(pSink);
1477 const uint32_t cbStreamReadable = hdaR3StreamGetUsed(pStream);
1478 const uint32_t cbToReadFromStream = RT_MIN(cbStreamReadable, cbSinkWritable);
1479
1480 Log3Func(("[SD%RU8] cbSinkWritable=%RU32, cbStreamReadable=%RU32\n", pStream->u8SD, cbSinkWritable, cbStreamReadable));
1481
1482 if (cbToReadFromStream)
1483 {
1484 /* Read (guest output) data and write it to the stream's sink. */
1485 rc2 = hdaR3StreamRead(pStream, cbToReadFromStream, NULL);
1486 AssertRC(rc2);
1487 }
1488
1489 /* When running synchronously, update the associated sink here.
1490 * Otherwise this will be done in the async I/O thread. */
1491 rc2 = AudioMixerSinkUpdate(pSink);
1492 AssertRC(rc2);
1493 }
1494 }
1495 else /* Input (SDI). */
1496 {
1497# ifdef VBOX_WITH_AUDIO_HDA_ASYNC_IO
1498 if (!fInTimer)
1499 {
1500# endif
1501 rc2 = AudioMixerSinkUpdate(pSink);
1502 AssertRC(rc2);
1503
1504 /* Is the sink ready to be read (host input data) from? If so, by how much? */
1505 uint32_t cbSinkReadable = AudioMixerSinkGetReadable(pSink);
1506
1507 /* How much (guest input) data is available for writing at the moment for the HDA stream? */
1508 const uint32_t cbStreamFree = hdaR3StreamGetFree(pStream);
1509
1510 Log3Func(("[SD%RU8] cbSinkReadable=%RU32, cbStreamFree=%RU32\n", pStream->u8SD, cbSinkReadable, cbStreamFree));
1511
1512 /* Do not read more than the HDA stream can hold at the moment.
1513 * The host sets the overall pace. */
1514 if (cbSinkReadable > cbStreamFree)
1515 cbSinkReadable = cbStreamFree;
1516
1517 if (cbSinkReadable)
1518 {
1519 uint8_t abFIFO[HDA_FIFO_MAX + 1];
1520 while (cbSinkReadable)
1521 {
1522 uint32_t cbRead;
1523 rc2 = AudioMixerSinkRead(pSink, AUDMIXOP_COPY,
1524 abFIFO, RT_MIN(cbSinkReadable, (uint32_t)sizeof(abFIFO)), &cbRead);
1525 AssertRCBreak(rc2);
1526
1527 if (!cbRead)
1528 {
1529 AssertMsgFailed(("Nothing read from sink, even if %RU32 bytes were (still) announced\n", cbSinkReadable));
1530 break;
1531 }
1532
1533 /* Write (guest input) data to the stream which was read from stream's sink before. */
1534 uint32_t cbWritten;
1535 rc2 = hdaR3StreamWrite(pStream, abFIFO, cbRead, &cbWritten);
1536 AssertRCBreak(rc2);
1537
1538 if (!cbWritten)
1539 {
1540 AssertFailed(); /* Should never happen, as we know how much we can write. */
1541 break;
1542 }
1543
1544 Assert(cbSinkReadable >= cbRead);
1545 cbSinkReadable -= cbRead;
1546 }
1547 }
1548# ifdef VBOX_WITH_AUDIO_HDA_ASYNC_IO
1549 }
1550 else /* fInTimer */
1551 {
1552# endif
1553
1554# ifdef VBOX_WITH_AUDIO_HDA_ASYNC_IO
1555 const uint64_t tsNowNs = RTTimeNanoTS();
1556 if (tsNowNs - pStream->State.tsLastUpdateNs >= pStream->State.Cfg.Device.uSchedulingHintMs * RT_NS_1MS)
1557 {
1558 rc2 = hdaR3StreamAsyncIONotify(pStream);
1559 AssertRC(rc2);
1560
1561 pStream->State.tsLastUpdateNs = tsNowNs;
1562 }
1563# endif
1564 const uint32_t cbStreamUsed = hdaR3StreamGetUsed(pStream);
1565 if (cbStreamUsed)
1566 {
1567 rc2 = hdaR3StreamTransfer(pStream, cbStreamUsed);
1568 AssertRC(rc2);
1569 }
1570# ifdef VBOX_WITH_AUDIO_HDA_ASYNC_IO
1571 }
1572# endif
1573 }
1574}
1575
1576/**
1577 * Locks an HDA stream for serialized access.
1578 *
1579 * @returns IPRT status code.
1580 * @param pStream HDA stream to lock.
1581 */
1582void hdaR3StreamLock(PHDASTREAM pStream)
1583{
1584 AssertPtrReturnVoid(pStream);
1585 int rc2 = RTCritSectEnter(&pStream->CritSect);
1586 AssertRC(rc2);
1587}
1588
1589/**
1590 * Unlocks a formerly locked HDA stream.
1591 *
1592 * @returns IPRT status code.
1593 * @param pStream HDA stream to unlock.
1594 */
1595void hdaR3StreamUnlock(PHDASTREAM pStream)
1596{
1597 AssertPtrReturnVoid(pStream);
1598 int rc2 = RTCritSectLeave(&pStream->CritSect);
1599 AssertRC(rc2);
1600}
1601
1602/**
1603 * Updates an HDA stream's current read or write buffer position (depending on the stream type) by
1604 * updating its associated LPIB register and DMA position buffer (if enabled).
1605 *
1606 * @returns Set LPIB value.
1607 * @param pStream HDA stream to update read / write position for.
1608 * @param u32LPIB New LPIB (position) value to set.
1609 */
1610uint32_t hdaR3StreamUpdateLPIB(PHDASTREAM pStream, uint32_t u32LPIB)
1611{
1612 AssertPtrReturn(pStream, 0);
1613
1614 AssertMsg(u32LPIB <= pStream->u32CBL,
1615 ("[SD%RU8] New LPIB (%RU32) exceeds CBL (%RU32)\n", pStream->u8SD, u32LPIB, pStream->u32CBL));
1616
1617 const PHDASTATE pThis = pStream->pHDAState;
1618
1619 u32LPIB = RT_MIN(u32LPIB, pStream->u32CBL);
1620
1621 LogFlowFunc(("[SD%RU8] LPIB=%RU32 (DMA Position Buffer Enabled: %RTbool)\n",
1622 pStream->u8SD, u32LPIB, pThis->fDMAPosition));
1623
1624 /* Update LPIB in any case. */
1625 HDA_STREAM_REG(pThis, LPIB, pStream->u8SD) = u32LPIB;
1626
1627 /* Do we need to tell the current DMA position? */
1628 if (pThis->fDMAPosition)
1629 {
1630 int rc2 = PDMDevHlpPCIPhysWrite(pThis->CTX_SUFF(pDevIns),
1631 pThis->u64DPBase + (pStream->u8SD * 2 * sizeof(uint32_t)),
1632 (void *)&u32LPIB, sizeof(uint32_t));
1633 AssertRC(rc2);
1634 }
1635
1636 return u32LPIB;
1637}
1638
1639# ifdef HDA_USE_DMA_ACCESS_HANDLER
1640/**
1641 * Registers access handlers for a stream's BDLE DMA accesses.
1642 *
1643 * @returns true if registration was successful, false if not.
1644 * @param pStream HDA stream to register BDLE access handlers for.
1645 */
1646bool hdaR3StreamRegisterDMAHandlers(PHDASTREAM pStream)
1647{
1648 /* At least LVI and the BDL base must be set. */
1649 if ( !pStream->u16LVI
1650 || !pStream->u64BDLBase)
1651 {
1652 return false;
1653 }
1654
1655 hdaR3StreamUnregisterDMAHandlers(pStream);
1656
1657 LogFunc(("Registering ...\n"));
1658
1659 int rc = VINF_SUCCESS;
1660
1661 /*
1662 * Create BDLE ranges.
1663 */
1664
1665 struct BDLERANGE
1666 {
1667 RTGCPHYS uAddr;
1668 uint32_t uSize;
1669 } arrRanges[16]; /** @todo Use a define. */
1670
1671 size_t cRanges = 0;
1672
1673 for (uint16_t i = 0; i < pStream->u16LVI + 1; i++)
1674 {
1675 HDABDLE BDLE;
1676 rc = hdaR3BDLEFetch(pThis, &BDLE, pStream->u64BDLBase, i /* Index */);
1677 if (RT_FAILURE(rc))
1678 break;
1679
1680 bool fAddRange = true;
1681 BDLERANGE *pRange;
1682
1683 if (cRanges)
1684 {
1685 pRange = &arrRanges[cRanges - 1];
1686
1687 /* Is the current range a direct neighbor of the current BLDE? */
1688 if ((pRange->uAddr + pRange->uSize) == BDLE.Desc.u64BufAddr)
1689 {
1690 /* Expand the current range by the current BDLE's size. */
1691 pRange->uSize += BDLE.Desc.u32BufSize;
1692
1693 /* Adding a new range in this case is not needed anymore. */
1694 fAddRange = false;
1695
1696 LogFunc(("Expanding range %zu by %RU32 (%RU32 total now)\n", cRanges - 1, BDLE.Desc.u32BufSize, pRange->uSize));
1697 }
1698 }
1699
1700 /* Do we need to add a new range? */
1701 if ( fAddRange
1702 && cRanges < RT_ELEMENTS(arrRanges))
1703 {
1704 pRange = &arrRanges[cRanges];
1705
1706 pRange->uAddr = BDLE.Desc.u64BufAddr;
1707 pRange->uSize = BDLE.Desc.u32BufSize;
1708
1709 LogFunc(("Adding range %zu - 0x%x (%RU32)\n", cRanges, pRange->uAddr, pRange->uSize));
1710
1711 cRanges++;
1712 }
1713 }
1714
1715 LogFunc(("%zu ranges total\n", cRanges));
1716
1717 /*
1718 * Register all ranges as DMA access handlers.
1719 */
1720
1721 for (size_t i = 0; i < cRanges; i++)
1722 {
1723 BDLERANGE *pRange = &arrRanges[i];
1724
1725 PHDADMAACCESSHANDLER pHandler = (PHDADMAACCESSHANDLER)RTMemAllocZ(sizeof(HDADMAACCESSHANDLER));
1726 if (!pHandler)
1727 {
1728 rc = VERR_NO_MEMORY;
1729 break;
1730 }
1731
1732 RTListAppend(&pStream->State.lstDMAHandlers, &pHandler->Node);
1733
1734 pHandler->pStream = pStream; /* Save a back reference to the owner. */
1735
1736 char szDesc[32];
1737 RTStrPrintf(szDesc, sizeof(szDesc), "HDA[SD%RU8 - RANGE%02zu]", pStream->u8SD, i);
1738
1739 int rc2 = PGMR3HandlerPhysicalTypeRegister(PDMDevHlpGetVM(pStream->pHDAState->pDevInsR3), PGMPHYSHANDLERKIND_WRITE,
1740 hdaDMAAccessHandler,
1741 NULL, NULL, NULL,
1742 NULL, NULL, NULL,
1743 szDesc, &pHandler->hAccessHandlerType);
1744 AssertRCBreak(rc2);
1745
1746 pHandler->BDLEAddr = pRange->uAddr;
1747 pHandler->BDLESize = pRange->uSize;
1748
1749 /* Get first and last pages of the BDLE range. */
1750 RTGCPHYS pgFirst = pRange->uAddr & ~PAGE_OFFSET_MASK;
1751 RTGCPHYS pgLast = RT_ALIGN(pgFirst + pRange->uSize, PAGE_SIZE);
1752
1753 /* Calculate the region size (in pages). */
1754 RTGCPHYS regionSize = RT_ALIGN(pgLast - pgFirst, PAGE_SIZE);
1755
1756 pHandler->GCPhysFirst = pgFirst;
1757 pHandler->GCPhysLast = pHandler->GCPhysFirst + (regionSize - 1);
1758
1759 LogFunc(("\tRegistering region '%s': 0x%x - 0x%x (region size: %zu)\n",
1760 szDesc, pHandler->GCPhysFirst, pHandler->GCPhysLast, regionSize));
1761 LogFunc(("\tBDLE @ 0x%x - 0x%x (%RU32)\n",
1762 pHandler->BDLEAddr, pHandler->BDLEAddr + pHandler->BDLESize, pHandler->BDLESize));
1763
1764 rc2 = PGMHandlerPhysicalRegister(PDMDevHlpGetVM(pStream->pHDAState->pDevInsR3),
1765 pHandler->GCPhysFirst, pHandler->GCPhysLast,
1766 pHandler->hAccessHandlerType, pHandler, NIL_RTR0PTR, NIL_RTRCPTR,
1767 szDesc);
1768 AssertRCBreak(rc2);
1769
1770 pHandler->fRegistered = true;
1771 }
1772
1773 LogFunc(("Registration ended with rc=%Rrc\n", rc));
1774
1775 return RT_SUCCESS(rc);
1776}
1777
1778/**
1779 * Unregisters access handlers of a stream's BDLEs.
1780 *
1781 * @param pStream HDA stream to unregister BDLE access handlers for.
1782 */
1783void hdaR3StreamUnregisterDMAHandlers(PHDASTREAM pStream)
1784{
1785 LogFunc(("\n"));
1786
1787 PHDADMAACCESSHANDLER pHandler, pHandlerNext;
1788 RTListForEachSafe(&pStream->State.lstDMAHandlers, pHandler, pHandlerNext, HDADMAACCESSHANDLER, Node)
1789 {
1790 if (!pHandler->fRegistered) /* Handler not registered? Skip. */
1791 continue;
1792
1793 LogFunc(("Unregistering 0x%x - 0x%x (%zu)\n",
1794 pHandler->GCPhysFirst, pHandler->GCPhysLast, pHandler->GCPhysLast - pHandler->GCPhysFirst));
1795
1796 int rc2 = PGMHandlerPhysicalDeregister(PDMDevHlpGetVM(pStream->pHDAState->pDevInsR3),
1797 pHandler->GCPhysFirst);
1798 AssertRC(rc2);
1799
1800 RTListNodeRemove(&pHandler->Node);
1801
1802 RTMemFree(pHandler);
1803 pHandler = NULL;
1804 }
1805
1806 Assert(RTListIsEmpty(&pStream->State.lstDMAHandlers));
1807}
1808# endif /* HDA_USE_DMA_ACCESS_HANDLER */
1809
1810# ifdef VBOX_WITH_AUDIO_HDA_ASYNC_IO
1811/**
1812 * Asynchronous I/O thread for a HDA stream.
1813 * This will do the heavy lifting work for us as soon as it's getting notified by another thread.
1814 *
1815 * @returns IPRT status code.
1816 * @param hThreadSelf Thread handle.
1817 * @param pvUser User argument. Must be of type PHDASTREAMTHREADCTX.
1818 */
1819DECLCALLBACK(int) hdaR3StreamAsyncIOThread(RTTHREAD hThreadSelf, void *pvUser)
1820{
1821 PHDASTREAMTHREADCTX pCtx = (PHDASTREAMTHREADCTX)pvUser;
1822 AssertPtr(pCtx);
1823
1824 PHDASTREAM pStream = pCtx->pStream;
1825 AssertPtr(pStream);
1826
1827 PHDASTREAMSTATEAIO pAIO = &pCtx->pStream->State.AIO;
1828
1829 ASMAtomicXchgBool(&pAIO->fStarted, true);
1830
1831 RTThreadUserSignal(hThreadSelf);
1832
1833 LogFunc(("[SD%RU8] Started\n", pStream->u8SD));
1834
1835 for (;;)
1836 {
1837 int rc2 = RTSemEventWait(pAIO->Event, RT_INDEFINITE_WAIT);
1838 if (RT_FAILURE(rc2))
1839 break;
1840
1841 if (ASMAtomicReadBool(&pAIO->fShutdown))
1842 break;
1843
1844 rc2 = RTCritSectEnter(&pAIO->CritSect);
1845 if (RT_SUCCESS(rc2))
1846 {
1847 if (!pAIO->fEnabled)
1848 {
1849 RTCritSectLeave(&pAIO->CritSect);
1850 continue;
1851 }
1852
1853 hdaR3StreamUpdate(pStream, false /* fInTimer */);
1854
1855 int rc3 = RTCritSectLeave(&pAIO->CritSect);
1856 AssertRC(rc3);
1857 }
1858
1859 AssertRC(rc2);
1860 }
1861
1862 LogFunc(("[SD%RU8] Ended\n", pStream->u8SD));
1863
1864 ASMAtomicXchgBool(&pAIO->fStarted, false);
1865
1866 return VINF_SUCCESS;
1867}
1868
1869/**
1870 * Creates the async I/O thread for a specific HDA audio stream.
1871 *
1872 * @returns IPRT status code.
1873 * @param pStream HDA audio stream to create the async I/O thread for.
1874 */
1875int hdaR3StreamAsyncIOCreate(PHDASTREAM pStream)
1876{
1877 PHDASTREAMSTATEAIO pAIO = &pStream->State.AIO;
1878
1879 int rc;
1880
1881 if (!ASMAtomicReadBool(&pAIO->fStarted))
1882 {
1883 pAIO->fShutdown = false;
1884 pAIO->fEnabled = true; /* Enabled by default. */
1885
1886 rc = RTSemEventCreate(&pAIO->Event);
1887 if (RT_SUCCESS(rc))
1888 {
1889 rc = RTCritSectInit(&pAIO->CritSect);
1890 if (RT_SUCCESS(rc))
1891 {
1892 HDASTREAMTHREADCTX Ctx = { pStream->pHDAState, pStream };
1893
1894 char szThreadName[64];
1895 RTStrPrintf2(szThreadName, sizeof(szThreadName), "hdaAIO%RU8", pStream->u8SD);
1896
1897 rc = RTThreadCreate(&pAIO->Thread, hdaR3StreamAsyncIOThread, &Ctx,
1898 0, RTTHREADTYPE_IO, RTTHREADFLAGS_WAITABLE, szThreadName);
1899 if (RT_SUCCESS(rc))
1900 rc = RTThreadUserWait(pAIO->Thread, 10 * 1000 /* 10s timeout */);
1901 }
1902 }
1903 }
1904 else
1905 rc = VINF_SUCCESS;
1906
1907 LogFunc(("[SD%RU8] Returning %Rrc\n", pStream->u8SD, rc));
1908 return rc;
1909}
1910
1911/**
1912 * Destroys the async I/O thread of a specific HDA audio stream.
1913 *
1914 * @returns IPRT status code.
1915 * @param pStream HDA audio stream to destroy the async I/O thread for.
1916 */
1917int hdaR3StreamAsyncIODestroy(PHDASTREAM pStream)
1918{
1919 PHDASTREAMSTATEAIO pAIO = &pStream->State.AIO;
1920
1921 if (!ASMAtomicReadBool(&pAIO->fStarted))
1922 return VINF_SUCCESS;
1923
1924 ASMAtomicWriteBool(&pAIO->fShutdown, true);
1925
1926 int rc = hdaR3StreamAsyncIONotify(pStream);
1927 AssertRC(rc);
1928
1929 int rcThread;
1930 rc = RTThreadWait(pAIO->Thread, 30 * 1000 /* 30s timeout */, &rcThread);
1931 LogFunc(("Async I/O thread ended with %Rrc (%Rrc)\n", rc, rcThread));
1932
1933 if (RT_SUCCESS(rc))
1934 {
1935 rc = RTCritSectDelete(&pAIO->CritSect);
1936 AssertRC(rc);
1937
1938 rc = RTSemEventDestroy(pAIO->Event);
1939 AssertRC(rc);
1940
1941 pAIO->fStarted = false;
1942 pAIO->fShutdown = false;
1943 pAIO->fEnabled = false;
1944 }
1945
1946 LogFunc(("[SD%RU8] Returning %Rrc\n", pStream->u8SD, rc));
1947 return rc;
1948}
1949
1950/**
1951 * Lets the stream's async I/O thread know that there is some data to process.
1952 *
1953 * @returns IPRT status code.
1954 * @param pStream HDA stream to notify async I/O thread for.
1955 */
1956int hdaR3StreamAsyncIONotify(PHDASTREAM pStream)
1957{
1958 return RTSemEventSignal(pStream->State.AIO.Event);
1959}
1960
1961/**
1962 * Locks the async I/O thread of a specific HDA audio stream.
1963 *
1964 * @param pStream HDA stream to lock async I/O thread for.
1965 */
1966void hdaR3StreamAsyncIOLock(PHDASTREAM pStream)
1967{
1968 PHDASTREAMSTATEAIO pAIO = &pStream->State.AIO;
1969
1970 if (!ASMAtomicReadBool(&pAIO->fStarted))
1971 return;
1972
1973 int rc2 = RTCritSectEnter(&pAIO->CritSect);
1974 AssertRC(rc2);
1975}
1976
1977/**
1978 * Unlocks the async I/O thread of a specific HDA audio stream.
1979 *
1980 * @param pStream HDA stream to unlock async I/O thread for.
1981 */
1982void hdaR3StreamAsyncIOUnlock(PHDASTREAM pStream)
1983{
1984 PHDASTREAMSTATEAIO pAIO = &pStream->State.AIO;
1985
1986 if (!ASMAtomicReadBool(&pAIO->fStarted))
1987 return;
1988
1989 int rc2 = RTCritSectLeave(&pAIO->CritSect);
1990 AssertRC(rc2);
1991}
1992
1993/**
1994 * Enables (resumes) or disables (pauses) the async I/O thread.
1995 *
1996 * @param pStream HDA stream to enable/disable async I/O thread for.
1997 * @param fEnable Whether to enable or disable the I/O thread.
1998 *
1999 * @remarks Does not do locking.
2000 */
2001void hdaR3StreamAsyncIOEnable(PHDASTREAM pStream, bool fEnable)
2002{
2003 PHDASTREAMSTATEAIO pAIO = &pStream->State.AIO;
2004 ASMAtomicXchgBool(&pAIO->fEnabled, fEnable);
2005}
2006# endif /* VBOX_WITH_AUDIO_HDA_ASYNC_IO */
2007
2008#endif /* IN_RING3 */
2009
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