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