VirtualBox

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

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

Forward ported r127158 (Audio/HDA: Implemented support for Windows 10 Build 1809 default surround speaker setup) + build fixes (r127159, r127160, r127162, r127165, r127167).

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