VirtualBox

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

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

Audio: Converted PDMAUDIODSTSRCUNION, PDMAUDIORECSRC and PDMAUDIOPLAYBACKDST into a single enum type PDMAUDIOPATH. bugref:9890

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