linux 2.6.16.38 w/ vs2.0.3-rc1
[linux-2.6.git] / sound / oss / trident.c
1 /*
2  *      OSS driver for Linux 2.[46].x for
3  *
4  *      Trident 4D-Wave
5  *      SiS 7018
6  *      ALi 5451
7  *      Tvia/IGST CyberPro 5050
8  *
9  *      Driver: Alan Cox <alan@redhat.com>
10  *
11  *  Built from:
12  *      Low level code: <audio@tridentmicro.com> from ALSA
13  *      Framework: Thomas Sailer <sailer@ife.ee.ethz.ch>
14  *      Extended by: Zach Brown <zab@redhat.com>  
15  *
16  *  Hacked up by:
17  *      Aaron Holtzman <aholtzma@ess.engr.uvic.ca>
18  *      Ollie Lho <ollie@sis.com.tw> SiS 7018 Audio Core Support
19  *      Ching-Ling Lee <cling-li@ali.com.tw> ALi 5451 Audio Core Support 
20  *      Matt Wu <mattwu@acersoftech.com.cn> ALi 5451 Audio Core Support
21  *      Peter Wächtler <pwaechtler@loewe-komp.de> CyberPro5050 support
22  *      Muli Ben-Yehuda <mulix@mulix.org>
23  *
24  *
25  *      This program is free software; you can redistribute it and/or modify
26  *      it under the terms of the GNU General Public License as published by
27  *      the Free Software Foundation; either version 2 of the License, or
28  *      (at your option) any later version.
29  *
30  *      This program is distributed in the hope that it will be useful,
31  *      but WITHOUT ANY WARRANTY; without even the implied warranty of
32  *      MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
33  *      GNU General Public License for more details.
34  *
35  *      You should have received a copy of the GNU General Public License
36  *      along with this program; if not, write to the Free Software
37  *      Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
38  *
39  *  History
40  *  v0.14.10j
41  *      January 3 2004 Eugene Teo <eugeneteo@eugeneteo.net>
42  *      minor cleanup to use pr_debug instead of TRDBG since it is already
43  *      defined in linux/kernel.h.
44  *  v0.14.10i
45  *      December 29 2003 Muli Ben-Yehuda <mulix@mulix.org>
46  *      major cleanup for 2.6, fix a few error patch buglets
47  *      with returning without properly cleaning up first,
48  *      get rid of lock_kernel().
49  *  v0.14.10h
50  *      Sept 10 2002 Pascal Schmidt <der.eremit@email.de>
51  *      added support for ALi 5451 joystick port
52  *  v0.14.10g
53  *      Sept 05 2002 Alan Cox <alan@redhat.com>
54  *      adapt to new pci joystick attachment interface
55  *  v0.14.10f
56  *      July 24 2002 Muli Ben-Yehuda <mulix@actcom.co.il>
57  *      patch from Eric Lemar (via Ian Soboroff): in suspend and resume, 
58  *      fix wrong cast from pci_dev* to struct trident_card*. 
59  *  v0.14.10e
60  *      July 19 2002 Muli Ben-Yehuda <mulix@actcom.co.il>
61  *      rewrite the DMA buffer allocation/deallcoation functions, to make it 
62  *      modular and fix a bug where we would call free_pages on memory 
63  *      obtained with pci_alloc_consistent. Also remove unnecessary #ifdef 
64  *      CONFIG_PROC_FS and various other cleanups.
65  *  v0.14.10d
66  *      July 19 2002 Muli Ben-Yehuda <mulix@actcom.co.il>
67  *      made several printk(KERN_NOTICE...) into TRDBG(...), to avoid spamming
68  *      my syslog with hundreds of messages. 
69  *  v0.14.10c
70  *      July 16 2002 Muli Ben-Yehuda <mulix@actcom.co.il>
71  *      Cleaned up Lei Hu's 0.4.10 driver to conform to Documentation/CodingStyle
72  *      and the coding style used in the rest of the file. 
73  *  v0.14.10b
74  *      June 23 2002 Muli Ben-Yehuda <mulix@actcom.co.il>
75  *      add a missing unlock_set_fmt, remove a superflous lock/unlock pair 
76  *      with nothing in between. 
77  *  v0.14.10a
78  *      June 21 2002 Muli Ben-Yehuda <mulix@actcom.co.il> 
79  *      use a debug macro instead of #ifdef CONFIG_DEBUG, trim to 80 columns 
80  *      per line, use 'do {} while (0)' in statement macros. 
81  *  v0.14.10
82  *      June 6 2002 Lei Hu <Lei_hu@ali.com.tw>
83  *      rewrite the part to read/write registers of audio codec for Ali5451 
84  *  v0.14.9e
85  *      January 2 2002 Vojtech Pavlik <vojtech@ucw.cz> added gameport
86  *      support to avoid resource conflict with pcigame.c
87  *  v0.14.9d
88  *      October 8 2001 Arnaldo Carvalho de Melo <acme@conectiva.com.br>
89  *      use set_current_state, properly release resources on failure in
90  *      trident_probe, get rid of check_region
91  *  v0.14.9c
92  *      August 10 2001 Peter Wächtler <pwaechtler@loewe-komp.de>
93  *      added support for Tvia (formerly Integraphics/IGST) CyberPro5050
94  *      this chip is often found in settop boxes (combined video+audio)
95  *  v0.14.9b
96  *      Switch to static inline not extern inline (gcc 3)
97  *  v0.14.9a
98  *      Aug 6 2001 Alan Cox
99  *      0.14.9 crashed on rmmod due to a timer/bh left running. Simplified
100  *      the existing logic (the BH doesn't help as ac97 is lock_irqsave)
101  *      and used del_timer_sync to clean up
102  *      Fixed a problem where the ALi change broke my generic card
103  *  v0.14.9
104  *      Jul 10 2001 Matt Wu
105  *      Add H/W Volume Control
106  *  v0.14.8a
107  *      July 7 2001 Alan Cox
108  *      Moved Matt Wu's ac97 register cache into the card structure
109  *  v0.14.8
110  *      Apr 30 2001 Matt Wu
111  *      Set EBUF1 and EBUF2 to still mode
112  *      Add dc97/ac97 reset function
113  *      Fix power management: ali_restore_regs
114  *  unreleased 
115  *      Mar 09 2001 Matt Wu
116  *      Add cache for ac97 access
117  *  v0.14.7
118  *      Feb 06 2001 Matt Wu
119  *      Fix ac97 initialization
120  *      Fix bug: an extra tail will be played when playing
121  *      Jan 05 2001 Matt Wu
122  *      Implement multi-channels and S/PDIF in support for ALi 1535+
123  *  v0.14.6 
124  *      Nov 1 2000 Ching-Ling Lee
125  *      Fix the bug of memory leak when switching 5.1-channels to 2 channels.
126  *      Add lock protection into dynamic changing format of data.
127  *      Oct 18 2000 Ching-Ling Lee
128  *      5.1-channels support for ALi
129  *      June 28 2000 Ching-Ling Lee
130  *      S/PDIF out/in(playback/record) support for ALi 1535+, using /proc to be selected by user
131  *      Simple Power Management support for ALi
132  *  v0.14.5 May 23 2000 Ollie Lho
133  *      Misc bug fix from the Net
134  *  v0.14.4 May 20 2000 Aaron Holtzman
135  *      Fix kfree'd memory access in release
136  *      Fix race in open while looking for a free virtual channel slot
137  *      remove open_wait wq (which appears to be unused)
138  *  v0.14.3 May 10 2000 Ollie Lho
139  *      fixed a small bug in trident_update_ptr, xmms 1.0.1 no longer uses 100% CPU
140  *  v0.14.2 Mar 29 2000 Ching-Ling Lee
141  *      Add clear to silence advance in trident_update_ptr 
142  *      fix invalid data of the end of the sound
143  *  v0.14.1 Mar 24 2000 Ching-Ling Lee
144  *      ALi 5451 support added, playback and recording O.K.
145  *      ALi 5451 originally developed and structured based on sonicvibes, and
146  *      suggested to merge into this file by Alan Cox.
147  *  v0.14 Mar 15 2000 Ollie Lho
148  *      5.1 channel output support with channel binding. What's the Matrix ?
149  *  v0.13.1 Mar 10 2000 Ollie Lho
150  *      few minor bugs on dual codec support, needs more testing
151  *  v0.13 Mar 03 2000 Ollie Lho
152  *      new pci_* for 2.4 kernel, back ported to 2.2
153  *  v0.12 Feb 23 2000 Ollie Lho
154  *      Preliminary Recording support
155  *  v0.11.2 Feb 19 2000 Ollie Lho
156  *      removed incomplete full-dulplex support
157  *  v0.11.1 Jan 28 2000 Ollie Lho
158  *      small bug in setting sample rate for 4d-nx (reported by Aaron)
159  *  v0.11 Jan 27 2000 Ollie Lho
160  *      DMA bug, scheduler latency, second try
161  *  v0.10 Jan 24 2000 Ollie Lho
162  *      DMA bug fixed, found kernel scheduling problem
163  *  v0.09 Jan 20 2000 Ollie Lho
164  *      Clean up of channel register access routine (prepare for channel binding)
165  *  v0.08 Jan 14 2000 Ollie Lho
166  *      Isolation of AC97 codec code
167  *  v0.07 Jan 13 2000 Ollie Lho
168  *      Get rid of ugly old low level access routines (e.g. CHRegs.lp****)
169  *  v0.06 Jan 11 2000 Ollie Lho
170  *      Preliminary support for dual (more ?) AC97 codecs
171  *  v0.05 Jan 08 2000 Luca Montecchiani <m.luca@iname.com>
172  *      adapt to 2.3.x new __setup/__init call
173  *  v0.04 Dec 31 1999 Ollie Lho
174  *      Multiple Open, using Middle Loop Interrupt to smooth playback
175  *  v0.03 Dec 24 1999 Ollie Lho
176  *      mem leak in prog_dmabuf and dealloc_dmabuf removed
177  *  v0.02 Dec 15 1999 Ollie Lho
178  *      SiS 7018 support added, playback O.K.
179  *  v0.01 Alan Cox et. al.
180  *      Initial Release in kernel 2.3.30, does not work
181  * 
182  *  ToDo
183  *      Clean up of low level channel register access code. (done)
184  *      Fix the bug on dma buffer management in update_ptr, read/write, drain_dac (done)
185  *      Dual AC97 codecs support (done)
186  *      Recording support (done)
187  *      Mmap support
188  *      "Channel Binding" ioctl extension (done)
189  *      new pci device driver interface for 2.4 kernel (done)
190  *
191  *      Lock order (high->low)
192  *              lock    -       hardware lock
193  *              open_sem -      guard opens
194  *              sem     -       guard dmabuf, write re-entry etc
195  */
196
197 #include <linux/config.h>
198 #include <linux/module.h>
199 #include <linux/string.h>
200 #include <linux/ctype.h>
201 #include <linux/ioport.h>
202 #include <linux/sched.h>
203 #include <linux/delay.h>
204 #include <linux/sound.h>
205 #include <linux/slab.h>
206 #include <linux/soundcard.h>
207 #include <linux/pci.h>
208 #include <linux/init.h>
209 #include <linux/poll.h>
210 #include <linux/spinlock.h>
211 #include <linux/smp_lock.h>
212 #include <linux/ac97_codec.h>
213 #include <linux/bitops.h>
214 #include <linux/proc_fs.h>
215 #include <linux/interrupt.h>
216 #include <linux/pm.h>
217 #include <linux/gameport.h>
218 #include <linux/kernel.h>
219 #include <asm/uaccess.h>
220 #include <asm/io.h>
221 #include <asm/dma.h>
222
223 #if defined(CONFIG_ALPHA_NAUTILUS) || defined(CONFIG_ALPHA_GENERIC)
224 #include <asm/hwrpb.h>
225 #endif
226
227 #include "trident.h"
228
229 #define DRIVER_VERSION "0.14.10j-2.6"
230
231 #if defined(CONFIG_GAMEPORT) || (defined(MODULE) && defined(CONFIG_GAMEPORT_MODULE))
232 #define SUPPORT_JOYSTICK 1
233 #endif
234
235 /* magic numbers to protect our data structures */
236 #define TRIDENT_CARD_MAGIC      0x5072696E      /* "Prin" */
237 #define TRIDENT_STATE_MAGIC     0x63657373      /* "cess" */
238
239 #define TRIDENT_DMA_MASK        0x3fffffff      /* DMA buffer mask for pci_alloc_consist */
240 #define ALI_DMA_MASK            0x7fffffff      /* ALI Tridents have 31-bit DMA. Wow. */
241
242 #define NR_HW_CH                32
243
244 /* maximum number of AC97 codecs connected, AC97 2.0 defined 4, but 7018 and 4D-NX only
245    have 2 SDATA_IN lines (currently) */
246 #define NR_AC97         2
247
248 /* minor number of /dev/swmodem (temporary, experimental) */
249 #define SND_DEV_SWMODEM 7
250
251 static const unsigned ali_multi_channels_5_1[] = {
252         /*ALI_SURR_LEFT_CHANNEL, ALI_SURR_RIGHT_CHANNEL, */
253         ALI_CENTER_CHANNEL,
254         ALI_LEF_CHANNEL,
255         ALI_SURR_LEFT_CHANNEL,
256         ALI_SURR_RIGHT_CHANNEL
257 };
258
259 static const unsigned sample_size[] = { 1, 2, 2, 4 };
260 static const unsigned sample_shift[] = { 0, 1, 1, 2 };
261
262 static const char invalid_magic[] = KERN_CRIT "trident: invalid magic value in %s\n";
263
264 enum {
265         TRIDENT_4D_DX = 0,
266         TRIDENT_4D_NX,
267         SIS_7018,
268         ALI_5451,
269         CYBER5050
270 };
271
272 static char *card_names[] = {
273         "Trident 4DWave DX",
274         "Trident 4DWave NX",
275         "SiS 7018 PCI Audio",
276         "ALi Audio Accelerator",
277         "Tvia/IGST CyberPro 5050"
278 };
279
280 static struct pci_device_id trident_pci_tbl[] = {
281         {PCI_DEVICE(PCI_VENDOR_ID_TRIDENT, PCI_DEVICE_ID_TRIDENT_4DWAVE_DX),
282                 PCI_CLASS_MULTIMEDIA_AUDIO << 8, 0xffff00, TRIDENT_4D_DX},
283         {PCI_DEVICE(PCI_VENDOR_ID_TRIDENT, PCI_DEVICE_ID_TRIDENT_4DWAVE_NX),
284                 0, 0, TRIDENT_4D_NX},
285         {PCI_DEVICE(PCI_VENDOR_ID_SI, PCI_DEVICE_ID_SI_7018), 0, 0, SIS_7018},
286         {PCI_DEVICE(PCI_VENDOR_ID_ALI, PCI_DEVICE_ID_ALI_5451), 0, 0, ALI_5451},
287         {PCI_DEVICE(PCI_VENDOR_ID_INTERG, PCI_DEVICE_ID_INTERG_5050),
288                 0, 0, CYBER5050},
289         {0,}
290 };
291
292 MODULE_DEVICE_TABLE(pci, trident_pci_tbl);
293
294 /* "software" or virtual channel, an instance of opened /dev/dsp */
295 struct trident_state {
296         unsigned int magic;
297         struct trident_card *card;      /* Card info */
298
299         /* file mode */
300         mode_t open_mode;
301
302         /* virtual channel number */
303         int virt;
304
305         struct dmabuf {
306                 /* wave sample stuff */
307                 unsigned int rate;
308                 unsigned char fmt, enable;
309
310                 /* hardware channel */
311                 struct trident_channel *channel;
312
313                 /* OSS buffer management stuff */
314                 void *rawbuf;
315                 dma_addr_t dma_handle;
316                 unsigned buforder;
317                 unsigned numfrag;
318                 unsigned fragshift;
319
320                 /* our buffer acts like a circular ring */
321                 unsigned hwptr; /* where dma last started, updated by update_ptr */
322                 unsigned swptr; /* where driver last clear/filled, updated by read/write */
323                 int count;      /* bytes to be comsumed or been generated by dma machine */
324                 unsigned total_bytes;   /* total bytes dmaed by hardware */
325
326                 unsigned error; /* number of over/underruns */
327                 /* put process on wait queue when no more space in buffer */
328                 wait_queue_head_t wait; 
329
330                 /* redundant, but makes calculations easier */
331                 unsigned fragsize;
332                 unsigned dmasize;
333                 unsigned fragsamples;
334
335                 /* OSS stuff */
336                 unsigned mapped:1;
337                 unsigned ready:1;
338                 unsigned endcleared:1;
339                 unsigned update_flag;
340                 unsigned ossfragshift;
341                 int ossmaxfrags;
342                 unsigned subdivision;
343
344         } dmabuf;
345
346         /* 5.1 channels */
347         struct trident_state *other_states[4];
348         int multi_channels_adjust_count;
349         unsigned chans_num;
350         unsigned long fmt_flag;
351         /* Guard against mmap/write/read races */
352         struct semaphore sem;
353
354 };
355
356 /* hardware channels */
357 struct trident_channel {
358         int num; /* channel number */
359         u32 lba; /* Loop Begine Address, where dma buffer starts */
360         u32 eso; /* End Sample Offset, wehre dma buffer ends */ 
361                  /* (in the unit of samples) */
362         u32 delta; /* delta value, sample rate / 48k for playback, */
363                    /* 48k/sample rate for recording */
364         u16 attribute; /* control where PCM data go and come  */
365         u16 fm_vol;
366         u32 control; /* signed/unsigned, 8/16 bits, mono/stereo */
367 };
368
369 struct trident_pcm_bank_address {
370         u32 start;
371         u32 stop;
372         u32 aint;
373         u32 aint_en;
374 };
375
376 static struct trident_pcm_bank_address bank_a_addrs = {
377         T4D_START_A,
378         T4D_STOP_A,
379         T4D_AINT_A,
380         T4D_AINTEN_A
381 };
382
383 static struct trident_pcm_bank_address bank_b_addrs = {
384         T4D_START_B,
385         T4D_STOP_B,
386         T4D_AINT_B,
387         T4D_AINTEN_B
388 };
389
390 struct trident_pcm_bank {
391         /* register addresses to control bank operations */
392         struct trident_pcm_bank_address *addresses;
393         /* each bank has 32 channels */
394         u32 bitmap;             /* channel allocation bitmap */
395         struct trident_channel channels[32];
396 };
397
398 struct trident_card {
399         unsigned int magic;
400
401         /* We keep trident cards in a linked list */
402         struct trident_card *next;
403
404         /* single open lock mechanism, only used for recording */
405         struct semaphore open_sem;
406
407         /* The trident has a certain amount of cross channel interaction
408            so we use a single per card lock */
409         spinlock_t lock;
410
411         /* PCI device stuff */
412         struct pci_dev *pci_dev;
413         u16 pci_id;
414         u8 revision;
415
416         /* soundcore stuff */
417         int dev_audio;
418
419         /* structures for abstraction of hardware facilities, codecs, */ 
420         /* banks and channels */
421         struct ac97_codec *ac97_codec[NR_AC97];
422         struct trident_pcm_bank banks[NR_BANKS];
423         struct trident_state *states[NR_HW_CH];
424
425         /* hardware resources */
426         unsigned long iobase;
427         u32 irq;
428
429         /* Function support */
430         struct trident_channel *(*alloc_pcm_channel) (struct trident_card *);
431         struct trident_channel *(*alloc_rec_pcm_channel) (struct trident_card *);
432         void (*free_pcm_channel) (struct trident_card *, unsigned int chan);
433         void (*address_interrupt) (struct trident_card *);
434
435         /* Added by Matt Wu 01-05-2001 for spdif in */
436         int multi_channel_use_count;
437         int rec_channel_use_count;
438         u16 mixer_regs[64][NR_AC97];    /* Made card local by Alan */
439         int mixer_regs_ready;
440
441         /* Added for hardware volume control */
442         int hwvolctl;
443         struct timer_list timer;
444
445         /* Game port support */
446         struct gameport *gameport;
447 };
448
449 enum dmabuf_mode {
450         DM_PLAYBACK = 0,
451         DM_RECORD
452 };
453
454 /* table to map from CHANNELMASK to channel attribute for SiS 7018 */
455 static u16 mask2attr[] = {
456         PCM_LR, PCM_LR, SURR_LR, CENTER_LFE,
457         HSET, MIC, MODEM_LINE1, MODEM_LINE2,
458         I2S_LR, SPDIF_LR
459 };
460
461 /* table to map from channel attribute to CHANNELMASK for SiS 7018 */
462 static int attr2mask[] = {
463         DSP_BIND_MODEM1, DSP_BIND_MODEM2, DSP_BIND_FRONT, DSP_BIND_HANDSET,
464         DSP_BIND_I2S, DSP_BIND_CENTER_LFE, DSP_BIND_SURR, DSP_BIND_SPDIF
465 };
466
467 /* Added by Matt Wu 01-05-2001 for spdif in */
468 static int ali_close_multi_channels(void);
469 static void ali_delay(struct trident_card *card, int interval);
470 static void ali_detect_spdif_rate(struct trident_card *card);
471
472 static void ali_ac97_write(struct ac97_codec *codec, u8 reg, u16 val);
473 static u16 ali_ac97_read(struct ac97_codec *codec, u8 reg);
474
475 static struct trident_card *devs;
476
477 static void trident_ac97_set(struct ac97_codec *codec, u8 reg, u16 val);
478 static u16 trident_ac97_get(struct ac97_codec *codec, u8 reg);
479
480 static int trident_open_mixdev(struct inode *inode, struct file *file);
481 static int trident_ioctl_mixdev(struct inode *inode, struct file *file, 
482                                 unsigned int cmd, unsigned long arg);
483
484 static void ali_ac97_set(struct trident_card *card, int secondary, u8 reg, u16 val);
485 static u16 ali_ac97_get(struct trident_card *card, int secondary, u8 reg);
486 static void ali_set_spdif_out_rate(struct trident_card *card, unsigned int rate);
487 static void ali_enable_special_channel(struct trident_state *stat);
488 static struct trident_channel *ali_alloc_rec_pcm_channel(struct trident_card *card);
489 static struct trident_channel *ali_alloc_pcm_channel(struct trident_card *card);
490 static void ali_restore_regs(struct trident_card *card);
491 static void ali_save_regs(struct trident_card *card);
492 static int trident_suspend(struct pci_dev *dev, pm_message_t unused);
493 static int trident_resume(struct pci_dev *dev);
494 static void ali_free_pcm_channel(struct trident_card *card, unsigned int channel);
495 static int ali_setup_multi_channels(struct trident_card *card, int chan_nums);
496 static unsigned int ali_get_spdif_in_rate(struct trident_card *card);
497 static void ali_setup_spdif_in(struct trident_card *card);
498 static void ali_disable_spdif_in(struct trident_card *card);
499 static void ali_disable_special_channel(struct trident_card *card, int ch);
500 static void ali_setup_spdif_out(struct trident_card *card, int flag);
501 static int ali_write_5_1(struct trident_state *state,
502                          const char __user *buffer, 
503                          int cnt_for_multi_channel, unsigned int *copy_count, 
504                          unsigned int *state_cnt);
505 static int ali_allocate_other_states_resources(struct trident_state *state, 
506                                                int chan_nums);
507 static void ali_free_other_states_resources(struct trident_state *state);
508
509 /* save registers for ALi Power Management */
510 static struct ali_saved_registers {
511         unsigned long global_regs[ALI_GLOBAL_REGS];
512         unsigned long channel_regs[ALI_CHANNELS][ALI_CHANNEL_REGS];
513         unsigned mixer_regs[ALI_MIXER_REGS];
514 } ali_registers;
515
516 #define seek_offset(dma_ptr, buffer, cnt, offset, copy_count)   do { \
517         (dma_ptr) += (offset);    \
518         (buffer) += (offset);     \
519         (cnt) -= (offset);        \
520         (copy_count) += (offset); \
521 } while (0)
522
523 static inline int lock_set_fmt(struct trident_state* state)
524 {
525         if (test_and_set_bit(0, &state->fmt_flag))
526                 return -EFAULT;
527
528         return 0;
529 }
530
531 static inline void unlock_set_fmt(struct trident_state* state)
532 {
533         clear_bit(0, &state->fmt_flag);
534 }
535
536 static int
537 trident_enable_loop_interrupts(struct trident_card *card)
538 {
539         u32 global_control;
540
541         global_control = inl(TRID_REG(card, T4D_LFO_GC_CIR));
542
543         switch (card->pci_id) {
544         case PCI_DEVICE_ID_SI_7018:
545                 global_control |= (ENDLP_IE | MIDLP_IE | BANK_B_EN);
546                 break;
547         case PCI_DEVICE_ID_ALI_5451:
548         case PCI_DEVICE_ID_TRIDENT_4DWAVE_DX:
549         case PCI_DEVICE_ID_TRIDENT_4DWAVE_NX:
550         case PCI_DEVICE_ID_INTERG_5050:
551                 global_control |= (ENDLP_IE | MIDLP_IE);
552                 break;
553         default:
554                 return 0;
555         }
556
557         outl(global_control, TRID_REG(card, T4D_LFO_GC_CIR));
558
559         pr_debug("trident: Enable Loop Interrupts, globctl = 0x%08X\n",
560                  inl(TRID_REG(card, T4D_LFO_GC_CIR)));
561
562         return 1;
563 }
564
565 static int
566 trident_disable_loop_interrupts(struct trident_card *card)
567 {
568         u32 global_control;
569
570         global_control = inl(TRID_REG(card, T4D_LFO_GC_CIR));
571         global_control &= ~(ENDLP_IE | MIDLP_IE);
572         outl(global_control, TRID_REG(card, T4D_LFO_GC_CIR));
573
574         pr_debug("trident: Disabled Loop Interrupts, globctl = 0x%08X\n",
575                  global_control);
576
577         return 1;
578 }
579
580 static void
581 trident_enable_voice_irq(struct trident_card *card, unsigned int channel)
582 {
583         unsigned int mask = 1 << (channel & 0x1f);
584         struct trident_pcm_bank *bank = &card->banks[channel >> 5];
585         u32 reg, addr = bank->addresses->aint_en;
586
587         reg = inl(TRID_REG(card, addr));
588         reg |= mask;
589         outl(reg, TRID_REG(card, addr));
590
591 #ifdef DEBUG
592         reg = inl(TRID_REG(card, addr));
593         pr_debug("trident: enabled IRQ on channel %d, %s = 0x%08x(addr:%X)\n",
594                  channel, addr == T4D_AINTEN_B ? "AINTEN_B" : "AINTEN_A",
595                  reg, addr);
596 #endif /* DEBUG */
597 }
598
599 static void
600 trident_disable_voice_irq(struct trident_card *card, unsigned int channel)
601 {
602         unsigned int mask = 1 << (channel & 0x1f);
603         struct trident_pcm_bank *bank = &card->banks[channel >> 5];
604         u32 reg, addr = bank->addresses->aint_en;
605
606         reg = inl(TRID_REG(card, addr));
607         reg &= ~mask;
608         outl(reg, TRID_REG(card, addr));
609
610         /* Ack the channel in case the interrupt was set before we disable it. */
611         outl(mask, TRID_REG(card, bank->addresses->aint));
612
613 #ifdef DEBUG
614         reg = inl(TRID_REG(card, addr));
615         pr_debug("trident: disabled IRQ on channel %d, %s = 0x%08x(addr:%X)\n",
616                  channel, addr == T4D_AINTEN_B ? "AINTEN_B" : "AINTEN_A",
617                  reg, addr);
618 #endif /* DEBUG */
619 }
620
621 static void
622 trident_start_voice(struct trident_card *card, unsigned int channel)
623 {
624         unsigned int mask = 1 << (channel & 0x1f);
625         struct trident_pcm_bank *bank = &card->banks[channel >> 5];
626         u32 addr = bank->addresses->start;
627
628 #ifdef DEBUG
629         u32 reg;
630 #endif /* DEBUG */
631
632         outl(mask, TRID_REG(card, addr));
633
634 #ifdef DEBUG
635         reg = inl(TRID_REG(card, addr));
636         pr_debug("trident: start voice on channel %d, %s = 0x%08x(addr:%X)\n",
637                  channel, addr == T4D_START_B ? "START_B" : "START_A",
638                  reg, addr);
639 #endif /* DEBUG */
640 }
641
642 static void
643 trident_stop_voice(struct trident_card *card, unsigned int channel)
644 {
645         unsigned int mask = 1 << (channel & 0x1f);
646         struct trident_pcm_bank *bank = &card->banks[channel >> 5];
647         u32 addr = bank->addresses->stop;
648
649 #ifdef DEBUG
650         u32 reg;
651 #endif /* DEBUG */
652
653         outl(mask, TRID_REG(card, addr));
654
655 #ifdef DEBUG
656         reg = inl(TRID_REG(card, addr));
657         pr_debug("trident: stop voice on channel %d, %s = 0x%08x(addr:%X)\n",
658                  channel, addr == T4D_STOP_B ? "STOP_B" : "STOP_A",
659                  reg, addr);
660 #endif /* DEBUG */
661 }
662
663 static u32
664 trident_get_interrupt_mask(struct trident_card *card, unsigned int channel)
665 {
666         struct trident_pcm_bank *bank = &card->banks[channel];
667         u32 addr = bank->addresses->aint;
668         return inl(TRID_REG(card, addr));
669 }
670
671 static int
672 trident_check_channel_interrupt(struct trident_card *card, unsigned int channel)
673 {
674         unsigned int mask = 1 << (channel & 0x1f);
675         u32 reg = trident_get_interrupt_mask(card, channel >> 5);
676
677 #ifdef DEBUG
678         if (reg & mask)
679                 pr_debug("trident: channel %d has interrupt, %s = 0x%08x\n",
680                          channel, reg == T4D_AINT_B ? "AINT_B" : "AINT_A",
681                          reg);
682 #endif /* DEBUG */
683         return (reg & mask) ? 1 : 0;
684 }
685
686 static void
687 trident_ack_channel_interrupt(struct trident_card *card, unsigned int channel)
688 {
689         unsigned int mask = 1 << (channel & 0x1f);
690         struct trident_pcm_bank *bank = &card->banks[channel >> 5];
691         u32 reg, addr = bank->addresses->aint;
692
693         reg = inl(TRID_REG(card, addr));
694         reg &= mask;
695         outl(reg, TRID_REG(card, addr));
696
697 #ifdef DEBUG
698         reg = inl(TRID_REG(card, T4D_AINT_B));
699         pr_debug("trident: Ack channel %d interrupt, AINT_B = 0x%08x\n",
700                  channel, reg);
701 #endif /* DEBUG */
702 }
703
704 static struct trident_channel *
705 trident_alloc_pcm_channel(struct trident_card *card)
706 {
707         struct trident_pcm_bank *bank;
708         int idx;
709
710         bank = &card->banks[BANK_B];
711
712         for (idx = 31; idx >= 0; idx--) {
713                 if (!(bank->bitmap & (1 << idx))) {
714                         struct trident_channel *channel = &bank->channels[idx];
715                         bank->bitmap |= 1 << idx;
716                         channel->num = idx + 32;
717                         return channel;
718                 }
719         }
720
721         /* no more free channels available */
722         printk(KERN_ERR "trident: no more channels available on Bank B.\n");
723         return NULL;
724 }
725
726 static void
727 trident_free_pcm_channel(struct trident_card *card, unsigned int channel)
728 {
729         int bank;
730         unsigned char b;
731
732         if (channel < 31 || channel > 63)
733                 return;
734
735         if (card->pci_id == PCI_DEVICE_ID_TRIDENT_4DWAVE_DX || 
736             card->pci_id == PCI_DEVICE_ID_TRIDENT_4DWAVE_NX) {
737                 b = inb(TRID_REG(card, T4D_REC_CH));
738                 if ((b & ~0x80) == channel)
739                         outb(0x0, TRID_REG(card, T4D_REC_CH));
740         }
741
742         bank = channel >> 5;
743         channel = channel & 0x1f;
744
745         card->banks[bank].bitmap &= ~(1 << (channel));
746 }
747
748 static struct trident_channel *
749 cyber_alloc_pcm_channel(struct trident_card *card)
750 {
751         struct trident_pcm_bank *bank;
752         int idx;
753
754         /* The cyberpro 5050 has only 32 voices and one bank */
755         /* .. at least they are not documented (if you want to call that 
756          * crap documentation), perhaps broken ? */
757
758         bank = &card->banks[BANK_A];
759
760         for (idx = 31; idx >= 0; idx--) {
761                 if (!(bank->bitmap & (1 << idx))) {
762                         struct trident_channel *channel = &bank->channels[idx];
763                         bank->bitmap |= 1 << idx;
764                         channel->num = idx;
765                         return channel;
766                 }
767         }
768
769         /* no more free channels available */
770         printk(KERN_ERR "cyberpro5050: no more channels available on Bank A.\n");
771         return NULL;
772 }
773
774 static void
775 cyber_free_pcm_channel(struct trident_card *card, unsigned int channel)
776 {
777         if (channel > 31)
778                 return;
779         card->banks[BANK_A].bitmap &= ~(1 << (channel));
780 }
781
782 static inline void
783 cyber_outidx(int port, int idx, int data)
784 {
785         outb(idx, port);
786         outb(data, port + 1);
787 }
788
789 static inline int
790 cyber_inidx(int port, int idx)
791 {
792         outb(idx, port);
793         return inb(port + 1);
794 }
795
796 static int
797 cyber_init_ritual(struct trident_card *card)
798 {
799         /* some black magic, taken from SDK samples */
800         /* remove this and nothing will work */
801         int portDat;
802         int ret = 0;
803         unsigned long flags;
804
805         /*
806          *      Keep interrupts off for the configure - we don't want to
807          *      clash with another cyberpro config event
808          */
809
810         spin_lock_irqsave(&card->lock, flags);
811         portDat = cyber_inidx(CYBER_PORT_AUDIO, CYBER_IDX_AUDIO_ENABLE);
812         /* enable, if it was disabled */
813         if ((portDat & CYBER_BMSK_AUENZ) != CYBER_BMSK_AUENZ_ENABLE) {
814                 printk(KERN_INFO "cyberpro5050: enabling audio controller\n");
815                 cyber_outidx(CYBER_PORT_AUDIO, CYBER_IDX_AUDIO_ENABLE, 
816                              portDat | CYBER_BMSK_AUENZ_ENABLE);
817                 /* check again if hardware is enabled now */
818                 portDat = cyber_inidx(CYBER_PORT_AUDIO, CYBER_IDX_AUDIO_ENABLE);
819         }
820         if ((portDat & CYBER_BMSK_AUENZ) != CYBER_BMSK_AUENZ_ENABLE) {
821                 printk(KERN_ERR "cyberpro5050: initAudioAccess: no success\n");
822                 ret = -1;
823         } else {
824                 cyber_outidx(CYBER_PORT_AUDIO, CYBER_IDX_IRQ_ENABLE, 
825                              CYBER_BMSK_AUDIO_INT_ENABLE);
826                 cyber_outidx(CYBER_PORT_AUDIO, 0xbf, 0x01);
827                 cyber_outidx(CYBER_PORT_AUDIO, 0xba, 0x20);
828                 cyber_outidx(CYBER_PORT_AUDIO, 0xbb, 0x08);
829                 cyber_outidx(CYBER_PORT_AUDIO, 0xbf, 0x02);
830                 cyber_outidx(CYBER_PORT_AUDIO, 0xb3, 0x06);
831                 cyber_outidx(CYBER_PORT_AUDIO, 0xbf, 0x00);
832         }
833         spin_unlock_irqrestore(&card->lock, flags);
834         return ret;
835 }
836
837 /*  called with spin lock held */
838
839 static int
840 trident_load_channel_registers(struct trident_card *card, u32 * data, 
841                                unsigned int channel)
842 {
843         int i;
844
845         if (channel > 63)
846                 return 0;
847
848         /* select hardware channel to write */
849         outb(channel, TRID_REG(card, T4D_LFO_GC_CIR));
850
851         /* Output the channel registers, but don't write register
852            three to an ALI chip. */
853         for (i = 0; i < CHANNEL_REGS; i++) {
854                 if (i == 3 && card->pci_id == PCI_DEVICE_ID_ALI_5451)
855                         continue;
856                 outl(data[i], TRID_REG(card, CHANNEL_START + 4 * i));
857         }
858         if (card->pci_id == PCI_DEVICE_ID_ALI_5451 || 
859             card->pci_id == PCI_DEVICE_ID_INTERG_5050) {
860                 outl(ALI_EMOD_Still, TRID_REG(card, ALI_EBUF1));
861                 outl(ALI_EMOD_Still, TRID_REG(card, ALI_EBUF2));
862         }
863         return 1;
864 }
865
866 /* called with spin lock held */
867 static int
868 trident_write_voice_regs(struct trident_state *state)
869 {
870         unsigned int data[CHANNEL_REGS + 1];
871         struct trident_channel *channel;
872
873         channel = state->dmabuf.channel;
874
875         data[1] = channel->lba;
876         data[4] = channel->control;
877
878         switch (state->card->pci_id) {
879         case PCI_DEVICE_ID_ALI_5451:
880                 data[0] = 0;    /* Current Sample Offset */
881                 data[2] = (channel->eso << 16) | (channel->delta & 0xffff);
882                 data[3] = 0;
883                 break;
884         case PCI_DEVICE_ID_SI_7018:
885         case PCI_DEVICE_ID_INTERG_5050:
886                 data[0] = 0;    /* Current Sample Offset */
887                 data[2] = (channel->eso << 16) | (channel->delta & 0xffff);
888                 data[3] = (channel->attribute << 16) | (channel->fm_vol & 0xffff);
889                 break;
890         case PCI_DEVICE_ID_TRIDENT_4DWAVE_DX:
891                 data[0] = 0;    /* Current Sample Offset */
892                 data[2] = (channel->eso << 16) | (channel->delta & 0xffff);
893                 data[3] = channel->fm_vol & 0xffff;
894                 break;
895         case PCI_DEVICE_ID_TRIDENT_4DWAVE_NX:
896                 data[0] = (channel->delta << 24);
897                 data[2] = ((channel->delta << 16) & 0xff000000) | 
898                         (channel->eso & 0x00ffffff);
899                 data[3] = channel->fm_vol & 0xffff;
900                 break;
901         default:
902                 return 0;
903         }
904
905         return trident_load_channel_registers(state->card, data, channel->num);
906 }
907
908 static int
909 compute_rate_play(u32 rate)
910 {
911         int delta;
912         /* We special case 44100 and 8000 since rounding with the equation
913            does not give us an accurate enough value. For 11025 and 22050
914            the equation gives us the best answer. All other frequencies will
915            also use the equation. JDW */
916         if (rate == 44100)
917                 delta = 0xeb3;
918         else if (rate == 8000)
919                 delta = 0x2ab;
920         else if (rate == 48000)
921                 delta = 0x1000;
922         else
923                 delta = (((rate << 12) + rate) / 48000) & 0x0000ffff;
924         return delta;
925 }
926
927 static int
928 compute_rate_rec(u32 rate)
929 {
930         int delta;
931
932         if (rate == 44100)
933                 delta = 0x116a;
934         else if (rate == 8000)
935                 delta = 0x6000;
936         else if (rate == 48000)
937                 delta = 0x1000;
938         else
939                 delta = ((48000 << 12) / rate) & 0x0000ffff;
940
941         return delta;
942 }
943
944 /* set playback sample rate */
945 static unsigned int
946 trident_set_dac_rate(struct trident_state *state, unsigned int rate)
947 {
948         struct dmabuf *dmabuf = &state->dmabuf;
949
950         if (rate > 48000)
951                 rate = 48000;
952         if (rate < 4000)
953                 rate = 4000;
954
955         dmabuf->rate = rate;
956         dmabuf->channel->delta = compute_rate_play(rate);
957
958         trident_write_voice_regs(state);
959
960         pr_debug("trident: called trident_set_dac_rate : rate = %d\n", rate);
961
962         return rate;
963 }
964
965 /* set recording sample rate */
966 static unsigned int
967 trident_set_adc_rate(struct trident_state *state, unsigned int rate)
968 {
969         struct dmabuf *dmabuf = &state->dmabuf;
970
971         if (rate > 48000)
972                 rate = 48000;
973         if (rate < 4000)
974                 rate = 4000;
975
976         dmabuf->rate = rate;
977         dmabuf->channel->delta = compute_rate_rec(rate);
978
979         trident_write_voice_regs(state);
980
981         pr_debug("trident: called trident_set_adc_rate : rate = %d\n", rate);
982
983         return rate;
984 }
985
986 /* prepare channel attributes for playback */
987 static void
988 trident_play_setup(struct trident_state *state)
989 {
990         struct dmabuf *dmabuf = &state->dmabuf;
991         struct trident_channel *channel = dmabuf->channel;
992
993         channel->lba = dmabuf->dma_handle;
994         channel->delta = compute_rate_play(dmabuf->rate);
995
996         channel->eso = dmabuf->dmasize >> sample_shift[dmabuf->fmt];
997         channel->eso -= 1;
998
999         if (state->card->pci_id != PCI_DEVICE_ID_SI_7018) {
1000                 channel->attribute = 0;
1001                 if (state->card->pci_id == PCI_DEVICE_ID_ALI_5451) {
1002                         if ((channel->num == ALI_SPDIF_IN_CHANNEL) || 
1003                             (channel->num == ALI_PCM_IN_CHANNEL))
1004                                 ali_disable_special_channel(state->card, channel->num);
1005                         else if ((inl(TRID_REG(state->card, ALI_GLOBAL_CONTROL)) 
1006                                   & ALI_SPDIF_OUT_CH_ENABLE)
1007                                  && (channel->num == ALI_SPDIF_OUT_CHANNEL)) {
1008                                 ali_set_spdif_out_rate(state->card, 
1009                                                        state->dmabuf.rate);
1010                                 state->dmabuf.channel->delta = 0x1000;
1011                         }
1012                 }
1013         }
1014
1015         channel->fm_vol = 0x0;
1016
1017         channel->control = CHANNEL_LOOP;
1018         if (dmabuf->fmt & TRIDENT_FMT_16BIT) {
1019                 /* 16-bits */
1020                 channel->control |= CHANNEL_16BITS;
1021                 /* signed */
1022                 channel->control |= CHANNEL_SIGNED;
1023         }
1024         if (dmabuf->fmt & TRIDENT_FMT_STEREO)
1025                 /* stereo */
1026                 channel->control |= CHANNEL_STEREO;
1027
1028         pr_debug("trident: trident_play_setup, LBA = 0x%08x, Delta = 0x%08x, "
1029                  "ESO = 0x%08x, Control = 0x%08x\n", channel->lba,
1030                  channel->delta, channel->eso, channel->control);
1031
1032         trident_write_voice_regs(state);
1033 }
1034
1035 /* prepare channel attributes for recording */
1036 static void
1037 trident_rec_setup(struct trident_state *state)
1038 {
1039         u16 w;
1040         u8 bval;
1041
1042         struct trident_card *card = state->card;
1043         struct dmabuf *dmabuf = &state->dmabuf;
1044         struct trident_channel *channel = dmabuf->channel;
1045         unsigned int rate;
1046
1047         /* Enable AC-97 ADC (capture) */
1048         switch (card->pci_id) {
1049         case PCI_DEVICE_ID_ALI_5451:
1050                 ali_enable_special_channel(state);
1051                 break;
1052         case PCI_DEVICE_ID_SI_7018:
1053                 /* for 7018, the ac97 is always in playback/record (duplex) mode */
1054                 break;
1055         case PCI_DEVICE_ID_TRIDENT_4DWAVE_DX:
1056                 w = inb(TRID_REG(card, DX_ACR2_AC97_COM_STAT));
1057                 outb(w | 0x48, TRID_REG(card, DX_ACR2_AC97_COM_STAT));
1058                 /* enable and set record channel */
1059                 outb(0x80 | channel->num, TRID_REG(card, T4D_REC_CH));
1060                 break;
1061         case PCI_DEVICE_ID_TRIDENT_4DWAVE_NX:
1062                 w = inw(TRID_REG(card, T4D_MISCINT));
1063                 outw(w | 0x1000, TRID_REG(card, T4D_MISCINT));
1064                 /* enable and set record channel */
1065                 outb(0x80 | channel->num, TRID_REG(card, T4D_REC_CH));
1066                 break;
1067         case PCI_DEVICE_ID_INTERG_5050:
1068                 /* don't know yet, using special channel 22 in GC1(0xd4)? */
1069                 break;
1070         default:
1071                 return;
1072         }
1073
1074         channel->lba = dmabuf->dma_handle;
1075         channel->delta = compute_rate_rec(dmabuf->rate);
1076         if ((card->pci_id == PCI_DEVICE_ID_ALI_5451) && 
1077             (channel->num == ALI_SPDIF_IN_CHANNEL)) {
1078                 rate = ali_get_spdif_in_rate(card);
1079                 if (rate == 0) {
1080                         printk(KERN_WARNING "trident: ALi 5451 "
1081                                "S/PDIF input setup error!\n");
1082                         rate = 48000;
1083                 }
1084                 bval = inb(TRID_REG(card, ALI_SPDIF_CTRL));
1085                 if (bval & 0x10) {
1086                         outb(bval, TRID_REG(card, ALI_SPDIF_CTRL));
1087                         printk(KERN_WARNING "trident: cleared ALi "
1088                                "5451 S/PDIF parity error flag.\n");
1089                 }
1090
1091                 if (rate != 48000)
1092                         channel->delta = ((rate << 12) / dmabuf->rate) & 0x0000ffff;
1093         }
1094
1095         channel->eso = dmabuf->dmasize >> sample_shift[dmabuf->fmt];
1096         channel->eso -= 1;
1097
1098         if (state->card->pci_id != PCI_DEVICE_ID_SI_7018) {
1099                 channel->attribute = 0;
1100         }
1101
1102         channel->fm_vol = 0x0;
1103
1104         channel->control = CHANNEL_LOOP;
1105         if (dmabuf->fmt & TRIDENT_FMT_16BIT) {
1106                 /* 16-bits */
1107                 channel->control |= CHANNEL_16BITS;
1108                 /* signed */
1109                 channel->control |= CHANNEL_SIGNED;
1110         }
1111         if (dmabuf->fmt & TRIDENT_FMT_STEREO)
1112                 /* stereo */
1113                 channel->control |= CHANNEL_STEREO;
1114
1115         pr_debug("trident: trident_rec_setup, LBA = 0x%08x, Delat = 0x%08x, "
1116                  "ESO = 0x%08x, Control = 0x%08x\n", channel->lba,
1117                  channel->delta, channel->eso, channel->control);
1118
1119         trident_write_voice_regs(state);
1120 }
1121
1122 /* get current playback/recording dma buffer pointer (byte offset from LBA),
1123    called with spinlock held! */
1124 static inline unsigned
1125 trident_get_dma_addr(struct trident_state *state)
1126 {
1127         struct dmabuf *dmabuf = &state->dmabuf;
1128         u32 cso;
1129
1130         if (!dmabuf->enable)
1131                 return 0;
1132
1133         outb(dmabuf->channel->num, TRID_REG(state->card, T4D_LFO_GC_CIR));
1134
1135         switch (state->card->pci_id) {
1136         case PCI_DEVICE_ID_ALI_5451:
1137         case PCI_DEVICE_ID_SI_7018:
1138         case PCI_DEVICE_ID_TRIDENT_4DWAVE_DX:
1139         case PCI_DEVICE_ID_INTERG_5050:
1140                 /* 16 bits ESO, CSO for 7018 and DX */
1141                 cso = inw(TRID_REG(state->card, CH_DX_CSO_ALPHA_FMS + 2));
1142                 break;
1143         case PCI_DEVICE_ID_TRIDENT_4DWAVE_NX:
1144                 /* 24 bits ESO, CSO for NX */
1145                 cso = inl(TRID_REG(state->card, CH_NX_DELTA_CSO)) & 0x00ffffff;
1146                 break;
1147         default:
1148                 return 0;
1149         }
1150
1151         pr_debug("trident: trident_get_dma_addr: chip reported channel: %d, "
1152                  "cso = 0x%04x\n", dmabuf->channel->num, cso);
1153
1154         /* ESO and CSO are in units of Samples, convert to byte offset */
1155         cso <<= sample_shift[dmabuf->fmt];
1156
1157         return (cso % dmabuf->dmasize);
1158 }
1159
1160 /* Stop recording (lock held) */
1161 static inline void
1162 __stop_adc(struct trident_state *state)
1163 {
1164         struct dmabuf *dmabuf = &state->dmabuf;
1165         unsigned int chan_num = dmabuf->channel->num;
1166         struct trident_card *card = state->card;
1167
1168         dmabuf->enable &= ~ADC_RUNNING;
1169         trident_stop_voice(card, chan_num);
1170         trident_disable_voice_irq(card, chan_num);
1171 }
1172
1173 static void
1174 stop_adc(struct trident_state *state)
1175 {
1176         struct trident_card *card = state->card;
1177         unsigned long flags;
1178
1179         spin_lock_irqsave(&card->lock, flags);
1180         __stop_adc(state);
1181         spin_unlock_irqrestore(&card->lock, flags);
1182 }
1183
1184 static void
1185 start_adc(struct trident_state *state)
1186 {
1187         struct dmabuf *dmabuf = &state->dmabuf;
1188         unsigned int chan_num = dmabuf->channel->num;
1189         struct trident_card *card = state->card;
1190         unsigned long flags;
1191
1192         spin_lock_irqsave(&card->lock, flags);
1193         if ((dmabuf->mapped || 
1194              dmabuf->count < (signed) dmabuf->dmasize) && 
1195             dmabuf->ready) {
1196                 dmabuf->enable |= ADC_RUNNING;
1197                 trident_enable_voice_irq(card, chan_num);
1198                 trident_start_voice(card, chan_num);
1199         }
1200         spin_unlock_irqrestore(&card->lock, flags);
1201 }
1202
1203 /* stop playback (lock held) */
1204 static inline void
1205 __stop_dac(struct trident_state *state)
1206 {
1207         struct dmabuf *dmabuf = &state->dmabuf;
1208         unsigned int chan_num = dmabuf->channel->num;
1209         struct trident_card *card = state->card;
1210
1211         dmabuf->enable &= ~DAC_RUNNING;
1212         trident_stop_voice(card, chan_num);
1213         if (state->chans_num == 6) {
1214                 trident_stop_voice(card, state->other_states[0]->
1215                                    dmabuf.channel->num);
1216                 trident_stop_voice(card, state->other_states[1]->
1217                                    dmabuf.channel->num);
1218                 trident_stop_voice(card, state->other_states[2]->
1219                                    dmabuf.channel->num);
1220                 trident_stop_voice(card, state->other_states[3]->
1221                                    dmabuf.channel->num);
1222         }
1223         trident_disable_voice_irq(card, chan_num);
1224 }
1225
1226 static void
1227 stop_dac(struct trident_state *state)
1228 {
1229         struct trident_card *card = state->card;
1230         unsigned long flags;
1231
1232         spin_lock_irqsave(&card->lock, flags);
1233         __stop_dac(state);
1234         spin_unlock_irqrestore(&card->lock, flags);
1235 }
1236
1237 static void
1238 start_dac(struct trident_state *state)
1239 {
1240         struct dmabuf *dmabuf = &state->dmabuf;
1241         unsigned int chan_num = dmabuf->channel->num;
1242         struct trident_card *card = state->card;
1243         unsigned long flags;
1244
1245         spin_lock_irqsave(&card->lock, flags);
1246         if ((dmabuf->mapped || dmabuf->count > 0) && dmabuf->ready) {
1247                 dmabuf->enable |= DAC_RUNNING;
1248                 trident_enable_voice_irq(card, chan_num);
1249                 trident_start_voice(card, chan_num);
1250                 if (state->chans_num == 6) {
1251                         trident_start_voice(card, state->other_states[0]->
1252                                             dmabuf.channel->num);
1253                         trident_start_voice(card, state->other_states[1]->
1254                                             dmabuf.channel->num);
1255                         trident_start_voice(card, state->other_states[2]->
1256                                             dmabuf.channel->num);
1257                         trident_start_voice(card, state->other_states[3]->
1258                                             dmabuf.channel->num);
1259                 }
1260         }
1261         spin_unlock_irqrestore(&card->lock, flags);
1262 }
1263
1264 #define DMABUF_DEFAULTORDER (15-PAGE_SHIFT)
1265 #define DMABUF_MINORDER 1
1266
1267 /* alloc a DMA buffer of with a buffer of this order */
1268 static int
1269 alloc_dmabuf(struct dmabuf *dmabuf, struct pci_dev *pci_dev, int order)
1270 {
1271         void *rawbuf = NULL;
1272         struct page *page, *pend;
1273
1274         if (!(rawbuf = pci_alloc_consistent(pci_dev, PAGE_SIZE << order, 
1275                                             &dmabuf->dma_handle)))
1276                 return -ENOMEM;
1277
1278         pr_debug("trident: allocated %ld (order = %d) bytes at %p\n",
1279                  PAGE_SIZE << order, order, rawbuf);
1280
1281         dmabuf->ready = dmabuf->mapped = 0;
1282         dmabuf->rawbuf = rawbuf;
1283         dmabuf->buforder = order;
1284
1285         /* now mark the pages as reserved; otherwise */ 
1286         /* remap_pfn_range doesn't do what we want */
1287         pend = virt_to_page(rawbuf + (PAGE_SIZE << order) - 1);
1288         for (page = virt_to_page(rawbuf); page <= pend; page++)
1289                 SetPageReserved(page);
1290
1291         return 0;
1292 }
1293
1294 /* allocate the main DMA buffer, playback and recording buffer should be */
1295 /* allocated separately */
1296 static int
1297 alloc_main_dmabuf(struct trident_state *state)
1298 {
1299         struct dmabuf *dmabuf = &state->dmabuf;
1300         int order;
1301         int ret = -ENOMEM;
1302
1303         /* alloc as big a chunk as we can, FIXME: is this necessary ?? */
1304         for (order = DMABUF_DEFAULTORDER; order >= DMABUF_MINORDER; order--) {
1305                 if (!(ret = alloc_dmabuf(dmabuf, state->card->pci_dev, order)))
1306                         return 0;
1307                 /* else try again */
1308         }
1309         return ret;
1310 }
1311
1312 /* deallocate a DMA buffer */
1313 static void
1314 dealloc_dmabuf(struct dmabuf *dmabuf, struct pci_dev *pci_dev)
1315 {
1316         struct page *page, *pend;
1317
1318         if (dmabuf->rawbuf) {
1319                 /* undo marking the pages as reserved */
1320                 pend = virt_to_page(dmabuf->rawbuf + (PAGE_SIZE << dmabuf->buforder) - 1);
1321                 for (page = virt_to_page(dmabuf->rawbuf); page <= pend; page++)
1322                         ClearPageReserved(page);
1323                 pci_free_consistent(pci_dev, PAGE_SIZE << dmabuf->buforder, 
1324                                     dmabuf->rawbuf, dmabuf->dma_handle);
1325                 dmabuf->rawbuf = NULL;
1326         }
1327         dmabuf->mapped = dmabuf->ready = 0;
1328 }
1329
1330 static int
1331 prog_dmabuf(struct trident_state *state, enum dmabuf_mode rec)
1332 {
1333         struct dmabuf *dmabuf = &state->dmabuf;
1334         unsigned bytepersec;
1335         struct trident_state *s = state;
1336         unsigned bufsize, dma_nums;
1337         unsigned long flags;
1338         int ret, i, order;
1339
1340         if ((ret = lock_set_fmt(state)) < 0)
1341                 return ret;
1342
1343         if (state->chans_num == 6)
1344                 dma_nums = 5;
1345         else
1346                 dma_nums = 1;
1347
1348         for (i = 0; i < dma_nums; i++) {
1349                 if (i > 0) {
1350                         s = state->other_states[i - 1];
1351                         dmabuf = &s->dmabuf;
1352                         dmabuf->fmt = state->dmabuf.fmt;
1353                         dmabuf->rate = state->dmabuf.rate;
1354                 }
1355
1356                 spin_lock_irqsave(&s->card->lock, flags);
1357                 dmabuf->hwptr = dmabuf->swptr = dmabuf->total_bytes = 0;
1358                 dmabuf->count = dmabuf->error = 0;
1359                 spin_unlock_irqrestore(&s->card->lock, flags);
1360
1361                 /* allocate DMA buffer if not allocated yet */
1362                 if (!dmabuf->rawbuf) {
1363                         if (i == 0) {
1364                                 if ((ret = alloc_main_dmabuf(state))) {
1365                                         unlock_set_fmt(state);
1366                                         return ret;
1367                                 }
1368                         } else {
1369                                 ret = -ENOMEM;
1370                                 order = state->dmabuf.buforder - 1;
1371                                 if (order >= DMABUF_MINORDER) {
1372                                         ret = alloc_dmabuf(dmabuf,
1373                                                            state->card->pci_dev,
1374                                                            order);
1375                                 }
1376                                 if (ret) {
1377                                         /* release the main DMA buffer */
1378                                         dealloc_dmabuf(&state->dmabuf, state->card->pci_dev);
1379                                         /* release the auxiliary DMA buffers */
1380                                         for (i -= 2; i >= 0; i--)
1381                                                 dealloc_dmabuf(&state->other_states[i]->dmabuf, 
1382                                                                state->card->pci_dev);
1383                                         unlock_set_fmt(state);
1384                                         return ret;
1385                                 }
1386                         }
1387                 }
1388                 /* FIXME: figure out all this OSS fragment stuff */
1389                 bytepersec = dmabuf->rate << sample_shift[dmabuf->fmt];
1390                 bufsize = PAGE_SIZE << dmabuf->buforder;
1391                 if (dmabuf->ossfragshift) {
1392                         if ((1000 << dmabuf->ossfragshift) < bytepersec)
1393                                 dmabuf->fragshift = ld2(bytepersec / 1000);
1394                         else
1395                                 dmabuf->fragshift = dmabuf->ossfragshift;
1396                 } else {
1397                         /* lets hand out reasonable big ass buffers by default */
1398                         dmabuf->fragshift = (dmabuf->buforder + PAGE_SHIFT - 2);
1399                 }
1400                 dmabuf->numfrag = bufsize >> dmabuf->fragshift;
1401                 while (dmabuf->numfrag < 4 && dmabuf->fragshift > 3) {
1402                         dmabuf->fragshift--;
1403                         dmabuf->numfrag = bufsize >> dmabuf->fragshift;
1404                 }
1405                 dmabuf->fragsize = 1 << dmabuf->fragshift;
1406                 if (dmabuf->ossmaxfrags >= 4 && dmabuf->ossmaxfrags < dmabuf->numfrag)
1407                         dmabuf->numfrag = dmabuf->ossmaxfrags;
1408                 dmabuf->fragsamples = dmabuf->fragsize >> sample_shift[dmabuf->fmt];
1409                 dmabuf->dmasize = dmabuf->numfrag << dmabuf->fragshift;
1410
1411                 memset(dmabuf->rawbuf, (dmabuf->fmt & TRIDENT_FMT_16BIT) ? 0 : 0x80, 
1412                        dmabuf->dmasize);
1413
1414                 spin_lock_irqsave(&s->card->lock, flags);
1415                 if (rec == DM_RECORD)
1416                         trident_rec_setup(s);
1417                 else /* DM_PLAYBACK */
1418                         trident_play_setup(s);
1419
1420                 spin_unlock_irqrestore(&s->card->lock, flags);
1421
1422                 /* set the ready flag for the dma buffer */
1423                 dmabuf->ready = 1;
1424
1425                 pr_debug("trident: prog_dmabuf(%d), sample rate = %d, "
1426                          "format = %d, numfrag = %d, fragsize = %d "
1427                          "dmasize = %d\n", dmabuf->channel->num,
1428                          dmabuf->rate, dmabuf->fmt, dmabuf->numfrag,
1429                          dmabuf->fragsize, dmabuf->dmasize);
1430         }
1431         unlock_set_fmt(state);
1432         return 0;
1433 }
1434
1435
1436 static inline int prog_dmabuf_record(struct trident_state* state)
1437 {
1438         return prog_dmabuf(state, DM_RECORD);
1439 }
1440
1441 static inline int prog_dmabuf_playback(struct trident_state* state)
1442 {
1443         return prog_dmabuf(state, DM_PLAYBACK);
1444 }
1445
1446 /* we are doing quantum mechanics here, the buffer can only be empty, half or full filled i.e.
1447    |------------|------------|   or   |xxxxxxxxxxxx|------------|   or   |xxxxxxxxxxxx|xxxxxxxxxxxx|
1448    but we almost always get this
1449    |xxxxxx------|------------|   or   |xxxxxxxxxxxx|xxxxx-------|
1450    so we have to clear the tail space to "silence"
1451    |xxxxxx000000|------------|   or   |xxxxxxxxxxxx|xxxxxx000000|
1452 */
1453 static void
1454 trident_clear_tail(struct trident_state *state)
1455 {
1456         struct dmabuf *dmabuf = &state->dmabuf;
1457         unsigned swptr;
1458         unsigned char silence = (dmabuf->fmt & TRIDENT_FMT_16BIT) ? 0 : 0x80;
1459         unsigned int len;
1460         unsigned long flags;
1461
1462         spin_lock_irqsave(&state->card->lock, flags);
1463         swptr = dmabuf->swptr;
1464         spin_unlock_irqrestore(&state->card->lock, flags);
1465
1466         if (swptr == 0 || swptr == dmabuf->dmasize / 2 || 
1467             swptr == dmabuf->dmasize)
1468                 return;
1469
1470         if (swptr < dmabuf->dmasize / 2)
1471                 len = dmabuf->dmasize / 2 - swptr;
1472         else
1473                 len = dmabuf->dmasize - swptr;
1474
1475         memset(dmabuf->rawbuf + swptr, silence, len);
1476         if (state->card->pci_id != PCI_DEVICE_ID_ALI_5451) {
1477                 spin_lock_irqsave(&state->card->lock, flags);
1478                 dmabuf->swptr += len;
1479                 dmabuf->count += len;
1480                 spin_unlock_irqrestore(&state->card->lock, flags);
1481         }
1482
1483         /* restart the dma machine in case it is halted */
1484         start_dac(state);
1485 }
1486
1487 static int
1488 drain_dac(struct trident_state *state, int nonblock)
1489 {
1490         DECLARE_WAITQUEUE(wait, current);
1491         struct dmabuf *dmabuf = &state->dmabuf;
1492         unsigned long flags;
1493         unsigned long tmo;
1494         int count;
1495         unsigned long diff = 0;
1496
1497         if (dmabuf->mapped || !dmabuf->ready)
1498                 return 0;
1499
1500         add_wait_queue(&dmabuf->wait, &wait);
1501         for (;;) {
1502                 /* It seems that we have to set the current state to TASK_INTERRUPTIBLE
1503                    every time to make the process really go to sleep */
1504                 set_current_state(TASK_INTERRUPTIBLE);
1505
1506                 spin_lock_irqsave(&state->card->lock, flags);
1507                 count = dmabuf->count;
1508                 spin_unlock_irqrestore(&state->card->lock, flags);
1509
1510                 if (count <= 0)
1511                         break;
1512
1513                 if (signal_pending(current))
1514                         break;
1515
1516                 if (nonblock) {
1517                         remove_wait_queue(&dmabuf->wait, &wait);
1518                         set_current_state(TASK_RUNNING);
1519                         return -EBUSY;
1520                 }
1521
1522                 /* No matter how much data is left in the buffer, we have to wait until
1523                    CSO == ESO/2 or CSO == ESO when address engine interrupts */
1524                 if (state->card->pci_id == PCI_DEVICE_ID_ALI_5451 || 
1525                     state->card->pci_id == PCI_DEVICE_ID_INTERG_5050) {
1526                         diff = dmabuf->swptr - trident_get_dma_addr(state) + dmabuf->dmasize;
1527                         diff = diff % (dmabuf->dmasize);
1528                         tmo = (diff * HZ) / dmabuf->rate;
1529                 } else {
1530                         tmo = (dmabuf->dmasize * HZ) / dmabuf->rate;
1531                 }
1532                 tmo >>= sample_shift[dmabuf->fmt];
1533                 if (!schedule_timeout(tmo ? tmo : 1) && tmo) {
1534                         break;
1535                 }
1536         }
1537         remove_wait_queue(&dmabuf->wait, &wait);
1538         set_current_state(TASK_RUNNING);
1539         if (signal_pending(current))
1540                 return -ERESTARTSYS;
1541
1542         return 0;
1543 }
1544
1545 /* update buffer manangement pointers, especially, */ 
1546 /* dmabuf->count and dmabuf->hwptr */
1547 static void
1548 trident_update_ptr(struct trident_state *state)
1549 {
1550         struct dmabuf *dmabuf = &state->dmabuf;
1551         unsigned hwptr, swptr;
1552         int clear_cnt = 0;
1553         int diff;
1554         unsigned char silence;
1555         unsigned half_dmasize;
1556
1557         /* update hardware pointer */
1558         hwptr = trident_get_dma_addr(state);
1559         diff = (dmabuf->dmasize + hwptr - dmabuf->hwptr) % dmabuf->dmasize;
1560         dmabuf->hwptr = hwptr;
1561         dmabuf->total_bytes += diff;
1562
1563         /* error handling and process wake up for ADC */
1564         if (dmabuf->enable == ADC_RUNNING) {
1565                 if (dmabuf->mapped) {
1566                         dmabuf->count -= diff;
1567                         if (dmabuf->count >= (signed) dmabuf->fragsize)
1568                                 wake_up(&dmabuf->wait);
1569                 } else {
1570                         dmabuf->count += diff;
1571
1572                         if (dmabuf->count < 0 || 
1573                             dmabuf->count > dmabuf->dmasize) {
1574                                 /* buffer underrun or buffer overrun, */ 
1575                                 /* we have no way to recover it here, just */ 
1576                                 /* stop the machine and let the process */ 
1577                                 /* force hwptr and swptr to sync */
1578                                 __stop_adc(state);
1579                                 dmabuf->error++;
1580                         }
1581                         if (dmabuf->count < (signed) dmabuf->dmasize / 2)
1582                                 wake_up(&dmabuf->wait);
1583                 }
1584         }
1585
1586         /* error handling and process wake up for DAC */
1587         if (dmabuf->enable == DAC_RUNNING) {
1588                 if (dmabuf->mapped) {
1589                         dmabuf->count += diff;
1590                         if (dmabuf->count >= (signed) dmabuf->fragsize)
1591                                 wake_up(&dmabuf->wait);
1592                 } else {
1593                         dmabuf->count -= diff;
1594
1595                         if (dmabuf->count < 0 || 
1596                             dmabuf->count > dmabuf->dmasize) {
1597                                 /* buffer underrun or buffer overrun, we have no way to recover
1598                                    it here, just stop the machine and let the process force hwptr
1599                                    and swptr to sync */
1600                                 __stop_dac(state);
1601                                 dmabuf->error++;
1602                         } else if (!dmabuf->endcleared) {
1603                                 swptr = dmabuf->swptr;
1604                                 silence = (dmabuf->fmt & TRIDENT_FMT_16BIT ? 0 : 0x80);
1605                                 if (dmabuf->update_flag & ALI_ADDRESS_INT_UPDATE) {
1606                                         /* We must clear end data of 1/2 dmabuf if needed.
1607                                            According to 1/2 algorithm of Address Engine Interrupt,
1608                                            check the validation of the data of half dmasize. */
1609                                         half_dmasize = dmabuf->dmasize / 2;
1610                                         if ((diff = hwptr - half_dmasize) < 0)
1611                                                 diff = hwptr;
1612                                         if ((dmabuf->count + diff) < half_dmasize) {
1613                                                 //there is invalid data in the end of half buffer
1614                                                 if ((clear_cnt = half_dmasize - swptr) < 0)
1615                                                         clear_cnt += half_dmasize;
1616                                                 //clear the invalid data
1617                                                 memset(dmabuf->rawbuf + swptr, silence, clear_cnt);
1618                                                 if (state->chans_num == 6) {
1619                                                         clear_cnt = clear_cnt / 2;
1620                                                         swptr = swptr / 2;
1621                                                         memset(state->other_states[0]->dmabuf.rawbuf + swptr, 
1622                                                                silence, clear_cnt);
1623                                                         memset(state->other_states[1]->dmabuf.rawbuf + swptr, 
1624                                                                silence, clear_cnt);
1625                                                         memset(state->other_states[2]->dmabuf.rawbuf + swptr, 
1626                                                                silence, clear_cnt);
1627                                                         memset(state->other_states[3]->dmabuf.rawbuf + swptr, 
1628                                                                silence, clear_cnt);
1629                                                 }
1630                                                 dmabuf->endcleared = 1;
1631                                         }
1632                                 } else if (dmabuf->count < (signed) dmabuf->fragsize) {
1633                                         clear_cnt = dmabuf->fragsize;
1634                                         if ((swptr + clear_cnt) > dmabuf->dmasize)
1635                                                 clear_cnt = dmabuf->dmasize - swptr;
1636                                         memset(dmabuf->rawbuf + swptr, silence, clear_cnt);
1637                                         if (state->chans_num == 6) {
1638                                                 clear_cnt = clear_cnt / 2;
1639                                                 swptr = swptr / 2;
1640                                                 memset(state->other_states[0]->dmabuf.rawbuf + swptr, 
1641                                                        silence, clear_cnt);
1642                                                 memset(state->other_states[1]->dmabuf.rawbuf + swptr, 
1643                                                        silence, clear_cnt);
1644                                                 memset(state->other_states[2]->dmabuf.rawbuf + swptr, 
1645                                                        silence, clear_cnt);
1646                                                 memset(state->other_states[3]->dmabuf.rawbuf + swptr, 
1647                                                        silence, clear_cnt);
1648                                         }
1649                                         dmabuf->endcleared = 1;
1650                                 }
1651                         }
1652                         /* trident_update_ptr is called by interrupt handler or by process via
1653                            ioctl/poll, we only wake up the waiting process when we have more
1654                            than 1/2 buffer free (always true for interrupt handler) */
1655                         if (dmabuf->count < (signed) dmabuf->dmasize / 2)
1656                                 wake_up(&dmabuf->wait);
1657                 }
1658         }
1659         dmabuf->update_flag &= ~ALI_ADDRESS_INT_UPDATE;
1660 }
1661
1662 static void
1663 trident_address_interrupt(struct trident_card *card)
1664 {
1665         int i;
1666         struct trident_state *state;
1667         unsigned int channel;
1668
1669         /* Update the pointers for all channels we are running. */
1670         /* FIXME: should read interrupt status only once */
1671         for (i = 0; i < NR_HW_CH; i++) {
1672                 channel = 63 - i;
1673                 if (trident_check_channel_interrupt(card, channel)) {
1674                         trident_ack_channel_interrupt(card, channel);
1675                         if ((state = card->states[i]) != NULL) {
1676                                 trident_update_ptr(state);
1677                         } else {
1678                                 printk(KERN_WARNING "trident: spurious channel " 
1679                                        "irq %d.\n", channel);
1680                                 trident_stop_voice(card, channel);
1681                                 trident_disable_voice_irq(card, channel);
1682                         }
1683                 }
1684         }
1685 }
1686
1687 static void
1688 ali_hwvol_control(struct trident_card *card, int opt)
1689 {
1690         u16 dwTemp, volume[2], mute, diff, *pVol[2];
1691
1692         dwTemp = ali_ac97_read(card->ac97_codec[0], 0x02);
1693         mute = dwTemp & 0x8000;
1694         volume[0] = dwTemp & 0x001f;
1695         volume[1] = (dwTemp & 0x1f00) >> 8;
1696         if (volume[0] < volume[1]) {
1697                 pVol[0] = &volume[0];
1698                 pVol[1] = &volume[1];
1699         } else {
1700                 pVol[1] = &volume[0];
1701                 pVol[0] = &volume[1];
1702         }
1703         diff = *(pVol[1]) - *(pVol[0]);
1704
1705         if (opt == 1) {         // MUTE
1706                 dwTemp ^= 0x8000;
1707                 ali_ac97_write(card->ac97_codec[0], 
1708                                0x02, dwTemp);
1709         } else if (opt == 2) {  // Down
1710                 if (mute)
1711                         return;
1712                 if (*(pVol[1]) < 0x001f) {
1713                         (*pVol[1])++;
1714                         *(pVol[0]) = *(pVol[1]) - diff;
1715                 }
1716                 dwTemp &= 0xe0e0;
1717                 dwTemp |= (volume[0]) | (volume[1] << 8);
1718                 ali_ac97_write(card->ac97_codec[0], 0x02, dwTemp);
1719                 card->ac97_codec[0]->mixer_state[0] = ((32 - volume[0]) * 25 / 8) | 
1720                         (((32 - volume[1]) * 25 / 8) << 8);
1721         } else if (opt == 4) {  // Up
1722                 if (mute)
1723                         return;
1724                 if (*(pVol[0]) > 0) {
1725                         (*pVol[0])--;
1726                         *(pVol[1]) = *(pVol[0]) + diff;
1727                 }
1728                 dwTemp &= 0xe0e0;
1729                 dwTemp |= (volume[0]) | (volume[1] << 8);
1730                 ali_ac97_write(card->ac97_codec[0], 0x02, dwTemp);
1731                 card->ac97_codec[0]->mixer_state[0] = ((32 - volume[0]) * 25 / 8) | 
1732                         (((32 - volume[1]) * 25 / 8) << 8);
1733         } else {
1734                 /* Nothing needs doing */
1735         }
1736 }
1737
1738 /*
1739  *      Re-enable reporting of vol change after 0.1 seconds
1740  */
1741
1742 static void
1743 ali_timeout(unsigned long ptr)
1744 {
1745         struct trident_card *card = (struct trident_card *) ptr;
1746         u16 temp = 0;
1747
1748         /* Enable GPIO IRQ (MISCINT bit 18h) */
1749         temp = inw(TRID_REG(card, T4D_MISCINT + 2));
1750         temp |= 0x0004;
1751         outw(temp, TRID_REG(card, T4D_MISCINT + 2));
1752 }
1753
1754 /*
1755  *      Set up the timer to clear the vol change notification
1756  */
1757
1758 static void
1759 ali_set_timer(struct trident_card *card)
1760 {
1761         /* Add Timer Routine to Enable GPIO IRQ */
1762         del_timer(&card->timer);        /* Never queue twice */
1763         card->timer.function = ali_timeout;
1764         card->timer.data = (unsigned long) card;
1765         card->timer.expires = jiffies + HZ / 10;
1766         add_timer(&card->timer);
1767 }
1768
1769 /*
1770  *      Process a GPIO event
1771  */
1772
1773 static void
1774 ali_queue_task(struct trident_card *card, int opt)
1775 {
1776         u16 temp;
1777
1778         /* Disable GPIO IRQ (MISCINT bit 18h) */
1779         temp = inw(TRID_REG(card, T4D_MISCINT + 2));
1780         temp &= (u16) (~0x0004);
1781         outw(temp, TRID_REG(card, T4D_MISCINT + 2));
1782
1783         /* Adjust the volume */
1784         ali_hwvol_control(card, opt);
1785
1786         /* Set the timer for 1/10th sec */
1787         ali_set_timer(card);
1788 }
1789
1790 static void
1791 cyber_address_interrupt(struct trident_card *card)
1792 {
1793         int i, irq_status;
1794         struct trident_state *state;
1795         unsigned int channel;
1796
1797         /* Update the pointers for all channels we are running. */
1798         /* FIXED: read interrupt status only once */
1799         irq_status = inl(TRID_REG(card, T4D_AINT_A));
1800
1801         pr_debug("cyber_address_interrupt: irq_status 0x%X\n", irq_status);
1802
1803         for (i = 0; i < NR_HW_CH; i++) {
1804                 channel = 31 - i;
1805                 if (irq_status & (1 << channel)) {
1806                         /* clear bit by writing a 1, zeroes are ignored */
1807                         outl((1 << channel), TRID_REG(card, T4D_AINT_A));
1808
1809                         pr_debug("cyber_interrupt: channel %d\n", channel);
1810
1811                         if ((state = card->states[i]) != NULL) {
1812                                 trident_update_ptr(state);
1813                         } else {
1814                                 printk(KERN_WARNING "cyber5050: spurious " 
1815                                        "channel irq %d.\n", channel);
1816                                 trident_stop_voice(card, channel);
1817                                 trident_disable_voice_irq(card, channel);
1818                         }
1819                 }
1820         }
1821 }
1822
1823 static irqreturn_t
1824 trident_interrupt(int irq, void *dev_id, struct pt_regs *regs)
1825 {
1826         struct trident_card *card = (struct trident_card *) dev_id;
1827         u32 event;
1828         u32 gpio;
1829
1830         spin_lock(&card->lock);
1831         event = inl(TRID_REG(card, T4D_MISCINT));
1832
1833         pr_debug("trident: trident_interrupt called, MISCINT = 0x%08x\n",
1834                  event);
1835
1836         if (event & ADDRESS_IRQ) {
1837                 card->address_interrupt(card);
1838         }
1839
1840         if (card->pci_id == PCI_DEVICE_ID_ALI_5451) {
1841                 /* GPIO IRQ (H/W Volume Control) */
1842                 event = inl(TRID_REG(card, T4D_MISCINT));
1843                 if (event & (1 << 25)) {
1844                         gpio = inl(TRID_REG(card, ALI_GPIO));
1845                         if (!timer_pending(&card->timer))
1846                                 ali_queue_task(card, gpio & 0x07);
1847                 }
1848                 event = inl(TRID_REG(card, T4D_MISCINT));
1849                 outl(event | (ST_TARGET_REACHED | MIXER_OVERFLOW | MIXER_UNDERFLOW), 
1850                      TRID_REG(card, T4D_MISCINT));
1851                 spin_unlock(&card->lock);
1852                 return IRQ_HANDLED;
1853         }
1854
1855         /* manually clear interrupt status, bad hardware design, blame T^2 */
1856         outl((ST_TARGET_REACHED | MIXER_OVERFLOW | MIXER_UNDERFLOW), 
1857              TRID_REG(card, T4D_MISCINT));
1858         spin_unlock(&card->lock);
1859         return IRQ_HANDLED;
1860 }
1861
1862 /* in this loop, dmabuf.count signifies the amount of data that is waiting */ 
1863 /* to be copied to the user's buffer.  it is filled by the dma machine and */ 
1864 /* drained by this loop. */
1865 static ssize_t
1866 trident_read(struct file *file, char __user *buffer, size_t count, loff_t * ppos)
1867 {
1868         struct trident_state *state = (struct trident_state *)file->private_data;
1869         struct dmabuf *dmabuf = &state->dmabuf;
1870         ssize_t ret = 0;
1871         unsigned long flags;
1872         unsigned swptr;
1873         int cnt;
1874
1875         pr_debug("trident: trident_read called, count = %d\n", count);
1876
1877         VALIDATE_STATE(state);
1878
1879         if (dmabuf->mapped)
1880                 return -ENXIO;
1881         if (!access_ok(VERIFY_WRITE, buffer, count))
1882                 return -EFAULT;
1883
1884         down(&state->sem);
1885         if (!dmabuf->ready && (ret = prog_dmabuf_record(state)))
1886                 goto out;
1887
1888         while (count > 0) {
1889                 spin_lock_irqsave(&state->card->lock, flags);
1890                 if (dmabuf->count > (signed) dmabuf->dmasize) {
1891                         /* buffer overrun, we are recovering from */ 
1892                         /* sleep_on_timeout, resync hwptr and swptr, */ 
1893                         /* make process flush the buffer */
1894                         dmabuf->count = dmabuf->dmasize;
1895                         dmabuf->swptr = dmabuf->hwptr;
1896                 }
1897                 swptr = dmabuf->swptr;
1898                 cnt = dmabuf->dmasize - swptr;
1899                 if (dmabuf->count < cnt)
1900                         cnt = dmabuf->count;
1901                 spin_unlock_irqrestore(&state->card->lock, flags);
1902
1903                 if (cnt > count)
1904                         cnt = count;
1905                 if (cnt <= 0) {
1906                         unsigned long tmo;
1907                         /* buffer is empty, start the dma machine and */ 
1908                         /* wait for data to be recorded */
1909                         start_adc(state);
1910                         if (file->f_flags & O_NONBLOCK) {
1911                                 if (!ret)
1912                                         ret = -EAGAIN;
1913                                 goto out;
1914                         }
1915
1916                         up(&state->sem);
1917                         /* No matter how much space left in the buffer, */ 
1918                         /* we have to wait until CSO == ESO/2 or CSO == ESO */ 
1919                         /* when address engine interrupts */
1920                         tmo = (dmabuf->dmasize * HZ) / (dmabuf->rate * 2);
1921                         tmo >>= sample_shift[dmabuf->fmt];
1922                         /* There are two situations when sleep_on_timeout returns, one is when
1923                            the interrupt is serviced correctly and the process is waked up by
1924                            ISR ON TIME. Another is when timeout is expired, which means that
1925                            either interrupt is NOT serviced correctly (pending interrupt) or it
1926                            is TOO LATE for the process to be scheduled to run (scheduler latency)
1927                            which results in a (potential) buffer overrun. And worse, there is
1928                            NOTHING we can do to prevent it. */
1929                         if (!interruptible_sleep_on_timeout(&dmabuf->wait, tmo)) {
1930                                 pr_debug(KERN_ERR "trident: recording schedule timeout, "
1931                                          "dmasz %u fragsz %u count %i hwptr %u swptr %u\n",
1932                                          dmabuf->dmasize, dmabuf->fragsize, dmabuf->count,
1933                                          dmabuf->hwptr, dmabuf->swptr);
1934
1935                                 /* a buffer overrun, we delay the recovery until next time the
1936                                    while loop begin and we REALLY have space to record */
1937                         }
1938                         if (signal_pending(current)) {
1939                                 if (!ret)
1940                                         ret = -ERESTARTSYS;
1941                                 goto out;
1942                         }
1943                         down(&state->sem);
1944                         if (dmabuf->mapped) {
1945                                 if (!ret)
1946                                         ret = -ENXIO;
1947                                 goto out;
1948                         }
1949                         continue;
1950                 }
1951
1952                 if (copy_to_user(buffer, dmabuf->rawbuf + swptr, cnt)) {
1953                         if (!ret)
1954                                 ret = -EFAULT;
1955                         goto out;
1956                 }
1957
1958                 swptr = (swptr + cnt) % dmabuf->dmasize;
1959
1960                 spin_lock_irqsave(&state->card->lock, flags);
1961                 dmabuf->swptr = swptr;
1962                 dmabuf->count -= cnt;
1963                 spin_unlock_irqrestore(&state->card->lock, flags);
1964
1965                 count -= cnt;
1966                 buffer += cnt;
1967                 ret += cnt;
1968                 start_adc(state);
1969         }
1970 out:
1971         up(&state->sem);
1972         return ret;
1973 }
1974
1975 /* in this loop, dmabuf.count signifies the amount of data that is waiting to be dma to
1976    the soundcard.  it is drained by the dma machine and filled by this loop. */
1977
1978 static ssize_t
1979 trident_write(struct file *file, const char __user *buffer, size_t count, loff_t * ppos)
1980 {
1981         struct trident_state *state = (struct trident_state *)file->private_data;
1982         struct dmabuf *dmabuf = &state->dmabuf;
1983         ssize_t ret;
1984         unsigned long flags;
1985         unsigned swptr;
1986         int cnt;
1987         unsigned int state_cnt;
1988         unsigned int copy_count;
1989         int lret; /* for lock_set_fmt */
1990
1991         pr_debug("trident: trident_write called, count = %d\n", count);
1992
1993         VALIDATE_STATE(state);
1994
1995         /*
1996          *      Guard against an mmap or ioctl while writing
1997          */
1998
1999         down(&state->sem);
2000
2001         if (dmabuf->mapped) {
2002                 ret = -ENXIO;
2003                 goto out;
2004         }
2005         if (!dmabuf->ready && (ret = prog_dmabuf_playback(state)))
2006                 goto out;
2007
2008         if (!access_ok(VERIFY_READ, buffer, count)) {
2009                 ret = -EFAULT;
2010                 goto out;
2011         }
2012
2013         ret = 0;
2014
2015         while (count > 0) {
2016                 spin_lock_irqsave(&state->card->lock, flags);
2017                 if (dmabuf->count < 0) {
2018                         /* buffer underrun, we are recovering from */ 
2019                         /* sleep_on_timeout, resync hwptr and swptr */
2020                         dmabuf->count = 0;
2021                         dmabuf->swptr = dmabuf->hwptr;
2022                 }
2023                 swptr = dmabuf->swptr;
2024                 cnt = dmabuf->dmasize - swptr;
2025                 if (dmabuf->count + cnt > dmabuf->dmasize)
2026                         cnt = dmabuf->dmasize - dmabuf->count;
2027                 spin_unlock_irqrestore(&state->card->lock, flags);
2028
2029                 if (cnt > count)
2030                         cnt = count;
2031                 if (cnt <= 0) {
2032                         unsigned long tmo;
2033                         /* buffer is full, start the dma machine and */ 
2034                         /* wait for data to be played */
2035                         start_dac(state);
2036                         if (file->f_flags & O_NONBLOCK) {
2037                                 if (!ret)
2038                                         ret = -EAGAIN;
2039                                 goto out;
2040                         }
2041                         /* No matter how much data left in the buffer, */ 
2042                         /* we have to wait until CSO == ESO/2 or CSO == ESO */ 
2043                         /* when address engine interrupts */
2044                         lock_set_fmt(state);
2045                         tmo = (dmabuf->dmasize * HZ) / (dmabuf->rate * 2);
2046                         tmo >>= sample_shift[dmabuf->fmt];
2047                         unlock_set_fmt(state);
2048                         up(&state->sem);
2049
2050                         /* There are two situations when sleep_on_timeout */ 
2051                         /* returns, one is when the interrupt is serviced */ 
2052                         /* correctly and the process is waked up by ISR */ 
2053                         /* ON TIME. Another is when timeout is expired, which */ 
2054                         /* means that either interrupt is NOT serviced */ 
2055                         /* correctly (pending interrupt) or it is TOO LATE */ 
2056                         /* for the process to be scheduled to run */ 
2057                         /* (scheduler latency) which results in a (potential) */ 
2058                         /* buffer underrun. And worse, there is NOTHING we */ 
2059                         /* can do to prevent it. */
2060                         if (!interruptible_sleep_on_timeout(&dmabuf->wait, tmo)) {
2061                                 pr_debug(KERN_ERR "trident: playback schedule "
2062                                          "timeout, dmasz %u fragsz %u count %i "
2063                                          "hwptr %u swptr %u\n", dmabuf->dmasize,
2064                                          dmabuf->fragsize, dmabuf->count,
2065                                          dmabuf->hwptr, dmabuf->swptr);
2066
2067                                 /* a buffer underrun, we delay the recovery */ 
2068                                 /* until next time the while loop begin and */ 
2069                                 /* we REALLY have data to play */
2070                         }
2071                         if (signal_pending(current)) {
2072                                 if (!ret)
2073                                         ret = -ERESTARTSYS;
2074                                 goto out_nolock;
2075                         }
2076                         down(&state->sem);
2077                         if (dmabuf->mapped) {
2078                                 if (!ret)
2079                                         ret = -ENXIO;
2080                                 goto out;
2081                         }
2082                         continue;
2083                 }
2084                 if ((lret = lock_set_fmt(state)) < 0) {
2085                         ret = lret;
2086                         goto out;
2087                 }
2088
2089                 if (state->chans_num == 6) {
2090                         copy_count = 0;
2091                         state_cnt = 0;
2092                         if (ali_write_5_1(state, buffer, cnt, &copy_count, 
2093                                           &state_cnt) == -EFAULT) {
2094                                 if (state_cnt) {
2095                                         swptr = (swptr + state_cnt) % dmabuf->dmasize;
2096                                         spin_lock_irqsave(&state->card->lock, flags);
2097                                         dmabuf->swptr = swptr;
2098                                         dmabuf->count += state_cnt;
2099                                         dmabuf->endcleared = 0;
2100                                         spin_unlock_irqrestore(&state->card->lock, flags);
2101                                 }
2102                                 ret += copy_count;
2103                                 if (!ret)
2104                                         ret = -EFAULT;
2105                                 unlock_set_fmt(state);
2106                                 goto out;
2107                         }
2108                 } else {
2109                         if (copy_from_user(dmabuf->rawbuf + swptr, 
2110                                            buffer, cnt)) {
2111                                 if (!ret)
2112                                         ret = -EFAULT;
2113                                 unlock_set_fmt(state);
2114                                 goto out;
2115                         }
2116                         state_cnt = cnt;
2117                 }
2118                 unlock_set_fmt(state);
2119
2120                 swptr = (swptr + state_cnt) % dmabuf->dmasize;
2121
2122                 spin_lock_irqsave(&state->card->lock, flags);
2123                 dmabuf->swptr = swptr;
2124                 dmabuf->count += state_cnt;
2125                 dmabuf->endcleared = 0;
2126                 spin_unlock_irqrestore(&state->card->lock, flags);
2127
2128                 count -= cnt;
2129                 buffer += cnt;
2130                 ret += cnt;
2131                 start_dac(state);
2132         }
2133 out:
2134         up(&state->sem);
2135 out_nolock:
2136         return ret;
2137 }
2138
2139 /* No kernel lock - we have our own spinlock */
2140 static unsigned int
2141 trident_poll(struct file *file, struct poll_table_struct *wait)
2142 {
2143         struct trident_state *state = (struct trident_state *)file->private_data;
2144         struct dmabuf *dmabuf = &state->dmabuf;
2145         unsigned long flags;
2146         unsigned int mask = 0;
2147
2148         VALIDATE_STATE(state);
2149
2150         /*
2151          *      Guard against a parallel poll and write causing multiple
2152          *      prog_dmabuf events
2153          */
2154
2155         down(&state->sem);
2156
2157         if (file->f_mode & FMODE_WRITE) {
2158                 if (!dmabuf->ready && prog_dmabuf_playback(state)) {
2159                         up(&state->sem);
2160                         return 0;
2161                 }
2162                 poll_wait(file, &dmabuf->wait, wait);
2163         }
2164         if (file->f_mode & FMODE_READ) {
2165                 if (!dmabuf->ready && prog_dmabuf_record(state)) {
2166                         up(&state->sem);
2167                         return 0;
2168                 }
2169                 poll_wait(file, &dmabuf->wait, wait);
2170         }
2171
2172         up(&state->sem);
2173
2174         spin_lock_irqsave(&state->card->lock, flags);
2175         trident_update_ptr(state);
2176         if (file->f_mode & FMODE_READ) {
2177                 if (dmabuf->count >= (signed) dmabuf->fragsize)
2178                         mask |= POLLIN | POLLRDNORM;
2179         }
2180         if (file->f_mode & FMODE_WRITE) {
2181                 if (dmabuf->mapped) {
2182                         if (dmabuf->count >= (signed) dmabuf->fragsize)
2183                                 mask |= POLLOUT | POLLWRNORM;
2184                 } else {
2185                         if ((signed) dmabuf->dmasize >= dmabuf->count + 
2186                             (signed) dmabuf->fragsize)
2187                                 mask |= POLLOUT | POLLWRNORM;
2188                 }
2189         }
2190         spin_unlock_irqrestore(&state->card->lock, flags);
2191
2192         return mask;
2193 }
2194
2195 static int
2196 trident_mmap(struct file *file, struct vm_area_struct *vma)
2197 {
2198         struct trident_state *state = (struct trident_state *)file->private_data;
2199         struct dmabuf *dmabuf = &state->dmabuf;
2200         int ret = -EINVAL;
2201         unsigned long size;
2202
2203         VALIDATE_STATE(state);
2204
2205         /*
2206          *      Lock against poll read write or mmap creating buffers. Also lock
2207          *      a read or write against an mmap.
2208          */
2209
2210         down(&state->sem);
2211
2212         if (vma->vm_flags & VM_WRITE) {
2213                 if ((ret = prog_dmabuf_playback(state)) != 0)
2214                         goto out;
2215         } else if (vma->vm_flags & VM_READ) {
2216                 if ((ret = prog_dmabuf_record(state)) != 0)
2217                         goto out;
2218         } else
2219                 goto out;
2220
2221         ret = -EINVAL;
2222         if (vma->vm_pgoff != 0)
2223                 goto out;
2224         size = vma->vm_end - vma->vm_start;
2225         if (size > (PAGE_SIZE << dmabuf->buforder))
2226                 goto out;
2227         ret = -EAGAIN;
2228         if (remap_pfn_range(vma, vma->vm_start,
2229                              virt_to_phys(dmabuf->rawbuf) >> PAGE_SHIFT,
2230                              size, vma->vm_page_prot))
2231                 goto out;
2232         dmabuf->mapped = 1;
2233         ret = 0;
2234 out:
2235         up(&state->sem);
2236         return ret;
2237 }
2238
2239 static int
2240 trident_ioctl(struct inode *inode, struct file *file, 
2241               unsigned int cmd, unsigned long arg)
2242 {
2243         struct trident_state *state = (struct trident_state *)file->private_data;
2244         struct dmabuf *dmabuf = &state->dmabuf;
2245         unsigned long flags;
2246         audio_buf_info abinfo;
2247         count_info cinfo;
2248         int val, mapped, ret = 0;
2249         struct trident_card *card = state->card;
2250         void __user *argp = (void __user *)arg;
2251         int __user *p = argp;
2252
2253         VALIDATE_STATE(state);
2254
2255
2256         mapped = ((file->f_mode & (FMODE_WRITE | FMODE_READ)) && dmabuf->mapped);
2257
2258         pr_debug("trident: trident_ioctl, command = %2d, arg = 0x%08x\n",
2259                  _IOC_NR(cmd), arg ? *p : 0);
2260
2261         switch (cmd) {
2262         case OSS_GETVERSION:
2263                 ret = put_user(SOUND_VERSION, p);
2264                 break;
2265
2266         case SNDCTL_DSP_RESET:
2267                 /* FIXME: spin_lock ? */
2268                 if (file->f_mode & FMODE_WRITE) {
2269                         stop_dac(state);
2270                         synchronize_irq(card->irq);
2271                         dmabuf->ready = 0;
2272                         dmabuf->swptr = dmabuf->hwptr = 0;
2273                         dmabuf->count = dmabuf->total_bytes = 0;
2274                 }
2275                 if (file->f_mode & FMODE_READ) {
2276                         stop_adc(state);
2277                         synchronize_irq(card->irq);
2278                         dmabuf->ready = 0;
2279                         dmabuf->swptr = dmabuf->hwptr = 0;
2280                         dmabuf->count = dmabuf->total_bytes = 0;
2281                 }
2282                 break;
2283
2284         case SNDCTL_DSP_SYNC:
2285                 if (file->f_mode & FMODE_WRITE)
2286                         ret = drain_dac(state, file->f_flags & O_NONBLOCK);
2287                 break;
2288
2289         case SNDCTL_DSP_SPEED:  /* set smaple rate */
2290                 if (get_user(val, p)) {
2291                         ret = -EFAULT;
2292                         break;
2293                 }
2294                 if (val >= 0) {
2295                         if (file->f_mode & FMODE_WRITE) {
2296                                 stop_dac(state);
2297                                 dmabuf->ready = 0;
2298                                 spin_lock_irqsave(&state->card->lock, flags);
2299                                 trident_set_dac_rate(state, val);
2300                                 spin_unlock_irqrestore(&state->card->lock, flags);
2301                         }
2302                         if (file->f_mode & FMODE_READ) {
2303                                 stop_adc(state);
2304                                 dmabuf->ready = 0;
2305                                 spin_lock_irqsave(&state->card->lock, flags);
2306                                 trident_set_adc_rate(state, val);
2307                                 spin_unlock_irqrestore(&state->card->lock, flags);
2308                         }
2309                 }
2310                 ret = put_user(dmabuf->rate, p);
2311                 break;
2312
2313         case SNDCTL_DSP_STEREO: /* set stereo or mono channel */
2314                 if (get_user(val, p)) {
2315                         ret = -EFAULT;
2316                         break;
2317                 }
2318                 if ((ret = lock_set_fmt(state)) < 0)
2319                         return ret;
2320
2321                 if (file->f_mode & FMODE_WRITE) {
2322                         stop_dac(state);
2323                         dmabuf->ready = 0;
2324                         if (val)
2325                                 dmabuf->fmt |= TRIDENT_FMT_STEREO;
2326                         else
2327                                 dmabuf->fmt &= ~TRIDENT_FMT_STEREO;
2328                 }
2329                 if (file->f_mode & FMODE_READ) {
2330                         stop_adc(state);
2331                         dmabuf->ready = 0;
2332                         if (val)
2333                                 dmabuf->fmt |= TRIDENT_FMT_STEREO;
2334                         else
2335                                 dmabuf->fmt &= ~TRIDENT_FMT_STEREO;
2336                 }
2337                 unlock_set_fmt(state);
2338                 break;
2339
2340         case SNDCTL_DSP_GETBLKSIZE:
2341                 if (file->f_mode & FMODE_WRITE) {
2342                         if ((val = prog_dmabuf_playback(state)))
2343                                 ret = val;
2344                         else
2345                                 ret = put_user(dmabuf->fragsize, p);
2346                         break;
2347                 }
2348                 if (file->f_mode & FMODE_READ) {
2349                         if ((val = prog_dmabuf_record(state)))
2350                                 ret = val;
2351                         else
2352                                 ret = put_user(dmabuf->fragsize, p);
2353                         break;
2354                 }
2355                 /* neither READ nor WRITE? is this even possible? */
2356                 ret = -EINVAL;
2357                 break;
2358
2359
2360         case SNDCTL_DSP_GETFMTS: /* Returns a mask of supported sample format */
2361                 ret = put_user(AFMT_S16_LE | AFMT_U16_LE | AFMT_S8 | 
2362                                AFMT_U8, p);
2363                 break;
2364
2365         case SNDCTL_DSP_SETFMT: /* Select sample format */
2366                 if (get_user(val, p)) {
2367                         ret = -EFAULT;
2368                         break;
2369                 }
2370                 if ((ret = lock_set_fmt(state)) < 0)
2371                         return ret;
2372
2373                 if (val != AFMT_QUERY) {
2374                         if (file->f_mode & FMODE_WRITE) {
2375                                 stop_dac(state);
2376                                 dmabuf->ready = 0;
2377                                 if (val == AFMT_S16_LE)
2378                                         dmabuf->fmt |= TRIDENT_FMT_16BIT;
2379                                 else
2380                                         dmabuf->fmt &= ~TRIDENT_FMT_16BIT;
2381                         }
2382                         if (file->f_mode & FMODE_READ) {
2383                                 stop_adc(state);
2384                                 dmabuf->ready = 0;
2385                                 if (val == AFMT_S16_LE)
2386                                         dmabuf->fmt |= TRIDENT_FMT_16BIT;
2387                                 else
2388                                         dmabuf->fmt &= ~TRIDENT_FMT_16BIT;
2389                         }
2390                 }
2391                 unlock_set_fmt(state);
2392                 ret = put_user((dmabuf->fmt & TRIDENT_FMT_16BIT) ? AFMT_S16_LE : 
2393                                AFMT_U8, p);
2394                 break;
2395
2396         case SNDCTL_DSP_CHANNELS:
2397                 if (get_user(val, p)) {
2398                         ret = -EFAULT;
2399                         break;
2400                 }
2401                 if (val != 0) {
2402                         if ((ret = lock_set_fmt(state)) < 0)
2403                                 return ret;
2404
2405                         if (file->f_mode & FMODE_WRITE) {
2406                                 stop_dac(state);
2407                                 dmabuf->ready = 0;
2408
2409                                 //prevent from memory leak
2410                                 if ((state->chans_num > 2) && (state->chans_num != val)) {
2411                                         ali_free_other_states_resources(state);
2412                                         state->chans_num = 1;
2413                                 }
2414
2415                                 if (val >= 2) {
2416
2417                                         dmabuf->fmt |= TRIDENT_FMT_STEREO;
2418                                         if ((val == 6) && (state->card->pci_id == PCI_DEVICE_ID_ALI_5451)) {
2419                                                 if (card->rec_channel_use_count > 0) {
2420                                                         printk(KERN_ERR "trident: Record is "
2421                                                                "working on the card!\n");
2422                                                         ret = -EBUSY;
2423                                                         unlock_set_fmt(state);
2424                                                         break;
2425                                                 }
2426
2427                                                 ret = ali_setup_multi_channels(state->card, 6);
2428                                                 if (ret < 0) {
2429                                                         unlock_set_fmt(state);
2430                                                         break;
2431                                                 }
2432                                                 down(&state->card->open_sem);
2433                                                 ret = ali_allocate_other_states_resources(state, 6);
2434                                                 if (ret < 0) {
2435                                                         up(&state->card->open_sem);
2436                                                         unlock_set_fmt(state);
2437                                                         break;
2438                                                 }
2439                                                 state->card->multi_channel_use_count++;
2440                                                 up(&state->card->open_sem);
2441                                         } else
2442                                                 val = 2;        /*yield to 2-channels */
2443                                 } else
2444                                         dmabuf->fmt &= ~TRIDENT_FMT_STEREO;
2445                                 state->chans_num = val;
2446                         }
2447                         if (file->f_mode & FMODE_READ) {
2448                                 stop_adc(state);
2449                                 dmabuf->ready = 0;
2450                                 if (val >= 2) {
2451                                         if (!((file->f_mode & FMODE_WRITE) && 
2452                                               (val == 6)))
2453                                                 val = 2;
2454                                         dmabuf->fmt |= TRIDENT_FMT_STEREO;
2455                                 } else
2456                                         dmabuf->fmt &= ~TRIDENT_FMT_STEREO;
2457                                 state->chans_num = val;
2458                         }
2459                         unlock_set_fmt(state);
2460                 }
2461                 ret = put_user(val, p);
2462                 break;
2463
2464         case SNDCTL_DSP_POST:
2465                 /* Cause the working fragment to be output */
2466                 break;
2467
2468         case SNDCTL_DSP_SUBDIVIDE:
2469                 if (dmabuf->subdivision) {
2470                         ret = -EINVAL;
2471                         break;
2472                 }
2473                 if (get_user(val, p)) {
2474                         ret = -EFAULT;
2475                         break;
2476                 }
2477                 if (val != 1 && val != 2 && val != 4) {
2478                         ret = -EINVAL;
2479                         break;
2480                 }
2481                 dmabuf->subdivision = val;
2482                 break;
2483
2484         case SNDCTL_DSP_SETFRAGMENT:
2485                 if (get_user(val, p)) {
2486                         ret = -EFAULT;
2487                         break;
2488                 }
2489
2490                 dmabuf->ossfragshift = val & 0xffff;
2491                 dmabuf->ossmaxfrags = (val >> 16) & 0xffff;
2492                 if (dmabuf->ossfragshift < 4)
2493                         dmabuf->ossfragshift = 4;
2494                 if (dmabuf->ossfragshift > 15)
2495                         dmabuf->ossfragshift = 15;
2496                 if (dmabuf->ossmaxfrags < 4)
2497                         dmabuf->ossmaxfrags = 4;
2498
2499                 break;
2500
2501         case SNDCTL_DSP_GETOSPACE:
2502                 if (!(file->f_mode & FMODE_WRITE)) {
2503                         ret = -EINVAL;
2504                         break;
2505                 }
2506                 if (!dmabuf->ready && (val = prog_dmabuf_playback(state)) != 0) {
2507                         ret = val;
2508                         break;
2509                 }
2510                 spin_lock_irqsave(&state->card->lock, flags);
2511                 trident_update_ptr(state);
2512                 abinfo.fragsize = dmabuf->fragsize;
2513                 abinfo.bytes = dmabuf->dmasize - dmabuf->count;
2514                 abinfo.fragstotal = dmabuf->numfrag;
2515                 abinfo.fragments = abinfo.bytes >> dmabuf->fragshift;
2516                 spin_unlock_irqrestore(&state->card->lock, flags);
2517                 ret = copy_to_user(argp, &abinfo, sizeof (abinfo)) ? 
2518                         -EFAULT : 0;
2519                 break;
2520
2521         case SNDCTL_DSP_GETISPACE:
2522                 if (!(file->f_mode & FMODE_READ)) {
2523                         ret = -EINVAL;
2524                         break;
2525                 }
2526                 if (!dmabuf->ready && (val = prog_dmabuf_record(state)) != 0) {
2527                         ret = val;
2528                         break;
2529                 }
2530                 spin_lock_irqsave(&state->card->lock, flags);
2531                 trident_update_ptr(state);
2532                 abinfo.fragsize = dmabuf->fragsize;
2533                 abinfo.bytes = dmabuf->count;
2534                 abinfo.fragstotal = dmabuf->numfrag;
2535                 abinfo.fragments = abinfo.bytes >> dmabuf->fragshift;
2536                 spin_unlock_irqrestore(&state->card->lock, flags);
2537                 ret = copy_to_user(argp, &abinfo, sizeof (abinfo)) ? 
2538                         -EFAULT : 0;
2539                 break;
2540
2541         case SNDCTL_DSP_NONBLOCK:
2542                 file->f_flags |= O_NONBLOCK;
2543                 break;
2544
2545         case SNDCTL_DSP_GETCAPS:
2546                 ret = put_user(DSP_CAP_REALTIME | DSP_CAP_TRIGGER | 
2547                                DSP_CAP_MMAP | DSP_CAP_BIND, p);
2548                 break;
2549
2550         case SNDCTL_DSP_GETTRIGGER:
2551                 val = 0;
2552                 if ((file->f_mode & FMODE_READ) && dmabuf->enable)
2553                         val |= PCM_ENABLE_INPUT;
2554                 if ((file->f_mode & FMODE_WRITE) && dmabuf->enable)
2555                         val |= PCM_ENABLE_OUTPUT;
2556                 ret = put_user(val, p);
2557                 break;
2558
2559         case SNDCTL_DSP_SETTRIGGER:
2560                 if (get_user(val, p)) {
2561                         ret = -EFAULT;
2562                         break;
2563                 }
2564                 if (file->f_mode & FMODE_READ) {
2565                         if (val & PCM_ENABLE_INPUT) {
2566                                 if (!dmabuf->ready && 
2567                                     (ret = prog_dmabuf_record(state)))
2568                                         break;
2569                                 start_adc(state);
2570                         } else
2571                                 stop_adc(state);
2572                 }
2573                 if (file->f_mode & FMODE_WRITE) {
2574                         if (val & PCM_ENABLE_OUTPUT) {
2575                                 if (!dmabuf->ready && 
2576                                     (ret = prog_dmabuf_playback(state)))
2577                                         break;
2578                                 start_dac(state);
2579                         } else
2580                                 stop_dac(state);
2581                 }
2582                 break;
2583
2584         case SNDCTL_DSP_GETIPTR:
2585                 if (!(file->f_mode & FMODE_READ)) {
2586                         ret = -EINVAL;
2587                         break;
2588                 }
2589                 if (!dmabuf->ready && (val = prog_dmabuf_record(state))
2590                     != 0) {
2591                         ret = val;
2592                         break;
2593                 }
2594                 spin_lock_irqsave(&state->card->lock, flags);
2595                 trident_update_ptr(state);
2596                 cinfo.bytes = dmabuf->total_bytes;
2597                 cinfo.blocks = dmabuf->count >> dmabuf->fragshift;
2598                 cinfo.ptr = dmabuf->hwptr;
2599                 if (dmabuf->mapped)
2600                         dmabuf->count &= dmabuf->fragsize - 1;
2601                 spin_unlock_irqrestore(&state->card->lock, flags);
2602                 ret = copy_to_user(argp, &cinfo, sizeof (cinfo)) ? 
2603                         -EFAULT : 0;
2604                 break;
2605
2606         case SNDCTL_DSP_GETOPTR:
2607                 if (!(file->f_mode & FMODE_WRITE)) {
2608                         ret = -EINVAL;
2609                         break;
2610                 }
2611                 if (!dmabuf->ready && (val = prog_dmabuf_playback(state))
2612                     != 0) {
2613                         ret = val;
2614                         break;
2615                 }
2616
2617                 spin_lock_irqsave(&state->card->lock, flags);
2618                 trident_update_ptr(state);
2619                 cinfo.bytes = dmabuf->total_bytes;
2620                 cinfo.blocks = dmabuf->count >> dmabuf->fragshift;
2621                 cinfo.ptr = dmabuf->hwptr;
2622                 if (dmabuf->mapped)
2623                         dmabuf->count &= dmabuf->fragsize - 1;
2624                 spin_unlock_irqrestore(&state->card->lock, flags);
2625                 ret = copy_to_user(argp, &cinfo, sizeof (cinfo)) ? 
2626                         -EFAULT : 0;
2627                 break;
2628
2629         case SNDCTL_DSP_SETDUPLEX:
2630                 ret = -EINVAL;
2631                 break;
2632
2633         case SNDCTL_DSP_GETODELAY:
2634                 if (!(file->f_mode & FMODE_WRITE)) {
2635                         ret = -EINVAL;
2636                         break;
2637                 }
2638                 if (!dmabuf->ready && (val = prog_dmabuf_playback(state)) != 0) {
2639                         ret = val;
2640                         break;
2641                 }
2642                 spin_lock_irqsave(&state->card->lock, flags);
2643                 trident_update_ptr(state);
2644                 val = dmabuf->count;
2645                 spin_unlock_irqrestore(&state->card->lock, flags);
2646                 ret = put_user(val, p);
2647                 break;
2648
2649         case SOUND_PCM_READ_RATE:
2650                 ret = put_user(dmabuf->rate, p);
2651                 break;
2652
2653         case SOUND_PCM_READ_CHANNELS:
2654                 ret = put_user((dmabuf->fmt & TRIDENT_FMT_STEREO) ? 2 : 1, 
2655                                p);
2656                 break;
2657
2658         case SOUND_PCM_READ_BITS:
2659                 ret = put_user((dmabuf->fmt & TRIDENT_FMT_16BIT) ? AFMT_S16_LE : 
2660                                AFMT_U8, p);
2661                 break;
2662
2663         case SNDCTL_DSP_GETCHANNELMASK:
2664                 ret = put_user(DSP_BIND_FRONT | DSP_BIND_SURR | 
2665                                DSP_BIND_CENTER_LFE,  p);
2666                 break;
2667
2668         case SNDCTL_DSP_BIND_CHANNEL:
2669                 if (state->card->pci_id != PCI_DEVICE_ID_SI_7018) {
2670                         ret = -EINVAL;
2671                         break;
2672                 }
2673
2674                 if (get_user(val, p)) {
2675                         ret = -EFAULT;
2676                         break;
2677                 }
2678                 if (val == DSP_BIND_QUERY) {
2679                         val = dmabuf->channel->attribute | 0x3c00;
2680                         val = attr2mask[val >> 8];
2681                 } else {
2682                         dmabuf->ready = 0;
2683                         if (file->f_mode & FMODE_READ)
2684                                 dmabuf->channel->attribute = (CHANNEL_REC | 
2685                                                               SRC_ENABLE);
2686                         if (file->f_mode & FMODE_WRITE)
2687                                 dmabuf->channel->attribute = (CHANNEL_SPC_PB | 
2688                                                               SRC_ENABLE);
2689                         dmabuf->channel->attribute |= mask2attr[ffs(val)];
2690                 }
2691                 ret = put_user(val, p);
2692                 break;
2693
2694         case SNDCTL_DSP_MAPINBUF:
2695         case SNDCTL_DSP_MAPOUTBUF:
2696         case SNDCTL_DSP_SETSYNCRO:
2697         case SOUND_PCM_WRITE_FILTER:
2698         case SOUND_PCM_READ_FILTER:
2699         default:
2700                 ret = -EINVAL;
2701                 break;
2702
2703         }
2704         return ret;
2705 }
2706
2707 static int
2708 trident_open(struct inode *inode, struct file *file)
2709 {
2710         int i = 0;
2711         int minor = iminor(inode);
2712         struct trident_card *card = devs;
2713         struct trident_state *state = NULL;
2714         struct dmabuf *dmabuf = NULL;
2715
2716         /* Added by Matt Wu 01-05-2001 */
2717         /* TODO: there's some redundacy here wrt the check below */
2718         /* for multi_use_count > 0. Should we return -EBUSY or find */
2719         /* a different card? for now, don't break current behaviour */
2720         /* -- mulix */
2721         if (file->f_mode & FMODE_READ) {
2722                 if (card->pci_id == PCI_DEVICE_ID_ALI_5451) {
2723                         if (card->multi_channel_use_count > 0)
2724                                 return -EBUSY;
2725                 }
2726         }
2727
2728         /* find an available virtual channel (instance of /dev/dsp) */
2729         while (card != NULL) {
2730                 down(&card->open_sem);
2731                 if (file->f_mode & FMODE_READ) {
2732                         /* Skip opens on cards that are in 6 channel mode */
2733                         if (card->multi_channel_use_count > 0) {
2734                                 up(&card->open_sem);
2735                                 card = card->next;
2736                                 continue;
2737                         }
2738                 }
2739                 for (i = 0; i < NR_HW_CH; i++) {
2740                         if (card->states[i] == NULL) {
2741                                 state = card->states[i] = kmalloc(sizeof(*state), GFP_KERNEL);
2742                                 if (state == NULL) {
2743                                         up(&card->open_sem);
2744                                         return -ENOMEM;
2745                                 }
2746                                 memset(state, 0, sizeof(*state));
2747                                 init_MUTEX(&state->sem);
2748                                 dmabuf = &state->dmabuf;
2749                                 goto found_virt;
2750                         }
2751                 }
2752                 up(&card->open_sem);
2753                 card = card->next;
2754         }
2755         /* no more virtual channel avaiable */
2756         if (!state) {
2757                 return -ENODEV;
2758         }
2759       found_virt:
2760         /* found a free virtual channel, allocate hardware channels */
2761         if (file->f_mode & FMODE_READ)
2762                 dmabuf->channel = card->alloc_rec_pcm_channel(card);
2763         else
2764                 dmabuf->channel = card->alloc_pcm_channel(card);
2765
2766         if (dmabuf->channel == NULL) {
2767                 kfree(card->states[i]);
2768                 card->states[i] = NULL;
2769                 return -ENODEV;
2770         }
2771
2772         /* initialize the virtual channel */
2773         state->virt = i;
2774         state->card = card;
2775         state->magic = TRIDENT_STATE_MAGIC;
2776         init_waitqueue_head(&dmabuf->wait);
2777         file->private_data = state;
2778
2779         /* set default sample format. According to OSS Programmer's */ 
2780         /* Guide  /dev/dsp should be default to unsigned 8-bits, mono, */ 
2781         /* with sample rate 8kHz and /dev/dspW will accept 16-bits sample */
2782         if (file->f_mode & FMODE_WRITE) {
2783                 dmabuf->fmt &= ~TRIDENT_FMT_MASK;
2784                 if ((minor & 0x0f) == SND_DEV_DSP16)
2785                         dmabuf->fmt |= TRIDENT_FMT_16BIT;
2786                 dmabuf->ossfragshift = 0;
2787                 dmabuf->ossmaxfrags = 0;
2788                 dmabuf->subdivision = 0;
2789                 if (card->pci_id == PCI_DEVICE_ID_SI_7018) {
2790                         /* set default channel attribute to normal playback */
2791                         dmabuf->channel->attribute = CHANNEL_PB;
2792                 }
2793                 trident_set_dac_rate(state, 8000);
2794         }
2795
2796         if (file->f_mode & FMODE_READ) {
2797                 /* FIXME: Trident 4d can only record in signed 16-bits stereo, */ 
2798                 /* 48kHz sample, to be dealed with in trident_set_adc_rate() ?? */
2799                 dmabuf->fmt &= ~TRIDENT_FMT_MASK;
2800                 if ((minor & 0x0f) == SND_DEV_DSP16)
2801                         dmabuf->fmt |= TRIDENT_FMT_16BIT;
2802                 dmabuf->ossfragshift = 0;
2803                 dmabuf->ossmaxfrags = 0;
2804                 dmabuf->subdivision = 0;
2805                 if (card->pci_id == PCI_DEVICE_ID_SI_7018) {
2806                         /* set default channel attribute to 0x8a80, record from
2807                            PCM L/R FIFO and mono = (left + right + 1)/2 */
2808                         dmabuf->channel->attribute = (CHANNEL_REC | PCM_LR | 
2809                                                       MONO_MIX);
2810                 }
2811                 trident_set_adc_rate(state, 8000);
2812
2813                 /* Added by Matt Wu 01-05-2001 */
2814                 if (card->pci_id == PCI_DEVICE_ID_ALI_5451)
2815                         card->rec_channel_use_count++;
2816         }
2817
2818         state->open_mode |= file->f_mode & (FMODE_READ | FMODE_WRITE);
2819         up(&card->open_sem);
2820
2821         pr_debug("trident: open virtual channel %d, hard channel %d\n",
2822                  state->virt, dmabuf->channel->num);
2823
2824         return nonseekable_open(inode, file);
2825 }
2826
2827 static int
2828 trident_release(struct inode *inode, struct file *file)
2829 {
2830         struct trident_state *state = (struct trident_state *)file->private_data;
2831         struct trident_card *card;
2832         struct dmabuf *dmabuf;
2833
2834         VALIDATE_STATE(state);
2835
2836         card = state->card;
2837         dmabuf = &state->dmabuf;
2838
2839         if (file->f_mode & FMODE_WRITE) {
2840                 trident_clear_tail(state);
2841                 drain_dac(state, file->f_flags & O_NONBLOCK);
2842         }
2843
2844         pr_debug("trident: closing virtual channel %d, hard channel %d\n",
2845                  state->virt, dmabuf->channel->num);
2846
2847         /* stop DMA state machine and free DMA buffers/channels */
2848         down(&card->open_sem);
2849
2850         if (file->f_mode & FMODE_WRITE) {
2851                 stop_dac(state);
2852                 dealloc_dmabuf(&state->dmabuf, state->card->pci_dev);
2853                 state->card->free_pcm_channel(state->card, dmabuf->channel->num);
2854
2855                 /* Added by Matt Wu */
2856                 if (card->pci_id == PCI_DEVICE_ID_ALI_5451) {
2857                         if (state->chans_num > 2) {
2858                                 if (card->multi_channel_use_count-- < 0)
2859                                         card->multi_channel_use_count = 0;
2860                                 if (card->multi_channel_use_count == 0)
2861                                         ali_close_multi_channels();
2862                                 ali_free_other_states_resources(state);
2863                         }
2864                 }
2865         }
2866         if (file->f_mode & FMODE_READ) {
2867                 stop_adc(state);
2868                 dealloc_dmabuf(&state->dmabuf, state->card->pci_dev);
2869                 state->card->free_pcm_channel(state->card, dmabuf->channel->num);
2870
2871                 /* Added by Matt Wu */
2872                 if (card->pci_id == PCI_DEVICE_ID_ALI_5451) {
2873                         if (card->rec_channel_use_count-- < 0)
2874                                 card->rec_channel_use_count = 0;
2875                 }
2876         }
2877
2878         card->states[state->virt] = NULL;
2879         kfree(state);
2880
2881         /* we're covered by the open_sem */
2882         up(&card->open_sem);
2883
2884         return 0;
2885 }
2886
2887 static /*const */ struct file_operations trident_audio_fops = {
2888         .owner = THIS_MODULE,
2889         .llseek = no_llseek,
2890         .read = trident_read,
2891         .write = trident_write,
2892         .poll = trident_poll,
2893         .ioctl = trident_ioctl,
2894         .mmap = trident_mmap,
2895         .open = trident_open,
2896         .release = trident_release,
2897 };
2898
2899 /* trident specific AC97 functions */
2900 /* Write AC97 codec registers */
2901 static void
2902 trident_ac97_set(struct ac97_codec *codec, u8 reg, u16 val)
2903 {
2904         struct trident_card *card = (struct trident_card *)codec->private_data;
2905         unsigned int address, mask, busy;
2906         unsigned short count = 0xffff;
2907         unsigned long flags;
2908         u32 data;
2909
2910         data = ((u32) val) << 16;
2911
2912         switch (card->pci_id) {
2913         default:
2914         case PCI_DEVICE_ID_SI_7018:
2915                 address = SI_AC97_WRITE;
2916                 mask = SI_AC97_BUSY_WRITE | SI_AC97_AUDIO_BUSY;
2917                 if (codec->id)
2918                         mask |= SI_AC97_SECONDARY;
2919                 busy = SI_AC97_BUSY_WRITE;
2920                 break;
2921         case PCI_DEVICE_ID_TRIDENT_4DWAVE_DX:
2922                 address = DX_ACR0_AC97_W;
2923                 mask = busy = DX_AC97_BUSY_WRITE;
2924                 break;
2925         case PCI_DEVICE_ID_TRIDENT_4DWAVE_NX:
2926                 address = NX_ACR1_AC97_W;
2927                 mask = NX_AC97_BUSY_WRITE;
2928                 if (codec->id)
2929                         mask |= NX_AC97_WRITE_SECONDARY;
2930                 busy = NX_AC97_BUSY_WRITE;
2931                 break;
2932         case PCI_DEVICE_ID_INTERG_5050:
2933                 address = SI_AC97_WRITE;
2934                 mask = busy = SI_AC97_BUSY_WRITE;
2935                 if (codec->id)
2936                         mask |= SI_AC97_SECONDARY;
2937                 break;
2938         }
2939
2940         spin_lock_irqsave(&card->lock, flags);
2941         do {
2942                 if ((inw(TRID_REG(card, address)) & busy) == 0)
2943                         break;
2944         } while (count--);
2945
2946         data |= (mask | (reg & AC97_REG_ADDR));
2947
2948         if (count == 0) {
2949                 printk(KERN_ERR "trident: AC97 CODEC write timed out.\n");
2950                 spin_unlock_irqrestore(&card->lock, flags);
2951                 return;
2952         }
2953
2954         outl(data, TRID_REG(card, address));
2955         spin_unlock_irqrestore(&card->lock, flags);
2956 }
2957
2958 /* Read AC97 codec registers */
2959 static u16
2960 trident_ac97_get(struct ac97_codec *codec, u8 reg)
2961 {
2962         struct trident_card *card = (struct trident_card *)codec->private_data;
2963         unsigned int address, mask, busy;
2964         unsigned short count = 0xffff;
2965         unsigned long flags;
2966         u32 data;
2967
2968         switch (card->pci_id) {
2969         default:
2970         case PCI_DEVICE_ID_SI_7018:
2971                 address = SI_AC97_READ;
2972                 mask = SI_AC97_BUSY_READ | SI_AC97_AUDIO_BUSY;
2973                 if (codec->id)
2974                         mask |= SI_AC97_SECONDARY;
2975                 busy = SI_AC97_BUSY_READ;
2976                 break;
2977         case PCI_DEVICE_ID_TRIDENT_4DWAVE_DX:
2978                 address = DX_ACR1_AC97_R;
2979                 mask = busy = DX_AC97_BUSY_READ;
2980                 break;
2981         case PCI_DEVICE_ID_TRIDENT_4DWAVE_NX:
2982                 if (codec->id)
2983                         address = NX_ACR3_AC97_R_SECONDARY;
2984                 else
2985                         address = NX_ACR2_AC97_R_PRIMARY;
2986                 mask = NX_AC97_BUSY_READ;
2987                 busy = NX_AC97_BUSY_READ | NX_AC97_BUSY_DATA;
2988                 break;
2989         case PCI_DEVICE_ID_INTERG_5050:
2990                 address = SI_AC97_READ;
2991                 mask = busy = SI_AC97_BUSY_READ;
2992                 if (codec->id)
2993                         mask |= SI_AC97_SECONDARY;
2994                 break;
2995         }
2996
2997         data = (mask | (reg & AC97_REG_ADDR));
2998
2999         spin_lock_irqsave(&card->lock, flags);
3000         outl(data, TRID_REG(card, address));
3001         do {
3002                 data = inl(TRID_REG(card, address));
3003                 if ((data & busy) == 0)
3004                         break;
3005         } while (count--);
3006         spin_unlock_irqrestore(&card->lock, flags);
3007
3008         if (count == 0) {
3009                 printk(KERN_ERR "trident: AC97 CODEC read timed out.\n");
3010                 data = 0;
3011         }
3012         return ((u16) (data >> 16));
3013 }
3014
3015 /* rewrite ac97 read and write mixer register by hulei for ALI*/
3016 static int
3017 acquirecodecaccess(struct trident_card *card)
3018 {
3019         u16 wsemamask = 0x6000; /* bit 14..13 */
3020         u16 wsemabits;
3021         u16 wcontrol;
3022         int block = 0;
3023         int ncount = 25;
3024         while (1) {
3025                 wcontrol = inw(TRID_REG(card, ALI_AC97_WRITE));
3026                 wsemabits = wcontrol & wsemamask;
3027
3028                 if (wsemabits == 0x4000)
3029                         return 1;       /* 0x4000 is audio ,then success */
3030                 if (ncount-- < 0)
3031                         break;
3032                 if (wsemabits == 0) {
3033                       unlock:
3034                         outl(((u32) (wcontrol & 0x1eff) | 0x00004000), 
3035                              TRID_REG(card, ALI_AC97_WRITE));
3036                         continue;
3037                 }
3038                 udelay(20);
3039         }
3040         if (!block) {
3041                 pr_debug("accesscodecsemaphore: try unlock\n");
3042                 block = 1;
3043                 goto unlock;
3044         }
3045         return 0;
3046 }
3047
3048 static void
3049 releasecodecaccess(struct trident_card *card)
3050 {
3051         unsigned long wcontrol;
3052         wcontrol = inl(TRID_REG(card, ALI_AC97_WRITE));
3053         outl((wcontrol & 0xffff1eff), TRID_REG(card, ALI_AC97_WRITE));
3054 }
3055
3056 static int
3057 waitforstimertick(struct trident_card *card)
3058 {
3059         unsigned long chk1, chk2;
3060         unsigned int wcount = 0xffff;
3061         chk1 = inl(TRID_REG(card, ALI_STIMER));
3062
3063         while (1) {
3064                 chk2 = inl(TRID_REG(card, ALI_STIMER));
3065                 if ((wcount > 0) && chk1 != chk2)
3066                         return 1;
3067                 if (wcount <= 0)
3068                         break;
3069                 udelay(50);
3070         }
3071         return 0;
3072 }
3073
3074 /* Read AC97 codec registers for ALi*/
3075 static u16
3076 ali_ac97_get(struct trident_card *card, int secondary, u8 reg)
3077 {
3078         unsigned int address, mask;
3079         unsigned int ncount;
3080         unsigned long aud_reg;
3081         u32 data;
3082         u16 wcontrol;
3083         unsigned long flags;
3084
3085         if (!card)
3086                 BUG();
3087
3088         address = ALI_AC97_READ;
3089         if (card->revision == ALI_5451_V02) {
3090                 address = ALI_AC97_WRITE;
3091         }
3092         mask = ALI_AC97_READ_ACTION | ALI_AC97_AUDIO_BUSY;
3093         if (secondary)
3094                 mask |= ALI_AC97_SECONDARY;
3095
3096         spin_lock_irqsave(&card->lock, flags);
3097
3098         if (!acquirecodecaccess(card))
3099                 printk(KERN_ERR "access codec fail\n");
3100
3101         wcontrol = inw(TRID_REG(card, ALI_AC97_WRITE));
3102         wcontrol &= 0xfe00;
3103         wcontrol |= (0x8000 | reg);
3104         outw(wcontrol, TRID_REG(card, ALI_AC97_WRITE));
3105
3106         data = (mask | (reg & AC97_REG_ADDR));
3107
3108         if (!waitforstimertick(card)) {
3109                 printk(KERN_ERR "ali_ac97_read: BIT_CLOCK is dead\n");
3110                 goto releasecodec;
3111         }
3112
3113         udelay(20);
3114
3115         ncount = 10;
3116
3117         while (1) {
3118                 if ((inw(TRID_REG(card, ALI_AC97_WRITE)) & ALI_AC97_BUSY_READ) 
3119                     != 0)
3120                         break;
3121                 if (ncount <= 0)
3122                         break;
3123                 if (ncount-- == 1) {
3124                         pr_debug("ali_ac97_read :try clear busy flag\n");
3125                         aud_reg = inl(TRID_REG(card, ALI_AC97_WRITE));
3126                         outl((aud_reg & 0xffff7fff), 
3127                              TRID_REG(card, ALI_AC97_WRITE));
3128                 }
3129                 udelay(10);
3130         }
3131
3132         data = inl(TRID_REG(card, address));
3133
3134         spin_unlock_irqrestore(&card->lock, flags);
3135
3136         return ((u16) (data >> 16));
3137
3138       releasecodec:
3139         releasecodecaccess(card);
3140         spin_unlock_irqrestore(&card->lock, flags);
3141         printk(KERN_ERR "ali_ac97_read: AC97 CODEC read timed out.\n");
3142         return 0;
3143 }
3144
3145 /* Write AC97 codec registers for hulei*/
3146 static void
3147 ali_ac97_set(struct trident_card *card, int secondary, u8 reg, u16 val)
3148 {
3149         unsigned int address, mask;
3150         unsigned int ncount;
3151         u32 data;
3152         u16 wcontrol;
3153         unsigned long flags;
3154
3155         data = ((u32) val) << 16;
3156
3157         if (!card)
3158                 BUG();
3159
3160         address = ALI_AC97_WRITE;
3161         mask = ALI_AC97_WRITE_ACTION | ALI_AC97_AUDIO_BUSY;
3162         if (secondary)
3163                 mask |= ALI_AC97_SECONDARY;
3164         if (card->revision == ALI_5451_V02)
3165                 mask |= ALI_AC97_WRITE_MIXER_REGISTER;
3166
3167         spin_lock_irqsave(&card->lock, flags);
3168         if (!acquirecodecaccess(card))
3169                 printk(KERN_ERR "ali_ac97_write: access codec fail\n");
3170
3171         wcontrol = inw(TRID_REG(card, ALI_AC97_WRITE));
3172         wcontrol &= 0xff00;
3173         wcontrol |= (0x8100 | reg); /* bit 8=1: (ali1535 )reserved/ */ 
3174                                     /* ali1535+ write */
3175         outl((data | wcontrol), TRID_REG(card, ALI_AC97_WRITE));
3176
3177         if (!waitforstimertick(card)) {
3178                 printk(KERN_ERR "BIT_CLOCK is dead\n");
3179                 goto releasecodec;
3180         }
3181
3182         ncount = 10;
3183         while (1) {
3184                 wcontrol = inw(TRID_REG(card, ALI_AC97_WRITE));
3185                 if (!(wcontrol & 0x8000))
3186                         break;
3187                 if (ncount <= 0)
3188                         break;
3189                 if (ncount-- == 1) {
3190                         pr_debug("ali_ac97_set :try clear busy flag!!\n");
3191                         outw(wcontrol & 0x7fff, 
3192                              TRID_REG(card, ALI_AC97_WRITE));
3193                 }
3194                 udelay(10);
3195         }
3196
3197       releasecodec:
3198         releasecodecaccess(card);
3199         spin_unlock_irqrestore(&card->lock, flags);
3200         return;
3201 }
3202
3203 static void
3204 ali_enable_special_channel(struct trident_state *stat)
3205 {
3206         struct trident_card *card = stat->card;
3207         unsigned long s_channels;
3208
3209         s_channels = inl(TRID_REG(card, ALI_GLOBAL_CONTROL));
3210         s_channels |= (1 << stat->dmabuf.channel->num);
3211         outl(s_channels, TRID_REG(card, ALI_GLOBAL_CONTROL));
3212 }
3213
3214 static u16
3215 ali_ac97_read(struct ac97_codec *codec, u8 reg)
3216 {
3217         int id;
3218         u16 data;
3219         struct trident_card *card = NULL;
3220
3221         /* Added by Matt Wu */
3222         if (!codec)
3223                 BUG();
3224
3225         card = (struct trident_card *) codec->private_data;
3226
3227         if (!card->mixer_regs_ready)
3228                 return ali_ac97_get(card, codec->id, reg);
3229
3230         /*
3231          *      FIXME: need to stop this caching some registers
3232          */
3233         if (codec->id)
3234                 id = 1;
3235         else
3236                 id = 0;
3237
3238         data = card->mixer_regs[reg / 2][id];
3239         return data;
3240 }
3241
3242 static void
3243 ali_ac97_write(struct ac97_codec *codec, u8 reg, u16 val)
3244 {
3245         int id;
3246         struct trident_card *card;
3247
3248         /*  Added by Matt Wu */
3249         if (!codec)
3250                 BUG();
3251
3252         card = (struct trident_card *) codec->private_data;
3253
3254         if (!card->mixer_regs_ready) {
3255                 ali_ac97_set(card, codec->id, reg, val);
3256                 return;
3257         }
3258
3259         if (codec->id)
3260                 id = 1;
3261         else
3262                 id = 0;
3263
3264         card->mixer_regs[reg / 2][id] = val;
3265         ali_ac97_set(card, codec->id, reg, val);
3266 }
3267
3268 /*
3269 flag:   ALI_SPDIF_OUT_TO_SPDIF_OUT
3270         ALI_PCM_TO_SPDIF_OUT
3271 */
3272
3273 static void
3274 ali_setup_spdif_out(struct trident_card *card, int flag)
3275 {
3276         unsigned long spdif;
3277         unsigned char ch;
3278
3279         char temp;
3280         struct pci_dev *pci_dev = NULL;
3281
3282         pci_dev = pci_find_device(PCI_VENDOR_ID_AL, PCI_DEVICE_ID_AL_M1533, 
3283                                   pci_dev);
3284         if (pci_dev == NULL)
3285                 return;
3286         pci_read_config_byte(pci_dev, 0x61, &temp);
3287         temp |= 0x40;
3288         pci_write_config_byte(pci_dev, 0x61, temp);
3289         pci_read_config_byte(pci_dev, 0x7d, &temp);
3290         temp |= 0x01;
3291         pci_write_config_byte(pci_dev, 0x7d, temp);
3292         pci_read_config_byte(pci_dev, 0x7e, &temp);
3293         temp &= (~0x20);
3294         temp |= 0x10;
3295         pci_write_config_byte(pci_dev, 0x7e, temp);
3296
3297         ch = inb(TRID_REG(card, ALI_SCTRL));
3298         outb(ch | ALI_SPDIF_OUT_ENABLE, TRID_REG(card, ALI_SCTRL));
3299         ch = inb(TRID_REG(card, ALI_SPDIF_CTRL));
3300         outb(ch & ALI_SPDIF_OUT_CH_STATUS, TRID_REG(card, ALI_SPDIF_CTRL));
3301
3302         if (flag & ALI_SPDIF_OUT_TO_SPDIF_OUT) {
3303                 spdif = inw(TRID_REG(card, ALI_GLOBAL_CONTROL));
3304                 spdif |= ALI_SPDIF_OUT_CH_ENABLE;
3305                 spdif &= ALI_SPDIF_OUT_SEL_SPDIF;
3306                 outw(spdif, TRID_REG(card, ALI_GLOBAL_CONTROL));
3307                 spdif = inw(TRID_REG(card, ALI_SPDIF_CS));
3308                 if (flag & ALI_SPDIF_OUT_NON_PCM)
3309                         spdif |= 0x0002;
3310                 else
3311                         spdif &= (~0x0002);
3312                 outw(spdif, TRID_REG(card, ALI_SPDIF_CS));
3313         } else {
3314                 spdif = inw(TRID_REG(card, ALI_GLOBAL_CONTROL));
3315                 spdif |= ALI_SPDIF_OUT_SEL_PCM;
3316                 outw(spdif, TRID_REG(card, ALI_GLOBAL_CONTROL));
3317         }
3318 }
3319
3320 static void
3321 ali_disable_special_channel(struct trident_card *card, int ch)
3322 {
3323         unsigned long sc;
3324
3325         sc = inl(TRID_REG(card, ALI_GLOBAL_CONTROL));
3326         sc &= ~(1 << ch);
3327         outl(sc, TRID_REG(card, ALI_GLOBAL_CONTROL));
3328 }
3329
3330 static void
3331 ali_disable_spdif_in(struct trident_card *card)
3332 {
3333         unsigned long spdif;
3334
3335         spdif = inl(TRID_REG(card, ALI_GLOBAL_CONTROL));
3336         spdif &= (~ALI_SPDIF_IN_SUPPORT);
3337         outl(spdif, TRID_REG(card, ALI_GLOBAL_CONTROL));
3338
3339         ali_disable_special_channel(card, ALI_SPDIF_IN_CHANNEL);
3340 }
3341
3342 static void
3343 ali_setup_spdif_in(struct trident_card *card)
3344 {
3345         unsigned long spdif;
3346
3347         //Set SPDIF IN Supported
3348         spdif = inl(TRID_REG(card, ALI_GLOBAL_CONTROL));
3349         spdif |= ALI_SPDIF_IN_SUPPORT;
3350         outl(spdif, TRID_REG(card, ALI_GLOBAL_CONTROL));
3351
3352         //Set SPDIF IN Rec
3353         spdif = inl(TRID_REG(card, ALI_GLOBAL_CONTROL));
3354         spdif |= ALI_SPDIF_IN_CH_ENABLE;
3355         outl(spdif, TRID_REG(card, ALI_GLOBAL_CONTROL));
3356
3357         spdif = inb(TRID_REG(card, ALI_SPDIF_CTRL));
3358         spdif |= ALI_SPDIF_IN_CH_STATUS;
3359         outb(spdif, TRID_REG(card, ALI_SPDIF_CTRL));
3360 /*
3361         spdif = inb(TRID_REG(card, ALI_SPDIF_CTRL));
3362         spdif |= ALI_SPDIF_IN_FUNC_ENABLE;
3363         outb(spdif, TRID_REG(card, ALI_SPDIF_CTRL));
3364 */
3365 }
3366
3367 static void
3368 ali_delay(struct trident_card *card, int interval)
3369 {
3370         unsigned long begintimer, currenttimer;
3371
3372         begintimer = inl(TRID_REG(card, ALI_STIMER));
3373         currenttimer = inl(TRID_REG(card, ALI_STIMER));
3374
3375         while (currenttimer < begintimer + interval)
3376                 currenttimer = inl(TRID_REG(card, ALI_STIMER));
3377 }
3378
3379 static void
3380 ali_detect_spdif_rate(struct trident_card *card)
3381 {
3382         u16 wval = 0;
3383         u16 count = 0;
3384         u8 bval = 0, R1 = 0, R2 = 0;
3385
3386         bval = inb(TRID_REG(card, ALI_SPDIF_CTRL));
3387         bval |= 0x02;
3388         outb(bval, TRID_REG(card, ALI_SPDIF_CTRL));
3389
3390         bval = inb(TRID_REG(card, ALI_SPDIF_CTRL + 1));
3391         bval |= 0x1F;
3392         outb(bval, TRID_REG(card, ALI_SPDIF_CTRL + 1));
3393
3394         while (((R1 < 0x0B) || (R1 > 0x0E)) && (R1 != 0x12) && 
3395                count <= 50000) {
3396                 count++;
3397
3398                 ali_delay(card, 6);
3399
3400                 bval = inb(TRID_REG(card, ALI_SPDIF_CTRL + 1));
3401                 R1 = bval & 0x1F;
3402         }
3403
3404         if (count > 50000) {
3405                 printk(KERN_WARNING "trident: Error in "
3406                        "ali_detect_spdif_rate!\n");
3407                 return;
3408         }
3409
3410         count = 0;
3411
3412         while (count <= 50000) {
3413                 count++;
3414
3415                 ali_delay(card, 6);
3416
3417                 bval = inb(TRID_REG(card, ALI_SPDIF_CTRL + 1));
3418                 R2 = bval & 0x1F;
3419
3420                 if (R2 != R1)
3421                         R1 = R2;
3422                 else
3423                         break;
3424         }
3425
3426         if (count > 50000) {
3427                 printk(KERN_WARNING "trident: Error in "
3428                        "ali_detect_spdif_rate!\n");
3429                 return;
3430         }
3431
3432         switch (R2) {
3433         case 0x0b:
3434         case 0x0c:
3435         case 0x0d:
3436         case 0x0e:
3437                 wval = inw(TRID_REG(card, ALI_SPDIF_CTRL + 2));
3438                 wval &= 0xE0F0;
3439                 wval |= (u16) 0x09 << 8 | (u16) 0x05;
3440                 outw(wval, TRID_REG(card, ALI_SPDIF_CTRL + 2));
3441
3442                 bval = inb(TRID_REG(card, ALI_SPDIF_CS + 3)) & 0xF0;
3443                 outb(bval | 0x02, TRID_REG(card, ALI_SPDIF_CS + 3));
3444                 break;
3445
3446         case 0x12:
3447                 wval = inw(TRID_REG(card, ALI_SPDIF_CTRL + 2));
3448                 wval &= 0xE0F0;
3449                 wval |= (u16) 0x0E << 8 | (u16) 0x08;
3450                 outw(wval, TRID_REG(card, ALI_SPDIF_CTRL + 2));
3451
3452                 bval = inb(TRID_REG(card, ALI_SPDIF_CS + 3)) & 0xF0;
3453                 outb(bval | 0x03, TRID_REG(card, ALI_SPDIF_CS + 3));
3454                 break;
3455
3456         default:
3457                 break;
3458         }
3459
3460 }
3461
3462 static unsigned int
3463 ali_get_spdif_in_rate(struct trident_card *card)
3464 {
3465         u32 dwRate = 0;
3466         u8 bval = 0;
3467
3468         ali_detect_spdif_rate(card);
3469
3470         bval = inb(TRID_REG(card, ALI_SPDIF_CTRL));
3471         bval &= 0x7F;
3472         bval |= 0x40;
3473         outb(bval, TRID_REG(card, ALI_SPDIF_CTRL));
3474
3475         bval = inb(TRID_REG(card, ALI_SPDIF_CS + 3));
3476         bval &= 0x0F;
3477
3478         switch (bval) {
3479         case 0:
3480                 dwRate = 44100;
3481                 break;
3482         case 1:
3483                 dwRate = 48000;
3484                 break;
3485         case 2:
3486                 dwRate = 32000;
3487                 break;
3488         default:
3489                 // Error occurs
3490                 break;
3491         }
3492
3493         return dwRate;
3494
3495 }
3496
3497 static int
3498 ali_close_multi_channels(void)
3499 {
3500         char temp = 0;
3501         struct pci_dev *pci_dev = NULL;
3502
3503         pci_dev = pci_find_device(PCI_VENDOR_ID_AL, PCI_DEVICE_ID_AL_M1533, 
3504                                   pci_dev);
3505         if (pci_dev == NULL)
3506                 return -1;
3507         pci_read_config_byte(pci_dev, 0x59, &temp);
3508         temp &= ~0x80;
3509         pci_write_config_byte(pci_dev, 0x59, temp);
3510
3511         pci_dev = pci_find_device(PCI_VENDOR_ID_AL, PCI_DEVICE_ID_AL_M7101, 
3512                                   pci_dev);
3513         if (pci_dev == NULL)
3514                 return -1;
3515
3516         pci_read_config_byte(pci_dev, 0xB8, &temp);
3517         temp &= ~0x20;
3518         pci_write_config_byte(pci_dev, 0xB8, temp);
3519
3520         return 0;
3521 }
3522
3523 static int
3524 ali_setup_multi_channels(struct trident_card *card, int chan_nums)
3525 {
3526         unsigned long dwValue;
3527         char temp = 0;
3528         struct pci_dev *pci_dev = NULL;
3529
3530         pci_dev = pci_find_device(PCI_VENDOR_ID_AL, PCI_DEVICE_ID_AL_M1533, 
3531                                   pci_dev);
3532         if (pci_dev == NULL)
3533                 return -1;
3534         pci_read_config_byte(pci_dev, 0x59, &temp);
3535         temp |= 0x80;
3536         pci_write_config_byte(pci_dev, 0x59, temp);
3537
3538         pci_dev = pci_find_device(PCI_VENDOR_ID_AL, PCI_DEVICE_ID_AL_M7101, 
3539                                   pci_dev);
3540         if (pci_dev == NULL)
3541                 return -1;
3542         pci_read_config_byte(pci_dev, (int) 0xB8, &temp);
3543         temp |= 0x20;
3544         pci_write_config_byte(pci_dev, (int) 0xB8, (u8) temp);
3545         if (chan_nums == 6) {
3546                 dwValue = inl(TRID_REG(card, ALI_SCTRL)) | 0x000f0000;
3547                 outl(dwValue, TRID_REG(card, ALI_SCTRL));
3548                 mdelay(4);
3549                 dwValue = inl(TRID_REG(card, ALI_SCTRL));
3550                 if (dwValue & 0x2000000) {
3551                         ali_ac97_write(card->ac97_codec[0], 0x02, 8080);
3552                         ali_ac97_write(card->ac97_codec[0], 0x36, 0);
3553                         ali_ac97_write(card->ac97_codec[0], 0x38, 0);
3554                         /*
3555                          *      On a board with a single codec you won't get the
3556                          *      surround. On other boards configure it.
3557                          */
3558                         if (card->ac97_codec[1] != NULL) {
3559                                 ali_ac97_write(card->ac97_codec[1], 0x36, 0);
3560                                 ali_ac97_write(card->ac97_codec[1], 0x38, 0);
3561                                 ali_ac97_write(card->ac97_codec[1], 0x02, 0x0606);
3562                                 ali_ac97_write(card->ac97_codec[1], 0x18, 0x0303);
3563                                 ali_ac97_write(card->ac97_codec[1], 0x74, 0x3);
3564                         }
3565                         return 1;
3566                 }
3567         }
3568         return -EINVAL;
3569 }
3570
3571 static void
3572 ali_free_pcm_channel(struct trident_card *card, unsigned int channel)
3573 {
3574         int bank;
3575
3576         if (channel > 31)
3577                 return;
3578
3579         bank = channel >> 5;
3580         channel = channel & 0x1f;
3581
3582         card->banks[bank].bitmap &= ~(1 << (channel));
3583 }
3584
3585 static int
3586 ali_allocate_other_states_resources(struct trident_state *state, int chan_nums)
3587 {
3588         struct trident_card *card = state->card;
3589         struct trident_state *s;
3590         int i, state_count = 0;
3591         struct trident_pcm_bank *bank;
3592         struct trident_channel *channel;
3593         unsigned long num;
3594
3595         bank = &card->banks[BANK_A];
3596
3597         if (chan_nums != 6)
3598                 return 0;
3599
3600         for (i = 0; (i < ALI_CHANNELS) && (state_count != 4); i++) {
3601                 if (card->states[i])
3602                         continue;
3603
3604                 num = ali_multi_channels_5_1[state_count];
3605                 if (!(bank->bitmap & (1 << num))) {
3606                         bank->bitmap |= 1 << num;
3607                         channel = &bank->channels[num];
3608                         channel->num = num;
3609                 } else {
3610                         state_count--;
3611                         for (; state_count >= 0; state_count--) {
3612                                 kfree(state->other_states[state_count]);
3613                                 num = ali_multi_channels_5_1[state_count];
3614                                         ali_free_pcm_channel(card, num);
3615                         }
3616                         return -EBUSY;
3617                 }
3618                 s = card->states[i] = kmalloc(sizeof(*state), GFP_KERNEL);
3619                 if (!s) {
3620                         num = ali_multi_channels_5_1[state_count];
3621                         ali_free_pcm_channel(card, num);
3622                         state_count--;
3623                         for (; state_count >= 0; state_count--) {
3624                                 num = ali_multi_channels_5_1[state_count];
3625                                 ali_free_pcm_channel(card, num);
3626                                 kfree(state->other_states[state_count]);
3627                         }
3628                         return -ENOMEM;
3629                 }
3630                 memset(s, 0, sizeof(*state));
3631
3632                 s->dmabuf.channel = channel;
3633                 s->dmabuf.ossfragshift = s->dmabuf.ossmaxfrags =
3634                         s->dmabuf.subdivision = 0;
3635                 init_waitqueue_head(&s->dmabuf.wait);
3636                 s->magic = card->magic;
3637                 s->card = card;
3638                 s->virt = i;
3639                 ali_enable_special_channel(s);
3640                 state->other_states[state_count++] = s;
3641         }
3642
3643         if (state_count != 4) {
3644                 state_count--;
3645                 for (; state_count >= 0; state_count--) {
3646                         kfree(state->other_states[state_count]);
3647                         num = ali_multi_channels_5_1[state_count];
3648                         ali_free_pcm_channel(card, num);
3649                 }
3650                 return -EBUSY;
3651         }
3652         return 0;
3653 }
3654
3655 static void
3656 ali_save_regs(struct trident_card *card)
3657 {
3658         unsigned long flags;
3659         int i, j;
3660
3661         spin_lock_irqsave(&card->lock, flags);
3662
3663         ali_registers.global_regs[0x2c] = inl(TRID_REG(card, T4D_MISCINT));
3664         //ali_registers.global_regs[0x20] = inl(TRID_REG(card,T4D_START_A));    
3665         ali_registers.global_regs[0x21] = inl(TRID_REG(card, T4D_STOP_A));
3666
3667         //disable all IRQ bits
3668         outl(ALI_DISABLE_ALL_IRQ, TRID_REG(card, T4D_MISCINT));
3669
3670         for (i = 1; i < ALI_MIXER_REGS; i++)
3671                 ali_registers.mixer_regs[i] = ali_ac97_read(card->ac97_codec[0], 
3672                                                             i * 2);
3673
3674         for (i = 0; i < ALI_GLOBAL_REGS; i++) {
3675                 if ((i * 4 == T4D_MISCINT) || (i * 4 == T4D_STOP_A))
3676                         continue;
3677                 ali_registers.global_regs[i] = inl(TRID_REG(card, i * 4));
3678         }
3679
3680         for (i = 0; i < ALI_CHANNELS; i++) {
3681                 outb(i, TRID_REG(card, T4D_LFO_GC_CIR));
3682                 for (j = 0; j < ALI_CHANNEL_REGS; j++)
3683                         ali_registers.channel_regs[i][j] = inl(TRID_REG(card, 
3684                                                                         j * 4 + 0xe0));
3685         }
3686
3687         //Stop all HW channel
3688         outl(ALI_STOP_ALL_CHANNELS, TRID_REG(card, T4D_STOP_A));
3689
3690         spin_unlock_irqrestore(&card->lock, flags);
3691 }
3692
3693 static void
3694 ali_restore_regs(struct trident_card *card)
3695 {
3696         unsigned long flags;
3697         int i, j;
3698
3699         spin_lock_irqsave(&card->lock, flags);
3700
3701         for (i = 1; i < ALI_MIXER_REGS; i++)
3702                 ali_ac97_write(card->ac97_codec[0], i * 2, 
3703                                ali_registers.mixer_regs[i]);
3704
3705         for (i = 0; i < ALI_CHANNELS; i++) {
3706                 outb(i, TRID_REG(card, T4D_LFO_GC_CIR));
3707                 for (j = 0; j < ALI_CHANNEL_REGS; j++)
3708                         outl(ali_registers.channel_regs[i][j], 
3709                              TRID_REG(card, j * 4 + 0xe0));
3710         }
3711
3712         for (i = 0; i < ALI_GLOBAL_REGS; i++) {
3713                 if ((i * 4 == T4D_MISCINT) || (i * 4 == T4D_STOP_A) || 
3714                     (i * 4 == T4D_START_A))
3715                         continue;
3716                 outl(ali_registers.global_regs[i], TRID_REG(card, i * 4));
3717         }
3718
3719         //start HW channel
3720         outl(ali_registers.global_regs[0x20], TRID_REG(card, T4D_START_A));
3721         //restore IRQ enable bits
3722         outl(ali_registers.global_regs[0x2c], TRID_REG(card, T4D_MISCINT));
3723
3724         spin_unlock_irqrestore(&card->lock, flags);
3725 }
3726
3727 static int
3728 trident_suspend(struct pci_dev *dev, pm_message_t unused)
3729 {
3730         struct trident_card *card = pci_get_drvdata(dev);
3731
3732         if (card->pci_id == PCI_DEVICE_ID_ALI_5451) {
3733                 ali_save_regs(card);
3734         }
3735         return 0;
3736 }
3737
3738 static int
3739 trident_resume(struct pci_dev *dev)
3740 {
3741         struct trident_card *card = pci_get_drvdata(dev);
3742
3743         if (card->pci_id == PCI_DEVICE_ID_ALI_5451) {
3744                 ali_restore_regs(card);
3745         }
3746         return 0;
3747 }
3748
3749 static struct trident_channel *
3750 ali_alloc_pcm_channel(struct trident_card *card)
3751 {
3752         struct trident_pcm_bank *bank;
3753         int idx;
3754
3755         bank = &card->banks[BANK_A];
3756
3757         if (inl(TRID_REG(card, ALI_GLOBAL_CONTROL)) & 
3758             (ALI_SPDIF_OUT_CH_ENABLE)) {
3759                 idx = ALI_SPDIF_OUT_CHANNEL;
3760                 if (!(bank->bitmap & (1 << idx))) {
3761                         struct trident_channel *channel = &bank->channels[idx];
3762                         bank->bitmap |= 1 << idx;
3763                         channel->num = idx;
3764                         return channel;
3765                 }
3766         }
3767
3768         for (idx = ALI_PCM_OUT_CHANNEL_FIRST; idx <= ALI_PCM_OUT_CHANNEL_LAST; 
3769              idx++) {
3770                 if (!(bank->bitmap & (1 << idx))) {
3771                         struct trident_channel *channel = &bank->channels[idx];
3772                         bank->bitmap |= 1 << idx;
3773                         channel->num = idx;
3774                         return channel;
3775                 }
3776         }
3777
3778         /* no more free channels avaliable */
3779 #if 0 
3780         printk(KERN_ERR "ali: no more channels available on Bank A.\n");
3781 #endif /* 0 */ 
3782         return NULL;
3783 }
3784
3785 static struct trident_channel *
3786 ali_alloc_rec_pcm_channel(struct trident_card *card)
3787 {
3788         struct trident_pcm_bank *bank;
3789         int idx;
3790
3791         if (inl(TRID_REG(card, ALI_GLOBAL_CONTROL)) & ALI_SPDIF_IN_SUPPORT)
3792                 idx = ALI_SPDIF_IN_CHANNEL;
3793         else
3794                 idx = ALI_PCM_IN_CHANNEL;
3795
3796         bank = &card->banks[BANK_A];
3797
3798         if (!(bank->bitmap & (1 << idx))) {
3799                 struct trident_channel *channel = &bank->channels[idx];
3800                 bank->bitmap |= 1 << idx;
3801                 channel->num = idx;
3802                 return channel;
3803         }
3804
3805         /* no free recordable channels avaliable */
3806 #if 0 
3807         printk(KERN_ERR "ali: no recordable channels available on Bank A.\n");
3808 #endif /* 0 */ 
3809         return NULL;
3810 }
3811
3812 static void
3813 ali_set_spdif_out_rate(struct trident_card *card, unsigned int rate)
3814 {
3815         unsigned char ch_st_sel;
3816         unsigned short status_rate;
3817
3818         switch (rate) {
3819         case 44100:
3820                 status_rate = 0;
3821                 break;
3822         case 32000:
3823                 status_rate = 0x300;
3824                 break;
3825         case 48000:
3826         default:
3827                 status_rate = 0x200;
3828                 break;
3829         }
3830
3831         /* select spdif_out */ 
3832         ch_st_sel = inb(TRID_REG(card, ALI_SPDIF_CTRL)) & ALI_SPDIF_OUT_CH_STATUS;
3833
3834         ch_st_sel |= 0x80;      /* select right */ 
3835         outb(ch_st_sel, TRID_REG(card, ALI_SPDIF_CTRL));
3836         outb(status_rate | 0x20, TRID_REG(card, ALI_SPDIF_CS + 2));
3837
3838         ch_st_sel &= (~0x80);   /* select left */ 
3839         outb(ch_st_sel, TRID_REG(card, ALI_SPDIF_CTRL));
3840         outw(status_rate | 0x10, TRID_REG(card, ALI_SPDIF_CS + 2));
3841 }
3842
3843 static void
3844 ali_address_interrupt(struct trident_card *card)
3845 {
3846         int i, channel;
3847         struct trident_state *state;
3848         u32 mask, channel_mask;
3849
3850         mask = trident_get_interrupt_mask(card, 0);
3851         for (i = 0; i < NR_HW_CH; i++) {
3852                 if ((state = card->states[i]) == NULL)
3853                         continue;
3854                 channel = state->dmabuf.channel->num;
3855                 if ((channel_mask = 1 << channel) & mask) {
3856                         mask &= ~channel_mask;
3857                         trident_ack_channel_interrupt(card, channel);
3858                         udelay(100);
3859                         state->dmabuf.update_flag |= ALI_ADDRESS_INT_UPDATE;
3860                         trident_update_ptr(state);
3861                 }
3862         }
3863         if (mask) {
3864                 for (i = 0; i < NR_HW_CH; i++) {
3865                         if (mask & (1 << i)) {
3866                                 printk("ali: spurious channel irq %d.\n", i);
3867                                 trident_ack_channel_interrupt(card, i);
3868                                 trident_stop_voice(card, i);
3869                                 trident_disable_voice_irq(card, i);
3870                         }
3871                 }
3872         }
3873 }
3874
3875 /* Updating the values of counters of other_states' DMAs without lock 
3876 protection is no harm because all DMAs of multi-channels and interrupt
3877 depend on a master state's DMA, and changing the counters of the master
3878 state DMA is protected by a spinlock.
3879 */
3880 static int
3881 ali_write_5_1(struct trident_state *state, const char __user *buf, 
3882               int cnt_for_multi_channel, unsigned int *copy_count, 
3883               unsigned int *state_cnt)
3884 {
3885
3886         struct dmabuf *dmabuf = &state->dmabuf;
3887         struct dmabuf *dmabuf_temp;
3888         const char __user *buffer = buf;
3889         unsigned swptr, other_dma_nums, sample_s;
3890         unsigned int i, loop;
3891
3892         other_dma_nums = 4;
3893         sample_s = sample_size[dmabuf->fmt] >> 1;
3894         swptr = dmabuf->swptr;
3895
3896         if ((i = state->multi_channels_adjust_count) > 0) {
3897                 if (i == 1) {
3898                         if (copy_from_user(dmabuf->rawbuf + swptr, 
3899                                            buffer, sample_s))
3900                                 return -EFAULT;
3901                         seek_offset(swptr, buffer, cnt_for_multi_channel, 
3902                                     sample_s, *copy_count);
3903                         i--;
3904                         (*state_cnt) += sample_s;
3905                         state->multi_channels_adjust_count++;
3906                 } else
3907                         i = i - (state->chans_num - other_dma_nums);
3908                 for (; (i < other_dma_nums) && (cnt_for_multi_channel > 0); i++) {
3909                         dmabuf_temp = &state->other_states[i]->dmabuf;
3910                         if (copy_from_user(dmabuf_temp->rawbuf + dmabuf_temp->swptr, 
3911                                            buffer, sample_s))
3912                                 return -EFAULT;
3913                         seek_offset(dmabuf_temp->swptr, buffer, cnt_for_multi_channel, 
3914                                     sample_s, *copy_count);
3915                 }
3916                 if (cnt_for_multi_channel == 0)
3917                         state->multi_channels_adjust_count += i;
3918         }
3919         if (cnt_for_multi_channel > 0) {
3920                 loop = cnt_for_multi_channel / (state->chans_num * sample_s);
3921                 for (i = 0; i < loop; i++) {
3922                         if (copy_from_user(dmabuf->rawbuf + swptr, buffer, 
3923                                            sample_s * 2))
3924                                 return -EFAULT;
3925                         seek_offset(swptr, buffer, cnt_for_multi_channel, 
3926                                     sample_s * 2, *copy_count);
3927                         (*state_cnt) += (sample_s * 2);
3928
3929                         dmabuf_temp = &state->other_states[0]->dmabuf;
3930                         if (copy_from_user(dmabuf_temp->rawbuf + dmabuf_temp->swptr, 
3931                                            buffer, sample_s))
3932                                 return -EFAULT;
3933                         seek_offset(dmabuf_temp->swptr, buffer, cnt_for_multi_channel, 
3934                                     sample_s, *copy_count);
3935
3936                         dmabuf_temp = &state->other_states[1]->dmabuf;
3937                         if (copy_from_user(dmabuf_temp->rawbuf + dmabuf_temp->swptr, 
3938                                            buffer, sample_s))
3939                                 return -EFAULT;
3940                         seek_offset(dmabuf_temp->swptr, buffer, cnt_for_multi_channel, 
3941                                     sample_s, *copy_count);
3942
3943                         dmabuf_temp = &state->other_states[2]->dmabuf;
3944                         if (copy_from_user(dmabuf_temp->rawbuf + dmabuf_temp->swptr, 
3945                                            buffer, sample_s))
3946                                 return -EFAULT;
3947                         seek_offset(dmabuf_temp->swptr, buffer, cnt_for_multi_channel, 
3948                                     sample_s, *copy_count);
3949
3950                         dmabuf_temp = &state->other_states[3]->dmabuf;
3951                         if (copy_from_user(dmabuf_temp->rawbuf + dmabuf_temp->swptr, 
3952                                            buffer, sample_s))
3953                                 return -EFAULT;
3954                         seek_offset(dmabuf_temp->swptr, buffer, cnt_for_multi_channel, 
3955                                     sample_s, *copy_count);
3956                 }
3957
3958                 if (cnt_for_multi_channel > 0) {
3959                         state->multi_channels_adjust_count = cnt_for_multi_channel / sample_s;
3960
3961                         if (copy_from_user(dmabuf->rawbuf + swptr, buffer, sample_s))
3962                                 return -EFAULT;
3963                         seek_offset(swptr, buffer, cnt_for_multi_channel, 
3964                                     sample_s, *copy_count);
3965                         (*state_cnt) += sample_s;
3966
3967                         if (cnt_for_multi_channel > 0) {
3968                                 if (copy_from_user(dmabuf->rawbuf + swptr, 
3969                                                    buffer, sample_s))
3970                                         return -EFAULT;
3971                                 seek_offset(swptr, buffer, cnt_for_multi_channel, 
3972                                             sample_s, *copy_count);
3973                                 (*state_cnt) += sample_s;
3974
3975                                 if (cnt_for_multi_channel > 0) {
3976                                         int diff = state->chans_num - other_dma_nums;
3977                                         loop = state->multi_channels_adjust_count - diff;
3978                                         for (i = 0; i < loop; i++) {
3979                                                 dmabuf_temp = &state->other_states[i]->dmabuf;
3980                                                 if (copy_from_user(dmabuf_temp->rawbuf + 
3981                                                                    dmabuf_temp->swptr, 
3982                                                                    buffer, sample_s))
3983                                                         return -EFAULT;
3984                                                 seek_offset(dmabuf_temp->swptr, buffer, 
3985                                                             cnt_for_multi_channel, 
3986                                                             sample_s, *copy_count);
3987                                         }
3988                                 }
3989                         }
3990                 } else
3991                         state->multi_channels_adjust_count = 0;
3992         }
3993         for (i = 0; i < other_dma_nums; i++) {
3994                 dmabuf_temp = &state->other_states[i]->dmabuf;
3995                 dmabuf_temp->swptr = dmabuf_temp->swptr % dmabuf_temp->dmasize;
3996         }
3997         return *state_cnt;
3998 }
3999
4000 static void
4001 ali_free_other_states_resources(struct trident_state *state)
4002 {
4003         int i;
4004         struct trident_card *card = state->card;
4005         struct trident_state *s;
4006         unsigned other_states_count;
4007
4008         other_states_count = state->chans_num - 2; /* except PCM L/R channels */
4009         for (i = 0; i < other_states_count; i++) {
4010                 s = state->other_states[i];
4011                 dealloc_dmabuf(&s->dmabuf, card->pci_dev);
4012                 ali_disable_special_channel(s->card, s->dmabuf.channel->num);
4013                 state->card->free_pcm_channel(s->card, s->dmabuf.channel->num);
4014                 card->states[s->virt] = NULL;
4015                 kfree(s);
4016         }
4017 }
4018
4019 static struct proc_dir_entry *res;
4020
4021 static int
4022 ali_write_proc(struct file *file, const char __user *buffer, unsigned long count, void *data)
4023 {
4024         struct trident_card *card = (struct trident_card *) data;
4025         unsigned long flags;
4026         char c;
4027
4028         if (count < 0)
4029                 return -EINVAL;
4030         if (count == 0)
4031                 return 0;
4032         if (get_user(c, buffer))
4033                 return -EFAULT;
4034
4035         spin_lock_irqsave(&card->lock, flags);
4036         switch (c) {
4037         case '0':
4038                 ali_setup_spdif_out(card, ALI_PCM_TO_SPDIF_OUT);
4039                 ali_disable_special_channel(card, ALI_SPDIF_OUT_CHANNEL);
4040                 break;
4041         case '1':
4042                 ali_setup_spdif_out(card, ALI_SPDIF_OUT_TO_SPDIF_OUT | 
4043                                     ALI_SPDIF_OUT_PCM);
4044                 break;
4045         case '2':
4046                 ali_setup_spdif_out(card, ALI_SPDIF_OUT_TO_SPDIF_OUT | 
4047                                     ALI_SPDIF_OUT_NON_PCM);
4048                 break;
4049         case '3':
4050                 ali_disable_spdif_in(card);     //default
4051                 break;
4052         case '4':
4053                 ali_setup_spdif_in(card);
4054                 break;
4055         }
4056         spin_unlock_irqrestore(&card->lock, flags);
4057
4058         return count;
4059 }
4060
4061 /* OSS /dev/mixer file operation methods */
4062 static int
4063 trident_open_mixdev(struct inode *inode, struct file *file)
4064 {
4065         int i = 0;
4066         int minor = iminor(inode);
4067         struct trident_card *card = devs;
4068
4069         for (card = devs; card != NULL; card = card->next)
4070                 for (i = 0; i < NR_AC97; i++)
4071                         if (card->ac97_codec[i] != NULL && 
4072                             card->ac97_codec[i]->dev_mixer == minor)
4073                                 goto match;
4074
4075         if (!card) {
4076                 return -ENODEV;
4077         }
4078       match:
4079         file->private_data = card->ac97_codec[i];
4080
4081         return nonseekable_open(inode, file);
4082 }
4083
4084 static int
4085 trident_ioctl_mixdev(struct inode *inode, struct file *file, unsigned int cmd, 
4086                      unsigned long arg)
4087 {
4088         struct ac97_codec *codec = (struct ac97_codec *) file->private_data;
4089
4090         return codec->mixer_ioctl(codec, cmd, arg);
4091 }
4092
4093 static /*const */ struct file_operations trident_mixer_fops = {
4094         .owner = THIS_MODULE,
4095         .llseek = no_llseek,
4096         .ioctl = trident_ioctl_mixdev,
4097         .open = trident_open_mixdev,
4098 };
4099
4100 static int
4101 ali_reset_5451(struct trident_card *card)
4102 {
4103         struct pci_dev *pci_dev = NULL;
4104         unsigned int dwVal;
4105         unsigned short wCount, wReg;
4106
4107         pci_dev = pci_find_device(PCI_VENDOR_ID_AL, PCI_DEVICE_ID_AL_M1533, 
4108                                   pci_dev);
4109         if (pci_dev == NULL)
4110                 return -1;
4111
4112         pci_read_config_dword(pci_dev, 0x7c, &dwVal);
4113         pci_write_config_dword(pci_dev, 0x7c, dwVal | 0x08000000);
4114         udelay(5000);
4115         pci_read_config_dword(pci_dev, 0x7c, &dwVal);
4116         pci_write_config_dword(pci_dev, 0x7c, dwVal & 0xf7ffffff);
4117         udelay(5000);
4118
4119         pci_dev = card->pci_dev;
4120         if (pci_dev == NULL)
4121                 return -1;
4122
4123         pci_read_config_dword(pci_dev, 0x44, &dwVal);
4124         pci_write_config_dword(pci_dev, 0x44, dwVal | 0x000c0000);
4125         udelay(500);
4126         pci_read_config_dword(pci_dev, 0x44, &dwVal);
4127         pci_write_config_dword(pci_dev, 0x44, dwVal & 0xfffbffff);
4128         udelay(5000);
4129
4130         /* TODO: recognize if we have a PM capable codec and only do this */
4131         /* if the codec is PM capable */
4132         wCount = 2000;
4133         while (wCount--) {
4134                 wReg = ali_ac97_get(card, 0, AC97_POWER_CONTROL);
4135                 if ((wReg & 0x000f) == 0x000f)
4136                         return 0;
4137                 udelay(5000);
4138         }
4139         /* This is non fatal if you have a non PM capable codec.. */
4140         return 0;
4141 }
4142
4143 /* AC97 codec initialisation. */
4144 static int __devinit
4145 trident_ac97_init(struct trident_card *card)
4146 {
4147         int num_ac97 = 0;
4148         unsigned long ready_2nd = 0;
4149         struct ac97_codec *codec;
4150         int i = 0;
4151
4152         /* initialize controller side of AC link, and find out if secondary codes
4153            really exist */
4154         switch (card->pci_id) {
4155         case PCI_DEVICE_ID_ALI_5451:
4156                 if (ali_reset_5451(card)) {
4157                         printk(KERN_ERR "trident_ac97_init: error "
4158                                "resetting 5451.\n");
4159                         return -1;
4160                 }
4161                 outl(0x80000001, TRID_REG(card, ALI_GLOBAL_CONTROL));
4162                 outl(0x00000000, TRID_REG(card, T4D_AINTEN_A));
4163                 outl(0xffffffff, TRID_REG(card, T4D_AINT_A));
4164                 outl(0x00000000, TRID_REG(card, T4D_MUSICVOL_WAVEVOL));
4165                 outb(0x10, TRID_REG(card, ALI_MPUR2));
4166                 ready_2nd = inl(TRID_REG(card, ALI_SCTRL));
4167                 ready_2nd &= 0x3fff;
4168                 outl(ready_2nd | PCMOUT | 0x8000, TRID_REG(card, ALI_SCTRL));
4169                 ready_2nd = inl(TRID_REG(card, ALI_SCTRL));
4170                 ready_2nd &= SI_AC97_SECONDARY_READY;
4171                 if (card->revision < ALI_5451_V02)
4172                         ready_2nd = 0;
4173                 break;
4174         case PCI_DEVICE_ID_SI_7018:
4175                 /* disable AC97 GPIO interrupt */
4176                 outl(0x00, TRID_REG(card, SI_AC97_GPIO));
4177                 /* when power up the AC link is in cold reset mode so stop it */
4178                 outl(PCMOUT | SURROUT | CENTEROUT | LFEOUT | SECONDARY_ID, 
4179                      TRID_REG(card, SI_SERIAL_INTF_CTRL));
4180                 /* it take a long time to recover from a cold reset */ 
4181                 /* (especially when you have more than one codec) */
4182                 udelay(2000);
4183                 ready_2nd = inl(TRID_REG(card, SI_SERIAL_INTF_CTRL));
4184                 ready_2nd &= SI_AC97_SECONDARY_READY;
4185                 break;
4186         case PCI_DEVICE_ID_TRIDENT_4DWAVE_DX:
4187                 /* playback on */
4188                 outl(DX_AC97_PLAYBACK, TRID_REG(card, DX_ACR2_AC97_COM_STAT));
4189                 break;
4190         case PCI_DEVICE_ID_TRIDENT_4DWAVE_NX:
4191                 /* enable AC97 Output Slot 3,4 (PCM Left/Right Playback) */
4192                 outl(NX_AC97_PCM_OUTPUT, TRID_REG(card, NX_ACR0_AC97_COM_STAT));
4193                 ready_2nd = inl(TRID_REG(card, NX_ACR0_AC97_COM_STAT));
4194                 ready_2nd &= NX_AC97_SECONDARY_READY;
4195                 break;
4196         case PCI_DEVICE_ID_INTERG_5050:
4197                 /* disable AC97 GPIO interrupt */
4198                 outl(0x00, TRID_REG(card, SI_AC97_GPIO));
4199                 /* when power up, the AC link is in cold reset mode, so stop it */
4200                 outl(PCMOUT | SURROUT | CENTEROUT | LFEOUT, 
4201                      TRID_REG(card, SI_SERIAL_INTF_CTRL));
4202                 /* it take a long time to recover from a cold reset (especially */ 
4203                 /* when you have more than one codec) */
4204                 udelay(2000);
4205                 ready_2nd = inl(TRID_REG(card, SI_SERIAL_INTF_CTRL));
4206                 ready_2nd &= SI_AC97_SECONDARY_READY;
4207                 break;
4208         }
4209
4210         for (num_ac97 = 0; num_ac97 < NR_AC97; num_ac97++) {
4211                 if ((codec = ac97_alloc_codec()) == NULL)
4212                         return -ENOMEM;
4213
4214                 /* initialize some basic codec information, other fields */ 
4215                 /* will be filled in ac97_probe_codec */
4216                 codec->private_data = card;
4217                 codec->id = num_ac97;
4218
4219                 if (card->pci_id == PCI_DEVICE_ID_ALI_5451) {
4220                         codec->codec_read = ali_ac97_read;
4221                         codec->codec_write = ali_ac97_write;
4222                 } else {
4223                         codec->codec_read = trident_ac97_get;
4224                         codec->codec_write = trident_ac97_set;
4225                 }
4226
4227                 if (ac97_probe_codec(codec) == 0)
4228                         break;
4229
4230                 codec->dev_mixer = register_sound_mixer(&trident_mixer_fops, -1);
4231                 if (codec->dev_mixer < 0) {
4232                         printk(KERN_ERR "trident: couldn't register mixer!\n");
4233                         ac97_release_codec(codec);
4234                         break;
4235                 }
4236
4237                 card->ac97_codec[num_ac97] = codec;
4238
4239                 /* if there is no secondary codec at all, don't probe any more */
4240                 if (!ready_2nd)
4241                         break;
4242         }
4243
4244         if (card->pci_id == PCI_DEVICE_ID_ALI_5451) {
4245                 for (num_ac97 = 0; num_ac97 < NR_AC97; num_ac97++) {
4246                         if (card->ac97_codec[num_ac97] == NULL)
4247                                 break;
4248                         for (i = 0; i < 64; i++) {
4249                                 u16 reg = ali_ac97_get(card, num_ac97, i * 2);
4250                                 card->mixer_regs[i][num_ac97] = reg;
4251                         }
4252                 }
4253         }
4254         return num_ac97 + 1;
4255 }
4256
4257 #ifdef SUPPORT_JOYSTICK
4258 /* Gameport functions for the cards ADC gameport */
4259
4260 static unsigned char trident_game_read(struct gameport *gameport)
4261 {
4262         struct trident_card *card = gameport->port_data;
4263
4264         return inb(TRID_REG(card, T4D_GAME_LEG));
4265 }
4266
4267 static void trident_game_trigger(struct gameport *gameport)
4268 {
4269         struct trident_card *card = gameport->port_data;
4270
4271         outb(0xff, TRID_REG(card, T4D_GAME_LEG));
4272 }
4273
4274 static int trident_game_cooked_read(struct gameport *gameport,
4275                                     int *axes, int *buttons)
4276 {
4277         struct trident_card *card = gameport->port_data;
4278         int i;
4279
4280         *buttons = (~inb(TRID_REG(card, T4D_GAME_LEG)) >> 4) & 0xf;
4281
4282         for (i = 0; i < 4; i++) {
4283                 axes[i] = inw(TRID_REG(card, T4D_GAME_AXD) + i * sizeof (u16));
4284                 if (axes[i] == 0xffff)
4285                         axes[i] = -1;
4286         }
4287
4288         return 0;
4289 }
4290
4291 static int trident_game_open(struct gameport *gameport, int mode)
4292 {
4293         struct trident_card *card = gameport->port_data;
4294
4295         switch (mode) {
4296         case GAMEPORT_MODE_COOKED:
4297                 outb(0x80, TRID_REG(card, T4D_GAME_CR));
4298                 msleep(20);
4299                 return 0;
4300         case GAMEPORT_MODE_RAW:
4301                 outb(0x00, TRID_REG(card, T4D_GAME_CR));
4302                 return 0;
4303         default:
4304                 return -1;
4305         }
4306
4307         return 0;
4308 }
4309
4310 static int __devinit trident_register_gameport(struct trident_card *card)
4311 {
4312         struct gameport *gp;
4313
4314         card->gameport = gp = gameport_allocate_port();
4315         if (!gp) {
4316                 printk(KERN_ERR "trident: can not allocate memory for gameport\n");
4317                 return -ENOMEM;
4318         }
4319
4320         gameport_set_name(gp, "Trident 4DWave");
4321         gameport_set_phys(gp, "pci%s/gameport0", pci_name(card->pci_dev));
4322         gp->read = trident_game_read;
4323         gp->trigger = trident_game_trigger;
4324         gp->cooked_read = trident_game_cooked_read;
4325         gp->open = trident_game_open;
4326         gp->fuzz = 64;
4327         gp->port_data = card;
4328
4329         gameport_register_port(gp);
4330
4331         return 0;
4332 }
4333
4334 static inline void trident_unregister_gameport(struct trident_card *card)
4335 {
4336         if (card->gameport)
4337                 gameport_unregister_port(card->gameport);
4338 }
4339
4340 #else
4341 static inline int trident_register_gameport(struct trident_card *card) { return -ENOSYS; }
4342 static inline void trident_unregister_gameport(struct trident_card *card) { }
4343 #endif /* SUPPORT_JOYSTICK */
4344
4345 /* install the driver, we do not allocate hardware channel nor DMA buffer */ 
4346 /* now, they are defered until "ACCESS" time (in prog_dmabuf called by */ 
4347 /* open/read/write/ioctl/mmap) */
4348 static int __devinit
4349 trident_probe(struct pci_dev *pci_dev, const struct pci_device_id *pci_id)
4350 {
4351         unsigned long iobase;
4352         struct trident_card *card;
4353         u8 bits;
4354         u8 revision;
4355         int i = 0;
4356         u16 temp;
4357         struct pci_dev *pci_dev_m1533 = NULL;
4358         int rc = -ENODEV;
4359         u64 dma_mask;
4360
4361         if (pci_enable_device(pci_dev))
4362                 goto out;
4363
4364         if (pci_dev->device == PCI_DEVICE_ID_ALI_5451)
4365                 dma_mask = ALI_DMA_MASK;
4366         else
4367                 dma_mask = TRIDENT_DMA_MASK;
4368         if (pci_set_dma_mask(pci_dev, dma_mask)) {
4369                 printk(KERN_ERR "trident: architecture does not support" 
4370                        " %s PCI busmaster DMA\n", 
4371                        pci_dev->device == PCI_DEVICE_ID_ALI_5451 ? 
4372                        "32-bit" : "30-bit");
4373                 goto out;
4374         }
4375         pci_read_config_byte(pci_dev, PCI_CLASS_REVISION, &revision);
4376
4377         if (pci_id->device == PCI_DEVICE_ID_INTERG_5050)
4378                 iobase = pci_resource_start(pci_dev, 1);
4379         else
4380                 iobase = pci_resource_start(pci_dev, 0);
4381
4382         if (!request_region(iobase, 256, card_names[pci_id->driver_data])) {
4383                 printk(KERN_ERR "trident: can't allocate I/O space at "
4384                        "0x%4.4lx\n", iobase);
4385                 goto out;
4386         }
4387
4388         rc = -ENOMEM;
4389         if ((card = kmalloc(sizeof(*card), GFP_KERNEL)) == NULL) {
4390                 printk(KERN_ERR "trident: out of memory\n");
4391                 goto out_release_region;
4392         }
4393         memset(card, 0, sizeof (*card));
4394
4395         init_timer(&card->timer);
4396         card->iobase = iobase;
4397         card->pci_dev = pci_dev;
4398         card->pci_id = pci_id->device;
4399         card->revision = revision;
4400         card->irq = pci_dev->irq;
4401         card->next = devs;
4402         card->magic = TRIDENT_CARD_MAGIC;
4403         card->banks[BANK_A].addresses = &bank_a_addrs;
4404         card->banks[BANK_A].bitmap = 0UL;
4405         card->banks[BANK_B].addresses = &bank_b_addrs;
4406         card->banks[BANK_B].bitmap = 0UL;
4407
4408         init_MUTEX(&card->open_sem);
4409         spin_lock_init(&card->lock);
4410         init_timer(&card->timer);
4411
4412         devs = card;
4413
4414         pci_set_master(pci_dev);
4415
4416         printk(KERN_INFO "trident: %s found at IO 0x%04lx, IRQ %d\n", 
4417                card_names[pci_id->driver_data], card->iobase, card->irq);
4418
4419         if (card->pci_id == PCI_DEVICE_ID_ALI_5451) {
4420                 /* ALi channel Management */
4421                 card->alloc_pcm_channel = ali_alloc_pcm_channel;
4422                 card->alloc_rec_pcm_channel = ali_alloc_rec_pcm_channel;
4423                 card->free_pcm_channel = ali_free_pcm_channel;
4424
4425                 card->address_interrupt = ali_address_interrupt;
4426
4427                 /* Added by Matt Wu 01-05-2001 for spdif in */
4428                 card->multi_channel_use_count = 0;
4429                 card->rec_channel_use_count = 0;
4430
4431                 /* ALi SPDIF OUT function */
4432                 if (card->revision == ALI_5451_V02) {
4433                         ali_setup_spdif_out(card, ALI_PCM_TO_SPDIF_OUT);
4434                         res = create_proc_entry("ALi5451", 0, NULL);
4435                         if (res) {
4436                                 res->write_proc = ali_write_proc;
4437                                 res->data = card;
4438                         }
4439                 }
4440
4441                 /* Add H/W Volume Control By Matt Wu Jul. 06, 2001 */
4442                 card->hwvolctl = 0;
4443                 pci_dev_m1533 = pci_find_device(PCI_VENDOR_ID_AL, 
4444                                                 PCI_DEVICE_ID_AL_M1533, 
4445                                                 pci_dev_m1533);
4446                 rc = -ENODEV;
4447                 if (pci_dev_m1533 == NULL)
4448                         goto out_proc_fs;
4449                 pci_read_config_byte(pci_dev_m1533, 0x63, &bits);
4450                 if (bits & (1 << 5))
4451                         card->hwvolctl = 1;
4452                 if (card->hwvolctl) {
4453                         /* Clear m1533 pci cfg 78h bit 30 to zero, which makes
4454                            GPIO11/12/13 work as ACGP_UP/DOWN/MUTE. */
4455                         pci_read_config_byte(pci_dev_m1533, 0x7b, &bits);
4456                         bits &= 0xbf;   /*clear bit 6 */
4457                         pci_write_config_byte(pci_dev_m1533, 0x7b, bits);
4458                 }
4459         } else if (card->pci_id == PCI_DEVICE_ID_INTERG_5050) {
4460                 card->alloc_pcm_channel = cyber_alloc_pcm_channel;
4461                 card->alloc_rec_pcm_channel = cyber_alloc_pcm_channel;
4462                 card->free_pcm_channel = cyber_free_pcm_channel;
4463                 card->address_interrupt = cyber_address_interrupt;
4464                 cyber_init_ritual(card);
4465         } else {
4466                 card->alloc_pcm_channel = trident_alloc_pcm_channel;
4467                 card->alloc_rec_pcm_channel = trident_alloc_pcm_channel;
4468                 card->free_pcm_channel = trident_free_pcm_channel;
4469                 card->address_interrupt = trident_address_interrupt;
4470         }
4471
4472         /* claim our irq */
4473         rc = -ENODEV;
4474         if (request_irq(card->irq, &trident_interrupt, SA_SHIRQ, 
4475                         card_names[pci_id->driver_data], card)) {
4476                 printk(KERN_ERR "trident: unable to allocate irq %d\n", 
4477                        card->irq);
4478                 goto out_proc_fs;
4479         }
4480         /* register /dev/dsp */
4481         if ((card->dev_audio = register_sound_dsp(&trident_audio_fops, -1)) < 0) {
4482                 printk(KERN_ERR "trident: couldn't register DSP device!\n");
4483                 goto out_free_irq;
4484         }
4485         card->mixer_regs_ready = 0;
4486         /* initialize AC97 codec and register /dev/mixer */
4487         if (trident_ac97_init(card) <= 0) {
4488                 /* unregister audio devices */
4489                 for (i = 0; i < NR_AC97; i++) {
4490                         if (card->ac97_codec[i] != NULL) {
4491                                 struct ac97_codec* codec = card->ac97_codec[i];
4492                                 unregister_sound_mixer(codec->dev_mixer);
4493                                 ac97_release_codec(codec);
4494                         }
4495                 }
4496                 goto out_unregister_sound_dsp;
4497         }
4498         card->mixer_regs_ready = 1;
4499         outl(0x00, TRID_REG(card, T4D_MUSICVOL_WAVEVOL));
4500
4501         if (card->pci_id == PCI_DEVICE_ID_ALI_5451) {
4502                 /* Add H/W Volume Control By Matt Wu Jul. 06, 2001 */
4503                 if (card->hwvolctl) {
4504                         /* Enable GPIO IRQ (MISCINT bit 18h) */
4505                         temp = inw(TRID_REG(card, T4D_MISCINT + 2));
4506                         temp |= 0x0004;
4507                         outw(temp, TRID_REG(card, T4D_MISCINT + 2));
4508
4509                         /* Enable H/W Volume Control GLOVAL CONTROL bit 0 */
4510                         temp = inw(TRID_REG(card, ALI_GLOBAL_CONTROL));
4511                         temp |= 0x0001;
4512                         outw(temp, TRID_REG(card, ALI_GLOBAL_CONTROL));
4513
4514                 }
4515                 if (card->revision == ALI_5451_V02)
4516                         ali_close_multi_channels();
4517                 /* edited by HMSEO for GT sound */
4518 #if defined(CONFIG_ALPHA_NAUTILUS) || defined(CONFIG_ALPHA_GENERIC)
4519                 {
4520                         u16 ac97_data;
4521                         extern struct hwrpb_struct *hwrpb;
4522
4523                         if ((hwrpb->sys_type) == 201) {
4524                                 printk(KERN_INFO "trident: Running on Alpha system "
4525                                        "type Nautilus\n");
4526                                 ac97_data = ali_ac97_get(card, 0, AC97_POWER_CONTROL);
4527                                 ali_ac97_set(card, 0, AC97_POWER_CONTROL, 
4528                                              ac97_data | ALI_EAPD_POWER_DOWN);
4529                         }
4530                 }
4531 #endif                          /* CONFIG_ALPHA_NAUTILUS || CONFIG_ALPHA_GENERIC */
4532                 /* edited by HMSEO for GT sound */
4533         }
4534         rc = 0;
4535         pci_set_drvdata(pci_dev, card);
4536
4537         /* Enable Address Engine Interrupts */
4538         trident_enable_loop_interrupts(card);
4539
4540         /* Register gameport */
4541         trident_register_gameport(card);
4542
4543 out:
4544         return rc;
4545
4546 out_unregister_sound_dsp:
4547         unregister_sound_dsp(card->dev_audio);
4548 out_free_irq:
4549         free_irq(card->irq, card);
4550 out_proc_fs:
4551         if (res) {
4552                 remove_proc_entry("ALi5451", NULL);
4553                 res = NULL;
4554         }
4555         kfree(card);
4556         devs = NULL;
4557 out_release_region:
4558         release_region(iobase, 256);
4559         return rc; 
4560 }
4561
4562 static void __devexit
4563 trident_remove(struct pci_dev *pci_dev)
4564 {
4565         int i;
4566         struct trident_card *card = pci_get_drvdata(pci_dev);
4567
4568         /*
4569          *      Kill running timers before unload. We can't have them
4570          *      going off after rmmod!
4571          */
4572         if (card->hwvolctl)
4573                 del_timer_sync(&card->timer);
4574
4575         /* ALi S/PDIF and Power Management */
4576         if (card->pci_id == PCI_DEVICE_ID_ALI_5451) {
4577                 ali_setup_spdif_out(card, ALI_PCM_TO_SPDIF_OUT);
4578                 ali_disable_special_channel(card, ALI_SPDIF_OUT_CHANNEL);
4579                 ali_disable_spdif_in(card);
4580                 remove_proc_entry("ALi5451", NULL);
4581         }
4582
4583         /* Unregister gameport */
4584         trident_unregister_gameport(card);
4585
4586         /* Kill interrupts, and SP/DIF */
4587         trident_disable_loop_interrupts(card);
4588
4589         /* free hardware resources */
4590         free_irq(card->irq, card);
4591         release_region(card->iobase, 256);
4592
4593         /* unregister audio devices */
4594         for (i = 0; i < NR_AC97; i++)
4595                 if (card->ac97_codec[i] != NULL) {
4596                         unregister_sound_mixer(card->ac97_codec[i]->dev_mixer);
4597                         ac97_release_codec(card->ac97_codec[i]);
4598                 }
4599         unregister_sound_dsp(card->dev_audio);
4600
4601         kfree(card);
4602
4603         pci_set_drvdata(pci_dev, NULL);
4604 }
4605
4606 MODULE_AUTHOR("Alan Cox, Aaron Holtzman, Ollie Lho, Ching Ling Lee, Muli Ben-Yehuda");
4607 MODULE_DESCRIPTION("Trident 4DWave/SiS 7018/ALi 5451 and Tvia/IGST CyberPro5050 PCI "
4608                    "Audio Driver");
4609 MODULE_LICENSE("GPL");
4610
4611 #define TRIDENT_MODULE_NAME "trident"
4612
4613 static struct pci_driver trident_pci_driver = {
4614         .name = TRIDENT_MODULE_NAME,
4615         .id_table = trident_pci_tbl,
4616         .probe = trident_probe,
4617         .remove = __devexit_p(trident_remove),
4618         .suspend = trident_suspend,
4619         .resume = trident_resume
4620 };
4621
4622 static int __init
4623 trident_init_module(void)
4624 {
4625         printk(KERN_INFO "Trident 4DWave/SiS 7018/ALi 5451,Tvia CyberPro " 
4626                "5050 PCI Audio, version " DRIVER_VERSION ", " __TIME__ " " 
4627                __DATE__ "\n");
4628
4629         return pci_register_driver(&trident_pci_driver);
4630 }
4631
4632 static void __exit
4633 trident_cleanup_module(void)
4634 {
4635         pci_unregister_driver(&trident_pci_driver);
4636 }
4637
4638 module_init(trident_init_module);
4639 module_exit(trident_cleanup_module);