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