VirtualBox

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

Last change on this file since 78268 was 76553, checked in by vboxsync, 6 years ago

scm --update-copyright-year

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