VirtualBox

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

Last change on this file since 82303 was 82295, checked in by vboxsync, 5 years ago

DevIchAc97: Converted I/O ports, forgot ring-0 bits. [grr] bugref:9218

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