VirtualBox

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

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

Audio/Mixer: Added support for setting / getting an (input) sink's current recording source via AudioMixerSink[Get|Set]RecordingSource().

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