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