VirtualBox

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

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

Audio: Try to fix a hang w/ VRDE audio driver enabled.

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