VirtualBox

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

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

Audio/AC97: Logging nit.

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