VirtualBox

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

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

Audio/AC97: Condensed NABMBAR status register writes.

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