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