VirtualBox

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

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

Audio: Changed cBits -> cBytes of PDMAUDIOPCMPROPS to avoid some unnecessary calculations (light optimization).

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