VirtualBox

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

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

Audio/HDA: Do hdaRegWriteSDFMT() in R0.

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 190.1 KB
Line 
1/* $Id: DevHDA.cpp 73209 2018-07-18 15:03:47Z 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 if (RT_SUCCESS(rc))
2424 {
2425 rc = AudioMixerSinkAddStream(pMixSink, pMixStrm);
2426 LogFlowFunc(("LUN#%RU8: Added \"%s\" to sink, rc=%Rrc\n", pDrv->uLUN, pStreamCfg->szName, rc));
2427 }
2428
2429 if (RT_SUCCESS(rc))
2430 pDrvStream->pMixStrm = pMixStrm;
2431 }
2432
2433 RTMemFree(pStreamCfg);
2434
2435 LogFlowFuncLeaveRC(rc);
2436 return rc;
2437}
2438
2439/**
2440 * Adds all current driver streams to a specific mixer sink.
2441 *
2442 * @returns IPRT status code.
2443 * @param pThis HDA state.
2444 * @param pMixSink Audio mixer sink to add stream to.
2445 * @param pCfg Audio stream configuration to use for the audio streams to add.
2446 */
2447static int hdaR3MixerAddDrvStreams(PHDASTATE pThis, PAUDMIXSINK pMixSink, PPDMAUDIOSTREAMCFG pCfg)
2448{
2449 AssertPtrReturn(pThis, VERR_INVALID_POINTER);
2450 AssertPtrReturn(pMixSink, VERR_INVALID_POINTER);
2451 AssertPtrReturn(pCfg, VERR_INVALID_POINTER);
2452
2453 LogFunc(("Sink=%s, Stream=%s\n", pMixSink->pszName, pCfg->szName));
2454
2455 if (!DrvAudioHlpStreamCfgIsValid(pCfg))
2456 return VERR_INVALID_PARAMETER;
2457
2458 int rc = AudioMixerSinkSetFormat(pMixSink, &pCfg->Props);
2459 if (RT_FAILURE(rc))
2460 return rc;
2461
2462 PHDADRIVER pDrv;
2463 RTListForEach(&pThis->lstDrv, pDrv, HDADRIVER, Node)
2464 {
2465 int rc2 = hdaR3MixerAddDrvStream(pThis, pMixSink, pCfg, pDrv);
2466 if (RT_FAILURE(rc2))
2467 LogFunc(("Attaching stream failed with %Rrc\n", rc2));
2468
2469 /* Do not pass failure to rc here, as there might be drivers which aren't
2470 * configured / ready yet. */
2471 }
2472
2473 return rc;
2474}
2475
2476/**
2477 * @interface_method_impl{HDACODEC,pfnCbMixerAddStream}
2478 *
2479 * Adds a new audio stream to a specific mixer control.
2480 *
2481 * Depending on the mixer control the stream then gets assigned to one of the internal
2482 * mixer sinks, which in turn then handle the mixing of all connected streams to that sink.
2483 *
2484 * @return IPRT status code.
2485 * @param pThis HDA state.
2486 * @param enmMixerCtl Mixer control to assign new stream to.
2487 * @param pCfg Stream configuration for the new stream.
2488 */
2489static DECLCALLBACK(int) hdaR3MixerAddStream(PHDASTATE pThis, PDMAUDIOMIXERCTL enmMixerCtl, PPDMAUDIOSTREAMCFG pCfg)
2490{
2491 AssertPtrReturn(pThis, VERR_INVALID_POINTER);
2492 AssertPtrReturn(pCfg, VERR_INVALID_POINTER);
2493
2494 int rc;
2495
2496 PHDAMIXERSINK pSink = hdaR3MixerControlToSink(pThis, enmMixerCtl);
2497 if (pSink)
2498 {
2499 rc = hdaR3MixerAddDrvStreams(pThis, pSink->pMixSink, pCfg);
2500
2501 AssertPtr(pSink->pMixSink);
2502 LogFlowFunc(("Sink=%s, Mixer control=%s\n", pSink->pMixSink->pszName, DrvAudioHlpAudMixerCtlToStr(enmMixerCtl)));
2503 }
2504 else
2505 rc = VERR_NOT_FOUND;
2506
2507 LogFlowFuncLeaveRC(rc);
2508 return rc;
2509}
2510
2511/**
2512 * @interface_method_impl{HDACODEC,pfnCbMixerRemoveStream}
2513 *
2514 * Removes a specified mixer control from the HDA's mixer.
2515 *
2516 * @return IPRT status code.
2517 * @param pThis HDA state.
2518 * @param enmMixerCtl Mixer control to remove.
2519 *
2520 * @remarks Can be called as a callback by the HDA codec.
2521 */
2522static DECLCALLBACK(int) hdaR3MixerRemoveStream(PHDASTATE pThis, PDMAUDIOMIXERCTL enmMixerCtl)
2523{
2524 AssertPtrReturn(pThis, VERR_INVALID_POINTER);
2525
2526 int rc;
2527
2528 PHDAMIXERSINK pSink = hdaR3MixerControlToSink(pThis, enmMixerCtl);
2529 if (pSink)
2530 {
2531 PHDADRIVER pDrv;
2532 RTListForEach(&pThis->lstDrv, pDrv, HDADRIVER, Node)
2533 {
2534 PAUDMIXSTREAM pMixStream = NULL;
2535 switch (enmMixerCtl)
2536 {
2537 /*
2538 * Input.
2539 */
2540 case PDMAUDIOMIXERCTL_LINE_IN:
2541 pMixStream = pDrv->LineIn.pMixStrm;
2542 pDrv->LineIn.pMixStrm = NULL;
2543 break;
2544# ifdef VBOX_WITH_AUDIO_HDA_MIC_IN
2545 case PDMAUDIOMIXERCTL_MIC_IN:
2546 pMixStream = pDrv->MicIn.pMixStrm;
2547 pDrv->MicIn.pMixStrm = NULL;
2548 break;
2549# endif
2550 /*
2551 * Output.
2552 */
2553 case PDMAUDIOMIXERCTL_FRONT:
2554 pMixStream = pDrv->Front.pMixStrm;
2555 pDrv->Front.pMixStrm = NULL;
2556 break;
2557# ifdef VBOX_WITH_AUDIO_HDA_51_SURROUND
2558 case PDMAUDIOMIXERCTL_CENTER_LFE:
2559 pMixStream = pDrv->CenterLFE.pMixStrm;
2560 pDrv->CenterLFE.pMixStrm = NULL;
2561 break;
2562 case PDMAUDIOMIXERCTL_REAR:
2563 pMixStream = pDrv->Rear.pMixStrm;
2564 pDrv->Rear.pMixStrm = NULL;
2565 break;
2566# endif
2567 default:
2568 AssertMsgFailed(("Mixer control %d not implemented\n", enmMixerCtl));
2569 break;
2570 }
2571
2572 if (pMixStream)
2573 {
2574 AudioMixerSinkRemoveStream(pSink->pMixSink, pMixStream);
2575 AudioMixerStreamDestroy(pMixStream);
2576
2577 pMixStream = NULL;
2578 }
2579 }
2580
2581 AudioMixerSinkRemoveAllStreams(pSink->pMixSink);
2582 rc = VINF_SUCCESS;
2583 }
2584 else
2585 rc = VERR_NOT_FOUND;
2586
2587 LogFunc(("Mixer control=%s, rc=%Rrc\n", DrvAudioHlpAudMixerCtlToStr(enmMixerCtl), rc));
2588 return rc;
2589}
2590
2591/**
2592 * @interface_method_impl{HDACODEC,pfnCbMixerControl}
2593 *
2594 * Controls an input / output converter widget, that is, which converter is connected
2595 * to which stream (and channel).
2596 *
2597 * @returns IPRT status code.
2598 * @param pThis HDA State.
2599 * @param enmMixerCtl Mixer control to set SD stream number and channel for.
2600 * @param uSD SD stream number (number + 1) to set. Set to 0 for unassign.
2601 * @param uChannel Channel to set. Only valid if a valid SD stream number is specified.
2602 *
2603 * @remarks Can be called as a callback by the HDA codec.
2604 */
2605static DECLCALLBACK(int) hdaR3MixerControl(PHDASTATE pThis, PDMAUDIOMIXERCTL enmMixerCtl, uint8_t uSD, uint8_t uChannel)
2606{
2607 LogFunc(("enmMixerCtl=%s, uSD=%RU8, uChannel=%RU8\n", DrvAudioHlpAudMixerCtlToStr(enmMixerCtl), uSD, uChannel));
2608
2609 if (uSD == 0) /* Stream number 0 is reserved. */
2610 {
2611 Log2Func(("Invalid SDn (%RU8) number for mixer control '%s', ignoring\n", uSD, DrvAudioHlpAudMixerCtlToStr(enmMixerCtl)));
2612 return VINF_SUCCESS;
2613 }
2614 /* uChannel is optional. */
2615
2616 /* SDn0 starts as 1. */
2617 Assert(uSD);
2618 uSD--;
2619
2620# ifndef VBOX_WITH_AUDIO_HDA_MIC_IN
2621 /* Only SDI0 (Line-In) is supported. */
2622 if ( hdaGetDirFromSD(uSD) == PDMAUDIODIR_IN
2623 && uSD >= 1)
2624 {
2625 LogRel2(("HDA: Dedicated Mic-In support not imlpemented / built-in (stream #%RU8), using Line-In (stream #0) instead\n", uSD));
2626 uSD = 0;
2627 }
2628# endif
2629
2630 int rc = VINF_SUCCESS;
2631
2632 PHDAMIXERSINK pSink = hdaR3MixerControlToSink(pThis, enmMixerCtl);
2633 if (pSink)
2634 {
2635 AssertPtr(pSink->pMixSink);
2636
2637 /* If this an output stream, determine the correct SD#. */
2638 if ( (uSD < HDA_MAX_SDI)
2639 && AudioMixerSinkGetDir(pSink->pMixSink) == AUDMIXSINKDIR_OUTPUT)
2640 {
2641 uSD += HDA_MAX_SDI;
2642 }
2643
2644 /* Detach the existing stream from the sink. */
2645 if ( pSink->pStream
2646 && ( pSink->pStream->u8SD != uSD
2647 || pSink->pStream->u8Channel != uChannel)
2648 )
2649 {
2650 LogFunc(("Sink '%s' was assigned to stream #%RU8 (channel %RU8) before\n",
2651 pSink->pMixSink->pszName, pSink->pStream->u8SD, pSink->pStream->u8Channel));
2652
2653 hdaR3StreamLock(pSink->pStream);
2654
2655 /* Only disable the stream if the stream descriptor # has changed. */
2656 if (pSink->pStream->u8SD != uSD)
2657 hdaR3StreamEnable(pSink->pStream, false);
2658
2659 pSink->pStream->pMixSink = NULL;
2660
2661 hdaR3StreamUnlock(pSink->pStream);
2662
2663 pSink->pStream = NULL;
2664 }
2665
2666 Assert(uSD < HDA_MAX_STREAMS);
2667
2668 /* Attach the new stream to the sink.
2669 * Enabling the stream will be done by the gust via a separate SDnCTL call then. */
2670 if (pSink->pStream == NULL)
2671 {
2672 LogRel2(("HDA: Setting sink '%s' to stream #%RU8 (channel %RU8), mixer control=%s\n",
2673 pSink->pMixSink->pszName, uSD, uChannel, DrvAudioHlpAudMixerCtlToStr(enmMixerCtl)));
2674
2675 PHDASTREAM pStream = hdaGetStreamFromSD(pThis, uSD);
2676 if (pStream)
2677 {
2678 hdaR3StreamLock(pStream);
2679
2680 pSink->pStream = pStream;
2681
2682 pStream->u8Channel = uChannel;
2683 pStream->pMixSink = pSink;
2684
2685 hdaR3StreamUnlock(pStream);
2686
2687 rc = VINF_SUCCESS;
2688 }
2689 else
2690 rc = VERR_NOT_IMPLEMENTED;
2691 }
2692 }
2693 else
2694 rc = VERR_NOT_FOUND;
2695
2696 if (RT_FAILURE(rc))
2697 LogRel(("HDA: Converter control for stream #%RU8 (channel %RU8) / mixer control '%s' failed with %Rrc, skipping\n",
2698 uSD, uChannel, DrvAudioHlpAudMixerCtlToStr(enmMixerCtl), rc));
2699
2700 LogFlowFuncLeaveRC(rc);
2701 return rc;
2702}
2703
2704/**
2705 * @interface_method_impl{HDACODEC,pfnCbMixerSetVolume}
2706 *
2707 * Sets the volume of a specified mixer control.
2708 *
2709 * @return IPRT status code.
2710 * @param pThis HDA State.
2711 * @param enmMixerCtl Mixer control to set volume for.
2712 * @param pVol Pointer to volume data to set.
2713 *
2714 * @remarks Can be called as a callback by the HDA codec.
2715 */
2716static DECLCALLBACK(int) hdaR3MixerSetVolume(PHDASTATE pThis, PDMAUDIOMIXERCTL enmMixerCtl, PPDMAUDIOVOLUME pVol)
2717{
2718 int rc;
2719
2720 PHDAMIXERSINK pSink = hdaR3MixerControlToSink(pThis, enmMixerCtl);
2721 if ( pSink
2722 && pSink->pMixSink)
2723 {
2724 LogRel2(("HDA: Setting volume for mixer sink '%s' to %RU8/%RU8 (%s)\n",
2725 pSink->pMixSink->pszName, pVol->uLeft, pVol->uRight, pVol->fMuted ? "Muted" : "Unmuted"));
2726
2727 /* Set the volume.
2728 * We assume that the codec already converted it to the correct range. */
2729 rc = AudioMixerSinkSetVolume(pSink->pMixSink, pVol);
2730 }
2731 else
2732 rc = VERR_NOT_FOUND;
2733
2734 LogFlowFuncLeaveRC(rc);
2735 return rc;
2736}
2737
2738/**
2739 * Main routine for the stream's timer.
2740 *
2741 * @param pDevIns Device instance.
2742 * @param pTimer Timer this callback was called for.
2743 * @param pvUser Pointer to associated HDASTREAM.
2744 */
2745static DECLCALLBACK(void) hdaR3Timer(PPDMDEVINS pDevIns, PTMTIMER pTimer, void *pvUser)
2746{
2747 RT_NOREF(pDevIns, pTimer);
2748
2749 PHDASTREAM pStream = (PHDASTREAM)pvUser;
2750 AssertPtr(pStream);
2751
2752 PHDASTATE pThis = pStream->pHDAState;
2753
2754 DEVHDA_LOCK_BOTH_RETURN_VOID(pStream->pHDAState, pStream->u8SD);
2755
2756 hdaR3StreamUpdate(pStream, true /* fInTimer */);
2757
2758 /* Flag indicating whether to kick the timer again for a
2759 * new data processing round. */
2760 const bool fSinkActive = AudioMixerSinkIsActive(pStream->pMixSink->pMixSink);
2761 if (fSinkActive)
2762 {
2763 const bool fTimerScheduled = hdaR3StreamTransferIsScheduled(pStream);
2764 Log3Func(("fSinksActive=%RTbool, fTimerScheduled=%RTbool\n", fSinkActive, fTimerScheduled));
2765 if (!fTimerScheduled)
2766 hdaR3TimerSet(pThis, pStream,
2767 TMTimerGet(pThis->pTimer[pStream->u8SD])
2768 + TMTimerGetFreq(pThis->pTimer[pStream->u8SD]) / pStream->pHDAState->u16TimerHz,
2769 true /* fForce */);
2770 }
2771 else
2772 Log3Func(("fSinksActive=%RTbool\n", fSinkActive));
2773
2774 DEVHDA_UNLOCK_BOTH(pThis, pStream->u8SD);
2775}
2776
2777# ifdef HDA_USE_DMA_ACCESS_HANDLER
2778/**
2779 * HC access handler for the FIFO.
2780 *
2781 * @returns VINF_SUCCESS if the handler have carried out the operation.
2782 * @returns VINF_PGM_HANDLER_DO_DEFAULT if the caller should carry out the access operation.
2783 * @param pVM VM Handle.
2784 * @param pVCpu The cross context CPU structure for the calling EMT.
2785 * @param GCPhys The physical address the guest is writing to.
2786 * @param pvPhys The HC mapping of that address.
2787 * @param pvBuf What the guest is reading/writing.
2788 * @param cbBuf How much it's reading/writing.
2789 * @param enmAccessType The access type.
2790 * @param enmOrigin Who is making the access.
2791 * @param pvUser User argument.
2792 */
2793static DECLCALLBACK(VBOXSTRICTRC) hdaR3DMAAccessHandler(PVM pVM, PVMCPU pVCpu, RTGCPHYS GCPhys, void *pvPhys,
2794 void *pvBuf, size_t cbBuf,
2795 PGMACCESSTYPE enmAccessType, PGMACCESSORIGIN enmOrigin, void *pvUser)
2796{
2797 RT_NOREF(pVM, pVCpu, pvPhys, pvBuf, enmOrigin);
2798
2799 PHDADMAACCESSHANDLER pHandler = (PHDADMAACCESSHANDLER)pvUser;
2800 AssertPtr(pHandler);
2801
2802 PHDASTREAM pStream = pHandler->pStream;
2803 AssertPtr(pStream);
2804
2805 Assert(GCPhys >= pHandler->GCPhysFirst);
2806 Assert(GCPhys <= pHandler->GCPhysLast);
2807 Assert(enmAccessType == PGMACCESSTYPE_WRITE);
2808
2809 /* Not within BDLE range? Bail out. */
2810 if ( (GCPhys < pHandler->BDLEAddr)
2811 || (GCPhys + cbBuf > pHandler->BDLEAddr + pHandler->BDLESize))
2812 {
2813 return VINF_PGM_HANDLER_DO_DEFAULT;
2814 }
2815
2816 switch(enmAccessType)
2817 {
2818 case PGMACCESSTYPE_WRITE:
2819 {
2820# ifdef DEBUG
2821 PHDASTREAMDBGINFO pStreamDbg = &pStream->Dbg;
2822
2823 const uint64_t tsNowNs = RTTimeNanoTS();
2824 const uint32_t tsElapsedMs = (tsNowNs - pStreamDbg->tsWriteSlotBegin) / 1000 / 1000;
2825
2826 uint64_t cWritesHz = ASMAtomicReadU64(&pStreamDbg->cWritesHz);
2827 uint64_t cbWrittenHz = ASMAtomicReadU64(&pStreamDbg->cbWrittenHz);
2828
2829 if (tsElapsedMs >= (1000 / HDA_TIMER_HZ_DEFAULT))
2830 {
2831 LogFunc(("[SD%RU8] %RU32ms elapsed, cbWritten=%RU64, cWritten=%RU64 -- %RU32 bytes on average per time slot (%zums)\n",
2832 pStream->u8SD, tsElapsedMs, cbWrittenHz, cWritesHz,
2833 ASMDivU64ByU32RetU32(cbWrittenHz, cWritesHz ? cWritesHz : 1), 1000 / HDA_TIMER_HZ_DEFAULT));
2834
2835 pStreamDbg->tsWriteSlotBegin = tsNowNs;
2836
2837 cWritesHz = 0;
2838 cbWrittenHz = 0;
2839 }
2840
2841 cWritesHz += 1;
2842 cbWrittenHz += cbBuf;
2843
2844 ASMAtomicIncU64(&pStreamDbg->cWritesTotal);
2845 ASMAtomicAddU64(&pStreamDbg->cbWrittenTotal, cbBuf);
2846
2847 ASMAtomicWriteU64(&pStreamDbg->cWritesHz, cWritesHz);
2848 ASMAtomicWriteU64(&pStreamDbg->cbWrittenHz, cbWrittenHz);
2849
2850 LogFunc(("[SD%RU8] Writing %3zu @ 0x%x (off %zu)\n",
2851 pStream->u8SD, cbBuf, GCPhys, GCPhys - pHandler->BDLEAddr));
2852
2853 LogFunc(("[SD%RU8] cWrites=%RU64, cbWritten=%RU64 -> %RU32 bytes on average\n",
2854 pStream->u8SD, pStreamDbg->cWritesTotal, pStreamDbg->cbWrittenTotal,
2855 ASMDivU64ByU32RetU32(pStreamDbg->cbWrittenTotal, pStreamDbg->cWritesTotal)));
2856# endif
2857
2858 if (pThis->fDebugEnabled)
2859 {
2860 RTFILE fh;
2861 RTFileOpen(&fh, VBOX_AUDIO_DEBUG_DUMP_PCM_DATA_PATH "hdaDMAAccessWrite.pcm",
2862 RTFILE_O_OPEN_CREATE | RTFILE_O_APPEND | RTFILE_O_WRITE | RTFILE_O_DENY_NONE);
2863 RTFileWrite(fh, pvBuf, cbBuf, NULL);
2864 RTFileClose(fh);
2865 }
2866
2867# ifdef HDA_USE_DMA_ACCESS_HANDLER_WRITING
2868 PRTCIRCBUF pCircBuf = pStream->State.pCircBuf;
2869 AssertPtr(pCircBuf);
2870
2871 uint8_t *pbBuf = (uint8_t *)pvBuf;
2872 while (cbBuf)
2873 {
2874 /* Make sure we only copy as much as the stream's FIFO can hold (SDFIFOS, 18.2.39). */
2875 void *pvChunk;
2876 size_t cbChunk;
2877 RTCircBufAcquireWriteBlock(pCircBuf, cbBuf, &pvChunk, &cbChunk);
2878
2879 if (cbChunk)
2880 {
2881 memcpy(pvChunk, pbBuf, cbChunk);
2882
2883 pbBuf += cbChunk;
2884 Assert(cbBuf >= cbChunk);
2885 cbBuf -= cbChunk;
2886 }
2887 else
2888 {
2889 //AssertMsg(RTCircBufFree(pCircBuf), ("No more space but still %zu bytes to write\n", cbBuf));
2890 break;
2891 }
2892
2893 LogFunc(("[SD%RU8] cbChunk=%zu\n", pStream->u8SD, cbChunk));
2894
2895 RTCircBufReleaseWriteBlock(pCircBuf, cbChunk);
2896 }
2897# endif /* HDA_USE_DMA_ACCESS_HANDLER_WRITING */
2898 break;
2899 }
2900
2901 default:
2902 AssertMsgFailed(("Access type not implemented\n"));
2903 break;
2904 }
2905
2906 return VINF_PGM_HANDLER_DO_DEFAULT;
2907}
2908# endif /* HDA_USE_DMA_ACCESS_HANDLER */
2909
2910/**
2911 * Soft reset of the device triggered via GCTL.
2912 *
2913 * @param pThis HDA state.
2914 *
2915 */
2916static void hdaR3GCTLReset(PHDASTATE pThis)
2917{
2918 LogFlowFuncEnter();
2919
2920 pThis->cStreamsActive = 0;
2921
2922 HDA_REG(pThis, GCAP) = HDA_MAKE_GCAP(HDA_MAX_SDO, HDA_MAX_SDI, 0, 0, 1); /* see 6.2.1 */
2923 HDA_REG(pThis, VMIN) = 0x00; /* see 6.2.2 */
2924 HDA_REG(pThis, VMAJ) = 0x01; /* see 6.2.3 */
2925 HDA_REG(pThis, OUTPAY) = 0x003C; /* see 6.2.4 */
2926 HDA_REG(pThis, INPAY) = 0x001D; /* see 6.2.5 */
2927 HDA_REG(pThis, CORBSIZE) = 0x42; /* Up to 256 CORB entries see 6.2.1 */
2928 HDA_REG(pThis, RIRBSIZE) = 0x42; /* Up to 256 RIRB entries see 6.2.1 */
2929 HDA_REG(pThis, CORBRP) = 0x0;
2930 HDA_REG(pThis, CORBWP) = 0x0;
2931 HDA_REG(pThis, RIRBWP) = 0x0;
2932 /* Some guests (like Haiku) don't set RINTCNT explicitly but expect an interrupt after each
2933 * RIRB response -- so initialize RINTCNT to 1 by default. */
2934 HDA_REG(pThis, RINTCNT) = 0x1;
2935
2936 /*
2937 * Stop any audio currently playing and/or recording.
2938 */
2939 pThis->SinkFront.pStream = NULL;
2940 if (pThis->SinkFront.pMixSink)
2941 AudioMixerSinkReset(pThis->SinkFront.pMixSink);
2942# ifdef VBOX_WITH_AUDIO_HDA_MIC_IN
2943 pThis->SinkMicIn.pStream = NULL;
2944 if (pThis->SinkMicIn.pMixSink)
2945 AudioMixerSinkReset(pThis->SinkMicIn.pMixSink);
2946# endif
2947 pThis->SinkLineIn.pStream = NULL;
2948 if (pThis->SinkLineIn.pMixSink)
2949 AudioMixerSinkReset(pThis->SinkLineIn.pMixSink);
2950# ifdef VBOX_WITH_AUDIO_HDA_51_SURROUND
2951 pThis->SinkCenterLFE = NULL;
2952 if (pThis->SinkCenterLFE.pMixSink)
2953 AudioMixerSinkReset(pThis->SinkCenterLFE.pMixSink);
2954 pThis->SinkRear.pStream = NULL;
2955 if (pThis->SinkRear.pMixSink)
2956 AudioMixerSinkReset(pThis->SinkRear.pMixSink);
2957# endif
2958
2959 /*
2960 * Reset the codec.
2961 */
2962 if ( pThis->pCodec
2963 && pThis->pCodec->pfnReset)
2964 {
2965 pThis->pCodec->pfnReset(pThis->pCodec);
2966 }
2967
2968 /*
2969 * Set some sensible defaults for which HDA sinks
2970 * are connected to which stream number.
2971 *
2972 * We use SD0 for input and SD4 for output by default.
2973 * These stream numbers can be changed by the guest dynamically lateron.
2974 */
2975# ifdef VBOX_WITH_AUDIO_HDA_MIC_IN
2976 hdaR3MixerControl(pThis, PDMAUDIOMIXERCTL_MIC_IN , 1 /* SD0 */, 0 /* Channel */);
2977# endif
2978 hdaR3MixerControl(pThis, PDMAUDIOMIXERCTL_LINE_IN , 1 /* SD0 */, 0 /* Channel */);
2979
2980 hdaR3MixerControl(pThis, PDMAUDIOMIXERCTL_FRONT , 5 /* SD4 */, 0 /* Channel */);
2981# ifdef VBOX_WITH_AUDIO_HDA_51_SURROUND
2982 hdaR3MixerControl(pThis, PDMAUDIOMIXERCTL_CENTER_LFE, 5 /* SD4 */, 0 /* Channel */);
2983 hdaR3MixerControl(pThis, PDMAUDIOMIXERCTL_REAR , 5 /* SD4 */, 0 /* Channel */);
2984# endif
2985
2986 /* Reset CORB. */
2987 pThis->cbCorbBuf = HDA_CORB_SIZE * HDA_CORB_ELEMENT_SIZE;
2988 RT_BZERO(pThis->pu32CorbBuf, pThis->cbCorbBuf);
2989
2990 /* Reset RIRB. */
2991 pThis->cbRirbBuf = HDA_RIRB_SIZE * HDA_RIRB_ELEMENT_SIZE;
2992 RT_BZERO(pThis->pu64RirbBuf, pThis->cbRirbBuf);
2993
2994 /* Clear our internal response interrupt counter. */
2995 pThis->u16RespIntCnt = 0;
2996
2997 for (uint8_t uSD = 0; uSD < HDA_MAX_STREAMS; ++uSD)
2998 {
2999 int rc2 = hdaR3StreamEnable(&pThis->aStreams[uSD], false /* fEnable */);
3000 if (RT_SUCCESS(rc2))
3001 {
3002 /* Remove the RUN bit from SDnCTL in case the stream was in a running state before. */
3003 HDA_STREAM_REG(pThis, CTL, uSD) &= ~HDA_SDCTL_RUN;
3004 hdaR3StreamReset(pThis, &pThis->aStreams[uSD], uSD);
3005 }
3006 }
3007
3008 /* Clear stream tags <-> objects mapping table. */
3009 RT_ZERO(pThis->aTags);
3010
3011 /* Emulation of codec "wake up" (HDA spec 5.5.1 and 6.5). */
3012 HDA_REG(pThis, STATESTS) = 0x1;
3013
3014 LogFlowFuncLeave();
3015 LogRel(("HDA: Reset\n"));
3016}
3017
3018#endif /* IN_RING3 */
3019
3020/* MMIO callbacks */
3021
3022/**
3023 * @callback_method_impl{FNIOMMMIOREAD, Looks up and calls the appropriate handler.}
3024 *
3025 * @note During implementation, we discovered so-called "forgotten" or "hole"
3026 * registers whose description is not listed in the RPM, datasheet, or
3027 * spec.
3028 */
3029PDMBOTHCBDECL(int) hdaMMIORead(PPDMDEVINS pDevIns, void *pvUser, RTGCPHYS GCPhysAddr, void *pv, unsigned cb)
3030{
3031 PHDASTATE pThis = PDMINS_2_DATA(pDevIns, PHDASTATE);
3032 int rc;
3033 RT_NOREF_PV(pvUser);
3034 Assert(pThis->uAlignmentCheckMagic == HDASTATE_ALIGNMENT_CHECK_MAGIC);
3035
3036 /*
3037 * Look up and log.
3038 */
3039 uint32_t offReg = GCPhysAddr - pThis->MMIOBaseAddr;
3040 int idxRegDsc = hdaRegLookup(offReg); /* Register descriptor index. */
3041#ifdef LOG_ENABLED
3042 unsigned const cbLog = cb;
3043 uint32_t offRegLog = offReg;
3044#endif
3045
3046 Log3Func(("offReg=%#x cb=%#x\n", offReg, cb));
3047 Assert(cb == 4); Assert((offReg & 3) == 0);
3048
3049 DEVHDA_LOCK_RETURN(pThis, VINF_IOM_R3_MMIO_READ);
3050
3051 if (!(HDA_REG(pThis, GCTL) & HDA_GCTL_CRST) && idxRegDsc != HDA_REG_GCTL)
3052 LogFunc(("Access to registers except GCTL is blocked while reset\n"));
3053
3054 if (idxRegDsc == -1)
3055 LogRel(("HDA: Invalid read access @0x%x (bytes=%u)\n", offReg, cb));
3056
3057 if (idxRegDsc != -1)
3058 {
3059 /* Leave lock before calling read function. */
3060 DEVHDA_UNLOCK(pThis);
3061
3062 /* ASSUMES gapless DWORD at end of map. */
3063 if (g_aHdaRegMap[idxRegDsc].size == 4)
3064 {
3065 /*
3066 * Straight forward DWORD access.
3067 */
3068 rc = g_aHdaRegMap[idxRegDsc].pfnRead(pThis, idxRegDsc, (uint32_t *)pv);
3069 Log3Func(("\tRead %s => %x (%Rrc)\n", g_aHdaRegMap[idxRegDsc].abbrev, *(uint32_t *)pv, rc));
3070 }
3071 else
3072 {
3073 /*
3074 * Multi register read (unless there are trailing gaps).
3075 * ASSUMES that only DWORD reads have sideeffects.
3076 */
3077#ifdef IN_RING3
3078 uint32_t u32Value = 0;
3079 unsigned cbLeft = 4;
3080 do
3081 {
3082 uint32_t const cbReg = g_aHdaRegMap[idxRegDsc].size;
3083 uint32_t u32Tmp = 0;
3084
3085 rc = g_aHdaRegMap[idxRegDsc].pfnRead(pThis, idxRegDsc, &u32Tmp);
3086 Log3Func(("\tRead %s[%db] => %x (%Rrc)*\n", g_aHdaRegMap[idxRegDsc].abbrev, cbReg, u32Tmp, rc));
3087 if (rc != VINF_SUCCESS)
3088 break;
3089 u32Value |= (u32Tmp & g_afMasks[cbReg]) << ((4 - cbLeft) * 8);
3090
3091 cbLeft -= cbReg;
3092 offReg += cbReg;
3093 idxRegDsc++;
3094 } while (cbLeft > 0 && g_aHdaRegMap[idxRegDsc].offset == offReg);
3095
3096 if (rc == VINF_SUCCESS)
3097 *(uint32_t *)pv = u32Value;
3098 else
3099 Assert(!IOM_SUCCESS(rc));
3100#else /* !IN_RING3 */
3101 /* Take the easy way out. */
3102 rc = VINF_IOM_R3_MMIO_READ;
3103#endif /* !IN_RING3 */
3104 }
3105 }
3106 else
3107 {
3108 DEVHDA_UNLOCK(pThis);
3109
3110 rc = VINF_IOM_MMIO_UNUSED_FF;
3111 Log3Func(("\tHole at %x is accessed for read\n", offReg));
3112 }
3113
3114 /*
3115 * Log the outcome.
3116 */
3117#ifdef LOG_ENABLED
3118 if (cbLog == 4)
3119 Log3Func(("\tReturning @%#05x -> %#010x %Rrc\n", offRegLog, *(uint32_t *)pv, rc));
3120 else if (cbLog == 2)
3121 Log3Func(("\tReturning @%#05x -> %#06x %Rrc\n", offRegLog, *(uint16_t *)pv, rc));
3122 else if (cbLog == 1)
3123 Log3Func(("\tReturning @%#05x -> %#04x %Rrc\n", offRegLog, *(uint8_t *)pv, rc));
3124#endif
3125 return rc;
3126}
3127
3128
3129DECLINLINE(int) hdaWriteReg(PHDASTATE pThis, int idxRegDsc, uint32_t u32Value, char const *pszLog)
3130{
3131 DEVHDA_LOCK_RETURN(pThis, VINF_IOM_R3_MMIO_WRITE);
3132
3133 if (!(HDA_REG(pThis, GCTL) & HDA_GCTL_CRST) && idxRegDsc != HDA_REG_GCTL)
3134 {
3135 Log(("hdaWriteReg: Warning: Access to %s is blocked while controller is in reset mode\n", g_aHdaRegMap[idxRegDsc].abbrev));
3136 LogRel2(("HDA: Warning: Access to register %s is blocked while controller is in reset mode\n",
3137 g_aHdaRegMap[idxRegDsc].abbrev));
3138
3139 DEVHDA_UNLOCK(pThis);
3140 return VINF_SUCCESS;
3141 }
3142
3143 /*
3144 * Handle RD (register description) flags.
3145 */
3146
3147 /* For SDI / SDO: Check if writes to those registers are allowed while SDCTL's RUN bit is set. */
3148 if (idxRegDsc >= HDA_NUM_GENERAL_REGS)
3149 {
3150 const uint32_t uSDCTL = HDA_STREAM_REG(pThis, CTL, HDA_SD_NUM_FROM_REG(pThis, CTL, idxRegDsc));
3151
3152 /*
3153 * Some OSes (like Win 10 AU) violate the spec by writing stuff to registers which are not supposed to be be touched
3154 * while SDCTL's RUN bit is set. So just ignore those values.
3155 */
3156
3157 /* Is the RUN bit currently set? */
3158 if ( RT_BOOL(uSDCTL & HDA_SDCTL_RUN)
3159 /* Are writes to the register denied if RUN bit is set? */
3160 && !(g_aHdaRegMap[idxRegDsc].fFlags & HDA_RD_FLAG_SD_WRITE_RUN))
3161 {
3162 Log(("hdaWriteReg: Warning: Access to %s is blocked! %R[sdctl]\n", g_aHdaRegMap[idxRegDsc].abbrev, uSDCTL));
3163 LogRel2(("HDA: Warning: Access to register %s is blocked while the stream's RUN bit is set\n",
3164 g_aHdaRegMap[idxRegDsc].abbrev));
3165
3166 DEVHDA_UNLOCK(pThis);
3167 return VINF_SUCCESS;
3168 }
3169 }
3170
3171 /* Leave the lock before calling write function. */
3172 /** @todo r=bird: Why do we need to do that?? There is no
3173 * explanation why this is necessary here...
3174 *
3175 * More or less all write functions retake the lock, so why not let
3176 * those who need to drop the lock or take additional locks release
3177 * it? See, releasing a lock you already got always runs the risk
3178 * of someone else grabbing it and forcing you to wait, better to
3179 * do the two-three things a write handle needs to do than enter
3180 * and exit the lock all the time. */
3181 DEVHDA_UNLOCK(pThis);
3182
3183#ifdef LOG_ENABLED
3184 uint32_t const idxRegMem = g_aHdaRegMap[idxRegDsc].mem_idx;
3185 uint32_t const u32OldValue = pThis->au32Regs[idxRegMem];
3186#endif
3187 int rc = g_aHdaRegMap[idxRegDsc].pfnWrite(pThis, idxRegDsc, u32Value);
3188 Log3Func(("Written value %#x to %s[%d byte]; %x => %x%s, rc=%d\n", u32Value, g_aHdaRegMap[idxRegDsc].abbrev,
3189 g_aHdaRegMap[idxRegDsc].size, u32OldValue, pThis->au32Regs[idxRegMem], pszLog, rc));
3190 RT_NOREF(pszLog);
3191 return rc;
3192}
3193
3194
3195/**
3196 * @callback_method_impl{FNIOMMMIOWRITE, Looks up and calls the appropriate handler.}
3197 */
3198PDMBOTHCBDECL(int) hdaMMIOWrite(PPDMDEVINS pDevIns, void *pvUser, RTGCPHYS GCPhysAddr, void const *pv, unsigned cb)
3199{
3200 PHDASTATE pThis = PDMINS_2_DATA(pDevIns, PHDASTATE);
3201 int rc;
3202 RT_NOREF_PV(pvUser);
3203 Assert(pThis->uAlignmentCheckMagic == HDASTATE_ALIGNMENT_CHECK_MAGIC);
3204
3205 /*
3206 * The behavior of accesses that aren't aligned on natural boundraries is
3207 * undefined. Just reject them outright.
3208 */
3209 /** @todo IOM could check this, it could also split the 8 byte accesses for us. */
3210 Assert(cb == 1 || cb == 2 || cb == 4 || cb == 8);
3211 if (GCPhysAddr & (cb - 1))
3212 return PDMDevHlpDBGFStop(pDevIns, RT_SRC_POS, "misaligned write access: GCPhysAddr=%RGp cb=%u\n", GCPhysAddr, cb);
3213
3214 /*
3215 * Look up and log the access.
3216 */
3217 uint32_t offReg = GCPhysAddr - pThis->MMIOBaseAddr;
3218 int idxRegDsc = hdaRegLookup(offReg);
3219#if defined(IN_RING3) || defined(LOG_ENABLED)
3220 uint32_t idxRegMem = idxRegDsc != -1 ? g_aHdaRegMap[idxRegDsc].mem_idx : UINT32_MAX;
3221#endif
3222 uint64_t u64Value;
3223 if (cb == 4) u64Value = *(uint32_t const *)pv;
3224 else if (cb == 2) u64Value = *(uint16_t const *)pv;
3225 else if (cb == 1) u64Value = *(uint8_t const *)pv;
3226 else if (cb == 8) u64Value = *(uint64_t const *)pv;
3227 else
3228 {
3229 u64Value = 0; /* shut up gcc. */
3230 AssertReleaseMsgFailed(("%u\n", cb));
3231 }
3232
3233#ifdef LOG_ENABLED
3234 uint32_t const u32LogOldValue = idxRegDsc >= 0 ? pThis->au32Regs[idxRegMem] : UINT32_MAX;
3235 if (idxRegDsc == -1)
3236 Log3Func(("@%#05x u32=%#010x cb=%d\n", offReg, *(uint32_t const *)pv, cb));
3237 else if (cb == 4)
3238 Log3Func(("@%#05x u32=%#010x %s\n", offReg, *(uint32_t *)pv, g_aHdaRegMap[idxRegDsc].abbrev));
3239 else if (cb == 2)
3240 Log3Func(("@%#05x u16=%#06x (%#010x) %s\n", offReg, *(uint16_t *)pv, *(uint32_t *)pv, g_aHdaRegMap[idxRegDsc].abbrev));
3241 else if (cb == 1)
3242 Log3Func(("@%#05x u8=%#04x (%#010x) %s\n", offReg, *(uint8_t *)pv, *(uint32_t *)pv, g_aHdaRegMap[idxRegDsc].abbrev));
3243
3244 if (idxRegDsc >= 0 && g_aHdaRegMap[idxRegDsc].size != cb)
3245 Log3Func(("\tsize=%RU32 != cb=%u!!\n", g_aHdaRegMap[idxRegDsc].size, cb));
3246#endif
3247
3248 /*
3249 * Try for a direct hit first.
3250 */
3251 if (idxRegDsc != -1 && g_aHdaRegMap[idxRegDsc].size == cb)
3252 {
3253 rc = hdaWriteReg(pThis, idxRegDsc, u64Value, "");
3254 Log3Func(("\t%#x -> %#x\n", u32LogOldValue, idxRegMem != UINT32_MAX ? pThis->au32Regs[idxRegMem] : UINT32_MAX));
3255 }
3256 /*
3257 * Partial or multiple register access, loop thru the requested memory.
3258 */
3259 else
3260 {
3261#ifdef IN_RING3
3262 /*
3263 * If it's an access beyond the start of the register, shift the input
3264 * value and fill in missing bits. Natural alignment rules means we
3265 * will only see 1 or 2 byte accesses of this kind, so no risk of
3266 * shifting out input values.
3267 */
3268 if (idxRegDsc == -1 && (idxRegDsc = hdaR3RegLookupWithin(offReg)) != -1)
3269 {
3270 uint32_t const cbBefore = offReg - g_aHdaRegMap[idxRegDsc].offset; Assert(cbBefore > 0 && cbBefore < 4);
3271 offReg -= cbBefore;
3272 idxRegMem = g_aHdaRegMap[idxRegDsc].mem_idx;
3273 u64Value <<= cbBefore * 8;
3274 u64Value |= pThis->au32Regs[idxRegMem] & g_afMasks[cbBefore];
3275 Log3Func(("\tWithin register, supplied %u leading bits: %#llx -> %#llx ...\n",
3276 cbBefore * 8, ~g_afMasks[cbBefore] & u64Value, u64Value));
3277 }
3278
3279 /* Loop thru the write area, it may cover multiple registers. */
3280 rc = VINF_SUCCESS;
3281 for (;;)
3282 {
3283 uint32_t cbReg;
3284 if (idxRegDsc != -1)
3285 {
3286 idxRegMem = g_aHdaRegMap[idxRegDsc].mem_idx;
3287 cbReg = g_aHdaRegMap[idxRegDsc].size;
3288 if (cb < cbReg)
3289 {
3290 u64Value |= pThis->au32Regs[idxRegMem] & g_afMasks[cbReg] & ~g_afMasks[cb];
3291 Log3Func(("\tSupplying missing bits (%#x): %#llx -> %#llx ...\n",
3292 g_afMasks[cbReg] & ~g_afMasks[cb], u64Value & g_afMasks[cb], u64Value));
3293 }
3294# ifdef LOG_ENABLED
3295 uint32_t uLogOldVal = pThis->au32Regs[idxRegMem];
3296# endif
3297 rc = hdaWriteReg(pThis, idxRegDsc, u64Value, "*");
3298 Log3Func(("\t%#x -> %#x\n", uLogOldVal, pThis->au32Regs[idxRegMem]));
3299 }
3300 else
3301 {
3302 LogRel(("HDA: Invalid write access @0x%x\n", offReg));
3303 cbReg = 1;
3304 }
3305 if (rc != VINF_SUCCESS)
3306 break;
3307 if (cbReg >= cb)
3308 break;
3309
3310 /* Advance. */
3311 offReg += cbReg;
3312 cb -= cbReg;
3313 u64Value >>= cbReg * 8;
3314 if (idxRegDsc == -1)
3315 idxRegDsc = hdaRegLookup(offReg);
3316 else
3317 {
3318 idxRegDsc++;
3319 if ( (unsigned)idxRegDsc >= RT_ELEMENTS(g_aHdaRegMap)
3320 || g_aHdaRegMap[idxRegDsc].offset != offReg)
3321 {
3322 idxRegDsc = -1;
3323 }
3324 }
3325 }
3326
3327#else /* !IN_RING3 */
3328 /* Take the simple way out. */
3329 rc = VINF_IOM_R3_MMIO_WRITE;
3330#endif /* !IN_RING3 */
3331 }
3332
3333 return rc;
3334}
3335
3336
3337/* PCI callback. */
3338
3339#ifdef IN_RING3
3340/**
3341 * @callback_method_impl{FNPCIIOREGIONMAP}
3342 */
3343static DECLCALLBACK(int) hdaR3PciIoRegionMap(PPDMDEVINS pDevIns, PPDMPCIDEV pPciDev, uint32_t iRegion,
3344 RTGCPHYS GCPhysAddress, RTGCPHYS cb, PCIADDRESSSPACE enmType)
3345{
3346 RT_NOREF(iRegion, enmType);
3347 PHDASTATE pThis = RT_FROM_MEMBER(pPciDev, HDASTATE, PciDev);
3348
3349 /*
3350 * 18.2 of the ICH6 datasheet defines the valid access widths as byte, word, and double word.
3351 *
3352 * Let IOM talk DWORDs when reading, saves a lot of complications. On
3353 * writing though, we have to do it all ourselves because of sideeffects.
3354 */
3355 Assert(enmType == PCI_ADDRESS_SPACE_MEM);
3356 int rc = PDMDevHlpMMIORegister(pDevIns, GCPhysAddress, cb, NULL /*pvUser*/,
3357 IOMMMIO_FLAGS_READ_DWORD
3358 | IOMMMIO_FLAGS_WRITE_PASSTHRU,
3359 hdaMMIOWrite, hdaMMIORead, "HDA");
3360
3361 if (RT_FAILURE(rc))
3362 return rc;
3363
3364 if (pThis->fRZEnabled)
3365 {
3366 rc = PDMDevHlpMMIORegisterR0(pDevIns, GCPhysAddress, cb, NIL_RTR0PTR /*pvUser*/,
3367 "hdaMMIOWrite", "hdaMMIORead");
3368 if (RT_FAILURE(rc))
3369 return rc;
3370
3371 rc = PDMDevHlpMMIORegisterRC(pDevIns, GCPhysAddress, cb, NIL_RTRCPTR /*pvUser*/,
3372 "hdaMMIOWrite", "hdaMMIORead");
3373 if (RT_FAILURE(rc))
3374 return rc;
3375 }
3376
3377 pThis->MMIOBaseAddr = GCPhysAddress;
3378 return VINF_SUCCESS;
3379}
3380
3381
3382/* Saved state workers and callbacks. */
3383
3384static int hdaR3SaveStream(PPDMDEVINS pDevIns, PSSMHANDLE pSSM, PHDASTREAM pStream)
3385{
3386 RT_NOREF(pDevIns);
3387#ifdef VBOX_STRICT
3388 PHDASTATE pThis = PDMINS_2_DATA(pDevIns, PHDASTATE);
3389#endif
3390
3391 Log2Func(("[SD%RU8]\n", pStream->u8SD));
3392
3393 /* Save stream ID. */
3394 int rc = SSMR3PutU8(pSSM, pStream->u8SD);
3395 AssertRCReturn(rc, rc);
3396 Assert(pStream->u8SD < HDA_MAX_STREAMS);
3397
3398 rc = SSMR3PutStructEx(pSSM, &pStream->State, sizeof(HDASTREAMSTATE), 0 /*fFlags*/, g_aSSMStreamStateFields7, NULL);
3399 AssertRCReturn(rc, rc);
3400
3401#ifdef VBOX_STRICT /* Sanity checks. */
3402 uint64_t u64BaseDMA = RT_MAKE_U64(HDA_STREAM_REG(pThis, BDPL, pStream->u8SD),
3403 HDA_STREAM_REG(pThis, BDPU, pStream->u8SD));
3404 uint16_t u16LVI = HDA_STREAM_REG(pThis, LVI, pStream->u8SD);
3405 uint32_t u32CBL = HDA_STREAM_REG(pThis, CBL, pStream->u8SD);
3406
3407 Assert(u64BaseDMA == pStream->u64BDLBase);
3408 Assert(u16LVI == pStream->u16LVI);
3409 Assert(u32CBL == pStream->u32CBL);
3410#endif
3411
3412 rc = SSMR3PutStructEx(pSSM, &pStream->State.BDLE.Desc, sizeof(HDABDLEDESC),
3413 0 /*fFlags*/, g_aSSMBDLEDescFields7, NULL);
3414 AssertRCReturn(rc, rc);
3415
3416 rc = SSMR3PutStructEx(pSSM, &pStream->State.BDLE.State, sizeof(HDABDLESTATE),
3417 0 /*fFlags*/, g_aSSMBDLEStateFields7, NULL);
3418 AssertRCReturn(rc, rc);
3419
3420 rc = SSMR3PutStructEx(pSSM, &pStream->State.Period, sizeof(HDASTREAMPERIOD),
3421 0 /* fFlags */, g_aSSMStreamPeriodFields7, NULL);
3422 AssertRCReturn(rc, rc);
3423
3424#ifdef VBOX_STRICT /* Sanity checks. */
3425 PHDABDLE pBDLE = &pStream->State.BDLE;
3426 if (u64BaseDMA)
3427 {
3428 Assert(pStream->State.uCurBDLE <= u16LVI + 1);
3429
3430 HDABDLE curBDLE;
3431 rc = hdaR3BDLEFetch(pThis, &curBDLE, u64BaseDMA, pStream->State.uCurBDLE);
3432 AssertRC(rc);
3433
3434 Assert(curBDLE.Desc.u32BufSize == pBDLE->Desc.u32BufSize);
3435 Assert(curBDLE.Desc.u64BufAdr == pBDLE->Desc.u64BufAdr);
3436 Assert(curBDLE.Desc.fFlags == pBDLE->Desc.fFlags);
3437 }
3438 else
3439 {
3440 Assert(pBDLE->Desc.u64BufAdr == 0);
3441 Assert(pBDLE->Desc.u32BufSize == 0);
3442 }
3443#endif
3444
3445 uint32_t cbCircBufSize = 0;
3446 uint32_t cbCircBufUsed = 0;
3447
3448 if (pStream->State.pCircBuf)
3449 {
3450 cbCircBufSize = (uint32_t)RTCircBufSize(pStream->State.pCircBuf);
3451 cbCircBufUsed = (uint32_t)RTCircBufUsed(pStream->State.pCircBuf);
3452 }
3453
3454 rc = SSMR3PutU32(pSSM, cbCircBufSize);
3455 AssertRCReturn(rc, rc);
3456
3457 rc = SSMR3PutU32(pSSM, cbCircBufUsed);
3458 AssertRCReturn(rc, rc);
3459
3460 if (cbCircBufUsed)
3461 {
3462 /*
3463 * We now need to get the circular buffer's data without actually modifying
3464 * the internal read / used offsets -- otherwise we would end up with broken audio
3465 * data after saving the state.
3466 *
3467 * So get the current read offset and serialize the buffer data manually based on that.
3468 */
3469 size_t cbCircBufOffRead = RTCircBufOffsetRead(pStream->State.pCircBuf);
3470
3471 void *pvBuf;
3472 size_t cbBuf;
3473 RTCircBufAcquireReadBlock(pStream->State.pCircBuf, cbCircBufUsed, &pvBuf, &cbBuf);
3474
3475 if (cbBuf)
3476 {
3477 size_t cbToRead = cbCircBufUsed;
3478 size_t cbEnd = 0;
3479
3480 if (cbCircBufUsed > cbCircBufOffRead)
3481 cbEnd = cbCircBufUsed - cbCircBufOffRead;
3482
3483 if (cbEnd) /* Save end of buffer first. */
3484 {
3485 rc = SSMR3PutMem(pSSM, (uint8_t *)pvBuf + cbCircBufSize - cbEnd /* End of buffer */, cbEnd);
3486 AssertRCReturn(rc, rc);
3487
3488 Assert(cbToRead >= cbEnd);
3489 cbToRead -= cbEnd;
3490 }
3491
3492 if (cbToRead) /* Save remaining stuff at start of buffer (if any). */
3493 {
3494 rc = SSMR3PutMem(pSSM, (uint8_t *)pvBuf - cbCircBufUsed /* Start of buffer */, cbToRead);
3495 AssertRCReturn(rc, rc);
3496 }
3497 }
3498
3499 RTCircBufReleaseReadBlock(pStream->State.pCircBuf, 0 /* Don't advance read pointer -- see comment above */);
3500 }
3501
3502 Log2Func(("[SD%RU8] LPIB=%RU32, CBL=%RU32, LVI=%RU32\n",
3503 pStream->u8SD,
3504 HDA_STREAM_REG(pThis, LPIB, pStream->u8SD), HDA_STREAM_REG(pThis, CBL, pStream->u8SD), HDA_STREAM_REG(pThis, LVI, pStream->u8SD)));
3505
3506#ifdef LOG_ENABLED
3507 hdaR3BDLEDumpAll(pThis, pStream->u64BDLBase, pStream->u16LVI + 1);
3508#endif
3509
3510 return rc;
3511}
3512
3513/**
3514 * @callback_method_impl{FNSSMDEVSAVEEXEC}
3515 */
3516static DECLCALLBACK(int) hdaR3SaveExec(PPDMDEVINS pDevIns, PSSMHANDLE pSSM)
3517{
3518 PHDASTATE pThis = PDMINS_2_DATA(pDevIns, PHDASTATE);
3519
3520 /* Save Codec nodes states. */
3521 hdaCodecSaveState(pThis->pCodec, pSSM);
3522
3523 /* Save MMIO registers. */
3524 SSMR3PutU32(pSSM, RT_ELEMENTS(pThis->au32Regs));
3525 SSMR3PutMem(pSSM, pThis->au32Regs, sizeof(pThis->au32Regs));
3526
3527 /* Save controller-specifc internals. */
3528 SSMR3PutU64(pSSM, pThis->u64WalClk);
3529 SSMR3PutU8(pSSM, pThis->u8IRQL);
3530
3531 /* Save number of streams. */
3532 SSMR3PutU32(pSSM, HDA_MAX_STREAMS);
3533
3534 /* Save stream states. */
3535 for (uint8_t i = 0; i < HDA_MAX_STREAMS; i++)
3536 {
3537 int rc = hdaR3SaveStream(pDevIns, pSSM, &pThis->aStreams[i]);
3538 AssertRCReturn(rc, rc);
3539 }
3540
3541 return VINF_SUCCESS;
3542}
3543
3544/**
3545 * Does required post processing when loading a saved state.
3546 *
3547 * @param pThis Pointer to HDA state.
3548 */
3549static int hdaR3LoadExecPost(PHDASTATE pThis)
3550{
3551 int rc = VINF_SUCCESS;
3552
3553 /*
3554 * Enable all previously active streams.
3555 */
3556 for (uint8_t i = 0; i < HDA_MAX_STREAMS; i++)
3557 {
3558 PHDASTREAM pStream = hdaGetStreamFromSD(pThis, i);
3559 if (pStream)
3560 {
3561 int rc2;
3562
3563 bool fActive = RT_BOOL(HDA_STREAM_REG(pThis, CTL, i) & HDA_SDCTL_RUN);
3564 if (fActive)
3565 {
3566#ifdef VBOX_WITH_AUDIO_HDA_ASYNC_IO
3567 /* Make sure to also create the async I/O thread before actually enabling the stream. */
3568 rc2 = hdaR3StreamAsyncIOCreate(pStream);
3569 AssertRC(rc2);
3570
3571 /* ... and enabling it. */
3572 hdaR3StreamAsyncIOEnable(pStream, true /* fEnable */);
3573#endif
3574 /* Resume the stream's period. */
3575 hdaR3StreamPeriodResume(&pStream->State.Period);
3576
3577 /* (Re-)enable the stream. */
3578 rc2 = hdaR3StreamEnable(pStream, true /* fEnable */);
3579 AssertRC(rc2);
3580
3581 /* Add the stream to the device setup. */
3582 rc2 = hdaR3AddStream(pThis, &pStream->State.Cfg);
3583 AssertRC(rc2);
3584
3585#ifdef HDA_USE_DMA_ACCESS_HANDLER
3586 /* (Re-)install the DMA handler. */
3587 hdaR3StreamRegisterDMAHandlers(pThis, pStream);
3588#endif
3589 if (hdaR3StreamTransferIsScheduled(pStream))
3590 hdaR3TimerSet(pThis, pStream, hdaR3StreamTransferGetNext(pStream), true /* fForce */);
3591
3592 /* Also keep track of the currently active streams. */
3593 pThis->cStreamsActive++;
3594 }
3595 }
3596 }
3597
3598 LogFlowFuncLeaveRC(rc);
3599 return rc;
3600}
3601
3602
3603/**
3604 * Handles loading of all saved state versions older than the current one.
3605 *
3606 * @param pThis Pointer to HDA state.
3607 * @param pSSM Pointer to SSM handle.
3608 * @param uVersion Saved state version to load.
3609 * @param uPass Loading stage to handle.
3610 */
3611static int hdaR3LoadExecLegacy(PHDASTATE pThis, PSSMHANDLE pSSM, uint32_t uVersion, uint32_t uPass)
3612{
3613 RT_NOREF(uPass);
3614
3615 int rc = VINF_SUCCESS;
3616
3617 /*
3618 * Load MMIO registers.
3619 */
3620 uint32_t cRegs;
3621 switch (uVersion)
3622 {
3623 case HDA_SSM_VERSION_1:
3624 /* Starting with r71199, we would save 112 instead of 113
3625 registers due to some code cleanups. This only affected trunk
3626 builds in the 4.1 development period. */
3627 cRegs = 113;
3628 if (SSMR3HandleRevision(pSSM) >= 71199)
3629 {
3630 uint32_t uVer = SSMR3HandleVersion(pSSM);
3631 if ( VBOX_FULL_VERSION_GET_MAJOR(uVer) == 4
3632 && VBOX_FULL_VERSION_GET_MINOR(uVer) == 0
3633 && VBOX_FULL_VERSION_GET_BUILD(uVer) >= 51)
3634 cRegs = 112;
3635 }
3636 break;
3637
3638 case HDA_SSM_VERSION_2:
3639 case HDA_SSM_VERSION_3:
3640 cRegs = 112;
3641 AssertCompile(RT_ELEMENTS(pThis->au32Regs) >= 112);
3642 break;
3643
3644 /* Since version 4 we store the register count to stay flexible. */
3645 case HDA_SSM_VERSION_4:
3646 case HDA_SSM_VERSION_5:
3647 case HDA_SSM_VERSION_6:
3648 rc = SSMR3GetU32(pSSM, &cRegs); AssertRCReturn(rc, rc);
3649 if (cRegs != RT_ELEMENTS(pThis->au32Regs))
3650 LogRel(("HDA: SSM version cRegs is %RU32, expected %RU32\n", cRegs, RT_ELEMENTS(pThis->au32Regs)));
3651 break;
3652
3653 default:
3654 LogRel(("HDA: Warning: Unsupported / too new saved state version (%RU32)\n", uVersion));
3655 return VERR_SSM_UNSUPPORTED_DATA_UNIT_VERSION;
3656 }
3657
3658 if (cRegs >= RT_ELEMENTS(pThis->au32Regs))
3659 {
3660 SSMR3GetMem(pSSM, pThis->au32Regs, sizeof(pThis->au32Regs));
3661 SSMR3Skip(pSSM, sizeof(uint32_t) * (cRegs - RT_ELEMENTS(pThis->au32Regs)));
3662 }
3663 else
3664 SSMR3GetMem(pSSM, pThis->au32Regs, sizeof(uint32_t) * cRegs);
3665
3666 /* Make sure to update the base addresses first before initializing any streams down below. */
3667 pThis->u64CORBBase = RT_MAKE_U64(HDA_REG(pThis, CORBLBASE), HDA_REG(pThis, CORBUBASE));
3668 pThis->u64RIRBBase = RT_MAKE_U64(HDA_REG(pThis, RIRBLBASE), HDA_REG(pThis, RIRBUBASE));
3669 pThis->u64DPBase = RT_MAKE_U64(HDA_REG(pThis, DPLBASE) & DPBASE_ADDR_MASK, HDA_REG(pThis, DPUBASE));
3670
3671 /* Also make sure to update the DMA position bit if this was enabled when saving the state. */
3672 pThis->fDMAPosition = RT_BOOL(HDA_REG(pThis, DPLBASE) & RT_BIT_32(0));
3673
3674 /*
3675 * Note: Saved states < v5 store LVI (u32BdleMaxCvi) for
3676 * *every* BDLE state, whereas it only needs to be stored
3677 * *once* for every stream. Most of the BDLE state we can
3678 * get out of the registers anyway, so just ignore those values.
3679 *
3680 * Also, only the current BDLE was saved, regardless whether
3681 * there were more than one (and there are at least two entries,
3682 * according to the spec).
3683 */
3684#define HDA_SSM_LOAD_BDLE_STATE_PRE_V5(v, x) \
3685 { \
3686 rc = SSMR3Skip(pSSM, sizeof(uint32_t)); /* Begin marker */ \
3687 AssertRCReturn(rc, rc); \
3688 rc = SSMR3GetU64(pSSM, &x.Desc.u64BufAdr); /* u64BdleCviAddr */ \
3689 AssertRCReturn(rc, rc); \
3690 rc = SSMR3Skip(pSSM, sizeof(uint32_t)); /* u32BdleMaxCvi */ \
3691 AssertRCReturn(rc, rc); \
3692 rc = SSMR3GetU32(pSSM, &x.State.u32BDLIndex); /* u32BdleCvi */ \
3693 AssertRCReturn(rc, rc); \
3694 rc = SSMR3GetU32(pSSM, &x.Desc.u32BufSize); /* u32BdleCviLen */ \
3695 AssertRCReturn(rc, rc); \
3696 rc = SSMR3GetU32(pSSM, &x.State.u32BufOff); /* u32BdleCviPos */ \
3697 AssertRCReturn(rc, rc); \
3698 bool fIOC; \
3699 rc = SSMR3GetBool(pSSM, &fIOC); /* fBdleCviIoc */ \
3700 AssertRCReturn(rc, rc); \
3701 x.Desc.fFlags = fIOC ? HDA_BDLE_FLAG_IOC : 0; \
3702 rc = SSMR3GetU32(pSSM, &x.State.cbBelowFIFOW); /* cbUnderFifoW */ \
3703 AssertRCReturn(rc, rc); \
3704 rc = SSMR3Skip(pSSM, sizeof(uint8_t) * 256); /* FIFO */ \
3705 AssertRCReturn(rc, rc); \
3706 rc = SSMR3Skip(pSSM, sizeof(uint32_t)); /* End marker */ \
3707 AssertRCReturn(rc, rc); \
3708 }
3709
3710 /*
3711 * Load BDLEs (Buffer Descriptor List Entries) and DMA counters.
3712 */
3713 switch (uVersion)
3714 {
3715 case HDA_SSM_VERSION_1:
3716 case HDA_SSM_VERSION_2:
3717 case HDA_SSM_VERSION_3:
3718 case HDA_SSM_VERSION_4:
3719 {
3720 /* Only load the internal states.
3721 * The rest will be initialized from the saved registers later. */
3722
3723 /* Note 1: Only the *current* BDLE for a stream was saved! */
3724 /* Note 2: The stream's saving order is/was fixed, so don't touch! */
3725
3726 /* Output */
3727 PHDASTREAM pStream = &pThis->aStreams[4];
3728 rc = hdaR3StreamInit(pStream, 4 /* Stream descriptor, hardcoded */);
3729 if (RT_FAILURE(rc))
3730 break;
3731 HDA_SSM_LOAD_BDLE_STATE_PRE_V5(uVersion, pStream->State.BDLE);
3732 pStream->State.uCurBDLE = pStream->State.BDLE.State.u32BDLIndex;
3733
3734 /* Microphone-In */
3735 pStream = &pThis->aStreams[2];
3736 rc = hdaR3StreamInit(pStream, 2 /* Stream descriptor, hardcoded */);
3737 if (RT_FAILURE(rc))
3738 break;
3739 HDA_SSM_LOAD_BDLE_STATE_PRE_V5(uVersion, pStream->State.BDLE);
3740 pStream->State.uCurBDLE = pStream->State.BDLE.State.u32BDLIndex;
3741
3742 /* Line-In */
3743 pStream = &pThis->aStreams[0];
3744 rc = hdaR3StreamInit(pStream, 0 /* Stream descriptor, hardcoded */);
3745 if (RT_FAILURE(rc))
3746 break;
3747 HDA_SSM_LOAD_BDLE_STATE_PRE_V5(uVersion, pStream->State.BDLE);
3748 pStream->State.uCurBDLE = pStream->State.BDLE.State.u32BDLIndex;
3749 break;
3750 }
3751
3752#undef HDA_SSM_LOAD_BDLE_STATE_PRE_V5
3753
3754 default: /* Since v5 we support flexible stream and BDLE counts. */
3755 {
3756 uint32_t cStreams;
3757 rc = SSMR3GetU32(pSSM, &cStreams);
3758 if (RT_FAILURE(rc))
3759 break;
3760
3761 if (cStreams > HDA_MAX_STREAMS)
3762 cStreams = HDA_MAX_STREAMS; /* Sanity. */
3763
3764 /* Load stream states. */
3765 for (uint32_t i = 0; i < cStreams; i++)
3766 {
3767 uint8_t uStreamID;
3768 rc = SSMR3GetU8(pSSM, &uStreamID);
3769 if (RT_FAILURE(rc))
3770 break;
3771
3772 PHDASTREAM pStream = hdaGetStreamFromSD(pThis, uStreamID);
3773 HDASTREAM StreamDummy;
3774
3775 if (!pStream)
3776 {
3777 pStream = &StreamDummy;
3778 LogRel2(("HDA: Warning: Stream ID=%RU32 not supported, skipping to load ...\n", uStreamID));
3779 }
3780
3781 rc = hdaR3StreamInit(pStream, uStreamID);
3782 if (RT_FAILURE(rc))
3783 {
3784 LogRel(("HDA: Stream #%RU32: Initialization of stream %RU8 failed, rc=%Rrc\n", i, uStreamID, rc));
3785 break;
3786 }
3787
3788 /*
3789 * Load BDLEs (Buffer Descriptor List Entries) and DMA counters.
3790 */
3791
3792 if (uVersion == HDA_SSM_VERSION_5)
3793 {
3794 /* Get the current BDLE entry and skip the rest. */
3795 uint16_t cBDLE;
3796
3797 rc = SSMR3Skip(pSSM, sizeof(uint32_t)); /* Begin marker */
3798 AssertRC(rc);
3799 rc = SSMR3GetU16(pSSM, &cBDLE); /* cBDLE */
3800 AssertRC(rc);
3801 rc = SSMR3GetU16(pSSM, &pStream->State.uCurBDLE); /* uCurBDLE */
3802 AssertRC(rc);
3803 rc = SSMR3Skip(pSSM, sizeof(uint32_t)); /* End marker */
3804 AssertRC(rc);
3805
3806 uint32_t u32BDLEIndex;
3807 for (uint16_t a = 0; a < cBDLE; a++)
3808 {
3809 rc = SSMR3Skip(pSSM, sizeof(uint32_t)); /* Begin marker */
3810 AssertRC(rc);
3811 rc = SSMR3GetU32(pSSM, &u32BDLEIndex); /* u32BDLIndex */
3812 AssertRC(rc);
3813
3814 /* Does the current BDLE index match the current BDLE to process? */
3815 if (u32BDLEIndex == pStream->State.uCurBDLE)
3816 {
3817 rc = SSMR3GetU32(pSSM, &pStream->State.BDLE.State.cbBelowFIFOW); /* cbBelowFIFOW */
3818 AssertRC(rc);
3819 rc = SSMR3Skip(pSSM, sizeof(uint8_t) * 256); /* FIFO, deprecated */
3820 AssertRC(rc);
3821 rc = SSMR3GetU32(pSSM, &pStream->State.BDLE.State.u32BufOff); /* u32BufOff */
3822 AssertRC(rc);
3823 rc = SSMR3Skip(pSSM, sizeof(uint32_t)); /* End marker */
3824 AssertRC(rc);
3825 }
3826 else /* Skip not current BDLEs. */
3827 {
3828 rc = SSMR3Skip(pSSM, sizeof(uint32_t) /* cbBelowFIFOW */
3829 + sizeof(uint8_t) * 256 /* au8FIFO */
3830 + sizeof(uint32_t) /* u32BufOff */
3831 + sizeof(uint32_t)); /* End marker */
3832 AssertRC(rc);
3833 }
3834 }
3835 }
3836 else
3837 {
3838 rc = SSMR3GetStructEx(pSSM, &pStream->State, sizeof(HDASTREAMSTATE),
3839 0 /* fFlags */, g_aSSMStreamStateFields6, NULL);
3840 if (RT_FAILURE(rc))
3841 break;
3842
3843 /* Get HDABDLEDESC. */
3844 uint32_t uMarker;
3845 rc = SSMR3GetU32(pSSM, &uMarker); /* Begin marker. */
3846 AssertRC(rc);
3847 Assert(uMarker == UINT32_C(0x19200102) /* SSMR3STRUCT_BEGIN */);
3848 rc = SSMR3GetU64(pSSM, &pStream->State.BDLE.Desc.u64BufAdr);
3849 AssertRC(rc);
3850 rc = SSMR3GetU32(pSSM, &pStream->State.BDLE.Desc.u32BufSize);
3851 AssertRC(rc);
3852 bool fFlags = false;
3853 rc = SSMR3GetBool(pSSM, &fFlags); /* Saved states < v7 only stored the IOC as boolean flag. */
3854 AssertRC(rc);
3855 pStream->State.BDLE.Desc.fFlags = fFlags ? HDA_BDLE_FLAG_IOC : 0;
3856 rc = SSMR3GetU32(pSSM, &uMarker); /* End marker. */
3857 AssertRC(rc);
3858 Assert(uMarker == UINT32_C(0x19920406) /* SSMR3STRUCT_END */);
3859
3860 rc = SSMR3GetStructEx(pSSM, &pStream->State.BDLE.State, sizeof(HDABDLESTATE),
3861 0 /* fFlags */, g_aSSMBDLEStateFields6, NULL);
3862 if (RT_FAILURE(rc))
3863 break;
3864
3865 Log2Func(("[SD%RU8] LPIB=%RU32, CBL=%RU32, LVI=%RU32\n",
3866 uStreamID,
3867 HDA_STREAM_REG(pThis, LPIB, uStreamID), HDA_STREAM_REG(pThis, CBL, uStreamID), HDA_STREAM_REG(pThis, LVI, uStreamID)));
3868#ifdef LOG_ENABLED
3869 hdaR3BDLEDumpAll(pThis, pStream->u64BDLBase, pStream->u16LVI + 1);
3870#endif
3871 }
3872
3873 } /* for cStreams */
3874 break;
3875 } /* default */
3876 }
3877
3878 return rc;
3879}
3880
3881/**
3882 * @callback_method_impl{FNSSMDEVLOADEXEC}
3883 */
3884static DECLCALLBACK(int) hdaR3LoadExec(PPDMDEVINS pDevIns, PSSMHANDLE pSSM, uint32_t uVersion, uint32_t uPass)
3885{
3886 PHDASTATE pThis = PDMINS_2_DATA(pDevIns, PHDASTATE);
3887
3888 Assert(uPass == SSM_PASS_FINAL); NOREF(uPass);
3889
3890 LogRel2(("hdaR3LoadExec: uVersion=%RU32, uPass=0x%x\n", uVersion, uPass));
3891
3892 /*
3893 * Load Codec nodes states.
3894 */
3895 int rc = hdaCodecLoadState(pThis->pCodec, pSSM, uVersion);
3896 if (RT_FAILURE(rc))
3897 {
3898 LogRel(("HDA: Failed loading codec state (version %RU32, pass 0x%x), rc=%Rrc\n", uVersion, uPass, rc));
3899 return rc;
3900 }
3901
3902 if (uVersion < HDA_SSM_VERSION) /* Handle older saved states? */
3903 {
3904 rc = hdaR3LoadExecLegacy(pThis, pSSM, uVersion, uPass);
3905 if (RT_SUCCESS(rc))
3906 rc = hdaR3LoadExecPost(pThis);
3907
3908 return rc;
3909 }
3910
3911 /*
3912 * Load MMIO registers.
3913 */
3914 uint32_t cRegs;
3915 rc = SSMR3GetU32(pSSM, &cRegs); AssertRCReturn(rc, rc);
3916 if (cRegs != RT_ELEMENTS(pThis->au32Regs))
3917 LogRel(("HDA: SSM version cRegs is %RU32, expected %RU32\n", cRegs, RT_ELEMENTS(pThis->au32Regs)));
3918
3919 if (cRegs >= RT_ELEMENTS(pThis->au32Regs))
3920 {
3921 SSMR3GetMem(pSSM, pThis->au32Regs, sizeof(pThis->au32Regs));
3922 SSMR3Skip(pSSM, sizeof(uint32_t) * (cRegs - RT_ELEMENTS(pThis->au32Regs)));
3923 }
3924 else
3925 SSMR3GetMem(pSSM, pThis->au32Regs, sizeof(uint32_t) * cRegs);
3926
3927 /* Make sure to update the base addresses first before initializing any streams down below. */
3928 pThis->u64CORBBase = RT_MAKE_U64(HDA_REG(pThis, CORBLBASE), HDA_REG(pThis, CORBUBASE));
3929 pThis->u64RIRBBase = RT_MAKE_U64(HDA_REG(pThis, RIRBLBASE), HDA_REG(pThis, RIRBUBASE));
3930 pThis->u64DPBase = RT_MAKE_U64(HDA_REG(pThis, DPLBASE) & DPBASE_ADDR_MASK, HDA_REG(pThis, DPUBASE));
3931
3932 /* Also make sure to update the DMA position bit if this was enabled when saving the state. */
3933 pThis->fDMAPosition = RT_BOOL(HDA_REG(pThis, DPLBASE) & RT_BIT_32(0));
3934
3935 /*
3936 * Load controller-specifc internals.
3937 * Don't annoy other team mates (forgot this for state v7).
3938 */
3939 if ( SSMR3HandleRevision(pSSM) >= 116273
3940 || SSMR3HandleVersion(pSSM) >= VBOX_FULL_VERSION_MAKE(5, 2, 0))
3941 {
3942 rc = SSMR3GetU64(pSSM, &pThis->u64WalClk);
3943 AssertRC(rc);
3944
3945 rc = SSMR3GetU8(pSSM, &pThis->u8IRQL);
3946 AssertRC(rc);
3947 }
3948
3949 /*
3950 * Load streams.
3951 */
3952 uint32_t cStreams;
3953 rc = SSMR3GetU32(pSSM, &cStreams);
3954 AssertRC(rc);
3955
3956 if (cStreams > HDA_MAX_STREAMS)
3957 cStreams = HDA_MAX_STREAMS; /* Sanity. */
3958
3959 Log2Func(("cStreams=%RU32\n", cStreams));
3960
3961 /* Load stream states. */
3962 for (uint32_t i = 0; i < cStreams; i++)
3963 {
3964 uint8_t uStreamID;
3965 rc = SSMR3GetU8(pSSM, &uStreamID);
3966 AssertRC(rc);
3967
3968 PHDASTREAM pStream = hdaGetStreamFromSD(pThis, uStreamID);
3969 HDASTREAM StreamDummy;
3970
3971 if (!pStream)
3972 {
3973 pStream = &StreamDummy;
3974 LogRel2(("HDA: Warning: Loading of stream #%RU8 not supported, skipping to load ...\n", uStreamID));
3975 }
3976
3977 rc = hdaR3StreamInit(pStream, uStreamID);
3978 if (RT_FAILURE(rc))
3979 {
3980 LogRel(("HDA: Stream #%RU8: Loading initialization failed, rc=%Rrc\n", uStreamID, rc));
3981 /* Continue. */
3982 }
3983
3984 rc = SSMR3GetStructEx(pSSM, &pStream->State, sizeof(HDASTREAMSTATE),
3985 0 /* fFlags */, g_aSSMStreamStateFields7,
3986 NULL);
3987 AssertRC(rc);
3988
3989 /*
3990 * Load BDLEs (Buffer Descriptor List Entries) and DMA counters.
3991 */
3992 rc = SSMR3GetStructEx(pSSM, &pStream->State.BDLE.Desc, sizeof(HDABDLEDESC),
3993 0 /* fFlags */, g_aSSMBDLEDescFields7, NULL);
3994 AssertRC(rc);
3995
3996 rc = SSMR3GetStructEx(pSSM, &pStream->State.BDLE.State, sizeof(HDABDLESTATE),
3997 0 /* fFlags */, g_aSSMBDLEStateFields7, NULL);
3998 AssertRC(rc);
3999
4000 Log2Func(("[SD%RU8] %R[bdle]\n", pStream->u8SD, &pStream->State.BDLE));
4001
4002 /*
4003 * Load period state.
4004 * Don't annoy other team mates (forgot this for state v7).
4005 */
4006 hdaR3StreamPeriodInit(&pStream->State.Period,
4007 pStream->u8SD, pStream->u16LVI, pStream->u32CBL, &pStream->State.Cfg);
4008
4009 if ( SSMR3HandleRevision(pSSM) >= 116273
4010 || SSMR3HandleVersion(pSSM) >= VBOX_FULL_VERSION_MAKE(5, 2, 0))
4011 {
4012 rc = SSMR3GetStructEx(pSSM, &pStream->State.Period, sizeof(HDASTREAMPERIOD),
4013 0 /* fFlags */, g_aSSMStreamPeriodFields7, NULL);
4014 AssertRC(rc);
4015 }
4016
4017 /*
4018 * Load internal (FIFO) buffer.
4019 */
4020 uint32_t cbCircBufSize = 0;
4021 rc = SSMR3GetU32(pSSM, &cbCircBufSize); /* cbCircBuf */
4022 AssertRC(rc);
4023
4024 uint32_t cbCircBufUsed = 0;
4025 rc = SSMR3GetU32(pSSM, &cbCircBufUsed); /* cbCircBuf */
4026 AssertRC(rc);
4027
4028 if (cbCircBufSize) /* If 0, skip the buffer. */
4029 {
4030 /* Paranoia. */
4031 AssertReleaseMsg(cbCircBufSize <= _1M,
4032 ("HDA: Saved state contains bogus DMA buffer size (%RU32) for stream #%RU8",
4033 cbCircBufSize, uStreamID));
4034 AssertReleaseMsg(cbCircBufUsed <= cbCircBufSize,
4035 ("HDA: Saved state contains invalid DMA buffer usage (%RU32/%RU32) for stream #%RU8",
4036 cbCircBufUsed, cbCircBufSize, uStreamID));
4037 AssertPtr(pStream->State.pCircBuf);
4038
4039 /* Do we need to cre-create the circular buffer do fit the data size? */
4040 if (cbCircBufSize != (uint32_t)RTCircBufSize(pStream->State.pCircBuf))
4041 {
4042 RTCircBufDestroy(pStream->State.pCircBuf);
4043 pStream->State.pCircBuf = NULL;
4044
4045 rc = RTCircBufCreate(&pStream->State.pCircBuf, cbCircBufSize);
4046 AssertRC(rc);
4047 }
4048
4049 if ( RT_SUCCESS(rc)
4050 && cbCircBufUsed)
4051 {
4052 void *pvBuf;
4053 size_t cbBuf;
4054
4055 RTCircBufAcquireWriteBlock(pStream->State.pCircBuf, cbCircBufUsed, &pvBuf, &cbBuf);
4056
4057 if (cbBuf)
4058 {
4059 rc = SSMR3GetMem(pSSM, pvBuf, cbBuf);
4060 AssertRC(rc);
4061 }
4062
4063 RTCircBufReleaseWriteBlock(pStream->State.pCircBuf, cbBuf);
4064
4065 Assert(cbBuf == cbCircBufUsed);
4066 }
4067 }
4068
4069 Log2Func(("[SD%RU8] LPIB=%RU32, CBL=%RU32, LVI=%RU32\n",
4070 uStreamID,
4071 HDA_STREAM_REG(pThis, LPIB, uStreamID), HDA_STREAM_REG(pThis, CBL, uStreamID), HDA_STREAM_REG(pThis, LVI, uStreamID)));
4072#ifdef LOG_ENABLED
4073 hdaR3BDLEDumpAll(pThis, pStream->u64BDLBase, pStream->u16LVI + 1);
4074#endif
4075 /** @todo (Re-)initialize active periods? */
4076
4077 } /* for cStreams */
4078
4079 rc = hdaR3LoadExecPost(pThis);
4080 AssertRC(rc);
4081
4082 LogFlowFuncLeaveRC(rc);
4083 return rc;
4084}
4085
4086/* IPRT format type handlers. */
4087
4088/**
4089 * @callback_method_impl{FNRTSTRFORMATTYPE}
4090 */
4091static DECLCALLBACK(size_t) hdaR3StrFmtBDLE(PFNRTSTROUTPUT pfnOutput, void *pvArgOutput,
4092 const char *pszType, void const *pvValue,
4093 int cchWidth, int cchPrecision, unsigned fFlags,
4094 void *pvUser)
4095{
4096 RT_NOREF(pszType, cchWidth, cchPrecision, fFlags, pvUser);
4097 PHDABDLE pBDLE = (PHDABDLE)pvValue;
4098 return RTStrFormat(pfnOutput, pvArgOutput, NULL, 0,
4099 "BDLE(idx:%RU32, off:%RU32, fifow:%RU32, IOC:%RTbool, DMA[%RU32 bytes @ 0x%x])",
4100 pBDLE->State.u32BDLIndex, pBDLE->State.u32BufOff, pBDLE->State.cbBelowFIFOW,
4101 pBDLE->Desc.fFlags & HDA_BDLE_FLAG_IOC, pBDLE->Desc.u32BufSize, pBDLE->Desc.u64BufAdr);
4102}
4103
4104/**
4105 * @callback_method_impl{FNRTSTRFORMATTYPE}
4106 */
4107static DECLCALLBACK(size_t) hdaR3StrFmtSDCTL(PFNRTSTROUTPUT pfnOutput, void *pvArgOutput,
4108 const char *pszType, void const *pvValue,
4109 int cchWidth, int cchPrecision, unsigned fFlags,
4110 void *pvUser)
4111{
4112 RT_NOREF(pszType, cchWidth, cchPrecision, fFlags, pvUser);
4113 uint32_t uSDCTL = (uint32_t)(uintptr_t)pvValue;
4114 return RTStrFormat(pfnOutput, pvArgOutput, NULL, 0,
4115 "SDCTL(raw:%#x, DIR:%s, TP:%RTbool, STRIPE:%x, DEIE:%RTbool, FEIE:%RTbool, IOCE:%RTbool, RUN:%RTbool, RESET:%RTbool)",
4116 uSDCTL,
4117 uSDCTL & HDA_SDCTL_DIR ? "OUT" : "IN",
4118 RT_BOOL(uSDCTL & HDA_SDCTL_TP),
4119 (uSDCTL & HDA_SDCTL_STRIPE_MASK) >> HDA_SDCTL_STRIPE_SHIFT,
4120 RT_BOOL(uSDCTL & HDA_SDCTL_DEIE),
4121 RT_BOOL(uSDCTL & HDA_SDCTL_FEIE),
4122 RT_BOOL(uSDCTL & HDA_SDCTL_IOCE),
4123 RT_BOOL(uSDCTL & HDA_SDCTL_RUN),
4124 RT_BOOL(uSDCTL & HDA_SDCTL_SRST));
4125}
4126
4127/**
4128 * @callback_method_impl{FNRTSTRFORMATTYPE}
4129 */
4130static DECLCALLBACK(size_t) hdaR3StrFmtSDFIFOS(PFNRTSTROUTPUT pfnOutput, void *pvArgOutput,
4131 const char *pszType, void const *pvValue,
4132 int cchWidth, int cchPrecision, unsigned fFlags,
4133 void *pvUser)
4134{
4135 RT_NOREF(pszType, cchWidth, cchPrecision, fFlags, pvUser);
4136 uint32_t uSDFIFOS = (uint32_t)(uintptr_t)pvValue;
4137 return RTStrFormat(pfnOutput, pvArgOutput, NULL, 0, "SDFIFOS(raw:%#x, sdfifos:%RU8 B)", uSDFIFOS, uSDFIFOS ? uSDFIFOS + 1 : 0);
4138}
4139
4140/**
4141 * @callback_method_impl{FNRTSTRFORMATTYPE}
4142 */
4143static DECLCALLBACK(size_t) hdaR3StrFmtSDFIFOW(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 uSDFIFOW = (uint32_t)(uintptr_t)pvValue;
4150 return RTStrFormat(pfnOutput, pvArgOutput, NULL, 0, "SDFIFOW(raw: %#0x, sdfifow:%d B)", uSDFIFOW, hdaSDFIFOWToBytes(uSDFIFOW));
4151}
4152
4153/**
4154 * @callback_method_impl{FNRTSTRFORMATTYPE}
4155 */
4156static DECLCALLBACK(size_t) hdaR3StrFmtSDSTS(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 uSdSts = (uint32_t)(uintptr_t)pvValue;
4163 return RTStrFormat(pfnOutput, pvArgOutput, NULL, 0,
4164 "SDSTS(raw:%#0x, fifordy:%RTbool, dese:%RTbool, fifoe:%RTbool, bcis:%RTbool)",
4165 uSdSts,
4166 RT_BOOL(uSdSts & HDA_SDSTS_FIFORDY),
4167 RT_BOOL(uSdSts & HDA_SDSTS_DESE),
4168 RT_BOOL(uSdSts & HDA_SDSTS_FIFOE),
4169 RT_BOOL(uSdSts & HDA_SDSTS_BCIS));
4170}
4171
4172/* Debug info dumpers */
4173
4174static int hdaR3DbgLookupRegByName(const char *pszArgs)
4175{
4176 int iReg = 0;
4177 for (; iReg < HDA_NUM_REGS; ++iReg)
4178 if (!RTStrICmp(g_aHdaRegMap[iReg].abbrev, pszArgs))
4179 return iReg;
4180 return -1;
4181}
4182
4183
4184static void hdaR3DbgPrintRegister(PHDASTATE pThis, PCDBGFINFOHLP pHlp, int iHdaIndex)
4185{
4186 Assert( pThis
4187 && iHdaIndex >= 0
4188 && iHdaIndex < HDA_NUM_REGS);
4189 pHlp->pfnPrintf(pHlp, "%s: 0x%x\n", g_aHdaRegMap[iHdaIndex].abbrev, pThis->au32Regs[g_aHdaRegMap[iHdaIndex].mem_idx]);
4190}
4191
4192/**
4193 * @callback_method_impl{FNDBGFHANDLERDEV}
4194 */
4195static DECLCALLBACK(void) hdaR3DbgInfo(PPDMDEVINS pDevIns, PCDBGFINFOHLP pHlp, const char *pszArgs)
4196{
4197 PHDASTATE pThis = PDMINS_2_DATA(pDevIns, PHDASTATE);
4198 int iHdaRegisterIndex = hdaR3DbgLookupRegByName(pszArgs);
4199 if (iHdaRegisterIndex != -1)
4200 hdaR3DbgPrintRegister(pThis, pHlp, iHdaRegisterIndex);
4201 else
4202 {
4203 for(iHdaRegisterIndex = 0; (unsigned int)iHdaRegisterIndex < HDA_NUM_REGS; ++iHdaRegisterIndex)
4204 hdaR3DbgPrintRegister(pThis, pHlp, iHdaRegisterIndex);
4205 }
4206}
4207
4208static void hdaR3DbgPrintStream(PHDASTATE pThis, PCDBGFINFOHLP pHlp, int iIdx)
4209{
4210 Assert( pThis
4211 && iIdx >= 0
4212 && iIdx < HDA_MAX_STREAMS);
4213
4214 const PHDASTREAM pStream = &pThis->aStreams[iIdx];
4215
4216 pHlp->pfnPrintf(pHlp, "Stream #%d:\n", iIdx);
4217 pHlp->pfnPrintf(pHlp, "\tSD%dCTL : %R[sdctl]\n", iIdx, HDA_STREAM_REG(pThis, CTL, iIdx));
4218 pHlp->pfnPrintf(pHlp, "\tSD%dCTS : %R[sdsts]\n", iIdx, HDA_STREAM_REG(pThis, STS, iIdx));
4219 pHlp->pfnPrintf(pHlp, "\tSD%dFIFOS: %R[sdfifos]\n", iIdx, HDA_STREAM_REG(pThis, FIFOS, iIdx));
4220 pHlp->pfnPrintf(pHlp, "\tSD%dFIFOW: %R[sdfifow]\n", iIdx, HDA_STREAM_REG(pThis, FIFOW, iIdx));
4221 pHlp->pfnPrintf(pHlp, "\tBDLE : %R[bdle]\n", &pStream->State.BDLE);
4222}
4223
4224static void hdaR3DbgPrintBDLE(PHDASTATE pThis, PCDBGFINFOHLP pHlp, int iIdx)
4225{
4226 Assert( pThis
4227 && iIdx >= 0
4228 && iIdx < HDA_MAX_STREAMS);
4229
4230 const PHDASTREAM pStream = &pThis->aStreams[iIdx];
4231 const PHDABDLE pBDLE = &pStream->State.BDLE;
4232
4233 pHlp->pfnPrintf(pHlp, "Stream #%d BDLE:\n", iIdx);
4234
4235 uint64_t u64BaseDMA = RT_MAKE_U64(HDA_STREAM_REG(pThis, BDPL, iIdx),
4236 HDA_STREAM_REG(pThis, BDPU, iIdx));
4237 uint16_t u16LVI = HDA_STREAM_REG(pThis, LVI, iIdx);
4238 uint32_t u32CBL = HDA_STREAM_REG(pThis, CBL, iIdx);
4239
4240 if (!u64BaseDMA)
4241 return;
4242
4243 pHlp->pfnPrintf(pHlp, "\tCurrent: %R[bdle]\n\n", pBDLE);
4244
4245 pHlp->pfnPrintf(pHlp, "\tMemory:\n");
4246
4247 uint32_t cbBDLE = 0;
4248 for (uint16_t i = 0; i < u16LVI + 1; i++)
4249 {
4250 HDABDLEDESC bd;
4251 PDMDevHlpPhysRead(pThis->CTX_SUFF(pDevIns), u64BaseDMA + i * sizeof(HDABDLEDESC), &bd, sizeof(bd));
4252
4253 pHlp->pfnPrintf(pHlp, "\t\t%s #%03d BDLE(adr:0x%llx, size:%RU32, ioc:%RTbool)\n",
4254 pBDLE->State.u32BDLIndex == i ? "*" : " ", i, bd.u64BufAdr, bd.u32BufSize, bd.fFlags & HDA_BDLE_FLAG_IOC);
4255
4256 cbBDLE += bd.u32BufSize;
4257 }
4258
4259 pHlp->pfnPrintf(pHlp, "Total: %RU32 bytes\n", cbBDLE);
4260
4261 if (cbBDLE != u32CBL)
4262 pHlp->pfnPrintf(pHlp, "Warning: %RU32 bytes does not match CBL (%RU32)!\n", cbBDLE, u32CBL);
4263
4264 pHlp->pfnPrintf(pHlp, "DMA counters (base @ 0x%llx):\n", u64BaseDMA);
4265 if (!u64BaseDMA) /* No DMA base given? Bail out. */
4266 {
4267 pHlp->pfnPrintf(pHlp, "\tNo counters found\n");
4268 return;
4269 }
4270
4271 for (int i = 0; i < u16LVI + 1; i++)
4272 {
4273 uint32_t uDMACnt;
4274 PDMDevHlpPhysRead(pThis->CTX_SUFF(pDevIns), (pThis->u64DPBase & DPBASE_ADDR_MASK) + (i * 2 * sizeof(uint32_t)),
4275 &uDMACnt, sizeof(uDMACnt));
4276
4277 pHlp->pfnPrintf(pHlp, "\t#%03d DMA @ 0x%x\n", i , uDMACnt);
4278 }
4279}
4280
4281static int hdaR3DbgLookupStrmIdx(PHDASTATE pThis, const char *pszArgs)
4282{
4283 RT_NOREF(pThis, pszArgs);
4284 /** @todo Add args parsing. */
4285 return -1;
4286}
4287
4288/**
4289 * @callback_method_impl{FNDBGFHANDLERDEV}
4290 */
4291static DECLCALLBACK(void) hdaR3DbgInfoStream(PPDMDEVINS pDevIns, PCDBGFINFOHLP pHlp, const char *pszArgs)
4292{
4293 PHDASTATE pThis = PDMINS_2_DATA(pDevIns, PHDASTATE);
4294 int iHdaStreamdex = hdaR3DbgLookupStrmIdx(pThis, pszArgs);
4295 if (iHdaStreamdex != -1)
4296 hdaR3DbgPrintStream(pThis, pHlp, iHdaStreamdex);
4297 else
4298 for(iHdaStreamdex = 0; iHdaStreamdex < HDA_MAX_STREAMS; ++iHdaStreamdex)
4299 hdaR3DbgPrintStream(pThis, pHlp, iHdaStreamdex);
4300}
4301
4302/**
4303 * @callback_method_impl{FNDBGFHANDLERDEV}
4304 */
4305static DECLCALLBACK(void) hdaR3DbgInfoBDLE(PPDMDEVINS pDevIns, PCDBGFINFOHLP pHlp, const char *pszArgs)
4306{
4307 PHDASTATE pThis = PDMINS_2_DATA(pDevIns, PHDASTATE);
4308 int iHdaStreamdex = hdaR3DbgLookupStrmIdx(pThis, pszArgs);
4309 if (iHdaStreamdex != -1)
4310 hdaR3DbgPrintBDLE(pThis, pHlp, iHdaStreamdex);
4311 else
4312 for (iHdaStreamdex = 0; iHdaStreamdex < HDA_MAX_STREAMS; ++iHdaStreamdex)
4313 hdaR3DbgPrintBDLE(pThis, pHlp, iHdaStreamdex);
4314}
4315
4316/**
4317 * @callback_method_impl{FNDBGFHANDLERDEV}
4318 */
4319static DECLCALLBACK(void) hdaR3DbgInfoCodecNodes(PPDMDEVINS pDevIns, PCDBGFINFOHLP pHlp, const char *pszArgs)
4320{
4321 PHDASTATE pThis = PDMINS_2_DATA(pDevIns, PHDASTATE);
4322
4323 if (pThis->pCodec->pfnDbgListNodes)
4324 pThis->pCodec->pfnDbgListNodes(pThis->pCodec, pHlp, pszArgs);
4325 else
4326 pHlp->pfnPrintf(pHlp, "Codec implementation doesn't provide corresponding callback\n");
4327}
4328
4329/**
4330 * @callback_method_impl{FNDBGFHANDLERDEV}
4331 */
4332static DECLCALLBACK(void) hdaR3DbgInfoCodecSelector(PPDMDEVINS pDevIns, PCDBGFINFOHLP pHlp, const char *pszArgs)
4333{
4334 PHDASTATE pThis = PDMINS_2_DATA(pDevIns, PHDASTATE);
4335
4336 if (pThis->pCodec->pfnDbgSelector)
4337 pThis->pCodec->pfnDbgSelector(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) hdaR3DbgInfoMixer(PPDMDEVINS pDevIns, PCDBGFINFOHLP pHlp, const char *pszArgs)
4346{
4347 PHDASTATE pThis = PDMINS_2_DATA(pDevIns, PHDASTATE);
4348
4349 if (pThis->pMixer)
4350 AudioMixerDebug(pThis->pMixer, pHlp, pszArgs);
4351 else
4352 pHlp->pfnPrintf(pHlp, "Mixer not available\n");
4353}
4354
4355
4356/* PDMIBASE */
4357
4358/**
4359 * @interface_method_impl{PDMIBASE,pfnQueryInterface}
4360 */
4361static DECLCALLBACK(void *) hdaR3QueryInterface(struct PDMIBASE *pInterface, const char *pszIID)
4362{
4363 PHDASTATE pThis = RT_FROM_MEMBER(pInterface, HDASTATE, IBase);
4364 Assert(&pThis->IBase == pInterface);
4365
4366 PDMIBASE_RETURN_INTERFACE(pszIID, PDMIBASE, &pThis->IBase);
4367 return NULL;
4368}
4369
4370
4371/* PDMDEVREG */
4372
4373/**
4374 * Attach command, internal version.
4375 *
4376 * This is called to let the device attach to a driver for a specified LUN
4377 * during runtime. This is not called during VM construction, the device
4378 * constructor has to attach to all the available drivers.
4379 *
4380 * @returns VBox status code.
4381 * @param pThis HDA state.
4382 * @param uLUN The logical unit which is being detached.
4383 * @param fFlags Flags, combination of the PDMDEVATT_FLAGS_* \#defines.
4384 * @param ppDrv Attached driver instance on success. Optional.
4385 */
4386static int hdaR3AttachInternal(PHDASTATE pThis, unsigned uLUN, uint32_t fFlags, PHDADRIVER *ppDrv)
4387{
4388 RT_NOREF(fFlags);
4389
4390 /*
4391 * Attach driver.
4392 */
4393 char *pszDesc;
4394 if (RTStrAPrintf(&pszDesc, "Audio driver port (HDA) for LUN#%u", uLUN) <= 0)
4395 AssertLogRelFailedReturn(VERR_NO_MEMORY);
4396
4397 PPDMIBASE pDrvBase;
4398 int rc = PDMDevHlpDriverAttach(pThis->pDevInsR3, uLUN,
4399 &pThis->IBase, &pDrvBase, pszDesc);
4400 if (RT_SUCCESS(rc))
4401 {
4402 PHDADRIVER pDrv = (PHDADRIVER)RTMemAllocZ(sizeof(HDADRIVER));
4403 if (pDrv)
4404 {
4405 pDrv->pDrvBase = pDrvBase;
4406 pDrv->pConnector = PDMIBASE_QUERY_INTERFACE(pDrvBase, PDMIAUDIOCONNECTOR);
4407 AssertMsg(pDrv->pConnector != NULL, ("Configuration error: LUN#%u has no host audio interface, rc=%Rrc\n", uLUN, rc));
4408 pDrv->pHDAState = pThis;
4409 pDrv->uLUN = uLUN;
4410
4411 /*
4412 * For now we always set the driver at LUN 0 as our primary
4413 * host backend. This might change in the future.
4414 */
4415 if (pDrv->uLUN == 0)
4416 pDrv->fFlags |= PDMAUDIODRVFLAGS_PRIMARY;
4417
4418 LogFunc(("LUN#%u: pCon=%p, drvFlags=0x%x\n", uLUN, pDrv->pConnector, pDrv->fFlags));
4419
4420 /* Attach to driver list if not attached yet. */
4421 if (!pDrv->fAttached)
4422 {
4423 RTListAppend(&pThis->lstDrv, &pDrv->Node);
4424 pDrv->fAttached = true;
4425 }
4426
4427 if (ppDrv)
4428 *ppDrv = pDrv;
4429 }
4430 else
4431 rc = VERR_NO_MEMORY;
4432 }
4433 else if (rc == VERR_PDM_NO_ATTACHED_DRIVER)
4434 LogFunc(("No attached driver for LUN #%u\n", uLUN));
4435
4436 if (RT_FAILURE(rc))
4437 {
4438 /* Only free this string on failure;
4439 * must remain valid for the live of the driver instance. */
4440 RTStrFree(pszDesc);
4441 }
4442
4443 LogFunc(("uLUN=%u, fFlags=0x%x, rc=%Rrc\n", uLUN, fFlags, rc));
4444 return rc;
4445}
4446
4447/**
4448 * Detach command, internal version.
4449 *
4450 * This is called to let the device detach from a driver for a specified LUN
4451 * during runtime.
4452 *
4453 * @returns VBox status code.
4454 * @param pThis HDA state.
4455 * @param pDrv Driver to detach device from.
4456 * @param fFlags Flags, combination of the PDMDEVATT_FLAGS_* \#defines.
4457 */
4458static int hdaR3DetachInternal(PHDASTATE pThis, PHDADRIVER pDrv, uint32_t fFlags)
4459{
4460 RT_NOREF(fFlags);
4461
4462 AudioMixerSinkRemoveStream(pThis->SinkFront.pMixSink, pDrv->Front.pMixStrm);
4463 AudioMixerStreamDestroy(pDrv->Front.pMixStrm);
4464 pDrv->Front.pMixStrm = NULL;
4465
4466#ifdef VBOX_WITH_AUDIO_HDA_51_SURROUND
4467 AudioMixerSinkRemoveStream(pThis->SinkCenterLFE.pMixSink, pDrv->CenterLFE.pMixStrm);
4468 AudioMixerStreamDestroy(pDrv->CenterLFE.pMixStrm);
4469 pDrv->CenterLFE.pMixStrm = NULL;
4470
4471 AudioMixerSinkRemoveStream(pThis->SinkRear.pMixSink, pDrv->Rear.pMixStrm);
4472 AudioMixerStreamDestroy(pDrv->Rear.pMixStrm);
4473 pDrv->Rear.pMixStrm = NULL;
4474#endif
4475
4476 AudioMixerSinkRemoveStream(pThis->SinkLineIn.pMixSink, pDrv->LineIn.pMixStrm);
4477 AudioMixerStreamDestroy(pDrv->LineIn.pMixStrm);
4478 pDrv->LineIn.pMixStrm = NULL;
4479
4480#ifdef VBOX_WITH_AUDIO_HDA_MIC_IN
4481 AudioMixerSinkRemoveStream(pThis->SinkMicIn.pMixSink, pDrv->MicIn.pMixStrm);
4482 AudioMixerStreamDestroy(pDrv->MicIn.pMixStrm);
4483 pDrv->MicIn.pMixStrm = NULL;
4484#endif
4485
4486 RTListNodeRemove(&pDrv->Node);
4487
4488 LogFunc(("uLUN=%u, fFlags=0x%x\n", pDrv->uLUN, fFlags));
4489 return VINF_SUCCESS;
4490}
4491
4492/**
4493 * @interface_method_impl{PDMDEVREG,pfnAttach}
4494 */
4495static DECLCALLBACK(int) hdaR3Attach(PPDMDEVINS pDevIns, unsigned uLUN, uint32_t fFlags)
4496{
4497 PHDASTATE pThis = PDMINS_2_DATA(pDevIns, PHDASTATE);
4498
4499 DEVHDA_LOCK_RETURN(pThis, VERR_IGNORED);
4500
4501 LogFunc(("uLUN=%u, fFlags=0x%x\n", uLUN, fFlags));
4502
4503 PHDADRIVER pDrv;
4504 int rc2 = hdaR3AttachInternal(pThis, uLUN, fFlags, &pDrv);
4505 if (RT_SUCCESS(rc2))
4506 {
4507 PHDASTREAM pStream = hdaR3GetStreamFromSink(pThis, &pThis->SinkFront);
4508 if (DrvAudioHlpStreamCfgIsValid(&pStream->State.Cfg))
4509 hdaR3MixerAddDrvStream(pThis, pThis->SinkFront.pMixSink, &pStream->State.Cfg, pDrv);
4510
4511#ifdef VBOX_WITH_AUDIO_HDA_51_SURROUND
4512 pStream = hdaR3GetStreamFromSink(pThis, &pThis->SinkCenterLFE);
4513 if (DrvAudioHlpStreamCfgIsValid(&pStream->State.Cfg))
4514 hdaR3MixerAddDrvStream(pThis, pThis->SinkCenterLFE.pMixSink, &pStream->State.Cfg, pDrv);
4515
4516 pStream = hdaR3GetStreamFromSink(pThis, &pThis->SinkRear);
4517 if (DrvAudioHlpStreamCfgIsValid(&pStream->State.Cfg))
4518 hdaR3MixerAddDrvStream(pThis, pThis->SinkRear.pMixSink, &pStream->State.Cfg, pDrv);
4519#endif
4520 pStream = hdaR3GetStreamFromSink(pThis, &pThis->SinkLineIn);
4521 if (DrvAudioHlpStreamCfgIsValid(&pStream->State.Cfg))
4522 hdaR3MixerAddDrvStream(pThis, pThis->SinkLineIn.pMixSink, &pStream->State.Cfg, pDrv);
4523
4524#ifdef VBOX_WITH_AUDIO_HDA_MIC_IN
4525 pStream = hdaR3GetStreamFromSink(pThis, &pThis->SinkMicIn);
4526 if (DrvAudioHlpStreamCfgIsValid(&pStream->State.Cfg))
4527 hdaR3MixerAddDrvStream(pThis, pThis->SinkMicIn.pMixSink, &pStream->State.Cfg, pDrv);
4528#endif
4529 }
4530
4531 DEVHDA_UNLOCK(pThis);
4532
4533 return VINF_SUCCESS;
4534}
4535
4536/**
4537 * @interface_method_impl{PDMDEVREG,pfnDetach}
4538 */
4539static DECLCALLBACK(void) hdaR3Detach(PPDMDEVINS pDevIns, unsigned uLUN, uint32_t fFlags)
4540{
4541 PHDASTATE pThis = PDMINS_2_DATA(pDevIns, PHDASTATE);
4542
4543 DEVHDA_LOCK(pThis);
4544
4545 LogFunc(("uLUN=%u, fFlags=0x%x\n", uLUN, fFlags));
4546
4547 PHDADRIVER pDrv, pDrvNext;
4548 RTListForEachSafe(&pThis->lstDrv, pDrv, pDrvNext, HDADRIVER, Node)
4549 {
4550 if (pDrv->uLUN == uLUN)
4551 {
4552 int rc2 = hdaR3DetachInternal(pThis, pDrv, fFlags);
4553 if (RT_SUCCESS(rc2))
4554 {
4555 RTMemFree(pDrv);
4556 pDrv = NULL;
4557 }
4558
4559 break;
4560 }
4561 }
4562
4563 DEVHDA_UNLOCK(pThis);
4564}
4565
4566/**
4567 * Powers off the device.
4568 *
4569 * @param pDevIns Device instance to power off.
4570 */
4571static DECLCALLBACK(void) hdaR3PowerOff(PPDMDEVINS pDevIns)
4572{
4573 PHDASTATE pThis = PDMINS_2_DATA(pDevIns, PHDASTATE);
4574
4575 DEVHDA_LOCK_RETURN_VOID(pThis);
4576
4577 LogRel2(("HDA: Powering off ...\n"));
4578
4579 /* Ditto goes for the codec, which in turn uses the mixer. */
4580 hdaCodecPowerOff(pThis->pCodec);
4581
4582 /*
4583 * Note: Destroy the mixer while powering off and *not* in hdaR3Destruct,
4584 * giving the mixer the chance to release any references held to
4585 * PDM audio streams it maintains.
4586 */
4587 if (pThis->pMixer)
4588 {
4589 AudioMixerDestroy(pThis->pMixer);
4590 pThis->pMixer = NULL;
4591 }
4592
4593 DEVHDA_UNLOCK(pThis);
4594}
4595
4596
4597/**
4598 * Re-attaches (replaces) a driver with a new driver.
4599 *
4600 * This is only used by to attach the Null driver when it failed to attach the
4601 * one that was configured.
4602 *
4603 * @returns VBox status code.
4604 * @param pThis Device instance to re-attach driver to.
4605 * @param pDrv Driver instance used for attaching to.
4606 * If NULL is specified, a new driver will be created and appended
4607 * to the driver list.
4608 * @param uLUN The logical unit which is being re-detached.
4609 * @param pszDriver New driver name to attach.
4610 */
4611static int hdaR3ReattachInternal(PHDASTATE pThis, PHDADRIVER pDrv, uint8_t uLUN, const char *pszDriver)
4612{
4613 AssertPtrReturn(pThis, VERR_INVALID_POINTER);
4614 AssertPtrReturn(pszDriver, VERR_INVALID_POINTER);
4615
4616 int rc;
4617
4618 if (pDrv)
4619 {
4620 rc = hdaR3DetachInternal(pThis, pDrv, 0 /* fFlags */);
4621 if (RT_SUCCESS(rc))
4622 rc = PDMDevHlpDriverDetach(pThis->pDevInsR3, PDMIBASE_2_PDMDRV(pDrv->pDrvBase), 0 /* fFlags */);
4623
4624 if (RT_FAILURE(rc))
4625 return rc;
4626
4627 pDrv = NULL;
4628 }
4629
4630 PVM pVM = PDMDevHlpGetVM(pThis->pDevInsR3);
4631 PCFGMNODE pRoot = CFGMR3GetRoot(pVM);
4632 PCFGMNODE pDev0 = CFGMR3GetChild(pRoot, "Devices/hda/0/");
4633
4634 /* Remove LUN branch. */
4635 CFGMR3RemoveNode(CFGMR3GetChildF(pDev0, "LUN#%u/", uLUN));
4636
4637#define RC_CHECK() if (RT_FAILURE(rc)) { AssertReleaseRC(rc); break; }
4638
4639 do
4640 {
4641 PCFGMNODE pLunL0;
4642 rc = CFGMR3InsertNodeF(pDev0, &pLunL0, "LUN#%u/", uLUN); RC_CHECK();
4643 rc = CFGMR3InsertString(pLunL0, "Driver", "AUDIO"); RC_CHECK();
4644 rc = CFGMR3InsertNode(pLunL0, "Config/", NULL); RC_CHECK();
4645
4646 PCFGMNODE pLunL1, pLunL2;
4647 rc = CFGMR3InsertNode (pLunL0, "AttachedDriver/", &pLunL1); RC_CHECK();
4648 rc = CFGMR3InsertNode (pLunL1, "Config/", &pLunL2); RC_CHECK();
4649 rc = CFGMR3InsertString(pLunL1, "Driver", pszDriver); RC_CHECK();
4650
4651 rc = CFGMR3InsertString(pLunL2, "AudioDriver", pszDriver); RC_CHECK();
4652
4653 } while (0);
4654
4655 if (RT_SUCCESS(rc))
4656 rc = hdaR3AttachInternal(pThis, uLUN, 0 /* fFlags */, NULL /* ppDrv */);
4657
4658 LogFunc(("pThis=%p, uLUN=%u, pszDriver=%s, rc=%Rrc\n", pThis, uLUN, pszDriver, rc));
4659
4660#undef RC_CHECK
4661
4662 return rc;
4663}
4664
4665
4666/**
4667 * @interface_method_impl{PDMDEVREG,pfnReset}
4668 */
4669static DECLCALLBACK(void) hdaR3Reset(PPDMDEVINS pDevIns)
4670{
4671 PHDASTATE pThis = PDMINS_2_DATA(pDevIns, PHDASTATE);
4672
4673 LogFlowFuncEnter();
4674
4675 DEVHDA_LOCK_RETURN_VOID(pThis);
4676
4677 /*
4678 * 18.2.6,7 defines that values of this registers might be cleared on power on/reset
4679 * hdaR3Reset shouldn't affects these registers.
4680 */
4681 HDA_REG(pThis, WAKEEN) = 0x0;
4682
4683 hdaR3GCTLReset(pThis);
4684
4685 /* Indicate that HDA is not in reset. The firmware is supposed to (un)reset HDA,
4686 * but we can take a shortcut.
4687 */
4688 HDA_REG(pThis, GCTL) = HDA_GCTL_CRST;
4689
4690 DEVHDA_UNLOCK(pThis);
4691}
4692
4693
4694/**
4695 * @interface_method_impl{PDMDEVREG,pfnRelocate}
4696 */
4697static DECLCALLBACK(void) hdaR3Relocate(PPDMDEVINS pDevIns, RTGCINTPTR offDelta)
4698{
4699 NOREF(offDelta);
4700 PHDASTATE pThis = PDMINS_2_DATA(pDevIns, PHDASTATE);
4701 pThis->pDevInsRC = PDMDEVINS_2_RCPTR(pDevIns);
4702}
4703
4704
4705/**
4706 * @interface_method_impl{PDMDEVREG,pfnDestruct}
4707 */
4708static DECLCALLBACK(int) hdaR3Destruct(PPDMDEVINS pDevIns)
4709{
4710 PDMDEV_CHECK_VERSIONS_RETURN_QUIET(pDevIns); /* this shall come first */
4711 PHDASTATE pThis = PDMINS_2_DATA(pDevIns, PHDASTATE);
4712 DEVHDA_LOCK(pThis); /** @todo r=bird: this will fail on early constructor failure. */
4713
4714 PHDADRIVER pDrv;
4715 while (!RTListIsEmpty(&pThis->lstDrv))
4716 {
4717 pDrv = RTListGetFirst(&pThis->lstDrv, HDADRIVER, Node);
4718
4719 RTListNodeRemove(&pDrv->Node);
4720 RTMemFree(pDrv);
4721 }
4722
4723 if (pThis->pCodec)
4724 {
4725 hdaCodecDestruct(pThis->pCodec);
4726
4727 RTMemFree(pThis->pCodec);
4728 pThis->pCodec = NULL;
4729 }
4730
4731 RTMemFree(pThis->pu32CorbBuf);
4732 pThis->pu32CorbBuf = NULL;
4733
4734 RTMemFree(pThis->pu64RirbBuf);
4735 pThis->pu64RirbBuf = NULL;
4736
4737 for (uint8_t i = 0; i < HDA_MAX_STREAMS; i++)
4738 hdaR3StreamDestroy(&pThis->aStreams[i]);
4739
4740 DEVHDA_UNLOCK(pThis);
4741 return VINF_SUCCESS;
4742}
4743
4744
4745/**
4746 * @interface_method_impl{PDMDEVREG,pfnConstruct}
4747 */
4748static DECLCALLBACK(int) hdaR3Construct(PPDMDEVINS pDevIns, int iInstance, PCFGMNODE pCfg)
4749{
4750 PDMDEV_CHECK_VERSIONS_RETURN(pDevIns); /* this shall come first */
4751 PHDASTATE pThis = PDMINS_2_DATA(pDevIns, PHDASTATE);
4752 Assert(iInstance == 0); RT_NOREF(iInstance);
4753
4754 /*
4755 * Initialize the state sufficently to make the destructor work.
4756 */
4757 pThis->uAlignmentCheckMagic = HDASTATE_ALIGNMENT_CHECK_MAGIC;
4758 RTListInit(&pThis->lstDrv);
4759 /** @todo r=bird: There are probably other things which should be
4760 * initialized here before we start failing. */
4761
4762 /*
4763 * Validations.
4764 */
4765 if (!CFGMR3AreValuesValid(pCfg, "RZEnabled\0"
4766 "TimerHz\0"
4767 "PosAdjustEnabled\0"
4768 "PosAdjustFrames\0"
4769 "DebugEnabled\0"
4770 "DebugPathOut\0"))
4771 {
4772 return PDMDEV_SET_ERROR(pDevIns, VERR_PDM_DEVINS_UNKNOWN_CFG_VALUES,
4773 N_ ("Invalid configuration for the Intel HDA device"));
4774 }
4775
4776 int rc = CFGMR3QueryBoolDef(pCfg, "RZEnabled", &pThis->fRZEnabled, true);
4777 if (RT_FAILURE(rc))
4778 return PDMDEV_SET_ERROR(pDevIns, rc,
4779 N_("HDA configuration error: failed to read RCEnabled as boolean"));
4780
4781
4782 rc = CFGMR3QueryU16Def(pCfg, "TimerHz", &pThis->u16TimerHz, HDA_TIMER_HZ_DEFAULT /* Default value, if not set. */);
4783 if (RT_FAILURE(rc))
4784 return PDMDEV_SET_ERROR(pDevIns, rc,
4785 N_("HDA configuration error: failed to read Hertz (Hz) rate as unsigned integer"));
4786
4787 if (pThis->u16TimerHz != HDA_TIMER_HZ_DEFAULT)
4788 LogRel(("HDA: Using custom device timer rate (%RU16Hz)\n", pThis->u16TimerHz));
4789
4790 rc = CFGMR3QueryBoolDef(pCfg, "PosAdjustEnabled", &pThis->fPosAdjustEnabled, true);
4791 if (RT_FAILURE(rc))
4792 return PDMDEV_SET_ERROR(pDevIns, rc,
4793 N_("HDA configuration error: failed to read position adjustment enabled as boolean"));
4794
4795 if (!pThis->fPosAdjustEnabled)
4796 LogRel(("HDA: Position adjustment is disabled\n"));
4797
4798 rc = CFGMR3QueryU16Def(pCfg, "PosAdjustFrames", &pThis->cPosAdjustFrames, HDA_POS_ADJUST_DEFAULT);
4799 if (RT_FAILURE(rc))
4800 return PDMDEV_SET_ERROR(pDevIns, rc,
4801 N_("HDA configuration error: failed to read position adjustment frames as unsigned integer"));
4802
4803 if (pThis->cPosAdjustFrames)
4804 LogRel(("HDA: Using custom position adjustment (%RU16 audio frames)\n", pThis->cPosAdjustFrames));
4805
4806 rc = CFGMR3QueryBoolDef(pCfg, "DebugEnabled", &pThis->Dbg.fEnabled, false);
4807 if (RT_FAILURE(rc))
4808 return PDMDEV_SET_ERROR(pDevIns, rc,
4809 N_("HDA configuration error: failed to read debugging enabled flag as boolean"));
4810
4811 rc = CFGMR3QueryStringDef(pCfg, "DebugPathOut", pThis->Dbg.szOutPath, sizeof(pThis->Dbg.szOutPath),
4812 VBOX_AUDIO_DEBUG_DUMP_PCM_DATA_PATH);
4813 if (RT_FAILURE(rc))
4814 return PDMDEV_SET_ERROR(pDevIns, rc,
4815 N_("HDA configuration error: failed to read debugging output path flag as string"));
4816
4817 if (!strlen(pThis->Dbg.szOutPath))
4818 RTStrPrintf(pThis->Dbg.szOutPath, sizeof(pThis->Dbg.szOutPath), VBOX_AUDIO_DEBUG_DUMP_PCM_DATA_PATH);
4819
4820 if (pThis->Dbg.fEnabled)
4821 LogRel2(("HDA: Debug output will be saved to '%s'\n", pThis->Dbg.szOutPath));
4822
4823 /*
4824 * Use an own critical section for the device instead of the default
4825 * one provided by PDM. This allows fine-grained locking in combination
4826 * with TM when timer-specific stuff is being called in e.g. the MMIO handlers.
4827 */
4828 rc = PDMDevHlpCritSectInit(pDevIns, &pThis->CritSect, RT_SRC_POS, "HDA");
4829 AssertRCReturn(rc, rc);
4830
4831 rc = PDMDevHlpSetDeviceCritSect(pDevIns, PDMDevHlpCritSectGetNop(pDevIns));
4832 AssertRCReturn(rc, rc);
4833
4834 /*
4835 * Initialize data (most of it anyway).
4836 */
4837 pThis->pDevInsR3 = pDevIns;
4838 pThis->pDevInsR0 = PDMDEVINS_2_R0PTR(pDevIns);
4839 pThis->pDevInsRC = PDMDEVINS_2_RCPTR(pDevIns);
4840 /* IBase */
4841 pThis->IBase.pfnQueryInterface = hdaR3QueryInterface;
4842
4843 /* PCI Device */
4844 PCIDevSetVendorId (&pThis->PciDev, HDA_PCI_VENDOR_ID); /* nVidia */
4845 PCIDevSetDeviceId (&pThis->PciDev, HDA_PCI_DEVICE_ID); /* HDA */
4846
4847 PCIDevSetCommand (&pThis->PciDev, 0x0000); /* 04 rw,ro - pcicmd. */
4848 PCIDevSetStatus (&pThis->PciDev, VBOX_PCI_STATUS_CAP_LIST); /* 06 rwc?,ro? - pcists. */
4849 PCIDevSetRevisionId (&pThis->PciDev, 0x01); /* 08 ro - rid. */
4850 PCIDevSetClassProg (&pThis->PciDev, 0x00); /* 09 ro - pi. */
4851 PCIDevSetClassSub (&pThis->PciDev, 0x03); /* 0a ro - scc; 03 == HDA. */
4852 PCIDevSetClassBase (&pThis->PciDev, 0x04); /* 0b ro - bcc; 04 == multimedia. */
4853 PCIDevSetHeaderType (&pThis->PciDev, 0x00); /* 0e ro - headtyp. */
4854 PCIDevSetBaseAddress (&pThis->PciDev, 0, /* 10 rw - MMIO */
4855 false /* fIoSpace */, false /* fPrefetchable */, true /* f64Bit */, 0x00000000);
4856 PCIDevSetInterruptLine (&pThis->PciDev, 0x00); /* 3c rw. */
4857 PCIDevSetInterruptPin (&pThis->PciDev, 0x01); /* 3d ro - INTA#. */
4858
4859#if defined(HDA_AS_PCI_EXPRESS)
4860 PCIDevSetCapabilityList (&pThis->PciDev, 0x80);
4861#elif defined(VBOX_WITH_MSI_DEVICES)
4862 PCIDevSetCapabilityList (&pThis->PciDev, 0x60);
4863#else
4864 PCIDevSetCapabilityList (&pThis->PciDev, 0x50); /* ICH6 datasheet 18.1.16 */
4865#endif
4866
4867 /// @todo r=michaln: If there are really no PCIDevSetXx for these, the meaning
4868 /// of these values needs to be properly documented!
4869 /* HDCTL off 0x40 bit 0 selects signaling mode (1-HDA, 0 - Ac97) 18.1.19 */
4870 PCIDevSetByte(&pThis->PciDev, 0x40, 0x01);
4871
4872 /* Power Management */
4873 PCIDevSetByte(&pThis->PciDev, 0x50 + 0, VBOX_PCI_CAP_ID_PM);
4874 PCIDevSetByte(&pThis->PciDev, 0x50 + 1, 0x0); /* next */
4875 PCIDevSetWord(&pThis->PciDev, 0x50 + 2, VBOX_PCI_PM_CAP_DSI | 0x02 /* version, PM1.1 */ );
4876
4877#ifdef HDA_AS_PCI_EXPRESS
4878 /* PCI Express */
4879 PCIDevSetByte(&pThis->PciDev, 0x80 + 0, VBOX_PCI_CAP_ID_EXP); /* PCI_Express */
4880 PCIDevSetByte(&pThis->PciDev, 0x80 + 1, 0x60); /* next */
4881 /* Device flags */
4882 PCIDevSetWord(&pThis->PciDev, 0x80 + 2,
4883 /* version */ 0x1 |
4884 /* Root Complex Integrated Endpoint */ (VBOX_PCI_EXP_TYPE_ROOT_INT_EP << 4) |
4885 /* MSI */ (100) << 9 );
4886 /* Device capabilities */
4887 PCIDevSetDWord(&pThis->PciDev, 0x80 + 4, VBOX_PCI_EXP_DEVCAP_FLRESET);
4888 /* Device control */
4889 PCIDevSetWord( &pThis->PciDev, 0x80 + 8, 0);
4890 /* Device status */
4891 PCIDevSetWord( &pThis->PciDev, 0x80 + 10, 0);
4892 /* Link caps */
4893 PCIDevSetDWord(&pThis->PciDev, 0x80 + 12, 0);
4894 /* Link control */
4895 PCIDevSetWord( &pThis->PciDev, 0x80 + 16, 0);
4896 /* Link status */
4897 PCIDevSetWord( &pThis->PciDev, 0x80 + 18, 0);
4898 /* Slot capabilities */
4899 PCIDevSetDWord(&pThis->PciDev, 0x80 + 20, 0);
4900 /* Slot control */
4901 PCIDevSetWord( &pThis->PciDev, 0x80 + 24, 0);
4902 /* Slot status */
4903 PCIDevSetWord( &pThis->PciDev, 0x80 + 26, 0);
4904 /* Root control */
4905 PCIDevSetWord( &pThis->PciDev, 0x80 + 28, 0);
4906 /* Root capabilities */
4907 PCIDevSetWord( &pThis->PciDev, 0x80 + 30, 0);
4908 /* Root status */
4909 PCIDevSetDWord(&pThis->PciDev, 0x80 + 32, 0);
4910 /* Device capabilities 2 */
4911 PCIDevSetDWord(&pThis->PciDev, 0x80 + 36, 0);
4912 /* Device control 2 */
4913 PCIDevSetQWord(&pThis->PciDev, 0x80 + 40, 0);
4914 /* Link control 2 */
4915 PCIDevSetQWord(&pThis->PciDev, 0x80 + 48, 0);
4916 /* Slot control 2 */
4917 PCIDevSetWord( &pThis->PciDev, 0x80 + 56, 0);
4918#endif
4919
4920 /*
4921 * Register the PCI device.
4922 */
4923 rc = PDMDevHlpPCIRegister(pDevIns, &pThis->PciDev);
4924 if (RT_FAILURE(rc))
4925 return rc;
4926
4927 rc = PDMDevHlpPCIIORegionRegister(pDevIns, 0, 0x4000, PCI_ADDRESS_SPACE_MEM, hdaR3PciIoRegionMap);
4928 if (RT_FAILURE(rc))
4929 return rc;
4930
4931#ifdef VBOX_WITH_MSI_DEVICES
4932 PDMMSIREG MsiReg;
4933 RT_ZERO(MsiReg);
4934 MsiReg.cMsiVectors = 1;
4935 MsiReg.iMsiCapOffset = 0x60;
4936 MsiReg.iMsiNextOffset = 0x50;
4937 rc = PDMDevHlpPCIRegisterMsi(pDevIns, &MsiReg);
4938 if (RT_FAILURE(rc))
4939 {
4940 /* That's OK, we can work without MSI */
4941 PCIDevSetCapabilityList(&pThis->PciDev, 0x50);
4942 }
4943#endif
4944
4945 rc = PDMDevHlpSSMRegister(pDevIns, HDA_SSM_VERSION, sizeof(*pThis), hdaR3SaveExec, hdaR3LoadExec);
4946 if (RT_FAILURE(rc))
4947 return rc;
4948
4949#ifdef VBOX_WITH_AUDIO_HDA_ASYNC_IO
4950 LogRel(("HDA: Asynchronous I/O enabled\n"));
4951#endif
4952
4953 uint8_t uLUN;
4954 for (uLUN = 0; uLUN < UINT8_MAX; ++uLUN)
4955 {
4956 LogFunc(("Trying to attach driver for LUN #%RU32 ...\n", uLUN));
4957 rc = hdaR3AttachInternal(pThis, uLUN, 0 /* fFlags */, NULL /* ppDrv */);
4958 if (RT_FAILURE(rc))
4959 {
4960 if (rc == VERR_PDM_NO_ATTACHED_DRIVER)
4961 rc = VINF_SUCCESS;
4962 else if (rc == VERR_AUDIO_BACKEND_INIT_FAILED)
4963 {
4964 hdaR3ReattachInternal(pThis, NULL /* pDrv */, uLUN, "NullAudio");
4965 PDMDevHlpVMSetRuntimeError(pDevIns, 0 /*fFlags*/, "HostAudioNotResponding",
4966 N_("Host audio backend initialization has failed. Selecting the NULL audio backend "
4967 "with the consequence that no sound is audible"));
4968 /* Attaching to the NULL audio backend will never fail. */
4969 rc = VINF_SUCCESS;
4970 }
4971 break;
4972 }
4973 }
4974
4975 LogFunc(("cLUNs=%RU8, rc=%Rrc\n", uLUN, rc));
4976
4977 if (RT_SUCCESS(rc))
4978 {
4979 rc = AudioMixerCreate("HDA Mixer", 0 /* uFlags */, &pThis->pMixer);
4980 if (RT_SUCCESS(rc))
4981 {
4982 /*
4983 * Add mixer output sinks.
4984 */
4985#ifdef VBOX_WITH_AUDIO_HDA_51_SURROUND
4986 rc = AudioMixerCreateSink(pThis->pMixer, "[Playback] Front",
4987 AUDMIXSINKDIR_OUTPUT, &pThis->SinkFront.pMixSink);
4988 AssertRC(rc);
4989 rc = AudioMixerCreateSink(pThis->pMixer, "[Playback] Center / Subwoofer",
4990 AUDMIXSINKDIR_OUTPUT, &pThis->SinkCenterLFE.pMixSink);
4991 AssertRC(rc);
4992 rc = AudioMixerCreateSink(pThis->pMixer, "[Playback] Rear",
4993 AUDMIXSINKDIR_OUTPUT, &pThis->SinkRear.pMixSink);
4994 AssertRC(rc);
4995#else
4996 rc = AudioMixerCreateSink(pThis->pMixer, "[Playback] PCM Output",
4997 AUDMIXSINKDIR_OUTPUT, &pThis->SinkFront.pMixSink);
4998 AssertRC(rc);
4999#endif
5000 /*
5001 * Add mixer input sinks.
5002 */
5003 rc = AudioMixerCreateSink(pThis->pMixer, "[Recording] Line In",
5004 AUDMIXSINKDIR_INPUT, &pThis->SinkLineIn.pMixSink);
5005 AssertRC(rc);
5006#ifdef VBOX_WITH_AUDIO_HDA_MIC_IN
5007 rc = AudioMixerCreateSink(pThis->pMixer, "[Recording] Microphone In",
5008 AUDMIXSINKDIR_INPUT, &pThis->SinkMicIn.pMixSink);
5009 AssertRC(rc);
5010#endif
5011 /* There is no master volume control. Set the master to max. */
5012 PDMAUDIOVOLUME vol = { false, 255, 255 };
5013 rc = AudioMixerSetMasterVolume(pThis->pMixer, &vol);
5014 AssertRC(rc);
5015 }
5016 }
5017
5018 if (RT_SUCCESS(rc))
5019 {
5020 /* Allocate CORB buffer. */
5021 pThis->cbCorbBuf = HDA_CORB_SIZE * HDA_CORB_ELEMENT_SIZE;
5022 pThis->pu32CorbBuf = (uint32_t *)RTMemAllocZ(pThis->cbCorbBuf);
5023 if (pThis->pu32CorbBuf)
5024 {
5025 /* Allocate RIRB buffer. */
5026 pThis->cbRirbBuf = HDA_RIRB_SIZE * HDA_RIRB_ELEMENT_SIZE;
5027 pThis->pu64RirbBuf = (uint64_t *)RTMemAllocZ(pThis->cbRirbBuf);
5028 if (pThis->pu64RirbBuf)
5029 {
5030 /* Allocate codec. */
5031 pThis->pCodec = (PHDACODEC)RTMemAllocZ(sizeof(HDACODEC));
5032 if (!pThis->pCodec)
5033 rc = PDMDEV_SET_ERROR(pDevIns, VERR_NO_MEMORY, N_("Out of memory allocating HDA codec state"));
5034 }
5035 else
5036 rc = PDMDEV_SET_ERROR(pDevIns, VERR_NO_MEMORY, N_("Out of memory allocating RIRB"));
5037 }
5038 else
5039 rc = PDMDEV_SET_ERROR(pDevIns, VERR_NO_MEMORY, N_("Out of memory allocating CORB"));
5040
5041 if (RT_SUCCESS(rc))
5042 {
5043 /* Set codec callbacks to this controller. */
5044 pThis->pCodec->pfnCbMixerAddStream = hdaR3MixerAddStream;
5045 pThis->pCodec->pfnCbMixerRemoveStream = hdaR3MixerRemoveStream;
5046 pThis->pCodec->pfnCbMixerControl = hdaR3MixerControl;
5047 pThis->pCodec->pfnCbMixerSetVolume = hdaR3MixerSetVolume;
5048
5049 pThis->pCodec->pHDAState = pThis; /* Assign HDA controller state to codec. */
5050
5051 /* Construct the codec. */
5052 rc = hdaCodecConstruct(pDevIns, pThis->pCodec, 0 /* Codec index */, pCfg);
5053 if (RT_FAILURE(rc))
5054 AssertRCReturn(rc, rc);
5055
5056 /* ICH6 datasheet defines 0 values for SVID and SID (18.1.14-15), which together with values returned for
5057 verb F20 should provide device/codec recognition. */
5058 Assert(pThis->pCodec->u16VendorId);
5059 Assert(pThis->pCodec->u16DeviceId);
5060 PCIDevSetSubSystemVendorId(&pThis->PciDev, pThis->pCodec->u16VendorId); /* 2c ro - intel.) */
5061 PCIDevSetSubSystemId( &pThis->PciDev, pThis->pCodec->u16DeviceId); /* 2e ro. */
5062 }
5063 }
5064
5065 if (RT_SUCCESS(rc))
5066 {
5067 /*
5068 * Create all hardware streams.
5069 */
5070 for (uint8_t i = 0; i < HDA_MAX_STREAMS; ++i)
5071 {
5072 /* Create the emulation timer (per stream).
5073 *
5074 * Note: Use TMCLOCK_VIRTUAL_SYNC here, as the guest's HDA driver
5075 * relies on exact (virtual) DMA timing and uses DMA Position Buffers
5076 * instead of the LPIB registers.
5077 */
5078 char szTimer[16];
5079 RTStrPrintf2(szTimer, sizeof(szTimer), "HDA SD%RU8", i);
5080
5081 rc = PDMDevHlpTMTimerCreate(pDevIns, TMCLOCK_VIRTUAL_SYNC, hdaR3Timer, &pThis->aStreams[i],
5082 TMTIMER_FLAGS_NO_CRIT_SECT, szTimer, &pThis->pTimer[i]);
5083 AssertRCReturn(rc, rc);
5084
5085 /* Use our own critcal section for the device timer.
5086 * That way we can control more fine-grained when to lock what. */
5087 rc = TMR3TimerSetCritSect(pThis->pTimer[i], &pThis->CritSect);
5088 AssertRCReturn(rc, rc);
5089
5090 rc = hdaR3StreamCreate(&pThis->aStreams[i], pThis, i /* u8SD */);
5091 AssertRC(rc);
5092 }
5093
5094#ifdef VBOX_WITH_AUDIO_HDA_ONETIME_INIT
5095 /*
5096 * Initialize the driver chain.
5097 */
5098 PHDADRIVER pDrv;
5099 RTListForEach(&pThis->lstDrv, pDrv, HDADRIVER, Node)
5100 {
5101 /*
5102 * Only primary drivers are critical for the VM to run. Everything else
5103 * might not worth showing an own error message box in the GUI.
5104 */
5105 if (!(pDrv->fFlags & PDMAUDIODRVFLAGS_PRIMARY))
5106 continue;
5107
5108 PPDMIAUDIOCONNECTOR pCon = pDrv->pConnector;
5109 AssertPtr(pCon);
5110
5111 bool fValidLineIn = AudioMixerStreamIsValid(pDrv->LineIn.pMixStrm);
5112# ifdef VBOX_WITH_AUDIO_HDA_MIC_IN
5113 bool fValidMicIn = AudioMixerStreamIsValid(pDrv->MicIn.pMixStrm);
5114# endif
5115 bool fValidOut = AudioMixerStreamIsValid(pDrv->Front.pMixStrm);
5116# ifdef VBOX_WITH_AUDIO_HDA_51_SURROUND
5117 /** @todo Anything to do here? */
5118# endif
5119
5120 if ( !fValidLineIn
5121# ifdef VBOX_WITH_AUDIO_HDA_MIC_IN
5122 && !fValidMicIn
5123# endif
5124 && !fValidOut)
5125 {
5126 LogRel(("HDA: Falling back to NULL backend (no sound audible)\n"));
5127
5128 hdaR3Reset(pDevIns);
5129 hdaR3ReattachInternal(pThis, pDrv, pDrv->uLUN, "NullAudio");
5130
5131 PDMDevHlpVMSetRuntimeError(pDevIns, 0 /*fFlags*/, "HostAudioNotResponding",
5132 N_("No audio devices could be opened. Selecting the NULL audio backend "
5133 "with the consequence that no sound is audible"));
5134 }
5135 else
5136 {
5137 bool fWarn = false;
5138
5139 PDMAUDIOBACKENDCFG backendCfg;
5140 int rc2 = pCon->pfnGetConfig(pCon, &backendCfg);
5141 if (RT_SUCCESS(rc2))
5142 {
5143 if (backendCfg.cMaxStreamsIn)
5144 {
5145# ifdef VBOX_WITH_AUDIO_HDA_MIC_IN
5146 /* If the audio backend supports two or more input streams at once,
5147 * warn if one of our two inputs (microphone-in and line-in) failed to initialize. */
5148 if (backendCfg.cMaxStreamsIn >= 2)
5149 fWarn = !fValidLineIn || !fValidMicIn;
5150 /* If the audio backend only supports one input stream at once (e.g. pure ALSA, and
5151 * *not* ALSA via PulseAudio plugin!), only warn if both of our inputs failed to initialize.
5152 * One of the two simply is not in use then. */
5153 else if (backendCfg.cMaxStreamsIn == 1)
5154 fWarn = !fValidLineIn && !fValidMicIn;
5155 /* Don't warn if our backend is not able of supporting any input streams at all. */
5156# else /* !VBOX_WITH_AUDIO_HDA_MIC_IN */
5157 /* We only have line-in as input source. */
5158 fWarn = !fValidLineIn;
5159# endif /* VBOX_WITH_AUDIO_HDA_MIC_IN */
5160 }
5161
5162 if ( !fWarn
5163 && backendCfg.cMaxStreamsOut)
5164 {
5165 fWarn = !fValidOut;
5166 }
5167 }
5168 else
5169 {
5170 LogRel(("HDA: Unable to retrieve audio backend configuration for LUN #%RU8, rc=%Rrc\n", pDrv->uLUN, rc2));
5171 fWarn = true;
5172 }
5173
5174 if (fWarn)
5175 {
5176 char szMissingStreams[255];
5177 size_t len = 0;
5178 if (!fValidLineIn)
5179 {
5180 LogRel(("HDA: WARNING: Unable to open PCM line input for LUN #%RU8!\n", pDrv->uLUN));
5181 len = RTStrPrintf(szMissingStreams, sizeof(szMissingStreams), "PCM Input");
5182 }
5183# ifdef VBOX_WITH_AUDIO_HDA_MIC_IN
5184 if (!fValidMicIn)
5185 {
5186 LogRel(("HDA: WARNING: Unable to open PCM microphone input for LUN #%RU8!\n", pDrv->uLUN));
5187 len += RTStrPrintf(szMissingStreams + len,
5188 sizeof(szMissingStreams) - len, len ? ", PCM Microphone" : "PCM Microphone");
5189 }
5190# endif /* VBOX_WITH_AUDIO_HDA_MIC_IN */
5191 if (!fValidOut)
5192 {
5193 LogRel(("HDA: WARNING: Unable to open PCM output for LUN #%RU8!\n", pDrv->uLUN));
5194 len += RTStrPrintf(szMissingStreams + len,
5195 sizeof(szMissingStreams) - len, len ? ", PCM Output" : "PCM Output");
5196 }
5197
5198 PDMDevHlpVMSetRuntimeError(pDevIns, 0 /*fFlags*/, "HostAudioNotResponding",
5199 N_("Some HDA audio streams (%s) could not be opened. Guest applications generating audio "
5200 "output or depending on audio input may hang. Make sure your host audio device "
5201 "is working properly. Check the logfile for error messages of the audio "
5202 "subsystem"), szMissingStreams);
5203 }
5204 }
5205 }
5206#endif /* VBOX_WITH_AUDIO_HDA_ONETIME_INIT */
5207 }
5208
5209 if (RT_SUCCESS(rc))
5210 {
5211 hdaR3Reset(pDevIns);
5212
5213 /*
5214 * Debug and string formatter types.
5215 */
5216 PDMDevHlpDBGFInfoRegister(pDevIns, "hda", "HDA info. (hda [register case-insensitive])", hdaR3DbgInfo);
5217 PDMDevHlpDBGFInfoRegister(pDevIns, "hdabdle", "HDA stream BDLE info. (hdabdle [stream number])", hdaR3DbgInfoBDLE);
5218 PDMDevHlpDBGFInfoRegister(pDevIns, "hdastream", "HDA stream info. (hdastream [stream number])", hdaR3DbgInfoStream);
5219 PDMDevHlpDBGFInfoRegister(pDevIns, "hdcnodes", "HDA codec nodes.", hdaR3DbgInfoCodecNodes);
5220 PDMDevHlpDBGFInfoRegister(pDevIns, "hdcselector", "HDA codec's selector states [node number].", hdaR3DbgInfoCodecSelector);
5221 PDMDevHlpDBGFInfoRegister(pDevIns, "hdamixer", "HDA mixer state.", hdaR3DbgInfoMixer);
5222
5223 rc = RTStrFormatTypeRegister("bdle", hdaR3StrFmtBDLE, NULL);
5224 AssertRC(rc);
5225 rc = RTStrFormatTypeRegister("sdctl", hdaR3StrFmtSDCTL, NULL);
5226 AssertRC(rc);
5227 rc = RTStrFormatTypeRegister("sdsts", hdaR3StrFmtSDSTS, NULL);
5228 AssertRC(rc);
5229 rc = RTStrFormatTypeRegister("sdfifos", hdaR3StrFmtSDFIFOS, NULL);
5230 AssertRC(rc);
5231 rc = RTStrFormatTypeRegister("sdfifow", hdaR3StrFmtSDFIFOW, NULL);
5232 AssertRC(rc);
5233
5234 /*
5235 * Some debug assertions.
5236 */
5237 for (unsigned i = 0; i < RT_ELEMENTS(g_aHdaRegMap); i++)
5238 {
5239 struct HDAREGDESC const *pReg = &g_aHdaRegMap[i];
5240 struct HDAREGDESC const *pNextReg = i + 1 < RT_ELEMENTS(g_aHdaRegMap) ? &g_aHdaRegMap[i + 1] : NULL;
5241
5242 /* binary search order. */
5243 AssertReleaseMsg(!pNextReg || pReg->offset + pReg->size <= pNextReg->offset,
5244 ("[%#x] = {%#x LB %#x} vs. [%#x] = {%#x LB %#x}\n",
5245 i, pReg->offset, pReg->size, i + 1, pNextReg->offset, pNextReg->size));
5246
5247 /* alignment. */
5248 AssertReleaseMsg( pReg->size == 1
5249 || (pReg->size == 2 && (pReg->offset & 1) == 0)
5250 || (pReg->size == 3 && (pReg->offset & 3) == 0)
5251 || (pReg->size == 4 && (pReg->offset & 3) == 0),
5252 ("[%#x] = {%#x LB %#x}\n", i, pReg->offset, pReg->size));
5253
5254 /* registers are packed into dwords - with 3 exceptions with gaps at the end of the dword. */
5255 AssertRelease(((pReg->offset + pReg->size) & 3) == 0 || pNextReg);
5256 if (pReg->offset & 3)
5257 {
5258 struct HDAREGDESC const *pPrevReg = i > 0 ? &g_aHdaRegMap[i - 1] : NULL;
5259 AssertReleaseMsg(pPrevReg, ("[%#x] = {%#x LB %#x}\n", i, pReg->offset, pReg->size));
5260 if (pPrevReg)
5261 AssertReleaseMsg(pPrevReg->offset + pPrevReg->size == pReg->offset,
5262 ("[%#x] = {%#x LB %#x} vs. [%#x] = {%#x LB %#x}\n",
5263 i - 1, pPrevReg->offset, pPrevReg->size, i + 1, pReg->offset, pReg->size));
5264 }
5265#if 0
5266 if ((pReg->offset + pReg->size) & 3)
5267 {
5268 AssertReleaseMsg(pNextReg, ("[%#x] = {%#x LB %#x}\n", i, pReg->offset, pReg->size));
5269 if (pNextReg)
5270 AssertReleaseMsg(pReg->offset + pReg->size == pNextReg->offset,
5271 ("[%#x] = {%#x LB %#x} vs. [%#x] = {%#x LB %#x}\n",
5272 i, pReg->offset, pReg->size, i + 1, pNextReg->offset, pNextReg->size));
5273 }
5274#endif
5275 /* The final entry is a full DWORD, no gaps! Allows shortcuts. */
5276 AssertReleaseMsg(pNextReg || ((pReg->offset + pReg->size) & 3) == 0,
5277 ("[%#x] = {%#x LB %#x}\n", i, pReg->offset, pReg->size));
5278 }
5279 }
5280
5281# ifdef VBOX_WITH_STATISTICS
5282 if (RT_SUCCESS(rc))
5283 {
5284 /*
5285 * Register statistics.
5286 */
5287 PDMDevHlpSTAMRegister(pDevIns, &pThis->StatTimer, STAMTYPE_PROFILE, "/Devices/HDA/Timer", STAMUNIT_TICKS_PER_CALL, "Profiling hdaR3Timer.");
5288 PDMDevHlpSTAMRegister(pDevIns, &pThis->StatIn, STAMTYPE_PROFILE, "/Devices/HDA/Input", STAMUNIT_TICKS_PER_CALL, "Profiling input.");
5289 PDMDevHlpSTAMRegister(pDevIns, &pThis->StatOut, STAMTYPE_PROFILE, "/Devices/HDA/Output", STAMUNIT_TICKS_PER_CALL, "Profiling output.");
5290 PDMDevHlpSTAMRegister(pDevIns, &pThis->StatBytesRead, STAMTYPE_COUNTER, "/Devices/HDA/BytesRead" , STAMUNIT_BYTES, "Bytes read from HDA emulation.");
5291 PDMDevHlpSTAMRegister(pDevIns, &pThis->StatBytesWritten, STAMTYPE_COUNTER, "/Devices/HDA/BytesWritten", STAMUNIT_BYTES, "Bytes written to HDA emulation.");
5292 }
5293# endif
5294
5295 LogFlowFuncLeaveRC(rc);
5296 return rc;
5297}
5298
5299/**
5300 * The device registration structure.
5301 */
5302const PDMDEVREG g_DeviceHDA =
5303{
5304 /* u32Version */
5305 PDM_DEVREG_VERSION,
5306 /* szName */
5307 "hda",
5308 /* szRCMod */
5309 "VBoxDDRC.rc",
5310 /* szR0Mod */
5311 "VBoxDDR0.r0",
5312 /* pszDescription */
5313 "Intel HD Audio Controller",
5314 /* fFlags */
5315 PDM_DEVREG_FLAGS_DEFAULT_BITS | PDM_DEVREG_FLAGS_RC | PDM_DEVREG_FLAGS_R0,
5316 /* fClass */
5317 PDM_DEVREG_CLASS_AUDIO,
5318 /* cMaxInstances */
5319 1,
5320 /* cbInstance */
5321 sizeof(HDASTATE),
5322 /* pfnConstruct */
5323 hdaR3Construct,
5324 /* pfnDestruct */
5325 hdaR3Destruct,
5326 /* pfnRelocate */
5327 hdaR3Relocate,
5328 /* pfnMemSetup */
5329 NULL,
5330 /* pfnPowerOn */
5331 NULL,
5332 /* pfnReset */
5333 hdaR3Reset,
5334 /* pfnSuspend */
5335 NULL,
5336 /* pfnResume */
5337 NULL,
5338 /* pfnAttach */
5339 hdaR3Attach,
5340 /* pfnDetach */
5341 hdaR3Detach,
5342 /* pfnQueryInterface. */
5343 NULL,
5344 /* pfnInitComplete */
5345 NULL,
5346 /* pfnPowerOff */
5347 hdaR3PowerOff,
5348 /* pfnSoftReset */
5349 NULL,
5350 /* u32VersionEnd */
5351 PDM_DEVREG_VERSION
5352};
5353
5354#endif /* IN_RING3 */
5355#endif /* !VBOX_DEVICE_STRUCT_TESTCASE */
5356
Note: See TracBrowser for help on using the repository browser.

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