VServer 1.9.2 (patch-2.6.8.1-vs1.9.2.diff)
[linux-2.6.git] / sound / oss / i810_audio.c
1 /*
2  *      Intel i810 and friends ICH driver for Linux
3  *      Alan Cox <alan@redhat.com>
4  *
5  *  Built from:
6  *      Low level code:  Zach Brown (original nonworking i810 OSS driver)
7  *                       Jaroslav Kysela <perex@suse.cz> (working ALSA driver)
8  *
9  *      Framework: Thomas Sailer <sailer@ife.ee.ethz.ch>
10  *      Extended by: Zach Brown <zab@redhat.com>  
11  *                      and others..
12  *
13  *  Hardware Provided By:
14  *      Analog Devices (A major AC97 codec maker)
15  *      Intel Corp  (you've probably heard of them already)
16  *
17  *  AC97 clues and assistance provided by
18  *      Analog Devices
19  *      Zach 'Fufu' Brown
20  *      Jeff Garzik
21  *
22  *      This program is free software; you can redistribute it and/or modify
23  *      it under the terms of the GNU General Public License as published by
24  *      the Free Software Foundation; either version 2 of the License, or
25  *      (at your option) any later version.
26  *
27  *      This program is distributed in the hope that it will be useful,
28  *      but WITHOUT ANY WARRANTY; without even the implied warranty of
29  *      MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
30  *      GNU General Public License for more details.
31  *
32  *      You should have received a copy of the GNU General Public License
33  *      along with this program; if not, write to the Free Software
34  *      Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
35  *
36  *
37  *      Intel 810 theory of operation
38  *
39  *      The chipset provides three DMA channels that talk to an AC97
40  *      CODEC (AC97 is a digital/analog mixer standard). At its simplest
41  *      you get 48Khz audio with basic volume and mixer controls. At the
42  *      best you get rate adaption in the codec. We set the card up so
43  *      that we never take completion interrupts but instead keep the card
44  *      chasing its tail around a ring buffer. This is needed for mmap
45  *      mode audio and happens to work rather well for non-mmap modes too.
46  *
47  *      The board has one output channel for PCM audio (supported) and
48  *      a stereo line in and mono microphone input. Again these are normally
49  *      locked to 48Khz only. Right now recording is not finished.
50  *
51  *      There is no midi support, no synth support. Use timidity. To get
52  *      esd working you need to use esd -r 48000 as it won't probe 48KHz
53  *      by default. mpg123 can't handle 48Khz only audio so use xmms.
54  *
55  *      Fix The Sound On Dell
56  *
57  *      Not everyone uses 48KHz. We know of no way to detect this reliably
58  *      and certainly not to get the right data. If your i810 audio sounds
59  *      stupid you may need to investigate other speeds. According to Analog
60  *      they tend to use a 14.318MHz clock which gives you a base rate of
61  *      41194Hz.
62  *
63  *      This is available via the 'ftsodell=1' option. 
64  *
65  *      If you need to force a specific rate set the clocking= option
66  *
67  *      This driver is cursed. (Ben LaHaise)
68  *
69  *  ICH 3 caveats
70  *      Intel errata #7 for ICH3 IO. We need to disable SMI stuff
71  *      when codec probing. [Not Yet Done]
72  *
73  *  ICH 4 caveats
74  *
75  *      The ICH4 has the feature, that the codec ID doesn't have to be 
76  *      congruent with the IO connection.
77  * 
78  *      Therefore, from driver version 0.23 on, there is a "codec ID" <->
79  *      "IO register base offset" mapping (card->ac97_id_map) field.
80  *   
81  *      Juergen "George" Sawinski (jsaw) 
82  */
83  
84 #include <linux/module.h>
85 #include <linux/string.h>
86 #include <linux/ctype.h>
87 #include <linux/ioport.h>
88 #include <linux/sched.h>
89 #include <linux/delay.h>
90 #include <linux/sound.h>
91 #include <linux/slab.h>
92 #include <linux/soundcard.h>
93 #include <linux/pci.h>
94 #include <linux/interrupt.h>
95 #include <asm/io.h>
96 #include <asm/dma.h>
97 #include <linux/init.h>
98 #include <linux/poll.h>
99 #include <linux/spinlock.h>
100 #include <linux/smp_lock.h>
101 #include <linux/ac97_codec.h>
102 #include <linux/bitops.h>
103 #include <asm/uaccess.h>
104 #include <asm/hardirq.h>
105
106 #define DRIVER_VERSION "1.01"
107
108 #define MODULOP2(a, b) ((a) & ((b) - 1))
109 #define MASKP2(a, b) ((a) & ~((b) - 1))
110
111 static int ftsodell;
112 static int strict_clocking;
113 static unsigned int clocking;
114 static int spdif_locked;
115
116 //#define DEBUG
117 //#define DEBUG2
118 //#define DEBUG_INTERRUPTS
119 //#define DEBUG_MMAP
120 //#define DEBUG_MMIO
121
122 #define ADC_RUNNING     1
123 #define DAC_RUNNING     2
124
125 #define I810_FMT_16BIT  1
126 #define I810_FMT_STEREO 2
127 #define I810_FMT_MASK   3
128
129 #define SPDIF_ON        0x0004
130 #define SURR_ON         0x0010
131 #define CENTER_LFE_ON   0x0020
132 #define VOL_MUTED       0x8000
133
134 /* the 810's array of pointers to data buffers */
135
136 struct sg_item {
137 #define BUSADDR_MASK    0xFFFFFFFE
138         u32 busaddr;    
139 #define CON_IOC         0x80000000 /* interrupt on completion */
140 #define CON_BUFPAD      0x40000000 /* pad underrun with last sample, else 0 */
141 #define CON_BUFLEN_MASK 0x0000ffff /* buffer length in samples */
142         u32 control;
143 };
144
145 /* an instance of the i810 channel */
146 #define SG_LEN 32
147 struct i810_channel 
148 {
149         /* these sg guys should probably be allocated
150            separately as nocache. Must be 8 byte aligned */
151         struct sg_item sg[SG_LEN];      /* 32*8 */
152         u32 offset;                     /* 4 */
153         u32 port;                       /* 4 */
154         u32 used;
155         u32 num;
156 };
157
158 /*
159  * we have 3 separate dma engines.  pcm in, pcm out, and mic.
160  * each dma engine has controlling registers.  These goofy
161  * names are from the datasheet, but make it easy to write
162  * code while leafing through it.
163  *
164  * ICH4 has 6 dma engines, pcm in, pcm out, mic, pcm in 2, 
165  * mic in 2, s/pdif.   Of special interest is the fact that
166  * the upper 3 DMA engines on the ICH4 *must* be accessed
167  * via mmio access instead of pio access.
168  */
169
170 #define ENUM_ENGINE(PRE,DIG)                                                                    \
171 enum {                                                                                          \
172         PRE##_BASE =    0x##DIG##0,             /* Base Address */                              \
173         PRE##_BDBAR =   0x##DIG##0,             /* Buffer Descriptor list Base Address */       \
174         PRE##_CIV =     0x##DIG##4,             /* Current Index Value */                       \
175         PRE##_LVI =     0x##DIG##5,             /* Last Valid Index */                          \
176         PRE##_SR =      0x##DIG##6,             /* Status Register */                           \
177         PRE##_PICB =    0x##DIG##8,             /* Position In Current Buffer */                \
178         PRE##_PIV =     0x##DIG##a,             /* Prefetched Index Value */                    \
179         PRE##_CR =      0x##DIG##b              /* Control Register */                          \
180 }
181
182 ENUM_ENGINE(OFF,0);     /* Offsets */
183 ENUM_ENGINE(PI,0);      /* PCM In */
184 ENUM_ENGINE(PO,1);      /* PCM Out */
185 ENUM_ENGINE(MC,2);      /* Mic In */
186
187 enum {
188         GLOB_CNT =      0x2c,                   /* Global Control */
189         GLOB_STA =      0x30,                   /* Global Status */
190         CAS      =      0x34                    /* Codec Write Semaphore Register */
191 };
192
193 ENUM_ENGINE(MC2,4);     /* Mic In 2 */
194 ENUM_ENGINE(PI2,5);     /* PCM In 2 */
195 ENUM_ENGINE(SP,6);      /* S/PDIF */
196
197 enum {
198         SDM =           0x80                    /* SDATA_IN Map Register */
199 };
200
201 /* interrupts for a dma engine */
202 #define DMA_INT_FIFO            (1<<4)  /* fifo under/over flow */
203 #define DMA_INT_COMPLETE        (1<<3)  /* buffer read/write complete and ioc set */
204 #define DMA_INT_LVI             (1<<2)  /* last valid done */
205 #define DMA_INT_CELV            (1<<1)  /* last valid is current */
206 #define DMA_INT_DCH             (1)     /* DMA Controller Halted (happens on LVI interrupts) */
207 #define DMA_INT_MASK (DMA_INT_FIFO|DMA_INT_COMPLETE|DMA_INT_LVI)
208
209 /* interrupts for the whole chip */
210 #define INT_SEC         (1<<11)
211 #define INT_PRI         (1<<10)
212 #define INT_MC          (1<<7)
213 #define INT_PO          (1<<6)
214 #define INT_PI          (1<<5)
215 #define INT_MO          (1<<2)
216 #define INT_NI          (1<<1)
217 #define INT_GPI         (1<<0)
218 #define INT_MASK (INT_SEC|INT_PRI|INT_MC|INT_PO|INT_PI|INT_MO|INT_NI|INT_GPI)
219
220 /* magic numbers to protect our data structures */
221 #define I810_CARD_MAGIC         0x5072696E /* "Prin" */
222 #define I810_STATE_MAGIC        0x63657373 /* "cess" */
223 #define I810_DMA_MASK           0xffffffff /* DMA buffer mask for pci_alloc_consist */
224 #define NR_HW_CH                3
225
226 /* maxinum number of AC97 codecs connected, AC97 2.0 defined 4 */
227 #define NR_AC97                 4
228
229 /* Please note that an 8bit mono stream is not valid on this card, you must have a 16bit */
230 /* stream at a minimum for this card to be happy */
231 static const unsigned sample_size[] = { 1, 2, 2, 4 };
232 /* Samples are 16bit values, so we are shifting to a word, not to a byte, hence shift */
233 /* values are one less than might be expected */
234 static const unsigned sample_shift[] = { -1, 0, 0, 1 };
235
236 enum {
237         ICH82801AA = 0,
238         ICH82901AB,
239         INTEL440MX,
240         INTELICH2,
241         INTELICH3,
242         INTELICH4,
243         INTELICH5,
244         SI7012,
245         NVIDIA_NFORCE,
246         AMD768,
247         AMD8111
248 };
249
250 static char * card_names[] = {
251         "Intel ICH 82801AA",
252         "Intel ICH 82901AB",
253         "Intel 440MX",
254         "Intel ICH2",
255         "Intel ICH3",
256         "Intel ICH4",
257         "Intel ICH5",
258         "SiS 7012",
259         "NVIDIA nForce Audio",
260         "AMD 768",
261         "AMD-8111 IOHub"
262 };
263
264 /* These are capabilities (and bugs) the chipsets _can_ have */
265 static struct {
266         int16_t      nr_ac97;
267 #define CAP_MMIO                 0x0001
268 #define CAP_20BIT_AUDIO_SUPPORT  0x0002
269         u_int16_t flags;
270 } card_cap[] = {
271         {  1, 0x0000 }, /* ICH82801AA */
272         {  1, 0x0000 }, /* ICH82901AB */
273         {  1, 0x0000 }, /* INTEL440MX */
274         {  1, 0x0000 }, /* INTELICH2 */
275         {  2, 0x0000 }, /* INTELICH3 */
276         {  3, 0x0003 }, /* INTELICH4 */
277         {  3, 0x0003 }, /* INTELICH5 */
278         /*@FIXME to be verified*/       {  2, 0x0000 }, /* SI7012 */
279         /*@FIXME to be verified*/       {  2, 0x0000 }, /* NVIDIA_NFORCE */
280         /*@FIXME to be verified*/       {  2, 0x0000 }, /* AMD768 */
281         /*@FIXME to be verified*/       {  3, 0x0001 }, /* AMD8111 */
282 };
283
284 static struct pci_device_id i810_pci_tbl [] = {
285         {PCI_VENDOR_ID_INTEL, PCI_DEVICE_ID_INTEL_82801AA_5,
286          PCI_ANY_ID, PCI_ANY_ID, 0, 0, ICH82801AA},
287         {PCI_VENDOR_ID_INTEL, PCI_DEVICE_ID_INTEL_82801AB_5,
288          PCI_ANY_ID, PCI_ANY_ID, 0, 0, ICH82901AB},
289         {PCI_VENDOR_ID_INTEL, PCI_DEVICE_ID_INTEL_440MX,
290          PCI_ANY_ID, PCI_ANY_ID, 0, 0, INTEL440MX},
291         {PCI_VENDOR_ID_INTEL, PCI_DEVICE_ID_INTEL_82801BA_4,
292          PCI_ANY_ID, PCI_ANY_ID, 0, 0, INTELICH2},
293         {PCI_VENDOR_ID_INTEL, PCI_DEVICE_ID_INTEL_82801CA_5,
294          PCI_ANY_ID, PCI_ANY_ID, 0, 0, INTELICH3},
295         {PCI_VENDOR_ID_INTEL, PCI_DEVICE_ID_INTEL_82801DB_5,
296          PCI_ANY_ID, PCI_ANY_ID, 0, 0, INTELICH4},
297         {PCI_VENDOR_ID_INTEL, PCI_DEVICE_ID_INTEL_82801EB_5,
298          PCI_ANY_ID, PCI_ANY_ID, 0, 0, INTELICH5},
299         {PCI_VENDOR_ID_SI, PCI_DEVICE_ID_SI_7012,
300          PCI_ANY_ID, PCI_ANY_ID, 0, 0, SI7012},
301         {PCI_VENDOR_ID_NVIDIA, PCI_DEVICE_ID_NVIDIA_MCP1_AUDIO,
302          PCI_ANY_ID, PCI_ANY_ID, 0, 0, NVIDIA_NFORCE},
303         {PCI_VENDOR_ID_NVIDIA, PCI_DEVICE_ID_NVIDIA_MCP2_AUDIO,
304          PCI_ANY_ID, PCI_ANY_ID, 0, 0, NVIDIA_NFORCE},
305         {PCI_VENDOR_ID_NVIDIA, PCI_DEVICE_ID_NVIDIA_MCP3_AUDIO,
306          PCI_ANY_ID, PCI_ANY_ID, 0, 0, NVIDIA_NFORCE},
307         {PCI_VENDOR_ID_AMD, PCI_DEVICE_ID_AMD_OPUS_7445,
308          PCI_ANY_ID, PCI_ANY_ID, 0, 0, AMD768},
309         {PCI_VENDOR_ID_AMD, PCI_DEVICE_ID_AMD_8111_AUDIO,
310          PCI_ANY_ID, PCI_ANY_ID, 0, 0, AMD8111},
311         {PCI_VENDOR_ID_INTEL, PCI_DEVICE_ID_INTEL_ESB_5,
312          PCI_ANY_ID, PCI_ANY_ID, 0, 0, INTELICH4},
313         {PCI_VENDOR_ID_INTEL, PCI_DEVICE_ID_INTEL_ICH6_18,
314          PCI_ANY_ID, PCI_ANY_ID, 0, 0, INTELICH4},
315
316         {0,}
317 };
318
319 MODULE_DEVICE_TABLE (pci, i810_pci_tbl);
320
321 #ifdef CONFIG_PM
322 #define PM_SUSPENDED(card) (card->pm_suspended)
323 #else
324 #define PM_SUSPENDED(card) (0)
325 #endif
326
327 /* "software" or virtual channel, an instance of opened /dev/dsp */
328 struct i810_state {
329         unsigned int magic;
330         struct i810_card *card; /* Card info */
331
332         /* single open lock mechanism, only used for recording */
333         struct semaphore open_sem;
334         wait_queue_head_t open_wait;
335
336         /* file mode */
337         mode_t open_mode;
338
339         /* virtual channel number */
340         int virt;
341
342 #ifdef CONFIG_PM
343         unsigned int pm_saved_dac_rate,pm_saved_adc_rate;
344 #endif
345         struct dmabuf {
346                 /* wave sample stuff */
347                 unsigned int rate;
348                 unsigned char fmt, enable, trigger;
349
350                 /* hardware channel */
351                 struct i810_channel *read_channel;
352                 struct i810_channel *write_channel;
353
354                 /* OSS buffer management stuff */
355                 void *rawbuf;
356                 dma_addr_t dma_handle;
357                 unsigned buforder;
358                 unsigned numfrag;
359                 unsigned fragshift;
360
361                 /* our buffer acts like a circular ring */
362                 unsigned hwptr;         /* where dma last started, updated by update_ptr */
363                 unsigned swptr;         /* where driver last clear/filled, updated by read/write */
364                 int count;              /* bytes to be consumed or been generated by dma machine */
365                 unsigned total_bytes;   /* total bytes dmaed by hardware */
366
367                 unsigned error;         /* number of over/underruns */
368                 wait_queue_head_t wait; /* put process on wait queue when no more space in buffer */
369
370                 /* redundant, but makes calculations easier */
371                 /* what the hardware uses */
372                 unsigned dmasize;
373                 unsigned fragsize;
374                 unsigned fragsamples;
375
376                 /* what we tell the user to expect */
377                 unsigned userfrags;
378                 unsigned userfragsize;
379
380                 /* OSS stuff */
381                 unsigned mapped:1;
382                 unsigned ready:1;
383                 unsigned update_flag;
384                 unsigned ossfragsize;
385                 unsigned ossmaxfrags;
386                 unsigned subdivision;
387         } dmabuf;
388 };
389
390
391 struct i810_card {
392         unsigned int magic;
393
394         /* We keep i810 cards in a linked list */
395         struct i810_card *next;
396
397         /* The i810 has a certain amount of cross channel interaction
398            so we use a single per card lock */
399         spinlock_t lock;
400         
401         /* Control AC97 access serialization */
402         spinlock_t ac97_lock;
403
404         /* PCI device stuff */
405         struct pci_dev * pci_dev;
406         u16 pci_id;
407         u16 pci_id_internal; /* used to access card_cap[] */
408 #ifdef CONFIG_PM        
409         u16 pm_suspended;
410         u32 pm_save_state[64/sizeof(u32)];
411         int pm_saved_mixer_settings[SOUND_MIXER_NRDEVICES][NR_AC97];
412 #endif
413         /* soundcore stuff */
414         int dev_audio;
415
416         /* structures for abstraction of hardware facilities, codecs, banks and channels*/
417         u16    ac97_id_map[NR_AC97];
418         struct ac97_codec *ac97_codec[NR_AC97];
419         struct i810_state *states[NR_HW_CH];
420         struct i810_channel *channel;   /* 1:1 to states[] but diff. lifetime */
421         dma_addr_t chandma;
422
423         u16 ac97_features;
424         u16 ac97_status;
425         u16 channels;
426         
427         /* hardware resources */
428         unsigned long ac97base;
429         unsigned long iobase;
430         u32 irq;
431
432         unsigned long ac97base_mmio_phys;
433         unsigned long iobase_mmio_phys;
434         u_int8_t *ac97base_mmio;
435         u_int8_t *iobase_mmio;
436
437         int           use_mmio;
438         
439         /* Function support */
440         struct i810_channel *(*alloc_pcm_channel)(struct i810_card *);
441         struct i810_channel *(*alloc_rec_pcm_channel)(struct i810_card *);
442         struct i810_channel *(*alloc_rec_mic_channel)(struct i810_card *);
443         void (*free_pcm_channel)(struct i810_card *, int chan);
444
445         /* We have a *very* long init time possibly, so use this to block */
446         /* attempts to open our devices before we are ready (stops oops'es) */
447         int initializing;
448 };
449
450 /* extract register offset from codec struct */
451 #define IO_REG_OFF(codec) (((struct i810_card *) codec->private_data)->ac97_id_map[codec->id])
452
453 #define I810_IOREAD(size, type, card, off)                              \
454 ({                                                                      \
455         type val;                                                       \
456         if (card->use_mmio)                                             \
457                 val=read##size(card->iobase_mmio+off);                  \
458         else                                                            \
459                 val=in##size(card->iobase+off);                         \
460         val;                                                            \
461 })
462
463 #define I810_IOREADL(card, off)         I810_IOREAD(l, u32, card, off)
464 #define I810_IOREADW(card, off)         I810_IOREAD(w, u16, card, off)
465 #define I810_IOREADB(card, off)         I810_IOREAD(b, u8,  card, off)
466
467 #define I810_IOWRITE(size, val, card, off)                              \
468 ({                                                                      \
469         if (card->use_mmio)                                             \
470                 write##size(val, card->iobase_mmio+off);                \
471         else                                                            \
472                 out##size(val, card->iobase+off);                       \
473 })
474
475 #define I810_IOWRITEL(val, card, off)   I810_IOWRITE(l, val, card, off)
476 #define I810_IOWRITEW(val, card, off)   I810_IOWRITE(w, val, card, off)
477 #define I810_IOWRITEB(val, card, off)   I810_IOWRITE(b, val, card, off)
478
479 #define GET_CIV(card, port) MODULOP2(I810_IOREADB((card), (port) + OFF_CIV), SG_LEN)
480 #define GET_LVI(card, port) MODULOP2(I810_IOREADB((card), (port) + OFF_LVI), SG_LEN)
481
482 /* set LVI from CIV */
483 #define CIV_TO_LVI(card, port, off) \
484         I810_IOWRITEB(MODULOP2(GET_CIV((card), (port)) + (off), SG_LEN), (card), (port) + OFF_LVI)
485
486 static struct i810_card *devs = NULL;
487
488 static int i810_open_mixdev(struct inode *inode, struct file *file);
489 static int i810_ioctl_mixdev(struct inode *inode, struct file *file,
490                              unsigned int cmd, unsigned long arg);
491 static u16 i810_ac97_get(struct ac97_codec *dev, u8 reg);
492 static void i810_ac97_set(struct ac97_codec *dev, u8 reg, u16 data);
493 static u16 i810_ac97_get_mmio(struct ac97_codec *dev, u8 reg);
494 static void i810_ac97_set_mmio(struct ac97_codec *dev, u8 reg, u16 data);
495 static u16 i810_ac97_get_io(struct ac97_codec *dev, u8 reg);
496 static void i810_ac97_set_io(struct ac97_codec *dev, u8 reg, u16 data);
497
498 static struct i810_channel *i810_alloc_pcm_channel(struct i810_card *card)
499 {
500         if(card->channel[1].used==1)
501                 return NULL;
502         card->channel[1].used=1;
503         return &card->channel[1];
504 }
505
506 static struct i810_channel *i810_alloc_rec_pcm_channel(struct i810_card *card)
507 {
508         if(card->channel[0].used==1)
509                 return NULL;
510         card->channel[0].used=1;
511         return &card->channel[0];
512 }
513
514 static struct i810_channel *i810_alloc_rec_mic_channel(struct i810_card *card)
515 {
516         if(card->channel[2].used==1)
517                 return NULL;
518         card->channel[2].used=1;
519         return &card->channel[2];
520 }
521
522 static void i810_free_pcm_channel(struct i810_card *card, int channel)
523 {
524         card->channel[channel].used=0;
525 }
526
527 static int i810_valid_spdif_rate ( struct ac97_codec *codec, int rate )
528 {
529         unsigned long id = 0L;
530
531         id = (i810_ac97_get(codec, AC97_VENDOR_ID1) << 16);
532         id |= i810_ac97_get(codec, AC97_VENDOR_ID2) & 0xffff;
533 #ifdef DEBUG
534         printk ( "i810_audio: codec = %s, codec_id = 0x%08lx\n", codec->name, id);
535 #endif
536         switch ( id ) {
537                 case 0x41445361: /* AD1886 */
538                         if (rate == 48000) {
539                                 return 1;
540                         }
541                         break;
542                 default: /* all other codecs, until we know otherwiae */
543                         if (rate == 48000 || rate == 44100 || rate == 32000) {
544                                 return 1;
545                         }
546                         break;
547         }
548         return (0);
549 }
550
551 /* i810_set_spdif_output
552  * 
553  *  Configure the S/PDIF output transmitter. When we turn on
554  *  S/PDIF, we turn off the analog output. This may not be
555  *  the right thing to do.
556  *
557  *  Assumptions:
558  *     The DSP sample rate must already be set to a supported
559  *     S/PDIF rate (32kHz, 44.1kHz, or 48kHz) or we abort.
560  */
561 static int i810_set_spdif_output(struct i810_state *state, int slots, int rate)
562 {
563         int     vol;
564         int     aud_reg;
565         int     r = 0;
566         struct ac97_codec *codec = state->card->ac97_codec[0];
567
568         if(!codec->codec_ops->digital) {
569                 state->card->ac97_status &= ~SPDIF_ON;
570         } else {
571                 if ( slots == -1 ) { /* Turn off S/PDIF */
572                         codec->codec_ops->digital(codec, 0, 0, 0);
573                         /* If the volume wasn't muted before we turned on S/PDIF, unmute it */
574                         if ( !(state->card->ac97_status & VOL_MUTED) ) {
575                                 aud_reg = i810_ac97_get(codec, AC97_MASTER_VOL_STEREO);
576                                 i810_ac97_set(codec, AC97_MASTER_VOL_STEREO, (aud_reg & ~VOL_MUTED));
577                         }
578                         state->card->ac97_status &= ~(VOL_MUTED | SPDIF_ON);
579                         return 0;
580                 }
581
582                 vol = i810_ac97_get(codec, AC97_MASTER_VOL_STEREO);
583                 state->card->ac97_status = vol & VOL_MUTED;
584                 
585                 r = codec->codec_ops->digital(codec, slots, rate, 0);
586
587                 if(r)
588                         state->card->ac97_status |= SPDIF_ON;
589                 else
590                         state->card->ac97_status &= ~SPDIF_ON;
591
592                 /* Mute the analog output */
593                 /* Should this only mute the PCM volume??? */
594                 i810_ac97_set(codec, AC97_MASTER_VOL_STEREO, (vol | VOL_MUTED));
595         }
596         return r;
597 }
598
599 /* i810_set_dac_channels
600  *
601  *  Configure the codec's multi-channel DACs
602  *
603  *  The logic is backwards. Setting the bit to 1 turns off the DAC. 
604  *
605  *  What about the ICH? We currently configure it using the
606  *  SNDCTL_DSP_CHANNELS ioctl.  If we're turnning on the DAC, 
607  *  does that imply that we want the ICH set to support
608  *  these channels?
609  *  
610  *  TODO:
611  *    vailidate that the codec really supports these DACs
612  *    before turning them on. 
613  */
614 static void i810_set_dac_channels(struct i810_state *state, int channel)
615 {
616         int     aud_reg;
617         struct ac97_codec *codec = state->card->ac97_codec[0];
618         
619         /* No codec, no setup */
620         
621         if(codec == NULL)
622                 return;
623
624         aud_reg = i810_ac97_get(codec, AC97_EXTENDED_STATUS);
625         aud_reg |= AC97_EA_PRI | AC97_EA_PRJ | AC97_EA_PRK;
626         state->card->ac97_status &= ~(SURR_ON | CENTER_LFE_ON);
627
628         switch ( channel ) {
629                 case 2: /* always enabled */
630                         break;
631                 case 4:
632                         aud_reg &= ~AC97_EA_PRJ;
633                         state->card->ac97_status |= SURR_ON;
634                         break;
635                 case 6:
636                         aud_reg &= ~(AC97_EA_PRJ | AC97_EA_PRI | AC97_EA_PRK);
637                         state->card->ac97_status |= SURR_ON | CENTER_LFE_ON;
638                         break;
639                 default:
640                         break;
641         }
642         i810_ac97_set(codec, AC97_EXTENDED_STATUS, aud_reg);
643
644 }
645
646
647 /* set playback sample rate */
648 static unsigned int i810_set_dac_rate(struct i810_state * state, unsigned int rate)
649 {       
650         struct dmabuf *dmabuf = &state->dmabuf;
651         u32 new_rate;
652         struct ac97_codec *codec=state->card->ac97_codec[0];
653         
654         if(!(state->card->ac97_features&0x0001))
655         {
656                 dmabuf->rate = clocking;
657 #ifdef DEBUG
658                 printk("Asked for %d Hz, but ac97_features says we only do %dHz.  Sorry!\n",
659                        rate,clocking);
660 #endif                 
661                 return clocking;
662         }
663                         
664         if (rate > 48000)
665                 rate = 48000;
666         if (rate < 8000)
667                 rate = 8000;
668         dmabuf->rate = rate;
669                 
670         /*
671          *      Adjust for misclocked crap
672          */
673         rate = ( rate * clocking)/48000;
674         if(strict_clocking && rate < 8000) {
675                 rate = 8000;
676                 dmabuf->rate = (rate * 48000)/clocking;
677         }
678
679         new_rate=ac97_set_dac_rate(codec, rate);
680         if(new_rate != rate) {
681                 dmabuf->rate = (new_rate * 48000)/clocking;
682         }
683 #ifdef DEBUG
684         printk("i810_audio: called i810_set_dac_rate : asked for %d, got %d\n", rate, dmabuf->rate);
685 #endif
686         rate = new_rate;
687         return dmabuf->rate;
688 }
689
690 /* set recording sample rate */
691 static unsigned int i810_set_adc_rate(struct i810_state * state, unsigned int rate)
692 {
693         struct dmabuf *dmabuf = &state->dmabuf;
694         u32 new_rate;
695         struct ac97_codec *codec=state->card->ac97_codec[0];
696         
697         if(!(state->card->ac97_features&0x0001))
698         {
699                 dmabuf->rate = clocking;
700                 return clocking;
701         }
702                         
703         if (rate > 48000)
704                 rate = 48000;
705         if (rate < 8000)
706                 rate = 8000;
707         dmabuf->rate = rate;
708
709         /*
710          *      Adjust for misclocked crap
711          */
712          
713         rate = ( rate * clocking)/48000;
714         if(strict_clocking && rate < 8000) {
715                 rate = 8000;
716                 dmabuf->rate = (rate * 48000)/clocking;
717         }
718
719         new_rate = ac97_set_adc_rate(codec, rate);
720         
721         if(new_rate != rate) {
722                 dmabuf->rate = (new_rate * 48000)/clocking;
723                 rate = new_rate;
724         }
725 #ifdef DEBUG
726         printk("i810_audio: called i810_set_adc_rate : rate = %d/%d\n", dmabuf->rate, rate);
727 #endif
728         return dmabuf->rate;
729 }
730
731 /* get current playback/recording dma buffer pointer (byte offset from LBA),
732    called with spinlock held! */
733    
734 static inline unsigned i810_get_dma_addr(struct i810_state *state, int rec)
735 {
736         struct dmabuf *dmabuf = &state->dmabuf;
737         unsigned int civ, offset, port, port_picb, bytes = 2;
738         
739         if (!dmabuf->enable)
740                 return 0;
741
742         if (rec)
743                 port = dmabuf->read_channel->port;
744         else
745                 port = dmabuf->write_channel->port;
746
747         if(state->card->pci_id == PCI_DEVICE_ID_SI_7012) {
748                 port_picb = port + OFF_SR;
749                 bytes = 1;
750         } else
751                 port_picb = port + OFF_PICB;
752
753         do {
754                 civ = GET_CIV(state->card, port);
755                 offset = I810_IOREADW(state->card, port_picb);
756                 /* Must have a delay here! */ 
757                 if(offset == 0)
758                         udelay(1);
759                 /* Reread both registers and make sure that that total
760                  * offset from the first reading to the second is 0.
761                  * There is an issue with SiS hardware where it will count
762                  * picb down to 0, then update civ to the next value,
763                  * then set the new picb to fragsize bytes.  We can catch
764                  * it between the civ update and the picb update, making
765                  * it look as though we are 1 fragsize ahead of where we
766                  * are.  The next to we get the address though, it will
767                  * be back in the right place, and we will suddenly think
768                  * we just went forward dmasize - fragsize bytes, causing
769                  * totally stupid *huge* dma overrun messages.  We are
770                  * assuming that the 1us delay is more than long enough
771                  * that we won't have to worry about the chip still being
772                  * out of sync with reality ;-)
773                  */
774         } while (civ != GET_CIV(state->card, port) || offset != I810_IOREADW(state->card, port_picb));
775                  
776         return (((civ + 1) * dmabuf->fragsize - (bytes * offset))
777                 % dmabuf->dmasize);
778 }
779
780 /* Stop recording (lock held) */
781 static inline void __stop_adc(struct i810_state *state)
782 {
783         struct dmabuf *dmabuf = &state->dmabuf;
784         struct i810_card *card = state->card;
785
786         dmabuf->enable &= ~ADC_RUNNING;
787         I810_IOWRITEB(0, card, PI_CR);
788         // wait for the card to acknowledge shutdown
789         while( I810_IOREADB(card, PI_CR) != 0 ) ;
790         // now clear any latent interrupt bits (like the halt bit)
791         if(card->pci_id == PCI_DEVICE_ID_SI_7012)
792                 I810_IOWRITEB( I810_IOREADB(card, PI_PICB), card, PI_PICB );
793         else
794                 I810_IOWRITEB( I810_IOREADB(card, PI_SR), card, PI_SR );
795         I810_IOWRITEL( I810_IOREADL(card, GLOB_STA) & INT_PI, card, GLOB_STA);
796 }
797
798 static void stop_adc(struct i810_state *state)
799 {
800         struct i810_card *card = state->card;
801         unsigned long flags;
802
803         spin_lock_irqsave(&card->lock, flags);
804         __stop_adc(state);
805         spin_unlock_irqrestore(&card->lock, flags);
806 }
807
808 static inline void __start_adc(struct i810_state *state)
809 {
810         struct dmabuf *dmabuf = &state->dmabuf;
811
812         if (dmabuf->count < dmabuf->dmasize && dmabuf->ready && !dmabuf->enable &&
813             (dmabuf->trigger & PCM_ENABLE_INPUT)) {
814                 dmabuf->enable |= ADC_RUNNING;
815                 // Interrupt enable, LVI enable, DMA enable
816                 I810_IOWRITEB(0x10 | 0x04 | 0x01, state->card, PI_CR);
817         }
818 }
819
820 static void start_adc(struct i810_state *state)
821 {
822         struct i810_card *card = state->card;
823         unsigned long flags;
824
825         spin_lock_irqsave(&card->lock, flags);
826         __start_adc(state);
827         spin_unlock_irqrestore(&card->lock, flags);
828 }
829
830 /* stop playback (lock held) */
831 static inline void __stop_dac(struct i810_state *state)
832 {
833         struct dmabuf *dmabuf = &state->dmabuf;
834         struct i810_card *card = state->card;
835
836         dmabuf->enable &= ~DAC_RUNNING;
837         I810_IOWRITEB(0, card, PO_CR);
838         // wait for the card to acknowledge shutdown
839         while( I810_IOREADB(card, PO_CR) != 0 ) ;
840         // now clear any latent interrupt bits (like the halt bit)
841         if(card->pci_id == PCI_DEVICE_ID_SI_7012)
842                 I810_IOWRITEB( I810_IOREADB(card, PO_PICB), card, PO_PICB );
843         else
844                 I810_IOWRITEB( I810_IOREADB(card, PO_SR), card, PO_SR );
845         I810_IOWRITEL( I810_IOREADL(card, GLOB_STA) & INT_PO, card, GLOB_STA);
846 }
847
848 static void stop_dac(struct i810_state *state)
849 {
850         struct i810_card *card = state->card;
851         unsigned long flags;
852
853         spin_lock_irqsave(&card->lock, flags);
854         __stop_dac(state);
855         spin_unlock_irqrestore(&card->lock, flags);
856 }       
857
858 static inline void __start_dac(struct i810_state *state)
859 {
860         struct dmabuf *dmabuf = &state->dmabuf;
861
862         if (dmabuf->count > 0 && dmabuf->ready && !dmabuf->enable &&
863             (dmabuf->trigger & PCM_ENABLE_OUTPUT)) {
864                 dmabuf->enable |= DAC_RUNNING;
865                 // Interrupt enable, LVI enable, DMA enable
866                 I810_IOWRITEB(0x10 | 0x04 | 0x01, state->card, PO_CR);
867         }
868 }
869 static void start_dac(struct i810_state *state)
870 {
871         struct i810_card *card = state->card;
872         unsigned long flags;
873
874         spin_lock_irqsave(&card->lock, flags);
875         __start_dac(state);
876         spin_unlock_irqrestore(&card->lock, flags);
877 }
878
879 #define DMABUF_DEFAULTORDER (16-PAGE_SHIFT)
880 #define DMABUF_MINORDER 1
881
882 /* allocate DMA buffer, playback and recording buffer should be allocated separately */
883 static int alloc_dmabuf(struct i810_state *state)
884 {
885         struct dmabuf *dmabuf = &state->dmabuf;
886         void *rawbuf= NULL;
887         int order, size;
888         struct page *page, *pend;
889
890         /* If we don't have any oss frag params, then use our default ones */
891         if(dmabuf->ossmaxfrags == 0)
892                 dmabuf->ossmaxfrags = 4;
893         if(dmabuf->ossfragsize == 0)
894                 dmabuf->ossfragsize = (PAGE_SIZE<<DMABUF_DEFAULTORDER)/dmabuf->ossmaxfrags;
895         size = dmabuf->ossfragsize * dmabuf->ossmaxfrags;
896
897         if(dmabuf->rawbuf && (PAGE_SIZE << dmabuf->buforder) == size)
898                 return 0;
899         /* alloc enough to satisfy the oss params */
900         for (order = DMABUF_DEFAULTORDER; order >= DMABUF_MINORDER; order--) {
901                 if ( (PAGE_SIZE<<order) > size )
902                         continue;
903                 if ((rawbuf = pci_alloc_consistent(state->card->pci_dev,
904                                                    PAGE_SIZE << order,
905                                                    &dmabuf->dma_handle)))
906                         break;
907         }
908         if (!rawbuf)
909                 return -ENOMEM;
910
911
912 #ifdef DEBUG
913         printk("i810_audio: allocated %ld (order = %d) bytes at %p\n",
914                PAGE_SIZE << order, order, rawbuf);
915 #endif
916
917         dmabuf->ready  = dmabuf->mapped = 0;
918         dmabuf->rawbuf = rawbuf;
919         dmabuf->buforder = order;
920         
921         /* now mark the pages as reserved; otherwise remap_page_range doesn't do what we want */
922         pend = virt_to_page(rawbuf + (PAGE_SIZE << order) - 1);
923         for (page = virt_to_page(rawbuf); page <= pend; page++)
924                 SetPageReserved(page);
925
926         return 0;
927 }
928
929 /* free DMA buffer */
930 static void dealloc_dmabuf(struct i810_state *state)
931 {
932         struct dmabuf *dmabuf = &state->dmabuf;
933         struct page *page, *pend;
934
935         if (dmabuf->rawbuf) {
936                 /* undo marking the pages as reserved */
937                 pend = virt_to_page(dmabuf->rawbuf + (PAGE_SIZE << dmabuf->buforder) - 1);
938                 for (page = virt_to_page(dmabuf->rawbuf); page <= pend; page++)
939                         ClearPageReserved(page);
940                 pci_free_consistent(state->card->pci_dev, PAGE_SIZE << dmabuf->buforder,
941                                     dmabuf->rawbuf, dmabuf->dma_handle);
942         }
943         dmabuf->rawbuf = NULL;
944         dmabuf->mapped = dmabuf->ready = 0;
945 }
946
947 static int prog_dmabuf(struct i810_state *state, unsigned rec)
948 {
949         struct dmabuf *dmabuf = &state->dmabuf;
950         struct i810_channel *c;
951         struct sg_item *sg;
952         unsigned long flags;
953         int ret;
954         unsigned fragint;
955         int i;
956
957         spin_lock_irqsave(&state->card->lock, flags);
958         if(dmabuf->enable & DAC_RUNNING)
959                 __stop_dac(state);
960         if(dmabuf->enable & ADC_RUNNING)
961                 __stop_adc(state);
962         dmabuf->total_bytes = 0;
963         dmabuf->count = dmabuf->error = 0;
964         dmabuf->swptr = dmabuf->hwptr = 0;
965         spin_unlock_irqrestore(&state->card->lock, flags);
966
967         /* allocate DMA buffer, let alloc_dmabuf determine if we are already
968          * allocated well enough or if we should replace the current buffer
969          * (assuming one is already allocated, if it isn't, then allocate it).
970          */
971         if ((ret = alloc_dmabuf(state)))
972                 return ret;
973
974         /* FIXME: figure out all this OSS fragment stuff */
975         /* I did, it now does what it should according to the OSS API.  DL */
976         /* We may not have realloced our dmabuf, but the fragment size to
977          * fragment number ratio may have changed, so go ahead and reprogram
978          * things
979          */
980         dmabuf->dmasize = PAGE_SIZE << dmabuf->buforder;
981         dmabuf->numfrag = SG_LEN;
982         dmabuf->fragsize = dmabuf->dmasize/dmabuf->numfrag;
983         dmabuf->fragsamples = dmabuf->fragsize >> 1;
984         dmabuf->fragshift = ffs(dmabuf->fragsize) - 1;
985         dmabuf->userfragsize = dmabuf->ossfragsize;
986         dmabuf->userfrags = dmabuf->dmasize/dmabuf->ossfragsize;
987
988         memset(dmabuf->rawbuf, 0, dmabuf->dmasize);
989
990         if(dmabuf->ossmaxfrags == 4) {
991                 fragint = 8;
992         } else if (dmabuf->ossmaxfrags == 8) {
993                 fragint = 4;
994         } else if (dmabuf->ossmaxfrags == 16) {
995                 fragint = 2;
996         } else {
997                 fragint = 1;
998         }
999         /*
1000          *      Now set up the ring 
1001          */
1002         if(dmabuf->read_channel)
1003                 c = dmabuf->read_channel;
1004         else
1005                 c = dmabuf->write_channel;
1006         while(c != NULL) {
1007                 sg=&c->sg[0];
1008                 /*
1009                  *      Load up 32 sg entries and take an interrupt at half
1010                  *      way (we might want more interrupts later..) 
1011                  */
1012           
1013                 for(i=0;i<dmabuf->numfrag;i++)
1014                 {
1015                         sg->busaddr=(u32)dmabuf->dma_handle+dmabuf->fragsize*i;
1016                         // the card will always be doing 16bit stereo
1017                         sg->control=dmabuf->fragsamples;
1018                         if(state->card->pci_id == PCI_DEVICE_ID_SI_7012)
1019                                 sg->control <<= 1;
1020                         sg->control|=CON_BUFPAD;
1021                         // set us up to get IOC interrupts as often as needed to
1022                         // satisfy numfrag requirements, no more
1023                         if( ((i+1) % fragint) == 0) {
1024                                 sg->control|=CON_IOC;
1025                         }
1026                         sg++;
1027                 }
1028                 spin_lock_irqsave(&state->card->lock, flags);
1029                 I810_IOWRITEB(2, state->card, c->port+OFF_CR);   /* reset DMA machine */
1030                 while( I810_IOREADB(state->card, c->port+OFF_CR) & 0x02 ) ;
1031                 I810_IOWRITEL((u32)state->card->chandma +
1032                     c->num*sizeof(struct i810_channel),
1033                     state->card, c->port+OFF_BDBAR);
1034                 CIV_TO_LVI(state->card, c->port, 0);
1035
1036                 spin_unlock_irqrestore(&state->card->lock, flags);
1037
1038                 if(c != dmabuf->write_channel)
1039                         c = dmabuf->write_channel;
1040                 else
1041                         c = NULL;
1042         }
1043         
1044         /* set the ready flag for the dma buffer */
1045         dmabuf->ready = 1;
1046
1047 #ifdef DEBUG
1048         printk("i810_audio: prog_dmabuf, sample rate = %d, format = %d,\n\tnumfrag = %d, "
1049                "fragsize = %d dmasize = %d\n",
1050                dmabuf->rate, dmabuf->fmt, dmabuf->numfrag,
1051                dmabuf->fragsize, dmabuf->dmasize);
1052 #endif
1053
1054         return 0;
1055 }
1056
1057 static void __i810_update_lvi(struct i810_state *state, int rec)
1058 {
1059         struct dmabuf *dmabuf = &state->dmabuf;
1060         int x, port;
1061         int trigger;
1062         int count, fragsize;
1063         void (*start)(struct i810_state *);
1064
1065         count = dmabuf->count;
1066         if (rec) {
1067                 port = dmabuf->read_channel->port;
1068                 trigger = PCM_ENABLE_INPUT;
1069                 start = __start_adc;
1070                 count = dmabuf->dmasize - count;
1071         } else {
1072                 port = dmabuf->write_channel->port;
1073                 trigger = PCM_ENABLE_OUTPUT;
1074                 start = __start_dac;
1075         }
1076
1077         /* Do not process partial fragments. */
1078         fragsize = dmabuf->fragsize;
1079         if (count < fragsize)
1080                 return;
1081
1082         if (!dmabuf->enable && dmabuf->ready) {
1083                 if (!(dmabuf->trigger & trigger))
1084                         return;
1085
1086                 start(state);
1087                 while (!(I810_IOREADB(state->card, port + OFF_CR) & ((1<<4) | (1<<2))))
1088                         ;
1089         }
1090
1091         /* MASKP2(swptr, fragsize) - 1 is the tail of our transfer */
1092         x = MODULOP2(MASKP2(dmabuf->swptr, fragsize) - 1, dmabuf->dmasize);
1093         x >>= dmabuf->fragshift;
1094         I810_IOWRITEB(x, state->card, port + OFF_LVI);
1095 }
1096
1097 static void i810_update_lvi(struct i810_state *state, int rec)
1098 {
1099         struct dmabuf *dmabuf = &state->dmabuf;
1100         unsigned long flags;
1101
1102         if(!dmabuf->ready)
1103                 return;
1104         spin_lock_irqsave(&state->card->lock, flags);
1105         __i810_update_lvi(state, rec);
1106         spin_unlock_irqrestore(&state->card->lock, flags);
1107 }
1108
1109 /* update buffer manangement pointers, especially, dmabuf->count and dmabuf->hwptr */
1110 static void i810_update_ptr(struct i810_state *state)
1111 {
1112         struct dmabuf *dmabuf = &state->dmabuf;
1113         unsigned hwptr;
1114         unsigned fragmask, dmamask;
1115         int diff;
1116
1117         fragmask = MASKP2(~0, dmabuf->fragsize);
1118         dmamask = MODULOP2(~0, dmabuf->dmasize);
1119
1120         /* error handling and process wake up for ADC */
1121         if (dmabuf->enable == ADC_RUNNING) {
1122                 /* update hardware pointer */
1123                 hwptr = i810_get_dma_addr(state, 1) & fragmask;
1124                 diff = (hwptr - dmabuf->hwptr) & dmamask;
1125 #if defined(DEBUG_INTERRUPTS) || defined(DEBUG_MMAP)
1126                 printk("ADC HWP %d,%d,%d\n", hwptr, dmabuf->hwptr, diff);
1127 #endif
1128                 dmabuf->hwptr = hwptr;
1129                 dmabuf->total_bytes += diff;
1130                 dmabuf->count += diff;
1131                 if (dmabuf->count > dmabuf->dmasize) {
1132                         /* buffer underrun or buffer overrun */
1133                         /* this is normal for the end of a read */
1134                         /* only give an error if we went past the */
1135                         /* last valid sg entry */
1136                         if (GET_CIV(state->card, PI_BASE) !=
1137                             GET_LVI(state->card, PI_BASE)) {
1138                                 printk(KERN_WARNING "i810_audio: DMA overrun on read\n");
1139                                 dmabuf->error++;
1140                         }
1141                 }
1142                 if (diff)
1143                         wake_up(&dmabuf->wait);
1144         }
1145         /* error handling and process wake up for DAC */
1146         if (dmabuf->enable == DAC_RUNNING) {
1147                 /* update hardware pointer */
1148                 hwptr = i810_get_dma_addr(state, 0) & fragmask;
1149                 diff = (hwptr - dmabuf->hwptr) & dmamask;
1150 #if defined(DEBUG_INTERRUPTS) || defined(DEBUG_MMAP)
1151                 printk("DAC HWP %d,%d,%d\n", hwptr, dmabuf->hwptr, diff);
1152 #endif
1153                 dmabuf->hwptr = hwptr;
1154                 dmabuf->total_bytes += diff;
1155                 dmabuf->count -= diff;
1156                 if (dmabuf->count < 0) {
1157                         /* buffer underrun or buffer overrun */
1158                         /* this is normal for the end of a write */
1159                         /* only give an error if we went past the */
1160                         /* last valid sg entry */
1161                         if (GET_CIV(state->card, PO_BASE) !=
1162                             GET_LVI(state->card, PO_BASE)) {
1163                                 printk(KERN_WARNING "i810_audio: DMA overrun on write\n");
1164                                 printk("i810_audio: CIV %d, LVI %d, hwptr %x, "
1165                                         "count %d\n",
1166                                         GET_CIV(state->card, PO_BASE),
1167                                         GET_LVI(state->card, PO_BASE),
1168                                         dmabuf->hwptr, dmabuf->count);
1169                                 dmabuf->error++;
1170                         }
1171                 }
1172                 if (diff)
1173                         wake_up(&dmabuf->wait);
1174         }
1175 }
1176
1177 static inline int i810_get_free_write_space(struct i810_state *state)
1178 {
1179         struct dmabuf *dmabuf = &state->dmabuf;
1180         int free;
1181
1182         i810_update_ptr(state);
1183         // catch underruns during playback
1184         if (dmabuf->count < 0) {
1185                 dmabuf->count = 0;
1186                 dmabuf->swptr = dmabuf->hwptr;
1187         }
1188         free = dmabuf->dmasize - dmabuf->count;
1189         if(free < 0)
1190                 return(0);
1191         return(free);
1192 }
1193
1194 static inline int i810_get_available_read_data(struct i810_state *state)
1195 {
1196         struct dmabuf *dmabuf = &state->dmabuf;
1197         int avail;
1198
1199         i810_update_ptr(state);
1200         // catch overruns during record
1201         if (dmabuf->count > dmabuf->dmasize) {
1202                 dmabuf->count = dmabuf->dmasize;
1203                 dmabuf->swptr = dmabuf->hwptr;
1204         }
1205         avail = dmabuf->count;
1206         if(avail < 0)
1207                 return(0);
1208         return(avail);
1209 }
1210
1211 static inline void fill_partial_frag(struct dmabuf *dmabuf)
1212 {
1213         unsigned fragsize;
1214         unsigned swptr, len;
1215
1216         fragsize = dmabuf->fragsize;
1217         swptr = dmabuf->swptr;
1218         len = fragsize - MODULOP2(dmabuf->swptr, fragsize);
1219         if (len == fragsize)
1220                 return;
1221
1222         memset(dmabuf->rawbuf + swptr, '\0', len);
1223         dmabuf->swptr = MODULOP2(swptr + len, dmabuf->dmasize);
1224         dmabuf->count += len;
1225 }
1226
1227 static int drain_dac(struct i810_state *state, int signals_allowed)
1228 {
1229         DECLARE_WAITQUEUE(wait, current);
1230         struct dmabuf *dmabuf = &state->dmabuf;
1231         unsigned long flags;
1232         unsigned long tmo;
1233         int count;
1234
1235         if (!dmabuf->ready)
1236                 return 0;
1237         if(dmabuf->mapped) {
1238                 stop_dac(state);
1239                 return 0;
1240         }
1241
1242         spin_lock_irqsave(&state->card->lock, flags);
1243
1244         fill_partial_frag(dmabuf);
1245
1246         /* 
1247          * This will make sure that our LVI is correct, that our
1248          * pointer is updated, and that the DAC is running.  We
1249          * have to force the setting of dmabuf->trigger to avoid
1250          * any possible deadlocks.
1251          */
1252         dmabuf->trigger = PCM_ENABLE_OUTPUT;
1253         __i810_update_lvi(state, 0);
1254
1255         spin_unlock_irqrestore(&state->card->lock, flags);
1256
1257         add_wait_queue(&dmabuf->wait, &wait);
1258         for (;;) {
1259
1260                 spin_lock_irqsave(&state->card->lock, flags);
1261                 i810_update_ptr(state);
1262                 count = dmabuf->count;
1263
1264                 /* It seems that we have to set the current state to
1265                  * TASK_INTERRUPTIBLE every time to make the process
1266                  * really go to sleep.  This also has to be *after* the
1267                  * update_ptr() call because update_ptr is likely to
1268                  * do a wake_up() which will unset this before we ever
1269                  * try to sleep, resuling in a tight loop in this code
1270                  * instead of actually sleeping and waiting for an
1271                  * interrupt to wake us up!
1272                  */
1273                 __set_current_state(signals_allowed ?
1274                                     TASK_INTERRUPTIBLE : TASK_UNINTERRUPTIBLE);
1275                 spin_unlock_irqrestore(&state->card->lock, flags);
1276
1277                 if (count <= 0)
1278                         break;
1279
1280                 if (signal_pending(current) && signals_allowed) {
1281                         break;
1282                 }
1283
1284                 /*
1285                  * set the timeout to significantly longer than it *should*
1286                  * take for the DAC to drain the DMA buffer
1287                  */
1288                 tmo = (count * HZ) / (dmabuf->rate);
1289                 if (!schedule_timeout(tmo >= 2 ? tmo : 2)){
1290                         printk(KERN_ERR "i810_audio: drain_dac, dma timeout?\n");
1291                         count = 0;
1292                         break;
1293                 }
1294         }
1295         set_current_state(TASK_RUNNING);
1296         remove_wait_queue(&dmabuf->wait, &wait);
1297         if(count > 0 && signal_pending(current) && signals_allowed)
1298                 return -ERESTARTSYS;
1299         stop_dac(state);
1300         return 0;
1301 }
1302
1303 static void i810_channel_interrupt(struct i810_card *card)
1304 {
1305         int i, count;
1306         
1307 #ifdef DEBUG_INTERRUPTS
1308         printk("CHANNEL ");
1309 #endif
1310         for(i=0;i<NR_HW_CH;i++)
1311         {
1312                 struct i810_state *state = card->states[i];
1313                 struct i810_channel *c;
1314                 struct dmabuf *dmabuf;
1315                 unsigned long port;
1316                 u16 status;
1317                 
1318                 if(!state)
1319                         continue;
1320                 if(!state->dmabuf.ready)
1321                         continue;
1322                 dmabuf = &state->dmabuf;
1323                 if(dmabuf->enable & DAC_RUNNING) {
1324                         c=dmabuf->write_channel;
1325                 } else if(dmabuf->enable & ADC_RUNNING) {
1326                         c=dmabuf->read_channel;
1327                 } else  /* This can occur going from R/W to close */
1328                         continue;
1329                 
1330                 port = c->port;
1331
1332                 if(card->pci_id == PCI_DEVICE_ID_SI_7012)
1333                         status = I810_IOREADW(card, port + OFF_PICB);
1334                 else
1335                         status = I810_IOREADW(card, port + OFF_SR);
1336
1337 #ifdef DEBUG_INTERRUPTS
1338                 printk("NUM %d PORT %X IRQ ( ST%d ", c->num, c->port, status);
1339 #endif
1340                 if(status & DMA_INT_COMPLETE)
1341                 {
1342                         /* only wake_up() waiters if this interrupt signals
1343                          * us being beyond a userfragsize of data open or
1344                          * available, and i810_update_ptr() does that for
1345                          * us
1346                          */
1347                         i810_update_ptr(state);
1348 #ifdef DEBUG_INTERRUPTS
1349                         printk("COMP %d ", dmabuf->hwptr /
1350                                         dmabuf->fragsize);
1351 #endif
1352                 }
1353                 if(status & (DMA_INT_LVI | DMA_INT_DCH))
1354                 {
1355                         /* wake_up() unconditionally on LVI and DCH */
1356                         i810_update_ptr(state);
1357                         wake_up(&dmabuf->wait);
1358 #ifdef DEBUG_INTERRUPTS
1359                         if(status & DMA_INT_LVI)
1360                                 printk("LVI ");
1361                         if(status & DMA_INT_DCH)
1362                                 printk("DCH -");
1363 #endif
1364                         count = dmabuf->count;
1365                         if(dmabuf->enable & ADC_RUNNING)
1366                                 count = dmabuf->dmasize - count;
1367                         if (count >= (int)dmabuf->fragsize) {
1368                                 I810_IOWRITEB(I810_IOREADB(card, port+OFF_CR) | 1, card, port+OFF_CR);
1369 #ifdef DEBUG_INTERRUPTS
1370                                 printk(" CONTINUE ");
1371 #endif
1372                         } else {
1373                                 if (dmabuf->enable & DAC_RUNNING)
1374                                         __stop_dac(state);
1375                                 if (dmabuf->enable & ADC_RUNNING)
1376                                         __stop_adc(state);
1377                                 dmabuf->enable = 0;
1378 #ifdef DEBUG_INTERRUPTS
1379                                 printk(" STOP ");
1380 #endif
1381                         }
1382                 }
1383                 if(card->pci_id == PCI_DEVICE_ID_SI_7012)
1384                         I810_IOWRITEW(status & DMA_INT_MASK, card, port + OFF_PICB);
1385                 else
1386                         I810_IOWRITEW(status & DMA_INT_MASK, card, port + OFF_SR);
1387         }
1388 #ifdef DEBUG_INTERRUPTS
1389         printk(")\n");
1390 #endif
1391 }
1392
1393 static irqreturn_t i810_interrupt(int irq, void *dev_id, struct pt_regs *regs)
1394 {
1395         struct i810_card *card = (struct i810_card *)dev_id;
1396         u32 status;
1397
1398         spin_lock(&card->lock);
1399
1400         status = I810_IOREADL(card, GLOB_STA);
1401
1402         if(!(status & INT_MASK)) 
1403         {
1404                 spin_unlock(&card->lock);
1405                 return IRQ_NONE;  /* not for us */
1406         }
1407
1408         if(status & (INT_PO|INT_PI|INT_MC))
1409                 i810_channel_interrupt(card);
1410
1411         /* clear 'em */
1412         I810_IOWRITEL(status & INT_MASK, card, GLOB_STA);
1413         spin_unlock(&card->lock);
1414         return IRQ_HANDLED;
1415 }
1416
1417 /* in this loop, dmabuf.count signifies the amount of data that is
1418    waiting to be copied to the user's buffer.  It is filled by the dma
1419    machine and drained by this loop. */
1420
1421 static ssize_t i810_read(struct file *file, char __user *buffer, size_t count, loff_t *ppos)
1422 {
1423         struct i810_state *state = (struct i810_state *)file->private_data;
1424         struct i810_card *card=state ? state->card : NULL;
1425         struct dmabuf *dmabuf = &state->dmabuf;
1426         ssize_t ret;
1427         unsigned long flags;
1428         unsigned int swptr;
1429         int cnt;
1430         int pending;
1431         DECLARE_WAITQUEUE(waita, current);
1432
1433 #ifdef DEBUG2
1434         printk("i810_audio: i810_read called, count = %d\n", count);
1435 #endif
1436
1437         if (dmabuf->mapped)
1438                 return -ENXIO;
1439         if (dmabuf->enable & DAC_RUNNING)
1440                 return -ENODEV;
1441         if (!dmabuf->read_channel) {
1442                 dmabuf->ready = 0;
1443                 dmabuf->read_channel = card->alloc_rec_pcm_channel(card);
1444                 if (!dmabuf->read_channel) {
1445                         return -EBUSY;
1446                 }
1447         }
1448         if (!dmabuf->ready && (ret = prog_dmabuf(state, 1)))
1449                 return ret;
1450         if (!access_ok(VERIFY_WRITE, buffer, count))
1451                 return -EFAULT;
1452         ret = 0;
1453
1454         pending = 0;
1455
1456         add_wait_queue(&dmabuf->wait, &waita);
1457         while (count > 0) {
1458                 set_current_state(TASK_INTERRUPTIBLE);
1459                 spin_lock_irqsave(&card->lock, flags);
1460                 if (PM_SUSPENDED(card)) {
1461                         spin_unlock_irqrestore(&card->lock, flags);
1462                         schedule();
1463                         if (signal_pending(current)) {
1464                                 if (!ret) ret = -EAGAIN;
1465                                 break;
1466                         }
1467                         continue;
1468                 }
1469                 cnt = i810_get_available_read_data(state);
1470                 swptr = dmabuf->swptr;
1471                 // this is to make the copy_to_user simpler below
1472                 if(cnt > (dmabuf->dmasize - swptr))
1473                         cnt = dmabuf->dmasize - swptr;
1474                 spin_unlock_irqrestore(&card->lock, flags);
1475
1476                 if (cnt > count)
1477                         cnt = count;
1478                 if (cnt <= 0) {
1479                         unsigned long tmo;
1480                         /*
1481                          * Don't let us deadlock.  The ADC won't start if
1482                          * dmabuf->trigger isn't set.  A call to SETTRIGGER
1483                          * could have turned it off after we set it to on
1484                          * previously.
1485                          */
1486                         dmabuf->trigger = PCM_ENABLE_INPUT;
1487                         /*
1488                          * This does three things.  Updates LVI to be correct,
1489                          * makes sure the ADC is running, and updates the
1490                          * hwptr.
1491                          */
1492                         i810_update_lvi(state,1);
1493                         if (file->f_flags & O_NONBLOCK) {
1494                                 if (!ret) ret = -EAGAIN;
1495                                 goto done;
1496                         }
1497                         /* Set the timeout to how long it would take to fill
1498                          * two of our buffers.  If we haven't been woke up
1499                          * by then, then we know something is wrong.
1500                          */
1501                         tmo = (dmabuf->dmasize * HZ * 2) / (dmabuf->rate * 4);
1502                         /* There are two situations when sleep_on_timeout returns, one is when
1503                            the interrupt is serviced correctly and the process is waked up by
1504                            ISR ON TIME. Another is when timeout is expired, which means that
1505                            either interrupt is NOT serviced correctly (pending interrupt) or it
1506                            is TOO LATE for the process to be scheduled to run (scheduler latency)
1507                            which results in a (potential) buffer overrun. And worse, there is
1508                            NOTHING we can do to prevent it. */
1509                         if (!schedule_timeout(tmo >= 2 ? tmo : 2)) {
1510 #ifdef DEBUG
1511                                 printk(KERN_ERR "i810_audio: recording schedule timeout, "
1512                                        "dmasz %u fragsz %u count %i hwptr %u swptr %u\n",
1513                                        dmabuf->dmasize, dmabuf->fragsize, dmabuf->count,
1514                                        dmabuf->hwptr, dmabuf->swptr);
1515 #endif
1516                                 /* a buffer overrun, we delay the recovery until next time the
1517                                    while loop begin and we REALLY have space to record */
1518                         }
1519                         if (signal_pending(current)) {
1520                                 ret = ret ? ret : -ERESTARTSYS;
1521                                 goto done;
1522                         }
1523                         continue;
1524                 }
1525
1526                 if (copy_to_user(buffer, dmabuf->rawbuf + swptr, cnt)) {
1527                         if (!ret) ret = -EFAULT;
1528                         goto done;
1529                 }
1530
1531                 swptr = MODULOP2(swptr + cnt, dmabuf->dmasize);
1532
1533                 spin_lock_irqsave(&card->lock, flags);
1534
1535                 if (PM_SUSPENDED(card)) {
1536                         spin_unlock_irqrestore(&card->lock, flags);
1537                         continue;
1538                 }
1539                 dmabuf->swptr = swptr;
1540                 pending = dmabuf->count -= cnt;
1541                 spin_unlock_irqrestore(&card->lock, flags);
1542
1543                 count -= cnt;
1544                 buffer += cnt;
1545                 ret += cnt;
1546         }
1547  done:
1548         pending = dmabuf->dmasize - pending;
1549         if (dmabuf->enable || pending >= dmabuf->userfragsize)
1550                 i810_update_lvi(state, 1);
1551         set_current_state(TASK_RUNNING);
1552         remove_wait_queue(&dmabuf->wait, &waita);
1553
1554         return ret;
1555 }
1556
1557 /* in this loop, dmabuf.count signifies the amount of data that is waiting to be dma to
1558    the soundcard.  it is drained by the dma machine and filled by this loop. */
1559 static ssize_t i810_write(struct file *file, const char __user *buffer, size_t count, loff_t *ppos)
1560 {
1561         struct i810_state *state = (struct i810_state *)file->private_data;
1562         struct i810_card *card=state ? state->card : NULL;
1563         struct dmabuf *dmabuf = &state->dmabuf;
1564         ssize_t ret;
1565         unsigned long flags;
1566         unsigned int swptr = 0;
1567         int pending;
1568         int cnt;
1569         DECLARE_WAITQUEUE(waita, current);
1570
1571 #ifdef DEBUG2
1572         printk("i810_audio: i810_write called, count = %d\n", count);
1573 #endif
1574
1575         if (dmabuf->mapped)
1576                 return -ENXIO;
1577         if (dmabuf->enable & ADC_RUNNING)
1578                 return -ENODEV;
1579         if (!dmabuf->write_channel) {
1580                 dmabuf->ready = 0;
1581                 dmabuf->write_channel = card->alloc_pcm_channel(card);
1582                 if(!dmabuf->write_channel)
1583                         return -EBUSY;
1584         }
1585         if (!dmabuf->ready && (ret = prog_dmabuf(state, 0)))
1586                 return ret;
1587         if (!access_ok(VERIFY_READ, buffer, count))
1588                 return -EFAULT;
1589         ret = 0;
1590
1591         pending = 0;
1592
1593         add_wait_queue(&dmabuf->wait, &waita);
1594         while (count > 0) {
1595                 set_current_state(TASK_INTERRUPTIBLE);
1596                 spin_lock_irqsave(&state->card->lock, flags);
1597                 if (PM_SUSPENDED(card)) {
1598                         spin_unlock_irqrestore(&card->lock, flags);
1599                         schedule();
1600                         if (signal_pending(current)) {
1601                                 if (!ret) ret = -EAGAIN;
1602                                 break;
1603                         }
1604                         continue;
1605                 }
1606
1607                 cnt = i810_get_free_write_space(state);
1608                 swptr = dmabuf->swptr;
1609                 /* Bound the maximum size to how much we can copy to the
1610                  * dma buffer before we hit the end.  If we have more to
1611                  * copy then it will get done in a second pass of this
1612                  * loop starting from the beginning of the buffer.
1613                  */
1614                 if(cnt > (dmabuf->dmasize - swptr))
1615                         cnt = dmabuf->dmasize - swptr;
1616                 spin_unlock_irqrestore(&state->card->lock, flags);
1617
1618 #ifdef DEBUG2
1619                 printk(KERN_INFO "i810_audio: i810_write: %d bytes available space\n", cnt);
1620 #endif
1621                 if (cnt > count)
1622                         cnt = count;
1623                 if (cnt <= 0) {
1624                         unsigned long tmo;
1625                         // There is data waiting to be played
1626                         /*
1627                          * Force the trigger setting since we would
1628                          * deadlock with it set any other way
1629                          */
1630                         dmabuf->trigger = PCM_ENABLE_OUTPUT;
1631                         i810_update_lvi(state,0);
1632                         if (file->f_flags & O_NONBLOCK) {
1633                                 if (!ret) ret = -EAGAIN;
1634                                 goto ret;
1635                         }
1636                         /* Not strictly correct but works */
1637                         tmo = (dmabuf->dmasize * HZ * 2) / (dmabuf->rate * 4);
1638                         /* There are two situations when sleep_on_timeout returns, one is when
1639                            the interrupt is serviced correctly and the process is waked up by
1640                            ISR ON TIME. Another is when timeout is expired, which means that
1641                            either interrupt is NOT serviced correctly (pending interrupt) or it
1642                            is TOO LATE for the process to be scheduled to run (scheduler latency)
1643                            which results in a (potential) buffer underrun. And worse, there is
1644                            NOTHING we can do to prevent it. */
1645                         if (!schedule_timeout(tmo >= 2 ? tmo : 2)) {
1646 #ifdef DEBUG
1647                                 printk(KERN_ERR "i810_audio: playback schedule timeout, "
1648                                        "dmasz %u fragsz %u count %i hwptr %u swptr %u\n",
1649                                        dmabuf->dmasize, dmabuf->fragsize, dmabuf->count,
1650                                        dmabuf->hwptr, dmabuf->swptr);
1651 #endif
1652                                 /* a buffer underrun, we delay the recovery until next time the
1653                                    while loop begin and we REALLY have data to play */
1654                                 //return ret;
1655                         }
1656                         if (signal_pending(current)) {
1657                                 if (!ret) ret = -ERESTARTSYS;
1658                                 goto ret;
1659                         }
1660                         continue;
1661                 }
1662                 if (copy_from_user(dmabuf->rawbuf+swptr,buffer,cnt)) {
1663                         if (!ret) ret = -EFAULT;
1664                         goto ret;
1665                 }
1666
1667                 swptr = MODULOP2(swptr + cnt, dmabuf->dmasize);
1668
1669                 spin_lock_irqsave(&state->card->lock, flags);
1670                 if (PM_SUSPENDED(card)) {
1671                         spin_unlock_irqrestore(&card->lock, flags);
1672                         continue;
1673                 }
1674
1675                 dmabuf->swptr = swptr;
1676                 pending = dmabuf->count += cnt;
1677
1678                 count -= cnt;
1679                 buffer += cnt;
1680                 ret += cnt;
1681                 spin_unlock_irqrestore(&state->card->lock, flags);
1682         }
1683 ret:
1684         if (dmabuf->enable || pending >= dmabuf->userfragsize)
1685                 i810_update_lvi(state, 0);
1686         set_current_state(TASK_RUNNING);
1687         remove_wait_queue(&dmabuf->wait, &waita);
1688
1689         return ret;
1690 }
1691
1692 /* No kernel lock - we have our own spinlock */
1693 static unsigned int i810_poll(struct file *file, struct poll_table_struct *wait)
1694 {
1695         struct i810_state *state = (struct i810_state *)file->private_data;
1696         struct dmabuf *dmabuf = &state->dmabuf;
1697         unsigned long flags;
1698         unsigned int mask = 0;
1699
1700         if(!dmabuf->ready)
1701                 return 0;
1702         poll_wait(file, &dmabuf->wait, wait);
1703         spin_lock_irqsave(&state->card->lock, flags);
1704         if (dmabuf->enable & ADC_RUNNING ||
1705             dmabuf->trigger & PCM_ENABLE_INPUT) {
1706                 if (i810_get_available_read_data(state) >= 
1707                     (signed)dmabuf->userfragsize)
1708                         mask |= POLLIN | POLLRDNORM;
1709         }
1710         if (dmabuf->enable & DAC_RUNNING ||
1711             dmabuf->trigger & PCM_ENABLE_OUTPUT) {
1712                 if (i810_get_free_write_space(state) >=
1713                     (signed)dmabuf->userfragsize)
1714                         mask |= POLLOUT | POLLWRNORM;
1715         }
1716         spin_unlock_irqrestore(&state->card->lock, flags);
1717         return mask;
1718 }
1719
1720 static int i810_mmap(struct file *file, struct vm_area_struct *vma)
1721 {
1722         struct i810_state *state = (struct i810_state *)file->private_data;
1723         struct dmabuf *dmabuf = &state->dmabuf;
1724         int ret = -EINVAL;
1725         unsigned long size;
1726
1727         lock_kernel();
1728         if (vma->vm_flags & VM_WRITE) {
1729                 if (!dmabuf->write_channel &&
1730                     (dmabuf->write_channel =
1731                      state->card->alloc_pcm_channel(state->card)) == NULL) {
1732                         ret = -EBUSY;
1733                         goto out;
1734                 }
1735         }
1736         if (vma->vm_flags & VM_READ) {
1737                 if (!dmabuf->read_channel &&
1738                     (dmabuf->read_channel = 
1739                      state->card->alloc_rec_pcm_channel(state->card)) == NULL) {
1740                         ret = -EBUSY;
1741                         goto out;
1742                 }
1743         }
1744         if ((ret = prog_dmabuf(state, 0)) != 0)
1745                 goto out;
1746
1747         ret = -EINVAL;
1748         if (vma->vm_pgoff != 0)
1749                 goto out;
1750         size = vma->vm_end - vma->vm_start;
1751         if (size > (PAGE_SIZE << dmabuf->buforder))
1752                 goto out;
1753         ret = -EAGAIN;
1754         if (remap_page_range(vma, vma->vm_start, virt_to_phys(dmabuf->rawbuf),
1755                              size, vma->vm_page_prot))
1756                 goto out;
1757         dmabuf->mapped = 1;
1758         dmabuf->trigger = 0;
1759         ret = 0;
1760 #ifdef DEBUG_MMAP
1761         printk("i810_audio: mmap'ed %ld bytes of data space\n", size);
1762 #endif
1763 out:
1764         unlock_kernel();
1765         return ret;
1766 }
1767
1768 static int i810_ioctl(struct inode *inode, struct file *file, unsigned int cmd, unsigned long arg)
1769 {
1770         struct i810_state *state = (struct i810_state *)file->private_data;
1771         struct i810_channel *c = NULL;
1772         struct dmabuf *dmabuf = &state->dmabuf;
1773         unsigned long flags;
1774         audio_buf_info abinfo;
1775         count_info cinfo;
1776         unsigned int i_glob_cnt;
1777         int val = 0, ret;
1778         struct ac97_codec *codec = state->card->ac97_codec[0];
1779         void __user *argp = (void __user *)arg;
1780         int __user *p = argp;
1781
1782 #ifdef DEBUG
1783         printk("i810_audio: i810_ioctl, arg=0x%x, cmd=", arg ? *p : 0);
1784 #endif
1785
1786         switch (cmd) 
1787         {
1788         case OSS_GETVERSION:
1789 #ifdef DEBUG
1790                 printk("OSS_GETVERSION\n");
1791 #endif
1792                 return put_user(SOUND_VERSION, p);
1793
1794         case SNDCTL_DSP_RESET:
1795 #ifdef DEBUG
1796                 printk("SNDCTL_DSP_RESET\n");
1797 #endif
1798                 spin_lock_irqsave(&state->card->lock, flags);
1799                 if (dmabuf->enable == DAC_RUNNING) {
1800                         c = dmabuf->write_channel;
1801                         __stop_dac(state);
1802                 }
1803                 if (dmabuf->enable == ADC_RUNNING) {
1804                         c = dmabuf->read_channel;
1805                         __stop_adc(state);
1806                 }
1807                 if (c != NULL) {
1808                         I810_IOWRITEB(2, state->card, c->port+OFF_CR);   /* reset DMA machine */
1809                         while ( I810_IOREADB(state->card, c->port+OFF_CR) & 2 )
1810                                 cpu_relax();
1811                         I810_IOWRITEL((u32)state->card->chandma +
1812                             c->num*sizeof(struct i810_channel),
1813                             state->card, c->port+OFF_BDBAR);
1814                         CIV_TO_LVI(state->card, c->port, 0);
1815                 }
1816
1817                 spin_unlock_irqrestore(&state->card->lock, flags);
1818                 synchronize_irq(state->card->pci_dev->irq);
1819                 dmabuf->ready = 0;
1820                 dmabuf->swptr = dmabuf->hwptr = 0;
1821                 dmabuf->count = dmabuf->total_bytes = 0;
1822                 return 0;
1823
1824         case SNDCTL_DSP_SYNC:
1825 #ifdef DEBUG
1826                 printk("SNDCTL_DSP_SYNC\n");
1827 #endif
1828                 if (dmabuf->enable != DAC_RUNNING || file->f_flags & O_NONBLOCK)
1829                         return 0;
1830                 if((val = drain_dac(state, 1)))
1831                         return val;
1832                 dmabuf->total_bytes = 0;
1833                 return 0;
1834
1835         case SNDCTL_DSP_SPEED: /* set smaple rate */
1836 #ifdef DEBUG
1837                 printk("SNDCTL_DSP_SPEED\n");
1838 #endif
1839                 if (get_user(val, p))
1840                         return -EFAULT;
1841                 if (val >= 0) {
1842                         if (file->f_mode & FMODE_WRITE) {
1843                                 if ( (state->card->ac97_status & SPDIF_ON) ) {  /* S/PDIF Enabled */
1844                                         /* AD1886 only supports 48000, need to check that */
1845                                         if ( i810_valid_spdif_rate ( codec, val ) ) {
1846                                                 /* Set DAC rate */
1847                                                 i810_set_spdif_output ( state, -1, 0 );
1848                                                 stop_dac(state);
1849                                                 dmabuf->ready = 0;
1850                                                 spin_lock_irqsave(&state->card->lock, flags);
1851                                                 i810_set_dac_rate(state, val);
1852                                                 spin_unlock_irqrestore(&state->card->lock, flags);
1853                                                 /* Set S/PDIF transmitter rate. */
1854                                                 i810_set_spdif_output ( state, AC97_EA_SPSA_3_4, val );
1855                                                 if ( ! (state->card->ac97_status & SPDIF_ON) ) {
1856                                                         val = dmabuf->rate;
1857                                                 }
1858                                         } else { /* Not a valid rate for S/PDIF, ignore it */
1859                                                 val = dmabuf->rate;
1860                                         }
1861                                 } else {
1862                                         stop_dac(state);
1863                                         dmabuf->ready = 0;
1864                                         spin_lock_irqsave(&state->card->lock, flags);
1865                                         i810_set_dac_rate(state, val);
1866                                         spin_unlock_irqrestore(&state->card->lock, flags);
1867                                 }
1868                         }
1869                         if (file->f_mode & FMODE_READ) {
1870                                 stop_adc(state);
1871                                 dmabuf->ready = 0;
1872                                 spin_lock_irqsave(&state->card->lock, flags);
1873                                 i810_set_adc_rate(state, val);
1874                                 spin_unlock_irqrestore(&state->card->lock, flags);
1875                         }
1876                 }
1877                 return put_user(dmabuf->rate, p);
1878
1879         case SNDCTL_DSP_STEREO: /* set stereo or mono channel */
1880 #ifdef DEBUG
1881                 printk("SNDCTL_DSP_STEREO\n");
1882 #endif
1883                 if (dmabuf->enable & DAC_RUNNING) {
1884                         stop_dac(state);
1885                 }
1886                 if (dmabuf->enable & ADC_RUNNING) {
1887                         stop_adc(state);
1888                 }
1889                 return put_user(1, p);
1890
1891         case SNDCTL_DSP_GETBLKSIZE:
1892                 if (file->f_mode & FMODE_WRITE) {
1893                         if (!dmabuf->ready && (val = prog_dmabuf(state, 0)))
1894                                 return val;
1895                 }
1896                 if (file->f_mode & FMODE_READ) {
1897                         if (!dmabuf->ready && (val = prog_dmabuf(state, 1)))
1898                                 return val;
1899                 }
1900 #ifdef DEBUG
1901                 printk("SNDCTL_DSP_GETBLKSIZE %d\n", dmabuf->userfragsize);
1902 #endif
1903                 return put_user(dmabuf->userfragsize, p);
1904
1905         case SNDCTL_DSP_GETFMTS: /* Returns a mask of supported sample format*/
1906 #ifdef DEBUG
1907                 printk("SNDCTL_DSP_GETFMTS\n");
1908 #endif
1909                 return put_user(AFMT_S16_LE, p);
1910
1911         case SNDCTL_DSP_SETFMT: /* Select sample format */
1912 #ifdef DEBUG
1913                 printk("SNDCTL_DSP_SETFMT\n");
1914 #endif
1915                 return put_user(AFMT_S16_LE, p);
1916
1917         case SNDCTL_DSP_CHANNELS:
1918 #ifdef DEBUG
1919                 printk("SNDCTL_DSP_CHANNELS\n");
1920 #endif
1921                 if (get_user(val, p))
1922                         return -EFAULT;
1923
1924                 if (val > 0) {
1925                         if (dmabuf->enable & DAC_RUNNING) {
1926                                 stop_dac(state);
1927                         }
1928                         if (dmabuf->enable & ADC_RUNNING) {
1929                                 stop_adc(state);
1930                         }
1931                 } else {
1932                         return put_user(state->card->channels, p);
1933                 }
1934
1935                 /* ICH and ICH0 only support 2 channels */
1936                 if ( state->card->pci_id == PCI_DEVICE_ID_INTEL_82801AA_5
1937                      || state->card->pci_id == PCI_DEVICE_ID_INTEL_82801AB_5) 
1938                         return put_user(2, p);
1939         
1940                 /* Multi-channel support was added with ICH2. Bits in */
1941                 /* Global Status and Global Control register are now  */
1942                 /* used to indicate this.                             */
1943
1944                 i_glob_cnt = I810_IOREADL(state->card, GLOB_CNT);
1945
1946                 /* Current # of channels enabled */
1947                 if ( i_glob_cnt & 0x0100000 )
1948                         ret = 4;
1949                 else if ( i_glob_cnt & 0x0200000 )
1950                         ret = 6;
1951                 else
1952                         ret = 2;
1953
1954                 switch ( val ) {
1955                         case 2: /* 2 channels is always supported */
1956                                 I810_IOWRITEL(i_glob_cnt & 0xffcfffff,
1957                                      state->card, GLOB_CNT);
1958                                 /* Do we need to change mixer settings????  */
1959                                 break;
1960                         case 4: /* Supported on some chipsets, better check first */
1961                                 if ( state->card->channels >= 4 ) {
1962                                         I810_IOWRITEL((i_glob_cnt & 0xffcfffff) | 0x100000,
1963                                               state->card, GLOB_CNT);
1964                                         /* Do we need to change mixer settings??? */
1965                                 } else {
1966                                         val = ret;
1967                                 }
1968                                 break;
1969                         case 6: /* Supported on some chipsets, better check first */
1970                                 if ( state->card->channels >= 6 ) {
1971                                         I810_IOWRITEL((i_glob_cnt & 0xffcfffff) | 0x200000,
1972                                               state->card, GLOB_CNT);
1973                                         /* Do we need to change mixer settings??? */
1974                                 } else {
1975                                         val = ret;
1976                                 }
1977                                 break;
1978                         default: /* nothing else is ever supported by the chipset */
1979                                 val = ret;
1980                                 break;
1981                 }
1982
1983                 return put_user(val, p);
1984
1985         case SNDCTL_DSP_POST: /* the user has sent all data and is notifying us */
1986                 /* we update the swptr to the end of the last sg segment then return */
1987 #ifdef DEBUG
1988                 printk("SNDCTL_DSP_POST\n");
1989 #endif
1990                 if(!dmabuf->ready || (dmabuf->enable != DAC_RUNNING))
1991                         return 0;
1992                 if((dmabuf->swptr % dmabuf->fragsize) != 0) {
1993                         val = dmabuf->fragsize - (dmabuf->swptr % dmabuf->fragsize);
1994                         dmabuf->swptr += val;
1995                         dmabuf->count += val;
1996                 }
1997                 return 0;
1998
1999         case SNDCTL_DSP_SUBDIVIDE:
2000                 if (dmabuf->subdivision)
2001                         return -EINVAL;
2002                 if (get_user(val, p))
2003                         return -EFAULT;
2004                 if (val != 1 && val != 2 && val != 4)
2005                         return -EINVAL;
2006 #ifdef DEBUG
2007                 printk("SNDCTL_DSP_SUBDIVIDE %d\n", val);
2008 #endif
2009                 dmabuf->subdivision = val;
2010                 dmabuf->ready = 0;
2011                 return 0;
2012
2013         case SNDCTL_DSP_SETFRAGMENT:
2014                 if (get_user(val, p))
2015                         return -EFAULT;
2016
2017                 dmabuf->ossfragsize = 1<<(val & 0xffff);
2018                 dmabuf->ossmaxfrags = (val >> 16) & 0xffff;
2019                 if (!dmabuf->ossfragsize || !dmabuf->ossmaxfrags)
2020                         return -EINVAL;
2021                 /*
2022                  * Bound the frag size into our allowed range of 256 - 4096
2023                  */
2024                 if (dmabuf->ossfragsize < 256)
2025                         dmabuf->ossfragsize = 256;
2026                 else if (dmabuf->ossfragsize > 4096)
2027                         dmabuf->ossfragsize = 4096;
2028                 /*
2029                  * The numfrags could be something reasonable, or it could
2030                  * be 0xffff meaning "Give me as much as possible".  So,
2031                  * we check the numfrags * fragsize doesn't exceed our
2032                  * 64k buffer limit, nor is it less than our 8k minimum.
2033                  * If it fails either one of these checks, then adjust the
2034                  * number of fragments, not the size of them.  It's OK if
2035                  * our number of fragments doesn't equal 32 or anything
2036                  * like our hardware based number now since we are using
2037                  * a different frag count for the hardware.  Before we get
2038                  * into this though, bound the maxfrags to avoid overflow
2039                  * issues.  A reasonable bound would be 64k / 256 since our
2040                  * maximum buffer size is 64k and our minimum frag size is
2041                  * 256.  On the other end, our minimum buffer size is 8k and
2042                  * our maximum frag size is 4k, so the lower bound should
2043                  * be 2.
2044                  */
2045
2046                 if(dmabuf->ossmaxfrags > 256)
2047                         dmabuf->ossmaxfrags = 256;
2048                 else if (dmabuf->ossmaxfrags < 2)
2049                         dmabuf->ossmaxfrags = 2;
2050
2051                 val = dmabuf->ossfragsize * dmabuf->ossmaxfrags;
2052                 while (val < 8192) {
2053                     val <<= 1;
2054                     dmabuf->ossmaxfrags <<= 1;
2055                 }
2056                 while (val > 65536) {
2057                     val >>= 1;
2058                     dmabuf->ossmaxfrags >>= 1;
2059                 }
2060                 dmabuf->ready = 0;
2061 #ifdef DEBUG
2062                 printk("SNDCTL_DSP_SETFRAGMENT 0x%x, %d, %d\n", val,
2063                         dmabuf->ossfragsize, dmabuf->ossmaxfrags);
2064 #endif
2065
2066                 return 0;
2067
2068         case SNDCTL_DSP_GETOSPACE:
2069                 if (!(file->f_mode & FMODE_WRITE))
2070                         return -EINVAL;
2071                 if (!dmabuf->ready && (val = prog_dmabuf(state, 0)) != 0)
2072                         return val;
2073                 spin_lock_irqsave(&state->card->lock, flags);
2074                 i810_update_ptr(state);
2075                 abinfo.fragsize = dmabuf->userfragsize;
2076                 abinfo.fragstotal = dmabuf->userfrags;
2077                 if (dmabuf->mapped)
2078                         abinfo.bytes = dmabuf->dmasize;
2079                 else
2080                         abinfo.bytes = i810_get_free_write_space(state);
2081                 abinfo.fragments = abinfo.bytes / dmabuf->userfragsize;
2082                 spin_unlock_irqrestore(&state->card->lock, flags);
2083 #if defined(DEBUG) || defined(DEBUG_MMAP)
2084                 printk("SNDCTL_DSP_GETOSPACE %d, %d, %d, %d\n", abinfo.bytes,
2085                         abinfo.fragsize, abinfo.fragments, abinfo.fragstotal);
2086 #endif
2087                 return copy_to_user(argp, &abinfo, sizeof(abinfo)) ? -EFAULT : 0;
2088
2089         case SNDCTL_DSP_GETOPTR:
2090                 if (!(file->f_mode & FMODE_WRITE))
2091                         return -EINVAL;
2092                 if (!dmabuf->ready && (val = prog_dmabuf(state, 0)) != 0)
2093                         return val;
2094                 spin_lock_irqsave(&state->card->lock, flags);
2095                 val = i810_get_free_write_space(state);
2096                 cinfo.bytes = dmabuf->total_bytes;
2097                 cinfo.ptr = dmabuf->hwptr;
2098                 cinfo.blocks = val/dmabuf->userfragsize;
2099                 if (dmabuf->mapped && (dmabuf->trigger & PCM_ENABLE_OUTPUT)) {
2100                         dmabuf->count += val;
2101                         dmabuf->swptr = (dmabuf->swptr + val) % dmabuf->dmasize;
2102                         __i810_update_lvi(state, 0);
2103                 }
2104                 spin_unlock_irqrestore(&state->card->lock, flags);
2105 #if defined(DEBUG) || defined(DEBUG_MMAP)
2106                 printk("SNDCTL_DSP_GETOPTR %d, %d, %d, %d\n", cinfo.bytes,
2107                         cinfo.blocks, cinfo.ptr, dmabuf->count);
2108 #endif
2109                 return copy_to_user(argp, &cinfo, sizeof(cinfo)) ? -EFAULT : 0;
2110
2111         case SNDCTL_DSP_GETISPACE:
2112                 if (!(file->f_mode & FMODE_READ))
2113                         return -EINVAL;
2114                 if (!dmabuf->ready && (val = prog_dmabuf(state, 1)) != 0)
2115                         return val;
2116                 spin_lock_irqsave(&state->card->lock, flags);
2117                 abinfo.bytes = i810_get_available_read_data(state);
2118                 abinfo.fragsize = dmabuf->userfragsize;
2119                 abinfo.fragstotal = dmabuf->userfrags;
2120                 abinfo.fragments = abinfo.bytes / dmabuf->userfragsize;
2121                 spin_unlock_irqrestore(&state->card->lock, flags);
2122 #if defined(DEBUG) || defined(DEBUG_MMAP)
2123                 printk("SNDCTL_DSP_GETISPACE %d, %d, %d, %d\n", abinfo.bytes,
2124                         abinfo.fragsize, abinfo.fragments, abinfo.fragstotal);
2125 #endif
2126                 return copy_to_user(argp, &abinfo, sizeof(abinfo)) ? -EFAULT : 0;
2127
2128         case SNDCTL_DSP_GETIPTR:
2129                 if (!(file->f_mode & FMODE_READ))
2130                         return -EINVAL;
2131                 if (!dmabuf->ready && (val = prog_dmabuf(state, 0)) != 0)
2132                         return val;
2133                 spin_lock_irqsave(&state->card->lock, flags);
2134                 val = i810_get_available_read_data(state);
2135                 cinfo.bytes = dmabuf->total_bytes;
2136                 cinfo.blocks = val/dmabuf->userfragsize;
2137                 cinfo.ptr = dmabuf->hwptr;
2138                 if (dmabuf->mapped && (dmabuf->trigger & PCM_ENABLE_INPUT)) {
2139                         dmabuf->count -= val;
2140                         dmabuf->swptr = (dmabuf->swptr + val) % dmabuf->dmasize;
2141                         __i810_update_lvi(state, 1);
2142                 }
2143                 spin_unlock_irqrestore(&state->card->lock, flags);
2144 #if defined(DEBUG) || defined(DEBUG_MMAP)
2145                 printk("SNDCTL_DSP_GETIPTR %d, %d, %d, %d\n", cinfo.bytes,
2146                         cinfo.blocks, cinfo.ptr, dmabuf->count);
2147 #endif
2148                 return copy_to_user(argp, &cinfo, sizeof(cinfo)) ? -EFAULT : 0;
2149
2150         case SNDCTL_DSP_NONBLOCK:
2151 #ifdef DEBUG
2152                 printk("SNDCTL_DSP_NONBLOCK\n");
2153 #endif
2154                 file->f_flags |= O_NONBLOCK;
2155                 return 0;
2156
2157         case SNDCTL_DSP_GETCAPS:
2158 #ifdef DEBUG
2159                 printk("SNDCTL_DSP_GETCAPS\n");
2160 #endif
2161             return put_user(DSP_CAP_REALTIME|DSP_CAP_TRIGGER|DSP_CAP_MMAP|DSP_CAP_BIND,
2162                             p);
2163
2164         case SNDCTL_DSP_GETTRIGGER:
2165                 val = 0;
2166 #ifdef DEBUG
2167                 printk("SNDCTL_DSP_GETTRIGGER 0x%x\n", dmabuf->trigger);
2168 #endif
2169                 return put_user(dmabuf->trigger, p);
2170
2171         case SNDCTL_DSP_SETTRIGGER:
2172                 if (get_user(val, p))
2173                         return -EFAULT;
2174 #if defined(DEBUG) || defined(DEBUG_MMAP)
2175                 printk("SNDCTL_DSP_SETTRIGGER 0x%x\n", val);
2176 #endif
2177                 /* silently ignore invalid PCM_ENABLE_xxx bits,
2178                  * like the other drivers do
2179                  */
2180                 if (!(file->f_mode & FMODE_READ ))
2181                         val &= ~PCM_ENABLE_INPUT;
2182                 if (!(file->f_mode & FMODE_WRITE ))
2183                         val &= ~PCM_ENABLE_OUTPUT;
2184                 if((file->f_mode & FMODE_READ) && !(val & PCM_ENABLE_INPUT) && dmabuf->enable == ADC_RUNNING) {
2185                         stop_adc(state);
2186                 }
2187                 if((file->f_mode & FMODE_WRITE) && !(val & PCM_ENABLE_OUTPUT) && dmabuf->enable == DAC_RUNNING) {
2188                         stop_dac(state);
2189                 }
2190                 dmabuf->trigger = val;
2191                 if((val & PCM_ENABLE_OUTPUT) && !(dmabuf->enable & DAC_RUNNING)) {
2192                         if (!dmabuf->write_channel) {
2193                                 dmabuf->ready = 0;
2194                                 dmabuf->write_channel = state->card->alloc_pcm_channel(state->card);
2195                                 if (!dmabuf->write_channel)
2196                                         return -EBUSY;
2197                         }
2198                         if (!dmabuf->ready && (ret = prog_dmabuf(state, 0)))
2199                                 return ret;
2200                         if (dmabuf->mapped) {
2201                                 spin_lock_irqsave(&state->card->lock, flags);
2202                                 i810_update_ptr(state);
2203                                 dmabuf->count = 0;
2204                                 dmabuf->swptr = dmabuf->hwptr;
2205                                 dmabuf->count = i810_get_free_write_space(state);
2206                                 dmabuf->swptr = (dmabuf->swptr + dmabuf->count) % dmabuf->dmasize;
2207                                 spin_unlock_irqrestore(&state->card->lock, flags);
2208                         }
2209                         i810_update_lvi(state, 0);
2210                         start_dac(state);
2211                 }
2212                 if((val & PCM_ENABLE_INPUT) && !(dmabuf->enable & ADC_RUNNING)) {
2213                         if (!dmabuf->read_channel) {
2214                                 dmabuf->ready = 0;
2215                                 dmabuf->read_channel = state->card->alloc_rec_pcm_channel(state->card);
2216                                 if (!dmabuf->read_channel)
2217                                         return -EBUSY;
2218                         }
2219                         if (!dmabuf->ready && (ret = prog_dmabuf(state, 1)))
2220                                 return ret;
2221                         if (dmabuf->mapped) {
2222                                 spin_lock_irqsave(&state->card->lock, flags);
2223                                 i810_update_ptr(state);
2224                                 dmabuf->swptr = dmabuf->hwptr;
2225                                 dmabuf->count = 0;
2226                                 spin_unlock_irqrestore(&state->card->lock, flags);
2227                         }
2228                         i810_update_lvi(state, 1);
2229                         start_adc(state);
2230                 }
2231                 return 0;
2232
2233         case SNDCTL_DSP_SETDUPLEX:
2234 #ifdef DEBUG
2235                 printk("SNDCTL_DSP_SETDUPLEX\n");
2236 #endif
2237                 return -EINVAL;
2238
2239         case SNDCTL_DSP_GETODELAY:
2240                 if (!(file->f_mode & FMODE_WRITE))
2241                         return -EINVAL;
2242                 spin_lock_irqsave(&state->card->lock, flags);
2243                 i810_update_ptr(state);
2244                 val = dmabuf->count;
2245                 spin_unlock_irqrestore(&state->card->lock, flags);
2246 #ifdef DEBUG
2247                 printk("SNDCTL_DSP_GETODELAY %d\n", dmabuf->count);
2248 #endif
2249                 return put_user(val, p);
2250
2251         case SOUND_PCM_READ_RATE:
2252 #ifdef DEBUG
2253                 printk("SOUND_PCM_READ_RATE %d\n", dmabuf->rate);
2254 #endif
2255                 return put_user(dmabuf->rate, p);
2256
2257         case SOUND_PCM_READ_CHANNELS:
2258 #ifdef DEBUG
2259                 printk("SOUND_PCM_READ_CHANNELS\n");
2260 #endif
2261                 return put_user(2, p);
2262
2263         case SOUND_PCM_READ_BITS:
2264 #ifdef DEBUG
2265                 printk("SOUND_PCM_READ_BITS\n");
2266 #endif
2267                 return put_user(AFMT_S16_LE, p);
2268
2269         case SNDCTL_DSP_SETSPDIF: /* Set S/PDIF Control register */
2270 #ifdef DEBUG
2271                 printk("SNDCTL_DSP_SETSPDIF\n");
2272 #endif
2273                 if (get_user(val, p))
2274                         return -EFAULT;
2275
2276                 /* Check to make sure the codec supports S/PDIF transmitter */
2277
2278                 if((state->card->ac97_features & 4)) {
2279                         /* mask out the transmitter speed bits so the user can't set them */
2280                         val &= ~0x3000;
2281
2282                         /* Add the current transmitter speed bits to the passed value */
2283                         ret = i810_ac97_get(codec, AC97_SPDIF_CONTROL);
2284                         val |= (ret & 0x3000);
2285
2286                         i810_ac97_set(codec, AC97_SPDIF_CONTROL, val);
2287                         if(i810_ac97_get(codec, AC97_SPDIF_CONTROL) != val ) {
2288                                 printk(KERN_ERR "i810_audio: Unable to set S/PDIF configuration to 0x%04x.\n", val);
2289                                 return -EFAULT;
2290                         }
2291                 }
2292 #ifdef DEBUG
2293                 else 
2294                         printk(KERN_WARNING "i810_audio: S/PDIF transmitter not avalible.\n");
2295 #endif
2296                 return put_user(val, p);
2297
2298         case SNDCTL_DSP_GETSPDIF: /* Get S/PDIF Control register */
2299 #ifdef DEBUG
2300                 printk("SNDCTL_DSP_GETSPDIF\n");
2301 #endif
2302                 if (get_user(val, p))
2303                         return -EFAULT;
2304
2305                 /* Check to make sure the codec supports S/PDIF transmitter */
2306
2307                 if(!(state->card->ac97_features & 4)) {
2308 #ifdef DEBUG
2309                         printk(KERN_WARNING "i810_audio: S/PDIF transmitter not avalible.\n");
2310 #endif
2311                         val = 0;
2312                 } else {
2313                         val = i810_ac97_get(codec, AC97_SPDIF_CONTROL);
2314                 }
2315                 //return put_user((val & 0xcfff), p);
2316                 return put_user(val, p);
2317                         
2318         case SNDCTL_DSP_GETCHANNELMASK:
2319 #ifdef DEBUG
2320                 printk("SNDCTL_DSP_GETCHANNELMASK\n");
2321 #endif
2322                 if (get_user(val, p))
2323                         return -EFAULT;
2324                 
2325                 /* Based on AC'97 DAC support, not ICH hardware */
2326                 val = DSP_BIND_FRONT;
2327                 if ( state->card->ac97_features & 0x0004 )
2328                         val |= DSP_BIND_SPDIF;
2329
2330                 if ( state->card->ac97_features & 0x0080 )
2331                         val |= DSP_BIND_SURR;
2332                 if ( state->card->ac97_features & 0x0140 )
2333                         val |= DSP_BIND_CENTER_LFE;
2334
2335                 return put_user(val, p);
2336
2337         case SNDCTL_DSP_BIND_CHANNEL:
2338 #ifdef DEBUG
2339                 printk("SNDCTL_DSP_BIND_CHANNEL\n");
2340 #endif
2341                 if (get_user(val, p))
2342                         return -EFAULT;
2343                 if ( val == DSP_BIND_QUERY ) {
2344                         val = DSP_BIND_FRONT; /* Always report this as being enabled */
2345                         if ( state->card->ac97_status & SPDIF_ON ) 
2346                                 val |= DSP_BIND_SPDIF;
2347                         else {
2348                                 if ( state->card->ac97_status & SURR_ON )
2349                                         val |= DSP_BIND_SURR;
2350                                 if ( state->card->ac97_status & CENTER_LFE_ON )
2351                                         val |= DSP_BIND_CENTER_LFE;
2352                         }
2353                 } else {  /* Not a query, set it */
2354                         if (!(file->f_mode & FMODE_WRITE))
2355                                 return -EINVAL;
2356                         if ( dmabuf->enable == DAC_RUNNING ) {
2357                                 stop_dac(state);
2358                         }
2359                         if ( val & DSP_BIND_SPDIF ) {  /* Turn on SPDIF */
2360                                 /*  Ok, this should probably define what slots
2361                                  *  to use. For now, we'll only set it to the
2362                                  *  defaults:
2363                                  * 
2364                                  *   non multichannel codec maps to slots 3&4
2365                                  *   2 channel codec maps to slots 7&8
2366                                  *   4 channel codec maps to slots 6&9
2367                                  *   6 channel codec maps to slots 10&11
2368                                  *
2369                                  *  there should be some way for the app to
2370                                  *  select the slot assignment.
2371                                  */
2372         
2373                                 i810_set_spdif_output ( state, AC97_EA_SPSA_3_4, dmabuf->rate );
2374                                 if ( !(state->card->ac97_status & SPDIF_ON) )
2375                                         val &= ~DSP_BIND_SPDIF;
2376                         } else {
2377                                 int mask;
2378                                 int channels;
2379
2380                                 /* Turn off S/PDIF if it was on */
2381                                 if ( state->card->ac97_status & SPDIF_ON ) 
2382                                         i810_set_spdif_output ( state, -1, 0 );
2383                                 
2384                                 mask = val & (DSP_BIND_FRONT | DSP_BIND_SURR | DSP_BIND_CENTER_LFE);
2385                                 switch (mask) {
2386                                         case DSP_BIND_FRONT:
2387                                                 channels = 2;
2388                                                 break;
2389                                         case DSP_BIND_FRONT|DSP_BIND_SURR:
2390                                                 channels = 4;
2391                                                 break;
2392                                         case DSP_BIND_FRONT|DSP_BIND_SURR|DSP_BIND_CENTER_LFE:
2393                                                 channels = 6;
2394                                                 break;
2395                                         default:
2396                                                 val = DSP_BIND_FRONT;
2397                                                 channels = 2;
2398                                                 break;
2399                                 }
2400                                 i810_set_dac_channels ( state, channels );
2401
2402                                 /* check that they really got turned on */
2403                                 if (!(state->card->ac97_status & SURR_ON))
2404                                         val &= ~DSP_BIND_SURR;
2405                                 if (!(state->card->ac97_status & CENTER_LFE_ON))
2406                                         val &= ~DSP_BIND_CENTER_LFE;
2407                         }
2408                 }
2409                 return put_user(val, p);
2410                 
2411         case SNDCTL_DSP_MAPINBUF:
2412         case SNDCTL_DSP_MAPOUTBUF:
2413         case SNDCTL_DSP_SETSYNCRO:
2414         case SOUND_PCM_WRITE_FILTER:
2415         case SOUND_PCM_READ_FILTER:
2416 #ifdef DEBUG
2417                 printk("SNDCTL_* -EINVAL\n");
2418 #endif
2419                 return -EINVAL;
2420         }
2421         return -EINVAL;
2422 }
2423
2424 static int i810_open(struct inode *inode, struct file *file)
2425 {
2426         int i = 0;
2427         struct i810_card *card = devs;
2428         struct i810_state *state = NULL;
2429         struct dmabuf *dmabuf = NULL;
2430
2431         /* find an avaiable virtual channel (instance of /dev/dsp) */
2432         while (card != NULL) {
2433                 /*
2434                  * If we are initializing and then fail, card could go
2435                  * away unuexpectedly while we are in the for() loop.
2436                  * So, check for card on each iteration before we check
2437                  * for card->initializing to avoid a possible oops.
2438                  * This usually only matters for times when the driver is
2439                  * autoloaded by kmod.
2440                  */
2441                 for (i = 0; i < 50 && card && card->initializing; i++) {
2442                         set_current_state(TASK_UNINTERRUPTIBLE);
2443                         schedule_timeout(HZ/20);
2444                 }
2445                 for (i = 0; i < NR_HW_CH && card && !card->initializing; i++) {
2446                         if (card->states[i] == NULL) {
2447                                 state = card->states[i] = (struct i810_state *)
2448                                         kmalloc(sizeof(struct i810_state), GFP_KERNEL);
2449                                 if (state == NULL)
2450                                         return -ENOMEM;
2451                                 memset(state, 0, sizeof(struct i810_state));
2452                                 dmabuf = &state->dmabuf;
2453                                 goto found_virt;
2454                         }
2455                 }
2456                 card = card->next;
2457         }
2458         /* no more virtual channel avaiable */
2459         if (!state)
2460                 return -ENODEV;
2461
2462 found_virt:
2463         /* initialize the virtual channel */
2464         state->virt = i;
2465         state->card = card;
2466         state->magic = I810_STATE_MAGIC;
2467         init_waitqueue_head(&dmabuf->wait);
2468         init_MUTEX(&state->open_sem);
2469         file->private_data = state;
2470         dmabuf->trigger = 0;
2471
2472         /* allocate hardware channels */
2473         if(file->f_mode & FMODE_READ) {
2474                 if((dmabuf->read_channel = card->alloc_rec_pcm_channel(card)) == NULL) {
2475                         kfree (card->states[i]);
2476                         card->states[i] = NULL;
2477                         return -EBUSY;
2478                 }
2479                 dmabuf->trigger |= PCM_ENABLE_INPUT;
2480                 i810_set_adc_rate(state, 8000);
2481         }
2482         if(file->f_mode & FMODE_WRITE) {
2483                 if((dmabuf->write_channel = card->alloc_pcm_channel(card)) == NULL) {
2484                         /* make sure we free the record channel allocated above */
2485                         if(file->f_mode & FMODE_READ)
2486                                 card->free_pcm_channel(card,dmabuf->read_channel->num);
2487                         kfree (card->states[i]);
2488                         card->states[i] = NULL;
2489                         return -EBUSY;
2490                 }
2491                 /* Initialize to 8kHz?  What if we don't support 8kHz? */
2492                 /*  Let's change this to check for S/PDIF stuff */
2493         
2494                 dmabuf->trigger |= PCM_ENABLE_OUTPUT;
2495                 if ( spdif_locked ) {
2496                         i810_set_dac_rate(state, spdif_locked);
2497                         i810_set_spdif_output(state, AC97_EA_SPSA_3_4, spdif_locked);
2498                 } else {
2499                         i810_set_dac_rate(state, 8000);
2500                         /* Put the ACLink in 2 channel mode by default */
2501                         i = I810_IOREADL(card, GLOB_CNT);
2502                         I810_IOWRITEL(i & 0xffcfffff, card, GLOB_CNT);
2503                 }
2504         }
2505                 
2506         /* set default sample format. According to OSS Programmer's Guide  /dev/dsp
2507            should be default to unsigned 8-bits, mono, with sample rate 8kHz and
2508            /dev/dspW will accept 16-bits sample, but we don't support those so we
2509            set it immediately to stereo and 16bit, which is all we do support */
2510         dmabuf->fmt |= I810_FMT_16BIT | I810_FMT_STEREO;
2511         dmabuf->ossfragsize = 0;
2512         dmabuf->ossmaxfrags  = 0;
2513         dmabuf->subdivision  = 0;
2514
2515         state->open_mode |= file->f_mode & (FMODE_READ | FMODE_WRITE);
2516
2517         return nonseekable_open(inode, file);
2518 }
2519
2520 static int i810_release(struct inode *inode, struct file *file)
2521 {
2522         struct i810_state *state = (struct i810_state *)file->private_data;
2523         struct i810_card *card = state->card;
2524         struct dmabuf *dmabuf = &state->dmabuf;
2525         unsigned long flags;
2526
2527         lock_kernel();
2528
2529         /* stop DMA state machine and free DMA buffers/channels */
2530         if(dmabuf->trigger & PCM_ENABLE_OUTPUT) {
2531                 drain_dac(state, 0);
2532         }
2533         if(dmabuf->trigger & PCM_ENABLE_INPUT) {
2534                 stop_adc(state);
2535         }
2536         spin_lock_irqsave(&card->lock, flags);
2537         dealloc_dmabuf(state);
2538         if (file->f_mode & FMODE_WRITE) {
2539                 state->card->free_pcm_channel(state->card, dmabuf->write_channel->num);
2540         }
2541         if (file->f_mode & FMODE_READ) {
2542                 state->card->free_pcm_channel(state->card, dmabuf->read_channel->num);
2543         }
2544
2545         state->card->states[state->virt] = NULL;
2546         kfree(state);
2547         spin_unlock_irqrestore(&card->lock, flags);
2548         unlock_kernel();
2549
2550         return 0;
2551 }
2552
2553 static /*const*/ struct file_operations i810_audio_fops = {
2554         .owner          = THIS_MODULE,
2555         .llseek         = no_llseek,
2556         .read           = i810_read,
2557         .write          = i810_write,
2558         .poll           = i810_poll,
2559         .ioctl          = i810_ioctl,
2560         .mmap           = i810_mmap,
2561         .open           = i810_open,
2562         .release        = i810_release,
2563 };
2564
2565 /* Write AC97 codec registers */
2566
2567 static u16 i810_ac97_get_mmio(struct ac97_codec *dev, u8 reg)
2568 {
2569         struct i810_card *card = dev->private_data;
2570         int count = 100;
2571         u16 reg_set = IO_REG_OFF(dev) | (reg&0x7f);
2572         
2573         while(count-- && (readb(card->iobase_mmio + CAS) & 1)) 
2574                 udelay(1);
2575         
2576 #ifdef DEBUG_MMIO
2577         {
2578                 u16 ans = readw(card->ac97base_mmio + reg_set);
2579                 printk(KERN_DEBUG "i810_audio: ac97_get_mmio(%d) -> 0x%04X\n", ((int) reg_set) & 0xffff, (u32) ans);
2580                 return ans;
2581         }
2582 #else
2583         return readw(card->ac97base_mmio + reg_set);
2584 #endif
2585 }
2586
2587 static u16 i810_ac97_get_io(struct ac97_codec *dev, u8 reg)
2588 {
2589         struct i810_card *card = dev->private_data;
2590         int count = 100;
2591         u16 reg_set = IO_REG_OFF(dev) | (reg&0x7f);
2592         
2593         while(count-- && (I810_IOREADB(card, CAS) & 1)) 
2594                 udelay(1);
2595         
2596         return inw(card->ac97base + reg_set);
2597 }
2598
2599 static void i810_ac97_set_mmio(struct ac97_codec *dev, u8 reg, u16 data)
2600 {
2601         struct i810_card *card = dev->private_data;
2602         int count = 100;
2603         u16 reg_set = IO_REG_OFF(dev) | (reg&0x7f);
2604         
2605         while(count-- && (readb(card->iobase_mmio + CAS) & 1)) 
2606                 udelay(1);
2607         
2608         writew(data, card->ac97base_mmio + reg_set);
2609
2610 #ifdef DEBUG_MMIO
2611         printk(KERN_DEBUG "i810_audio: ac97_set_mmio(0x%04X, %d)\n", (u32) data, ((int) reg_set) & 0xffff);
2612 #endif
2613 }
2614
2615 static void i810_ac97_set_io(struct ac97_codec *dev, u8 reg, u16 data)
2616 {
2617         struct i810_card *card = dev->private_data;
2618         int count = 100;
2619         u16 reg_set = IO_REG_OFF(dev) | (reg&0x7f);
2620         
2621         while(count-- && (I810_IOREADB(card, CAS) & 1)) 
2622                 udelay(1);
2623         
2624         outw(data, card->ac97base + reg_set);
2625 }
2626
2627 static u16 i810_ac97_get(struct ac97_codec *dev, u8 reg)
2628 {
2629         struct i810_card *card = dev->private_data;
2630         u16 ret;
2631         
2632         spin_lock(&card->ac97_lock);
2633         if (card->use_mmio) {
2634                 ret = i810_ac97_get_mmio(dev, reg);
2635         }
2636         else {
2637                 ret = i810_ac97_get_io(dev, reg);
2638         }
2639         spin_unlock(&card->ac97_lock);
2640         
2641         return ret;
2642 }
2643
2644 static void i810_ac97_set(struct ac97_codec *dev, u8 reg, u16 data)
2645 {
2646         struct i810_card *card = dev->private_data;
2647         
2648         spin_lock(&card->ac97_lock);
2649         if (card->use_mmio) {
2650                 i810_ac97_set_mmio(dev, reg, data);
2651         }
2652         else {
2653                 i810_ac97_set_io(dev, reg, data);
2654         }
2655         spin_unlock(&card->ac97_lock);
2656 }
2657
2658
2659 /* OSS /dev/mixer file operation methods */
2660
2661 static int i810_open_mixdev(struct inode *inode, struct file *file)
2662 {
2663         int i;
2664         int minor = iminor(inode);
2665         struct i810_card *card = devs;
2666
2667         for (card = devs; card != NULL; card = card->next) {
2668                 /*
2669                  * If we are initializing and then fail, card could go
2670                  * away unuexpectedly while we are in the for() loop.
2671                  * So, check for card on each iteration before we check
2672                  * for card->initializing to avoid a possible oops.
2673                  * This usually only matters for times when the driver is
2674                  * autoloaded by kmod.
2675                  */
2676                 for (i = 0; i < 50 && card && card->initializing; i++) {
2677                         set_current_state(TASK_UNINTERRUPTIBLE);
2678                         schedule_timeout(HZ/20);
2679                 }
2680                 for (i = 0; i < NR_AC97 && card && !card->initializing; i++) 
2681                         if (card->ac97_codec[i] != NULL &&
2682                             card->ac97_codec[i]->dev_mixer == minor) {
2683                                 file->private_data = card->ac97_codec[i];
2684                                 return nonseekable_open(inode, file);
2685                         }
2686         }
2687         return -ENODEV;
2688 }
2689
2690 static int i810_ioctl_mixdev(struct inode *inode, struct file *file, unsigned int cmd,
2691                                 unsigned long arg)
2692 {
2693         struct ac97_codec *codec = (struct ac97_codec *)file->private_data;
2694
2695         return codec->mixer_ioctl(codec, cmd, arg);
2696 }
2697
2698 static /*const*/ struct file_operations i810_mixer_fops = {
2699         .owner          = THIS_MODULE,
2700         .llseek         = no_llseek,
2701         .ioctl          = i810_ioctl_mixdev,
2702         .open           = i810_open_mixdev,
2703 };
2704
2705 /* AC97 codec initialisation.  These small functions exist so we don't
2706    duplicate code between module init and apm resume */
2707
2708 static inline int i810_ac97_exists(struct i810_card *card, int ac97_number)
2709 {
2710         u32 reg = I810_IOREADL(card, GLOB_STA);
2711         switch (ac97_number) {
2712         case 0:
2713                 return reg & (1<<8);
2714         case 1: 
2715                 return reg & (1<<9);
2716         case 2:
2717                 return reg & (1<<28);
2718         }
2719         return 0;
2720 }
2721
2722 static inline int i810_ac97_enable_variable_rate(struct ac97_codec *codec)
2723 {
2724         i810_ac97_set(codec, AC97_EXTENDED_STATUS, 9);
2725         i810_ac97_set(codec,AC97_EXTENDED_STATUS,
2726                       i810_ac97_get(codec, AC97_EXTENDED_STATUS)|0xE800);
2727         
2728         return (i810_ac97_get(codec, AC97_EXTENDED_STATUS)&1);
2729 }
2730
2731
2732 static int i810_ac97_probe_and_powerup(struct i810_card *card,struct ac97_codec *codec)
2733 {
2734         /* Returns 0 on failure */
2735         int i;
2736
2737         if (ac97_probe_codec(codec) == 0) return 0;
2738         
2739         /* power it all up */
2740         i810_ac97_set(codec, AC97_POWER_CONTROL,
2741                       i810_ac97_get(codec, AC97_POWER_CONTROL) & ~0x7f00);
2742
2743         /* wait for analog ready */
2744         for (i=100; i && ((i810_ac97_get(codec, AC97_POWER_CONTROL) & 0xf) != 0xf); i--)
2745         {
2746                 set_current_state(TASK_UNINTERRUPTIBLE);
2747                 schedule_timeout(HZ/20);
2748         } 
2749         return i;
2750 }
2751
2752 static int is_new_ich(u16 pci_id)
2753 {
2754         switch (pci_id) {
2755         case PCI_DEVICE_ID_INTEL_82801DB_5:
2756         case PCI_DEVICE_ID_INTEL_82801EB_5:
2757         case PCI_DEVICE_ID_INTEL_ESB_5:
2758         case PCI_DEVICE_ID_INTEL_ICH6_18:
2759                 return 1;
2760         default:
2761                 break;
2762         }
2763
2764         return 0;
2765 }
2766
2767 static inline int ich_use_mmio(struct i810_card *card)
2768 {
2769         return is_new_ich(card->pci_id) && card->use_mmio;
2770 }
2771
2772 /**
2773  *      i810_ac97_power_up_bus  -       bring up AC97 link
2774  *      @card : ICH audio device to power up
2775  *
2776  *      Bring up the ACLink AC97 codec bus
2777  */
2778  
2779 static int i810_ac97_power_up_bus(struct i810_card *card)
2780 {       
2781         u32 reg = I810_IOREADL(card, GLOB_CNT);
2782         int i;
2783         int primary_codec_id = 0;
2784
2785         if((reg&2)==0)  /* Cold required */
2786                 reg|=2;
2787         else
2788                 reg|=4; /* Warm */
2789                 
2790         reg&=~8;        /* ACLink on */
2791         
2792         /* At this point we deassert AC_RESET # */
2793         I810_IOWRITEL(reg , card, GLOB_CNT);
2794
2795         /* We must now allow time for the Codec initialisation.
2796            600mS is the specified time */
2797                 
2798         for(i=0;i<10;i++)
2799         {
2800                 if((I810_IOREADL(card, GLOB_CNT)&4)==0)
2801                         break;
2802
2803                 set_current_state(TASK_UNINTERRUPTIBLE);
2804                 schedule_timeout(HZ/20);
2805         }
2806         if(i==10)
2807         {
2808                 printk(KERN_ERR "i810_audio: AC'97 reset failed.\n");
2809                 return 0;
2810         }
2811
2812         set_current_state(TASK_UNINTERRUPTIBLE);
2813         schedule_timeout(HZ/2);
2814
2815         /*
2816          *      See if the primary codec comes ready. This must happen
2817          *      before we start doing DMA stuff
2818          */     
2819         /* see i810_ac97_init for the next 10 lines (jsaw) */
2820         if (card->use_mmio)
2821                 readw(card->ac97base_mmio);
2822         else
2823                 inw(card->ac97base);
2824         if (ich_use_mmio(card)) {
2825                 primary_codec_id = (int) readl(card->iobase_mmio + SDM) & 0x3;
2826                 printk(KERN_INFO "i810_audio: Primary codec has ID %d\n",
2827                        primary_codec_id);
2828         }
2829
2830         if(! i810_ac97_exists(card, primary_codec_id))
2831         {
2832                 printk(KERN_INFO "i810_audio: Codec not ready.. wait.. ");
2833                 set_current_state(TASK_UNINTERRUPTIBLE);
2834                 schedule_timeout(HZ);   /* actually 600mS by the spec */
2835
2836                 if(i810_ac97_exists(card, primary_codec_id))
2837                         printk("OK\n");
2838                 else 
2839                         printk("no response.\n");
2840         }
2841         if (card->use_mmio)
2842                 readw(card->ac97base_mmio);
2843         else
2844                 inw(card->ac97base);
2845         return 1;
2846 }
2847
2848 static int __devinit i810_ac97_init(struct i810_card *card)
2849 {
2850         int num_ac97 = 0;
2851         int ac97_id;
2852         int total_channels = 0;
2853         int nr_ac97_max = card_cap[card->pci_id_internal].nr_ac97;
2854         struct ac97_codec *codec;
2855         u16 eid;
2856         u32 reg;
2857
2858         if(!i810_ac97_power_up_bus(card)) return 0;
2859
2860         /* Number of channels supported */
2861         /* What about the codec?  Just because the ICH supports */
2862         /* multiple channels doesn't mean the codec does.       */
2863         /* we'll have to modify this in the codec section below */
2864         /* to reflect what the codec has.                       */
2865         /* ICH and ICH0 only support 2 channels so don't bother */
2866         /* to check....                                         */
2867
2868         card->channels = 2;
2869         reg = I810_IOREADL(card, GLOB_STA);
2870         if ( reg & 0x0200000 )
2871                 card->channels = 6;
2872         else if ( reg & 0x0100000 )
2873                 card->channels = 4;
2874         printk(KERN_INFO "i810_audio: Audio Controller supports %d channels.\n", card->channels);
2875         printk(KERN_INFO "i810_audio: Defaulting to base 2 channel mode.\n");
2876         reg = I810_IOREADL(card, GLOB_CNT);
2877         I810_IOWRITEL(reg & 0xffcfffff, card, GLOB_CNT);
2878                 
2879         for (num_ac97 = 0; num_ac97 < NR_AC97; num_ac97++) 
2880                 card->ac97_codec[num_ac97] = NULL;
2881
2882         /*@FIXME I don't know, if I'm playing to safe here... (jsaw) */
2883         if ((nr_ac97_max > 2) && !card->use_mmio) nr_ac97_max = 2;
2884
2885         for (num_ac97 = 0; num_ac97 < nr_ac97_max; num_ac97++) {
2886                 /* codec reset */
2887                 printk(KERN_INFO "i810_audio: Resetting connection %d\n", num_ac97);
2888                 if (card->use_mmio)
2889                         readw(card->ac97base_mmio + 0x80*num_ac97);
2890                 else
2891                         inw(card->ac97base + 0x80*num_ac97);
2892
2893                 /* If we have the SDATA_IN Map Register, as on ICH4, we
2894                    do not loop thru all possible codec IDs but thru all 
2895                    possible IO channels. Bit 0:1 of SDM then holds the 
2896                    last codec ID spoken to. 
2897                 */
2898                 if (ich_use_mmio(card)) {
2899                         ac97_id = (int) readl(card->iobase_mmio + SDM) & 0x3;
2900                         printk(KERN_INFO "i810_audio: Connection %d with codec id %d\n",
2901                                num_ac97, ac97_id);
2902                 }
2903                 else {
2904                         ac97_id = num_ac97;
2905                 }
2906
2907                 /* The ICH programmer's reference says you should   */
2908                 /* check the ready status before probing. So we chk */
2909                 /*   What do we do if it's not ready?  Wait and try */
2910                 /*   again, or abort?                               */
2911                 if (!i810_ac97_exists(card, ac97_id)) {
2912                         if(num_ac97 == 0)
2913                                 printk(KERN_ERR "i810_audio: Primary codec not ready.\n");
2914                 }
2915                 
2916                 if ((codec = ac97_alloc_codec()) == NULL)
2917                         return -ENOMEM;
2918
2919                 /* initialize some basic codec information, other fields will be filled
2920                    in ac97_probe_codec */
2921                 codec->private_data = card;
2922                 codec->id = ac97_id;
2923                 card->ac97_id_map[ac97_id] = num_ac97 * 0x80;
2924
2925                 if (card->use_mmio) {   
2926                         codec->codec_read = i810_ac97_get_mmio;
2927                         codec->codec_write = i810_ac97_set_mmio;
2928                 }
2929                 else {
2930                         codec->codec_read = i810_ac97_get_io;
2931                         codec->codec_write = i810_ac97_set_io;
2932                 }
2933         
2934                 if(!i810_ac97_probe_and_powerup(card,codec)) {
2935                         printk(KERN_ERR "i810_audio: timed out waiting for codec %d analog ready.\n", ac97_id);
2936                         ac97_release_codec(codec);
2937                         break;  /* it didn't work */
2938                 }
2939                 /* Store state information about S/PDIF transmitter */
2940                 card->ac97_status = 0;
2941                 
2942                 /* Don't attempt to get eid until powerup is complete */
2943                 eid = i810_ac97_get(codec, AC97_EXTENDED_ID);
2944
2945                 if(eid==0xFFFF)
2946                 {
2947                         printk(KERN_WARNING "i810_audio: no codec attached ?\n");
2948                         ac97_release_codec(codec);
2949                         break;
2950                 }
2951                 
2952                 /* Check for an AC97 1.0 soft modem (ID1) */
2953                 
2954                 if(codec->modem)
2955                 {
2956                         printk(KERN_WARNING "i810_audio: codec %d is a softmodem - skipping.\n", ac97_id);
2957                         ac97_release_codec(codec);
2958                         continue;
2959                 }
2960                 
2961                 card->ac97_features = eid;
2962
2963                 /* Now check the codec for useful features to make up for
2964                    the dumbness of the 810 hardware engine */
2965
2966                 if(!(eid&0x0001))
2967                         printk(KERN_WARNING "i810_audio: only 48Khz playback available.\n");
2968                 else
2969                 {
2970                         if(!i810_ac97_enable_variable_rate(codec)) {
2971                                 printk(KERN_WARNING "i810_audio: Codec refused to allow VRA, using 48Khz only.\n");
2972                                 card->ac97_features&=~1;
2973                         }                       
2974                 }
2975                 
2976                 /* Turn on the amplifier */
2977
2978                 codec->codec_write(codec, AC97_POWER_CONTROL, 
2979                          codec->codec_read(codec, AC97_POWER_CONTROL) & ~0x8000);
2980                                 
2981                 /* Determine how many channels the codec(s) support   */
2982                 /*   - The primary codec always supports 2            */
2983                 /*   - If the codec supports AMAP, surround DACs will */
2984                 /*     automaticlly get assigned to slots.            */
2985                 /*     * Check for surround DACs and increment if     */
2986                 /*       found.                                       */
2987                 /*   - Else check if the codec is revision 2.2        */
2988                 /*     * If surround DACs exist, assign them to slots */
2989                 /*       and increment channel count.                 */
2990
2991                 /* All of this only applies to ICH2 and above. ICH    */
2992                 /* and ICH0 only support 2 channels.  ICH2 will only  */
2993                 /* support multiple codecs in a "split audio" config. */
2994                 /* as described above.                                */
2995
2996                 /* TODO: Remove all the debugging messages!           */
2997
2998                 if((eid & 0xc000) == 0) /* primary codec */
2999                         total_channels += 2; 
3000
3001                 if(eid & 0x200) { /* GOOD, AMAP support */
3002                         if (eid & 0x0080) /* L/R Surround channels */
3003                                 total_channels += 2;
3004                         if (eid & 0x0140) /* LFE and Center channels */
3005                                 total_channels += 2;
3006                         printk("i810_audio: AC'97 codec %d supports AMAP, total channels = %d\n", ac97_id, total_channels);
3007                 } else if (eid & 0x0400) {  /* this only works on 2.2 compliant codecs */
3008                         eid &= 0xffcf;
3009                         if((eid & 0xc000) != 0) {
3010                                 switch ( total_channels ) {
3011                                         case 2:
3012                                                 /* Set dsa1, dsa0 to 01 */
3013                                                 eid |= 0x0010;
3014                                                 break;
3015                                         case 4:
3016                                                 /* Set dsa1, dsa0 to 10 */
3017                                                 eid |= 0x0020;
3018                                                 break;
3019                                         case 6:
3020                                                 /* Set dsa1, dsa0 to 11 */
3021                                                 eid |= 0x0030;
3022                                                 break;
3023                                 }
3024                                 total_channels += 2;
3025                         }
3026                         i810_ac97_set(codec, AC97_EXTENDED_ID, eid);
3027                         eid = i810_ac97_get(codec, AC97_EXTENDED_ID);
3028                         printk("i810_audio: AC'97 codec %d, new EID value = 0x%04x\n", ac97_id, eid);
3029                         if (eid & 0x0080) /* L/R Surround channels */
3030                                 total_channels += 2;
3031                         if (eid & 0x0140) /* LFE and Center channels */
3032                                 total_channels += 2;
3033                         printk("i810_audio: AC'97 codec %d, DAC map configured, total channels = %d\n", ac97_id, total_channels);
3034                 } else {
3035                         printk("i810_audio: AC'97 codec %d Unable to map surround DAC's (or DAC's not present), total channels = %d\n", ac97_id, total_channels);
3036                 }
3037
3038                 if ((codec->dev_mixer = register_sound_mixer(&i810_mixer_fops, -1)) < 0) {
3039                         printk(KERN_ERR "i810_audio: couldn't register mixer!\n");
3040                         ac97_release_codec(codec);
3041                         break;
3042                 }
3043
3044                 card->ac97_codec[num_ac97] = codec;
3045         }
3046
3047         /* pick the minimum of channels supported by ICHx or codec(s) */
3048         card->channels = (card->channels > total_channels)?total_channels:card->channels;
3049
3050         return num_ac97;
3051 }
3052
3053 static void __devinit i810_configure_clocking (void)
3054 {
3055         struct i810_card *card;
3056         struct i810_state *state;
3057         struct dmabuf *dmabuf;
3058         unsigned int i, offset, new_offset;
3059         unsigned long flags;
3060
3061         card = devs;
3062         /* We could try to set the clocking for multiple cards, but can you even have
3063          * more than one i810 in a machine?  Besides, clocking is global, so unless
3064          * someone actually thinks more than one i810 in a machine is possible and
3065          * decides to rewrite that little bit, setting the rate for more than one card
3066          * is a waste of time.
3067          */
3068         if(card != NULL) {
3069                 state = card->states[0] = (struct i810_state *)
3070                                         kmalloc(sizeof(struct i810_state), GFP_KERNEL);
3071                 if (state == NULL)
3072                         return;
3073                 memset(state, 0, sizeof(struct i810_state));
3074                 dmabuf = &state->dmabuf;
3075
3076                 dmabuf->write_channel = card->alloc_pcm_channel(card);
3077                 state->virt = 0;
3078                 state->card = card;
3079                 state->magic = I810_STATE_MAGIC;
3080                 init_waitqueue_head(&dmabuf->wait);
3081                 init_MUTEX(&state->open_sem);
3082                 dmabuf->fmt = I810_FMT_STEREO | I810_FMT_16BIT;
3083                 dmabuf->trigger = PCM_ENABLE_OUTPUT;
3084                 i810_set_spdif_output(state, -1, 0);
3085                 i810_set_dac_channels(state, 2);
3086                 i810_set_dac_rate(state, 48000);
3087                 if(prog_dmabuf(state, 0) != 0) {
3088                         goto config_out_nodmabuf;
3089                 }
3090                 if(dmabuf->dmasize < 16384) {
3091                         goto config_out;
3092                 }
3093                 dmabuf->count = dmabuf->dmasize;
3094                 CIV_TO_LVI(card, dmabuf->write_channel->port, -1);
3095                 local_irq_save(flags);
3096                 start_dac(state);
3097                 offset = i810_get_dma_addr(state, 0);
3098                 mdelay(50);
3099                 new_offset = i810_get_dma_addr(state, 0);
3100                 stop_dac(state);
3101                 local_irq_restore(flags);
3102                 i = new_offset - offset;
3103 #ifdef DEBUG_INTERRUPTS
3104                 printk("i810_audio: %d bytes in 50 milliseconds\n", i);
3105 #endif
3106                 if(i == 0)
3107                         goto config_out;
3108                 i = i / 4 * 20;
3109                 if (i > 48500 || i < 47500) {
3110                         clocking = clocking * clocking / i;
3111                         printk("i810_audio: setting clocking to %d\n", clocking);
3112                 }
3113 config_out:
3114                 dealloc_dmabuf(state);
3115 config_out_nodmabuf:
3116                 state->card->free_pcm_channel(state->card,state->dmabuf.write_channel->num);
3117                 kfree(state);
3118                 card->states[0] = NULL;
3119         }
3120 }
3121
3122 /* install the driver, we do not allocate hardware channel nor DMA buffer now, they are defered 
3123    until "ACCESS" time (in prog_dmabuf called by open/read/write/ioctl/mmap) */
3124    
3125 static int __devinit i810_probe(struct pci_dev *pci_dev, const struct pci_device_id *pci_id)
3126 {
3127         struct i810_card *card;
3128
3129         if (pci_enable_device(pci_dev))
3130                 return -EIO;
3131
3132         if (pci_set_dma_mask(pci_dev, I810_DMA_MASK)) {
3133                 printk(KERN_ERR "i810_audio: architecture does not support"
3134                        " 32bit PCI busmaster DMA\n");
3135                 return -ENODEV;
3136         }
3137         
3138         if ((card = kmalloc(sizeof(struct i810_card), GFP_KERNEL)) == NULL) {
3139                 printk(KERN_ERR "i810_audio: out of memory\n");
3140                 return -ENOMEM;
3141         }
3142         memset(card, 0, sizeof(*card));
3143
3144         card->initializing = 1;
3145         card->pci_dev = pci_dev;
3146         card->pci_id = pci_id->device;
3147         card->ac97base = pci_resource_start (pci_dev, 0);
3148         card->iobase = pci_resource_start (pci_dev, 1);
3149
3150         if (!(card->ac97base) || !(card->iobase)) {
3151                 card->ac97base = 0;
3152                 card->iobase = 0;
3153         }
3154
3155         /* if chipset could have mmio capability, check it */ 
3156         if (card_cap[pci_id->driver_data].flags & CAP_MMIO) {
3157                 card->ac97base_mmio_phys = pci_resource_start (pci_dev, 2);
3158                 card->iobase_mmio_phys = pci_resource_start (pci_dev, 3);
3159
3160                 if ((card->ac97base_mmio_phys) && (card->iobase_mmio_phys)) {
3161                         card->use_mmio = 1;
3162                 }
3163                 else {
3164                         card->ac97base_mmio_phys = 0;
3165                         card->iobase_mmio_phys = 0;
3166                 }
3167         }
3168
3169         if (!(card->use_mmio) && (!(card->iobase) || !(card->ac97base))) {
3170                 printk(KERN_ERR "i810_audio: No I/O resources available.\n");
3171                 goto out_mem;
3172         }
3173
3174         card->irq = pci_dev->irq;
3175         card->next = devs;
3176         card->magic = I810_CARD_MAGIC;
3177 #ifdef CONFIG_PM
3178         card->pm_suspended=0;
3179 #endif
3180         spin_lock_init(&card->lock);
3181         spin_lock_init(&card->ac97_lock);
3182         devs = card;
3183
3184         pci_set_master(pci_dev);
3185
3186         printk(KERN_INFO "i810: %s found at IO 0x%04lx and 0x%04lx, "
3187                "MEM 0x%04lx and 0x%04lx, IRQ %d\n",
3188                card_names[pci_id->driver_data], 
3189                card->iobase, card->ac97base, 
3190                card->ac97base_mmio_phys, card->iobase_mmio_phys,
3191                card->irq);
3192
3193         card->alloc_pcm_channel = i810_alloc_pcm_channel;
3194         card->alloc_rec_pcm_channel = i810_alloc_rec_pcm_channel;
3195         card->alloc_rec_mic_channel = i810_alloc_rec_mic_channel;
3196         card->free_pcm_channel = i810_free_pcm_channel;
3197
3198         if ((card->channel = pci_alloc_consistent(pci_dev,
3199             sizeof(struct i810_channel)*NR_HW_CH, &card->chandma)) == NULL) {
3200                 printk(KERN_ERR "i810: cannot allocate channel DMA memory\n");
3201                 goto out_mem;
3202         }
3203
3204         { /* We may dispose of this altogether some time soon, so... */
3205                 struct i810_channel *cp = card->channel;
3206
3207                 cp[0].offset = 0;
3208                 cp[0].port = 0x00;
3209                 cp[0].num = 0;
3210                 cp[1].offset = 0;
3211                 cp[1].port = 0x10;
3212                 cp[1].num = 1;
3213                 cp[2].offset = 0;
3214                 cp[2].port = 0x20;
3215                 cp[2].num = 2;
3216         }
3217
3218         /* claim our iospace and irq */
3219         request_region(card->iobase, 64, card_names[pci_id->driver_data]);
3220         request_region(card->ac97base, 256, card_names[pci_id->driver_data]);
3221
3222         if (request_irq(card->irq, &i810_interrupt, SA_SHIRQ,
3223                         card_names[pci_id->driver_data], card)) {
3224                 printk(KERN_ERR "i810_audio: unable to allocate irq %d\n", card->irq);
3225                 goto out_pio;
3226         }
3227
3228         if (card->use_mmio) {
3229                 if (request_mem_region(card->ac97base_mmio_phys, 512, "ich_audio MMBAR")) {
3230                         if ((card->ac97base_mmio = ioremap(card->ac97base_mmio_phys, 512))) { /*@FIXME can ioremap fail? don't know (jsaw) */
3231                                 if (request_mem_region(card->iobase_mmio_phys, 256, "ich_audio MBBAR")) {
3232                                         if ((card->iobase_mmio = ioremap(card->iobase_mmio_phys, 256))) {
3233                                                 printk(KERN_INFO "i810: %s mmio at 0x%04lx and 0x%04lx\n",
3234                                                        card_names[pci_id->driver_data], 
3235                                                        (unsigned long) card->ac97base_mmio, 
3236                                                        (unsigned long) card->iobase_mmio); 
3237                                         }
3238                                         else {
3239                                                 iounmap(card->ac97base_mmio);
3240                                                 release_mem_region(card->ac97base_mmio_phys, 512);
3241                                                 release_mem_region(card->iobase_mmio_phys, 512);
3242                                                 card->use_mmio = 0;
3243                                         }
3244                                 }
3245                                 else {
3246                                         iounmap(card->ac97base_mmio);
3247                                         release_mem_region(card->ac97base_mmio_phys, 512);
3248                                         card->use_mmio = 0;
3249                                 }
3250                         }
3251                 }
3252                 else {
3253                         card->use_mmio = 0;
3254                 }
3255         }
3256
3257         /* initialize AC97 codec and register /dev/mixer */
3258         if (i810_ac97_init(card) <= 0) {
3259                 free_irq(card->irq, card);
3260                 goto out_iospace;
3261         }
3262         pci_set_drvdata(pci_dev, card);
3263
3264         if(clocking == 0) {
3265                 clocking = 48000;
3266                 i810_configure_clocking();
3267         }
3268
3269         /* register /dev/dsp */
3270         if ((card->dev_audio = register_sound_dsp(&i810_audio_fops, -1)) < 0) {
3271                 int i;
3272                 printk(KERN_ERR "i810_audio: couldn't register DSP device!\n");
3273                 free_irq(card->irq, card);
3274                 for (i = 0; i < NR_AC97; i++)
3275                 if (card->ac97_codec[i] != NULL) {
3276                         unregister_sound_mixer(card->ac97_codec[i]->dev_mixer);
3277                         ac97_release_codec(card->ac97_codec[i]);
3278                 }
3279                 goto out_iospace;
3280         }
3281
3282         card->initializing = 0;
3283         return 0;
3284
3285 out_iospace:
3286         if (card->use_mmio) {
3287                 iounmap(card->ac97base_mmio);
3288                 iounmap(card->iobase_mmio);
3289                 release_mem_region(card->ac97base_mmio_phys, 512);
3290                 release_mem_region(card->iobase_mmio_phys, 256);
3291         }
3292 out_pio:        
3293         release_region(card->iobase, 64);
3294         release_region(card->ac97base, 256);
3295         pci_free_consistent(pci_dev, sizeof(struct i810_channel)*NR_HW_CH,
3296             card->channel, card->chandma);
3297 out_mem:
3298         kfree(card);
3299         return -ENODEV;
3300 }
3301
3302 static void __devexit i810_remove(struct pci_dev *pci_dev)
3303 {
3304         int i;
3305         struct i810_card *card = pci_get_drvdata(pci_dev);
3306         /* free hardware resources */
3307         free_irq(card->irq, devs);
3308         release_region(card->iobase, 64);
3309         release_region(card->ac97base, 256);
3310         pci_free_consistent(pci_dev, sizeof(struct i810_channel)*NR_HW_CH,
3311                             card->channel, card->chandma);
3312         if (card->use_mmio) {
3313                 iounmap(card->ac97base_mmio);
3314                 iounmap(card->iobase_mmio);
3315                 release_mem_region(card->ac97base_mmio_phys, 512);
3316                 release_mem_region(card->iobase_mmio_phys, 256);
3317         }
3318
3319         /* unregister audio devices */
3320         for (i = 0; i < NR_AC97; i++)
3321                 if (card->ac97_codec[i] != NULL) {
3322                         unregister_sound_mixer(card->ac97_codec[i]->dev_mixer);
3323                         ac97_release_codec(card->ac97_codec[i]);
3324                         card->ac97_codec[i] = NULL;
3325                 }
3326         unregister_sound_dsp(card->dev_audio);
3327         kfree(card);
3328 }
3329
3330 #ifdef CONFIG_PM
3331 static int i810_pm_suspend(struct pci_dev *dev, u32 pm_state)
3332 {
3333         struct i810_card *card = pci_get_drvdata(dev);
3334         struct i810_state *state;
3335         unsigned long flags;
3336         struct dmabuf *dmabuf;
3337         int i,num_ac97;
3338 #ifdef DEBUG
3339         printk("i810_audio: i810_pm_suspend called\n");
3340 #endif
3341         if(!card) return 0;
3342         spin_lock_irqsave(&card->lock, flags);
3343         card->pm_suspended=1;
3344         for(i=0;i<NR_HW_CH;i++) {
3345                 state = card->states[i];
3346                 if(!state) continue;
3347                 /* this happens only if there are open files */
3348                 dmabuf = &state->dmabuf;
3349                 if(dmabuf->enable & DAC_RUNNING ||
3350                    (dmabuf->count && (dmabuf->trigger & PCM_ENABLE_OUTPUT))) {
3351                         state->pm_saved_dac_rate=dmabuf->rate;
3352                         stop_dac(state);
3353                 } else {
3354                         state->pm_saved_dac_rate=0;
3355                 }
3356                 if(dmabuf->enable & ADC_RUNNING) {
3357                         state->pm_saved_adc_rate=dmabuf->rate;  
3358                         stop_adc(state);
3359                 } else {
3360                         state->pm_saved_adc_rate=0;
3361                 }
3362                 dmabuf->ready = 0;
3363                 dmabuf->swptr = dmabuf->hwptr = 0;
3364                 dmabuf->count = dmabuf->total_bytes = 0;
3365         }
3366
3367         spin_unlock_irqrestore(&card->lock, flags);
3368
3369         /* save mixer settings */
3370         for (num_ac97 = 0; num_ac97 < NR_AC97; num_ac97++) {
3371                 struct ac97_codec *codec = card->ac97_codec[num_ac97];
3372                 if(!codec) continue;
3373                 for(i=0;i< SOUND_MIXER_NRDEVICES ;i++) {
3374                         if((supported_mixer(codec,i)) &&
3375                            (codec->read_mixer)) {
3376                                 card->pm_saved_mixer_settings[i][num_ac97]=
3377                                         codec->read_mixer(codec,i);
3378                         }
3379                 }
3380         }
3381         pci_save_state(dev,card->pm_save_state); /* XXX do we need this? */
3382         pci_disable_device(dev); /* disable busmastering */
3383         pci_set_power_state(dev,3); /* Zzz. */
3384
3385         return 0;
3386 }
3387
3388
3389 static int i810_pm_resume(struct pci_dev *dev)
3390 {
3391         int num_ac97,i=0;
3392         struct i810_card *card=pci_get_drvdata(dev);
3393         pci_enable_device(dev);
3394         pci_restore_state (dev,card->pm_save_state);
3395
3396         /* observation of a toshiba portege 3440ct suggests that the 
3397            hardware has to be more or less completely reinitialized from
3398            scratch after an apm suspend.  Works For Me.   -dan */
3399
3400         i810_ac97_power_up_bus(card);
3401
3402         for (num_ac97 = 0; num_ac97 < NR_AC97; num_ac97++) {
3403                 struct ac97_codec *codec = card->ac97_codec[num_ac97];
3404                 /* check they haven't stolen the hardware while we were
3405                    away */
3406                 if(!codec || !i810_ac97_exists(card,num_ac97)) {
3407                         if(num_ac97) continue;
3408                         else BUG();
3409                 }
3410                 if(!i810_ac97_probe_and_powerup(card,codec)) BUG();
3411                 
3412                 if((card->ac97_features&0x0001)) {
3413                         /* at probe time we found we could do variable
3414                            rates, but APM suspend has made it forget
3415                            its magical powers */
3416                         if(!i810_ac97_enable_variable_rate(codec)) BUG();
3417                 }
3418                 /* we lost our mixer settings, so restore them */
3419                 for(i=0;i< SOUND_MIXER_NRDEVICES ;i++) {
3420                         if(supported_mixer(codec,i)){
3421                                 int val=card->
3422                                         pm_saved_mixer_settings[i][num_ac97];
3423                                 codec->mixer_state[i]=val;
3424                                 codec->write_mixer(codec,i,
3425                                                    (val  & 0xff) ,
3426                                                    ((val >> 8)  & 0xff) );
3427                         }
3428                 }
3429         }
3430
3431         /* we need to restore the sample rate from whatever it was */
3432         for(i=0;i<NR_HW_CH;i++) {
3433                 struct i810_state * state=card->states[i];
3434                 if(state) {
3435                         if(state->pm_saved_adc_rate)
3436                                 i810_set_adc_rate(state,state->pm_saved_adc_rate);
3437                         if(state->pm_saved_dac_rate)
3438                                 i810_set_dac_rate(state,state->pm_saved_dac_rate);
3439                 }
3440         }
3441
3442         
3443         card->pm_suspended = 0;
3444
3445         /* any processes that were reading/writing during the suspend
3446            probably ended up here */
3447         for(i=0;i<NR_HW_CH;i++) {
3448                 struct i810_state *state = card->states[i];
3449                 if(state) wake_up(&state->dmabuf.wait);
3450         }
3451
3452         return 0;
3453 }       
3454 #endif /* CONFIG_PM */
3455
3456 MODULE_AUTHOR("");
3457 MODULE_DESCRIPTION("Intel 810 audio support");
3458 MODULE_LICENSE("GPL");
3459 MODULE_PARM(ftsodell, "i");
3460 MODULE_PARM(clocking, "i");
3461 MODULE_PARM(strict_clocking, "i");
3462 MODULE_PARM(spdif_locked, "i");
3463
3464 #define I810_MODULE_NAME "intel810_audio"
3465
3466 static struct pci_driver i810_pci_driver = {
3467         .name           = I810_MODULE_NAME,
3468         .id_table       = i810_pci_tbl,
3469         .probe          = i810_probe,
3470         .remove         = __devexit_p(i810_remove),
3471 #ifdef CONFIG_PM
3472         .suspend        = i810_pm_suspend,
3473         .resume         = i810_pm_resume,
3474 #endif /* CONFIG_PM */
3475 };
3476
3477
3478 static int __init i810_init_module (void)
3479 {
3480         printk(KERN_INFO "Intel 810 + AC97 Audio, version "
3481                DRIVER_VERSION ", " __TIME__ " " __DATE__ "\n");
3482
3483         if (!pci_register_driver(&i810_pci_driver)) {
3484                 pci_unregister_driver(&i810_pci_driver);
3485                 return -ENODEV;
3486         }
3487         if(ftsodell != 0) {
3488                 printk("i810_audio: ftsodell is now a deprecated option.\n");
3489         }
3490         if(spdif_locked > 0 ) {
3491                 if(spdif_locked == 32000 || spdif_locked == 44100 || spdif_locked == 48000) {
3492                         printk("i810_audio: Enabling S/PDIF at sample rate %dHz.\n", spdif_locked);
3493                 } else {
3494                         printk("i810_audio: S/PDIF can only be locked to 32000, 44100, or 48000Hz.\n");
3495                         spdif_locked = 0;
3496                 }
3497         }
3498         
3499         return 0;
3500 }
3501
3502 static void __exit i810_cleanup_module (void)
3503 {
3504         pci_unregister_driver(&i810_pci_driver);
3505 }
3506
3507 module_init(i810_init_module);
3508 module_exit(i810_cleanup_module);
3509
3510 /*
3511 Local Variables:
3512 c-basic-offset: 8
3513 End:
3514 */