VirtualBox

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

Last change on this file since 70255 was 70246, checked in by vboxsync, 7 years ago

Audio/HDA: Use a dedicated fRunning flag for a stream, as the RUN bit of SDnCTL does not necessarily reflect the current (internal) state.

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