VirtualBox

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

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

DevHDA.cpp: build fix and more logging.

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

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