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