VirtualBox

source: vbox/trunk/src/VBox/Devices/Audio/DevIchAc97.cpp@ 89691

Last change on this file since 89691 was 89691, checked in by vboxsync, 3 years ago

DevIchAc97: Addressed the incorrect LVI understanding from ichac97R3DbgPrintBdl used in ichac97R3StreamOpen. Explained why ichac97R3StreamFetchNextBdle will start with BDLE00 after a stream reset (PVI=0). Some paranoia. bugref:9890

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 174.0 KB
Line 
1/* $Id: DevIchAc97.cpp 89691 2021-06-14 20:01:32Z vboxsync $ */
2/** @file
3 * DevIchAc97 - VBox ICH AC97 Audio Controller.
4 */
5
6/*
7 * Copyright (C) 2006-2020 Oracle Corporation
8 *
9 * This file is part of VirtualBox Open Source Edition (OSE), as
10 * available from http://www.virtualbox.org. This file is free software;
11 * you can redistribute it and/or modify it under the terms of the GNU
12 * General Public License (GPL) as published by the Free Software
13 * Foundation, in version 2 as it comes in the "COPYING" file of the
14 * VirtualBox OSE distribution. VirtualBox OSE is distributed in the
15 * hope that it will be useful, but WITHOUT ANY WARRANTY of any kind.
16 */
17
18
19/*********************************************************************************************************************************
20* Header Files *
21*********************************************************************************************************************************/
22#define LOG_GROUP LOG_GROUP_DEV_AC97
23#include <VBox/log.h>
24#include <VBox/vmm/pdmdev.h>
25#include <VBox/vmm/pdmaudioifs.h>
26#include <VBox/vmm/pdmaudioinline.h>
27#include <VBox/AssertGuest.h>
28
29#include <iprt/assert.h>
30#ifdef IN_RING3
31# ifdef DEBUG
32# include <iprt/file.h>
33# endif
34# include <iprt/mem.h>
35# include <iprt/semaphore.h>
36# include <iprt/string.h>
37# include <iprt/uuid.h>
38#endif
39
40#include "VBoxDD.h"
41
42#include "AudioMixBuffer.h"
43#include "AudioMixer.h"
44#include "AudioHlp.h"
45
46
47/*********************************************************************************************************************************
48* Defined Constants And Macros *
49*********************************************************************************************************************************/
50/** Current saved state version. */
51#define AC97_SAVED_STATE_VERSION 1
52
53/** Default timer frequency (in Hz). */
54#define AC97_TIMER_HZ_DEFAULT 100
55
56/** Maximum number of streams we support. */
57#define AC97_MAX_STREAMS 3
58
59/** Maximum FIFO size (in bytes) - unused. */
60#define AC97_FIFO_MAX 256
61
62/** @name AC97_SR_XXX - Status Register Bits (AC97_NABM_OFF_SR, PI_SR, PO_SR, MC_SR).
63 * @{ */
64#define AC97_SR_FIFOE RT_BIT(4) /**< rwc, FIFO error. */
65#define AC97_SR_BCIS RT_BIT(3) /**< rwc, Buffer completion interrupt status. */
66#define AC97_SR_LVBCI RT_BIT(2) /**< rwc, Last valid buffer completion interrupt. */
67#define AC97_SR_CELV RT_BIT(1) /**< ro, Current equals last valid. */
68#define AC97_SR_DCH RT_BIT(0) /**< ro, Controller halted. */
69#define AC97_SR_VALID_MASK (RT_BIT(5) - 1)
70#define AC97_SR_WCLEAR_MASK (AC97_SR_FIFOE | AC97_SR_BCIS | AC97_SR_LVBCI)
71#define AC97_SR_RO_MASK (AC97_SR_DCH | AC97_SR_CELV)
72#define AC97_SR_INT_MASK (AC97_SR_FIFOE | AC97_SR_BCIS | AC97_SR_LVBCI)
73/** @} */
74
75/** @name AC97_CR_XXX - Control Register Bits (AC97_NABM_OFF_CR, PI_CR, PO_CR, MC_CR).
76 * @{ */
77#define AC97_CR_IOCE RT_BIT(4) /**< rw, Interrupt On Completion Enable. */
78#define AC97_CR_FEIE RT_BIT(3) /**< rw FIFO Error Interrupt Enable. */
79#define AC97_CR_LVBIE RT_BIT(2) /**< rw Last Valid Buffer Interrupt Enable. */
80#define AC97_CR_RR RT_BIT(1) /**< rw Reset Registers. */
81#define AC97_CR_RPBM RT_BIT(0) /**< rw Run/Pause Bus Master. */
82#define AC97_CR_VALID_MASK (RT_BIT(5) - 1)
83#define AC97_CR_DONT_CLEAR_MASK (AC97_CR_IOCE | AC97_CR_FEIE | AC97_CR_LVBIE)
84/** @} */
85
86/** @name AC97_GC_XXX - Global Control Bits (see AC97_GLOB_CNT). */
87#define AC97_GC_WR 4 /**< rw Warm reset. */
88#define AC97_GC_CR 2 /**< rw Cold reset. */
89#define AC97_GC_VALID_MASK (RT_BIT(6) - 1)
90/** @} */
91
92/** @name AC97_GS_XXX - Global Status Bits (AC97_GLOB_STA).
93 * @{ */
94#define AC97_GS_MD3 RT_BIT(17) /**< rw */
95#define AC97_GS_AD3 RT_BIT(16) /**< rw */
96#define AC97_GS_RCS RT_BIT(15) /**< rwc */
97#define AC97_GS_B3S12 RT_BIT(14) /**< ro */
98#define AC97_GS_B2S12 RT_BIT(13) /**< ro */
99#define AC97_GS_B1S12 RT_BIT(12) /**< ro */
100#define AC97_GS_S1R1 RT_BIT(11) /**< rwc */
101#define AC97_GS_S0R1 RT_BIT(10) /**< rwc */
102#define AC97_GS_S1CR RT_BIT(9) /**< ro */
103#define AC97_GS_S0CR RT_BIT(8) /**< ro */
104#define AC97_GS_MINT RT_BIT(7) /**< ro */
105#define AC97_GS_POINT RT_BIT(6) /**< ro */
106#define AC97_GS_PIINT RT_BIT(5) /**< ro */
107#define AC97_GS_RSRVD (RT_BIT(4) | RT_BIT(3))
108#define AC97_GS_MOINT RT_BIT(2) /**< ro */
109#define AC97_GS_MIINT RT_BIT(1) /**< ro */
110#define AC97_GS_GSCI RT_BIT(0) /**< rwc */
111#define AC97_GS_RO_MASK ( AC97_GS_B3S12 \
112 | AC97_GS_B2S12 \
113 | AC97_GS_B1S12 \
114 | AC97_GS_S1CR \
115 | AC97_GS_S0CR \
116 | AC97_GS_MINT \
117 | AC97_GS_POINT \
118 | AC97_GS_PIINT \
119 | AC97_GS_RSRVD \
120 | AC97_GS_MOINT \
121 | AC97_GS_MIINT)
122#define AC97_GS_VALID_MASK (RT_BIT(18) - 1)
123#define AC97_GS_WCLEAR_MASK (AC97_GS_RCS | AC97_GS_S1R1 | AC97_GS_S0R1 | AC97_GS_GSCI)
124/** @} */
125
126/** @name Buffer Descriptor (BDLE, BDL).
127 * @{ */
128#define AC97_BD_IOC RT_BIT(31) /**< Interrupt on Completion. */
129#define AC97_BD_BUP RT_BIT(30) /**< Buffer Underrun Policy. */
130
131#define AC97_BD_LEN_MASK 0xFFFF /**< Mask for the BDL buffer length. */
132
133#define AC97_BD_LEN_CTL_MBZ UINT32_C(0x3fff0000) /**< Must-be-zero mask for AC97BDLE.ctl_len. */
134
135#define AC97_MAX_BDLE 32 /**< Maximum number of BDLEs. */
136/** @} */
137
138/** @name Extended Audio ID Register (EAID).
139 * @{ */
140#define AC97_EAID_VRA RT_BIT(0) /**< Variable Rate Audio. */
141#define AC97_EAID_VRM RT_BIT(3) /**< Variable Rate Mic Audio. */
142#define AC97_EAID_REV0 RT_BIT(10) /**< AC'97 revision compliance. */
143#define AC97_EAID_REV1 RT_BIT(11) /**< AC'97 revision compliance. */
144/** @} */
145
146/** @name Extended Audio Control and Status Register (EACS).
147 * @{ */
148#define AC97_EACS_VRA RT_BIT(0) /**< Variable Rate Audio (4.2.1.1). */
149#define AC97_EACS_VRM RT_BIT(3) /**< Variable Rate Mic Audio (4.2.1.1). */
150/** @} */
151
152/** @name Baseline Audio Register Set (BARS).
153 * @{ */
154#define AC97_BARS_VOL_MASK 0x1f /**< Volume mask for the Baseline Audio Register Set (5.7.2). */
155#define AC97_BARS_GAIN_MASK 0x0f /**< Gain mask for the Baseline Audio Register Set. */
156#define AC97_BARS_VOL_MUTE_SHIFT 15 /**< Mute bit shift for the Baseline Audio Register Set (5.7.2). */
157/** @} */
158
159/** AC'97 uses 1.5dB steps, we use 0.375dB steps: 1 AC'97 step equals 4 PDM steps. */
160#define AC97_DB_FACTOR 4
161
162/** @name Recording inputs?
163 * @{ */
164#define AC97_REC_MIC UINT8_C(0)
165#define AC97_REC_CD UINT8_C(1)
166#define AC97_REC_VIDEO UINT8_C(2)
167#define AC97_REC_AUX UINT8_C(3)
168#define AC97_REC_LINE_IN UINT8_C(4)
169#define AC97_REC_STEREO_MIX UINT8_C(5)
170#define AC97_REC_MONO_MIX UINT8_C(6)
171#define AC97_REC_PHONE UINT8_C(7)
172#define AC97_REC_MASK UINT8_C(7)
173/** @} */
174
175/** @name Mixer registers / NAM BAR registers?
176 * @{ */
177#define AC97_Reset 0x00
178#define AC97_Master_Volume_Mute 0x02
179#define AC97_Headphone_Volume_Mute 0x04 /**< Also known as AUX, see table 16, section 5.7. */
180#define AC97_Master_Volume_Mono_Mute 0x06
181#define AC97_Master_Tone_RL 0x08
182#define AC97_PC_BEEP_Volume_Mute 0x0a
183#define AC97_Phone_Volume_Mute 0x0c
184#define AC97_Mic_Volume_Mute 0x0e
185#define AC97_Line_In_Volume_Mute 0x10
186#define AC97_CD_Volume_Mute 0x12
187#define AC97_Video_Volume_Mute 0x14
188#define AC97_Aux_Volume_Mute 0x16
189#define AC97_PCM_Out_Volume_Mute 0x18
190#define AC97_Record_Select 0x1a
191#define AC97_Record_Gain_Mute 0x1c
192#define AC97_Record_Gain_Mic_Mute 0x1e
193#define AC97_General_Purpose 0x20
194#define AC97_3D_Control 0x22
195#define AC97_AC_97_RESERVED 0x24
196#define AC97_Powerdown_Ctrl_Stat 0x26
197#define AC97_Extended_Audio_ID 0x28
198#define AC97_Extended_Audio_Ctrl_Stat 0x2a
199#define AC97_PCM_Front_DAC_Rate 0x2c
200#define AC97_PCM_Surround_DAC_Rate 0x2e
201#define AC97_PCM_LFE_DAC_Rate 0x30
202#define AC97_PCM_LR_ADC_Rate 0x32
203#define AC97_MIC_ADC_Rate 0x34
204#define AC97_6Ch_Vol_C_LFE_Mute 0x36
205#define AC97_6Ch_Vol_L_R_Surround_Mute 0x38
206#define AC97_Vendor_Reserved 0x58
207#define AC97_AD_Misc 0x76
208#define AC97_Vendor_ID1 0x7c
209#define AC97_Vendor_ID2 0x7e
210/** @} */
211
212/** @name Analog Devices miscellaneous regiter bits used in AD1980.
213 * @{ */
214#define AC97_AD_MISC_LOSEL RT_BIT(5) /**< Surround (rear) goes to line out outputs. */
215#define AC97_AD_MISC_HPSEL RT_BIT(10) /**< PCM (front) goes to headphone outputs. */
216/** @} */
217
218
219/** @name BUP flag values.
220 * @{ */
221#define BUP_SET RT_BIT_32(0)
222#define BUP_LAST RT_BIT_32(1)
223/** @} */
224
225/** @name AC'97 source indices.
226 * @note The order of these indices is fixed (also applies for saved states) for
227 * the moment. So make sure you know what you're done when altering this!
228 * @{
229 */
230#define AC97SOUNDSOURCE_PI_INDEX 0 /**< PCM in */
231#define AC97SOUNDSOURCE_PO_INDEX 1 /**< PCM out */
232#define AC97SOUNDSOURCE_MC_INDEX 2 /**< Mic in */
233#define AC97SOUNDSOURCE_MAX 3 /**< Max sound sources. */
234/** @} */
235
236/** Port number (offset into NABM BAR) to stream index. */
237#define AC97_PORT2IDX(a_idx) ( ((a_idx) >> 4) & 3 )
238/** Port number (offset into NABM BAR) to stream index, but no masking. */
239#define AC97_PORT2IDX_UNMASKED(a_idx) ( ((a_idx) >> 4) )
240
241/** @name Stream offsets
242 * @{ */
243#define AC97_NABM_OFF_BDBAR 0x0 /**< Buffer Descriptor Base Address */
244#define AC97_NABM_OFF_CIV 0x4 /**< Current Index Value */
245#define AC97_NABM_OFF_LVI 0x5 /**< Last Valid Index */
246#define AC97_NABM_OFF_SR 0x6 /**< Status Register */
247#define AC97_NABM_OFF_PICB 0x8 /**< Position in Current Buffer */
248#define AC97_NABM_OFF_PIV 0xa /**< Prefetched Index Value */
249#define AC97_NABM_OFF_CR 0xb /**< Control Register */
250#define AC97_NABM_OFF_MASK 0xf /**< Mask for getting the the per-stream register. */
251/** @} */
252
253
254/** @name PCM in NABM BAR registers (0x00..0x0f).
255 * @{ */
256#define PI_BDBAR (AC97SOUNDSOURCE_PI_INDEX * 0x10 + 0x0) /**< PCM in: Buffer Descriptor Base Address */
257#define PI_CIV (AC97SOUNDSOURCE_PI_INDEX * 0x10 + 0x4) /**< PCM in: Current Index Value */
258#define PI_LVI (AC97SOUNDSOURCE_PI_INDEX * 0x10 + 0x5) /**< PCM in: Last Valid Index */
259#define PI_SR (AC97SOUNDSOURCE_PI_INDEX * 0x10 + 0x6) /**< PCM in: Status Register */
260#define PI_PICB (AC97SOUNDSOURCE_PI_INDEX * 0x10 + 0x8) /**< PCM in: Position in Current Buffer */
261#define PI_PIV (AC97SOUNDSOURCE_PI_INDEX * 0x10 + 0xa) /**< PCM in: Prefetched Index Value */
262#define PI_CR (AC97SOUNDSOURCE_PI_INDEX * 0x10 + 0xb) /**< PCM in: Control Register */
263/** @} */
264
265/** @name PCM out NABM BAR registers (0x10..0x1f).
266 * @{ */
267#define PO_BDBAR (AC97SOUNDSOURCE_PO_INDEX * 0x10 + 0x0) /**< PCM out: Buffer Descriptor Base Address */
268#define PO_CIV (AC97SOUNDSOURCE_PO_INDEX * 0x10 + 0x4) /**< PCM out: Current Index Value */
269#define PO_LVI (AC97SOUNDSOURCE_PO_INDEX * 0x10 + 0x5) /**< PCM out: Last Valid Index */
270#define PO_SR (AC97SOUNDSOURCE_PO_INDEX * 0x10 + 0x6) /**< PCM out: Status Register */
271#define PO_PICB (AC97SOUNDSOURCE_PO_INDEX * 0x10 + 0x8) /**< PCM out: Position in Current Buffer */
272#define PO_PIV (AC97SOUNDSOURCE_PO_INDEX * 0x10 + 0xa) /**< PCM out: Prefetched Index Value */
273#define PO_CR (AC97SOUNDSOURCE_PO_INDEX * 0x10 + 0xb) /**< PCM out: Control Register */
274/** @} */
275
276/** @name Mic in NABM BAR registers (0x20..0x2f).
277 * @{ */
278#define MC_BDBAR (AC97SOUNDSOURCE_MC_INDEX * 0x10 + 0x0) /**< PCM in: Buffer Descriptor Base Address */
279#define MC_CIV (AC97SOUNDSOURCE_MC_INDEX * 0x10 + 0x4) /**< PCM in: Current Index Value */
280#define MC_LVI (AC97SOUNDSOURCE_MC_INDEX * 0x10 + 0x5) /**< PCM in: Last Valid Index */
281#define MC_SR (AC97SOUNDSOURCE_MC_INDEX * 0x10 + 0x6) /**< PCM in: Status Register */
282#define MC_PICB (AC97SOUNDSOURCE_MC_INDEX * 0x10 + 0x8) /**< PCM in: Position in Current Buffer */
283#define MC_PIV (AC97SOUNDSOURCE_MC_INDEX * 0x10 + 0xa) /**< PCM in: Prefetched Index Value */
284#define MC_CR (AC97SOUNDSOURCE_MC_INDEX * 0x10 + 0xb) /**< PCM in: Control Register */
285/** @} */
286
287/** @name Misc NABM BAR registers.
288 * @{ */
289/** NABMBAR: Global Control Register.
290 * @note This is kind of in the MIC IN area. */
291#define AC97_GLOB_CNT 0x2c
292/** NABMBAR: Global Status. */
293#define AC97_GLOB_STA 0x30
294/** Codec Access Semaphore Register. */
295#define AC97_CAS 0x34
296/** @} */
297
298
299/*********************************************************************************************************************************
300* Structures and Typedefs *
301*********************************************************************************************************************************/
302/** The ICH AC'97 (Intel) controller (shared). */
303typedef struct AC97STATE *PAC97STATE;
304/** The ICH AC'97 (Intel) controller (ring-3). */
305typedef struct AC97STATER3 *PAC97STATER3;
306
307/**
308 * Buffer Descriptor List Entry (BDLE).
309 *
310 * (See section 3.2.1 in Intel document number 252751-001, or section 1.2.2.1 in
311 * Intel document number 302349-003.)
312 */
313typedef struct AC97BDLE
314{
315 /** Location of data buffer (bits 31:1). */
316 uint32_t addr;
317 /** Flags (bits 31 + 30) and length (bits 15:0) of data buffer (in audio samples).
318 * @todo split up into two 16-bit fields. */
319 uint32_t ctl_len;
320} AC97BDLE;
321AssertCompileSize(AC97BDLE, 8);
322/** Pointer to BDLE. */
323typedef AC97BDLE *PAC97BDLE;
324
325/**
326 * Bus master register set for an audio stream.
327 *
328 * (See section 16.2 in Intel document 301473-002, or section 2.2 in Intel
329 * document 302349-003.)
330 */
331typedef struct AC97BMREGS
332{
333 uint32_t bdbar; /**< rw 0, Buffer Descriptor List: BAR (Base Address Register). */
334 uint8_t civ; /**< ro 0, Current index value. */
335 uint8_t lvi; /**< rw 0, Last valid index. */
336 uint16_t sr; /**< rw 1, Status register. */
337 uint16_t picb; /**< ro 0, Position in current buffer (samples left to process). */
338 uint8_t piv; /**< ro 0, Prefetched index value. */
339 uint8_t cr; /**< rw 0, Control register. */
340 int32_t bd_valid; /**< Whether current BDLE is initialized or not. */
341 AC97BDLE bd; /**< Current Buffer Descriptor List Entry (BDLE). */
342} AC97BMREGS;
343AssertCompileSizeAlignment(AC97BMREGS, 8);
344/** Pointer to the BM registers of an audio stream. */
345typedef AC97BMREGS *PAC97BMREGS;
346
347/**
348 * The internal state of an AC'97 stream.
349 */
350typedef struct AC97STREAMSTATE
351{
352 /** Critical section for this stream. */
353 RTCRITSECT CritSect;
354 /** Circular buffer (FIFO) for holding DMA'ed data. */
355 R3PTRTYPE(PRTCIRCBUF) pCircBuf;
356#if HC_ARCH_BITS == 32
357 uint32_t Padding;
358#endif
359 /** Current circular buffer read offset (for tracing & logging). */
360 uint64_t offRead;
361 /** Current circular buffer write offset (for tracing & logging). */
362 uint64_t offWrite;
363 /** The stream's current configuration. */
364 PDMAUDIOSTREAMCFG Cfg; //+108
365 /** Timestamp of the last DMA data transfer. */
366 uint64_t tsTransferLast;
367 /** Timestamp of the next DMA data transfer.
368 * Next for determining the next scheduling window.
369 * Can be 0 if no next transfer is scheduled. */
370 uint64_t tsTransferNext;
371 /** Transfer chunk size (in bytes) of a transfer period. */
372 uint32_t cbTransferChunk;
373 /** The stream's timer Hz rate.
374 * This value can can be different from the device's default Hz rate,
375 * depending on the rate the stream expects (e.g. for 5.1 speaker setups).
376 * Set in R3StreamInit(). */
377 uint16_t uTimerHz;
378 /** Set if we've registered the asynchronous update job. */
379 bool fRegisteredAsyncUpdateJob;
380 uint8_t Padding3;
381 /** (Virtual) clock ticks per transfer. */
382 uint64_t cTransferTicks;
383 /** Timestamp (in ns) of last stream update. */
384 uint64_t tsLastUpdateNs;
385
386 /** Size of the DMA buffer (pCircBuf) in bytes. */
387 uint32_t StatDmaBufSize;
388 /** Number of used bytes in the DMA buffer (pCircBuf). */
389 uint32_t StatDmaBufUsed;
390} AC97STREAMSTATE;
391AssertCompileSizeAlignment(AC97STREAMSTATE, 8);
392/** Pointer to internal state of an AC'97 stream. */
393typedef AC97STREAMSTATE *PAC97STREAMSTATE;
394
395/**
396 * Runtime configurable debug stuff for an AC'97 stream.
397 */
398typedef struct AC97STREAMDEBUGRT
399{
400 /** Whether debugging is enabled or not. */
401 bool fEnabled;
402 uint8_t Padding[7];
403 /** File for dumping stream reads / writes.
404 * For input streams, this dumps data being written to the device FIFO,
405 * whereas for output streams this dumps data being read from the device FIFO. */
406 R3PTRTYPE(PAUDIOHLPFILE) pFileStream;
407 /** File for dumping DMA reads / writes.
408 * For input streams, this dumps data being written to the device DMA,
409 * whereas for output streams this dumps data being read from the device DMA. */
410 R3PTRTYPE(PAUDIOHLPFILE) pFileDMA;
411} AC97STREAMDEBUGRT;
412
413/**
414 * Debug stuff for an AC'97 stream.
415 */
416typedef struct AC97STREAMDEBUG
417{
418 /** Runtime debug stuff. */
419 AC97STREAMDEBUGRT Runtime;
420} AC97STREAMDEBUG;
421
422/**
423 * The shared AC'97 stream state.
424 */
425typedef struct AC97STREAM
426{
427 /** Stream number (SDn). */
428 uint8_t u8SD;
429 uint8_t abPadding0[7];
430 /** Bus master registers of this stream. */
431 AC97BMREGS Regs;
432 /** The timer for pumping data thru the attached LUN drivers. */
433 TMTIMERHANDLE hTimer;
434} AC97STREAM;
435AssertCompileSizeAlignment(AC97STREAM, 8);
436/** Pointer to a shared AC'97 stream state. */
437typedef AC97STREAM *PAC97STREAM;
438
439
440/**
441 * The ring-3 AC'97 stream state.
442 */
443typedef struct AC97STREAMR3
444{
445 /** Stream number (SDn). */
446 uint8_t u8SD;
447 uint8_t abPadding0[7];
448 /** Internal state of this stream. */
449 AC97STREAMSTATE State;
450 /** Debug stuff. */
451 AC97STREAMDEBUG Dbg;
452} AC97STREAMR3;
453AssertCompileSizeAlignment(AC97STREAMR3, 8);
454/** Pointer to an AC'97 stream state for ring-3. */
455typedef AC97STREAMR3 *PAC97STREAMR3;
456
457
458/**
459 * A driver stream (host backend).
460 *
461 * Each driver has its own instances of audio mixer streams, which then
462 * can go into the same (or even different) audio mixer sinks.
463 */
464typedef struct AC97DRIVERSTREAM
465{
466 /** Associated mixer stream handle. */
467 R3PTRTYPE(PAUDMIXSTREAM) pMixStrm;
468} AC97DRIVERSTREAM;
469/** Pointer to a driver stream. */
470typedef AC97DRIVERSTREAM *PAC97DRIVERSTREAM;
471
472/**
473 * A host backend driver (LUN).
474 */
475typedef struct AC97DRIVER
476{
477 /** Node for storing this driver in our device driver list of AC97STATE. */
478 RTLISTNODER3 Node;
479 /** LUN # to which this driver has been assigned. */
480 uint8_t uLUN;
481 /** Whether this driver is in an attached state or not. */
482 bool fAttached;
483 uint8_t abPadding[6];
484 /** Pointer to the description string passed to PDMDevHlpDriverAttach(). */
485 R3PTRTYPE(char *) pszDesc;
486 /** Pointer to attached driver base interface. */
487 R3PTRTYPE(PPDMIBASE) pDrvBase;
488 /** Audio connector interface to the underlying host backend. */
489 R3PTRTYPE(PPDMIAUDIOCONNECTOR) pConnector;
490 /** Driver stream for line input. */
491 AC97DRIVERSTREAM LineIn;
492 /** Driver stream for mic input. */
493 AC97DRIVERSTREAM MicIn;
494 /** Driver stream for output. */
495 AC97DRIVERSTREAM Out;
496} AC97DRIVER;
497/** Pointer to a host backend driver (LUN). */
498typedef AC97DRIVER *PAC97DRIVER;
499
500/**
501 * Debug settings.
502 */
503typedef struct AC97STATEDEBUG
504{
505 /** Whether debugging is enabled or not. */
506 bool fEnabled;
507 bool afAlignment[7];
508 /** Path where to dump the debug output to.
509 * Can be NULL, in which the system's temporary directory will be used then. */
510 R3PTRTYPE(char *) pszOutPath;
511} AC97STATEDEBUG;
512
513
514/* Codec models. */
515typedef enum AC97CODEC
516{
517 AC97CODEC_INVALID = 0, /**< Customary illegal zero value. */
518 AC97CODEC_STAC9700, /**< SigmaTel STAC9700 */
519 AC97CODEC_AD1980, /**< Analog Devices AD1980 */
520 AC97CODEC_AD1981B, /**< Analog Devices AD1981B */
521 AC97CODEC_32BIT_HACK = 0x7fffffff
522} AC97CODEC;
523
524
525/**
526 * The shared AC'97 device state.
527 */
528typedef struct AC97STATE
529{
530 /** Critical section protecting the AC'97 state. */
531 PDMCRITSECT CritSect;
532 /** Global Control (Bus Master Control Register). */
533 uint32_t glob_cnt;
534 /** Global Status (Bus Master Control Register). */
535 uint32_t glob_sta;
536 /** Codec Access Semaphore Register (Bus Master Control Register). */
537 uint32_t cas;
538 uint32_t last_samp;
539 uint8_t mixer_data[256];
540 /** Array of AC'97 streams (parallel to AC97STATER3::aStreams). */
541 AC97STREAM aStreams[AC97_MAX_STREAMS];
542 /** The device timer Hz rate. Defaults to AC97_TIMER_HZ_DEFAULT_DEFAULT. */
543 uint16_t uTimerHz;
544 /** Config: Internal input DMA buffer size override, specified in milliseconds.
545 * Zero means default size according to buffer and stream config.
546 * @sa BufSizeInMs config value. */
547 uint16_t cMsCircBufIn;
548 /** Config: Internal output DMA buffer size override, specified in milliseconds.
549 * Zero means default size according to buffer and stream config.
550 * @sa BufSizeOutMs config value. */
551 uint16_t cMsCircBufOut;
552 uint16_t au16Padding1[1];
553 uint8_t silence[128];
554 uint32_t bup_flag;
555 /** Codec model. */
556 AC97CODEC enmCodecModel;
557
558 /** PCI region \#0: NAM I/O ports. */
559 IOMIOPORTHANDLE hIoPortsNam;
560 /** PCI region \#0: NANM I/O ports. */
561 IOMIOPORTHANDLE hIoPortsNabm;
562
563 STAMCOUNTER StatUnimplementedNabmReads;
564 STAMCOUNTER StatUnimplementedNabmWrites;
565#ifdef VBOX_WITH_STATISTICS
566 STAMPROFILE StatTimer;
567 STAMPROFILE StatIn;
568 STAMPROFILE StatOut;
569 STAMCOUNTER StatBytesRead;
570 STAMCOUNTER StatBytesWritten;
571#endif
572} AC97STATE;
573AssertCompileMemberAlignment(AC97STATE, aStreams, 8);
574AssertCompileMemberAlignment(AC97STATE, StatUnimplementedNabmReads, 8);
575#ifdef VBOX_WITH_STATISTICS
576AssertCompileMemberAlignment(AC97STATE, StatTimer, 8);
577AssertCompileMemberAlignment(AC97STATE, StatBytesRead, 8);
578AssertCompileMemberAlignment(AC97STATE, StatBytesWritten, 8);
579#endif
580
581
582/**
583 * The ring-3 AC'97 device state.
584 */
585typedef struct AC97STATER3
586{
587 /** Array of AC'97 streams (parallel to AC97STATE:aStreams). */
588 AC97STREAMR3 aStreams[AC97_MAX_STREAMS];
589 /** R3 pointer to the device instance. */
590 PPDMDEVINSR3 pDevIns;
591 /** List of associated LUN drivers (AC97DRIVER). */
592 RTLISTANCHORR3 lstDrv;
593 /** The device's software mixer. */
594 R3PTRTYPE(PAUDIOMIXER) pMixer;
595 /** Audio sink for PCM output. */
596 R3PTRTYPE(PAUDMIXSINK) pSinkOut;
597 /** Audio sink for line input. */
598 R3PTRTYPE(PAUDMIXSINK) pSinkLineIn;
599 /** Audio sink for microphone input. */
600 R3PTRTYPE(PAUDMIXSINK) pSinkMicIn;
601 /** The base interface for LUN\#0. */
602 PDMIBASE IBase;
603 /** Debug settings. */
604 AC97STATEDEBUG Dbg;
605} AC97STATER3;
606AssertCompileMemberAlignment(AC97STATER3, aStreams, 8);
607/** Pointer to the ring-3 AC'97 device state. */
608typedef AC97STATER3 *PAC97STATER3;
609
610
611/**
612 * Acquires the AC'97 lock.
613 */
614#define DEVAC97_LOCK(a_pDevIns, a_pThis) \
615 do { \
616 int rcLock = PDMDevHlpCritSectEnter((a_pDevIns), &(a_pThis)->CritSect, VERR_IGNORED); \
617 AssertRC(rcLock); \
618 } while (0)
619
620/**
621 * Acquires the AC'97 lock or returns.
622 */
623# define DEVAC97_LOCK_RETURN(a_pDevIns, a_pThis, a_rcBusy) \
624 do { \
625 int rcLock = PDMDevHlpCritSectEnter((a_pDevIns), &(a_pThis)->CritSect, a_rcBusy); \
626 if (rcLock == VINF_SUCCESS) \
627 break; \
628 AssertRC(rcLock); \
629 return rcLock; \
630 } while (0)
631
632/** Retrieves an attribute from a specific audio stream in RC. */
633#define DEVAC97_CTX_SUFF_SD(a_Var, a_SD) CTX_SUFF(a_Var)[a_SD]
634
635/**
636 * Releases the AC'97 lock.
637 */
638#define DEVAC97_UNLOCK(a_pDevIns, a_pThis) \
639 do { PDMDevHlpCritSectLeave((a_pDevIns), &(a_pThis)->CritSect); } while (0)
640
641/**
642 * Acquires the TM lock and AC'97 lock, returns on failure.
643 *
644 * @todo r=bird: Isn't this overkill for ring-0, only ring-3 access the timer
645 * from what I can tell (ichac97R3StreamTransferCalcNext,
646 * ichac97R3TimerSet, timer callback and state load).
647 */
648#define DEVAC97_LOCK_BOTH_RETURN(a_pDevIns, a_pThis, a_pStream, a_rcBusy) \
649 do { \
650 VBOXSTRICTRC rcLock = PDMDevHlpTimerLockClock2((a_pDevIns), (a_pStream)->hTimer, &(a_pThis)->CritSect, (a_rcBusy)); \
651 if (RT_LIKELY(rcLock == VINF_SUCCESS)) \
652 { /* likely */ } \
653 else \
654 { \
655 AssertRC(VBOXSTRICTRC_VAL(rcLock)); \
656 return rcLock; \
657 } \
658 } while (0)
659
660/**
661 * Releases the AC'97 lock and TM lock.
662 */
663#define DEVAC97_UNLOCK_BOTH(a_pDevIns, a_pThis, a_pStream) \
664 PDMDevHlpTimerUnlockClock2((a_pDevIns), (a_pStream)->hTimer, &(a_pThis)->CritSect)
665
666#ifndef VBOX_DEVICE_STRUCT_TESTCASE
667
668
669/*********************************************************************************************************************************
670* Internal Functions *
671*********************************************************************************************************************************/
672#ifdef IN_RING3
673static int ichac97R3StreamOpen(PPDMDEVINS pDevIns, PAC97STATE pThis, PAC97STATER3 pThisCC, PAC97STREAM pStream,
674 PAC97STREAMR3 pStreamCC, bool fForce);
675static int ichac97R3StreamClose(PAC97STREAM pStream);
676static void ichac97R3StreamLock(PAC97STREAMR3 pStreamCC);
677static void ichac97R3StreamUnlock(PAC97STREAMR3 pStreamCC);
678static uint32_t ichac97R3StreamGetUsed(PAC97STREAMR3 pStreamCC);
679static uint32_t ichac97R3StreamGetFree(PAC97STREAMR3 pStreamCC);
680static int ichac97R3StreamTransfer(PPDMDEVINS pDevIns, PAC97STATE pThis, PAC97STREAM pStream,
681 PAC97STREAMR3 pStreamCC, uint32_t cbToProcessMax);
682static DECLCALLBACK(void) ichac97R3StreamUpdateAsyncIoJob(PPDMDEVINS pDevIns, PAUDMIXSINK pSink, void *pvUser);
683
684static DECLCALLBACK(void) ichac97R3Reset(PPDMDEVINS pDevIns);
685
686static void ichac97R3MixerRemoveDrvStreams(PPDMDEVINS pDevIns, PAC97STATER3 pThisCC, PAUDMIXSINK pMixSink,
687 PDMAUDIODIR enmDir, PDMAUDIOPATH enmPath);
688
689DECLINLINE(PDMAUDIODIR) ichac97GetDirFromSD(uint8_t uSD);
690DECLINLINE(void) ichac97R3TimerSet(PPDMDEVINS pDevIns, PAC97STREAM pStream, uint64_t cTicksToDeadline);
691
692static void ichac97R3DbgPrintBdl(PPDMDEVINS pDevIns, PAC97STATE pThis, PAC97STREAM pStream,
693 PCDBGFINFOHLP pHlp, const char *pszPrefix);
694#endif /* IN_RING3 */
695
696
697/*********************************************************************************************************************************
698* Global Variables *
699*********************************************************************************************************************************/
700#ifdef IN_RING3
701/** NABM I/O port descriptions. */
702static const IOMIOPORTDESC g_aNabmPorts[] =
703{
704 { "PCM IN - BDBAR", "PCM IN - BDBAR", NULL, NULL },
705 { "", NULL, NULL, NULL },
706 { "", NULL, NULL, NULL },
707 { "", NULL, NULL, NULL },
708 { "PCM IN - CIV", "PCM IN - CIV", NULL, NULL },
709 { "PCM IN - LVI", "PCM IN - LIV", NULL, NULL },
710 { "PCM IN - SR", "PCM IN - SR", NULL, NULL },
711 { "", NULL, NULL, NULL },
712 { "PCM IN - PICB", "PCM IN - PICB", NULL, NULL },
713 { "", NULL, NULL, NULL },
714 { "PCM IN - PIV", "PCM IN - PIV", NULL, NULL },
715 { "PCM IN - CR", "PCM IN - CR", NULL, NULL },
716 { "", NULL, NULL, NULL },
717 { "", NULL, NULL, NULL },
718 { "", NULL, NULL, NULL },
719 { "", NULL, NULL, NULL },
720
721 { "PCM OUT - BDBAR", "PCM OUT - BDBAR", NULL, NULL },
722 { "", NULL, NULL, NULL },
723 { "", NULL, NULL, NULL },
724 { "", NULL, NULL, NULL },
725 { "PCM OUT - CIV", "PCM OUT - CIV", NULL, NULL },
726 { "PCM OUT - LVI", "PCM OUT - LIV", NULL, NULL },
727 { "PCM OUT - SR", "PCM OUT - SR", NULL, NULL },
728 { "", NULL, NULL, NULL },
729 { "PCM OUT - PICB", "PCM OUT - PICB", NULL, NULL },
730 { "", NULL, NULL, NULL },
731 { "PCM OUT - PIV", "PCM OUT - PIV", NULL, NULL },
732 { "PCM OUT - CR", "PCM IN - CR", NULL, NULL },
733 { "", NULL, NULL, NULL },
734 { "", NULL, NULL, NULL },
735 { "", NULL, NULL, NULL },
736 { "", NULL, NULL, NULL },
737
738 { "MIC IN - BDBAR", "MIC IN - BDBAR", NULL, NULL },
739 { "", NULL, NULL, NULL },
740 { "", NULL, NULL, NULL },
741 { "", NULL, NULL, NULL },
742 { "MIC IN - CIV", "MIC IN - CIV", NULL, NULL },
743 { "MIC IN - LVI", "MIC IN - LIV", NULL, NULL },
744 { "MIC IN - SR", "MIC IN - SR", NULL, NULL },
745 { "", NULL, NULL, NULL },
746 { "MIC IN - PICB", "MIC IN - PICB", NULL, NULL },
747 { "", NULL, NULL, NULL },
748 { "MIC IN - PIV", "MIC IN - PIV", NULL, NULL },
749 { "MIC IN - CR", "MIC IN - CR", NULL, NULL },
750 { "GLOB CNT", "GLOB CNT", NULL, NULL },
751 { "", NULL, NULL, NULL },
752 { "", NULL, NULL, NULL },
753 { "", NULL, NULL, NULL },
754
755 { "GLOB STA", "GLOB STA", NULL, NULL },
756 { "", NULL, NULL, NULL },
757 { "", NULL, NULL, NULL },
758 { "", NULL, NULL, NULL },
759 { "CAS", "CAS", NULL, NULL },
760 { NULL, NULL, NULL, NULL },
761};
762
763/** @name Source indices
764 * @{ */
765# define AC97SOUNDSOURCE_PI_INDEX 0 /**< PCM in */
766# define AC97SOUNDSOURCE_PO_INDEX 1 /**< PCM out */
767# define AC97SOUNDSOURCE_MC_INDEX 2 /**< Mic in */
768# define AC97SOUNDSOURCE_MAX 3 /**< Max sound sources. */
769/** @} */
770
771/** Port number (offset into NABM BAR) to stream index. */
772# define AC97_PORT2IDX(a_idx) ( ((a_idx) >> 4) & 3 )
773/** Port number (offset into NABM BAR) to stream index, but no masking. */
774# define AC97_PORT2IDX_UNMASKED(a_idx) ( ((a_idx) >> 4) )
775
776/** @name Stream offsets
777 * @{ */
778# define AC97_NABM_OFF_BDBAR 0x0 /**< Buffer Descriptor Base Address */
779# define AC97_NABM_OFF_CIV 0x4 /**< Current Index Value */
780# define AC97_NABM_OFF_LVI 0x5 /**< Last Valid Index */
781# define AC97_NABM_OFF_SR 0x6 /**< Status Register */
782# define AC97_NABM_OFF_PICB 0x8 /**< Position in Current Buffer */
783# define AC97_NABM_OFF_PIV 0xa /**< Prefetched Index Value */
784# define AC97_NABM_OFF_CR 0xb /**< Control Register */
785# define AC97_NABM_OFF_MASK 0xf /**< Mask for getting the the per-stream register. */
786/** @} */
787
788#endif /* IN_RING3 */
789
790
791
792static void ichac97WarmReset(PAC97STATE pThis)
793{
794 NOREF(pThis);
795}
796
797static void ichac97ColdReset(PAC97STATE pThis)
798{
799 NOREF(pThis);
800}
801
802
803#ifdef IN_RING3
804
805/**
806 * Retrieves the audio mixer sink of a corresponding AC'97 stream index.
807 *
808 * @returns Pointer to audio mixer sink if found, or NULL if not found / invalid.
809 * @param pThisCC The ring-3 AC'97 state.
810 * @param uIndex Stream index to get audio mixer sink for.
811 */
812DECLINLINE(PAUDMIXSINK) ichac97R3IndexToSink(PAC97STATER3 pThisCC, uint8_t uIndex)
813{
814 switch (uIndex)
815 {
816 case AC97SOUNDSOURCE_PI_INDEX: return pThisCC->pSinkLineIn;
817 case AC97SOUNDSOURCE_PO_INDEX: return pThisCC->pSinkOut;
818 case AC97SOUNDSOURCE_MC_INDEX: return pThisCC->pSinkMicIn;
819 default:
820 AssertMsgFailedReturn(("Wrong index %RU8\n", uIndex), NULL);
821 }
822}
823
824/**
825 * Fetches the next buffer descriptor (BDLE) updating the stream registers.
826 *
827 * This will skip zero length descriptors.
828 *
829 * @returns Zero, or AC97_SR_BCIS if skipped zero length buffer with IOC set.
830 * @param pDevIns The device instance.
831 * @param pStream AC'97 stream to fetch BDLE for.
832 * @param pStreamCC The AC'97 stream, ring-3 state.
833 *
834 * @remarks Updates CIV, PIV, BD and PICB.
835 *
836 * @note Both PIV and CIV will be zero after a stream reset, so the first
837 * time we advance the buffer position afterwards, CIV will remain zero
838 * and PIV becomes 1. Thus we will start processing from BDLE00 and
839 * not BDLE01 as CIV=0 may lead you to think.
840 */
841static uint32_t ichac97R3StreamFetchNextBdle(PPDMDEVINS pDevIns, PAC97STREAM pStream, PAC97STREAMR3 pStreamCC)
842{
843 RT_NOREF(pStreamCC);
844 uint32_t fSrBcis = 0;
845
846 /*
847 * Loop for skipping zero length entries.
848 */
849 for (;;)
850 {
851 /* Advance the buffer. */
852 pStream->Regs.civ = pStream->Regs.piv % AC97_MAX_BDLE /* (paranoia) */;
853 pStream->Regs.piv = (pStream->Regs.piv + 1) % AC97_MAX_BDLE;
854
855 /* Load it. */
856 AC97BDLE Bdle = { 0, 0 };
857 PDMDevHlpPCIPhysRead(pDevIns, pStream->Regs.bdbar + pStream->Regs.civ * sizeof(AC97BDLE), &Bdle, sizeof(AC97BDLE));
858 pStream->Regs.bd_valid = 1;
859 pStream->Regs.bd.addr = RT_H2LE_U32(Bdle.addr) & ~3;
860 pStream->Regs.bd.ctl_len = RT_H2LE_U32(Bdle.ctl_len);
861 pStream->Regs.picb = pStream->Regs.bd.ctl_len & AC97_BD_LEN_MASK;
862
863 LogFlowFunc(("BDLE%02u: %#RX32 L %#x / LB %#x, ctl=%#06x%s%s\n",
864 pStream->Regs.civ, pStream->Regs.bd.addr, pStream->Regs.bd.ctl_len & AC97_BD_LEN_MASK,
865 (pStream->Regs.bd.ctl_len & AC97_BD_LEN_MASK) * PDMAudioPropsSampleSize(&pStreamCC->State.Cfg.Props),
866 pStream->Regs.bd.ctl_len >> 16,
867 pStream->Regs.bd.ctl_len & AC97_BD_IOC ? " ioc" : "",
868 pStream->Regs.bd.ctl_len & AC97_BD_BUP ? " bup" : ""));
869
870 /* Complain about any reserved bits set in CTL and ADDR: */
871 ASSERT_GUEST_MSG(!(pStream->Regs.bd.ctl_len & AC97_BD_LEN_CTL_MBZ),
872 ("Reserved bits set: %#RX32\n", pStream->Regs.bd.ctl_len));
873 ASSERT_GUEST_MSG(!(RT_H2LE_U32(Bdle.addr) & 3),
874 ("Reserved addr bits set: %#RX32\n", RT_H2LE_U32(Bdle.addr) ));
875
876 /* If the length is non-zero or if we've reached LVI, we're done regardless
877 of what's been loaded. Otherwise, we skip zero length buffers. */
878 if (pStream->Regs.picb)
879 break;
880 if (pStream->Regs.civ == (pStream->Regs.lvi % AC97_MAX_BDLE /* (paranoia) */))
881 {
882 LogFunc(("BDLE%02u is zero length! Can't skip (CIV=LVI). %#RX32 %#RX32\n", pStream->Regs.civ, Bdle.addr, Bdle.ctl_len));
883 break;
884 }
885 LogFunc(("BDLE%02u is zero length! Skipping. %#RX32 %#RX32\n", pStream->Regs.civ, Bdle.addr, Bdle.ctl_len));
886
887 /* If the buffer has IOC set, make sure it's triggered by the caller. */
888 if (pStream->Regs.bd.ctl_len & AC97_BD_IOC)
889 fSrBcis |= AC97_SR_BCIS;
890 }
891
892 /* 1.2.4.2 PCM Buffer Restrictions (in 302349-003) - #1 */
893 ASSERT_GUEST_MSG(!(pStream->Regs.picb & 1),
894 ("Odd lengths buffers are not allowed: %#x (%d) samples\n", pStream->Regs.picb, pStream->Regs.picb));
895
896 /* 1.2.4.2 PCM Buffer Restrictions (in 302349-003) - #2 */
897 ASSERT_GUEST_MSG(pStream->Regs.picb > 0, ("Zero length buffers not allowed to terminate list (LVI=%u CIV=%u)\n",
898 pStream->Regs.lvi, pStream->Regs.civ));
899
900 return fSrBcis;
901}
902
903#endif /* IN_RING3 */
904
905/**
906 * Updates the status register (SR) of an AC'97 audio stream.
907 *
908 * @param pDevIns The device instance.
909 * @param pThis The shared AC'97 state.
910 * @param pStream AC'97 stream to update SR for.
911 * @param new_sr New value for status register (SR).
912 */
913static void ichac97StreamUpdateSR(PPDMDEVINS pDevIns, PAC97STATE pThis, PAC97STREAM pStream, uint32_t new_sr)
914{
915 PAC97BMREGS pRegs = &pStream->Regs;
916
917 bool fSignal = false;
918 int iIRQL = 0;
919
920 uint32_t new_mask = new_sr & AC97_SR_INT_MASK;
921 uint32_t old_mask = pRegs->sr & AC97_SR_INT_MASK;
922
923 if (new_mask ^ old_mask)
924 {
925 /** @todo Is IRQ deasserted when only one of status bits is cleared? */
926 if (!new_mask)
927 {
928 fSignal = true;
929 iIRQL = 0;
930 }
931 else if ((new_mask & AC97_SR_LVBCI) && (pRegs->cr & AC97_CR_LVBIE))
932 {
933 fSignal = true;
934 iIRQL = 1;
935 }
936 else if ((new_mask & AC97_SR_BCIS) && (pRegs->cr & AC97_CR_IOCE))
937 {
938 fSignal = true;
939 iIRQL = 1;
940 }
941 }
942
943 pRegs->sr = new_sr;
944
945 LogFlowFunc(("IOC%d, LVB%d, sr=%#x, fSignal=%RTbool, IRQL=%d\n",
946 pRegs->sr & AC97_SR_BCIS, pRegs->sr & AC97_SR_LVBCI, pRegs->sr, fSignal, iIRQL));
947
948 if (fSignal)
949 {
950 static uint32_t const s_aMasks[] = { AC97_GS_PIINT, AC97_GS_POINT, AC97_GS_MINT };
951 Assert(pStream->u8SD < AC97_MAX_STREAMS);
952 if (iIRQL)
953 pThis->glob_sta |= s_aMasks[pStream->u8SD];
954 else
955 pThis->glob_sta &= ~s_aMasks[pStream->u8SD];
956
957 LogFlowFunc(("Setting IRQ level=%d\n", iIRQL));
958 PDMDevHlpPCISetIrq(pDevIns, 0, iIRQL);
959 }
960}
961
962/**
963 * Writes a new value to a stream's status register (SR).
964 *
965 * @param pDevIns The device instance.
966 * @param pThis The shared AC'97 device state.
967 * @param pStream Stream to update SR for.
968 * @param u32Val New value to set the stream's SR to.
969 */
970static void ichac97StreamWriteSR(PPDMDEVINS pDevIns, PAC97STATE pThis, PAC97STREAM pStream, uint32_t u32Val)
971{
972 PAC97BMREGS pRegs = &pStream->Regs;
973
974 Log3Func(("[SD%RU8] SR <- %#x (sr %#x)\n", pStream->u8SD, u32Val, pRegs->sr));
975
976 pRegs->sr |= u32Val & ~(AC97_SR_RO_MASK | AC97_SR_WCLEAR_MASK);
977 ichac97StreamUpdateSR(pDevIns, pThis, pStream, pRegs->sr & ~(u32Val & AC97_SR_WCLEAR_MASK));
978}
979
980#ifdef IN_RING3
981
982/**
983 * Returns whether an AC'97 stream is enabled or not.
984 *
985 * @returns VBox status code.
986 * @param pThisCC The ring-3 AC'97 device state.
987 * @param pStream Stream to return status for.
988 */
989static bool ichac97R3StreamIsEnabled(PAC97STATER3 pThisCC, PAC97STREAM pStream)
990{
991 PAUDMIXSINK pSink = ichac97R3IndexToSink(pThisCC, pStream->u8SD);
992 bool fIsEnabled = pSink && (AudioMixerSinkGetStatus(pSink) & AUDMIXSINK_STS_RUNNING);
993
994 LogFunc(("[SD%RU8] fIsEnabled=%RTbool\n", pStream->u8SD, fIsEnabled));
995 return fIsEnabled;
996}
997
998/**
999 * Enables or disables an AC'97 audio stream.
1000 *
1001 * @returns VBox status code.
1002 * @param pDevIns The device instance.
1003 * @param pThis The shared AC'97 state.
1004 * @param pThisCC The ring-3 AC'97 state.
1005 * @param pStream The AC'97 stream to enable or disable (shared state).
1006 * @param pStreamCC The ring-3 stream state (matching to @a pStream).
1007 * @param fEnable Whether to enable or disable the stream.
1008 *
1009 */
1010static int ichac97R3StreamEnable(PPDMDEVINS pDevIns, PAC97STATE pThis, PAC97STATER3 pThisCC,
1011 PAC97STREAM pStream, PAC97STREAMR3 pStreamCC, bool fEnable)
1012{
1013 ichac97R3StreamLock(pStreamCC);
1014 PAUDMIXSINK const pSink = ichac97R3IndexToSink(pThisCC, pStream->u8SD);
1015 AudioMixerSinkLock(pSink);
1016
1017 int rc = VINF_SUCCESS;
1018 if (fEnable)
1019 {
1020 if (pStreamCC->State.pCircBuf)
1021 RTCircBufReset(pStreamCC->State.pCircBuf);
1022
1023 rc = ichac97R3StreamOpen(pDevIns, pThis, pThisCC, pStream, pStreamCC, false /* fForce */);
1024
1025 /* Re-register the update job with the AIO thread with correct sched hint.
1026 Note! We do not unregister it on disable because of draining. */
1027 if (pStreamCC->State.fRegisteredAsyncUpdateJob)
1028 AudioMixerSinkRemoveUpdateJob(pSink, ichac97R3StreamUpdateAsyncIoJob, pStreamCC);
1029 int rc2 = AudioMixerSinkAddUpdateJob(pSink, ichac97R3StreamUpdateAsyncIoJob, pStreamCC,
1030 pStreamCC->State.Cfg.Device.cMsSchedulingHint);
1031 AssertRC(rc2);
1032 pStreamCC->State.fRegisteredAsyncUpdateJob = RT_SUCCESS(rc2) || rc2 == VERR_ALREADY_EXISTS;
1033
1034 /* Open debug files: */
1035 if (RT_LIKELY(!pStreamCC->Dbg.Runtime.fEnabled))
1036 { /* likely */ }
1037 else
1038 {
1039 if (!AudioHlpFileIsOpen(pStreamCC->Dbg.Runtime.pFileStream))
1040 {
1041 rc2 = AudioHlpFileOpen(pStreamCC->Dbg.Runtime.pFileStream, AUDIOHLPFILE_DEFAULT_OPEN_FLAGS,
1042 &pStreamCC->State.Cfg.Props);
1043 AssertRC(rc2);
1044 }
1045
1046 if (!AudioHlpFileIsOpen(pStreamCC->Dbg.Runtime.pFileDMA))
1047 {
1048 rc2 = AudioHlpFileOpen(pStreamCC->Dbg.Runtime.pFileDMA, AUDIOHLPFILE_DEFAULT_OPEN_FLAGS,
1049 &pStreamCC->State.Cfg.Props);
1050 AssertRC(rc2);
1051 }
1052 }
1053
1054 if (RT_SUCCESS(rc))
1055 rc = AudioMixerSinkStart(pSink);
1056 }
1057 else
1058 {
1059 rc = ichac97R3StreamClose(pStream);
1060 if (RT_SUCCESS(rc))
1061 rc = AudioMixerSinkDrainAndStop(pSink,
1062 pStreamCC->State.pCircBuf ? (uint32_t)RTCircBufUsed(pStreamCC->State.pCircBuf) : 0);
1063 }
1064
1065 /* Make sure to leave the lock before (eventually) starting the timer. */
1066 AudioMixerSinkUnlock(pSink);
1067 ichac97R3StreamUnlock(pStreamCC);
1068 LogFunc(("[SD%RU8] fEnable=%RTbool, rc=%Rrc\n", pStream->u8SD, fEnable, rc));
1069 return rc;
1070}
1071
1072/**
1073 * Resets an AC'97 stream.
1074 *
1075 * @param pThis The shared AC'97 state.
1076 * @param pStream The AC'97 stream to reset (shared).
1077 * @param pStreamCC The AC'97 stream to reset (ring-3).
1078 */
1079static void ichac97R3StreamReset(PAC97STATE pThis, PAC97STREAM pStream, PAC97STREAMR3 pStreamCC)
1080{
1081 ichac97R3StreamLock(pStreamCC);
1082
1083 LogFunc(("[SD%RU8]\n", pStream->u8SD));
1084
1085 if (pStreamCC->State.pCircBuf)
1086 RTCircBufReset(pStreamCC->State.pCircBuf);
1087
1088 PAC97BMREGS pRegs = &pStream->Regs;
1089
1090 pRegs->bdbar = 0;
1091 pRegs->civ = 0;
1092 pRegs->lvi = 0;
1093
1094 pRegs->picb = 0;
1095 pRegs->piv = 0; /* Note! Because this is also zero, we will actually start transferring with BDLE00. */
1096 pRegs->cr = pRegs->cr & AC97_CR_DONT_CLEAR_MASK;
1097 pRegs->bd_valid = 0;
1098
1099 RT_ZERO(pThis->silence);
1100
1101 ichac97R3StreamUnlock(pStreamCC);
1102}
1103
1104/**
1105 * Creates an AC'97 audio stream.
1106 *
1107 * @returns VBox status code.
1108 * @param pThisCC The ring-3 AC'97 state.
1109 * @param pStream The AC'97 stream to create (shared).
1110 * @param pStreamCC The AC'97 stream to create (ring-3).
1111 * @param u8SD Stream descriptor number to assign.
1112 */
1113static int ichac97R3StreamCreate(PAC97STATER3 pThisCC, PAC97STREAM pStream, PAC97STREAMR3 pStreamCC, uint8_t u8SD)
1114{
1115 LogFunc(("[SD%RU8] pStream=%p\n", u8SD, pStream));
1116
1117 AssertReturn(u8SD < AC97_MAX_STREAMS, VERR_INVALID_PARAMETER);
1118 pStream->u8SD = u8SD;
1119 pStreamCC->u8SD = u8SD;
1120
1121 int rc = RTCritSectInit(&pStreamCC->State.CritSect);
1122 AssertRCReturn(rc, rc);
1123
1124 pStreamCC->Dbg.Runtime.fEnabled = pThisCC->Dbg.fEnabled;
1125
1126 if (RT_LIKELY(!pStreamCC->Dbg.Runtime.fEnabled))
1127 { /* likely */ }
1128 else
1129 {
1130 char szFile[64];
1131
1132 if (ichac97GetDirFromSD(pStream->u8SD) == PDMAUDIODIR_IN)
1133 RTStrPrintf(szFile, sizeof(szFile), "ac97StreamWriteSD%RU8", pStream->u8SD);
1134 else
1135 RTStrPrintf(szFile, sizeof(szFile), "ac97StreamReadSD%RU8", pStream->u8SD);
1136
1137 char szPath[RTPATH_MAX];
1138 int rc2 = AudioHlpFileNameGet(szPath, sizeof(szPath), pThisCC->Dbg.pszOutPath, szFile,
1139 0 /* uInst */, AUDIOHLPFILETYPE_WAV, AUDIOHLPFILENAME_FLAGS_NONE);
1140 AssertRC(rc2);
1141 rc2 = AudioHlpFileCreate(AUDIOHLPFILETYPE_WAV, szPath, AUDIOHLPFILE_FLAGS_NONE, &pStreamCC->Dbg.Runtime.pFileStream);
1142 AssertRC(rc2);
1143
1144 if (ichac97GetDirFromSD(pStream->u8SD) == PDMAUDIODIR_IN)
1145 RTStrPrintf(szFile, sizeof(szFile), "ac97DMAWriteSD%RU8", pStream->u8SD);
1146 else
1147 RTStrPrintf(szFile, sizeof(szFile), "ac97DMAReadSD%RU8", pStream->u8SD);
1148
1149 rc2 = AudioHlpFileNameGet(szPath, sizeof(szPath), pThisCC->Dbg.pszOutPath, szFile,
1150 0 /* uInst */, AUDIOHLPFILETYPE_WAV, AUDIOHLPFILENAME_FLAGS_NONE);
1151 AssertRC(rc2);
1152
1153 rc2 = AudioHlpFileCreate(AUDIOHLPFILETYPE_WAV, szPath, AUDIOHLPFILE_FLAGS_NONE, &pStreamCC->Dbg.Runtime.pFileDMA);
1154 AssertRC(rc2);
1155
1156 /* Delete stale debugging files from a former run. */
1157 AudioHlpFileDelete(pStreamCC->Dbg.Runtime.pFileStream);
1158 AudioHlpFileDelete(pStreamCC->Dbg.Runtime.pFileDMA);
1159 }
1160
1161 return rc;
1162}
1163
1164/**
1165 * Destroys an AC'97 audio stream.
1166 *
1167 * @returns VBox status code.
1168 * @param pThisCC The ring-3 AC'97 state.
1169 * @param pStream The AC'97 stream to destroy (shared).
1170 * @param pStreamCC The AC'97 stream to destroy (ring-3).
1171 */
1172static void ichac97R3StreamDestroy(PAC97STATER3 pThisCC, PAC97STREAM pStream, PAC97STREAMR3 pStreamCC)
1173{
1174 LogFlowFunc(("[SD%RU8]\n", pStream->u8SD));
1175
1176 ichac97R3StreamClose(pStream);
1177
1178 int rc2 = RTCritSectDelete(&pStreamCC->State.CritSect);
1179 AssertRC(rc2);
1180
1181 if (pStreamCC->State.fRegisteredAsyncUpdateJob)
1182 {
1183 PAUDMIXSINK pSink = ichac97R3IndexToSink(pThisCC, pStream->u8SD);
1184 if (pSink)
1185 AudioMixerSinkRemoveUpdateJob(pSink, ichac97R3StreamUpdateAsyncIoJob, pStreamCC);
1186 pStreamCC->State.fRegisteredAsyncUpdateJob = false;
1187 }
1188
1189 if (RT_LIKELY(!pStreamCC->Dbg.Runtime.fEnabled))
1190 { /* likely */ }
1191 else
1192 {
1193 AudioHlpFileDestroy(pStreamCC->Dbg.Runtime.pFileStream);
1194 pStreamCC->Dbg.Runtime.pFileStream = NULL;
1195
1196 AudioHlpFileDestroy(pStreamCC->Dbg.Runtime.pFileDMA);
1197 pStreamCC->Dbg.Runtime.pFileDMA = NULL;
1198 }
1199
1200 if (pStreamCC->State.pCircBuf)
1201 {
1202 RTCircBufDestroy(pStreamCC->State.pCircBuf);
1203 pStreamCC->State.pCircBuf = NULL;
1204 }
1205
1206 LogFlowFuncLeave();
1207}
1208
1209/**
1210 * Destroys all AC'97 audio streams of the device.
1211 *
1212 * @param pDevIns The device AC'97 instance.
1213 * @param pThis The shared AC'97 state.
1214 * @param pThisCC The ring-3 AC'97 state.
1215 */
1216static void ichac97R3StreamsDestroy(PPDMDEVINS pDevIns, PAC97STATE pThis, PAC97STATER3 pThisCC)
1217{
1218 LogFlowFuncEnter();
1219
1220 /*
1221 * Destroy all AC'97 streams.
1222 */
1223 for (unsigned i = 0; i < AC97_MAX_STREAMS; i++)
1224 ichac97R3StreamDestroy(pThisCC, &pThis->aStreams[i], &pThisCC->aStreams[i]);
1225
1226 /*
1227 * Destroy all sinks.
1228 */
1229 if (pThisCC->pSinkLineIn)
1230 {
1231 ichac97R3MixerRemoveDrvStreams(pDevIns, pThisCC, pThisCC->pSinkLineIn, PDMAUDIODIR_IN, PDMAUDIOPATH_IN_LINE);
1232
1233 AudioMixerSinkDestroy(pThisCC->pSinkLineIn, pDevIns);
1234 pThisCC->pSinkLineIn = NULL;
1235 }
1236
1237 if (pThisCC->pSinkMicIn)
1238 {
1239 ichac97R3MixerRemoveDrvStreams(pDevIns, pThisCC, pThisCC->pSinkMicIn, PDMAUDIODIR_IN, PDMAUDIOPATH_IN_MIC);
1240
1241 AudioMixerSinkDestroy(pThisCC->pSinkMicIn, pDevIns);
1242 pThisCC->pSinkMicIn = NULL;
1243 }
1244
1245 if (pThisCC->pSinkOut)
1246 {
1247 ichac97R3MixerRemoveDrvStreams(pDevIns, pThisCC, pThisCC->pSinkOut, PDMAUDIODIR_OUT, PDMAUDIOPATH_OUT_FRONT);
1248
1249 AudioMixerSinkDestroy(pThisCC->pSinkOut, pDevIns);
1250 pThisCC->pSinkOut = NULL;
1251 }
1252}
1253
1254
1255/**
1256 * Input streams: Pulls data from the mixer, putting it in the internal DMA
1257 * buffer.
1258 *
1259 * @param pStreamR3 The AC'97 stream (ring-3 bits).
1260 * @param pSink The mixer sink to pull from.
1261 */
1262static void ichac97R3StreamPullFromMixer(PAC97STREAMR3 pStreamR3, PAUDMIXSINK pSink)
1263{
1264#ifdef LOG_ENABLED
1265 uint64_t const offWriteOld = pStreamR3->State.offWrite;
1266#endif
1267 pStreamR3->State.offWrite = AudioMixerSinkTransferToCircBuf(pSink,
1268 pStreamR3->State.pCircBuf,
1269 pStreamR3->State.offWrite,
1270 pStreamR3->u8SD,
1271 pStreamR3->Dbg.Runtime.fEnabled
1272 ? pStreamR3->Dbg.Runtime.pFileStream : NULL);
1273
1274 Log3Func(("[SD%RU8] transferred=%#RX64 bytes -> @%#RX64\n", pStreamR3->u8SD,
1275 pStreamR3->State.offWrite - offWriteOld, pStreamR3->State.offWrite));
1276
1277 /* Update buffer stats. */
1278 pStreamR3->State.StatDmaBufUsed = (uint32_t)RTCircBufUsed(pStreamR3->State.pCircBuf);
1279}
1280
1281
1282/**
1283 * Output streams: Pushes data to the mixer.
1284 *
1285 * @param pStreamR3 The AC'97 stream (ring-3 bits).
1286 * @param pSink The mixer sink to push to.
1287 */
1288static void ichac97R3StreamPushToMixer(PAC97STREAMR3 pStreamR3, PAUDMIXSINK pSink)
1289{
1290#ifdef LOG_ENABLED
1291 uint64_t const offReadOld = pStreamR3->State.offRead;
1292#endif
1293 pStreamR3->State.offRead = AudioMixerSinkTransferFromCircBuf(pSink,
1294 pStreamR3->State.pCircBuf,
1295 pStreamR3->State.offRead,
1296 pStreamR3->u8SD,
1297 pStreamR3->Dbg.Runtime.fEnabled
1298 ? pStreamR3->Dbg.Runtime.pFileStream : NULL);
1299
1300 Log3Func(("[SD%RU8] transferred=%#RX64 bytes -> @%#RX64\n", pStreamR3->u8SD,
1301 pStreamR3->State.offRead - offReadOld, pStreamR3->State.offRead));
1302
1303 /* Update buffer stats. */
1304 pStreamR3->State.StatDmaBufUsed = (uint32_t)RTCircBufUsed(pStreamR3->State.pCircBuf);
1305}
1306
1307
1308/**
1309 * Updates an AC'97 stream by doing its DMA transfers.
1310 *
1311 * The host sink(s) set the overall pace (bird: no it doesn't, the DMA timer
1312 * does - we just hope like heck it matches the speed at which the *backend*
1313 * host audio driver processes samples).
1314 *
1315 * @param pDevIns The device instance.
1316 * @param pThis The shared AC'97 state.
1317 * @param pThisCC The ring-3 AC'97 state.
1318 * @param pStream The AC'97 stream to update (shared).
1319 * @param pStreamCC The AC'97 stream to update (ring-3).
1320 */
1321static void ichac97R3StreamUpdateDma(PPDMDEVINS pDevIns, PAC97STATE pThis, PAC97STATER3 pThisCC,
1322 PAC97STREAM pStream, PAC97STREAMR3 pStreamCC)
1323{
1324 /*
1325 * Make sure we're running and got an active mixer sink.
1326 */
1327 PAUDMIXSINK pSink = ichac97R3IndexToSink(pThisCC, pStream->u8SD); /** @todo caller will need + check this too afterwards... */
1328 AssertPtr(pSink);
1329 if (RT_LIKELY(AudioMixerSinkIsActive(pSink)))
1330 { /* likely */ }
1331 else
1332 return;
1333
1334 int rc2;
1335
1336 /*
1337 * Output streams (SDO).
1338 */
1339 if (pStreamCC->State.Cfg.enmDir == PDMAUDIODIR_OUT)
1340 {
1341 uint32_t cbStreamFree = ichac97R3StreamGetFree(pStreamCC);
1342 if (cbStreamFree)
1343 { /* likely */ }
1344 else
1345 {
1346 /** @todo Record this as a statistic. Try make some space available. */
1347 }
1348 if (cbStreamFree)
1349 {
1350 Log3Func(("[SD%RU8] PICB=%zu (%RU64ms), cbFree=%zu (%RU64ms), cbTransferChunk=%zu (%RU64ms)\n",
1351 pStream->u8SD,
1352 (pStream->Regs.picb << 1), PDMAudioPropsBytesToMilli(&pStreamCC->State.Cfg.Props, pStream->Regs.picb << 1),
1353 cbStreamFree, PDMAudioPropsBytesToMilli(&pStreamCC->State.Cfg.Props, cbStreamFree),
1354 pStreamCC->State.cbTransferChunk, PDMAudioPropsBytesToMilli(&pStreamCC->State.Cfg.Props, pStreamCC->State.cbTransferChunk)));
1355
1356 /* Do the DMA transfer. */
1357 rc2 = ichac97R3StreamTransfer(pDevIns, pThis, pStream, pStreamCC,
1358 RT_MIN(pStreamCC->State.cbTransferChunk, cbStreamFree));
1359 AssertRC(rc2);
1360
1361 pStreamCC->State.tsLastUpdateNs = RTTimeNanoTS();
1362 }
1363
1364 rc2 = AudioMixerSinkSignalUpdateJob(pSink);
1365 AssertRC(rc2);
1366 }
1367 else /* Input (SDI). */
1368 {
1369#if 0 /* bird: I just love when crusial code like this with no explanation. This just causing AIO
1370 * skipping a DMA timer cycle if the timer callback is a bit quicker than the 'hint' (see HDA/9890). */
1371 const uint64_t tsNowNs = RTTimeNanoTS();
1372 if (tsNowNs - pStreamCC->State.tsLastUpdateNs >= pStreamCC->State.Cfg.Device.cMsSchedulingHint * RT_NS_1MS)
1373 {
1374 rc2 = AudioMixerSinkSignalUpdateJob(pSink);
1375 AssertRC(rc2);
1376
1377 pStreamCC->State.tsLastUpdateNs = tsNowNs;
1378 }
1379#endif
1380
1381 uint32_t cbStreamUsed = ichac97R3StreamGetUsed(pStreamCC);
1382 if (cbStreamUsed)
1383 { /* likey */ }
1384 else
1385 {
1386 /** @todo Record this as a statistic. Try pull some data into the DMA buffer.*/
1387 }
1388
1389 if (cbStreamUsed)
1390 {
1391 /* When running synchronously, do the DMA data transfers here.
1392 * Otherwise this will be done in the stream's async I/O thread. */
1393 rc2 = ichac97R3StreamTransfer(pDevIns, pThis, pStream, pStreamCC, cbStreamUsed);
1394 AssertRC(rc2);
1395 }
1396
1397 /*
1398 * We should always kick the AIO thread.
1399 */
1400 /** @todo This isn't entirely ideal. If we get into an underrun situation,
1401 * we ideally want the AIO thread to run right before the DMA timer
1402 * rather than right after it ran. */
1403 Log5Func(("Notifying AIO thread\n"));
1404 rc2 = AudioMixerSinkSignalUpdateJob(pSink);
1405 AssertRC(rc2);
1406 pStreamCC->State.tsLastUpdateNs = RTTimeNanoTS();
1407 }
1408}
1409
1410
1411/**
1412 * @callback_method_impl{FNAUDMIXSINKUPDATE}
1413 *
1414 * For output streams this moves data from the internal DMA buffer (in which
1415 * ichac97R3StreamUpdateDma put it), thru the mixer and to the various backend
1416 * audio devices.
1417 *
1418 * For input streams this pulls data from the backend audio device(s), thru the
1419 * mixer and puts it in the internal DMA buffer ready for
1420 * ichac97R3StreamUpdateDma to pump into guest memory.
1421 */
1422static DECLCALLBACK(void) ichac97R3StreamUpdateAsyncIoJob(PPDMDEVINS pDevIns, PAUDMIXSINK pSink, void *pvUser)
1423{
1424 PAC97STATER3 const pThisCC = PDMDEVINS_2_DATA_CC(pDevIns, PAC97STATER3);
1425 PAC97STREAMR3 const pStreamCC = (PAC97STREAMR3)pvUser;
1426 Assert(pStreamCC->u8SD == (uintptr_t)(pStreamCC - &pThisCC->aStreams[0]));
1427 Assert(pSink == ichac97R3IndexToSink(pThisCC, pStreamCC->u8SD));
1428 RT_NOREF(pThisCC);
1429
1430 /*
1431 * Output (SDO).
1432 */
1433 if (pStreamCC->State.Cfg.enmDir == PDMAUDIODIR_OUT)
1434 ichac97R3StreamPushToMixer(pStreamCC, pSink);
1435 /*
1436 * Input (SDI).
1437 */
1438 else
1439 ichac97R3StreamPullFromMixer(pStreamCC, pSink);
1440}
1441
1442#endif /* IN_RING3 */
1443
1444/**
1445 * Sets a AC'97 mixer control to a specific value.
1446 *
1447 * @returns VBox status code.
1448 * @param pThis The shared AC'97 state.
1449 * @param uMixerIdx Mixer control to set value for.
1450 * @param uVal Value to set.
1451 */
1452static void ichac97MixerSet(PAC97STATE pThis, uint8_t uMixerIdx, uint16_t uVal)
1453{
1454 AssertMsgReturnVoid(uMixerIdx + 2U <= sizeof(pThis->mixer_data),
1455 ("Index %RU8 out of bounds (%zu)\n", uMixerIdx, sizeof(pThis->mixer_data)));
1456
1457 LogRel2(("AC97: Setting mixer index #%RU8 to %RU16 (%RU8 %RU8)\n",
1458 uMixerIdx, uVal, RT_HI_U8(uVal), RT_LO_U8(uVal)));
1459
1460 pThis->mixer_data[uMixerIdx + 0] = RT_LO_U8(uVal);
1461 pThis->mixer_data[uMixerIdx + 1] = RT_HI_U8(uVal);
1462}
1463
1464/**
1465 * Gets a value from a specific AC'97 mixer control.
1466 *
1467 * @returns Retrieved mixer control value.
1468 * @param pThis The shared AC'97 state.
1469 * @param uMixerIdx Mixer control to get value for.
1470 */
1471static uint16_t ichac97MixerGet(PAC97STATE pThis, uint32_t uMixerIdx)
1472{
1473 AssertMsgReturn(uMixerIdx + 2U <= sizeof(pThis->mixer_data),
1474 ("Index %RU8 out of bounds (%zu)\n", uMixerIdx, sizeof(pThis->mixer_data)),
1475 UINT16_MAX);
1476 return RT_MAKE_U16(pThis->mixer_data[uMixerIdx + 0], pThis->mixer_data[uMixerIdx + 1]);
1477}
1478
1479#ifdef IN_RING3
1480
1481/**
1482 * Retrieves a specific driver stream of a AC'97 driver.
1483 *
1484 * @returns Pointer to driver stream if found, or NULL if not found.
1485 * @param pDrv Driver to retrieve driver stream for.
1486 * @param enmDir Stream direction to retrieve.
1487 * @param enmPath Stream destination / source to retrieve.
1488 */
1489static PAC97DRIVERSTREAM ichac97R3MixerGetDrvStream(PAC97DRIVER pDrv, PDMAUDIODIR enmDir, PDMAUDIOPATH enmPath)
1490{
1491 PAC97DRIVERSTREAM pDrvStream = NULL;
1492
1493 if (enmDir == PDMAUDIODIR_IN)
1494 {
1495 LogFunc(("enmRecSource=%d\n", enmPath));
1496
1497 switch (enmPath)
1498 {
1499 case PDMAUDIOPATH_IN_LINE:
1500 pDrvStream = &pDrv->LineIn;
1501 break;
1502 case PDMAUDIOPATH_IN_MIC:
1503 pDrvStream = &pDrv->MicIn;
1504 break;
1505 default:
1506 AssertFailed();
1507 break;
1508 }
1509 }
1510 else if (enmDir == PDMAUDIODIR_OUT)
1511 {
1512 LogFunc(("enmPlaybackDst=%d\n", enmPath));
1513
1514 switch (enmPath)
1515 {
1516 case PDMAUDIOPATH_OUT_FRONT:
1517 pDrvStream = &pDrv->Out;
1518 break;
1519 default:
1520 AssertFailed();
1521 break;
1522 }
1523 }
1524 else
1525 AssertFailed();
1526
1527 return pDrvStream;
1528}
1529
1530/**
1531 * Adds a driver stream to a specific mixer sink.
1532 *
1533 * @returns VBox status code.
1534 * @param pDevIns The device instance.
1535 * @param pMixSink Mixer sink to add driver stream to.
1536 * @param pCfg Stream configuration to use.
1537 * @param pDrv Driver stream to add.
1538 */
1539static int ichac97R3MixerAddDrvStream(PPDMDEVINS pDevIns, PAUDMIXSINK pMixSink, PPDMAUDIOSTREAMCFG pCfg, PAC97DRIVER pDrv)
1540{
1541 AssertPtrReturn(pMixSink, VERR_INVALID_POINTER);
1542
1543 PPDMAUDIOSTREAMCFG pStreamCfg = PDMAudioStrmCfgDup(pCfg);
1544 if (!pStreamCfg)
1545 return VERR_NO_MEMORY;
1546
1547 AssertCompile(sizeof(pStreamCfg->szName) == sizeof(pCfg->szName));
1548 RTStrCopy(pStreamCfg->szName, sizeof(pStreamCfg->szName), pCfg->szName);
1549
1550 LogFunc(("[LUN#%RU8] %s\n", pDrv->uLUN, pStreamCfg->szName));
1551
1552 int rc;
1553
1554 PAC97DRIVERSTREAM pDrvStream = ichac97R3MixerGetDrvStream(pDrv, pStreamCfg->enmDir, pStreamCfg->enmPath);
1555 if (pDrvStream)
1556 {
1557 AssertMsg(pDrvStream->pMixStrm == NULL, ("[LUN#%RU8] Driver stream already present when it must not\n", pDrv->uLUN));
1558
1559 PAUDMIXSTREAM pMixStrm;
1560 rc = AudioMixerSinkCreateStream(pMixSink, pDrv->pConnector, pStreamCfg, pDevIns, &pMixStrm);
1561 LogFlowFunc(("LUN#%RU8: Created stream \"%s\" for sink, rc=%Rrc\n", pDrv->uLUN, pStreamCfg->szName, rc));
1562 if (RT_SUCCESS(rc))
1563 {
1564 rc = AudioMixerSinkAddStream(pMixSink, pMixStrm);
1565 LogFlowFunc(("LUN#%RU8: Added stream \"%s\" to sink, rc=%Rrc\n", pDrv->uLUN, pStreamCfg->szName, rc));
1566 if (RT_FAILURE(rc))
1567 AudioMixerStreamDestroy(pMixStrm, pDevIns, true /*fImmediate*/);
1568 }
1569
1570 if (RT_SUCCESS(rc))
1571 pDrvStream->pMixStrm = pMixStrm;
1572 }
1573 else
1574 rc = VERR_INVALID_PARAMETER;
1575
1576 PDMAudioStrmCfgFree(pStreamCfg);
1577
1578 LogFlowFuncLeaveRC(rc);
1579 return rc;
1580}
1581
1582/**
1583 * Adds all current driver streams to a specific mixer sink.
1584 *
1585 * @returns VBox status code.
1586 * @param pDevIns The device instance.
1587 * @param pThisCC The ring-3 AC'97 state.
1588 * @param pMixSink Mixer sink to add stream to.
1589 * @param pCfg Stream configuration to use.
1590 */
1591static int ichac97R3MixerAddDrvStreams(PPDMDEVINS pDevIns, PAC97STATER3 pThisCC, PAUDMIXSINK pMixSink, PPDMAUDIOSTREAMCFG pCfg)
1592{
1593 AssertPtrReturn(pMixSink, VERR_INVALID_POINTER);
1594
1595 if (!AudioHlpStreamCfgIsValid(pCfg))
1596 return VERR_INVALID_PARAMETER;
1597
1598 int rc = AudioMixerSinkSetFormat(pMixSink, &pCfg->Props);
1599 if (RT_FAILURE(rc))
1600 return rc;
1601
1602 PAC97DRIVER pDrv;
1603 RTListForEach(&pThisCC->lstDrv, pDrv, AC97DRIVER, Node)
1604 {
1605 int rc2 = ichac97R3MixerAddDrvStream(pDevIns, pMixSink, pCfg, pDrv);
1606 if (RT_FAILURE(rc2))
1607 LogFunc(("Attaching stream failed with %Rrc\n", rc2));
1608
1609 /* Do not pass failure to rc here, as there might be drivers which aren't
1610 * configured / ready yet. */
1611 }
1612
1613 LogFlowFuncLeaveRC(rc);
1614 return rc;
1615}
1616
1617/**
1618 * Adds a specific AC'97 driver to the driver chain.
1619 *
1620 * @returns VBox status code.
1621 * @param pDevIns The device instance.
1622 * @param pThisCC The ring-3 AC'97 device state.
1623 * @param pDrv The AC'97 driver to add.
1624 */
1625static int ichac97R3MixerAddDrv(PPDMDEVINS pDevIns, PAC97STATER3 pThisCC, PAC97DRIVER pDrv)
1626{
1627 int rc = VINF_SUCCESS;
1628
1629 if (AudioHlpStreamCfgIsValid(&pThisCC->aStreams[AC97SOUNDSOURCE_PI_INDEX].State.Cfg))
1630 rc = ichac97R3MixerAddDrvStream(pDevIns, pThisCC->pSinkLineIn,
1631 &pThisCC->aStreams[AC97SOUNDSOURCE_PI_INDEX].State.Cfg, pDrv);
1632
1633 if (AudioHlpStreamCfgIsValid(&pThisCC->aStreams[AC97SOUNDSOURCE_PO_INDEX].State.Cfg))
1634 {
1635 int rc2 = ichac97R3MixerAddDrvStream(pDevIns, pThisCC->pSinkOut,
1636 &pThisCC->aStreams[AC97SOUNDSOURCE_PO_INDEX].State.Cfg, pDrv);
1637 if (RT_SUCCESS(rc))
1638 rc = rc2;
1639 }
1640
1641 if (AudioHlpStreamCfgIsValid(&pThisCC->aStreams[AC97SOUNDSOURCE_MC_INDEX].State.Cfg))
1642 {
1643 int rc2 = ichac97R3MixerAddDrvStream(pDevIns, pThisCC->pSinkMicIn,
1644 &pThisCC->aStreams[AC97SOUNDSOURCE_MC_INDEX].State.Cfg, pDrv);
1645 if (RT_SUCCESS(rc))
1646 rc = rc2;
1647 }
1648
1649 return rc;
1650}
1651
1652/**
1653 * Removes a specific AC'97 driver from the driver chain and destroys its
1654 * associated streams.
1655 *
1656 * @param pDevIns The device instance.
1657 * @param pThisCC The ring-3 AC'97 device state.
1658 * @param pDrv AC'97 driver to remove.
1659 */
1660static void ichac97R3MixerRemoveDrv(PPDMDEVINS pDevIns, PAC97STATER3 pThisCC, PAC97DRIVER pDrv)
1661{
1662 if (pDrv->MicIn.pMixStrm)
1663 {
1664 AudioMixerSinkRemoveStream(pThisCC->pSinkMicIn, pDrv->MicIn.pMixStrm);
1665 AudioMixerStreamDestroy(pDrv->MicIn.pMixStrm, pDevIns, true /*fImmediate*/);
1666 pDrv->MicIn.pMixStrm = NULL;
1667 }
1668
1669 if (pDrv->LineIn.pMixStrm)
1670 {
1671 AudioMixerSinkRemoveStream(pThisCC->pSinkLineIn, pDrv->LineIn.pMixStrm);
1672 AudioMixerStreamDestroy(pDrv->LineIn.pMixStrm, pDevIns, true /*fImmediate*/);
1673 pDrv->LineIn.pMixStrm = NULL;
1674 }
1675
1676 if (pDrv->Out.pMixStrm)
1677 {
1678 AudioMixerSinkRemoveStream(pThisCC->pSinkOut, pDrv->Out.pMixStrm);
1679 AudioMixerStreamDestroy(pDrv->Out.pMixStrm, pDevIns, true /*fImmediate*/);
1680 pDrv->Out.pMixStrm = NULL;
1681 }
1682
1683 RTListNodeRemove(&pDrv->Node);
1684}
1685
1686/**
1687 * Removes a driver stream from a specific mixer sink.
1688 *
1689 * @param pDevIns The device instance.
1690 * @param pMixSink Mixer sink to remove audio streams from.
1691 * @param enmDir Stream direction to remove.
1692 * @param enmPath Stream destination / source to remove.
1693 * @param pDrv Driver stream to remove.
1694 */
1695static void ichac97R3MixerRemoveDrvStream(PPDMDEVINS pDevIns, PAUDMIXSINK pMixSink, PDMAUDIODIR enmDir,
1696 PDMAUDIOPATH enmPath, PAC97DRIVER pDrv)
1697{
1698 PAC97DRIVERSTREAM pDrvStream = ichac97R3MixerGetDrvStream(pDrv, enmDir, enmPath);
1699 if (pDrvStream)
1700 {
1701 if (pDrvStream->pMixStrm)
1702 {
1703 AudioMixerSinkRemoveStream(pMixSink, pDrvStream->pMixStrm);
1704
1705 AudioMixerStreamDestroy(pDrvStream->pMixStrm, pDevIns, false /*fImmediate*/);
1706 pDrvStream->pMixStrm = NULL;
1707 }
1708 }
1709}
1710
1711/**
1712 * Removes all driver streams from a specific mixer sink.
1713 *
1714 * @param pDevIns The device instance.
1715 * @param pThisCC The ring-3 AC'97 state.
1716 * @param pMixSink Mixer sink to remove audio streams from.
1717 * @param enmDir Stream direction to remove.
1718 * @param enmPath Stream destination / source to remove.
1719 */
1720static void ichac97R3MixerRemoveDrvStreams(PPDMDEVINS pDevIns, PAC97STATER3 pThisCC, PAUDMIXSINK pMixSink,
1721 PDMAUDIODIR enmDir, PDMAUDIOPATH enmPath)
1722{
1723 AssertPtrReturnVoid(pMixSink);
1724
1725 PAC97DRIVER pDrv;
1726 RTListForEach(&pThisCC->lstDrv, pDrv, AC97DRIVER, Node)
1727 {
1728 ichac97R3MixerRemoveDrvStream(pDevIns, pMixSink, enmDir, enmPath, pDrv);
1729 }
1730}
1731
1732
1733/**
1734 * Updates the next transfer based on a specific amount of bytes.
1735 *
1736 * @param pDevIns The device instance.
1737 * @param pStream The AC'97 stream to update (shared).
1738 * @param pStreamCC The AC'97 stream to update (ring-3).
1739 */
1740static void ichac97R3StreamTransferUpdate(PPDMDEVINS pDevIns, PAC97STREAM pStream, PAC97STREAMR3 pStreamCC)
1741{
1742 /*
1743 * Get the number of bytes left in the current buffer.
1744 *
1745 * This isn't entirely optimal iff the current entry doesn't have IOC set, in
1746 * that case we should use the number of bytes to the next IOC. Unfortuantely,
1747 * it seems the spec doesn't allow us to prefetch more than one BDLE, so we
1748 * probably cannot look ahead without violating that restriction. This is
1749 * probably a purely theoretical problem at this point.
1750 */
1751 uint32_t const cbLeftInBdle = pStream->Regs.picb * PDMAudioPropsSampleSize(&pStreamCC->State.Cfg.Props);
1752 if (cbLeftInBdle > 0) /** @todo r=bird: see todo about this in ichac97R3StreamFetchBDLE. */
1753 {
1754 /*
1755 * Since the buffer can be up to 0xfffe samples long (frame aligning stereo
1756 * prevents 0xffff), which translates to 743ms at a 44.1kHz rate, we must
1757 * also take the nominal timer frequency into account here so we keep
1758 * moving data at a steady rate. (In theory, I think the guest can even
1759 * set up just one buffer and anticipate where we are in the buffer
1760 * processing when it writes/reads from it. Linux seems to be doing such
1761 * configs when not playing or something.)
1762 */
1763 uint32_t const cbMaxPerHz = PDMAudioPropsNanoToBytes(&pStreamCC->State.Cfg.Props, RT_NS_1SEC / pStreamCC->State.uTimerHz);
1764
1765 if (cbLeftInBdle <= cbMaxPerHz)
1766 pStreamCC->State.cbTransferChunk = cbLeftInBdle;
1767 /* Try avoid leaving a very short period at the end of a buffer. */
1768 else if (cbLeftInBdle >= cbMaxPerHz + cbMaxPerHz / 2)
1769 pStreamCC->State.cbTransferChunk = cbMaxPerHz;
1770 else
1771 pStreamCC->State.cbTransferChunk = PDMAudioPropsFloorBytesToFrame(&pStreamCC->State.Cfg.Props, cbLeftInBdle / 2);
1772
1773 /*
1774 * Translate the chunk size to timer ticks.
1775 */
1776 uint64_t const cNsXferChunk = PDMAudioPropsBytesToNano(&pStreamCC->State.Cfg.Props, pStreamCC->State.cbTransferChunk);
1777 pStreamCC->State.cTransferTicks = PDMDevHlpTimerFromNano(pDevIns, pStream->hTimer, cNsXferChunk);
1778 Assert(pStreamCC->State.cTransferTicks > 0);
1779
1780 Log3Func(("[SD%RU8] cbLeftInBdle=%#RX32 cbMaxPerHz=%#RX32 (%RU16Hz) -> cbTransferChunk=%#RX32 cTransferTicks=%RX64\n",
1781 pStream->u8SD, cbLeftInBdle, cbMaxPerHz, pStreamCC->State.uTimerHz,
1782 pStreamCC->State.cbTransferChunk, pStreamCC->State.cTransferTicks));
1783 }
1784}
1785
1786
1787/**
1788 * Gets the frequency of a given stream.
1789 *
1790 * @returns The frequency. Zero if invalid stream index.
1791 * @param pThis The shared AC'97 device state.
1792 * @param idxStream The stream.
1793 */
1794DECLINLINE(uint32_t) ichach97R3CalcStreamHz(PAC97STATE pThis, uint8_t idxStream)
1795{
1796 switch (idxStream)
1797 {
1798 case AC97SOUNDSOURCE_PI_INDEX:
1799 return ichac97MixerGet(pThis, AC97_PCM_LR_ADC_Rate);
1800
1801 case AC97SOUNDSOURCE_MC_INDEX:
1802 return ichac97MixerGet(pThis, AC97_MIC_ADC_Rate);
1803
1804 case AC97SOUNDSOURCE_PO_INDEX:
1805 return ichac97MixerGet(pThis, AC97_PCM_Front_DAC_Rate);
1806
1807 default:
1808 AssertMsgFailedReturn(("%d\n", idxStream), 0);
1809 }
1810}
1811
1812
1813/**
1814 * Gets the PCM properties for a given stream.
1815 *
1816 * @returns pProps.
1817 * @param pThis The shared AC'97 device state.
1818 * @param idxStream Which stream
1819 * @param pProps Where to return the stream properties.
1820 */
1821DECLINLINE(PPDMAUDIOPCMPROPS) ichach97R3CalcStreamProps(PAC97STATE pThis, uint8_t idxStream, PPDMAUDIOPCMPROPS pProps)
1822{
1823 PDMAudioPropsInit(pProps, 2 /*16-bit*/, true /*signed*/, 2 /*stereo*/, ichach97R3CalcStreamHz(pThis, idxStream));
1824 return pProps;
1825}
1826
1827
1828/**
1829 * Opens an AC'97 stream with its current mixer settings.
1830 *
1831 * This will open an AC'97 stream with 2 (stereo) channels, 16-bit samples and
1832 * the last set sample rate in the AC'97 mixer for this stream.
1833 *
1834 * @returns VBox status code.
1835 * @param pDevIns The device instance.
1836 * @param pThis The shared AC'97 device state (shared).
1837 * @param pThisCC The shared AC'97 device state (ring-3).
1838 * @param pStream The AC'97 stream to open (shared).
1839 * @param pStreamCC The AC'97 stream to open (ring-3).
1840 * @param fForce Whether to force re-opening the stream or not.
1841 * Otherwise re-opening only will happen if the PCM properties have changed.
1842 */
1843static int ichac97R3StreamOpen(PPDMDEVINS pDevIns, PAC97STATE pThis, PAC97STATER3 pThisCC, PAC97STREAM pStream,
1844 PAC97STREAMR3 pStreamCC, bool fForce)
1845{
1846 /*
1847 * Assemble the stream config and get the associate mixer sink.
1848 */
1849 PDMAUDIOPCMPROPS PropsTmp;
1850 PDMAUDIOSTREAMCFG Cfg;
1851 PDMAudioStrmCfgInitWithProps(&Cfg, ichach97R3CalcStreamProps(pThis, pStream->u8SD, &PropsTmp));
1852
1853 PAUDMIXSINK pMixSink;
1854 switch (pStream->u8SD)
1855 {
1856 case AC97SOUNDSOURCE_PI_INDEX:
1857 Cfg.enmDir = PDMAUDIODIR_IN;
1858 Cfg.enmPath = PDMAUDIOPATH_IN_LINE;
1859 RTStrCopy(Cfg.szName, sizeof(Cfg.szName), "Line-In");
1860
1861 pMixSink = pThisCC->pSinkLineIn;
1862 break;
1863
1864 case AC97SOUNDSOURCE_MC_INDEX:
1865 Cfg.enmDir = PDMAUDIODIR_IN;
1866 Cfg.enmPath = PDMAUDIOPATH_IN_MIC;
1867 RTStrCopy(Cfg.szName, sizeof(Cfg.szName), "Mic-In");
1868
1869 pMixSink = pThisCC->pSinkMicIn;
1870 break;
1871
1872 case AC97SOUNDSOURCE_PO_INDEX:
1873 Cfg.enmDir = PDMAUDIODIR_OUT;
1874 Cfg.enmPath = PDMAUDIOPATH_OUT_FRONT;
1875 RTStrCopy(Cfg.szName, sizeof(Cfg.szName), "Output");
1876
1877 pMixSink = pThisCC->pSinkOut;
1878 break;
1879
1880 default:
1881 AssertMsgFailedReturn(("u8SD=%d\n", pStream->u8SD), VERR_INTERNAL_ERROR_3);
1882 }
1883
1884 /*
1885 * Read the buffer descriptors and check what the max distance between
1886 * interrupts are, so we can more correctly size the internal DMA buffer.
1887 *
1888 * Note! The buffer list are not fixed once the stream starts running as
1889 * with HDA, so this is just a general idea of what the guest is
1890 * up to and we cannot really make much of a plan out of it.
1891 */
1892 AC97BDLE aBdl[AC97_MAX_BDLE];
1893 RT_ZERO(aBdl);
1894 PDMDevHlpPCIPhysRead(pDevIns, pStream->Regs.bdbar, aBdl, sizeof(aBdl));
1895
1896 uint8_t const bLvi = pStream->Regs.lvi % AC97_MAX_BDLE /* paranoia */;
1897 uint8_t const bCiv = pStream->Regs.civ % AC97_MAX_BDLE /* paranoia */;
1898 uint32_t cSamplesMax = 0;
1899 uint32_t cSamplesMin = UINT32_MAX;
1900 uint32_t cSamplesCur = 0;
1901 uint32_t cSamplesTotal = 0;
1902 uint32_t cBuffers = 1;
1903 for (uintptr_t i = bCiv; ; cBuffers++)
1904 {
1905 cSamplesTotal += aBdl[i].ctl_len & AC97_BD_LEN_MASK;
1906 cSamplesCur += aBdl[i].ctl_len & AC97_BD_LEN_MASK;
1907 if (aBdl[i].ctl_len & AC97_BD_IOC)
1908 {
1909 if (cSamplesCur > cSamplesMax)
1910 cSamplesMax = cSamplesCur;
1911 if (cSamplesCur < cSamplesMin)
1912 cSamplesMin = cSamplesCur;
1913 cSamplesCur = 0;
1914 }
1915
1916 /* Advance. */
1917 if (i != bLvi)
1918 i = (i + 1) % RT_ELEMENTS(aBdl);
1919 else
1920 break;
1921 }
1922 if (!cSamplesCur)
1923 { /* likely */ }
1924 else if (!cSamplesMax)
1925 {
1926 LogFlowFunc(("%u buffers without IOC set, assuming %#x samples as the IOC period.\n", cBuffers, cSamplesMax));
1927 cSamplesMin = cSamplesMax = cSamplesCur;
1928 }
1929 else if (cSamplesCur > cSamplesMax)
1930 {
1931 LogFlowFunc(("final buffer is without IOC, using open period as max (%#x vs current max %#x).\n", cSamplesCur, cSamplesMax));
1932 cSamplesMax = cSamplesCur;
1933 }
1934 else
1935 LogFlowFunc(("final buffer is without IOC, ignoring (%#x vs current max %#x).\n", cSamplesCur, cSamplesMax));
1936
1937 uint32_t const cbDmaMinBuf = cSamplesMax * PDMAudioPropsSampleSize(&Cfg.Props) * 3; /* see further down */
1938 uint32_t const cMsDmaMinBuf = PDMAudioPropsBytesToMilli(&Cfg.Props, cbDmaMinBuf);
1939 LogRel3(("AC97: [SD%RU8] buffer length stats: total=%#x in %u buffers, min=%#x, max=%#x => min DMA buffer %u ms / %#x bytes\n",
1940 pStream->u8SD, cSamplesTotal, cBuffers, cSamplesMin, cSamplesMax, cMsDmaMinBuf, cbDmaMinBuf));
1941
1942 /*
1943 * Only (re-)create the stream (and driver chain) if we really have to.
1944 * Otherwise avoid this and just reuse it, as this costs performance.
1945 */
1946 int rc = VINF_SUCCESS;
1947 if ( fForce
1948 || !PDMAudioStrmCfgMatchesProps(&Cfg, &pStreamCC->State.Cfg.Props)
1949 || !pStreamCC->State.pCircBuf
1950 || cbDmaMinBuf > RTCircBufSize(pStreamCC->State.pCircBuf))
1951 {
1952 LogRel2(("AC97: (Re-)Opening stream '%s' (%RU32Hz, %RU8 channels, %s%RU8)\n", Cfg.szName, Cfg.Props.uHz,
1953 PDMAudioPropsChannels(&Cfg.Props), Cfg.Props.fSigned ? "S" : "U", PDMAudioPropsSampleBits(&Cfg.Props)));
1954
1955 LogFlowFunc(("[SD%RU8] uHz=%RU32\n", pStream->u8SD, Cfg.Props.uHz));
1956
1957 if (Cfg.Props.uHz)
1958 {
1959 Assert(Cfg.enmDir != PDMAUDIODIR_UNKNOWN);
1960
1961 /*
1962 * Set the stream's timer Hz rate, based on the PCM properties Hz rate.
1963 */
1964 if (pThis->uTimerHz == AC97_TIMER_HZ_DEFAULT) /* Make sure that we don't have any custom Hz rate set we want to enforce */
1965 {
1966 if (Cfg.Props.uHz > 44100) /* E.g. 48000 Hz. */
1967 pStreamCC->State.uTimerHz = 200;
1968 else /* Just take the global Hz rate otherwise. */
1969 pStreamCC->State.uTimerHz = pThis->uTimerHz;
1970 }
1971 else
1972 pStreamCC->State.uTimerHz = pThis->uTimerHz;
1973
1974 if ( pStreamCC->State.uTimerHz >= 10
1975 && pStreamCC->State.uTimerHz <= 500)
1976 { /* likely */ }
1977 else
1978 {
1979 LogFunc(("[SD%RU8] Adjusting uTimerHz=%u to %u\n", pStream->u8SD, pStreamCC->State.uTimerHz,
1980 Cfg.Props.uHz > 44100 ? 200 : AC97_TIMER_HZ_DEFAULT));
1981 pStreamCC->State.uTimerHz = Cfg.Props.uHz > 44100 ? 200 : AC97_TIMER_HZ_DEFAULT;
1982 }
1983
1984 /* Set scheduling hint. */
1985 Cfg.Device.cMsSchedulingHint = RT_MS_1SEC / pStreamCC->State.uTimerHz;
1986
1987 /*
1988 * Re-create the circular buffer if necessary.
1989 *
1990 * As mentioned in the HDA code, this should be at least able to hold the
1991 * data transferred in three DMA periods and in three AIO period (whichever
1992 * is higher). However, if we assume that the DMA code will engage the DMA
1993 * timer thread (currently EMT) if the AIO thread isn't getting schduled to
1994 * transfer data thru the stack, we don't need to go overboard and double
1995 * the minimums here. The less buffer the less possible delay can build when
1996 * TM is doing catch up.
1997 */
1998 uint32_t cMsCircBuf = Cfg.enmDir == PDMAUDIODIR_IN ? pThis->cMsCircBufIn : pThis->cMsCircBufOut;
1999 cMsCircBuf = RT_MAX(cMsCircBuf, cMsDmaMinBuf);
2000 cMsCircBuf = RT_MAX(cMsCircBuf, Cfg.Device.cMsSchedulingHint * 3);
2001 cMsCircBuf = RT_MIN(cMsCircBuf, RT_MS_1SEC * 2); /** @todo make sure the DMA timer doesn't go over 500ms (use uTimerHz as max, really). */
2002 uint32_t const cbCircBuf = PDMAudioPropsMilliToBytes(&Cfg.Props, cMsCircBuf);
2003
2004 if (pStreamCC->State.pCircBuf && RTCircBufSize(pStreamCC->State.pCircBuf) == cbCircBuf)
2005 RTCircBufReset(pStreamCC->State.pCircBuf);
2006 else
2007 {
2008 LogFlowFunc(("Re-creating circular buffer with size %u ms / %#x bytes (was %#x); cMsSchedulingHint=%u cMsDmaMinBuf=%u cMsCircBufXxx=%u\n",
2009 cMsCircBuf, cbCircBuf, pStreamCC->State.StatDmaBufSize, Cfg.Device.cMsSchedulingHint, cMsDmaMinBuf,
2010 Cfg.enmDir == PDMAUDIODIR_IN ? pThis->cMsCircBufIn : pThis->cMsCircBufOut));
2011 if (pStreamCC->State.pCircBuf)
2012 RTCircBufDestroy(pStreamCC->State.pCircBuf);
2013
2014 rc = RTCircBufCreate(&pStreamCC->State.pCircBuf, cbCircBuf);
2015 AssertRCReturnStmt(rc, pStreamCC->State.pCircBuf = NULL, rc);
2016
2017 pStreamCC->State.StatDmaBufSize = (uint32_t)RTCircBufSize(pStreamCC->State.pCircBuf);
2018 }
2019 Assert(pStreamCC->State.StatDmaBufSize == cbCircBuf);
2020
2021 /*
2022 * <there should be a comment here>
2023 */
2024 ichac97R3MixerRemoveDrvStreams(pDevIns, pThisCC, pMixSink, Cfg.enmDir, Cfg.enmPath);
2025 rc = ichac97R3MixerAddDrvStreams(pDevIns, pThisCC, pMixSink, &Cfg);
2026 if (RT_SUCCESS(rc))
2027 rc = PDMAudioStrmCfgCopy(&pStreamCC->State.Cfg, &Cfg);
2028 }
2029 LogFlowFunc(("[SD%RU8] rc=%Rrc\n", pStream->u8SD, rc));
2030 }
2031 else
2032 LogFlowFunc(("[SD%RU8] Skipping (re-)creation\n", pStream->u8SD));
2033 return rc;
2034}
2035
2036/**
2037 * Closes an AC'97 stream.
2038 *
2039 * @returns VBox status code.
2040 * @param pStream The AC'97 stream to close (shared).
2041 */
2042static int ichac97R3StreamClose(PAC97STREAM pStream)
2043{
2044 RT_NOREF(pStream);
2045 LogFlowFunc(("[SD%RU8]\n", pStream->u8SD));
2046 return VINF_SUCCESS;
2047}
2048
2049/**
2050 * Re-opens (that is, closes and opens again) an AC'97 stream on the backend
2051 * side with the current AC'97 mixer settings for this stream.
2052 *
2053 * @returns VBox status code.
2054 * @param pDevIns The device instance.
2055 * @param pThis The shared AC'97 device state.
2056 * @param pThisCC The ring-3 AC'97 device state.
2057 * @param pStream The AC'97 stream to re-open (shared).
2058 * @param pStreamCC The AC'97 stream to re-open (ring-3).
2059 * @param fForce Whether to force re-opening the stream or not.
2060 * Otherwise re-opening only will happen if the PCM properties have changed.
2061 */
2062static int ichac97R3StreamReOpen(PPDMDEVINS pDevIns, PAC97STATE pThis, PAC97STATER3 pThisCC,
2063 PAC97STREAM pStream, PAC97STREAMR3 pStreamCC, bool fForce)
2064{
2065 LogFlowFunc(("[SD%RU8]\n", pStream->u8SD));
2066 Assert(pStream->u8SD == pStreamCC->u8SD);
2067 Assert(pStream - &pThis->aStreams[0] == pStream->u8SD);
2068 Assert(pStreamCC - &pThisCC->aStreams[0] == pStream->u8SD);
2069
2070 int rc = ichac97R3StreamClose(pStream);
2071 if (RT_SUCCESS(rc))
2072 rc = ichac97R3StreamOpen(pDevIns, pThis, pThisCC, pStream, pStreamCC, fForce);
2073
2074 return rc;
2075}
2076
2077/**
2078 * Locks an AC'97 stream for serialized access.
2079 *
2080 * @returns VBox status code.
2081 * @param pStreamCC The AC'97 stream to lock (ring-3).
2082 */
2083static void ichac97R3StreamLock(PAC97STREAMR3 pStreamCC)
2084{
2085 int rc2 = RTCritSectEnter(&pStreamCC->State.CritSect);
2086 AssertRC(rc2);
2087}
2088
2089/**
2090 * Unlocks a formerly locked AC'97 stream.
2091 *
2092 * @returns VBox status code.
2093 * @param pStreamCC The AC'97 stream to unlock (ring-3).
2094 */
2095static void ichac97R3StreamUnlock(PAC97STREAMR3 pStreamCC)
2096{
2097 int rc2 = RTCritSectLeave(&pStreamCC->State.CritSect);
2098 AssertRC(rc2);
2099}
2100
2101/**
2102 * Retrieves the available size of (buffered) audio data (in bytes) of a given AC'97 stream.
2103 *
2104 * @returns Available data (in bytes).
2105 * @param pStreamCC The AC'97 stream to retrieve size for (ring-3).
2106 */
2107static uint32_t ichac97R3StreamGetUsed(PAC97STREAMR3 pStreamCC)
2108{
2109 if (!pStreamCC->State.pCircBuf)
2110 return 0;
2111
2112 return (uint32_t)RTCircBufUsed(pStreamCC->State.pCircBuf);
2113}
2114
2115/**
2116 * Retrieves the free size of audio data (in bytes) of a given AC'97 stream.
2117 *
2118 * @returns Free data (in bytes).
2119 * @param pStreamCC AC'97 stream to retrieve size for (ring-3).
2120 */
2121static uint32_t ichac97R3StreamGetFree(PAC97STREAMR3 pStreamCC)
2122{
2123 if (!pStreamCC->State.pCircBuf)
2124 return 0;
2125
2126 return (uint32_t)RTCircBufFree(pStreamCC->State.pCircBuf);
2127}
2128
2129/**
2130 * Sets the volume of a specific AC'97 mixer control.
2131 *
2132 * This currently only supports attenuation -- gain support is currently not implemented.
2133 *
2134 * @returns VBox status code.
2135 * @param pThis The shared AC'97 state.
2136 * @param pThisCC The ring-3 AC'97 state.
2137 * @param index AC'97 mixer index to set volume for.
2138 * @param enmMixerCtl Corresponding audio mixer sink.
2139 * @param uVal Volume value to set.
2140 */
2141static int ichac97R3MixerSetVolume(PAC97STATE pThis, PAC97STATER3 pThisCC, int index, PDMAUDIOMIXERCTL enmMixerCtl, uint32_t uVal)
2142{
2143 /*
2144 * From AC'97 SoundMax Codec AD1981A/AD1981B:
2145 * "Because AC '97 defines 6-bit volume registers, to maintain compatibility whenever the
2146 * D5 or D13 bits are set to 1, their respective lower five volume bits are automatically
2147 * set to 1 by the Codec logic. On readback, all lower 5 bits will read ones whenever
2148 * these bits are set to 1."
2149 *
2150 * Linux ALSA depends on this behavior to detect that only 5 bits are used for volume
2151 * control and the optional 6th bit is not used. Note that this logic only applies to the
2152 * master volume controls.
2153 */
2154 if (index == AC97_Master_Volume_Mute || index == AC97_Headphone_Volume_Mute || index == AC97_Master_Volume_Mono_Mute)
2155 {
2156 if (uVal & RT_BIT(5)) /* D5 bit set? */
2157 uVal |= RT_BIT(4) | RT_BIT(3) | RT_BIT(2) | RT_BIT(1) | RT_BIT(0);
2158 if (uVal & RT_BIT(13)) /* D13 bit set? */
2159 uVal |= RT_BIT(12) | RT_BIT(11) | RT_BIT(10) | RT_BIT(9) | RT_BIT(8);
2160 }
2161
2162 const bool fCtlMuted = (uVal >> AC97_BARS_VOL_MUTE_SHIFT) & 1;
2163 uint8_t uCtlAttLeft = (uVal >> 8) & AC97_BARS_VOL_MASK;
2164 uint8_t uCtlAttRight = uVal & AC97_BARS_VOL_MASK;
2165
2166 /* For the master and headphone volume, 0 corresponds to 0dB attenuation. For the other
2167 * volume controls, 0 means 12dB gain and 8 means unity gain.
2168 */
2169 if (index != AC97_Master_Volume_Mute && index != AC97_Headphone_Volume_Mute)
2170 {
2171# ifndef VBOX_WITH_AC97_GAIN_SUPPORT
2172 /* NB: Currently there is no gain support, only attenuation. */
2173 uCtlAttLeft = uCtlAttLeft < 8 ? 0 : uCtlAttLeft - 8;
2174 uCtlAttRight = uCtlAttRight < 8 ? 0 : uCtlAttRight - 8;
2175# endif
2176 }
2177 Assert(uCtlAttLeft <= 255 / AC97_DB_FACTOR);
2178 Assert(uCtlAttRight <= 255 / AC97_DB_FACTOR);
2179
2180 LogFunc(("index=0x%x, uVal=%RU32, enmMixerCtl=%RU32\n", index, uVal, enmMixerCtl));
2181 LogFunc(("uCtlAttLeft=%RU8, uCtlAttRight=%RU8 ", uCtlAttLeft, uCtlAttRight));
2182
2183 /*
2184 * For AC'97 volume controls, each additional step means -1.5dB attenuation with
2185 * zero being maximum. In contrast, we're internally using 255 (PDMAUDIO_VOLUME_MAX)
2186 * steps, each -0.375dB, where 0 corresponds to -96dB and 255 corresponds to 0dB.
2187 */
2188 uint8_t lVol = PDMAUDIO_VOLUME_MAX - uCtlAttLeft * AC97_DB_FACTOR;
2189 uint8_t rVol = PDMAUDIO_VOLUME_MAX - uCtlAttRight * AC97_DB_FACTOR;
2190
2191 Log(("-> fMuted=%RTbool, lVol=%RU8, rVol=%RU8\n", fCtlMuted, lVol, rVol));
2192
2193 int rc = VINF_SUCCESS;
2194
2195 if (pThisCC->pMixer) /* Device can be in reset state, so no mixer available. */
2196 {
2197 PDMAUDIOVOLUME Vol = { fCtlMuted, lVol, rVol };
2198 PAUDMIXSINK pSink = NULL;
2199
2200 switch (enmMixerCtl)
2201 {
2202 case PDMAUDIOMIXERCTL_VOLUME_MASTER:
2203 rc = AudioMixerSetMasterVolume(pThisCC->pMixer, &Vol);
2204 break;
2205
2206 case PDMAUDIOMIXERCTL_FRONT:
2207 pSink = pThisCC->pSinkOut;
2208 break;
2209
2210 case PDMAUDIOMIXERCTL_MIC_IN:
2211 case PDMAUDIOMIXERCTL_LINE_IN:
2212 /* These are recognized but do nothing. */
2213 break;
2214
2215 default:
2216 AssertFailed();
2217 rc = VERR_NOT_SUPPORTED;
2218 break;
2219 }
2220
2221 if (pSink)
2222 rc = AudioMixerSinkSetVolume(pSink, &Vol);
2223 }
2224
2225 ichac97MixerSet(pThis, index, uVal);
2226
2227 if (RT_FAILURE(rc))
2228 LogFlowFunc(("Failed with %Rrc\n", rc));
2229
2230 return rc;
2231}
2232
2233/**
2234 * Sets the gain of a specific AC'97 recording control.
2235 *
2236 * NB: gain support is currently not implemented in PDM audio.
2237 *
2238 * @returns VBox status code.
2239 * @param pThis The shared AC'97 state.
2240 * @param pThisCC The ring-3 AC'97 state.
2241 * @param index AC'97 mixer index to set volume for.
2242 * @param enmMixerCtl Corresponding audio mixer sink.
2243 * @param uVal Volume value to set.
2244 */
2245static int ichac97R3MixerSetGain(PAC97STATE pThis, PAC97STATER3 pThisCC, int index, PDMAUDIOMIXERCTL enmMixerCtl, uint32_t uVal)
2246{
2247 /*
2248 * For AC'97 recording controls, each additional step means +1.5dB gain with
2249 * zero being 0dB gain and 15 being +22.5dB gain.
2250 */
2251 const bool fCtlMuted = (uVal >> AC97_BARS_VOL_MUTE_SHIFT) & 1;
2252 uint8_t uCtlGainLeft = (uVal >> 8) & AC97_BARS_GAIN_MASK;
2253 uint8_t uCtlGainRight = uVal & AC97_BARS_GAIN_MASK;
2254
2255 Assert(uCtlGainLeft <= 255 / AC97_DB_FACTOR);
2256 Assert(uCtlGainRight <= 255 / AC97_DB_FACTOR);
2257
2258 LogFunc(("index=0x%x, uVal=%RU32, enmMixerCtl=%RU32\n", index, uVal, enmMixerCtl));
2259 LogFunc(("uCtlGainLeft=%RU8, uCtlGainRight=%RU8 ", uCtlGainLeft, uCtlGainRight));
2260
2261 uint8_t lVol = PDMAUDIO_VOLUME_MAX + uCtlGainLeft * AC97_DB_FACTOR;
2262 uint8_t rVol = PDMAUDIO_VOLUME_MAX + uCtlGainRight * AC97_DB_FACTOR;
2263
2264 /* We do not currently support gain. Since AC'97 does not support attenuation
2265 * for the recording input, the best we can do is set the maximum volume.
2266 */
2267# ifndef VBOX_WITH_AC97_GAIN_SUPPORT
2268 /* NB: Currently there is no gain support, only attenuation. Since AC'97 does not
2269 * support attenuation for the recording inputs, the best we can do is set the
2270 * maximum volume.
2271 */
2272 lVol = rVol = PDMAUDIO_VOLUME_MAX;
2273# endif
2274
2275 Log(("-> fMuted=%RTbool, lVol=%RU8, rVol=%RU8\n", fCtlMuted, lVol, rVol));
2276
2277 int rc = VINF_SUCCESS;
2278
2279 if (pThisCC->pMixer) /* Device can be in reset state, so no mixer available. */
2280 {
2281 PDMAUDIOVOLUME Vol = { fCtlMuted, lVol, rVol };
2282 PAUDMIXSINK pSink = NULL;
2283
2284 switch (enmMixerCtl)
2285 {
2286 case PDMAUDIOMIXERCTL_MIC_IN:
2287 pSink = pThisCC->pSinkMicIn;
2288 break;
2289
2290 case PDMAUDIOMIXERCTL_LINE_IN:
2291 pSink = pThisCC->pSinkLineIn;
2292 break;
2293
2294 default:
2295 AssertFailed();
2296 rc = VERR_NOT_SUPPORTED;
2297 break;
2298 }
2299
2300 if (pSink) {
2301 rc = AudioMixerSinkSetVolume(pSink, &Vol);
2302 /* There is only one AC'97 recording gain control. If line in
2303 * is changed, also update the microphone. If the optional dedicated
2304 * microphone is changed, only change that.
2305 * NB: The codecs we support do not have the dedicated microphone control.
2306 */
2307 if ((pSink == pThisCC->pSinkLineIn) && pThisCC->pSinkMicIn)
2308 rc = AudioMixerSinkSetVolume(pSink, &Vol);
2309 }
2310 }
2311
2312 ichac97MixerSet(pThis, index, uVal);
2313
2314 if (RT_FAILURE(rc))
2315 LogFlowFunc(("Failed with %Rrc\n", rc));
2316
2317 return rc;
2318}
2319
2320/**
2321 * Converts an AC'97 recording source index to a PDM audio recording source.
2322 *
2323 * @returns PDM audio recording source.
2324 * @param uIdx AC'97 index to convert.
2325 */
2326static PDMAUDIOPATH ichac97R3IdxToRecSource(uint8_t uIdx)
2327{
2328 switch (uIdx)
2329 {
2330 case AC97_REC_MIC: return PDMAUDIOPATH_IN_MIC;
2331 case AC97_REC_CD: return PDMAUDIOPATH_IN_CD;
2332 case AC97_REC_VIDEO: return PDMAUDIOPATH_IN_VIDEO;
2333 case AC97_REC_AUX: return PDMAUDIOPATH_IN_AUX;
2334 case AC97_REC_LINE_IN: return PDMAUDIOPATH_IN_LINE;
2335 case AC97_REC_PHONE: return PDMAUDIOPATH_IN_PHONE;
2336 default:
2337 break;
2338 }
2339
2340 LogFlowFunc(("Unknown record source %d, using MIC\n", uIdx));
2341 return PDMAUDIOPATH_IN_MIC;
2342}
2343
2344/**
2345 * Converts a PDM audio recording source to an AC'97 recording source index.
2346 *
2347 * @returns AC'97 recording source index.
2348 * @param enmRecSrc PDM audio recording source to convert.
2349 */
2350static uint8_t ichac97R3RecSourceToIdx(PDMAUDIOPATH enmRecSrc)
2351{
2352 switch (enmRecSrc)
2353 {
2354 case PDMAUDIOPATH_IN_MIC: return AC97_REC_MIC;
2355 case PDMAUDIOPATH_IN_CD: return AC97_REC_CD;
2356 case PDMAUDIOPATH_IN_VIDEO: return AC97_REC_VIDEO;
2357 case PDMAUDIOPATH_IN_AUX: return AC97_REC_AUX;
2358 case PDMAUDIOPATH_IN_LINE: return AC97_REC_LINE_IN;
2359 case PDMAUDIOPATH_IN_PHONE: return AC97_REC_PHONE;
2360 default:
2361 AssertMsgFailedBreak(("%d\n", enmRecSrc));
2362 }
2363
2364 LogFlowFunc(("Unknown audio recording source %d using MIC\n", enmRecSrc));
2365 return AC97_REC_MIC;
2366}
2367
2368/**
2369 * Returns the audio direction of a specified stream descriptor.
2370 *
2371 * @return Audio direction.
2372 */
2373DECLINLINE(PDMAUDIODIR) ichac97GetDirFromSD(uint8_t uSD)
2374{
2375 switch (uSD)
2376 {
2377 case AC97SOUNDSOURCE_PI_INDEX: return PDMAUDIODIR_IN;
2378 case AC97SOUNDSOURCE_PO_INDEX: return PDMAUDIODIR_OUT;
2379 case AC97SOUNDSOURCE_MC_INDEX: return PDMAUDIODIR_IN;
2380 }
2381
2382 AssertFailed();
2383 return PDMAUDIODIR_UNKNOWN;
2384}
2385
2386#endif /* IN_RING3 */
2387
2388#ifdef IN_RING3
2389
2390/**
2391 * Performs an AC'97 mixer record select to switch to a different recording
2392 * source.
2393 *
2394 * @param pThis The shared AC'97 state.
2395 * @param val AC'97 recording source index to set.
2396 */
2397static void ichac97R3MixerRecordSelect(PAC97STATE pThis, uint32_t val)
2398{
2399 uint8_t rs = val & AC97_REC_MASK;
2400 uint8_t ls = (val >> 8) & AC97_REC_MASK;
2401
2402 PDMAUDIOPATH const ars = ichac97R3IdxToRecSource(rs);
2403 PDMAUDIOPATH const als = ichac97R3IdxToRecSource(ls);
2404
2405 rs = ichac97R3RecSourceToIdx(ars);
2406 ls = ichac97R3RecSourceToIdx(als);
2407
2408 LogRel(("AC97: Record select to left=%s, right=%s\n", PDMAudioPathGetName(ars), PDMAudioPathGetName(als)));
2409
2410 ichac97MixerSet(pThis, AC97_Record_Select, rs | (ls << 8));
2411}
2412
2413/**
2414 * Resets the AC'97 mixer.
2415 *
2416 * @returns VBox status code.
2417 * @param pThis The shared AC'97 state.
2418 * @param pThisCC The ring-3 AC'97 state.
2419 */
2420static int ichac97R3MixerReset(PAC97STATE pThis, PAC97STATER3 pThisCC)
2421{
2422 LogFlowFuncEnter();
2423
2424 RT_ZERO(pThis->mixer_data);
2425
2426 /* Note: Make sure to reset all registers first before bailing out on error. */
2427
2428 ichac97MixerSet(pThis, AC97_Reset , 0x0000); /* 6940 */
2429 ichac97MixerSet(pThis, AC97_Master_Volume_Mono_Mute , 0x8000);
2430 ichac97MixerSet(pThis, AC97_PC_BEEP_Volume_Mute , 0x0000);
2431
2432 ichac97MixerSet(pThis, AC97_Phone_Volume_Mute , 0x8008);
2433 ichac97MixerSet(pThis, AC97_Mic_Volume_Mute , 0x8008);
2434 ichac97MixerSet(pThis, AC97_CD_Volume_Mute , 0x8808);
2435 ichac97MixerSet(pThis, AC97_Aux_Volume_Mute , 0x8808);
2436 ichac97MixerSet(pThis, AC97_Record_Gain_Mic_Mute , 0x8000);
2437 ichac97MixerSet(pThis, AC97_General_Purpose , 0x0000);
2438 ichac97MixerSet(pThis, AC97_3D_Control , 0x0000);
2439 ichac97MixerSet(pThis, AC97_Powerdown_Ctrl_Stat , 0x000f);
2440
2441 /* Configure Extended Audio ID (EAID) + Control & Status (EACS) registers. */
2442 const uint16_t fEAID = AC97_EAID_REV1 | AC97_EACS_VRA | AC97_EACS_VRM; /* Our hardware is AC'97 rev2.3 compliant. */
2443 const uint16_t fEACS = AC97_EACS_VRA | AC97_EACS_VRM; /* Variable Rate PCM Audio (VRA) + Mic-In (VRM) capable. */
2444
2445 LogRel(("AC97: Mixer reset (EAID=0x%x, EACS=0x%x)\n", fEAID, fEACS));
2446
2447 ichac97MixerSet(pThis, AC97_Extended_Audio_ID, fEAID);
2448 ichac97MixerSet(pThis, AC97_Extended_Audio_Ctrl_Stat, fEACS);
2449 ichac97MixerSet(pThis, AC97_PCM_Front_DAC_Rate , 0xbb80 /* 48000 Hz by default */);
2450 ichac97MixerSet(pThis, AC97_PCM_Surround_DAC_Rate , 0xbb80 /* 48000 Hz by default */);
2451 ichac97MixerSet(pThis, AC97_PCM_LFE_DAC_Rate , 0xbb80 /* 48000 Hz by default */);
2452 ichac97MixerSet(pThis, AC97_PCM_LR_ADC_Rate , 0xbb80 /* 48000 Hz by default */);
2453 ichac97MixerSet(pThis, AC97_MIC_ADC_Rate , 0xbb80 /* 48000 Hz by default */);
2454
2455 if (pThis->enmCodecModel == AC97CODEC_AD1980)
2456 {
2457 /* Analog Devices 1980 (AD1980) */
2458 ichac97MixerSet(pThis, AC97_Reset , 0x0010); /* Headphones. */
2459 ichac97MixerSet(pThis, AC97_Vendor_ID1 , 0x4144);
2460 ichac97MixerSet(pThis, AC97_Vendor_ID2 , 0x5370);
2461 ichac97MixerSet(pThis, AC97_Headphone_Volume_Mute , 0x8000);
2462 }
2463 else if (pThis->enmCodecModel == AC97CODEC_AD1981B)
2464 {
2465 /* Analog Devices 1981B (AD1981B) */
2466 ichac97MixerSet(pThis, AC97_Vendor_ID1 , 0x4144);
2467 ichac97MixerSet(pThis, AC97_Vendor_ID2 , 0x5374);
2468 }
2469 else
2470 {
2471 /* Sigmatel 9700 (STAC9700) */
2472 ichac97MixerSet(pThis, AC97_Vendor_ID1 , 0x8384);
2473 ichac97MixerSet(pThis, AC97_Vendor_ID2 , 0x7600); /* 7608 */
2474 }
2475 ichac97R3MixerRecordSelect(pThis, 0);
2476
2477 /* The default value is 8000h, which corresponds to 0 dB attenuation with mute on. */
2478 ichac97R3MixerSetVolume(pThis, pThisCC, AC97_Master_Volume_Mute, PDMAUDIOMIXERCTL_VOLUME_MASTER, 0x8000);
2479
2480 /* The default value for stereo registers is 8808h, which corresponds to 0 dB gain with mute on.*/
2481 ichac97R3MixerSetVolume(pThis, pThisCC, AC97_PCM_Out_Volume_Mute, PDMAUDIOMIXERCTL_FRONT, 0x8808);
2482 ichac97R3MixerSetVolume(pThis, pThisCC, AC97_Line_In_Volume_Mute, PDMAUDIOMIXERCTL_LINE_IN, 0x8808);
2483 ichac97R3MixerSetVolume(pThis, pThisCC, AC97_Mic_Volume_Mute, PDMAUDIOMIXERCTL_MIC_IN, 0x8008);
2484
2485 /* The default for record controls is 0 dB gain with mute on. */
2486 ichac97R3MixerSetGain(pThis, pThisCC, AC97_Record_Gain_Mute, PDMAUDIOMIXERCTL_LINE_IN, 0x8000);
2487 ichac97R3MixerSetGain(pThis, pThisCC, AC97_Record_Gain_Mic_Mute, PDMAUDIOMIXERCTL_MIC_IN, 0x8000);
2488
2489 return VINF_SUCCESS;
2490}
2491
2492# if 0 /* Unused */
2493static void ichac97R3WriteBUP(PAC97STATE pThis, uint32_t cbElapsed)
2494{
2495 LogFlowFunc(("cbElapsed=%RU32\n", cbElapsed));
2496
2497 if (!(pThis->bup_flag & BUP_SET))
2498 {
2499 if (pThis->bup_flag & BUP_LAST)
2500 {
2501 unsigned int i;
2502 uint32_t *p = (uint32_t*)pThis->silence;
2503 for (i = 0; i < sizeof(pThis->silence) / 4; i++) /** @todo r=andy Assumes 16-bit samples, stereo. */
2504 *p++ = pThis->last_samp;
2505 }
2506 else
2507 RT_ZERO(pThis->silence);
2508
2509 pThis->bup_flag |= BUP_SET;
2510 }
2511
2512 while (cbElapsed)
2513 {
2514 uint32_t cbToWrite = RT_MIN(cbElapsed, (uint32_t)sizeof(pThis->silence));
2515 uint32_t cbWrittenToStream;
2516
2517 int rc2 = AudioMixerSinkWrite(pThisCC->pSinkOut, AUDMIXOP_COPY,
2518 pThis->silence, cbToWrite, &cbWrittenToStream);
2519 if (RT_SUCCESS(rc2))
2520 {
2521 if (cbWrittenToStream < cbToWrite) /* Lagging behind? */
2522 LogFlowFunc(("Warning: Only written %RU32 / %RU32 bytes, expect lags\n", cbWrittenToStream, cbToWrite));
2523 }
2524
2525 /* Always report all data as being written;
2526 * backends who were not able to catch up have to deal with it themselves. */
2527 Assert(cbElapsed >= cbToWrite);
2528 cbElapsed -= cbToWrite;
2529 }
2530}
2531# endif /* Unused */
2532
2533/**
2534 * @callback_method_impl{FNTMTIMERDEV,
2535 * Timer callback which handles the audio data transfers on a periodic basis.}
2536 */
2537static DECLCALLBACK(void) ichac97R3Timer(PPDMDEVINS pDevIns, TMTIMERHANDLE hTimer, void *pvUser)
2538{
2539 PAC97STATE pThis = PDMDEVINS_2_DATA(pDevIns, PAC97STATE);
2540 STAM_PROFILE_START(&pThis->StatTimer, a);
2541 PAC97STATER3 pThisCC = PDMDEVINS_2_DATA_CC(pDevIns, PAC97STATER3);
2542 PAC97STREAM pStream = (PAC97STREAM)pvUser;
2543 PAC97STREAMR3 pStreamCC = &RT_SAFE_SUBSCRIPT8(pThisCC->aStreams, pStream->u8SD);
2544 Assert(hTimer == pStream->hTimer); RT_NOREF(hTimer);
2545
2546 Assert(pStream - &pThis->aStreams[0] == pStream->u8SD);
2547 Assert(PDMDevHlpCritSectIsOwner(pDevIns, &pThis->CritSect));
2548 Assert(PDMDevHlpTimerIsLockOwner(pDevIns, pStream->hTimer));
2549
2550 PAUDMIXSINK pSink = ichac97R3IndexToSink(pThisCC, pStream->u8SD);
2551 if (pSink && AudioMixerSinkIsActive(pSink))
2552 {
2553 ichac97R3StreamUpdateDma(pDevIns, pThis, pThisCC, pStream, pStreamCC);
2554
2555 ichac97R3StreamTransferUpdate(pDevIns, pStream, pStreamCC);
2556 ichac97R3TimerSet(pDevIns, pStream, pStreamCC->State.cTransferTicks);
2557 }
2558
2559 STAM_PROFILE_STOP(&pThis->StatTimer, a);
2560}
2561
2562
2563/**
2564 * Sets the virtual device timer to a new expiration time.
2565 *
2566 * @param pDevIns The device instance.
2567 * @param pStream AC'97 stream to set timer for.
2568 * @param cTicksToDeadline The number of ticks to the new deadline.
2569 *
2570 * @remarks This used to be more complicated a long time ago...
2571 */
2572DECLINLINE(void) ichac97R3TimerSet(PPDMDEVINS pDevIns, PAC97STREAM pStream, uint64_t cTicksToDeadline)
2573{
2574 int rc = PDMDevHlpTimerSetRelative(pDevIns, pStream->hTimer, cTicksToDeadline, NULL /*pu64Now*/);
2575 AssertRC(rc);
2576}
2577
2578
2579/**
2580 * Transfers data of an AC'97 stream according to its usage (input / output).
2581 *
2582 * For an SDO (output) stream this means reading DMA data from the device to
2583 * the AC'97 stream's internal FIFO buffer.
2584 *
2585 * For an SDI (input) stream this is reading audio data from the AC'97 stream's
2586 * internal FIFO buffer and writing it as DMA data to the device.
2587 *
2588 * @returns VBox status code.
2589 * @param pDevIns The device instance.
2590 * @param pThis The shared AC'97 state.
2591 * @param pStream The AC'97 stream to update (shared).
2592 * @param pStreamCC The AC'97 stream to update (ring-3).
2593 * @param cbToProcessMax Maximum of data (in bytes) to process.
2594 */
2595static int ichac97R3StreamTransfer(PPDMDEVINS pDevIns, PAC97STATE pThis, PAC97STREAM pStream,
2596 PAC97STREAMR3 pStreamCC, uint32_t cbToProcessMax)
2597{
2598 if (!cbToProcessMax)
2599 return VINF_SUCCESS;
2600
2601#ifdef VBOX_STRICT
2602 const unsigned cbFrame = PDMAudioPropsBytesPerFrame(&pStreamCC->State.Cfg.Props);
2603#endif
2604
2605 /* Make sure to only process an integer number of audio frames. */
2606 Assert(cbToProcessMax % cbFrame == 0);
2607
2608 ichac97R3StreamLock(pStreamCC);
2609
2610 PAC97BMREGS pRegs = &pStream->Regs;
2611
2612 if (pRegs->sr & AC97_SR_DCH) /* Controller halted? */
2613 {
2614 if (pRegs->cr & AC97_CR_RPBM) /* Bus master operation starts. */
2615 {
2616 switch (pStream->u8SD)
2617 {
2618 case AC97SOUNDSOURCE_PO_INDEX:
2619 /*ichac97R3WriteBUP(pThis, cbToProcess);*/
2620 break;
2621
2622 default:
2623 break;
2624 }
2625 }
2626
2627 ichac97R3StreamUnlock(pStreamCC);
2628 return VINF_SUCCESS;
2629 }
2630
2631 /* BCIS flag still set? Skip iteration. */
2632 if (pRegs->sr & AC97_SR_BCIS)
2633 {
2634 Log3Func(("[SD%RU8] BCIS set\n", pStream->u8SD));
2635
2636 ichac97R3StreamUnlock(pStreamCC);
2637 return VINF_SUCCESS;
2638 }
2639
2640 uint32_t cbLeft = RT_MIN((uint32_t)(pRegs->picb << 1), cbToProcessMax); /** @todo r=andy Assumes 16bit samples. */
2641 uint32_t cbProcessedTotal = 0;
2642
2643 PRTCIRCBUF pCircBuf = pStreamCC->State.pCircBuf;
2644 AssertPtr(pCircBuf);
2645
2646 int rc = VINF_SUCCESS;
2647
2648 Log3Func(("[SD%RU8] cbToProcessMax=%RU32, cbLeft=%RU32\n", pStream->u8SD, cbToProcessMax, cbLeft));
2649
2650 while (cbLeft)
2651 {
2652 if (!pRegs->picb) /* Got a new buffer descriptor, that is, the position is 0? */
2653 {
2654 Log3Func(("Fresh buffer descriptor %RU8 is empty, addr=%#x, len=%#x, skipping\n",
2655 pRegs->civ, pRegs->bd.addr, pRegs->bd.ctl_len));
2656 if (pRegs->civ == pRegs->lvi)
2657 {
2658 pRegs->sr |= AC97_SR_DCH; /** @todo r=andy Also set CELV? */
2659 pThis->bup_flag = 0;
2660
2661 rc = VINF_EOF;
2662 break;
2663 }
2664
2665 pRegs->sr &= ~AC97_SR_CELV;
2666 if (ichac97R3StreamFetchNextBdle(pDevIns, pStream, pStreamCC))
2667 ichac97StreamUpdateSR(pDevIns, pThis, pStream, pRegs->sr | AC97_SR_BCIS);
2668 continue;
2669 }
2670
2671 uint32_t cbChunk = cbLeft;
2672
2673 switch (pStream->u8SD)
2674 {
2675 case AC97SOUNDSOURCE_PO_INDEX: /* Output */
2676 {
2677 void *pvDst;
2678 size_t cbDst;
2679
2680 RTCircBufAcquireWriteBlock(pCircBuf, cbChunk, &pvDst, &cbDst);
2681
2682 if (cbDst)
2683 {
2684 int rc2 = PDMDevHlpPCIPhysRead(pDevIns, pRegs->bd.addr, (uint8_t *)pvDst, cbDst);
2685 AssertRC(rc2);
2686
2687 if (RT_LIKELY(!pStreamCC->Dbg.Runtime.fEnabled))
2688 { /* likely */ }
2689 else
2690 AudioHlpFileWrite(pStreamCC->Dbg.Runtime.pFileDMA, pvDst, cbDst, 0 /* fFlags */);
2691 }
2692
2693 RTCircBufReleaseWriteBlock(pCircBuf, cbDst);
2694
2695 cbChunk = (uint32_t)cbDst; /* Update the current chunk size to what really has been written. */
2696 break;
2697 }
2698
2699 case AC97SOUNDSOURCE_PI_INDEX: /* Input */
2700 case AC97SOUNDSOURCE_MC_INDEX: /* Input */
2701 {
2702 void *pvSrc;
2703 size_t cbSrc;
2704
2705 RTCircBufAcquireReadBlock(pCircBuf, cbChunk, &pvSrc, &cbSrc);
2706
2707 if (cbSrc)
2708 {
2709 int rc2 = PDMDevHlpPCIPhysWrite(pDevIns, pRegs->bd.addr, (uint8_t *)pvSrc, cbSrc);
2710 AssertRC(rc2);
2711
2712 if (RT_LIKELY(!pStreamCC->Dbg.Runtime.fEnabled))
2713 { /* likely */ }
2714 else
2715 AudioHlpFileWrite(pStreamCC->Dbg.Runtime.pFileDMA, pvSrc, cbSrc, 0 /* fFlags */);
2716 }
2717
2718 RTCircBufReleaseReadBlock(pCircBuf, cbSrc);
2719
2720 cbChunk = (uint32_t)cbSrc; /* Update the current chunk size to what really has been read. */
2721 break;
2722 }
2723
2724 default:
2725 AssertMsgFailed(("Stream #%RU8 not supported\n", pStream->u8SD));
2726 rc = VERR_NOT_SUPPORTED;
2727 break;
2728 }
2729
2730 if (RT_FAILURE(rc))
2731 break;
2732
2733 if (cbChunk)
2734 {
2735 cbProcessedTotal += cbChunk;
2736 Assert(cbProcessedTotal <= cbToProcessMax);
2737 Assert(cbLeft >= cbChunk);
2738 cbLeft -= cbChunk;
2739 Assert((cbChunk & 1) == 0); /* Else the following shift won't work */
2740
2741 pRegs->picb -= (cbChunk >> 1); /** @todo r=andy Assumes 16bit samples. */
2742 pRegs->bd.addr += cbChunk;
2743 }
2744
2745 LogFlowFunc(("[SD%RU8] cbChunk=%RU32, cbLeft=%RU32, cbTotal=%RU32, rc=%Rrc\n",
2746 pStream->u8SD, cbChunk, cbLeft, cbProcessedTotal, rc));
2747
2748 if (!pRegs->picb)
2749 {
2750 uint32_t new_sr = pRegs->sr & ~AC97_SR_CELV;
2751
2752 if (pRegs->bd.ctl_len & AC97_BD_IOC)
2753 {
2754 new_sr |= AC97_SR_BCIS;
2755 }
2756
2757 if (pRegs->civ == pRegs->lvi)
2758 {
2759 /* Did we run out of data? */
2760 LogFunc(("Underrun CIV (%RU8) == LVI (%RU8)\n", pRegs->civ, pRegs->lvi));
2761
2762 new_sr |= AC97_SR_LVBCI | AC97_SR_DCH | AC97_SR_CELV;
2763 pThis->bup_flag = (pRegs->bd.ctl_len & AC97_BD_BUP) ? BUP_LAST : 0;
2764
2765 rc = VINF_EOF;
2766 }
2767 else
2768 new_sr |= ichac97R3StreamFetchNextBdle(pDevIns, pStream, pStreamCC);
2769
2770 ichac97StreamUpdateSR(pDevIns, pThis, pStream, new_sr);
2771 }
2772
2773 if (/* All data processed? */
2774 rc == VINF_EOF
2775 /* ... or an error occurred? */
2776 || RT_FAILURE(rc))
2777 {
2778 break;
2779 }
2780 }
2781
2782 ichac97R3StreamUnlock(pStreamCC);
2783
2784 LogFlowFuncLeaveRC(rc);
2785 return rc;
2786}
2787
2788#endif /* IN_RING3 */
2789
2790
2791/**
2792 * @callback_method_impl{FNIOMIOPORTNEWIN}
2793 */
2794static DECLCALLBACK(VBOXSTRICTRC)
2795ichac97IoPortNabmRead(PPDMDEVINS pDevIns, void *pvUser, RTIOPORT offPort, uint32_t *pu32, unsigned cb)
2796{
2797 PAC97STATE pThis = PDMDEVINS_2_DATA(pDevIns, PAC97STATE);
2798 RT_NOREF(pvUser);
2799
2800 DEVAC97_LOCK_RETURN(pDevIns, pThis, VINF_IOM_R3_IOPORT_READ);
2801
2802 /* Get the index of the NABMBAR port. */
2803 if ( AC97_PORT2IDX_UNMASKED(offPort) < AC97_MAX_STREAMS
2804 && offPort != AC97_GLOB_CNT)
2805 {
2806 PAC97STREAM pStream = &pThis->aStreams[AC97_PORT2IDX(offPort)];
2807 PAC97BMREGS pRegs = &pStream->Regs;
2808
2809 switch (cb)
2810 {
2811 case 1:
2812 switch (offPort & AC97_NABM_OFF_MASK)
2813 {
2814 case AC97_NABM_OFF_CIV:
2815 /* Current Index Value Register */
2816 *pu32 = pRegs->civ;
2817 Log3Func(("CIV[%d] -> %#x\n", AC97_PORT2IDX(offPort), *pu32));
2818 break;
2819 case AC97_NABM_OFF_LVI:
2820 /* Last Valid Index Register */
2821 *pu32 = pRegs->lvi;
2822 Log3Func(("LVI[%d] -> %#x\n", AC97_PORT2IDX(offPort), *pu32));
2823 break;
2824 case AC97_NABM_OFF_PIV:
2825 /* Prefetched Index Value Register */
2826 *pu32 = pRegs->piv;
2827 Log3Func(("PIV[%d] -> %#x\n", AC97_PORT2IDX(offPort), *pu32));
2828 break;
2829 case AC97_NABM_OFF_CR:
2830 /* Control Register */
2831 *pu32 = pRegs->cr;
2832 Log3Func(("CR[%d] -> %#x\n", AC97_PORT2IDX(offPort), *pu32));
2833 break;
2834 case AC97_NABM_OFF_SR:
2835 /* Status Register (lower part) */
2836 *pu32 = RT_LO_U8(pRegs->sr);
2837 Log3Func(("SRb[%d] -> %#x\n", AC97_PORT2IDX(offPort), *pu32));
2838 break;
2839 default:
2840 *pu32 = UINT32_MAX;
2841 LogFunc(("U nabm readb %#x -> %#x\n", offPort, UINT32_MAX));
2842 STAM_REL_COUNTER_INC(&pThis->StatUnimplementedNabmReads);
2843 break;
2844 }
2845 break;
2846
2847 case 2:
2848 switch (offPort & AC97_NABM_OFF_MASK)
2849 {
2850 case AC97_NABM_OFF_SR:
2851 /* Status Register */
2852 *pu32 = pRegs->sr;
2853 Log3Func(("SR[%d] -> %#x\n", AC97_PORT2IDX(offPort), *pu32));
2854 break;
2855 case AC97_NABM_OFF_PICB:
2856 /* Position in Current Buffer */
2857 *pu32 = pRegs->picb;
2858 Log3Func(("PICB[%d] -> %#x\n", AC97_PORT2IDX(offPort), *pu32));
2859 break;
2860 default:
2861 *pu32 = UINT32_MAX;
2862 LogFunc(("U nabm readw %#x -> %#x\n", offPort, UINT32_MAX));
2863 STAM_REL_COUNTER_INC(&pThis->StatUnimplementedNabmReads);
2864 break;
2865 }
2866 break;
2867
2868 case 4:
2869 switch (offPort & AC97_NABM_OFF_MASK)
2870 {
2871 case AC97_NABM_OFF_BDBAR:
2872 /* Buffer Descriptor Base Address Register */
2873 *pu32 = pRegs->bdbar;
2874 Log3Func(("BMADDR[%d] -> %#x\n", AC97_PORT2IDX(offPort), *pu32));
2875 break;
2876 case AC97_NABM_OFF_CIV:
2877 /* 32-bit access: Current Index Value Register +
2878 * Last Valid Index Register +
2879 * Status Register */
2880 *pu32 = pRegs->civ | ((uint32_t)pRegs->lvi << 8) | ((uint32_t)pRegs->sr << 16);
2881 Log3Func(("CIV LVI SR[%d] -> %#x, %#x, %#x\n",
2882 AC97_PORT2IDX(offPort), pRegs->civ, pRegs->lvi, pRegs->sr));
2883 break;
2884 case AC97_NABM_OFF_PICB:
2885 /* 32-bit access: Position in Current Buffer Register +
2886 * Prefetched Index Value Register +
2887 * Control Register */
2888 *pu32 = pRegs->picb | ((uint32_t)pRegs->piv << 16) | ((uint32_t)pRegs->cr << 24);
2889 Log3Func(("PICB PIV CR[%d] -> %#x %#x %#x %#x\n",
2890 AC97_PORT2IDX(offPort), *pu32, pRegs->picb, pRegs->piv, pRegs->cr));
2891 break;
2892
2893 default:
2894 *pu32 = UINT32_MAX;
2895 LogFunc(("U nabm readl %#x -> %#x\n", offPort, UINT32_MAX));
2896 STAM_REL_COUNTER_INC(&pThis->StatUnimplementedNabmReads);
2897 break;
2898 }
2899 break;
2900
2901 default:
2902 DEVAC97_UNLOCK(pDevIns, pThis);
2903 AssertFailed();
2904 return VERR_IOM_IOPORT_UNUSED;
2905 }
2906 }
2907 else
2908 {
2909 switch (cb)
2910 {
2911 case 1:
2912 switch (offPort)
2913 {
2914 case AC97_CAS:
2915 /* Codec Access Semaphore Register */
2916 Log3Func(("CAS %d\n", pThis->cas));
2917 *pu32 = pThis->cas;
2918 pThis->cas = 1;
2919 break;
2920 default:
2921 *pu32 = UINT32_MAX;
2922 LogFunc(("U nabm readb %#x -> %#x\n", offPort, UINT32_MAX));
2923 STAM_REL_COUNTER_INC(&pThis->StatUnimplementedNabmReads);
2924 break;
2925 }
2926 break;
2927
2928 case 2:
2929 *pu32 = UINT32_MAX;
2930 LogFunc(("U nabm readw %#x -> %#x\n", offPort, UINT32_MAX));
2931 STAM_REL_COUNTER_INC(&pThis->StatUnimplementedNabmReads);
2932 break;
2933
2934 case 4:
2935 switch (offPort)
2936 {
2937 case AC97_GLOB_CNT:
2938 /* Global Control */
2939 *pu32 = pThis->glob_cnt;
2940 Log3Func(("glob_cnt -> %#x\n", *pu32));
2941 break;
2942 case AC97_GLOB_STA:
2943 /* Global Status */
2944 *pu32 = pThis->glob_sta | AC97_GS_S0CR;
2945 Log3Func(("glob_sta -> %#x\n", *pu32));
2946 break;
2947 default:
2948 *pu32 = UINT32_MAX;
2949 LogFunc(("U nabm readl %#x -> %#x\n", offPort, UINT32_MAX));
2950 STAM_REL_COUNTER_INC(&pThis->StatUnimplementedNabmReads);
2951 break;
2952 }
2953 break;
2954
2955 default:
2956 DEVAC97_UNLOCK(pDevIns, pThis);
2957 AssertFailed();
2958 return VERR_IOM_IOPORT_UNUSED;
2959 }
2960 }
2961
2962 DEVAC97_UNLOCK(pDevIns, pThis);
2963 return VINF_SUCCESS;
2964}
2965
2966/**
2967 * @callback_method_impl{FNIOMIOPORTNEWOUT}
2968 */
2969static DECLCALLBACK(VBOXSTRICTRC)
2970ichac97IoPortNabmWrite(PPDMDEVINS pDevIns, void *pvUser, RTIOPORT offPort, uint32_t u32, unsigned cb)
2971{
2972 PAC97STATE pThis = PDMDEVINS_2_DATA(pDevIns, PAC97STATE);
2973#ifdef IN_RING3
2974 PAC97STATER3 pThisCC = PDMDEVINS_2_DATA_CC(pDevIns, PAC97STATER3);
2975#endif
2976 RT_NOREF(pvUser);
2977
2978 VBOXSTRICTRC rc = VINF_SUCCESS;
2979 if ( AC97_PORT2IDX_UNMASKED(offPort) < AC97_MAX_STREAMS
2980 && offPort != AC97_GLOB_CNT)
2981 {
2982#ifdef IN_RING3
2983 PAC97STREAMR3 pStreamCC = &pThisCC->aStreams[AC97_PORT2IDX(offPort)];
2984#endif
2985 PAC97STREAM pStream = &pThis->aStreams[AC97_PORT2IDX(offPort)];
2986 PAC97BMREGS pRegs = &pStream->Regs;
2987
2988 DEVAC97_LOCK_BOTH_RETURN(pDevIns, pThis, pStream, VINF_IOM_R3_IOPORT_WRITE);
2989 switch (cb)
2990 {
2991 case 1:
2992 switch (offPort & AC97_NABM_OFF_MASK)
2993 {
2994 /*
2995 * Last Valid Index.
2996 */
2997 case AC97_NABM_OFF_LVI:
2998 if ( (pRegs->cr & AC97_CR_RPBM)
2999 && (pRegs->sr & AC97_SR_DCH))
3000 {
3001#ifdef IN_RING3 /** @todo r=bird: What kind of unexplained non-sense is this ifdef?!? */
3002 pRegs->sr &= ~(AC97_SR_DCH | AC97_SR_CELV);
3003 pRegs->civ = pRegs->piv;
3004 pRegs->piv = (pRegs->piv + 1) % AC97_MAX_BDLE;
3005#else
3006 rc = VINF_IOM_R3_IOPORT_WRITE;
3007#endif
3008 }
3009 pRegs->lvi = u32 % AC97_MAX_BDLE;
3010 Log3Func(("[SD%RU8] LVI <- %#x\n", pStream->u8SD, u32));
3011 break;
3012
3013 /*
3014 * Control Registers.
3015 */
3016 case AC97_NABM_OFF_CR:
3017#ifdef IN_RING3
3018 Log3Func(("[SD%RU8] CR <- %#x (cr %#x)\n", pStream->u8SD, u32, pRegs->cr));
3019 if (u32 & AC97_CR_RR) /* Busmaster reset. */
3020 {
3021 Log3Func(("[SD%RU8] Reset\n", pStream->u8SD));
3022
3023 /* Make sure that Run/Pause Bus Master bit (RPBM) is cleared (0). */
3024 Assert((pRegs->cr & AC97_CR_RPBM) == 0);
3025 if (pRegs->cr & AC97_CR_RPBM)
3026 ichac97R3StreamEnable(pDevIns, pThis, pThisCC, pStream, pStreamCC, false /* fEnable */);
3027
3028 ichac97R3StreamReset(pThis, pStream, pStreamCC);
3029
3030 ichac97StreamUpdateSR(pDevIns, pThis, pStream, AC97_SR_DCH); /** @todo Do we need to do that? */
3031 }
3032 else
3033 {
3034 pRegs->cr = u32 & AC97_CR_VALID_MASK;
3035
3036 if (!(pRegs->cr & AC97_CR_RPBM))
3037 {
3038 Log3Func(("[SD%RU8] Disable\n", pStream->u8SD));
3039
3040 ichac97R3StreamEnable(pDevIns, pThis, pThisCC, pStream, pStreamCC, false /* fEnable */);
3041
3042 pRegs->sr |= AC97_SR_DCH;
3043 }
3044 else
3045 {
3046 Log3Func(("[SD%RU8] Enable\n", pStream->u8SD));
3047
3048 pRegs->sr &= ~AC97_SR_DCH;
3049
3050 if (ichac97R3StreamFetchNextBdle(pDevIns, pStream, pStreamCC))
3051 ichac97StreamUpdateSR(pDevIns, pThis, pStream, pRegs->sr | AC97_SR_BCIS);
3052# ifdef LOG_ENABLED
3053 if (LogIsFlowEnabled())
3054 ichac97R3DbgPrintBdl(pDevIns, pThis, pStream, DBGFR3InfoLogHlp(), "ichac97IoPortNabmWrite: ");
3055# endif
3056 ichac97R3StreamEnable(pDevIns, pThis, pThisCC, pStream, pStreamCC, true /* fEnable */);
3057
3058 /* Arm the timer for this stream. */
3059 ichac97R3TimerSet(pDevIns, pStream, pStreamCC->State.cTransferTicks);
3060 }
3061 }
3062#else /* !IN_RING3 */
3063 rc = VINF_IOM_R3_IOPORT_WRITE;
3064#endif
3065 break;
3066
3067 /*
3068 * Status Registers.
3069 */
3070 case AC97_NABM_OFF_SR:
3071 ichac97StreamWriteSR(pDevIns, pThis, pStream, u32);
3072 break;
3073
3074 default:
3075 LogRel2(("AC97: Warning: Unimplemented NABMWrite offPort=%#x <- %#x LB 1\n", offPort, u32));
3076 STAM_REL_COUNTER_INC(&pThis->StatUnimplementedNabmWrites);
3077 break;
3078 }
3079 break;
3080
3081 case 2:
3082 switch (offPort & AC97_NABM_OFF_MASK)
3083 {
3084 case AC97_NABM_OFF_SR:
3085 ichac97StreamWriteSR(pDevIns, pThis, pStream, u32);
3086 break;
3087 default:
3088 LogRel2(("AC97: Warning: Unimplemented NABMWrite offPort=%#x <- %#x LB 2\n", offPort, u32));
3089 STAM_REL_COUNTER_INC(&pThis->StatUnimplementedNabmWrites);
3090 break;
3091 }
3092 break;
3093
3094 case 4:
3095 switch (offPort & AC97_NABM_OFF_MASK)
3096 {
3097 case AC97_NABM_OFF_BDBAR:
3098 /* Buffer Descriptor list Base Address Register */
3099 pRegs->bdbar = u32 & ~(uint32_t)3;
3100 Log3Func(("[SD%RU8] BDBAR <- %#x (bdbar %#x)\n", AC97_PORT2IDX(offPort), u32, pRegs->bdbar));
3101 break;
3102 default:
3103 LogRel2(("AC97: Warning: Unimplemented NABMWrite offPort=%#x <- %#x LB 4\n", offPort, u32));
3104 STAM_REL_COUNTER_INC(&pThis->StatUnimplementedNabmWrites);
3105 break;
3106 }
3107 break;
3108
3109 default:
3110 AssertMsgFailed(("offPort=%#x <- %#x LB %u\n", offPort, u32, cb));
3111 break;
3112 }
3113 DEVAC97_UNLOCK_BOTH(pDevIns, pThis, pStream);
3114 }
3115 else
3116 {
3117 switch (cb)
3118 {
3119 case 1:
3120 LogRel2(("AC97: Warning: Unimplemented NABMWrite offPort=%#x <- %#x LB 1\n", offPort, u32));
3121 STAM_REL_COUNTER_INC(&pThis->StatUnimplementedNabmWrites);
3122 break;
3123
3124 case 2:
3125 LogRel2(("AC97: Warning: Unimplemented NABMWrite offPort=%#x <- %#x LB 2\n", offPort, u32));
3126 STAM_REL_COUNTER_INC(&pThis->StatUnimplementedNabmWrites);
3127 break;
3128
3129 case 4:
3130 switch (offPort)
3131 {
3132 case AC97_GLOB_CNT:
3133 /* Global Control */
3134 DEVAC97_LOCK_RETURN(pDevIns, pThis, VINF_IOM_R3_IOPORT_WRITE);
3135 if (u32 & AC97_GC_WR)
3136 ichac97WarmReset(pThis);
3137 if (u32 & AC97_GC_CR)
3138 ichac97ColdReset(pThis);
3139 if (!(u32 & (AC97_GC_WR | AC97_GC_CR)))
3140 pThis->glob_cnt = u32 & AC97_GC_VALID_MASK;
3141 Log3Func(("glob_cnt <- %#x (glob_cnt %#x)\n", u32, pThis->glob_cnt));
3142 DEVAC97_UNLOCK(pDevIns, pThis);
3143 break;
3144 case AC97_GLOB_STA:
3145 /* Global Status */
3146 DEVAC97_LOCK_RETURN(pDevIns, pThis, VINF_IOM_R3_IOPORT_WRITE);
3147 pThis->glob_sta &= ~(u32 & AC97_GS_WCLEAR_MASK);
3148 pThis->glob_sta |= (u32 & ~(AC97_GS_WCLEAR_MASK | AC97_GS_RO_MASK)) & AC97_GS_VALID_MASK;
3149 Log3Func(("glob_sta <- %#x (glob_sta %#x)\n", u32, pThis->glob_sta));
3150 DEVAC97_UNLOCK(pDevIns, pThis);
3151 break;
3152 default:
3153 LogRel2(("AC97: Warning: Unimplemented NABMWrite offPort=%#x <- %#x LB 4\n", offPort, u32));
3154 STAM_REL_COUNTER_INC(&pThis->StatUnimplementedNabmWrites);
3155 break;
3156 }
3157 break;
3158
3159 default:
3160 AssertMsgFailed(("offPort=%#x <- %#x LB %u\n", offPort, u32, cb));
3161 break;
3162 }
3163 }
3164
3165 return rc;
3166}
3167
3168/**
3169 * @callback_method_impl{FNIOMIOPORTNEWIN}
3170 */
3171static DECLCALLBACK(VBOXSTRICTRC)
3172ichac97IoPortNamRead(PPDMDEVINS pDevIns, void *pvUser, RTIOPORT offPort, uint32_t *pu32, unsigned cb)
3173{
3174 PAC97STATE pThis = PDMDEVINS_2_DATA(pDevIns, PAC97STATE);
3175 RT_NOREF(pvUser);
3176 Assert(offPort < 256);
3177
3178 DEVAC97_LOCK_RETURN(pDevIns, pThis, VINF_IOM_R3_IOPORT_READ);
3179
3180 VBOXSTRICTRC rc = VINF_SUCCESS;
3181 switch (cb)
3182 {
3183 case 1:
3184 {
3185 LogRel2(("AC97: Warning: Unimplemented read (1 byte) offPort=%#x\n", offPort));
3186 pThis->cas = 0;
3187 *pu32 = UINT32_MAX;
3188 break;
3189 }
3190
3191 case 2:
3192 {
3193 pThis->cas = 0;
3194 *pu32 = ichac97MixerGet(pThis, offPort);
3195 break;
3196 }
3197
3198 case 4:
3199 {
3200 LogRel2(("AC97: Warning: Unimplemented read (4 bytes) offPort=%#x\n", offPort));
3201 pThis->cas = 0;
3202 *pu32 = UINT32_MAX;
3203 break;
3204 }
3205
3206 default:
3207 {
3208 AssertFailed();
3209 rc = VERR_IOM_IOPORT_UNUSED;
3210 }
3211 }
3212
3213 DEVAC97_UNLOCK(pDevIns, pThis);
3214 return rc;
3215}
3216
3217/**
3218 * @callback_method_impl{FNIOMIOPORTNEWOUT}
3219 */
3220static DECLCALLBACK(VBOXSTRICTRC)
3221ichac97IoPortNamWrite(PPDMDEVINS pDevIns, void *pvUser, RTIOPORT offPort, uint32_t u32, unsigned cb)
3222{
3223 PAC97STATE pThis = PDMDEVINS_2_DATA(pDevIns, PAC97STATE);
3224#ifdef IN_RING3
3225 PAC97STATER3 pThisCC = PDMDEVINS_2_DATA_CC(pDevIns, PAC97STATER3);
3226#endif
3227 RT_NOREF(pvUser);
3228
3229 DEVAC97_LOCK_RETURN(pDevIns, pThis, VINF_IOM_R3_IOPORT_WRITE);
3230
3231 VBOXSTRICTRC rc = VINF_SUCCESS;
3232 switch (cb)
3233 {
3234 case 1:
3235 {
3236 LogRel2(("AC97: Warning: Unimplemented NAMWrite (1 byte) offPort=%#x <- %#x\n", offPort, u32));
3237 pThis->cas = 0;
3238 break;
3239 }
3240
3241 case 2:
3242 {
3243 pThis->cas = 0;
3244 switch (offPort)
3245 {
3246 case AC97_Reset:
3247#ifdef IN_RING3
3248 ichac97R3Reset(pDevIns);
3249#else
3250 rc = VINF_IOM_R3_IOPORT_WRITE;
3251#endif
3252 break;
3253 case AC97_Powerdown_Ctrl_Stat:
3254 u32 &= ~0xf;
3255 u32 |= ichac97MixerGet(pThis, offPort) & 0xf;
3256 ichac97MixerSet(pThis, offPort, u32);
3257 break;
3258 case AC97_Master_Volume_Mute:
3259 if (pThis->enmCodecModel == AC97CODEC_AD1980)
3260 {
3261 if (ichac97MixerGet(pThis, AC97_AD_Misc) & AC97_AD_MISC_LOSEL)
3262 break; /* Register controls surround (rear), do nothing. */
3263 }
3264#ifdef IN_RING3
3265 ichac97R3MixerSetVolume(pThis, pThisCC, offPort, PDMAUDIOMIXERCTL_VOLUME_MASTER, u32);
3266#else
3267 rc = VINF_IOM_R3_IOPORT_WRITE;
3268#endif
3269 break;
3270 case AC97_Headphone_Volume_Mute:
3271 if (pThis->enmCodecModel == AC97CODEC_AD1980)
3272 {
3273 if (ichac97MixerGet(pThis, AC97_AD_Misc) & AC97_AD_MISC_HPSEL)
3274 {
3275 /* Register controls PCM (front) outputs. */
3276#ifdef IN_RING3
3277 ichac97R3MixerSetVolume(pThis, pThisCC, offPort, PDMAUDIOMIXERCTL_VOLUME_MASTER, u32);
3278#else
3279 rc = VINF_IOM_R3_IOPORT_WRITE;
3280#endif
3281 }
3282 }
3283 break;
3284 case AC97_PCM_Out_Volume_Mute:
3285#ifdef IN_RING3
3286 ichac97R3MixerSetVolume(pThis, pThisCC, offPort, PDMAUDIOMIXERCTL_FRONT, u32);
3287#else
3288 rc = VINF_IOM_R3_IOPORT_WRITE;
3289#endif
3290 break;
3291 case AC97_Line_In_Volume_Mute:
3292#ifdef IN_RING3
3293 ichac97R3MixerSetVolume(pThis, pThisCC, offPort, PDMAUDIOMIXERCTL_LINE_IN, u32);
3294#else
3295 rc = VINF_IOM_R3_IOPORT_WRITE;
3296#endif
3297 break;
3298 case AC97_Record_Select:
3299#ifdef IN_RING3
3300 ichac97R3MixerRecordSelect(pThis, u32);
3301#else
3302 rc = VINF_IOM_R3_IOPORT_WRITE;
3303#endif
3304 break;
3305 case AC97_Record_Gain_Mute:
3306#ifdef IN_RING3
3307 /* Newer Ubuntu guests rely on that when controlling gain and muting
3308 * the recording (capturing) levels. */
3309 ichac97R3MixerSetGain(pThis, pThisCC, offPort, PDMAUDIOMIXERCTL_LINE_IN, u32);
3310#else
3311 rc = VINF_IOM_R3_IOPORT_WRITE;
3312#endif
3313 break;
3314 case AC97_Record_Gain_Mic_Mute:
3315#ifdef IN_RING3
3316 /* Ditto; see note above. */
3317 ichac97R3MixerSetGain(pThis, pThisCC, offPort, PDMAUDIOMIXERCTL_MIC_IN, u32);
3318#else
3319 rc = VINF_IOM_R3_IOPORT_WRITE;
3320#endif
3321 break;
3322 case AC97_Vendor_ID1:
3323 case AC97_Vendor_ID2:
3324 LogFunc(("Attempt to write vendor ID to %#x\n", u32));
3325 break;
3326 case AC97_Extended_Audio_ID:
3327 LogFunc(("Attempt to write extended audio ID to %#x\n", u32));
3328 break;
3329 case AC97_Extended_Audio_Ctrl_Stat:
3330#ifdef IN_RING3
3331 /*
3332 * Handle VRA bits.
3333 */
3334 if (!(u32 & AC97_EACS_VRA)) /* Check if VRA bit is not set. */
3335 {
3336 ichac97MixerSet(pThis, AC97_PCM_Front_DAC_Rate, 0xbb80); /* Set default (48000 Hz). */
3337 /** @todo r=bird: Why reopen it now? Can't we put that off till it's
3338 * actually used? */
3339 ichac97R3StreamReOpen(pDevIns, pThis, pThisCC, &pThis->aStreams[AC97SOUNDSOURCE_PO_INDEX],
3340 &pThisCC->aStreams[AC97SOUNDSOURCE_PO_INDEX], true /* fForce */);
3341
3342 ichac97MixerSet(pThis, AC97_PCM_LR_ADC_Rate, 0xbb80); /* Set default (48000 Hz). */
3343 /** @todo r=bird: Why reopen it now? Can't we put that off till it's
3344 * actually used? */
3345 ichac97R3StreamReOpen(pDevIns, pThis, pThisCC, &pThis->aStreams[AC97SOUNDSOURCE_PI_INDEX],
3346 &pThisCC->aStreams[AC97SOUNDSOURCE_PI_INDEX], true /* fForce */);
3347 }
3348 else
3349 LogRel2(("AC97: Variable rate audio (VRA) is not supported\n"));
3350
3351 /*
3352 * Handle VRM bits.
3353 */
3354 if (!(u32 & AC97_EACS_VRM)) /* Check if VRM bit is not set. */
3355 {
3356 ichac97MixerSet(pThis, AC97_MIC_ADC_Rate, 0xbb80); /* Set default (48000 Hz). */
3357 /** @todo r=bird: Why reopen it now? Can't we put that off till it's
3358 * actually used? */
3359 ichac97R3StreamReOpen(pDevIns, pThis, pThisCC, &pThis->aStreams[AC97SOUNDSOURCE_MC_INDEX],
3360 &pThisCC->aStreams[AC97SOUNDSOURCE_MC_INDEX], true /* fForce */);
3361 }
3362 else
3363 LogRel2(("AC97: Variable rate microphone audio (VRM) is not supported\n"));
3364
3365 LogRel2(("AC97: Setting extended audio control to %#x\n", u32));
3366 ichac97MixerSet(pThis, AC97_Extended_Audio_Ctrl_Stat, u32);
3367#else /* !IN_RING3 */
3368 rc = VINF_IOM_R3_IOPORT_WRITE;
3369#endif
3370 break;
3371 case AC97_PCM_Front_DAC_Rate: /* Output slots 3, 4, 6. */
3372#ifdef IN_RING3
3373 if (ichac97MixerGet(pThis, AC97_Extended_Audio_Ctrl_Stat) & AC97_EACS_VRA)
3374 {
3375 LogRel2(("AC97: Setting front DAC rate to 0x%x\n", u32));
3376 ichac97MixerSet(pThis, offPort, u32);
3377 /** @todo r=bird: Why reopen it now? Can't we put that off till it's
3378 * actually used? */
3379 ichac97R3StreamReOpen(pDevIns, pThis, pThisCC, &pThis->aStreams[AC97SOUNDSOURCE_PO_INDEX],
3380 &pThisCC->aStreams[AC97SOUNDSOURCE_PO_INDEX], true /* fForce */);
3381 }
3382 else
3383 LogRel2(("AC97: Setting front DAC rate (0x%x) when VRA is not set is forbidden, ignoring\n", u32));
3384#else
3385 rc = VINF_IOM_R3_IOPORT_WRITE;
3386#endif
3387 break;
3388 case AC97_MIC_ADC_Rate: /* Input slot 6. */
3389#ifdef IN_RING3
3390 if (ichac97MixerGet(pThis, AC97_Extended_Audio_Ctrl_Stat) & AC97_EACS_VRM)
3391 {
3392 LogRel2(("AC97: Setting microphone ADC rate to 0x%x\n", u32));
3393 ichac97MixerSet(pThis, offPort, u32);
3394 /** @todo r=bird: Why reopen it now? Can't we put that off till it's
3395 * actually used? */
3396 ichac97R3StreamReOpen(pDevIns, pThis, pThisCC, &pThis->aStreams[AC97SOUNDSOURCE_MC_INDEX],
3397 &pThisCC->aStreams[AC97SOUNDSOURCE_MC_INDEX], true /* fForce */);
3398 }
3399 else
3400 LogRel2(("AC97: Setting microphone ADC rate (0x%x) when VRM is not set is forbidden, ignoring\n", u32));
3401#else
3402 rc = VINF_IOM_R3_IOPORT_WRITE;
3403#endif
3404 break;
3405 case AC97_PCM_LR_ADC_Rate: /* Input slots 3, 4. */
3406#ifdef IN_RING3
3407 if (ichac97MixerGet(pThis, AC97_Extended_Audio_Ctrl_Stat) & AC97_EACS_VRA)
3408 {
3409 LogRel2(("AC97: Setting line-in ADC rate to 0x%x\n", u32));
3410 ichac97MixerSet(pThis, offPort, u32);
3411 /** @todo r=bird: Why reopen it now? Can't we put that off till it's
3412 * actually used? */
3413 ichac97R3StreamReOpen(pDevIns, pThis, pThisCC, &pThis->aStreams[AC97SOUNDSOURCE_PI_INDEX],
3414 &pThisCC->aStreams[AC97SOUNDSOURCE_PI_INDEX], true /* fForce */);
3415 }
3416 else
3417 LogRel2(("AC97: Setting line-in ADC rate (0x%x) when VRA is not set is forbidden, ignoring\n", u32));
3418#else
3419 rc = VINF_IOM_R3_IOPORT_WRITE;
3420#endif
3421 break;
3422 default:
3423 LogRel2(("AC97: Warning: Unimplemented NAMWrite (2 bytes) offPort=%#x <- %#x\n", offPort, u32));
3424 ichac97MixerSet(pThis, offPort, u32);
3425 break;
3426 }
3427 break;
3428 }
3429
3430 case 4:
3431 {
3432 LogRel2(("AC97: Warning: Unimplemented 4 byte NAMWrite: offPort=%#x <- %#x\n", offPort, u32));
3433 pThis->cas = 0;
3434 break;
3435 }
3436
3437 default:
3438 AssertMsgFailed(("Unhandled NAMWrite offPort=%#x, cb=%u u32=%#x\n", offPort, cb, u32));
3439 break;
3440 }
3441
3442 DEVAC97_UNLOCK(pDevIns, pThis);
3443 return rc;
3444}
3445
3446#ifdef IN_RING3
3447
3448
3449/*********************************************************************************************************************************
3450* State Saving & Loading *
3451*********************************************************************************************************************************/
3452
3453/**
3454 * Saves (serializes) an AC'97 stream using SSM.
3455 *
3456 * @param pDevIns Device instance.
3457 * @param pSSM Saved state manager (SSM) handle to use.
3458 * @param pStream AC'97 stream to save.
3459 */
3460static void ichac97R3SaveStream(PPDMDEVINS pDevIns, PSSMHANDLE pSSM, PAC97STREAM pStream)
3461{
3462 PAC97BMREGS pRegs = &pStream->Regs;
3463 PCPDMDEVHLPR3 pHlp = pDevIns->pHlpR3;
3464
3465 pHlp->pfnSSMPutU32(pSSM, pRegs->bdbar);
3466 pHlp->pfnSSMPutU8( pSSM, pRegs->civ);
3467 pHlp->pfnSSMPutU8( pSSM, pRegs->lvi);
3468 pHlp->pfnSSMPutU16(pSSM, pRegs->sr);
3469 pHlp->pfnSSMPutU16(pSSM, pRegs->picb);
3470 pHlp->pfnSSMPutU8( pSSM, pRegs->piv);
3471 pHlp->pfnSSMPutU8( pSSM, pRegs->cr);
3472 pHlp->pfnSSMPutS32(pSSM, pRegs->bd_valid);
3473 pHlp->pfnSSMPutU32(pSSM, pRegs->bd.addr);
3474 pHlp->pfnSSMPutU32(pSSM, pRegs->bd.ctl_len);
3475}
3476
3477/**
3478 * @callback_method_impl{FNSSMDEVSAVEEXEC}
3479 */
3480static DECLCALLBACK(int) ichac97R3SaveExec(PPDMDEVINS pDevIns, PSSMHANDLE pSSM)
3481{
3482 PAC97STATE pThis = PDMDEVINS_2_DATA(pDevIns, PAC97STATE);
3483 PAC97STATER3 pThisCC = PDMDEVINS_2_DATA_CC(pDevIns, PAC97STATER3);
3484 PCPDMDEVHLPR3 pHlp = pDevIns->pHlpR3;
3485 LogFlowFuncEnter();
3486
3487 pHlp->pfnSSMPutU32(pSSM, pThis->glob_cnt);
3488 pHlp->pfnSSMPutU32(pSSM, pThis->glob_sta);
3489 pHlp->pfnSSMPutU32(pSSM, pThis->cas);
3490
3491 /*
3492 * The order that the streams are saved here is fixed, so don't change.
3493 */
3494 /** @todo r=andy For the next saved state version, add unique stream identifiers and a stream count. */
3495 for (unsigned i = 0; i < AC97_MAX_STREAMS; i++)
3496 ichac97R3SaveStream(pDevIns, pSSM, &pThis->aStreams[i]);
3497
3498 pHlp->pfnSSMPutMem(pSSM, pThis->mixer_data, sizeof(pThis->mixer_data));
3499
3500 /* The stream order is against fixed and set in stone. */
3501 uint8_t afActiveStrms[AC97SOUNDSOURCE_MAX];
3502 afActiveStrms[AC97SOUNDSOURCE_PI_INDEX] = ichac97R3StreamIsEnabled(pThisCC, &pThis->aStreams[AC97SOUNDSOURCE_PI_INDEX]);
3503 afActiveStrms[AC97SOUNDSOURCE_PO_INDEX] = ichac97R3StreamIsEnabled(pThisCC, &pThis->aStreams[AC97SOUNDSOURCE_PO_INDEX]);
3504 afActiveStrms[AC97SOUNDSOURCE_MC_INDEX] = ichac97R3StreamIsEnabled(pThisCC, &pThis->aStreams[AC97SOUNDSOURCE_MC_INDEX]);
3505 AssertCompile(RT_ELEMENTS(afActiveStrms) == 3);
3506 pHlp->pfnSSMPutMem(pSSM, afActiveStrms, sizeof(afActiveStrms));
3507
3508 LogFlowFuncLeaveRC(VINF_SUCCESS);
3509 return VINF_SUCCESS;
3510}
3511
3512/**
3513 * Loads an AC'97 stream from SSM.
3514 *
3515 * @returns VBox status code.
3516 * @param pDevIns The device instance.
3517 * @param pSSM Saved state manager (SSM) handle to use.
3518 * @param pStream AC'97 stream to load.
3519 */
3520static int ichac97R3LoadStream(PPDMDEVINS pDevIns, PSSMHANDLE pSSM, PAC97STREAM pStream)
3521{
3522 PAC97BMREGS pRegs = &pStream->Regs;
3523 PCPDMDEVHLPR3 pHlp = pDevIns->pHlpR3;
3524
3525 pHlp->pfnSSMGetU32(pSSM, &pRegs->bdbar);
3526 pHlp->pfnSSMGetU8( pSSM, &pRegs->civ);
3527 pHlp->pfnSSMGetU8( pSSM, &pRegs->lvi);
3528 pHlp->pfnSSMGetU16(pSSM, &pRegs->sr);
3529 pHlp->pfnSSMGetU16(pSSM, &pRegs->picb);
3530 pHlp->pfnSSMGetU8( pSSM, &pRegs->piv);
3531 pHlp->pfnSSMGetU8( pSSM, &pRegs->cr);
3532 pHlp->pfnSSMGetS32(pSSM, &pRegs->bd_valid);
3533 pHlp->pfnSSMGetU32(pSSM, &pRegs->bd.addr);
3534 return pHlp->pfnSSMGetU32(pSSM, &pRegs->bd.ctl_len);
3535}
3536
3537/**
3538 * @callback_method_impl{FNSSMDEVLOADEXEC}
3539 */
3540static DECLCALLBACK(int) ichac97R3LoadExec(PPDMDEVINS pDevIns, PSSMHANDLE pSSM, uint32_t uVersion, uint32_t uPass)
3541{
3542 PAC97STATE pThis = PDMDEVINS_2_DATA(pDevIns, PAC97STATE);
3543 PAC97STATER3 pThisCC = PDMDEVINS_2_DATA_CC(pDevIns, PAC97STATER3);
3544 PCPDMDEVHLPR3 pHlp = pDevIns->pHlpR3;
3545
3546 LogRel2(("ichac97LoadExec: uVersion=%RU32, uPass=0x%x\n", uVersion, uPass));
3547
3548 AssertMsgReturn (uVersion == AC97_SAVED_STATE_VERSION, ("%RU32\n", uVersion), VERR_SSM_UNSUPPORTED_DATA_UNIT_VERSION);
3549 Assert(uPass == SSM_PASS_FINAL); NOREF(uPass);
3550
3551 pHlp->pfnSSMGetU32(pSSM, &pThis->glob_cnt);
3552 pHlp->pfnSSMGetU32(pSSM, &pThis->glob_sta);
3553 pHlp->pfnSSMGetU32(pSSM, &pThis->cas);
3554
3555 /*
3556 * The order the streams are loaded here is critical (defined by
3557 * AC97SOUNDSOURCE_XX_INDEX), so don't touch!
3558 */
3559 for (unsigned i = 0; i < AC97_MAX_STREAMS; i++)
3560 {
3561 int rc2 = ichac97R3LoadStream(pDevIns, pSSM, &pThis->aStreams[i]);
3562 AssertRCReturn(rc2, rc2);
3563 }
3564
3565 pHlp->pfnSSMGetMem(pSSM, pThis->mixer_data, sizeof(pThis->mixer_data));
3566
3567 ichac97R3MixerRecordSelect(pThis, ichac97MixerGet(pThis, AC97_Record_Select));
3568 ichac97R3MixerSetVolume(pThis, pThisCC, AC97_Master_Volume_Mute, PDMAUDIOMIXERCTL_VOLUME_MASTER,
3569 ichac97MixerGet(pThis, AC97_Master_Volume_Mute));
3570 ichac97R3MixerSetVolume(pThis, pThisCC, AC97_PCM_Out_Volume_Mute, PDMAUDIOMIXERCTL_FRONT,
3571 ichac97MixerGet(pThis, AC97_PCM_Out_Volume_Mute));
3572 ichac97R3MixerSetVolume(pThis, pThisCC, AC97_Line_In_Volume_Mute, PDMAUDIOMIXERCTL_LINE_IN,
3573 ichac97MixerGet(pThis, AC97_Line_In_Volume_Mute));
3574 ichac97R3MixerSetVolume(pThis, pThisCC, AC97_Mic_Volume_Mute, PDMAUDIOMIXERCTL_MIC_IN,
3575 ichac97MixerGet(pThis, AC97_Mic_Volume_Mute));
3576 ichac97R3MixerSetGain(pThis, pThisCC, AC97_Record_Gain_Mic_Mute, PDMAUDIOMIXERCTL_MIC_IN,
3577 ichac97MixerGet(pThis, AC97_Record_Gain_Mic_Mute));
3578 ichac97R3MixerSetGain(pThis, pThisCC, AC97_Record_Gain_Mute, PDMAUDIOMIXERCTL_LINE_IN,
3579 ichac97MixerGet(pThis, AC97_Record_Gain_Mute));
3580 if (pThis->enmCodecModel == AC97CODEC_AD1980)
3581 if (ichac97MixerGet(pThis, AC97_AD_Misc) & AC97_AD_MISC_HPSEL)
3582 ichac97R3MixerSetVolume(pThis, pThisCC, AC97_Headphone_Volume_Mute, PDMAUDIOMIXERCTL_VOLUME_MASTER,
3583 ichac97MixerGet(pThis, AC97_Headphone_Volume_Mute));
3584
3585 /*
3586 * Again the stream order is set is stone.
3587 */
3588 uint8_t afActiveStrms[AC97SOUNDSOURCE_MAX];
3589 int rc2 = pHlp->pfnSSMGetMem(pSSM, afActiveStrms, sizeof(afActiveStrms));
3590 AssertRCReturn(rc2, rc2);
3591
3592 for (unsigned i = 0; i < AC97_MAX_STREAMS; i++)
3593 {
3594 const bool fEnable = RT_BOOL(afActiveStrms[i]);
3595 const PAC97STREAM pStream = &pThis->aStreams[i];
3596 const PAC97STREAMR3 pStreamCC = &pThisCC->aStreams[i];
3597
3598 rc2 = ichac97R3StreamEnable(pDevIns, pThis, pThisCC, pStream, pStreamCC, fEnable);
3599 AssertRC(rc2);
3600 if ( fEnable
3601 && RT_SUCCESS(rc2))
3602 {
3603 /* Re-arm the timer for this stream. */
3604 /** @todo r=aeichner This causes a VM hang upon saved state resume when NetBSD is used as a guest
3605 * Stopping the timer if cTransferTicks is 0 is a workaround but needs further investigation,
3606 * see @bugref{9759} for more information. */
3607 if (pStreamCC->State.cTransferTicks)
3608 ichac97R3TimerSet(pDevIns, pStream, pStreamCC->State.cTransferTicks);
3609 else
3610 PDMDevHlpTimerStop(pDevIns, pStream->hTimer);
3611 }
3612
3613 /* Keep going. */
3614 }
3615
3616 pThis->bup_flag = 0;
3617 pThis->last_samp = 0;
3618
3619 return VINF_SUCCESS;
3620}
3621
3622
3623/*********************************************************************************************************************************
3624* Debug Info Items *
3625*********************************************************************************************************************************/
3626
3627/** Used by ichac97R3DbgInfoStream and ichac97R3DbgInfoBDL. */
3628static int ichac97R3DbgLookupStrmIdx(PCDBGFINFOHLP pHlp, const char *pszArgs)
3629{
3630 if (pszArgs && *pszArgs)
3631 {
3632 int32_t idxStream;
3633 int rc = RTStrToInt32Full(pszArgs, 0, &idxStream);
3634 if (RT_SUCCESS(rc) && idxStream >= -1 && idxStream < AC97_MAX_STREAMS)
3635 return idxStream;
3636 pHlp->pfnPrintf(pHlp, "Argument '%s' is not a valid stream number!\n", pszArgs);
3637 }
3638 return -1;
3639}
3640
3641
3642/**
3643 * Generic buffer descriptor list dumper.
3644 */
3645static void ichac97R3DbgPrintBdl(PPDMDEVINS pDevIns, PAC97STATE pThis, PAC97STREAM pStream,
3646 PCDBGFINFOHLP pHlp, const char *pszPrefix)
3647{
3648 uint8_t const bLvi = pStream->Regs.lvi;
3649 uint8_t const bCiv = pStream->Regs.civ;
3650 pHlp->pfnPrintf(pHlp, "%sBDL for stream #%u: @ %#RX32 LB 0x100; CIV=%#04x LVI=%#04x:\n",
3651 pszPrefix, pStream->u8SD, pStream->Regs.bdbar, bCiv, bLvi);
3652 if (pStream->Regs.bdbar != 0)
3653 {
3654 /* Read all in one go. */
3655 AC97BDLE aBdl[AC97_MAX_BDLE];
3656 RT_ZERO(aBdl);
3657 PDMDevHlpPCIPhysRead(pDevIns, pStream->Regs.bdbar, aBdl, sizeof(aBdl));
3658
3659 /* Get the audio props for the stream so we can translate the sizes correctly. */
3660 PDMAUDIOPCMPROPS Props;
3661 ichach97R3CalcStreamProps(pThis, pStream->u8SD, &Props);
3662
3663 /* Dump them. */
3664 uint64_t cbTotal = 0;
3665 uint64_t cbValid = 0;
3666 for (unsigned i = 0; i < RT_ELEMENTS(aBdl); i++)
3667 {
3668 aBdl[i].addr = RT_LE2H_U32(aBdl[i].addr);
3669 aBdl[i].ctl_len = RT_LE2H_U32(aBdl[i].ctl_len);
3670
3671 bool const fValid = bCiv <= bLvi
3672 ? i >= bCiv && i <= bLvi
3673 : i >= bCiv || i <= bLvi;
3674
3675 uint32_t const cb = (aBdl[i].ctl_len & AC97_BD_LEN_MASK) * PDMAudioPropsSampleSize(&Props); /** @todo or frame size? OSDev says frame... */
3676 cbTotal += cb;
3677 if (fValid)
3678 cbValid += cb;
3679
3680 char szFlags[64];
3681 szFlags[0] = '\0';
3682 if (aBdl[i].ctl_len & ~(AC97_BD_LEN_MASK | AC97_BD_IOC | AC97_BD_BUP))
3683 RTStrPrintf(szFlags, sizeof(szFlags), " !!fFlags=%#x!!\n", aBdl[i].ctl_len & ~AC97_BD_LEN_MASK);
3684
3685 pHlp->pfnPrintf(pHlp, "%s %cBDLE%02u: %#010RX32 L %#06x / LB %#RX32 / %RU64ms%s%s%s%s\n",
3686 pszPrefix, fValid ? ' ' : '?', i, aBdl[i].addr,
3687 aBdl[i].ctl_len & AC97_BD_LEN_MASK, cb, PDMAudioPropsBytesToMilli(&Props, cb),
3688 aBdl[i].ctl_len & AC97_BD_IOC ? " ioc" : "",
3689 aBdl[i].ctl_len & AC97_BD_BUP ? " bup" : "",
3690 szFlags, !(aBdl[i].addr & 3) ? "" : " !!Addr!!");
3691 }
3692
3693 pHlp->pfnPrintf(pHlp, "%sTotal: %#RX64 bytes (%RU64), %RU64 ms; Valid: %#RX64 bytes (%RU64), %RU64 ms\n", pszPrefix,
3694 cbTotal, cbTotal, PDMAudioPropsBytesToMilli(&Props, cbTotal),
3695 cbValid, cbValid, PDMAudioPropsBytesToMilli(&Props, cbValid) );
3696 }
3697}
3698
3699
3700/**
3701 * @callback_method_impl{FNDBGFHANDLERDEV, ac97bdl}
3702 */
3703static DECLCALLBACK(void) ichac97R3DbgInfoBDL(PPDMDEVINS pDevIns, PCDBGFINFOHLP pHlp, const char *pszArgs)
3704{
3705 PAC97STATE pThis = PDMDEVINS_2_DATA(pDevIns, PAC97STATE);
3706 int idxStream = ichac97R3DbgLookupStrmIdx(pHlp, pszArgs);
3707 if (idxStream != -1)
3708 ichac97R3DbgPrintBdl(pDevIns, pThis, &pThis->aStreams[idxStream], pHlp, "");
3709 else
3710 for (idxStream = 0; idxStream < AC97_MAX_STREAMS; ++idxStream)
3711 ichac97R3DbgPrintBdl(pDevIns, pThis, &pThis->aStreams[idxStream], pHlp, "");
3712}
3713
3714
3715/** Worker for ichac97R3DbgInfoStream. */
3716static void ichac97R3DbgPrintStream(PCDBGFINFOHLP pHlp, PAC97STREAM pStream, PAC97STREAMR3 pStreamR3)
3717{
3718 char szTmp[PDMAUDIOSTRMCFGTOSTRING_MAX];
3719 pHlp->pfnPrintf(pHlp, "Stream #%d: %s\n", pStream->u8SD,
3720 PDMAudioStrmCfgToString(&pStreamR3->State.Cfg, szTmp, sizeof(szTmp)));
3721 pHlp->pfnPrintf(pHlp, " BDBAR %#010RX32\n", pStream->Regs.bdbar);
3722 pHlp->pfnPrintf(pHlp, " CIV %#04RX8\n", pStream->Regs.civ);
3723 pHlp->pfnPrintf(pHlp, " LVI %#04RX8\n", pStream->Regs.lvi);
3724 pHlp->pfnPrintf(pHlp, " SR %#06RX16\n", pStream->Regs.sr);
3725 pHlp->pfnPrintf(pHlp, " PICB %#06RX16\n", pStream->Regs.picb);
3726 pHlp->pfnPrintf(pHlp, " PIV %#04RX8\n", pStream->Regs.piv);
3727 pHlp->pfnPrintf(pHlp, " CR %#04RX8\n", pStream->Regs.cr);
3728 if (pStream->Regs.bd_valid)
3729 {
3730 pHlp->pfnPrintf(pHlp, " BD.ADDR %#010RX32\n", pStream->Regs.bd.addr);
3731 pHlp->pfnPrintf(pHlp, " BD.LEN %#04RX16\n", (uint16_t)pStream->Regs.bd.ctl_len);
3732 pHlp->pfnPrintf(pHlp, " BD.CTL %#04RX16\n", (uint16_t)(pStream->Regs.bd.ctl_len >> 16));
3733 }
3734
3735 pHlp->pfnPrintf(pHlp, " offRead %#RX64\n", pStreamR3->State.offRead);
3736 pHlp->pfnPrintf(pHlp, " offWrite %#RX64\n", pStreamR3->State.offWrite);
3737 pHlp->pfnPrintf(pHlp, " uTimerHz %RU16\n", pStreamR3->State.uTimerHz);
3738 pHlp->pfnPrintf(pHlp, " cTransferTicks %RU64\n", pStreamR3->State.cTransferTicks);
3739 pHlp->pfnPrintf(pHlp, " cbTransferChunk %#RX32\n", pStreamR3->State.cbTransferChunk);
3740}
3741
3742
3743/**
3744 * @callback_method_impl{FNDBGFHANDLERDEV, ac97stream}
3745 */
3746static DECLCALLBACK(void) ichac97R3DbgInfoStream(PPDMDEVINS pDevIns, PCDBGFINFOHLP pHlp, const char *pszArgs)
3747{
3748 PAC97STATE pThis = PDMDEVINS_2_DATA(pDevIns, PAC97STATE);
3749 PAC97STATER3 pThisCC = PDMDEVINS_2_DATA_CC(pDevIns, PAC97STATER3);
3750 int idxStream = ichac97R3DbgLookupStrmIdx(pHlp, pszArgs);
3751 if (idxStream != -1)
3752 ichac97R3DbgPrintStream(pHlp, &pThis->aStreams[idxStream], &pThisCC->aStreams[idxStream]);
3753 else
3754 for (idxStream = 0; idxStream < AC97_MAX_STREAMS; ++idxStream)
3755 ichac97R3DbgPrintStream(pHlp, &pThis->aStreams[idxStream], &pThisCC->aStreams[idxStream]);
3756}
3757
3758
3759/*********************************************************************************************************************************
3760* PDMIBASE *
3761*********************************************************************************************************************************/
3762
3763/**
3764 * @interface_method_impl{PDMIBASE,pfnQueryInterface}
3765 */
3766static DECLCALLBACK(void *) ichac97R3QueryInterface(struct PDMIBASE *pInterface, const char *pszIID)
3767{
3768 PAC97STATER3 pThisCC = RT_FROM_MEMBER(pInterface, AC97STATER3, IBase);
3769 PDMIBASE_RETURN_INTERFACE(pszIID, PDMIBASE, &pThisCC->IBase);
3770 return NULL;
3771}
3772
3773
3774/*********************************************************************************************************************************
3775* PDMDEVREG *
3776*********************************************************************************************************************************/
3777
3778/**
3779 * Powers off the device.
3780 *
3781 * @param pDevIns Device instance to power off.
3782 */
3783static DECLCALLBACK(void) ichac97R3PowerOff(PPDMDEVINS pDevIns)
3784{
3785 PAC97STATE pThis = PDMDEVINS_2_DATA(pDevIns, PAC97STATE);
3786 PAC97STATER3 pThisCC = PDMDEVINS_2_DATA_CC(pDevIns, PAC97STATER3);
3787
3788 LogRel2(("AC97: Powering off ...\n"));
3789
3790 /* Note: Involves mixer stream / sink destruction, so also do this here
3791 * instead of in ichac97R3Destruct(). */
3792 ichac97R3StreamsDestroy(pDevIns, pThis, pThisCC);
3793
3794 /*
3795 * Note: Destroy the mixer while powering off and *not* in ichac97R3Destruct,
3796 * giving the mixer the chance to release any references held to
3797 * PDM audio streams it maintains.
3798 */
3799 if (pThisCC->pMixer)
3800 {
3801 AudioMixerDestroy(pThisCC->pMixer, pDevIns);
3802 pThisCC->pMixer = NULL;
3803 }
3804}
3805
3806
3807/**
3808 * @interface_method_impl{PDMDEVREG,pfnReset}
3809 *
3810 * @remarks The original sources didn't install a reset handler, but it seems to
3811 * make sense to me so we'll do it.
3812 */
3813static DECLCALLBACK(void) ichac97R3Reset(PPDMDEVINS pDevIns)
3814{
3815 PAC97STATE pThis = PDMDEVINS_2_DATA(pDevIns, PAC97STATE);
3816 PAC97STATER3 pThisCC = PDMDEVINS_2_DATA_CC(pDevIns, PAC97STATER3);
3817
3818 LogRel(("AC97: Reset\n"));
3819
3820 /*
3821 * Reset the mixer too. The Windows XP driver seems to rely on
3822 * this. At least it wants to read the vendor id before it resets
3823 * the codec manually.
3824 */
3825 ichac97R3MixerReset(pThis, pThisCC);
3826
3827 /*
3828 * Reset all streams.
3829 */
3830 for (unsigned i = 0; i < AC97_MAX_STREAMS; i++)
3831 {
3832 ichac97R3StreamEnable(pDevIns, pThis, pThisCC, &pThis->aStreams[i], &pThisCC->aStreams[i], false /* fEnable */);
3833 ichac97R3StreamReset(pThis, &pThis->aStreams[i], &pThisCC->aStreams[i]);
3834 }
3835
3836 /*
3837 * Reset mixer sinks.
3838 *
3839 * Do the reset here instead of in ichac97R3StreamReset();
3840 * the mixer sink(s) might still have data to be processed when an audio stream gets reset.
3841 */
3842 AudioMixerSinkReset(pThisCC->pSinkLineIn);
3843 AudioMixerSinkReset(pThisCC->pSinkMicIn);
3844 AudioMixerSinkReset(pThisCC->pSinkOut);
3845}
3846
3847
3848/**
3849 * Worker for ichac97R3Construct() and ichac97R3Attach().
3850 *
3851 * @returns VBox status code.
3852 * @param pDevIns The device instance.
3853 * @param pThisCC The ring-3 AC'97 device state.
3854 * @param iLun The logical unit which is being attached.
3855 * @param ppDrv Attached driver instance on success. Optional.
3856 */
3857static int ichac97R3AttachInternal(PPDMDEVINS pDevIns, PAC97STATER3 pThisCC, unsigned iLun, PAC97DRIVER *ppDrv)
3858{
3859 /*
3860 * Attach driver.
3861 */
3862 char *pszDesc = RTStrAPrintf2("Audio driver port (AC'97) for LUN #%u", iLun);
3863 AssertLogRelReturn(pszDesc, VERR_NO_STR_MEMORY);
3864
3865 PPDMIBASE pDrvBase;
3866 int rc = PDMDevHlpDriverAttach(pDevIns, iLun, &pThisCC->IBase, &pDrvBase, pszDesc);
3867 if (RT_SUCCESS(rc))
3868 {
3869 PAC97DRIVER pDrv = (PAC97DRIVER)RTMemAllocZ(sizeof(AC97DRIVER));
3870 if (pDrv)
3871 {
3872 pDrv->pConnector = PDMIBASE_QUERY_INTERFACE(pDrvBase, PDMIAUDIOCONNECTOR);
3873 AssertPtr(pDrv->pConnector);
3874 if (RT_VALID_PTR(pDrv->pConnector))
3875 {
3876 pDrv->pDrvBase = pDrvBase;
3877 pDrv->uLUN = iLun;
3878 pDrv->pszDesc = pszDesc;
3879
3880 /* Attach to driver list if not attached yet. */
3881 if (!pDrv->fAttached)
3882 {
3883 RTListAppend(&pThisCC->lstDrv, &pDrv->Node);
3884 pDrv->fAttached = true;
3885 }
3886
3887 if (ppDrv)
3888 *ppDrv = pDrv;
3889 LogFunc(("LUN#%u: returns VINF_SUCCESS (pCon=%p)\n", iLun, pDrv->pConnector));
3890 return VINF_SUCCESS;
3891 }
3892 RTMemFree(pDrv);
3893 rc = VERR_PDM_MISSING_INTERFACE_BELOW;
3894 }
3895 else
3896 rc = VERR_NO_MEMORY;
3897 }
3898 else if (rc == VERR_PDM_NO_ATTACHED_DRIVER)
3899 LogFunc(("No attached driver for LUN #%u\n", iLun));
3900 else
3901 LogFunc(("Attached driver for LUN #%u failed: %Rrc\n", iLun, rc));
3902
3903 RTStrFree(pszDesc);
3904 LogFunc(("LUN#%u: rc=%Rrc\n", iLun, rc));
3905 return rc;
3906}
3907
3908/**
3909 * @interface_method_impl{PDMDEVREGR3,pfnAttach}
3910 */
3911static DECLCALLBACK(int) ichac97R3Attach(PPDMDEVINS pDevIns, unsigned iLUN, uint32_t fFlags)
3912{
3913 PAC97STATE pThis = PDMDEVINS_2_DATA(pDevIns, PAC97STATE);
3914 PAC97STATER3 pThisCC = PDMDEVINS_2_DATA_CC(pDevIns, PAC97STATER3);
3915 RT_NOREF(fFlags);
3916 LogFunc(("iLUN=%u, fFlags=%#x\n", iLUN, fFlags));
3917
3918 DEVAC97_LOCK(pDevIns, pThis);
3919
3920 PAC97DRIVER pDrv;
3921 int rc = ichac97R3AttachInternal(pDevIns, pThisCC, iLUN, &pDrv);
3922 if (RT_SUCCESS(rc))
3923 {
3924 int rc2 = ichac97R3MixerAddDrv(pDevIns, pThisCC, pDrv);
3925 if (RT_FAILURE(rc2))
3926 LogFunc(("ichac97R3MixerAddDrv failed with %Rrc (ignored)\n", rc2));
3927 }
3928
3929 DEVAC97_UNLOCK(pDevIns, pThis);
3930
3931 return rc;
3932}
3933
3934/**
3935 * Worker for ichac97R3Detach that does all but freeing the pDrv structure.
3936 *
3937 * This is called to let the device detach from a driver for a specified LUN
3938 * at runtime.
3939 *
3940 * @param pDevIns The device instance.
3941 * @param pThisCC The ring-3 AC'97 device state.
3942 * @param pDrv Driver to detach from device.
3943 */
3944static void ichac97R3DetachInternal(PPDMDEVINS pDevIns, PAC97STATER3 pThisCC, PAC97DRIVER pDrv)
3945{
3946 /* Remove the driver from our list and destory it's associated streams.
3947 This also will un-set the driver as a recording source (if associated). */
3948 ichac97R3MixerRemoveDrv(pDevIns, pThisCC, pDrv);
3949 LogFunc(("Detached LUN#%u\n", pDrv->uLUN));
3950}
3951
3952/**
3953 * @interface_method_impl{PDMDEVREG,pfnDetach}
3954 */
3955static DECLCALLBACK(void) ichac97R3Detach(PPDMDEVINS pDevIns, unsigned iLUN, uint32_t fFlags)
3956{
3957 PAC97STATE pThis = PDMDEVINS_2_DATA(pDevIns, PAC97STATE);
3958 PAC97STATER3 pThisCC = PDMDEVINS_2_DATA_CC(pDevIns, PAC97STATER3);
3959 RT_NOREF(fFlags);
3960
3961 LogFunc(("iLUN=%u, fFlags=0x%x\n", iLUN, fFlags));
3962
3963 DEVAC97_LOCK(pDevIns, pThis);
3964
3965 PAC97DRIVER pDrv;
3966 RTListForEach(&pThisCC->lstDrv, pDrv, AC97DRIVER, Node)
3967 {
3968 if (pDrv->uLUN == iLUN)
3969 {
3970 ichac97R3DetachInternal(pDevIns, pThisCC, pDrv);
3971 RTStrFree(pDrv->pszDesc);
3972 RTMemFree(pDrv);
3973 DEVAC97_UNLOCK(pDevIns, pThis);
3974 return;
3975 }
3976 }
3977
3978 DEVAC97_UNLOCK(pDevIns, pThis);
3979 LogFunc(("LUN#%u was not found\n", iLUN));
3980}
3981
3982
3983/**
3984 * @interface_method_impl{PDMDEVREG,pfnDestruct}
3985 */
3986static DECLCALLBACK(int) ichac97R3Destruct(PPDMDEVINS pDevIns)
3987{
3988 PDMDEV_CHECK_VERSIONS_RETURN_QUIET(pDevIns); /* this shall come first */
3989 PAC97STATER3 pThisCC = PDMDEVINS_2_DATA_CC(pDevIns, PAC97STATER3);
3990
3991 LogFlowFuncEnter();
3992
3993 PAC97DRIVER pDrv, pDrvNext;
3994 RTListForEachSafe(&pThisCC->lstDrv, pDrv, pDrvNext, AC97DRIVER, Node)
3995 {
3996 RTListNodeRemove(&pDrv->Node);
3997 RTMemFree(pDrv->pszDesc);
3998 RTMemFree(pDrv);
3999 }
4000
4001 /* Sanity. */
4002 Assert(RTListIsEmpty(&pThisCC->lstDrv));
4003
4004 /* We don't always go via PowerOff, so make sure the mixer is destroyed. */
4005 if (pThisCC->pMixer)
4006 {
4007 AudioMixerDestroy(pThisCC->pMixer, pDevIns);
4008 pThisCC->pMixer = NULL;
4009 }
4010
4011 return VINF_SUCCESS;
4012}
4013
4014/**
4015 * @interface_method_impl{PDMDEVREG,pfnConstruct}
4016 */
4017static DECLCALLBACK(int) ichac97R3Construct(PPDMDEVINS pDevIns, int iInstance, PCFGMNODE pCfg)
4018{
4019 PDMDEV_CHECK_VERSIONS_RETURN(pDevIns); /* this shall come first */
4020 PAC97STATE pThis = PDMDEVINS_2_DATA(pDevIns, PAC97STATE);
4021 PAC97STATER3 pThisCC = PDMDEVINS_2_DATA_CC(pDevIns, PAC97STATER3);
4022 PCPDMDEVHLPR3 pHlp = pDevIns->pHlpR3;
4023 Assert(iInstance == 0); RT_NOREF(iInstance);
4024
4025 /*
4026 * Initialize data so we can run the destructor without scewing up.
4027 */
4028 pThisCC->pDevIns = pDevIns;
4029 pThisCC->IBase.pfnQueryInterface = ichac97R3QueryInterface;
4030 RTListInit(&pThisCC->lstDrv);
4031
4032 /*
4033 * Validate and read configuration.
4034 */
4035 PDMDEV_VALIDATE_CONFIG_RETURN(pDevIns, "BufSizeInMs|BufSizeOutMs|Codec|TimerHz|DebugEnabled|DebugPathOut", "");
4036
4037 /** @devcfgm{ac97,BufSizeInMs,uint16_t,0,2000,0,ms}
4038 * The size of the DMA buffer for input streams expressed in milliseconds. */
4039 int rc = pHlp->pfnCFGMQueryU16Def(pCfg, "BufSizeInMs", &pThis->cMsCircBufIn, 0);
4040 if (RT_FAILURE(rc))
4041 return PDMDEV_SET_ERROR(pDevIns, rc,
4042 N_("AC97 configuration error: failed to read 'BufSizeInMs' as 16-bit unsigned integer"));
4043 if (pThis->cMsCircBufIn > 2000)
4044 return PDMDEV_SET_ERROR(pDevIns, VERR_OUT_OF_RANGE,
4045 N_("AC97 configuration error: 'BufSizeInMs' is out of bound, max 2000 ms"));
4046
4047 /** @devcfgm{ac97,BufSizeOutMs,uint16_t,0,2000,0,ms}
4048 * The size of the DMA buffer for output streams expressed in milliseconds. */
4049 rc = pHlp->pfnCFGMQueryU16Def(pCfg, "BufSizeOutMs", &pThis->cMsCircBufOut, 0);
4050 if (RT_FAILURE(rc))
4051 return PDMDEV_SET_ERROR(pDevIns, rc,
4052 N_("AC97 configuration error: failed to read 'BufSizeOutMs' as 16-bit unsigned integer"));
4053 if (pThis->cMsCircBufOut > 2000)
4054 return PDMDEV_SET_ERROR(pDevIns, VERR_OUT_OF_RANGE,
4055 N_("AC97 configuration error: 'BufSizeOutMs' is out of bound, max 2000 ms"));
4056
4057 /** @devcfgm{ac97,TimerHz,uint16_t,10,1000,100,ms}
4058 * Currently the approximate rate at which the asynchronous I/O threads move
4059 * data from/to the DMA buffer, thru the mixer and drivers stack, and
4060 * to/from the host device/whatever. (It does NOT govern any DMA timer rate any
4061 * more as might be hinted at by the name.) */
4062 rc = pHlp->pfnCFGMQueryU16Def(pCfg, "TimerHz", &pThis->uTimerHz, AC97_TIMER_HZ_DEFAULT);
4063 if (RT_FAILURE(rc))
4064 return PDMDEV_SET_ERROR(pDevIns, rc,
4065 N_("AC'97 configuration error: failed to read 'TimerHz' as a 16-bit unsigned integer"));
4066 if (pThis->uTimerHz < 10 || pThis->uTimerHz > 1000)
4067 return PDMDEV_SET_ERROR(pDevIns, VERR_OUT_OF_RANGE,
4068 N_("AC'97 configuration error: 'TimerHz' is out of range (10-1000 Hz)"));
4069
4070 if (pThis->uTimerHz != AC97_TIMER_HZ_DEFAULT)
4071 LogRel(("AC97: Using custom device timer rate: %RU16 Hz\n", pThis->uTimerHz));
4072
4073 rc = pHlp->pfnCFGMQueryBoolDef(pCfg, "DebugEnabled", &pThisCC->Dbg.fEnabled, false);
4074 if (RT_FAILURE(rc))
4075 return PDMDEV_SET_ERROR(pDevIns, rc,
4076 N_("AC97 configuration error: failed to read debugging enabled flag as boolean"));
4077
4078 rc = pHlp->pfnCFGMQueryStringAllocDef(pCfg, "DebugPathOut", &pThisCC->Dbg.pszOutPath, NULL);
4079 if (RT_FAILURE(rc))
4080 return PDMDEV_SET_ERROR(pDevIns, rc,
4081 N_("AC97 configuration error: failed to read debugging output path flag as string"));
4082
4083 if (pThisCC->Dbg.fEnabled)
4084 LogRel2(("AC97: Debug output will be saved to '%s'\n", pThisCC->Dbg.pszOutPath));
4085
4086 /*
4087 * The AD1980 codec (with corresponding PCI subsystem vendor ID) is whitelisted
4088 * in the Linux kernel; Linux makes no attempt to measure the data rate and assumes
4089 * 48 kHz rate, which is exactly what we need. Same goes for AD1981B.
4090 */
4091 char szCodec[20];
4092 rc = pHlp->pfnCFGMQueryStringDef(pCfg, "Codec", &szCodec[0], sizeof(szCodec), "STAC9700");
4093 if (RT_FAILURE(rc))
4094 return PDMDEV_SET_ERROR(pDevIns, VERR_PDM_DEVINS_UNKNOWN_CFG_VALUES,
4095 N_("AC'97 configuration error: Querying \"Codec\" as string failed"));
4096 if (!strcmp(szCodec, "STAC9700"))
4097 pThis->enmCodecModel = AC97CODEC_STAC9700;
4098 else if (!strcmp(szCodec, "AD1980"))
4099 pThis->enmCodecModel = AC97CODEC_AD1980;
4100 else if (!strcmp(szCodec, "AD1981B"))
4101 pThis->enmCodecModel = AC97CODEC_AD1981B;
4102 else
4103 return PDMDevHlpVMSetError(pDevIns, VERR_PDM_DEVINS_UNKNOWN_CFG_VALUES, RT_SRC_POS,
4104 N_("AC'97 configuration error: The \"Codec\" value \"%s\" is unsupported"), szCodec);
4105
4106 LogRel(("AC97: Using codec '%s'\n", szCodec));
4107
4108 /*
4109 * Use an own critical section for the device instead of the default
4110 * one provided by PDM. This allows fine-grained locking in combination
4111 * with TM when timer-specific stuff is being called in e.g. the MMIO handlers.
4112 */
4113 rc = PDMDevHlpCritSectInit(pDevIns, &pThis->CritSect, RT_SRC_POS, "AC'97");
4114 AssertRCReturn(rc, rc);
4115
4116 rc = PDMDevHlpSetDeviceCritSect(pDevIns, PDMDevHlpCritSectGetNop(pDevIns));
4117 AssertRCReturn(rc, rc);
4118
4119 /*
4120 * Initialize data (most of it anyway).
4121 */
4122 /* PCI Device */
4123 PPDMPCIDEV pPciDev = pDevIns->apPciDevs[0];
4124 PCIDevSetVendorId(pPciDev, 0x8086); /* 00 ro - intel. */ Assert(pPciDev->abConfig[0x00] == 0x86); Assert(pPciDev->abConfig[0x01] == 0x80);
4125 PCIDevSetDeviceId(pPciDev, 0x2415); /* 02 ro - 82801 / 82801aa(?). */ Assert(pPciDev->abConfig[0x02] == 0x15); Assert(pPciDev->abConfig[0x03] == 0x24);
4126 PCIDevSetCommand(pPciDev, 0x0000); /* 04 rw,ro - pcicmd. */ Assert(pPciDev->abConfig[0x04] == 0x00); Assert(pPciDev->abConfig[0x05] == 0x00);
4127 PCIDevSetStatus(pPciDev, VBOX_PCI_STATUS_DEVSEL_MEDIUM | VBOX_PCI_STATUS_FAST_BACK); /* 06 rwc?,ro? - pcists. */ Assert(pPciDev->abConfig[0x06] == 0x80); Assert(pPciDev->abConfig[0x07] == 0x02);
4128 PCIDevSetRevisionId(pPciDev, 0x01); /* 08 ro - rid. */ Assert(pPciDev->abConfig[0x08] == 0x01);
4129 PCIDevSetClassProg(pPciDev, 0x00); /* 09 ro - pi. */ Assert(pPciDev->abConfig[0x09] == 0x00);
4130 PCIDevSetClassSub(pPciDev, 0x01); /* 0a ro - scc; 01 == Audio. */ Assert(pPciDev->abConfig[0x0a] == 0x01);
4131 PCIDevSetClassBase(pPciDev, 0x04); /* 0b ro - bcc; 04 == multimedia.*/Assert(pPciDev->abConfig[0x0b] == 0x04);
4132 PCIDevSetHeaderType(pPciDev, 0x00); /* 0e ro - headtyp. */ Assert(pPciDev->abConfig[0x0e] == 0x00);
4133 PCIDevSetBaseAddress(pPciDev, 0, /* 10 rw - nambar - native audio mixer base. */
4134 true /* fIoSpace */, false /* fPrefetchable */, false /* f64Bit */, 0x00000000); Assert(pPciDev->abConfig[0x10] == 0x01); Assert(pPciDev->abConfig[0x11] == 0x00); Assert(pPciDev->abConfig[0x12] == 0x00); Assert(pPciDev->abConfig[0x13] == 0x00);
4135 PCIDevSetBaseAddress(pPciDev, 1, /* 14 rw - nabmbar - native audio bus mastering. */
4136 true /* fIoSpace */, false /* fPrefetchable */, false /* f64Bit */, 0x00000000); Assert(pPciDev->abConfig[0x14] == 0x01); Assert(pPciDev->abConfig[0x15] == 0x00); Assert(pPciDev->abConfig[0x16] == 0x00); Assert(pPciDev->abConfig[0x17] == 0x00);
4137 PCIDevSetInterruptLine(pPciDev, 0x00); /* 3c rw. */ Assert(pPciDev->abConfig[0x3c] == 0x00);
4138 PCIDevSetInterruptPin(pPciDev, 0x01); /* 3d ro - INTA#. */ Assert(pPciDev->abConfig[0x3d] == 0x01);
4139
4140 if (pThis->enmCodecModel == AC97CODEC_AD1980)
4141 {
4142 PCIDevSetSubSystemVendorId(pPciDev, 0x1028); /* 2c ro - Dell.) */
4143 PCIDevSetSubSystemId(pPciDev, 0x0177); /* 2e ro. */
4144 }
4145 else if (pThis->enmCodecModel == AC97CODEC_AD1981B)
4146 {
4147 PCIDevSetSubSystemVendorId(pPciDev, 0x1028); /* 2c ro - Dell.) */
4148 PCIDevSetSubSystemId(pPciDev, 0x01ad); /* 2e ro. */
4149 }
4150 else
4151 {
4152 PCIDevSetSubSystemVendorId(pPciDev, 0x8086); /* 2c ro - Intel.) */
4153 PCIDevSetSubSystemId(pPciDev, 0x0000); /* 2e ro. */
4154 }
4155
4156 /*
4157 * Register the PCI device and associated I/O regions.
4158 */
4159 rc = PDMDevHlpPCIRegister(pDevIns, pPciDev);
4160 if (RT_FAILURE(rc))
4161 return rc;
4162
4163 rc = PDMDevHlpPCIIORegionCreateIo(pDevIns, 0 /*iPciRegion*/, 256 /*cPorts*/,
4164 ichac97IoPortNamWrite, ichac97IoPortNamRead, NULL /*pvUser*/,
4165 "ICHAC97 NAM", NULL /*paExtDescs*/, &pThis->hIoPortsNam);
4166 AssertRCReturn(rc, rc);
4167
4168 rc = PDMDevHlpPCIIORegionCreateIo(pDevIns, 1 /*iPciRegion*/, 64 /*cPorts*/,
4169 ichac97IoPortNabmWrite, ichac97IoPortNabmRead, NULL /*pvUser*/,
4170 "ICHAC97 NABM", g_aNabmPorts, &pThis->hIoPortsNabm);
4171 AssertRCReturn(rc, rc);
4172
4173 /*
4174 * Saved state.
4175 */
4176 rc = PDMDevHlpSSMRegister(pDevIns, AC97_SAVED_STATE_VERSION, sizeof(*pThis), ichac97R3SaveExec, ichac97R3LoadExec);
4177 if (RT_FAILURE(rc))
4178 return rc;
4179
4180 /*
4181 * Attach drivers. We ASSUME they are configured consecutively without any
4182 * gaps, so we stop when we hit the first LUN w/o a driver configured.
4183 */
4184 for (unsigned iLun = 0; ; iLun++)
4185 {
4186 AssertBreak(iLun < UINT8_MAX);
4187 LogFunc(("Trying to attach driver for LUN#%u ...\n", iLun));
4188 rc = ichac97R3AttachInternal(pDevIns, pThisCC, iLun, NULL /* ppDrv */);
4189 if (rc == VERR_PDM_NO_ATTACHED_DRIVER)
4190 {
4191 LogFunc(("cLUNs=%u\n", iLun));
4192 break;
4193 }
4194 AssertLogRelMsgReturn(RT_SUCCESS(rc), ("LUN#%u: rc=%Rrc\n", iLun, rc), rc);
4195 }
4196
4197 uint32_t fMixer = AUDMIXER_FLAGS_NONE;
4198 if (pThisCC->Dbg.fEnabled)
4199 fMixer |= AUDMIXER_FLAGS_DEBUG;
4200
4201 rc = AudioMixerCreate("AC'97 Mixer", 0 /* uFlags */, &pThisCC->pMixer);
4202 AssertRCReturn(rc, rc);
4203
4204 rc = AudioMixerCreateSink(pThisCC->pMixer, "Line In",
4205 PDMAUDIODIR_IN, pDevIns, &pThisCC->pSinkLineIn);
4206 AssertRCReturn(rc, rc);
4207 rc = AudioMixerCreateSink(pThisCC->pMixer, "Microphone In",
4208 PDMAUDIODIR_IN, pDevIns, &pThisCC->pSinkMicIn);
4209 AssertRCReturn(rc, rc);
4210 rc = AudioMixerCreateSink(pThisCC->pMixer, "PCM Output",
4211 PDMAUDIODIR_OUT, pDevIns, &pThisCC->pSinkOut);
4212 AssertRCReturn(rc, rc);
4213
4214 /*
4215 * Create all hardware streams.
4216 */
4217 AssertCompile(RT_ELEMENTS(pThis->aStreams) == AC97_MAX_STREAMS);
4218 for (unsigned i = 0; i < AC97_MAX_STREAMS; i++)
4219 {
4220 rc = ichac97R3StreamCreate(pThisCC, &pThis->aStreams[i], &pThisCC->aStreams[i], i /* SD# */);
4221 AssertRCReturn(rc, rc);
4222 }
4223
4224 /*
4225 * Create the emulation timers (one per stream).
4226 *
4227 * We must the critical section for the timers as the device has a
4228 * noop section associated with it.
4229 *
4230 * Note: Use TMCLOCK_VIRTUAL_SYNC here, as the guest's AC'97 driver
4231 * relies on exact (virtual) DMA timing and uses DMA Position Buffers
4232 * instead of the LPIB registers.
4233 */
4234 /** @todo r=bird: The need to use virtual sync is perhaps because TM
4235 * doesn't schedule regular TMCLOCK_VIRTUAL timers as accurately as it
4236 * should (VT-x preemption timer, etc). Hope to address that before
4237 * long. @bugref{9943}. */
4238 static const char * const s_apszNames[] = { "AC97 PI", "AC97 PO", "AC97 MC" };
4239 AssertCompile(RT_ELEMENTS(s_apszNames) == AC97_MAX_STREAMS);
4240 for (unsigned i = 0; i < AC97_MAX_STREAMS; i++)
4241 {
4242 rc = PDMDevHlpTimerCreate(pDevIns, TMCLOCK_VIRTUAL_SYNC, ichac97R3Timer, &pThis->aStreams[i],
4243 TMTIMER_FLAGS_NO_CRIT_SECT | TMTIMER_FLAGS_RING0, s_apszNames[i], &pThis->aStreams[i].hTimer);
4244 AssertRCReturn(rc, rc);
4245
4246 rc = PDMDevHlpTimerSetCritSect(pDevIns, pThis->aStreams[i].hTimer, &pThis->CritSect);
4247 AssertRCReturn(rc, rc);
4248 }
4249
4250 ichac97R3Reset(pDevIns);
4251
4252 /*
4253 * Info items.
4254 */
4255 //PDMDevHlpDBGFInfoRegister(pDevIns, "ac97", "AC'97 registers. (ac97 [register case-insensitive])", ichac97R3DbgInfo);
4256 PDMDevHlpDBGFInfoRegister(pDevIns, "ac97bdl", "AC'97 buffer descriptor list (BDL). (ac97bdl [stream number])",
4257 ichac97R3DbgInfoBDL);
4258 PDMDevHlpDBGFInfoRegister(pDevIns, "ac97stream", "AC'97 stream info. (ac97stream [stream number])", ichac97R3DbgInfoStream);
4259 //PDMDevHlpDBGFInfoRegister(pDevIns, "ac97mixer", "AC'97 mixer state.", ichac97R3DbgInfoMixer);
4260
4261 /*
4262 * Register statistics.
4263 */
4264 PDMDevHlpSTAMRegister(pDevIns, &pThis->StatUnimplementedNabmReads, STAMTYPE_COUNTER, "UnimplementedNabmReads", STAMUNIT_OCCURENCES, "Unimplemented NABM register reads.");
4265 PDMDevHlpSTAMRegister(pDevIns, &pThis->StatUnimplementedNabmWrites, STAMTYPE_COUNTER, "UnimplementedNabmWrites", STAMUNIT_OCCURENCES, "Unimplemented NABM register writes.");
4266# ifdef VBOX_WITH_STATISTICS
4267 PDMDevHlpSTAMRegister(pDevIns, &pThis->StatTimer, STAMTYPE_PROFILE, "Timer", STAMUNIT_TICKS_PER_CALL, "Profiling ichac97Timer.");
4268 PDMDevHlpSTAMRegister(pDevIns, &pThis->StatIn, STAMTYPE_PROFILE, "Input", STAMUNIT_TICKS_PER_CALL, "Profiling input.");
4269 PDMDevHlpSTAMRegister(pDevIns, &pThis->StatOut, STAMTYPE_PROFILE, "Output", STAMUNIT_TICKS_PER_CALL, "Profiling output.");
4270 PDMDevHlpSTAMRegister(pDevIns, &pThis->StatBytesRead, STAMTYPE_COUNTER, "BytesRead" , STAMUNIT_BYTES, "Bytes read from AC97 emulation.");
4271 PDMDevHlpSTAMRegister(pDevIns, &pThis->StatBytesWritten, STAMTYPE_COUNTER, "BytesWritten", STAMUNIT_BYTES, "Bytes written to AC97 emulation.");
4272# endif
4273 for (unsigned idxStream = 0; idxStream < RT_ELEMENTS(pThis->aStreams); idxStream++)
4274 {
4275 PDMDevHlpSTAMRegisterF(pDevIns, &pThisCC->aStreams[idxStream].State.offRead, STAMTYPE_U64, STAMVISIBILITY_USED, STAMUNIT_BYTES,
4276 "Virtual internal buffer read position.", "Stream%u/offRead", idxStream);
4277 PDMDevHlpSTAMRegisterF(pDevIns, &pThisCC->aStreams[idxStream].State.offWrite, STAMTYPE_U64, STAMVISIBILITY_USED, STAMUNIT_BYTES,
4278 "Virtual internal buffer write position.", "Stream%u/offWrite", idxStream);
4279 PDMDevHlpSTAMRegisterF(pDevIns, &pThisCC->aStreams[idxStream].State.StatDmaBufSize, STAMTYPE_U32, STAMVISIBILITY_USED, STAMUNIT_BYTES,
4280 "Size of the internal DMA buffer.", "Stream%u/DMABufSize", idxStream);
4281 PDMDevHlpSTAMRegisterF(pDevIns, &pThisCC->aStreams[idxStream].State.StatDmaBufUsed, STAMTYPE_U32, STAMVISIBILITY_USED, STAMUNIT_BYTES,
4282 "Number of bytes used in the internal DMA buffer.", "Stream%u/DMABufUsed", idxStream);
4283 }
4284
4285 LogFlowFuncLeaveRC(VINF_SUCCESS);
4286 return VINF_SUCCESS;
4287}
4288
4289#else /* !IN_RING3 */
4290
4291/**
4292 * @callback_method_impl{PDMDEVREGR0,pfnConstruct}
4293 */
4294static DECLCALLBACK(int) ichac97RZConstruct(PPDMDEVINS pDevIns)
4295{
4296 PDMDEV_CHECK_VERSIONS_RETURN(pDevIns);
4297 PAC97STATE pThis = PDMDEVINS_2_DATA(pDevIns, PAC97STATE);
4298
4299 int rc = PDMDevHlpSetDeviceCritSect(pDevIns, PDMDevHlpCritSectGetNop(pDevIns));
4300 AssertRCReturn(rc, rc);
4301
4302 rc = PDMDevHlpIoPortSetUpContext(pDevIns, pThis->hIoPortsNam, ichac97IoPortNamWrite, ichac97IoPortNamRead, NULL /*pvUser*/);
4303 AssertRCReturn(rc, rc);
4304 rc = PDMDevHlpIoPortSetUpContext(pDevIns, pThis->hIoPortsNabm, ichac97IoPortNabmWrite, ichac97IoPortNabmRead, NULL /*pvUser*/);
4305 AssertRCReturn(rc, rc);
4306
4307 return VINF_SUCCESS;
4308}
4309
4310#endif /* !IN_RING3 */
4311
4312/**
4313 * The device registration structure.
4314 */
4315const PDMDEVREG g_DeviceICHAC97 =
4316{
4317 /* .u32Version = */ PDM_DEVREG_VERSION,
4318 /* .uReserved0 = */ 0,
4319 /* .szName = */ "ichac97",
4320 /* .fFlags = */ PDM_DEVREG_FLAGS_DEFAULT_BITS | PDM_DEVREG_FLAGS_RZ | PDM_DEVREG_FLAGS_NEW_STYLE
4321 | PDM_DEVREG_FLAGS_FIRST_POWEROFF_NOTIFICATION /* stream clearnup with working drivers */,
4322 /* .fClass = */ PDM_DEVREG_CLASS_AUDIO,
4323 /* .cMaxInstances = */ 1,
4324 /* .uSharedVersion = */ 42,
4325 /* .cbInstanceShared = */ sizeof(AC97STATE),
4326 /* .cbInstanceCC = */ CTX_EXPR(sizeof(AC97STATER3), 0, 0),
4327 /* .cbInstanceRC = */ 0,
4328 /* .cMaxPciDevices = */ 1,
4329 /* .cMaxMsixVectors = */ 0,
4330 /* .pszDescription = */ "ICH AC'97 Audio Controller",
4331#if defined(IN_RING3)
4332 /* .pszRCMod = */ "VBoxDDRC.rc",
4333 /* .pszR0Mod = */ "VBoxDDR0.r0",
4334 /* .pfnConstruct = */ ichac97R3Construct,
4335 /* .pfnDestruct = */ ichac97R3Destruct,
4336 /* .pfnRelocate = */ NULL,
4337 /* .pfnMemSetup = */ NULL,
4338 /* .pfnPowerOn = */ NULL,
4339 /* .pfnReset = */ ichac97R3Reset,
4340 /* .pfnSuspend = */ NULL,
4341 /* .pfnResume = */ NULL,
4342 /* .pfnAttach = */ ichac97R3Attach,
4343 /* .pfnDetach = */ ichac97R3Detach,
4344 /* .pfnQueryInterface = */ NULL,
4345 /* .pfnInitComplete = */ NULL,
4346 /* .pfnPowerOff = */ ichac97R3PowerOff,
4347 /* .pfnSoftReset = */ NULL,
4348 /* .pfnReserved0 = */ NULL,
4349 /* .pfnReserved1 = */ NULL,
4350 /* .pfnReserved2 = */ NULL,
4351 /* .pfnReserved3 = */ NULL,
4352 /* .pfnReserved4 = */ NULL,
4353 /* .pfnReserved5 = */ NULL,
4354 /* .pfnReserved6 = */ NULL,
4355 /* .pfnReserved7 = */ NULL,
4356#elif defined(IN_RING0)
4357 /* .pfnEarlyConstruct = */ NULL,
4358 /* .pfnConstruct = */ ichac97RZConstruct,
4359 /* .pfnDestruct = */ NULL,
4360 /* .pfnFinalDestruct = */ NULL,
4361 /* .pfnRequest = */ NULL,
4362 /* .pfnReserved0 = */ NULL,
4363 /* .pfnReserved1 = */ NULL,
4364 /* .pfnReserved2 = */ NULL,
4365 /* .pfnReserved3 = */ NULL,
4366 /* .pfnReserved4 = */ NULL,
4367 /* .pfnReserved5 = */ NULL,
4368 /* .pfnReserved6 = */ NULL,
4369 /* .pfnReserved7 = */ NULL,
4370#elif defined(IN_RC)
4371 /* .pfnConstruct = */ ichac97RZConstruct,
4372 /* .pfnReserved0 = */ NULL,
4373 /* .pfnReserved1 = */ NULL,
4374 /* .pfnReserved2 = */ NULL,
4375 /* .pfnReserved3 = */ NULL,
4376 /* .pfnReserved4 = */ NULL,
4377 /* .pfnReserved5 = */ NULL,
4378 /* .pfnReserved6 = */ NULL,
4379 /* .pfnReserved7 = */ NULL,
4380#else
4381# error "Not in IN_RING3, IN_RING0 or IN_RC!"
4382#endif
4383 /* .u32VersionEnd = */ PDM_DEVREG_VERSION
4384};
4385
4386#endif /* !VBOX_DEVICE_STRUCT_TESTCASE */
4387
Note: See TracBrowser for help on using the repository browser.

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