v2.4.8 -> v2.4.8.1
[opensuse:kernel.git] / drivers / sound / sonicvibes.c
1 /*****************************************************************************/
2
3 /*
4  *      sonicvibes.c  --  S3 Sonic Vibes audio driver.
5  *
6  *      Copyright (C) 1998-2001  Thomas Sailer (t.sailer@alumni.ethz.ch)
7  *
8  *      This program is free software; you can redistribute it and/or modify
9  *      it under the terms of the GNU General Public License as published by
10  *      the Free Software Foundation; either version 2 of the License, or
11  *      (at your option) any later version.
12  *
13  *      This program is distributed in the hope that it will be useful,
14  *      but WITHOUT ANY WARRANTY; without even the implied warranty of
15  *      MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16  *      GNU General Public License for more details.
17  *
18  *      You should have received a copy of the GNU General Public License
19  *      along with this program; if not, write to the Free Software
20  *      Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
21  *
22  * Special thanks to David C. Niemi
23  *
24  *
25  * Module command line parameters:
26  *   none so far
27  *
28  *
29  *  Supported devices:
30  *  /dev/dsp    standard /dev/dsp device, (mostly) OSS compatible
31  *  /dev/mixer  standard /dev/mixer device, (mostly) OSS compatible
32  *  /dev/midi   simple MIDI UART interface, no ioctl
33  *
34  *  The card has both an FM and a Wavetable synth, but I have to figure
35  *  out first how to drive them...
36  *
37  *  Revision history
38  *    06.05.1998   0.1   Initial release
39  *    10.05.1998   0.2   Fixed many bugs, esp. ADC rate calculation
40  *                       First stab at a simple midi interface (no bells&whistles)
41  *    13.05.1998   0.3   Fix stupid cut&paste error: set_adc_rate was called instead of
42  *                       set_dac_rate in the FMODE_WRITE case in sv_open
43  *                       Fix hwptr out of bounds (now mpg123 works)
44  *    14.05.1998   0.4   Don't allow excessive interrupt rates
45  *    08.06.1998   0.5   First release using Alan Cox' soundcore instead of miscdevice
46  *    03.08.1998   0.6   Do not include modversions.h
47  *                       Now mixer behaviour can basically be selected between
48  *                       "OSS documented" and "OSS actual" behaviour
49  *    31.08.1998   0.7   Fix realplayer problems - dac.count issues
50  *    10.12.1998   0.8   Fix drain_dac trying to wait on not yet initialized DMA
51  *    16.12.1998   0.9   Fix a few f_file & FMODE_ bugs
52  *    06.01.1999   0.10  remove the silly SA_INTERRUPT flag.
53  *                       hopefully killed the egcs section type conflict
54  *    12.03.1999   0.11  cinfo.blocks should be reset after GETxPTR ioctl.
55  *                       reported by Johan Maes <joma@telindus.be>
56  *    22.03.1999   0.12  return EAGAIN instead of EBUSY when O_NONBLOCK
57  *                       read/write cannot be executed
58  *    05.04.1999   0.13  added code to sv_read and sv_write which should detect
59  *                       lockups of the sound chip and revive it. This is basically
60  *                       an ugly hack, but at least applications using this driver
61  *                       won't hang forever. I don't know why these lockups happen,
62  *                       it might well be the motherboard chipset (an early 486 PCI
63  *                       board with ALI chipset), since every busmastering 100MB
64  *                       ethernet card I've tried (Realtek 8139 and Macronix tulip clone)
65  *                       exhibit similar behaviour (they work for a couple of packets
66  *                       and then lock up and can be revived by ifconfig down/up).
67  *    07.04.1999   0.14  implemented the following ioctl's: SOUND_PCM_READ_RATE, 
68  *                       SOUND_PCM_READ_CHANNELS, SOUND_PCM_READ_BITS; 
69  *                       Alpha fixes reported by Peter Jones <pjones@redhat.com>
70  *                       Note: dmaio hack might still be wrong on archs other than i386
71  *    15.06.1999   0.15  Fix bad allocation bug.
72  *                       Thanks to Deti Fliegl <fliegl@in.tum.de>
73  *    28.06.1999   0.16  Add pci_set_master
74  *    03.08.1999   0.17  adapt to Linus' new __setup/__initcall
75  *                       added kernel command line options "sonicvibes=reverb" and "sonicvibesdmaio=dmaioaddr"
76  *    12.08.1999   0.18  module_init/__setup fixes
77  *    24.08.1999   0.19  get rid of the dmaio kludge, replace with allocate_resource
78  *    31.08.1999   0.20  add spin_lock_init
79  *                       use new resource allocation to allocate DDMA IO space
80  *                       replaced current->state = x with set_current_state(x)
81  *    03.09.1999   0.21  change read semantics for MIDI to match
82  *                       OSS more closely; remove possible wakeup race
83  *    28.10.1999   0.22  More waitqueue races fixed
84  *    01.12.1999   0.23  New argument to allocate_resource
85  *    07.12.1999   0.24  More allocate_resource semantics change
86  *    08.01.2000   0.25  Prevent some ioctl's from returning bad count values on underrun/overrun;
87  *                       Tim Janik's BSE (Bedevilled Sound Engine) found this
88  *                       use Martin Mares' pci_assign_resource
89  *    07.02.2000   0.26  Use pci_alloc_consistent and pci_register_driver
90  *    21.11.2000   0.27  Initialize dma buffers in poll, otherwise poll may return a bogus mask
91  *    12.12.2000   0.28  More dma buffer initializations, patch from
92  *                       Tjeerd Mulder <tjeerd.mulder@fujitsu-siemens.com>
93  *    31.01.2001   0.29  Register/Unregister gameport
94  *                       Fix SETTRIGGER non OSS API conformity
95  *    18.05.2001   0.30  PCI probing and error values cleaned up by Marcus
96  *                       Meissner <mm@caldera.de>
97  *
98  */
99
100 /*****************************************************************************/
101       
102 #include <linux/version.h>
103 #include <linux/module.h>
104 #include <linux/string.h>
105 #include <linux/ioport.h>
106 #include <linux/sched.h>
107 #include <linux/delay.h>
108 #include <linux/sound.h>
109 #include <linux/slab.h>
110 #include <linux/soundcard.h>
111 #include <linux/pci.h>
112 #include <asm/io.h>
113 #include <asm/dma.h>
114 #include <linux/init.h>
115 #include <linux/poll.h>
116 #include <linux/spinlock.h>
117 #include <linux/smp_lock.h>
118 #include <linux/wrapper.h>
119 #include <asm/uaccess.h>
120 #include <asm/hardirq.h>
121
122 #include "dm.h"
123
124 #if defined(CONFIG_INPUT_ANALOG) || defined(CONFIG_INPUT_ANALOG_MODULE)
125 #include <linux/gameport.h>
126 #else
127 struct gameport {
128         int io;
129         int size;
130 };
131
132 extern inline void gameport_register_port(struct gameport *gameport)
133 {
134 }
135
136 extern inline void gameport_unregister_port(struct gameport *gameport)
137 {
138 }
139 #endif
140
141 /* --------------------------------------------------------------------- */
142
143 #undef OSS_DOCUMENTED_MIXER_SEMANTICS
144
145 /* --------------------------------------------------------------------- */
146
147 #ifndef PCI_VENDOR_ID_S3
148 #define PCI_VENDOR_ID_S3             0x5333
149 #endif
150 #ifndef PCI_DEVICE_ID_S3_SONICVIBES
151 #define PCI_DEVICE_ID_S3_SONICVIBES  0xca00
152 #endif
153
154 #define SV_MAGIC  ((PCI_VENDOR_ID_S3<<16)|PCI_DEVICE_ID_S3_SONICVIBES)
155
156 #define SV_EXTENT_SB      0x10
157 #define SV_EXTENT_ENH     0x10
158 #define SV_EXTENT_SYNTH   0x4
159 #define SV_EXTENT_MIDI    0x4
160 #define SV_EXTENT_GAME    0x8
161 #define SV_EXTENT_DMA     0x10
162
163 /*
164  * we are not a bridge and thus use a resource for DDMA that is used for bridges but
165  * left empty for normal devices
166  */
167 #define RESOURCE_SB       0
168 #define RESOURCE_ENH      1
169 #define RESOURCE_SYNTH    2
170 #define RESOURCE_MIDI     3
171 #define RESOURCE_GAME     4
172 #define RESOURCE_DDMA     7
173
174 #define SV_MIDI_DATA      0
175 #define SV_MIDI_COMMAND   1
176 #define SV_MIDI_STATUS    1
177
178 #define SV_DMA_ADDR0      0
179 #define SV_DMA_ADDR1      1
180 #define SV_DMA_ADDR2      2
181 #define SV_DMA_ADDR3      3
182 #define SV_DMA_COUNT0     4
183 #define SV_DMA_COUNT1     5
184 #define SV_DMA_COUNT2     6
185 #define SV_DMA_MODE       0xb
186 #define SV_DMA_RESET      0xd
187 #define SV_DMA_MASK       0xf
188
189 /*
190  * DONT reset the DMA controllers unless you understand
191  * the reset semantics. Assuming reset semantics as in
192  * the 8237 does not work.
193  */
194
195 #define DMA_MODE_AUTOINIT 0x10
196 #define DMA_MODE_READ     0x44    /* I/O to memory, no autoinit, increment, single mode */
197 #define DMA_MODE_WRITE    0x48    /* memory to I/O, no autoinit, increment, single mode */
198
199 #define SV_CODEC_CONTROL  0
200 #define SV_CODEC_INTMASK  1
201 #define SV_CODEC_STATUS   2
202 #define SV_CODEC_IADDR    4
203 #define SV_CODEC_IDATA    5
204
205 #define SV_CCTRL_RESET      0x80
206 #define SV_CCTRL_INTADRIVE  0x20
207 #define SV_CCTRL_WAVETABLE  0x08
208 #define SV_CCTRL_REVERB     0x04
209 #define SV_CCTRL_ENHANCED   0x01
210
211 #define SV_CINTMASK_DMAA    0x01
212 #define SV_CINTMASK_DMAC    0x04
213 #define SV_CINTMASK_SPECIAL 0x08
214 #define SV_CINTMASK_UPDOWN  0x40
215 #define SV_CINTMASK_MIDI    0x80
216
217 #define SV_CSTAT_DMAA       0x01
218 #define SV_CSTAT_DMAC       0x04
219 #define SV_CSTAT_SPECIAL    0x08
220 #define SV_CSTAT_UPDOWN     0x40
221 #define SV_CSTAT_MIDI       0x80
222
223 #define SV_CIADDR_TRD       0x80
224 #define SV_CIADDR_MCE       0x40
225
226 /* codec indirect registers */
227 #define SV_CIMIX_ADCINL     0x00
228 #define SV_CIMIX_ADCINR     0x01
229 #define SV_CIMIX_AUX1INL    0x02
230 #define SV_CIMIX_AUX1INR    0x03
231 #define SV_CIMIX_CDINL      0x04
232 #define SV_CIMIX_CDINR      0x05
233 #define SV_CIMIX_LINEINL    0x06
234 #define SV_CIMIX_LINEINR    0x07
235 #define SV_CIMIX_MICIN      0x08
236 #define SV_CIMIX_SYNTHINL   0x0A
237 #define SV_CIMIX_SYNTHINR   0x0B
238 #define SV_CIMIX_AUX2INL    0x0C
239 #define SV_CIMIX_AUX2INR    0x0D
240 #define SV_CIMIX_ANALOGINL  0x0E
241 #define SV_CIMIX_ANALOGINR  0x0F
242 #define SV_CIMIX_PCMINL     0x10
243 #define SV_CIMIX_PCMINR     0x11
244
245 #define SV_CIGAMECONTROL    0x09
246 #define SV_CIDATAFMT        0x12
247 #define SV_CIENABLE         0x13
248 #define SV_CIUPDOWN         0x14
249 #define SV_CIREVISION       0x15
250 #define SV_CIADCOUTPUT      0x16
251 #define SV_CIDMAABASECOUNT1 0x18
252 #define SV_CIDMAABASECOUNT0 0x19
253 #define SV_CIDMACBASECOUNT1 0x1c
254 #define SV_CIDMACBASECOUNT0 0x1d
255 #define SV_CIPCMSR0         0x1e
256 #define SV_CIPCMSR1         0x1f
257 #define SV_CISYNTHSR0       0x20
258 #define SV_CISYNTHSR1       0x21
259 #define SV_CIADCCLKSOURCE   0x22
260 #define SV_CIADCALTSR       0x23
261 #define SV_CIADCPLLM        0x24
262 #define SV_CIADCPLLN        0x25
263 #define SV_CISYNTHPLLM      0x26
264 #define SV_CISYNTHPLLN      0x27
265 #define SV_CIUARTCONTROL    0x2a
266 #define SV_CIDRIVECONTROL   0x2b
267 #define SV_CISRSSPACE       0x2c
268 #define SV_CISRSCENTER      0x2d
269 #define SV_CIWAVETABLESRC   0x2e
270 #define SV_CIANALOGPWRDOWN  0x30
271 #define SV_CIDIGITALPWRDOWN 0x31
272
273
274 #define SV_CIMIX_ADCSRC_CD     0x20
275 #define SV_CIMIX_ADCSRC_DAC    0x40
276 #define SV_CIMIX_ADCSRC_AUX2   0x60
277 #define SV_CIMIX_ADCSRC_LINE   0x80
278 #define SV_CIMIX_ADCSRC_AUX1   0xa0
279 #define SV_CIMIX_ADCSRC_MIC    0xc0
280 #define SV_CIMIX_ADCSRC_MIXOUT 0xe0
281 #define SV_CIMIX_ADCSRC_MASK   0xe0
282
283 #define SV_CFMT_STEREO     0x01
284 #define SV_CFMT_16BIT      0x02
285 #define SV_CFMT_MASK       0x03
286 #define SV_CFMT_ASHIFT     0   
287 #define SV_CFMT_CSHIFT     4
288
289 static const unsigned sample_size[] = { 1, 2, 2, 4 };
290 static const unsigned sample_shift[] = { 0, 1, 1, 2 };
291
292 #define SV_CENABLE_PPE     0x4
293 #define SV_CENABLE_RE      0x2
294 #define SV_CENABLE_PE      0x1
295
296
297 /* MIDI buffer sizes */
298
299 #define MIDIINBUF  256
300 #define MIDIOUTBUF 256
301
302 #define FMODE_MIDI_SHIFT 2
303 #define FMODE_MIDI_READ  (FMODE_READ << FMODE_MIDI_SHIFT)
304 #define FMODE_MIDI_WRITE (FMODE_WRITE << FMODE_MIDI_SHIFT)
305
306 #define FMODE_DMFM 0x10
307
308 /* --------------------------------------------------------------------- */
309
310 struct sv_state {
311         /* magic */
312         unsigned int magic;
313
314         /* list of sonicvibes devices */
315         struct list_head devs;
316
317         /* the corresponding pci_dev structure */
318         struct pci_dev *dev;
319
320         /* soundcore stuff */
321         int dev_audio;
322         int dev_mixer;
323         int dev_midi;
324         int dev_dmfm;
325
326         /* hardware resources */
327         unsigned long iosb, ioenh, iosynth, iomidi;  /* long for SPARC */
328         unsigned int iodmaa, iodmac, irq;
329
330         /* mixer stuff */
331         struct {
332                 unsigned int modcnt;
333 #ifndef OSS_DOCUMENTED_MIXER_SEMANTICS
334                 unsigned short vol[13];
335 #endif /* OSS_DOCUMENTED_MIXER_SEMANTICS */
336         } mix;
337
338         /* wave stuff */
339         unsigned int rateadc, ratedac;
340         unsigned char fmt, enable;
341
342         spinlock_t lock;
343         struct semaphore open_sem;
344         mode_t open_mode;
345         wait_queue_head_t open_wait;
346
347         struct dmabuf {
348                 void *rawbuf;
349                 dma_addr_t dmaaddr;
350                 unsigned buforder;
351                 unsigned numfrag;
352                 unsigned fragshift;
353                 unsigned hwptr, swptr;
354                 unsigned total_bytes;
355                 int count;
356                 unsigned error; /* over/underrun */
357                 wait_queue_head_t wait;
358                 /* redundant, but makes calculations easier */
359                 unsigned fragsize;
360                 unsigned dmasize;
361                 unsigned fragsamples;
362                 /* OSS stuff */
363                 unsigned mapped:1;
364                 unsigned ready:1;
365                 unsigned endcleared:1;
366                 unsigned enabled:1;
367                 unsigned ossfragshift;
368                 int ossmaxfrags;
369                 unsigned subdivision;
370         } dma_dac, dma_adc;
371
372         /* midi stuff */
373         struct {
374                 unsigned ird, iwr, icnt;
375                 unsigned ord, owr, ocnt;
376                 wait_queue_head_t iwait;
377                 wait_queue_head_t owait;
378                 struct timer_list timer;
379                 unsigned char ibuf[MIDIINBUF];
380                 unsigned char obuf[MIDIOUTBUF];
381         } midi;
382
383         struct gameport gameport;
384 };
385
386 /* --------------------------------------------------------------------- */
387
388 static LIST_HEAD(devs);
389 static unsigned long wavetable_mem = 0;
390
391 /* --------------------------------------------------------------------- */
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 /*
419  * hweightN: returns the hamming weight (i.e. the number
420  * of bits set) of a N-bit word
421  */
422
423 #ifdef hweight32
424 #undef hweight32
425 #endif
426
427 static inline unsigned int hweight32(unsigned int w)
428 {
429         unsigned int res = (w & 0x55555555) + ((w >> 1) & 0x55555555);
430         res = (res & 0x33333333) + ((res >> 2) & 0x33333333);
431         res = (res & 0x0F0F0F0F) + ((res >> 4) & 0x0F0F0F0F);
432         res = (res & 0x00FF00FF) + ((res >> 8) & 0x00FF00FF);
433         return (res & 0x0000FFFF) + ((res >> 16) & 0x0000FFFF);
434 }
435
436 /* --------------------------------------------------------------------- */
437
438 /*
439  * Why use byte IO? Nobody knows, but S3 does it also in their Windows driver.
440  */
441
442 #undef DMABYTEIO
443
444 static void set_dmaa(struct sv_state *s, unsigned int addr, unsigned int count)
445 {
446 #ifdef DMABYTEIO
447         unsigned io = s->iodmaa, u;
448
449         count--;
450         for (u = 4; u > 0; u--, addr >>= 8, io++)
451                 outb(addr & 0xff, io);
452         for (u = 3; u > 0; u--, count >>= 8, io++)
453                 outb(count & 0xff, io);
454 #else /* DMABYTEIO */
455         count--;
456         outl(addr, s->iodmaa + SV_DMA_ADDR0);
457         outl(count, s->iodmaa + SV_DMA_COUNT0);
458 #endif /* DMABYTEIO */
459         outb(0x18, s->iodmaa + SV_DMA_MODE);
460 }
461
462 static void set_dmac(struct sv_state *s, unsigned int addr, unsigned int count)
463 {
464 #ifdef DMABYTEIO
465         unsigned io = s->iodmac, u;
466
467         count >>= 1;
468         count--;
469         for (u = 4; u > 0; u--, addr >>= 8, io++)
470                 outb(addr & 0xff, io);
471         for (u = 3; u > 0; u--, count >>= 8, io++)
472                 outb(count & 0xff, io);
473 #else /* DMABYTEIO */
474         count >>= 1;
475         count--;
476         outl(addr, s->iodmac + SV_DMA_ADDR0);
477         outl(count, s->iodmac + SV_DMA_COUNT0);
478 #endif /* DMABYTEIO */
479         outb(0x14, s->iodmac + SV_DMA_MODE);
480 }
481
482 static inline unsigned get_dmaa(struct sv_state *s)
483 {
484 #ifdef DMABYTEIO
485         unsigned io = s->iodmaa+6, v = 0, u;
486
487         for (u = 3; u > 0; u--, io--) {
488                 v <<= 8;
489                 v |= inb(io);
490         }
491         return v + 1;
492 #else /* DMABYTEIO */
493         return (inl(s->iodmaa + SV_DMA_COUNT0) & 0xffffff) + 1;
494 #endif /* DMABYTEIO */
495 }
496
497 static inline unsigned get_dmac(struct sv_state *s)
498 {
499 #ifdef DMABYTEIO
500         unsigned io = s->iodmac+6, v = 0, u;
501
502         for (u = 3; u > 0; u--, io--) {
503                 v <<= 8;
504                 v |= inb(io);
505         }
506         return (v + 1) << 1;
507 #else /* DMABYTEIO */
508         return ((inl(s->iodmac + SV_DMA_COUNT0) & 0xffffff) + 1) << 1;
509 #endif /* DMABYTEIO */
510 }
511
512 static void wrindir(struct sv_state *s, unsigned char idx, unsigned char data)
513 {
514         outb(idx & 0x3f, s->ioenh + SV_CODEC_IADDR);
515         udelay(10);
516         outb(data, s->ioenh + SV_CODEC_IDATA);
517         udelay(10);
518 }
519
520 static unsigned char rdindir(struct sv_state *s, unsigned char idx)
521 {
522         unsigned char v;
523
524         outb(idx & 0x3f, s->ioenh + SV_CODEC_IADDR);
525         udelay(10);
526         v = inb(s->ioenh + SV_CODEC_IDATA);
527         udelay(10);
528         return v;
529 }
530
531 static void set_fmt(struct sv_state *s, unsigned char mask, unsigned char data)
532 {
533         unsigned long flags;
534
535         spin_lock_irqsave(&s->lock, flags);
536         outb(SV_CIDATAFMT | SV_CIADDR_MCE, s->ioenh + SV_CODEC_IADDR);
537         if (mask) {
538                 s->fmt = inb(s->ioenh + SV_CODEC_IDATA);
539                 udelay(10);
540         }
541         s->fmt = (s->fmt & mask) | data;
542         outb(s->fmt, s->ioenh + SV_CODEC_IDATA);
543         udelay(10);
544         outb(0, s->ioenh + SV_CODEC_IADDR);
545         spin_unlock_irqrestore(&s->lock, flags);
546         udelay(10);
547 }
548
549 static void frobindir(struct sv_state *s, unsigned char idx, unsigned char mask, unsigned char data)
550 {
551         outb(idx & 0x3f, s->ioenh + SV_CODEC_IADDR);
552         udelay(10);
553         outb((inb(s->ioenh + SV_CODEC_IDATA) & mask) ^ data, s->ioenh + SV_CODEC_IDATA);
554         udelay(10);
555 }
556
557 #define REFFREQUENCY  24576000
558 #define ADCMULT 512
559 #define FULLRATE 48000
560
561 static unsigned setpll(struct sv_state *s, unsigned char reg, unsigned rate)
562 {
563         unsigned long flags;
564         unsigned char r, m=0, n=0;
565         unsigned xm, xn, xr, xd, metric = ~0U;
566         /* the warnings about m and n used uninitialized are bogus and may safely be ignored */
567
568         if (rate < 625000/ADCMULT)
569                 rate = 625000/ADCMULT;
570         if (rate > 150000000/ADCMULT)
571                 rate = 150000000/ADCMULT;
572         /* slight violation of specs, needed for continuous sampling rates */
573         for (r = 0; rate < 75000000/ADCMULT; r += 0x20, rate <<= 1);
574         for (xn = 3; xn < 35; xn++)
575                 for (xm = 3; xm < 130; xm++) {
576                         xr = REFFREQUENCY/ADCMULT * xm / xn;
577                         xd = abs((signed)(xr - rate));
578                         if (xd < metric) {
579                                 metric = xd;
580                                 m = xm - 2;
581                                 n = xn - 2;
582                         }
583                 }
584         reg &= 0x3f;
585         spin_lock_irqsave(&s->lock, flags);
586         outb(reg, s->ioenh + SV_CODEC_IADDR);
587         udelay(10);
588         outb(m, s->ioenh + SV_CODEC_IDATA);
589         udelay(10);
590         outb(reg+1, s->ioenh + SV_CODEC_IADDR);
591         udelay(10);
592         outb(r | n, s->ioenh + SV_CODEC_IDATA);
593         spin_unlock_irqrestore(&s->lock, flags);
594         udelay(10);
595         return (REFFREQUENCY/ADCMULT * (m + 2) / (n + 2)) >> ((r >> 5) & 7);
596 }
597
598 #if 0
599
600 static unsigned getpll(struct sv_state *s, unsigned char reg)
601 {
602         unsigned long flags;
603         unsigned char m, n;
604
605         reg &= 0x3f;
606         spin_lock_irqsave(&s->lock, flags);
607         outb(reg, s->ioenh + SV_CODEC_IADDR);
608         udelay(10);
609         m = inb(s->ioenh + SV_CODEC_IDATA);
610         udelay(10);
611         outb(reg+1, s->ioenh + SV_CODEC_IADDR);
612         udelay(10);
613         n = inb(s->ioenh + SV_CODEC_IDATA);
614         spin_unlock_irqrestore(&s->lock, flags);
615         udelay(10);
616         return (REFFREQUENCY/ADCMULT * (m + 2) / ((n & 0x1f) + 2)) >> ((n >> 5) & 7);
617 }
618
619 #endif
620
621 static void set_dac_rate(struct sv_state *s, unsigned rate)
622 {
623         unsigned div;
624         unsigned long flags;
625
626         if (rate > 48000)
627                 rate = 48000;
628         if (rate < 4000)
629                 rate = 4000;
630         div = (rate * 65536 + FULLRATE/2) / FULLRATE;
631         if (div > 65535)
632                 div = 65535;
633         spin_lock_irqsave(&s->lock, flags);
634         wrindir(s, SV_CIPCMSR1, div >> 8);
635         wrindir(s, SV_CIPCMSR0, div);
636         spin_unlock_irqrestore(&s->lock, flags);
637         s->ratedac = (div * FULLRATE + 32768) / 65536;
638 }
639
640 static void set_adc_rate(struct sv_state *s, unsigned rate)
641 {
642         unsigned long flags;
643         unsigned rate1, rate2, div;
644
645         if (rate > 48000)
646                 rate = 48000;
647         if (rate < 4000)
648                 rate = 4000;
649         rate1 = setpll(s, SV_CIADCPLLM, rate);
650         div = (48000 + rate/2) / rate;
651         if (div > 8)
652                 div = 8;
653         rate2 = (48000 + div/2) / div;
654         spin_lock_irqsave(&s->lock, flags);
655         wrindir(s, SV_CIADCALTSR, (div-1) << 4);
656         if (abs((signed)(rate-rate2)) <= abs((signed)(rate-rate1))) {
657                 wrindir(s, SV_CIADCCLKSOURCE, 0x10);
658                 s->rateadc = rate2;
659         } else {
660                 wrindir(s, SV_CIADCCLKSOURCE, 0x00);
661                 s->rateadc = rate1;
662         }
663         spin_unlock_irqrestore(&s->lock, flags);
664 }
665
666 /* --------------------------------------------------------------------- */
667
668 static inline void stop_adc(struct sv_state *s)
669 {
670         unsigned long flags;
671
672         spin_lock_irqsave(&s->lock, flags);
673         s->enable &= ~SV_CENABLE_RE;
674         wrindir(s, SV_CIENABLE, s->enable);
675         spin_unlock_irqrestore(&s->lock, flags);
676 }       
677
678 static inline void stop_dac(struct sv_state *s)
679 {
680         unsigned long flags;
681
682         spin_lock_irqsave(&s->lock, flags);
683         s->enable &= ~(SV_CENABLE_PPE | SV_CENABLE_PE);
684         wrindir(s, SV_CIENABLE, s->enable);
685         spin_unlock_irqrestore(&s->lock, flags);
686 }       
687
688 static void start_dac(struct sv_state *s)
689 {
690         unsigned long flags;
691
692         spin_lock_irqsave(&s->lock, flags);
693         if ((s->dma_dac.mapped || s->dma_dac.count > 0) && s->dma_dac.ready) {
694                 s->enable = (s->enable & ~SV_CENABLE_PPE) | SV_CENABLE_PE;
695                 wrindir(s, SV_CIENABLE, s->enable);
696         }
697         spin_unlock_irqrestore(&s->lock, flags);
698 }       
699
700 static void start_adc(struct sv_state *s)
701 {
702         unsigned long flags;
703
704         spin_lock_irqsave(&s->lock, flags);
705         if ((s->dma_adc.mapped || s->dma_adc.count < (signed)(s->dma_adc.dmasize - 2*s->dma_adc.fragsize)) 
706             && s->dma_adc.ready) {
707                 s->enable |= SV_CENABLE_RE;
708                 wrindir(s, SV_CIENABLE, s->enable);
709         }
710         spin_unlock_irqrestore(&s->lock, flags);
711 }       
712
713 /* --------------------------------------------------------------------- */
714
715 #define DMABUF_DEFAULTORDER (17-PAGE_SHIFT)
716 #define DMABUF_MINORDER 1
717
718 static void dealloc_dmabuf(struct sv_state *s, struct dmabuf *db)
719 {
720         struct page *page, *pend;
721
722         if (db->rawbuf) {
723                 /* undo marking the pages as reserved */
724                 pend = virt_to_page(db->rawbuf + (PAGE_SIZE << db->buforder) - 1);
725                 for (page = virt_to_page(db->rawbuf); page <= pend; page++)
726                         mem_map_unreserve(page);
727                 pci_free_consistent(s->dev, PAGE_SIZE << db->buforder, db->rawbuf, db->dmaaddr);
728         }
729         db->rawbuf = NULL;
730         db->mapped = db->ready = 0;
731 }
732
733
734 /* DMAA is used for playback, DMAC is used for recording */
735
736 static int prog_dmabuf(struct sv_state *s, unsigned rec)
737 {
738         struct dmabuf *db = rec ? &s->dma_adc : &s->dma_dac;
739         unsigned rate = rec ? s->rateadc : s->ratedac;
740         int order;
741         unsigned bytepersec;
742         unsigned bufs;
743         struct page *page, *pend;
744         unsigned char fmt;
745         unsigned long flags;
746
747         spin_lock_irqsave(&s->lock, flags);
748         fmt = s->fmt;
749         if (rec) {
750                 s->enable &= ~SV_CENABLE_RE;
751                 fmt >>= SV_CFMT_CSHIFT;
752         } else {
753                 s->enable &= ~SV_CENABLE_PE;
754                 fmt >>= SV_CFMT_ASHIFT;
755         }
756         wrindir(s, SV_CIENABLE, s->enable);
757         spin_unlock_irqrestore(&s->lock, flags);
758         fmt &= SV_CFMT_MASK;
759         db->hwptr = db->swptr = db->total_bytes = db->count = db->error = db->endcleared = 0;
760         if (!db->rawbuf) {
761                 db->ready = db->mapped = 0;
762                 for (order = DMABUF_DEFAULTORDER; order >= DMABUF_MINORDER; order--)
763                         if ((db->rawbuf = pci_alloc_consistent(s->dev, PAGE_SIZE << order, &db->dmaaddr)))
764                                 break;
765                 if (!db->rawbuf)
766                         return -ENOMEM;
767                 db->buforder = order;
768                 if ((virt_to_bus(db->rawbuf) ^ (virt_to_bus(db->rawbuf) + (PAGE_SIZE << db->buforder) - 1)) & ~0xffff)
769                         printk(KERN_DEBUG "sv: DMA buffer crosses 64k boundary: busaddr 0x%lx  size %ld\n", 
770                                virt_to_bus(db->rawbuf), PAGE_SIZE << db->buforder);
771                 if ((virt_to_bus(db->rawbuf) + (PAGE_SIZE << db->buforder) - 1) & ~0xffffff)
772                         printk(KERN_DEBUG "sv: DMA buffer beyond 16MB: busaddr 0x%lx  size %ld\n", 
773                                virt_to_bus(db->rawbuf), PAGE_SIZE << db->buforder);
774                 /* now mark the pages as reserved; otherwise remap_page_range doesn't do what we want */
775                 pend = virt_to_page(db->rawbuf + (PAGE_SIZE << db->buforder) - 1);
776                 for (page = virt_to_page(db->rawbuf); page <= pend; page++)
777                         mem_map_reserve(page);
778         }
779         bytepersec = rate << sample_shift[fmt];
780         bufs = PAGE_SIZE << db->buforder;
781         if (db->ossfragshift) {
782                 if ((1000 << db->ossfragshift) < bytepersec)
783                         db->fragshift = ld2(bytepersec/1000);
784                 else
785                         db->fragshift = db->ossfragshift;
786         } else {
787                 db->fragshift = ld2(bytepersec/100/(db->subdivision ? db->subdivision : 1));
788                 if (db->fragshift < 3)
789                         db->fragshift = 3;
790         }
791         db->numfrag = bufs >> db->fragshift;
792         while (db->numfrag < 4 && db->fragshift > 3) {
793                 db->fragshift--;
794                 db->numfrag = bufs >> db->fragshift;
795         }
796         db->fragsize = 1 << db->fragshift;
797         if (db->ossmaxfrags >= 4 && db->ossmaxfrags < db->numfrag)
798                 db->numfrag = db->ossmaxfrags;
799         db->fragsamples = db->fragsize >> sample_shift[fmt];
800         db->dmasize = db->numfrag << db->fragshift;
801         memset(db->rawbuf, (fmt & SV_CFMT_16BIT) ? 0 : 0x80, db->dmasize);
802         spin_lock_irqsave(&s->lock, flags);
803         if (rec) {
804                 set_dmac(s, db->dmaaddr, db->numfrag << db->fragshift);
805                 /* program enhanced mode registers */
806                 wrindir(s, SV_CIDMACBASECOUNT1, (db->fragsamples-1) >> 8);
807                 wrindir(s, SV_CIDMACBASECOUNT0, db->fragsamples-1);
808         } else {
809                 set_dmaa(s, db->dmaaddr, db->numfrag << db->fragshift);
810                 /* program enhanced mode registers */
811                 wrindir(s, SV_CIDMAABASECOUNT1, (db->fragsamples-1) >> 8);
812                 wrindir(s, SV_CIDMAABASECOUNT0, db->fragsamples-1);
813         }
814         spin_unlock_irqrestore(&s->lock, flags);
815         db->enabled = 1;
816         db->ready = 1;
817         return 0;
818 }
819
820 static inline void clear_advance(struct sv_state *s)
821 {
822         unsigned char c = (s->fmt & (SV_CFMT_16BIT << SV_CFMT_ASHIFT)) ? 0 : 0x80;
823         unsigned char *buf = s->dma_dac.rawbuf;
824         unsigned bsize = s->dma_dac.dmasize;
825         unsigned bptr = s->dma_dac.swptr;
826         unsigned len = s->dma_dac.fragsize;
827
828         if (bptr + len > bsize) {
829                 unsigned x = bsize - bptr;
830                 memset(buf + bptr, c, x);
831                 bptr = 0;
832                 len -= x;
833         }
834         memset(buf + bptr, c, len);
835 }
836
837 /* call with spinlock held! */
838 static void sv_update_ptr(struct sv_state *s)
839 {
840         unsigned hwptr;
841         int diff;
842
843         /* update ADC pointer */
844         if (s->dma_adc.ready) {
845                 hwptr = (s->dma_adc.dmasize - get_dmac(s)) % s->dma_adc.dmasize;
846                 diff = (s->dma_adc.dmasize + hwptr - s->dma_adc.hwptr) % s->dma_adc.dmasize;
847                 s->dma_adc.hwptr = hwptr;
848                 s->dma_adc.total_bytes += diff;
849                 s->dma_adc.count += diff;
850                 if (s->dma_adc.count >= (signed)s->dma_adc.fragsize) 
851                         wake_up(&s->dma_adc.wait);
852                 if (!s->dma_adc.mapped) {
853                         if (s->dma_adc.count > (signed)(s->dma_adc.dmasize - ((3 * s->dma_adc.fragsize) >> 1))) {
854                                 s->enable &= ~SV_CENABLE_RE;
855                                 wrindir(s, SV_CIENABLE, s->enable);
856                                 s->dma_adc.error++;
857                         }
858                 }
859         }
860         /* update DAC pointer */
861         if (s->dma_dac.ready) {
862                 hwptr = (s->dma_dac.dmasize - get_dmaa(s)) % s->dma_dac.dmasize;
863                 diff = (s->dma_dac.dmasize + hwptr - s->dma_dac.hwptr) % s->dma_dac.dmasize;
864                 s->dma_dac.hwptr = hwptr;
865                 s->dma_dac.total_bytes += diff;
866                 if (s->dma_dac.mapped) {
867                         s->dma_dac.count += diff;
868                         if (s->dma_dac.count >= (signed)s->dma_dac.fragsize)
869                                 wake_up(&s->dma_dac.wait);
870                 } else {
871                         s->dma_dac.count -= diff;
872                         if (s->dma_dac.count <= 0) {
873                                 s->enable &= ~SV_CENABLE_PE;
874                                 wrindir(s, SV_CIENABLE, s->enable);
875                                 s->dma_dac.error++;
876                         } else if (s->dma_dac.count <= (signed)s->dma_dac.fragsize && !s->dma_dac.endcleared) {
877                                 clear_advance(s);
878                                 s->dma_dac.endcleared = 1;
879                         }
880                         if (s->dma_dac.count + (signed)s->dma_dac.fragsize <= (signed)s->dma_dac.dmasize)
881                                 wake_up(&s->dma_dac.wait);
882                 }
883         }
884 }
885
886 /* hold spinlock for the following! */
887 static void sv_handle_midi(struct sv_state *s)
888 {
889         unsigned char ch;
890         int wake;
891
892         wake = 0;
893         while (!(inb(s->iomidi+1) & 0x80)) {
894                 ch = inb(s->iomidi);
895                 if (s->midi.icnt < MIDIINBUF) {
896                         s->midi.ibuf[s->midi.iwr] = ch;
897                         s->midi.iwr = (s->midi.iwr + 1) % MIDIINBUF;
898                         s->midi.icnt++;
899                 }
900                 wake = 1;
901         }
902         if (wake)
903                 wake_up(&s->midi.iwait);
904         wake = 0;
905         while (!(inb(s->iomidi+1) & 0x40) && s->midi.ocnt > 0) {
906                 outb(s->midi.obuf[s->midi.ord], s->iomidi);
907                 s->midi.ord = (s->midi.ord + 1) % MIDIOUTBUF;
908                 s->midi.ocnt--;
909                 if (s->midi.ocnt < MIDIOUTBUF-16)
910                         wake = 1;
911         }
912         if (wake)
913                 wake_up(&s->midi.owait);
914 }
915
916 static void sv_interrupt(int irq, void *dev_id, struct pt_regs *regs)
917 {
918         struct sv_state *s = (struct sv_state *)dev_id;
919         unsigned int intsrc;
920         
921         /* fastpath out, to ease interrupt sharing */
922         intsrc = inb(s->ioenh + SV_CODEC_STATUS);
923         if (!(intsrc & (SV_CSTAT_DMAA | SV_CSTAT_DMAC | SV_CSTAT_MIDI)))
924                 return;
925         spin_lock(&s->lock);
926         sv_update_ptr(s);
927         sv_handle_midi(s);
928         spin_unlock(&s->lock);
929 }
930
931 static void sv_midi_timer(unsigned long data)
932 {
933         struct sv_state *s = (struct sv_state *)data;
934         unsigned long flags;
935         
936         spin_lock_irqsave(&s->lock, flags);
937         sv_handle_midi(s);
938         spin_unlock_irqrestore(&s->lock, flags);
939         s->midi.timer.expires = jiffies+1;
940         add_timer(&s->midi.timer);
941 }
942
943 /* --------------------------------------------------------------------- */
944
945 static const char invalid_magic[] = KERN_CRIT "sv: invalid magic value\n";
946
947 #define VALIDATE_STATE(s)                         \
948 ({                                                \
949         if (!(s) || (s)->magic != SV_MAGIC) { \
950                 printk(invalid_magic);            \
951                 return -ENXIO;                    \
952         }                                         \
953 })
954
955 /* --------------------------------------------------------------------- */
956
957 #define MT_4          1
958 #define MT_5MUTE      2
959 #define MT_4MUTEMONO  3
960 #define MT_6MUTE      4
961
962 static const struct {
963         unsigned left:5;
964         unsigned right:5;
965         unsigned type:3;
966         unsigned rec:3;
967 } mixtable[SOUND_MIXER_NRDEVICES] = {
968         [SOUND_MIXER_RECLEV] = { SV_CIMIX_ADCINL,    SV_CIMIX_ADCINR,    MT_4,         0 },
969         [SOUND_MIXER_LINE1]  = { SV_CIMIX_AUX1INL,   SV_CIMIX_AUX1INR,   MT_5MUTE,     5 },
970         [SOUND_MIXER_CD]     = { SV_CIMIX_CDINL,     SV_CIMIX_CDINR,     MT_5MUTE,     1 },
971         [SOUND_MIXER_LINE]   = { SV_CIMIX_LINEINL,   SV_CIMIX_LINEINR,   MT_5MUTE,     4 },
972         [SOUND_MIXER_MIC]    = { SV_CIMIX_MICIN,     SV_CIMIX_ADCINL,    MT_4MUTEMONO, 6 },
973         [SOUND_MIXER_SYNTH]  = { SV_CIMIX_SYNTHINL,  SV_CIMIX_SYNTHINR,  MT_5MUTE,     2 },
974         [SOUND_MIXER_LINE2]  = { SV_CIMIX_AUX2INL,   SV_CIMIX_AUX2INR,   MT_5MUTE,     3 },
975         [SOUND_MIXER_VOLUME] = { SV_CIMIX_ANALOGINL, SV_CIMIX_ANALOGINR, MT_5MUTE,     7 },
976         [SOUND_MIXER_PCM]    = { SV_CIMIX_PCMINL,    SV_CIMIX_PCMINR,    MT_6MUTE,     0 }
977 };
978
979 #ifdef OSS_DOCUMENTED_MIXER_SEMANTICS
980
981 static int return_mixval(struct sv_state *s, unsigned i, int *arg)
982 {
983         unsigned long flags;
984         unsigned char l, r, rl, rr;
985
986         spin_lock_irqsave(&s->lock, flags);
987         l = rdindir(s, mixtable[i].left);
988         r = rdindir(s, mixtable[i].right);
989         spin_unlock_irqrestore(&s->lock, flags);
990         switch (mixtable[i].type) {
991         case MT_4:
992                 r &= 0xf;
993                 l &= 0xf;
994                 rl = 10 + 6 * (l & 15);
995                 rr = 10 + 6 * (r & 15);
996                 break;
997
998         case MT_4MUTEMONO:
999                 rl = 55 - 3 * (l & 15);
1000                 if (r & 0x10)
1001                         rl += 45;
1002                 rr = rl;
1003                 r = l;
1004                 break;
1005
1006         case MT_5MUTE:
1007         default:
1008                 rl = 100 - 3 * (l & 31);
1009                 rr = 100 - 3 * (r & 31);
1010                 break;
1011                                 
1012         case MT_6MUTE:
1013                 rl = 100 - 3 * (l & 63) / 2;
1014                 rr = 100 - 3 * (r & 63) / 2;
1015                 break;
1016         }
1017         if (l & 0x80)
1018                 rl = 0;
1019         if (r & 0x80)
1020                 rr = 0;
1021         return put_user((rr << 8) | rl, arg);
1022 }
1023
1024 #else /* OSS_DOCUMENTED_MIXER_SEMANTICS */
1025
1026 static const unsigned char volidx[SOUND_MIXER_NRDEVICES] = 
1027 {
1028         [SOUND_MIXER_RECLEV] = 1,
1029         [SOUND_MIXER_LINE1]  = 2,
1030         [SOUND_MIXER_CD]     = 3,
1031         [SOUND_MIXER_LINE]   = 4,
1032         [SOUND_MIXER_MIC]    = 5,
1033         [SOUND_MIXER_SYNTH]  = 6,
1034         [SOUND_MIXER_LINE2]  = 7,
1035         [SOUND_MIXER_VOLUME] = 8,
1036         [SOUND_MIXER_PCM]    = 9
1037 };
1038
1039 #endif /* OSS_DOCUMENTED_MIXER_SEMANTICS */
1040
1041 static unsigned mixer_recmask(struct sv_state *s)
1042 {
1043         unsigned long flags;
1044         int i, j;
1045
1046         spin_lock_irqsave(&s->lock, flags);
1047         j = rdindir(s, SV_CIMIX_ADCINL) >> 5;
1048         spin_unlock_irqrestore(&s->lock, flags);
1049         j &= 7;
1050         for (i = 0; i < SOUND_MIXER_NRDEVICES && mixtable[i].rec != j; i++);
1051         return 1 << i;
1052 }
1053
1054 static int mixer_ioctl(struct sv_state *s, unsigned int cmd, unsigned long arg)
1055 {
1056         unsigned long flags;
1057         int i, val;
1058         unsigned char l, r, rl, rr;
1059
1060         VALIDATE_STATE(s);
1061         if (cmd == SOUND_MIXER_INFO) {
1062                 mixer_info info;
1063                 strncpy(info.id, "SonicVibes", sizeof(info.id));
1064                 strncpy(info.name, "S3 SonicVibes", sizeof(info.name));
1065                 info.modify_counter = s->mix.modcnt;
1066                 if (copy_to_user((void *)arg, &info, sizeof(info)))
1067                         return -EFAULT;
1068                 return 0;
1069         }
1070         if (cmd == SOUND_OLD_MIXER_INFO) {
1071                 _old_mixer_info info;
1072                 strncpy(info.id, "SonicVibes", sizeof(info.id));
1073                 strncpy(info.name, "S3 SonicVibes", sizeof(info.name));
1074                 if (copy_to_user((void *)arg, &info, sizeof(info)))
1075                         return -EFAULT;
1076                 return 0;
1077         }
1078         if (cmd == OSS_GETVERSION)
1079                 return put_user(SOUND_VERSION, (int *)arg);
1080         if (cmd == SOUND_MIXER_PRIVATE1) {  /* SRS settings */
1081                 if (get_user(val, (int *)arg))
1082                         return -EFAULT;
1083                 spin_lock_irqsave(&s->lock, flags);
1084                 if (val & 1) {
1085                         if (val & 2) {
1086                                 l = 4 - ((val >> 2) & 7);
1087                                 if (l & ~3)
1088                                         l = 4;
1089                                 r = 4 - ((val >> 5) & 7);
1090                                 if (r & ~3)
1091                                         r = 4;
1092                                 wrindir(s, SV_CISRSSPACE, l);
1093                                 wrindir(s, SV_CISRSCENTER, r);
1094                         } else
1095                                 wrindir(s, SV_CISRSSPACE, 0x80);
1096                 }
1097                 l = rdindir(s, SV_CISRSSPACE);
1098                 r = rdindir(s, SV_CISRSCENTER);
1099                 spin_unlock_irqrestore(&s->lock, flags);
1100                 if (l & 0x80)
1101                         return put_user(0, (int *)arg);
1102                 return put_user(((4 - (l & 7)) << 2) | ((4 - (r & 7)) << 5) | 2, (int *)arg);
1103         }
1104         if (_IOC_TYPE(cmd) != 'M' || _SIOC_SIZE(cmd) != sizeof(int))
1105                 return -EINVAL;
1106         if (_SIOC_DIR(cmd) == _SIOC_READ) {
1107                 switch (_IOC_NR(cmd)) {
1108                 case SOUND_MIXER_RECSRC: /* Arg contains a bit for each recording source */
1109                         return put_user(mixer_recmask(s), (int *)arg);
1110                         
1111                 case SOUND_MIXER_DEVMASK: /* Arg contains a bit for each supported device */
1112                         for (val = i = 0; i < SOUND_MIXER_NRDEVICES; i++)
1113                                 if (mixtable[i].type)
1114                                         val |= 1 << i;
1115                         return put_user(val, (int *)arg);
1116
1117                 case SOUND_MIXER_RECMASK: /* Arg contains a bit for each supported recording source */
1118                         for (val = i = 0; i < SOUND_MIXER_NRDEVICES; i++)
1119                                 if (mixtable[i].rec)
1120                                         val |= 1 << i;
1121                         return put_user(val, (int *)arg);
1122                         
1123                 case SOUND_MIXER_STEREODEVS: /* Mixer channels supporting stereo */
1124                         for (val = i = 0; i < SOUND_MIXER_NRDEVICES; i++)
1125                                 if (mixtable[i].type && mixtable[i].type != MT_4MUTEMONO)
1126                                         val |= 1 << i;
1127                         return put_user(val, (int *)arg);
1128                         
1129                 case SOUND_MIXER_CAPS:
1130                         return put_user(SOUND_CAP_EXCL_INPUT, (int *)arg);
1131
1132                 default:
1133                         i = _IOC_NR(cmd);
1134                         if (i >= SOUND_MIXER_NRDEVICES || !mixtable[i].type)
1135                                 return -EINVAL;
1136 #ifdef OSS_DOCUMENTED_MIXER_SEMANTICS
1137                         return return_mixval(s, i, (int *)arg);
1138 #else /* OSS_DOCUMENTED_MIXER_SEMANTICS */
1139                         if (!volidx[i])
1140                                 return -EINVAL;
1141                         return put_user(s->mix.vol[volidx[i]-1], (int *)arg);
1142 #endif /* OSS_DOCUMENTED_MIXER_SEMANTICS */
1143                 }
1144         }
1145         if (_SIOC_DIR(cmd) != (_SIOC_READ|_SIOC_WRITE)) 
1146                 return -EINVAL;
1147         s->mix.modcnt++;
1148         switch (_IOC_NR(cmd)) {
1149         case SOUND_MIXER_RECSRC: /* Arg contains a bit for each recording source */
1150                 if (get_user(val, (int *)arg))
1151                         return -EFAULT;
1152                 i = hweight32(val);
1153                 if (i == 0)
1154                         return 0; /*val = mixer_recmask(s);*/
1155                 else if (i > 1) 
1156                         val &= ~mixer_recmask(s);
1157                 for (i = 0; i < SOUND_MIXER_NRDEVICES; i++) {
1158                         if (!(val & (1 << i)))
1159                                 continue;
1160                         if (mixtable[i].rec)
1161                                 break;
1162                 }
1163                 if (!mixtable[i].rec)
1164                         return 0;
1165                 spin_lock_irqsave(&s->lock, flags);
1166                 frobindir(s, SV_CIMIX_ADCINL, 0x1f, mixtable[i].rec << 5);
1167                 frobindir(s, SV_CIMIX_ADCINR, 0x1f, mixtable[i].rec << 5);
1168                 spin_unlock_irqrestore(&s->lock, flags);
1169                 return 0;
1170
1171         default:
1172                 i = _IOC_NR(cmd);
1173                 if (i >= SOUND_MIXER_NRDEVICES || !mixtable[i].type)
1174                         return -EINVAL;
1175                 if (get_user(val, (int *)arg))
1176                         return -EFAULT;
1177                 l = val & 0xff;
1178                 r = (val >> 8) & 0xff;
1179                 if (mixtable[i].type == MT_4MUTEMONO)
1180                         l = (r + l) / 2;
1181                 if (l > 100)
1182                         l = 100;
1183                 if (r > 100)
1184                         r = 100;
1185                 spin_lock_irqsave(&s->lock, flags);
1186                 switch (mixtable[i].type) {
1187                 case MT_4:
1188                         if (l >= 10)
1189                                 l -= 10;
1190                         if (r >= 10)
1191                                 r -= 10;
1192                         frobindir(s, mixtable[i].left, 0xf0, l / 6);
1193                         frobindir(s, mixtable[i].right, 0xf0, l / 6);
1194                         break;
1195
1196                 case MT_4MUTEMONO:
1197                         rr = 0;
1198                         if (l < 10)
1199                                 rl = 0x80;
1200                         else {
1201                                 if (l >= 55) {
1202                                         rr = 0x10;
1203                                         l -= 45;
1204                                 }
1205                                 rl = (55 - l) / 3;
1206                         }
1207                         wrindir(s, mixtable[i].left, rl);
1208                         frobindir(s, mixtable[i].right, ~0x10, rr);
1209                         break;
1210                         
1211                 case MT_5MUTE:
1212                         if (l < 7)
1213                                 rl = 0x80;
1214                         else
1215                                 rl = (100 - l) / 3;
1216                         if (r < 7)
1217                                 rr = 0x80;
1218                         else
1219                                 rr = (100 - r) / 3;
1220                         wrindir(s, mixtable[i].left, rl);
1221                         wrindir(s, mixtable[i].right, rr);
1222                         break;
1223                                 
1224                 case MT_6MUTE:
1225                         if (l < 6)
1226                                 rl = 0x80;
1227                         else
1228                                 rl = (100 - l) * 2 / 3;
1229                         if (r < 6)
1230                                 rr = 0x80;
1231                         else
1232                                 rr = (100 - r) * 2 / 3;
1233                         wrindir(s, mixtable[i].left, rl);
1234                         wrindir(s, mixtable[i].right, rr);
1235                         break;
1236                 }
1237                 spin_unlock_irqrestore(&s->lock, flags);
1238 #ifdef OSS_DOCUMENTED_MIXER_SEMANTICS
1239                 return return_mixval(s, i, (int *)arg);
1240 #else /* OSS_DOCUMENTED_MIXER_SEMANTICS */
1241                 if (!volidx[i])
1242                         return -EINVAL;
1243                 s->mix.vol[volidx[i]-1] = val;
1244                 return put_user(s->mix.vol[volidx[i]-1], (int *)arg);
1245 #endif /* OSS_DOCUMENTED_MIXER_SEMANTICS */
1246         }
1247 }
1248
1249 /* --------------------------------------------------------------------- */
1250
1251 static int sv_open_mixdev(struct inode *inode, struct file *file)
1252 {
1253         int minor = MINOR(inode->i_rdev);
1254         struct list_head *list;
1255         struct sv_state *s;
1256
1257         for (list = devs.next; ; list = list->next) {
1258                 if (list == &devs)
1259                         return -ENODEV;
1260                 s = list_entry(list, struct sv_state, devs);
1261                 if (s->dev_mixer == minor)
1262                         break;
1263         }
1264         VALIDATE_STATE(s);
1265         file->private_data = s;
1266         return 0;
1267 }
1268
1269 static int sv_release_mixdev(struct inode *inode, struct file *file)
1270 {
1271         struct sv_state *s = (struct sv_state *)file->private_data;
1272         
1273         VALIDATE_STATE(s);
1274         return 0;
1275 }
1276
1277 static int sv_ioctl_mixdev(struct inode *inode, struct file *file, unsigned int cmd, unsigned long arg)
1278 {
1279         return mixer_ioctl((struct sv_state *)file->private_data, cmd, arg);
1280 }
1281
1282 static /*const*/ struct file_operations sv_mixer_fops = {
1283         owner:          THIS_MODULE,
1284         llseek:         no_llseek,
1285         ioctl:          sv_ioctl_mixdev,
1286         open:           sv_open_mixdev,
1287         release:        sv_release_mixdev,
1288 };
1289
1290 /* --------------------------------------------------------------------- */
1291
1292 static int drain_dac(struct sv_state *s, int nonblock)
1293 {
1294         DECLARE_WAITQUEUE(wait, current);
1295         unsigned long flags;
1296         int count, tmo;
1297
1298         if (s->dma_dac.mapped || !s->dma_dac.ready)
1299                 return 0;
1300         add_wait_queue(&s->dma_dac.wait, &wait);
1301         for (;;) {
1302                 __set_current_state(TASK_INTERRUPTIBLE);
1303                 spin_lock_irqsave(&s->lock, flags);
1304                 count = s->dma_dac.count;
1305                 spin_unlock_irqrestore(&s->lock, flags);
1306                 if (count <= 0)
1307                         break;
1308                 if (signal_pending(current))
1309                         break;
1310                 if (nonblock) {
1311                         remove_wait_queue(&s->dma_dac.wait, &wait);
1312                         set_current_state(TASK_RUNNING);
1313                         return -EBUSY;
1314                 }
1315                 tmo = 3 * HZ * (count + s->dma_dac.fragsize) / 2 / s->ratedac;
1316                 tmo >>= sample_shift[(s->fmt >> SV_CFMT_ASHIFT) & SV_CFMT_MASK];
1317                 if (!schedule_timeout(tmo + 1))
1318                         printk(KERN_DEBUG "sv: dma timed out??\n");
1319         }
1320         remove_wait_queue(&s->dma_dac.wait, &wait);
1321         set_current_state(TASK_RUNNING);
1322         if (signal_pending(current))
1323                 return -ERESTARTSYS;
1324         return 0;
1325 }
1326
1327 /* --------------------------------------------------------------------- */
1328
1329 static ssize_t sv_read(struct file *file, char *buffer, size_t count, loff_t *ppos)
1330 {
1331         struct sv_state *s = (struct sv_state *)file->private_data;
1332         DECLARE_WAITQUEUE(wait, current);
1333         ssize_t ret;
1334         unsigned long flags;
1335         unsigned swptr;
1336         int cnt;
1337
1338         VALIDATE_STATE(s);
1339         if (ppos != &file->f_pos)
1340                 return -ESPIPE;
1341         if (s->dma_adc.mapped)
1342                 return -ENXIO;
1343         if (!s->dma_adc.ready && (ret = prog_dmabuf(s, 1)))
1344                 return ret;
1345         if (!access_ok(VERIFY_WRITE, buffer, count))
1346                 return -EFAULT;
1347         ret = 0;
1348 #if 0
1349         spin_lock_irqsave(&s->lock, flags);
1350         sv_update_ptr(s);
1351         spin_unlock_irqrestore(&s->lock, flags);
1352 #endif
1353         add_wait_queue(&s->dma_adc.wait, &wait);
1354         while (count > 0) {
1355                 spin_lock_irqsave(&s->lock, flags);
1356                 swptr = s->dma_adc.swptr;
1357                 cnt = s->dma_adc.dmasize-swptr;
1358                 if (s->dma_adc.count < cnt)
1359                         cnt = s->dma_adc.count;
1360                 if (cnt <= 0)
1361                         __set_current_state(TASK_INTERRUPTIBLE);
1362                 spin_unlock_irqrestore(&s->lock, flags);
1363                 if (cnt > count)
1364                         cnt = count;
1365                 if (cnt <= 0) {
1366                         if (s->dma_adc.enabled)
1367                                 start_adc(s);
1368                         if (file->f_flags & O_NONBLOCK) {
1369                                 if (!ret)
1370                                         ret = -EAGAIN;
1371                                 break;
1372                         }
1373                         if (!schedule_timeout(HZ)) {
1374                                 printk(KERN_DEBUG "sv: read: chip lockup? dmasz %u fragsz %u count %i hwptr %u swptr %u\n",
1375                                        s->dma_adc.dmasize, s->dma_adc.fragsize, s->dma_adc.count, 
1376                                        s->dma_adc.hwptr, s->dma_adc.swptr);
1377                                 stop_adc(s);
1378                                 spin_lock_irqsave(&s->lock, flags);
1379                                 set_dmac(s, virt_to_bus(s->dma_adc.rawbuf), s->dma_adc.numfrag << s->dma_adc.fragshift);
1380                                 /* program enhanced mode registers */
1381                                 wrindir(s, SV_CIDMACBASECOUNT1, (s->dma_adc.fragsamples-1) >> 8);
1382                                 wrindir(s, SV_CIDMACBASECOUNT0, s->dma_adc.fragsamples-1);
1383                                 s->dma_adc.count = s->dma_adc.hwptr = s->dma_adc.swptr = 0;
1384                                 spin_unlock_irqrestore(&s->lock, flags);
1385                         }
1386                         if (signal_pending(current)) {
1387                                 if (!ret)
1388                                         ret = -ERESTARTSYS;
1389                                 break;
1390                         }
1391                         continue;
1392                 }
1393                 if (copy_to_user(buffer, s->dma_adc.rawbuf + swptr, cnt)) {
1394                         if (!ret)
1395                                 ret = -EFAULT;
1396                         break;
1397                 }
1398                 swptr = (swptr + cnt) % s->dma_adc.dmasize;
1399                 spin_lock_irqsave(&s->lock, flags);
1400                 s->dma_adc.swptr = swptr;
1401                 s->dma_adc.count -= cnt;
1402                 spin_unlock_irqrestore(&s->lock, flags);
1403                 count -= cnt;
1404                 buffer += cnt;
1405                 ret += cnt;
1406                 if (s->dma_adc.enabled)
1407                         start_adc(s);
1408         }
1409         remove_wait_queue(&s->dma_adc.wait, &wait);
1410         set_current_state(TASK_RUNNING);
1411         return ret;
1412 }
1413
1414 static ssize_t sv_write(struct file *file, const char *buffer, size_t count, loff_t *ppos)
1415 {
1416         struct sv_state *s = (struct sv_state *)file->private_data;
1417         DECLARE_WAITQUEUE(wait, current);
1418         ssize_t ret;
1419         unsigned long flags;
1420         unsigned swptr;
1421         int cnt;
1422
1423         VALIDATE_STATE(s);
1424         if (ppos != &file->f_pos)
1425                 return -ESPIPE;
1426         if (s->dma_dac.mapped)
1427                 return -ENXIO;
1428         if (!s->dma_dac.ready && (ret = prog_dmabuf(s, 0)))
1429                 return ret;
1430         if (!access_ok(VERIFY_READ, buffer, count))
1431                 return -EFAULT;
1432         ret = 0;
1433 #if 0
1434         spin_lock_irqsave(&s->lock, flags);
1435         sv_update_ptr(s);
1436         spin_unlock_irqrestore(&s->lock, flags);
1437 #endif
1438         add_wait_queue(&s->dma_dac.wait, &wait);
1439         while (count > 0) {
1440                 spin_lock_irqsave(&s->lock, flags);
1441                 if (s->dma_dac.count < 0) {
1442                         s->dma_dac.count = 0;
1443                         s->dma_dac.swptr = s->dma_dac.hwptr;
1444                 }
1445                 swptr = s->dma_dac.swptr;
1446                 cnt = s->dma_dac.dmasize-swptr;
1447                 if (s->dma_dac.count + cnt > s->dma_dac.dmasize)
1448                         cnt = s->dma_dac.dmasize - s->dma_dac.count;
1449                 if (cnt <= 0)
1450                         __set_current_state(TASK_INTERRUPTIBLE);
1451                 spin_unlock_irqrestore(&s->lock, flags);
1452                 if (cnt > count)
1453                         cnt = count;
1454                 if (cnt <= 0) {
1455                         if (s->dma_dac.enabled)
1456                                 start_dac(s);
1457                         if (file->f_flags & O_NONBLOCK) {
1458                                 if (!ret)
1459                                         ret = -EAGAIN;
1460                                 break;
1461                         }
1462                         if (!schedule_timeout(HZ)) {
1463                                 printk(KERN_DEBUG "sv: write: chip lockup? dmasz %u fragsz %u count %i hwptr %u swptr %u\n",
1464                                        s->dma_dac.dmasize, s->dma_dac.fragsize, s->dma_dac.count, 
1465                                        s->dma_dac.hwptr, s->dma_dac.swptr);
1466                                 stop_dac(s);
1467                                 spin_lock_irqsave(&s->lock, flags);
1468                                 set_dmaa(s, virt_to_bus(s->dma_dac.rawbuf), s->dma_dac.numfrag << s->dma_dac.fragshift);
1469                                 /* program enhanced mode registers */
1470                                 wrindir(s, SV_CIDMAABASECOUNT1, (s->dma_dac.fragsamples-1) >> 8);
1471                                 wrindir(s, SV_CIDMAABASECOUNT0, s->dma_dac.fragsamples-1);
1472                                 s->dma_dac.count = s->dma_dac.hwptr = s->dma_dac.swptr = 0;
1473                                 spin_unlock_irqrestore(&s->lock, flags);
1474                         }
1475                         if (signal_pending(current)) {
1476                                 if (!ret)
1477                                         ret = -ERESTARTSYS;
1478                                 break;
1479                         }
1480                         continue;
1481                 }
1482                 if (copy_from_user(s->dma_dac.rawbuf + swptr, buffer, cnt)) {
1483                         if (!ret)
1484                                 ret = -EFAULT;
1485                         break;
1486                 }
1487                 swptr = (swptr + cnt) % s->dma_dac.dmasize;
1488                 spin_lock_irqsave(&s->lock, flags);
1489                 s->dma_dac.swptr = swptr;
1490                 s->dma_dac.count += cnt;
1491                 s->dma_dac.endcleared = 0;
1492                 spin_unlock_irqrestore(&s->lock, flags);
1493                 count -= cnt;
1494                 buffer += cnt;
1495                 ret += cnt;
1496                 if (s->dma_dac.enabled)
1497                         start_dac(s);
1498         }
1499         remove_wait_queue(&s->dma_dac.wait, &wait);
1500         set_current_state(TASK_RUNNING);
1501         return ret;
1502 }
1503
1504 /* No kernel lock - we have our own spinlock */
1505 static unsigned int sv_poll(struct file *file, struct poll_table_struct *wait)
1506 {
1507         struct sv_state *s = (struct sv_state *)file->private_data;
1508         unsigned long flags;
1509         unsigned int mask = 0;
1510
1511         VALIDATE_STATE(s);
1512         if (file->f_mode & FMODE_WRITE) {
1513                 if (!s->dma_dac.ready && prog_dmabuf(s, 1))
1514                         return 0;
1515                 poll_wait(file, &s->dma_dac.wait, wait);
1516         }
1517         if (file->f_mode & FMODE_READ) {
1518                 if (!s->dma_adc.ready && prog_dmabuf(s, 0))
1519                         return 0;
1520                 poll_wait(file, &s->dma_adc.wait, wait);
1521         }
1522         spin_lock_irqsave(&s->lock, flags);
1523         sv_update_ptr(s);
1524         if (file->f_mode & FMODE_READ) {
1525                 if (s->dma_adc.count >= (signed)s->dma_adc.fragsize)
1526                         mask |= POLLIN | POLLRDNORM;
1527         }
1528         if (file->f_mode & FMODE_WRITE) {
1529                 if (s->dma_dac.mapped) {
1530                         if (s->dma_dac.count >= (signed)s->dma_dac.fragsize) 
1531                                 mask |= POLLOUT | POLLWRNORM;
1532                 } else {
1533                         if ((signed)s->dma_dac.dmasize >= s->dma_dac.count + (signed)s->dma_dac.fragsize)
1534                                 mask |= POLLOUT | POLLWRNORM;
1535                 }
1536         }
1537         spin_unlock_irqrestore(&s->lock, flags);
1538         return mask;
1539 }
1540
1541 static int sv_mmap(struct file *file, struct vm_area_struct *vma)
1542 {
1543         struct sv_state *s = (struct sv_state *)file->private_data;
1544         struct dmabuf *db;
1545         int ret = -EINVAL;
1546         unsigned long size;
1547
1548         VALIDATE_STATE(s);
1549         lock_kernel();
1550         if (vma->vm_flags & VM_WRITE) {
1551                 if ((ret = prog_dmabuf(s, 1)) != 0)
1552                         goto out;
1553                 db = &s->dma_dac;
1554         } else if (vma->vm_flags & VM_READ) {
1555                 if ((ret = prog_dmabuf(s, 0)) != 0)
1556                         goto out;
1557                 db = &s->dma_adc;
1558         } else 
1559                 goto out;
1560         ret = -EINVAL;
1561         if (vma->vm_pgoff != 0)
1562                 goto out;
1563         size = vma->vm_end - vma->vm_start;
1564         if (size > (PAGE_SIZE << db->buforder))
1565                 goto out;
1566         ret = -EAGAIN;
1567         if (remap_page_range(vma->vm_start, virt_to_phys(db->rawbuf), size, vma->vm_page_prot))
1568                 goto out;
1569         db->mapped = 1;
1570         ret = 0;
1571 out:
1572         unlock_kernel();
1573         return ret;
1574 }
1575
1576 static int sv_ioctl(struct inode *inode, struct file *file, unsigned int cmd, unsigned long arg)
1577 {
1578         struct sv_state *s = (struct sv_state *)file->private_data;
1579         unsigned long flags;
1580         audio_buf_info abinfo;
1581         count_info cinfo;
1582         int count;
1583         int val, mapped, ret;
1584         unsigned char fmtm, fmtd;
1585
1586         VALIDATE_STATE(s);
1587         mapped = ((file->f_mode & FMODE_WRITE) && s->dma_dac.mapped) ||
1588                 ((file->f_mode & FMODE_READ) && s->dma_adc.mapped);
1589         switch (cmd) {
1590         case OSS_GETVERSION:
1591                 return put_user(SOUND_VERSION, (int *)arg);
1592
1593         case SNDCTL_DSP_SYNC:
1594                 if (file->f_mode & FMODE_WRITE)
1595                         return drain_dac(s, 0/*file->f_flags & O_NONBLOCK*/);
1596                 return 0;
1597                 
1598         case SNDCTL_DSP_SETDUPLEX:
1599                 return 0;
1600
1601         case SNDCTL_DSP_GETCAPS:
1602                 return put_user(DSP_CAP_DUPLEX | DSP_CAP_REALTIME | DSP_CAP_TRIGGER | DSP_CAP_MMAP, (int *)arg);
1603                 
1604         case SNDCTL_DSP_RESET:
1605                 if (file->f_mode & FMODE_WRITE) {
1606                         stop_dac(s);
1607                         synchronize_irq();
1608                         s->dma_dac.swptr = s->dma_dac.hwptr = s->dma_dac.count = s->dma_dac.total_bytes = 0;
1609                 }
1610                 if (file->f_mode & FMODE_READ) {
1611                         stop_adc(s);
1612                         synchronize_irq();
1613                         s->dma_adc.swptr = s->dma_adc.hwptr = s->dma_adc.count = s->dma_adc.total_bytes = 0;
1614                 }
1615                 return 0;
1616
1617         case SNDCTL_DSP_SPEED:
1618                 if (get_user(val, (int *)arg))
1619                         return -EFAULT;
1620                 if (val >= 0) {
1621                         if (file->f_mode & FMODE_READ) {
1622                                 stop_adc(s);
1623                                 s->dma_adc.ready = 0;
1624                                 set_adc_rate(s, val);
1625                         }
1626                         if (file->f_mode & FMODE_WRITE) {
1627                                 stop_dac(s);
1628                                 s->dma_dac.ready = 0;
1629                                 set_dac_rate(s, val);
1630                         }
1631                 }
1632                 return put_user((file->f_mode & FMODE_READ) ? s->rateadc : s->ratedac, (int *)arg);
1633                 
1634         case SNDCTL_DSP_STEREO:
1635                 if (get_user(val, (int *)arg))
1636                         return -EFAULT;
1637                 fmtd = 0;
1638                 fmtm = ~0;
1639                 if (file->f_mode & FMODE_READ) {
1640                         stop_adc(s);
1641                         s->dma_adc.ready = 0;
1642                         if (val)
1643                                 fmtd |= SV_CFMT_STEREO << SV_CFMT_CSHIFT;
1644                         else
1645                                 fmtm &= ~(SV_CFMT_STEREO << SV_CFMT_CSHIFT);
1646                 }
1647                 if (file->f_mode & FMODE_WRITE) {
1648                         stop_dac(s);
1649                         s->dma_dac.ready = 0;
1650                         if (val)
1651                                 fmtd |= SV_CFMT_STEREO << SV_CFMT_ASHIFT;
1652                         else
1653                                 fmtm &= ~(SV_CFMT_STEREO << SV_CFMT_ASHIFT);
1654                 }
1655                 set_fmt(s, fmtm, fmtd);
1656                 return 0;
1657
1658         case SNDCTL_DSP_CHANNELS:
1659                 if (get_user(val, (int *)arg))
1660                         return -EFAULT;
1661                 if (val != 0) {
1662                         fmtd = 0;
1663                         fmtm = ~0;
1664                         if (file->f_mode & FMODE_READ) {
1665                                 stop_adc(s);
1666                                 s->dma_adc.ready = 0;
1667                                 if (val >= 2)
1668                                         fmtd |= SV_CFMT_STEREO << SV_CFMT_CSHIFT;
1669                                 else
1670                                         fmtm &= ~(SV_CFMT_STEREO << SV_CFMT_CSHIFT);
1671                         }
1672                         if (file->f_mode & FMODE_WRITE) {
1673                                 stop_dac(s);
1674                                 s->dma_dac.ready = 0;
1675                                 if (val >= 2)
1676                                         fmtd |= SV_CFMT_STEREO << SV_CFMT_ASHIFT;
1677                                 else
1678                                         fmtm &= ~(SV_CFMT_STEREO << SV_CFMT_ASHIFT);
1679                         }
1680                         set_fmt(s, fmtm, fmtd);
1681                 }
1682                 return put_user((s->fmt & ((file->f_mode & FMODE_READ) ? (SV_CFMT_STEREO << SV_CFMT_CSHIFT) 
1683                                            : (SV_CFMT_STEREO << SV_CFMT_ASHIFT))) ? 2 : 1, (int *)arg);
1684                 
1685         case SNDCTL_DSP_GETFMTS: /* Returns a mask */
1686                 return put_user(AFMT_S16_LE|AFMT_U8, (int *)arg);
1687                 
1688         case SNDCTL_DSP_SETFMT: /* Selects ONE fmt*/
1689                 if (get_user(val, (int *)arg))
1690                         return -EFAULT;
1691                 if (val != AFMT_QUERY) {
1692                         fmtd = 0;
1693                         fmtm = ~0;
1694                         if (file->f_mode & FMODE_READ) {
1695                                 stop_adc(s);
1696                                 s->dma_adc.ready = 0;
1697                                 if (val == AFMT_S16_LE)
1698                                         fmtd |= SV_CFMT_16BIT << SV_CFMT_CSHIFT;
1699                                 else
1700                                         fmtm &= ~(SV_CFMT_16BIT << SV_CFMT_CSHIFT);
1701                         }
1702                         if (file->f_mode & FMODE_WRITE) {
1703                                 stop_dac(s);
1704                                 s->dma_dac.ready = 0;
1705                                 if (val == AFMT_S16_LE)
1706                                         fmtd |= SV_CFMT_16BIT << SV_CFMT_ASHIFT;
1707                                 else
1708                                         fmtm &= ~(SV_CFMT_16BIT << SV_CFMT_ASHIFT);
1709                         }
1710                         set_fmt(s, fmtm, fmtd);
1711                 }
1712                 return put_user((s->fmt & ((file->f_mode & FMODE_READ) ? (SV_CFMT_16BIT << SV_CFMT_CSHIFT) 
1713                                            : (SV_CFMT_16BIT << SV_CFMT_ASHIFT))) ? AFMT_S16_LE : AFMT_U8, (int *)arg);
1714                 
1715         case SNDCTL_DSP_POST:
1716                 return 0;
1717
1718         case SNDCTL_DSP_GETTRIGGER:
1719                 val = 0;
1720                 if (file->f_mode & FMODE_READ && s->enable & SV_CENABLE_RE) 
1721                         val |= PCM_ENABLE_INPUT;
1722                 if (file->f_mode & FMODE_WRITE && s->enable & SV_CENABLE_PE) 
1723                         val |= PCM_ENABLE_OUTPUT;
1724                 return put_user(val, (int *)arg);
1725                 
1726         case SNDCTL_DSP_SETTRIGGER:
1727                 if (get_user(val, (int *)arg))
1728                         return -EFAULT;
1729                 if (file->f_mode & FMODE_READ) {
1730                         if (val & PCM_ENABLE_INPUT) {
1731                                 if (!s->dma_adc.ready && (ret =  prog_dmabuf(s, 1)))
1732                                         return ret;
1733                                 s->dma_adc.enabled = 1;
1734                                 start_adc(s);
1735                         } else {
1736                                 s->dma_adc.enabled = 0;
1737                                 stop_adc(s);
1738                         }
1739                 }
1740                 if (file->f_mode & FMODE_WRITE) {
1741                         if (val & PCM_ENABLE_OUTPUT) {
1742                                 if (!s->dma_dac.ready && (ret = prog_dmabuf(s, 0)))
1743                                         return ret;
1744                                 s->dma_dac.enabled = 1;
1745                                 start_dac(s);
1746                         } else {
1747                                 s->dma_dac.enabled = 0;
1748                                 stop_dac(s);
1749                         }
1750                 }
1751                 return 0;
1752
1753         case SNDCTL_DSP_GETOSPACE:
1754                 if (!(file->f_mode & FMODE_WRITE))
1755                         return -EINVAL;
1756                 if (!s->dma_dac.ready && (val = prog_dmabuf(s, 0)) != 0)
1757                         return val;
1758                 spin_lock_irqsave(&s->lock, flags);
1759                 sv_update_ptr(s);
1760                 abinfo.fragsize = s->dma_dac.fragsize;
1761                 count = s->dma_dac.count;
1762                 if (count < 0)
1763                         count = 0;
1764                 abinfo.bytes = s->dma_dac.dmasize - count;
1765                 abinfo.fragstotal = s->dma_dac.numfrag;
1766                 abinfo.fragments = abinfo.bytes >> s->dma_dac.fragshift;      
1767                 spin_unlock_irqrestore(&s->lock, flags);
1768                 return copy_to_user((void *)arg, &abinfo, sizeof(abinfo)) ? -EFAULT : 0;
1769
1770         case SNDCTL_DSP_GETISPACE:
1771                 if (!(file->f_mode & FMODE_READ))
1772                         return -EINVAL;
1773                 if (!s->dma_adc.ready && (val = prog_dmabuf(s, 1)) != 0)
1774                         return val;
1775                 spin_lock_irqsave(&s->lock, flags);
1776                 sv_update_ptr(s);
1777                 abinfo.fragsize = s->dma_adc.fragsize;
1778                 count = s->dma_adc.count;
1779                 if (count < 0)
1780                         count = 0;
1781                 abinfo.bytes = count;
1782                 abinfo.fragstotal = s->dma_adc.numfrag;
1783                 abinfo.fragments = abinfo.bytes >> s->dma_adc.fragshift;      
1784                 spin_unlock_irqrestore(&s->lock, flags);
1785                 return copy_to_user((void *)arg, &abinfo, sizeof(abinfo)) ? -EFAULT : 0;
1786                 
1787         case SNDCTL_DSP_NONBLOCK:
1788                 file->f_flags |= O_NONBLOCK;
1789                 return 0;
1790
1791         case SNDCTL_DSP_GETODELAY:
1792                 if (!(file->f_mode & FMODE_WRITE))
1793                         return -EINVAL;
1794                 if (!s->dma_dac.ready && (val = prog_dmabuf(s, 0)) != 0)
1795                         return val;
1796                 spin_lock_irqsave(&s->lock, flags);
1797                 sv_update_ptr(s);
1798                 count = s->dma_dac.count;
1799                 spin_unlock_irqrestore(&s->lock, flags);
1800                 if (count < 0)
1801                         count = 0;
1802                 return put_user(count, (int *)arg);
1803
1804         case SNDCTL_DSP_GETIPTR:
1805                 if (!(file->f_mode & FMODE_READ))
1806                         return -EINVAL;
1807                 if (!s->dma_adc.ready && (val = prog_dmabuf(s, 1)) != 0)
1808                         return val;
1809                 spin_lock_irqsave(&s->lock, flags);
1810                 sv_update_ptr(s);
1811                 cinfo.bytes = s->dma_adc.total_bytes;
1812                 count = s->dma_adc.count;
1813                 if (count < 0)
1814                         count = 0;
1815                 cinfo.blocks = count >> s->dma_adc.fragshift;
1816                 cinfo.ptr = s->dma_adc.hwptr;
1817                 if (s->dma_adc.mapped)
1818                         s->dma_adc.count &= s->dma_adc.fragsize-1;
1819                 spin_unlock_irqrestore(&s->lock, flags);
1820                 return copy_to_user((void *)arg, &cinfo, sizeof(cinfo));
1821
1822         case SNDCTL_DSP_GETOPTR:
1823                 if (!(file->f_mode & FMODE_WRITE))
1824                         return -EINVAL;
1825                 if (!s->dma_dac.ready && (val = prog_dmabuf(s, 0)) != 0)
1826                         return val;
1827                 spin_lock_irqsave(&s->lock, flags);
1828                 sv_update_ptr(s);
1829                 cinfo.bytes = s->dma_dac.total_bytes;
1830                 count = s->dma_dac.count;
1831                 if (count < 0)
1832                         count = 0;
1833                 cinfo.blocks = count >> s->dma_dac.fragshift;
1834                 cinfo.ptr = s->dma_dac.hwptr;
1835                 if (s->dma_dac.mapped)
1836                         s->dma_dac.count &= s->dma_dac.fragsize-1;
1837                 spin_unlock_irqrestore(&s->lock, flags);
1838                 return copy_to_user((void *)arg, &cinfo, sizeof(cinfo));
1839
1840         case SNDCTL_DSP_GETBLKSIZE:
1841                 if (file->f_mode & FMODE_WRITE) {
1842                         if ((val = prog_dmabuf(s, 0)))
1843                                 return val;
1844                         return put_user(s->dma_dac.fragsize, (int *)arg);
1845                 }
1846                 if ((val = prog_dmabuf(s, 1)))
1847                         return val;
1848                 return put_user(s->dma_adc.fragsize, (int *)arg);
1849
1850         case SNDCTL_DSP_SETFRAGMENT:
1851                 if (get_user(val, (int *)arg))
1852                         return -EFAULT;
1853                 if (file->f_mode & FMODE_READ) {
1854                         s->dma_adc.ossfragshift = val & 0xffff;
1855                         s->dma_adc.ossmaxfrags = (val >> 16) & 0xffff;
1856                         if (s->dma_adc.ossfragshift < 4)
1857                                 s->dma_adc.ossfragshift = 4;
1858                         if (s->dma_adc.ossfragshift > 15)
1859                                 s->dma_adc.ossfragshift = 15;
1860                         if (s->dma_adc.ossmaxfrags < 4)
1861                                 s->dma_adc.ossmaxfrags = 4;
1862                 }
1863                 if (file->f_mode & FMODE_WRITE) {
1864                         s->dma_dac.ossfragshift = val & 0xffff;
1865                         s->dma_dac.ossmaxfrags = (val >> 16) & 0xffff;
1866                         if (s->dma_dac.ossfragshift < 4)
1867                                 s->dma_dac.ossfragshift = 4;
1868                         if (s->dma_dac.ossfragshift > 15)
1869                                 s->dma_dac.ossfragshift = 15;
1870                         if (s->dma_dac.ossmaxfrags < 4)
1871                                 s->dma_dac.ossmaxfrags = 4;
1872                 }
1873                 return 0;
1874
1875         case SNDCTL_DSP_SUBDIVIDE:
1876                 if ((file->f_mode & FMODE_READ && s->dma_adc.subdivision) ||
1877                     (file->f_mode & FMODE_WRITE && s->dma_dac.subdivision))
1878                         return -EINVAL;
1879                 if (get_user(val, (int *)arg))
1880                         return -EFAULT;
1881                 if (val != 1 && val != 2 && val != 4)
1882                         return -EINVAL;
1883                 if (file->f_mode & FMODE_READ)
1884                         s->dma_adc.subdivision = val;
1885                 if (file->f_mode & FMODE_WRITE)
1886                         s->dma_dac.subdivision = val;
1887                 return 0;
1888
1889         case SOUND_PCM_READ_RATE:
1890                 return put_user((file->f_mode & FMODE_READ) ? s->rateadc : s->ratedac, (int *)arg);
1891
1892         case SOUND_PCM_READ_CHANNELS:
1893                 return put_user((s->fmt & ((file->f_mode & FMODE_READ) ? (SV_CFMT_STEREO << SV_CFMT_CSHIFT) 
1894                                            : (SV_CFMT_STEREO << SV_CFMT_ASHIFT))) ? 2 : 1, (int *)arg);
1895
1896         case SOUND_PCM_READ_BITS:
1897                 return put_user((s->fmt & ((file->f_mode & FMODE_READ) ? (SV_CFMT_16BIT << SV_CFMT_CSHIFT) 
1898                                            : (SV_CFMT_16BIT << SV_CFMT_ASHIFT))) ? 16 : 8, (int *)arg);
1899
1900         case SOUND_PCM_WRITE_FILTER:
1901         case SNDCTL_DSP_SETSYNCRO:
1902         case SOUND_PCM_READ_FILTER:
1903                 return -EINVAL;
1904                 
1905         }
1906         return mixer_ioctl(s, cmd, arg);
1907 }
1908
1909 static int sv_open(struct inode *inode, struct file *file)
1910 {
1911         int minor = MINOR(inode->i_rdev);
1912         DECLARE_WAITQUEUE(wait, current);
1913         unsigned char fmtm = ~0, fmts = 0;
1914         struct list_head *list;
1915         struct sv_state *s;
1916
1917         for (list = devs.next; ; list = list->next) {
1918                 if (list == &devs)
1919                         return -ENODEV;
1920                 s = list_entry(list, struct sv_state, devs);
1921                 if (!((s->dev_audio ^ minor) & ~0xf))
1922                         break;
1923         }
1924         VALIDATE_STATE(s);
1925         file->private_data = s;
1926         /* wait for device to become free */
1927         down(&s->open_sem);
1928         while (s->open_mode & file->f_mode) {
1929                 if (file->f_flags & O_NONBLOCK) {
1930                         up(&s->open_sem);
1931                         return -EBUSY;
1932                 }
1933                 add_wait_queue(&s->open_wait, &wait);
1934                 __set_current_state(TASK_INTERRUPTIBLE);
1935                 up(&s->open_sem);
1936                 schedule();
1937                 remove_wait_queue(&s->open_wait, &wait);
1938                 set_current_state(TASK_RUNNING);
1939                 if (signal_pending(current))
1940                         return -ERESTARTSYS;
1941                 down(&s->open_sem);
1942         }
1943         if (file->f_mode & FMODE_READ) {
1944                 fmtm &= ~((SV_CFMT_STEREO | SV_CFMT_16BIT) << SV_CFMT_CSHIFT);
1945                 if ((minor & 0xf) == SND_DEV_DSP16)
1946                         fmts |= SV_CFMT_16BIT << SV_CFMT_CSHIFT;
1947                 s->dma_adc.ossfragshift = s->dma_adc.ossmaxfrags = s->dma_adc.subdivision = 0;
1948                 s->dma_adc.enabled = 1;
1949                 set_adc_rate(s, 8000);
1950         }
1951         if (file->f_mode & FMODE_WRITE) {
1952                 fmtm &= ~((SV_CFMT_STEREO | SV_CFMT_16BIT) << SV_CFMT_ASHIFT);
1953                 if ((minor & 0xf) == SND_DEV_DSP16)
1954                         fmts |= SV_CFMT_16BIT << SV_CFMT_ASHIFT;
1955                 s->dma_dac.ossfragshift = s->dma_dac.ossmaxfrags = s->dma_dac.subdivision = 0;
1956                 s->dma_dac.enabled = 1;
1957                 set_dac_rate(s, 8000);
1958         }
1959         set_fmt(s, fmtm, fmts);
1960         s->open_mode |= file->f_mode & (FMODE_READ | FMODE_WRITE);
1961         up(&s->open_sem);
1962         return 0;
1963 }
1964
1965 static int sv_release(struct inode *inode, struct file *file)
1966 {
1967         struct sv_state *s = (struct sv_state *)file->private_data;
1968
1969         VALIDATE_STATE(s);
1970         lock_kernel();
1971         if (file->f_mode & FMODE_WRITE)
1972                 drain_dac(s, file->f_flags & O_NONBLOCK);
1973         down(&s->open_sem);
1974         if (file->f_mode & FMODE_WRITE) {
1975                 stop_dac(s);
1976                 dealloc_dmabuf(s, &s->dma_dac);
1977         }
1978         if (file->f_mode & FMODE_READ) {
1979                 stop_adc(s);
1980                 dealloc_dmabuf(s, &s->dma_adc);
1981         }
1982         s->open_mode &= (~file->f_mode) & (FMODE_READ|FMODE_WRITE);
1983         wake_up(&s->open_wait);
1984         up(&s->open_sem);
1985         unlock_kernel();
1986         return 0;
1987 }
1988
1989 static /*const*/ struct file_operations sv_audio_fops = {
1990         owner:          THIS_MODULE,
1991         llseek:         no_llseek,
1992         read:           sv_read,
1993         write:          sv_write,
1994         poll:           sv_poll,
1995         ioctl:          sv_ioctl,
1996         mmap:           sv_mmap,
1997         open:           sv_open,
1998         release:        sv_release,
1999 };
2000
2001 /* --------------------------------------------------------------------- */
2002
2003 static ssize_t sv_midi_read(struct file *file, char *buffer, size_t count, loff_t *ppos)
2004 {
2005         struct sv_state *s = (struct sv_state *)file->private_data;
2006         DECLARE_WAITQUEUE(wait, current);
2007         ssize_t ret;
2008         unsigned long flags;
2009         unsigned ptr;
2010         int cnt;
2011
2012         VALIDATE_STATE(s);
2013         if (ppos != &file->f_pos)
2014                 return -ESPIPE;
2015         if (!access_ok(VERIFY_WRITE, buffer, count))
2016                 return -EFAULT;
2017         if (count == 0)
2018                 return 0;
2019         ret = 0;
2020         add_wait_queue(&s->midi.iwait, &wait);
2021         while (count > 0) {
2022                 spin_lock_irqsave(&s->lock, flags);
2023                 ptr = s->midi.ird;
2024                 cnt = MIDIINBUF - ptr;
2025                 if (s->midi.icnt < cnt)
2026                         cnt = s->midi.icnt;
2027                 if (cnt <= 0)
2028                       __set_current_state(TASK_INTERRUPTIBLE);
2029                 spin_unlock_irqrestore(&s->lock, flags);
2030                 if (cnt > count)
2031                         cnt = count;
2032                 if (cnt <= 0) {
2033                       if (file->f_flags & O_NONBLOCK) {
2034                               if (!ret)
2035                                       ret = -EAGAIN;
2036                               break;
2037                       }
2038                       schedule();
2039                       if (signal_pending(current)) {
2040                               if (!ret)
2041                                       ret = -ERESTARTSYS;
2042                               break;
2043                       }
2044                         continue;
2045                 }
2046                 if (copy_to_user(buffer, s->midi.ibuf + ptr, cnt)) {
2047                         if (!ret)
2048                                 ret = -EFAULT;
2049                         break;
2050                 }
2051                 ptr = (ptr + cnt) % MIDIINBUF;
2052                 spin_lock_irqsave(&s->lock, flags);
2053                 s->midi.ird = ptr;
2054                 s->midi.icnt -= cnt;
2055                 spin_unlock_irqrestore(&s->lock, flags);
2056                 count -= cnt;
2057                 buffer += cnt;
2058                 ret += cnt;
2059                 break;
2060         }
2061         __set_current_state(TASK_RUNNING);
2062         remove_wait_queue(&s->midi.iwait, &wait);
2063         return ret;
2064 }
2065
2066 static ssize_t sv_midi_write(struct file *file, const char *buffer, size_t count, loff_t *ppos)
2067 {
2068         struct sv_state *s = (struct sv_state *)file->private_data;
2069         DECLARE_WAITQUEUE(wait, current);
2070         ssize_t ret;
2071         unsigned long flags;
2072         unsigned ptr;
2073         int cnt;
2074
2075         VALIDATE_STATE(s);
2076         if (ppos != &file->f_pos)
2077                 return -ESPIPE;
2078         if (!access_ok(VERIFY_READ, buffer, count))
2079                 return -EFAULT;
2080         if (count == 0)
2081                 return 0;
2082         ret = 0;
2083         add_wait_queue(&s->midi.owait, &wait);
2084         while (count > 0) {
2085                 spin_lock_irqsave(&s->lock, flags);
2086                 ptr = s->midi.owr;
2087                 cnt = MIDIOUTBUF - ptr;
2088                 if (s->midi.ocnt + cnt > MIDIOUTBUF)
2089                         cnt = MIDIOUTBUF - s->midi.ocnt;
2090                 if (cnt <= 0) {
2091                         __set_current_state(TASK_INTERRUPTIBLE);
2092                         sv_handle_midi(s);
2093                 }
2094                 spin_unlock_irqrestore(&s->lock, flags);
2095                 if (cnt > count)
2096                         cnt = count;
2097                 if (cnt <= 0) {
2098                         if (file->f_flags & O_NONBLOCK) {
2099                                 if (!ret)
2100                                         ret = -EAGAIN;
2101                                 break;
2102                         }
2103                         schedule();
2104                         if (signal_pending(current)) {
2105                                 if (!ret)
2106                                         ret = -ERESTARTSYS;
2107                                 break;
2108                         }
2109                         continue;
2110                 }
2111                 if (copy_from_user(s->midi.obuf + ptr, buffer, cnt)) {
2112                         if (!ret)
2113                                 ret = -EFAULT;
2114                         break;
2115                 }
2116                 ptr = (ptr + cnt) % MIDIOUTBUF;
2117                 spin_lock_irqsave(&s->lock, flags);
2118                 s->midi.owr = ptr;
2119                 s->midi.ocnt += cnt;
2120                 spin_unlock_irqrestore(&s->lock, flags);
2121                 count -= cnt;
2122                 buffer += cnt;
2123                 ret += cnt;
2124                 spin_lock_irqsave(&s->lock, flags);
2125                 sv_handle_midi(s);
2126                 spin_unlock_irqrestore(&s->lock, flags);
2127         }
2128         __set_current_state(TASK_RUNNING);
2129         remove_wait_queue(&s->midi.owait, &wait);
2130         return ret;
2131 }
2132
2133 /* No kernel lock - we have our own spinlock */
2134 static unsigned int sv_midi_poll(struct file *file, struct poll_table_struct *wait)
2135 {
2136         struct sv_state *s = (struct sv_state *)file->private_data;
2137         unsigned long flags;
2138         unsigned int mask = 0;
2139
2140         VALIDATE_STATE(s);
2141         if (file->f_mode & FMODE_WRITE)
2142                 poll_wait(file, &s->midi.owait, wait);
2143         if (file->f_mode & FMODE_READ)
2144                 poll_wait(file, &s->midi.iwait, wait);
2145         spin_lock_irqsave(&s->lock, flags);
2146         if (file->f_mode & FMODE_READ) {
2147                 if (s->midi.icnt > 0)
2148                         mask |= POLLIN | POLLRDNORM;
2149         }
2150         if (file->f_mode & FMODE_WRITE) {
2151                 if (s->midi.ocnt < MIDIOUTBUF)
2152                         mask |= POLLOUT | POLLWRNORM;
2153         }
2154         spin_unlock_irqrestore(&s->lock, flags);
2155         return mask;
2156 }
2157
2158 static int sv_midi_open(struct inode *inode, struct file *file)
2159 {
2160         int minor = MINOR(inode->i_rdev);
2161         DECLARE_WAITQUEUE(wait, current);
2162         unsigned long flags;
2163         struct list_head *list;
2164         struct sv_state *s;
2165
2166         for (list = devs.next; ; list = list->next) {
2167                 if (list == &devs)
2168                         return -ENODEV;
2169                 s = list_entry(list, struct sv_state, devs);
2170                 if (s->dev_midi == minor)
2171                         break;
2172         }
2173         VALIDATE_STATE(s);
2174         file->private_data = s;
2175         /* wait for device to become free */
2176         down(&s->open_sem);
2177         while (s->open_mode & (file->f_mode << FMODE_MIDI_SHIFT)) {
2178                 if (file->f_flags & O_NONBLOCK) {
2179                         up(&s->open_sem);
2180                         return -EBUSY;
2181                 }
2182                 add_wait_queue(&s->open_wait, &wait);
2183                 __set_current_state(TASK_INTERRUPTIBLE);
2184                 up(&s->open_sem);
2185                 schedule();
2186                 remove_wait_queue(&s->open_wait, &wait);
2187                 set_current_state(TASK_RUNNING);
2188                 if (signal_pending(current))
2189                         return -ERESTARTSYS;
2190                 down(&s->open_sem);
2191         }
2192         spin_lock_irqsave(&s->lock, flags);
2193         if (!(s->open_mode & (FMODE_MIDI_READ | FMODE_MIDI_WRITE))) {
2194                 s->midi.ird = s->midi.iwr = s->midi.icnt = 0;
2195                 s->midi.ord = s->midi.owr = s->midi.ocnt = 0;
2196                 //outb(inb(s->ioenh + SV_CODEC_CONTROL) | SV_CCTRL_WAVETABLE, s->ioenh + SV_CODEC_CONTROL);
2197                 outb(inb(s->ioenh + SV_CODEC_INTMASK) | SV_CINTMASK_MIDI, s->ioenh + SV_CODEC_INTMASK);
2198                 wrindir(s, SV_CIUARTCONTROL, 5); /* output MIDI data to external and internal synth */
2199                 wrindir(s, SV_CIWAVETABLESRC, 1); /* Wavetable in PC RAM */
2200                 outb(0xff, s->iomidi+1); /* reset command */
2201                 outb(0x3f, s->iomidi+1); /* uart command */
2202                 if (!(inb(s->iomidi+1) & 0x80))
2203                         inb(s->iomidi);
2204                 s->midi.ird = s->midi.iwr = s->midi.icnt = 0;
2205                 init_timer(&s->midi.timer);
2206                 s->midi.timer.expires = jiffies+1;
2207                 s->midi.timer.data = (unsigned long)s;
2208                 s->midi.timer.function = sv_midi_timer;
2209                 add_timer(&s->midi.timer);
2210         }
2211         if (file->f_mode & FMODE_READ) {
2212                 s->midi.ird = s->midi.iwr = s->midi.icnt = 0;
2213         }
2214         if (file->f_mode & FMODE_WRITE) {
2215                 s->midi.ord = s->midi.owr = s->midi.ocnt = 0;
2216         }
2217         spin_unlock_irqrestore(&s->lock, flags);
2218         s->open_mode |= (file->f_mode << FMODE_MIDI_SHIFT) & (FMODE_MIDI_READ | FMODE_MIDI_WRITE);
2219         up(&s->open_sem);
2220         return 0;
2221 }
2222
2223 static int sv_midi_release(struct inode *inode, struct file *file)
2224 {
2225         struct sv_state *s = (struct sv_state *)file->private_data;
2226         DECLARE_WAITQUEUE(wait, current);
2227         unsigned long flags;
2228         unsigned count, tmo;
2229
2230         VALIDATE_STATE(s);
2231
2232         lock_kernel();
2233         if (file->f_mode & FMODE_WRITE) {
2234                 add_wait_queue(&s->midi.owait, &wait);
2235                 for (;;) {
2236                         __set_current_state(TASK_INTERRUPTIBLE);
2237                         spin_lock_irqsave(&s->lock, flags);
2238                         count = s->midi.ocnt;
2239                         spin_unlock_irqrestore(&s->lock, flags);
2240                         if (count <= 0)
2241                                 break;
2242                         if (signal_pending(current))
2243                                 break;
2244                         if (file->f_flags & O_NONBLOCK) {
2245                                 remove_wait_queue(&s->midi.owait, &wait);
2246                                 set_current_state(TASK_RUNNING);
2247                                 unlock_kernel();
2248                                 return -EBUSY;
2249                         }
2250                         tmo = (count * HZ) / 3100;
2251                         if (!schedule_timeout(tmo ? : 1) && tmo)
2252                                 printk(KERN_DEBUG "sv: midi timed out??\n");
2253                 }
2254                 remove_wait_queue(&s->midi.owait, &wait);
2255                 set_current_state(TASK_RUNNING);
2256         }
2257         down(&s->open_sem);
2258         s->open_mode &= (~(file->f_mode << FMODE_MIDI_SHIFT)) & (FMODE_MIDI_READ|FMODE_MIDI_WRITE);
2259         spin_lock_irqsave(&s->lock, flags);
2260         if (!(s->open_mode & (FMODE_MIDI_READ | FMODE_MIDI_WRITE))) {
2261                 outb(inb(s->ioenh + SV_CODEC_INTMASK) & ~SV_CINTMASK_MIDI, s->ioenh + SV_CODEC_INTMASK);
2262                 del_timer(&s->midi.timer);              
2263         }
2264         spin_unlock_irqrestore(&s->lock, flags);
2265         wake_up(&s->open_wait);
2266         up(&s->open_sem);
2267         unlock_kernel();
2268         return 0;
2269 }
2270
2271 static /*const*/ struct file_operations sv_midi_fops = {
2272         owner:          THIS_MODULE,
2273         llseek:         no_llseek,
2274         read:           sv_midi_read,
2275         write:          sv_midi_write,
2276         poll:           sv_midi_poll,
2277         open:           sv_midi_open,
2278         release:        sv_midi_release,
2279 };
2280
2281 /* --------------------------------------------------------------------- */
2282
2283 static int sv_dmfm_ioctl(struct inode *inode, struct file *file, unsigned int cmd, unsigned long arg)
2284 {
2285         static const unsigned char op_offset[18] = {
2286                 0x00, 0x01, 0x02, 0x03, 0x04, 0x05,
2287                 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D,
2288                 0x10, 0x11, 0x12, 0x13, 0x14, 0x15
2289         };
2290         struct sv_state *s = (struct sv_state *)file->private_data;
2291         struct dm_fm_voice v;
2292         struct dm_fm_note n;
2293         struct dm_fm_params p;
2294         unsigned int io;
2295         unsigned int regb;
2296
2297         switch (cmd) {          
2298         case FM_IOCTL_RESET:
2299                 for (regb = 0xb0; regb < 0xb9; regb++) {
2300                         outb(regb, s->iosynth);
2301                         outb(0, s->iosynth+1);
2302                         outb(regb, s->iosynth+2);
2303                         outb(0, s->iosynth+3);
2304                 }
2305                 return 0;
2306
2307         case FM_IOCTL_PLAY_NOTE:
2308                 if (copy_from_user(&n, (void *)arg, sizeof(n)))
2309                         return -EFAULT;
2310                 if (n.voice >= 18)
2311                         return -EINVAL;
2312                 if (n.voice >= 9) {
2313                         regb = n.voice - 9;
2314                         io = s->iosynth+2;
2315                 } else {
2316                         regb = n.voice;
2317                         io = s->iosynth;
2318                 }
2319                 outb(0xa0 + regb, io);
2320                 outb(n.fnum & 0xff, io+1);
2321                 outb(0xb0 + regb, io);
2322                 outb(((n.fnum >> 8) & 3) | ((n.octave & 7) << 2) | ((n.key_on & 1) << 5), io+1);
2323                 return 0;
2324
2325         case FM_IOCTL_SET_VOICE:
2326                 if (copy_from_user(&v, (void *)arg, sizeof(v)))
2327                         return -EFAULT;
2328                 if (v.voice >= 18)
2329                         return -EINVAL;
2330                 regb = op_offset[v.voice];
2331                 io = s->iosynth + ((v.op & 1) << 1);
2332                 outb(0x20 + regb, io);
2333                 outb(((v.am & 1) << 7) | ((v.vibrato & 1) << 6) | ((v.do_sustain & 1) << 5) | 
2334                      ((v.kbd_scale & 1) << 4) | (v.harmonic & 0xf), io+1);
2335                 outb(0x40 + regb, io);
2336                 outb(((v.scale_level & 0x3) << 6) | (v.volume & 0x3f), io+1);
2337                 outb(0x60 + regb, io);
2338                 outb(((v.attack & 0xf) << 4) | (v.decay & 0xf), io+1);
2339                 outb(0x80 + regb, io);
2340                 outb(((v.sustain & 0xf) << 4) | (v.release & 0xf), io+1);
2341                 outb(0xe0 + regb, io);
2342                 outb(v.waveform & 0x7, io+1);
2343                 if (n.voice >= 9) {
2344                         regb = n.voice - 9;
2345                         io = s->iosynth+2;
2346                 } else {
2347                         regb = n.voice;
2348                         io = s->iosynth;
2349                 }
2350                 outb(0xc0 + regb, io);
2351                 outb(((v.right & 1) << 5) | ((v.left & 1) << 4) | ((v.feedback & 7) << 1) |
2352                      (v.connection & 1), io+1);
2353                 return 0;
2354                 
2355         case FM_IOCTL_SET_PARAMS:
2356                 if (copy_from_user(&p, (void *)arg, sizeof(p)))
2357                         return -EFAULT;
2358                 outb(0x08, s->iosynth);
2359                 outb((p.kbd_split & 1) << 6, s->iosynth+1);
2360                 outb(0xbd, s->iosynth);
2361                 outb(((p.am_depth & 1) << 7) | ((p.vib_depth & 1) << 6) | ((p.rhythm & 1) << 5) | ((p.bass & 1) << 4) |
2362                      ((p.snare & 1) << 3) | ((p.tomtom & 1) << 2) | ((p.cymbal & 1) << 1) | (p.hihat & 1), s->iosynth+1);
2363                 return 0;
2364
2365         case FM_IOCTL_SET_OPL:
2366                 outb(4, s->iosynth+2);
2367                 outb(arg, s->iosynth+3);
2368                 return 0;
2369
2370         case FM_IOCTL_SET_MODE:
2371                 outb(5, s->iosynth+2);
2372                 outb(arg & 1, s->iosynth+3);
2373                 return 0;
2374
2375         default:
2376                 return -EINVAL;
2377         }
2378 }
2379
2380 static int sv_dmfm_open(struct inode *inode, struct file *file)
2381 {
2382         int minor = MINOR(inode->i_rdev);
2383         DECLARE_WAITQUEUE(wait, current);
2384         struct list_head *list;
2385         struct sv_state *s;
2386
2387         for (list = devs.next; ; list = list->next) {
2388                 if (list == &devs)
2389                         return -ENODEV;
2390                 s = list_entry(list, struct sv_state, devs);
2391                 if (s->dev_dmfm == minor)
2392                         break;
2393         }
2394         VALIDATE_STATE(s);
2395         file->private_data = s;
2396         /* wait for device to become free */
2397         down(&s->open_sem);
2398         while (s->open_mode & FMODE_DMFM) {
2399                 if (file->f_flags & O_NONBLOCK) {
2400                         up(&s->open_sem);
2401                         return -EBUSY;
2402                 }
2403                 add_wait_queue(&s->open_wait, &wait);
2404                 __set_current_state(TASK_INTERRUPTIBLE);
2405                 up(&s->open_sem);
2406                 schedule();
2407                 remove_wait_queue(&s->open_wait, &wait);
2408                 set_current_state(TASK_RUNNING);
2409                 if (signal_pending(current))
2410                         return -ERESTARTSYS;
2411                 down(&s->open_sem);
2412         }
2413         /* init the stuff */
2414         outb(1, s->iosynth);
2415         outb(0x20, s->iosynth+1); /* enable waveforms */
2416         outb(4, s->iosynth+2);
2417         outb(0, s->iosynth+3);  /* no 4op enabled */
2418         outb(5, s->iosynth+2);
2419         outb(1, s->iosynth+3);  /* enable OPL3 */
2420         s->open_mode |= FMODE_DMFM;
2421         up(&s->open_sem);
2422         return 0;
2423 }
2424
2425 static int sv_dmfm_release(struct inode *inode, struct file *file)
2426 {
2427         struct sv_state *s = (struct sv_state *)file->private_data;
2428         unsigned int regb;
2429
2430         VALIDATE_STATE(s);
2431         lock_kernel();
2432         down(&s->open_sem);
2433         s->open_mode &= ~FMODE_DMFM;
2434         for (regb = 0xb0; regb < 0xb9; regb++) {
2435                 outb(regb, s->iosynth);
2436                 outb(0, s->iosynth+1);
2437                 outb(regb, s->iosynth+2);
2438                 outb(0, s->iosynth+3);
2439         }
2440         wake_up(&s->open_wait);
2441         up(&s->open_sem);
2442         unlock_kernel();
2443         return 0;
2444 }
2445
2446 static /*const*/ struct file_operations sv_dmfm_fops = {
2447         owner:          THIS_MODULE,
2448         llseek:         no_llseek,
2449         ioctl:          sv_dmfm_ioctl,
2450         open:           sv_dmfm_open,
2451         release:        sv_dmfm_release,
2452 };
2453
2454 /* --------------------------------------------------------------------- */
2455
2456 /* maximum number of devices; only used for command line params */
2457 #define NR_DEVICE 5
2458
2459 static int reverb[NR_DEVICE] = { 0, };
2460
2461 #if 0
2462 static int wavetable[NR_DEVICE] = { 0, };
2463 #endif
2464
2465 static unsigned int devindex = 0;
2466
2467 MODULE_PARM(reverb, "1-" __MODULE_STRING(NR_DEVICE) "i");
2468 MODULE_PARM_DESC(reverb, "if 1 enables the reverb circuitry. NOTE: your card must have the reverb RAM");
2469 #if 0
2470 MODULE_PARM(wavetable, "1-" __MODULE_STRING(NR_DEVICE) "i");
2471 MODULE_PARM_DESC(wavetable, "if 1 the wavetable synth is enabled");
2472 #endif
2473
2474 MODULE_AUTHOR("Thomas M. Sailer, sailer@ife.ee.ethz.ch, hb9jnx@hb9w.che.eu");
2475 MODULE_DESCRIPTION("S3 SonicVibes Driver");
2476
2477 /* --------------------------------------------------------------------- */
2478
2479 static struct initvol {
2480         int mixch;
2481         int vol;
2482 } initvol[] __initdata = {
2483         { SOUND_MIXER_WRITE_RECLEV, 0x4040 },
2484         { SOUND_MIXER_WRITE_LINE1, 0x4040 },
2485         { SOUND_MIXER_WRITE_CD, 0x4040 },
2486         { SOUND_MIXER_WRITE_LINE, 0x4040 },
2487         { SOUND_MIXER_WRITE_MIC, 0x4040 },
2488         { SOUND_MIXER_WRITE_SYNTH, 0x4040 },
2489         { SOUND_MIXER_WRITE_LINE2, 0x4040 },
2490         { SOUND_MIXER_WRITE_VOLUME, 0x4040 },
2491         { SOUND_MIXER_WRITE_PCM, 0x4040 }
2492 };
2493
2494 #define RSRCISIOREGION(dev,num) (pci_resource_start((dev), (num)) != 0 && \
2495                                  (pci_resource_flags((dev), (num)) & IORESOURCE_IO))
2496
2497 static int __devinit sv_probe(struct pci_dev *pcidev, const struct pci_device_id *pciid)
2498 {
2499         static const char __initdata sv_ddma_name[] = "S3 Inc. SonicVibes DDMA Controller";
2500         struct sv_state *s;
2501         mm_segment_t fs;
2502         int i, val, ret;
2503         char *ddmaname;
2504         unsigned ddmanamelen;
2505
2506         if ((ret=pci_enable_device(pcidev)))
2507                 return ret;
2508
2509         if (!RSRCISIOREGION(pcidev, RESOURCE_SB) ||
2510             !RSRCISIOREGION(pcidev, RESOURCE_ENH) ||
2511             !RSRCISIOREGION(pcidev, RESOURCE_SYNTH) ||
2512             !RSRCISIOREGION(pcidev, RESOURCE_MIDI) ||
2513             !RSRCISIOREGION(pcidev, RESOURCE_GAME))
2514                 return -ENODEV;
2515         if (pcidev->irq == 0)
2516                 return -ENODEV;
2517         if (pci_set_dma_mask(pcidev, 0x00ffffff)) {
2518                 printk(KERN_WARNING "sonicvibes: architecture does not support 24bit PCI busmaster DMA\n");
2519                 return -ENODEV;
2520         }
2521         /* try to allocate a DDMA resource if not already available */
2522         if (!RSRCISIOREGION(pcidev, RESOURCE_DDMA)) {
2523                 pcidev->resource[RESOURCE_DDMA].start = 0;
2524                 pcidev->resource[RESOURCE_DDMA].end = 2*SV_EXTENT_DMA-1;
2525                 pcidev->resource[RESOURCE_DDMA].flags = PCI_BASE_ADDRESS_SPACE_IO | IORESOURCE_IO;
2526                 ddmanamelen = strlen(sv_ddma_name)+1;
2527                 if (!(ddmaname = kmalloc(ddmanamelen, GFP_KERNEL)))
2528                         return -1;
2529                 memcpy(ddmaname, sv_ddma_name, ddmanamelen);
2530                 pcidev->resource[RESOURCE_DDMA].name = ddmaname;
2531                 if (pci_assign_resource(pcidev, RESOURCE_DDMA)) {
2532                         pcidev->resource[RESOURCE_DDMA].name = NULL;
2533                         kfree(ddmaname);
2534                         printk(KERN_ERR "sv: cannot allocate DDMA controller io ports\n");
2535                         return -EBUSY;
2536                 }
2537         }
2538         if (!(s = kmalloc(sizeof(struct sv_state), GFP_KERNEL))) {
2539                 printk(KERN_WARNING "sv: out of memory\n");
2540                 return -ENOMEM;
2541         }
2542         memset(s, 0, sizeof(struct sv_state));
2543         init_waitqueue_head(&s->dma_adc.wait);
2544         init_waitqueue_head(&s->dma_dac.wait);
2545         init_waitqueue_head(&s->open_wait);
2546         init_waitqueue_head(&s->midi.iwait);
2547         init_waitqueue_head(&s->midi.owait);
2548         init_MUTEX(&s->open_sem);
2549         spin_lock_init(&s->lock);
2550         s->magic = SV_MAGIC;
2551         s->dev = pcidev;
2552         s->iosb = pci_resource_start(pcidev, RESOURCE_SB);
2553         s->ioenh = pci_resource_start(pcidev, RESOURCE_ENH);
2554         s->iosynth = pci_resource_start(pcidev, RESOURCE_SYNTH);
2555         s->iomidi = pci_resource_start(pcidev, RESOURCE_MIDI);
2556         s->iodmaa = pci_resource_start(pcidev, RESOURCE_DDMA);
2557         s->iodmac = pci_resource_start(pcidev, RESOURCE_DDMA) + SV_EXTENT_DMA;
2558         s->gameport.io = pci_resource_start(pcidev, RESOURCE_GAME);
2559         pci_write_config_dword(pcidev, 0x40, s->iodmaa | 9);  /* enable and use extended mode */
2560         pci_write_config_dword(pcidev, 0x48, s->iodmac | 9);  /* enable */
2561         printk(KERN_DEBUG "sv: io ports: %#lx %#lx %#lx %#lx %#x %#x %#x\n",
2562                s->iosb, s->ioenh, s->iosynth, s->iomidi, s->gameport.io, s->iodmaa, s->iodmac);
2563         s->irq = pcidev->irq;
2564         
2565         /* hack */
2566         pci_write_config_dword(pcidev, 0x60, wavetable_mem >> 12);  /* wavetable base address */
2567
2568         ret = -EBUSY;
2569         if (!request_region(s->ioenh, SV_EXTENT_ENH, "S3 SonicVibes PCM")) {
2570                 printk(KERN_ERR "sv: io ports %#lx-%#lx in use\n", s->ioenh, s->ioenh+SV_EXTENT_ENH-1);
2571                 goto err_region5;
2572         }
2573         if (!request_region(s->iodmaa, SV_EXTENT_DMA, "S3 SonicVibes DMAA")) {
2574                 printk(KERN_ERR "sv: io ports %#x-%#x in use\n", s->iodmaa, s->iodmaa+SV_EXTENT_DMA-1);
2575                 goto err_region4;
2576         }
2577         if (!request_region(s->iodmac, SV_EXTENT_DMA, "S3 SonicVibes DMAC")) {
2578                 printk(KERN_ERR "sv: io ports %#x-%#x in use\n", s->iodmac, s->iodmac+SV_EXTENT_DMA-1);
2579                 goto err_region3;
2580         }
2581         if (!request_region(s->iomidi, SV_EXTENT_MIDI, "S3 SonicVibes Midi")) {
2582                 printk(KERN_ERR "sv: io ports %#lx-%#lx in use\n", s->iomidi, s->iomidi+SV_EXTENT_MIDI-1);
2583                 goto err_region2;
2584         }
2585         if (!request_region(s->iosynth, SV_EXTENT_SYNTH, "S3 SonicVibes Synth")) {
2586                 printk(KERN_ERR "sv: io ports %#lx-%#lx in use\n", s->iosynth, s->iosynth+SV_EXTENT_SYNTH-1);
2587                 goto err_region1;
2588         }
2589         if (s->gameport.io && !request_region(s->gameport.io, SV_EXTENT_GAME, "ESS Solo1")) {
2590                 printk(KERN_ERR "sv: gameport io ports in use\n");
2591                 s->gameport.io = 0;
2592         }
2593         /* initialize codec registers */
2594         outb(0x80, s->ioenh + SV_CODEC_CONTROL); /* assert reset */
2595         udelay(50);
2596         outb(0x00, s->ioenh + SV_CODEC_CONTROL); /* deassert reset */
2597         udelay(50);
2598         outb(SV_CCTRL_INTADRIVE | SV_CCTRL_ENHANCED /*| SV_CCTRL_WAVETABLE */
2599              | (reverb[devindex] ? SV_CCTRL_REVERB : 0), s->ioenh + SV_CODEC_CONTROL);
2600         inb(s->ioenh + SV_CODEC_STATUS); /* clear ints */
2601         wrindir(s, SV_CIDRIVECONTROL, 0);  /* drive current 16mA */
2602         wrindir(s, SV_CIENABLE, s->enable = 0);  /* disable DMAA and DMAC */
2603         outb(~(SV_CINTMASK_DMAA | SV_CINTMASK_DMAC), s->ioenh + SV_CODEC_INTMASK);
2604         /* outb(0xff, s->iodmaa + SV_DMA_RESET); */
2605         /* outb(0xff, s->iodmac + SV_DMA_RESET); */
2606         inb(s->ioenh + SV_CODEC_STATUS); /* ack interrupts */
2607         wrindir(s, SV_CIADCCLKSOURCE, 0); /* use pll as ADC clock source */
2608         wrindir(s, SV_CIANALOGPWRDOWN, 0); /* power up the analog parts of the device */
2609         wrindir(s, SV_CIDIGITALPWRDOWN, 0); /* power up the digital parts of the device */
2610         setpll(s, SV_CIADCPLLM, 8000);
2611         wrindir(s, SV_CISRSSPACE, 0x80); /* SRS off */
2612         wrindir(s, SV_CIPCMSR0, (8000 * 65536 / FULLRATE) & 0xff);
2613         wrindir(s, SV_CIPCMSR1, ((8000 * 65536 / FULLRATE) >> 8) & 0xff);
2614         wrindir(s, SV_CIADCOUTPUT, 0);
2615         /* request irq */
2616         if ((ret=request_irq(s->irq,sv_interrupt,SA_SHIRQ,"S3 SonicVibes",s))) {
2617                 printk(KERN_ERR "sv: irq %u in use\n", s->irq);