Remove all inclusions of <linux/config.h>
[linux-3.10.git] / sound / oss / cmpci.c
1 /*
2  *      cmpci.c  --  C-Media PCI audio driver.
3  *
4  *      Copyright (C) 1999  C-media support (support@cmedia.com.tw)
5  *
6  *      Based on the PCI drivers by Thomas Sailer (sailer@ife.ee.ethz.ch)
7  *
8  *      For update, visit:
9  *              http://www.cmedia.com.tw
10  *
11  *      This program is free software; you can redistribute it and/or modify
12  *      it under the terms of the GNU General Public License as published by
13  *      the Free Software Foundation; either version 2 of the License, or
14  *      (at your option) any later version.
15  *
16  *      This program is distributed in the hope that it will be useful,
17  *      but WITHOUT ANY WARRANTY; without even the implied warranty of
18  *      MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
19  *      GNU General Public License for more details.
20  *
21  *      You should have received a copy of the GNU General Public License
22  *      along with this program; if not, write to the Free Software
23  *      Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
24  *
25  * Special thanks to David C. Niemi, Jan Pfeifer
26  *
27  *
28  * Module command line parameters:
29  *   none so far
30  *
31  *
32  *  Supported devices:
33  *  /dev/dsp    standard /dev/dsp device, (mostly) OSS compatible
34  *  /dev/mixer  standard /dev/mixer device, (mostly) OSS compatible
35  *  /dev/midi   simple MIDI UART interface, no ioctl
36  *
37  *  The card has both an FM and a Wavetable synth, but I have to figure
38  *  out first how to drive them...
39  *
40  *  Revision history
41  *    06.05.98   0.1   Initial release
42  *    10.05.98   0.2   Fixed many bugs, esp. ADC rate calculation
43  *                     First stab at a simple midi interface (no bells&whistles)
44  *    13.05.98   0.3   Fix stupid cut&paste error: set_adc_rate was called instead of
45  *                     set_dac_rate in the FMODE_WRITE case in cm_open
46  *                     Fix hwptr out of bounds (now mpg123 works)
47  *    14.05.98   0.4   Don't allow excessive interrupt rates
48  *    08.06.98   0.5   First release using Alan Cox' soundcore instead of miscdevice
49  *    03.08.98   0.6   Do not include modversions.h
50  *                     Now mixer behaviour can basically be selected between
51  *                     "OSS documented" and "OSS actual" behaviour
52  *    31.08.98   0.7   Fix realplayer problems - dac.count issues
53  *    10.12.98   0.8   Fix drain_dac trying to wait on not yet initialized DMA
54  *    16.12.98   0.9   Fix a few f_file & FMODE_ bugs
55  *    06.01.99   0.10  remove the silly SA_INTERRUPT flag.
56  *                     hopefully killed the egcs section type conflict
57  *    12.03.99   0.11  cinfo.blocks should be reset after GETxPTR ioctl.
58  *                     reported by Johan Maes <joma@telindus.be>
59  *    22.03.99   0.12  return EAGAIN instead of EBUSY when O_NONBLOCK
60  *                     read/write cannot be executed
61  *    18.08.99   1.5   Only deallocate DMA buffer when unloading.
62  *    02.09.99   1.6   Enable SPDIF LOOP
63  *                     Change the mixer read back
64  *    21.09.99   2.33  Use RCS version as driver version.
65  *                     Add support for modem, S/PDIF loop and 4 channels.
66  *                     (8738 only)
67  *                     Fix bug cause x11amp cannot play.
68  *
69  *    Fixes:
70  *    Arnaldo Carvalho de Melo <acme@conectiva.com.br>
71  *    18/05/2001 - .bss nitpicks, fix a bug in set_dac_channels where it
72  *                 was calling prog_dmabuf with s->lock held, call missing
73  *                 unlock_kernel in cm_midi_release
74  *    08/10/2001 - use set_current_state in some more places
75  *
76  *      Carlos Eduardo Gorges <carlos@techlinux.com.br>
77  *      Fri May 25 2001
78  *      - SMP support ( spin[un]lock* revision )
79  *      - speaker mixer support
80  *      Mon Aug 13 2001
81  *      - optimizations and cleanups
82  *
83  *    03/01/2003 - open_mode fixes from Georg Acher <acher@in.tum.de>
84  *      Simon Braunschmidt <brasimon@web.de>
85  *     Sat Jan 31 2004
86  *      - provide support for opl3 FM by releasing IO range after initialization
87  *
88  *    ChenLi Tien <cltien@cmedia.com.tw>
89  *    Mar 9 2004
90  *      - Fix S/PDIF out if spdif_loop enabled
91  *      - Load opl3 driver if enabled (fmio in proper range)
92  *      - Load mpu401 if enabled (mpuio in proper range)
93  *    Apr 5 2004
94  *      - Fix DUAL_DAC dma synchronization bug
95  *      - Check exist FM/MPU401 I/O before activate.
96  *      - Add AFTM_S16_BE format support, so MPlayer/Xine can play AC3/mutlichannel
97  *        on Mac
98  *      - Change to support kernel 2.6 so only small patch needed
99  *      - All parameters default to 0
100  *      - Add spdif_out to send PCM through S/PDIF out jack
101  *      - Add hw_copy to get 4-spaker output for general PCM/analog output
102  *
103  *    Stefan Thater <stefan.thaeter@gmx.de>
104  *    Apr 5 2004
105  *      - Fix mute single channel for CD/Line-in/AUX-in
106  */
107 /*****************************************************************************/
108
109 #include <linux/module.h>
110 #include <linux/string.h>
111 #include <linux/interrupt.h>
112 #include <linux/ioport.h>
113 #include <linux/sched.h>
114 #include <linux/delay.h>
115 #include <linux/sound.h>
116 #include <linux/slab.h>
117 #include <linux/soundcard.h>
118 #include <linux/pci.h>
119 #include <linux/init.h>
120 #include <linux/poll.h>
121 #include <linux/spinlock.h>
122 #include <linux/smp_lock.h>
123 #include <linux/bitops.h>
124 #include <linux/wait.h>
125 #include <linux/dma-mapping.h>
126
127 #include <asm/io.h>
128 #include <asm/page.h>
129 #include <asm/uaccess.h>
130
131 #ifdef CONFIG_SOUND_CMPCI_MIDI
132 #include "sound_config.h"
133 #include "mpu401.h"
134 #endif
135 #ifdef CONFIG_SOUND_CMPCI_FM
136 #include "opl3.h"
137 #endif
138 #ifdef CONFIG_SOUND_CMPCI_JOYSTICK
139 #include <linux/gameport.h>
140 #include <linux/mutex.h>
141
142 #endif
143
144 /* --------------------------------------------------------------------- */
145 #undef OSS_DOCUMENTED_MIXER_SEMANTICS
146 #undef DMABYTEIO
147 #define DBG(x) {}
148 /* --------------------------------------------------------------------- */
149
150 #define CM_MAGIC  ((PCI_VENDOR_ID_CMEDIA<<16)|PCI_DEVICE_ID_CMEDIA_CM8338A)
151
152 /* CM8338 registers definition ****************/
153
154 #define CODEC_CMI_FUNCTRL0              (0x00)
155 #define CODEC_CMI_FUNCTRL1              (0x04)
156 #define CODEC_CMI_CHFORMAT              (0x08)
157 #define CODEC_CMI_INT_HLDCLR            (0x0C)
158 #define CODEC_CMI_INT_STATUS            (0x10)
159 #define CODEC_CMI_LEGACY_CTRL           (0x14)
160 #define CODEC_CMI_MISC_CTRL             (0x18)
161 #define CODEC_CMI_TDMA_POS              (0x1C)
162 #define CODEC_CMI_MIXER                 (0x20)
163 #define CODEC_SB16_DATA                 (0x22)
164 #define CODEC_SB16_ADDR                 (0x23)
165 #define CODEC_CMI_MIXER1                (0x24)
166 #define CODEC_CMI_MIXER2                (0x25)
167 #define CODEC_CMI_AUX_VOL               (0x26)
168 #define CODEC_CMI_MISC                  (0x27)
169 #define CODEC_CMI_AC97                  (0x28)
170
171 #define CODEC_CMI_CH0_FRAME1            (0x80)
172 #define CODEC_CMI_CH0_FRAME2            (0x84)
173 #define CODEC_CMI_CH1_FRAME1            (0x88)
174 #define CODEC_CMI_CH1_FRAME2            (0x8C)
175
176 #define CODEC_CMI_SPDIF_CTRL            (0x90)
177 #define CODEC_CMI_MISC_CTRL2            (0x92)
178
179 #define CODEC_CMI_EXT_REG               (0xF0)
180
181 /*  Mixer registers for SB16 ******************/
182
183 #define DSP_MIX_DATARESETIDX            ((unsigned char)(0x00))
184
185 #define DSP_MIX_MASTERVOLIDX_L          ((unsigned char)(0x30))
186 #define DSP_MIX_MASTERVOLIDX_R          ((unsigned char)(0x31))
187 #define DSP_MIX_VOICEVOLIDX_L           ((unsigned char)(0x32))
188 #define DSP_MIX_VOICEVOLIDX_R           ((unsigned char)(0x33))
189 #define DSP_MIX_FMVOLIDX_L              ((unsigned char)(0x34))
190 #define DSP_MIX_FMVOLIDX_R              ((unsigned char)(0x35))
191 #define DSP_MIX_CDVOLIDX_L              ((unsigned char)(0x36))
192 #define DSP_MIX_CDVOLIDX_R              ((unsigned char)(0x37))
193 #define DSP_MIX_LINEVOLIDX_L            ((unsigned char)(0x38))
194 #define DSP_MIX_LINEVOLIDX_R            ((unsigned char)(0x39))
195
196 #define DSP_MIX_MICVOLIDX               ((unsigned char)(0x3A))
197 #define DSP_MIX_SPKRVOLIDX              ((unsigned char)(0x3B))
198
199 #define DSP_MIX_OUTMIXIDX               ((unsigned char)(0x3C))
200
201 #define DSP_MIX_ADCMIXIDX_L             ((unsigned char)(0x3D))
202 #define DSP_MIX_ADCMIXIDX_R             ((unsigned char)(0x3E))
203
204 #define DSP_MIX_INGAINIDX_L             ((unsigned char)(0x3F))
205 #define DSP_MIX_INGAINIDX_R             ((unsigned char)(0x40))
206 #define DSP_MIX_OUTGAINIDX_L            ((unsigned char)(0x41))
207 #define DSP_MIX_OUTGAINIDX_R            ((unsigned char)(0x42))
208
209 #define DSP_MIX_AGCIDX                  ((unsigned char)(0x43))
210
211 #define DSP_MIX_TREBLEIDX_L             ((unsigned char)(0x44))
212 #define DSP_MIX_TREBLEIDX_R             ((unsigned char)(0x45))
213 #define DSP_MIX_BASSIDX_L               ((unsigned char)(0x46))
214 #define DSP_MIX_BASSIDX_R               ((unsigned char)(0x47))
215 #define DSP_MIX_EXTENSION               ((unsigned char)(0xf0))
216 // pseudo register for AUX
217 #define DSP_MIX_AUXVOL_L                ((unsigned char)(0x50))
218 #define DSP_MIX_AUXVOL_R                ((unsigned char)(0x51))
219
220 // I/O length
221 #define CM_EXTENT_CODEC   0x100
222 #define CM_EXTENT_MIDI    0x2
223 #define CM_EXTENT_SYNTH   0x4
224 #define CM_EXTENT_GAME    0x8
225
226 // Function Control Register 0 (00h)
227 #define CHADC0          0x01
228 #define CHADC1          0x02
229 #define PAUSE0          0x04
230 #define PAUSE1          0x08
231
232 // Function Control Register 0+2 (02h)
233 #define CHEN0           0x01
234 #define CHEN1           0x02
235 #define RST_CH0         0x04
236 #define RST_CH1         0x08
237
238 // Function Control Register 1 (04h)
239 #define JYSTK_EN        0x02
240 #define UART_EN         0x04
241 #define SPDO2DAC        0x40
242 #define SPDFLOOP        0x80
243
244 // Function Control Register 1+1 (05h)
245 #define SPDF_0          0x01
246 #define SPDF_1          0x02
247 #define ASFC            0x1c
248 #define DSFC            0xe0
249 #define SPDIF2DAC       (SPDF_1 << 8 | SPDO2DAC)
250
251 // Channel Format Register (08h)
252 #define CM_CFMT_STEREO  0x01
253 #define CM_CFMT_16BIT   0x02
254 #define CM_CFMT_MASK    0x03
255 #define POLVALID        0x20
256 #define INVSPDIFI       0x80
257
258 // Channel Format Register+2 (0ah)
259 #define SPD24SEL        0x20
260
261 // Channel Format Register+3 (0bh)
262 #define CHB3D           0x20
263 #define CHB3D5C         0x80
264
265 // Interrupt Hold/Clear Register+2 (0eh)
266 #define CH0_INT_EN      0x01
267 #define CH1_INT_EN      0x02
268
269 // Interrupt Register (10h)
270 #define CHINT0          0x01
271 #define CHINT1          0x02
272 #define CH0BUSY         0x04
273 #define CH1BUSY         0x08
274
275 // Legacy Control/Status Register+1 (15h)
276 #define EXBASEN         0x10
277 #define BASE2LIN        0x20
278 #define CENTR2LIN       0x40
279 #define CB2LIN          (BASE2LIN | CENTR2LIN)
280 #define CHB3D6C         0x80
281
282 // Legacy Control/Status Register+2 (16h)
283 #define DAC2SPDO        0x20
284 #define SPDCOPYRHT      0x40
285 #define ENSPDOUT        0x80
286
287 // Legacy Control/Status Register+3 (17h)
288 #define FMSEL           0x03
289 #define VSBSEL          0x0c
290 #define VMPU            0x60
291 #define NXCHG           0x80
292
293 // Miscellaneous Control Register (18h)
294 #define REAR2LIN        0x20
295 #define MUTECH1         0x40
296 #define ENCENTER        0x80
297
298 // Miscellaneous Control Register+1 (19h)
299 #define SELSPDIFI2      0x01
300 #define SPDF_AC97       0x80
301
302 // Miscellaneous Control Register+2 (1ah)
303 #define AC3_EN          0x04
304 #define FM_EN           0x08
305 #define SPD32SEL        0x20
306 #define XCHGDAC         0x40
307 #define ENDBDAC         0x80
308
309 // Miscellaneous Control Register+3 (1bh)
310 #define SPDIFI48K       0x01
311 #define SPDO5V          0x02
312 #define N4SPK3D         0x04
313 #define RESET           0x40
314 #define PWD             0x80
315 #define SPDIF48K        (SPDIFI48K << 24 | SPDF_AC97 << 8)
316
317 // Mixer1 (24h)
318 #define CDPLAY          0x01
319 #define X3DEN           0x02
320 #define REAR2FRONT      0x10
321 #define SPK4            0x20
322 #define WSMUTE          0x40
323 #define FMMUTE          0x80
324
325 // Miscellaneous Register (27h)
326 #define SPDVALID        0x02
327 #define CENTR2MIC       0x04
328
329 // Miscellaneous Register2 (92h)
330 #define SPD32KFMT       0x10
331
332 #define CM_CFMT_DACSHIFT   2
333 #define CM_CFMT_ADCSHIFT   0
334 #define CM_FREQ_DACSHIFT   5
335 #define CM_FREQ_ADCSHIFT   2
336 #define RSTDAC  RST_CH1
337 #define RSTADC  RST_CH0
338 #define ENDAC   CHEN1
339 #define ENADC   CHEN0
340 #define PAUSEDAC        PAUSE1
341 #define PAUSEADC        PAUSE0
342 #define CODEC_CMI_ADC_FRAME1    CODEC_CMI_CH0_FRAME1
343 #define CODEC_CMI_ADC_FRAME2    CODEC_CMI_CH0_FRAME2
344 #define CODEC_CMI_DAC_FRAME1    CODEC_CMI_CH1_FRAME1
345 #define CODEC_CMI_DAC_FRAME2    CODEC_CMI_CH1_FRAME2
346 #define DACINT  CHINT1
347 #define ADCINT  CHINT0
348 #define DACBUSY CH1BUSY
349 #define ADCBUSY CH0BUSY
350 #define ENDACINT        CH1_INT_EN
351 #define ENADCINT        CH0_INT_EN
352
353 static const unsigned sample_size[] = { 1, 2, 2, 4 };
354 static const unsigned sample_shift[]    = { 0, 1, 1, 2 };
355
356 #define SND_DEV_DSP16   5
357
358 #define NR_DEVICE 3             /* maximum number of devices */
359
360 #define set_dac1_rate   set_adc_rate
361 #define set_dac1_rate_unlocked  set_adc_rate_unlocked
362 #define stop_dac1       stop_adc
363 #define stop_dac1_unlocked      stop_adc_unlocked
364 #define get_dmadac1     get_dmaadc
365
366 static unsigned int devindex = 0;
367
368 //*********************************************/
369
370 struct cm_state {
371         /* magic */
372         unsigned int magic;
373
374         /* list of cmedia devices */
375         struct list_head devs;
376
377         /* the corresponding pci_dev structure */
378         struct pci_dev *dev;
379
380         int dev_audio;                  /* soundcore stuff */
381         int dev_mixer;
382
383         unsigned int iosb, iobase, iosynth,
384                          iomidi, iogame, irq;   /* hardware resources */
385         unsigned short deviceid;                /* pci_id */
386
387         struct {                                /* mixer stuff */
388                 unsigned int modcnt;
389                 unsigned short vol[13];
390         } mix;
391
392         unsigned int rateadc, ratedac;          /* wave stuff */
393         unsigned char fmt, enable;
394
395         spinlock_t lock;
396         struct mutex open_mutex;
397         mode_t open_mode;
398         wait_queue_head_t open_wait;
399
400         struct dmabuf {
401                 void *rawbuf;
402                 dma_addr_t dmaaddr;
403                 unsigned buforder;
404                 unsigned numfrag;
405                 unsigned fragshift;
406                 unsigned hwptr, swptr;
407                 unsigned total_bytes;
408                 int count;
409                 unsigned error;         /* over/underrun */
410                 wait_queue_head_t wait;
411
412                 unsigned fragsize;      /* redundant, but makes calculations easier */
413                 unsigned dmasize;
414                 unsigned fragsamples;
415                 unsigned dmasamples;
416
417                 unsigned mapped:1;      /* OSS stuff */
418                 unsigned ready:1;
419                 unsigned endcleared:1;
420                 unsigned enabled:1;
421                 unsigned ossfragshift;
422                 int ossmaxfrags;
423                 unsigned subdivision;
424         } dma_dac, dma_adc;
425
426 #ifdef CONFIG_SOUND_CMPCI_MIDI
427         int midi_devc;
428         struct address_info mpu_data;
429 #endif
430 #ifdef CONFIG_SOUND_CMPCI_JOYSTICK
431         struct gameport *gameport;
432 #endif
433
434         int     chip_version;
435         int     max_channels;
436         int     curr_channels;
437         int     capability;             /* HW capability, various for chip versions */
438
439         int     status;                 /* HW or SW state */
440
441         int     spdif_counter;          /* spdif frame counter */
442 };
443
444 /* flags used for capability */
445 #define CAN_AC3_HW              0x00000001              /* 037 or later */
446 #define CAN_AC3_SW              0x00000002              /* 033 or later */
447 #define CAN_AC3                 (CAN_AC3_HW | CAN_AC3_SW)
448 #define CAN_DUAL_DAC            0x00000004              /* 033 or later */
449 #define CAN_MULTI_CH_HW         0x00000008              /* 039 or later */
450 #define CAN_MULTI_CH            (CAN_MULTI_CH_HW | CAN_DUAL_DAC)
451 #define CAN_LINE_AS_REAR        0x00000010              /* 033 or later */
452 #define CAN_LINE_AS_BASS        0x00000020              /* 039 or later */
453 #define CAN_MIC_AS_BASS         0x00000040              /* 039 or later */
454
455 /* flags used for status */
456 #define DO_AC3_HW               0x00000001
457 #define DO_AC3_SW               0x00000002
458 #define DO_AC3                  (DO_AC3_HW | DO_AC3_SW)
459 #define DO_DUAL_DAC             0x00000004
460 #define DO_MULTI_CH_HW          0x00000008
461 #define DO_MULTI_CH             (DO_MULTI_CH_HW | DO_DUAL_DAC)
462 #define DO_LINE_AS_REAR         0x00000010              /* 033 or later */
463 #define DO_LINE_AS_BASS         0x00000020              /* 039 or later */
464 #define DO_MIC_AS_BASS          0x00000040              /* 039 or later */
465 #define DO_SPDIF_OUT            0x00000100
466 #define DO_SPDIF_IN             0x00000200
467 #define DO_SPDIF_LOOP           0x00000400
468 #define DO_BIGENDIAN_W          0x00001000              /* used in PowerPC */
469 #define DO_BIGENDIAN_R          0x00002000              /* used in PowerPC */
470
471 static LIST_HEAD(devs);
472
473 static  int     mpuio;
474 static  int     fmio;
475 static  int     joystick;
476 static  int     spdif_inverse;
477 static  int     spdif_loop;
478 static  int     spdif_out;
479 static  int     use_line_as_rear;
480 static  int     use_line_as_bass;
481 static  int     use_mic_as_bass;
482 static  int     mic_boost;
483 static  int     hw_copy;
484 module_param(mpuio, int, 0);
485 module_param(fmio, int, 0);
486 module_param(joystick, bool, 0);
487 module_param(spdif_inverse, bool, 0);
488 module_param(spdif_loop, bool, 0);
489 module_param(spdif_out, bool, 0);
490 module_param(use_line_as_rear, bool, 0);
491 module_param(use_line_as_bass, bool, 0);
492 module_param(use_mic_as_bass, bool, 0);
493 module_param(mic_boost, bool, 0);
494 module_param(hw_copy, bool, 0);
495 MODULE_PARM_DESC(mpuio, "(0x330, 0x320, 0x310, 0x300) Base of MPU-401, 0 to disable");
496 MODULE_PARM_DESC(fmio, "(0x388, 0x3C8, 0x3E0) Base of OPL3, 0 to disable");
497 MODULE_PARM_DESC(joystick, "(1/0) Enable joystick interface, still need joystick driver");
498 MODULE_PARM_DESC(spdif_inverse, "(1/0) Invert S/PDIF-in signal");
499 MODULE_PARM_DESC(spdif_loop, "(1/0) Route S/PDIF-in to S/PDIF-out directly");
500 MODULE_PARM_DESC(spdif_out, "(1/0) Send PCM to S/PDIF-out (PCM volume will not function)");
501 MODULE_PARM_DESC(use_line_as_rear, "(1/0) Use line-in jack as rear-out");
502 MODULE_PARM_DESC(use_line_as_bass, "(1/0) Use line-in jack as bass/center");
503 MODULE_PARM_DESC(use_mic_as_bass, "(1/0) Use mic-in jack as bass/center");
504 MODULE_PARM_DESC(mic_boost, "(1/0) Enable microphone boost");
505 MODULE_PARM_DESC(hw_copy, "Copy front channel to surround channel");
506
507 /* --------------------------------------------------------------------- */
508
509 static inline unsigned ld2(unsigned int x)
510 {
511         unsigned exp=16,l=5,r=0;
512         static const unsigned num[]={0x2,0x4,0x10,0x100,0x10000};
513
514         /* num: 2, 4, 16, 256, 65536 */
515         /* exp: 1, 2,  4,   8,    16 */
516
517         while(l--) {
518                 if( x >= num[l] ) {
519                         if(num[l]>2) x >>= exp;
520                         r+=exp;
521                 }
522                 exp>>=1;
523         }
524
525         return r;
526 }
527
528 /* --------------------------------------------------------------------- */
529
530 static void maskb(unsigned int addr, unsigned int mask, unsigned int value)
531 {
532         outb((inb(addr) & mask) | value, addr);
533 }
534
535 static void maskw(unsigned int addr, unsigned int mask, unsigned int value)
536 {
537         outw((inw(addr) & mask) | value, addr);
538 }
539
540 static void maskl(unsigned int addr, unsigned int mask, unsigned int value)
541 {
542         outl((inl(addr) & mask) | value, addr);
543 }
544
545 static void set_dmadac1(struct cm_state *s, unsigned int addr, unsigned int count)
546 {
547         if (addr)
548             outl(addr, s->iobase + CODEC_CMI_ADC_FRAME1);
549         outw(count - 1, s->iobase + CODEC_CMI_ADC_FRAME2);
550         maskb(s->iobase + CODEC_CMI_FUNCTRL0, ~CHADC0, 0);
551 }
552
553 static void set_dmaadc(struct cm_state *s, unsigned int addr, unsigned int count)
554 {
555         outl(addr, s->iobase + CODEC_CMI_ADC_FRAME1);
556         outw(count - 1, s->iobase + CODEC_CMI_ADC_FRAME2);
557         maskb(s->iobase + CODEC_CMI_FUNCTRL0, ~0, CHADC0);
558 }
559
560 static void set_dmadac(struct cm_state *s, unsigned int addr, unsigned int count)
561 {
562         outl(addr, s->iobase + CODEC_CMI_DAC_FRAME1);
563         outw(count - 1, s->iobase + CODEC_CMI_DAC_FRAME2);
564         maskb(s->iobase + CODEC_CMI_FUNCTRL0, ~CHADC1, 0);
565         if (s->status & DO_DUAL_DAC)
566                 set_dmadac1(s, 0, count);
567 }
568
569 static void set_countadc(struct cm_state *s, unsigned count)
570 {
571         outw(count - 1, s->iobase + CODEC_CMI_ADC_FRAME2 + 2);
572 }
573
574 static void set_countdac(struct cm_state *s, unsigned count)
575 {
576         outw(count - 1, s->iobase + CODEC_CMI_DAC_FRAME2 + 2);
577         if (s->status & DO_DUAL_DAC)
578             set_countadc(s, count);
579 }
580
581 static unsigned get_dmadac(struct cm_state *s)
582 {
583         unsigned int curr_addr;
584
585         curr_addr = inw(s->iobase + CODEC_CMI_DAC_FRAME2) + 1;
586         curr_addr <<= sample_shift[(s->fmt >> CM_CFMT_DACSHIFT) & CM_CFMT_MASK];
587         curr_addr = s->dma_dac.dmasize - curr_addr;
588
589         return curr_addr;
590 }
591
592 static unsigned get_dmaadc(struct cm_state *s)
593 {
594         unsigned int curr_addr;
595
596         curr_addr = inw(s->iobase + CODEC_CMI_ADC_FRAME2) + 1;
597         curr_addr <<= sample_shift[(s->fmt >> CM_CFMT_ADCSHIFT) & CM_CFMT_MASK];
598         curr_addr = s->dma_adc.dmasize - curr_addr;
599
600         return curr_addr;
601 }
602
603 static void wrmixer(struct cm_state *s, unsigned char idx, unsigned char data)
604 {
605         unsigned char regval, pseudo;
606
607         // pseudo register
608         if (idx == DSP_MIX_AUXVOL_L) {
609                 data >>= 4;
610                 data &= 0x0f;
611                 regval = inb(s->iobase + CODEC_CMI_AUX_VOL) & ~0x0f;
612                 outb(regval | data, s->iobase + CODEC_CMI_AUX_VOL);
613                 return;
614         }
615         if (idx == DSP_MIX_AUXVOL_R) {
616                 data &= 0xf0;
617                 regval = inb(s->iobase + CODEC_CMI_AUX_VOL) & ~0xf0;
618                 outb(regval | data, s->iobase + CODEC_CMI_AUX_VOL);
619                 return;
620         }
621         outb(idx, s->iobase + CODEC_SB16_ADDR);
622         udelay(10);
623         // pseudo bits
624         if (idx == DSP_MIX_OUTMIXIDX) {
625                 pseudo = data & ~0x1f;
626                 pseudo >>= 1;
627                 regval = inb(s->iobase + CODEC_CMI_MIXER2) & ~0x30;
628                 outb(regval | pseudo, s->iobase + CODEC_CMI_MIXER2);
629         }
630         if (idx == DSP_MIX_ADCMIXIDX_L) {
631                 pseudo = data & 0x80;
632                 pseudo >>= 1;
633                 regval = inb(s->iobase + CODEC_CMI_MIXER2) & ~0x40;
634                 outb(regval | pseudo, s->iobase + CODEC_CMI_MIXER2);
635         }
636         if (idx == DSP_MIX_ADCMIXIDX_R) {
637                 pseudo = data & 0x80;
638                 regval = inb(s->iobase + CODEC_CMI_MIXER2) & ~0x80;
639                 outb(regval | pseudo, s->iobase + CODEC_CMI_MIXER2);
640         }
641         outb(data, s->iobase + CODEC_SB16_DATA);
642         udelay(10);
643 }
644
645 static unsigned char rdmixer(struct cm_state *s, unsigned char idx)
646 {
647         unsigned char v, pseudo;
648
649         // pseudo register
650         if (idx == DSP_MIX_AUXVOL_L) {
651                 v = inb(s->iobase + CODEC_CMI_AUX_VOL) & 0x0f;
652                 v <<= 4;
653                 return v;
654         }
655         if (idx == DSP_MIX_AUXVOL_L) {
656                 v = inb(s->iobase + CODEC_CMI_AUX_VOL) & 0xf0;
657                 return v;
658         }
659         outb(idx, s->iobase + CODEC_SB16_ADDR);
660         udelay(10);
661         v = inb(s->iobase + CODEC_SB16_DATA);
662         udelay(10);
663         // pseudo bits
664         if (idx == DSP_MIX_OUTMIXIDX) {
665                 pseudo = inb(s->iobase + CODEC_CMI_MIXER2) & 0x30;
666                 pseudo <<= 1;
667                 v |= pseudo;
668         }
669         if (idx == DSP_MIX_ADCMIXIDX_L) {
670                 pseudo = inb(s->iobase + CODEC_CMI_MIXER2) & 0x40;
671                 pseudo <<= 1;
672                 v |= pseudo;
673         }
674         if (idx == DSP_MIX_ADCMIXIDX_R) {
675                 pseudo = inb(s->iobase + CODEC_CMI_MIXER2) & 0x80;
676                 v |= pseudo;
677         }
678         return v;
679 }
680
681 static void set_fmt_unlocked(struct cm_state *s, unsigned char mask, unsigned char data)
682 {
683         if (mask && s->chip_version > 0) {      /* 8338 cannot keep this */
684                 s->fmt = inb(s->iobase + CODEC_CMI_CHFORMAT);
685                 udelay(10);
686         }
687         s->fmt = (s->fmt & mask) | data;
688         outb(s->fmt, s->iobase + CODEC_CMI_CHFORMAT);
689         udelay(10);
690 }
691
692 static void set_fmt(struct cm_state *s, unsigned char mask, unsigned char data)
693 {
694         unsigned long flags;
695
696         spin_lock_irqsave(&s->lock, flags);
697         set_fmt_unlocked(s,mask,data);
698         spin_unlock_irqrestore(&s->lock, flags);
699 }
700
701 static void frobindir(struct cm_state *s, unsigned char idx, unsigned char mask, unsigned char data)
702 {
703         outb(idx, s->iobase + CODEC_SB16_ADDR);
704         udelay(10);
705         outb((inb(s->iobase + CODEC_SB16_DATA) & mask) | data, s->iobase + CODEC_SB16_DATA);
706         udelay(10);
707 }
708
709 static struct {
710         unsigned        rate;
711         unsigned        lower;
712         unsigned        upper;
713         unsigned char   freq;
714 } rate_lookup[] =
715 {
716         { 5512,         (0 + 5512) / 2,         (5512 + 8000) / 2,      0 },
717         { 8000,         (5512 + 8000) / 2,      (8000 + 11025) / 2,     4 },
718         { 11025,        (8000 + 11025) / 2,     (11025 + 16000) / 2,    1 },
719         { 16000,        (11025 + 16000) / 2,    (16000 + 22050) / 2,    5 },
720         { 22050,        (16000 + 22050) / 2,    (22050 + 32000) / 2,    2 },
721         { 32000,        (22050 + 32000) / 2,    (32000 + 44100) / 2,    6 },
722         { 44100,        (32000 + 44100) / 2,    (44100 + 48000) / 2,    3 },
723         { 48000,        (44100 + 48000) / 2,    48000,                  7 }
724 };
725
726 static void set_spdif_copyright(struct cm_state *s, int spdif_copyright)
727 {
728         /* enable SPDIF-in Copyright */
729         maskb(s->iobase + CODEC_CMI_LEGACY_CTRL + 2, ~SPDCOPYRHT, spdif_copyright ? SPDCOPYRHT : 0);
730 }
731
732 static void set_spdif_loop(struct cm_state *s, int spdif_loop)
733 {
734         /* enable SPDIF loop */
735         if (spdif_loop) {
736                 s->status |= DO_SPDIF_LOOP;
737                 /* turn on spdif-in to spdif-out */
738                 maskb(s->iobase + CODEC_CMI_FUNCTRL1, ~0, SPDFLOOP);
739         } else {
740                 s->status &= ~DO_SPDIF_LOOP;
741                 /* turn off spdif-in to spdif-out */
742                 maskb(s->iobase + CODEC_CMI_FUNCTRL1, ~SPDFLOOP, 0);
743         }
744 }
745
746 static void set_spdif_monitor(struct cm_state *s, int channel)
747 {
748         // SPDO2DAC
749         maskw(s->iobase + CODEC_CMI_FUNCTRL1, ~SPDO2DAC, channel == 2 ? SPDO2DAC : 0);
750         // CDPLAY
751         if (s->chip_version >= 39)
752                 maskb(s->iobase + CODEC_CMI_MIXER1, ~CDPLAY, channel ? CDPLAY : 0);
753 }
754
755 static void set_spdifout_level(struct cm_state *s, int level5v)
756 {
757         /* SPDO5V */
758         if (s->chip_version > 0)
759                 maskb(s->iobase + CODEC_CMI_MISC_CTRL + 3, ~SPDO5V, level5v ? SPDO5V : 0);
760 }
761
762 static void set_spdifin_inverse(struct cm_state *s, int spdif_inverse)
763 {
764         if (s->chip_version == 0)       /* 8338 has not this feature */
765                 return;
766         if (spdif_inverse) {
767                 /* turn on spdif-in inverse */
768                 if (s->chip_version >= 39)
769                         maskb(s->iobase + CODEC_CMI_CHFORMAT, ~0, INVSPDIFI);
770                 else
771                         maskb(s->iobase + CODEC_CMI_CHFORMAT + 2, ~0, 1);
772         } else {
773                 /* turn off spdif-ininverse */
774                 if (s->chip_version >= 39)
775                         maskb(s->iobase + CODEC_CMI_CHFORMAT, ~INVSPDIFI, 0);
776                 else
777                         maskb(s->iobase + CODEC_CMI_CHFORMAT + 2, ~1, 0);
778         }
779 }
780
781 static void set_spdifin_channel2(struct cm_state *s, int channel2)
782 {
783         /* SELSPDIFI2 */
784         if (s->chip_version >= 39)
785                 maskb(s->iobase + CODEC_CMI_MISC_CTRL + 1, ~SELSPDIFI2, channel2 ? SELSPDIFI2 : 0);
786 }
787
788 static void set_spdifin_valid(struct cm_state *s, int valid)
789 {
790         /* SPDVALID */
791         maskb(s->iobase + CODEC_CMI_MISC, ~SPDVALID, valid ? SPDVALID : 0);
792 }
793
794 static void set_spdifout_unlocked(struct cm_state *s, unsigned rate)
795 {
796         if (rate != 48000 && rate != 44100)
797                 rate = 0;
798         if (rate == 48000 || rate == 44100) {
799                 set_spdif_loop(s, 0);
800                 // SPDF_1
801                 maskb(s->iobase + CODEC_CMI_FUNCTRL1 + 1, ~0, SPDF_1);
802                 // SPDIFI48K SPDF_AC97
803                 maskl(s->iobase + CODEC_CMI_MISC_CTRL, ~SPDIF48K, rate == 48000 ? SPDIF48K : 0);
804                 if (s->chip_version >= 55)
805                 // SPD32KFMT
806                         maskb(s->iobase + CODEC_CMI_MISC_CTRL2, ~SPD32KFMT, rate == 48000 ? SPD32KFMT : 0);
807                 if (s->chip_version > 0)
808                 // ENSPDOUT
809                         maskb(s->iobase + CODEC_CMI_LEGACY_CTRL + 2, ~0, ENSPDOUT);
810                 // monitor SPDIF out
811                 set_spdif_monitor(s, 2);
812                 s->status |= DO_SPDIF_OUT;
813         } else {
814                 maskb(s->iobase + CODEC_CMI_FUNCTRL1 + 1, ~SPDF_1, 0);
815                 maskb(s->iobase + CODEC_CMI_LEGACY_CTRL + 2, ~ENSPDOUT, 0);
816                 // monitor none
817                 set_spdif_monitor(s, 0);
818                 s->status &= ~DO_SPDIF_OUT;
819         }
820 }
821
822 static void set_spdifout(struct cm_state *s, unsigned rate)
823 {
824         unsigned long flags;
825
826         spin_lock_irqsave(&s->lock, flags);
827         set_spdifout_unlocked(s,rate);
828         spin_unlock_irqrestore(&s->lock, flags);
829 }
830
831 static void set_spdifin_unlocked(struct cm_state *s, unsigned rate)
832 {
833         if (rate == 48000 || rate == 44100) {
834                 // SPDF_1
835                 maskb(s->iobase + CODEC_CMI_FUNCTRL1 + 1, ~0, SPDF_1);
836                 // SPDIFI48K SPDF_AC97
837                 maskl(s->iobase + CODEC_CMI_MISC_CTRL, ~SPDIF48K, rate == 48000 ? SPDIF48K : 0);
838                 s->status |= DO_SPDIF_IN;
839         } else {
840                 maskb(s->iobase + CODEC_CMI_FUNCTRL1 + 1, ~SPDF_1, 0);
841                 s->status &= ~DO_SPDIF_IN;
842         }
843 }
844
845 static void set_spdifin(struct cm_state *s, unsigned rate)
846 {
847         unsigned long flags;
848
849         spin_lock_irqsave(&s->lock, flags);
850         set_spdifin_unlocked(s,rate);
851         spin_unlock_irqrestore(&s->lock, flags);
852 }
853
854 /* find parity for bit 4~30 */
855 static unsigned parity(unsigned data)
856 {
857         unsigned parity = 0;
858         int counter = 4;
859
860         data >>= 4;     // start from bit 4
861         while (counter <= 30) {
862                 if (data & 1)
863                         parity++;
864                 data >>= 1;
865                 counter++;
866         }
867         return parity & 1;
868 }
869
870 static void set_ac3_unlocked(struct cm_state *s, unsigned rate)
871 {
872         if (!(s->capability & CAN_AC3))
873                 return;
874         /* enable AC3 */
875         if (rate && rate != 44100)
876                 rate = 48000;
877         if (rate == 48000 || rate == 44100) {
878                 // mute DAC
879                 maskb(s->iobase + CODEC_CMI_MIXER1, ~0, WSMUTE);
880                 if (s->chip_version >= 39)
881                         maskb(s->iobase + CODEC_CMI_MISC_CTRL, ~0, MUTECH1);
882                 // AC3EN for 039, 0x04
883                 if (s->chip_version >= 39) {
884                         maskb(s->iobase + CODEC_CMI_MISC_CTRL + 2, ~0, AC3_EN);
885                         if (s->chip_version == 55)
886                                 maskb(s->iobase + CODEC_CMI_SPDIF_CTRL, ~2, 0);
887                 // AC3EN for 037, 0x10
888                 } else if (s->chip_version == 37)
889                         maskb(s->iobase + CODEC_CMI_CHFORMAT + 2, ~0, 0x10);
890                 if (s->capability & CAN_AC3_HW) {
891                         // SPD24SEL for 039, 0x20, but cannot be set
892                         if (s->chip_version == 39)
893                                 maskb(s->iobase + CODEC_CMI_CHFORMAT + 2, ~0, SPD24SEL);
894                         // SPD24SEL for 037, 0x02
895                         else if (s->chip_version == 37)
896                                 maskb(s->iobase + CODEC_CMI_CHFORMAT + 2, ~0, 0x02);
897                         if (s->chip_version >= 39)
898                                 maskb(s->iobase + CODEC_CMI_MIXER1, ~CDPLAY, 0);
899
900                         s->status |= DO_AC3_HW;
901                  } else {
902                         // SPD32SEL for 037 & 039
903                         maskb(s->iobase + CODEC_CMI_MISC_CTRL + 2, ~0, SPD32SEL);
904                         // set 176K sample rate to fix 033 HW bug
905                         if (s->chip_version == 33) {
906                                 if (rate == 48000)
907                                         maskb(s->iobase + CODEC_CMI_CHFORMAT + 1, ~0, 0x08);
908                                 else
909                                         maskb(s->iobase + CODEC_CMI_CHFORMAT + 1, ~0x08, 0);
910                         }
911                         s->status |= DO_AC3_SW;
912                 }
913         } else {
914                 maskb(s->iobase + CODEC_CMI_MIXER1, ~WSMUTE, 0);
915                 if (s->chip_version >= 39)
916                         maskb(s->iobase + CODEC_CMI_MISC_CTRL, ~MUTECH1, 0);
917                 maskb(s->iobase + CODEC_CMI_CHFORMAT + 2, ~(SPD24SEL|0x12), 0);
918                 maskb(s->iobase + CODEC_CMI_MISC_CTRL + 2, ~(SPD32SEL|AC3_EN), 0);
919                 if (s->chip_version == 33)
920                         maskb(s->iobase + CODEC_CMI_CHFORMAT + 1, ~0x08, 0);
921                 if (s->chip_version >= 39)
922                         maskb(s->iobase + CODEC_CMI_MIXER1, ~0, CDPLAY);
923                 s->status &= ~DO_AC3;
924         }
925         s->spdif_counter = 0;
926 }
927
928 static void set_line_as_rear(struct cm_state *s, int use_line_as_rear)
929 {
930         if (!(s->capability & CAN_LINE_AS_REAR))
931                 return;
932         if (use_line_as_rear) {
933                 maskb(s->iobase + CODEC_CMI_MIXER1, ~0, SPK4);
934                 s->status |= DO_LINE_AS_REAR;
935         } else {
936                 maskb(s->iobase + CODEC_CMI_MIXER1, ~SPK4, 0);
937                 s->status &= ~DO_LINE_AS_REAR;
938         }
939 }
940
941 static void set_line_as_bass(struct cm_state *s, int use_line_as_bass)
942 {
943         if (!(s->capability & CAN_LINE_AS_BASS))
944                 return;
945         if (use_line_as_bass) {
946                 maskb(s->iobase + CODEC_CMI_LEGACY_CTRL + 1, ~0, CB2LIN);
947                 s->status |= DO_LINE_AS_BASS;
948         } else {
949                 maskb(s->iobase + CODEC_CMI_LEGACY_CTRL + 1, ~CB2LIN, 0);
950                 s->status &= ~DO_LINE_AS_BASS;
951         }
952 }
953
954 static void set_mic_as_bass(struct cm_state *s, int use_mic_as_bass)
955 {
956         if (!(s->capability & CAN_MIC_AS_BASS))
957                 return;
958         if (use_mic_as_bass) {
959                 maskb(s->iobase + CODEC_CMI_MISC, ~0, 0x04);
960                 s->status |= DO_MIC_AS_BASS;
961         } else {
962                 maskb(s->iobase + CODEC_CMI_MISC, ~0x04, 0);
963                 s->status &= ~DO_MIC_AS_BASS;
964         }
965 }
966
967 static void set_hw_copy(struct cm_state *s, int hw_copy)
968 {
969         if (s->max_channels > 2 && hw_copy)
970                 maskb(s->iobase + CODEC_CMI_MISC_CTRL + 3, ~0, N4SPK3D);
971         else
972                 maskb(s->iobase + CODEC_CMI_MISC_CTRL + 3, ~N4SPK3D, 0);
973 }
974
975 static void set_ac3(struct cm_state *s, unsigned rate)
976 {
977         unsigned long flags;
978
979         spin_lock_irqsave(&s->lock, flags);
980         set_spdifout_unlocked(s, rate);
981         set_ac3_unlocked(s, rate);
982         spin_unlock_irqrestore(&s->lock, flags);
983 }
984
985 static int trans_ac3(struct cm_state *s, void *dest, const char __user *source, int size)
986 {
987         int   i = size / 2;
988         unsigned long data;
989         unsigned short data16;
990         unsigned long *dst = (unsigned long *) dest;
991         unsigned short __user *src = (unsigned short __user *)source;
992         int err;
993
994         do {
995                 if ((err = __get_user(data16, src++)))
996                         return err;
997                 data = (unsigned long)le16_to_cpu(data16);
998                 data <<= 12;                    // ok for 16-bit data
999                 if (s->spdif_counter == 2 || s->spdif_counter == 3)
1000                         data |= 0x40000000;     // indicate AC-3 raw data
1001                 if (parity(data))
1002                         data |= 0x80000000;     // parity
1003                 if (s->spdif_counter == 0)
1004                         data |= 3;              // preamble 'M'
1005                 else if (s->spdif_counter & 1)
1006                         data |= 5;              // odd, 'W'
1007                 else
1008                         data |= 9;              // even, 'M'
1009                 *dst++ = cpu_to_le32(data);
1010                 s->spdif_counter++;
1011                 if (s->spdif_counter == 384)
1012                         s->spdif_counter = 0;
1013         } while (--i);
1014
1015         return 0;
1016 }
1017
1018 static void set_adc_rate_unlocked(struct cm_state *s, unsigned rate)
1019 {
1020         unsigned char freq = 4;
1021         int     i;
1022
1023         if (rate > 48000)
1024                 rate = 48000;
1025         if (rate < 8000)
1026                 rate = 8000;
1027         for (i = 0; i < sizeof(rate_lookup) / sizeof(rate_lookup[0]); i++) {
1028                 if (rate > rate_lookup[i].lower && rate <= rate_lookup[i].upper) {
1029                         rate = rate_lookup[i].rate;
1030                         freq = rate_lookup[i].freq;
1031                         break;
1032                 }
1033         }
1034         s->rateadc = rate;
1035         freq <<= CM_FREQ_ADCSHIFT;
1036
1037         maskb(s->iobase + CODEC_CMI_FUNCTRL1 + 1, ~ASFC, freq);
1038 }
1039
1040 static void set_adc_rate(struct cm_state *s, unsigned rate)
1041 {
1042         unsigned long flags;
1043         unsigned char freq = 4;
1044         int     i;
1045
1046         if (rate > 48000)
1047                 rate = 48000;
1048         if (rate < 8000)
1049                 rate = 8000;
1050         for (i = 0; i < sizeof(rate_lookup) / sizeof(rate_lookup[0]); i++) {
1051                 if (rate > rate_lookup[i].lower && rate <= rate_lookup[i].upper) {
1052                         rate = rate_lookup[i].rate;
1053                         freq = rate_lookup[i].freq;
1054                         break;
1055                 }
1056         }
1057         s->rateadc = rate;
1058         freq <<= CM_FREQ_ADCSHIFT;
1059
1060         spin_lock_irqsave(&s->lock, flags);
1061         maskb(s->iobase + CODEC_CMI_FUNCTRL1 + 1, ~ASFC, freq);
1062         spin_unlock_irqrestore(&s->lock, flags);
1063 }
1064
1065 static void set_dac_rate(struct cm_state *s, unsigned rate)
1066 {
1067         unsigned long flags;
1068         unsigned char freq = 4;
1069         int     i;
1070
1071         if (rate > 48000)
1072                 rate = 48000;
1073         if (rate < 8000)
1074                 rate = 8000;
1075         for (i = 0; i < sizeof(rate_lookup) / sizeof(rate_lookup[0]); i++) {
1076                 if (rate > rate_lookup[i].lower && rate <= rate_lookup[i].upper) {
1077                         rate = rate_lookup[i].rate;
1078                         freq = rate_lookup[i].freq;
1079                         break;
1080                 }
1081         }
1082         s->ratedac = rate;
1083         freq <<= CM_FREQ_DACSHIFT;
1084
1085         spin_lock_irqsave(&s->lock, flags);
1086         maskb(s->iobase + CODEC_CMI_FUNCTRL1 + 1, ~DSFC, freq);
1087         spin_unlock_irqrestore(&s->lock, flags);
1088
1089         if (s->curr_channels <= 2 && spdif_out)
1090                 set_spdifout(s, rate);
1091         if (s->status & DO_DUAL_DAC)
1092                 set_dac1_rate(s, rate);
1093 }
1094
1095 /* --------------------------------------------------------------------- */
1096 static inline void reset_adc(struct cm_state *s)
1097 {
1098         /* reset bus master */
1099         outb(s->enable | RSTADC, s->iobase + CODEC_CMI_FUNCTRL0 + 2);
1100         udelay(10);
1101         outb(s->enable & ~RSTADC, s->iobase + CODEC_CMI_FUNCTRL0 + 2);
1102 }
1103
1104 static inline void reset_dac(struct cm_state *s)
1105 {
1106         /* reset bus master */
1107         outb(s->enable | RSTDAC, s->iobase + CODEC_CMI_FUNCTRL0 + 2);
1108         udelay(10);
1109         outb(s->enable & ~RSTDAC, s->iobase + CODEC_CMI_FUNCTRL0 + 2);
1110         if (s->status & DO_DUAL_DAC)
1111                 reset_adc(s);
1112 }
1113
1114 static inline void pause_adc(struct cm_state *s)
1115 {
1116         maskb(s->iobase + CODEC_CMI_FUNCTRL0, ~0, PAUSEADC);
1117 }
1118
1119 static inline void pause_dac(struct cm_state *s)
1120 {
1121         maskb(s->iobase + CODEC_CMI_FUNCTRL0, ~0, PAUSEDAC);
1122         if (s->status & DO_DUAL_DAC)
1123                 pause_adc(s);
1124 }
1125
1126 static inline void disable_adc(struct cm_state *s)
1127 {
1128         /* disable channel */
1129         s->enable &= ~ENADC;
1130         outb(s->enable, s->iobase + CODEC_CMI_FUNCTRL0 + 2);
1131         reset_adc(s);
1132 }
1133
1134 static inline void disable_dac(struct cm_state *s)
1135 {
1136         /* disable channel */
1137         s->enable &= ~ENDAC;
1138         outb(s->enable, s->iobase + CODEC_CMI_FUNCTRL0 + 2);
1139         reset_dac(s);
1140         if (s->status & DO_DUAL_DAC)
1141                 disable_adc(s);
1142 }
1143
1144 static inline void enable_adc(struct cm_state *s)
1145 {
1146         if (!(s->enable & ENADC)) {
1147                 /* enable channel */
1148                 s->enable |= ENADC;
1149                 outb(s->enable, s->iobase + CODEC_CMI_FUNCTRL0 + 2);
1150         }
1151         maskb(s->iobase + CODEC_CMI_FUNCTRL0, ~PAUSEADC, 0);
1152 }
1153
1154 static inline void enable_dac_unlocked(struct cm_state *s)
1155 {
1156         if (!(s->enable & ENDAC)) {
1157                 /* enable channel */
1158                 s->enable |= ENDAC;
1159                 outb(s->enable, s->iobase + CODEC_CMI_FUNCTRL0 + 2);
1160         }
1161         maskb(s->iobase + CODEC_CMI_FUNCTRL0, ~PAUSEDAC, 0);
1162
1163         if (s->status & DO_DUAL_DAC)
1164                 enable_adc(s);
1165 }
1166
1167 static inline void stop_adc_unlocked(struct cm_state *s)
1168 {
1169         if (s->enable & ENADC) {
1170                 /* disable interrupt */
1171                 maskb(s->iobase + CODEC_CMI_INT_HLDCLR + 2, ~ENADCINT, 0);
1172                 disable_adc(s);
1173         }
1174 }
1175
1176 static inline void stop_adc(struct cm_state *s)
1177 {
1178         unsigned long flags;
1179
1180         spin_lock_irqsave(&s->lock, flags);
1181         stop_adc_unlocked(s);
1182         spin_unlock_irqrestore(&s->lock, flags);
1183
1184 }
1185
1186 static inline void stop_dac_unlocked(struct cm_state *s)
1187 {
1188         if (s->enable & ENDAC) {
1189                 /* disable interrupt */
1190                 maskb(s->iobase + CODEC_CMI_INT_HLDCLR + 2, ~ENDACINT, 0);
1191                 disable_dac(s);
1192         }
1193         if (s->status & DO_DUAL_DAC)
1194                 stop_dac1_unlocked(s);
1195 }
1196
1197 static inline void stop_dac(struct cm_state *s)
1198 {
1199         unsigned long flags;
1200
1201         spin_lock_irqsave(&s->lock, flags);
1202         stop_dac_unlocked(s);
1203         spin_unlock_irqrestore(&s->lock, flags);
1204 }
1205
1206 static inline void start_adc_unlocked(struct cm_state *s)
1207 {
1208         if ((s->dma_adc.mapped || s->dma_adc.count < (signed)(s->dma_adc.dmasize - 2*s->dma_adc.fragsize))
1209             && s->dma_adc.ready) {
1210                 /* enable interrupt */
1211                 maskb(s->iobase + CODEC_CMI_INT_HLDCLR + 2, ~0, ENADCINT);
1212                 enable_adc(s);
1213         }
1214 }
1215
1216 static void start_adc(struct cm_state *s)
1217 {
1218         unsigned long flags;
1219
1220         spin_lock_irqsave(&s->lock, flags);
1221         start_adc_unlocked(s);
1222         spin_unlock_irqrestore(&s->lock, flags);
1223 }
1224
1225 static void start_dac1_unlocked(struct cm_state *s)
1226 {
1227         if ((s->dma_adc.mapped || s->dma_adc.count > 0) && s->dma_adc.ready) {
1228                 /* enable interrupt */
1229                 maskb(s->iobase + CODEC_CMI_INT_HLDCLR + 2, ~0, ENADCINT);
1230                 enable_dac_unlocked(s);
1231         }
1232 }
1233
1234 static void start_dac_unlocked(struct cm_state *s)
1235 {
1236         if ((s->dma_dac.mapped || s->dma_dac.count > 0) && s->dma_dac.ready) {
1237                 /* enable interrupt */
1238                 maskb(s->iobase + CODEC_CMI_INT_HLDCLR + 2, ~0, ENDACINT);
1239                 enable_dac_unlocked(s);
1240         }
1241         if (s->status & DO_DUAL_DAC)
1242                 start_dac1_unlocked(s);
1243 }
1244
1245 static void start_dac(struct cm_state *s)
1246 {
1247         unsigned long flags;
1248
1249         spin_lock_irqsave(&s->lock, flags);
1250         start_dac_unlocked(s);
1251         spin_unlock_irqrestore(&s->lock, flags);
1252 }
1253
1254 static int prog_dmabuf(struct cm_state *s, unsigned rec);
1255
1256 static int set_dac_channels(struct cm_state *s, int channels)
1257 {
1258         unsigned long flags;
1259         static unsigned int fmmute = 0;
1260
1261         spin_lock_irqsave(&s->lock, flags);
1262
1263         if ((channels > 2) && (channels <= s->max_channels)
1264          && (((s->fmt >> CM_CFMT_DACSHIFT) & CM_CFMT_MASK) == (CM_CFMT_STEREO | CM_CFMT_16BIT))) {
1265             set_spdifout_unlocked(s, 0);
1266             if (s->capability & CAN_MULTI_CH_HW) {
1267                 // NXCHG
1268                 maskb(s->iobase + CODEC_CMI_LEGACY_CTRL + 3, ~0, NXCHG);
1269                 // CHB3D or CHB3D5C
1270                 maskb(s->iobase + CODEC_CMI_CHFORMAT + 3, ~(CHB3D5C|CHB3D), channels > 4 ? CHB3D5C : CHB3D);
1271                 // CHB3D6C
1272                 maskb(s->iobase + CODEC_CMI_LEGACY_CTRL + 1, ~CHB3D6C, channels == 6 ? CHB3D6C : 0);
1273                 // ENCENTER
1274                 maskb(s->iobase + CODEC_CMI_MISC_CTRL, ~ENCENTER, channels == 6 ? ENCENTER : 0);
1275                 s->status |= DO_MULTI_CH_HW;
1276             } else if (s->capability & CAN_DUAL_DAC) {
1277                 unsigned char fmtm = ~0, fmts = 0;
1278                 ssize_t ret;
1279
1280                 // ENDBDAC, turn on double DAC mode
1281                 // XCHGDAC, CH0 -> back, CH1->front
1282                 maskb(s->iobase + CODEC_CMI_MISC_CTRL + 2, ~0, ENDBDAC|XCHGDAC);
1283                 // mute FM
1284                 fmmute = inb(s->iobase + CODEC_CMI_MIXER1) & FMMUTE;
1285                 maskb(s->iobase + CODEC_CMI_MIXER1, ~0, FMMUTE);
1286                 s->status |= DO_DUAL_DAC;
1287                 // prepare secondary buffer
1288                 spin_unlock_irqrestore(&s->lock, flags);
1289                 ret = prog_dmabuf(s, 1);
1290                 if (ret) return ret;
1291                 spin_lock_irqsave(&s->lock, flags);
1292
1293                 // copy the hw state
1294                 fmtm &= ~((CM_CFMT_STEREO | CM_CFMT_16BIT) << CM_CFMT_DACSHIFT);
1295                 fmtm &= ~((CM_CFMT_STEREO | CM_CFMT_16BIT) << CM_CFMT_ADCSHIFT);
1296                 // the HW only support 16-bit stereo
1297                 fmts |= CM_CFMT_16BIT << CM_CFMT_DACSHIFT;
1298                 fmts |= CM_CFMT_16BIT << CM_CFMT_ADCSHIFT;
1299                 fmts |= CM_CFMT_STEREO << CM_CFMT_DACSHIFT;
1300                 fmts |= CM_CFMT_STEREO << CM_CFMT_ADCSHIFT;
1301
1302                 set_fmt_unlocked(s, fmtm, fmts);
1303                 set_adc_rate_unlocked(s, s->ratedac);
1304             }
1305             // disable 4 speaker mode (analog duplicate)
1306             set_hw_copy(s, 0);
1307             s->curr_channels = channels;
1308
1309             // enable jack redirect
1310             set_line_as_rear(s, use_line_as_rear);
1311             if (channels > 4) {
1312                     set_line_as_bass(s, use_line_as_bass);
1313                     set_mic_as_bass(s, use_mic_as_bass);
1314             }
1315         } else {
1316             if (s->status & DO_MULTI_CH_HW) {
1317                 maskb(s->iobase + CODEC_CMI_LEGACY_CTRL + 3, ~NXCHG, 0);
1318                 maskb(s->iobase + CODEC_CMI_CHFORMAT + 3, ~(CHB3D5C|CHB3D), 0);
1319                 maskb(s->iobase + CODEC_CMI_LEGACY_CTRL + 1, ~CHB3D6C, 0);
1320             } else if (s->status & DO_DUAL_DAC) {
1321                 maskb(s->iobase + CODEC_CMI_MISC_CTRL + 2, ~ENDBDAC, 0);
1322                 maskb(s->iobase + CODEC_CMI_MIXER1, ~FMMUTE, fmmute);
1323             }
1324             // enable 4 speaker mode (analog duplicate)
1325             set_hw_copy(s, hw_copy);
1326             s->status &= ~DO_MULTI_CH;
1327             s->curr_channels = s->fmt & (CM_CFMT_STEREO << CM_CFMT_DACSHIFT) ? 2 : 1;
1328             // disable jack redirect
1329             set_line_as_rear(s, hw_copy ? use_line_as_rear : 0);
1330             set_line_as_bass(s, 0);
1331             set_mic_as_bass(s, 0);
1332         }
1333         spin_unlock_irqrestore(&s->lock, flags);
1334         return s->curr_channels;
1335 }
1336
1337 /* --------------------------------------------------------------------- */
1338
1339 #define DMABUF_DEFAULTORDER (16-PAGE_SHIFT)
1340 #define DMABUF_MINORDER 1
1341
1342 static void dealloc_dmabuf(struct cm_state *s, struct dmabuf *db)
1343 {
1344         struct page *pstart, *pend;
1345
1346         if (db->rawbuf) {
1347                 /* undo marking the pages as reserved */
1348                 pend = virt_to_page(db->rawbuf + (PAGE_SIZE << db->buforder) - 1);
1349                 for (pstart = virt_to_page(db->rawbuf); pstart <= pend; pstart++)
1350                         ClearPageReserved(pstart);
1351                 pci_free_consistent(s->dev, PAGE_SIZE << db->buforder, db->rawbuf, db->dmaaddr);
1352         }
1353         db->rawbuf = NULL;
1354         db->mapped = db->ready = 0;
1355 }
1356
1357 /* Ch1 is used for playback, Ch0 is used for recording */
1358
1359 static int prog_dmabuf(struct cm_state *s, unsigned rec)
1360 {
1361         struct dmabuf *db = rec ? &s->dma_adc : &s->dma_dac;
1362         unsigned rate = rec ? s->rateadc : s->ratedac;
1363         int order;
1364         unsigned bytepersec;
1365         unsigned bufs;
1366         struct page *pstart, *pend;
1367         unsigned char fmt;
1368         unsigned long flags;
1369
1370         fmt = s->fmt;
1371         if (rec) {
1372                 stop_adc(s);
1373                 fmt >>= CM_CFMT_ADCSHIFT;
1374         } else {
1375                 stop_dac(s);
1376                 fmt >>= CM_CFMT_DACSHIFT;
1377         }
1378
1379         fmt &= CM_CFMT_MASK;
1380         db->hwptr = db->swptr = db->total_bytes = db->count = db->error = db->endcleared = 0;
1381         if (!db->rawbuf) {
1382                 db->ready = db->mapped = 0;
1383                 for (order = DMABUF_DEFAULTORDER; order >= DMABUF_MINORDER; order--)
1384                         if ((db->rawbuf = pci_alloc_consistent(s->dev, PAGE_SIZE << order, &db->dmaaddr)))
1385                                 break;
1386                 if (!db->rawbuf || !db->dmaaddr)
1387                         return -ENOMEM;
1388                 db->buforder = order;
1389                 /* now mark the pages as reserved; otherwise remap_pfn_range doesn't do what we want */
1390                 pend = virt_to_page(db->rawbuf + (PAGE_SIZE << db->buforder) - 1);
1391                 for (pstart = virt_to_page(db->rawbuf); pstart <= pend; pstart++)
1392                         SetPageReserved(pstart);
1393         }
1394         bytepersec = rate << sample_shift[fmt];
1395         bufs = PAGE_SIZE << db->buforder;
1396         if (db->ossfragshift) {
1397                 if ((1000 << db->ossfragshift) < bytepersec)
1398                         db->fragshift = ld2(bytepersec/1000);
1399                 else
1400                         db->fragshift = db->ossfragshift;
1401         } else {
1402                 db->fragshift = ld2(bytepersec/100/(db->subdivision ? db->subdivision : 1));
1403                 if (db->fragshift < 3)
1404                         db->fragshift = 3;
1405         }
1406         db->numfrag = bufs >> db->fragshift;
1407         while (db->numfrag < 4 && db->fragshift > 3) {
1408                 db->fragshift--;
1409                 db->numfrag = bufs >> db->fragshift;
1410         }
1411         db->fragsize = 1 << db->fragshift;
1412         if (db->ossmaxfrags >= 4 && db->ossmaxfrags < db->numfrag)
1413                 db->numfrag = db->ossmaxfrags;
1414         /* to make fragsize >= 4096 */
1415         db->fragsamples = db->fragsize >> sample_shift[fmt];
1416         db->dmasize = db->numfrag << db->fragshift;
1417         db->dmasamples = db->dmasize >> sample_shift[fmt];
1418         memset(db->rawbuf, (fmt & CM_CFMT_16BIT) ? 0 : 0x80, db->dmasize);
1419         spin_lock_irqsave(&s->lock, flags);
1420         if (rec) {
1421                 if (s->status & DO_DUAL_DAC)
1422                     set_dmadac1(s, db->dmaaddr, db->dmasize >> sample_shift[fmt]);
1423                 else
1424                     set_dmaadc(s, db->dmaaddr, db->dmasize >> sample_shift[fmt]);
1425                 /* program sample counts */
1426                 set_countdac(s, db->fragsamples);
1427         } else {
1428                 set_dmadac(s, db->dmaaddr, db->dmasize >> sample_shift[fmt]);
1429                 /* program sample counts */
1430                 set_countdac(s, db->fragsamples);
1431         }
1432         spin_unlock_irqrestore(&s->lock, flags);
1433         db->enabled = 1;
1434         db->ready = 1;
1435         return 0;
1436 }
1437
1438 static inline void clear_advance(struct cm_state *s)
1439 {
1440         unsigned char c = (s->fmt & (CM_CFMT_16BIT << CM_CFMT_DACSHIFT)) ? 0 : 0x80;
1441         unsigned char *buf = s->dma_dac.rawbuf;
1442         unsigned char *buf1 = s->dma_adc.rawbuf;
1443         unsigned bsize = s->dma_dac.dmasize;
1444         unsigned bptr = s->dma_dac.swptr;
1445         unsigned len = s->dma_dac.fragsize;
1446
1447         if (bptr + len > bsize) {
1448                 unsigned x = bsize - bptr;
1449                 memset(buf + bptr, c, x);
1450                 if (s->status & DO_DUAL_DAC)
1451                         memset(buf1 + bptr, c, x);
1452                 bptr = 0;
1453                 len -= x;
1454         }
1455         memset(buf + bptr, c, len);
1456         if (s->status & DO_DUAL_DAC)
1457                 memset(buf1 + bptr, c, len);
1458 }
1459
1460 /* call with spinlock held! */
1461 static void cm_update_ptr(struct cm_state *s)
1462 {
1463         unsigned hwptr;
1464         int diff;
1465
1466         /* update ADC pointer */
1467         if (s->dma_adc.ready) {
1468             if (s->status & DO_DUAL_DAC) {
1469                     /* the dac part will finish for this */
1470             } else {
1471                 hwptr = get_dmaadc(s) % s->dma_adc.dmasize;
1472                 diff = (s->dma_adc.dmasize + hwptr - s->dma_adc.hwptr) % s->dma_adc.dmasize;
1473                 s->dma_adc.hwptr = hwptr;
1474                 s->dma_adc.total_bytes += diff;
1475                 s->dma_adc.count += diff;
1476                 if (s->dma_adc.count >= (signed)s->dma_adc.fragsize)
1477                         wake_up(&s->dma_adc.wait);
1478                 if (!s->dma_adc.mapped) {
1479                         if (s->dma_adc.count > (signed)(s->dma_adc.dmasize - ((3 * s->dma_adc.fragsize) >> 1))) {
1480                                 pause_adc(s);
1481                                 s->dma_adc.error++;
1482                         }
1483                 }
1484             }
1485         }
1486         /* update DAC pointer */
1487         if (s->dma_dac.ready) {
1488                 hwptr = get_dmadac(s) % s->dma_dac.dmasize;
1489                 diff = (s->dma_dac.dmasize + hwptr - s->dma_dac.hwptr) % s->dma_dac.dmasize;
1490                 s->dma_dac.hwptr = hwptr;
1491                 s->dma_dac.total_bytes += diff;
1492                 if (s->status & DO_DUAL_DAC) {
1493                         s->dma_adc.hwptr = hwptr;
1494                         s->dma_adc.total_bytes += diff;
1495                 }
1496                 if (s->dma_dac.mapped) {
1497                         s->dma_dac.count += diff;
1498                         if (s->status & DO_DUAL_DAC)
1499                                 s->dma_adc.count += diff;
1500                         if (s->dma_dac.count >= (signed)s->dma_dac.fragsize)
1501                                 wake_up(&s->dma_dac.wait);
1502                 } else {
1503                         s->dma_dac.count -= diff;
1504                         if (s->status & DO_DUAL_DAC)
1505                                 s->dma_adc.count -= diff;
1506                         if (s->dma_dac.count <= 0) {
1507                                 pause_dac(s);
1508                                 s->dma_dac.error++;
1509                         } else if (s->dma_dac.count <= (signed)s->dma_dac.fragsize && !s->dma_dac.endcleared) {
1510                                 clear_advance(s);
1511                                 s->dma_dac.endcleared = 1;
1512                                 if (s->status & DO_DUAL_DAC)
1513                                         s->dma_adc.endcleared = 1;
1514                         }
1515                         if (s->dma_dac.count + (signed)s->dma_dac.fragsize <= (signed)s->dma_dac.dmasize)
1516                                 wake_up(&s->dma_dac.wait);
1517                 }
1518         }
1519 }
1520
1521 static irqreturn_t cm_interrupt(int irq, void *dev_id, struct pt_regs *regs)
1522 {
1523         struct cm_state *s = (struct cm_state *)dev_id;
1524         unsigned int intsrc, intstat;
1525         unsigned char mask = 0;
1526
1527         /* fastpath out, to ease interrupt sharing */
1528         intsrc = inl(s->iobase + CODEC_CMI_INT_STATUS);
1529         if (!(intsrc & 0x80000000))
1530                 return IRQ_NONE;
1531         spin_lock(&s->lock);
1532         intstat = inb(s->iobase + CODEC_CMI_INT_HLDCLR + 2);
1533         /* acknowledge interrupt */
1534         if (intsrc & ADCINT)
1535                 mask |= ENADCINT;
1536         if (intsrc & DACINT)
1537                 mask |= ENDACINT;
1538         outb(intstat & ~mask, s->iobase + CODEC_CMI_INT_HLDCLR + 2);
1539         outb(intstat | mask, s->iobase + CODEC_CMI_INT_HLDCLR + 2);
1540         cm_update_ptr(s);
1541         spin_unlock(&s->lock);
1542 #ifdef CONFIG_SOUND_CMPCI_MIDI
1543         if (intsrc & 0x00010000) {      // UART interrupt
1544                 if (s->midi_devc && intchk_mpu401((void *)s->midi_devc))
1545                         mpuintr(irq, (void *)s->midi_devc, regs);
1546                 else
1547                         inb(s->iomidi);// dummy read
1548         }
1549 #endif
1550         return IRQ_HANDLED;
1551 }
1552
1553 /* --------------------------------------------------------------------- */
1554
1555 static const char invalid_magic[] = KERN_CRIT "cmpci: invalid magic value\n";
1556
1557 #define VALIDATE_STATE(s)                         \
1558 ({                                                \
1559         if (!(s) || (s)->magic != CM_MAGIC) { \
1560                 printk(invalid_magic);            \
1561                 return -ENXIO;                    \
1562         }                                         \
1563 })
1564
1565 /* --------------------------------------------------------------------- */
1566
1567 #define MT_4          1
1568 #define MT_5MUTE      2
1569 #define MT_4MUTEMONO  3
1570 #define MT_6MUTE      4
1571 #define MT_5MUTEMONO  5
1572
1573 static const struct {
1574         unsigned left;
1575         unsigned right;
1576         unsigned type;
1577         unsigned rec;
1578         unsigned play;
1579 } mixtable[SOUND_MIXER_NRDEVICES] = {
1580         [SOUND_MIXER_CD]     = { DSP_MIX_CDVOLIDX_L,     DSP_MIX_CDVOLIDX_R,     MT_5MUTE,     0x04, 0x06 },
1581         [SOUND_MIXER_LINE]   = { DSP_MIX_LINEVOLIDX_L,   DSP_MIX_LINEVOLIDX_R,   MT_5MUTE,     0x10, 0x18 },
1582         [SOUND_MIXER_MIC]    = { DSP_MIX_MICVOLIDX,      DSP_MIX_MICVOLIDX,      MT_5MUTEMONO, 0x01, 0x01 },
1583         [SOUND_MIXER_SYNTH]  = { DSP_MIX_FMVOLIDX_L,     DSP_MIX_FMVOLIDX_R,     MT_5MUTE,     0x40, 0x00 },
1584         [SOUND_MIXER_VOLUME] = { DSP_MIX_MASTERVOLIDX_L, DSP_MIX_MASTERVOLIDX_R, MT_5MUTE,     0x00, 0x00 },
1585         [SOUND_MIXER_PCM]    = { DSP_MIX_VOICEVOLIDX_L,  DSP_MIX_VOICEVOLIDX_R,  MT_5MUTE,     0x00, 0x00 },
1586         [SOUND_MIXER_LINE1]  = { DSP_MIX_AUXVOL_L,       DSP_MIX_AUXVOL_R,       MT_5MUTE,     0x80, 0x60 },
1587         [SOUND_MIXER_SPEAKER]= { DSP_MIX_SPKRVOLIDX,     DSP_MIX_SPKRVOLIDX,     MT_5MUTEMONO, 0x00, 0x01 }
1588 };
1589
1590 static const unsigned char volidx[SOUND_MIXER_NRDEVICES] =
1591 {
1592         [SOUND_MIXER_CD]     = 1,
1593         [SOUND_MIXER_LINE]   = 2,
1594         [SOUND_MIXER_MIC]    = 3,
1595         [SOUND_MIXER_SYNTH]  = 4,
1596         [SOUND_MIXER_VOLUME] = 5,
1597         [SOUND_MIXER_PCM]    = 6,
1598         [SOUND_MIXER_LINE1]  = 7,
1599         [SOUND_MIXER_SPEAKER]= 8
1600 };
1601
1602 static unsigned mixer_outmask(struct cm_state *s)
1603 {
1604         unsigned long flags;
1605         int i, j, k;
1606
1607         spin_lock_irqsave(&s->lock, flags);
1608         j = rdmixer(s, DSP_MIX_OUTMIXIDX);
1609         spin_unlock_irqrestore(&s->lock, flags);
1610         for (k = i = 0; i < SOUND_MIXER_NRDEVICES; i++)
1611                 if (j & mixtable[i].play)
1612                         k |= 1 << i;
1613         return k;
1614 }
1615
1616 static unsigned mixer_recmask(struct cm_state *s)
1617 {
1618         unsigned long flags;
1619         int i, j, k;
1620
1621         spin_lock_irqsave(&s->lock, flags);
1622         j = rdmixer(s, DSP_MIX_ADCMIXIDX_L);
1623         spin_unlock_irqrestore(&s->lock, flags);
1624         for (k = i = 0; i < SOUND_MIXER_NRDEVICES; i++)
1625                 if (j & mixtable[i].rec)
1626                         k |= 1 << i;
1627         return k;
1628 }
1629
1630 static int mixer_ioctl(struct cm_state *s, unsigned int cmd, unsigned long arg)
1631 {
1632         unsigned long flags;
1633         int i, val, j;
1634         unsigned char l, r, rl, rr;
1635         void __user *argp = (void __user *)arg;
1636         int __user *p = argp;
1637
1638         VALIDATE_STATE(s);
1639         if (cmd == SOUND_MIXER_INFO) {
1640                 mixer_info info;
1641                 memset(&info, 0, sizeof(info));
1642                 strlcpy(info.id, "cmpci", sizeof(info.id));
1643                 strlcpy(info.name, "C-Media PCI", sizeof(info.name));
1644                 info.modify_counter = s->mix.modcnt;
1645                 if (copy_to_user(argp, &info, sizeof(info)))
1646                         return -EFAULT;
1647                 return 0;
1648         }
1649         if (cmd == SOUND_OLD_MIXER_INFO) {
1650                 _old_mixer_info info;
1651                 memset(&info, 0, sizeof(info));
1652                 strlcpy(info.id, "cmpci", sizeof(info.id));
1653                 strlcpy(info.name, "C-Media cmpci", sizeof(info.name));
1654                 if (copy_to_user(argp, &info, sizeof(info)))
1655                         return -EFAULT;
1656                 return 0;
1657         }
1658         if (cmd == OSS_GETVERSION)
1659                 return put_user(SOUND_VERSION, p);
1660         if (_IOC_TYPE(cmd) != 'M' || _SIOC_SIZE(cmd) != sizeof(int))
1661                 return -EINVAL;
1662         if (_SIOC_DIR(cmd) == _SIOC_READ) {
1663                 switch (_IOC_NR(cmd)) {
1664                 case SOUND_MIXER_RECSRC: /* Arg contains a bit for each recording source */
1665                         val = mixer_recmask(s);
1666                         return put_user(val, p);
1667
1668                 case SOUND_MIXER_OUTSRC: /* Arg contains a bit for each recording source */
1669                         val = mixer_outmask(s);
1670                         return put_user(val, p);
1671
1672                 case SOUND_MIXER_DEVMASK: /* Arg contains a bit for each supported device */
1673                         for (val = i = 0; i < SOUND_MIXER_NRDEVICES; i++)
1674                                 if (mixtable[i].type)
1675                                         val |= 1 << i;
1676                         return put_user(val, p);
1677
1678                 case SOUND_MIXER_RECMASK: /* Arg contains a bit for each supported recording source */
1679                         for (val = i = 0; i < SOUND_MIXER_NRDEVICES; i++)
1680                                 if (mixtable[i].rec)
1681                                         val |= 1 << i;
1682                         return put_user(val, p);
1683
1684                 case SOUND_MIXER_OUTMASK: /* Arg contains a bit for each supported recording source */
1685                         for (val = i = 0; i < SOUND_MIXER_NRDEVICES; i++)
1686                                 if (mixtable[i].play)
1687                                         val |= 1 << i;
1688                         return put_user(val, p);
1689
1690                  case SOUND_MIXER_STEREODEVS: /* Mixer channels supporting stereo */
1691                         for (val = i = 0; i < SOUND_MIXER_NRDEVICES; i++)
1692                                 if (mixtable[i].type && mixtable[i].type != MT_4MUTEMONO)
1693                                         val |= 1 << i;
1694                         return put_user(val, p);
1695
1696                 case SOUND_MIXER_CAPS:
1697                         return put_user(0, p);
1698
1699                 default:
1700                         i = _IOC_NR(cmd);
1701                         if (i >= SOUND_MIXER_NRDEVICES || !mixtable[i].type)
1702                                 return -EINVAL;
1703                         if (!volidx[i])
1704                                 return -EINVAL;
1705                         return put_user(s->mix.vol[volidx[i]-1], p);
1706                 }
1707         }
1708         if (_SIOC_DIR(cmd) != (_SIOC_READ|_SIOC_WRITE))
1709                 return -EINVAL;
1710         s->mix.modcnt++;
1711         switch (_IOC_NR(cmd)) {
1712         case SOUND_MIXER_RECSRC: /* Arg contains a bit for each recording source */
1713                 if (get_user(val, p))
1714                         return -EFAULT;
1715                 i = hweight32(val);
1716                 for (j = i = 0; i < SOUND_MIXER_NRDEVICES; i++) {
1717                         if (!(val & (1 << i)))
1718                                 continue;
1719                         if (!mixtable[i].rec) {
1720                                 val &= ~(1 << i);
1721                                 continue;
1722                         }
1723                         j |= mixtable[i].rec;
1724                 }
1725                 spin_lock_irqsave(&s->lock, flags);
1726                 wrmixer(s, DSP_MIX_ADCMIXIDX_L, j);
1727                 wrmixer(s, DSP_MIX_ADCMIXIDX_R, (j & 1) | (j>>1) | (j & 0x80));
1728                 spin_unlock_irqrestore(&s->lock, flags);
1729                 return 0;
1730
1731         case SOUND_MIXER_OUTSRC: /* Arg contains a bit for each recording source */
1732                 if (get_user(val, p))
1733                         return -EFAULT;
1734                 for (j = i = 0; i < SOUND_MIXER_NRDEVICES; i++) {
1735                         if (!(val & (1 << i)))
1736                                 continue;
1737                         if (!mixtable[i].play) {
1738                                 val &= ~(1 << i);
1739                                 continue;
1740                         }
1741                         j |= mixtable[i].play;
1742                 }
1743                 spin_lock_irqsave(&s->lock, flags);
1744                 wrmixer(s, DSP_MIX_OUTMIXIDX, j);
1745                 spin_unlock_irqrestore(&s->lock, flags);
1746                 return 0;
1747
1748         default:
1749                 i = _IOC_NR(cmd);
1750                 if (i >= SOUND_MIXER_NRDEVICES || !mixtable[i].type)
1751                         return -EINVAL;
1752                 if (get_user(val, p))
1753                         return -EFAULT;
1754                 l = val & 0xff;
1755                 r = (val >> 8) & 0xff;
1756                 if (l > 100)
1757                         l = 100;
1758                 if (r > 100)
1759                         r = 100;
1760                 spin_lock_irqsave(&s->lock, flags);
1761                 switch (mixtable[i].type) {
1762                 case MT_4:
1763                         if (l >= 10)
1764                                 l -= 10;
1765                         if (r >= 10)
1766                                 r -= 10;
1767                         frobindir(s, mixtable[i].left, 0xf0, l / 6);
1768                         frobindir(s, mixtable[i].right, 0xf0, l / 6);
1769                         break;
1770
1771                 case MT_4MUTEMONO:
1772                         rl = (l < 4 ? 0 : (l - 5) / 3) & 31;
1773                         rr = (rl >> 2) & 7;
1774                         wrmixer(s, mixtable[i].left, rl<<3);
1775                         if (i == SOUND_MIXER_MIC)
1776                                 maskb(s->iobase + CODEC_CMI_MIXER2, ~0x0e, rr<<1);
1777                         break;
1778
1779                 case MT_5MUTEMONO:
1780                         rl = l < 4 ? 0 : (l - 5) / 3;
1781                         wrmixer(s, mixtable[i].left, rl<<3);
1782                         l = rdmixer(s, DSP_MIX_OUTMIXIDX) & ~mixtable[i].play;
1783                         r = rl ? mixtable[i].play : 0;
1784                         wrmixer(s, DSP_MIX_OUTMIXIDX, l | r);
1785                         /* for recording */
1786                         if (i == SOUND_MIXER_MIC) {
1787                                 if (s->chip_version >= 37) {
1788                                         rr = rl >> 1;
1789                                         maskb(s->iobase + CODEC_CMI_MIXER2, ~0x0e, (rr&0x07)<<1);
1790                                         frobindir(s, DSP_MIX_EXTENSION, ~0x01, rr>>3);
1791                                 } else {
1792                                         rr = rl >> 2;
1793                                         maskb(s->iobase + CODEC_CMI_MIXER2, ~0x0e, rr<<1);
1794                                 }
1795                         }
1796                         break;
1797
1798                 case MT_5MUTE:
1799                         rl = l < 4 ? 0 : (l - 5) / 3;
1800                         rr = r < 4 ? 0 : (r - 5) / 3;
1801                         wrmixer(s, mixtable[i].left, rl<<3);
1802                         wrmixer(s, mixtable[i].right, rr<<3);
1803                         l = rdmixer(s, DSP_MIX_OUTMIXIDX);
1804                         l &= ~mixtable[i].play;
1805                         r = (rl|rr) ? mixtable[i].play : 0;
1806                         wrmixer(s, DSP_MIX_OUTMIXIDX, l | r);
1807                         break;
1808
1809                 case MT_6MUTE:
1810                         if (l < 6)
1811                                 rl = 0x00;
1812                         else
1813                                 rl = l * 2 / 3;
1814                         if (r < 6)
1815                                 rr = 0x00;
1816                         else
1817                                 rr = r * 2 / 3;
1818                         wrmixer(s, mixtable[i].left, rl);
1819                         wrmixer(s, mixtable[i].right, rr);
1820                         break;
1821                 }
1822                 spin_unlock_irqrestore(&s->lock, flags);
1823
1824                 if (!volidx[i])
1825                         return -EINVAL;
1826                 s->mix.vol[volidx[i]-1] = val;
1827                 return put_user(s->mix.vol[volidx[i]-1], p);
1828         }
1829 }
1830
1831 /* --------------------------------------------------------------------- */
1832
1833 static int cm_open_mixdev(struct inode *inode, struct file *file)
1834 {
1835         int minor = iminor(inode);
1836         struct list_head *list;
1837         struct cm_state *s;
1838
1839         for (list = devs.next; ; list = list->next) {
1840                 if (list == &devs)
1841                         return -ENODEV;
1842                 s = list_entry(list, struct cm_state, devs);
1843                 if (s->dev_mixer == minor)
1844                         break;
1845         }
1846         VALIDATE_STATE(s);
1847         file->private_data = s;
1848         return nonseekable_open(inode, file);
1849 }
1850
1851 static int cm_release_mixdev(struct inode *inode, struct file *file)
1852 {
1853         struct cm_state *s = (struct cm_state *)file->private_data;
1854
1855         VALIDATE_STATE(s);
1856         return 0;
1857 }
1858
1859 static int cm_ioctl_mixdev(struct inode *inode, struct file *file, unsigned int cmd, unsigned long arg)
1860 {
1861         return mixer_ioctl((struct cm_state *)file->private_data, cmd, arg);
1862 }
1863
1864 static /*const*/ struct file_operations cm_mixer_fops = {
1865         .owner   = THIS_MODULE,
1866         .llseek  = no_llseek,
1867         .ioctl   = cm_ioctl_mixdev,
1868         .open    = cm_open_mixdev,
1869         .release = cm_release_mixdev,
1870 };
1871
1872
1873 /* --------------------------------------------------------------------- */
1874
1875 static int drain_dac(struct cm_state *s, int nonblock)
1876 {
1877         DECLARE_WAITQUEUE(wait, current);
1878         unsigned long flags;
1879         int count, tmo;
1880
1881         if (s->dma_dac.mapped || !s->dma_dac.ready)
1882                 return 0;
1883         add_wait_queue(&s->dma_dac.wait, &wait);
1884         for (;;) {
1885                 __set_current_state(TASK_INTERRUPTIBLE);
1886                 spin_lock_irqsave(&s->lock, flags);
1887                 count = s->dma_dac.count;
1888                 spin_unlock_irqrestore(&s->lock, flags);
1889                 if (count <= 0)
1890                         break;
1891                 if (signal_pending(current))
1892                         break;
1893                 if (nonblock) {
1894                         remove_wait_queue(&s->dma_dac.wait, &wait);
1895                         set_current_state(TASK_RUNNING);
1896                         return -EBUSY;
1897                 }
1898                 tmo = 3 * HZ * (count + s->dma_dac.fragsize) / 2 / s->ratedac;
1899                 tmo >>= sample_shift[(s->fmt >> CM_CFMT_DACSHIFT) & CM_CFMT_MASK];
1900                 if (!schedule_timeout(tmo + 1))
1901                         DBG(printk(KERN_DEBUG "cmpci: dma timed out??\n");)
1902         }
1903         remove_wait_queue(&s->dma_dac.wait, &wait);
1904         set_current_state(TASK_RUNNING);
1905         if (signal_pending(current))
1906                 return -ERESTARTSYS;
1907         return 0;
1908 }
1909
1910 /* --------------------------------------------------------------------- */
1911
1912 static ssize_t cm_read(struct file *file, char __user *buffer, size_t count, loff_t *ppos)
1913 {
1914         struct cm_state *s = (struct cm_state *)file->private_data;
1915         DECLARE_WAITQUEUE(wait, current);
1916         ssize_t ret;
1917         unsigned long flags;
1918         unsigned swptr;
1919         int cnt;
1920
1921         VALIDATE_STATE(s);
1922         if (s->dma_adc.mapped)
1923                 return -ENXIO;
1924         if (!s->dma_adc.ready && (ret = prog_dmabuf(s, 1)))
1925                 return ret;
1926         if (!access_ok(VERIFY_WRITE, buffer, count))
1927                 return -EFAULT;
1928         ret = 0;
1929
1930         add_wait_queue(&s->dma_adc.wait, &wait);
1931         while (count > 0) {
1932                 spin_lock_irqsave(&s->lock, flags);
1933                 swptr = s->dma_adc.swptr;
1934                 cnt = s->dma_adc.dmasize-swptr;
1935                 if (s->dma_adc.count < cnt)
1936                         cnt = s->dma_adc.count;
1937                 if (cnt <= 0)
1938                         __set_current_state(TASK_INTERRUPTIBLE);
1939                 spin_unlock_irqrestore(&s->lock, flags);
1940                 if (cnt > count)
1941                         cnt = count;
1942                 if (cnt <= 0) {
1943                         if (s->dma_adc.enabled)
1944                                 start_adc(s);
1945                         if (file->f_flags & O_NONBLOCK) {
1946                                 if (!ret)
1947                                         ret = -EAGAIN;
1948                                 goto out;
1949                         }
1950                         if (!schedule_timeout(HZ)) {
1951                                 printk(KERN_DEBUG "cmpci: read: chip lockup? dmasz %u fragsz %u count %i hwptr %u swptr %u\n",
1952                                        s->dma_adc.dmasize, s->dma_adc.fragsize, s->dma_adc.count,
1953                                        s->dma_adc.hwptr, s->dma_adc.swptr);
1954                                 spin_lock_irqsave(&s->lock, flags);
1955                                 stop_adc_unlocked(s);
1956                                 set_dmaadc(s, s->dma_adc.dmaaddr, s->dma_adc.dmasamples);
1957                                 /* program sample counts */
1958                                 set_countadc(s, s->dma_adc.fragsamples);
1959                                 s->dma_adc.count = s->dma_adc.hwptr = s->dma_adc.swptr = 0;
1960                                 spin_unlock_irqrestore(&s->lock, flags);
1961                         }
1962                         if (signal_pending(current)) {
1963                                 if (!ret)
1964                                         ret = -ERESTARTSYS;
1965                                 goto out;
1966                         }
1967                         continue;
1968                 }
1969                 if (s->status & DO_BIGENDIAN_R) {
1970                         int     i, err;
1971                         unsigned char *src;
1972                         char __user *dst = buffer;
1973                         unsigned char data[2];
1974
1975                         src = (unsigned char *) (s->dma_adc.rawbuf + swptr);
1976                         // copy left/right sample at one time
1977                         for (i = 0; i < cnt / 2; i++) {
1978                                 data[0] = src[1];
1979                                 data[1] = src[0];
1980                                 if ((err = __put_user(data[0], dst++))) {
1981                                         ret = err;
1982                                         goto out;
1983                                 }
1984                                 if ((err = __put_user(data[1], dst++))) {
1985                                         ret = err;
1986                                         goto out;
1987                                 }
1988                                 src += 2;
1989                         }
1990                 } else if (copy_to_user(buffer, s->dma_adc.rawbuf + swptr, cnt)) {
1991                         if (!ret)
1992                                 ret = -EFAULT;
1993                         goto out;
1994                 }
1995                 swptr = (swptr + cnt) % s->dma_adc.dmasize;
1996                 spin_lock_irqsave(&s->lock, flags);
1997                 s->dma_adc.swptr = swptr;
1998                 s->dma_adc.count -= cnt;
1999                 count -= cnt;
2000                 buffer += cnt;
2001                 ret += cnt;
2002                 if (s->dma_adc.enabled)
2003                         start_adc_unlocked(s);
2004                 spin_unlock_irqrestore(&s->lock, flags);
2005         }
2006 out:
2007         remove_wait_queue(&s->dma_adc.wait, &wait);
2008         set_current_state(TASK_RUNNING);
2009         return ret;
2010 }
2011
2012 static ssize_t cm_write(struct file *file, const char __user *buffer, size_t count, loff_t *ppos)
2013 {
2014         struct cm_state *s = (struct cm_state *)file->private_data;
2015         DECLARE_WAITQUEUE(wait, current);
2016         ssize_t ret;
2017         unsigned long flags;
2018         unsigned swptr;
2019         int cnt;
2020
2021         VALIDATE_STATE(s);
2022         if (s->dma_dac.mapped)
2023                 return -ENXIO;
2024         if (!s->dma_dac.ready && (ret = prog_dmabuf(s, 0)))
2025                 return ret;
2026         if (!access_ok(VERIFY_READ, buffer, count))
2027                 return -EFAULT;
2028         if (s->status & DO_DUAL_DAC) {
2029                 if (s->dma_adc.mapped)
2030                         return -ENXIO;
2031                 if (!s->dma_adc.ready && (ret = prog_dmabuf(s, 1)))
2032                         return ret;
2033         }
2034         if (!access_ok(VERIFY_READ, buffer, count))
2035                 return -EFAULT;
2036         ret = 0;
2037
2038         add_wait_queue(&s->dma_dac.wait, &wait);
2039         while (count > 0) {
2040                 spin_lock_irqsave(&s->lock, flags);
2041                 if (s->dma_dac.count < 0) {
2042                         s->dma_dac.count = 0;
2043                         s->dma_dac.swptr = s->dma_dac.hwptr;
2044                 }
2045                 if (s->status & DO_DUAL_DAC) {
2046                         s->dma_adc.swptr = s->dma_dac.swptr;
2047                         s->dma_adc.count = s->dma_dac.count;
2048                         s->dma_adc.endcleared = s->dma_dac.endcleared;
2049                 }
2050                 swptr = s->dma_dac.swptr;
2051                 cnt = s->dma_dac.dmasize-swptr;
2052                 if (s->status & DO_AC3_SW) {
2053                         if (s->dma_dac.count + 2 * cnt > s->dma_dac.dmasize)
2054                                 cnt = (s->dma_dac.dmasize - s->dma_dac.count) / 2;
2055                 } else {
2056                         if (s->dma_dac.count + cnt > s->dma_dac.dmasize)
2057                                 cnt = s->dma_dac.dmasize - s->dma_dac.count;
2058                 }
2059                 if (cnt <= 0)
2060                         __set_current_state(TASK_INTERRUPTIBLE);
2061                 spin_unlock_irqrestore(&s->lock, flags);
2062                 if (cnt > count)
2063                         cnt = count;
2064                 if ((s->status & DO_DUAL_DAC) && (cnt > count / 2))
2065                     cnt = count / 2;
2066                 if (cnt <= 0) {
2067                         if (s->dma_dac.enabled)
2068                                 start_dac(s);
2069                         if (file->f_flags & O_NONBLOCK) {
2070                                 if (!ret)
2071                                         ret = -EAGAIN;
2072                                 goto out;
2073                         }
2074                         if (!schedule_timeout(HZ)) {
2075                                 printk(KERN_DEBUG "cmpci: write: chip lockup? dmasz %u fragsz %u count %i hwptr %u swptr %u\n",
2076                                        s->dma_dac.dmasize, s->dma_dac.fragsize, s->dma_dac.count,
2077                                        s->dma_dac.hwptr, s->dma_dac.swptr);
2078                                 spin_lock_irqsave(&s->lock, flags);
2079                                 stop_dac_unlocked(s);
2080                                 set_dmadac(s, s->dma_dac.dmaaddr, s->dma_dac.dmasamples);
2081                                 /* program sample counts */
2082                                 set_countdac(s, s->dma_dac.fragsamples);
2083                                 s->dma_dac.count = s->dma_dac.hwptr = s->dma_dac.swptr = 0;
2084                                 if (s->status & DO_DUAL_DAC)  {
2085                                         set_dmadac1(s, s->dma_adc.dmaaddr, s->dma_adc.dmasamples);
2086                                         s->dma_adc.count = s->dma_adc.hwptr = s->dma_adc.swptr = 0;
2087                                 }
2088                                 spin_unlock_irqrestore(&s->lock, flags);
2089                         }
2090                         if (signal_pending(current)) {
2091                                 if (!ret)
2092                                         ret = -ERESTARTSYS;
2093                                 goto out;
2094                         }
2095                         continue;
2096                 }
2097                 if (s->status & DO_AC3_SW) {
2098                         int err;
2099
2100                         // clip exceeded data, caught by 033 and 037
2101                         if (swptr + 2 * cnt > s->dma_dac.dmasize)
2102                                 cnt = (s->dma_dac.dmasize - swptr) / 2;
2103                         if ((err = trans_ac3(s, s->dma_dac.rawbuf + swptr, buffer, cnt))) {
2104                                 ret = err;
2105                                 goto out;
2106                         }
2107                         swptr = (swptr + 2 * cnt) % s->dma_dac.dmasize;
2108                 } else if ((s->status & DO_DUAL_DAC) && (s->status & DO_BIGENDIAN_W)) {
2109                         int     i, err;
2110                         const char __user *src = buffer;
2111                         unsigned char *dst0, *dst1;
2112                         unsigned char data[8];
2113
2114                         dst0 = (unsigned char *) (s->dma_dac.rawbuf + swptr);
2115                         dst1 = (unsigned char *) (s->dma_adc.rawbuf + swptr);
2116                         // copy left/right sample at one time
2117                         for (i = 0; i < cnt / 4; i++) {
2118                                 if ((err = __get_user(data[0], src++))) {
2119                                         ret = err;
2120                                         goto out;
2121                                 }
2122                                 if ((err = __get_user(data[1], src++))) {
2123                                         ret = err;
2124                                         goto out;
2125                                 }
2126                                 if ((err = __get_user(data[2], src++))) {
2127                                         ret = err;
2128                                         goto out;
2129                                 }
2130                                 if ((err = __get_user(data[3], src++))) {
2131                                         ret = err;
2132                                         goto out;
2133                                 }
2134                                 if ((err = __get_user(data[4], src++))) {
2135                                         ret = err;
2136                                         goto out;
2137                                 }
2138                                 if ((err = __get_user(data[5], src++))) {
2139                                         ret = err;
2140                                         goto out;
2141                                 }
2142                                 if ((err = __get_user(data[6], src++))) {
2143                                         ret = err;
2144                                         goto out;
2145                                 }
2146                                 if ((err = __get_user(data[7], src++))) {
2147                                         ret = err;
2148                                         goto out;
2149                                 }
2150                                 dst0[0] = data[1];
2151                                 dst0[1] = data[0];
2152                                 dst0[2] = data[3];
2153                                 dst0[3] = data[2];
2154                                 dst1[0] = data[5];
2155                                 dst1[1] = data[4];
2156                                 dst1[2] = data[7];
2157                                 dst1[3] = data[6];
2158                                 dst0 += 4;
2159                                 dst1 += 4;
2160                         }
2161                         swptr = (swptr + cnt) % s->dma_dac.dmasize;
2162                 } else if (s->status & DO_DUAL_DAC) {
2163                         int     i, err;
2164                         unsigned long __user *src = (unsigned long __user *) buffer;
2165                         unsigned long *dst0, *dst1;
2166
2167                         dst0 = (unsigned long *) (s->dma_dac.rawbuf + swptr);
2168                         dst1 = (unsigned long *) (s->dma_adc.rawbuf + swptr);
2169                         // copy left/right sample at one time
2170                         for (i = 0; i < cnt / 4; i++) {
2171                                 if ((err = __get_user(*dst0++, src++))) {
2172                                         ret = err;
2173                                         goto out;
2174                                 }
2175                                 if ((err = __get_user(*dst1++, src++))) {
2176                                         ret = err;
2177                                         goto out;
2178                                 }
2179                         }
2180                         swptr = (swptr + cnt) % s->dma_dac.dmasize;
2181                 } else if (s->status & DO_BIGENDIAN_W) {
2182                         int     i, err;
2183                         const char __user *src = buffer;
2184                         unsigned char *dst;
2185                         unsigned char data[2];
2186
2187                         dst = (unsigned char *) (s->dma_dac.rawbuf + swptr);
2188                         // swap hi/lo bytes for each sample
2189                         for (i = 0; i < cnt / 2; i++) {
2190                                 if ((err = __get_user(data[0], src++))) {
2191                                         ret = err;
2192                                         goto out;
2193                                 }
2194                                 if ((err = __get_user(data[1], src++))) {
2195                                         ret = err;
2196                                         goto out;
2197                                 }
2198                                 dst[0] = data[1];
2199                                 dst[1] = data[0];
2200                                 dst += 2;
2201                         }
2202                         swptr = (swptr + cnt) % s->dma_dac.dmasize;
2203                 } else {
2204                         if (copy_from_user(s->dma_dac.rawbuf + swptr, buffer, cnt)) {
2205                                 if (!ret)
2206                                         ret = -EFAULT;
2207                                 goto out;
2208                         }
2209                         swptr = (swptr + cnt) % s->dma_dac.dmasize;
2210                 }
2211                 spin_lock_irqsave(&s->lock, flags);
2212                 s->dma_dac.swptr = swptr;
2213                 s->dma_dac.count += cnt;
2214                 if (s->status & DO_AC3_SW)
2215                         s->dma_dac.count += cnt;
2216                 s->dma_dac.endcleared = 0;
2217                 spin_unlock_irqrestore(&s->lock, flags);
2218                 count -= cnt;
2219                 buffer += cnt;
2220                 ret += cnt;
2221                 if (s->status & DO_DUAL_DAC) {
2222                         count -= cnt;
2223                         buffer += cnt;
2224                         ret += cnt;
2225                 }
2226                 if (s->dma_dac.enabled)
2227                         start_dac(s);
2228         }
2229 out:
2230         remove_wait_queue(&s->dma_dac.wait, &wait);
2231         set_current_state(TASK_RUNNING);
2232         return ret;
2233 }
2234
2235 static unsigned int cm_poll(struct file *file, struct poll_table_struct *wait)
2236 {
2237         struct cm_state *s = (struct cm_state *)file->private_data;
2238         unsigned long flags;
2239         unsigned int mask = 0;
2240
2241         VALIDATE_STATE(s);
2242         if (file->f_mode & FMODE_WRITE) {
2243                 if (!s->dma_dac.ready && prog_dmabuf(s, 0))
2244                         return 0;
2245                 poll_wait(file, &s->dma_dac.wait, wait);
2246         }
2247         if (file->f_mode & FMODE_READ) {
2248                 if (!s->dma_adc.ready && prog_dmabuf(s, 1))
2249                         return 0;
2250                 poll_wait(file, &s->dma_adc.wait, wait);
2251         }
2252         spin_lock_irqsave(&s->lock, flags);
2253         cm_update_ptr(s);
2254         if (file->f_mode & FMODE_READ) {
2255                 if (s->dma_adc.count >= (signed)s->dma_adc.fragsize)
2256                         mask |= POLLIN | POLLRDNORM;
2257         }
2258         if (file->f_mode & FMODE_WRITE) {
2259                 if (s->dma_dac.mapped) {
2260                         if (s->dma_dac.count >= (signed)s->dma_dac.fragsize)
2261                                 mask |= POLLOUT | POLLWRNORM;
2262                 } else {
2263                         if ((signed)s->dma_dac.dmasize >= s->dma_dac.count + (signed)s->dma_dac.fragsize)
2264                                 mask |= POLLOUT | POLLWRNORM;
2265                 }
2266         }
2267         spin_unlock_irqrestore(&s->lock, flags);
2268         return mask;
2269 }
2270
2271 static int cm_mmap(struct file *file, struct vm_area_struct *vma)
2272 {
2273         struct cm_state *s = (struct cm_state *)file->private_data;
2274         struct dmabuf *db;
2275         int ret = -EINVAL;
2276         unsigned long size;
2277
2278         VALIDATE_STATE(s);
2279         lock_kernel();
2280         if (vma->vm_flags & VM_WRITE) {
2281                 if ((ret = prog_dmabuf(s, 0)) != 0)
2282                         goto out;
2283                 db = &s->dma_dac;
2284         } else if (vma->vm_flags & VM_READ) {
2285                 if ((ret = prog_dmabuf(s, 1)) != 0)
2286                         goto out;
2287                 db = &s->dma_adc;
2288         } else
2289                 goto out;
2290         ret = -EINVAL;
2291         if (vma->vm_pgoff != 0)
2292                 goto out;
2293         size = vma->vm_end - vma->vm_start;
2294         if (size > (PAGE_SIZE << db->buforder))
2295                 goto out;
2296         ret = -EINVAL;
2297         if (remap_pfn_range(vma, vma->vm_start,
2298                                 virt_to_phys(db->rawbuf) >> PAGE_SHIFT,
2299                                 size, vma->vm_page_prot))
2300                 goto out;
2301         db->mapped = 1;
2302         ret = 0;
2303 out:
2304         unlock_kernel();
2305         return ret;
2306 }
2307
2308 #define SNDCTL_SPDIF_COPYRIGHT  _SIOW('S',  0, int)       // set/reset S/PDIF copy protection
2309 #define SNDCTL_SPDIF_LOOP       _SIOW('S',  1, int)       // set/reset S/PDIF loop
2310 #define SNDCTL_SPDIF_MONITOR    _SIOW('S',  2, int)       // set S/PDIF monitor
2311 #define SNDCTL_SPDIF_LEVEL      _SIOW('S',  3, int)       // set/reset S/PDIF out level
2312 #define SNDCTL_SPDIF_INV        _SIOW('S',  4, int)       // set/reset S/PDIF in inverse
2313 #define SNDCTL_SPDIF_SEL2       _SIOW('S',  5, int)       // set S/PDIF in #2
2314 #define SNDCTL_SPDIF_VALID      _SIOW('S',  6, int)       // set S/PDIF valid
2315 #define SNDCTL_SPDIFOUT         _SIOW('S',  7, int)       // set S/PDIF out
2316 #define SNDCTL_SPDIFIN          _SIOW('S',  8, int)       // set S/PDIF out
2317
2318 static int cm_ioctl(struct inode *inode, struct file *file, unsigned int cmd, unsigned long arg)
2319 {
2320         struct cm_state *s = (struct cm_state *)file->private_data;
2321         unsigned long flags;
2322         audio_buf_info abinfo;
2323         count_info cinfo;
2324         int val, mapped, ret;
2325         unsigned char fmtm, fmtd;
2326         void __user *argp = (void __user *)arg;
2327         int __user *p = argp;
2328
2329         VALIDATE_STATE(s);
2330         mapped = ((file->f_mode & FMODE_WRITE) && s->dma_dac.mapped) ||
2331                 ((file->f_mode & FMODE_READ) && s->dma_adc.mapped);
2332         switch (cmd) {
2333         case OSS_GETVERSION:
2334                 return put_user(SOUND_VERSION, p);
2335
2336         case SNDCTL_DSP_SYNC:
2337                 if (file->f_mode & FMODE_WRITE)
2338                         return drain_dac(s, 0/*file->f_flags & O_NONBLOCK*/);
2339                 return 0;
2340
2341         case SNDCTL_DSP_SETDUPLEX:
2342                 return 0;
2343
2344         case SNDCTL_DSP_GETCAPS:
2345                 return put_user(DSP_CAP_DUPLEX | DSP_CAP_REALTIME | DSP_CAP_TRIGGER | DSP_CAP_MMAP | DSP_CAP_BIND, p);
2346
2347         case SNDCTL_DSP_RESET:
2348                 if (file->f_mode & FMODE_WRITE) {
2349                         stop_dac(s);
2350                         synchronize_irq(s->irq);
2351                         s->dma_dac.swptr = s->dma_dac.hwptr = s->dma_dac.count = s->dma_dac.total_bytes = 0;
2352                         if (s->status & DO_DUAL_DAC)
2353                                 s->dma_adc.swptr = s->dma_adc.hwptr = s->dma_adc.count = s->dma_adc.total_bytes = 0;
2354                 }
2355                 if (file->f_mode & FMODE_READ) {
2356                         stop_adc(s);
2357                         synchronize_irq(s->irq);
2358                         s->dma_adc.swptr = s->dma_adc.hwptr = s->dma_adc.count = s->dma_adc.total_bytes = 0;
2359                 }
2360                 return 0;
2361
2362         case SNDCTL_DSP_SPEED:
2363                 if (get_user(val, p))
2364                         return -EFAULT;
2365                 if (val >= 0) {
2366                         if (file->f_mode & FMODE_READ) {
2367                                 spin_lock_irqsave(&s->lock, flags);
2368                                 stop_adc_unlocked(s);
2369                                 s->dma_adc.ready = 0;
2370                                 set_adc_rate_unlocked(s, val);
2371                                 spin_unlock_irqrestore(&s->lock, flags);
2372                         }
2373                         if (file->f_mode & FMODE_WRITE) {
2374                                 stop_dac(s);
2375                                 s->dma_dac.ready = 0;
2376                                 if (s->status & DO_DUAL_DAC)
2377                                         s->dma_adc.ready = 0;
2378                                 set_dac_rate(s, val);
2379                         }
2380                 }
2381                 return put_user((file->f_mode & FMODE_READ) ? s->rateadc : s->ratedac, p);
2382
2383         case SNDCTL_DSP_STEREO:
2384                 if (get_user(val, p))
2385                         return -EFAULT;
2386                 fmtd = 0;
2387                 fmtm = ~0;
2388                 if (file->f_mode & FMODE_READ) {
2389                         stop_adc(s);
2390                         s->dma_adc.ready = 0;
2391                         if (val)
2392                                 fmtd |= CM_CFMT_STEREO << CM_CFMT_ADCSHIFT;
2393                         else
2394                                 fmtm &= ~(CM_CFMT_STEREO << CM_CFMT_ADCSHIFT);
2395                 }
2396                 if (file->f_mode & FMODE_WRITE) {
2397                         stop_dac(s);
2398                         s->dma_dac.ready = 0;
2399                         if (val)
2400                                 fmtd |= CM_CFMT_STEREO << CM_CFMT_DACSHIFT;
2401                         else
2402                                 fmtm &= ~(CM_CFMT_STEREO << CM_CFMT_DACSHIFT);
2403                         if (s->status & DO_DUAL_DAC) {
2404                                 s->dma_adc.ready = 0;
2405                                 if (val)
2406                                         fmtd |= CM_CFMT_STEREO << CM_CFMT_ADCSHIFT;
2407                                 else
2408                                         fmtm &= ~(CM_CFMT_STEREO << CM_CFMT_ADCSHIFT);
2409                         }
2410                 }
2411                 set_fmt(s, fmtm, fmtd);
2412                 return 0;
2413
2414         case SNDCTL_DSP_CHANNELS:
2415                 if (get_user(val, p))
2416                         return -EFAULT;
2417                 if (val != 0) {
2418                         fmtd = 0;
2419                         fmtm = ~0;
2420                         if (file->f_mode & FMODE_READ) {
2421                                 stop_adc(s);
2422                                 s->dma_adc.ready = 0;
2423                                 if (val >= 2)
2424                                         fmtd |= CM_CFMT_STEREO << CM_CFMT_ADCSHIFT;
2425                                 else
2426                                         fmtm &= ~(CM_CFMT_STEREO << CM_CFMT_ADCSHIFT);
2427                         }
2428                         if (file->f_mode & FMODE_WRITE) {
2429                                 stop_dac(s);
2430                                 s->dma_dac.ready = 0;
2431                                 if (val >= 2)
2432                                         fmtd |= CM_CFMT_STEREO << CM_CFMT_DACSHIFT;
2433                                 else
2434                                         fmtm &= ~(CM_CFMT_STEREO << CM_CFMT_DACSHIFT);
2435                                 if (s->status & DO_DUAL_DAC) {
2436                                         s->dma_adc.ready = 0;
2437                                         if (val >= 2)
2438                                                 fmtd |= CM_CFMT_STEREO << CM_CFMT_ADCSHIFT;
2439                                         else
2440                                                 fmtm &= ~(CM_CFMT_STEREO << CM_CFMT_ADCSHIFT);
2441                                 }
2442                         }
2443                         set_fmt(s, fmtm, fmtd);
2444                         if ((s->capability & CAN_MULTI_CH)
2445                              && (file->f_mode & FMODE_WRITE)) {
2446                                 val = set_dac_channels(s, val);
2447                                 return put_user(val, p);
2448                         }
2449                 }
2450                 return put_user((s->fmt & ((file->f_mode & FMODE_READ) ? (CM_CFMT_STEREO << CM_CFMT_ADCSHIFT)
2451                                            : (CM_CFMT_STEREO << CM_CFMT_DACSHIFT))) ? 2 : 1, p);
2452
2453         case SNDCTL_DSP_GETFMTS: /* Returns a mask */
2454                 return put_user(AFMT_S16_BE|AFMT_S16_LE|AFMT_U8|
2455                         ((s->capability & CAN_AC3) ? AFMT_AC3 : 0), p);
2456
2457         case SNDCTL_DSP_SETFMT: /* Selects ONE fmt*/
2458                 if (get_user(val, p))
2459                         return -EFAULT;
2460                 if (val != AFMT_QUERY) {
2461                         fmtd = 0;
2462                         fmtm = ~0;
2463                         if (file->f_mode & FMODE_READ) {
2464                                 stop_adc(s);
2465                                 s->dma_adc.ready = 0;
2466                                 if (val == AFMT_S16_BE || val == AFMT_S16_LE)
2467                                         fmtd |= CM_CFMT_16BIT << CM_CFMT_ADCSHIFT;
2468                                 else
2469                                         fmtm &= ~(CM_CFMT_16BIT << CM_CFMT_ADCSHIFT);
2470                                 if (val == AFMT_S16_BE)
2471                                         s->status |= DO_BIGENDIAN_R;
2472                                 else
2473                                         s->status &= ~DO_BIGENDIAN_R;
2474                         }
2475                         if (file->f_mode & FMODE_WRITE) {
2476                                 stop_dac(s);
2477                                 s->dma_dac.ready = 0;
2478                                 if (val == AFMT_S16_BE || val == AFMT_S16_LE || val == AFMT_AC3)
2479                                         fmtd |= CM_CFMT_16BIT << CM_CFMT_DACSHIFT;
2480                                 else
2481                                         fmtm &= ~(CM_CFMT_16BIT << CM_CFMT_DACSHIFT);
2482                                 if (val == AFMT_AC3) {
2483                                         fmtd |= CM_CFMT_STEREO << CM_CFMT_DACSHIFT;
2484                                         set_ac3(s, 48000);
2485                                 } else
2486                                         set_ac3(s, 0);
2487                                 if (s->status & DO_DUAL_DAC) {
2488                                         s->dma_adc.ready = 0;
2489                                         if (val == AFMT_S16_BE || val == AFMT_S16_LE)
2490                                                 fmtd |= CM_CFMT_STEREO << CM_CFMT_ADCSHIFT;
2491                                         else
2492                                                 fmtm &= ~(CM_CFMT_STEREO << CM_CFMT_ADCSHIFT);
2493                                 }
2494                                 if (val == AFMT_S16_BE)
2495                                         s->status |= DO_BIGENDIAN_W;
2496                                 else
2497                                         s->status &= ~DO_BIGENDIAN_W;
2498                         }
2499                         set_fmt(s, fmtm, fmtd);
2500                 }
2501                 if (s->status & DO_AC3) return put_user(AFMT_AC3, p);
2502                 return put_user((s->fmt & ((file->f_mode & FMODE_READ) ? (CM_CFMT_16BIT << CM_CFMT_ADCSHIFT)
2503                                            : (CM_CFMT_16BIT << CM_CFMT_DACSHIFT))) ? val : AFMT_U8, p);
2504
2505         case SNDCTL_DSP_POST:
2506                 return 0;
2507
2508         case SNDCTL_DSP_GETTRIGGER:
2509                 val = 0;
2510                 if (s->status & DO_DUAL_DAC) {
2511                         if (file->f_mode & FMODE_WRITE &&
2512                          (s->enable & ENDAC) &&
2513                          (s->enable & ENADC))
2514                                 val |= PCM_ENABLE_OUTPUT;
2515                         return put_user(val, p);
2516                 }
2517                 if (file->f_mode & FMODE_READ && s->enable & ENADC)
2518                         val |= PCM_ENABLE_INPUT;
2519                 if (file->f_mode & FMODE_WRITE && s->enable & ENDAC)
2520                         val |= PCM_ENABLE_OUTPUT;
2521                 return put_user(val, p);
2522
2523         case SNDCTL_DSP_SETTRIGGER:
2524                 if (get_user(val, p))
2525                         return -EFAULT;
2526                 if (file->f_mode & FMODE_READ) {
2527                         if (val & PCM_ENABLE_INPUT) {
2528                                 if (!s->dma_adc.ready && (ret = prog_dmabuf(s, 1)))
2529                                         return ret;
2530                                 s->dma_adc.enabled = 1;
2531                                 start_adc(s);
2532                         } else {
2533                                 s->dma_adc.enabled = 0;
2534                                 stop_adc(s);
2535                         }
2536                 }
2537                 if (file->f_mode & FMODE_WRITE) {
2538                         if (val & PCM_ENABLE_OUTPUT) {
2539                                 if (!s->dma_dac.ready && (ret = prog_dmabuf(s, 0)))
2540                                         return ret;
2541                                 if (s->status & DO_DUAL_DAC) {
2542                                         if (!s->dma_adc.ready && (ret = prog_dmabuf(s, 1)))
2543                                                 return ret;
2544                                 }
2545                                 s->dma_dac.enabled = 1;
2546                                 start_dac(s);
2547                         } else {
2548                                 s->dma_dac.enabled = 0;
2549                                 stop_dac(s);
2550                         }
2551                 }
2552                 return 0;
2553
2554         case SNDCTL_DSP_GETOSPACE:
2555                 if (!(file->f_mode & FMODE_WRITE))
2556                         return -EINVAL;
2557                 if (!(s->enable & ENDAC) && (val = prog_dmabuf(s, 0)) != 0)
2558                         return val;
2559                 spin_lock_irqsave(&s->lock, flags);
2560                 cm_update_ptr(s);
2561                 abinfo.fragsize = s->dma_dac.fragsize;
2562                 abinfo.bytes = s->dma_dac.dmasize - s->dma_dac.count;
2563                 abinfo.fragstotal = s->dma_dac.numfrag;
2564                 abinfo.fragments = abinfo.bytes >> s->dma_dac.fragshift;
2565                 spin_unlock_irqrestore(&s->lock, flags);
2566                 return copy_to_user(argp, &abinfo, sizeof(abinfo)) ? -EFAULT : 0;
2567
2568         case SNDCTL_DSP_GETISPACE:
2569                 if (!(file->f_mode & FMODE_READ))
2570                         return -EINVAL;
2571                 if (!(s->enable & ENADC) && (val = prog_dmabuf(s, 1)) != 0)
2572                         return val;
2573                 spin_lock_irqsave(&s->lock, flags);
2574                 cm_update_ptr(s);
2575                 abinfo.fragsize = s->dma_adc.fragsize;
2576                 abinfo.bytes = s->dma_adc.count;
2577                 abinfo.fragstotal = s->dma_adc.numfrag;
2578                 abinfo.fragments = abinfo.bytes >> s->dma_adc.fragshift;
2579                 spin_unlock_irqrestore(&s->lock, flags);
2580                 return copy_to_user(argp, &abinfo, sizeof(abinfo)) ? -EFAULT : 0;
2581
2582         case SNDCTL_DSP_NONBLOCK:
2583                 file->f_flags |= O_NONBLOCK;
2584                 return 0;
2585
2586         case SNDCTL_DSP_GETODELAY:
2587                 if (!(file->f_mode & FMODE_WRITE))
2588                         return -EINVAL;
2589                 spin_lock_irqsave(&s->lock, flags);
2590                 cm_update_ptr(s);
2591                 val = s->dma_dac.count;
2592                 spin_unlock_irqrestore(&s->lock, flags);
2593                 return put_user(val, p);
2594
2595         case SNDCTL_DSP_GETIPTR:
2596                 if (!(file->f_mode & FMODE_READ))
2597                         return -EINVAL;
2598                 spin_lock_irqsave(&s->lock, flags);
2599                 cm_update_ptr(s);
2600                 cinfo.bytes = s->dma_adc.total_bytes;
2601                 cinfo.blocks = s->dma_adc.count >> s->dma_adc.fragshift;
2602                 cinfo.ptr = s->dma_adc.hwptr;
2603                 if (s->dma_adc.mapped)
2604                         s->dma_adc.count &= s->dma_adc.fragsize-1;
2605                 spin_unlock_irqrestore(&s->lock, flags);
2606                 return copy_to_user(argp, &cinfo, sizeof(cinfo))  ? -EFAULT : 0;
2607
2608         case SNDCTL_DSP_GETOPTR:
2609                 if (!(file->f_mode & FMODE_WRITE))
2610                         return -EINVAL;
2611                 spin_lock_irqsave(&s->lock, flags);
2612                 cm_update_ptr(s);
2613                 cinfo.bytes = s->dma_dac.total_bytes;
2614                 cinfo.blocks = s->dma_dac.count >> s->dma_dac.fragshift;
2615                 cinfo.ptr = s->dma_dac.hwptr;
2616                 if (s->dma_dac.mapped)
2617                         s->dma_dac.count &= s->dma_dac.fragsize-1;
2618                 if (s->status & DO_DUAL_DAC) {
2619                         if (s->dma_adc.mapped)
2620                                 s->dma_adc.count &= s->dma_adc.fragsize-1;
2621                 }
2622                 spin_unlock_irqrestore(&s->lock, flags);
2623                 return copy_to_user(argp, &cinfo, sizeof(cinfo)) ? -EFAULT : 0;
2624
2625         case SNDCTL_DSP_GETBLKSIZE:
2626                 if (file->f_mode & FMODE_WRITE) {
2627                         if ((val = prog_dmabuf(s, 0)))
2628                                 return val;
2629                         if (s->status & DO_DUAL_DAC) {
2630                                 if ((val = prog_dmabuf(s, 1)))
2631                                         return val;
2632                                 return put_user(2 * s->dma_dac.fragsize, p);
2633                         }
2634                         return put_user(s->dma_dac.fragsize, p);
2635                 }
2636                 if ((val = prog_dmabuf(s, 1)))
2637                         return val;
2638                 return put_user(s->dma_adc.fragsize, p);
2639
2640         case SNDCTL_DSP_SETFRAGMENT:
2641                 if (get_user(val, p))
2642                         return -EFAULT;
2643                 if (file->f_mode & FMODE_READ) {
2644                         s->dma_adc.ossfragshift = val & 0xffff;
2645                         s->dma_adc.ossmaxfrags = (val >> 16) & 0xffff;
2646                         if (s->dma_adc.ossfragshift < 4)
2647                                 s->dma_adc.ossfragshift = 4;
2648                         if (s->dma_adc.ossfragshift > 15)
2649                                 s->dma_adc.ossfragshift = 15;
2650                         if (s->dma_adc.ossmaxfrags < 4)
2651                                 s->dma_adc.ossmaxfrags = 4;
2652                 }
2653                 if (file->f_mode & FMODE_WRITE) {
2654                         s->dma_dac.ossfragshift = val & 0xffff;
2655                         s->dma_dac.ossmaxfrags = (val >> 16) & 0xffff;
2656                         if (s->dma_dac.ossfragshift < 4)
2657                                 s->dma_dac.ossfragshift = 4;
2658                         if (s->dma_dac.ossfragshift > 15)
2659                                 s->dma_dac.ossfragshift = 15;
2660                         if (s->dma_dac.ossmaxfrags < 4)
2661                                 s->dma_dac.ossmaxfrags = 4;
2662                         if (s->status & DO_DUAL_DAC) {
2663                                 s->dma_adc.ossfragshift = s->dma_dac.ossfragshift;
2664                                 s->dma_adc.ossmaxfrags = s->dma_dac.ossmaxfrags;
2665                         }
2666                 }
2667                 return 0;
2668
2669         case SNDCTL_DSP_SUBDIVIDE:
2670                 if ((file->f_mode & FMODE_READ && s->dma_adc.subdivision) ||
2671                     (file->f_mode & FMODE_WRITE && s->dma_dac.subdivision))
2672                         return -EINVAL;
2673                 if (get_user(val, p))
2674                         return -EFAULT;
2675                 if (val != 1 && val != 2 && val != 4)
2676                         return -EINVAL;
2677                 if (file->f_mode & FMODE_READ)
2678                         s->dma_adc.subdivision = val;
2679                 if (file->f_mode & FMODE_WRITE) {
2680                         s->dma_dac.subdivision = val;
2681                         if (s->status & DO_DUAL_DAC)
2682                                 s->dma_adc.subdivision = val;
2683                 }
2684                 return 0;
2685
2686         case SOUND_PCM_READ_RATE:
2687                 return put_user((file->f_mode & FMODE_READ) ? s->rateadc : s->ratedac, p);
2688
2689         case SOUND_PCM_READ_CHANNELS:
2690                 return put_user((s->fmt & ((file->f_mode & FMODE_READ) ? (CM_CFMT_STEREO << CM_CFMT_ADCSHIFT) : (CM_CFMT_STEREO << CM_CFMT_DACSHIFT))) ? 2 : 1, p);
2691
2692         case SOUND_PCM_READ_BITS:
2693                 return put_user((s->fmt & ((file->f_mode & FMODE_READ) ? (CM_CFMT_16BIT << CM_CFMT_ADCSHIFT) : (CM_CFMT_16BIT << CM_CFMT_DACSHIFT))) ? 16 : 8, p);
2694
2695         case SOUND_PCM_READ_FILTER:
2696                 return put_user((file->f_mode & FMODE_READ) ? s->rateadc : s->ratedac, p);
2697
2698         case SNDCTL_DSP_GETCHANNELMASK:
2699                 return put_user(DSP_BIND_FRONT|DSP_BIND_SURR|DSP_BIND_CENTER_LFE|DSP_BIND_SPDIF, p);
2700
2701         case SNDCTL_DSP_BIND_CHANNEL:
2702                 if (get_user(val, p))
2703                         return -EFAULT;
2704                 if (val == DSP_BIND_QUERY) {
2705                         val = DSP_BIND_FRONT;
2706                         if (s->status & DO_SPDIF_OUT)
2707                                 val |= DSP_BIND_SPDIF;
2708                         else {
2709                                 if (s->curr_channels == 4)
2710                                         val |= DSP_BIND_SURR;
2711                                 if (s->curr_channels > 4)
2712                                         val |= DSP_BIND_CENTER_LFE;
2713                         }
2714                 } else {
2715                         if (file->f_mode & FMODE_READ) {
2716                                 stop_adc(s);
2717                                 s->dma_adc.ready = 0;
2718                                 if (val & DSP_BIND_SPDIF) {
2719                                         set_spdifin(s, s->rateadc);
2720                                         if (!(s->status & DO_SPDIF_OUT))
2721                                                 val &= ~DSP_BIND_SPDIF;
2722                                 }
2723                         }
2724                         if (file->f_mode & FMODE_WRITE) {
2725                                 stop_dac(s);
2726                                 s->dma_dac.ready = 0;
2727                                 if (val & DSP_BIND_SPDIF) {
2728                                         set_spdifout(s, s->ratedac);
2729                                         set_dac_channels(s, s->fmt & (CM_CFMT_STEREO << CM_CFMT_DACSHIFT) ? 2 : 1);
2730                                         if (!(s->status & DO_SPDIF_OUT))
2731                                                 val &= ~DSP_BIND_SPDIF;
2732                                 } else {
2733                                         int channels;
2734                                         int mask;
2735
2736                                         mask = val & (DSP_BIND_FRONT|DSP_BIND_SURR|DSP_BIND_CENTER_LFE);
2737                                         switch (mask) {
2738                                             case DSP_BIND_FRONT:
2739                                                 channels = 2;
2740                                                 break;
2741                                             case DSP_BIND_FRONT|DSP_BIND_SURR:
2742                                                 channels = 4;
2743                                                 break;
2744                                             case DSP_BIND_FRONT|DSP_BIND_SURR|DSP_BIND_CENTER_LFE:
2745                                                 channels = 6;
2746                                                 break;
2747                                             default:
2748                                                 channels = s->fmt & (CM_CFMT_STEREO << CM_CFMT_DACSHIFT) ? 2 : 1;
2749                                                 break;
2750                                         }
2751                                         set_dac_channels(s, channels);
2752                                 }
2753                         }
2754                 }
2755                 return put_user(val, p);
2756
2757         case SOUND_PCM_WRITE_FILTER:
2758         case SNDCTL_DSP_MAPINBUF:
2759         case SNDCTL_DSP_MAPOUTBUF:
2760         case SNDCTL_DSP_SETSYNCRO:
2761                 return -EINVAL;
2762         case SNDCTL_SPDIF_COPYRIGHT:
2763                 if (get_user(val, p))
2764                         return -EFAULT;
2765                 set_spdif_copyright(s, val);
2766                 return 0;
2767         case SNDCTL_SPDIF_LOOP:
2768                 if (get_user(val, p))
2769                         return -EFAULT;
2770                 set_spdif_loop(s, val);
2771                 return 0;
2772         case SNDCTL_SPDIF_MONITOR:
2773                 if (get_user(val, p))
2774                         return -EFAULT;
2775                 set_spdif_monitor(s, val);
2776                 return 0;
2777         case SNDCTL_SPDIF_LEVEL:
2778                 if (get_user(val, p))
2779                         return -EFAULT;
2780                 set_spdifout_level(s, val);
2781                 return 0;
2782         case SNDCTL_SPDIF_INV:
2783                 if (get_user(val, p))
2784                         return -EFAULT;
2785                 set_spdifin_inverse(s, val);
2786                 return 0;
2787         case SNDCTL_SPDIF_SEL2:
2788                 if (get_user(val, p))
2789                         return -EFAULT;
2790                 set_spdifin_channel2(s, val);
2791                 return 0;
2792         case SNDCTL_SPDIF_VALID:
2793                 if (get_user(val, p))
2794                         return -EFAULT;
2795                 set_spdifin_valid(s, val);
2796                 return 0;
2797         case SNDCTL_SPDIFOUT:
2798                 if (get_user(val, p))
2799                         return -EFAULT;
2800                 set_spdifout(s, val ? s->ratedac : 0);
2801                 return 0;
2802         case SNDCTL_SPDIFIN:
2803                 if (get_user(val, p))
2804                         return -EFAULT;
2805                 set_spdifin(s, val ? s->rateadc : 0);
2806                 return 0;
2807         }
2808         return mixer_ioctl(s, cmd, arg);
2809 }
2810
2811 static int cm_open(struct inode *inode, struct file *file)
2812 {
2813         int minor = iminor(inode);
2814         DECLARE_WAITQUEUE(wait, current);
2815         unsigned char fmtm = ~0, fmts = 0;
2816         struct list_head *list;
2817         struct cm_state *s;
2818
2819         for (list = devs.next; ; list = list->next) {
2820                 if (list == &devs)
2821                         return -ENODEV;
2822                 s = list_entry(list, struct cm_state, devs);
2823                 if (!((s->dev_audio ^ minor) & ~0xf))
2824                         break;
2825         }
2826         VALIDATE_STATE(s);
2827         file->private_data = s;
2828         /* wait for device to become free */
2829         mutex_lock(&s->open_mutex);
2830         while (s->open_mode & file->f_mode) {
2831                 if (file->f_flags & O_NONBLOCK) {
2832                         mutex_unlock(&s->open_mutex);
2833                         return -EBUSY;
2834                 }
2835                 add_wait_queue(&s->open_wait, &wait);
2836                 __set_current_state(TASK_INTERRUPTIBLE);
2837                 mutex_unlock(&s->open_mutex);
2838                 schedule();
2839                 remove_wait_queue(&s->open_wait, &wait);
2840                 set_current_state(TASK_RUNNING);
2841                 if (signal_pending(current))
2842                         return -ERESTARTSYS;
2843                 mutex_lock(&s->open_mutex);
2844         }
2845         if (file->f_mode & FMODE_READ) {
2846                 s->status &= ~DO_BIGENDIAN_R;
2847                 fmtm &= ~((CM_CFMT_STEREO | CM_CFMT_16BIT) << CM_CFMT_ADCSHIFT);
2848                 if ((minor & 0xf) == SND_DEV_DSP16)
2849                         fmts |= CM_CFMT_16BIT << CM_CFMT_ADCSHIFT;
2850                 s->dma_adc.ossfragshift = s->dma_adc.ossmaxfrags = s->dma_adc.subdivision = 0;
2851                 s->dma_adc.enabled = 1;
2852                 set_adc_rate(s, 8000);
2853                 // spdif-in is turnned off by default
2854                 set_spdifin(s, 0);
2855         }
2856         if (file->f_mode & FMODE_WRITE) {
2857                 s->status &= ~DO_BIGENDIAN_W;
2858                 fmtm &= ~((CM_CFMT_STEREO | CM_CFMT_16BIT) << CM_CFMT_DACSHIFT);
2859                 if ((minor & 0xf) == SND_DEV_DSP16)
2860                         fmts |= CM_CFMT_16BIT << CM_CFMT_DACSHIFT;
2861                 s->dma_dac.ossfragshift = s->dma_dac.ossmaxfrags = s->dma_dac.subdivision = 0;
2862                 s->dma_dac.enabled = 1;
2863                 set_dac_rate(s, 8000);
2864                 // clear previous multichannel, spdif, ac3 state
2865                 set_spdifout(s, 0);
2866                 set_ac3(s, 0);
2867                 set_dac_channels(s, 1);
2868         }
2869         set_fmt(s, fmtm, fmts);
2870         s->open_mode |= file->f_mode & (FMODE_READ | FMODE_WRITE);
2871         mutex_unlock(&s->open_mutex);
2872         return nonseekable_open(inode, file);
2873 }
2874
2875 static int cm_release(struct inode *inode, struct file *file)
2876 {
2877         struct cm_state *s = (struct cm_state *)file->private_data;
2878
2879         VALIDATE_STATE(s);
2880         lock_kernel();
2881         if (file->f_mode & FMODE_WRITE)
2882                 drain_dac(s, file->f_flags & O_NONBLOCK);
2883         mutex_lock(&s->open_mutex);
2884         if (file->f_mode & FMODE_WRITE) {
2885                 stop_dac(s);
2886
2887                 dealloc_dmabuf(s, &s->dma_dac);
2888                 if (s->status & DO_DUAL_DAC)
2889                         dealloc_dmabuf(s, &s->dma_adc);
2890
2891                 if (s->status & DO_MULTI_CH)
2892                         set_dac_channels(s, 1);
2893                 if (s->status & DO_AC3)
2894                         set_ac3(s, 0);
2895                 if (s->status & DO_SPDIF_OUT)
2896                         set_spdifout(s, 0);
2897                 /* enable SPDIF loop */
2898                 set_spdif_loop(s, spdif_loop);
2899                 s->status &= ~DO_BIGENDIAN_W;
2900         }
2901         if (file->f_mode & FMODE_READ) {
2902                 stop_adc(s);
2903                 dealloc_dmabuf(s, &s->dma_adc);
2904                 s->status &= ~DO_BIGENDIAN_R;
2905         }
2906         s->open_mode &= ~(file->f_mode & (FMODE_READ|FMODE_WRITE));
2907         mutex_unlock(&s->open_mutex);
2908         wake_up(&s->open_wait);
2909         unlock_kernel();
2910         return 0;
2911 }
2912
2913 static /*const*/ struct file_operations cm_audio_fops = {
2914         .owner   = THIS_MODULE,
2915         .llseek  = no_llseek,
2916         .read    = cm_read,
2917         .write   = cm_write,
2918         .poll    = cm_poll,
2919         .ioctl   = cm_ioctl,
2920         .mmap    = cm_mmap,
2921         .open    = cm_open,
2922         .release = cm_release,
2923 };
2924
2925 /* --------------------------------------------------------------------- */
2926
2927 static struct initvol {
2928         int mixch;
2929         int vol;
2930 } initvol[] __devinitdata = {
2931         { SOUND_MIXER_WRITE_CD, 0x4f4f },
2932         { SOUND_MIXER_WRITE_LINE, 0x4f4f },
2933         { SOUND_MIXER_WRITE_MIC, 0x4f4f },
2934         { SOUND_MIXER_WRITE_SYNTH, 0x4f4f },
2935         { SOUND_MIXER_WRITE_VOLUME, 0x4f4f },
2936         { SOUND_MIXER_WRITE_PCM, 0x4f4f }
2937 };
2938
2939 /* check chip version and capability */
2940 static int query_chip(struct cm_state *s)
2941 {
2942         int ChipVersion = -1;
2943         unsigned char RegValue;
2944
2945         // check reg 0Ch, bit 24-31
2946         RegValue = inb(s->iobase + CODEC_CMI_INT_HLDCLR + 3);
2947         if (RegValue == 0) {
2948             // check reg 08h, bit 24-28
2949             RegValue = inb(s->iobase + CODEC_CMI_CHFORMAT + 3);
2950             RegValue &= 0x1f;
2951             if (RegValue == 0) {
2952                 ChipVersion = 33;
2953                 s->max_channels = 4;
2954                 s->capability |= CAN_AC3_SW;
2955                 s->capability |= CAN_DUAL_DAC;
2956             } else {
2957                 ChipVersion = 37;
2958                 s->max_channels = 4;
2959                 s->capability |= CAN_AC3_HW;
2960                 s->capability |= CAN_DUAL_DAC;
2961             }
2962         } else {
2963             // check reg 0Ch, bit 26
2964             if (RegValue & (1 << (26-24))) {
2965                 ChipVersion = 39;
2966                 if (RegValue & (1 << (24-24)))
2967                     s->max_channels = 6;
2968                 else
2969                     s->max_channels = 4;
2970                 s->capability |= CAN_AC3_HW;
2971                 s->capability |= CAN_DUAL_DAC;
2972                 s->capability |= CAN_MULTI_CH_HW;
2973                 s->capability |= CAN_LINE_AS_BASS;
2974                 s->capability |= CAN_MIC_AS_BASS;
2975             } else {
2976                 ChipVersion = 55; // 4 or 6 channels
2977                 s->max_channels = 6;
2978                 s->capability |= CAN_AC3_HW;
2979                 s->capability |= CAN_DUAL_DAC;
2980                 s->capability |= CAN_MULTI_CH_HW;
2981                 s->capability |= CAN_LINE_AS_BASS;
2982                 s->capability |= CAN_MIC_AS_BASS;
2983             }
2984         }
2985         s->capability |= CAN_LINE_AS_REAR;
2986         return ChipVersion;
2987 }
2988
2989 #ifdef CONFIG_SOUND_CMPCI_JOYSTICK
2990 static int __devinit cm_create_gameport(struct cm_state *s, int io_port)
2991 {
2992         struct gameport *gp;
2993
2994         if (!request_region(io_port, CM_EXTENT_GAME, "cmpci GAME")) {
2995                 printk(KERN_ERR "cmpci: gameport io ports 0x%#x in use\n", io_port);
2996                 return -EBUSY;
2997         }
2998
2999         if (!(s->gameport = gp = gameport_allocate_port())) {
3000                 printk(KERN_ERR "cmpci: can not allocate memory for gameport\n");
3001                 release_region(io_port, CM_EXTENT_GAME);
3002                 return -ENOMEM;
3003         }
3004
3005         gameport_set_name(gp, "C-Media GP");
3006         gameport_set_phys(gp, "pci%s/gameport0", pci_name(s->dev));
3007         gp->dev.parent = &s->dev->dev;
3008         gp->io = io_port;
3009
3010         /* enable joystick */
3011         maskb(s->iobase + CODEC_CMI_FUNCTRL1, ~0, 0x02);
3012
3013         gameport_register_port(gp);
3014
3015         return 0;
3016 }
3017
3018 static void __devexit cm_free_gameport(struct cm_state *s)
3019 {
3020         if (s->gameport) {
3021                 int gpio = s->gameport->io;
3022
3023                 gameport_unregister_port(s->gameport);
3024                 s->gameport = NULL;
3025                 maskb(s->iobase + CODEC_CMI_FUNCTRL1, ~0x02, 0);
3026                 release_region(gpio, CM_EXTENT_GAME);
3027         }
3028 }
3029 #else
3030 static inline int cm_create_gameport(struct cm_state *s, int io_port) { return -ENOSYS; }
3031 static inline void cm_free_gameport(struct cm_state *s) { }
3032 #endif
3033
3034 #define echo_option(x)\
3035 if (x) strcat(options, "" #x " ")
3036
3037 static int __devinit cm_probe(struct pci_dev *pcidev, const struct pci_device_id *pciid)
3038 {
3039         struct cm_state *s;
3040         mm_segment_t fs;
3041         int i, val, ret;
3042         unsigned char reg_mask;
3043         int timeout;
3044         struct resource *ports;
3045         struct {
3046                 unsigned short  deviceid;
3047                 char            *devicename;
3048         } devicetable[] = {
3049                 { PCI_DEVICE_ID_CMEDIA_CM8338A, "CM8338A" },
3050                 { PCI_DEVICE_ID_CMEDIA_CM8338B, "CM8338B" },
3051                 { PCI_DEVICE_ID_CMEDIA_CM8738,  "CM8738" },
3052                 { PCI_DEVICE_ID_CMEDIA_CM8738B, "CM8738B" },
3053         };
3054         char    *devicename = "unknown";
3055         char    options[256];
3056
3057         if ((ret = pci_enable_device(pcidev)))
3058                 return ret;
3059         if (!(pci_resource_flags(pcidev, 0) & IORESOURCE_IO))
3060                 return -ENODEV;
3061         if (pcidev->irq == 0)
3062                 return -ENODEV;
3063         i = pci_set_dma_mask(pcidev, DMA_32BIT_MASK);
3064         if (i) {
3065                 printk(KERN_WARNING "cmpci: architecture does not support 32bit PCI busmaster DMA\n");
3066                 return i;
3067         }
3068         s = kmalloc(sizeof(*s), GFP_KERNEL);
3069         if (!s) {
3070                 printk(KERN_WARNING "cmpci: out of memory\n");
3071                 return -ENOMEM;
3072         }
3073         /* search device name */
3074         for (i = 0; i < sizeof(devicetable) / sizeof(devicetable[0]); i++) {
3075                 if (devicetable[i].deviceid == pcidev->device) {
3076                         devicename = devicetable[i].devicename;
3077                         break;
3078                 }
3079         }
3080         memset(s, 0, sizeof(struct cm_state));
3081         init_waitqueue_head(&s->dma_adc.wait);
3082         init_waitqueue_head(&s->dma_dac.wait);
3083         init_waitqueue_head(&s->open_wait);
3084         mutex_init(&s->open_mutex);
3085         spin_lock_init(&s->lock);
3086         s->magic = CM_MAGIC;
3087         s->dev = pcidev;
3088         s->iobase = pci_resource_start(pcidev, 0);
3089         s->iosynth = fmio;
3090         s->iomidi = mpuio;
3091 #ifdef CONFIG_SOUND_CMPCI_MIDI
3092         s->midi_devc = 0;
3093 #endif
3094         s->status = 0;
3095         if (s->iobase == 0)
3096                 return -ENODEV;
3097         s->irq = pcidev->irq;
3098
3099         if (!request_region(s->iobase, CM_EXTENT_CODEC, "cmpci")) {
3100                 printk(KERN_ERR "cmpci: io ports %#x-%#x in use\n", s->iobase, s->iobase+CM_EXTENT_CODEC-1);
3101                 ret = -EBUSY;
3102                 goto err_region5;
3103         }
3104         /* dump parameters */
3105         strcpy(options, "cmpci: ");
3106         echo_option(joystick);
3107         echo_option(spdif_inverse);
3108         echo_option(spdif_loop);
3109         echo_option(spdif_out);
3110         echo_option(use_line_as_rear);
3111         echo_option(use_line_as_bass);
3112         echo_option(use_mic_as_bass);
3113         echo_option(mic_boost);
3114         echo_option(hw_copy);
3115         printk(KERN_INFO "%s\n", options);
3116
3117         /* initialize codec registers */
3118         outb(0, s->iobase + CODEC_CMI_INT_HLDCLR + 2);  /* disable ints */
3119         outb(0, s->iobase + CODEC_CMI_FUNCTRL0 + 2); /* disable channels */
3120         /* reset mixer */
3121         wrmixer(s, DSP_MIX_DATARESETIDX, 0);
3122
3123         /* request irq */
3124         if ((ret = request_irq(s->irq, cm_interrupt, IRQF_SHARED, "cmpci", s))) {
3125                 printk(KERN_ERR "cmpci: irq %u in use\n", s->irq);
3126                 goto err_irq;
3127         }
3128         printk(KERN_INFO "cmpci: found %s adapter at io %#x irq %u\n",
3129                devicename, s->iobase, s->irq);
3130         /* register devices */
3131         if ((s->dev_audio = register_sound_dsp(&cm_audio_fops, -1)) < 0) {
3132                 ret = s->dev_audio;
3133                 goto err_dev1;
3134         }
3135         if ((s->dev_mixer = register_sound_mixer(&cm_mixer_fops, -1)) < 0) {
3136                 ret = s->dev_mixer;
3137                 goto err_dev2;
3138         }
3139         pci_set_master(pcidev); /* enable bus mastering */
3140         /* initialize the chips */
3141         fs = get_fs();
3142         set_fs(KERNEL_DS);
3143         /* set mixer output */
3144         frobindir(s, DSP_MIX_OUTMIXIDX, 0x1f, 0x1f);
3145         /* set mixer input */
3146         val = SOUND_MASK_LINE|SOUND_MASK_SYNTH|SOUND_MASK_CD|SOUND_MASK_MIC;
3147         mixer_ioctl(s, SOUND_MIXER_WRITE_RECSRC, (unsigned long)&val);
3148         for (i = 0; i < sizeof(initvol)/sizeof(initvol[0]); i++) {
3149                 val = initvol[i].vol;
3150                 mixer_ioctl(s, initvol[i].mixch, (unsigned long)&val);
3151         }
3152         set_fs(fs);
3153         /* use channel 1 for playback, channel 0 for record */
3154         maskb(s->iobase + CODEC_CMI_FUNCTRL0, ~CHADC1, CHADC0);
3155         /* turn off VMIC3 - mic boost */
3156         if (mic_boost)
3157                 maskb(s->iobase + CODEC_CMI_MIXER2, ~1, 0);
3158         else
3159                 maskb(s->iobase + CODEC_CMI_MIXER2, ~0, 1);
3160         s->deviceid = pcidev->device;
3161
3162         if (pcidev->device == PCI_DEVICE_ID_CMEDIA_CM8738
3163          || pcidev->device == PCI_DEVICE_ID_CMEDIA_CM8738B) {
3164
3165                 /* chip version and hw capability check */
3166                 s->chip_version = query_chip(s);
3167                 printk(KERN_INFO "cmpci: chip version = 0%d\n", s->chip_version);
3168
3169                 /* set SPDIF-in inverse before enable SPDIF loop */
3170                 set_spdifin_inverse(s, spdif_inverse);
3171
3172                 /* use SPDIF in #1 */
3173                 set_spdifin_channel2(s, 0);
3174         } else {
3175                 s->chip_version = 0;
3176                 /* 8338 will fall here */
3177                 s->max_channels = 4;
3178                 s->capability |= CAN_DUAL_DAC;
3179                 s->capability |= CAN_LINE_AS_REAR;
3180         }
3181         /* enable SPDIF loop */
3182         set_spdif_loop(s, spdif_loop);
3183
3184         // enable 4 speaker mode (analog duplicate)
3185         set_hw_copy(s, hw_copy);
3186
3187         reg_mask = 0;
3188 #ifdef CONFIG_SOUND_CMPCI_FM
3189         /* disable FM */
3190         maskb(s->iobase + CODEC_CMI_MISC_CTRL + 2, ~8, 0);
3191         if (s->iosynth) {
3192             /* don't enable OPL3 if there is one */
3193             if (opl3_detect(s->iosynth, NULL)) {
3194                 s->iosynth = 0;
3195             } else {
3196                 /* set IO based at 0x388 */
3197                 switch (s->iosynth) {
3198                     case 0x388:
3199                         reg_mask = 0;
3200                         break;
3201                     case 0x3C8:
3202                         reg_mask = 0x01;
3203                         break;
3204                     case 0x3E0:
3205                         reg_mask = 0x02;
3206                         break;
3207                     case 0x3E8:
3208                         reg_mask = 0x03;
3209                         break;
3210                     default:
3211                         s->iosynth = 0;
3212                         break;
3213                 }
3214                 maskb(s->iobase + CODEC_CMI_LEGACY_CTRL + 3, ~0x03, reg_mask);
3215                 /* enable FM */
3216                 if (s->iosynth) {
3217                         maskb(s->iobase + CODEC_CMI_MISC_CTRL + 2, ~0, 8);
3218                         if (opl3_detect(s->iosynth, NULL))
3219                                 ret = opl3_init(s->iosynth, NULL, THIS_MODULE);
3220                         else {
3221                                 maskb(s->iobase + CODEC_CMI_MISC_CTRL + 2, ~8, 0);
3222                                 s->iosynth = 0;
3223                         }
3224                 }
3225             }
3226         }
3227 #endif
3228 #ifdef CONFIG_SOUND_CMPCI_MIDI
3229         switch (s->iomidi) {
3230             case 0x330:
3231                 reg_mask = 0;
3232                 break;
3233             case 0x320:
3234                 reg_mask = 0x20;
3235                 break;
3236             case 0x310:
3237                 reg_mask = 0x40;
3238                 break;
3239             case 0x300:
3240                 reg_mask = 0x60;
3241                 break;
3242             default:
3243                 s->iomidi = 0;
3244                 goto skip_mpu;
3245         }
3246         ports = request_region(s->iomidi, 2, "mpu401");
3247         if (!ports)
3248                 goto skip_mpu;
3249         /* disable MPU-401 */
3250         maskb(s->iobase + CODEC_CMI_FUNCTRL1, ~0x04, 0);
3251         s->mpu_data.name = "cmpci mpu";
3252         s->mpu_data.io_base = s->iomidi;
3253         s->mpu_data.irq = -s->irq;      // tell mpu401 to share irq
3254         if (probe_mpu401(&s->mpu_data, ports)) {
3255                 release_region(s->iomidi, 2);
3256                 s->iomidi = 0;
3257                 goto skip_mpu;
3258         }
3259         maskb(s->iobase + CODEC_CMI_LEGACY_CTRL + 3, ~0x60, reg_mask);
3260         /* enable MPU-401 */
3261         maskb(s->iobase + CODEC_CMI_FUNCTRL1, ~0, 0x04);
3262         /* clear all previously received interrupt */
3263         for (timeout = 900000; timeout > 0; timeout--) {
3264                 if ((inb(s->iomidi + 1) && 0x80) == 0)
3265                         inb(s->iomidi);
3266                 else
3267                         break;
3268         }
3269         if (!probe_mpu401(&s->mpu_data, ports)) {
3270                 release_region(s->iomidi, 2);
3271                 s->iomidi = 0;
3272                 maskb(s->iobase + CODEC_CMI_FUNCTRL1, ~0, 0x04);
3273         } else {
3274                 attach_mpu401(&s->mpu_data, THIS_MODULE);
3275                 s->midi_devc = s->mpu_data.slots[1];
3276         }
3277 skip_mpu:
3278 #endif
3279         /* disable joystick port */
3280         maskb(s->iobase + CODEC_CMI_FUNCTRL1, ~0x02, 0);
3281         if (joystick)
3282                 cm_create_gameport(s, 0x200);
3283
3284         /* store it in the driver field */
3285         pci_set_drvdata(pcidev, s);
3286         /* put it into driver list */
3287         list_add_tail(&s->devs, &devs);
3288         /* increment devindex */
3289         if (devindex < NR_DEVICE-1)
3290                 devindex++;
3291         return 0;
3292
3293 err_dev2:
3294         unregister_sound_dsp(s->dev_audio);
3295 err_dev1:
3296         printk(KERN_ERR "cmpci: cannot register misc device\n");
3297         free_irq(s->irq, s);
3298 err_irq:
3299         release_region(s->iobase, CM_EXTENT_CODEC);
3300 err_region5:
3301         kfree(s);
3302         return ret;
3303 }
3304
3305 /* --------------------------------------------------------------------- */
3306
3307 MODULE_AUTHOR("ChenLi Tien, cltien@cmedia.com.tw");
3308 MODULE_DESCRIPTION("CM8x38 Audio Driver");
3309 MODULE_LICENSE("GPL");
3310
3311 static void __devexit cm_remove(struct pci_dev *dev)
3312 {
3313         struct cm_state *s = pci_get_drvdata(dev);
3314
3315         if (!s)
3316                 return;
3317
3318         cm_free_gameport(s);
3319
3320 #ifdef CONFIG_SOUND_CMPCI_FM
3321         if (s->iosynth) {
3322                 /* disable FM */
3323                 maskb(s->iobase + CODEC_CMI_MISC_CTRL + 2, ~8, 0);
3324         }
3325 #endif
3326 #ifdef CONFIG_SOUND_CMPCI_MIDI
3327         if (s->iomidi) {
3328                 unload_mpu401(&s->mpu_data);
3329                 /* disable MPU-401 */
3330                 maskb(s->iobase + CODEC_CMI_FUNCTRL1, ~0x04, 0);
3331         }
3332 #endif
3333         set_spdif_loop(s, 0);
3334         list_del(&s->devs);
3335         outb(0, s->iobase + CODEC_CMI_INT_HLDCLR + 2);  /* disable ints */
3336         synchronize_irq(s->irq);
3337         outb(0, s->iobase + CODEC_CMI_FUNCTRL0 + 2); /* disable channels */
3338         free_irq(s->irq, s);
3339
3340         /* reset mixer */
3341         wrmixer(s, DSP_MIX_DATARESETIDX, 0);
3342
3343         release_region(s->iobase, CM_EXTENT_CODEC);
3344         unregister_sound_dsp(s->dev_audio);
3345         unregister_sound_mixer(s->dev_mixer);
3346         kfree(s);
3347         pci_set_drvdata(dev, NULL);
3348 }
3349
3350 static struct pci_device_id id_table[] __devinitdata = {
3351         { PCI_VENDOR_ID_CMEDIA, PCI_DEVICE_ID_CMEDIA_CM8738B, PCI_ANY_ID, PCI_ANY_ID, 0, 0 },
3352         { PCI_VENDOR_ID_CMEDIA, PCI_DEVICE_ID_CMEDIA_CM8738, PCI_ANY_ID, PCI_ANY_ID, 0, 0 },
3353         { PCI_VENDOR_ID_CMEDIA, PCI_DEVICE_ID_CMEDIA_CM8338A, PCI_ANY_ID, PCI_ANY_ID, 0, 0 },
3354         { PCI_VENDOR_ID_CMEDIA, PCI_DEVICE_ID_CMEDIA_CM8338B, PCI_ANY_ID, PCI_ANY_ID, 0, 0 },
3355         { 0, }
3356 };
3357
3358 MODULE_DEVICE_TABLE(pci, id_table);
3359
3360 static struct pci_driver cm_driver = {
3361        .name     = "cmpci",
3362        .id_table = id_table,
3363        .probe    = cm_probe,
3364        .remove   = __devexit_p(cm_remove)
3365 };
3366
3367 static int __init init_cmpci(void)
3368 {
3369         printk(KERN_INFO "cmpci: version $Revision: 6.82 $ time " __TIME__ " " __DATE__ "\n");
3370         return pci_register_driver(&cm_driver);
3371 }
3372
3373 static void __exit cleanup_cmpci(void)
3374 {
3375         printk(KERN_INFO "cmpci: unloading\n");
3376         pci_unregister_driver(&cm_driver);
3377 }
3378
3379 module_init(init_cmpci);
3380 module_exit(cleanup_cmpci);