setup enviroment for compilation
[linux-2.4.21-pre4.git] / drivers / sound / ite8172.c
1 /*
2  *      ite8172.c  --  ITE IT8172G Sound Driver.
3  *
4  * Copyright 2001 MontaVista Software Inc.
5  * Author: MontaVista Software, Inc.
6  *              stevel@mvista.com or source@mvista.com
7  *
8  *  This program is free software; you can redistribute  it and/or modify it
9  *  under  the terms of  the GNU General  Public License as published by the
10  *  Free Software Foundation;  either version 2 of the  License, or (at your
11  *  option) any later version.
12  *
13  *  THIS  SOFTWARE  IS PROVIDED   ``AS  IS'' AND   ANY  EXPRESS OR IMPLIED
14  *  WARRANTIES,   INCLUDING, BUT NOT  LIMITED  TO, THE IMPLIED WARRANTIES OF
15  *  MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN
16  *  NO  EVENT  SHALL   THE AUTHOR  BE    LIABLE FOR ANY   DIRECT, INDIRECT,
17  *  INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
18  *  NOT LIMITED   TO, PROCUREMENT OF  SUBSTITUTE GOODS  OR SERVICES; LOSS OF
19  *  USE, DATA,  OR PROFITS; OR  BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
20  *  ANY THEORY OF LIABILITY, WHETHER IN  CONTRACT, STRICT LIABILITY, OR TORT
21  *  (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
22  *  THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
23  *
24  *  You should have received a copy of the  GNU General Public License along
25  *  with this program; if not, write  to the Free Software Foundation, Inc.,
26  *  675 Mass Ave, Cambridge, MA 02139, USA.
27  *
28  *
29  * Module command line parameters:
30  *
31  *  Supported devices:
32  *  /dev/dsp    standard OSS /dev/dsp device
33  *  /dev/mixer  standard OSS /dev/mixer device
34  *
35  * Notes:
36  *
37  *  1. Much of the OSS buffer allocation, ioctl's, and mmap'ing are
38  *     taken, slightly modified or not at all, from the ES1371 driver,
39  *     so refer to the credits in es1371.c for those. The rest of the
40  *     code (probe, open, read, write, the ISR, etc.) is new.
41  *  2. The following support is untested:
42  *      * Memory mapping the audio buffers, and the ioctl controls that go
43  *        with it.
44  *      * S/PDIF output.
45  *      * I2S support.
46  *  3. The following is not supported:
47  *      * legacy audio mode.
48  *  4. Support for volume button interrupts is implemented but doesn't
49  *     work yet.
50  *
51  *  Revision history
52  *    02.08.2001  Initial release
53  *    06.22.2001  Added I2S support
54  */
55 #include <linux/version.h>
56 #include <linux/module.h>
57 #include <linux/string.h>
58 #include <linux/ioport.h>
59 #include <linux/sched.h>
60 #include <linux/delay.h>
61 #include <linux/sound.h>
62 #include <linux/slab.h>
63 #include <linux/soundcard.h>
64 #include <linux/pci.h>
65 #include <linux/init.h>
66 #include <linux/poll.h>
67 #include <linux/bitops.h>
68 #include <linux/proc_fs.h>
69 #include <linux/spinlock.h>
70 #include <linux/smp_lock.h>
71 #include <linux/ac97_codec.h>
72 #include <linux/wrapper.h>
73 #include <asm/io.h>
74 #include <asm/dma.h>
75 #include <asm/uaccess.h>
76 #include <asm/hardirq.h>
77 #include <asm/it8172/it8172.h>
78
79 /* --------------------------------------------------------------------- */
80
81 #undef OSS_DOCUMENTED_MIXER_SEMANTICS
82 #define IT8172_DEBUG
83 #undef IT8172_VERBOSE_DEBUG
84 #define DBG(x) {}
85
86 #define IT8172_MODULE_NAME "IT8172 audio"
87 #define PFX IT8172_MODULE_NAME
88
89 #ifdef IT8172_DEBUG
90 #define dbg(format, arg...) printk(KERN_DEBUG PFX ": " format "\n" , ## arg)
91 #else
92 #define dbg(format, arg...) do {} while (0)
93 #endif
94 #define err(format, arg...) printk(KERN_ERR PFX ": " format "\n" , ## arg)
95 #define info(format, arg...) printk(KERN_INFO PFX ": " format "\n" , ## arg)
96 #define warn(format, arg...) printk(KERN_WARNING PFX ": " format "\n" , ## arg)
97
98
99 static const unsigned sample_shift[] = { 0, 1, 1, 2 };
100
101
102 /*
103  * Audio Controller register bit definitions follow. See
104  * include/asm/it8172/it8172.h for register offsets.
105  */
106
107 /* PCM Out Volume Reg */
108 #define PCMOV_PCMOM     (1<<15) /* PCM Out Mute default 1: mute */
109 #define PCMOV_PCMRCG_BIT 8      /* PCM Right channel Gain */
110 #define PCMOV_PCMRCG_MASK (0x1f<<PCMOV_PCMRCG_BIT)
111 #define PCMOV_PCMLCG_BIT 0      /* PCM Left channel gain  */
112 #define PCMOV_PCMLCG_MASK 0x1f
113
114 /* FM Out Volume Reg */
115 #define FMOV_FMOM       (1<<15) /* FM Out Mute default 1: mute */
116 #define FMOV_FMRCG_BIT  8       /* FM Right channel Gain */
117 #define FMOV_FMRCG_MASK (0x1f<<FMOV_FMRCG_BIT)
118 #define FMOV_FMLCG_BIT  0       /* FM Left channel gain  */
119 #define FMOV_FMLCG_MASK 0x1f
120
121 /* I2S Out Volume Reg */
122 #define I2SV_I2SOM       (1<<15) /* I2S Out Mute default 1: mute */
123 #define I2SV_I2SRCG_BIT  8       /* I2S Right channel Gain */
124 #define I2SV_I2SRCG_MASK (0x1f<<I2SV_I2SRCG_BIT)
125 #define I2SV_I2SLCG_BIT  0       /* I2S Left channel gain  */
126 #define I2SV_I2SLCG_MASK 0x1f
127
128 /* Digital Recording Source Select Reg */
129 #define DRSS_BIT   0
130 #define DRSS_MASK  0x07
131 #define   DRSS_AC97_PRIM 0
132 #define   DRSS_FM        1
133 #define   DRSS_I2S       2
134 #define   DRSS_PCM       3
135 #define   DRSS_AC97_SEC  4
136
137 /* Playback/Capture Channel Control Registers */
138 #define CC_SM           (1<<15) /* Stereo, Mone 0: mono 1: stereo */
139 #define CC_DF           (1<<14) /* Data Format 0: 8 bit 1: 16 bit */
140 #define CC_FMT_BIT      14
141 #define CC_FMT_MASK     (0x03<<CC_FMT_BIT)
142 #define CC_CF_BIT       12      /* Channel format (Playback only) */
143 #define CC_CF_MASK      (0x03<<CC_CF_BIT)
144 #define   CC_CF_2       0
145 #define   CC_CF_4       (1<<CC_CF_BIT)
146 #define   CC_CF_6       (2<<CC_CF_BIT)
147 #define CC_SR_BIT       8       /* sample Rate */
148 #define CC_SR_MASK      (0x0f<<CC_SR_BIT)
149 #define   CC_SR_5500    0
150 #define   CC_SR_8000    (1<<CC_SR_BIT)
151 #define   CC_SR_9600    (2<<CC_SR_BIT)
152 #define   CC_SR_11025   (3<<CC_SR_BIT)
153 #define   CC_SR_16000   (4<<CC_SR_BIT)
154 #define   CC_SR_19200   (5<<CC_SR_BIT)
155 #define   CC_SR_22050   (6<<CC_SR_BIT)
156 #define   CC_SR_32000   (7<<CC_SR_BIT)
157 #define   CC_SR_38400   (8<<CC_SR_BIT)
158 #define   CC_SR_44100   (9<<CC_SR_BIT)
159 #define   CC_SR_48000   (10<<CC_SR_BIT)
160 #define CC_CSP          (1<<7)  /* Channel stop 
161                                  * 0: End of Current buffer
162                                  * 1: Immediately stop when rec stop */
163 #define CC_CP           (1<<6)  /* Channel pause 0: normal, 1: pause */
164 #define CC_CA           (1<<5)  /* Channel Action 0: Stop , 1: start */
165 #define CC_CB2L         (1<<2)  /* Cur. buf. 2 xfr is last 0: No, 1: Yes */
166 #define CC_CB1L         (1<<1)  /* Cur. buf. 1 xfr is last 0: No, 1: Yes */
167 #define CC_DE           1       /* DFC/DFIFO Data Empty 1: empty, 0: not empty
168                                  * (Playback only)
169                                  */
170
171 /* Codec Control Reg */
172 #define CODECC_GME      (1<<9)  /* AC97 GPIO Mode enable */
173 #define CODECC_ATM      (1<<8)  /* AC97 ATE test mode 0: test 1: normal */
174 #define CODECC_WR       (1<<6)  /* AC97 Warn reset 1: warm reset , 0: Normal */
175 #define CODECC_CR       (1<<5)  /* AC97 Cold reset 1: Cold reset , 0: Normal */
176
177
178 /* I2S Control Reg      */
179 #define I2SMC_SR_BIT     6      /* I2S Sampling rate 
180                                  * 00: 48KHz, 01: 44.1 KHz, 10: 32 32 KHz */
181 #define I2SMC_SR_MASK    (0x03<<I2SMC_SR_BIT)
182 #define   I2SMC_SR_48000 0
183 #define   I2SMC_SR_44100 (1<<I2SMC_SR_BIT)
184 #define   I2SMC_SR_32000 (2<<I2SMC_SR_BIT)
185 #define I2SMC_SRSS       (1<<5) /* Sample Rate Source Select 1:S/W, 0: H/W */
186 #define I2SMC_I2SF_BIT   0      /* I2S Format */
187 #define I2SMC_I2SF_MASK  0x03
188 #define   I2SMC_I2SF_DAC 0
189 #define   I2SMC_I2SF_ADC 2
190 #define   I2SMC_I2SF_I2S 3
191
192
193 /* Volume up, Down, Mute */
194 #define VS_VMP  (1<<2)  /* Volume mute 1: pushed, 0: not */
195 #define VS_VDP  (1<<1)  /* Volume Down 1: pushed, 0: not */
196 #define VS_VUP  1       /* Volime Up 1: pushed, 0: not */
197
198 /* SRC, Mixer test control/DFC status reg */
199 #define SRCS_DPUSC      (1<<5)  /* DFC Playback underrun Status/clear */
200 #define SRCS_DCOSC      (1<<4)  /* DFC Capture Overrun Status/clear */
201 #define SRCS_SIS        (1<<3)  /* SRC input select 1: Mixer, 0: Codec I/F */
202 #define SRCS_CDIS_BIT   0       /* Codec Data Input Select */
203 #define SRCS_CDIS_MASK  0x07
204 #define   SRCS_CDIS_MIXER 0
205 #define   SRCS_CDIS_PCM   1
206 #define   SRCS_CDIS_I2S   2
207 #define   SRCS_CDIS_FM    3
208 #define   SRCS_CDIS_DFC   4
209
210
211 /* Codec Index Reg command Port */
212 #define CIRCP_CID_BIT   10
213 #define CIRCP_CID_MASK  (0x03<<CIRCP_CID_BIT)
214 #define CIRCP_CPS       (1<<9)  /* Command Port Status 0: ready, 1: busy */
215 #define CIRCP_DPVF      (1<<8)  /* Data Port Valid Flag 0: invalis, 1: valid */
216 #define CIRCP_RWC       (1<<7)  /* Read/write command */
217 #define CIRCP_CIA_BIT   0
218 #define CIRCP_CIA_MASK  0x007F  /* Codec Index Address */
219
220 /* Test Mode Control/Test group Select Control */
221
222 /* General Control Reg */
223 #define GC_VDC_BIT      6       /* Volume Division Control */
224 #define GC_VDC_MASK     (0x03<<GC_VDC_BIT)
225 #define   GC_VDC_NONE   0
226 #define   GC_VDC_DIV2   (1<<GC_VDC_BIT)
227 #define   GC_VDC_DIV4   (2<<GC_VDC_BIT)
228 #define GC_SOE          (1<<2)  /* S/PDIF Output enable */
229 #define GC_SWR          1       /* Software warn reset */
230
231 /* Interrupt mask Control Reg */
232 #define IMC_VCIM        (1<<6)  /* Volume CNTL interrupt mask */
233 #define IMC_CCIM        (1<<1)  /* Capture Chan. iterrupt mask */
234 #define IMC_PCIM        1       /* Playback Chan. interrupt mask */
235
236 /* Interrupt status/clear reg */
237 #define ISC_VCI         (1<<6)  /* Volume CNTL interrupt 1: clears */
238 #define ISC_CCI         (1<<1)  /* Capture Chan. interrupt 1: clears  */
239 #define ISC_PCI         1       /* Playback Chan. interrupt 1: clears */
240
241 /* misc stuff */
242 #define POLL_COUNT   0x5000
243
244
245 /* --------------------------------------------------------------------- */
246
247 /*
248  * Define DIGITAL1 as the I2S channel, since it is not listed in
249  * soundcard.h.
250  */
251 #define SOUND_MIXER_I2S        SOUND_MIXER_DIGITAL1
252 #define SOUND_MASK_I2S         SOUND_MASK_DIGITAL1
253 #define SOUND_MIXER_READ_I2S   MIXER_READ(SOUND_MIXER_I2S)
254 #define SOUND_MIXER_WRITE_I2S  MIXER_WRITE(SOUND_MIXER_I2S)
255
256 /* --------------------------------------------------------------------- */
257
258 struct it8172_state {
259         /* list of it8172 devices */
260         struct list_head devs;
261
262         /* the corresponding pci_dev structure */
263         struct pci_dev *dev;
264
265         /* soundcore stuff */
266         int dev_audio;
267
268         /* hardware resources */
269         unsigned long io;
270         unsigned int irq;
271
272         /* PCI ID's */
273         u16 vendor;
274         u16 device;
275         u8 rev; /* the chip revision */
276
277         /* options */
278         int spdif_volume; /* S/PDIF output is enabled if != -1 */
279         int i2s_volume;   /* current I2S out volume, in OSS format */
280         int i2s_recording;/* 1 = recording from I2S, 0 = not */
281     
282 #ifdef IT8172_DEBUG
283         /* debug /proc entry */
284         struct proc_dir_entry *ps;
285         struct proc_dir_entry *ac97_ps;
286 #endif /* IT8172_DEBUG */
287
288         struct ac97_codec codec;
289
290         unsigned short pcc, capcc;
291         unsigned dacrate, adcrate;
292
293         spinlock_t lock;
294         struct semaphore open_sem;
295         mode_t open_mode;
296         wait_queue_head_t open_wait;
297
298         struct dmabuf {
299                 void *rawbuf;
300                 dma_addr_t dmaaddr;
301                 unsigned buforder;
302                 unsigned numfrag;
303                 unsigned fragshift;
304                 void* nextIn;
305                 void* nextOut;
306                 int count;
307                 int curBufPtr;
308                 unsigned total_bytes;
309                 unsigned error; /* over/underrun */
310                 wait_queue_head_t wait;
311                 /* redundant, but makes calculations easier */
312                 unsigned fragsize;
313                 unsigned dmasize;
314                 unsigned fragsamples;
315                 /* OSS stuff */
316                 unsigned mapped:1;
317                 unsigned ready:1;
318                 unsigned stopped:1;
319                 unsigned ossfragshift;
320                 int ossmaxfrags;
321                 unsigned subdivision;
322         } dma_dac, dma_adc;
323 };
324
325 /* --------------------------------------------------------------------- */
326
327 static LIST_HEAD(devs);
328
329 /* --------------------------------------------------------------------- */
330
331 static inline unsigned ld2(unsigned int x)
332 {
333         unsigned r = 0;
334         
335         if (x >= 0x10000) {
336                 x >>= 16;
337                 r += 16;
338         }
339         if (x >= 0x100) {
340                 x >>= 8;
341                 r += 8;
342         }
343         if (x >= 0x10) {
344                 x >>= 4;
345                 r += 4;
346         }
347         if (x >= 4) {
348                 x >>= 2;
349                 r += 2;
350         }
351         if (x >= 2)
352                 r++;
353         return r;
354 }
355
356 /* --------------------------------------------------------------------- */
357
358 static void it8172_delay(int msec)
359 {
360         unsigned long tmo;
361         signed long tmo2;
362
363         if (in_interrupt())
364                 return;
365     
366         tmo = jiffies + (msec*HZ)/1000;
367         for (;;) {
368                 tmo2 = tmo - jiffies;
369                 if (tmo2 <= 0)
370                         break;
371                 schedule_timeout(tmo2);
372         }
373 }
374
375
376 static unsigned short
377 get_compat_rate(unsigned* rate)
378 {
379         unsigned rate_out = *rate;
380         unsigned short sr;
381     
382         if (rate_out >= 46050) {
383                 sr = CC_SR_48000; rate_out = 48000;
384         } else if (rate_out >= 41250) {
385                 sr = CC_SR_44100; rate_out = 44100;
386         } else if (rate_out >= 35200) {
387                 sr = CC_SR_38400; rate_out = 38400;
388         } else if (rate_out >= 27025) {
389                 sr = CC_SR_32000; rate_out = 32000;
390         } else if (rate_out >= 20625) {
391                 sr = CC_SR_22050; rate_out = 22050;
392         } else if (rate_out >= 17600) {
393                 sr = CC_SR_19200; rate_out = 19200;
394         } else if (rate_out >= 13513) {
395                 sr = CC_SR_16000; rate_out = 16000;
396         } else if (rate_out >= 10313) {
397                 sr = CC_SR_11025; rate_out = 11025;
398         } else if (rate_out >= 8800) {
399                 sr = CC_SR_9600; rate_out = 9600;
400         } else if (rate_out >= 6750) {
401                 sr = CC_SR_8000; rate_out = 8000;
402         } else {
403                 sr = CC_SR_5500; rate_out = 5500;
404         }
405
406         *rate = rate_out;
407         return sr;
408 }
409
410 static void set_adc_rate(struct it8172_state *s, unsigned rate)
411 {
412         unsigned long flags;
413         unsigned short sr;
414     
415         sr = get_compat_rate(&rate);
416
417         spin_lock_irqsave(&s->lock, flags);
418         s->capcc &= ~CC_SR_MASK;
419         s->capcc |= sr;
420         outw(s->capcc, s->io+IT_AC_CAPCC);
421         spin_unlock_irqrestore(&s->lock, flags);
422
423         s->adcrate = rate;
424 }
425
426
427 static void set_dac_rate(struct it8172_state *s, unsigned rate)
428 {
429         unsigned long flags;
430         unsigned short sr;
431     
432         sr = get_compat_rate(&rate);
433
434         spin_lock_irqsave(&s->lock, flags);
435         s->pcc &= ~CC_SR_MASK;
436         s->pcc |= sr;
437         outw(s->pcc, s->io+IT_AC_PCC);
438         spin_unlock_irqrestore(&s->lock, flags);
439
440         s->dacrate = rate;
441 }
442
443
444 /* --------------------------------------------------------------------- */
445
446 static u16 rdcodec(struct ac97_codec *codec, u8 addr)
447 {
448         struct it8172_state *s = (struct it8172_state *)codec->private_data;
449         unsigned long flags;
450         unsigned short circp, data;
451         int i;
452     
453         spin_lock_irqsave(&s->lock, flags);
454
455         for (i = 0; i < POLL_COUNT; i++)
456                 if (!(inw(s->io+IT_AC_CIRCP) & CIRCP_CPS))
457                         break;
458         if (i == POLL_COUNT)
459                 err("rdcodec: codec ready poll expired!");
460
461         circp = addr & CIRCP_CIA_MASK;
462         circp |= (codec->id << CIRCP_CID_BIT);
463         circp |= CIRCP_RWC; // read command
464         outw(circp, s->io+IT_AC_CIRCP);
465
466         /* now wait for the data */
467         for (i = 0; i < POLL_COUNT; i++)
468                 if (inw(s->io+IT_AC_CIRCP) & CIRCP_DPVF)
469                         break;
470         if (i == POLL_COUNT)
471                 err("rdcodec: read poll expired!");
472
473         data = inw(s->io+IT_AC_CIRDP);
474         spin_unlock_irqrestore(&s->lock, flags);
475
476         return data;
477 }
478
479
480 static void wrcodec(struct ac97_codec *codec, u8 addr, u16 data)
481 {
482         struct it8172_state *s = (struct it8172_state *)codec->private_data;
483         unsigned long flags;
484         unsigned short circp;
485         int i;
486     
487         spin_lock_irqsave(&s->lock, flags);
488
489         for (i = 0; i < POLL_COUNT; i++)
490                 if (!(inw(s->io+IT_AC_CIRCP) & CIRCP_CPS))
491                         break;
492         if (i == POLL_COUNT)
493                 err("wrcodec: codec ready poll expired!");
494
495         circp = addr & CIRCP_CIA_MASK;
496         circp |= (codec->id << CIRCP_CID_BIT);
497         circp &= ~CIRCP_RWC; // write command
498
499         outw(data,  s->io+IT_AC_CIRDP);  // send data first
500         outw(circp, s->io+IT_AC_CIRCP);
501
502         spin_unlock_irqrestore(&s->lock, flags);
503 }
504
505
506 static void waitcodec(struct ac97_codec *codec)
507 {
508         unsigned short temp;
509
510         /* codec_wait is used to wait for a ready state after
511            an AC97_RESET. */
512         it8172_delay(10);
513
514         temp = rdcodec(codec, 0x26);
515
516         // If power down, power up
517         if (temp & 0x3f00) {
518                 // Power on
519                 wrcodec(codec, 0x26, 0);
520                 it8172_delay(100);
521                 // Reread
522                 temp = rdcodec(codec, 0x26);
523         }
524     
525         // Check if Codec REF,ANL,DAC,ADC ready***/
526         if ((temp & 0x3f0f) != 0x000f) {
527                 err("codec reg 26 status (0x%x) not ready!!", temp);
528                 return;
529         }
530 }
531
532
533 /* --------------------------------------------------------------------- */
534
535 static inline void stop_adc(struct it8172_state *s)
536 {
537         struct dmabuf* db = &s->dma_adc;
538         unsigned long flags;
539         unsigned char imc;
540     
541         if (db->stopped)
542                 return;
543
544         spin_lock_irqsave(&s->lock, flags);
545
546         s->capcc &= ~(CC_CA | CC_CP | CC_CB2L | CC_CB1L);
547         s->capcc |= CC_CSP;
548         outw(s->capcc, s->io+IT_AC_CAPCC);
549     
550         // disable capture interrupt
551         imc = inb(s->io+IT_AC_IMC);
552         outb(imc | IMC_CCIM, s->io+IT_AC_IMC);
553
554         db->stopped = 1;
555
556         spin_unlock_irqrestore(&s->lock, flags);
557 }       
558
559 static inline void stop_dac(struct it8172_state *s)
560 {
561         struct dmabuf* db = &s->dma_dac;
562         unsigned long flags;
563         unsigned char imc;
564     
565         if (db->stopped)
566                 return;
567
568         spin_lock_irqsave(&s->lock, flags);
569
570         s->pcc &= ~(CC_CA | CC_CP | CC_CB2L | CC_CB1L);
571         s->pcc |= CC_CSP;
572         outw(s->pcc, s->io+IT_AC_PCC);
573     
574         // disable playback interrupt
575         imc = inb(s->io+IT_AC_IMC);
576         outb(imc | IMC_PCIM, s->io+IT_AC_IMC);
577
578         db->stopped = 1;
579     
580         spin_unlock_irqrestore(&s->lock, flags);
581 }       
582
583 static void start_dac(struct it8172_state *s)
584 {
585         struct dmabuf* db = &s->dma_dac;
586         unsigned long flags;
587         unsigned char imc;
588         unsigned long buf1, buf2;
589     
590         if (!db->stopped)
591                 return;
592     
593         spin_lock_irqsave(&s->lock, flags);
594
595         // reset Buffer 1 and 2 pointers to nextOut and nextOut+fragsize
596         buf1 = virt_to_bus(db->nextOut);
597         buf2 = buf1 + db->fragsize;
598         if (buf2 >= db->dmaaddr + db->dmasize)
599                 buf2 -= db->dmasize;
600     
601         outl(buf1, s->io+IT_AC_PCB1STA);
602         outl(buf2, s->io+IT_AC_PCB2STA);
603         db->curBufPtr = IT_AC_PCB1STA;
604     
605         // enable playback interrupt
606         imc = inb(s->io+IT_AC_IMC);
607         outb(imc & ~IMC_PCIM, s->io+IT_AC_IMC);
608
609         s->pcc &= ~(CC_CSP | CC_CP | CC_CB2L | CC_CB1L);
610         s->pcc |= CC_CA;
611         outw(s->pcc, s->io+IT_AC_PCC);
612     
613         db->stopped = 0;
614
615         spin_unlock_irqrestore(&s->lock, flags);
616 }       
617
618 static void start_adc(struct it8172_state *s)
619 {
620         struct dmabuf* db = &s->dma_adc;
621         unsigned long flags;
622         unsigned char imc;
623         unsigned long buf1, buf2;
624     
625         if (!db->stopped)
626                 return;
627
628         spin_lock_irqsave(&s->lock, flags);
629
630         // reset Buffer 1 and 2 pointers to nextIn and nextIn+fragsize
631         buf1 = virt_to_bus(db->nextIn);
632         buf2 = buf1 + db->fragsize;
633         if (buf2 >= db->dmaaddr + db->dmasize)
634                 buf2 -= db->dmasize;
635     
636         outl(buf1, s->io+IT_AC_CAPB1STA);
637         outl(buf2, s->io+IT_AC_CAPB2STA);
638         db->curBufPtr = IT_AC_CAPB1STA;
639
640         // enable capture interrupt
641         imc = inb(s->io+IT_AC_IMC);
642         outb(imc & ~IMC_CCIM, s->io+IT_AC_IMC);
643
644         s->capcc &= ~(CC_CSP | CC_CP | CC_CB2L | CC_CB1L);
645         s->capcc |= CC_CA;
646         outw(s->capcc, s->io+IT_AC_CAPCC);
647     
648         db->stopped = 0;
649
650         spin_unlock_irqrestore(&s->lock, flags);
651 }       
652
653 /* --------------------------------------------------------------------- */
654
655 #define DMABUF_DEFAULTORDER (17-PAGE_SHIFT)
656 #define DMABUF_MINORDER 1
657
658 static inline void dealloc_dmabuf(struct it8172_state *s, struct dmabuf *db)
659 {
660         struct page *page, *pend;
661
662         if (db->rawbuf) {
663                 /* undo marking the pages as reserved */
664                 pend = virt_to_page(db->rawbuf +
665                                     (PAGE_SIZE << db->buforder) - 1);
666                 for (page = virt_to_page(db->rawbuf); page <= pend; page++)
667                         mem_map_unreserve(page);
668                 pci_free_consistent(s->dev, PAGE_SIZE << db->buforder,
669                                     db->rawbuf, db->dmaaddr);
670         }
671         db->rawbuf = db->nextIn = db->nextOut = NULL;
672         db->mapped = db->ready = 0;
673 }
674
675 static int prog_dmabuf(struct it8172_state *s, struct dmabuf *db,
676                        unsigned rate, unsigned fmt, unsigned reg)
677 {
678         int order;
679         unsigned bytepersec;
680         unsigned bufs;
681         struct page *page, *pend;
682
683         if (!db->rawbuf) {
684                 db->ready = db->mapped = 0;
685                 for (order = DMABUF_DEFAULTORDER;
686                      order >= DMABUF_MINORDER; order--)
687                         if ((db->rawbuf =
688                              pci_alloc_consistent(s->dev,
689                                                   PAGE_SIZE << order,
690                                                   &db->dmaaddr)))
691                                 break;
692                 if (!db->rawbuf)
693                         return -ENOMEM;
694                 db->buforder = order;
695                 /* now mark the pages as reserved;
696                    otherwise remap_page_range doesn't do what we want */
697                 pend = virt_to_page(db->rawbuf +
698                                     (PAGE_SIZE << db->buforder) - 1);
699                 for (page = virt_to_page(db->rawbuf); page <= pend; page++)
700                         mem_map_reserve(page);
701         }
702
703         db->count = 0;
704         db->nextIn = db->nextOut = db->rawbuf;
705     
706         bytepersec = rate << sample_shift[fmt];
707         bufs = PAGE_SIZE << db->buforder;
708         if (db->ossfragshift) {
709                 if ((1000 << db->ossfragshift) < bytepersec)
710                         db->fragshift = ld2(bytepersec/1000);
711                 else
712                         db->fragshift = db->ossfragshift;
713         } else {
714                 db->fragshift = ld2(bytepersec/100/(db->subdivision ?
715                                                     db->subdivision : 1));
716                 if (db->fragshift < 3)
717                         db->fragshift = 3;
718         }
719         db->numfrag = bufs >> db->fragshift;
720         while (db->numfrag < 4 && db->fragshift > 3) {
721                 db->fragshift--;
722                 db->numfrag = bufs >> db->fragshift;
723         }
724         db->fragsize = 1 << db->fragshift;
725         if (db->ossmaxfrags >= 4 && db->ossmaxfrags < db->numfrag)
726                 db->numfrag = db->ossmaxfrags;
727         db->fragsamples = db->fragsize >> sample_shift[fmt];
728         db->dmasize = db->numfrag << db->fragshift;
729         memset(db->rawbuf, (fmt & (CC_DF>>CC_FMT_BIT)) ? 0 : 0x80, bufs);
730     
731 #ifdef IT8172_VERBOSE_DEBUG
732         dbg("rate=%d, fragsize=%d, numfrag=%d, dmasize=%d",
733             rate, db->fragsize, db->numfrag, db->dmasize);
734 #endif
735
736         // set data length register
737         outw(db->fragsize, s->io+reg+2);
738         db->ready = 1;
739
740         return 0;
741 }
742
743 static inline int prog_dmabuf_adc(struct it8172_state *s)
744 {
745         stop_adc(s);
746         return prog_dmabuf(s, &s->dma_adc, s->adcrate,
747                            (s->capcc & CC_FMT_MASK) >> CC_FMT_BIT,
748                            IT_AC_CAPCC);
749 }
750
751 static inline int prog_dmabuf_dac(struct it8172_state *s)
752 {
753         stop_dac(s);
754         return prog_dmabuf(s, &s->dma_dac, s->dacrate,
755                            (s->pcc & CC_FMT_MASK) >> CC_FMT_BIT,
756                            IT_AC_PCC);
757 }
758
759
760 /* hold spinlock for the following! */
761
762 static void it8172_interrupt(int irq, void *dev_id, struct pt_regs *regs)
763 {
764         struct it8172_state *s = (struct it8172_state *)dev_id;
765         struct dmabuf* dac = &s->dma_dac;
766         struct dmabuf* adc = &s->dma_adc;
767         unsigned char isc, vs;
768         unsigned short vol, mute;
769         unsigned long newptr;
770     
771         spin_lock(&s->lock);
772
773         isc = inb(s->io+IT_AC_ISC);
774
775         /* fastpath out, to ease interrupt sharing */
776         if (!(isc & (ISC_VCI | ISC_CCI | ISC_PCI))) {
777                 spin_unlock(&s->lock);
778                 return;
779         }
780     
781         /* clear audio interrupts first */
782         outb(isc | ISC_VCI | ISC_CCI | ISC_PCI, s->io+IT_AC_ISC);
783     
784         /* handle volume button events (ignore if S/PDIF enabled) */
785         if ((isc & ISC_VCI) && s->spdif_volume == -1) {
786                 vs = inb(s->io+IT_AC_VS);
787                 outb(0, s->io+IT_AC_VS);
788                 vol = inw(s->io+IT_AC_PCMOV);
789                 mute = vol & PCMOV_PCMOM;
790                 vol &= PCMOV_PCMLCG_MASK;
791                 if ((vs & VS_VUP) && vol > 0)
792                         vol--;
793                 if ((vs & VS_VDP) && vol < 0x1f)
794                         vol++;
795                 vol |= (vol << PCMOV_PCMRCG_BIT);
796                 if (vs & VS_VMP)
797                         vol |= (mute ^ PCMOV_PCMOM);
798                 outw(vol, s->io+IT_AC_PCMOV);
799         }
800     
801         /* update capture pointers */
802         if (isc & ISC_CCI) {
803                 if (adc->count > adc->dmasize - adc->fragsize) {
804                         // Overrun. Stop ADC and log the error
805                         stop_adc(s);
806                         adc->error++;
807                         dbg("adc overrun");
808                 } else {
809                         newptr = virt_to_bus(adc->nextIn) + 2*adc->fragsize;
810                         if (newptr >= adc->dmaaddr + adc->dmasize)
811                                 newptr -= adc->dmasize;
812             
813                         outl(newptr, s->io+adc->curBufPtr);
814                         adc->curBufPtr = (adc->curBufPtr == IT_AC_CAPB1STA) ?
815                                 IT_AC_CAPB2STA : IT_AC_CAPB1STA;
816             
817                         adc->nextIn += adc->fragsize;
818                         if (adc->nextIn >= adc->rawbuf + adc->dmasize)
819                                 adc->nextIn -= adc->dmasize;
820             
821                         adc->count += adc->fragsize;
822                         adc->total_bytes += adc->fragsize;
823
824                         /* wake up anybody listening */
825                         if (waitqueue_active(&adc->wait))
826                                 wake_up_interruptible(&adc->wait);
827                 }
828         }
829     
830         /* update playback pointers */
831         if (isc & ISC_PCI) {
832                 newptr = virt_to_bus(dac->nextOut) + 2*dac->fragsize;
833                 if (newptr >= dac->dmaaddr + dac->dmasize)
834                         newptr -= dac->dmasize;
835         
836                 outl(newptr, s->io+dac->curBufPtr);
837                 dac->curBufPtr = (dac->curBufPtr == IT_AC_PCB1STA) ?
838                         IT_AC_PCB2STA : IT_AC_PCB1STA;
839         
840                 dac->nextOut += dac->fragsize;
841                 if (dac->nextOut >= dac->rawbuf + dac->dmasize)
842                         dac->nextOut -= dac->dmasize;
843         
844                 dac->count -= dac->fragsize;
845                 dac->total_bytes += dac->fragsize;
846
847                 /* wake up anybody listening */
848                 if (waitqueue_active(&dac->wait))
849                         wake_up_interruptible(&dac->wait);
850         
851                 if (dac->count <= 0)
852                         stop_dac(s);
853         }
854     
855         spin_unlock(&s->lock);
856 }
857
858 /* --------------------------------------------------------------------- */
859
860 static loff_t it8172_llseek(struct file *file, loff_t offset, int origin)
861 {
862         return -ESPIPE;
863 }
864
865
866 static int it8172_open_mixdev(struct inode *inode, struct file *file)
867 {
868         int minor = MINOR(inode->i_rdev);
869         struct list_head *list;
870         struct it8172_state *s;
871
872         for (list = devs.next; ; list = list->next) {
873                 if (list == &devs)
874                         return -ENODEV;
875                 s = list_entry(list, struct it8172_state, devs);
876                 if (s->codec.dev_mixer == minor)
877                         break;
878         }
879         file->private_data = s;
880         return 0;
881 }
882
883 static int it8172_release_mixdev(struct inode *inode, struct file *file)
884 {
885         return 0;
886 }
887
888
889 static u16
890 cvt_ossvol(unsigned int gain)
891 {
892         u16 ret;
893     
894         if (gain == 0)
895                 return 0;
896     
897         if (gain > 100)
898                 gain = 100;
899     
900         ret = (100 - gain + 32) / 4;
901         ret = ret > 31 ? 31 : ret;
902         return ret;
903 }
904
905
906 static int mixdev_ioctl(struct ac97_codec *codec, unsigned int cmd,
907                         unsigned long arg)
908 {
909         struct it8172_state *s = (struct it8172_state *)codec->private_data;
910         unsigned int left, right;
911         unsigned long flags;
912         int val;
913         u16 vol;
914     
915         /*
916          * When we are in S/PDIF mode, we want to disable any analog output so
917          * we filter the master/PCM channel volume ioctls.
918          *
919          * Also filter I2S channel, which AC'97 knows nothing about.
920          */
921
922         switch (cmd) {
923         case SOUND_MIXER_WRITE_VOLUME:
924                 // if not in S/PDIF mode, pass to AC'97
925                 if (s->spdif_volume == -1)
926                         break;
927                 return 0;
928         case SOUND_MIXER_WRITE_PCM:
929                 // if not in S/PDIF mode, pass to AC'97
930                 if (s->spdif_volume == -1)
931                         break;
932                 if (get_user(val, (int *)arg))
933                         return -EFAULT;
934                 right = ((val >> 8)  & 0xff);
935                 left = (val  & 0xff);
936                 if (right > 100)
937                         right = 100;
938                 if (left > 100)
939                         left = 100;
940                 s->spdif_volume = (right << 8) | left;
941                 vol = cvt_ossvol(left);
942                 vol |= (cvt_ossvol(right) << PCMOV_PCMRCG_BIT);
943                 if (vol == 0)
944                         vol = PCMOV_PCMOM; // mute
945                 spin_lock_irqsave(&s->lock, flags);
946                 outw(vol, s->io+IT_AC_PCMOV);
947                 spin_unlock_irqrestore(&s->lock, flags);
948                 return put_user(s->spdif_volume, (int *)arg);
949         case SOUND_MIXER_READ_PCM:
950                 // if not in S/PDIF mode, pass to AC'97
951                 if (s->spdif_volume == -1)
952                         break;
953                 return put_user(s->spdif_volume, (int *)arg);
954         case SOUND_MIXER_WRITE_I2S:
955                 if (get_user(val, (int *)arg))
956                         return -EFAULT;
957                 right = ((val >> 8)  & 0xff);
958                 left = (val  & 0xff);
959                 if (right > 100)
960                         right = 100;
961                 if (left > 100)
962                         left = 100;
963                 s->i2s_volume = (right << 8) | left;
964                 vol = cvt_ossvol(left);
965                 vol |= (cvt_ossvol(right) << I2SV_I2SRCG_BIT);
966                 if (vol == 0)
967                         vol = I2SV_I2SOM; // mute
968                 outw(vol, s->io+IT_AC_I2SV);
969                 return put_user(s->i2s_volume, (int *)arg);
970         case SOUND_MIXER_READ_I2S:
971                 return put_user(s->i2s_volume, (int *)arg);
972         case SOUND_MIXER_WRITE_RECSRC:
973                 if (get_user(val, (int *)arg))
974                         return -EFAULT;
975                 if (val & SOUND_MASK_I2S) {
976                         s->i2s_recording = 1;
977                         outb(DRSS_I2S, s->io+IT_AC_DRSS);
978                         return 0;
979                 } else {
980                         s->i2s_recording = 0;
981                         outb(DRSS_AC97_PRIM, s->io+IT_AC_DRSS);
982                         // now let AC'97 select record source
983                         break;
984                 }
985         case SOUND_MIXER_READ_RECSRC:
986                 if (s->i2s_recording)
987                         return put_user(SOUND_MASK_I2S, (int *)arg);
988                 else
989                         // let AC'97 report recording source
990                         break;
991         }
992
993         return codec->mixer_ioctl(codec, cmd, arg);
994 }
995
996 static int it8172_ioctl_mixdev(struct inode *inode, struct file *file,
997                                unsigned int cmd, unsigned long arg)
998 {
999         struct it8172_state *s = (struct it8172_state *)file->private_data;
1000         struct ac97_codec *codec = &s->codec;
1001
1002         return mixdev_ioctl(codec, cmd, arg);
1003 }
1004
1005 static /*const*/ struct file_operations it8172_mixer_fops = {
1006         owner:  THIS_MODULE,
1007         llseek: it8172_llseek,
1008         ioctl:  it8172_ioctl_mixdev,
1009         open:   it8172_open_mixdev,
1010         release:        it8172_release_mixdev,
1011 };
1012
1013 /* --------------------------------------------------------------------- */
1014
1015 static int drain_dac(struct it8172_state *s, int nonblock)
1016 {
1017         unsigned long flags;
1018         int count, tmo;
1019         
1020         if (s->dma_dac.mapped || !s->dma_dac.ready || s->dma_dac.stopped)
1021                 return 0;
1022
1023         for (;;) {
1024                 spin_lock_irqsave(&s->lock, flags);
1025                 count = s->dma_dac.count;
1026                 spin_unlock_irqrestore(&s->lock, flags);
1027                 if (count <= 0)
1028                         break;
1029                 if (signal_pending(current))
1030                         break;
1031                 //if (nonblock)
1032                 //return -EBUSY;
1033                 tmo = 1000 * count / s->dacrate;
1034                 tmo >>= sample_shift[(s->pcc & CC_FMT_MASK) >> CC_FMT_BIT];
1035                 it8172_delay(tmo);
1036         }
1037         if (signal_pending(current))
1038                 return -ERESTARTSYS;
1039         return 0;
1040 }
1041
1042 /* --------------------------------------------------------------------- */
1043
1044
1045 /*
1046  * Copy audio data to/from user buffer from/to dma buffer, taking care
1047  * that we wrap when reading/writing the dma buffer. Returns actual byte
1048  * count written to or read from the dma buffer.
1049  */
1050 static int copy_dmabuf_user(struct dmabuf *db, char* userbuf,
1051                             int count, int to_user)
1052 {
1053         char* bufptr = to_user ? db->nextOut : db->nextIn;
1054         char* bufend = db->rawbuf + db->dmasize;
1055         
1056         if (bufptr + count > bufend) {
1057                 int partial = (int)(bufend - bufptr);
1058                 if (to_user) {
1059                         if (copy_to_user(userbuf, bufptr, partial))
1060                                 return -EFAULT;
1061                         if (copy_to_user(userbuf + partial, db->rawbuf,
1062                                          count - partial))
1063                                 return -EFAULT;
1064                 } else {
1065                         if (copy_from_user(bufptr, userbuf, partial))
1066                                 return -EFAULT;
1067                         if (copy_from_user(db->rawbuf,
1068                                            userbuf + partial,
1069                                            count - partial))
1070                                 return -EFAULT;
1071                 }
1072         } else {
1073                 if (to_user) {
1074                         if (copy_to_user(userbuf, bufptr, count))
1075                                 return -EFAULT;
1076                 } else {
1077                         if (copy_from_user(bufptr, userbuf, count))
1078                                 return -EFAULT;
1079                 }
1080         }
1081         
1082         return count;
1083 }
1084
1085
1086 static ssize_t it8172_read(struct file *file, char *buffer,
1087                            size_t count, loff_t *ppos)
1088 {
1089         struct it8172_state *s = (struct it8172_state *)file->private_data;
1090         struct dmabuf *db = &s->dma_adc;
1091         ssize_t ret;
1092         unsigned long flags;
1093         int cnt, remainder, avail;
1094
1095         if (ppos != &file->f_pos)
1096                 return -ESPIPE;
1097         if (db->mapped)
1098                 return -ENXIO;
1099         if (!access_ok(VERIFY_WRITE, buffer, count))
1100                 return -EFAULT;
1101         ret = 0;
1102
1103         while (count > 0) {
1104                 // wait for samples in capture buffer
1105                 do {
1106                         spin_lock_irqsave(&s->lock, flags);
1107                         if (db->stopped)
1108                                 start_adc(s);
1109                         avail = db->count;
1110                         spin_unlock_irqrestore(&s->lock, flags);
1111                         if (avail <= 0) {
1112                                 if (file->f_flags & O_NONBLOCK) {
1113                                         if (!ret)
1114                                                 ret = -EAGAIN;
1115                                         return ret;
1116                                 }
1117                                 interruptible_sleep_on(&db->wait);
1118                                 if (signal_pending(current)) {
1119                                         if (!ret)
1120                                                 ret = -ERESTARTSYS;
1121                                         return ret;
1122                                 }
1123                         }
1124                 } while (avail <= 0);
1125
1126                 // copy from nextOut to user
1127                 if ((cnt = copy_dmabuf_user(db, buffer, count > avail ?
1128                                             avail : count, 1)) < 0) {
1129                         if (!ret)
1130                                 ret = -EFAULT;
1131                         return ret;
1132                 }
1133
1134                 spin_lock_irqsave(&s->lock, flags);
1135                 db->count -= cnt;
1136                 spin_unlock_irqrestore(&s->lock, flags);
1137
1138                 db->nextOut += cnt;
1139                 if (db->nextOut >= db->rawbuf + db->dmasize)
1140                         db->nextOut -= db->dmasize;     
1141
1142                 count -= cnt;
1143                 buffer += cnt;
1144                 ret += cnt;
1145         } // while (count > 0)
1146
1147         /*
1148          * See if the dma buffer count after this read call is
1149          * aligned on a fragsize boundary. If not, read from
1150          * buffer until we reach a boundary, and let's hope this
1151          * is just the last remainder of an audio record. If not
1152          * it means the user is not reading in fragsize chunks, in
1153          * which case it's his/her fault that there are audio gaps
1154          * in their record.
1155          */
1156         spin_lock_irqsave(&s->lock, flags);
1157         remainder = db->count % db->fragsize;
1158         if (remainder) {
1159                 db->nextOut += remainder;
1160                 if (db->nextOut >= db->rawbuf + db->dmasize)
1161                         db->nextOut -= db->dmasize;
1162                 db->count -= remainder;
1163         }
1164         spin_unlock_irqrestore(&s->lock, flags);
1165
1166         return ret;
1167 }
1168
1169 static ssize_t it8172_write(struct file *file, const char *buffer,
1170                             size_t count, loff_t *ppos)
1171 {
1172         struct it8172_state *s = (struct it8172_state *)file->private_data;
1173         struct dmabuf *db = &s->dma_dac;
1174         ssize_t ret;
1175         unsigned long flags;
1176         int cnt, remainder, avail;
1177
1178         if (ppos != &file->f_pos)
1179                 return -ESPIPE;
1180         if (db->mapped)
1181                 return -ENXIO;
1182         if (!access_ok(VERIFY_READ, buffer, count))
1183                 return -EFAULT;
1184         ret = 0;
1185     
1186         while (count > 0) {
1187                 // wait for space in playback buffer
1188                 do {
1189                         spin_lock_irqsave(&s->lock, flags);
1190                         avail = db->dmasize - db->count;
1191                         spin_unlock_irqrestore(&s->lock, flags);
1192                         if (avail <= 0) {
1193                                 if (file->f_flags & O_NONBLOCK) {
1194                                         if (!ret)
1195                                                 ret = -EAGAIN;
1196                                         return ret;
1197                                 }
1198                                 interruptible_sleep_on(&db->wait);
1199                                 if (signal_pending(current)) {
1200                                         if (!ret)
1201                                                 ret = -ERESTARTSYS;
1202                                         return ret;
1203                                 }
1204                         }
1205                 } while (avail <= 0);
1206         
1207                 // copy to nextIn
1208                 if ((cnt = copy_dmabuf_user(db, (char*)buffer,
1209                                             count > avail ?
1210                                             avail : count, 0)) < 0) {
1211                         if (!ret)
1212                                 ret = -EFAULT;
1213                         return ret;
1214                 }
1215
1216                 spin_lock_irqsave(&s->lock, flags);
1217                 db->count += cnt;
1218                 if (db->stopped)
1219                         start_dac(s);
1220                 spin_unlock_irqrestore(&s->lock, flags);
1221         
1222                 db->nextIn += cnt;
1223                 if (db->nextIn >= db->rawbuf + db->dmasize)
1224                         db->nextIn -= db->dmasize;
1225         
1226                 count -= cnt;
1227                 buffer += cnt;
1228                 ret += cnt;
1229         } // while (count > 0)
1230         
1231         /*
1232          * See if the dma buffer count after this write call is
1233          * aligned on a fragsize boundary. If not, fill buffer
1234          * with silence to the next boundary, and let's hope this
1235          * is just the last remainder of an audio playback. If not
1236          * it means the user is not sending us fragsize chunks, in
1237          * which case it's his/her fault that there are audio gaps
1238          * in their playback.
1239          */
1240         spin_lock_irqsave(&s->lock, flags);
1241         remainder = db->count % db->fragsize;
1242         if (remainder) {
1243                 int fill_cnt = db->fragsize - remainder;
1244                 memset(db->nextIn, 0, fill_cnt);
1245                 db->nextIn += fill_cnt;
1246                 if (db->nextIn >= db->rawbuf + db->dmasize)
1247                         db->nextIn -= db->dmasize;
1248                 db->count += fill_cnt;
1249         }
1250         spin_unlock_irqrestore(&s->lock, flags);
1251
1252         return ret;
1253 }
1254
1255 /* No kernel lock - we have our own spinlock */
1256 static unsigned int it8172_poll(struct file *file,
1257                                 struct poll_table_struct *wait)
1258 {
1259         struct it8172_state *s = (struct it8172_state *)file->private_data;
1260         unsigned long flags;
1261         unsigned int mask = 0;
1262
1263         if (file->f_mode & FMODE_WRITE) {
1264                 if (!s->dma_dac.ready)
1265                         return 0;
1266                 poll_wait(file, &s->dma_dac.wait, wait);
1267         }
1268         if (file->f_mode & FMODE_READ) {
1269                 if (!s->dma_adc.ready)
1270                         return 0;
1271                 poll_wait(file, &s->dma_adc.wait, wait);
1272         }
1273         
1274         spin_lock_irqsave(&s->lock, flags);
1275         if (file->f_mode & FMODE_READ) {
1276                 if (s->dma_adc.count >= (signed)s->dma_adc.fragsize)
1277                         mask |= POLLIN | POLLRDNORM;
1278         }
1279         if (file->f_mode & FMODE_WRITE) {
1280                 if (s->dma_dac.mapped) {
1281                         if (s->dma_dac.count >= (signed)s->dma_dac.fragsize) 
1282                                 mask |= POLLOUT | POLLWRNORM;
1283                 } else {
1284                         if ((signed)s->dma_dac.dmasize >=
1285                             s->dma_dac.count + (signed)s->dma_dac.fragsize)
1286                                 mask |= POLLOUT | POLLWRNORM;
1287                 }
1288         }
1289         spin_unlock_irqrestore(&s->lock, flags);
1290         return mask;
1291 }
1292
1293 static int it8172_mmap(struct file *file, struct vm_area_struct *vma)
1294 {
1295         struct it8172_state *s = (struct it8172_state *)file->private_data;
1296         struct dmabuf *db;
1297         unsigned long size;
1298
1299         lock_kernel();
1300         if (vma->vm_flags & VM_WRITE)
1301                 db = &s->dma_dac;
1302         else if (vma->vm_flags & VM_READ)
1303                 db = &s->dma_adc;
1304         else {
1305                 unlock_kernel();
1306                 return -EINVAL;
1307         }
1308         if (vma->vm_pgoff != 0) {
1309                 unlock_kernel();
1310                 return -EINVAL;
1311         }
1312         size = vma->vm_end - vma->vm_start;
1313         if (size > (PAGE_SIZE << db->buforder)) {
1314                 unlock_kernel();
1315                 return -EINVAL;
1316         }
1317         if (remap_page_range(vma->vm_start, virt_to_phys(db->rawbuf),
1318                              size, vma->vm_page_prot)) {
1319                 unlock_kernel();
1320                 return -EAGAIN;
1321         }
1322         db->mapped = 1;
1323         unlock_kernel();
1324         return 0;
1325 }
1326
1327
1328 #ifdef IT8172_VERBOSE_DEBUG
1329 static struct ioctl_str_t {
1330         unsigned int cmd;
1331         const char* str;
1332 } ioctl_str[] = {
1333         {SNDCTL_DSP_RESET, "SNDCTL_DSP_RESET"},
1334         {SNDCTL_DSP_SYNC, "SNDCTL_DSP_SYNC"},
1335         {SNDCTL_DSP_SPEED, "SNDCTL_DSP_SPEED"},
1336         {SNDCTL_DSP_STEREO, "SNDCTL_DSP_STEREO"},
1337         {SNDCTL_DSP_GETBLKSIZE, "SNDCTL_DSP_GETBLKSIZE"},
1338         {SNDCTL_DSP_SAMPLESIZE, "SNDCTL_DSP_SAMPLESIZE"},
1339         {SNDCTL_DSP_CHANNELS, "SNDCTL_DSP_CHANNELS"},
1340         {SOUND_PCM_WRITE_CHANNELS, "SOUND_PCM_WRITE_CHANNELS"},
1341         {SOUND_PCM_WRITE_FILTER, "SOUND_PCM_WRITE_FILTER"},
1342         {SNDCTL_DSP_POST, "SNDCTL_DSP_POST"},
1343         {SNDCTL_DSP_SUBDIVIDE, "SNDCTL_DSP_SUBDIVIDE"},
1344         {SNDCTL_DSP_SETFRAGMENT, "SNDCTL_DSP_SETFRAGMENT"},
1345         {SNDCTL_DSP_GETFMTS, "SNDCTL_DSP_GETFMTS"},
1346         {SNDCTL_DSP_SETFMT, "SNDCTL_DSP_SETFMT"},
1347         {SNDCTL_DSP_GETOSPACE, "SNDCTL_DSP_GETOSPACE"},
1348         {SNDCTL_DSP_GETISPACE, "SNDCTL_DSP_GETISPACE"},
1349         {SNDCTL_DSP_NONBLOCK, "SNDCTL_DSP_NONBLOCK"},
1350         {SNDCTL_DSP_GETCAPS, "SNDCTL_DSP_GETCAPS"},
1351         {SNDCTL_DSP_GETTRIGGER, "SNDCTL_DSP_GETTRIGGER"},
1352         {SNDCTL_DSP_SETTRIGGER, "SNDCTL_DSP_SETTRIGGER"},
1353         {SNDCTL_DSP_GETIPTR, "SNDCTL_DSP_GETIPTR"},
1354         {SNDCTL_DSP_GETOPTR, "SNDCTL_DSP_GETOPTR"},
1355         {SNDCTL_DSP_MAPINBUF, "SNDCTL_DSP_MAPINBUF"},
1356         {SNDCTL_DSP_MAPOUTBUF, "SNDCTL_DSP_MAPOUTBUF"},
1357         {SNDCTL_DSP_SETSYNCRO, "SNDCTL_DSP_SETSYNCRO"},
1358         {SNDCTL_DSP_SETDUPLEX, "SNDCTL_DSP_SETDUPLEX"},
1359         {SNDCTL_DSP_GETODELAY, "SNDCTL_DSP_GETODELAY"},
1360         {SNDCTL_DSP_GETCHANNELMASK, "SNDCTL_DSP_GETCHANNELMASK"},
1361         {SNDCTL_DSP_BIND_CHANNEL, "SNDCTL_DSP_BIND_CHANNEL"},
1362         {OSS_GETVERSION, "OSS_GETVERSION"},
1363         {SOUND_PCM_READ_RATE, "SOUND_PCM_READ_RATE"},
1364         {SOUND_PCM_READ_CHANNELS, "SOUND_PCM_READ_CHANNELS"},
1365         {SOUND_PCM_READ_BITS, "SOUND_PCM_READ_BITS"},
1366         {SOUND_PCM_READ_FILTER, "SOUND_PCM_READ_FILTER"}
1367 };
1368 #endif    
1369
1370 static int it8172_ioctl(struct inode *inode, struct file *file,
1371                         unsigned int cmd, unsigned long arg)
1372 {
1373         struct it8172_state *s = (struct it8172_state *)file->private_data;
1374         unsigned long flags;
1375         audio_buf_info abinfo;
1376         count_info cinfo;
1377         int count;
1378         int val, mapped, ret, diff;
1379
1380         mapped = ((file->f_mode & FMODE_WRITE) && s->dma_dac.mapped) ||
1381                 ((file->f_mode & FMODE_READ) && s->dma_adc.mapped);
1382
1383 #ifdef IT8172_VERBOSE_DEBUG
1384         for (count=0; count<sizeof(ioctl_str)/sizeof(ioctl_str[0]); count++) {
1385                 if (ioctl_str[count].cmd == cmd)
1386                         break;
1387         }
1388         if (count < sizeof(ioctl_str)/sizeof(ioctl_str[0]))
1389                 dbg("ioctl %s, arg=0x%08x",
1390                     ioctl_str[count].str, (unsigned int)arg);
1391         else
1392                 dbg("ioctl unknown, 0x%x", cmd);
1393 #endif
1394     
1395         switch (cmd) {
1396         case OSS_GETVERSION:
1397                 return put_user(SOUND_VERSION, (int *)arg);
1398
1399         case SNDCTL_DSP_SYNC:
1400                 if (file->f_mode & FMODE_WRITE)
1401                         return drain_dac(s, file->f_flags & O_NONBLOCK);
1402                 return 0;
1403                 
1404         case SNDCTL_DSP_SETDUPLEX:
1405                 return 0;
1406
1407         case SNDCTL_DSP_GETCAPS:
1408                 return put_user(DSP_CAP_DUPLEX | DSP_CAP_REALTIME |
1409                                 DSP_CAP_TRIGGER | DSP_CAP_MMAP, (int *)arg);
1410                 
1411         case SNDCTL_DSP_RESET:
1412                 if (file->f_mode & FMODE_WRITE) {
1413                         stop_dac(s);
1414                         synchronize_irq();
1415                         s->dma_dac.count = s->dma_dac.total_bytes = 0;
1416                         s->dma_dac.nextIn = s->dma_dac.nextOut =
1417                                 s->dma_dac.rawbuf;
1418                 }
1419                 if (file->f_mode & FMODE_READ) {
1420                         stop_adc(s);
1421                         synchronize_irq();
1422                         s->dma_adc.count = s->dma_adc.total_bytes = 0;
1423                         s->dma_adc.nextIn = s->dma_adc.nextOut =
1424                                 s->dma_adc.rawbuf;
1425                 }
1426                 return 0;
1427
1428         case SNDCTL_DSP_SPEED:
1429                 if (get_user(val, (int *)arg))
1430                         return -EFAULT;
1431                 if (val >= 0) {
1432                         if (file->f_mode & FMODE_READ) {
1433                                 stop_adc(s);
1434                                 set_adc_rate(s, val);
1435                                 if ((ret = prog_dmabuf_adc(s)))
1436                                         return ret;
1437                         }
1438                         if (file->f_mode & FMODE_WRITE) {
1439                                 stop_dac(s);
1440                                 set_dac_rate(s, val);
1441                                 if ((ret = prog_dmabuf_dac(s)))
1442                                         return ret;
1443                         }
1444                 }
1445                 return put_user((file->f_mode & FMODE_READ) ?
1446                                 s->adcrate : s->dacrate, (int *)arg);
1447
1448         case SNDCTL_DSP_STEREO:
1449                 if (get_user(val, (int *)arg))
1450                         return -EFAULT;
1451                 if (file->f_mode & FMODE_READ) {
1452                         stop_adc(s);
1453                         if (val)
1454                                 s->capcc |= CC_SM;
1455                         else
1456                                 s->capcc &= ~CC_SM;
1457                         outw(s->capcc, s->io+IT_AC_CAPCC);
1458                         if ((ret = prog_dmabuf_adc(s)))
1459                                 return ret;
1460                 }
1461                 if (file->f_mode & FMODE_WRITE) {
1462                         stop_dac(s);
1463                         if (val)
1464                                 s->pcc |= CC_SM;
1465                         else
1466                                 s->pcc &= ~CC_SM;
1467                         outw(s->pcc, s->io+IT_AC_PCC);
1468                         if ((ret = prog_dmabuf_dac(s)))
1469                                 return ret;
1470                 }
1471                 return 0;
1472
1473         case SNDCTL_DSP_CHANNELS:
1474                 if (get_user(val, (int *)arg))
1475                         return -EFAULT;
1476                 if (val != 0) {
1477                         if (file->f_mode & FMODE_READ) {
1478                                 stop_adc(s);
1479                                 if (val >= 2) {
1480                                         val = 2;
1481                                         s->capcc |= CC_SM;
1482                                 }
1483                                 else
1484                                         s->capcc &= ~CC_SM;
1485                                 outw(s->capcc, s->io+IT_AC_CAPCC);
1486                                 if ((ret = prog_dmabuf_adc(s)))
1487                                         return ret;
1488                         }
1489                         if (file->f_mode & FMODE_WRITE) {
1490                                 stop_dac(s);
1491                                 switch (val) {
1492                                 case 1:
1493                                         s->pcc &= ~CC_SM;
1494                                         break;
1495                                 case 2:
1496                                         s->pcc |= CC_SM;
1497                                         break;
1498                                 default:
1499                                         // FIX! support multichannel???
1500                                         val = 2;
1501                                         s->pcc |= CC_SM;
1502                                         break;
1503                                 }
1504                                 outw(s->pcc, s->io+IT_AC_PCC);
1505                                 if ((ret = prog_dmabuf_dac(s)))
1506                                         return ret;
1507                         }
1508                 }
1509                 return put_user(val, (int *)arg);
1510                 
1511         case SNDCTL_DSP_GETFMTS: /* Returns a mask */
1512                 return put_user(AFMT_S16_LE|AFMT_U8, (int *)arg);
1513                 
1514         case SNDCTL_DSP_SETFMT: /* Selects ONE fmt*/
1515                 if (get_user(val, (int *)arg))
1516                         return -EFAULT;
1517                 if (val != AFMT_QUERY) {
1518                         if (file->f_mode & FMODE_READ) {
1519                                 stop_adc(s);
1520                                 if (val == AFMT_S16_LE)
1521                                         s->capcc |= CC_DF;
1522                                 else {
1523                                         val = AFMT_U8;
1524                                         s->capcc &= ~CC_DF;
1525                                 }
1526                                 outw(s->capcc, s->io+IT_AC_CAPCC);
1527                                 if ((ret = prog_dmabuf_adc(s)))
1528                                         return ret;
1529                         }
1530                         if (file->f_mode & FMODE_WRITE) {
1531                                 stop_dac(s);
1532                                 if (val == AFMT_S16_LE)
1533                                         s->pcc |= CC_DF;
1534                                 else {
1535                                         val = AFMT_U8;
1536                                         s->pcc &= ~CC_DF;
1537                                 }
1538                                 outw(s->pcc, s->io+IT_AC_PCC);
1539                                 if ((ret = prog_dmabuf_dac(s)))
1540                                         return ret;
1541                         }
1542                 } else {
1543                         if (file->f_mode & FMODE_READ)
1544                                 val = (s->capcc & CC_DF) ?
1545                                         AFMT_S16_LE : AFMT_U8;
1546                         else
1547                                 val = (s->pcc & CC_DF) ?
1548                                         AFMT_S16_LE : AFMT_U8;
1549                 }
1550                 return put_user(val, (int *)arg);
1551                 
1552         case SNDCTL_DSP_POST:
1553                 return 0;
1554
1555         case SNDCTL_DSP_GETTRIGGER:
1556                 val = 0;
1557                 spin_lock_irqsave(&s->lock, flags);
1558                 if (file->f_mode & FMODE_READ && !s->dma_adc.stopped)
1559                         val |= PCM_ENABLE_INPUT;
1560                 if (file->f_mode & FMODE_WRITE && !s->dma_dac.stopped)
1561                         val |= PCM_ENABLE_OUTPUT;
1562                 spin_unlock_irqrestore(&s->lock, flags);
1563                 return put_user(val, (int *)arg);
1564                 
1565         case SNDCTL_DSP_SETTRIGGER:
1566                 if (get_user(val, (int *)arg))
1567                         return -EFAULT;
1568                 if (file->f_mode & FMODE_READ) {
1569                         if (val & PCM_ENABLE_INPUT)
1570                                 start_adc(s);
1571                         else
1572                                 stop_adc(s);
1573                 }
1574                 if (file->f_mode & FMODE_WRITE) {
1575                         if (val & PCM_ENABLE_OUTPUT)
1576                                 start_dac(s);
1577                         else
1578                                 stop_dac(s);
1579                 }
1580                 return 0;
1581
1582         case SNDCTL_DSP_GETOSPACE:
1583                 if (!(file->f_mode & FMODE_WRITE))
1584                         return -EINVAL;
1585                 abinfo.fragsize = s->dma_dac.fragsize;
1586                 spin_lock_irqsave(&s->lock, flags);
1587                 count = s->dma_dac.count;
1588                 if (!s->dma_dac.stopped)
1589                         count -= (s->dma_dac.fragsize -
1590                                   inw(s->io+IT_AC_PCDL));
1591                 spin_unlock_irqrestore(&s->lock, flags);
1592                 if (count < 0)
1593                         count = 0;
1594                 abinfo.bytes = s->dma_dac.dmasize - count;
1595                 abinfo.fragstotal = s->dma_dac.numfrag;
1596                 abinfo.fragments = abinfo.bytes >> s->dma_dac.fragshift;      
1597                 return copy_to_user((void *)arg, &abinfo, sizeof(abinfo)) ?
1598                         -EFAULT : 0;
1599
1600         case SNDCTL_DSP_GETISPACE:
1601                 if (!(file->f_mode & FMODE_READ))
1602                         return -EINVAL;
1603                 abinfo.fragsize = s->dma_adc.fragsize;
1604                 spin_lock_irqsave(&s->lock, flags);
1605                 count = s->dma_adc.count;
1606                 if (!s->dma_adc.stopped)
1607                         count += (s->dma_adc.fragsize -
1608                                   inw(s->io+IT_AC_CAPCDL));
1609                 spin_unlock_irqrestore(&s->lock, flags);
1610                 if (count < 0)
1611                         count = 0;
1612                 abinfo.bytes = count;
1613                 abinfo.fragstotal = s->dma_adc.numfrag;
1614                 abinfo.fragments = abinfo.bytes >> s->dma_adc.fragshift;      
1615                 return copy_to_user((void *)arg, &abinfo, sizeof(abinfo)) ?
1616                         -EFAULT : 0;
1617                 
1618         case SNDCTL_DSP_NONBLOCK:
1619                 file->f_flags |= O_NONBLOCK;
1620                 return 0;
1621
1622         case SNDCTL_DSP_GETODELAY:
1623                 if (!(file->f_mode & FMODE_WRITE))
1624                         return -EINVAL;
1625                 spin_lock_irqsave(&s->lock, flags);
1626                 count = s->dma_dac.count;
1627                 if (!s->dma_dac.stopped)
1628                         count -= (s->dma_dac.fragsize -
1629                                   inw(s->io+IT_AC_PCDL));
1630                 spin_unlock_irqrestore(&s->lock, flags);
1631                 if (count < 0)
1632                         count = 0;
1633                 return put_user(count, (int *)arg);
1634
1635         case SNDCTL_DSP_GETIPTR:
1636                 if (!(file->f_mode & FMODE_READ))
1637                         return -EINVAL;
1638                 spin_lock_irqsave(&s->lock, flags);
1639                 cinfo.bytes = s->dma_adc.total_bytes;
1640                 count = s->dma_adc.count;
1641                 if (!s->dma_adc.stopped) {
1642                         diff = s->dma_adc.fragsize - inw(s->io+IT_AC_CAPCDL);
1643                         count += diff;
1644                         cinfo.bytes += diff;
1645                         cinfo.ptr = inl(s->io+s->dma_adc.curBufPtr) -
1646                                 s->dma_adc.dmaaddr;
1647                 } else
1648                         cinfo.ptr = virt_to_bus(s->dma_adc.nextIn) -
1649                                 s->dma_adc.dmaaddr;
1650                 if (s->dma_adc.mapped)
1651                         s->dma_adc.count &= s->dma_adc.fragsize-1;
1652                 spin_unlock_irqrestore(&s->lock, flags);
1653                 if (count < 0)
1654                         count = 0;
1655                 cinfo.blocks = count >> s->dma_adc.fragshift;
1656                 return copy_to_user((void *)arg, &cinfo, sizeof(cinfo));
1657
1658         case SNDCTL_DSP_GETOPTR:
1659                 if (!(file->f_mode & FMODE_READ))
1660                         return -EINVAL;
1661                 spin_lock_irqsave(&s->lock, flags);
1662                 cinfo.bytes = s->dma_dac.total_bytes;
1663                 count = s->dma_dac.count;
1664                 if (!s->dma_dac.stopped) {
1665                         diff = s->dma_dac.fragsize - inw(s->io+IT_AC_CAPCDL);
1666                         count -= diff;
1667                         cinfo.bytes += diff;
1668                         cinfo.ptr = inl(s->io+s->dma_dac.curBufPtr) -
1669                                 s->dma_dac.dmaaddr;
1670                 } else
1671                         cinfo.ptr = virt_to_bus(s->dma_dac.nextOut) -
1672                                 s->dma_dac.dmaaddr;
1673                 if (s->dma_dac.mapped)
1674                         s->dma_dac.count &= s->dma_dac.fragsize-1;
1675                 spin_unlock_irqrestore(&s->lock, flags);
1676                 if (count < 0)
1677                         count = 0;
1678                 cinfo.blocks = count >> s->dma_dac.fragshift;
1679                 return copy_to_user((void *)arg, &cinfo, sizeof(cinfo));
1680
1681         case SNDCTL_DSP_GETBLKSIZE:
1682                 if (file->f_mode & FMODE_WRITE)
1683                         return put_user(s->dma_dac.fragsize, (int *)arg);
1684                 else
1685                         return put_user(s->dma_adc.fragsize, (int *)arg);
1686
1687         case SNDCTL_DSP_SETFRAGMENT:
1688                 if (get_user(val, (int *)arg))
1689                         return -EFAULT;
1690                 if (file->f_mode & FMODE_READ) {
1691                         stop_adc(s);
1692                         s->dma_adc.ossfragshift = val & 0xffff;
1693                         s->dma_adc.ossmaxfrags = (val >> 16) & 0xffff;
1694                         if (s->dma_adc.ossfragshift < 4)
1695                                 s->dma_adc.ossfragshift = 4;
1696                         if (s->dma_adc.ossfragshift > 15)
1697                                 s->dma_adc.ossfragshift = 15;
1698                         if (s->dma_adc.ossmaxfrags < 4)
1699                                 s->dma_adc.ossmaxfrags = 4;
1700                         if ((ret = prog_dmabuf_adc(s)))
1701                                 return ret;
1702                 }
1703                 if (file->f_mode & FMODE_WRITE) {
1704                         stop_dac(s);
1705                         s->dma_dac.ossfragshift = val & 0xffff;
1706                         s->dma_dac.ossmaxfrags = (val >> 16) & 0xffff;
1707                         if (s->dma_dac.ossfragshift < 4)
1708                                 s->dma_dac.ossfragshift = 4;
1709                         if (s->dma_dac.ossfragshift > 15)
1710                                 s->dma_dac.ossfragshift = 15;
1711                         if (s->dma_dac.ossmaxfrags < 4)
1712                                 s->dma_dac.ossmaxfrags = 4;
1713                         if ((ret = prog_dmabuf_dac(s)))
1714                                 return ret;
1715                 }
1716                 return 0;
1717
1718         case SNDCTL_DSP_SUBDIVIDE:
1719                 if ((file->f_mode & FMODE_READ && s->dma_adc.subdivision) ||
1720                     (file->f_mode & FMODE_WRITE && s->dma_dac.subdivision))
1721                         return -EINVAL;
1722                 if (get_user(val, (int *)arg))
1723                         return -EFAULT;
1724                 if (val != 1 && val != 2 && val != 4)
1725                         return -EINVAL;
1726                 if (file->f_mode & FMODE_READ) {
1727                         stop_adc(s);
1728                         s->dma_adc.subdivision = val;
1729                         if ((ret = prog_dmabuf_adc(s)))
1730                                 return ret;
1731                 }
1732                 if (file->f_mode & FMODE_WRITE) {
1733                         stop_dac(s);
1734                         s->dma_dac.subdivision = val;
1735                         if ((ret = prog_dmabuf_dac(s)))
1736                                 return ret;
1737                 }
1738                 return 0;
1739
1740         case SOUND_PCM_READ_RATE:
1741                 return put_user((file->f_mode & FMODE_READ) ?
1742                                 s->adcrate : s->dacrate, (int *)arg);
1743
1744         case SOUND_PCM_READ_CHANNELS:
1745                 if (file->f_mode & FMODE_READ)
1746                         return put_user((s->capcc & CC_SM) ? 2 : 1,
1747                                         (int *)arg);
1748                 else
1749                         return put_user((s->pcc & CC_SM) ? 2 : 1,
1750                                         (int *)arg);
1751             
1752         case SOUND_PCM_READ_BITS:
1753                 if (file->f_mode & FMODE_READ)
1754                         return put_user((s->capcc & CC_DF) ? 16 : 8,
1755                                         (int *)arg);
1756                 else
1757                         return put_user((s->pcc & CC_DF) ? 16 : 8,
1758                                         (int *)arg);
1759
1760         case SOUND_PCM_WRITE_FILTER:
1761         case SNDCTL_DSP_SETSYNCRO:
1762         case SOUND_PCM_READ_FILTER:
1763                 return -EINVAL;
1764         }
1765
1766         return mixdev_ioctl(&s->codec, cmd, arg);
1767 }
1768
1769
1770 static int it8172_open(struct inode *inode, struct file *file)
1771 {
1772         int minor = MINOR(inode->i_rdev);
1773         DECLARE_WAITQUEUE(wait, current);
1774         unsigned long flags;
1775         struct list_head *list;
1776         struct it8172_state *s;
1777         int ret;
1778     
1779 #ifdef IT8172_VERBOSE_DEBUG
1780         if (file->f_flags & O_NONBLOCK)
1781                 dbg(__FUNCTION__ ": non-blocking");
1782         else
1783                 dbg(__FUNCTION__ ": blocking");
1784 #endif
1785         
1786         for (list = devs.next; ; list = list->next) {
1787                 if (list == &devs)
1788                         return -ENODEV;
1789                 s = list_entry(list, struct it8172_state, devs);
1790                 if (!((s->dev_audio ^ minor) & ~0xf))
1791                         break;
1792         }
1793         file->private_data = s;
1794         /* wait for device to become free */
1795         down(&s->open_sem);
1796         while (s->open_mode & file->f_mode) {
1797                 if (file->f_flags & O_NONBLOCK) {
1798                         up(&s->open_sem);
1799                         return -EBUSY;
1800                 }
1801                 add_wait_queue(&s->open_wait, &wait);
1802                 __set_current_state(TASK_INTERRUPTIBLE);
1803                 up(&s->open_sem);
1804                 schedule();
1805                 remove_wait_queue(&s->open_wait, &wait);
1806                 set_current_state(TASK_RUNNING);
1807                 if (signal_pending(current))
1808                         return -ERESTARTSYS;
1809                 down(&s->open_sem);
1810         }
1811
1812         spin_lock_irqsave(&s->lock, flags);
1813
1814         if (file->f_mode & FMODE_READ) {
1815                 s->dma_adc.ossfragshift = s->dma_adc.ossmaxfrags =
1816                         s->dma_adc.subdivision = s->dma_adc.total_bytes = 0;
1817                 s->capcc &= ~(CC_SM | CC_DF);
1818                 set_adc_rate(s, 8000);
1819                 if ((minor & 0xf) == SND_DEV_DSP16)
1820                         s->capcc |= CC_DF;
1821                 outw(s->capcc, s->io+IT_AC_CAPCC);
1822                 if ((ret = prog_dmabuf_adc(s))) {
1823                         spin_unlock_irqrestore(&s->lock, flags);
1824                         return ret;
1825                 }
1826         }
1827         if (file->f_mode & FMODE_WRITE) {
1828                 s->dma_dac.ossfragshift = s->dma_dac.ossmaxfrags =
1829                         s->dma_dac.subdivision = s->dma_dac.total_bytes = 0;
1830                 s->pcc &= ~(CC_SM | CC_DF);
1831                 set_dac_rate(s, 8000);
1832                 if ((minor & 0xf) == SND_DEV_DSP16)
1833                         s->pcc |= CC_DF;
1834                 outw(s->pcc, s->io+IT_AC_PCC);
1835                 if ((ret = prog_dmabuf_dac(s))) {
1836                         spin_unlock_irqrestore(&s->lock, flags);
1837                         return ret;
1838                 }
1839         }
1840     
1841         spin_unlock_irqrestore(&s->lock, flags);
1842
1843         s->open_mode |= (file->f_mode & (FMODE_READ | FMODE_WRITE));
1844         up(&s->open_sem);
1845         return 0;
1846 }
1847
1848 static int it8172_release(struct inode *inode, struct file *file)
1849 {
1850         struct it8172_state *s = (struct it8172_state *)file->private_data;
1851
1852 #ifdef IT8172_VERBOSE_DEBUG
1853         dbg(__FUNCTION__);
1854 #endif
1855         lock_kernel();
1856         if (file->f_mode & FMODE_WRITE)
1857                 drain_dac(s, file->f_flags & O_NONBLOCK);
1858         down(&s->open_sem);
1859         if (file->f_mode & FMODE_WRITE) {
1860                 stop_dac(s);
1861                 dealloc_dmabuf(s, &s->dma_dac);
1862         }
1863         if (file->f_mode & FMODE_READ) {
1864                 stop_adc(s);
1865                 dealloc_dmabuf(s, &s->dma_adc);
1866         }
1867         s->open_mode &= ((~file->f_mode) & (FMODE_READ|FMODE_WRITE));
1868         up(&s->open_sem);
1869         wake_up(&s->open_wait);
1870         unlock_kernel();
1871         return 0;
1872 }
1873
1874 static /*const*/ struct file_operations it8172_audio_fops = {
1875         owner:  THIS_MODULE,
1876         llseek: it8172_llseek,
1877         read:   it8172_read,
1878         write:  it8172_write,
1879         poll:   it8172_poll,
1880         ioctl:  it8172_ioctl,
1881         mmap:   it8172_mmap,
1882         open:   it8172_open,
1883         release:        it8172_release,
1884 };
1885
1886
1887 /* --------------------------------------------------------------------- */
1888
1889
1890 /* --------------------------------------------------------------------- */
1891
1892 /*
1893  * for debugging purposes, we'll create a proc device that dumps the
1894  * CODEC chipstate
1895  */
1896
1897 #ifdef IT8172_DEBUG
1898 static int proc_it8172_dump (char *buf, char **start, off_t fpos,
1899                              int length, int *eof, void *data)
1900 {
1901         struct it8172_state *s;
1902         int cnt, len = 0;
1903
1904         if (list_empty(&devs))
1905                 return 0;
1906         s = list_entry(devs.next, struct it8172_state, devs);
1907
1908         /* print out header */
1909         len += sprintf(buf + len, "\n\t\tIT8172 Audio Debug\n\n");
1910
1911         // print out digital controller state
1912         len += sprintf (buf + len, "IT8172 Audio Controller registers\n");
1913         len += sprintf (buf + len, "---------------------------------\n");
1914         cnt=0;
1915         while (cnt < 0x72) {
1916                 if (cnt == IT_AC_PCB1STA || cnt == IT_AC_PCB2STA ||
1917                     cnt == IT_AC_CAPB1STA || cnt == IT_AC_CAPB2STA ||
1918                     cnt == IT_AC_PFDP) {
1919                         len+= sprintf (buf + len, "reg %02x = %08x\n",
1920                                        cnt, inl(s->io+cnt));
1921                         cnt += 4;
1922                 } else {
1923                         len+= sprintf (buf + len, "reg %02x = %04x\n",
1924                                        cnt, inw(s->io+cnt));
1925                         cnt += 2;
1926                 }
1927         }
1928     
1929         /* print out CODEC state */
1930         len += sprintf (buf + len, "\nAC97 CODEC registers\n");
1931         len += sprintf (buf + len, "----------------------\n");
1932         for (cnt=0; cnt <= 0x7e; cnt = cnt +2)
1933                 len+= sprintf (buf + len, "reg %02x = %04x\n",
1934                                cnt, rdcodec(&s->codec, cnt));
1935
1936         if (fpos >=len){
1937                 *start = buf;
1938                 *eof =1;
1939                 return 0;
1940         }
1941         *start = buf + fpos;
1942         if ((len -= fpos) > length)
1943                 return length;
1944         *eof =1;
1945         return len;
1946
1947 }
1948 #endif /* IT8172_DEBUG */
1949
1950 /* --------------------------------------------------------------------- */
1951
1952 /* maximum number of devices; only used for command line params */
1953 #define NR_DEVICE 5
1954
1955 static int spdif[NR_DEVICE] = { 0, };
1956 static int i2s_fmt[NR_DEVICE] = { 0, };
1957
1958 static unsigned int devindex = 0;
1959
1960 MODULE_PARM(spdif, "1-" __MODULE_STRING(NR_DEVICE) "i");
1961 MODULE_PARM_DESC(spdif, "if 1 the S/PDIF digital output is enabled");
1962 MODULE_PARM(i2s_fmt, "1-" __MODULE_STRING(NR_DEVICE) "i");
1963 MODULE_PARM_DESC(i2s_fmt, "the format of I2S");
1964
1965 MODULE_AUTHOR("Monta Vista Software, stevel@mvista.com");
1966 MODULE_DESCRIPTION("IT8172 Audio Driver");
1967
1968 /* --------------------------------------------------------------------- */
1969
1970 static int __devinit it8172_probe(struct pci_dev *pcidev,
1971                                   const struct pci_device_id *pciid)
1972 {
1973         struct it8172_state *s;
1974         int i, val;
1975         unsigned short pcisr, vol;
1976         unsigned char legacy, imc;
1977         char proc_str[80];
1978     
1979         if (pcidev->irq == 0) 
1980                 return -1;
1981
1982         if (!(s = kmalloc(sizeof(struct it8172_state), GFP_KERNEL))) {
1983                 err("alloc of device struct failed");
1984                 return -1;
1985         }
1986         
1987         memset(s, 0, sizeof(struct it8172_state));
1988         init_waitqueue_head(&s->dma_adc.wait);
1989         init_waitqueue_head(&s->dma_dac.wait);
1990         init_waitqueue_head(&s->open_wait);
1991         init_MUTEX(&s->open_sem);
1992         spin_lock_init(&s->lock);
1993         s->dev = pcidev;
1994         s->io = pci_resource_start(pcidev, 0);
1995         s->irq = pcidev->irq;
1996         s->vendor = pcidev->vendor;
1997         s->device = pcidev->device;
1998         pci_read_config_byte(pcidev, PCI_REVISION_ID, &s->rev);
1999         s->codec.private_data = s;
2000         s->codec.id = 0;
2001         s->codec.codec_read = rdcodec;
2002         s->codec.codec_write = wrcodec;
2003         s->codec.codec_wait = waitcodec;
2004
2005         if (!request_region(s->io, pci_resource_len(pcidev,0),
2006                             IT8172_MODULE_NAME)) {
2007                 err("io ports %#lx->%#lx in use",
2008                     s->io, s->io + pci_resource_len(pcidev,0)-1);
2009                 goto err_region;
2010         }
2011         if (request_irq(s->irq, it8172_interrupt, SA_INTERRUPT,
2012                         IT8172_MODULE_NAME, s)) {
2013                 err("irq %u in use", s->irq);
2014                 goto err_irq;
2015         }
2016
2017         info("IO at %#lx, IRQ %d", s->io, s->irq);
2018
2019         /* register devices */
2020         if ((s->dev_audio = register_sound_dsp(&it8172_audio_fops, -1)) < 0)
2021                 goto err_dev1;
2022         if ((s->codec.dev_mixer =
2023              register_sound_mixer(&it8172_mixer_fops, -1)) < 0)
2024                 goto err_dev2;
2025
2026 #ifdef IT8172_DEBUG
2027         /* intialize the debug proc device */
2028         s->ps = create_proc_read_entry(IT8172_MODULE_NAME, 0, NULL,
2029                                        proc_it8172_dump, NULL);
2030 #endif /* IT8172_DEBUG */
2031         
2032         /*
2033          * Reset the Audio device using the IT8172 PCI Reset register. This
2034          * creates an audible double click on a speaker connected to Line-out.
2035          */
2036         IT_IO_READ16(IT_PM_PCISR, pcisr);
2037         pcisr |= IT_PM_PCISR_ACSR;
2038         IT_IO_WRITE16(IT_PM_PCISR, pcisr);
2039         /* wait up to 100msec for reset to complete */
2040         for (i=0; pcisr & IT_PM_PCISR_ACSR; i++) {
2041                 it8172_delay(10);
2042                 if (i == 10)
2043                         break;
2044                 IT_IO_READ16(IT_PM_PCISR, pcisr);
2045         }
2046         if (i == 10) {
2047                 err("chip reset timeout!");
2048                 goto err_dev3;
2049         }
2050     
2051         /* enable pci io and bus mastering */
2052         if (pci_enable_device(pcidev))
2053                 goto err_dev3;
2054         pci_set_master(pcidev);
2055
2056         /* get out of legacy mode */
2057         pci_read_config_byte (pcidev, 0x40, &legacy);
2058         pci_write_config_byte (pcidev, 0x40, legacy & ~1);
2059     
2060         s->spdif_volume = -1;
2061         /* check to see if s/pdif mode is being requested */
2062         if (spdif[devindex]) {
2063                 info("enabling S/PDIF output");
2064                 s->spdif_volume = 0;
2065                 outb(GC_SOE, s->io+IT_AC_GC);
2066         } else {
2067                 info("disabling S/PDIF output");
2068                 outb(0, s->io+IT_AC_GC);
2069         }
2070     
2071         /* check to see if I2S format requested */
2072         if (i2s_fmt[devindex]) {
2073                 info("setting I2S format to 0x%02x", i2s_fmt[devindex]);
2074                 outb(i2s_fmt[devindex], s->io+IT_AC_I2SMC);
2075         } else {
2076                 outb(I2SMC_I2SF_I2S, s->io+IT_AC_I2SMC);
2077         }
2078
2079         /* cold reset the AC97 */
2080         outw(CODECC_CR, s->io+IT_AC_CODECC);
2081         udelay(1000);
2082         outw(0, s->io+IT_AC_CODECC);
2083         /* need to delay around 500msec(bleech) to give
2084            some CODECs enough time to wakeup */
2085         it8172_delay(500);
2086     
2087         /* AC97 warm reset to start the bitclk */
2088         outw(CODECC_WR, s->io+IT_AC_CODECC);
2089         udelay(1000);
2090         outw(0, s->io+IT_AC_CODECC);
2091     
2092         /* codec init */
2093         if (!ac97_probe_codec(&s->codec))
2094                 goto err_dev3;
2095
2096         /* add I2S as allowable recording source */
2097         s->codec.record_sources |= SOUND_MASK_I2S;
2098         
2099         /* Enable Volume button interrupts */
2100         imc = inb(s->io+IT_AC_IMC);
2101         outb(imc & ~IMC_VCIM, s->io+IT_AC_IMC);
2102
2103         /* Un-mute PCM and FM out on the controller */
2104         vol = inw(s->io+IT_AC_PCMOV);
2105         outw(vol & ~PCMOV_PCMOM, s->io+IT_AC_PCMOV);
2106         vol = inw(s->io+IT_AC_FMOV);
2107         outw(vol & ~FMOV_FMOM, s->io+IT_AC_FMOV);
2108     
2109         /* set channel defaults to 8-bit, mono, 8 Khz */
2110         s->pcc = 0;
2111         s->capcc = 0;
2112         set_dac_rate(s, 8000);
2113         set_adc_rate(s, 8000);
2114
2115         /* set mic to be the recording source */
2116         val = SOUND_MASK_MIC;
2117         mixdev_ioctl(&s->codec, SOUND_MIXER_WRITE_RECSRC,
2118                      (unsigned long)&val);
2119
2120         /* mute AC'97 master and PCM when in S/PDIF mode */
2121         if (s->spdif_volume != -1) {
2122                 val = 0x0000;
2123                 s->codec.mixer_ioctl(&s->codec, SOUND_MIXER_WRITE_VOLUME,
2124                                      (unsigned long)&val);
2125                 s->codec.mixer_ioctl(&s->codec, SOUND_MIXER_WRITE_PCM,
2126                                      (unsigned long)&val);
2127         }
2128     
2129 #ifdef IT8172_DEBUG
2130         sprintf(proc_str, "driver/%s/%d/ac97", IT8172_MODULE_NAME,
2131                 s->codec.id);
2132         s->ac97_ps = create_proc_read_entry (proc_str, 0, NULL,
2133                                              ac97_read_proc, &s->codec);
2134 #endif
2135     
2136         /* store it in the driver field */
2137         pci_set_drvdata(pcidev, s);
2138         pcidev->dma_mask = 0xffffffff;
2139         /* put it into driver list */
2140         list_add_tail(&s->devs, &devs);
2141         /* increment devindex */
2142         if (devindex < NR_DEVICE-1)
2143                 devindex++;
2144         return 0;
2145
2146  err_dev3:
2147         unregister_sound_mixer(s->codec.dev_mixer);
2148  err_dev2:
2149         unregister_sound_dsp(s->dev_audio);
2150  err_dev1:
2151         err("cannot register misc device");
2152         free_irq(s->irq, s);
2153  err_irq:
2154         release_region(s->io, pci_resource_len(pcidev,0));
2155  err_region:
2156         kfree(s);
2157         return -1;
2158 }
2159
2160 static void __devinit it8172_remove(struct pci_dev *dev)
2161 {
2162         struct it8172_state *s = pci_get_drvdata(dev);
2163
2164         if (!s)
2165                 return;
2166         list_del(&s->devs);
2167 #ifdef IT8172_DEBUG
2168         if (s->ps)
2169                 remove_proc_entry(IT8172_MODULE_NAME, NULL);
2170 #endif /* IT8172_DEBUG */
2171         synchronize_irq();
2172         free_irq(s->irq, s);
2173         release_region(s->io, pci_resource_len(dev,0));
2174         unregister_sound_dsp(s->dev_audio);
2175         unregister_sound_mixer(s->codec.dev_mixer);
2176         kfree(s);
2177         pci_set_drvdata(dev, NULL);
2178 }
2179
2180
2181
2182 static struct pci_device_id id_table[] __devinitdata = {
2183         { PCI_VENDOR_ID_ITE, PCI_DEVICE_ID_ITE_IT8172G_AUDIO, PCI_ANY_ID,
2184           PCI_ANY_ID, 0, 0 },
2185         { 0, }
2186 };
2187
2188 MODULE_DEVICE_TABLE(pci, id_table);
2189
2190 static struct pci_driver it8172_driver = {
2191         name: IT8172_MODULE_NAME,
2192         id_table: id_table,
2193         probe: it8172_probe,
2194         remove: it8172_remove
2195 };
2196
2197 static int __init init_it8172(void)
2198 {
2199         if (!pci_present())   /* No PCI bus in this machine! */
2200                 return -ENODEV;
2201         info("version v0.5 time " __TIME__ " " __DATE__);
2202         return pci_module_init(&it8172_driver);
2203 }
2204
2205 static void __exit cleanup_it8172(void)
2206 {
2207         info("unloading");
2208         pci_unregister_driver(&it8172_driver);
2209 }
2210
2211 module_init(init_it8172);
2212 module_exit(cleanup_it8172);
2213
2214 /* --------------------------------------------------------------------- */
2215
2216 #ifndef MODULE
2217
2218 /* format is: it8172=[spdif],[i2s:<I2S format>] */
2219
2220 static int __init it8172_setup(char *options)
2221 {
2222         char* this_opt;
2223         static unsigned __initdata nr_dev = 0;
2224
2225         if (nr_dev >= NR_DEVICE)
2226                 return 0;
2227
2228         if (!options || !*options)
2229                 return 0;
2230
2231         for(this_opt=strtok(options, ",");
2232             this_opt; this_opt=strtok(NULL, ",")) {
2233                 if (!strncmp(this_opt, "spdif", 5)) {
2234                         spdif[nr_dev] = 1;
2235                 } else if (!strncmp(this_opt, "i2s:", 4)) {
2236                         if (!strncmp(this_opt+4, "dac", 3))
2237                                 i2s_fmt[nr_dev] = I2SMC_I2SF_DAC;
2238                         else if (!strncmp(this_opt+4, "adc", 3))
2239                                 i2s_fmt[nr_dev] = I2SMC_I2SF_ADC;
2240                         else if (!strncmp(this_opt+4, "i2s", 3))
2241                                 i2s_fmt[nr_dev] = I2SMC_I2SF_I2S;
2242                 }
2243         }
2244
2245         nr_dev++;
2246         return 1;
2247 }
2248
2249 __setup("it8172=", it8172_setup);
2250
2251 #endif /* MODULE */