VirtualBox

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

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

Audio/HDA: Integrated fixes up to r119397 from 5.1-audio-timing branch into trunk.

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

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