VirtualBox

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

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

Audio/AC97: Added more code for transfer calculation for helping with A/V synchronization.

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 160.7 KB
Line 
1/* $Id: DevIchAc97.cpp 76862 2019-01-17 13:58:54Z 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 (RT_FAILURE(rc))
1218 break;
1219
1220 Assert(cbLeft >= cbWritten);
1221 cbLeft -= cbWritten;
1222
1223 cbReadTotal += cbWritten;
1224 }
1225
1226 if (pcbRead)
1227 *pcbRead = cbReadTotal;
1228
1229 return rc;
1230}
1231
1232# ifdef VBOX_WITH_AUDIO_AC97_ASYNC_IO
1233
1234/**
1235 * Asynchronous I/O thread for an AC'97 stream.
1236 * This will do the heavy lifting work for us as soon as it's getting notified by another thread.
1237 *
1238 * @returns IPRT status code.
1239 * @param hThreadSelf Thread handle.
1240 * @param pvUser User argument. Must be of type PAC97STREAMTHREADCTX.
1241 */
1242static DECLCALLBACK(int) ichac97R3StreamAsyncIOThread(RTTHREAD hThreadSelf, void *pvUser)
1243{
1244 PAC97STREAMTHREADCTX pCtx = (PAC97STREAMTHREADCTX)pvUser;
1245 AssertPtr(pCtx);
1246
1247 PAC97STATE pThis = pCtx->pThis;
1248 AssertPtr(pThis);
1249
1250 PAC97STREAM pStream = pCtx->pStream;
1251 AssertPtr(pStream);
1252
1253 PAC97STREAMSTATEAIO pAIO = &pCtx->pStream->State.AIO;
1254
1255 ASMAtomicXchgBool(&pAIO->fStarted, true);
1256
1257 RTThreadUserSignal(hThreadSelf);
1258
1259 LogFunc(("[SD%RU8] Started\n", pStream->u8SD));
1260
1261 for (;;)
1262 {
1263 Log2Func(("[SD%RU8] Waiting ...\n", pStream->u8SD));
1264
1265 int rc2 = RTSemEventWait(pAIO->Event, RT_INDEFINITE_WAIT);
1266 if (RT_FAILURE(rc2))
1267 break;
1268
1269 if (ASMAtomicReadBool(&pAIO->fShutdown))
1270 break;
1271
1272 rc2 = RTCritSectEnter(&pAIO->CritSect);
1273 if (RT_SUCCESS(rc2))
1274 {
1275 if (!pAIO->fEnabled)
1276 {
1277 RTCritSectLeave(&pAIO->CritSect);
1278 continue;
1279 }
1280
1281 ichac97R3StreamUpdate(pThis, pStream, false /* fInTimer */);
1282
1283 int rc3 = RTCritSectLeave(&pAIO->CritSect);
1284 AssertRC(rc3);
1285 }
1286
1287 AssertRC(rc2);
1288 }
1289
1290 LogFunc(("[SD%RU8] Ended\n", pStream->u8SD));
1291
1292 ASMAtomicXchgBool(&pAIO->fStarted, false);
1293
1294 return VINF_SUCCESS;
1295}
1296
1297/**
1298 * Creates the async I/O thread for a specific AC'97 audio stream.
1299 *
1300 * @returns IPRT status code.
1301 * @param pThis AC'97 state.
1302 * @param pStream AC'97 audio stream to create the async I/O thread for.
1303 */
1304static int ichac97R3StreamAsyncIOCreate(PAC97STATE pThis, PAC97STREAM pStream)
1305{
1306 PAC97STREAMSTATEAIO pAIO = &pStream->State.AIO;
1307
1308 int rc;
1309
1310 if (!ASMAtomicReadBool(&pAIO->fStarted))
1311 {
1312 pAIO->fShutdown = false;
1313 pAIO->fEnabled = true; /* Enabled by default. */
1314
1315 rc = RTSemEventCreate(&pAIO->Event);
1316 if (RT_SUCCESS(rc))
1317 {
1318 rc = RTCritSectInit(&pAIO->CritSect);
1319 if (RT_SUCCESS(rc))
1320 {
1321 AC97STREAMTHREADCTX Ctx = { pThis, pStream };
1322
1323 char szThreadName[64];
1324 RTStrPrintf2(szThreadName, sizeof(szThreadName), "ac97AIO%RU8", pStream->u8SD);
1325
1326 rc = RTThreadCreate(&pAIO->Thread, ichac97R3StreamAsyncIOThread, &Ctx,
1327 0, RTTHREADTYPE_IO, RTTHREADFLAGS_WAITABLE, szThreadName);
1328 if (RT_SUCCESS(rc))
1329 rc = RTThreadUserWait(pAIO->Thread, 10 * 1000 /* 10s timeout */);
1330 }
1331 }
1332 }
1333 else
1334 rc = VINF_SUCCESS;
1335
1336 LogFunc(("[SD%RU8] Returning %Rrc\n", pStream->u8SD, rc));
1337 return rc;
1338}
1339
1340/**
1341 * Destroys the async I/O thread of a specific AC'97 audio stream.
1342 *
1343 * @returns IPRT status code.
1344 * @param pThis AC'97 state.
1345 * @param pStream AC'97 audio stream to destroy the async I/O thread for.
1346 */
1347static int ichac97R3StreamAsyncIODestroy(PAC97STATE pThis, PAC97STREAM pStream)
1348{
1349 PAC97STREAMSTATEAIO pAIO = &pStream->State.AIO;
1350
1351 if (!ASMAtomicReadBool(&pAIO->fStarted))
1352 return VINF_SUCCESS;
1353
1354 ASMAtomicWriteBool(&pAIO->fShutdown, true);
1355
1356 int rc = ichac97R3StreamAsyncIONotify(pThis, pStream);
1357 AssertRC(rc);
1358
1359 int rcThread;
1360 rc = RTThreadWait(pAIO->Thread, 30 * 1000 /* 30s timeout */, &rcThread);
1361 LogFunc(("Async I/O thread ended with %Rrc (%Rrc)\n", rc, rcThread));
1362
1363 if (RT_SUCCESS(rc))
1364 {
1365 rc = RTCritSectDelete(&pAIO->CritSect);
1366 AssertRC(rc);
1367
1368 rc = RTSemEventDestroy(pAIO->Event);
1369 AssertRC(rc);
1370
1371 pAIO->fStarted = false;
1372 pAIO->fShutdown = false;
1373 pAIO->fEnabled = false;
1374 }
1375
1376 LogFunc(("[SD%RU8] Returning %Rrc\n", pStream->u8SD, rc));
1377 return rc;
1378}
1379
1380/**
1381 * Lets the stream's async I/O thread know that there is some data to process.
1382 *
1383 * @returns IPRT status code.
1384 * @param pThis AC'97 state.
1385 * @param pStream AC'97 stream to notify async I/O thread for.
1386 */
1387static int ichac97R3StreamAsyncIONotify(PAC97STATE pThis, PAC97STREAM pStream)
1388{
1389 RT_NOREF(pThis);
1390
1391 LogFunc(("[SD%RU8]\n", pStream->u8SD));
1392 return RTSemEventSignal(pStream->State.AIO.Event);
1393}
1394
1395/**
1396 * Locks the async I/O thread of a specific AC'97 audio stream.
1397 *
1398 * @param pStream AC'97 stream to lock async I/O thread for.
1399 */
1400static void ichac97R3StreamAsyncIOLock(PAC97STREAM pStream)
1401{
1402 PAC97STREAMSTATEAIO pAIO = &pStream->State.AIO;
1403
1404 if (!ASMAtomicReadBool(&pAIO->fStarted))
1405 return;
1406
1407 int rc2 = RTCritSectEnter(&pAIO->CritSect);
1408 AssertRC(rc2);
1409}
1410
1411/**
1412 * Unlocks the async I/O thread of a specific AC'97 audio stream.
1413 *
1414 * @param pStream AC'97 stream to unlock async I/O thread for.
1415 */
1416static void ichac97R3StreamAsyncIOUnlock(PAC97STREAM pStream)
1417{
1418 PAC97STREAMSTATEAIO pAIO = &pStream->State.AIO;
1419
1420 if (!ASMAtomicReadBool(&pAIO->fStarted))
1421 return;
1422
1423 int rc2 = RTCritSectLeave(&pAIO->CritSect);
1424 AssertRC(rc2);
1425}
1426
1427#if 0 /* Unused */
1428/**
1429 * Enables (resumes) or disables (pauses) the async I/O thread.
1430 *
1431 * @param pStream AC'97 stream to enable/disable async I/O thread for.
1432 * @param fEnable Whether to enable or disable the I/O thread.
1433 *
1434 * @remarks Does not do locking.
1435 */
1436static void ichac97R3StreamAsyncIOEnable(PAC97STREAM pStream, bool fEnable)
1437{
1438 PAC97STREAMSTATEAIO pAIO = &pStream->State.AIO;
1439 ASMAtomicXchgBool(&pAIO->fEnabled, fEnable);
1440}
1441#endif
1442# endif /* VBOX_WITH_AUDIO_AC97_ASYNC_IO */
1443
1444# ifdef LOG_ENABLED
1445static void ichac97R3BDLEDumpAll(PAC97STATE pThis, uint64_t u64BDLBase, uint16_t cBDLE)
1446{
1447 LogFlowFunc(("BDLEs @ 0x%x (%RU16):\n", u64BDLBase, cBDLE));
1448 if (!u64BDLBase)
1449 return;
1450
1451 uint32_t cbBDLE = 0;
1452 for (uint16_t i = 0; i < cBDLE; i++)
1453 {
1454 AC97BDLE BDLE;
1455 PDMDevHlpPhysRead(pThis->CTX_SUFF(pDevIns), u64BDLBase + i * sizeof(AC97BDLE), &BDLE, sizeof(AC97BDLE));
1456
1457# ifndef RT_LITTLE_ENDIAN
1458# error "Please adapt the code (audio buffers are little endian)!"
1459# else
1460 BDLE.addr = RT_H2LE_U32(BDLE.addr & ~3);
1461 BDLE.ctl_len = RT_H2LE_U32(BDLE.ctl_len);
1462#endif
1463 LogFunc(("\t#%03d BDLE(adr:0x%llx, size:%RU32 [%RU32 bytes], bup:%RTbool, ioc:%RTbool)\n",
1464 i, BDLE.addr,
1465 BDLE.ctl_len & AC97_BD_LEN_MASK,
1466 (BDLE.ctl_len & AC97_BD_LEN_MASK) << 1, /** @todo r=andy Assumes 16bit samples. */
1467 RT_BOOL(BDLE.ctl_len & AC97_BD_BUP),
1468 RT_BOOL(BDLE.ctl_len & AC97_BD_IOC)));
1469
1470 cbBDLE += (BDLE.ctl_len & AC97_BD_LEN_MASK) << 1; /** @todo r=andy Ditto. */
1471 }
1472
1473 LogFlowFunc(("Total: %RU32 bytes\n", cbBDLE));
1474}
1475# endif /* LOG_ENABLED */
1476
1477/**
1478 * Updates an AC'97 stream by doing its required data transfers.
1479 * The host sink(s) set the overall pace.
1480 *
1481 * This routine is called by both, the synchronous and the asynchronous
1482 * (VBOX_WITH_AUDIO_AC97_ASYNC_IO), implementations.
1483 *
1484 * When running synchronously, the device DMA transfers *and* the mixer sink
1485 * processing is within the device timer.
1486 *
1487 * When running asynchronously, only the device DMA transfers are done in the
1488 * device timer, whereas the mixer sink processing then is done in the stream's
1489 * own async I/O thread. This thread also will call this function
1490 * (with fInTimer set to @c false).
1491 *
1492 * @param pThis AC'97 state.
1493 * @param pStream AC'97 stream to update.
1494 * @param fInTimer Whether to this function was called from the timer
1495 * context or an asynchronous I/O stream thread (if supported).
1496 */
1497static void ichac97R3StreamUpdate(PAC97STATE pThis, PAC97STREAM pStream, bool fInTimer)
1498{
1499 RT_NOREF(fInTimer);
1500
1501 PAUDMIXSINK pSink = ichac97R3IndexToSink(pThis, pStream->u8SD);
1502 AssertPtr(pSink);
1503
1504 if (!AudioMixerSinkIsActive(pSink)) /* No sink available? Bail out. */
1505 return;
1506
1507 int rc2;
1508
1509 if (pStream->State.Cfg.enmDir == PDMAUDIODIR_OUT) /* Output (SDO). */
1510 {
1511# ifdef VBOX_WITH_AUDIO_AC97_ASYNC_IO
1512 if (fInTimer)
1513# endif
1514 {
1515 const uint32_t cbStreamFree = ichac97R3StreamGetFree(pStream);
1516 if (cbStreamFree)
1517 {
1518 Log3Func(("[SD%RU8] PICB=%zu (%RU64ms), cbFree=%zu (%RU64ms), cbTransferChunk=%zu (%RU64ms)\n",
1519 pStream->u8SD,
1520 (pStream->Regs.picb << 1), DrvAudioHlpBytesToMilli((pStream->Regs.picb << 1), &pStream->State.Cfg.Props),
1521 cbStreamFree, DrvAudioHlpBytesToMilli(cbStreamFree, &pStream->State.Cfg.Props),
1522 pStream->State.cbTransferChunk, DrvAudioHlpBytesToMilli(pStream->State.cbTransferChunk, &pStream->State.Cfg.Props)));
1523
1524 /* Do the DMA transfer. */
1525 rc2 = ichac97R3StreamTransfer(pThis, pStream, RT_MIN(pStream->State.cbTransferChunk, cbStreamFree));
1526 AssertRC(rc2);
1527
1528 pStream->State.tsLastUpdateNs = RTTimeNanoTS();
1529 }
1530 }
1531
1532 Log3Func(("[SD%RU8] fInTimer=%RTbool\n", pStream->u8SD, fInTimer));
1533
1534# ifdef VBOX_WITH_AUDIO_AC97_ASYNC_IO
1535 rc2 = ichac97R3StreamAsyncIONotify(pThis, pStream);
1536 AssertRC(rc2);
1537# endif
1538
1539# ifdef VBOX_WITH_AUDIO_AC97_ASYNC_IO
1540 if (!fInTimer) /* In async I/O thread */
1541 {
1542# endif
1543 const uint32_t cbSinkWritable = AudioMixerSinkGetWritable(pSink);
1544 const uint32_t cbStreamReadable = ichac97R3StreamGetUsed(pStream);
1545 const uint32_t cbToReadFromStream = RT_MIN(cbStreamReadable, cbSinkWritable);
1546
1547 Log3Func(("[SD%RU8] cbSinkWritable=%RU32, cbStreamReadable=%RU32\n", pStream->u8SD, cbSinkWritable, cbStreamReadable));
1548
1549 if (cbToReadFromStream)
1550 {
1551 /* Read (guest output) data and write it to the stream's sink. */
1552 rc2 = ichac97R3StreamRead(pThis, pStream, pSink, cbToReadFromStream, NULL);
1553 AssertRC(rc2);
1554 }
1555# ifdef VBOX_WITH_AUDIO_AC97_ASYNC_IO
1556 }
1557#endif
1558 /* When running synchronously, update the associated sink here.
1559 * Otherwise this will be done in the async I/O thread. */
1560 rc2 = AudioMixerSinkUpdate(pSink);
1561 AssertRC(rc2);
1562 }
1563 else /* Input (SDI). */
1564 {
1565# ifdef VBOX_WITH_AUDIO_AC97_ASYNC_IO
1566 if (!fInTimer)
1567 {
1568# endif
1569 rc2 = AudioMixerSinkUpdate(pSink);
1570 AssertRC(rc2);
1571
1572 /* Is the sink ready to be read (host input data) from? If so, by how much? */
1573 uint32_t cbSinkReadable = AudioMixerSinkGetReadable(pSink);
1574
1575 /* How much (guest input) data is available for writing at the moment for the AC'97 stream? */
1576 uint32_t cbStreamFree = ichac97R3StreamGetFree(pStream);
1577
1578 Log3Func(("[SD%RU8] cbSinkReadable=%RU32, cbStreamFree=%RU32\n", pStream->u8SD, cbSinkReadable, cbStreamFree));
1579
1580 /* Do not read more than the sink can provide at the moment.
1581 * The host sets the overall pace. */
1582 if (cbSinkReadable > cbStreamFree)
1583 cbSinkReadable = cbStreamFree;
1584
1585 if (cbSinkReadable)
1586 {
1587 /* Write (guest input) data to the stream which was read from stream's sink before. */
1588 rc2 = ichac97R3StreamWrite(pThis, pStream, pSink, cbSinkReadable, NULL /* pcbWritten */);
1589 AssertRC(rc2);
1590 }
1591# ifdef VBOX_WITH_AUDIO_AC97_ASYNC_IO
1592 }
1593 else /* fInTimer */
1594 {
1595# endif
1596
1597# ifdef VBOX_WITH_AUDIO_AC97_ASYNC_IO
1598 const uint64_t tsNowNs = RTTimeNanoTS();
1599 if (tsNowNs - pStream->State.tsLastUpdateNs >= pStream->State.Cfg.Device.uSchedulingHintMs * RT_NS_1MS)
1600 {
1601 rc2 = ichac97R3StreamAsyncIONotify(pThis, pStream);
1602 AssertRC(rc2);
1603
1604 pStream->State.tsLastUpdateNs = tsNowNs;
1605 }
1606# endif
1607
1608 const uint32_t cbStreamUsed = ichac97R3StreamGetUsed(pStream);
1609 if (cbStreamUsed)
1610 {
1611 /* When running synchronously, do the DMA data transfers here.
1612 * Otherwise this will be done in the stream's async I/O thread. */
1613 rc2 = ichac97R3StreamTransfer(pThis, pStream, cbStreamUsed);
1614 AssertRC(rc2);
1615 }
1616# ifdef VBOX_WITH_AUDIO_AC97_ASYNC_IO
1617 }
1618# endif
1619 }
1620}
1621
1622#endif /* IN_RING3 */
1623
1624/**
1625 * Sets a AC'97 mixer control to a specific value.
1626 *
1627 * @returns IPRT status code.
1628 * @param pThis AC'97 state.
1629 * @param uMixerIdx Mixer control to set value for.
1630 * @param uVal Value to set.
1631 */
1632static void ichac97MixerSet(PAC97STATE pThis, uint8_t uMixerIdx, uint16_t uVal)
1633{
1634 AssertMsgReturnVoid(uMixerIdx + 2U <= sizeof(pThis->mixer_data),
1635 ("Index %RU8 out of bounds (%zu)\n", uMixerIdx, sizeof(pThis->mixer_data)));
1636 pThis->mixer_data[uMixerIdx + 0] = RT_LO_U8(uVal);
1637 pThis->mixer_data[uMixerIdx + 1] = RT_HI_U8(uVal);
1638}
1639
1640/**
1641 * Gets a value from a specific AC'97 mixer control.
1642 *
1643 * @returns Retrieved mixer control value.
1644 * @param pThis AC'97 state.
1645 * @param uMixerIdx Mixer control to get value for.
1646 */
1647static uint16_t ichac97MixerGet(PAC97STATE pThis, uint32_t uMixerIdx)
1648{
1649 AssertMsgReturn(uMixerIdx + 2U <= sizeof(pThis->mixer_data),
1650 ("Index %RU8 out of bounds (%zu)\n", uMixerIdx, sizeof(pThis->mixer_data)),
1651 UINT16_MAX);
1652 return RT_MAKE_U16(pThis->mixer_data[uMixerIdx + 0], pThis->mixer_data[uMixerIdx + 1]);
1653}
1654
1655#ifdef IN_RING3
1656
1657/**
1658 * Retrieves a specific driver stream of a AC'97 driver.
1659 *
1660 * @returns Pointer to driver stream if found, or NULL if not found.
1661 * @param pThis AC'97 state.
1662 * @param pDrv Driver to retrieve driver stream for.
1663 * @param enmDir Stream direction to retrieve.
1664 * @param dstSrc Stream destination / source to retrieve.
1665 */
1666static PAC97DRIVERSTREAM ichac97R3MixerGetDrvStream(PAC97STATE pThis, PAC97DRIVER pDrv,
1667 PDMAUDIODIR enmDir, PDMAUDIODESTSOURCE dstSrc)
1668{
1669 RT_NOREF(pThis);
1670
1671 PAC97DRIVERSTREAM pDrvStream = NULL;
1672
1673 if (enmDir == PDMAUDIODIR_IN)
1674 {
1675 LogFunc(("enmRecSource=%d\n", dstSrc.Source));
1676
1677 switch (dstSrc.Source)
1678 {
1679 case PDMAUDIORECSOURCE_LINE:
1680 pDrvStream = &pDrv->LineIn;
1681 break;
1682 case PDMAUDIORECSOURCE_MIC:
1683 pDrvStream = &pDrv->MicIn;
1684 break;
1685 default:
1686 AssertFailed();
1687 break;
1688 }
1689 }
1690 else if (enmDir == PDMAUDIODIR_OUT)
1691 {
1692 LogFunc(("enmPlaybackDest=%d\n", dstSrc.Dest));
1693
1694 switch (dstSrc.Dest)
1695 {
1696 case PDMAUDIOPLAYBACKDEST_FRONT:
1697 pDrvStream = &pDrv->Out;
1698 break;
1699 default:
1700 AssertFailed();
1701 break;
1702 }
1703 }
1704 else
1705 AssertFailed();
1706
1707 return pDrvStream;
1708}
1709
1710/**
1711 * Adds a driver stream to a specific mixer sink.
1712 *
1713 * @returns IPRT status code.
1714 * @param pThis AC'97 state.
1715 * @param pMixSink Mixer sink to add driver stream to.
1716 * @param pCfg Stream configuration to use.
1717 * @param pDrv Driver stream to add.
1718 */
1719static int ichac97R3MixerAddDrvStream(PAC97STATE pThis, PAUDMIXSINK pMixSink, PPDMAUDIOSTREAMCFG pCfg, PAC97DRIVER pDrv)
1720{
1721 AssertPtrReturn(pThis, VERR_INVALID_POINTER);
1722 AssertPtrReturn(pMixSink, VERR_INVALID_POINTER);
1723 AssertPtrReturn(pCfg, VERR_INVALID_POINTER);
1724
1725 PPDMAUDIOSTREAMCFG pStreamCfg = DrvAudioHlpStreamCfgDup(pCfg);
1726 if (!pStreamCfg)
1727 return VERR_NO_MEMORY;
1728
1729 if (!RTStrPrintf(pStreamCfg->szName, sizeof(pStreamCfg->szName), "%s", pCfg->szName))
1730 {
1731 DrvAudioHlpStreamCfgFree(pStreamCfg);
1732 return VERR_BUFFER_OVERFLOW;
1733 }
1734
1735 LogFunc(("[LUN#%RU8] %s\n", pDrv->uLUN, pStreamCfg->szName));
1736
1737 int rc;
1738
1739 PAC97DRIVERSTREAM pDrvStream = ichac97R3MixerGetDrvStream(pThis, pDrv, pStreamCfg->enmDir, pStreamCfg->DestSource);
1740 if (pDrvStream)
1741 {
1742 AssertMsg(pDrvStream->pMixStrm == NULL, ("[LUN#%RU8] Driver stream already present when it must not\n", pDrv->uLUN));
1743
1744 PAUDMIXSTREAM pMixStrm;
1745 rc = AudioMixerSinkCreateStream(pMixSink, pDrv->pConnector, pStreamCfg, 0 /* fFlags */, &pMixStrm);
1746 LogFlowFunc(("LUN#%RU8: Created stream \"%s\" for sink, rc=%Rrc\n", pDrv->uLUN, pStreamCfg->szName, rc));
1747 if (RT_SUCCESS(rc))
1748 {
1749 rc = AudioMixerSinkAddStream(pMixSink, pMixStrm);
1750 LogFlowFunc(("LUN#%RU8: Added stream \"%s\" to sink, rc=%Rrc\n", pDrv->uLUN, pStreamCfg->szName, rc));
1751 if (RT_SUCCESS(rc))
1752 {
1753 /* If this is an input stream, always set the latest (added) stream
1754 * as the recording source.
1755 * @todo Make the recording source dynamic (CFGM?). */
1756 if (pStreamCfg->enmDir == PDMAUDIODIR_IN)
1757 {
1758 PDMAUDIOBACKENDCFG Cfg;
1759 rc = pDrv->pConnector->pfnGetConfig(pDrv->pConnector, &Cfg);
1760 if (RT_SUCCESS(rc))
1761 {
1762 if (Cfg.cMaxStreamsIn) /* At least one input source available? */
1763 {
1764 rc = AudioMixerSinkSetRecordingSource(pMixSink, pMixStrm);
1765 LogFlowFunc(("LUN#%RU8: Recording source for '%s' -> '%s', rc=%Rrc\n",
1766 pDrv->uLUN, pStreamCfg->szName, Cfg.szName, rc));
1767
1768 if (RT_SUCCESS(rc))
1769 LogRel2(("AC97: Set recording source for '%s' to '%s'\n", pStreamCfg->szName, Cfg.szName));
1770 }
1771 else
1772 LogRel(("AC97: Backend '%s' currently is not offering any recording source for '%s'\n",
1773 Cfg.szName, pStreamCfg->szName));
1774 }
1775 else if (RT_FAILURE(rc))
1776 LogFunc(("LUN#%RU8: Unable to retrieve backend configuratio for '%s', rc=%Rrc\n",
1777 pDrv->uLUN, pStreamCfg->szName, rc));
1778 }
1779 }
1780 }
1781
1782 if (RT_SUCCESS(rc))
1783 pDrvStream->pMixStrm = pMixStrm;
1784 }
1785 else
1786 rc = VERR_INVALID_PARAMETER;
1787
1788 DrvAudioHlpStreamCfgFree(pStreamCfg);
1789
1790 LogFlowFuncLeaveRC(rc);
1791 return rc;
1792}
1793
1794/**
1795 * Adds all current driver streams to a specific mixer sink.
1796 *
1797 * @returns IPRT status code.
1798 * @param pThis AC'97 state.
1799 * @param pMixSink Mixer sink to add stream to.
1800 * @param pCfg Stream configuration to use.
1801 */
1802static int ichac97R3MixerAddDrvStreams(PAC97STATE pThis, PAUDMIXSINK pMixSink, PPDMAUDIOSTREAMCFG pCfg)
1803{
1804 AssertPtrReturn(pThis, VERR_INVALID_POINTER);
1805 AssertPtrReturn(pMixSink, VERR_INVALID_POINTER);
1806 AssertPtrReturn(pCfg, VERR_INVALID_POINTER);
1807
1808 if (!DrvAudioHlpStreamCfgIsValid(pCfg))
1809 return VERR_INVALID_PARAMETER;
1810
1811 int rc = AudioMixerSinkSetFormat(pMixSink, &pCfg->Props);
1812 if (RT_FAILURE(rc))
1813 return rc;
1814
1815 PAC97DRIVER pDrv;
1816 RTListForEach(&pThis->lstDrv, pDrv, AC97DRIVER, Node)
1817 {
1818 int rc2 = ichac97R3MixerAddDrvStream(pThis, pMixSink, pCfg, pDrv);
1819 if (RT_FAILURE(rc2))
1820 LogFunc(("Attaching stream failed with %Rrc\n", rc2));
1821
1822 /* Do not pass failure to rc here, as there might be drivers which aren't
1823 * configured / ready yet. */
1824 }
1825
1826 LogFlowFuncLeaveRC(rc);
1827 return rc;
1828}
1829
1830/**
1831 * Adds a specific AC'97 driver to the driver chain.
1832 *
1833 * @return IPRT status code.
1834 * @param pThis AC'97 state.
1835 * @param pDrv AC'97 driver to add.
1836 */
1837static int ichac97R3MixerAddDrv(PAC97STATE pThis, PAC97DRIVER pDrv)
1838{
1839 int rc = VINF_SUCCESS;
1840
1841 if (DrvAudioHlpStreamCfgIsValid(&pThis->aStreams[AC97SOUNDSOURCE_PI_INDEX].State.Cfg))
1842 {
1843 int rc2 = ichac97R3MixerAddDrvStream(pThis, pThis->pSinkLineIn,
1844 &pThis->aStreams[AC97SOUNDSOURCE_PI_INDEX].State.Cfg, pDrv);
1845 if (RT_SUCCESS(rc))
1846 rc = rc2;
1847 }
1848
1849 if (DrvAudioHlpStreamCfgIsValid(&pThis->aStreams[AC97SOUNDSOURCE_PO_INDEX].State.Cfg))
1850 {
1851 int rc2 = ichac97R3MixerAddDrvStream(pThis, pThis->pSinkOut,
1852 &pThis->aStreams[AC97SOUNDSOURCE_PO_INDEX].State.Cfg, pDrv);
1853 if (RT_SUCCESS(rc))
1854 rc = rc2;
1855 }
1856
1857 if (DrvAudioHlpStreamCfgIsValid(&pThis->aStreams[AC97SOUNDSOURCE_MC_INDEX].State.Cfg))
1858 {
1859 int rc2 = ichac97R3MixerAddDrvStream(pThis, pThis->pSinkMicIn,
1860 &pThis->aStreams[AC97SOUNDSOURCE_MC_INDEX].State.Cfg, pDrv);
1861 if (RT_SUCCESS(rc))
1862 rc = rc2;
1863 }
1864
1865 return rc;
1866}
1867
1868/**
1869 * Removes a specific AC'97 driver from the driver chain and destroys its
1870 * associated streams.
1871 *
1872 * @param pThis AC'97 state.
1873 * @param pDrv AC'97 driver to remove.
1874 */
1875static void ichac97R3MixerRemoveDrv(PAC97STATE pThis, PAC97DRIVER pDrv)
1876{
1877 AssertPtrReturnVoid(pThis);
1878 AssertPtrReturnVoid(pDrv);
1879
1880 if (pDrv->MicIn.pMixStrm)
1881 {
1882 if (AudioMixerSinkGetRecordingSource(pThis->pSinkMicIn) == pDrv->MicIn.pMixStrm)
1883 AudioMixerSinkSetRecordingSource(pThis->pSinkMicIn, NULL);
1884
1885 AudioMixerSinkRemoveStream(pThis->pSinkMicIn, pDrv->MicIn.pMixStrm);
1886 AudioMixerStreamDestroy(pDrv->MicIn.pMixStrm);
1887 pDrv->MicIn.pMixStrm = NULL;
1888 }
1889
1890 if (pDrv->LineIn.pMixStrm)
1891 {
1892 if (AudioMixerSinkGetRecordingSource(pThis->pSinkLineIn) == pDrv->LineIn.pMixStrm)
1893 AudioMixerSinkSetRecordingSource(pThis->pSinkLineIn, NULL);
1894
1895 AudioMixerSinkRemoveStream(pThis->pSinkLineIn, pDrv->LineIn.pMixStrm);
1896 AudioMixerStreamDestroy(pDrv->LineIn.pMixStrm);
1897 pDrv->LineIn.pMixStrm = NULL;
1898 }
1899
1900 if (pDrv->Out.pMixStrm)
1901 {
1902 AudioMixerSinkRemoveStream(pThis->pSinkOut, pDrv->Out.pMixStrm);
1903 AudioMixerStreamDestroy(pDrv->Out.pMixStrm);
1904 pDrv->Out.pMixStrm = NULL;
1905 }
1906
1907 RTListNodeRemove(&pDrv->Node);
1908}
1909
1910/**
1911 * Removes a driver stream from a specific mixer sink.
1912 *
1913 * @param pThis AC'97 state.
1914 * @param pMixSink Mixer sink to remove audio streams from.
1915 * @param enmDir Stream direction to remove.
1916 * @param dstSrc Stream destination / source to remove.
1917 * @param pDrv Driver stream to remove.
1918 */
1919static void ichac97R3MixerRemoveDrvStream(PAC97STATE pThis, PAUDMIXSINK pMixSink,
1920 PDMAUDIODIR enmDir, PDMAUDIODESTSOURCE dstSrc, PAC97DRIVER pDrv)
1921{
1922 AssertPtrReturnVoid(pThis);
1923 AssertPtrReturnVoid(pMixSink);
1924
1925 PAC97DRIVERSTREAM pDrvStream = ichac97R3MixerGetDrvStream(pThis, pDrv, enmDir, dstSrc);
1926 if (pDrvStream)
1927 {
1928 if (pDrvStream->pMixStrm)
1929 {
1930 AudioMixerSinkRemoveStream(pMixSink, pDrvStream->pMixStrm);
1931
1932 AudioMixerStreamDestroy(pDrvStream->pMixStrm);
1933 pDrvStream->pMixStrm = NULL;
1934 }
1935 }
1936}
1937
1938/**
1939 * Removes all driver streams from a specific mixer sink.
1940 *
1941 * @param pThis AC'97 state.
1942 * @param pMixSink Mixer sink to remove audio streams from.
1943 * @param enmDir Stream direction to remove.
1944 * @param dstSrc Stream destination / source to remove.
1945 */
1946static void ichac97R3MixerRemoveDrvStreams(PAC97STATE pThis, PAUDMIXSINK pMixSink,
1947 PDMAUDIODIR enmDir, PDMAUDIODESTSOURCE dstSrc)
1948{
1949 AssertPtrReturnVoid(pThis);
1950 AssertPtrReturnVoid(pMixSink);
1951
1952 PAC97DRIVER pDrv;
1953 RTListForEach(&pThis->lstDrv, pDrv, AC97DRIVER, Node)
1954 {
1955 ichac97R3MixerRemoveDrvStream(pThis, pMixSink, enmDir, dstSrc, pDrv);
1956 }
1957}
1958
1959/**
1960 * Calculates and returns the ticks for a specified amount of bytes.
1961 *
1962 * @returns Calculated ticks
1963 * @param pThis AC'97 device state.
1964 * @param pStream AC'97 stream to calculate ticks for.
1965 * @param cbBytes Bytes to calculate ticks for.
1966 */
1967static uint64_t ichac97R3StreamTransferCalcNext(PAC97STATE pThis, PAC97STREAM pStream, uint32_t cbBytes)
1968{
1969 if (!cbBytes)
1970 return 0;
1971
1972 AssertReturn(DrvAudioHlpPCMPropsAreValid(&pStream->State.Cfg.Props), 0);
1973 const uint32_t cbFrame = DrvAudioHlpPCMPropsBytesPerFrame(&pStream->State.Cfg.Props);
1974
1975 AssertReturn(cbBytes % cbFrame == 0, 0);
1976
1977 const uint64_t cTicksPerHz = TMTimerGetFreq((pThis)->DEVAC97_CTX_SUFF_SD(pTimer, pStream->u8SD)) / pStream->State.uTimerHz;
1978 const uint64_t cTicksPerByte = cTicksPerHz / cbBytes;
1979 Assert(cTicksPerByte);
1980 const uint64_t cTransferTicks = cbBytes * cTicksPerByte;
1981
1982 LogFunc(("[SD%RU8] Timer %uHz (%RU64 ticks per Hz), cTicksPerByte=%RU64, cbBytes=%RU32 -> cTransferTicks=%RU64\n",
1983 pStream->u8SD, pStream->State.uTimerHz, cTicksPerHz, cTicksPerByte, cbBytes, cTransferTicks));
1984
1985 return cTransferTicks;
1986}
1987
1988/**
1989 * Updates the next transfer based on a specific amount of bytes.
1990 *
1991 * @returns IPRT status code.
1992 * @param pThis AC'97 device state.
1993 * @param pStream AC'97 stream to update.
1994 * @param cbBytes Bytes to update next transfer for.
1995 */
1996static void ichac97R3StreamTransferUpdate(PAC97STATE pThis, PAC97STREAM pStream, uint32_t cbBytes)
1997{
1998 if (!cbBytes)
1999 return;
2000
2001 /* Calculate the bytes we need to transfer to / from the stream's DMA per iteration.
2002 * This is bound to the device's Hz rate and thus to the (virtual) timing the device expects. */
2003 pStream->State.cbTransferChunk = cbBytes;
2004
2005 /* Update the transfer ticks. */
2006 pStream->State.cTransferTicks = ichac97R3StreamTransferCalcNext(pThis, pStream, pStream->State.cbTransferChunk);
2007 Assert(pStream->State.cTransferTicks); /* Paranoia. */
2008}
2009
2010/**
2011 * Opens an AC'97 stream with its current mixer settings.
2012 *
2013 * This will open an AC'97 stream with 2 (stereo) channels, 16-bit samples and
2014 * the last set sample rate in the AC'97 mixer for this stream.
2015 *
2016 * @returns IPRT status code.
2017 * @param pThis AC'97 device state.
2018 * @param pStream AC'97 stream to open.
2019 */
2020static int ichac97R3StreamOpen(PAC97STATE pThis, PAC97STREAM pStream)
2021{
2022 int rc = VINF_SUCCESS;
2023
2024 PDMAUDIOSTREAMCFG Cfg;
2025 RT_ZERO(Cfg);
2026
2027 PAUDMIXSINK pMixSink = NULL;
2028
2029 Cfg.Props.cChannels = 2;
2030 Cfg.Props.cBytes = 2 /* 16-bit */;
2031 Cfg.Props.fSigned = true;
2032 Cfg.Props.cShift = PDMAUDIOPCMPROPS_MAKE_SHIFT_PARMS(Cfg.Props.cBytes, Cfg.Props.cChannels);
2033
2034 switch (pStream->u8SD)
2035 {
2036 case AC97SOUNDSOURCE_PI_INDEX:
2037 {
2038 Cfg.Props.uHz = ichac97MixerGet(pThis, AC97_PCM_LR_ADC_Rate);
2039 Cfg.enmDir = PDMAUDIODIR_IN;
2040 Cfg.DestSource.Source = PDMAUDIORECSOURCE_LINE;
2041 Cfg.enmLayout = PDMAUDIOSTREAMLAYOUT_NON_INTERLEAVED;
2042 RTStrCopy(Cfg.szName, sizeof(Cfg.szName), "Line-In");
2043
2044 pMixSink = pThis->pSinkLineIn;
2045 break;
2046 }
2047
2048 case AC97SOUNDSOURCE_MC_INDEX:
2049 {
2050 Cfg.Props.uHz = ichac97MixerGet(pThis, AC97_MIC_ADC_Rate);
2051 Cfg.enmDir = PDMAUDIODIR_IN;
2052 Cfg.DestSource.Source = PDMAUDIORECSOURCE_MIC;
2053 Cfg.enmLayout = PDMAUDIOSTREAMLAYOUT_NON_INTERLEAVED;
2054 RTStrCopy(Cfg.szName, sizeof(Cfg.szName), "Mic-In");
2055
2056 pMixSink = pThis->pSinkMicIn;
2057 break;
2058 }
2059
2060 case AC97SOUNDSOURCE_PO_INDEX:
2061 {
2062 Cfg.Props.uHz = ichac97MixerGet(pThis, AC97_PCM_Front_DAC_Rate);
2063 Cfg.enmDir = PDMAUDIODIR_OUT;
2064 Cfg.DestSource.Dest = PDMAUDIOPLAYBACKDEST_FRONT;
2065 Cfg.enmLayout = PDMAUDIOSTREAMLAYOUT_NON_INTERLEAVED;
2066 RTStrCopy(Cfg.szName, sizeof(Cfg.szName), "Output");
2067
2068 pMixSink = pThis->pSinkOut;
2069 break;
2070 }
2071
2072 default:
2073 rc = VERR_NOT_SUPPORTED;
2074 break;
2075 }
2076
2077 if (RT_SUCCESS(rc))
2078 {
2079 /* Only (re-)create the stream (and driver chain) if we really have to.
2080 * Otherwise avoid this and just reuse it, as this costs performance. */
2081 if (!DrvAudioHlpPCMPropsAreEqual(&Cfg.Props, &pStream->State.Cfg.Props))
2082 {
2083 LogFlowFunc(("[SD%RU8] uHz=%RU32\n", pStream->u8SD, Cfg.Props.uHz));
2084
2085 if (Cfg.Props.uHz)
2086 {
2087 Assert(Cfg.enmDir != PDMAUDIODIR_UNKNOWN);
2088
2089 /*
2090 * Set the stream's timer Hz rate, based on the PCM properties Hz rate.
2091 */
2092 if (pThis->uTimerHz == AC97_TIMER_HZ_DEFAULT) /* Make sure that we don't have any custom Hz rate set we want to enforce */
2093 {
2094 if (Cfg.Props.uHz > 44100) /* E.g. 48000 Hz. */
2095 pStream->State.uTimerHz = 200;
2096 else /* Just take the global Hz rate otherwise. */
2097 pStream->State.uTimerHz = pThis->uTimerHz;
2098 }
2099 else
2100 pStream->State.uTimerHz = pThis->uTimerHz;
2101
2102 /* Set scheduling hint (if available). */
2103 if (pStream->State.uTimerHz)
2104 Cfg.Device.uSchedulingHintMs = 1000 /* ms */ / pStream->State.uTimerHz;
2105
2106 if (pStream->State.pCircBuf)
2107 {
2108 RTCircBufDestroy(pStream->State.pCircBuf);
2109 pStream->State.pCircBuf = NULL;
2110 }
2111
2112 rc = RTCircBufCreate(&pStream->State.pCircBuf, DrvAudioHlpMilliToBytes(100 /* ms */, &Cfg.Props)); /** @todo Make this configurable. */
2113 if (RT_SUCCESS(rc))
2114 {
2115 ichac97R3MixerRemoveDrvStreams(pThis, pMixSink, Cfg.enmDir, Cfg.DestSource);
2116
2117 rc = ichac97R3MixerAddDrvStreams(pThis, pMixSink, &Cfg);
2118 if (RT_SUCCESS(rc))
2119 rc = DrvAudioHlpStreamCfgCopy(&pStream->State.Cfg, &Cfg);
2120 }
2121 }
2122 }
2123 else
2124 LogFlowFunc(("[SD%RU8] Skipping (re-)creation\n", pStream->u8SD));
2125 }
2126
2127 LogFlowFunc(("[SD%RU8] rc=%Rrc\n", pStream->u8SD, rc));
2128 return rc;
2129}
2130
2131/**
2132 * Closes an AC'97 stream.
2133 *
2134 * @returns IPRT status code.
2135 * @param pThis AC'97 state.
2136 * @param pStream AC'97 stream to close.
2137 */
2138static int ichac97R3StreamClose(PAC97STATE pThis, PAC97STREAM pStream)
2139{
2140 RT_NOREF(pThis, pStream);
2141
2142 LogFlowFunc(("[SD%RU8]\n", pStream->u8SD));
2143
2144 return VINF_SUCCESS;
2145}
2146
2147/**
2148 * Re-opens (that is, closes and opens again) an AC'97 stream on the backend
2149 * side with the current AC'97 mixer settings for this stream.
2150 *
2151 * @returns IPRT status code.
2152 * @param pThis AC'97 device state.
2153 * @param pStream AC'97 stream to re-open.
2154 */
2155static int ichac97R3StreamReOpen(PAC97STATE pThis, PAC97STREAM pStream)
2156{
2157 LogFlowFunc(("[SD%RU8]\n", pStream->u8SD));
2158
2159 int rc = ichac97R3StreamClose(pThis, pStream);
2160 if (RT_SUCCESS(rc))
2161 rc = ichac97R3StreamOpen(pThis, pStream);
2162
2163 return rc;
2164}
2165
2166/**
2167 * Locks an AC'97 stream for serialized access.
2168 *
2169 * @returns IPRT status code.
2170 * @param pStream AC'97 stream to lock.
2171 */
2172static void ichac97R3StreamLock(PAC97STREAM pStream)
2173{
2174 AssertPtrReturnVoid(pStream);
2175 int rc2 = RTCritSectEnter(&pStream->State.CritSect);
2176 AssertRC(rc2);
2177}
2178
2179/**
2180 * Unlocks a formerly locked AC'97 stream.
2181 *
2182 * @returns IPRT status code.
2183 * @param pStream AC'97 stream to unlock.
2184 */
2185static void ichac97R3StreamUnlock(PAC97STREAM pStream)
2186{
2187 AssertPtrReturnVoid(pStream);
2188 int rc2 = RTCritSectLeave(&pStream->State.CritSect);
2189 AssertRC(rc2);
2190}
2191
2192/**
2193 * Retrieves the available size of (buffered) audio data (in bytes) of a given AC'97 stream.
2194 *
2195 * @returns Available data (in bytes).
2196 * @param pStream AC'97 stream to retrieve size for.
2197 */
2198static uint32_t ichac97R3StreamGetUsed(PAC97STREAM pStream)
2199{
2200 AssertPtrReturn(pStream, 0);
2201
2202 if (!pStream->State.pCircBuf)
2203 return 0;
2204
2205 return (uint32_t)RTCircBufUsed(pStream->State.pCircBuf);
2206}
2207
2208/**
2209 * Retrieves the free size of audio data (in bytes) of a given AC'97 stream.
2210 *
2211 * @returns Free data (in bytes).
2212 * @param pStream AC'97 stream to retrieve size for.
2213 */
2214static uint32_t ichac97R3StreamGetFree(PAC97STREAM pStream)
2215{
2216 AssertPtrReturn(pStream, 0);
2217
2218 if (!pStream->State.pCircBuf)
2219 return 0;
2220
2221 return (uint32_t)RTCircBufFree(pStream->State.pCircBuf);
2222}
2223
2224/**
2225 * Sets the volume of a specific AC'97 mixer control.
2226 *
2227 * This currently only supports attenuation -- gain support is currently not implemented.
2228 *
2229 * @returns IPRT status code.
2230 * @param pThis AC'97 state.
2231 * @param index AC'97 mixer index to set volume for.
2232 * @param enmMixerCtl Corresponding audio mixer sink.
2233 * @param uVal Volume value to set.
2234 */
2235static int ichac97R3MixerSetVolume(PAC97STATE pThis, int index, PDMAUDIOMIXERCTL enmMixerCtl, uint32_t uVal)
2236{
2237 /*
2238 * From AC'97 SoundMax Codec AD1981A/AD1981B:
2239 * "Because AC '97 defines 6-bit volume registers, to maintain compatibility whenever the
2240 * D5 or D13 bits are set to 1, their respective lower five volume bits are automatically
2241 * set to 1 by the Codec logic. On readback, all lower 5 bits will read ones whenever
2242 * these bits are set to 1."
2243 *
2244 * Linux ALSA depends on this behavior to detect that only 5 bits are used for volume
2245 * control and the optional 6th bit is not used. Note that this logic only applies to the
2246 * master volume controls.
2247 */
2248 if ((index == AC97_Master_Volume_Mute) || (index == AC97_Headphone_Volume_Mute) || (index == AC97_Master_Volume_Mono_Mute))
2249 {
2250 if (uVal & RT_BIT(5)) /* D5 bit set? */
2251 uVal |= RT_BIT(4) | RT_BIT(3) | RT_BIT(2) | RT_BIT(1) | RT_BIT(0);
2252 if (uVal & RT_BIT(13)) /* D13 bit set? */
2253 uVal |= RT_BIT(12) | RT_BIT(11) | RT_BIT(10) | RT_BIT(9) | RT_BIT(8);
2254 }
2255
2256 const bool fCtlMuted = (uVal >> AC97_BARS_VOL_MUTE_SHIFT) & 1;
2257 uint8_t uCtlAttLeft = (uVal >> 8) & AC97_BARS_VOL_MASK;
2258 uint8_t uCtlAttRight = uVal & AC97_BARS_VOL_MASK;
2259
2260 /* For the master and headphone volume, 0 corresponds to 0dB attenuation. For the other
2261 * volume controls, 0 means 12dB gain and 8 means unity gain.
2262 */
2263 if (index != AC97_Master_Volume_Mute && index != AC97_Headphone_Volume_Mute)
2264 {
2265# ifndef VBOX_WITH_AC97_GAIN_SUPPORT
2266 /* NB: Currently there is no gain support, only attenuation. */
2267 uCtlAttLeft = uCtlAttLeft < 8 ? 0 : uCtlAttLeft - 8;
2268 uCtlAttRight = uCtlAttRight < 8 ? 0 : uCtlAttRight - 8;
2269# endif
2270 }
2271 Assert(uCtlAttLeft <= 255 / AC97_DB_FACTOR);
2272 Assert(uCtlAttRight <= 255 / AC97_DB_FACTOR);
2273
2274 LogFunc(("index=0x%x, uVal=%RU32, enmMixerCtl=%RU32\n", index, uVal, enmMixerCtl));
2275 LogFunc(("uCtlAttLeft=%RU8, uCtlAttRight=%RU8 ", uCtlAttLeft, uCtlAttRight));
2276
2277 /*
2278 * For AC'97 volume controls, each additional step means -1.5dB attenuation with
2279 * zero being maximum. In contrast, we're internally using 255 (PDMAUDIO_VOLUME_MAX)
2280 * steps, each -0.375dB, where 0 corresponds to -96dB and 255 corresponds to 0dB.
2281 */
2282 uint8_t lVol = PDMAUDIO_VOLUME_MAX - uCtlAttLeft * AC97_DB_FACTOR;
2283 uint8_t rVol = PDMAUDIO_VOLUME_MAX - uCtlAttRight * AC97_DB_FACTOR;
2284
2285 Log(("-> fMuted=%RTbool, lVol=%RU8, rVol=%RU8\n", fCtlMuted, lVol, rVol));
2286
2287 int rc = VINF_SUCCESS;
2288
2289 if (pThis->pMixer) /* Device can be in reset state, so no mixer available. */
2290 {
2291 PDMAUDIOVOLUME Vol = { fCtlMuted, lVol, rVol };
2292 PAUDMIXSINK pSink = NULL;
2293
2294 switch (enmMixerCtl)
2295 {
2296 case PDMAUDIOMIXERCTL_VOLUME_MASTER:
2297 rc = AudioMixerSetMasterVolume(pThis->pMixer, &Vol);
2298 break;
2299
2300 case PDMAUDIOMIXERCTL_FRONT:
2301 pSink = pThis->pSinkOut;
2302 break;
2303
2304 case PDMAUDIOMIXERCTL_MIC_IN:
2305 case PDMAUDIOMIXERCTL_LINE_IN:
2306 /* These are recognized but do nothing. */
2307 break;
2308
2309 default:
2310 AssertFailed();
2311 rc = VERR_NOT_SUPPORTED;
2312 break;
2313 }
2314
2315 if (pSink)
2316 rc = AudioMixerSinkSetVolume(pSink, &Vol);
2317 }
2318
2319 ichac97MixerSet(pThis, index, uVal);
2320
2321 if (RT_FAILURE(rc))
2322 LogFlowFunc(("Failed with %Rrc\n", rc));
2323
2324 return rc;
2325}
2326
2327/**
2328 * Sets the gain of a specific AC'97 recording control.
2329 *
2330 * NB: gain support is currently not implemented in PDM audio.
2331 *
2332 * @returns IPRT status code.
2333 * @param pThis AC'97 state.
2334 * @param index AC'97 mixer index to set volume for.
2335 * @param enmMixerCtl Corresponding audio mixer sink.
2336 * @param uVal Volume value to set.
2337 */
2338static int ichac97R3MixerSetGain(PAC97STATE pThis, int index, PDMAUDIOMIXERCTL enmMixerCtl, uint32_t uVal)
2339{
2340 /*
2341 * For AC'97 recording controls, each additional step means +1.5dB gain with
2342 * zero being 0dB gain and 15 being +22.5dB gain.
2343 */
2344 const bool fCtlMuted = (uVal >> AC97_BARS_VOL_MUTE_SHIFT) & 1;
2345 uint8_t uCtlGainLeft = (uVal >> 8) & AC97_BARS_GAIN_MASK;
2346 uint8_t uCtlGainRight = uVal & AC97_BARS_GAIN_MASK;
2347
2348 Assert(uCtlGainLeft <= 255 / AC97_DB_FACTOR);
2349 Assert(uCtlGainRight <= 255 / AC97_DB_FACTOR);
2350
2351 LogFunc(("index=0x%x, uVal=%RU32, enmMixerCtl=%RU32\n", index, uVal, enmMixerCtl));
2352 LogFunc(("uCtlGainLeft=%RU8, uCtlGainRight=%RU8 ", uCtlGainLeft, uCtlGainRight));
2353
2354 uint8_t lVol = PDMAUDIO_VOLUME_MAX + uCtlGainLeft * AC97_DB_FACTOR;
2355 uint8_t rVol = PDMAUDIO_VOLUME_MAX + uCtlGainRight * AC97_DB_FACTOR;
2356
2357 /* We do not currently support gain. Since AC'97 does not support attenuation
2358 * for the recording input, the best we can do is set the maximum volume.
2359 */
2360# ifndef VBOX_WITH_AC97_GAIN_SUPPORT
2361 /* NB: Currently there is no gain support, only attenuation. Since AC'97 does not
2362 * support attenuation for the recording inputs, the best we can do is set the
2363 * maximum volume.
2364 */
2365 lVol = rVol = PDMAUDIO_VOLUME_MAX;
2366# endif
2367
2368 Log(("-> fMuted=%RTbool, lVol=%RU8, rVol=%RU8\n", fCtlMuted, lVol, rVol));
2369
2370 int rc = VINF_SUCCESS;
2371
2372 if (pThis->pMixer) /* Device can be in reset state, so no mixer available. */
2373 {
2374 PDMAUDIOVOLUME Vol = { fCtlMuted, lVol, rVol };
2375 PAUDMIXSINK pSink = NULL;
2376
2377 switch (enmMixerCtl)
2378 {
2379 case PDMAUDIOMIXERCTL_MIC_IN:
2380 pSink = pThis->pSinkMicIn;
2381 break;
2382
2383 case PDMAUDIOMIXERCTL_LINE_IN:
2384 pSink = pThis->pSinkLineIn;
2385 break;
2386
2387 default:
2388 AssertFailed();
2389 rc = VERR_NOT_SUPPORTED;
2390 break;
2391 }
2392
2393 if (pSink) {
2394 rc = AudioMixerSinkSetVolume(pSink, &Vol);
2395 /* There is only one AC'97 recording gain control. If line in
2396 * is changed, also update the microphone. If the optional dedicated
2397 * microphone is changed, only change that.
2398 * NB: The codecs we support do not have the dedicated microphone control.
2399 */
2400 if ((pSink == pThis->pSinkLineIn) && pThis->pSinkMicIn)
2401 rc = AudioMixerSinkSetVolume(pSink, &Vol);
2402 }
2403 }
2404
2405 ichac97MixerSet(pThis, index, uVal);
2406
2407 if (RT_FAILURE(rc))
2408 LogFlowFunc(("Failed with %Rrc\n", rc));
2409
2410 return rc;
2411}
2412
2413/**
2414 * Converts an AC'97 recording source index to a PDM audio recording source.
2415 *
2416 * @returns PDM audio recording source.
2417 * @param uIdx AC'97 index to convert.
2418 */
2419static PDMAUDIORECSOURCE ichac97R3IdxToRecSource(uint8_t uIdx)
2420{
2421 switch (uIdx)
2422 {
2423 case AC97_REC_MIC: return PDMAUDIORECSOURCE_MIC;
2424 case AC97_REC_CD: return PDMAUDIORECSOURCE_CD;
2425 case AC97_REC_VIDEO: return PDMAUDIORECSOURCE_VIDEO;
2426 case AC97_REC_AUX: return PDMAUDIORECSOURCE_AUX;
2427 case AC97_REC_LINE_IN: return PDMAUDIORECSOURCE_LINE;
2428 case AC97_REC_PHONE: return PDMAUDIORECSOURCE_PHONE;
2429 default:
2430 break;
2431 }
2432
2433 LogFlowFunc(("Unknown record source %d, using MIC\n", uIdx));
2434 return PDMAUDIORECSOURCE_MIC;
2435}
2436
2437/**
2438 * Converts a PDM audio recording source to an AC'97 recording source index.
2439 *
2440 * @returns AC'97 recording source index.
2441 * @param enmRecSrc PDM audio recording source to convert.
2442 */
2443static uint8_t ichac97R3RecSourceToIdx(PDMAUDIORECSOURCE enmRecSrc)
2444{
2445 switch (enmRecSrc)
2446 {
2447 case PDMAUDIORECSOURCE_MIC: return AC97_REC_MIC;
2448 case PDMAUDIORECSOURCE_CD: return AC97_REC_CD;
2449 case PDMAUDIORECSOURCE_VIDEO: return AC97_REC_VIDEO;
2450 case PDMAUDIORECSOURCE_AUX: return AC97_REC_AUX;
2451 case PDMAUDIORECSOURCE_LINE: return AC97_REC_LINE_IN;
2452 case PDMAUDIORECSOURCE_PHONE: return AC97_REC_PHONE;
2453 default:
2454 break;
2455 }
2456
2457 LogFlowFunc(("Unknown audio recording source %d using MIC\n", enmRecSrc));
2458 return AC97_REC_MIC;
2459}
2460
2461/**
2462 * Returns the audio direction of a specified stream descriptor.
2463 *
2464 * @return Audio direction.
2465 */
2466DECLINLINE(PDMAUDIODIR) ichac97GetDirFromSD(uint8_t uSD)
2467{
2468 switch (uSD)
2469 {
2470 case AC97SOUNDSOURCE_PI_INDEX: return PDMAUDIODIR_IN;
2471 case AC97SOUNDSOURCE_PO_INDEX: return PDMAUDIODIR_OUT;
2472 case AC97SOUNDSOURCE_MC_INDEX: return PDMAUDIODIR_IN;
2473 }
2474
2475 AssertFailed();
2476 return PDMAUDIODIR_UNKNOWN;
2477}
2478
2479#endif /* IN_RING3 */
2480
2481#ifdef IN_RING3
2482
2483/**
2484 * Performs an AC'97 mixer record select to switch to a different recording
2485 * source.
2486 *
2487 * @param pThis AC'97 state.
2488 * @param val AC'97 recording source index to set.
2489 */
2490static void ichac97R3MixerRecordSelect(PAC97STATE pThis, uint32_t val)
2491{
2492 uint8_t rs = val & AC97_REC_MASK;
2493 uint8_t ls = (val >> 8) & AC97_REC_MASK;
2494 PDMAUDIORECSOURCE ars = ichac97R3IdxToRecSource(rs);
2495 PDMAUDIORECSOURCE als = ichac97R3IdxToRecSource(ls);
2496 rs = ichac97R3RecSourceToIdx(ars);
2497 ls = ichac97R3RecSourceToIdx(als);
2498 ichac97MixerSet(pThis, AC97_Record_Select, rs | (ls << 8));
2499}
2500
2501/**
2502 * Resets the AC'97 mixer.
2503 *
2504 * @returns IPRT status code.
2505 * @param pThis AC'97 state.
2506 */
2507static int ichac97R3MixerReset(PAC97STATE pThis)
2508{
2509 AssertPtrReturn(pThis, VERR_INVALID_PARAMETER);
2510
2511 LogFlowFuncEnter();
2512
2513 RT_ZERO(pThis->mixer_data);
2514
2515 /* Note: Make sure to reset all registers first before bailing out on error. */
2516
2517 ichac97MixerSet(pThis, AC97_Reset , 0x0000); /* 6940 */
2518 ichac97MixerSet(pThis, AC97_Master_Volume_Mono_Mute , 0x8000);
2519 ichac97MixerSet(pThis, AC97_PC_BEEP_Volume_Mute , 0x0000);
2520
2521 ichac97MixerSet(pThis, AC97_Phone_Volume_Mute , 0x8008);
2522 ichac97MixerSet(pThis, AC97_Mic_Volume_Mute , 0x8008);
2523 ichac97MixerSet(pThis, AC97_CD_Volume_Mute , 0x8808);
2524 ichac97MixerSet(pThis, AC97_Aux_Volume_Mute , 0x8808);
2525 ichac97MixerSet(pThis, AC97_Record_Gain_Mic_Mute , 0x8000);
2526 ichac97MixerSet(pThis, AC97_General_Purpose , 0x0000);
2527 ichac97MixerSet(pThis, AC97_3D_Control , 0x0000);
2528 ichac97MixerSet(pThis, AC97_Powerdown_Ctrl_Stat , 0x000f);
2529
2530 /* Configure Extended Audio ID (EAID) + Control & Status (EACS) registers. */
2531 uint16_t fEAID = AC97_EAID_REV1; /* Our hardware is AC'97 rev2.3 compliant. */
2532 uint16_t fEACS = 0;
2533#ifdef VBOX_WITH_AC97_VRA
2534 fEAID |= AC97_EAID_VRA; /* Variable Rate PCM Audio capable. */
2535 fEACS |= AC97_EACS_VRA; /* Ditto. */
2536#endif
2537#ifdef VBOX_WITH_AC97_VRM
2538 fEAID |= AC97_EAID_VRM; /* Variable Rate Mic-In Audio capable. */
2539 fEACS |= AC97_EACS_VRM; /* Ditto. */
2540#endif
2541
2542 ichac97MixerSet(pThis, AC97_Extended_Audio_ID, fEAID);
2543 ichac97MixerSet(pThis, AC97_Extended_Audio_Ctrl_Stat, fEACS);
2544 ichac97MixerSet(pThis, AC97_PCM_Front_DAC_Rate , 0xbb80);
2545 ichac97MixerSet(pThis, AC97_PCM_Surround_DAC_Rate , 0xbb80);
2546 ichac97MixerSet(pThis, AC97_PCM_LFE_DAC_Rate , 0xbb80);
2547 ichac97MixerSet(pThis, AC97_PCM_LR_ADC_Rate , 0xbb80);
2548 ichac97MixerSet(pThis, AC97_MIC_ADC_Rate , 0xbb80);
2549
2550 if (pThis->uCodecModel == AC97_CODEC_AD1980)
2551 {
2552 /* Analog Devices 1980 (AD1980) */
2553 ichac97MixerSet(pThis, AC97_Reset , 0x0010); /* Headphones. */
2554 ichac97MixerSet(pThis, AC97_Vendor_ID1 , 0x4144);
2555 ichac97MixerSet(pThis, AC97_Vendor_ID2 , 0x5370);
2556 ichac97MixerSet(pThis, AC97_Headphone_Volume_Mute , 0x8000);
2557 }
2558 else if (pThis->uCodecModel == AC97_CODEC_AD1981B)
2559 {
2560 /* Analog Devices 1981B (AD1981B) */
2561 ichac97MixerSet(pThis, AC97_Vendor_ID1 , 0x4144);
2562 ichac97MixerSet(pThis, AC97_Vendor_ID2 , 0x5374);
2563 }
2564 else
2565 {
2566 /* Sigmatel 9700 (STAC9700) */
2567 ichac97MixerSet(pThis, AC97_Vendor_ID1 , 0x8384);
2568 ichac97MixerSet(pThis, AC97_Vendor_ID2 , 0x7600); /* 7608 */
2569 }
2570 ichac97R3MixerRecordSelect(pThis, 0);
2571
2572 /* The default value is 8000h, which corresponds to 0 dB attenuation with mute on. */
2573 ichac97R3MixerSetVolume(pThis, AC97_Master_Volume_Mute, PDMAUDIOMIXERCTL_VOLUME_MASTER, 0x8000);
2574
2575 /* The default value for stereo registers is 8808h, which corresponds to 0 dB gain with mute on.*/
2576 ichac97R3MixerSetVolume(pThis, AC97_PCM_Out_Volume_Mute, PDMAUDIOMIXERCTL_FRONT, 0x8808);
2577 ichac97R3MixerSetVolume(pThis, AC97_Line_In_Volume_Mute, PDMAUDIOMIXERCTL_LINE_IN, 0x8808);
2578 ichac97R3MixerSetVolume(pThis, AC97_Mic_Volume_Mute, PDMAUDIOMIXERCTL_MIC_IN, 0x8008);
2579
2580 /* The default for record controls is 0 dB gain with mute on. */
2581 ichac97R3MixerSetGain(pThis, AC97_Record_Gain_Mute, PDMAUDIOMIXERCTL_LINE_IN, 0x8000);
2582 ichac97R3MixerSetGain(pThis, AC97_Record_Gain_Mic_Mute, PDMAUDIOMIXERCTL_MIC_IN, 0x8000);
2583
2584 return VINF_SUCCESS;
2585}
2586
2587# if 0 /* Unused */
2588static void ichac97R3WriteBUP(PAC97STATE pThis, uint32_t cbElapsed)
2589{
2590 LogFlowFunc(("cbElapsed=%RU32\n", cbElapsed));
2591
2592 if (!(pThis->bup_flag & BUP_SET))
2593 {
2594 if (pThis->bup_flag & BUP_LAST)
2595 {
2596 unsigned int i;
2597 uint32_t *p = (uint32_t*)pThis->silence;
2598 for (i = 0; i < sizeof(pThis->silence) / 4; i++) /** @todo r=andy Assumes 16-bit samples, stereo. */
2599 *p++ = pThis->last_samp;
2600 }
2601 else
2602 RT_ZERO(pThis->silence);
2603
2604 pThis->bup_flag |= BUP_SET;
2605 }
2606
2607 while (cbElapsed)
2608 {
2609 uint32_t cbToWrite = RT_MIN(cbElapsed, (uint32_t)sizeof(pThis->silence));
2610 uint32_t cbWrittenToStream;
2611
2612 int rc2 = AudioMixerSinkWrite(pThis->pSinkOut, AUDMIXOP_COPY,
2613 pThis->silence, cbToWrite, &cbWrittenToStream);
2614 if (RT_SUCCESS(rc2))
2615 {
2616 if (cbWrittenToStream < cbToWrite) /* Lagging behind? */
2617 LogFlowFunc(("Warning: Only written %RU32 / %RU32 bytes, expect lags\n", cbWrittenToStream, cbToWrite));
2618 }
2619
2620 /* Always report all data as being written;
2621 * backends who were not able to catch up have to deal with it themselves. */
2622 Assert(cbElapsed >= cbToWrite);
2623 cbElapsed -= cbToWrite;
2624 }
2625}
2626# endif /* Unused */
2627
2628/**
2629 * Timer callback which handles the audio data transfers on a periodic basis.
2630 *
2631 * @param pDevIns Device instance.
2632 * @param pTimer Timer which was used when calling this.
2633 * @param pvUser User argument as PAC97STATE.
2634 */
2635static DECLCALLBACK(void) ichac97R3Timer(PPDMDEVINS pDevIns, PTMTIMER pTimer, void *pvUser)
2636{
2637 RT_NOREF(pDevIns, pTimer);
2638
2639 PAC97STREAM pStream = (PAC97STREAM)pvUser;
2640 AssertPtr(pStream);
2641
2642 PAC97STATE pThis = pStream->pAC97State;
2643 AssertPtr(pThis);
2644
2645 STAM_PROFILE_START(&pThis->StatTimer, a);
2646
2647 DEVAC97_LOCK_BOTH_RETURN_VOID(pThis, pStream->u8SD);
2648
2649 ichac97R3StreamUpdate(pThis, pStream, true /* fInTimer */);
2650
2651 PAUDMIXSINK pSink = ichac97R3IndexToSink(pThis, pStream->u8SD);
2652
2653 bool fSinkActive = false;
2654 if (pSink)
2655 fSinkActive = AudioMixerSinkIsActive(pSink);
2656
2657 if (fSinkActive)
2658 {
2659 ichac97R3StreamTransferUpdate(pThis, pStream, pStream->Regs.picb << 1); /** @todo r=andy Assumes 16-bit samples. */
2660
2661 ichac97TimerSet(pThis,pStream,
2662 TMTimerGet((pThis)->DEVAC97_CTX_SUFF_SD(pTimer, pStream->u8SD)) + pStream->State.cTransferTicks,
2663 false /* fForce */);
2664 }
2665
2666 DEVAC97_UNLOCK_BOTH(pThis, pStream->u8SD);
2667
2668 STAM_PROFILE_STOP(&pThis->StatTimer, a);
2669}
2670#endif /* IN_RING3 */
2671
2672/**
2673 * Sets the virtual device timer to a new expiration time.
2674 *
2675 * @returns Whether the new expiration time was set or not.
2676 * @param pThis AC'97 state.
2677 * @param pStream AC'97 stream to set timer for.
2678 * @param tsExpire New (virtual) expiration time to set.
2679 * @param fForce Whether to force setting the expiration time or not.
2680 *
2681 * @remark This function takes all active AC'97 streams and their
2682 * current timing into account. This is needed to make sure
2683 * that all streams can match their needed timing.
2684 *
2685 * To achieve this, the earliest (lowest) timestamp of all
2686 * active streams found will be used for the next scheduling slot.
2687 *
2688 * Forcing a new expiration time will override the above mechanism.
2689 */
2690bool ichac97TimerSet(PAC97STATE pThis, PAC97STREAM pStream, uint64_t tsExpire, bool fForce)
2691{
2692 AssertPtrReturn(pThis, false);
2693 AssertPtrReturn(pStream, false);
2694
2695 RT_NOREF(fForce);
2696
2697 uint64_t tsExpireMin = tsExpire;
2698
2699 AssertPtr((pThis)->DEVAC97_CTX_SUFF_SD(pTimer, pStream->u8SD));
2700
2701 const uint64_t tsNow = TMTimerGet((pThis)->DEVAC97_CTX_SUFF_SD(pTimer, pStream->u8SD));
2702
2703 /* Make sure to not go backwards in time, as this will assert in TMTimerSet(). */
2704 if (tsExpireMin < tsNow)
2705 tsExpireMin = tsNow;
2706
2707 int rc = TMTimerSet((pThis)->DEVAC97_CTX_SUFF_SD(pTimer, pStream->u8SD), tsExpireMin);
2708 AssertRC(rc);
2709
2710 return RT_SUCCESS(rc);
2711}
2712
2713#ifdef IN_RING3
2714
2715/**
2716 * Transfers data of an AC'97 stream according to its usage (input / output).
2717 *
2718 * For an SDO (output) stream this means reading DMA data from the device to
2719 * the AC'97 stream's internal FIFO buffer.
2720 *
2721 * For an SDI (input) stream this is reading audio data from the AC'97 stream's
2722 * internal FIFO buffer and writing it as DMA data to the device.
2723 *
2724 * @returns IPRT status code.
2725 * @param pThis AC'97 state.
2726 * @param pStream AC'97 stream to update.
2727 * @param cbToProcessMax Maximum of data (in bytes) to process.
2728 */
2729static int ichac97R3StreamTransfer(PAC97STATE pThis, PAC97STREAM pStream, uint32_t cbToProcessMax)
2730{
2731 AssertPtrReturn(pThis, VERR_INVALID_POINTER);
2732 AssertPtrReturn(pStream, VERR_INVALID_POINTER);
2733
2734 if (!cbToProcessMax)
2735 return VINF_SUCCESS;
2736
2737#ifdef VBOX_STRICT
2738 const unsigned cbFrame = DrvAudioHlpPCMPropsBytesPerFrame(&pStream->State.Cfg.Props);
2739#endif
2740
2741 /* Make sure to only process an integer number of audio frames. */
2742 Assert(cbToProcessMax % cbFrame == 0);
2743
2744 ichac97R3StreamLock(pStream);
2745
2746 PAC97BMREGS pRegs = &pStream->Regs;
2747
2748 if (pRegs->sr & AC97_SR_DCH) /* Controller halted? */
2749 {
2750 if (pRegs->cr & AC97_CR_RPBM) /* Bus master operation starts. */
2751 {
2752 switch (pStream->u8SD)
2753 {
2754 case AC97SOUNDSOURCE_PO_INDEX:
2755 /*ichac97R3WriteBUP(pThis, cbToProcess);*/
2756 break;
2757
2758 default:
2759 break;
2760 }
2761 }
2762
2763 ichac97R3StreamUnlock(pStream);
2764 return VINF_SUCCESS;
2765 }
2766
2767 /* BCIS flag still set? Skip iteration. */
2768 if (pRegs->sr & AC97_SR_BCIS)
2769 {
2770 Log3Func(("[SD%RU8] BCIS set\n", pStream->u8SD));
2771
2772 ichac97R3StreamUnlock(pStream);
2773 return VINF_SUCCESS;
2774 }
2775
2776 uint32_t cbLeft = RT_MIN((uint32_t)(pRegs->picb << 1), cbToProcessMax); /** @todo r=andy Assumes 16bit samples. */
2777 uint32_t cbProcessedTotal = 0;
2778
2779 PRTCIRCBUF pCircBuf = pStream->State.pCircBuf;
2780 AssertPtr(pCircBuf);
2781
2782 int rc = VINF_SUCCESS;
2783
2784 Log3Func(("[SD%RU8] cbToProcessMax=%RU32, cbLeft=%RU32\n", pStream->u8SD, cbToProcessMax, cbLeft));
2785
2786 while (cbLeft)
2787 {
2788 if (!pRegs->picb) /* Got a new buffer descriptor, that is, the position is 0? */
2789 {
2790 Log3Func(("Fresh buffer descriptor %RU8 is empty, addr=%#x, len=%#x, skipping\n",
2791 pRegs->civ, pRegs->bd.addr, pRegs->bd.ctl_len));
2792 if (pRegs->civ == pRegs->lvi)
2793 {
2794 pRegs->sr |= AC97_SR_DCH; /** @todo r=andy Also set CELV? */
2795 pThis->bup_flag = 0;
2796
2797 rc = VINF_EOF;
2798 break;
2799 }
2800
2801 pRegs->sr &= ~AC97_SR_CELV;
2802 pRegs->civ = pRegs->piv;
2803 pRegs->piv = (pRegs->piv + 1) % AC97_MAX_BDLE;
2804
2805 ichac97R3StreamFetchBDLE(pThis, pStream);
2806 continue;
2807 }
2808
2809 uint32_t cbChunk = cbLeft;
2810
2811 switch (pStream->u8SD)
2812 {
2813 case AC97SOUNDSOURCE_PO_INDEX: /* Output */
2814 {
2815 void *pvDst;
2816 size_t cbDst;
2817
2818 RTCircBufAcquireWriteBlock(pCircBuf, cbChunk, &pvDst, &cbDst);
2819
2820 if (cbDst)
2821 {
2822 int rc2 = PDMDevHlpPhysRead(pThis->CTX_SUFF(pDevIns), pRegs->bd.addr, (uint8_t *)pvDst, cbDst);
2823 AssertRC(rc2);
2824
2825 if (pStream->Dbg.Runtime.fEnabled)
2826 DrvAudioHlpFileWrite(pStream->Dbg.Runtime.pFileDMA, pvDst, cbDst, 0 /* fFlags */);
2827 }
2828
2829 RTCircBufReleaseWriteBlock(pCircBuf, cbDst);
2830
2831 cbChunk = (uint32_t)cbDst; /* Update the current chunk size to what really has been written. */
2832 break;
2833 }
2834
2835 case AC97SOUNDSOURCE_PI_INDEX: /* Input */
2836 case AC97SOUNDSOURCE_MC_INDEX: /* Input */
2837 {
2838 void *pvSrc;
2839 size_t cbSrc;
2840
2841 RTCircBufAcquireReadBlock(pCircBuf, cbChunk, &pvSrc, &cbSrc);
2842
2843 if (cbSrc)
2844 {
2845/** @todo r=bird: Just curious, DevHDA uses PDMDevHlpPCIPhysWrite here. So,
2846 * is AC97 not subject to PCI busmaster enable/disable? */
2847 int rc2 = PDMDevHlpPhysWrite(pThis->CTX_SUFF(pDevIns), pRegs->bd.addr, (uint8_t *)pvSrc, cbSrc);
2848 AssertRC(rc2);
2849
2850 if (pStream->Dbg.Runtime.fEnabled)
2851 DrvAudioHlpFileWrite(pStream->Dbg.Runtime.pFileDMA, pvSrc, cbSrc, 0 /* fFlags */);
2852 }
2853
2854 RTCircBufReleaseReadBlock(pCircBuf, cbSrc);
2855
2856 cbChunk = (uint32_t)cbSrc; /* Update the current chunk size to what really has been read. */
2857 break;
2858 }
2859
2860 default:
2861 AssertMsgFailed(("Stream #%RU8 not supported\n", pStream->u8SD));
2862 rc = VERR_NOT_SUPPORTED;
2863 break;
2864 }
2865
2866 if (RT_FAILURE(rc))
2867 break;
2868
2869 if (cbChunk)
2870 {
2871 cbProcessedTotal += cbChunk;
2872 Assert(cbProcessedTotal <= cbToProcessMax);
2873 Assert(cbLeft >= cbChunk);
2874 cbLeft -= cbChunk;
2875 Assert((cbChunk & 1) == 0); /* Else the following shift won't work */
2876
2877 pRegs->picb -= (cbChunk >> 1); /** @todo r=andy Assumes 16bit samples. */
2878 pRegs->bd.addr += cbChunk;
2879 }
2880
2881 LogFlowFunc(("[SD%RU8] cbChunk=%RU32, cbLeft=%RU32, cbTotal=%RU32, rc=%Rrc\n",
2882 pStream->u8SD, cbChunk, cbLeft, cbProcessedTotal, rc));
2883
2884 if (!pRegs->picb)
2885 {
2886 uint32_t new_sr = pRegs->sr & ~AC97_SR_CELV;
2887
2888 if (pRegs->bd.ctl_len & AC97_BD_IOC)
2889 {
2890 new_sr |= AC97_SR_BCIS;
2891 }
2892
2893 if (pRegs->civ == pRegs->lvi)
2894 {
2895 /* Did we run out of data? */
2896 LogFunc(("Underrun CIV (%RU8) == LVI (%RU8)\n", pRegs->civ, pRegs->lvi));
2897
2898 new_sr |= AC97_SR_LVBCI | AC97_SR_DCH | AC97_SR_CELV;
2899 pThis->bup_flag = (pRegs->bd.ctl_len & AC97_BD_BUP) ? BUP_LAST : 0;
2900
2901 rc = VINF_EOF;
2902 }
2903 else
2904 {
2905 pRegs->civ = pRegs->piv;
2906 pRegs->piv = (pRegs->piv + 1) % AC97_MAX_BDLE;
2907 ichac97R3StreamFetchBDLE(pThis, pStream);
2908 }
2909
2910 ichac97StreamUpdateSR(pThis, pStream, new_sr);
2911 }
2912
2913 if (/* All data processed? */
2914 rc == VINF_EOF
2915 /* ... or an error occurred? */
2916 || RT_FAILURE(rc))
2917 {
2918 break;
2919 }
2920 }
2921
2922 ichac97R3StreamUnlock(pStream);
2923
2924 LogFlowFuncLeaveRC(rc);
2925 return rc;
2926}
2927
2928#endif /* IN_RING3 */
2929
2930
2931/**
2932 * Port I/O Handler for IN operations.
2933 *
2934 * @returns VINF_SUCCESS or VINF_EM_*.
2935 * @returns VERR_IOM_IOPORT_UNUSED if the port is really unused and a ~0 value should be returned.
2936 *
2937 * @param pDevIns The device instance.
2938 * @param pvUser User argument.
2939 * @param uPort Port number used for the IN operation.
2940 * @param pu32Val Where to store the result. This is always a 32-bit
2941 * variable regardless of what @a cbVal might say.
2942 * @param cbVal Number of bytes read.
2943 */
2944PDMBOTHCBDECL(int) ichac97IOPortNABMRead(PPDMDEVINS pDevIns, void *pvUser, RTIOPORT uPort, uint32_t *pu32Val, unsigned cbVal)
2945{
2946 PAC97STATE pThis = PDMINS_2_DATA(pDevIns, PAC97STATE);
2947 RT_NOREF(pvUser);
2948
2949 DEVAC97_LOCK_RETURN(pThis, VINF_IOM_R3_IOPORT_READ);
2950
2951 /* Get the index of the NABMBAR port. */
2952 const uint32_t uPortIdx = uPort - pThis->IOPortBase[1];
2953
2954 PAC97STREAM pStream = NULL;
2955 PAC97BMREGS pRegs = NULL;
2956
2957 if (AC97_PORT2IDX(uPortIdx) < AC97_MAX_STREAMS)
2958 {
2959 pStream = &pThis->aStreams[AC97_PORT2IDX(uPortIdx)];
2960 AssertPtr(pStream);
2961 pRegs = &pStream->Regs;
2962 }
2963
2964 int rc = VINF_SUCCESS;
2965
2966 switch (cbVal)
2967 {
2968 case 1:
2969 {
2970 switch (uPortIdx)
2971 {
2972 case AC97_CAS:
2973 /* Codec Access Semaphore Register */
2974 Log3Func(("CAS %d\n", pThis->cas));
2975 *pu32Val = pThis->cas;
2976 pThis->cas = 1;
2977 break;
2978 case PI_CIV:
2979 case PO_CIV:
2980 case MC_CIV:
2981 /* Current Index Value Register */
2982 *pu32Val = pRegs->civ;
2983 Log3Func(("CIV[%d] -> %#x\n", AC97_PORT2IDX(uPortIdx), *pu32Val));
2984 break;
2985 case PI_LVI:
2986 case PO_LVI:
2987 case MC_LVI:
2988 /* Last Valid Index Register */
2989 *pu32Val = pRegs->lvi;
2990 Log3Func(("LVI[%d] -> %#x\n", AC97_PORT2IDX(uPortIdx), *pu32Val));
2991 break;
2992 case PI_PIV:
2993 case PO_PIV:
2994 case MC_PIV:
2995 /* Prefetched Index Value Register */
2996 *pu32Val = pRegs->piv;
2997 Log3Func(("PIV[%d] -> %#x\n", AC97_PORT2IDX(uPortIdx), *pu32Val));
2998 break;
2999 case PI_CR:
3000 case PO_CR:
3001 case MC_CR:
3002 /* Control Register */
3003 *pu32Val = pRegs->cr;
3004 Log3Func(("CR[%d] -> %#x\n", AC97_PORT2IDX(uPortIdx), *pu32Val));
3005 break;
3006 case PI_SR:
3007 case PO_SR:
3008 case MC_SR:
3009 /* Status Register (lower part) */
3010 *pu32Val = RT_LO_U8(pRegs->sr);
3011 Log3Func(("SRb[%d] -> %#x\n", AC97_PORT2IDX(uPortIdx), *pu32Val));
3012 break;
3013 default:
3014 *pu32Val = UINT32_MAX;
3015 LogFunc(("U nabm readb %#x -> %#x\n", uPort, *pu32Val));
3016 break;
3017 }
3018 break;
3019 }
3020
3021 case 2:
3022 {
3023 switch (uPortIdx)
3024 {
3025 case PI_SR:
3026 case PO_SR:
3027 case MC_SR:
3028 /* Status Register */
3029 *pu32Val = pRegs->sr;
3030 Log3Func(("SR[%d] -> %#x\n", AC97_PORT2IDX(uPortIdx), *pu32Val));
3031 break;
3032 case PI_PICB:
3033 case PO_PICB:
3034 case MC_PICB:
3035 /* Position in Current Buffer */
3036 *pu32Val = pRegs->picb;
3037 Log3Func(("PICB[%d] -> %#x\n", AC97_PORT2IDX(uPortIdx), *pu32Val));
3038 break;
3039 default:
3040 *pu32Val = UINT32_MAX;
3041 LogFunc(("U nabm readw %#x -> %#x\n", uPort, *pu32Val));
3042 break;
3043 }
3044 break;
3045 }
3046
3047 case 4:
3048 {
3049 switch (uPortIdx)
3050 {
3051 case PI_BDBAR:
3052 case PO_BDBAR:
3053 case MC_BDBAR:
3054 /* Buffer Descriptor Base Address Register */
3055 *pu32Val = pRegs->bdbar;
3056 Log3Func(("BMADDR[%d] -> %#x\n", AC97_PORT2IDX(uPortIdx), *pu32Val));
3057 break;
3058 case PI_CIV:
3059 case PO_CIV:
3060 case MC_CIV:
3061 /* 32-bit access: Current Index Value Register +
3062 * Last Valid Index Register +
3063 * Status Register */
3064 *pu32Val = pRegs->civ | (pRegs->lvi << 8) | (pRegs->sr << 16); /** @todo r=andy Use RT_MAKE_U32_FROM_U8. */
3065 Log3Func(("CIV LVI SR[%d] -> %#x, %#x, %#x\n",
3066 AC97_PORT2IDX(uPortIdx), pRegs->civ, pRegs->lvi, pRegs->sr));
3067 break;
3068 case PI_PICB:
3069 case PO_PICB:
3070 case MC_PICB:
3071 /* 32-bit access: Position in Current Buffer Register +
3072 * Prefetched Index Value Register +
3073 * Control Register */
3074 *pu32Val = pRegs->picb | (pRegs->piv << 16) | (pRegs->cr << 24); /** @todo r=andy Use RT_MAKE_U32_FROM_U8. */
3075 Log3Func(("PICB PIV CR[%d] -> %#x %#x %#x %#x\n",
3076 AC97_PORT2IDX(uPortIdx), *pu32Val, pRegs->picb, pRegs->piv, pRegs->cr));
3077 break;
3078 case AC97_GLOB_CNT:
3079 /* Global Control */
3080 *pu32Val = pThis->glob_cnt;
3081 Log3Func(("glob_cnt -> %#x\n", *pu32Val));
3082 break;
3083 case AC97_GLOB_STA:
3084 /* Global Status */
3085 *pu32Val = pThis->glob_sta | AC97_GS_S0CR;
3086 Log3Func(("glob_sta -> %#x\n", *pu32Val));
3087 break;
3088 default:
3089 *pu32Val = UINT32_MAX;
3090 LogFunc(("U nabm readl %#x -> %#x\n", uPort, *pu32Val));
3091 break;
3092 }
3093 break;
3094 }
3095
3096 default:
3097 {
3098 AssertFailed();
3099 rc = VERR_IOM_IOPORT_UNUSED;
3100 }
3101 }
3102
3103 DEVAC97_UNLOCK(pThis);
3104
3105 return rc;
3106}
3107
3108/**
3109 * Port I/O Handler for OUT operations.
3110 *
3111 * @returns VINF_SUCCESS or VINF_EM_*.
3112 *
3113 * @param pDevIns The device instance.
3114 * @param pvUser User argument.
3115 * @param uPort Port number used for the OUT operation.
3116 * @param u32Val The value to output.
3117 * @param cbVal The value size in bytes.
3118 */
3119PDMBOTHCBDECL(int) ichac97IOPortNABMWrite(PPDMDEVINS pDevIns, void *pvUser, RTIOPORT uPort, uint32_t u32Val, unsigned cbVal)
3120{
3121 PAC97STATE pThis = PDMINS_2_DATA(pDevIns, PAC97STATE);
3122 RT_NOREF(pvUser);
3123
3124 /* Get the index of the NABMBAR register. */
3125 const uint32_t uPortIdx = uPort - pThis->IOPortBase[1];
3126
3127 PAC97STREAM pStream = NULL;
3128 PAC97BMREGS pRegs = NULL;
3129
3130 if (AC97_PORT2IDX(uPortIdx) < AC97_MAX_STREAMS)
3131 {
3132 pStream = &pThis->aStreams[AC97_PORT2IDX(uPortIdx)];
3133 AssertPtr(pStream);
3134 pRegs = &pStream->Regs;
3135
3136 DEVAC97_LOCK_BOTH_RETURN(pThis, pStream->u8SD, VINF_IOM_R3_IOPORT_WRITE);
3137 }
3138
3139 int rc = VINF_SUCCESS;
3140 switch (cbVal)
3141 {
3142 case 1:
3143 {
3144 switch (uPortIdx)
3145 {
3146 /*
3147 * Last Valid Index.
3148 */
3149 case PI_LVI:
3150 case PO_LVI:
3151 case MC_LVI:
3152 {
3153 AssertPtr(pStream);
3154 AssertPtr(pRegs);
3155 if ( (pRegs->cr & AC97_CR_RPBM)
3156 && (pRegs->sr & AC97_SR_DCH))
3157 {
3158#ifdef IN_RING3
3159 pRegs->sr &= ~(AC97_SR_DCH | AC97_SR_CELV);
3160 pRegs->civ = pRegs->piv;
3161 pRegs->piv = (pRegs->piv + 1) % AC97_MAX_BDLE;
3162#else
3163 rc = VINF_IOM_R3_IOPORT_WRITE;
3164#endif
3165 }
3166 pRegs->lvi = u32Val % AC97_MAX_BDLE;
3167 Log3Func(("[SD%RU8] LVI <- %#x\n", pStream->u8SD, u32Val));
3168 break;
3169 }
3170
3171 /*
3172 * Control Registers.
3173 */
3174 case PI_CR:
3175 case PO_CR:
3176 case MC_CR:
3177 {
3178 AssertPtr(pStream);
3179 AssertPtr(pRegs);
3180#ifdef IN_RING3
3181 Log3Func(("[SD%RU8] CR <- %#x (cr %#x)\n", pStream->u8SD, u32Val, pRegs->cr));
3182 if (u32Val & AC97_CR_RR) /* Busmaster reset. */
3183 {
3184 Log3Func(("[SD%RU8] Reset\n", pStream->u8SD));
3185
3186 /* Make sure that Run/Pause Bus Master bit (RPBM) is cleared (0). */
3187 Assert((pRegs->cr & AC97_CR_RPBM) == 0);
3188
3189 ichac97R3StreamEnable(pThis, pStream, false /* fEnable */);
3190 ichac97R3StreamReset(pThis, pStream);
3191
3192 ichac97StreamUpdateSR(pThis, pStream, AC97_SR_DCH); /** @todo Do we need to do that? */
3193 }
3194 else
3195 {
3196 pRegs->cr = u32Val & AC97_CR_VALID_MASK;
3197
3198 if (!(pRegs->cr & AC97_CR_RPBM))
3199 {
3200 Log3Func(("[SD%RU8] Disable\n", pStream->u8SD));
3201
3202 ichac97R3StreamEnable(pThis, pStream, false /* fEnable */);
3203
3204 pRegs->sr |= AC97_SR_DCH;
3205 }
3206 else
3207 {
3208 Log3Func(("[SD%RU8] Enable\n", pStream->u8SD));
3209
3210 pRegs->civ = pRegs->piv;
3211 pRegs->piv = (pRegs->piv + 1) % AC97_MAX_BDLE;
3212
3213 pRegs->sr &= ~AC97_SR_DCH;
3214
3215 /* Fetch the initial BDLE descriptor. */
3216 ichac97R3StreamFetchBDLE(pThis, pStream);
3217# ifdef LOG_ENABLED
3218 ichac97R3BDLEDumpAll(pThis, pStream->Regs.bdbar, pStream->Regs.lvi + 1);
3219# endif
3220 ichac97R3StreamEnable(pThis, pStream, true /* fEnable */);
3221
3222 /* Arm the timer for this stream. */
3223 int rc2 = ichac97TimerSet(pThis, pStream,
3224 TMTimerGet((pThis)->DEVAC97_CTX_SUFF_SD(pTimer, pStream->u8SD)) + pStream->State.cTransferTicks,
3225 false /* fForce */);
3226 AssertRC(rc2);
3227 }
3228 }
3229#else /* !IN_RING3 */
3230 rc = VINF_IOM_R3_IOPORT_WRITE;
3231#endif
3232 break;
3233 }
3234
3235 /*
3236 * Status Registers.
3237 */
3238 case PI_SR:
3239 case PO_SR:
3240 case MC_SR:
3241 {
3242 ichac97StreamWriteSR(pThis, pStream, u32Val);
3243 break;
3244 }
3245
3246 default:
3247 LogRel2(("AC97: Warning: Unimplemented NABMWrite (%u byte) portIdx=%#x <- %#x\n", cbVal, uPortIdx, u32Val));
3248 break;
3249 }
3250 break;
3251 }
3252
3253 case 2:
3254 {
3255 switch (uPortIdx)
3256 {
3257 case PI_SR:
3258 case PO_SR:
3259 case MC_SR:
3260 ichac97StreamWriteSR(pThis, pStream, u32Val);
3261 break;
3262 default:
3263 LogRel2(("AC97: Warning: Unimplemented NABMWrite (%u byte) portIdx=%#x <- %#x\n", cbVal, uPortIdx, u32Val));
3264 break;
3265 }
3266 break;
3267 }
3268
3269 case 4:
3270 {
3271 switch (uPortIdx)
3272 {
3273 case PI_BDBAR:
3274 case PO_BDBAR:
3275 case MC_BDBAR:
3276 AssertPtr(pStream);
3277 AssertPtr(pRegs);
3278 /* Buffer Descriptor list Base Address Register */
3279 pRegs->bdbar = u32Val & ~3;
3280 Log3Func(("[SD%RU8] BDBAR <- %#x (bdbar %#x)\n", AC97_PORT2IDX(uPortIdx), u32Val, pRegs->bdbar));
3281 break;
3282 case AC97_GLOB_CNT:
3283 /* Global Control */
3284 if (u32Val & AC97_GC_WR)
3285 ichac97WarmReset(pThis);
3286 if (u32Val & AC97_GC_CR)
3287 ichac97ColdReset(pThis);
3288 if (!(u32Val & (AC97_GC_WR | AC97_GC_CR)))
3289 pThis->glob_cnt = u32Val & AC97_GC_VALID_MASK;
3290 Log3Func(("glob_cnt <- %#x (glob_cnt %#x)\n", u32Val, pThis->glob_cnt));
3291 break;
3292 case AC97_GLOB_STA:
3293 /* Global Status */
3294 pThis->glob_sta &= ~(u32Val & AC97_GS_WCLEAR_MASK);
3295 pThis->glob_sta |= (u32Val & ~(AC97_GS_WCLEAR_MASK | AC97_GS_RO_MASK)) & AC97_GS_VALID_MASK;
3296 Log3Func(("glob_sta <- %#x (glob_sta %#x)\n", u32Val, pThis->glob_sta));
3297 break;
3298 default:
3299 LogRel2(("AC97: Warning: Unimplemented NABMWrite (%u byte) portIdx=%#x <- %#x\n", cbVal, uPortIdx, u32Val));
3300 break;
3301 }
3302 break;
3303 }
3304
3305 default:
3306 LogRel2(("AC97: Warning: Unimplemented NABMWrite (%u byte) portIdx=%#x <- %#x\n", cbVal, uPortIdx, u32Val));
3307 break;
3308 }
3309
3310 if (pStream)
3311 DEVAC97_UNLOCK_BOTH(pThis, pStream->u8SD);
3312
3313 return rc;
3314}
3315
3316/**
3317 * Port I/O Handler for IN operations.
3318 *
3319 * @returns VINF_SUCCESS or VINF_EM_*.
3320 * @returns VERR_IOM_IOPORT_UNUSED if the port is really unused and a ~0 value should be returned.
3321 *
3322 * @param pDevIns The device instance.
3323 * @param pvUser User argument.
3324 * @param uPort Port number used for the IN operation.
3325 * @param pu32Val Where to store the result. This is always a 32-bit
3326 * variable regardless of what @a cbVal might say.
3327 * @param cbVal Number of bytes read.
3328 */
3329PDMBOTHCBDECL(int) ichac97IOPortNAMRead(PPDMDEVINS pDevIns, void *pvUser, RTIOPORT uPort, uint32_t *pu32Val, unsigned cbVal)
3330{
3331 PAC97STATE pThis = PDMINS_2_DATA(pDevIns, PAC97STATE);
3332 RT_NOREF(pvUser);
3333
3334 DEVAC97_LOCK_RETURN(pThis, VINF_IOM_R3_IOPORT_READ);
3335
3336 int rc = VINF_SUCCESS;
3337
3338 uint32_t index = uPort - pThis->IOPortBase[0];
3339 Assert(index < 256);
3340
3341 switch (cbVal)
3342 {
3343 case 1:
3344 {
3345 LogRel2(("AC97: Warning: Unimplemented read (%u byte) port=%#x, idx=%RU32\n", cbVal, uPort, index));
3346 pThis->cas = 0;
3347 *pu32Val = UINT32_MAX;
3348 break;
3349 }
3350
3351 case 2:
3352 {
3353 pThis->cas = 0;
3354 *pu32Val = ichac97MixerGet(pThis, index);
3355 break;
3356 }
3357
3358 case 4:
3359 {
3360 LogRel2(("AC97: Warning: Unimplemented read (%u byte) port=%#x, idx=%RU32\n", cbVal, uPort, index));
3361 pThis->cas = 0;
3362 *pu32Val = UINT32_MAX;
3363 break;
3364 }
3365
3366 default:
3367 {
3368 AssertFailed();
3369 rc = VERR_IOM_IOPORT_UNUSED;
3370 }
3371 }
3372
3373 DEVAC97_UNLOCK(pThis);
3374
3375 return rc;
3376}
3377
3378/**
3379 * Port I/O Handler for OUT operations.
3380 *
3381 * @returns VINF_SUCCESS or VINF_EM_*.
3382 *
3383 * @param pDevIns The device instance.
3384 * @param pvUser User argument.
3385 * @param uPort Port number used for the OUT operation.
3386 * @param u32Val The value to output.
3387 * @param cbVal The value size in bytes.
3388 * @remarks Caller enters the device critical section.
3389 */
3390PDMBOTHCBDECL(int) ichac97IOPortNAMWrite(PPDMDEVINS pDevIns, void *pvUser, RTIOPORT uPort, uint32_t u32Val, unsigned cbVal)
3391{
3392 PAC97STATE pThis = PDMINS_2_DATA(pDevIns, PAC97STATE);
3393 RT_NOREF(pvUser);
3394
3395 DEVAC97_LOCK_RETURN(pThis, VINF_IOM_R3_IOPORT_WRITE);
3396
3397 uint32_t uPortIdx = uPort - pThis->IOPortBase[0];
3398
3399 int rc = VINF_SUCCESS;
3400 switch (cbVal)
3401 {
3402 case 1:
3403 {
3404 LogRel2(("AC97: Warning: Unimplemented NAMWrite (%u byte) port=%#x, idx=0x%x <- %#x\n", cbVal, uPort, uPortIdx, u32Val));
3405 pThis->cas = 0;
3406 break;
3407 }
3408
3409 case 2:
3410 {
3411 pThis->cas = 0;
3412 switch (uPortIdx)
3413 {
3414 case AC97_Reset:
3415#ifdef IN_RING3
3416 ichac97R3Reset(pThis->CTX_SUFF(pDevIns));
3417#else
3418 rc = VINF_IOM_R3_IOPORT_WRITE;
3419#endif
3420 break;
3421 case AC97_Powerdown_Ctrl_Stat:
3422 u32Val &= ~0xf;
3423 u32Val |= ichac97MixerGet(pThis, uPortIdx) & 0xf;
3424 ichac97MixerSet(pThis, uPortIdx, u32Val);
3425 break;
3426 case AC97_Master_Volume_Mute:
3427 if (pThis->uCodecModel == AC97_CODEC_AD1980)
3428 {
3429 if (ichac97MixerGet(pThis, AC97_AD_Misc) & AC97_AD_MISC_LOSEL)
3430 break; /* Register controls surround (rear), do nothing. */
3431 }
3432#ifdef IN_RING3
3433 ichac97R3MixerSetVolume(pThis, uPortIdx, PDMAUDIOMIXERCTL_VOLUME_MASTER, u32Val);
3434#else
3435 rc = VINF_IOM_R3_IOPORT_WRITE;
3436#endif
3437 break;
3438 case AC97_Headphone_Volume_Mute:
3439 if (pThis->uCodecModel == AC97_CODEC_AD1980)
3440 {
3441 if (ichac97MixerGet(pThis, AC97_AD_Misc) & AC97_AD_MISC_HPSEL)
3442 {
3443 /* Register controls PCM (front) outputs. */
3444#ifdef IN_RING3
3445 ichac97R3MixerSetVolume(pThis, uPortIdx, PDMAUDIOMIXERCTL_VOLUME_MASTER, u32Val);
3446#else
3447 rc = VINF_IOM_R3_IOPORT_WRITE;
3448#endif
3449 }
3450 }
3451 break;
3452 case AC97_PCM_Out_Volume_Mute:
3453#ifdef IN_RING3
3454 ichac97R3MixerSetVolume(pThis, uPortIdx, PDMAUDIOMIXERCTL_FRONT, u32Val);
3455#else
3456 rc = VINF_IOM_R3_IOPORT_WRITE;
3457#endif
3458 break;
3459 case AC97_Line_In_Volume_Mute:
3460#ifdef IN_RING3
3461 ichac97R3MixerSetVolume(pThis, uPortIdx, PDMAUDIOMIXERCTL_LINE_IN, u32Val);
3462#else
3463 rc = VINF_IOM_R3_IOPORT_WRITE;
3464#endif
3465 break;
3466 case AC97_Record_Select:
3467#ifdef IN_RING3
3468 ichac97R3MixerRecordSelect(pThis, u32Val);
3469#else
3470 rc = VINF_IOM_R3_IOPORT_WRITE;
3471#endif
3472 break;
3473 case AC97_Record_Gain_Mute:
3474#ifdef IN_RING3
3475 /* Newer Ubuntu guests rely on that when controlling gain and muting
3476 * the recording (capturing) levels. */
3477 ichac97R3MixerSetGain(pThis, uPortIdx, PDMAUDIOMIXERCTL_LINE_IN, u32Val);
3478#else
3479 rc = VINF_IOM_R3_IOPORT_WRITE;
3480#endif
3481 break;
3482 case AC97_Record_Gain_Mic_Mute:
3483#ifdef IN_RING3
3484 /* Ditto; see note above. */
3485 ichac97R3MixerSetGain(pThis, uPortIdx, PDMAUDIOMIXERCTL_MIC_IN, u32Val);
3486#else
3487 rc = VINF_IOM_R3_IOPORT_WRITE;
3488#endif
3489 break;
3490 case AC97_Vendor_ID1:
3491 case AC97_Vendor_ID2:
3492 LogFunc(("Attempt to write vendor ID to %#x\n", u32Val));
3493 break;
3494 case AC97_Extended_Audio_ID:
3495 LogFunc(("Attempt to write extended audio ID to %#x\n", u32Val));
3496 break;
3497 case AC97_Extended_Audio_Ctrl_Stat:
3498#ifdef IN_RING3
3499 if (!(u32Val & AC97_EACS_VRA))
3500 {
3501 ichac97MixerSet(pThis, AC97_PCM_Front_DAC_Rate, 48000);
3502 ichac97R3StreamReOpen(pThis, &pThis->aStreams[AC97SOUNDSOURCE_PO_INDEX]);
3503
3504 ichac97MixerSet(pThis, AC97_PCM_LR_ADC_Rate, 48000);
3505 ichac97R3StreamReOpen(pThis, &pThis->aStreams[AC97SOUNDSOURCE_PI_INDEX]);
3506 }
3507 else
3508 LogRel2(("AC97: Variable rate audio (VRA) is not supported\n"));
3509
3510 if (!(u32Val & AC97_EACS_VRM))
3511 {
3512 ichac97MixerSet(pThis, AC97_MIC_ADC_Rate, 48000);
3513 ichac97R3StreamReOpen(pThis, &pThis->aStreams[AC97SOUNDSOURCE_MC_INDEX]);
3514 }
3515 else
3516 LogRel2(("AC97: Variable rate microphone audio (VRM) is not supported\n"));
3517
3518 LogFunc(("Setting extended audio control to %#x\n", u32Val));
3519 ichac97MixerSet(pThis, AC97_Extended_Audio_Ctrl_Stat, u32Val);
3520#else
3521 rc = VINF_IOM_R3_IOPORT_WRITE;
3522#endif
3523 break;
3524 case AC97_PCM_Front_DAC_Rate:
3525 if (ichac97MixerGet(pThis, AC97_Extended_Audio_Ctrl_Stat) & AC97_EACS_VRA)
3526 {
3527#ifdef IN_RING3
3528 ichac97MixerSet(pThis, uPortIdx, u32Val);
3529 LogFunc(("Set front DAC rate to %RU32\n", u32Val));
3530 ichac97R3StreamReOpen(pThis, &pThis->aStreams[AC97SOUNDSOURCE_PO_INDEX]);
3531#else
3532 rc = VINF_IOM_R3_IOPORT_WRITE;
3533#endif
3534 }
3535 else
3536 LogRel2(("AC97: Setting Front DAC rate when VRA is not set is forbidden, ignoring\n"));
3537 break;
3538 case AC97_MIC_ADC_Rate:
3539 if (ichac97MixerGet(pThis, AC97_Extended_Audio_Ctrl_Stat) & AC97_EACS_VRM)
3540 {
3541#ifdef IN_RING3
3542 ichac97MixerSet(pThis, uPortIdx, u32Val);
3543 LogFunc(("Set MIC ADC rate to %RU32\n", u32Val));
3544 ichac97R3StreamReOpen(pThis, &pThis->aStreams[AC97SOUNDSOURCE_MC_INDEX]);
3545#else
3546 rc = VINF_IOM_R3_IOPORT_WRITE;
3547#endif
3548 }
3549 else
3550 LogRel2(("AC97: Setting MIC ADC rate when VRM is not set is forbidden, ignoring\n"));
3551 break;
3552 case AC97_PCM_LR_ADC_Rate:
3553 if (ichac97MixerGet(pThis, AC97_Extended_Audio_Ctrl_Stat) & AC97_EACS_VRA)
3554 {
3555#ifdef IN_RING3
3556 ichac97MixerSet(pThis, uPortIdx, u32Val);
3557 LogFunc(("Set front LR ADC rate to %RU32\n", u32Val));
3558 ichac97R3StreamReOpen(pThis, &pThis->aStreams[AC97SOUNDSOURCE_PI_INDEX]);
3559#else
3560 rc = VINF_IOM_R3_IOPORT_WRITE;
3561#endif
3562 }
3563 else
3564 LogRel2(("AC97: Setting LR ADC rate when VRA is not set is forbidden, ignoring\n"));
3565 break;
3566 default:
3567 LogRel2(("AC97: Warning: Unimplemented NAMWrite (%u byte) port=%#x, idx=0x%x <- %#x\n", cbVal, uPort, uPortIdx, u32Val));
3568 ichac97MixerSet(pThis, uPortIdx, u32Val);
3569 break;
3570 }
3571 break;
3572 }
3573
3574 case 4:
3575 {
3576 LogRel2(("AC97: Warning: Unimplemented NAMWrite (%u byte) port=%#x, idx=0x%x <- %#x\n", cbVal, uPort, uPortIdx, u32Val));
3577 pThis->cas = 0;
3578 break;
3579 }
3580
3581 default:
3582 AssertMsgFailed(("Unhandled NAMWrite port=%#x, cbVal=%u u32Val=%#x\n", uPort, cbVal, u32Val));
3583 break;
3584 }
3585
3586 DEVAC97_UNLOCK(pThis);
3587
3588 return rc;
3589}
3590
3591#ifdef IN_RING3
3592
3593/**
3594 * @callback_method_impl{FNPCIIOREGIONMAP}
3595 */
3596static DECLCALLBACK(int) ichac97R3IOPortMap(PPDMDEVINS pDevIns, PPDMPCIDEV pPciDev, uint32_t iRegion,
3597 RTGCPHYS GCPhysAddress, RTGCPHYS cb, PCIADDRESSSPACE enmType)
3598{
3599 RT_NOREF(cb, enmType);
3600
3601 Assert(enmType == PCI_ADDRESS_SPACE_IO);
3602 Assert(cb >= 0x20);
3603
3604 if (iRegion > 1) /* We support 2 regions max. at the moment. */
3605 return VERR_INVALID_PARAMETER;
3606
3607 PAC97STATE pThis = RT_FROM_MEMBER(pPciDev, AC97STATE, PciDev);
3608 RTIOPORT Port = (RTIOPORT)GCPhysAddress;
3609
3610 int rc;
3611 if (iRegion == 0)
3612 {
3613 rc = PDMDevHlpIOPortRegister(pDevIns, Port, 256, NULL, ichac97IOPortNAMWrite, ichac97IOPortNAMRead,
3614 NULL, NULL, "ICHAC97 NAM");
3615 AssertRCReturn(rc, rc);
3616 if (pThis->fRZEnabled)
3617 {
3618 rc = PDMDevHlpIOPortRegisterR0(pDevIns, Port, 256, NIL_RTR0PTR, "ichac97IOPortNAMWrite", "ichac97IOPortNAMRead",
3619 NULL, NULL, "ICHAC97 NAM");
3620 AssertRCReturn(rc, rc);
3621 rc = PDMDevHlpIOPortRegisterRC(pDevIns, Port, 256, NIL_RTRCPTR, "ichac97IOPortNAMWrite", "ichac97IOPortNAMRead",
3622 NULL, NULL, "ICHAC97 NAM");
3623 AssertRCReturn(rc, rc);
3624 }
3625 }
3626 else
3627 {
3628 rc = PDMDevHlpIOPortRegister(pDevIns, Port, 64, NULL, ichac97IOPortNABMWrite, ichac97IOPortNABMRead,
3629 NULL, NULL, "ICHAC97 NABM");
3630 AssertRCReturn(rc, rc);
3631 if (pThis->fRZEnabled)
3632 {
3633 rc = PDMDevHlpIOPortRegisterR0(pDevIns, Port, 64, NIL_RTR0PTR, "ichac97IOPortNABMWrite", "ichac97IOPortNABMRead",
3634 NULL, NULL, "ICHAC97 NABM");
3635 AssertRCReturn(rc, rc);
3636 rc = PDMDevHlpIOPortRegisterRC(pDevIns, Port, 64, NIL_RTRCPTR, "ichac97IOPortNABMWrite", "ichac97IOPortNABMRead",
3637 NULL, NULL, "ICHAC97 NABM");
3638 AssertRCReturn(rc, rc);
3639
3640 }
3641 }
3642
3643 pThis->IOPortBase[iRegion] = Port;
3644 return VINF_SUCCESS;
3645}
3646
3647
3648/**
3649 * Saves (serializes) an AC'97 stream using SSM.
3650 *
3651 * @returns IPRT status code.
3652 * @param pDevIns Device instance.
3653 * @param pSSM Saved state manager (SSM) handle to use.
3654 * @param pStream AC'97 stream to save.
3655 */
3656static int ichac97R3SaveStream(PPDMDEVINS pDevIns, PSSMHANDLE pSSM, PAC97STREAM pStream)
3657{
3658 RT_NOREF(pDevIns);
3659 PAC97BMREGS pRegs = &pStream->Regs;
3660
3661 SSMR3PutU32(pSSM, pRegs->bdbar);
3662 SSMR3PutU8( pSSM, pRegs->civ);
3663 SSMR3PutU8( pSSM, pRegs->lvi);
3664 SSMR3PutU16(pSSM, pRegs->sr);
3665 SSMR3PutU16(pSSM, pRegs->picb);
3666 SSMR3PutU8( pSSM, pRegs->piv);
3667 SSMR3PutU8( pSSM, pRegs->cr);
3668 SSMR3PutS32(pSSM, pRegs->bd_valid);
3669 SSMR3PutU32(pSSM, pRegs->bd.addr);
3670 SSMR3PutU32(pSSM, pRegs->bd.ctl_len);
3671
3672 return VINF_SUCCESS;
3673}
3674
3675/**
3676 * @callback_method_impl{FNSSMDEVSAVEEXEC}
3677 */
3678static DECLCALLBACK(int) ichac97R3SaveExec(PPDMDEVINS pDevIns, PSSMHANDLE pSSM)
3679{
3680 PAC97STATE pThis = PDMINS_2_DATA(pDevIns, PAC97STATE);
3681
3682 LogFlowFuncEnter();
3683
3684 SSMR3PutU32(pSSM, pThis->glob_cnt);
3685 SSMR3PutU32(pSSM, pThis->glob_sta);
3686 SSMR3PutU32(pSSM, pThis->cas);
3687
3688 /** @todo r=andy For the next saved state version, add unique stream identifiers and a stream count. */
3689 /* Note: The order the streams are loaded here is critical, so don't touch. */
3690 for (unsigned i = 0; i < AC97_MAX_STREAMS; i++)
3691 {
3692 int rc2 = ichac97R3SaveStream(pDevIns, pSSM, &pThis->aStreams[i]);
3693 AssertRC(rc2);
3694 }
3695
3696 SSMR3PutMem(pSSM, pThis->mixer_data, sizeof(pThis->mixer_data));
3697
3698 uint8_t active[AC97SOUNDSOURCE_END_INDEX];
3699
3700 active[AC97SOUNDSOURCE_PI_INDEX] = ichac97R3StreamIsEnabled(pThis, &pThis->aStreams[AC97SOUNDSOURCE_PI_INDEX]) ? 1 : 0;
3701 active[AC97SOUNDSOURCE_PO_INDEX] = ichac97R3StreamIsEnabled(pThis, &pThis->aStreams[AC97SOUNDSOURCE_PO_INDEX]) ? 1 : 0;
3702 active[AC97SOUNDSOURCE_MC_INDEX] = ichac97R3StreamIsEnabled(pThis, &pThis->aStreams[AC97SOUNDSOURCE_MC_INDEX]) ? 1 : 0;
3703
3704 SSMR3PutMem(pSSM, active, sizeof(active));
3705
3706 LogFlowFuncLeaveRC(VINF_SUCCESS);
3707 return VINF_SUCCESS;
3708}
3709
3710/**
3711 * Loads an AC'97 stream from SSM.
3712 *
3713 * @returns IPRT status code.
3714 * @param pSSM Saved state manager (SSM) handle to use.
3715 * @param pStream AC'97 stream to load.
3716 */
3717static int ichac97R3LoadStream(PSSMHANDLE pSSM, PAC97STREAM pStream)
3718{
3719 PAC97BMREGS pRegs = &pStream->Regs;
3720
3721 SSMR3GetU32(pSSM, &pRegs->bdbar);
3722 SSMR3GetU8( pSSM, &pRegs->civ);
3723 SSMR3GetU8( pSSM, &pRegs->lvi);
3724 SSMR3GetU16(pSSM, &pRegs->sr);
3725 SSMR3GetU16(pSSM, &pRegs->picb);
3726 SSMR3GetU8( pSSM, &pRegs->piv);
3727 SSMR3GetU8( pSSM, &pRegs->cr);
3728 SSMR3GetS32(pSSM, &pRegs->bd_valid);
3729 SSMR3GetU32(pSSM, &pRegs->bd.addr);
3730 return SSMR3GetU32(pSSM, &pRegs->bd.ctl_len);
3731}
3732
3733/**
3734 * @callback_method_impl{FNSSMDEVLOADEXEC}
3735 */
3736static DECLCALLBACK(int) ichac97R3LoadExec(PPDMDEVINS pDevIns, PSSMHANDLE pSSM, uint32_t uVersion, uint32_t uPass)
3737{
3738 PAC97STATE pThis = PDMINS_2_DATA(pDevIns, PAC97STATE);
3739
3740 LogRel2(("ichac97LoadExec: uVersion=%RU32, uPass=0x%x\n", uVersion, uPass));
3741
3742 AssertMsgReturn (uVersion == AC97_SSM_VERSION, ("%RU32\n", uVersion), VERR_SSM_UNSUPPORTED_DATA_UNIT_VERSION);
3743 Assert(uPass == SSM_PASS_FINAL); NOREF(uPass);
3744
3745 SSMR3GetU32(pSSM, &pThis->glob_cnt);
3746 SSMR3GetU32(pSSM, &pThis->glob_sta);
3747 SSMR3GetU32(pSSM, &pThis->cas);
3748
3749 /** @todo r=andy For the next saved state version, add unique stream identifiers and a stream count. */
3750 /* Note: The order the streams are loaded here is critical, so don't touch. */
3751 for (unsigned i = 0; i < AC97_MAX_STREAMS; i++)
3752 {
3753 int rc2 = ichac97R3LoadStream(pSSM, &pThis->aStreams[i]);
3754 AssertRCReturn(rc2, rc2);
3755 }
3756
3757 SSMR3GetMem(pSSM, pThis->mixer_data, sizeof(pThis->mixer_data));
3758
3759 /** @todo r=andy Stream IDs are hardcoded to certain streams. */
3760 uint8_t uaStrmsActive[AC97SOUNDSOURCE_END_INDEX];
3761 int rc2 = SSMR3GetMem(pSSM, uaStrmsActive, sizeof(uaStrmsActive));
3762 AssertRCReturn(rc2, rc2);
3763
3764 ichac97R3MixerRecordSelect(pThis, ichac97MixerGet(pThis, AC97_Record_Select));
3765 ichac97R3MixerSetVolume(pThis, AC97_Master_Volume_Mute, PDMAUDIOMIXERCTL_VOLUME_MASTER, ichac97MixerGet(pThis, AC97_Master_Volume_Mute));
3766 ichac97R3MixerSetVolume(pThis, AC97_PCM_Out_Volume_Mute, PDMAUDIOMIXERCTL_FRONT, ichac97MixerGet(pThis, AC97_PCM_Out_Volume_Mute));
3767 ichac97R3MixerSetVolume(pThis, AC97_Line_In_Volume_Mute, PDMAUDIOMIXERCTL_LINE_IN, ichac97MixerGet(pThis, AC97_Line_In_Volume_Mute));
3768 ichac97R3MixerSetVolume(pThis, AC97_Mic_Volume_Mute, PDMAUDIOMIXERCTL_MIC_IN, ichac97MixerGet(pThis, AC97_Mic_Volume_Mute));
3769 ichac97R3MixerSetGain(pThis, AC97_Record_Gain_Mic_Mute, PDMAUDIOMIXERCTL_MIC_IN, ichac97MixerGet(pThis, AC97_Record_Gain_Mic_Mute));
3770 ichac97R3MixerSetGain(pThis, AC97_Record_Gain_Mute, PDMAUDIOMIXERCTL_LINE_IN, ichac97MixerGet(pThis, AC97_Record_Gain_Mute));
3771 if (pThis->uCodecModel == AC97_CODEC_AD1980)
3772 if (ichac97MixerGet(pThis, AC97_AD_Misc) & AC97_AD_MISC_HPSEL)
3773 ichac97R3MixerSetVolume(pThis, AC97_Headphone_Volume_Mute, PDMAUDIOMIXERCTL_VOLUME_MASTER,
3774 ichac97MixerGet(pThis, AC97_Headphone_Volume_Mute));
3775
3776 /** @todo r=andy Stream IDs are hardcoded to certain streams. */
3777 for (unsigned i = 0; i < AC97_MAX_STREAMS; i++)
3778 {
3779 const bool fEnable = RT_BOOL(uaStrmsActive[i]);
3780 const PAC97STREAM pStream = &pThis->aStreams[i];
3781
3782 rc2 = ichac97R3StreamEnable(pThis, pStream, fEnable);
3783 if ( fEnable
3784 && RT_SUCCESS(rc2))
3785 {
3786 /* Re-arm the timer for this stream. */
3787 rc2 = ichac97TimerSet(pThis, pStream,
3788 TMTimerGet((pThis)->DEVAC97_CTX_SUFF_SD(pTimer, pStream->u8SD)) + pStream->State.cTransferTicks,
3789 false /* fForce */);
3790 }
3791
3792 AssertRC(rc2);
3793 /* Keep going. */
3794 }
3795
3796 pThis->bup_flag = 0;
3797 pThis->last_samp = 0;
3798
3799 return VINF_SUCCESS;
3800}
3801
3802
3803/**
3804 * @interface_method_impl{PDMIBASE,pfnQueryInterface}
3805 */
3806static DECLCALLBACK(void *) ichac97R3QueryInterface(struct PDMIBASE *pInterface, const char *pszIID)
3807{
3808 PAC97STATE pThis = RT_FROM_MEMBER(pInterface, AC97STATE, IBase);
3809 Assert(&pThis->IBase == pInterface);
3810
3811 PDMIBASE_RETURN_INTERFACE(pszIID, PDMIBASE, &pThis->IBase);
3812 return NULL;
3813}
3814
3815
3816/**
3817 * Powers off the device.
3818 *
3819 * @param pDevIns Device instance to power off.
3820 */
3821static DECLCALLBACK(void) ichac97R3PowerOff(PPDMDEVINS pDevIns)
3822{
3823 PAC97STATE pThis = PDMINS_2_DATA(pDevIns, PAC97STATE);
3824
3825 LogRel2(("AC97: Powering off ...\n"));
3826
3827 /* Note: Involves mixer stream / sink destruction, so also do this here
3828 * instead of in ichac97R3Destruct(). */
3829 ichac97R3StreamsDestroy(pThis);
3830
3831 /**
3832 * Note: Destroy the mixer while powering off and *not* in ichac97R3Destruct,
3833 * giving the mixer the chance to release any references held to
3834 * PDM audio streams it maintains.
3835 */
3836 if (pThis->pMixer)
3837 {
3838 AudioMixerDestroy(pThis->pMixer);
3839 pThis->pMixer = NULL;
3840 }
3841}
3842
3843
3844/**
3845 * @interface_method_impl{PDMDEVREG,pfnReset}
3846 *
3847 * @remarks The original sources didn't install a reset handler, but it seems to
3848 * make sense to me so we'll do it.
3849 */
3850static DECLCALLBACK(void) ichac97R3Reset(PPDMDEVINS pDevIns)
3851{
3852 PAC97STATE pThis = PDMINS_2_DATA(pDevIns, PAC97STATE);
3853
3854 LogRel(("AC97: Reset\n"));
3855
3856 /*
3857 * Reset the mixer too. The Windows XP driver seems to rely on
3858 * this. At least it wants to read the vendor id before it resets
3859 * the codec manually.
3860 */
3861 ichac97R3MixerReset(pThis);
3862
3863 /*
3864 * Reset all streams.
3865 */
3866 for (unsigned i = 0; i < AC97_MAX_STREAMS; i++)
3867 {
3868 ichac97R3StreamEnable(pThis, &pThis->aStreams[i], false /* fEnable */);
3869 ichac97R3StreamReset(pThis, &pThis->aStreams[i]);
3870 }
3871
3872 /*
3873 * Reset mixer sinks.
3874 *
3875 * Do the reset here instead of in ichac97R3StreamReset();
3876 * the mixer sink(s) might still have data to be processed when an audio stream gets reset.
3877 */
3878 AudioMixerSinkReset(pThis->pSinkLineIn);
3879 AudioMixerSinkReset(pThis->pSinkMicIn);
3880 AudioMixerSinkReset(pThis->pSinkOut);
3881}
3882
3883
3884/**
3885 * Attach command, internal version.
3886 *
3887 * This is called to let the device attach to a driver for a specified LUN
3888 * during runtime. This is not called during VM construction, the device
3889 * constructor has to attach to all the available drivers.
3890 *
3891 * @returns VBox status code.
3892 * @param pThis AC'97 state.
3893 * @param uLUN The logical unit which is being attached.
3894 * @param fFlags Flags, combination of the PDMDEVATT_FLAGS_* \#defines.
3895 * @param ppDrv Attached driver instance on success. Optional.
3896 */
3897static int ichac97R3AttachInternal(PAC97STATE pThis, unsigned uLUN, uint32_t fFlags, PAC97DRIVER *ppDrv)
3898{
3899 RT_NOREF(fFlags);
3900
3901 /*
3902 * Attach driver.
3903 */
3904 char *pszDesc;
3905 if (RTStrAPrintf(&pszDesc, "Audio driver port (AC'97) for LUN #%u", uLUN) <= 0)
3906 AssertLogRelFailedReturn(VERR_NO_MEMORY);
3907
3908 PPDMIBASE pDrvBase;
3909 int rc = PDMDevHlpDriverAttach(pThis->pDevInsR3, uLUN,
3910 &pThis->IBase, &pDrvBase, pszDesc);
3911 if (RT_SUCCESS(rc))
3912 {
3913 PAC97DRIVER pDrv = (PAC97DRIVER)RTMemAllocZ(sizeof(AC97DRIVER));
3914 if (pDrv)
3915 {
3916 pDrv->pDrvBase = pDrvBase;
3917 pDrv->pConnector = PDMIBASE_QUERY_INTERFACE(pDrvBase, PDMIAUDIOCONNECTOR);
3918 AssertMsg(pDrv->pConnector != NULL, ("Configuration error: LUN #%u has no host audio interface, rc=%Rrc\n", uLUN, rc));
3919 pDrv->pAC97State = pThis;
3920 pDrv->uLUN = uLUN;
3921
3922 /*
3923 * For now we always set the driver at LUN 0 as our primary
3924 * host backend. This might change in the future.
3925 */
3926 if (pDrv->uLUN == 0)
3927 pDrv->fFlags |= PDMAUDIODRVFLAGS_PRIMARY;
3928
3929 LogFunc(("LUN#%RU8: pCon=%p, drvFlags=0x%x\n", uLUN, pDrv->pConnector, pDrv->fFlags));
3930
3931 /* Attach to driver list if not attached yet. */
3932 if (!pDrv->fAttached)
3933 {
3934 RTListAppend(&pThis->lstDrv, &pDrv->Node);
3935 pDrv->fAttached = true;
3936 }
3937
3938 if (ppDrv)
3939 *ppDrv = pDrv;
3940 }
3941 else
3942 rc = VERR_NO_MEMORY;
3943 }
3944 else if (rc == VERR_PDM_NO_ATTACHED_DRIVER)
3945 LogFunc(("No attached driver for LUN #%u\n", uLUN));
3946
3947 if (RT_FAILURE(rc))
3948 {
3949 /* Only free this string on failure;
3950 * must remain valid for the live of the driver instance. */
3951 RTStrFree(pszDesc);
3952 }
3953
3954 LogFunc(("uLUN=%u, fFlags=0x%x, rc=%Rrc\n", uLUN, fFlags, rc));
3955 return rc;
3956}
3957
3958/**
3959 * Detach command, internal version.
3960 *
3961 * This is called to let the device detach from a driver for a specified LUN
3962 * during runtime.
3963 *
3964 * @returns VBox status code.
3965 * @param pThis AC'97 state.
3966 * @param pDrv Driver to detach from device.
3967 * @param fFlags Flags, combination of the PDMDEVATT_FLAGS_* \#defines.
3968 */
3969static int ichac97R3DetachInternal(PAC97STATE pThis, PAC97DRIVER pDrv, uint32_t fFlags)
3970{
3971 RT_NOREF(fFlags);
3972
3973 /* First, remove the driver from our list and destory it's associated streams.
3974 * This also will un-set the driver as a recording source (if associated). */
3975 ichac97R3MixerRemoveDrv(pThis, pDrv);
3976
3977 /* Next, search backwards for a capable (attached) driver which now will be the
3978 * new recording source. */
3979 PDMAUDIODESTSOURCE dstSrc;
3980 PAC97DRIVER pDrvCur;
3981 RTListForEachReverse(&pThis->lstDrv, pDrvCur, AC97DRIVER, Node)
3982 {
3983 if (!pDrvCur->pConnector)
3984 continue;
3985
3986 PDMAUDIOBACKENDCFG Cfg;
3987 int rc2 = pDrvCur->pConnector->pfnGetConfig(pDrvCur->pConnector, &Cfg);
3988 if (RT_FAILURE(rc2))
3989 continue;
3990
3991 dstSrc.Source = PDMAUDIORECSOURCE_MIC;
3992 PAC97DRIVERSTREAM pDrvStrm = ichac97R3MixerGetDrvStream(pThis, pDrvCur, PDMAUDIODIR_IN, dstSrc);
3993 if ( pDrvStrm
3994 && pDrvStrm->pMixStrm)
3995 {
3996 rc2 = AudioMixerSinkSetRecordingSource(pThis->pSinkMicIn, pDrvStrm->pMixStrm);
3997 if (RT_SUCCESS(rc2))
3998 LogRel2(("AC97: Set new recording source for 'Mic In' to '%s'\n", Cfg.szName));
3999 }
4000
4001 dstSrc.Source = PDMAUDIORECSOURCE_LINE;
4002 pDrvStrm = ichac97R3MixerGetDrvStream(pThis, pDrvCur, PDMAUDIODIR_IN, dstSrc);
4003 if ( pDrvStrm
4004 && pDrvStrm->pMixStrm)
4005 {
4006 rc2 = AudioMixerSinkSetRecordingSource(pThis->pSinkLineIn, pDrvStrm->pMixStrm);
4007 if (RT_SUCCESS(rc2))
4008 LogRel2(("AC97: Set new recording source for 'Line In' to '%s'\n", Cfg.szName));
4009 }
4010 }
4011
4012 LogFunc(("uLUN=%u, fFlags=0x%x\n", pDrv->uLUN, fFlags));
4013 return VINF_SUCCESS;
4014}
4015
4016/**
4017 * @interface_method_impl{PDMDEVREG,pfnAttach}
4018 */
4019static DECLCALLBACK(int) ichac97R3Attach(PPDMDEVINS pDevIns, unsigned uLUN, uint32_t fFlags)
4020{
4021 PAC97STATE pThis = PDMINS_2_DATA(pDevIns, PAC97STATE);
4022
4023 LogFunc(("uLUN=%u, fFlags=0x%x\n", uLUN, fFlags));
4024
4025 DEVAC97_LOCK(pThis);
4026
4027 PAC97DRIVER pDrv;
4028 int rc2 = ichac97R3AttachInternal(pThis, uLUN, fFlags, &pDrv);
4029 if (RT_SUCCESS(rc2))
4030 rc2 = ichac97R3MixerAddDrv(pThis, pDrv);
4031
4032 if (RT_FAILURE(rc2))
4033 LogFunc(("Failed with %Rrc\n", rc2));
4034
4035 DEVAC97_UNLOCK(pThis);
4036
4037 return VINF_SUCCESS;
4038}
4039
4040/**
4041 * @interface_method_impl{PDMDEVREG,pfnDetach}
4042 */
4043static DECLCALLBACK(void) ichac97R3Detach(PPDMDEVINS pDevIns, unsigned uLUN, uint32_t fFlags)
4044{
4045 PAC97STATE pThis = PDMINS_2_DATA(pDevIns, PAC97STATE);
4046
4047 LogFunc(("uLUN=%u, fFlags=0x%x\n", uLUN, fFlags));
4048
4049 DEVAC97_LOCK(pThis);
4050
4051 PAC97DRIVER pDrv, pDrvNext;
4052 RTListForEachSafe(&pThis->lstDrv, pDrv, pDrvNext, AC97DRIVER, Node)
4053 {
4054 if (pDrv->uLUN == uLUN)
4055 {
4056 int rc2 = ichac97R3DetachInternal(pThis, pDrv, fFlags);
4057 if (RT_SUCCESS(rc2))
4058 {
4059 RTMemFree(pDrv);
4060 pDrv = NULL;
4061 }
4062
4063 break;
4064 }
4065 }
4066
4067 DEVAC97_UNLOCK(pThis);
4068}
4069
4070/**
4071 * Re-attaches (replaces) a driver with a new driver.
4072 *
4073 * @returns VBox status code.
4074 * @param pThis Device instance.
4075 * @param pDrv Driver instance used for attaching to.
4076 * If NULL is specified, a new driver will be created and appended
4077 * to the driver list.
4078 * @param uLUN The logical unit which is being re-detached.
4079 * @param pszDriver New driver name to attach.
4080 */
4081static int ichac97R3ReattachInternal(PAC97STATE pThis, PAC97DRIVER pDrv, uint8_t uLUN, const char *pszDriver)
4082{
4083 AssertPtrReturn(pThis, VERR_INVALID_POINTER);
4084 AssertPtrReturn(pszDriver, VERR_INVALID_POINTER);
4085
4086 int rc;
4087
4088 if (pDrv)
4089 {
4090 rc = ichac97R3DetachInternal(pThis, pDrv, 0 /* fFlags */);
4091 if (RT_SUCCESS(rc))
4092 rc = PDMDevHlpDriverDetach(pThis->pDevInsR3, PDMIBASE_2_PDMDRV(pDrv->pDrvBase), 0 /* fFlags */);
4093
4094 if (RT_FAILURE(rc))
4095 return rc;
4096
4097 pDrv = NULL;
4098 }
4099
4100 PVM pVM = PDMDevHlpGetVM(pThis->pDevInsR3);
4101 PCFGMNODE pRoot = CFGMR3GetRoot(pVM);
4102 PCFGMNODE pDev0 = CFGMR3GetChild(pRoot, "Devices/ichac97/0/");
4103
4104 /* Remove LUN branch. */
4105 CFGMR3RemoveNode(CFGMR3GetChildF(pDev0, "LUN#%u/", uLUN));
4106
4107# define RC_CHECK() if (RT_FAILURE(rc)) { AssertReleaseRC(rc); break; }
4108
4109 do
4110 {
4111 PCFGMNODE pLunL0;
4112 rc = CFGMR3InsertNodeF(pDev0, &pLunL0, "LUN#%u/", uLUN); RC_CHECK();
4113 rc = CFGMR3InsertString(pLunL0, "Driver", "AUDIO"); RC_CHECK();
4114 rc = CFGMR3InsertNode(pLunL0, "Config/", NULL); RC_CHECK();
4115
4116 PCFGMNODE pLunL1, pLunL2;
4117 rc = CFGMR3InsertNode (pLunL0, "AttachedDriver/", &pLunL1); RC_CHECK();
4118 rc = CFGMR3InsertNode (pLunL1, "Config/", &pLunL2); RC_CHECK();
4119 rc = CFGMR3InsertString(pLunL1, "Driver", pszDriver); RC_CHECK();
4120
4121 rc = CFGMR3InsertString(pLunL2, "AudioDriver", pszDriver); RC_CHECK();
4122
4123 } while (0);
4124
4125 if (RT_SUCCESS(rc))
4126 rc = ichac97R3AttachInternal(pThis, uLUN, 0 /* fFlags */, NULL /* ppDrv */);
4127
4128 LogFunc(("pThis=%p, uLUN=%u, pszDriver=%s, rc=%Rrc\n", pThis, uLUN, pszDriver, rc));
4129
4130# undef RC_CHECK
4131
4132 return rc;
4133}
4134
4135/**
4136 * @interface_method_impl{PDMDEVREG,pfnRelocate}
4137 */
4138static DECLCALLBACK(void) ichac97R3Relocate(PPDMDEVINS pDevIns, RTGCINTPTR offDelta)
4139{
4140 NOREF(offDelta);
4141 PAC97STATE pThis = PDMINS_2_DATA(pDevIns, PAC97STATE);
4142 pThis->pDevInsRC = PDMDEVINS_2_RCPTR(pDevIns);
4143
4144 for (unsigned i = 0; i < AC97_MAX_STREAMS; i++)
4145 pThis->pTimerRC[i] = TMTimerRCPtr(pThis->pTimerR3[i]);
4146}
4147
4148/**
4149 * @interface_method_impl{PDMDEVREG,pfnDestruct}
4150 */
4151static DECLCALLBACK(int) ichac97R3Destruct(PPDMDEVINS pDevIns)
4152{
4153 PDMDEV_CHECK_VERSIONS_RETURN_QUIET(pDevIns); /* this shall come first */
4154 PAC97STATE pThis = PDMINS_2_DATA(pDevIns, PAC97STATE);
4155
4156 LogFlowFuncEnter();
4157
4158 PAC97DRIVER pDrv, pDrvNext;
4159 RTListForEachSafe(&pThis->lstDrv, pDrv, pDrvNext, AC97DRIVER, Node)
4160 {
4161 RTListNodeRemove(&pDrv->Node);
4162 RTMemFree(pDrv);
4163 }
4164
4165 /* Sanity. */
4166 Assert(RTListIsEmpty(&pThis->lstDrv));
4167
4168 return VINF_SUCCESS;
4169}
4170
4171/**
4172 * @interface_method_impl{PDMDEVREG,pfnConstruct}
4173 */
4174static DECLCALLBACK(int) ichac97R3Construct(PPDMDEVINS pDevIns, int iInstance, PCFGMNODE pCfg)
4175{
4176 PDMDEV_CHECK_VERSIONS_RETURN(pDevIns); /* this shall come first */
4177 PAC97STATE pThis = PDMINS_2_DATA(pDevIns, PAC97STATE);
4178 Assert(iInstance == 0); RT_NOREF(iInstance);
4179
4180 /*
4181 * Initialize data so we can run the destructor without scewing up.
4182 */
4183 pThis->pDevInsR3 = pDevIns;
4184 pThis->pDevInsR0 = PDMDEVINS_2_R0PTR(pDevIns);
4185 pThis->pDevInsRC = PDMDEVINS_2_RCPTR(pDevIns);
4186 pThis->IBase.pfnQueryInterface = ichac97R3QueryInterface;
4187 RTListInit(&pThis->lstDrv);
4188
4189 /*
4190 * Validations.
4191 */
4192 if (!CFGMR3AreValuesValid(pCfg, "RZEnabled\0"
4193 "Codec\0"
4194 "TimerHz\0"
4195 "DebugEnabled\0"
4196 "DebugPathOut\0"))
4197 return PDMDEV_SET_ERROR(pDevIns, VERR_PDM_DEVINS_UNKNOWN_CFG_VALUES,
4198 N_("Invalid configuration for the AC'97 device"));
4199
4200 /*
4201 * Read config data.
4202 */
4203 int rc = CFGMR3QueryBoolDef(pCfg, "RZEnabled", &pThis->fRZEnabled, true);
4204 if (RT_FAILURE(rc))
4205 return PDMDEV_SET_ERROR(pDevIns, rc,
4206 N_("AC'97 configuration error: failed to read RCEnabled as boolean"));
4207
4208 char szCodec[20];
4209 rc = CFGMR3QueryStringDef(pCfg, "Codec", &szCodec[0], sizeof(szCodec), "STAC9700");
4210 if (RT_FAILURE(rc))
4211 return PDMDEV_SET_ERROR(pDevIns, VERR_PDM_DEVINS_UNKNOWN_CFG_VALUES,
4212 N_("AC'97 configuration error: Querying \"Codec\" as string failed"));
4213
4214 rc = CFGMR3QueryU16Def(pCfg, "TimerHz", &pThis->uTimerHz, AC97_TIMER_HZ_DEFAULT /* Default value, if not set. */);
4215 if (RT_FAILURE(rc))
4216 return PDMDEV_SET_ERROR(pDevIns, rc,
4217 N_("AC'97 configuration error: failed to read Hertz (Hz) rate as unsigned integer"));
4218
4219 if (pThis->uTimerHz != AC97_TIMER_HZ_DEFAULT)
4220 LogRel(("AC97: Using custom device timer rate (%RU16Hz)\n", pThis->uTimerHz));
4221
4222 rc = CFGMR3QueryBoolDef(pCfg, "DebugEnabled", &pThis->Dbg.fEnabled, false);
4223 if (RT_FAILURE(rc))
4224 return PDMDEV_SET_ERROR(pDevIns, rc,
4225 N_("AC97 configuration error: failed to read debugging enabled flag as boolean"));
4226
4227 rc = CFGMR3QueryStringDef(pCfg, "DebugPathOut", pThis->Dbg.szOutPath, sizeof(pThis->Dbg.szOutPath),
4228 VBOX_AUDIO_DEBUG_DUMP_PCM_DATA_PATH);
4229 if (RT_FAILURE(rc))
4230 return PDMDEV_SET_ERROR(pDevIns, rc,
4231 N_("AC97 configuration error: failed to read debugging output path flag as string"));
4232
4233 if (!strlen(pThis->Dbg.szOutPath))
4234 RTStrPrintf(pThis->Dbg.szOutPath, sizeof(pThis->Dbg.szOutPath), VBOX_AUDIO_DEBUG_DUMP_PCM_DATA_PATH);
4235
4236 if (pThis->Dbg.fEnabled)
4237 LogRel2(("AC97: Debug output will be saved to '%s'\n", pThis->Dbg.szOutPath));
4238
4239 /*
4240 * The AD1980 codec (with corresponding PCI subsystem vendor ID) is whitelisted
4241 * in the Linux kernel; Linux makes no attempt to measure the data rate and assumes
4242 * 48 kHz rate, which is exactly what we need. Same goes for AD1981B.
4243 */
4244 if (!strcmp(szCodec, "STAC9700"))
4245 pThis->uCodecModel = AC97_CODEC_STAC9700;
4246 else if (!strcmp(szCodec, "AD1980"))
4247 pThis->uCodecModel = AC97_CODEC_AD1980;
4248 else if (!strcmp(szCodec, "AD1981B"))
4249 pThis->uCodecModel = AC97_CODEC_AD1981B;
4250 else
4251 return PDMDevHlpVMSetError(pDevIns, VERR_PDM_DEVINS_UNKNOWN_CFG_VALUES, RT_SRC_POS,
4252 N_("AC'97 configuration error: The \"Codec\" value \"%s\" is unsupported"), szCodec);
4253
4254 LogRel(("AC97: Using codec '%s'\n", szCodec));
4255
4256 /*
4257 * Use an own critical section for the device instead of the default
4258 * one provided by PDM. This allows fine-grained locking in combination
4259 * with TM when timer-specific stuff is being called in e.g. the MMIO handlers.
4260 */
4261 rc = PDMDevHlpCritSectInit(pDevIns, &pThis->CritSect, RT_SRC_POS, "AC'97");
4262 AssertRCReturn(rc, rc);
4263
4264 rc = PDMDevHlpSetDeviceCritSect(pDevIns, PDMDevHlpCritSectGetNop(pDevIns));
4265 AssertRCReturn(rc, rc);
4266
4267 /*
4268 * Initialize data (most of it anyway).
4269 */
4270 /* PCI Device */
4271 PCIDevSetVendorId (&pThis->PciDev, 0x8086); /* 00 ro - intel. */ Assert(pThis->PciDev.abConfig[0x00] == 0x86); Assert(pThis->PciDev.abConfig[0x01] == 0x80);
4272 PCIDevSetDeviceId (&pThis->PciDev, 0x2415); /* 02 ro - 82801 / 82801aa(?). */ Assert(pThis->PciDev.abConfig[0x02] == 0x15); Assert(pThis->PciDev.abConfig[0x03] == 0x24);
4273 PCIDevSetCommand (&pThis->PciDev, 0x0000); /* 04 rw,ro - pcicmd. */ Assert(pThis->PciDev.abConfig[0x04] == 0x00); Assert(pThis->PciDev.abConfig[0x05] == 0x00);
4274 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);
4275 PCIDevSetRevisionId (&pThis->PciDev, 0x01); /* 08 ro - rid. */ Assert(pThis->PciDev.abConfig[0x08] == 0x01);
4276 PCIDevSetClassProg (&pThis->PciDev, 0x00); /* 09 ro - pi. */ Assert(pThis->PciDev.abConfig[0x09] == 0x00);
4277 PCIDevSetClassSub (&pThis->PciDev, 0x01); /* 0a ro - scc; 01 == Audio. */ Assert(pThis->PciDev.abConfig[0x0a] == 0x01);
4278 PCIDevSetClassBase (&pThis->PciDev, 0x04); /* 0b ro - bcc; 04 == multimedia.*/Assert(pThis->PciDev.abConfig[0x0b] == 0x04);
4279 PCIDevSetHeaderType (&pThis->PciDev, 0x00); /* 0e ro - headtyp. */ Assert(pThis->PciDev.abConfig[0x0e] == 0x00);
4280 PCIDevSetBaseAddress (&pThis->PciDev, 0, /* 10 rw - nambar - native audio mixer base. */
4281 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);
4282 PCIDevSetBaseAddress (&pThis->PciDev, 1, /* 14 rw - nabmbar - native audio bus mastering. */
4283 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);
4284 PCIDevSetInterruptLine(&pThis->PciDev, 0x00); /* 3c rw. */ Assert(pThis->PciDev.abConfig[0x3c] == 0x00);
4285 PCIDevSetInterruptPin (&pThis->PciDev, 0x01); /* 3d ro - INTA#. */ Assert(pThis->PciDev.abConfig[0x3d] == 0x01);
4286
4287 if (pThis->uCodecModel == AC97_CODEC_AD1980)
4288 {
4289 PCIDevSetSubSystemVendorId(&pThis->PciDev, 0x1028); /* 2c ro - Dell.) */
4290 PCIDevSetSubSystemId (&pThis->PciDev, 0x0177); /* 2e ro. */
4291 }
4292 else if (pThis->uCodecModel == AC97_CODEC_AD1981B)
4293 {
4294 PCIDevSetSubSystemVendorId(&pThis->PciDev, 0x1028); /* 2c ro - Dell.) */
4295 PCIDevSetSubSystemId (&pThis->PciDev, 0x01ad); /* 2e ro. */
4296 }
4297 else
4298 {
4299 PCIDevSetSubSystemVendorId(&pThis->PciDev, 0x8086); /* 2c ro - Intel.) */
4300 PCIDevSetSubSystemId (&pThis->PciDev, 0x0000); /* 2e ro. */
4301 }
4302
4303 /*
4304 * Register the PCI device, it's I/O regions, the timer and the
4305 * saved state item.
4306 */
4307 rc = PDMDevHlpPCIRegister(pDevIns, &pThis->PciDev);
4308 if (RT_FAILURE(rc))
4309 return rc;
4310
4311 rc = PDMDevHlpPCIIORegionRegister(pDevIns, 0, 256, PCI_ADDRESS_SPACE_IO, ichac97R3IOPortMap);
4312 if (RT_FAILURE(rc))
4313 return rc;
4314
4315 rc = PDMDevHlpPCIIORegionRegister(pDevIns, 1, 64, PCI_ADDRESS_SPACE_IO, ichac97R3IOPortMap);
4316 if (RT_FAILURE(rc))
4317 return rc;
4318
4319 rc = PDMDevHlpSSMRegister(pDevIns, AC97_SSM_VERSION, sizeof(*pThis), ichac97R3SaveExec, ichac97R3LoadExec);
4320 if (RT_FAILURE(rc))
4321 return rc;
4322
4323# ifdef VBOX_WITH_AUDIO_AC97_ASYNC_IO
4324 LogRel(("AC97: Asynchronous I/O enabled\n"));
4325# endif
4326
4327 /*
4328 * Attach driver.
4329 */
4330 uint8_t uLUN;
4331 for (uLUN = 0; uLUN < UINT8_MAX; ++uLUN)
4332 {
4333 LogFunc(("Trying to attach driver for LUN #%RU8 ...\n", uLUN));
4334 rc = ichac97R3AttachInternal(pThis, uLUN, 0 /* fFlags */, NULL /* ppDrv */);
4335 if (RT_FAILURE(rc))
4336 {
4337 if (rc == VERR_PDM_NO_ATTACHED_DRIVER)
4338 rc = VINF_SUCCESS;
4339 else if (rc == VERR_AUDIO_BACKEND_INIT_FAILED)
4340 {
4341 ichac97R3ReattachInternal(pThis, NULL /* pDrv */, uLUN, "NullAudio");
4342 PDMDevHlpVMSetRuntimeError(pDevIns, 0 /*fFlags*/, "HostAudioNotResponding",
4343 N_("Host audio backend initialization has failed. Selecting the NULL audio backend "
4344 "with the consequence that no sound is audible"));
4345 /* Attaching to the NULL audio backend will never fail. */
4346 rc = VINF_SUCCESS;
4347 }
4348 break;
4349 }
4350 }
4351
4352 LogFunc(("cLUNs=%RU8, rc=%Rrc\n", uLUN, rc));
4353
4354 if (RT_SUCCESS(rc))
4355 {
4356 rc = AudioMixerCreate("AC'97 Mixer", 0 /* uFlags */, &pThis->pMixer);
4357 if (RT_SUCCESS(rc))
4358 {
4359 rc = AudioMixerCreateSink(pThis->pMixer, "[Recording] Line In", AUDMIXSINKDIR_INPUT, &pThis->pSinkLineIn);
4360 AssertRC(rc);
4361 rc = AudioMixerCreateSink(pThis->pMixer, "[Recording] Microphone In", AUDMIXSINKDIR_INPUT, &pThis->pSinkMicIn);
4362 AssertRC(rc);
4363 rc = AudioMixerCreateSink(pThis->pMixer, "[Playback] PCM Output", AUDMIXSINKDIR_OUTPUT, &pThis->pSinkOut);
4364 AssertRC(rc);
4365 }
4366 }
4367
4368 if (RT_SUCCESS(rc))
4369 {
4370 /*
4371 * Create all hardware streams.
4372 */
4373 for (unsigned i = 0; i < AC97_MAX_STREAMS; i++)
4374 {
4375 int rc2 = ichac97R3StreamCreate(pThis, &pThis->aStreams[i], i /* SD# */);
4376 AssertRC(rc2);
4377 if (RT_SUCCESS(rc))
4378 rc = rc2;
4379 }
4380
4381# ifdef VBOX_WITH_AUDIO_AC97_ONETIME_INIT
4382 PAC97DRIVER pDrv;
4383 RTListForEach(&pThis->lstDrv, pDrv, AC97DRIVER, Node)
4384 {
4385 /*
4386 * Only primary drivers are critical for the VM to run. Everything else
4387 * might not worth showing an own error message box in the GUI.
4388 */
4389 if (!(pDrv->fFlags & PDMAUDIODRVFLAGS_PRIMARY))
4390 continue;
4391
4392 PPDMIAUDIOCONNECTOR pCon = pDrv->pConnector;
4393 AssertPtr(pCon);
4394
4395 bool fValidLineIn = AudioMixerStreamIsValid(pDrv->LineIn.pMixStrm);
4396 bool fValidMicIn = AudioMixerStreamIsValid(pDrv->MicIn.pMixStrm);
4397 bool fValidOut = AudioMixerStreamIsValid(pDrv->Out.pMixStrm);
4398
4399 if ( !fValidLineIn
4400 && !fValidMicIn
4401 && !fValidOut)
4402 {
4403 LogRel(("AC97: Falling back to NULL backend (no sound audible)\n"));
4404
4405 ichac97R3Reset(pDevIns);
4406 ichac97R3ReattachInternal(pThis, pDrv, pDrv->uLUN, "NullAudio");
4407
4408 PDMDevHlpVMSetRuntimeError(pDevIns, 0 /*fFlags*/, "HostAudioNotResponding",
4409 N_("No audio devices could be opened. Selecting the NULL audio backend "
4410 "with the consequence that no sound is audible"));
4411 }
4412 else
4413 {
4414 bool fWarn = false;
4415
4416 PDMAUDIOBACKENDCFG backendCfg;
4417 int rc2 = pCon->pfnGetConfig(pCon, &backendCfg);
4418 if (RT_SUCCESS(rc2))
4419 {
4420 if (backendCfg.cMaxStreamsIn)
4421 {
4422 /* If the audio backend supports two or more input streams at once,
4423 * warn if one of our two inputs (microphone-in and line-in) failed to initialize. */
4424 if (backendCfg.cMaxStreamsIn >= 2)
4425 fWarn = !fValidLineIn || !fValidMicIn;
4426 /* If the audio backend only supports one input stream at once (e.g. pure ALSA, and
4427 * *not* ALSA via PulseAudio plugin!), only warn if both of our inputs failed to initialize.
4428 * One of the two simply is not in use then. */
4429 else if (backendCfg.cMaxStreamsIn == 1)
4430 fWarn = !fValidLineIn && !fValidMicIn;
4431 /* Don't warn if our backend is not able of supporting any input streams at all. */
4432 }
4433
4434 if ( !fWarn
4435 && backendCfg.cMaxStreamsOut)
4436 {
4437 fWarn = !fValidOut;
4438 }
4439 }
4440 else
4441 {
4442 LogRel(("AC97: Unable to retrieve audio backend configuration for LUN #%RU8, rc=%Rrc\n", pDrv->uLUN, rc2));
4443 fWarn = true;
4444 }
4445
4446 if (fWarn)
4447 {
4448 char szMissingStreams[255] = "";
4449 size_t len = 0;
4450 if (!fValidLineIn)
4451 {
4452 LogRel(("AC97: WARNING: Unable to open PCM line input for LUN #%RU8!\n", pDrv->uLUN));
4453 len = RTStrPrintf(szMissingStreams, sizeof(szMissingStreams), "PCM Input");
4454 }
4455 if (!fValidMicIn)
4456 {
4457 LogRel(("AC97: WARNING: Unable to open PCM microphone input for LUN #%RU8!\n", pDrv->uLUN));
4458 len += RTStrPrintf(szMissingStreams + len,
4459 sizeof(szMissingStreams) - len, len ? ", PCM Microphone" : "PCM Microphone");
4460 }
4461 if (!fValidOut)
4462 {
4463 LogRel(("AC97: WARNING: Unable to open PCM output for LUN #%RU8!\n", pDrv->uLUN));
4464 len += RTStrPrintf(szMissingStreams + len,
4465 sizeof(szMissingStreams) - len, len ? ", PCM Output" : "PCM Output");
4466 }
4467
4468 PDMDevHlpVMSetRuntimeError(pDevIns, 0 /*fFlags*/, "HostAudioNotResponding",
4469 N_("Some AC'97 audio streams (%s) could not be opened. Guest applications generating audio "
4470 "output or depending on audio input may hang. Make sure your host audio device "
4471 "is working properly. Check the logfile for error messages of the audio "
4472 "subsystem"), szMissingStreams);
4473 }
4474 }
4475 }
4476# endif /* VBOX_WITH_AUDIO_AC97_ONETIME_INIT */
4477 }
4478
4479 if (RT_SUCCESS(rc))
4480 ichac97R3Reset(pDevIns);
4481
4482 if (RT_SUCCESS(rc))
4483 {
4484 for (unsigned i = 0; i < AC97_MAX_STREAMS; i++)
4485 {
4486 /* Create the emulation timer (per stream).
4487 *
4488 * Note: Use TMCLOCK_VIRTUAL_SYNC here, as the guest's AC'97 driver
4489 * relies on exact (virtual) DMA timing and uses DMA Position Buffers
4490 * instead of the LPIB registers.
4491 */
4492 char szTimer[16];
4493 RTStrPrintf2(szTimer, sizeof(szTimer), "AC97SD%i", i);
4494
4495 rc = PDMDevHlpTMTimerCreate(pDevIns, TMCLOCK_VIRTUAL_SYNC, ichac97R3Timer, &pThis->aStreams[i],
4496 TMTIMER_FLAGS_NO_CRIT_SECT, szTimer, &pThis->pTimerR3[i]);
4497 AssertRCReturn(rc, rc);
4498 pThis->pTimerR0[i] = TMTimerR0Ptr(pThis->pTimerR3[i]);
4499 pThis->pTimerRC[i] = TMTimerRCPtr(pThis->pTimerR3[i]);
4500
4501 /* Use our own critcal section for the device timer.
4502 * That way we can control more fine-grained when to lock what. */
4503 rc = TMR3TimerSetCritSect(pThis->pTimerR3[i], &pThis->CritSect);
4504 AssertRCReturn(rc, rc);
4505 }
4506 }
4507
4508# ifdef VBOX_WITH_STATISTICS
4509 if (RT_SUCCESS(rc))
4510 {
4511 /*
4512 * Register statistics.
4513 */
4514 PDMDevHlpSTAMRegister(pDevIns, &pThis->StatTimer, STAMTYPE_PROFILE, "/Devices/AC97/Timer", STAMUNIT_TICKS_PER_CALL, "Profiling ichac97Timer.");
4515 PDMDevHlpSTAMRegister(pDevIns, &pThis->StatIn, STAMTYPE_PROFILE, "/Devices/AC97/Input", STAMUNIT_TICKS_PER_CALL, "Profiling input.");
4516 PDMDevHlpSTAMRegister(pDevIns, &pThis->StatOut, STAMTYPE_PROFILE, "/Devices/AC97/Output", STAMUNIT_TICKS_PER_CALL, "Profiling output.");
4517 PDMDevHlpSTAMRegister(pDevIns, &pThis->StatBytesRead, STAMTYPE_COUNTER, "/Devices/AC97/BytesRead" , STAMUNIT_BYTES, "Bytes read from AC97 emulation.");
4518 PDMDevHlpSTAMRegister(pDevIns, &pThis->StatBytesWritten, STAMTYPE_COUNTER, "/Devices/AC97/BytesWritten", STAMUNIT_BYTES, "Bytes written to AC97 emulation.");
4519 }
4520# endif
4521
4522 LogFlowFuncLeaveRC(rc);
4523 return rc;
4524}
4525
4526/**
4527 * The device registration structure.
4528 */
4529const PDMDEVREG g_DeviceICHAC97 =
4530{
4531 /* u32Version */
4532 PDM_DEVREG_VERSION,
4533 /* szName */
4534 "ichac97",
4535 /* szRCMod */
4536 "VBoxDDRC.rc",
4537 /* szR0Mod */
4538 "VBoxDDR0.r0",
4539 /* pszDescription */
4540 "ICH AC'97 Audio Controller",
4541 /* fFlags */
4542 PDM_DEVREG_FLAGS_DEFAULT_BITS | PDM_DEVREG_FLAGS_RC | PDM_DEVREG_FLAGS_R0,
4543 /* fClass */
4544 PDM_DEVREG_CLASS_AUDIO,
4545 /* cMaxInstances */
4546 1,
4547 /* cbInstance */
4548 sizeof(AC97STATE),
4549 /* pfnConstruct */
4550 ichac97R3Construct,
4551 /* pfnDestruct */
4552 ichac97R3Destruct,
4553 /* pfnRelocate */
4554 ichac97R3Relocate,
4555 /* pfnMemSetup */
4556 NULL,
4557 /* pfnPowerOn */
4558 NULL,
4559 /* pfnReset */
4560 ichac97R3Reset,
4561 /* pfnSuspend */
4562 NULL,
4563 /* pfnResume */
4564 NULL,
4565 /* pfnAttach */
4566 ichac97R3Attach,
4567 /* pfnDetach */
4568 ichac97R3Detach,
4569 /* pfnQueryInterface. */
4570 NULL,
4571 /* pfnInitComplete */
4572 NULL,
4573 /* pfnPowerOff */
4574 ichac97R3PowerOff,
4575 /* pfnSoftReset */
4576 NULL,
4577 /* u32VersionEnd */
4578 PDM_DEVREG_VERSION
4579};
4580
4581#endif /* !IN_RING3 */
4582#endif /* !VBOX_DEVICE_STRUCT_TESTCASE */
4583
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