VirtualBox

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

Last change on this file since 80596 was 80531, checked in by vboxsync, 5 years ago

VMM,Devices: Some PDM device model refactoring. bugref:9218

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