VirtualBox

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

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

PDM,DevACPI,DevHPET,DevPit-i8254,DevRTC,APIC: Added device helpers for locking and unlocking both the virtual-sync clock and entering a user specified critical section. bugref:9218

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

© 2025 Oracle Support Privacy / Do Not Sell My Info Terms of Use Trademark Policy Automated Access Etiquette