VirtualBox

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

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

DevIchAc97: Converted timers. bugref:9218

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