VirtualBox

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

Last change on this file since 71737 was 71737, checked in by vboxsync, 7 years ago

DevAC97: tiny cleanups

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