Merge branch 'release' of master.kernel.org:/pub/scm/linux/kernel/git/lenb/linux...
[pandora-kernel.git] / sound / oss / cs46xx.c
1 /*
2  *      Crystal SoundFusion CS46xx driver
3  *
4  *      Copyright 1998-2001 Cirrus Logic Corporation <pcaudio@crystal.cirrus.com>
5  *                                              <twoller@crystal.cirrus.com>
6  *      Copyright 1999-2000 Jaroslav Kysela <perex@suse.cz>
7  *      Copyright 2000 Alan Cox <alan@redhat.com>
8  *
9  *      The core of this code is taken from the ALSA project driver by 
10  *      Jaroslav. Please send Jaroslav the credit for the driver and 
11  *      report bugs in this port to <alan@redhat.com>
12  *
13  *      This program is free software; you can redistribute it and/or modify
14  *      it under the terms of the GNU General Public License as published by
15  *      the Free Software Foundation; either version 2 of the License, or
16  *      (at your option) any later version.
17  *
18  *      This program is distributed in the hope that it will be useful,
19  *      but WITHOUT ANY WARRANTY; without even the implied warranty of
20  *      MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
21  *      GNU General Public License for more details.
22  *
23  *      You should have received a copy of the GNU General Public License
24  *      along with this program; if not, write to the Free Software
25  *      Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
26  *      Current maintainers:
27  *              Cirrus Logic Corporation, Thomas Woller (tw)
28  *                      <twoller@crystal.cirrus.com>
29  *              Nils Faerber (nf)
30  *                      <nils@kernelconcepts.de>
31  *              Thanks to David Pollard for testing.
32  *
33  *      Changes:
34  *      20000909-nf     Changed cs_read, cs_write and drain_dac
35  *      20001025-tw     Separate Playback/Capture structs and buffers.
36  *                      Added Scatter/Gather support for Playback.
37  *                      Added Capture.
38  *      20001027-nf     Port to kernel 2.4.0-test9, some clean-ups
39  *                      Start of powermanagement support (CS46XX_PM).
40  *      20001128-tw     Add module parm for default buffer order.
41  *                      added DMA_GFP flag to kmalloc dma buffer allocs.
42  *                      backfill silence to eliminate stuttering on
43  *                      underruns.
44  *      20001201-tw     add resyncing of swptr on underruns.
45  *      20001205-tw-nf  fixed GETOSPACE ioctl() after open()
46  *      20010113-tw     patch from Hans Grobler general cleanup.
47  *      20010117-tw     2.4.0 pci cleanup, wrapper code for 2.2.16-2.4.0
48  *      20010118-tw     basic PM support for 2.2.16+ and 2.4.0/2.4.2.
49  *      20010228-dh     patch from David Huggins - cs_update_ptr recursion.
50  *      20010409-tw     add hercules game theatre XP amp code.
51  *      20010420-tw     cleanup powerdown/up code.
52  *      20010521-tw     eliminate pops, and fixes for powerdown.
53  *      20010525-tw     added fixes for thinkpads with powerdown logic.
54  *      20010723-sh     patch from Horms (Simon Horman) -
55  *                      SOUND_PCM_READ_BITS returns bits as set in driver
56  *                      rather than a logical or of the possible values.
57  *                      Various ioctls handle the case where the device
58  *                      is open for reading or writing but not both better.
59  *
60  *      Status:
61  *      Playback/Capture supported from 8k-48k.
62  *      16Bit Signed LE & 8Bit Unsigned, with Mono or Stereo supported.
63  *
64  *      APM/PM - 2.2.x APM is enabled and functioning fine. APM can also
65  *      be enabled for 2.4.x by modifying the CS46XX_ACPI_SUPPORT macro
66  *      definition.
67  *
68  *      Hercules Game Theatre XP - the EGPIO2 pin controls the external Amp,
69  *      so, use the drain/polarity to enable.  
70  *      hercules_egpio_disable set to 1, will force a 0 to EGPIODR.
71  *
72  *      VTB Santa Cruz - the GPIO7/GPIO8 on the Secondary Codec control
73  *      the external amplifier for the "back" speakers, since we do not
74  *      support the secondary codec then this external amp is also not
75  *      turned on.
76  */
77  
78 #include <linux/interrupt.h>
79 #include <linux/list.h>
80 #include <linux/module.h>
81 #include <linux/string.h>
82 #include <linux/ioport.h>
83 #include <linux/sched.h>
84 #include <linux/delay.h>
85 #include <linux/sound.h>
86 #include <linux/slab.h>
87 #include <linux/soundcard.h>
88 #include <linux/pci.h>
89 #include <linux/bitops.h>
90 #include <linux/init.h>
91 #include <linux/poll.h>
92 #include <linux/ac97_codec.h>
93 #include <linux/mutex.h>
94
95 #include <asm/io.h>
96 #include <asm/dma.h>
97 #include <asm/uaccess.h>
98
99 #include "cs46xxpm.h"
100 #include "cs46xx_wrapper-24.h"
101 #include "cs461x.h"
102
103 /* MIDI buffer sizes */
104 #define CS_MIDIINBUF  500
105 #define CS_MIDIOUTBUF 500
106
107 #define ADC_RUNNING     1
108 #define DAC_RUNNING     2
109
110 #define CS_FMT_16BIT    1               /* These are fixed in fact */
111 #define CS_FMT_STEREO   2
112 #define CS_FMT_MASK     3
113
114 #define CS_TYPE_ADC     1
115 #define CS_TYPE_DAC     2
116
117 #define CS_TRUE         1
118 #define CS_FALSE        0
119
120 #define CS_INC_USE_COUNT(m) (atomic_inc(m))
121 #define CS_DEC_USE_COUNT(m) (atomic_dec(m))
122 #define CS_DEC_AND_TEST(m) (atomic_dec_and_test(m))
123 #define CS_IN_USE(m) (atomic_read(m) != 0)
124
125 #define CS_DBGBREAKPOINT {__asm__("INT $3");}
126 /*
127  *      CS461x definitions
128  */
129  
130 #define CS461X_BA0_SIZE         0x2000
131 #define CS461X_BA1_DATA0_SIZE   0x3000
132 #define CS461X_BA1_DATA1_SIZE   0x3800
133 #define CS461X_BA1_PRG_SIZE     0x7000
134 #define CS461X_BA1_REG_SIZE     0x0100
135
136 #define GOF_PER_SEC     200
137
138 #define CSDEBUG_INTERFACE 1
139 #define CSDEBUG 1
140 /*
141  * Turn on/off debugging compilation by using 1/0 respectively for CSDEBUG
142  *
143  *
144  * CSDEBUG is usual mode is set to 1, then use the
145  * cs_debuglevel and cs_debugmask to turn on or off debugging.
146  * Debug level of 1 has been defined to be kernel errors and info
147  * that should be printed on any released driver.
148  */
149 #if CSDEBUG
150 #define CS_DBGOUT(mask,level,x) if ((cs_debuglevel >= (level)) && ((mask) & cs_debugmask)) {x;}
151 #else
152 #define CS_DBGOUT(mask,level,x) 
153 #endif
154 /*
155  * cs_debugmask areas
156  */
157 #define CS_INIT         0x00000001              /* initialization and probe functions */
158 #define CS_ERROR        0x00000002              /* tmp debugging bit placeholder */
159 #define CS_INTERRUPT    0x00000004              /* interrupt handler (separate from all other) */
160 #define CS_FUNCTION     0x00000008              /* enter/leave functions */
161 #define CS_WAVE_WRITE   0x00000010              /* write information for wave */
162 #define CS_WAVE_READ    0x00000020              /* read information for wave */
163 #define CS_MIDI_WRITE   0x00000040              /* write information for midi */
164 #define CS_MIDI_READ    0x00000080              /* read information for midi */
165 #define CS_MPU401_WRITE 0x00000100              /* write information for mpu401 */
166 #define CS_MPU401_READ  0x00000200              /* read information for mpu401 */
167 #define CS_OPEN         0x00000400              /* all open functions in the driver */
168 #define CS_RELEASE      0x00000800              /* all release functions in the driver */
169 #define CS_PARMS        0x00001000              /* functional and operational parameters */
170 #define CS_IOCTL        0x00002000              /* ioctl (non-mixer) */
171 #define CS_PM           0x00004000              /* PM */
172 #define CS_TMP          0x10000000              /* tmp debug mask bit */
173
174 #define CS_IOCTL_CMD_SUSPEND    0x1     // suspend
175 #define CS_IOCTL_CMD_RESUME     0x2     // resume
176
177 #if CSDEBUG
178 static unsigned long cs_debuglevel = 1;                 /* levels range from 1-9 */
179 module_param(cs_debuglevel, ulong, 0644);
180 static unsigned long cs_debugmask = CS_INIT | CS_ERROR; /* use CS_DBGOUT with various mask values */
181 module_param(cs_debugmask, ulong, 0644);
182 #endif
183 static unsigned long hercules_egpio_disable;  /* if non-zero set all EGPIO to 0 */
184 module_param(hercules_egpio_disable, ulong, 0);
185 static unsigned long initdelay = 700;  /* PM delay in millisecs */
186 module_param(initdelay, ulong, 0);
187 static unsigned long powerdown = -1;  /* turn on/off powerdown processing in driver */
188 module_param(powerdown, ulong, 0);
189 #define DMABUF_DEFAULTORDER 3
190 static unsigned long defaultorder = DMABUF_DEFAULTORDER;
191 module_param(defaultorder, ulong, 0);
192
193 static int external_amp;
194 module_param(external_amp, bool, 0);
195 static int thinkpad;
196 module_param(thinkpad, bool, 0);
197
198 /*
199 * set the powerdown module parm to 0 to disable all 
200 * powerdown. also set thinkpad to 1 to disable powerdown, 
201 * but also to enable the clkrun functionality.
202 */
203 static unsigned cs_powerdown = 1;
204 static unsigned cs_laptop_wait = 1;
205
206 /* An instance of the 4610 channel */
207 struct cs_channel 
208 {
209         int used;
210         int num;
211         void *state;
212 };
213
214 #define CS46XX_MAJOR_VERSION "1"
215 #define CS46XX_MINOR_VERSION "28"
216
217 #ifdef __ia64__
218 #define CS46XX_ARCH             "64"    //architecture key
219 #else
220 #define CS46XX_ARCH             "32"    //architecture key
221 #endif
222
223 static struct list_head cs46xx_devs = { &cs46xx_devs, &cs46xx_devs };
224
225 /* magic numbers to protect our data structures */
226 #define CS_CARD_MAGIC           0x43525553 /* "CRUS" */
227 #define CS_STATE_MAGIC          0x4c4f4749 /* "LOGI" */
228 #define NR_HW_CH                3
229
230 /* maxinum number of AC97 codecs connected, AC97 2.0 defined 4 */
231 #define NR_AC97         2
232
233 static const unsigned sample_size[] = { 1, 2, 2, 4 };
234 static const unsigned sample_shift[] = { 0, 1, 1, 2 };
235
236 /* "software" or virtual channel, an instance of opened /dev/dsp */
237 struct cs_state {
238         unsigned int magic;
239         struct cs_card *card;   /* Card info */
240
241         /* single open lock mechanism, only used for recording */
242         struct mutex open_mutex;
243         wait_queue_head_t open_wait;
244
245         /* file mode */
246         mode_t open_mode;
247
248         /* virtual channel number */
249         int virt;
250         
251         struct dmabuf {
252                 /* wave sample stuff */
253                 unsigned int rate;
254                 unsigned char fmt, enable;
255
256                 /* hardware channel */
257                 struct cs_channel *channel;
258                 int pringbuf;           /* Software ring slot */
259                 void *pbuf;             /* 4K hardware DMA buffer */
260
261                 /* OSS buffer management stuff */
262                 void *rawbuf;
263                 dma_addr_t dma_handle;
264                 unsigned buforder;
265                 unsigned numfrag;
266                 unsigned fragshift;
267                 unsigned divisor;
268                 unsigned type;
269                 void *tmpbuff;                  /* tmp buffer for sample conversions */
270                 dma_addr_t dmaaddr;
271                 dma_addr_t dmaaddr_tmpbuff;
272                 unsigned buforder_tmpbuff;      /* Log base 2 of size in bytes.. */
273
274                 /* our buffer acts like a circular ring */
275                 unsigned hwptr;         /* where dma last started, updated by update_ptr */
276                 unsigned swptr;         /* where driver last clear/filled, updated by read/write */
277                 int count;              /* bytes to be comsumed or been generated by dma machine */
278                 unsigned total_bytes;   /* total bytes dmaed by hardware */
279                 unsigned blocks;        /* total blocks */
280
281                 unsigned error;         /* number of over/underruns */
282                 unsigned underrun;      /* underrun pending before next write has occurred */
283                 wait_queue_head_t wait; /* put process on wait queue when no more space in buffer */
284
285                 /* redundant, but makes calculations easier */
286                 unsigned fragsize;
287                 unsigned dmasize;
288                 unsigned fragsamples;
289
290                 /* OSS stuff */
291                 unsigned mapped:1;
292                 unsigned ready:1;
293                 unsigned endcleared:1;
294                 unsigned SGok:1;
295                 unsigned update_flag;
296                 unsigned ossfragshift;
297                 int ossmaxfrags;
298                 unsigned subdivision;
299         } dmabuf;
300         /* Guard against mmap/write/read races */
301         struct mutex sem;
302 };
303
304 struct cs_card {
305         struct cs_channel channel[2];
306         unsigned int magic;
307
308         /* We keep cs461x cards in a linked list */
309         struct cs_card *next;
310
311         /* The cs461x has a certain amount of cross channel interaction
312            so we use a single per card lock */
313         spinlock_t lock;
314         
315         /* Keep AC97 sane */
316         spinlock_t ac97_lock;
317
318         /* mixer use count */
319         atomic_t mixer_use_cnt;
320
321         /* PCI device stuff */
322         struct pci_dev *pci_dev;
323         struct list_head list;
324
325         unsigned int pctl, cctl;        /* Hardware DMA flag sets */
326
327         /* soundcore stuff */
328         int dev_audio;
329         int dev_midi;
330
331         /* structures for abstraction of hardware facilities, codecs, banks and channels*/
332         struct ac97_codec *ac97_codec[NR_AC97];
333         struct cs_state *states[2];
334
335         u16 ac97_features;
336         
337         int amplifier;                  /* Amplifier control */
338         void (*amplifier_ctrl)(struct cs_card *, int);
339         void (*amp_init)(struct cs_card *);
340         
341         int active;                     /* Active clocking */
342         void (*active_ctrl)(struct cs_card *, int);
343         
344         /* hardware resources */
345         unsigned long ba0_addr;
346         unsigned long ba1_addr;
347         u32 irq;
348         
349         /* mappings */
350         void __iomem *ba0;
351         union
352         {
353                 struct
354                 {
355                         u8 __iomem *data0;
356                         u8 __iomem *data1;
357                         u8 __iomem *pmem;
358                         u8 __iomem *reg;
359                 } name;
360                 u8 __iomem *idx[4];
361         } ba1;
362         
363         /* Function support */
364         struct cs_channel *(*alloc_pcm_channel)(struct cs_card *);
365         struct cs_channel *(*alloc_rec_pcm_channel)(struct cs_card *);
366         void (*free_pcm_channel)(struct cs_card *, int chan);
367
368         /* /dev/midi stuff */
369         struct {
370                 unsigned ird, iwr, icnt;
371                 unsigned ord, owr, ocnt;
372                 wait_queue_head_t open_wait;
373                 wait_queue_head_t iwait;
374                 wait_queue_head_t owait;
375                 spinlock_t lock;
376                 unsigned char ibuf[CS_MIDIINBUF];
377                 unsigned char obuf[CS_MIDIOUTBUF];
378                 mode_t open_mode;
379                 struct mutex open_mutex;
380         } midi;
381         struct cs46xx_pm pm;
382 };
383
384 static int cs_open_mixdev(struct inode *inode, struct file *file);
385 static int cs_release_mixdev(struct inode *inode, struct file *file);
386 static int cs_ioctl_mixdev(struct inode *inode, struct file *file, unsigned int cmd,
387                         unsigned long arg);
388 static int cs_hardware_init(struct cs_card *card);
389 static int cs46xx_powerup(struct cs_card *card, unsigned int type);
390 static int cs461x_powerdown(struct cs_card *card, unsigned int type, int suspendflag);
391 static void cs461x_clear_serial_FIFOs(struct cs_card *card, int type);
392 #ifdef CONFIG_PM
393 static int cs46xx_suspend_tbl(struct pci_dev *pcidev, pm_message_t state);
394 static int cs46xx_resume_tbl(struct pci_dev *pcidev);
395 #endif
396
397 #if CSDEBUG
398
399 /* DEBUG ROUTINES */
400
401 #define SOUND_MIXER_CS_GETDBGLEVEL      _SIOWR('M',120, int)
402 #define SOUND_MIXER_CS_SETDBGLEVEL      _SIOWR('M',121, int)
403 #define SOUND_MIXER_CS_GETDBGMASK       _SIOWR('M',122, int)
404 #define SOUND_MIXER_CS_SETDBGMASK       _SIOWR('M',123, int)
405 #define SOUND_MIXER_CS_APM              _SIOWR('M',124, int)
406
407 static void printioctl(unsigned int x)
408 {
409     unsigned int i;
410     unsigned char vidx;
411         /* these values are incorrect for the ac97 driver, fix.
412          * Index of mixtable1[] member is Device ID 
413          * and must be <= SOUND_MIXER_NRDEVICES.
414          * Value of array member is index into s->mix.vol[]
415          */
416         static const unsigned char mixtable1[SOUND_MIXER_NRDEVICES] = {
417                 [SOUND_MIXER_PCM]     = 1,   /* voice */
418                 [SOUND_MIXER_LINE1]   = 2,   /* AUX */
419                 [SOUND_MIXER_CD]      = 3,   /* CD */
420                 [SOUND_MIXER_LINE]    = 4,   /* Line */
421                 [SOUND_MIXER_SYNTH]   = 5,   /* FM */
422                 [SOUND_MIXER_MIC]     = 6,   /* Mic */
423                 [SOUND_MIXER_SPEAKER] = 7,   /* Speaker */
424                 [SOUND_MIXER_RECLEV]  = 8,   /* Recording level */
425                 [SOUND_MIXER_VOLUME]  = 9    /* Master Volume */
426         };
427         
428     switch (x) {
429         case SOUND_MIXER_CS_GETDBGMASK:
430                 CS_DBGOUT(CS_IOCTL, 4, printk("SOUND_MIXER_CS_GETDBGMASK: ") );
431                 break;
432         case SOUND_MIXER_CS_GETDBGLEVEL:
433                 CS_DBGOUT(CS_IOCTL, 4, printk("SOUND_MIXER_CS_GETDBGLEVEL: ") );
434                 break;
435         case SOUND_MIXER_CS_SETDBGMASK:
436                 CS_DBGOUT(CS_IOCTL, 4, printk("SOUND_MIXER_CS_SETDBGMASK: ") );
437                 break;
438         case SOUND_MIXER_CS_SETDBGLEVEL:
439                 CS_DBGOUT(CS_IOCTL, 4, printk("SOUND_MIXER_CS_SETDBGLEVEL: ") );
440                 break;
441         case OSS_GETVERSION:
442                 CS_DBGOUT(CS_IOCTL, 4, printk("OSS_GETVERSION: ") );
443                 break;
444         case SNDCTL_DSP_SYNC:
445                 CS_DBGOUT(CS_IOCTL, 4, printk("SNDCTL_DSP_SYNC: ") );
446                 break;
447         case SNDCTL_DSP_SETDUPLEX:
448                 CS_DBGOUT(CS_IOCTL, 4, printk("SNDCTL_DSP_SETDUPLEX: ") );
449                 break;
450         case SNDCTL_DSP_GETCAPS:
451                 CS_DBGOUT(CS_IOCTL, 4, printk("SNDCTL_DSP_GETCAPS: ") );
452                 break;
453         case SNDCTL_DSP_RESET:
454                 CS_DBGOUT(CS_IOCTL, 4, printk("SNDCTL_DSP_RESET: ") );
455                 break;
456         case SNDCTL_DSP_SPEED:
457                 CS_DBGOUT(CS_IOCTL, 4, printk("SNDCTL_DSP_SPEED: ") );
458                 break;
459         case SNDCTL_DSP_STEREO:
460                 CS_DBGOUT(CS_IOCTL, 4, printk("SNDCTL_DSP_STEREO: ") );
461                 break;
462         case SNDCTL_DSP_CHANNELS:
463                 CS_DBGOUT(CS_IOCTL, 4, printk("SNDCTL_DSP_CHANNELS: ") );
464                 break;
465         case SNDCTL_DSP_GETFMTS: 
466                 CS_DBGOUT(CS_IOCTL, 4, printk("SNDCTL_DSP_GETFMTS: ") );
467                 break;
468         case SNDCTL_DSP_SETFMT: 
469                 CS_DBGOUT(CS_IOCTL, 4, printk("SNDCTL_DSP_SETFMT: ") );
470                 break;
471         case SNDCTL_DSP_POST:
472                 CS_DBGOUT(CS_IOCTL, 4, printk("SNDCTL_DSP_POST: ") );
473                 break;
474         case SNDCTL_DSP_GETTRIGGER:
475                 CS_DBGOUT(CS_IOCTL, 4, printk("SNDCTL_DSP_GETTRIGGER: ") );
476                 break;
477         case SNDCTL_DSP_SETTRIGGER:
478                 CS_DBGOUT(CS_IOCTL, 4, printk("SNDCTL_DSP_SETTRIGGER: ") );
479                 break;
480         case SNDCTL_DSP_GETOSPACE:
481                 CS_DBGOUT(CS_IOCTL, 4, printk("SNDCTL_DSP_GETOSPACE: ") );
482                 break;
483         case SNDCTL_DSP_GETISPACE:
484                 CS_DBGOUT(CS_IOCTL, 4, printk("SNDCTL_DSP_GETISPACE: ") );
485                 break;
486         case SNDCTL_DSP_NONBLOCK:
487                 CS_DBGOUT(CS_IOCTL, 4, printk("SNDCTL_DSP_NONBLOCK: ") );
488                 break;
489         case SNDCTL_DSP_GETODELAY:
490                 CS_DBGOUT(CS_IOCTL, 4, printk("SNDCTL_DSP_GETODELAY: ") );
491                 break;
492         case SNDCTL_DSP_GETIPTR:
493                 CS_DBGOUT(CS_IOCTL, 4, printk("SNDCTL_DSP_GETIPTR: ") );
494                 break;
495         case SNDCTL_DSP_GETOPTR:
496                 CS_DBGOUT(CS_IOCTL, 4, printk("SNDCTL_DSP_GETOPTR: ") );
497                 break;
498         case SNDCTL_DSP_GETBLKSIZE:
499                 CS_DBGOUT(CS_IOCTL, 4, printk("SNDCTL_DSP_GETBLKSIZE: ") );
500                 break;
501         case SNDCTL_DSP_SETFRAGMENT:
502                 CS_DBGOUT(CS_IOCTL, 4, printk("SNDCTL_DSP_SETFRAGMENT: ") );
503                 break;
504         case SNDCTL_DSP_SUBDIVIDE:
505                 CS_DBGOUT(CS_IOCTL, 4, printk("SNDCTL_DSP_SUBDIVIDE: ") );
506                 break;
507         case SOUND_PCM_READ_RATE:
508                 CS_DBGOUT(CS_IOCTL, 4, printk("SOUND_PCM_READ_RATE: ") );
509                 break;
510         case SOUND_PCM_READ_CHANNELS:
511                 CS_DBGOUT(CS_IOCTL, 4, printk("SOUND_PCM_READ_CHANNELS: ") );
512                 break;
513         case SOUND_PCM_READ_BITS:
514                 CS_DBGOUT(CS_IOCTL, 4, printk("SOUND_PCM_READ_BITS: ") );
515                 break;
516         case SOUND_PCM_WRITE_FILTER:
517                 CS_DBGOUT(CS_IOCTL, 4, printk("SOUND_PCM_WRITE_FILTER: ") );
518                 break;
519         case SNDCTL_DSP_SETSYNCRO:
520                 CS_DBGOUT(CS_IOCTL, 4, printk("SNDCTL_DSP_SETSYNCRO: ") );
521                 break;
522         case SOUND_PCM_READ_FILTER:
523                 CS_DBGOUT(CS_IOCTL, 4, printk("SOUND_PCM_READ_FILTER: ") );
524                 break;
525         case SOUND_MIXER_PRIVATE1:
526                 CS_DBGOUT(CS_IOCTL, 4, printk("SOUND_MIXER_PRIVATE1: ") );
527                 break;
528         case SOUND_MIXER_PRIVATE2:
529                 CS_DBGOUT(CS_IOCTL, 4, printk("SOUND_MIXER_PRIVATE2: ") );
530                 break;
531         case SOUND_MIXER_PRIVATE3:
532                 CS_DBGOUT(CS_IOCTL, 4, printk("SOUND_MIXER_PRIVATE3: ") );
533                 break;
534         case SOUND_MIXER_PRIVATE4:
535                 CS_DBGOUT(CS_IOCTL, 4, printk("SOUND_MIXER_PRIVATE4: ") );
536                 break;
537         case SOUND_MIXER_PRIVATE5:
538                 CS_DBGOUT(CS_IOCTL, 4, printk("SOUND_MIXER_PRIVATE5: ") );
539                 break;
540         case SOUND_MIXER_INFO:
541                 CS_DBGOUT(CS_IOCTL, 4, printk("SOUND_MIXER_INFO: ") );
542                 break;
543         case SOUND_OLD_MIXER_INFO:
544                 CS_DBGOUT(CS_IOCTL, 4, printk("SOUND_OLD_MIXER_INFO: ") );
545                 break;
546         default:
547                 switch (_IOC_NR(x)) {
548                         case SOUND_MIXER_VOLUME:
549                                 CS_DBGOUT(CS_IOCTL, 4, printk("SOUND_MIXER_VOLUME: ") );
550                                 break;
551                         case SOUND_MIXER_SPEAKER:
552                                 CS_DBGOUT(CS_IOCTL, 4, printk("SOUND_MIXER_SPEAKER: ") );
553                                 break;
554                         case SOUND_MIXER_RECLEV:
555                                 CS_DBGOUT(CS_IOCTL, 4, printk("SOUND_MIXER_RECLEV: ") );
556                                 break;
557                         case SOUND_MIXER_MIC:
558                                 CS_DBGOUT(CS_IOCTL, 4, printk("SOUND_MIXER_MIC: ") );
559                                 break;
560                         case SOUND_MIXER_SYNTH:
561                                 CS_DBGOUT(CS_IOCTL, 4, printk("SOUND_MIXER_SYNTH: ") );
562                                 break;
563                         case SOUND_MIXER_RECSRC: 
564                                 CS_DBGOUT(CS_IOCTL, 4, printk("SOUND_MIXER_RECSRC: ") );
565                                 break;
566                         case SOUND_MIXER_DEVMASK:
567                                 CS_DBGOUT(CS_IOCTL, 4, printk("SOUND_MIXER_DEVMASK: ") );
568                                 break;
569                         case SOUND_MIXER_RECMASK:
570                                 CS_DBGOUT(CS_IOCTL, 4, printk("SOUND_MIXER_RECMASK: ") );
571                                 break;
572                         case SOUND_MIXER_STEREODEVS: 
573                                 CS_DBGOUT(CS_IOCTL, 4, printk("SOUND_MIXER_STEREODEVS: ") );
574                                 break;
575                         case SOUND_MIXER_CAPS:
576                                 CS_DBGOUT(CS_IOCTL, 4, printk("SOUND_MIXER_CAPS:") );
577                                 break;
578                         default:
579                                 i = _IOC_NR(x);
580                                 if (i >= SOUND_MIXER_NRDEVICES || !(vidx = mixtable1[i])) {
581                                         CS_DBGOUT(CS_IOCTL, 4, printk("UNKNOWN IOCTL: 0x%.8x NR=%d ",x,i) );
582                                 } else {
583                                         CS_DBGOUT(CS_IOCTL, 4, printk("SOUND_MIXER_IOCTL AC9x: 0x%.8x NR=%d ",
584                                                         x,i));
585                                 }
586                                 break;
587                 }
588     }
589     CS_DBGOUT(CS_IOCTL, 4, printk("command = 0x%x IOC_NR=%d\n",x, _IOC_NR(x)) );
590 }
591 #endif
592
593 /*
594  *  common I/O routines
595  */
596
597 static void cs461x_poke(struct cs_card *codec, unsigned long reg, unsigned int val)
598 {
599         writel(val, codec->ba1.idx[(reg >> 16) & 3] + (reg & 0xffff));
600 }
601
602 static unsigned int cs461x_peek(struct cs_card *codec, unsigned long reg)
603 {
604         return readl(codec->ba1.idx[(reg >> 16) & 3] + (reg & 0xffff));
605 }
606
607 static void cs461x_pokeBA0(struct cs_card *codec, unsigned long reg, unsigned int val)
608 {
609         writel(val, codec->ba0 + reg);
610 }
611
612 static unsigned int cs461x_peekBA0(struct cs_card *codec, unsigned long reg)
613 {
614         return readl(codec->ba0 + reg);
615 }
616
617
618 static u16 cs_ac97_get(struct ac97_codec *dev, u8 reg);
619 static void cs_ac97_set(struct ac97_codec *dev, u8 reg, u16 data);
620
621 static struct cs_channel *cs_alloc_pcm_channel(struct cs_card *card)
622 {
623         if (card->channel[1].used == 1)
624                 return NULL;
625         card->channel[1].used = 1;
626         card->channel[1].num = 1;
627         return &card->channel[1];
628 }
629
630 static struct cs_channel *cs_alloc_rec_pcm_channel(struct cs_card *card)
631 {
632         if (card->channel[0].used == 1)
633                 return NULL;
634         card->channel[0].used = 1;
635         card->channel[0].num = 0;
636         return &card->channel[0];
637 }
638
639 static void cs_free_pcm_channel(struct cs_card *card, int channel)
640 {
641         card->channel[channel].state = NULL;
642         card->channel[channel].used = 0;
643 }
644
645 /*
646  * setup a divisor value to help with conversion from
647  * 16bit Stereo, down to 8bit stereo/mono or 16bit mono.
648  * assign a divisor of 1 if using 16bit Stereo as that is
649  * the only format that the static image will capture.
650  */
651 static void cs_set_divisor(struct dmabuf *dmabuf)
652 {
653         if (dmabuf->type == CS_TYPE_DAC)
654                 dmabuf->divisor = 1;
655         else if (!(dmabuf->fmt & CS_FMT_STEREO) &&
656             (dmabuf->fmt & CS_FMT_16BIT))
657                 dmabuf->divisor = 2;
658         else if ((dmabuf->fmt & CS_FMT_STEREO) &&
659             !(dmabuf->fmt & CS_FMT_16BIT))
660                 dmabuf->divisor = 2;
661         else if (!(dmabuf->fmt & CS_FMT_STEREO) &&
662             !(dmabuf->fmt & CS_FMT_16BIT))
663                 dmabuf->divisor = 4;
664         else
665                 dmabuf->divisor = 1;
666
667         CS_DBGOUT(CS_PARMS | CS_FUNCTION, 8, printk(
668                 "cs46xx: cs_set_divisor()- %s %d\n",
669                         (dmabuf->type == CS_TYPE_ADC) ? "ADC" : "DAC", 
670                         dmabuf->divisor) );
671 }
672
673 /*
674 * mute some of the more prevalent registers to avoid popping.
675 */
676 static void cs_mute(struct cs_card *card, int state) 
677 {
678         struct ac97_codec *dev = card->ac97_codec[0];
679
680         CS_DBGOUT(CS_FUNCTION, 2, printk(KERN_INFO "cs46xx: cs_mute()+ %s\n",
681                 (state == CS_TRUE) ? "Muting" : "UnMuting"));
682
683         if (state == CS_TRUE) {
684         /*
685         * fix pops when powering up on thinkpads
686         */
687                 card->pm.u32AC97_master_volume = (u32)cs_ac97_get( dev, 
688                                 (u8)BA0_AC97_MASTER_VOLUME); 
689                 card->pm.u32AC97_headphone_volume = (u32)cs_ac97_get(dev, 
690                                 (u8)BA0_AC97_HEADPHONE_VOLUME); 
691                 card->pm.u32AC97_master_volume_mono = (u32)cs_ac97_get(dev, 
692                                 (u8)BA0_AC97_MASTER_VOLUME_MONO); 
693                 card->pm.u32AC97_pcm_out_volume = (u32)cs_ac97_get(dev, 
694                                 (u8)BA0_AC97_PCM_OUT_VOLUME);
695                         
696                 cs_ac97_set(dev, (u8)BA0_AC97_MASTER_VOLUME, 0x8000);
697                 cs_ac97_set(dev, (u8)BA0_AC97_HEADPHONE_VOLUME, 0x8000);
698                 cs_ac97_set(dev, (u8)BA0_AC97_MASTER_VOLUME_MONO, 0x8000);
699                 cs_ac97_set(dev, (u8)BA0_AC97_PCM_OUT_VOLUME, 0x8000);
700         } else {
701                 cs_ac97_set(dev, (u8)BA0_AC97_MASTER_VOLUME, card->pm.u32AC97_master_volume);
702                 cs_ac97_set(dev, (u8)BA0_AC97_HEADPHONE_VOLUME, card->pm.u32AC97_headphone_volume);
703                 cs_ac97_set(dev, (u8)BA0_AC97_MASTER_VOLUME_MONO, card->pm.u32AC97_master_volume_mono);
704                 cs_ac97_set(dev, (u8)BA0_AC97_PCM_OUT_VOLUME, card->pm.u32AC97_pcm_out_volume);
705         }
706         CS_DBGOUT(CS_FUNCTION, 2, printk(KERN_INFO "cs46xx: cs_mute()-\n"));
707 }
708
709 /* set playback sample rate */
710 static unsigned int cs_set_dac_rate(struct cs_state * state, unsigned int rate)
711 {       
712         struct dmabuf *dmabuf = &state->dmabuf;
713         unsigned int tmp1, tmp2;
714         unsigned int phiIncr;
715         unsigned int correctionPerGOF, correctionPerSec;
716         unsigned long flags;
717
718         CS_DBGOUT(CS_FUNCTION, 2, printk("cs46xx: cs_set_dac_rate()+ %d\n",rate) );
719
720         /*
721          *  Compute the values used to drive the actual sample rate conversion.
722          *  The following formulas are being computed, using inline assembly
723          *  since we need to use 64 bit arithmetic to compute the values:
724          *
725          *  phiIncr = floor((Fs,in * 2^26) / Fs,out)
726          *  correctionPerGOF = floor((Fs,in * 2^26 - Fs,out * phiIncr) /
727          *                                   GOF_PER_SEC)
728          *  ulCorrectionPerSec = Fs,in * 2^26 - Fs,out * phiIncr -M
729          *                       GOF_PER_SEC * correctionPerGOF
730          *
731          *  i.e.
732          *
733          *  phiIncr:other = dividend:remainder((Fs,in * 2^26) / Fs,out)
734          *  correctionPerGOF:correctionPerSec =
735          *      dividend:remainder(ulOther / GOF_PER_SEC)
736          */
737         tmp1 = rate << 16;
738         phiIncr = tmp1 / 48000;
739         tmp1 -= phiIncr * 48000;
740         tmp1 <<= 10;
741         phiIncr <<= 10;
742         tmp2 = tmp1 / 48000;
743         phiIncr += tmp2;
744         tmp1 -= tmp2 * 48000;
745         correctionPerGOF = tmp1 / GOF_PER_SEC;
746         tmp1 -= correctionPerGOF * GOF_PER_SEC;
747         correctionPerSec = tmp1;
748
749         /*
750          *  Fill in the SampleRateConverter control block.
751          */
752         spin_lock_irqsave(&state->card->lock, flags);
753         cs461x_poke(state->card, BA1_PSRC,
754           ((correctionPerSec << 16) & 0xFFFF0000) | (correctionPerGOF & 0xFFFF));
755         cs461x_poke(state->card, BA1_PPI, phiIncr);
756         spin_unlock_irqrestore(&state->card->lock, flags);
757         dmabuf->rate = rate;
758         
759         CS_DBGOUT(CS_FUNCTION, 2, printk("cs46xx: cs_set_dac_rate()- %d\n",rate) );
760         return rate;
761 }
762
763 /* set recording sample rate */
764 static unsigned int cs_set_adc_rate(struct cs_state *state, unsigned int rate)
765 {
766         struct dmabuf *dmabuf = &state->dmabuf;
767         struct cs_card *card = state->card;
768         unsigned int phiIncr, coeffIncr, tmp1, tmp2;
769         unsigned int correctionPerGOF, correctionPerSec, initialDelay;
770         unsigned int frameGroupLength, cnt;
771         unsigned long flags;
772         CS_DBGOUT(CS_FUNCTION, 2, printk("cs46xx: cs_set_adc_rate()+ %d\n",rate) );
773
774         /*
775          *  We can only decimate by up to a factor of 1/9th the hardware rate.
776          *  Correct the value if an attempt is made to stray outside that limit.
777          */
778         if ((rate * 9) < 48000)
779                 rate = 48000 / 9;
780
781         /*
782          *  We cannot capture at at rate greater than the Input Rate (48000).
783          *  Return an error if an attempt is made to stray outside that limit.
784          */
785         if (rate > 48000)
786                 rate = 48000;
787
788         /*
789          *  Compute the values used to drive the actual sample rate conversion.
790          *  The following formulas are being computed, using inline assembly
791          *  since we need to use 64 bit arithmetic to compute the values:
792          *
793          *     coeffIncr = -floor((Fs,out * 2^23) / Fs,in)
794          *     phiIncr = floor((Fs,in * 2^26) / Fs,out)
795          *     correctionPerGOF = floor((Fs,in * 2^26 - Fs,out * phiIncr) /
796          *                                GOF_PER_SEC)
797          *     correctionPerSec = Fs,in * 2^26 - Fs,out * phiIncr -
798          *                          GOF_PER_SEC * correctionPerGOF
799          *     initialDelay = ceil((24 * Fs,in) / Fs,out)
800          *
801          * i.e.
802          *
803          *     coeffIncr = neg(dividend((Fs,out * 2^23) / Fs,in))
804          *     phiIncr:ulOther = dividend:remainder((Fs,in * 2^26) / Fs,out)
805          *     correctionPerGOF:correctionPerSec =
806          *          dividend:remainder(ulOther / GOF_PER_SEC)
807          *     initialDelay = dividend(((24 * Fs,in) + Fs,out - 1) / Fs,out)
808          */
809         tmp1 = rate << 16;
810         coeffIncr = tmp1 / 48000;
811         tmp1 -= coeffIncr * 48000;
812         tmp1 <<= 7;
813         coeffIncr <<= 7;
814         coeffIncr += tmp1 / 48000;
815         coeffIncr ^= 0xFFFFFFFF;
816         coeffIncr++;
817         tmp1 = 48000 << 16;
818         phiIncr = tmp1 / rate;
819         tmp1 -= phiIncr * rate;
820         tmp1 <<= 10;
821         phiIncr <<= 10;
822         tmp2 = tmp1 / rate;
823         phiIncr += tmp2;
824         tmp1 -= tmp2 * rate;
825         correctionPerGOF = tmp1 / GOF_PER_SEC;
826         tmp1 -= correctionPerGOF * GOF_PER_SEC;
827         correctionPerSec = tmp1;
828         initialDelay = ((48000 * 24) + rate - 1) / rate;
829
830         /*
831          *  Fill in the VariDecimate control block.
832          */
833         spin_lock_irqsave(&card->lock, flags);
834         cs461x_poke(card, BA1_CSRC,
835                 ((correctionPerSec << 16) & 0xFFFF0000) | (correctionPerGOF & 0xFFFF));
836         cs461x_poke(card, BA1_CCI, coeffIncr);
837         cs461x_poke(card, BA1_CD,
838                 (((BA1_VARIDEC_BUF_1 + (initialDelay << 2)) << 16) & 0xFFFF0000) | 0x80);
839         cs461x_poke(card, BA1_CPI, phiIncr);
840         spin_unlock_irqrestore(&card->lock, flags);
841
842         /*
843          *  Figure out the frame group length for the write back task.  Basically,
844          *  this is just the factors of 24000 (2^6*3*5^3) that are not present in
845          *  the output sample rate.
846          */
847         frameGroupLength = 1;
848         for (cnt = 2; cnt <= 64; cnt *= 2) {
849                 if (((rate / cnt) * cnt) != rate)
850                         frameGroupLength *= 2;
851         }
852         if (((rate / 3) * 3) != rate) {
853                 frameGroupLength *= 3;
854         }
855         for (cnt = 5; cnt <= 125; cnt *= 5) {
856                 if (((rate / cnt) * cnt) != rate) 
857                         frameGroupLength *= 5;
858         }
859
860         /*
861          * Fill in the WriteBack control block.
862          */
863         spin_lock_irqsave(&card->lock, flags);
864         cs461x_poke(card, BA1_CFG1, frameGroupLength);
865         cs461x_poke(card, BA1_CFG2, (0x00800000 | frameGroupLength));
866         cs461x_poke(card, BA1_CCST, 0x0000FFFF);
867         cs461x_poke(card, BA1_CSPB, ((65536 * rate) / 24000));
868         cs461x_poke(card, (BA1_CSPB + 4), 0x0000FFFF);
869         spin_unlock_irqrestore(&card->lock, flags);
870         dmabuf->rate = rate;
871         CS_DBGOUT(CS_FUNCTION, 2, printk("cs46xx: cs_set_adc_rate()- %d\n",rate) );
872         return rate;
873 }
874
875 /* prepare channel attributes for playback */ 
876 static void cs_play_setup(struct cs_state *state)
877 {
878         struct dmabuf *dmabuf = &state->dmabuf;
879         struct cs_card *card = state->card;
880         unsigned int tmp, Count, playFormat;
881
882         CS_DBGOUT(CS_FUNCTION, 2, printk("cs46xx: cs_play_setup()+\n") );
883         cs461x_poke(card, BA1_PVOL, 0x80008000);
884         if (!dmabuf->SGok)
885                cs461x_poke(card, BA1_PBA, virt_to_bus(dmabuf->pbuf));
886     
887         Count = 4;                                                          
888         playFormat=cs461x_peek(card, BA1_PFIE);                             
889         if ((dmabuf->fmt & CS_FMT_STEREO)) {                                
890                 playFormat &= ~DMA_RQ_C2_AC_MONO_TO_STEREO;                 
891                 Count *= 2;                                                 
892         } else
893                 playFormat |= DMA_RQ_C2_AC_MONO_TO_STEREO;                  
894                                                                             
895         if ((dmabuf->fmt & CS_FMT_16BIT)) {                                 
896                 playFormat &= ~(DMA_RQ_C2_AC_8_TO_16_BIT                    
897                            | DMA_RQ_C2_AC_SIGNED_CONVERT);                  
898                 Count *= 2;                                                 
899         } else
900                 playFormat |= (DMA_RQ_C2_AC_8_TO_16_BIT                     
901                            | DMA_RQ_C2_AC_SIGNED_CONVERT);                  
902                                                                             
903         cs461x_poke(card, BA1_PFIE, playFormat);                            
904                                                                             
905         tmp = cs461x_peek(card, BA1_PDTC);                                  
906         tmp &= 0xfffffe00;                                                  
907         cs461x_poke(card, BA1_PDTC, tmp | --Count);                         
908
909         CS_DBGOUT(CS_FUNCTION, 2, printk("cs46xx: cs_play_setup()-\n") );
910 }
911
912 static struct InitStruct
913 {
914     u32 off;
915     u32 val;
916 } InitArray[] = { {0x00000040, 0x3fc0000f},
917                   {0x0000004c, 0x04800000},
918
919                   {0x000000b3, 0x00000780},
920                   {0x000000b7, 0x00000000},
921                   {0x000000bc, 0x07800000},
922
923                   {0x000000cd, 0x00800000},
924                 };
925
926 /*
927  * "SetCaptureSPValues()" -- Initialize record task values before each
928  *      capture startup.  
929  */
930 static void SetCaptureSPValues(struct cs_card *card)
931 {
932         unsigned i, offset;
933         CS_DBGOUT(CS_FUNCTION, 8, printk("cs46xx: SetCaptureSPValues()+\n") );
934         for (i = 0; i < sizeof(InitArray) / sizeof(struct InitStruct); i++) {
935                 offset = InitArray[i].off*4; /* 8bit to 32bit offset value */
936                 cs461x_poke(card, offset, InitArray[i].val );
937         }
938         CS_DBGOUT(CS_FUNCTION, 8, printk("cs46xx: SetCaptureSPValues()-\n") );
939 }
940
941 /* prepare channel attributes for recording */
942 static void cs_rec_setup(struct cs_state *state)
943 {
944         struct cs_card *card = state->card;
945         struct dmabuf *dmabuf = &state->dmabuf;
946
947         CS_DBGOUT(CS_FUNCTION, 2, printk("cs46xx: cs_rec_setup()+\n"));
948         SetCaptureSPValues(card);
949
950         /*
951          * set the attenuation to 0dB 
952          */
953         cs461x_poke(card, BA1_CVOL, 0x80008000);
954
955         /*
956          * set the physical address of the capture buffer into the SP
957          */
958         cs461x_poke(card, BA1_CBA, virt_to_bus(dmabuf->rawbuf));
959
960         CS_DBGOUT(CS_FUNCTION, 2, printk("cs46xx: cs_rec_setup()-\n") );
961 }
962
963
964 /* get current playback/recording dma buffer pointer (byte offset from LBA),
965    called with spinlock held! */
966    
967 static inline unsigned cs_get_dma_addr(struct cs_state *state)
968 {
969         struct dmabuf *dmabuf = &state->dmabuf;
970         u32 offset;
971         
972         if ( (!(dmabuf->enable & DAC_RUNNING)) &&
973              (!(dmabuf->enable & ADC_RUNNING) ) )
974         {
975                 CS_DBGOUT(CS_ERROR, 2, printk(
976                         "cs46xx: ERROR cs_get_dma_addr(): not enabled \n") );
977                 return 0;
978         }
979                 
980         /*
981          * granularity is byte boundary, good part.
982          */
983         if (dmabuf->enable & DAC_RUNNING)
984                 offset = cs461x_peek(state->card, BA1_PBA);                                  
985         else /* ADC_RUNNING must be set */
986                 offset = cs461x_peek(state->card, BA1_CBA);                                  
987
988         CS_DBGOUT(CS_PARMS | CS_FUNCTION, 9, 
989                 printk("cs46xx: cs_get_dma_addr() %d\n",offset) );
990         offset = (u32)bus_to_virt((unsigned long)offset) - (u32)dmabuf->rawbuf;
991         CS_DBGOUT(CS_PARMS | CS_FUNCTION, 8, 
992                 printk("cs46xx: cs_get_dma_addr()- %d\n",offset) );
993         return offset;
994 }
995
996 static void resync_dma_ptrs(struct cs_state *state)
997 {
998         struct dmabuf *dmabuf;
999         
1000         CS_DBGOUT(CS_FUNCTION, 2, printk("cs46xx: resync_dma_ptrs()+ \n") );
1001         if (state) {
1002                 dmabuf = &state->dmabuf;
1003                 dmabuf->hwptr=dmabuf->swptr = 0;
1004                 dmabuf->pringbuf = 0;
1005         }
1006         CS_DBGOUT(CS_FUNCTION, 2, printk("cs46xx: resync_dma_ptrs()- \n") );
1007 }
1008         
1009 /* Stop recording (lock held) */
1010 static inline void __stop_adc(struct cs_state *state)
1011 {
1012         struct dmabuf *dmabuf = &state->dmabuf;
1013         struct cs_card *card = state->card;
1014         unsigned int tmp;
1015         
1016         dmabuf->enable &= ~ADC_RUNNING;
1017         
1018         tmp = cs461x_peek(card, BA1_CCTL);
1019         tmp &= 0xFFFF0000;
1020         cs461x_poke(card, BA1_CCTL, tmp );
1021 }
1022
1023 static void stop_adc(struct cs_state *state)
1024 {
1025         unsigned long flags;
1026
1027         CS_DBGOUT(CS_FUNCTION, 2, printk("cs46xx: stop_adc()+ \n") );
1028         spin_lock_irqsave(&state->card->lock, flags);
1029         __stop_adc(state);
1030         spin_unlock_irqrestore(&state->card->lock, flags);
1031         CS_DBGOUT(CS_FUNCTION, 2, printk("cs46xx: stop_adc()- \n") );
1032 }
1033
1034 static void start_adc(struct cs_state *state)
1035 {
1036         struct dmabuf *dmabuf = &state->dmabuf;
1037         struct cs_card *card = state->card;
1038         unsigned long flags;
1039         unsigned int tmp;
1040
1041         spin_lock_irqsave(&card->lock, flags);
1042         if (!(dmabuf->enable & ADC_RUNNING) && 
1043              ((dmabuf->mapped || dmabuf->count < (signed)dmabuf->dmasize) 
1044                && dmabuf->ready) && 
1045                ((card->pm.flags & CS46XX_PM_IDLE) || 
1046                 (card->pm.flags & CS46XX_PM_RESUMED)) )
1047         {
1048                 dmabuf->enable |= ADC_RUNNING;
1049                 cs_set_divisor(dmabuf);
1050                 tmp = cs461x_peek(card, BA1_CCTL);
1051                 tmp &= 0xFFFF0000;
1052                 tmp |= card->cctl;
1053                 CS_DBGOUT(CS_FUNCTION, 2, printk(
1054                         "cs46xx: start_adc() poke 0x%x \n",tmp) );
1055                 cs461x_poke(card, BA1_CCTL, tmp);
1056         }
1057         spin_unlock_irqrestore(&card->lock, flags);
1058 }
1059
1060 /* stop playback (lock held) */
1061 static inline void __stop_dac(struct cs_state *state)
1062 {
1063         struct dmabuf *dmabuf = &state->dmabuf;
1064         struct cs_card *card = state->card;
1065         unsigned int tmp;
1066
1067         dmabuf->enable &= ~DAC_RUNNING;
1068         
1069         tmp=cs461x_peek(card, BA1_PCTL);
1070         tmp&=0xFFFF;
1071         cs461x_poke(card, BA1_PCTL, tmp);
1072 }
1073
1074 static void stop_dac(struct cs_state *state)
1075 {
1076         unsigned long flags;
1077
1078         CS_DBGOUT(CS_FUNCTION, 2, printk("cs46xx: stop_dac()+ \n") );
1079         spin_lock_irqsave(&state->card->lock, flags);
1080         __stop_dac(state);
1081         spin_unlock_irqrestore(&state->card->lock, flags);
1082         CS_DBGOUT(CS_FUNCTION, 2, printk("cs46xx: stop_dac()- \n") );
1083 }       
1084
1085 static void start_dac(struct cs_state *state)
1086 {
1087         struct dmabuf *dmabuf = &state->dmabuf;
1088         struct cs_card *card = state->card;
1089         unsigned long flags;
1090         int tmp;
1091
1092         CS_DBGOUT(CS_FUNCTION, 2, printk("cs46xx: start_dac()+ \n") );
1093         spin_lock_irqsave(&card->lock, flags);
1094         if (!(dmabuf->enable & DAC_RUNNING) && 
1095             ((dmabuf->mapped || dmabuf->count > 0) && dmabuf->ready) &&
1096                ((card->pm.flags & CS46XX_PM_IDLE) || 
1097                 (card->pm.flags & CS46XX_PM_RESUMED)) )
1098         {
1099                 dmabuf->enable |= DAC_RUNNING;
1100                 tmp = cs461x_peek(card, BA1_PCTL);
1101                 tmp &= 0xFFFF;
1102                 tmp |= card->pctl;
1103                 CS_DBGOUT(CS_PARMS, 6, printk(
1104                     "cs46xx: start_dac() poke card=%p tmp=0x%.08x addr=%p \n",
1105                     card, (unsigned)tmp, 
1106                     card->ba1.idx[(BA1_PCTL >> 16) & 3]+(BA1_PCTL&0xffff) ) );
1107                 cs461x_poke(card, BA1_PCTL, tmp);
1108         }
1109         spin_unlock_irqrestore(&card->lock, flags);
1110         CS_DBGOUT(CS_FUNCTION, 2, printk("cs46xx: start_dac()- \n") );
1111 }
1112
1113 #define DMABUF_MINORDER 1
1114
1115 /*
1116  * allocate DMA buffer, playback and recording buffers are separate.
1117  */
1118 static int alloc_dmabuf(struct cs_state *state)
1119 {
1120
1121         struct cs_card *card=state->card;
1122         struct dmabuf *dmabuf = &state->dmabuf;
1123         void *rawbuf = NULL;
1124         void *tmpbuff = NULL;
1125         int order;
1126         struct page *map, *mapend;
1127         unsigned long df;
1128         
1129         dmabuf->ready  = dmabuf->mapped = 0;
1130         dmabuf->SGok = 0;
1131 /*
1132 * check for order within limits, but do not overwrite value.
1133 */
1134         if ((defaultorder > 1) && (defaultorder < 12))
1135                 df = defaultorder;
1136         else
1137                 df = 2; 
1138
1139         for (order = df; order >= DMABUF_MINORDER; order--)
1140                 if ((rawbuf = (void *)pci_alloc_consistent(
1141                         card->pci_dev, PAGE_SIZE << order, &dmabuf->dmaaddr)))
1142                             break;
1143         if (!rawbuf) {
1144                 CS_DBGOUT(CS_ERROR, 1, printk(KERN_ERR
1145                         "cs46xx: alloc_dmabuf(): unable to allocate rawbuf\n"));
1146                 return -ENOMEM;
1147         }
1148         dmabuf->buforder = order;
1149         dmabuf->rawbuf = rawbuf;
1150         // Now mark the pages as reserved; otherwise the 
1151         // remap_pfn_range() in cs46xx_mmap doesn't work.
1152         // 1. get index to last page in mem_map array for rawbuf.
1153         mapend = virt_to_page(dmabuf->rawbuf + 
1154                 (PAGE_SIZE << dmabuf->buforder) - 1);
1155
1156         // 2. mark each physical page in range as 'reserved'.
1157         for (map = virt_to_page(dmabuf->rawbuf); map <= mapend; map++)
1158                 cs4x_mem_map_reserve(map);
1159
1160         CS_DBGOUT(CS_PARMS, 9, printk("cs46xx: alloc_dmabuf(): allocated %ld (order = %d) bytes at %p\n",
1161                PAGE_SIZE << order, order, rawbuf) );
1162
1163 /*
1164 *  only allocate the conversion buffer for the ADC
1165 */
1166         if (dmabuf->type == CS_TYPE_DAC) {
1167                 dmabuf->tmpbuff = NULL;
1168                 dmabuf->buforder_tmpbuff = 0;
1169                 return 0;
1170         }
1171 /*
1172  * now the temp buffer for 16/8 conversions
1173  */
1174
1175         tmpbuff = (void *) pci_alloc_consistent(
1176                 card->pci_dev, PAGE_SIZE << order, &dmabuf->dmaaddr_tmpbuff);
1177
1178         if (!tmpbuff)
1179                 return -ENOMEM;
1180         CS_DBGOUT(CS_PARMS, 9, printk("cs46xx: allocated %ld (order = %d) bytes at %p\n",
1181                PAGE_SIZE << order, order, tmpbuff) );
1182
1183         dmabuf->tmpbuff = tmpbuff;
1184         dmabuf->buforder_tmpbuff = order;
1185         
1186         // Now mark the pages as reserved; otherwise the 
1187         // remap_pfn_range() in cs46xx_mmap doesn't work.
1188         // 1. get index to last page in mem_map array for rawbuf.
1189         mapend = virt_to_page(dmabuf->tmpbuff + 
1190                 (PAGE_SIZE << dmabuf->buforder_tmpbuff) - 1);
1191
1192         // 2. mark each physical page in range as 'reserved'.
1193         for (map = virt_to_page(dmabuf->tmpbuff); map <= mapend; map++)
1194                 cs4x_mem_map_reserve(map);
1195         return 0;
1196 }
1197
1198 /* free DMA buffer */
1199 static void dealloc_dmabuf(struct cs_state *state)
1200 {
1201         struct dmabuf *dmabuf = &state->dmabuf;
1202         struct page *map, *mapend;
1203
1204         if (dmabuf->rawbuf) {
1205                 // Undo prog_dmabuf()'s marking the pages as reserved 
1206                 mapend = virt_to_page(dmabuf->rawbuf + 
1207                                 (PAGE_SIZE << dmabuf->buforder) - 1);
1208                 for (map = virt_to_page(dmabuf->rawbuf); map <= mapend; map++)
1209                         cs4x_mem_map_unreserve(map);
1210                 free_dmabuf(state->card, dmabuf);
1211         }
1212
1213         if (dmabuf->tmpbuff) {
1214                 // Undo prog_dmabuf()'s marking the pages as reserved 
1215                 mapend = virt_to_page(dmabuf->tmpbuff +
1216                                 (PAGE_SIZE << dmabuf->buforder_tmpbuff) - 1);
1217                 for (map = virt_to_page(dmabuf->tmpbuff); map <= mapend; map++)
1218                         cs4x_mem_map_unreserve(map);
1219                 free_dmabuf2(state->card, dmabuf);
1220         }
1221
1222         dmabuf->rawbuf = NULL;
1223         dmabuf->tmpbuff = NULL;
1224         dmabuf->mapped = dmabuf->ready = 0;
1225         dmabuf->SGok = 0;
1226 }
1227
1228 static int __prog_dmabuf(struct cs_state *state)
1229 {
1230         struct dmabuf *dmabuf = &state->dmabuf;
1231         unsigned long flags;
1232         unsigned long allocated_pages, allocated_bytes;                     
1233         unsigned long tmp1, tmp2, fmt=0;                                           
1234         unsigned long *ptmp = (unsigned long *) dmabuf->pbuf;               
1235         unsigned long SGarray[9], nSGpages=0;                               
1236         int ret;
1237
1238         CS_DBGOUT(CS_FUNCTION, 4, printk("cs46xx: prog_dmabuf()+ \n"));
1239 /*
1240  * check for CAPTURE and use only non-sg for initial release
1241  */
1242         if (dmabuf->type == CS_TYPE_ADC) {
1243                 CS_DBGOUT(CS_FUNCTION, 4, printk("cs46xx: prog_dmabuf() ADC\n"));
1244                 /* 
1245                  * add in non-sg support for capture.
1246                  */
1247                 spin_lock_irqsave(&state->card->lock, flags);
1248         /* add code to reset the rawbuf memory. TRW */
1249                 resync_dma_ptrs(state);
1250                 dmabuf->total_bytes = dmabuf->blocks = 0;
1251                 dmabuf->count = dmabuf->error = dmabuf->underrun = 0;
1252
1253                 dmabuf->SGok = 0;                                                   
1254
1255                 spin_unlock_irqrestore(&state->card->lock, flags);
1256
1257                 /* allocate DMA buffer if not allocated yet */
1258                 if (!dmabuf->rawbuf || !dmabuf->tmpbuff)
1259                         if ((ret = alloc_dmabuf(state)))
1260                                 return ret; 
1261         /*
1262          * static image only supports 16Bit signed, stereo - hard code fmt
1263          */
1264                 fmt = CS_FMT_16BIT | CS_FMT_STEREO;
1265
1266                 dmabuf->numfrag = 2;                                        
1267                 dmabuf->fragsize = 2048;                                    
1268                 dmabuf->fragsamples = 2048 >> sample_shift[fmt];    
1269                 dmabuf->dmasize = 4096;                                     
1270                 dmabuf->fragshift = 11;                                     
1271
1272                 memset(dmabuf->rawbuf, (fmt & CS_FMT_16BIT) ? 0 : 0x80,
1273                        dmabuf->dmasize);
1274                 memset(dmabuf->tmpbuff, (fmt & CS_FMT_16BIT) ? 0 : 0x80, 
1275                         PAGE_SIZE<<dmabuf->buforder_tmpbuff);      
1276
1277                 /*
1278                  *      Now set up the ring
1279                  */
1280
1281                 spin_lock_irqsave(&state->card->lock, flags);
1282                 cs_rec_setup(state);
1283                 spin_unlock_irqrestore(&state->card->lock, flags);
1284
1285                 /* set the ready flag for the dma buffer */
1286                 dmabuf->ready = 1;
1287
1288                 CS_DBGOUT(CS_PARMS, 4, printk(
1289                         "cs46xx: prog_dmabuf(): CAPTURE rate=%d fmt=0x%x numfrag=%d "
1290                         "fragsize=%d dmasize=%d\n",
1291                             dmabuf->rate, dmabuf->fmt, dmabuf->numfrag,
1292                             dmabuf->fragsize, dmabuf->dmasize) );
1293
1294                 CS_DBGOUT(CS_FUNCTION, 4, printk("cs46xx: prog_dmabuf()- 0 \n"));
1295                 return 0;
1296         } else if (dmabuf->type == CS_TYPE_DAC) {
1297         /*
1298          * Must be DAC
1299          */
1300                 CS_DBGOUT(CS_FUNCTION, 4, printk("cs46xx: prog_dmabuf() DAC\n"));
1301                 spin_lock_irqsave(&state->card->lock, flags);
1302                 resync_dma_ptrs(state);
1303                 dmabuf->total_bytes = dmabuf->blocks = 0;
1304                 dmabuf->count = dmabuf->error = dmabuf->underrun = 0;
1305
1306                 dmabuf->SGok = 0;                                                   
1307
1308                 spin_unlock_irqrestore(&state->card->lock, flags);
1309
1310                 /* allocate DMA buffer if not allocated yet */
1311                 if (!dmabuf->rawbuf)
1312                         if ((ret = alloc_dmabuf(state)))
1313                                 return ret;
1314
1315                 allocated_pages = 1 << dmabuf->buforder;                            
1316                 allocated_bytes = allocated_pages*PAGE_SIZE;                        
1317                                                                                     
1318                 if (allocated_pages < 2) {
1319                         CS_DBGOUT(CS_FUNCTION, 4, printk(
1320                             "cs46xx: prog_dmabuf() Error: allocated_pages too small (%d)\n",
1321                                 (unsigned)allocated_pages));
1322                         return -ENOMEM;
1323                 }
1324                                                                                     
1325                 /* Use all the pages allocated, fragsize 4k. */
1326                 /* Use 'pbuf' for S/G page map table. */
1327                 dmabuf->SGok = 1;           /* Use S/G. */
1328
1329                 nSGpages = allocated_bytes/4096;    /* S/G pages always 4k. */
1330                                                                                     
1331                      /* Set up S/G variables. */
1332                 *ptmp = virt_to_bus(dmabuf->rawbuf);                                
1333                 *(ptmp + 1) = 0x00000008;
1334                 for (tmp1 = 1; tmp1 < nSGpages; tmp1++) {
1335                         *(ptmp + 2 * tmp1) = virt_to_bus((dmabuf->rawbuf) + 4096 * tmp1);
1336                         if (tmp1 == nSGpages - 1)
1337                                 tmp2 = 0xbfff0000;
1338                         else                                                        
1339                                 tmp2 = 0x80000000 + 8 * (tmp1 + 1);
1340                         *(ptmp + 2 * tmp1 + 1) = tmp2;
1341                 }                                                                   
1342                 SGarray[0] = 0x82c0200d;                                            
1343                 SGarray[1] = 0xffff0000;                                            
1344                 SGarray[2] = *ptmp;                                                 
1345                 SGarray[3] = 0x00010600;                                            
1346                 SGarray[4] = *(ptmp+2);                                             
1347                 SGarray[5] = 0x80000010;                                            
1348                 SGarray[6] = *ptmp;
1349                 SGarray[7] = *(ptmp+2);
1350                 SGarray[8] = (virt_to_bus(dmabuf->pbuf) & 0xffff000) | 0x10;
1351
1352                 if (dmabuf->SGok) {
1353                         dmabuf->numfrag = nSGpages;
1354                         dmabuf->fragsize = 4096;
1355                         dmabuf->fragsamples = 4096 >> sample_shift[dmabuf->fmt];
1356                         dmabuf->fragshift = 12;
1357                         dmabuf->dmasize = dmabuf->numfrag * 4096;
1358                 } else {
1359                         SGarray[0] = 0xf2c0000f;                                    
1360                         SGarray[1] = 0x00000200;                                    
1361                         SGarray[2] = 0;                                             
1362                         SGarray[3] = 0x00010600;                                    
1363                         SGarray[4]=SGarray[5]=SGarray[6]=SGarray[7]=SGarray[8] = 0; 
1364                         dmabuf->numfrag = 2;                                        
1365                         dmabuf->fragsize = 2048;                                    
1366                         dmabuf->fragsamples = 2048 >> sample_shift[dmabuf->fmt];    
1367                         dmabuf->dmasize = 4096;                                     
1368                         dmabuf->fragshift = 11;                                     
1369                 }
1370                 for (tmp1 = 0; tmp1 < sizeof(SGarray) / 4; tmp1++)
1371                         cs461x_poke(state->card, BA1_PDTC+tmp1 * 4, SGarray[tmp1]);
1372
1373                 memset(dmabuf->rawbuf, (dmabuf->fmt & CS_FMT_16BIT) ? 0 : 0x80,
1374                        dmabuf->dmasize);
1375
1376                 /*
1377                  *      Now set up the ring
1378                  */
1379
1380                 spin_lock_irqsave(&state->card->lock, flags);
1381                 cs_play_setup(state);
1382                 spin_unlock_irqrestore(&state->card->lock, flags);
1383
1384                 /* set the ready flag for the dma buffer */
1385                 dmabuf->ready = 1;
1386
1387                 CS_DBGOUT(CS_PARMS, 4, printk(
1388                         "cs46xx: prog_dmabuf(): PLAYBACK rate=%d fmt=0x%x numfrag=%d "
1389                         "fragsize=%d dmasize=%d\n",
1390                             dmabuf->rate, dmabuf->fmt, dmabuf->numfrag,
1391                             dmabuf->fragsize, dmabuf->dmasize) );
1392
1393                 CS_DBGOUT(CS_FUNCTION, 4, printk("cs46xx: prog_dmabuf()- \n"));
1394                 return 0;
1395         } else {
1396                 CS_DBGOUT(CS_FUNCTION, 4, printk("cs46xx: prog_dmabuf()- Invalid Type %d\n",
1397                         dmabuf->type));
1398         }
1399         return 1;
1400 }
1401
1402 static int prog_dmabuf(struct cs_state *state)
1403 {
1404         int ret;
1405         
1406         mutex_lock(&state->sem);
1407         ret = __prog_dmabuf(state);
1408         mutex_unlock(&state->sem);
1409         
1410         return ret;
1411 }
1412
1413 static void cs_clear_tail(struct cs_state *state)
1414 {
1415 }
1416
1417 static int drain_dac(struct cs_state *state, int nonblock)
1418 {
1419         DECLARE_WAITQUEUE(wait, current);
1420         struct dmabuf *dmabuf = &state->dmabuf;
1421         struct cs_card *card=state->card;
1422         unsigned long flags;
1423         unsigned long tmo;
1424         int count;
1425
1426         CS_DBGOUT(CS_FUNCTION, 4, printk("cs46xx: drain_dac()+ \n"));
1427         if (dmabuf->mapped || !dmabuf->ready)
1428         {
1429                 CS_DBGOUT(CS_FUNCTION, 4, printk("cs46xx: drain_dac()- 0, not ready\n"));
1430                 return 0;
1431         }
1432
1433         add_wait_queue(&dmabuf->wait, &wait);
1434         for (;;) {
1435                 /* It seems that we have to set the current state to TASK_INTERRUPTIBLE
1436                    every time to make the process really go to sleep */
1437                 current->state = TASK_INTERRUPTIBLE;
1438
1439                 spin_lock_irqsave(&state->card->lock, flags);
1440                 count = dmabuf->count;
1441                 spin_unlock_irqrestore(&state->card->lock, flags);
1442
1443                 if (count <= 0)
1444                         break;
1445
1446                 if (signal_pending(current))
1447                         break;
1448
1449                 if (nonblock) {
1450                         remove_wait_queue(&dmabuf->wait, &wait);
1451                         current->state = TASK_RUNNING;
1452                         return -EBUSY;
1453                 }
1454
1455                 tmo = (dmabuf->dmasize * HZ) / dmabuf->rate;
1456                 tmo >>= sample_shift[dmabuf->fmt];
1457                 tmo += (2048*HZ)/dmabuf->rate;
1458                 
1459                 if (!schedule_timeout(tmo ? tmo : 1) && tmo){
1460                         printk(KERN_ERR "cs46xx: drain_dac, dma timeout? %d\n", count);
1461                         break;
1462                 }
1463         }
1464         remove_wait_queue(&dmabuf->wait, &wait);
1465         current->state = TASK_RUNNING;
1466         if (signal_pending(current)) {
1467                 CS_DBGOUT(CS_FUNCTION, 4, printk("cs46xx: drain_dac()- -ERESTARTSYS\n"));
1468                 /*
1469                 * set to silence and let that clear the fifos.
1470                 */
1471                 cs461x_clear_serial_FIFOs(card, CS_TYPE_DAC);
1472                 return -ERESTARTSYS;
1473         }
1474
1475         CS_DBGOUT(CS_FUNCTION, 4, printk("cs46xx: drain_dac()- 0\n"));
1476         return 0;
1477 }
1478
1479
1480 /* update buffer manangement pointers, especially, dmabuf->count and dmabuf->hwptr */
1481 static void cs_update_ptr(struct cs_card *card, int wake)
1482 {
1483         struct cs_state *state;
1484         struct dmabuf *dmabuf;
1485         unsigned hwptr;
1486         int diff;
1487
1488         /* error handling and process wake up for ADC */
1489         state = card->states[0];
1490         if (state) {
1491                 dmabuf = &state->dmabuf;
1492                 if (dmabuf->enable & ADC_RUNNING) {
1493                         /* update hardware pointer */
1494                         hwptr = cs_get_dma_addr(state);
1495
1496                         diff = (dmabuf->dmasize + hwptr - dmabuf->hwptr) % dmabuf->dmasize;
1497                         CS_DBGOUT(CS_PARMS, 9, printk(
1498                                 "cs46xx: cs_update_ptr()+ ADC hwptr=%d diff=%d\n", 
1499                                 hwptr,diff) );
1500                         dmabuf->hwptr = hwptr;
1501                         dmabuf->total_bytes += diff;
1502                         dmabuf->count += diff;
1503                         if (dmabuf->count > dmabuf->dmasize)
1504                                 dmabuf->count = dmabuf->dmasize;
1505
1506                         if (dmabuf->mapped) {
1507                                 if (wake && dmabuf->count >= (signed)dmabuf->fragsize)
1508                                         wake_up(&dmabuf->wait);
1509                         } else {
1510                                 if (wake && dmabuf->count > 0)
1511                                         wake_up(&dmabuf->wait);
1512                         }
1513                 }
1514         }
1515
1516 /*
1517  * Now the DAC
1518  */
1519         state = card->states[1];
1520         if (state) {
1521                 dmabuf = &state->dmabuf;
1522                 /* error handling and process wake up for DAC */
1523                 if (dmabuf->enable & DAC_RUNNING) {
1524                         /* update hardware pointer */
1525                         hwptr = cs_get_dma_addr(state);
1526
1527                         diff = (dmabuf->dmasize + hwptr - dmabuf->hwptr) % dmabuf->dmasize;
1528                         CS_DBGOUT(CS_PARMS, 9, printk(
1529                                 "cs46xx: cs_update_ptr()+ DAC hwptr=%d diff=%d\n", 
1530                                 hwptr,diff) );
1531                         dmabuf->hwptr = hwptr;
1532                         dmabuf->total_bytes += diff;
1533                         if (dmabuf->mapped) {
1534                                 dmabuf->count += diff;
1535                                 if (wake && dmabuf->count >= (signed)dmabuf->fragsize)
1536                                         wake_up(&dmabuf->wait);
1537                                 /*
1538                                  * other drivers use fragsize, but don't see any sense
1539                                  * in that, since dmasize is the buffer asked for
1540                                  * via mmap.
1541                                  */
1542                                 if (dmabuf->count > dmabuf->dmasize)
1543                                         dmabuf->count &= dmabuf->dmasize-1;
1544                         } else {
1545                                 dmabuf->count -= diff;
1546                                 /*
1547                                  * backfill with silence and clear out the last 
1548                                  * "diff" number of bytes.
1549                                  */
1550                                 if (hwptr >= diff) {
1551                                         memset(dmabuf->rawbuf + hwptr - diff, 
1552                                                 (dmabuf->fmt & CS_FMT_16BIT) ? 0 : 0x80, diff);
1553                                 } else {
1554                                         memset(dmabuf->rawbuf, 
1555                                                 (dmabuf->fmt & CS_FMT_16BIT) ? 0 : 0x80,
1556                                                 (unsigned)hwptr);
1557                                         memset((char *)dmabuf->rawbuf + 
1558                                                         dmabuf->dmasize + hwptr - diff,
1559                                                 (dmabuf->fmt & CS_FMT_16BIT) ? 0 : 0x80, 
1560                                                 diff - hwptr); 
1561                                 }
1562
1563                                 if (dmabuf->count < 0 || dmabuf->count > dmabuf->dmasize) {
1564                                         CS_DBGOUT(CS_ERROR, 2, printk(KERN_INFO
1565                                           "cs46xx: ERROR DAC count<0 or count > dmasize (%d)\n",
1566                                                 dmabuf->count));
1567                                         /* 
1568                                         * buffer underrun or buffer overrun, reset the
1569                                         * count of bytes written back to 0.
1570                                         */
1571                                         if (dmabuf->count < 0)
1572                                                 dmabuf->underrun = 1;
1573                                         dmabuf->count = 0;
1574                                         dmabuf->error++;
1575                                 }
1576                                 if (wake && dmabuf->count < (signed)dmabuf->dmasize / 2)
1577                                         wake_up(&dmabuf->wait);
1578                         }
1579                 }
1580         }
1581 }
1582
1583
1584 /* hold spinlock for the following! */
1585 static void cs_handle_midi(struct cs_card *card)
1586 {
1587         unsigned char ch;
1588         int wake;
1589         unsigned temp1;
1590
1591         wake = 0;
1592         while (!(cs461x_peekBA0(card,  BA0_MIDSR) & MIDSR_RBE)) {
1593                 ch = cs461x_peekBA0(card, BA0_MIDRP);
1594                 if (card->midi.icnt < CS_MIDIINBUF) {
1595                         card->midi.ibuf[card->midi.iwr] = ch;
1596                         card->midi.iwr = (card->midi.iwr + 1) % CS_MIDIINBUF;
1597                         card->midi.icnt++;
1598                 }
1599                 wake = 1;
1600         }
1601         if (wake)
1602                 wake_up(&card->midi.iwait);
1603         wake = 0;
1604         while (!(cs461x_peekBA0(card,  BA0_MIDSR) & MIDSR_TBF) && card->midi.ocnt > 0) {
1605                 temp1 = ( card->midi.obuf[card->midi.ord] ) & 0x000000ff;
1606                 cs461x_pokeBA0(card, BA0_MIDWP,temp1);
1607                 card->midi.ord = (card->midi.ord + 1) % CS_MIDIOUTBUF;
1608                 card->midi.ocnt--;
1609                 if (card->midi.ocnt < CS_MIDIOUTBUF-16)
1610                         wake = 1;
1611         }
1612         if (wake)
1613                 wake_up(&card->midi.owait);
1614 }
1615
1616 static irqreturn_t cs_interrupt(int irq, void *dev_id)
1617 {
1618         struct cs_card *card = (struct cs_card *)dev_id;
1619         /* Single channel card */
1620         struct cs_state *recstate = card->channel[0].state;
1621         struct cs_state *playstate = card->channel[1].state;
1622         u32 status;
1623
1624         CS_DBGOUT(CS_INTERRUPT, 9, printk("cs46xx: cs_interrupt()+ \n"));
1625
1626         spin_lock(&card->lock);
1627
1628         status = cs461x_peekBA0(card, BA0_HISR);
1629         
1630         if ((status & 0x7fffffff) == 0) {
1631                 cs461x_pokeBA0(card, BA0_HICR, HICR_CHGM|HICR_IEV);
1632                 spin_unlock(&card->lock);
1633                 return IRQ_HANDLED;     /* Might be IRQ_NONE.. */
1634         }
1635         
1636         /*
1637          * check for playback or capture interrupt only
1638          */
1639         if (((status & HISR_VC0) && playstate && playstate->dmabuf.ready) ||
1640             (((status & HISR_VC1) && recstate && recstate->dmabuf.ready))) {
1641                 CS_DBGOUT(CS_INTERRUPT, 8, printk(
1642                         "cs46xx: cs_interrupt() interrupt bit(s) set (0x%x)\n",status));
1643                 cs_update_ptr(card, CS_TRUE);
1644         }
1645
1646         if (status & HISR_MIDI)
1647                 cs_handle_midi(card);
1648         
1649         /* clear 'em */
1650         cs461x_pokeBA0(card, BA0_HICR, HICR_CHGM|HICR_IEV);
1651         spin_unlock(&card->lock);
1652         CS_DBGOUT(CS_INTERRUPT, 9, printk("cs46xx: cs_interrupt()- \n"));
1653         return IRQ_HANDLED;
1654 }
1655
1656
1657 /**********************************************************************/
1658
1659 static ssize_t cs_midi_read(struct file *file, char __user *buffer, size_t count, loff_t *ppos)
1660 {
1661         struct cs_card *card = file->private_data;
1662         ssize_t ret;
1663         unsigned long flags;
1664         unsigned ptr;
1665         int cnt;
1666
1667         if (!access_ok(VERIFY_WRITE, buffer, count))
1668                 return -EFAULT;
1669         ret = 0;
1670         while (count > 0) {
1671                 spin_lock_irqsave(&card->lock, flags);
1672                 ptr = card->midi.ird;
1673                 cnt = CS_MIDIINBUF - ptr;
1674                 if (card->midi.icnt < cnt)
1675                         cnt = card->midi.icnt;
1676                 spin_unlock_irqrestore(&card->lock, flags);
1677                 if (cnt > count)
1678                         cnt = count;
1679                 if (cnt <= 0) {
1680                         if (file->f_flags & O_NONBLOCK)
1681                                 return ret ? ret : -EAGAIN;
1682                         interruptible_sleep_on(&card->midi.iwait);
1683                         if (signal_pending(current))
1684                                 return ret ? ret : -ERESTARTSYS;
1685                         continue;
1686                 }
1687                 if (copy_to_user(buffer, card->midi.ibuf + ptr, cnt))
1688                         return ret ? ret : -EFAULT;
1689                 ptr = (ptr + cnt) % CS_MIDIINBUF;
1690                 spin_lock_irqsave(&card->lock, flags);
1691                 card->midi.ird = ptr;
1692                 card->midi.icnt -= cnt;
1693                 spin_unlock_irqrestore(&card->lock, flags);
1694                 count -= cnt;
1695                 buffer += cnt;
1696                 ret += cnt;
1697         }
1698         return ret;
1699 }
1700
1701
1702 static ssize_t cs_midi_write(struct file *file, const char __user *buffer, size_t count, loff_t *ppos)
1703 {
1704         struct cs_card *card = file->private_data;
1705         ssize_t ret;
1706         unsigned long flags;
1707         unsigned ptr;
1708         int cnt;
1709
1710         if (!access_ok(VERIFY_READ, buffer, count))
1711                 return -EFAULT;
1712         ret = 0;
1713         while (count > 0) {
1714                 spin_lock_irqsave(&card->lock, flags);
1715                 ptr = card->midi.owr;
1716                 cnt = CS_MIDIOUTBUF - ptr;
1717                 if (card->midi.ocnt + cnt > CS_MIDIOUTBUF)
1718                         cnt = CS_MIDIOUTBUF - card->midi.ocnt;
1719                 if (cnt <= 0)
1720                         cs_handle_midi(card);
1721                 spin_unlock_irqrestore(&card->lock, flags);
1722                 if (cnt > count)
1723                         cnt = count;
1724                 if (cnt <= 0) {
1725                         if (file->f_flags & O_NONBLOCK)
1726                                 return ret ? ret : -EAGAIN;
1727                         interruptible_sleep_on(&card->midi.owait);
1728                         if (signal_pending(current))
1729                                 return ret ? ret : -ERESTARTSYS;
1730                         continue;
1731                 }
1732                 if (copy_from_user(card->midi.obuf + ptr, buffer, cnt))
1733                         return ret ? ret : -EFAULT;
1734                 ptr = (ptr + cnt) % CS_MIDIOUTBUF;
1735                 spin_lock_irqsave(&card->lock, flags);
1736                 card->midi.owr = ptr;
1737                 card->midi.ocnt += cnt;
1738                 spin_unlock_irqrestore(&card->lock, flags);
1739                 count -= cnt;
1740                 buffer += cnt;
1741                 ret += cnt;
1742                 spin_lock_irqsave(&card->lock, flags);
1743                 cs_handle_midi(card);
1744                 spin_unlock_irqrestore(&card->lock, flags);
1745         }
1746         return ret;
1747 }
1748
1749
1750 static unsigned int cs_midi_poll(struct file *file, struct poll_table_struct *wait)
1751 {
1752         struct cs_card *card = file->private_data;
1753         unsigned long flags;
1754         unsigned int mask = 0;
1755
1756         if (file->f_flags & FMODE_WRITE)
1757                 poll_wait(file, &card->midi.owait, wait);
1758         if (file->f_flags & FMODE_READ)
1759                 poll_wait(file, &card->midi.iwait, wait);
1760         spin_lock_irqsave(&card->lock, flags);
1761         if (file->f_flags & FMODE_READ) {
1762                 if (card->midi.icnt > 0)
1763                         mask |= POLLIN | POLLRDNORM;
1764         }
1765         if (file->f_flags & FMODE_WRITE) {
1766                 if (card->midi.ocnt < CS_MIDIOUTBUF)
1767                         mask |= POLLOUT | POLLWRNORM;
1768         }
1769         spin_unlock_irqrestore(&card->lock, flags);
1770         return mask;
1771 }
1772
1773
1774 static int cs_midi_open(struct inode *inode, struct file *file)
1775 {
1776         unsigned int minor = iminor(inode);
1777         struct cs_card *card = NULL;
1778         unsigned long flags;
1779         struct list_head *entry;
1780
1781         list_for_each(entry, &cs46xx_devs) {
1782                 card = list_entry(entry, struct cs_card, list);
1783                 if (card->dev_midi == minor)
1784                         break;
1785         }
1786
1787         if (entry == &cs46xx_devs)
1788                 return -ENODEV;
1789         if (!card) {
1790                 CS_DBGOUT(CS_FUNCTION | CS_OPEN, 2, printk(KERN_INFO
1791                         "cs46xx: cs46xx_midi_open(): Error - unable to find card struct\n"));
1792                 return -ENODEV;
1793         }
1794
1795         file->private_data = card;
1796         /* wait for device to become free */
1797         mutex_lock(&card->midi.open_mutex);
1798         while (card->midi.open_mode & file->f_mode) {
1799                 if (file->f_flags & O_NONBLOCK) {
1800                         mutex_unlock(&card->midi.open_mutex);
1801                         return -EBUSY;
1802                 }
1803                 mutex_unlock(&card->midi.open_mutex);
1804                 interruptible_sleep_on(&card->midi.open_wait);
1805                 if (signal_pending(current))
1806                         return -ERESTARTSYS;
1807                 mutex_lock(&card->midi.open_mutex);
1808         }
1809         spin_lock_irqsave(&card->midi.lock, flags);
1810         if (!(card->midi.open_mode & (FMODE_READ | FMODE_WRITE))) {
1811                 card->midi.ird = card->midi.iwr = card->midi.icnt = 0;
1812                 card->midi.ord = card->midi.owr = card->midi.ocnt = 0;
1813                 card->midi.ird = card->midi.iwr = card->midi.icnt = 0;
1814                 cs461x_pokeBA0(card, BA0_MIDCR, 0x0000000f);            /* Enable xmit, rcv. */
1815                 cs461x_pokeBA0(card, BA0_HICR, HICR_IEV | HICR_CHGM);   /* Enable interrupts */
1816         }
1817         if (file->f_mode & FMODE_READ)
1818                 card->midi.ird = card->midi.iwr = card->midi.icnt = 0;
1819         if (file->f_mode & FMODE_WRITE)
1820                 card->midi.ord = card->midi.owr = card->midi.ocnt = 0;
1821         spin_unlock_irqrestore(&card->midi.lock, flags);
1822         card->midi.open_mode |= (file->f_mode & (FMODE_READ | FMODE_WRITE));
1823         mutex_unlock(&card->midi.open_mutex);
1824         return 0;
1825 }
1826
1827
1828 static int cs_midi_release(struct inode *inode, struct file *file)
1829 {
1830         struct cs_card *card = file->private_data;
1831         DECLARE_WAITQUEUE(wait, current);
1832         unsigned long flags;
1833         unsigned count, tmo;
1834
1835         if (file->f_mode & FMODE_WRITE) {
1836                 current->state = TASK_INTERRUPTIBLE;
1837                 add_wait_queue(&card->midi.owait, &wait);
1838                 for (;;) {
1839                         spin_lock_irqsave(&card->midi.lock, flags);
1840                         count = card->midi.ocnt;
1841                         spin_unlock_irqrestore(&card->midi.lock, flags);
1842                         if (count <= 0)
1843                                 break;
1844                         if (signal_pending(current))
1845                                 break;
1846                         if (file->f_flags & O_NONBLOCK)
1847                                 break;
1848                         tmo = (count * HZ) / 3100;
1849                         if (!schedule_timeout(tmo ? : 1) && tmo)
1850                                 printk(KERN_DEBUG "cs46xx: midi timed out??\n");
1851                 }
1852                 remove_wait_queue(&card->midi.owait, &wait);
1853                 current->state = TASK_RUNNING;
1854         }
1855         mutex_lock(&card->midi.open_mutex);
1856         card->midi.open_mode &= (~(file->f_mode & (FMODE_READ | FMODE_WRITE)));
1857         mutex_unlock(&card->midi.open_mutex);
1858         wake_up(&card->midi.open_wait);
1859         return 0;
1860 }
1861
1862 /*
1863  *   Midi file operations struct.
1864  */
1865 static /*const*/ struct file_operations cs_midi_fops = {
1866         CS_OWNER        CS_THIS_MODULE
1867         .llseek         = no_llseek,
1868         .read           = cs_midi_read,
1869         .write          = cs_midi_write,
1870         .poll           = cs_midi_poll,
1871         .open           = cs_midi_open,
1872         .release        = cs_midi_release,
1873 };
1874
1875 /*
1876  *
1877  * CopySamples copies 16-bit stereo signed samples from the source to the
1878  * destination, possibly converting down to unsigned 8-bit and/or mono.
1879  * count specifies the number of output bytes to write.
1880  *
1881  *  Arguments:
1882  *
1883  *  dst             - Pointer to a destination buffer.
1884  *  src             - Pointer to a source buffer
1885  *  count           - The number of bytes to copy into the destination buffer.
1886  *  fmt             - CS_FMT_16BIT and/or CS_FMT_STEREO bits
1887  *  dmabuf          - pointer to the dma buffer structure
1888  *
1889  * NOTES: only call this routine if the output desired is not 16 Signed Stereo
1890  *      
1891  *
1892  */
1893 static void CopySamples(char *dst, char *src, int count, unsigned fmt, 
1894                 struct dmabuf *dmabuf)
1895 {
1896     s32 s32AudioSample;
1897     s16 *psSrc = (s16 *)src;
1898     s16 *psDst = (s16 *)dst;
1899     u8 *pucDst = (u8 *)dst;
1900
1901     CS_DBGOUT(CS_FUNCTION, 2, printk(KERN_INFO "cs46xx: CopySamples()+ ") );
1902     CS_DBGOUT(CS_WAVE_READ, 8, printk(KERN_INFO
1903         " dst=%p src=%p count=%d fmt=0x%x\n",
1904         dst,src,count,fmt) );
1905
1906     /*
1907      * See if the data should be output as 8-bit unsigned stereo.
1908      */
1909     if ((fmt & CS_FMT_STEREO) && !(fmt & CS_FMT_16BIT)) {
1910         /*
1911          * Convert each 16-bit signed stereo sample to 8-bit unsigned 
1912          * stereo using rounding.
1913          */
1914         psSrc = (s16 *)src;
1915         count = count / 2;
1916         while (count--)
1917             *(pucDst++) = (u8)(((s16)(*psSrc++) + (s16)0x8000) >> 8);
1918     }
1919     /*
1920      * See if the data should be output at 8-bit unsigned mono.
1921      */
1922     else if (!(fmt & CS_FMT_STEREO) && !(fmt & CS_FMT_16BIT)) {
1923         /*
1924          * Convert each 16-bit signed stereo sample to 8-bit unsigned 
1925          * mono using averaging and rounding.
1926          */
1927         psSrc = (s16 *)src;
1928         count = count / 2;
1929         while (count--) {
1930             s32AudioSample = ((*psSrc) + (*(psSrc + 1))) / 2 + (s32)0x80;
1931             if (s32AudioSample > 0x7fff)
1932                 s32AudioSample = 0x7fff;
1933             *(pucDst++) = (u8)(((s16)s32AudioSample + (s16)0x8000) >> 8);
1934             psSrc += 2;
1935         }
1936     }
1937     /*
1938      * See if the data should be output at 16-bit signed mono.
1939      */
1940     else if (!(fmt & CS_FMT_STEREO) && (fmt & CS_FMT_16BIT)) {
1941         /*
1942          * Convert each 16-bit signed stereo sample to 16-bit signed 
1943          * mono using averaging.
1944          */
1945         psSrc = (s16 *)src;
1946         count = count / 2;
1947         while (count--) {
1948             *(psDst++) = (s16)((*psSrc) + (*(psSrc + 1))) / 2;
1949             psSrc += 2;
1950         }
1951     }
1952 }
1953
1954 /*
1955  * cs_copy_to_user()
1956  * replacement for the standard copy_to_user, to allow for a conversion from
1957  * 16 bit to 8 bit and from stereo to mono, if the record conversion is active.  
1958  * The current CS46xx/CS4280 static image only records in 16bit unsigned Stereo, 
1959  * so we convert from any of the other format combinations.
1960  */
1961 static unsigned cs_copy_to_user(
1962         struct cs_state *s, 
1963         void __user *dest, 
1964         void *hwsrc, 
1965         unsigned cnt, 
1966         unsigned *copied)
1967 {
1968         struct dmabuf *dmabuf = &s->dmabuf;
1969         void *src = hwsrc;  /* default to the standard destination buffer addr */
1970
1971         CS_DBGOUT(CS_FUNCTION, 6, printk(KERN_INFO 
1972                 "cs_copy_to_user()+ fmt=0x%x cnt=%d dest=%p\n",
1973                 dmabuf->fmt,(unsigned)cnt,dest) );
1974
1975         if (cnt > dmabuf->dmasize)
1976                 cnt = dmabuf->dmasize;
1977         if (!cnt) {
1978                 *copied = 0;
1979                 return 0;
1980         }
1981         if (dmabuf->divisor != 1) {
1982                 if (!dmabuf->tmpbuff) {
1983                         *copied = cnt / dmabuf->divisor;
1984                         return 0;
1985                 }
1986
1987                 CopySamples((char *)dmabuf->tmpbuff, (char *)hwsrc, cnt, 
1988                         dmabuf->fmt, dmabuf);
1989                 src = dmabuf->tmpbuff;
1990                 cnt = cnt/dmabuf->divisor;
1991         }
1992         if (copy_to_user(dest, src, cnt)) {
1993                 CS_DBGOUT(CS_FUNCTION, 2, printk(KERN_ERR 
1994                         "cs46xx: cs_copy_to_user()- fault dest=%p src=%p cnt=%d\n",
1995                                 dest,src,cnt));
1996                 *copied = 0;
1997                 return -EFAULT;
1998         }
1999         *copied = cnt;
2000         CS_DBGOUT(CS_FUNCTION, 2, printk(KERN_INFO 
2001                 "cs46xx: cs_copy_to_user()- copied bytes is %d \n",cnt));
2002         return 0;
2003 }
2004
2005 /* in this loop, dmabuf.count signifies the amount of data that is waiting to be copied to
2006    the user's buffer.  it is filled by the dma machine and drained by this loop. */
2007 static ssize_t cs_read(struct file *file, char __user *buffer, size_t count, loff_t *ppos)
2008 {
2009         struct cs_card *card = file->private_data;
2010         struct cs_state *state;
2011         DECLARE_WAITQUEUE(wait, current);
2012         struct dmabuf *dmabuf;
2013         ssize_t ret = 0;
2014         unsigned long flags;
2015         unsigned swptr;
2016         int cnt;
2017         unsigned copied = 0;
2018
2019         CS_DBGOUT(CS_WAVE_READ | CS_FUNCTION, 4, 
2020                 printk("cs46xx: cs_read()+ %zd\n",count) );
2021         state = card->states[0];
2022         if (!state)
2023                 return -ENODEV;
2024         dmabuf = &state->dmabuf;
2025
2026         if (dmabuf->mapped)
2027                 return -ENXIO;
2028         if (!access_ok(VERIFY_WRITE, buffer, count))
2029                 return -EFAULT;
2030         
2031         mutex_lock(&state->sem);
2032         if (!dmabuf->ready && (ret = __prog_dmabuf(state)))
2033                 goto out2;
2034
2035         add_wait_queue(&state->dmabuf.wait, &wait);
2036         while (count > 0) {
2037                 while (!(card->pm.flags & CS46XX_PM_IDLE)) {
2038                         schedule();
2039                         if (signal_pending(current)) {
2040                                 if (!ret)
2041                                         ret = -ERESTARTSYS;
2042                                 goto out;
2043                         }
2044                 }
2045                 spin_lock_irqsave(&state->card->lock, flags);
2046                 swptr = dmabuf->swptr;
2047                 cnt = dmabuf->dmasize - swptr;
2048                 if (dmabuf->count < cnt)
2049                         cnt = dmabuf->count;
2050                 if (cnt <= 0)
2051                         __set_current_state(TASK_INTERRUPTIBLE);
2052                 spin_unlock_irqrestore(&state->card->lock, flags);
2053
2054                 if (cnt > (count * dmabuf->divisor))
2055                         cnt = count * dmabuf->divisor;
2056                 if (cnt <= 0) {
2057                         /* buffer is empty, start the dma machine and wait for data to be
2058                            recorded */
2059                         start_adc(state);
2060                         if (file->f_flags & O_NONBLOCK) {
2061                                 if (!ret)
2062                                         ret = -EAGAIN;
2063                                 goto out;
2064                         }
2065                         mutex_unlock(&state->sem);
2066                         schedule();
2067                         if (signal_pending(current)) {
2068                                 if (!ret)
2069                                         ret = -ERESTARTSYS;
2070                                 goto out;
2071                         }
2072                         mutex_lock(&state->sem);
2073                         if (dmabuf->mapped) {
2074                                 if (!ret)
2075                                         ret = -ENXIO;
2076                                 goto out;
2077                         }
2078                         continue;
2079                 }
2080
2081                 CS_DBGOUT(CS_WAVE_READ, 2, printk(KERN_INFO 
2082                         "_read() copy_to cnt=%d count=%zd ", cnt,count) );
2083                 CS_DBGOUT(CS_WAVE_READ, 8, printk(KERN_INFO 
2084                         " .dmasize=%d .count=%d buffer=%p ret=%zd\n",
2085                         dmabuf->dmasize,dmabuf->count,buffer,ret));
2086
2087                 if (cs_copy_to_user(state, buffer, 
2088                         (char *)dmabuf->rawbuf + swptr, cnt, &copied)) {
2089                         if (!ret)
2090                                 ret = -EFAULT;
2091                         goto out;
2092                 }
2093                 swptr = (swptr + cnt) % dmabuf->dmasize;
2094                 spin_lock_irqsave(&card->lock, flags);
2095                 dmabuf->swptr = swptr;
2096                 dmabuf->count -= cnt;
2097                 spin_unlock_irqrestore(&card->lock, flags);
2098                 count -= copied;
2099                 buffer += copied;
2100                 ret += copied;
2101                 start_adc(state);
2102         }
2103 out:
2104         remove_wait_queue(&state->dmabuf.wait, &wait);
2105 out2:
2106         mutex_unlock(&state->sem);
2107         set_current_state(TASK_RUNNING);
2108         CS_DBGOUT(CS_WAVE_READ | CS_FUNCTION, 4, 
2109                 printk("cs46xx: cs_read()- %zd\n",ret) );
2110         return ret;
2111 }
2112
2113 /* in this loop, dmabuf.count signifies the amount of data that is waiting to be dma to
2114    the soundcard.  it is drained by the dma machine and filled by this loop. */
2115 static ssize_t cs_write(struct file *file, const char __user *buffer, size_t count, loff_t *ppos)
2116 {
2117         struct cs_card *card = file->private_data;
2118         struct cs_state *state;
2119         DECLARE_WAITQUEUE(wait, current);
2120         struct dmabuf *dmabuf;
2121         ssize_t ret;
2122         unsigned long flags;
2123         unsigned swptr;
2124         int cnt;
2125
2126         CS_DBGOUT(CS_WAVE_WRITE | CS_FUNCTION, 4,
2127                 printk("cs46xx: cs_write called, count = %zd\n", count) );
2128         state = card->states[1];
2129         if (!state)
2130                 return -ENODEV;
2131         if (!access_ok(VERIFY_READ, buffer, count))
2132                 return -EFAULT;
2133         dmabuf = &state->dmabuf;
2134
2135         mutex_lock(&state->sem);
2136         if (dmabuf->mapped) {
2137                 ret = -ENXIO;
2138                 goto out;
2139         }
2140
2141         if (!dmabuf->ready && (ret = __prog_dmabuf(state)))
2142                 goto out;
2143         add_wait_queue(&state->dmabuf.wait, &wait);
2144         ret = 0;
2145 /*
2146 * Start the loop to read from the user's buffer and write to the dma buffer.
2147 * check for PM events and underrun/overrun in the loop.
2148 */
2149         while (count > 0) {
2150                 while (!(card->pm.flags & CS46XX_PM_IDLE)) {
2151                         schedule();
2152                         if (signal_pending(current)) {
2153                                 if (!ret)
2154                                         ret = -ERESTARTSYS;
2155                                 goto out;
2156                         }
2157                 }
2158                 spin_lock_irqsave(&state->card->lock, flags);
2159                 if (dmabuf->count < 0) {
2160                         /* buffer underrun, we are recovering from sleep_on_timeout,
2161                            resync hwptr and swptr */
2162                         dmabuf->count = 0;
2163                         dmabuf->swptr = dmabuf->hwptr;
2164                 }
2165                 if (dmabuf->underrun) {
2166                         dmabuf->underrun = 0;
2167                         dmabuf->hwptr = cs_get_dma_addr(state);
2168                         dmabuf->swptr = dmabuf->hwptr;
2169                 }
2170
2171                 swptr = dmabuf->swptr;
2172                 cnt = dmabuf->dmasize - swptr;
2173                 if (dmabuf->count + cnt > dmabuf->dmasize)
2174                         cnt = dmabuf->dmasize - dmabuf->count;
2175                 if (cnt <= 0)
2176                         __set_current_state(TASK_INTERRUPTIBLE);
2177                 spin_unlock_irqrestore(&state->card->lock, flags);
2178
2179                 if (cnt > count)
2180                         cnt = count;
2181                 if (cnt <= 0) {
2182                         /* buffer is full, start the dma machine and wait for data to be
2183                            played */
2184                         start_dac(state);
2185                         if (file->f_flags & O_NONBLOCK) {
2186                                 if (!ret)
2187                                         ret = -EAGAIN;
2188                                 goto out;
2189                         }
2190                         mutex_unlock(&state->sem);
2191                         schedule();
2192                         if (signal_pending(current)) {
2193                                 if (!ret)
2194                                         ret = -ERESTARTSYS;
2195                                 goto out;
2196                         }
2197                         mutex_lock(&state->sem);
2198                         if (dmabuf->mapped) {
2199                                 if (!ret)
2200                                         ret = -ENXIO;
2201                                 goto out;
2202                         }
2203                         continue;
2204                 }
2205                 if (copy_from_user(dmabuf->rawbuf + swptr, buffer, cnt)) {
2206                         if (!ret)
2207                                 ret = -EFAULT;
2208                         goto out;
2209                 }
2210                 spin_lock_irqsave(&state->card->lock, flags);
2211                 swptr = (swptr + cnt) % dmabuf->dmasize;
2212                 dmabuf->swptr = swptr;
2213                 dmabuf->count += cnt;
2214                 if (dmabuf->count > dmabuf->dmasize) {
2215                         CS_DBGOUT(CS_WAVE_WRITE | CS_ERROR, 2, printk(
2216                             "cs46xx: cs_write() d->count > dmasize - resetting\n"));
2217                         dmabuf->count = dmabuf->dmasize;
2218                 }
2219                 dmabuf->endcleared = 0;
2220                 spin_unlock_irqrestore(&state->card->lock, flags);
2221
2222                 count -= cnt;
2223                 buffer += cnt;
2224                 ret += cnt;
2225                 start_dac(state);
2226         }
2227 out:
2228         mutex_unlock(&state->sem);
2229         remove_wait_queue(&state->dmabuf.wait, &wait);
2230         set_current_state(TASK_RUNNING);
2231
2232         CS_DBGOUT(CS_WAVE_WRITE | CS_FUNCTION, 2, 
2233                 printk("cs46xx: cs_write()- ret=%zd\n", ret));
2234         return ret;
2235 }
2236
2237 static unsigned int cs_poll(struct file *file, struct poll_table_struct *wait)
2238 {
2239         struct cs_card *card = file->private_data;
2240         struct dmabuf *dmabuf;
2241         struct cs_state *state;
2242         unsigned long flags;
2243         unsigned int mask = 0;
2244
2245         CS_DBGOUT(CS_FUNCTION, 2, printk("cs46xx: cs_poll()+ \n"));
2246         if (!(file->f_mode & (FMODE_WRITE | FMODE_READ))) {
2247                 return -EINVAL;
2248         }
2249         if (file->f_mode & FMODE_WRITE) {
2250                 state = card->states[1];
2251                 if (state) {
2252                         dmabuf = &state->dmabuf;
2253                         poll_wait(file, &dmabuf->wait, wait);
2254                 }
2255         }
2256         if (file->f_mode & FMODE_READ) {
2257                 state = card->states[0];
2258                 if (state) {
2259                         dmabuf = &state->dmabuf;
2260                         poll_wait(file, &dmabuf->wait, wait);
2261                 }
2262         }
2263
2264         spin_lock_irqsave(&card->lock, flags);
2265         cs_update_ptr(card, CS_FALSE);
2266         if (file->f_mode & FMODE_READ) {
2267                 state = card->states[0];
2268                 if (state) {
2269                         dmabuf = &state->dmabuf;
2270                         if (dmabuf->count >= (signed)dmabuf->fragsize)
2271                                 mask |= POLLIN | POLLRDNORM;
2272                 }
2273         }
2274         if (file->f_mode & FMODE_WRITE) {
2275                 state = card->states[1];
2276                 if (state) {
2277                         dmabuf = &state->dmabuf;
2278                         if (dmabuf->mapped) {
2279                                 if (dmabuf->count >= (signed)dmabuf->fragsize)
2280                                     mask |= POLLOUT | POLLWRNORM;
2281                         } else {
2282                                 if ((signed)dmabuf->dmasize >= dmabuf->count 
2283                                         + (signed)dmabuf->fragsize)
2284                                     mask |= POLLOUT | POLLWRNORM;
2285                         }
2286                 }
2287         }
2288         spin_unlock_irqrestore(&card->lock, flags);
2289
2290         CS_DBGOUT(CS_FUNCTION, 2, printk("cs46xx: cs_poll()- (0x%x) \n",
2291                 mask));
2292         return mask;
2293 }
2294
2295 /*
2296  *      We let users mmap the ring buffer. Its not the real DMA buffer but
2297  *      that side of the code is hidden in the IRQ handling. We do a software
2298  *      emulation of DMA from a 64K or so buffer into a 2K FIFO. 
2299  *      (the hardware probably deserves a moan here but Crystal send me nice
2300  *      toys ;)).
2301  */
2302  
2303 static int cs_mmap(struct file *file, struct vm_area_struct *vma)
2304 {
2305         struct cs_card *card = file->private_data;
2306         struct cs_state *state;
2307         struct dmabuf *dmabuf;
2308         int ret = 0;
2309         unsigned long size;
2310
2311         CS_DBGOUT(CS_FUNCTION | CS_PARMS, 2, printk("cs46xx: cs_mmap()+ file=%p %s %s\n", 
2312                 file, vma->vm_flags & VM_WRITE ? "VM_WRITE" : "",
2313                 vma->vm_flags & VM_READ ? "VM_READ" : "") );
2314
2315         if (vma->vm_flags & VM_WRITE) {
2316                 state = card->states[1];
2317                 if (state) {
2318                         CS_DBGOUT(CS_OPEN, 2, printk(
2319                           "cs46xx: cs_mmap() VM_WRITE - state TRUE prog_dmabuf DAC\n") );
2320                         if ((ret = prog_dmabuf(state)) != 0)
2321                                 return ret;
2322                 }
2323         } else if (vma->vm_flags & VM_READ) {
2324                 state = card->states[0];
2325                 if (state) {
2326                         CS_DBGOUT(CS_OPEN, 2, printk(
2327                           "cs46xx: cs_mmap() VM_READ - state TRUE prog_dmabuf ADC\n") );
2328                         if ((ret = prog_dmabuf(state)) != 0)
2329                                 return ret;
2330                 }
2331         } else {
2332                 CS_DBGOUT(CS_ERROR, 2, printk(
2333                   "cs46xx: cs_mmap() return -EINVAL\n") );
2334                 return -EINVAL;
2335         }
2336
2337 /*
2338  * For now ONLY support playback, but seems like the only way to use
2339  * mmap() is to open an FD with RDWR, just read or just write access
2340  * does not function, get an error back from the kernel.
2341  * Also, QuakeIII opens with RDWR!  So, there must be something
2342  * to needing read/write access mapping.  So, allow read/write but 
2343  * use the DAC only.
2344  */
2345         state = card->states[1];  
2346         if (!state) {
2347                 ret = -EINVAL;
2348                 goto out;
2349         }
2350
2351         mutex_lock(&state->sem);
2352         dmabuf = &state->dmabuf;
2353         if (cs4x_pgoff(vma) != 0) {
2354                 ret = -EINVAL;
2355                 goto out;
2356         }
2357         size = vma->vm_end - vma->vm_start;
2358
2359         CS_DBGOUT(CS_PARMS, 2, printk("cs46xx: cs_mmap(): size=%d\n",(unsigned)size) );
2360
2361         if (size > (PAGE_SIZE << dmabuf->buforder)) {
2362                 ret = -EINVAL;
2363                 goto out;
2364         }
2365         if (remap_pfn_range(vma, vma->vm_start,
2366                              virt_to_phys(dmabuf->rawbuf) >> PAGE_SHIFT,
2367                              size, vma->vm_page_prot)) {
2368                 ret = -EAGAIN;
2369                 goto out;
2370         }
2371         dmabuf->mapped = 1;
2372
2373         CS_DBGOUT(CS_FUNCTION, 2, printk("cs46xx: cs_mmap()-\n") );
2374 out:
2375         mutex_unlock(&state->sem);
2376         return ret;     
2377 }
2378
2379 static int cs_ioctl(struct inode *inode, struct file *file, unsigned int cmd, unsigned long arg)
2380 {
2381         struct cs_card *card = file->private_data;
2382         struct cs_state *state;
2383         struct dmabuf *dmabuf = NULL;
2384         unsigned long flags;
2385         audio_buf_info abinfo;
2386         count_info cinfo;
2387         int val, valsave, ret;
2388         int mapped = 0;
2389         void __user *argp = (void __user *)arg;
2390         int __user *p = argp;
2391
2392         state = card->states[0];
2393         if (state) {
2394                 dmabuf = &state->dmabuf;
2395                 mapped = (file->f_mode & FMODE_READ) && dmabuf->mapped;
2396         }
2397         state = card->states[1];
2398         if (state) {
2399                 dmabuf = &state->dmabuf;
2400                 mapped |= (file->f_mode & FMODE_WRITE) && dmabuf->mapped;
2401         }
2402                 
2403 #if CSDEBUG
2404         printioctl(cmd);
2405 #endif
2406
2407         switch (cmd) {
2408         case OSS_GETVERSION:
2409                 return put_user(SOUND_VERSION, p);
2410         case SNDCTL_DSP_RESET:
2411                 /* FIXME: spin_lock ? */
2412                 if (file->f_mode & FMODE_WRITE) {
2413                         state = card->states[1];
2414                         if (state) {
2415                                 dmabuf = &state->dmabuf;
2416                                 stop_dac(state);
2417                                 synchronize_irq(card->irq);
2418                                 dmabuf->ready = 0;
2419                                 resync_dma_ptrs(state);
2420                                 dmabuf->swptr = dmabuf->hwptr = 0;
2421                                 dmabuf->count = dmabuf->total_bytes = 0;
2422                                 dmabuf->blocks = 0;
2423                                 dmabuf->SGok = 0;
2424                         }
2425                 }
2426                 if (file->f_mode & FMODE_READ) {
2427                         state = card->states[0];
2428                         if (state) {
2429                                 dmabuf = &state->dmabuf;
2430                                 stop_adc(state);
2431                                 synchronize_irq(card->irq);
2432                                 resync_dma_ptrs(state);
2433                                 dmabuf->ready = 0;
2434                                 dmabuf->swptr = dmabuf->hwptr = 0;
2435                                 dmabuf->count = dmabuf->total_bytes = 0;
2436                                 dmabuf->blocks = 0;
2437                                 dmabuf->SGok = 0;
2438                         }
2439                 }
2440                 CS_DBGOUT(CS_IOCTL, 2, printk("cs46xx: DSP_RESET()-\n") );
2441                 return 0;
2442         case SNDCTL_DSP_SYNC:
2443                 if (file->f_mode & FMODE_WRITE)
2444                         return drain_dac(state, file->f_flags & O_NONBLOCK);
2445                 return 0;
2446         case SNDCTL_DSP_SPEED: /* set sample rate */
2447                 if (get_user(val, p))
2448                         return -EFAULT;
2449                 if (val >= 0) {
2450                         if (file->f_mode & FMODE_READ) {
2451                                 state = card->states[0];
2452                                 if (state) {
2453                                         dmabuf = &state->dmabuf;
2454                                         stop_adc(state);
2455                                         dmabuf->ready = 0;
2456                                         dmabuf->SGok = 0;
2457                                         cs_set_adc_rate(state, val);
2458                                         cs_set_divisor(dmabuf);
2459                                 }
2460                         }
2461                         if (file->f_mode & FMODE_WRITE) {
2462                                 state = card->states[1];
2463                                 if (state) {
2464                                         dmabuf = &state->dmabuf;
2465                                         stop_dac(state);
2466                                         dmabuf->ready = 0;
2467                                         dmabuf->SGok = 0;
2468                                         cs_set_dac_rate(state, val);
2469                                         cs_set_divisor(dmabuf);
2470                                 }
2471                         }
2472                         CS_DBGOUT(CS_IOCTL | CS_PARMS, 4, printk(
2473                             "cs46xx: cs_ioctl() DSP_SPEED %s %s %d\n",
2474                                 file->f_mode & FMODE_WRITE ? "DAC" : "",
2475                                 file->f_mode & FMODE_READ ? "ADC" : "",
2476                                 dmabuf->rate ) );
2477                         return put_user(dmabuf->rate, p);
2478                 }
2479                 return put_user(0, p);
2480         case SNDCTL_DSP_STEREO: /* set stereo or mono channel */
2481                 if (get_user(val, p))
2482                         return -EFAULT;
2483                 if (file->f_mode & FMODE_WRITE) {
2484                         state = card->states[1];
2485                         if (state) {
2486                                 dmabuf = &state->dmabuf;
2487                                 stop_dac(state);
2488                                 dmabuf->ready = 0;
2489                                 dmabuf->SGok = 0;
2490                                 if (val)
2491                                         dmabuf->fmt |= CS_FMT_STEREO;
2492                                 else
2493                                         dmabuf->fmt &= ~CS_FMT_STEREO;
2494                                 cs_set_divisor(dmabuf);
2495                                 CS_DBGOUT(CS_IOCTL | CS_PARMS, 4, printk(
2496                                     "cs46xx: DSP_STEREO() DAC %s\n",
2497                                     (dmabuf->fmt & CS_FMT_STEREO) ?
2498                                         "STEREO":"MONO") );
2499                         }
2500                 }
2501                 if (file->f_mode & FMODE_READ) {
2502                         state = card->states[0];
2503                         if (state) {
2504                                 dmabuf = &state->dmabuf;
2505                                 stop_adc(state);
2506                                 dmabuf->ready = 0;
2507                                 dmabuf->SGok = 0;
2508                                 if (val)
2509                                         dmabuf->fmt |= CS_FMT_STEREO;
2510                                 else
2511                                         dmabuf->fmt &= ~CS_FMT_STEREO;
2512                                 cs_set_divisor(dmabuf);
2513                                 CS_DBGOUT(CS_IOCTL | CS_PARMS, 4, printk(
2514                                     "cs46xx: DSP_STEREO() ADC %s\n",
2515                                     (dmabuf->fmt & CS_FMT_STEREO) ?
2516                                         "STEREO":"MONO") );
2517                         }
2518                 }
2519                 return 0;
2520         case SNDCTL_DSP_GETBLKSIZE:
2521                 if (file->f_mode & FMODE_WRITE) {
2522                         state = card->states[1];
2523                         if (state) {
2524                                 dmabuf = &state->dmabuf;
2525                                 if ((val = prog_dmabuf(state)))
2526                                         return val;
2527                                 return put_user(dmabuf->fragsize, p);
2528                         }
2529                 }
2530                 if (file->f_mode & FMODE_READ) {
2531                         state = card->states[0];
2532                         if (state) {
2533                                 dmabuf = &state->dmabuf;
2534                                 if ((val = prog_dmabuf(state)))
2535                                         return val;
2536                                 return put_user(dmabuf->fragsize/dmabuf->divisor, 
2537                                                 p);
2538                         }
2539                 }
2540                 return put_user(0, p);
2541         case SNDCTL_DSP_GETFMTS: /* Returns a mask of supported sample format*/
2542                 return put_user(AFMT_S16_LE | AFMT_U8, p);
2543         case SNDCTL_DSP_SETFMT: /* Select sample format */
2544                 if (get_user(val, p))
2545                         return -EFAULT;
2546                 CS_DBGOUT(CS_IOCTL | CS_PARMS, 4, printk(
2547                     "cs46xx: cs_ioctl() DSP_SETFMT %s %s %s %s\n",
2548                         file->f_mode & FMODE_WRITE ? "DAC" : "",
2549                         file->f_mode & FMODE_READ ? "ADC" : "",
2550                         val == AFMT_S16_LE ? "16Bit Signed" : "",
2551                         val == AFMT_U8 ? "8Bit Unsigned" : "") );
2552                 valsave = val;
2553                 if (val != AFMT_QUERY) {
2554                         if (val==AFMT_S16_LE || val==AFMT_U8) {
2555                                 if (file->f_mode & FMODE_WRITE) {
2556                                         state = card->states[1];
2557                                         if (state) {
2558                                                 dmabuf = &state->dmabuf;
2559                                                 stop_dac(state);
2560                                                 dmabuf->ready = 0;
2561                                                 dmabuf->SGok = 0;
2562                                                 if (val == AFMT_S16_LE)
2563                                                         dmabuf->fmt |= CS_FMT_16BIT;
2564                                                 else
2565                                                         dmabuf->fmt &= ~CS_FMT_16BIT;
2566                                                 cs_set_divisor(dmabuf);
2567                                                 if ((ret = prog_dmabuf(state)))
2568                                                         return ret;
2569                                         }
2570                                 }
2571                                 if (file->f_mode & FMODE_READ) {
2572                                         val = valsave;
2573                                         state = card->states[0];
2574                                         if (state) {
2575                                                 dmabuf = &state->dmabuf;
2576                                                 stop_adc(state);
2577                                                 dmabuf->ready = 0;
2578                                                 dmabuf->SGok = 0;
2579                                                 if (val == AFMT_S16_LE)
2580                                                         dmabuf->fmt |= CS_FMT_16BIT;
2581                                                 else
2582                                                         dmabuf->fmt &= ~CS_FMT_16BIT;
2583                                                 cs_set_divisor(dmabuf);
2584                                                 if ((ret = prog_dmabuf(state)))
2585                                                         return ret;
2586                                         }
2587                                 }
2588                         } else {
2589                                 CS_DBGOUT(CS_IOCTL | CS_ERROR, 2, printk(
2590                                     "cs46xx: DSP_SETFMT() Unsupported format (0x%x)\n",
2591                                         valsave) );
2592                         }
2593                 } else {
2594                         if (file->f_mode & FMODE_WRITE) {
2595                                 state = card->states[1];
2596                                 if (state)
2597                                         dmabuf = &state->dmabuf;
2598                         } else if (file->f_mode & FMODE_READ) {
2599                                 state = card->states[0];
2600                                 if (state)
2601                                         dmabuf = &state->dmabuf;
2602                         }
2603                 }
2604                 if (dmabuf) {
2605                         if (dmabuf->fmt & CS_FMT_16BIT)
2606                                 return put_user(AFMT_S16_LE, p);
2607                         else
2608                                 return put_user(AFMT_U8, p);
2609                 }
2610                 return put_user(0, p);
2611         case SNDCTL_DSP_CHANNELS:
2612                 if (get_user(val, p))
2613                         return -EFAULT;
2614                 if (val != 0) {
2615                         if (file->f_mode & FMODE_WRITE) {
2616                                 state = card->states[1];
2617                                 if (state) {
2618                                         dmabuf = &state->dmabuf;
2619                                         stop_dac(state);
2620                                         dmabuf->ready = 0;
2621                                         dmabuf->SGok = 0;
2622                                         if (val > 1)
2623                                                 dmabuf->fmt |= CS_FMT_STEREO;
2624                                         else
2625                                                 dmabuf->fmt &= ~CS_FMT_STEREO;
2626                                         cs_set_divisor(dmabuf);
2627                                         if (prog_dmabuf(state))
2628                                                 return 0;
2629                                 }
2630                         }
2631                         if (file->f_mode & FMODE_READ) {
2632                                 state = card->states[0];
2633                                 if (state) {
2634                                         dmabuf = &state->dmabuf;
2635                                         stop_adc(state);
2636                                         dmabuf->ready = 0;
2637                                         dmabuf->SGok = 0;
2638                                         if (val > 1)
2639                                                 dmabuf->fmt |= CS_FMT_STEREO;
2640                                         else
2641                                                 dmabuf->fmt &= ~CS_FMT_STEREO;
2642                                         cs_set_divisor(dmabuf);
2643                                         if (prog_dmabuf(state))
2644                                                 return 0;
2645                                 }
2646                         }
2647                 }
2648                 return put_user((dmabuf->fmt & CS_FMT_STEREO) ? 2 : 1,
2649                                 p);
2650         case SNDCTL_DSP_POST:
2651                 /*
2652                  * There will be a longer than normal pause in the data.
2653                  * so... do nothing, because there is nothing that we can do.
2654                  */
2655                 return 0;
2656         case SNDCTL_DSP_SUBDIVIDE:
2657                 if (file->f_mode & FMODE_WRITE) {
2658                         state = card->states[1];
2659                         if (state) {
2660                                 dmabuf = &state->dmabuf;
2661                                 if (dmabuf->subdivision)
2662                                         return -EINVAL;
2663                                 if (get_user(val, p))
2664                                         return -EFAULT;
2665                                 if (val != 1 && val != 2)
2666                                         return -EINVAL;
2667                                 dmabuf->subdivision = val;
2668                         }
2669                 }
2670                 if (file->f_mode & FMODE_READ) {
2671                         state = card->states[0];
2672                         if (state) {
2673                                 dmabuf = &state->dmabuf;
2674                                 if (dmabuf->subdivision)
2675                                         return -EINVAL;
2676                                 if (get_user(val, p))
2677                                         return -EFAULT;
2678                                 if (val != 1 && val != 2)
2679                                         return -EINVAL;
2680                                 dmabuf->subdivision = val;
2681                         }
2682                 }
2683                 return 0;
2684         case SNDCTL_DSP_SETFRAGMENT:
2685                 if (get_user(val, p))
2686                         return -EFAULT;
2687                 if (file->f_mode & FMODE_WRITE) {
2688                         state = card->states[1];
2689                         if (state) {
2690                                 dmabuf = &state->dmabuf;
2691                                 dmabuf->ossfragshift = val & 0xffff;
2692                                 dmabuf->ossmaxfrags = (val >> 16) & 0xffff;
2693                         }
2694                 }
2695                 if (file->f_mode & FMODE_READ) {
2696                         state = card->states[0];
2697                         if (state) {
2698                                 dmabuf = &state->dmabuf;
2699                                 dmabuf->ossfragshift = val & 0xffff;
2700                                 dmabuf->ossmaxfrags = (val >> 16) & 0xffff;
2701                         }
2702                 }
2703                 return 0;
2704         case SNDCTL_DSP_GETOSPACE:
2705                 if (!(file->f_mode & FMODE_WRITE))
2706                         return -EINVAL;
2707                 state = card->states[1];
2708                 if (state) {
2709                         dmabuf = &state->dmabuf;
2710                         spin_lock_irqsave(&state->card->lock, flags);
2711                         cs_update_ptr(card, CS_TRUE);
2712                         abinfo.fragsize = dmabuf->fragsize;
2713                         abinfo.fragstotal = dmabuf->numfrag;
2714                 /*
2715                  * for mmap we always have total space available
2716                  */
2717                         if (dmabuf->mapped)
2718                                 abinfo.bytes = dmabuf->dmasize;
2719                         else
2720                                 abinfo.bytes = dmabuf->dmasize - dmabuf->count;
2721
2722                         abinfo.fragments = abinfo.bytes >> dmabuf->fragshift;
2723                         spin_unlock_irqrestore(&state->card->lock, flags);
2724                         return copy_to_user(argp, &abinfo, sizeof(abinfo)) ? -EFAULT : 0;
2725                 }
2726                 return -ENODEV;
2727         case SNDCTL_DSP_GETISPACE:
2728                 if (!(file->f_mode & FMODE_READ))
2729                         return -EINVAL;
2730                 state = card->states[0];
2731                 if (state) {
2732                         dmabuf = &state->dmabuf;
2733                         spin_lock_irqsave(&state->card->lock, flags);
2734                         cs_update_ptr(card, CS_TRUE);
2735                         abinfo.fragsize = dmabuf->fragsize/dmabuf->divisor;
2736                         abinfo.bytes = dmabuf->count/dmabuf->divisor;
2737                         abinfo.fragstotal = dmabuf->numfrag;
2738                         abinfo.fragments = abinfo.bytes >> dmabuf->fragshift;
2739                         spin_unlock_irqrestore(&state->card->lock, flags);
2740                         return copy_to_user(argp, &abinfo, sizeof(abinfo)) ? -EFAULT : 0;
2741                 }
2742                 return -ENODEV;
2743         case SNDCTL_DSP_NONBLOCK:
2744                 file->f_flags |= O_NONBLOCK;
2745                 return 0;
2746         case SNDCTL_DSP_GETCAPS:
2747                 return put_user(DSP_CAP_REALTIME|DSP_CAP_TRIGGER|DSP_CAP_MMAP,
2748                             p);
2749         case SNDCTL_DSP_GETTRIGGER:
2750                 val = 0;
2751                 CS_DBGOUT(CS_IOCTL, 2, printk("cs46xx: DSP_GETTRIGGER()+\n") );
2752                 if (file->f_mode & FMODE_WRITE) {
2753                         state = card->states[1];
2754                         if (state) {
2755                                 dmabuf = &state->dmabuf;
2756                                 if (dmabuf->enable & DAC_RUNNING)
2757                                         val |= PCM_ENABLE_INPUT;
2758                         }
2759                 }
2760                 if (file->f_mode & FMODE_READ) {
2761                         if (state) {
2762                                 state = card->states[0];
2763                                 dmabuf = &state->dmabuf;
2764                                 if (dmabuf->enable & ADC_RUNNING)
2765                                         val |= PCM_ENABLE_OUTPUT;
2766                         }
2767                 }
2768                 CS_DBGOUT(CS_IOCTL, 2, printk("cs46xx: DSP_GETTRIGGER()- val=0x%x\n",val) );
2769                 return put_user(val, p);
2770         case SNDCTL_DSP_SETTRIGGER:
2771                 if (get_user(val, p))
2772                         return -EFAULT;
2773                 if (file->f_mode & FMODE_READ) {
2774                         state = card->states[0];
2775                         if (state) {
2776                                 dmabuf = &state->dmabuf;
2777                                 if (val & PCM_ENABLE_INPUT) {
2778                                         if (!dmabuf->ready && (ret = prog_dmabuf(state)))
2779                                                 return ret;
2780                                         start_adc(state);
2781                                 } else
2782                                         stop_adc(state);
2783                         }
2784                 }
2785                 if (file->f_mode & FMODE_WRITE) {
2786                         state = card->states[1];
2787                         if (state) {
2788                                 dmabuf = &state->dmabuf;
2789                                 if (val & PCM_ENABLE_OUTPUT) {
2790                                         if (!dmabuf->ready && (ret = prog_dmabuf(state)))
2791                                                 return ret;
2792                                         start_dac(state);
2793                                 } else
2794                                         stop_dac(state);
2795                         }
2796                 }
2797                 return 0;
2798         case SNDCTL_DSP_GETIPTR:
2799                 if (!(file->f_mode & FMODE_READ))
2800                         return -EINVAL;
2801                 state = card->states[0];
2802                 if (state) {
2803                         dmabuf = &state->dmabuf;
2804                         spin_lock_irqsave(&state->card->lock, flags);
2805                         cs_update_ptr(card, CS_TRUE);
2806                         cinfo.bytes = dmabuf->total_bytes/dmabuf->divisor;
2807                         cinfo.blocks = dmabuf->count/dmabuf->divisor >> dmabuf->fragshift;
2808                         cinfo.ptr = dmabuf->hwptr/dmabuf->divisor;
2809                         spin_unlock_irqrestore(&state->card->lock, flags);
2810                         if (copy_to_user(argp, &cinfo, sizeof(cinfo)))
2811                                 return -EFAULT;
2812                         return 0;
2813                 }
2814                 return -ENODEV;
2815         case SNDCTL_DSP_GETOPTR:
2816                 if (!(file->f_mode & FMODE_WRITE))
2817                         return -EINVAL;
2818                 state = card->states[1];
2819                 if (state) {
2820                         dmabuf = &state->dmabuf;
2821                         spin_lock_irqsave(&state->card->lock, flags);
2822                         cs_update_ptr(card, CS_TRUE);
2823                         cinfo.bytes = dmabuf->total_bytes;
2824                         if (dmabuf->mapped) {
2825                                 cinfo.blocks = (cinfo.bytes >> dmabuf->fragshift) 
2826                                                         - dmabuf->blocks;
2827                                 CS_DBGOUT(CS_PARMS, 8, 
2828                                         printk("total_bytes=%d blocks=%d dmabuf->blocks=%d\n", 
2829                                         cinfo.bytes,cinfo.blocks,dmabuf->blocks) );
2830                                 dmabuf->blocks = cinfo.bytes >> dmabuf->fragshift;
2831                         } else {
2832                                 cinfo.blocks = dmabuf->count >> dmabuf->fragshift;
2833                         }
2834                         cinfo.ptr = dmabuf->hwptr;
2835
2836                         CS_DBGOUT(CS_PARMS, 4, printk(
2837                             "cs46xx: GETOPTR bytes=%d blocks=%d ptr=%d\n",
2838                                 cinfo.bytes,cinfo.blocks,cinfo.ptr) );
2839                         spin_unlock_irqrestore(&state->card->lock, flags);
2840                         if (copy_to_user(argp, &cinfo, sizeof(cinfo)))
2841                                 return -EFAULT;
2842                         return 0;
2843                 }
2844                 return -ENODEV;
2845         case SNDCTL_DSP_SETDUPLEX:
2846                 return 0;
2847         case SNDCTL_DSP_GETODELAY:
2848                 if (!(file->f_mode & FMODE_WRITE))
2849                         return -EINVAL;
2850                 state = card->states[1];
2851                 if (state) {
2852                         dmabuf = &state->dmabuf;
2853                         spin_lock_irqsave(&state->card->lock, flags);
2854                         cs_update_ptr(card, CS_TRUE);
2855                         val = dmabuf->count;
2856                         spin_unlock_irqrestore(&state->card->lock, flags);
2857                 } else
2858                         val = 0;
2859                 return put_user(val, p);
2860         case SOUND_PCM_READ_RATE:
2861                 if (file->f_mode & FMODE_READ)
2862                         state = card->states[0];
2863                 else 
2864                         state = card->states[1];
2865                 if (state) {
2866                         dmabuf = &state->dmabuf;
2867                         return put_user(dmabuf->rate, p);
2868                 }
2869                 return put_user(0, p);
2870         case SOUND_PCM_READ_CHANNELS:
2871                 if (file->f_mode & FMODE_READ)
2872                         state = card->states[0];
2873                 else 
2874                         state = card->states[1];
2875                 if (state) {
2876                         dmabuf = &state->dmabuf;
2877                         return put_user((dmabuf->fmt & CS_FMT_STEREO) ? 2 : 1,
2878                                 p);
2879                 }
2880                 return put_user(0, p);
2881         case SOUND_PCM_READ_BITS:
2882                 if (file->f_mode & FMODE_READ)
2883                         state = card->states[0];
2884                 else 
2885                         state = card->states[1];
2886                 if (state) {
2887                         dmabuf = &state->dmabuf;
2888                         return put_user((dmabuf->fmt & CS_FMT_16BIT) ? 
2889                                 AFMT_S16_LE : AFMT_U8, p);
2890
2891                 }
2892                 return put_user(0, p);
2893         case SNDCTL_DSP_MAPINBUF:
2894         case SNDCTL_DSP_MAPOUTBUF:
2895         case SNDCTL_DSP_SETSYNCRO:
2896         case SOUND_PCM_WRITE_FILTER:
2897         case SOUND_PCM_READ_FILTER:
2898                 return -EINVAL;
2899         }
2900         return -EINVAL;
2901 }
2902
2903
2904 /*
2905  *      AMP control - null AMP
2906  */
2907  
2908 static void amp_none(struct cs_card *card, int change)
2909 {       
2910 }
2911
2912 /*
2913  *      Crystal EAPD mode
2914  */
2915  
2916 static void amp_voyetra(struct cs_card *card, int change)
2917 {
2918         /* Manage the EAPD bit on the Crystal 4297 
2919            and the Analog AD1885 */
2920            
2921         int old = card->amplifier;
2922         
2923         card->amplifier+=change;
2924         if (card->amplifier && !old) {
2925                 /* Turn the EAPD amp on */
2926                 cs_ac97_set(card->ac97_codec[0],  AC97_POWER_CONTROL, 
2927                         cs_ac97_get(card->ac97_codec[0], AC97_POWER_CONTROL) |
2928                                 0x8000);
2929         } else if(old && !card->amplifier) {
2930                 /* Turn the EAPD amp off */
2931                 cs_ac97_set(card->ac97_codec[0],  AC97_POWER_CONTROL, 
2932                         cs_ac97_get(card->ac97_codec[0], AC97_POWER_CONTROL) &
2933                                 ~0x8000);
2934         }
2935 }
2936
2937                        
2938 /*
2939  *      Game Theatre XP card - EGPIO[2] is used to enable the external amp.
2940  */
2941  
2942 static void amp_hercules(struct cs_card *card, int change)
2943 {
2944         int old = card->amplifier;
2945         if (!card) {
2946                 CS_DBGOUT(CS_ERROR, 2, printk(KERN_INFO 
2947                         "cs46xx: amp_hercules() called before initialized.\n"));
2948                 return;
2949         }
2950         card->amplifier+=change;
2951         if ((card->amplifier && !old) && !(hercules_egpio_disable)) {
2952                 CS_DBGOUT(CS_PARMS, 4, printk(KERN_INFO 
2953                         "cs46xx: amp_hercules() external amp enabled\n"));
2954                 cs461x_pokeBA0(card, BA0_EGPIODR, 
2955                         EGPIODR_GPOE2);     /* enable EGPIO2 output */
2956                 cs461x_pokeBA0(card, BA0_EGPIOPTR, 
2957                         EGPIOPTR_GPPT2);   /* open-drain on output */
2958         } else if (old && !card->amplifier) {
2959                 CS_DBGOUT(CS_PARMS, 4, printk(KERN_INFO 
2960                         "cs46xx: amp_hercules() external amp disabled\n"));
2961                 cs461x_pokeBA0(card, BA0_EGPIODR, 0); /* disable */
2962                 cs461x_pokeBA0(card, BA0_EGPIOPTR, 0); /* disable */
2963         }
2964 }
2965
2966 /*
2967  *      Handle the CLKRUN on a thinkpad. We must disable CLKRUN support
2968  *      whenever we need to beat on the chip.
2969  *
2970  *      The original idea and code for this hack comes from David Kaiser at
2971  *      Linuxcare. Perhaps one day Crystal will document their chips well
2972  *      enough to make them useful.
2973  */
2974  
2975 static void clkrun_hack(struct cs_card *card, int change)
2976 {
2977         struct pci_dev *acpi_dev;
2978         u16 control;
2979         u8 pp;
2980         unsigned long port;
2981         int old = card->active;
2982         
2983         card->active+=change;
2984         
2985         acpi_dev = pci_get_device(PCI_VENDOR_ID_INTEL, PCI_DEVICE_ID_INTEL_82371AB_3, NULL);
2986         if (acpi_dev == NULL)
2987                 return;         /* Not a thinkpad thats for sure */
2988
2989         /* Find the control port */             
2990         pci_read_config_byte(acpi_dev, 0x41, &pp);
2991         port = pp << 8;
2992
2993         /* Read ACPI port */    
2994         control = inw(port + 0x10);
2995
2996         /* Flip CLKRUN off while running */
2997         if (!card->active && old) {
2998                 CS_DBGOUT(CS_PARMS , 9, printk( KERN_INFO
2999                         "cs46xx: clkrun() enable clkrun - change=%d active=%d\n",
3000                                 change,card->active));
3001                 outw(control|0x2000, port+0x10);
3002         } else {
3003         /*
3004         * sometimes on a resume the bit is set, so always reset the bit.
3005         */
3006                 CS_DBGOUT(CS_PARMS , 9, printk( KERN_INFO
3007                         "cs46xx: clkrun() disable clkrun - change=%d active=%d\n",
3008                                 change,card->active));
3009                 outw(control&~0x2000, port+0x10);
3010         }
3011         pci_dev_put(acpi_dev);
3012 }
3013
3014         
3015 static int cs_open(struct inode *inode, struct file *file)
3016 {
3017         struct cs_card *card = file->private_data;
3018         struct cs_state *state = NULL;
3019         struct dmabuf *dmabuf = NULL;
3020         struct list_head *entry;
3021         unsigned int minor = iminor(inode);
3022         int ret = 0;
3023         unsigned int tmp;
3024
3025         CS_DBGOUT(CS_OPEN | CS_FUNCTION, 2, printk("cs46xx: cs_open()+ file=%p %s %s\n",
3026                 file, file->f_mode & FMODE_WRITE ? "FMODE_WRITE" : "",
3027                 file->f_mode & FMODE_READ ? "FMODE_READ" : "") );
3028
3029         list_for_each(entry, &cs46xx_devs) {
3030                 card = list_entry(entry, struct cs_card, list);
3031
3032                 if (!((card->dev_audio ^ minor) & ~0xf))
3033                         break;
3034         }
3035         if (entry == &cs46xx_devs)
3036                 return -ENODEV;
3037         if (!card) {
3038                 CS_DBGOUT(CS_FUNCTION | CS_OPEN, 2, printk(KERN_INFO
3039                         "cs46xx: cs_open(): Error - unable to find audio card struct\n"));
3040                 return -ENODEV;
3041         }
3042
3043         /*
3044          * hardcode state[0] for capture, [1] for playback
3045          */
3046         if (file->f_mode & FMODE_READ) {
3047                 CS_DBGOUT(CS_WAVE_READ, 2, printk("cs46xx: cs_open() FMODE_READ\n") );
3048                 if (card->states[0] == NULL) {
3049                         state = card->states[0] =
3050                                 kmalloc(sizeof(struct cs_state), GFP_KERNEL);
3051                         if (state == NULL)
3052                                 return -ENOMEM;
3053                         memset(state, 0, sizeof(struct cs_state));
3054                         mutex_init(&state->sem);
3055                         dmabuf = &state->dmabuf;
3056                         dmabuf->pbuf = (void *)get_zeroed_page(GFP_KERNEL | GFP_DMA);
3057                         if (dmabuf->pbuf == NULL) {
3058                                 kfree(state);
3059                                 card->states[0] = NULL;
3060                                 return -ENOMEM;
3061                         }
3062                 } else {
3063                         state = card->states[0];
3064                         if (state->open_mode & FMODE_READ)
3065                                 return -EBUSY;
3066                 }
3067                 dmabuf->channel = card->alloc_rec_pcm_channel(card);
3068                         
3069                 if (dmabuf->channel == NULL) {
3070                         kfree(card->states[0]);
3071                         card->states[0] = NULL;
3072                         return -ENODEV;
3073                 }
3074
3075                 /* Now turn on external AMP if needed */
3076                 state->card = card;
3077                 state->card->active_ctrl(state->card, 1);
3078                 state->card->amplifier_ctrl(state->card, 1);
3079                 
3080                 if ((tmp = cs46xx_powerup(card, CS_POWER_ADC))) {
3081                         CS_DBGOUT(CS_ERROR | CS_INIT, 1, printk(KERN_INFO 
3082                                 "cs46xx: cs46xx_powerup of ADC failed (0x%x)\n", tmp));
3083                         return -EIO;
3084                 }
3085
3086                 dmabuf->channel->state = state;
3087                 /* initialize the virtual channel */
3088                 state->virt = 0;
3089                 state->magic = CS_STATE_MAGIC;
3090                 init_waitqueue_head(&dmabuf->wait);
3091                 mutex_init(&state->open_mutex);
3092                 file->private_data = card;
3093
3094                 mutex_lock(&state->open_mutex);
3095
3096                 /* set default sample format. According to OSS Programmer's Guide  /dev/dsp
3097                    should be default to unsigned 8-bits, mono, with sample rate 8kHz and
3098                    /dev/dspW will accept 16-bits sample */
3099
3100                 /* Default input is 8bit mono */
3101                 dmabuf->fmt &= ~CS_FMT_MASK;
3102                 dmabuf->type = CS_TYPE_ADC;
3103                 dmabuf->ossfragshift = 0;
3104                 dmabuf->ossmaxfrags  = 0;
3105                 dmabuf->subdivision  = 0;
3106                 cs_set_adc_rate(state, 8000);
3107                 cs_set_divisor(dmabuf);
3108
3109                 state->open_mode |= FMODE_READ;
3110                 mutex_unlock(&state->open_mutex);
3111         }
3112         if (file->f_mode & FMODE_WRITE) {
3113                 CS_DBGOUT(CS_OPEN, 2, printk("cs46xx: cs_open() FMODE_WRITE\n") );
3114                 if (card->states[1] == NULL) {
3115                         state = card->states[1] =
3116                                 kmalloc(sizeof(struct cs_state), GFP_KERNEL);
3117                         if (state == NULL)
3118                                 return -ENOMEM;
3119                         memset(state, 0, sizeof(struct cs_state));
3120                         mutex_init(&state->sem);
3121                         dmabuf = &state->dmabuf;
3122                         dmabuf->pbuf = (void *)get_zeroed_page(GFP_KERNEL | GFP_DMA);
3123                         if (dmabuf->pbuf == NULL) {
3124                                 kfree(state);
3125                                 card->states[1] = NULL;
3126                                 return -ENOMEM;
3127                         }
3128                 } else {
3129                         state = card->states[1];
3130                         if (state->open_mode & FMODE_WRITE)
3131                                 return -EBUSY;
3132                 }
3133                 dmabuf->channel = card->alloc_pcm_channel(card);
3134                         
3135                 if (dmabuf->channel == NULL) {
3136                         kfree(card->states[1]);
3137                         card->states[1] = NULL;
3138                         return -ENODEV;
3139                 }
3140
3141                 /* Now turn on external AMP if needed */
3142                 state->card = card;
3143                 state->card->active_ctrl(state->card, 1);
3144                 state->card->amplifier_ctrl(state->card, 1);
3145
3146                 if ((tmp = cs46xx_powerup(card, CS_POWER_DAC))) {
3147                         CS_DBGOUT(CS_ERROR | CS_INIT, 1, printk(KERN_INFO 
3148                                 "cs46xx: cs46xx_powerup of DAC failed (0x%x)\n", tmp));
3149                         return -EIO;
3150                 }
3151                 
3152                 dmabuf->channel->state = state;
3153                 /* initialize the virtual channel */
3154                 state->virt = 1;
3155                 state->magic = CS_STATE_MAGIC;
3156                 init_waitqueue_head(&dmabuf->wait);
3157                 mutex_init(&state->open_mutex);
3158                 file->private_data = card;
3159
3160                 mutex_lock(&state->open_mutex);
3161
3162                 /* set default sample format. According to OSS Programmer's Guide  /dev/dsp
3163                    should be default to unsigned 8-bits, mono, with sample rate 8kHz and
3164                    /dev/dspW will accept 16-bits sample */
3165
3166                 /* Default output is 8bit mono. */
3167                 dmabuf->fmt &= ~CS_FMT_MASK;
3168                 dmabuf->type = CS_TYPE_DAC;
3169                 dmabuf->ossfragshift = 0;
3170                 dmabuf->ossmaxfrags  = 0;
3171                 dmabuf->subdivision  = 0;
3172                 cs_set_dac_rate(state, 8000);
3173                 cs_set_divisor(dmabuf);
3174
3175                 state->open_mode |= FMODE_WRITE;
3176                 mutex_unlock(&state->open_mutex);
3177                 if ((ret = prog_dmabuf(state)))
3178                         return ret;
3179         }
3180         CS_DBGOUT(CS_OPEN | CS_FUNCTION, 2, printk("cs46xx: cs_open()- 0\n"));
3181         return nonseekable_open(inode, file);
3182 }
3183
3184 static int cs_release(struct inode *inode, struct file *file)
3185 {
3186         struct cs_card *card = file->private_data;
3187         struct dmabuf *dmabuf;
3188         struct cs_state *state;
3189         unsigned int tmp;
3190         CS_DBGOUT(CS_RELEASE | CS_FUNCTION, 2, printk("cs46xx: cs_release()+ file=%p %s %s\n",
3191                 file, file->f_mode & FMODE_WRITE ? "FMODE_WRITE" : "",
3192                 file->f_mode & FMODE_READ ? "FMODE_READ" : ""));
3193
3194         if (!(file->f_mode & (FMODE_WRITE | FMODE_READ)))
3195                 return -EINVAL;
3196         state = card->states[1];
3197         if (state) {
3198                 if ((state->open_mode & FMODE_WRITE) & (file->f_mode & FMODE_WRITE)) {
3199                         CS_DBGOUT(CS_RELEASE, 2, printk("cs46xx: cs_release() FMODE_WRITE\n"));
3200                         dmabuf = &state->dmabuf;
3201                         cs_clear_tail(state);
3202                         drain_dac(state, file->f_flags & O_NONBLOCK);
3203                         /* stop DMA state machine and free DMA buffers/channels */
3204                         mutex_lock(&state->open_mutex);
3205                         stop_dac(state);
3206                         dealloc_dmabuf(state);
3207                         state->card->free_pcm_channel(state->card, dmabuf->channel->num);
3208                         free_page((unsigned long)state->dmabuf.pbuf);
3209
3210                         /* we're covered by the open_mutex */
3211                         mutex_unlock(&state->open_mutex);
3212                         state->card->states[state->virt] = NULL;
3213                         state->open_mode &= (~file->f_mode) & (FMODE_READ|FMODE_WRITE);
3214
3215                         if ((tmp = cs461x_powerdown(card, CS_POWER_DAC, CS_FALSE))) {
3216                                 CS_DBGOUT(CS_ERROR, 1, printk(KERN_INFO 
3217                                         "cs46xx: cs_release_mixdev() powerdown DAC failure (0x%x)\n",tmp) );
3218                         }
3219
3220                         /* Now turn off external AMP if needed */
3221                         state->card->amplifier_ctrl(state->card, -1);
3222                         state->card->active_ctrl(state->card, -1);
3223                         kfree(state);
3224                 }
3225         }
3226
3227         state = card->states[0];
3228         if (state) {
3229                 if ((state->open_mode & FMODE_READ) & (file->f_mode & FMODE_READ)) {
3230                         CS_DBGOUT(CS_RELEASE, 2, printk("cs46xx: cs_release() FMODE_READ\n"));
3231                         dmabuf = &state->dmabuf;
3232                         mutex_lock(&state->open_mutex);
3233                         stop_adc(state);
3234                         dealloc_dmabuf(state);
3235                         state->card->free_pcm_channel(state->card, dmabuf->channel->num);
3236                         free_page((unsigned long)state->dmabuf.pbuf);
3237
3238                         /* we're covered by the open_mutex */
3239                         mutex_unlock(&state->open_mutex);
3240                         state->card->states[state->virt] = NULL;
3241                         state->open_mode &= (~file->f_mode) & (FMODE_READ|FMODE_WRITE);
3242
3243                         if ((tmp = cs461x_powerdown(card, CS_POWER_ADC, CS_FALSE))) {
3244                                 CS_DBGOUT(CS_ERROR, 1, printk(KERN_INFO 
3245                                         "cs46xx: cs_release_mixdev() powerdown ADC failure (0x%x)\n",tmp) );
3246                         }
3247
3248                         /* Now turn off external AMP if needed */
3249                         state->card->amplifier_ctrl(state->card, -1);
3250                         state->card->active_ctrl(state->card, -1);
3251                         kfree(state);
3252                 }
3253         }
3254
3255         CS_DBGOUT(CS_FUNCTION | CS_RELEASE, 2, printk("cs46xx: cs_release()- 0\n"));
3256         return 0;
3257 }
3258
3259 static void printpm(struct cs_card *s)
3260 {
3261         CS_DBGOUT(CS_PM, 9, printk("pm struct:\n"));
3262         CS_DBGOUT(CS_PM, 9, printk("flags:0x%x u32CLKCR1_SAVE: 0%x u32SSPMValue: 0x%x\n",
3263                 (unsigned)s->pm.flags,s->pm.u32CLKCR1_SAVE,s->pm.u32SSPMValue));
3264         CS_DBGOUT(CS_PM, 9, printk("u32PPLVCvalue: 0x%x u32PPRVCvalue: 0x%x\n",
3265                 s->pm.u32PPLVCvalue,s->pm.u32PPRVCvalue));
3266         CS_DBGOUT(CS_PM, 9, printk("u32FMLVCvalue: 0x%x u32FMRVCvalue: 0x%x\n",
3267                 s->pm.u32FMLVCvalue,s->pm.u32FMRVCvalue));
3268         CS_DBGOUT(CS_PM, 9, printk("u32GPIORvalue: 0x%x u32JSCTLvalue: 0x%x\n",
3269                 s->pm.u32GPIORvalue,s->pm.u32JSCTLvalue));
3270         CS_DBGOUT(CS_PM, 9, printk("u32SSCR: 0x%x u32SRCSA: 0x%x\n",
3271                 s->pm.u32SSCR,s->pm.u32SRCSA));
3272         CS_DBGOUT(CS_PM, 9, printk("u32DacASR: 0x%x u32AdcASR: 0x%x\n",
3273                 s->pm.u32DacASR,s->pm.u32AdcASR));
3274         CS_DBGOUT(CS_PM, 9, printk("u32DacSR: 0x%x u32AdcSR: 0x%x\n",
3275                 s->pm.u32DacSR,s->pm.u32AdcSR));
3276         CS_DBGOUT(CS_PM, 9, printk("u32MIDCR_Save: 0x%x\n",
3277                 s->pm.u32MIDCR_Save));
3278         CS_DBGOUT(CS_PM, 9, printk("u32AC97_powerdown: 0x%x _general_purpose 0x%x\n",
3279                 s->pm.u32AC97_powerdown,s->pm.u32AC97_general_purpose));
3280         CS_DBGOUT(CS_PM, 9, printk("u32AC97_master_volume: 0x%x\n",
3281                 s->pm.u32AC97_master_volume));
3282         CS_DBGOUT(CS_PM, 9, printk("u32AC97_headphone_volume: 0x%x\n",
3283                 s->pm.u32AC97_headphone_volume));
3284         CS_DBGOUT(CS_PM, 9, printk("u32AC97_master_volume_mono: 0x%x\n",
3285                 s->pm.u32AC97_master_volume_mono));
3286         CS_DBGOUT(CS_PM, 9, printk("u32AC97_pcm_out_volume: 0x%x\n",
3287                 s->pm.u32AC97_pcm_out_volume));
3288         CS_DBGOUT(CS_PM, 9, printk("dmabuf_swptr_play: 0x%x dmabuf_count_play: %d\n",
3289                 s->pm.dmabuf_swptr_play,s->pm.dmabuf_count_play));
3290         CS_DBGOUT(CS_PM, 9, printk("dmabuf_swptr_capture: 0x%x dmabuf_count_capture: %d\n",
3291                 s->pm.dmabuf_swptr_capture,s->pm.dmabuf_count_capture));
3292
3293 }
3294
3295 /****************************************************************************
3296 *
3297 *  Suspend - save the ac97 regs, mute the outputs and power down the part.  
3298 *
3299 ****************************************************************************/
3300 static void cs46xx_ac97_suspend(struct cs_card *card)
3301 {
3302         int Count,i;
3303         struct ac97_codec *dev=card->ac97_codec[0];
3304         unsigned int tmp;
3305
3306         CS_DBGOUT(CS_PM, 9, printk("cs46xx: cs46xx_ac97_suspend()+\n"));
3307
3308         if (card->states[1]) {
3309                 stop_dac(card->states[1]);
3310                 resync_dma_ptrs(card->states[1]);
3311         }
3312         if (card->states[0]) {
3313                 stop_adc(card->states[0]);
3314                 resync_dma_ptrs(card->states[0]);
3315         }
3316
3317         for (Count = 0x2, i = 0; (Count <= CS46XX_AC97_HIGHESTREGTORESTORE)
3318                         && (i < CS46XX_AC97_NUMBER_RESTORE_REGS);
3319                         Count += 2, i++) {
3320                 card->pm.ac97[i] = cs_ac97_get(dev, BA0_AC97_RESET + Count);
3321         }
3322 /*
3323 * Save the ac97 volume registers as well as the current powerdown state.
3324 * Now, mute the all the outputs (master, headphone, and mono), as well
3325 * as the PCM volume, in preparation for powering down the entire part.
3326         card->pm.u32AC97_master_volume = (u32)cs_ac97_get( dev, 
3327                         (u8)BA0_AC97_MASTER_VOLUME); 
3328         card->pm.u32AC97_headphone_volume = (u32)cs_ac97_get(dev, 
3329                         (u8)BA0_AC97_HEADPHONE_VOLUME); 
3330         card->pm.u32AC97_master_volume_mono = (u32)cs_ac97_get(dev, 
3331                         (u8)BA0_AC97_MASTER_VOLUME_MONO); 
3332         card->pm.u32AC97_pcm_out_volume = (u32)cs_ac97_get(dev, 
3333                         (u8)BA0_AC97_PCM_OUT_VOLUME);
3334 */ 
3335 /*
3336 * mute the outputs
3337 */
3338         cs_ac97_set(dev, (u8)BA0_AC97_MASTER_VOLUME, 0x8000);
3339         cs_ac97_set(dev, (u8)BA0_AC97_HEADPHONE_VOLUME, 0x8000);
3340         cs_ac97_set(dev, (u8)BA0_AC97_MASTER_VOLUME_MONO, 0x8000);
3341         cs_ac97_set(dev, (u8)BA0_AC97_PCM_OUT_VOLUME, 0x8000);
3342
3343 /*
3344 * save the registers that cause pops
3345 */
3346         card->pm.u32AC97_powerdown = (u32)cs_ac97_get(dev, (u8)AC97_POWER_CONTROL); 
3347         card->pm.u32AC97_general_purpose = (u32)cs_ac97_get(dev, (u8)BA0_AC97_GENERAL_PURPOSE); 
3348 /*
3349 * And power down everything on the AC97 codec.
3350 * well, for now, only power down the DAC/ADC and MIXER VREFON components. 
3351 * trouble with removing VREF.
3352 */
3353         if ((tmp = cs461x_powerdown(card, CS_POWER_DAC | CS_POWER_ADC |
3354                         CS_POWER_MIXVON, CS_TRUE))) {
3355                 CS_DBGOUT(CS_ERROR | CS_INIT, 1, printk(KERN_INFO 
3356                         "cs46xx: cs46xx_ac97_suspend() failure (0x%x)\n",tmp));
3357         }
3358
3359         CS_DBGOUT(CS_PM, 9, printk("cs46xx: cs46xx_ac97_suspend()-\n"));
3360 }
3361
3362 /****************************************************************************
3363 *
3364 *  Resume - power up the part and restore its registers..  
3365 *
3366 ****************************************************************************/
3367 static void cs46xx_ac97_resume(struct cs_card *card)
3368 {
3369         int Count,i;
3370         struct ac97_codec *dev=card->ac97_codec[0];
3371
3372         CS_DBGOUT(CS_PM, 9, printk("cs46xx: cs46xx_ac97_resume()+\n"));
3373
3374 /*
3375 * First, we restore the state of the general purpose register.  This
3376 * contains the mic select (mic1 or mic2) and if we restore this after
3377 * we restore the mic volume/boost state and mic2 was selected at
3378 * suspend time, we will end up with a brief period of time where mic1
3379 * is selected with the volume/boost settings for mic2, causing
3380 * acoustic feedback.  So we restore the general purpose register
3381 * first, thereby getting the correct mic selected before we restore
3382 * the mic volume/boost.
3383 */
3384         cs_ac97_set(dev, (u8)BA0_AC97_GENERAL_PURPOSE, 
3385                 (u16)card->pm.u32AC97_general_purpose);
3386 /*
3387 * Now, while the outputs are still muted, restore the state of power
3388 * on the AC97 part.
3389 */
3390         cs_ac97_set(dev, (u8)BA0_AC97_POWERDOWN, (u16)card->pm.u32AC97_powerdown);
3391         mdelay(5 * cs_laptop_wait);
3392 /*
3393 * Restore just the first set of registers, from register number
3394 * 0x02 to the register number that ulHighestRegToRestore specifies.
3395 */
3396         for (Count = 0x2, i=0; (Count <= CS46XX_AC97_HIGHESTREGTORESTORE) &&
3397                         (i < CS46XX_AC97_NUMBER_RESTORE_REGS); Count += 2, i++) {
3398                 cs_ac97_set(dev, (u8)(BA0_AC97_RESET + Count), (u16)card->pm.ac97[i]);
3399         }
3400
3401         /* Check if we have to init the amplifier */
3402         if (card->amp_init)
3403                 card->amp_init(card);
3404         
3405         CS_DBGOUT(CS_PM, 9, printk("cs46xx: cs46xx_ac97_resume()-\n"));
3406 }
3407
3408
3409 static int cs46xx_restart_part(struct cs_card *card)
3410 {
3411         struct dmabuf *dmabuf;
3412
3413         CS_DBGOUT(CS_PM | CS_FUNCTION, 4, 
3414                 printk( "cs46xx: cs46xx_restart_part()+\n"));
3415         if (card->states[1]) {
3416                 dmabuf = &card->states[1]->dmabuf;
3417                 dmabuf->ready = 0;
3418                 resync_dma_ptrs(card->states[1]);
3419                 cs_set_divisor(dmabuf);
3420                 if (__prog_dmabuf(card->states[1])) {
3421                         CS_DBGOUT(CS_PM | CS_ERROR, 1, 
3422                                 printk("cs46xx: cs46xx_restart_part()- (-1) prog_dmabuf() dac error\n"));
3423                         return -1;
3424                 }
3425                 cs_set_dac_rate(card->states[1], dmabuf->rate);
3426         }
3427         if (card->states[0]) {
3428                 dmabuf = &card->states[0]->dmabuf;
3429                 dmabuf->ready = 0;
3430                 resync_dma_ptrs(card->states[0]);
3431                 cs_set_divisor(dmabuf);
3432                 if (__prog_dmabuf(card->states[0])) {
3433                         CS_DBGOUT(CS_PM | CS_ERROR, 1, 
3434                                 printk("cs46xx: cs46xx_restart_part()- (-1) prog_dmabuf() adc error\n"));
3435                         return -1;
3436                 }
3437                 cs_set_adc_rate(card->states[0], dmabuf->rate);
3438         }
3439         card->pm.flags |= CS46XX_PM_RESUMED;
3440         if (card->states[0])
3441                 start_adc(card->states[0]);
3442         if (card->states[1])
3443                 start_dac(card->states[1]);
3444
3445         card->pm.flags |= CS46XX_PM_IDLE;
3446         card->pm.flags &= ~(CS46XX_PM_SUSPENDING | CS46XX_PM_SUSPENDED 
3447                         | CS46XX_PM_RESUMING | CS46XX_PM_RESUMED);
3448         if (card->states[0])
3449                 wake_up(&card->states[0]->dmabuf.wait);
3450         if (card->states[1])
3451                 wake_up(&card->states[1]->dmabuf.wait);
3452
3453         CS_DBGOUT(CS_PM | CS_FUNCTION, 4, 
3454                 printk( "cs46xx: cs46xx_restart_part()-\n"));
3455         return 0;
3456 }
3457
3458 static void cs461x_reset(struct cs_card *card);
3459 static void cs461x_proc_stop(struct cs_card *card);
3460 static int cs46xx_suspend(struct cs_card *card, pm_message_t state)
3461 {
3462         unsigned int tmp;
3463
3464         CS_DBGOUT(CS_PM | CS_FUNCTION, 4, 
3465                 printk("cs46xx: cs46xx_suspend()+ flags=0x%x s=%p\n",
3466                         (unsigned)card->pm.flags,card));
3467 /*
3468 * check the current state, only suspend if IDLE
3469 */
3470         if (!(card->pm.flags & CS46XX_PM_IDLE)) {
3471                 CS_DBGOUT(CS_PM | CS_ERROR, 2, 
3472                         printk("cs46xx: cs46xx_suspend() unable to suspend, not IDLE\n"));
3473                 return 1;
3474         }
3475         card->pm.flags &= ~CS46XX_PM_IDLE;
3476         card->pm.flags |= CS46XX_PM_SUSPENDING;
3477
3478         card->active_ctrl(card,1);
3479         
3480         tmp = cs461x_peek(card, BA1_PFIE);
3481         tmp &= ~0x0000f03f;
3482         tmp |=  0x00000010;
3483         cs461x_poke(card, BA1_PFIE, tmp);       /* playback interrupt disable */
3484
3485         tmp = cs461x_peek(card, BA1_CIE);
3486         tmp &= ~0x0000003f;
3487         tmp |=  0x00000011;
3488         cs461x_poke(card, BA1_CIE, tmp);        /* capture interrupt disable */
3489
3490         /*
3491          *  Stop playback DMA.
3492          */
3493         tmp = cs461x_peek(card, BA1_PCTL);
3494         cs461x_poke(card, BA1_PCTL, tmp & 0x0000ffff);
3495
3496         /*
3497          *  Stop capture DMA.
3498          */
3499         tmp = cs461x_peek(card, BA1_CCTL);
3500         cs461x_poke(card, BA1_CCTL, tmp & 0xffff0000);
3501
3502         if (card->states[1]) {
3503                 card->pm.dmabuf_swptr_play = card->states[1]->dmabuf.swptr;
3504                 card->pm.dmabuf_count_play = card->states[1]->dmabuf.count;
3505         }
3506         if (card->states[0]) {
3507                 card->pm.dmabuf_swptr_capture = card->states[0]->dmabuf.swptr;
3508                 card->pm.dmabuf_count_capture = card->states[0]->dmabuf.count;
3509         }
3510
3511         cs46xx_ac97_suspend(card);
3512
3513         /*
3514          *  Reset the processor.
3515          */
3516         cs461x_reset(card);
3517
3518         cs461x_proc_stop(card);
3519
3520         /*
3521          *  Power down the DAC and ADC.  For now leave the other areas on.
3522          */
3523         cs_ac97_set(card->ac97_codec[0], AC97_POWER_CONTROL, 0x0300);
3524
3525         /*
3526          *  Power down the PLL.
3527          */
3528         cs461x_pokeBA0(card, BA0_CLKCR1, 0);
3529
3530         /*
3531          *  Turn off the Processor by turning off the software clock enable flag in 
3532          *  the clock control register.
3533          */
3534         tmp = cs461x_peekBA0(card, BA0_CLKCR1) & ~CLKCR1_SWCE;
3535         cs461x_pokeBA0(card, BA0_CLKCR1, tmp);
3536
3537         card->active_ctrl(card,-1);
3538
3539         card->pm.flags &= ~CS46XX_PM_SUSPENDING;
3540         card->pm.flags |= CS46XX_PM_SUSPENDED;
3541
3542         printpm(card);
3543
3544         CS_DBGOUT(CS_PM | CS_FUNCTION, 4, 
3545                 printk("cs46xx: cs46xx_suspend()- flags=0x%x\n",
3546                         (unsigned)card->pm.flags));
3547         return 0;
3548 }
3549
3550 static int cs46xx_resume(struct cs_card *card)
3551 {
3552         int i;
3553
3554         CS_DBGOUT(CS_PM | CS_FUNCTION, 4, 
3555                 printk( "cs46xx: cs46xx_resume()+ flags=0x%x\n",
3556                         (unsigned)card->pm.flags));
3557         if (!(card->pm.flags & CS46XX_PM_SUSPENDED)) {
3558                 CS_DBGOUT(CS_PM | CS_ERROR, 2, 
3559                         printk("cs46xx: cs46xx_resume() unable to resume, not SUSPENDED\n"));
3560                 return 1;
3561         }
3562         card->pm.flags |= CS46XX_PM_RESUMING;
3563         card->pm.flags &= ~CS46XX_PM_SUSPENDED;
3564         printpm(card);
3565         card->active_ctrl(card, 1);
3566
3567         for (i = 0; i < 5; i++) {
3568                 if (cs_hardware_init(card) != 0) {
3569                         CS_DBGOUT(CS_PM | CS_ERROR, 4, printk(
3570                                 "cs46xx: cs46xx_resume()- ERROR in cs_hardware_init()\n"));
3571                         mdelay(10 * cs_laptop_wait);
3572                         cs461x_reset(card);
3573                         continue;
3574                 }
3575                 break;
3576         }
3577         if (i >= 4) {
3578                 CS_DBGOUT(CS_PM | CS_ERROR, 1, printk(
3579                         "cs46xx: cs46xx_resume()- cs_hardware_init() failed, retried %d times.\n",i));
3580                 return 0;
3581         }
3582
3583         if (cs46xx_restart_part(card)) {
3584                 CS_DBGOUT(CS_PM | CS_ERROR, 4, printk(
3585                         "cs46xx: cs46xx_resume(): cs46xx_restart_part() returned error\n"));
3586         }
3587
3588         card->active_ctrl(card, -1);
3589
3590         CS_DBGOUT(CS_PM | CS_FUNCTION, 4, printk("cs46xx: cs46xx_resume()- flags=0x%x\n",
3591                 (unsigned)card->pm.flags));
3592         return 0;
3593 }
3594
3595 static /*const*/ struct file_operations cs461x_fops = {
3596         CS_OWNER        CS_THIS_MODULE
3597         .llseek         = no_llseek,
3598         .read           = cs_read,
3599         .write          = cs_write,
3600         .poll           = cs_poll,
3601         .ioctl          = cs_ioctl,
3602         .mmap           = cs_mmap,
3603         .open           = cs_open,
3604         .release        = cs_release,
3605 };
3606
3607 /* Write AC97 codec registers */
3608
3609
3610 static u16 _cs_ac97_get(struct ac97_codec *dev, u8 reg)
3611 {
3612         struct cs_card *card = dev->private_data;
3613         int count,loopcnt;
3614         unsigned int tmp;
3615         u16 ret;
3616         
3617         /*
3618          *  1. Write ACCAD = Command Address Register = 46Ch for AC97 register address
3619          *  2. Write ACCDA = Command Data Register = 470h    for data to write to AC97 
3620          *  3. Write ACCTL = Control Register = 460h for initiating the write
3621          *  4. Read ACCTL = 460h, DCV should be reset by now and 460h = 17h
3622          *  5. if DCV not cleared, break and return error
3623          *  6. Read ACSTS = Status Register = 464h, check VSTS bit
3624          */
3625
3626         cs461x_peekBA0(card, BA0_ACSDA);
3627
3628         /*
3629          *  Setup the AC97 control registers on the CS461x to send the
3630          *  appropriate command to the AC97 to perform the read.
3631          *  ACCAD = Command Address Register = 46Ch
3632          *  ACCDA = Command Data Register = 470h
3633          *  ACCTL = Control Register = 460h
3634          *  set DCV - will clear when process completed
3635          *  set CRW - Read command
3636          *  set VFRM - valid frame enabled
3637          *  set ESYN - ASYNC generation enabled
3638          *  set RSTN - ARST# inactive, AC97 codec not reset
3639          */
3640
3641         cs461x_pokeBA0(card, BA0_ACCAD, reg);
3642         cs461x_pokeBA0(card, BA0_ACCDA, 0);
3643         cs461x_pokeBA0(card, BA0_ACCTL, ACCTL_DCV | ACCTL_CRW |
3644                                              ACCTL_VFRM | ACCTL_ESYN |
3645                                              ACCTL_RSTN);
3646
3647
3648         /*
3649          *  Wait for the read to occur.
3650          */
3651         if (!(card->pm.flags & CS46XX_PM_IDLE))
3652                 loopcnt = 2000;
3653         else
3654                 loopcnt = 500 * cs_laptop_wait;
3655         loopcnt *= cs_laptop_wait;
3656         for (count = 0; count < loopcnt; count++) {
3657                 /*
3658                  *  First, we want to wait for a short time.
3659                  */
3660                 udelay(10 * cs_laptop_wait);
3661                 /*
3662                  *  Now, check to see if the read has completed.
3663                  *  ACCTL = 460h, DCV should be reset by now and 460h = 17h
3664                  */
3665                 if (!(cs461x_peekBA0(card, BA0_ACCTL) & ACCTL_DCV))
3666                         break;
3667         }
3668
3669         /*
3670          *  Make sure the read completed.
3671          */
3672         if (cs461x_peekBA0(card, BA0_ACCTL) & ACCTL_DCV) {
3673                 CS_DBGOUT(CS_ERROR, 1, printk(KERN_WARNING 
3674                         "cs46xx: AC'97 read problem (ACCTL_DCV), reg = 0x%x returning 0xffff\n", reg));
3675                 return 0xffff;
3676         }
3677
3678         /*
3679          *  Wait for the valid status bit to go active.
3680          */
3681
3682         if (!(card->pm.flags & CS46XX_PM_IDLE))
3683                 loopcnt = 2000;
3684         else
3685                 loopcnt = 1000;
3686         loopcnt *= cs_laptop_wait;
3687         for (count = 0; count < loopcnt; count++) {
3688                 /*
3689                  *  Read the AC97 status register.
3690                  *  ACSTS = Status Register = 464h
3691                  *  VSTS - Valid Status
3692                  */
3693                 if (cs461x_peekBA0(card, BA0_ACSTS) & ACSTS_VSTS)
3694                         break;
3695                 udelay(10 * cs_laptop_wait);
3696         }
3697         
3698         /*
3699          *  Make sure we got valid status.
3700          */
3701         if (!((tmp = cs461x_peekBA0(card, BA0_ACSTS)) & ACSTS_VSTS)) {
3702                 CS_DBGOUT(CS_ERROR, 2, printk(KERN_WARNING 
3703                         "cs46xx: AC'97 read problem (ACSTS_VSTS), reg = 0x%x val=0x%x 0xffff \n", 
3704                                 reg, tmp));
3705                 return 0xffff;
3706         }
3707
3708         /*
3709          *  Read the data returned from the AC97 register.
3710          *  ACSDA = Status Data Register = 474h
3711          */
3712         CS_DBGOUT(CS_FUNCTION, 9, printk(KERN_INFO
3713                 "cs46xx: cs_ac97_get() reg = 0x%x, val = 0x%x, BA0_ACCAD = 0x%x\n", 
3714                         reg, cs461x_peekBA0(card, BA0_ACSDA),
3715                         cs461x_peekBA0(card, BA0_ACCAD)));
3716         ret = cs461x_peekBA0(card, BA0_ACSDA);
3717         return ret;
3718 }
3719
3720 static u16 cs_ac97_get(struct ac97_codec *dev, u8 reg)
3721 {
3722         u16 ret;
3723         struct cs_card *card = dev->private_data;
3724         
3725         spin_lock(&card->ac97_lock);
3726         ret = _cs_ac97_get(dev, reg);
3727         spin_unlock(&card->ac97_lock);
3728         return ret;
3729 }
3730
3731 static void cs_ac97_set(struct ac97_codec *dev, u8 reg, u16 val)
3732 {
3733         struct cs_card *card = dev->private_data;
3734         int count;
3735         int val2 = 0;
3736         
3737         spin_lock(&card->ac97_lock);
3738         
3739         if (reg == AC97_CD_VOL)
3740                 val2 = _cs_ac97_get(dev, AC97_CD_VOL);
3741
3742         /*
3743          *  1. Write ACCAD = Command Address Register = 46Ch for AC97 register address
3744          *  2. Write ACCDA = Command Data Register = 470h    for data to write to AC97
3745          *  3. Write ACCTL = Control Register = 460h for initiating the write
3746          *  4. Read ACCTL = 460h, DCV should be reset by now and 460h = 07h
3747          *  5. if DCV not cleared, break and return error
3748          */
3749
3750         /*
3751          *  Setup the AC97 control registers on the CS461x to send the
3752          *  appropriate command to the AC97 to perform the read.
3753          *  ACCAD = Command Address Register = 46Ch
3754          *  ACCDA = Command Data Register = 470h
3755          *  ACCTL = Control Register = 460h
3756          *  set DCV - will clear when process completed
3757          *  reset CRW - Write command
3758          *  set VFRM - valid frame enabled
3759          *  set ESYN - ASYNC generation enabled
3760          *  set RSTN - ARST# inactive, AC97 codec not reset
3761          */
3762         cs461x_pokeBA0(card, BA0_ACCAD, reg);
3763         cs461x_pokeBA0(card, BA0_ACCDA, val);
3764         cs461x_peekBA0(card, BA0_ACCTL);
3765         cs461x_pokeBA0(card, BA0_ACCTL, 0 | ACCTL_VFRM | ACCTL_ESYN | ACCTL_RSTN);
3766         cs461x_pokeBA0(card, BA0_ACCTL, ACCTL_DCV | ACCTL_VFRM |
3767                                              ACCTL_ESYN | ACCTL_RSTN);
3768         for (count = 0; count < 1000; count++) {
3769                 /*
3770                  *  First, we want to wait for a short time.
3771                  */
3772                 udelay(10 * cs_laptop_wait);
3773                 /*
3774                  *  Now, check to see if the write has completed.
3775                  *  ACCTL = 460h, DCV should be reset by now and 460h = 07h
3776                  */
3777                 if (!(cs461x_peekBA0(card, BA0_ACCTL) & ACCTL_DCV))
3778                         break;
3779         }
3780         /*
3781          *  Make sure the write completed.
3782          */
3783         if (cs461x_peekBA0(card, BA0_ACCTL) & ACCTL_DCV) {
3784                 CS_DBGOUT(CS_ERROR, 1, printk(KERN_WARNING 
3785                         "cs46xx: AC'97 write problem, reg = 0x%x, val = 0x%x\n", reg, val));
3786         }
3787
3788         spin_unlock(&card->ac97_lock);
3789
3790         /*
3791          *      Adjust power if the mixer is selected/deselected according
3792          *      to the CD.
3793          *
3794          *      IF the CD is a valid input source (mixer or direct) AND
3795          *              the CD is not muted THEN power is needed
3796          *
3797          *      We do two things. When record select changes the input to
3798          *      add/remove the CD we adjust the power count if the CD is
3799          *      unmuted.
3800          *
3801          *      When the CD mute changes we adjust the power level if the
3802          *      CD was a valid input.
3803          *
3804          *      We also check for CD volume != 0, as the CD mute isn't
3805          *      normally tweaked from userspace.
3806          */
3807          
3808         /* CD mute change ? */
3809         
3810         if (reg == AC97_CD_VOL) {
3811                 /* Mute bit change ? */
3812                 if ((val2^val) & 0x8000 ||
3813                     ((val2 == 0x1f1f || val == 0x1f1f) && val2 != val)) {
3814                         /* This is a hack but its cleaner than the alternatives.
3815                            Right now card->ac97_codec[0] might be NULL as we are
3816                            still doing codec setup. This does an early assignment
3817                            to avoid the problem if it occurs */
3818                            
3819                         if (card->ac97_codec[0] == NULL)
3820                                 card->ac97_codec[0] = dev;
3821                                 
3822                         /* Mute on */
3823                         if (val & 0x8000 || val == 0x1f1f)
3824                                 card->amplifier_ctrl(card, -1);
3825                         else { /* Mute off power on */
3826                                 if (card->amp_init)
3827                                         card->amp_init(card);
3828                                 card->amplifier_ctrl(card, 1);
3829                         }
3830                 }
3831         }
3832 }
3833
3834 /* OSS /dev/mixer file operation methods */
3835
3836 static int cs_open_mixdev(struct inode *inode, struct file *file)
3837 {
3838         int i = 0;
3839         unsigned int minor = iminor(inode);
3840         struct cs_card *card = NULL;
3841         struct list_head *entry;
3842         unsigned int tmp;
3843
3844         CS_DBGOUT(CS_FUNCTION | CS_OPEN, 4,
3845                   printk(KERN_INFO "cs46xx: cs_open_mixdev()+\n"));
3846
3847         list_for_each(entry, &cs46xx_devs) {
3848                 card = list_entry(entry, struct cs_card, list);
3849                 for (i = 0; i < NR_AC97; i++)
3850                         if (card->ac97_codec[i] != NULL &&
3851                             card->ac97_codec[i]->dev_mixer == minor)
3852                                 goto match;
3853         }
3854         if (!card) {
3855                 CS_DBGOUT(CS_FUNCTION | CS_OPEN | CS_ERROR, 2,
3856                         printk(KERN_INFO "cs46xx: cs46xx_open_mixdev()- -ENODEV\n"));
3857                 return -ENODEV;
3858         }
3859  match:
3860         if (!card->ac97_codec[i])
3861                 return -ENODEV;
3862         file->private_data = card->ac97_codec[i];
3863
3864         card->active_ctrl(card,1);
3865         if (!CS_IN_USE(&card->mixer_use_cnt)) {
3866                 if ((tmp = cs46xx_powerup(card, CS_POWER_MIXVON))) {
3867                         CS_DBGOUT(CS_ERROR | CS_INIT, 1, printk(KERN_INFO 
3868                                 "cs46xx: cs_open_mixdev() powerup failure (0x%x)\n", tmp));
3869                         return -EIO;
3870                 }
3871         }
3872         card->amplifier_ctrl(card, 1);
3873         CS_INC_USE_COUNT(&card->mixer_use_cnt);
3874         CS_DBGOUT(CS_FUNCTION | CS_OPEN, 4,
3875                   printk(KERN_INFO "cs46xx: cs_open_mixdev()- 0\n"));
3876         return nonseekable_open(inode, file);
3877 }
3878
3879 static int cs_release_mixdev(struct inode *inode, struct file *file)
3880 {
3881         unsigned int minor = iminor(inode);
3882         struct cs_card *card = NULL;
3883         struct list_head *entry;
3884         int i;
3885         unsigned int tmp;
3886
3887         CS_DBGOUT(CS_FUNCTION | CS_RELEASE, 4,
3888                   printk(KERN_INFO "cs46xx: cs_release_mixdev()+\n"));
3889         list_for_each(entry, &cs46xx_devs)
3890         {
3891                 card = list_entry(entry, struct cs_card, list);
3892                 for (i = 0; i < NR_AC97; i++)
3893                         if (card->ac97_codec[i] != NULL &&
3894                             card->ac97_codec[i]->dev_mixer == minor)
3895                                 goto match;
3896         }
3897         if (!card) {
3898                 CS_DBGOUT(CS_FUNCTION | CS_OPEN | CS_ERROR, 2,
3899                         printk(KERN_INFO "cs46xx: cs46xx_open_mixdev()- -ENODEV\n"));
3900                 return -ENODEV;
3901         }
3902 match:
3903         if (!CS_DEC_AND_TEST(&card->mixer_use_cnt)) {
3904                 CS_DBGOUT(CS_FUNCTION | CS_RELEASE, 4,
3905                           printk(KERN_INFO "cs46xx: cs_release_mixdev()- no powerdown, usecnt>0\n"));
3906                 card->active_ctrl(card, -1);
3907                 card->amplifier_ctrl(card, -1);
3908                 return 0;
3909         }
3910 /*
3911 * ok, no outstanding mixer opens, so powerdown.
3912 */
3913         if ((tmp = cs461x_powerdown(card, CS_POWER_MIXVON, CS_FALSE))) {
3914                 CS_DBGOUT(CS_ERROR | CS_INIT, 1, printk(KERN_INFO 
3915                         "cs46xx: cs_release_mixdev() powerdown MIXVON failure (0x%x)\n", tmp));
3916                 card->active_ctrl(card, -1);
3917                 card->amplifier_ctrl(card, -1);
3918                 return -EIO;
3919         }
3920         card->active_ctrl(card, -1);
3921         card->amplifier_ctrl(card, -1);
3922         CS_DBGOUT(CS_FUNCTION | CS_RELEASE, 4,
3923                   printk(KERN_INFO "cs46xx: cs_release_mixdev()- 0\n"));
3924         return 0;
3925 }
3926
3927 static int cs_ioctl_mixdev(struct inode *inode, struct file *file, unsigned int cmd,
3928                         unsigned long arg)
3929 {
3930         struct ac97_codec *codec = file->private_data;
3931         struct cs_card *card = NULL;
3932         struct list_head *entry;
3933         unsigned long __user *p = (long __user *)arg;
3934 #if CSDEBUG_INTERFACE
3935         int val;
3936
3937         if (    (cmd == SOUND_MIXER_CS_GETDBGMASK) ||
3938                 (cmd == SOUND_MIXER_CS_SETDBGMASK) ||
3939                 (cmd == SOUND_MIXER_CS_GETDBGLEVEL) ||
3940                 (cmd == SOUND_MIXER_CS_SETDBGLEVEL) ||
3941                 (cmd == SOUND_MIXER_CS_APM)) {
3942                 switch (cmd) {
3943                 case SOUND_MIXER_CS_GETDBGMASK:
3944                         return put_user(cs_debugmask, p);
3945                 case SOUND_MIXER_CS_GETDBGLEVEL:
3946                         return put_user(cs_debuglevel, p);
3947                 case SOUND_MIXER_CS_SETDBGMASK:
3948                         if (get_user(val, p))
3949                                 return -EFAULT;
3950                         cs_debugmask = val;
3951                         return 0;
3952                 case SOUND_MIXER_CS_SETDBGLEVEL:
3953                         if (get_user(val, p))
3954                                 return -EFAULT;
3955                         cs_debuglevel = val;
3956                         return 0;
3957                 case SOUND_MIXER_CS_APM:
3958                         if (get_user(val, p))
3959                                 return -EFAULT;
3960                         if (val == CS_IOCTL_CMD_SUSPEND) {
3961                                 list_for_each(entry, &cs46xx_devs) {
3962                                         card = list_entry(entry, struct cs_card, list);
3963                                         cs46xx_suspend(card, PMSG_ON);
3964                                 }
3965
3966                         } else if (val == CS_IOCTL_CMD_RESUME) {
3967                                 list_for_each(entry, &cs46xx_devs) {
3968                                         card = list_entry(entry, struct cs_card, list);
3969                                         cs46xx_resume(card);
3970                                 }
3971                         } else {
3972                                 CS_DBGOUT(CS_ERROR, 1, printk(KERN_INFO
3973                                     "cs46xx: mixer_ioctl(): invalid APM cmd (%d)\n",
3974                                         val));
3975                         }
3976                         return 0;
3977                 default:
3978                         CS_DBGOUT(CS_ERROR, 1, printk(KERN_INFO 
3979                                 "cs46xx: mixer_ioctl(): ERROR unknown debug cmd\n"));
3980                         return 0;
3981                 }
3982         }
3983 #endif
3984         return codec->mixer_ioctl(codec, cmd, arg);
3985 }
3986
3987 static /*const*/ struct file_operations cs_mixer_fops = {
3988         CS_OWNER        CS_THIS_MODULE
3989         .llseek         = no_llseek,
3990         .ioctl          = cs_ioctl_mixdev,
3991         .open           = cs_open_mixdev,
3992         .release        = cs_release_mixdev,
3993 };
3994
3995 /* AC97 codec initialisation. */
3996 static int __init cs_ac97_init(struct cs_card *card)
3997 {
3998         int num_ac97 = 0;
3999         int ready_2nd = 0;
4000         struct ac97_codec *codec;
4001         u16 eid;
4002
4003         CS_DBGOUT(CS_FUNCTION | CS_INIT, 2, printk(KERN_INFO 
4004                 "cs46xx: cs_ac97_init()+\n") );
4005
4006         for (num_ac97 = 0; num_ac97 < NR_AC97; num_ac97++) {
4007                 if ((codec = ac97_alloc_codec()) == NULL)
4008                         return -ENOMEM;
4009
4010                 /* initialize some basic codec information, other fields will be filled
4011                    in ac97_probe_codec */
4012                 codec->private_data = card;
4013                 codec->id = num_ac97;
4014
4015                 codec->codec_read = cs_ac97_get;
4016                 codec->codec_write = cs_ac97_set;
4017         
4018                 if (ac97_probe_codec(codec) == 0) {
4019                         CS_DBGOUT(CS_FUNCTION | CS_INIT, 2, printk(KERN_INFO 
4020                                 "cs46xx: cs_ac97_init()- codec number %d not found\n",
4021                                         num_ac97) );
4022                         card->ac97_codec[num_ac97] = NULL;
4023                         break;
4024                 }
4025                 CS_DBGOUT(CS_FUNCTION | CS_INIT, 2, printk(KERN_INFO 
4026                         "cs46xx: cs_ac97_init() found codec %d\n",num_ac97));
4027
4028                 eid = cs_ac97_get(codec, AC97_EXTENDED_ID);
4029                 
4030                 if (eid == 0xFFFF) {
4031                         printk(KERN_WARNING "cs46xx: codec %d not present\n",num_ac97);
4032                         ac97_release_codec(codec);
4033                         break;
4034                 }
4035                 
4036                 card->ac97_features = eid;
4037                         
4038                 if ((codec->dev_mixer = register_sound_mixer(&cs_mixer_fops, -1)) < 0) {
4039                         printk(KERN_ERR "cs46xx: couldn't register mixer!\n");
4040                         ac97_release_codec(codec);
4041                         break;
4042                 }
4043                 card->ac97_codec[num_ac97] = codec;
4044
4045                 CS_DBGOUT(CS_FUNCTION | CS_INIT, 2, printk(KERN_INFO 
4046                         "cs46xx: cs_ac97_init() ac97_codec[%d] set to %p\n",
4047                                 (unsigned int)num_ac97,
4048                                 codec));
4049                 /* if there is no secondary codec at all, don't probe any more */
4050                 if (!ready_2nd)
4051                 {
4052                         num_ac97 += 1;
4053                         break;
4054                 }
4055         }
4056         CS_DBGOUT(CS_FUNCTION | CS_INIT, 2, printk(KERN_INFO 
4057                 "cs46xx: cs_ac97_init()- %d\n", (unsigned int)num_ac97));
4058         return num_ac97;
4059 }
4060
4061 /*
4062  * load the static image into the DSP
4063  */
4064 #include "cs461x_image.h"
4065 static void cs461x_download_image(struct cs_card *card)
4066 {
4067     unsigned i, j, temp1, temp2, offset, count;
4068     unsigned char __iomem *pBA1 = ioremap(card->ba1_addr, 0x40000);
4069     for (i = 0; i < CLEAR__COUNT; i++) {
4070         offset = ClrStat[i].BA1__DestByteOffset;
4071         count  = ClrStat[i].BA1__SourceSize;
4072         for (temp1 = offset; temp1 < (offset + count); temp1 += 4)
4073               writel(0, pBA1+temp1);
4074     }
4075
4076     for (i = 0; i < FILL__COUNT; i++) {
4077         temp2 = FillStat[i].Offset;
4078         for (j = 0; j < (FillStat[i].Size) / 4; j++) {
4079             temp1 = (FillStat[i]).pFill[j];
4080             writel(temp1, pBA1+temp2 + j * 4);
4081         }
4082     }
4083     iounmap(pBA1);
4084 }
4085
4086 /*
4087  *  Chip reset
4088  */
4089
4090 static void cs461x_reset(struct cs_card *card)
4091 {
4092         int idx;
4093
4094         /*
4095          *  Write the reset bit of the SP control register.
4096          */
4097         cs461x_poke(card, BA1_SPCR, SPCR_RSTSP);
4098
4099         /*
4100          *  Write the control register.
4101          */
4102         cs461x_poke(card, BA1_SPCR, SPCR_DRQEN);
4103
4104         /*
4105          *  Clear the trap registers.
4106          */
4107         for (idx = 0; idx < 8; idx++) {
4108                 cs461x_poke(card, BA1_DREG, DREG_REGID_TRAP_SELECT + idx);
4109                 cs461x_poke(card, BA1_TWPR, 0xFFFF);
4110         }
4111         cs461x_poke(card, BA1_DREG, 0);
4112
4113         /*
4114          *  Set the frame timer to reflect the number of cycles per frame.
4115          */
4116         cs461x_poke(card, BA1_FRMT, 0xadf);
4117 }
4118
4119 static void cs461x_clear_serial_FIFOs(struct cs_card *card, int type)
4120 {
4121         int idx, loop, startfifo=0, endfifo=0, powerdown1 = 0;
4122         unsigned int tmp;
4123
4124         /*
4125          *  See if the devices are powered down.  If so, we must power them up first
4126          *  or they will not respond.
4127          */
4128         if (!((tmp = cs461x_peekBA0(card, BA0_CLKCR1)) & CLKCR1_SWCE)) {
4129                 cs461x_pokeBA0(card, BA0_CLKCR1, tmp | CLKCR1_SWCE);
4130                 powerdown1 = 1;
4131         }
4132
4133         /*
4134          *  We want to clear out the serial port FIFOs so we don't end up playing
4135          *  whatever random garbage happens to be in them.  We fill the sample FIFOS
4136          *  with zero (silence).
4137          */
4138         cs461x_pokeBA0(card, BA0_SERBWP, 0);
4139
4140         /*
4141         * Check for which FIFO locations to clear, if we are currently
4142         * playing or capturing then we don't want to put in 128 bytes of
4143         * "noise".
4144          */
4145         if (type & CS_TYPE_DAC) {
4146                 startfifo = 128;
4147                 endfifo = 256;
4148         }
4149         if (type & CS_TYPE_ADC) {
4150                 startfifo = 0;
4151                 if (!endfifo)
4152                         endfifo = 128;
4153         }
4154         /*
4155          *  Fill sample FIFO locations (256 locations total).
4156          */
4157         for (idx = startfifo; idx < endfifo; idx++) {
4158                 /*
4159                  *  Make sure the previous FIFO write operation has completed.
4160                  */
4161                 for (loop = 0; loop < 5; loop++) {
4162                         udelay(50);
4163                         if (!(cs461x_peekBA0(card, BA0_SERBST) & SERBST_WBSY))
4164                                 break;
4165                 }
4166                 if (cs461x_peekBA0(card, BA0_SERBST) & SERBST_WBSY) {
4167                         if (powerdown1)
4168                                 cs461x_pokeBA0(card, BA0_CLKCR1, tmp);
4169                 }
4170                 /*
4171                  *  Write the serial port FIFO index.
4172                  */
4173                 cs461x_pokeBA0(card, BA0_SERBAD, idx);
4174                 /*
4175                  *  Tell the serial port to load the new value into the FIFO location.
4176                  */
4177                 cs461x_pokeBA0(card, BA0_SERBCM, SERBCM_WRC);
4178         }
4179         /*
4180          *  Now, if we powered up the devices, then power them back down again.
4181          *  This is kinda ugly, but should never happen.
4182          */
4183         if (powerdown1)
4184                 cs461x_pokeBA0(card, BA0_CLKCR1, tmp);
4185 }
4186
4187
4188 static int cs461x_powerdown(struct cs_card *card, unsigned int type, int suspendflag)
4189 {
4190         int count;
4191         unsigned int tmp=0,muted=0;
4192
4193         CS_DBGOUT(CS_FUNCTION, 4, printk(KERN_INFO 
4194                 "cs46xx: cs461x_powerdown()+ type=0x%x\n",type));
4195         if (!cs_powerdown && !suspendflag) {
4196                 CS_DBGOUT(CS_FUNCTION, 8, printk(KERN_INFO 
4197                         "cs46xx: cs461x_powerdown() DISABLED exiting\n"));
4198                 return 0;
4199         }
4200         tmp = cs_ac97_get(card->ac97_codec[0], AC97_POWER_CONTROL);
4201         CS_DBGOUT(CS_FUNCTION, 8, printk(KERN_INFO 
4202                 "cs46xx: cs461x_powerdown() powerdown reg=0x%x\n",tmp));
4203 /*
4204 * if powering down only the VREF, and not powering down the DAC/ADC,
4205 * then do not power down the VREF, UNLESS both the DAC and ADC are not
4206 * currently powered down.  If powering down DAC and ADC, then
4207 * it is possible to power down the VREF (ON).
4208 */
4209         if (((type & CS_POWER_MIXVON) &&
4210                  (!(type & CS_POWER_ADC) || (!(type & CS_POWER_DAC))))
4211               && 
4212                 ((tmp & CS_AC97_POWER_CONTROL_ADC_ON) ||
4213                  (tmp & CS_AC97_POWER_CONTROL_DAC_ON))) {
4214                 CS_DBGOUT(CS_FUNCTION, 8, printk(KERN_INFO 
4215                         "cs46xx: cs461x_powerdown()- 0  unable to powerdown. tmp=0x%x\n",tmp));
4216                 return 0;
4217         }
4218 /*
4219 * for now, always keep power to the mixer block.
4220 * not sure why it's a problem but it seems to be if we power off.
4221 */
4222         type &= ~CS_POWER_MIXVON;
4223         type &= ~CS_POWER_MIXVOFF;
4224
4225         /*
4226          *  Power down indicated areas.
4227          */
4228         if (type & CS_POWER_MIXVOFF) {
4229
4230                 CS_DBGOUT(CS_FUNCTION, 4, 
4231                         printk(KERN_INFO "cs46xx: cs461x_powerdown()+ MIXVOFF\n"));
4232                 /*
4233                  *  Power down the MIXER (VREF ON) on the AC97 card.  
4234                  */
4235                 tmp = cs_ac97_get(card->ac97_codec[0], AC97_POWER_CONTROL);
4236                 if (tmp & CS_AC97_POWER_CONTROL_MIXVOFF_ON) {
4237                         if (!muted) {
4238                                 cs_mute(card, CS_TRUE);
4239                                 muted = 1;
4240                         }
4241                         tmp |= CS_AC97_POWER_CONTROL_MIXVOFF;
4242                         cs_ac97_set(card->ac97_codec[0], AC97_POWER_CONTROL, tmp );
4243                         /*
4244                          *  Now, we wait until we sample a ready state.
4245                          */
4246                         for (count = 0; count < 32; count++) {
4247                                 /*
4248                                  *  First, lets wait a short while to let things settle out a
4249                                  *  bit, and to prevent retrying the read too quickly.
4250                                  */
4251                                 udelay(500);
4252
4253                                 /*
4254                                  *  Read the current state of the power control register.
4255                                  */
4256                                 if (!(cs_ac97_get(card->ac97_codec[0], AC97_POWER_CONTROL) & 
4257                                         CS_AC97_POWER_CONTROL_MIXVOFF_ON))
4258                                         break;
4259                         }
4260                         
4261                         /*
4262                          *  Check the status..
4263                          */
4264                         if (cs_ac97_get(card->ac97_codec[0], AC97_POWER_CONTROL) & 
4265                                 CS_AC97_POWER_CONTROL_MIXVOFF_ON) {
4266                                 CS_DBGOUT(CS_ERROR, 1, printk(KERN_WARNING 
4267                                         "cs46xx: powerdown MIXVOFF failed\n"));
4268                                 return 1;
4269                         }
4270                 }
4271         }
4272         if (type & CS_POWER_MIXVON) {
4273
4274                 CS_DBGOUT(CS_FUNCTION, 4, 
4275                         printk(KERN_INFO "cs46xx: cs461x_powerdown()+ MIXVON\n"));
4276                 /*
4277                  *  Power down the MIXER (VREF ON) on the AC97 card.  
4278                  */
4279                 tmp = cs_ac97_get(card->ac97_codec[0], AC97_POWER_CONTROL);
4280                 if (tmp & CS_AC97_POWER_CONTROL_MIXVON_ON) {
4281                         if (!muted) {
4282                                 cs_mute(card, CS_TRUE);
4283                                 muted = 1;
4284                         }
4285                         tmp |= CS_AC97_POWER_CONTROL_MIXVON;
4286                         cs_ac97_set(card->ac97_codec[0], AC97_POWER_CONTROL, tmp);
4287                         /*
4288                          *  Now, we wait until we sample a ready state.
4289                          */
4290                         for (count = 0; count < 32; count++) {
4291                                 /*
4292                                  *  First, lets wait a short while to let things settle out a
4293                                  *  bit, and to prevent retrying the read too quickly.
4294                                  */
4295                                 udelay(500);
4296
4297                                 /*
4298                                  *  Read the current state of the power control register.
4299                                  */
4300                                 if (!(cs_ac97_get(card->ac97_codec[0], AC97_POWER_CONTROL) & 
4301                                         CS_AC97_POWER_CONTROL_MIXVON_ON))
4302                                         break;
4303                         }
4304                         
4305                         /*
4306                          *  Check the status..
4307                          */
4308                         if (cs_ac97_get(card->ac97_codec[0], AC97_POWER_CONTROL) & 
4309                                 CS_AC97_POWER_CONTROL_MIXVON_ON) {
4310                                 CS_DBGOUT(CS_ERROR, 1, printk(KERN_WARNING 
4311                                         "cs46xx: powerdown MIXVON failed\n"));
4312                                 return 1;
4313                         }
4314                 }
4315         }
4316         if (type & CS_POWER_ADC) {
4317                 /*
4318                  *  Power down the ADC on the AC97 card.  
4319                  */
4320                 CS_DBGOUT(CS_FUNCTION, 4, printk(KERN_INFO "cs46xx: cs461x_powerdown()+ ADC\n"));
4321                 tmp = cs_ac97_get(card->ac97_codec[0], AC97_POWER_CONTROL);
4322                 if (tmp & CS_AC97_POWER_CONTROL_ADC_ON) {
4323                         if (!muted) {
4324                                 cs_mute(card, CS_TRUE);
4325                                 muted = 1;
4326                         }
4327                         tmp |= CS_AC97_POWER_CONTROL_ADC;
4328                         cs_ac97_set(card->ac97_codec[0], AC97_POWER_CONTROL, tmp);
4329
4330                         /*
4331                          *  Now, we wait until we sample a ready state.
4332                          */
4333                         for (count = 0; count < 32; count++) {
4334                                 /*
4335                                  *  First, lets wait a short while to let things settle out a
4336                                  *  bit, and to prevent retrying the read too quickly.
4337                                  */
4338                                 udelay(500);
4339
4340                                 /*
4341                                  *  Read the current state of the power control register.
4342                                  */
4343                                 if (!(cs_ac97_get(card->ac97_codec[0], AC97_POWER_CONTROL) & 
4344                                         CS_AC97_POWER_CONTROL_ADC_ON))
4345                                         break;
4346                         }
4347
4348                         /*
4349                          *  Check the status..
4350                          */
4351                         if (cs_ac97_get(card->ac97_codec[0], AC97_POWER_CONTROL) & 
4352                                 CS_AC97_POWER_CONTROL_ADC_ON) {
4353                                 CS_DBGOUT(CS_ERROR, 1, printk(KERN_WARNING 
4354                                         "cs46xx: powerdown ADC failed\n"));
4355                                 return 1;
4356                         }
4357                 }
4358         }
4359         if (type & CS_POWER_DAC) {
4360                 /*
4361                  *  Power down the DAC on the AC97 card.  
4362                  */
4363
4364                 CS_DBGOUT(CS_FUNCTION, 4, 
4365                         printk(KERN_INFO "cs46xx: cs461x_powerdown()+ DAC\n"));
4366                 tmp = cs_ac97_get(card->ac97_codec[0], AC97_POWER_CONTROL);
4367                 if (tmp & CS_AC97_POWER_CONTROL_DAC_ON) {
4368                         if (!muted) {
4369                                 cs_mute(card, CS_TRUE);
4370                                 muted = 1;
4371                         }
4372                         tmp |= CS_AC97_POWER_CONTROL_DAC;
4373                         cs_ac97_set(card->ac97_codec[0], AC97_POWER_CONTROL, tmp);
4374                         /*
4375                          *  Now, we wait until we sample a ready state.
4376                          */
4377                         for (count = 0; count < 32; count++) {
4378                                 /*
4379                                  *  First, lets wait a short while to let things settle out a
4380                                  *  bit, and to prevent retrying the read too quickly.
4381                                  */
4382                                 udelay(500);
4383
4384                                 /*
4385                                  *  Read the current state of the power control register.
4386                                  */
4387                                 if (!(cs_ac97_get(card->ac97_codec[0], AC97_POWER_CONTROL) & 
4388                                         CS_AC97_POWER_CONTROL_DAC_ON))
4389                                         break;
4390                         }
4391                         
4392                         /*
4393                          *  Check the status..
4394                          */
4395                         if (cs_ac97_get(card->ac97_codec[0], AC97_POWER_CONTROL) & 
4396                                 CS_AC97_POWER_CONTROL_DAC_ON) {
4397                                 CS_DBGOUT(CS_ERROR, 1, printk(KERN_WARNING 
4398                                         "cs46xx: powerdown DAC failed\n"));
4399                                 return 1;
4400                         }
4401                 }
4402         }
4403         tmp = cs_ac97_get(card->ac97_codec[0], AC97_POWER_CONTROL);
4404         if (muted)
4405                 cs_mute(card, CS_FALSE);
4406         CS_DBGOUT(CS_FUNCTION, 4, printk(KERN_INFO 
4407                 "cs46xx: cs461x_powerdown()- 0 tmp=0x%x\n",tmp));
4408         return 0;
4409 }
4410
4411 static int cs46xx_powerup(struct cs_card *card, unsigned int type)
4412 {
4413         int count;
4414         unsigned int tmp = 0, muted = 0;
4415
4416         CS_DBGOUT(CS_FUNCTION, 8, printk(KERN_INFO 
4417                 "cs46xx: cs46xx_powerup()+ type=0x%x\n",type));
4418         /*
4419         * check for VREF and powerup if need to.
4420         */
4421         if (type & CS_POWER_MIXVON)
4422                 type |= CS_POWER_MIXVOFF;
4423         if (type & (CS_POWER_DAC | CS_POWER_ADC))
4424                 type |= CS_POWER_MIXVON | CS_POWER_MIXVOFF;
4425
4426         /*
4427          *  Power up indicated areas.
4428          */
4429         if (type & CS_POWER_MIXVOFF) {
4430
4431                 CS_DBGOUT(CS_FUNCTION, 4, 
4432                         printk(KERN_INFO "cs46xx: cs46xx_powerup()+ MIXVOFF\n"));
4433                 /*
4434                  *  Power up the MIXER (VREF ON) on the AC97 card.  
4435                  */
4436                 tmp = cs_ac97_get(card->ac97_codec[0], AC97_POWER_CONTROL);
4437                 if (!(tmp & CS_AC97_POWER_CONTROL_MIXVOFF_ON)) {
4438                         if (!muted) {
4439                                 cs_mute(card, CS_TRUE);
4440                                 muted = 1;
4441                         }
4442                         tmp &= ~CS_AC97_POWER_CONTROL_MIXVOFF;
4443                         cs_ac97_set(card->ac97_codec[0], AC97_POWER_CONTROL, tmp );
4444                         /*
4445                          *  Now, we wait until we sample a ready state.
4446                          */
4447                         for (count = 0; count < 32; count++) {
4448                                 /*
4449                                  *  First, lets wait a short while to let things settle out a
4450                                  *  bit, and to prevent retrying the read too quickly.
4451                                  */
4452                                 udelay(500);
4453
4454                                 /*
4455                                  *  Read the current state of the power control register.
4456                                  */
4457                                 if (cs_ac97_get(card->ac97_codec[0], AC97_POWER_CONTROL) & 
4458                                         CS_AC97_POWER_CONTROL_MIXVOFF_ON)
4459                                         break;
4460                         }
4461                         
4462                         /*
4463                          *  Check the status..
4464                          */
4465                         if (!(cs_ac97_get(card->ac97_codec[0], AC97_POWER_CONTROL) & 
4466                                 CS_AC97_POWER_CONTROL_MIXVOFF_ON)) {
4467                                 CS_DBGOUT(CS_ERROR, 1, printk(KERN_WARNING 
4468                                         "cs46xx: powerup MIXVOFF failed\n"));
4469                                 return 1;
4470                         }
4471                 }
4472         }
4473         if(type & CS_POWER_MIXVON) {
4474
4475                 CS_DBGOUT(CS_FUNCTION, 4, 
4476                         printk(KERN_INFO "cs46xx: cs46xx_powerup()+ MIXVON\n"));
4477                 /*
4478                  *  Power up the MIXER (VREF ON) on the AC97 card.  
4479                  */
4480                 tmp = cs_ac97_get(card->ac97_codec[0], AC97_POWER_CONTROL);
4481                 if (!(tmp & CS_AC97_POWER_CONTROL_MIXVON_ON)) {
4482                         if (!muted) {
4483                                 cs_mute(card, CS_TRUE);
4484                                 muted = 1;
4485                         }
4486                         tmp &= ~CS_AC97_POWER_CONTROL_MIXVON;
4487                         cs_ac97_set(card->ac97_codec[0], AC97_POWER_CONTROL, tmp );
4488                         /*
4489                          *  Now, we wait until we sample a ready state.
4490                          */
4491                         for (count = 0; count < 32; count++) {
4492                                 /*
4493                                  *  First, lets wait a short while to let things settle out a
4494                                  *  bit, and to prevent retrying the read too quickly.
4495                                  */
4496                                 udelay(500);
4497
4498                                 /*
4499                                  *  Read the current state of the power control register.
4500                                  */
4501                                 if (cs_ac97_get(card->ac97_codec[0], AC97_POWER_CONTROL) & 
4502                                         CS_AC97_POWER_CONTROL_MIXVON_ON)
4503                                         break;
4504                         }
4505                         
4506                         /*
4507                          *  Check the status..
4508                          */
4509                         if (!(cs_ac97_get(card->ac97_codec[0], AC97_POWER_CONTROL) & 
4510                                 CS_AC97_POWER_CONTROL_MIXVON_ON)) {
4511                                 CS_DBGOUT(CS_ERROR, 1, printk(KERN_WARNING 
4512                                         "cs46xx: powerup MIXVON failed\n"));
4513                                 return 1;
4514                         }
4515                 }
4516         }
4517         if (type & CS_POWER_ADC) {
4518                 /*
4519                  *  Power up the ADC on the AC97 card.  
4520                  */
4521                 CS_DBGOUT(CS_FUNCTION, 4, printk(KERN_INFO "cs46xx: cs46xx_powerup()+ ADC\n"));
4522                 tmp = cs_ac97_get(card->ac97_codec[0], AC97_POWER_CONTROL);
4523                 if (!(tmp & CS_AC97_POWER_CONTROL_ADC_ON)) {
4524                         if (!muted) {
4525                                 cs_mute(card, CS_TRUE);
4526                                 muted = 1;
4527                         }
4528                         tmp &= ~CS_AC97_POWER_CONTROL_ADC;
4529                         cs_ac97_set(card->ac97_codec[0], AC97_POWER_CONTROL, tmp );
4530
4531                         /*
4532                          *  Now, we wait until we sample a ready state.
4533                          */
4534                         for (count = 0; count < 32; count++) {
4535                                 /*
4536                                  *  First, lets wait a short while to let things settle out a
4537                                  *  bit, and to prevent retrying the read too quickly.
4538                                  */
4539                                 udelay(500);
4540
4541                                 /*
4542                                  *  Read the current state of the power control register.
4543                                  */
4544                                 if (cs_ac97_get(card->ac97_codec[0], AC97_POWER_CONTROL) & 
4545                                         CS_AC97_POWER_CONTROL_ADC_ON)
4546                                         break;
4547                         }
4548
4549                         /*
4550                          *  Check the status..
4551                          */
4552                         if (!(cs_ac97_get(card->ac97_codec[0], AC97_POWER_CONTROL) & 
4553                                 CS_AC97_POWER_CONTROL_ADC_ON)) {
4554                                 CS_DBGOUT(CS_ERROR, 1, printk(KERN_WARNING 
4555                                         "cs46xx: powerup ADC failed\n"));
4556                                 return 1;
4557                         }
4558                 }
4559         }
4560         if (type & CS_POWER_DAC) {
4561                 /*
4562                  *  Power up the DAC on the AC97 card.  
4563                  */
4564
4565                 CS_DBGOUT(CS_FUNCTION, 4, 
4566                         printk(KERN_INFO "cs46xx: cs46xx_powerup()+ DAC\n"));
4567                 tmp = cs_ac97_get(card->ac97_codec[0], AC97_POWER_CONTROL);
4568                 if (!(tmp & CS_AC97_POWER_CONTROL_DAC_ON)) {
4569                         if (!muted) {
4570                                 cs_mute(card, CS_TRUE);
4571                                 muted = 1;
4572                         }
4573                         tmp &= ~CS_AC97_POWER_CONTROL_DAC;
4574                         cs_ac97_set(card->ac97_codec[0], AC97_POWER_CONTROL, tmp );
4575                         /*
4576                          *  Now, we wait until we sample a ready state.
4577                          */
4578                         for (count = 0; count < 32; count++) {
4579                                 /*
4580                                  *  First, lets wait a short while to let things settle out a
4581                                  *  bit, and to prevent retrying the read too quickly.
4582                                  */
4583                                 udelay(500);
4584
4585                                 /*
4586                                  *  Read the current state of the power control register.
4587                                  */
4588                                 if (cs_ac97_get(card->ac97_codec[0], AC97_POWER_CONTROL) & 
4589                                         CS_AC97_POWER_CONTROL_DAC_ON)
4590                                         break;
4591                         }
4592                         
4593                         /*
4594                          *  Check the status..
4595                          */
4596                         if (!(cs_ac97_get(card->ac97_codec[0], AC97_POWER_CONTROL) & 
4597                                 CS_AC97_POWER_CONTROL_DAC_ON)) {
4598                                 CS_DBGOUT(CS_ERROR, 1, printk(KERN_WARNING 
4599                                         "cs46xx: powerup DAC failed\n"));
4600                                 return 1;
4601                         }
4602                 }
4603         }
4604         tmp = cs_ac97_get(card->ac97_codec[0], AC97_POWER_CONTROL);
4605         if (muted)
4606                 cs_mute(card, CS_FALSE);
4607         CS_DBGOUT(CS_FUNCTION, 4, printk(KERN_INFO 
4608                 "cs46xx: cs46xx_powerup()- 0 tmp=0x%x\n",tmp));
4609         return 0;
4610 }
4611
4612 static void cs461x_proc_start(struct cs_card *card)
4613 {
4614         int cnt;
4615
4616         /*
4617          *  Set the frame timer to reflect the number of cycles per frame.
4618          */
4619         cs461x_poke(card, BA1_FRMT, 0xadf);
4620         /*
4621          *  Turn on the run, run at frame, and DMA enable bits in the local copy of
4622          *  the SP control register.
4623          */
4624         cs461x_poke(card, BA1_SPCR, SPCR_RUN | SPCR_RUNFR | SPCR_DRQEN);
4625         /*
4626          *  Wait until the run at frame bit resets itself in the SP control
4627          *  register.
4628          */
4629         for (cnt = 0; cnt < 25; cnt++) {
4630                 udelay(50);
4631                 if (!(cs461x_peek(card, BA1_SPCR) & SPCR_RUNFR))
4632                         break;
4633         }
4634
4635         if (cs461x_peek(card, BA1_SPCR) & SPCR_RUNFR)
4636                 printk(KERN_WARNING "cs46xx: SPCR_RUNFR never reset\n");
4637 }
4638
4639 static void cs461x_proc_stop(struct cs_card *card)
4640 {
4641         /*
4642          *  Turn off the run, run at frame, and DMA enable bits in the local copy of
4643          *  the SP control register.
4644          */
4645         cs461x_poke(card, BA1_SPCR, 0);
4646 }
4647
4648 static int cs_hardware_init(struct cs_card *card)
4649 {
4650         unsigned long end_time;
4651         unsigned int tmp,count;
4652         
4653         CS_DBGOUT(CS_FUNCTION | CS_INIT, 2, printk(KERN_INFO 
4654                 "cs46xx: cs_hardware_init()+\n") );
4655         /* 
4656          *  First, blast the clock control register to zero so that the PLL starts
4657          *  out in a known state, and blast the master serial port control register
4658          *  to zero so that the serial ports also start out in a known state.
4659          */
4660         cs461x_pokeBA0(card, BA0_CLKCR1, 0);
4661         cs461x_pokeBA0(card, BA0_SERMC1, 0);
4662
4663         /*
4664          *  If we are in AC97 mode, then we must set the part to a host controlled
4665          *  AC-link.  Otherwise, we won't be able to bring up the link.
4666          */        
4667         cs461x_pokeBA0(card, BA0_SERACC, SERACC_HSP | SERACC_CODEC_TYPE_1_03);  /* 1.03 card */
4668         /* cs461x_pokeBA0(card, BA0_SERACC, SERACC_HSP | SERACC_CODEC_TYPE_2_0); */ /* 2.00 card */
4669
4670         /*
4671          *  Drive the ARST# pin low for a minimum of 1uS (as defined in the AC97
4672          *  spec) and then drive it high.  This is done for non AC97 modes since
4673          *  there might be logic external to the CS461x that uses the ARST# line
4674          *  for a reset.
4675          */
4676         cs461x_pokeBA0(card, BA0_ACCTL, 1);
4677         udelay(50);
4678         cs461x_pokeBA0(card, BA0_ACCTL, 0);
4679         udelay(50);
4680         cs461x_pokeBA0(card, BA0_ACCTL, ACCTL_RSTN);
4681
4682         /*
4683          *  The first thing we do here is to enable sync generation.  As soon
4684          *  as we start receiving bit clock, we'll start producing the SYNC
4685          *  signal.
4686          */
4687         cs461x_pokeBA0(card, BA0_ACCTL, ACCTL_ESYN | ACCTL_RSTN);
4688
4689         /*
4690          *  Now wait for a short while to allow the AC97 part to start
4691          *  generating bit clock (so we don't try to start the PLL without an
4692          *  input clock).
4693          */
4694         mdelay(5 * cs_laptop_wait);             /* 1 should be enough ?? (and pigs might fly) */
4695
4696         /*
4697          *  Set the serial port timing configuration, so that
4698          *  the clock control circuit gets its clock from the correct place.
4699          */
4700         cs461x_pokeBA0(card, BA0_SERMC1, SERMC1_PTC_AC97);
4701
4702         /*
4703         * The part seems to not be ready for a while after a resume.
4704         * so, if we are resuming, then wait for 700 mils.  Note that 600 mils
4705         * is not enough for some platforms! tested on an IBM Thinkpads and 
4706         * reference cards.
4707         */
4708         if (!(card->pm.flags & CS46XX_PM_IDLE))
4709                 mdelay(initdelay);
4710         /*
4711          *  Write the selected clock control setup to the hardware.  Do not turn on
4712          *  SWCE yet (if requested), so that the devices clocked by the output of
4713          *  PLL are not clocked until the PLL is stable.
4714          */
4715         cs461x_pokeBA0(card, BA0_PLLCC, PLLCC_LPF_1050_2780_KHZ | PLLCC_CDR_73_104_MHZ);
4716         cs461x_pokeBA0(card, BA0_PLLM, 0x3a);
4717         cs461x_pokeBA0(card, BA0_CLKCR2, CLKCR2_PDIVS_8);
4718
4719         /*
4720          *  Power up the PLL.
4721          */
4722         cs461x_pokeBA0(card, BA0_CLKCR1, CLKCR1_PLLP);
4723
4724         /*
4725          *  Wait until the PLL has stabilized.
4726          */
4727         mdelay(5 * cs_laptop_wait);             /* Again 1 should be enough ?? */
4728
4729         /*
4730          *  Turn on clocking of the core so that we can setup the serial ports.
4731          */
4732         tmp = cs461x_peekBA0(card, BA0_CLKCR1) | CLKCR1_SWCE;
4733         cs461x_pokeBA0(card, BA0_CLKCR1, tmp);
4734
4735         /*
4736          *  Fill the serial port FIFOs with silence.
4737          */
4738         cs461x_clear_serial_FIFOs(card,CS_TYPE_DAC | CS_TYPE_ADC);
4739
4740         /*
4741          *  Set the serial port FIFO pointer to the first sample in the FIFO.
4742          */
4743         /* cs461x_pokeBA0(card, BA0_SERBSP, 0); */
4744
4745         /*
4746          *  Write the serial port configuration to the part.  The master
4747          *  enable bit is not set until all other values have been written.
4748          */
4749         cs461x_pokeBA0(card, BA0_SERC1, SERC1_SO1F_AC97 | SERC1_SO1EN);
4750         cs461x_pokeBA0(card, BA0_SERC2, SERC2_SI1F_AC97 | SERC1_SO1EN);
4751         cs461x_pokeBA0(card, BA0_SERMC1, SERMC1_PTC_AC97 | SERMC1_MSPE);
4752
4753
4754         mdelay(5 * cs_laptop_wait);             /* Shouldnt be needed ?? */
4755         
4756 /*
4757 * If we are resuming under 2.2.x then we cannot schedule a timeout,
4758 * so just spin the CPU.
4759 */
4760         if (card->pm.flags & CS46XX_PM_IDLE) {
4761         /*
4762          * Wait for the card ready signal from the AC97 card.
4763          */
4764                 end_time = jiffies + 3 * (HZ >> 2);
4765                 do {
4766                 /*
4767                  *  Read the AC97 status register to see if we've seen a CODEC READY
4768                  *  signal from the AC97 card.
4769                  */
4770                         if (cs461x_peekBA0(card, BA0_ACSTS) & ACSTS_CRDY)
4771                                 break;
4772                         current->state = TASK_UNINTERRUPTIBLE;
4773                         schedule_timeout(1);
4774                 } while (time_before(jiffies, end_time));
4775         } else {
4776                 for (count = 0; count < 100; count++) {
4777                 // First, we want to wait for a short time.
4778                         udelay(25 * cs_laptop_wait);
4779
4780                         if (cs461x_peekBA0(card, BA0_ACSTS) & ACSTS_CRDY)
4781                                 break;
4782                 }
4783         }
4784
4785         /*
4786          *  Make sure CODEC is READY.
4787          */
4788         if (!(cs461x_peekBA0(card, BA0_ACSTS) & ACSTS_CRDY)) {
4789                 CS_DBGOUT(CS_ERROR | CS_INIT, 1, printk(KERN_WARNING  
4790                         "cs46xx: create - never read card ready from AC'97\n"));
4791                 CS_DBGOUT(CS_ERROR | CS_INIT, 1, printk(KERN_WARNING  
4792                         "cs46xx: probably not a bug, try using the CS4232 driver,\n"));
4793                 CS_DBGOUT(CS_ERROR | CS_INIT, 1, printk(KERN_WARNING  
4794                         "cs46xx: or turn off any automatic Power Management support in the BIOS.\n"));
4795                 return -EIO;
4796         }
4797
4798         /*
4799          *  Assert the vaid frame signal so that we can start sending commands
4800          *  to the AC97 card.
4801          */
4802         cs461x_pokeBA0(card, BA0_ACCTL, ACCTL_VFRM | ACCTL_ESYN | ACCTL_RSTN);
4803
4804         if (card->pm.flags & CS46XX_PM_IDLE) {
4805         /*
4806          *  Wait until we've sampled input slots 3 and 4 as valid, meaning that
4807          *  the card is pumping ADC data across the AC-link.
4808          */
4809                 end_time = jiffies + 3 * (HZ >> 2);
4810                 do {
4811                         /*
4812                          *  Read the input slot valid register and see if input slots 3 and
4813                          *  4 are valid yet.
4814                          */
4815                         if ((cs461x_peekBA0(card, BA0_ACISV) & (ACISV_ISV3 | ACISV_ISV4)) == (ACISV_ISV3 | ACISV_ISV4))
4816                                 break;
4817                         current->state = TASK_UNINTERRUPTIBLE;
4818                         schedule_timeout(1);
4819                 } while (time_before(jiffies, end_time));
4820         } else {
4821                 for (count = 0; count < 100; count++) {
4822                 // First, we want to wait for a short time.
4823                         udelay(25 * cs_laptop_wait);
4824
4825                         if ((cs461x_peekBA0(card, BA0_ACISV) & (ACISV_ISV3 | ACISV_ISV4)) == (ACISV_ISV3 | ACISV_ISV4))
4826                                 break;
4827                 }
4828         }
4829         /*
4830          *  Make sure input slots 3 and 4 are valid.  If not, then return
4831          *  an error.
4832          */
4833         if ((cs461x_peekBA0(card, BA0_ACISV) & (ACISV_ISV3 | ACISV_ISV4)) != (ACISV_ISV3 | ACISV_ISV4)) {
4834                 printk(KERN_WARNING "cs46xx: create - never read ISV3 & ISV4 from AC'97\n");
4835                 return -EIO;
4836         }
4837
4838         /*
4839          *  Now, assert valid frame and the slot 3 and 4 valid bits.  This will
4840          *  commense the transfer of digital audio data to the AC97 card.
4841          */
4842         cs461x_pokeBA0(card, BA0_ACOSV, ACOSV_SLV3 | ACOSV_SLV4);
4843
4844         /*
4845          *  Turn off the Processor by turning off the software clock enable flag in 
4846          *  the clock control register.
4847          */
4848         /* tmp = cs461x_peekBA0(card, BA0_CLKCR1) & ~CLKCR1_SWCE; */
4849         /* cs461x_pokeBA0(card, BA0_CLKCR1, tmp); */
4850
4851         /*
4852          *  Reset the processor.
4853          */
4854         cs461x_reset(card);
4855
4856         /*
4857          *  Download the image to the processor.
4858          */
4859         
4860         cs461x_download_image(card);
4861
4862         /*
4863          *  Stop playback DMA.
4864          */
4865         tmp = cs461x_peek(card, BA1_PCTL);
4866         card->pctl = tmp & 0xffff0000;
4867         cs461x_poke(card, BA1_PCTL, tmp & 0x0000ffff);
4868
4869         /*
4870          *  Stop capture DMA.
4871          */
4872         tmp = cs461x_peek(card, BA1_CCTL);
4873         card->cctl = tmp & 0x0000ffff;
4874         cs461x_poke(card, BA1_CCTL, tmp & 0xffff0000);
4875
4876         /* initialize AC97 codec and register /dev/mixer */
4877         if (card->pm.flags & CS46XX_PM_IDLE) {
4878                 if (cs_ac97_init(card) <= 0) {
4879                         CS_DBGOUT(CS_ERROR | CS_INIT, 1, printk(KERN_INFO 
4880                                 "cs46xx: cs_ac97_init() failure\n"));
4881                         return -EIO;
4882                 }
4883         } else {
4884                 cs46xx_ac97_resume(card);
4885         }
4886         
4887         cs461x_proc_start(card);
4888
4889         /*
4890          *  Enable interrupts on the part.
4891          */
4892         cs461x_pokeBA0(card, BA0_HICR, HICR_IEV | HICR_CHGM);
4893
4894         tmp = cs461x_peek(card, BA1_PFIE);
4895         tmp &= ~0x0000f03f;
4896         cs461x_poke(card, BA1_PFIE, tmp);       /* playback interrupt enable */
4897
4898         tmp = cs461x_peek(card, BA1_CIE);
4899         tmp &= ~0x0000003f;
4900         tmp |=  0x00000001;
4901         cs461x_poke(card, BA1_CIE, tmp);        /* capture interrupt enable */  
4902
4903         /*
4904          *  If IDLE then Power down the part.  We will power components up 
4905          *  when we need them.  
4906          */
4907         if (card->pm.flags & CS46XX_PM_IDLE) {
4908                 if (!cs_powerdown) {
4909                         if ((tmp = cs46xx_powerup(card, CS_POWER_DAC | CS_POWER_ADC |
4910                                         CS_POWER_MIXVON))) {
4911                                 CS_DBGOUT(CS_ERROR | CS_INIT, 1, printk(KERN_INFO 
4912                                         "cs46xx: cs461x_powerup() failure (0x%x)\n",tmp) );
4913                                 return -EIO;
4914                         }
4915                 } else {
4916                         if ((tmp = cs461x_powerdown(card, CS_POWER_DAC | CS_POWER_ADC |
4917                                         CS_POWER_MIXVON, CS_FALSE))) {
4918                                 CS_DBGOUT(CS_ERROR | CS_INIT, 1, printk(KERN_INFO 
4919                                         "cs46xx: cs461x_powerdown() failure (0x%x)\n",tmp) );
4920                                 return -EIO;
4921                         }
4922                 }
4923         }
4924         CS_DBGOUT(CS_FUNCTION | CS_INIT, 2, printk(KERN_INFO 
4925                 "cs46xx: cs_hardware_init()- 0\n"));
4926         return 0;
4927 }
4928
4929 /* install the driver, we do not allocate hardware channel nor DMA buffer now, they are defered 
4930    until "ACCESS" time (in prog_dmabuf called by open/read/write/ioctl/mmap) */
4931    
4932 /*
4933  *      Card subid table
4934  */
4935  
4936 struct cs_card_type
4937 {
4938         u16 vendor;
4939         u16 id;
4940         char *name;
4941         void (*amp)(struct cs_card *, int);
4942         void (*amp_init)(struct cs_card *);
4943         void (*active)(struct cs_card *, int);
4944 };
4945
4946 static struct cs_card_type cards[] = {
4947         {
4948                 .vendor = 0x1489,
4949                 .id     = 0x7001,
4950                 .name   = "Genius Soundmaker 128 value",
4951                 .amp    = amp_none,
4952         },
4953         {
4954                 .vendor = 0x5053,
4955                 .id     = 0x3357,
4956                 .name   = "Voyetra",
4957                 .amp    = amp_voyetra,
4958         },
4959         {
4960                 .vendor = 0x1071,
4961                 .id     = 0x6003,
4962                 .name   = "Mitac MI6020/21",
4963                 .amp    = amp_voyetra,
4964         },
4965         {
4966                 .vendor = 0x14AF,
4967                 .id     = 0x0050,
4968                 .name   = "Hercules Game Theatre XP",
4969                 .amp    = amp_hercules,
4970         },
4971         {
4972                 .vendor = 0x1681,
4973                 .id     = 0x0050,
4974                 .name   = "Hercules Game Theatre XP",
4975                 .amp    = amp_hercules,
4976         },
4977         {
4978                 .vendor = 0x1681,
4979                 .id     = 0x0051,
4980                 .name   = "Hercules Game Theatre XP",
4981                 .amp    = amp_hercules,
4982         },
4983         {
4984                 .vendor = 0x1681,
4985                 .id     = 0x0052,
4986                 .name   = "Hercules Game Theatre XP",
4987                 .amp    = amp_hercules,
4988         },
4989         {
4990                 .vendor = 0x1681,
4991                 .id     = 0x0053,
4992                 .name   = "Hercules Game Theatre XP",
4993                 .amp    = amp_hercules,
4994         },
4995         {
4996                 .vendor = 0x1681,
4997                 .id     = 0x0054,
4998                 .name   = "Hercules Game Theatre XP",
4999                 .amp    = amp_hercules,
5000         },
5001         {
5002                 .vendor = 0x1681,
5003                 .id     = 0xa010,
5004                 .name   = "Hercules Fortissimo II",
5005                 .amp    = amp_none,
5006         },
5007         /* Not sure if the 570 needs the clkrun hack */
5008         {
5009                 .vendor = PCI_VENDOR_ID_IBM,
5010                 .id     = 0x0132,
5011                 .name   = "Thinkpad 570",
5012                 .amp    = amp_none,
5013                 .active = clkrun_hack,
5014         },
5015         {
5016                 .vendor = PCI_VENDOR_ID_IBM,
5017                 .id     = 0x0153,
5018                 .name   = "Thinkpad 600X/A20/T20",
5019                 .amp    = amp_none,
5020                 .active = clkrun_hack,
5021         },
5022         {
5023                 .vendor = PCI_VENDOR_ID_IBM,
5024                 .id     = 0x1010,
5025                 .name   = "Thinkpad 600E (unsupported)",
5026         },
5027         {
5028                 .name   = "Card without SSID set",
5029         },
5030         { 0, },
5031 };
5032
5033 MODULE_AUTHOR("Alan Cox <alan@redhat.com>, Jaroslav Kysela, <pcaudio@crystal.cirrus.com>");
5034 MODULE_DESCRIPTION("Crystal SoundFusion Audio Support");
5035 MODULE_LICENSE("GPL");
5036
5037 static const char cs46xx_banner[] = KERN_INFO "Crystal 4280/46xx + AC97 Audio, version " CS46XX_MAJOR_VERSION "." CS46XX_MINOR_VERSION "." CS46XX_ARCH ", " __TIME__ " " __DATE__ "\n";
5038 static const char fndmsg[] = KERN_INFO "cs46xx: Found %d audio device(s).\n";
5039
5040 static int __devinit cs46xx_probe(struct pci_dev *pci_dev,
5041                                   const struct pci_device_id *pciid)
5042 {
5043         int i, j;
5044         u16 ss_card, ss_vendor;
5045         struct cs_card *card;
5046         dma_addr_t dma_mask;
5047         struct cs_card_type *cp = &cards[0];
5048
5049         CS_DBGOUT(CS_FUNCTION | CS_INIT, 2,
5050                   printk(KERN_INFO "cs46xx: probe()+\n"));
5051
5052         dma_mask = 0xffffffff;  /* this enables playback and recording */
5053         if (pci_enable_device(pci_dev)) {
5054                 CS_DBGOUT(CS_INIT | CS_ERROR, 1, printk(KERN_ERR
5055                          "cs46xx: pci_enable_device() failed\n"));
5056                 return -1;
5057         }
5058         if (!RSRCISMEMORYREGION(pci_dev, 0) ||
5059             !RSRCISMEMORYREGION(pci_dev, 1)) {
5060                 CS_DBGOUT(CS_ERROR, 1, printk(KERN_ERR
5061                          "cs46xx: probe()- Memory region not assigned\n"));
5062                 return -1;
5063         }
5064         if (pci_dev->irq == 0) {
5065                 CS_DBGOUT(CS_ERROR, 1, printk(KERN_ERR
5066                          "cs46xx: probe() IRQ not assigned\n"));
5067                 return -1;
5068         }
5069         if (!pci_dma_supported(pci_dev, 0xffffffff)) {
5070                 CS_DBGOUT(CS_ERROR, 1, printk(KERN_ERR
5071                       "cs46xx: probe() architecture does not support 32bit PCI busmaster DMA\n"));
5072                 return -1;
5073         }
5074         pci_read_config_word(pci_dev, PCI_SUBSYSTEM_VENDOR_ID, &ss_vendor);
5075         pci_read_config_word(pci_dev, PCI_SUBSYSTEM_ID, &ss_card);
5076
5077         if ((card = kmalloc(sizeof(struct cs_card), GFP_KERNEL)) == NULL) {
5078                 printk(KERN_ERR "cs46xx: out of memory\n");
5079                 return -ENOMEM;
5080         }
5081         memset(card, 0, sizeof(*card));
5082         card->ba0_addr = RSRCADDRESS(pci_dev, 0);
5083         card->ba1_addr = RSRCADDRESS(pci_dev, 1);
5084         card->pci_dev = pci_dev;
5085         card->irq = pci_dev->irq;
5086         card->magic = CS_CARD_MAGIC;
5087         spin_lock_init(&card->lock);
5088         spin_lock_init(&card->ac97_lock);
5089
5090         pci_set_master(pci_dev);
5091
5092         printk(cs46xx_banner);
5093         printk(KERN_INFO "cs46xx: Card found at 0x%08lx and 0x%08lx, IRQ %d\n",
5094                card->ba0_addr, card->ba1_addr, card->irq);
5095
5096         card->alloc_pcm_channel = cs_alloc_pcm_channel;
5097         card->alloc_rec_pcm_channel = cs_alloc_rec_pcm_channel;
5098         card->free_pcm_channel = cs_free_pcm_channel;
5099         card->amplifier_ctrl = amp_none;
5100         card->active_ctrl = amp_none;
5101
5102         while (cp->name)
5103         {
5104                 if (cp->vendor == ss_vendor && cp->id == ss_card) {
5105                         card->amplifier_ctrl = cp->amp;
5106                         if (cp->active)
5107                                 card->active_ctrl = cp->active;
5108                         if (cp->amp_init)
5109                                 card->amp_init = cp->amp_init;
5110                         break;
5111                 }
5112                 cp++;
5113         }
5114         if (cp->name == NULL) {
5115                 printk(KERN_INFO "cs46xx: Unknown card (%04X:%04X) at 0x%08lx/0x%08lx, IRQ %d\n",
5116                         ss_vendor, ss_card, card->ba0_addr, card->ba1_addr,  card->irq);
5117         } else {
5118                 printk(KERN_INFO "cs46xx: %s (%04X:%04X) at 0x%08lx/0x%08lx, IRQ %d\n",
5119                         cp->name, ss_vendor, ss_card, card->ba0_addr, card->ba1_addr, card->irq);
5120         }
5121         
5122         if (card->amplifier_ctrl == NULL) {
5123                 card->amplifier_ctrl = amp_none;
5124                 card->active_ctrl = clkrun_hack;
5125         }               
5126
5127         if (external_amp == 1) {
5128                 printk(KERN_INFO "cs46xx: Crystal EAPD support forced on.\n");
5129                 card->amplifier_ctrl = amp_voyetra;
5130         }
5131
5132         if (thinkpad == 1) {
5133                 printk(KERN_INFO "cs46xx: Activating CLKRUN hack for Thinkpad.\n");
5134                 card->active_ctrl = clkrun_hack;
5135         }
5136 /*
5137 * The thinkpads don't work well without runtime updating on their kernel 
5138 * delay values (or any laptop with variable CPU speeds really).
5139 * so, just to be safe set the init delay to 2100.  Eliminates
5140 * failures on T21 Thinkpads.  remove this code when the udelay
5141 * and mdelay kernel code is replaced by a pm timer, or the delays
5142 * work well for battery and/or AC power both.
5143 */
5144         if (card->active_ctrl == clkrun_hack) {
5145                 initdelay = 2100;
5146                 cs_laptop_wait = 5;
5147         }
5148         if ((card->active_ctrl == clkrun_hack) && !(powerdown == 1)) {
5149 /*
5150 * for some currently unknown reason, powering down the DAC and ADC component
5151 * blocks on thinkpads causes some funky behavior... distoorrrtion and ac97 
5152 * codec access problems.  probably the serial clock becomes unsynced. 
5153 * added code to sync the chips back up, but only helped about 70% the time.
5154 */
5155                 cs_powerdown = 0;
5156         }
5157         if (powerdown == 0)
5158                 cs_powerdown = 0;
5159         card->active_ctrl(card, 1);
5160
5161         /* claim our iospace and irq */
5162         
5163         card->ba0 = ioremap_nocache(card->ba0_addr, CS461X_BA0_SIZE);
5164         card->ba1.name.data0 = ioremap_nocache(card->ba1_addr + BA1_SP_DMEM0, CS461X_BA1_DATA0_SIZE);
5165         card->ba1.name.data1 = ioremap_nocache(card->ba1_addr + BA1_SP_DMEM1, CS461X_BA1_DATA1_SIZE);
5166         card->ba1.name.pmem = ioremap_nocache(card->ba1_addr + BA1_SP_PMEM, CS461X_BA1_PRG_SIZE);
5167         card->ba1.name.reg = ioremap_nocache(card->ba1_addr + BA1_SP_REG, CS461X_BA1_REG_SIZE);
5168         
5169         CS_DBGOUT(CS_INIT, 4, printk(KERN_INFO 
5170                 "cs46xx: card=%p card->ba0=%p\n",card,card->ba0) );
5171         CS_DBGOUT(CS_INIT, 4, printk(KERN_INFO 
5172                 "cs46xx: card->ba1=%p %p %p %p\n",
5173                         card->ba1.name.data0,
5174                         card->ba1.name.data1,
5175                         card->ba1.name.pmem,
5176                         card->ba1.name.reg) );
5177
5178         if (card->ba0 == 0 || card->ba1.name.data0 == 0 ||
5179                 card->ba1.name.data1 == 0 || card->ba1.name.pmem == 0 ||
5180                 card->ba1.name.reg == 0)
5181                 goto fail2;
5182                 
5183         if (request_irq(card->irq, &cs_interrupt, IRQF_SHARED, "cs46xx", card)) {
5184                 printk(KERN_ERR "cs46xx: unable to allocate irq %d\n", card->irq);
5185                 goto fail2;
5186         }
5187         /* register /dev/dsp */
5188         if ((card->dev_audio = register_sound_dsp(&cs461x_fops, -1)) < 0) {
5189                 printk(KERN_ERR "cs46xx: unable to register dsp\n");
5190                 goto fail;
5191         }
5192
5193         /* register /dev/midi */
5194         if ((card->dev_midi = register_sound_midi(&cs_midi_fops, -1)) < 0)
5195                 printk(KERN_ERR "cs46xx: unable to register midi\n");
5196                 
5197         card->pm.flags |= CS46XX_PM_IDLE;
5198         for (i = 0; i < 5; i++) {
5199                 if (cs_hardware_init(card) != 0) {
5200                         CS_DBGOUT(CS_ERROR, 4, printk(
5201                                 "cs46xx: ERROR in cs_hardware_init()... retrying\n"));
5202                         for (j = 0; j < NR_AC97; j++)
5203                                 if (card->ac97_codec[j] != NULL) {
5204                                         unregister_sound_mixer(card->ac97_codec[j]->dev_mixer);
5205                                         ac97_release_codec(card->ac97_codec[j]);
5206                                 }
5207                         mdelay(10 * cs_laptop_wait);
5208                         continue;
5209                 }
5210                 break;
5211         }
5212         if(i >= 4) {
5213                 CS_DBGOUT(CS_PM | CS_ERROR, 1, printk(
5214                         "cs46xx: cs46xx_probe()- cs_hardware_init() failed, retried %d times.\n",i));
5215                 unregister_sound_dsp(card->dev_audio);
5216                 if (card->dev_midi)
5217                         unregister_sound_midi(card->dev_midi);
5218                 goto fail;
5219         }
5220
5221         init_waitqueue_head(&card->midi.open_wait);
5222         mutex_init(&card->midi.open_mutex);
5223         init_waitqueue_head(&card->midi.iwait);
5224         init_waitqueue_head(&card->midi.owait);
5225         cs461x_pokeBA0(card, BA0_MIDCR, MIDCR_MRST);   
5226         cs461x_pokeBA0(card, BA0_MIDCR, 0);   
5227
5228         /* 
5229         * Check if we have to init the amplifier, but probably already done
5230         * since the CD logic in the ac97 init code will turn on the ext amp.
5231         */
5232         if (cp->amp_init)
5233                 cp->amp_init(card);
5234         card->active_ctrl(card, -1);
5235
5236         PCI_SET_DRIVER_DATA(pci_dev, card);
5237         PCI_SET_DMA_MASK(pci_dev, dma_mask);
5238         list_add(&card->list, &cs46xx_devs);
5239
5240         CS_DBGOUT(CS_PM, 9, printk(KERN_INFO "cs46xx: pm.flags=0x%x card=%p\n",
5241                 (unsigned)card->pm.flags,card));
5242
5243         CS_DBGOUT(CS_INIT | CS_FUNCTION, 2, printk(KERN_INFO
5244                 "cs46xx: probe()- device allocated successfully\n"));
5245         return 0;
5246
5247 fail:
5248         free_irq(card->irq, card);
5249 fail2:
5250         if (card->ba0)
5251                 iounmap(card->ba0);
5252         if (card->ba1.name.data0)
5253                 iounmap(card->ba1.name.data0);
5254         if (card->ba1.name.data1)
5255                 iounmap(card->ba1.name.data1);
5256         if (card->ba1.name.pmem)
5257                 iounmap(card->ba1.name.pmem);
5258         if (card->ba1.name.reg)
5259                 iounmap(card->ba1.name.reg);
5260         kfree(card);
5261         CS_DBGOUT(CS_INIT | CS_ERROR, 1, printk(KERN_INFO
5262                 "cs46xx: probe()- no device allocated\n"));
5263         return -ENODEV;
5264 } // probe_cs46xx
5265
5266 // --------------------------------------------------------------------- 
5267
5268 static void __devexit cs46xx_remove(struct pci_dev *pci_dev)
5269 {
5270         struct cs_card *card = PCI_GET_DRIVER_DATA(pci_dev);
5271         int i;
5272         unsigned int tmp;
5273         
5274         CS_DBGOUT(CS_INIT | CS_FUNCTION, 2, printk(KERN_INFO
5275                  "cs46xx: cs46xx_remove()+\n"));
5276
5277         card->active_ctrl(card,1);
5278         
5279         tmp = cs461x_peek(card, BA1_PFIE);
5280         tmp &= ~0x0000f03f;
5281         tmp |=  0x00000010;
5282         cs461x_poke(card, BA1_PFIE, tmp);       /* playback interrupt disable */
5283
5284         tmp = cs461x_peek(card, BA1_CIE);
5285         tmp &= ~0x0000003f;
5286         tmp |=  0x00000011;
5287         cs461x_poke(card, BA1_CIE, tmp);        /* capture interrupt disable */
5288
5289         /*
5290          *  Stop playback DMA.
5291          */
5292         tmp = cs461x_peek(card, BA1_PCTL);
5293         cs461x_poke(card, BA1_PCTL, tmp & 0x0000ffff);
5294
5295         /*
5296          *  Stop capture DMA.
5297          */
5298         tmp = cs461x_peek(card, BA1_CCTL);
5299         cs461x_poke(card, BA1_CCTL, tmp & 0xffff0000);
5300
5301         /*
5302          *  Reset the processor.
5303          */
5304         cs461x_reset(card);
5305
5306         cs461x_proc_stop(card);
5307
5308         /*
5309          *  Power down the DAC and ADC.  We will power them up (if) when we need
5310          *  them.
5311          */
5312         if ((tmp = cs461x_powerdown(card, CS_POWER_DAC | CS_POWER_ADC |
5313                         CS_POWER_MIXVON, CS_TRUE))) {
5314                 CS_DBGOUT(CS_ERROR | CS_INIT, 1, printk(KERN_INFO 
5315                         "cs46xx: cs461x_powerdown() failure (0x%x)\n",tmp) );
5316         }
5317
5318         /*
5319          *  Power down the PLL.
5320          */
5321         cs461x_pokeBA0(card, BA0_CLKCR1, 0);
5322
5323         /*
5324          *  Turn off the Processor by turning off the software clock enable flag in 
5325          *  the clock control register.
5326          */
5327         tmp = cs461x_peekBA0(card, BA0_CLKCR1) & ~CLKCR1_SWCE;
5328         cs461x_pokeBA0(card, BA0_CLKCR1, tmp);
5329
5330         card->active_ctrl(card,-1);
5331
5332         /* free hardware resources */
5333         free_irq(card->irq, card);
5334         iounmap(card->ba0);
5335         iounmap(card->ba1.name.data0);
5336         iounmap(card->ba1.name.data1);
5337         iounmap(card->ba1.name.pmem);
5338         iounmap(card->ba1.name.reg);
5339         
5340         /* unregister audio devices */
5341         for (i = 0; i < NR_AC97; i++)
5342                 if (card->ac97_codec[i] != NULL) {
5343                         unregister_sound_mixer(card->ac97_codec[i]->dev_mixer);
5344                         ac97_release_codec(card->ac97_codec[i]);
5345                 }
5346         unregister_sound_dsp(card->dev_audio);
5347         if (card->dev_midi)
5348                 unregister_sound_midi(card->dev_midi);
5349         list_del(&card->list);
5350         kfree(card);
5351         PCI_SET_DRIVER_DATA(pci_dev,NULL);
5352
5353         CS_DBGOUT(CS_INIT | CS_FUNCTION, 2, printk(KERN_INFO
5354                  "cs46xx: cs46xx_remove()-: remove successful\n"));
5355 }
5356
5357 enum {
5358         CS46XX_4610 = 0,
5359         CS46XX_4612,    /* same as 4630 */
5360         CS46XX_4615,    /* same as 4624 */
5361 };
5362
5363 static struct pci_device_id cs46xx_pci_tbl[] = {
5364         {
5365                 .vendor      = PCI_VENDOR_ID_CIRRUS,
5366                 .device      = PCI_DEVICE_ID_CIRRUS_4610,
5367                 .subvendor   = PCI_ANY_ID,
5368                 .subdevice   = PCI_ANY_ID,
5369                 .driver_data = CS46XX_4610,
5370         },
5371         {
5372                 .vendor      = PCI_VENDOR_ID_CIRRUS,
5373                 .device      = PCI_DEVICE_ID_CIRRUS_4612,
5374                 .subvendor   = PCI_ANY_ID,
5375                 .subdevice   = PCI_ANY_ID,
5376                 .driver_data = CS46XX_4612,
5377         },
5378         {
5379                 .vendor      = PCI_VENDOR_ID_CIRRUS,
5380                 .device      = PCI_DEVICE_ID_CIRRUS_4615,
5381                 .subvendor   = PCI_ANY_ID,
5382                 .subdevice   = PCI_ANY_ID,
5383                 .driver_data = CS46XX_4615,
5384         },
5385         { 0, },
5386 };
5387
5388 MODULE_DEVICE_TABLE(pci, cs46xx_pci_tbl);
5389
5390 static struct pci_driver cs46xx_pci_driver = {
5391         .name     = "cs46xx",
5392         .id_table = cs46xx_pci_tbl,
5393         .probe    = cs46xx_probe,
5394         .remove   = __devexit_p(cs46xx_remove),
5395 #ifdef CONFIG_PM
5396         .suspend  = cs46xx_suspend_tbl,
5397         .resume   = cs46xx_resume_tbl,
5398 #endif
5399 };
5400
5401 static int __init cs46xx_init_module(void)
5402 {
5403         int rtn = 0;
5404         CS_DBGOUT(CS_INIT | CS_FUNCTION, 2, printk(KERN_INFO 
5405                 "cs46xx: cs46xx_init_module()+ \n"));
5406         rtn = pci_register_driver(&cs46xx_pci_driver);
5407
5408         if (rtn == -ENODEV) {
5409                 CS_DBGOUT(CS_ERROR | CS_INIT, 1, printk( 
5410                         "cs46xx: Unable to detect valid cs46xx device\n"));
5411         }
5412
5413         CS_DBGOUT(CS_INIT | CS_FUNCTION, 2,
5414                   printk(KERN_INFO "cs46xx: cs46xx_init_module()- (%d)\n",rtn));
5415         return rtn;
5416 }
5417
5418 static void __exit cs46xx_cleanup_module(void)
5419 {
5420         pci_unregister_driver(&cs46xx_pci_driver);
5421         CS_DBGOUT(CS_INIT | CS_FUNCTION, 2,
5422                   printk(KERN_INFO "cs46xx: cleanup_cs46xx() finished\n"));
5423 }
5424
5425 module_init(cs46xx_init_module);
5426 module_exit(cs46xx_cleanup_module);
5427
5428 #ifdef CONFIG_PM
5429 static int cs46xx_suspend_tbl(struct pci_dev *pcidev, pm_message_t state)
5430 {
5431         struct cs_card *s = PCI_GET_DRIVER_DATA(pcidev);
5432         CS_DBGOUT(CS_PM | CS_FUNCTION, 2, 
5433                 printk(KERN_INFO "cs46xx: cs46xx_suspend_tbl request\n"));
5434         cs46xx_suspend(s, state);
5435         return 0;
5436 }
5437
5438 static int cs46xx_resume_tbl(struct pci_dev *pcidev)
5439 {
5440         struct cs_card *s = PCI_GET_DRIVER_DATA(pcidev);
5441         CS_DBGOUT(CS_PM | CS_FUNCTION, 2, 
5442                 printk(KERN_INFO "cs46xx: cs46xx_resume_tbl request\n"));
5443         cs46xx_resume(s);
5444         return 0;
5445 }
5446 #endif