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