VirtualBox

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

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

DevHDA: Converted timers to new style. Left some todos. bugref:9218

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

© 2025 Oracle Support Privacy / Do Not Sell My Info Terms of Use Trademark Policy Automated Access Etiquette