ftp://ftp.kernel.org/pub/linux/kernel/v2.6/linux-2.6.6.tar.bz2
[linux-2.6.git] / sound / pci / cmipci.c
1 /*
2  * Driver for C-Media CMI8338 and 8738 PCI soundcards.
3  * Copyright (c) 2000 by Takashi Iwai <tiwai@suse.de>
4  *
5  *   This program is free software; you can redistribute it and/or modify
6  *   it under the terms of the GNU General Public License as published by
7  *   the Free Software Foundation; either version 2 of the License, or
8  *   (at your option) any later version.
9  *
10  *   This program is distributed in the hope that it will be useful,
11  *   but WITHOUT ANY WARRANTY; without even the implied warranty of
12  *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13  *   GNU General Public License for more details.
14  *
15  *   You should have received a copy of the GNU General Public License
16  *   along with this program; if not, write to the Free Software
17  *   Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307 USA
18  */
19  
20 /* Does not work. Warning may block system in capture mode */
21 /* #define USE_VAR48KRATE */
22
23 /* Define this if you want soft ac3 encoding */
24 #define DO_SOFT_AC3
25 #define USE_AES_IEC958
26
27 #include <sound/driver.h>
28 #include <asm/io.h>
29 #include <linux/delay.h>
30 #include <linux/interrupt.h>
31 #include <linux/init.h>
32 #include <linux/pci.h>
33 #include <linux/slab.h>
34 #include <linux/gameport.h>
35 #include <sound/core.h>
36 #include <sound/info.h>
37 #include <sound/control.h>
38 #include <sound/pcm.h>
39 #include <sound/rawmidi.h>
40 #include <sound/mpu401.h>
41 #include <sound/opl3.h>
42 #include <sound/sb.h>
43 #include <sound/asoundef.h>
44 #define SNDRV_GET_ID
45 #include <sound/initval.h>
46
47 MODULE_AUTHOR("Takashi Iwai <tiwai@suse.de>");
48 MODULE_DESCRIPTION("C-Media CMI8x38 PCI");
49 MODULE_LICENSE("GPL");
50 MODULE_CLASSES("{sound}");
51 MODULE_DEVICES("{{C-Media,CMI8738},"
52                 "{C-Media,CMI8738B},"
53                 "{C-Media,CMI8338A},"
54                 "{C-Media,CMI8338B}}");
55
56 #if defined(CONFIG_GAMEPORT) || (defined(MODULE) && defined(CONFIG_GAMEPORT_MODULE))
57 #define SUPPORT_JOYSTICK 1
58 #endif
59
60 static int index[SNDRV_CARDS] = SNDRV_DEFAULT_IDX;      /* Index 0-MAX */
61 static char *id[SNDRV_CARDS] = SNDRV_DEFAULT_STR;       /* ID for this card */
62 static int enable[SNDRV_CARDS] = SNDRV_DEFAULT_ENABLE_PNP;      /* Enable switches */
63 static long mpu_port[SNDRV_CARDS];
64 static long fm_port[SNDRV_CARDS];
65 #ifdef DO_SOFT_AC3
66 static int soft_ac3[SNDRV_CARDS] = {[0 ... (SNDRV_CARDS-1)]=1};
67 #endif
68 #ifdef SUPPORT_JOYSTICK
69 static int joystick_port[SNDRV_CARDS];
70 #endif
71
72 MODULE_PARM(index, "1-" __MODULE_STRING(SNDRV_CARDS) "i");
73 MODULE_PARM_DESC(index, "Index value for C-Media PCI soundcard.");
74 MODULE_PARM_SYNTAX(index, SNDRV_INDEX_DESC);
75 MODULE_PARM(id, "1-" __MODULE_STRING(SNDRV_CARDS) "s");
76 MODULE_PARM_DESC(id, "ID string for C-Media PCI soundcard.");
77 MODULE_PARM_SYNTAX(id, SNDRV_ID_DESC);
78 MODULE_PARM(enable, "1-" __MODULE_STRING(SNDRV_CARDS) "i");
79 MODULE_PARM_DESC(enable, "Enable C-Media PCI soundcard.");
80 MODULE_PARM_SYNTAX(enable, SNDRV_ENABLE_DESC);
81 MODULE_PARM(mpu_port, "1-" __MODULE_STRING(SNDRV_CARDS) "l");
82 MODULE_PARM_DESC(mpu_port, "MPU-401 port.");
83 MODULE_PARM_SYNTAX(mpu_port, SNDRV_ENABLED ",allows:{{0},{0x330},{0x320},{0x310},{0x300}},dialog:list");
84 MODULE_PARM(fm_port, "1-" __MODULE_STRING(SNDRV_CARDS) "l");
85 MODULE_PARM_DESC(fm_port, "FM port.");
86 MODULE_PARM_SYNTAX(fm_port, SNDRV_ENABLED ",allows:{{0},{0x388},{0x3c8},{0x3e0},{0x3e8}},dialog:list");
87 #ifdef DO_SOFT_AC3
88 MODULE_PARM(soft_ac3, "1-" __MODULE_STRING(SNDRV_CARDS) "l");
89 MODULE_PARM_DESC(soft_ac3, "Sofware-conversion of raw SPDIF packets (model 033 only).");
90 MODULE_PARM_SYNTAX(soft_ac3, SNDRV_ENABLED "," SNDRV_BOOLEAN_TRUE_DESC);
91 #endif
92 #ifdef SUPPORT_JOYSTICK
93 MODULE_PARM(joystick_port, "1-" __MODULE_STRING(SNDRV_CARDS) "i");
94 MODULE_PARM_DESC(joystick_port, "Joystick port address.");
95 MODULE_PARM_SYNTAX(joystick_port, SNDRV_ENABLED ",allows:{{0},{1},{0x200},{0x201}},dialog:list");
96 #endif
97
98 #ifndef PCI_DEVICE_ID_CMEDIA_CM8738
99 #define PCI_DEVICE_ID_CMEDIA_CM8738     0x0111
100 #endif
101 #ifndef PCI_DEVICE_ID_CMEDIA_CM8738B
102 #define PCI_DEVICE_ID_CMEDIA_CM8738B    0x0112
103 #endif
104
105 /*
106  * CM8x38 registers definition
107  */
108
109 #define CM_REG_FUNCTRL0         0x00
110 #define CM_RST_CH1              0x00080000
111 #define CM_RST_CH0              0x00040000
112 #define CM_CHEN1                0x00020000      /* ch1: enable */
113 #define CM_CHEN0                0x00010000      /* ch0: enable */
114 #define CM_PAUSE1               0x00000008      /* ch1: pause */
115 #define CM_PAUSE0               0x00000004      /* ch0: pause */
116 #define CM_CHADC1               0x00000002      /* ch1, 0:playback, 1:record */
117 #define CM_CHADC0               0x00000001      /* ch0, 0:playback, 1:record */
118
119 #define CM_REG_FUNCTRL1         0x04
120 #define CM_ASFC_MASK            0x0000E000      /* ADC sampling frequency */
121 #define CM_ASFC_SHIFT           13
122 #define CM_DSFC_MASK            0x00001C00      /* DAC sampling frequency */
123 #define CM_DSFC_SHIFT           10
124 #define CM_SPDF_1               0x00000200      /* SPDIF IN/OUT at channel B */
125 #define CM_SPDF_0               0x00000100      /* SPDIF OUT only channel A */
126 #define CM_SPDFLOOP             0x00000080      /* ext. SPDIIF/OUT -> IN loopback */
127 #define CM_SPDO2DAC             0x00000040      /* SPDIF/OUT can be heard from internal DAC */
128 #define CM_INTRM                0x00000020      /* master control block (MCB) interrupt enabled */
129 #define CM_BREQ                 0x00000010      /* bus master enabled */
130 #define CM_VOICE_EN             0x00000008      /* legacy voice (SB16,FM) */
131 #define CM_UART_EN              0x00000004      /* UART */
132 #define CM_JYSTK_EN             0x00000002      /* joy stick */
133
134 #define CM_REG_CHFORMAT         0x08
135
136 #define CM_CHB3D5C              0x80000000      /* 5,6 channels */
137 #define CM_CHB3D                0x20000000      /* 4 channels */
138
139 #define CM_CHIP_MASK1           0x1f000000
140 #define CM_CHIP_037             0x01000000
141
142 #define CM_SPDIF_SELECT1        0x00080000      /* for model <= 037 ? */
143 #define CM_AC3EN1               0x00100000      /* enable AC3: model 037 */
144 #define CM_SPD24SEL             0x00020000      /* 24bit spdif: model 037 */
145 /* #define CM_SPDIF_INVERSE     0x00010000 */ /* ??? */
146
147 #define CM_ADCBITLEN_MASK       0x0000C000      
148 #define CM_ADCBITLEN_16         0x00000000
149 #define CM_ADCBITLEN_15         0x00004000
150 #define CM_ADCBITLEN_14         0x00008000
151 #define CM_ADCBITLEN_13         0x0000C000
152
153 #define CM_ADCDACLEN_MASK       0x00003000
154 #define CM_ADCDACLEN_060        0x00000000
155 #define CM_ADCDACLEN_066        0x00001000
156 #define CM_ADCDACLEN_130        0x00002000
157 #define CM_ADCDACLEN_280        0x00003000
158
159 #define CM_CH1_SRATE_176K       0x00000800
160 #define CM_CH1_SRATE_88K        0x00000400
161 #define CM_CH0_SRATE_176K       0x00000200
162 #define CM_CH0_SRATE_88K        0x00000100
163
164 #define CM_SPDIF_INVERSE2       0x00000080      /* model 055? */
165
166 #define CM_CH1FMT_MASK          0x0000000C
167 #define CM_CH1FMT_SHIFT         2
168 #define CM_CH0FMT_MASK          0x00000003
169 #define CM_CH0FMT_SHIFT         0
170
171 #define CM_REG_INT_HLDCLR       0x0C
172 #define CM_CHIP_MASK2           0xff000000
173 #define CM_CHIP_039             0x04000000
174 #define CM_CHIP_039_6CH         0x01000000
175 #define CM_TDMA_INT_EN          0x00040000
176 #define CM_CH1_INT_EN           0x00020000
177 #define CM_CH0_INT_EN           0x00010000
178 #define CM_INT_HOLD             0x00000002
179 #define CM_INT_CLEAR            0x00000001
180
181 #define CM_REG_INT_STATUS       0x10
182 #define CM_INTR                 0x80000000
183 #define CM_VCO                  0x08000000      /* Voice Control? CMI8738 */
184 #define CM_MCBINT               0x04000000      /* Master Control Block abort cond.? */
185 #define CM_UARTINT              0x00010000
186 #define CM_LTDMAINT             0x00008000
187 #define CM_HTDMAINT             0x00004000
188 #define CM_XDO46                0x00000080      /* Modell 033? Direct programming EEPROM (read data register) */
189 #define CM_LHBTOG               0x00000040      /* High/Low status from DMA ctrl register */
190 #define CM_LEG_HDMA             0x00000020      /* Legacy is in High DMA channel */
191 #define CM_LEG_STEREO           0x00000010      /* Legacy is in Stereo mode */
192 #define CM_CH1BUSY              0x00000008
193 #define CM_CH0BUSY              0x00000004
194 #define CM_CHINT1               0x00000002
195 #define CM_CHINT0               0x00000001
196
197 #define CM_REG_LEGACY_CTRL      0x14
198 #define CM_NXCHG                0x80000000      /* h/w multi channels? */
199 #define CM_VMPU_MASK            0x60000000      /* MPU401 i/o port address */
200 #define CM_VMPU_330             0x00000000
201 #define CM_VMPU_320             0x20000000
202 #define CM_VMPU_310             0x40000000
203 #define CM_VMPU_300             0x60000000
204 #define CM_VSBSEL_MASK          0x0C000000      /* SB16 base address */
205 #define CM_VSBSEL_220           0x00000000
206 #define CM_VSBSEL_240           0x04000000
207 #define CM_VSBSEL_260           0x08000000
208 #define CM_VSBSEL_280           0x0C000000
209 #define CM_FMSEL_MASK           0x03000000      /* FM OPL3 base address */
210 #define CM_FMSEL_388            0x00000000
211 #define CM_FMSEL_3C8            0x01000000
212 #define CM_FMSEL_3E0            0x02000000
213 #define CM_FMSEL_3E8            0x03000000
214 #define CM_ENSPDOUT             0x00800000      /* enable XPDIF/OUT to I/O interface */
215 #define CM_SPDCOPYRHT           0x00400000      /* set copyright spdif in/out */
216 #define CM_DAC2SPDO             0x00200000      /* enable wave+fm_midi -> SPDIF/OUT */
217 #define CM_SETRETRY             0x00010000      /* 0: legacy i/o wait (default), 1: legacy i/o bus retry */
218 #define CM_CHB3D6C              0x00008000      /* 5.1 channels support */
219 #define CM_LINE_AS_BASS         0x00006000      /* use line-in as bass */
220
221 #define CM_REG_MISC_CTRL        0x18
222 #define CM_PWD                  0x80000000
223 #define CM_RESET                0x40000000
224 #define CM_SFIL_MASK            0x30000000
225 #define CM_TXVX                 0x08000000
226 #define CM_N4SPK3D              0x04000000      /* 4ch output */
227 #define CM_SPDO5V               0x02000000      /* 5V spdif output (1 = 0.5v (coax)) */
228 #define CM_SPDIF48K             0x01000000      /* write */
229 #define CM_SPATUS48K            0x01000000      /* read */
230 #define CM_ENDBDAC              0x00800000      /* enable dual dac */
231 #define CM_XCHGDAC              0x00400000      /* 0: front=ch0, 1: front=ch1 */
232 #define CM_SPD32SEL             0x00200000      /* 0: 16bit SPDIF, 1: 32bit */
233 #define CM_SPDFLOOPI            0x00100000      /* int. SPDIF-IN -> int. OUT */
234 #define CM_FM_EN                0x00080000      /* enalbe FM */
235 #define CM_AC3EN2               0x00040000      /* enable AC3: model 039 */
236 #define CM_VIDWPDSB             0x00010000 
237 #define CM_SPDF_AC97            0x00008000      /* 0: SPDIF/OUT 44.1K, 1: 48K */
238 #define CM_MASK_EN              0x00004000
239 #define CM_VIDWPPRT             0x00002000
240 #define CM_SFILENB              0x00001000
241 #define CM_MMODE_MASK           0x00000E00
242 #define CM_SPDIF_SELECT2        0x00000100      /* for model > 039 ? */
243 #define CM_ENCENTER             0x00000080
244 #define CM_FLINKON              0x00000040
245 #define CM_FLINKOFF             0x00000020
246 #define CM_MIDSMP               0x00000010
247 #define CM_UPDDMA_MASK          0x0000000C
248 #define CM_TWAIT_MASK           0x00000003
249
250         /* byte */
251 #define CM_REG_MIXER0           0x20
252
253 #define CM_REG_SB16_DATA        0x22
254 #define CM_REG_SB16_ADDR        0x23
255
256 #define CM_REFFREQ_XIN          (315*1000*1000)/22      /* 14.31818 Mhz reference clock frequency pin XIN */
257 #define CM_ADCMULT_XIN          512                     /* Guessed (487 best for 44.1kHz, not for 88/176kHz) */
258 #define CM_TOLERANCE_RATE       0.001                   /* Tolerance sample rate pitch (1000ppm) */
259 #define CM_MAXIMUM_RATE         80000000                /* Note more than 80MHz */
260
261 #define CM_REG_MIXER1           0x24
262 #define CM_FMMUTE               0x80    /* mute FM */
263 #define CM_FMMUTE_SHIFT         7
264 #define CM_WSMUTE               0x40    /* mute PCM */
265 #define CM_WSMUTE_SHIFT         6
266 #define CM_SPK4                 0x20    /* lin-in -> rear line out */
267 #define CM_SPK4_SHIFT           5
268 #define CM_REAR2FRONT           0x10    /* exchange rear/front */
269 #define CM_REAR2FRONT_SHIFT     4
270 #define CM_WAVEINL              0x08    /* digital wave rec. left chan */
271 #define CM_WAVEINL_SHIFT        3
272 #define CM_WAVEINR              0x04    /* digical wave rec. right */
273 #define CM_WAVEINR_SHIFT        2
274 #define CM_X3DEN                0x02    /* 3D surround enable */
275 #define CM_X3DEN_SHIFT          1
276 #define CM_CDPLAY               0x01    /* enable SPDIF/IN PCM -> DAC */
277 #define CM_CDPLAY_SHIFT         0
278
279 #define CM_REG_MIXER2           0x25
280 #define CM_RAUXREN              0x80    /* AUX right capture */
281 #define CM_RAUXREN_SHIFT        7
282 #define CM_RAUXLEN              0x40    /* AUX left capture */
283 #define CM_RAUXLEN_SHIFT        6
284 #define CM_VAUXRM               0x20    /* AUX right mute */
285 #define CM_VAUXRM_SHIFT         5
286 #define CM_VAUXLM               0x10    /* AUX left mute */
287 #define CM_VAUXLM_SHIFT         4
288 #define CM_VADMIC_MASK          0x0e    /* mic gain level (0-3) << 1 */
289 #define CM_VADMIC_SHIFT         1
290 #define CM_MICGAINZ             0x01    /* mic boost */
291 #define CM_MICGAINZ_SHIFT       0
292
293 #define CM_REG_AUX_VOL          0x26
294 #define CM_VAUXL_MASK           0xf0
295 #define CM_VAUXR_MASK           0x0f
296
297 #define CM_REG_MISC             0x27
298 #define CM_XGPO1                0x20
299 // #define CM_XGPBIO            0x04
300 #define CM_MIC_CENTER_LFE       0x04    /* mic as center/lfe out? (model 039 or later?) */
301 #define CM_SPDIF_INVERSE        0x04    /* spdif input phase inverse (model 037) */
302 #define CM_SPDVALID             0x02    /* spdif input valid check */
303 #define CM_DMAUTO               0x01
304
305 #define CM_REG_AC97             0x28    /* hmmm.. do we have ac97 link? */
306 /*
307  * For CMI-8338 (0x28 - 0x2b) .. is this valid for CMI-8738
308  * or identical with AC97 codec?
309  */
310 #define CM_REG_EXTERN_CODEC     CM_REG_AC97
311
312 /*
313  * MPU401 pci port index address 0x40 - 0x4f (CMI-8738 spec ver. 0.6)
314  */
315 #define CM_REG_MPU_PCI          0x40
316
317 /*
318  * FM pci port index address 0x50 - 0x5f (CMI-8738 spec ver. 0.6)
319  */
320 #define CM_REG_FM_PCI           0x50
321
322 /*
323  * for CMI-8338 .. this is not valid for CMI-8738.
324  */
325 #define CM_REG_EXTENT_IND       0xf0
326 #define CM_VPHONE_MASK          0xe0    /* Phone volume control (0-3) << 5 */
327 #define CM_VPHONE_SHIFT         5
328 #define CM_VPHOM                0x10    /* Phone mute control */
329 #define CM_VSPKM                0x08    /* Speaker mute control, default high */
330 #define CM_RLOOPREN             0x04    /* Rec. R-channel enable */
331 #define CM_RLOOPLEN             0x02    /* Rec. L-channel enable */
332
333 /*
334  * CMI-8338 spec ver 0.5 (this is not valid for CMI-8738):
335  * the 8 registers 0xf8 - 0xff are used for programming m/n counter by the PLL
336  * unit (readonly?).
337  */
338 #define CM_REG_PLL              0xf8
339
340 /*
341  * extended registers
342  */
343 #define CM_REG_CH0_FRAME1       0x80    /* base address */
344 #define CM_REG_CH0_FRAME2       0x84
345 #define CM_REG_CH1_FRAME1       0x88    /* 0-15: count of samples at bus master; buffer size */
346 #define CM_REG_CH1_FRAME2       0x8C    /* 16-31: count of samples at codec; fragment size */
347
348 /*
349  * size of i/o region
350  */
351 #define CM_EXTENT_CODEC   0x100
352 #define CM_EXTENT_MIDI    0x2
353 #define CM_EXTENT_SYNTH   0x4
354
355
356 /*
357  * pci ids
358  */
359 #ifndef PCI_VENDOR_ID_CMEDIA
360 #define PCI_VENDOR_ID_CMEDIA         0x13F6
361 #endif
362 #ifndef PCI_DEVICE_ID_CMEDIA_CM8338A
363 #define PCI_DEVICE_ID_CMEDIA_CM8338A 0x0100
364 #endif
365 #ifndef PCI_DEVICE_ID_CMEDIA_CM8338B
366 #define PCI_DEVICE_ID_CMEDIA_CM8338B 0x0101
367 #endif
368 #ifndef PCI_DEVICE_ID_CMEDIA_CM8738
369 #define PCI_DEVICE_ID_CMEDIA_CM8738  0x0111
370 #endif
371 #ifndef PCI_DEVICE_ID_CMEDIA_CM8738B
372 #define PCI_DEVICE_ID_CMEDIA_CM8738B 0x0112
373 #endif
374
375 /*
376  * channels for playback / capture
377  */
378 #define CM_CH_PLAY      0
379 #define CM_CH_CAPT      1
380
381 /*
382  * flags to check device open/close
383  */
384 #define CM_OPEN_NONE    0
385 #define CM_OPEN_CH_MASK 0x01
386 #define CM_OPEN_DAC     0x10
387 #define CM_OPEN_ADC     0x20
388 #define CM_OPEN_SPDIF   0x40
389 #define CM_OPEN_MCHAN   0x80
390 #define CM_OPEN_PLAYBACK        (CM_CH_PLAY | CM_OPEN_DAC)
391 #define CM_OPEN_PLAYBACK2       (CM_CH_CAPT | CM_OPEN_DAC)
392 #define CM_OPEN_PLAYBACK_MULTI  (CM_CH_PLAY | CM_OPEN_DAC | CM_OPEN_MCHAN)
393 #define CM_OPEN_CAPTURE         (CM_CH_CAPT | CM_OPEN_ADC)
394 #define CM_OPEN_SPDIF_PLAYBACK  (CM_CH_PLAY | CM_OPEN_DAC | CM_OPEN_SPDIF)
395 #define CM_OPEN_SPDIF_CAPTURE   (CM_CH_CAPT | CM_OPEN_ADC | CM_OPEN_SPDIF)
396
397
398 #if CM_CH_PLAY == 1
399 #define CM_PLAYBACK_SRATE_176K  CM_CH1_SRATE_176K
400 #define CM_PLAYBACK_SPDF        CM_SPDF_1
401 #define CM_CAPTURE_SPDF         CM_SPDF_0
402 #else
403 #define CM_PLAYBACK_SRATE_176K CM_CH0_SRATE_176K
404 #define CM_PLAYBACK_SPDF        CM_SPDF_0
405 #define CM_CAPTURE_SPDF         CM_SPDF_1
406 #endif
407
408
409 /*
410  * driver data
411  */
412
413 typedef struct snd_stru_cmipci cmipci_t;
414 typedef struct snd_stru_cmipci_pcm cmipci_pcm_t;
415
416 #define chip_t cmipci_t
417
418 struct snd_stru_cmipci_pcm {
419         snd_pcm_substream_t *substream;
420         int running;            /* dac/adc running? */
421         unsigned int dma_size;  /* in frames */
422         unsigned int period_size;       /* in frames */
423         unsigned int offset;    /* physical address of the buffer */
424         unsigned int fmt;       /* format bits */
425         int ch;                 /* channel (0/1) */
426         unsigned int is_dac;            /* is dac? */
427         int bytes_per_frame;
428         int shift;
429         int ac3_shift;  /* extra shift: 1 on soft ac3 mode */
430 };
431
432 /* mixer elements toggled/resumed during ac3 playback */
433 struct cmipci_mixer_auto_switches {
434         const char *name;       /* switch to toggle */
435         int toggle_on;          /* value to change when ac3 mode */
436 };
437 static const struct cmipci_mixer_auto_switches cm_saved_mixer[] = {
438         {"PCM Playback Switch", 0},
439         {"IEC958 Output Switch", 1},
440         {"IEC958 Mix Analog", 0},
441         // {"IEC958 Out To DAC", 1}, // no longer used
442         {"IEC958 Loop", 0},
443 };
444 #define CM_SAVED_MIXERS         ARRAY_SIZE(cm_saved_mixer)
445
446 struct snd_stru_cmipci {
447         snd_card_t *card;
448
449         struct pci_dev *pci;
450         unsigned int device;    /* device ID */
451         int irq;
452
453         unsigned long iobase;
454         struct resource *res_iobase;
455         unsigned int ctrl;      /* FUNCTRL0 current value */
456
457         snd_pcm_t *pcm;         /* DAC/ADC PCM */
458         snd_pcm_t *pcm2;        /* 2nd DAC */
459         snd_pcm_t *pcm_spdif;   /* SPDIF */
460
461         int chip_version;
462         int max_channels;
463         unsigned int has_dual_dac: 1;
464         unsigned int can_ac3_sw: 1;
465         unsigned int can_ac3_hw: 1;
466         unsigned int can_multi_ch: 1;
467         unsigned int do_soft_ac3: 1;
468
469         unsigned int spdif_playback_avail: 1;   /* spdif ready? */
470         unsigned int spdif_playback_enabled: 1; /* spdif switch enabled? */
471         int spdif_counter;      /* for software AC3 */
472
473         unsigned int dig_status;
474         unsigned int dig_pcm_status;
475 #ifdef USE_AES_IEC958
476         snd_ctl_elem_value_t *spdif_channel;
477 #endif
478         snd_kcontrol_t *spdif_pcm_ctl;
479
480         snd_pcm_hardware_t *hw_info[3]; /* for playbacks */
481
482         int opened[2];  /* open mode */
483         struct semaphore open_mutex;
484
485         int mixer_insensitive: 1;
486         snd_kcontrol_t *mixer_res_ctl[CM_SAVED_MIXERS];
487         int mixer_res_status[CM_SAVED_MIXERS];
488
489         opl3_t *opl3;
490         snd_hwdep_t *opl3hwdep;
491
492         cmipci_pcm_t channel[2];        /* ch0 - DAC, ch1 - ADC or 2nd DAC */
493
494         /* external MIDI */
495         snd_rawmidi_t *rmidi;
496
497 #ifdef SUPPORT_JOYSTICK
498         struct gameport gameport;
499         struct resource *res_joystick;
500 #endif
501
502         spinlock_t reg_lock;
503 };
504
505
506 /* read/write operations for dword register */
507 inline static void snd_cmipci_write(cmipci_t *cm, unsigned int cmd, unsigned int data)
508 {
509         outl(data, cm->iobase + cmd);
510 }
511 inline static unsigned int snd_cmipci_read(cmipci_t *cm, unsigned int cmd)
512 {
513         return inl(cm->iobase + cmd);
514 }
515
516 /* read/write operations for word register */
517 inline static void snd_cmipci_write_w(cmipci_t *cm, unsigned int cmd, unsigned short data)
518 {
519         outw(data, cm->iobase + cmd);
520 }
521 inline static unsigned short snd_cmipci_read_w(cmipci_t *cm, unsigned int cmd)
522 {
523         return inw(cm->iobase + cmd);
524 }
525
526 /* read/write operations for byte register */
527 inline static void snd_cmipci_write_b(cmipci_t *cm, unsigned int cmd, unsigned char data)
528 {
529         outb(data, cm->iobase + cmd);
530 }
531
532 inline static unsigned char snd_cmipci_read_b(cmipci_t *cm, unsigned int cmd)
533 {
534         return inb(cm->iobase + cmd);
535 }
536
537 /* bit operations for dword register */
538 static void snd_cmipci_set_bit(cmipci_t *cm, unsigned int cmd, unsigned int flag)
539 {
540         unsigned int val;
541         val = inl(cm->iobase + cmd);
542         val |= flag;
543         outl(val, cm->iobase + cmd);
544 }
545
546 static void snd_cmipci_clear_bit(cmipci_t *cm, unsigned int cmd, unsigned int flag)
547 {
548         unsigned int val;
549         val = inl(cm->iobase + cmd);
550         val &= ~flag;
551         outl(val, cm->iobase + cmd);
552 }
553
554 #if 0 // not used
555 /* bit operations for byte register */
556 static void snd_cmipci_set_bit_b(cmipci_t *cm, unsigned int cmd, unsigned char flag)
557 {
558         unsigned char val;
559         val = inb(cm->iobase + cmd);
560         val |= flag;
561         outb(val, cm->iobase + cmd);
562 }
563
564 static void snd_cmipci_clear_bit_b(cmipci_t *cm, unsigned int cmd, unsigned char flag)
565 {
566         unsigned char val;
567         val = inb(cm->iobase + cmd);
568         val &= ~flag;
569         outb(val, cm->iobase + cmd);
570 }
571 #endif
572
573
574 /*
575  * PCM interface
576  */
577
578 /*
579  * calculate frequency
580  */
581
582 static unsigned int rates[] = { 5512, 11025, 22050, 44100, 8000, 16000, 32000, 48000 };
583
584 static unsigned int snd_cmipci_rate_freq(unsigned int rate)
585 {
586         unsigned int i;
587         for (i = 0; i < ARRAY_SIZE(rates); i++) {
588                 if (rates[i] == rate)
589                         return i;
590         }
591         snd_BUG();
592         return 0;
593 }
594
595 #ifdef USE_VAR48KRATE
596 /*
597  * Determine PLL values for frequency setup, maybe the CMI8338 (CMI8738???)
598  * does it this way .. maybe not.  Never get any information from C-Media about
599  * that <werner@suse.de>.
600  */
601 static int snd_cmipci_pll_rmn(unsigned int rate, unsigned int adcmult, int *r, int *m, int *n)
602 {
603         unsigned int delta, tolerance;
604         int xm, xn, xr;
605
606         for (*r = 0; rate < CM_MAXIMUM_RATE/adcmult; *r += (1<<5))
607                 rate <<= 1;
608         *n = -1;
609         if (*r > 0xff)
610                 goto out;
611         tolerance = rate*CM_TOLERANCE_RATE;
612
613         for (xn = (1+2); xn < (0x1f+2); xn++) {
614                 for (xm = (1+2); xm < (0xff+2); xm++) {
615                         xr = ((CM_REFFREQ_XIN/adcmult) * xm) / xn;
616
617                         if (xr < rate)
618                                 delta = rate - xr;
619                         else
620                                 delta = xr - rate;
621
622                         /*
623                          * If we found one, remember this,
624                          * and try to find a closer one
625                          */
626                         if (delta < tolerance) {
627                                 tolerance = delta;
628                                 *m = xm - 2;
629                                 *n = xn - 2;
630                         }
631                 }
632         }
633 out:
634         return (*n > -1);
635 }
636
637 /*
638  * Program pll register bits, I assume that the 8 registers 0xf8 upto 0xff
639  * are mapped onto the 8 ADC/DAC sampling frequency which can be choosen
640  * at the register CM_REG_FUNCTRL1 (0x04).
641  * Problem: other ways are also possible (any information about that?)
642  */
643 static void snd_cmipci_set_pll(cmipci_t *cm, unsigned int rate, unsigned int slot)
644 {
645         unsigned int reg = CM_REG_PLL + slot;
646         /*
647          * Guess that this programs at reg. 0x04 the pos 15:13/12:10
648          * for DSFC/ASFC (000 upto 111).
649          */
650
651         /* FIXME: Init (Do we've to set an other register first before programming?) */
652
653         /* FIXME: Is this correct? Or shouldn't the m/n/r values be used for that? */
654         snd_cmipci_write_b(cm, reg, rate>>8);
655         snd_cmipci_write_b(cm, reg, rate&0xff);
656
657         /* FIXME: Setup (Do we've to set an other register first to enable this?) */
658 }
659 #endif /* USE_VAR48KRATE */
660
661 static int snd_cmipci_hw_params(snd_pcm_substream_t * substream,
662                                 snd_pcm_hw_params_t * hw_params)
663 {
664         return snd_pcm_lib_malloc_pages(substream, params_buffer_bytes(hw_params));
665 }
666
667 static int snd_cmipci_playback2_hw_params(snd_pcm_substream_t * substream,
668                                           snd_pcm_hw_params_t * hw_params)
669 {
670         cmipci_t *cm = snd_pcm_substream_chip(substream);
671         if (params_channels(hw_params) > 2) {
672                 down(&cm->open_mutex);
673                 if (cm->opened[CM_CH_PLAY]) {
674                         up(&cm->open_mutex);
675                         return -EBUSY;
676                 }
677                 /* reserve the channel A */
678                 cm->opened[CM_CH_PLAY] = CM_OPEN_PLAYBACK_MULTI;
679                 up(&cm->open_mutex);
680         }
681         return snd_pcm_lib_malloc_pages(substream, params_buffer_bytes(hw_params));
682 }
683
684 static void snd_cmipci_ch_reset(cmipci_t *cm, int ch)
685 {
686         int reset = CM_RST_CH0 << (cm->channel[ch].ch);
687         snd_cmipci_write(cm, CM_REG_FUNCTRL0, cm->ctrl | reset);
688         snd_cmipci_write(cm, CM_REG_FUNCTRL0, cm->ctrl & ~reset);
689         udelay(10);
690 }
691
692 static int snd_cmipci_hw_free(snd_pcm_substream_t * substream)
693 {
694         return snd_pcm_lib_free_pages(substream);
695 }
696
697
698 /*
699  */
700
701 static unsigned int hw_channels[] = {1, 2, 4, 5, 6};
702 static snd_pcm_hw_constraint_list_t hw_constraints_channels_4 = {
703         .count = 3,
704         .list = hw_channels,
705         .mask = 0,
706 };
707 static snd_pcm_hw_constraint_list_t hw_constraints_channels_6 = {
708         .count = 5,
709         .list = hw_channels,
710         .mask = 0,
711 };
712
713 static int set_dac_channels(cmipci_t *cm, cmipci_pcm_t *rec, int channels)
714 {
715         unsigned long flags;
716
717         if (channels > 2) {
718                 if (! cm->can_multi_ch)
719                         return -EINVAL;
720                 if (rec->fmt != 0x03) /* stereo 16bit only */
721                         return -EINVAL;
722
723                 spin_lock_irqsave(&cm->reg_lock, flags);
724                 snd_cmipci_set_bit(cm, CM_REG_LEGACY_CTRL, CM_NXCHG);
725                 snd_cmipci_set_bit(cm, CM_REG_MISC_CTRL, CM_XCHGDAC);
726                 if (channels > 4) {
727                         snd_cmipci_clear_bit(cm, CM_REG_CHFORMAT, CM_CHB3D);
728                         snd_cmipci_set_bit(cm, CM_REG_CHFORMAT, CM_CHB3D5C);
729                 } else {
730                         snd_cmipci_clear_bit(cm, CM_REG_CHFORMAT, CM_CHB3D5C);
731                         snd_cmipci_set_bit(cm, CM_REG_CHFORMAT, CM_CHB3D);
732                 }
733                 if (channels == 6) {
734                         snd_cmipci_set_bit(cm, CM_REG_LEGACY_CTRL, CM_CHB3D6C);
735                         snd_cmipci_set_bit(cm, CM_REG_MISC_CTRL, CM_ENCENTER);
736                 } else {
737                         snd_cmipci_clear_bit(cm, CM_REG_LEGACY_CTRL, CM_CHB3D6C);
738                         snd_cmipci_clear_bit(cm, CM_REG_MISC_CTRL, CM_ENCENTER);
739                 }
740                 spin_unlock_irqrestore(&cm->reg_lock, flags);
741
742         } else {
743                 if (cm->can_multi_ch) {
744                         spin_lock_irqsave(&cm->reg_lock, flags);
745                         snd_cmipci_clear_bit(cm, CM_REG_LEGACY_CTRL, CM_NXCHG);
746                         snd_cmipci_clear_bit(cm, CM_REG_CHFORMAT, CM_CHB3D);
747                         snd_cmipci_clear_bit(cm, CM_REG_CHFORMAT, CM_CHB3D5C);
748                         snd_cmipci_clear_bit(cm, CM_REG_LEGACY_CTRL, CM_CHB3D6C);
749                         snd_cmipci_clear_bit(cm, CM_REG_MISC_CTRL, CM_ENCENTER);
750                         snd_cmipci_clear_bit(cm, CM_REG_MISC_CTRL, CM_XCHGDAC);
751                         spin_unlock_irqrestore(&cm->reg_lock, flags);
752                 }
753         }
754         return 0;
755 }
756
757
758 /*
759  * prepare playback/capture channel
760  * channel to be used must have been set in rec->ch.
761  */
762 static int snd_cmipci_pcm_prepare(cmipci_t *cm, cmipci_pcm_t *rec,
763                                  snd_pcm_substream_t *substream)
764 {
765         unsigned long flags;
766         unsigned int reg, freq, val;
767         snd_pcm_runtime_t *runtime = substream->runtime;
768
769         rec->fmt = 0;
770         rec->shift = 0;
771         if (snd_pcm_format_width(runtime->format) >= 16) {
772                 rec->fmt |= 0x02;
773                 if (snd_pcm_format_width(runtime->format) > 16)
774                         rec->shift++; /* 24/32bit */
775         }
776         if (runtime->channels > 1)
777                 rec->fmt |= 0x01;
778         if (rec->is_dac && set_dac_channels(cm, rec, runtime->channels) < 0) {
779                 snd_printd("cannot set dac channels\n");
780                 return -EINVAL;
781         }
782
783         rec->offset = runtime->dma_addr;
784         /* buffer and period sizes in frame */
785         rec->dma_size = runtime->buffer_size << rec->shift;
786         rec->period_size = runtime->period_size << rec->shift;
787         rec->dma_size <<= rec->ac3_shift;
788         rec->period_size <<= rec->ac3_shift;
789         if (runtime->channels > 2) {
790                 /* multi-channels */
791                 rec->dma_size = (rec->dma_size * runtime->channels) / 2;
792                 rec->period_size = (rec->period_size * runtime->channels) / 2;
793         }
794
795         spin_lock_irqsave(&cm->reg_lock, flags);
796
797         /* set buffer address */
798         reg = rec->ch ? CM_REG_CH1_FRAME1 : CM_REG_CH0_FRAME1;
799         snd_cmipci_write(cm, reg, rec->offset);
800         /* program sample counts */
801         reg = rec->ch ? CM_REG_CH1_FRAME2 : CM_REG_CH0_FRAME2;
802         snd_cmipci_write_w(cm, reg, rec->dma_size - 1);
803         snd_cmipci_write_w(cm, reg + 2, rec->period_size - 1);
804
805         /* set adc/dac flag */
806         val = rec->ch ? CM_CHADC1 : CM_CHADC0;
807         if (rec->is_dac)
808                 cm->ctrl &= ~val;
809         else
810                 cm->ctrl |= val;
811         snd_cmipci_write(cm, CM_REG_FUNCTRL0, cm->ctrl);
812         //snd_printd("cmipci: functrl0 = %08x\n", cm->ctrl);
813
814         /* set sample rate */
815         freq = snd_cmipci_rate_freq(runtime->rate);
816         val = snd_cmipci_read(cm, CM_REG_FUNCTRL1);
817         if (rec->ch) {
818                 val &= ~CM_ASFC_MASK;
819                 val |= (freq << CM_ASFC_SHIFT) & CM_ASFC_MASK;
820         } else {
821                 val &= ~CM_DSFC_MASK;
822                 val |= (freq << CM_DSFC_SHIFT) & CM_DSFC_MASK;
823         }
824         snd_cmipci_write(cm, CM_REG_FUNCTRL1, val);
825         //snd_printd("cmipci: functrl1 = %08x\n", val);
826
827         /* set format */
828         val = snd_cmipci_read(cm, CM_REG_CHFORMAT);
829         if (rec->ch) {
830                 val &= ~CM_CH1FMT_MASK;
831                 val |= rec->fmt << CM_CH1FMT_SHIFT;
832         } else {
833                 val &= ~CM_CH0FMT_MASK;
834                 val |= rec->fmt << CM_CH0FMT_SHIFT;
835         }
836         snd_cmipci_write(cm, CM_REG_CHFORMAT, val);
837         //snd_printd("cmipci: chformat = %08x\n", val);
838
839         rec->running = 0;
840         spin_unlock_irqrestore(&cm->reg_lock, flags);
841
842         return 0;
843 }
844
845 /*
846  * PCM trigger/stop
847  */
848 static int snd_cmipci_pcm_trigger(cmipci_t *cm, cmipci_pcm_t *rec,
849                                  snd_pcm_substream_t *substream, int cmd)
850 {
851         unsigned int inthld, chen, reset, pause;
852         int result = 0;
853
854         inthld = CM_CH0_INT_EN << rec->ch;
855         chen = CM_CHEN0 << rec->ch;
856         reset = CM_RST_CH0 << rec->ch;
857         pause = CM_PAUSE0 << rec->ch;
858
859         spin_lock(&cm->reg_lock);
860         switch (cmd) {
861         case SNDRV_PCM_TRIGGER_START:
862                 rec->running = 1;
863                 /* set interrupt */
864                 snd_cmipci_set_bit(cm, CM_REG_INT_HLDCLR, inthld);
865                 cm->ctrl |= chen;
866                 /* enable channel */
867                 snd_cmipci_write(cm, CM_REG_FUNCTRL0, cm->ctrl);
868                 //snd_printd("cmipci: functrl0 = %08x\n", cm->ctrl);
869                 break;
870         case SNDRV_PCM_TRIGGER_STOP:
871                 rec->running = 0;
872                 /* disable interrupt */
873                 snd_cmipci_clear_bit(cm, CM_REG_INT_HLDCLR, inthld);
874                 /* reset */
875                 cm->ctrl &= ~chen;
876                 snd_cmipci_write(cm, CM_REG_FUNCTRL0, cm->ctrl | reset);
877                 snd_cmipci_write(cm, CM_REG_FUNCTRL0, cm->ctrl & ~reset);
878                 break;
879         case SNDRV_PCM_TRIGGER_PAUSE_PUSH:
880                 cm->ctrl |= pause;
881                 snd_cmipci_write(cm, CM_REG_FUNCTRL0, cm->ctrl);
882                 break;
883         case SNDRV_PCM_TRIGGER_PAUSE_RELEASE:
884                 cm->ctrl &= ~pause;
885                 snd_cmipci_write(cm, CM_REG_FUNCTRL0, cm->ctrl);
886                 break;
887         default:
888                 result = -EINVAL;
889                 break;
890         }
891         spin_unlock(&cm->reg_lock);
892         return result;
893 }
894
895 /*
896  * return the current pointer
897  */
898 static snd_pcm_uframes_t snd_cmipci_pcm_pointer(cmipci_t *cm, cmipci_pcm_t *rec,
899                                           snd_pcm_substream_t *substream)
900 {
901         size_t ptr;
902         unsigned int reg;
903         if (!rec->running)
904                 return 0;
905 #if 1 // this seems better..
906         reg = rec->ch ? CM_REG_CH1_FRAME2 : CM_REG_CH0_FRAME2;
907         ptr = rec->dma_size - (snd_cmipci_read_w(cm, reg) + 1);
908         ptr >>= rec->shift;
909 #else
910         reg = rec->ch ? CM_REG_CH1_FRAME1 : CM_REG_CH0_FRAME1;
911         ptr = snd_cmipci_read(cm, reg) - rec->offset;
912         ptr = bytes_to_frames(substream->runtime, ptr);
913 #endif
914         ptr >>= rec->ac3_shift;
915         if (substream->runtime->channels > 2)
916                 ptr = (ptr * 2) / substream->runtime->channels;
917         return ptr;
918 }
919
920 /*
921  * playback
922  */
923
924 static int snd_cmipci_playback_trigger(snd_pcm_substream_t *substream,
925                                        int cmd)
926 {
927         cmipci_t *cm = snd_pcm_substream_chip(substream);
928         return snd_cmipci_pcm_trigger(cm, &cm->channel[CM_CH_PLAY], substream, cmd);
929 }
930
931 static snd_pcm_uframes_t snd_cmipci_playback_pointer(snd_pcm_substream_t *substream)
932 {
933         cmipci_t *cm = snd_pcm_substream_chip(substream);
934         return snd_cmipci_pcm_pointer(cm, &cm->channel[CM_CH_PLAY], substream);
935 }
936
937
938
939 /*
940  * capture
941  */
942
943 static int snd_cmipci_capture_trigger(snd_pcm_substream_t *substream,
944                                      int cmd)
945 {
946         cmipci_t *cm = snd_pcm_substream_chip(substream);
947         return snd_cmipci_pcm_trigger(cm, &cm->channel[CM_CH_CAPT], substream, cmd);
948 }
949
950 static snd_pcm_uframes_t snd_cmipci_capture_pointer(snd_pcm_substream_t *substream)
951 {
952         cmipci_t *cm = snd_pcm_substream_chip(substream);
953         return snd_cmipci_pcm_pointer(cm, &cm->channel[CM_CH_CAPT], substream);
954 }
955
956 #ifdef DO_SOFT_AC3
957 /*
958  * special tricks for soft ac3 transfer:
959  *
960  * we compose an iec958 subframe from 16bit ac3 sample and
961  * write the raw subframe via 32bit data mode.
962  */
963
964 # ifndef USE_AES_IEC958
965
966 /* find parity for bit 4~30 */
967 static unsigned int parity(unsigned int data)
968 {
969         unsigned int parity = 0;
970         int counter = 4;
971
972         data >>= 4;     /* start from bit 4 */
973         while (counter <= 30) {
974                 if (data & 1)
975                         parity++;
976                 data >>= 1;
977                 counter++;
978         }
979         return parity & 1;
980 }
981
982 /*
983  * compose 32bit iec958 subframe with non-audio data.
984  * bit 0-3  = preamble
985  *     4-7  = aux (=0)
986  *     8-27 = data (12-27 for 16bit)
987  *     28   = validity (=0)
988  *     29   = user data (=0)
989  *     30   = channel status
990  *     31   = parity
991  *
992  * channel status is assumed as consumer, non-audio
993  * thus all 0 except bit 1
994  */
995 inline static u32 convert_ac3_32bit(cmipci_t *cm, u32 val)
996 {
997         u32 data = (u32)val << 12;
998
999         if (cm->spdif_counter == 2 || cm->spdif_counter == 3) /* bit 1 */
1000                 data |= 0x40000000;     /* indicate AC-3 raw data */
1001         if (parity(data))               /* parity bit 4-30 */
1002                 data |= 0x80000000;
1003         if (cm->spdif_counter == 0)
1004                 data |= 3;              /* preamble 'M' */
1005         else if (cm->spdif_counter & 1)
1006                 data |= 5;              /* odd, 'W' */
1007         else
1008                 data |= 9;              /* even, 'M' */
1009
1010         cm->spdif_counter++;
1011         if (cm->spdif_counter == 384)
1012                 cm->spdif_counter = 0;
1013
1014         return data;
1015 }
1016
1017 # else  /* if USE_AES_IEC958 */
1018
1019 /*
1020  * The bitstream handling
1021  */
1022 typedef struct iec958_stru_bitstream {
1023         u32 *data;              /* Holds the current position */
1024         u32  left;              /* Bits left in current 32bit frame */
1025         u32  word;              /* The 32bit frame of the current position */
1026         u32  bits;              /* All bits together */
1027         int   err;              /* Error condition */
1028 } iec958_bitstream_t ;
1029
1030 static iec958_bitstream_t bs;
1031
1032 /* Initialize ptr on the buffer */
1033 static void iec958_init_bitstream(u8 *buf, u32 size)
1034 {
1035         bs.data = (u32 *)buf;           /* Set initial position */
1036         bs.word = *bs.data;             /* The first 32bit frame */
1037         bs.left = 32;                   /* has exactly 32bits */
1038         bs.bits = size;
1039         bs.err = 0;
1040 }
1041
1042 /* Remove ptr on the buffer */
1043 static void iec958_clear_bitstream(void)
1044 {
1045         bs.data = NULL;
1046         bs.left = 0;
1047         bs.err = 0;
1048 }
1049
1050 /* Get bits from bitstream (max 32) */
1051 static inline u32 iec958_getbits(u32 bits)
1052 {
1053         u32 res;
1054
1055         if (bs.bits < bits) {
1056                 bits = bs.bits;
1057                 bs.err = 1;
1058         }
1059         if (bits > 32) {
1060                 bits = 32;
1061                 bs.err = 1;
1062         }
1063         bs.bits -= bits;
1064
1065 #  ifdef WORDS_BIGENDIAN
1066         if (bits < bs.left) {           /* Within 32bit frame */
1067                 res = (bs.word << (32 - bs.left)) >> (32 - bits);
1068                 bs.left -= bits;
1069                 goto out;
1070         }                               /* We may cross the frame boundary */
1071         res   = (bs.word << (32 - bs.left)) >> (32 - bs.left);
1072         bits -= bs.left;
1073
1074         bs.word = *(++bs.data);         /* Next 32bit frame */
1075
1076         if (bits)                       /* Add remaining bits, if any */
1077                 res = (res << bits) | (bs.word >> (32 - bits));
1078
1079 #  else  /* not WORDS_BIGENDIAN */
1080
1081         if (bits < bs.left) {           /* Within 32bit frame */
1082                 res = (bs.word << (32 - bits)) >> (32 - bits);
1083                 bs.word >>= bits;
1084                 bs.left -= bits;
1085                 goto out;
1086         }                               /* We may cross the frame boundary */
1087         res   = bs.word;
1088         bits -= bs.left;
1089
1090         bs.word = *(++bs.data);         /* Next 32bit frame */
1091
1092         if (bits) {                     /* Add remaining bits, if any */
1093                 res = res | (((bs.word << (32 - bits)) >> (32 - bits)) << bits);
1094                 bs.word >>= bits;
1095         }
1096 #  endif /* not WORDS_BIGENDIAN */
1097
1098         bs.left = (32 - bits);
1099 out:
1100         return res;
1101 }
1102
1103 static inline u32 iec958_bits_avail(void)
1104 {
1105         return bs.bits;
1106 }
1107
1108 static inline int iec958_error(void)
1109 {
1110         return bs.err;
1111 }
1112
1113 /*
1114  * Determine parity for time slots 4 upto 30
1115  * to be sure that bit 4 upt 31 will carry
1116  * an even number of ones and zeros.
1117  */
1118 static u32 iec958_parity(u32 data)
1119 {
1120         u32 parity = 0;
1121         int counter = 4;
1122
1123         data >>= 4;     /* start from bit 4 */
1124         while (counter++ <= 30) {
1125                 if (data & 0x00000001)
1126                         parity++;
1127                 data >>= 1;
1128         }
1129         return (parity & 0x00000001);
1130 }
1131
1132 /*
1133  * Compose 32bit iec958 subframe, two sub frames
1134  * build one frame with two channels.
1135  *
1136  * bit 0-3  = preamble
1137  *     4-7  = AUX (=0)
1138  *     8-27 = data (12-27 for 16bit, 8-27 for 20bit, and 24bit without AUX)
1139  *     28   = validity (0 for valid data, else 'in error')
1140  *     29   = user data (0)
1141  *     30   = channel status (24 bytes for 192 frames)
1142  *     31   = parity
1143  */
1144
1145 static inline u32 iec958_subframe(cmipci_t *cm, snd_ctl_elem_value_t * ucontrol)
1146 {
1147         u32 data;
1148         u32 byte = cm->spdif_counter >> 4;
1149         u32 mask = 1 << ((cm->spdif_counter >> 1) - (byte << 3));
1150         u8 * status = ucontrol->value.iec958.status;
1151
1152         if (status[2] & IEC958_AES2_PRO_SBITS_24) {
1153                 /* Does this work for LE systems ??? */
1154                 if (status[2] & IEC958_AES2_PRO_WORDLEN_24_20) {
1155                         data = iec958_getbits(24);
1156                         data <<= 4;
1157                 } else {
1158                         data = iec958_getbits(20);
1159                         data <<= 8;
1160                 }
1161         } else {
1162                 if (status[2] & IEC958_AES2_PRO_WORDLEN_24_20) {
1163                         /* Does this work for LE systems ??? */
1164                         data = iec958_getbits(20);
1165                         data <<= 8;
1166                 } else {
1167                         data = iec958_getbits(16);
1168                         data <<= 12;
1169                 }
1170         }
1171
1172         /*
1173          * Set one of the 192 bits of the channel status (AES3 and higher)
1174          */
1175         if (status[byte] & mask)
1176                 data |= 0x40000000;
1177
1178         if (iec958_parity(data))        /* parity bit 4-30 */
1179                 data |= 0x80000000;
1180
1181         /* Preamble */
1182         if      (!cm->spdif_counter)
1183                 data |= 0x03;           /* Block start, 'Z' */
1184         else if (cm->spdif_counter % 2)
1185                 data |= 0x05;           /* odd sub frame, 'Y' */
1186         else
1187                 data |= 0x09;           /* even sub frame, 'X' */
1188
1189         /*
1190          * sub frame counter: 2 sub frame are one audio frame
1191          * and 192 frames are one block
1192          */
1193         cm->spdif_counter = (++cm->spdif_counter) % 384;
1194
1195         return data;
1196 }
1197 # endif /* if USE_AES_IEC958 */
1198
1199 static int snd_cmipci_ac3_copy(snd_pcm_substream_t *subs, int channel,
1200                                snd_pcm_uframes_t pos, void *src,
1201                                snd_pcm_uframes_t count)
1202 {
1203         cmipci_t *cm = snd_pcm_substream_chip(subs);
1204         u32 *dst;
1205         snd_pcm_uframes_t offset;
1206         snd_pcm_runtime_t *runtime = subs->runtime;
1207 #ifndef USE_AES_IEC958
1208         u16 *srcp = src, val;
1209 #else
1210         char buf[480];         /* bits can be divided by 20, 24, 16 */
1211         size_t bytes = frames_to_bytes(runtime, count);
1212 #endif
1213
1214
1215         if (!cm->channel[CM_CH_PLAY].ac3_shift) {
1216                 if (copy_from_user(runtime->dma_area +
1217                                    frames_to_bytes(runtime, pos), src,
1218                                    frames_to_bytes(runtime, count)))
1219                         return -EFAULT;
1220                 return 0;
1221         }
1222
1223         if (! access_ok(VERIFY_READ, src, count))
1224                 return -EFAULT;
1225
1226         /* frame = 16bit stereo */
1227         offset = (pos << 1) % (cm->channel[CM_CH_PLAY].dma_size << 2);
1228         dst = (u32*)(runtime->dma_area + offset);
1229 # ifndef USE_AES_IEC958
1230         count /= 2;
1231         while (count-- > 0) {
1232                 get_user(val, srcp);
1233                 srcp++;
1234                 *dst++ = convert_ac3_32bit(cm, val);
1235         }
1236 # else
1237         while (bytes) {
1238                 size_t c = bytes;
1239
1240                 if (c > sizeof(buf))
1241                         c = sizeof(buf);
1242
1243                 if (copy_from_user(buf, src, c))
1244                         return -EFAULT;
1245                 bytes -= c;
1246                 src   += c;
1247
1248                 iec958_init_bitstream(buf, c*8);
1249                 while (iec958_bits_avail()) {
1250                         *(dst++) = iec958_subframe(cm, cm->spdif_channel);
1251                         if (iec958_error())
1252                                 return -EINVAL;
1253                 }
1254                 iec958_clear_bitstream();
1255         }
1256 # endif
1257         return 0;
1258 }
1259
1260 static int snd_cmipci_ac3_silence(snd_pcm_substream_t *subs, int channel,
1261                                   snd_pcm_uframes_t pos,
1262                                   snd_pcm_uframes_t count)
1263 {
1264         cmipci_t *cm = snd_pcm_substream_chip(subs);
1265         u32 *dst;
1266         snd_pcm_uframes_t offset;
1267         snd_pcm_runtime_t *runtime = subs->runtime;
1268 # ifdef USE_AES_IEC958
1269         char buf[480];          /* bits can be divided by 20, 24, 16 */
1270         size_t bytes = frames_to_bytes(runtime, count);
1271 # endif
1272         if (! cm->channel[CM_CH_PLAY].ac3_shift)
1273                 return snd_pcm_format_set_silence(runtime->format,
1274                                                   runtime->dma_area + frames_to_bytes(runtime, pos), count);
1275         
1276         /* frame = 16bit stereo */
1277         offset = (pos << 1) % (cm->channel[CM_CH_PLAY].dma_size << 2);
1278         dst = (u32*)(subs->runtime->dma_area + offset);
1279 # ifndef USE_AES_IEC958
1280         count /= 2;
1281         while (count-- > 0) {
1282                 *dst++ = convert_ac3_32bit(cm, 0);
1283         }
1284 # else
1285         while (bytes) {
1286                 size_t c = bytes;
1287
1288                 if (c > sizeof(buf))
1289                         c = sizeof(buf);
1290
1291                 /* Q: Does this function know about 24bit silence? */
1292                 if (snd_pcm_format_set_silence(runtime->format, buf, bytes_to_frames(runtime, c)))
1293                         return -EINVAL;
1294
1295                 iec958_init_bitstream(buf, c*8);
1296                 while (iec958_bits_avail()) {
1297                         *(dst++) = iec958_subframe(cm, cm->spdif_channel);
1298                         if (iec958_error())
1299                                 return -EINVAL;
1300                 }
1301                 iec958_clear_bitstream();
1302         }
1303 # endif
1304         return 0;
1305 }
1306 #endif /* DO_SOFT_AC3 */
1307
1308
1309 /*
1310  * hw preparation for spdif
1311  */
1312
1313 static int snd_cmipci_spdif_default_info(snd_kcontrol_t *kcontrol,
1314                                          snd_ctl_elem_info_t *uinfo)
1315 {
1316         uinfo->type = SNDRV_CTL_ELEM_TYPE_IEC958;
1317         uinfo->count = 1;
1318         return 0;
1319 }
1320
1321 static int snd_cmipci_spdif_default_get(snd_kcontrol_t *kcontrol,
1322                                         snd_ctl_elem_value_t *ucontrol)
1323 {
1324         cmipci_t *chip = snd_kcontrol_chip(kcontrol);
1325         unsigned long flags;
1326         int i;
1327
1328         spin_lock_irqsave(&chip->reg_lock, flags);
1329         for (i = 0; i < 4; i++)
1330                 ucontrol->value.iec958.status[i] = (chip->dig_status >> (i * 8)) & 0xff;
1331         spin_unlock_irqrestore(&chip->reg_lock, flags);
1332         return 0;
1333 }
1334
1335 static int snd_cmipci_spdif_default_put(snd_kcontrol_t * kcontrol,
1336                                          snd_ctl_elem_value_t * ucontrol)
1337 {
1338         cmipci_t *chip = snd_kcontrol_chip(kcontrol);
1339         unsigned long flags;
1340         int i, change;
1341         unsigned int val;
1342
1343         val = 0;
1344         spin_lock_irqsave(&chip->reg_lock, flags);
1345         for (i = 0; i < 4; i++)
1346                 val |= (unsigned int)ucontrol->value.iec958.status[i] << (i * 8);
1347         change = val != chip->dig_status;
1348         chip->dig_status = val;
1349         spin_unlock_irqrestore(&chip->reg_lock, flags);
1350         return change;
1351 }
1352
1353 static snd_kcontrol_new_t snd_cmipci_spdif_default __devinitdata =
1354 {
1355         .iface =        SNDRV_CTL_ELEM_IFACE_PCM,
1356         .name =         SNDRV_CTL_NAME_IEC958("",PLAYBACK,DEFAULT),
1357         .info =         snd_cmipci_spdif_default_info,
1358         .get =          snd_cmipci_spdif_default_get,
1359         .put =          snd_cmipci_spdif_default_put
1360 };
1361
1362 static int snd_cmipci_spdif_mask_info(snd_kcontrol_t *kcontrol,
1363                                       snd_ctl_elem_info_t *uinfo)
1364 {
1365         uinfo->type = SNDRV_CTL_ELEM_TYPE_IEC958;
1366         uinfo->count = 1;
1367         return 0;
1368 }
1369
1370 static int snd_cmipci_spdif_mask_get(snd_kcontrol_t * kcontrol,
1371                                      snd_ctl_elem_value_t *ucontrol)
1372 {
1373         ucontrol->value.iec958.status[0] = 0xff;
1374         ucontrol->value.iec958.status[1] = 0xff;
1375         ucontrol->value.iec958.status[2] = 0xff;
1376         ucontrol->value.iec958.status[3] = 0xff;
1377         return 0;
1378 }
1379
1380 static snd_kcontrol_new_t snd_cmipci_spdif_mask __devinitdata =
1381 {
1382         .access =       SNDRV_CTL_ELEM_ACCESS_READ,
1383         .iface =        SNDRV_CTL_ELEM_IFACE_MIXER,
1384         .name =         SNDRV_CTL_NAME_IEC958("",PLAYBACK,CON_MASK),
1385         .info =         snd_cmipci_spdif_mask_info,
1386         .get =          snd_cmipci_spdif_mask_get,
1387 };
1388
1389 static int snd_cmipci_spdif_stream_info(snd_kcontrol_t *kcontrol,
1390                                         snd_ctl_elem_info_t *uinfo)
1391 {
1392         uinfo->type = SNDRV_CTL_ELEM_TYPE_IEC958;
1393         uinfo->count = 1;
1394         return 0;
1395 }
1396
1397 static int snd_cmipci_spdif_stream_get(snd_kcontrol_t *kcontrol,
1398                                        snd_ctl_elem_value_t *ucontrol)
1399 {
1400         cmipci_t *chip = snd_kcontrol_chip(kcontrol);
1401         unsigned long flags;
1402         int i;
1403
1404         spin_lock_irqsave(&chip->reg_lock, flags);
1405         for (i = 0; i < 4; i++)
1406                 ucontrol->value.iec958.status[i] = (chip->dig_pcm_status >> (i * 8)) & 0xff;
1407 #ifdef USE_AES_IEC958
1408         ucontrol = chip->spdif_channel;
1409 #endif
1410         spin_unlock_irqrestore(&chip->reg_lock, flags);
1411         return 0;
1412 }
1413
1414 static int snd_cmipci_spdif_stream_put(snd_kcontrol_t *kcontrol,
1415                                        snd_ctl_elem_value_t *ucontrol)
1416 {
1417         cmipci_t *chip = snd_kcontrol_chip(kcontrol);
1418         unsigned long flags;
1419         int i, change;
1420         unsigned int val;
1421
1422         val = 0;
1423         spin_lock_irqsave(&chip->reg_lock, flags);
1424         for (i = 0; i < 4; i++)
1425                 val |= (unsigned int)ucontrol->value.iec958.status[i] << (i * 8);
1426         change = val != chip->dig_pcm_status;
1427         chip->dig_pcm_status = val;
1428 #ifdef USE_AES_IEC958
1429         chip->spdif_channel = ucontrol;
1430 #endif
1431         spin_unlock_irqrestore(&chip->reg_lock, flags);
1432         return change;
1433 }
1434
1435 static snd_kcontrol_new_t snd_cmipci_spdif_stream __devinitdata =
1436 {
1437         .access =       SNDRV_CTL_ELEM_ACCESS_READWRITE | SNDRV_CTL_ELEM_ACCESS_INACTIVE,
1438         .iface =        SNDRV_CTL_ELEM_IFACE_PCM,
1439         .name =         SNDRV_CTL_NAME_IEC958("",PLAYBACK,PCM_STREAM),
1440         .info =         snd_cmipci_spdif_stream_info,
1441         .get =          snd_cmipci_spdif_stream_get,
1442         .put =          snd_cmipci_spdif_stream_put
1443 };
1444
1445 /*
1446  */
1447
1448 /* save mixer setting and mute for AC3 playback */
1449 static void save_mixer_state(cmipci_t *cm)
1450 {
1451         if (! cm->mixer_insensitive) {
1452                 unsigned int i;
1453                 for (i = 0; i < CM_SAVED_MIXERS; i++) {
1454                         snd_kcontrol_t *ctl = cm->mixer_res_ctl[i];
1455                         if (ctl) {
1456                                 snd_ctl_elem_value_t val;
1457                                 int event;
1458                                 memset(&val, 0, sizeof(val));
1459                                 ctl->get(ctl, &val);
1460                                 cm->mixer_res_status[i] = val.value.integer.value[0];
1461                                 val.value.integer.value[0] = cm_saved_mixer[i].toggle_on;
1462                                 event = SNDRV_CTL_EVENT_MASK_INFO;
1463                                 if (cm->mixer_res_status[i] != val.value.integer.value[0]) {
1464                                         ctl->put(ctl, &val); /* toggle */
1465                                         event |= SNDRV_CTL_EVENT_MASK_VALUE;
1466                                 }
1467                                 ctl->vd[0].access |= SNDRV_CTL_ELEM_ACCESS_INACTIVE;
1468                                 snd_ctl_notify(cm->card, event, &ctl->id);
1469                         }
1470                 }
1471                 cm->mixer_insensitive = 1;
1472         }
1473 }
1474
1475
1476 /* restore the previously saved mixer status */
1477 static void restore_mixer_state(cmipci_t *cm)
1478 {
1479         if (cm->mixer_insensitive) {
1480                 unsigned int i;
1481                 cm->mixer_insensitive = 0; /* at first clear this;
1482                                               otherwise the changes will be ignored */
1483                 for (i = 0; i < CM_SAVED_MIXERS; i++) {
1484                         snd_kcontrol_t *ctl = cm->mixer_res_ctl[i];
1485                         if (ctl) {
1486                                 snd_ctl_elem_value_t val;
1487                                 int event;
1488
1489                                 memset(&val, 0, sizeof(val));
1490                                 ctl->vd[0].access &= ~SNDRV_CTL_ELEM_ACCESS_INACTIVE;
1491                                 ctl->get(ctl, &val);
1492                                 event = SNDRV_CTL_EVENT_MASK_INFO;
1493                                 if (val.value.integer.value[0] != cm->mixer_res_status[i]) {
1494                                         val.value.integer.value[0] = cm->mixer_res_status[i];
1495                                         ctl->put(ctl, &val);
1496                                         event |= SNDRV_CTL_EVENT_MASK_VALUE;
1497                                 }
1498                                 snd_ctl_notify(cm->card, event, &ctl->id);
1499                         }
1500                 }
1501         }
1502 }
1503
1504 /* spinlock held! */
1505 static void setup_ac3(cmipci_t *cm, snd_pcm_substream_t *subs, int do_ac3, int rate)
1506 {
1507         cm->channel[CM_CH_PLAY].ac3_shift = 0;
1508         cm->spdif_counter = 0;
1509
1510         if (do_ac3) {
1511                 /* AC3EN for 037 */
1512                 snd_cmipci_set_bit(cm, CM_REG_CHFORMAT, CM_AC3EN1);
1513                 /* AC3EN for 039 */
1514                 snd_cmipci_set_bit(cm, CM_REG_MISC_CTRL, CM_AC3EN2);
1515         
1516                 if (cm->can_ac3_hw) {
1517                         /* SPD24SEL for 037, 0x02 */
1518                         /* SPD24SEL for 039, 0x20, but cannot be set */
1519                         snd_cmipci_set_bit(cm, CM_REG_CHFORMAT, CM_SPD24SEL);
1520                         snd_cmipci_clear_bit(cm, CM_REG_MISC_CTRL, CM_SPD32SEL);
1521                 } else { /* can_ac3_sw */
1522 #ifdef DO_SOFT_AC3
1523                         /* FIXME: ugly hack! */
1524                         subs->runtime->buffer_size /= 2;
1525                         /* SPD32SEL for 037 & 039, 0x20 */
1526                         snd_cmipci_set_bit(cm, CM_REG_MISC_CTRL, CM_SPD32SEL);
1527                         /* set 176K sample rate to fix 033 HW bug */
1528                         if (cm->chip_version == 33) {
1529                                 if (rate >= 48000) {
1530                                         snd_cmipci_set_bit(cm, CM_REG_CHFORMAT, CM_PLAYBACK_SRATE_176K);
1531                                 } else {
1532                                         snd_cmipci_clear_bit(cm, CM_REG_CHFORMAT, CM_PLAYBACK_SRATE_176K);
1533                                 }
1534                         }
1535                         cm->channel[CM_CH_PLAY].ac3_shift = 1; /* use 32bit */
1536 #endif /* DO_SOFT_AC3 */
1537                 }
1538
1539         } else {
1540                 snd_cmipci_clear_bit(cm, CM_REG_CHFORMAT, CM_AC3EN1);
1541                 snd_cmipci_clear_bit(cm, CM_REG_MISC_CTRL, CM_AC3EN2);
1542
1543                 if (cm->can_ac3_hw) {
1544                         /* chip model >= 37 */
1545                         if (snd_pcm_format_width(subs->runtime->format) > 16) {
1546                                 snd_cmipci_set_bit(cm, CM_REG_MISC_CTRL, CM_SPD32SEL);
1547                                 snd_cmipci_set_bit(cm, CM_REG_CHFORMAT, CM_SPD24SEL);
1548                         } else {
1549                                 snd_cmipci_clear_bit(cm, CM_REG_MISC_CTRL, CM_SPD32SEL);
1550                                 snd_cmipci_clear_bit(cm, CM_REG_CHFORMAT, CM_SPD24SEL);
1551                         }
1552                 } else {
1553 #ifdef DO_SOFT_AC3
1554                         snd_cmipci_clear_bit(cm, CM_REG_MISC_CTRL, CM_SPD32SEL);
1555                         snd_cmipci_clear_bit(cm, CM_REG_CHFORMAT, CM_SPD24SEL);
1556                         snd_cmipci_clear_bit(cm, CM_REG_CHFORMAT, CM_PLAYBACK_SRATE_176K);
1557 #endif /* DO_SOFT_AC3 */
1558                 }
1559         }
1560 }
1561
1562 static void setup_spdif_playback(cmipci_t *cm, snd_pcm_substream_t *subs, int up, int do_ac3)
1563 {
1564         int rate;
1565         unsigned long flags;
1566
1567         rate = subs->runtime->rate;
1568
1569         if (up && do_ac3)
1570                 save_mixer_state(cm);
1571
1572         spin_lock_irqsave(&cm->reg_lock, flags);
1573         cm->spdif_playback_avail = up;
1574         if (up) {
1575                 /* they are controlled via "IEC958 Output Switch" */
1576                 /* snd_cmipci_set_bit(cm, CM_REG_LEGACY_CTRL, CM_ENSPDOUT); */
1577                 /* snd_cmipci_set_bit(cm, CM_REG_FUNCTRL1, CM_SPDO2DAC); */
1578                 if (cm->spdif_playback_enabled)
1579                         snd_cmipci_set_bit(cm, CM_REG_FUNCTRL1, CM_PLAYBACK_SPDF);
1580                 setup_ac3(cm, subs, do_ac3, rate);
1581
1582                 if (rate == 48000)
1583                         snd_cmipci_set_bit(cm, CM_REG_MISC_CTRL, CM_SPDIF48K | CM_SPDF_AC97);
1584                 else
1585                         snd_cmipci_clear_bit(cm, CM_REG_MISC_CTRL, CM_SPDIF48K | CM_SPDF_AC97);
1586
1587         } else {
1588                 /* they are controlled via "IEC958 Output Switch" */
1589                 /* snd_cmipci_clear_bit(cm, CM_REG_LEGACY_CTRL, CM_ENSPDOUT); */
1590                 /* snd_cmipci_clear_bit(cm, CM_REG_FUNCTRL1, CM_SPDO2DAC); */
1591                 snd_cmipci_clear_bit(cm, CM_REG_FUNCTRL1, CM_PLAYBACK_SPDF);
1592                 setup_ac3(cm, subs, 0, 0);
1593         }
1594         spin_unlock_irqrestore(&cm->reg_lock, flags);
1595 }
1596
1597
1598 /*
1599  * preparation
1600  */
1601
1602 /* playback - enable spdif only on the certain condition */
1603 static int snd_cmipci_playback_prepare(snd_pcm_substream_t *substream)
1604 {
1605         cmipci_t *cm = snd_pcm_substream_chip(substream);
1606         int rate = substream->runtime->rate;
1607         int do_spdif, do_ac3;
1608         do_spdif = ((rate == 44100 || rate == 48000) &&
1609                     substream->runtime->format == SNDRV_PCM_FORMAT_S16_LE &&
1610                     substream->runtime->channels == 2);
1611         do_ac3 = cm->dig_pcm_status & IEC958_AES0_NONAUDIO;
1612 #ifdef DO_SOFT_AC3
1613         if (do_ac3 && cm->can_ac3_sw)
1614                 do_spdif = 0;
1615 #endif
1616         setup_spdif_playback(cm, substream, do_spdif, do_ac3);
1617         return snd_cmipci_pcm_prepare(cm, &cm->channel[CM_CH_PLAY], substream);
1618 }
1619
1620 /* playback  (via device #2) - enable spdif always */
1621 static int snd_cmipci_playback_spdif_prepare(snd_pcm_substream_t *substream)
1622 {
1623         cmipci_t *cm = snd_pcm_substream_chip(substream);
1624         setup_spdif_playback(cm, substream, 1, cm->dig_pcm_status & IEC958_AES0_NONAUDIO);
1625         return snd_cmipci_pcm_prepare(cm, &cm->channel[CM_CH_PLAY], substream);
1626 }
1627
1628 static int snd_cmipci_playback_hw_free(snd_pcm_substream_t *substream)
1629 {
1630         cmipci_t *cm = snd_pcm_substream_chip(substream);
1631         setup_spdif_playback(cm, substream, 0, 0);
1632         restore_mixer_state(cm);
1633         return snd_cmipci_hw_free(substream);
1634 }
1635
1636 /* capture */
1637 static int snd_cmipci_capture_prepare(snd_pcm_substream_t *substream)
1638 {
1639         cmipci_t *cm = snd_pcm_substream_chip(substream);
1640         return snd_cmipci_pcm_prepare(cm, &cm->channel[CM_CH_CAPT], substream);
1641 }
1642
1643 /* capture with spdif (via device #2) */
1644 static int snd_cmipci_capture_spdif_prepare(snd_pcm_substream_t *substream)
1645 {
1646         cmipci_t *cm = snd_pcm_substream_chip(substream);
1647         unsigned long flags;
1648
1649         spin_lock_irqsave(&cm->reg_lock, flags);
1650         snd_cmipci_set_bit(cm, CM_REG_FUNCTRL1, CM_CAPTURE_SPDF);
1651         spin_unlock_irqrestore(&cm->reg_lock, flags);
1652
1653         return snd_cmipci_pcm_prepare(cm, &cm->channel[CM_CH_CAPT], substream);
1654 }
1655
1656 static int snd_cmipci_capture_spdif_hw_free(snd_pcm_substream_t *subs)
1657 {
1658         cmipci_t *cm = snd_pcm_substream_chip(subs);
1659         unsigned long flags;
1660
1661         spin_lock_irqsave(&cm->reg_lock, flags);
1662         snd_cmipci_clear_bit(cm, CM_REG_FUNCTRL1, CM_CAPTURE_SPDF);
1663         spin_unlock_irqrestore(&cm->reg_lock, flags);
1664
1665         return snd_cmipci_hw_free(subs);
1666 }
1667
1668
1669 /*
1670  * interrupt handler
1671  */
1672 static irqreturn_t snd_cmipci_interrupt(int irq, void *dev_id, struct pt_regs *regs)
1673 {
1674         cmipci_t *cm = snd_magic_cast(cmipci_t, dev_id, return IRQ_NONE);
1675         unsigned int status, mask = 0;
1676         
1677         /* fastpath out, to ease interrupt sharing */
1678         status = snd_cmipci_read(cm, CM_REG_INT_STATUS);
1679         if (!(status & CM_INTR))
1680                 return IRQ_NONE;
1681
1682         /* acknowledge interrupt */
1683         spin_lock(&cm->reg_lock);
1684         if (status & CM_CHINT0)
1685                 mask |= CM_CH0_INT_EN;
1686         if (status & CM_CHINT1)
1687                 mask |= CM_CH1_INT_EN;
1688         snd_cmipci_clear_bit(cm, CM_REG_INT_HLDCLR, mask);
1689         snd_cmipci_set_bit(cm, CM_REG_INT_HLDCLR, mask);
1690         spin_unlock(&cm->reg_lock);
1691
1692         if (cm->rmidi && (status & CM_UARTINT))
1693                 snd_mpu401_uart_interrupt(irq, cm->rmidi->private_data, regs);
1694
1695         if (cm->pcm) {
1696                 if ((status & CM_CHINT0) && cm->channel[0].running)
1697                         snd_pcm_period_elapsed(cm->channel[0].substream);
1698                 if ((status & CM_CHINT1) && cm->channel[1].running)
1699                         snd_pcm_period_elapsed(cm->channel[1].substream);
1700         }
1701         return IRQ_HANDLED;
1702 }
1703
1704 /*
1705  * h/w infos
1706  */
1707
1708 /* playback on channel A */
1709 static snd_pcm_hardware_t snd_cmipci_playback =
1710 {
1711         .info =                 (SNDRV_PCM_INFO_MMAP | SNDRV_PCM_INFO_INTERLEAVED |
1712                                  SNDRV_PCM_INFO_BLOCK_TRANSFER | SNDRV_PCM_INFO_PAUSE |
1713                                  SNDRV_PCM_INFO_MMAP_VALID),
1714         .formats =              SNDRV_PCM_FMTBIT_U8 | SNDRV_PCM_FMTBIT_S16_LE,
1715         .rates =                SNDRV_PCM_RATE_5512 | SNDRV_PCM_RATE_8000_48000,
1716         .rate_min =             5512,
1717         .rate_max =             48000,
1718         .channels_min =         1,
1719         .channels_max =         2,
1720         .buffer_bytes_max =     (128*1024),
1721         .period_bytes_min =     64,
1722         .period_bytes_max =     (128*1024),
1723         .periods_min =          2,
1724         .periods_max =          1024,
1725         .fifo_size =            0,
1726 };
1727
1728 /* capture on channel B */
1729 static snd_pcm_hardware_t snd_cmipci_capture =
1730 {
1731         .info =                 (SNDRV_PCM_INFO_MMAP | SNDRV_PCM_INFO_INTERLEAVED |
1732                                  SNDRV_PCM_INFO_BLOCK_TRANSFER | SNDRV_PCM_INFO_PAUSE |
1733                                  SNDRV_PCM_INFO_MMAP_VALID),
1734         .formats =              SNDRV_PCM_FMTBIT_U8 | SNDRV_PCM_FMTBIT_S16_LE,
1735         .rates =                SNDRV_PCM_RATE_5512 | SNDRV_PCM_RATE_8000_48000,
1736         .rate_min =             5512,
1737         .rate_max =             48000,
1738         .channels_min =         1,
1739         .channels_max =         2,
1740         .buffer_bytes_max =     (128*1024),
1741         .period_bytes_min =     64,
1742         .period_bytes_max =     (128*1024),
1743         .periods_min =          2,
1744         .periods_max =          1024,
1745         .fifo_size =            0,
1746 };
1747
1748 /* playback on channel B - stereo 16bit only? */
1749 static snd_pcm_hardware_t snd_cmipci_playback2 =
1750 {
1751         .info =                 (SNDRV_PCM_INFO_MMAP | SNDRV_PCM_INFO_INTERLEAVED |
1752                                  SNDRV_PCM_INFO_BLOCK_TRANSFER | SNDRV_PCM_INFO_PAUSE |
1753                                  SNDRV_PCM_INFO_MMAP_VALID),
1754         .formats =              SNDRV_PCM_FMTBIT_S16_LE,
1755         .rates =                SNDRV_PCM_RATE_5512 | SNDRV_PCM_RATE_8000_48000,
1756         .rate_min =             5512,
1757         .rate_max =             48000,
1758         .channels_min =         2,
1759         .channels_max =         2,
1760         .buffer_bytes_max =     (128*1024),
1761         .period_bytes_min =     64,
1762         .period_bytes_max =     (128*1024),
1763         .periods_min =          2,
1764         .periods_max =          1024,
1765         .fifo_size =            0,
1766 };
1767
1768 /* spdif playback on channel A */
1769 static snd_pcm_hardware_t snd_cmipci_playback_spdif =
1770 {
1771         .info =                 (SNDRV_PCM_INFO_INTERLEAVED |
1772                                  SNDRV_PCM_INFO_BLOCK_TRANSFER | SNDRV_PCM_INFO_PAUSE),
1773         .formats =              SNDRV_PCM_FMTBIT_S16_LE,
1774         .rates =                SNDRV_PCM_RATE_44100 | SNDRV_PCM_RATE_48000,
1775         .rate_min =             44100,
1776         .rate_max =             48000,
1777         .channels_min =         2,
1778         .channels_max =         2,
1779         .buffer_bytes_max =     (128*1024),
1780         .period_bytes_min =     64,
1781         .period_bytes_max =     (128*1024),
1782         .periods_min =          2,
1783         .periods_max =          1024,
1784         .fifo_size =            0,
1785 };
1786
1787 /* spdif capture on channel B */
1788 static snd_pcm_hardware_t snd_cmipci_capture_spdif =
1789 {
1790         .info =                 (SNDRV_PCM_INFO_MMAP | SNDRV_PCM_INFO_INTERLEAVED |
1791                                  SNDRV_PCM_INFO_BLOCK_TRANSFER | SNDRV_PCM_INFO_PAUSE |
1792                                  SNDRV_PCM_INFO_MMAP_VALID),
1793         .formats =              SNDRV_PCM_FMTBIT_S16_LE,
1794         .rates =                SNDRV_PCM_RATE_44100 | SNDRV_PCM_RATE_48000,
1795         .rate_min =             44100,
1796         .rate_max =             48000,
1797         .channels_min =         2,
1798         .channels_max =         2,
1799         .buffer_bytes_max =     (128*1024),
1800         .period_bytes_min =     64,
1801         .period_bytes_max =     (128*1024),
1802         .periods_min =          2,
1803         .periods_max =          1024,
1804         .fifo_size =            0,
1805 };
1806
1807 /*
1808  * check device open/close
1809  */
1810 static int open_device_check(cmipci_t *cm, int mode, snd_pcm_substream_t *subs)
1811 {
1812         unsigned long flags;
1813         int ch = mode & CM_OPEN_CH_MASK;
1814
1815         /* FIXME: a file should wait until the device becomes free
1816          * when it's opened on blocking mode.  however, since the current
1817          * pcm framework doesn't pass file pointer before actually opened,
1818          * we can't know whether blocking mode or not in open callback..
1819          */
1820         down(&cm->open_mutex);
1821         if (cm->opened[ch]) {
1822                 up(&cm->open_mutex);
1823                 return -EBUSY;
1824         }
1825         cm->opened[ch] = mode;
1826         cm->channel[ch].substream = subs;
1827         if (! (mode & CM_OPEN_DAC)) {
1828                 /* disable dual DAC mode */
1829                 cm->channel[ch].is_dac = 0;
1830                 spin_lock_irqsave(&cm->reg_lock, flags);
1831                 snd_cmipci_clear_bit(cm, CM_REG_MISC_CTRL, CM_ENDBDAC);
1832                 spin_unlock_irqrestore(&cm->reg_lock, flags);
1833         }
1834         up(&cm->open_mutex);
1835         return 0;
1836 }
1837
1838 static void close_device_check(cmipci_t *cm, int mode)
1839 {
1840         unsigned long flags;
1841         int ch = mode & CM_OPEN_CH_MASK;
1842
1843         down(&cm->open_mutex);
1844         if (cm->opened[ch] == mode) {
1845                 if (cm->channel[ch].substream) {
1846                         snd_cmipci_ch_reset(cm, ch);
1847                         cm->channel[ch].running = 0;
1848                         cm->channel[ch].substream = NULL;
1849                 }
1850                 cm->opened[ch] = 0;
1851                 if (! cm->channel[ch].is_dac) {
1852                         /* enable dual DAC mode again */
1853                         cm->channel[ch].is_dac = 1;
1854                         spin_lock_irqsave(&cm->reg_lock, flags);
1855                         snd_cmipci_set_bit(cm, CM_REG_MISC_CTRL, CM_ENDBDAC);
1856                         spin_unlock_irqrestore(&cm->reg_lock, flags);
1857                 }
1858         }
1859         up(&cm->open_mutex);
1860 }
1861
1862 /*
1863  */
1864
1865 static int snd_cmipci_playback_open(snd_pcm_substream_t *substream)
1866 {
1867         cmipci_t *cm = snd_pcm_substream_chip(substream);
1868         snd_pcm_runtime_t *runtime = substream->runtime;
1869         int err;
1870
1871         if ((err = open_device_check(cm, CM_OPEN_PLAYBACK, substream)) < 0)
1872                 return err;
1873         runtime->hw = snd_cmipci_playback;
1874         snd_pcm_hw_constraint_minmax(runtime, SNDRV_PCM_HW_PARAM_BUFFER_SIZE, 0, 0x10000);
1875         cm->dig_pcm_status = cm->dig_status;
1876         return 0;
1877 }
1878
1879 static int snd_cmipci_capture_open(snd_pcm_substream_t *substream)
1880 {
1881         cmipci_t *cm = snd_pcm_substream_chip(substream);
1882         snd_pcm_runtime_t *runtime = substream->runtime;
1883         int err;
1884
1885         if ((err = open_device_check(cm, CM_OPEN_CAPTURE, substream)) < 0)
1886                 return err;
1887         runtime->hw = snd_cmipci_capture;
1888         snd_pcm_hw_constraint_minmax(runtime, SNDRV_PCM_HW_PARAM_BUFFER_SIZE, 0, 0x10000);
1889         return 0;
1890 }
1891
1892 static int snd_cmipci_playback2_open(snd_pcm_substream_t *substream)
1893 {
1894         cmipci_t *cm = snd_pcm_substream_chip(substream);
1895         snd_pcm_runtime_t *runtime = substream->runtime;
1896         int err;
1897
1898         if ((err = open_device_check(cm, CM_OPEN_PLAYBACK2, substream)) < 0) /* use channel B */
1899                 return err;
1900         runtime->hw = snd_cmipci_playback2;
1901         down(&cm->open_mutex);
1902         if (! cm->opened[CM_CH_PLAY]) {
1903                 if (cm->can_multi_ch) {
1904                         runtime->hw.channels_max = cm->max_channels;
1905                         if (cm->max_channels == 4)
1906                                 snd_pcm_hw_constraint_list(runtime, 0, SNDRV_PCM_HW_PARAM_CHANNELS, &hw_constraints_channels_4);
1907                         else
1908                                 snd_pcm_hw_constraint_list(runtime, 0, SNDRV_PCM_HW_PARAM_CHANNELS, &hw_constraints_channels_6);
1909                 }
1910                 snd_pcm_hw_constraint_minmax(runtime, SNDRV_PCM_HW_PARAM_BUFFER_SIZE, 0, 0x10000);
1911         }
1912         up(&cm->open_mutex);
1913         return 0;
1914 }
1915
1916 static int snd_cmipci_playback_spdif_open(snd_pcm_substream_t *substream)
1917 {
1918         cmipci_t *cm = snd_pcm_substream_chip(substream);
1919         snd_pcm_runtime_t *runtime = substream->runtime;
1920         int err;
1921
1922         if ((err = open_device_check(cm, CM_OPEN_SPDIF_PLAYBACK, substream)) < 0) /* use channel A */
1923                 return err;
1924         runtime->hw = snd_cmipci_playback_spdif;
1925 #ifdef DO_SOFT_AC3
1926         if (cm->can_ac3_hw)
1927 #endif
1928                 runtime->hw.info |= SNDRV_PCM_INFO_MMAP | SNDRV_PCM_INFO_MMAP_VALID;
1929         if (cm->chip_version >= 37)
1930                 runtime->hw.formats |= SNDRV_PCM_FMTBIT_S32_LE;
1931         snd_pcm_hw_constraint_minmax(runtime, SNDRV_PCM_HW_PARAM_BUFFER_SIZE, 0, 0x40000);
1932         cm->dig_pcm_status = cm->dig_status;
1933         return 0;
1934 }
1935
1936 static int snd_cmipci_capture_spdif_open(snd_pcm_substream_t * substream)
1937 {
1938         cmipci_t *cm = snd_pcm_substream_chip(substream);
1939         snd_pcm_runtime_t *runtime = substream->runtime;
1940         int err;
1941
1942         if ((err = open_device_check(cm, CM_OPEN_SPDIF_CAPTURE, substream)) < 0) /* use channel B */
1943                 return err;
1944         runtime->hw = snd_cmipci_capture_spdif;
1945         snd_pcm_hw_constraint_minmax(runtime, SNDRV_PCM_HW_PARAM_BUFFER_SIZE, 0, 0x40000);
1946         return 0;
1947 }
1948
1949
1950 /*
1951  */
1952
1953 static int snd_cmipci_playback_close(snd_pcm_substream_t * substream)
1954 {
1955         cmipci_t *cm = snd_pcm_substream_chip(substream);
1956         close_device_check(cm, CM_OPEN_PLAYBACK);
1957         return 0;
1958 }
1959
1960 static int snd_cmipci_capture_close(snd_pcm_substream_t * substream)
1961 {
1962         cmipci_t *cm = snd_pcm_substream_chip(substream);
1963         close_device_check(cm, CM_OPEN_CAPTURE);
1964         return 0;
1965 }
1966
1967 static int snd_cmipci_playback2_close(snd_pcm_substream_t * substream)
1968 {
1969         cmipci_t *cm = snd_pcm_substream_chip(substream);
1970         close_device_check(cm, CM_OPEN_PLAYBACK2);
1971         close_device_check(cm, CM_OPEN_PLAYBACK_MULTI);
1972         return 0;
1973 }
1974
1975 static int snd_cmipci_playback_spdif_close(snd_pcm_substream_t * substream)
1976 {
1977         cmipci_t *cm = snd_pcm_substream_chip(substream);
1978         close_device_check(cm, CM_OPEN_SPDIF_PLAYBACK);
1979         return 0;
1980 }
1981
1982 static int snd_cmipci_capture_spdif_close(snd_pcm_substream_t * substream)
1983 {
1984         cmipci_t *cm = snd_pcm_substream_chip(substream);
1985         close_device_check(cm, CM_OPEN_SPDIF_CAPTURE);
1986         return 0;
1987 }
1988
1989
1990 /*
1991  */
1992
1993 static snd_pcm_ops_t snd_cmipci_playback_ops = {
1994         .open =         snd_cmipci_playback_open,
1995         .close =        snd_cmipci_playback_close,
1996         .ioctl =        snd_pcm_lib_ioctl,
1997         .hw_params =    snd_cmipci_hw_params,
1998         .hw_free =      snd_cmipci_playback_hw_free,
1999         .prepare =      snd_cmipci_playback_prepare,
2000         .trigger =      snd_cmipci_playback_trigger,
2001         .pointer =      snd_cmipci_playback_pointer,
2002 };
2003
2004 static snd_pcm_ops_t snd_cmipci_capture_ops = {
2005         .open =         snd_cmipci_capture_open,
2006         .close =        snd_cmipci_capture_close,
2007         .ioctl =        snd_pcm_lib_ioctl,
2008         .hw_params =    snd_cmipci_hw_params,
2009         .hw_free =      snd_cmipci_hw_free,
2010         .prepare =      snd_cmipci_capture_prepare,
2011         .trigger =      snd_cmipci_capture_trigger,
2012         .pointer =      snd_cmipci_capture_pointer,
2013 };
2014
2015 static snd_pcm_ops_t snd_cmipci_playback2_ops = {
2016         .open =         snd_cmipci_playback2_open,
2017         .close =        snd_cmipci_playback2_close,
2018         .ioctl =        snd_pcm_lib_ioctl,
2019         .hw_params =    snd_cmipci_playback2_hw_params,
2020         .hw_free =      snd_cmipci_hw_free,
2021         .prepare =      snd_cmipci_capture_prepare,     /* channel B */
2022         .trigger =      snd_cmipci_capture_trigger,     /* channel B */
2023         .pointer =      snd_cmipci_capture_pointer,     /* channel B */
2024 };
2025
2026 static snd_pcm_ops_t snd_cmipci_playback_spdif_ops = {
2027         .open =         snd_cmipci_playback_spdif_open,
2028         .close =        snd_cmipci_playback_spdif_close,
2029         .ioctl =        snd_pcm_lib_ioctl,
2030         .hw_params =    snd_cmipci_hw_params,
2031         .hw_free =      snd_cmipci_playback_hw_free,
2032         .prepare =      snd_cmipci_playback_spdif_prepare,      /* set up rate */
2033         .trigger =      snd_cmipci_playback_trigger,
2034         .pointer =      snd_cmipci_playback_pointer,
2035 };
2036
2037 #ifdef DO_SOFT_AC3
2038 static snd_pcm_ops_t snd_cmipci_playback_spdif_soft_ops = {
2039         .open =         snd_cmipci_playback_spdif_open,
2040         .close =        snd_cmipci_playback_spdif_close,
2041         .ioctl =        snd_pcm_lib_ioctl,
2042         .hw_params =    snd_cmipci_hw_params,
2043         .hw_free =      snd_cmipci_playback_hw_free,
2044         .prepare =      snd_cmipci_playback_spdif_prepare,      /* set up rate */
2045         .trigger =      snd_cmipci_playback_trigger,
2046         .pointer =      snd_cmipci_playback_pointer,
2047         .copy =         snd_cmipci_ac3_copy,
2048         .silence =      snd_cmipci_ac3_silence,
2049 };
2050 #endif
2051
2052 static snd_pcm_ops_t snd_cmipci_capture_spdif_ops = {
2053         .open =         snd_cmipci_capture_spdif_open,
2054         .close =        snd_cmipci_capture_spdif_close,
2055         .ioctl =        snd_pcm_lib_ioctl,
2056         .hw_params =    snd_cmipci_hw_params,
2057         .hw_free =      snd_cmipci_capture_spdif_hw_free,
2058         .prepare =      snd_cmipci_capture_spdif_prepare,
2059         .trigger =      snd_cmipci_capture_trigger,
2060         .pointer =      snd_cmipci_capture_pointer,
2061 };
2062
2063
2064 /*
2065  */
2066
2067 static void snd_cmipci_pcm_free(snd_pcm_t *pcm)
2068 {
2069         snd_pcm_lib_preallocate_free_for_all(pcm);
2070 }
2071
2072 static int __devinit snd_cmipci_pcm_new(cmipci_t *cm, int device)
2073 {
2074         snd_pcm_t *pcm;
2075         int err;
2076
2077         err = snd_pcm_new(cm->card, cm->card->driver, device, 1, 1, &pcm);
2078         if (err < 0)
2079                 return err;
2080
2081         snd_pcm_set_ops(pcm, SNDRV_PCM_STREAM_PLAYBACK, &snd_cmipci_playback_ops);
2082         snd_pcm_set_ops(pcm, SNDRV_PCM_STREAM_CAPTURE, &snd_cmipci_capture_ops);
2083
2084         pcm->private_data = cm;
2085         pcm->private_free = snd_cmipci_pcm_free;
2086         pcm->info_flags = 0;
2087         strcpy(pcm->name, "C-Media PCI DAC/ADC");
2088         cm->pcm = pcm;
2089
2090         snd_pcm_lib_preallocate_pages_for_all(pcm, SNDRV_DMA_TYPE_DEV,
2091                                               snd_dma_pci_data(cm->pci), 64*1024, 128*1024);
2092
2093         return 0;
2094 }
2095
2096 static int __devinit snd_cmipci_pcm2_new(cmipci_t *cm, int device)
2097 {
2098         snd_pcm_t *pcm;
2099         int err;
2100
2101         err = snd_pcm_new(cm->card, cm->card->driver, device, 1, 0, &pcm);
2102         if (err < 0)
2103                 return err;
2104
2105         snd_pcm_set_ops(pcm, SNDRV_PCM_STREAM_PLAYBACK, &snd_cmipci_playback2_ops);
2106
2107         pcm->private_data = cm;
2108         pcm->private_free = snd_cmipci_pcm_free;
2109         pcm->info_flags = 0;
2110         strcpy(pcm->name, "C-Media PCI 2nd DAC");
2111         cm->pcm2 = pcm;
2112
2113         snd_pcm_lib_preallocate_pages_for_all(pcm, SNDRV_DMA_TYPE_DEV,
2114                                               snd_dma_pci_data(cm->pci), 64*1024, 128*1024);
2115
2116         return 0;
2117 }
2118
2119 static int __devinit snd_cmipci_pcm_spdif_new(cmipci_t *cm, int device)
2120 {
2121         snd_pcm_t *pcm;
2122         int err;
2123
2124         err = snd_pcm_new(cm->card, cm->card->driver, device, 1, 1, &pcm);
2125         if (err < 0)
2126                 return err;
2127
2128 #ifdef DO_SOFT_AC3
2129         if (cm->can_ac3_hw)
2130                 snd_pcm_set_ops(pcm, SNDRV_PCM_STREAM_PLAYBACK, &snd_cmipci_playback_spdif_ops);
2131         else
2132                 snd_pcm_set_ops(pcm, SNDRV_PCM_STREAM_PLAYBACK, &snd_cmipci_playback_spdif_soft_ops);
2133 #else
2134         snd_pcm_set_ops(pcm, SNDRV_PCM_STREAM_PLAYBACK, &snd_cmipci_playback_spdif_ops);
2135 #endif
2136         snd_pcm_set_ops(pcm, SNDRV_PCM_STREAM_CAPTURE, &snd_cmipci_capture_spdif_ops);
2137
2138         pcm->private_data = cm;
2139         pcm->private_free = snd_cmipci_pcm_free;
2140         pcm->info_flags = 0;
2141         strcpy(pcm->name, "C-Media PCI IEC958");
2142         cm->pcm_spdif = pcm;
2143
2144         snd_pcm_lib_preallocate_pages_for_all(pcm, SNDRV_DMA_TYPE_DEV,
2145                                               snd_dma_pci_data(cm->pci), 64*1024, 128*1024);
2146
2147         return 0;
2148 }
2149
2150 /*
2151  * mixer interface:
2152  * - CM8338/8738 has a compatible mixer interface with SB16, but
2153  *   lack of some elements like tone control, i/o gain and AGC.
2154  * - Access to native registers:
2155  *   - A 3D switch
2156  *   - Output mute switches
2157  */
2158
2159 static void snd_cmipci_mixer_write(cmipci_t *s, unsigned char idx, unsigned char data)
2160 {
2161         outb(idx, s->iobase + CM_REG_SB16_ADDR);
2162         outb(data, s->iobase + CM_REG_SB16_DATA);
2163 }
2164
2165 static unsigned char snd_cmipci_mixer_read(cmipci_t *s, unsigned char idx)
2166 {
2167         unsigned char v;
2168
2169         outb(idx, s->iobase + CM_REG_SB16_ADDR);
2170         v = inb(s->iobase + CM_REG_SB16_DATA);
2171         return v;
2172 }
2173
2174 /*
2175  * general mixer element
2176  */
2177 typedef struct cmipci_sb_reg {
2178         unsigned int left_reg, right_reg;
2179         unsigned int left_shift, right_shift;
2180         unsigned int mask;
2181         unsigned int invert: 1;
2182         unsigned int stereo: 1;
2183 } cmipci_sb_reg_t;
2184
2185 #define COMPOSE_SB_REG(lreg,rreg,lshift,rshift,mask,invert,stereo) \
2186  ((lreg) | ((rreg) << 8) | (lshift << 16) | (rshift << 19) | (mask << 24) | (invert << 22) | (stereo << 23))
2187
2188 #define CMIPCI_DOUBLE(xname, left_reg, right_reg, left_shift, right_shift, mask, invert, stereo) \
2189 { .iface = SNDRV_CTL_ELEM_IFACE_MIXER, .name = xname, \
2190   .info = snd_cmipci_info_volume, \
2191   .get = snd_cmipci_get_volume, .put = snd_cmipci_put_volume, \
2192   .private_value = COMPOSE_SB_REG(left_reg, right_reg, left_shift, right_shift, mask, invert, stereo), \
2193 }
2194
2195 #define CMIPCI_SB_VOL_STEREO(xname,reg,shift,mask) CMIPCI_DOUBLE(xname, reg, reg+1, shift, shift, mask, 0, 1)
2196 #define CMIPCI_SB_VOL_MONO(xname,reg,shift,mask) CMIPCI_DOUBLE(xname, reg, reg, shift, shift, mask, 0, 0)
2197 #define CMIPCI_SB_SW_STEREO(xname,lshift,rshift) CMIPCI_DOUBLE(xname, SB_DSP4_OUTPUT_SW, SB_DSP4_OUTPUT_SW, lshift, rshift, 1, 0, 1)
2198 #define CMIPCI_SB_SW_MONO(xname,shift) CMIPCI_DOUBLE(xname, SB_DSP4_OUTPUT_SW, SB_DSP4_OUTPUT_SW, shift, shift, 1, 0, 0)
2199
2200 static void cmipci_sb_reg_decode(cmipci_sb_reg_t *r, unsigned long val)
2201 {
2202         r->left_reg = val & 0xff;
2203         r->right_reg = (val >> 8) & 0xff;
2204         r->left_shift = (val >> 16) & 0x07;
2205         r->right_shift = (val >> 19) & 0x07;
2206         r->invert = (val >> 22) & 1;
2207         r->stereo = (val >> 23) & 1;
2208         r->mask = (val >> 24) & 0xff;
2209 }
2210
2211 static int snd_cmipci_info_volume(snd_kcontrol_t * kcontrol, snd_ctl_elem_info_t * uinfo)
2212 {
2213         cmipci_sb_reg_t reg;
2214
2215         cmipci_sb_reg_decode(&reg, kcontrol->private_value);
2216         uinfo->type = reg.mask == 1 ? SNDRV_CTL_ELEM_TYPE_BOOLEAN : SNDRV_CTL_ELEM_TYPE_INTEGER;
2217         uinfo->count = reg.stereo + 1;
2218         uinfo->value.integer.min = 0;
2219         uinfo->value.integer.max = reg.mask;
2220         return 0;
2221 }
2222  
2223 static int snd_cmipci_get_volume(snd_kcontrol_t * kcontrol, snd_ctl_elem_value_t * ucontrol)
2224 {
2225         cmipci_t *cm = snd_kcontrol_chip(kcontrol);
2226         unsigned long flags;
2227         cmipci_sb_reg_t reg;
2228         int val;
2229
2230         cmipci_sb_reg_decode(&reg, kcontrol->private_value);
2231         spin_lock_irqsave(&cm->reg_lock, flags);
2232         val = (snd_cmipci_mixer_read(cm, reg.left_reg) >> reg.left_shift) & reg.mask;
2233         if (reg.invert)
2234                 val = reg.mask - val;
2235         ucontrol->value.integer.value[0] = val;
2236         if (reg.stereo) {
2237                 val = (snd_cmipci_mixer_read(cm, reg.right_reg) >> reg.right_shift) & reg.mask;
2238                 if (reg.invert)
2239                         val = reg.mask - val;
2240                  ucontrol->value.integer.value[1] = val;
2241         }
2242         spin_unlock_irqrestore(&cm->reg_lock, flags);
2243         return 0;
2244 }
2245
2246 static int snd_cmipci_put_volume(snd_kcontrol_t * kcontrol, snd_ctl_elem_value_t * ucontrol)
2247 {
2248         cmipci_t *cm = snd_kcontrol_chip(kcontrol);
2249         unsigned long flags;
2250         cmipci_sb_reg_t reg;
2251         int change;
2252         int left, right, oleft, oright;
2253
2254         cmipci_sb_reg_decode(&reg, kcontrol->private_value);
2255         left = ucontrol->value.integer.value[0] & reg.mask;
2256         if (reg.invert)
2257                 left = reg.mask - left;
2258         left <<= reg.left_shift;
2259         if (reg.stereo) {
2260                 right = ucontrol->value.integer.value[1] & reg.mask;
2261                 if (reg.invert)
2262                         right = reg.mask - right;
2263                 right <<= reg.right_shift;
2264         } else
2265                 right = 0;
2266         spin_lock_irqsave(&cm->reg_lock, flags);
2267         oleft = snd_cmipci_mixer_read(cm, reg.left_reg);
2268         left |= oleft & ~(reg.mask << reg.left_shift);
2269         change = left != oleft;
2270         if (reg.stereo) {
2271                 if (reg.left_reg != reg.right_reg) {
2272                         snd_cmipci_mixer_write(cm, reg.left_reg, left);
2273                         oright = snd_cmipci_mixer_read(cm, reg.right_reg);
2274                 } else
2275                         oright = left;
2276                 right |= oright & ~(reg.mask << reg.right_shift);
2277                 change |= right != oright;
2278                 snd_cmipci_mixer_write(cm, reg.right_reg, right);
2279         } else
2280                 snd_cmipci_mixer_write(cm, reg.left_reg, left);
2281         spin_unlock_irqrestore(&cm->reg_lock, flags);
2282         return change;
2283 }
2284
2285 /*
2286  * input route (left,right) -> (left,right)
2287  */
2288 #define CMIPCI_SB_INPUT_SW(xname, left_shift, right_shift) \
2289 { .iface = SNDRV_CTL_ELEM_IFACE_MIXER, .name = xname, \
2290   .info = snd_cmipci_info_input_sw, \
2291   .get = snd_cmipci_get_input_sw, .put = snd_cmipci_put_input_sw, \
2292   .private_value = COMPOSE_SB_REG(SB_DSP4_INPUT_LEFT, SB_DSP4_INPUT_RIGHT, left_shift, right_shift, 1, 0, 1), \
2293 }
2294
2295 static int snd_cmipci_info_input_sw(snd_kcontrol_t * kcontrol, snd_ctl_elem_info_t * uinfo)
2296 {
2297         uinfo->type = SNDRV_CTL_ELEM_TYPE_BOOLEAN;
2298         uinfo->count = 4;
2299         uinfo->value.integer.min = 0;
2300         uinfo->value.integer.max = 1;
2301         return 0;
2302 }
2303  
2304 static int snd_cmipci_get_input_sw(snd_kcontrol_t * kcontrol, snd_ctl_elem_value_t * ucontrol)
2305 {
2306         cmipci_t *cm = snd_kcontrol_chip(kcontrol);
2307         unsigned long flags;
2308         cmipci_sb_reg_t reg;
2309         int val1, val2;
2310
2311         cmipci_sb_reg_decode(&reg, kcontrol->private_value);
2312         spin_lock_irqsave(&cm->reg_lock, flags);
2313         val1 = snd_cmipci_mixer_read(cm, reg.left_reg);
2314         val2 = snd_cmipci_mixer_read(cm, reg.right_reg);
2315         spin_unlock_irqrestore(&cm->reg_lock, flags);
2316         ucontrol->value.integer.value[0] = (val1 >> reg.left_shift) & 1;
2317         ucontrol->value.integer.value[1] = (val2 >> reg.left_shift) & 1;
2318         ucontrol->value.integer.value[2] = (val1 >> reg.right_shift) & 1;
2319         ucontrol->value.integer.value[3] = (val2 >> reg.right_shift) & 1;
2320         return 0;
2321 }
2322
2323 static int snd_cmipci_put_input_sw(snd_kcontrol_t * kcontrol, snd_ctl_elem_value_t * ucontrol)
2324 {
2325         cmipci_t *cm = snd_kcontrol_chip(kcontrol);
2326         unsigned long flags;
2327         cmipci_sb_reg_t reg;
2328         int change;
2329         int val1, val2, oval1, oval2;
2330
2331         cmipci_sb_reg_decode(&reg, kcontrol->private_value);
2332         spin_lock_irqsave(&cm->reg_lock, flags);
2333         oval1 = snd_cmipci_mixer_read(cm, reg.left_reg);
2334         oval2 = snd_cmipci_mixer_read(cm, reg.right_reg);
2335         val1 = oval1 & ~((1 << reg.left_shift) | (1 << reg.right_shift));
2336         val2 = oval2 & ~((1 << reg.left_shift) | (1 << reg.right_shift));
2337         val1 |= (ucontrol->value.integer.value[0] & 1) << reg.left_shift;
2338         val2 |= (ucontrol->value.integer.value[1] & 1) << reg.left_shift;
2339         val1 |= (ucontrol->value.integer.value[2] & 1) << reg.right_shift;
2340         val2 |= (ucontrol->value.integer.value[3] & 1) << reg.right_shift;
2341         change = val1 != oval1 || val2 != oval2;
2342         snd_cmipci_mixer_write(cm, reg.left_reg, val1);
2343         snd_cmipci_mixer_write(cm, reg.right_reg, val2);
2344         spin_unlock_irqrestore(&cm->reg_lock, flags);
2345         return change;
2346 }
2347
2348 /*
2349  * native mixer switches/volumes
2350  */
2351
2352 #define CMIPCI_MIXER_SW_STEREO(xname, reg, lshift, rshift, invert) \
2353 { .iface = SNDRV_CTL_ELEM_IFACE_MIXER, .name = xname, \
2354   .info = snd_cmipci_info_native_mixer, \
2355   .get = snd_cmipci_get_native_mixer, .put = snd_cmipci_put_native_mixer, \
2356   .private_value = COMPOSE_SB_REG(reg, reg, lshift, rshift, 1, invert, 1), \
2357 }
2358
2359 #define CMIPCI_MIXER_SW_MONO(xname, reg, shift, invert) \
2360 { .iface = SNDRV_CTL_ELEM_IFACE_MIXER, .name = xname, \
2361   .info = snd_cmipci_info_native_mixer, \
2362   .get = snd_cmipci_get_native_mixer, .put = snd_cmipci_put_native_mixer, \
2363   .private_value = COMPOSE_SB_REG(reg, reg, shift, shift, 1, invert, 0), \
2364 }
2365
2366 #define CMIPCI_MIXER_VOL_STEREO(xname, reg, lshift, rshift, mask) \
2367 { .iface = SNDRV_CTL_ELEM_IFACE_MIXER, .name = xname, \
2368   .info = snd_cmipci_info_native_mixer, \
2369   .get = snd_cmipci_get_native_mixer, .put = snd_cmipci_put_native_mixer, \
2370   .private_value = COMPOSE_SB_REG(reg, reg, lshift, rshift, mask, 0, 1), \
2371 }
2372
2373 #define CMIPCI_MIXER_VOL_MONO(xname, reg, shift, mask) \
2374 { .iface = SNDRV_CTL_ELEM_IFACE_MIXER, .name = xname, \
2375   .info = snd_cmipci_info_native_mixer, \
2376   .get = snd_cmipci_get_native_mixer, .put = snd_cmipci_put_native_mixer, \
2377   .private_value = COMPOSE_SB_REG(reg, reg, shift, shift, mask, 0, 0), \
2378 }
2379
2380 static int snd_cmipci_info_native_mixer(snd_kcontrol_t *kcontrol, snd_ctl_elem_info_t *uinfo)
2381 {
2382         cmipci_sb_reg_t reg;
2383
2384         cmipci_sb_reg_decode(&reg, kcontrol->private_value);
2385         uinfo->type = reg.mask == 1 ? SNDRV_CTL_ELEM_TYPE_BOOLEAN : SNDRV_CTL_ELEM_TYPE_INTEGER;
2386         uinfo->count = reg.stereo + 1;
2387         uinfo->value.integer.min = 0;
2388         uinfo->value.integer.max = reg.mask;
2389         return 0;
2390
2391 }
2392
2393 static int snd_cmipci_get_native_mixer(snd_kcontrol_t * kcontrol, snd_ctl_elem_value_t * ucontrol)
2394 {
2395         cmipci_t *cm = snd_kcontrol_chip(kcontrol);
2396         cmipci_sb_reg_t reg;
2397         unsigned long flags;
2398         unsigned char oreg, val;
2399
2400         cmipci_sb_reg_decode(&reg, kcontrol->private_value);
2401         spin_lock_irqsave(&cm->reg_lock, flags);
2402         oreg = inb(cm->iobase + reg.left_reg);
2403         val = (oreg >> reg.left_shift) & reg.mask;
2404         if (reg.invert)
2405                 val = reg.mask - val;
2406         ucontrol->value.integer.value[0] = val;
2407         if (reg.stereo) {
2408                 val = (oreg >> reg.right_shift) & reg.mask;
2409                 if (reg.invert)
2410                         val = reg.mask - val;
2411                 ucontrol->value.integer.value[1] = val;
2412         }
2413         spin_unlock_irqrestore(&cm->reg_lock, flags);
2414         return 0;
2415 }
2416
2417 static int snd_cmipci_put_native_mixer(snd_kcontrol_t * kcontrol, snd_ctl_elem_value_t * ucontrol)
2418 {
2419         cmipci_t *cm = snd_kcontrol_chip(kcontrol);
2420         cmipci_sb_reg_t reg;
2421         unsigned long flags;
2422         unsigned char oreg, nreg, val;
2423
2424         cmipci_sb_reg_decode(&reg, kcontrol->private_value);
2425         spin_lock_irqsave(&cm->reg_lock, flags);
2426         oreg = inb(cm->iobase + reg.left_reg);
2427         val = ucontrol->value.integer.value[0] & reg.mask;
2428         if (reg.invert)
2429                 val = reg.mask - val;
2430         nreg = oreg & ~(reg.mask << reg.left_shift);
2431         nreg |= (val << reg.left_shift);
2432         if (reg.stereo) {
2433                 val = ucontrol->value.integer.value[1] & reg.mask;
2434                 if (reg.invert)
2435                         val = reg.mask - val;
2436                 nreg &= ~(reg.mask << reg.right_shift);
2437                 nreg |= (val << reg.right_shift);
2438         }
2439         outb(nreg, cm->iobase + reg.left_reg);
2440         spin_unlock_irqrestore(&cm->reg_lock, flags);
2441         return (nreg != oreg);
2442 }
2443
2444 /*
2445  * special case - check mixer sensitivity
2446  */
2447 static int snd_cmipci_get_native_mixer_sensitive(snd_kcontrol_t *kcontrol, snd_ctl_elem_value_t *ucontrol)
2448 {
2449         //cmipci_t *cm = snd_kcontrol_chip(kcontrol);
2450         return snd_cmipci_get_native_mixer(kcontrol, ucontrol);
2451 }
2452
2453 static int snd_cmipci_put_native_mixer_sensitive(snd_kcontrol_t *kcontrol, snd_ctl_elem_value_t *ucontrol)
2454 {
2455         cmipci_t *cm = snd_kcontrol_chip(kcontrol);
2456         if (cm->mixer_insensitive) {
2457                 /* ignored */
2458                 return 0;
2459         }
2460         return snd_cmipci_put_native_mixer(kcontrol, ucontrol);
2461 }
2462
2463
2464 #define num_controls(ary) (sizeof(ary) / sizeof(snd_kcontrol_new_t))
2465
2466 static snd_kcontrol_new_t snd_cmipci_mixers[] __devinitdata = {
2467         CMIPCI_SB_VOL_STEREO("Master Playback Volume", SB_DSP4_MASTER_DEV, 3, 31),
2468         CMIPCI_MIXER_SW_MONO("3D Control - Switch", CM_REG_MIXER1, CM_X3DEN_SHIFT, 0),
2469         CMIPCI_SB_VOL_STEREO("PCM Playback Volume", SB_DSP4_PCM_DEV, 3, 31),
2470         //CMIPCI_MIXER_SW_MONO("PCM Playback Switch", CM_REG_MIXER1, CM_WSMUTE_SHIFT, 1),
2471         { /* switch with sensitivity */
2472                 .iface = SNDRV_CTL_ELEM_IFACE_MIXER,
2473                 .name = "PCM Playback Switch",
2474                 .info = snd_cmipci_info_native_mixer,
2475                 .get = snd_cmipci_get_native_mixer_sensitive,
2476                 .put = snd_cmipci_put_native_mixer_sensitive,
2477                 .private_value = COMPOSE_SB_REG(CM_REG_MIXER1, CM_REG_MIXER1, CM_WSMUTE_SHIFT, CM_WSMUTE_SHIFT, 1, 1, 0),
2478         },
2479         CMIPCI_MIXER_SW_STEREO("PCM Capture Switch", CM_REG_MIXER1, CM_WAVEINL_SHIFT, CM_WAVEINR_SHIFT, 0),
2480         CMIPCI_SB_VOL_STEREO("Synth Playback Volume", SB_DSP4_SYNTH_DEV, 3, 31),
2481         CMIPCI_MIXER_SW_MONO("Synth Playback Switch", CM_REG_MIXER1, CM_FMMUTE_SHIFT, 1),
2482         CMIPCI_SB_INPUT_SW("Synth Capture Route", 6, 5),
2483         CMIPCI_SB_VOL_STEREO("CD Playback Volume", SB_DSP4_CD_DEV, 3, 31),
2484         CMIPCI_SB_SW_STEREO("CD Playback Switch", 2, 1),
2485         CMIPCI_SB_INPUT_SW("CD Capture Route", 2, 1),
2486         CMIPCI_SB_VOL_STEREO("Line Playback Volume", SB_DSP4_LINE_DEV, 3, 31),
2487         CMIPCI_SB_SW_STEREO("Line Playback Switch", 4, 3),
2488         CMIPCI_SB_INPUT_SW("Line Capture Route", 4, 3),
2489         CMIPCI_SB_VOL_MONO("Mic Playback Volume", SB_DSP4_MIC_DEV, 3, 31),
2490         CMIPCI_SB_SW_MONO("Mic Playback Switch", 0),
2491         CMIPCI_DOUBLE("Mic Capture Switch", SB_DSP4_INPUT_LEFT, SB_DSP4_INPUT_RIGHT, 0, 0, 1, 0, 0),
2492         CMIPCI_SB_VOL_MONO("PC Speaker Playback Volume", SB_DSP4_SPEAKER_DEV, 6, 3),
2493         CMIPCI_MIXER_VOL_STEREO("Aux Playback Volume", CM_REG_AUX_VOL, 4, 0, 15),
2494         CMIPCI_MIXER_SW_STEREO("Aux Playback Switch", CM_REG_MIXER2, CM_VAUXLM_SHIFT, CM_VAUXRM_SHIFT, 0),
2495         CMIPCI_MIXER_SW_STEREO("Aux Capture Switch", CM_REG_MIXER2, CM_RAUXLEN_SHIFT, CM_RAUXREN_SHIFT, 0),
2496         CMIPCI_MIXER_SW_MONO("Mic Boost", CM_REG_MIXER2, CM_MICGAINZ_SHIFT, 1),
2497         CMIPCI_MIXER_VOL_MONO("Mic Capture Volume", CM_REG_MIXER2, CM_VADMIC_SHIFT, 7),
2498 };
2499
2500 /*
2501  * other switches
2502  */
2503
2504 typedef struct snd_cmipci_switch_args {
2505         int reg;                /* register index */
2506         unsigned int mask;      /* mask bits */
2507         unsigned int mask_on;   /* mask bits to turn on */
2508         int is_byte: 1;         /* byte access? */
2509         int ac3_sensitive: 1;   /* access forbidden during non-audio operation? */
2510 } snd_cmipci_switch_args_t;
2511
2512 static int snd_cmipci_uswitch_info(snd_kcontrol_t *kcontrol, snd_ctl_elem_info_t *uinfo)
2513 {
2514         uinfo->type = SNDRV_CTL_ELEM_TYPE_BOOLEAN;
2515         uinfo->count = 1;
2516         uinfo->value.integer.min = 0;
2517         uinfo->value.integer.max = 1;
2518         return 0;
2519 }
2520
2521 static int _snd_cmipci_uswitch_get(snd_kcontrol_t *kcontrol, snd_ctl_elem_value_t *ucontrol, snd_cmipci_switch_args_t *args)
2522 {
2523         unsigned long flags;
2524         unsigned int val;
2525         cmipci_t *cm = snd_kcontrol_chip(kcontrol);
2526
2527         spin_lock_irqsave(&cm->reg_lock, flags);
2528         if (args->ac3_sensitive && cm->mixer_insensitive) {
2529                 ucontrol->value.integer.value[0] = 0;
2530                 spin_unlock_irqrestore(&cm->reg_lock, flags);
2531                 return 0;
2532         }
2533         if (args->is_byte)
2534                 val = inb(cm->iobase + args->reg);
2535         else
2536                 val = snd_cmipci_read(cm, args->reg);
2537         ucontrol->value.integer.value[0] = ((val & args->mask) == args->mask_on) ? 1 : 0;
2538         spin_unlock_irqrestore(&cm->reg_lock, flags);
2539         return 0;
2540 }
2541
2542 static int snd_cmipci_uswitch_get(snd_kcontrol_t *kcontrol, snd_ctl_elem_value_t *ucontrol)
2543 {
2544         snd_cmipci_switch_args_t *args = (snd_cmipci_switch_args_t*)kcontrol->private_value;
2545         snd_assert(args != NULL, return -EINVAL);
2546         return _snd_cmipci_uswitch_get(kcontrol, ucontrol, args);
2547 }
2548
2549 static int _snd_cmipci_uswitch_put(snd_kcontrol_t *kcontrol, snd_ctl_elem_value_t *ucontrol, snd_cmipci_switch_args_t *args)
2550 {
2551         unsigned long flags;
2552         unsigned int val;
2553         int change;
2554         cmipci_t *cm = snd_kcontrol_chip(kcontrol);
2555
2556         spin_lock_irqsave(&cm->reg_lock, flags);
2557         if (args->ac3_sensitive && cm->mixer_insensitive) {
2558                 /* ignored */
2559                 spin_unlock_irqrestore(&cm->reg_lock, flags);
2560                 return 0;
2561         }
2562         if (args->is_byte)
2563                 val = inb(cm->iobase + args->reg);
2564         else
2565                 val = snd_cmipci_read(cm, args->reg);
2566         change = (val & args->mask) != (ucontrol->value.integer.value[0] ? args->mask : 0);
2567         if (change) {
2568                 val &= ~args->mask;
2569                 if (ucontrol->value.integer.value[0])
2570                         val |= args->mask_on;
2571                 else
2572                         val |= (args->mask & ~args->mask_on);
2573                 if (args->is_byte)
2574                         outb((unsigned char)val, cm->iobase + args->reg);
2575                 else
2576                         snd_cmipci_write(cm, args->reg, val);
2577         }
2578         spin_unlock_irqrestore(&cm->reg_lock, flags);
2579         return change;
2580 }
2581
2582 static int snd_cmipci_uswitch_put(snd_kcontrol_t *kcontrol, snd_ctl_elem_value_t *ucontrol)
2583 {
2584         snd_cmipci_switch_args_t *args = (snd_cmipci_switch_args_t*)kcontrol->private_value;
2585         snd_assert(args != NULL, return -EINVAL);
2586         return _snd_cmipci_uswitch_put(kcontrol, ucontrol, args);
2587 }
2588
2589 #define DEFINE_SWITCH_ARG(sname, xreg, xmask, xmask_on, xis_byte, xac3) \
2590 static snd_cmipci_switch_args_t cmipci_switch_arg_##sname = { \
2591   .reg = xreg, \
2592   .mask = xmask, \
2593   .mask_on = xmask_on, \
2594   .is_byte = xis_byte, \
2595   .ac3_sensitive = xac3, \
2596 }
2597         
2598 #define DEFINE_BIT_SWITCH_ARG(sname, xreg, xmask, xis_byte, xac3) \
2599         DEFINE_SWITCH_ARG(sname, xreg, xmask, xmask, xis_byte, xac3)
2600
2601 #if 0 /* these will be controlled in pcm device */
2602 DEFINE_BIT_SWITCH_ARG(spdif_in, CM_REG_FUNCTRL1, CM_SPDF_1, 0, 0);
2603 DEFINE_BIT_SWITCH_ARG(spdif_out, CM_REG_FUNCTRL1, CM_SPDF_0, 0, 0);
2604 #endif
2605 DEFINE_BIT_SWITCH_ARG(spdif_in_sel1, CM_REG_CHFORMAT, CM_SPDIF_SELECT1, 0, 0);
2606 DEFINE_BIT_SWITCH_ARG(spdif_in_sel2, CM_REG_MISC_CTRL, CM_SPDIF_SELECT2, 0, 0);
2607 DEFINE_BIT_SWITCH_ARG(spdif_enable, CM_REG_LEGACY_CTRL, CM_ENSPDOUT, 0, 0);
2608 DEFINE_BIT_SWITCH_ARG(spdo2dac, CM_REG_FUNCTRL1, CM_SPDO2DAC, 0, 1);
2609 DEFINE_BIT_SWITCH_ARG(spdi_valid, CM_REG_MISC, CM_SPDVALID, 1, 0);
2610 DEFINE_BIT_SWITCH_ARG(spdif_copyright, CM_REG_LEGACY_CTRL, CM_SPDCOPYRHT, 0, 0);
2611 DEFINE_BIT_SWITCH_ARG(spdif_dac_out, CM_REG_LEGACY_CTRL, CM_DAC2SPDO, 0, 1);
2612 DEFINE_SWITCH_ARG(spdo_5v, CM_REG_MISC_CTRL, CM_SPDO5V, 0, 0, 0); /* inverse: 0 = 5V */
2613 // DEFINE_BIT_SWITCH_ARG(spdo_48k, CM_REG_MISC_CTRL, CM_SPDF_AC97|CM_SPDIF48K, 0, 1);
2614 DEFINE_BIT_SWITCH_ARG(spdif_loop, CM_REG_FUNCTRL1, CM_SPDFLOOP, 0, 1);
2615 DEFINE_BIT_SWITCH_ARG(spdi_monitor, CM_REG_MIXER1, CM_CDPLAY, 1, 0);
2616 /* DEFINE_BIT_SWITCH_ARG(spdi_phase, CM_REG_CHFORMAT, CM_SPDIF_INVERSE, 0, 0); */
2617 DEFINE_BIT_SWITCH_ARG(spdi_phase, CM_REG_MISC, CM_SPDIF_INVERSE, 1, 0);
2618 DEFINE_BIT_SWITCH_ARG(spdi_phase2, CM_REG_CHFORMAT, CM_SPDIF_INVERSE2, 0, 0);
2619 #if CM_CH_PLAY == 1
2620 DEFINE_SWITCH_ARG(exchange_dac, CM_REG_MISC_CTRL, CM_XCHGDAC, 0, 0, 0); /* reversed */
2621 #else
2622 DEFINE_SWITCH_ARG(exchange_dac, CM_REG_MISC_CTRL, CM_XCHGDAC, CM_XCHGDAC, 0, 0);
2623 #endif
2624 DEFINE_BIT_SWITCH_ARG(fourch, CM_REG_MISC_CTRL, CM_N4SPK3D, 0, 0);
2625 DEFINE_BIT_SWITCH_ARG(line_rear, CM_REG_MIXER1, CM_SPK4, 1, 0);
2626 DEFINE_BIT_SWITCH_ARG(line_bass, CM_REG_LEGACY_CTRL, CM_LINE_AS_BASS, 0, 0);
2627 // DEFINE_BIT_SWITCH_ARG(joystick, CM_REG_FUNCTRL1, CM_JYSTK_EN, 0, 0); /* now module option */
2628 DEFINE_SWITCH_ARG(modem, CM_REG_MISC_CTRL, CM_FLINKON|CM_FLINKOFF, CM_FLINKON, 0, 0);
2629
2630 #define DEFINE_SWITCH(sname, stype, sarg) \
2631 { .name = sname, \
2632   .iface = stype, \
2633   .info = snd_cmipci_uswitch_info, \
2634   .get = snd_cmipci_uswitch_get, \
2635   .put = snd_cmipci_uswitch_put, \
2636   .private_value = (unsigned long)&cmipci_switch_arg_##sarg,\
2637 }
2638
2639 #define DEFINE_CARD_SWITCH(sname, sarg) DEFINE_SWITCH(sname, SNDRV_CTL_ELEM_IFACE_CARD, sarg)
2640 #define DEFINE_MIXER_SWITCH(sname, sarg) DEFINE_SWITCH(sname, SNDRV_CTL_ELEM_IFACE_MIXER, sarg)
2641
2642
2643 /*
2644  * callbacks for spdif output switch
2645  * needs toggle two registers..
2646  */
2647 static int snd_cmipci_spdout_enable_get(snd_kcontrol_t *kcontrol, snd_ctl_elem_value_t *ucontrol)
2648 {
2649         int changed;
2650         changed = _snd_cmipci_uswitch_get(kcontrol, ucontrol, &cmipci_switch_arg_spdif_enable);
2651         changed |= _snd_cmipci_uswitch_get(kcontrol, ucontrol, &cmipci_switch_arg_spdo2dac);
2652         return changed;
2653 }
2654
2655 static int snd_cmipci_spdout_enable_put(snd_kcontrol_t *kcontrol, snd_ctl_elem_value_t *ucontrol)
2656 {
2657         cmipci_t *chip = snd_kcontrol_chip(kcontrol);
2658         int changed;
2659         changed = _snd_cmipci_uswitch_put(kcontrol, ucontrol, &cmipci_switch_arg_spdif_enable);
2660         changed |= _snd_cmipci_uswitch_put(kcontrol, ucontrol, &cmipci_switch_arg_spdo2dac);
2661         if (changed) {
2662                 if (ucontrol->value.integer.value[0]) {
2663                         if (chip->spdif_playback_avail)
2664                                 snd_cmipci_set_bit(chip, CM_REG_FUNCTRL1, CM_PLAYBACK_SPDF);
2665                 } else {
2666                         if (chip->spdif_playback_avail)
2667                                 snd_cmipci_clear_bit(chip, CM_REG_FUNCTRL1, CM_PLAYBACK_SPDF);
2668                 }
2669         }
2670         chip->spdif_playback_enabled = ucontrol->value.integer.value[0];
2671         return changed;
2672 }
2673
2674
2675 /* both for CM8338/8738 */
2676 static snd_kcontrol_new_t snd_cmipci_mixer_switches[] __devinitdata = {
2677         DEFINE_MIXER_SWITCH("Four Channel Mode", fourch),
2678         DEFINE_MIXER_SWITCH("Line-In As Rear", line_rear),
2679 };
2680
2681 /* for non-multichannel chips */
2682 static snd_kcontrol_new_t snd_cmipci_nomulti_switch __devinitdata =
2683 DEFINE_MIXER_SWITCH("Exchange DAC", exchange_dac);
2684
2685 /* only for CM8738 */
2686 static snd_kcontrol_new_t snd_cmipci_8738_mixer_switches[] __devinitdata = {
2687 #if 0 /* controlled in pcm device */
2688         DEFINE_MIXER_SWITCH("IEC958 In Record", spdif_in),
2689         DEFINE_MIXER_SWITCH("IEC958 Out", spdif_out),
2690         DEFINE_MIXER_SWITCH("IEC958 Out To DAC", spdo2dac),
2691 #endif
2692         // DEFINE_MIXER_SWITCH("IEC958 Output Switch", spdif_enable),
2693         { .name = "IEC958 Output Switch",
2694           .iface = SNDRV_CTL_ELEM_IFACE_MIXER,
2695           .info = snd_cmipci_uswitch_info,
2696           .get = snd_cmipci_spdout_enable_get,
2697           .put = snd_cmipci_spdout_enable_put,
2698         },
2699         DEFINE_MIXER_SWITCH("IEC958 In Valid", spdi_valid),
2700         DEFINE_MIXER_SWITCH("IEC958 Copyright", spdif_copyright),
2701         DEFINE_MIXER_SWITCH("IEC958 5V", spdo_5v),
2702 //      DEFINE_MIXER_SWITCH("IEC958 In/Out 48KHz", spdo_48k),
2703         DEFINE_MIXER_SWITCH("IEC958 Loop", spdif_loop),
2704         DEFINE_MIXER_SWITCH("IEC958 In Monitor", spdi_monitor),
2705 };
2706
2707 /* only for model 033/037 */
2708 static snd_kcontrol_new_t snd_cmipci_old_mixer_switches[] __devinitdata = {
2709         DEFINE_MIXER_SWITCH("IEC958 Mix Analog", spdif_dac_out),
2710         DEFINE_MIXER_SWITCH("IEC958 In Phase Inverse", spdi_phase),
2711         DEFINE_MIXER_SWITCH("IEC958 In Select", spdif_in_sel1),
2712 };
2713
2714 /* only for model 039 or later */
2715 static snd_kcontrol_new_t snd_cmipci_extra_mixer_switches[] __devinitdata = {
2716         DEFINE_MIXER_SWITCH("Line-In As Bass", line_bass),
2717         DEFINE_MIXER_SWITCH("IEC958 In Select", spdif_in_sel2),
2718         DEFINE_MIXER_SWITCH("IEC958 In Phase Inverse", spdi_phase2),
2719         DEFINE_MIXER_SWITCH("Mic As Center/LFE", spdi_phase), /* same bit as spdi_phase */
2720 };
2721
2722 /* card control switches */
2723 static snd_kcontrol_new_t snd_cmipci_control_switches[] __devinitdata = {
2724         // DEFINE_CARD_SWITCH("Joystick", joystick), /* now module option */
2725         DEFINE_CARD_SWITCH("Modem", modem),
2726 };
2727
2728
2729 static int __devinit snd_cmipci_mixer_new(cmipci_t *cm, int pcm_spdif_device)
2730 {
2731         unsigned long flags;
2732         snd_card_t *card;
2733         snd_kcontrol_new_t *sw;
2734         snd_kcontrol_t *kctl;
2735         unsigned int idx;
2736         int err;
2737
2738         snd_assert(cm != NULL && cm->card != NULL, return -EINVAL);
2739
2740         card = cm->card;
2741
2742         strcpy(card->mixername, "CMedia PCI");
2743
2744         spin_lock_irqsave(&cm->reg_lock, flags);
2745         snd_cmipci_mixer_write(cm, 0x00, 0x00);         /* mixer reset */
2746         spin_unlock_irqrestore(&cm->reg_lock, flags);
2747
2748         for (idx = 0; idx < num_controls(snd_cmipci_mixers); idx++) {
2749                 if ((err = snd_ctl_add(card, snd_ctl_new1(&snd_cmipci_mixers[idx], cm))) < 0)
2750                         return err;
2751         }
2752
2753         /* mixer switches */
2754         sw = snd_cmipci_mixer_switches;
2755         for (idx = 0; idx < num_controls(snd_cmipci_mixer_switches); idx++, sw++) {
2756                 err = snd_ctl_add(cm->card, snd_ctl_new1(sw, cm));
2757                 if (err < 0)
2758                         return err;
2759         }
2760         if (! cm->can_multi_ch) {
2761                 err = snd_ctl_add(cm->card, snd_ctl_new1(&snd_cmipci_nomulti_switch, cm));
2762                 if (err < 0)
2763                         return err;
2764         }
2765         if (cm->device == PCI_DEVICE_ID_CMEDIA_CM8738 ||
2766             cm->device == PCI_DEVICE_ID_CMEDIA_CM8738B) {
2767                 sw = snd_cmipci_8738_mixer_switches;
2768                 for (idx = 0; idx < num_controls(snd_cmipci_8738_mixer_switches); idx++, sw++) {
2769                         err = snd_ctl_add(cm->card, snd_ctl_new1(sw, cm));
2770                         if (err < 0)
2771                                 return err;
2772                 }
2773                 if ((err = snd_ctl_add(card, kctl = snd_ctl_new1(&snd_cmipci_spdif_default, cm))) < 0)
2774                         return err;
2775                 kctl->id.device = pcm_spdif_device;
2776                 if ((err = snd_ctl_add(card, kctl = snd_ctl_new1(&snd_cmipci_spdif_mask, cm))) < 0)
2777                         return err;
2778                 kctl->id.device = pcm_spdif_device;
2779                 if ((err = snd_ctl_add(card, kctl = snd_ctl_new1(&snd_cmipci_spdif_stream, cm))) < 0)
2780                         return err;
2781                 kctl->id.device = pcm_spdif_device;
2782                 cm->spdif_pcm_ctl = kctl;
2783                 if (cm->chip_version <= 37) {
2784                         sw = snd_cmipci_old_mixer_switches;
2785                         for (idx = 0; idx < num_controls(snd_cmipci_old_mixer_switches); idx++, sw++) {
2786                                 err = snd_ctl_add(cm->card, snd_ctl_new1(sw, cm));
2787                                 if (err < 0)
2788                                         return err;
2789                         }
2790                 }
2791         }
2792         if (cm->chip_version >= 39) {
2793                 sw = snd_cmipci_extra_mixer_switches;
2794                 for (idx = 0; idx < num_controls(snd_cmipci_extra_mixer_switches); idx++, sw++) {
2795                         err = snd_ctl_add(cm->card, snd_ctl_new1(sw, cm));
2796                         if (err < 0)
2797                                 return err;
2798                 }
2799         }
2800
2801         /* card switches */
2802         sw = snd_cmipci_control_switches;
2803         for (idx = 0; idx < num_controls(snd_cmipci_control_switches); idx++, sw++) {
2804                 err = snd_ctl_add(cm->card, snd_ctl_new1(sw, cm));
2805                 if (err < 0)
2806                         return err;
2807         }
2808
2809         for (idx = 0; idx < CM_SAVED_MIXERS; idx++) {
2810                 snd_ctl_elem_id_t id;
2811                 snd_kcontrol_t *ctl;
2812                 memset(&id, 0, sizeof(id));
2813                 id.iface = SNDRV_CTL_ELEM_IFACE_MIXER;
2814                 strcpy(id.name, cm_saved_mixer[idx].name);
2815                 if ((ctl = snd_ctl_find_id(cm->card, &id)) != NULL)
2816                         cm->mixer_res_ctl[idx] = ctl;
2817         }
2818
2819         return 0;
2820 }
2821
2822
2823 /*
2824  * proc interface
2825  */
2826
2827 #ifdef CONFIG_PROC_FS
2828 static void snd_cmipci_proc_read(snd_info_entry_t *entry, 
2829                                  snd_info_buffer_t *buffer)
2830 {
2831         cmipci_t *cm = snd_magic_cast(cmipci_t, entry->private_data, return);
2832         int i;
2833         
2834         snd_iprintf(buffer, "%s\n\n", cm->card->longname);
2835         for (i = 0; i < 0x40; i++) {
2836                 int v = inb(cm->iobase + i);
2837                 if (i % 4 == 0)
2838                         snd_iprintf(buffer, "%02x: ", i);
2839                 snd_iprintf(buffer, "%02x", v);
2840                 if (i % 4 == 3)
2841                         snd_iprintf(buffer, "\n");
2842                 else
2843                         snd_iprintf(buffer, " ");
2844         }
2845 }
2846
2847 static void __devinit snd_cmipci_proc_init(cmipci_t *cm)
2848 {
2849         snd_info_entry_t *entry;
2850
2851         if (! snd_card_proc_new(cm->card, "cmipci", &entry))
2852                 snd_info_set_text_ops(entry, cm, 1024, snd_cmipci_proc_read);
2853 }
2854 #else /* !CONFIG_PROC_FS */
2855 static inline void snd_cmipci_proc_init(cmipci_t *cm) {}
2856 #endif
2857
2858
2859 static struct pci_device_id snd_cmipci_ids[] = {
2860         {PCI_VENDOR_ID_CMEDIA, PCI_DEVICE_ID_CMEDIA_CM8338A, PCI_ANY_ID, PCI_ANY_ID, 0, 0, 0},
2861         {PCI_VENDOR_ID_CMEDIA, PCI_DEVICE_ID_CMEDIA_CM8338B, PCI_ANY_ID, PCI_ANY_ID, 0, 0, 0},
2862         {PCI_VENDOR_ID_CMEDIA, PCI_DEVICE_ID_CMEDIA_CM8738, PCI_ANY_ID, PCI_ANY_ID, 0, 0, 0},
2863         {PCI_VENDOR_ID_CMEDIA, PCI_DEVICE_ID_CMEDIA_CM8738B, PCI_ANY_ID, PCI_ANY_ID, 0, 0, 0},
2864         {PCI_VENDOR_ID_AL, PCI_DEVICE_ID_CMEDIA_CM8738, PCI_ANY_ID, PCI_ANY_ID, 0, 0, 0},
2865         {0,},
2866 };
2867
2868
2869 /*
2870  * check chip version and capabilities
2871  * driver name is modified according to the chip model
2872  */
2873 static void __devinit query_chip(cmipci_t *cm)
2874 {
2875         unsigned int detect;
2876
2877         /* check reg 0Ch, bit 24-31 */
2878         detect = snd_cmipci_read(cm, CM_REG_INT_HLDCLR) & CM_CHIP_MASK2;
2879         if (! detect) {
2880                 /* check reg 08h, bit 24-28 */
2881                 detect = snd_cmipci_read(cm, CM_REG_CHFORMAT) & CM_CHIP_MASK1;
2882                 if (! detect) {
2883                         cm->chip_version = 33;
2884                         cm->max_channels = 2;
2885                         if (cm->do_soft_ac3)
2886                                 cm->can_ac3_sw = 1;
2887                         else
2888                                 cm->can_ac3_hw = 1;
2889                         cm->has_dual_dac = 1;
2890                 } else {
2891                         cm->chip_version = 37;
2892                         cm->max_channels = 2;
2893                         cm->can_ac3_hw = 1;
2894                         cm->has_dual_dac = 1;
2895                 }
2896         } else {
2897                 /* check reg 0Ch, bit 26 */
2898                 if (detect & CM_CHIP_039) {
2899                         cm->chip_version = 39;
2900                         if (detect & CM_CHIP_039_6CH)
2901                                 cm->max_channels  = 6;
2902                         else
2903                                 cm->max_channels = 4;
2904                         cm->can_ac3_hw = 1;
2905                         cm->has_dual_dac = 1;
2906                         cm->can_multi_ch = 1;
2907                 } else {
2908                         cm->chip_version = 55; /* 4 or 6 channels */
2909                         cm->max_channels  = 6;
2910                         cm->can_ac3_hw = 1;
2911                         cm->has_dual_dac = 1;
2912                         cm->can_multi_ch = 1;
2913                 }
2914         }
2915
2916         /* added -MCx suffix for chip supporting multi-channels */
2917         if (cm->can_multi_ch)
2918                 sprintf(cm->card->driver + strlen(cm->card->driver),
2919                         "-MC%d", cm->max_channels);
2920 }
2921
2922
2923 static int snd_cmipci_free(cmipci_t *cm)
2924 {
2925         if (cm->irq >= 0) {
2926                 snd_cmipci_clear_bit(cm, CM_REG_MISC_CTRL, CM_FM_EN);
2927                 snd_cmipci_clear_bit(cm, CM_REG_LEGACY_CTRL, CM_ENSPDOUT);
2928                 snd_cmipci_write(cm, CM_REG_INT_HLDCLR, 0);  /* disable ints */
2929                 snd_cmipci_ch_reset(cm, CM_CH_PLAY);
2930                 snd_cmipci_ch_reset(cm, CM_CH_CAPT);
2931                 snd_cmipci_write(cm, CM_REG_FUNCTRL0, 0); /* disable channels */
2932                 snd_cmipci_write(cm, CM_REG_FUNCTRL1, 0);
2933
2934                 /* reset mixer */
2935                 snd_cmipci_mixer_write(cm, 0, 0);
2936
2937                 synchronize_irq(cm->irq);
2938
2939                 free_irq(cm->irq, (void *)cm);
2940         }
2941 #ifdef SUPPORT_JOYSTICK
2942         if (cm->res_joystick) {
2943                 gameport_unregister_port(&cm->gameport);
2944                 snd_cmipci_clear_bit(cm, CM_REG_FUNCTRL1, CM_JYSTK_EN);
2945                 release_resource(cm->res_joystick);
2946                 kfree_nocheck(cm->res_joystick);
2947         }
2948 #endif
2949         if (cm->res_iobase) {
2950                 release_resource(cm->res_iobase);
2951                 kfree_nocheck(cm->res_iobase);
2952         }
2953         snd_magic_kfree(cm);
2954         return 0;
2955 }
2956
2957 static int snd_cmipci_dev_free(snd_device_t *device)
2958 {
2959         cmipci_t *cm = snd_magic_cast(cmipci_t, device->device_data, return -ENXIO);
2960         return snd_cmipci_free(cm);
2961 }
2962
2963 static int __devinit snd_cmipci_create(snd_card_t *card, struct pci_dev *pci,
2964                                        int dev, cmipci_t **rcmipci)
2965 {
2966         cmipci_t *cm;
2967         int err;
2968         static snd_device_ops_t ops = {
2969                 .dev_free =     snd_cmipci_dev_free,
2970         };
2971         unsigned int val = 0;
2972         long iomidi = mpu_port[dev];
2973         long iosynth = fm_port[dev];
2974         int pcm_index, pcm_spdif_index;
2975
2976         *rcmipci = NULL;
2977
2978         if ((err = pci_enable_device(pci)) < 0)
2979                 return err;
2980
2981         cm = snd_magic_kcalloc(cmipci_t, 0, GFP_KERNEL);
2982         if (cm == NULL)
2983                 return -ENOMEM;
2984
2985         spin_lock_init(&cm->reg_lock);
2986         init_MUTEX(&cm->open_mutex);
2987         cm->device = pci->device;
2988         cm->card = card;
2989         cm->pci = pci;
2990         cm->irq = -1;
2991         cm->iobase = pci_resource_start(pci, 0);
2992         cm->channel[0].ch = 0;
2993         cm->channel[1].ch = 1;
2994         cm->channel[0].is_dac = cm->channel[1].is_dac = 1; /* dual DAC mode */
2995
2996         if ((cm->res_iobase = request_region(cm->iobase, CM_EXTENT_CODEC, card->driver)) == NULL) {
2997                 snd_printk("unable to grab ports 0x%lx-0x%lx\n", cm->iobase, cm->iobase + CM_EXTENT_CODEC - 1);
2998                 err = -EBUSY;
2999                 goto __error;
3000         }
3001         if (request_irq(pci->irq, snd_cmipci_interrupt, SA_INTERRUPT|SA_SHIRQ, card->driver, (void *)cm)) {
3002                 snd_printk("unable to grab IRQ %d\n", pci->irq);
3003                 err = -EBUSY;
3004                 goto __error;
3005         }
3006         cm->irq = pci->irq;
3007
3008         pci_set_master(cm->pci);
3009
3010         /*
3011          * check chip version, max channels and capabilities
3012          */
3013
3014         cm->chip_version = 0;
3015         cm->max_channels = 2;
3016 #ifdef DO_SOFT_AC3
3017         cm->do_soft_ac3 = soft_ac3[dev];
3018 #endif
3019
3020         query_chip(cm);
3021
3022         cm->dig_status = SNDRV_PCM_DEFAULT_CON_SPDIF;
3023         cm->dig_pcm_status = SNDRV_PCM_DEFAULT_CON_SPDIF;
3024
3025 #if CM_CH_PLAY == 1
3026         cm->ctrl = CM_CHADC0;   /* default FUNCNTRL0 */
3027 #else
3028         cm->ctrl = CM_CHADC1;   /* default FUNCNTRL0 */
3029 #endif
3030
3031         /* initialize codec registers */
3032         snd_cmipci_write(cm, CM_REG_INT_HLDCLR, 0);     /* disable ints */
3033         snd_cmipci_ch_reset(cm, CM_CH_PLAY);
3034         snd_cmipci_ch_reset(cm, CM_CH_CAPT);
3035         snd_cmipci_write(cm, CM_REG_FUNCTRL0, 0);       /* disable channels */
3036         snd_cmipci_write(cm, CM_REG_FUNCTRL1, 0);
3037
3038         snd_cmipci_write(cm, CM_REG_CHFORMAT, 0);
3039         snd_cmipci_set_bit(cm, CM_REG_MISC_CTRL, CM_ENDBDAC|CM_N4SPK3D);
3040 #if CM_CH_PLAY == 1
3041         snd_cmipci_set_bit(cm, CM_REG_MISC_CTRL, CM_XCHGDAC);
3042 #else
3043         snd_cmipci_clear_bit(cm, CM_REG_MISC_CTRL, CM_XCHGDAC);
3044 #endif
3045         /* Set Bus Master Request */
3046         snd_cmipci_set_bit(cm, CM_REG_FUNCTRL1, CM_BREQ);
3047
3048         /* Assume TX and compatible chip set (Autodetection required for VX chip sets) */
3049         switch (pci->device) {
3050         case PCI_DEVICE_ID_CMEDIA_CM8738:
3051         case PCI_DEVICE_ID_CMEDIA_CM8738B:
3052                 /* PCI_VENDOR_ID_INTEL, PCI_DEVICE_ID_INTEL_82437VX */
3053                 if (! pci_find_device(0x8086, 0x7030, NULL))
3054                         snd_cmipci_set_bit(cm, CM_REG_MISC_CTRL, CM_TXVX);
3055                 break;
3056         default:
3057                 break;
3058         }
3059
3060         /* set MPU address */
3061         switch (iomidi) {
3062         case 0x320: val = CM_VMPU_320; break;
3063         case 0x310: val = CM_VMPU_310; break;
3064         case 0x300: val = CM_VMPU_300; break;
3065         case 0x330: val = CM_VMPU_330; break;
3066         default:
3067                 iomidi = 0; break;
3068         }
3069         if (iomidi > 0) {
3070                 snd_cmipci_write(cm, CM_REG_LEGACY_CTRL, val);
3071                 /* enable UART */
3072                 snd_cmipci_set_bit(cm, CM_REG_FUNCTRL1, CM_UART_EN);
3073         }
3074
3075         /* set FM address */
3076         val = snd_cmipci_read(cm, CM_REG_LEGACY_CTRL) & ~CM_FMSEL_MASK;
3077         switch (iosynth) {
3078         case 0x3E8: val |= CM_FMSEL_3E8; break;
3079         case 0x3E0: val |= CM_FMSEL_3E0; break;
3080         case 0x3C8: val |= CM_FMSEL_3C8; break;
3081         case 0x388: val |= CM_FMSEL_388; break;
3082         default:
3083                 iosynth = 0; break;
3084         }
3085         if (iosynth > 0) {
3086                 snd_cmipci_write(cm, CM_REG_LEGACY_CTRL, val);
3087                 /* enable FM */
3088                 snd_cmipci_set_bit(cm, CM_REG_MISC_CTRL, CM_FM_EN);
3089
3090                 if (snd_opl3_create(card, iosynth, iosynth + 2,
3091                                     OPL3_HW_OPL3, 0, &cm->opl3) < 0) {
3092                         printk(KERN_ERR "cmipci: no OPL device at 0x%lx, skipping...\n", iosynth);
3093                         iosynth = 0;
3094                 } else {
3095                         if ((err = snd_opl3_hwdep_new(cm->opl3, 0, 1, &cm->opl3hwdep)) < 0) {
3096                                 printk(KERN_ERR "cmipci: cannot create OPL3 hwdep\n");
3097                                 return err;
3098                         }
3099                 }
3100         }
3101         if (! iosynth) {
3102                 /* disable FM */
3103                 snd_cmipci_write(cm, CM_REG_LEGACY_CTRL, val & ~CM_FMSEL_MASK);
3104                 snd_cmipci_clear_bit(cm, CM_REG_MISC_CTRL, CM_FM_EN);
3105         }
3106
3107         /* reset mixer */
3108         snd_cmipci_mixer_write(cm, 0, 0);
3109
3110         snd_cmipci_proc_init(cm);
3111
3112         /* create pcm devices */
3113         pcm_index = pcm_spdif_index = 0;
3114         if ((err = snd_cmipci_pcm_new(cm, pcm_index)) < 0)
3115                 goto __error;
3116         pcm_index++;
3117         if (cm->has_dual_dac) {
3118                 if ((err = snd_cmipci_pcm2_new(cm, pcm_index)) < 0)
3119                         goto __error;
3120                 pcm_index++;
3121         }
3122         if (cm->can_ac3_hw || cm->can_ac3_sw) {
3123                 pcm_spdif_index = pcm_index;
3124                 if ((err = snd_cmipci_pcm_spdif_new(cm, pcm_index)) < 0)
3125                         goto __error;
3126         }
3127
3128         /* create mixer interface & switches */
3129         if ((err = snd_cmipci_mixer_new(cm, pcm_spdif_index)) < 0)
3130                 goto __error;
3131
3132         if (iomidi > 0) {
3133                 if ((err = snd_mpu401_uart_new(card, 0, MPU401_HW_CMIPCI,
3134                                                iomidi, 0,
3135                                                cm->irq, 0, &cm->rmidi)) < 0) {
3136                         printk(KERN_ERR "cmipci: no UART401 device at 0x%lx\n", iomidi);
3137                 }
3138         }
3139
3140         if ((err = snd_device_new(card, SNDRV_DEV_LOWLEVEL, cm, &ops)) < 0) {
3141                 snd_cmipci_free(cm);
3142                 return err;
3143         }
3144 #ifdef USE_VAR48KRATE
3145         for (val = 0; val < ARRAY_SIZE(rates); val++)
3146                 snd_cmipci_set_pll(cm, rates[val], val);
3147
3148         /*
3149          * (Re-)Enable external switch spdo_48k
3150          */
3151         snd_cmipci_set_bit(cm, CM_REG_MISC_CTRL, CM_SPDIF48K|CM_SPDF_AC97);
3152 #endif /* USE_VAR48KRATE */
3153
3154 #ifdef SUPPORT_JOYSTICK
3155         if (joystick_port[dev] > 0) {
3156                 if (joystick_port[dev] == 1) { /* auto-detect */
3157                         static int ports[] = { 0x201, 0x200, 0 }; /* FIXME: majority is 0x201? */
3158                         int i;
3159                         for (i = 0; ports[i]; i++) {
3160                                 joystick_port[dev] = ports[i];
3161                                 cm->res_joystick = request_region(ports[i], 8, "CMIPCI gameport");
3162                                 if (cm->res_joystick)
3163                                         break;
3164                         }
3165                 } else {
3166                         cm->res_joystick = request_region(joystick_port[dev], 8, "CMIPCI gameport");
3167                 }
3168         }
3169         if (cm->res_joystick) {
3170                 cm->gameport.io = joystick_port[dev];
3171                 snd_cmipci_set_bit(cm, CM_REG_FUNCTRL1, CM_JYSTK_EN);
3172                 gameport_register_port(&cm->gameport);
3173         } else {
3174                 if (joystick_port[dev] > 0)
3175                         printk(KERN_WARNING "cmipci: cannot reserve joystick ports\n");
3176                 snd_cmipci_clear_bit(cm, CM_REG_FUNCTRL1, CM_JYSTK_EN);
3177         }
3178 #endif
3179         snd_card_set_dev(card, &pci->dev);
3180
3181         *rcmipci = cm;
3182         return 0;
3183
3184  __error:
3185         snd_cmipci_free(cm);
3186         return err;
3187 }
3188
3189 /*
3190  */
3191
3192 MODULE_DEVICE_TABLE(pci, snd_cmipci_ids);
3193
3194 static int __devinit snd_cmipci_probe(struct pci_dev *pci,
3195                                       const struct pci_device_id *pci_id)
3196 {
3197         static int dev;
3198         snd_card_t *card;
3199         cmipci_t *cm;
3200         int err;
3201
3202         if (dev >= SNDRV_CARDS)
3203                 return -ENODEV;
3204         if (! enable[dev]) {
3205                 dev++;
3206                 return -ENOENT;
3207         }
3208
3209         card = snd_card_new(index[dev], id[dev], THIS_MODULE, 0);
3210         if (card == NULL)
3211                 return -ENOMEM;
3212         
3213         switch (pci->device) {
3214         case PCI_DEVICE_ID_CMEDIA_CM8738:
3215         case PCI_DEVICE_ID_CMEDIA_CM8738B:
3216                 strcpy(card->driver, "CMI8738");
3217                 break;
3218         case PCI_DEVICE_ID_CMEDIA_CM8338A:
3219         case PCI_DEVICE_ID_CMEDIA_CM8338B:
3220                 strcpy(card->driver, "CMI8338");
3221                 break;
3222         default:
3223                 strcpy(card->driver, "CMIPCI");
3224                 break;
3225         }
3226
3227         if ((err = snd_cmipci_create(card, pci, dev, &cm)) < 0) {
3228                 snd_card_free(card);
3229                 return err;
3230         }
3231
3232         sprintf(card->shortname, "C-Media PCI %s", card->driver);
3233         sprintf(card->longname, "%s (model %d) at 0x%lx, irq %i",
3234                 card->shortname,
3235                 cm->chip_version,
3236                 cm->iobase,
3237                 cm->irq);
3238
3239         //snd_printd("%s is detected\n", card->longname);
3240
3241         if ((err = snd_card_register(card)) < 0) {
3242                 snd_card_free(card);
3243                 return err;
3244         }
3245         pci_set_drvdata(pci, card);
3246         dev++;
3247         return 0;
3248
3249 }
3250
3251 static void __devexit snd_cmipci_remove(struct pci_dev *pci)
3252 {
3253         snd_card_free(pci_get_drvdata(pci));
3254         pci_set_drvdata(pci, NULL);
3255 }
3256
3257
3258 static struct pci_driver driver = {
3259         .name = "C-Media PCI",
3260         .id_table = snd_cmipci_ids,
3261         .probe = snd_cmipci_probe,
3262         .remove = __devexit_p(snd_cmipci_remove),
3263 };
3264         
3265 static int __init alsa_card_cmipci_init(void)
3266 {
3267         int err;
3268
3269         if ((err = pci_module_init(&driver)) < 0) {
3270 #ifdef MODULE
3271                 printk(KERN_ERR "C-Media PCI soundcard not found or device busy\n");
3272 #endif
3273                 return err;
3274         }
3275         return 0;
3276 }
3277
3278 static void __exit alsa_card_cmipci_exit(void)
3279 {
3280         pci_unregister_driver(&driver);
3281 }
3282
3283 module_init(alsa_card_cmipci_init)
3284 module_exit(alsa_card_cmipci_exit)
3285
3286 #ifndef MODULE
3287
3288 /* format is: snd-cmipci=enable,index,id,
3289                          mpu_port,fm_port,soft_ac3,joystick_port */
3290
3291 static int __init alsa_card_cmipci_setup(char *str)
3292 {
3293         static unsigned __initdata nr_dev = 0;
3294
3295         if (nr_dev >= SNDRV_CARDS)
3296                 return 0;
3297         (void)(get_option(&str,&enable[nr_dev]) == 2 &&
3298                get_option(&str,&index[nr_dev]) == 2 &&
3299                get_id(&str,&id[nr_dev]) == 2 &&
3300                get_option_long(&str,&mpu_port[nr_dev]) == 2 &&
3301                get_option_long(&str,&fm_port[nr_dev]) == 2
3302 #ifdef DO_SOFT_AC3
3303                && get_option(&str,&soft_ac3[nr_dev]) == 2
3304 #endif
3305 #ifdef SUPPORT_JOYSTICK
3306                && get_option(&str,&joystick_port[nr_dev]) == 2
3307 #endif
3308                );
3309         nr_dev++;
3310         return 1;
3311 }
3312
3313 __setup("snd-cmipci=", alsa_card_cmipci_setup);
3314
3315 #endif /* ifndef MODULE */