VirtualBox

source: vbox/trunk/src/VBox/Devices/Audio/DevHDA.cpp@ 70363

Last change on this file since 70363 was 70316, checked in by vboxsync, 7 years ago

Audio/HDA: Take pending stream interrupts into account in hdaStreamTransferIsScheduled() and do the refcounting in hdaRegWriteSDSTS(). That way a re-scheduling in hdaTimerMain() should not happen anymore when an interrupt is pending and thus should improve timing accuracy quite a bit.

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 187.7 KB
Line 
1/* $Id: DevHDA.cpp 70316 2017-12-22 12:58:24Z vboxsync $ */
2/** @file
3 * DevHDA.cpp - VBox Intel HD Audio Controller.
4 *
5 * Implemented against the specifications found in "High Definition Audio
6 * Specification", Revision 1.0a June 17, 2010, and "Intel I/O Controller
7 * HUB 6 (ICH6) Family, Datasheet", document number 301473-002.
8 */
9
10/*
11 * Copyright (C) 2006-2017 Oracle Corporation
12 *
13 * This file is part of VirtualBox Open Source Edition (OSE), as
14 * available from http://www.virtualbox.org. This file is free software;
15 * you can redistribute it and/or modify it under the terms of the GNU
16 * General Public License (GPL) as published by the Free Software
17 * Foundation, in version 2 as it comes in the "COPYING" file of the
18 * VirtualBox OSE distribution. VirtualBox OSE is distributed in the
19 * hope that it will be useful, but WITHOUT ANY WARRANTY of any kind.
20 */
21
22
23/*********************************************************************************************************************************
24* Header Files *
25*********************************************************************************************************************************/
26#define LOG_GROUP LOG_GROUP_DEV_HDA
27#include <VBox/log.h>
28
29#include <VBox/vmm/pdmdev.h>
30#include <VBox/vmm/pdmaudioifs.h>
31#include <VBox/version.h>
32
33#include <iprt/assert.h>
34#include <iprt/asm.h>
35#include <iprt/asm-math.h>
36#include <iprt/file.h>
37#include <iprt/list.h>
38#ifdef IN_RING3
39# include <iprt/mem.h>
40# include <iprt/semaphore.h>
41# include <iprt/string.h>
42# include <iprt/uuid.h>
43#endif
44
45#include "VBoxDD.h"
46
47#include "AudioMixBuffer.h"
48#include "AudioMixer.h"
49
50#include "DevHDA.h"
51#include "DevHDACommon.h"
52
53#include "HDACodec.h"
54#include "HDAStream.h"
55# if defined(VBOX_WITH_HDA_AUDIO_INTERLEAVING_STREAMS_SUPPORT) || defined(VBOX_WITH_AUDIO_HDA_51_SURROUND)
56# include "HDAStreamChannel.h"
57# endif
58#include "HDAStreamMap.h"
59#include "HDAStreamPeriod.h"
60
61#include "DrvAudio.h"
62
63
64/*********************************************************************************************************************************
65* Defined Constants And Macros *
66*********************************************************************************************************************************/
67//#define HDA_AS_PCI_EXPRESS
68#define VBOX_WITH_INTEL_HDA
69
70/* Installs a DMA access handler (via PGM callback) to monitor
71 * HDA's DMA operations, that is, writing / reading audio stream data.
72 *
73 * !!! Note: Certain guests are *that* timing sensitive that when enabling !!!
74 * !!! such a handler will mess up audio completely (e.g. Windows 7). !!! */
75//#define HDA_USE_DMA_ACCESS_HANDLER
76#ifdef HDA_USE_DMA_ACCESS_HANDLER
77# include <VBox/vmm/pgm.h>
78#endif
79
80/* Uses the DMA access handler to read the written DMA audio (output) data.
81 * Only valid if HDA_USE_DMA_ACCESS_HANDLER is set.
82 *
83 * Also see the note / warning for HDA_USE_DMA_ACCESS_HANDLER. */
84//# define HDA_USE_DMA_ACCESS_HANDLER_WRITING
85
86/* Useful to debug the device' timing. */
87//#define HDA_DEBUG_TIMING
88
89/* To debug silence coming from the guest in form of audio gaps.
90 * Very crude implementation for now. */
91//#define HDA_DEBUG_SILENCE
92
93#if defined(VBOX_WITH_HP_HDA)
94/* HP Pavilion dv4t-1300 */
95# define HDA_PCI_VENDOR_ID 0x103c
96# define HDA_PCI_DEVICE_ID 0x30f7
97#elif defined(VBOX_WITH_INTEL_HDA)
98/* Intel HDA controller */
99# define HDA_PCI_VENDOR_ID 0x8086
100# define HDA_PCI_DEVICE_ID 0x2668
101#elif defined(VBOX_WITH_NVIDIA_HDA)
102/* nVidia HDA controller */
103# define HDA_PCI_VENDOR_ID 0x10de
104# define HDA_PCI_DEVICE_ID 0x0ac0
105#else
106# error "Please specify your HDA device vendor/device IDs"
107#endif
108
109/* Make sure that interleaving streams support is enabled if the 5.1 surround code is being used. */
110#if defined (VBOX_WITH_AUDIO_HDA_51_SURROUND) && !defined(VBOX_WITH_HDA_AUDIO_INTERLEAVING_STREAMS_SUPPORT)
111# define VBOX_WITH_HDA_AUDIO_INTERLEAVING_STREAMS_SUPPORT
112#endif
113
114
115/*********************************************************************************************************************************
116* Structures and Typedefs *
117*********************************************************************************************************************************/
118
119/**
120 * Structure defining a (host backend) driver stream.
121 * Each driver has its own instances of audio mixer streams, which then
122 * can go into the same (or even different) audio mixer sinks.
123 */
124typedef struct HDADRIVERSTREAM
125{
126 union
127 {
128 /** Desired playback destination (for an output stream). */
129 PDMAUDIOPLAYBACKDEST Dest;
130 /** Desired recording source (for an input stream). */
131 PDMAUDIORECSOURCE Source;
132 } DestSource;
133 uint8_t Padding1[4];
134 /** Associated mixer handle. */
135 R3PTRTYPE(PAUDMIXSTREAM) pMixStrm;
136} HDADRIVERSTREAM, *PHDADRIVERSTREAM;
137
138#ifdef HDA_USE_DMA_ACCESS_HANDLER
139/**
140 * Struct for keeping an HDA DMA access handler context.
141 */
142typedef struct HDADMAACCESSHANDLER
143{
144 /** Node for storing this handler in our list in HDASTREAMSTATE. */
145 RTLISTNODER3 Node;
146 /** Pointer to stream to which this access handler is assigned to. */
147 R3PTRTYPE(PHDASTREAM) pStream;
148 /** Access handler type handle. */
149 PGMPHYSHANDLERTYPE hAccessHandlerType;
150 /** First address this handler uses. */
151 RTGCPHYS GCPhysFirst;
152 /** Last address this handler uses. */
153 RTGCPHYS GCPhysLast;
154 /** Actual BDLE address to handle. */
155 RTGCPHYS BDLEAddr;
156 /** Actual BDLE buffer size to handle. */
157 RTGCPHYS BDLESize;
158 /** Whether the access handler has been registered or not. */
159 bool fRegistered;
160 uint8_t Padding[3];
161} HDADMAACCESSHANDLER, *PHDADMAACCESSHANDLER;
162#endif
163
164/**
165 * Struct for maintaining a host backend driver.
166 * This driver must be associated to one, and only one,
167 * HDA codec. The HDA controller does the actual multiplexing
168 * of HDA codec data to various host backend drivers then.
169 *
170 * This HDA device uses a timer in order to synchronize all
171 * read/write accesses across all attached LUNs / backends.
172 */
173typedef struct HDADRIVER
174{
175 /** Node for storing this driver in our device driver list of HDASTATE. */
176 RTLISTNODER3 Node;
177 /** Pointer to HDA controller (state). */
178 R3PTRTYPE(PHDASTATE) pHDAState;
179 /** Driver flags. */
180 PDMAUDIODRVFLAGS fFlags;
181 uint8_t u32Padding0[2];
182 /** LUN to which this driver has been assigned. */
183 uint8_t uLUN;
184 /** Whether this driver is in an attached state or not. */
185 bool fAttached;
186 /** Pointer to attached driver base interface. */
187 R3PTRTYPE(PPDMIBASE) pDrvBase;
188 /** Audio connector interface to the underlying host backend. */
189 R3PTRTYPE(PPDMIAUDIOCONNECTOR) pConnector;
190 /** Mixer stream for line input. */
191 HDADRIVERSTREAM LineIn;
192#ifdef VBOX_WITH_AUDIO_HDA_MIC_IN
193 /** Mixer stream for mic input. */
194 HDADRIVERSTREAM MicIn;
195#endif
196 /** Mixer stream for front output. */
197 HDADRIVERSTREAM Front;
198#ifdef VBOX_WITH_AUDIO_HDA_51_SURROUND
199 /** Mixer stream for center/LFE output. */
200 HDADRIVERSTREAM CenterLFE;
201 /** Mixer stream for rear output. */
202 HDADRIVERSTREAM Rear;
203#endif
204} HDADRIVER;
205
206
207/*********************************************************************************************************************************
208* Internal Functions *
209*********************************************************************************************************************************/
210#ifndef VBOX_DEVICE_STRUCT_TESTCASE
211#ifdef IN_RING3
212static void hdaGCTLReset(PHDASTATE pThis);
213#endif
214
215/** @name Register read/write stubs.
216 * @{
217 */
218static int hdaRegReadUnimpl(PHDASTATE pThis, uint32_t iReg, uint32_t *pu32Value);
219static int hdaRegWriteUnimpl(PHDASTATE pThis, uint32_t iReg, uint32_t pu32Value);
220/** @} */
221
222/** @name Global register set read/write functions.
223 * @{
224 */
225static int hdaRegWriteGCTL(PHDASTATE pThis, uint32_t iReg, uint32_t u32Value);
226static int hdaRegReadLPIB(PHDASTATE pThis, uint32_t iReg, uint32_t *pu32Value);
227static int hdaRegReadWALCLK(PHDASTATE pThis, uint32_t iReg, uint32_t *pu32Value);
228static int hdaRegWriteCORBWP(PHDASTATE pThis, uint32_t iReg, uint32_t u32Value);
229static int hdaRegWriteCORBRP(PHDASTATE pThis, uint32_t iReg, uint32_t u32Value);
230static int hdaRegWriteCORBCTL(PHDASTATE pThis, uint32_t iReg, uint32_t u32Value);
231static int hdaRegWriteCORBSIZE(PHDASTATE pThis, uint32_t iReg, uint32_t u32Value);
232static int hdaRegWriteCORBSTS(PHDASTATE pThis, uint32_t iReg, uint32_t u32Value);
233static int hdaRegWriteRINTCNT(PHDASTATE pThis, uint32_t iReg, uint32_t pu32Value);
234static int hdaRegWriteRIRBWP(PHDASTATE pThis, uint32_t iReg, uint32_t u32Value);
235static int hdaRegWriteRIRBSTS(PHDASTATE pThis, uint32_t iReg, uint32_t u32Value);
236static int hdaRegWriteSTATESTS(PHDASTATE pThis, uint32_t iReg, uint32_t u32Value);
237static int hdaRegWriteIRS(PHDASTATE pThis, uint32_t iReg, uint32_t u32Value);
238static int hdaRegReadIRS(PHDASTATE pThis, uint32_t iReg, uint32_t *pu32Value);
239static int hdaRegWriteBase(PHDASTATE pThis, uint32_t iReg, uint32_t u32Value);
240/** @} */
241
242/** @name {IOB}SDn write functions.
243 * @{
244 */
245static int hdaRegWriteSDCBL(PHDASTATE pThis, uint32_t iReg, uint32_t u32Value);
246static int hdaRegWriteSDCTL(PHDASTATE pThis, uint32_t iReg, uint32_t u32Value);
247static int hdaRegWriteSDSTS(PHDASTATE pThis, uint32_t iReg, uint32_t u32Value);
248static int hdaRegWriteSDLVI(PHDASTATE pThis, uint32_t iReg, uint32_t u32Value);
249static int hdaRegWriteSDFIFOW(PHDASTATE pThis, uint32_t iReg, uint32_t u32Value);
250static int hdaRegWriteSDFIFOS(PHDASTATE pThis, uint32_t iReg, uint32_t u32Value);
251static int hdaRegWriteSDFMT(PHDASTATE pThis, uint32_t iReg, uint32_t u32Value);
252static int hdaRegWriteSDBDPL(PHDASTATE pThis, uint32_t iReg, uint32_t u32Value);
253static int hdaRegWriteSDBDPU(PHDASTATE pThis, uint32_t iReg, uint32_t u32Value);
254/** @} */
255
256/** @name Generic register read/write functions.
257 * @{
258 */
259static int hdaRegReadU32(PHDASTATE pThis, uint32_t iReg, uint32_t *pu32Value);
260static int hdaRegWriteU32(PHDASTATE pThis, uint32_t iReg, uint32_t u32Value);
261static int hdaRegReadU24(PHDASTATE pThis, uint32_t iReg, uint32_t *pu32Value);
262#ifdef IN_RING3
263static int hdaRegWriteU24(PHDASTATE pThis, uint32_t iReg, uint32_t u32Value);
264#endif
265static int hdaRegReadU16(PHDASTATE pThis, uint32_t iReg, uint32_t *pu32Value);
266static int hdaRegWriteU16(PHDASTATE pThis, uint32_t iReg, uint32_t u32Value);
267static int hdaRegReadU8(PHDASTATE pThis, uint32_t iReg, uint32_t *pu32Value);
268static int hdaRegWriteU8(PHDASTATE pThis, uint32_t iReg, uint32_t u32Value);
269/** @} */
270
271/** @name HDA device functions.
272 * @{
273 */
274#ifdef IN_RING3
275# ifdef HDA_USE_DMA_ACCESS_HANDLER
276static DECLCALLBACK(VBOXSTRICTRC) hdaDMAAccessHandler(PVM pVM, PVMCPU pVCpu, RTGCPHYS GCPhys, void *pvPhys, void *pvBuf, size_t cbBuf, PGMACCESSTYPE enmAccessType, PGMACCESSORIGIN enmOrigin, void *pvUser);
277# endif
278static void hdaDoTransfers(PHDASTATE pThis);
279#endif /* IN_RING3 */
280/** @} */
281
282/** @name Timer functions.
283 * @{
284 */
285#ifdef IN_RING3
286static void hdaTimerMain(PHDASTATE pThis);
287#endif
288/** @} */
289
290
291/*********************************************************************************************************************************
292* Global Variables *
293*********************************************************************************************************************************/
294
295/** No register description (RD) flags defined. */
296#define HDA_RD_FLAG_NONE 0
297/** Writes to SD are allowed while RUN bit is set. */
298#define HDA_RD_FLAG_SD_WRITE_RUN RT_BIT(0)
299
300/** Emits a single audio stream register set (e.g. OSD0) at a specified offset. */
301#define HDA_REG_MAP_STRM(offset, name) \
302 /* offset size read mask write mask flags read callback write callback index + abbrev description */ \
303 /* ------- ------- ---------- ---------- ------------------------- -------------- ----------------- ----------------------------- ----------- */ \
304 /* Offset 0x80 (SD0) */ \
305 { offset, 0x00003, 0x00FF001F, 0x00F0001F, HDA_RD_FLAG_SD_WRITE_RUN, hdaRegReadU24 , hdaRegWriteSDCTL , HDA_REG_IDX_STRM(name, CTL) , #name " Stream Descriptor Control" }, \
306 /* Offset 0x83 (SD0) */ \
307 { offset + 0x3, 0x00001, 0x0000003C, 0x0000001C, HDA_RD_FLAG_SD_WRITE_RUN, hdaRegReadU8 , hdaRegWriteSDSTS , HDA_REG_IDX_STRM(name, STS) , #name " Status" }, \
308 /* Offset 0x84 (SD0) */ \
309 { offset + 0x4, 0x00004, 0xFFFFFFFF, 0x00000000, HDA_RD_FLAG_NONE, hdaRegReadLPIB, hdaRegWriteU32 , HDA_REG_IDX_STRM(name, LPIB) , #name " Link Position In Buffer" }, \
310 /* Offset 0x88 (SD0) */ \
311 { offset + 0x8, 0x00004, 0xFFFFFFFF, 0xFFFFFFFF, HDA_RD_FLAG_NONE, hdaRegReadU32 , hdaRegWriteSDCBL , HDA_REG_IDX_STRM(name, CBL) , #name " Cyclic Buffer Length" }, \
312 /* Offset 0x8C (SD0) */ \
313 { offset + 0xC, 0x00002, 0x0000FFFF, 0x0000FFFF, HDA_RD_FLAG_NONE, hdaRegReadU16 , hdaRegWriteSDLVI , HDA_REG_IDX_STRM(name, LVI) , #name " Last Valid Index" }, \
314 /* Reserved: FIFO Watermark. ** @todo Document this! */ \
315 { offset + 0xE, 0x00002, 0x00000007, 0x00000007, HDA_RD_FLAG_NONE, hdaRegReadU16 , hdaRegWriteSDFIFOW, HDA_REG_IDX_STRM(name, FIFOW), #name " FIFO Watermark" }, \
316 /* Offset 0x90 (SD0) */ \
317 { offset + 0x10, 0x00002, 0x000000FF, 0x000000FF, HDA_RD_FLAG_NONE, hdaRegReadU16 , hdaRegWriteSDFIFOS, HDA_REG_IDX_STRM(name, FIFOS), #name " FIFO Size" }, \
318 /* Offset 0x92 (SD0) */ \
319 { offset + 0x12, 0x00002, 0x00007F7F, 0x00007F7F, HDA_RD_FLAG_NONE, hdaRegReadU16 , hdaRegWriteSDFMT , HDA_REG_IDX_STRM(name, FMT) , #name " Stream Format" }, \
320 /* Reserved: 0x94 - 0x98. */ \
321 /* Offset 0x98 (SD0) */ \
322 { offset + 0x18, 0x00004, 0xFFFFFF80, 0xFFFFFF80, HDA_RD_FLAG_NONE, hdaRegReadU32 , hdaRegWriteSDBDPL , HDA_REG_IDX_STRM(name, BDPL) , #name " Buffer Descriptor List Pointer-Lower Base Address" }, \
323 /* Offset 0x9C (SD0) */ \
324 { offset + 0x1C, 0x00004, 0xFFFFFFFF, 0xFFFFFFFF, HDA_RD_FLAG_NONE, hdaRegReadU32 , hdaRegWriteSDBDPU , HDA_REG_IDX_STRM(name, BDPU) , #name " Buffer Descriptor List Pointer-Upper Base Address" }
325
326/** Defines a single audio stream register set (e.g. OSD0). */
327#define HDA_REG_MAP_DEF_STREAM(index, name) \
328 HDA_REG_MAP_STRM(HDA_REG_DESC_SD0_BASE + (index * 32 /* 0x20 */), name)
329
330/* See 302349 p 6.2. */
331const HDAREGDESC g_aHdaRegMap[HDA_NUM_REGS] =
332{
333 /* offset size read mask write mask flags read callback write callback index + abbrev */
334 /*------- ------- ---------- ---------- ----------------- ---------------- ------------------- ------------------------ */
335 { 0x00000, 0x00002, 0x0000FFFB, 0x00000000, HDA_RD_FLAG_NONE, hdaRegReadU16 , hdaRegWriteUnimpl , HDA_REG_IDX(GCAP) }, /* Global Capabilities */
336 { 0x00002, 0x00001, 0x000000FF, 0x00000000, HDA_RD_FLAG_NONE, hdaRegReadU8 , hdaRegWriteUnimpl , HDA_REG_IDX(VMIN) }, /* Minor Version */
337 { 0x00003, 0x00001, 0x000000FF, 0x00000000, HDA_RD_FLAG_NONE, hdaRegReadU8 , hdaRegWriteUnimpl , HDA_REG_IDX(VMAJ) }, /* Major Version */
338 { 0x00004, 0x00002, 0x0000FFFF, 0x00000000, HDA_RD_FLAG_NONE, hdaRegReadU16 , hdaRegWriteU16 , HDA_REG_IDX(OUTPAY) }, /* Output Payload Capabilities */
339 { 0x00006, 0x00002, 0x0000FFFF, 0x00000000, HDA_RD_FLAG_NONE, hdaRegReadU16 , hdaRegWriteUnimpl , HDA_REG_IDX(INPAY) }, /* Input Payload Capabilities */
340 { 0x00008, 0x00004, 0x00000103, 0x00000103, HDA_RD_FLAG_NONE, hdaRegReadU32 , hdaRegWriteGCTL , HDA_REG_IDX(GCTL) }, /* Global Control */
341 { 0x0000c, 0x00002, 0x00007FFF, 0x00007FFF, HDA_RD_FLAG_NONE, hdaRegReadU16 , hdaRegWriteU16 , HDA_REG_IDX(WAKEEN) }, /* Wake Enable */
342 { 0x0000e, 0x00002, 0x00000007, 0x00000007, HDA_RD_FLAG_NONE, hdaRegReadU8 , hdaRegWriteSTATESTS, HDA_REG_IDX(STATESTS) }, /* State Change Status */
343 { 0x00010, 0x00002, 0xFFFFFFFF, 0x00000000, HDA_RD_FLAG_NONE, hdaRegReadUnimpl, hdaRegWriteUnimpl , HDA_REG_IDX(GSTS) }, /* Global Status */
344 { 0x00018, 0x00002, 0x0000FFFF, 0x00000000, HDA_RD_FLAG_NONE, hdaRegReadU16 , hdaRegWriteU16 , HDA_REG_IDX(OUTSTRMPAY) }, /* Output Stream Payload Capability */
345 { 0x0001A, 0x00002, 0x0000FFFF, 0x00000000, HDA_RD_FLAG_NONE, hdaRegReadU16 , hdaRegWriteUnimpl , HDA_REG_IDX(INSTRMPAY) }, /* Input Stream Payload Capability */
346 { 0x00020, 0x00004, 0xC00000FF, 0xC00000FF, HDA_RD_FLAG_NONE, hdaRegReadU32 , hdaRegWriteU32 , HDA_REG_IDX(INTCTL) }, /* Interrupt Control */
347 { 0x00024, 0x00004, 0xC00000FF, 0x00000000, HDA_RD_FLAG_NONE, hdaRegReadU32 , hdaRegWriteUnimpl , HDA_REG_IDX(INTSTS) }, /* Interrupt Status */
348 { 0x00030, 0x00004, 0xFFFFFFFF, 0x00000000, HDA_RD_FLAG_NONE, hdaRegReadWALCLK, hdaRegWriteUnimpl , HDA_REG_IDX_NOMEM(WALCLK) }, /* Wall Clock Counter */
349 { 0x00034, 0x00004, 0x000000FF, 0x000000FF, HDA_RD_FLAG_NONE, hdaRegReadU32 , hdaRegWriteU32 , HDA_REG_IDX(SSYNC) }, /* Stream Synchronization */
350 { 0x00040, 0x00004, 0xFFFFFF80, 0xFFFFFF80, HDA_RD_FLAG_NONE, hdaRegReadU32 , hdaRegWriteBase , HDA_REG_IDX(CORBLBASE) }, /* CORB Lower Base Address */
351 { 0x00044, 0x00004, 0xFFFFFFFF, 0xFFFFFFFF, HDA_RD_FLAG_NONE, hdaRegReadU32 , hdaRegWriteBase , HDA_REG_IDX(CORBUBASE) }, /* CORB Upper Base Address */
352 { 0x00048, 0x00002, 0x000000FF, 0x000000FF, HDA_RD_FLAG_NONE, hdaRegReadU16 , hdaRegWriteCORBWP , HDA_REG_IDX(CORBWP) }, /* CORB Write Pointer */
353 { 0x0004A, 0x00002, 0x000080FF, 0x00008000, HDA_RD_FLAG_NONE, hdaRegReadU16 , hdaRegWriteCORBRP , HDA_REG_IDX(CORBRP) }, /* CORB Read Pointer */
354 { 0x0004C, 0x00001, 0x00000003, 0x00000003, HDA_RD_FLAG_NONE, hdaRegReadU8 , hdaRegWriteCORBCTL , HDA_REG_IDX(CORBCTL) }, /* CORB Control */
355 { 0x0004D, 0x00001, 0x00000001, 0x00000001, HDA_RD_FLAG_NONE, hdaRegReadU8 , hdaRegWriteCORBSTS , HDA_REG_IDX(CORBSTS) }, /* CORB Status */
356 { 0x0004E, 0x00001, 0x000000F3, 0x00000003, HDA_RD_FLAG_NONE, hdaRegReadU8 , hdaRegWriteCORBSIZE, HDA_REG_IDX(CORBSIZE) }, /* CORB Size */
357 { 0x00050, 0x00004, 0xFFFFFF80, 0xFFFFFF80, HDA_RD_FLAG_NONE, hdaRegReadU32 , hdaRegWriteBase , HDA_REG_IDX(RIRBLBASE) }, /* RIRB Lower Base Address */
358 { 0x00054, 0x00004, 0xFFFFFFFF, 0xFFFFFFFF, HDA_RD_FLAG_NONE, hdaRegReadU32 , hdaRegWriteBase , HDA_REG_IDX(RIRBUBASE) }, /* RIRB Upper Base Address */
359 { 0x00058, 0x00002, 0x000000FF, 0x00008000, HDA_RD_FLAG_NONE, hdaRegReadU8 , hdaRegWriteRIRBWP , HDA_REG_IDX(RIRBWP) }, /* RIRB Write Pointer */
360 { 0x0005A, 0x00002, 0x000000FF, 0x000000FF, HDA_RD_FLAG_NONE, hdaRegReadU16 , hdaRegWriteRINTCNT , HDA_REG_IDX(RINTCNT) }, /* Response Interrupt Count */
361 { 0x0005C, 0x00001, 0x00000007, 0x00000007, HDA_RD_FLAG_NONE, hdaRegReadU8 , hdaRegWriteU8 , HDA_REG_IDX(RIRBCTL) }, /* RIRB Control */
362 { 0x0005D, 0x00001, 0x00000005, 0x00000005, HDA_RD_FLAG_NONE, hdaRegReadU8 , hdaRegWriteRIRBSTS , HDA_REG_IDX(RIRBSTS) }, /* RIRB Status */
363 { 0x0005E, 0x00001, 0x000000F3, 0x00000000, HDA_RD_FLAG_NONE, hdaRegReadU8 , hdaRegWriteUnimpl , HDA_REG_IDX(RIRBSIZE) }, /* RIRB Size */
364 { 0x00060, 0x00004, 0xFFFFFFFF, 0xFFFFFFFF, HDA_RD_FLAG_NONE, hdaRegReadU32 , hdaRegWriteU32 , HDA_REG_IDX(IC) }, /* Immediate Command */
365 { 0x00064, 0x00004, 0x00000000, 0xFFFFFFFF, HDA_RD_FLAG_NONE, hdaRegReadU32 , hdaRegWriteUnimpl , HDA_REG_IDX(IR) }, /* Immediate Response */
366 { 0x00068, 0x00002, 0x00000002, 0x00000002, HDA_RD_FLAG_NONE, hdaRegReadIRS , hdaRegWriteIRS , HDA_REG_IDX(IRS) }, /* Immediate Command Status */
367 { 0x00070, 0x00004, 0xFFFFFFFF, 0xFFFFFF81, HDA_RD_FLAG_NONE, hdaRegReadU32 , hdaRegWriteBase , HDA_REG_IDX(DPLBASE) }, /* DMA Position Lower Base */
368 { 0x00074, 0x00004, 0xFFFFFFFF, 0xFFFFFFFF, HDA_RD_FLAG_NONE, hdaRegReadU32 , hdaRegWriteBase , HDA_REG_IDX(DPUBASE) }, /* DMA Position Upper Base */
369 /* 4 Serial Data In (SDI). */
370 HDA_REG_MAP_DEF_STREAM(0, SD0),
371 HDA_REG_MAP_DEF_STREAM(1, SD1),
372 HDA_REG_MAP_DEF_STREAM(2, SD2),
373 HDA_REG_MAP_DEF_STREAM(3, SD3),
374 /* 4 Serial Data Out (SDO). */
375 HDA_REG_MAP_DEF_STREAM(4, SD4),
376 HDA_REG_MAP_DEF_STREAM(5, SD5),
377 HDA_REG_MAP_DEF_STREAM(6, SD6),
378 HDA_REG_MAP_DEF_STREAM(7, SD7)
379};
380
381const HDAREGALIAS g_aHdaRegAliases[] =
382{
383 { 0x2084, HDA_REG_SD0LPIB },
384 { 0x20a4, HDA_REG_SD1LPIB },
385 { 0x20c4, HDA_REG_SD2LPIB },
386 { 0x20e4, HDA_REG_SD3LPIB },
387 { 0x2104, HDA_REG_SD4LPIB },
388 { 0x2124, HDA_REG_SD5LPIB },
389 { 0x2144, HDA_REG_SD6LPIB },
390 { 0x2164, HDA_REG_SD7LPIB }
391};
392
393#ifdef IN_RING3
394/** HDABDLEDESC field descriptors for the v7 saved state. */
395static SSMFIELD const g_aSSMBDLEDescFields7[] =
396{
397 SSMFIELD_ENTRY(HDABDLEDESC, u64BufAdr),
398 SSMFIELD_ENTRY(HDABDLEDESC, u32BufSize),
399 SSMFIELD_ENTRY(HDABDLEDESC, fFlags),
400 SSMFIELD_ENTRY_TERM()
401};
402
403/** HDABDLESTATE field descriptors for the v6+ saved state. */
404static SSMFIELD const g_aSSMBDLEStateFields6[] =
405{
406 SSMFIELD_ENTRY(HDABDLESTATE, u32BDLIndex),
407 SSMFIELD_ENTRY(HDABDLESTATE, cbBelowFIFOW),
408 SSMFIELD_ENTRY_OLD(FIFO, HDA_FIFO_MAX), /* Deprecated; now is handled in the stream's circular buffer. */
409 SSMFIELD_ENTRY(HDABDLESTATE, u32BufOff),
410 SSMFIELD_ENTRY_TERM()
411};
412
413/** HDABDLESTATE field descriptors for the v7 saved state. */
414static SSMFIELD const g_aSSMBDLEStateFields7[] =
415{
416 SSMFIELD_ENTRY(HDABDLESTATE, u32BDLIndex),
417 SSMFIELD_ENTRY(HDABDLESTATE, cbBelowFIFOW),
418 SSMFIELD_ENTRY(HDABDLESTATE, u32BufOff),
419 SSMFIELD_ENTRY_TERM()
420};
421
422/** HDASTREAMSTATE field descriptors for the v6 saved state. */
423static SSMFIELD const g_aSSMStreamStateFields6[] =
424{
425 SSMFIELD_ENTRY_OLD(cBDLE, sizeof(uint16_t)), /* Deprecated. */
426 SSMFIELD_ENTRY(HDASTREAMSTATE, uCurBDLE),
427 SSMFIELD_ENTRY_OLD(fStop, 1), /* Deprecated; see SSMR3PutBool(). */
428 SSMFIELD_ENTRY_OLD(fRunning, 1), /* Deprecated; using the HDA_SDCTL_RUN bit is sufficient. */
429 SSMFIELD_ENTRY(HDASTREAMSTATE, fInReset),
430 SSMFIELD_ENTRY_TERM()
431};
432
433/** HDASTREAMSTATE field descriptors for the v7 saved state. */
434static SSMFIELD const g_aSSMStreamStateFields7[] =
435{
436 SSMFIELD_ENTRY(HDASTREAMSTATE, uCurBDLE),
437 SSMFIELD_ENTRY(HDASTREAMSTATE, fInReset),
438 SSMFIELD_ENTRY(HDASTREAMSTATE, tsTransferNext),
439 SSMFIELD_ENTRY_TERM()
440};
441
442/** HDASTREAMPERIOD field descriptors for the v7 saved state. */
443static SSMFIELD const g_aSSMStreamPeriodFields7[] =
444{
445 SSMFIELD_ENTRY(HDASTREAMPERIOD, u64StartWalClk),
446 SSMFIELD_ENTRY(HDASTREAMPERIOD, u64ElapsedWalClk),
447 SSMFIELD_ENTRY(HDASTREAMPERIOD, framesTransferred),
448 SSMFIELD_ENTRY(HDASTREAMPERIOD, cIntPending),
449 SSMFIELD_ENTRY_TERM()
450};
451#endif
452
453/**
454 * 32-bit size indexed masks, i.e. g_afMasks[2 bytes] = 0xffff.
455 */
456static uint32_t const g_afMasks[5] =
457{
458 UINT32_C(0), UINT32_C(0x000000ff), UINT32_C(0x0000ffff), UINT32_C(0x00ffffff), UINT32_C(0xffffffff)
459};
460
461/**
462 * Acquires the HDA lock.
463 */
464#define DEVHDA_LOCK(a_pThis) \
465 do { \
466 int rcLock = PDMCritSectEnter(&(a_pThis)->CritSect, VERR_IGNORED); \
467 AssertRC(rcLock); \
468 } while (0)
469
470/**
471 * Acquires the HDA lock or returns.
472 */
473# define DEVHDA_LOCK_RETURN(a_pThis, a_rcBusy) \
474 do { \
475 int rcLock = PDMCritSectEnter(&(a_pThis)->CritSect, a_rcBusy); \
476 if (rcLock != VINF_SUCCESS) \
477 { \
478 AssertRC(rcLock); \
479 return rcLock; \
480 } \
481 } while (0)
482
483/**
484 * Acquires the HDA lock or returns.
485 */
486# define DEVHDA_LOCK_RETURN_VOID(a_pThis) \
487 do { \
488 int rcLock = PDMCritSectEnter(&(a_pThis)->CritSect, VERR_IGNORED); \
489 if (rcLock != VINF_SUCCESS) \
490 { \
491 AssertRC(rcLock); \
492 return; \
493 } \
494 } while (0)
495
496/**
497 * Releases the HDA lock.
498 */
499#define DEVHDA_UNLOCK(a_pThis) \
500 do { PDMCritSectLeave(&(a_pThis)->CritSect); } while (0)
501
502/**
503 * Acquires the TM lock and HDA lock, returns on failure.
504 */
505#define DEVHDA_LOCK_BOTH_RETURN_VOID(a_pThis) \
506 do { \
507 int rcLock = TMTimerLock((a_pThis)->pTimer, VERR_IGNORED); \
508 if (rcLock != VINF_SUCCESS) \
509 { \
510 AssertRC(rcLock); \
511 return; \
512 } \
513 rcLock = PDMCritSectEnter(&(a_pThis)->CritSect, VERR_IGNORED); \
514 if (rcLock != VINF_SUCCESS) \
515 { \
516 AssertRC(rcLock); \
517 TMTimerUnlock((a_pThis)->pTimer); \
518 return; \
519 } \
520 } while (0)
521
522/**
523 * Acquires the TM lock and HDA lock, returns on failure.
524 */
525#define DEVHDA_LOCK_BOTH_RETURN(a_pThis, a_rcBusy) \
526 do { \
527 int rcLock = TMTimerLock((a_pThis)->pTimer, (a_rcBusy)); \
528 if (rcLock != VINF_SUCCESS) \
529 return rcLock; \
530 rcLock = PDMCritSectEnter(&(a_pThis)->CritSect, (a_rcBusy)); \
531 if (rcLock != VINF_SUCCESS) \
532 { \
533 AssertRC(rcLock); \
534 TMTimerUnlock((a_pThis)->pTimer); \
535 return rcLock; \
536 } \
537 } while (0)
538
539/**
540 * Releases the HDA lock and TM lock.
541 */
542#define DEVHDA_UNLOCK_BOTH(a_pThis) \
543 do { \
544 PDMCritSectLeave(&(a_pThis)->CritSect); \
545 TMTimerUnlock((a_pThis)->pTimer); \
546 } while (0)
547
548#ifdef IN_RING3
549/**
550 * Retrieves the number of bytes of a FIFOW register.
551 *
552 * @return Number of bytes of a given FIFOW register.
553 */
554DECLINLINE(uint8_t) hdaSDFIFOWToBytes(uint32_t u32RegFIFOW)
555{
556 uint32_t cb;
557 switch (u32RegFIFOW)
558 {
559 case HDA_SDFIFOW_8B: cb = 8; break;
560 case HDA_SDFIFOW_16B: cb = 16; break;
561 case HDA_SDFIFOW_32B: cb = 32; break;
562 default: cb = 0; break;
563 }
564
565 Assert(RT_IS_POWER_OF_TWO(cb));
566 return cb;
567}
568
569/**
570 * Reschedules pending interrupts for all audio streams which have complete
571 * audio periods but did not have the chance to issue their (pending) interrupts yet.
572 *
573 * @param pThis The HDA device state.
574 */
575static void hdaReschedulePendingInterrupts(PHDASTATE pThis)
576{
577 bool fInterrupt = false;
578
579 for (uint8_t i = 0; i < HDA_MAX_STREAMS; ++i)
580 {
581 PHDASTREAM pStream = hdaGetStreamFromSD(pThis, i);
582 if (!pStream)
583 continue;
584
585 if ( hdaStreamPeriodIsComplete (&pStream->State.Period)
586 && hdaStreamPeriodNeedsInterrupt(&pStream->State.Period)
587 && hdaWalClkSet(pThis, hdaStreamPeriodGetAbsElapsedWalClk(&pStream->State.Period), false /* fForce */))
588 {
589 fInterrupt = true;
590 break;
591 }
592 }
593
594 LogFunc(("fInterrupt=%RTbool\n", fInterrupt));
595
596#ifndef DEBUG
597 hdaProcessInterrupt(pThis);
598#else
599 hdaProcessInterrupt(pThis, __FUNCTION__);
600#endif
601}
602#endif
603
604/**
605 * Looks up a register at the exact offset given by @a offReg.
606 *
607 * @returns Register index on success, -1 if not found.
608 * @param offReg The register offset.
609 */
610static int hdaRegLookup(uint32_t offReg)
611{
612 /*
613 * Aliases.
614 */
615 if (offReg >= g_aHdaRegAliases[0].offReg)
616 {
617 for (unsigned i = 0; i < RT_ELEMENTS(g_aHdaRegAliases); i++)
618 if (offReg == g_aHdaRegAliases[i].offReg)
619 return g_aHdaRegAliases[i].idxAlias;
620 Assert(g_aHdaRegMap[RT_ELEMENTS(g_aHdaRegMap) - 1].offset < offReg);
621 return -1;
622 }
623
624 /*
625 * Binary search the
626 */
627 int idxEnd = RT_ELEMENTS(g_aHdaRegMap);
628 int idxLow = 0;
629 for (;;)
630 {
631 int idxMiddle = idxLow + (idxEnd - idxLow) / 2;
632 if (offReg < g_aHdaRegMap[idxMiddle].offset)
633 {
634 if (idxLow == idxMiddle)
635 break;
636 idxEnd = idxMiddle;
637 }
638 else if (offReg > g_aHdaRegMap[idxMiddle].offset)
639 {
640 idxLow = idxMiddle + 1;
641 if (idxLow >= idxEnd)
642 break;
643 }
644 else
645 return idxMiddle;
646 }
647
648#ifdef RT_STRICT
649 for (unsigned i = 0; i < RT_ELEMENTS(g_aHdaRegMap); i++)
650 Assert(g_aHdaRegMap[i].offset != offReg);
651#endif
652 return -1;
653}
654
655/**
656 * Looks up a register covering the offset given by @a offReg.
657 *
658 * @returns Register index on success, -1 if not found.
659 * @param offReg The register offset.
660 */
661static int hdaRegLookupWithin(uint32_t offReg)
662{
663 /*
664 * Aliases.
665 */
666 if (offReg >= g_aHdaRegAliases[0].offReg)
667 {
668 for (unsigned i = 0; i < RT_ELEMENTS(g_aHdaRegAliases); i++)
669 {
670 uint32_t off = offReg - g_aHdaRegAliases[i].offReg;
671 if (off < 4 && off < g_aHdaRegMap[g_aHdaRegAliases[i].idxAlias].size)
672 return g_aHdaRegAliases[i].idxAlias;
673 }
674 Assert(g_aHdaRegMap[RT_ELEMENTS(g_aHdaRegMap) - 1].offset < offReg);
675 return -1;
676 }
677
678 /*
679 * Binary search the register map.
680 */
681 int idxEnd = RT_ELEMENTS(g_aHdaRegMap);
682 int idxLow = 0;
683 for (;;)
684 {
685 int idxMiddle = idxLow + (idxEnd - idxLow) / 2;
686 if (offReg < g_aHdaRegMap[idxMiddle].offset)
687 {
688 if (idxLow == idxMiddle)
689 break;
690 idxEnd = idxMiddle;
691 }
692 else if (offReg >= g_aHdaRegMap[idxMiddle].offset + g_aHdaRegMap[idxMiddle].size)
693 {
694 idxLow = idxMiddle + 1;
695 if (idxLow >= idxEnd)
696 break;
697 }
698 else
699 return idxMiddle;
700 }
701
702#ifdef RT_STRICT
703 for (unsigned i = 0; i < RT_ELEMENTS(g_aHdaRegMap); i++)
704 Assert(offReg - g_aHdaRegMap[i].offset >= g_aHdaRegMap[i].size);
705#endif
706 return -1;
707}
708
709#ifdef IN_RING3
710/**
711 * Synchronizes the CORB / RIRB buffers between internal <-> device state.
712 *
713 * @returns IPRT status code.
714 * @param pThis HDA state.
715 * @param fLocal Specify true to synchronize HDA state's CORB buffer with the device state,
716 * or false to synchronize the device state's RIRB buffer with the HDA state.
717 *
718 * @todo r=andy Break this up into two functions?
719 */
720static int hdaCmdSync(PHDASTATE pThis, bool fLocal)
721{
722 int rc = VINF_SUCCESS;
723 if (fLocal)
724 {
725 if (pThis->u64CORBBase)
726 {
727 AssertPtr(pThis->pu32CorbBuf);
728 Assert(pThis->cbCorbBuf);
729
730 rc = PDMDevHlpPhysRead(pThis->CTX_SUFF(pDevIns), pThis->u64CORBBase, pThis->pu32CorbBuf, pThis->cbCorbBuf);
731 if (RT_FAILURE(rc))
732 AssertRCReturn(rc, rc);
733 }
734 }
735 else
736 {
737 if (pThis->u64RIRBBase)
738 {
739 AssertPtr(pThis->pu64RirbBuf);
740 Assert(pThis->cbRirbBuf);
741
742 rc = PDMDevHlpPCIPhysWrite(pThis->CTX_SUFF(pDevIns), pThis->u64RIRBBase, pThis->pu64RirbBuf, pThis->cbRirbBuf);
743 if (RT_FAILURE(rc))
744 AssertRCReturn(rc, rc);
745 }
746 }
747
748#ifdef DEBUG_CMD_BUFFER
749 LogFunc(("fLocal=%RTbool\n", fLocal));
750
751 uint8_t i = 0;
752 do
753 {
754 LogFunc(("CORB%02x: ", i));
755 uint8_t j = 0;
756 do
757 {
758 const char *pszPrefix;
759 if ((i + j) == HDA_REG(pThis, CORBRP))
760 pszPrefix = "[R]";
761 else if ((i + j) == HDA_REG(pThis, CORBWP))
762 pszPrefix = "[W]";
763 else
764 pszPrefix = " "; /* three spaces */
765 Log((" %s%08x", pszPrefix, pThis->pu32CorbBuf[i + j]));
766 j++;
767 } while (j < 8);
768 Log(("\n"));
769 i += 8;
770 } while(i != 0);
771
772 do {
773 LogFunc(("RIRB%02x: ", i));
774 uint8_t j = 0;
775 do {
776 const char *prefix;
777 if ((i + j) == HDA_REG(pThis, RIRBWP))
778 prefix = "[W]";
779 else
780 prefix = " ";
781 Log((" %s%016lx", prefix, pThis->pu64RirbBuf[i + j]));
782 } while (++j < 8);
783 Log(("\n"));
784 i += 8;
785 } while (i != 0);
786#endif
787 return rc;
788}
789
790/**
791 * Processes the next CORB buffer command in the queue.
792 * This will invoke the HDA codec verb dispatcher.
793 *
794 * @returns IPRT status code.
795 * @param pThis HDA state.
796 */
797static int hdaCORBCmdProcess(PHDASTATE pThis)
798{
799 uint8_t corbRp = HDA_REG(pThis, CORBRP);
800 uint8_t corbWp = HDA_REG(pThis, CORBWP);
801 uint8_t rirbWp = HDA_REG(pThis, RIRBWP);
802
803 Log3Func(("CORB(RP:%x, WP:%x) RIRBWP:%x\n", corbRp, corbWp, rirbWp));
804
805 if (!(HDA_REG(pThis, CORBCTL) & HDA_CORBCTL_DMA))
806 {
807 LogFunc(("CORB DMA not active, skipping\n"));
808 return VINF_SUCCESS;
809 }
810
811 Assert(pThis->cbCorbBuf);
812
813 int rc = hdaCmdSync(pThis, true /* Sync from guest */);
814 AssertRCReturn(rc, rc);
815
816 uint16_t cIntCnt = HDA_REG(pThis, RINTCNT) & 0xff;
817
818 if (!cIntCnt) /* 0 means 256 interrupts. */
819 cIntCnt = HDA_MAX_RINTCNT;
820
821 Log3Func(("START CORB(RP:%x, WP:%x) RIRBWP:%x, RINTCNT:%RU8/%RU8\n",
822 corbRp, corbWp, rirbWp, pThis->u16RespIntCnt, cIntCnt));
823
824 while (corbRp != corbWp)
825 {
826 corbRp = (corbRp + 1) % (pThis->cbCorbBuf / HDA_CORB_ELEMENT_SIZE); /* Advance +1 as the first command(s) are at CORBWP + 1. */
827
828 uint32_t uCmd = pThis->pu32CorbBuf[corbRp];
829 uint64_t uResp = 0;
830
831 rc = pThis->pCodec->pfnLookup(pThis->pCodec, HDA_CODEC_CMD(uCmd, 0 /* Codec index */), &uResp);
832 if (RT_FAILURE(rc))
833 LogFunc(("Codec lookup failed with rc=%Rrc\n", rc));
834
835 Log3Func(("Codec verb %08x -> response %016lx\n", uCmd, uResp));
836
837 if ( (uResp & CODEC_RESPONSE_UNSOLICITED)
838 && !(HDA_REG(pThis, GCTL) & HDA_GCTL_UNSOL))
839 {
840 LogFunc(("Unexpected unsolicited response.\n"));
841 HDA_REG(pThis, CORBRP) = corbRp;
842
843 /** @todo r=andy No CORB/RIRB syncing to guest required in that case? */
844 return rc;
845 }
846
847 rirbWp = (rirbWp + 1) % HDA_RIRB_SIZE;
848
849 pThis->pu64RirbBuf[rirbWp] = uResp;
850
851 pThis->u16RespIntCnt++;
852
853 bool fSendInterrupt = false;
854
855 if (pThis->u16RespIntCnt == cIntCnt) /* Response interrupt count reached? */
856 {
857 pThis->u16RespIntCnt = 0; /* Reset internal interrupt response counter. */
858
859 Log3Func(("Response interrupt count reached (%RU16)\n", pThis->u16RespIntCnt));
860 fSendInterrupt = true;
861
862 }
863 else if (corbRp == corbWp) /* Did we reach the end of the current command buffer? */
864 {
865 Log3Func(("Command buffer empty\n"));
866 fSendInterrupt = true;
867 }
868
869 if (fSendInterrupt)
870 {
871 if (HDA_REG(pThis, RIRBCTL) & HDA_RIRBCTL_RINTCTL) /* Response Interrupt Control (RINTCTL) enabled? */
872 {
873 HDA_REG(pThis, RIRBSTS) |= HDA_RIRBSTS_RINTFL;
874
875#ifndef DEBUG
876 rc = hdaProcessInterrupt(pThis);
877#else
878 rc = hdaProcessInterrupt(pThis, __FUNCTION__);
879#endif
880 }
881 }
882 }
883
884 Log3Func(("END CORB(RP:%x, WP:%x) RIRBWP:%x, RINTCNT:%RU8/%RU8\n",
885 corbRp, corbWp, rirbWp, pThis->u16RespIntCnt, cIntCnt));
886
887 HDA_REG(pThis, CORBRP) = corbRp;
888 HDA_REG(pThis, RIRBWP) = rirbWp;
889
890 rc = hdaCmdSync(pThis, false /* Sync to guest */);
891 AssertRCReturn(rc, rc);
892
893 if (RT_FAILURE(rc))
894 AssertRCReturn(rc, rc);
895
896 return rc;
897}
898#endif /* IN_RING3 */
899
900/* Register access handlers. */
901
902static int hdaRegReadUnimpl(PHDASTATE pThis, uint32_t iReg, uint32_t *pu32Value)
903{
904 RT_NOREF_PV(pThis); RT_NOREF_PV(iReg);
905 *pu32Value = 0;
906 return VINF_SUCCESS;
907}
908
909static int hdaRegWriteUnimpl(PHDASTATE pThis, uint32_t iReg, uint32_t u32Value)
910{
911 RT_NOREF_PV(pThis); RT_NOREF_PV(iReg); RT_NOREF_PV(u32Value);
912 return VINF_SUCCESS;
913}
914
915/* U8 */
916static int hdaRegReadU8(PHDASTATE pThis, uint32_t iReg, uint32_t *pu32Value)
917{
918 Assert(((pThis->au32Regs[g_aHdaRegMap[iReg].mem_idx] & g_aHdaRegMap[iReg].readable) & 0xffffff00) == 0);
919 return hdaRegReadU32(pThis, iReg, pu32Value);
920}
921
922static int hdaRegWriteU8(PHDASTATE pThis, uint32_t iReg, uint32_t u32Value)
923{
924 Assert((u32Value & 0xffffff00) == 0);
925 return hdaRegWriteU32(pThis, iReg, u32Value);
926}
927
928/* U16 */
929static int hdaRegReadU16(PHDASTATE pThis, uint32_t iReg, uint32_t *pu32Value)
930{
931 Assert(((pThis->au32Regs[g_aHdaRegMap[iReg].mem_idx] & g_aHdaRegMap[iReg].readable) & 0xffff0000) == 0);
932 return hdaRegReadU32(pThis, iReg, pu32Value);
933}
934
935static int hdaRegWriteU16(PHDASTATE pThis, uint32_t iReg, uint32_t u32Value)
936{
937 Assert((u32Value & 0xffff0000) == 0);
938 return hdaRegWriteU32(pThis, iReg, u32Value);
939}
940
941/* U24 */
942static int hdaRegReadU24(PHDASTATE pThis, uint32_t iReg, uint32_t *pu32Value)
943{
944 Assert(((pThis->au32Regs[g_aHdaRegMap[iReg].mem_idx] & g_aHdaRegMap[iReg].readable) & 0xff000000) == 0);
945 return hdaRegReadU32(pThis, iReg, pu32Value);
946}
947
948#ifdef IN_RING3
949static int hdaRegWriteU24(PHDASTATE pThis, uint32_t iReg, uint32_t u32Value)
950{
951 Assert((u32Value & 0xff000000) == 0);
952 return hdaRegWriteU32(pThis, iReg, u32Value);
953}
954#endif
955
956/* U32 */
957static int hdaRegReadU32(PHDASTATE pThis, uint32_t iReg, uint32_t *pu32Value)
958{
959 uint32_t iRegMem = g_aHdaRegMap[iReg].mem_idx;
960
961 DEVHDA_LOCK_RETURN(pThis, VINF_IOM_R3_MMIO_READ);
962
963 *pu32Value = pThis->au32Regs[iRegMem] & g_aHdaRegMap[iReg].readable;
964
965 DEVHDA_UNLOCK(pThis);
966 return VINF_SUCCESS;
967}
968
969static int hdaRegWriteU32(PHDASTATE pThis, uint32_t iReg, uint32_t u32Value)
970{
971 DEVHDA_LOCK_RETURN(pThis, VINF_IOM_R3_MMIO_WRITE);
972
973 uint32_t iRegMem = g_aHdaRegMap[iReg].mem_idx;
974
975 pThis->au32Regs[iRegMem] = (u32Value & g_aHdaRegMap[iReg].writable)
976 | (pThis->au32Regs[iRegMem] & ~g_aHdaRegMap[iReg].writable);
977 DEVHDA_UNLOCK(pThis);
978 return VINF_SUCCESS;
979}
980
981static int hdaRegWriteGCTL(PHDASTATE pThis, uint32_t iReg, uint32_t u32Value)
982{
983 RT_NOREF_PV(iReg);
984
985 if (u32Value & HDA_GCTL_CRST)
986 {
987 DEVHDA_LOCK_RETURN(pThis, VINF_IOM_R3_MMIO_WRITE);
988
989 /* Set the CRST bit to indicate that we're leaving reset mode. */
990 HDA_REG(pThis, GCTL) |= HDA_GCTL_CRST;
991 LogFunc(("Guest leaving HDA reset\n"));
992
993 DEVHDA_UNLOCK(pThis);
994 }
995 else
996 {
997#ifdef IN_RING3
998 DEVHDA_LOCK(pThis);
999
1000 /* Enter reset state. */
1001 LogFunc(("Guest entering HDA reset with DMA(RIRB:%s, CORB:%s)\n",
1002 HDA_REG(pThis, CORBCTL) & HDA_CORBCTL_DMA ? "on" : "off",
1003 HDA_REG(pThis, RIRBCTL) & HDA_RIRBCTL_RDMAEN ? "on" : "off"));
1004
1005 /* Clear the CRST bit to indicate that we're in reset state. */
1006 HDA_REG(pThis, GCTL) &= ~HDA_GCTL_CRST;
1007
1008 hdaGCTLReset(pThis);
1009
1010 DEVHDA_UNLOCK(pThis);
1011#else
1012 return VINF_IOM_R3_MMIO_WRITE;
1013#endif
1014 }
1015
1016 if (u32Value & HDA_GCTL_FCNTRL)
1017 {
1018 DEVHDA_LOCK(pThis);
1019
1020 /* Flush: GSTS:1 set, see 6.2.6. */
1021 HDA_REG(pThis, GSTS) |= HDA_GSTS_FSTS; /* Set the flush status. */
1022 /* DPLBASE and DPUBASE should be initialized with initial value (see 6.2.6). */
1023
1024 DEVHDA_UNLOCK(pThis);
1025 }
1026
1027 return VINF_SUCCESS;
1028}
1029
1030static int hdaRegWriteSTATESTS(PHDASTATE pThis, uint32_t iReg, uint32_t u32Value)
1031{
1032 DEVHDA_LOCK_RETURN(pThis, VINF_IOM_R3_MMIO_WRITE);
1033
1034 uint32_t v = HDA_REG_IND(pThis, iReg);
1035 uint32_t nv = u32Value & HDA_STATESTS_SCSF_MASK;
1036
1037 HDA_REG(pThis, STATESTS) &= ~(v & nv); /* Write of 1 clears corresponding bit. */
1038
1039 DEVHDA_UNLOCK(pThis);
1040
1041 return VINF_SUCCESS;
1042}
1043
1044static int hdaRegReadLPIB(PHDASTATE pThis, uint32_t iReg, uint32_t *pu32Value)
1045{
1046 DEVHDA_LOCK_RETURN(pThis, VINF_IOM_R3_MMIO_READ);
1047
1048 const uint8_t uSD = HDA_SD_NUM_FROM_REG(pThis, LPIB, iReg);
1049 uint32_t u32LPIB = HDA_STREAM_REG(pThis, LPIB, uSD);
1050#ifdef LOG_ENABLED
1051 const uint32_t u32CBL = HDA_STREAM_REG(pThis, CBL, uSD);
1052 LogFlowFunc(("[SD%RU8] LPIB=%RU32, CBL=%RU32\n", uSD, u32LPIB, u32CBL));
1053#endif
1054
1055 *pu32Value = u32LPIB;
1056
1057 DEVHDA_UNLOCK(pThis);
1058 return VINF_SUCCESS;
1059}
1060
1061#ifdef IN_RING3
1062/**
1063 * Returns the current maximum value the wall clock counter can be set to.
1064 * This maximum value depends on all currently handled HDA streams and their own current timing.
1065 *
1066 * @return Current maximum value the wall clock counter can be set to.
1067 * @param pThis HDA state.
1068 *
1069 * @remark Does not actually set the wall clock counter.
1070 */
1071uint64_t hdaWalClkGetMax(PHDASTATE pThis)
1072{
1073 const uint64_t u64WalClkCur = ASMAtomicReadU64(&pThis->u64WalClk);
1074 const uint64_t u64FrontAbsWalClk = pThis->SinkFront.pStream
1075 ? hdaStreamPeriodGetAbsElapsedWalClk(&pThis->SinkFront.pStream->State.Period) : 0;
1076#ifdef VBOX_WITH_AUDIO_HDA_51_SURROUND
1077# error "Implement me!"
1078#endif
1079 const uint64_t u64LineInAbsWalClk = pThis->SinkLineIn.pStream
1080 ? hdaStreamPeriodGetAbsElapsedWalClk(&pThis->SinkLineIn.pStream->State.Period) : 0;
1081#ifdef VBOX_WITH_HDA_MIC_IN
1082 const uint64_t u64MicInAbsWalClk = pThis->SinkMicIn.pStream
1083 ? hdaStreamPeriodGetAbsElapsedWalClk(&pThis->SinkMicIn.pStream->State.Period) : 0;
1084#endif
1085
1086 uint64_t u64WalClkNew = RT_MAX(u64WalClkCur, u64FrontAbsWalClk);
1087#ifdef VBOX_WITH_AUDIO_HDA_51_SURROUND
1088# error "Implement me!"
1089#endif
1090 u64WalClkNew = RT_MAX(u64WalClkNew, u64LineInAbsWalClk);
1091#ifdef VBOX_WITH_HDA_MIC_IN
1092 u64WalClkNew = RT_MAX(u64WalClkNew, u64MicInAbsWalClk);
1093#endif
1094
1095 Log3Func(("%RU64 -> Front=%RU64, LineIn=%RU64 -> %RU64\n",
1096 u64WalClkCur, u64FrontAbsWalClk, u64LineInAbsWalClk, u64WalClkNew));
1097
1098 return u64WalClkNew;
1099}
1100#endif /* IN_RING3 */
1101
1102static int hdaRegReadWALCLK(PHDASTATE pThis, uint32_t iReg, uint32_t *pu32Value)
1103{
1104#ifdef IN_RING3
1105 RT_NOREF(iReg);
1106
1107 DEVHDA_LOCK(pThis);
1108
1109 *pu32Value = RT_LO_U32(ASMAtomicReadU64(&pThis->u64WalClk));
1110
1111 Log3Func(("%RU32 (max @ %RU64)\n",*pu32Value, hdaWalClkGetMax(pThis)));
1112
1113 DEVHDA_UNLOCK(pThis);
1114 return VINF_SUCCESS;
1115#else
1116 RT_NOREF(pThis, iReg, pu32Value);
1117 return VINF_IOM_R3_MMIO_WRITE;
1118#endif
1119}
1120
1121static int hdaRegWriteCORBRP(PHDASTATE pThis, uint32_t iReg, uint32_t u32Value)
1122{
1123 RT_NOREF(iReg);
1124
1125 DEVHDA_LOCK_RETURN(pThis, VINF_IOM_R3_MMIO_WRITE);
1126
1127 if (u32Value & HDA_CORBRP_RST)
1128 {
1129 /* Do a CORB reset. */
1130 if (pThis->cbCorbBuf)
1131 {
1132 Assert(pThis->pu32CorbBuf);
1133 RT_BZERO((void *)pThis->pu32CorbBuf, pThis->cbCorbBuf);
1134 }
1135
1136 LogRel2(("HDA: CORB reset\n"));
1137
1138 HDA_REG(pThis, CORBRP) = HDA_CORBRP_RST; /* Clears the pointer. */
1139 }
1140 else
1141 HDA_REG(pThis, CORBRP) &= ~HDA_CORBRP_RST; /* Only CORBRP_RST bit is writable. */
1142
1143 DEVHDA_UNLOCK(pThis);
1144 return VINF_SUCCESS;
1145}
1146
1147static int hdaRegWriteCORBCTL(PHDASTATE pThis, uint32_t iReg, uint32_t u32Value)
1148{
1149#ifdef IN_RING3
1150 DEVHDA_LOCK_RETURN(pThis, VINF_IOM_R3_MMIO_WRITE);
1151
1152 int rc = hdaRegWriteU8(pThis, iReg, u32Value);
1153 AssertRC(rc);
1154
1155 if (HDA_REG(pThis, CORBCTL) & HDA_CORBCTL_DMA) /* Start DMA engine. */
1156 {
1157 rc = hdaCORBCmdProcess(pThis);
1158 }
1159 else
1160 LogFunc(("CORB DMA not running, skipping\n"));
1161
1162 DEVHDA_UNLOCK(pThis);
1163 return rc;
1164#else
1165 RT_NOREF(pThis, iReg, u32Value);
1166 return VINF_IOM_R3_MMIO_WRITE;
1167#endif
1168}
1169
1170static int hdaRegWriteCORBSIZE(PHDASTATE pThis, uint32_t iReg, uint32_t u32Value)
1171{
1172#ifdef IN_RING3
1173 RT_NOREF(iReg);
1174
1175 DEVHDA_LOCK_RETURN(pThis, VINF_IOM_R3_MMIO_WRITE);
1176
1177 if (HDA_REG(pThis, CORBCTL) & HDA_CORBCTL_DMA) /* Ignore request if CORB DMA engine is (still) running. */
1178 {
1179 LogFunc(("CORB DMA is (still) running, skipping\n"));
1180
1181 DEVHDA_UNLOCK(pThis);
1182 return VINF_SUCCESS;
1183 }
1184
1185 u32Value = (u32Value & HDA_CORBSIZE_SZ);
1186
1187 uint16_t cEntries = HDA_CORB_SIZE; /* Set default. */
1188
1189 switch (u32Value)
1190 {
1191 case 0: /* 8 byte; 2 entries. */
1192 cEntries = 2;
1193 break;
1194
1195 case 1: /* 64 byte; 16 entries. */
1196 cEntries = 16;
1197 break;
1198
1199 case 2: /* 1 KB; 256 entries. */
1200 /* Use default size. */
1201 break;
1202
1203 default:
1204 LogRel(("HDA: Guest tried to set an invalid CORB size (0x%x), keeping default\n", u32Value));
1205 u32Value = 2;
1206 /* Use default size. */
1207 break;
1208 }
1209
1210 uint32_t cbCorbBuf = cEntries * sizeof(uint32_t);
1211
1212 if (cbCorbBuf != pThis->cbCorbBuf)
1213 {
1214 if (pThis->pu32CorbBuf)
1215 {
1216 RTMemFree(pThis->pu32CorbBuf);
1217 pThis->pu32CorbBuf = NULL;
1218 }
1219
1220 if (cbCorbBuf)
1221 {
1222 Assert(cbCorbBuf % sizeof(uint32_t) == 0);
1223
1224 pThis->pu32CorbBuf = (uint32_t *)RTMemAllocZ(cbCorbBuf);
1225 pThis->cbCorbBuf = cbCorbBuf;
1226 }
1227 }
1228
1229 LogFunc(("CORB buffer size is now %RU32 bytes (%u entries)\n", pThis->cbCorbBuf, pThis->cbCorbBuf / HDA_CORB_ELEMENT_SIZE));
1230
1231 HDA_REG(pThis, CORBSIZE) = u32Value;
1232
1233 DEVHDA_UNLOCK(pThis);
1234 return VINF_SUCCESS;
1235#else
1236 RT_NOREF(pThis, iReg, u32Value);
1237 return VINF_IOM_R3_MMIO_WRITE;
1238#endif
1239}
1240
1241static int hdaRegWriteCORBSTS(PHDASTATE pThis, uint32_t iReg, uint32_t u32Value)
1242{
1243 RT_NOREF_PV(iReg);
1244
1245 DEVHDA_LOCK_RETURN(pThis, VINF_IOM_R3_MMIO_WRITE);
1246
1247 uint32_t v = HDA_REG(pThis, CORBSTS);
1248 HDA_REG(pThis, CORBSTS) &= ~(v & u32Value);
1249
1250 DEVHDA_UNLOCK(pThis);
1251 return VINF_SUCCESS;
1252}
1253
1254static int hdaRegWriteCORBWP(PHDASTATE pThis, uint32_t iReg, uint32_t u32Value)
1255{
1256#ifdef IN_RING3
1257 DEVHDA_LOCK_RETURN(pThis, VINF_IOM_R3_MMIO_WRITE);
1258
1259 int rc = hdaRegWriteU16(pThis, iReg, u32Value);
1260 if (RT_FAILURE(rc))
1261 AssertRCReturn(rc, rc);
1262
1263 rc = hdaCORBCmdProcess(pThis);
1264
1265 DEVHDA_UNLOCK(pThis);
1266 return rc;
1267#else
1268 RT_NOREF(pThis, iReg, u32Value);
1269 return VINF_IOM_R3_MMIO_WRITE;
1270#endif
1271}
1272
1273static int hdaRegWriteSDCBL(PHDASTATE pThis, uint32_t iReg, uint32_t u32Value)
1274{
1275#ifdef IN_RING3
1276 DEVHDA_LOCK(pThis);
1277
1278 PHDASTREAM pStream = hdaGetStreamFromSD(pThis, HDA_SD_NUM_FROM_REG(pThis, CBL, iReg));
1279 if (!pStream)
1280 {
1281 LogFunc(("[SD%RU8] Warning: Changing SDCBL on non-attached stream (0x%x)\n",
1282 HDA_SD_NUM_FROM_REG(pThis, CTL, iReg), u32Value));
1283
1284 DEVHDA_UNLOCK(pThis);
1285 return hdaRegWriteU32(pThis, iReg, u32Value);
1286 }
1287
1288 pStream->u32CBL = u32Value;
1289
1290 LogFlowFunc(("[SD%RU8] CBL=%RU32\n", pStream->u8SD, u32Value));
1291
1292 DEVHDA_UNLOCK(pThis);
1293
1294 int rc2 = hdaRegWriteU32(pThis, iReg, u32Value);
1295 AssertRC(rc2);
1296
1297 return VINF_SUCCESS; /* Always return success to the MMIO handler. */
1298#else /* !IN_RING3 */
1299 RT_NOREF_PV(pThis); RT_NOREF_PV(iReg); RT_NOREF_PV(u32Value);
1300 return VINF_IOM_R3_MMIO_WRITE;
1301#endif /* IN_RING3 */
1302}
1303
1304static int hdaRegWriteSDCTL(PHDASTATE pThis, uint32_t iReg, uint32_t u32Value)
1305{
1306#ifdef IN_RING3
1307 DEVHDA_LOCK_BOTH_RETURN(pThis, VINF_IOM_R3_MMIO_WRITE);
1308
1309 /*
1310 * Some guests write too much (that is, 32-bit with the top 8 bit being junk)
1311 * instead of 24-bit required for SDCTL. So just mask this here to be safe.
1312 */
1313 u32Value = (u32Value & 0x00ffffff);
1314
1315 bool fRun = RT_BOOL(u32Value & HDA_SDCTL_RUN);
1316 bool fInRun = RT_BOOL(HDA_REG_IND(pThis, iReg) & HDA_SDCTL_RUN);
1317
1318 bool fReset = RT_BOOL(u32Value & HDA_SDCTL_SRST);
1319 bool fInReset = RT_BOOL(HDA_REG_IND(pThis, iReg) & HDA_SDCTL_SRST);
1320
1321 /* Get the stream descriptor. */
1322 uint8_t uSD = HDA_SD_NUM_FROM_REG(pThis, CTL, iReg);
1323
1324 LogFunc(("[SD%RU8] fRun=%RTbool, fInRun=%RTbool, fReset=%RTbool, fInReset=%RTbool, %R[sdctl]\n",
1325 uSD, fRun, fInRun, fReset, fInReset, u32Value));
1326
1327 /*
1328 * Extract the stream tag the guest wants to use for this specific
1329 * stream descriptor (SDn). This only can happen if the stream is in a non-running
1330 * state, so we're doing the lookup and assignment here.
1331 *
1332 * So depending on the guest OS, SD3 can use stream tag 4, for example.
1333 */
1334 uint8_t uTag = (u32Value >> HDA_SDCTL_NUM_SHIFT) & HDA_SDCTL_NUM_MASK;
1335 if (uTag > HDA_MAX_TAGS)
1336 {
1337 LogFunc(("[SD%RU8] Warning: Invalid stream tag %RU8 specified!\n", uSD, uTag));
1338
1339 DEVHDA_UNLOCK_BOTH(pThis);
1340 return hdaRegWriteU24(pThis, iReg, u32Value);
1341 }
1342
1343 PHDATAG pTag = &pThis->aTags[uTag];
1344 AssertPtr(pTag);
1345
1346 LogFunc(("[SD%RU8] Using stream tag=%RU8\n", uSD, uTag));
1347
1348 /* Assign new values. */
1349 pTag->uTag = uTag;
1350 pTag->pStream = hdaGetStreamFromSD(pThis, uSD);
1351
1352 PHDASTREAM pStream = pTag->pStream;
1353 AssertPtr(pStream);
1354
1355 if (fInReset)
1356 {
1357 Assert(!fReset);
1358 Assert(!fInRun && !fRun);
1359
1360 /* Exit reset state. */
1361 ASMAtomicXchgBool(&pStream->State.fInReset, false);
1362
1363 /* Report that we're done resetting this stream by clearing SRST. */
1364 HDA_STREAM_REG(pThis, CTL, uSD) &= ~HDA_SDCTL_SRST;
1365
1366 LogFunc(("[SD%RU8] Reset exit\n", uSD));
1367 }
1368 else if (fReset)
1369 {
1370 /* ICH6 datasheet 18.2.33 says that RUN bit should be cleared before initiation of reset. */
1371 Assert(!fInRun && !fRun);
1372
1373 LogFunc(("[SD%RU8] Reset enter\n", uSD));
1374
1375 hdaStreamLock(pStream);
1376
1377# ifdef VBOX_WITH_AUDIO_HDA_ASYNC_IO
1378 hdaStreamAsyncIOLock(pStream);
1379 hdaStreamAsyncIOEnable(pStream, false /* fEnable */);
1380# endif
1381 /* Make sure to remove the run bit before doing the actual stream reset. */
1382 HDA_STREAM_REG(pThis, CTL, uSD) &= ~HDA_SDCTL_RUN;
1383
1384 hdaStreamReset(pThis, pStream, pStream->u8SD);
1385
1386# ifdef VBOX_WITH_AUDIO_HDA_ASYNC_IO
1387 hdaStreamAsyncIOUnlock(pStream);
1388# endif
1389 hdaStreamUnlock(pStream);
1390 }
1391 else
1392 {
1393 /*
1394 * We enter here to change DMA states only.
1395 */
1396 if (fInRun != fRun)
1397 {
1398 Assert(!fReset && !fInReset);
1399 LogFunc(("[SD%RU8] State changed (fRun=%RTbool)\n", uSD, fRun));
1400
1401 hdaStreamLock(pStream);
1402
1403# ifdef VBOX_WITH_AUDIO_HDA_ASYNC_IO
1404 hdaStreamAsyncIOLock(pStream);
1405 hdaStreamAsyncIOEnable(pStream, fRun /* fEnable */);
1406# endif
1407 /* (Re-)initialize the stream with current values. */
1408 int rc2 = hdaStreamInit(pStream, pStream->u8SD);
1409 AssertRC(rc2);
1410
1411 /* Enable/disable the stream. */
1412 rc2 = hdaStreamEnable(pStream, fRun /* fEnable */);
1413 AssertRC(rc2);
1414
1415 if (fRun)
1416 {
1417 /* Keep track of running streams. */
1418 pThis->cStreamsActive++;
1419
1420 /* (Re-)init the stream's period. */
1421 hdaStreamPeriodInit(&pStream->State.Period,
1422 pStream->u8SD, pStream->u16LVI, pStream->u32CBL, &pStream->State.Cfg);
1423
1424 /* Begin a new period for this stream. */
1425 rc2 = hdaStreamPeriodBegin(&pStream->State.Period, hdaWalClkGetCurrent(pThis)/* Use current wall clock time */);
1426 AssertRC(rc2);
1427
1428 rc2 = hdaTimerSet(pThis, TMTimerGet(pThis->pTimer) + pStream->State.cTransferTicks, false /* fForce */);
1429 AssertRC(rc2);
1430 }
1431 else
1432 {
1433 /* Keep track of running streams. */
1434 Assert(pThis->cStreamsActive);
1435 if (pThis->cStreamsActive)
1436 pThis->cStreamsActive--;
1437
1438 /* Make sure to (re-)schedule outstanding (delayed) interrupts. */
1439 hdaReschedulePendingInterrupts(pThis);
1440
1441 /* Reset the period. */
1442 hdaStreamPeriodReset(&pStream->State.Period);
1443 }
1444
1445# ifdef VBOX_WITH_AUDIO_HDA_ASYNC_IO
1446 hdaStreamAsyncIOUnlock(pStream);
1447# endif
1448 /* Make sure to leave the lock before (eventually) starting the timer. */
1449 hdaStreamUnlock(pStream);
1450 }
1451 }
1452
1453 int rc2 = hdaRegWriteU24(pThis, iReg, u32Value);
1454 AssertRC(rc2);
1455
1456 DEVHDA_UNLOCK_BOTH(pThis);
1457
1458 return VINF_SUCCESS; /* Always return success to the MMIO handler. */
1459#else /* !IN_RING3 */
1460 RT_NOREF_PV(pThis); RT_NOREF_PV(iReg); RT_NOREF_PV(u32Value);
1461 return VINF_IOM_R3_MMIO_WRITE;
1462#endif /* IN_RING3 */
1463}
1464
1465static int hdaRegWriteSDSTS(PHDASTATE pThis, uint32_t iReg, uint32_t u32Value)
1466{
1467#ifdef IN_RING3
1468 DEVHDA_LOCK_BOTH_RETURN(pThis, VINF_IOM_R3_MMIO_WRITE);
1469
1470 PHDASTREAM pStream = hdaGetStreamFromSD(pThis, HDA_SD_NUM_FROM_REG(pThis, STS, iReg));
1471 if (!pStream)
1472 {
1473 AssertMsgFailed(("[SD%RU8] Warning: Writing SDSTS on non-attached stream (0x%x)\n",
1474 HDA_SD_NUM_FROM_REG(pThis, STS, iReg), u32Value));
1475
1476 DEVHDA_UNLOCK_BOTH(pThis);
1477 return hdaRegWriteU16(pThis, iReg, u32Value);
1478 }
1479
1480 hdaStreamLock(pStream);
1481
1482 uint32_t v = HDA_REG_IND(pThis, iReg);
1483
1484 /* Clear (zero) FIFOE, DESE and BCIS bits when writing 1 to it (6.2.33). */
1485 HDA_REG_IND(pThis, iReg) &= ~(u32Value & v);
1486
1487 /* Some guests tend to write SDnSTS even if the stream is not running.
1488 * So make sure to check if the RUN bit is set first. */
1489 const bool fRunning = pStream->State.fRunning;
1490
1491 Log3Func(("[SD%RU8] fRunning=%RTbool %R[sdsts]\n", pStream->u8SD, fRunning, v));
1492
1493 PHDASTREAMPERIOD pPeriod = &pStream->State.Period;
1494
1495 if (hdaStreamPeriodLock(pPeriod))
1496 {
1497 const bool fNeedsInterrupt = hdaStreamPeriodNeedsInterrupt(pPeriod);
1498 if (fNeedsInterrupt)
1499 hdaStreamPeriodReleaseInterrupt(pPeriod);
1500
1501 if (hdaStreamPeriodIsComplete(pPeriod))
1502 {
1503 /* Make sure to try to update the WALCLK register if a period is complete.
1504 * Use the maximum WALCLK value all (active) streams agree to. */
1505 const uint64_t uWalClkMax = hdaWalClkGetMax(pThis);
1506 if (uWalClkMax > hdaWalClkGetCurrent(pThis))
1507 hdaWalClkSet(pThis, uWalClkMax, false /* fForce */);
1508
1509 hdaStreamPeriodEnd(pPeriod);
1510
1511 if (fRunning)
1512 hdaStreamPeriodBegin(pPeriod, hdaWalClkGetCurrent(pThis) /* Use current wall clock time */);
1513 }
1514
1515 hdaStreamPeriodUnlock(pPeriod); /* Unlock before processing interrupt. */
1516 }
1517
1518#ifndef DEBUG
1519 hdaProcessInterrupt(pThis);
1520#else
1521 hdaProcessInterrupt(pThis, __FUNCTION__);
1522#endif
1523
1524 const uint64_t tsNow = TMTimerGet(pThis->pTimer);
1525 Assert(tsNow >= pStream->State.tsTransferLast);
1526
1527 const uint64_t cTicksElapsed = tsNow - pStream->State.tsTransferLast;
1528#ifdef LOG_ENABLED
1529 const uint64_t cTicksTransferred = pStream->State.cbTransferProcessed * pStream->State.cTicksPerByte;
1530#endif
1531
1532 uint64_t cTicksToNext = pStream->State.cTransferTicks;
1533 if (cTicksToNext) /* Only do any calculations if the stream currently is set up for transfers. */
1534 {
1535 Log3Func(("[SD%RU8] cTicksElapsed=%RU64, cTicksTransferred=%RU64, cTicksToNext=%RU64\n",
1536 pStream->u8SD, cTicksElapsed, cTicksTransferred, cTicksToNext));
1537
1538 Log3Func(("[SD%RU8] cbTransferProcessed=%RU32, cbTransferChunk=%RU32, cbTransferSize=%RU32\n",
1539 pStream->u8SD, pStream->State.cbTransferProcessed, pStream->State.cbTransferChunk, pStream->State.cbTransferSize));
1540
1541 if (cTicksElapsed <= cTicksToNext)
1542 {
1543 cTicksToNext = cTicksToNext - cTicksElapsed;
1544 }
1545 else /* Catch up. */
1546 {
1547 Log3Func(("[SD%RU8] Warning: Lagging behind (%RU64 ticks elapsed, maximum allowed is %RU64)\n",
1548 pStream->u8SD, cTicksElapsed, cTicksToNext));
1549
1550 LogRelMax2(64, ("HDA: Stream #%RU8 interrupt lagging behind (expected %uus, got %uus), trying to catch up ...\n",
1551 pStream->u8SD,
1552 (TMTimerGetFreq(pThis->pTimer) / pThis->u16TimerHz) / 1000, (tsNow - pStream->State.tsTransferLast) / 1000));
1553
1554 cTicksToNext = 0;
1555 }
1556
1557 Log3Func(("[SD%RU8] -> cTicksToNext=%RU64\n", pStream->u8SD, cTicksToNext));
1558
1559 /* Reset processed data counter. */
1560 pStream->State.cbTransferProcessed = 0;
1561 pStream->State.tsTransferNext = tsNow + cTicksToNext;
1562
1563 Assert(pStream->State.cTransferPendingInterrupts);
1564 if (pStream->State.cTransferPendingInterrupts)
1565 pStream->State.cTransferPendingInterrupts--;
1566
1567 /* Re-arm the timer. */
1568 hdaTimerSet(pThis, tsNow + cTicksToNext, false /* fForce */);
1569 }
1570
1571 hdaStreamUnlock(pStream);
1572
1573 DEVHDA_UNLOCK_BOTH(pThis);
1574 return VINF_SUCCESS;
1575#else /* IN_RING3 */
1576 RT_NOREF(pThis, iReg, u32Value);
1577 return VINF_IOM_R3_MMIO_WRITE;
1578#endif /* !IN_RING3 */
1579}
1580
1581static int hdaRegWriteSDLVI(PHDASTATE pThis, uint32_t iReg, uint32_t u32Value)
1582{
1583#ifdef IN_RING3
1584 DEVHDA_LOCK(pThis);
1585
1586 if (HDA_REG_IND(pThis, iReg) == u32Value) /* Value already set? */
1587 {
1588 DEVHDA_UNLOCK(pThis);
1589 return VINF_SUCCESS;
1590 }
1591
1592 uint8_t uSD = HDA_SD_NUM_FROM_REG(pThis, LVI, iReg);
1593
1594 PHDASTREAM pStream = hdaGetStreamFromSD(pThis, uSD);
1595 if (!pStream)
1596 {
1597 AssertMsgFailed(("[SD%RU8] Warning: Changing SDLVI on non-attached stream (0x%x)\n", uSD, u32Value));
1598
1599 DEVHDA_UNLOCK(pThis);
1600 return hdaRegWriteU16(pThis, iReg, u32Value);
1601 }
1602
1603 /** @todo Validate LVI. */
1604 pStream->u16LVI = u32Value;
1605 LogFunc(("[SD%RU8] Updating LVI to %RU16\n", uSD, pStream->u16LVI));
1606
1607# ifdef HDA_USE_DMA_ACCESS_HANDLER
1608 if (hdaGetDirFromSD(uSD) == PDMAUDIODIR_OUT)
1609 {
1610 /* Try registering the DMA handlers.
1611 * As we can't be sure in which order LVI + BDL base are set, try registering in both routines. */
1612 if (hdaStreamRegisterDMAHandlers(pThis, pStream))
1613 LogFunc(("[SD%RU8] DMA logging enabled\n", pStream->u8SD));
1614 }
1615# endif
1616
1617 DEVHDA_UNLOCK(pThis);
1618
1619 int rc2 = hdaRegWriteU16(pThis, iReg, u32Value);
1620 AssertRC(rc2);
1621
1622 return VINF_SUCCESS; /* Always return success to the MMIO handler. */
1623#else /* !IN_RING3 */
1624 RT_NOREF_PV(pThis); RT_NOREF_PV(iReg); RT_NOREF_PV(u32Value);
1625 return VINF_IOM_R3_MMIO_WRITE;
1626#endif /* IN_RING3 */
1627}
1628
1629static int hdaRegWriteSDFIFOW(PHDASTATE pThis, uint32_t iReg, uint32_t u32Value)
1630{
1631#ifdef IN_RING3
1632 DEVHDA_LOCK(pThis);
1633
1634 uint8_t uSD = HDA_SD_NUM_FROM_REG(pThis, FIFOW, iReg);
1635
1636 if (hdaGetDirFromSD(uSD) != PDMAUDIODIR_IN) /* FIFOW for input streams only. */
1637 {
1638 LogRel(("HDA: Warning: Guest tried to write read-only FIFOW to output stream #%RU8, ignoring\n", uSD));
1639
1640 DEVHDA_UNLOCK(pThis);
1641 return VINF_SUCCESS;
1642 }
1643
1644 PHDASTREAM pStream = hdaGetStreamFromSD(pThis, HDA_SD_NUM_FROM_REG(pThis, FIFOW, iReg));
1645 if (!pStream)
1646 {
1647 AssertMsgFailed(("[SD%RU8] Warning: Changing FIFOW on non-attached stream (0x%x)\n", uSD, u32Value));
1648
1649 DEVHDA_UNLOCK(pThis);
1650 return hdaRegWriteU16(pThis, iReg, u32Value);
1651 }
1652
1653 uint32_t u32FIFOW = 0;
1654
1655 switch (u32Value)
1656 {
1657 case HDA_SDFIFOW_8B:
1658 case HDA_SDFIFOW_16B:
1659 case HDA_SDFIFOW_32B:
1660 u32FIFOW = u32Value;
1661 break;
1662 default:
1663 LogRel(("HDA: Warning: Guest tried write unsupported FIFOW (0x%x) to stream #%RU8, defaulting to 32 bytes\n",
1664 u32Value, uSD));
1665 AssertFailed();
1666 u32FIFOW = HDA_SDFIFOW_32B;
1667 break;
1668 }
1669
1670 if (u32FIFOW)
1671 {
1672 pStream->u16FIFOW = hdaSDFIFOWToBytes(u32FIFOW);
1673 LogFunc(("[SD%RU8] Updating FIFOW to %RU32 bytes\n", uSD, pStream->u16FIFOW));
1674
1675 DEVHDA_UNLOCK(pThis);
1676
1677 int rc2 = hdaRegWriteU16(pThis, iReg, u32FIFOW);
1678 AssertRC(rc2);
1679 }
1680
1681 DEVHDA_UNLOCK(pThis);
1682 return VINF_SUCCESS; /* Always return success to the MMIO handler. */
1683#else /* !IN_RING3 */
1684 RT_NOREF_PV(pThis); RT_NOREF_PV(iReg); RT_NOREF_PV(u32Value);
1685 return VINF_IOM_R3_MMIO_WRITE;
1686#endif /* IN_RING3 */
1687}
1688
1689/**
1690 * @note This method could be called for changing value on Output Streams only (ICH6 datasheet 18.2.39).
1691 */
1692static int hdaRegWriteSDFIFOS(PHDASTATE pThis, uint32_t iReg, uint32_t u32Value)
1693{
1694#ifdef IN_RING3
1695 DEVHDA_LOCK(pThis);
1696
1697 uint8_t uSD = HDA_SD_NUM_FROM_REG(pThis, FIFOS, iReg);
1698
1699 if (hdaGetDirFromSD(uSD) != PDMAUDIODIR_OUT) /* FIFOS for output streams only. */
1700 {
1701 LogRel(("HDA: Warning: Guest tried to write read-only FIFOS to input stream #%RU8, ignoring\n", uSD));
1702
1703 DEVHDA_UNLOCK(pThis);
1704 return VINF_SUCCESS;
1705 }
1706
1707 PHDASTREAM pStream = hdaGetStreamFromSD(pThis, uSD);
1708 if (!pStream)
1709 {
1710 AssertMsgFailed(("[SD%RU8] Warning: Changing FIFOS on non-attached stream (0x%x)\n", uSD, u32Value));
1711
1712 DEVHDA_UNLOCK(pThis);
1713 return hdaRegWriteU16(pThis, iReg, u32Value);
1714 }
1715
1716 uint32_t u32FIFOS = 0;
1717
1718 switch(u32Value)
1719 {
1720 case HDA_SDOFIFO_16B:
1721 case HDA_SDOFIFO_32B:
1722 case HDA_SDOFIFO_64B:
1723 case HDA_SDOFIFO_128B:
1724 case HDA_SDOFIFO_192B:
1725 case HDA_SDOFIFO_256B:
1726 u32FIFOS = u32Value;
1727 break;
1728
1729 default:
1730 LogRel(("HDA: Warning: Guest tried write unsupported FIFOS (0x%x) to stream #%RU8, defaulting to 192 bytes\n",
1731 u32Value, uSD));
1732 AssertFailed();
1733 u32FIFOS = HDA_SDOFIFO_192B;
1734 break;
1735 }
1736
1737 if (u32FIFOS)
1738 {
1739 pStream->u16FIFOS = u32FIFOS + 1;
1740 LogFunc(("[SD%RU8] Updating FIFOS to %RU32 bytes\n", uSD, pStream->u16FIFOS));
1741
1742 DEVHDA_UNLOCK(pThis);
1743
1744 int rc2 = hdaRegWriteU16(pThis, iReg, u32FIFOS);
1745 AssertRC(rc2);
1746 }
1747 else
1748 DEVHDA_UNLOCK(pThis);
1749
1750 return VINF_SUCCESS; /* Always return success to the MMIO handler. */
1751#else /* !IN_RING3 */
1752 RT_NOREF_PV(pThis); RT_NOREF_PV(iReg); RT_NOREF_PV(u32Value);
1753 return VINF_IOM_R3_MMIO_WRITE;
1754#endif /* IN_RING3 */
1755}
1756
1757#ifdef IN_RING3
1758/**
1759 * Adds an audio output stream to the device setup using the given configuration.
1760 *
1761 * @returns IPRT status code.
1762 * @param pThis Device state.
1763 * @param pCfg Stream configuration to use for adding a stream.
1764 */
1765static int hdaAddStreamOut(PHDASTATE pThis, PPDMAUDIOSTREAMCFG pCfg)
1766{
1767 AssertPtrReturn(pThis, VERR_INVALID_POINTER);
1768 AssertPtrReturn(pCfg, VERR_INVALID_POINTER);
1769
1770 AssertReturn(pCfg->enmDir == PDMAUDIODIR_OUT, VERR_INVALID_PARAMETER);
1771
1772 LogFlowFunc(("Stream=%s\n", pCfg->szName));
1773
1774 int rc = VINF_SUCCESS;
1775
1776 bool fUseFront = true; /* Always use front out by default. */
1777#ifdef VBOX_WITH_AUDIO_HDA_51_SURROUND
1778 bool fUseRear;
1779 bool fUseCenter;
1780 bool fUseLFE;
1781
1782 fUseRear = fUseCenter = fUseLFE = false;
1783
1784 /*
1785 * Use commonly used setups for speaker configurations.
1786 */
1787
1788 /** @todo Make the following configurable through mixer API and/or CFGM? */
1789 switch (pCfg->Props.cChannels)
1790 {
1791 case 3: /* 2.1: Front (Stereo) + LFE. */
1792 {
1793 fUseLFE = true;
1794 break;
1795 }
1796
1797 case 4: /* Quadrophonic: Front (Stereo) + Rear (Stereo). */
1798 {
1799 fUseRear = true;
1800 break;
1801 }
1802
1803 case 5: /* 4.1: Front (Stereo) + Rear (Stereo) + LFE. */
1804 {
1805 fUseRear = true;
1806 fUseLFE = true;
1807 break;
1808 }
1809
1810 case 6: /* 5.1: Front (Stereo) + Rear (Stereo) + Center/LFE. */
1811 {
1812 fUseRear = true;
1813 fUseCenter = true;
1814 fUseLFE = true;
1815 break;
1816 }
1817
1818 default: /* Unknown; fall back to 2 front channels (stereo). */
1819 {
1820 rc = VERR_NOT_SUPPORTED;
1821 break;
1822 }
1823 }
1824#else /* !VBOX_WITH_AUDIO_HDA_51_SURROUND */
1825 /* Only support mono or stereo channels. */
1826 if ( pCfg->Props.cChannels != 1 /* Mono */
1827 && pCfg->Props.cChannels != 2 /* Stereo */)
1828 {
1829 rc = VERR_NOT_SUPPORTED;
1830 }
1831#endif
1832
1833 if (rc == VERR_NOT_SUPPORTED)
1834 {
1835 LogRel2(("HDA: Warning: Unsupported channel count (%RU8), falling back to stereo channels (2)\n", pCfg->Props.cChannels));
1836
1837 /* Fall back to 2 channels (see below in fUseFront block). */
1838 rc = VINF_SUCCESS;
1839 }
1840
1841 do
1842 {
1843 if (RT_FAILURE(rc))
1844 break;
1845
1846 if (fUseFront)
1847 {
1848 RTStrPrintf(pCfg->szName, RT_ELEMENTS(pCfg->szName), "Front");
1849
1850 pCfg->DestSource.Dest = PDMAUDIOPLAYBACKDEST_FRONT;
1851 pCfg->enmLayout = PDMAUDIOSTREAMLAYOUT_NON_INTERLEAVED;
1852
1853 pCfg->Props.cChannels = 2;
1854 pCfg->Props.cShift = PDMAUDIOPCMPROPS_MAKE_SHIFT_PARMS(pCfg->Props.cBits, pCfg->Props.cChannels);
1855
1856 rc = hdaCodecRemoveStream(pThis->pCodec, PDMAUDIOMIXERCTL_FRONT);
1857 if (RT_SUCCESS(rc))
1858 rc = hdaCodecAddStream(pThis->pCodec, PDMAUDIOMIXERCTL_FRONT, pCfg);
1859 }
1860
1861#ifdef VBOX_WITH_AUDIO_HDA_51_SURROUND
1862 if ( RT_SUCCESS(rc)
1863 && (fUseCenter || fUseLFE))
1864 {
1865 RTStrPrintf(pCfg->szName, RT_ELEMENTS(pCfg->szName), "Center/LFE");
1866
1867 pCfg->DestSource.Dest = PDMAUDIOPLAYBACKDEST_CENTER_LFE;
1868 pCfg->enmLayout = PDMAUDIOSTREAMLAYOUT_NON_INTERLEAVED;
1869
1870 pCfg->Props.cChannels = (fUseCenter && fUseLFE) ? 2 : 1;
1871 pCfg->Props.cShift = PDMAUDIOPCMPROPS_MAKE_SHIFT_PARMS(pCfg->Props.cBits, pCfg->Props.cChannels);
1872
1873 rc = hdaCodecRemoveStream(pThis->pCodec, PDMAUDIOMIXERCTL_CENTER_LFE);
1874 if (RT_SUCCESS(rc))
1875 rc = hdaCodecAddStream(pThis->pCodec, PDMAUDIOMIXERCTL_CENTER_LFE, pCfg);
1876 }
1877
1878 if ( RT_SUCCESS(rc)
1879 && fUseRear)
1880 {
1881 RTStrPrintf(pCfg->szName, RT_ELEMENTS(pCfg->szName), "Rear");
1882
1883 pCfg->DestSource.Dest = PDMAUDIOPLAYBACKDEST_REAR;
1884 pCfg->enmLayout = PDMAUDIOSTREAMLAYOUT_NON_INTERLEAVED;
1885
1886 pCfg->Props.cChannels = 2;
1887 pCfg->Props.cShift = PDMAUDIOPCMPROPS_MAKE_SHIFT_PARMS(pCfg->Props.cBits, pCfg->Props.cChannels);
1888
1889 rc = hdaCodecRemoveStream(pThis->pCodec, PDMAUDIOMIXERCTL_REAR);
1890 if (RT_SUCCESS(rc))
1891 rc = hdaCodecAddStream(pThis->pCodec, PDMAUDIOMIXERCTL_REAR, pCfg);
1892 }
1893#endif /* VBOX_WITH_AUDIO_HDA_51_SURROUND */
1894
1895 } while (0);
1896
1897 LogFlowFuncLeaveRC(rc);
1898 return rc;
1899}
1900
1901/**
1902 * Adds an audio input stream to the device setup using the given configuration.
1903 *
1904 * @returns IPRT status code.
1905 * @param pThis Device state.
1906 * @param pCfg Stream configuration to use for adding a stream.
1907 */
1908static int hdaAddStreamIn(PHDASTATE pThis, PPDMAUDIOSTREAMCFG pCfg)
1909{
1910 AssertPtrReturn(pThis, VERR_INVALID_POINTER);
1911 AssertPtrReturn(pCfg, VERR_INVALID_POINTER);
1912
1913 AssertReturn(pCfg->enmDir == PDMAUDIODIR_IN, VERR_INVALID_PARAMETER);
1914
1915 LogFlowFunc(("Stream=%s, Source=%ld\n", pCfg->szName, pCfg->DestSource.Source));
1916
1917 int rc;
1918
1919 switch (pCfg->DestSource.Source)
1920 {
1921 case PDMAUDIORECSOURCE_LINE:
1922 {
1923 rc = hdaCodecRemoveStream(pThis->pCodec, PDMAUDIOMIXERCTL_LINE_IN);
1924 if (RT_SUCCESS(rc))
1925 rc = hdaCodecAddStream(pThis->pCodec, PDMAUDIOMIXERCTL_LINE_IN, pCfg);
1926 break;
1927 }
1928#ifdef VBOX_WITH_AUDIO_HDA_MIC_IN
1929 case PDMAUDIORECSOURCE_MIC:
1930 {
1931 rc = hdaCodecRemoveStream(pThis->pCodec, PDMAUDIOMIXERCTL_MIC_IN);
1932 if (RT_SUCCESS(rc))
1933 rc = hdaCodecAddStream(pThis->pCodec, PDMAUDIOMIXERCTL_MIC_IN, pCfg);
1934 break;
1935 }
1936#endif
1937 default:
1938 rc = VERR_NOT_SUPPORTED;
1939 break;
1940 }
1941
1942 LogFlowFuncLeaveRC(rc);
1943 return rc;
1944}
1945
1946/**
1947 * Adds an audio stream to the device setup using the given configuration.
1948 *
1949 * @returns IPRT status code.
1950 * @param pThis Device state.
1951 * @param pCfg Stream configuration to use for adding a stream.
1952 */
1953static int hdaAddStream(PHDASTATE pThis, PPDMAUDIOSTREAMCFG pCfg)
1954{
1955 AssertPtrReturn(pThis, VERR_INVALID_POINTER);
1956 AssertPtrReturn(pCfg, VERR_INVALID_POINTER);
1957
1958 int rc = VINF_SUCCESS;
1959
1960 PHDADRIVER pDrv;
1961 RTListForEach(&pThis->lstDrv, pDrv, HDADRIVER, Node)
1962 {
1963 int rc2;
1964
1965 switch (pCfg->enmDir)
1966 {
1967 case PDMAUDIODIR_OUT:
1968 rc2 = hdaAddStreamOut(pThis, pCfg);
1969 break;
1970
1971 case PDMAUDIODIR_IN:
1972 rc2 = hdaAddStreamIn(pThis, pCfg);
1973 break;
1974
1975 default:
1976 rc2 = VERR_NOT_SUPPORTED;
1977 AssertFailed();
1978 break;
1979 }
1980
1981 if ( RT_FAILURE(rc2)
1982 && (pDrv->fFlags & PDMAUDIODRVFLAGS_PRIMARY)) /* We only care about primary drivers here, the rest may fail. */
1983 {
1984 if (RT_SUCCESS(rc))
1985 rc = rc2;
1986 /* Keep going. */
1987 }
1988 }
1989
1990 return rc;
1991}
1992#endif /* IN_RING3 */
1993
1994static int hdaRegWriteSDFMT(PHDASTATE pThis, uint32_t iReg, uint32_t u32Value)
1995{
1996#ifdef IN_RING3
1997 DEVHDA_LOCK(pThis);
1998
1999 PHDASTREAM pStream = hdaGetStreamFromSD(pThis, HDA_SD_NUM_FROM_REG(pThis, FMT, iReg));
2000 if (!pStream)
2001 {
2002 LogFunc(("[SD%RU8] Warning: Changing SDFMT on non-attached stream (0x%x)\n",
2003 HDA_SD_NUM_FROM_REG(pThis, FMT, iReg), u32Value));
2004 return hdaRegWriteU16(pThis, iReg, u32Value);
2005 }
2006
2007 /* Write the wanted stream format into the register in any case.
2008 *
2009 * This is important for e.g. MacOS guests, as those try to initialize streams which are not reported
2010 * by the device emulation (wants 4 channels, only have 2 channels at the moment).
2011 *
2012 * When ignoring those (invalid) formats, this leads to MacOS thinking that the device is malfunctioning
2013 * and therefore disabling the device completely. */
2014 int rc = hdaRegWriteU16(pThis, iReg, u32Value);
2015 AssertRC(rc);
2016
2017 rc = hdaStreamInit(pStream, pStream->u8SD);
2018 if (RT_SUCCESS(rc))
2019 {
2020 /* Add the stream to the device setup. */
2021 rc = hdaAddStream(pThis, &pStream->State.Cfg);
2022# ifdef VBOX_WITH_AUDIO_HDA_ASYNC_IO
2023 if (RT_SUCCESS(rc))
2024 rc = hdaStreamAsyncIOCreate(pStream);
2025# endif
2026 }
2027
2028 DEVHDA_UNLOCK(pThis);
2029 return VINF_SUCCESS; /* Never return failure. */
2030#else /* !IN_RING3 */
2031 RT_NOREF_PV(pThis); RT_NOREF_PV(iReg); RT_NOREF_PV(u32Value);
2032 return VINF_IOM_R3_MMIO_WRITE;
2033#endif
2034}
2035
2036/* Note: Will be called for both, BDPL and BDPU, registers. */
2037DECLINLINE(int) hdaRegWriteSDBDPX(PHDASTATE pThis, uint32_t iReg, uint32_t u32Value, uint8_t uSD)
2038{
2039#ifdef IN_RING3
2040 int rc2 = hdaRegWriteU32(pThis, iReg, u32Value);
2041 AssertRC(rc2);
2042
2043 DEVHDA_LOCK(pThis);
2044
2045 PHDASTREAM pStream = hdaGetStreamFromSD(pThis, uSD);
2046 if (!pStream)
2047 {
2048 DEVHDA_UNLOCK(pThis);
2049 return VINF_SUCCESS;
2050 }
2051
2052 /* Update BDL base. */
2053 pStream->u64BDLBase = RT_MAKE_U64(HDA_STREAM_REG(pThis, BDPL, uSD),
2054 HDA_STREAM_REG(pThis, BDPU, uSD));
2055
2056# ifdef HDA_USE_DMA_ACCESS_HANDLER
2057 if (hdaGetDirFromSD(uSD) == PDMAUDIODIR_OUT)
2058 {
2059 /* Try registering the DMA handlers.
2060 * As we can't be sure in which order LVI + BDL base are set, try registering in both routines. */
2061 if (hdaStreamRegisterDMAHandlers(pThis, pStream))
2062 LogFunc(("[SD%RU8] DMA logging enabled\n", pStream->u8SD));
2063 }
2064# endif
2065
2066 LogFlowFunc(("[SD%RU8] BDLBase=0x%x\n", pStream->u8SD, pStream->u64BDLBase));
2067
2068 DEVHDA_UNLOCK(pThis);
2069
2070 return VINF_SUCCESS; /* Always return success to the MMIO handler. */
2071#else /* !IN_RING3 */
2072 RT_NOREF_PV(pThis); RT_NOREF_PV(iReg); RT_NOREF_PV(u32Value); RT_NOREF_PV(uSD);
2073 return VINF_IOM_R3_MMIO_WRITE;
2074#endif /* IN_RING3 */
2075}
2076
2077static int hdaRegWriteSDBDPL(PHDASTATE pThis, uint32_t iReg, uint32_t u32Value)
2078{
2079 return hdaRegWriteSDBDPX(pThis, iReg, u32Value, HDA_SD_NUM_FROM_REG(pThis, BDPL, iReg));
2080}
2081
2082static int hdaRegWriteSDBDPU(PHDASTATE pThis, uint32_t iReg, uint32_t u32Value)
2083{
2084 return hdaRegWriteSDBDPX(pThis, iReg, u32Value, HDA_SD_NUM_FROM_REG(pThis, BDPU, iReg));
2085}
2086
2087static int hdaRegReadIRS(PHDASTATE pThis, uint32_t iReg, uint32_t *pu32Value)
2088{
2089 DEVHDA_LOCK_RETURN(pThis, VINF_IOM_R3_MMIO_READ);
2090
2091 /* regarding 3.4.3 we should mark IRS as busy in case CORB is active */
2092 if ( HDA_REG(pThis, CORBWP) != HDA_REG(pThis, CORBRP)
2093 || (HDA_REG(pThis, CORBCTL) & HDA_CORBCTL_DMA))
2094 {
2095 HDA_REG(pThis, IRS) = HDA_IRS_ICB; /* busy */
2096 }
2097
2098 DEVHDA_UNLOCK(pThis);
2099
2100 return hdaRegReadU32(pThis, iReg, pu32Value);
2101}
2102
2103static int hdaRegWriteIRS(PHDASTATE pThis, uint32_t iReg, uint32_t u32Value)
2104{
2105 RT_NOREF_PV(iReg);
2106
2107 DEVHDA_LOCK_RETURN(pThis, VINF_IOM_R3_MMIO_WRITE);
2108
2109 /*
2110 * If the guest set the ICB bit of IRS register, HDA should process the verb in IC register,
2111 * write the response to IR register, and set the IRV (valid in case of success) bit of IRS register.
2112 */
2113 if ( (u32Value & HDA_IRS_ICB)
2114 && !(HDA_REG(pThis, IRS) & HDA_IRS_ICB))
2115 {
2116#ifdef IN_RING3
2117 uint32_t uCmd = HDA_REG(pThis, IC);
2118
2119 if (HDA_REG(pThis, CORBWP) != HDA_REG(pThis, CORBRP))
2120 {
2121 DEVHDA_UNLOCK(pThis);
2122
2123 /*
2124 * 3.4.3: Defines behavior of immediate Command status register.
2125 */
2126 LogRel(("HDA: Guest attempted process immediate verb (%x) with active CORB\n", uCmd));
2127 return VINF_SUCCESS;
2128 }
2129
2130 HDA_REG(pThis, IRS) = HDA_IRS_ICB; /* busy */
2131
2132 uint64_t uResp;
2133 int rc2 = pThis->pCodec->pfnLookup(pThis->pCodec,
2134 HDA_CODEC_CMD(uCmd, 0 /* LUN */), &uResp);
2135 if (RT_FAILURE(rc2))
2136 LogFunc(("Codec lookup failed with rc2=%Rrc\n", rc2));
2137
2138 HDA_REG(pThis, IR) = (uint32_t)uResp; /** @todo r=andy Do we need a 64-bit response? */
2139 HDA_REG(pThis, IRS) = HDA_IRS_IRV; /* result is ready */
2140 /** @todo r=michaln We just set the IRS value, why are we clearing unset bits? */
2141 HDA_REG(pThis, IRS) &= ~HDA_IRS_ICB; /* busy is clear */
2142
2143 DEVHDA_UNLOCK(pThis);
2144 return VINF_SUCCESS;
2145#else /* !IN_RING3 */
2146 DEVHDA_UNLOCK(pThis);
2147 return VINF_IOM_R3_MMIO_WRITE;
2148#endif /* !IN_RING3 */
2149 }
2150
2151 /*
2152 * Once the guest read the response, it should clear the IRV bit of the IRS register.
2153 */
2154 HDA_REG(pThis, IRS) &= ~(u32Value & HDA_IRS_IRV);
2155
2156 DEVHDA_UNLOCK(pThis);
2157 return VINF_SUCCESS;
2158}
2159
2160static int hdaRegWriteRIRBWP(PHDASTATE pThis, uint32_t iReg, uint32_t u32Value)
2161{
2162 RT_NOREF(iReg);
2163
2164 DEVHDA_LOCK_RETURN(pThis, VINF_IOM_R3_MMIO_WRITE);
2165
2166 if (HDA_REG(pThis, CORBCTL) & HDA_CORBCTL_DMA) /* Ignore request if CORB DMA engine is (still) running. */
2167 {
2168 LogFunc(("CORB DMA (still) running, skipping\n"));
2169
2170 DEVHDA_UNLOCK(pThis);
2171 return VINF_SUCCESS;
2172 }
2173
2174 if (u32Value & HDA_RIRBWP_RST)
2175 {
2176 /* Do a RIRB reset. */
2177 if (pThis->cbRirbBuf)
2178 {
2179 Assert(pThis->pu64RirbBuf);
2180 RT_BZERO((void *)pThis->pu64RirbBuf, pThis->cbRirbBuf);
2181 }
2182
2183 LogRel2(("HDA: RIRB reset\n"));
2184
2185 HDA_REG(pThis, RIRBWP) = 0;
2186 }
2187
2188 DEVHDA_UNLOCK(pThis);
2189
2190 /* The remaining bits are O, see 6.2.22. */
2191 return VINF_SUCCESS;
2192}
2193
2194static int hdaRegWriteRINTCNT(PHDASTATE pThis, uint32_t iReg, uint32_t u32Value)
2195{
2196 DEVHDA_LOCK_RETURN(pThis, VINF_IOM_R3_MMIO_WRITE);
2197
2198 if (HDA_REG(pThis, CORBCTL) & HDA_CORBCTL_DMA) /* Ignore request if CORB DMA engine is (still) running. */
2199 {
2200 LogFunc(("CORB DMA is (still) running, skipping\n"));
2201
2202 DEVHDA_UNLOCK(pThis);
2203 return VINF_SUCCESS;
2204 }
2205
2206 RT_NOREF(iReg);
2207
2208 int rc = hdaRegWriteU16(pThis, iReg, u32Value);
2209 AssertRC(rc);
2210
2211 LogFunc(("Response interrupt count is now %RU8\n", HDA_REG(pThis, RINTCNT) & 0xFF));
2212
2213 DEVHDA_UNLOCK(pThis);
2214 return rc;
2215}
2216
2217static int hdaRegWriteBase(PHDASTATE pThis, uint32_t iReg, uint32_t u32Value)
2218{
2219 uint32_t iRegMem = g_aHdaRegMap[iReg].mem_idx;
2220 int rc = hdaRegWriteU32(pThis, iReg, u32Value);
2221 if (RT_FAILURE(rc))
2222 AssertRCReturn(rc, rc);
2223
2224 DEVHDA_LOCK_RETURN(pThis, VINF_IOM_R3_MMIO_WRITE);
2225
2226 switch(iReg)
2227 {
2228 case HDA_REG_CORBLBASE:
2229 pThis->u64CORBBase &= UINT64_C(0xFFFFFFFF00000000);
2230 pThis->u64CORBBase |= pThis->au32Regs[iRegMem];
2231 break;
2232 case HDA_REG_CORBUBASE:
2233 pThis->u64CORBBase &= UINT64_C(0x00000000FFFFFFFF);
2234 pThis->u64CORBBase |= ((uint64_t)pThis->au32Regs[iRegMem] << 32);
2235 break;
2236 case HDA_REG_RIRBLBASE:
2237 pThis->u64RIRBBase &= UINT64_C(0xFFFFFFFF00000000);
2238 pThis->u64RIRBBase |= pThis->au32Regs[iRegMem];
2239 break;
2240 case HDA_REG_RIRBUBASE:
2241 pThis->u64RIRBBase &= UINT64_C(0x00000000FFFFFFFF);
2242 pThis->u64RIRBBase |= ((uint64_t)pThis->au32Regs[iRegMem] << 32);
2243 break;
2244 case HDA_REG_DPLBASE:
2245 {
2246 pThis->u64DPBase = pThis->au32Regs[iRegMem] & DPBASE_ADDR_MASK;
2247 Assert(pThis->u64DPBase % 128 == 0); /* Must be 128-byte aligned. */
2248
2249 /* Also make sure to handle the DMA position enable bit. */
2250 pThis->fDMAPosition = pThis->au32Regs[iRegMem] & RT_BIT_32(0);
2251 LogRel(("HDA: %s DMA position buffer\n", pThis->fDMAPosition ? "Enabled" : "Disabled"));
2252 break;
2253 }
2254 case HDA_REG_DPUBASE:
2255 pThis->u64DPBase = RT_MAKE_U64(RT_LO_U32(pThis->u64DPBase) & DPBASE_ADDR_MASK, pThis->au32Regs[iRegMem]);
2256 break;
2257 default:
2258 AssertMsgFailed(("Invalid index\n"));
2259 break;
2260 }
2261
2262 LogFunc(("CORB base:%llx RIRB base: %llx DP base: %llx\n",
2263 pThis->u64CORBBase, pThis->u64RIRBBase, pThis->u64DPBase));
2264
2265 DEVHDA_UNLOCK(pThis);
2266 return rc;
2267}
2268
2269static int hdaRegWriteRIRBSTS(PHDASTATE pThis, uint32_t iReg, uint32_t u32Value)
2270{
2271 RT_NOREF_PV(iReg);
2272
2273 DEVHDA_LOCK_RETURN(pThis, VINF_IOM_R3_MMIO_WRITE);
2274
2275 uint8_t v = HDA_REG(pThis, RIRBSTS);
2276 HDA_REG(pThis, RIRBSTS) &= ~(v & u32Value);
2277
2278 DEVHDA_UNLOCK(pThis);
2279
2280#ifndef DEBUG
2281 return hdaProcessInterrupt(pThis);
2282#else
2283 return hdaProcessInterrupt(pThis, __FUNCTION__);
2284#endif
2285}
2286
2287#ifdef IN_RING3
2288/**
2289 * Retrieves a corresponding sink for a given mixer control.
2290 * Returns NULL if no sink is found.
2291 *
2292 * @return PHDAMIXERSINK
2293 * @param pThis HDA state.
2294 * @param enmMixerCtl Mixer control to get the corresponding sink for.
2295 */
2296static PHDAMIXERSINK hdaMixerControlToSink(PHDASTATE pThis, PDMAUDIOMIXERCTL enmMixerCtl)
2297{
2298 PHDAMIXERSINK pSink;
2299
2300 switch (enmMixerCtl)
2301 {
2302 case PDMAUDIOMIXERCTL_VOLUME_MASTER:
2303 /* Fall through is intentional. */
2304 case PDMAUDIOMIXERCTL_FRONT:
2305 pSink = &pThis->SinkFront;
2306 break;
2307#ifdef VBOX_WITH_AUDIO_HDA_51_SURROUND
2308 case PDMAUDIOMIXERCTL_CENTER_LFE:
2309 pSink = &pThis->SinkCenterLFE;
2310 break;
2311 case PDMAUDIOMIXERCTL_REAR:
2312 pSink = &pThis->SinkRear;
2313 break;
2314#endif
2315 case PDMAUDIOMIXERCTL_LINE_IN:
2316 pSink = &pThis->SinkLineIn;
2317 break;
2318#ifdef VBOX_WITH_AUDIO_HDA_MIC_IN
2319 case PDMAUDIOMIXERCTL_MIC_IN:
2320 pSink = &pThis->SinkMicIn;
2321 break;
2322#endif
2323 default:
2324 pSink = NULL;
2325 AssertMsgFailed(("Unhandled mixer control\n"));
2326 break;
2327 }
2328
2329 return pSink;
2330}
2331
2332/**
2333 * Adds a driver stream to a specific mixer sink.
2334 *
2335 * @returns IPRT status code.
2336 * @param pThis HDA state.
2337 * @param pMixSink Audio mixer sink to add audio streams to.
2338 * @param pCfg Audio stream configuration to use for the audio streams to add.
2339 * @param pDrv Driver stream to add.
2340 */
2341static int hdaMixerAddDrvStream(PHDASTATE pThis, PAUDMIXSINK pMixSink, PPDMAUDIOSTREAMCFG pCfg, PHDADRIVER pDrv)
2342{
2343 AssertPtrReturn(pThis, VERR_INVALID_POINTER);
2344 AssertPtrReturn(pMixSink, VERR_INVALID_POINTER);
2345 AssertPtrReturn(pCfg, VERR_INVALID_POINTER);
2346
2347 LogFunc(("Sink=%s, Stream=%s\n", pMixSink->pszName, pCfg->szName));
2348
2349 PPDMAUDIOSTREAMCFG pStreamCfg = DrvAudioHlpStreamCfgDup(pCfg);
2350 if (!pStreamCfg)
2351 return VERR_NO_MEMORY;
2352
2353 if (!RTStrPrintf(pStreamCfg->szName, sizeof(pStreamCfg->szName), "%s", pCfg->szName))
2354 {
2355 RTMemFree(pStreamCfg);
2356 return VERR_BUFFER_OVERFLOW;
2357 }
2358
2359 LogFunc(("[LUN#%RU8] %s\n", pDrv->uLUN, pStreamCfg->szName));
2360
2361 int rc = VINF_SUCCESS;
2362
2363 PHDADRIVERSTREAM pDrvStream = NULL;
2364
2365 if (pStreamCfg->enmDir == PDMAUDIODIR_IN)
2366 {
2367 LogFunc(("enmRecSource=%d\n", pStreamCfg->DestSource.Source));
2368
2369 switch (pStreamCfg->DestSource.Source)
2370 {
2371 case PDMAUDIORECSOURCE_LINE:
2372 pDrvStream = &pDrv->LineIn;
2373 break;
2374#ifdef VBOX_WITH_AUDIO_HDA_MIC_IN
2375 case PDMAUDIORECSOURCE_MIC:
2376 pDrvStream = &pDrv->MicIn;
2377 break;
2378#endif
2379 default:
2380 rc = VERR_NOT_SUPPORTED;
2381 break;
2382 }
2383 }
2384 else if (pStreamCfg->enmDir == PDMAUDIODIR_OUT)
2385 {
2386 LogFunc(("enmPlaybackDest=%d\n", pStreamCfg->DestSource.Dest));
2387
2388 switch (pStreamCfg->DestSource.Dest)
2389 {
2390 case PDMAUDIOPLAYBACKDEST_FRONT:
2391 pDrvStream = &pDrv->Front;
2392 break;
2393#ifdef VBOX_WITH_AUDIO_HDA_51_SURROUND
2394 case PDMAUDIOPLAYBACKDEST_CENTER_LFE:
2395 pDrvStream = &pDrv->CenterLFE;
2396 break;
2397 case PDMAUDIOPLAYBACKDEST_REAR:
2398 pDrvStream = &pDrv->Rear;
2399 break;
2400#endif
2401 default:
2402 rc = VERR_NOT_SUPPORTED;
2403 break;
2404 }
2405 }
2406 else
2407 rc = VERR_NOT_SUPPORTED;
2408
2409 if (RT_SUCCESS(rc))
2410 {
2411 AssertPtr(pDrvStream);
2412 AssertMsg(pDrvStream->pMixStrm == NULL, ("[LUN#%RU8] Driver stream already present when it must not\n", pDrv->uLUN));
2413
2414 PAUDMIXSTREAM pMixStrm;
2415 rc = AudioMixerSinkCreateStream(pMixSink, pDrv->pConnector, pStreamCfg, 0 /* fFlags */, &pMixStrm);
2416 if (RT_SUCCESS(rc))
2417 {
2418 rc = AudioMixerSinkAddStream(pMixSink, pMixStrm);
2419 LogFlowFunc(("LUN#%RU8: Added \"%s\" to sink, rc=%Rrc\n", pDrv->uLUN, pStreamCfg->szName, rc));
2420 }
2421
2422 if (RT_SUCCESS(rc))
2423 pDrvStream->pMixStrm = pMixStrm;
2424 }
2425
2426 if (pStreamCfg)
2427 {
2428 RTMemFree(pStreamCfg);
2429 pStreamCfg = NULL;
2430 }
2431
2432 LogFlowFuncLeaveRC(rc);
2433 return rc;
2434}
2435
2436/**
2437 * Adds all current driver streams to a specific mixer sink.
2438 *
2439 * @returns IPRT status code.
2440 * @param pThis HDA state.
2441 * @param pMixSink Audio mixer sink to add stream to.
2442 * @param pCfg Audio stream configuration to use for the audio streams to add.
2443 */
2444static int hdaMixerAddDrvStreams(PHDASTATE pThis, PAUDMIXSINK pMixSink, PPDMAUDIOSTREAMCFG pCfg)
2445{
2446 AssertPtrReturn(pThis, VERR_INVALID_POINTER);
2447 AssertPtrReturn(pMixSink, VERR_INVALID_POINTER);
2448 AssertPtrReturn(pCfg, VERR_INVALID_POINTER);
2449
2450 LogFunc(("Sink=%s, Stream=%s\n", pMixSink->pszName, pCfg->szName));
2451
2452 if (!DrvAudioHlpStreamCfgIsValid(pCfg))
2453 return VERR_INVALID_PARAMETER;
2454
2455 int rc = AudioMixerSinkSetFormat(pMixSink, &pCfg->Props);
2456 if (RT_FAILURE(rc))
2457 return rc;
2458
2459 PHDADRIVER pDrv;
2460 RTListForEach(&pThis->lstDrv, pDrv, HDADRIVER, Node)
2461 {
2462 int rc2 = hdaMixerAddDrvStream(pThis, pMixSink, pCfg, pDrv);
2463 if (RT_SUCCESS(rc))
2464 rc = rc2;
2465 }
2466
2467 LogFlowFuncLeaveRC(rc);
2468 return rc;
2469}
2470
2471/**
2472 * Adds a new audio stream to a specific mixer control.
2473 * Depending on the mixer control the stream then gets assigned to one of the internal
2474 * mixer sinks, which in turn then handle the mixing of all connected streams to that sink.
2475 *
2476 * @return IPRT status code.
2477 * @param pThis HDA state.
2478 * @param enmMixerCtl Mixer control to assign new stream to.
2479 * @param pCfg Stream configuration for the new stream.
2480 */
2481static DECLCALLBACK(int) hdaMixerAddStream(PHDASTATE pThis, PDMAUDIOMIXERCTL enmMixerCtl, PPDMAUDIOSTREAMCFG pCfg)
2482{
2483 AssertPtrReturn(pThis, VERR_INVALID_POINTER);
2484 AssertPtrReturn(pCfg, VERR_INVALID_POINTER);
2485
2486 int rc;
2487
2488 PHDAMIXERSINK pSink = hdaMixerControlToSink(pThis, enmMixerCtl);
2489 if (pSink)
2490 {
2491 rc = hdaMixerAddDrvStreams(pThis, pSink->pMixSink, pCfg);
2492
2493 AssertPtr(pSink->pMixSink);
2494 LogFlowFunc(("Sink=%s, Mixer control=%s\n", pSink->pMixSink->pszName, DrvAudioHlpAudMixerCtlToStr(enmMixerCtl)));
2495 }
2496 else
2497 rc = VERR_NOT_FOUND;
2498
2499 LogFlowFuncLeaveRC(rc);
2500 return rc;
2501}
2502
2503/**
2504 * Removes a specified mixer control from the HDA's mixer.
2505 *
2506 * @return IPRT status code.
2507 * @param pThis HDA state.
2508 * @param enmMixerCtl Mixer control to remove.
2509 *
2510 * @remarks Can be called as a callback by the HDA codec.
2511 */
2512static DECLCALLBACK(int) hdaMixerRemoveStream(PHDASTATE pThis, PDMAUDIOMIXERCTL enmMixerCtl)
2513{
2514 AssertPtrReturn(pThis, VERR_INVALID_POINTER);
2515
2516 int rc;
2517
2518 PHDAMIXERSINK pSink = hdaMixerControlToSink(pThis, enmMixerCtl);
2519 if (pSink)
2520 {
2521 PHDADRIVER pDrv;
2522 RTListForEach(&pThis->lstDrv, pDrv, HDADRIVER, Node)
2523 {
2524 PAUDMIXSTREAM pMixStream = NULL;
2525 switch (enmMixerCtl)
2526 {
2527 /*
2528 * Input.
2529 */
2530 case PDMAUDIOMIXERCTL_LINE_IN:
2531 pMixStream = pDrv->LineIn.pMixStrm;
2532 pDrv->LineIn.pMixStrm = NULL;
2533 break;
2534#ifdef VBOX_WITH_AUDIO_HDA_MIC_IN
2535 case PDMAUDIOMIXERCTL_MIC_IN:
2536 pMixStream = pDrv->MicIn.pMixStrm;
2537 pDrv->MicIn.pMixStrm = NULL;
2538 break;
2539#endif
2540 /*
2541 * Output.
2542 */
2543 case PDMAUDIOMIXERCTL_FRONT:
2544 pMixStream = pDrv->Front.pMixStrm;
2545 pDrv->Front.pMixStrm = NULL;
2546 break;
2547#ifdef VBOX_WITH_AUDIO_HDA_51_SURROUND
2548 case PDMAUDIOMIXERCTL_CENTER_LFE:
2549 pMixStream = pDrv->CenterLFE.pMixStrm;
2550 pDrv->CenterLFE.pMixStrm = NULL;
2551 break;
2552 case PDMAUDIOMIXERCTL_REAR:
2553 pMixStream = pDrv->Rear.pMixStrm;
2554 pDrv->Rear.pMixStrm = NULL;
2555 break;
2556#endif
2557 default:
2558 AssertMsgFailed(("Mixer control %d not implemented\n", enmMixerCtl));
2559 break;
2560 }
2561
2562 if (pMixStream)
2563 {
2564 AudioMixerSinkRemoveStream(pSink->pMixSink, pMixStream);
2565 AudioMixerStreamDestroy(pMixStream);
2566
2567 pMixStream = NULL;
2568 }
2569 }
2570
2571 AudioMixerSinkRemoveAllStreams(pSink->pMixSink);
2572 rc = VINF_SUCCESS;
2573 }
2574 else
2575 rc = VERR_NOT_FOUND;
2576
2577 LogFunc(("Mixer control=%s, rc=%Rrc\n", DrvAudioHlpAudMixerCtlToStr(enmMixerCtl), rc));
2578 return rc;
2579}
2580
2581/**
2582 * Controls an input / output converter widget, that is, which converter is connected
2583 * to which stream (and channel).
2584 *
2585 * @returns IPRT status code.
2586 * @param pThis HDA State.
2587 * @param enmMixerCtl Mixer control to set SD stream number and channel for.
2588 * @param uSD SD stream number (number + 1) to set. Set to 0 for unassign.
2589 * @param uChannel Channel to set. Only valid if a valid SD stream number is specified.
2590 *
2591 * @remarks Can be called as a callback by the HDA codec.
2592 */
2593static DECLCALLBACK(int) hdaMixerControl(PHDASTATE pThis, PDMAUDIOMIXERCTL enmMixerCtl, uint8_t uSD, uint8_t uChannel)
2594{
2595 LogFunc(("enmMixerCtl=%s, uSD=%RU8, uChannel=%RU8\n", DrvAudioHlpAudMixerCtlToStr(enmMixerCtl), uSD, uChannel));
2596
2597 if (uSD == 0) /* Stream number 0 is reserved. */
2598 {
2599 Log2Func(("Invalid SDn (%RU8) number for mixer control '%s', ignoring\n", uSD, DrvAudioHlpAudMixerCtlToStr(enmMixerCtl)));
2600 return VINF_SUCCESS;
2601 }
2602 /* uChannel is optional. */
2603
2604 /* SDn0 starts as 1. */
2605 Assert(uSD);
2606 uSD--;
2607
2608#ifndef VBOX_WITH_AUDIO_HDA_MIC_IN
2609 /* Only SDI0 (Line-In) is supported. */
2610 if ( hdaGetDirFromSD(uSD) == PDMAUDIODIR_IN
2611 && uSD >= 1)
2612 {
2613 LogRel2(("HDA: Dedicated Mic-In support not imlpemented / built-in (stream #%RU8), using Line-In (stream #0) instead\n", uSD));
2614 uSD = 0;
2615 }
2616#endif
2617
2618 int rc = VINF_SUCCESS;
2619
2620 PHDAMIXERSINK pSink = hdaMixerControlToSink(pThis, enmMixerCtl);
2621 if (pSink)
2622 {
2623 AssertPtr(pSink->pMixSink);
2624
2625 /* If this an output stream, determine the correct SD#. */
2626 if ( (uSD < HDA_MAX_SDI)
2627 && AudioMixerSinkGetDir(pSink->pMixSink) == AUDMIXSINKDIR_OUTPUT)
2628 {
2629 uSD += HDA_MAX_SDI;
2630 }
2631
2632 /* Detach the existing stream from the sink. */
2633 if ( pSink->pStream
2634 && ( pSink->pStream->u8SD != uSD
2635 || pSink->pStream->u8Channel != uChannel)
2636 )
2637 {
2638 LogFunc(("Sink '%s' was assigned to stream #%RU8 (channel %RU8) before\n",
2639 pSink->pMixSink->pszName, pSink->pStream->u8SD, pSink->pStream->u8Channel));
2640
2641 hdaStreamLock(pSink->pStream);
2642
2643 /* Only disable the stream if the stream descriptor # has changed. */
2644 if (pSink->pStream->u8SD != uSD)
2645 hdaStreamEnable(pSink->pStream, false);
2646
2647 pSink->pStream->pMixSink = NULL;
2648
2649 hdaStreamUnlock(pSink->pStream);
2650
2651 pSink->pStream = NULL;
2652 }
2653
2654 Assert(uSD < HDA_MAX_STREAMS);
2655
2656 /* Attach the new stream to the sink.
2657 * Enabling the stream will be done by the gust via a separate SDnCTL call then. */
2658 if (pSink->pStream == NULL)
2659 {
2660 LogRel2(("HDA: Setting sink '%s' to stream #%RU8 (channel %RU8), mixer control=%s\n",
2661 pSink->pMixSink->pszName, uSD, uChannel, DrvAudioHlpAudMixerCtlToStr(enmMixerCtl)));
2662
2663 PHDASTREAM pStream = hdaGetStreamFromSD(pThis, uSD);
2664 if (pStream)
2665 {
2666 hdaStreamLock(pStream);
2667
2668 pSink->pStream = pStream;
2669
2670 pStream->u8Channel = uChannel;
2671 pStream->pMixSink = pSink;
2672
2673 hdaStreamUnlock(pStream);
2674
2675 rc = VINF_SUCCESS;
2676 }
2677 else
2678 rc = VERR_NOT_IMPLEMENTED;
2679 }
2680 }
2681 else
2682 rc = VERR_NOT_FOUND;
2683
2684 if (RT_FAILURE(rc))
2685 LogRel(("HDA: Converter control for stream #%RU8 (channel %RU8) / mixer control '%s' failed with %Rrc, skipping\n",
2686 uSD, uChannel, DrvAudioHlpAudMixerCtlToStr(enmMixerCtl), rc));
2687
2688 LogFlowFuncLeaveRC(rc);
2689 return rc;
2690}
2691
2692/**
2693 * Sets the volume of a specified mixer control.
2694 *
2695 * @return IPRT status code.
2696 * @param pThis HDA State.
2697 * @param enmMixerCtl Mixer control to set volume for.
2698 * @param pVol Pointer to volume data to set.
2699 *
2700 * @remarks Can be called as a callback by the HDA codec.
2701 */
2702static DECLCALLBACK(int) hdaMixerSetVolume(PHDASTATE pThis,
2703 PDMAUDIOMIXERCTL enmMixerCtl, PPDMAUDIOVOLUME pVol)
2704{
2705 int rc;
2706
2707 PHDAMIXERSINK pSink = hdaMixerControlToSink(pThis, enmMixerCtl);
2708 if ( pSink
2709 && pSink->pMixSink)
2710 {
2711 LogRel2(("HDA: Setting volume for mixer sink '%s' to %RU8/%RU8 (%s)\n",
2712 pSink->pMixSink->pszName, pVol->uLeft, pVol->uRight, pVol->fMuted ? "Muted" : "Unmuted"));
2713
2714 /* Set the volume.
2715 * We assume that the codec already converted it to the correct range. */
2716 rc = AudioMixerSinkSetVolume(pSink->pMixSink, pVol);
2717 }
2718 else
2719 rc = VERR_NOT_FOUND;
2720
2721 LogFlowFuncLeaveRC(rc);
2722 return rc;
2723}
2724
2725/**
2726 * Main routine for the device timer.
2727 *
2728 * @param pThis HDA state.
2729 */
2730static void hdaTimerMain(PHDASTATE pThis)
2731{
2732 AssertPtrReturnVoid(pThis);
2733
2734 STAM_PROFILE_START(&pThis->StatTimer, a);
2735
2736 DEVHDA_LOCK_BOTH_RETURN_VOID(pThis);
2737
2738 /* Do all transfers from/to DMA. */
2739 hdaDoTransfers(pThis);
2740
2741 /* Flag indicating whether to kick the timer again for a
2742 * new data processing round. */
2743 bool fSinksActive = false;
2744
2745 /* Do we need to kick the timer again? */
2746 if ( AudioMixerSinkIsActive(pThis->SinkFront.pMixSink)
2747#ifdef VBOX_WITH_AUDIO_HDA_51_SURROUND
2748 || AudioMixerSinkIsActive(pThis->SinkCenterLFE.pMixSink)
2749 || AudioMixerSinkIsActive(pThis->SinkRear.pMixSink)
2750#endif
2751 || AudioMixerSinkIsActive(pThis->SinkLineIn.pMixSink)
2752#ifdef VBOX_WITH_AUDIO_HDA_MIC_IN
2753 || AudioMixerSinkIsActive(pThis->SinkMicIn.pMixSink)
2754#endif
2755 )
2756 {
2757 fSinksActive = true;
2758 }
2759
2760 bool fTimerScheduled = false;
2761 if ( hdaStreamTransferIsScheduled(hdaGetStreamFromSink(pThis, &pThis->SinkFront))
2762#ifdef VBOX_WITH_AUDIO_HDA_MIC_IN
2763 || hdaStreamTransferIsScheduled(hdaGetStreamFromSink(pThis, &pThis->SinkMicIn))
2764#endif
2765 || hdaStreamTransferIsScheduled(hdaGetStreamFromSink(pThis, &pThis->SinkLineIn)))
2766 {
2767 fTimerScheduled = true;
2768 }
2769
2770 Log3Func(("fSinksActive=%RTbool, fTimerScheduled=%RTbool\n", fSinksActive, fTimerScheduled));
2771
2772 if ( fSinksActive
2773 && !fTimerScheduled)
2774 {
2775 hdaTimerSet(pThis, TMTimerGet(pThis->pTimer) + TMTimerGetFreq(pThis->pTimer) / pThis->u16TimerHz, true /* fForce */);
2776 }
2777
2778 DEVHDA_UNLOCK_BOTH(pThis);
2779
2780 STAM_PROFILE_STOP(&pThis->StatTimer, a);
2781}
2782
2783#ifdef HDA_USE_DMA_ACCESS_HANDLER
2784/**
2785 * HC access handler for the FIFO.
2786 *
2787 * @returns VINF_SUCCESS if the handler have carried out the operation.
2788 * @returns VINF_PGM_HANDLER_DO_DEFAULT if the caller should carry out the access operation.
2789 * @param pVM VM Handle.
2790 * @param pVCpu The cross context CPU structure for the calling EMT.
2791 * @param GCPhys The physical address the guest is writing to.
2792 * @param pvPhys The HC mapping of that address.
2793 * @param pvBuf What the guest is reading/writing.
2794 * @param cbBuf How much it's reading/writing.
2795 * @param enmAccessType The access type.
2796 * @param enmOrigin Who is making the access.
2797 * @param pvUser User argument.
2798 */
2799static DECLCALLBACK(VBOXSTRICTRC) hdaDMAAccessHandler(PVM pVM, PVMCPU pVCpu, RTGCPHYS GCPhys, void *pvPhys,
2800 void *pvBuf, size_t cbBuf,
2801 PGMACCESSTYPE enmAccessType, PGMACCESSORIGIN enmOrigin, void *pvUser)
2802{
2803 RT_NOREF(pVM, pVCpu, pvPhys, pvBuf, enmOrigin);
2804
2805 PHDADMAACCESSHANDLER pHandler = (PHDADMAACCESSHANDLER)pvUser;
2806 AssertPtr(pHandler);
2807
2808 PHDASTREAM pStream = pHandler->pStream;
2809 AssertPtr(pStream);
2810
2811 Assert(GCPhys >= pHandler->GCPhysFirst);
2812 Assert(GCPhys <= pHandler->GCPhysLast);
2813 Assert(enmAccessType == PGMACCESSTYPE_WRITE);
2814
2815 /* Not within BDLE range? Bail out. */
2816 if ( (GCPhys < pHandler->BDLEAddr)
2817 || (GCPhys + cbBuf > pHandler->BDLEAddr + pHandler->BDLESize))
2818 {
2819 return VINF_PGM_HANDLER_DO_DEFAULT;
2820 }
2821
2822 switch(enmAccessType)
2823 {
2824 case PGMACCESSTYPE_WRITE:
2825 {
2826# ifdef DEBUG
2827 PHDASTREAMDBGINFO pStreamDbg = &pStream->Dbg;
2828
2829 const uint64_t tsNowNs = RTTimeNanoTS();
2830 const uint32_t tsElapsedMs = (tsNowNs - pStreamDbg->tsWriteSlotBegin) / 1000 / 1000;
2831
2832 uint64_t cWritesHz = ASMAtomicReadU64(&pStreamDbg->cWritesHz);
2833 uint64_t cbWrittenHz = ASMAtomicReadU64(&pStreamDbg->cbWrittenHz);
2834
2835 if (tsElapsedMs >= (1000 / HDA_TIMER_HZ_DEFAULT))
2836 {
2837 LogFunc(("[SD%RU8] %RU32ms elapsed, cbWritten=%RU64, cWritten=%RU64 -- %RU32 bytes on average per time slot (%zums)\n",
2838 pStream->u8SD, tsElapsedMs, cbWrittenHz, cWritesHz,
2839 ASMDivU64ByU32RetU32(cbWrittenHz, cWritesHz ? cWritesHz : 1), 1000 / HDA_TIMER_HZ_DEFAULT));
2840
2841 pStreamDbg->tsWriteSlotBegin = tsNowNs;
2842
2843 cWritesHz = 0;
2844 cbWrittenHz = 0;
2845 }
2846
2847 cWritesHz += 1;
2848 cbWrittenHz += cbBuf;
2849
2850 ASMAtomicIncU64(&pStreamDbg->cWritesTotal);
2851 ASMAtomicAddU64(&pStreamDbg->cbWrittenTotal, cbBuf);
2852
2853 ASMAtomicWriteU64(&pStreamDbg->cWritesHz, cWritesHz);
2854 ASMAtomicWriteU64(&pStreamDbg->cbWrittenHz, cbWrittenHz);
2855
2856 LogFunc(("[SD%RU8] Writing %3zu @ 0x%x (off %zu)\n",
2857 pStream->u8SD, cbBuf, GCPhys, GCPhys - pHandler->BDLEAddr));
2858
2859 LogFunc(("[SD%RU8] cWrites=%RU64, cbWritten=%RU64 -> %RU32 bytes on average\n",
2860 pStream->u8SD, pStreamDbg->cWritesTotal, pStreamDbg->cbWrittenTotal,
2861 ASMDivU64ByU32RetU32(pStreamDbg->cbWrittenTotal, pStreamDbg->cWritesTotal)));
2862# endif
2863
2864 if (pThis->fDebugEnabled)
2865 {
2866 RTFILE fh;
2867 RTFileOpen(&fh, VBOX_AUDIO_DEBUG_DUMP_PCM_DATA_PATH "hdaDMAAccessWrite.pcm",
2868 RTFILE_O_OPEN_CREATE | RTFILE_O_APPEND | RTFILE_O_WRITE | RTFILE_O_DENY_NONE);
2869 RTFileWrite(fh, pvBuf, cbBuf, NULL);
2870 RTFileClose(fh);
2871 }
2872
2873# ifdef HDA_USE_DMA_ACCESS_HANDLER_WRITING
2874 PRTCIRCBUF pCircBuf = pStream->State.pCircBuf;
2875 AssertPtr(pCircBuf);
2876
2877 uint8_t *pbBuf = (uint8_t *)pvBuf;
2878 while (cbBuf)
2879 {
2880 /* Make sure we only copy as much as the stream's FIFO can hold (SDFIFOS, 18.2.39). */
2881 void *pvChunk;
2882 size_t cbChunk;
2883 RTCircBufAcquireWriteBlock(pCircBuf, cbBuf, &pvChunk, &cbChunk);
2884
2885 if (cbChunk)
2886 {
2887 memcpy(pvChunk, pbBuf, cbChunk);
2888
2889 pbBuf += cbChunk;
2890 Assert(cbBuf >= cbChunk);
2891 cbBuf -= cbChunk;
2892 }
2893 else
2894 {
2895 //AssertMsg(RTCircBufFree(pCircBuf), ("No more space but still %zu bytes to write\n", cbBuf));
2896 break;
2897 }
2898
2899 LogFunc(("[SD%RU8] cbChunk=%zu\n", pStream->u8SD, cbChunk));
2900
2901 RTCircBufReleaseWriteBlock(pCircBuf, cbChunk);
2902 }
2903# endif /* HDA_USE_DMA_ACCESS_HANDLER_WRITING */
2904 break;
2905 }
2906
2907 default:
2908 AssertMsgFailed(("Access type not implemented\n"));
2909 break;
2910 }
2911
2912 return VINF_PGM_HANDLER_DO_DEFAULT;
2913}
2914#endif /* HDA_USE_DMA_ACCESS_HANDLER */
2915
2916/**
2917 * Soft reset of the device triggered via GCTL.
2918 *
2919 * @param pThis HDA state.
2920 *
2921 */
2922static void hdaGCTLReset(PHDASTATE pThis)
2923{
2924 LogFlowFuncEnter();
2925
2926 pThis->cStreamsActive = 0;
2927
2928 HDA_REG(pThis, GCAP) = HDA_MAKE_GCAP(HDA_MAX_SDO, HDA_MAX_SDI, 0, 0, 1); /* see 6.2.1 */
2929 HDA_REG(pThis, VMIN) = 0x00; /* see 6.2.2 */
2930 HDA_REG(pThis, VMAJ) = 0x01; /* see 6.2.3 */
2931 HDA_REG(pThis, OUTPAY) = 0x003C; /* see 6.2.4 */
2932 HDA_REG(pThis, INPAY) = 0x001D; /* see 6.2.5 */
2933 HDA_REG(pThis, CORBSIZE) = 0x42; /* Up to 256 CORB entries see 6.2.1 */
2934 HDA_REG(pThis, RIRBSIZE) = 0x42; /* Up to 256 RIRB entries see 6.2.1 */
2935 HDA_REG(pThis, CORBRP) = 0x0;
2936 HDA_REG(pThis, CORBWP) = 0x0;
2937 HDA_REG(pThis, RIRBWP) = 0x0;
2938 /* Some guests (like Haiku) don't set RINTCNT explicitly but expect an interrupt after each
2939 * RIRB response -- so initialize RINTCNT to 1 by default. */
2940 HDA_REG(pThis, RINTCNT) = 0x1;
2941
2942 /*
2943 * Stop any audio currently playing and/or recording.
2944 */
2945 pThis->SinkFront.pStream = NULL;
2946 if (pThis->SinkFront.pMixSink)
2947 AudioMixerSinkReset(pThis->SinkFront.pMixSink);
2948# ifdef VBOX_WITH_AUDIO_HDA_MIC_IN
2949 pThis->SinkMicIn.pStream = NULL;
2950 if (pThis->SinkMicIn.pMixSink)
2951 AudioMixerSinkReset(pThis->SinkMicIn.pMixSink);
2952# endif
2953 pThis->SinkLineIn.pStream = NULL;
2954 if (pThis->SinkLineIn.pMixSink)
2955 AudioMixerSinkReset(pThis->SinkLineIn.pMixSink);
2956# ifdef VBOX_WITH_AUDIO_HDA_51_SURROUND
2957 pThis->SinkCenterLFE = NULL;
2958 if (pThis->SinkCenterLFE.pMixSink)
2959 AudioMixerSinkReset(pThis->SinkCenterLFE.pMixSink);
2960 pThis->SinkRear.pStream = NULL;
2961 if (pThis->SinkRear.pMixSink)
2962 AudioMixerSinkReset(pThis->SinkRear.pMixSink);
2963# endif
2964
2965 /*
2966 * Reset the codec.
2967 */
2968 if ( pThis->pCodec
2969 && pThis->pCodec->pfnReset)
2970 {
2971 pThis->pCodec->pfnReset(pThis->pCodec);
2972 }
2973
2974 /*
2975 * Set some sensible defaults for which HDA sinks
2976 * are connected to which stream number.
2977 *
2978 * We use SD0 for input and SD4 for output by default.
2979 * These stream numbers can be changed by the guest dynamically lateron.
2980 */
2981#ifdef VBOX_WITH_AUDIO_HDA_MIC_IN
2982 hdaMixerControl(pThis, PDMAUDIOMIXERCTL_MIC_IN , 1 /* SD0 */, 0 /* Channel */);
2983#endif
2984 hdaMixerControl(pThis, PDMAUDIOMIXERCTL_LINE_IN , 1 /* SD0 */, 0 /* Channel */);
2985
2986 hdaMixerControl(pThis, PDMAUDIOMIXERCTL_FRONT , 5 /* SD4 */, 0 /* Channel */);
2987#ifdef VBOX_WITH_AUDIO_HDA_51_SURROUND
2988 hdaMixerControl(pThis, PDMAUDIOMIXERCTL_CENTER_LFE, 5 /* SD4 */, 0 /* Channel */);
2989 hdaMixerControl(pThis, PDMAUDIOMIXERCTL_REAR , 5 /* SD4 */, 0 /* Channel */);
2990#endif
2991
2992 pThis->cbCorbBuf = HDA_CORB_SIZE * sizeof(uint32_t);
2993
2994 if (pThis->pu32CorbBuf)
2995 RT_BZERO(pThis->pu32CorbBuf, pThis->cbCorbBuf);
2996 else
2997 pThis->pu32CorbBuf = (uint32_t *)RTMemAllocZ(pThis->cbCorbBuf);
2998
2999 pThis->cbRirbBuf = HDA_RIRB_SIZE * sizeof(uint64_t);
3000 if (pThis->pu64RirbBuf)
3001 RT_BZERO(pThis->pu64RirbBuf, pThis->cbRirbBuf);
3002 else
3003 pThis->pu64RirbBuf = (uint64_t *)RTMemAllocZ(pThis->cbRirbBuf);
3004
3005 /* Clear our internal response interrupt counter. */
3006 pThis->u16RespIntCnt = 0;
3007
3008 for (uint8_t uSD = 0; uSD < HDA_MAX_STREAMS; ++uSD)
3009 {
3010 /* Remove the RUN bit from SDnCTL in case the stream was in a running state before. */
3011 HDA_STREAM_REG(pThis, CTL, uSD) &= ~HDA_SDCTL_RUN;
3012 hdaStreamReset(pThis, &pThis->aStreams[uSD], uSD);
3013 }
3014
3015 /* Clear stream tags <-> objects mapping table. */
3016 RT_ZERO(pThis->aTags);
3017
3018 /* Emulation of codec "wake up" (HDA spec 5.5.1 and 6.5). */
3019 HDA_REG(pThis, STATESTS) = 0x1;
3020
3021 LogFlowFuncLeave();
3022 LogRel(("HDA: Reset\n"));
3023}
3024
3025/**
3026 * Timer callback which handles the audio data transfers on a periodic basis.
3027 *
3028 * @param pDevIns Device instance.
3029 * @param pTimer Timer which was used when calling this.
3030 * @param pvUser User argument as PHDASTATE.
3031 */
3032static DECLCALLBACK(void) hdaTimer(PPDMDEVINS pDevIns, PTMTIMER pTimer, void *pvUser)
3033{
3034 RT_NOREF(pDevIns, pTimer);
3035
3036 PHDASTATE pThis = (PHDASTATE)pvUser;
3037 Assert(pThis == PDMINS_2_DATA(pDevIns, PHDASTATE));
3038 AssertPtr(pThis);
3039
3040 hdaTimerMain(pThis);
3041}
3042
3043/**
3044 * Main routine to perform the actual audio data transfers from the HDA streams
3045 * to the backend(s) and vice versa.
3046 *
3047 * @param pThis HDA state.
3048 */
3049static void hdaDoTransfers(PHDASTATE pThis)
3050{
3051 PHDASTREAM pStreamLineIn = hdaGetStreamFromSink(pThis, &pThis->SinkLineIn);
3052#ifdef VBOX_WITH_AUDIO_HDA_MIC_IN
3053 PHDASTREAM pStreamMicIn = hdaGetStreamFromSink(pThis, &pThis->SinkMicIn);
3054#endif
3055 PHDASTREAM pStreamFront = hdaGetStreamFromSink(pThis, &pThis->SinkFront);
3056
3057 hdaStreamUpdate(pStreamFront, true /* fInTimer */);
3058#ifdef VBOX_WITH_AUDIO_HDA_MIC_IN
3059 hdaStreamUpdate(pStreamMicIn, true /* fInTimer */);
3060#endif
3061 hdaStreamUpdate(pStreamLineIn, true /* fInTimer */);
3062}
3063
3064#ifdef DEBUG_andy
3065# define HDA_DEBUG_DMA
3066#endif
3067
3068#endif /* IN_RING3 */
3069
3070/* MMIO callbacks */
3071
3072/**
3073 * @callback_method_impl{FNIOMMMIOREAD, Looks up and calls the appropriate handler.}
3074 *
3075 * @note During implementation, we discovered so-called "forgotten" or "hole"
3076 * registers whose description is not listed in the RPM, datasheet, or
3077 * spec.
3078 */
3079PDMBOTHCBDECL(int) hdaMMIORead(PPDMDEVINS pDevIns, void *pvUser, RTGCPHYS GCPhysAddr, void *pv, unsigned cb)
3080{
3081 PHDASTATE pThis = PDMINS_2_DATA(pDevIns, PHDASTATE);
3082 int rc;
3083 RT_NOREF_PV(pvUser);
3084
3085 /*
3086 * Look up and log.
3087 */
3088 uint32_t offReg = GCPhysAddr - pThis->MMIOBaseAddr;
3089 int idxRegDsc = hdaRegLookup(offReg); /* Register descriptor index. */
3090#ifdef LOG_ENABLED
3091 unsigned const cbLog = cb;
3092 uint32_t offRegLog = offReg;
3093#endif
3094
3095 Log3Func(("offReg=%#x cb=%#x\n", offReg, cb));
3096 Assert(cb == 4); Assert((offReg & 3) == 0);
3097
3098 DEVHDA_LOCK_RETURN(pThis, VINF_IOM_R3_MMIO_READ);
3099
3100 if (!(HDA_REG(pThis, GCTL) & HDA_GCTL_CRST) && idxRegDsc != HDA_REG_GCTL)
3101 LogFunc(("Access to registers except GCTL is blocked while reset\n"));
3102
3103 if (idxRegDsc == -1)
3104 LogRel(("HDA: Invalid read access @0x%x (bytes=%u)\n", offReg, cb));
3105
3106 if (idxRegDsc != -1)
3107 {
3108 /* Leave lock before calling read function. */
3109 DEVHDA_UNLOCK(pThis);
3110
3111 /* ASSUMES gapless DWORD at end of map. */
3112 if (g_aHdaRegMap[idxRegDsc].size == 4)
3113 {
3114 /*
3115 * Straight forward DWORD access.
3116 */
3117 rc = g_aHdaRegMap[idxRegDsc].pfnRead(pThis, idxRegDsc, (uint32_t *)pv);
3118 Log3Func(("\tRead %s => %x (%Rrc)\n", g_aHdaRegMap[idxRegDsc].abbrev, *(uint32_t *)pv, rc));
3119 }
3120 else
3121 {
3122 /*
3123 * Multi register read (unless there are trailing gaps).
3124 * ASSUMES that only DWORD reads have sideeffects.
3125 */
3126 uint32_t u32Value = 0;
3127 unsigned cbLeft = 4;
3128 do
3129 {
3130 uint32_t const cbReg = g_aHdaRegMap[idxRegDsc].size;
3131 uint32_t u32Tmp = 0;
3132
3133 rc = g_aHdaRegMap[idxRegDsc].pfnRead(pThis, idxRegDsc, &u32Tmp);
3134 Log3Func(("\tRead %s[%db] => %x (%Rrc)*\n", g_aHdaRegMap[idxRegDsc].abbrev, cbReg, u32Tmp, rc));
3135 if (rc != VINF_SUCCESS)
3136 break;
3137 u32Value |= (u32Tmp & g_afMasks[cbReg]) << ((4 - cbLeft) * 8);
3138
3139 cbLeft -= cbReg;
3140 offReg += cbReg;
3141 idxRegDsc++;
3142 } while (cbLeft > 0 && g_aHdaRegMap[idxRegDsc].offset == offReg);
3143
3144 if (rc == VINF_SUCCESS)
3145 *(uint32_t *)pv = u32Value;
3146 else
3147 Assert(!IOM_SUCCESS(rc));
3148 }
3149 }
3150 else
3151 {
3152 DEVHDA_UNLOCK(pThis);
3153
3154 rc = VINF_IOM_MMIO_UNUSED_FF;
3155 Log3Func(("\tHole at %x is accessed for read\n", offReg));
3156 }
3157
3158 /*
3159 * Log the outcome.
3160 */
3161#ifdef LOG_ENABLED
3162 if (cbLog == 4)
3163 Log3Func(("\tReturning @%#05x -> %#010x %Rrc\n", offRegLog, *(uint32_t *)pv, rc));
3164 else if (cbLog == 2)
3165 Log3Func(("\tReturning @%#05x -> %#06x %Rrc\n", offRegLog, *(uint16_t *)pv, rc));
3166 else if (cbLog == 1)
3167 Log3Func(("\tReturning @%#05x -> %#04x %Rrc\n", offRegLog, *(uint8_t *)pv, rc));
3168#endif
3169 return rc;
3170}
3171
3172
3173DECLINLINE(int) hdaWriteReg(PHDASTATE pThis, int idxRegDsc, uint32_t u32Value, char const *pszLog)
3174{
3175 DEVHDA_LOCK_RETURN(pThis, VINF_IOM_R3_MMIO_READ);
3176
3177 if (!(HDA_REG(pThis, GCTL) & HDA_GCTL_CRST) && idxRegDsc != HDA_REG_GCTL)
3178 {
3179 Log(("hdaWriteReg: Warning: Access to %s is blocked while controller is in reset mode\n", g_aHdaRegMap[idxRegDsc].abbrev));
3180 LogRel2(("HDA: Warning: Access to register %s is blocked while controller is in reset mode\n",
3181 g_aHdaRegMap[idxRegDsc].abbrev));
3182
3183 DEVHDA_UNLOCK(pThis);
3184 return VINF_SUCCESS;
3185 }
3186
3187 /*
3188 * Handle RD (register description) flags.
3189 */
3190
3191 /* For SDI / SDO: Check if writes to those registers are allowed while SDCTL's RUN bit is set. */
3192 if (idxRegDsc >= HDA_NUM_GENERAL_REGS)
3193 {
3194 const uint32_t uSDCTL = HDA_STREAM_REG(pThis, CTL, HDA_SD_NUM_FROM_REG(pThis, CTL, idxRegDsc));
3195
3196 /*
3197 * Some OSes (like Win 10 AU) violate the spec by writing stuff to registers which are not supposed to be be touched
3198 * while SDCTL's RUN bit is set. So just ignore those values.
3199 */
3200
3201 /* Is the RUN bit currently set? */
3202 if ( RT_BOOL(uSDCTL & HDA_SDCTL_RUN)
3203 /* Are writes to the register denied if RUN bit is set? */
3204 && !(g_aHdaRegMap[idxRegDsc].fFlags & HDA_RD_FLAG_SD_WRITE_RUN))
3205 {
3206 Log(("hdaWriteReg: Warning: Access to %s is blocked! %R[sdctl]\n", g_aHdaRegMap[idxRegDsc].abbrev, uSDCTL));
3207 LogRel2(("HDA: Warning: Access to register %s is blocked while the stream's RUN bit is set\n",
3208 g_aHdaRegMap[idxRegDsc].abbrev));
3209
3210 DEVHDA_UNLOCK(pThis);
3211 return VINF_SUCCESS;
3212 }
3213 }
3214
3215 /* Leave the lock before calling write function. */
3216 DEVHDA_UNLOCK(pThis);
3217
3218#ifdef LOG_ENABLED
3219 uint32_t const idxRegMem = g_aHdaRegMap[idxRegDsc].mem_idx;
3220 uint32_t const u32OldValue = pThis->au32Regs[idxRegMem];
3221#endif
3222 int rc = g_aHdaRegMap[idxRegDsc].pfnWrite(pThis, idxRegDsc, u32Value);
3223 Log3Func(("Written value %#x to %s[%d byte]; %x => %x%s\n", u32Value, g_aHdaRegMap[idxRegDsc].abbrev,
3224 g_aHdaRegMap[idxRegDsc].size, u32OldValue, pThis->au32Regs[idxRegMem], pszLog));
3225 RT_NOREF(pszLog);
3226 return rc;
3227}
3228
3229
3230/**
3231 * @callback_method_impl{FNIOMMMIOWRITE, Looks up and calls the appropriate handler.}
3232 */
3233PDMBOTHCBDECL(int) hdaMMIOWrite(PPDMDEVINS pDevIns, void *pvUser, RTGCPHYS GCPhysAddr, void const *pv, unsigned cb)
3234{
3235 PHDASTATE pThis = PDMINS_2_DATA(pDevIns, PHDASTATE);
3236 int rc;
3237 RT_NOREF_PV(pvUser);
3238
3239 /*
3240 * The behavior of accesses that aren't aligned on natural boundraries is
3241 * undefined. Just reject them outright.
3242 */
3243 /** @todo IOM could check this, it could also split the 8 byte accesses for us. */
3244 Assert(cb == 1 || cb == 2 || cb == 4 || cb == 8);
3245 if (GCPhysAddr & (cb - 1))
3246 return PDMDevHlpDBGFStop(pDevIns, RT_SRC_POS, "misaligned write access: GCPhysAddr=%RGp cb=%u\n", GCPhysAddr, cb);
3247
3248 /*
3249 * Look up and log the access.
3250 */
3251 uint32_t offReg = GCPhysAddr - pThis->MMIOBaseAddr;
3252 int idxRegDsc = hdaRegLookup(offReg);
3253 uint32_t idxRegMem = idxRegDsc != -1 ? g_aHdaRegMap[idxRegDsc].mem_idx : UINT32_MAX;
3254 uint64_t u64Value;
3255 if (cb == 4) u64Value = *(uint32_t const *)pv;
3256 else if (cb == 2) u64Value = *(uint16_t const *)pv;
3257 else if (cb == 1) u64Value = *(uint8_t const *)pv;
3258 else if (cb == 8) u64Value = *(uint64_t const *)pv;
3259 else
3260 {
3261 u64Value = 0; /* shut up gcc. */
3262 AssertReleaseMsgFailed(("%u\n", cb));
3263 }
3264
3265#ifdef LOG_ENABLED
3266 uint32_t const u32LogOldValue = idxRegDsc >= 0 ? pThis->au32Regs[idxRegMem] : UINT32_MAX;
3267 if (idxRegDsc == -1)
3268 Log3Func(("@%#05x u32=%#010x cb=%d\n", offReg, *(uint32_t const *)pv, cb));
3269 else if (cb == 4)
3270 Log3Func(("@%#05x u32=%#010x %s\n", offReg, *(uint32_t *)pv, g_aHdaRegMap[idxRegDsc].abbrev));
3271 else if (cb == 2)
3272 Log3Func(("@%#05x u16=%#06x (%#010x) %s\n", offReg, *(uint16_t *)pv, *(uint32_t *)pv, g_aHdaRegMap[idxRegDsc].abbrev));
3273 else if (cb == 1)
3274 Log3Func(("@%#05x u8=%#04x (%#010x) %s\n", offReg, *(uint8_t *)pv, *(uint32_t *)pv, g_aHdaRegMap[idxRegDsc].abbrev));
3275
3276 if (idxRegDsc >= 0 && g_aHdaRegMap[idxRegDsc].size != cb)
3277 Log3Func(("\tsize=%RU32 != cb=%u!!\n", g_aHdaRegMap[idxRegDsc].size, cb));
3278#endif
3279
3280 /*
3281 * Try for a direct hit first.
3282 */
3283 if (idxRegDsc != -1 && g_aHdaRegMap[idxRegDsc].size == cb)
3284 {
3285 rc = hdaWriteReg(pThis, idxRegDsc, u64Value, "");
3286 Log3Func(("\t%#x -> %#x\n", u32LogOldValue, idxRegMem != UINT32_MAX ? pThis->au32Regs[idxRegMem] : UINT32_MAX));
3287 }
3288 /*
3289 * Partial or multiple register access, loop thru the requested memory.
3290 */
3291 else
3292 {
3293 /*
3294 * If it's an access beyond the start of the register, shift the input
3295 * value and fill in missing bits. Natural alignment rules means we
3296 * will only see 1 or 2 byte accesses of this kind, so no risk of
3297 * shifting out input values.
3298 */
3299 if (idxRegDsc == -1 && (idxRegDsc = hdaRegLookupWithin(offReg)) != -1)
3300 {
3301 uint32_t const cbBefore = offReg - g_aHdaRegMap[idxRegDsc].offset; Assert(cbBefore > 0 && cbBefore < 4);
3302 offReg -= cbBefore;
3303 idxRegMem = g_aHdaRegMap[idxRegDsc].mem_idx;
3304 u64Value <<= cbBefore * 8;
3305 u64Value |= pThis->au32Regs[idxRegMem] & g_afMasks[cbBefore];
3306 Log3Func(("\tWithin register, supplied %u leading bits: %#llx -> %#llx ...\n",
3307 cbBefore * 8, ~g_afMasks[cbBefore] & u64Value, u64Value));
3308 }
3309
3310 /* Loop thru the write area, it may cover multiple registers. */
3311 rc = VINF_SUCCESS;
3312 for (;;)
3313 {
3314 uint32_t cbReg;
3315 if (idxRegDsc != -1)
3316 {
3317 idxRegMem = g_aHdaRegMap[idxRegDsc].mem_idx;
3318 cbReg = g_aHdaRegMap[idxRegDsc].size;
3319 if (cb < cbReg)
3320 {
3321 u64Value |= pThis->au32Regs[idxRegMem] & g_afMasks[cbReg] & ~g_afMasks[cb];
3322 Log3Func(("\tSupplying missing bits (%#x): %#llx -> %#llx ...\n",
3323 g_afMasks[cbReg] & ~g_afMasks[cb], u64Value & g_afMasks[cb], u64Value));
3324 }
3325#ifdef LOG_ENABLED
3326 uint32_t uLogOldVal = pThis->au32Regs[idxRegMem];
3327#endif
3328 rc = hdaWriteReg(pThis, idxRegDsc, u64Value, "*");
3329 Log3Func(("\t%#x -> %#x\n", uLogOldVal, pThis->au32Regs[idxRegMem]));
3330 }
3331 else
3332 {
3333 LogRel(("HDA: Invalid write access @0x%x\n", offReg));
3334 cbReg = 1;
3335 }
3336 if (rc != VINF_SUCCESS)
3337 break;
3338 if (cbReg >= cb)
3339 break;
3340
3341 /* Advance. */
3342 offReg += cbReg;
3343 cb -= cbReg;
3344 u64Value >>= cbReg * 8;
3345 if (idxRegDsc == -1)
3346 idxRegDsc = hdaRegLookup(offReg);
3347 else
3348 {
3349 idxRegDsc++;
3350 if ( (unsigned)idxRegDsc >= RT_ELEMENTS(g_aHdaRegMap)
3351 || g_aHdaRegMap[idxRegDsc].offset != offReg)
3352 {
3353 idxRegDsc = -1;
3354 }
3355 }
3356 }
3357 }
3358
3359 return rc;
3360}
3361
3362
3363/* PCI callback. */
3364
3365#ifdef IN_RING3
3366/**
3367 * @callback_method_impl{FNPCIIOREGIONMAP}
3368 */
3369static DECLCALLBACK(int) hdaPciIoRegionMap(PPDMDEVINS pDevIns, PPDMPCIDEV pPciDev, uint32_t iRegion,
3370 RTGCPHYS GCPhysAddress, RTGCPHYS cb, PCIADDRESSSPACE enmType)
3371{
3372 RT_NOREF(iRegion, enmType);
3373 PHDASTATE pThis = RT_FROM_MEMBER(pPciDev, HDASTATE, PciDev);
3374
3375 /*
3376 * 18.2 of the ICH6 datasheet defines the valid access widths as byte, word, and double word.
3377 *
3378 * Let IOM talk DWORDs when reading, saves a lot of complications. On
3379 * writing though, we have to do it all ourselves because of sideeffects.
3380 */
3381 Assert(enmType == PCI_ADDRESS_SPACE_MEM);
3382 int rc = PDMDevHlpMMIORegister(pDevIns, GCPhysAddress, cb, NULL /*pvUser*/,
3383 IOMMMIO_FLAGS_READ_DWORD
3384 | IOMMMIO_FLAGS_WRITE_PASSTHRU,
3385 hdaMMIOWrite, hdaMMIORead, "HDA");
3386
3387 if (RT_FAILURE(rc))
3388 return rc;
3389
3390 if (pThis->fR0Enabled)
3391 {
3392 rc = PDMDevHlpMMIORegisterR0(pDevIns, GCPhysAddress, cb, NIL_RTR0PTR /*pvUser*/,
3393 "hdaMMIOWrite", "hdaMMIORead");
3394 if (RT_FAILURE(rc))
3395 return rc;
3396 }
3397
3398 if (pThis->fRCEnabled)
3399 {
3400 rc = PDMDevHlpMMIORegisterRC(pDevIns, GCPhysAddress, cb, NIL_RTRCPTR /*pvUser*/,
3401 "hdaMMIOWrite", "hdaMMIORead");
3402 if (RT_FAILURE(rc))
3403 return rc;
3404 }
3405
3406 pThis->MMIOBaseAddr = GCPhysAddress;
3407 return VINF_SUCCESS;
3408}
3409
3410
3411/* Saved state callbacks. */
3412
3413static int hdaSaveStream(PPDMDEVINS pDevIns, PSSMHANDLE pSSM, PHDASTREAM pStream)
3414{
3415 RT_NOREF(pDevIns);
3416#ifdef VBOX_STRICT
3417 PHDASTATE pThis = PDMINS_2_DATA(pDevIns, PHDASTATE);
3418#endif
3419
3420 Log2Func(("[SD%RU8]\n", pStream->u8SD));
3421
3422 /* Save stream ID. */
3423 int rc = SSMR3PutU8(pSSM, pStream->u8SD);
3424 AssertRCReturn(rc, rc);
3425 Assert(pStream->u8SD < HDA_MAX_STREAMS);
3426
3427 rc = SSMR3PutStructEx(pSSM, &pStream->State, sizeof(HDASTREAMSTATE), 0 /*fFlags*/, g_aSSMStreamStateFields7, NULL);
3428 AssertRCReturn(rc, rc);
3429
3430#ifdef VBOX_STRICT /* Sanity checks. */
3431 uint64_t u64BaseDMA = RT_MAKE_U64(HDA_STREAM_REG(pThis, BDPL, pStream->u8SD),
3432 HDA_STREAM_REG(pThis, BDPU, pStream->u8SD));
3433 uint16_t u16LVI = HDA_STREAM_REG(pThis, LVI, pStream->u8SD);
3434 uint32_t u32CBL = HDA_STREAM_REG(pThis, CBL, pStream->u8SD);
3435
3436 Assert(u64BaseDMA == pStream->u64BDLBase);
3437 Assert(u16LVI == pStream->u16LVI);
3438 Assert(u32CBL == pStream->u32CBL);
3439#endif
3440
3441 rc = SSMR3PutStructEx(pSSM, &pStream->State.BDLE.Desc, sizeof(HDABDLEDESC),
3442 0 /*fFlags*/, g_aSSMBDLEDescFields7, NULL);
3443 AssertRCReturn(rc, rc);
3444
3445 rc = SSMR3PutStructEx(pSSM, &pStream->State.BDLE.State, sizeof(HDABDLESTATE),
3446 0 /*fFlags*/, g_aSSMBDLEStateFields7, NULL);
3447 AssertRCReturn(rc, rc);
3448
3449 rc = SSMR3PutStructEx(pSSM, &pStream->State.Period, sizeof(HDASTREAMPERIOD),
3450 0 /* fFlags */, g_aSSMStreamPeriodFields7, NULL);
3451 AssertRCReturn(rc, rc);
3452
3453#ifdef VBOX_STRICT /* Sanity checks. */
3454 PHDABDLE pBDLE = &pStream->State.BDLE;
3455 if (u64BaseDMA)
3456 {
3457 Assert(pStream->State.uCurBDLE <= u16LVI + 1);
3458
3459 HDABDLE curBDLE;
3460 rc = hdaBDLEFetch(pThis, &curBDLE, u64BaseDMA, pStream->State.uCurBDLE);
3461 AssertRC(rc);
3462
3463 Assert(curBDLE.Desc.u32BufSize == pBDLE->Desc.u32BufSize);
3464 Assert(curBDLE.Desc.u64BufAdr == pBDLE->Desc.u64BufAdr);
3465 Assert(curBDLE.Desc.fFlags == pBDLE->Desc.fFlags);
3466 }
3467 else
3468 {
3469 Assert(pBDLE->Desc.u64BufAdr == 0);
3470 Assert(pBDLE->Desc.u32BufSize == 0);
3471 }
3472#endif
3473
3474 uint32_t cbCircBufSize = 0;
3475 uint32_t cbCircBufUsed = 0;
3476
3477 if (pStream->State.pCircBuf)
3478 {
3479 cbCircBufSize = (uint32_t)RTCircBufSize(pStream->State.pCircBuf);
3480 cbCircBufUsed = (uint32_t)RTCircBufUsed(pStream->State.pCircBuf);
3481 }
3482
3483 rc = SSMR3PutU32(pSSM, cbCircBufSize);
3484 AssertRCReturn(rc, rc);
3485
3486 rc = SSMR3PutU32(pSSM, cbCircBufUsed);
3487 AssertRCReturn(rc, rc);
3488
3489 if (cbCircBufUsed)
3490 {
3491 /*
3492 * We now need to get the circular buffer's data without actually modifying
3493 * the internal read / used offsets -- otherwise we would end up with broken audio
3494 * data after saving the state.
3495 *
3496 * So get the current read offset and serialize the buffer data manually based on that.
3497 */
3498 size_t cbCircBufOffRead = RTCircBufOffsetRead(pStream->State.pCircBuf);
3499
3500 void *pvBuf;
3501 size_t cbBuf;
3502 RTCircBufAcquireReadBlock(pStream->State.pCircBuf, cbCircBufUsed, &pvBuf, &cbBuf);
3503
3504 if (cbBuf)
3505 {
3506 size_t cbToRead = cbCircBufUsed;
3507 size_t cbEnd = 0;
3508
3509 if (cbCircBufUsed > cbCircBufOffRead)
3510 cbEnd = cbCircBufUsed - cbCircBufOffRead;
3511
3512 if (cbEnd) /* Save end of buffer first. */
3513 {
3514 rc = SSMR3PutMem(pSSM, (uint8_t *)pvBuf + cbCircBufSize - cbEnd /* End of buffer */, cbEnd);
3515 AssertRCReturn(rc, rc);
3516
3517 Assert(cbToRead >= cbEnd);
3518 cbToRead -= cbEnd;
3519 }
3520
3521 if (cbToRead) /* Save remaining stuff at start of buffer (if any). */
3522 {
3523 rc = SSMR3PutMem(pSSM, (uint8_t *)pvBuf - cbCircBufUsed /* Start of buffer */, cbToRead);
3524 AssertRCReturn(rc, rc);
3525 }
3526 }
3527
3528 RTCircBufReleaseReadBlock(pStream->State.pCircBuf, 0 /* Don't advance read pointer -- see comment above */);
3529 }
3530
3531 Log2Func(("[SD%RU8] LPIB=%RU32, CBL=%RU32, LVI=%RU32\n",
3532 pStream->u8SD,
3533 HDA_STREAM_REG(pThis, LPIB, pStream->u8SD), HDA_STREAM_REG(pThis, CBL, pStream->u8SD), HDA_STREAM_REG(pThis, LVI, pStream->u8SD)));
3534
3535#ifdef LOG_ENABLED
3536 hdaBDLEDumpAll(pThis, pStream->u64BDLBase, pStream->u16LVI + 1);
3537#endif
3538
3539 return rc;
3540}
3541
3542/**
3543 * @callback_method_impl{FNSSMDEVSAVEEXEC}
3544 */
3545static DECLCALLBACK(int) hdaSaveExec(PPDMDEVINS pDevIns, PSSMHANDLE pSSM)
3546{
3547 PHDASTATE pThis = PDMINS_2_DATA(pDevIns, PHDASTATE);
3548
3549 /* Save Codec nodes states. */
3550 hdaCodecSaveState(pThis->pCodec, pSSM);
3551
3552 /* Save MMIO registers. */
3553 SSMR3PutU32(pSSM, RT_ELEMENTS(pThis->au32Regs));
3554 SSMR3PutMem(pSSM, pThis->au32Regs, sizeof(pThis->au32Regs));
3555
3556 /* Save controller-specifc internals. */
3557 SSMR3PutU64(pSSM, pThis->u64WalClk);
3558 SSMR3PutU8(pSSM, pThis->u8IRQL);
3559
3560 /* Save number of streams. */
3561 SSMR3PutU32(pSSM, HDA_MAX_STREAMS);
3562
3563 /* Save stream states. */
3564 for (uint8_t i = 0; i < HDA_MAX_STREAMS; i++)
3565 {
3566 int rc = hdaSaveStream(pDevIns, pSSM, &pThis->aStreams[i]);
3567 AssertRCReturn(rc, rc);
3568 }
3569
3570 return VINF_SUCCESS;
3571}
3572
3573/**
3574 * Does required post processing when loading a saved state.
3575 *
3576 * @param pThis Pointer to HDA state.
3577 */
3578static int hdaLoadExecPost(PHDASTATE pThis)
3579{
3580 int rc = VINF_SUCCESS;
3581
3582 uint64_t tsExpire = 0; /* Timestamp of new timer expiration time / Whether to resume the device timer. */
3583
3584 /*
3585 * Enable all previously active streams.
3586 */
3587 for (uint8_t i = 0; i < HDA_MAX_STREAMS; i++)
3588 {
3589 PHDASTREAM pStream = hdaGetStreamFromSD(pThis, i);
3590 if (pStream)
3591 {
3592 int rc2;
3593
3594 bool fActive = RT_BOOL(HDA_STREAM_REG(pThis, CTL, i) & HDA_SDCTL_RUN);
3595 if (fActive)
3596 {
3597#ifdef VBOX_WITH_AUDIO_HDA_ASYNC_IO
3598 /* Make sure to also create the async I/O thread before actually enabling the stream. */
3599 rc2 = hdaStreamAsyncIOCreate(pStream);
3600 AssertRC(rc2);
3601
3602 /* ... and enabling it. */
3603 hdaStreamAsyncIOEnable(pStream, true /* fEnable */);
3604#endif
3605 /* Resume the stream's period. */
3606 hdaStreamPeriodResume(&pStream->State.Period);
3607
3608 /* (Re-)enable the stream. */
3609 rc2 = hdaStreamEnable(pStream, true /* fEnable */);
3610 AssertRC(rc2);
3611
3612 /* Add the stream to the device setup. */
3613 rc2 = hdaAddStream(pThis, &pStream->State.Cfg);
3614 AssertRC(rc2);
3615
3616#ifdef HDA_USE_DMA_ACCESS_HANDLER
3617 /* (Re-)install the DMA handler. */
3618 hdaStreamRegisterDMAHandlers(pThis, pStream);
3619#endif
3620 /* Determine the earliest timing slot we need to use. */
3621 if (tsExpire)
3622 tsExpire = RT_MIN(tsExpire, hdaStreamTransferGetNext(pStream));
3623 else
3624 tsExpire = hdaStreamTransferGetNext(pStream);
3625
3626 Log2Func(("[SD%RU8] tsExpire=%RU64\n", pStream->u8SD, tsExpire));
3627
3628 /* Also keep track of the currently active streams. */
3629 pThis->cStreamsActive++;
3630 }
3631 }
3632 }
3633
3634 /* Start the timer if one of the above streams were active during taking the saved state. */
3635 if (tsExpire)
3636 {
3637 LogFunc(("Resuming timer at %RU64\n", tsExpire));
3638 hdaTimerSet(pThis, tsExpire, true /* fForce */);
3639 }
3640
3641 LogFlowFuncLeaveRC(rc);
3642 return rc;
3643}
3644
3645
3646/**
3647 * Handles loading of all saved state versions older than the current one.
3648 *
3649 * @param pThis Pointer to HDA state.
3650 * @param pSSM Pointer to SSM handle.
3651 * @param uVersion Saved state version to load.
3652 * @param uPass Loading stage to handle.
3653 */
3654static int hdaLoadExecLegacy(PHDASTATE pThis, PSSMHANDLE pSSM, uint32_t uVersion, uint32_t uPass)
3655{
3656 RT_NOREF(uPass);
3657
3658 int rc = VINF_SUCCESS;
3659
3660 /*
3661 * Load MMIO registers.
3662 */
3663 uint32_t cRegs;
3664 switch (uVersion)
3665 {
3666 case HDA_SSM_VERSION_1:
3667 /* Starting with r71199, we would save 112 instead of 113
3668 registers due to some code cleanups. This only affected trunk
3669 builds in the 4.1 development period. */
3670 cRegs = 113;
3671 if (SSMR3HandleRevision(pSSM) >= 71199)
3672 {
3673 uint32_t uVer = SSMR3HandleVersion(pSSM);
3674 if ( VBOX_FULL_VERSION_GET_MAJOR(uVer) == 4
3675 && VBOX_FULL_VERSION_GET_MINOR(uVer) == 0
3676 && VBOX_FULL_VERSION_GET_BUILD(uVer) >= 51)
3677 cRegs = 112;
3678 }
3679 break;
3680
3681 case HDA_SSM_VERSION_2:
3682 case HDA_SSM_VERSION_3:
3683 cRegs = 112;
3684 AssertCompile(RT_ELEMENTS(pThis->au32Regs) >= 112);
3685 break;
3686
3687 /* Since version 4 we store the register count to stay flexible. */
3688 case HDA_SSM_VERSION_4:
3689 case HDA_SSM_VERSION_5:
3690 case HDA_SSM_VERSION_6:
3691 rc = SSMR3GetU32(pSSM, &cRegs); AssertRCReturn(rc, rc);
3692 if (cRegs != RT_ELEMENTS(pThis->au32Regs))
3693 LogRel(("HDA: SSM version cRegs is %RU32, expected %RU32\n", cRegs, RT_ELEMENTS(pThis->au32Regs)));
3694 break;
3695
3696 default:
3697 LogRel(("HDA: Warning: Unsupported / too new saved state version (%RU32)\n", uVersion));
3698 return VERR_SSM_UNSUPPORTED_DATA_UNIT_VERSION;
3699 }
3700
3701 if (cRegs >= RT_ELEMENTS(pThis->au32Regs))
3702 {
3703 SSMR3GetMem(pSSM, pThis->au32Regs, sizeof(pThis->au32Regs));
3704 SSMR3Skip(pSSM, sizeof(uint32_t) * (cRegs - RT_ELEMENTS(pThis->au32Regs)));
3705 }
3706 else
3707 SSMR3GetMem(pSSM, pThis->au32Regs, sizeof(uint32_t) * cRegs);
3708
3709 /* Make sure to update the base addresses first before initializing any streams down below. */
3710 pThis->u64CORBBase = RT_MAKE_U64(HDA_REG(pThis, CORBLBASE), HDA_REG(pThis, CORBUBASE));
3711 pThis->u64RIRBBase = RT_MAKE_U64(HDA_REG(pThis, RIRBLBASE), HDA_REG(pThis, RIRBUBASE));
3712 pThis->u64DPBase = RT_MAKE_U64(HDA_REG(pThis, DPLBASE) & DPBASE_ADDR_MASK, HDA_REG(pThis, DPUBASE));
3713
3714 /* Also make sure to update the DMA position bit if this was enabled when saving the state. */
3715 pThis->fDMAPosition = RT_BOOL(HDA_REG(pThis, DPLBASE) & RT_BIT_32(0));
3716
3717 /*
3718 * Note: Saved states < v5 store LVI (u32BdleMaxCvi) for
3719 * *every* BDLE state, whereas it only needs to be stored
3720 * *once* for every stream. Most of the BDLE state we can
3721 * get out of the registers anyway, so just ignore those values.
3722 *
3723 * Also, only the current BDLE was saved, regardless whether
3724 * there were more than one (and there are at least two entries,
3725 * according to the spec).
3726 */
3727#define HDA_SSM_LOAD_BDLE_STATE_PRE_V5(v, x) \
3728 { \
3729 rc = SSMR3Skip(pSSM, sizeof(uint32_t)); /* Begin marker */ \
3730 AssertRCReturn(rc, rc); \
3731 rc = SSMR3GetU64(pSSM, &x.Desc.u64BufAdr); /* u64BdleCviAddr */ \
3732 AssertRCReturn(rc, rc); \
3733 rc = SSMR3Skip(pSSM, sizeof(uint32_t)); /* u32BdleMaxCvi */ \
3734 AssertRCReturn(rc, rc); \
3735 rc = SSMR3GetU32(pSSM, &x.State.u32BDLIndex); /* u32BdleCvi */ \
3736 AssertRCReturn(rc, rc); \
3737 rc = SSMR3GetU32(pSSM, &x.Desc.u32BufSize); /* u32BdleCviLen */ \
3738 AssertRCReturn(rc, rc); \
3739 rc = SSMR3GetU32(pSSM, &x.State.u32BufOff); /* u32BdleCviPos */ \
3740 AssertRCReturn(rc, rc); \
3741 bool fIOC; \
3742 rc = SSMR3GetBool(pSSM, &fIOC); /* fBdleCviIoc */ \
3743 AssertRCReturn(rc, rc); \
3744 x.Desc.fFlags = fIOC ? HDA_BDLE_FLAG_IOC : 0; \
3745 rc = SSMR3GetU32(pSSM, &x.State.cbBelowFIFOW); /* cbUnderFifoW */ \
3746 AssertRCReturn(rc, rc); \
3747 rc = SSMR3Skip(pSSM, sizeof(uint8_t) * 256); /* FIFO */ \
3748 AssertRCReturn(rc, rc); \
3749 rc = SSMR3Skip(pSSM, sizeof(uint32_t)); /* End marker */ \
3750 AssertRCReturn(rc, rc); \
3751 }
3752
3753 /*
3754 * Load BDLEs (Buffer Descriptor List Entries) and DMA counters.
3755 */
3756 switch (uVersion)
3757 {
3758 case HDA_SSM_VERSION_1:
3759 case HDA_SSM_VERSION_2:
3760 case HDA_SSM_VERSION_3:
3761 case HDA_SSM_VERSION_4:
3762 {
3763 /* Only load the internal states.
3764 * The rest will be initialized from the saved registers later. */
3765
3766 /* Note 1: Only the *current* BDLE for a stream was saved! */
3767 /* Note 2: The stream's saving order is/was fixed, so don't touch! */
3768
3769 /* Output */
3770 PHDASTREAM pStream = &pThis->aStreams[4];
3771 rc = hdaStreamInit(pStream, 4 /* Stream descriptor, hardcoded */);
3772 if (RT_FAILURE(rc))
3773 break;
3774 HDA_SSM_LOAD_BDLE_STATE_PRE_V5(uVersion, pStream->State.BDLE);
3775 pStream->State.uCurBDLE = pStream->State.BDLE.State.u32BDLIndex;
3776
3777 /* Microphone-In */
3778 pStream = &pThis->aStreams[2];
3779 rc = hdaStreamInit(pStream, 2 /* Stream descriptor, hardcoded */);
3780 if (RT_FAILURE(rc))
3781 break;
3782 HDA_SSM_LOAD_BDLE_STATE_PRE_V5(uVersion, pStream->State.BDLE);
3783 pStream->State.uCurBDLE = pStream->State.BDLE.State.u32BDLIndex;
3784
3785 /* Line-In */
3786 pStream = &pThis->aStreams[0];
3787 rc = hdaStreamInit(pStream, 0 /* Stream descriptor, hardcoded */);
3788 if (RT_FAILURE(rc))
3789 break;
3790 HDA_SSM_LOAD_BDLE_STATE_PRE_V5(uVersion, pStream->State.BDLE);
3791 pStream->State.uCurBDLE = pStream->State.BDLE.State.u32BDLIndex;
3792 break;
3793 }
3794
3795#undef HDA_SSM_LOAD_BDLE_STATE_PRE_V5
3796
3797 default: /* Since v5 we support flexible stream and BDLE counts. */
3798 {
3799 uint32_t cStreams;
3800 rc = SSMR3GetU32(pSSM, &cStreams);
3801 if (RT_FAILURE(rc))
3802 break;
3803
3804 if (cStreams > HDA_MAX_STREAMS)
3805 cStreams = HDA_MAX_STREAMS; /* Sanity. */
3806
3807 /* Load stream states. */
3808 for (uint32_t i = 0; i < cStreams; i++)
3809 {
3810 uint8_t uStreamID;
3811 rc = SSMR3GetU8(pSSM, &uStreamID);
3812 if (RT_FAILURE(rc))
3813 break;
3814
3815 PHDASTREAM pStream = hdaGetStreamFromSD(pThis, uStreamID);
3816 HDASTREAM StreamDummy;
3817
3818 if (!pStream)
3819 {
3820 pStream = &StreamDummy;
3821 LogRel2(("HDA: Warning: Stream ID=%RU32 not supported, skipping to load ...\n", uStreamID));
3822 }
3823
3824 rc = hdaStreamInit(pStream, uStreamID);
3825 if (RT_FAILURE(rc))
3826 {
3827 LogRel(("HDA: Stream #%RU32: Initialization of stream %RU8 failed, rc=%Rrc\n", i, uStreamID, rc));
3828 break;
3829 }
3830
3831 /*
3832 * Load BDLEs (Buffer Descriptor List Entries) and DMA counters.
3833 */
3834
3835 if (uVersion == HDA_SSM_VERSION_5)
3836 {
3837 /* Get the current BDLE entry and skip the rest. */
3838 uint16_t cBDLE;
3839
3840 rc = SSMR3Skip(pSSM, sizeof(uint32_t)); /* Begin marker */
3841 AssertRC(rc);
3842 rc = SSMR3GetU16(pSSM, &cBDLE); /* cBDLE */
3843 AssertRC(rc);
3844 rc = SSMR3GetU16(pSSM, &pStream->State.uCurBDLE); /* uCurBDLE */
3845 AssertRC(rc);
3846 rc = SSMR3Skip(pSSM, sizeof(uint32_t)); /* End marker */
3847 AssertRC(rc);
3848
3849 uint32_t u32BDLEIndex;
3850 for (uint16_t a = 0; a < cBDLE; a++)
3851 {
3852 rc = SSMR3Skip(pSSM, sizeof(uint32_t)); /* Begin marker */
3853 AssertRC(rc);
3854 rc = SSMR3GetU32(pSSM, &u32BDLEIndex); /* u32BDLIndex */
3855 AssertRC(rc);
3856
3857 /* Does the current BDLE index match the current BDLE to process? */
3858 if (u32BDLEIndex == pStream->State.uCurBDLE)
3859 {
3860 rc = SSMR3GetU32(pSSM, &pStream->State.BDLE.State.cbBelowFIFOW); /* cbBelowFIFOW */
3861 AssertRC(rc);
3862 rc = SSMR3Skip(pSSM, sizeof(uint8_t) * 256); /* FIFO, deprecated */
3863 AssertRC(rc);
3864 rc = SSMR3GetU32(pSSM, &pStream->State.BDLE.State.u32BufOff); /* u32BufOff */
3865 AssertRC(rc);
3866 rc = SSMR3Skip(pSSM, sizeof(uint32_t)); /* End marker */
3867 AssertRC(rc);
3868 }
3869 else /* Skip not current BDLEs. */
3870 {
3871 rc = SSMR3Skip(pSSM, sizeof(uint32_t) /* cbBelowFIFOW */
3872 + sizeof(uint8_t) * 256 /* au8FIFO */
3873 + sizeof(uint32_t) /* u32BufOff */
3874 + sizeof(uint32_t)); /* End marker */
3875 AssertRC(rc);
3876 }
3877 }
3878 }
3879 else
3880 {
3881 rc = SSMR3GetStructEx(pSSM, &pStream->State, sizeof(HDASTREAMSTATE),
3882 0 /* fFlags */, g_aSSMStreamStateFields6, NULL);
3883 if (RT_FAILURE(rc))
3884 break;
3885
3886 /* Get HDABDLEDESC. */
3887 uint32_t uMarker;
3888 rc = SSMR3GetU32(pSSM, &uMarker); /* Begin marker. */
3889 AssertRC(rc);
3890 Assert(uMarker == UINT32_C(0x19200102) /* SSMR3STRUCT_BEGIN */);
3891 rc = SSMR3GetU64(pSSM, &pStream->State.BDLE.Desc.u64BufAdr);
3892 AssertRC(rc);
3893 rc = SSMR3GetU32(pSSM, &pStream->State.BDLE.Desc.u32BufSize);
3894 AssertRC(rc);
3895 bool fFlags = false;
3896 rc = SSMR3GetBool(pSSM, &fFlags); /* Saved states < v7 only stored the IOC as boolean flag. */
3897 AssertRC(rc);
3898 pStream->State.BDLE.Desc.fFlags = fFlags ? HDA_BDLE_FLAG_IOC : 0;
3899 rc = SSMR3GetU32(pSSM, &uMarker); /* End marker. */
3900 AssertRC(rc);
3901 Assert(uMarker == UINT32_C(0x19920406) /* SSMR3STRUCT_END */);
3902
3903 rc = SSMR3GetStructEx(pSSM, &pStream->State.BDLE.State, sizeof(HDABDLESTATE),
3904 0 /* fFlags */, g_aSSMBDLEStateFields6, NULL);
3905 if (RT_FAILURE(rc))
3906 break;
3907
3908 Log2Func(("[SD%RU8] LPIB=%RU32, CBL=%RU32, LVI=%RU32\n",
3909 uStreamID,
3910 HDA_STREAM_REG(pThis, LPIB, uStreamID), HDA_STREAM_REG(pThis, CBL, uStreamID), HDA_STREAM_REG(pThis, LVI, uStreamID)));
3911#ifdef LOG_ENABLED
3912 hdaBDLEDumpAll(pThis, pStream->u64BDLBase, pStream->u16LVI + 1);
3913#endif
3914 }
3915
3916 } /* for cStreams */
3917 break;
3918 } /* default */
3919 }
3920
3921 return rc;
3922}
3923
3924/**
3925 * @callback_method_impl{FNSSMDEVLOADEXEC}
3926 */
3927static DECLCALLBACK(int) hdaLoadExec(PPDMDEVINS pDevIns, PSSMHANDLE pSSM, uint32_t uVersion, uint32_t uPass)
3928{
3929 PHDASTATE pThis = PDMINS_2_DATA(pDevIns, PHDASTATE);
3930
3931 Assert(uPass == SSM_PASS_FINAL); NOREF(uPass);
3932
3933 LogRel2(("hdaLoadExec: uVersion=%RU32, uPass=0x%x\n", uVersion, uPass));
3934
3935 /*
3936 * Load Codec nodes states.
3937 */
3938 int rc = hdaCodecLoadState(pThis->pCodec, pSSM, uVersion);
3939 if (RT_FAILURE(rc))
3940 {
3941 LogRel(("HDA: Failed loading codec state (version %RU32, pass 0x%x), rc=%Rrc\n", uVersion, uPass, rc));
3942 return rc;
3943 }
3944
3945 if (uVersion < HDA_SSM_VERSION) /* Handle older saved states? */
3946 {
3947 rc = hdaLoadExecLegacy(pThis, pSSM, uVersion, uPass);
3948 if (RT_SUCCESS(rc))
3949 rc = hdaLoadExecPost(pThis);
3950
3951 return rc;
3952 }
3953
3954 /*
3955 * Load MMIO registers.
3956 */
3957 uint32_t cRegs;
3958 rc = SSMR3GetU32(pSSM, &cRegs); AssertRCReturn(rc, rc);
3959 if (cRegs != RT_ELEMENTS(pThis->au32Regs))
3960 LogRel(("HDA: SSM version cRegs is %RU32, expected %RU32\n", cRegs, RT_ELEMENTS(pThis->au32Regs)));
3961
3962 if (cRegs >= RT_ELEMENTS(pThis->au32Regs))
3963 {
3964 SSMR3GetMem(pSSM, pThis->au32Regs, sizeof(pThis->au32Regs));
3965 SSMR3Skip(pSSM, sizeof(uint32_t) * (cRegs - RT_ELEMENTS(pThis->au32Regs)));
3966 }
3967 else
3968 SSMR3GetMem(pSSM, pThis->au32Regs, sizeof(uint32_t) * cRegs);
3969
3970 /* Make sure to update the base addresses first before initializing any streams down below. */
3971 pThis->u64CORBBase = RT_MAKE_U64(HDA_REG(pThis, CORBLBASE), HDA_REG(pThis, CORBUBASE));
3972 pThis->u64RIRBBase = RT_MAKE_U64(HDA_REG(pThis, RIRBLBASE), HDA_REG(pThis, RIRBUBASE));
3973 pThis->u64DPBase = RT_MAKE_U64(HDA_REG(pThis, DPLBASE) & DPBASE_ADDR_MASK, HDA_REG(pThis, DPUBASE));
3974
3975 /* Also make sure to update the DMA position bit if this was enabled when saving the state. */
3976 pThis->fDMAPosition = RT_BOOL(HDA_REG(pThis, DPLBASE) & RT_BIT_32(0));
3977
3978 /*
3979 * Load controller-specifc internals.
3980 * Don't annoy other team mates (forgot this for state v7).
3981 */
3982 if ( SSMR3HandleRevision(pSSM) >= 116273
3983 || SSMR3HandleVersion(pSSM) >= VBOX_FULL_VERSION_MAKE(5, 2, 0))
3984 {
3985 rc = SSMR3GetU64(pSSM, &pThis->u64WalClk);
3986 AssertRC(rc);
3987
3988 rc = SSMR3GetU8(pSSM, &pThis->u8IRQL);
3989 AssertRC(rc);
3990 }
3991
3992 /*
3993 * Load streams.
3994 */
3995 uint32_t cStreams;
3996 rc = SSMR3GetU32(pSSM, &cStreams);
3997 AssertRC(rc);
3998
3999 if (cStreams > HDA_MAX_STREAMS)
4000 cStreams = HDA_MAX_STREAMS; /* Sanity. */
4001
4002 Log2Func(("cStreams=%RU32\n", cStreams));
4003
4004 /* Load stream states. */
4005 for (uint32_t i = 0; i < cStreams; i++)
4006 {
4007 uint8_t uStreamID;
4008 rc = SSMR3GetU8(pSSM, &uStreamID);
4009 AssertRC(rc);
4010
4011 PHDASTREAM pStream = hdaGetStreamFromSD(pThis, uStreamID);
4012 HDASTREAM StreamDummy;
4013
4014 if (!pStream)
4015 {
4016 pStream = &StreamDummy;
4017 LogRel2(("HDA: Warning: Loading of stream #%RU8 not supported, skipping to load ...\n", uStreamID));
4018 }
4019
4020 rc = hdaStreamInit(pStream, uStreamID);
4021 if (RT_FAILURE(rc))
4022 {
4023 LogRel(("HDA: Stream #%RU8: Loading initialization failed, rc=%Rrc\n", uStreamID, rc));
4024 /* Continue. */
4025 }
4026
4027 rc = SSMR3GetStructEx(pSSM, &pStream->State, sizeof(HDASTREAMSTATE),
4028 0 /* fFlags */, g_aSSMStreamStateFields7,
4029 NULL);
4030 AssertRC(rc);
4031
4032 /*
4033 * Load BDLEs (Buffer Descriptor List Entries) and DMA counters.
4034 */
4035 rc = SSMR3GetStructEx(pSSM, &pStream->State.BDLE.Desc, sizeof(HDABDLEDESC),
4036 0 /* fFlags */, g_aSSMBDLEDescFields7, NULL);
4037 AssertRC(rc);
4038
4039 rc = SSMR3GetStructEx(pSSM, &pStream->State.BDLE.State, sizeof(HDABDLESTATE),
4040 0 /* fFlags */, g_aSSMBDLEStateFields7, NULL);
4041 AssertRC(rc);
4042
4043 Log2Func(("[SD%RU8] %R[bdle]\n", pStream->u8SD, &pStream->State.BDLE));
4044
4045 /*
4046 * Load period state.
4047 * Don't annoy other team mates (forgot this for state v7).
4048 */
4049 hdaStreamPeriodInit(&pStream->State.Period,
4050 pStream->u8SD, pStream->u16LVI, pStream->u32CBL, &pStream->State.Cfg);
4051
4052 if ( SSMR3HandleRevision(pSSM) >= 116273
4053 || SSMR3HandleVersion(pSSM) >= VBOX_FULL_VERSION_MAKE(5, 2, 0))
4054 {
4055 rc = SSMR3GetStructEx(pSSM, &pStream->State.Period, sizeof(HDASTREAMPERIOD),
4056 0 /* fFlags */, g_aSSMStreamPeriodFields7, NULL);
4057 AssertRC(rc);
4058 }
4059
4060 /*
4061 * Load internal (FIFO) buffer.
4062 */
4063 uint32_t cbCircBufSize = 0;
4064 rc = SSMR3GetU32(pSSM, &cbCircBufSize); /* cbCircBuf */
4065 AssertRC(rc);
4066
4067 uint32_t cbCircBufUsed = 0;
4068 rc = SSMR3GetU32(pSSM, &cbCircBufUsed); /* cbCircBuf */
4069 AssertRC(rc);
4070
4071 if (cbCircBufSize) /* If 0, skip the buffer. */
4072 {
4073 /* Paranoia. */
4074 AssertReleaseMsg(cbCircBufSize <= _1M,
4075 ("HDA: Saved state contains bogus DMA buffer size (%RU32) for stream #%RU8",
4076 cbCircBufSize, uStreamID));
4077 AssertReleaseMsg(cbCircBufUsed <= cbCircBufSize,
4078 ("HDA: Saved state contains invalid DMA buffer usage (%RU32/%RU32) for stream #%RU8",
4079 cbCircBufUsed, cbCircBufSize, uStreamID));
4080 AssertPtr(pStream->State.pCircBuf);
4081
4082 /* Do we need to cre-create the circular buffer do fit the data size? */
4083 if (cbCircBufSize != (uint32_t)RTCircBufSize(pStream->State.pCircBuf))
4084 {
4085 RTCircBufDestroy(pStream->State.pCircBuf);
4086 pStream->State.pCircBuf = NULL;
4087
4088 rc = RTCircBufCreate(&pStream->State.pCircBuf, cbCircBufSize);
4089 AssertRC(rc);
4090 }
4091
4092 if ( RT_SUCCESS(rc)
4093 && cbCircBufUsed)
4094 {
4095 void *pvBuf;
4096 size_t cbBuf;
4097
4098 RTCircBufAcquireWriteBlock(pStream->State.pCircBuf, cbCircBufUsed, &pvBuf, &cbBuf);
4099
4100 if (cbBuf)
4101 {
4102 rc = SSMR3GetMem(pSSM, pvBuf, cbBuf);
4103 AssertRC(rc);
4104 }
4105
4106 RTCircBufReleaseWriteBlock(pStream->State.pCircBuf, cbBuf);
4107
4108 Assert(cbBuf == cbCircBufUsed);
4109 }
4110 }
4111
4112 Log2Func(("[SD%RU8] LPIB=%RU32, CBL=%RU32, LVI=%RU32\n",
4113 uStreamID,
4114 HDA_STREAM_REG(pThis, LPIB, uStreamID), HDA_STREAM_REG(pThis, CBL, uStreamID), HDA_STREAM_REG(pThis, LVI, uStreamID)));
4115#ifdef LOG_ENABLED
4116 hdaBDLEDumpAll(pThis, pStream->u64BDLBase, pStream->u16LVI + 1);
4117#endif
4118 /** @todo (Re-)initialize active periods? */
4119
4120 } /* for cStreams */
4121
4122 rc = hdaLoadExecPost(pThis);
4123 AssertRC(rc);
4124
4125 LogFlowFuncLeaveRC(rc);
4126 return rc;
4127}
4128
4129/* Debug and log type formatters. */
4130
4131/**
4132 * @callback_method_impl{FNRTSTRFORMATTYPE}
4133 */
4134static DECLCALLBACK(size_t) hdaDbgFmtBDLE(PFNRTSTROUTPUT pfnOutput, void *pvArgOutput,
4135 const char *pszType, void const *pvValue,
4136 int cchWidth, int cchPrecision, unsigned fFlags,
4137 void *pvUser)
4138{
4139 RT_NOREF(pszType, cchWidth, cchPrecision, fFlags, pvUser);
4140 PHDABDLE pBDLE = (PHDABDLE)pvValue;
4141 return RTStrFormat(pfnOutput, pvArgOutput, NULL, 0,
4142 "BDLE(idx:%RU32, off:%RU32, fifow:%RU32, IOC:%RTbool, DMA[%RU32 bytes @ 0x%x])",
4143 pBDLE->State.u32BDLIndex, pBDLE->State.u32BufOff, pBDLE->State.cbBelowFIFOW,
4144 pBDLE->Desc.fFlags & HDA_BDLE_FLAG_IOC, pBDLE->Desc.u32BufSize, pBDLE->Desc.u64BufAdr);
4145}
4146
4147/**
4148 * @callback_method_impl{FNRTSTRFORMATTYPE}
4149 */
4150static DECLCALLBACK(size_t) hdaDbgFmtSDCTL(PFNRTSTROUTPUT pfnOutput, void *pvArgOutput,
4151 const char *pszType, void const *pvValue,
4152 int cchWidth, int cchPrecision, unsigned fFlags,
4153 void *pvUser)
4154{
4155 RT_NOREF(pszType, cchWidth, cchPrecision, fFlags, pvUser);
4156 uint32_t uSDCTL = (uint32_t)(uintptr_t)pvValue;
4157 return RTStrFormat(pfnOutput, pvArgOutput, NULL, 0,
4158 "SDCTL(raw:%#x, DIR:%s, TP:%RTbool, STRIPE:%x, DEIE:%RTbool, FEIE:%RTbool, IOCE:%RTbool, RUN:%RTbool, RESET:%RTbool)",
4159 uSDCTL,
4160 uSDCTL & HDA_SDCTL_DIR ? "OUT" : "IN",
4161 RT_BOOL(uSDCTL & HDA_SDCTL_TP),
4162 (uSDCTL & HDA_SDCTL_STRIPE_MASK) >> HDA_SDCTL_STRIPE_SHIFT,
4163 RT_BOOL(uSDCTL & HDA_SDCTL_DEIE),
4164 RT_BOOL(uSDCTL & HDA_SDCTL_FEIE),
4165 RT_BOOL(uSDCTL & HDA_SDCTL_IOCE),
4166 RT_BOOL(uSDCTL & HDA_SDCTL_RUN),
4167 RT_BOOL(uSDCTL & HDA_SDCTL_SRST));
4168}
4169
4170/**
4171 * @callback_method_impl{FNRTSTRFORMATTYPE}
4172 */
4173static DECLCALLBACK(size_t) hdaDbgFmtSDFIFOS(PFNRTSTROUTPUT pfnOutput, void *pvArgOutput,
4174 const char *pszType, void const *pvValue,
4175 int cchWidth, int cchPrecision, unsigned fFlags,
4176 void *pvUser)
4177{
4178 RT_NOREF(pszType, cchWidth, cchPrecision, fFlags, pvUser);
4179 uint32_t uSDFIFOS = (uint32_t)(uintptr_t)pvValue;
4180 return RTStrFormat(pfnOutput, pvArgOutput, NULL, 0, "SDFIFOS(raw:%#x, sdfifos:%RU8 B)", uSDFIFOS, uSDFIFOS ? uSDFIFOS + 1 : 0);
4181}
4182
4183/**
4184 * @callback_method_impl{FNRTSTRFORMATTYPE}
4185 */
4186static DECLCALLBACK(size_t) hdaDbgFmtSDFIFOW(PFNRTSTROUTPUT pfnOutput, void *pvArgOutput,
4187 const char *pszType, void const *pvValue,
4188 int cchWidth, int cchPrecision, unsigned fFlags,
4189 void *pvUser)
4190{
4191 RT_NOREF(pszType, cchWidth, cchPrecision, fFlags, pvUser);
4192 uint32_t uSDFIFOW = (uint32_t)(uintptr_t)pvValue;
4193 return RTStrFormat(pfnOutput, pvArgOutput, NULL, 0, "SDFIFOW(raw: %#0x, sdfifow:%d B)", uSDFIFOW, hdaSDFIFOWToBytes(uSDFIFOW));
4194}
4195
4196/**
4197 * @callback_method_impl{FNRTSTRFORMATTYPE}
4198 */
4199static DECLCALLBACK(size_t) hdaDbgFmtSDSTS(PFNRTSTROUTPUT pfnOutput, void *pvArgOutput,
4200 const char *pszType, void const *pvValue,
4201 int cchWidth, int cchPrecision, unsigned fFlags,
4202 void *pvUser)
4203{
4204 RT_NOREF(pszType, cchWidth, cchPrecision, fFlags, pvUser);
4205 uint32_t uSdSts = (uint32_t)(uintptr_t)pvValue;
4206 return RTStrFormat(pfnOutput, pvArgOutput, NULL, 0,
4207 "SDSTS(raw:%#0x, fifordy:%RTbool, dese:%RTbool, fifoe:%RTbool, bcis:%RTbool)",
4208 uSdSts,
4209 RT_BOOL(uSdSts & HDA_SDSTS_FIFORDY),
4210 RT_BOOL(uSdSts & HDA_SDSTS_DESE),
4211 RT_BOOL(uSdSts & HDA_SDSTS_FIFOE),
4212 RT_BOOL(uSdSts & HDA_SDSTS_BCIS));
4213}
4214
4215static int hdaDbgLookupRegByName(const char *pszArgs)
4216{
4217 int iReg = 0;
4218 for (; iReg < HDA_NUM_REGS; ++iReg)
4219 if (!RTStrICmp(g_aHdaRegMap[iReg].abbrev, pszArgs))
4220 return iReg;
4221 return -1;
4222}
4223
4224
4225static void hdaDbgPrintRegister(PHDASTATE pThis, PCDBGFINFOHLP pHlp, int iHdaIndex)
4226{
4227 Assert( pThis
4228 && iHdaIndex >= 0
4229 && iHdaIndex < HDA_NUM_REGS);
4230 pHlp->pfnPrintf(pHlp, "%s: 0x%x\n", g_aHdaRegMap[iHdaIndex].abbrev, pThis->au32Regs[g_aHdaRegMap[iHdaIndex].mem_idx]);
4231}
4232
4233/**
4234 * @callback_method_impl{FNDBGFHANDLERDEV}
4235 */
4236static DECLCALLBACK(void) hdaDbgInfo(PPDMDEVINS pDevIns, PCDBGFINFOHLP pHlp, const char *pszArgs)
4237{
4238 PHDASTATE pThis = PDMINS_2_DATA(pDevIns, PHDASTATE);
4239 int iHdaRegisterIndex = hdaDbgLookupRegByName(pszArgs);
4240 if (iHdaRegisterIndex != -1)
4241 hdaDbgPrintRegister(pThis, pHlp, iHdaRegisterIndex);
4242 else
4243 {
4244 for(iHdaRegisterIndex = 0; (unsigned int)iHdaRegisterIndex < HDA_NUM_REGS; ++iHdaRegisterIndex)
4245 hdaDbgPrintRegister(pThis, pHlp, iHdaRegisterIndex);
4246 }
4247}
4248
4249static void hdaDbgPrintStream(PHDASTATE pThis, PCDBGFINFOHLP pHlp, int iIdx)
4250{
4251 Assert( pThis
4252 && iIdx >= 0
4253 && iIdx < HDA_MAX_STREAMS);
4254
4255 const PHDASTREAM pStream = &pThis->aStreams[iIdx];
4256
4257 pHlp->pfnPrintf(pHlp, "Stream #%d:\n", iIdx);
4258 pHlp->pfnPrintf(pHlp, "\tSD%dCTL : %R[sdctl]\n", iIdx, HDA_STREAM_REG(pThis, CTL, iIdx));
4259 pHlp->pfnPrintf(pHlp, "\tSD%dCTS : %R[sdsts]\n", iIdx, HDA_STREAM_REG(pThis, STS, iIdx));
4260 pHlp->pfnPrintf(pHlp, "\tSD%dFIFOS: %R[sdfifos]\n", iIdx, HDA_STREAM_REG(pThis, FIFOS, iIdx));
4261 pHlp->pfnPrintf(pHlp, "\tSD%dFIFOW: %R[sdfifow]\n", iIdx, HDA_STREAM_REG(pThis, FIFOW, iIdx));
4262 pHlp->pfnPrintf(pHlp, "\tBDLE : %R[bdle]\n", &pStream->State.BDLE);
4263}
4264
4265static void hdaDbgPrintBDLE(PHDASTATE pThis, PCDBGFINFOHLP pHlp, int iIdx)
4266{
4267 Assert( pThis
4268 && iIdx >= 0
4269 && iIdx < HDA_MAX_STREAMS);
4270
4271 const PHDASTREAM pStream = &pThis->aStreams[iIdx];
4272 const PHDABDLE pBDLE = &pStream->State.BDLE;
4273
4274 pHlp->pfnPrintf(pHlp, "Stream #%d BDLE:\n", iIdx);
4275
4276 uint64_t u64BaseDMA = RT_MAKE_U64(HDA_STREAM_REG(pThis, BDPL, iIdx),
4277 HDA_STREAM_REG(pThis, BDPU, iIdx));
4278 uint16_t u16LVI = HDA_STREAM_REG(pThis, LVI, iIdx);
4279 uint32_t u32CBL = HDA_STREAM_REG(pThis, CBL, iIdx);
4280
4281 if (!u64BaseDMA)
4282 return;
4283
4284 pHlp->pfnPrintf(pHlp, "\tCurrent: %R[bdle]\n\n", pBDLE);
4285
4286 pHlp->pfnPrintf(pHlp, "\tMemory:\n");
4287
4288 uint32_t cbBDLE = 0;
4289 for (uint16_t i = 0; i < u16LVI + 1; i++)
4290 {
4291 HDABDLEDESC bd;
4292 PDMDevHlpPhysRead(pThis->CTX_SUFF(pDevIns), u64BaseDMA + i * sizeof(HDABDLEDESC), &bd, sizeof(bd));
4293
4294 pHlp->pfnPrintf(pHlp, "\t\t%s #%03d BDLE(adr:0x%llx, size:%RU32, ioc:%RTbool)\n",
4295 pBDLE->State.u32BDLIndex == i ? "*" : " ", i, bd.u64BufAdr, bd.u32BufSize, bd.fFlags & HDA_BDLE_FLAG_IOC);
4296
4297 cbBDLE += bd.u32BufSize;
4298 }
4299
4300 pHlp->pfnPrintf(pHlp, "Total: %RU32 bytes\n", cbBDLE);
4301
4302 if (cbBDLE != u32CBL)
4303 pHlp->pfnPrintf(pHlp, "Warning: %RU32 bytes does not match CBL (%RU32)!\n", cbBDLE, u32CBL);
4304
4305 pHlp->pfnPrintf(pHlp, "DMA counters (base @ 0x%llx):\n", u64BaseDMA);
4306 if (!u64BaseDMA) /* No DMA base given? Bail out. */
4307 {
4308 pHlp->pfnPrintf(pHlp, "\tNo counters found\n");
4309 return;
4310 }
4311
4312 for (int i = 0; i < u16LVI + 1; i++)
4313 {
4314 uint32_t uDMACnt;
4315 PDMDevHlpPhysRead(pThis->CTX_SUFF(pDevIns), (pThis->u64DPBase & DPBASE_ADDR_MASK) + (i * 2 * sizeof(uint32_t)),
4316 &uDMACnt, sizeof(uDMACnt));
4317
4318 pHlp->pfnPrintf(pHlp, "\t#%03d DMA @ 0x%x\n", i , uDMACnt);
4319 }
4320}
4321
4322static int hdaDbgLookupStrmIdx(PHDASTATE pThis, const char *pszArgs)
4323{
4324 RT_NOREF(pThis, pszArgs);
4325 /** @todo Add args parsing. */
4326 return -1;
4327}
4328
4329/**
4330 * @callback_method_impl{FNDBGFHANDLERDEV}
4331 */
4332static DECLCALLBACK(void) hdaDbgInfoStream(PPDMDEVINS pDevIns, PCDBGFINFOHLP pHlp, const char *pszArgs)
4333{
4334 PHDASTATE pThis = PDMINS_2_DATA(pDevIns, PHDASTATE);
4335 int iHdaStreamdex = hdaDbgLookupStrmIdx(pThis, pszArgs);
4336 if (iHdaStreamdex != -1)
4337 hdaDbgPrintStream(pThis, pHlp, iHdaStreamdex);
4338 else
4339 for(iHdaStreamdex = 0; iHdaStreamdex < HDA_MAX_STREAMS; ++iHdaStreamdex)
4340 hdaDbgPrintStream(pThis, pHlp, iHdaStreamdex);
4341}
4342
4343/**
4344 * @callback_method_impl{FNDBGFHANDLERDEV}
4345 */
4346static DECLCALLBACK(void) hdaDbgInfoBDLE(PPDMDEVINS pDevIns, PCDBGFINFOHLP pHlp, const char *pszArgs)
4347{
4348 PHDASTATE pThis = PDMINS_2_DATA(pDevIns, PHDASTATE);
4349 int iHdaStreamdex = hdaDbgLookupStrmIdx(pThis, pszArgs);
4350 if (iHdaStreamdex != -1)
4351 hdaDbgPrintBDLE(pThis, pHlp, iHdaStreamdex);
4352 else
4353 for(iHdaStreamdex = 0; iHdaStreamdex < HDA_MAX_STREAMS; ++iHdaStreamdex)
4354 hdaDbgPrintBDLE(pThis, pHlp, iHdaStreamdex);
4355}
4356
4357/**
4358 * @callback_method_impl{FNDBGFHANDLERDEV}
4359 */
4360static DECLCALLBACK(void) hdaDbgInfoCodecNodes(PPDMDEVINS pDevIns, PCDBGFINFOHLP pHlp, const char *pszArgs)
4361{
4362 PHDASTATE pThis = PDMINS_2_DATA(pDevIns, PHDASTATE);
4363
4364 if (pThis->pCodec->pfnDbgListNodes)
4365 pThis->pCodec->pfnDbgListNodes(pThis->pCodec, pHlp, pszArgs);
4366 else
4367 pHlp->pfnPrintf(pHlp, "Codec implementation doesn't provide corresponding callback\n");
4368}
4369
4370/**
4371 * @callback_method_impl{FNDBGFHANDLERDEV}
4372 */
4373static DECLCALLBACK(void) hdaDbgInfoCodecSelector(PPDMDEVINS pDevIns, PCDBGFINFOHLP pHlp, const char *pszArgs)
4374{
4375 PHDASTATE pThis = PDMINS_2_DATA(pDevIns, PHDASTATE);
4376
4377 if (pThis->pCodec->pfnDbgSelector)
4378 pThis->pCodec->pfnDbgSelector(pThis->pCodec, pHlp, pszArgs);
4379 else
4380 pHlp->pfnPrintf(pHlp, "Codec implementation doesn't provide corresponding callback\n");
4381}
4382
4383/**
4384 * @callback_method_impl{FNDBGFHANDLERDEV}
4385 */
4386static DECLCALLBACK(void) hdaDbgInfoMixer(PPDMDEVINS pDevIns, PCDBGFINFOHLP pHlp, const char *pszArgs)
4387{
4388 PHDASTATE pThis = PDMINS_2_DATA(pDevIns, PHDASTATE);
4389
4390 if (pThis->pMixer)
4391 AudioMixerDebug(pThis->pMixer, pHlp, pszArgs);
4392 else
4393 pHlp->pfnPrintf(pHlp, "Mixer not available\n");
4394}
4395
4396
4397/* PDMIBASE */
4398
4399/**
4400 * @interface_method_impl{PDMIBASE,pfnQueryInterface}
4401 */
4402static DECLCALLBACK(void *) hdaQueryInterface(struct PDMIBASE *pInterface, const char *pszIID)
4403{
4404 PHDASTATE pThis = RT_FROM_MEMBER(pInterface, HDASTATE, IBase);
4405 Assert(&pThis->IBase == pInterface);
4406
4407 PDMIBASE_RETURN_INTERFACE(pszIID, PDMIBASE, &pThis->IBase);
4408 return NULL;
4409}
4410
4411
4412/* PDMDEVREG */
4413
4414
4415/**
4416 * @interface_method_impl{PDMDEVREG,pfnReset}
4417 */
4418static DECLCALLBACK(void) hdaReset(PPDMDEVINS pDevIns)
4419{
4420 PHDASTATE pThis = PDMINS_2_DATA(pDevIns, PHDASTATE);
4421
4422 LogFlowFuncEnter();
4423
4424 DEVHDA_LOCK_RETURN_VOID(pThis);
4425
4426 /*
4427 * 18.2.6,7 defines that values of this registers might be cleared on power on/reset
4428 * hdaReset shouldn't affects these registers.
4429 */
4430 HDA_REG(pThis, WAKEEN) = 0x0;
4431
4432 hdaGCTLReset(pThis);
4433
4434 /* Indicate that HDA is not in reset. The firmware is supposed to (un)reset HDA,
4435 * but we can take a shortcut.
4436 */
4437 HDA_REG(pThis, GCTL) = HDA_GCTL_CRST;
4438
4439 DEVHDA_UNLOCK(pThis);
4440}
4441
4442/**
4443 * @interface_method_impl{PDMDEVREG,pfnDestruct}
4444 */
4445static DECLCALLBACK(int) hdaDestruct(PPDMDEVINS pDevIns)
4446{
4447 PHDASTATE pThis = PDMINS_2_DATA(pDevIns, PHDASTATE);
4448
4449 DEVHDA_LOCK_RETURN(pThis, VINF_IOM_R3_MMIO_WRITE);
4450
4451 PHDADRIVER pDrv;
4452 while (!RTListIsEmpty(&pThis->lstDrv))
4453 {
4454 pDrv = RTListGetFirst(&pThis->lstDrv, HDADRIVER, Node);
4455
4456 RTListNodeRemove(&pDrv->Node);
4457 RTMemFree(pDrv);
4458 }
4459
4460 if (pThis->pCodec)
4461 {
4462 hdaCodecDestruct(pThis->pCodec);
4463
4464 RTMemFree(pThis->pCodec);
4465 pThis->pCodec = NULL;
4466 }
4467
4468 RTMemFree(pThis->pu32CorbBuf);
4469 pThis->pu32CorbBuf = NULL;
4470
4471 RTMemFree(pThis->pu64RirbBuf);
4472 pThis->pu64RirbBuf = NULL;
4473
4474 for (uint8_t i = 0; i < HDA_MAX_STREAMS; i++)
4475 hdaStreamDestroy(&pThis->aStreams[i]);
4476
4477 DEVHDA_UNLOCK(pThis);
4478
4479 return VINF_SUCCESS;
4480}
4481
4482
4483/**
4484 * Attach command, internal version.
4485 *
4486 * This is called to let the device attach to a driver for a specified LUN
4487 * during runtime. This is not called during VM construction, the device
4488 * constructor has to attach to all the available drivers.
4489 *
4490 * @returns VBox status code.
4491 * @param pThis HDA state.
4492 * @param uLUN The logical unit which is being detached.
4493 * @param fFlags Flags, combination of the PDMDEVATT_FLAGS_* \#defines.
4494 * @param ppDrv Attached driver instance on success. Optional.
4495 */
4496static int hdaAttachInternal(PHDASTATE pThis, unsigned uLUN, uint32_t fFlags, PHDADRIVER *ppDrv)
4497{
4498 RT_NOREF(fFlags);
4499
4500 /*
4501 * Attach driver.
4502 */
4503 char *pszDesc;
4504 if (RTStrAPrintf(&pszDesc, "Audio driver port (HDA) for LUN#%u", uLUN) <= 0)
4505 AssertLogRelFailedReturn(VERR_NO_MEMORY);
4506
4507 PPDMIBASE pDrvBase;
4508 int rc = PDMDevHlpDriverAttach(pThis->pDevInsR3, uLUN,
4509 &pThis->IBase, &pDrvBase, pszDesc);
4510 if (RT_SUCCESS(rc))
4511 {
4512 PHDADRIVER pDrv = (PHDADRIVER)RTMemAllocZ(sizeof(HDADRIVER));
4513 if (pDrv)
4514 {
4515 pDrv->pDrvBase = pDrvBase;
4516 pDrv->pConnector = PDMIBASE_QUERY_INTERFACE(pDrvBase, PDMIAUDIOCONNECTOR);
4517 AssertMsg(pDrv->pConnector != NULL, ("Configuration error: LUN#%u has no host audio interface, rc=%Rrc\n", uLUN, rc));
4518 pDrv->pHDAState = pThis;
4519 pDrv->uLUN = uLUN;
4520
4521 /*
4522 * For now we always set the driver at LUN 0 as our primary
4523 * host backend. This might change in the future.
4524 */
4525 if (pDrv->uLUN == 0)
4526 pDrv->fFlags |= PDMAUDIODRVFLAGS_PRIMARY;
4527
4528 LogFunc(("LUN#%u: pCon=%p, drvFlags=0x%x\n", uLUN, pDrv->pConnector, pDrv->fFlags));
4529
4530 /* Attach to driver list if not attached yet. */
4531 if (!pDrv->fAttached)
4532 {
4533 RTListAppend(&pThis->lstDrv, &pDrv->Node);
4534 pDrv->fAttached = true;
4535 }
4536
4537 if (ppDrv)
4538 *ppDrv = pDrv;
4539 }
4540 else
4541 rc = VERR_NO_MEMORY;
4542 }
4543 else if (rc == VERR_PDM_NO_ATTACHED_DRIVER)
4544 LogFunc(("No attached driver for LUN #%u\n", uLUN));
4545
4546 if (RT_FAILURE(rc))
4547 {
4548 /* Only free this string on failure;
4549 * must remain valid for the live of the driver instance. */
4550 RTStrFree(pszDesc);
4551 }
4552
4553 LogFunc(("uLUN=%u, fFlags=0x%x, rc=%Rrc\n", uLUN, fFlags, rc));
4554 return rc;
4555}
4556
4557/**
4558 * Detach command, internal version.
4559 *
4560 * This is called to let the device detach from a driver for a specified LUN
4561 * during runtime.
4562 *
4563 * @returns VBox status code.
4564 * @param pThis HDA state.
4565 * @param pDrv Driver to detach device from.
4566 * @param fFlags Flags, combination of the PDMDEVATT_FLAGS_* \#defines.
4567 */
4568static int hdaDetachInternal(PHDASTATE pThis, PHDADRIVER pDrv, uint32_t fFlags)
4569{
4570 RT_NOREF(fFlags);
4571
4572 AudioMixerSinkRemoveStream(pThis->SinkFront.pMixSink, pDrv->Front.pMixStrm);
4573 AudioMixerStreamDestroy(pDrv->Front.pMixStrm);
4574 pDrv->Front.pMixStrm = NULL;
4575
4576#ifdef VBOX_WITH_AUDIO_HDA_51_SURROUND
4577 AudioMixerSinkRemoveStream(pThis->SinkCenterLFE.pMixSink, pDrv->CenterLFE.pMixStrm);
4578 AudioMixerStreamDestroy(pDrv->CenterLFE.pMixStrm);
4579 pDrv->CenterLFE.pMixStrm = NULL;
4580
4581 AudioMixerSinkRemoveStream(pThis->SinkRear.pMixSink, pDrv->Rear.pMixStrm);
4582 AudioMixerStreamDestroy(pDrv->Rear.pMixStrm);
4583 pDrv->Rear.pMixStrm = NULL;
4584#endif
4585
4586 AudioMixerSinkRemoveStream(pThis->SinkLineIn.pMixSink, pDrv->LineIn.pMixStrm);
4587 AudioMixerStreamDestroy(pDrv->LineIn.pMixStrm);
4588 pDrv->LineIn.pMixStrm = NULL;
4589
4590#ifdef VBOX_WITH_AUDIO_HDA_MIC_IN
4591 AudioMixerSinkRemoveStream(pThis->SinkMicIn.pMixSink, pDrv->MicIn.pMixStrm);
4592 AudioMixerStreamDestroy(pDrv->MicIn.pMixStrm);
4593 pDrv->MicIn.pMixStrm = NULL;
4594#endif
4595
4596 RTListNodeRemove(&pDrv->Node);
4597
4598 LogFunc(("uLUN=%u, fFlags=0x%x\n", pDrv->uLUN, fFlags));
4599 return VINF_SUCCESS;
4600}
4601
4602/**
4603 * @interface_method_impl{PDMDEVREG,pfnAttach}
4604 */
4605static DECLCALLBACK(int) hdaAttach(PPDMDEVINS pDevIns, unsigned uLUN, uint32_t fFlags)
4606{
4607 PHDASTATE pThis = PDMINS_2_DATA(pDevIns, PHDASTATE);
4608
4609 DEVHDA_LOCK_RETURN(pThis, VINF_IOM_R3_MMIO_WRITE);
4610
4611 PHDADRIVER pDrv;
4612 int rc2 = hdaAttachInternal(pThis, uLUN, fFlags, &pDrv);
4613 if (RT_SUCCESS(rc2))
4614 {
4615 PHDASTREAM pStream = hdaGetStreamFromSink(pThis, &pThis->SinkFront);
4616 if (DrvAudioHlpStreamCfgIsValid(&pStream->State.Cfg))
4617 hdaMixerAddDrvStream(pThis, pThis->SinkFront.pMixSink, &pStream->State.Cfg, pDrv);
4618
4619#ifdef VBOX_WITH_AUDIO_HDA_51_SURROUND
4620 pStream = hdaGetStreamFromSink(pThis, &pThis->SinkCenterLFE);
4621 if (DrvAudioHlpStreamCfgIsValid(&pStream->State.Cfg))
4622 hdaMixerAddDrvStream(pThis, pThis->SinkCenterLFE.pMixSink, &pStream->State.Cfg, pDrv);
4623
4624 pStream = hdaGetStreamFromSink(pThis, &pThis->SinkRear);
4625 if (DrvAudioHlpStreamCfgIsValid(&pStream->State.Cfg))
4626 hdaMixerAddDrvStream(pThis, pThis->SinkRear.pMixSink, &pStream->State.Cfg, pDrv);
4627#endif
4628 pStream = hdaGetStreamFromSink(pThis, &pThis->SinkLineIn);
4629 if (DrvAudioHlpStreamCfgIsValid(&pStream->State.Cfg))
4630 hdaMixerAddDrvStream(pThis, pThis->SinkLineIn.pMixSink, &pStream->State.Cfg, pDrv);
4631
4632#ifdef VBOX_WITH_AUDIO_HDA_MIC_IN
4633 pStream = hdaGetStreamFromSink(pThis, &pThis->SinkMicIn);
4634 if (DrvAudioHlpStreamCfgIsValid(&pStream->State.Cfg))
4635 hdaMixerAddDrvStream(pThis, pThis->SinkMicIn.pMixSink, &pStream->State.Cfg, pDrv);
4636#endif
4637 }
4638
4639 DEVHDA_UNLOCK(pThis);
4640
4641 return VINF_SUCCESS;
4642}
4643
4644/**
4645 * @interface_method_impl{PDMDEVREG,pfnDetach}
4646 */
4647static DECLCALLBACK(void) hdaDetach(PPDMDEVINS pDevIns, unsigned uLUN, uint32_t fFlags)
4648{
4649 PHDASTATE pThis = PDMINS_2_DATA(pDevIns, PHDASTATE);
4650
4651 LogFunc(("uLUN=%u, fFlags=0x%x\n", uLUN, fFlags));
4652
4653 DEVHDA_LOCK(pThis);
4654
4655 PHDADRIVER pDrv, pDrvNext;
4656 RTListForEachSafe(&pThis->lstDrv, pDrv, pDrvNext, HDADRIVER, Node)
4657 {
4658 if (pDrv->uLUN == uLUN)
4659 {
4660 int rc2 = hdaDetachInternal(pThis, pDrv, fFlags);
4661 if (RT_SUCCESS(rc2))
4662 {
4663 RTMemFree(pDrv);
4664 pDrv = NULL;
4665 }
4666
4667 break;
4668 }
4669 }
4670
4671 DEVHDA_UNLOCK(pThis);
4672}
4673
4674/**
4675 * Re-attaches (replaces) a driver with a new driver.
4676 *
4677 * @returns VBox status code.
4678 * @param pThis Device instance to re-attach driver to.
4679 * @param pDrv Driver instance used for attaching to.
4680 * If NULL is specified, a new driver will be created and appended
4681 * to the driver list.
4682 * @param uLUN The logical unit which is being re-detached.
4683 * @param pszDriver New driver name to attach.
4684 */
4685static int hdaReattachInternal(PHDASTATE pThis, PHDADRIVER pDrv, uint8_t uLUN, const char *pszDriver)
4686{
4687 AssertPtrReturn(pThis, VERR_INVALID_POINTER);
4688 AssertPtrReturn(pszDriver, VERR_INVALID_POINTER);
4689
4690 int rc;
4691
4692 if (pDrv)
4693 {
4694 rc = hdaDetachInternal(pThis, pDrv, 0 /* fFlags */);
4695 if (RT_SUCCESS(rc))
4696 rc = PDMDevHlpDriverDetach(pThis->pDevInsR3, PDMIBASE_2_PDMDRV(pDrv->pDrvBase), 0 /* fFlags */);
4697
4698 if (RT_FAILURE(rc))
4699 return rc;
4700
4701 pDrv = NULL;
4702 }
4703
4704 PVM pVM = PDMDevHlpGetVM(pThis->pDevInsR3);
4705 PCFGMNODE pRoot = CFGMR3GetRoot(pVM);
4706 PCFGMNODE pDev0 = CFGMR3GetChild(pRoot, "Devices/hda/0/");
4707
4708 /* Remove LUN branch. */
4709 CFGMR3RemoveNode(CFGMR3GetChildF(pDev0, "LUN#%u/", uLUN));
4710
4711#define RC_CHECK() if (RT_FAILURE(rc)) { AssertReleaseRC(rc); break; }
4712
4713 do
4714 {
4715 PCFGMNODE pLunL0;
4716 rc = CFGMR3InsertNodeF(pDev0, &pLunL0, "LUN#%u/", uLUN); RC_CHECK();
4717 rc = CFGMR3InsertString(pLunL0, "Driver", "AUDIO"); RC_CHECK();
4718 rc = CFGMR3InsertNode(pLunL0, "Config/", NULL); RC_CHECK();
4719
4720 PCFGMNODE pLunL1, pLunL2;
4721 rc = CFGMR3InsertNode (pLunL0, "AttachedDriver/", &pLunL1); RC_CHECK();
4722 rc = CFGMR3InsertNode (pLunL1, "Config/", &pLunL2); RC_CHECK();
4723 rc = CFGMR3InsertString(pLunL1, "Driver", pszDriver); RC_CHECK();
4724
4725 rc = CFGMR3InsertString(pLunL2, "AudioDriver", pszDriver); RC_CHECK();
4726
4727 } while (0);
4728
4729 if (RT_SUCCESS(rc))
4730 rc = hdaAttachInternal(pThis, uLUN, 0 /* fFlags */, NULL /* ppDrv */);
4731
4732 LogFunc(("pThis=%p, uLUN=%u, pszDriver=%s, rc=%Rrc\n", pThis, uLUN, pszDriver, rc));
4733
4734#undef RC_CHECK
4735
4736 return rc;
4737}
4738
4739/**
4740 * Powers off the device.
4741 *
4742 * @param pDevIns Device instance to power off.
4743 */
4744static DECLCALLBACK(void) hdaPowerOff(PPDMDEVINS pDevIns)
4745{
4746 PHDASTATE pThis = PDMINS_2_DATA(pDevIns, PHDASTATE);
4747
4748 DEVHDA_LOCK_RETURN_VOID(pThis);
4749
4750 LogRel2(("HDA: Powering off ...\n"));
4751
4752 /* Ditto goes for the codec, which in turn uses the mixer. */
4753 hdaCodecPowerOff(pThis->pCodec);
4754
4755 /**
4756 * Note: Destroy the mixer while powering off and *not* in hdaDestruct,
4757 * giving the mixer the chance to release any references held to
4758 * PDM audio streams it maintains.
4759 */
4760 if (pThis->pMixer)
4761 {
4762 AudioMixerDestroy(pThis->pMixer);
4763 pThis->pMixer = NULL;
4764 }
4765
4766 DEVHDA_UNLOCK(pThis);
4767}
4768
4769/**
4770 * @interface_method_impl{PDMDEVREG,pfnConstruct}
4771 */
4772static DECLCALLBACK(int) hdaConstruct(PPDMDEVINS pDevIns, int iInstance, PCFGMNODE pCfg)
4773{
4774 RT_NOREF(iInstance);
4775 PDMDEV_CHECK_VERSIONS_RETURN(pDevIns);
4776 PHDASTATE pThis = PDMINS_2_DATA(pDevIns, PHDASTATE);
4777 Assert(iInstance == 0);
4778
4779 /*
4780 * Validations.
4781 */
4782 if (!CFGMR3AreValuesValid(pCfg, "R0Enabled\0"
4783 "RCEnabled\0"
4784 "TimerHz\0"
4785 "PosAdjustEnabled\0"
4786 "PosAdjustFrames\0"
4787 "DebugEnabled\0"
4788 "DebugPathOut\0"))
4789 {
4790 return PDMDEV_SET_ERROR(pDevIns, VERR_PDM_DEVINS_UNKNOWN_CFG_VALUES,
4791 N_ ("Invalid configuration for the Intel HDA device"));
4792 }
4793
4794 int rc = CFGMR3QueryBoolDef(pCfg, "RCEnabled", &pThis->fRCEnabled, false);
4795 if (RT_FAILURE(rc))
4796 return PDMDEV_SET_ERROR(pDevIns, rc,
4797 N_("HDA configuration error: failed to read RCEnabled as boolean"));
4798 rc = CFGMR3QueryBoolDef(pCfg, "R0Enabled", &pThis->fR0Enabled, false);
4799 if (RT_FAILURE(rc))
4800 return PDMDEV_SET_ERROR(pDevIns, rc,
4801 N_("HDA configuration error: failed to read R0Enabled as boolean"));
4802
4803 rc = CFGMR3QueryU16Def(pCfg, "TimerHz", &pThis->u16TimerHz, HDA_TIMER_HZ_DEFAULT /* Default value, if not set. */);
4804 if (RT_FAILURE(rc))
4805 return PDMDEV_SET_ERROR(pDevIns, rc,
4806 N_("HDA configuration error: failed to read Hertz (Hz) rate as unsigned integer"));
4807
4808 if (pThis->u16TimerHz != HDA_TIMER_HZ_DEFAULT)
4809 LogRel(("HDA: Using custom device timer rate (%RU16Hz)\n", pThis->u16TimerHz));
4810
4811 rc = CFGMR3QueryBoolDef(pCfg, "PosAdjustEnabled", &pThis->fPosAdjustEnabled, true);
4812 if (RT_FAILURE(rc))
4813 return PDMDEV_SET_ERROR(pDevIns, rc,
4814 N_("HDA configuration error: failed to read position adjustment enabled as boolean"));
4815
4816 if (!pThis->fPosAdjustEnabled)
4817 LogRel(("HDA: Position adjustment is disabled\n"));
4818
4819 rc = CFGMR3QueryU16Def(pCfg, "PosAdjustFrames", &pThis->cPosAdjustFrames, HDA_POS_ADJUST_DEFAULT);
4820 if (RT_FAILURE(rc))
4821 return PDMDEV_SET_ERROR(pDevIns, rc,
4822 N_("HDA configuration error: failed to read position adjustment frames as unsigned integer"));
4823
4824 if (pThis->cPosAdjustFrames)
4825 LogRel(("HDA: Using custom position adjustment (%RU16 audio frames)\n", pThis->cPosAdjustFrames));
4826
4827 rc = CFGMR3QueryBoolDef(pCfg, "DebugEnabled", &pThis->Dbg.fEnabled, false);
4828 if (RT_FAILURE(rc))
4829 return PDMDEV_SET_ERROR(pDevIns, rc,
4830 N_("HDA configuration error: failed to read debugging enabled flag as boolean"));
4831
4832 rc = CFGMR3QueryStringDef(pCfg, "DebugPathOut", pThis->Dbg.szOutPath, sizeof(pThis->Dbg.szOutPath),
4833 VBOX_AUDIO_DEBUG_DUMP_PCM_DATA_PATH);
4834 if (RT_FAILURE(rc))
4835 return PDMDEV_SET_ERROR(pDevIns, rc,
4836 N_("HDA configuration error: failed to read debugging output path flag as string"));
4837
4838 if (!strlen(pThis->Dbg.szOutPath))
4839 RTStrPrintf(pThis->Dbg.szOutPath, sizeof(pThis->Dbg.szOutPath), VBOX_AUDIO_DEBUG_DUMP_PCM_DATA_PATH);
4840
4841 if (pThis->Dbg.fEnabled)
4842 LogRel2(("HDA: Debug output will be saved to '%s'\n", pThis->Dbg.szOutPath));
4843
4844 /*
4845 * Use an own critical section for the device instead of the default
4846 * one provided by PDM. This allows fine-grained locking in combination
4847 * with TM when timer-specific stuff is being called in e.g. the MMIO handlers.
4848 */
4849 rc = PDMDevHlpCritSectInit(pDevIns, &pThis->CritSect, RT_SRC_POS, "HDA");
4850 AssertRCReturn(rc, rc);
4851
4852 rc = PDMDevHlpSetDeviceCritSect(pDevIns, PDMDevHlpCritSectGetNop(pDevIns));
4853 AssertRCReturn(rc, rc);
4854
4855 /*
4856 * Initialize data (most of it anyway).
4857 */
4858 pThis->pDevInsR3 = pDevIns;
4859 pThis->pDevInsR0 = PDMDEVINS_2_R0PTR(pDevIns);
4860 pThis->pDevInsRC = PDMDEVINS_2_RCPTR(pDevIns);
4861 /* IBase */
4862 pThis->IBase.pfnQueryInterface = hdaQueryInterface;
4863
4864 /* PCI Device */
4865 PCIDevSetVendorId (&pThis->PciDev, HDA_PCI_VENDOR_ID); /* nVidia */
4866 PCIDevSetDeviceId (&pThis->PciDev, HDA_PCI_DEVICE_ID); /* HDA */
4867
4868 PCIDevSetCommand (&pThis->PciDev, 0x0000); /* 04 rw,ro - pcicmd. */
4869 PCIDevSetStatus (&pThis->PciDev, VBOX_PCI_STATUS_CAP_LIST); /* 06 rwc?,ro? - pcists. */
4870 PCIDevSetRevisionId (&pThis->PciDev, 0x01); /* 08 ro - rid. */
4871 PCIDevSetClassProg (&pThis->PciDev, 0x00); /* 09 ro - pi. */
4872 PCIDevSetClassSub (&pThis->PciDev, 0x03); /* 0a ro - scc; 03 == HDA. */
4873 PCIDevSetClassBase (&pThis->PciDev, 0x04); /* 0b ro - bcc; 04 == multimedia. */
4874 PCIDevSetHeaderType (&pThis->PciDev, 0x00); /* 0e ro - headtyp. */
4875 PCIDevSetBaseAddress (&pThis->PciDev, 0, /* 10 rw - MMIO */
4876 false /* fIoSpace */, false /* fPrefetchable */, true /* f64Bit */, 0x00000000);
4877 PCIDevSetInterruptLine (&pThis->PciDev, 0x00); /* 3c rw. */
4878 PCIDevSetInterruptPin (&pThis->PciDev, 0x01); /* 3d ro - INTA#. */
4879
4880#if defined(HDA_AS_PCI_EXPRESS)
4881 PCIDevSetCapabilityList (&pThis->PciDev, 0x80);
4882#elif defined(VBOX_WITH_MSI_DEVICES)
4883 PCIDevSetCapabilityList (&pThis->PciDev, 0x60);
4884#else
4885 PCIDevSetCapabilityList (&pThis->PciDev, 0x50); /* ICH6 datasheet 18.1.16 */
4886#endif
4887
4888 /// @todo r=michaln: If there are really no PCIDevSetXx for these, the meaning
4889 /// of these values needs to be properly documented!
4890 /* HDCTL off 0x40 bit 0 selects signaling mode (1-HDA, 0 - Ac97) 18.1.19 */
4891 PCIDevSetByte(&pThis->PciDev, 0x40, 0x01);
4892
4893 /* Power Management */
4894 PCIDevSetByte(&pThis->PciDev, 0x50 + 0, VBOX_PCI_CAP_ID_PM);
4895 PCIDevSetByte(&pThis->PciDev, 0x50 + 1, 0x0); /* next */
4896 PCIDevSetWord(&pThis->PciDev, 0x50 + 2, VBOX_PCI_PM_CAP_DSI | 0x02 /* version, PM1.1 */ );
4897
4898#ifdef HDA_AS_PCI_EXPRESS
4899 /* PCI Express */
4900 PCIDevSetByte(&pThis->PciDev, 0x80 + 0, VBOX_PCI_CAP_ID_EXP); /* PCI_Express */
4901 PCIDevSetByte(&pThis->PciDev, 0x80 + 1, 0x60); /* next */
4902 /* Device flags */
4903 PCIDevSetWord(&pThis->PciDev, 0x80 + 2,
4904 /* version */ 0x1 |
4905 /* Root Complex Integrated Endpoint */ (VBOX_PCI_EXP_TYPE_ROOT_INT_EP << 4) |
4906 /* MSI */ (100) << 9 );
4907 /* Device capabilities */
4908 PCIDevSetDWord(&pThis->PciDev, 0x80 + 4, VBOX_PCI_EXP_DEVCAP_FLRESET);
4909 /* Device control */
4910 PCIDevSetWord( &pThis->PciDev, 0x80 + 8, 0);
4911 /* Device status */
4912 PCIDevSetWord( &pThis->PciDev, 0x80 + 10, 0);
4913 /* Link caps */
4914 PCIDevSetDWord(&pThis->PciDev, 0x80 + 12, 0);
4915 /* Link control */
4916 PCIDevSetWord( &pThis->PciDev, 0x80 + 16, 0);
4917 /* Link status */
4918 PCIDevSetWord( &pThis->PciDev, 0x80 + 18, 0);
4919 /* Slot capabilities */
4920 PCIDevSetDWord(&pThis->PciDev, 0x80 + 20, 0);
4921 /* Slot control */
4922 PCIDevSetWord( &pThis->PciDev, 0x80 + 24, 0);
4923 /* Slot status */
4924 PCIDevSetWord( &pThis->PciDev, 0x80 + 26, 0);
4925 /* Root control */
4926 PCIDevSetWord( &pThis->PciDev, 0x80 + 28, 0);
4927 /* Root capabilities */
4928 PCIDevSetWord( &pThis->PciDev, 0x80 + 30, 0);
4929 /* Root status */
4930 PCIDevSetDWord(&pThis->PciDev, 0x80 + 32, 0);
4931 /* Device capabilities 2 */
4932 PCIDevSetDWord(&pThis->PciDev, 0x80 + 36, 0);
4933 /* Device control 2 */
4934 PCIDevSetQWord(&pThis->PciDev, 0x80 + 40, 0);
4935 /* Link control 2 */
4936 PCIDevSetQWord(&pThis->PciDev, 0x80 + 48, 0);
4937 /* Slot control 2 */
4938 PCIDevSetWord( &pThis->PciDev, 0x80 + 56, 0);
4939#endif
4940
4941 /*
4942 * Register the PCI device.
4943 */
4944 rc = PDMDevHlpPCIRegister(pDevIns, &pThis->PciDev);
4945 if (RT_FAILURE(rc))
4946 return rc;
4947
4948 rc = PDMDevHlpPCIIORegionRegister(pDevIns, 0, 0x4000, PCI_ADDRESS_SPACE_MEM, hdaPciIoRegionMap);
4949 if (RT_FAILURE(rc))
4950 return rc;
4951
4952#ifdef VBOX_WITH_MSI_DEVICES
4953 PDMMSIREG MsiReg;
4954 RT_ZERO(MsiReg);
4955 MsiReg.cMsiVectors = 1;
4956 MsiReg.iMsiCapOffset = 0x60;
4957 MsiReg.iMsiNextOffset = 0x50;
4958 rc = PDMDevHlpPCIRegisterMsi(pDevIns, &MsiReg);
4959 if (RT_FAILURE(rc))
4960 {
4961 /* That's OK, we can work without MSI */
4962 PCIDevSetCapabilityList(&pThis->PciDev, 0x50);
4963 }
4964#endif
4965
4966 rc = PDMDevHlpSSMRegister(pDevIns, HDA_SSM_VERSION, sizeof(*pThis), hdaSaveExec, hdaLoadExec);
4967 if (RT_FAILURE(rc))
4968 return rc;
4969
4970 RTListInit(&pThis->lstDrv);
4971
4972#ifdef VBOX_WITH_AUDIO_HDA_ASYNC_IO
4973 LogRel(("HDA: Asynchronous I/O enabled\n"));
4974#endif
4975
4976 uint8_t uLUN;
4977 for (uLUN = 0; uLUN < UINT8_MAX; ++uLUN)
4978 {
4979 LogFunc(("Trying to attach driver for LUN #%RU32 ...\n", uLUN));
4980 rc = hdaAttachInternal(pThis, uLUN, 0 /* fFlags */, NULL /* ppDrv */);
4981 if (RT_FAILURE(rc))
4982 {
4983 if (rc == VERR_PDM_NO_ATTACHED_DRIVER)
4984 rc = VINF_SUCCESS;
4985 else if (rc == VERR_AUDIO_BACKEND_INIT_FAILED)
4986 {
4987 hdaReattachInternal(pThis, NULL /* pDrv */, uLUN, "NullAudio");
4988 PDMDevHlpVMSetRuntimeError(pDevIns, 0 /*fFlags*/, "HostAudioNotResponding",
4989 N_("Host audio backend initialization has failed. Selecting the NULL audio backend "
4990 "with the consequence that no sound is audible"));
4991 /* Attaching to the NULL audio backend will never fail. */
4992 rc = VINF_SUCCESS;
4993 }
4994 break;
4995 }
4996 }
4997
4998 LogFunc(("cLUNs=%RU8, rc=%Rrc\n", uLUN, rc));
4999
5000 if (RT_SUCCESS(rc))
5001 {
5002 rc = AudioMixerCreate("HDA Mixer", 0 /* uFlags */, &pThis->pMixer);
5003 if (RT_SUCCESS(rc))
5004 {
5005 /*
5006 * Add mixer output sinks.
5007 */
5008#ifdef VBOX_WITH_AUDIO_HDA_51_SURROUND
5009 rc = AudioMixerCreateSink(pThis->pMixer, "[Playback] Front",
5010 AUDMIXSINKDIR_OUTPUT, &pThis->SinkFront.pMixSink);
5011 AssertRC(rc);
5012 rc = AudioMixerCreateSink(pThis->pMixer, "[Playback] Center / Subwoofer",
5013 AUDMIXSINKDIR_OUTPUT, &pThis->SinkCenterLFE.pMixSink);
5014 AssertRC(rc);
5015 rc = AudioMixerCreateSink(pThis->pMixer, "[Playback] Rear",
5016 AUDMIXSINKDIR_OUTPUT, &pThis->SinkRear.pMixSink);
5017 AssertRC(rc);
5018#else
5019 rc = AudioMixerCreateSink(pThis->pMixer, "[Playback] PCM Output",
5020 AUDMIXSINKDIR_OUTPUT, &pThis->SinkFront.pMixSink);
5021 AssertRC(rc);
5022#endif
5023 /*
5024 * Add mixer input sinks.
5025 */
5026 rc = AudioMixerCreateSink(pThis->pMixer, "[Recording] Line In",
5027 AUDMIXSINKDIR_INPUT, &pThis->SinkLineIn.pMixSink);
5028 AssertRC(rc);
5029#ifdef VBOX_WITH_AUDIO_HDA_MIC_IN
5030 rc = AudioMixerCreateSink(pThis->pMixer, "[Recording] Microphone In",
5031 AUDMIXSINKDIR_INPUT, &pThis->SinkMicIn.pMixSink);
5032 AssertRC(rc);
5033#endif
5034 /* There is no master volume control. Set the master to max. */
5035 PDMAUDIOVOLUME vol = { false, 255, 255 };
5036 rc = AudioMixerSetMasterVolume(pThis->pMixer, &vol);
5037 AssertRC(rc);
5038 }
5039 }
5040
5041 if (RT_SUCCESS(rc))
5042 {
5043 /* Construct codec. */
5044 pThis->pCodec = (PHDACODEC)RTMemAllocZ(sizeof(HDACODEC));
5045 if (!pThis->pCodec)
5046 return PDMDEV_SET_ERROR(pDevIns, VERR_NO_MEMORY, N_("Out of memory allocating HDA codec state"));
5047
5048 /* Set codec callbacks to this controller. */
5049 pThis->pCodec->pfnCbMixerAddStream = hdaMixerAddStream;
5050 pThis->pCodec->pfnCbMixerRemoveStream = hdaMixerRemoveStream;
5051 pThis->pCodec->pfnCbMixerControl = hdaMixerControl;
5052 pThis->pCodec->pfnCbMixerSetVolume = hdaMixerSetVolume;
5053
5054 pThis->pCodec->pHDAState = pThis; /* Assign HDA controller state to codec. */
5055
5056 /* Construct the codec. */
5057 rc = hdaCodecConstruct(pDevIns, pThis->pCodec, 0 /* Codec index */, pCfg);
5058 if (RT_FAILURE(rc))
5059 AssertRCReturn(rc, rc);
5060
5061 /* ICH6 datasheet defines 0 values for SVID and SID (18.1.14-15), which together with values returned for
5062 verb F20 should provide device/codec recognition. */
5063 Assert(pThis->pCodec->u16VendorId);
5064 Assert(pThis->pCodec->u16DeviceId);
5065 PCIDevSetSubSystemVendorId(&pThis->PciDev, pThis->pCodec->u16VendorId); /* 2c ro - intel.) */
5066 PCIDevSetSubSystemId( &pThis->PciDev, pThis->pCodec->u16DeviceId); /* 2e ro. */
5067 }
5068
5069 if (RT_SUCCESS(rc))
5070 {
5071 /*
5072 * Create all hardware streams.
5073 */
5074 for (uint8_t i = 0; i < HDA_MAX_STREAMS; ++i)
5075 {
5076 rc = hdaStreamCreate(&pThis->aStreams[i], pThis, i /* u8SD */);
5077 AssertRC(rc);
5078 }
5079
5080#ifdef VBOX_WITH_AUDIO_HDA_ONETIME_INIT
5081 /*
5082 * Initialize the driver chain.
5083 */
5084 PHDADRIVER pDrv;
5085 RTListForEach(&pThis->lstDrv, pDrv, HDADRIVER, Node)
5086 {
5087 /*
5088 * Only primary drivers are critical for the VM to run. Everything else
5089 * might not worth showing an own error message box in the GUI.
5090 */
5091 if (!(pDrv->fFlags & PDMAUDIODRVFLAGS_PRIMARY))
5092 continue;
5093
5094 PPDMIAUDIOCONNECTOR pCon = pDrv->pConnector;
5095 AssertPtr(pCon);
5096
5097 bool fValidLineIn = AudioMixerStreamIsValid(pDrv->LineIn.pMixStrm);
5098# ifdef VBOX_WITH_AUDIO_HDA_MIC_IN
5099 bool fValidMicIn = AudioMixerStreamIsValid(pDrv->MicIn.pMixStrm);
5100# endif
5101 bool fValidOut = AudioMixerStreamIsValid(pDrv->Front.pMixStrm);
5102# ifdef VBOX_WITH_AUDIO_HDA_51_SURROUND
5103 /** @todo Anything to do here? */
5104# endif
5105
5106 if ( !fValidLineIn
5107# ifdef VBOX_WITH_AUDIO_HDA_MIC_IN
5108 && !fValidMicIn
5109# endif
5110 && !fValidOut)
5111 {
5112 LogRel(("HDA: Falling back to NULL backend (no sound audible)\n"));
5113
5114 hdaReset(pDevIns);
5115 hdaReattachInternal(pThis, pDrv, pDrv->uLUN, "NullAudio");
5116
5117 PDMDevHlpVMSetRuntimeError(pDevIns, 0 /*fFlags*/, "HostAudioNotResponding",
5118 N_("No audio devices could be opened. Selecting the NULL audio backend "
5119 "with the consequence that no sound is audible"));
5120 }
5121 else
5122 {
5123 bool fWarn = false;
5124
5125 PDMAUDIOBACKENDCFG backendCfg;
5126 int rc2 = pCon->pfnGetConfig(pCon, &backendCfg);
5127 if (RT_SUCCESS(rc2))
5128 {
5129 if (backendCfg.cMaxStreamsIn)
5130 {
5131# ifdef VBOX_WITH_AUDIO_HDA_MIC_IN
5132 /* If the audio backend supports two or more input streams at once,
5133 * warn if one of our two inputs (microphone-in and line-in) failed to initialize. */
5134 if (backendCfg.cMaxStreamsIn >= 2)
5135 fWarn = !fValidLineIn || !fValidMicIn;
5136 /* If the audio backend only supports one input stream at once (e.g. pure ALSA, and
5137 * *not* ALSA via PulseAudio plugin!), only warn if both of our inputs failed to initialize.
5138 * One of the two simply is not in use then. */
5139 else if (backendCfg.cMaxStreamsIn == 1)
5140 fWarn = !fValidLineIn && !fValidMicIn;
5141 /* Don't warn if our backend is not able of supporting any input streams at all. */
5142# else /* !VBOX_WITH_AUDIO_HDA_MIC_IN */
5143 /* We only have line-in as input source. */
5144 fWarn = !fValidLineIn;
5145# endif /* VBOX_WITH_AUDIO_HDA_MIC_IN */
5146 }
5147
5148 if ( !fWarn
5149 && backendCfg.cMaxStreamsOut)
5150 {
5151 fWarn = !fValidOut;
5152 }
5153 }
5154 else
5155 {
5156 LogRel(("HDA: Unable to retrieve audio backend configuration for LUN #%RU8, rc=%Rrc\n", pDrv->uLUN, rc2));
5157 fWarn = true;
5158 }
5159
5160 if (fWarn)
5161 {
5162 char szMissingStreams[255];
5163 size_t len = 0;
5164 if (!fValidLineIn)
5165 {
5166 LogRel(("HDA: WARNING: Unable to open PCM line input for LUN #%RU8!\n", pDrv->uLUN));
5167 len = RTStrPrintf(szMissingStreams, sizeof(szMissingStreams), "PCM Input");
5168 }
5169# ifdef VBOX_WITH_AUDIO_HDA_MIC_IN
5170 if (!fValidMicIn)
5171 {
5172 LogRel(("HDA: WARNING: Unable to open PCM microphone input for LUN #%RU8!\n", pDrv->uLUN));
5173 len += RTStrPrintf(szMissingStreams + len,
5174 sizeof(szMissingStreams) - len, len ? ", PCM Microphone" : "PCM Microphone");
5175 }
5176# endif /* VBOX_WITH_AUDIO_HDA_MIC_IN */
5177 if (!fValidOut)
5178 {
5179 LogRel(("HDA: WARNING: Unable to open PCM output for LUN #%RU8!\n", pDrv->uLUN));
5180 len += RTStrPrintf(szMissingStreams + len,
5181 sizeof(szMissingStreams) - len, len ? ", PCM Output" : "PCM Output");
5182 }
5183
5184 PDMDevHlpVMSetRuntimeError(pDevIns, 0 /*fFlags*/, "HostAudioNotResponding",
5185 N_("Some HDA audio streams (%s) could not be opened. Guest applications generating audio "
5186 "output or depending on audio input may hang. Make sure your host audio device "
5187 "is working properly. Check the logfile for error messages of the audio "
5188 "subsystem"), szMissingStreams);
5189 }
5190 }
5191 }
5192#endif /* VBOX_WITH_AUDIO_HDA_ONETIME_INIT */
5193 }
5194
5195 if (RT_SUCCESS(rc))
5196 {
5197 hdaReset(pDevIns);
5198
5199 /*
5200 * Debug and string formatter types.
5201 */
5202 PDMDevHlpDBGFInfoRegister(pDevIns, "hda", "HDA info. (hda [register case-insensitive])", hdaDbgInfo);
5203 PDMDevHlpDBGFInfoRegister(pDevIns, "hdabdle", "HDA stream BDLE info. (hdabdle [stream number])", hdaDbgInfoBDLE);
5204 PDMDevHlpDBGFInfoRegister(pDevIns, "hdastream", "HDA stream info. (hdastream [stream number])", hdaDbgInfoStream);
5205 PDMDevHlpDBGFInfoRegister(pDevIns, "hdcnodes", "HDA codec nodes.", hdaDbgInfoCodecNodes);
5206 PDMDevHlpDBGFInfoRegister(pDevIns, "hdcselector", "HDA codec's selector states [node number].", hdaDbgInfoCodecSelector);
5207 PDMDevHlpDBGFInfoRegister(pDevIns, "hdamixer", "HDA mixer state.", hdaDbgInfoMixer);
5208
5209 rc = RTStrFormatTypeRegister("bdle", hdaDbgFmtBDLE, NULL);
5210 AssertRC(rc);
5211 rc = RTStrFormatTypeRegister("sdctl", hdaDbgFmtSDCTL, NULL);
5212 AssertRC(rc);
5213 rc = RTStrFormatTypeRegister("sdsts", hdaDbgFmtSDSTS, NULL);
5214 AssertRC(rc);
5215 rc = RTStrFormatTypeRegister("sdfifos", hdaDbgFmtSDFIFOS, NULL);
5216 AssertRC(rc);
5217 rc = RTStrFormatTypeRegister("sdfifow", hdaDbgFmtSDFIFOW, NULL);
5218 AssertRC(rc);
5219
5220 /*
5221 * Some debug assertions.
5222 */
5223 for (unsigned i = 0; i < RT_ELEMENTS(g_aHdaRegMap); i++)
5224 {
5225 struct HDAREGDESC const *pReg = &g_aHdaRegMap[i];
5226 struct HDAREGDESC const *pNextReg = i + 1 < RT_ELEMENTS(g_aHdaRegMap) ? &g_aHdaRegMap[i + 1] : NULL;
5227
5228 /* binary search order. */
5229 AssertReleaseMsg(!pNextReg || pReg->offset + pReg->size <= pNextReg->offset,
5230 ("[%#x] = {%#x LB %#x} vs. [%#x] = {%#x LB %#x}\n",
5231 i, pReg->offset, pReg->size, i + 1, pNextReg->offset, pNextReg->size));
5232
5233 /* alignment. */
5234 AssertReleaseMsg( pReg->size == 1
5235 || (pReg->size == 2 && (pReg->offset & 1) == 0)
5236 || (pReg->size == 3 && (pReg->offset & 3) == 0)
5237 || (pReg->size == 4 && (pReg->offset & 3) == 0),
5238 ("[%#x] = {%#x LB %#x}\n", i, pReg->offset, pReg->size));
5239
5240 /* registers are packed into dwords - with 3 exceptions with gaps at the end of the dword. */
5241 AssertRelease(((pReg->offset + pReg->size) & 3) == 0 || pNextReg);
5242 if (pReg->offset & 3)
5243 {
5244 struct HDAREGDESC const *pPrevReg = i > 0 ? &g_aHdaRegMap[i - 1] : NULL;
5245 AssertReleaseMsg(pPrevReg, ("[%#x] = {%#x LB %#x}\n", i, pReg->offset, pReg->size));
5246 if (pPrevReg)
5247 AssertReleaseMsg(pPrevReg->offset + pPrevReg->size == pReg->offset,
5248 ("[%#x] = {%#x LB %#x} vs. [%#x] = {%#x LB %#x}\n",
5249 i - 1, pPrevReg->offset, pPrevReg->size, i + 1, pReg->offset, pReg->size));
5250 }
5251#if 0
5252 if ((pReg->offset + pReg->size) & 3)
5253 {
5254 AssertReleaseMsg(pNextReg, ("[%#x] = {%#x LB %#x}\n", i, pReg->offset, pReg->size));
5255 if (pNextReg)
5256 AssertReleaseMsg(pReg->offset + pReg->size == pNextReg->offset,
5257 ("[%#x] = {%#x LB %#x} vs. [%#x] = {%#x LB %#x}\n",
5258 i, pReg->offset, pReg->size, i + 1, pNextReg->offset, pNextReg->size));
5259 }
5260#endif
5261 /* The final entry is a full DWORD, no gaps! Allows shortcuts. */
5262 AssertReleaseMsg(pNextReg || ((pReg->offset + pReg->size) & 3) == 0,
5263 ("[%#x] = {%#x LB %#x}\n", i, pReg->offset, pReg->size));
5264 }
5265 }
5266
5267 if (RT_SUCCESS(rc))
5268 {
5269 /* Create the emulation timer.
5270 *
5271 * Note: Use TMCLOCK_VIRTUAL_SYNC here, as the guest's HDA driver
5272 * relies on exact (virtual) DMA timing and uses DMA Position Buffers
5273 * instead of the LPIB registers.
5274 */
5275 rc = PDMDevHlpTMTimerCreate(pDevIns, TMCLOCK_VIRTUAL_SYNC, hdaTimer, pThis,
5276 TMTIMER_FLAGS_NO_CRIT_SECT, "HDA Timer", &pThis->pTimer);
5277 AssertRCReturn(rc, rc);
5278
5279 /* Use our own critcal section for the device timer.
5280 * That way we can control more fine-grained when to lock what. */
5281 rc = TMR3TimerSetCritSect(pThis->pTimer, &pThis->CritSect);
5282 AssertRCReturn(rc, rc);
5283 }
5284
5285# ifdef VBOX_WITH_STATISTICS
5286 if (RT_SUCCESS(rc))
5287 {
5288 /*
5289 * Register statistics.
5290 */
5291 PDMDevHlpSTAMRegister(pDevIns, &pThis->StatTimer, STAMTYPE_PROFILE, "/Devices/HDA/Timer", STAMUNIT_TICKS_PER_CALL, "Profiling hdaTimer.");
5292 PDMDevHlpSTAMRegister(pDevIns, &pThis->StatIn, STAMTYPE_PROFILE, "/Devices/HDA/Input", STAMUNIT_TICKS_PER_CALL, "Profiling input.");
5293 PDMDevHlpSTAMRegister(pDevIns, &pThis->StatOut, STAMTYPE_PROFILE, "/Devices/HDA/Output", STAMUNIT_TICKS_PER_CALL, "Profiling output.");
5294 PDMDevHlpSTAMRegister(pDevIns, &pThis->StatBytesRead, STAMTYPE_COUNTER, "/Devices/HDA/BytesRead" , STAMUNIT_BYTES, "Bytes read from HDA emulation.");
5295 PDMDevHlpSTAMRegister(pDevIns, &pThis->StatBytesWritten, STAMTYPE_COUNTER, "/Devices/HDA/BytesWritten", STAMUNIT_BYTES, "Bytes written to HDA emulation.");
5296 }
5297# endif
5298
5299 LogFlowFuncLeaveRC(rc);
5300 return rc;
5301}
5302
5303/**
5304 * The device registration structure.
5305 */
5306const PDMDEVREG g_DeviceHDA =
5307{
5308 /* u32Version */
5309 PDM_DEVREG_VERSION,
5310 /* szName */
5311 "hda",
5312 /* szRCMod */
5313 "VBoxDDRC.rc",
5314 /* szR0Mod */
5315 "VBoxDDR0.r0",
5316 /* pszDescription */
5317 "Intel HD Audio Controller",
5318 /* fFlags */
5319 PDM_DEVREG_FLAGS_DEFAULT_BITS | PDM_DEVREG_FLAGS_RC | PDM_DEVREG_FLAGS_R0,
5320 /* fClass */
5321 PDM_DEVREG_CLASS_AUDIO,
5322 /* cMaxInstances */
5323 1,
5324 /* cbInstance */
5325 sizeof(HDASTATE),
5326 /* pfnConstruct */
5327 hdaConstruct,
5328 /* pfnDestruct */
5329 hdaDestruct,
5330 /* pfnRelocate */
5331 NULL,
5332 /* pfnMemSetup */
5333 NULL,
5334 /* pfnPowerOn */
5335 NULL,
5336 /* pfnReset */
5337 hdaReset,
5338 /* pfnSuspend */
5339 NULL,
5340 /* pfnResume */
5341 NULL,
5342 /* pfnAttach */
5343 hdaAttach,
5344 /* pfnDetach */
5345 hdaDetach,
5346 /* pfnQueryInterface. */
5347 NULL,
5348 /* pfnInitComplete */
5349 NULL,
5350 /* pfnPowerOff */
5351 hdaPowerOff,
5352 /* pfnSoftReset */
5353 NULL,
5354 /* u32VersionEnd */
5355 PDM_DEVREG_VERSION
5356};
5357
5358#endif /* IN_RING3 */
5359#endif /* !VBOX_DEVICE_STRUCT_TESTCASE */
5360
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