VirtualBox

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

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

Audio/HDA: Use a pointer to the associated audio stream for HDAMIXERSINK instead of duplicating information (like SD# / stream channel).

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

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