VirtualBox

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

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

DevHDA,DevIchAc97: Moved the per-stream timers into the stream structures, dropping the ahTimers arrays in the device state structures. This eliminates bunch of unnecessary indexing and pThis parameter passing. bugref:9218

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 70.9 KB
Line 
1/* $Id: HDAStream.cpp 82345 2019-12-03 14:40:21Z 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 Assert(pStream->hTimer != NIL_TMTIMERHANDLE); /* hdaR3Construct initalized this one already. */
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 pStream HDA stream to retrieve schedule status for.
723 * @param tsNow The current time.
724 */
725bool hdaR3StreamTransferIsScheduled(PHDASTREAM pStream, uint64_t tsNow)
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 if (pStream->State.tsTransferNext > tsNow)
740 {
741 Log3Func(("[SD%RU8] Scheduled in %RU64\n", pStream->u8SD, pStream->State.tsTransferNext - tsNow));
742 return true;
743 }
744 }
745 }
746 return false;
747}
748
749/**
750 * Returns the (virtual) clock timestamp of the next transfer, if any.
751 * Will return 0 if no new transfer is scheduled.
752 *
753 * @returns The (virtual) clock timestamp of the next transfer.
754 * @param pStream HDA stream to retrieve timestamp for.
755 */
756uint64_t hdaR3StreamTransferGetNext(PHDASTREAM pStream)
757{
758 return pStream->State.tsTransferNext;
759}
760
761/**
762 * Writes audio data from a mixer sink into an HDA stream's DMA buffer.
763 *
764 * @returns IPRT status code.
765 * @param pStream HDA stream to write to.
766 * @param pvBuf Data buffer to write.
767 * If NULL, silence will be written.
768 * @param cbBuf Number of bytes of data buffer to write.
769 * @param pcbWritten Number of bytes written. Optional.
770 */
771int hdaR3StreamWrite(PHDASTREAM pStream, const void *pvBuf, uint32_t cbBuf, uint32_t *pcbWritten)
772{
773 AssertPtrReturn(pStream, VERR_INVALID_POINTER);
774 /* pvBuf is optional. */
775 AssertReturn(cbBuf, VERR_INVALID_PARAMETER);
776 /* pcbWritten is optional. */
777
778 PRTCIRCBUF pCircBuf = pStream->State.pCircBuf;
779 AssertPtr(pCircBuf);
780
781 int rc = VINF_SUCCESS;
782
783 uint32_t cbWrittenTotal = 0;
784 uint32_t cbLeft = RT_MIN(cbBuf, (uint32_t)RTCircBufFree(pCircBuf));
785
786 while (cbLeft)
787 {
788 void *pvDst;
789 size_t cbDst;
790
791 RTCircBufAcquireWriteBlock(pCircBuf, cbLeft, &pvDst, &cbDst);
792
793 if (cbDst)
794 {
795 if (pvBuf)
796 {
797 memcpy(pvDst, (uint8_t *)pvBuf + cbWrittenTotal, cbDst);
798 }
799 else /* Send silence. */
800 {
801 /** @todo Use a sample spec for "silence" based on the PCM parameters.
802 * For now we ASSUME that silence equals NULLing the data. */
803 RT_BZERO(pvDst, cbDst);
804 }
805
806 if (pStream->Dbg.Runtime.fEnabled)
807 DrvAudioHlpFileWrite(pStream->Dbg.Runtime.pFileStream, pvDst, cbDst, 0 /* fFlags */);
808 }
809
810 RTCircBufReleaseWriteBlock(pCircBuf, cbDst);
811
812 if (RT_FAILURE(rc))
813 break;
814
815 Assert(cbLeft >= (uint32_t)cbDst);
816 cbLeft -= (uint32_t)cbDst;
817
818 cbWrittenTotal += (uint32_t)cbDst;
819 }
820
821 Log3Func(("cbWrittenTotal=%RU32\n", cbWrittenTotal));
822
823 if (pcbWritten)
824 *pcbWritten = cbWrittenTotal;
825
826 return rc;
827}
828
829
830/**
831 * Reads audio data from an HDA stream's DMA buffer and writes into a specified mixer sink.
832 *
833 * @returns IPRT status code.
834 * @param pStream HDA stream to read audio data from.
835 * @param cbToRead Number of bytes to read.
836 * @param pcbRead Number of bytes read. Optional.
837 */
838int hdaR3StreamRead(PHDASTREAM pStream, uint32_t cbToRead, uint32_t *pcbRead)
839{
840 AssertPtrReturn(pStream, VERR_INVALID_POINTER);
841 AssertReturn(cbToRead, VERR_INVALID_PARAMETER);
842 /* pcbWritten is optional. */
843
844 PHDAMIXERSINK pSink = pStream->pMixSink;
845 if (!pSink)
846 {
847 AssertMsgFailed(("[SD%RU8] Can't read from a stream with no sink attached\n", pStream->u8SD));
848
849 if (pcbRead)
850 *pcbRead = 0;
851 return VINF_SUCCESS;
852 }
853
854 PRTCIRCBUF pCircBuf = pStream->State.pCircBuf;
855 AssertPtr(pCircBuf);
856
857 int rc = VINF_SUCCESS;
858
859 uint32_t cbReadTotal = 0;
860 uint32_t cbLeft = RT_MIN(cbToRead, (uint32_t)RTCircBufUsed(pCircBuf));
861
862 while (cbLeft)
863 {
864 void *pvSrc;
865 size_t cbSrc;
866
867 uint32_t cbWritten = 0;
868
869 RTCircBufAcquireReadBlock(pCircBuf, cbLeft, &pvSrc, &cbSrc);
870
871 if (cbSrc)
872 {
873 if (pStream->Dbg.Runtime.fEnabled)
874 DrvAudioHlpFileWrite(pStream->Dbg.Runtime.pFileStream, pvSrc, cbSrc, 0 /* fFlags */);
875
876 rc = AudioMixerSinkWrite(pSink->pMixSink, AUDMIXOP_COPY, pvSrc, (uint32_t)cbSrc, &cbWritten);
877 AssertRC(rc);
878
879 Assert(cbSrc >= cbWritten);
880 Log2Func(("[SD%RU8] %RU32/%zu bytes read\n", pStream->u8SD, cbWritten, cbSrc));
881 }
882
883 RTCircBufReleaseReadBlock(pCircBuf, cbWritten);
884
885 if ( !cbWritten /* Nothing written? */
886 || RT_FAILURE(rc))
887 break;
888
889 Assert(cbLeft >= cbWritten);
890 cbLeft -= cbWritten;
891
892 cbReadTotal += cbWritten;
893 }
894
895 if (pcbRead)
896 *pcbRead = cbReadTotal;
897
898 return rc;
899}
900
901/**
902 * Transfers data of an HDA stream according to its usage (input / output).
903 *
904 * For an SDO (output) stream this means reading DMA data from the device to
905 * the HDA stream's internal FIFO buffer.
906 *
907 * For an SDI (input) stream this is reading audio data from the HDA stream's
908 * internal FIFO buffer and writing it as DMA data to the device.
909 *
910 * @returns IPRT status code.
911 * @param pDevIns The device instance.
912 * @param pStream HDA stream to update.
913 * @param cbToProcessMax How much data (in bytes) to process as maximum.
914 * @param fInTimer Set if we're in the timer callout.
915 */
916static int hdaR3StreamTransfer(PPDMDEVINS pDevIns, PHDASTREAM pStream, uint32_t cbToProcessMax, bool fInTimer)
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 Assert(!fInTimer || tsNow == PDMDevHlpTimerGet(pDevIns, pStream->hTimer));
1382 hdaR3TimerSet(pDevIns, pStream, tsTransferNext, true /* fForce - skip tsTransferNext check */, fInTimer ? tsNow : 0);
1383
1384 pStream->State.tsTransferNext = tsTransferNext;
1385 }
1386
1387 pStream->State.tsTransferLast = tsNow;
1388
1389 Log3Func(("[SD%RU8] cbTransferLeft=%RU32 -- %RU32/%RU32\n",
1390 pStream->u8SD, cbTransferLeft, pStream->State.cbTransferProcessed, pStream->State.cbTransferSize));
1391 Log3Func(("[SD%RU8] fTransferComplete=%RTbool, cTransferPendingInterrupts=%RU8\n",
1392 pStream->u8SD, fTransferComplete, pStream->State.cTransferPendingInterrupts));
1393 Log3Func(("[SD%RU8] tsNow=%RU64, tsTransferNext=%RU64 (in %RU64 ticks)\n",
1394 pStream->u8SD, tsNow, tsTransferNext, tsTransferNext - tsNow));
1395
1396 hdaR3StreamPeriodUnlock(pPeriod);
1397 hdaR3StreamUnlock(pStream);
1398
1399 return VINF_SUCCESS;
1400}
1401
1402/**
1403 * Updates a HDA stream by doing its required data transfers.
1404 * The host sink(s) set the overall pace.
1405 *
1406 * This routine is called by both, the synchronous and the asynchronous, implementations.
1407 *
1408 * This routine is called by both, the synchronous and the asynchronous
1409 * (VBOX_WITH_AUDIO_HDA_ASYNC_IO), implementations.
1410 *
1411 * When running synchronously, the device DMA transfers *and* the mixer sink
1412 * processing is within the device timer.
1413 *
1414 * When running asynchronously, only the device DMA transfers are done in the
1415 * device timer, whereas the mixer sink processing then is done in the stream's
1416 * own async I/O thread. This thread also will call this function
1417 * (with fInTimer set to @c false).
1418 *
1419 * @param pDevIns The device instance.
1420 * @param pStream HDA stream to update.
1421 * @param fInTimer Whether to this function was called from the timer
1422 * context or an asynchronous I/O stream thread (if supported).
1423 */
1424void hdaR3StreamUpdate(PPDMDEVINS pDevIns, PHDASTREAM pStream, bool fInTimer)
1425{
1426 if (!pStream)
1427 return;
1428
1429 PAUDMIXSINK pSink = NULL;
1430 if ( pStream->pMixSink
1431 && pStream->pMixSink->pMixSink)
1432 {
1433 pSink = pStream->pMixSink->pMixSink;
1434 }
1435
1436 if (!AudioMixerSinkIsActive(pSink)) /* No sink available? Bail out. */
1437 return;
1438
1439 int rc2;
1440
1441 if (hdaGetDirFromSD(pStream->u8SD) == PDMAUDIODIR_OUT) /* Output (SDO). */
1442 {
1443 bool fDoRead = false; /* Whether to read from the HDA stream or not. */
1444
1445# ifdef VBOX_WITH_AUDIO_HDA_ASYNC_IO
1446 if (fInTimer)
1447# endif
1448 {
1449 const uint32_t cbStreamFree = hdaR3StreamGetFree(pStream);
1450 if (cbStreamFree)
1451 {
1452 /* Do the DMA transfer. */
1453 rc2 = hdaR3StreamTransfer(pDevIns, pStream, cbStreamFree, fInTimer);
1454 AssertRC(rc2);
1455 }
1456
1457 /* Only read from the HDA stream at the given scheduling rate. */
1458 const uint64_t tsNowNs = RTTimeNanoTS();
1459 if (tsNowNs - pStream->State.tsLastUpdateNs >= pStream->State.Cfg.Device.cMsSchedulingHint * RT_NS_1MS)
1460 {
1461 fDoRead = true;
1462 pStream->State.tsLastUpdateNs = tsNowNs;
1463 }
1464 }
1465
1466 Log3Func(("[SD%RU8] fInTimer=%RTbool, fDoRead=%RTbool\n", pStream->u8SD, fInTimer, fDoRead));
1467
1468# ifdef VBOX_WITH_AUDIO_HDA_ASYNC_IO
1469 if (fDoRead)
1470 {
1471 rc2 = hdaR3StreamAsyncIONotify(pStream);
1472 AssertRC(rc2);
1473 }
1474# endif
1475
1476# ifdef VBOX_WITH_AUDIO_HDA_ASYNC_IO
1477 if (!fInTimer) /* In async I/O thread */
1478 {
1479# else
1480 if (fDoRead)
1481 {
1482# endif
1483 const uint32_t cbSinkWritable = AudioMixerSinkGetWritable(pSink);
1484 const uint32_t cbStreamReadable = hdaR3StreamGetUsed(pStream);
1485 const uint32_t cbToReadFromStream = RT_MIN(cbStreamReadable, cbSinkWritable);
1486
1487 Log3Func(("[SD%RU8] cbSinkWritable=%RU32, cbStreamReadable=%RU32\n", pStream->u8SD, cbSinkWritable, cbStreamReadable));
1488
1489 if (cbToReadFromStream)
1490 {
1491 /* Read (guest output) data and write it to the stream's sink. */
1492 rc2 = hdaR3StreamRead(pStream, cbToReadFromStream, NULL /* pcbRead */);
1493 AssertRC(rc2);
1494 }
1495
1496 /* When running synchronously, update the associated sink here.
1497 * Otherwise this will be done in the async I/O thread. */
1498 rc2 = AudioMixerSinkUpdate(pSink);
1499 AssertRC(rc2);
1500 }
1501 }
1502 else /* Input (SDI). */
1503 {
1504# ifdef VBOX_WITH_AUDIO_HDA_ASYNC_IO
1505 if (!fInTimer)
1506 {
1507# endif
1508 rc2 = AudioMixerSinkUpdate(pSink);
1509 AssertRC(rc2);
1510
1511 /* Is the sink ready to be read (host input data) from? If so, by how much? */
1512 uint32_t cbSinkReadable = AudioMixerSinkGetReadable(pSink);
1513
1514 /* How much (guest input) data is available for writing at the moment for the HDA stream? */
1515 const uint32_t cbStreamFree = hdaR3StreamGetFree(pStream);
1516
1517 Log3Func(("[SD%RU8] cbSinkReadable=%RU32, cbStreamFree=%RU32\n", pStream->u8SD, cbSinkReadable, cbStreamFree));
1518
1519 /* Do not read more than the HDA stream can hold at the moment.
1520 * The host sets the overall pace. */
1521 if (cbSinkReadable > cbStreamFree)
1522 cbSinkReadable = cbStreamFree;
1523
1524 if (cbSinkReadable)
1525 {
1526 uint8_t abFIFO[HDA_FIFO_MAX + 1];
1527 while (cbSinkReadable)
1528 {
1529 uint32_t cbRead;
1530 rc2 = AudioMixerSinkRead(pSink, AUDMIXOP_COPY,
1531 abFIFO, RT_MIN(cbSinkReadable, (uint32_t)sizeof(abFIFO)), &cbRead);
1532 AssertRCBreak(rc2);
1533
1534 if (!cbRead)
1535 {
1536 AssertMsgFailed(("Nothing read from sink, even if %RU32 bytes were (still) announced\n", cbSinkReadable));
1537 break;
1538 }
1539
1540 /* Write (guest input) data to the stream which was read from stream's sink before. */
1541 uint32_t cbWritten;
1542 rc2 = hdaR3StreamWrite(pStream, abFIFO, cbRead, &cbWritten);
1543 AssertRCBreak(rc2);
1544
1545 if (!cbWritten)
1546 {
1547 AssertFailed(); /* Should never happen, as we know how much we can write. */
1548 break;
1549 }
1550
1551 Assert(cbSinkReadable >= cbRead);
1552 cbSinkReadable -= cbRead;
1553 }
1554 }
1555# ifdef VBOX_WITH_AUDIO_HDA_ASYNC_IO
1556 }
1557 else /* fInTimer */
1558 {
1559# endif
1560
1561# ifdef VBOX_WITH_AUDIO_HDA_ASYNC_IO
1562 const uint64_t tsNowNs = RTTimeNanoTS();
1563 if (tsNowNs - pStream->State.tsLastUpdateNs >= pStream->State.Cfg.Device.cMsSchedulingHint * RT_NS_1MS)
1564 {
1565 rc2 = hdaR3StreamAsyncIONotify(pStream);
1566 AssertRC(rc2);
1567
1568 pStream->State.tsLastUpdateNs = tsNowNs;
1569 }
1570# endif
1571 const uint32_t cbStreamUsed = hdaR3StreamGetUsed(pStream);
1572 if (cbStreamUsed)
1573 {
1574 rc2 = hdaR3StreamTransfer(pDevIns, pStream, cbStreamUsed, fInTimer);
1575 AssertRC(rc2);
1576 }
1577# ifdef VBOX_WITH_AUDIO_HDA_ASYNC_IO
1578 }
1579# endif
1580 }
1581}
1582
1583/**
1584 * Locks an HDA stream for serialized access.
1585 *
1586 * @returns IPRT status code.
1587 * @param pStream HDA stream to lock.
1588 */
1589void hdaR3StreamLock(PHDASTREAM pStream)
1590{
1591 AssertPtrReturnVoid(pStream);
1592 int rc2 = RTCritSectEnter(&pStream->CritSect);
1593 AssertRC(rc2);
1594}
1595
1596/**
1597 * Unlocks a formerly locked HDA stream.
1598 *
1599 * @returns IPRT status code.
1600 * @param pStream HDA stream to unlock.
1601 */
1602void hdaR3StreamUnlock(PHDASTREAM pStream)
1603{
1604 AssertPtrReturnVoid(pStream);
1605 int rc2 = RTCritSectLeave(&pStream->CritSect);
1606 AssertRC(rc2);
1607}
1608
1609/**
1610 * Updates an HDA stream's current read or write buffer position (depending on the stream type) by
1611 * updating its associated LPIB register and DMA position buffer (if enabled).
1612 *
1613 * @returns Set LPIB value.
1614 * @param pStream HDA stream to update read / write position for.
1615 * @param u32LPIB New LPIB (position) value to set.
1616 */
1617uint32_t hdaR3StreamUpdateLPIB(PHDASTREAM pStream, uint32_t u32LPIB)
1618{
1619 AssertPtrReturn(pStream, 0);
1620
1621 AssertMsg(u32LPIB <= pStream->u32CBL,
1622 ("[SD%RU8] New LPIB (%RU32) exceeds CBL (%RU32)\n", pStream->u8SD, u32LPIB, pStream->u32CBL));
1623
1624 const PHDASTATE pThis = pStream->pHDAState;
1625
1626 u32LPIB = RT_MIN(u32LPIB, pStream->u32CBL);
1627
1628 LogFlowFunc(("[SD%RU8] LPIB=%RU32 (DMA Position Buffer Enabled: %RTbool)\n",
1629 pStream->u8SD, u32LPIB, pThis->fDMAPosition));
1630
1631 /* Update LPIB in any case. */
1632 HDA_STREAM_REG(pThis, LPIB, pStream->u8SD) = u32LPIB;
1633
1634 /* Do we need to tell the current DMA position? */
1635 if (pThis->fDMAPosition)
1636 {
1637 int rc2 = PDMDevHlpPCIPhysWrite(pThis->CTX_SUFF(pDevIns),
1638 pThis->u64DPBase + (pStream->u8SD * 2 * sizeof(uint32_t)),
1639 (void *)&u32LPIB, sizeof(uint32_t));
1640 AssertRC(rc2);
1641 }
1642
1643 return u32LPIB;
1644}
1645
1646# ifdef HDA_USE_DMA_ACCESS_HANDLER
1647/**
1648 * Registers access handlers for a stream's BDLE DMA accesses.
1649 *
1650 * @returns true if registration was successful, false if not.
1651 * @param pStream HDA stream to register BDLE access handlers for.
1652 */
1653bool hdaR3StreamRegisterDMAHandlers(PHDASTREAM pStream)
1654{
1655 /* At least LVI and the BDL base must be set. */
1656 if ( !pStream->u16LVI
1657 || !pStream->u64BDLBase)
1658 {
1659 return false;
1660 }
1661
1662 hdaR3StreamUnregisterDMAHandlers(pStream);
1663
1664 LogFunc(("Registering ...\n"));
1665
1666 int rc = VINF_SUCCESS;
1667
1668 /*
1669 * Create BDLE ranges.
1670 */
1671
1672 struct BDLERANGE
1673 {
1674 RTGCPHYS uAddr;
1675 uint32_t uSize;
1676 } arrRanges[16]; /** @todo Use a define. */
1677
1678 size_t cRanges = 0;
1679
1680 for (uint16_t i = 0; i < pStream->u16LVI + 1; i++)
1681 {
1682 HDABDLE BDLE;
1683 rc = hdaR3BDLEFetch(pThis, &BDLE, pStream->u64BDLBase, i /* Index */);
1684 if (RT_FAILURE(rc))
1685 break;
1686
1687 bool fAddRange = true;
1688 BDLERANGE *pRange;
1689
1690 if (cRanges)
1691 {
1692 pRange = &arrRanges[cRanges - 1];
1693
1694 /* Is the current range a direct neighbor of the current BLDE? */
1695 if ((pRange->uAddr + pRange->uSize) == BDLE.Desc.u64BufAddr)
1696 {
1697 /* Expand the current range by the current BDLE's size. */
1698 pRange->uSize += BDLE.Desc.u32BufSize;
1699
1700 /* Adding a new range in this case is not needed anymore. */
1701 fAddRange = false;
1702
1703 LogFunc(("Expanding range %zu by %RU32 (%RU32 total now)\n", cRanges - 1, BDLE.Desc.u32BufSize, pRange->uSize));
1704 }
1705 }
1706
1707 /* Do we need to add a new range? */
1708 if ( fAddRange
1709 && cRanges < RT_ELEMENTS(arrRanges))
1710 {
1711 pRange = &arrRanges[cRanges];
1712
1713 pRange->uAddr = BDLE.Desc.u64BufAddr;
1714 pRange->uSize = BDLE.Desc.u32BufSize;
1715
1716 LogFunc(("Adding range %zu - 0x%x (%RU32)\n", cRanges, pRange->uAddr, pRange->uSize));
1717
1718 cRanges++;
1719 }
1720 }
1721
1722 LogFunc(("%zu ranges total\n", cRanges));
1723
1724 /*
1725 * Register all ranges as DMA access handlers.
1726 */
1727
1728 for (size_t i = 0; i < cRanges; i++)
1729 {
1730 BDLERANGE *pRange = &arrRanges[i];
1731
1732 PHDADMAACCESSHANDLER pHandler = (PHDADMAACCESSHANDLER)RTMemAllocZ(sizeof(HDADMAACCESSHANDLER));
1733 if (!pHandler)
1734 {
1735 rc = VERR_NO_MEMORY;
1736 break;
1737 }
1738
1739 RTListAppend(&pStream->State.lstDMAHandlers, &pHandler->Node);
1740
1741 pHandler->pStream = pStream; /* Save a back reference to the owner. */
1742
1743 char szDesc[32];
1744 RTStrPrintf(szDesc, sizeof(szDesc), "HDA[SD%RU8 - RANGE%02zu]", pStream->u8SD, i);
1745
1746 int rc2 = PGMR3HandlerPhysicalTypeRegister(PDMDevHlpGetVM(pStream->pHDAState->pDevInsR3), PGMPHYSHANDLERKIND_WRITE,
1747 hdaDMAAccessHandler,
1748 NULL, NULL, NULL,
1749 NULL, NULL, NULL,
1750 szDesc, &pHandler->hAccessHandlerType);
1751 AssertRCBreak(rc2);
1752
1753 pHandler->BDLEAddr = pRange->uAddr;
1754 pHandler->BDLESize = pRange->uSize;
1755
1756 /* Get first and last pages of the BDLE range. */
1757 RTGCPHYS pgFirst = pRange->uAddr & ~PAGE_OFFSET_MASK;
1758 RTGCPHYS pgLast = RT_ALIGN(pgFirst + pRange->uSize, PAGE_SIZE);
1759
1760 /* Calculate the region size (in pages). */
1761 RTGCPHYS regionSize = RT_ALIGN(pgLast - pgFirst, PAGE_SIZE);
1762
1763 pHandler->GCPhysFirst = pgFirst;
1764 pHandler->GCPhysLast = pHandler->GCPhysFirst + (regionSize - 1);
1765
1766 LogFunc(("\tRegistering region '%s': 0x%x - 0x%x (region size: %zu)\n",
1767 szDesc, pHandler->GCPhysFirst, pHandler->GCPhysLast, regionSize));
1768 LogFunc(("\tBDLE @ 0x%x - 0x%x (%RU32)\n",
1769 pHandler->BDLEAddr, pHandler->BDLEAddr + pHandler->BDLESize, pHandler->BDLESize));
1770
1771 rc2 = PGMHandlerPhysicalRegister(PDMDevHlpGetVM(pStream->pHDAState->pDevInsR3),
1772 pHandler->GCPhysFirst, pHandler->GCPhysLast,
1773 pHandler->hAccessHandlerType, pHandler, NIL_RTR0PTR, NIL_RTRCPTR,
1774 szDesc);
1775 AssertRCBreak(rc2);
1776
1777 pHandler->fRegistered = true;
1778 }
1779
1780 LogFunc(("Registration ended with rc=%Rrc\n", rc));
1781
1782 return RT_SUCCESS(rc);
1783}
1784
1785/**
1786 * Unregisters access handlers of a stream's BDLEs.
1787 *
1788 * @param pStream HDA stream to unregister BDLE access handlers for.
1789 */
1790void hdaR3StreamUnregisterDMAHandlers(PHDASTREAM pStream)
1791{
1792 LogFunc(("\n"));
1793
1794 PHDADMAACCESSHANDLER pHandler, pHandlerNext;
1795 RTListForEachSafe(&pStream->State.lstDMAHandlers, pHandler, pHandlerNext, HDADMAACCESSHANDLER, Node)
1796 {
1797 if (!pHandler->fRegistered) /* Handler not registered? Skip. */
1798 continue;
1799
1800 LogFunc(("Unregistering 0x%x - 0x%x (%zu)\n",
1801 pHandler->GCPhysFirst, pHandler->GCPhysLast, pHandler->GCPhysLast - pHandler->GCPhysFirst));
1802
1803 int rc2 = PGMHandlerPhysicalDeregister(PDMDevHlpGetVM(pStream->pHDAState->pDevInsR3),
1804 pHandler->GCPhysFirst);
1805 AssertRC(rc2);
1806
1807 RTListNodeRemove(&pHandler->Node);
1808
1809 RTMemFree(pHandler);
1810 pHandler = NULL;
1811 }
1812
1813 Assert(RTListIsEmpty(&pStream->State.lstDMAHandlers));
1814}
1815# endif /* HDA_USE_DMA_ACCESS_HANDLER */
1816
1817# ifdef VBOX_WITH_AUDIO_HDA_ASYNC_IO
1818/**
1819 * Asynchronous I/O thread for a HDA stream.
1820 * This will do the heavy lifting work for us as soon as it's getting notified by another thread.
1821 *
1822 * @returns IPRT status code.
1823 * @param hThreadSelf Thread handle.
1824 * @param pvUser User argument. Must be of type PHDASTREAMTHREADCTX.
1825 */
1826DECLCALLBACK(int) hdaR3StreamAsyncIOThread(RTTHREAD hThreadSelf, void *pvUser)
1827{
1828 PHDASTREAMTHREADCTX pCtx = (PHDASTREAMTHREADCTX)pvUser;
1829 AssertPtr(pCtx);
1830 PHDASTREAM pStream = pCtx->pStream;
1831
1832 AssertPtr(pStream);
1833 PHDASTREAMSTATEAIO pAIO = &pStream->State.AIO;
1834
1835 PPDMDEVINS pDevIns = pCtx->pThis->pDevInsR3;
1836
1837 ASMAtomicXchgBool(&pAIO->fStarted, true);
1838
1839 RTThreadUserSignal(hThreadSelf);
1840
1841 LogFunc(("[SD%RU8] Started\n", pStream->u8SD));
1842
1843 for (;;)
1844 {
1845 int rc2 = RTSemEventWait(pAIO->Event, RT_INDEFINITE_WAIT);
1846 if (RT_FAILURE(rc2))
1847 break;
1848
1849 if (ASMAtomicReadBool(&pAIO->fShutdown))
1850 break;
1851
1852 rc2 = RTCritSectEnter(&pAIO->CritSect);
1853 if (RT_SUCCESS(rc2))
1854 {
1855 if (!pAIO->fEnabled)
1856 {
1857 RTCritSectLeave(&pAIO->CritSect);
1858 continue;
1859 }
1860
1861 hdaR3StreamUpdate(pDevIns, pStream, false /* fInTimer */);
1862
1863 int rc3 = RTCritSectLeave(&pAIO->CritSect);
1864 AssertRC(rc3);
1865 }
1866
1867 AssertRC(rc2);
1868 }
1869
1870 LogFunc(("[SD%RU8] Ended\n", pStream->u8SD));
1871
1872 ASMAtomicXchgBool(&pAIO->fStarted, false);
1873
1874 return VINF_SUCCESS;
1875}
1876
1877/**
1878 * Creates the async I/O thread for a specific HDA audio stream.
1879 *
1880 * @returns IPRT status code.
1881 * @param pStream HDA audio stream to create the async I/O thread for.
1882 */
1883int hdaR3StreamAsyncIOCreate(PHDASTREAM pStream)
1884{
1885 PHDASTREAMSTATEAIO pAIO = &pStream->State.AIO;
1886
1887 int rc;
1888
1889 if (!ASMAtomicReadBool(&pAIO->fStarted))
1890 {
1891 pAIO->fShutdown = false;
1892 pAIO->fEnabled = true; /* Enabled by default. */
1893
1894 rc = RTSemEventCreate(&pAIO->Event);
1895 if (RT_SUCCESS(rc))
1896 {
1897 rc = RTCritSectInit(&pAIO->CritSect);
1898 if (RT_SUCCESS(rc))
1899 {
1900 HDASTREAMTHREADCTX Ctx = { pStream->pHDAState, pStream };
1901
1902 char szThreadName[64];
1903 RTStrPrintf2(szThreadName, sizeof(szThreadName), "hdaAIO%RU8", pStream->u8SD);
1904
1905 rc = RTThreadCreate(&pAIO->Thread, hdaR3StreamAsyncIOThread, &Ctx,
1906 0, RTTHREADTYPE_IO, RTTHREADFLAGS_WAITABLE, szThreadName);
1907 if (RT_SUCCESS(rc))
1908 rc = RTThreadUserWait(pAIO->Thread, 10 * 1000 /* 10s timeout */);
1909 }
1910 }
1911 }
1912 else
1913 rc = VINF_SUCCESS;
1914
1915 LogFunc(("[SD%RU8] Returning %Rrc\n", pStream->u8SD, rc));
1916 return rc;
1917}
1918
1919/**
1920 * Destroys the async I/O thread of a specific HDA audio stream.
1921 *
1922 * @returns IPRT status code.
1923 * @param pStream HDA audio stream to destroy the async I/O thread for.
1924 */
1925int hdaR3StreamAsyncIODestroy(PHDASTREAM pStream)
1926{
1927 PHDASTREAMSTATEAIO pAIO = &pStream->State.AIO;
1928
1929 if (!ASMAtomicReadBool(&pAIO->fStarted))
1930 return VINF_SUCCESS;
1931
1932 ASMAtomicWriteBool(&pAIO->fShutdown, true);
1933
1934 int rc = hdaR3StreamAsyncIONotify(pStream);
1935 AssertRC(rc);
1936
1937 int rcThread;
1938 rc = RTThreadWait(pAIO->Thread, 30 * 1000 /* 30s timeout */, &rcThread);
1939 LogFunc(("Async I/O thread ended with %Rrc (%Rrc)\n", rc, rcThread));
1940
1941 if (RT_SUCCESS(rc))
1942 {
1943 rc = RTCritSectDelete(&pAIO->CritSect);
1944 AssertRC(rc);
1945
1946 rc = RTSemEventDestroy(pAIO->Event);
1947 AssertRC(rc);
1948
1949 pAIO->fStarted = false;
1950 pAIO->fShutdown = false;
1951 pAIO->fEnabled = false;
1952 }
1953
1954 LogFunc(("[SD%RU8] Returning %Rrc\n", pStream->u8SD, rc));
1955 return rc;
1956}
1957
1958/**
1959 * Lets the stream's async I/O thread know that there is some data to process.
1960 *
1961 * @returns IPRT status code.
1962 * @param pStream HDA stream to notify async I/O thread for.
1963 */
1964int hdaR3StreamAsyncIONotify(PHDASTREAM pStream)
1965{
1966 return RTSemEventSignal(pStream->State.AIO.Event);
1967}
1968
1969/**
1970 * Locks the async I/O thread of a specific HDA audio stream.
1971 *
1972 * @param pStream HDA stream to lock async I/O thread for.
1973 */
1974void hdaR3StreamAsyncIOLock(PHDASTREAM pStream)
1975{
1976 PHDASTREAMSTATEAIO pAIO = &pStream->State.AIO;
1977
1978 if (!ASMAtomicReadBool(&pAIO->fStarted))
1979 return;
1980
1981 int rc2 = RTCritSectEnter(&pAIO->CritSect);
1982 AssertRC(rc2);
1983}
1984
1985/**
1986 * Unlocks the async I/O thread of a specific HDA audio stream.
1987 *
1988 * @param pStream HDA stream to unlock async I/O thread for.
1989 */
1990void hdaR3StreamAsyncIOUnlock(PHDASTREAM pStream)
1991{
1992 PHDASTREAMSTATEAIO pAIO = &pStream->State.AIO;
1993
1994 if (!ASMAtomicReadBool(&pAIO->fStarted))
1995 return;
1996
1997 int rc2 = RTCritSectLeave(&pAIO->CritSect);
1998 AssertRC(rc2);
1999}
2000
2001/**
2002 * Enables (resumes) or disables (pauses) the async I/O thread.
2003 *
2004 * @param pStream HDA stream to enable/disable async I/O thread for.
2005 * @param fEnable Whether to enable or disable the I/O thread.
2006 *
2007 * @remarks Does not do locking.
2008 */
2009void hdaR3StreamAsyncIOEnable(PHDASTREAM pStream, bool fEnable)
2010{
2011 PHDASTREAMSTATEAIO pAIO = &pStream->State.AIO;
2012 ASMAtomicXchgBool(&pAIO->fEnabled, fEnable);
2013}
2014# endif /* VBOX_WITH_AUDIO_HDA_ASYNC_IO */
2015
2016#endif /* IN_RING3 */
2017
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