VirtualBox

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

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

Audio/AC97: Only expose VRA / VRM (variable rates) features if we really offer support for it (VBOX_WITH_AC97_VRA and VBOX_WITH_AC97_VRM, both currently disabled).

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

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