VirtualBox

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

Last change on this file since 68625 was 68625, checked in by vboxsync, 8 years ago

Audio/HDA: Use own device locking instead of default PDM device lock (implicit). This enables more fine-grained locking in combination with TM when handling timer stuff in e.g. the MMIO handlers.

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