VirtualBox

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

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

Audio/AC97: Logging nit.

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