VirtualBox

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

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

Audio/HDA: Only do stream tagging when enabling a stream and use stream tags when doing lookups via hdaGetStreamFromSD(). Needd for macOS guests.

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

© 2025 Oracle Support Privacy / Do Not Sell My Info Terms of Use Trademark Policy Automated Access Etiquette