VirtualBox

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

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

DevIchAc97: Tried to organized the functions a bit more logically. No functional changes. bugref:9890

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