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