v2.4.8 -> v2.4.8.1
[opensuse:kernel.git] / drivers / sound / trident.c
1 /*
2  *
3  *      Trident 4D-Wave/SiS 7018/ALi 5451 OSS driver for Linux 2.2.x
4  *
5  *      Driver: Alan Cox <alan@redhat.com>
6  *
7  *  Built from:
8  *      Low level code: <audio@tridentmicro.com> from ALSA
9  *      Framework: Thomas Sailer <sailer@ife.ee.ethz.ch>
10  *      Extended by: Zach Brown <zab@redhat.com>  
11  *
12  *  Hacked up by:
13  *      Aaron Holtzman <aholtzma@ess.engr.uvic.ca>
14  *      Ollie Lho <ollie@sis.com.tw> SiS 7018 Audio Core Support
15  *      Ching-Ling Lee <cling-li@ali.com.tw> ALi 5451 Audio Core Support 
16  *      Matt Wu <mattwu@acersoftech.com.cn> ALi 5451 Audio Core Support
17  *
18  *
19  *      This program is free software; you can redistribute it and/or modify
20  *      it under the terms of the GNU General Public License as published by
21  *      the Free Software Foundation; either version 2 of the License, or
22  *      (at your option) any later version.
23  *
24  *      This program is distributed in the hope that it will be useful,
25  *      but WITHOUT ANY WARRANTY; without even the implied warranty of
26  *      MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
27  *      GNU General Public License for more details.
28  *
29  *      You should have received a copy of the GNU General Public License
30  *      along with this program; if not, write to the Free Software
31  *      Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
32  *
33  *  History
34  *  v0.14.9b
35  *      Switch to static inline not extern inline (gcc 3)
36  *  v0.14.9a
37  *      Aug 6 2001 Alan Cox
38  *      0.14.9 crashed on rmmod due to a timer/bh left running. Simplified
39  *      the existing logic (the BH doesnt help as ac97 is lock_irqsave)
40  *      and used del_timer_sync to clean up
41  *      Fixed a problem where the ALi change broke my generic card
42  *  v0.14.9
43  *      Jul 10 2001 Matt Wu
44  *      Add H/W Volume Control
45  *  v0.14.8a
46  *      July 7 2001 Alan Cox
47  *      Moved Matt Wu's ac97 register cache into the card structure
48  *  v0.14.8
49  *      Apr 30 2001 Matt Wu
50  *      Set EBUF1 and EBUF2 to still mode
51  *      Add dc97/ac97 reset function
52  *      Fix power management: ali_restore_regs
53  *  unreleased 
54  *      Mar 09 2001 Matt Wu
55  *      Add cache for ac97 access
56  *  v0.14.7
57  *      Feb 06 2001 Matt Wu
58  *      Fix ac97 initialization
59  *      Fix bug: an extra tail will be played when playing
60  *      Jan 05 2001 Matt Wu
61  *      Implement multi-channels and S/PDIF in support for ALi 1535+
62  *  v0.14.6 
63  *      Nov 1 2000 Ching-Ling Lee
64  *      Fix the bug of memory leak when swithing 5.1-channels to 2 channels.
65  *      Add lock protection into dynamic changing format of data.
66  *      Oct 18 2000 Ching-Ling Lee
67  *      5.1-channels support for ALi
68  *      June 28 2000 Ching-Ling Lee
69  *      S/PDIF out/in(playback/record) support for ALi 1535+, using /proc to be selected by user
70  *      Simple Power Management support for ALi
71  *  v0.14.5 May 23 2000 Ollie Lho
72  *      Misc bug fix from the Net
73  *  v0.14.4 May 20 2000 Aaron Holtzman
74  *      Fix kfree'd memory access in release
75  *      Fix race in open while looking for a free virtual channel slot
76  *      remove open_wait wq (which appears to be unused)
77  *  v0.14.3 May 10 2000 Ollie Lho
78  *      fixed a small bug in trident_update_ptr, xmms 1.0.1 no longer uses 100% CPU
79  *  v0.14.2 Mar 29 2000 Ching-Ling Lee
80  *      Add clear to silence advance in trident_update_ptr 
81  *      fix invalid data of the end of the sound
82  *  v0.14.1 Mar 24 2000 Ching-Ling Lee
83  *      ALi 5451 support added, playback and recording O.K.
84  *      ALi 5451 originally developed and structured based on sonicvibes, and
85  *      suggested to merge into this file by Alan Cox.
86  *  v0.14 Mar 15 2000 Ollie Lho
87  *      5.1 channel output support with channel binding. What's the Matrix ?
88  *  v0.13.1 Mar 10 2000 Ollie Lho
89  *      few minor bugs on dual codec support, needs more testing
90  *  v0.13 Mar 03 2000 Ollie Lho
91  *      new pci_* for 2.4 kernel, back ported to 2.2
92  *  v0.12 Feb 23 2000 Ollie Lho
93  *      Preliminary Recording support
94  *  v0.11.2 Feb 19 2000 Ollie Lho
95  *      removed incomplete full-dulplex support
96  *  v0.11.1 Jan 28 2000 Ollie Lho
97  *      small bug in setting sample rate for 4d-nx (reported by Aaron)
98  *  v0.11 Jan 27 2000 Ollie Lho
99  *      DMA bug, scheduler latency, second try
100  *  v0.10 Jan 24 2000 Ollie Lho
101  *      DMA bug fixed, found kernel scheduling problem
102  *  v0.09 Jan 20 2000 Ollie Lho
103  *      Clean up of channel register access routine (prepare for channel binding)
104  *  v0.08 Jan 14 2000 Ollie Lho
105  *      Isolation of AC97 codec code
106  *  v0.07 Jan 13 2000 Ollie Lho
107  *      Get rid of ugly old low level access routines (e.g. CHRegs.lp****)
108  *  v0.06 Jan 11 2000 Ollie Lho
109  *      Preliminary support for dual (more ?) AC97 codecs
110  *  v0.05 Jan 08 2000 Luca Montecchiani <m.luca@iname.com>
111  *      adapt to 2.3.x new __setup/__init call
112  *  v0.04 Dec 31 1999 Ollie Lho
113  *      Multiple Open, using Middle Loop Interrupt to smooth playback
114  *  v0.03 Dec 24 1999 Ollie Lho
115  *      mem leak in prog_dmabuf and dealloc_dmabuf removed
116  *  v0.02 Dec 15 1999 Ollie Lho
117  *      SiS 7018 support added, playback O.K.
118  *  v0.01 Alan Cox et. al.
119  *      Initial Release in kernel 2.3.30, does not work
120  * 
121  *  ToDo
122  *      Clean up of low level channel register access code. (done)
123  *      Fix the bug on dma buffer management in update_ptr, read/write, drain_dac (done)
124  *      Dual AC97 codecs support (done)
125  *      Recording support (done)
126  *      Mmap support
127  *      "Channel Binding" ioctl extension (done)
128  *      new pci device driver interface for 2.4 kernel (done)
129  *
130  *      Lock order (high->low)
131  *              lock    -       hardware lock
132  *              open_sem -      guard opens
133  *              sem     -       guard dmabuf, write re-entry etc
134  */
135
136 #include <linux/config.h>
137 #include <linux/module.h>
138 #include <linux/version.h>
139 #include <linux/string.h>
140 #include <linux/ctype.h>
141 #include <linux/ioport.h>
142 #include <linux/sched.h>
143 #include <linux/delay.h>
144 #include <linux/sound.h>
145 #include <linux/slab.h>
146 #include <linux/soundcard.h>
147 #include <linux/pci.h>
148 #include <asm/io.h>
149 #include <asm/dma.h>
150 #include <linux/init.h>
151 #include <linux/poll.h>
152 #include <linux/spinlock.h>
153 #include <linux/smp_lock.h>
154 #include <linux/ac97_codec.h>
155 #include <linux/wrapper.h>
156 #include <asm/uaccess.h>
157 #include <asm/hardirq.h>
158 #include <linux/bitops.h>
159 #include <linux/proc_fs.h>
160 #include <linux/interrupt.h>
161
162 #if defined CONFIG_ALPHA_NAUTILUS || CONFIG_ALPHA_GENERIC
163 #include <asm/hwrpb.h>
164 #endif
165
166 #include "trident.h"
167
168 #include <linux/pm.h>
169
170 #define DRIVER_VERSION "0.14.9b"
171
172 /* magic numbers to protect our data structures */
173 #define TRIDENT_CARD_MAGIC      0x5072696E /* "Prin" */
174 #define TRIDENT_STATE_MAGIC     0x63657373 /* "cess" */
175
176 #define TRIDENT_DMA_MASK        0x3fffffff /* DMA buffer mask for pci_alloc_consist */
177
178 #define NR_HW_CH                32
179
180 /* maxinum nuber of AC97 codecs connected, AC97 2.0 defined 4, but 7018 and 4D-NX only
181    have 2 SDATA_IN lines (currently) */
182 #define NR_AC97         2       
183
184 /* minor number of /dev/swmodem (temporary, experimental) */
185 #define SND_DEV_SWMODEM 7
186
187 static const unsigned ali_multi_channels_5_1[] = { /*ALI_SURR_LEFT_CHANNEL, ALI_SURR_RIGHT_CHANNEL,*/ ALI_CENTER_CHANNEL, ALI_LEF_CHANNEL, ALI_SURR_LEFT_CHANNEL, ALI_SURR_RIGHT_CHANNEL};
188
189 static const unsigned sample_size[] = { 1, 2, 2, 4 };
190 static const unsigned sample_shift[] = { 0, 1, 1, 2 };
191
192 static const char invalid_magic[] = KERN_CRIT "trident: invalid magic value in %s\n";
193
194 enum {
195         TRIDENT_4D_DX = 0,
196         TRIDENT_4D_NX,
197         SIS_7018,
198         ALI_5451
199 };
200
201 static char * card_names[] = {
202         "Trident 4DWave DX",
203         "Trident 4DWave NX",
204         "SiS 7018 PCI Audio",
205         "ALi Audio Accelerator"
206 };
207
208 static struct pci_device_id trident_pci_tbl [] __devinitdata = {
209         {PCI_VENDOR_ID_TRIDENT, PCI_DEVICE_ID_TRIDENT_4DWAVE_DX,
210          PCI_ANY_ID, PCI_ANY_ID, 0, 0, TRIDENT_4D_DX},
211         {PCI_VENDOR_ID_TRIDENT, PCI_DEVICE_ID_TRIDENT_4DWAVE_NX,
212          PCI_ANY_ID, PCI_ANY_ID, 0, 0, TRIDENT_4D_NX},
213         {PCI_VENDOR_ID_SI, PCI_DEVICE_ID_SI_7018,
214          PCI_ANY_ID, PCI_ANY_ID, 0, 0, SIS_7018},
215         {PCI_VENDOR_ID_ALI, PCI_DEVICE_ID_ALI_5451,
216          PCI_ANY_ID, PCI_ANY_ID, 0, 0, ALI_5451},
217         {0,}
218 };
219
220 MODULE_DEVICE_TABLE (pci, trident_pci_tbl);
221
222 /* "software" or virtual channel, an instance of opened /dev/dsp */
223 struct trident_state {
224         unsigned int magic;
225         struct trident_card *card;      /* Card info */
226
227         /* file mode */
228         mode_t open_mode;
229
230         /* virtual channel number */
231         int virt;
232
233         struct dmabuf {
234                 /* wave sample stuff */
235                 unsigned int rate;
236                 unsigned char fmt, enable;
237
238                 /* hardware channel */
239                 struct trident_channel *channel;
240
241                 /* OSS buffer management stuff */
242                 void *rawbuf;
243                 dma_addr_t dma_handle;
244                 unsigned buforder;
245                 unsigned numfrag;
246                 unsigned fragshift;
247
248                 /* our buffer acts like a circular ring */
249                 unsigned hwptr;         /* where dma last started, updated by update_ptr */
250                 unsigned swptr;         /* where driver last clear/filled, updated by read/write */
251                 int count;              /* bytes to be comsumed or been generated by dma machine */
252                 unsigned total_bytes;   /* total bytes dmaed by hardware */
253
254                 unsigned error;         /* number of over/underruns */
255                 wait_queue_head_t wait; /* put process on wait queue when no more space in buffer */
256
257                 /* redundant, but makes calculations easier */
258                 unsigned fragsize;
259                 unsigned dmasize;
260                 unsigned fragsamples;
261
262                 /* OSS stuff */
263                 unsigned mapped:1;
264                 unsigned ready:1;
265                 unsigned endcleared:1;
266                 unsigned update_flag;
267                 unsigned ossfragshift;
268                 int ossmaxfrags;
269                 unsigned subdivision;
270                 
271         } dmabuf;
272
273         /* 5.1channels */       
274         struct trident_state *other_states[4];
275         int multi_channels_adjust_count;
276         unsigned chans_num;
277         unsigned fmt_flag:1;
278         /* Guard against mmap/write/read races */
279         struct semaphore sem;
280
281 };
282
283 /* hardware channels */
284 struct trident_channel {
285         int  num;       /* channel number */
286         u32 lba;        /* Loop Begine Address, where dma buffer starts */
287         u32 eso;        /* End Sample Offset, wehre dma buffer ends (in the unit of samples) */
288         u32 delta;      /* delta value, sample rate / 48k for playback, 48k/sample rate for recording */
289         u16 attribute;  /* control where PCM data go and come  */
290         u16 fm_vol;
291         u32 control;    /* signed/unsigned, 8/16 bits, mono/stereo */
292 };
293
294 struct trident_pcm_bank_address {
295         u32 start;
296         u32 stop;
297         u32 aint;
298         u32 aint_en;
299 };
300 static struct trident_pcm_bank_address bank_a_addrs =
301 {
302         T4D_START_A,
303         T4D_STOP_A,
304         T4D_AINT_A,
305         T4D_AINTEN_A
306 };
307 static struct trident_pcm_bank_address bank_b_addrs =
308 {
309         T4D_START_B,
310         T4D_STOP_B,
311         T4D_AINT_B,
312         T4D_AINTEN_B
313 };
314 struct trident_pcm_bank {
315         /* register addresses to control bank operations */
316         struct trident_pcm_bank_address *addresses;
317         /* each bank has 32 channels */
318         u32 bitmap; /* channel allocation bitmap */
319         struct trident_channel channels[32];
320 };
321
322 struct trident_card {
323         unsigned int magic;
324
325         /* We keep trident cards in a linked list */
326         struct trident_card *next;
327
328         /* single open lock mechanism, only used for recording */
329         struct semaphore open_sem;
330
331         /* The trident has a certain amount of cross channel interaction
332            so we use a single per card lock */
333         spinlock_t lock;
334         
335         /* PCI device stuff */
336         struct pci_dev * pci_dev;
337         u16 pci_id;
338         u8 revision;
339
340         /* soundcore stuff */
341         int dev_audio;
342
343         /* structures for abstraction of hardware facilities, codecs, banks and channels*/
344         struct ac97_codec *ac97_codec[NR_AC97];
345         struct trident_pcm_bank banks[NR_BANKS];
346         struct trident_state *states[NR_HW_CH];
347
348         /* hardware resources */
349         unsigned long iobase;
350         u32 irq;
351         
352         /* Function support */
353         struct trident_channel *(*alloc_pcm_channel)(struct trident_card *);
354         struct trident_channel *(*alloc_rec_pcm_channel)(struct trident_card *);
355         void (*free_pcm_channel)(struct trident_card *, unsigned int chan);
356         void (*address_interrupt)(struct trident_card *);
357         
358         /* Added by Matt Wu 01-05-2001 for spdif in */
359         int multi_channel_use_count;
360         int rec_channel_use_count;
361         u16 mixer_regs[64][NR_AC97];    /* Made card local by Alan */
362         int mixer_regs_ready;
363
364         /* Added for hardware volume control */
365         int hwvolctl;
366         struct timer_list timer;
367 };
368
369 /* table to map from CHANNELMASK to channel attribute for SiS 7018 */
370 static u16 mask2attr [] =
371 {
372         PCM_LR, PCM_LR, SURR_LR, CENTER_LFE,
373         HSET, MIC, MODEM_LINE1, MODEM_LINE2,
374         I2S_LR, SPDIF_LR
375 };
376 /* table to map from channel attribute to CHANNELMASK for SiS 7018 */
377 static int attr2mask [] = {
378         DSP_BIND_MODEM1, DSP_BIND_MODEM2, DSP_BIND_FRONT, DSP_BIND_HANDSET,
379         DSP_BIND_I2S, DSP_BIND_CENTER_LFE, DSP_BIND_SURR, DSP_BIND_SPDIF
380 };
381
382 /* Added by Matt Wu 01-05-2001 for spdif in */
383 static int ali_close_multi_channels(void);
384 static void ali_delay(struct trident_card *card,int interval);
385 static void ali_detect_spdif_rate(struct trident_card *card);
386
387 static void ali_ac97_write(struct ac97_codec *codec, u8 reg, u16 val);
388 static u16 ali_ac97_read(struct ac97_codec *codec, u8 reg);
389
390 static struct trident_card *devs;
391
392 static void trident_ac97_set(struct ac97_codec *codec, u8 reg, u16 val);
393 static u16 trident_ac97_get(struct ac97_codec *codec, u8 reg);
394
395 static int trident_open_mixdev(struct inode *inode, struct file *file);
396 static int trident_ioctl_mixdev(struct inode *inode, struct file *file, unsigned int cmd,
397                                 unsigned long arg);
398
399 static void ali_ac97_set(struct trident_card *card, int secondary, u8 reg, u16 val);
400 static u16 ali_ac97_get(struct trident_card *card, int secondary, u8 reg);
401 static void ali_set_spdif_out_rate(struct trident_card *card, unsigned int rate);
402 static void ali_enable_special_channel(struct trident_state *stat);
403 static struct trident_channel *ali_alloc_rec_pcm_channel(struct trident_card *card);
404 static struct trident_channel *ali_alloc_pcm_channel(struct trident_card *card);
405 static void ali_restore_regs(struct trident_card *card);
406 static void ali_save_regs(struct trident_card *card);
407 static int trident_suspend(struct pci_dev *dev, u32 unused);
408 static int trident_resume(struct pci_dev *dev);
409 static void ali_free_pcm_channel(struct trident_card *card, unsigned int channel);
410 static int ali_setup_multi_channels(struct trident_card *card, int chan_nums);
411 static unsigned int ali_get_spdif_in_rate(struct trident_card *card);
412 static void ali_setup_spdif_in(struct trident_card *card);
413 static void ali_disable_spdif_in(struct trident_card *card);
414 static void ali_disable_special_channel(struct trident_card *card, int ch);
415 static void ali_setup_spdif_out(struct trident_card *card, int flag);
416 static int ali_write_5_1(struct trident_state *state, const char *buffer,int cnt_for_multi_channel, unsigned int *copy_count, unsigned int *state_cnt);
417 static int ali_allocate_other_states_resources(struct trident_state *state, int chan_nums);
418 static void ali_free_other_states_resources(struct trident_state *state);
419
420
421 /* save registers for ALi Power Management */
422 static struct ali_saved_registers {
423         unsigned long global_regs[ALI_GLOBAL_REGS];
424         unsigned long channel_regs[ALI_CHANNELS][ALI_CHANNEL_REGS];
425         unsigned mixer_regs[ALI_MIXER_REGS];
426 } ali_registers;
427
428 #define seek_offset(dma_ptr, buffer, cnt, offset, copy_count)   (dma_ptr) += (offset);  \
429                                                         (buffer) += (offset);   \
430                                                         (cnt) -= (offset);      \
431                                                         (copy_count) += (offset);
432
433 #define lock_set_fmt(state)     {spin_lock_irqsave(&state->card->lock, flags);                  \
434                                 if (state->fmt_flag) {                                          \
435                                         spin_unlock_irqrestore(&state->card->lock, flags);      \
436                                         return -EFAULT;                                         \
437                                 }                                                               \
438                                 state->fmt_flag = 1;                                            \
439                                 spin_unlock_irqrestore(&state->card->lock, flags);}
440                                 
441 #define unlock_set_fmt(state)   {spin_lock_irqsave(&state->card->lock, flags);          \
442                                 state->fmt_flag = 0;                                    \
443                                 spin_unlock_irqrestore(&state->card->lock, flags);}
444
445 static int trident_enable_loop_interrupts(struct trident_card * card)
446 {
447         u32 global_control;
448
449         global_control = inl(TRID_REG(card, T4D_LFO_GC_CIR));
450
451         switch (card->pci_id)
452         {
453         case PCI_DEVICE_ID_SI_7018:
454                 global_control |= (ENDLP_IE | MIDLP_IE| BANK_B_EN);
455                 break;
456         case PCI_DEVICE_ID_ALI_5451:
457         case PCI_DEVICE_ID_TRIDENT_4DWAVE_DX:
458         case PCI_DEVICE_ID_TRIDENT_4DWAVE_NX:
459                 global_control |= (ENDLP_IE | MIDLP_IE);
460                 break;
461         default:
462                 return FALSE;
463         }
464
465         outl(global_control, TRID_REG(card, T4D_LFO_GC_CIR));
466
467 #ifdef DEBUG
468         printk("trident: Enable Loop Interrupts, globctl = 0x%08X\n",
469                global_control);
470 #endif
471         return (TRUE);
472 }
473
474 static int trident_disable_loop_interrupts(struct trident_card * card)
475 {
476         u32 global_control;
477
478         global_control = inl(TRID_REG(card, T4D_LFO_GC_CIR));
479         global_control &= ~(ENDLP_IE | MIDLP_IE);
480         outl(global_control, TRID_REG(card, T4D_LFO_GC_CIR));
481
482 #ifdef DEBUG
483         printk("trident: Disabled Loop Interrupts, globctl = 0x%08X\n",
484                global_control);
485 #endif
486         return (TRUE);
487 }
488
489 static void trident_enable_voice_irq(struct trident_card * card, unsigned int channel)
490 {
491         unsigned int mask = 1 << (channel & 0x1f);
492         struct trident_pcm_bank *bank = &card->banks[channel >> 5];
493         u32 reg, addr = bank->addresses->aint_en;
494
495         reg = inl(TRID_REG(card, addr));
496         reg |= mask;
497         outl(reg, TRID_REG(card, addr));
498
499 #ifdef DEBUG
500         reg = inl(TRID_REG(card, T4D_AINTEN_B));
501         printk("trident: enabled IRQ on channel %d, AINTEN_B = 0x%08x\n",
502                channel, reg);
503 #endif
504 }
505
506 static void trident_disable_voice_irq(struct trident_card * card, unsigned int channel)
507 {
508         unsigned int mask = 1 << (channel & 0x1f);
509         struct trident_pcm_bank *bank = &card->banks[channel >> 5];
510         u32 reg, addr = bank->addresses->aint_en;
511         
512         reg = inl(TRID_REG(card, addr));
513         reg &= ~mask;
514         outl(reg, TRID_REG(card, addr));
515         
516         /* Ack the channel in case the interrupt was set before we disable it. */
517         outl(mask, TRID_REG(card, bank->addresses->aint));
518
519 #ifdef DEBUG
520         reg = inl(TRID_REG(card, T4D_AINTEN_B));
521         printk("trident: disabled IRQ on channel %d, AINTEN_B = 0x%08x\n",
522                channel, reg);
523 #endif
524 }
525
526 static void trident_start_voice(struct trident_card * card, unsigned int channel)
527 {
528         unsigned int mask = 1 << (channel & 0x1f);
529         struct trident_pcm_bank *bank = &card->banks[channel >> 5];
530         u32 addr = bank->addresses->start;
531
532 #ifdef DEBUG
533         u32 reg;
534 #endif
535
536         outl(mask, TRID_REG(card, addr));
537
538 #ifdef DEBUG
539         reg = inl(TRID_REG(card, T4D_START_B));
540         printk("trident: start voice on channel %d, START_B  = 0x%08x\n",
541                channel, reg);
542 #endif
543 }
544
545 static void trident_stop_voice(struct trident_card * card, unsigned int channel)
546 {
547         unsigned int mask = 1 << (channel & 0x1f);
548         struct trident_pcm_bank *bank = &card->banks[channel >> 5];
549         u32 addr = bank->addresses->stop;
550
551 #ifdef DEBUG
552         u32 reg;
553 #endif
554
555         outl(mask, TRID_REG(card, addr));
556
557 #ifdef DEBUG
558         reg = inl(TRID_REG(card, T4D_STOP_B));
559         printk("trident: stop voice on channel %d,  STOP_B  = 0x%08x\n",
560                channel, reg);
561 #endif
562 }
563
564 static u32 trident_get_interrupt_mask (struct trident_card * card, unsigned int channel)
565 {
566         struct trident_pcm_bank *bank = &card->banks[channel];
567         u32 addr = bank->addresses->aint;
568         return inl(TRID_REG(card, addr));
569 }
570
571 static int trident_check_channel_interrupt(struct trident_card * card, unsigned int channel)
572 {
573         unsigned int mask = 1 << (channel & 0x1f);
574         u32 reg = trident_get_interrupt_mask (card, channel >> 5);
575
576 #ifdef DEBUG
577         if (reg & mask)
578                 printk("trident: channel %d has interrupt, AINT_B = 0x%08x\n",
579                        channel, reg);
580 #endif
581         return (reg & mask) ? TRUE : FALSE;
582 }
583
584 static void trident_ack_channel_interrupt(struct trident_card * card, unsigned int channel)
585 {
586         unsigned int mask = 1 << (channel & 0x1f);
587         struct trident_pcm_bank *bank = &card->banks[channel >> 5];
588         u32 reg, addr = bank->addresses->aint;
589
590         reg = inl(TRID_REG(card, addr));
591         reg &= mask;
592         outl(reg, TRID_REG(card, addr));
593
594 #ifdef DEBUG
595         reg = inl(TRID_REG(card, T4D_AINT_B));
596         printk("trident: Ack channel %d interrupt, AINT_B = 0x%08x\n",
597                channel, reg);
598 #endif
599 }
600
601 static struct trident_channel * trident_alloc_pcm_channel(struct trident_card *card)
602 {
603         struct trident_pcm_bank *bank;
604         int idx;
605
606         bank = &card->banks[BANK_B];
607
608         for (idx = 31; idx >= 0; idx--) {
609                 if (!(bank->bitmap & (1 << idx))) {
610                         struct trident_channel *channel = &bank->channels[idx];
611                         bank->bitmap |= 1 << idx;
612                         channel->num = idx + 32;
613                         return channel;
614                 }
615         }
616
617         /* no more free channels avaliable */
618         printk(KERN_ERR "trident: no more channels available on Bank B.\n");
619         return NULL;
620 }
621
622 static void trident_free_pcm_channel(struct trident_card *card, unsigned int channel)
623 {
624         int bank;
625
626         if (channel < 31 || channel > 63)
627                 return;
628
629         bank = channel >> 5;
630         channel = channel & 0x1f;
631
632         card->banks[bank].bitmap &= ~(1 << (channel));
633 }
634
635 /* called with spin lock held */
636
637 static int trident_load_channel_registers(struct trident_card *card, u32 *data, unsigned int channel)
638 {
639         int i;
640
641         if (channel > 63)
642                 return FALSE;
643
644         /* select hardware channel to write */
645         outb(channel, TRID_REG(card, T4D_LFO_GC_CIR));
646
647         /* Output the channel registers, but don't write register
648            three to an ALI chip. */
649         for (i = 0; i < CHANNEL_REGS; i++) {
650                 if (i == 3 && card->pci_id == PCI_DEVICE_ID_ALI_5451)
651                         continue;
652                 outl(data[i], TRID_REG(card, CHANNEL_START + 4*i));
653         }
654         if (card->pci_id == PCI_DEVICE_ID_ALI_5451) {
655                 outl(ALI_EMOD_Still, TRID_REG(card, ALI_EBUF1));
656                 outl(ALI_EMOD_Still, TRID_REG(card, ALI_EBUF2));
657         }
658         return TRUE;
659 }
660
661 /* called with spin lock held */
662 static int trident_write_voice_regs(struct trident_state *state)
663 {
664         unsigned int data[CHANNEL_REGS + 1];
665         struct trident_channel *channel;
666
667         channel = state->dmabuf.channel;
668
669         data[1] = channel->lba;
670         data[4] = channel->control;
671
672         switch (state->card->pci_id)
673         {
674         case PCI_DEVICE_ID_ALI_5451:
675                 data[0] = 0; /* Current Sample Offset */
676                 data[2] = (channel->eso << 16) | (channel->delta & 0xffff);
677                 data[3] = 0;
678                 break;  
679         case PCI_DEVICE_ID_SI_7018:
680                 data[0] = 0; /* Current Sample Offset */
681                 data[2] = (channel->eso << 16) | (channel->delta & 0xffff);
682                 data[3] = (channel->attribute << 16) | (channel->fm_vol & 0xffff);
683                 break;
684         case PCI_DEVICE_ID_TRIDENT_4DWAVE_DX:
685                 data[0] = 0; /* Current Sample Offset */
686                 data[2] = (channel->eso << 16) | (channel->delta & 0xffff);
687                 data[3] = channel->fm_vol & 0xffff;
688                 break;
689         case PCI_DEVICE_ID_TRIDENT_4DWAVE_NX:
690                 data[0] = (channel->delta << 24);
691                 data[2] = ((channel->delta << 16) & 0xff000000) | (channel->eso & 0x00ffffff);
692                 data[3] = channel->fm_vol & 0xffff;
693                 break;
694         default:
695                 return FALSE;
696         }
697
698         return trident_load_channel_registers(state->card, data, channel->num);
699 }
700
701 static int compute_rate_play(u32 rate)
702 {
703         int delta;
704         /* We special case 44100 and 8000 since rounding with the equation
705            does not give us an accurate enough value. For 11025 and 22050
706            the equation gives us the best answer. All other frequencies will
707            also use the equation. JDW */
708         if (rate == 44100)
709                 delta = 0xeb3;
710         else if (rate == 8000)
711                 delta = 0x2ab;
712         else if (rate == 48000)
713                 delta = 0x1000;
714         else
715                 delta = (((rate << 12) + rate) / 48000) & 0x0000ffff;
716         return delta;
717 }
718
719 static int compute_rate_rec(u32 rate)
720 {
721         int delta;
722
723         if (rate == 44100)
724                 delta = 0x116a;
725         else if (rate == 8000)
726                 delta = 0x6000;
727         else if (rate == 48000)
728                 delta = 0x1000;
729         else
730                 delta = ((48000 << 12) / rate) & 0x0000ffff;
731
732         return delta;
733 }
734 /* set playback sample rate */
735 static unsigned int trident_set_dac_rate(struct trident_state * state, unsigned int rate)
736 {       
737         struct dmabuf *dmabuf = &state->dmabuf;
738
739         if (rate > 48000)
740                 rate = 48000;
741         if (rate < 4000)
742                 rate = 4000;
743
744         dmabuf->rate = rate;
745         dmabuf->channel->delta = compute_rate_play(rate);
746
747         trident_write_voice_regs(state);
748
749 #ifdef DEBUG
750         printk("trident: called trident_set_dac_rate : rate = %d\n", rate);
751 #endif
752
753         return rate;
754 }
755
756 /* set recording sample rate */
757 static unsigned int trident_set_adc_rate(struct trident_state * state, unsigned int rate)
758 {
759         struct dmabuf *dmabuf = &state->dmabuf;
760
761         if (rate > 48000)
762                 rate = 48000;
763         if (rate < 4000)
764                 rate = 4000;
765
766         dmabuf->rate = rate;
767         dmabuf->channel->delta = compute_rate_rec(rate);
768
769         trident_write_voice_regs(state);
770
771 #ifdef DEBUG
772         printk("trident: called trident_set_adc_rate : rate = %d\n", rate);
773 #endif
774         return rate;
775 }
776
777 /* prepare channel attributes for playback */ 
778 static void trident_play_setup(struct trident_state *state)
779 {
780         struct dmabuf *dmabuf = &state->dmabuf;
781         struct trident_channel *channel = dmabuf->channel;
782
783         channel->lba = dmabuf->dma_handle;
784         channel->delta = compute_rate_play(dmabuf->rate);
785
786         channel->eso = dmabuf->dmasize >> sample_shift[dmabuf->fmt];
787         channel->eso -= 1;
788
789         if (state->card->pci_id != PCI_DEVICE_ID_SI_7018) {
790                 channel->attribute = 0;
791                 if (state->card->pci_id == PCI_DEVICE_ID_ALI_5451) {
792                         if ((channel->num == ALI_SPDIF_IN_CHANNEL) || (channel->num == ALI_PCM_IN_CHANNEL))
793                                 ali_disable_special_channel(state->card, channel->num);
794                         else if ((inl(TRID_REG(state->card, ALI_GLOBAL_CONTROL)) & ALI_SPDIF_OUT_CH_ENABLE) 
795                                                                 && (channel->num == ALI_SPDIF_OUT_CHANNEL))
796                         {
797                                 ali_set_spdif_out_rate(state->card, state->dmabuf.rate);
798                                 state->dmabuf.channel->delta = 0x1000;
799                         }
800                 }
801         }
802
803         channel->fm_vol = 0x0;
804         
805         channel->control = CHANNEL_LOOP;
806         if (dmabuf->fmt & TRIDENT_FMT_16BIT) {
807                 /* 16-bits */
808                 channel->control |= CHANNEL_16BITS;
809                 /* signed */
810                 channel->control |= CHANNEL_SIGNED;
811         }
812         if (dmabuf->fmt & TRIDENT_FMT_STEREO)
813                 /* stereo */
814                 channel->control |= CHANNEL_STEREO;
815 #ifdef DEBUG
816         printk("trident: trident_play_setup, LBA = 0x%08x, "
817                "Delat = 0x%08x, ESO = 0x%08x, Control = 0x%08x\n",
818                channel->lba, channel->delta, channel->eso, channel->control);
819 #endif
820         trident_write_voice_regs(state);
821 }
822
823 /* prepare channel attributes for recording */
824 static void trident_rec_setup(struct trident_state *state)
825 {
826         u16 w;
827         u8  bval;
828
829         struct trident_card *card = state->card;
830         struct dmabuf *dmabuf = &state->dmabuf;
831         struct trident_channel *channel = dmabuf->channel;
832         unsigned int rate;
833
834         /* Enable AC-97 ADC (capture) */
835         switch (card->pci_id) 
836         {
837         case PCI_DEVICE_ID_ALI_5451:
838                 ali_enable_special_channel(state);
839                 break;
840         case PCI_DEVICE_ID_SI_7018:
841                 /* for 7018, the ac97 is always in playback/record (duplex) mode */
842                 break;
843         case PCI_DEVICE_ID_TRIDENT_4DWAVE_DX:
844                 w = inb(TRID_REG(card, DX_ACR2_AC97_COM_STAT));
845                 outb(w | 0x48, TRID_REG(card, DX_ACR2_AC97_COM_STAT));
846                 /* enable and set record channel */
847                 outb(0x80 | channel->num, TRID_REG(card, T4D_REC_CH));
848                 break;
849         case PCI_DEVICE_ID_TRIDENT_4DWAVE_NX:
850                 w = inw(TRID_REG(card, T4D_MISCINT));
851                 outw(w | 0x1000, TRID_REG(card, T4D_MISCINT));
852                 /* enable and set record channel */
853                 outb(0x80 | channel->num, TRID_REG(card, T4D_REC_CH));
854                 break;
855         default:
856                 return;
857         }
858
859         channel->lba = dmabuf->dma_handle;
860         channel->delta = compute_rate_rec(dmabuf->rate);
861         if ((card->pci_id == PCI_DEVICE_ID_ALI_5451) && (channel->num == ALI_SPDIF_IN_CHANNEL)) {
862                 rate = ali_get_spdif_in_rate(card);
863                 if (rate == 0)
864                 {
865                         printk(KERN_WARNING "trident: ALi 5451 S/PDIF input setup error!\n");
866                         rate = 48000;
867                 }
868                 bval = inb(TRID_REG(card,ALI_SPDIF_CTRL));
869                 if (bval & 0x10)
870                 {
871                         outb(bval,TRID_REG(card,ALI_SPDIF_CTRL));
872                         printk(KERN_WARNING "trident: cleared ALi 5451 S/PDIF parity error flag.\n");
873                 }
874
875                 if (rate != 48000)
876                         channel->delta = ((rate << 12) / dmabuf->rate) & 0x0000ffff;
877         }
878         
879         channel->eso = dmabuf->dmasize >> sample_shift[dmabuf->fmt];
880         channel->eso -= 1;
881
882         if (state->card->pci_id != PCI_DEVICE_ID_SI_7018) {
883                 channel->attribute = 0;
884         }
885
886         channel->fm_vol = 0x0;
887         
888         channel->control = CHANNEL_LOOP;
889         if (dmabuf->fmt & TRIDENT_FMT_16BIT) {
890                 /* 16-bits */
891                 channel->control |= CHANNEL_16BITS;
892                 /* signed */
893                 channel->control |= CHANNEL_SIGNED;
894         }
895         if (dmabuf->fmt & TRIDENT_FMT_STEREO)
896                 /* stereo */
897                 channel->control |= CHANNEL_STEREO;
898 #ifdef DEBUG
899         printk("trident: trident_rec_setup, LBA = 0x%08x, "
900                "Delat = 0x%08x, ESO = 0x%08x, Control = 0x%08x\n",
901                channel->lba, channel->delta, channel->eso, channel->control);
902 #endif
903         trident_write_voice_regs(state);
904 }
905
906 /* get current playback/recording dma buffer pointer (byte offset from LBA),
907    called with spinlock held! */
908 static inline unsigned trident_get_dma_addr(struct trident_state *state)
909 {
910         struct dmabuf *dmabuf = &state->dmabuf;
911         u32 cso;
912
913         if (!dmabuf->enable)
914                 return 0;
915
916         outb(dmabuf->channel->num, TRID_REG(state->card, T4D_LFO_GC_CIR));
917
918         switch (state->card->pci_id) 
919         {
920         case PCI_DEVICE_ID_ALI_5451:
921         case PCI_DEVICE_ID_SI_7018:
922         case PCI_DEVICE_ID_TRIDENT_4DWAVE_DX:
923                 /* 16 bits ESO, CSO for 7018 and DX */
924                 cso = inw(TRID_REG(state->card, CH_DX_CSO_ALPHA_FMS + 2));
925                 break;
926         case PCI_DEVICE_ID_TRIDENT_4DWAVE_NX:
927                 /* 24 bits ESO, CSO for NX */
928                 cso = inl(TRID_REG(state->card, CH_NX_DELTA_CSO)) & 0x00ffffff;
929                 break;
930         default:
931                 return 0;
932         }
933
934 #ifdef DEBUG
935         printk("trident: trident_get_dma_addr: chip reported channel: %d, "
936                "cso = 0x%04x\n",
937                dmabuf->channel->num, cso);
938 #endif
939         /* ESO and CSO are in units of Samples, convert to byte offset */
940         cso <<= sample_shift[dmabuf->fmt];
941
942         return (cso % dmabuf->dmasize);
943 }
944
945 /* Stop recording (lock held) */
946 static inline void __stop_adc(struct trident_state *state)
947 {
948         struct dmabuf *dmabuf = &state->dmabuf;
949         unsigned int chan_num = dmabuf->channel->num;
950         struct trident_card *card = state->card;
951
952         dmabuf->enable &= ~ADC_RUNNING;
953         trident_stop_voice(card, chan_num);
954         trident_disable_voice_irq(card, chan_num);
955 }
956
957 static void stop_adc(struct trident_state *state)
958 {
959         struct trident_card *card = state->card;
960         unsigned long flags;
961
962         spin_lock_irqsave(&card->lock, flags);
963         __stop_adc(state);
964         spin_unlock_irqrestore(&card->lock, flags);
965 }
966
967 static void start_adc(struct trident_state *state)
968 {
969         struct dmabuf *dmabuf = &state->dmabuf;
970         unsigned int chan_num = dmabuf->channel->num;
971         struct trident_card *card = state->card;
972         unsigned long flags;
973
974         spin_lock_irqsave(&card->lock, flags);
975         if ((dmabuf->mapped || dmabuf->count < (signed)dmabuf->dmasize) && dmabuf->ready) {
976                 dmabuf->enable |= ADC_RUNNING;
977                 trident_enable_voice_irq(card, chan_num);
978                 trident_start_voice(card, chan_num);
979         }
980         spin_unlock_irqrestore(&card->lock, flags);
981 }
982
983 /* stop playback (lock held) */
984 static inline void __stop_dac(struct trident_state *state)
985 {
986         struct dmabuf *dmabuf = &state->dmabuf;
987         unsigned int chan_num = dmabuf->channel->num;
988         struct trident_card *card = state->card;
989
990         dmabuf->enable &= ~DAC_RUNNING;
991         trident_stop_voice(card, chan_num);
992         if (state->chans_num == 6) {
993                 trident_stop_voice(card, state->other_states[0]->dmabuf.channel->num);
994                 trident_stop_voice(card, state->other_states[1]->dmabuf.channel->num);
995                 trident_stop_voice(card, state->other_states[2]->dmabuf.channel->num);
996                 trident_stop_voice(card, state->other_states[3]->dmabuf.channel->num);
997         }
998         trident_disable_voice_irq(card, chan_num);
999 }
1000
1001 static void stop_dac(struct trident_state *state)
1002 {
1003         struct trident_card *card = state->card;
1004         unsigned long flags;
1005
1006         spin_lock_irqsave(&card->lock, flags);
1007         __stop_dac(state);
1008         spin_unlock_irqrestore(&card->lock, flags);
1009 }       
1010
1011 static void start_dac(struct trident_state *state)
1012 {
1013         struct dmabuf *dmabuf = &state->dmabuf;
1014         unsigned int chan_num = dmabuf->channel->num;
1015         struct trident_card *card = state->card;
1016         unsigned long flags;
1017
1018         spin_lock_irqsave(&card->lock, flags);
1019         if ((dmabuf->mapped || dmabuf->count > 0) && dmabuf->ready) {
1020                 dmabuf->enable |= DAC_RUNNING;
1021                 trident_enable_voice_irq(card, chan_num);
1022                 trident_start_voice(card, chan_num);
1023                 if (state->chans_num == 6) {
1024                         trident_start_voice(card, state->other_states[0]->dmabuf.channel->num);
1025                         trident_start_voice(card, state->other_states[1]->dmabuf.channel->num);
1026                         trident_start_voice(card, state->other_states[2]->dmabuf.channel->num);
1027                         trident_start_voice(card, state->other_states[3]->dmabuf.channel->num);
1028                 }
1029         }
1030         spin_unlock_irqrestore(&card->lock, flags);
1031 }
1032
1033 #define DMABUF_DEFAULTORDER (15-PAGE_SHIFT)
1034 #define DMABUF_MINORDER 1
1035
1036 /* allocate DMA buffer, playback and recording buffer should be allocated seperately */
1037 static int alloc_dmabuf(struct trident_state *state)
1038 {
1039         struct dmabuf *dmabuf = &state->dmabuf;
1040         void *rawbuf = NULL;
1041         int order;
1042         struct page *page, *pend;
1043
1044         /* alloc as big a chunk as we can, FIXME: is this necessary ?? */
1045         for (order = DMABUF_DEFAULTORDER; order >= DMABUF_MINORDER; order--)
1046                 if ((rawbuf = pci_alloc_consistent(state->card->pci_dev,
1047                                                    PAGE_SIZE << order,
1048                                                    &dmabuf->dma_handle)))
1049                         break;
1050         if (!rawbuf)
1051                 return -ENOMEM;
1052
1053 #ifdef DEBUG
1054         printk("trident: allocated %ld (order = %d) bytes at %p\n",
1055                PAGE_SIZE << order, order, rawbuf);
1056 #endif
1057
1058         dmabuf->ready  = dmabuf->mapped = 0;
1059         dmabuf->rawbuf = rawbuf;
1060         dmabuf->buforder = order;
1061         
1062         /* now mark the pages as reserved; otherwise remap_page_range doesn't do what we want */
1063         pend = virt_to_page(rawbuf + (PAGE_SIZE << order) - 1);
1064         for (page = virt_to_page(rawbuf); page <= pend; page++)
1065                 mem_map_reserve(page);
1066
1067         return 0;
1068 }
1069
1070 /* free DMA buffer */
1071 static void dealloc_dmabuf(struct trident_state *state)
1072 {
1073         struct dmabuf *dmabuf = &state->dmabuf;
1074         struct page *page, *pend;
1075
1076         if (dmabuf->rawbuf) {
1077                 /* undo marking the pages as reserved */
1078                 pend = virt_to_page(dmabuf->rawbuf + (PAGE_SIZE << dmabuf->buforder) - 1);
1079                 for (page = virt_to_page(dmabuf->rawbuf); page <= pend; page++)
1080                         mem_map_unreserve(page);
1081                 pci_free_consistent(state->card->pci_dev, PAGE_SIZE << dmabuf->buforder,
1082                                     dmabuf->rawbuf, dmabuf->dma_handle);
1083         }
1084         dmabuf->rawbuf = NULL;
1085         dmabuf->mapped = dmabuf->ready = 0;
1086 }
1087
1088 static int prog_dmabuf(struct trident_state *state, unsigned rec)
1089 {
1090         struct dmabuf *dmabuf = &state->dmabuf;
1091         unsigned bytepersec;
1092         struct trident_state *s = state;
1093         unsigned bufsize, dma_nums;
1094         unsigned long flags;
1095         int ret, i, order;
1096         struct page *page, *pend;
1097         
1098         lock_set_fmt(state);
1099         if (state->chans_num == 6)
1100                 dma_nums = 5;
1101         else    dma_nums = 1;
1102         
1103         for (i = 0; i < dma_nums; i++) {
1104                 if (i > 0) {
1105                         s = state->other_states[i - 1];                 
1106                         dmabuf = &s->dmabuf;
1107                         dmabuf->fmt = state->dmabuf.fmt;
1108                         dmabuf->rate = state->dmabuf.rate;
1109                 }
1110
1111                 spin_lock_irqsave(&s->card->lock, flags);
1112                 dmabuf->hwptr = dmabuf->swptr = dmabuf->total_bytes = 0;
1113                 dmabuf->count = dmabuf->error = 0;
1114                 spin_unlock_irqrestore(&s->card->lock, flags);
1115
1116                 /* allocate DMA buffer if not allocated yet */
1117                 if (!dmabuf->rawbuf) {
1118                         if (i == 0) {
1119                                 if ((ret = alloc_dmabuf(state))) {
1120                                         unlock_set_fmt(state);
1121                                         return ret;
1122                                 }
1123                         }
1124                         else {
1125                                 if ((order = state->dmabuf.buforder - 1) >= DMABUF_MINORDER) {
1126                                         dmabuf->rawbuf = pci_alloc_consistent(state->card->pci_dev,
1127                                                                               PAGE_SIZE << order,
1128                                                                               &dmabuf->dma_handle);
1129                                 }
1130                                 if (!dmabuf->rawbuf) {
1131                                         free_pages((unsigned long)state->dmabuf.rawbuf, state->dmabuf.buforder);
1132                                         state->dmabuf.rawbuf = NULL;
1133                                         i-=2;
1134                                         for (; i >= 0; i--) {
1135                                                 pci_free_consistent(state->card->pci_dev,
1136                                                                     PAGE_SIZE << state->other_states[i]->dmabuf.buforder,
1137                                                                     state->other_states[i]->dmabuf.rawbuf,
1138                                                                     state->other_states[i]->dmabuf.dma_handle);
1139                                         }
1140                                         unlock_set_fmt(state);
1141                                         return -ENOMEM;
1142                                 }
1143                                 dmabuf->ready  = dmabuf->mapped = 0;
1144                                 dmabuf->buforder = order;
1145                                 pend = virt_to_page(dmabuf->rawbuf + (PAGE_SIZE << order) - 1);
1146                                 for (page = virt_to_page(dmabuf->rawbuf); page <= pend; page++)
1147                                         mem_map_reserve(page);
1148                         }
1149                 }
1150                 /* FIXME: figure out all this OSS fragment stuff */
1151                 bytepersec = dmabuf->rate << sample_shift[dmabuf->fmt];
1152                 bufsize = PAGE_SIZE << dmabuf->buforder;
1153                 if (dmabuf->ossfragshift) {
1154                         if ((1000 << dmabuf->ossfragshift) < bytepersec)
1155                                 dmabuf->fragshift = ld2(bytepersec/1000);
1156                         else
1157                                 dmabuf->fragshift = dmabuf->ossfragshift;
1158                 } else {
1159                         /* lets hand out reasonable big ass buffers by default */
1160                         dmabuf->fragshift = (dmabuf->buforder + PAGE_SHIFT -2);
1161                 }
1162                 dmabuf->numfrag = bufsize >> dmabuf->fragshift;
1163                 while (dmabuf->numfrag < 4 && dmabuf->fragshift > 3) {
1164                         dmabuf->fragshift--;
1165                         dmabuf->numfrag = bufsize >> dmabuf->fragshift;
1166                 }
1167                 dmabuf->fragsize = 1 << dmabuf->fragshift;
1168                 if (dmabuf->ossmaxfrags >= 4 && dmabuf->ossmaxfrags < dmabuf->numfrag)
1169                         dmabuf->numfrag = dmabuf->ossmaxfrags;
1170                 dmabuf->fragsamples = dmabuf->fragsize >> sample_shift[dmabuf->fmt];
1171                 dmabuf->dmasize = dmabuf->numfrag << dmabuf->fragshift;
1172
1173                 memset(dmabuf->rawbuf, (dmabuf->fmt & TRIDENT_FMT_16BIT) ? 0 : 0x80,
1174                        dmabuf->dmasize);
1175
1176                 spin_lock_irqsave(&s->card->lock, flags);
1177                 if (rec) {
1178                         trident_rec_setup(s);
1179                 } else {
1180                         trident_play_setup(s);
1181                 }
1182                 spin_unlock_irqrestore(&s->card->lock, flags);
1183
1184                 /* set the ready flag for the dma buffer */
1185                 dmabuf->ready = 1;
1186
1187 #ifdef DEBUG
1188         printk("trident: prog_dmabuf(%d), sample rate = %d, format = %d, numfrag = %d, "
1189                "fragsize = %d dmasize = %d\n",
1190                dmabuf->channel->num, dmabuf->rate, dmabuf->fmt, dmabuf->numfrag,
1191                dmabuf->fragsize, dmabuf->dmasize);
1192 #endif
1193         }
1194         unlock_set_fmt(state);
1195         return 0;
1196 }
1197
1198 /* we are doing quantum mechanics here, the buffer can only be empty, half or full filled i.e.
1199    |------------|------------|   or   |xxxxxxxxxxxx|------------|   or   |xxxxxxxxxxxx|xxxxxxxxxxxx|
1200    but we almost always get this
1201    |xxxxxx------|------------|   or   |xxxxxxxxxxxx|xxxxx-------|
1202    so we have to clear the tail space to "silence"
1203    |xxxxxx000000|------------|   or   |xxxxxxxxxxxx|xxxxxx000000|
1204 */
1205 static void trident_clear_tail(struct trident_state *state)
1206 {
1207         struct dmabuf *dmabuf = &state->dmabuf;
1208         unsigned swptr;
1209         unsigned char silence = (dmabuf->fmt & TRIDENT_FMT_16BIT) ? 0 : 0x80;
1210         unsigned int len;
1211         unsigned long flags;
1212
1213         spin_lock_irqsave(&state->card->lock, flags);
1214         swptr = dmabuf->swptr;
1215         spin_unlock_irqrestore(&state->card->lock, flags);
1216
1217         if (swptr == 0 || swptr == dmabuf->dmasize / 2 || swptr == dmabuf->dmasize)
1218                 return;
1219
1220         if (swptr < dmabuf->dmasize/2)
1221                 len = dmabuf->dmasize/2 - swptr;
1222         else
1223                 len = dmabuf->dmasize - swptr;
1224
1225         memset(dmabuf->rawbuf + swptr, silence, len);
1226         if(state->card->pci_id != PCI_DEVICE_ID_ALI_5451)
1227         {
1228                 spin_lock_irqsave(&state->card->lock, flags);
1229                 dmabuf->swptr += len;
1230                 dmabuf->count += len;
1231                 spin_unlock_irqrestore(&state->card->lock, flags);
1232         }
1233
1234         /* restart the dma machine in case it is halted */
1235         start_dac(state);
1236 }
1237
1238 static int drain_dac(struct trident_state *state, int nonblock)
1239 {
1240         DECLARE_WAITQUEUE(wait, current);
1241         struct dmabuf *dmabuf = &state->dmabuf;
1242         unsigned long flags;
1243         unsigned long tmo;
1244         int count;
1245         unsigned long diff = 0;
1246
1247         if (dmabuf->mapped || !dmabuf->ready)
1248                 return 0;
1249
1250         add_wait_queue(&dmabuf->wait, &wait);
1251         for (;;) {
1252                 /* It seems that we have to set the current state to TASK_INTERRUPTIBLE
1253                    every time to make the process really go to sleep */
1254                 current->state = TASK_INTERRUPTIBLE;
1255
1256                 spin_lock_irqsave(&state->card->lock, flags);
1257                 count = dmabuf->count;
1258                 spin_unlock_irqrestore(&state->card->lock, flags);
1259
1260                 if (count <= 0)
1261                         break;
1262
1263                 if (signal_pending(current))
1264                         break;
1265
1266                 if (nonblock) {
1267                         remove_wait_queue(&dmabuf->wait, &wait);
1268                         current->state = TASK_RUNNING;
1269                         return -EBUSY;
1270                 }
1271
1272                 /* No matter how much data is left in the buffer, we have to wait until
1273                    CSO == ESO/2 or CSO == ESO when address engine interrupts */
1274                 if (state->card->pci_id == PCI_DEVICE_ID_ALI_5451)
1275                 {       
1276                         diff = dmabuf->swptr - trident_get_dma_addr(state) + dmabuf->dmasize ;
1277                         diff = diff % (dmabuf->dmasize);
1278                         tmo  = (diff * HZ) / dmabuf->rate;
1279                 }
1280                 else
1281                 {
1282                         tmo = (dmabuf->dmasize * HZ) / dmabuf->rate;
1283                 }
1284                 tmo >>= sample_shift[dmabuf->fmt];
1285                 if (!schedule_timeout(tmo ? tmo : 1) && tmo){
1286                         break;
1287                 }
1288         }
1289         remove_wait_queue(&dmabuf->wait, &wait);
1290         current->state = TASK_RUNNING;
1291         if (signal_pending(current))
1292                 return -ERESTARTSYS;
1293
1294         return 0;
1295 }
1296
1297 /* update buffer manangement pointers, especially, dmabuf->count and dmabuf->hwptr */
1298 static void trident_update_ptr(struct trident_state *state)
1299 {
1300         struct dmabuf *dmabuf = &state->dmabuf;
1301         unsigned hwptr, swptr;
1302         int clear_cnt = 0;
1303         int diff;
1304         unsigned char silence;
1305         unsigned half_dmasize;
1306
1307         /* update hardware pointer */
1308         hwptr = trident_get_dma_addr(state);
1309         diff = (dmabuf->dmasize + hwptr - dmabuf->hwptr) % dmabuf->dmasize;
1310         dmabuf->hwptr = hwptr;
1311         dmabuf->total_bytes += diff;
1312
1313         /* error handling and process wake up for ADC */
1314         if (dmabuf->enable == ADC_RUNNING) {
1315                 if (dmabuf->mapped) {
1316                         dmabuf->count -= diff;
1317                         if (dmabuf->count >= (signed)dmabuf->fragsize)
1318                                 wake_up(&dmabuf->wait);
1319                 } else {
1320                         dmabuf->count += diff;
1321
1322                         if (dmabuf->count < 0 || dmabuf->count > dmabuf->dmasize) {
1323                                 /* buffer underrun or buffer overrun, we have no way to recover
1324                                    it here, just stop the machine and let the process force hwptr
1325                                    and swptr to sync */
1326                                 __stop_adc(state);
1327                                 dmabuf->error++;
1328                         }
1329                         if (dmabuf->count < (signed)dmabuf->dmasize/2)
1330                                 wake_up(&dmabuf->wait);
1331                 }
1332         }
1333
1334         /* error handling and process wake up for DAC */
1335         if (dmabuf->enable == DAC_RUNNING) {
1336                 if (dmabuf->mapped) {
1337                         dmabuf->count += diff;
1338                         if (dmabuf->count >= (signed)dmabuf->fragsize)
1339                                 wake_up(&dmabuf->wait);
1340                 } else {
1341                         dmabuf->count -= diff;
1342
1343                         if (dmabuf->count < 0 || dmabuf->count > dmabuf->dmasize) {
1344                                 /* buffer underrun or buffer overrun, we have no way to recover
1345                                    it here, just stop the machine and let the process force hwptr
1346                                    and swptr to sync */
1347                                 __stop_dac(state);
1348                                 dmabuf->error++;
1349                         }
1350                         else if (!dmabuf->endcleared) {
1351                                 swptr = dmabuf->swptr;
1352                                 silence = (dmabuf->fmt & TRIDENT_FMT_16BIT ? 0 : 0x80);
1353                                 if (dmabuf->update_flag & ALI_ADDRESS_INT_UPDATE) {
1354                                         /* We must clear end data of 1/2 dmabuf if needed.
1355                                            According to 1/2 algorithm of Address Engine Interrupt,
1356                                            check the validation of the data of half dmasize. */
1357                                         half_dmasize = dmabuf->dmasize / 2;
1358                                         if ((diff = hwptr - half_dmasize) < 0 )
1359                                                 diff = hwptr;
1360                                         if ((dmabuf->count + diff) < half_dmasize) {
1361                                                 //there is invalid data in the end of half buffer
1362                                                 if ((clear_cnt = half_dmasize - swptr) < 0)
1363                                                         clear_cnt += half_dmasize;
1364                                                 //clear the invalid data
1365                                                 memset (dmabuf->rawbuf + swptr,
1366                                                         silence, clear_cnt);
1367                                                 if (state->chans_num == 6) {
1368                                                 clear_cnt = clear_cnt / 2;
1369                                                 swptr = swptr / 2;
1370                                                         memset (state->other_states[0]->dmabuf.rawbuf + swptr,
1371                                                                 silence, clear_cnt);
1372                                                         memset (state->other_states[1]->dmabuf.rawbuf + swptr,
1373                                                                 silence, clear_cnt);
1374                                                         memset (state->other_states[2]->dmabuf.rawbuf + swptr,
1375                                                                 silence, clear_cnt);
1376                                                         memset (state->other_states[3]->dmabuf.rawbuf + swptr,
1377                                                                 silence, clear_cnt);
1378                                                 }
1379                                                 dmabuf->endcleared = 1;
1380                                         }
1381                                 } else if (dmabuf->count < (signed) dmabuf->fragsize) {
1382                                         clear_cnt = dmabuf->fragsize;
1383                                         if ((swptr + clear_cnt) > dmabuf->dmasize)
1384                                                 clear_cnt = dmabuf->dmasize - swptr;
1385                                         memset (dmabuf->rawbuf + swptr, silence, clear_cnt);
1386                                         if (state->chans_num == 6) {
1387                                                 clear_cnt = clear_cnt / 2;
1388                                                 swptr = swptr / 2;
1389                                                 memset (state->other_states[0]->dmabuf.rawbuf + swptr,
1390                                                         silence, clear_cnt);
1391                                                 memset (state->other_states[1]->dmabuf.rawbuf + swptr,
1392                                                         silence, clear_cnt);
1393                                                 memset (state->other_states[2]->dmabuf.rawbuf + swptr,
1394                                                         silence, clear_cnt);
1395                                                 memset (state->other_states[3]->dmabuf.rawbuf + swptr,
1396                                                         silence, clear_cnt);
1397                                         }
1398                                         dmabuf->endcleared = 1;
1399                                 }
1400                         }
1401                         /* trident_update_ptr is called by interrupt handler or by process via
1402                            ioctl/poll, we only wake up the waiting process when we have more
1403                            than 1/2 buffer free (always true for interrupt handler) */
1404                         if (dmabuf->count < (signed)dmabuf->dmasize/2)
1405                                 wake_up(&dmabuf->wait);
1406                 }
1407         }
1408         dmabuf->update_flag &= ~ALI_ADDRESS_INT_UPDATE;
1409 }
1410
1411 static void trident_address_interrupt(struct trident_card *card)
1412 {
1413         int i;
1414         struct trident_state *state;
1415         
1416         /* Update the pointers for all channels we are running. */
1417         /* FIXME: should read interrupt status only once */
1418         for (i = 0; i < NR_HW_CH; i++) {
1419                 if (trident_check_channel_interrupt(card, 63 - i)) {
1420                         trident_ack_channel_interrupt(card, 63 - i);
1421                         if ((state = card->states[i]) != NULL) {
1422                                 trident_update_ptr(state);
1423                         } else {
1424                                 printk("trident: spurious channel irq %d.\n",
1425                                        63 - i);
1426                                 trident_stop_voice(card, 63 - i);
1427                                 trident_disable_voice_irq(card, 63 - i);
1428                         }
1429                 }
1430         }
1431 }
1432
1433 static void ali_hwvol_control(struct trident_card *card, int opt)
1434 {
1435         u16 dwTemp, volume[2], mute, diff, *pVol[2];
1436
1437         dwTemp = ali_ac97_read(card->ac97_codec[0], 0x02);
1438         mute = dwTemp & 0x8000;
1439         volume[0] = dwTemp & 0x001f;
1440         volume[1] = (dwTemp & 0x1f00) >> 8;
1441         if (volume[0] < volume [1]) {
1442                 pVol[0] = &volume[0];
1443                 pVol[1] = &volume[1];
1444         } else {
1445                 pVol[1] = &volume[0];
1446                 pVol[0] = &volume[1];
1447         }
1448         diff = *(pVol[1]) - *(pVol[0]);
1449
1450         if (opt == 1) {                     // MUTE
1451                 dwTemp ^= 0x8000;
1452                 ali_ac97_write(card->ac97_codec[0], 0x02, dwTemp);
1453         } else if (opt == 2) {   // Down
1454                 if (mute)
1455                         return;
1456                 if (*(pVol[1]) < 0x001f) {
1457                         (*pVol[1])++;
1458                         *(pVol[0]) = *(pVol[1]) - diff;
1459                 }
1460                 dwTemp &= 0xe0e0;
1461                 dwTemp |= (volume[0]) | (volume[1] << 8);
1462                 ali_ac97_write(card->ac97_codec[0], 0x02, dwTemp);
1463                 card->ac97_codec[0]->mixer_state[0] = ((32-volume[0])*25/8) | (((32-volume[1])*25/8) << 8);
1464         } else if (opt == 4) {   // Up
1465                 if (mute)
1466                         return;
1467                 if (*(pVol[0]) >0) {
1468                         (*pVol[0])--;
1469                         *(pVol[1]) = *(pVol[0]) + diff;
1470                 }
1471                 dwTemp &= 0xe0e0;
1472                 dwTemp |= (volume[0]) | (volume[1] << 8);
1473                 ali_ac97_write(card->ac97_codec[0], 0x02, dwTemp);
1474                 card->ac97_codec[0]->mixer_state[0] = ((32-volume[0])*25/8) | (((32-volume[1])*25/8) << 8);
1475         } 
1476         else 
1477         {
1478                 /* Nothing needs doing */
1479         }
1480 }
1481
1482 /*
1483  *      Re-enable reporting of vol change after 0.1 seconds
1484  */
1485
1486 static void ali_timeout(unsigned long ptr)
1487 {
1488         struct trident_card *card = (struct trident_card *)ptr;
1489         u16 temp = 0;
1490
1491         /* Enable GPIO IRQ (MISCINT bit 18h)*/
1492         temp = inw(TRID_REG(card, T4D_MISCINT + 2));
1493         temp |= 0x0004;
1494         outw(temp, TRID_REG(card, T4D_MISCINT + 2));
1495 }
1496
1497 /*
1498  *      Set up the timer to clear the vol change notification
1499  */
1500  
1501 static void ali_set_timer(struct trident_card *card)
1502 {
1503         /* Add Timer Routine to Enable GPIO IRQ */
1504         del_timer(&card->timer);        /* Never queue twice */
1505         card->timer.function = ali_timeout;
1506         card->timer.data = (unsigned long) card;
1507         card->timer.expires = jiffies + HZ/10;
1508         add_timer(&card->timer);
1509 }
1510
1511 /*
1512  *      Process a GPIO event
1513  */
1514  
1515 static void ali_queue_task(struct trident_card *card, int opt)
1516 {
1517         u16 temp;
1518
1519         /* Disable GPIO IRQ (MISCINT bit 18h)*/
1520         temp = inw(TRID_REG(card, T4D_MISCINT + 2));
1521         temp &= (u16)(~0x0004);
1522         outw(temp, TRID_REG(card, T4D_MISCINT + 2));
1523
1524         /* Adjust the volume */
1525         ali_hwvol_control(card, opt);
1526         
1527         /* Set the timer for 1/10th sec */
1528         ali_set_timer(card);
1529 }
1530
1531 static void trident_interrupt(int irq, void *dev_id, struct pt_regs *regs)
1532 {
1533         struct trident_card *card = (struct trident_card *)dev_id;
1534         u32 event;
1535         u32 gpio;
1536
1537         spin_lock(&card->lock);
1538         event = inl(TRID_REG(card, T4D_MISCINT));
1539
1540 #ifdef DEBUG
1541         printk("trident: trident_interrupt called, MISCINT = 0x%08x\n", event);
1542 #endif
1543
1544         if (event & ADDRESS_IRQ) {
1545                 card->address_interrupt(card);
1546         }
1547
1548         if(card->pci_id == PCI_DEVICE_ID_ALI_5451)
1549         {
1550                 /* GPIO IRQ (H/W Volume Control) */
1551                 event = inl(TRID_REG(card, T4D_MISCINT));
1552                 if (event & (1<<25)) {
1553                         gpio = inl(TRID_REG(card, ALI_GPIO));
1554                         if (!timer_pending(&card->timer)) 
1555                                 ali_queue_task(card, gpio&0x07);
1556                 }
1557                 event = inl(TRID_REG(card, T4D_MISCINT));
1558                 outl(event | (ST_TARGET_REACHED | MIXER_OVERFLOW | MIXER_UNDERFLOW), TRID_REG(card, T4D_MISCINT));
1559                 spin_unlock(&card->lock);
1560                 return;
1561         }
1562
1563         /* manually clear interrupt status, bad hardware design, blame T^2 */
1564         outl((ST_TARGET_REACHED | MIXER_OVERFLOW | MIXER_UNDERFLOW),
1565              TRID_REG(card, T4D_MISCINT));
1566         spin_unlock(&card->lock);
1567 }
1568
1569 /* in this loop, dmabuf.count signifies the amount of data that is waiting to be copied to
1570    the user's buffer.  it is filled by the dma machine and drained by this loop. */
1571 static ssize_t trident_read(struct file *file, char *buffer, size_t count, loff_t *ppos)
1572 {
1573         struct trident_state *state = (struct trident_state *)file->private_data;
1574         struct dmabuf *dmabuf = &state->dmabuf;
1575         ssize_t ret = 0;
1576         unsigned long flags;
1577         unsigned swptr;
1578         int cnt;
1579
1580 #ifdef DEBUG
1581         printk("trident: trident_read called, count = %d\n", count);
1582 #endif
1583
1584         VALIDATE_STATE(state);
1585         if (ppos != &file->f_pos)
1586                 return -ESPIPE;
1587                 
1588         if (dmabuf->mapped)
1589                 return -ENXIO;
1590         if (!access_ok(VERIFY_WRITE, buffer, count))
1591                 return -EFAULT;
1592                 
1593         down(&state->sem);
1594         if (!dmabuf->ready && (ret = prog_dmabuf(state, 1)))
1595                 goto out;
1596
1597         while (count > 0) {
1598                 spin_lock_irqsave(&state->card->lock, flags);
1599                 if (dmabuf->count > (signed) dmabuf->dmasize) {
1600                         /* buffer overrun, we are recovering from sleep_on_timeout,
1601                            resync hwptr and swptr, make process flush the buffer */
1602                         dmabuf->count = dmabuf->dmasize;
1603                         dmabuf->swptr = dmabuf->hwptr;
1604                 }
1605                 swptr = dmabuf->swptr;
1606                 cnt = dmabuf->dmasize - swptr;
1607                 if (dmabuf->count < cnt)
1608                         cnt = dmabuf->count;
1609                 spin_unlock_irqrestore(&state->card->lock, flags);
1610
1611                 if (cnt > count)
1612                         cnt = count;
1613                 if (cnt <= 0) {
1614                         unsigned long tmo;
1615                         /* buffer is empty, start the dma machine and wait for data to be
1616                            recorded */
1617                         start_adc(state);
1618                         if (file->f_flags & O_NONBLOCK) {
1619                                 if (!ret) ret = -EAGAIN;
1620                                 goto out;
1621                         }
1622                         
1623                         up(&state->sem);
1624                         /* No matter how much space left in the buffer, we have to wait until
1625                            CSO == ESO/2 or CSO == ESO when address engine interrupts */
1626                         tmo = (dmabuf->dmasize * HZ) / (dmabuf->rate * 2);
1627                         tmo >>= sample_shift[dmabuf->fmt];
1628                         /* There are two situations when sleep_on_timeout returns, one is when
1629                            the interrupt is serviced correctly and the process is waked up by
1630                            ISR ON TIME. Another is when timeout is expired, which means that
1631                            either interrupt is NOT serviced correctly (pending interrupt) or it
1632                            is TOO LATE for the process to be scheduled to run (scheduler latency)
1633                            which results in a (potential) buffer overrun. And worse, there is
1634                            NOTHING we can do to prevent it. */
1635                         if (!interruptible_sleep_on_timeout(&dmabuf->wait, tmo)) {
1636 #ifdef DEBUG
1637                                 printk(KERN_ERR "trident: recording schedule timeout, "
1638                                        "dmasz %u fragsz %u count %i hwptr %u swptr %u\n",
1639                                        dmabuf->dmasize, dmabuf->fragsize, dmabuf->count,
1640                                        dmabuf->hwptr, dmabuf->swptr);
1641 #endif
1642                                 /* a buffer overrun, we delay the recovery until next time the
1643                                    while loop begin and we REALLY have space to record */
1644                         }
1645                         if (signal_pending(current)) {
1646                                 if(!ret) ret = -ERESTARTSYS;
1647                                 goto out;
1648                         }
1649                         down(&state->sem);
1650                         if(dmabuf->mapped)
1651                         {
1652                                 if(!ret)
1653                                         ret = -ENXIO;
1654                                 goto out;
1655                         }
1656                         continue;
1657                 }
1658
1659                 if (copy_to_user(buffer, dmabuf->rawbuf + swptr, cnt)) {
1660                         if (!ret) ret = -EFAULT;
1661                         goto out;
1662                 }
1663
1664                 swptr = (swptr + cnt) % dmabuf->dmasize;
1665
1666                 spin_lock_irqsave(&state->card->lock, flags);
1667                 dmabuf->swptr = swptr;
1668                 dmabuf->count -= cnt;
1669                 spin_unlock_irqrestore(&state->card->lock, flags);
1670
1671                 count -= cnt;
1672                 buffer += cnt;
1673                 ret += cnt;
1674                 start_adc(state);
1675         }
1676 out:
1677         up(&state->sem);
1678         return ret;
1679 }
1680
1681 /* in this loop, dmabuf.count signifies the amount of data that is waiting to be dma to
1682    the soundcard.  it is drained by the dma machine and filled by this loop. */
1683
1684 static ssize_t trident_write(struct file *file, const char *buffer, size_t count, loff_t *ppos)
1685 {
1686         struct trident_state *state = (struct trident_state *)file->private_data;
1687         struct dmabuf *dmabuf = &state->dmabuf;
1688         ssize_t ret;
1689         unsigned long flags;
1690         unsigned swptr;
1691         int cnt;
1692         unsigned int state_cnt;
1693         unsigned int copy_count;
1694
1695 #ifdef DEBUG
1696         printk("trident: trident_write called, count = %d\n", count);
1697 #endif
1698         VALIDATE_STATE(state);
1699         if (ppos != &file->f_pos)
1700                 return -ESPIPE;
1701         
1702         /*
1703          *      Guard against an mmap or ioctl while writing
1704          */     
1705          
1706         down(&state->sem);
1707         
1708         if (dmabuf->mapped)
1709         {
1710                 ret = -ENXIO;
1711                 goto out;
1712         }
1713         if (!dmabuf->ready && (ret = prog_dmabuf(state, 0)))
1714                 goto out;
1715
1716         if (!access_ok(VERIFY_READ, buffer, count))
1717         {
1718                 ret= -EFAULT;
1719                 goto out;
1720         }
1721         
1722         ret = 0;
1723
1724         while (count > 0) {
1725                 spin_lock_irqsave(&state->card->lock, flags);
1726                 if (dmabuf->count < 0) {
1727                         /* buffer underrun, we are recovering from sleep_on_timeout,
1728                            resync hwptr and swptr */
1729                         dmabuf->count = 0;
1730                         dmabuf->swptr = dmabuf->hwptr;
1731                 }
1732                 swptr = dmabuf->swptr;
1733                 cnt = dmabuf->dmasize - swptr;
1734                 if (dmabuf->count + cnt > dmabuf->dmasize)
1735                         cnt = dmabuf->dmasize - dmabuf->count;
1736                 spin_unlock_irqrestore(&state->card->lock, flags);
1737
1738                 if (cnt > count)
1739                         cnt = count;
1740                 if (cnt <= 0) {
1741                         unsigned long tmo;
1742                         /* buffer is full, start the dma machine and wait for data to be
1743                            played */
1744                         start_dac(state);
1745                         if (file->f_flags & O_NONBLOCK) {
1746                                 if (!ret) ret = -EAGAIN;
1747                                 goto out;
1748                         }
1749                         /* No matter how much data left in the buffer, we have to wait until
1750                            CSO == ESO/2 or CSO == ESO when address engine interrupts */
1751                         lock_set_fmt(state);
1752                         tmo = (dmabuf->dmasize * HZ) / (dmabuf->rate * 2);
1753                         tmo >>= sample_shift[dmabuf->fmt];
1754                         unlock_set_fmt(state);
1755                         up(&state->sem);
1756                         
1757                         /* There are two situations when sleep_on_timeout returns, one is when
1758                            the interrupt is serviced correctly and the process is waked up by
1759                            ISR ON TIME. Another is when timeout is expired, which means that
1760                            either interrupt is NOT serviced correctly (pending interrupt) or it
1761                            is TOO LATE for the process to be scheduled to run (scheduler latency)
1762                            which results in a (potential) buffer underrun. And worse, there is
1763                            NOTHING we can do to prevent it. */
1764                         if (!interruptible_sleep_on_timeout(&dmabuf->wait, tmo)) {
1765 #ifdef DEBUG
1766                                 printk(KERN_ERR "trident: playback schedule timeout, "
1767                                        "dmasz %u fragsz %u count %i hwptr %u swptr %u\n",
1768                                        dmabuf->dmasize, dmabuf->fragsize, dmabuf->count,
1769                                        dmabuf->hwptr, dmabuf->swptr);
1770 #endif
1771                                 /* a buffer underrun, we delay the recovery until next time the
1772                                    while loop begin and we REALLY have data to play */
1773                         }
1774                         if (signal_pending(current)) {
1775                                 if (!ret) ret = -ERESTARTSYS;
1776                                 goto out;
1777                         }
1778                         down(&state->sem);
1779                         if(dmabuf->mapped)
1780                         {
1781                                 if(!ret)
1782                                         ret = -ENXIO;
1783                                 goto out;
1784                         }
1785                         continue;
1786                 }
1787                 lock_set_fmt(state);
1788                 if (state->chans_num == 6) {
1789                         copy_count = 0;
1790                         state_cnt = 0;
1791                         if (ali_write_5_1(state, buffer, cnt, &copy_count, &state_cnt) == -EFAULT) {
1792                                 if (state_cnt){
1793                                         swptr = (swptr + state_cnt) % dmabuf->dmasize;
1794                                         spin_lock_irqsave(&state->card->lock, flags);
1795                                         dmabuf->swptr = swptr;
1796                                         dmabuf->count += state_cnt;
1797                                         dmabuf->endcleared = 0;
1798                                         spin_unlock_irqrestore(&state->card->lock, flags);
1799                                 }
1800                                 ret += copy_count;
1801                                 if (!ret) ret = -EFAULT;
1802                                 unlock_set_fmt(state);
1803                                 goto out;
1804                         }
1805                 }
1806                 else {
1807                         if (copy_from_user(dmabuf->rawbuf + swptr, buffer, cnt)) {
1808                                 if (!ret) ret = -EFAULT;
1809                                 unlock_set_fmt(state);
1810                                 goto out;
1811                         }
1812                         state_cnt = cnt;
1813                 }
1814                 unlock_set_fmt(state);
1815                 
1816                 swptr = (swptr + state_cnt) % dmabuf->dmasize;          
1817                 
1818                 spin_lock_irqsave(&state->card->lock, flags);
1819                 dmabuf->swptr = swptr;
1820                 dmabuf->count += state_cnt;
1821                 dmabuf->endcleared = 0;
1822                 spin_unlock_irqrestore(&state->card->lock, flags);
1823
1824                 count -= cnt;
1825                 buffer += cnt;  
1826                 ret += cnt;
1827                 start_dac(state);
1828         }
1829 out:
1830         up(&state->sem);
1831         return ret;
1832 }
1833
1834
1835 /* No kernel lock - we have our own spinlock */
1836 static unsigned int trident_poll(struct file *file, struct poll_table_struct *wait)
1837 {
1838         struct trident_state *state = (struct trident_state *)file->private_data;
1839         struct dmabuf *dmabuf = &state->dmabuf;
1840         unsigned long flags;
1841         unsigned int mask = 0;
1842
1843         VALIDATE_STATE(state);
1844
1845         /*
1846          *      Guard against a parallel poll and write causing multiple
1847          *      prog_dmabuf events
1848          */
1849          
1850         down(&state->sem);
1851
1852         if (file->f_mode & FMODE_WRITE) {
1853                 if (!dmabuf->ready && prog_dmabuf(state, 0))
1854                 {
1855                         up(&state->sem);
1856                         return 0;
1857                 }
1858                 poll_wait(file, &dmabuf->wait, wait);
1859         }
1860         if (file->f_mode & FMODE_READ) {
1861                 if (!dmabuf->ready && prog_dmabuf(state, 1))
1862                 {
1863                         up(&state->sem);
1864                         return 0;
1865                 }
1866                 poll_wait(file, &dmabuf->wait, wait);
1867         }
1868
1869         up(&state->sem);
1870         
1871         spin_lock_irqsave(&state->card->lock, flags);
1872         trident_update_ptr(state);
1873         if (file->f_mode & FMODE_READ) {
1874                 if (dmabuf->count >= (signed)dmabuf->fragsize)
1875                         mask |= POLLIN | POLLRDNORM;
1876         }
1877         if (file->f_mode & FMODE_WRITE) {
1878                 if (dmabuf->mapped) {
1879                         if (dmabuf->count >= (signed)dmabuf->fragsize)
1880                                 mask |= POLLOUT | POLLWRNORM;
1881                 } else {
1882                         if ((signed)dmabuf->dmasize >= dmabuf->count + (signed)dmabuf->fragsize)
1883                                 mask |= POLLOUT | POLLWRNORM;
1884                 }
1885         }
1886         spin_unlock_irqrestore(&state->card->lock, flags);
1887
1888         return mask;
1889 }
1890
1891 static int trident_mmap(struct file *file, struct vm_area_struct *vma)
1892 {
1893         struct trident_state *state = (struct trident_state *)file->private_data;
1894         struct dmabuf *dmabuf = &state->dmabuf;
1895         int ret = -EINVAL;
1896         unsigned long size;
1897
1898         VALIDATE_STATE(state);
1899         lock_kernel();
1900         
1901         /*
1902          *      Lock against poll read write or mmap creating buffers. Also lock
1903          *      a read or write against an mmap.
1904          */
1905          
1906         down(&state->sem);
1907         
1908         if (vma->vm_flags & VM_WRITE) {
1909                 if ((ret = prog_dmabuf(state, 0)) != 0)
1910                         goto out;
1911         } else if (vma->vm_flags & VM_READ) {
1912                 if ((ret = prog_dmabuf(state, 1)) != 0)
1913                         goto out;
1914         } else
1915                 goto out;
1916
1917         ret = -EINVAL;
1918         if (vma->vm_pgoff != 0)
1919                 goto out;
1920         size = vma->vm_end - vma->vm_start;
1921         if (size > (PAGE_SIZE << dmabuf->buforder))
1922                 goto out;
1923         ret = -EAGAIN;
1924         if (remap_page_range(vma->vm_start, virt_to_phys(dmabuf->rawbuf),
1925                              size, vma->vm_page_prot))
1926                 goto out;
1927         dmabuf->mapped = 1;
1928         ret = 0;
1929 out:
1930         up(&state->sem);
1931         unlock_kernel();
1932         return ret;
1933 }
1934
1935 static int trident_ioctl(struct inode *inode, struct file *file, unsigned int cmd, unsigned long arg)
1936 {
1937         struct trident_state *state = (struct trident_state *)file->private_data;
1938         struct dmabuf *dmabuf = &state->dmabuf;
1939         unsigned long flags;
1940         audio_buf_info abinfo;
1941         count_info cinfo;
1942         int val, mapped, ret = 0;
1943
1944         struct trident_card *card = state->card;
1945
1946         VALIDATE_STATE(state);
1947         mapped = ((file->f_mode & FMODE_WRITE) && dmabuf->mapped) ||
1948                 ((file->f_mode & FMODE_READ) && dmabuf->mapped);
1949 #ifdef DEBUG
1950         printk("trident: trident_ioctl, command = %2d, arg = 0x%08x\n",
1951                _IOC_NR(cmd), arg ? *(int *)arg : 0);
1952 #endif
1953
1954         switch (cmd) 
1955         {
1956         case OSS_GETVERSION:
1957                 ret = put_user(SOUND_VERSION, (int *)arg);
1958                 break;
1959                 
1960         case SNDCTL_DSP_RESET:
1961                 /* FIXME: spin_lock ? */
1962                 if (file->f_mode & FMODE_WRITE) {
1963                         stop_dac(state);
1964                         synchronize_irq();
1965                         dmabuf->ready = 0;
1966                         dmabuf->swptr = dmabuf->hwptr = 0;
1967                         dmabuf->count = dmabuf->total_bytes = 0;
1968                 }
1969                 if (file->f_mode & FMODE_READ) {
1970                         stop_adc(state);
1971                         synchronize_irq();
1972                         dmabuf->ready = 0;
1973                         dmabuf->swptr = dmabuf->hwptr = 0;
1974                         dmabuf->count = dmabuf->total_bytes = 0;
1975                 }
1976                 break;
1977
1978         case SNDCTL_DSP_SYNC:
1979                 if (file->f_mode & FMODE_WRITE)
1980                         ret = drain_dac(state, file->f_flags & O_NONBLOCK);
1981                 break;
1982
1983         case SNDCTL_DSP_SPEED: /* set smaple rate */
1984                 if (get_user(val, (int *)arg))
1985                 {
1986                         ret = -EFAULT;
1987                         break;
1988                 }
1989                 if (val >= 0) {
1990                         if (file->f_mode & FMODE_WRITE) {
1991                                 stop_dac(state);
1992                                 dmabuf->ready = 0;
1993                                 spin_lock_irqsave(&state->card->lock, flags);
1994                                 trident_set_dac_rate(state, val);
1995                                 spin_unlock_irqrestore(&state->card->lock, flags);
1996                         }
1997                         if (file->f_mode & FMODE_READ) {
1998                                 stop_adc(state);
1999                                 dmabuf->ready = 0;
2000                                 spin_lock_irqsave(&state->card->lock, flags);
2001                                 trident_set_adc_rate(state, val);
2002                                 spin_unlock_irqrestore(&state->card->lock, flags);
2003                         }
2004                 }
2005                 ret = put_user(dmabuf->rate, (int *)arg);
2006                 break;
2007
2008         case SNDCTL_DSP_STEREO: /* set stereo or mono channel */
2009                 if (get_user(val, (int *)arg))
2010                 {
2011                         ret = -EFAULT;
2012                         break;
2013                 }
2014                 lock_set_fmt(state);
2015                 if (file->f_mode & FMODE_WRITE) {
2016                         stop_dac(state);
2017                         dmabuf->ready = 0;
2018                         if (val)
2019                                 dmabuf->fmt |= TRIDENT_FMT_STEREO;
2020                         else
2021                                 dmabuf->fmt &= ~TRIDENT_FMT_STEREO;
2022                 }
2023                 if (file->f_mode & FMODE_READ) {
2024                         stop_adc(state);
2025                         dmabuf->ready = 0;
2026                         if (val)
2027                                 dmabuf->fmt |= TRIDENT_FMT_STEREO;
2028                         else
2029                                 dmabuf->fmt &= ~TRIDENT_FMT_STEREO;
2030                 }
2031                 unlock_set_fmt(state);
2032                 break;
2033
2034         case SNDCTL_DSP_GETBLKSIZE:
2035                 if (file->f_mode & FMODE_WRITE) {
2036                         if ((val = prog_dmabuf(state, 0)))
2037                                 ret = val;
2038                         else
2039                                 ret = put_user(dmabuf->fragsize, (int *)arg);
2040                         break;
2041                 }
2042                 if (file->f_mode & FMODE_READ) {
2043                         if ((val = prog_dmabuf(state, 1)))
2044                                 ret = val;
2045                         else
2046                                 ret = put_user(dmabuf->fragsize, (int *)arg);
2047                         break;
2048                 }
2049
2050         case SNDCTL_DSP_GETFMTS: /* Returns a mask of supported sample format*/
2051                 ret = put_user(AFMT_S16_LE|AFMT_U16_LE|AFMT_S8|AFMT_U8, (int *)arg);
2052                 break;
2053
2054         case SNDCTL_DSP_SETFMT: /* Select sample format */
2055                 if (get_user(val, (int *)arg))
2056                 {
2057                         ret = -EFAULT;
2058                         break;
2059                 }
2060                 lock_set_fmt(state);
2061                 if (val != AFMT_QUERY) {
2062                         if (file->f_mode & FMODE_WRITE) {
2063                                 stop_dac(state);
2064                                 dmabuf->ready = 0;
2065                                 if (val == AFMT_S16_LE)
2066                                         dmabuf->fmt |= TRIDENT_FMT_16BIT;
2067                                 else
2068                                         dmabuf->fmt &= ~TRIDENT_FMT_16BIT;
2069                         }
2070                         if (file->f_mode & FMODE_READ) {
2071                                 stop_adc(state);
2072                                 dmabuf->ready = 0;
2073                                 if (val == AFMT_S16_LE)
2074                                         dmabuf->fmt |= TRIDENT_FMT_16BIT;
2075                                 else
2076                                         dmabuf->fmt &= ~TRIDENT_FMT_16BIT;
2077                         }
2078                 }
2079                 unlock_set_fmt(state);
2080                 ret = put_user((dmabuf->fmt & TRIDENT_FMT_16BIT) ?
2081                                 AFMT_S16_LE : AFMT_U8, (int *)arg);
2082                 break;
2083
2084         case SNDCTL_DSP_CHANNELS:
2085                 if (get_user(val, (int *)arg))
2086                 {
2087                         ret = -EFAULT;
2088                         break;
2089                 }
2090                 if (val != 0) {
2091                         lock_set_fmt(state);
2092                         if (file->f_mode & FMODE_WRITE) {
2093                                 stop_dac(state);
2094                                 dmabuf->ready = 0;
2095                                                                 
2096                                 //prevent from memory leak
2097                                 if ((state->chans_num > 2) && (state->chans_num != val)) {
2098                                         ali_free_other_states_resources(state);
2099                                         state->chans_num = 1;
2100                                 }
2101                                 
2102                                 if (val >= 2)
2103                                 {
2104
2105                                         dmabuf->fmt |= TRIDENT_FMT_STEREO;
2106                                         if ((val == 6) && (state->card->pci_id == PCI_DEVICE_ID_ALI_5451)) {
2107
2108                                                 if( card->rec_channel_use_count > 0 )
2109                                                 {
2110                                                         printk(KERN_ERR "trident: Record is working on the card!\n");
2111                                                         ret = -EBUSY;
2112                                                         break;
2113                                                 }
2114
2115                                                 ret = ali_setup_multi_channels(state->card, 6);
2116                                                 if (ret < 0) {
2117                                                         unlock_set_fmt(state);
2118                                                         break;
2119                                                 }
2120                                                 down(&state->card->open_sem);
2121                                                 ret = ali_allocate_other_states_resources(state, 6);
2122                                                 if (ret < 0) {
2123                                                         up(&state->card->open_sem);
2124                                                         unlock_set_fmt(state);
2125                                                         break;
2126                                                 }
2127                                                 state->card->multi_channel_use_count ++;
2128                                                 up(&state->card->open_sem);
2129                                         }
2130                                         else val = 2;   /*yield to 2-channels*/
2131                                 }
2132                                 else
2133                                         dmabuf->fmt &= ~TRIDENT_FMT_STEREO;
2134                                 state->chans_num = val;
2135                         }
2136                         if (file->f_mode & FMODE_READ) {
2137                                 stop_adc(state);
2138                                 dmabuf->ready = 0;
2139                                 if (val >= 2) {
2140                                         if (!((file->f_mode & FMODE_WRITE) && (val == 6)))
2141                                                 val = 2;
2142                                         dmabuf->fmt |= TRIDENT_FMT_STEREO;
2143                                 }
2144                                 else
2145                                         dmabuf->fmt &= ~TRIDENT_FMT_STEREO;
2146                                 state->chans_num = val;
2147                         }
2148                         unlock_set_fmt(state);
2149                 }
2150                 ret = put_user(val, (int *)arg);
2151                 break;
2152
2153         case SNDCTL_DSP_POST:
2154                 /* Cause the working fragment to be output */
2155                 break;
2156
2157         case SNDCTL_DSP_SUBDIVIDE:
2158                 if (dmabuf->subdivision)
2159                 {
2160                         ret = -EINVAL;
2161                         break;
2162                 }
2163                 if (get_user(val, (int *)arg))
2164                 {
2165                         ret = -EFAULT;
2166                         break;
2167                 }
2168                 if (val != 1 && val != 2 && val != 4)
2169                 {
2170                         ret = -EINVAL;
2171                         break;
2172                 }
2173                 dmabuf->subdivision = val;
2174                 break;
2175
2176         case SNDCTL_DSP_SETFRAGMENT:
2177                 if (get_user(val, (int *)arg))
2178                 {
2179                         ret = -EFAULT;
2180                         break;
2181                 }
2182
2183                 dmabuf->ossfragshift = val & 0xffff;
2184                 dmabuf->ossmaxfrags = (val >> 16) & 0xffff;
2185                 if (dmabuf->ossfragshift < 4)
2186                         dmabuf->ossfragshift = 4;
2187                 if (dmabuf->ossfragshift > 15)
2188                         dmabuf->ossfragshift = 15;
2189                 if (dmabuf->ossmaxfrags < 4)
2190                         dmabuf->ossmaxfrags = 4;
2191
2192                 break;
2193
2194         case SNDCTL_DSP_GETOSPACE:
2195                 if (!(file->f_mode & FMODE_WRITE))
2196                 {
2197                         ret = -EINVAL;
2198                         break;
2199                 }
2200                 if (!dmabuf->ready && (val = prog_dmabuf(state, 0)) != 0)
2201                 { 
2202                         ret = val;
2203                         break;
2204                 }
2205                 spin_lock_irqsave(&state->card->lock, flags);
2206                 trident_update_ptr(state);
2207                 abinfo.fragsize = dmabuf->fragsize;
2208                 abinfo.bytes = dmabuf->dmasize - dmabuf->count;
2209                 abinfo.fragstotal = dmabuf->numfrag;
2210                 abinfo.fragments = abinfo.bytes >> dmabuf->fragshift;
2211                 spin_unlock_irqrestore(&state->card->lock, flags);
2212                 ret = copy_to_user((void *)arg, &abinfo, sizeof(abinfo)) ? -EFAULT : 0;
2213                 break;
2214
2215         case SNDCTL_DSP_GETISPACE:
2216                 if (!(file->f_mode & FMODE_READ))
2217                 {
2218                         ret = -EINVAL;
2219                         break;
2220                 }
2221                 if (!dmabuf->ready && (val = prog_dmabuf(state, 1)) != 0)
2222                 {
2223                         ret = val;
2224                         break;
2225                 }
2226                 spin_lock_irqsave(&state->card->lock, flags);
2227                 trident_update_ptr(state);
2228                 abinfo.fragsize = dmabuf->fragsize;
2229                 abinfo.bytes = dmabuf->count;
2230                 abinfo.fragstotal = dmabuf->numfrag;
2231                 abinfo.fragments = abinfo.bytes >> dmabuf->fragshift;
2232                 spin_unlock_irqrestore(&state->card->lock, flags);
2233                 ret = copy_to_user((void *)arg, &abinfo, sizeof(abinfo)) ? -EFAULT : 0;
2234                 break;
2235
2236         case SNDCTL_DSP_NONBLOCK:
2237                 file->f_flags |= O_NONBLOCK;
2238                 break;
2239
2240         case SNDCTL_DSP_GETCAPS:
2241                 ret = put_user(DSP_CAP_REALTIME|DSP_CAP_TRIGGER|DSP_CAP_MMAP|DSP_CAP_BIND,
2242                             (int *)arg);
2243                 break;
2244
2245         case SNDCTL_DSP_GETTRIGGER:
2246                 val = 0;
2247                 if ((file->f_mode & FMODE_READ) && dmabuf->enable)
2248                         val |= PCM_ENABLE_INPUT;
2249                 if ((file->f_mode & FMODE_WRITE) && dmabuf->enable)
2250                         val |= PCM_ENABLE_OUTPUT;
2251                 ret = put_user(val, (int *)arg);
2252                 break;
2253
2254         case SNDCTL_DSP_SETTRIGGER:
2255                 if (get_user(val, (int *)arg))
2256                 {
2257                         ret = -EFAULT;
2258                         break;
2259                 }
2260                 if (file->f_mode & FMODE_READ) {
2261                         if (val & PCM_ENABLE_INPUT) {
2262                                 if (!dmabuf->ready && (ret = prog_dmabuf(state, 1)))
2263                                         break;
2264                                 start_adc(state);
2265                         } else
2266                                 stop_adc(state);
2267                 }
2268                 if (file->f_mode & FMODE_WRITE) {
2269                         if (val & PCM_ENABLE_OUTPUT) {
2270                                 if (!dmabuf->ready && (ret = prog_dmabuf(state, 0)))
2271                                         break;
2272                                 start_dac(state);
2273                         } else
2274                                 stop_dac(state);
2275                 }
2276                 break;
2277
2278         case SNDCTL_DSP_GETIPTR:
2279                 if (!(file->f_mode & FMODE_READ))
2280                 {
2281                         ret = -EINVAL;
2282                         break;
2283                 }
2284                 if (!dmabuf->ready && (val = prog_dmabuf(state, 1)) != 0)
2285                 {
2286                         ret = val;
2287                         break;
2288                 }
2289                 spin_lock_irqsave(&state->card->lock, flags);
2290                 trident_update_ptr(state);
2291                 cinfo.bytes = dmabuf->total_bytes;
2292                 cinfo.blocks = dmabuf->count >> dmabuf->fragshift;
2293                 cinfo.ptr = dmabuf->hwptr;
2294                 if (dmabuf->mapped)
2295                         dmabuf->count &= dmabuf->fragsize-1;
2296                 spin_unlock_irqrestore(&state->card->lock, flags);
2297                 ret = copy_to_user((void *)arg, &cinfo, sizeof(cinfo));
2298                 break;
2299
2300         case SNDCTL_DSP_GETOPTR:
2301                 if (!(file->f_mode & FMODE_WRITE))
2302                 {
2303                         ret = -EINVAL;
2304                         break;
2305                 }
2306                 if (!dmabuf->ready && (val = prog_dmabuf(state, 0)) != 0)
2307                 {
2308                         ret = val;
2309                         break;
2310                 }
2311                 
2312                 spin_lock_irqsave(&state->card->lock, flags);
2313                 trident_update_ptr(state);
2314                 cinfo.bytes = dmabuf->total_bytes;
2315                 cinfo.blocks = dmabuf->count >> dmabuf->fragshift;
2316                 cinfo.ptr = dmabuf->hwptr;
2317                 if (dmabuf->mapped)
2318                         dmabuf->count &= dmabuf->fragsize-1;
2319                 spin_unlock_irqrestore(&state->card->lock, flags);
2320                 ret = copy_to_user((void *)arg, &cinfo, sizeof(cinfo))?-EFAULT:0;
2321                 break;
2322
2323         case SNDCTL_DSP_SETDUPLEX:
2324                 ret = -EINVAL;
2325                 break;
2326
2327         case SNDCTL_DSP_GETODELAY:
2328                 if (!(file->f_mode & FMODE_WRITE))
2329                 {
2330                         ret = -EINVAL;
2331                         break;
2332                 }
2333                 if (!dmabuf->ready && (val = prog_dmabuf(state, 0)) != 0)
2334                 {
2335                         ret = val;
2336                         break;
2337                 }
2338                 spin_lock_irqsave(&state->card->lock, flags);
2339                 trident_update_ptr(state);
2340                 val = dmabuf->count;
2341                 spin_unlock_irqrestore(&state->card->lock, flags);
2342                 ret = put_user(val, (int *)arg);
2343                 break;
2344
2345         case SOUND_PCM_READ_RATE:
2346                 ret = put_user(dmabuf->rate, (int *)arg);
2347                 break;
2348
2349         case SOUND_PCM_READ_CHANNELS:
2350                 ret = put_user((dmabuf->fmt & TRIDENT_FMT_STEREO) ? 2 : 1,
2351                                 (int *)arg);
2352                 break;
2353
2354         case SOUND_PCM_READ_BITS:
2355                 ret = put_user((dmabuf->fmt & TRIDENT_FMT_16BIT) ?
2356                                 AFMT_S16_LE : AFMT_U8, (int *)arg);
2357                 break;
2358
2359         case SNDCTL_DSP_GETCHANNELMASK:
2360                 ret = put_user(DSP_BIND_FRONT|DSP_BIND_SURR|DSP_BIND_CENTER_LFE,
2361                                 (int *)arg);
2362                 break;
2363
2364         case SNDCTL_DSP_BIND_CHANNEL:
2365                 if (state->card->pci_id != PCI_DEVICE_ID_SI_7018)
2366                 {
2367                         ret = -EINVAL;
2368                         break;
2369                 }
2370
2371                 if (get_user(val, (int *)arg))
2372                 {
2373                         ret = -EFAULT;
2374                         break;
2375                 }
2376                 if (val == DSP_BIND_QUERY) {
2377                         val = dmabuf->channel->attribute | 0x3c00;
2378                         val = attr2mask[val >> 8];
2379                 } else {
2380                         dmabuf->ready = 0;
2381                         if (file->f_mode & FMODE_READ)
2382                                 dmabuf->channel->attribute = (CHANNEL_REC|SRC_ENABLE);
2383                         if (file->f_mode & FMODE_WRITE)
2384                                 dmabuf->channel->attribute = (CHANNEL_SPC_PB|SRC_ENABLE);
2385                         dmabuf->channel->attribute |= mask2attr[ffs(val)];
2386                 }
2387                 ret = put_user(val, (int *)arg);
2388                 break;
2389
2390         case SNDCTL_DSP_MAPINBUF:
2391         case SNDCTL_DSP_MAPOUTBUF:
2392         case SNDCTL_DSP_SETSYNCRO:
2393         case SOUND_PCM_WRITE_FILTER:
2394         case SOUND_PCM_READ_FILTER:
2395         default:
2396                 ret = -EINVAL;
2397                 break;
2398                 
2399         }
2400         return ret;
2401 }
2402
2403 static int trident_open(struct inode *inode, struct file *file)
2404 {
2405         int i = 0;
2406         int minor = MINOR(inode->i_rdev);
2407         struct trident_card *card = devs;
2408         struct trident_state *state = NULL;
2409         struct dmabuf *dmabuf = NULL;
2410         
2411         /* Added by Matt Wu 01-05-2001 */
2412         if(file->f_mode & FMODE_READ)
2413         {
2414                 if(card->pci_id == PCI_DEVICE_ID_ALI_5451) {
2415                         if (card->multi_channel_use_count > 0)
2416                                 return -EBUSY;
2417                 }
2418         }
2419
2420         /* find an available virtual channel (instance of /dev/dsp) */
2421         while (card != NULL) {
2422                 down(&card->open_sem);
2423                 if(file->f_mode & FMODE_READ)
2424                 {
2425                         /* Skip opens on cards that are in 6 channel mode */
2426                         if (card->multi_channel_use_count > 0)
2427                         {
2428                                 up(&card->open_sem);
2429                                 card = card->next;
2430                                 continue;
2431                         }
2432                 }
2433                 for (i = 0; i < NR_HW_CH; i++) {
2434                         if (card->states[i] == NULL) {
2435                                 state = card->states[i] = (struct trident_state *)
2436                                         kmalloc(sizeof(struct trident_state), GFP_KERNEL);
2437                                 if (state == NULL) {
2438                                         return -ENOMEM;
2439                                 }
2440                                 memset(state, 0, sizeof(struct trident_state));
2441                                 init_MUTEX(&state->sem);
2442                                 dmabuf = &state->dmabuf;
2443                                 goto found_virt;
2444                         }
2445                 }
2446                 up(&card->open_sem);
2447                 card = card->next;
2448         }
2449         /* no more virtual channel avaiable */
2450         if (!state) {
2451                 return -ENODEV;
2452         }
2453  found_virt:
2454         /* found a free virtual channel, allocate hardware channels */
2455         if(file->f_mode & FMODE_READ)
2456                 dmabuf->channel = card->alloc_rec_pcm_channel(card);
2457         else
2458                 dmabuf->channel = card->alloc_pcm_channel(card);
2459                 
2460         if (dmabuf->channel == NULL) {
2461                 kfree (card->states[i]);
2462                 card->states[i] = NULL;
2463                 return -ENODEV;
2464         }
2465
2466         /* initialize the virtual channel */
2467         state->virt = i;
2468         state->card = card;
2469         state->magic = TRIDENT_STATE_MAGIC;
2470         init_waitqueue_head(&dmabuf->wait);
2471         file->private_data = state;
2472
2473         /* set default sample format. According to OSS Programmer's Guide  /dev/dsp
2474            should be default to unsigned 8-bits, mono, with sample rate 8kHz and
2475            /dev/dspW will accept 16-bits sample */
2476         if (file->f_mode & FMODE_WRITE) {
2477                 dmabuf->fmt &= ~TRIDENT_FMT_MASK;
2478                 if ((minor & 0x0f) == SND_DEV_DSP16)
2479                         dmabuf->fmt |= TRIDENT_FMT_16BIT;
2480                 dmabuf->ossfragshift = 0;
2481                 dmabuf->ossmaxfrags  = 0;
2482                 dmabuf->subdivision  = 0;
2483                 if (card->pci_id == PCI_DEVICE_ID_SI_7018) {
2484                         /* set default channel attribute to normal playback */
2485                         dmabuf->channel->attribute = CHANNEL_PB;
2486                 }
2487                 trident_set_dac_rate(state, 8000);
2488         }
2489
2490         if (file->f_mode & FMODE_READ) {
2491                 /* FIXME: Trident 4d can only record in signed 16-bits stereo, 48kHz sample,
2492                    to be dealed with in trident_set_adc_rate() ?? */
2493                 dmabuf->fmt &= ~TRIDENT_FMT_MASK;
2494                 if ((minor & 0x0f) == SND_DEV_DSP16)
2495                         dmabuf->fmt |= TRIDENT_FMT_16BIT;
2496                 dmabuf->ossfragshift = 0;
2497                 dmabuf->ossmaxfrags  = 0;
2498                 dmabuf->subdivision  = 0;
2499                 if (card->pci_id == PCI_DEVICE_ID_SI_7018) {
2500                         /* set default channel attribute to 0x8a80, record from
2501                            PCM L/R FIFO and mono = (left + right + 1)/2*/
2502                         dmabuf->channel->attribute =
2503                                 (CHANNEL_REC|PCM_LR|MONO_MIX);
2504                 }
2505                 trident_set_adc_rate(state, 8000);
2506         
2507                 /* Added by Matt Wu 01-05-2001 */
2508                 if(card->pci_id == PCI_DEVICE_ID_ALI_5451)
2509                         card->rec_channel_use_count ++;
2510         }
2511
2512         state->open_mode |= file->f_mode & (FMODE_READ | FMODE_WRITE);
2513         up(&card->open_sem);
2514
2515 #ifdef DEBUG
2516        printk(KERN_ERR "trident: open virtual channel %d, hard channel %d\n", 
2517               state->virt, dmabuf->channel->num);
2518 #endif
2519
2520         return 0;
2521 }
2522
2523 static int trident_release(struct inode *inode, struct file *file)
2524 {
2525         struct trident_state *state = (struct trident_state *)file->private_data;
2526         struct trident_card *card;
2527         struct dmabuf *dmabuf;
2528         unsigned long flags;
2529
2530         lock_kernel();
2531         card = state->card;
2532         dmabuf = &state->dmabuf;
2533         VALIDATE_STATE(state);
2534
2535         if (file->f_mode & FMODE_WRITE) {
2536                 trident_clear_tail(state);
2537                 drain_dac(state, file->f_flags & O_NONBLOCK);
2538         }
2539
2540         /* stop DMA state machine and free DMA buffers/channels */
2541         down(&card->open_sem);
2542
2543         if (file->f_mode & FMODE_WRITE) {
2544                 stop_dac(state);
2545                 lock_set_fmt(state);
2546
2547                 unlock_set_fmt(state);
2548                 dealloc_dmabuf(state);
2549                 state->card->free_pcm_channel(state->card, dmabuf->channel->num);
2550
2551                 /* Added by Matt Wu */
2552                 if (card->pci_id == PCI_DEVICE_ID_ALI_5451) {
2553                         if (state->chans_num > 2) {
2554                                 if (card->multi_channel_use_count-- < 0)
2555                                         card->multi_channel_use_count = 0;
2556                                 if (card->multi_channel_use_count == 0)
2557                                         ali_close_multi_channels();
2558                                 ali_free_other_states_resources(state);
2559                         }
2560                 }
2561         }
2562         if (file->f_mode & FMODE_READ) {
2563                 stop_adc(state);
2564                 dealloc_dmabuf(state);
2565                 state->card->free_pcm_channel(state->card, dmabuf->channel->num);
2566
2567                 /* Added by Matt Wu */
2568                 if (card->pci_id == PCI_DEVICE_ID_ALI_5451) {
2569                         if( card->rec_channel_use_count-- < 0 )
2570                                 card->rec_channel_use_count = 0;
2571                 }
2572         }
2573
2574         card->states[state->virt] = NULL;
2575         kfree(state);
2576
2577         /* we're covered by the open_sem */
2578         up(&card->open_sem);
2579         unlock_kernel();
2580
2581         return 0;
2582 }
2583
2584 static /*const*/ struct file_operations trident_audio_fops = {
2585         owner:          THIS_MODULE,
2586         llseek:         no_llseek,
2587         read:           trident_read,
2588         write:          trident_write,
2589         poll:           trident_poll,
2590         ioctl:          trident_ioctl,
2591         mmap:           trident_mmap,
2592         open:           trident_open,
2593         release:        trident_release,
2594 };
2595
2596 /* trident specific AC97 functions */
2597 /* Write AC97 codec registers */
2598 static void trident_ac97_set(struct ac97_codec *codec, u8 reg, u16 val)
2599 {
2600         struct trident_card *card = (struct trident_card *)codec->private_data;