VirtualBox

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

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

Build fix.

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