VirtualBox

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

最後變更 在這個檔案從80824是 80733,由 vboxsync 提交於 6 年 前

Audio/AC97: Try to relax (EACS VRA / VRM) capabilities / checks to make it more compatible.

  • 屬性 svn:eol-style 設為 native
  • 屬性 svn:keywords 設為 Author Date Id Revision
檔案大小: 164.3 KB
 
1/* $Id: DevIchAc97.cpp 80733 2019-09-11 14:10:42Z 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.alldomusa.eu.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
2502 const PDMAUDIORECSOURCE ars = ichac97R3IdxToRecSource(rs);
2503 const PDMAUDIORECSOURCE als = ichac97R3IdxToRecSource(ls);
2504
2505 rs = ichac97R3RecSourceToIdx(ars);
2506 ls = ichac97R3RecSourceToIdx(als);
2507
2508 LogRel(("AC97: Record select to left=%s, right=%s\n", DrvAudioHlpRecSrcToStr(ars), DrvAudioHlpRecSrcToStr(als)));
2509
2510 ichac97MixerSet(pThis, AC97_Record_Select, rs | (ls << 8));
2511}
2512
2513/**
2514 * Resets the AC'97 mixer.
2515 *
2516 * @returns IPRT status code.
2517 * @param pThis AC'97 state.
2518 */
2519static int ichac97R3MixerReset(PAC97STATE pThis)
2520{
2521 AssertPtrReturn(pThis, VERR_INVALID_PARAMETER);
2522
2523 LogFlowFuncEnter();
2524
2525 RT_ZERO(pThis->mixer_data);
2526
2527 /* Note: Make sure to reset all registers first before bailing out on error. */
2528
2529 ichac97MixerSet(pThis, AC97_Reset , 0x0000); /* 6940 */
2530 ichac97MixerSet(pThis, AC97_Master_Volume_Mono_Mute , 0x8000);
2531 ichac97MixerSet(pThis, AC97_PC_BEEP_Volume_Mute , 0x0000);
2532
2533 ichac97MixerSet(pThis, AC97_Phone_Volume_Mute , 0x8008);
2534 ichac97MixerSet(pThis, AC97_Mic_Volume_Mute , 0x8008);
2535 ichac97MixerSet(pThis, AC97_CD_Volume_Mute , 0x8808);
2536 ichac97MixerSet(pThis, AC97_Aux_Volume_Mute , 0x8808);
2537 ichac97MixerSet(pThis, AC97_Record_Gain_Mic_Mute , 0x8000);
2538 ichac97MixerSet(pThis, AC97_General_Purpose , 0x0000);
2539 ichac97MixerSet(pThis, AC97_3D_Control , 0x0000);
2540 ichac97MixerSet(pThis, AC97_Powerdown_Ctrl_Stat , 0x000f);
2541
2542 /* Configure Extended Audio ID (EAID) + Control & Status (EACS) registers. */
2543 const uint16_t fEAID = AC97_EAID_REV1 | AC97_EACS_VRA | AC97_EACS_VRM; /* Our hardware is AC'97 rev2.3 compliant. */
2544 const uint16_t fEACS = AC97_EACS_VRA | AC97_EACS_VRM; /* Variable Rate PCM Audio (VRA) + Mic-In (VRM) capable. */
2545
2546 LogRel(("AC97: Mixer reset (EAID=0x%x, EACS=0x%x)\n", fEAID, fEACS));
2547
2548 ichac97MixerSet(pThis, AC97_Extended_Audio_ID, fEAID);
2549 ichac97MixerSet(pThis, AC97_Extended_Audio_Ctrl_Stat, fEACS);
2550 ichac97MixerSet(pThis, AC97_PCM_Front_DAC_Rate , 0xbb80 /* 48000 Hz by default */);
2551 ichac97MixerSet(pThis, AC97_PCM_Surround_DAC_Rate , 0xbb80 /* 48000 Hz by default */);
2552 ichac97MixerSet(pThis, AC97_PCM_LFE_DAC_Rate , 0xbb80 /* 48000 Hz by default */);
2553 ichac97MixerSet(pThis, AC97_PCM_LR_ADC_Rate , 0xbb80 /* 48000 Hz by default */);
2554 ichac97MixerSet(pThis, AC97_MIC_ADC_Rate , 0xbb80 /* 48000 Hz by default */);
2555
2556 if (pThis->uCodecModel == AC97_CODEC_AD1980)
2557 {
2558 /* Analog Devices 1980 (AD1980) */
2559 ichac97MixerSet(pThis, AC97_Reset , 0x0010); /* Headphones. */
2560 ichac97MixerSet(pThis, AC97_Vendor_ID1 , 0x4144);
2561 ichac97MixerSet(pThis, AC97_Vendor_ID2 , 0x5370);
2562 ichac97MixerSet(pThis, AC97_Headphone_Volume_Mute , 0x8000);
2563 }
2564 else if (pThis->uCodecModel == AC97_CODEC_AD1981B)
2565 {
2566 /* Analog Devices 1981B (AD1981B) */
2567 ichac97MixerSet(pThis, AC97_Vendor_ID1 , 0x4144);
2568 ichac97MixerSet(pThis, AC97_Vendor_ID2 , 0x5374);
2569 }
2570 else
2571 {
2572 /* Sigmatel 9700 (STAC9700) */
2573 ichac97MixerSet(pThis, AC97_Vendor_ID1 , 0x8384);
2574 ichac97MixerSet(pThis, AC97_Vendor_ID2 , 0x7600); /* 7608 */
2575 }
2576 ichac97R3MixerRecordSelect(pThis, 0);
2577
2578 /* The default value is 8000h, which corresponds to 0 dB attenuation with mute on. */
2579 ichac97R3MixerSetVolume(pThis, AC97_Master_Volume_Mute, PDMAUDIOMIXERCTL_VOLUME_MASTER, 0x8000);
2580
2581 /* The default value for stereo registers is 8808h, which corresponds to 0 dB gain with mute on.*/
2582 ichac97R3MixerSetVolume(pThis, AC97_PCM_Out_Volume_Mute, PDMAUDIOMIXERCTL_FRONT, 0x8808);
2583 ichac97R3MixerSetVolume(pThis, AC97_Line_In_Volume_Mute, PDMAUDIOMIXERCTL_LINE_IN, 0x8808);
2584 ichac97R3MixerSetVolume(pThis, AC97_Mic_Volume_Mute, PDMAUDIOMIXERCTL_MIC_IN, 0x8008);
2585
2586 /* The default for record controls is 0 dB gain with mute on. */
2587 ichac97R3MixerSetGain(pThis, AC97_Record_Gain_Mute, PDMAUDIOMIXERCTL_LINE_IN, 0x8000);
2588 ichac97R3MixerSetGain(pThis, AC97_Record_Gain_Mic_Mute, PDMAUDIOMIXERCTL_MIC_IN, 0x8000);
2589
2590 return VINF_SUCCESS;
2591}
2592
2593# if 0 /* Unused */
2594static void ichac97R3WriteBUP(PAC97STATE pThis, uint32_t cbElapsed)
2595{
2596 LogFlowFunc(("cbElapsed=%RU32\n", cbElapsed));
2597
2598 if (!(pThis->bup_flag & BUP_SET))
2599 {
2600 if (pThis->bup_flag & BUP_LAST)
2601 {
2602 unsigned int i;
2603 uint32_t *p = (uint32_t*)pThis->silence;
2604 for (i = 0; i < sizeof(pThis->silence) / 4; i++) /** @todo r=andy Assumes 16-bit samples, stereo. */
2605 *p++ = pThis->last_samp;
2606 }
2607 else
2608 RT_ZERO(pThis->silence);
2609
2610 pThis->bup_flag |= BUP_SET;
2611 }
2612
2613 while (cbElapsed)
2614 {
2615 uint32_t cbToWrite = RT_MIN(cbElapsed, (uint32_t)sizeof(pThis->silence));
2616 uint32_t cbWrittenToStream;
2617
2618 int rc2 = AudioMixerSinkWrite(pThis->pSinkOut, AUDMIXOP_COPY,
2619 pThis->silence, cbToWrite, &cbWrittenToStream);
2620 if (RT_SUCCESS(rc2))
2621 {
2622 if (cbWrittenToStream < cbToWrite) /* Lagging behind? */
2623 LogFlowFunc(("Warning: Only written %RU32 / %RU32 bytes, expect lags\n", cbWrittenToStream, cbToWrite));
2624 }
2625
2626 /* Always report all data as being written;
2627 * backends who were not able to catch up have to deal with it themselves. */
2628 Assert(cbElapsed >= cbToWrite);
2629 cbElapsed -= cbToWrite;
2630 }
2631}
2632# endif /* Unused */
2633
2634/**
2635 * Timer callback which handles the audio data transfers on a periodic basis.
2636 *
2637 * @param pDevIns Device instance.
2638 * @param pTimer Timer which was used when calling this.
2639 * @param pvUser User argument as PAC97STATE.
2640 */
2641static DECLCALLBACK(void) ichac97R3Timer(PPDMDEVINS pDevIns, PTMTIMER pTimer, void *pvUser)
2642{
2643 RT_NOREF(pDevIns, pTimer);
2644
2645 PAC97STREAM pStream = (PAC97STREAM)pvUser;
2646 AssertPtr(pStream);
2647
2648 PAC97STATE pThis = pStream->pAC97State;
2649 AssertPtr(pThis);
2650
2651 STAM_PROFILE_START(&pThis->StatTimer, a);
2652
2653 DEVAC97_LOCK_BOTH_RETURN_VOID(pThis, pStream->u8SD);
2654
2655 ichac97R3StreamUpdate(pThis, pStream, true /* fInTimer */);
2656
2657 PAUDMIXSINK pSink = ichac97R3IndexToSink(pThis, pStream->u8SD);
2658
2659 bool fSinkActive = false;
2660 if (pSink)
2661 fSinkActive = AudioMixerSinkIsActive(pSink);
2662
2663 if (fSinkActive)
2664 {
2665 ichac97R3StreamTransferUpdate(pThis, pStream, pStream->Regs.picb << 1); /** @todo r=andy Assumes 16-bit samples. */
2666
2667 ichac97TimerSet(pThis,pStream,
2668 TMTimerGet((pThis)->DEVAC97_CTX_SUFF_SD(pTimer, pStream->u8SD)) + pStream->State.cTransferTicks,
2669 false /* fForce */);
2670 }
2671
2672 DEVAC97_UNLOCK_BOTH(pThis, pStream->u8SD);
2673
2674 STAM_PROFILE_STOP(&pThis->StatTimer, a);
2675}
2676#endif /* IN_RING3 */
2677
2678/**
2679 * Sets the virtual device timer to a new expiration time.
2680 *
2681 * @returns Whether the new expiration time was set or not.
2682 * @param pThis AC'97 state.
2683 * @param pStream AC'97 stream to set timer for.
2684 * @param tsExpire New (virtual) expiration time to set.
2685 * @param fForce Whether to force setting the expiration time or not.
2686 *
2687 * @remark This function takes all active AC'97 streams and their
2688 * current timing into account. This is needed to make sure
2689 * that all streams can match their needed timing.
2690 *
2691 * To achieve this, the earliest (lowest) timestamp of all
2692 * active streams found will be used for the next scheduling slot.
2693 *
2694 * Forcing a new expiration time will override the above mechanism.
2695 */
2696bool ichac97TimerSet(PAC97STATE pThis, PAC97STREAM pStream, uint64_t tsExpire, bool fForce)
2697{
2698 AssertPtrReturn(pThis, false);
2699 AssertPtrReturn(pStream, false);
2700
2701 RT_NOREF(fForce);
2702
2703 uint64_t tsExpireMin = tsExpire;
2704
2705 AssertPtr((pThis)->DEVAC97_CTX_SUFF_SD(pTimer, pStream->u8SD));
2706
2707 const uint64_t tsNow = TMTimerGet((pThis)->DEVAC97_CTX_SUFF_SD(pTimer, pStream->u8SD));
2708
2709 /* Make sure to not go backwards in time, as this will assert in TMTimerSet(). */
2710 if (tsExpireMin < tsNow)
2711 tsExpireMin = tsNow;
2712
2713 int rc = TMTimerSet((pThis)->DEVAC97_CTX_SUFF_SD(pTimer, pStream->u8SD), tsExpireMin);
2714 AssertRC(rc);
2715
2716 return RT_SUCCESS(rc);
2717}
2718
2719#ifdef IN_RING3
2720
2721/**
2722 * Transfers data of an AC'97 stream according to its usage (input / output).
2723 *
2724 * For an SDO (output) stream this means reading DMA data from the device to
2725 * the AC'97 stream's internal FIFO buffer.
2726 *
2727 * For an SDI (input) stream this is reading audio data from the AC'97 stream's
2728 * internal FIFO buffer and writing it as DMA data to the device.
2729 *
2730 * @returns IPRT status code.
2731 * @param pThis AC'97 state.
2732 * @param pStream AC'97 stream to update.
2733 * @param cbToProcessMax Maximum of data (in bytes) to process.
2734 */
2735static int ichac97R3StreamTransfer(PAC97STATE pThis, PAC97STREAM pStream, uint32_t cbToProcessMax)
2736{
2737 AssertPtrReturn(pThis, VERR_INVALID_POINTER);
2738 AssertPtrReturn(pStream, VERR_INVALID_POINTER);
2739
2740 if (!cbToProcessMax)
2741 return VINF_SUCCESS;
2742
2743#ifdef VBOX_STRICT
2744 const unsigned cbFrame = DrvAudioHlpPCMPropsBytesPerFrame(&pStream->State.Cfg.Props);
2745#endif
2746
2747 /* Make sure to only process an integer number of audio frames. */
2748 Assert(cbToProcessMax % cbFrame == 0);
2749
2750 ichac97R3StreamLock(pStream);
2751
2752 PAC97BMREGS pRegs = &pStream->Regs;
2753
2754 if (pRegs->sr & AC97_SR_DCH) /* Controller halted? */
2755 {
2756 if (pRegs->cr & AC97_CR_RPBM) /* Bus master operation starts. */
2757 {
2758 switch (pStream->u8SD)
2759 {
2760 case AC97SOUNDSOURCE_PO_INDEX:
2761 /*ichac97R3WriteBUP(pThis, cbToProcess);*/
2762 break;
2763
2764 default:
2765 break;
2766 }
2767 }
2768
2769 ichac97R3StreamUnlock(pStream);
2770 return VINF_SUCCESS;
2771 }
2772
2773 /* BCIS flag still set? Skip iteration. */
2774 if (pRegs->sr & AC97_SR_BCIS)
2775 {
2776 Log3Func(("[SD%RU8] BCIS set\n", pStream->u8SD));
2777
2778 ichac97R3StreamUnlock(pStream);
2779 return VINF_SUCCESS;
2780 }
2781
2782 uint32_t cbLeft = RT_MIN((uint32_t)(pRegs->picb << 1), cbToProcessMax); /** @todo r=andy Assumes 16bit samples. */
2783 uint32_t cbProcessedTotal = 0;
2784
2785 PRTCIRCBUF pCircBuf = pStream->State.pCircBuf;
2786 AssertPtr(pCircBuf);
2787
2788 int rc = VINF_SUCCESS;
2789
2790 Log3Func(("[SD%RU8] cbToProcessMax=%RU32, cbLeft=%RU32\n", pStream->u8SD, cbToProcessMax, cbLeft));
2791
2792 while (cbLeft)
2793 {
2794 if (!pRegs->picb) /* Got a new buffer descriptor, that is, the position is 0? */
2795 {
2796 Log3Func(("Fresh buffer descriptor %RU8 is empty, addr=%#x, len=%#x, skipping\n",
2797 pRegs->civ, pRegs->bd.addr, pRegs->bd.ctl_len));
2798 if (pRegs->civ == pRegs->lvi)
2799 {
2800 pRegs->sr |= AC97_SR_DCH; /** @todo r=andy Also set CELV? */
2801 pThis->bup_flag = 0;
2802
2803 rc = VINF_EOF;
2804 break;
2805 }
2806
2807 pRegs->sr &= ~AC97_SR_CELV;
2808 pRegs->civ = pRegs->piv;
2809 pRegs->piv = (pRegs->piv + 1) % AC97_MAX_BDLE;
2810
2811 ichac97R3StreamFetchBDLE(pThis, pStream);
2812 continue;
2813 }
2814
2815 uint32_t cbChunk = cbLeft;
2816
2817 switch (pStream->u8SD)
2818 {
2819 case AC97SOUNDSOURCE_PO_INDEX: /* Output */
2820 {
2821 void *pvDst;
2822 size_t cbDst;
2823
2824 RTCircBufAcquireWriteBlock(pCircBuf, cbChunk, &pvDst, &cbDst);
2825
2826 if (cbDst)
2827 {
2828 int rc2 = PDMDevHlpPhysRead(pThis->CTX_SUFF(pDevIns), pRegs->bd.addr, (uint8_t *)pvDst, cbDst);
2829 AssertRC(rc2);
2830
2831 if (pStream->Dbg.Runtime.fEnabled)
2832 DrvAudioHlpFileWrite(pStream->Dbg.Runtime.pFileDMA, pvDst, cbDst, 0 /* fFlags */);
2833 }
2834
2835 RTCircBufReleaseWriteBlock(pCircBuf, cbDst);
2836
2837 cbChunk = (uint32_t)cbDst; /* Update the current chunk size to what really has been written. */
2838 break;
2839 }
2840
2841 case AC97SOUNDSOURCE_PI_INDEX: /* Input */
2842 case AC97SOUNDSOURCE_MC_INDEX: /* Input */
2843 {
2844 void *pvSrc;
2845 size_t cbSrc;
2846
2847 RTCircBufAcquireReadBlock(pCircBuf, cbChunk, &pvSrc, &cbSrc);
2848
2849 if (cbSrc)
2850 {
2851/** @todo r=bird: Just curious, DevHDA uses PDMDevHlpPCIPhysWrite here. So,
2852 * is AC97 not subject to PCI busmaster enable/disable? */
2853 int rc2 = PDMDevHlpPhysWrite(pThis->CTX_SUFF(pDevIns), pRegs->bd.addr, (uint8_t *)pvSrc, cbSrc);
2854 AssertRC(rc2);
2855
2856 if (pStream->Dbg.Runtime.fEnabled)
2857 DrvAudioHlpFileWrite(pStream->Dbg.Runtime.pFileDMA, pvSrc, cbSrc, 0 /* fFlags */);
2858 }
2859
2860 RTCircBufReleaseReadBlock(pCircBuf, cbSrc);
2861
2862 cbChunk = (uint32_t)cbSrc; /* Update the current chunk size to what really has been read. */
2863 break;
2864 }
2865
2866 default:
2867 AssertMsgFailed(("Stream #%RU8 not supported\n", pStream->u8SD));
2868 rc = VERR_NOT_SUPPORTED;
2869 break;
2870 }
2871
2872 if (RT_FAILURE(rc))
2873 break;
2874
2875 if (cbChunk)
2876 {
2877 cbProcessedTotal += cbChunk;
2878 Assert(cbProcessedTotal <= cbToProcessMax);
2879 Assert(cbLeft >= cbChunk);
2880 cbLeft -= cbChunk;
2881 Assert((cbChunk & 1) == 0); /* Else the following shift won't work */
2882
2883 pRegs->picb -= (cbChunk >> 1); /** @todo r=andy Assumes 16bit samples. */
2884 pRegs->bd.addr += cbChunk;
2885 }
2886
2887 LogFlowFunc(("[SD%RU8] cbChunk=%RU32, cbLeft=%RU32, cbTotal=%RU32, rc=%Rrc\n",
2888 pStream->u8SD, cbChunk, cbLeft, cbProcessedTotal, rc));
2889
2890 if (!pRegs->picb)
2891 {
2892 uint32_t new_sr = pRegs->sr & ~AC97_SR_CELV;
2893
2894 if (pRegs->bd.ctl_len & AC97_BD_IOC)
2895 {
2896 new_sr |= AC97_SR_BCIS;
2897 }
2898
2899 if (pRegs->civ == pRegs->lvi)
2900 {
2901 /* Did we run out of data? */
2902 LogFunc(("Underrun CIV (%RU8) == LVI (%RU8)\n", pRegs->civ, pRegs->lvi));
2903
2904 new_sr |= AC97_SR_LVBCI | AC97_SR_DCH | AC97_SR_CELV;
2905 pThis->bup_flag = (pRegs->bd.ctl_len & AC97_BD_BUP) ? BUP_LAST : 0;
2906
2907 rc = VINF_EOF;
2908 }
2909 else
2910 {
2911 pRegs->civ = pRegs->piv;
2912 pRegs->piv = (pRegs->piv + 1) % AC97_MAX_BDLE;
2913 ichac97R3StreamFetchBDLE(pThis, pStream);
2914 }
2915
2916 ichac97StreamUpdateSR(pThis, pStream, new_sr);
2917 }
2918
2919 if (/* All data processed? */
2920 rc == VINF_EOF
2921 /* ... or an error occurred? */
2922 || RT_FAILURE(rc))
2923 {
2924 break;
2925 }
2926 }
2927
2928 ichac97R3StreamUnlock(pStream);
2929
2930 LogFlowFuncLeaveRC(rc);
2931 return rc;
2932}
2933
2934#endif /* IN_RING3 */
2935
2936
2937/**
2938 * Port I/O Handler for IN operations.
2939 *
2940 * @returns VINF_SUCCESS or VINF_EM_*.
2941 * @returns VERR_IOM_IOPORT_UNUSED if the port is really unused and a ~0 value should be returned.
2942 *
2943 * @param pDevIns The device instance.
2944 * @param pvUser User argument.
2945 * @param uPort Port number used for the IN operation.
2946 * @param pu32Val Where to store the result. This is always a 32-bit
2947 * variable regardless of what @a cbVal might say.
2948 * @param cbVal Number of bytes read.
2949 */
2950PDMBOTHCBDECL(int) ichac97IOPortNABMRead(PPDMDEVINS pDevIns, void *pvUser, RTIOPORT uPort, uint32_t *pu32Val, unsigned cbVal)
2951{
2952 PAC97STATE pThis = PDMINS_2_DATA(pDevIns, PAC97STATE);
2953 RT_NOREF(pvUser);
2954
2955 DEVAC97_LOCK_RETURN(pThis, VINF_IOM_R3_IOPORT_READ);
2956
2957 /* Get the index of the NABMBAR port. */
2958 const uint32_t uPortIdx = uPort - pThis->IOPortBase[1];
2959
2960 PAC97STREAM pStream = NULL;
2961 PAC97BMREGS pRegs = NULL;
2962
2963 if (AC97_PORT2IDX(uPortIdx) < AC97_MAX_STREAMS)
2964 {
2965 pStream = &pThis->aStreams[AC97_PORT2IDX(uPortIdx)];
2966 AssertPtr(pStream);
2967 pRegs = &pStream->Regs;
2968 }
2969
2970 int rc = VINF_SUCCESS;
2971
2972 switch (cbVal)
2973 {
2974 case 1:
2975 {
2976 switch (uPortIdx)
2977 {
2978 case AC97_CAS:
2979 /* Codec Access Semaphore Register */
2980 Log3Func(("CAS %d\n", pThis->cas));
2981 *pu32Val = pThis->cas;
2982 pThis->cas = 1;
2983 break;
2984 case PI_CIV:
2985 case PO_CIV:
2986 case MC_CIV:
2987 /* Current Index Value Register */
2988 *pu32Val = pRegs->civ;
2989 Log3Func(("CIV[%d] -> %#x\n", AC97_PORT2IDX(uPortIdx), *pu32Val));
2990 break;
2991 case PI_LVI:
2992 case PO_LVI:
2993 case MC_LVI:
2994 /* Last Valid Index Register */
2995 *pu32Val = pRegs->lvi;
2996 Log3Func(("LVI[%d] -> %#x\n", AC97_PORT2IDX(uPortIdx), *pu32Val));
2997 break;
2998 case PI_PIV:
2999 case PO_PIV:
3000 case MC_PIV:
3001 /* Prefetched Index Value Register */
3002 *pu32Val = pRegs->piv;
3003 Log3Func(("PIV[%d] -> %#x\n", AC97_PORT2IDX(uPortIdx), *pu32Val));
3004 break;
3005 case PI_CR:
3006 case PO_CR:
3007 case MC_CR:
3008 /* Control Register */
3009 *pu32Val = pRegs->cr;
3010 Log3Func(("CR[%d] -> %#x\n", AC97_PORT2IDX(uPortIdx), *pu32Val));
3011 break;
3012 case PI_SR:
3013 case PO_SR:
3014 case MC_SR:
3015 /* Status Register (lower part) */
3016 *pu32Val = RT_LO_U8(pRegs->sr);
3017 Log3Func(("SRb[%d] -> %#x\n", AC97_PORT2IDX(uPortIdx), *pu32Val));
3018 break;
3019 default:
3020 *pu32Val = UINT32_MAX;
3021 LogFunc(("U nabm readb %#x -> %#x\n", uPort, *pu32Val));
3022 break;
3023 }
3024 break;
3025 }
3026
3027 case 2:
3028 {
3029 switch (uPortIdx)
3030 {
3031 case PI_SR:
3032 case PO_SR:
3033 case MC_SR:
3034 /* Status Register */
3035 *pu32Val = pRegs->sr;
3036 Log3Func(("SR[%d] -> %#x\n", AC97_PORT2IDX(uPortIdx), *pu32Val));
3037 break;
3038 case PI_PICB:
3039 case PO_PICB:
3040 case MC_PICB:
3041 /* Position in Current Buffer */
3042 *pu32Val = pRegs->picb;
3043 Log3Func(("PICB[%d] -> %#x\n", AC97_PORT2IDX(uPortIdx), *pu32Val));
3044 break;
3045 default:
3046 *pu32Val = UINT32_MAX;
3047 LogFunc(("U nabm readw %#x -> %#x\n", uPort, *pu32Val));
3048 break;
3049 }
3050 break;
3051 }
3052
3053 case 4:
3054 {
3055 switch (uPortIdx)
3056 {
3057 case PI_BDBAR:
3058 case PO_BDBAR:
3059 case MC_BDBAR:
3060 /* Buffer Descriptor Base Address Register */
3061 *pu32Val = pRegs->bdbar;
3062 Log3Func(("BMADDR[%d] -> %#x\n", AC97_PORT2IDX(uPortIdx), *pu32Val));
3063 break;
3064 case PI_CIV:
3065 case PO_CIV:
3066 case MC_CIV:
3067 /* 32-bit access: Current Index Value Register +
3068 * Last Valid Index Register +
3069 * Status Register */
3070 *pu32Val = pRegs->civ | (pRegs->lvi << 8) | (pRegs->sr << 16); /** @todo r=andy Use RT_MAKE_U32_FROM_U8. */
3071 Log3Func(("CIV LVI SR[%d] -> %#x, %#x, %#x\n",
3072 AC97_PORT2IDX(uPortIdx), pRegs->civ, pRegs->lvi, pRegs->sr));
3073 break;
3074 case PI_PICB:
3075 case PO_PICB:
3076 case MC_PICB:
3077 /* 32-bit access: Position in Current Buffer Register +
3078 * Prefetched Index Value Register +
3079 * Control Register */
3080 *pu32Val = pRegs->picb | (pRegs->piv << 16) | (pRegs->cr << 24); /** @todo r=andy Use RT_MAKE_U32_FROM_U8. */
3081 Log3Func(("PICB PIV CR[%d] -> %#x %#x %#x %#x\n",
3082 AC97_PORT2IDX(uPortIdx), *pu32Val, pRegs->picb, pRegs->piv, pRegs->cr));
3083 break;
3084 case AC97_GLOB_CNT:
3085 /* Global Control */
3086 *pu32Val = pThis->glob_cnt;
3087 Log3Func(("glob_cnt -> %#x\n", *pu32Val));
3088 break;
3089 case AC97_GLOB_STA:
3090 /* Global Status */
3091 *pu32Val = pThis->glob_sta | AC97_GS_S0CR;
3092 Log3Func(("glob_sta -> %#x\n", *pu32Val));
3093 break;
3094 default:
3095 *pu32Val = UINT32_MAX;
3096 LogFunc(("U nabm readl %#x -> %#x\n", uPort, *pu32Val));
3097 break;
3098 }
3099 break;
3100 }
3101
3102 default:
3103 {
3104 AssertFailed();
3105 rc = VERR_IOM_IOPORT_UNUSED;
3106 }
3107 }
3108
3109 DEVAC97_UNLOCK(pThis);
3110
3111 return rc;
3112}
3113
3114/**
3115 * Port I/O Handler for OUT operations.
3116 *
3117 * @returns VINF_SUCCESS or VINF_EM_*.
3118 *
3119 * @param pDevIns The device instance.
3120 * @param pvUser User argument.
3121 * @param uPort Port number used for the OUT operation.
3122 * @param u32Val The value to output.
3123 * @param cbVal The value size in bytes.
3124 */
3125PDMBOTHCBDECL(int) ichac97IOPortNABMWrite(PPDMDEVINS pDevIns, void *pvUser, RTIOPORT uPort, uint32_t u32Val, unsigned cbVal)
3126{
3127 PAC97STATE pThis = PDMINS_2_DATA(pDevIns, PAC97STATE);
3128 RT_NOREF(pvUser);
3129
3130 /* Get the index of the NABMBAR register. */
3131 const uint32_t uPortIdx = uPort - pThis->IOPortBase[1];
3132
3133 PAC97STREAM pStream = NULL;
3134 PAC97BMREGS pRegs = NULL;
3135
3136 if (AC97_PORT2IDX(uPortIdx) < AC97_MAX_STREAMS)
3137 {
3138 pStream = &pThis->aStreams[AC97_PORT2IDX(uPortIdx)];
3139 AssertPtr(pStream);
3140 pRegs = &pStream->Regs;
3141
3142 DEVAC97_LOCK_BOTH_RETURN(pThis, pStream->u8SD, VINF_IOM_R3_IOPORT_WRITE);
3143 }
3144
3145 int rc = VINF_SUCCESS;
3146 switch (cbVal)
3147 {
3148 case 1:
3149 {
3150 switch (uPortIdx)
3151 {
3152 /*
3153 * Last Valid Index.
3154 */
3155 case PI_LVI:
3156 case PO_LVI:
3157 case MC_LVI:
3158 {
3159 AssertPtr(pStream);
3160 AssertPtr(pRegs);
3161 if ( (pRegs->cr & AC97_CR_RPBM)
3162 && (pRegs->sr & AC97_SR_DCH))
3163 {
3164#ifdef IN_RING3
3165 pRegs->sr &= ~(AC97_SR_DCH | AC97_SR_CELV);
3166 pRegs->civ = pRegs->piv;
3167 pRegs->piv = (pRegs->piv + 1) % AC97_MAX_BDLE;
3168#else
3169 rc = VINF_IOM_R3_IOPORT_WRITE;
3170#endif
3171 }
3172 pRegs->lvi = u32Val % AC97_MAX_BDLE;
3173 Log3Func(("[SD%RU8] LVI <- %#x\n", pStream->u8SD, u32Val));
3174 break;
3175 }
3176
3177 /*
3178 * Control Registers.
3179 */
3180 case PI_CR:
3181 case PO_CR:
3182 case MC_CR:
3183 {
3184 AssertPtr(pStream);
3185 AssertPtr(pRegs);
3186#ifdef IN_RING3
3187 Log3Func(("[SD%RU8] CR <- %#x (cr %#x)\n", pStream->u8SD, u32Val, pRegs->cr));
3188 if (u32Val & AC97_CR_RR) /* Busmaster reset. */
3189 {
3190 Log3Func(("[SD%RU8] Reset\n", pStream->u8SD));
3191
3192 /* Make sure that Run/Pause Bus Master bit (RPBM) is cleared (0). */
3193 Assert((pRegs->cr & AC97_CR_RPBM) == 0);
3194
3195 ichac97R3StreamEnable(pThis, pStream, false /* fEnable */);
3196 ichac97R3StreamReset(pThis, pStream);
3197
3198 ichac97StreamUpdateSR(pThis, pStream, AC97_SR_DCH); /** @todo Do we need to do that? */
3199 }
3200 else
3201 {
3202 pRegs->cr = u32Val & AC97_CR_VALID_MASK;
3203
3204 if (!(pRegs->cr & AC97_CR_RPBM))
3205 {
3206 Log3Func(("[SD%RU8] Disable\n", pStream->u8SD));
3207
3208 ichac97R3StreamEnable(pThis, pStream, false /* fEnable */);
3209
3210 pRegs->sr |= AC97_SR_DCH;
3211 }
3212 else
3213 {
3214 Log3Func(("[SD%RU8] Enable\n", pStream->u8SD));
3215
3216 pRegs->civ = pRegs->piv;
3217 pRegs->piv = (pRegs->piv + 1) % AC97_MAX_BDLE;
3218
3219 pRegs->sr &= ~AC97_SR_DCH;
3220
3221 /* Fetch the initial BDLE descriptor. */
3222 ichac97R3StreamFetchBDLE(pThis, pStream);
3223# ifdef LOG_ENABLED
3224 ichac97R3BDLEDumpAll(pThis, pStream->Regs.bdbar, pStream->Regs.lvi + 1);
3225# endif
3226 ichac97R3StreamEnable(pThis, pStream, true /* fEnable */);
3227
3228 /* Arm the timer for this stream. */
3229 int rc2 = ichac97TimerSet(pThis, pStream,
3230 TMTimerGet((pThis)->DEVAC97_CTX_SUFF_SD(pTimer, pStream->u8SD)) + pStream->State.cTransferTicks,
3231 false /* fForce */);
3232 AssertRC(rc2);
3233 }
3234 }
3235#else /* !IN_RING3 */
3236 rc = VINF_IOM_R3_IOPORT_WRITE;
3237#endif
3238 break;
3239 }
3240
3241 /*
3242 * Status Registers.
3243 */
3244 case PI_SR:
3245 case PO_SR:
3246 case MC_SR:
3247 {
3248 ichac97StreamWriteSR(pThis, pStream, u32Val);
3249 break;
3250 }
3251
3252 default:
3253 LogRel2(("AC97: Warning: Unimplemented NABMWrite (%u byte) portIdx=%#x <- %#x\n", cbVal, uPortIdx, u32Val));
3254 break;
3255 }
3256 break;
3257 }
3258
3259 case 2:
3260 {
3261 switch (uPortIdx)
3262 {
3263 case PI_SR:
3264 case PO_SR:
3265 case MC_SR:
3266 ichac97StreamWriteSR(pThis, pStream, u32Val);
3267 break;
3268 default:
3269 LogRel2(("AC97: Warning: Unimplemented NABMWrite (%u byte) portIdx=%#x <- %#x\n", cbVal, uPortIdx, u32Val));
3270 break;
3271 }
3272 break;
3273 }
3274
3275 case 4:
3276 {
3277 switch (uPortIdx)
3278 {
3279 case PI_BDBAR:
3280 case PO_BDBAR:
3281 case MC_BDBAR:
3282 AssertPtr(pStream);
3283 AssertPtr(pRegs);
3284 /* Buffer Descriptor list Base Address Register */
3285 pRegs->bdbar = u32Val & ~3;
3286 Log3Func(("[SD%RU8] BDBAR <- %#x (bdbar %#x)\n", AC97_PORT2IDX(uPortIdx), u32Val, pRegs->bdbar));
3287 break;
3288 case AC97_GLOB_CNT:
3289 /* Global Control */
3290 if (u32Val & AC97_GC_WR)
3291 ichac97WarmReset(pThis);
3292 if (u32Val & AC97_GC_CR)
3293 ichac97ColdReset(pThis);
3294 if (!(u32Val & (AC97_GC_WR | AC97_GC_CR)))
3295 pThis->glob_cnt = u32Val & AC97_GC_VALID_MASK;
3296 Log3Func(("glob_cnt <- %#x (glob_cnt %#x)\n", u32Val, pThis->glob_cnt));
3297 break;
3298 case AC97_GLOB_STA:
3299 /* Global Status */
3300 pThis->glob_sta &= ~(u32Val & AC97_GS_WCLEAR_MASK);
3301 pThis->glob_sta |= (u32Val & ~(AC97_GS_WCLEAR_MASK | AC97_GS_RO_MASK)) & AC97_GS_VALID_MASK;
3302 Log3Func(("glob_sta <- %#x (glob_sta %#x)\n", u32Val, pThis->glob_sta));
3303 break;
3304 default:
3305 LogRel2(("AC97: Warning: Unimplemented NABMWrite (%u byte) portIdx=%#x <- %#x\n", cbVal, uPortIdx, u32Val));
3306 break;
3307 }
3308 break;
3309 }
3310
3311 default:
3312 LogRel2(("AC97: Warning: Unimplemented NABMWrite (%u byte) portIdx=%#x <- %#x\n", cbVal, uPortIdx, u32Val));
3313 break;
3314 }
3315
3316 if (pStream)
3317 DEVAC97_UNLOCK_BOTH(pThis, pStream->u8SD);
3318
3319 return rc;
3320}
3321
3322/**
3323 * Port I/O Handler for IN operations.
3324 *
3325 * @returns VINF_SUCCESS or VINF_EM_*.
3326 * @returns VERR_IOM_IOPORT_UNUSED if the port is really unused and a ~0 value should be returned.
3327 *
3328 * @param pDevIns The device instance.
3329 * @param pvUser User argument.
3330 * @param uPort Port number used for the IN operation.
3331 * @param pu32Val Where to store the result. This is always a 32-bit
3332 * variable regardless of what @a cbVal might say.
3333 * @param cbVal Number of bytes read.
3334 */
3335PDMBOTHCBDECL(int) ichac97IOPortNAMRead(PPDMDEVINS pDevIns, void *pvUser, RTIOPORT uPort, uint32_t *pu32Val, unsigned cbVal)
3336{
3337 PAC97STATE pThis = PDMINS_2_DATA(pDevIns, PAC97STATE);
3338 RT_NOREF(pvUser);
3339
3340 DEVAC97_LOCK_RETURN(pThis, VINF_IOM_R3_IOPORT_READ);
3341
3342 int rc = VINF_SUCCESS;
3343
3344 uint32_t index = uPort - pThis->IOPortBase[0];
3345 Assert(index < 256);
3346
3347 switch (cbVal)
3348 {
3349 case 1:
3350 {
3351 LogRel2(("AC97: Warning: Unimplemented read (%u byte) port=%#x, idx=%RU32\n", cbVal, uPort, index));
3352 pThis->cas = 0;
3353 *pu32Val = UINT32_MAX;
3354 break;
3355 }
3356
3357 case 2:
3358 {
3359 pThis->cas = 0;
3360 *pu32Val = ichac97MixerGet(pThis, index);
3361 break;
3362 }
3363
3364 case 4:
3365 {
3366 LogRel2(("AC97: Warning: Unimplemented read (%u byte) port=%#x, idx=%RU32\n", cbVal, uPort, index));
3367 pThis->cas = 0;
3368 *pu32Val = UINT32_MAX;
3369 break;
3370 }
3371
3372 default:
3373 {
3374 AssertFailed();
3375 rc = VERR_IOM_IOPORT_UNUSED;
3376 }
3377 }
3378
3379 DEVAC97_UNLOCK(pThis);
3380
3381 return rc;
3382}
3383
3384/**
3385 * Port I/O Handler for OUT operations.
3386 *
3387 * @returns VINF_SUCCESS or VINF_EM_*.
3388 *
3389 * @param pDevIns The device instance.
3390 * @param pvUser User argument.
3391 * @param uPort Port number used for the OUT operation.
3392 * @param u32Val The value to output.
3393 * @param cbVal The value size in bytes.
3394 * @remarks Caller enters the device critical section.
3395 */
3396PDMBOTHCBDECL(int) ichac97IOPortNAMWrite(PPDMDEVINS pDevIns, void *pvUser, RTIOPORT uPort, uint32_t u32Val, unsigned cbVal)
3397{
3398 PAC97STATE pThis = PDMINS_2_DATA(pDevIns, PAC97STATE);
3399 RT_NOREF(pvUser);
3400
3401 DEVAC97_LOCK_RETURN(pThis, VINF_IOM_R3_IOPORT_WRITE);
3402
3403 uint32_t uPortIdx = uPort - pThis->IOPortBase[0];
3404
3405 int rc = VINF_SUCCESS;
3406 switch (cbVal)
3407 {
3408 case 1:
3409 {
3410 LogRel2(("AC97: Warning: Unimplemented NAMWrite (%u byte) port=%#x, idx=0x%x <- %#x\n", cbVal, uPort, uPortIdx, u32Val));
3411 pThis->cas = 0;
3412 break;
3413 }
3414
3415 case 2:
3416 {
3417 pThis->cas = 0;
3418 switch (uPortIdx)
3419 {
3420 case AC97_Reset:
3421#ifdef IN_RING3
3422 ichac97R3Reset(pThis->CTX_SUFF(pDevIns));
3423#else
3424 rc = VINF_IOM_R3_IOPORT_WRITE;
3425#endif
3426 break;
3427 case AC97_Powerdown_Ctrl_Stat:
3428 u32Val &= ~0xf;
3429 u32Val |= ichac97MixerGet(pThis, uPortIdx) & 0xf;
3430 ichac97MixerSet(pThis, uPortIdx, u32Val);
3431 break;
3432 case AC97_Master_Volume_Mute:
3433 if (pThis->uCodecModel == AC97_CODEC_AD1980)
3434 {
3435 if (ichac97MixerGet(pThis, AC97_AD_Misc) & AC97_AD_MISC_LOSEL)
3436 break; /* Register controls surround (rear), do nothing. */
3437 }
3438#ifdef IN_RING3
3439 ichac97R3MixerSetVolume(pThis, uPortIdx, PDMAUDIOMIXERCTL_VOLUME_MASTER, u32Val);
3440#else
3441 rc = VINF_IOM_R3_IOPORT_WRITE;
3442#endif
3443 break;
3444 case AC97_Headphone_Volume_Mute:
3445 if (pThis->uCodecModel == AC97_CODEC_AD1980)
3446 {
3447 if (ichac97MixerGet(pThis, AC97_AD_Misc) & AC97_AD_MISC_HPSEL)
3448 {
3449 /* Register controls PCM (front) outputs. */
3450#ifdef IN_RING3
3451 ichac97R3MixerSetVolume(pThis, uPortIdx, PDMAUDIOMIXERCTL_VOLUME_MASTER, u32Val);
3452#else
3453 rc = VINF_IOM_R3_IOPORT_WRITE;
3454#endif
3455 }
3456 }
3457 break;
3458 case AC97_PCM_Out_Volume_Mute:
3459#ifdef IN_RING3
3460 ichac97R3MixerSetVolume(pThis, uPortIdx, PDMAUDIOMIXERCTL_FRONT, u32Val);
3461#else
3462 rc = VINF_IOM_R3_IOPORT_WRITE;
3463#endif
3464 break;
3465 case AC97_Line_In_Volume_Mute:
3466#ifdef IN_RING3
3467 ichac97R3MixerSetVolume(pThis, uPortIdx, PDMAUDIOMIXERCTL_LINE_IN, u32Val);
3468#else
3469 rc = VINF_IOM_R3_IOPORT_WRITE;
3470#endif
3471 break;
3472 case AC97_Record_Select:
3473#ifdef IN_RING3
3474 ichac97R3MixerRecordSelect(pThis, u32Val);
3475#else
3476 rc = VINF_IOM_R3_IOPORT_WRITE;
3477#endif
3478 break;
3479 case AC97_Record_Gain_Mute:
3480#ifdef IN_RING3
3481 /* Newer Ubuntu guests rely on that when controlling gain and muting
3482 * the recording (capturing) levels. */
3483 ichac97R3MixerSetGain(pThis, uPortIdx, PDMAUDIOMIXERCTL_LINE_IN, u32Val);
3484#else
3485 rc = VINF_IOM_R3_IOPORT_WRITE;
3486#endif
3487 break;
3488 case AC97_Record_Gain_Mic_Mute:
3489#ifdef IN_RING3
3490 /* Ditto; see note above. */
3491 ichac97R3MixerSetGain(pThis, uPortIdx, PDMAUDIOMIXERCTL_MIC_IN, u32Val);
3492#else
3493 rc = VINF_IOM_R3_IOPORT_WRITE;
3494#endif
3495 break;
3496 case AC97_Vendor_ID1:
3497 case AC97_Vendor_ID2:
3498 LogFunc(("Attempt to write vendor ID to %#x\n", u32Val));
3499 break;
3500 case AC97_Extended_Audio_ID:
3501 LogFunc(("Attempt to write extended audio ID to %#x\n", u32Val));
3502 break;
3503 case AC97_Extended_Audio_Ctrl_Stat:
3504#ifdef IN_RING3
3505 /*
3506 * Handle VRA bits.
3507 */
3508 if (!(u32Val & AC97_EACS_VRA)) /* Check if VRA bit is not set. */
3509 {
3510 ichac97MixerSet(pThis, AC97_PCM_Front_DAC_Rate, 0xbb80); /* Set default (48000 Hz). */
3511 ichac97R3StreamReOpen(pThis, &pThis->aStreams[AC97SOUNDSOURCE_PO_INDEX], true /* fForce */);
3512
3513 ichac97MixerSet(pThis, AC97_PCM_LR_ADC_Rate, 0xbb80); /* Set default (48000 Hz). */
3514 ichac97R3StreamReOpen(pThis, &pThis->aStreams[AC97SOUNDSOURCE_PI_INDEX], true /* fForce */);
3515 }
3516 else
3517 LogRel2(("AC97: Variable rate audio (VRA) is not supported\n"));
3518
3519 /*
3520 * Handle VRM bits.
3521 */
3522 if (!(u32Val & AC97_EACS_VRM)) /* Check if VRM bit is not set. */
3523 {
3524 ichac97MixerSet(pThis, AC97_MIC_ADC_Rate, 0xbb80); /* Set default (48000 Hz). */
3525 ichac97R3StreamReOpen(pThis, &pThis->aStreams[AC97SOUNDSOURCE_MC_INDEX], true /* fForce */);
3526 }
3527 else
3528 LogRel2(("AC97: Variable rate microphone audio (VRM) is not supported\n"));
3529
3530 LogRel2(("AC97: Setting extended audio control to %#x\n", u32Val));
3531 ichac97MixerSet(pThis, AC97_Extended_Audio_Ctrl_Stat, u32Val);
3532#else /* !IN_RING3 */
3533 rc = VINF_IOM_R3_IOPORT_WRITE;
3534#endif
3535 break;
3536 case AC97_PCM_Front_DAC_Rate: /* Output slots 3, 4, 6. */
3537#ifdef IN_RING3
3538 if (ichac97MixerGet(pThis, AC97_Extended_Audio_Ctrl_Stat) & AC97_EACS_VRA)
3539 {
3540 LogRel2(("AC97: Setting front DAC rate to 0x%x\n", u32Val));
3541 ichac97MixerSet(pThis, uPortIdx, u32Val);
3542 ichac97R3StreamReOpen(pThis, &pThis->aStreams[AC97SOUNDSOURCE_PO_INDEX], true /* fForce */);
3543 }
3544 else
3545 LogRel2(("AC97: Setting front DAC rate (0x%x) when VRA is not set is forbidden, ignoring\n", u32Val));
3546#else
3547 rc = VINF_IOM_R3_IOPORT_WRITE;
3548#endif
3549 break;
3550 case AC97_MIC_ADC_Rate: /* Input slot 6. */
3551#ifdef IN_RING3
3552 if (ichac97MixerGet(pThis, AC97_Extended_Audio_Ctrl_Stat) & AC97_EACS_VRM)
3553 {
3554 LogRel2(("AC97: Setting microphone ADC rate to 0x%x\n", u32Val));
3555 ichac97MixerSet(pThis, uPortIdx, u32Val);
3556 ichac97R3StreamReOpen(pThis, &pThis->aStreams[AC97SOUNDSOURCE_MC_INDEX], true /* fForce */);
3557 }
3558 else
3559 LogRel2(("AC97: Setting microphone ADC rate (0x%x) when VRM is not set is forbidden, ignoring\n",
3560 u32Val));
3561#else
3562 rc = VINF_IOM_R3_IOPORT_WRITE;
3563#endif
3564 break;
3565 case AC97_PCM_LR_ADC_Rate: /* Input slots 3, 4. */
3566#ifdef IN_RING3
3567 if (ichac97MixerGet(pThis, AC97_Extended_Audio_Ctrl_Stat) & AC97_EACS_VRA)
3568 {
3569 LogRel2(("AC97: Setting line-in ADC rate to 0x%x\n", u32Val));
3570 ichac97MixerSet(pThis, uPortIdx, u32Val);
3571 ichac97R3StreamReOpen(pThis, &pThis->aStreams[AC97SOUNDSOURCE_PI_INDEX], true /* fForce */);
3572 }
3573 else
3574 LogRel2(("AC97: Setting line-in ADC rate (0x%x) when VRA is not set is forbidden, ignoring\n", u32Val));
3575#else
3576 rc = VINF_IOM_R3_IOPORT_WRITE;
3577#endif
3578 break;
3579 default:
3580 LogRel2(("AC97: Warning: Unimplemented NAMWrite (%u byte) port=%#x, idx=0x%x <- %#x\n", cbVal, uPort, uPortIdx, u32Val));
3581 ichac97MixerSet(pThis, uPortIdx, u32Val);
3582 break;
3583 }
3584 break;
3585 }
3586
3587 case 4:
3588 {
3589 LogRel2(("AC97: Warning: Unimplemented NAMWrite (%u byte) port=%#x, idx=0x%x <- %#x\n", cbVal, uPort, uPortIdx, u32Val));
3590 pThis->cas = 0;
3591 break;
3592 }
3593
3594 default:
3595 AssertMsgFailed(("Unhandled NAMWrite port=%#x, cbVal=%u u32Val=%#x\n", uPort, cbVal, u32Val));
3596 break;
3597 }
3598
3599 DEVAC97_UNLOCK(pThis);
3600
3601 return rc;
3602}
3603
3604#ifdef IN_RING3
3605
3606/**
3607 * @callback_method_impl{FNPCIIOREGIONMAP}
3608 */
3609static DECLCALLBACK(int) ichac97R3IOPortMap(PPDMDEVINS pDevIns, PPDMPCIDEV pPciDev, uint32_t iRegion,
3610 RTGCPHYS GCPhysAddress, RTGCPHYS cb, PCIADDRESSSPACE enmType)
3611{
3612 RT_NOREF(cb, enmType);
3613
3614 Assert(enmType == PCI_ADDRESS_SPACE_IO);
3615 Assert(cb >= 0x20);
3616
3617 if (iRegion > 1) /* We support 2 regions max. at the moment. */
3618 return VERR_INVALID_PARAMETER;
3619
3620 PAC97STATE pThis = RT_FROM_MEMBER(pPciDev, AC97STATE, PciDev);
3621 RTIOPORT Port = (RTIOPORT)GCPhysAddress;
3622
3623 int rc;
3624 if (iRegion == 0)
3625 {
3626 rc = PDMDevHlpIOPortRegister(pDevIns, Port, 256, NULL, ichac97IOPortNAMWrite, ichac97IOPortNAMRead,
3627 NULL, NULL, "ICHAC97 NAM");
3628 AssertRCReturn(rc, rc);
3629 if (pThis->fRZEnabled)
3630 {
3631 rc = PDMDevHlpIOPortRegisterR0(pDevIns, Port, 256, NIL_RTR0PTR, "ichac97IOPortNAMWrite", "ichac97IOPortNAMRead",
3632 NULL, NULL, "ICHAC97 NAM");
3633 AssertRCReturn(rc, rc);
3634 rc = PDMDevHlpIOPortRegisterRC(pDevIns, Port, 256, NIL_RTRCPTR, "ichac97IOPortNAMWrite", "ichac97IOPortNAMRead",
3635 NULL, NULL, "ICHAC97 NAM");
3636 AssertRCReturn(rc, rc);
3637 }
3638 }
3639 else
3640 {
3641 rc = PDMDevHlpIOPortRegister(pDevIns, Port, 64, NULL, ichac97IOPortNABMWrite, ichac97IOPortNABMRead,
3642 NULL, NULL, "ICHAC97 NABM");
3643 AssertRCReturn(rc, rc);
3644 if (pThis->fRZEnabled)
3645 {
3646 rc = PDMDevHlpIOPortRegisterR0(pDevIns, Port, 64, NIL_RTR0PTR, "ichac97IOPortNABMWrite", "ichac97IOPortNABMRead",
3647 NULL, NULL, "ICHAC97 NABM");
3648 AssertRCReturn(rc, rc);
3649 rc = PDMDevHlpIOPortRegisterRC(pDevIns, Port, 64, NIL_RTRCPTR, "ichac97IOPortNABMWrite", "ichac97IOPortNABMRead",
3650 NULL, NULL, "ICHAC97 NABM");
3651 AssertRCReturn(rc, rc);
3652
3653 }
3654 }
3655
3656 pThis->IOPortBase[iRegion] = Port;
3657 return VINF_SUCCESS;
3658}
3659
3660
3661/**
3662 * Saves (serializes) an AC'97 stream using SSM.
3663 *
3664 * @returns IPRT status code.
3665 * @param pDevIns Device instance.
3666 * @param pSSM Saved state manager (SSM) handle to use.
3667 * @param pStream AC'97 stream to save.
3668 */
3669static int ichac97R3SaveStream(PPDMDEVINS pDevIns, PSSMHANDLE pSSM, PAC97STREAM pStream)
3670{
3671 RT_NOREF(pDevIns);
3672 PAC97BMREGS pRegs = &pStream->Regs;
3673
3674 SSMR3PutU32(pSSM, pRegs->bdbar);
3675 SSMR3PutU8( pSSM, pRegs->civ);
3676 SSMR3PutU8( pSSM, pRegs->lvi);
3677 SSMR3PutU16(pSSM, pRegs->sr);
3678 SSMR3PutU16(pSSM, pRegs->picb);
3679 SSMR3PutU8( pSSM, pRegs->piv);
3680 SSMR3PutU8( pSSM, pRegs->cr);
3681 SSMR3PutS32(pSSM, pRegs->bd_valid);
3682 SSMR3PutU32(pSSM, pRegs->bd.addr);
3683 SSMR3PutU32(pSSM, pRegs->bd.ctl_len);
3684
3685 return VINF_SUCCESS;
3686}
3687
3688/**
3689 * @callback_method_impl{FNSSMDEVSAVEEXEC}
3690 */
3691static DECLCALLBACK(int) ichac97R3SaveExec(PPDMDEVINS pDevIns, PSSMHANDLE pSSM)
3692{
3693 PAC97STATE pThis = PDMINS_2_DATA(pDevIns, PAC97STATE);
3694
3695 LogFlowFuncEnter();
3696
3697 SSMR3PutU32(pSSM, pThis->glob_cnt);
3698 SSMR3PutU32(pSSM, pThis->glob_sta);
3699 SSMR3PutU32(pSSM, pThis->cas);
3700
3701 /** @todo r=andy For the next saved state version, add unique stream identifiers and a stream count. */
3702 /* Note: The order the streams are loaded here is critical, so don't touch. */
3703 for (unsigned i = 0; i < AC97_MAX_STREAMS; i++)
3704 {
3705 int rc2 = ichac97R3SaveStream(pDevIns, pSSM, &pThis->aStreams[i]);
3706 AssertRC(rc2);
3707 }
3708
3709 SSMR3PutMem(pSSM, pThis->mixer_data, sizeof(pThis->mixer_data));
3710
3711 uint8_t active[AC97SOUNDSOURCE_END_INDEX];
3712
3713 active[AC97SOUNDSOURCE_PI_INDEX] = ichac97R3StreamIsEnabled(pThis, &pThis->aStreams[AC97SOUNDSOURCE_PI_INDEX]) ? 1 : 0;
3714 active[AC97SOUNDSOURCE_PO_INDEX] = ichac97R3StreamIsEnabled(pThis, &pThis->aStreams[AC97SOUNDSOURCE_PO_INDEX]) ? 1 : 0;
3715 active[AC97SOUNDSOURCE_MC_INDEX] = ichac97R3StreamIsEnabled(pThis, &pThis->aStreams[AC97SOUNDSOURCE_MC_INDEX]) ? 1 : 0;
3716
3717 SSMR3PutMem(pSSM, active, sizeof(active));
3718
3719 LogFlowFuncLeaveRC(VINF_SUCCESS);
3720 return VINF_SUCCESS;
3721}
3722
3723/**
3724 * Loads an AC'97 stream from SSM.
3725 *
3726 * @returns IPRT status code.
3727 * @param pSSM Saved state manager (SSM) handle to use.
3728 * @param pStream AC'97 stream to load.
3729 */
3730static int ichac97R3LoadStream(PSSMHANDLE pSSM, PAC97STREAM pStream)
3731{
3732 PAC97BMREGS pRegs = &pStream->Regs;
3733
3734 SSMR3GetU32(pSSM, &pRegs->bdbar);
3735 SSMR3GetU8( pSSM, &pRegs->civ);
3736 SSMR3GetU8( pSSM, &pRegs->lvi);
3737 SSMR3GetU16(pSSM, &pRegs->sr);
3738 SSMR3GetU16(pSSM, &pRegs->picb);
3739 SSMR3GetU8( pSSM, &pRegs->piv);
3740 SSMR3GetU8( pSSM, &pRegs->cr);
3741 SSMR3GetS32(pSSM, &pRegs->bd_valid);
3742 SSMR3GetU32(pSSM, &pRegs->bd.addr);
3743 return SSMR3GetU32(pSSM, &pRegs->bd.ctl_len);
3744}
3745
3746/**
3747 * @callback_method_impl{FNSSMDEVLOADEXEC}
3748 */
3749static DECLCALLBACK(int) ichac97R3LoadExec(PPDMDEVINS pDevIns, PSSMHANDLE pSSM, uint32_t uVersion, uint32_t uPass)
3750{
3751 PAC97STATE pThis = PDMINS_2_DATA(pDevIns, PAC97STATE);
3752
3753 LogRel2(("ichac97LoadExec: uVersion=%RU32, uPass=0x%x\n", uVersion, uPass));
3754
3755 AssertMsgReturn (uVersion == AC97_SSM_VERSION, ("%RU32\n", uVersion), VERR_SSM_UNSUPPORTED_DATA_UNIT_VERSION);
3756 Assert(uPass == SSM_PASS_FINAL); NOREF(uPass);
3757
3758 SSMR3GetU32(pSSM, &pThis->glob_cnt);
3759 SSMR3GetU32(pSSM, &pThis->glob_sta);
3760 SSMR3GetU32(pSSM, &pThis->cas);
3761
3762 /** @todo r=andy For the next saved state version, add unique stream identifiers and a stream count. */
3763 /* Note: The order the streams are loaded here is critical, so don't touch. */
3764 for (unsigned i = 0; i < AC97_MAX_STREAMS; i++)
3765 {
3766 int rc2 = ichac97R3LoadStream(pSSM, &pThis->aStreams[i]);
3767 AssertRCReturn(rc2, rc2);
3768 }
3769
3770 SSMR3GetMem(pSSM, pThis->mixer_data, sizeof(pThis->mixer_data));
3771
3772 /** @todo r=andy Stream IDs are hardcoded to certain streams. */
3773 uint8_t uaStrmsActive[AC97SOUNDSOURCE_END_INDEX];
3774 int rc2 = SSMR3GetMem(pSSM, uaStrmsActive, sizeof(uaStrmsActive));
3775 AssertRCReturn(rc2, rc2);
3776
3777 ichac97R3MixerRecordSelect(pThis, ichac97MixerGet(pThis, AC97_Record_Select));
3778 ichac97R3MixerSetVolume(pThis, AC97_Master_Volume_Mute, PDMAUDIOMIXERCTL_VOLUME_MASTER, ichac97MixerGet(pThis, AC97_Master_Volume_Mute));
3779 ichac97R3MixerSetVolume(pThis, AC97_PCM_Out_Volume_Mute, PDMAUDIOMIXERCTL_FRONT, ichac97MixerGet(pThis, AC97_PCM_Out_Volume_Mute));
3780 ichac97R3MixerSetVolume(pThis, AC97_Line_In_Volume_Mute, PDMAUDIOMIXERCTL_LINE_IN, ichac97MixerGet(pThis, AC97_Line_In_Volume_Mute));
3781 ichac97R3MixerSetVolume(pThis, AC97_Mic_Volume_Mute, PDMAUDIOMIXERCTL_MIC_IN, ichac97MixerGet(pThis, AC97_Mic_Volume_Mute));
3782 ichac97R3MixerSetGain(pThis, AC97_Record_Gain_Mic_Mute, PDMAUDIOMIXERCTL_MIC_IN, ichac97MixerGet(pThis, AC97_Record_Gain_Mic_Mute));
3783 ichac97R3MixerSetGain(pThis, AC97_Record_Gain_Mute, PDMAUDIOMIXERCTL_LINE_IN, ichac97MixerGet(pThis, AC97_Record_Gain_Mute));
3784 if (pThis->uCodecModel == AC97_CODEC_AD1980)
3785 if (ichac97MixerGet(pThis, AC97_AD_Misc) & AC97_AD_MISC_HPSEL)
3786 ichac97R3MixerSetVolume(pThis, AC97_Headphone_Volume_Mute, PDMAUDIOMIXERCTL_VOLUME_MASTER,
3787 ichac97MixerGet(pThis, AC97_Headphone_Volume_Mute));
3788
3789 /** @todo r=andy Stream IDs are hardcoded to certain streams. */
3790 for (unsigned i = 0; i < AC97_MAX_STREAMS; i++)
3791 {
3792 const bool fEnable = RT_BOOL(uaStrmsActive[i]);
3793 const PAC97STREAM pStream = &pThis->aStreams[i];
3794
3795 rc2 = ichac97R3StreamEnable(pThis, pStream, fEnable);
3796 if ( fEnable
3797 && RT_SUCCESS(rc2))
3798 {
3799 /* Re-arm the timer for this stream. */
3800 rc2 = ichac97TimerSet(pThis, pStream,
3801 TMTimerGet((pThis)->DEVAC97_CTX_SUFF_SD(pTimer, pStream->u8SD)) + pStream->State.cTransferTicks,
3802 false /* fForce */);
3803 }
3804
3805 AssertRC(rc2);
3806 /* Keep going. */
3807 }
3808
3809 pThis->bup_flag = 0;
3810 pThis->last_samp = 0;
3811
3812 return VINF_SUCCESS;
3813}
3814
3815
3816/**
3817 * @interface_method_impl{PDMIBASE,pfnQueryInterface}
3818 */
3819static DECLCALLBACK(void *) ichac97R3QueryInterface(struct PDMIBASE *pInterface, const char *pszIID)
3820{
3821 PAC97STATE pThis = RT_FROM_MEMBER(pInterface, AC97STATE, IBase);
3822 Assert(&pThis->IBase == pInterface);
3823
3824 PDMIBASE_RETURN_INTERFACE(pszIID, PDMIBASE, &pThis->IBase);
3825 return NULL;
3826}
3827
3828
3829/**
3830 * Powers off the device.
3831 *
3832 * @param pDevIns Device instance to power off.
3833 */
3834static DECLCALLBACK(void) ichac97R3PowerOff(PPDMDEVINS pDevIns)
3835{
3836 PAC97STATE pThis = PDMINS_2_DATA(pDevIns, PAC97STATE);
3837
3838 LogRel2(("AC97: Powering off ...\n"));
3839
3840 /* Note: Involves mixer stream / sink destruction, so also do this here
3841 * instead of in ichac97R3Destruct(). */
3842 ichac97R3StreamsDestroy(pThis);
3843
3844 /**
3845 * Note: Destroy the mixer while powering off and *not* in ichac97R3Destruct,
3846 * giving the mixer the chance to release any references held to
3847 * PDM audio streams it maintains.
3848 */
3849 if (pThis->pMixer)
3850 {
3851 AudioMixerDestroy(pThis->pMixer);
3852 pThis->pMixer = NULL;
3853 }
3854}
3855
3856
3857/**
3858 * @interface_method_impl{PDMDEVREG,pfnReset}
3859 *
3860 * @remarks The original sources didn't install a reset handler, but it seems to
3861 * make sense to me so we'll do it.
3862 */
3863static DECLCALLBACK(void) ichac97R3Reset(PPDMDEVINS pDevIns)
3864{
3865 PAC97STATE pThis = PDMINS_2_DATA(pDevIns, PAC97STATE);
3866
3867 LogRel(("AC97: Reset\n"));
3868
3869 /*
3870 * Reset the mixer too. The Windows XP driver seems to rely on
3871 * this. At least it wants to read the vendor id before it resets
3872 * the codec manually.
3873 */
3874 ichac97R3MixerReset(pThis);
3875
3876 /*
3877 * Reset all streams.
3878 */
3879 for (unsigned i = 0; i < AC97_MAX_STREAMS; i++)
3880 {
3881 ichac97R3StreamEnable(pThis, &pThis->aStreams[i], false /* fEnable */);
3882 ichac97R3StreamReset(pThis, &pThis->aStreams[i]);
3883 }
3884
3885 /*
3886 * Reset mixer sinks.
3887 *
3888 * Do the reset here instead of in ichac97R3StreamReset();
3889 * the mixer sink(s) might still have data to be processed when an audio stream gets reset.
3890 */
3891 AudioMixerSinkReset(pThis->pSinkLineIn);
3892 AudioMixerSinkReset(pThis->pSinkMicIn);
3893 AudioMixerSinkReset(pThis->pSinkOut);
3894}
3895
3896
3897/**
3898 * Attach command, internal version.
3899 *
3900 * This is called to let the device attach to a driver for a specified LUN
3901 * during runtime. This is not called during VM construction, the device
3902 * constructor has to attach to all the available drivers.
3903 *
3904 * @returns VBox status code.
3905 * @param pThis AC'97 state.
3906 * @param uLUN The logical unit which is being attached.
3907 * @param fFlags Flags, combination of the PDMDEVATT_FLAGS_* \#defines.
3908 * @param ppDrv Attached driver instance on success. Optional.
3909 */
3910static int ichac97R3AttachInternal(PAC97STATE pThis, unsigned uLUN, uint32_t fFlags, PAC97DRIVER *ppDrv)
3911{
3912 RT_NOREF(fFlags);
3913
3914 /*
3915 * Attach driver.
3916 */
3917 char *pszDesc;
3918 if (RTStrAPrintf(&pszDesc, "Audio driver port (AC'97) for LUN #%u", uLUN) <= 0)
3919 AssertLogRelFailedReturn(VERR_NO_MEMORY);
3920
3921 PPDMIBASE pDrvBase;
3922 int rc = PDMDevHlpDriverAttach(pThis->pDevInsR3, uLUN,
3923 &pThis->IBase, &pDrvBase, pszDesc);
3924 if (RT_SUCCESS(rc))
3925 {
3926 PAC97DRIVER pDrv = (PAC97DRIVER)RTMemAllocZ(sizeof(AC97DRIVER));
3927 if (pDrv)
3928 {
3929 pDrv->pDrvBase = pDrvBase;
3930 pDrv->pConnector = PDMIBASE_QUERY_INTERFACE(pDrvBase, PDMIAUDIOCONNECTOR);
3931 AssertMsg(pDrv->pConnector != NULL, ("Configuration error: LUN #%u has no host audio interface, rc=%Rrc\n", uLUN, rc));
3932 pDrv->pAC97State = pThis;
3933 pDrv->uLUN = uLUN;
3934 pDrv->pszDesc = pszDesc;
3935
3936 /*
3937 * For now we always set the driver at LUN 0 as our primary
3938 * host backend. This might change in the future.
3939 */
3940 if (pDrv->uLUN == 0)
3941 pDrv->fFlags |= PDMAUDIODRVFLAGS_PRIMARY;
3942
3943 LogFunc(("LUN#%RU8: pCon=%p, drvFlags=0x%x\n", uLUN, pDrv->pConnector, pDrv->fFlags));
3944
3945 /* Attach to driver list if not attached yet. */
3946 if (!pDrv->fAttached)
3947 {
3948 RTListAppend(&pThis->lstDrv, &pDrv->Node);
3949 pDrv->fAttached = true;
3950 }
3951
3952 if (ppDrv)
3953 *ppDrv = pDrv;
3954 }
3955 else
3956 rc = VERR_NO_MEMORY;
3957 }
3958 else if (rc == VERR_PDM_NO_ATTACHED_DRIVER)
3959 LogFunc(("No attached driver for LUN #%u\n", uLUN));
3960
3961 if (RT_FAILURE(rc))
3962 {
3963 /* Only free this string on failure;
3964 * must remain valid for the live of the driver instance. */
3965 RTStrFree(pszDesc);
3966 }
3967
3968 LogFunc(("uLUN=%u, fFlags=0x%x, rc=%Rrc\n", uLUN, fFlags, rc));
3969 return rc;
3970}
3971
3972/**
3973 * Detach command, internal version.
3974 *
3975 * This is called to let the device detach from a driver for a specified LUN
3976 * during runtime.
3977 *
3978 * @returns VBox status code.
3979 * @param pThis AC'97 state.
3980 * @param pDrv Driver to detach from device.
3981 * @param fFlags Flags, combination of the PDMDEVATT_FLAGS_* \#defines.
3982 */
3983static int ichac97R3DetachInternal(PAC97STATE pThis, PAC97DRIVER pDrv, uint32_t fFlags)
3984{
3985 RT_NOREF(fFlags);
3986
3987 /* First, remove the driver from our list and destory it's associated streams.
3988 * This also will un-set the driver as a recording source (if associated). */
3989 ichac97R3MixerRemoveDrv(pThis, pDrv);
3990
3991 /* Next, search backwards for a capable (attached) driver which now will be the
3992 * new recording source. */
3993 PDMAUDIODESTSOURCE dstSrc;
3994 PAC97DRIVER pDrvCur;
3995 RTListForEachReverse(&pThis->lstDrv, pDrvCur, AC97DRIVER, Node)
3996 {
3997 if (!pDrvCur->pConnector)
3998 continue;
3999
4000 PDMAUDIOBACKENDCFG Cfg;
4001 int rc2 = pDrvCur->pConnector->pfnGetConfig(pDrvCur->pConnector, &Cfg);
4002 if (RT_FAILURE(rc2))
4003 continue;
4004
4005 dstSrc.Source = PDMAUDIORECSOURCE_MIC;
4006 PAC97DRIVERSTREAM pDrvStrm = ichac97R3MixerGetDrvStream(pThis, pDrvCur, PDMAUDIODIR_IN, dstSrc);
4007 if ( pDrvStrm
4008 && pDrvStrm->pMixStrm)
4009 {
4010 rc2 = AudioMixerSinkSetRecordingSource(pThis->pSinkMicIn, pDrvStrm->pMixStrm);
4011 if (RT_SUCCESS(rc2))
4012 LogRel2(("AC97: Set new recording source for 'Mic In' to '%s'\n", Cfg.szName));
4013 }
4014
4015 dstSrc.Source = PDMAUDIORECSOURCE_LINE;
4016 pDrvStrm = ichac97R3MixerGetDrvStream(pThis, pDrvCur, PDMAUDIODIR_IN, dstSrc);
4017 if ( pDrvStrm
4018 && pDrvStrm->pMixStrm)
4019 {
4020 rc2 = AudioMixerSinkSetRecordingSource(pThis->pSinkLineIn, pDrvStrm->pMixStrm);
4021 if (RT_SUCCESS(rc2))
4022 LogRel2(("AC97: Set new recording source for 'Line In' to '%s'\n", Cfg.szName));
4023 }
4024 }
4025
4026 LogFunc(("uLUN=%u, fFlags=0x%x\n", pDrv->uLUN, fFlags));
4027 return VINF_SUCCESS;
4028}
4029
4030/**
4031 * @interface_method_impl{PDMDEVREG,pfnAttach}
4032 */
4033static DECLCALLBACK(int) ichac97R3Attach(PPDMDEVINS pDevIns, unsigned uLUN, uint32_t fFlags)
4034{
4035 PAC97STATE pThis = PDMINS_2_DATA(pDevIns, PAC97STATE);
4036
4037 LogFunc(("uLUN=%u, fFlags=0x%x\n", uLUN, fFlags));
4038
4039 DEVAC97_LOCK(pThis);
4040
4041 PAC97DRIVER pDrv;
4042 int rc2 = ichac97R3AttachInternal(pThis, uLUN, fFlags, &pDrv);
4043 if (RT_SUCCESS(rc2))
4044 rc2 = ichac97R3MixerAddDrv(pThis, pDrv);
4045
4046 if (RT_FAILURE(rc2))
4047 LogFunc(("Failed with %Rrc\n", rc2));
4048
4049 DEVAC97_UNLOCK(pThis);
4050
4051 return VINF_SUCCESS;
4052}
4053
4054/**
4055 * @interface_method_impl{PDMDEVREG,pfnDetach}
4056 */
4057static DECLCALLBACK(void) ichac97R3Detach(PPDMDEVINS pDevIns, unsigned uLUN, uint32_t fFlags)
4058{
4059 PAC97STATE pThis = PDMINS_2_DATA(pDevIns, PAC97STATE);
4060
4061 LogFunc(("uLUN=%u, fFlags=0x%x\n", uLUN, fFlags));
4062
4063 DEVAC97_LOCK(pThis);
4064
4065 PAC97DRIVER pDrv, pDrvNext;
4066 RTListForEachSafe(&pThis->lstDrv, pDrv, pDrvNext, AC97DRIVER, Node)
4067 {
4068 if (pDrv->uLUN == uLUN)
4069 {
4070 int rc2 = ichac97R3DetachInternal(pThis, pDrv, fFlags);
4071 if (RT_SUCCESS(rc2))
4072 {
4073 RTStrFree(pDrv->pszDesc);
4074 RTMemFree(pDrv);
4075 pDrv = NULL;
4076 }
4077
4078 break;
4079 }
4080 }
4081
4082 DEVAC97_UNLOCK(pThis);
4083}
4084
4085/**
4086 * Re-attaches (replaces) a driver with a new driver.
4087 *
4088 * @returns VBox status code.
4089 * @param pThis Device instance.
4090 * @param pDrv Driver instance used for attaching to.
4091 * If NULL is specified, a new driver will be created and appended
4092 * to the driver list.
4093 * @param uLUN The logical unit which is being re-detached.
4094 * @param pszDriver New driver name to attach.
4095 */
4096static int ichac97R3ReattachInternal(PAC97STATE pThis, PAC97DRIVER pDrv, uint8_t uLUN, const char *pszDriver)
4097{
4098 AssertPtrReturn(pThis, VERR_INVALID_POINTER);
4099 AssertPtrReturn(pszDriver, VERR_INVALID_POINTER);
4100
4101 int rc;
4102
4103 if (pDrv)
4104 {
4105 rc = ichac97R3DetachInternal(pThis, pDrv, 0 /* fFlags */);
4106 if (RT_SUCCESS(rc))
4107 rc = PDMDevHlpDriverDetach(pThis->pDevInsR3, PDMIBASE_2_PDMDRV(pDrv->pDrvBase), 0 /* fFlags */);
4108
4109 if (RT_FAILURE(rc))
4110 return rc;
4111
4112 RTStrFree(pDrv->pszDesc);
4113 RTMemFree(pDrv);
4114 pDrv = NULL;
4115 }
4116
4117 PVM pVM = PDMDevHlpGetVM(pThis->pDevInsR3);
4118 PCFGMNODE pRoot = CFGMR3GetRoot(pVM);
4119 PCFGMNODE pDev0 = CFGMR3GetChild(pRoot, "Devices/ichac97/0/");
4120
4121 /* Remove LUN branch. */
4122 CFGMR3RemoveNode(CFGMR3GetChildF(pDev0, "LUN#%u/", uLUN));
4123
4124# define RC_CHECK() if (RT_FAILURE(rc)) { AssertReleaseRC(rc); break; }
4125
4126 do
4127 {
4128 PCFGMNODE pLunL0;
4129 rc = CFGMR3InsertNodeF(pDev0, &pLunL0, "LUN#%u/", uLUN); RC_CHECK();
4130 rc = CFGMR3InsertString(pLunL0, "Driver", "AUDIO"); RC_CHECK();
4131 rc = CFGMR3InsertNode(pLunL0, "Config/", NULL); RC_CHECK();
4132
4133 PCFGMNODE pLunL1, pLunL2;
4134 rc = CFGMR3InsertNode (pLunL0, "AttachedDriver/", &pLunL1); RC_CHECK();
4135 rc = CFGMR3InsertNode (pLunL1, "Config/", &pLunL2); RC_CHECK();
4136 rc = CFGMR3InsertString(pLunL1, "Driver", pszDriver); RC_CHECK();
4137
4138 rc = CFGMR3InsertString(pLunL2, "AudioDriver", pszDriver); RC_CHECK();
4139
4140 } while (0);
4141
4142 if (RT_SUCCESS(rc))
4143 rc = ichac97R3AttachInternal(pThis, uLUN, 0 /* fFlags */, NULL /* ppDrv */);
4144
4145 LogFunc(("pThis=%p, uLUN=%u, pszDriver=%s, rc=%Rrc\n", pThis, uLUN, pszDriver, rc));
4146
4147# undef RC_CHECK
4148
4149 return rc;
4150}
4151
4152/**
4153 * @interface_method_impl{PDMDEVREG,pfnRelocate}
4154 */
4155static DECLCALLBACK(void) ichac97R3Relocate(PPDMDEVINS pDevIns, RTGCINTPTR offDelta)
4156{
4157 NOREF(offDelta);
4158 PAC97STATE pThis = PDMINS_2_DATA(pDevIns, PAC97STATE);
4159 pThis->pDevInsRC = PDMDEVINS_2_RCPTR(pDevIns);
4160
4161 for (unsigned i = 0; i < AC97_MAX_STREAMS; i++)
4162 pThis->pTimerRC[i] = TMTimerRCPtr(pThis->pTimerR3[i]);
4163}
4164
4165/**
4166 * @interface_method_impl{PDMDEVREG,pfnDestruct}
4167 */
4168static DECLCALLBACK(int) ichac97R3Destruct(PPDMDEVINS pDevIns)
4169{
4170 PDMDEV_CHECK_VERSIONS_RETURN_QUIET(pDevIns); /* this shall come first */
4171 PAC97STATE pThis = PDMINS_2_DATA(pDevIns, PAC97STATE);
4172
4173 LogFlowFuncEnter();
4174
4175 PAC97DRIVER pDrv, pDrvNext;
4176 RTListForEachSafe(&pThis->lstDrv, pDrv, pDrvNext, AC97DRIVER, Node)
4177 {
4178 RTListNodeRemove(&pDrv->Node);
4179 RTMemFree(pDrv->pszDesc);
4180 RTMemFree(pDrv);
4181 }
4182
4183 /* Sanity. */
4184 Assert(RTListIsEmpty(&pThis->lstDrv));
4185
4186 return VINF_SUCCESS;
4187}
4188
4189/**
4190 * @interface_method_impl{PDMDEVREG,pfnConstruct}
4191 */
4192static DECLCALLBACK(int) ichac97R3Construct(PPDMDEVINS pDevIns, int iInstance, PCFGMNODE pCfg)
4193{
4194 PDMDEV_CHECK_VERSIONS_RETURN(pDevIns); /* this shall come first */
4195 PAC97STATE pThis = PDMINS_2_DATA(pDevIns, PAC97STATE);
4196 Assert(iInstance == 0); RT_NOREF(iInstance);
4197
4198 /*
4199 * Initialize data so we can run the destructor without scewing up.
4200 */
4201 pThis->pDevInsR3 = pDevIns;
4202 pThis->pDevInsR0 = PDMDEVINS_2_R0PTR(pDevIns);
4203 pThis->pDevInsRC = PDMDEVINS_2_RCPTR(pDevIns);
4204 pThis->IBase.pfnQueryInterface = ichac97R3QueryInterface;
4205 RTListInit(&pThis->lstDrv);
4206
4207 /*
4208 * Validations.
4209 */
4210 if (!CFGMR3AreValuesValid(pCfg, "RZEnabled\0"
4211 "Codec\0"
4212 "TimerHz\0"
4213 "DebugEnabled\0"
4214 "DebugPathOut\0"))
4215 return PDMDEV_SET_ERROR(pDevIns, VERR_PDM_DEVINS_UNKNOWN_CFG_VALUES,
4216 N_("Invalid configuration for the AC'97 device"));
4217
4218 /*
4219 * Read config data.
4220 */
4221 int rc = CFGMR3QueryBoolDef(pCfg, "RZEnabled", &pThis->fRZEnabled, true);
4222 if (RT_FAILURE(rc))
4223 return PDMDEV_SET_ERROR(pDevIns, rc,
4224 N_("AC'97 configuration error: failed to read RCEnabled as boolean"));
4225
4226 char szCodec[20];
4227 rc = CFGMR3QueryStringDef(pCfg, "Codec", &szCodec[0], sizeof(szCodec), "STAC9700");
4228 if (RT_FAILURE(rc))
4229 return PDMDEV_SET_ERROR(pDevIns, VERR_PDM_DEVINS_UNKNOWN_CFG_VALUES,
4230 N_("AC'97 configuration error: Querying \"Codec\" as string failed"));
4231
4232 rc = CFGMR3QueryU16Def(pCfg, "TimerHz", &pThis->uTimerHz, AC97_TIMER_HZ_DEFAULT /* Default value, if not set. */);
4233 if (RT_FAILURE(rc))
4234 return PDMDEV_SET_ERROR(pDevIns, rc,
4235 N_("AC'97 configuration error: failed to read Hertz (Hz) rate as unsigned integer"));
4236
4237 if (pThis->uTimerHz != AC97_TIMER_HZ_DEFAULT)
4238 LogRel(("AC97: Using custom device timer rate (%RU16Hz)\n", pThis->uTimerHz));
4239
4240 rc = CFGMR3QueryBoolDef(pCfg, "DebugEnabled", &pThis->Dbg.fEnabled, false);
4241 if (RT_FAILURE(rc))
4242 return PDMDEV_SET_ERROR(pDevIns, rc,
4243 N_("AC97 configuration error: failed to read debugging enabled flag as boolean"));
4244
4245 rc = CFGMR3QueryStringDef(pCfg, "DebugPathOut", pThis->Dbg.szOutPath, sizeof(pThis->Dbg.szOutPath),
4246 VBOX_AUDIO_DEBUG_DUMP_PCM_DATA_PATH);
4247 if (RT_FAILURE(rc))
4248 return PDMDEV_SET_ERROR(pDevIns, rc,
4249 N_("AC97 configuration error: failed to read debugging output path flag as string"));
4250
4251 if (!strlen(pThis->Dbg.szOutPath))
4252 RTStrPrintf(pThis->Dbg.szOutPath, sizeof(pThis->Dbg.szOutPath), VBOX_AUDIO_DEBUG_DUMP_PCM_DATA_PATH);
4253
4254 if (pThis->Dbg.fEnabled)
4255 LogRel2(("AC97: Debug output will be saved to '%s'\n", pThis->Dbg.szOutPath));
4256
4257 /*
4258 * The AD1980 codec (with corresponding PCI subsystem vendor ID) is whitelisted
4259 * in the Linux kernel; Linux makes no attempt to measure the data rate and assumes
4260 * 48 kHz rate, which is exactly what we need. Same goes for AD1981B.
4261 */
4262 if (!strcmp(szCodec, "STAC9700"))
4263 pThis->uCodecModel = AC97_CODEC_STAC9700;
4264 else if (!strcmp(szCodec, "AD1980"))
4265 pThis->uCodecModel = AC97_CODEC_AD1980;
4266 else if (!strcmp(szCodec, "AD1981B"))
4267 pThis->uCodecModel = AC97_CODEC_AD1981B;
4268 else
4269 return PDMDevHlpVMSetError(pDevIns, VERR_PDM_DEVINS_UNKNOWN_CFG_VALUES, RT_SRC_POS,
4270 N_("AC'97 configuration error: The \"Codec\" value \"%s\" is unsupported"), szCodec);
4271
4272 LogRel(("AC97: Using codec '%s'\n", szCodec));
4273
4274 /*
4275 * Use an own critical section for the device instead of the default
4276 * one provided by PDM. This allows fine-grained locking in combination
4277 * with TM when timer-specific stuff is being called in e.g. the MMIO handlers.
4278 */
4279 rc = PDMDevHlpCritSectInit(pDevIns, &pThis->CritSect, RT_SRC_POS, "AC'97");
4280 AssertRCReturn(rc, rc);
4281
4282 rc = PDMDevHlpSetDeviceCritSect(pDevIns, PDMDevHlpCritSectGetNop(pDevIns));
4283 AssertRCReturn(rc, rc);
4284
4285 /*
4286 * Initialize data (most of it anyway).
4287 */
4288 /* PCI Device */
4289 PCIDevSetVendorId (&pThis->PciDev, 0x8086); /* 00 ro - intel. */ Assert(pThis->PciDev.abConfig[0x00] == 0x86); Assert(pThis->PciDev.abConfig[0x01] == 0x80);
4290 PCIDevSetDeviceId (&pThis->PciDev, 0x2415); /* 02 ro - 82801 / 82801aa(?). */ Assert(pThis->PciDev.abConfig[0x02] == 0x15); Assert(pThis->PciDev.abConfig[0x03] == 0x24);
4291 PCIDevSetCommand (&pThis->PciDev, 0x0000); /* 04 rw,ro - pcicmd. */ Assert(pThis->PciDev.abConfig[0x04] == 0x00); Assert(pThis->PciDev.abConfig[0x05] == 0x00);
4292 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);
4293 PCIDevSetRevisionId (&pThis->PciDev, 0x01); /* 08 ro - rid. */ Assert(pThis->PciDev.abConfig[0x08] == 0x01);
4294 PCIDevSetClassProg (&pThis->PciDev, 0x00); /* 09 ro - pi. */ Assert(pThis->PciDev.abConfig[0x09] == 0x00);
4295 PCIDevSetClassSub (&pThis->PciDev, 0x01); /* 0a ro - scc; 01 == Audio. */ Assert(pThis->PciDev.abConfig[0x0a] == 0x01);
4296 PCIDevSetClassBase (&pThis->PciDev, 0x04); /* 0b ro - bcc; 04 == multimedia.*/Assert(pThis->PciDev.abConfig[0x0b] == 0x04);
4297 PCIDevSetHeaderType (&pThis->PciDev, 0x00); /* 0e ro - headtyp. */ Assert(pThis->PciDev.abConfig[0x0e] == 0x00);
4298 PCIDevSetBaseAddress (&pThis->PciDev, 0, /* 10 rw - nambar - native audio mixer base. */
4299 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);
4300 PCIDevSetBaseAddress (&pThis->PciDev, 1, /* 14 rw - nabmbar - native audio bus mastering. */
4301 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);
4302 PCIDevSetInterruptLine(&pThis->PciDev, 0x00); /* 3c rw. */ Assert(pThis->PciDev.abConfig[0x3c] == 0x00);
4303 PCIDevSetInterruptPin (&pThis->PciDev, 0x01); /* 3d ro - INTA#. */ Assert(pThis->PciDev.abConfig[0x3d] == 0x01);
4304
4305 if (pThis->uCodecModel == AC97_CODEC_AD1980)
4306 {
4307 PCIDevSetSubSystemVendorId(&pThis->PciDev, 0x1028); /* 2c ro - Dell.) */
4308 PCIDevSetSubSystemId (&pThis->PciDev, 0x0177); /* 2e ro. */
4309 }
4310 else if (pThis->uCodecModel == AC97_CODEC_AD1981B)
4311 {
4312 PCIDevSetSubSystemVendorId(&pThis->PciDev, 0x1028); /* 2c ro - Dell.) */
4313 PCIDevSetSubSystemId (&pThis->PciDev, 0x01ad); /* 2e ro. */
4314 }
4315 else
4316 {
4317 PCIDevSetSubSystemVendorId(&pThis->PciDev, 0x8086); /* 2c ro - Intel.) */
4318 PCIDevSetSubSystemId (&pThis->PciDev, 0x0000); /* 2e ro. */
4319 }
4320
4321 /*
4322 * Register the PCI device, it's I/O regions, the timer and the
4323 * saved state item.
4324 */
4325 rc = PDMDevHlpPCIRegister(pDevIns, &pThis->PciDev);
4326 if (RT_FAILURE(rc))
4327 return rc;
4328
4329 rc = PDMDevHlpPCIIORegionRegister(pDevIns, 0, 256, PCI_ADDRESS_SPACE_IO, ichac97R3IOPortMap);
4330 if (RT_FAILURE(rc))
4331 return rc;
4332
4333 rc = PDMDevHlpPCIIORegionRegister(pDevIns, 1, 64, PCI_ADDRESS_SPACE_IO, ichac97R3IOPortMap);
4334 if (RT_FAILURE(rc))
4335 return rc;
4336
4337 rc = PDMDevHlpSSMRegister(pDevIns, AC97_SSM_VERSION, sizeof(*pThis), ichac97R3SaveExec, ichac97R3LoadExec);
4338 if (RT_FAILURE(rc))
4339 return rc;
4340
4341# ifdef VBOX_WITH_AUDIO_AC97_ASYNC_IO
4342 LogRel(("AC97: Asynchronous I/O enabled\n"));
4343# endif
4344
4345 /*
4346 * Attach driver.
4347 */
4348 uint8_t uLUN;
4349 for (uLUN = 0; uLUN < UINT8_MAX; ++uLUN)
4350 {
4351 LogFunc(("Trying to attach driver for LUN #%RU8 ...\n", uLUN));
4352 rc = ichac97R3AttachInternal(pThis, uLUN, 0 /* fFlags */, NULL /* ppDrv */);
4353 if (RT_FAILURE(rc))
4354 {
4355 if (rc == VERR_PDM_NO_ATTACHED_DRIVER)
4356 rc = VINF_SUCCESS;
4357 else if (rc == VERR_AUDIO_BACKEND_INIT_FAILED)
4358 {
4359 ichac97R3ReattachInternal(pThis, NULL /* pDrv */, uLUN, "NullAudio");
4360 PDMDevHlpVMSetRuntimeError(pDevIns, 0 /*fFlags*/, "HostAudioNotResponding",
4361 N_("Host audio backend initialization has failed. Selecting the NULL audio backend "
4362 "with the consequence that no sound is audible"));
4363 /* Attaching to the NULL audio backend will never fail. */
4364 rc = VINF_SUCCESS;
4365 }
4366 break;
4367 }
4368 }
4369
4370 LogFunc(("cLUNs=%RU8, rc=%Rrc\n", uLUN, rc));
4371
4372 if (RT_SUCCESS(rc))
4373 {
4374 rc = AudioMixerCreate("AC'97 Mixer", 0 /* uFlags */, &pThis->pMixer);
4375 if (RT_SUCCESS(rc))
4376 {
4377 rc = AudioMixerCreateSink(pThis->pMixer, "[Recording] Line In", AUDMIXSINKDIR_INPUT, &pThis->pSinkLineIn);
4378 AssertRC(rc);
4379 rc = AudioMixerCreateSink(pThis->pMixer, "[Recording] Microphone In", AUDMIXSINKDIR_INPUT, &pThis->pSinkMicIn);
4380 AssertRC(rc);
4381 rc = AudioMixerCreateSink(pThis->pMixer, "[Playback] PCM Output", AUDMIXSINKDIR_OUTPUT, &pThis->pSinkOut);
4382 AssertRC(rc);
4383 }
4384 }
4385
4386 if (RT_SUCCESS(rc))
4387 {
4388 /*
4389 * Create all hardware streams.
4390 */
4391 for (unsigned i = 0; i < AC97_MAX_STREAMS; i++)
4392 {
4393 int rc2 = ichac97R3StreamCreate(pThis, &pThis->aStreams[i], i /* SD# */);
4394 AssertRC(rc2);
4395 if (RT_SUCCESS(rc))
4396 rc = rc2;
4397 }
4398
4399# ifdef VBOX_WITH_AUDIO_AC97_ONETIME_INIT
4400 PAC97DRIVER pDrv;
4401 RTListForEach(&pThis->lstDrv, pDrv, AC97DRIVER, Node)
4402 {
4403 /*
4404 * Only primary drivers are critical for the VM to run. Everything else
4405 * might not worth showing an own error message box in the GUI.
4406 */
4407 if (!(pDrv->fFlags & PDMAUDIODRVFLAGS_PRIMARY))
4408 continue;
4409
4410 PPDMIAUDIOCONNECTOR pCon = pDrv->pConnector;
4411 AssertPtr(pCon);
4412
4413 bool fValidLineIn = AudioMixerStreamIsValid(pDrv->LineIn.pMixStrm);
4414 bool fValidMicIn = AudioMixerStreamIsValid(pDrv->MicIn.pMixStrm);
4415 bool fValidOut = AudioMixerStreamIsValid(pDrv->Out.pMixStrm);
4416
4417 if ( !fValidLineIn
4418 && !fValidMicIn
4419 && !fValidOut)
4420 {
4421 LogRel(("AC97: Falling back to NULL backend (no sound audible)\n"));
4422
4423 ichac97R3Reset(pDevIns);
4424 ichac97R3ReattachInternal(pThis, pDrv, pDrv->uLUN, "NullAudio");
4425
4426 PDMDevHlpVMSetRuntimeError(pDevIns, 0 /*fFlags*/, "HostAudioNotResponding",
4427 N_("No audio devices could be opened. Selecting the NULL audio backend "
4428 "with the consequence that no sound is audible"));
4429 }
4430 else
4431 {
4432 bool fWarn = false;
4433
4434 PDMAUDIOBACKENDCFG backendCfg;
4435 int rc2 = pCon->pfnGetConfig(pCon, &backendCfg);
4436 if (RT_SUCCESS(rc2))
4437 {
4438 if (backendCfg.cMaxStreamsIn)
4439 {
4440 /* If the audio backend supports two or more input streams at once,
4441 * warn if one of our two inputs (microphone-in and line-in) failed to initialize. */
4442 if (backendCfg.cMaxStreamsIn >= 2)
4443 fWarn = !fValidLineIn || !fValidMicIn;
4444 /* If the audio backend only supports one input stream at once (e.g. pure ALSA, and
4445 * *not* ALSA via PulseAudio plugin!), only warn if both of our inputs failed to initialize.
4446 * One of the two simply is not in use then. */
4447 else if (backendCfg.cMaxStreamsIn == 1)
4448 fWarn = !fValidLineIn && !fValidMicIn;
4449 /* Don't warn if our backend is not able of supporting any input streams at all. */
4450 }
4451
4452 if ( !fWarn
4453 && backendCfg.cMaxStreamsOut)
4454 {
4455 fWarn = !fValidOut;
4456 }
4457 }
4458 else
4459 {
4460 LogRel(("AC97: Unable to retrieve audio backend configuration for LUN #%RU8, rc=%Rrc\n", pDrv->uLUN, rc2));
4461 fWarn = true;
4462 }
4463
4464 if (fWarn)
4465 {
4466 char szMissingStreams[255] = "";
4467 size_t len = 0;
4468 if (!fValidLineIn)
4469 {
4470 LogRel(("AC97: WARNING: Unable to open PCM line input for LUN #%RU8!\n", pDrv->uLUN));
4471 len = RTStrPrintf(szMissingStreams, sizeof(szMissingStreams), "PCM Input");
4472 }
4473 if (!fValidMicIn)
4474 {
4475 LogRel(("AC97: WARNING: Unable to open PCM microphone input for LUN #%RU8!\n", pDrv->uLUN));
4476 len += RTStrPrintf(szMissingStreams + len,
4477 sizeof(szMissingStreams) - len, len ? ", PCM Microphone" : "PCM Microphone");
4478 }
4479 if (!fValidOut)
4480 {
4481 LogRel(("AC97: WARNING: Unable to open PCM output for LUN #%RU8!\n", pDrv->uLUN));
4482 len += RTStrPrintf(szMissingStreams + len,
4483 sizeof(szMissingStreams) - len, len ? ", PCM Output" : "PCM Output");
4484 }
4485
4486 PDMDevHlpVMSetRuntimeError(pDevIns, 0 /*fFlags*/, "HostAudioNotResponding",
4487 N_("Some AC'97 audio streams (%s) could not be opened. Guest applications generating audio "
4488 "output or depending on audio input may hang. Make sure your host audio device "
4489 "is working properly. Check the logfile for error messages of the audio "
4490 "subsystem"), szMissingStreams);
4491 }
4492 }
4493 }
4494# endif /* VBOX_WITH_AUDIO_AC97_ONETIME_INIT */
4495 }
4496
4497 if (RT_SUCCESS(rc))
4498 ichac97R3Reset(pDevIns);
4499
4500 if (RT_SUCCESS(rc))
4501 {
4502 static const char * const s_apszNames[] =
4503 {
4504 "AC97 PI", "AC97 PO", "AC97 MC"
4505 };
4506 AssertCompile(RT_ELEMENTS(s_apszNames) == AC97_MAX_STREAMS);
4507
4508 for (unsigned i = 0; i < AC97_MAX_STREAMS; i++)
4509 {
4510 /* Create the emulation timer (per stream).
4511 *
4512 * Note: Use TMCLOCK_VIRTUAL_SYNC here, as the guest's AC'97 driver
4513 * relies on exact (virtual) DMA timing and uses DMA Position Buffers
4514 * instead of the LPIB registers.
4515 */
4516 rc = PDMDevHlpTMTimerCreate(pDevIns, TMCLOCK_VIRTUAL_SYNC, ichac97R3Timer, &pThis->aStreams[i],
4517 TMTIMER_FLAGS_NO_CRIT_SECT, s_apszNames[i], &pThis->pTimerR3[i]);
4518 AssertRCReturn(rc, rc);
4519 pThis->pTimerR0[i] = TMTimerR0Ptr(pThis->pTimerR3[i]);
4520 pThis->pTimerRC[i] = TMTimerRCPtr(pThis->pTimerR3[i]);
4521
4522 /* Use our own critcal section for the device timer.
4523 * That way we can control more fine-grained when to lock what. */
4524 rc = TMR3TimerSetCritSect(pThis->pTimerR3[i], &pThis->CritSect);
4525 AssertRCReturn(rc, rc);
4526 }
4527 }
4528
4529# ifdef VBOX_WITH_STATISTICS
4530 if (RT_SUCCESS(rc))
4531 {
4532 /*
4533 * Register statistics.
4534 */
4535 PDMDevHlpSTAMRegister(pDevIns, &pThis->StatTimer, STAMTYPE_PROFILE, "/Devices/AC97/Timer", STAMUNIT_TICKS_PER_CALL, "Profiling ichac97Timer.");
4536 PDMDevHlpSTAMRegister(pDevIns, &pThis->StatIn, STAMTYPE_PROFILE, "/Devices/AC97/Input", STAMUNIT_TICKS_PER_CALL, "Profiling input.");
4537 PDMDevHlpSTAMRegister(pDevIns, &pThis->StatOut, STAMTYPE_PROFILE, "/Devices/AC97/Output", STAMUNIT_TICKS_PER_CALL, "Profiling output.");
4538 PDMDevHlpSTAMRegister(pDevIns, &pThis->StatBytesRead, STAMTYPE_COUNTER, "/Devices/AC97/BytesRead" , STAMUNIT_BYTES, "Bytes read from AC97 emulation.");
4539 PDMDevHlpSTAMRegister(pDevIns, &pThis->StatBytesWritten, STAMTYPE_COUNTER, "/Devices/AC97/BytesWritten", STAMUNIT_BYTES, "Bytes written to AC97 emulation.");
4540 }
4541# endif
4542
4543 LogFlowFuncLeaveRC(rc);
4544 return rc;
4545}
4546
4547#endif /* !IN_RING3 */
4548
4549/**
4550 * The device registration structure.
4551 */
4552const PDMDEVREG g_DeviceICHAC97 =
4553{
4554 /* .u32Version = */ PDM_DEVREG_VERSION,
4555 /* .uReserved0 = */ 0,
4556 /* .szName = */ "ichac97",
4557 /* .fFlags = */ PDM_DEVREG_FLAGS_DEFAULT_BITS | PDM_DEVREG_FLAGS_RC | PDM_DEVREG_FLAGS_R0,
4558 /* .fClass = */ PDM_DEVREG_CLASS_AUDIO,
4559 /* .cMaxInstances = */ 1,
4560 /* .uSharedVersion = */ 42,
4561 /* .cbInstanceShared = */ sizeof(AC97STATE),
4562 /* .cbInstanceCC = */ 0,
4563 /* .cbInstanceRC = */ 0,
4564 /* .cMaxPciDevices = */ 1,
4565 /* .cMaxMsixVectors = */ 0,
4566 /* .pszDescription = */ "ICH AC'97 Audio Controller",
4567#if defined(IN_RING3)
4568 /* .pszRCMod = */ "VBoxDDRC.rc",
4569 /* .pszR0Mod = */ "VBoxDDR0.r0",
4570 /* .pfnConstruct = */ ichac97R3Construct,
4571 /* .pfnDestruct = */ ichac97R3Destruct,
4572 /* .pfnRelocate = */ ichac97R3Relocate,
4573 /* .pfnMemSetup = */ NULL,
4574 /* .pfnPowerOn = */ NULL,
4575 /* .pfnReset = */ ichac97R3Reset,
4576 /* .pfnSuspend = */ NULL,
4577 /* .pfnResume = */ NULL,
4578 /* .pfnAttach = */ ichac97R3Attach,
4579 /* .pfnDetach = */ ichac97R3Detach,
4580 /* .pfnQueryInterface = */ NULL,
4581 /* .pfnInitComplete = */ NULL,
4582 /* .pfnPowerOff = */ ichac97R3PowerOff,
4583 /* .pfnSoftReset = */ NULL,
4584 /* .pfnReserved0 = */ NULL,
4585 /* .pfnReserved1 = */ NULL,
4586 /* .pfnReserved2 = */ NULL,
4587 /* .pfnReserved3 = */ NULL,
4588 /* .pfnReserved4 = */ NULL,
4589 /* .pfnReserved5 = */ NULL,
4590 /* .pfnReserved6 = */ NULL,
4591 /* .pfnReserved7 = */ NULL,
4592#elif defined(IN_RING0)
4593 /* .pfnEarlyConstruct = */ NULL,
4594 /* .pfnConstruct = */ NULL,
4595 /* .pfnDestruct = */ NULL,
4596 /* .pfnFinalDestruct = */ NULL,
4597 /* .pfnRequest = */ NULL,
4598 /* .pfnReserved0 = */ NULL,
4599 /* .pfnReserved1 = */ NULL,
4600 /* .pfnReserved2 = */ NULL,
4601 /* .pfnReserved3 = */ NULL,
4602 /* .pfnReserved4 = */ NULL,
4603 /* .pfnReserved5 = */ NULL,
4604 /* .pfnReserved6 = */ NULL,
4605 /* .pfnReserved7 = */ NULL,
4606#elif defined(IN_RC)
4607 /* .pfnConstruct = */ NULL,
4608 /* .pfnReserved0 = */ NULL,
4609 /* .pfnReserved1 = */ NULL,
4610 /* .pfnReserved2 = */ NULL,
4611 /* .pfnReserved3 = */ NULL,
4612 /* .pfnReserved4 = */ NULL,
4613 /* .pfnReserved5 = */ NULL,
4614 /* .pfnReserved6 = */ NULL,
4615 /* .pfnReserved7 = */ NULL,
4616#else
4617# error "Not in IN_RING3, IN_RING0 or IN_RC!"
4618#endif
4619 /* .u32VersionEnd = */ PDM_DEVREG_VERSION
4620};
4621
4622#endif /* !VBOX_DEVICE_STRUCT_TESTCASE */
4623
注意: 瀏覽 TracBrowser 來幫助您使用儲存庫瀏覽器

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