VirtualBox

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

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

Audio/AC97: Saved state fix (also re-arm the per-stream timer when loading from a saved state).

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

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