VirtualBox

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

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

Audio/AC97: Build fix.

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