VirtualBox

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

Last change on this file since 65512 was 65150, checked in by vboxsync, 8 years ago

Renaming.

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 125.7 KB
Line 
1/* $Id: DevIchAc97.cpp 65150 2017-01-05 12:07:11Z vboxsync $ */
2/** @file
3 * DevIchAc97 - VBox ICH AC97 Audio Controller.
4 */
5
6/*
7 * Copyright (C) 2006-2016 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#ifdef DEBUG_andy
50/*
51 * AC97_DEBUG_DUMP_PCM_DATA enables dumping the raw PCM data
52 * to a file on the host. Be sure to adjust AC97_DEBUG_DUMP_PCM_DATA_PATH
53 * to your needs before using this!
54 */
55# define AC97_DEBUG_DUMP_PCM_DATA
56# ifdef RT_OS_WINDOWS
57# define AC97_DEBUG_DUMP_PCM_DATA_PATH "c:\\temp\\"
58# else
59# define AC97_DEBUG_DUMP_PCM_DATA_PATH "/tmp/"
60# endif
61#endif
62
63/** Current saved state version. */
64#define AC97_SSM_VERSION 1
65
66/** Default timer frequency (in Hz). */
67#define AC97_TIMER_HZ 100
68
69/** Maximum FIFO size (in bytes). */
70#define AC97_FIFO_MAX 256
71
72#define AC97_SR_FIFOE RT_BIT(4) /* rwc, FIFO error. */
73#define AC97_SR_BCIS RT_BIT(3) /* rwc, Buffer completion interrupt status. */
74#define AC97_SR_LVBCI RT_BIT(2) /* rwc, Last valid buffer completion interrupt. */
75#define AC97_SR_CELV RT_BIT(1) /* ro, Current equals last valid. */
76#define AC97_SR_DCH RT_BIT(0) /* ro, Controller halted. */
77#define AC97_SR_VALID_MASK (RT_BIT(5) - 1)
78#define AC97_SR_WCLEAR_MASK (AC97_SR_FIFOE | AC97_SR_BCIS | AC97_SR_LVBCI)
79#define AC97_SR_RO_MASK (AC97_SR_DCH | AC97_SR_CELV)
80#define AC97_SR_INT_MASK (AC97_SR_FIFOE | AC97_SR_BCIS | AC97_SR_LVBCI)
81
82#define AC97_CR_IOCE RT_BIT(4) /* rw, Interrupt On Completion Enable. */
83#define AC97_CR_FEIE RT_BIT(3) /* rw FIFO Error Interrupt Enable. */
84#define AC97_CR_LVBIE RT_BIT(2) /* rw Last Valid Buffer Interrupt Enable. */
85#define AC97_CR_RR RT_BIT(1) /* rw Reset Registers. */
86#define AC97_CR_RPBM RT_BIT(0) /* rw Run/Pause Bus Master. */
87#define AC97_CR_VALID_MASK (RT_BIT(5) - 1)
88#define AC97_CR_DONT_CLEAR_MASK (AC97_CR_IOCE | AC97_CR_FEIE | AC97_CR_LVBIE)
89
90#define AC97_GC_WR 4 /* rw Warm reset. */
91#define AC97_GC_CR 2 /* rw Cold reset. */
92#define AC97_GC_VALID_MASK (RT_BIT(6) - 1)
93
94#define AC97_GS_MD3 RT_BIT(17) /* rw */
95#define AC97_GS_AD3 RT_BIT(16) /* rw */
96#define AC97_GS_RCS RT_BIT(15) /* rwc */
97#define AC97_GS_B3S12 RT_BIT(14) /* ro */
98#define AC97_GS_B2S12 RT_BIT(13) /* ro */
99#define AC97_GS_B1S12 RT_BIT(12) /* ro */
100#define AC97_GS_S1R1 RT_BIT(11) /* rwc */
101#define AC97_GS_S0R1 RT_BIT(10) /* rwc */
102#define AC97_GS_S1CR RT_BIT(9) /* ro */
103#define AC97_GS_S0CR RT_BIT(8) /* ro */
104#define AC97_GS_MINT RT_BIT(7) /* ro */
105#define AC97_GS_POINT RT_BIT(6) /* ro */
106#define AC97_GS_PIINT RT_BIT(5) /* ro */
107#define AC97_GS_RSRVD (RT_BIT(4)|RT_BIT(3))
108#define AC97_GS_MOINT RT_BIT(2) /* ro */
109#define AC97_GS_MIINT RT_BIT(1) /* ro */
110#define AC97_GS_GSCI RT_BIT(0) /* rwc */
111#define AC97_GS_RO_MASK (AC97_GS_B3S12 | \
112 AC97_GS_B2S12 | \
113 AC97_GS_B1S12 | \
114 AC97_GS_S1CR | \
115 AC97_GS_S0CR | \
116 AC97_GS_MINT | \
117 AC97_GS_POINT | \
118 AC97_GS_PIINT | \
119 AC97_GS_RSRVD | \
120 AC97_GS_MOINT | \
121 AC97_GS_MIINT)
122#define AC97_GS_VALID_MASK (RT_BIT(18) - 1)
123#define AC97_GS_WCLEAR_MASK (AC97_GS_RCS|AC97_GS_S1R1|AC97_GS_S0R1|AC97_GS_GSCI)
124
125/** @name Buffer Descriptor (BD).
126 * @{ */
127#define AC97_BD_IOC RT_BIT(31) /**< Interrupt on Completion. */
128#define AC97_BD_BUP RT_BIT(30) /**< Buffer Underrun Policy. */
129
130#define AC97_BD_MAX_LEN_MASK 0xFFFE
131/** @} */
132
133/** @name Extended Audio Status and Control Register (EACS).
134 * @{ */
135#define AC97_EACS_VRA 1 /**< Variable Rate Audio (4.2.1.1). */
136#define AC97_EACS_VRM 8 /**< Variable Rate Mic Audio (4.2.1.1). */
137/** @} */
138
139/** @name Baseline Audio Register Set (BARS).
140 * @{ */
141#define AC97_BARS_VOL_MASK 0x1f /**< Volume mask for the Baseline Audio Register Set (5.7.2). */
142#define AC97_BARS_VOL_STEPS 31 /**< Volume steps for the Baseline Audio Register Set (5.7.2). */
143#define AC97_BARS_VOL_MUTE_SHIFT 15 /**< Mute bit shift for the Baseline Audio Register Set (5.7.2). */
144/** @} */
145
146/* AC'97 uses 1.5dB steps, we use 0.375dB steps: 1 AC'97 step equals 4 PDM steps. */
147#define AC97_DB_FACTOR 4
148
149#define AC97_REC_MASK 7
150enum
151{
152 AC97_REC_MIC = 0,
153 AC97_REC_CD,
154 AC97_REC_VIDEO,
155 AC97_REC_AUX,
156 AC97_REC_LINE_IN,
157 AC97_REC_STEREO_MIX,
158 AC97_REC_MONO_MIX,
159 AC97_REC_PHONE
160};
161
162enum
163{
164 AC97_Reset = 0x00,
165 AC97_Master_Volume_Mute = 0x02,
166 AC97_Headphone_Volume_Mute = 0x04, /** Also known as AUX, see table 16, section 5.7. */
167 AC97_Master_Volume_Mono_Mute = 0x06,
168 AC97_Master_Tone_RL = 0x08,
169 AC97_PC_BEEP_Volume_Mute = 0x0A,
170 AC97_Phone_Volume_Mute = 0x0C,
171 AC97_Mic_Volume_Mute = 0x0E,
172 AC97_Line_In_Volume_Mute = 0x10,
173 AC97_CD_Volume_Mute = 0x12,
174 AC97_Video_Volume_Mute = 0x14,
175 AC97_Aux_Volume_Mute = 0x16,
176 AC97_PCM_Out_Volume_Mute = 0x18,
177 AC97_Record_Select = 0x1A,
178 AC97_Record_Gain_Mute = 0x1C,
179 AC97_Record_Gain_Mic_Mute = 0x1E,
180 AC97_General_Purpose = 0x20,
181 AC97_3D_Control = 0x22,
182 AC97_AC_97_RESERVED = 0x24,
183 AC97_Powerdown_Ctrl_Stat = 0x26,
184 AC97_Extended_Audio_ID = 0x28,
185 AC97_Extended_Audio_Ctrl_Stat = 0x2A,
186 AC97_PCM_Front_DAC_Rate = 0x2C,
187 AC97_PCM_Surround_DAC_Rate = 0x2E,
188 AC97_PCM_LFE_DAC_Rate = 0x30,
189 AC97_PCM_LR_ADC_Rate = 0x32,
190 AC97_MIC_ADC_Rate = 0x34,
191 AC97_6Ch_Vol_C_LFE_Mute = 0x36,
192 AC97_6Ch_Vol_L_R_Surround_Mute = 0x38,
193 AC97_Vendor_Reserved = 0x58,
194 AC97_AD_Misc = 0x76,
195 AC97_Vendor_ID1 = 0x7c,
196 AC97_Vendor_ID2 = 0x7e
197};
198
199/* Codec models. */
200typedef enum
201{
202 AC97_CODEC_STAC9700 = 0, /* SigmaTel STAC9700 */
203 AC97_CODEC_AD1980, /* Analog Devices AD1980 */
204 AC97_CODEC_AD1981B /* Analog Devices AD1981B */
205} AC97CODEC;
206
207/* Analog Devices miscellaneous regiter bits used in AD1980. */
208#define AC97_AD_MISC_LOSEL RT_BIT(5) /* Surround (rear) goes to line out outputs. */
209#define AC97_AD_MISC_HPSEL RT_BIT(10) /* PCM (front) goes to headphone outputs. */
210
211#define ICHAC97STATE_2_DEVINS(a_pAC97) ((a_pAC97)->pDevInsR3)
212
213enum
214{
215 BUP_SET = RT_BIT(0),
216 BUP_LAST = RT_BIT(1)
217};
218
219/** Emits registers for a specific (Native Audio Bus Master BAR) NABMBAR. */
220#define AC97_NABMBAR_REGS(prefix, off) \
221 enum { \
222 prefix ## _BDBAR = off, /* Buffer Descriptor Base Address */ \
223 prefix ## _CIV = off + 4, /* Current Index Value */ \
224 prefix ## _LVI = off + 5, /* Last Valid Index */ \
225 prefix ## _SR = off + 6, /* Status Register */ \
226 prefix ## _PICB = off + 8, /* Position in Current Buffer */ \
227 prefix ## _PIV = off + 10, /* Prefetched Index Value */ \
228 prefix ## _CR = off + 11 /* Control Register */ \
229 }
230
231#ifndef VBOX_DEVICE_STRUCT_TESTCASE
232typedef enum
233{
234 AC97SOUNDSOURCE_PI_INDEX = 0, /** PCM in */
235 AC97SOUNDSOURCE_PO_INDEX, /** PCM out */
236 AC97SOUNDSOURCE_MC_INDEX, /** Mic in */
237 AC97SOUNDSOURCE_LAST_INDEX
238} AC97SOUNDSOURCE;
239
240AC97_NABMBAR_REGS(PI, AC97SOUNDSOURCE_PI_INDEX * 16);
241AC97_NABMBAR_REGS(PO, AC97SOUNDSOURCE_PO_INDEX * 16);
242AC97_NABMBAR_REGS(MC, AC97SOUNDSOURCE_MC_INDEX * 16);
243#endif
244
245enum
246{
247 /** NABMBAR: Global Control Register. */
248 AC97_GLOB_CNT = 0x2c,
249 /** NABMBAR Global Status. */
250 AC97_GLOB_STA = 0x30,
251 /** Codec Access Semaphore Register. */
252 AC97_CAS = 0x34
253};
254
255#define AC97_PORT2IDX(a_idx) ( ((a_idx) >> 4) & 3 )
256
257
258/*********************************************************************************************************************************
259* Structures and Typedefs *
260*********************************************************************************************************************************/
261
262/**
263 * Buffer Descriptor List Entry (BDLE).
264 */
265typedef struct AC97BDLE
266{
267 uint32_t addr;
268 uint32_t ctl_len;
269} AC97BDLE, *PAC97BDLE;
270
271/**
272 * Bus master register set for an audio stream.
273 */
274typedef struct AC97BMREGS
275{
276 uint32_t bdbar; /** rw 0, Buffer Descriptor List: BAR (Base Address Register). */
277 uint8_t civ; /** ro 0, Current index value. */
278 uint8_t lvi; /** rw 0, Last valid index. */
279 uint16_t sr; /** rw 1, Status register. */
280 uint16_t picb; /** ro 0, Position in current buffer (in samples). */
281 uint8_t piv; /** ro 0, Prefetched index value. */
282 uint8_t cr; /** rw 0, Control register. */
283 int bd_valid; /** Whether current BDLE is initialized or not. */
284 AC97BDLE bd; /** Current Buffer Descriptor List Entry (BDLE). */
285} AC97BMREGS, *PAC97BMREGS;
286
287#ifdef VBOX_WITH_AUDIO_AC97_ASYNC_IO
288/**
289 * Structure keeping the AC'97 stream's state for asynchronous I/O.
290 */
291typedef struct AC97STREAMSTATEAIO
292{
293 /** Thread handle for the actual I/O thread. */
294 RTTHREAD Thread;
295 /** Event for letting the thread know there is some data to process. */
296 RTSEMEVENT Event;
297 /** Critical section for synchronizing access. */
298 RTCRITSECT CritSect;
299 /** Started indicator. */
300 volatile bool fStarted;
301 /** Shutdown indicator. */
302 volatile bool fShutdown;
303 /** Whether the thread should do any data processing or not. */
304 volatile bool fEnabled;
305 uint32_t Padding1;
306} AC97STREAMSTATEAIO, *PAC97STREAMSTATEAIO;
307#endif
308
309/**
310 * Structure for keeping the internal state of an AC'97 stream.
311 */
312typedef struct AC97STREAMSTATE
313{
314 /** Circular buffer (FIFO) for holding DMA'ed data. */
315 R3PTRTYPE(PRTCIRCBUF) pCircBuf;
316 /** Criticial section for this stream. */
317 RTCRITSECT CritSect;
318#ifdef VBOX_WITH_AUDIO_AC97_ASYNC_IO
319 /** Asynchronous I/O state members. */
320 AC97STREAMSTATEAIO AIO;
321#endif
322} AC97STREAMSTATE, *PAC97STREAMSTATE;
323
324/**
325 * Structure for an AC'97 stream.
326 */
327typedef struct AC97STREAM
328{
329 /** Stream number (SDn). */
330 uint8_t u8SD;
331 /** Bus master registers of this stream. */
332 AC97BMREGS Regs;
333 /** Internal state of this stream. */
334 AC97STREAMSTATE State;
335} AC97STREAM, *PAC97STREAM;
336
337typedef struct AC97STATE *PAC97STATE;
338#ifdef VBOX_WITH_AUDIO_AC97_ASYNC_IO
339/**
340 * Structure for the async I/O thread context.
341 */
342typedef struct AC97STREAMTHREADCTX
343{
344 PAC97STATE pThis;
345 PAC97STREAM pStream;
346} AC97STREAMTHREADCTX, *PAC97STREAMTHREADCTX;
347#endif
348
349/**
350 * Structure defining a (host backend) driver stream.
351 * Each driver has its own instances of audio mixer streams, which then
352 * can go into the same (or even different) audio mixer sinks.
353 */
354typedef struct AC97DRIVERSTREAM
355{
356 union
357 {
358 /** Desired playback destination (for an output stream). */
359 PDMAUDIOPLAYBACKDEST Dest;
360 /** Desired recording source (for an input stream). */
361 PDMAUDIORECSOURCE Source;
362 } DestSource;
363 uint8_t Padding1[4];
364 /** Associated mixer stream handle. */
365 R3PTRTYPE(PAUDMIXSTREAM) pMixStrm;
366} AC97DRIVERSTREAM, *PAC97DRIVERSTREAM;
367
368/**
369 * Struct for maintaining a host backend driver.
370 */
371typedef struct AC97DRIVER
372{
373 /** Node for storing this driver in our device driver list of AC97STATE. */
374 RTLISTNODER3 Node;
375 /** Pointer to AC97 controller (state). */
376 R3PTRTYPE(PAC97STATE) pAC97State;
377 /** Driver flags. */
378 PDMAUDIODRVFLAGS Flags;
379 uint32_t PaddingFlags;
380 /** LUN # to which this driver has been assigned. */
381 uint8_t uLUN;
382 /** Whether this driver is in an attached state or not. */
383 bool fAttached;
384 uint8_t Padding[4];
385 /** Pointer to attached driver base interface. */
386 R3PTRTYPE(PPDMIBASE) pDrvBase;
387 /** Audio connector interface to the underlying host backend. */
388 R3PTRTYPE(PPDMIAUDIOCONNECTOR) pConnector;
389 /** Driver stream for line input. */
390 AC97DRIVERSTREAM LineIn;
391 /** Driver stream for mic input. */
392 AC97DRIVERSTREAM MicIn;
393 /** Driver stream for output. */
394 AC97DRIVERSTREAM Out;
395} AC97DRIVER, *PAC97DRIVER;
396
397/**
398 * Structure for maintaining an AC'97 device state.
399 */
400typedef struct AC97STATE
401{
402 /** The PCI device state. */
403 PDMPCIDEV PciDev;
404 /** R3 Pointer to the device instance. */
405 PPDMDEVINSR3 pDevInsR3;
406 /** Global Control (Bus Master Control Register). */
407 uint32_t glob_cnt;
408 /** Global Status (Bus Master Control Register). */
409 uint32_t glob_sta;
410 /** Codec Access Semaphore Register (Bus Master Control Register). */
411 uint32_t cas;
412 uint32_t last_samp;
413 uint8_t mixer_data[256];
414 /** AC'97 stream for line-in. */
415 AC97STREAM StreamLineIn;
416 /** AC'97 stream for microphone-in. */
417 AC97STREAM StreamMicIn;
418 /** AC'97 stream for output. */
419 AC97STREAM StreamOut;
420 /** Number of active (running) SDn streams. */
421 uint8_t cStreamsActive;
422#ifndef VBOX_WITH_AUDIO_AC97_CALLBACKS
423 /** The timer for pumping data thru the attached LUN drivers. */
424 PTMTIMERR3 pTimer;
425 /** Criticial section for timer. */
426 RTCRITSECT csTimer;
427# if HC_ARCH_BITS == 32
428 uint32_t Padding0;
429# endif
430 /** Flag indicating whether the timer is active or not. */
431 bool fTimerActive;
432 uint8_t u8Padding1[7];
433 /** The timer interval for pumping data thru the LUN drivers in timer ticks. */
434 uint64_t cTimerTicks;
435 /** Timestamp of the last timer callback (ac97Timer).
436 * Used to calculate the time actually elapsed between two timer callbacks. */
437 uint64_t uTimerTS;
438#endif
439#ifdef VBOX_WITH_STATISTICS
440 STAMPROFILE StatTimer;
441 STAMPROFILE StatIn;
442 STAMPROFILE StatOut;
443 STAMCOUNTER StatBytesRead;
444 STAMCOUNTER StatBytesWritten;
445#endif
446 /** List of associated LUN drivers (AC97DRIVER). */
447 RTLISTANCHOR lstDrv;
448 /** The device's software mixer. */
449 R3PTRTYPE(PAUDIOMIXER) pMixer;
450 /** Audio sink for PCM output. */
451 R3PTRTYPE(PAUDMIXSINK) pSinkOut;
452 /** Audio sink for line input. */
453 R3PTRTYPE(PAUDMIXSINK) pSinkLineIn;
454 /** Audio sink for microphone input. */
455 R3PTRTYPE(PAUDMIXSINK) pSinkMicIn;
456 uint8_t silence[128];
457 int bup_flag;
458 /** The base interface for LUN\#0. */
459 PDMIBASE IBase;
460 /** Base port of the I/O space region. */
461 RTIOPORT IOPortBase[2];
462 /** Codec model. */
463 uint32_t uCodecModel;
464} AC97STATE, *PAC97STATE;
465
466#ifdef VBOX_WITH_STATISTICS
467AssertCompileMemberAlignment(AC97STATE, StatTimer, 8);
468AssertCompileMemberAlignment(AC97STATE, StatBytesRead, 8);
469AssertCompileMemberAlignment(AC97STATE, StatBytesWritten, 8);
470#endif
471
472#ifndef VBOX_DEVICE_STRUCT_TESTCASE
473
474DECLINLINE(PAC97STREAM) ichac97GetStreamFromIdx(PAC97STATE pThis, uint32_t uIdx);
475static int ichac97StreamCreate(PAC97STATE pThis, PAC97STREAM pStream, uint8_t u8Strm);
476static void ichac97StreamDestroy(PAC97STATE pThis, PAC97STREAM pStream);
477static int ichac97StreamOpen(PAC97STATE pThis, PAC97STREAM pStream);
478static int ichac97StreamReOpen(PAC97STATE pThis, PAC97STREAM pStream);
479static int ichac97StreamClose(PAC97STATE pThis, PAC97STREAM pStream);
480static void ichac97StreamReset(PAC97STATE pThis, PAC97STREAM pStream);
481static void ichac97StreamLock(PAC97STREAM pStream);
482static void ichac97StreamUnlock(PAC97STREAM pStream);
483
484static DECLCALLBACK(void) ichac97Reset(PPDMDEVINS pDevIns);
485#ifndef VBOX_WITH_AUDIO_AC97_CALLBACKS
486static void ichac97TimerMaybeStart(PAC97STATE pThis);
487static void ichac97TimerMaybeStop(PAC97STATE pThis);
488static void ichac97TimerMain(PAC97STATE pThis);
489static DECLCALLBACK(void) ichac97Timer(PPDMDEVINS pDevIns, PTMTIMER pTimer, void *pvUser);
490#endif
491static int ichac97DoDMA(PAC97STATE pThis, PAC97STREAM pStream, void *pvBuf, uint32_t cbBuf, uint32_t cbToProcess, uint32_t *pcbProcessed);
492static void ichac97DoTransfers(PAC97STATE pThis);
493
494static int ichac97MixerAddDrvStreams(PAC97STATE pThis, PAUDMIXSINK pMixSink, PPDMAUDIOSTREAMCFG pCfg);
495static void ichac97MixerRemoveDrvStreams(PAC97STATE pThis, PAUDMIXSINK pMixSink, PDMAUDIODIR enmDir, PDMAUDIODESTSOURCE dstSrc);
496
497#ifdef VBOX_WITH_AUDIO_AC97_ASYNC_IO
498static DECLCALLBACK(int) ichac97StreamAsyncIOThread(RTTHREAD hThreadSelf, void *pvUser);
499static int ichac97StreamAsyncIOCreate(PAC97STATE pThis, PAC97STREAM pStream);
500static int ichac97StreamAsyncIODestroy(PAC97STATE pThis, PAC97STREAM pStream);
501static int ichac97StreamAsyncIONotify(PAC97STATE pThis, PAC97STREAM pStream);
502static void ichac97StreamAsyncIOLock(PAC97STREAM pStream);
503static void ichac97StreamAsyncIOUnlock(PAC97STREAM pStream);
504static void ichac97StreamAsyncIOEnable(PAC97STREAM pStream, bool fEnable);
505#endif
506
507static void ichac97WarmReset(PAC97STATE pThis)
508{
509 NOREF(pThis);
510}
511
512static void ichac97ColdReset(PAC97STATE pThis)
513{
514 NOREF(pThis);
515}
516
517/**
518 * Retrieves the audio mixer sink of a corresponding AC'97 stream index.
519 *
520 * @returns Pointer to audio mixer sink if found, or NULL if not found / invalid.
521 * @param pThis AC'97 state.
522 * @param uIndex Stream index to get audio mixer sink for.
523 */
524DECLINLINE(PAUDMIXSINK) ichac97IndexToSink(PAC97STATE pThis, uint8_t uIndex)
525{
526 AssertPtrReturn(pThis, NULL);
527
528 switch (uIndex)
529 {
530 case AC97SOUNDSOURCE_PI_INDEX: return pThis->pSinkLineIn; break;
531 case AC97SOUNDSOURCE_PO_INDEX: return pThis->pSinkOut; break;
532 case AC97SOUNDSOURCE_MC_INDEX: return pThis->pSinkMicIn; break;
533 default: break;
534 }
535
536 AssertMsgFailed(("Wrong index %RU8\n", uIndex));
537 return NULL;
538}
539
540/**
541 * Fetches the current BDLE (Buffer Descriptor List Entry) of an AC'97 audio stream.
542 *
543 * @returns IPRT status code.
544 * @param pThis AC'97 state.
545 * @param pStream AC'97 stream to fetch BDLE for.
546 *
547 * @remark Uses CIV as BDLE index.
548 */
549static void ichac97StreamFetchBDLE(PAC97STATE pThis, PAC97STREAM pStream)
550{
551 PPDMDEVINS pDevIns = ICHAC97STATE_2_DEVINS(pThis);
552 PAC97BMREGS pRegs = &pStream->Regs;
553
554 uint32_t u32[2];
555
556 PDMDevHlpPhysRead(pDevIns, pRegs->bdbar + pRegs->civ * 8, &u32[0], sizeof(u32));
557 pRegs->bd_valid = 1;
558#if !defined(RT_ARCH_X86) && !defined(RT_ARCH_AMD64)
559# error Please adapt the code (audio buffers are little endian)!
560#else
561 pRegs->bd.addr = RT_H2LE_U32(u32[0] & ~3);
562 pRegs->bd.ctl_len = RT_H2LE_U32(u32[1]);
563#endif
564 pRegs->picb = pRegs->bd.ctl_len & AC97_BD_MAX_LEN_MASK;
565 LogFlowFunc(("bd %2d addr=%#x ctl=%#06x len=%#x(%d bytes)\n",
566 pRegs->civ, pRegs->bd.addr, pRegs->bd.ctl_len >> 16,
567 pRegs->bd.ctl_len & AC97_BD_MAX_LEN_MASK,
568 (pRegs->bd.ctl_len & AC97_BD_MAX_LEN_MASK) << 1)); /** @todo r=andy Assumes 16bit samples. */
569}
570
571/**
572 * Updates the status register (SR) of an AC'97 audio stream.
573 *
574 * @param pThis AC'97 state.
575 * @param pStream AC'97 stream to update SR for.
576 * @param new_sr New value for status register (SR).
577 */
578static void ichac97StreamUpdateSR(PAC97STATE pThis, PAC97STREAM pStream, uint32_t new_sr)
579{
580 PPDMDEVINS pDevIns = ICHAC97STATE_2_DEVINS(pThis);
581 PAC97BMREGS pRegs = &pStream->Regs;
582
583 bool fSignal = false;
584 int iIRQL = 0;
585
586 uint32_t new_mask = new_sr & AC97_SR_INT_MASK;
587 uint32_t old_mask = pRegs->sr & AC97_SR_INT_MASK;
588
589 static uint32_t const masks[] = { AC97_GS_PIINT, AC97_GS_POINT, AC97_GS_MINT };
590
591 if (new_mask ^ old_mask)
592 {
593 /** @todo Is IRQ deasserted when only one of status bits is cleared? */
594 if (!new_mask)
595 {
596 fSignal = true;
597 iIRQL = 0;
598 }
599 else if ((new_mask & AC97_SR_LVBCI) && (pRegs->cr & AC97_CR_LVBIE))
600 {
601 fSignal = true;
602 iIRQL = 1;
603 }
604 else if ((new_mask & AC97_SR_BCIS) && (pRegs->cr & AC97_CR_IOCE))
605 {
606 fSignal = true;
607 iIRQL = 1;
608 }
609 }
610
611 pRegs->sr = new_sr;
612
613 LogFlowFunc(("IOC%d, LVB%d, sr=%#x, fSignal=%RTbool, IRQL=%d\n",
614 pRegs->sr & AC97_SR_BCIS, pRegs->sr & AC97_SR_LVBCI, pRegs->sr, fSignal, iIRQL));
615
616 if (fSignal)
617 {
618 if (iIRQL)
619 pThis->glob_sta |= masks[pStream->u8SD];
620 else
621 pThis->glob_sta &= ~masks[pStream->u8SD];
622
623 LogFlowFunc(("Setting IRQ level=%d\n", iIRQL));
624 PDMDevHlpPCISetIrq(pDevIns, 0, iIRQL);
625 }
626}
627
628/**
629 * Returns whether an AC'97 stream is enabled or not.
630 *
631 * @returns IPRT status code.
632 * @param pThis AC'97 device state.
633 * @param pStream Stream to return status for.
634 */
635static bool ichac97StreamIsEnabled(PAC97STATE pThis, PAC97STREAM pStream)
636{
637 AssertPtrReturn(pThis, false);
638 AssertPtrReturn(pStream, false);
639
640 PAUDMIXSINK pSink = ichac97IndexToSink(pThis, pStream->u8SD);
641 bool fIsEnabled = RT_BOOL(AudioMixerSinkGetStatus(pSink) & AUDMIXSINK_STS_RUNNING);
642
643 LogFunc(("[SD%RU8] fIsEnabled=%RTbool\n", pStream->u8SD, fIsEnabled));
644 return fIsEnabled;
645}
646
647/**
648 * Enables or disables an AC'97 audio stream.
649 *
650 * @returns IPRT status code.
651 * @param pThis AC'97 state.
652 * @param pStream AC'97 stream to enable or disable.
653 * @param fEnable Whether to enable or disble the stream.
654 *
655 */
656static int ichac97StreamEnable(PAC97STATE pThis, PAC97STREAM pStream, bool fEnable)
657{
658 AssertPtrReturn(pThis, VERR_INVALID_POINTER);
659 AssertPtrReturn(pStream, VERR_INVALID_POINTER);
660
661 ichac97StreamLock(pStream);
662
663 int rc = VINF_SUCCESS;
664
665#ifdef VBOX_WITH_AUDIO_AC97_ASYNC_IO
666 if (fEnable)
667 rc = ichac97StreamAsyncIOCreate(pThis, pStream);
668 if (RT_SUCCESS(rc))
669 {
670 ichac97StreamAsyncIOLock(pStream);
671 ichac97StreamAsyncIOEnable(pStream, fEnable);
672 }
673#endif
674
675 if (fEnable)
676 {
677 if (pStream->State.pCircBuf)
678 RTCircBufReset(pStream->State.pCircBuf);
679
680 rc = ichac97StreamOpen(pThis, pStream);
681 }
682 else
683 rc = ichac97StreamClose(pThis, pStream);
684
685 if (RT_SUCCESS(rc))
686 {
687 /* First, enable or disable the stream and the stream's sink, if any. */
688 rc = AudioMixerSinkCtl(ichac97IndexToSink(pThis, pStream->u8SD),
689 fEnable ? AUDMIXSINKCMD_ENABLE : AUDMIXSINKCMD_DISABLE);
690 }
691
692#ifdef VBOX_WITH_AUDIO_AC97_ASYNC_IO
693 ichac97StreamAsyncIOUnlock(pStream);
694#endif
695
696 /* Make sure to leave the lock before (eventually) starting the timer. */
697 ichac97StreamUnlock(pStream);
698
699#ifndef VBOX_WITH_AUDIO_AC97_CALLBACKS
700 /* Second, see if we need to start or stop the timer. */
701 if (!fEnable)
702 ichac97TimerMaybeStop(pThis);
703 else
704 ichac97TimerMaybeStart(pThis);
705#endif
706
707 LogFunc(("[SD%RU8]: cStreamsActive=%RU8, rc=%Rrc\n", pStream->u8SD, pThis->cStreamsActive, rc));
708 return rc;
709}
710
711/**
712 * Resets an AC'97 stream.
713 *
714 * @param pThis AC'97 state.
715 * @param pStream AC'97 stream to reset.
716 *
717 */
718static void ichac97StreamReset(PAC97STATE pThis, PAC97STREAM pStream)
719{
720 AssertPtrReturnVoid(pThis);
721 AssertPtrReturnVoid(pStream);
722
723 ichac97StreamLock(pStream);
724
725 LogFunc(("[SD%RU8]\n", pStream->u8SD));
726
727 AudioMixerSinkReset(ichac97IndexToSink(pThis, pStream->u8SD));
728
729 if (pStream->State.pCircBuf)
730 RTCircBufReset(pStream->State.pCircBuf);
731
732 PAC97BMREGS pRegs = &pStream->Regs;
733
734 pRegs->bdbar = 0;
735 pRegs->civ = 0;
736 pRegs->lvi = 0;
737
738 pRegs->picb = 0;
739 pRegs->piv = 0;
740 pRegs->cr = pRegs->cr & AC97_CR_DONT_CLEAR_MASK;
741 pRegs->bd_valid = 0;
742
743 RT_ZERO(pThis->silence);
744
745 ichac97StreamUnlock(pStream);
746}
747
748/**
749 * Creates an AC'97 audio stream.
750 *
751 * @returns IPRT status code.
752 * @param pThis AC'97 state.
753 * @param pStream AC'97 stream to create.
754 * @param u8Strm Stream ID to assign AC'97 stream to.
755 */
756static int ichac97StreamCreate(PAC97STATE pThis, PAC97STREAM pStream, uint8_t u8Strm)
757{
758 RT_NOREF(pThis);
759 AssertPtrReturn(pStream, VERR_INVALID_PARAMETER);
760 /** @todo Validate u8Strm. */
761
762 LogFunc(("[SD%RU8] pStream=%p\n", u8Strm, pStream));
763
764 pStream->u8SD = u8Strm;
765
766 int rc = RTCritSectInit(&pStream->State.CritSect);
767 if (RT_SUCCESS(rc))
768 rc = RTCircBufCreate(&pStream->State.pCircBuf, _4K); /** @todo Make this configurable. */
769
770 return rc;
771}
772
773/**
774 * Destroys an AC'97 audio stream.
775 *
776 * @returns IPRT status code.
777 * @param pThis AC'97 state.
778 * @param pStream AC'97 stream to destroy.
779 */
780static void ichac97StreamDestroy(PAC97STATE pThis, PAC97STREAM pStream)
781{
782 LogFlowFunc(("[SD%RU8]\n", pStream->u8SD));
783
784 int rc2 = RTCritSectDelete(&pStream->State.CritSect);
785 AssertRC(rc2);
786
787 if (pStream->State.pCircBuf)
788 {
789 RTCircBufDestroy(pStream->State.pCircBuf);
790 pStream->State.pCircBuf = NULL;
791 }
792
793#ifdef VBOX_WITH_AUDIO_AC97_ASYNC_IO
794 rc2 = ichac97StreamAsyncIODestroy(pThis, pStream);
795 AssertRC(rc2);
796#else
797 RT_NOREF(pThis);
798#endif
799
800 LogFlowFuncLeave();
801}
802
803/**
804 * Destroys all AC'97 audio streams of the device.
805 *
806 * @param pThis AC'97 state.
807 */
808static void ichac97StreamsDestroy(PAC97STATE pThis)
809{
810 LogFlowFuncEnter();
811
812 /*
813 * Destroy all AC'97 streams.
814 */
815
816 ichac97StreamDestroy(pThis, &pThis->StreamLineIn);
817 ichac97StreamDestroy(pThis, &pThis->StreamMicIn);
818 ichac97StreamDestroy(pThis, &pThis->StreamOut);
819
820 /*
821 * Destroy all sinks.
822 */
823
824 PDMAUDIODESTSOURCE dstSrc;
825 if (pThis->pSinkLineIn)
826 {
827 dstSrc.Source = PDMAUDIORECSOURCE_LINE;
828 ichac97MixerRemoveDrvStreams(pThis, pThis->pSinkLineIn, PDMAUDIODIR_IN, dstSrc);
829
830 AudioMixerSinkDestroy(pThis->pSinkLineIn);
831 pThis->pSinkLineIn = NULL;
832 }
833
834 if (pThis->pSinkMicIn)
835 {
836 dstSrc.Source = PDMAUDIORECSOURCE_MIC;
837 ichac97MixerRemoveDrvStreams(pThis, pThis->pSinkMicIn, PDMAUDIODIR_IN, dstSrc);
838
839 AudioMixerSinkDestroy(pThis->pSinkMicIn);
840 pThis->pSinkMicIn = NULL;
841 }
842
843 if (pThis->pSinkOut)
844 {
845 dstSrc.Dest = PDMAUDIOPLAYBACKDEST_FRONT;
846 ichac97MixerRemoveDrvStreams(pThis, pThis->pSinkOut, PDMAUDIODIR_OUT, dstSrc);
847
848 AudioMixerSinkDestroy(pThis->pSinkOut);
849 pThis->pSinkOut = NULL;
850 }
851}
852
853/**
854 * Writes audio data from a mixer sink into an AC'97 stream's DMA buffer.
855 *
856 * @returns IPRT status code.
857 * @param pThis AC'97 state.
858 * @param pDstStream AC'97 stream to write to.
859 * @param pSrcMixSink Mixer sink to get audio data to write from.
860 * @param cbToWrite Number of bytes to write.
861 * @param pcbWritten Number of bytes written. Optional.
862 */
863static int ichac97StreamWrite(PAC97STATE pThis, PAC97STREAM pDstStream, PAUDMIXSINK pSrcMixSink, uint32_t cbToWrite,
864 uint32_t *pcbWritten)
865{
866 RT_NOREF(pThis);
867 AssertPtrReturn(pDstStream, VERR_INVALID_POINTER);
868 AssertPtrReturn(pSrcMixSink, VERR_INVALID_POINTER);
869 AssertReturn(cbToWrite, VERR_INVALID_PARAMETER);
870 /* pcbWritten is optional. */
871
872 PRTCIRCBUF pCircBuf = pDstStream->State.pCircBuf;
873 AssertPtr(pCircBuf);
874
875 void *pvDst;
876 size_t cbDst;
877
878 uint32_t cbRead = 0;
879
880 RTCircBufAcquireWriteBlock(pCircBuf, cbToWrite, &pvDst, &cbDst);
881
882 if (cbDst)
883 {
884 int rc2 = AudioMixerSinkRead(pSrcMixSink, AUDMIXOP_COPY, pvDst, (uint32_t)cbDst, &cbRead);
885 AssertRC(rc2);
886
887#ifdef AC97_DEBUG_DUMP_PCM_DATA
888 RTFILE fh;
889 RTFileOpen(&fh, AC97_DEBUG_DUMP_PCM_DATA_PATH "ichac97StreamWrite.pcm",
890 RTFILE_O_OPEN_CREATE | RTFILE_O_APPEND | RTFILE_O_WRITE | RTFILE_O_DENY_NONE);
891 RTFileWrite(fh, pvDst, cbRead, NULL);
892 RTFileClose(fh);
893#endif
894 }
895
896 RTCircBufReleaseWriteBlock(pCircBuf, cbRead);
897
898 if (pcbWritten)
899 *pcbWritten = cbRead;
900
901 return VINF_SUCCESS;
902}
903
904/**
905 * Reads audio data from an AC'97 stream's DMA buffer and writes into a specified mixer sink.
906 *
907 * @returns IPRT status code.
908 * @param pThis AC'97 state.
909 * @param pSrcStream AC'97 stream to read audio data from.
910 * @param pDstMixSink Mixer sink to write audio data to.
911 * @param cbToRead Number of bytes to read.
912 * @param pcbRead Number of bytes read. Optional.
913 */
914static int ichac97StreamRead(PAC97STATE pThis, PAC97STREAM pSrcStream, PAUDMIXSINK pDstMixSink, uint32_t cbToRead,
915 uint32_t *pcbRead)
916{
917 RT_NOREF(pThis);
918 AssertPtrReturn(pSrcStream, VERR_INVALID_POINTER);
919 AssertPtrReturn(pDstMixSink, VERR_INVALID_POINTER);
920 AssertReturn(cbToRead, VERR_INVALID_PARAMETER);
921 /* pcbRead is optional. */
922
923 PRTCIRCBUF pCircBuf = pSrcStream->State.pCircBuf;
924 AssertPtr(pCircBuf);
925
926 void *pvSrc;
927 size_t cbSrc;
928
929 uint32_t cbWritten = 0;
930
931 RTCircBufAcquireReadBlock(pCircBuf, cbToRead, &pvSrc, &cbSrc);
932
933 if (cbSrc)
934 {
935#ifdef AC97_DEBUG_DUMP_PCM_DATA
936 RTFILE fh;
937 RTFileOpen(&fh, AC97_DEBUG_DUMP_PCM_DATA_PATH "ac97StreamRead.pcm",
938 RTFILE_O_OPEN_CREATE | RTFILE_O_APPEND | RTFILE_O_WRITE | RTFILE_O_DENY_NONE);
939 RTFileWrite(fh, pvSrc, cbSrc, NULL);
940 RTFileClose(fh);
941#endif
942 int rc2 = AudioMixerSinkWrite(pDstMixSink, AUDMIXOP_COPY, pvSrc, (uint32_t)cbSrc, &cbWritten);
943 AssertRC(rc2);
944
945#ifdef DEBUG_andy
946 Assert(cbWritten == cbSrc);
947#endif
948 }
949
950 RTCircBufReleaseReadBlock(pCircBuf, cbWritten);
951
952 if (pcbRead)
953 *pcbRead = cbWritten;
954
955 return VINF_SUCCESS;
956}
957
958#ifdef VBOX_WITH_AUDIO_AC97_ASYNC_IO
959/**
960 * Asynchronous I/O thread for an AC'97 stream.
961 * This will do the heavy lifting work for us as soon as it's getting notified by another thread.
962 *
963 * @returns IPRT status code.
964 * @param hThreadSelf Thread handle.
965 * @param pvUser User argument. Must be of type PAC97STREAMTHREADCTX.
966 */
967static DECLCALLBACK(int) ichac97StreamAsyncIOThread(RTTHREAD hThreadSelf, void *pvUser)
968{
969 PAC97STREAMTHREADCTX pCtx = (PAC97STREAMTHREADCTX)pvUser;
970 AssertPtr(pCtx);
971
972 PAC97STATE pThis = pCtx->pThis;
973 AssertPtr(pThis);
974
975 PAC97STREAM pStream = pCtx->pStream;
976 AssertPtr(pStream);
977
978 PAC97STREAMSTATEAIO pAIO = &pCtx->pStream->State.AIO;
979
980 PRTCIRCBUF pCircBuf = pStream->State.pCircBuf;
981 AssertPtr(pCircBuf);
982
983 PAUDMIXSINK pMixSink = ichac97IndexToSink(pThis, pStream->u8SD);
984 AssertPtr(pMixSink);
985
986 ASMAtomicXchgBool(&pAIO->fStarted, true);
987
988 RTThreadUserSignal(hThreadSelf);
989
990 LogFunc(("[SD%RU8]: Started\n", pStream->u8SD));
991
992 for (;;)
993 {
994 Log2Func(("[SD%RU8]: Waiting ...\n", pStream->u8SD));
995
996 int rc2 = RTSemEventWait(pAIO->Event, RT_INDEFINITE_WAIT);
997 if (RT_FAILURE(rc2))
998 break;
999
1000 if (ASMAtomicReadBool(&pAIO->fShutdown))
1001 break;
1002
1003 rc2 = RTCritSectEnter(&pAIO->CritSect);
1004 if (RT_SUCCESS(rc2))
1005 {
1006 if (!pAIO->fEnabled)
1007 {
1008 RTCritSectLeave(&pAIO->CritSect);
1009 continue;
1010 }
1011
1012 uint32_t cbToProcess;
1013 uint32_t cbProcessed = 0;
1014
1015 switch (pStream->u8SD)
1016 {
1017 /* Input. */
1018 case AC97SOUNDSOURCE_PI_INDEX:
1019 case AC97SOUNDSOURCE_MC_INDEX:
1020 {
1021 cbToProcess = RTCircBufFree(pCircBuf);
1022 if (cbToProcess)
1023 rc2 = ichac97StreamWrite(pThis, pStream, pMixSink, (uint32_t)cbToProcess, &cbProcessed);
1024 break;
1025 }
1026
1027 /* Output. */
1028 case AC97SOUNDSOURCE_PO_INDEX:
1029 {
1030 cbToProcess = RTCircBufUsed(pCircBuf);
1031 if (cbToProcess)
1032 rc2 = ichac97StreamRead(pThis, pStream, pMixSink, (uint32_t)cbToProcess, &cbProcessed);
1033 break;
1034 }
1035
1036 default:
1037 AssertFailedStmt(rc2 = VERR_NOT_SUPPORTED);
1038 break;
1039 }
1040
1041 if (RT_SUCCESS(rc2))
1042 rc2 = AudioMixerSinkUpdate(pMixSink);
1043
1044 int rc3 = RTCritSectLeave(&pAIO->CritSect);
1045 AssertRC(rc3);
1046 }
1047
1048 AssertRC(rc2);
1049 }
1050
1051 LogFunc(("[SD%RU8]: Ended\n", pStream->u8SD));
1052
1053 ASMAtomicXchgBool(&pAIO->fStarted, false);
1054
1055 return VINF_SUCCESS;
1056}
1057
1058/**
1059 * Creates the async I/O thread for a specific AC'97 audio stream.
1060 *
1061 * @returns IPRT status code.
1062 * @param pThis AC'97 state.
1063 * @param pStream AC'97 audio stream to create the async I/O thread for.
1064 */
1065static int ichac97StreamAsyncIOCreate(PAC97STATE pThis, PAC97STREAM pStream)
1066{
1067 PAC97STREAMSTATEAIO pAIO = &pStream->State.AIO;
1068
1069 int rc;
1070
1071 if (!ASMAtomicReadBool(&pAIO->fStarted))
1072 {
1073 pAIO->fShutdown = false;
1074
1075 rc = RTSemEventCreate(&pAIO->Event);
1076 if (RT_SUCCESS(rc))
1077 {
1078 rc = RTCritSectInit(&pAIO->CritSect);
1079 if (RT_SUCCESS(rc))
1080 {
1081 AC97STREAMTHREADCTX Ctx = { pThis, pStream };
1082
1083 char szThreadName[64];
1084 RTStrPrintf2(szThreadName, sizeof(szThreadName), "ac97AIO%RU8", pStream->u8SD);
1085
1086 rc = RTThreadCreate(&pAIO->Thread, ichac97StreamAsyncIOThread, &Ctx,
1087 0, RTTHREADTYPE_IO, RTTHREADFLAGS_WAITABLE, szThreadName);
1088 if (RT_SUCCESS(rc))
1089 rc = RTThreadUserWait(pAIO->Thread, 10 * 1000 /* 10s timeout */);
1090 }
1091 }
1092 }
1093 else
1094 rc = VINF_SUCCESS;
1095
1096 LogFunc(("[SD%RU8]: Returning %Rrc\n", pStream->u8SD, rc));
1097 return rc;
1098}
1099
1100/**
1101 * Destroys the async I/O thread of a specific AC'97 audio stream.
1102 *
1103 * @returns IPRT status code.
1104 * @param pThis AC'97 state.
1105 * @param pStream AC'97 audio stream to destroy the async I/O thread for.
1106 */
1107static int ichac97StreamAsyncIODestroy(PAC97STATE pThis, PAC97STREAM pStream)
1108{
1109 PAC97STREAMSTATEAIO pAIO = &pStream->State.AIO;
1110
1111 if (!ASMAtomicReadBool(&pAIO->fStarted))
1112 return VINF_SUCCESS;
1113
1114 ASMAtomicWriteBool(&pAIO->fShutdown, true);
1115
1116 int rc = ichac97StreamAsyncIONotify(pThis, pStream);
1117 AssertRC(rc);
1118
1119 int rcThread;
1120 rc = RTThreadWait(pAIO->Thread, 30 * 1000 /* 30s timeout */, &rcThread);
1121 LogFunc(("Async I/O thread ended with %Rrc (%Rrc)\n", rc, rcThread));
1122
1123 if (RT_SUCCESS(rc))
1124 {
1125 rc = RTCritSectDelete(&pAIO->CritSect);
1126 AssertRC(rc);
1127
1128 rc = RTSemEventDestroy(pAIO->Event);
1129 AssertRC(rc);
1130
1131 pAIO->fStarted = false;
1132 pAIO->fShutdown = false;
1133 pAIO->fEnabled = false;
1134 }
1135
1136 LogFunc(("[SD%RU8]: Returning %Rrc\n", pStream->u8SD, rc));
1137 return rc;
1138}
1139
1140/**
1141 * Lets the stream's async I/O thread know that there is some data to process.
1142 *
1143 * @returns IPRT status code.
1144 * @param pThis AC'97 state.
1145 * @param pStream AC'97 stream to notify async I/O thread for.
1146 */
1147static int ichac97StreamAsyncIONotify(PAC97STATE pThis, PAC97STREAM pStream)
1148{
1149 RT_NOREF(pThis);
1150
1151 LogFunc(("[SD%RU8]\n", pStream->u8SD));
1152 return RTSemEventSignal(pStream->State.AIO.Event);
1153}
1154
1155/**
1156 * Locks the async I/O thread of a specific AC'97 audio stream.
1157 *
1158 * @param pStream AC'97 stream to lock async I/O thread for.
1159 */
1160static void ichac97StreamAsyncIOLock(PAC97STREAM pStream)
1161{
1162 PAC97STREAMSTATEAIO pAIO = &pStream->State.AIO;
1163
1164 if (!ASMAtomicReadBool(&pAIO->fStarted))
1165 return;
1166
1167 int rc2 = RTCritSectEnter(&pAIO->CritSect);
1168 AssertRC(rc2);
1169}
1170
1171/**
1172 * Unlocks the async I/O thread of a specific AC'97 audio stream.
1173 *
1174 * @param pStream AC'97 stream to unlock async I/O thread for.
1175 */
1176static void ichac97StreamAsyncIOUnlock(PAC97STREAM pStream)
1177{
1178 PAC97STREAMSTATEAIO pAIO = &pStream->State.AIO;
1179
1180 if (!ASMAtomicReadBool(&pAIO->fStarted))
1181 return;
1182
1183 int rc2 = RTCritSectLeave(&pAIO->CritSect);
1184 AssertRC(rc2);
1185}
1186
1187/**
1188 * Enables (resumes) or disables (pauses) the async I/O thread.
1189 *
1190 * @param pStream AC'97 stream to enable/disable async I/O thread for.
1191 * @param fEnable Whether to enable or disable the I/O thread.
1192 *
1193 * @remarks Does not do locking.
1194 */
1195static void ichac97StreamAsyncIOEnable(PAC97STREAM pStream, bool fEnable)
1196{
1197 PAC97STREAMSTATEAIO pAIO = &pStream->State.AIO;
1198 ASMAtomicXchgBool(&pAIO->fEnabled, fEnable);
1199}
1200#endif /* VBOX_WITH_AUDIO_AC97_ASYNC_IO */
1201
1202/**
1203 * Updates an AC'97 stream according to its usage (input / output).
1204 *
1205 * For an SDO (output) stream this means reading DMA data from the device to
1206 * the connected audio sink(s).
1207 *
1208 * For an SDI (input) stream this is reading audio data from the connected
1209 * audio sink(s) and writing it as DMA data to the device.
1210 *
1211 * @returns IPRT status code.
1212 * @param pThis AC'97 state.
1213 * @param pStream AC'97 stream to update.
1214 */
1215static int ichac97StreamUpdate(PAC97STATE pThis, PAC97STREAM pStream)
1216{
1217 AssertPtrReturn(pThis, VERR_INVALID_POINTER);
1218 AssertPtrReturn(pStream, VERR_INVALID_POINTER);
1219
1220 ichac97StreamLock(pStream);
1221
1222 PAUDMIXSINK pMixSink = ichac97IndexToSink(pThis, pStream->u8SD);
1223 AssertPtr(pMixSink);
1224
1225 if (!AudioMixerSinkIsActive(pMixSink))
1226 {
1227 ichac97StreamUnlock(pStream);
1228 return VINF_SUCCESS;
1229 }
1230
1231 PRTCIRCBUF pCircBuf = pStream->State.pCircBuf;
1232 AssertPtr(pCircBuf);
1233
1234 bool fDone = false;
1235 uint8_t cTransfers = 0;
1236
1237 Log2Func(("[SD%RU8] Started\n", pStream->u8SD));
1238
1239 while (!fDone)
1240 {
1241 int rc2;
1242 uint32_t cbDMA = 0;
1243
1244 if (pStream->u8SD == AC97SOUNDSOURCE_PO_INDEX) /* Output. */
1245 {
1246 STAM_PROFILE_START(&pThis->StatOut, a);
1247
1248 /*
1249 * Read from DMA.
1250 */
1251 uint8_t abFIFO[AC97_FIFO_MAX + 1];
1252 size_t offFIFO = 0;
1253
1254 /* Do one DMA transfer with FIFOS size at a time. */
1255 rc2 = ichac97DoDMA(pThis, pStream, abFIFO, sizeof(abFIFO), AC97_FIFO_MAX /** @todo FIFOS? */, &cbDMA);
1256 AssertRC(rc2);
1257
1258 uint32_t cbDMALeft = cbDMA;
1259
1260 while ( cbDMALeft
1261 && RTCircBufFree(pCircBuf))
1262 {
1263 Log3Func(("[SD%RU8] cbLeft=%RU32\n", pStream->u8SD, cbDMALeft));
1264
1265 void *pvDst;
1266 size_t cbDst;
1267
1268 RTCircBufAcquireWriteBlock(pCircBuf, cbDMALeft, &pvDst, &cbDst);
1269
1270 if (cbDst)
1271 {
1272 memcpy(pvDst, abFIFO + offFIFO, cbDst);
1273
1274 offFIFO += cbDst;
1275 Assert(offFIFO <= sizeof(abFIFO));
1276 }
1277
1278 RTCircBufReleaseWriteBlock(pCircBuf, cbDst);
1279
1280 Assert(cbDst <= cbDMALeft);
1281 cbDMALeft -= (uint32_t)cbDst;
1282 }
1283
1284#ifdef DEBUG_andy
1285 AssertMsg(cbDMALeft == 0, ("%RU32 bytes of DMA data left, CircBuf=%zu/%zu\n",
1286 cbDMALeft, RTCircBufUsed(pCircBuf), RTCircBufSize(pCircBuf)));
1287#endif
1288 /*
1289 * Process backends.
1290 */
1291
1292 /* Do we have data left to write to the backends? */
1293 uint32_t cbUsed = (uint32_t)RTCircBufUsed(pCircBuf);
1294 if (cbUsed)
1295 {
1296 Log3Func(("[SD%RU8] cbUsed=%RU32\n", pStream->u8SD, cbUsed));
1297
1298#ifdef VBOX_WITH_AUDIO_AC97_ASYNC_IO
1299 /* Let the asynchronous thread know that there is some new data to process. */
1300 ichac97StreamAsyncIONotify(pThis, pStream);
1301#else
1302 /* Read audio data from the AC'97 stream and write to the backends. */
1303 rc2 = ichac97StreamRead(pThis, pStream, pMixSink, cbUsed, NULL /* pcbRead */);
1304 AssertRC(rc2);
1305#endif
1306 }
1307
1308 /* All DMA transfers done for now? */
1309 if ( !cbDMA
1310#ifndef VBOX_WITH_AUDIO_AC97_ASYNC_IO
1311 /* All data read *and* processed for now? */
1312 && RTCircBufUsed(pCircBuf) == 0
1313#endif
1314 )
1315 {
1316 fDone = true;
1317 }
1318
1319#ifndef VBOX_WITH_AUDIO_AC97_ASYNC_IO
1320 rc2 = AudioMixerSinkUpdate(pMixSink);
1321 AssertRC(rc2);
1322#endif
1323 STAM_PROFILE_STOP(&pThis->StatOut, a);
1324 }
1325 else if ( pStream->u8SD == AC97SOUNDSOURCE_PI_INDEX /* Input. */
1326 || pStream->u8SD == AC97SOUNDSOURCE_MC_INDEX) /* Input. */
1327 {
1328 STAM_PROFILE_START(&pThis->StatIn, a);
1329
1330 /*
1331 * Process backends.
1332 */
1333
1334#ifdef VBOX_WITH_AUDIO_AC97_ASYNC_IO
1335 /* Let the asynchronous thread know that there is some new data to process. */
1336 ichac97StreamAsyncIONotify(pThis, pStream);
1337#else
1338 rc2 = AudioMixerSinkUpdate(pMixSink);
1339 AssertRC(rc2);
1340
1341 /* Write read data from the backend to the AC'97 stream. */
1342 rc2 = ichac97StreamWrite(pThis, pStream, pMixSink, 256 /** @todo Fix this! */, NULL /* pcbWritten */);
1343 AssertRC(rc2);
1344#endif
1345 /*
1346 * Write to DMA.
1347 */
1348 void *pvSrc;
1349 size_t cbSrc;
1350
1351 RTCircBufAcquireReadBlock(pCircBuf, 256 /** @todo Fix this! */, &pvSrc, &cbSrc);
1352
1353 if (cbSrc)
1354 {
1355 /* Do one DMA transfer with FIFOS size at a time. */
1356 rc2 = ichac97DoDMA(pThis, pStream, pvSrc, (uint32_t)cbSrc, (uint32_t)cbSrc /* cbToProcess */, &cbDMA);
1357 AssertRC(rc2);
1358 }
1359
1360 RTCircBufReleaseReadBlock(pCircBuf, cbDMA);
1361
1362 /* All DMA transfers done for now? */
1363 if (!cbDMA)
1364 fDone = true;
1365
1366 STAM_PROFILE_STOP(&pThis->StatIn, a);
1367 }
1368 else
1369 AssertFailed();
1370
1371 if (++cTransfers > 32) /* Failsafe counter. */
1372 fDone = true;
1373
1374 } /* while !fDone */
1375
1376 Log2Func(("[SD%RU8] End\n", pStream->u8SD));
1377
1378 ichac97StreamUnlock(pStream);
1379
1380 return VINF_SUCCESS;
1381}
1382
1383static void ichac97MixerSet(PAC97STATE pThis, uint8_t uMixerIdx, uint16_t uVal)
1384{
1385 if (size_t(uMixerIdx + 2) > sizeof(pThis->mixer_data))
1386 {
1387 AssertMsgFailed(("Index %RU8 out of bounds(%zu)\n", uMixerIdx, sizeof(pThis->mixer_data)));
1388 return;
1389 }
1390
1391 pThis->mixer_data[uMixerIdx + 0] = RT_LO_U8(uVal);
1392 pThis->mixer_data[uMixerIdx + 1] = RT_HI_U8(uVal);
1393}
1394
1395static uint16_t ichac97MixerGet(PAC97STATE pThis, uint32_t uMixerIdx)
1396{
1397 uint16_t uVal;
1398
1399 if (size_t(uMixerIdx + 2) > sizeof(pThis->mixer_data))
1400 {
1401 AssertMsgFailed(("Index %RU8 out of bounds (%zu)\n", uMixerIdx, sizeof(pThis->mixer_data)));
1402 uVal = UINT16_MAX;
1403 }
1404 else
1405 uVal = RT_MAKE_U16(pThis->mixer_data[uMixerIdx + 0], pThis->mixer_data[uMixerIdx + 1]);
1406
1407 return uVal;
1408}
1409
1410/**
1411 * Retrieves a specific driver stream of a AC'97 driver.
1412 *
1413 * @returns Pointer to driver stream if found, or NULL if not found.
1414 * @param pThis AC'97 state.
1415 * @param pDrv Driver to retrieve driver stream for.
1416 * @param enmDir Stream direction to retrieve.
1417 * @param dstSrc Stream destination / source to retrieve.
1418 */
1419static PAC97DRIVERSTREAM ichac97MixerGetDrvStream(PAC97STATE pThis, PAC97DRIVER pDrv,
1420 PDMAUDIODIR enmDir, PDMAUDIODESTSOURCE dstSrc)
1421{
1422 RT_NOREF(pThis);
1423
1424 PAC97DRIVERSTREAM pDrvStream = NULL;
1425
1426 if (enmDir == PDMAUDIODIR_IN)
1427 {
1428 LogFunc(("enmRecSource=%d\n", dstSrc.Source));
1429
1430 switch (dstSrc.Source)
1431 {
1432 case PDMAUDIORECSOURCE_LINE:
1433 pDrvStream = &pDrv->LineIn;
1434 break;
1435 case PDMAUDIORECSOURCE_MIC:
1436 pDrvStream = &pDrv->MicIn;
1437 break;
1438 default:
1439 AssertFailed();
1440 break;
1441 }
1442 }
1443 else if (enmDir == PDMAUDIODIR_OUT)
1444 {
1445 LogFunc(("enmPlaybackDest=%d\n", dstSrc.Dest));
1446
1447 switch (dstSrc.Dest)
1448 {
1449 case PDMAUDIOPLAYBACKDEST_FRONT:
1450 pDrvStream = &pDrv->Out;
1451 break;
1452 default:
1453 AssertFailed();
1454 break;
1455 }
1456 }
1457 else
1458 AssertFailed();
1459
1460 return pDrvStream;
1461}
1462
1463/**
1464 * Adds audio streams for all drivers to a specific mixer sink.
1465 *
1466 * @returns IPRT status code.
1467 * @param pThis AC'97 state.
1468 * @param pMixSink Mixer sink to add stream to.
1469 * @param pCfg Stream configuration to use.
1470 */
1471static int ichac97MixerAddDrvStreams(PAC97STATE pThis, PAUDMIXSINK pMixSink, PPDMAUDIOSTREAMCFG pCfg)
1472{
1473 AssertPtrReturn(pThis, VERR_INVALID_POINTER);
1474 AssertPtrReturn(pMixSink, VERR_INVALID_POINTER);
1475 AssertPtrReturn(pCfg, VERR_INVALID_POINTER);
1476
1477 /* Update the sink's format. */
1478 PDMAUDIOPCMPROPS PCMProps;
1479 int rc = DrvAudioHlpStreamCfgToProps(pCfg, &PCMProps);
1480 if (RT_SUCCESS(rc))
1481 rc = AudioMixerSinkSetFormat(pMixSink, &PCMProps);
1482
1483 if (RT_FAILURE(rc))
1484 return rc;
1485
1486 PAC97DRIVER pDrv;
1487 RTListForEach(&pThis->lstDrv, pDrv, AC97DRIVER, Node)
1488 {
1489 PPDMAUDIOSTREAMCFG pStreamCfg = (PPDMAUDIOSTREAMCFG)RTMemDup(pCfg, sizeof(PDMAUDIOSTREAMCFG));
1490 if (!pStreamCfg)
1491 {
1492 rc = VERR_NO_MEMORY;
1493 break;
1494 }
1495
1496 if (!RTStrPrintf(pStreamCfg->szName, sizeof(pStreamCfg->szName), "[LUN#%RU8] %s", pDrv->uLUN, pCfg->szName))
1497 {
1498 RTMemFree(pStreamCfg);
1499
1500 rc = VERR_BUFFER_OVERFLOW;
1501 break;
1502 }
1503
1504 LogFunc(("%s\n", pStreamCfg->szName));
1505
1506 int rc2 = VINF_SUCCESS;
1507
1508 PAC97DRIVERSTREAM pDrvStream = ichac97MixerGetDrvStream(pThis, pDrv, pStreamCfg->enmDir, pStreamCfg->DestSource);
1509 if (pDrvStream)
1510 {
1511 AssertMsg(pDrvStream->pMixStrm == NULL, ("[LUN#%RU8] Driver stream already present when it must not\n", pDrv->uLUN));
1512
1513 PAUDMIXSTREAM pMixStrm;
1514 rc2 = AudioMixerSinkCreateStream(pMixSink, pDrv->pConnector, pStreamCfg, 0 /* fFlags */, &pMixStrm);
1515 if (RT_SUCCESS(rc2))
1516 {
1517 rc2 = AudioMixerSinkAddStream(pMixSink, pMixStrm);
1518 LogFlowFunc(("LUN#%RU8: Created stream \"%s\", rc=%Rrc\n", pDrv->uLUN, pCfg->szName, rc2));
1519 }
1520
1521 if (RT_SUCCESS(rc2))
1522 pDrvStream->pMixStrm = pMixStrm;
1523 }
1524
1525 if (RT_SUCCESS(rc))
1526 rc = rc2;
1527
1528 if (pStreamCfg)
1529 {
1530 RTMemFree(pStreamCfg);
1531 pStreamCfg = NULL;
1532 }
1533 }
1534
1535 LogFlowFuncLeaveRC(rc);
1536 return rc;
1537}
1538
1539/**
1540 * Removes specific audio streams for all drivers.
1541 *
1542 * @param pThis AC'97 state.
1543 * @param pMixSink Mixer sink to remove audio streams from.
1544 * @param enmDir Stream direction to remove.
1545 * @param dstSrc Stream destination / source to remove.
1546 */
1547static void ichac97MixerRemoveDrvStreams(PAC97STATE pThis, PAUDMIXSINK pMixSink,
1548 PDMAUDIODIR enmDir, PDMAUDIODESTSOURCE dstSrc)
1549{
1550 AssertPtrReturnVoid(pThis);
1551 AssertPtrReturnVoid(pMixSink);
1552
1553 PAC97DRIVER pDrv;
1554 RTListForEach(&pThis->lstDrv, pDrv, AC97DRIVER, Node)
1555 {
1556 PAC97DRIVERSTREAM pDrvStream = ichac97MixerGetDrvStream(pThis, pDrv, enmDir, dstSrc);
1557 if (pDrvStream)
1558 {
1559 if (pDrvStream->pMixStrm)
1560 {
1561 AudioMixerSinkRemoveStream(pMixSink, pDrvStream->pMixStrm);
1562
1563 AudioMixerStreamDestroy(pDrvStream->pMixStrm);
1564 pDrvStream->pMixStrm = NULL;
1565 }
1566 }
1567 }
1568}
1569
1570/**
1571 * Opens an AC'97 stream with its current mixer settings.
1572 *
1573 * This will open an AC'97 stream with 2 (stereo) channels, 16-bit samples and
1574 * the last set sample rate in the AC'97 mixer for this stream.
1575 *
1576 * @returns IPRT status code.
1577 * @param pThis AC'97 state.
1578 * @param pStream AC'97 Stream to open.
1579 */
1580static int ichac97StreamOpen(PAC97STATE pThis, PAC97STREAM pStream)
1581{
1582 int rc = VINF_SUCCESS;
1583
1584 LogFunc(("[SD%RU8]\n", pStream->u8SD));
1585
1586 PDMAUDIOSTREAMCFG streamCfg;
1587 RT_ZERO(streamCfg);
1588
1589 PAUDMIXSINK pMixSink = NULL;
1590
1591 switch (pStream->u8SD)
1592 {
1593 case AC97SOUNDSOURCE_PI_INDEX:
1594 {
1595 streamCfg.uHz = ichac97MixerGet(pThis, AC97_PCM_LR_ADC_Rate);
1596 streamCfg.enmDir = PDMAUDIODIR_IN;
1597 streamCfg.DestSource.Source = PDMAUDIORECSOURCE_LINE;
1598
1599 RTStrPrintf2(streamCfg.szName, sizeof(streamCfg.szName), "Line-In");
1600
1601 pMixSink = pThis->pSinkLineIn;
1602 break;
1603 }
1604
1605 case AC97SOUNDSOURCE_MC_INDEX:
1606 {
1607 streamCfg.uHz = ichac97MixerGet(pThis, AC97_MIC_ADC_Rate);
1608 streamCfg.enmDir = PDMAUDIODIR_IN;
1609 streamCfg.DestSource.Source = PDMAUDIORECSOURCE_MIC;
1610
1611 RTStrPrintf2(streamCfg.szName, sizeof(streamCfg.szName), "Mic-In");
1612
1613 pMixSink = pThis->pSinkMicIn;
1614 break;
1615 }
1616
1617 case AC97SOUNDSOURCE_PO_INDEX:
1618 {
1619 streamCfg.uHz = ichac97MixerGet(pThis, AC97_PCM_Front_DAC_Rate);
1620 streamCfg.enmDir = PDMAUDIODIR_OUT;
1621 streamCfg.DestSource.Dest = PDMAUDIOPLAYBACKDEST_FRONT;
1622
1623 RTStrPrintf2(streamCfg.szName, sizeof(streamCfg.szName), "Output");
1624
1625 pMixSink = pThis->pSinkOut;
1626 break;
1627 }
1628
1629 default:
1630 rc = VERR_NOT_SUPPORTED;
1631 break;
1632 }
1633
1634 if (RT_SUCCESS(rc))
1635 {
1636 ichac97MixerRemoveDrvStreams(pThis, pMixSink, streamCfg.enmDir, streamCfg.DestSource);
1637
1638 if (streamCfg.uHz)
1639 {
1640 Assert(streamCfg.enmDir != PDMAUDIODIR_UNKNOWN);
1641
1642 streamCfg.cChannels = 2;
1643 streamCfg.enmFormat = PDMAUDIOFMT_S16;
1644 streamCfg.enmEndianness = PDMAUDIOHOSTENDIANNESS;
1645
1646 rc = ichac97MixerAddDrvStreams(pThis, pMixSink, &streamCfg);
1647 }
1648 }
1649
1650 LogFlowFunc(("[SD%RU8] rc=%Rrc\n", pStream->u8SD, rc));
1651 return rc;
1652}
1653
1654/**
1655 * Closes an AC'97 stream.
1656 *
1657 * @returns IPRT status code.
1658 * @param pThis AC'97 state.
1659 * @param pStream AC'97 stream to close.
1660 */
1661static int ichac97StreamClose(PAC97STATE pThis, PAC97STREAM pStream)
1662{
1663 RT_NOREF(pThis);
1664 RT_NOREF(pStream);
1665
1666 LogFlowFunc(("[SD%RU8]\n", pStream->u8SD));
1667
1668 return VINF_SUCCESS;
1669}
1670
1671/**
1672 * Re-opens (that is, closes and opens again) an AC'97 stream on the backend
1673 * side with the current AC'97 mixer settings for this stream.
1674 *
1675 * @returns IPRT status code.
1676 * @param pThis AC'97 device state.
1677 * @param pStream AC'97 stream to re-open.
1678 */
1679static int ichac97StreamReOpen(PAC97STATE pThis, PAC97STREAM pStream)
1680{
1681 LogFlowFunc(("[SD%RU8]\n", pStream->u8SD));
1682
1683 int rc = ichac97StreamClose(pThis, pStream);
1684 if (RT_SUCCESS(rc))
1685 rc = ichac97StreamOpen(pThis, pStream);
1686
1687 return rc;
1688}
1689
1690/**
1691 * Locks an AC'97 stream for serialized access.
1692 *
1693 * @returns IPRT status code.
1694 * @param pStream AC'97 stream to lock.
1695 */
1696static void ichac97StreamLock(PAC97STREAM pStream)
1697{
1698 AssertPtrReturnVoid(pStream);
1699 int rc2 = RTCritSectEnter(&pStream->State.CritSect);
1700 AssertRC(rc2);
1701}
1702
1703
1704/**
1705 * Unlocks a formerly locked AC'97 stream.
1706 *
1707 * @returns IPRT status code.
1708 * @param pStream AC'97 stream to unlock.
1709 */
1710static void ichac97StreamUnlock(PAC97STREAM pStream)
1711{
1712 AssertPtrReturnVoid(pStream);
1713 int rc2 = RTCritSectLeave(&pStream->State.CritSect);
1714 AssertRC(rc2);
1715}
1716
1717/**
1718 * Sets the volume of a specific AC'97 mixer control.
1719 *
1720 * This currently only supports attenuation -- gain support is currently not implemented.
1721 *
1722 * @returns IPRT status code.
1723 * @param pThis AC'97 state.
1724 * @param index AC'97 mixer index to set volume for.
1725 * @param enmMixerCtl Corresponding audio mixer sink.
1726 * @param uVal Volume value to set.
1727 */
1728static int ichac97MixerSetVolume(PAC97STATE pThis, int index, PDMAUDIOMIXERCTL enmMixerCtl, uint32_t uVal)
1729{
1730 bool fCntlMuted;
1731 uint8_t lCntlAtt, rCntlAtt;
1732
1733 /*
1734 * From AC'97 SoundMax Codec AD1981A/AD1981B:
1735 * "Because AC '97 defines 6-bit volume registers, to maintain compatibility whenever the
1736 * D5 or D13 bits are set to 1, their respective lower five volume bits are automatically
1737 * set to 1 by the Codec logic. On readback, all lower 5 bits will read ones whenever
1738 * these bits are set to 1."
1739 *
1740 * Linux ALSA depends on this behavior.
1741 */
1742 /// @todo Does this apply to anything other than the master volume control?
1743 if (uVal & RT_BIT(5))
1744 uVal |= RT_BIT(4) | RT_BIT(3) | RT_BIT(2) | RT_BIT(1) | RT_BIT(0);
1745 if (uVal & RT_BIT(13))
1746 uVal |= RT_BIT(12) | RT_BIT(11) | RT_BIT(10) | RT_BIT(9) | RT_BIT(8);
1747
1748 fCntlMuted = (uVal >> AC97_BARS_VOL_MUTE_SHIFT) & 1;
1749 lCntlAtt = (uVal >> 8) & AC97_BARS_VOL_MASK;
1750 rCntlAtt = uVal & AC97_BARS_VOL_MASK;
1751
1752 /* For the master and headphone volume, 0 corresponds to 0dB attenuation. For the other
1753 * volume controls, 0 means 12dB gain and 8 means unity gain.
1754 */
1755 if (index != AC97_Master_Volume_Mute && index != AC97_Headphone_Volume_Mute)
1756 {
1757#ifndef VBOX_WITH_AC97_GAIN_SUPPORT
1758 /* NB: Currently there is no gain support, only attenuation. */
1759 lCntlAtt = lCntlAtt < 8 ? 0 : lCntlAtt - 8;
1760 rCntlAtt = rCntlAtt < 8 ? 0 : rCntlAtt - 8;
1761#endif
1762 }
1763 Assert(lCntlAtt <= 255 / AC97_DB_FACTOR);
1764 Assert(rCntlAtt <= 255 / AC97_DB_FACTOR);
1765
1766 LogFunc(("index=0x%x, uVal=%RU32, enmMixerCtl=%RU32\n", index, uVal, enmMixerCtl));
1767 LogFunc(("lAtt=%RU8, rAtt=%RU8 ", lCntlAtt, rCntlAtt));
1768
1769 /*
1770 * For AC'97 volume controls, each additional step means -1.5dB attenuation with
1771 * zero being maximum. In contrast, we're internally using 255 (PDMAUDIO_VOLUME_MAX)
1772 * steps, each -0.375dB, where 0 corresponds to -96dB and 255 corresponds to 0dB.
1773 */
1774 uint8_t lVol = PDMAUDIO_VOLUME_MAX - lCntlAtt * AC97_DB_FACTOR;
1775 uint8_t rVol = PDMAUDIO_VOLUME_MAX - rCntlAtt * AC97_DB_FACTOR;
1776
1777 Log(("-> fMuted=%RTbool, lVol=%RU8, rVol=%RU8\n", fCntlMuted, lVol, rVol));
1778
1779 int rc = VINF_SUCCESS;
1780
1781 if (pThis->pMixer) /* Device can be in reset state, so no mixer available. */
1782 {
1783 PDMAUDIOVOLUME Vol = { fCntlMuted, lVol, rVol };
1784 PAUDMIXSINK pSink = NULL;
1785
1786 switch (enmMixerCtl)
1787 {
1788 case PDMAUDIOMIXERCTL_VOLUME_MASTER:
1789 rc = AudioMixerSetMasterVolume(pThis->pMixer, &Vol);
1790 break;
1791
1792 case PDMAUDIOMIXERCTL_FRONT:
1793 pSink = pThis->pSinkOut;
1794 break;
1795
1796 case PDMAUDIOMIXERCTL_MIC_IN:
1797 pSink = pThis->pSinkMicIn;
1798 break;
1799
1800 case PDMAUDIOMIXERCTL_LINE_IN:
1801 pSink = pThis->pSinkLineIn;
1802 break;
1803
1804 default:
1805 AssertFailed();
1806 rc = VERR_NOT_SUPPORTED;
1807 break;
1808 }
1809
1810 if (pSink)
1811 rc = AudioMixerSinkSetVolume(pSink, &Vol);
1812 }
1813
1814 ichac97MixerSet(pThis, index, uVal);
1815
1816 if (RT_FAILURE(rc))
1817 LogFlowFunc(("Failed with %Rrc\n", rc));
1818
1819 return rc;
1820}
1821
1822/**
1823 * Converts an AC'97 recording source index to a PDM audio recording source.
1824 *
1825 * @returns PDM audio recording source.
1826 * @param uIdx AC'97 index to convert.
1827 */
1828static PDMAUDIORECSOURCE ichac97IdxToRecSource(uint8_t uIdx)
1829{
1830 switch (uIdx)
1831 {
1832 case AC97_REC_MIC: return PDMAUDIORECSOURCE_MIC;
1833 case AC97_REC_CD: return PDMAUDIORECSOURCE_CD;
1834 case AC97_REC_VIDEO: return PDMAUDIORECSOURCE_VIDEO;
1835 case AC97_REC_AUX: return PDMAUDIORECSOURCE_AUX;
1836 case AC97_REC_LINE_IN: return PDMAUDIORECSOURCE_LINE;
1837 case AC97_REC_PHONE: return PDMAUDIORECSOURCE_PHONE;
1838 default:
1839 break;
1840 }
1841
1842 LogFlowFunc(("Unknown record source %d, using MIC\n", uIdx));
1843 return PDMAUDIORECSOURCE_MIC;
1844}
1845
1846/**
1847 * Converts a PDM audio recording source to an AC'97 recording source index.
1848 *
1849 * @returns AC'97 recording source index.
1850 * @param enmRecSrc PDM audio recording source to convert.
1851 */
1852static uint8_t ichac97RecSourceToIdx(PDMAUDIORECSOURCE enmRecSrc)
1853{
1854 switch (enmRecSrc)
1855 {
1856 case PDMAUDIORECSOURCE_MIC: return AC97_REC_MIC;
1857 case PDMAUDIORECSOURCE_CD: return AC97_REC_CD;
1858 case PDMAUDIORECSOURCE_VIDEO: return AC97_REC_VIDEO;
1859 case PDMAUDIORECSOURCE_AUX: return AC97_REC_AUX;
1860 case PDMAUDIORECSOURCE_LINE: return AC97_REC_LINE_IN;
1861 case PDMAUDIORECSOURCE_PHONE: return AC97_REC_PHONE;
1862 default:
1863 break;
1864 }
1865
1866 LogFlowFunc(("Unknown audio recording source %d using MIC\n", enmRecSrc));
1867 return AC97_REC_MIC;
1868}
1869
1870/**
1871 * Retrieves an AC'97 audio stream from an AC'97 stream index.
1872 *
1873 * @returns Pointer to AC'97 audio stream if found, or NULL if not found / invalid.
1874 * @param pThis AC'97 state.
1875 * @param uIdx AC'97 stream index to retrieve AC'97 audio stream for.
1876 */
1877DECLINLINE(PAC97STREAM) ichac97GetStreamFromIdx(PAC97STATE pThis, uint32_t uIdx)
1878{
1879 switch (uIdx)
1880 {
1881 case AC97SOUNDSOURCE_PI_INDEX: return &pThis->StreamLineIn;
1882 case AC97SOUNDSOURCE_MC_INDEX: return &pThis->StreamMicIn;
1883 case AC97SOUNDSOURCE_PO_INDEX: return &pThis->StreamOut;
1884 default: break;
1885 }
1886
1887 return NULL;
1888}
1889
1890/**
1891 * Performs an AC'97 mixer record select to switch to a different recording
1892 * source.
1893 *
1894 * @param pThis AC'97 state.
1895 * @param val AC'97 recording source index to set.
1896 */
1897static void ichac97MixerRecordSelect(PAC97STATE pThis, uint32_t val)
1898{
1899 uint8_t rs = val & AC97_REC_MASK;
1900 uint8_t ls = (val >> 8) & AC97_REC_MASK;
1901 PDMAUDIORECSOURCE ars = ichac97IdxToRecSource(rs);
1902 PDMAUDIORECSOURCE als = ichac97IdxToRecSource(ls);
1903 rs = ichac97RecSourceToIdx(ars);
1904 ls = ichac97RecSourceToIdx(als);
1905 ichac97MixerSet(pThis, AC97_Record_Select, rs | (ls << 8));
1906}
1907
1908/**
1909 * Resets the AC'97 mixer.
1910 *
1911 * @returns IPRT status code.
1912 * @param pThis AC'97 state.
1913 */
1914static int ichac97MixerReset(PAC97STATE pThis)
1915{
1916 AssertPtrReturn(pThis, VERR_INVALID_PARAMETER);
1917
1918 LogFlowFuncEnter();
1919
1920 RT_ZERO(pThis->mixer_data);
1921
1922 /* Note: Make sure to reset all registers first before bailing out on error. */
1923
1924 ichac97MixerSet(pThis, AC97_Reset , 0x0000); /* 6940 */
1925 ichac97MixerSet(pThis, AC97_Master_Volume_Mono_Mute , 0x8000);
1926 ichac97MixerSet(pThis, AC97_PC_BEEP_Volume_Mute , 0x0000);
1927
1928 ichac97MixerSet(pThis, AC97_Phone_Volume_Mute , 0x8008);
1929 ichac97MixerSet(pThis, AC97_Mic_Volume_Mute , 0x8008);
1930 ichac97MixerSet(pThis, AC97_CD_Volume_Mute , 0x8808);
1931 ichac97MixerSet(pThis, AC97_Aux_Volume_Mute , 0x8808);
1932 ichac97MixerSet(pThis, AC97_Record_Gain_Mic_Mute , 0x8000);
1933 ichac97MixerSet(pThis, AC97_General_Purpose , 0x0000);
1934 ichac97MixerSet(pThis, AC97_3D_Control , 0x0000);
1935 ichac97MixerSet(pThis, AC97_Powerdown_Ctrl_Stat , 0x000f);
1936
1937 ichac97MixerSet(pThis, AC97_Extended_Audio_ID , 0x0809);
1938 ichac97MixerSet(pThis, AC97_Extended_Audio_Ctrl_Stat, 0x0009);
1939 ichac97MixerSet(pThis, AC97_PCM_Front_DAC_Rate , 0xbb80);
1940 ichac97MixerSet(pThis, AC97_PCM_Surround_DAC_Rate , 0xbb80);
1941 ichac97MixerSet(pThis, AC97_PCM_LFE_DAC_Rate , 0xbb80);
1942 ichac97MixerSet(pThis, AC97_PCM_LR_ADC_Rate , 0xbb80);
1943 ichac97MixerSet(pThis, AC97_MIC_ADC_Rate , 0xbb80);
1944
1945 if (pThis->uCodecModel == AC97_CODEC_AD1980)
1946 {
1947 /* Analog Devices 1980 (AD1980) */
1948 ichac97MixerSet(pThis, AC97_Reset , 0x0010); /* Headphones. */
1949 ichac97MixerSet(pThis, AC97_Vendor_ID1 , 0x4144);
1950 ichac97MixerSet(pThis, AC97_Vendor_ID2 , 0x5370);
1951 ichac97MixerSet(pThis, AC97_Headphone_Volume_Mute , 0x8000);
1952 }
1953 else if (pThis->uCodecModel == AC97_CODEC_AD1981B)
1954 {
1955 /* Analog Devices 1981B (AD1981B) */
1956 ichac97MixerSet(pThis, AC97_Vendor_ID1 , 0x4144);
1957 ichac97MixerSet(pThis, AC97_Vendor_ID2 , 0x5374);
1958 }
1959 else
1960 {
1961 /* Sigmatel 9700 (STAC9700) */
1962 ichac97MixerSet(pThis, AC97_Vendor_ID1 , 0x8384);
1963 ichac97MixerSet(pThis, AC97_Vendor_ID2 , 0x7600); /* 7608 */
1964 }
1965 ichac97MixerRecordSelect(pThis, 0);
1966
1967 ichac97MixerSetVolume(pThis, AC97_Master_Volume_Mute, PDMAUDIOMIXERCTL_VOLUME_MASTER, 0x8000);
1968 ichac97MixerSetVolume(pThis, AC97_PCM_Out_Volume_Mute, PDMAUDIOMIXERCTL_FRONT, 0x8808);
1969 ichac97MixerSetVolume(pThis, AC97_Line_In_Volume_Mute, PDMAUDIOMIXERCTL_LINE_IN, 0x8808);
1970 ichac97MixerSetVolume(pThis, AC97_Mic_Volume_Mute, PDMAUDIOMIXERCTL_MIC_IN, 0x8808);
1971
1972 return VINF_SUCCESS;
1973}
1974
1975/* Unused */
1976#if 0
1977static void ichac97WriteBUP(PAC97STATE pThis, uint32_t cbElapsed)
1978{
1979 LogFlowFunc(("cbElapsed=%RU32\n", cbElapsed));
1980
1981 if (!(pThis->bup_flag & BUP_SET))
1982 {
1983 if (pThis->bup_flag & BUP_LAST)
1984 {
1985 unsigned int i;
1986 uint32_t *p = (uint32_t*)pThis->silence;
1987 for (i = 0; i < sizeof(pThis->silence) / 4; i++) /** @todo r=andy Assumes 16-bit samples, stereo. */
1988 *p++ = pThis->last_samp;
1989 }
1990 else
1991 RT_ZERO(pThis->silence);
1992
1993 pThis->bup_flag |= BUP_SET;
1994 }
1995
1996 while (cbElapsed)
1997 {
1998 uint32_t cbToWrite = RT_MIN(cbElapsed, (uint32_t)sizeof(pThis->silence));
1999 uint32_t cbWrittenToStream;
2000
2001 int rc2 = AudioMixerSinkWrite(pThis->pSinkOut, AUDMIXOP_COPY,
2002 pThis->silence, cbToWrite, &cbWrittenToStream);
2003 if (RT_SUCCESS(rc2))
2004 {
2005 if (cbWrittenToStream < cbToWrite) /* Lagging behind? */
2006 LogFlowFunc(("Warning: Only written %RU32 / %RU32 bytes, expect lags\n", cbWrittenToStream, cbToWrite));
2007 }
2008
2009 /* Always report all data as being written;
2010 * backends who were not able to catch up have to deal with it themselves. */
2011 Assert(cbElapsed >= cbToWrite);
2012 cbElapsed -= cbToWrite;
2013 }
2014}
2015#endif /* Unused */
2016
2017#ifndef VBOX_WITH_AUDIO_AC97_CALLBACKS
2018/**
2019 * Starts the internal audio device timer (if not started yet).
2020 *
2021 * @param pThis AC'97 state.
2022 */
2023static void ichac97TimerMaybeStart(PAC97STATE pThis)
2024{
2025 LogFlowFuncEnter();
2026
2027 if (!pThis->pTimer)
2028 return;
2029
2030 pThis->cStreamsActive++;
2031
2032 /* Only start the timer at the first active stream. */
2033 if (pThis->cStreamsActive == 1)
2034 {
2035 LogRel2(("AC97: Starting transfers\n"));
2036
2037 /* Set timer flag. */
2038 ASMAtomicXchgBool(&pThis->fTimerActive, true);
2039
2040 /* Update current time timestamp. */
2041 pThis->uTimerTS = TMTimerGet(pThis->pTimer);
2042
2043 /* Start transfers. */
2044 ichac97TimerMain(pThis);
2045 }
2046}
2047
2048/**
2049 * Stops the internal audio device timer.
2050 *
2051 * @param pThis AC'97 state.
2052 */
2053static void ichac97TimerStop(PAC97STATE pThis)
2054{
2055 LogFlowFuncEnter();
2056
2057 /* Set timer flag. */
2058 ASMAtomicXchgBool(&pThis->fTimerActive, false);
2059}
2060
2061/**
2062 * Decreases the active AC'97 streams count by one and
2063 * then checks if the internal audio device timer can be
2064 * stopped.
2065 *
2066 * @param pThis AC'97 state.
2067 */
2068static void ichac97TimerMaybeStop(PAC97STATE pThis)
2069{
2070 LogFlowFuncEnter();
2071
2072 if (!pThis->pTimer)
2073 return;
2074
2075 if (pThis->cStreamsActive) /* Function can be called mupltiple times. */
2076 {
2077 pThis->cStreamsActive--;
2078
2079 if (pThis->cStreamsActive == 0)
2080 ichac97TimerStop(pThis);
2081 }
2082}
2083
2084/**
2085 * Main routine for the device timer.
2086 *
2087 * @returns IPRT status code.
2088 * @param pThis AC'97 state.
2089 */
2090static void ichac97TimerMain(PAC97STATE pThis)
2091{
2092 STAM_PROFILE_START(&pThis->StatTimer, a);
2093
2094 uint64_t cTicksNow = TMTimerGet(pThis->pTimer);
2095
2096 /* Update current time timestamp. */
2097 pThis->uTimerTS = cTicksNow;
2098
2099 /* Flag indicating whether to kick the timer again for the next DMA transfer or sink processing. */
2100 bool fKickTimer = false;
2101
2102 ichac97DoTransfers(pThis);
2103
2104 /* Do we need to kick the timer again? */
2105 if ( AudioMixerSinkIsActive(ichac97IndexToSink(pThis, pThis->StreamLineIn.u8SD))
2106 || AudioMixerSinkIsActive(ichac97IndexToSink(pThis, pThis->StreamMicIn.u8SD))
2107 || AudioMixerSinkIsActive(ichac97IndexToSink(pThis, pThis->StreamOut.u8SD)))
2108 {
2109 fKickTimer = true;
2110 }
2111
2112 if ( ASMAtomicReadBool(&pThis->fTimerActive)
2113 || fKickTimer)
2114 {
2115 /* Kick the timer again. */
2116 uint64_t cTicks = pThis->cTimerTicks;
2117 /** @todo adjust cTicks down by now much cbOutMin represents. */
2118 TMTimerSet(pThis->pTimer, cTicksNow + cTicks);
2119 }
2120 else
2121 LogRel2(("AC97: Stopping transfers\n"));
2122
2123 STAM_PROFILE_STOP(&pThis->StatTimer, a);
2124}
2125
2126/**
2127 * Timer callback which handles the audio data transfers on a periodic basis.
2128 *
2129 * @param pDevIns Device instance.
2130 * @param pTimer Timer which was used when calling this.
2131 * @param pvUser User argument as PAC97STATE.
2132 */
2133static DECLCALLBACK(void) ichac97Timer(PPDMDEVINS pDevIns, PTMTIMER pTimer, void *pvUser)
2134{
2135 RT_NOREF(pDevIns, pTimer);
2136
2137 PAC97STATE pThis = (PAC97STATE)pvUser;
2138 Assert(pThis == PDMINS_2_DATA(pDevIns, PAC97STATE));
2139 AssertPtr(pThis);
2140
2141 ichac97TimerMain(pThis);
2142}
2143#endif /* !VBOX_WITH_AUDIO_AC97_CALLBACKS */
2144
2145/**
2146 * Main routine to perform the actual audio data transfers from the AC'97 streams
2147 * to the backend(s) and vice versa.
2148 *
2149 * @param pThis AC'97 state.
2150 */
2151static void ichac97DoTransfers(PAC97STATE pThis)
2152{
2153 AssertPtrReturnVoid(pThis);
2154
2155 ichac97StreamUpdate(pThis, &pThis->StreamLineIn);
2156 ichac97StreamUpdate(pThis, &pThis->StreamMicIn);
2157 ichac97StreamUpdate(pThis, &pThis->StreamOut);
2158}
2159
2160/**
2161 * Does a single DMA transfer for a specific AC'97 stream.
2162 * This either can be a read or write operation, depending on the AC'97 stream.
2163 *
2164 * @returns IPRT status code.
2165 * @param pThis AC'97 state.
2166 * @param pStream AC'97 stream to do the DMA transfer for.
2167 * @param pvBuf Pointer to buffer data to write data to / read data from.
2168 * @param cbBuf Size of buffer (in bytes).
2169 * @param cbToProcess Size (in bytes) to transfer (read/write).
2170 * @param pcbProcessed Size (in bytes) transferred (read/written). Optional.
2171 */
2172static int ichac97DoDMA(PAC97STATE pThis, PAC97STREAM pStream, void *pvBuf, uint32_t cbBuf,
2173 uint32_t cbToProcess, uint32_t *pcbProcessed)
2174{
2175 AssertPtrReturn(pThis, VERR_INVALID_POINTER);
2176 AssertPtrReturn(pStream, VERR_INVALID_POINTER);
2177 AssertPtrReturn(pvBuf, VERR_INVALID_POINTER);
2178 AssertReturn(cbBuf >= cbToProcess, VERR_INVALID_PARAMETER);
2179 /* pcbProcessed is optional. */
2180
2181 PAC97BMREGS pRegs = &pStream->Regs;
2182
2183 if (pRegs->sr & AC97_SR_DCH) /* Controller halted? */
2184 {
2185 if (pRegs->cr & AC97_CR_RPBM) /* Bus master operation starts. */
2186 {
2187 switch (pStream->u8SD)
2188 {
2189 case AC97SOUNDSOURCE_PO_INDEX:
2190 /*ichac97WriteBUP(pThis, cbToProcess);*/
2191 break;
2192
2193 default:
2194 break;
2195 }
2196 }
2197
2198 if (pcbProcessed)
2199 *pcbProcessed = 0;
2200
2201 return VINF_SUCCESS;
2202 }
2203
2204 /* BCIS flag still set? Skip iteration. */
2205 if (pRegs->sr & AC97_SR_BCIS)
2206 {
2207 Log3Func(("[SD%RU8] BCIS set\n", pStream->u8SD));
2208
2209 if (pcbProcessed)
2210 *pcbProcessed = 0;
2211
2212 return VINF_SUCCESS;
2213 }
2214
2215 uint32_t cbLeft = RT_MIN((uint32_t)(pRegs->picb << 1), RT_MIN(cbToProcess, cbBuf));
2216 uint32_t cbTotal = 0;
2217 uint32_t cbChunk;
2218
2219 int rc = VINF_SUCCESS;
2220
2221 Log3Func(("[SD%RU8] cbToProcess=%RU32, cbLeft=%RU32\n", pStream->u8SD, cbToProcess, cbLeft));
2222
2223 while (cbLeft)
2224 {
2225 if (!pRegs->bd_valid)
2226 {
2227 Log3Func(("Invalid buffer descriptor, fetching next one ...\n"));
2228 ichac97StreamFetchBDLE(pThis, pStream);
2229 }
2230
2231 if (!pRegs->picb) /* Got a new buffer descriptor, that is, the position is 0? */
2232 {
2233 Log3Func(("Fresh buffer descriptor %RU8 is empty, addr=%#x, len=%#x, skipping\n",
2234 pRegs->civ, pRegs->bd.addr, pRegs->bd.ctl_len));
2235 if (pRegs->civ == pRegs->lvi)
2236 {
2237 pRegs->sr |= AC97_SR_DCH; /** @todo r=andy Also set CELV? */
2238 pThis->bup_flag = 0;
2239
2240 rc = VINF_EOF;
2241 break;
2242 }
2243
2244 pRegs->sr &= ~AC97_SR_CELV;
2245 pRegs->civ = pRegs->piv;
2246 pRegs->piv = (pRegs->piv + 1) % 32; /** @todo r=andy Define for max BDLEs? */
2247
2248 ichac97StreamFetchBDLE(pThis, pStream);
2249 continue;
2250 }
2251
2252 cbChunk = RT_MIN((uint32_t)(pRegs->picb << 1), cbLeft); /** @todo r=andy Assumes 16bit samples. */
2253 Assert(cbChunk);
2254
2255 switch (pStream->u8SD)
2256 {
2257 case AC97SOUNDSOURCE_PO_INDEX: /* Output */
2258 {
2259 PDMDevHlpPhysRead(pThis->CTX_SUFF(pDevIns), pRegs->bd.addr,
2260 (uint8_t *)pvBuf + cbTotal, cbChunk);
2261 break;
2262 }
2263
2264 case AC97SOUNDSOURCE_PI_INDEX: /* Input */
2265 case AC97SOUNDSOURCE_MC_INDEX: /* Input */
2266 {
2267 PDMDevHlpPhysWrite(pThis->CTX_SUFF(pDevIns), pRegs->bd.addr,
2268 (uint8_t *)pvBuf + cbTotal, cbChunk);
2269 break;
2270 }
2271
2272 default:
2273 AssertMsgFailed(("Stream #%RU8 not supported\n", pStream->u8SD));
2274 rc = VERR_NOT_SUPPORTED;
2275 break;
2276 }
2277
2278 if (RT_FAILURE(rc))
2279 break;
2280
2281#ifdef AC97_DEBUG_DUMP_PCM_DATA
2282 RTFILE fh;
2283 RTFileOpen(&fh,
2284 pStream->u8SD == AC97SOUNDSOURCE_PO_INDEX
2285 ? AC97_DEBUG_DUMP_PCM_DATA_PATH "ac97DMARead.pcm" : AC97_DEBUG_DUMP_PCM_DATA_PATH "ac97DMAWrite.pcm",
2286 RTFILE_O_OPEN_CREATE | RTFILE_O_APPEND | RTFILE_O_WRITE | RTFILE_O_DENY_NONE);
2287 RTFileWrite(fh, (uint8_t *)pvBuf + cbTotal, cbChunk, NULL);
2288 RTFileClose(fh);
2289#endif
2290
2291 if (cbChunk)
2292 {
2293 cbTotal += cbChunk;
2294 Assert(cbTotal <= cbToProcess);
2295 Assert(cbLeft >= cbChunk);
2296 cbLeft -= cbChunk;
2297 Assert((cbChunk & 1) == 0); /* Else the following shift won't work */
2298
2299 pRegs->picb -= (cbChunk >> 1); /** @todo r=andy Assumes 16bit samples. */
2300 pRegs->bd.addr += cbChunk;
2301 }
2302
2303 LogFlowFunc(("[SD%RU8]: cbChunk=%RU32, cbLeft=%RU32, cbTotal=%RU32, rc=%Rrc\n",
2304 pStream->u8SD, cbChunk, cbLeft, cbTotal, rc));
2305
2306 if (!pRegs->picb)
2307 {
2308 uint32_t new_sr = pRegs->sr & ~AC97_SR_CELV;
2309
2310 if (pRegs->bd.ctl_len & AC97_BD_IOC)
2311 {
2312 new_sr |= AC97_SR_BCIS;
2313 }
2314
2315 if (pRegs->civ == pRegs->lvi)
2316 {
2317 /* Did we run out of data? */
2318 LogFunc(("Underrun CIV (%RU8) == LVI (%RU8)\n", pRegs->civ, pRegs->lvi));
2319
2320 new_sr |= AC97_SR_LVBCI | AC97_SR_DCH | AC97_SR_CELV;
2321 pThis->bup_flag = (pRegs->bd.ctl_len & AC97_BD_BUP) ? BUP_LAST : 0;
2322
2323 rc = VINF_EOF;
2324 }
2325 else
2326 {
2327 pRegs->civ = pRegs->piv;
2328 pRegs->piv = (pRegs->piv + 1) % 32; /** @todo r=andy Define for max BDLEs? */
2329 ichac97StreamFetchBDLE(pThis, pStream);
2330 }
2331
2332 ichac97StreamUpdateSR(pThis, pStream, new_sr);
2333 }
2334
2335 if (/* All data processed? */
2336 rc == VINF_EOF
2337 /* ... or an error occurred? */
2338 || RT_FAILURE(rc))
2339 {
2340 break;
2341 }
2342 }
2343
2344 if (RT_SUCCESS(rc))
2345 {
2346 if (pcbProcessed)
2347 *pcbProcessed = cbTotal;
2348 }
2349
2350 LogFlowFuncLeaveRC(rc);
2351 return rc;
2352}
2353
2354/**
2355 * @callback_method_impl{FNIOMIOPORTIN}
2356 */
2357static DECLCALLBACK(int) ichac97IOPortNABMRead(PPDMDEVINS pDevIns, void *pvUser, RTIOPORT uPort, uint32_t *pu32, unsigned cb)
2358{
2359 RT_NOREF(pDevIns);
2360 PAC97STATE pThis = (PAC97STATE)pvUser;
2361
2362 /* Get the index of the NABMBAR port. */
2363 const uint32_t uPortIdx = uPort - pThis->IOPortBase[1];
2364
2365 PAC97STREAM pStream = ichac97GetStreamFromIdx(pThis, AC97_PORT2IDX(uPortIdx));
2366 PAC97BMREGS pRegs = NULL;
2367
2368 if (pStream) /* Can be NULL, depending on the index (port). */
2369 pRegs = &pStream->Regs;
2370
2371 int rc = VINF_SUCCESS;
2372
2373 switch (cb)
2374 {
2375 case 1:
2376 {
2377 switch (uPortIdx)
2378 {
2379 case AC97_CAS:
2380 /* Codec Access Semaphore Register */
2381 Log3Func(("CAS %d\n", pThis->cas));
2382 *pu32 = pThis->cas;
2383 pThis->cas = 1;
2384 break;
2385 case PI_CIV:
2386 case PO_CIV:
2387 case MC_CIV:
2388 /* Current Index Value Register */
2389 *pu32 = pRegs->civ;
2390 Log3Func(("CIV[%d] -> %#x\n", AC97_PORT2IDX(uPortIdx), *pu32));
2391 break;
2392 case PI_LVI:
2393 case PO_LVI:
2394 case MC_LVI:
2395 /* Last Valid Index Register */
2396 *pu32 = pRegs->lvi;
2397 Log3Func(("LVI[%d] -> %#x\n", AC97_PORT2IDX(uPortIdx), *pu32));
2398 break;
2399 case PI_PIV:
2400 case PO_PIV:
2401 case MC_PIV:
2402 /* Prefetched Index Value Register */
2403 *pu32 = pRegs->piv;
2404 Log3Func(("PIV[%d] -> %#x\n", AC97_PORT2IDX(uPortIdx), *pu32));
2405 break;
2406 case PI_CR:
2407 case PO_CR:
2408 case MC_CR:
2409 /* Control Register */
2410 *pu32 = pRegs->cr;
2411 Log3Func(("CR[%d] -> %#x\n", AC97_PORT2IDX(uPortIdx), *pu32));
2412 break;
2413 case PI_SR:
2414 case PO_SR:
2415 case MC_SR:
2416 /* Status Register (lower part) */
2417 *pu32 = RT_LO_U8(pRegs->sr);
2418 Log3Func(("SRb[%d] -> %#x\n", AC97_PORT2IDX(uPortIdx), *pu32));
2419 break;
2420 default:
2421 *pu32 = UINT32_MAX;
2422 LogFunc(("U nabm readb %#x -> %#x\n", uPort, *pu32));
2423 break;
2424 }
2425 break;
2426 }
2427
2428 case 2:
2429 {
2430 switch (uPortIdx)
2431 {
2432 case PI_SR:
2433 case PO_SR:
2434 case MC_SR:
2435 /* Status Register */
2436 *pu32 = pRegs->sr;
2437 Log3Func(("SR[%d] -> %#x\n", AC97_PORT2IDX(uPortIdx), *pu32));
2438 break;
2439 case PI_PICB:
2440 case PO_PICB:
2441 case MC_PICB:
2442 /* Position in Current Buffer */
2443 *pu32 = pRegs->picb;
2444 Log3Func(("PICB[%d] -> %#x\n", AC97_PORT2IDX(uPortIdx), *pu32));
2445 break;
2446 default:
2447 *pu32 = UINT32_MAX;
2448 LogFunc(("U nabm readw %#x -> %#x\n", uPort, *pu32));
2449 break;
2450 }
2451 break;
2452 }
2453
2454 case 4:
2455 {
2456 switch (uPortIdx)
2457 {
2458 case PI_BDBAR:
2459 case PO_BDBAR:
2460 case MC_BDBAR:
2461 /* Buffer Descriptor Base Address Register */
2462 *pu32 = pRegs->bdbar;
2463 Log3Func(("BMADDR[%d] -> %#x\n", AC97_PORT2IDX(uPortIdx), *pu32));
2464 break;
2465 case PI_CIV:
2466 case PO_CIV:
2467 case MC_CIV:
2468 /* 32-bit access: Current Index Value Register +
2469 * Last Valid Index Register +
2470 * Status Register */
2471 *pu32 = pRegs->civ | (pRegs->lvi << 8) | (pRegs->sr << 16); /** @todo r=andy Use RT_MAKE_U32_FROM_U8. */
2472 Log3Func(("CIV LVI SR[%d] -> %#x, %#x, %#x\n",
2473 AC97_PORT2IDX(uPortIdx), pRegs->civ, pRegs->lvi, pRegs->sr));
2474 break;
2475 case PI_PICB:
2476 case PO_PICB:
2477 case MC_PICB:
2478 /* 32-bit access: Position in Current Buffer Register +
2479 * Prefetched Index Value Register +
2480 * Control Register */
2481 *pu32 = pRegs->picb | (pRegs->piv << 16) | (pRegs->cr << 24); /** @todo r=andy Use RT_MAKE_U32_FROM_U8. */
2482 Log3Func(("PICB PIV CR[%d] -> %#x %#x %#x %#x\n",
2483 AC97_PORT2IDX(uPortIdx), *pu32, pRegs->picb, pRegs->piv, pRegs->cr));
2484 break;
2485 case AC97_GLOB_CNT:
2486 /* Global Control */
2487 *pu32 = pThis->glob_cnt;
2488 Log3Func(("glob_cnt -> %#x\n", *pu32));
2489 break;
2490 case AC97_GLOB_STA:
2491 /* Global Status */
2492 *pu32 = pThis->glob_sta | AC97_GS_S0CR;
2493 Log3Func(("glob_sta -> %#x\n", *pu32));
2494 break;
2495 default:
2496 *pu32 = UINT32_MAX;
2497 LogFunc(("U nabm readl %#x -> %#x\n", uPort, *pu32));
2498 break;
2499 }
2500 break;
2501 }
2502
2503 default:
2504 {
2505 AssertFailed();
2506 rc = VERR_IOM_IOPORT_UNUSED;
2507 }
2508 }
2509
2510 return rc;
2511}
2512
2513/**
2514 * @callback_method_impl{FNIOMIOPORTOUT}
2515 */
2516static DECLCALLBACK(int) ichac97IOPortNABMWrite(PPDMDEVINS pDevIns, void *pvUser, RTIOPORT uPort,
2517 uint32_t u32, unsigned cb)
2518{
2519 RT_NOREF(pDevIns);
2520 PAC97STATE pThis = (PAC97STATE)pvUser;
2521
2522 /* Get the index of the NABMBAR register. */
2523 const uint32_t uPortIdx = uPort - pThis->IOPortBase[1];
2524
2525 PAC97STREAM pStream = ichac97GetStreamFromIdx(pThis, AC97_PORT2IDX(uPortIdx));
2526 PAC97BMREGS pRegs = NULL;
2527
2528 if (pStream) /* Can be NULL, depending on the index (port). */
2529 pRegs = &pStream->Regs;
2530
2531 switch (cb)
2532 {
2533 case 1:
2534 {
2535 switch (uPortIdx)
2536 {
2537 /*
2538 * Last Valid Index.
2539 */
2540 case PI_LVI:
2541 case PO_LVI:
2542 case MC_LVI:
2543 {
2544 if ( (pRegs->cr & AC97_CR_RPBM)
2545 && (pRegs->sr & AC97_SR_DCH))
2546 {
2547 pRegs->sr &= ~(AC97_SR_DCH | AC97_SR_CELV);
2548 pRegs->civ = pRegs->piv;
2549 pRegs->piv = (pRegs->piv + 1) % 32;
2550
2551 ichac97StreamFetchBDLE(pThis, pStream);
2552 }
2553 pRegs->lvi = u32 % 32;
2554 Log3Func(("[SD%RU8] LVI <- %#x\n", pStream->u8SD, u32));
2555 break;
2556 }
2557
2558 /*
2559 * Control Registers.
2560 */
2561 case PI_CR:
2562 case PO_CR:
2563 case MC_CR:
2564 {
2565 Log3Func(("[SD%RU8] CR <- %#x (cr %#x)\n", pStream->u8SD, u32, pRegs->cr));
2566
2567 if (u32 & AC97_CR_RR) /* Busmaster reset. */
2568 {
2569 Log3Func(("[SD%RU8] Reset\n", pStream->u8SD));
2570
2571 /* Make sure that Run/Pause Bus Master bit (RPBM) is cleared (0). */
2572 Assert((pRegs->cr & AC97_CR_RPBM) == 0);
2573
2574 ichac97StreamEnable(pThis, pStream, false /* Disable */);
2575 ichac97StreamReset(pThis, pStream);
2576
2577 ichac97StreamUpdateSR(pThis, pStream, AC97_SR_DCH); /** @todo Do we need to do that? */
2578 }
2579 else
2580 {
2581 pRegs->cr = u32 & AC97_CR_VALID_MASK;
2582
2583 if (!(pRegs->cr & AC97_CR_RPBM))
2584 {
2585 Log3Func(("[SD%RU8] Disable\n", pStream->u8SD));
2586
2587 ichac97StreamEnable(pThis, pStream, false /* fEnable */);
2588
2589 pRegs->sr |= AC97_SR_DCH;
2590 }
2591 else
2592 {
2593 Log3Func(("[SD%RU8] Enable\n", pStream->u8SD));
2594
2595 pRegs->civ = pRegs->piv;
2596 pRegs->piv = (pRegs->piv + 1) % 32;
2597
2598 pRegs->sr &= ~AC97_SR_DCH;
2599
2600 /* Fetch the initial BDLE descriptor. */
2601 ichac97StreamFetchBDLE(pThis, pStream);
2602
2603 ichac97StreamEnable(pThis, pStream, true /* fEnable */);
2604 }
2605 }
2606 break;
2607 }
2608
2609 /*
2610 * Status Registers.
2611 */
2612 case PI_SR:
2613 case PO_SR:
2614 case MC_SR:
2615 {
2616 pRegs->sr |= u32 & ~(AC97_SR_RO_MASK | AC97_SR_WCLEAR_MASK);
2617 ichac97StreamUpdateSR(pThis, pStream, pRegs->sr & ~(u32 & AC97_SR_WCLEAR_MASK));
2618 Log3Func(("[SD%RU8] SR <- %#x (sr %#x)\n", pStream->u8SD, u32, pRegs->sr));
2619 break;
2620 }
2621
2622 default:
2623 LogFunc(("Unimplemented: %#x <- %#x (Byte)\n", uPort, u32));
2624 break;
2625 }
2626 break;
2627 }
2628
2629 case 2:
2630 {
2631 switch (uPortIdx)
2632 {
2633 case PI_SR:
2634 case PO_SR:
2635 case MC_SR:
2636 /* Status Register */
2637 pRegs->sr |= u32 & ~(AC97_SR_RO_MASK | AC97_SR_WCLEAR_MASK);
2638 ichac97StreamUpdateSR(pThis, pStream, pRegs->sr & ~(u32 & AC97_SR_WCLEAR_MASK));
2639 Log3Func(("[SD%RU8] SR <- %#x (sr %#x)\n", pStream->u8SD, u32, pRegs->sr));
2640 break;
2641 default:
2642 LogFunc(("Unimplemented: %#x <- %#x (Word)\n", uPort, u32));
2643 break;
2644 }
2645 break;
2646 }
2647
2648 case 4:
2649 {
2650 switch (uPortIdx)
2651 {
2652 case PI_BDBAR:
2653 case PO_BDBAR:
2654 case MC_BDBAR:
2655 /* Buffer Descriptor list Base Address Register */
2656 pRegs->bdbar = u32 & ~3;
2657 Log3Func(("[SD%RU8] BDBAR <- %#x (bdbar %#x)\n", AC97_PORT2IDX(uPortIdx), u32, pRegs->bdbar));
2658 break;
2659 case AC97_GLOB_CNT:
2660 /* Global Control */
2661 if (u32 & AC97_GC_WR)
2662 ichac97WarmReset(pThis);
2663 if (u32 & AC97_GC_CR)
2664 ichac97ColdReset(pThis);
2665 if (!(u32 & (AC97_GC_WR | AC97_GC_CR)))
2666 pThis->glob_cnt = u32 & AC97_GC_VALID_MASK;
2667 Log3Func(("glob_cnt <- %#x (glob_cnt %#x)\n", u32, pThis->glob_cnt));
2668 break;
2669 case AC97_GLOB_STA:
2670 /* Global Status */
2671 pThis->glob_sta &= ~(u32 & AC97_GS_WCLEAR_MASK);
2672 pThis->glob_sta |= (u32 & ~(AC97_GS_WCLEAR_MASK | AC97_GS_RO_MASK)) & AC97_GS_VALID_MASK;
2673 Log3Func(("glob_sta <- %#x (glob_sta %#x)\n", u32, pThis->glob_sta));
2674 break;
2675 default:
2676 LogFunc(("Unimplemented: %#x <- %#x (DWord)\n", uPort, u32));
2677 break;
2678 }
2679 break;
2680 }
2681
2682 default:
2683 AssertMsgFailed(("Port=%#x cb=%d u32=%#x\n", uPort, cb, u32));
2684 break;
2685 }
2686
2687 return VINF_SUCCESS;
2688}
2689
2690/**
2691 * @callback_method_impl{FNIOMIOPORTIN}
2692 */
2693static DECLCALLBACK(int) ichac97IOPortNAMRead(PPDMDEVINS pDevIns, void *pvUser, RTIOPORT uPort, uint32_t *pu32, unsigned cb)
2694{
2695 RT_NOREF(pDevIns);
2696 PAC97STATE pThis = (PAC97STATE)pvUser;
2697
2698 int rc = VINF_SUCCESS;
2699
2700 switch (cb)
2701 {
2702 case 1:
2703 {
2704 Log3Func(("U nam readb %#x\n", uPort));
2705 pThis->cas = 0;
2706 *pu32 = UINT32_MAX;
2707 break;
2708 }
2709
2710 case 2:
2711 {
2712 uint32_t index = uPort - pThis->IOPortBase[0];
2713 *pu32 = UINT32_MAX;
2714 pThis->cas = 0;
2715 switch (index)
2716 {
2717 default:
2718 *pu32 = ichac97MixerGet(pThis, index);
2719 Log3Func(("nam readw %#x -> %#x\n", uPort, *pu32));
2720 break;
2721 }
2722 break;
2723 }
2724
2725 case 4:
2726 {
2727 Log3Func(("U nam readl %#x\n", uPort));
2728 pThis->cas = 0;
2729 *pu32 = UINT32_MAX;
2730 break;
2731 }
2732
2733 default:
2734 {
2735 AssertFailed();
2736 rc = VERR_IOM_IOPORT_UNUSED;
2737 }
2738 }
2739
2740 return rc;
2741}
2742
2743/**
2744 * @callback_method_impl{FNIOMIOPORTOUT}
2745 */
2746static DECLCALLBACK(int) ichac97IOPortNAMWrite(PPDMDEVINS pDevIns, void *pvUser, RTIOPORT uPort, uint32_t u32, unsigned cb)
2747{
2748 RT_NOREF(pDevIns);
2749 PAC97STATE pThis = (PAC97STATE)pvUser;
2750
2751 switch (cb)
2752 {
2753 case 1:
2754 {
2755 Log3Func(("U nam writeb %#x <- %#x\n", uPort, u32));
2756 pThis->cas = 0;
2757 break;
2758 }
2759
2760 case 2:
2761 {
2762 uint32_t index = uPort - pThis->IOPortBase[0];
2763 pThis->cas = 0;
2764 switch (index)
2765 {
2766 case AC97_Reset:
2767 ichac97Reset(pThis->CTX_SUFF(pDevIns));
2768 break;
2769 case AC97_Powerdown_Ctrl_Stat:
2770 u32 &= ~0xf;
2771 u32 |= ichac97MixerGet(pThis, index) & 0xf;
2772 ichac97MixerSet(pThis, index, u32);
2773 break;
2774 case AC97_Master_Volume_Mute:
2775 if (pThis->uCodecModel == AC97_CODEC_AD1980)
2776 {
2777 if (ichac97MixerGet(pThis, AC97_AD_Misc) & AC97_AD_MISC_LOSEL)
2778 break; /* Register controls surround (rear), do nothing. */
2779 }
2780 ichac97MixerSetVolume(pThis, index, PDMAUDIOMIXERCTL_VOLUME_MASTER, u32);
2781 break;
2782 case AC97_Headphone_Volume_Mute:
2783 if (pThis->uCodecModel == AC97_CODEC_AD1980)
2784 {
2785 if (ichac97MixerGet(pThis, AC97_AD_Misc) & AC97_AD_MISC_HPSEL)
2786 {
2787 /* Register controls PCM (front) outputs. */
2788 ichac97MixerSetVolume(pThis, index, PDMAUDIOMIXERCTL_VOLUME_MASTER, u32);
2789 }
2790 }
2791 break;
2792 case AC97_PCM_Out_Volume_Mute:
2793 ichac97MixerSetVolume(pThis, index, PDMAUDIOMIXERCTL_FRONT, u32);
2794 break;
2795 case AC97_Line_In_Volume_Mute:
2796 ichac97MixerSetVolume(pThis, index, PDMAUDIOMIXERCTL_LINE_IN, u32);
2797 break;
2798 case AC97_Record_Select:
2799 ichac97MixerRecordSelect(pThis, u32);
2800 break;
2801 case AC97_Vendor_ID1:
2802 case AC97_Vendor_ID2:
2803 LogFunc(("Attempt to write vendor ID to %#x\n", u32));
2804 break;
2805 case AC97_Extended_Audio_ID:
2806 LogFunc(("Attempt to write extended audio ID to %#x\n", u32));
2807 break;
2808 case AC97_Extended_Audio_Ctrl_Stat:
2809 if (!(u32 & AC97_EACS_VRA))
2810 {
2811 ichac97MixerSet(pThis, AC97_PCM_Front_DAC_Rate, 48000);
2812 ichac97StreamReOpen(pThis, &pThis->StreamOut);
2813
2814 ichac97MixerSet(pThis, AC97_PCM_LR_ADC_Rate, 48000);
2815 ichac97StreamReOpen(pThis, &pThis->StreamLineIn);
2816 }
2817 else
2818 LogRel2(("AC97: Variable rate audio (VRA) is not supported\n"));
2819
2820 if (!(u32 & AC97_EACS_VRM))
2821 {
2822 ichac97MixerSet(pThis, AC97_MIC_ADC_Rate, 48000);
2823 ichac97StreamReOpen(pThis, &pThis->StreamMicIn);
2824 }
2825 else
2826 LogRel2(("AC97: Variable rate microphone audio (VRM) is not supported\n"));
2827
2828 LogFunc(("Setting extended audio control to %#x\n", u32));
2829 ichac97MixerSet(pThis, AC97_Extended_Audio_Ctrl_Stat, u32);
2830 break;
2831 case AC97_PCM_Front_DAC_Rate:
2832 if (ichac97MixerGet(pThis, AC97_Extended_Audio_Ctrl_Stat) & AC97_EACS_VRA)
2833 {
2834 ichac97MixerSet(pThis, index, u32);
2835 LogFunc(("Set front DAC rate to %RU32\n", u32));
2836 ichac97StreamReOpen(pThis, &pThis->StreamOut);
2837 }
2838 else
2839 AssertMsgFailed(("Attempt to set front DAC rate to %RU32, but VRA is not set\n", u32));
2840 break;
2841 case AC97_MIC_ADC_Rate:
2842 if (ichac97MixerGet(pThis, AC97_Extended_Audio_Ctrl_Stat) & AC97_EACS_VRM)
2843 {
2844 ichac97MixerSet(pThis, index, u32);
2845 LogFunc(("Set MIC ADC rate to %RU32\n", u32));
2846 ichac97StreamReOpen(pThis, &pThis->StreamMicIn);
2847 }
2848 else
2849 AssertMsgFailed(("Attempt to set MIC ADC rate to %RU32, but VRM is not set\n", u32));
2850 break;
2851 case AC97_PCM_LR_ADC_Rate:
2852 if (ichac97MixerGet(pThis, AC97_Extended_Audio_Ctrl_Stat) & AC97_EACS_VRA)
2853 {
2854 ichac97MixerSet(pThis, index, u32);
2855 LogFunc(("Set front LR ADC rate to %RU32\n", u32));
2856 ichac97StreamReOpen(pThis, &pThis->StreamLineIn);
2857 }
2858 else
2859 AssertMsgFailed(("Attempt to set LR ADC rate to %RU32, but VRA is not set\n", u32));
2860 break;
2861 default:
2862 LogFunc(("U nam writew %#x <- %#x\n", uPort, u32));
2863 ichac97MixerSet(pThis, index, u32);
2864 break;
2865 }
2866 break;
2867 }
2868
2869 case 4:
2870 {
2871 Log3Func(("U nam writel %#x <- %#x\n", uPort, u32));
2872 pThis->cas = 0;
2873 break;
2874 }
2875
2876 default:
2877 AssertMsgFailed(("Port=%#x cb=%d u32=%#x\n", uPort, cb, u32));
2878 break;
2879 }
2880
2881 return VINF_SUCCESS;
2882}
2883
2884
2885/**
2886 * @callback_method_impl{FNPCIIOREGIONMAP}
2887 */
2888static DECLCALLBACK(int) ichac97IOPortMap(PPDMDEVINS pDevIns, PPDMPCIDEV pPciDev, uint32_t iRegion,
2889 RTGCPHYS GCPhysAddress, RTGCPHYS cb, PCIADDRESSSPACE enmType)
2890{
2891 RT_NOREF(cb, enmType);
2892 PAC97STATE pThis = RT_FROM_MEMBER(pPciDev, AC97STATE, PciDev);
2893 RTIOPORT Port = (RTIOPORT)GCPhysAddress;
2894
2895 Assert(enmType == PCI_ADDRESS_SPACE_IO);
2896 Assert(cb >= 0x20);
2897
2898 if (iRegion > 1) /* We support 2 regions max. at the moment. */
2899 return VERR_INVALID_PARAMETER;
2900
2901 int rc;
2902 if (iRegion == 0)
2903 rc = PDMDevHlpIOPortRegister(pDevIns, Port, 256, pThis,
2904 ichac97IOPortNAMWrite, ichac97IOPortNAMRead,
2905 NULL, NULL, "ICHAC97 NAM");
2906 else
2907 rc = PDMDevHlpIOPortRegister(pDevIns, Port, 64, pThis,
2908 ichac97IOPortNABMWrite, ichac97IOPortNABMRead,
2909 NULL, NULL, "ICHAC97 NABM");
2910 if (RT_FAILURE(rc))
2911 return rc;
2912
2913 pThis->IOPortBase[iRegion] = Port;
2914 return VINF_SUCCESS;
2915}
2916
2917#ifdef IN_RING3
2918/**
2919 * Saves (serializes) an AC'97 stream using SSM.
2920 *
2921 * @returns IPRT status code.
2922 * @param pDevIns Device instance.
2923 * @param pSSM Saved state manager (SSM) handle to use.
2924 * @param pStream AC'97 stream to save.
2925 */
2926static int ichac97SaveStream(PPDMDEVINS pDevIns, PSSMHANDLE pSSM, PAC97STREAM pStream)
2927{
2928 RT_NOREF(pDevIns);
2929 PAC97BMREGS pRegs = &pStream->Regs;
2930
2931 SSMR3PutU32(pSSM, pRegs->bdbar);
2932 SSMR3PutU8( pSSM, pRegs->civ);
2933 SSMR3PutU8( pSSM, pRegs->lvi);
2934 SSMR3PutU16(pSSM, pRegs->sr);
2935 SSMR3PutU16(pSSM, pRegs->picb);
2936 SSMR3PutU8( pSSM, pRegs->piv);
2937 SSMR3PutU8( pSSM, pRegs->cr);
2938 SSMR3PutS32(pSSM, pRegs->bd_valid);
2939 SSMR3PutU32(pSSM, pRegs->bd.addr);
2940 SSMR3PutU32(pSSM, pRegs->bd.ctl_len);
2941
2942 return VINF_SUCCESS;
2943}
2944
2945/**
2946 * @callback_method_impl{FNSSMDEVSAVEEXEC}
2947 */
2948static DECLCALLBACK(int) ichac97SaveExec(PPDMDEVINS pDevIns, PSSMHANDLE pSSM)
2949{
2950 PAC97STATE pThis = PDMINS_2_DATA(pDevIns, PAC97STATE);
2951
2952 LogFlowFuncEnter();
2953
2954 SSMR3PutU32(pSSM, pThis->glob_cnt);
2955 SSMR3PutU32(pSSM, pThis->glob_sta);
2956 SSMR3PutU32(pSSM, pThis->cas);
2957
2958 /** @todo r=andy For the next saved state version, add unique stream identifiers and a stream count. */
2959 /* Note: The order the streams are saved here is critical, so don't touch. */
2960 int rc2 = ichac97SaveStream(pDevIns, pSSM, &pThis->StreamLineIn);
2961 AssertRC(rc2);
2962 rc2 = ichac97SaveStream(pDevIns, pSSM, &pThis->StreamOut);
2963 AssertRC(rc2);
2964 rc2 = ichac97SaveStream(pDevIns, pSSM, &pThis->StreamMicIn);
2965 AssertRC(rc2);
2966
2967 SSMR3PutMem(pSSM, pThis->mixer_data, sizeof(pThis->mixer_data));
2968
2969 uint8_t active[AC97SOUNDSOURCE_LAST_INDEX];
2970
2971 active[AC97SOUNDSOURCE_PI_INDEX] = ichac97StreamIsEnabled(pThis, &pThis->StreamLineIn) ? 1 : 0;
2972 active[AC97SOUNDSOURCE_PO_INDEX] = ichac97StreamIsEnabled(pThis, &pThis->StreamOut) ? 1 : 0;
2973 active[AC97SOUNDSOURCE_MC_INDEX] = ichac97StreamIsEnabled(pThis, &pThis->StreamMicIn) ? 1 : 0;
2974
2975 SSMR3PutMem(pSSM, active, sizeof(active));
2976
2977 LogFlowFuncLeaveRC(VINF_SUCCESS);
2978 return VINF_SUCCESS;
2979}
2980
2981/**
2982 * Loads an AC'97 stream from SSM.
2983 *
2984 * @returns IPRT status code.
2985 * @param pDevIns Device instance.
2986 * @param pSSM Saved state manager (SSM) handle to use.
2987 * @param pStream AC'97 stream to load.
2988 */
2989static int ichac97LoadStream(PPDMDEVINS pDevIns, PSSMHANDLE pSSM, PAC97STREAM pStream)
2990{
2991 RT_NOREF(pDevIns);
2992 PAC97BMREGS pRegs = &pStream->Regs;
2993
2994 SSMR3GetU32(pSSM, &pRegs->bdbar);
2995 SSMR3GetU8( pSSM, &pRegs->civ);
2996 SSMR3GetU8( pSSM, &pRegs->lvi);
2997 SSMR3GetU16(pSSM, &pRegs->sr);
2998 SSMR3GetU16(pSSM, &pRegs->picb);
2999 SSMR3GetU8( pSSM, &pRegs->piv);
3000 SSMR3GetU8( pSSM, &pRegs->cr);
3001 SSMR3GetS32(pSSM, &pRegs->bd_valid);
3002 SSMR3GetU32(pSSM, &pRegs->bd.addr);
3003 SSMR3GetU32(pSSM, &pRegs->bd.ctl_len);
3004
3005 return VINF_SUCCESS;
3006}
3007
3008/**
3009 * @callback_method_impl{FNSSMDEVLOADEXEC}
3010 */
3011static DECLCALLBACK(int) ichac97LoadExec(PPDMDEVINS pDevIns, PSSMHANDLE pSSM, uint32_t uVersion, uint32_t uPass)
3012{
3013 PAC97STATE pThis = PDMINS_2_DATA(pDevIns, PAC97STATE);
3014
3015 LogRel2(("ichac97LoadExec: uVersion=%RU32, uPass=0x%x\n", uVersion, uPass));
3016
3017 AssertMsgReturn (uVersion == AC97_SSM_VERSION, ("%RU32\n", uVersion), VERR_SSM_UNSUPPORTED_DATA_UNIT_VERSION);
3018 Assert(uPass == SSM_PASS_FINAL); NOREF(uPass);
3019
3020 SSMR3GetU32(pSSM, &pThis->glob_cnt);
3021 SSMR3GetU32(pSSM, &pThis->glob_sta);
3022 SSMR3GetU32(pSSM, &pThis->cas);
3023
3024 /** @todo r=andy For the next saved state version, add unique stream identifiers and a stream count. */
3025 /* Note: The order the streams are loaded here is critical, so don't touch. */
3026 int rc2 = ichac97LoadStream(pDevIns, pSSM, &pThis->StreamLineIn);
3027 AssertRC(rc2);
3028 rc2 = ichac97LoadStream(pDevIns, pSSM, &pThis->StreamOut);
3029 AssertRC(rc2);
3030 rc2 = ichac97LoadStream(pDevIns, pSSM, &pThis->StreamMicIn);
3031 AssertRC(rc2);
3032
3033 SSMR3GetMem(pSSM, pThis->mixer_data, sizeof(pThis->mixer_data));
3034
3035 /** @todo r=andy Stream IDs are hardcoded to certain streams. */
3036 uint8_t uaStrmsActive[AC97SOUNDSOURCE_LAST_INDEX];
3037 SSMR3GetMem(pSSM, uaStrmsActive, sizeof(uaStrmsActive));
3038
3039 ichac97MixerRecordSelect(pThis, ichac97MixerGet(pThis, AC97_Record_Select));
3040# define V_(a, b) ichac97MixerSetVolume(pThis, a, b, ichac97MixerGet(pThis, a))
3041 V_(AC97_Master_Volume_Mute, PDMAUDIOMIXERCTL_VOLUME_MASTER);
3042 V_(AC97_PCM_Out_Volume_Mute, PDMAUDIOMIXERCTL_FRONT);
3043 V_(AC97_Line_In_Volume_Mute, PDMAUDIOMIXERCTL_LINE_IN);
3044 V_(AC97_Mic_Volume_Mute, PDMAUDIOMIXERCTL_MIC_IN);
3045# undef V_
3046 if (pThis->uCodecModel == AC97_CODEC_AD1980)
3047 if (ichac97MixerGet(pThis, AC97_AD_Misc) & AC97_AD_MISC_HPSEL)
3048 ichac97MixerSetVolume(pThis, AC97_Headphone_Volume_Mute, PDMAUDIOMIXERCTL_VOLUME_MASTER,
3049 ichac97MixerGet(pThis, AC97_Headphone_Volume_Mute));
3050
3051 /** @todo r=andy Stream IDs are hardcoded to certain streams. */
3052 rc2 = ichac97StreamEnable(pThis, &pThis->StreamLineIn, RT_BOOL(uaStrmsActive[AC97SOUNDSOURCE_PI_INDEX]));
3053 if (RT_SUCCESS(rc2))
3054 rc2 = ichac97StreamEnable(pThis, &pThis->StreamMicIn, RT_BOOL(uaStrmsActive[AC97SOUNDSOURCE_MC_INDEX]));
3055 if (RT_SUCCESS(rc2))
3056 rc2 = ichac97StreamEnable(pThis, &pThis->StreamOut, RT_BOOL(uaStrmsActive[AC97SOUNDSOURCE_PO_INDEX]));
3057
3058 pThis->bup_flag = 0;
3059 pThis->last_samp = 0;
3060
3061 return VINF_SUCCESS;
3062}
3063
3064
3065/**
3066 * @interface_method_impl{PDMIBASE,pfnQueryInterface}
3067 */
3068static DECLCALLBACK(void *) ichac97QueryInterface(struct PDMIBASE *pInterface, const char *pszIID)
3069{
3070 PAC97STATE pThis = RT_FROM_MEMBER(pInterface, AC97STATE, IBase);
3071 Assert(&pThis->IBase == pInterface);
3072
3073 PDMIBASE_RETURN_INTERFACE(pszIID, PDMIBASE, &pThis->IBase);
3074 return NULL;
3075}
3076
3077
3078/**
3079 * Powers off the device.
3080 *
3081 * @param pDevIns Device instance to power off.
3082 */
3083static DECLCALLBACK(void) ichac97PowerOff(PPDMDEVINS pDevIns)
3084{
3085 PAC97STATE pThis = PDMINS_2_DATA(pDevIns, PAC97STATE);
3086
3087 LogRel2(("AC97: Powering off ...\n"));
3088
3089 /* Note: Involves mixer stream / sink destruction, so also do this here
3090 * instead of in ichac97Destruct(). */
3091 ichac97StreamsDestroy(pThis);
3092
3093 /**
3094 * Note: Destroy the mixer while powering off and *not* in ichac97Destruct,
3095 * giving the mixer the chance to release any references held to
3096 * PDM audio streams it maintains.
3097 */
3098 if (pThis->pMixer)
3099 {
3100 AudioMixerDestroy(pThis->pMixer);
3101 pThis->pMixer = NULL;
3102 }
3103}
3104
3105
3106/**
3107 * @interface_method_impl{PDMDEVREG,pfnReset}
3108 *
3109 * @remarks The original sources didn't install a reset handler, but it seems to
3110 * make sense to me so we'll do it.
3111 */
3112static DECLCALLBACK(void) ichac97Reset(PPDMDEVINS pDevIns)
3113{
3114 PAC97STATE pThis = PDMINS_2_DATA(pDevIns, PAC97STATE);
3115
3116 LogFlowFuncEnter();
3117
3118 /*
3119 * Reset the mixer too. The Windows XP driver seems to rely on
3120 * this. At least it wants to read the vendor id before it resets
3121 * the codec manually.
3122 */
3123 ichac97MixerReset(pThis);
3124
3125 /*
3126 * Reset all streams.
3127 */
3128 ichac97StreamEnable(pThis, &pThis->StreamLineIn, false /* Disable */);
3129 ichac97StreamReset(pThis, &pThis->StreamLineIn);
3130
3131 ichac97StreamEnable(pThis, &pThis->StreamMicIn, false /* Disable */);
3132 ichac97StreamReset(pThis, &pThis->StreamMicIn);
3133
3134 ichac97StreamEnable(pThis, &pThis->StreamOut, false /* Disable */);
3135 ichac97StreamReset(pThis, &pThis->StreamOut);
3136
3137 LogRel(("AC97: Reset\n"));
3138}
3139
3140
3141/**
3142 * @interface_method_impl{PDMDEVREG,pfnDestruct}
3143 */
3144static DECLCALLBACK(int) ichac97Destruct(PPDMDEVINS pDevIns)
3145{
3146 PAC97STATE pThis = PDMINS_2_DATA(pDevIns, PAC97STATE);
3147
3148 LogFlowFuncEnter();
3149
3150 PAC97DRIVER pDrv, pDrvNext;
3151 RTListForEachSafe(&pThis->lstDrv, pDrv, pDrvNext, AC97DRIVER, Node)
3152 {
3153 RTListNodeRemove(&pDrv->Node);
3154 RTMemFree(pDrv);
3155 }
3156
3157 /* Sanity. */
3158 Assert(RTListIsEmpty(&pThis->lstDrv));
3159
3160 int rc;
3161#ifndef VBOX_WITH_AUDIO_AC97_CALLBACKS
3162 rc = RTCritSectDelete(&pThis->csTimer);
3163#else
3164 rc = VINF_SUCCESS;
3165#endif
3166
3167 LogFlowFuncLeaveRC(rc);
3168 return rc;
3169}
3170
3171
3172/**
3173 * Attach command, internal version.
3174 *
3175 * This is called to let the device attach to a driver for a specified LUN
3176 * during runtime. This is not called during VM construction, the device
3177 * constructor has to attach to all the available drivers.
3178 *
3179 * @returns VBox status code.
3180 * @param pDevIns The device instance.
3181 * @param pDrv Driver to (re-)use for (re-)attaching to.
3182 * If NULL is specified, a new driver will be created and appended
3183 * to the driver list.
3184 * @param uLUN The logical unit which is being detached.
3185 * @param fFlags Flags, combination of the PDMDEVATT_FLAGS_* \#defines.
3186 */
3187static DECLCALLBACK(int) ichac97AttachInternal(PPDMDEVINS pDevIns, PAC97DRIVER pDrv, unsigned uLUN, uint32_t fFlags)
3188{
3189 RT_NOREF(fFlags);
3190 PAC97STATE pThis = PDMINS_2_DATA(pDevIns, PAC97STATE);
3191
3192 /*
3193 * Attach driver.
3194 */
3195 char *pszDesc = NULL;
3196 if (RTStrAPrintf(&pszDesc, "Audio driver port (AC'97) for LUN #%u", uLUN) <= 0)
3197 AssertReleaseMsgReturn(pszDesc,
3198 ("Not enough memory for AC'97 driver port description of LUN #%u\n", uLUN),
3199 VERR_NO_MEMORY);
3200
3201 PPDMIBASE pDrvBase;
3202 int rc = PDMDevHlpDriverAttach(pDevIns, uLUN,
3203 &pThis->IBase, &pDrvBase, pszDesc);
3204 if (RT_SUCCESS(rc))
3205 {
3206 if (pDrv == NULL)
3207 pDrv = (PAC97DRIVER)RTMemAllocZ(sizeof(AC97DRIVER));
3208 if (pDrv)
3209 {
3210 pDrv->pDrvBase = pDrvBase;
3211 pDrv->pConnector = PDMIBASE_QUERY_INTERFACE(pDrvBase, PDMIAUDIOCONNECTOR);
3212 AssertMsg(pDrv->pConnector != NULL, ("Configuration error: LUN #%u has no host audio interface, rc=%Rrc\n", uLUN, rc));
3213 pDrv->pAC97State = pThis;
3214 pDrv->uLUN = uLUN;
3215
3216 /*
3217 * For now we always set the driver at LUN 0 as our primary
3218 * host backend. This might change in the future.
3219 */
3220 if (pDrv->uLUN == 0)
3221 pDrv->Flags |= PDMAUDIODRVFLAGS_PRIMARY;
3222
3223 LogFunc(("LUN#%RU8: pCon=%p, drvFlags=0x%x\n", uLUN, pDrv->pConnector, pDrv->Flags));
3224
3225 /* Attach to driver list if not attached yet. */
3226 if (!pDrv->fAttached)
3227 {
3228 RTListAppend(&pThis->lstDrv, &pDrv->Node);
3229 pDrv->fAttached = true;
3230 }
3231 }
3232 else
3233 rc = VERR_NO_MEMORY;
3234 }
3235 else if (rc == VERR_PDM_NO_ATTACHED_DRIVER)
3236 LogFunc(("No attached driver for LUN #%u\n", uLUN));
3237
3238 if (RT_FAILURE(rc))
3239 {
3240 /* Only free this string on failure;
3241 * must remain valid for the live of the driver instance. */
3242 RTStrFree(pszDesc);
3243 }
3244
3245 LogFunc(("iLUN=%u, fFlags=0x%x, rc=%Rrc\n", uLUN, fFlags, rc));
3246 return rc;
3247}
3248
3249
3250/**
3251 * Attach command.
3252 *
3253 * This is called to let the device attach to a driver for a specified LUN
3254 * during runtime. This is not called during VM construction, the device
3255 * constructor has to attach to all the available drivers.
3256 *
3257 * @returns VBox status code.
3258 * @param pDevIns The device instance.
3259 * @param uLUN The logical unit which is being detached.
3260 * @param fFlags Flags, combination of the PDMDEVATT_FLAGS_* \#defines.
3261 */
3262static DECLCALLBACK(int) ichac97Attach(PPDMDEVINS pDevIns, unsigned uLUN, uint32_t fFlags)
3263{
3264 return ichac97AttachInternal(pDevIns, NULL /* pDrv */, uLUN, fFlags);
3265}
3266
3267static DECLCALLBACK(void) ichac97Detach(PPDMDEVINS pDevIns, unsigned uLUN, uint32_t fFlags)
3268{
3269 RT_NOREF(pDevIns, uLUN, fFlags);
3270 LogFunc(("iLUN=%u, fFlags=0x%x\n", uLUN, fFlags));
3271}
3272
3273/**
3274 * Re-attach.
3275 *
3276 * @returns VBox status code.
3277 * @param pThis Device instance.
3278 * @param pDrv Driver instance used for attaching to.
3279 * If NULL is specified, a new driver will be created and appended
3280 * to the driver list.
3281 * @param uLUN The logical unit which is being re-detached.
3282 * @param pszDriver Driver name.
3283 */
3284static int ichac97Reattach(PAC97STATE pThis, PAC97DRIVER pDrv, uint8_t uLUN, const char *pszDriver)
3285{
3286 AssertPtrReturn(pThis, VERR_INVALID_POINTER);
3287 AssertPtrReturn(pszDriver, VERR_INVALID_POINTER);
3288
3289 PVM pVM = PDMDevHlpGetVM(pThis->pDevInsR3);
3290 PCFGMNODE pRoot = CFGMR3GetRoot(pVM);
3291 PCFGMNODE pDev0 = CFGMR3GetChild(pRoot, "Devices/ichac97/0/");
3292
3293 /* Remove LUN branch. */
3294 CFGMR3RemoveNode(CFGMR3GetChildF(pDev0, "LUN#%u/", uLUN));
3295
3296 if (pDrv)
3297 {
3298 /* Re-use a driver instance => detach the driver before. */
3299 int rc = PDMDevHlpDriverDetach(pThis->pDevInsR3, PDMIBASE_2_PDMDRV(pDrv->pDrvBase), 0 /* fFlags */);
3300 if (RT_FAILURE(rc))
3301 return rc;
3302 }
3303
3304#define RC_CHECK() if (RT_FAILURE(rc)) { AssertReleaseRC(rc); break; }
3305
3306 int rc;
3307 do
3308 {
3309 PCFGMNODE pLunL0;
3310 rc = CFGMR3InsertNodeF(pDev0, &pLunL0, "LUN#%u/", uLUN); RC_CHECK();
3311 rc = CFGMR3InsertString(pLunL0, "Driver", "AUDIO"); RC_CHECK();
3312 rc = CFGMR3InsertNode(pLunL0, "Config/", NULL); RC_CHECK();
3313
3314 PCFGMNODE pLunL1, pLunL2;
3315 rc = CFGMR3InsertNode (pLunL0, "AttachedDriver/", &pLunL1); RC_CHECK();
3316 rc = CFGMR3InsertNode (pLunL1, "Config/", &pLunL2); RC_CHECK();
3317 rc = CFGMR3InsertString(pLunL1, "Driver", pszDriver); RC_CHECK();
3318
3319 rc = CFGMR3InsertString(pLunL2, "AudioDriver", pszDriver); RC_CHECK();
3320
3321 } while (0);
3322
3323 if (RT_SUCCESS(rc))
3324 rc = ichac97AttachInternal(pThis->pDevInsR3, pDrv, uLUN, 0 /* fFlags */);
3325
3326 LogFunc(("pThis=%p, uLUN=%u, pszDriver=%s, rc=%Rrc\n", pThis, uLUN, pszDriver, rc));
3327
3328#undef RC_CHECK
3329
3330 return rc;
3331}
3332
3333/**
3334 * @interface_method_impl{PDMDEVREG,pfnConstruct}
3335 */
3336static DECLCALLBACK(int) ichac97Construct(PPDMDEVINS pDevIns, int iInstance, PCFGMNODE pCfg)
3337{
3338 RT_NOREF(iInstance);
3339 PAC97STATE pThis = PDMINS_2_DATA(pDevIns, PAC97STATE);
3340
3341 /* NB: This must be done *before* any possible failure (and running the destructor). */
3342 RTListInit(&pThis->lstDrv);
3343
3344 Assert(iInstance == 0);
3345 PDMDEV_CHECK_VERSIONS_RETURN(pDevIns);
3346
3347 /*
3348 * Validations.
3349 */
3350 if (!CFGMR3AreValuesValid(pCfg,
3351 "Codec\0"
3352 "TimerHz\0"))
3353 return PDMDEV_SET_ERROR(pDevIns, VERR_PDM_DEVINS_UNKNOWN_CFG_VALUES,
3354 N_("Invalid configuration for the AC'97 device"));
3355
3356 /*
3357 * Read config data.
3358 */
3359 char szCodec[20];
3360 int rc = CFGMR3QueryStringDef(pCfg, "Codec", &szCodec[0], sizeof(szCodec), "STAC9700");
3361 if (RT_FAILURE(rc))
3362 return PDMDEV_SET_ERROR(pDevIns, VERR_PDM_DEVINS_UNKNOWN_CFG_VALUES,
3363 N_("AC'97 configuration error: Querying \"Codec\" as string failed"));
3364
3365#ifndef VBOX_WITH_AUDIO_AC97_CALLBACKS
3366 uint16_t uTimerHz;
3367 rc = CFGMR3QueryU16Def(pCfg, "TimerHz", &uTimerHz, AC97_TIMER_HZ /* Default value, if not set. */);
3368 if (RT_FAILURE(rc))
3369 return PDMDEV_SET_ERROR(pDevIns, rc,
3370 N_("AC'97 configuration error: failed to read Hertz (Hz) rate as unsigned integer"));
3371#endif
3372
3373 /*
3374 * The AD1980 codec (with corresponding PCI subsystem vendor ID) is whitelisted
3375 * in the Linux kernel; Linux makes no attempt to measure the data rate and assumes
3376 * 48 kHz rate, which is exactly what we need. Same goes for AD1981B.
3377 */
3378 if (!strcmp(szCodec, "STAC9700"))
3379 pThis->uCodecModel = AC97_CODEC_STAC9700;
3380 else if (!strcmp(szCodec, "AD1980"))
3381 pThis->uCodecModel = AC97_CODEC_AD1980;
3382 else if (!strcmp(szCodec, "AD1981B"))
3383 pThis->uCodecModel = AC97_CODEC_AD1981B;
3384 else
3385 {
3386 return PDMDevHlpVMSetError(pDevIns, VERR_PDM_DEVINS_UNKNOWN_CFG_VALUES, RT_SRC_POS,
3387 N_("AC'97 configuration error: The \"Codec\" value \"%s\" is unsupported"),
3388 szCodec);
3389 }
3390
3391 /*
3392 * Initialize data (most of it anyway).
3393 */
3394 pThis->pDevInsR3 = pDevIns;
3395 /* IBase */
3396 pThis->IBase.pfnQueryInterface = ichac97QueryInterface;
3397
3398 /* PCI Device (the assertions will be removed later) */
3399 PCIDevSetVendorId (&pThis->PciDev, 0x8086); /* 00 ro - intel. */ Assert(pThis->PciDev.abConfig[0x00] == 0x86); Assert(pThis->PciDev.abConfig[0x01] == 0x80);
3400 PCIDevSetDeviceId (&pThis->PciDev, 0x2415); /* 02 ro - 82801 / 82801aa(?). */ Assert(pThis->PciDev.abConfig[0x02] == 0x15); Assert(pThis->PciDev.abConfig[0x03] == 0x24);
3401 PCIDevSetCommand (&pThis->PciDev, 0x0000); /* 04 rw,ro - pcicmd. */ Assert(pThis->PciDev.abConfig[0x04] == 0x00); Assert(pThis->PciDev.abConfig[0x05] == 0x00);
3402 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);
3403 PCIDevSetRevisionId (&pThis->PciDev, 0x01); /* 08 ro - rid. */ Assert(pThis->PciDev.abConfig[0x08] == 0x01);
3404 PCIDevSetClassProg (&pThis->PciDev, 0x00); /* 09 ro - pi. */ Assert(pThis->PciDev.abConfig[0x09] == 0x00);
3405 PCIDevSetClassSub (&pThis->PciDev, 0x01); /* 0a ro - scc; 01 == Audio. */ Assert(pThis->PciDev.abConfig[0x0a] == 0x01);
3406 PCIDevSetClassBase (&pThis->PciDev, 0x04); /* 0b ro - bcc; 04 == multimedia. */ Assert(pThis->PciDev.abConfig[0x0b] == 0x04);
3407 PCIDevSetHeaderType (&pThis->PciDev, 0x00); /* 0e ro - headtyp. */ Assert(pThis->PciDev.abConfig[0x0e] == 0x00);
3408 PCIDevSetBaseAddress (&pThis->PciDev, 0, /* 10 rw - nambar - native audio mixer base. */
3409 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);
3410 PCIDevSetBaseAddress (&pThis->PciDev, 1, /* 14 rw - nabmbar - native audio bus mastering. */
3411 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);
3412 PCIDevSetInterruptLine (&pThis->PciDev, 0x00); /* 3c rw. */ Assert(pThis->PciDev.abConfig[0x3c] == 0x00);
3413 PCIDevSetInterruptPin (&pThis->PciDev, 0x01); /* 3d ro - INTA#. */ Assert(pThis->PciDev.abConfig[0x3d] == 0x01);
3414
3415 if (pThis->uCodecModel == AC97_CODEC_AD1980)
3416 {
3417 PCIDevSetSubSystemVendorId(&pThis->PciDev, 0x1028); /* 2c ro - Dell.) */
3418 PCIDevSetSubSystemId (&pThis->PciDev, 0x0177); /* 2e ro. */
3419 }
3420 else if (pThis->uCodecModel == AC97_CODEC_AD1981B)
3421 {
3422 PCIDevSetSubSystemVendorId(&pThis->PciDev, 0x1028); /* 2c ro - Dell.) */
3423 PCIDevSetSubSystemId (&pThis->PciDev, 0x01ad); /* 2e ro. */
3424 }
3425 else
3426 {
3427 PCIDevSetSubSystemVendorId(&pThis->PciDev, 0x8086); /* 2c ro - Intel.) */
3428 PCIDevSetSubSystemId (&pThis->PciDev, 0x0000); /* 2e ro. */
3429 }
3430
3431 /*
3432 * Register the PCI device, it's I/O regions, the timer and the
3433 * saved state item.
3434 */
3435 rc = PDMDevHlpPCIRegister(pDevIns, &pThis->PciDev);
3436 if (RT_FAILURE(rc))
3437 return rc;
3438
3439 rc = PDMDevHlpPCIIORegionRegister(pDevIns, 0, 256, PCI_ADDRESS_SPACE_IO, ichac97IOPortMap);
3440 if (RT_FAILURE(rc))
3441 return rc;
3442
3443 rc = PDMDevHlpPCIIORegionRegister(pDevIns, 1, 64, PCI_ADDRESS_SPACE_IO, ichac97IOPortMap);
3444 if (RT_FAILURE(rc))
3445 return rc;
3446
3447 rc = PDMDevHlpSSMRegister(pDevIns, AC97_SSM_VERSION, sizeof(*pThis), ichac97SaveExec, ichac97LoadExec);
3448 if (RT_FAILURE(rc))
3449 return rc;
3450
3451#ifdef VBOX_WITH_AUDIO_AC97_ASYNC_IO
3452 LogRel(("AC97: Asynchronous I/O enabled\n"));
3453#endif
3454
3455 /*
3456 * Attach driver.
3457 */
3458 uint8_t uLUN;
3459 for (uLUN = 0; uLUN < UINT8_MAX; ++uLUN)
3460 {
3461 LogFunc(("Trying to attach driver for LUN #%RU8 ...\n", uLUN));
3462 rc = ichac97AttachInternal(pDevIns, NULL /* pDrv */, uLUN, 0 /* fFlags */);
3463 if (RT_FAILURE(rc))
3464 {
3465 if (rc == VERR_PDM_NO_ATTACHED_DRIVER)
3466 rc = VINF_SUCCESS;
3467 else if (rc == VERR_AUDIO_BACKEND_INIT_FAILED)
3468 {
3469 ichac97Reattach(pThis, NULL /* pDrv */, uLUN, "NullAudio");
3470 PDMDevHlpVMSetRuntimeError(pDevIns, 0 /*fFlags*/, "HostAudioNotResponding",
3471 N_("Host audio backend initialization has failed. Selecting the NULL audio backend "
3472 "with the consequence that no sound is audible"));
3473 /* Attaching to the NULL audio backend will never fail. */
3474 rc = VINF_SUCCESS;
3475 }
3476 break;
3477 }
3478 }
3479
3480 LogFunc(("cLUNs=%RU8, rc=%Rrc\n", uLUN, rc));
3481
3482 if (RT_SUCCESS(rc))
3483 {
3484 rc = AudioMixerCreate("AC'97 Mixer", 0 /* uFlags */, &pThis->pMixer);
3485 if (RT_SUCCESS(rc))
3486 {
3487 rc = AudioMixerCreateSink(pThis->pMixer, "[Recording] Line In", AUDMIXSINKDIR_INPUT, &pThis->pSinkLineIn);
3488 AssertRC(rc);
3489 rc = AudioMixerCreateSink(pThis->pMixer, "[Recording] Microphone In", AUDMIXSINKDIR_INPUT, &pThis->pSinkMicIn);
3490 AssertRC(rc);
3491 rc = AudioMixerCreateSink(pThis->pMixer, "[Playback] PCM Output", AUDMIXSINKDIR_OUTPUT, &pThis->pSinkOut);
3492 AssertRC(rc);
3493 }
3494 }
3495
3496 if (RT_SUCCESS(rc))
3497 {
3498 /*
3499 * Create all hardware streams.
3500 */
3501 rc = ichac97StreamCreate(pThis, &pThis->StreamLineIn, AC97SOUNDSOURCE_PI_INDEX);
3502 if (RT_SUCCESS(rc))
3503 {
3504 rc = ichac97StreamCreate(pThis, &pThis->StreamMicIn, AC97SOUNDSOURCE_MC_INDEX);
3505 if (RT_SUCCESS(rc))
3506 rc = ichac97StreamCreate(pThis, &pThis->StreamOut, AC97SOUNDSOURCE_PO_INDEX);
3507 }
3508
3509#ifdef VBOX_WITH_AUDIO_AC97_ONETIME_INIT
3510 PAC97DRIVER pDrv;
3511 RTListForEach(&pThis->lstDrv, pDrv, AC97DRIVER, Node)
3512 {
3513 /*
3514 * Only primary drivers are critical for the VM to run. Everything else
3515 * might not worth showing an own error message box in the GUI.
3516 */
3517 if (!(pDrv->Flags & PDMAUDIODRVFLAGS_PRIMARY))
3518 continue;
3519
3520 PPDMIAUDIOCONNECTOR pCon = pDrv->pConnector;
3521 AssertPtr(pCon);
3522
3523 bool fValidLineIn = AudioMixerStreamIsValid(pDrv->LineIn.pMixStrm);
3524 bool fValidMicIn = AudioMixerStreamIsValid(pDrv->MicIn.pMixStrm);
3525 bool fValidOut = AudioMixerStreamIsValid(pDrv->Out.pMixStrm);
3526
3527 if ( !fValidLineIn
3528 && !fValidMicIn
3529 && !fValidOut)
3530 {
3531 LogRel(("AC97: Falling back to NULL backend (no sound audible)\n"));
3532
3533 ichac97Reset(pDevIns);
3534 ichac97Reattach(pThis, pDrv, pDrv->uLUN, "NullAudio");
3535
3536 PDMDevHlpVMSetRuntimeError(pDevIns, 0 /*fFlags*/, "HostAudioNotResponding",
3537 N_("No audio devices could be opened. Selecting the NULL audio backend "
3538 "with the consequence that no sound is audible"));
3539 }
3540 else
3541 {
3542 bool fWarn = false;
3543
3544 PDMAUDIOBACKENDCFG backendCfg;
3545 int rc2 = pCon->pfnGetConfig(pCon, &backendCfg);
3546 if (RT_SUCCESS(rc2))
3547 {
3548 if (backendCfg.cMaxStreamsIn)
3549 {
3550 /* If the audio backend supports two or more input streams at once,
3551 * warn if one of our two inputs (microphone-in and line-in) failed to initialize. */
3552 if (backendCfg.cMaxStreamsIn >= 2)
3553 fWarn = !fValidLineIn || !fValidMicIn;
3554 /* If the audio backend only supports one input stream at once (e.g. pure ALSA, and
3555 * *not* ALSA via PulseAudio plugin!), only warn if both of our inputs failed to initialize.
3556 * One of the two simply is not in use then. */
3557 else if (backendCfg.cMaxStreamsIn == 1)
3558 fWarn = !fValidLineIn && !fValidMicIn;
3559 /* Don't warn if our backend is not able of supporting any input streams at all. */
3560 }
3561
3562 if ( !fWarn
3563 && backendCfg.cMaxStreamsOut)
3564 {
3565 fWarn = !fValidOut;
3566 }
3567 }
3568 else
3569 {
3570 LogRel(("AC97: Unable to retrieve audio backend configuration for LUN #%RU8, rc=%Rrc\n", pDrv->uLUN, rc2));
3571 fWarn = true;
3572 }
3573
3574 if (fWarn)
3575 {
3576 char szMissingStreams[255] = "";
3577 size_t len = 0;
3578 if (!fValidLineIn)
3579 {
3580 LogRel(("AC97: WARNING: Unable to open PCM line input for LUN #%RU8!\n", pDrv->uLUN));
3581 len = RTStrPrintf(szMissingStreams, sizeof(szMissingStreams), "PCM Input");
3582 }
3583 if (!fValidMicIn)
3584 {
3585 LogRel(("AC97: WARNING: Unable to open PCM microphone input for LUN #%RU8!\n", pDrv->uLUN));
3586 len += RTStrPrintf(szMissingStreams + len,
3587 sizeof(szMissingStreams) - len, len ? ", PCM Microphone" : "PCM Microphone");
3588 }
3589 if (!fValidOut)
3590 {
3591 LogRel(("AC97: WARNING: Unable to open PCM output for LUN #%RU8!\n", pDrv->uLUN));
3592 len += RTStrPrintf(szMissingStreams + len,
3593 sizeof(szMissingStreams) - len, len ? ", PCM Output" : "PCM Output");
3594 }
3595
3596 PDMDevHlpVMSetRuntimeError(pDevIns, 0 /*fFlags*/, "HostAudioNotResponding",
3597 N_("Some AC'97 audio streams (%s) could not be opened. Guest applications generating audio "
3598 "output or depending on audio input may hang. Make sure your host audio device "
3599 "is working properly. Check the logfile for error messages of the audio "
3600 "subsystem"), szMissingStreams);
3601 }
3602 }
3603 }
3604#endif /* VBOX_WITH_AUDIO_AC97_ONETIME_INIT */
3605 }
3606
3607 if (RT_SUCCESS(rc))
3608 ichac97Reset(pDevIns);
3609
3610#ifndef VBOX_WITH_AUDIO_AC97_CALLBACKS
3611 if (RT_SUCCESS(rc))
3612 {
3613 rc = RTCritSectInit(&pThis->csTimer);
3614 if (RT_SUCCESS(rc))
3615 {
3616 /* Create the emulation timer. */
3617 rc = PDMDevHlpTMTimerCreate(pDevIns, TMCLOCK_VIRTUAL, ichac97Timer, pThis,
3618 TMTIMER_FLAGS_NO_CRIT_SECT, "DevIchAc97", &pThis->pTimer);
3619 AssertRCReturn(rc, rc);
3620
3621 if (RT_SUCCESS(rc))
3622 {
3623 pThis->cTimerTicks = TMTimerGetFreq(pThis->pTimer) / uTimerHz;
3624 pThis->uTimerTS = TMTimerGet(pThis->pTimer);
3625 LogFunc(("Timer ticks=%RU64 (%RU16 Hz)\n", pThis->cTimerTicks, uTimerHz));
3626 }
3627 }
3628 }
3629#else /* !VBOX_WITH_AUDIO_AC97_CALLBACKS */
3630 if (RT_SUCCESS(rc))
3631 {
3632 PAC97DRIVER pDrv;
3633 RTListForEach(&pThis->lstDrv, pDrv, AC97DRIVER, Node)
3634 {
3635 /* Only register primary driver.
3636 * The device emulation does the output multiplexing then. */
3637 if (!(pDrv->Flags & PDMAUDIODRVFLAGS_PRIMARY))
3638 continue;
3639
3640 PDMAUDIOCALLBACK AudioCallbacks[2];
3641
3642 AC97CALLBACKCTX Ctx = { pThis, pDrv };
3643
3644 AudioCallbacks[0].enmType = PDMAUDIOCALLBACKTYPE_INPUT;
3645 AudioCallbacks[0].pfnCallback = ac97CallbackInput;
3646 AudioCallbacks[0].pvCtx = &Ctx;
3647 AudioCallbacks[0].cbCtx = sizeof(AC97CALLBACKCTX);
3648
3649 AudioCallbacks[1].enmType = PDMAUDIOCALLBACKTYPE_OUTPUT;
3650 AudioCallbacks[1].pfnCallback = ac97CallbackOutput;
3651 AudioCallbacks[1].pvCtx = &Ctx;
3652 AudioCallbacks[1].cbCtx = sizeof(AC97CALLBACKCTX);
3653
3654 rc = pDrv->pConnector->pfnRegisterCallbacks(pDrv->pConnector, AudioCallbacks, RT_ELEMENTS(AudioCallbacks));
3655 if (RT_FAILURE(rc))
3656 break;
3657 }
3658 }
3659#endif /* VBOX_WITH_AUDIO_AC97_CALLBACKS */
3660
3661#ifdef VBOX_WITH_STATISTICS
3662 if (RT_SUCCESS(rc))
3663 {
3664 /*
3665 * Register statistics.
3666 */
3667 PDMDevHlpSTAMRegister(pDevIns, &pThis->StatTimer, STAMTYPE_PROFILE, "/Devices/AC97/Timer", STAMUNIT_TICKS_PER_CALL, "Profiling ichac97Timer.");
3668 PDMDevHlpSTAMRegister(pDevIns, &pThis->StatIn, STAMTYPE_PROFILE, "/Devices/AC97/Input", STAMUNIT_TICKS_PER_CALL, "Profiling input.");
3669 PDMDevHlpSTAMRegister(pDevIns, &pThis->StatOut, STAMTYPE_PROFILE, "/Devices/AC97/Output", STAMUNIT_TICKS_PER_CALL, "Profiling output.");
3670 PDMDevHlpSTAMRegister(pDevIns, &pThis->StatBytesRead, STAMTYPE_COUNTER, "/Devices/AC97/BytesRead" , STAMUNIT_BYTES, "Bytes read from AC97 emulation.");
3671 PDMDevHlpSTAMRegister(pDevIns, &pThis->StatBytesWritten, STAMTYPE_COUNTER, "/Devices/AC97/BytesWritten", STAMUNIT_BYTES, "Bytes written to AC97 emulation.");
3672 }
3673#endif
3674
3675#ifdef AC97_DEBUG_DUMP_PCM_DATA
3676 RTFileDelete(AC97_DEBUG_DUMP_PCM_DATA_PATH "ac97DMARead.pcm");
3677 RTFileDelete(AC97_DEBUG_DUMP_PCM_DATA_PATH "ac97DMAWrite.pcm");
3678 RTFileDelete(AC97_DEBUG_DUMP_PCM_DATA_PATH "ac97StreamRead.pcm");
3679 RTFileDelete(AC97_DEBUG_DUMP_PCM_DATA_PATH "ac97StreamWrite.pcm");
3680#endif
3681
3682 LogFlowFuncLeaveRC(rc);
3683 return rc;
3684}
3685
3686/**
3687 * The device registration structure.
3688 */
3689const PDMDEVREG g_DeviceICHAC97 =
3690{
3691 /* u32Version */
3692 PDM_DEVREG_VERSION,
3693 /* szName */
3694 "ichac97",
3695 /* szRCMod */
3696 "",
3697 /* szR0Mod */
3698 "",
3699 /* pszDescription */
3700 "ICH AC'97 Audio Controller",
3701 /* fFlags */
3702 PDM_DEVREG_FLAGS_DEFAULT_BITS,
3703 /* fClass */
3704 PDM_DEVREG_CLASS_AUDIO,
3705 /* cMaxInstances */
3706 1,
3707 /* cbInstance */
3708 sizeof(AC97STATE),
3709 /* pfnConstruct */
3710 ichac97Construct,
3711 /* pfnDestruct */
3712 ichac97Destruct,
3713 /* pfnRelocate */
3714 NULL,
3715 /* pfnMemSetup */
3716 NULL,
3717 /* pfnPowerOn */
3718 NULL,
3719 /* pfnReset */
3720 ichac97Reset,
3721 /* pfnSuspend */
3722 NULL,
3723 /* pfnResume */
3724 NULL,
3725 /* pfnAttach */
3726 ichac97Attach,
3727 /* pfnDetach */
3728 ichac97Detach,
3729 /* pfnQueryInterface. */
3730 NULL,
3731 /* pfnInitComplete */
3732 NULL,
3733 /* pfnPowerOff */
3734 ichac97PowerOff,
3735 /* pfnSoftReset */
3736 NULL,
3737 /* u32VersionEnd */
3738 PDM_DEVREG_VERSION
3739};
3740
3741#endif /* !IN_RING3 */
3742#endif /* !VBOX_DEVICE_STRUCT_TESTCASE */
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