VirtualBox

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

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

Audio/DevIchAc97.cpp: Make sure to also destroy all audio sinks in ichac97StreamsDestroy().

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