VirtualBox

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

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

Audio: Implemented backend-independent (pre-)buffering support. Work in progress.

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 142.7 KB
Line 
1/* $Id: DevIchAc97.cpp 73370 2018-07-26 13:52:12Z 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 if (RT_SUCCESS(rc))
1562 {
1563 rc = AudioMixerSinkAddStream(pMixSink, pMixStrm);
1564 LogFlowFunc(("LUN#%RU8: Created stream \"%s\", rc=%Rrc\n", pDrv->uLUN, pCfg->szName, rc));
1565 }
1566
1567 if (RT_SUCCESS(rc))
1568 pDrvStream->pMixStrm = pMixStrm;
1569 }
1570 else
1571 rc = VERR_INVALID_PARAMETER;
1572
1573 if (pStreamCfg)
1574 {
1575 RTMemFree(pStreamCfg);
1576 pStreamCfg = NULL;
1577 }
1578
1579 LogFlowFuncLeaveRC(rc);
1580 return rc;
1581}
1582
1583/**
1584 * Adds all current driver streams to a specific mixer sink.
1585 *
1586 * @returns IPRT status code.
1587 * @param pThis AC'97 state.
1588 * @param pMixSink Mixer sink to add stream to.
1589 * @param pCfg Stream configuration to use.
1590 */
1591static int ichac97R3MixerAddDrvStreams(PAC97STATE pThis, PAUDMIXSINK pMixSink, PPDMAUDIOSTREAMCFG pCfg)
1592{
1593 AssertPtrReturn(pThis, VERR_INVALID_POINTER);
1594 AssertPtrReturn(pMixSink, VERR_INVALID_POINTER);
1595 AssertPtrReturn(pCfg, VERR_INVALID_POINTER);
1596
1597 if (!DrvAudioHlpStreamCfgIsValid(pCfg))
1598 return VERR_INVALID_PARAMETER;
1599
1600 int rc = AudioMixerSinkSetFormat(pMixSink, &pCfg->Props);
1601 if (RT_FAILURE(rc))
1602 return rc;
1603
1604 PAC97DRIVER pDrv;
1605 RTListForEach(&pThis->lstDrv, pDrv, AC97DRIVER, Node)
1606 {
1607 int rc2 = ichac97R3MixerAddDrvStream(pThis, pMixSink, pCfg, pDrv);
1608 if (RT_FAILURE(rc2))
1609 LogFunc(("Attaching stream failed with %Rrc\n", rc2));
1610
1611 /* Do not pass failure to rc here, as there might be drivers which aren't
1612 * configured / ready yet. */
1613 }
1614
1615 LogFlowFuncLeaveRC(rc);
1616 return rc;
1617}
1618
1619/**
1620 * Removes a driver stream from a specific mixer sink.
1621 *
1622 * @param pThis AC'97 state.
1623 * @param pMixSink Mixer sink to remove audio streams from.
1624 * @param enmDir Stream direction to remove.
1625 * @param dstSrc Stream destination / source to remove.
1626 * @param pDrv Driver stream to remove.
1627 */
1628static void ichac97R3MixerRemoveDrvStream(PAC97STATE pThis, PAUDMIXSINK pMixSink,
1629 PDMAUDIODIR enmDir, PDMAUDIODESTSOURCE dstSrc, PAC97DRIVER pDrv)
1630{
1631 AssertPtrReturnVoid(pThis);
1632 AssertPtrReturnVoid(pMixSink);
1633
1634 PAC97DRIVERSTREAM pDrvStream = ichac97R3MixerGetDrvStream(pThis, pDrv, enmDir, dstSrc);
1635 if (pDrvStream)
1636 {
1637 if (pDrvStream->pMixStrm)
1638 {
1639 AudioMixerSinkRemoveStream(pMixSink, pDrvStream->pMixStrm);
1640
1641 AudioMixerStreamDestroy(pDrvStream->pMixStrm);
1642 pDrvStream->pMixStrm = NULL;
1643 }
1644 }
1645}
1646
1647/**
1648 * Removes all driver streams from a specific mixer sink.
1649 *
1650 * @param pThis AC'97 state.
1651 * @param pMixSink Mixer sink to remove audio streams from.
1652 * @param enmDir Stream direction to remove.
1653 * @param dstSrc Stream destination / source to remove.
1654 */
1655static void ichac97R3MixerRemoveDrvStreams(PAC97STATE pThis, PAUDMIXSINK pMixSink,
1656 PDMAUDIODIR enmDir, PDMAUDIODESTSOURCE dstSrc)
1657{
1658 AssertPtrReturnVoid(pThis);
1659 AssertPtrReturnVoid(pMixSink);
1660
1661 PAC97DRIVER pDrv;
1662 RTListForEach(&pThis->lstDrv, pDrv, AC97DRIVER, Node)
1663 {
1664 ichac97R3MixerRemoveDrvStream(pThis, pMixSink, enmDir, dstSrc, pDrv);
1665 }
1666}
1667
1668/**
1669 * Opens an AC'97 stream with its current mixer settings.
1670 *
1671 * This will open an AC'97 stream with 2 (stereo) channels, 16-bit samples and
1672 * the last set sample rate in the AC'97 mixer for this stream.
1673 *
1674 * @returns IPRT status code.
1675 * @param pThis AC'97 state.
1676 * @param pStream AC'97 Stream to open.
1677 */
1678static int ichac97R3StreamOpen(PAC97STATE pThis, PAC97STREAM pStream)
1679{
1680 int rc = VINF_SUCCESS;
1681
1682 LogFunc(("[SD%RU8]\n", pStream->u8SD));
1683
1684 RT_ZERO(pStream->State.Cfg);
1685
1686 PPDMAUDIOSTREAMCFG pCfg = &pStream->State.Cfg;
1687 PAUDMIXSINK pMixSink = NULL;
1688 AssertCompile(sizeof(pCfg->szName) >= 8);
1689
1690 /* Set scheduling hint (if available). */
1691 if (pThis->cTimerTicks)
1692 pCfg->Device.uSchedulingHintMs = 1000 /* ms */ / (TMTimerGetFreq(pThis->pTimerR3) / pThis->cTimerTicks);
1693
1694 switch (pStream->u8SD)
1695 {
1696 case AC97SOUNDSOURCE_PI_INDEX:
1697 {
1698 pCfg->Props.uHz = ichac97MixerGet(pThis, AC97_PCM_LR_ADC_Rate);
1699 pCfg->enmDir = PDMAUDIODIR_IN;
1700 pCfg->DestSource.Source = PDMAUDIORECSOURCE_LINE;
1701 pCfg->enmLayout = PDMAUDIOSTREAMLAYOUT_NON_INTERLEAVED;
1702 strcpy(pCfg->szName, "Line-In");
1703
1704 pMixSink = pThis->pSinkLineIn;
1705 break;
1706 }
1707
1708 case AC97SOUNDSOURCE_MC_INDEX:
1709 {
1710 pCfg->Props.uHz = ichac97MixerGet(pThis, AC97_MIC_ADC_Rate);
1711 pCfg->enmDir = PDMAUDIODIR_IN;
1712 pCfg->DestSource.Source = PDMAUDIORECSOURCE_MIC;
1713 pCfg->enmLayout = PDMAUDIOSTREAMLAYOUT_NON_INTERLEAVED;
1714 strcpy(pCfg->szName, "Mic-In");
1715
1716 pMixSink = pThis->pSinkMicIn;
1717 break;
1718 }
1719
1720 case AC97SOUNDSOURCE_PO_INDEX:
1721 {
1722 pCfg->Props.uHz = ichac97MixerGet(pThis, AC97_PCM_Front_DAC_Rate);
1723 pCfg->enmDir = PDMAUDIODIR_OUT;
1724 pCfg->DestSource.Dest = PDMAUDIOPLAYBACKDEST_FRONT;
1725 pCfg->enmLayout = PDMAUDIOSTREAMLAYOUT_NON_INTERLEAVED;
1726 strcpy(pCfg->szName, "Output");
1727
1728 pMixSink = pThis->pSinkOut;
1729 break;
1730 }
1731
1732 default:
1733 rc = VERR_NOT_SUPPORTED;
1734 break;
1735 }
1736
1737 if (RT_SUCCESS(rc))
1738 {
1739 ichac97R3MixerRemoveDrvStreams(pThis, pMixSink, pCfg->enmDir, pCfg->DestSource);
1740
1741 if (pCfg->Props.uHz)
1742 {
1743 Assert(pCfg->enmDir != PDMAUDIODIR_UNKNOWN);
1744
1745 pCfg->Props.cChannels = 2;
1746 pCfg->Props.cBits = 16;
1747 pCfg->Props.fSigned = true;
1748 pCfg->Props.cShift = PDMAUDIOPCMPROPS_MAKE_SHIFT_PARMS(pCfg->Props.cBits, pCfg->Props.cChannels);
1749
1750 rc = ichac97R3MixerAddDrvStreams(pThis, pMixSink, pCfg);
1751 }
1752 }
1753
1754 LogFlowFunc(("[SD%RU8] rc=%Rrc\n", pStream->u8SD, rc));
1755 return rc;
1756}
1757
1758/**
1759 * Closes an AC'97 stream.
1760 *
1761 * @returns IPRT status code.
1762 * @param pThis AC'97 state.
1763 * @param pStream AC'97 stream to close.
1764 */
1765static int ichac97R3StreamClose(PAC97STATE pThis, PAC97STREAM pStream)
1766{
1767 RT_NOREF(pThis);
1768 RT_NOREF(pStream);
1769
1770 LogFlowFunc(("[SD%RU8]\n", pStream->u8SD));
1771
1772 return VINF_SUCCESS;
1773}
1774
1775/**
1776 * Re-opens (that is, closes and opens again) an AC'97 stream on the backend
1777 * side with the current AC'97 mixer settings for this stream.
1778 *
1779 * @returns IPRT status code.
1780 * @param pThis AC'97 device state.
1781 * @param pStream AC'97 stream to re-open.
1782 */
1783static int ichac97R3StreamReOpen(PAC97STATE pThis, PAC97STREAM pStream)
1784{
1785 LogFlowFunc(("[SD%RU8]\n", pStream->u8SD));
1786
1787 int rc = ichac97R3StreamClose(pThis, pStream);
1788 if (RT_SUCCESS(rc))
1789 rc = ichac97R3StreamOpen(pThis, pStream);
1790
1791 return rc;
1792}
1793
1794/**
1795 * Locks an AC'97 stream for serialized access.
1796 *
1797 * @returns IPRT status code.
1798 * @param pStream AC'97 stream to lock.
1799 */
1800static void ichac97R3StreamLock(PAC97STREAM pStream)
1801{
1802 AssertPtrReturnVoid(pStream);
1803 int rc2 = RTCritSectEnter(&pStream->State.CritSect);
1804 AssertRC(rc2);
1805}
1806
1807/**
1808 * Unlocks a formerly locked AC'97 stream.
1809 *
1810 * @returns IPRT status code.
1811 * @param pStream AC'97 stream to unlock.
1812 */
1813static void ichac97R3StreamUnlock(PAC97STREAM pStream)
1814{
1815 AssertPtrReturnVoid(pStream);
1816 int rc2 = RTCritSectLeave(&pStream->State.CritSect);
1817 AssertRC(rc2);
1818}
1819
1820/**
1821 * Retrieves the available size of (buffered) audio data (in bytes) of a given AC'97 stream.
1822 *
1823 * @returns Available data (in bytes).
1824 * @param pStream AC'97 stream to retrieve size for.
1825 */
1826static uint32_t ichac97R3StreamGetUsed(PAC97STREAM pStream)
1827{
1828 AssertPtrReturn(pStream, 0);
1829
1830 if (!pStream->State.pCircBuf)
1831 return 0;
1832
1833 return (uint32_t)RTCircBufUsed(pStream->State.pCircBuf);
1834}
1835
1836/**
1837 * Retrieves the free size of audio data (in bytes) of a given AC'97 stream.
1838 *
1839 * @returns Free data (in bytes).
1840 * @param pStream AC'97 stream to retrieve size for.
1841 */
1842static uint32_t ichac97R3StreamGetFree(PAC97STREAM pStream)
1843{
1844 AssertPtrReturn(pStream, 0);
1845
1846 if (!pStream->State.pCircBuf)
1847 return 0;
1848
1849 return (uint32_t)RTCircBufFree(pStream->State.pCircBuf);
1850}
1851
1852/**
1853 * Sets the volume of a specific AC'97 mixer control.
1854 *
1855 * This currently only supports attenuation -- gain support is currently not implemented.
1856 *
1857 * @returns IPRT status code.
1858 * @param pThis AC'97 state.
1859 * @param index AC'97 mixer index to set volume for.
1860 * @param enmMixerCtl Corresponding audio mixer sink.
1861 * @param uVal Volume value to set.
1862 */
1863static int ichac97R3MixerSetVolume(PAC97STATE pThis, int index, PDMAUDIOMIXERCTL enmMixerCtl, uint32_t uVal)
1864{
1865 /*
1866 * From AC'97 SoundMax Codec AD1981A/AD1981B:
1867 * "Because AC '97 defines 6-bit volume registers, to maintain compatibility whenever the
1868 * D5 or D13 bits are set to 1, their respective lower five volume bits are automatically
1869 * set to 1 by the Codec logic. On readback, all lower 5 bits will read ones whenever
1870 * these bits are set to 1."
1871 *
1872 * Linux ALSA depends on this behavior.
1873 */
1874 /// @todo Does this apply to anything other than the master volume control?
1875 if (uVal & RT_BIT(5)) /* D5 bit set? */
1876 uVal |= RT_BIT(4) | RT_BIT(3) | RT_BIT(2) | RT_BIT(1) | RT_BIT(0);
1877 if (uVal & RT_BIT(13)) /* D13 bit set? */
1878 uVal |= RT_BIT(12) | RT_BIT(11) | RT_BIT(10) | RT_BIT(9) | RT_BIT(8);
1879
1880 const bool fCtlMuted = (uVal >> AC97_BARS_VOL_MUTE_SHIFT) & 1;
1881 uint8_t uCtlAttLeft = (uVal >> 8) & AC97_BARS_VOL_MASK;
1882 uint8_t uCtlAttRight = uVal & AC97_BARS_VOL_MASK;
1883
1884 /* For the master and headphone volume, 0 corresponds to 0dB attenuation. For the other
1885 * volume controls, 0 means 12dB gain and 8 means unity gain.
1886 */
1887 if (index != AC97_Master_Volume_Mute && index != AC97_Headphone_Volume_Mute)
1888 {
1889# ifndef VBOX_WITH_AC97_GAIN_SUPPORT
1890 /* NB: Currently there is no gain support, only attenuation. */
1891 uCtlAttLeft = uCtlAttLeft < 8 ? 0 : uCtlAttLeft - 8;
1892 uCtlAttRight = uCtlAttRight < 8 ? 0 : uCtlAttRight - 8;
1893# endif
1894 }
1895 Assert(uCtlAttLeft <= 255 / AC97_DB_FACTOR);
1896 Assert(uCtlAttRight <= 255 / AC97_DB_FACTOR);
1897
1898 LogFunc(("index=0x%x, uVal=%RU32, enmMixerCtl=%RU32\n", index, uVal, enmMixerCtl));
1899 LogFunc(("uCtlAttLeft=%RU8, uCtlAttRight=%RU8 ", uCtlAttLeft, uCtlAttRight));
1900
1901 /*
1902 * For AC'97 volume controls, each additional step means -1.5dB attenuation with
1903 * zero being maximum. In contrast, we're internally using 255 (PDMAUDIO_VOLUME_MAX)
1904 * steps, each -0.375dB, where 0 corresponds to -96dB and 255 corresponds to 0dB.
1905 */
1906 uint8_t lVol = PDMAUDIO_VOLUME_MAX - uCtlAttLeft * AC97_DB_FACTOR;
1907 uint8_t rVol = PDMAUDIO_VOLUME_MAX - uCtlAttRight * AC97_DB_FACTOR;
1908
1909 Log(("-> fMuted=%RTbool, lVol=%RU8, rVol=%RU8\n", fCtlMuted, lVol, rVol));
1910
1911 int rc = VINF_SUCCESS;
1912
1913 if (pThis->pMixer) /* Device can be in reset state, so no mixer available. */
1914 {
1915 PDMAUDIOVOLUME Vol = { fCtlMuted, lVol, rVol };
1916 PAUDMIXSINK pSink = NULL;
1917
1918 switch (enmMixerCtl)
1919 {
1920 case PDMAUDIOMIXERCTL_VOLUME_MASTER:
1921 rc = AudioMixerSetMasterVolume(pThis->pMixer, &Vol);
1922 break;
1923
1924 case PDMAUDIOMIXERCTL_FRONT:
1925 pSink = pThis->pSinkOut;
1926 break;
1927
1928 case PDMAUDIOMIXERCTL_MIC_IN:
1929 pSink = pThis->pSinkMicIn;
1930 break;
1931
1932 case PDMAUDIOMIXERCTL_LINE_IN:
1933 pSink = pThis->pSinkLineIn;
1934 break;
1935
1936 default:
1937 AssertFailed();
1938 rc = VERR_NOT_SUPPORTED;
1939 break;
1940 }
1941
1942 if (pSink)
1943 rc = AudioMixerSinkSetVolume(pSink, &Vol);
1944 }
1945
1946 ichac97MixerSet(pThis, index, uVal);
1947
1948 if (RT_FAILURE(rc))
1949 LogFlowFunc(("Failed with %Rrc\n", rc));
1950
1951 return rc;
1952}
1953
1954/**
1955 * Converts an AC'97 recording source index to a PDM audio recording source.
1956 *
1957 * @returns PDM audio recording source.
1958 * @param uIdx AC'97 index to convert.
1959 */
1960static PDMAUDIORECSOURCE ichac97R3IdxToRecSource(uint8_t uIdx)
1961{
1962 switch (uIdx)
1963 {
1964 case AC97_REC_MIC: return PDMAUDIORECSOURCE_MIC;
1965 case AC97_REC_CD: return PDMAUDIORECSOURCE_CD;
1966 case AC97_REC_VIDEO: return PDMAUDIORECSOURCE_VIDEO;
1967 case AC97_REC_AUX: return PDMAUDIORECSOURCE_AUX;
1968 case AC97_REC_LINE_IN: return PDMAUDIORECSOURCE_LINE;
1969 case AC97_REC_PHONE: return PDMAUDIORECSOURCE_PHONE;
1970 default:
1971 break;
1972 }
1973
1974 LogFlowFunc(("Unknown record source %d, using MIC\n", uIdx));
1975 return PDMAUDIORECSOURCE_MIC;
1976}
1977
1978/**
1979 * Converts a PDM audio recording source to an AC'97 recording source index.
1980 *
1981 * @returns AC'97 recording source index.
1982 * @param enmRecSrc PDM audio recording source to convert.
1983 */
1984static uint8_t ichac97R3RecSourceToIdx(PDMAUDIORECSOURCE enmRecSrc)
1985{
1986 switch (enmRecSrc)
1987 {
1988 case PDMAUDIORECSOURCE_MIC: return AC97_REC_MIC;
1989 case PDMAUDIORECSOURCE_CD: return AC97_REC_CD;
1990 case PDMAUDIORECSOURCE_VIDEO: return AC97_REC_VIDEO;
1991 case PDMAUDIORECSOURCE_AUX: return AC97_REC_AUX;
1992 case PDMAUDIORECSOURCE_LINE: return AC97_REC_LINE_IN;
1993 case PDMAUDIORECSOURCE_PHONE: return AC97_REC_PHONE;
1994 default:
1995 break;
1996 }
1997
1998 LogFlowFunc(("Unknown audio recording source %d using MIC\n", enmRecSrc));
1999 return AC97_REC_MIC;
2000}
2001
2002#endif /* IN_RING3 */
2003
2004/**
2005 * Retrieves an AC'97 audio stream from an AC'97 stream index.
2006 *
2007 * @returns Pointer to AC'97 audio stream if found, or NULL if not found / invalid.
2008 * @param pThis AC'97 state.
2009 * @param uIdx AC'97 stream index to retrieve AC'97 audio stream for.
2010 */
2011DECLINLINE(PAC97STREAM) ichac97GetStreamFromIdx(PAC97STATE pThis, uint32_t uIdx)
2012{
2013 switch (uIdx)
2014 {
2015 case AC97SOUNDSOURCE_PI_INDEX: return &pThis->StreamLineIn;
2016 case AC97SOUNDSOURCE_MC_INDEX: return &pThis->StreamMicIn;
2017 case AC97SOUNDSOURCE_PO_INDEX: return &pThis->StreamOut;
2018 default: return NULL;
2019 }
2020
2021}
2022
2023#ifdef IN_RING3
2024
2025/**
2026 * Performs an AC'97 mixer record select to switch to a different recording
2027 * source.
2028 *
2029 * @param pThis AC'97 state.
2030 * @param val AC'97 recording source index to set.
2031 */
2032static void ichac97R3MixerRecordSelect(PAC97STATE pThis, uint32_t val)
2033{
2034 uint8_t rs = val & AC97_REC_MASK;
2035 uint8_t ls = (val >> 8) & AC97_REC_MASK;
2036 PDMAUDIORECSOURCE ars = ichac97R3IdxToRecSource(rs);
2037 PDMAUDIORECSOURCE als = ichac97R3IdxToRecSource(ls);
2038 rs = ichac97R3RecSourceToIdx(ars);
2039 ls = ichac97R3RecSourceToIdx(als);
2040 ichac97MixerSet(pThis, AC97_Record_Select, rs | (ls << 8));
2041}
2042
2043/**
2044 * Resets the AC'97 mixer.
2045 *
2046 * @returns IPRT status code.
2047 * @param pThis AC'97 state.
2048 */
2049static int ichac97R3MixerReset(PAC97STATE pThis)
2050{
2051 AssertPtrReturn(pThis, VERR_INVALID_PARAMETER);
2052
2053 LogFlowFuncEnter();
2054
2055 RT_ZERO(pThis->mixer_data);
2056
2057 /* Note: Make sure to reset all registers first before bailing out on error. */
2058
2059 ichac97MixerSet(pThis, AC97_Reset , 0x0000); /* 6940 */
2060 ichac97MixerSet(pThis, AC97_Master_Volume_Mono_Mute , 0x8000);
2061 ichac97MixerSet(pThis, AC97_PC_BEEP_Volume_Mute , 0x0000);
2062
2063 ichac97MixerSet(pThis, AC97_Phone_Volume_Mute , 0x8008);
2064 ichac97MixerSet(pThis, AC97_Mic_Volume_Mute , 0x8008);
2065 ichac97MixerSet(pThis, AC97_CD_Volume_Mute , 0x8808);
2066 ichac97MixerSet(pThis, AC97_Aux_Volume_Mute , 0x8808);
2067 ichac97MixerSet(pThis, AC97_Record_Gain_Mic_Mute , 0x8000);
2068 ichac97MixerSet(pThis, AC97_General_Purpose , 0x0000);
2069 ichac97MixerSet(pThis, AC97_3D_Control , 0x0000);
2070 ichac97MixerSet(pThis, AC97_Powerdown_Ctrl_Stat , 0x000f);
2071
2072 ichac97MixerSet(pThis, AC97_Extended_Audio_ID , 0x0809);
2073 ichac97MixerSet(pThis, AC97_Extended_Audio_Ctrl_Stat, 0x0009);
2074 ichac97MixerSet(pThis, AC97_PCM_Front_DAC_Rate , 0xbb80);
2075 ichac97MixerSet(pThis, AC97_PCM_Surround_DAC_Rate , 0xbb80);
2076 ichac97MixerSet(pThis, AC97_PCM_LFE_DAC_Rate , 0xbb80);
2077 ichac97MixerSet(pThis, AC97_PCM_LR_ADC_Rate , 0xbb80);
2078 ichac97MixerSet(pThis, AC97_MIC_ADC_Rate , 0xbb80);
2079
2080 if (pThis->uCodecModel == AC97_CODEC_AD1980)
2081 {
2082 /* Analog Devices 1980 (AD1980) */
2083 ichac97MixerSet(pThis, AC97_Reset , 0x0010); /* Headphones. */
2084 ichac97MixerSet(pThis, AC97_Vendor_ID1 , 0x4144);
2085 ichac97MixerSet(pThis, AC97_Vendor_ID2 , 0x5370);
2086 ichac97MixerSet(pThis, AC97_Headphone_Volume_Mute , 0x8000);
2087 }
2088 else if (pThis->uCodecModel == AC97_CODEC_AD1981B)
2089 {
2090 /* Analog Devices 1981B (AD1981B) */
2091 ichac97MixerSet(pThis, AC97_Vendor_ID1 , 0x4144);
2092 ichac97MixerSet(pThis, AC97_Vendor_ID2 , 0x5374);
2093 }
2094 else
2095 {
2096 /* Sigmatel 9700 (STAC9700) */
2097 ichac97MixerSet(pThis, AC97_Vendor_ID1 , 0x8384);
2098 ichac97MixerSet(pThis, AC97_Vendor_ID2 , 0x7600); /* 7608 */
2099 }
2100 ichac97R3MixerRecordSelect(pThis, 0);
2101
2102 /* The default value is 8000h, which corresponds to 0 dB attenuation with mute on. */
2103 ichac97R3MixerSetVolume(pThis, AC97_Master_Volume_Mute, PDMAUDIOMIXERCTL_VOLUME_MASTER, 0x8000);
2104
2105 /* The default value for stereo registers is 8808h, which corresponds to 0 dB gain with mute on.*/
2106 ichac97R3MixerSetVolume(pThis, AC97_PCM_Out_Volume_Mute, PDMAUDIOMIXERCTL_FRONT, 0x8808);
2107 ichac97R3MixerSetVolume(pThis, AC97_Line_In_Volume_Mute, PDMAUDIOMIXERCTL_LINE_IN, 0x8808);
2108 ichac97R3MixerSetVolume(pThis, AC97_Mic_Volume_Mute, PDMAUDIOMIXERCTL_MIC_IN, 0x8808);
2109
2110 return VINF_SUCCESS;
2111}
2112
2113# if 0 /* Unused */
2114static void ichac97R3WriteBUP(PAC97STATE pThis, uint32_t cbElapsed)
2115{
2116 LogFlowFunc(("cbElapsed=%RU32\n", cbElapsed));
2117
2118 if (!(pThis->bup_flag & BUP_SET))
2119 {
2120 if (pThis->bup_flag & BUP_LAST)
2121 {
2122 unsigned int i;
2123 uint32_t *p = (uint32_t*)pThis->silence;
2124 for (i = 0; i < sizeof(pThis->silence) / 4; i++) /** @todo r=andy Assumes 16-bit samples, stereo. */
2125 *p++ = pThis->last_samp;
2126 }
2127 else
2128 RT_ZERO(pThis->silence);
2129
2130 pThis->bup_flag |= BUP_SET;
2131 }
2132
2133 while (cbElapsed)
2134 {
2135 uint32_t cbToWrite = RT_MIN(cbElapsed, (uint32_t)sizeof(pThis->silence));
2136 uint32_t cbWrittenToStream;
2137
2138 int rc2 = AudioMixerSinkWrite(pThis->pSinkOut, AUDMIXOP_COPY,
2139 pThis->silence, cbToWrite, &cbWrittenToStream);
2140 if (RT_SUCCESS(rc2))
2141 {
2142 if (cbWrittenToStream < cbToWrite) /* Lagging behind? */
2143 LogFlowFunc(("Warning: Only written %RU32 / %RU32 bytes, expect lags\n", cbWrittenToStream, cbToWrite));
2144 }
2145
2146 /* Always report all data as being written;
2147 * backends who were not able to catch up have to deal with it themselves. */
2148 Assert(cbElapsed >= cbToWrite);
2149 cbElapsed -= cbToWrite;
2150 }
2151}
2152# endif /* Unused */
2153
2154# ifndef VBOX_WITH_AUDIO_AC97_CALLBACKS
2155
2156/**
2157 * Starts the internal audio device timer.
2158 *
2159 * @return IPRT status code.
2160 * @param pThis AC'97 state.
2161 */
2162static int ichac97R3TimerStart(PAC97STATE pThis)
2163{
2164 LogFlowFuncEnter();
2165
2166 DEVAC97_LOCK_BOTH_RETURN(pThis, VINF_IOM_R3_MMIO_WRITE);
2167
2168 AssertPtr(pThis->CTX_SUFF(pTimer));
2169
2170 if (!pThis->fTimerActive)
2171 {
2172 LogRel2(("AC97: Starting transfers\n"));
2173
2174 pThis->fTimerActive = true;
2175
2176 /* Start transfers. */
2177 ichac97R3TimerMain(pThis);
2178 }
2179
2180 DEVAC97_UNLOCK_BOTH(pThis);
2181
2182 return VINF_SUCCESS;
2183}
2184
2185/**
2186 * Starts the internal audio device timer (if not started yet).
2187 *
2188 * @return IPRT status code.
2189 * @param pThis AC'97 state.
2190 */
2191static int ichac97R3TimerMaybeStart(PAC97STATE pThis)
2192{
2193 LogFlowFuncEnter();
2194
2195 if (!pThis->CTX_SUFF(pTimer))
2196 return VERR_WRONG_ORDER;
2197
2198 pThis->cStreamsActive++;
2199
2200 /* Only start the timer at the first active stream. */
2201 if (pThis->cStreamsActive == 1)
2202 return ichac97R3TimerStart(pThis);
2203
2204 return VINF_SUCCESS;
2205}
2206
2207/**
2208 * Stops the internal audio device timer.
2209 *
2210 * @return IPRT status code.
2211 * @param pThis AC'97 state.
2212 */
2213static int ichac97R3TimerStop(PAC97STATE pThis)
2214{
2215 LogFlowFuncEnter();
2216
2217 if (!pThis->CTX_SUFF(pTimer)) /* Only can happen on device construction time, so no locking needed here. */
2218 return VINF_SUCCESS;
2219
2220 DEVAC97_LOCK_BOTH_RETURN(pThis, VINF_IOM_R3_MMIO_WRITE);
2221
2222 if (pThis->fTimerActive)
2223 {
2224 LogRel2(("AC97: Stopping transfers ...\n"));
2225
2226 pThis->fTimerActive = false;
2227
2228 /* Note: Do not stop the timer via TMTimerStop() here, as there still might
2229 * be queued audio data which needs to be handled (e.g. played back) first
2230 * before actually stopping the timer for good. */
2231 }
2232
2233 DEVAC97_UNLOCK_BOTH(pThis);
2234
2235 return VINF_SUCCESS;
2236}
2237
2238/**
2239 * Decreases the active AC'97 streams count by one and
2240 * then checks if the internal audio device timer can be
2241 * stopped.
2242 *
2243 * @return IPRT status code.
2244 * @param pThis AC'97 state.
2245 */
2246static int ichac97R3TimerMaybeStop(PAC97STATE pThis)
2247{
2248 LogFlowFuncEnter();
2249
2250 if (!pThis->CTX_SUFF(pTimer))
2251 return VERR_WRONG_ORDER;
2252
2253 if (pThis->cStreamsActive) /* Function can be called mupltiple times. */
2254 {
2255 pThis->cStreamsActive--;
2256
2257 if (pThis->cStreamsActive == 0)
2258 return ichac97R3TimerStop(pThis);
2259 }
2260
2261 return VINF_SUCCESS;
2262}
2263
2264/**
2265 * Main routine for the device timer.
2266 *
2267 * @param pThis AC'97 state.
2268 */
2269static void ichac97R3TimerMain(PAC97STATE pThis)
2270{
2271 STAM_PROFILE_START(&pThis->StatTimer, a);
2272
2273 DEVAC97_LOCK_BOTH_RETURN_VOID(pThis);
2274
2275 uint64_t cTicksNow = TMTimerGet(pThis->CTX_SUFF(pTimer));
2276
2277 /* Update current time timestamp. */
2278 pThis->uTimerTS = cTicksNow;
2279
2280 /* Flag indicating whether to arm the timer again for the next DMA transfer or sink processing. */
2281 bool fArmTimer = false;
2282
2283 ichac97R3DoTransfers(pThis);
2284
2285 /* Do we need to arm the timer again? */
2286 if ( AudioMixerSinkIsActive(ichac97R3IndexToSink(pThis, pThis->StreamLineIn.u8SD))
2287 || AudioMixerSinkIsActive(ichac97R3IndexToSink(pThis, pThis->StreamMicIn.u8SD))
2288 || AudioMixerSinkIsActive(ichac97R3IndexToSink(pThis, pThis->StreamOut.u8SD)))
2289 {
2290 fArmTimer = true;
2291 }
2292
2293 if ( ASMAtomicReadBool(&pThis->fTimerActive) /** @todo r=bird: totally unnecessary to do atomic read here, isn't it? */
2294 || fArmTimer)
2295 {
2296 /* Arm the timer again. */
2297 uint64_t cTicks = pThis->cTimerTicks;
2298 /** @todo adjust cTicks down by now much cbOutMin represents. */
2299 TMTimerSet(pThis->CTX_SUFF(pTimer), cTicksNow + cTicks);
2300 }
2301 else
2302 LogRel2(("AC97: Stopped transfers\n"));
2303
2304 DEVAC97_UNLOCK_BOTH(pThis);
2305
2306 STAM_PROFILE_STOP(&pThis->StatTimer, a);
2307}
2308
2309/**
2310 * Timer callback which handles the audio data transfers on a periodic basis.
2311 *
2312 * @param pDevIns Device instance.
2313 * @param pTimer Timer which was used when calling this.
2314 * @param pvUser User argument as PAC97STATE.
2315 */
2316static DECLCALLBACK(void) ichac97R3Timer(PPDMDEVINS pDevIns, PTMTIMER pTimer, void *pvUser)
2317{
2318 RT_NOREF(pDevIns, pTimer);
2319
2320 PAC97STATE pThis = (PAC97STATE)pvUser;
2321 Assert(pThis == PDMINS_2_DATA(pDevIns, PAC97STATE));
2322
2323 ichac97R3TimerMain(pThis);
2324}
2325
2326# endif /* !VBOX_WITH_AUDIO_AC97_CALLBACKS */
2327
2328/**
2329 * Main routine to perform the actual audio data transfers from the AC'97 streams
2330 * to the backend(s) and vice versa.
2331 *
2332 * @param pThis AC'97 state.
2333 */
2334static void ichac97R3DoTransfers(PAC97STATE pThis)
2335{
2336 AssertPtrReturnVoid(pThis);
2337
2338 ichac97R3StreamUpdate(pThis, &pThis->StreamLineIn, true /* fInTimer */);
2339 ichac97R3StreamUpdate(pThis, &pThis->StreamMicIn, true /* fInTimer */);
2340 ichac97R3StreamUpdate(pThis, &pThis->StreamOut, true /* fInTimer */);
2341}
2342
2343/**
2344 * Transfers data of an AC'97 stream according to its usage (input / output).
2345 *
2346 * For an SDO (output) stream this means reading DMA data from the device to
2347 * the AC'97 stream's internal FIFO buffer.
2348 *
2349 * For an SDI (input) stream this is reading audio data from the AC'97 stream's
2350 * internal FIFO buffer and writing it as DMA data to the device.
2351 *
2352 * @returns IPRT status code.
2353 * @param pThis AC'97 state.
2354 * @param pStream AC'97 stream to update.
2355 * @param cbToProcessMax Maximum of data (in bytes) to process.
2356 */
2357static int ichac97R3StreamTransfer(PAC97STATE pThis, PAC97STREAM pStream, uint32_t cbToProcessMax)
2358{
2359 AssertPtrReturn(pThis, VERR_INVALID_POINTER);
2360 AssertPtrReturn(pStream, VERR_INVALID_POINTER);
2361 AssertReturn(cbToProcessMax, VERR_INVALID_PARAMETER);
2362
2363 ichac97R3StreamLock(pStream);
2364
2365 PAC97BMREGS pRegs = &pStream->Regs;
2366
2367 if (pRegs->sr & AC97_SR_DCH) /* Controller halted? */
2368 {
2369 if (pRegs->cr & AC97_CR_RPBM) /* Bus master operation starts. */
2370 {
2371 switch (pStream->u8SD)
2372 {
2373 case AC97SOUNDSOURCE_PO_INDEX:
2374 /*ichac97R3WriteBUP(pThis, cbToProcess);*/
2375 break;
2376
2377 default:
2378 break;
2379 }
2380 }
2381
2382 ichac97R3StreamUnlock(pStream);
2383 return VINF_SUCCESS;
2384 }
2385
2386 /* BCIS flag still set? Skip iteration. */
2387 if (pRegs->sr & AC97_SR_BCIS)
2388 {
2389 Log3Func(("[SD%RU8] BCIS set\n", pStream->u8SD));
2390
2391 ichac97R3StreamUnlock(pStream);
2392 return VINF_SUCCESS;
2393 }
2394
2395 uint32_t cbLeft = RT_MIN((uint32_t)(pRegs->picb << 1), cbToProcessMax); /** @todo r=andy Assumes 16bit samples. */
2396 uint32_t cbProcessedTotal = 0;
2397
2398 PRTCIRCBUF pCircBuf = pStream->State.pCircBuf;
2399 AssertPtr(pCircBuf);
2400
2401 int rc = VINF_SUCCESS;
2402
2403 Log3Func(("[SD%RU8] cbToProcessMax=%RU32, cbLeft=%RU32\n", pStream->u8SD, cbToProcessMax, cbLeft));
2404
2405 while (cbLeft)
2406 {
2407 if (!pRegs->bd_valid)
2408 {
2409 Log3Func(("Invalid buffer descriptor, fetching next one ...\n"));
2410 ichac97R3StreamFetchBDLE(pThis, pStream);
2411 }
2412
2413 if (!pRegs->picb) /* Got a new buffer descriptor, that is, the position is 0? */
2414 {
2415 Log3Func(("Fresh buffer descriptor %RU8 is empty, addr=%#x, len=%#x, skipping\n",
2416 pRegs->civ, pRegs->bd.addr, pRegs->bd.ctl_len));
2417 if (pRegs->civ == pRegs->lvi)
2418 {
2419 pRegs->sr |= AC97_SR_DCH; /** @todo r=andy Also set CELV? */
2420 pThis->bup_flag = 0;
2421
2422 rc = VINF_EOF;
2423 break;
2424 }
2425
2426 pRegs->sr &= ~AC97_SR_CELV;
2427 pRegs->civ = pRegs->piv;
2428 pRegs->piv = (pRegs->piv + 1) % AC97_MAX_BDLE;
2429
2430 ichac97R3StreamFetchBDLE(pThis, pStream);
2431 continue;
2432 }
2433
2434 uint32_t cbChunk = RT_MIN((uint32_t)(pRegs->picb << 1), cbLeft); /** @todo r=andy Assumes 16bit samples. */
2435 Assert(cbChunk);
2436
2437 switch (pStream->u8SD)
2438 {
2439 case AC97SOUNDSOURCE_PO_INDEX: /* Output */
2440 {
2441 void *pvDst;
2442 size_t cbDst;
2443
2444 RTCircBufAcquireWriteBlock(pCircBuf, cbChunk, &pvDst, &cbDst);
2445
2446 if (cbDst)
2447 {
2448 int rc2 = PDMDevHlpPhysRead(pThis->CTX_SUFF(pDevIns), pRegs->bd.addr, (uint8_t *)pvDst, cbDst);
2449 AssertRC(rc2);
2450
2451# ifdef VBOX_AUDIO_DEBUG_DUMP_PCM_DATA
2452 RTFILE fh;
2453 RTFileOpen(&fh, VBOX_AUDIO_DEBUG_DUMP_PCM_DATA_PATH "ac97DMARead.pcm",
2454 RTFILE_O_OPEN_CREATE | RTFILE_O_APPEND | RTFILE_O_WRITE | RTFILE_O_DENY_NONE);
2455 RTFileWrite(fh, pvDst, cbDst, NULL);
2456 RTFileClose(fh);
2457# endif
2458 }
2459
2460 RTCircBufReleaseWriteBlock(pCircBuf, cbDst);
2461
2462 cbChunk = (uint32_t)cbDst; /* Update the current chunk size to what really has been written. */
2463 break;
2464 }
2465
2466 case AC97SOUNDSOURCE_PI_INDEX: /* Input */
2467 case AC97SOUNDSOURCE_MC_INDEX: /* Input */
2468 {
2469 void *pvSrc;
2470 size_t cbSrc;
2471
2472 RTCircBufAcquireReadBlock(pCircBuf, cbChunk, &pvSrc, &cbSrc);
2473
2474 if (cbSrc)
2475 {
2476/** @todo r=bird: Just curious, DevHDA uses PDMDevHlpPCIPhysWrite here. So,
2477 * is AC97 not subject to PCI busmaster enable/disable? */
2478 int rc2 = PDMDevHlpPhysWrite(pThis->CTX_SUFF(pDevIns), pRegs->bd.addr, (uint8_t *)pvSrc, cbSrc);
2479 AssertRC(rc2);
2480
2481# ifdef VBOX_AUDIO_DEBUG_DUMP_PCM_DATA
2482 RTFILE fh;
2483 RTFileOpen(&fh, VBOX_AUDIO_DEBUG_DUMP_PCM_DATA_PATH "ac97DMAWrite.pcm",
2484 RTFILE_O_OPEN_CREATE | RTFILE_O_APPEND | RTFILE_O_WRITE | RTFILE_O_DENY_NONE);
2485 RTFileWrite(fh, pvSrc, cbSrc, NULL);
2486 RTFileClose(fh);
2487# endif
2488 }
2489
2490 RTCircBufReleaseReadBlock(pCircBuf, cbSrc);
2491
2492 cbChunk = (uint32_t)cbSrc; /* Update the current chunk size to what really has been read. */
2493 break;
2494 }
2495
2496 default:
2497 AssertMsgFailed(("Stream #%RU8 not supported\n", pStream->u8SD));
2498 rc = VERR_NOT_SUPPORTED;
2499 break;
2500 }
2501
2502 if (RT_FAILURE(rc))
2503 break;
2504
2505 if (cbChunk)
2506 {
2507 cbProcessedTotal += cbChunk;
2508 Assert(cbProcessedTotal <= cbToProcessMax);
2509 Assert(cbLeft >= cbChunk);
2510 cbLeft -= cbChunk;
2511 Assert((cbChunk & 1) == 0); /* Else the following shift won't work */
2512
2513 pRegs->picb -= (cbChunk >> 1); /** @todo r=andy Assumes 16bit samples. */
2514 pRegs->bd.addr += cbChunk;
2515 }
2516
2517 LogFlowFunc(("[SD%RU8] cbChunk=%RU32, cbLeft=%RU32, cbTotal=%RU32, rc=%Rrc\n",
2518 pStream->u8SD, cbChunk, cbLeft, cbProcessedTotal, rc));
2519
2520 if (!pRegs->picb)
2521 {
2522 uint32_t new_sr = pRegs->sr & ~AC97_SR_CELV;
2523
2524 if (pRegs->bd.ctl_len & AC97_BD_IOC)
2525 {
2526 new_sr |= AC97_SR_BCIS;
2527 }
2528
2529 if (pRegs->civ == pRegs->lvi)
2530 {
2531 /* Did we run out of data? */
2532 LogFunc(("Underrun CIV (%RU8) == LVI (%RU8)\n", pRegs->civ, pRegs->lvi));
2533
2534 new_sr |= AC97_SR_LVBCI | AC97_SR_DCH | AC97_SR_CELV;
2535 pThis->bup_flag = (pRegs->bd.ctl_len & AC97_BD_BUP) ? BUP_LAST : 0;
2536
2537 rc = VINF_EOF;
2538 }
2539 else
2540 {
2541 pRegs->civ = pRegs->piv;
2542 pRegs->piv = (pRegs->piv + 1) % AC97_MAX_BDLE;
2543 ichac97R3StreamFetchBDLE(pThis, pStream);
2544 }
2545
2546 ichac97StreamUpdateSR(pThis, pStream, new_sr);
2547 }
2548
2549 if (/* All data processed? */
2550 rc == VINF_EOF
2551 /* ... or an error occurred? */
2552 || RT_FAILURE(rc))
2553 {
2554 break;
2555 }
2556 }
2557
2558 ichac97R3StreamUnlock(pStream);
2559
2560 LogFlowFuncLeaveRC(rc);
2561 return rc;
2562}
2563
2564#endif /* IN_RING3 */
2565
2566
2567/**
2568 * Port I/O Handler for IN operations.
2569 *
2570 * @returns VINF_SUCCESS or VINF_EM_*.
2571 * @returns VERR_IOM_IOPORT_UNUSED if the port is really unused and a ~0 value should be returned.
2572 *
2573 * @param pDevIns The device instance.
2574 * @param pvUser User argument.
2575 * @param uPort Port number used for the IN operation.
2576 * @param pu32Val Where to store the result. This is always a 32-bit
2577 * variable regardless of what @a cbVal might say.
2578 * @param cbVal Number of bytes read.
2579 */
2580PDMBOTHCBDECL(int) ichac97IOPortNABMRead(PPDMDEVINS pDevIns, void *pvUser, RTIOPORT uPort, uint32_t *pu32Val, unsigned cbVal)
2581{
2582 PAC97STATE pThis = PDMINS_2_DATA(pDevIns, PAC97STATE);
2583 RT_NOREF(pvUser);
2584
2585 DEVAC97_LOCK_RETURN(pThis, VINF_IOM_R3_IOPORT_READ);
2586
2587 /* Get the index of the NABMBAR port. */
2588 const uint32_t uPortIdx = uPort - pThis->IOPortBase[1];
2589
2590 PAC97STREAM pStream = ichac97GetStreamFromIdx(pThis, AC97_PORT2IDX(uPortIdx));
2591 PAC97BMREGS pRegs = NULL;
2592
2593 if (pStream) /* Can be NULL, depending on the index (port). */
2594 pRegs = &pStream->Regs;
2595
2596 int rc = VINF_SUCCESS;
2597
2598 switch (cbVal)
2599 {
2600 case 1:
2601 {
2602 switch (uPortIdx)
2603 {
2604 case AC97_CAS:
2605 /* Codec Access Semaphore Register */
2606 Log3Func(("CAS %d\n", pThis->cas));
2607 *pu32Val = pThis->cas;
2608 pThis->cas = 1;
2609 break;
2610 case PI_CIV:
2611 case PO_CIV:
2612 case MC_CIV:
2613 /* Current Index Value Register */
2614 *pu32Val = pRegs->civ;
2615 Log3Func(("CIV[%d] -> %#x\n", AC97_PORT2IDX(uPortIdx), *pu32Val));
2616 break;
2617 case PI_LVI:
2618 case PO_LVI:
2619 case MC_LVI:
2620 /* Last Valid Index Register */
2621 *pu32Val = pRegs->lvi;
2622 Log3Func(("LVI[%d] -> %#x\n", AC97_PORT2IDX(uPortIdx), *pu32Val));
2623 break;
2624 case PI_PIV:
2625 case PO_PIV:
2626 case MC_PIV:
2627 /* Prefetched Index Value Register */
2628 *pu32Val = pRegs->piv;
2629 Log3Func(("PIV[%d] -> %#x\n", AC97_PORT2IDX(uPortIdx), *pu32Val));
2630 break;
2631 case PI_CR:
2632 case PO_CR:
2633 case MC_CR:
2634 /* Control Register */
2635 *pu32Val = pRegs->cr;
2636 Log3Func(("CR[%d] -> %#x\n", AC97_PORT2IDX(uPortIdx), *pu32Val));
2637 break;
2638 case PI_SR:
2639 case PO_SR:
2640 case MC_SR:
2641 /* Status Register (lower part) */
2642 *pu32Val = RT_LO_U8(pRegs->sr);
2643 Log3Func(("SRb[%d] -> %#x\n", AC97_PORT2IDX(uPortIdx), *pu32Val));
2644 break;
2645 default:
2646 *pu32Val = UINT32_MAX;
2647 LogFunc(("U nabm readb %#x -> %#x\n", uPort, *pu32Val));
2648 break;
2649 }
2650 break;
2651 }
2652
2653 case 2:
2654 {
2655 switch (uPortIdx)
2656 {
2657 case PI_SR:
2658 case PO_SR:
2659 case MC_SR:
2660 /* Status Register */
2661 *pu32Val = pRegs->sr;
2662 Log3Func(("SR[%d] -> %#x\n", AC97_PORT2IDX(uPortIdx), *pu32Val));
2663 break;
2664 case PI_PICB:
2665 case PO_PICB:
2666 case MC_PICB:
2667 /* Position in Current Buffer */
2668 *pu32Val = pRegs->picb;
2669 Log3Func(("PICB[%d] -> %#x\n", AC97_PORT2IDX(uPortIdx), *pu32Val));
2670 break;
2671 default:
2672 *pu32Val = UINT32_MAX;
2673 LogFunc(("U nabm readw %#x -> %#x\n", uPort, *pu32Val));
2674 break;
2675 }
2676 break;
2677 }
2678
2679 case 4:
2680 {
2681 switch (uPortIdx)
2682 {
2683 case PI_BDBAR:
2684 case PO_BDBAR:
2685 case MC_BDBAR:
2686 /* Buffer Descriptor Base Address Register */
2687 *pu32Val = pRegs->bdbar;
2688 Log3Func(("BMADDR[%d] -> %#x\n", AC97_PORT2IDX(uPortIdx), *pu32Val));
2689 break;
2690 case PI_CIV:
2691 case PO_CIV:
2692 case MC_CIV:
2693 /* 32-bit access: Current Index Value Register +
2694 * Last Valid Index Register +
2695 * Status Register */
2696 *pu32Val = pRegs->civ | (pRegs->lvi << 8) | (pRegs->sr << 16); /** @todo r=andy Use RT_MAKE_U32_FROM_U8. */
2697 Log3Func(("CIV LVI SR[%d] -> %#x, %#x, %#x\n",
2698 AC97_PORT2IDX(uPortIdx), pRegs->civ, pRegs->lvi, pRegs->sr));
2699 break;
2700 case PI_PICB:
2701 case PO_PICB:
2702 case MC_PICB:
2703 /* 32-bit access: Position in Current Buffer Register +
2704 * Prefetched Index Value Register +
2705 * Control Register */
2706 *pu32Val = pRegs->picb | (pRegs->piv << 16) | (pRegs->cr << 24); /** @todo r=andy Use RT_MAKE_U32_FROM_U8. */
2707 Log3Func(("PICB PIV CR[%d] -> %#x %#x %#x %#x\n",
2708 AC97_PORT2IDX(uPortIdx), *pu32Val, pRegs->picb, pRegs->piv, pRegs->cr));
2709 break;
2710 case AC97_GLOB_CNT:
2711 /* Global Control */
2712 *pu32Val = pThis->glob_cnt;
2713 Log3Func(("glob_cnt -> %#x\n", *pu32Val));
2714 break;
2715 case AC97_GLOB_STA:
2716 /* Global Status */
2717 *pu32Val = pThis->glob_sta | AC97_GS_S0CR;
2718 Log3Func(("glob_sta -> %#x\n", *pu32Val));
2719 break;
2720 default:
2721 *pu32Val = UINT32_MAX;
2722 LogFunc(("U nabm readl %#x -> %#x\n", uPort, *pu32Val));
2723 break;
2724 }
2725 break;
2726 }
2727
2728 default:
2729 {
2730 AssertFailed();
2731 rc = VERR_IOM_IOPORT_UNUSED;
2732 }
2733 }
2734
2735 DEVAC97_UNLOCK(pThis);
2736
2737 return rc;
2738}
2739
2740/**
2741 * Port I/O Handler for OUT operations.
2742 *
2743 * @returns VINF_SUCCESS or VINF_EM_*.
2744 *
2745 * @param pDevIns The device instance.
2746 * @param pvUser User argument.
2747 * @param uPort Port number used for the OUT operation.
2748 * @param u32Val The value to output.
2749 * @param cbVal The value size in bytes.
2750 */
2751PDMBOTHCBDECL(int) ichac97IOPortNABMWrite(PPDMDEVINS pDevIns, void *pvUser, RTIOPORT uPort, uint32_t u32Val, unsigned cbVal)
2752{
2753 PAC97STATE pThis = PDMINS_2_DATA(pDevIns, PAC97STATE);
2754 RT_NOREF(pvUser);
2755
2756 DEVAC97_LOCK_BOTH_RETURN(pThis, VINF_IOM_R3_IOPORT_WRITE);
2757
2758 /* Get the index of the NABMBAR register. */
2759 const uint32_t uPortIdx = uPort - pThis->IOPortBase[1];
2760
2761 PAC97STREAM pStream = ichac97GetStreamFromIdx(pThis, AC97_PORT2IDX(uPortIdx));
2762 PAC97BMREGS pRegs = NULL;
2763
2764 if (pStream) /* Can be NULL, depending on the index (port). */
2765 pRegs = &pStream->Regs;
2766
2767 int rc = VINF_SUCCESS;
2768 switch (cbVal)
2769 {
2770 case 1:
2771 {
2772 switch (uPortIdx)
2773 {
2774 /*
2775 * Last Valid Index.
2776 */
2777 case PI_LVI:
2778 case PO_LVI:
2779 case MC_LVI:
2780 {
2781 if ( (pRegs->cr & AC97_CR_RPBM)
2782 && (pRegs->sr & AC97_SR_DCH))
2783 {
2784#ifdef IN_RING3
2785 pRegs->sr &= ~(AC97_SR_DCH | AC97_SR_CELV);
2786 pRegs->civ = pRegs->piv;
2787 pRegs->piv = (pRegs->piv + 1) % AC97_MAX_BDLE;
2788
2789 ichac97R3StreamFetchBDLE(pThis, pStream);
2790#else
2791 rc = VINF_IOM_R3_IOPORT_WRITE;
2792#endif
2793 }
2794 pRegs->lvi = u32Val % AC97_MAX_BDLE;
2795 Log3Func(("[SD%RU8] LVI <- %#x\n", pStream->u8SD, u32Val));
2796 break;
2797 }
2798
2799 /*
2800 * Control Registers.
2801 */
2802 case PI_CR:
2803 case PO_CR:
2804 case MC_CR:
2805 {
2806#ifdef IN_RING3
2807 Log3Func(("[SD%RU8] CR <- %#x (cr %#x)\n", pStream->u8SD, u32Val, pRegs->cr));
2808 if (u32Val & AC97_CR_RR) /* Busmaster reset. */
2809 {
2810 Log3Func(("[SD%RU8] Reset\n", pStream->u8SD));
2811
2812 /* Make sure that Run/Pause Bus Master bit (RPBM) is cleared (0). */
2813 Assert((pRegs->cr & AC97_CR_RPBM) == 0);
2814
2815 ichac97R3StreamEnable(pThis, pStream, false /* fEnable */);
2816 ichac97R3StreamReset(pThis, pStream);
2817
2818 ichac97StreamUpdateSR(pThis, pStream, AC97_SR_DCH); /** @todo Do we need to do that? */
2819 }
2820 else
2821 {
2822 pRegs->cr = u32Val & AC97_CR_VALID_MASK;
2823
2824 if (!(pRegs->cr & AC97_CR_RPBM))
2825 {
2826 Log3Func(("[SD%RU8] Disable\n", pStream->u8SD));
2827
2828 ichac97R3StreamEnable(pThis, pStream, false /* fEnable */);
2829
2830 pRegs->sr |= AC97_SR_DCH;
2831 }
2832 else
2833 {
2834 Log3Func(("[SD%RU8] Enable\n", pStream->u8SD));
2835
2836 pRegs->civ = pRegs->piv;
2837 pRegs->piv = (pRegs->piv + 1) % AC97_MAX_BDLE;
2838
2839 pRegs->sr &= ~AC97_SR_DCH;
2840
2841 /* Fetch the initial BDLE descriptor. */
2842 ichac97R3StreamFetchBDLE(pThis, pStream);
2843
2844 ichac97R3StreamEnable(pThis, pStream, true /* fEnable */);
2845 }
2846 }
2847#else /* !IN_RING3 */
2848 rc = VINF_IOM_R3_IOPORT_WRITE;
2849#endif
2850 break;
2851 }
2852
2853 /*
2854 * Status Registers.
2855 */
2856 case PI_SR:
2857 case PO_SR:
2858 case MC_SR:
2859 {
2860 pRegs->sr |= u32Val & ~(AC97_SR_RO_MASK | AC97_SR_WCLEAR_MASK);
2861 ichac97StreamUpdateSR(pThis, pStream, pRegs->sr & ~(u32Val & AC97_SR_WCLEAR_MASK));
2862 Log3Func(("[SD%RU8] SR <- %#x (sr %#x)\n", pStream->u8SD, u32Val, pRegs->sr));
2863 break;
2864 }
2865
2866 default:
2867 LogRel2(("AC97: Warning: Unimplemented NABMWrite (%u byte) portIdx=%#x <- %#x\n", cbVal, uPortIdx, u32Val));
2868 break;
2869 }
2870 break;
2871 }
2872
2873 case 2:
2874 {
2875 switch (uPortIdx)
2876 {
2877 case PI_SR:
2878 case PO_SR:
2879 case MC_SR:
2880 /* Status Register */
2881 pRegs->sr |= u32Val & ~(AC97_SR_RO_MASK | AC97_SR_WCLEAR_MASK);
2882 ichac97StreamUpdateSR(pThis, pStream, pRegs->sr & ~(u32Val & AC97_SR_WCLEAR_MASK));
2883 Log3Func(("[SD%RU8] SR <- %#x (sr %#x)\n", pStream->u8SD, u32Val, pRegs->sr));
2884 break;
2885 default:
2886 LogRel2(("AC97: Warning: Unimplemented NABMWrite (%u byte) portIdx=%#x <- %#x\n", cbVal, uPortIdx, u32Val));
2887 break;
2888 }
2889 break;
2890 }
2891
2892 case 4:
2893 {
2894 switch (uPortIdx)
2895 {
2896 case PI_BDBAR:
2897 case PO_BDBAR:
2898 case MC_BDBAR:
2899 /* Buffer Descriptor list Base Address Register */
2900 pRegs->bdbar = u32Val & ~3;
2901 Log3Func(("[SD%RU8] BDBAR <- %#x (bdbar %#x)\n", AC97_PORT2IDX(uPortIdx), u32Val, pRegs->bdbar));
2902 break;
2903 case AC97_GLOB_CNT:
2904 /* Global Control */
2905 if (u32Val & AC97_GC_WR)
2906 ichac97WarmReset(pThis);
2907 if (u32Val & AC97_GC_CR)
2908 ichac97ColdReset(pThis);
2909 if (!(u32Val & (AC97_GC_WR | AC97_GC_CR)))
2910 pThis->glob_cnt = u32Val & AC97_GC_VALID_MASK;
2911 Log3Func(("glob_cnt <- %#x (glob_cnt %#x)\n", u32Val, pThis->glob_cnt));
2912 break;
2913 case AC97_GLOB_STA:
2914 /* Global Status */
2915 pThis->glob_sta &= ~(u32Val & AC97_GS_WCLEAR_MASK);
2916 pThis->glob_sta |= (u32Val & ~(AC97_GS_WCLEAR_MASK | AC97_GS_RO_MASK)) & AC97_GS_VALID_MASK;
2917 Log3Func(("glob_sta <- %#x (glob_sta %#x)\n", u32Val, pThis->glob_sta));
2918 break;
2919 default:
2920 LogRel2(("AC97: Warning: Unimplemented NABMWrite (%u byte) portIdx=%#x <- %#x\n", cbVal, uPortIdx, u32Val));
2921 break;
2922 }
2923 break;
2924 }
2925
2926 default:
2927 LogRel2(("AC97: Warning: Unimplemented NABMWrite (%u byte) portIdx=%#x <- %#x\n", cbVal, uPortIdx, u32Val));
2928 break;
2929 }
2930
2931 DEVAC97_UNLOCK_BOTH(pThis);
2932
2933 return rc;
2934}
2935
2936/**
2937 * Port I/O Handler for IN operations.
2938 *
2939 * @returns VINF_SUCCESS or VINF_EM_*.
2940 * @returns VERR_IOM_IOPORT_UNUSED if the port is really unused and a ~0 value should be returned.
2941 *
2942 * @param pDevIns The device instance.
2943 * @param pvUser User argument.
2944 * @param uPort Port number used for the IN operation.
2945 * @param pu32Val Where to store the result. This is always a 32-bit
2946 * variable regardless of what @a cbVal might say.
2947 * @param cbVal Number of bytes read.
2948 */
2949PDMBOTHCBDECL(int) ichac97IOPortNAMRead(PPDMDEVINS pDevIns, void *pvUser, RTIOPORT uPort, uint32_t *pu32Val, unsigned cbVal)
2950{
2951 PAC97STATE pThis = PDMINS_2_DATA(pDevIns, PAC97STATE);
2952 RT_NOREF(pvUser);
2953
2954 DEVAC97_LOCK_RETURN(pThis, VINF_IOM_R3_IOPORT_READ);
2955
2956 int rc = VINF_SUCCESS;
2957
2958 uint32_t index = uPort - pThis->IOPortBase[0];
2959 Assert(index < 256);
2960
2961 switch (cbVal)
2962 {
2963 case 1:
2964 {
2965 LogRel2(("AC97: Warning: Unimplemented read (%u byte) port=%#x, idx=%RU32\n", cbVal, uPort, index));
2966 pThis->cas = 0;
2967 *pu32Val = UINT32_MAX;
2968 break;
2969 }
2970
2971 case 2:
2972 {
2973 pThis->cas = 0;
2974 *pu32Val = ichac97MixerGet(pThis, index);
2975 break;
2976 }
2977
2978 case 4:
2979 {
2980 LogRel2(("AC97: Warning: Unimplemented read (%u byte) port=%#x, idx=%RU32\n", cbVal, uPort, index));
2981 pThis->cas = 0;
2982 *pu32Val = UINT32_MAX;
2983 break;
2984 }
2985
2986 default:
2987 {
2988 AssertFailed();
2989 rc = VERR_IOM_IOPORT_UNUSED;
2990 }
2991 }
2992
2993 DEVAC97_UNLOCK(pThis);
2994
2995 return rc;
2996}
2997
2998/**
2999 * Port I/O Handler for OUT operations.
3000 *
3001 * @returns VINF_SUCCESS or VINF_EM_*.
3002 *
3003 * @param pDevIns The device instance.
3004 * @param pvUser User argument.
3005 * @param uPort Port number used for the OUT operation.
3006 * @param u32Val The value to output.
3007 * @param cbVal The value size in bytes.
3008 * @remarks Caller enters the device critical section.
3009 */
3010PDMBOTHCBDECL(int) ichac97IOPortNAMWrite(PPDMDEVINS pDevIns, void *pvUser, RTIOPORT uPort, uint32_t u32Val, unsigned cbVal)
3011{
3012 PAC97STATE pThis = PDMINS_2_DATA(pDevIns, PAC97STATE);
3013 RT_NOREF(pvUser);
3014
3015 DEVAC97_LOCK_BOTH_RETURN(pThis, VINF_IOM_R3_IOPORT_WRITE);
3016
3017 uint32_t uPortIdx = uPort - pThis->IOPortBase[0];
3018 int rc = VINF_SUCCESS;
3019 switch (cbVal)
3020 {
3021 case 1:
3022 {
3023 LogRel2(("AC97: Warning: Unimplemented NAMWrite (%u byte) port=%#x, idx=0x%x <- %#x\n", cbVal, uPort, uPortIdx, u32Val));
3024 pThis->cas = 0;
3025 break;
3026 }
3027
3028 case 2:
3029 {
3030 pThis->cas = 0;
3031 switch (uPortIdx)
3032 {
3033 case AC97_Reset:
3034#ifdef IN_RING3
3035 ichac97R3Reset(pThis->CTX_SUFF(pDevIns));
3036#else
3037 rc = VINF_IOM_R3_IOPORT_WRITE;
3038#endif
3039 break;
3040 case AC97_Powerdown_Ctrl_Stat:
3041 u32Val &= ~0xf;
3042 u32Val |= ichac97MixerGet(pThis, uPortIdx) & 0xf;
3043 ichac97MixerSet(pThis, uPortIdx, u32Val);
3044 break;
3045 case AC97_Master_Volume_Mute:
3046 if (pThis->uCodecModel == AC97_CODEC_AD1980)
3047 {
3048 if (ichac97MixerGet(pThis, AC97_AD_Misc) & AC97_AD_MISC_LOSEL)
3049 break; /* Register controls surround (rear), do nothing. */
3050 }
3051#ifdef IN_RING3
3052 ichac97R3MixerSetVolume(pThis, uPortIdx, PDMAUDIOMIXERCTL_VOLUME_MASTER, u32Val);
3053#else
3054 rc = VINF_IOM_R3_IOPORT_WRITE;
3055#endif
3056 break;
3057 case AC97_Headphone_Volume_Mute:
3058 if (pThis->uCodecModel == AC97_CODEC_AD1980)
3059 {
3060 if (ichac97MixerGet(pThis, AC97_AD_Misc) & AC97_AD_MISC_HPSEL)
3061 {
3062 /* Register controls PCM (front) outputs. */
3063#ifdef IN_RING3
3064 ichac97R3MixerSetVolume(pThis, uPortIdx, PDMAUDIOMIXERCTL_VOLUME_MASTER, u32Val);
3065#else
3066 rc = VINF_IOM_R3_IOPORT_WRITE;
3067#endif
3068 }
3069 }
3070 break;
3071 case AC97_PCM_Out_Volume_Mute:
3072#ifdef IN_RING3
3073 ichac97R3MixerSetVolume(pThis, uPortIdx, PDMAUDIOMIXERCTL_FRONT, u32Val);
3074#else
3075 rc = VINF_IOM_R3_IOPORT_WRITE;
3076#endif
3077 break;
3078 case AC97_Line_In_Volume_Mute:
3079#ifdef IN_RING3
3080 ichac97R3MixerSetVolume(pThis, uPortIdx, PDMAUDIOMIXERCTL_LINE_IN, u32Val);
3081#else
3082 rc = VINF_IOM_R3_IOPORT_WRITE;
3083#endif
3084 break;
3085 case AC97_Record_Select:
3086#ifdef IN_RING3
3087 ichac97R3MixerRecordSelect(pThis, u32Val);
3088#else
3089 rc = VINF_IOM_R3_IOPORT_WRITE;
3090#endif
3091 break;
3092 case AC97_Record_Gain_Mute:
3093#ifdef IN_RING3
3094 /* Newer Ubuntu guests rely on that when controlling gain and muting
3095 * the recording (capturing) levels. */
3096 ichac97R3MixerSetVolume(pThis, uPortIdx, PDMAUDIOMIXERCTL_LINE_IN, u32Val);
3097#else
3098 rc = VINF_IOM_R3_IOPORT_WRITE;
3099#endif
3100 break;
3101 case AC97_Record_Gain_Mic_Mute:
3102#ifdef IN_RING3
3103 /* Ditto; see note above. */
3104 ichac97R3MixerSetVolume(pThis, uPortIdx, PDMAUDIOMIXERCTL_MIC_IN, u32Val);
3105#else
3106 rc = VINF_IOM_R3_IOPORT_WRITE;
3107#endif
3108 break;
3109 case AC97_Vendor_ID1:
3110 case AC97_Vendor_ID2:
3111 LogFunc(("Attempt to write vendor ID to %#x\n", u32Val));
3112 break;
3113 case AC97_Extended_Audio_ID:
3114 LogFunc(("Attempt to write extended audio ID to %#x\n", u32Val));
3115 break;
3116 case AC97_Extended_Audio_Ctrl_Stat:
3117#ifdef IN_RING3
3118 if (!(u32Val & AC97_EACS_VRA))
3119 {
3120 ichac97MixerSet(pThis, AC97_PCM_Front_DAC_Rate, 48000);
3121 ichac97R3StreamReOpen(pThis, &pThis->StreamOut);
3122
3123 ichac97MixerSet(pThis, AC97_PCM_LR_ADC_Rate, 48000);
3124 ichac97R3StreamReOpen(pThis, &pThis->StreamLineIn);
3125 }
3126 else
3127 LogRel2(("AC97: Variable rate audio (VRA) is not supported\n"));
3128
3129 if (!(u32Val & AC97_EACS_VRM))
3130 {
3131 ichac97MixerSet(pThis, AC97_MIC_ADC_Rate, 48000);
3132 ichac97R3StreamReOpen(pThis, &pThis->StreamMicIn);
3133 }
3134 else
3135 LogRel2(("AC97: Variable rate microphone audio (VRM) is not supported\n"));
3136
3137 LogFunc(("Setting extended audio control to %#x\n", u32Val));
3138 ichac97MixerSet(pThis, AC97_Extended_Audio_Ctrl_Stat, u32Val);
3139#else
3140 rc = VINF_IOM_R3_IOPORT_WRITE;
3141#endif
3142 break;
3143 case AC97_PCM_Front_DAC_Rate:
3144 if (ichac97MixerGet(pThis, AC97_Extended_Audio_Ctrl_Stat) & AC97_EACS_VRA)
3145 {
3146#ifdef IN_RING3
3147 ichac97MixerSet(pThis, uPortIdx, u32Val);
3148 LogFunc(("Set front DAC rate to %RU32\n", u32Val));
3149 ichac97R3StreamReOpen(pThis, &pThis->StreamOut);
3150#else
3151 rc = VINF_IOM_R3_IOPORT_WRITE;
3152#endif
3153 }
3154 else
3155 AssertMsgFailed(("Attempt to set front DAC rate to %RU32, but VRA is not set\n", u32Val));
3156 break;
3157 case AC97_MIC_ADC_Rate:
3158 if (ichac97MixerGet(pThis, AC97_Extended_Audio_Ctrl_Stat) & AC97_EACS_VRM)
3159 {
3160#ifdef IN_RING3
3161 ichac97MixerSet(pThis, uPortIdx, u32Val);
3162 LogFunc(("Set MIC ADC rate to %RU32\n", u32Val));
3163 ichac97R3StreamReOpen(pThis, &pThis->StreamMicIn);
3164#else
3165 rc = VINF_IOM_R3_IOPORT_WRITE;
3166#endif
3167 }
3168 else
3169 AssertMsgFailed(("Attempt to set MIC ADC rate to %RU32, but VRM is not set\n", u32Val));
3170 break;
3171 case AC97_PCM_LR_ADC_Rate:
3172 if (ichac97MixerGet(pThis, AC97_Extended_Audio_Ctrl_Stat) & AC97_EACS_VRA)
3173 {
3174#ifdef IN_RING3
3175 ichac97MixerSet(pThis, uPortIdx, u32Val);
3176 LogFunc(("Set front LR ADC rate to %RU32\n", u32Val));
3177 ichac97R3StreamReOpen(pThis, &pThis->StreamLineIn);
3178#else
3179 rc = VINF_IOM_R3_IOPORT_WRITE;
3180#endif
3181 }
3182 else
3183 AssertMsgFailed(("Attempt to set LR ADC rate to %RU32, but VRA is not set\n", u32Val));
3184 break;
3185 default:
3186 LogRel2(("AC97: Warning: Unimplemented NAMWrite (%u byte) port=%#x, idx=0x%x <- %#x\n", cbVal, uPort, uPortIdx, u32Val));
3187 ichac97MixerSet(pThis, uPortIdx, u32Val);
3188 break;
3189 }
3190 break;
3191 }
3192
3193 case 4:
3194 {
3195 LogRel2(("AC97: Warning: Unimplemented NAMWrite (%u byte) port=%#x, idx=0x%x <- %#x\n", cbVal, uPort, uPortIdx, u32Val));
3196 pThis->cas = 0;
3197 break;
3198 }
3199
3200 default:
3201 AssertMsgFailed(("Unhandled NAMWrite port=%#x, cbVal=%u u32Val=%#x\n", uPort, cbVal, u32Val));
3202 break;
3203 }
3204
3205 DEVAC97_UNLOCK_BOTH(pThis);
3206
3207 return rc;
3208}
3209
3210#ifdef IN_RING3
3211
3212/**
3213 * @callback_method_impl{FNPCIIOREGIONMAP}
3214 */
3215static DECLCALLBACK(int) ichac97R3IOPortMap(PPDMDEVINS pDevIns, PPDMPCIDEV pPciDev, uint32_t iRegion,
3216 RTGCPHYS GCPhysAddress, RTGCPHYS cb, PCIADDRESSSPACE enmType)
3217{
3218 RT_NOREF(cb, enmType);
3219
3220 Assert(enmType == PCI_ADDRESS_SPACE_IO);
3221 Assert(cb >= 0x20);
3222
3223 if (iRegion > 1) /* We support 2 regions max. at the moment. */
3224 return VERR_INVALID_PARAMETER;
3225
3226 PAC97STATE pThis = RT_FROM_MEMBER(pPciDev, AC97STATE, PciDev);
3227 RTIOPORT Port = (RTIOPORT)GCPhysAddress;
3228
3229 int rc;
3230 if (iRegion == 0)
3231 {
3232 rc = PDMDevHlpIOPortRegister(pDevIns, Port, 256, NULL, ichac97IOPortNAMWrite, ichac97IOPortNAMRead,
3233 NULL, NULL, "ICHAC97 NAM");
3234 AssertRCReturn(rc, rc);
3235 if (pThis->fRZEnabled)
3236 {
3237 rc = PDMDevHlpIOPortRegisterR0(pDevIns, Port, 256, NIL_RTR0PTR, "ichac97IOPortNAMWrite", "ichac97IOPortNAMRead",
3238 NULL, NULL, "ICHAC97 NAM");
3239 AssertRCReturn(rc, rc);
3240 rc = PDMDevHlpIOPortRegisterRC(pDevIns, Port, 256, NIL_RTRCPTR, "ichac97IOPortNAMWrite", "ichac97IOPortNAMRead",
3241 NULL, NULL, "ICHAC97 NAM");
3242 AssertRCReturn(rc, rc);
3243 }
3244 }
3245 else
3246 {
3247 rc = PDMDevHlpIOPortRegister(pDevIns, Port, 64, NULL, ichac97IOPortNABMWrite, ichac97IOPortNABMRead,
3248 NULL, NULL, "ICHAC97 NABM");
3249 AssertRCReturn(rc, rc);
3250 if (pThis->fRZEnabled)
3251 {
3252 rc = PDMDevHlpIOPortRegisterR0(pDevIns, Port, 64, NIL_RTR0PTR, "ichac97IOPortNABMWrite", "ichac97IOPortNABMRead",
3253 NULL, NULL, "ICHAC97 NABM");
3254 AssertRCReturn(rc, rc);
3255 rc = PDMDevHlpIOPortRegisterRC(pDevIns, Port, 64, NIL_RTRCPTR, "ichac97IOPortNABMWrite", "ichac97IOPortNABMRead",
3256 NULL, NULL, "ICHAC97 NABM");
3257 AssertRCReturn(rc, rc);
3258
3259 }
3260 }
3261
3262 pThis->IOPortBase[iRegion] = Port;
3263 return VINF_SUCCESS;
3264}
3265
3266
3267/**
3268 * Saves (serializes) an AC'97 stream using SSM.
3269 *
3270 * @returns IPRT status code.
3271 * @param pDevIns Device instance.
3272 * @param pSSM Saved state manager (SSM) handle to use.
3273 * @param pStream AC'97 stream to save.
3274 */
3275static int ichac97R3SaveStream(PPDMDEVINS pDevIns, PSSMHANDLE pSSM, PAC97STREAM pStream)
3276{
3277 RT_NOREF(pDevIns);
3278 PAC97BMREGS pRegs = &pStream->Regs;
3279
3280 SSMR3PutU32(pSSM, pRegs->bdbar);
3281 SSMR3PutU8( pSSM, pRegs->civ);
3282 SSMR3PutU8( pSSM, pRegs->lvi);
3283 SSMR3PutU16(pSSM, pRegs->sr);
3284 SSMR3PutU16(pSSM, pRegs->picb);
3285 SSMR3PutU8( pSSM, pRegs->piv);
3286 SSMR3PutU8( pSSM, pRegs->cr);
3287 SSMR3PutS32(pSSM, pRegs->bd_valid);
3288 SSMR3PutU32(pSSM, pRegs->bd.addr);
3289 SSMR3PutU32(pSSM, pRegs->bd.ctl_len);
3290
3291 return VINF_SUCCESS;
3292}
3293
3294/**
3295 * @callback_method_impl{FNSSMDEVSAVEEXEC}
3296 */
3297static DECLCALLBACK(int) ichac97R3SaveExec(PPDMDEVINS pDevIns, PSSMHANDLE pSSM)
3298{
3299 PAC97STATE pThis = PDMINS_2_DATA(pDevIns, PAC97STATE);
3300
3301 LogFlowFuncEnter();
3302
3303 SSMR3PutU32(pSSM, pThis->glob_cnt);
3304 SSMR3PutU32(pSSM, pThis->glob_sta);
3305 SSMR3PutU32(pSSM, pThis->cas);
3306
3307 /** @todo r=andy For the next saved state version, add unique stream identifiers and a stream count. */
3308 /* Note: The order the streams are saved here is critical, so don't touch. */
3309 int rc2 = ichac97R3SaveStream(pDevIns, pSSM, &pThis->StreamLineIn);
3310 AssertRC(rc2);
3311 rc2 = ichac97R3SaveStream(pDevIns, pSSM, &pThis->StreamOut);
3312 AssertRC(rc2);
3313 rc2 = ichac97R3SaveStream(pDevIns, pSSM, &pThis->StreamMicIn);
3314 AssertRC(rc2);
3315
3316 SSMR3PutMem(pSSM, pThis->mixer_data, sizeof(pThis->mixer_data));
3317
3318 uint8_t active[AC97SOUNDSOURCE_END_INDEX];
3319
3320 active[AC97SOUNDSOURCE_PI_INDEX] = ichac97R3StreamIsEnabled(pThis, &pThis->StreamLineIn) ? 1 : 0;
3321 active[AC97SOUNDSOURCE_PO_INDEX] = ichac97R3StreamIsEnabled(pThis, &pThis->StreamOut) ? 1 : 0;
3322 active[AC97SOUNDSOURCE_MC_INDEX] = ichac97R3StreamIsEnabled(pThis, &pThis->StreamMicIn) ? 1 : 0;
3323
3324 SSMR3PutMem(pSSM, active, sizeof(active));
3325
3326 LogFlowFuncLeaveRC(VINF_SUCCESS);
3327 return VINF_SUCCESS;
3328}
3329
3330/**
3331 * Loads an AC'97 stream from SSM.
3332 *
3333 * @returns IPRT status code.
3334 * @param pSSM Saved state manager (SSM) handle to use.
3335 * @param pStream AC'97 stream to load.
3336 */
3337static int ichac97R3LoadStream(PSSMHANDLE pSSM, PAC97STREAM pStream)
3338{
3339 PAC97BMREGS pRegs = &pStream->Regs;
3340
3341 SSMR3GetU32(pSSM, &pRegs->bdbar);
3342 SSMR3GetU8( pSSM, &pRegs->civ);
3343 SSMR3GetU8( pSSM, &pRegs->lvi);
3344 SSMR3GetU16(pSSM, &pRegs->sr);
3345 SSMR3GetU16(pSSM, &pRegs->picb);
3346 SSMR3GetU8( pSSM, &pRegs->piv);
3347 SSMR3GetU8( pSSM, &pRegs->cr);
3348 SSMR3GetS32(pSSM, &pRegs->bd_valid);
3349 SSMR3GetU32(pSSM, &pRegs->bd.addr);
3350 return SSMR3GetU32(pSSM, &pRegs->bd.ctl_len);
3351}
3352
3353/**
3354 * @callback_method_impl{FNSSMDEVLOADEXEC}
3355 */
3356static DECLCALLBACK(int) ichac97R3LoadExec(PPDMDEVINS pDevIns, PSSMHANDLE pSSM, uint32_t uVersion, uint32_t uPass)
3357{
3358 PAC97STATE pThis = PDMINS_2_DATA(pDevIns, PAC97STATE);
3359
3360 LogRel2(("ichac97LoadExec: uVersion=%RU32, uPass=0x%x\n", uVersion, uPass));
3361
3362 AssertMsgReturn (uVersion == AC97_SSM_VERSION, ("%RU32\n", uVersion), VERR_SSM_UNSUPPORTED_DATA_UNIT_VERSION);
3363 Assert(uPass == SSM_PASS_FINAL); NOREF(uPass);
3364
3365 SSMR3GetU32(pSSM, &pThis->glob_cnt);
3366 SSMR3GetU32(pSSM, &pThis->glob_sta);
3367 SSMR3GetU32(pSSM, &pThis->cas);
3368
3369 /** @todo r=andy For the next saved state version, add unique stream identifiers and a stream count. */
3370 /* Note: The order the streams are loaded here is critical, so don't touch. */
3371 int rc2 = ichac97R3LoadStream(pSSM, &pThis->StreamLineIn);
3372 AssertRCReturn(rc2, rc2);
3373 rc2 = ichac97R3LoadStream(pSSM, &pThis->StreamOut);
3374 AssertRCReturn(rc2, rc2);
3375 rc2 = ichac97R3LoadStream(pSSM, &pThis->StreamMicIn);
3376 AssertRCReturn(rc2, rc2);
3377
3378 SSMR3GetMem(pSSM, pThis->mixer_data, sizeof(pThis->mixer_data));
3379
3380 /** @todo r=andy Stream IDs are hardcoded to certain streams. */
3381 uint8_t uaStrmsActive[AC97SOUNDSOURCE_END_INDEX];
3382 rc2 = SSMR3GetMem(pSSM, uaStrmsActive, sizeof(uaStrmsActive));
3383 AssertRCReturn(rc2, rc2);
3384
3385 ichac97R3MixerRecordSelect(pThis, ichac97MixerGet(pThis, AC97_Record_Select));
3386# define V_(a, b) ichac97R3MixerSetVolume(pThis, a, b, ichac97MixerGet(pThis, a))
3387 V_(AC97_Master_Volume_Mute, PDMAUDIOMIXERCTL_VOLUME_MASTER);
3388 V_(AC97_PCM_Out_Volume_Mute, PDMAUDIOMIXERCTL_FRONT);
3389 V_(AC97_Line_In_Volume_Mute, PDMAUDIOMIXERCTL_LINE_IN);
3390 V_(AC97_Mic_Volume_Mute, PDMAUDIOMIXERCTL_MIC_IN);
3391# undef V_
3392 if (pThis->uCodecModel == AC97_CODEC_AD1980)
3393 if (ichac97MixerGet(pThis, AC97_AD_Misc) & AC97_AD_MISC_HPSEL)
3394 ichac97R3MixerSetVolume(pThis, AC97_Headphone_Volume_Mute, PDMAUDIOMIXERCTL_VOLUME_MASTER,
3395 ichac97MixerGet(pThis, AC97_Headphone_Volume_Mute));
3396
3397 /** @todo r=andy Stream IDs are hardcoded to certain streams. */
3398 rc2 = ichac97R3StreamEnable(pThis, &pThis->StreamLineIn, RT_BOOL(uaStrmsActive[AC97SOUNDSOURCE_PI_INDEX]));
3399 if (RT_SUCCESS(rc2))
3400 rc2 = ichac97R3StreamEnable(pThis, &pThis->StreamMicIn, RT_BOOL(uaStrmsActive[AC97SOUNDSOURCE_MC_INDEX]));
3401 if (RT_SUCCESS(rc2))
3402 rc2 = ichac97R3StreamEnable(pThis, &pThis->StreamOut, RT_BOOL(uaStrmsActive[AC97SOUNDSOURCE_PO_INDEX]));
3403
3404 pThis->bup_flag = 0;
3405 pThis->last_samp = 0;
3406
3407 return VINF_SUCCESS;
3408}
3409
3410
3411/**
3412 * @interface_method_impl{PDMIBASE,pfnQueryInterface}
3413 */
3414static DECLCALLBACK(void *) ichac97R3QueryInterface(struct PDMIBASE *pInterface, const char *pszIID)
3415{
3416 PAC97STATE pThis = RT_FROM_MEMBER(pInterface, AC97STATE, IBase);
3417 Assert(&pThis->IBase == pInterface);
3418
3419 PDMIBASE_RETURN_INTERFACE(pszIID, PDMIBASE, &pThis->IBase);
3420 return NULL;
3421}
3422
3423
3424/**
3425 * Powers off the device.
3426 *
3427 * @param pDevIns Device instance to power off.
3428 */
3429static DECLCALLBACK(void) ichac97R3PowerOff(PPDMDEVINS pDevIns)
3430{
3431 PAC97STATE pThis = PDMINS_2_DATA(pDevIns, PAC97STATE);
3432
3433 LogRel2(("AC97: Powering off ...\n"));
3434
3435 /* Note: Involves mixer stream / sink destruction, so also do this here
3436 * instead of in ichac97R3Destruct(). */
3437 ichac97R3StreamsDestroy(pThis);
3438
3439 /**
3440 * Note: Destroy the mixer while powering off and *not* in ichac97R3Destruct,
3441 * giving the mixer the chance to release any references held to
3442 * PDM audio streams it maintains.
3443 */
3444 if (pThis->pMixer)
3445 {
3446 AudioMixerDestroy(pThis->pMixer);
3447 pThis->pMixer = NULL;
3448 }
3449}
3450
3451
3452/**
3453 * @interface_method_impl{PDMDEVREG,pfnReset}
3454 *
3455 * @remarks The original sources didn't install a reset handler, but it seems to
3456 * make sense to me so we'll do it.
3457 */
3458static DECLCALLBACK(void) ichac97R3Reset(PPDMDEVINS pDevIns)
3459{
3460 PAC97STATE pThis = PDMINS_2_DATA(pDevIns, PAC97STATE);
3461
3462 LogRel(("AC97: Reset\n"));
3463
3464 /*
3465 * Reset the mixer too. The Windows XP driver seems to rely on
3466 * this. At least it wants to read the vendor id before it resets
3467 * the codec manually.
3468 */
3469 ichac97R3MixerReset(pThis);
3470
3471 /*
3472 * Reset all streams.
3473 */
3474 ichac97R3StreamEnable(pThis, &pThis->StreamLineIn, false /* fEnable */);
3475 ichac97R3StreamReset(pThis, &pThis->StreamLineIn);
3476
3477 ichac97R3StreamEnable(pThis, &pThis->StreamMicIn, false /* fEnable */);
3478 ichac97R3StreamReset(pThis, &pThis->StreamMicIn);
3479
3480 ichac97R3StreamEnable(pThis, &pThis->StreamOut, false /* fEnable */);
3481 ichac97R3StreamReset(pThis, &pThis->StreamOut);
3482
3483 /*
3484 * Reset mixer sinks.
3485 *
3486 * Do the reset here instead of in ichac97R3StreamReset();
3487 * the mixer sink(s) might still have data to be processed when an audio stream gets reset.
3488 */
3489 AudioMixerSinkReset(pThis->pSinkLineIn);
3490 AudioMixerSinkReset(pThis->pSinkMicIn);
3491 AudioMixerSinkReset(pThis->pSinkOut);
3492
3493# ifndef VBOX_WITH_AUDIO_AC97_CALLBACKS
3494 /*
3495 * Stop the timer, if any.
3496 */
3497 ichac97R3TimerStop(pThis);
3498
3499 pThis->cStreamsActive = 0;
3500# endif
3501}
3502
3503
3504/**
3505 * Attach command, internal version.
3506 *
3507 * This is called to let the device attach to a driver for a specified LUN
3508 * during runtime. This is not called during VM construction, the device
3509 * constructor has to attach to all the available drivers.
3510 *
3511 * @returns VBox status code.
3512 * @param pThis AC'97 state.
3513 * @param uLUN The logical unit which is being detached.
3514 * @param fFlags Flags, combination of the PDMDEVATT_FLAGS_* \#defines.
3515 * @param ppDrv Attached driver instance on success. Optional.
3516 */
3517static int ichac97R3AttachInternal(PAC97STATE pThis, unsigned uLUN, uint32_t fFlags, PAC97DRIVER *ppDrv)
3518{
3519 RT_NOREF(fFlags);
3520
3521 /*
3522 * Attach driver.
3523 */
3524 char *pszDesc;
3525 if (RTStrAPrintf(&pszDesc, "Audio driver port (AC'97) for LUN #%u", uLUN) <= 0)
3526 AssertLogRelFailedReturn(VERR_NO_MEMORY);
3527
3528 PPDMIBASE pDrvBase;
3529 int rc = PDMDevHlpDriverAttach(pThis->pDevInsR3, uLUN,
3530 &pThis->IBase, &pDrvBase, pszDesc);
3531 if (RT_SUCCESS(rc))
3532 {
3533 PAC97DRIVER pDrv = (PAC97DRIVER)RTMemAllocZ(sizeof(AC97DRIVER));
3534 if (pDrv)
3535 {
3536 pDrv->pDrvBase = pDrvBase;
3537 pDrv->pConnector = PDMIBASE_QUERY_INTERFACE(pDrvBase, PDMIAUDIOCONNECTOR);
3538 AssertMsg(pDrv->pConnector != NULL, ("Configuration error: LUN #%u has no host audio interface, rc=%Rrc\n", uLUN, rc));
3539 pDrv->pAC97State = pThis;
3540 pDrv->uLUN = uLUN;
3541
3542 /*
3543 * For now we always set the driver at LUN 0 as our primary
3544 * host backend. This might change in the future.
3545 */
3546 if (pDrv->uLUN == 0)
3547 pDrv->fFlags |= PDMAUDIODRVFLAGS_PRIMARY;
3548
3549 LogFunc(("LUN#%RU8: pCon=%p, drvFlags=0x%x\n", uLUN, pDrv->pConnector, pDrv->fFlags));
3550
3551 /* Attach to driver list if not attached yet. */
3552 if (!pDrv->fAttached)
3553 {
3554 RTListAppend(&pThis->lstDrv, &pDrv->Node);
3555 pDrv->fAttached = true;
3556 }
3557
3558 if (ppDrv)
3559 *ppDrv = pDrv;
3560 }
3561 else
3562 rc = VERR_NO_MEMORY;
3563 }
3564 else if (rc == VERR_PDM_NO_ATTACHED_DRIVER)
3565 LogFunc(("No attached driver for LUN #%u\n", uLUN));
3566
3567 if (RT_FAILURE(rc))
3568 {
3569 /* Only free this string on failure;
3570 * must remain valid for the live of the driver instance. */
3571 RTStrFree(pszDesc);
3572 }
3573
3574 LogFunc(("uLUN=%u, fFlags=0x%x, rc=%Rrc\n", uLUN, fFlags, rc));
3575 return rc;
3576}
3577
3578/**
3579 * Detach command, internal version.
3580 *
3581 * This is called to let the device detach from a driver for a specified LUN
3582 * during runtime.
3583 *
3584 * @returns VBox status code.
3585 * @param pThis AC'97 state.
3586 * @param pDrv Driver to detach device from.
3587 * @param fFlags Flags, combination of the PDMDEVATT_FLAGS_* \#defines.
3588 */
3589static int ichac97R3DetachInternal(PAC97STATE pThis, PAC97DRIVER pDrv, uint32_t fFlags)
3590{
3591 RT_NOREF(fFlags);
3592
3593 AudioMixerSinkRemoveStream(pThis->pSinkMicIn, pDrv->MicIn.pMixStrm);
3594 AudioMixerStreamDestroy(pDrv->MicIn.pMixStrm);
3595 pDrv->MicIn.pMixStrm = NULL;
3596
3597 AudioMixerSinkRemoveStream(pThis->pSinkLineIn, pDrv->LineIn.pMixStrm);
3598 AudioMixerStreamDestroy(pDrv->LineIn.pMixStrm);
3599 pDrv->LineIn.pMixStrm = NULL;
3600
3601 AudioMixerSinkRemoveStream(pThis->pSinkOut, pDrv->Out.pMixStrm);
3602 AudioMixerStreamDestroy(pDrv->Out.pMixStrm);
3603 pDrv->Out.pMixStrm = NULL;
3604
3605 RTListNodeRemove(&pDrv->Node);
3606
3607 LogFunc(("uLUN=%u, fFlags=0x%x\n", pDrv->uLUN, fFlags));
3608 return VINF_SUCCESS;
3609}
3610
3611/**
3612 * @interface_method_impl{PDMDEVREG,pfnAttach}
3613 */
3614static DECLCALLBACK(int) ichac97R3Attach(PPDMDEVINS pDevIns, unsigned uLUN, uint32_t fFlags)
3615{
3616 PAC97STATE pThis = PDMINS_2_DATA(pDevIns, PAC97STATE);
3617
3618 LogFunc(("uLUN=%u, fFlags=0x%x\n", uLUN, fFlags));
3619
3620 DEVAC97_LOCK(pThis);
3621
3622 PAC97DRIVER pDrv;
3623 int rc2 = ichac97R3AttachInternal(pThis, uLUN, fFlags, &pDrv);
3624 if (RT_SUCCESS(rc2))
3625 {
3626 if (DrvAudioHlpStreamCfgIsValid(&pThis->StreamLineIn.State.Cfg))
3627 ichac97R3MixerAddDrvStream(pThis, pThis->pSinkLineIn, &pThis->StreamLineIn.State.Cfg, pDrv);
3628
3629 if (DrvAudioHlpStreamCfgIsValid(&pThis->StreamMicIn.State.Cfg))
3630 ichac97R3MixerAddDrvStream(pThis, pThis->pSinkMicIn, &pThis->StreamMicIn.State.Cfg, pDrv);
3631
3632 if (DrvAudioHlpStreamCfgIsValid(&pThis->StreamOut.State.Cfg))
3633 ichac97R3MixerAddDrvStream(pThis, pThis->pSinkOut, &pThis->StreamOut.State.Cfg, pDrv);
3634 }
3635
3636 DEVAC97_UNLOCK(pThis);
3637
3638 return VINF_SUCCESS;
3639}
3640
3641/**
3642 * @interface_method_impl{PDMDEVREG,pfnDetach}
3643 */
3644static DECLCALLBACK(void) ichac97R3Detach(PPDMDEVINS pDevIns, unsigned uLUN, uint32_t fFlags)
3645{
3646 PAC97STATE pThis = PDMINS_2_DATA(pDevIns, PAC97STATE);
3647
3648 LogFunc(("uLUN=%u, fFlags=0x%x\n", uLUN, fFlags));
3649
3650 DEVAC97_LOCK(pThis);
3651
3652 PAC97DRIVER pDrv, pDrvNext;
3653 RTListForEachSafe(&pThis->lstDrv, pDrv, pDrvNext, AC97DRIVER, Node)
3654 {
3655 if (pDrv->uLUN == uLUN)
3656 {
3657 int rc2 = ichac97R3DetachInternal(pThis, pDrv, fFlags);
3658 if (RT_SUCCESS(rc2))
3659 {
3660 RTMemFree(pDrv);
3661 pDrv = NULL;
3662 }
3663
3664 break;
3665 }
3666 }
3667
3668 DEVAC97_UNLOCK(pThis);
3669}
3670
3671/**
3672 * Re-attaches (replaces) a driver with a new driver.
3673 *
3674 * @returns VBox status code.
3675 * @param pThis Device instance.
3676 * @param pDrv Driver instance used for attaching to.
3677 * If NULL is specified, a new driver will be created and appended
3678 * to the driver list.
3679 * @param uLUN The logical unit which is being re-detached.
3680 * @param pszDriver New driver name to attach.
3681 */
3682static int ichac97R3ReattachInternal(PAC97STATE pThis, PAC97DRIVER pDrv, uint8_t uLUN, const char *pszDriver)
3683{
3684 AssertPtrReturn(pThis, VERR_INVALID_POINTER);
3685 AssertPtrReturn(pszDriver, VERR_INVALID_POINTER);
3686
3687 int rc;
3688
3689 if (pDrv)
3690 {
3691 rc = ichac97R3DetachInternal(pThis, pDrv, 0 /* fFlags */);
3692 if (RT_SUCCESS(rc))
3693 rc = PDMDevHlpDriverDetach(pThis->pDevInsR3, PDMIBASE_2_PDMDRV(pDrv->pDrvBase), 0 /* fFlags */);
3694
3695 if (RT_FAILURE(rc))
3696 return rc;
3697
3698 pDrv = NULL;
3699 }
3700
3701 PVM pVM = PDMDevHlpGetVM(pThis->pDevInsR3);
3702 PCFGMNODE pRoot = CFGMR3GetRoot(pVM);
3703 PCFGMNODE pDev0 = CFGMR3GetChild(pRoot, "Devices/ichac97/0/");
3704
3705 /* Remove LUN branch. */
3706 CFGMR3RemoveNode(CFGMR3GetChildF(pDev0, "LUN#%u/", uLUN));
3707
3708# define RC_CHECK() if (RT_FAILURE(rc)) { AssertReleaseRC(rc); break; }
3709
3710 do
3711 {
3712 PCFGMNODE pLunL0;
3713 rc = CFGMR3InsertNodeF(pDev0, &pLunL0, "LUN#%u/", uLUN); RC_CHECK();
3714 rc = CFGMR3InsertString(pLunL0, "Driver", "AUDIO"); RC_CHECK();
3715 rc = CFGMR3InsertNode(pLunL0, "Config/", NULL); RC_CHECK();
3716
3717 PCFGMNODE pLunL1, pLunL2;
3718 rc = CFGMR3InsertNode (pLunL0, "AttachedDriver/", &pLunL1); RC_CHECK();
3719 rc = CFGMR3InsertNode (pLunL1, "Config/", &pLunL2); RC_CHECK();
3720 rc = CFGMR3InsertString(pLunL1, "Driver", pszDriver); RC_CHECK();
3721
3722 rc = CFGMR3InsertString(pLunL2, "AudioDriver", pszDriver); RC_CHECK();
3723
3724 } while (0);
3725
3726 if (RT_SUCCESS(rc))
3727 rc = ichac97R3AttachInternal(pThis, uLUN, 0 /* fFlags */, NULL /* ppDrv */);
3728
3729 LogFunc(("pThis=%p, uLUN=%u, pszDriver=%s, rc=%Rrc\n", pThis, uLUN, pszDriver, rc));
3730
3731# undef RC_CHECK
3732
3733 return rc;
3734}
3735
3736/**
3737 * @interface_method_impl{PDMDEVREG,pfnRelocate}
3738 */
3739static DECLCALLBACK(void) ichac97R3Relocate(PPDMDEVINS pDevIns, RTGCINTPTR offDelta)
3740{
3741 NOREF(offDelta);
3742 PAC97STATE pThis = PDMINS_2_DATA(pDevIns, PAC97STATE);
3743 pThis->pDevInsRC = PDMDEVINS_2_RCPTR(pDevIns);
3744# ifndef VBOX_WITH_AUDIO_AC97_CALLBACKS
3745 pThis->pTimerRC = TMTimerRCPtr(pThis->pTimerR3);
3746# endif
3747}
3748
3749/**
3750 * @interface_method_impl{PDMDEVREG,pfnDestruct}
3751 */
3752static DECLCALLBACK(int) ichac97R3Destruct(PPDMDEVINS pDevIns)
3753{
3754 PDMDEV_CHECK_VERSIONS_RETURN_QUIET(pDevIns); /* this shall come first */
3755 PAC97STATE pThis = PDMINS_2_DATA(pDevIns, PAC97STATE);
3756
3757 LogFlowFuncEnter();
3758
3759 PAC97DRIVER pDrv, pDrvNext;
3760 RTListForEachSafe(&pThis->lstDrv, pDrv, pDrvNext, AC97DRIVER, Node)
3761 {
3762 RTListNodeRemove(&pDrv->Node);
3763 RTMemFree(pDrv);
3764 }
3765
3766 /* Sanity. */
3767 Assert(RTListIsEmpty(&pThis->lstDrv));
3768
3769 return VINF_SUCCESS;
3770}
3771
3772/**
3773 * @interface_method_impl{PDMDEVREG,pfnConstruct}
3774 */
3775static DECLCALLBACK(int) ichac97R3Construct(PPDMDEVINS pDevIns, int iInstance, PCFGMNODE pCfg)
3776{
3777 PDMDEV_CHECK_VERSIONS_RETURN(pDevIns); /* this shall come first */
3778 PAC97STATE pThis = PDMINS_2_DATA(pDevIns, PAC97STATE);
3779 Assert(iInstance == 0); RT_NOREF(iInstance);
3780
3781 /*
3782 * Initialize data so we can run the destructor without scewing up.
3783 */
3784 pThis->pDevInsR3 = pDevIns;
3785 pThis->pDevInsR0 = PDMDEVINS_2_R0PTR(pDevIns);
3786 pThis->pDevInsRC = PDMDEVINS_2_RCPTR(pDevIns);
3787 pThis->IBase.pfnQueryInterface = ichac97R3QueryInterface;
3788 RTListInit(&pThis->lstDrv);
3789
3790 /*
3791 * Validations.
3792 */
3793 if (!CFGMR3AreValuesValid(pCfg,
3794 "RZEnabled\0"
3795 "Codec\0"
3796 "TimerHz\0"))
3797 return PDMDEV_SET_ERROR(pDevIns, VERR_PDM_DEVINS_UNKNOWN_CFG_VALUES,
3798 N_("Invalid configuration for the AC'97 device"));
3799
3800 /*
3801 * Read config data.
3802 */
3803 int rc = CFGMR3QueryBoolDef(pCfg, "RZEnabled", &pThis->fRZEnabled, true);
3804 if (RT_FAILURE(rc))
3805 return PDMDEV_SET_ERROR(pDevIns, rc,
3806 N_("HDA configuration error: failed to read RCEnabled as boolean"));
3807
3808 char szCodec[20];
3809 rc = CFGMR3QueryStringDef(pCfg, "Codec", &szCodec[0], sizeof(szCodec), "STAC9700");
3810 if (RT_FAILURE(rc))
3811 return PDMDEV_SET_ERROR(pDevIns, VERR_PDM_DEVINS_UNKNOWN_CFG_VALUES,
3812 N_("AC'97 configuration error: Querying \"Codec\" as string failed"));
3813
3814# ifndef VBOX_WITH_AUDIO_AC97_CALLBACKS
3815 uint16_t uTimerHz;
3816 rc = CFGMR3QueryU16Def(pCfg, "TimerHz", &uTimerHz, AC97_TIMER_HZ /* Default value, if not set. */);
3817 if (RT_FAILURE(rc))
3818 return PDMDEV_SET_ERROR(pDevIns, rc,
3819 N_("AC'97 configuration error: failed to read Hertz (Hz) rate as unsigned integer"));
3820# endif
3821
3822 /*
3823 * The AD1980 codec (with corresponding PCI subsystem vendor ID) is whitelisted
3824 * in the Linux kernel; Linux makes no attempt to measure the data rate and assumes
3825 * 48 kHz rate, which is exactly what we need. Same goes for AD1981B.
3826 */
3827 if (!strcmp(szCodec, "STAC9700"))
3828 pThis->uCodecModel = AC97_CODEC_STAC9700;
3829 else if (!strcmp(szCodec, "AD1980"))
3830 pThis->uCodecModel = AC97_CODEC_AD1980;
3831 else if (!strcmp(szCodec, "AD1981B"))
3832 pThis->uCodecModel = AC97_CODEC_AD1981B;
3833 else
3834 return PDMDevHlpVMSetError(pDevIns, VERR_PDM_DEVINS_UNKNOWN_CFG_VALUES, RT_SRC_POS,
3835 N_("AC'97 configuration error: The \"Codec\" value \"%s\" is unsupported"), szCodec);
3836
3837 /*
3838 * Use an own critical section for the device instead of the default
3839 * one provided by PDM. This allows fine-grained locking in combination
3840 * with TM when timer-specific stuff is being called in e.g. the MMIO handlers.
3841 */
3842 rc = PDMDevHlpCritSectInit(pDevIns, &pThis->CritSect, RT_SRC_POS, "AC'97");
3843 AssertRCReturn(rc, rc);
3844
3845 rc = PDMDevHlpSetDeviceCritSect(pDevIns, PDMDevHlpCritSectGetNop(pDevIns));
3846 AssertRCReturn(rc, rc);
3847
3848 /*
3849 * Initialize data (most of it anyway).
3850 */
3851 /* PCI Device */
3852 PCIDevSetVendorId (&pThis->PciDev, 0x8086); /* 00 ro - intel. */ Assert(pThis->PciDev.abConfig[0x00] == 0x86); Assert(pThis->PciDev.abConfig[0x01] == 0x80);
3853 PCIDevSetDeviceId (&pThis->PciDev, 0x2415); /* 02 ro - 82801 / 82801aa(?). */ Assert(pThis->PciDev.abConfig[0x02] == 0x15); Assert(pThis->PciDev.abConfig[0x03] == 0x24);
3854 PCIDevSetCommand (&pThis->PciDev, 0x0000); /* 04 rw,ro - pcicmd. */ Assert(pThis->PciDev.abConfig[0x04] == 0x00); Assert(pThis->PciDev.abConfig[0x05] == 0x00);
3855 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);
3856 PCIDevSetRevisionId (&pThis->PciDev, 0x01); /* 08 ro - rid. */ Assert(pThis->PciDev.abConfig[0x08] == 0x01);
3857 PCIDevSetClassProg (&pThis->PciDev, 0x00); /* 09 ro - pi. */ Assert(pThis->PciDev.abConfig[0x09] == 0x00);
3858 PCIDevSetClassSub (&pThis->PciDev, 0x01); /* 0a ro - scc; 01 == Audio. */ Assert(pThis->PciDev.abConfig[0x0a] == 0x01);
3859 PCIDevSetClassBase (&pThis->PciDev, 0x04); /* 0b ro - bcc; 04 == multimedia.*/Assert(pThis->PciDev.abConfig[0x0b] == 0x04);
3860 PCIDevSetHeaderType (&pThis->PciDev, 0x00); /* 0e ro - headtyp. */ Assert(pThis->PciDev.abConfig[0x0e] == 0x00);
3861 PCIDevSetBaseAddress (&pThis->PciDev, 0, /* 10 rw - nambar - native audio mixer base. */
3862 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);
3863 PCIDevSetBaseAddress (&pThis->PciDev, 1, /* 14 rw - nabmbar - native audio bus mastering. */
3864 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);
3865 PCIDevSetInterruptLine(&pThis->PciDev, 0x00); /* 3c rw. */ Assert(pThis->PciDev.abConfig[0x3c] == 0x00);
3866 PCIDevSetInterruptPin (&pThis->PciDev, 0x01); /* 3d ro - INTA#. */ Assert(pThis->PciDev.abConfig[0x3d] == 0x01);
3867
3868 if (pThis->uCodecModel == AC97_CODEC_AD1980)
3869 {
3870 PCIDevSetSubSystemVendorId(&pThis->PciDev, 0x1028); /* 2c ro - Dell.) */
3871 PCIDevSetSubSystemId (&pThis->PciDev, 0x0177); /* 2e ro. */
3872 }
3873 else if (pThis->uCodecModel == AC97_CODEC_AD1981B)
3874 {
3875 PCIDevSetSubSystemVendorId(&pThis->PciDev, 0x1028); /* 2c ro - Dell.) */
3876 PCIDevSetSubSystemId (&pThis->PciDev, 0x01ad); /* 2e ro. */
3877 }
3878 else
3879 {
3880 PCIDevSetSubSystemVendorId(&pThis->PciDev, 0x8086); /* 2c ro - Intel.) */
3881 PCIDevSetSubSystemId (&pThis->PciDev, 0x0000); /* 2e ro. */
3882 }
3883
3884 /*
3885 * Register the PCI device, it's I/O regions, the timer and the
3886 * saved state item.
3887 */
3888 rc = PDMDevHlpPCIRegister(pDevIns, &pThis->PciDev);
3889 if (RT_FAILURE(rc))
3890 return rc;
3891
3892 rc = PDMDevHlpPCIIORegionRegister(pDevIns, 0, 256, PCI_ADDRESS_SPACE_IO, ichac97R3IOPortMap);
3893 if (RT_FAILURE(rc))
3894 return rc;
3895
3896 rc = PDMDevHlpPCIIORegionRegister(pDevIns, 1, 64, PCI_ADDRESS_SPACE_IO, ichac97R3IOPortMap);
3897 if (RT_FAILURE(rc))
3898 return rc;
3899
3900 rc = PDMDevHlpSSMRegister(pDevIns, AC97_SSM_VERSION, sizeof(*pThis), ichac97R3SaveExec, ichac97R3LoadExec);
3901 if (RT_FAILURE(rc))
3902 return rc;
3903
3904# ifdef VBOX_WITH_AUDIO_AC97_ASYNC_IO
3905 LogRel(("AC97: Asynchronous I/O enabled\n"));
3906# endif
3907
3908 /*
3909 * Attach driver.
3910 */
3911 uint8_t uLUN;
3912 for (uLUN = 0; uLUN < UINT8_MAX; ++uLUN)
3913 {
3914 LogFunc(("Trying to attach driver for LUN #%RU8 ...\n", uLUN));
3915 rc = ichac97R3AttachInternal(pThis, uLUN, 0 /* fFlags */, NULL /* ppDrv */);
3916 if (RT_FAILURE(rc))
3917 {
3918 if (rc == VERR_PDM_NO_ATTACHED_DRIVER)
3919 rc = VINF_SUCCESS;
3920 else if (rc == VERR_AUDIO_BACKEND_INIT_FAILED)
3921 {
3922 ichac97R3ReattachInternal(pThis, NULL /* pDrv */, uLUN, "NullAudio");
3923 PDMDevHlpVMSetRuntimeError(pDevIns, 0 /*fFlags*/, "HostAudioNotResponding",
3924 N_("Host audio backend initialization has failed. Selecting the NULL audio backend "
3925 "with the consequence that no sound is audible"));
3926 /* Attaching to the NULL audio backend will never fail. */
3927 rc = VINF_SUCCESS;
3928 }
3929 break;
3930 }
3931 }
3932
3933 LogFunc(("cLUNs=%RU8, rc=%Rrc\n", uLUN, rc));
3934
3935 if (RT_SUCCESS(rc))
3936 {
3937 rc = AudioMixerCreate("AC'97 Mixer", 0 /* uFlags */, &pThis->pMixer);
3938 if (RT_SUCCESS(rc))
3939 {
3940 rc = AudioMixerCreateSink(pThis->pMixer, "[Recording] Line In", AUDMIXSINKDIR_INPUT, &pThis->pSinkLineIn);
3941 AssertRC(rc);
3942 rc = AudioMixerCreateSink(pThis->pMixer, "[Recording] Microphone In", AUDMIXSINKDIR_INPUT, &pThis->pSinkMicIn);
3943 AssertRC(rc);
3944 rc = AudioMixerCreateSink(pThis->pMixer, "[Playback] PCM Output", AUDMIXSINKDIR_OUTPUT, &pThis->pSinkOut);
3945 AssertRC(rc);
3946 }
3947 }
3948
3949 if (RT_SUCCESS(rc))
3950 {
3951 /*
3952 * Create all hardware streams.
3953 */
3954 rc = ichac97R3StreamCreate(pThis, &pThis->StreamLineIn, AC97SOUNDSOURCE_PI_INDEX);
3955 if (RT_SUCCESS(rc))
3956 {
3957 rc = ichac97R3StreamCreate(pThis, &pThis->StreamMicIn, AC97SOUNDSOURCE_MC_INDEX);
3958 if (RT_SUCCESS(rc))
3959 rc = ichac97R3StreamCreate(pThis, &pThis->StreamOut, AC97SOUNDSOURCE_PO_INDEX);
3960 }
3961
3962# ifdef VBOX_WITH_AUDIO_AC97_ONETIME_INIT
3963 PAC97DRIVER pDrv;
3964 RTListForEach(&pThis->lstDrv, pDrv, AC97DRIVER, Node)
3965 {
3966 /*
3967 * Only primary drivers are critical for the VM to run. Everything else
3968 * might not worth showing an own error message box in the GUI.
3969 */
3970 if (!(pDrv->fFlags & PDMAUDIODRVFLAGS_PRIMARY))
3971 continue;
3972
3973 PPDMIAUDIOCONNECTOR pCon = pDrv->pConnector;
3974 AssertPtr(pCon);
3975
3976 bool fValidLineIn = AudioMixerStreamIsValid(pDrv->LineIn.pMixStrm);
3977 bool fValidMicIn = AudioMixerStreamIsValid(pDrv->MicIn.pMixStrm);
3978 bool fValidOut = AudioMixerStreamIsValid(pDrv->Out.pMixStrm);
3979
3980 if ( !fValidLineIn
3981 && !fValidMicIn
3982 && !fValidOut)
3983 {
3984 LogRel(("AC97: Falling back to NULL backend (no sound audible)\n"));
3985
3986 ichac97R3Reset(pDevIns);
3987 ichac97R3ReattachInternal(pThis, pDrv, pDrv->uLUN, "NullAudio");
3988
3989 PDMDevHlpVMSetRuntimeError(pDevIns, 0 /*fFlags*/, "HostAudioNotResponding",
3990 N_("No audio devices could be opened. Selecting the NULL audio backend "
3991 "with the consequence that no sound is audible"));
3992 }
3993 else
3994 {
3995 bool fWarn = false;
3996
3997 PDMAUDIOBACKENDCFG backendCfg;
3998 int rc2 = pCon->pfnGetConfig(pCon, &backendCfg);
3999 if (RT_SUCCESS(rc2))
4000 {
4001 if (backendCfg.cMaxStreamsIn)
4002 {
4003 /* If the audio backend supports two or more input streams at once,
4004 * warn if one of our two inputs (microphone-in and line-in) failed to initialize. */
4005 if (backendCfg.cMaxStreamsIn >= 2)
4006 fWarn = !fValidLineIn || !fValidMicIn;
4007 /* If the audio backend only supports one input stream at once (e.g. pure ALSA, and
4008 * *not* ALSA via PulseAudio plugin!), only warn if both of our inputs failed to initialize.
4009 * One of the two simply is not in use then. */
4010 else if (backendCfg.cMaxStreamsIn == 1)
4011 fWarn = !fValidLineIn && !fValidMicIn;
4012 /* Don't warn if our backend is not able of supporting any input streams at all. */
4013 }
4014
4015 if ( !fWarn
4016 && backendCfg.cMaxStreamsOut)
4017 {
4018 fWarn = !fValidOut;
4019 }
4020 }
4021 else
4022 {
4023 LogRel(("AC97: Unable to retrieve audio backend configuration for LUN #%RU8, rc=%Rrc\n", pDrv->uLUN, rc2));
4024 fWarn = true;
4025 }
4026
4027 if (fWarn)
4028 {
4029 char szMissingStreams[255] = "";
4030 size_t len = 0;
4031 if (!fValidLineIn)
4032 {
4033 LogRel(("AC97: WARNING: Unable to open PCM line input for LUN #%RU8!\n", pDrv->uLUN));
4034 len = RTStrPrintf(szMissingStreams, sizeof(szMissingStreams), "PCM Input");
4035 }
4036 if (!fValidMicIn)
4037 {
4038 LogRel(("AC97: WARNING: Unable to open PCM microphone input for LUN #%RU8!\n", pDrv->uLUN));
4039 len += RTStrPrintf(szMissingStreams + len,
4040 sizeof(szMissingStreams) - len, len ? ", PCM Microphone" : "PCM Microphone");
4041 }
4042 if (!fValidOut)
4043 {
4044 LogRel(("AC97: WARNING: Unable to open PCM output for LUN #%RU8!\n", pDrv->uLUN));
4045 len += RTStrPrintf(szMissingStreams + len,
4046 sizeof(szMissingStreams) - len, len ? ", PCM Output" : "PCM Output");
4047 }
4048
4049 PDMDevHlpVMSetRuntimeError(pDevIns, 0 /*fFlags*/, "HostAudioNotResponding",
4050 N_("Some AC'97 audio streams (%s) could not be opened. Guest applications generating audio "
4051 "output or depending on audio input may hang. Make sure your host audio device "
4052 "is working properly. Check the logfile for error messages of the audio "
4053 "subsystem"), szMissingStreams);
4054 }
4055 }
4056 }
4057# endif /* VBOX_WITH_AUDIO_AC97_ONETIME_INIT */
4058 }
4059
4060 if (RT_SUCCESS(rc))
4061 ichac97R3Reset(pDevIns);
4062
4063# ifndef VBOX_WITH_AUDIO_AC97_CALLBACKS
4064 if (RT_SUCCESS(rc))
4065 {
4066 /* Create the emulation timer.
4067 *
4068 * Note: Use TMCLOCK_VIRTUAL_SYNC here, as the guest's AC'97 driver
4069 * relies on exact (virtual) DMA timing and uses DMA Position Buffers
4070 * instead of the LPIB registers.
4071 */
4072 rc = PDMDevHlpTMTimerCreate(pDevIns, TMCLOCK_VIRTUAL_SYNC, ichac97R3Timer, pThis,
4073 TMTIMER_FLAGS_NO_CRIT_SECT, "AC'97 Timer", &pThis->pTimerR3);
4074 AssertRCReturn(rc, rc);
4075 pThis->pTimerR0 = TMTimerR0Ptr(pThis->pTimerR3);
4076 pThis->pTimerRC = TMTimerRCPtr(pThis->pTimerR3);
4077
4078 /* Use our own critcal section for the device timer.
4079 * That way we can control more fine-grained when to lock what. */
4080 rc = TMR3TimerSetCritSect(pThis->pTimerR3, &pThis->CritSect);
4081 AssertRCReturn(rc, rc);
4082
4083 pThis->cTimerTicks = TMTimerGetFreq(pThis->pTimerR3) / uTimerHz;
4084 pThis->uTimerTS = TMTimerGet(pThis->pTimerR3);
4085 LogFunc(("Timer ticks=%RU64 (%RU16 Hz)\n", pThis->cTimerTicks, uTimerHz));
4086 }
4087# else /* !VBOX_WITH_AUDIO_AC97_CALLBACKS */
4088 if (RT_SUCCESS(rc))
4089 {
4090 PAC97DRIVER pDrv;
4091 RTListForEach(&pThis->lstDrv, pDrv, AC97DRIVER, Node)
4092 {
4093 /* Only register primary driver.
4094 * The device emulation does the output multiplexing then. */
4095 if (!(pDrv->fFlags & PDMAUDIODRVFLAGS_PRIMARY))
4096 continue;
4097
4098 PDMAUDIOCBRECORD AudioCallbacks[2];
4099
4100 AC97CALLBACKCTX Ctx = { pThis, pDrv };
4101
4102 AudioCallbacks[0].enmType = PDMAUDIOCALLBACKTYPE_INPUT;
4103 AudioCallbacks[0].pfnCallback = ac97CallbackInput;
4104 AudioCallbacks[0].pvCtx = &Ctx;
4105 AudioCallbacks[0].cbCtx = sizeof(AC97CALLBACKCTX);
4106
4107 AudioCallbacks[1].enmType = PDMAUDIOCALLBACKTYPE_OUTPUT;
4108 AudioCallbacks[1].pfnCallback = ac97CallbackOutput;
4109 AudioCallbacks[1].pvCtx = &Ctx;
4110 AudioCallbacks[1].cbCtx = sizeof(AC97CALLBACKCTX);
4111
4112 rc = pDrv->pConnector->pfnRegisterCallbacks(pDrv->pConnector, AudioCallbacks, RT_ELEMENTS(AudioCallbacks));
4113 if (RT_FAILURE(rc))
4114 break;
4115 }
4116 }
4117# endif /* VBOX_WITH_AUDIO_AC97_CALLBACKS */
4118
4119# ifdef VBOX_WITH_STATISTICS
4120 if (RT_SUCCESS(rc))
4121 {
4122 /*
4123 * Register statistics.
4124 */
4125 PDMDevHlpSTAMRegister(pDevIns, &pThis->StatTimer, STAMTYPE_PROFILE, "/Devices/AC97/Timer", STAMUNIT_TICKS_PER_CALL, "Profiling ichac97Timer.");
4126 PDMDevHlpSTAMRegister(pDevIns, &pThis->StatIn, STAMTYPE_PROFILE, "/Devices/AC97/Input", STAMUNIT_TICKS_PER_CALL, "Profiling input.");
4127 PDMDevHlpSTAMRegister(pDevIns, &pThis->StatOut, STAMTYPE_PROFILE, "/Devices/AC97/Output", STAMUNIT_TICKS_PER_CALL, "Profiling output.");
4128 PDMDevHlpSTAMRegister(pDevIns, &pThis->StatBytesRead, STAMTYPE_COUNTER, "/Devices/AC97/BytesRead" , STAMUNIT_BYTES, "Bytes read from AC97 emulation.");
4129 PDMDevHlpSTAMRegister(pDevIns, &pThis->StatBytesWritten, STAMTYPE_COUNTER, "/Devices/AC97/BytesWritten", STAMUNIT_BYTES, "Bytes written to AC97 emulation.");
4130 }
4131# endif
4132
4133# ifdef VBOX_AUDIO_DEBUG_DUMP_PCM_DATA
4134 RTFileDelete(VBOX_AUDIO_DEBUG_DUMP_PCM_DATA_PATH "ac97DMARead.pcm");
4135 RTFileDelete(VBOX_AUDIO_DEBUG_DUMP_PCM_DATA_PATH "ac97DMAWrite.pcm");
4136 RTFileDelete(VBOX_AUDIO_DEBUG_DUMP_PCM_DATA_PATH "ac97StreamRead.pcm");
4137 RTFileDelete(VBOX_AUDIO_DEBUG_DUMP_PCM_DATA_PATH "ac97StreamWrite.pcm");
4138# endif
4139
4140 LogFlowFuncLeaveRC(rc);
4141 return rc;
4142}
4143
4144/**
4145 * The device registration structure.
4146 */
4147const PDMDEVREG g_DeviceICHAC97 =
4148{
4149 /* u32Version */
4150 PDM_DEVREG_VERSION,
4151 /* szName */
4152 "ichac97",
4153 /* szRCMod */
4154 "VBoxDDRC.rc",
4155 /* szR0Mod */
4156 "VBoxDDR0.r0",
4157 /* pszDescription */
4158 "ICH AC'97 Audio Controller",
4159 /* fFlags */
4160 PDM_DEVREG_FLAGS_DEFAULT_BITS | PDM_DEVREG_FLAGS_RC | PDM_DEVREG_FLAGS_R0,
4161 /* fClass */
4162 PDM_DEVREG_CLASS_AUDIO,
4163 /* cMaxInstances */
4164 1,
4165 /* cbInstance */
4166 sizeof(AC97STATE),
4167 /* pfnConstruct */
4168 ichac97R3Construct,
4169 /* pfnDestruct */
4170 ichac97R3Destruct,
4171 /* pfnRelocate */
4172 ichac97R3Relocate,
4173 /* pfnMemSetup */
4174 NULL,
4175 /* pfnPowerOn */
4176 NULL,
4177 /* pfnReset */
4178 ichac97R3Reset,
4179 /* pfnSuspend */
4180 NULL,
4181 /* pfnResume */
4182 NULL,
4183 /* pfnAttach */
4184 ichac97R3Attach,
4185 /* pfnDetach */
4186 ichac97R3Detach,
4187 /* pfnQueryInterface. */
4188 NULL,
4189 /* pfnInitComplete */
4190 NULL,
4191 /* pfnPowerOff */
4192 ichac97R3PowerOff,
4193 /* pfnSoftReset */
4194 NULL,
4195 /* u32VersionEnd */
4196 PDM_DEVREG_VERSION
4197};
4198
4199#endif /* !IN_RING3 */
4200#endif /* !VBOX_DEVICE_STRUCT_TESTCASE */
4201
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