v2.4.8 -> v2.4.8.1
[opensuse:kernel.git] / drivers / sound / 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/list.h>
79 #include <linux/version.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 <asm/io.h>
91 #include <asm/dma.h>
92 #include <linux/init.h>
93 #include <linux/poll.h>
94 #include <linux/smp_lock.h>
95 #include <linux/wrapper.h>
96 #include <asm/uaccess.h>
97 #include <asm/hardirq.h>
98 #include <linux/ac97_codec.h>
99 #include "cs46xxpm-24.h"
100 #include "cs46xx_wrapper-24.h"
101
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_PARM(cs_debuglevel, "i");
181 static unsigned long cs_debugmask=CS_INIT | CS_ERROR;   /* use CS_DBGOUT with various mask values */
182 MODULE_PARM(cs_debugmask, "i");
183 #endif
184 static unsigned long hercules_egpio_disable=0;  /* if non-zero set all EGPIO to 0 */
185 MODULE_PARM(hercules_egpio_disable, "i");
186 static unsigned long initdelay=700;  /* PM delay in millisecs */
187 MODULE_PARM(initdelay, "i");
188 static unsigned long powerdown=-1;  /* turn on/off powerdown processing in driver */
189 MODULE_PARM(powerdown, "i");
190 #define DMABUF_DEFAULTORDER 3
191 static unsigned long defaultorder=DMABUF_DEFAULTORDER;
192 MODULE_PARM(defaultorder, "i");
193
194 static int external_amp;
195 MODULE_PARM(external_amp, "i");
196 static int thinkpad;
197 MODULE_PARM(thinkpad, "i");
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 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 semaphore open_sem;
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 semaphore 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         /* mixer use count */
317         atomic_t mixer_use_cnt;
318
319         /* PCI device stuff */
320         struct pci_dev * pci_dev;
321         struct list_head list;
322
323         unsigned int pctl, cctl;        /* Hardware DMA flag sets */
324
325         /* soundcore stuff */
326         int dev_audio;
327         int dev_midi;
328
329         /* structures for abstraction of hardware facilities, codecs, banks and channels*/
330         struct ac97_codec *ac97_codec[NR_AC97];
331         struct cs_state *states[2];
332
333         u16 ac97_features;
334         
335         int amplifier;                  /* Amplifier control */
336         void (*amplifier_ctrl)(struct cs_card *, int);
337         void (*amp_init)(struct cs_card *);
338         
339         int active;                     /* Active clocking */
340         void (*active_ctrl)(struct cs_card *, int);
341         
342         /* hardware resources */
343         unsigned long ba0_addr;
344         unsigned long ba1_addr;
345         u32 irq;
346         
347         /* mappings */
348         void *ba0;
349         union
350         {
351                 struct
352                 {
353                         u8 *data0;
354                         u8 *data1;
355                         u8 *pmem;
356                         u8 *reg;
357                 } name;
358                 u8 *idx[4];
359         } ba1;
360         
361         /* Function support */
362         struct cs_channel *(*alloc_pcm_channel)(struct cs_card *);
363         struct cs_channel *(*alloc_rec_pcm_channel)(struct cs_card *);
364         void (*free_pcm_channel)(struct cs_card *, int chan);
365
366         /* /dev/midi stuff */
367         struct {
368                 unsigned ird, iwr, icnt;
369                 unsigned ord, owr, ocnt;
370                 wait_queue_head_t open_wait;
371                 wait_queue_head_t iwait;
372                 wait_queue_head_t owait;
373                 spinlock_t lock;
374                 unsigned char ibuf[CS_MIDIINBUF];
375                 unsigned char obuf[CS_MIDIOUTBUF];
376                 mode_t open_mode;
377                 struct semaphore open_sem;
378         } midi;
379         struct cs46xx_pm pm;
380 };
381
382 static int cs_open_mixdev(struct inode *inode, struct file *file);
383 static int cs_release_mixdev(struct inode *inode, struct file *file);
384 static int cs_ioctl_mixdev(struct inode *inode, struct file *file, unsigned int cmd,
385                                 unsigned long arg);
386 static int cs_hardware_init(struct cs_card *card);
387 static int cs46xx_powerup(struct cs_card *card, unsigned int type);
388 static int cs461x_powerdown(struct cs_card *card, unsigned int type, int suspendflag);
389 static void cs461x_clear_serial_FIFOs(struct cs_card *card, int type);
390 static int cs46xx_suspend_tbl(struct pci_dev *pcidev, u32 state);
391 static int cs46xx_resume_tbl(struct pci_dev *pcidev);
392
393 static inline unsigned ld2(unsigned int x)
394 {
395         unsigned r = 0;
396         
397         if (x >= 0x10000) {
398                 x >>= 16;
399                 r += 16;
400         }
401         if (x >= 0x100) {
402                 x >>= 8;
403                 r += 8;
404         }
405         if (x >= 0x10) {
406                 x >>= 4;
407                 r += 4;
408         }
409         if (x >= 4) {
410                 x >>= 2;
411                 r += 2;
412         }
413         if (x >= 2)
414                 r++;
415         return r;
416 }
417
418 #if CSDEBUG
419
420 /* DEBUG ROUTINES */
421
422 #define SOUND_MIXER_CS_GETDBGLEVEL      _SIOWR('M',120, int)
423 #define SOUND_MIXER_CS_SETDBGLEVEL      _SIOWR('M',121, int)
424 #define SOUND_MIXER_CS_GETDBGMASK       _SIOWR('M',122, int)
425 #define SOUND_MIXER_CS_SETDBGMASK       _SIOWR('M',123, int)
426 #define SOUND_MIXER_CS_APM              _SIOWR('M',124, int)
427
428 void printioctl(unsigned int x)
429 {
430     unsigned int i;
431     unsigned char vidx;
432         /* these values are incorrect for the ac97 driver, fix.
433          * Index of mixtable1[] member is Device ID 
434          * and must be <= SOUND_MIXER_NRDEVICES.
435          * Value of array member is index into s->mix.vol[]
436          */
437         static const unsigned char mixtable1[SOUND_MIXER_NRDEVICES] = {
438                 [SOUND_MIXER_PCM]     = 1,   /* voice */
439                 [SOUND_MIXER_LINE1]   = 2,   /* AUX */
440                 [SOUND_MIXER_CD]      = 3,   /* CD */
441                 [SOUND_MIXER_LINE]    = 4,   /* Line */
442                 [SOUND_MIXER_SYNTH]   = 5,   /* FM */
443                 [SOUND_MIXER_MIC]     = 6,   /* Mic */
444                 [SOUND_MIXER_SPEAKER] = 7,   /* Speaker */
445                 [SOUND_MIXER_RECLEV]  = 8,   /* Recording level */
446                 [SOUND_MIXER_VOLUME]  = 9    /* Master Volume */
447         };
448         
449     switch(x) 
450     {
451         case SOUND_MIXER_CS_GETDBGMASK:
452                 CS_DBGOUT(CS_IOCTL, 4, printk("SOUND_MIXER_CS_GETDBGMASK: ") );
453                 break;
454         case SOUND_MIXER_CS_GETDBGLEVEL:
455                 CS_DBGOUT(CS_IOCTL, 4, printk("SOUND_MIXER_CS_GETDBGLEVEL: ") );
456                 break;
457         case SOUND_MIXER_CS_SETDBGMASK:
458                 CS_DBGOUT(CS_IOCTL, 4, printk("SOUND_MIXER_CS_SETDBGMASK: ") );
459                 break;
460         case SOUND_MIXER_CS_SETDBGLEVEL:
461                 CS_DBGOUT(CS_IOCTL, 4, printk("SOUND_MIXER_CS_SETDBGLEVEL: ") );
462                 break;
463         case OSS_GETVERSION:
464                 CS_DBGOUT(CS_IOCTL, 4, printk("OSS_GETVERSION: ") );
465                 break;
466         case SNDCTL_DSP_SYNC:
467                 CS_DBGOUT(CS_IOCTL, 4, printk("SNDCTL_DSP_SYNC: ") );
468                 break;
469         case SNDCTL_DSP_SETDUPLEX:
470                 CS_DBGOUT(CS_IOCTL, 4, printk("SNDCTL_DSP_SETDUPLEX: ") );
471                 break;
472         case SNDCTL_DSP_GETCAPS:
473                 CS_DBGOUT(CS_IOCTL, 4, printk("SNDCTL_DSP_GETCAPS: ") );
474                 break;
475         case SNDCTL_DSP_RESET:
476                 CS_DBGOUT(CS_IOCTL, 4, printk("SNDCTL_DSP_RESET: ") );
477                 break;
478         case SNDCTL_DSP_SPEED:
479                 CS_DBGOUT(CS_IOCTL, 4, printk("SNDCTL_DSP_SPEED: ") );
480                 break;
481         case SNDCTL_DSP_STEREO:
482                 CS_DBGOUT(CS_IOCTL, 4, printk("SNDCTL_DSP_STEREO: ") );
483                 break;
484         case SNDCTL_DSP_CHANNELS:
485                 CS_DBGOUT(CS_IOCTL, 4, printk("SNDCTL_DSP_CHANNELS: ") );
486                 break;
487         case SNDCTL_DSP_GETFMTS: 
488                 CS_DBGOUT(CS_IOCTL, 4, printk("SNDCTL_DSP_GETFMTS: ") );
489                 break;
490         case SNDCTL_DSP_SETFMT: 
491                 CS_DBGOUT(CS_IOCTL, 4, printk("SNDCTL_DSP_SETFMT: ") );
492                 break;
493         case SNDCTL_DSP_POST:
494                 CS_DBGOUT(CS_IOCTL, 4, printk("SNDCTL_DSP_POST: ") );
495                 break;
496         case SNDCTL_DSP_GETTRIGGER:
497                 CS_DBGOUT(CS_IOCTL, 4, printk("SNDCTL_DSP_GETTRIGGER: ") );
498                 break;
499         case SNDCTL_DSP_SETTRIGGER:
500                 CS_DBGOUT(CS_IOCTL, 4, printk("SNDCTL_DSP_SETTRIGGER: ") );
501                 break;
502         case SNDCTL_DSP_GETOSPACE:
503                 CS_DBGOUT(CS_IOCTL, 4, printk("SNDCTL_DSP_GETOSPACE: ") );
504                 break;
505         case SNDCTL_DSP_GETISPACE:
506                 CS_DBGOUT(CS_IOCTL, 4, printk("SNDCTL_DSP_GETISPACE: ") );
507                 break;
508         case SNDCTL_DSP_NONBLOCK:
509                 CS_DBGOUT(CS_IOCTL, 4, printk("SNDCTL_DSP_NONBLOCK: ") );
510                 break;
511         case SNDCTL_DSP_GETODELAY:
512                 CS_DBGOUT(CS_IOCTL, 4, printk("SNDCTL_DSP_GETODELAY: ") );
513                 break;
514         case SNDCTL_DSP_GETIPTR:
515                 CS_DBGOUT(CS_IOCTL, 4, printk("SNDCTL_DSP_GETIPTR: ") );
516                 break;
517         case SNDCTL_DSP_GETOPTR:
518                 CS_DBGOUT(CS_IOCTL, 4, printk("SNDCTL_DSP_GETOPTR: ") );
519                 break;
520         case SNDCTL_DSP_GETBLKSIZE:
521                 CS_DBGOUT(CS_IOCTL, 4, printk("SNDCTL_DSP_GETBLKSIZE: ") );
522                 break;
523         case SNDCTL_DSP_SETFRAGMENT:
524                 CS_DBGOUT(CS_IOCTL, 4, printk("SNDCTL_DSP_SETFRAGMENT: ") );
525                 break;
526         case SNDCTL_DSP_SUBDIVIDE:
527                 CS_DBGOUT(CS_IOCTL, 4, printk("SNDCTL_DSP_SUBDIVIDE: ") );
528                 break;
529         case SOUND_PCM_READ_RATE:
530                 CS_DBGOUT(CS_IOCTL, 4, printk("SOUND_PCM_READ_RATE: ") );
531                 break;
532         case SOUND_PCM_READ_CHANNELS:
533                 CS_DBGOUT(CS_IOCTL, 4, printk("SOUND_PCM_READ_CHANNELS: ") );
534                 break;
535         case SOUND_PCM_READ_BITS:
536                 CS_DBGOUT(CS_IOCTL, 4, printk("SOUND_PCM_READ_BITS: ") );
537                 break;
538         case SOUND_PCM_WRITE_FILTER:
539                 CS_DBGOUT(CS_IOCTL, 4, printk("SOUND_PCM_WRITE_FILTER: ") );
540                 break;
541         case SNDCTL_DSP_SETSYNCRO:
542                 CS_DBGOUT(CS_IOCTL, 4, printk("SNDCTL_DSP_SETSYNCRO: ") );
543                 break;
544         case SOUND_PCM_READ_FILTER:
545                 CS_DBGOUT(CS_IOCTL, 4, printk("SOUND_PCM_READ_FILTER: ") );
546                 break;
547
548         case SOUND_MIXER_PRIVATE1:
549                 CS_DBGOUT(CS_IOCTL, 4, printk("SOUND_MIXER_PRIVATE1: ") );
550                 break;
551         case SOUND_MIXER_PRIVATE2:
552                 CS_DBGOUT(CS_IOCTL, 4, printk("SOUND_MIXER_PRIVATE2: ") );
553                 break;
554         case SOUND_MIXER_PRIVATE3:
555                 CS_DBGOUT(CS_IOCTL, 4, printk("SOUND_MIXER_PRIVATE3: ") );
556                 break;
557         case SOUND_MIXER_PRIVATE4:
558                 CS_DBGOUT(CS_IOCTL, 4, printk("SOUND_MIXER_PRIVATE4: ") );
559                 break;
560         case SOUND_MIXER_PRIVATE5:
561                 CS_DBGOUT(CS_IOCTL, 4, printk("SOUND_MIXER_PRIVATE5: ") );
562                 break;
563         case SOUND_MIXER_INFO:
564                 CS_DBGOUT(CS_IOCTL, 4, printk("SOUND_MIXER_INFO: ") );
565                 break;
566         case SOUND_OLD_MIXER_INFO:
567                 CS_DBGOUT(CS_IOCTL, 4, printk("SOUND_OLD_MIXER_INFO: ") );
568                 break;
569
570         default:
571                 switch (_IOC_NR(x)) 
572                 {
573                         case SOUND_MIXER_VOLUME:
574                                 CS_DBGOUT(CS_IOCTL, 4, printk("SOUND_MIXER_VOLUME: ") );
575                                 break;
576                         case SOUND_MIXER_SPEAKER:
577                                 CS_DBGOUT(CS_IOCTL, 4, printk("SOUND_MIXER_SPEAKER: ") );
578                                 break;
579                         case SOUND_MIXER_RECLEV:
580                                 CS_DBGOUT(CS_IOCTL, 4, printk("SOUND_MIXER_RECLEV: ") );
581                                 break;
582                         case SOUND_MIXER_MIC:
583                                 CS_DBGOUT(CS_IOCTL, 4, printk("SOUND_MIXER_MIC: ") );
584                                 break;
585                         case SOUND_MIXER_SYNTH:
586                                 CS_DBGOUT(CS_IOCTL, 4, printk("SOUND_MIXER_SYNTH: ") );
587                                 break;
588                         case SOUND_MIXER_RECSRC: 
589                                 CS_DBGOUT(CS_IOCTL, 4, printk("SOUND_MIXER_RECSRC: ") );
590                                 break;
591                         case SOUND_MIXER_DEVMASK:
592                                 CS_DBGOUT(CS_IOCTL, 4, printk("SOUND_MIXER_DEVMASK: ") );
593                                 break;
594                         case SOUND_MIXER_RECMASK:
595                                 CS_DBGOUT(CS_IOCTL, 4, printk("SOUND_MIXER_RECMASK: ") );
596                                 break;
597                         case SOUND_MIXER_STEREODEVS: 
598                                 CS_DBGOUT(CS_IOCTL, 4, printk("SOUND_MIXER_STEREODEVS: ") );
599                                 break;
600                         case SOUND_MIXER_CAPS:
601                                 CS_DBGOUT(CS_IOCTL, 4, printk("SOUND_MIXER_CAPS:") );
602                                 break;
603                         default:
604                                 i = _IOC_NR(x);
605                                 if (i >= SOUND_MIXER_NRDEVICES || !(vidx = mixtable1[i]))
606                                 {
607                                         CS_DBGOUT(CS_IOCTL, 4, printk("UNKNOWN IOCTL: 0x%.8x NR=%d ",x,i) );
608                                 }
609                                 else
610                                 {
611                                         CS_DBGOUT(CS_IOCTL, 4, printk("SOUND_MIXER_IOCTL AC9x: 0x%.8x NR=%d ",
612                                                         x,i) );
613                                 }
614                                 break;
615                 }
616     }
617     CS_DBGOUT(CS_IOCTL, 4, printk("command = 0x%x IOC_NR=%d\n",x, _IOC_NR(x)) );
618 }
619 #endif
620
621 /*
622  *  common I/O routines
623  */
624
625 static void cs461x_poke(struct cs_card *codec, unsigned long reg, unsigned int val)
626 {
627         writel(val, codec->ba1.idx[(reg >> 16) & 3]+(reg&0xffff));
628 }
629
630 static unsigned int cs461x_peek(struct cs_card *codec, unsigned long reg)
631 {
632         return readl(codec->ba1.idx[(reg >> 16) & 3]+(reg&0xffff));
633 }
634
635 static void cs461x_pokeBA0(struct cs_card *codec, unsigned long reg, unsigned int val)
636 {
637         writel(val, codec->ba0+reg);
638 }
639
640 static unsigned int cs461x_peekBA0(struct cs_card *codec, unsigned long reg)
641 {
642         return readl(codec->ba0+reg);
643 }
644
645
646 static u16 cs_ac97_get(struct ac97_codec *dev, u8 reg);
647 static void cs_ac97_set(struct ac97_codec *dev, u8 reg, u16 data);
648
649 static struct cs_channel *cs_alloc_pcm_channel(struct cs_card *card)
650 {
651         if(card->channel[1].used==1)
652                 return NULL;
653         card->channel[1].used=1;
654         card->channel[1].num=1;
655         return &card->channel[1];
656 }
657
658 static struct cs_channel *cs_alloc_rec_pcm_channel(struct cs_card *card)
659 {
660         if(card->channel[0].used==1)
661                 return NULL;
662         card->channel[0].used=1;
663         card->channel[0].num=0;
664         return &card->channel[0];
665 }
666
667 static void cs_free_pcm_channel(struct cs_card *card, int channel)
668 {
669         card->channel[channel].state = NULL;
670         card->channel[channel].used=0;
671 }
672
673 /*
674  * setup a divisor value to help with conversion from
675  * 16bit Stereo, down to 8bit stereo/mono or 16bit mono.
676  * assign a divisor of 1 if using 16bit Stereo as that is
677  * the only format that the static image will capture.
678  */
679 static void cs_set_divisor(struct dmabuf *dmabuf)
680 {
681         if(dmabuf->type == CS_TYPE_DAC)
682                 dmabuf->divisor = 1;
683         else if( !(dmabuf->fmt & CS_FMT_STEREO) && 
684             (dmabuf->fmt & CS_FMT_16BIT))
685                 dmabuf->divisor = 2;
686         else if( (dmabuf->fmt & CS_FMT_STEREO) && 
687             !(dmabuf->fmt & CS_FMT_16BIT))
688                 dmabuf->divisor = 2;
689         else if( !(dmabuf->fmt & CS_FMT_STEREO) && 
690             !(dmabuf->fmt & CS_FMT_16BIT))
691                 dmabuf->divisor = 4;
692         else
693                 dmabuf->divisor = 1;
694
695         CS_DBGOUT(CS_PARMS | CS_FUNCTION, 8, printk(
696                 "cs46xx: cs_set_divisor()- %s %d\n",
697                         (dmabuf->type == CS_TYPE_ADC) ? "ADC" : "DAC", 
698                         dmabuf->divisor) );
699 }
700
701 /*
702 * mute some of the more prevalent registers to avoid popping.
703 */
704 static void cs_mute(struct cs_card *card, int state) 
705 {
706         struct ac97_codec *dev=card->ac97_codec[0];
707
708         CS_DBGOUT(CS_FUNCTION, 2, printk(KERN_INFO "cs46xx: cs_mute()+ %s\n",
709                 (state == CS_TRUE) ? "Muting" : "UnMuting") );
710
711         if(state == CS_TRUE)
712         {
713         /*
714         * fix pops when powering up on thinkpads
715         */
716                 card->pm.u32AC97_master_volume = (u32)cs_ac97_get( dev, 
717                                 (u8)BA0_AC97_MASTER_VOLUME); 
718                 card->pm.u32AC97_headphone_volume = (u32)cs_ac97_get(dev, 
719                                 (u8)BA0_AC97_HEADPHONE_VOLUME); 
720                 card->pm.u32AC97_master_volume_mono = (u32)cs_ac97_get(dev, 
721                                 (u8)BA0_AC97_MASTER_VOLUME_MONO); 
722                 card->pm.u32AC97_pcm_out_volume = (u32)cs_ac97_get(dev, 
723                                 (u8)BA0_AC97_PCM_OUT_VOLUME);
724                         
725                 cs_ac97_set(dev, (u8)BA0_AC97_MASTER_VOLUME, 0x8000);
726                 cs_ac97_set(dev, (u8)BA0_AC97_HEADPHONE_VOLUME, 0x8000);
727                 cs_ac97_set(dev, (u8)BA0_AC97_MASTER_VOLUME_MONO, 0x8000);
728                 cs_ac97_set(dev, (u8)BA0_AC97_PCM_OUT_VOLUME, 0x8000);
729         }
730         else
731         {
732                 cs_ac97_set(dev, (u8)BA0_AC97_MASTER_VOLUME, card->pm.u32AC97_master_volume);
733                 cs_ac97_set(dev, (u8)BA0_AC97_HEADPHONE_VOLUME, card->pm.u32AC97_headphone_volume);
734                 cs_ac97_set(dev, (u8)BA0_AC97_MASTER_VOLUME_MONO, card->pm.u32AC97_master_volume_mono);
735                 cs_ac97_set(dev, (u8)BA0_AC97_PCM_OUT_VOLUME, card->pm.u32AC97_pcm_out_volume);
736         }
737         CS_DBGOUT(CS_FUNCTION, 2, printk(KERN_INFO "cs46xx: cs_mute()-\n"));
738 }
739
740 /* set playback sample rate */
741 static unsigned int cs_set_dac_rate(struct cs_state * state, unsigned int rate)
742 {       
743         struct dmabuf *dmabuf = &state->dmabuf;
744         unsigned int tmp1, tmp2;
745         unsigned int phiIncr;
746         unsigned int correctionPerGOF, correctionPerSec;
747         unsigned long flags;
748
749         CS_DBGOUT(CS_FUNCTION, 2, printk("cs46xx: cs_set_dac_rate()+ %d\n",rate) );
750
751         /*
752          *  Compute the values used to drive the actual sample rate conversion.
753          *  The following formulas are being computed, using inline assembly
754          *  since we need to use 64 bit arithmetic to compute the values:
755          *
756          *  phiIncr = floor((Fs,in * 2^26) / Fs,out)
757          *  correctionPerGOF = floor((Fs,in * 2^26 - Fs,out * phiIncr) /
758          *                                   GOF_PER_SEC)
759          *  ulCorrectionPerSec = Fs,in * 2^26 - Fs,out * phiIncr -M
760          *                       GOF_PER_SEC * correctionPerGOF
761          *
762          *  i.e.
763          *
764          *  phiIncr:other = dividend:remainder((Fs,in * 2^26) / Fs,out)
765          *  correctionPerGOF:correctionPerSec =
766          *      dividend:remainder(ulOther / GOF_PER_SEC)
767          */
768         tmp1 = rate << 16;
769         phiIncr = tmp1 / 48000;
770         tmp1 -= phiIncr * 48000;
771         tmp1 <<= 10;
772         phiIncr <<= 10;
773         tmp2 = tmp1 / 48000;
774         phiIncr += tmp2;
775         tmp1 -= tmp2 * 48000;
776         correctionPerGOF = tmp1 / GOF_PER_SEC;
777         tmp1 -= correctionPerGOF * GOF_PER_SEC;
778         correctionPerSec = tmp1;
779
780         /*
781          *  Fill in the SampleRateConverter control block.
782          */
783          
784         spin_lock_irqsave(&state->card->lock, flags);
785         cs461x_poke(state->card, BA1_PSRC,
786           ((correctionPerSec << 16) & 0xFFFF0000) | (correctionPerGOF & 0xFFFF));
787         cs461x_poke(state->card, BA1_PPI, phiIncr);
788         spin_unlock_irqrestore(&state->card->lock, flags);
789         dmabuf->rate = rate;
790         
791         CS_DBGOUT(CS_FUNCTION, 2, printk("cs46xx: cs_set_dac_rate()- %d\n",rate) );
792         return rate;
793 }
794
795 /* set recording sample rate */
796 static unsigned int cs_set_adc_rate(struct cs_state * state, unsigned int rate)
797 {
798         struct dmabuf *dmabuf = &state->dmabuf;
799         struct cs_card *card = state->card;
800         unsigned int phiIncr, coeffIncr, tmp1, tmp2;
801         unsigned int correctionPerGOF, correctionPerSec, initialDelay;
802         unsigned int frameGroupLength, cnt;
803         unsigned long flags;
804         CS_DBGOUT(CS_FUNCTION, 2, printk("cs46xx: cs_set_adc_rate()+ %d\n",rate) );
805
806         /*
807          *  We can only decimate by up to a factor of 1/9th the hardware rate.
808          *  Correct the value if an attempt is made to stray outside that limit.
809          */
810         if ((rate * 9) < 48000)
811                 rate = 48000 / 9;
812
813         /*
814          *  We can not capture at at rate greater than the Input Rate (48000).
815          *  Return an error if an attempt is made to stray outside that limit.
816          */
817         if (rate > 48000)
818                 rate = 48000;
819
820         /*
821          *  Compute the values used to drive the actual sample rate conversion.
822          *  The following formulas are being computed, using inline assembly
823          *  since we need to use 64 bit arithmetic to compute the values:
824          *
825          *     coeffIncr = -floor((Fs,out * 2^23) / Fs,in)
826          *     phiIncr = floor((Fs,in * 2^26) / Fs,out)
827          *     correctionPerGOF = floor((Fs,in * 2^26 - Fs,out * phiIncr) /
828          *                                GOF_PER_SEC)
829          *     correctionPerSec = Fs,in * 2^26 - Fs,out * phiIncr -
830          *                          GOF_PER_SEC * correctionPerGOF
831          *     initialDelay = ceil((24 * Fs,in) / Fs,out)
832          *
833          * i.e.
834          *
835          *     coeffIncr = neg(dividend((Fs,out * 2^23) / Fs,in))
836          *     phiIncr:ulOther = dividend:remainder((Fs,in * 2^26) / Fs,out)
837          *     correctionPerGOF:correctionPerSec =
838          *          dividend:remainder(ulOther / GOF_PER_SEC)
839          *     initialDelay = dividend(((24 * Fs,in) + Fs,out - 1) / Fs,out)
840          */
841
842         tmp1 = rate << 16;
843         coeffIncr = tmp1 / 48000;
844         tmp1 -= coeffIncr * 48000;
845         tmp1 <<= 7;
846         coeffIncr <<= 7;
847         coeffIncr += tmp1 / 48000;
848         coeffIncr ^= 0xFFFFFFFF;
849         coeffIncr++;
850         tmp1 = 48000 << 16;
851         phiIncr = tmp1 / rate;
852         tmp1 -= phiIncr * rate;
853         tmp1 <<= 10;
854         phiIncr <<= 10;
855         tmp2 = tmp1 / rate;
856         phiIncr += tmp2;
857         tmp1 -= tmp2 * rate;
858         correctionPerGOF = tmp1 / GOF_PER_SEC;
859         tmp1 -= correctionPerGOF * GOF_PER_SEC;
860         correctionPerSec = tmp1;
861         initialDelay = ((48000 * 24) + rate - 1) / rate;
862
863         /*
864          *  Fill in the VariDecimate control block.
865          */
866         spin_lock_irqsave(&card->lock, flags);
867         cs461x_poke(card, BA1_CSRC,
868                 ((correctionPerSec << 16) & 0xFFFF0000) | (correctionPerGOF & 0xFFFF));
869         cs461x_poke(card, BA1_CCI, coeffIncr);
870         cs461x_poke(card, BA1_CD,
871                 (((BA1_VARIDEC_BUF_1 + (initialDelay << 2)) << 16) & 0xFFFF0000) | 0x80);
872         cs461x_poke(card, BA1_CPI, phiIncr);
873         spin_unlock_irqrestore(&card->lock, flags);
874
875         /*
876          *  Figure out the frame group length for the write back task.  Basically,
877          *  this is just the factors of 24000 (2^6*3*5^3) that are not present in
878          *  the output sample rate.
879          */
880         frameGroupLength = 1;
881         for (cnt = 2; cnt <= 64; cnt *= 2) {
882                 if (((rate / cnt) * cnt) != rate)
883                         frameGroupLength *= 2;
884         }
885         if (((rate / 3) * 3) != rate) {
886                 frameGroupLength *= 3;
887         }
888         for (cnt = 5; cnt <= 125; cnt *= 5) {
889                 if (((rate / cnt) * cnt) != rate) 
890                         frameGroupLength *= 5;
891         }
892
893         /*
894          * Fill in the WriteBack control block.
895          */
896         spin_lock_irqsave(&card->lock, flags);
897         cs461x_poke(card, BA1_CFG1, frameGroupLength);
898         cs461x_poke(card, BA1_CFG2, (0x00800000 | frameGroupLength));
899         cs461x_poke(card, BA1_CCST, 0x0000FFFF);
900         cs461x_poke(card, BA1_CSPB, ((65536 * rate) / 24000));
901         cs461x_poke(card, (BA1_CSPB + 4), 0x0000FFFF);
902         spin_unlock_irqrestore(&card->lock, flags);
903         dmabuf->rate = rate;
904         CS_DBGOUT(CS_FUNCTION, 2, printk("cs46xx: cs_set_adc_rate()- %d\n",rate) );
905         return rate;
906 }
907
908 /* prepare channel attributes for playback */ 
909 static void cs_play_setup(struct cs_state *state)
910 {
911         struct dmabuf *dmabuf = &state->dmabuf;
912         struct cs_card *card = state->card;
913         unsigned int tmp, Count, playFormat;
914
915         CS_DBGOUT(CS_FUNCTION, 2, printk("cs46xx: cs_play_setup()+\n") );
916         cs461x_poke(card, BA1_PVOL, 0x80008000);
917         if(!dmabuf->SGok)
918                cs461x_poke(card, BA1_PBA, virt_to_bus(dmabuf->pbuf));
919     
920         Count = 4;                                                          
921         playFormat=cs461x_peek(card, BA1_PFIE);                             
922         if ((dmabuf->fmt & CS_FMT_STEREO)) {                                
923                 playFormat &= ~DMA_RQ_C2_AC_MONO_TO_STEREO;                 
924                 Count *= 2;                                                 
925         }                                                                   
926         else                                                                
927                 playFormat |= DMA_RQ_C2_AC_MONO_TO_STEREO;                  
928                                                                             
929         if ((dmabuf->fmt & CS_FMT_16BIT)) {                                 
930                 playFormat &= ~(DMA_RQ_C2_AC_8_TO_16_BIT                    
931                            | DMA_RQ_C2_AC_SIGNED_CONVERT);                  
932                 Count *= 2;                                                 
933         }                                                                   
934         else                                                                
935                 playFormat |= (DMA_RQ_C2_AC_8_TO_16_BIT                     
936                            | DMA_RQ_C2_AC_SIGNED_CONVERT);                  
937                                                                             
938         cs461x_poke(card, BA1_PFIE, playFormat);                            
939                                                                             
940         tmp = cs461x_peek(card, BA1_PDTC);                                  
941         tmp &= 0xfffffe00;                                                  
942         cs461x_poke(card, BA1_PDTC, tmp | --Count);                         
943
944         CS_DBGOUT(CS_FUNCTION, 2, printk("cs46xx: cs_play_setup()-\n") );
945
946 }
947
948 struct InitStruct
949 {
950     u32 long off;
951     u32 long val;
952 } InitArray[] = { {0x00000040, 0x3fc0000f},
953                   {0x0000004c, 0x04800000},
954
955                   {0x000000b3, 0x00000780},
956                   {0x000000b7, 0x00000000},
957                   {0x000000bc, 0x07800000},
958
959                   {0x000000cd, 0x00800000},
960                 };
961
962 /*
963  * "SetCaptureSPValues()" -- Initialize record task values before each
964  *      capture startup.  
965  */
966 void SetCaptureSPValues(struct cs_card *card)
967 {
968         unsigned i, offset;
969         CS_DBGOUT(CS_FUNCTION, 8, printk("cs46xx: SetCaptureSPValues()+\n") );
970         for(i=0; i<sizeof(InitArray)/sizeof(struct InitStruct); i++)
971         {
972                 offset = InitArray[i].off*4; /* 8bit to 32bit offset value */
973                 cs461x_poke(card, offset, InitArray[i].val );
974         }
975         CS_DBGOUT(CS_FUNCTION, 8, printk("cs46xx: SetCaptureSPValues()-\n") );
976 }
977
978 /* prepare channel attributes for recording */
979 static void cs_rec_setup(struct cs_state *state)
980 {
981         struct cs_card *card = state->card;
982         struct dmabuf *dmabuf = &state->dmabuf;
983         CS_DBGOUT(CS_FUNCTION, 2, printk("cs46xx: cs_rec_setup()+\n") );
984
985         SetCaptureSPValues(card);
986
987         /*
988          * set the attenuation to 0dB 
989          */
990         cs461x_poke(card, BA1_CVOL, 0x80008000);
991
992         /*
993          * set the physical address of the capture buffer into the SP
994          */
995         cs461x_poke(card, BA1_CBA, virt_to_bus(dmabuf->rawbuf));
996
997         CS_DBGOUT(CS_FUNCTION, 2, printk("cs46xx: cs_rec_setup()-\n") );
998 }
999
1000
1001 /* get current playback/recording dma buffer pointer (byte offset from LBA),
1002    called with spinlock held! */
1003    
1004 static inline unsigned cs_get_dma_addr(struct cs_state *state)
1005 {
1006         struct dmabuf *dmabuf = &state->dmabuf;
1007         u32 offset;
1008         
1009         if ( (!(dmabuf->enable & DAC_RUNNING)) &&
1010              (!(dmabuf->enable & ADC_RUNNING) ) )
1011         {
1012                 CS_DBGOUT(CS_ERROR, 2, printk(
1013                         "cs46xx: ERROR cs_get_dma_addr(): not enabled \n") );
1014                 return 0;
1015         }
1016                 
1017         /*
1018          * ganularity is byte boundry, good part.
1019          */
1020         if(dmabuf->enable & DAC_RUNNING)
1021         {
1022                 offset = cs461x_peek(state->card, BA1_PBA);                                  
1023         }
1024         else /* ADC_RUNNING must be set */
1025         {
1026                 offset = cs461x_peek(state->card, BA1_CBA);                                  
1027         }
1028         CS_DBGOUT(CS_PARMS | CS_FUNCTION, 9, 
1029                 printk("cs46xx: cs_get_dma_addr() %d\n",offset) );
1030         offset = (u32)bus_to_virt((unsigned long)offset) - (u32)dmabuf->rawbuf;
1031         CS_DBGOUT(CS_PARMS | CS_FUNCTION, 8, 
1032                 printk("cs46xx: cs_get_dma_addr()- %d\n",offset) );
1033         return offset;
1034 }
1035
1036 static void resync_dma_ptrs(struct cs_state *state)
1037 {
1038         struct dmabuf *dmabuf;
1039         
1040         CS_DBGOUT(CS_FUNCTION, 2, printk("cs46xx: resync_dma_ptrs()+ \n") );
1041         if(state)
1042         {
1043                 dmabuf = &state->dmabuf;
1044                 dmabuf->hwptr=dmabuf->swptr = 0;
1045                 dmabuf->pringbuf = 0;
1046         }
1047         CS_DBGOUT(CS_FUNCTION, 2, printk("cs46xx: resync_dma_ptrs()- \n") );
1048 }
1049         
1050 /* Stop recording (lock held) */
1051 static inline void __stop_adc(struct cs_state *state)
1052 {
1053         struct dmabuf *dmabuf = &state->dmabuf;
1054         struct cs_card *card = state->card;
1055         unsigned int tmp;
1056         
1057         dmabuf->enable &= ~ADC_RUNNING;
1058         
1059         tmp = cs461x_peek(card, BA1_CCTL);
1060         tmp &= 0xFFFF0000;
1061         cs461x_poke(card, BA1_CCTL, tmp );
1062 }
1063
1064 static void stop_adc(struct cs_state *state)
1065 {
1066         unsigned long flags;
1067
1068         CS_DBGOUT(CS_FUNCTION, 2, printk("cs46xx: stop_adc()+ \n") );
1069         spin_lock_irqsave(&state->card->lock, flags);
1070         __stop_adc(state);
1071         spin_unlock_irqrestore(&state->card->lock, flags);
1072         CS_DBGOUT(CS_FUNCTION, 2, printk("cs46xx: stop_adc()- \n") );
1073 }
1074
1075 static void start_adc(struct cs_state *state)
1076 {
1077         struct dmabuf *dmabuf = &state->dmabuf;
1078         struct cs_card *card = state->card;
1079         unsigned long flags;
1080         unsigned int tmp;
1081
1082         spin_lock_irqsave(&card->lock, flags);
1083         if (!(dmabuf->enable & ADC_RUNNING) && 
1084              ((dmabuf->mapped || dmabuf->count < (signed)dmabuf->dmasize) 
1085                && dmabuf->ready) && 
1086                ((card->pm.flags & CS46XX_PM_IDLE) || 
1087                 (card->pm.flags & CS46XX_PM_RESUMED)) )
1088         {
1089                 dmabuf->enable |= ADC_RUNNING;
1090                 cs_set_divisor(dmabuf);
1091                 tmp = cs461x_peek(card, BA1_CCTL);
1092                 tmp &= 0xFFFF0000;
1093                 tmp |= card->cctl;
1094                 CS_DBGOUT(CS_FUNCTION, 2, printk(
1095                         "cs46xx: start_adc() poke 0x%x \n",tmp) );
1096                 cs461x_poke(card, BA1_CCTL, tmp);
1097         }
1098         spin_unlock_irqrestore(&card->lock, flags);
1099 }
1100
1101 /* stop playback (lock held) */
1102 static inline void __stop_dac(struct cs_state *state)
1103 {
1104         struct dmabuf *dmabuf = &state->dmabuf;
1105         struct cs_card *card = state->card;
1106         unsigned int tmp;
1107
1108         dmabuf->enable &= ~DAC_RUNNING;
1109         
1110         tmp=cs461x_peek(card, BA1_PCTL);
1111         tmp&=0xFFFF;
1112         cs461x_poke(card, BA1_PCTL, tmp);
1113 }
1114
1115 static void stop_dac(struct cs_state *state)
1116 {
1117         unsigned long flags;
1118
1119         CS_DBGOUT(CS_FUNCTION, 2, printk("cs46xx: stop_dac()+ \n") );
1120         spin_lock_irqsave(&state->card->lock, flags);
1121         __stop_dac(state);
1122         spin_unlock_irqrestore(&state->card->lock, flags);
1123         CS_DBGOUT(CS_FUNCTION, 2, printk("cs46xx: stop_dac()- \n") );
1124 }       
1125
1126 static void start_dac(struct cs_state *state)
1127 {
1128         struct dmabuf *dmabuf = &state->dmabuf;
1129         struct cs_card *card = state->card;
1130         unsigned long flags;
1131         int tmp;
1132
1133         CS_DBGOUT(CS_FUNCTION, 2, printk("cs46xx: start_dac()+ \n") );
1134         spin_lock_irqsave(&card->lock, flags);
1135         if (!(dmabuf->enable & DAC_RUNNING) && 
1136             ((dmabuf->mapped || dmabuf->count > 0) && dmabuf->ready) &&
1137                ((card->pm.flags & CS46XX_PM_IDLE) || 
1138                 (card->pm.flags & CS46XX_PM_RESUMED)) )
1139         {
1140                 dmabuf->enable |= DAC_RUNNING;
1141                 tmp = cs461x_peek(card, BA1_PCTL);
1142                 tmp &= 0xFFFF;
1143                 tmp |= card->pctl;
1144                 CS_DBGOUT(CS_PARMS, 6, printk(
1145                     "cs46xx: start_dac() poke card=0x%.08x tmp=0x%.08x addr=0x%.08x \n",
1146                     (unsigned)card, (unsigned)tmp, 
1147                     (unsigned)card->ba1.idx[(BA1_PCTL >> 16) & 3]+(BA1_PCTL&0xffff) ) );
1148                 cs461x_poke(card, BA1_PCTL, tmp);
1149         }
1150         spin_unlock_irqrestore(&card->lock, flags);
1151         CS_DBGOUT(CS_FUNCTION, 2, printk("cs46xx: start_dac()- \n") );
1152 }
1153
1154 #define DMABUF_MINORDER 1
1155
1156 /*
1157  * allocate DMA buffer, playback and recording buffers are separate.
1158  */
1159 static int alloc_dmabuf(struct cs_state *state)
1160 {
1161
1162         struct cs_card *card=state->card;
1163         struct dmabuf *dmabuf = &state->dmabuf;
1164         void *rawbuf = NULL;
1165         void *tmpbuff = NULL;
1166         int order;
1167         struct page *map, *mapend;
1168         unsigned long df;
1169         
1170         dmabuf->ready  = dmabuf->mapped = 0;
1171         dmabuf->SGok = 0;
1172 /*
1173 * check for order within limits, but do not overwrite value.
1174 */
1175         if((defaultorder > 1) && (defaultorder < 12))
1176                 df = defaultorder;
1177         else
1178                 df = 2; 
1179
1180         for (order = df; order >= DMABUF_MINORDER; order--)
1181                 if ( (rawbuf = (void *) pci_alloc_consistent(
1182                         card->pci_dev, PAGE_SIZE << order, &dmabuf->dmaaddr)))
1183                             break;
1184         if (!rawbuf) {
1185                 CS_DBGOUT(CS_ERROR, 1, printk(KERN_ERR
1186                         "cs46xx: alloc_dmabuf(): unable to allocate rawbuf\n"));
1187                 return -ENOMEM;
1188         }
1189         dmabuf->buforder = order;
1190         dmabuf->rawbuf = rawbuf;
1191         // Now mark the pages as reserved; otherwise the 
1192         // remap_page_range() in cs46xx_mmap doesn't work.
1193         // 1. get index to last page in mem_map array for rawbuf.
1194         mapend = virt_to_page(dmabuf->rawbuf + 
1195                 (PAGE_SIZE << dmabuf->buforder) - 1);
1196
1197         // 2. mark each physical page in range as 'reserved'.
1198         for (map = virt_to_page(dmabuf->rawbuf); map <= mapend; map++)
1199                 cs4x_mem_map_reserve(map);
1200
1201         CS_DBGOUT(CS_PARMS, 9, printk("cs46xx: alloc_dmabuf(): allocated %ld (order = %d) bytes at %p\n",
1202                PAGE_SIZE << order, order, rawbuf) );
1203
1204 /*
1205 *  only allocate the conversion buffer for the ADC
1206 */
1207         if(dmabuf->type == CS_TYPE_DAC)
1208         {
1209                 dmabuf->tmpbuff = NULL;
1210                 dmabuf->buforder_tmpbuff = 0;
1211                 return 0;
1212         }
1213 /*
1214  * now the temp buffer for 16/8 conversions
1215  */
1216
1217         tmpbuff = (void *) pci_alloc_consistent(
1218                 card->pci_dev, PAGE_SIZE << order, &dmabuf->dmaaddr_tmpbuff);
1219
1220         if (!tmpbuff)
1221                 return -ENOMEM;
1222         CS_DBGOUT(CS_PARMS, 9, printk("cs46xx: allocated %ld (order = %d) bytes at %p\n",
1223                PAGE_SIZE << order, order, tmpbuff) );
1224
1225         dmabuf->tmpbuff = tmpbuff;
1226         dmabuf->buforder_tmpbuff = order;
1227         
1228         // Now mark the pages as reserved; otherwise the 
1229         // remap_page_range() in cs46xx_mmap doesn't work.
1230         // 1. get index to last page in mem_map array for rawbuf.
1231         mapend = virt_to_page(dmabuf->tmpbuff + 
1232                 (PAGE_SIZE << dmabuf->buforder_tmpbuff) - 1);
1233
1234         // 2. mark each physical page in range as 'reserved'.
1235         for (map = virt_to_page(dmabuf->tmpbuff); map <= mapend; map++)
1236                 cs4x_mem_map_reserve(map);
1237         return 0;
1238 }
1239
1240 /* free DMA buffer */
1241 static void dealloc_dmabuf(struct cs_state *state)
1242 {
1243         struct dmabuf *dmabuf = &state->dmabuf;
1244         struct page *map, *mapend;
1245
1246         if (dmabuf->rawbuf) {
1247                 // Undo prog_dmabuf()'s marking the pages as reserved 
1248                 mapend = virt_to_page(dmabuf->rawbuf + 
1249                                 (PAGE_SIZE << dmabuf->buforder) - 1);
1250                 for (map = virt_to_page(dmabuf->rawbuf); map <= mapend; map++)
1251                         cs4x_mem_map_unreserve(map);
1252                 free_dmabuf(state->card, dmabuf);
1253         }
1254
1255         if (dmabuf->tmpbuff) {
1256                 // Undo prog_dmabuf()'s marking the pages as reserved 
1257                 mapend = virt_to_page(dmabuf->tmpbuff +
1258                                 (PAGE_SIZE << dmabuf->buforder_tmpbuff) - 1);
1259                 for (map = virt_to_page(dmabuf->tmpbuff); map <= mapend; map++)
1260                         cs4x_mem_map_unreserve(map);
1261                 free_dmabuf2(state->card, dmabuf);
1262         }
1263
1264         dmabuf->rawbuf = NULL;
1265         dmabuf->tmpbuff = NULL;
1266         dmabuf->mapped = dmabuf->ready = 0;
1267         dmabuf->SGok = 0;
1268 }
1269
1270 static int __prog_dmabuf(struct cs_state *state)
1271 {
1272         struct dmabuf *dmabuf = &state->dmabuf;
1273         unsigned long flags;
1274         unsigned long allocated_pages, allocated_bytes;                     
1275         unsigned long tmp1, tmp2, fmt=0;                                           
1276         unsigned long *ptmp = (unsigned long *) dmabuf->pbuf;               
1277         unsigned long SGarray[9], nSGpages=0;                               
1278         int ret;
1279
1280         CS_DBGOUT(CS_FUNCTION, 4, printk("cs46xx: prog_dmabuf()+ \n"));
1281 /*
1282  * check for CAPTURE and use only non-sg for initial release
1283  */
1284         if(dmabuf->type == CS_TYPE_ADC)
1285         {
1286                 CS_DBGOUT(CS_FUNCTION, 4, printk("cs46xx: prog_dmabuf() ADC\n"));
1287                 /* 
1288                  * add in non-sg support for capture.
1289                  */
1290                 spin_lock_irqsave(&state->card->lock, flags);
1291         /* add code to reset the rawbuf memory. TRW */
1292                 resync_dma_ptrs(state);
1293                 dmabuf->total_bytes = dmabuf->blocks = 0;
1294                 dmabuf->count = dmabuf->error = dmabuf->underrun = 0;
1295
1296                 dmabuf->SGok = 0;                                                   
1297
1298                 spin_unlock_irqrestore(&state->card->lock, flags);
1299
1300                 /* allocate DMA buffer if not allocated yet */
1301                 if (!dmabuf->rawbuf || !dmabuf->tmpbuff)
1302                         if ((ret = alloc_dmabuf(state)))
1303                                 return ret; 
1304         /*
1305          * static image only supports 16Bit signed, stereo - hard code fmt
1306          */
1307                 fmt = CS_FMT_16BIT | CS_FMT_STEREO;
1308
1309                 dmabuf->numfrag = 2;                                        
1310                 dmabuf->fragsize = 2048;                                    
1311                 dmabuf->fragsamples = 2048 >> sample_shift[fmt];    
1312                 dmabuf->dmasize = 4096;                                     
1313                 dmabuf->fragshift = 11;                                     
1314
1315                 memset(dmabuf->rawbuf, (fmt & CS_FMT_16BIT) ? 0 : 0x80,
1316                        dmabuf->dmasize);
1317                 memset(dmabuf->tmpbuff, (fmt & CS_FMT_16BIT) ? 0 : 0x80, 
1318                         PAGE_SIZE<<dmabuf->buforder_tmpbuff);      
1319
1320                 /*
1321                  *      Now set up the ring
1322                  */
1323
1324                 spin_lock_irqsave(&state->card->lock, flags);
1325                 cs_rec_setup(state);
1326                 spin_unlock_irqrestore(&state->card->lock, flags);
1327
1328                 /* set the ready flag for the dma buffer */
1329                 dmabuf->ready = 1;
1330
1331                 CS_DBGOUT(CS_PARMS, 4, printk(
1332                         "cs46xx: prog_dmabuf(): CAPTURE rate=%d fmt=0x%x numfrag=%d "
1333                         "fragsize=%d dmasize=%d\n",
1334                             dmabuf->rate, dmabuf->fmt, dmabuf->numfrag,
1335                             dmabuf->fragsize, dmabuf->dmasize) );
1336
1337                 CS_DBGOUT(CS_FUNCTION, 4, printk("cs46xx: prog_dmabuf()- 0 \n"));
1338                 return 0;
1339         }
1340         else if (dmabuf->type == CS_TYPE_DAC)
1341         {
1342         /*
1343          * Must be DAC
1344          */
1345                 CS_DBGOUT(CS_FUNCTION, 4, printk("cs46xx: prog_dmabuf() DAC\n"));
1346                 spin_lock_irqsave(&state->card->lock, flags);
1347                 resync_dma_ptrs(state);
1348                 dmabuf->total_bytes = dmabuf->blocks = 0;
1349                 dmabuf->count = dmabuf->error = dmabuf->underrun = 0;
1350
1351                 dmabuf->SGok = 0;                                                   
1352
1353                 spin_unlock_irqrestore(&state->card->lock, flags);
1354
1355                 /* allocate DMA buffer if not allocated yet */
1356                 if (!dmabuf->rawbuf)
1357                         if ((ret = alloc_dmabuf(state)))
1358                                 return ret;
1359
1360                 allocated_pages = 1 << dmabuf->buforder;                            
1361                 allocated_bytes = allocated_pages*PAGE_SIZE;                        
1362                                                                                     
1363                 if(allocated_pages < 2)                                             
1364                 {
1365                         CS_DBGOUT(CS_FUNCTION, 4, printk(
1366                             "cs46xx: prog_dmabuf() Error: allocated_pages too small (%d)\n",
1367                                 (unsigned)allocated_pages));
1368                         return -ENOMEM;
1369                 }
1370                                                                                     
1371                 /* Use all the pages allocated, fragsize 4k. */
1372                 /* Use 'pbuf' for S/G page map table. */
1373                 dmabuf->SGok = 1;           /* Use S/G. */
1374
1375                 nSGpages = allocated_bytes/4096;    /* S/G pages always 4k. */
1376                                                                                     
1377                      /* Set up S/G variables. */
1378                 *ptmp = virt_to_bus(dmabuf->rawbuf);                                
1379                 *(ptmp+1) = 0x00000008;                                             
1380                 for(tmp1= 1; tmp1 < nSGpages; tmp1++) {                             
1381                         *(ptmp+2*tmp1) = virt_to_bus( (dmabuf->rawbuf)+4096*tmp1);  
1382                         if( tmp1 == nSGpages-1)                                     
1383                                 tmp2 = 0xbfff0000;
1384                         else                                                        
1385                                 tmp2 = 0x80000000+8*(tmp1+1);                       
1386                         *(ptmp+2*tmp1+1) = tmp2;                                    
1387                 }                                                                   
1388                 SGarray[0] = 0x82c0200d;                                            
1389                 SGarray[1] = 0xffff0000;                                            
1390                 SGarray[2] = *ptmp;                                                 
1391                 SGarray[3] = 0x00010600;                                            
1392                 SGarray[4] = *(ptmp+2);                                             
1393                 SGarray[5] = 0x80000010;                                            
1394                 SGarray[6] = *ptmp;                                                 
1395                 SGarray[7] = *(ptmp+2);                                             
1396                 SGarray[8] = (virt_to_bus(dmabuf->pbuf) & 0xffff000) | 0x10;        
1397
1398                 if (dmabuf->SGok) {                                                 
1399                         dmabuf->numfrag = nSGpages;                                 
1400                         dmabuf->fragsize = 4096;                                    
1401                         dmabuf->fragsamples = 4096 >> sample_shift[dmabuf->fmt];    
1402                         dmabuf->fragshift = 12;                                     
1403                         dmabuf->dmasize = dmabuf->numfrag*4096;                     
1404                 }                                                                   
1405                 else {                                                              
1406                         SGarray[0] = 0xf2c0000f;                                    
1407                         SGarray[1] = 0x00000200;                                    
1408                         SGarray[2] = 0;                                             
1409                         SGarray[3] = 0x00010600;                                    
1410                         SGarray[4]=SGarray[5]=SGarray[6]=SGarray[7]=SGarray[8] = 0; 
1411                         dmabuf->numfrag = 2;                                        
1412                         dmabuf->fragsize = 2048;                                    
1413                         dmabuf->fragsamples = 2048 >> sample_shift[dmabuf->fmt];    
1414                         dmabuf->dmasize = 4096;                                     
1415                         dmabuf->fragshift = 11;                                     
1416                 }
1417                 for(tmp1 = 0; tmp1 < sizeof(SGarray)/4; tmp1++)                     
1418                         cs461x_poke( state->card, BA1_PDTC+tmp1*4, SGarray[tmp1]);  
1419
1420                 memset(dmabuf->rawbuf, (dmabuf->fmt & CS_FMT_16BIT) ? 0 : 0x80,
1421                        dmabuf->dmasize);
1422
1423                 /*
1424                  *      Now set up the ring
1425                  */
1426
1427                 spin_lock_irqsave(&state->card->lock, flags);
1428                 cs_play_setup(state);
1429                 spin_unlock_irqrestore(&state->card->lock, flags);
1430
1431                 /* set the ready flag for the dma buffer */
1432                 dmabuf->ready = 1;
1433
1434                 CS_DBGOUT(CS_PARMS, 4, printk(
1435                         "cs46xx: prog_dmabuf(): PLAYBACK rate=%d fmt=0x%x numfrag=%d "
1436                         "fragsize=%d dmasize=%d\n",
1437                             dmabuf->rate, dmabuf->fmt, dmabuf->numfrag,
1438                             dmabuf->fragsize, dmabuf->dmasize) );
1439
1440                 CS_DBGOUT(CS_FUNCTION, 4, printk("cs46xx: prog_dmabuf()- \n"));
1441                 return 0;
1442         }
1443         else
1444         {
1445                 CS_DBGOUT(CS_FUNCTION, 4, printk("cs46xx: prog_dmabuf()- Invalid Type %d\n",
1446                         dmabuf->type));
1447         }
1448         return 1;
1449 }
1450
1451 static int prog_dmabuf(struct cs_state *state)
1452 {
1453         int ret;
1454         
1455         down(&state->sem);
1456         ret = __prog_dmabuf(state);
1457         up(&state->sem);
1458         
1459         return ret;
1460 }
1461
1462 static void cs_clear_tail(struct cs_state *state)
1463 {
1464 }
1465
1466 static int drain_dac(struct cs_state *state, int nonblock)
1467 {
1468         DECLARE_WAITQUEUE(wait, current);
1469         struct dmabuf *dmabuf = &state->dmabuf;
1470         struct cs_card *card=state->card;
1471         unsigned long flags;
1472         unsigned long tmo;
1473         int count;
1474
1475         CS_DBGOUT(CS_FUNCTION, 4, printk("cs46xx: drain_dac()+ \n"));
1476         if (dmabuf->mapped || !dmabuf->ready)
1477         {
1478                 CS_DBGOUT(CS_FUNCTION, 4, printk("cs46xx: drain_dac()- 0, not ready\n"));
1479                 return 0;
1480         }
1481
1482         add_wait_queue(&dmabuf->wait, &wait);
1483         for (;;) {
1484                 /* It seems that we have to set the current state to TASK_INTERRUPTIBLE
1485                    every time to make the process really go to sleep */
1486                 current->state = TASK_INTERRUPTIBLE;
1487
1488                 spin_lock_irqsave(&state->card->lock, flags);
1489                 count = dmabuf->count;
1490                 spin_unlock_irqrestore(&state->card->lock, flags);
1491
1492                 if (count <= 0)
1493                         break;
1494
1495                 if (signal_pending(current))
1496                         break;
1497
1498                 if (nonblock) {
1499                         remove_wait_queue(&dmabuf->wait, &wait);
1500                         current->state = TASK_RUNNING;
1501                         return -EBUSY;
1502                 }
1503
1504                 tmo = (dmabuf->dmasize * HZ) / dmabuf->rate;
1505                 tmo >>= sample_shift[dmabuf->fmt];
1506                 tmo += (2048*HZ)/dmabuf->rate;
1507                 
1508                 if (!schedule_timeout(tmo ? tmo : 1) && tmo){
1509                         printk(KERN_ERR "cs46xx: drain_dac, dma timeout? %d\n", count);
1510                         break;
1511                 }
1512         }
1513         remove_wait_queue(&dmabuf->wait, &wait);
1514         current->state = TASK_RUNNING;
1515         if (signal_pending(current))
1516         {
1517                 CS_DBGOUT(CS_FUNCTION, 4, printk("cs46xx: drain_dac()- -ERESTARTSYS\n"));
1518                 /*
1519                 * set to silence and let that clear the fifos.
1520                 */
1521                 cs461x_clear_serial_FIFOs(card, CS_TYPE_DAC);
1522                 return -ERESTARTSYS;
1523         }
1524
1525         CS_DBGOUT(CS_FUNCTION, 4, printk("cs46xx: drain_dac()- 0\n"));
1526         return 0;
1527 }
1528
1529
1530 /* update buffer manangement pointers, especially, dmabuf->count and dmabuf->hwptr */
1531 static void cs_update_ptr(struct cs_card *card, int wake)
1532 {
1533         struct cs_state *state;
1534         struct dmabuf *dmabuf;
1535         unsigned hwptr;
1536         int diff;
1537
1538         /* error handling and process wake up for ADC */
1539         state = card->states[0];
1540         if(state)
1541         {
1542                 dmabuf = &state->dmabuf;
1543                 if (dmabuf->enable & ADC_RUNNING) {
1544                         /* update hardware pointer */
1545                         hwptr = cs_get_dma_addr(state);
1546
1547                         diff = (dmabuf->dmasize + hwptr - dmabuf->hwptr) % dmabuf->dmasize;
1548                         CS_DBGOUT(CS_PARMS, 9, printk(
1549                                 "cs46xx: cs_update_ptr()+ ADC hwptr=%d diff=%d\n", 
1550                                 hwptr,diff) );
1551                         dmabuf->hwptr = hwptr;
1552                         dmabuf->total_bytes += diff;
1553                         dmabuf->count += diff;
1554                         if (dmabuf->count > dmabuf->dmasize)
1555                                 dmabuf->count = dmabuf->dmasize;
1556
1557                         if(dmabuf->mapped)
1558                         {
1559                                 if (wake && dmabuf->count >= (signed)dmabuf->fragsize)
1560                                         wake_up(&dmabuf->wait);
1561                         } else 
1562                         {
1563                                 if (wake && dmabuf->count > 0)
1564                                         wake_up(&dmabuf->wait);
1565                         }
1566                 }
1567         }
1568
1569 /*
1570  * Now the DAC
1571  */
1572         state = card->states[1];
1573         if(state)
1574         {
1575                 dmabuf = &state->dmabuf;
1576                 /* error handling and process wake up for DAC */
1577                 if (dmabuf->enable & DAC_RUNNING) {
1578                         /* update hardware pointer */
1579                         hwptr = cs_get_dma_addr(state);
1580
1581                         diff = (dmabuf->dmasize + hwptr - dmabuf->hwptr) % dmabuf->dmasize;
1582                         CS_DBGOUT(CS_PARMS, 9, printk(
1583                                 "cs46xx: cs_update_ptr()+ DAC hwptr=%d diff=%d\n", 
1584                                 hwptr,diff) );
1585                         dmabuf->hwptr = hwptr;
1586                         dmabuf->total_bytes += diff;
1587                         if (dmabuf->mapped) {
1588                                 dmabuf->count += diff;
1589                                 if (wake && dmabuf->count >= (signed)dmabuf->fragsize)
1590                                         wake_up(&dmabuf->wait);
1591                                 /*
1592                                  * other drivers use fragsize, but don't see any sense
1593                                  * in that, since dmasize is the buffer asked for
1594                                  * via mmap.
1595                                  */
1596                                 if( dmabuf->count > dmabuf->dmasize)
1597                                         dmabuf->count &= dmabuf->dmasize-1;
1598                         } else {
1599                                 dmabuf->count -= diff;
1600                                 /*
1601                                  * backfill with silence and clear out the last 
1602                                  * "diff" number of bytes.
1603                                  */
1604                                 if(hwptr >= diff)
1605                                 {
1606                                         memset(dmabuf->rawbuf + hwptr - diff, 
1607                                                 (dmabuf->fmt & CS_FMT_16BIT) ? 0 : 0x80, diff);
1608                                 }
1609                                 else
1610                                 {
1611                                         memset(dmabuf->rawbuf, 
1612                                                 (dmabuf->fmt & CS_FMT_16BIT) ? 0 : 0x80,
1613                                                 (unsigned)hwptr);
1614                                         memset((void *)((unsigned)dmabuf->rawbuf + 
1615                                                         dmabuf->dmasize + hwptr - diff),
1616                                                 (dmabuf->fmt & CS_FMT_16BIT) ? 0 : 0x80, 
1617                                                 diff - hwptr); 
1618                                 }
1619
1620                                 if (dmabuf->count < 0 || dmabuf->count > dmabuf->dmasize) {
1621                                         CS_DBGOUT(CS_ERROR, 2, printk(KERN_INFO
1622                                           "cs46xx: ERROR DAC count<0 or count > dmasize (%d)\n",
1623                                                 dmabuf->count));
1624                                         /* 
1625                                         * buffer underrun or buffer overrun, reset the
1626                                         * count of bytes written back to 0.
1627                                         */
1628                                         if(dmabuf->count < 0)
1629                                                 dmabuf->underrun=1;
1630                                         dmabuf->count = 0;
1631                                         dmabuf->error++;
1632                                 }
1633                                 if (wake && dmabuf->count < (signed)dmabuf->dmasize/2)
1634                                         wake_up(&dmabuf->wait);
1635                         }
1636                 }
1637         }
1638 }
1639
1640
1641 /* hold spinlock for the following! */
1642 static void cs_handle_midi(struct cs_card *card)
1643 {
1644         unsigned char ch;
1645         int wake;
1646         unsigned temp1;
1647
1648         wake = 0;
1649         while (!(cs461x_peekBA0(card,  BA0_MIDSR) & MIDSR_RBE)) {
1650                 ch = cs461x_peekBA0(card, BA0_MIDRP);
1651                 if (card->midi.icnt < CS_MIDIINBUF) {
1652                         card->midi.ibuf[card->midi.iwr] = ch;
1653                         card->midi.iwr = (card->midi.iwr + 1) % CS_MIDIINBUF;
1654                         card->midi.icnt++;
1655                 }
1656                 wake = 1;
1657         }
1658         if (wake)
1659                 wake_up(&card->midi.iwait);
1660         wake = 0;
1661         while (!(cs461x_peekBA0(card,  BA0_MIDSR) & MIDSR_TBF) && card->midi.ocnt > 0) {
1662                 temp1 = ( card->midi.obuf[card->midi.ord] ) & 0x000000ff;
1663                 cs461x_pokeBA0(card, BA0_MIDWP,temp1);
1664                 card->midi.ord = (card->midi.ord + 1) % CS_MIDIOUTBUF;
1665                 card->midi.ocnt--;
1666                 if (card->midi.ocnt < CS_MIDIOUTBUF-16)
1667                         wake = 1;
1668         }
1669         if (wake)
1670                 wake_up(&card->midi.owait);
1671 }
1672
1673 static void cs_interrupt(int irq, void *dev_id, struct pt_regs *regs)
1674 {
1675         struct cs_card *card = (struct cs_card *)dev_id;
1676         /* Single channel card */
1677         struct cs_state *recstate = card->channel[0].state;
1678         struct cs_state *playstate = card->channel[1].state;
1679         u32 status;
1680
1681         CS_DBGOUT(CS_INTERRUPT, 9, printk("cs46xx: cs_interrupt()+ \n"));
1682
1683         spin_lock(&card->lock);
1684
1685         status = cs461x_peekBA0(card, BA0_HISR);
1686         
1687         if ((status & 0x7fffffff) == 0)
1688         {
1689                 cs461x_pokeBA0(card, BA0_HICR, HICR_CHGM|HICR_IEV);
1690                 spin_unlock(&card->lock);
1691                 return;
1692         }
1693         
1694         /*
1695          * check for playback or capture interrupt only
1696          */
1697         if( ((status & HISR_VC0) && playstate && playstate->dmabuf.ready) || 
1698             (((status & HISR_VC1) && recstate && recstate->dmabuf.ready)) )
1699         {
1700                 CS_DBGOUT(CS_INTERRUPT, 8, printk(
1701                         "cs46xx: cs_interrupt() interrupt bit(s) set (0x%x)\n",status));
1702                 cs_update_ptr(card, CS_TRUE);
1703         }
1704
1705         if( status & HISR_MIDI )
1706                 cs_handle_midi(card);
1707         
1708         /* clear 'em */
1709         cs461x_pokeBA0(card, BA0_HICR, HICR_CHGM|HICR_IEV);
1710         spin_unlock(&card->lock);
1711         CS_DBGOUT(CS_INTERRUPT, 9, printk("cs46xx: cs_interrupt()- \n"));
1712 }
1713
1714
1715 /**********************************************************************/
1716
1717 static ssize_t cs_midi_read(struct file *file, char *buffer, size_t count, loff_t *ppos)
1718 {
1719         struct cs_card *card = (struct cs_card *)file->private_data;
1720         ssize_t ret;
1721         unsigned long flags;
1722         unsigned ptr;
1723         int cnt;
1724
1725         if (ppos != &file->f_pos)
1726                 return -ESPIPE;
1727         if (!access_ok(VERIFY_WRITE, buffer, count))
1728                 return -EFAULT;
1729         ret = 0;
1730         while (count > 0) {
1731                 spin_lock_irqsave(&card->lock, flags);
1732                 ptr = card->midi.ird;
1733                 cnt = CS_MIDIINBUF - ptr;
1734                 if (card->midi.icnt < cnt)
1735                         cnt = card->midi.icnt;
1736                 spin_unlock_irqrestore(&card->lock, flags);
1737                 if (cnt > count)
1738                         cnt = count;
1739                 if (cnt <= 0) {
1740                         if (file->f_flags & O_NONBLOCK)
1741                                 return ret ? ret : -EAGAIN;
1742                         interruptible_sleep_on(&card->midi.iwait);
1743                         if (signal_pending(current))
1744                                 return ret ? ret : -ERESTARTSYS;
1745                         continue;
1746                 }
1747                 if (copy_to_user(buffer, card->midi.ibuf + ptr, cnt))
1748                         return ret ? ret : -EFAULT;
1749                 ptr = (ptr + cnt) % CS_MIDIINBUF;
1750                 spin_lock_irqsave(&card->lock, flags);
1751                 card->midi.ird = ptr;
1752                 card->midi.icnt -= cnt;
1753                 spin_unlock_irqrestore(&card->lock, flags);
1754                 count -= cnt;
1755                 buffer += cnt;
1756                 ret += cnt;
1757         }
1758         return ret;
1759 }
1760
1761
1762 static ssize_t cs_midi_write(struct file *file, const char *buffer, size_t count, loff_t *ppos)
1763 {
1764         struct cs_card *card = (struct cs_card *)file->private_data;
1765         ssize_t ret;
1766         unsigned long flags;
1767         unsigned ptr;
1768         int cnt;
1769
1770         if (ppos != &file->f_pos)
1771                 return -ESPIPE;
1772         if (!access_ok(VERIFY_READ, buffer, count))
1773                 return -EFAULT;
1774         ret = 0;
1775         while (count > 0) {
1776                 spin_lock_irqsave(&card->lock, flags);
1777                 ptr = card->midi.owr;
1778                 cnt = CS_MIDIOUTBUF - ptr;
1779                 if (card->midi.ocnt + cnt > CS_MIDIOUTBUF)
1780                         cnt = CS_MIDIOUTBUF - card->midi.ocnt;
1781                 if (cnt <= 0)
1782                         cs_handle_midi(card);
1783                 spin_unlock_irqrestore(&card->lock, flags);
1784                 if (cnt > count)
1785                         cnt = count;
1786                 if (cnt <= 0) {
1787                         if (file->f_flags & O_NONBLOCK)
1788                                 return ret ? ret : -EAGAIN;
1789                         interruptible_sleep_on(&card->midi.owait);
1790                         if (signal_pending(current))
1791                                 return ret ? ret : -ERESTARTSYS;
1792                         continue;
1793                 }
1794                 if (copy_from_user(card->midi.obuf + ptr, buffer, cnt))
1795                         return ret ? ret : -EFAULT;
1796                 ptr = (ptr + cnt) % CS_MIDIOUTBUF;
1797                 spin_lock_irqsave(&card->lock, flags);
1798                 card->midi.owr = ptr;
1799                 card->midi.ocnt += cnt;
1800                 spin_unlock_irqrestore(&card->lock, flags);
1801                 count -= cnt;
1802                 buffer += cnt;
1803                 ret += cnt;
1804                 spin_lock_irqsave(&card->lock, flags);
1805                 cs_handle_midi(card);
1806                 spin_unlock_irqrestore(&card->lock, flags);
1807         }
1808         return ret;
1809 }
1810
1811
1812 static unsigned int cs_midi_poll(struct file *file, struct poll_table_struct *wait)
1813 {
1814         struct cs_card *card = (struct cs_card *)file->private_data;
1815         unsigned long flags;
1816         unsigned int mask = 0;
1817
1818         if (file->f_flags & FMODE_WRITE)
1819                 poll_wait(file, &card->midi.owait, wait);
1820         if (file->f_flags & FMODE_READ)
1821                 poll_wait(file, &card->midi.iwait, wait);
1822         spin_lock_irqsave(&card->lock, flags);
1823         if (file->f_flags & FMODE_READ) {
1824                 if (card->midi.icnt > 0)
1825                         mask |= POLLIN | POLLRDNORM;
1826         }
1827         if (file->f_flags & FMODE_WRITE) {
1828                 if (card->midi.ocnt < CS_MIDIOUTBUF)
1829                         mask |= POLLOUT | POLLWRNORM;
1830         }
1831         spin_unlock_irqrestore(&card->lock, flags);
1832         return mask;
1833 }
1834
1835
1836 static int cs_midi_open(struct inode *inode, struct file *file)
1837 {
1838         int minor = MINOR(inode->i_rdev);
1839         struct cs_card *card=NULL;
1840         unsigned long flags;
1841         struct list_head *entry;
1842
1843         list_for_each(entry, &cs46xx_devs)
1844         {
1845                 card = list_entry(entry, struct cs_card, list);
1846                 if (card->dev_midi == minor)
1847                         break;
1848         }
1849
1850         if (entry == &cs46xx_devs)
1851                 return -ENODEV;
1852         if (!card)
1853         {
1854                 CS_DBGOUT(CS_FUNCTION | CS_OPEN, 2, printk(KERN_INFO
1855                         "cs46xx: cs46xx_midi_open(): Error - unable to find card struct\n"));
1856                 return -ENODEV;
1857         }
1858
1859         file->private_data = card;
1860         /* wait for device to become free */
1861         down(&card->midi.open_sem);
1862         while (card->midi.open_mode & file->f_mode) {
1863                 if (file->f_flags & O_NONBLOCK) {
1864                         up(&card->midi.open_sem);
1865                         return -EBUSY;
1866                 }
1867                 up(&card->midi.open_sem);
1868                 interruptible_sleep_on(&card->midi.open_wait);
1869                 if (signal_pending(current))
1870                         return -ERESTARTSYS;
1871                 down(&card->midi.open_sem);
1872         }
1873         spin_lock_irqsave(&card->midi.lock, flags);
1874         if (!(card->midi.open_mode & (FMODE_READ | FMODE_WRITE))) {
1875                 card->midi.ird = card->midi.iwr = card->midi.icnt = 0;
1876                 card->midi.ord = card->midi.owr = card->midi.ocnt = 0;
1877                 card->midi.ird = card->midi.iwr = card->midi.icnt = 0;
1878                 cs461x_pokeBA0(card, BA0_MIDCR, 0x0000000f);            /* Enable xmit, rcv. */
1879                 cs461x_pokeBA0(card, BA0_HICR, HICR_IEV | HICR_CHGM);   /* Enable interrupts */
1880         }
1881         if (file->f_mode & FMODE_READ) {
1882                 card->midi.ird = card->midi.iwr = card->midi.icnt = 0;
1883         }
1884         if (file->f_mode & FMODE_WRITE) {
1885                 card->midi.ord = card->midi.owr = card->midi.ocnt = 0;
1886         }
1887         spin_unlock_irqrestore(&card->midi.lock, flags);
1888         card->midi.open_mode |= (file->f_mode & (FMODE_READ | FMODE_WRITE));
1889         up(&card->midi.open_sem);
1890         MOD_INC_USE_COUNT;
1891         return 0;
1892 }
1893
1894
1895 static int cs_midi_release(struct inode *inode, struct file *file)
1896 {
1897         struct cs_card *card = (struct cs_card *)file->private_data;
1898         DECLARE_WAITQUEUE(wait, current);
1899         unsigned long flags;
1900         unsigned count, tmo;
1901
1902         if (file->f_mode & FMODE_WRITE) {
1903                 current->state = TASK_INTERRUPTIBLE;
1904                 add_wait_queue(&card->midi.owait, &wait);
1905                 for (;;) {
1906                         spin_lock_irqsave(&card->midi.lock, flags);
1907                         count = card->midi.ocnt;
1908                         spin_unlock_irqrestore(&card->midi.lock, flags);
1909                         if (count <= 0)
1910                                 break;
1911                         if (signal_pending(current))
1912                                 break;
1913                         if (file->f_flags & O_NONBLOCK) {
1914                                 remove_wait_queue(&card->midi.owait, &wait);
1915                                 current->state = TASK_RUNNING;
1916                                 return -EBUSY;
1917                         }                      
1918                         tmo = (count * HZ) / 3100;
1919                         if (!schedule_timeout(tmo ? : 1) && tmo)
1920                                 printk(KERN_DEBUG "cs46xx: midi timed out??\n");
1921                 }
1922                 remove_wait_queue(&card->midi.owait, &wait);
1923                 current->state = TASK_RUNNING;
1924         }
1925         down(&card->midi.open_sem);
1926         card->midi.open_mode &= (~(file->f_mode & (FMODE_READ | FMODE_WRITE)));
1927         up(&card->midi.open_sem);
1928         wake_up(&card->midi.open_wait);
1929         MOD_DEC_USE_COUNT;
1930         return 0;
1931 }
1932
1933 /*
1934  *   Midi file operations struct.
1935  */
1936 static /*const*/ struct file_operations cs_midi_fops = {
1937         CS_OWNER        CS_THIS_MODULE
1938         llseek:         no_llseek,
1939         read:           cs_midi_read,
1940         write:          cs_midi_write,
1941         poll:           cs_midi_poll,
1942         open:           cs_midi_open,
1943         release:        cs_midi_release,
1944 };
1945
1946 /*
1947  *
1948  * CopySamples copies 16-bit stereo signed samples from the source to the
1949  * destination, possibly converting down to unsigned 8-bit and/or mono.
1950  * count specifies the number of output bytes to write.
1951  *
1952  *  Arguments:
1953  *
1954  *  dst             - Pointer to a destination buffer.
1955  *  src             - Pointer to a source buffer
1956  *  count           - The number of bytes to copy into the destination buffer.
1957  *  fmt             - CS_FMT_16BIT and/or CS_FMT_STEREO bits
1958  *  dmabuf          - pointer to the dma buffer structure
1959  *
1960  * NOTES: only call this routine if the output desired is not 16 Signed Stereo
1961  *      
1962  *
1963  */
1964 static void CopySamples(char *dst, char *src, int count, unsigned fmt, 
1965                 struct dmabuf *dmabuf)
1966 {
1967
1968     s32 s32AudioSample;
1969     s16 *psSrc=(s16 *)src;
1970     s16 *psDst=(s16 *)dst;
1971     u8 *pucDst=(u8 *)dst;
1972
1973     CS_DBGOUT(CS_FUNCTION, 2, printk(KERN_INFO "cs46xx: CopySamples()+ ") );
1974     CS_DBGOUT(CS_WAVE_READ, 8, printk(KERN_INFO
1975         " dst=0x%x src=0x%x count=%d fmt=0x%x\n",
1976         (unsigned)dst,(unsigned)src,(unsigned)count,(unsigned)fmt) );
1977
1978     /*
1979      * See if the data should be output as 8-bit unsigned stereo.
1980      */
1981     if((fmt & CS_FMT_STEREO) && !(fmt & CS_FMT_16BIT))
1982     {
1983         /*
1984          * Convert each 16-bit signed stereo sample to 8-bit unsigned 
1985          * stereo using rounding.
1986          */
1987         psSrc = (s16 *)src;
1988         count = count/2;
1989         while(count--)
1990         {
1991             *(pucDst++) = (u8)(((s16)(*psSrc++) + (s16)0x8000) >> 8);
1992         }
1993     }
1994     /*
1995      * See if the data should be output at 8-bit unsigned mono.
1996      */
1997     else if(!(fmt & CS_FMT_STEREO) && !(fmt & CS_FMT_16BIT))
1998     {
1999         /*
2000          * Convert each 16-bit signed stereo sample to 8-bit unsigned 
2001          * mono using averaging and rounding.
2002          */
2003         psSrc = (s16 *)src;
2004         count = count/2;
2005         while(count--)
2006         {
2007             s32AudioSample = ((*psSrc)+(*(psSrc + 1)))/2 + (s32)0x80;
2008             if(s32AudioSample > 0x7fff)
2009                 s32AudioSample = 0x7fff;
2010             *(pucDst++) = (u8)(((s16)s32AudioSample + (s16)0x8000) >> 8);
2011             psSrc += 2;
2012         }
2013     }
2014     /*
2015      * See if the data should be output at 16-bit signed mono.
2016      */
2017     else if(!(fmt & CS_FMT_STEREO) && (fmt & CS_FMT_16BIT))
2018     {
2019         /*
2020          * Convert each 16-bit signed stereo sample to 16-bit signed 
2021          * mono using averaging.
2022          */
2023         psSrc = (s16 *)src;
2024         count = count/2;
2025         while(count--)
2026         {
2027             *(psDst++) = (s16)((*psSrc)+(*(psSrc + 1)))/2;
2028             psSrc += 2;
2029         }
2030     }
2031 }
2032
2033 /*
2034  * cs_copy_to_user()
2035  * replacement for the standard copy_to_user, to allow for a conversion from
2036  * 16 bit to 8 bit and from stereo to mono, if the record conversion is active.  
2037  * The current CS46xx/CS4280 static image only records in 16bit unsigned Stereo, 
2038  * so we convert from any of the other format combinations.
2039  */
2040 static unsigned cs_copy_to_user(
2041         struct cs_state *s, 
2042         void *dest, 
2043         void *hwsrc, 
2044         unsigned cnt, 
2045         unsigned *copied)
2046 {
2047         struct dmabuf *dmabuf = &s->dmabuf;
2048         void *src = hwsrc;  /* default to the standard destination buffer addr */
2049
2050         CS_DBGOUT(CS_FUNCTION, 6, printk(KERN_INFO 
2051                 "cs_copy_to_user()+ fmt=0x%x cnt=%d dest=0x%.8x\n",
2052                 dmabuf->fmt,(unsigned)cnt,(unsigned)dest) );
2053
2054         if(cnt > dmabuf->dmasize)
2055         {
2056                 cnt = dmabuf->dmasize;
2057         }
2058         if(!cnt)
2059         {
2060                 *copied = 0;
2061                 return 0;
2062         }
2063         if(dmabuf->divisor != 1)
2064         {
2065                 if(!dmabuf->tmpbuff)
2066                 {
2067                         *copied = cnt/dmabuf->divisor;
2068                         return 0;
2069                 }
2070
2071                 CopySamples((char *)dmabuf->tmpbuff, (char *)hwsrc, cnt, 
2072                         dmabuf->fmt, dmabuf);
2073                 src = dmabuf->tmpbuff;
2074                 cnt = cnt/dmabuf->divisor;
2075         }
2076         if (copy_to_user(dest, src, cnt))
2077         {
2078                 CS_DBGOUT(CS_FUNCTION, 2, printk(KERN_ERR 
2079                         "cs46xx: cs_copy_to_user()- fault dest=0x%x src=0x%x cnt=%d\n",
2080                                 (unsigned)dest,(unsigned)src,cnt) );
2081                 *copied = 0;
2082                 return -EFAULT;
2083         }
2084         *copied = cnt;
2085         CS_DBGOUT(CS_FUNCTION, 2, printk(KERN_INFO 
2086                 "cs46xx: cs_copy_to_user()- copied bytes is %d \n",cnt) );
2087         return 0;
2088 }
2089
2090 /* in this loop, dmabuf.count signifies the amount of data that is waiting to be copied to
2091    the user's buffer.  it is filled by the dma machine and drained by this loop. */
2092 static ssize_t cs_read(struct file *file, char *buffer, size_t count, loff_t *ppos)
2093 {
2094         struct cs_card *card = (struct cs_card *) file->private_data;
2095         struct cs_state *state;
2096         DECLARE_WAITQUEUE(wait, current);
2097         struct dmabuf *dmabuf;
2098         ssize_t ret = 0;
2099         unsigned long flags;
2100         unsigned swptr;
2101         int cnt;
2102         unsigned copied=0;
2103
2104         CS_DBGOUT(CS_WAVE_READ | CS_FUNCTION, 4, 
2105                 printk("cs46xx: cs_read()+ %d\n",count) );
2106         state = (struct cs_state *)card->states[0];
2107         if(!state)
2108                 return -ENODEV;
2109         dmabuf = &state->dmabuf;
2110
2111         if (ppos != &file->f_pos)
2112                 return -ESPIPE;
2113         if (dmabuf->mapped)
2114                 return -ENXIO;
2115         if (!access_ok(VERIFY_WRITE, buffer, count))
2116                 return -EFAULT;
2117         
2118         down(&state->sem);
2119         if (!dmabuf->ready && (ret = __prog_dmabuf(state)))
2120                 goto out;
2121
2122         add_wait_queue(&state->dmabuf.wait, &wait);
2123         while (count > 0) {
2124                 while(!(card->pm.flags & CS46XX_PM_IDLE))
2125                 {
2126                         schedule();
2127                         if (signal_pending(current)) {
2128                                 if(!ret) ret = -ERESTARTSYS;
2129                                 goto out;
2130                         }
2131                 }
2132                 spin_lock_irqsave(&state->card->lock, flags);
2133                 swptr = dmabuf->swptr;
2134                 cnt = dmabuf->dmasize - swptr;
2135                 if (dmabuf->count < cnt)
2136                         cnt = dmabuf->count;
2137                 if (cnt <= 0)
2138                         __set_current_state(TASK_INTERRUPTIBLE);
2139                 spin_unlock_irqrestore(&state->card->lock, flags);
2140
2141                 if (cnt > (count * dmabuf->divisor))
2142                         cnt = count * dmabuf->divisor;
2143                 if (cnt <= 0) {
2144                         /* buffer is empty, start the dma machine and wait for data to be
2145                            recorded */
2146                         start_adc(state);
2147                         if (file->f_flags & O_NONBLOCK) {
2148                                 if (!ret) ret = -EAGAIN;
2149                                 goto out;
2150                         }
2151                         up(&state->sem);
2152                         schedule();
2153                         if (signal_pending(current)) {
2154                                 if(!ret) ret = -ERESTARTSYS;
2155                                 goto out;
2156                         }
2157                         down(&state->sem);
2158                         if (dmabuf->mapped) 
2159                         {
2160                                 if(!ret)
2161                                         ret = -ENXIO;
2162                                 goto out;
2163                         }
2164                         continue;
2165                 }
2166
2167                 CS_DBGOUT(CS_WAVE_READ, 2, printk(KERN_INFO 
2168                         "_read() copy_to cnt=%d count=%d ", cnt,count) );
2169                 CS_DBGOUT(CS_WAVE_READ, 8, printk(KERN_INFO 
2170                         " .dmasize=%d .count=%d buffer=0x%.8x ret=%d\n",
2171                         dmabuf->dmasize,dmabuf->count,(unsigned)buffer,ret) );
2172
2173                 if (cs_copy_to_user(state, buffer, 
2174                         (void *)((unsigned)dmabuf->rawbuf + swptr), cnt, &copied))
2175                 {
2176                         if (!ret) ret = -EFAULT;
2177                         goto out;
2178                 }
2179                 swptr = (swptr + cnt) % dmabuf->dmasize;
2180                 spin_lock_irqsave(&card->lock, flags);
2181                 dmabuf->swptr = swptr;
2182                 dmabuf->count -= cnt;
2183                 spin_unlock_irqrestore(&card->lock, flags);
2184                 count -= copied;
2185                 buffer += copied;
2186                 ret += copied;
2187                 start_adc(state);
2188         }
2189 out:
2190         up(&state->sem);
2191         remove_wait_queue(&state->dmabuf.wait, &wait);
2192         set_current_state(TASK_RUNNING);
2193         CS_DBGOUT(CS_WAVE_READ | CS_FUNCTION, 4, 
2194                 printk("cs46xx: cs_read()- %d\n",ret) );
2195         return ret;
2196 }
2197
2198 /* in this loop, dmabuf.count signifies the amount of data that is waiting to be dma to
2199    the soundcard.  it is drained by the dma machine and filled by this loop. */
2200 static ssize_t cs_write(struct file *file, const char *buffer, size_t count, loff_t *ppos)
2201 {
2202         struct cs_card *card = (struct cs_card *) file->private_data;
2203         struct cs_state *state;
2204         DECLARE_WAITQUEUE(wait, current);
2205         struct dmabuf *dmabuf;
2206         ssize_t ret;
2207         unsigned long flags;
2208         unsigned swptr;
2209         int cnt;
2210
2211         CS_DBGOUT(CS_WAVE_WRITE | CS_FUNCTION, 4,
2212                 printk("cs46xx: cs_write called, count = %d\n", count) );
2213         state = (struct cs_state *)card->states[1];
2214         if(!state)
2215                 return -ENODEV;
2216         dmabuf = &state->dmabuf;
2217
2218         if (ppos != &file->f_pos)
2219                 return -ESPIPE;
2220
2221         down(&state->sem);
2222         if (dmabuf->mapped)
2223         {
2224                 ret = -ENXIO;
2225                 goto out;
2226         }
2227
2228         if (!dmabuf->ready && (ret = __prog_dmabuf(state)))
2229                 goto out;
2230         if (!access_ok(VERIFY_READ, buffer, count))
2231         {
2232         ret = -EFAULT;
2233         goto out;
2234         }
2235         add_wait_queue(&state->dmabuf.wait, &wait);
2236         ret = 0;
2237 /*
2238 * Start the loop to read from the user's buffer and write to the dma buffer.
2239 * check for PM events and underrun/overrun in the loop.
2240 */
2241         while (count > 0) {
2242                 while(!(card->pm.flags & CS46XX_PM_IDLE))
2243                 {
2244                         schedule();
2245                         if (signal_pending(current)) {
2246                                 if(!ret) ret = -ERESTARTSYS;
2247                                 goto out;
2248                         }
2249                 }
2250                 spin_lock_irqsave(&state->card->lock, flags);
2251                 if (dmabuf->count < 0) {
2252                         /* buffer underrun, we are recovering from sleep_on_timeout,
2253                            resync hwptr and swptr */
2254                         dmabuf->count = 0;
2255                         dmabuf->swptr = dmabuf->hwptr;
2256                 }
2257                 if (dmabuf->underrun)
2258                 {
2259                         dmabuf->underrun = 0;
2260                         dmabuf->hwptr = cs_get_dma_addr(state);
2261                         dmabuf->swptr = dmabuf->hwptr;
2262                 }
2263
2264                 swptr = dmabuf->swptr;
2265                 cnt = dmabuf->dmasize - swptr;
2266                 if (dmabuf->count + cnt > dmabuf->dmasize)
2267                         cnt = dmabuf->dmasize - dmabuf->count;
2268                 if (cnt <= 0)
2269                         __set_current_state(TASK_INTERRUPTIBLE);
2270                 spin_unlock_irqrestore(&state->card->lock, flags);
2271
2272                 if (cnt > count)
2273                         cnt = count;
2274                 if (cnt <= 0) {
2275                         /* buffer is full, start the dma machine and wait for data to be
2276                            played */
2277                         start_dac(state);
2278                         if (file->f_flags & O_NONBLOCK) {
2279                                 if (!ret) ret = -EAGAIN;
2280                                 goto out;
2281                         }
2282                         up(&state->sem);
2283                         schedule();
2284                         if (signal_pending(current)) {
2285                                 if(!ret) ret = -ERESTARTSYS;
2286                                 goto out;
2287                         }
2288                         down(&state->sem);
2289                         if (dmabuf->mapped)
2290                         {
2291                                 if(!ret)
2292                                         ret = -ENXIO;
2293                                 goto out;
2294                         }
2295                         continue;
2296                 }
2297                 if (copy_from_user(dmabuf->rawbuf + swptr, buffer, cnt)) {
2298                         if (!ret) ret = -EFAULT;
2299                         goto out;
2300                 }
2301                 spin_lock_irqsave(&state->card->lock, flags);
2302                 swptr = (swptr + cnt) % dmabuf->dmasize;
2303                 dmabuf->swptr = swptr;
2304                 dmabuf->count += cnt;
2305                 if(dmabuf->count > dmabuf->dmasize)
2306                 {
2307                         CS_DBGOUT(CS_WAVE_WRITE | CS_ERROR, 2, printk(
2308                             "cs46xx: cs_write() d->count > dmasize - resetting\n"));
2309                         dmabuf->count = dmabuf->dmasize;
2310                 }
2311                 dmabuf->endcleared = 0;
2312                 spin_unlock_irqrestore(&state->card->lock, flags);
2313
2314                 count -= cnt;
2315                 buffer += cnt;
2316                 ret += cnt;
2317                 start_dac(state);
2318         }
2319 out:
2320         up(&state->sem);
2321         remove_wait_queue(&state->dmabuf.wait, &wait);
2322         set_current_state(TASK_RUNNING);
2323
2324         CS_DBGOUT(CS_WAVE_WRITE | CS_FUNCTION, 2, 
2325                 printk("cs46xx: cs_write()- ret=0x%x\n", ret) );
2326         return ret;
2327 }
2328
2329 static unsigned int cs_poll(struct file *file, struct poll_table_struct *wait)
2330 {
2331         struct cs_card *card = (struct cs_card *)file->private_data;
2332         struct dmabuf *dmabuf;
2333         struct cs_state *state;
2334
2335         unsigned long flags;
2336         unsigned int mask = 0;
2337
2338         CS_DBGOUT(CS_FUNCTION, 2, printk("cs46xx: cs_poll()+ \n"));
2339         if (!(file->f_mode & (FMODE_WRITE | FMODE_READ)))
2340         {
2341                 return -EINVAL;
2342         }
2343         if (file->f_mode & FMODE_WRITE)
2344         {
2345                 state = card->states[1];
2346                 if(state)
2347                 {
2348                         dmabuf = &state->dmabuf;
2349                         poll_wait(file, &dmabuf->wait, wait);
2350                 }
2351         }
2352         if (file->f_mode & FMODE_READ)
2353         {
2354                 state = card->states[0];
2355                 if(state)
2356                 {
2357                         dmabuf = &state->dmabuf;
2358                         poll_wait(file, &dmabuf->wait, wait);
2359                 }
2360         }
2361
2362         spin_lock_irqsave(&card->lock, flags);
2363         cs_update_ptr(card, CS_FALSE);
2364         if (file->f_mode & FMODE_READ) {
2365                 state = card->states[0];
2366                 if(state)
2367                 {
2368                         dmabuf = &state->dmabuf;
2369                         if (dmabuf->count >= (signed)dmabuf->fragsize)
2370                                 mask |= POLLIN | POLLRDNORM;
2371                 }
2372         }
2373         if (file->f_mode & FMODE_WRITE) {
2374                 state = card->states[1];
2375                 if(state)
2376                 {
2377                         dmabuf = &state->dmabuf;
2378                         if (dmabuf->mapped) {
2379                                 if (dmabuf->count >= (signed)dmabuf->fragsize)
2380                                     mask |= POLLOUT | POLLWRNORM;
2381                         } else {
2382                                 if ((signed)dmabuf->dmasize >= dmabuf->count 
2383                                         + (signed)dmabuf->fragsize)
2384                                     mask |= POLLOUT | POLLWRNORM;
2385                         }
2386                 }
2387         }
2388         spin_unlock_irqrestore(&card->lock, flags);
2389
2390         CS_DBGOUT(CS_FUNCTION, 2, printk("cs46xx: cs_poll()- (0x%x) \n",
2391                 mask));
2392         return mask;
2393 }
2394
2395 /*
2396  *      We let users mmap the ring buffer. Its not the real DMA buffer but
2397  *      that side of the code is hidden in the IRQ handling. We do a software
2398  *      emulation of DMA from a 64K or so buffer into a 2K FIFO. 
2399  *      (the hardware probably deserves a moan here but Crystal send me nice
2400  *      toys ;)).
2401  */
2402  
2403 static int cs_mmap(struct file *file, struct vm_area_struct *vma)
2404 {
2405         struct cs_card *card = (struct cs_card *)file->private_data;
2406         struct cs_state *state;
2407         struct dmabuf *dmabuf;
2408         int ret = 0;
2409         unsigned long size;
2410
2411         CS_DBGOUT(CS_FUNCTION | CS_PARMS, 2, printk("cs46xx: cs_mmap()+ file=0x%x %s %s\n", 
2412                 (unsigned)file, vma->vm_flags & VM_WRITE ? "VM_WRITE" : "",
2413                 vma->vm_flags & VM_READ ? "VM_READ" : "") );
2414
2415         if (vma->vm_flags & VM_WRITE) {
2416                 state = card->states[1];
2417                 if(state)
2418                 {
2419                         CS_DBGOUT(CS_OPEN, 2, printk(
2420                           "cs46xx: cs_mmap() VM_WRITE - state TRUE prog_dmabuf DAC\n") );
2421                         if ((ret = prog_dmabuf(state)) != 0)
2422                                 return ret;
2423                 }
2424         } else if (vma->vm_flags & VM_READ) {
2425                 state = card->states[0];
2426                 if(state)
2427                 {
2428                         CS_DBGOUT(CS_OPEN, 2, printk(
2429                           "cs46xx: cs_mmap() VM_READ - state TRUE prog_dmabuf ADC\n") );
2430                         if ((ret = prog_dmabuf(state)) != 0)
2431                                 return ret;
2432                 }
2433         } else {
2434                 CS_DBGOUT(CS_ERROR, 2, printk(
2435                   "cs46xx: cs_mmap() return -EINVAL\n") );
2436                 return -EINVAL;
2437         }
2438
2439 /*
2440  * For now ONLY support playback, but seems like the only way to use
2441  * mmap() is to open an FD with RDWR, just read or just write access
2442  * does not function, get an error back from the kernel.
2443  * Also, QuakeIII opens with RDWR!  So, there must be something
2444  * to needing read/write access mapping.  So, allow read/write but 
2445  * use the DAC only.
2446  */
2447         state = card->states[1];  
2448         if(!(unsigned)state)
2449         {
2450                 ret = -EINVAL;
2451                 goto out;
2452         }
2453
2454         down(&state->sem);      
2455         dmabuf = &state->dmabuf;
2456         if (cs4x_pgoff(vma) != 0)
2457         {
2458                 ret = -EINVAL;
2459                 goto out;
2460         }
2461         size = vma->vm_end - vma->vm_start;
2462
2463         CS_DBGOUT(CS_PARMS, 2, printk("cs46xx: cs_mmap(): size=%d\n",(unsigned)size) );
2464
2465         if (size > (PAGE_SIZE << dmabuf->buforder))
2466         {
2467                 ret = -EINVAL;
2468                 goto out;
2469         }
2470         if (remap_page_range(vma->vm_start, virt_to_phys(dmabuf->rawbuf),
2471                              size, vma->vm_page_prot))
2472         {
2473                 ret = -EAGAIN;
2474                 goto out;
2475         }
2476         dmabuf->mapped = 1;
2477
2478         CS_DBGOUT(CS_FUNCTION, 2, printk("cs46xx: cs_mmap()-\n") );
2479 out:
2480         up(&state->sem);
2481         return ret;     
2482 }
2483
2484 static int cs_ioctl(struct inode *inode, struct file *file, unsigned int cmd, unsigned long arg)
2485 {
2486         struct cs_card *card = (struct cs_card *)file->private_data;
2487         struct cs_state *state;
2488         struct dmabuf *dmabuf=0;
2489         unsigned long flags;
2490         audio_buf_info abinfo;
2491         count_info cinfo;
2492         int val, valsave, mapped, ret;
2493
2494         state = (struct cs_state *)card->states[0];
2495         if(state)
2496         {
2497                 dmabuf = &state->dmabuf;
2498                 mapped = (file->f_mode & FMODE_READ) && dmabuf->mapped;
2499         }
2500         state = (struct cs_state *)card->states[1];
2501         if(state)
2502         {
2503                 dmabuf = &state->dmabuf;
2504                 mapped |= (file->f_mode & FMODE_WRITE) && dmabuf->mapped;
2505         }
2506                 
2507 #if CSDEBUG
2508         printioctl(cmd);
2509 #endif
2510
2511         switch (cmd) 
2512         {
2513         case OSS_GETVERSION:
2514                 return put_user(SOUND_VERSION, (int *)arg);
2515
2516         case SNDCTL_DSP_RESET:
2517                 /* FIXME: spin_lock ? */
2518                 if (file->f_mode & FMODE_WRITE) {
2519                         state = (struct cs_state *)card->states[1];
2520                         if(state)
2521                         {
2522                                 dmabuf = &state->dmabuf;
2523                                 stop_dac(state);
2524                                 synchronize_irq();
2525                                 dmabuf->ready = 0;
2526                                 resync_dma_ptrs(state);
2527                                 dmabuf->swptr = dmabuf->hwptr = 0;
2528                                 dmabuf->count = dmabuf->total_bytes = 0;
2529                                 dmabuf->blocks = 0;
2530                                 dmabuf->SGok = 0;
2531                         }
2532                 }
2533                 if (file->f_mode & FMODE_READ) {
2534                         state = (struct cs_state *)card->states[0];
2535                         if(state)
2536                         {
2537                                 dmabuf = &state->dmabuf;
2538                                 stop_adc(state);
2539                                 synchronize_irq();
2540                                 resync_dma_ptrs(state);
2541                                 dmabuf->ready = 0;
2542                                 dmabuf->swptr = dmabuf->hwptr = 0;
2543                                 dmabuf->count = dmabuf->total_bytes = 0;
2544                                 dmabuf->blocks = 0;
2545                                 dmabuf->SGok = 0;
2546                         }
2547                 }
2548                 CS_DBGOUT(CS_IOCTL, 2, printk("cs46xx: DSP_RESET()-\n") );
2549                 return 0;
2550
2551         case SNDCTL_DSP_SYNC:
2552                 if (file->f_mode & FMODE_WRITE)
2553                         return drain_dac(state, file->f_flags & O_NONBLOCK);
2554                 return 0;
2555
2556         case SNDCTL_DSP_SPEED: /* set sample rate */
2557                 if (get_user(val, (int *)arg))
2558                         return -EFAULT;
2559                 if (val >= 0) {
2560                         if (file->f_mode & FMODE_READ) {
2561                                 state = (struct cs_state *)card->states[0];
2562                                 if(state)
2563                                 {
2564                                         dmabuf = &state->dmabuf;
2565                                         stop_adc(state);
2566                                         dmabuf->ready = 0;
2567                                         dmabuf->SGok = 0;
2568                                         cs_set_adc_rate(state, val);
2569                                         cs_set_divisor(dmabuf);
2570                                 }
2571                         }
2572                         if (file->f_mode & FMODE_WRITE) {
2573                                 state = (struct cs_state *)card->states[1];
2574                                 if(state)
2575                                 {
2576                                         dmabuf = &state->dmabuf;
2577                                         stop_dac(state);
2578                                         dmabuf->ready = 0;
2579                                         dmabuf->SGok = 0;
2580                                         cs_set_dac_rate(state, val);
2581                                         cs_set_divisor(dmabuf);
2582                                 }
2583                         }
2584                         CS_DBGOUT(CS_IOCTL | CS_PARMS, 4, printk(
2585                             "cs46xx: cs_ioctl() DSP_SPEED %s %s %d\n",
2586                                 file->f_mode & FMODE_WRITE ? "DAC" : "",
2587                                 file->f_mode & FMODE_READ ? "ADC" : "",
2588                                 dmabuf->rate ) );
2589                         return put_user(dmabuf->rate, (int *)arg);
2590                 }
2591                 return put_user(0, (int *)arg);
2592
2593         case SNDCTL_DSP_STEREO: /* set stereo or mono channel */
2594                 if (get_user(val, (int *)arg))
2595                         return -EFAULT;
2596                 if (file->f_mode & FMODE_WRITE) {
2597                         state = (struct cs_state *)card->states[1];
2598                         if(state)
2599                         {
2600                                 dmabuf = &state->dmabuf;
2601                                 stop_dac(state);
2602                                 dmabuf->ready = 0;
2603                                 dmabuf->SGok = 0;
2604                                 if(val)
2605                                         dmabuf->fmt |= CS_FMT_STEREO;
2606                                 else
2607                                         dmabuf->fmt &= ~CS_FMT_STEREO;
2608                                 cs_set_divisor(dmabuf);
2609                                 CS_DBGOUT(CS_IOCTL | CS_PARMS, 4, printk(
2610                                     "cs46xx: DSP_STEREO() DAC %s\n",
2611                                     (dmabuf->fmt & CS_FMT_STEREO) ?
2612                                         "STEREO":"MONO") );
2613                   &