VirtualBox

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

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

Audio/AC97: More code needed for EACS VRA / VRM handling.

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

© 2025 Oracle Support Privacy / Do Not Sell My Info Terms of Use Trademark Policy Automated Access Etiquette