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