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