VServer 1.9.2 (patch-2.6.8.1-vs1.9.2.diff)
[linux-2.6.git] / sound / oss / 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  *    07.30.2003  Removed initialisation to zero for static variables
55  *                 (spdif[NR_DEVICE], i2s_fmt[NR_DEVICE], and devindex)
56  */
57 #include <linux/module.h>
58 #include <linux/string.h>
59 #include <linux/ioport.h>
60 #include <linux/sched.h>
61 #include <linux/delay.h>
62 #include <linux/sound.h>
63 #include <linux/slab.h>
64 #include <linux/soundcard.h>
65 #include <linux/pci.h>
66 #include <linux/init.h>
67 #include <linux/poll.h>
68 #include <linux/bitops.h>
69 #include <linux/proc_fs.h>
70 #include <linux/spinlock.h>
71 #include <linux/smp_lock.h>
72 #include <linux/ac97_codec.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 irqreturn_t 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 IRQ_NONE;
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         return IRQ_HANDLED;
857 }
858
859 /* --------------------------------------------------------------------- */
860
861 static loff_t it8172_llseek(struct file *file, loff_t offset, int origin)
862 {
863         return -ESPIPE;
864 }
865
866
867 static int it8172_open_mixdev(struct inode *inode, struct file *file)
868 {
869         int minor = iminor(inode);
870         struct list_head *list;
871         struct it8172_state *s;
872
873         for (list = devs.next; ; list = list->next) {
874                 if (list == &devs)
875                         return -ENODEV;
876                 s = list_entry(list, struct it8172_state, devs);
877                 if (s->codec->dev_mixer == minor)
878                         break;
879         }
880         file->private_data = s;
881         return nonseekable_open(inode, file);
882 }
883
884 static int it8172_release_mixdev(struct inode *inode, struct file *file)
885 {
886         return 0;
887 }
888
889
890 static u16
891 cvt_ossvol(unsigned int gain)
892 {
893         u16 ret;
894     
895         if (gain == 0)
896                 return 0;
897     
898         if (gain > 100)
899                 gain = 100;
900     
901         ret = (100 - gain + 32) / 4;
902         ret = ret > 31 ? 31 : ret;
903         return ret;
904 }
905
906
907 static int mixdev_ioctl(struct ac97_codec *codec, unsigned int cmd,
908                         unsigned long arg)
909 {
910         struct it8172_state *s = (struct it8172_state *)codec->private_data;
911         unsigned int left, right;
912         unsigned long flags;
913         int val;
914         u16 vol;
915     
916         /*
917          * When we are in S/PDIF mode, we want to disable any analog output so
918          * we filter the master/PCM channel volume ioctls.
919          *
920          * Also filter I2S channel, which AC'97 knows nothing about.
921          */
922
923         switch (cmd) {
924         case SOUND_MIXER_WRITE_VOLUME:
925                 // if not in S/PDIF mode, pass to AC'97
926                 if (s->spdif_volume == -1)
927                         break;
928                 return 0;
929         case SOUND_MIXER_WRITE_PCM:
930                 // if not in S/PDIF mode, pass to AC'97
931                 if (s->spdif_volume == -1)
932                         break;
933                 if (get_user(val, (int *)arg))
934                         return -EFAULT;
935                 right = ((val >> 8)  & 0xff);
936                 left = (val  & 0xff);
937                 if (right > 100)
938                         right = 100;
939                 if (left > 100)
940                         left = 100;
941                 s->spdif_volume = (right << 8) | left;
942                 vol = cvt_ossvol(left);
943                 vol |= (cvt_ossvol(right) << PCMOV_PCMRCG_BIT);
944                 if (vol == 0)
945                         vol = PCMOV_PCMOM; // mute
946                 spin_lock_irqsave(&s->lock, flags);
947                 outw(vol, s->io+IT_AC_PCMOV);
948                 spin_unlock_irqrestore(&s->lock, flags);
949                 return put_user(s->spdif_volume, (int *)arg);
950         case SOUND_MIXER_READ_PCM:
951                 // if not in S/PDIF mode, pass to AC'97
952                 if (s->spdif_volume == -1)
953                         break;
954                 return put_user(s->spdif_volume, (int *)arg);
955         case SOUND_MIXER_WRITE_I2S:
956                 if (get_user(val, (int *)arg))
957                         return -EFAULT;
958                 right = ((val >> 8)  & 0xff);
959                 left = (val  & 0xff);
960                 if (right > 100)
961                         right = 100;
962                 if (left > 100)
963                         left = 100;
964                 s->i2s_volume = (right << 8) | left;
965                 vol = cvt_ossvol(left);
966                 vol |= (cvt_ossvol(right) << I2SV_I2SRCG_BIT);
967                 if (vol == 0)
968                         vol = I2SV_I2SOM; // mute
969                 outw(vol, s->io+IT_AC_I2SV);
970                 return put_user(s->i2s_volume, (int *)arg);
971         case SOUND_MIXER_READ_I2S:
972                 return put_user(s->i2s_volume, (int *)arg);
973         case SOUND_MIXER_WRITE_RECSRC:
974                 if (get_user(val, (int *)arg))
975                         return -EFAULT;
976                 if (val & SOUND_MASK_I2S) {
977                         s->i2s_recording = 1;
978                         outb(DRSS_I2S, s->io+IT_AC_DRSS);
979                         return 0;
980                 } else {
981                         s->i2s_recording = 0;
982                         outb(DRSS_AC97_PRIM, s->io+IT_AC_DRSS);
983                         // now let AC'97 select record source
984                         break;
985                 }
986         case SOUND_MIXER_READ_RECSRC:
987                 if (s->i2s_recording)
988                         return put_user(SOUND_MASK_I2S, (int *)arg);
989                 else
990                         // let AC'97 report recording source
991                         break;
992         }
993
994         return codec->mixer_ioctl(codec, cmd, arg);
995 }
996
997 static int it8172_ioctl_mixdev(struct inode *inode, struct file *file,
998                                unsigned int cmd, unsigned long arg)
999 {
1000         struct it8172_state *s = (struct it8172_state *)file->private_data;
1001         struct ac97_codec *codec = s->codec;
1002
1003         return mixdev_ioctl(codec, cmd, arg);
1004 }
1005
1006 static /*const*/ struct file_operations it8172_mixer_fops = {
1007         .owner          = THIS_MODULE,
1008         .llseek         = it8172_llseek,
1009         .ioctl          = it8172_ioctl_mixdev,
1010         .open           = it8172_open_mixdev,
1011         .release        = it8172_release_mixdev,
1012 };
1013
1014 /* --------------------------------------------------------------------- */
1015
1016 static int drain_dac(struct it8172_state *s, int nonblock)
1017 {
1018         unsigned long flags;
1019         int count, tmo;
1020         
1021         if (s->dma_dac.mapped || !s->dma_dac.ready || s->dma_dac.stopped)
1022                 return 0;
1023
1024         for (;;) {
1025                 spin_lock_irqsave(&s->lock, flags);
1026                 count = s->dma_dac.count;
1027                 spin_unlock_irqrestore(&s->lock, flags);
1028                 if (count <= 0)
1029                         break;
1030                 if (signal_pending(current))
1031                         break;
1032                 //if (nonblock)
1033                 //return -EBUSY;
1034                 tmo = 1000 * count / s->dacrate;
1035                 tmo >>= sample_shift[(s->pcc & CC_FMT_MASK) >> CC_FMT_BIT];
1036                 it8172_delay(tmo);
1037         }
1038         if (signal_pending(current))
1039                 return -ERESTARTSYS;
1040         return 0;
1041 }
1042
1043 /* --------------------------------------------------------------------- */
1044
1045
1046 /*
1047  * Copy audio data to/from user buffer from/to dma buffer, taking care
1048  * that we wrap when reading/writing the dma buffer. Returns actual byte
1049  * count written to or read from the dma buffer.
1050  */
1051 static int copy_dmabuf_user(struct dmabuf *db, char* userbuf,
1052                             int count, int to_user)
1053 {
1054         char* bufptr = to_user ? db->nextOut : db->nextIn;
1055         char* bufend = db->rawbuf + db->dmasize;
1056         
1057         if (bufptr + count > bufend) {
1058                 int partial = (int)(bufend - bufptr);
1059                 if (to_user) {
1060                         if (copy_to_user(userbuf, bufptr, partial))
1061                                 return -EFAULT;
1062                         if (copy_to_user(userbuf + partial, db->rawbuf,
1063                                          count - partial))
1064                                 return -EFAULT;
1065                 } else {
1066                         if (copy_from_user(bufptr, userbuf, partial))
1067                                 return -EFAULT;
1068                         if (copy_from_user(db->rawbuf,
1069                                            userbuf + partial,
1070                                            count - partial))
1071                                 return -EFAULT;
1072                 }
1073         } else {
1074                 if (to_user) {
1075                         if (copy_to_user(userbuf, bufptr, count))
1076                                 return -EFAULT;
1077                 } else {
1078                         if (copy_from_user(bufptr, userbuf, count))
1079                                 return -EFAULT;
1080                 }
1081         }
1082         
1083         return count;
1084 }
1085
1086
1087 static ssize_t it8172_read(struct file *file, char *buffer,
1088                            size_t count, loff_t *ppos)
1089 {
1090         struct it8172_state *s = (struct it8172_state *)file->private_data;
1091         struct dmabuf *db = &s->dma_adc;
1092         ssize_t ret;
1093         unsigned long flags;
1094         int cnt, remainder, avail;
1095
1096         if (db->mapped)
1097                 return -ENXIO;
1098         if (!access_ok(VERIFY_WRITE, buffer, count))
1099                 return -EFAULT;
1100         ret = 0;
1101
1102         while (count > 0) {
1103                 // wait for samples in capture buffer
1104                 do {
1105                         spin_lock_irqsave(&s->lock, flags);
1106                         if (db->stopped)
1107                                 start_adc(s);
1108                         avail = db->count;
1109                         spin_unlock_irqrestore(&s->lock, flags);
1110                         if (avail <= 0) {
1111                                 if (file->f_flags & O_NONBLOCK) {
1112                                         if (!ret)
1113                                                 ret = -EAGAIN;
1114                                         return ret;
1115                                 }
1116                                 interruptible_sleep_on(&db->wait);
1117                                 if (signal_pending(current)) {
1118                                         if (!ret)
1119                                                 ret = -ERESTARTSYS;
1120                                         return ret;
1121                                 }
1122                         }
1123                 } while (avail <= 0);
1124
1125                 // copy from nextOut to user
1126                 if ((cnt = copy_dmabuf_user(db, buffer, count > avail ?
1127                                             avail : count, 1)) < 0) {
1128                         if (!ret)
1129                                 ret = -EFAULT;
1130                         return ret;
1131                 }
1132
1133                 spin_lock_irqsave(&s->lock, flags);
1134                 db->count -= cnt;
1135                 spin_unlock_irqrestore(&s->lock, flags);
1136
1137                 db->nextOut += cnt;
1138                 if (db->nextOut >= db->rawbuf + db->dmasize)
1139                         db->nextOut -= db->dmasize;     
1140
1141                 count -= cnt;
1142                 buffer += cnt;
1143                 ret += cnt;
1144         } // while (count > 0)
1145
1146         /*
1147          * See if the dma buffer count after this read call is
1148          * aligned on a fragsize boundary. If not, read from
1149          * buffer until we reach a boundary, and let's hope this
1150          * is just the last remainder of an audio record. If not
1151          * it means the user is not reading in fragsize chunks, in
1152          * which case it's his/her fault that there are audio gaps
1153          * in their record.
1154          */
1155         spin_lock_irqsave(&s->lock, flags);
1156         remainder = db->count % db->fragsize;
1157         if (remainder) {
1158                 db->nextOut += remainder;
1159                 if (db->nextOut >= db->rawbuf + db->dmasize)
1160                         db->nextOut -= db->dmasize;
1161                 db->count -= remainder;
1162         }
1163         spin_unlock_irqrestore(&s->lock, flags);
1164
1165         return ret;
1166 }
1167
1168 static ssize_t it8172_write(struct file *file, const char *buffer,
1169                             size_t count, loff_t *ppos)
1170 {
1171         struct it8172_state *s = (struct it8172_state *)file->private_data;
1172         struct dmabuf *db = &s->dma_dac;
1173         ssize_t ret;
1174         unsigned long flags;
1175         int cnt, remainder, avail;
1176
1177         if (db->mapped)
1178                 return -ENXIO;
1179         if (!access_ok(VERIFY_READ, buffer, count))
1180                 return -EFAULT;
1181         ret = 0;
1182     
1183         while (count > 0) {
1184                 // wait for space in playback buffer
1185                 do {
1186                         spin_lock_irqsave(&s->lock, flags);
1187                         avail = db->dmasize - db->count;
1188                         spin_unlock_irqrestore(&s->lock, flags);
1189                         if (avail <= 0) {
1190                                 if (file->f_flags & O_NONBLOCK) {
1191                                         if (!ret)
1192                                                 ret = -EAGAIN;
1193                                         return ret;
1194                                 }
1195                                 interruptible_sleep_on(&db->wait);
1196                                 if (signal_pending(current)) {
1197                                         if (!ret)
1198                                                 ret = -ERESTARTSYS;
1199                                         return ret;
1200                                 }
1201                         }
1202                 } while (avail <= 0);
1203         
1204                 // copy to nextIn
1205                 if ((cnt = copy_dmabuf_user(db, (char*)buffer,
1206                                             count > avail ?
1207                                             avail : count, 0)) < 0) {
1208                         if (!ret)
1209                                 ret = -EFAULT;
1210                         return ret;
1211                 }
1212
1213                 spin_lock_irqsave(&s->lock, flags);
1214                 db->count += cnt;
1215                 if (db->stopped)
1216                         start_dac(s);
1217                 spin_unlock_irqrestore(&s->lock, flags);
1218         
1219                 db->nextIn += cnt;
1220                 if (db->nextIn >= db->rawbuf + db->dmasize)
1221                         db->nextIn -= db->dmasize;
1222         
1223                 count -= cnt;
1224                 buffer += cnt;
1225                 ret += cnt;
1226         } // while (count > 0)
1227         
1228         /*
1229          * See if the dma buffer count after this write call is
1230          * aligned on a fragsize boundary. If not, fill buffer
1231          * with silence to the next boundary, and let's hope this
1232          * is just the last remainder of an audio playback. If not
1233          * it means the user is not sending us fragsize chunks, in
1234          * which case it's his/her fault that there are audio gaps
1235          * in their playback.
1236          */
1237         spin_lock_irqsave(&s->lock, flags);
1238         remainder = db->count % db->fragsize;
1239         if (remainder) {
1240                 int fill_cnt = db->fragsize - remainder;
1241                 memset(db->nextIn, 0, fill_cnt);
1242                 db->nextIn += fill_cnt;
1243                 if (db->nextIn >= db->rawbuf + db->dmasize)
1244                         db->nextIn -= db->dmasize;
1245                 db->count += fill_cnt;
1246         }
1247         spin_unlock_irqrestore(&s->lock, flags);
1248
1249         return ret;
1250 }
1251
1252 /* No kernel lock - we have our own spinlock */
1253 static unsigned int it8172_poll(struct file *file,
1254                                 struct poll_table_struct *wait)
1255 {
1256         struct it8172_state *s = (struct it8172_state *)file->private_data;
1257         unsigned long flags;
1258         unsigned int mask = 0;
1259
1260         if (file->f_mode & FMODE_WRITE) {
1261                 if (!s->dma_dac.ready)
1262                         return 0;
1263                 poll_wait(file, &s->dma_dac.wait, wait);
1264         }
1265         if (file->f_mode & FMODE_READ) {
1266                 if (!s->dma_adc.ready)
1267                         return 0;
1268                 poll_wait(file, &s->dma_adc.wait, wait);
1269         }
1270         
1271         spin_lock_irqsave(&s->lock, flags);
1272         if (file->f_mode & FMODE_READ) {
1273                 if (s->dma_adc.count >= (signed)s->dma_adc.fragsize)
1274                         mask |= POLLIN | POLLRDNORM;
1275         }
1276         if (file->f_mode & FMODE_WRITE) {
1277                 if (s->dma_dac.mapped) {
1278                         if (s->dma_dac.count >= (signed)s->dma_dac.fragsize) 
1279                                 mask |= POLLOUT | POLLWRNORM;
1280                 } else {
1281                         if ((signed)s->dma_dac.dmasize >=
1282                             s->dma_dac.count + (signed)s->dma_dac.fragsize)
1283                                 mask |= POLLOUT | POLLWRNORM;
1284                 }
1285         }
1286         spin_unlock_irqrestore(&s->lock, flags);
1287         return mask;
1288 }
1289
1290 static int it8172_mmap(struct file *file, struct vm_area_struct *vma)
1291 {
1292         struct it8172_state *s = (struct it8172_state *)file->private_data;
1293         struct dmabuf *db;
1294         unsigned long size;
1295
1296         lock_kernel();
1297         if (vma->vm_flags & VM_WRITE)
1298                 db = &s->dma_dac;
1299         else if (vma->vm_flags & VM_READ)
1300                 db = &s->dma_adc;
1301         else {
1302                 unlock_kernel();
1303                 return -EINVAL;
1304         }
1305         if (vma->vm_pgoff != 0) {
1306                 unlock_kernel();
1307                 return -EINVAL;
1308         }
1309         size = vma->vm_end - vma->vm_start;
1310         if (size > (PAGE_SIZE << db->buforder)) {
1311                 unlock_kernel();
1312                 return -EINVAL;
1313         }
1314         if (remap_page_range(vma, vma->vm_start, virt_to_phys(db->rawbuf),
1315                              size, vma->vm_page_prot)) {
1316                 unlock_kernel();
1317                 return -EAGAIN;
1318         }
1319         db->mapped = 1;
1320         unlock_kernel();
1321         return 0;
1322 }
1323
1324
1325 #ifdef IT8172_VERBOSE_DEBUG
1326 static struct ioctl_str_t {
1327         unsigned int cmd;
1328         const char* str;
1329 } ioctl_str[] = {
1330         {SNDCTL_DSP_RESET, "SNDCTL_DSP_RESET"},
1331         {SNDCTL_DSP_SYNC, "SNDCTL_DSP_SYNC"},
1332         {SNDCTL_DSP_SPEED, "SNDCTL_DSP_SPEED"},
1333         {SNDCTL_DSP_STEREO, "SNDCTL_DSP_STEREO"},
1334         {SNDCTL_DSP_GETBLKSIZE, "SNDCTL_DSP_GETBLKSIZE"},
1335         {SNDCTL_DSP_SAMPLESIZE, "SNDCTL_DSP_SAMPLESIZE"},
1336         {SNDCTL_DSP_CHANNELS, "SNDCTL_DSP_CHANNELS"},
1337         {SOUND_PCM_WRITE_CHANNELS, "SOUND_PCM_WRITE_CHANNELS"},
1338         {SOUND_PCM_WRITE_FILTER, "SOUND_PCM_WRITE_FILTER"},
1339         {SNDCTL_DSP_POST, "SNDCTL_DSP_POST"},
1340         {SNDCTL_DSP_SUBDIVIDE, "SNDCTL_DSP_SUBDIVIDE"},
1341         {SNDCTL_DSP_SETFRAGMENT, "SNDCTL_DSP_SETFRAGMENT"},
1342         {SNDCTL_DSP_GETFMTS, "SNDCTL_DSP_GETFMTS"},
1343         {SNDCTL_DSP_SETFMT, "SNDCTL_DSP_SETFMT"},
1344         {SNDCTL_DSP_GETOSPACE, "SNDCTL_DSP_GETOSPACE"},
1345         {SNDCTL_DSP_GETISPACE, "SNDCTL_DSP_GETISPACE"},
1346         {SNDCTL_DSP_NONBLOCK, "SNDCTL_DSP_NONBLOCK"},
1347         {SNDCTL_DSP_GETCAPS, "SNDCTL_DSP_GETCAPS"},
1348         {SNDCTL_DSP_GETTRIGGER, "SNDCTL_DSP_GETTRIGGER"},
1349         {SNDCTL_DSP_SETTRIGGER, "SNDCTL_DSP_SETTRIGGER"},
1350         {SNDCTL_DSP_GETIPTR, "SNDCTL_DSP_GETIPTR"},
1351         {SNDCTL_DSP_GETOPTR, "SNDCTL_DSP_GETOPTR"},
1352         {SNDCTL_DSP_MAPINBUF, "SNDCTL_DSP_MAPINBUF"},
1353         {SNDCTL_DSP_MAPOUTBUF, "SNDCTL_DSP_MAPOUTBUF"},
1354         {SNDCTL_DSP_SETSYNCRO, "SNDCTL_DSP_SETSYNCRO"},
1355         {SNDCTL_DSP_SETDUPLEX, "SNDCTL_DSP_SETDUPLEX"},
1356         {SNDCTL_DSP_GETODELAY, "SNDCTL_DSP_GETODELAY"},
1357         {SNDCTL_DSP_GETCHANNELMASK, "SNDCTL_DSP_GETCHANNELMASK"},
1358         {SNDCTL_DSP_BIND_CHANNEL, "SNDCTL_DSP_BIND_CHANNEL"},
1359         {OSS_GETVERSION, "OSS_GETVERSION"},
1360         {SOUND_PCM_READ_RATE, "SOUND_PCM_READ_RATE"},
1361         {SOUND_PCM_READ_CHANNELS, "SOUND_PCM_READ_CHANNELS"},
1362         {SOUND_PCM_READ_BITS, "SOUND_PCM_READ_BITS"},
1363         {SOUND_PCM_READ_FILTER, "SOUND_PCM_READ_FILTER"}
1364 };
1365 #endif    
1366
1367 static int it8172_ioctl(struct inode *inode, struct file *file,
1368                         unsigned int cmd, unsigned long arg)
1369 {
1370         struct it8172_state *s = (struct it8172_state *)file->private_data;
1371         unsigned long flags;
1372         audio_buf_info abinfo;
1373         count_info cinfo;
1374         int count;
1375         int val, mapped, ret, diff;
1376
1377         mapped = ((file->f_mode & FMODE_WRITE) && s->dma_dac.mapped) ||
1378                 ((file->f_mode & FMODE_READ) && s->dma_adc.mapped);
1379
1380 #ifdef IT8172_VERBOSE_DEBUG
1381         for (count=0; count<sizeof(ioctl_str)/sizeof(ioctl_str[0]); count++) {
1382                 if (ioctl_str[count].cmd == cmd)
1383                         break;
1384         }
1385         if (count < sizeof(ioctl_str)/sizeof(ioctl_str[0]))
1386                 dbg("ioctl %s, arg=0x%08x",
1387                     ioctl_str[count].str, (unsigned int)arg);
1388         else
1389                 dbg("ioctl unknown, 0x%x", cmd);
1390 #endif
1391     
1392         switch (cmd) {
1393         case OSS_GETVERSION:
1394                 return put_user(SOUND_VERSION, (int *)arg);
1395
1396         case SNDCTL_DSP_SYNC:
1397                 if (file->f_mode & FMODE_WRITE)
1398                         return drain_dac(s, file->f_flags & O_NONBLOCK);
1399                 return 0;
1400                 
1401         case SNDCTL_DSP_SETDUPLEX:
1402                 return 0;
1403
1404         case SNDCTL_DSP_GETCAPS:
1405                 return put_user(DSP_CAP_DUPLEX | DSP_CAP_REALTIME |
1406                                 DSP_CAP_TRIGGER | DSP_CAP_MMAP, (int *)arg);
1407                 
1408         case SNDCTL_DSP_RESET:
1409                 if (file->f_mode & FMODE_WRITE) {
1410                         stop_dac(s);
1411                         synchronize_irq();
1412                         s->dma_dac.count = s->dma_dac.total_bytes = 0;
1413                         s->dma_dac.nextIn = s->dma_dac.nextOut =
1414                                 s->dma_dac.rawbuf;
1415                 }
1416                 if (file->f_mode & FMODE_READ) {
1417                         stop_adc(s);
1418                         synchronize_irq();
1419                         s->dma_adc.count = s->dma_adc.total_bytes = 0;
1420                         s->dma_adc.nextIn = s->dma_adc.nextOut =
1421                                 s->dma_adc.rawbuf;
1422                 }
1423                 return 0;
1424
1425         case SNDCTL_DSP_SPEED:
1426                 if (get_user(val, (int *)arg))
1427                         return -EFAULT;
1428                 if (val >= 0) {
1429                         if (file->f_mode & FMODE_READ) {
1430                                 stop_adc(s);
1431                                 set_adc_rate(s, val);
1432                                 if ((ret = prog_dmabuf_adc(s)))
1433                                         return ret;
1434                         }
1435                         if (file->f_mode & FMODE_WRITE) {
1436                                 stop_dac(s);
1437                                 set_dac_rate(s, val);
1438                                 if ((ret = prog_dmabuf_dac(s)))
1439                                         return ret;
1440                         }
1441                 }
1442                 return put_user((file->f_mode & FMODE_READ) ?
1443                                 s->adcrate : s->dacrate, (int *)arg);
1444
1445         case SNDCTL_DSP_STEREO:
1446                 if (get_user(val, (int *)arg))
1447                         return -EFAULT;
1448                 if (file->f_mode & FMODE_READ) {
1449                         stop_adc(s);
1450                         if (val)
1451                                 s->capcc |= CC_SM;
1452                         else
1453                                 s->capcc &= ~CC_SM;
1454                         outw(s->capcc, s->io+IT_AC_CAPCC);
1455                         if ((ret = prog_dmabuf_adc(s)))
1456                                 return ret;
1457                 }
1458                 if (file->f_mode & FMODE_WRITE) {
1459                         stop_dac(s);
1460                         if (val)
1461                                 s->pcc |= CC_SM;
1462                         else
1463                                 s->pcc &= ~CC_SM;
1464                         outw(s->pcc, s->io+IT_AC_PCC);
1465                         if ((ret = prog_dmabuf_dac(s)))
1466                                 return ret;
1467                 }
1468                 return 0;
1469
1470         case SNDCTL_DSP_CHANNELS:
1471                 if (get_user(val, (int *)arg))
1472                         return -EFAULT;
1473                 if (val != 0) {
1474                         if (file->f_mode & FMODE_READ) {
1475                                 stop_adc(s);
1476                                 if (val >= 2) {
1477                                         val = 2;
1478                                         s->capcc |= CC_SM;
1479                                 }
1480                                 else
1481                                         s->capcc &= ~CC_SM;
1482                                 outw(s->capcc, s->io+IT_AC_CAPCC);
1483                                 if ((ret = prog_dmabuf_adc(s)))
1484                                         return ret;
1485                         }
1486                         if (file->f_mode & FMODE_WRITE) {
1487                                 stop_dac(s);
1488                                 switch (val) {
1489                                 case 1:
1490                                         s->pcc &= ~CC_SM;
1491                                         break;
1492                                 case 2:
1493                                         s->pcc |= CC_SM;
1494                                         break;
1495                                 default:
1496                                         // FIX! support multichannel???
1497                                         val = 2;
1498                                         s->pcc |= CC_SM;
1499                                         break;
1500                                 }
1501                                 outw(s->pcc, s->io+IT_AC_PCC);
1502                                 if ((ret = prog_dmabuf_dac(s)))
1503                                         return ret;
1504                         }
1505                 }
1506                 return put_user(val, (int *)arg);
1507                 
1508         case SNDCTL_DSP_GETFMTS: /* Returns a mask */
1509                 return put_user(AFMT_S16_LE|AFMT_U8, (int *)arg);
1510                 
1511         case SNDCTL_DSP_SETFMT: /* Selects ONE fmt*/
1512                 if (get_user(val, (int *)arg))
1513                         return -EFAULT;
1514                 if (val != AFMT_QUERY) {
1515                         if (file->f_mode & FMODE_READ) {
1516                                 stop_adc(s);
1517                                 if (val == AFMT_S16_LE)
1518                                         s->capcc |= CC_DF;
1519                                 else {
1520                                         val = AFMT_U8;
1521                                         s->capcc &= ~CC_DF;
1522                                 }
1523                                 outw(s->capcc, s->io+IT_AC_CAPCC);
1524                                 if ((ret = prog_dmabuf_adc(s)))
1525                                         return ret;
1526                         }
1527                         if (file->f_mode & FMODE_WRITE) {
1528                                 stop_dac(s);
1529                                 if (val == AFMT_S16_LE)
1530                                         s->pcc |= CC_DF;
1531                                 else {
1532                                         val = AFMT_U8;
1533                                         s->pcc &= ~CC_DF;
1534                                 }
1535                                 outw(s->pcc, s->io+IT_AC_PCC);
1536                                 if ((ret = prog_dmabuf_dac(s)))
1537                                         return ret;
1538                         }
1539                 } else {
1540                         if (file->f_mode & FMODE_READ)
1541                                 val = (s->capcc & CC_DF) ?
1542                                         AFMT_S16_LE : AFMT_U8;
1543                         else
1544                                 val = (s->pcc & CC_DF) ?
1545                                         AFMT_S16_LE : AFMT_U8;
1546                 }
1547                 return put_user(val, (int *)arg);
1548                 
1549         case SNDCTL_DSP_POST:
1550                 return 0;
1551
1552         case SNDCTL_DSP_GETTRIGGER:
1553                 val = 0;
1554                 spin_lock_irqsave(&s->lock, flags);
1555                 if (file->f_mode & FMODE_READ && !s->dma_adc.stopped)
1556                         val |= PCM_ENABLE_INPUT;
1557                 if (file->f_mode & FMODE_WRITE && !s->dma_dac.stopped)
1558                         val |= PCM_ENABLE_OUTPUT;
1559                 spin_unlock_irqrestore(&s->lock, flags);
1560                 return put_user(val, (int *)arg);
1561                 
1562         case SNDCTL_DSP_SETTRIGGER:
1563                 if (get_user(val, (int *)arg))
1564                         return -EFAULT;
1565                 if (file->f_mode & FMODE_READ) {
1566                         if (val & PCM_ENABLE_INPUT)
1567                                 start_adc(s);
1568                         else
1569                                 stop_adc(s);
1570                 }
1571                 if (file->f_mode & FMODE_WRITE) {
1572                         if (val & PCM_ENABLE_OUTPUT)
1573                                 start_dac(s);
1574                         else
1575                                 stop_dac(s);
1576                 }
1577                 return 0;
1578
1579         case SNDCTL_DSP_GETOSPACE:
1580                 if (!(file->f_mode & FMODE_WRITE))
1581                         return -EINVAL;
1582                 abinfo.fragsize = s->dma_dac.fragsize;
1583                 spin_lock_irqsave(&s->lock, flags);
1584                 count = s->dma_dac.count;
1585                 if (!s->dma_dac.stopped)
1586                         count -= (s->dma_dac.fragsize -
1587                                   inw(s->io+IT_AC_PCDL));
1588                 spin_unlock_irqrestore(&s->lock, flags);
1589                 if (count < 0)
1590                         count = 0;
1591                 abinfo.bytes = s->dma_dac.dmasize - count;
1592                 abinfo.fragstotal = s->dma_dac.numfrag;
1593                 abinfo.fragments = abinfo.bytes >> s->dma_dac.fragshift;      
1594                 return copy_to_user((void *)arg, &abinfo, sizeof(abinfo)) ?
1595                         -EFAULT : 0;
1596
1597         case SNDCTL_DSP_GETISPACE:
1598                 if (!(file->f_mode & FMODE_READ))
1599                         return -EINVAL;
1600                 abinfo.fragsize = s->dma_adc.fragsize;
1601                 spin_lock_irqsave(&s->lock, flags);
1602                 count = s->dma_adc.count;
1603                 if (!s->dma_adc.stopped)
1604                         count += (s->dma_adc.fragsize -
1605                                   inw(s->io+IT_AC_CAPCDL));
1606                 spin_unlock_irqrestore(&s->lock, flags);
1607                 if (count < 0)
1608                         count = 0;
1609                 abinfo.bytes = count;
1610                 abinfo.fragstotal = s->dma_adc.numfrag;
1611                 abinfo.fragments = abinfo.bytes >> s->dma_adc.fragshift;      
1612                 return copy_to_user((void *)arg, &abinfo, sizeof(abinfo)) ?
1613                         -EFAULT : 0;
1614                 
1615         case SNDCTL_DSP_NONBLOCK:
1616                 file->f_flags |= O_NONBLOCK;
1617                 return 0;
1618
1619         case SNDCTL_DSP_GETODELAY:
1620                 if (!(file->f_mode & FMODE_WRITE))
1621                         return -EINVAL;
1622                 spin_lock_irqsave(&s->lock, flags);
1623                 count = s->dma_dac.count;
1624                 if (!s->dma_dac.stopped)
1625                         count -= (s->dma_dac.fragsize -
1626                                   inw(s->io+IT_AC_PCDL));
1627                 spin_unlock_irqrestore(&s->lock, flags);
1628                 if (count < 0)
1629                         count = 0;
1630                 return put_user(count, (int *)arg);
1631
1632         case SNDCTL_DSP_GETIPTR:
1633                 if (!(file->f_mode & FMODE_READ))
1634                         return -EINVAL;
1635                 spin_lock_irqsave(&s->lock, flags);
1636                 cinfo.bytes = s->dma_adc.total_bytes;
1637                 count = s->dma_adc.count;
1638                 if (!s->dma_adc.stopped) {
1639                         diff = s->dma_adc.fragsize - inw(s->io+IT_AC_CAPCDL);
1640                         count += diff;
1641                         cinfo.bytes += diff;
1642                         cinfo.ptr = inl(s->io+s->dma_adc.curBufPtr) -
1643                                 s->dma_adc.dmaaddr;
1644                 } else
1645                         cinfo.ptr = virt_to_bus(s->dma_adc.nextIn) -
1646                                 s->dma_adc.dmaaddr;
1647                 if (s->dma_adc.mapped)
1648                         s->dma_adc.count &= s->dma_adc.fragsize-1;
1649                 spin_unlock_irqrestore(&s->lock, flags);
1650                 if (count < 0)
1651                         count = 0;
1652                 cinfo.blocks = count >> s->dma_adc.fragshift;
1653                 return copy_to_user((void *)arg, &cinfo, sizeof(cinfo)) ? -EFAULT : 0;
1654
1655         case SNDCTL_DSP_GETOPTR:
1656                 if (!(file->f_mode & FMODE_READ))
1657                         return -EINVAL;
1658                 spin_lock_irqsave(&s->lock, flags);
1659                 cinfo.bytes = s->dma_dac.total_bytes;
1660                 count = s->dma_dac.count;
1661                 if (!s->dma_dac.stopped) {
1662                         diff = s->dma_dac.fragsize - inw(s->io+IT_AC_CAPCDL);
1663                         count -= diff;
1664                         cinfo.bytes += diff;
1665                         cinfo.ptr = inl(s->io+s->dma_dac.curBufPtr) -
1666                                 s->dma_dac.dmaaddr;
1667                 } else
1668                         cinfo.ptr = virt_to_bus(s->dma_dac.nextOut) -
1669                                 s->dma_dac.dmaaddr;
1670                 if (s->dma_dac.mapped)
1671                         s->dma_dac.count &= s->dma_dac.fragsize-1;
1672                 spin_unlock_irqrestore(&s->lock, flags);
1673                 if (count < 0)
1674                         count = 0;
1675                 cinfo.blocks = count >> s->dma_dac.fragshift;
1676                 return copy_to_user((void *)arg, &cinfo, sizeof(cinfo)) ? -EFAULT : 0;
1677
1678         case SNDCTL_DSP_GETBLKSIZE:
1679                 if (file->f_mode & FMODE_WRITE)
1680                         return put_user(s->dma_dac.fragsize, (int *)arg);
1681                 else
1682                         return put_user(s->dma_adc.fragsize, (int *)arg);
1683
1684         case SNDCTL_DSP_SETFRAGMENT:
1685                 if (get_user(val, (int *)arg))
1686                         return -EFAULT;
1687                 if (file->f_mode & FMODE_READ) {
1688                         stop_adc(s);
1689                         s->dma_adc.ossfragshift = val & 0xffff;
1690                         s->dma_adc.ossmaxfrags = (val >> 16) & 0xffff;
1691                         if (s->dma_adc.ossfragshift < 4)
1692                                 s->dma_adc.ossfragshift = 4;
1693                         if (s->dma_adc.ossfragshift > 15)
1694                                 s->dma_adc.ossfragshift = 15;
1695                         if (s->dma_adc.ossmaxfrags < 4)
1696                                 s->dma_adc.ossmaxfrags = 4;
1697                         if ((ret = prog_dmabuf_adc(s)))
1698                                 return ret;
1699                 }
1700                 if (file->f_mode & FMODE_WRITE) {
1701                         stop_dac(s);
1702                         s->dma_dac.ossfragshift = val & 0xffff;
1703                         s->dma_dac.ossmaxfrags = (val >> 16) & 0xffff;
1704                         if (s->dma_dac.ossfragshift < 4)
1705                                 s->dma_dac.ossfragshift = 4;
1706                         if (s->dma_dac.ossfragshift > 15)
1707                                 s->dma_dac.ossfragshift = 15;
1708                         if (s->dma_dac.ossmaxfrags < 4)
1709                                 s->dma_dac.ossmaxfrags = 4;
1710                         if ((ret = prog_dmabuf_dac(s)))
1711                                 return ret;
1712                 }
1713                 return 0;
1714
1715         case SNDCTL_DSP_SUBDIVIDE:
1716                 if ((file->f_mode & FMODE_READ && s->dma_adc.subdivision) ||
1717                     (file->f_mode & FMODE_WRITE && s->dma_dac.subdivision))
1718                         return -EINVAL;
1719                 if (get_user(val, (int *)arg))
1720                         return -EFAULT;
1721                 if (val != 1 && val != 2 && val != 4)
1722                         return -EINVAL;
1723                 if (file->f_mode & FMODE_READ) {
1724                         stop_adc(s);
1725                         s->dma_adc.subdivision = val;
1726                         if ((ret = prog_dmabuf_adc(s)))
1727                                 return ret;
1728                 }
1729                 if (file->f_mode & FMODE_WRITE) {
1730                         stop_dac(s);
1731                         s->dma_dac.subdivision = val;
1732                         if ((ret = prog_dmabuf_dac(s)))
1733                                 return ret;
1734                 }
1735                 return 0;
1736
1737         case SOUND_PCM_READ_RATE:
1738                 return put_user((file->f_mode & FMODE_READ) ?
1739                                 s->adcrate : s->dacrate, (int *)arg);
1740
1741         case SOUND_PCM_READ_CHANNELS:
1742                 if (file->f_mode & FMODE_READ)
1743                         return put_user((s->capcc & CC_SM) ? 2 : 1,
1744                                         (int *)arg);
1745                 else
1746                         return put_user((s->pcc & CC_SM) ? 2 : 1,
1747                                         (int *)arg);
1748             
1749         case SOUND_PCM_READ_BITS:
1750                 if (file->f_mode & FMODE_READ)
1751                         return put_user((s->capcc & CC_DF) ? 16 : 8,
1752                                         (int *)arg);
1753                 else
1754                         return put_user((s->pcc & CC_DF) ? 16 : 8,
1755                                         (int *)arg);
1756
1757         case SOUND_PCM_WRITE_FILTER:
1758         case SNDCTL_DSP_SETSYNCRO:
1759         case SOUND_PCM_READ_FILTER:
1760                 return -EINVAL;
1761         }
1762
1763         return mixdev_ioctl(s->codec, cmd, arg);
1764 }
1765
1766
1767 static int it8172_open(struct inode *inode, struct file *file)
1768 {
1769         int minor = iminor(inode);
1770         DECLARE_WAITQUEUE(wait, current);
1771         unsigned long flags;
1772         struct list_head *list;
1773         struct it8172_state *s;
1774         int ret;
1775     
1776 #ifdef IT8172_VERBOSE_DEBUG
1777         if (file->f_flags & O_NONBLOCK)
1778                 dbg("%s: non-blocking", __FUNCTION__);
1779         else
1780                 dbg("%s: blocking", __FUNCTION__);
1781 #endif
1782         
1783         for (list = devs.next; ; list = list->next) {
1784                 if (list == &devs)
1785                         return -ENODEV;
1786                 s = list_entry(list, struct it8172_state, devs);
1787                 if (!((s->dev_audio ^ minor) & ~0xf))
1788                         break;
1789         }
1790         file->private_data = s;
1791         /* wait for device to become free */
1792         down(&s->open_sem);
1793         while (s->open_mode & file->f_mode) {
1794                 if (file->f_flags & O_NONBLOCK) {
1795                         up(&s->open_sem);
1796                         return -EBUSY;
1797                 }
1798                 add_wait_queue(&s->open_wait, &wait);
1799                 __set_current_state(TASK_INTERRUPTIBLE);
1800                 up(&s->open_sem);
1801                 schedule();
1802                 remove_wait_queue(&s->open_wait, &wait);
1803                 set_current_state(TASK_RUNNING);
1804                 if (signal_pending(current))
1805                         return -ERESTARTSYS;
1806                 down(&s->open_sem);
1807         }
1808
1809         spin_lock_irqsave(&s->lock, flags);
1810
1811         if (file->f_mode & FMODE_READ) {
1812                 s->dma_adc.ossfragshift = s->dma_adc.ossmaxfrags =
1813                         s->dma_adc.subdivision = s->dma_adc.total_bytes = 0;
1814                 s->capcc &= ~(CC_SM | CC_DF);
1815                 set_adc_rate(s, 8000);
1816                 if ((minor & 0xf) == SND_DEV_DSP16)
1817                         s->capcc |= CC_DF;
1818                 outw(s->capcc, s->io+IT_AC_CAPCC);
1819                 if ((ret = prog_dmabuf_adc(s))) {
1820                         spin_unlock_irqrestore(&s->lock, flags);
1821                         return ret;
1822                 }
1823         }
1824         if (file->f_mode & FMODE_WRITE) {
1825                 s->dma_dac.ossfragshift = s->dma_dac.ossmaxfrags =
1826                         s->dma_dac.subdivision = s->dma_dac.total_bytes = 0;
1827                 s->pcc &= ~(CC_SM | CC_DF);
1828                 set_dac_rate(s, 8000);
1829                 if ((minor & 0xf) == SND_DEV_DSP16)
1830                         s->pcc |= CC_DF;
1831                 outw(s->pcc, s->io+IT_AC_PCC);
1832                 if ((ret = prog_dmabuf_dac(s))) {
1833                         spin_unlock_irqrestore(&s->lock, flags);
1834                         return ret;
1835                 }
1836         }
1837     
1838         spin_unlock_irqrestore(&s->lock, flags);
1839
1840         s->open_mode |= (file->f_mode & (FMODE_READ | FMODE_WRITE));
1841         up(&s->open_sem);
1842         return nonseekable_open(inode, file);
1843 }
1844
1845 static int it8172_release(struct inode *inode, struct file *file)
1846 {
1847         struct it8172_state *s = (struct it8172_state *)file->private_data;
1848
1849 #ifdef IT8172_VERBOSE_DEBUG
1850         dbg(__FUNCTION__);
1851 #endif
1852         lock_kernel();
1853         if (file->f_mode & FMODE_WRITE)
1854                 drain_dac(s, file->f_flags & O_NONBLOCK);
1855         down(&s->open_sem);
1856         if (file->f_mode & FMODE_WRITE) {
1857                 stop_dac(s);
1858                 dealloc_dmabuf(s, &s->dma_dac);
1859         }
1860         if (file->f_mode & FMODE_READ) {
1861                 stop_adc(s);
1862                 dealloc_dmabuf(s, &s->dma_adc);
1863         }
1864         s->open_mode &= ((~file->f_mode) & (FMODE_READ|FMODE_WRITE));
1865         up(&s->open_sem);
1866         wake_up(&s->open_wait);
1867         unlock_kernel();
1868         return 0;
1869 }
1870
1871 static /*const*/ struct file_operations it8172_audio_fops = {
1872         .owner          = THIS_MODULE,
1873         .llseek         = it8172_llseek,
1874         .read           = it8172_read,
1875         .write          = it8172_write,
1876         .poll           = it8172_poll,
1877         .ioctl          = it8172_ioctl,
1878         .mmap           = it8172_mmap,
1879         .open           = it8172_open,
1880         .release        = it8172_release,
1881 };
1882
1883
1884 /* --------------------------------------------------------------------- */
1885
1886
1887 /* --------------------------------------------------------------------- */
1888
1889 /*
1890  * for debugging purposes, we'll create a proc device that dumps the
1891  * CODEC chipstate
1892  */
1893
1894 #ifdef IT8172_DEBUG
1895 static int proc_it8172_dump (char *buf, char **start, off_t fpos,
1896                              int length, int *eof, void *data)
1897 {
1898         struct it8172_state *s;
1899         int cnt, len = 0;
1900
1901         if (list_empty(&devs))
1902                 return 0;
1903         s = list_entry(devs.next, struct it8172_state, devs);
1904
1905         /* print out header */
1906         len += sprintf(buf + len, "\n\t\tIT8172 Audio Debug\n\n");
1907
1908         // print out digital controller state
1909         len += sprintf (buf + len, "IT8172 Audio Controller registers\n");
1910         len += sprintf (buf + len, "---------------------------------\n");
1911         cnt=0;
1912         while (cnt < 0x72) {
1913                 if (cnt == IT_AC_PCB1STA || cnt == IT_AC_PCB2STA ||
1914                     cnt == IT_AC_CAPB1STA || cnt == IT_AC_CAPB2STA ||
1915                     cnt == IT_AC_PFDP) {
1916                         len+= sprintf (buf + len, "reg %02x = %08x\n",
1917                                        cnt, inl(s->io+cnt));
1918                         cnt += 4;
1919                 } else {
1920                         len+= sprintf (buf + len, "reg %02x = %04x\n",
1921                                        cnt, inw(s->io+cnt));
1922                         cnt += 2;
1923                 }
1924         }
1925     
1926         /* print out CODEC state */
1927         len += sprintf (buf + len, "\nAC97 CODEC registers\n");
1928         len += sprintf (buf + len, "----------------------\n");
1929         for (cnt=0; cnt <= 0x7e; cnt = cnt +2)
1930                 len+= sprintf (buf + len, "reg %02x = %04x\n",
1931                                cnt, rdcodec(s->codec, cnt));
1932
1933         if (fpos >=len){
1934                 *start = buf;
1935                 *eof =1;
1936                 return 0;
1937         }
1938         *start = buf + fpos;
1939         if ((len -= fpos) > length)
1940                 return length;
1941         *eof =1;
1942         return len;
1943
1944 }
1945 #endif /* IT8172_DEBUG */
1946
1947 /* --------------------------------------------------------------------- */
1948
1949 /* maximum number of devices; only used for command line params */
1950 #define NR_DEVICE 5
1951
1952 static int spdif[NR_DEVICE];
1953 static int i2s_fmt[NR_DEVICE];
1954
1955 static unsigned int devindex;
1956
1957 MODULE_PARM(spdif, "1-" __MODULE_STRING(NR_DEVICE) "i");
1958 MODULE_PARM_DESC(spdif, "if 1 the S/PDIF digital output is enabled");
1959 MODULE_PARM(i2s_fmt, "1-" __MODULE_STRING(NR_DEVICE) "i");
1960 MODULE_PARM_DESC(i2s_fmt, "the format of I2S");
1961
1962 MODULE_AUTHOR("Monta Vista Software, stevel@mvista.com");
1963 MODULE_DESCRIPTION("IT8172 Audio Driver");
1964
1965 /* --------------------------------------------------------------------- */
1966
1967 static int __devinit it8172_probe(struct pci_dev *pcidev,
1968                                   const struct pci_device_id *pciid)
1969 {
1970         struct it8172_state *s;
1971         int i, val;
1972         unsigned short pcisr, vol;
1973         unsigned char legacy, imc;
1974         char proc_str[80];
1975     
1976         if (pcidev->irq == 0) 
1977                 return -1;
1978
1979         if (!(s = kmalloc(sizeof(struct it8172_state), GFP_KERNEL))) {
1980                 err("alloc of device struct failed");
1981                 return -1;
1982         }
1983         
1984         memset(s, 0, sizeof(struct it8172_state));
1985         init_waitqueue_head(&s->dma_adc.wait);
1986         init_waitqueue_head(&s->dma_dac.wait);
1987         init_waitqueue_head(&s->open_wait);
1988         init_MUTEX(&s->open_sem);
1989         spin_lock_init(&s->lock);
1990         s->dev = pcidev;
1991         s->io = pci_resource_start(pcidev, 0);
1992         s->irq = pcidev->irq;
1993         s->vendor = pcidev->vendor;
1994         s->device = pcidev->device;
1995         pci_read_config_byte(pcidev, PCI_REVISION_ID, &s->rev);
1996         
1997         s->codec = ac97_alloc_codec();
1998         if(s->codec == NULL)
1999                 goto err_codec;
2000                 
2001         s->codec->private_data = s;
2002         s->codec->id = 0;
2003         s->codec->codec_read = rdcodec;
2004         s->codec->codec_write = wrcodec;
2005         s->codec->codec_wait = waitcodec;
2006
2007         if (!request_region(s->io, pci_resource_len(pcidev,0),
2008                             IT8172_MODULE_NAME)) {
2009                 err("io ports %#lx->%#lx in use",
2010                     s->io, s->io + pci_resource_len(pcidev,0)-1);
2011                 goto err_region;
2012         }
2013         if (request_irq(s->irq, it8172_interrupt, SA_INTERRUPT,
2014                         IT8172_MODULE_NAME, s)) {
2015                 err("irq %u in use", s->irq);
2016                 goto err_irq;
2017         }
2018
2019         info("IO at %#lx, IRQ %d", s->io, s->irq);
2020
2021         /* register devices */
2022         if ((s->dev_audio = register_sound_dsp(&it8172_audio_fops, -1)) < 0)
2023                 goto err_dev1;
2024         if ((s->codec->dev_mixer =
2025              register_sound_mixer(&it8172_mixer_fops, -1)) < 0)
2026                 goto err_dev2;
2027
2028 #ifdef IT8172_DEBUG
2029         /* intialize the debug proc device */
2030         s->ps = create_proc_read_entry(IT8172_MODULE_NAME, 0, NULL,
2031                                        proc_it8172_dump, NULL);
2032 #endif /* IT8172_DEBUG */
2033         
2034         /*
2035          * Reset the Audio device using the IT8172 PCI Reset register. This
2036          * creates an audible double click on a speaker connected to Line-out.
2037          */
2038         IT_IO_READ16(IT_PM_PCISR, pcisr);
2039         pcisr |= IT_PM_PCISR_ACSR;
2040         IT_IO_WRITE16(IT_PM_PCISR, pcisr);
2041         /* wait up to 100msec for reset to complete */
2042         for (i=0; pcisr & IT_PM_PCISR_ACSR; i++) {
2043                 it8172_delay(10);
2044                 if (i == 10)
2045                         break;
2046                 IT_IO_READ16(IT_PM_PCISR, pcisr);
2047         }
2048         if (i == 10) {
2049                 err("chip reset timeout!");
2050                 goto err_dev3;
2051         }
2052     
2053         /* enable pci io and bus mastering */
2054         if (pci_enable_device(pcidev))
2055                 goto err_dev3;
2056         pci_set_master(pcidev);
2057
2058         /* get out of legacy mode */
2059         pci_read_config_byte (pcidev, 0x40, &legacy);
2060         pci_write_config_byte (pcidev, 0x40, legacy & ~1);
2061     
2062         s->spdif_volume = -1;
2063         /* check to see if s/pdif mode is being requested */
2064         if (spdif[devindex]) {
2065                 info("enabling S/PDIF output");
2066                 s->spdif_volume = 0;
2067                 outb(GC_SOE, s->io+IT_AC_GC);
2068         } else {
2069                 info("disabling S/PDIF output");
2070                 outb(0, s->io+IT_AC_GC);
2071         }
2072     
2073         /* check to see if I2S format requested */
2074         if (i2s_fmt[devindex]) {
2075                 info("setting I2S format to 0x%02x", i2s_fmt[devindex]);
2076                 outb(i2s_fmt[devindex], s->io+IT_AC_I2SMC);
2077         } else {
2078                 outb(I2SMC_I2SF_I2S, s->io+IT_AC_I2SMC);
2079         }
2080
2081         /* cold reset the AC97 */
2082         outw(CODECC_CR, s->io+IT_AC_CODECC);
2083         udelay(1000);
2084         outw(0, s->io+IT_AC_CODECC);
2085         /* need to delay around 500msec(bleech) to give
2086            some CODECs enough time to wakeup */
2087         it8172_delay(500);
2088     
2089         /* AC97 warm reset to start the bitclk */
2090         outw(CODECC_WR, s->io+IT_AC_CODECC);
2091         udelay(1000);
2092         outw(0, s->io+IT_AC_CODECC);
2093     
2094         /* codec init */
2095         if (!ac97_probe_codec(s->codec))
2096                 goto err_dev3;
2097
2098         /* add I2S as allowable recording source */
2099         s->codec->record_sources |= SOUND_MASK_I2S;
2100         
2101         /* Enable Volume button interrupts */
2102         imc = inb(s->io+IT_AC_IMC);
2103         outb(imc & ~IMC_VCIM, s->io+IT_AC_IMC);
2104
2105         /* Un-mute PCM and FM out on the controller */
2106         vol = inw(s->io+IT_AC_PCMOV);
2107         outw(vol & ~PCMOV_PCMOM, s->io+IT_AC_PCMOV);
2108         vol = inw(s->io+IT_AC_FMOV);
2109         outw(vol & ~FMOV_FMOM, s->io+IT_AC_FMOV);
2110     
2111         /* set channel defaults to 8-bit, mono, 8 Khz */
2112         s->pcc = 0;
2113         s->capcc = 0;
2114         set_dac_rate(s, 8000);
2115         set_adc_rate(s, 8000);
2116
2117         /* set mic to be the recording source */
2118         val = SOUND_MASK_MIC;
2119         mixdev_ioctl(s->codec, SOUND_MIXER_WRITE_RECSRC,
2120                      (unsigned long)&val);
2121
2122         /* mute AC'97 master and PCM when in S/PDIF mode */
2123         if (s->spdif_volume != -1) {
2124                 val = 0x0000;
2125                 s->codec->mixer_ioctl(s->codec, SOUND_MIXER_WRITE_VOLUME,
2126                                      (unsigned long)&val);
2127                 s->codec->mixer_ioctl(s->codec, SOUND_MIXER_WRITE_PCM,
2128                                      (unsigned long)&val);
2129         }
2130     
2131 #ifdef IT8172_DEBUG
2132         sprintf(proc_str, "driver/%s/%d/ac97", IT8172_MODULE_NAME,
2133                 s->codec->id);
2134         s->ac97_ps = create_proc_read_entry (proc_str, 0, NULL,
2135                                              ac97_read_proc, s->codec);
2136 #endif
2137     
2138         /* store it in the driver field */
2139         pci_set_drvdata(pcidev, s);
2140         pcidev->dma_mask = 0xffffffff;
2141         /* put it into driver list */
2142         list_add_tail(&s->devs, &devs);
2143         /* increment devindex */
2144         if (devindex < NR_DEVICE-1)
2145                 devindex++;
2146         return 0;
2147
2148  err_dev3:
2149         unregister_sound_mixer(s->codec->dev_mixer);
2150  err_dev2:
2151         unregister_sound_dsp(s->dev_audio);
2152  err_dev1:
2153         err("cannot register misc device");
2154         free_irq(s->irq, s);
2155  err_irq:
2156         release_region(s->io, pci_resource_len(pcidev,0));
2157  err_region:
2158         ac97_release_codec(s->codec);
2159  err_codec:
2160         kfree(s);
2161         return -1;
2162 }
2163
2164 static void __devexit it8172_remove(struct pci_dev *dev)
2165 {
2166         struct it8172_state *s = pci_get_drvdata(dev);
2167
2168         if (!s)
2169                 return;
2170         list_del(&s->devs);
2171 #ifdef IT8172_DEBUG
2172         if (s->ps)
2173                 remove_proc_entry(IT8172_MODULE_NAME, NULL);
2174 #endif /* IT8172_DEBUG */
2175         synchronize_irq();
2176         free_irq(s->irq, s);
2177         release_region(s->io, pci_resource_len(dev,0));
2178         unregister_sound_dsp(s->dev_audio);
2179         unregister_sound_mixer(s->codec->dev_mixer);
2180         ac97_codec_release(s->codec);
2181         kfree(s);
2182         pci_set_drvdata(dev, NULL);
2183 }
2184
2185
2186
2187 static struct pci_device_id id_table[] = {
2188         { PCI_VENDOR_ID_ITE, PCI_DEVICE_ID_ITE_IT8172G_AUDIO, PCI_ANY_ID,
2189           PCI_ANY_ID, 0, 0 },
2190         { 0, }
2191 };
2192
2193 MODULE_DEVICE_TABLE(pci, id_table);
2194
2195 static struct pci_driver it8172_driver = {
2196         .name = IT8172_MODULE_NAME,
2197         .id_table = id_table,
2198         .probe = it8172_probe,
2199         .remove = __devexit_p(it8172_remove)
2200 };
2201
2202 static int __init init_it8172(void)
2203 {
2204         if (!pci_present())   /* No PCI bus in this machine! */
2205                 return -ENODEV;
2206         info("version v0.5 time " __TIME__ " " __DATE__);
2207         return pci_module_init(&it8172_driver);
2208 }
2209
2210 static void __exit cleanup_it8172(void)
2211 {
2212         info("unloading");
2213         pci_unregister_driver(&it8172_driver);
2214 }
2215
2216 module_init(init_it8172);
2217 module_exit(cleanup_it8172);
2218
2219 /* --------------------------------------------------------------------- */
2220
2221 #ifndef MODULE
2222
2223 /* format is: it8172=[spdif],[i2s:<I2S format>] */
2224
2225 static int __init it8172_setup(char *options)
2226 {
2227         char* this_opt;
2228         static unsigned __initdata nr_dev = 0;
2229
2230         if (nr_dev >= NR_DEVICE)
2231                 return 0;
2232
2233         if (!options || !*options)
2234                 return 0;
2235
2236         while (this_opt = strsep(&options, ",")) {
2237                 if (!*this_opt)
2238                         continue;
2239                 if (!strncmp(this_opt, "spdif", 5)) {
2240                         spdif[nr_dev] = 1;
2241                 } else if (!strncmp(this_opt, "i2s:", 4)) {
2242                         if (!strncmp(this_opt+4, "dac", 3))
2243                                 i2s_fmt[nr_dev] = I2SMC_I2SF_DAC;
2244                         else if (!strncmp(this_opt+4, "adc", 3))
2245                                 i2s_fmt[nr_dev] = I2SMC_I2SF_ADC;
2246                         else if (!strncmp(this_opt+4, "i2s", 3))
2247                                 i2s_fmt[nr_dev] = I2SMC_I2SF_I2S;
2248                 }
2249         }
2250
2251         nr_dev++;
2252         return 1;
2253 }
2254
2255 __setup("it8172=", it8172_setup);
2256
2257 #endif /* MODULE */