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