VirtualBox

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

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

Audio/AC97: Moved setting the Hz rate / scheduling hint a bit more to the top so that it actually gets set when creating a stream.

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 159.8 KB
Line 
1/* $Id: DevIchAc97.cpp 76701 2019-01-08 11:07:10Z vboxsync $ */
2/** @file
3 * DevIchAc97 - VBox ICH AC97 Audio Controller.
4 */
5
6/*
7 * Copyright (C) 2006-2019 Oracle Corporation
8 *
9 * This file is part of VirtualBox Open Source Edition (OSE), as
10 * available from http://www.virtualbox.org. This file is free software;
11 * you can redistribute it and/or modify it under the terms of the GNU
12 * General Public License (GPL) as published by the Free Software
13 * Foundation, in version 2 as it comes in the "COPYING" file of the
14 * VirtualBox OSE distribution. VirtualBox OSE is distributed in the
15 * hope that it will be useful, but WITHOUT ANY WARRANTY of any kind.
16 */
17
18
19/*********************************************************************************************************************************
20* Header Files *
21*********************************************************************************************************************************/
22#define LOG_GROUP LOG_GROUP_DEV_AC97
23#include <VBox/log.h>
24#include <VBox/vmm/pdmdev.h>
25#include <VBox/vmm/pdmaudioifs.h>
26
27#include <iprt/assert.h>
28#ifdef IN_RING3
29# ifdef DEBUG
30# include <iprt/file.h>
31# endif
32# include <iprt/mem.h>
33# include <iprt/semaphore.h>
34# include <iprt/string.h>
35# include <iprt/uuid.h>
36#endif
37
38#include "VBoxDD.h"
39
40#include "AudioMixBuffer.h"
41#include "AudioMixer.h"
42#include "DrvAudio.h"
43
44
45/*********************************************************************************************************************************
46* Defined Constants And Macros *
47*********************************************************************************************************************************/
48
49/** Current saved state version. */
50#define AC97_SSM_VERSION 1
51
52/** Default timer frequency (in Hz). */
53#define AC97_TIMER_HZ_DEFAULT 100
54
55/** Maximum number of streams we support. */
56#define AC97_MAX_STREAMS 3
57
58/** Maximum FIFO size (in bytes). */
59#define AC97_FIFO_MAX 256
60
61#define AC97_SR_FIFOE RT_BIT(4) /**< rwc, FIFO error. */
62#define AC97_SR_BCIS RT_BIT(3) /**< rwc, Buffer completion interrupt status. */
63#define AC97_SR_LVBCI RT_BIT(2) /**< rwc, Last valid buffer completion interrupt. */
64#define AC97_SR_CELV RT_BIT(1) /**< ro, Current equals last valid. */
65#define AC97_SR_DCH RT_BIT(0) /**< ro, Controller halted. */
66#define AC97_SR_VALID_MASK (RT_BIT(5) - 1)
67#define AC97_SR_WCLEAR_MASK (AC97_SR_FIFOE | AC97_SR_BCIS | AC97_SR_LVBCI)
68#define AC97_SR_RO_MASK (AC97_SR_DCH | AC97_SR_CELV)
69#define AC97_SR_INT_MASK (AC97_SR_FIFOE | AC97_SR_BCIS | AC97_SR_LVBCI)
70
71#define AC97_CR_IOCE RT_BIT(4) /**< rw, Interrupt On Completion Enable. */
72#define AC97_CR_FEIE RT_BIT(3) /**< rw FIFO Error Interrupt Enable. */
73#define AC97_CR_LVBIE RT_BIT(2) /**< rw Last Valid Buffer Interrupt Enable. */
74#define AC97_CR_RR RT_BIT(1) /**< rw Reset Registers. */
75#define AC97_CR_RPBM RT_BIT(0) /**< rw Run/Pause Bus Master. */
76#define AC97_CR_VALID_MASK (RT_BIT(5) - 1)
77#define AC97_CR_DONT_CLEAR_MASK (AC97_CR_IOCE | AC97_CR_FEIE | AC97_CR_LVBIE)
78
79#define AC97_GC_WR 4 /**< rw Warm reset. */
80#define AC97_GC_CR 2 /**< rw Cold reset. */
81#define AC97_GC_VALID_MASK (RT_BIT(6) - 1)
82
83#define AC97_GS_MD3 RT_BIT(17) /**< rw */
84#define AC97_GS_AD3 RT_BIT(16) /**< rw */
85#define AC97_GS_RCS RT_BIT(15) /**< rwc */
86#define AC97_GS_B3S12 RT_BIT(14) /**< ro */
87#define AC97_GS_B2S12 RT_BIT(13) /**< ro */
88#define AC97_GS_B1S12 RT_BIT(12) /**< ro */
89#define AC97_GS_S1R1 RT_BIT(11) /**< rwc */
90#define AC97_GS_S0R1 RT_BIT(10) /**< rwc */
91#define AC97_GS_S1CR RT_BIT(9) /**< ro */
92#define AC97_GS_S0CR RT_BIT(8) /**< ro */
93#define AC97_GS_MINT RT_BIT(7) /**< ro */
94#define AC97_GS_POINT RT_BIT(6) /**< ro */
95#define AC97_GS_PIINT RT_BIT(5) /**< ro */
96#define AC97_GS_RSRVD (RT_BIT(4) | RT_BIT(3))
97#define AC97_GS_MOINT RT_BIT(2) /**< ro */
98#define AC97_GS_MIINT RT_BIT(1) /**< ro */
99#define AC97_GS_GSCI RT_BIT(0) /**< rwc */
100#define AC97_GS_RO_MASK ( AC97_GS_B3S12 \
101 | AC97_GS_B2S12 \
102 | AC97_GS_B1S12 \
103 | AC97_GS_S1CR \
104 | AC97_GS_S0CR \
105 | AC97_GS_MINT \
106 | AC97_GS_POINT \
107 | AC97_GS_PIINT \
108 | AC97_GS_RSRVD \
109 | AC97_GS_MOINT \
110 | AC97_GS_MIINT)
111#define AC97_GS_VALID_MASK (RT_BIT(18) - 1)
112#define AC97_GS_WCLEAR_MASK (AC97_GS_RCS | AC97_GS_S1R1 | AC97_GS_S0R1 | AC97_GS_GSCI)
113
114/** @name Buffer Descriptor (BD).
115 * @{ */
116#define AC97_BD_IOC RT_BIT(31) /**< Interrupt on Completion. */
117#define AC97_BD_BUP RT_BIT(30) /**< Buffer Underrun Policy. */
118
119#define AC97_BD_LEN_MASK 0xFFFF /**< Mask for the BDL buffer length. */
120
121#define AC97_MAX_BDLE 32 /**< Maximum number of BDLEs. */
122/** @} */
123
124/** @name Extended Audio 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 Cfg.Props.cChannels = 2;
1966 Cfg.Props.cBytes = 2 /* 16-bit */;
1967 Cfg.Props.fSigned = true;
1968 Cfg.Props.cShift = PDMAUDIOPCMPROPS_MAKE_SHIFT_PARMS(Cfg.Props.cBytes, Cfg.Props.cChannels);
1969
1970 switch (pStream->u8SD)
1971 {
1972 case AC97SOUNDSOURCE_PI_INDEX:
1973 {
1974 Cfg.Props.uHz = ichac97MixerGet(pThis, AC97_PCM_LR_ADC_Rate);
1975 Cfg.enmDir = PDMAUDIODIR_IN;
1976 Cfg.DestSource.Source = PDMAUDIORECSOURCE_LINE;
1977 Cfg.enmLayout = PDMAUDIOSTREAMLAYOUT_NON_INTERLEAVED;
1978 RTStrCopy(Cfg.szName, sizeof(Cfg.szName), "Line-In");
1979
1980 pMixSink = pThis->pSinkLineIn;
1981 break;
1982 }
1983
1984 case AC97SOUNDSOURCE_MC_INDEX:
1985 {
1986 Cfg.Props.uHz = ichac97MixerGet(pThis, AC97_MIC_ADC_Rate);
1987 Cfg.enmDir = PDMAUDIODIR_IN;
1988 Cfg.DestSource.Source = PDMAUDIORECSOURCE_MIC;
1989 Cfg.enmLayout = PDMAUDIOSTREAMLAYOUT_NON_INTERLEAVED;
1990 RTStrCopy(Cfg.szName, sizeof(Cfg.szName), "Mic-In");
1991
1992 pMixSink = pThis->pSinkMicIn;
1993 break;
1994 }
1995
1996 case AC97SOUNDSOURCE_PO_INDEX:
1997 {
1998 Cfg.Props.uHz = ichac97MixerGet(pThis, AC97_PCM_Front_DAC_Rate);
1999 Cfg.enmDir = PDMAUDIODIR_OUT;
2000 Cfg.DestSource.Dest = PDMAUDIOPLAYBACKDEST_FRONT;
2001 Cfg.enmLayout = PDMAUDIOSTREAMLAYOUT_NON_INTERLEAVED;
2002 RTStrCopy(Cfg.szName, sizeof(Cfg.szName), "Output");
2003
2004 pMixSink = pThis->pSinkOut;
2005 break;
2006 }
2007
2008 default:
2009 rc = VERR_NOT_SUPPORTED;
2010 break;
2011 }
2012
2013 if (RT_SUCCESS(rc))
2014 {
2015 /* Only (re-)create the stream (and driver chain) if we really have to.
2016 * Otherwise avoid this and just reuse it, as this costs performance. */
2017 if (!DrvAudioHlpPCMPropsAreEqual(&Cfg.Props, &pStream->State.Cfg.Props))
2018 {
2019 LogFlowFunc(("[SD%RU8] uHz=%RU32\n", pStream->u8SD, Cfg.Props.uHz));
2020
2021 if (Cfg.Props.uHz)
2022 {
2023 Assert(Cfg.enmDir != PDMAUDIODIR_UNKNOWN);
2024
2025 /*
2026 * Set the stream's timer Hz rate, based on the PCM properties Hz rate.
2027 */
2028 if (pThis->uTimerHz == AC97_TIMER_HZ_DEFAULT) /* Make sure that we don't have any custom Hz rate set we want to enforce */
2029 {
2030 if (Cfg.Props.uHz > 44100) /* E.g. 48000 Hz. */
2031 pStream->State.uTimerHz = 200;
2032 else /* Just take the global Hz rate otherwise. */
2033 pStream->State.uTimerHz = pThis->uTimerHz;
2034 }
2035 else
2036 pStream->State.uTimerHz = pThis->uTimerHz;
2037
2038 /* Set scheduling hint (if available). */
2039 if (pStream->State.uTimerHz)
2040 Cfg.Device.uSchedulingHintMs = 1000 /* ms */ / pStream->State.uTimerHz;
2041
2042 if (pStream->State.pCircBuf)
2043 {
2044 RTCircBufDestroy(pStream->State.pCircBuf);
2045 pStream->State.pCircBuf = NULL;
2046 }
2047
2048 rc = RTCircBufCreate(&pStream->State.pCircBuf, DrvAudioHlpMilliToBytes(100 /* ms */, &Cfg.Props)); /** @todo Make this configurable. */
2049 if (RT_SUCCESS(rc))
2050 {
2051 ichac97R3MixerRemoveDrvStreams(pThis, pMixSink, Cfg.enmDir, Cfg.DestSource);
2052
2053 rc = ichac97R3MixerAddDrvStreams(pThis, pMixSink, &Cfg);
2054 if (RT_SUCCESS(rc))
2055 rc = DrvAudioHlpStreamCfgCopy(&pStream->State.Cfg, &Cfg);
2056 }
2057
2058 /*
2059 * Set up data transfer stuff.
2060 */
2061#ifdef LOG_ENABLED
2062 ichac97R3BDLEDumpAll(pThis, pStream->Regs.bdbar, pStream->Regs.lvi + 1);
2063#endif
2064 const uint32_t cbFrame = DrvAudioHlpPCMPropsBytesPerFrame(&Cfg.Props);
2065
2066 /* Calculate the fragment size the guest OS expects interrupt delivery at. */
2067 pStream->State.cbTransferSize = 441 * 4;//pStream->u32CBL / cFragments;
2068 Assert(pStream->State.cbTransferSize);
2069 Assert(pStream->State.cbTransferSize % cbFrame == 0);
2070
2071 /* Calculate the bytes we need to transfer to / from the stream's DMA per iteration.
2072 * This is bound to the device's Hz rate and thus to the (virtual) timing the device expects. */
2073 pStream->State.cbTransferChunk = (pStream->State.Cfg.Props.uHz / pStream->State.uTimerHz) * cbFrame;
2074 Assert(pStream->State.cbTransferChunk);
2075 Assert(pStream->State.cbTransferChunk % cbFrame== 0);
2076
2077 /* Make sure that the transfer chunk does not exceed the overall transfer size. */
2078 if (pStream->State.cbTransferChunk > pStream->State.cbTransferSize)
2079 pStream->State.cbTransferChunk = pStream->State.cbTransferSize;
2080
2081 const uint64_t cTicksPerHz = TMTimerGetFreq((pThis)->DEVAC97_CTX_SUFF_SD(pTimer, pStream->u8SD))/ pStream->State.uTimerHz;
2082
2083 /* Calculate the timer ticks per byte for this stream. */
2084 pStream->State.cTicksPerByte = cTicksPerHz / pStream->State.cbTransferChunk;
2085 Assert(pStream->State.cTicksPerByte);
2086
2087 /* Calculate timer ticks per transfer. */
2088 pStream->State.cTransferTicks = pStream->State.cbTransferChunk * pStream->State.cTicksPerByte;
2089 Assert(pStream->State.cTransferTicks);
2090
2091 LogFunc(("[SD%RU8] Timer %uHz (%RU64 ticks per Hz), cTicksPerByte=%RU64, cbTransferChunk=%RU32, cTransferTicks=%RU64, " \
2092 "cbTransferSize=%RU32\n",
2093 pStream->u8SD, pStream->State.uTimerHz, cTicksPerHz, pStream->State.cTicksPerByte,
2094 pStream->State.cbTransferChunk, pStream->State.cTransferTicks, pStream->State.cbTransferSize));
2095
2096 }
2097 }
2098 else
2099 LogFlowFunc(("[SD%RU8] Skipping (re-)creation\n", pStream->u8SD));
2100 }
2101
2102 LogFlowFunc(("[SD%RU8] rc=%Rrc\n", pStream->u8SD, rc));
2103 return rc;
2104}
2105
2106/**
2107 * Closes an AC'97 stream.
2108 *
2109 * @returns IPRT status code.
2110 * @param pThis AC'97 state.
2111 * @param pStream AC'97 stream to close.
2112 */
2113static int ichac97R3StreamClose(PAC97STATE pThis, PAC97STREAM pStream)
2114{
2115 RT_NOREF(pThis, pStream);
2116
2117 LogFlowFunc(("[SD%RU8]\n", pStream->u8SD));
2118
2119 return VINF_SUCCESS;
2120}
2121
2122/**
2123 * Re-opens (that is, closes and opens again) an AC'97 stream on the backend
2124 * side with the current AC'97 mixer settings for this stream.
2125 *
2126 * @returns IPRT status code.
2127 * @param pThis AC'97 device state.
2128 * @param pStream AC'97 stream to re-open.
2129 */
2130static int ichac97R3StreamReOpen(PAC97STATE pThis, PAC97STREAM pStream)
2131{
2132 LogFlowFunc(("[SD%RU8]\n", pStream->u8SD));
2133
2134 int rc = ichac97R3StreamClose(pThis, pStream);
2135 if (RT_SUCCESS(rc))
2136 rc = ichac97R3StreamOpen(pThis, pStream);
2137
2138 return rc;
2139}
2140
2141/**
2142 * Locks an AC'97 stream for serialized access.
2143 *
2144 * @returns IPRT status code.
2145 * @param pStream AC'97 stream to lock.
2146 */
2147static void ichac97R3StreamLock(PAC97STREAM pStream)
2148{
2149 AssertPtrReturnVoid(pStream);
2150 int rc2 = RTCritSectEnter(&pStream->State.CritSect);
2151 AssertRC(rc2);
2152}
2153
2154/**
2155 * Unlocks a formerly locked AC'97 stream.
2156 *
2157 * @returns IPRT status code.
2158 * @param pStream AC'97 stream to unlock.
2159 */
2160static void ichac97R3StreamUnlock(PAC97STREAM pStream)
2161{
2162 AssertPtrReturnVoid(pStream);
2163 int rc2 = RTCritSectLeave(&pStream->State.CritSect);
2164 AssertRC(rc2);
2165}
2166
2167/**
2168 * Retrieves the available size of (buffered) audio data (in bytes) of a given AC'97 stream.
2169 *
2170 * @returns Available data (in bytes).
2171 * @param pStream AC'97 stream to retrieve size for.
2172 */
2173static uint32_t ichac97R3StreamGetUsed(PAC97STREAM pStream)
2174{
2175 AssertPtrReturn(pStream, 0);
2176
2177 if (!pStream->State.pCircBuf)
2178 return 0;
2179
2180 return (uint32_t)RTCircBufUsed(pStream->State.pCircBuf);
2181}
2182
2183/**
2184 * Retrieves the free size of audio data (in bytes) of a given AC'97 stream.
2185 *
2186 * @returns Free data (in bytes).
2187 * @param pStream AC'97 stream to retrieve size for.
2188 */
2189static uint32_t ichac97R3StreamGetFree(PAC97STREAM pStream)
2190{
2191 AssertPtrReturn(pStream, 0);
2192
2193 if (!pStream->State.pCircBuf)
2194 return 0;
2195
2196 return (uint32_t)RTCircBufFree(pStream->State.pCircBuf);
2197}
2198
2199/**
2200 * Sets the volume of a specific AC'97 mixer control.
2201 *
2202 * This currently only supports attenuation -- gain support is currently not implemented.
2203 *
2204 * @returns IPRT status code.
2205 * @param pThis AC'97 state.
2206 * @param index AC'97 mixer index to set volume for.
2207 * @param enmMixerCtl Corresponding audio mixer sink.
2208 * @param uVal Volume value to set.
2209 */
2210static int ichac97R3MixerSetVolume(PAC97STATE pThis, int index, PDMAUDIOMIXERCTL enmMixerCtl, uint32_t uVal)
2211{
2212 /*
2213 * From AC'97 SoundMax Codec AD1981A/AD1981B:
2214 * "Because AC '97 defines 6-bit volume registers, to maintain compatibility whenever the
2215 * D5 or D13 bits are set to 1, their respective lower five volume bits are automatically
2216 * set to 1 by the Codec logic. On readback, all lower 5 bits will read ones whenever
2217 * these bits are set to 1."
2218 *
2219 * Linux ALSA depends on this behavior to detect that only 5 bits are used for volume
2220 * control and the optional 6th bit is not used. Note that this logic only applies to the
2221 * master volume controls.
2222 */
2223 if ((index == AC97_Master_Volume_Mute) || (index == AC97_Headphone_Volume_Mute) || (index == AC97_Master_Volume_Mono_Mute))
2224 {
2225 if (uVal & RT_BIT(5)) /* D5 bit set? */
2226 uVal |= RT_BIT(4) | RT_BIT(3) | RT_BIT(2) | RT_BIT(1) | RT_BIT(0);
2227 if (uVal & RT_BIT(13)) /* D13 bit set? */
2228 uVal |= RT_BIT(12) | RT_BIT(11) | RT_BIT(10) | RT_BIT(9) | RT_BIT(8);
2229 }
2230
2231 const bool fCtlMuted = (uVal >> AC97_BARS_VOL_MUTE_SHIFT) & 1;
2232 uint8_t uCtlAttLeft = (uVal >> 8) & AC97_BARS_VOL_MASK;
2233 uint8_t uCtlAttRight = uVal & AC97_BARS_VOL_MASK;
2234
2235 /* For the master and headphone volume, 0 corresponds to 0dB attenuation. For the other
2236 * volume controls, 0 means 12dB gain and 8 means unity gain.
2237 */
2238 if (index != AC97_Master_Volume_Mute && index != AC97_Headphone_Volume_Mute)
2239 {
2240# ifndef VBOX_WITH_AC97_GAIN_SUPPORT
2241 /* NB: Currently there is no gain support, only attenuation. */
2242 uCtlAttLeft = uCtlAttLeft < 8 ? 0 : uCtlAttLeft - 8;
2243 uCtlAttRight = uCtlAttRight < 8 ? 0 : uCtlAttRight - 8;
2244# endif
2245 }
2246 Assert(uCtlAttLeft <= 255 / AC97_DB_FACTOR);
2247 Assert(uCtlAttRight <= 255 / AC97_DB_FACTOR);
2248
2249 LogFunc(("index=0x%x, uVal=%RU32, enmMixerCtl=%RU32\n", index, uVal, enmMixerCtl));
2250 LogFunc(("uCtlAttLeft=%RU8, uCtlAttRight=%RU8 ", uCtlAttLeft, uCtlAttRight));
2251
2252 /*
2253 * For AC'97 volume controls, each additional step means -1.5dB attenuation with
2254 * zero being maximum. In contrast, we're internally using 255 (PDMAUDIO_VOLUME_MAX)
2255 * steps, each -0.375dB, where 0 corresponds to -96dB and 255 corresponds to 0dB.
2256 */
2257 uint8_t lVol = PDMAUDIO_VOLUME_MAX - uCtlAttLeft * AC97_DB_FACTOR;
2258 uint8_t rVol = PDMAUDIO_VOLUME_MAX - uCtlAttRight * AC97_DB_FACTOR;
2259
2260 Log(("-> fMuted=%RTbool, lVol=%RU8, rVol=%RU8\n", fCtlMuted, lVol, rVol));
2261
2262 int rc = VINF_SUCCESS;
2263
2264 if (pThis->pMixer) /* Device can be in reset state, so no mixer available. */
2265 {
2266 PDMAUDIOVOLUME Vol = { fCtlMuted, lVol, rVol };
2267 PAUDMIXSINK pSink = NULL;
2268
2269 switch (enmMixerCtl)
2270 {
2271 case PDMAUDIOMIXERCTL_VOLUME_MASTER:
2272 rc = AudioMixerSetMasterVolume(pThis->pMixer, &Vol);
2273 break;
2274
2275 case PDMAUDIOMIXERCTL_FRONT:
2276 pSink = pThis->pSinkOut;
2277 break;
2278
2279 case PDMAUDIOMIXERCTL_MIC_IN:
2280 case PDMAUDIOMIXERCTL_LINE_IN:
2281 /* These are recognized but do nothing. */
2282 break;
2283
2284 default:
2285 AssertFailed();
2286 rc = VERR_NOT_SUPPORTED;
2287 break;
2288 }
2289
2290 if (pSink)
2291 rc = AudioMixerSinkSetVolume(pSink, &Vol);
2292 }
2293
2294 ichac97MixerSet(pThis, index, uVal);
2295
2296 if (RT_FAILURE(rc))
2297 LogFlowFunc(("Failed with %Rrc\n", rc));
2298
2299 return rc;
2300}
2301
2302/**
2303 * Sets the gain of a specific AC'97 recording control.
2304 *
2305 * NB: gain support is currently not implemented in PDM audio.
2306 *
2307 * @returns IPRT status code.
2308 * @param pThis AC'97 state.
2309 * @param index AC'97 mixer index to set volume for.
2310 * @param enmMixerCtl Corresponding audio mixer sink.
2311 * @param uVal Volume value to set.
2312 */
2313static int ichac97R3MixerSetGain(PAC97STATE pThis, int index, PDMAUDIOMIXERCTL enmMixerCtl, uint32_t uVal)
2314{
2315 /*
2316 * For AC'97 recording controls, each additional step means +1.5dB gain with
2317 * zero being 0dB gain and 15 being +22.5dB gain.
2318 */
2319 const bool fCtlMuted = (uVal >> AC97_BARS_VOL_MUTE_SHIFT) & 1;
2320 uint8_t uCtlGainLeft = (uVal >> 8) & AC97_BARS_GAIN_MASK;
2321 uint8_t uCtlGainRight = uVal & AC97_BARS_GAIN_MASK;
2322
2323 Assert(uCtlGainLeft <= 255 / AC97_DB_FACTOR);
2324 Assert(uCtlGainRight <= 255 / AC97_DB_FACTOR);
2325
2326 LogFunc(("index=0x%x, uVal=%RU32, enmMixerCtl=%RU32\n", index, uVal, enmMixerCtl));
2327 LogFunc(("uCtlGainLeft=%RU8, uCtlGainRight=%RU8 ", uCtlGainLeft, uCtlGainRight));
2328
2329 uint8_t lVol = PDMAUDIO_VOLUME_MAX + uCtlGainLeft * AC97_DB_FACTOR;
2330 uint8_t rVol = PDMAUDIO_VOLUME_MAX + uCtlGainRight * AC97_DB_FACTOR;
2331
2332 /* We do not currently support gain. Since AC'97 does not support attenuation
2333 * for the recording input, the best we can do is set the maximum volume.
2334 */
2335# ifndef VBOX_WITH_AC97_GAIN_SUPPORT
2336 /* NB: Currently there is no gain support, only attenuation. Since AC'97 does not
2337 * support attenuation for the recording inputs, the best we can do is set the
2338 * maximum volume.
2339 */
2340 lVol = rVol = PDMAUDIO_VOLUME_MAX;
2341# endif
2342
2343 Log(("-> fMuted=%RTbool, lVol=%RU8, rVol=%RU8\n", fCtlMuted, lVol, rVol));
2344
2345 int rc = VINF_SUCCESS;
2346
2347 if (pThis->pMixer) /* Device can be in reset state, so no mixer available. */
2348 {
2349 PDMAUDIOVOLUME Vol = { fCtlMuted, lVol, rVol };
2350 PAUDMIXSINK pSink = NULL;
2351
2352 switch (enmMixerCtl)
2353 {
2354 case PDMAUDIOMIXERCTL_MIC_IN:
2355 pSink = pThis->pSinkMicIn;
2356 break;
2357
2358 case PDMAUDIOMIXERCTL_LINE_IN:
2359 pSink = pThis->pSinkLineIn;
2360 break;
2361
2362 default:
2363 AssertFailed();
2364 rc = VERR_NOT_SUPPORTED;
2365 break;
2366 }
2367
2368 if (pSink) {
2369 rc = AudioMixerSinkSetVolume(pSink, &Vol);
2370 /* There is only one AC'97 recording gain control. If line in
2371 * is changed, also update the microphone. If the optional dedicated
2372 * microphone is changed, only change that.
2373 * NB: The codecs we support do not have the dedicated microphone control.
2374 */
2375 if ((pSink == pThis->pSinkLineIn) && pThis->pSinkMicIn)
2376 rc = AudioMixerSinkSetVolume(pSink, &Vol);
2377 }
2378 }
2379
2380 ichac97MixerSet(pThis, index, uVal);
2381
2382 if (RT_FAILURE(rc))
2383 LogFlowFunc(("Failed with %Rrc\n", rc));
2384
2385 return rc;
2386}
2387
2388/**
2389 * Converts an AC'97 recording source index to a PDM audio recording source.
2390 *
2391 * @returns PDM audio recording source.
2392 * @param uIdx AC'97 index to convert.
2393 */
2394static PDMAUDIORECSOURCE ichac97R3IdxToRecSource(uint8_t uIdx)
2395{
2396 switch (uIdx)
2397 {
2398 case AC97_REC_MIC: return PDMAUDIORECSOURCE_MIC;
2399 case AC97_REC_CD: return PDMAUDIORECSOURCE_CD;
2400 case AC97_REC_VIDEO: return PDMAUDIORECSOURCE_VIDEO;
2401 case AC97_REC_AUX: return PDMAUDIORECSOURCE_AUX;
2402 case AC97_REC_LINE_IN: return PDMAUDIORECSOURCE_LINE;
2403 case AC97_REC_PHONE: return PDMAUDIORECSOURCE_PHONE;
2404 default:
2405 break;
2406 }
2407
2408 LogFlowFunc(("Unknown record source %d, using MIC\n", uIdx));
2409 return PDMAUDIORECSOURCE_MIC;
2410}
2411
2412/**
2413 * Converts a PDM audio recording source to an AC'97 recording source index.
2414 *
2415 * @returns AC'97 recording source index.
2416 * @param enmRecSrc PDM audio recording source to convert.
2417 */
2418static uint8_t ichac97R3RecSourceToIdx(PDMAUDIORECSOURCE enmRecSrc)
2419{
2420 switch (enmRecSrc)
2421 {
2422 case PDMAUDIORECSOURCE_MIC: return AC97_REC_MIC;
2423 case PDMAUDIORECSOURCE_CD: return AC97_REC_CD;
2424 case PDMAUDIORECSOURCE_VIDEO: return AC97_REC_VIDEO;
2425 case PDMAUDIORECSOURCE_AUX: return AC97_REC_AUX;
2426 case PDMAUDIORECSOURCE_LINE: return AC97_REC_LINE_IN;
2427 case PDMAUDIORECSOURCE_PHONE: return AC97_REC_PHONE;
2428 default:
2429 break;
2430 }
2431
2432 LogFlowFunc(("Unknown audio recording source %d using MIC\n", enmRecSrc));
2433 return AC97_REC_MIC;
2434}
2435
2436/**
2437 * Returns the audio direction of a specified stream descriptor.
2438 *
2439 * @return Audio direction.
2440 */
2441DECLINLINE(PDMAUDIODIR) ichac97GetDirFromSD(uint8_t uSD)
2442{
2443 switch (uSD)
2444 {
2445 case AC97SOUNDSOURCE_PI_INDEX: return PDMAUDIODIR_IN;
2446 case AC97SOUNDSOURCE_PO_INDEX: return PDMAUDIODIR_OUT;
2447 case AC97SOUNDSOURCE_MC_INDEX: return PDMAUDIODIR_IN;
2448 }
2449
2450 AssertFailed();
2451 return PDMAUDIODIR_UNKNOWN;
2452}
2453
2454#endif /* IN_RING3 */
2455
2456#ifdef IN_RING3
2457
2458/**
2459 * Performs an AC'97 mixer record select to switch to a different recording
2460 * source.
2461 *
2462 * @param pThis AC'97 state.
2463 * @param val AC'97 recording source index to set.
2464 */
2465static void ichac97R3MixerRecordSelect(PAC97STATE pThis, uint32_t val)
2466{
2467 uint8_t rs = val & AC97_REC_MASK;
2468 uint8_t ls = (val >> 8) & AC97_REC_MASK;
2469 PDMAUDIORECSOURCE ars = ichac97R3IdxToRecSource(rs);
2470 PDMAUDIORECSOURCE als = ichac97R3IdxToRecSource(ls);
2471 rs = ichac97R3RecSourceToIdx(ars);
2472 ls = ichac97R3RecSourceToIdx(als);
2473 ichac97MixerSet(pThis, AC97_Record_Select, rs | (ls << 8));
2474}
2475
2476/**
2477 * Resets the AC'97 mixer.
2478 *
2479 * @returns IPRT status code.
2480 * @param pThis AC'97 state.
2481 */
2482static int ichac97R3MixerReset(PAC97STATE pThis)
2483{
2484 AssertPtrReturn(pThis, VERR_INVALID_PARAMETER);
2485
2486 LogFlowFuncEnter();
2487
2488 RT_ZERO(pThis->mixer_data);
2489
2490 /* Note: Make sure to reset all registers first before bailing out on error. */
2491
2492 ichac97MixerSet(pThis, AC97_Reset , 0x0000); /* 6940 */
2493 ichac97MixerSet(pThis, AC97_Master_Volume_Mono_Mute , 0x8000);
2494 ichac97MixerSet(pThis, AC97_PC_BEEP_Volume_Mute , 0x0000);
2495
2496 ichac97MixerSet(pThis, AC97_Phone_Volume_Mute , 0x8008);
2497 ichac97MixerSet(pThis, AC97_Mic_Volume_Mute , 0x8008);
2498 ichac97MixerSet(pThis, AC97_CD_Volume_Mute , 0x8808);
2499 ichac97MixerSet(pThis, AC97_Aux_Volume_Mute , 0x8808);
2500 ichac97MixerSet(pThis, AC97_Record_Gain_Mic_Mute , 0x8000);
2501 ichac97MixerSet(pThis, AC97_General_Purpose , 0x0000);
2502 ichac97MixerSet(pThis, AC97_3D_Control , 0x0000);
2503 ichac97MixerSet(pThis, AC97_Powerdown_Ctrl_Stat , 0x000f);
2504
2505 ichac97MixerSet(pThis, AC97_Extended_Audio_ID , 0x0809);
2506 ichac97MixerSet(pThis, AC97_Extended_Audio_Ctrl_Stat, 0x0009);
2507 ichac97MixerSet(pThis, AC97_PCM_Front_DAC_Rate , 0xbb80);
2508 ichac97MixerSet(pThis, AC97_PCM_Surround_DAC_Rate , 0xbb80);
2509 ichac97MixerSet(pThis, AC97_PCM_LFE_DAC_Rate , 0xbb80);
2510 ichac97MixerSet(pThis, AC97_PCM_LR_ADC_Rate , 0xbb80);
2511 ichac97MixerSet(pThis, AC97_MIC_ADC_Rate , 0xbb80);
2512
2513 if (pThis->uCodecModel == AC97_CODEC_AD1980)
2514 {
2515 /* Analog Devices 1980 (AD1980) */
2516 ichac97MixerSet(pThis, AC97_Reset , 0x0010); /* Headphones. */
2517 ichac97MixerSet(pThis, AC97_Vendor_ID1 , 0x4144);
2518 ichac97MixerSet(pThis, AC97_Vendor_ID2 , 0x5370);
2519 ichac97MixerSet(pThis, AC97_Headphone_Volume_Mute , 0x8000);
2520 }
2521 else if (pThis->uCodecModel == AC97_CODEC_AD1981B)
2522 {
2523 /* Analog Devices 1981B (AD1981B) */
2524 ichac97MixerSet(pThis, AC97_Vendor_ID1 , 0x4144);
2525 ichac97MixerSet(pThis, AC97_Vendor_ID2 , 0x5374);
2526 }
2527 else
2528 {
2529 /* Sigmatel 9700 (STAC9700) */
2530 ichac97MixerSet(pThis, AC97_Vendor_ID1 , 0x8384);
2531 ichac97MixerSet(pThis, AC97_Vendor_ID2 , 0x7600); /* 7608 */
2532 }
2533 ichac97R3MixerRecordSelect(pThis, 0);
2534
2535 /* The default value is 8000h, which corresponds to 0 dB attenuation with mute on. */
2536 ichac97R3MixerSetVolume(pThis, AC97_Master_Volume_Mute, PDMAUDIOMIXERCTL_VOLUME_MASTER, 0x8000);
2537
2538 /* The default value for stereo registers is 8808h, which corresponds to 0 dB gain with mute on.*/
2539 ichac97R3MixerSetVolume(pThis, AC97_PCM_Out_Volume_Mute, PDMAUDIOMIXERCTL_FRONT, 0x8808);
2540 ichac97R3MixerSetVolume(pThis, AC97_Line_In_Volume_Mute, PDMAUDIOMIXERCTL_LINE_IN, 0x8808);
2541 ichac97R3MixerSetVolume(pThis, AC97_Mic_Volume_Mute, PDMAUDIOMIXERCTL_MIC_IN, 0x8008);
2542
2543 /* The default for record controls is 0 dB gain with mute on. */
2544 ichac97R3MixerSetGain(pThis, AC97_Record_Gain_Mute, PDMAUDIOMIXERCTL_LINE_IN, 0x8000);
2545 ichac97R3MixerSetGain(pThis, AC97_Record_Gain_Mic_Mute, PDMAUDIOMIXERCTL_MIC_IN, 0x8000);
2546
2547 return VINF_SUCCESS;
2548}
2549
2550# if 0 /* Unused */
2551static void ichac97R3WriteBUP(PAC97STATE pThis, uint32_t cbElapsed)
2552{
2553 LogFlowFunc(("cbElapsed=%RU32\n", cbElapsed));
2554
2555 if (!(pThis->bup_flag & BUP_SET))
2556 {
2557 if (pThis->bup_flag & BUP_LAST)
2558 {
2559 unsigned int i;
2560 uint32_t *p = (uint32_t*)pThis->silence;
2561 for (i = 0; i < sizeof(pThis->silence) / 4; i++) /** @todo r=andy Assumes 16-bit samples, stereo. */
2562 *p++ = pThis->last_samp;
2563 }
2564 else
2565 RT_ZERO(pThis->silence);
2566
2567 pThis->bup_flag |= BUP_SET;
2568 }
2569
2570 while (cbElapsed)
2571 {
2572 uint32_t cbToWrite = RT_MIN(cbElapsed, (uint32_t)sizeof(pThis->silence));
2573 uint32_t cbWrittenToStream;
2574
2575 int rc2 = AudioMixerSinkWrite(pThis->pSinkOut, AUDMIXOP_COPY,
2576 pThis->silence, cbToWrite, &cbWrittenToStream);
2577 if (RT_SUCCESS(rc2))
2578 {
2579 if (cbWrittenToStream < cbToWrite) /* Lagging behind? */
2580 LogFlowFunc(("Warning: Only written %RU32 / %RU32 bytes, expect lags\n", cbWrittenToStream, cbToWrite));
2581 }
2582
2583 /* Always report all data as being written;
2584 * backends who were not able to catch up have to deal with it themselves. */
2585 Assert(cbElapsed >= cbToWrite);
2586 cbElapsed -= cbToWrite;
2587 }
2588}
2589# endif /* Unused */
2590
2591/**
2592 * Timer callback which handles the audio data transfers on a periodic basis.
2593 *
2594 * @param pDevIns Device instance.
2595 * @param pTimer Timer which was used when calling this.
2596 * @param pvUser User argument as PAC97STATE.
2597 */
2598static DECLCALLBACK(void) ichac97R3Timer(PPDMDEVINS pDevIns, PTMTIMER pTimer, void *pvUser)
2599{
2600 RT_NOREF(pDevIns, pTimer);
2601
2602 PAC97STREAM pStream = (PAC97STREAM)pvUser;
2603 AssertPtr(pStream);
2604
2605 PAC97STATE pThis = pStream->pAC97State;
2606 AssertPtr(pThis);
2607
2608 STAM_PROFILE_START(&pThis->StatTimer, a);
2609
2610 DEVAC97_LOCK_BOTH_RETURN_VOID(pThis, pStream->u8SD);
2611
2612 ichac97R3StreamUpdate(pThis, pStream, true /* fInTimer */);
2613
2614 PAUDMIXSINK pSink = ichac97R3IndexToSink(pThis, pStream->u8SD);
2615
2616 bool fSinkActive = false;
2617 if (pSink)
2618 fSinkActive = AudioMixerSinkIsActive(pSink);
2619
2620 if (fSinkActive)
2621 {
2622 TMTimerSet((pThis)->DEVAC97_CTX_SUFF_SD(pTimer, pStream->u8SD),
2623 TMTimerGet((pThis)->DEVAC97_CTX_SUFF_SD(pTimer, pStream->u8SD)) + pStream->State.cTransferTicks);
2624 }
2625
2626 DEVAC97_UNLOCK_BOTH(pThis, pStream->u8SD);
2627
2628 STAM_PROFILE_STOP(&pThis->StatTimer, a);
2629}
2630
2631/**
2632 * Sets the virtual device timer to a new expiration time.
2633 *
2634 * @returns Whether the new expiration time was set or not.
2635 * @param pThis AC'97 state.
2636 * @param pStream AC'97 stream to set timer for.
2637 * @param tsExpire New (virtual) expiration time to set.
2638 * @param fForce Whether to force setting the expiration time or not.
2639 *
2640 * @remark This function takes all active AC'97 streams and their
2641 * current timing into account. This is needed to make sure
2642 * that all streams can match their needed timing.
2643 *
2644 * To achieve this, the earliest (lowest) timestamp of all
2645 * active streams found will be used for the next scheduling slot.
2646 *
2647 * Forcing a new expiration time will override the above mechanism.
2648 */
2649bool ichac97R3TimerSet(PAC97STATE pThis, PAC97STREAM pStream, uint64_t tsExpire, bool fForce)
2650{
2651 AssertPtrReturn(pThis, false);
2652 AssertPtrReturn(pStream, false);
2653
2654 RT_NOREF(fForce);
2655
2656 uint64_t tsExpireMin = tsExpire;
2657
2658 AssertPtr((pThis)->DEVAC97_CTX_SUFF_SD(pTimer, pStream->u8SD));
2659
2660 const uint64_t tsNow = TMTimerGet((pThis)->DEVAC97_CTX_SUFF_SD(pTimer, pStream->u8SD));
2661
2662 /* Make sure to not go backwards in time, as this will assert in TMTimerSet(). */
2663 if (tsExpireMin < tsNow)
2664 tsExpireMin = tsNow;
2665
2666 int rc = TMTimerSet((pThis)->DEVAC97_CTX_SUFF_SD(pTimer, pStream->u8SD), tsExpireMin);
2667 AssertRC(rc);
2668
2669 return RT_SUCCESS(rc);
2670}
2671
2672/**
2673 * Transfers data of an AC'97 stream according to its usage (input / output).
2674 *
2675 * For an SDO (output) stream this means reading DMA data from the device to
2676 * the AC'97 stream's internal FIFO buffer.
2677 *
2678 * For an SDI (input) stream this is reading audio data from the AC'97 stream's
2679 * internal FIFO buffer and writing it as DMA data to the device.
2680 *
2681 * @returns IPRT status code.
2682 * @param pThis AC'97 state.
2683 * @param pStream AC'97 stream to update.
2684 * @param cbToProcessMax Maximum of data (in bytes) to process.
2685 */
2686static int ichac97R3StreamTransfer(PAC97STATE pThis, PAC97STREAM pStream, uint32_t cbToProcessMax)
2687{
2688 AssertPtrReturn(pThis, VERR_INVALID_POINTER);
2689 AssertPtrReturn(pStream, VERR_INVALID_POINTER);
2690 AssertReturn(cbToProcessMax, VERR_INVALID_PARAMETER);
2691
2692 ichac97R3StreamLock(pStream);
2693
2694 PAC97BMREGS pRegs = &pStream->Regs;
2695
2696 if (pRegs->sr & AC97_SR_DCH) /* Controller halted? */
2697 {
2698 if (pRegs->cr & AC97_CR_RPBM) /* Bus master operation starts. */
2699 {
2700 switch (pStream->u8SD)
2701 {
2702 case AC97SOUNDSOURCE_PO_INDEX:
2703 /*ichac97R3WriteBUP(pThis, cbToProcess);*/
2704 break;
2705
2706 default:
2707 break;
2708 }
2709 }
2710
2711 ichac97R3StreamUnlock(pStream);
2712 return VINF_SUCCESS;
2713 }
2714
2715 /* BCIS flag still set? Skip iteration. */
2716 if (pRegs->sr & AC97_SR_BCIS)
2717 {
2718 Log3Func(("[SD%RU8] BCIS set\n", pStream->u8SD));
2719
2720 ichac97R3StreamUnlock(pStream);
2721 return VINF_SUCCESS;
2722 }
2723
2724 uint32_t cbLeft = RT_MIN((uint32_t)(pRegs->picb << 1), cbToProcessMax); /** @todo r=andy Assumes 16bit samples. */
2725 uint32_t cbProcessedTotal = 0;
2726
2727 PRTCIRCBUF pCircBuf = pStream->State.pCircBuf;
2728 AssertPtr(pCircBuf);
2729
2730 int rc = VINF_SUCCESS;
2731
2732 Log3Func(("[SD%RU8] cbToProcessMax=%RU32, cbLeft=%RU32\n", pStream->u8SD, cbToProcessMax, cbLeft));
2733
2734 while (cbLeft)
2735 {
2736 if (!pRegs->bd_valid)
2737 {
2738 Log3Func(("Invalid buffer descriptor, fetching next one ...\n"));
2739 ichac97R3StreamFetchBDLE(pThis, pStream);
2740 }
2741
2742 if (!pRegs->picb) /* Got a new buffer descriptor, that is, the position is 0? */
2743 {
2744 Log3Func(("Fresh buffer descriptor %RU8 is empty, addr=%#x, len=%#x, skipping\n",
2745 pRegs->civ, pRegs->bd.addr, pRegs->bd.ctl_len));
2746 if (pRegs->civ == pRegs->lvi)
2747 {
2748 pRegs->sr |= AC97_SR_DCH; /** @todo r=andy Also set CELV? */
2749 pThis->bup_flag = 0;
2750
2751 rc = VINF_EOF;
2752 break;
2753 }
2754
2755 pRegs->sr &= ~AC97_SR_CELV;
2756 pRegs->civ = pRegs->piv;
2757 pRegs->piv = (pRegs->piv + 1) % AC97_MAX_BDLE;
2758
2759 ichac97R3StreamFetchBDLE(pThis, pStream);
2760 continue;
2761 }
2762
2763 uint32_t cbChunk = RT_MIN((uint32_t)(pRegs->picb << 1), cbLeft); /** @todo r=andy Assumes 16bit samples. */
2764 Assert(cbChunk);
2765
2766 switch (pStream->u8SD)
2767 {
2768 case AC97SOUNDSOURCE_PO_INDEX: /* Output */
2769 {
2770 void *pvDst;
2771 size_t cbDst;
2772
2773 RTCircBufAcquireWriteBlock(pCircBuf, cbChunk, &pvDst, &cbDst);
2774
2775 if (cbDst)
2776 {
2777 int rc2 = PDMDevHlpPhysRead(pThis->CTX_SUFF(pDevIns), pRegs->bd.addr, (uint8_t *)pvDst, cbDst);
2778 AssertRC(rc2);
2779
2780 if (pStream->Dbg.Runtime.fEnabled)
2781 DrvAudioHlpFileWrite(pStream->Dbg.Runtime.pFileDMA, pvDst, cbDst, 0 /* fFlags */);
2782 }
2783
2784 RTCircBufReleaseWriteBlock(pCircBuf, cbDst);
2785
2786 cbChunk = (uint32_t)cbDst; /* Update the current chunk size to what really has been written. */
2787 break;
2788 }
2789
2790 case AC97SOUNDSOURCE_PI_INDEX: /* Input */
2791 case AC97SOUNDSOURCE_MC_INDEX: /* Input */
2792 {
2793 void *pvSrc;
2794 size_t cbSrc;
2795
2796 RTCircBufAcquireReadBlock(pCircBuf, cbChunk, &pvSrc, &cbSrc);
2797
2798 if (cbSrc)
2799 {
2800/** @todo r=bird: Just curious, DevHDA uses PDMDevHlpPCIPhysWrite here. So,
2801 * is AC97 not subject to PCI busmaster enable/disable? */
2802 int rc2 = PDMDevHlpPhysWrite(pThis->CTX_SUFF(pDevIns), pRegs->bd.addr, (uint8_t *)pvSrc, cbSrc);
2803 AssertRC(rc2);
2804
2805 if (pStream->Dbg.Runtime.fEnabled)
2806 DrvAudioHlpFileWrite(pStream->Dbg.Runtime.pFileDMA, pvSrc, cbSrc, 0 /* fFlags */);
2807 }
2808
2809 RTCircBufReleaseReadBlock(pCircBuf, cbSrc);
2810
2811 cbChunk = (uint32_t)cbSrc; /* Update the current chunk size to what really has been read. */
2812 break;
2813 }
2814
2815 default:
2816 AssertMsgFailed(("Stream #%RU8 not supported\n", pStream->u8SD));
2817 rc = VERR_NOT_SUPPORTED;
2818 break;
2819 }
2820
2821 if (RT_FAILURE(rc))
2822 break;
2823
2824 if (cbChunk)
2825 {
2826 cbProcessedTotal += cbChunk;
2827 Assert(cbProcessedTotal <= cbToProcessMax);
2828 Assert(cbLeft >= cbChunk);
2829 cbLeft -= cbChunk;
2830 Assert((cbChunk & 1) == 0); /* Else the following shift won't work */
2831
2832 pRegs->picb -= (cbChunk >> 1); /** @todo r=andy Assumes 16bit samples. */
2833 pRegs->bd.addr += cbChunk;
2834 }
2835
2836 LogFlowFunc(("[SD%RU8] cbChunk=%RU32, cbLeft=%RU32, cbTotal=%RU32, rc=%Rrc\n",
2837 pStream->u8SD, cbChunk, cbLeft, cbProcessedTotal, rc));
2838
2839 if (!pRegs->picb)
2840 {
2841 uint32_t new_sr = pRegs->sr & ~AC97_SR_CELV;
2842
2843 if (pRegs->bd.ctl_len & AC97_BD_IOC)
2844 {
2845 new_sr |= AC97_SR_BCIS;
2846 }
2847
2848 if (pRegs->civ == pRegs->lvi)
2849 {
2850 /* Did we run out of data? */
2851 LogFunc(("Underrun CIV (%RU8) == LVI (%RU8)\n", pRegs->civ, pRegs->lvi));
2852
2853 new_sr |= AC97_SR_LVBCI | AC97_SR_DCH | AC97_SR_CELV;
2854 pThis->bup_flag = (pRegs->bd.ctl_len & AC97_BD_BUP) ? BUP_LAST : 0;
2855
2856 rc = VINF_EOF;
2857 }
2858 else
2859 {
2860 pRegs->civ = pRegs->piv;
2861 pRegs->piv = (pRegs->piv + 1) % AC97_MAX_BDLE;
2862 ichac97R3StreamFetchBDLE(pThis, pStream);
2863 }
2864
2865 ichac97StreamUpdateSR(pThis, pStream, new_sr);
2866 }
2867
2868 if (/* All data processed? */
2869 rc == VINF_EOF
2870 /* ... or an error occurred? */
2871 || RT_FAILURE(rc))
2872 {
2873 break;
2874 }
2875 }
2876
2877 ichac97R3StreamUnlock(pStream);
2878
2879 LogFlowFuncLeaveRC(rc);
2880 return rc;
2881}
2882
2883#endif /* IN_RING3 */
2884
2885
2886/**
2887 * Port I/O Handler for IN operations.
2888 *
2889 * @returns VINF_SUCCESS or VINF_EM_*.
2890 * @returns VERR_IOM_IOPORT_UNUSED if the port is really unused and a ~0 value should be returned.
2891 *
2892 * @param pDevIns The device instance.
2893 * @param pvUser User argument.
2894 * @param uPort Port number used for the IN operation.
2895 * @param pu32Val Where to store the result. This is always a 32-bit
2896 * variable regardless of what @a cbVal might say.
2897 * @param cbVal Number of bytes read.
2898 */
2899PDMBOTHCBDECL(int) ichac97IOPortNABMRead(PPDMDEVINS pDevIns, void *pvUser, RTIOPORT uPort, uint32_t *pu32Val, unsigned cbVal)
2900{
2901 PAC97STATE pThis = PDMINS_2_DATA(pDevIns, PAC97STATE);
2902 RT_NOREF(pvUser);
2903
2904 DEVAC97_LOCK_RETURN(pThis, VINF_IOM_R3_IOPORT_READ);
2905
2906 /* Get the index of the NABMBAR port. */
2907 const uint32_t uPortIdx = uPort - pThis->IOPortBase[1];
2908
2909 PAC97STREAM pStream = NULL;
2910 PAC97BMREGS pRegs = NULL;
2911
2912 if (AC97_PORT2IDX(uPortIdx) < AC97_MAX_STREAMS)
2913 {
2914 pStream = &pThis->aStreams[AC97_PORT2IDX(uPortIdx)];
2915 AssertPtr(pStream);
2916 pRegs = &pStream->Regs;
2917 }
2918
2919 int rc = VINF_SUCCESS;
2920
2921 switch (cbVal)
2922 {
2923 case 1:
2924 {
2925 switch (uPortIdx)
2926 {
2927 case AC97_CAS:
2928 /* Codec Access Semaphore Register */
2929 Log3Func(("CAS %d\n", pThis->cas));
2930 *pu32Val = pThis->cas;
2931 pThis->cas = 1;
2932 break;
2933 case PI_CIV:
2934 case PO_CIV:
2935 case MC_CIV:
2936 /* Current Index Value Register */
2937 *pu32Val = pRegs->civ;
2938 Log3Func(("CIV[%d] -> %#x\n", AC97_PORT2IDX(uPortIdx), *pu32Val));
2939 break;
2940 case PI_LVI:
2941 case PO_LVI:
2942 case MC_LVI:
2943 /* Last Valid Index Register */
2944 *pu32Val = pRegs->lvi;
2945 Log3Func(("LVI[%d] -> %#x\n", AC97_PORT2IDX(uPortIdx), *pu32Val));
2946 break;
2947 case PI_PIV:
2948 case PO_PIV:
2949 case MC_PIV:
2950 /* Prefetched Index Value Register */
2951 *pu32Val = pRegs->piv;
2952 Log3Func(("PIV[%d] -> %#x\n", AC97_PORT2IDX(uPortIdx), *pu32Val));
2953 break;
2954 case PI_CR:
2955 case PO_CR:
2956 case MC_CR:
2957 /* Control Register */
2958 *pu32Val = pRegs->cr;
2959 Log3Func(("CR[%d] -> %#x\n", AC97_PORT2IDX(uPortIdx), *pu32Val));
2960 break;
2961 case PI_SR:
2962 case PO_SR:
2963 case MC_SR:
2964 /* Status Register (lower part) */
2965 *pu32Val = RT_LO_U8(pRegs->sr);
2966 Log3Func(("SRb[%d] -> %#x\n", AC97_PORT2IDX(uPortIdx), *pu32Val));
2967 break;
2968 default:
2969 *pu32Val = UINT32_MAX;
2970 LogFunc(("U nabm readb %#x -> %#x\n", uPort, *pu32Val));
2971 break;
2972 }
2973 break;
2974 }
2975
2976 case 2:
2977 {
2978 switch (uPortIdx)
2979 {
2980 case PI_SR:
2981 case PO_SR:
2982 case MC_SR:
2983 /* Status Register */
2984 *pu32Val = pRegs->sr;
2985 Log3Func(("SR[%d] -> %#x\n", AC97_PORT2IDX(uPortIdx), *pu32Val));
2986 break;
2987 case PI_PICB:
2988 case PO_PICB:
2989 case MC_PICB:
2990 /* Position in Current Buffer */
2991 *pu32Val = pRegs->picb;
2992 Log3Func(("PICB[%d] -> %#x\n", AC97_PORT2IDX(uPortIdx), *pu32Val));
2993 break;
2994 default:
2995 *pu32Val = UINT32_MAX;
2996 LogFunc(("U nabm readw %#x -> %#x\n", uPort, *pu32Val));
2997 break;
2998 }
2999 break;
3000 }
3001
3002 case 4:
3003 {
3004 switch (uPortIdx)
3005 {
3006 case PI_BDBAR:
3007 case PO_BDBAR:
3008 case MC_BDBAR:
3009 /* Buffer Descriptor Base Address Register */
3010 *pu32Val = pRegs->bdbar;
3011 Log3Func(("BMADDR[%d] -> %#x\n", AC97_PORT2IDX(uPortIdx), *pu32Val));
3012 break;
3013 case PI_CIV:
3014 case PO_CIV:
3015 case MC_CIV:
3016 /* 32-bit access: Current Index Value Register +
3017 * Last Valid Index Register +
3018 * Status Register */
3019 *pu32Val = pRegs->civ | (pRegs->lvi << 8) | (pRegs->sr << 16); /** @todo r=andy Use RT_MAKE_U32_FROM_U8. */
3020 Log3Func(("CIV LVI SR[%d] -> %#x, %#x, %#x\n",
3021 AC97_PORT2IDX(uPortIdx), pRegs->civ, pRegs->lvi, pRegs->sr));
3022 break;
3023 case PI_PICB:
3024 case PO_PICB:
3025 case MC_PICB:
3026 /* 32-bit access: Position in Current Buffer Register +
3027 * Prefetched Index Value Register +
3028 * Control Register */
3029 *pu32Val = pRegs->picb | (pRegs->piv << 16) | (pRegs->cr << 24); /** @todo r=andy Use RT_MAKE_U32_FROM_U8. */
3030 Log3Func(("PICB PIV CR[%d] -> %#x %#x %#x %#x\n",
3031 AC97_PORT2IDX(uPortIdx), *pu32Val, pRegs->picb, pRegs->piv, pRegs->cr));
3032 break;
3033 case AC97_GLOB_CNT:
3034 /* Global Control */
3035 *pu32Val = pThis->glob_cnt;
3036 Log3Func(("glob_cnt -> %#x\n", *pu32Val));
3037 break;
3038 case AC97_GLOB_STA:
3039 /* Global Status */
3040 *pu32Val = pThis->glob_sta | AC97_GS_S0CR;
3041 Log3Func(("glob_sta -> %#x\n", *pu32Val));
3042 break;
3043 default:
3044 *pu32Val = UINT32_MAX;
3045 LogFunc(("U nabm readl %#x -> %#x\n", uPort, *pu32Val));
3046 break;
3047 }
3048 break;
3049 }
3050
3051 default:
3052 {
3053 AssertFailed();
3054 rc = VERR_IOM_IOPORT_UNUSED;
3055 }
3056 }
3057
3058 DEVAC97_UNLOCK(pThis);
3059
3060 return rc;
3061}
3062
3063/**
3064 * Port I/O Handler for OUT operations.
3065 *
3066 * @returns VINF_SUCCESS or VINF_EM_*.
3067 *
3068 * @param pDevIns The device instance.
3069 * @param pvUser User argument.
3070 * @param uPort Port number used for the OUT operation.
3071 * @param u32Val The value to output.
3072 * @param cbVal The value size in bytes.
3073 */
3074PDMBOTHCBDECL(int) ichac97IOPortNABMWrite(PPDMDEVINS pDevIns, void *pvUser, RTIOPORT uPort, uint32_t u32Val, unsigned cbVal)
3075{
3076 PAC97STATE pThis = PDMINS_2_DATA(pDevIns, PAC97STATE);
3077 RT_NOREF(pvUser);
3078
3079 /* Get the index of the NABMBAR register. */
3080 const uint32_t uPortIdx = uPort - pThis->IOPortBase[1];
3081
3082 PAC97STREAM pStream = NULL;
3083 PAC97BMREGS pRegs = NULL;
3084
3085 if (AC97_PORT2IDX(uPortIdx) < AC97_MAX_STREAMS)
3086 {
3087 pStream = &pThis->aStreams[AC97_PORT2IDX(uPortIdx)];
3088 AssertPtr(pStream);
3089 pRegs = &pStream->Regs;
3090
3091 DEVAC97_LOCK_BOTH_RETURN(pThis, pStream->u8SD, VINF_IOM_R3_IOPORT_WRITE);
3092 }
3093
3094 int rc = VINF_SUCCESS;
3095 switch (cbVal)
3096 {
3097 case 1:
3098 {
3099 switch (uPortIdx)
3100 {
3101 /*
3102 * Last Valid Index.
3103 */
3104 case PI_LVI:
3105 case PO_LVI:
3106 case MC_LVI:
3107 {
3108 AssertPtr(pStream);
3109 AssertPtr(pRegs);
3110 if ( (pRegs->cr & AC97_CR_RPBM)
3111 && (pRegs->sr & AC97_SR_DCH))
3112 {
3113#ifdef IN_RING3
3114 pRegs->sr &= ~(AC97_SR_DCH | AC97_SR_CELV);
3115 pRegs->civ = pRegs->piv;
3116 pRegs->piv = (pRegs->piv + 1) % AC97_MAX_BDLE;
3117
3118 ichac97R3StreamFetchBDLE(pThis, pStream);
3119#else
3120 rc = VINF_IOM_R3_IOPORT_WRITE;
3121#endif
3122 }
3123 pRegs->lvi = u32Val % AC97_MAX_BDLE;
3124 Log3Func(("[SD%RU8] LVI <- %#x\n", pStream->u8SD, u32Val));
3125 break;
3126 }
3127
3128 /*
3129 * Control Registers.
3130 */
3131 case PI_CR:
3132 case PO_CR:
3133 case MC_CR:
3134 {
3135 AssertPtr(pStream);
3136 AssertPtr(pRegs);
3137#ifdef IN_RING3
3138 Log3Func(("[SD%RU8] CR <- %#x (cr %#x)\n", pStream->u8SD, u32Val, pRegs->cr));
3139 if (u32Val & AC97_CR_RR) /* Busmaster reset. */
3140 {
3141 Log3Func(("[SD%RU8] Reset\n", pStream->u8SD));
3142
3143 /* Make sure that Run/Pause Bus Master bit (RPBM) is cleared (0). */
3144 Assert((pRegs->cr & AC97_CR_RPBM) == 0);
3145
3146 ichac97R3StreamEnable(pThis, pStream, false /* fEnable */);
3147 ichac97R3StreamReset(pThis, pStream);
3148
3149 ichac97StreamUpdateSR(pThis, pStream, AC97_SR_DCH); /** @todo Do we need to do that? */
3150 }
3151 else
3152 {
3153 pRegs->cr = u32Val & AC97_CR_VALID_MASK;
3154
3155 if (!(pRegs->cr & AC97_CR_RPBM))
3156 {
3157 Log3Func(("[SD%RU8] Disable\n", pStream->u8SD));
3158
3159 ichac97R3StreamEnable(pThis, pStream, false /* fEnable */);
3160
3161 pRegs->sr |= AC97_SR_DCH;
3162 }
3163 else
3164 {
3165 Log3Func(("[SD%RU8] Enable\n", pStream->u8SD));
3166
3167 pRegs->civ = pRegs->piv;
3168 pRegs->piv = (pRegs->piv + 1) % AC97_MAX_BDLE;
3169
3170 pRegs->sr &= ~AC97_SR_DCH;
3171
3172 /* Fetch the initial BDLE descriptor. */
3173 ichac97R3StreamFetchBDLE(pThis, pStream);
3174 ichac97R3StreamEnable(pThis, pStream, true /* fEnable */);
3175
3176 /* Arm the timer for this stream. */
3177 int rc2 = ichac97R3TimerSet(pThis, pStream,
3178 TMTimerGet((pThis)->DEVAC97_CTX_SUFF_SD(pTimer, pStream->u8SD)) + pStream->State.cTransferTicks,
3179 false /* fForce */);
3180 AssertRC(rc2);
3181 }
3182 }
3183#else /* !IN_RING3 */
3184 rc = VINF_IOM_R3_IOPORT_WRITE;
3185#endif
3186 break;
3187 }
3188
3189 /*
3190 * Status Registers.
3191 */
3192 case PI_SR:
3193 case PO_SR:
3194 case MC_SR:
3195 {
3196 AssertPtr(pStream);
3197 AssertPtr(pRegs);
3198 pRegs->sr |= u32Val & ~(AC97_SR_RO_MASK | AC97_SR_WCLEAR_MASK);
3199 ichac97StreamUpdateSR(pThis, pStream, pRegs->sr & ~(u32Val & AC97_SR_WCLEAR_MASK));
3200 Log3Func(("[SD%RU8] SR <- %#x (sr %#x)\n", pStream->u8SD, u32Val, pRegs->sr));
3201 break;
3202 }
3203
3204 default:
3205 LogRel2(("AC97: Warning: Unimplemented NABMWrite (%u byte) portIdx=%#x <- %#x\n", cbVal, uPortIdx, u32Val));
3206 break;
3207 }
3208 break;
3209 }
3210
3211 case 2:
3212 {
3213 switch (uPortIdx)
3214 {
3215 case PI_SR:
3216 case PO_SR:
3217 case MC_SR:
3218 AssertPtr(pStream);
3219 AssertPtr(pRegs);
3220 /* Status Register */
3221 pRegs->sr |= u32Val & ~(AC97_SR_RO_MASK | AC97_SR_WCLEAR_MASK);
3222 ichac97StreamUpdateSR(pThis, pStream, pRegs->sr & ~(u32Val & AC97_SR_WCLEAR_MASK));
3223 Log3Func(("[SD%RU8] SR <- %#x (sr %#x)\n", pStream->u8SD, u32Val, pRegs->sr));
3224 break;
3225 default:
3226 LogRel2(("AC97: Warning: Unimplemented NABMWrite (%u byte) portIdx=%#x <- %#x\n", cbVal, uPortIdx, u32Val));
3227 break;
3228 }
3229 break;
3230 }
3231
3232 case 4:
3233 {
3234 switch (uPortIdx)
3235 {
3236 case PI_BDBAR:
3237 case PO_BDBAR:
3238 case MC_BDBAR:
3239 AssertPtr(pStream);
3240 AssertPtr(pRegs);
3241 /* Buffer Descriptor list Base Address Register */
3242 pRegs->bdbar = u32Val & ~3;
3243 Log3Func(("[SD%RU8] BDBAR <- %#x (bdbar %#x)\n", AC97_PORT2IDX(uPortIdx), u32Val, pRegs->bdbar));
3244 break;
3245 case AC97_GLOB_CNT:
3246 /* Global Control */
3247 if (u32Val & AC97_GC_WR)
3248 ichac97WarmReset(pThis);
3249 if (u32Val & AC97_GC_CR)
3250 ichac97ColdReset(pThis);
3251 if (!(u32Val & (AC97_GC_WR | AC97_GC_CR)))
3252 pThis->glob_cnt = u32Val & AC97_GC_VALID_MASK;
3253 Log3Func(("glob_cnt <- %#x (glob_cnt %#x)\n", u32Val, pThis->glob_cnt));
3254 break;
3255 case AC97_GLOB_STA:
3256 /* Global Status */
3257 pThis->glob_sta &= ~(u32Val & AC97_GS_WCLEAR_MASK);
3258 pThis->glob_sta |= (u32Val & ~(AC97_GS_WCLEAR_MASK | AC97_GS_RO_MASK)) & AC97_GS_VALID_MASK;
3259 Log3Func(("glob_sta <- %#x (glob_sta %#x)\n", u32Val, pThis->glob_sta));
3260 break;
3261 default:
3262 LogRel2(("AC97: Warning: Unimplemented NABMWrite (%u byte) portIdx=%#x <- %#x\n", cbVal, uPortIdx, u32Val));
3263 break;
3264 }
3265 break;
3266 }
3267
3268 default:
3269 LogRel2(("AC97: Warning: Unimplemented NABMWrite (%u byte) portIdx=%#x <- %#x\n", cbVal, uPortIdx, u32Val));
3270 break;
3271 }
3272
3273 if (pStream)
3274 DEVAC97_UNLOCK_BOTH(pThis, pStream->u8SD);
3275
3276 return rc;
3277}
3278
3279/**
3280 * Port I/O Handler for IN operations.
3281 *
3282 * @returns VINF_SUCCESS or VINF_EM_*.
3283 * @returns VERR_IOM_IOPORT_UNUSED if the port is really unused and a ~0 value should be returned.
3284 *
3285 * @param pDevIns The device instance.
3286 * @param pvUser User argument.
3287 * @param uPort Port number used for the IN operation.
3288 * @param pu32Val Where to store the result. This is always a 32-bit
3289 * variable regardless of what @a cbVal might say.
3290 * @param cbVal Number of bytes read.
3291 */
3292PDMBOTHCBDECL(int) ichac97IOPortNAMRead(PPDMDEVINS pDevIns, void *pvUser, RTIOPORT uPort, uint32_t *pu32Val, unsigned cbVal)
3293{
3294 PAC97STATE pThis = PDMINS_2_DATA(pDevIns, PAC97STATE);
3295 RT_NOREF(pvUser);
3296
3297 DEVAC97_LOCK_RETURN(pThis, VINF_IOM_R3_IOPORT_READ);
3298
3299 int rc = VINF_SUCCESS;
3300
3301 uint32_t index = uPort - pThis->IOPortBase[0];
3302 Assert(index < 256);
3303
3304 switch (cbVal)
3305 {
3306 case 1:
3307 {
3308 LogRel2(("AC97: Warning: Unimplemented read (%u byte) port=%#x, idx=%RU32\n", cbVal, uPort, index));
3309 pThis->cas = 0;
3310 *pu32Val = UINT32_MAX;
3311 break;
3312 }
3313
3314 case 2:
3315 {
3316 pThis->cas = 0;
3317 *pu32Val = ichac97MixerGet(pThis, index);
3318 break;
3319 }
3320
3321 case 4:
3322 {
3323 LogRel2(("AC97: Warning: Unimplemented read (%u byte) port=%#x, idx=%RU32\n", cbVal, uPort, index));
3324 pThis->cas = 0;
3325 *pu32Val = UINT32_MAX;
3326 break;
3327 }
3328
3329 default:
3330 {
3331 AssertFailed();
3332 rc = VERR_IOM_IOPORT_UNUSED;
3333 }
3334 }
3335
3336 DEVAC97_UNLOCK(pThis);
3337
3338 return rc;
3339}
3340
3341/**
3342 * Port I/O Handler for OUT operations.
3343 *
3344 * @returns VINF_SUCCESS or VINF_EM_*.
3345 *
3346 * @param pDevIns The device instance.
3347 * @param pvUser User argument.
3348 * @param uPort Port number used for the OUT operation.
3349 * @param u32Val The value to output.
3350 * @param cbVal The value size in bytes.
3351 * @remarks Caller enters the device critical section.
3352 */
3353PDMBOTHCBDECL(int) ichac97IOPortNAMWrite(PPDMDEVINS pDevIns, void *pvUser, RTIOPORT uPort, uint32_t u32Val, unsigned cbVal)
3354{
3355 PAC97STATE pThis = PDMINS_2_DATA(pDevIns, PAC97STATE);
3356 RT_NOREF(pvUser);
3357
3358 DEVAC97_LOCK_RETURN(pThis, VINF_IOM_R3_IOPORT_WRITE);
3359
3360 uint32_t uPortIdx = uPort - pThis->IOPortBase[0];
3361
3362 int rc = VINF_SUCCESS;
3363 switch (cbVal)
3364 {
3365 case 1:
3366 {
3367 LogRel2(("AC97: Warning: Unimplemented NAMWrite (%u byte) port=%#x, idx=0x%x <- %#x\n", cbVal, uPort, uPortIdx, u32Val));
3368 pThis->cas = 0;
3369 break;
3370 }
3371
3372 case 2:
3373 {
3374 pThis->cas = 0;
3375 switch (uPortIdx)
3376 {
3377 case AC97_Reset:
3378#ifdef IN_RING3
3379 ichac97R3Reset(pThis->CTX_SUFF(pDevIns));
3380#else
3381 rc = VINF_IOM_R3_IOPORT_WRITE;
3382#endif
3383 break;
3384 case AC97_Powerdown_Ctrl_Stat:
3385 u32Val &= ~0xf;
3386 u32Val |= ichac97MixerGet(pThis, uPortIdx) & 0xf;
3387 ichac97MixerSet(pThis, uPortIdx, u32Val);
3388 break;
3389 case AC97_Master_Volume_Mute:
3390 if (pThis->uCodecModel == AC97_CODEC_AD1980)
3391 {
3392 if (ichac97MixerGet(pThis, AC97_AD_Misc) & AC97_AD_MISC_LOSEL)
3393 break; /* Register controls surround (rear), do nothing. */
3394 }
3395#ifdef IN_RING3
3396 ichac97R3MixerSetVolume(pThis, uPortIdx, PDMAUDIOMIXERCTL_VOLUME_MASTER, u32Val);
3397#else
3398 rc = VINF_IOM_R3_IOPORT_WRITE;
3399#endif
3400 break;
3401 case AC97_Headphone_Volume_Mute:
3402 if (pThis->uCodecModel == AC97_CODEC_AD1980)
3403 {
3404 if (ichac97MixerGet(pThis, AC97_AD_Misc) & AC97_AD_MISC_HPSEL)
3405 {
3406 /* Register controls PCM (front) outputs. */
3407#ifdef IN_RING3
3408 ichac97R3MixerSetVolume(pThis, uPortIdx, PDMAUDIOMIXERCTL_VOLUME_MASTER, u32Val);
3409#else
3410 rc = VINF_IOM_R3_IOPORT_WRITE;
3411#endif
3412 }
3413 }
3414 break;
3415 case AC97_PCM_Out_Volume_Mute:
3416#ifdef IN_RING3
3417 ichac97R3MixerSetVolume(pThis, uPortIdx, PDMAUDIOMIXERCTL_FRONT, u32Val);
3418#else
3419 rc = VINF_IOM_R3_IOPORT_WRITE;
3420#endif
3421 break;
3422 case AC97_Line_In_Volume_Mute:
3423#ifdef IN_RING3
3424 ichac97R3MixerSetVolume(pThis, uPortIdx, PDMAUDIOMIXERCTL_LINE_IN, u32Val);
3425#else
3426 rc = VINF_IOM_R3_IOPORT_WRITE;
3427#endif
3428 break;
3429 case AC97_Record_Select:
3430#ifdef IN_RING3
3431 ichac97R3MixerRecordSelect(pThis, u32Val);
3432#else
3433 rc = VINF_IOM_R3_IOPORT_WRITE;
3434#endif
3435 break;
3436 case AC97_Record_Gain_Mute:
3437#ifdef IN_RING3
3438 /* Newer Ubuntu guests rely on that when controlling gain and muting
3439 * the recording (capturing) levels. */
3440 ichac97R3MixerSetGain(pThis, uPortIdx, PDMAUDIOMIXERCTL_LINE_IN, u32Val);
3441#else
3442 rc = VINF_IOM_R3_IOPORT_WRITE;
3443#endif
3444 break;
3445 case AC97_Record_Gain_Mic_Mute:
3446#ifdef IN_RING3
3447 /* Ditto; see note above. */
3448 ichac97R3MixerSetGain(pThis, uPortIdx, PDMAUDIOMIXERCTL_MIC_IN, u32Val);
3449#else
3450 rc = VINF_IOM_R3_IOPORT_WRITE;
3451#endif
3452 break;
3453 case AC97_Vendor_ID1:
3454 case AC97_Vendor_ID2:
3455 LogFunc(("Attempt to write vendor ID to %#x\n", u32Val));
3456 break;
3457 case AC97_Extended_Audio_ID:
3458 LogFunc(("Attempt to write extended audio ID to %#x\n", u32Val));
3459 break;
3460 case AC97_Extended_Audio_Ctrl_Stat:
3461#ifdef IN_RING3
3462 if (!(u32Val & AC97_EACS_VRA))
3463 {
3464 ichac97MixerSet(pThis, AC97_PCM_Front_DAC_Rate, 48000);
3465 ichac97R3StreamReOpen(pThis, &pThis->aStreams[AC97SOUNDSOURCE_PO_INDEX]);
3466
3467 ichac97MixerSet(pThis, AC97_PCM_LR_ADC_Rate, 48000);
3468 ichac97R3StreamReOpen(pThis, &pThis->aStreams[AC97SOUNDSOURCE_PI_INDEX]);
3469 }
3470 else
3471 LogRel2(("AC97: Variable rate audio (VRA) is not supported\n"));
3472
3473 if (!(u32Val & AC97_EACS_VRM))
3474 {
3475 ichac97MixerSet(pThis, AC97_MIC_ADC_Rate, 48000);
3476 ichac97R3StreamReOpen(pThis, &pThis->aStreams[AC97SOUNDSOURCE_MC_INDEX]);
3477 }
3478 else
3479 LogRel2(("AC97: Variable rate microphone audio (VRM) is not supported\n"));
3480
3481 LogFunc(("Setting extended audio control to %#x\n", u32Val));
3482 ichac97MixerSet(pThis, AC97_Extended_Audio_Ctrl_Stat, u32Val);
3483#else
3484 rc = VINF_IOM_R3_IOPORT_WRITE;
3485#endif
3486 break;
3487 case AC97_PCM_Front_DAC_Rate:
3488 if (ichac97MixerGet(pThis, AC97_Extended_Audio_Ctrl_Stat) & AC97_EACS_VRA)
3489 {
3490#ifdef IN_RING3
3491 ichac97MixerSet(pThis, uPortIdx, u32Val);
3492 LogFunc(("Set front DAC rate to %RU32\n", u32Val));
3493 ichac97R3StreamReOpen(pThis, &pThis->aStreams[AC97SOUNDSOURCE_PO_INDEX]);
3494#else
3495 rc = VINF_IOM_R3_IOPORT_WRITE;
3496#endif
3497 }
3498 else
3499 AssertMsgFailed(("Attempt to set front DAC rate to %RU32, but VRA is not set\n", u32Val));
3500 break;
3501 case AC97_MIC_ADC_Rate:
3502 if (ichac97MixerGet(pThis, AC97_Extended_Audio_Ctrl_Stat) & AC97_EACS_VRM)
3503 {
3504#ifdef IN_RING3
3505 ichac97MixerSet(pThis, uPortIdx, u32Val);
3506 LogFunc(("Set MIC ADC rate to %RU32\n", u32Val));
3507 ichac97R3StreamReOpen(pThis, &pThis->aStreams[AC97SOUNDSOURCE_MC_INDEX]);
3508#else
3509 rc = VINF_IOM_R3_IOPORT_WRITE;
3510#endif
3511 }
3512 else
3513 AssertMsgFailed(("Attempt to set MIC ADC rate to %RU32, but VRM is not set\n", u32Val));
3514 break;
3515 case AC97_PCM_LR_ADC_Rate:
3516 if (ichac97MixerGet(pThis, AC97_Extended_Audio_Ctrl_Stat) & AC97_EACS_VRA)
3517 {
3518#ifdef IN_RING3
3519 ichac97MixerSet(pThis, uPortIdx, u32Val);
3520 LogFunc(("Set front LR ADC rate to %RU32\n", u32Val));
3521 ichac97R3StreamReOpen(pThis, &pThis->aStreams[AC97SOUNDSOURCE_PI_INDEX]);
3522#else
3523 rc = VINF_IOM_R3_IOPORT_WRITE;
3524#endif
3525 }
3526 else
3527 AssertMsgFailed(("Attempt to set LR ADC rate to %RU32, but VRA is not set\n", u32Val));
3528 break;
3529 default:
3530 LogRel2(("AC97: Warning: Unimplemented NAMWrite (%u byte) port=%#x, idx=0x%x <- %#x\n", cbVal, uPort, uPortIdx, u32Val));
3531 ichac97MixerSet(pThis, uPortIdx, u32Val);
3532 break;
3533 }
3534 break;
3535 }
3536
3537 case 4:
3538 {
3539 LogRel2(("AC97: Warning: Unimplemented NAMWrite (%u byte) port=%#x, idx=0x%x <- %#x\n", cbVal, uPort, uPortIdx, u32Val));
3540 pThis->cas = 0;
3541 break;
3542 }
3543
3544 default:
3545 AssertMsgFailed(("Unhandled NAMWrite port=%#x, cbVal=%u u32Val=%#x\n", uPort, cbVal, u32Val));
3546 break;
3547 }
3548
3549 DEVAC97_UNLOCK(pThis);
3550
3551 return rc;
3552}
3553
3554#ifdef IN_RING3
3555
3556/**
3557 * @callback_method_impl{FNPCIIOREGIONMAP}
3558 */
3559static DECLCALLBACK(int) ichac97R3IOPortMap(PPDMDEVINS pDevIns, PPDMPCIDEV pPciDev, uint32_t iRegion,
3560 RTGCPHYS GCPhysAddress, RTGCPHYS cb, PCIADDRESSSPACE enmType)
3561{
3562 RT_NOREF(cb, enmType);
3563
3564 Assert(enmType == PCI_ADDRESS_SPACE_IO);
3565 Assert(cb >= 0x20);
3566
3567 if (iRegion > 1) /* We support 2 regions max. at the moment. */
3568 return VERR_INVALID_PARAMETER;
3569
3570 PAC97STATE pThis = RT_FROM_MEMBER(pPciDev, AC97STATE, PciDev);
3571 RTIOPORT Port = (RTIOPORT)GCPhysAddress;
3572
3573 int rc;
3574 if (iRegion == 0)
3575 {
3576 rc = PDMDevHlpIOPortRegister(pDevIns, Port, 256, NULL, ichac97IOPortNAMWrite, ichac97IOPortNAMRead,
3577 NULL, NULL, "ICHAC97 NAM");
3578 AssertRCReturn(rc, rc);
3579 if (pThis->fRZEnabled)
3580 {
3581 rc = PDMDevHlpIOPortRegisterR0(pDevIns, Port, 256, NIL_RTR0PTR, "ichac97IOPortNAMWrite", "ichac97IOPortNAMRead",
3582 NULL, NULL, "ICHAC97 NAM");
3583 AssertRCReturn(rc, rc);
3584 rc = PDMDevHlpIOPortRegisterRC(pDevIns, Port, 256, NIL_RTRCPTR, "ichac97IOPortNAMWrite", "ichac97IOPortNAMRead",
3585 NULL, NULL, "ICHAC97 NAM");
3586 AssertRCReturn(rc, rc);
3587 }
3588 }
3589 else
3590 {
3591 rc = PDMDevHlpIOPortRegister(pDevIns, Port, 64, NULL, ichac97IOPortNABMWrite, ichac97IOPortNABMRead,
3592 NULL, NULL, "ICHAC97 NABM");
3593 AssertRCReturn(rc, rc);
3594 if (pThis->fRZEnabled)
3595 {
3596 rc = PDMDevHlpIOPortRegisterR0(pDevIns, Port, 64, NIL_RTR0PTR, "ichac97IOPortNABMWrite", "ichac97IOPortNABMRead",
3597 NULL, NULL, "ICHAC97 NABM");
3598 AssertRCReturn(rc, rc);
3599 rc = PDMDevHlpIOPortRegisterRC(pDevIns, Port, 64, NIL_RTRCPTR, "ichac97IOPortNABMWrite", "ichac97IOPortNABMRead",
3600 NULL, NULL, "ICHAC97 NABM");
3601 AssertRCReturn(rc, rc);
3602
3603 }
3604 }
3605
3606 pThis->IOPortBase[iRegion] = Port;
3607 return VINF_SUCCESS;
3608}
3609
3610
3611/**
3612 * Saves (serializes) an AC'97 stream using SSM.
3613 *
3614 * @returns IPRT status code.
3615 * @param pDevIns Device instance.
3616 * @param pSSM Saved state manager (SSM) handle to use.
3617 * @param pStream AC'97 stream to save.
3618 */
3619static int ichac97R3SaveStream(PPDMDEVINS pDevIns, PSSMHANDLE pSSM, PAC97STREAM pStream)
3620{
3621 RT_NOREF(pDevIns);
3622 PAC97BMREGS pRegs = &pStream->Regs;
3623
3624 SSMR3PutU32(pSSM, pRegs->bdbar);
3625 SSMR3PutU8( pSSM, pRegs->civ);
3626 SSMR3PutU8( pSSM, pRegs->lvi);
3627 SSMR3PutU16(pSSM, pRegs->sr);
3628 SSMR3PutU16(pSSM, pRegs->picb);
3629 SSMR3PutU8( pSSM, pRegs->piv);
3630 SSMR3PutU8( pSSM, pRegs->cr);
3631 SSMR3PutS32(pSSM, pRegs->bd_valid);
3632 SSMR3PutU32(pSSM, pRegs->bd.addr);
3633 SSMR3PutU32(pSSM, pRegs->bd.ctl_len);
3634
3635 return VINF_SUCCESS;
3636}
3637
3638/**
3639 * @callback_method_impl{FNSSMDEVSAVEEXEC}
3640 */
3641static DECLCALLBACK(int) ichac97R3SaveExec(PPDMDEVINS pDevIns, PSSMHANDLE pSSM)
3642{
3643 PAC97STATE pThis = PDMINS_2_DATA(pDevIns, PAC97STATE);
3644
3645 LogFlowFuncEnter();
3646
3647 SSMR3PutU32(pSSM, pThis->glob_cnt);
3648 SSMR3PutU32(pSSM, pThis->glob_sta);
3649 SSMR3PutU32(pSSM, pThis->cas);
3650
3651 /** @todo r=andy For the next saved state version, add unique stream identifiers and a stream count. */
3652 /* Note: The order the streams are loaded here is critical, so don't touch. */
3653 for (unsigned i = 0; i < AC97_MAX_STREAMS; i++)
3654 {
3655 int rc2 = ichac97R3SaveStream(pDevIns, pSSM, &pThis->aStreams[i]);
3656 AssertRC(rc2);
3657 }
3658
3659 SSMR3PutMem(pSSM, pThis->mixer_data, sizeof(pThis->mixer_data));
3660
3661 uint8_t active[AC97SOUNDSOURCE_END_INDEX];
3662
3663 active[AC97SOUNDSOURCE_PI_INDEX] = ichac97R3StreamIsEnabled(pThis, &pThis->aStreams[AC97SOUNDSOURCE_PI_INDEX]) ? 1 : 0;
3664 active[AC97SOUNDSOURCE_PO_INDEX] = ichac97R3StreamIsEnabled(pThis, &pThis->aStreams[AC97SOUNDSOURCE_PO_INDEX]) ? 1 : 0;
3665 active[AC97SOUNDSOURCE_MC_INDEX] = ichac97R3StreamIsEnabled(pThis, &pThis->aStreams[AC97SOUNDSOURCE_MC_INDEX]) ? 1 : 0;
3666
3667 SSMR3PutMem(pSSM, active, sizeof(active));
3668
3669 LogFlowFuncLeaveRC(VINF_SUCCESS);
3670 return VINF_SUCCESS;
3671}
3672
3673/**
3674 * Loads an AC'97 stream from SSM.
3675 *
3676 * @returns IPRT status code.
3677 * @param pSSM Saved state manager (SSM) handle to use.
3678 * @param pStream AC'97 stream to load.
3679 */
3680static int ichac97R3LoadStream(PSSMHANDLE pSSM, PAC97STREAM pStream)
3681{
3682 PAC97BMREGS pRegs = &pStream->Regs;
3683
3684 SSMR3GetU32(pSSM, &pRegs->bdbar);
3685 SSMR3GetU8( pSSM, &pRegs->civ);
3686 SSMR3GetU8( pSSM, &pRegs->lvi);
3687 SSMR3GetU16(pSSM, &pRegs->sr);
3688 SSMR3GetU16(pSSM, &pRegs->picb);
3689 SSMR3GetU8( pSSM, &pRegs->piv);
3690 SSMR3GetU8( pSSM, &pRegs->cr);
3691 SSMR3GetS32(pSSM, &pRegs->bd_valid);
3692 SSMR3GetU32(pSSM, &pRegs->bd.addr);
3693 return SSMR3GetU32(pSSM, &pRegs->bd.ctl_len);
3694}
3695
3696/**
3697 * @callback_method_impl{FNSSMDEVLOADEXEC}
3698 */
3699static DECLCALLBACK(int) ichac97R3LoadExec(PPDMDEVINS pDevIns, PSSMHANDLE pSSM, uint32_t uVersion, uint32_t uPass)
3700{
3701 PAC97STATE pThis = PDMINS_2_DATA(pDevIns, PAC97STATE);
3702
3703 LogRel2(("ichac97LoadExec: uVersion=%RU32, uPass=0x%x\n", uVersion, uPass));
3704
3705 AssertMsgReturn (uVersion == AC97_SSM_VERSION, ("%RU32\n", uVersion), VERR_SSM_UNSUPPORTED_DATA_UNIT_VERSION);
3706 Assert(uPass == SSM_PASS_FINAL); NOREF(uPass);
3707
3708 SSMR3GetU32(pSSM, &pThis->glob_cnt);
3709 SSMR3GetU32(pSSM, &pThis->glob_sta);
3710 SSMR3GetU32(pSSM, &pThis->cas);
3711
3712 /** @todo r=andy For the next saved state version, add unique stream identifiers and a stream count. */
3713 /* Note: The order the streams are loaded here is critical, so don't touch. */
3714 for (unsigned i = 0; i < AC97_MAX_STREAMS; i++)
3715 {
3716 int rc2 = ichac97R3LoadStream(pSSM, &pThis->aStreams[i]);
3717 AssertRCReturn(rc2, rc2);
3718 }
3719
3720 SSMR3GetMem(pSSM, pThis->mixer_data, sizeof(pThis->mixer_data));
3721
3722 /** @todo r=andy Stream IDs are hardcoded to certain streams. */
3723 uint8_t uaStrmsActive[AC97SOUNDSOURCE_END_INDEX];
3724 int rc2 = SSMR3GetMem(pSSM, uaStrmsActive, sizeof(uaStrmsActive));
3725 AssertRCReturn(rc2, rc2);
3726
3727 ichac97R3MixerRecordSelect(pThis, ichac97MixerGet(pThis, AC97_Record_Select));
3728 ichac97R3MixerSetVolume(pThis, AC97_Master_Volume_Mute, PDMAUDIOMIXERCTL_VOLUME_MASTER, ichac97MixerGet(pThis, AC97_Master_Volume_Mute));
3729 ichac97R3MixerSetVolume(pThis, AC97_PCM_Out_Volume_Mute, PDMAUDIOMIXERCTL_FRONT, ichac97MixerGet(pThis, AC97_PCM_Out_Volume_Mute));
3730 ichac97R3MixerSetVolume(pThis, AC97_Line_In_Volume_Mute, PDMAUDIOMIXERCTL_LINE_IN, ichac97MixerGet(pThis, AC97_Line_In_Volume_Mute));
3731 ichac97R3MixerSetVolume(pThis, AC97_Mic_Volume_Mute, PDMAUDIOMIXERCTL_MIC_IN, ichac97MixerGet(pThis, AC97_Mic_Volume_Mute));
3732 ichac97R3MixerSetGain(pThis, AC97_Record_Gain_Mic_Mute, PDMAUDIOMIXERCTL_MIC_IN, ichac97MixerGet(pThis, AC97_Record_Gain_Mic_Mute));
3733 ichac97R3MixerSetGain(pThis, AC97_Record_Gain_Mute, PDMAUDIOMIXERCTL_LINE_IN, ichac97MixerGet(pThis, AC97_Record_Gain_Mute));
3734 if (pThis->uCodecModel == AC97_CODEC_AD1980)
3735 if (ichac97MixerGet(pThis, AC97_AD_Misc) & AC97_AD_MISC_HPSEL)
3736 ichac97R3MixerSetVolume(pThis, AC97_Headphone_Volume_Mute, PDMAUDIOMIXERCTL_VOLUME_MASTER,
3737 ichac97MixerGet(pThis, AC97_Headphone_Volume_Mute));
3738
3739 /** @todo r=andy Stream IDs are hardcoded to certain streams. */
3740 for (unsigned i = 0; i < AC97_MAX_STREAMS; i++)
3741 {
3742 const bool fEnable = RT_BOOL(uaStrmsActive[i]);
3743 const PAC97STREAM pStream = &pThis->aStreams[i];
3744
3745 rc2 = ichac97R3StreamEnable(pThis, pStream, fEnable);
3746 if ( fEnable
3747 && RT_SUCCESS(rc2))
3748 {
3749 /* Re-arm the timer for this stream. */
3750 rc2 = ichac97R3TimerSet(pThis, pStream,
3751 TMTimerGet((pThis)->DEVAC97_CTX_SUFF_SD(pTimer, pStream->u8SD)) + pStream->State.cTransferTicks,
3752 false /* fForce */);
3753 }
3754
3755 AssertRC(rc2);
3756 /* Keep going. */
3757 }
3758
3759 pThis->bup_flag = 0;
3760 pThis->last_samp = 0;
3761
3762 return VINF_SUCCESS;
3763}
3764
3765
3766/**
3767 * @interface_method_impl{PDMIBASE,pfnQueryInterface}
3768 */
3769static DECLCALLBACK(void *) ichac97R3QueryInterface(struct PDMIBASE *pInterface, const char *pszIID)
3770{
3771 PAC97STATE pThis = RT_FROM_MEMBER(pInterface, AC97STATE, IBase);
3772 Assert(&pThis->IBase == pInterface);
3773
3774 PDMIBASE_RETURN_INTERFACE(pszIID, PDMIBASE, &pThis->IBase);
3775 return NULL;
3776}
3777
3778
3779/**
3780 * Powers off the device.
3781 *
3782 * @param pDevIns Device instance to power off.
3783 */
3784static DECLCALLBACK(void) ichac97R3PowerOff(PPDMDEVINS pDevIns)
3785{
3786 PAC97STATE pThis = PDMINS_2_DATA(pDevIns, PAC97STATE);
3787
3788 LogRel2(("AC97: Powering off ...\n"));
3789
3790 /* Note: Involves mixer stream / sink destruction, so also do this here
3791 * instead of in ichac97R3Destruct(). */
3792 ichac97R3StreamsDestroy(pThis);
3793
3794 /**
3795 * Note: Destroy the mixer while powering off and *not* in ichac97R3Destruct,
3796 * giving the mixer the chance to release any references held to
3797 * PDM audio streams it maintains.
3798 */
3799 if (pThis->pMixer)
3800 {
3801 AudioMixerDestroy(pThis->pMixer);
3802 pThis->pMixer = NULL;
3803 }
3804}
3805
3806
3807/**
3808 * @interface_method_impl{PDMDEVREG,pfnReset}
3809 *
3810 * @remarks The original sources didn't install a reset handler, but it seems to
3811 * make sense to me so we'll do it.
3812 */
3813static DECLCALLBACK(void) ichac97R3Reset(PPDMDEVINS pDevIns)
3814{
3815 PAC97STATE pThis = PDMINS_2_DATA(pDevIns, PAC97STATE);
3816
3817 LogRel(("AC97: Reset\n"));
3818
3819 /*
3820 * Reset the mixer too. The Windows XP driver seems to rely on
3821 * this. At least it wants to read the vendor id before it resets
3822 * the codec manually.
3823 */
3824 ichac97R3MixerReset(pThis);
3825
3826 /*
3827 * Reset all streams.
3828 */
3829 for (unsigned i = 0; i < AC97_MAX_STREAMS; i++)
3830 {
3831 ichac97R3StreamEnable(pThis, &pThis->aStreams[i], false /* fEnable */);
3832 ichac97R3StreamReset(pThis, &pThis->aStreams[i]);
3833 }
3834
3835 /*
3836 * Reset mixer sinks.
3837 *
3838 * Do the reset here instead of in ichac97R3StreamReset();
3839 * the mixer sink(s) might still have data to be processed when an audio stream gets reset.
3840 */
3841 AudioMixerSinkReset(pThis->pSinkLineIn);
3842 AudioMixerSinkReset(pThis->pSinkMicIn);
3843 AudioMixerSinkReset(pThis->pSinkOut);
3844}
3845
3846
3847/**
3848 * Attach command, internal version.
3849 *
3850 * This is called to let the device attach to a driver for a specified LUN
3851 * during runtime. This is not called during VM construction, the device
3852 * constructor has to attach to all the available drivers.
3853 *
3854 * @returns VBox status code.
3855 * @param pThis AC'97 state.
3856 * @param uLUN The logical unit which is being attached.
3857 * @param fFlags Flags, combination of the PDMDEVATT_FLAGS_* \#defines.
3858 * @param ppDrv Attached driver instance on success. Optional.
3859 */
3860static int ichac97R3AttachInternal(PAC97STATE pThis, unsigned uLUN, uint32_t fFlags, PAC97DRIVER *ppDrv)
3861{
3862 RT_NOREF(fFlags);
3863
3864 /*
3865 * Attach driver.
3866 */
3867 char *pszDesc;
3868 if (RTStrAPrintf(&pszDesc, "Audio driver port (AC'97) for LUN #%u", uLUN) <= 0)
3869 AssertLogRelFailedReturn(VERR_NO_MEMORY);
3870
3871 PPDMIBASE pDrvBase;
3872 int rc = PDMDevHlpDriverAttach(pThis->pDevInsR3, uLUN,
3873 &pThis->IBase, &pDrvBase, pszDesc);
3874 if (RT_SUCCESS(rc))
3875 {
3876 PAC97DRIVER pDrv = (PAC97DRIVER)RTMemAllocZ(sizeof(AC97DRIVER));
3877 if (pDrv)
3878 {
3879 pDrv->pDrvBase = pDrvBase;
3880 pDrv->pConnector = PDMIBASE_QUERY_INTERFACE(pDrvBase, PDMIAUDIOCONNECTOR);
3881 AssertMsg(pDrv->pConnector != NULL, ("Configuration error: LUN #%u has no host audio interface, rc=%Rrc\n", uLUN, rc));
3882 pDrv->pAC97State = pThis;
3883 pDrv->uLUN = uLUN;
3884
3885 /*
3886 * For now we always set the driver at LUN 0 as our primary
3887 * host backend. This might change in the future.
3888 */
3889 if (pDrv->uLUN == 0)
3890 pDrv->fFlags |= PDMAUDIODRVFLAGS_PRIMARY;
3891
3892 LogFunc(("LUN#%RU8: pCon=%p, drvFlags=0x%x\n", uLUN, pDrv->pConnector, pDrv->fFlags));
3893
3894 /* Attach to driver list if not attached yet. */
3895 if (!pDrv->fAttached)
3896 {
3897 RTListAppend(&pThis->lstDrv, &pDrv->Node);
3898 pDrv->fAttached = true;
3899 }
3900
3901 if (ppDrv)
3902 *ppDrv = pDrv;
3903 }
3904 else
3905 rc = VERR_NO_MEMORY;
3906 }
3907 else if (rc == VERR_PDM_NO_ATTACHED_DRIVER)
3908 LogFunc(("No attached driver for LUN #%u\n", uLUN));
3909
3910 if (RT_FAILURE(rc))
3911 {
3912 /* Only free this string on failure;
3913 * must remain valid for the live of the driver instance. */
3914 RTStrFree(pszDesc);
3915 }
3916
3917 LogFunc(("uLUN=%u, fFlags=0x%x, rc=%Rrc\n", uLUN, fFlags, rc));
3918 return rc;
3919}
3920
3921/**
3922 * Detach command, internal version.
3923 *
3924 * This is called to let the device detach from a driver for a specified LUN
3925 * during runtime.
3926 *
3927 * @returns VBox status code.
3928 * @param pThis AC'97 state.
3929 * @param pDrv Driver to detach from device.
3930 * @param fFlags Flags, combination of the PDMDEVATT_FLAGS_* \#defines.
3931 */
3932static int ichac97R3DetachInternal(PAC97STATE pThis, PAC97DRIVER pDrv, uint32_t fFlags)
3933{
3934 RT_NOREF(fFlags);
3935
3936 /* First, remove the driver from our list and destory it's associated streams.
3937 * This also will un-set the driver as a recording source (if associated). */
3938 ichac97R3MixerRemoveDrv(pThis, pDrv);
3939
3940 /* Next, search backwards for a capable (attached) driver which now will be the
3941 * new recording source. */
3942 PDMAUDIODESTSOURCE dstSrc;
3943 PAC97DRIVER pDrvCur;
3944 RTListForEachReverse(&pThis->lstDrv, pDrvCur, AC97DRIVER, Node)
3945 {
3946 if (!pDrvCur->pConnector)
3947 continue;
3948
3949 PDMAUDIOBACKENDCFG Cfg;
3950 int rc2 = pDrvCur->pConnector->pfnGetConfig(pDrvCur->pConnector, &Cfg);
3951 if (RT_FAILURE(rc2))
3952 continue;
3953
3954 dstSrc.Source = PDMAUDIORECSOURCE_MIC;
3955 PAC97DRIVERSTREAM pDrvStrm = ichac97R3MixerGetDrvStream(pThis, pDrvCur, PDMAUDIODIR_IN, dstSrc);
3956 if ( pDrvStrm
3957 && pDrvStrm->pMixStrm)
3958 {
3959 rc2 = AudioMixerSinkSetRecordingSource(pThis->pSinkMicIn, pDrvStrm->pMixStrm);
3960 if (RT_SUCCESS(rc2))
3961 LogRel2(("AC97: Set new recording source for 'Mic In' to '%s'\n", Cfg.szName));
3962 }
3963
3964 dstSrc.Source = PDMAUDIORECSOURCE_LINE;
3965 pDrvStrm = ichac97R3MixerGetDrvStream(pThis, pDrvCur, PDMAUDIODIR_IN, dstSrc);
3966 if ( pDrvStrm
3967 && pDrvStrm->pMixStrm)
3968 {
3969 rc2 = AudioMixerSinkSetRecordingSource(pThis->pSinkLineIn, pDrvStrm->pMixStrm);
3970 if (RT_SUCCESS(rc2))
3971 LogRel2(("AC97: Set new recording source for 'Line In' to '%s'\n", Cfg.szName));
3972 }
3973 }
3974
3975 LogFunc(("uLUN=%u, fFlags=0x%x\n", pDrv->uLUN, fFlags));
3976 return VINF_SUCCESS;
3977}
3978
3979/**
3980 * @interface_method_impl{PDMDEVREG,pfnAttach}
3981 */
3982static DECLCALLBACK(int) ichac97R3Attach(PPDMDEVINS pDevIns, unsigned uLUN, uint32_t fFlags)
3983{
3984 PAC97STATE pThis = PDMINS_2_DATA(pDevIns, PAC97STATE);
3985
3986 LogFunc(("uLUN=%u, fFlags=0x%x\n", uLUN, fFlags));
3987
3988 DEVAC97_LOCK(pThis);
3989
3990 PAC97DRIVER pDrv;
3991 int rc2 = ichac97R3AttachInternal(pThis, uLUN, fFlags, &pDrv);
3992 if (RT_SUCCESS(rc2))
3993 rc2 = ichac97R3MixerAddDrv(pThis, pDrv);
3994
3995 if (RT_FAILURE(rc2))
3996 LogFunc(("Failed with %Rrc\n", rc2));
3997
3998 DEVAC97_UNLOCK(pThis);
3999
4000 return VINF_SUCCESS;
4001}
4002
4003/**
4004 * @interface_method_impl{PDMDEVREG,pfnDetach}
4005 */
4006static DECLCALLBACK(void) ichac97R3Detach(PPDMDEVINS pDevIns, unsigned uLUN, uint32_t fFlags)
4007{
4008 PAC97STATE pThis = PDMINS_2_DATA(pDevIns, PAC97STATE);
4009
4010 LogFunc(("uLUN=%u, fFlags=0x%x\n", uLUN, fFlags));
4011
4012 DEVAC97_LOCK(pThis);
4013
4014 PAC97DRIVER pDrv, pDrvNext;
4015 RTListForEachSafe(&pThis->lstDrv, pDrv, pDrvNext, AC97DRIVER, Node)
4016 {
4017 if (pDrv->uLUN == uLUN)
4018 {
4019 int rc2 = ichac97R3DetachInternal(pThis, pDrv, fFlags);
4020 if (RT_SUCCESS(rc2))
4021 {
4022 RTMemFree(pDrv);
4023 pDrv = NULL;
4024 }
4025
4026 break;
4027 }
4028 }
4029
4030 DEVAC97_UNLOCK(pThis);
4031}
4032
4033/**
4034 * Re-attaches (replaces) a driver with a new driver.
4035 *
4036 * @returns VBox status code.
4037 * @param pThis Device instance.
4038 * @param pDrv Driver instance used for attaching to.
4039 * If NULL is specified, a new driver will be created and appended
4040 * to the driver list.
4041 * @param uLUN The logical unit which is being re-detached.
4042 * @param pszDriver New driver name to attach.
4043 */
4044static int ichac97R3ReattachInternal(PAC97STATE pThis, PAC97DRIVER pDrv, uint8_t uLUN, const char *pszDriver)
4045{
4046 AssertPtrReturn(pThis, VERR_INVALID_POINTER);
4047 AssertPtrReturn(pszDriver, VERR_INVALID_POINTER);
4048
4049 int rc;
4050
4051 if (pDrv)
4052 {
4053 rc = ichac97R3DetachInternal(pThis, pDrv, 0 /* fFlags */);
4054 if (RT_SUCCESS(rc))
4055 rc = PDMDevHlpDriverDetach(pThis->pDevInsR3, PDMIBASE_2_PDMDRV(pDrv->pDrvBase), 0 /* fFlags */);
4056
4057 if (RT_FAILURE(rc))
4058 return rc;
4059
4060 pDrv = NULL;
4061 }
4062
4063 PVM pVM = PDMDevHlpGetVM(pThis->pDevInsR3);
4064 PCFGMNODE pRoot = CFGMR3GetRoot(pVM);
4065 PCFGMNODE pDev0 = CFGMR3GetChild(pRoot, "Devices/ichac97/0/");
4066
4067 /* Remove LUN branch. */
4068 CFGMR3RemoveNode(CFGMR3GetChildF(pDev0, "LUN#%u/", uLUN));
4069
4070# define RC_CHECK() if (RT_FAILURE(rc)) { AssertReleaseRC(rc); break; }
4071
4072 do
4073 {
4074 PCFGMNODE pLunL0;
4075 rc = CFGMR3InsertNodeF(pDev0, &pLunL0, "LUN#%u/", uLUN); RC_CHECK();
4076 rc = CFGMR3InsertString(pLunL0, "Driver", "AUDIO"); RC_CHECK();
4077 rc = CFGMR3InsertNode(pLunL0, "Config/", NULL); RC_CHECK();
4078
4079 PCFGMNODE pLunL1, pLunL2;
4080 rc = CFGMR3InsertNode (pLunL0, "AttachedDriver/", &pLunL1); RC_CHECK();
4081 rc = CFGMR3InsertNode (pLunL1, "Config/", &pLunL2); RC_CHECK();
4082 rc = CFGMR3InsertString(pLunL1, "Driver", pszDriver); RC_CHECK();
4083
4084 rc = CFGMR3InsertString(pLunL2, "AudioDriver", pszDriver); RC_CHECK();
4085
4086 } while (0);
4087
4088 if (RT_SUCCESS(rc))
4089 rc = ichac97R3AttachInternal(pThis, uLUN, 0 /* fFlags */, NULL /* ppDrv */);
4090
4091 LogFunc(("pThis=%p, uLUN=%u, pszDriver=%s, rc=%Rrc\n", pThis, uLUN, pszDriver, rc));
4092
4093# undef RC_CHECK
4094
4095 return rc;
4096}
4097
4098/**
4099 * @interface_method_impl{PDMDEVREG,pfnRelocate}
4100 */
4101static DECLCALLBACK(void) ichac97R3Relocate(PPDMDEVINS pDevIns, RTGCINTPTR offDelta)
4102{
4103 NOREF(offDelta);
4104 PAC97STATE pThis = PDMINS_2_DATA(pDevIns, PAC97STATE);
4105 pThis->pDevInsRC = PDMDEVINS_2_RCPTR(pDevIns);
4106
4107 for (unsigned i = 0; i < AC97_MAX_STREAMS; i++)
4108 pThis->pTimerRC[i] = TMTimerRCPtr(pThis->pTimerR3[i]);
4109}
4110
4111/**
4112 * @interface_method_impl{PDMDEVREG,pfnDestruct}
4113 */
4114static DECLCALLBACK(int) ichac97R3Destruct(PPDMDEVINS pDevIns)
4115{
4116 PDMDEV_CHECK_VERSIONS_RETURN_QUIET(pDevIns); /* this shall come first */
4117 PAC97STATE pThis = PDMINS_2_DATA(pDevIns, PAC97STATE);
4118
4119 LogFlowFuncEnter();
4120
4121 PAC97DRIVER pDrv, pDrvNext;
4122 RTListForEachSafe(&pThis->lstDrv, pDrv, pDrvNext, AC97DRIVER, Node)
4123 {
4124 RTListNodeRemove(&pDrv->Node);
4125 RTMemFree(pDrv);
4126 }
4127
4128 /* Sanity. */
4129 Assert(RTListIsEmpty(&pThis->lstDrv));
4130
4131 return VINF_SUCCESS;
4132}
4133
4134/**
4135 * @interface_method_impl{PDMDEVREG,pfnConstruct}
4136 */
4137static DECLCALLBACK(int) ichac97R3Construct(PPDMDEVINS pDevIns, int iInstance, PCFGMNODE pCfg)
4138{
4139 PDMDEV_CHECK_VERSIONS_RETURN(pDevIns); /* this shall come first */
4140 PAC97STATE pThis = PDMINS_2_DATA(pDevIns, PAC97STATE);
4141 Assert(iInstance == 0); RT_NOREF(iInstance);
4142
4143 /*
4144 * Initialize data so we can run the destructor without scewing up.
4145 */
4146 pThis->pDevInsR3 = pDevIns;
4147 pThis->pDevInsR0 = PDMDEVINS_2_R0PTR(pDevIns);
4148 pThis->pDevInsRC = PDMDEVINS_2_RCPTR(pDevIns);
4149 pThis->IBase.pfnQueryInterface = ichac97R3QueryInterface;
4150 RTListInit(&pThis->lstDrv);
4151
4152 /*
4153 * Validations.
4154 */
4155 if (!CFGMR3AreValuesValid(pCfg, "RZEnabled\0"
4156 "Codec\0"
4157 "TimerHz\0"
4158 "DebugEnabled\0"
4159 "DebugPathOut\0"))
4160 return PDMDEV_SET_ERROR(pDevIns, VERR_PDM_DEVINS_UNKNOWN_CFG_VALUES,
4161 N_("Invalid configuration for the AC'97 device"));
4162
4163 /*
4164 * Read config data.
4165 */
4166 int rc = CFGMR3QueryBoolDef(pCfg, "RZEnabled", &pThis->fRZEnabled, true);
4167 if (RT_FAILURE(rc))
4168 return PDMDEV_SET_ERROR(pDevIns, rc,
4169 N_("AC'97 configuration error: failed to read RCEnabled as boolean"));
4170
4171 char szCodec[20];
4172 rc = CFGMR3QueryStringDef(pCfg, "Codec", &szCodec[0], sizeof(szCodec), "STAC9700");
4173 if (RT_FAILURE(rc))
4174 return PDMDEV_SET_ERROR(pDevIns, VERR_PDM_DEVINS_UNKNOWN_CFG_VALUES,
4175 N_("AC'97 configuration error: Querying \"Codec\" as string failed"));
4176
4177 rc = CFGMR3QueryU16Def(pCfg, "TimerHz", &pThis->uTimerHz, AC97_TIMER_HZ_DEFAULT /* Default value, if not set. */);
4178 if (RT_FAILURE(rc))
4179 return PDMDEV_SET_ERROR(pDevIns, rc,
4180 N_("AC'97 configuration error: failed to read Hertz (Hz) rate as unsigned integer"));
4181
4182 if (pThis->uTimerHz != AC97_TIMER_HZ_DEFAULT)
4183 LogRel(("AC97: Using custom device timer rate (%RU16Hz)\n", pThis->uTimerHz));
4184
4185 rc = CFGMR3QueryBoolDef(pCfg, "DebugEnabled", &pThis->Dbg.fEnabled, false);
4186 if (RT_FAILURE(rc))
4187 return PDMDEV_SET_ERROR(pDevIns, rc,
4188 N_("AC97 configuration error: failed to read debugging enabled flag as boolean"));
4189
4190 rc = CFGMR3QueryStringDef(pCfg, "DebugPathOut", pThis->Dbg.szOutPath, sizeof(pThis->Dbg.szOutPath),
4191 VBOX_AUDIO_DEBUG_DUMP_PCM_DATA_PATH);
4192 if (RT_FAILURE(rc))
4193 return PDMDEV_SET_ERROR(pDevIns, rc,
4194 N_("AC97 configuration error: failed to read debugging output path flag as string"));
4195
4196 if (!strlen(pThis->Dbg.szOutPath))
4197 RTStrPrintf(pThis->Dbg.szOutPath, sizeof(pThis->Dbg.szOutPath), VBOX_AUDIO_DEBUG_DUMP_PCM_DATA_PATH);
4198
4199 if (pThis->Dbg.fEnabled)
4200 LogRel2(("AC97: Debug output will be saved to '%s'\n", pThis->Dbg.szOutPath));
4201
4202 /*
4203 * The AD1980 codec (with corresponding PCI subsystem vendor ID) is whitelisted
4204 * in the Linux kernel; Linux makes no attempt to measure the data rate and assumes
4205 * 48 kHz rate, which is exactly what we need. Same goes for AD1981B.
4206 */
4207 if (!strcmp(szCodec, "STAC9700"))
4208 pThis->uCodecModel = AC97_CODEC_STAC9700;
4209 else if (!strcmp(szCodec, "AD1980"))
4210 pThis->uCodecModel = AC97_CODEC_AD1980;
4211 else if (!strcmp(szCodec, "AD1981B"))
4212 pThis->uCodecModel = AC97_CODEC_AD1981B;
4213 else
4214 return PDMDevHlpVMSetError(pDevIns, VERR_PDM_DEVINS_UNKNOWN_CFG_VALUES, RT_SRC_POS,
4215 N_("AC'97 configuration error: The \"Codec\" value \"%s\" is unsupported"), szCodec);
4216
4217 /*
4218 * Use an own critical section for the device instead of the default
4219 * one provided by PDM. This allows fine-grained locking in combination
4220 * with TM when timer-specific stuff is being called in e.g. the MMIO handlers.
4221 */
4222 rc = PDMDevHlpCritSectInit(pDevIns, &pThis->CritSect, RT_SRC_POS, "AC'97");
4223 AssertRCReturn(rc, rc);
4224
4225 rc = PDMDevHlpSetDeviceCritSect(pDevIns, PDMDevHlpCritSectGetNop(pDevIns));
4226 AssertRCReturn(rc, rc);
4227
4228 /*
4229 * Initialize data (most of it anyway).
4230 */
4231 /* PCI Device */
4232 PCIDevSetVendorId (&pThis->PciDev, 0x8086); /* 00 ro - intel. */ Assert(pThis->PciDev.abConfig[0x00] == 0x86); Assert(pThis->PciDev.abConfig[0x01] == 0x80);
4233 PCIDevSetDeviceId (&pThis->PciDev, 0x2415); /* 02 ro - 82801 / 82801aa(?). */ Assert(pThis->PciDev.abConfig[0x02] == 0x15); Assert(pThis->PciDev.abConfig[0x03] == 0x24);
4234 PCIDevSetCommand (&pThis->PciDev, 0x0000); /* 04 rw,ro - pcicmd. */ Assert(pThis->PciDev.abConfig[0x04] == 0x00); Assert(pThis->PciDev.abConfig[0x05] == 0x00);
4235 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);
4236 PCIDevSetRevisionId (&pThis->PciDev, 0x01); /* 08 ro - rid. */ Assert(pThis->PciDev.abConfig[0x08] == 0x01);
4237 PCIDevSetClassProg (&pThis->PciDev, 0x00); /* 09 ro - pi. */ Assert(pThis->PciDev.abConfig[0x09] == 0x00);
4238 PCIDevSetClassSub (&pThis->PciDev, 0x01); /* 0a ro - scc; 01 == Audio. */ Assert(pThis->PciDev.abConfig[0x0a] == 0x01);
4239 PCIDevSetClassBase (&pThis->PciDev, 0x04); /* 0b ro - bcc; 04 == multimedia.*/Assert(pThis->PciDev.abConfig[0x0b] == 0x04);
4240 PCIDevSetHeaderType (&pThis->PciDev, 0x00); /* 0e ro - headtyp. */ Assert(pThis->PciDev.abConfig[0x0e] == 0x00);
4241 PCIDevSetBaseAddress (&pThis->PciDev, 0, /* 10 rw - nambar - native audio mixer base. */
4242 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);
4243 PCIDevSetBaseAddress (&pThis->PciDev, 1, /* 14 rw - nabmbar - native audio bus mastering. */
4244 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);
4245 PCIDevSetInterruptLine(&pThis->PciDev, 0x00); /* 3c rw. */ Assert(pThis->PciDev.abConfig[0x3c] == 0x00);
4246 PCIDevSetInterruptPin (&pThis->PciDev, 0x01); /* 3d ro - INTA#. */ Assert(pThis->PciDev.abConfig[0x3d] == 0x01);
4247
4248 if (pThis->uCodecModel == AC97_CODEC_AD1980)
4249 {
4250 PCIDevSetSubSystemVendorId(&pThis->PciDev, 0x1028); /* 2c ro - Dell.) */
4251 PCIDevSetSubSystemId (&pThis->PciDev, 0x0177); /* 2e ro. */
4252 }
4253 else if (pThis->uCodecModel == AC97_CODEC_AD1981B)
4254 {
4255 PCIDevSetSubSystemVendorId(&pThis->PciDev, 0x1028); /* 2c ro - Dell.) */
4256 PCIDevSetSubSystemId (&pThis->PciDev, 0x01ad); /* 2e ro. */
4257 }
4258 else
4259 {
4260 PCIDevSetSubSystemVendorId(&pThis->PciDev, 0x8086); /* 2c ro - Intel.) */
4261 PCIDevSetSubSystemId (&pThis->PciDev, 0x0000); /* 2e ro. */
4262 }
4263
4264 /*
4265 * Register the PCI device, it's I/O regions, the timer and the
4266 * saved state item.
4267 */
4268 rc = PDMDevHlpPCIRegister(pDevIns, &pThis->PciDev);
4269 if (RT_FAILURE(rc))
4270 return rc;
4271
4272 rc = PDMDevHlpPCIIORegionRegister(pDevIns, 0, 256, PCI_ADDRESS_SPACE_IO, ichac97R3IOPortMap);
4273 if (RT_FAILURE(rc))
4274 return rc;
4275
4276 rc = PDMDevHlpPCIIORegionRegister(pDevIns, 1, 64, PCI_ADDRESS_SPACE_IO, ichac97R3IOPortMap);
4277 if (RT_FAILURE(rc))
4278 return rc;
4279
4280 rc = PDMDevHlpSSMRegister(pDevIns, AC97_SSM_VERSION, sizeof(*pThis), ichac97R3SaveExec, ichac97R3LoadExec);
4281 if (RT_FAILURE(rc))
4282 return rc;
4283
4284# ifdef VBOX_WITH_AUDIO_AC97_ASYNC_IO
4285 LogRel(("AC97: Asynchronous I/O enabled\n"));
4286# endif
4287
4288 /*
4289 * Attach driver.
4290 */
4291 uint8_t uLUN;
4292 for (uLUN = 0; uLUN < UINT8_MAX; ++uLUN)
4293 {
4294 LogFunc(("Trying to attach driver for LUN #%RU8 ...\n", uLUN));
4295 rc = ichac97R3AttachInternal(pThis, uLUN, 0 /* fFlags */, NULL /* ppDrv */);
4296 if (RT_FAILURE(rc))
4297 {
4298 if (rc == VERR_PDM_NO_ATTACHED_DRIVER)
4299 rc = VINF_SUCCESS;
4300 else if (rc == VERR_AUDIO_BACKEND_INIT_FAILED)
4301 {
4302 ichac97R3ReattachInternal(pThis, NULL /* pDrv */, uLUN, "NullAudio");
4303 PDMDevHlpVMSetRuntimeError(pDevIns, 0 /*fFlags*/, "HostAudioNotResponding",
4304 N_("Host audio backend initialization has failed. Selecting the NULL audio backend "
4305 "with the consequence that no sound is audible"));
4306 /* Attaching to the NULL audio backend will never fail. */
4307 rc = VINF_SUCCESS;
4308 }
4309 break;
4310 }
4311 }
4312
4313 LogFunc(("cLUNs=%RU8, rc=%Rrc\n", uLUN, rc));
4314
4315 if (RT_SUCCESS(rc))
4316 {
4317 rc = AudioMixerCreate("AC'97 Mixer", 0 /* uFlags */, &pThis->pMixer);
4318 if (RT_SUCCESS(rc))
4319 {
4320 rc = AudioMixerCreateSink(pThis->pMixer, "[Recording] Line In", AUDMIXSINKDIR_INPUT, &pThis->pSinkLineIn);
4321 AssertRC(rc);
4322 rc = AudioMixerCreateSink(pThis->pMixer, "[Recording] Microphone In", AUDMIXSINKDIR_INPUT, &pThis->pSinkMicIn);
4323 AssertRC(rc);
4324 rc = AudioMixerCreateSink(pThis->pMixer, "[Playback] PCM Output", AUDMIXSINKDIR_OUTPUT, &pThis->pSinkOut);
4325 AssertRC(rc);
4326 }
4327 }
4328
4329 if (RT_SUCCESS(rc))
4330 {
4331 /*
4332 * Create all hardware streams.
4333 */
4334 for (unsigned i = 0; i < AC97_MAX_STREAMS; i++)
4335 {
4336 int rc2 = ichac97R3StreamCreate(pThis, &pThis->aStreams[i], i /* SD# */);
4337 AssertRC(rc2);
4338 if (RT_SUCCESS(rc))
4339 rc = rc2;
4340 }
4341
4342# ifdef VBOX_WITH_AUDIO_AC97_ONETIME_INIT
4343 PAC97DRIVER pDrv;
4344 RTListForEach(&pThis->lstDrv, pDrv, AC97DRIVER, Node)
4345 {
4346 /*
4347 * Only primary drivers are critical for the VM to run. Everything else
4348 * might not worth showing an own error message box in the GUI.
4349 */
4350 if (!(pDrv->fFlags & PDMAUDIODRVFLAGS_PRIMARY))
4351 continue;
4352
4353 PPDMIAUDIOCONNECTOR pCon = pDrv->pConnector;
4354 AssertPtr(pCon);
4355
4356 bool fValidLineIn = AudioMixerStreamIsValid(pDrv->LineIn.pMixStrm);
4357 bool fValidMicIn = AudioMixerStreamIsValid(pDrv->MicIn.pMixStrm);
4358 bool fValidOut = AudioMixerStreamIsValid(pDrv->Out.pMixStrm);
4359
4360 if ( !fValidLineIn
4361 && !fValidMicIn
4362 && !fValidOut)
4363 {
4364 LogRel(("AC97: Falling back to NULL backend (no sound audible)\n"));
4365
4366 ichac97R3Reset(pDevIns);
4367 ichac97R3ReattachInternal(pThis, pDrv, pDrv->uLUN, "NullAudio");
4368
4369 PDMDevHlpVMSetRuntimeError(pDevIns, 0 /*fFlags*/, "HostAudioNotResponding",
4370 N_("No audio devices could be opened. Selecting the NULL audio backend "
4371 "with the consequence that no sound is audible"));
4372 }
4373 else
4374 {
4375 bool fWarn = false;
4376
4377 PDMAUDIOBACKENDCFG backendCfg;
4378 int rc2 = pCon->pfnGetConfig(pCon, &backendCfg);
4379 if (RT_SUCCESS(rc2))
4380 {
4381 if (backendCfg.cMaxStreamsIn)
4382 {
4383 /* If the audio backend supports two or more input streams at once,
4384 * warn if one of our two inputs (microphone-in and line-in) failed to initialize. */
4385 if (backendCfg.cMaxStreamsIn >= 2)
4386 fWarn = !fValidLineIn || !fValidMicIn;
4387 /* If the audio backend only supports one input stream at once (e.g. pure ALSA, and
4388 * *not* ALSA via PulseAudio plugin!), only warn if both of our inputs failed to initialize.
4389 * One of the two simply is not in use then. */
4390 else if (backendCfg.cMaxStreamsIn == 1)
4391 fWarn = !fValidLineIn && !fValidMicIn;
4392 /* Don't warn if our backend is not able of supporting any input streams at all. */
4393 }
4394
4395 if ( !fWarn
4396 && backendCfg.cMaxStreamsOut)
4397 {
4398 fWarn = !fValidOut;
4399 }
4400 }
4401 else
4402 {
4403 LogRel(("AC97: Unable to retrieve audio backend configuration for LUN #%RU8, rc=%Rrc\n", pDrv->uLUN, rc2));
4404 fWarn = true;
4405 }
4406
4407 if (fWarn)
4408 {
4409 char szMissingStreams[255] = "";
4410 size_t len = 0;
4411 if (!fValidLineIn)
4412 {
4413 LogRel(("AC97: WARNING: Unable to open PCM line input for LUN #%RU8!\n", pDrv->uLUN));
4414 len = RTStrPrintf(szMissingStreams, sizeof(szMissingStreams), "PCM Input");
4415 }
4416 if (!fValidMicIn)
4417 {
4418 LogRel(("AC97: WARNING: Unable to open PCM microphone input for LUN #%RU8!\n", pDrv->uLUN));
4419 len += RTStrPrintf(szMissingStreams + len,
4420 sizeof(szMissingStreams) - len, len ? ", PCM Microphone" : "PCM Microphone");
4421 }
4422 if (!fValidOut)
4423 {
4424 LogRel(("AC97: WARNING: Unable to open PCM output for LUN #%RU8!\n", pDrv->uLUN));
4425 len += RTStrPrintf(szMissingStreams + len,
4426 sizeof(szMissingStreams) - len, len ? ", PCM Output" : "PCM Output");
4427 }
4428
4429 PDMDevHlpVMSetRuntimeError(pDevIns, 0 /*fFlags*/, "HostAudioNotResponding",
4430 N_("Some AC'97 audio streams (%s) could not be opened. Guest applications generating audio "
4431 "output or depending on audio input may hang. Make sure your host audio device "
4432 "is working properly. Check the logfile for error messages of the audio "
4433 "subsystem"), szMissingStreams);
4434 }
4435 }
4436 }
4437# endif /* VBOX_WITH_AUDIO_AC97_ONETIME_INIT */
4438 }
4439
4440 if (RT_SUCCESS(rc))
4441 ichac97R3Reset(pDevIns);
4442
4443 if (RT_SUCCESS(rc))
4444 {
4445 for (unsigned i = 0; i < AC97_MAX_STREAMS; i++)
4446 {
4447 /* Create the emulation timer (per stream).
4448 *
4449 * Note: Use TMCLOCK_VIRTUAL_SYNC here, as the guest's AC'97 driver
4450 * relies on exact (virtual) DMA timing and uses DMA Position Buffers
4451 * instead of the LPIB registers.
4452 */
4453 char szTimer[16];
4454 RTStrPrintf2(szTimer, sizeof(szTimer), "AC97SD%i", i);
4455
4456 rc = PDMDevHlpTMTimerCreate(pDevIns, TMCLOCK_VIRTUAL_SYNC, ichac97R3Timer, &pThis->aStreams[i],
4457 TMTIMER_FLAGS_NO_CRIT_SECT, szTimer, &pThis->pTimerR3[i]);
4458 AssertRCReturn(rc, rc);
4459 pThis->pTimerR0[i] = TMTimerR0Ptr(pThis->pTimerR3[i]);
4460 pThis->pTimerRC[i] = TMTimerRCPtr(pThis->pTimerR3[i]);
4461
4462 /* Use our own critcal section for the device timer.
4463 * That way we can control more fine-grained when to lock what. */
4464 rc = TMR3TimerSetCritSect(pThis->pTimerR3[i], &pThis->CritSect);
4465 AssertRCReturn(rc, rc);
4466 }
4467 }
4468
4469# ifdef VBOX_WITH_STATISTICS
4470 if (RT_SUCCESS(rc))
4471 {
4472 /*
4473 * Register statistics.
4474 */
4475 PDMDevHlpSTAMRegister(pDevIns, &pThis->StatTimer, STAMTYPE_PROFILE, "/Devices/AC97/Timer", STAMUNIT_TICKS_PER_CALL, "Profiling ichac97Timer.");
4476 PDMDevHlpSTAMRegister(pDevIns, &pThis->StatIn, STAMTYPE_PROFILE, "/Devices/AC97/Input", STAMUNIT_TICKS_PER_CALL, "Profiling input.");
4477 PDMDevHlpSTAMRegister(pDevIns, &pThis->StatOut, STAMTYPE_PROFILE, "/Devices/AC97/Output", STAMUNIT_TICKS_PER_CALL, "Profiling output.");
4478 PDMDevHlpSTAMRegister(pDevIns, &pThis->StatBytesRead, STAMTYPE_COUNTER, "/Devices/AC97/BytesRead" , STAMUNIT_BYTES, "Bytes read from AC97 emulation.");
4479 PDMDevHlpSTAMRegister(pDevIns, &pThis->StatBytesWritten, STAMTYPE_COUNTER, "/Devices/AC97/BytesWritten", STAMUNIT_BYTES, "Bytes written to AC97 emulation.");
4480 }
4481# endif
4482
4483 LogFlowFuncLeaveRC(rc);
4484 return rc;
4485}
4486
4487/**
4488 * The device registration structure.
4489 */
4490const PDMDEVREG g_DeviceICHAC97 =
4491{
4492 /* u32Version */
4493 PDM_DEVREG_VERSION,
4494 /* szName */
4495 "ichac97",
4496 /* szRCMod */
4497 "VBoxDDRC.rc",
4498 /* szR0Mod */
4499 "VBoxDDR0.r0",
4500 /* pszDescription */
4501 "ICH AC'97 Audio Controller",
4502 /* fFlags */
4503 PDM_DEVREG_FLAGS_DEFAULT_BITS | PDM_DEVREG_FLAGS_RC | PDM_DEVREG_FLAGS_R0,
4504 /* fClass */
4505 PDM_DEVREG_CLASS_AUDIO,
4506 /* cMaxInstances */
4507 1,
4508 /* cbInstance */
4509 sizeof(AC97STATE),
4510 /* pfnConstruct */
4511 ichac97R3Construct,
4512 /* pfnDestruct */
4513 ichac97R3Destruct,
4514 /* pfnRelocate */
4515 ichac97R3Relocate,
4516 /* pfnMemSetup */
4517 NULL,
4518 /* pfnPowerOn */
4519 NULL,
4520 /* pfnReset */
4521 ichac97R3Reset,
4522 /* pfnSuspend */
4523 NULL,
4524 /* pfnResume */
4525 NULL,
4526 /* pfnAttach */
4527 ichac97R3Attach,
4528 /* pfnDetach */
4529 ichac97R3Detach,
4530 /* pfnQueryInterface. */
4531 NULL,
4532 /* pfnInitComplete */
4533 NULL,
4534 /* pfnPowerOff */
4535 ichac97R3PowerOff,
4536 /* pfnSoftReset */
4537 NULL,
4538 /* u32VersionEnd */
4539 PDM_DEVREG_VERSION
4540};
4541
4542#endif /* !IN_RING3 */
4543#endif /* !VBOX_DEVICE_STRUCT_TESTCASE */
4544
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