VirtualBox

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

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

Audio/AC97: Build fix.

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