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