VirtualBox

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

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

Audio/DevHDA.cpp: Save a lot of stream startup time by avoiding to create/destroy the driver stream in hdaAddStream(). The driver streams already are getting created/destroyed hdaMixerAddStream/hdaMixerDestroyStream.

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