VirtualBox

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

Last change on this file since 73639 was 73565, checked in by vboxsync, 6 years ago

Audio/HDA: Also (verbose) log the LUN# of the changed recording source.

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