VirtualBox

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

Last change on this file since 89693 was 89693, checked in by vboxsync, 4 years ago

DevIchAc97: Added pushback and statistics to the output portion of ichac97R3StreamUpdateDma (similar to HDA). bugref:9890

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