VirtualBox

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

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

Audio: Expose VBOX_WITH_INTEL_HDA (default) in Config.kmk.

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