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