VirtualBox

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

Last change on this file since 73403 was 73403, checked in by vboxsync, 6 years ago

Audio/Mixer: Added support for setting / getting an (input) sink's current recording source via AudioMixerSink[Get|Set]RecordingSource().

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