VirtualBox

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

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

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

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