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