patch-2_6_7-vs1_9_1_12
[linux-2.6.git] / sound / oss / gus_wave.c
1 /*
2  * sound/gus_wave.c
3  *
4  * Driver for the Gravis UltraSound wave table synth.
5  *
6  *
7  * Copyright (C) by Hannu Savolainen 1993-1997
8  *
9  * OSS/Free for Linux is distributed under the GNU GENERAL PUBLIC LICENSE (GPL)
10  * Version 2 (June 1991). See the "COPYING" file distributed with this software
11  * for more info.
12  *
13  *
14  * Thomas Sailer    : ioctl code reworked (vmalloc/vfree removed)
15  * Frank van de Pol : Fixed GUS MAX interrupt handling. Enabled simultanious
16  *                    usage of CS4231A codec, GUS wave and MIDI for GUS MAX.
17  * Bartlomiej Zolnierkiewicz : added some __init/__exit
18  */
19  
20 #include <linux/init.h> 
21 #include <linux/config.h>
22 #include <linux/spinlock.h>
23
24 #define GUSPNP_AUTODETECT
25
26 #include "sound_config.h"
27 #include <linux/ultrasound.h>
28
29 #include "gus.h"
30 #include "gus_hw.h"
31
32 #define GUS_BANK_SIZE (((iw_mode) ? 256*1024*1024 : 256*1024))
33
34 #define MAX_SAMPLE      150
35 #define MAX_PATCH       256
36
37 #define NOT_SAMPLE      0xffff
38
39 struct voice_info
40 {
41         unsigned long   orig_freq;
42         unsigned long   current_freq;
43         unsigned long   mode;
44         int             fixed_pitch;
45         int             bender;
46         int             bender_range;
47         int             panning;
48         int             midi_volume;
49         unsigned int    initial_volume;
50         unsigned int    current_volume;
51         int             loop_irq_mode, loop_irq_parm;
52 #define LMODE_FINISH            1
53 #define LMODE_PCM               2
54 #define LMODE_PCM_STOP          3
55         int             volume_irq_mode, volume_irq_parm;
56 #define VMODE_HALT              1
57 #define VMODE_ENVELOPE          2
58 #define VMODE_START_NOTE        3
59
60         int             env_phase;
61         unsigned char   env_rate[6];
62         unsigned char   env_offset[6];
63
64         /*
65          * Volume computation parameters for gus_adagio_vol()
66          */
67         int             main_vol, expression_vol, patch_vol;
68
69         /* Variables for "Ultraclick" removal */
70         int             dev_pending, note_pending, volume_pending,
71                         sample_pending;
72         char            kill_pending;
73         long            offset_pending;
74
75 };
76
77 static struct voice_alloc_info *voice_alloc;
78 static struct address_info *gus_hw_config;
79 extern int      gus_base;
80 extern int      gus_irq, gus_dma;
81 extern int      gus_pnp_flag;
82 extern int      gus_no_wave_dma;
83 static int      gus_dma2 = -1;
84 static int      dual_dma_mode;
85 static long     gus_mem_size;
86 static long     free_mem_ptr;
87 static int      gus_busy;
88 static int      gus_no_dma;
89 static int      nr_voices;
90 static int      gus_devnum;
91 static int      volume_base, volume_scale, volume_method;
92 static int      gus_recmask = SOUND_MASK_MIC;
93 static int      recording_active;
94 static int      only_read_access;
95 static int      only_8_bits;
96
97 int             iw_mode = 0;
98 int             gus_wave_volume = 60;
99 int             gus_pcm_volume = 80;
100 int             have_gus_max = 0;
101 static int      gus_line_vol = 100, gus_mic_vol;
102 static unsigned char mix_image = 0x00;
103
104 int             gus_timer_enabled = 0;
105
106 /*
107  * Current version of this driver doesn't allow synth and PCM functions
108  * at the same time. The active_device specifies the active driver
109  */
110
111 static int      active_device;
112
113 #define GUS_DEV_WAVE            1       /* Wave table synth */
114 #define GUS_DEV_PCM_DONE        2       /* PCM device, transfer done */
115 #define GUS_DEV_PCM_CONTINUE    3       /* PCM device, transfer done ch. 1/2 */
116
117 static int      gus_audio_speed;
118 static int      gus_audio_channels;
119 static int      gus_audio_bits;
120 static int      gus_audio_bsize;
121 static char     bounce_buf[8 * 1024];   /* Must match value set to max_fragment */
122
123 static DECLARE_WAIT_QUEUE_HEAD(dram_sleeper);
124
125 /*
126  * Variables and buffers for PCM output
127  */
128
129 #define MAX_PCM_BUFFERS         (128*MAX_REALTIME_FACTOR)       /* Don't change */
130
131 static int      pcm_bsize, pcm_nblk, pcm_banksize;
132 static int      pcm_datasize[MAX_PCM_BUFFERS];
133 static volatile int pcm_head, pcm_tail, pcm_qlen;
134 static volatile int pcm_active;
135 static volatile int dma_active;
136 static int      pcm_opened;
137 static int      pcm_current_dev;
138 static int      pcm_current_block;
139 static unsigned long pcm_current_buf;
140 static int      pcm_current_count;
141 static int      pcm_current_intrflag;
142 spinlock_t gus_lock=SPIN_LOCK_UNLOCKED;
143
144 extern int     *gus_osp;
145
146 static struct voice_info voices[32];
147
148 static int      freq_div_table[] =
149 {
150         44100,                  /* 14 */
151         41160,                  /* 15 */
152         38587,                  /* 16 */
153         36317,                  /* 17 */
154         34300,                  /* 18 */
155         32494,                  /* 19 */
156         30870,                  /* 20 */
157         29400,                  /* 21 */
158         28063,                  /* 22 */
159         26843,                  /* 23 */
160         25725,                  /* 24 */
161         24696,                  /* 25 */
162         23746,                  /* 26 */
163         22866,                  /* 27 */
164         22050,                  /* 28 */
165         21289,                  /* 29 */
166         20580,                  /* 30 */
167         19916,                  /* 31 */
168         19293                   /* 32 */
169 };
170
171 static struct patch_info *samples;
172 static long     sample_ptrs[MAX_SAMPLE + 1];
173 static int      sample_map[32];
174 static int      free_sample;
175 static int      mixer_type;
176
177
178 static int      patch_table[MAX_PATCH];
179 static int      patch_map[32];
180
181 static struct synth_info gus_info = {
182         "Gravis UltraSound", 0, SYNTH_TYPE_SAMPLE, SAMPLE_TYPE_GUS, 
183         0, 16, 0, MAX_PATCH
184 };
185
186 static void     gus_poke(long addr, unsigned char data);
187 static void     compute_and_set_volume(int voice, int volume, int ramp_time);
188 extern unsigned short gus_adagio_vol(int vel, int mainv, int xpn, int voicev);
189 extern unsigned short gus_linear_vol(int vol, int mainvol);
190 static void     compute_volume(int voice, int volume);
191 static void     do_volume_irq(int voice);
192 static void     set_input_volumes(void);
193 static void     gus_tmr_install(int io_base);
194
195 #define INSTANT_RAMP            -1      /* Instant change. No ramping */
196 #define FAST_RAMP               0       /* Fastest possible ramp */
197
198 static void reset_sample_memory(void)
199 {
200         int i;
201
202         for (i = 0; i <= MAX_SAMPLE; i++)
203                 sample_ptrs[i] = -1;
204         for (i = 0; i < 32; i++)
205                 sample_map[i] = -1;
206         for (i = 0; i < 32; i++)
207                 patch_map[i] = -1;
208
209         gus_poke(0, 0);         /* Put a silent sample to the beginning */
210         gus_poke(1, 0);
211         free_mem_ptr = 2;
212
213         free_sample = 0;
214
215         for (i = 0; i < MAX_PATCH; i++)
216                 patch_table[i] = NOT_SAMPLE;
217 }
218
219 void gus_delay(void)
220 {
221         int i;
222
223         for (i = 0; i < 7; i++)
224                 inb(u_DRAMIO);
225 }
226
227 static void gus_poke(long addr, unsigned char data)
228 {                               /* Writes a byte to the DRAM */
229         outb((0x43), u_Command);
230         outb((addr & 0xff), u_DataLo);
231         outb(((addr >> 8) & 0xff), u_DataHi);
232
233         outb((0x44), u_Command);
234         outb(((addr >> 16) & 0xff), u_DataHi);
235         outb((data), u_DRAMIO);
236 }
237
238 static unsigned char gus_peek(long addr)
239 {                               /* Reads a byte from the DRAM */
240         unsigned char   tmp;
241
242         outb((0x43), u_Command);
243         outb((addr & 0xff), u_DataLo);
244         outb(((addr >> 8) & 0xff), u_DataHi);
245
246         outb((0x44), u_Command);
247         outb(((addr >> 16) & 0xff), u_DataHi);
248         tmp = inb(u_DRAMIO);
249
250         return tmp;
251 }
252
253 void gus_write8(int reg, unsigned int data)
254 {                               /* Writes to an indirect register (8 bit) */
255         outb((reg), u_Command);
256         outb(((unsigned char) (data & 0xff)), u_DataHi);
257 }
258
259 static unsigned char gus_read8(int reg)
260 {                               
261         /* Reads from an indirect register (8 bit). Offset 0x80. */
262         unsigned char   val;
263
264         outb((reg | 0x80), u_Command);
265         val = inb(u_DataHi);
266
267         return val;
268 }
269
270 static unsigned char gus_look8(int reg)
271 {
272         /* Reads from an indirect register (8 bit). No additional offset. */
273         unsigned char   val;
274
275         outb((reg), u_Command);
276         val = inb(u_DataHi);
277
278         return val;
279 }
280
281 static void gus_write16(int reg, unsigned int data)
282 {
283         /* Writes to an indirect register (16 bit) */
284         outb((reg), u_Command);
285
286         outb(((unsigned char) (data & 0xff)), u_DataLo);
287         outb(((unsigned char) ((data >> 8) & 0xff)), u_DataHi);
288 }
289
290 static unsigned short gus_read16(int reg)
291 {
292         /* Reads from an indirect register (16 bit). Offset 0x80. */
293         unsigned char   hi, lo;
294
295         outb((reg | 0x80), u_Command);
296
297         lo = inb(u_DataLo);
298         hi = inb(u_DataHi);
299
300         return ((hi << 8) & 0xff00) | lo;
301 }
302
303 static unsigned short gus_look16(int reg)
304 {               
305         /* Reads from an indirect register (16 bit). No additional offset. */
306         unsigned char   hi, lo;
307
308         outb((reg), u_Command);
309
310         lo = inb(u_DataLo);
311         hi = inb(u_DataHi);
312
313         return ((hi << 8) & 0xff00) | lo;
314 }
315
316 static void gus_write_addr(int reg, unsigned long address, int frac, int is16bit)
317 {
318         /* Writes an 24 bit memory address */
319         unsigned long   hold_address;
320
321         if (is16bit)
322         {
323                 if (iw_mode)
324                 {
325                         /* Interwave spesific address translations */
326                         address >>= 1;
327                 }
328                 else
329                 {
330                         /*
331                          * Special processing required for 16 bit patches
332                          */
333
334                         hold_address = address;
335                         address = address >> 1;
336                         address &= 0x0001ffffL;
337                         address |= (hold_address & 0x000c0000L);
338                 }
339         }
340         gus_write16(reg, (unsigned short) ((address >> 7) & 0xffff));
341         gus_write16(reg + 1, (unsigned short) ((address << 9) & 0xffff)
342                     + (frac << 5));
343         /* Could writing twice fix problems with GUS_VOICE_POS()? Let's try. */
344         gus_delay();
345         gus_write16(reg, (unsigned short) ((address >> 7) & 0xffff));
346         gus_write16(reg + 1, (unsigned short) ((address << 9) & 0xffff)
347                     + (frac << 5));
348 }
349
350 static void gus_select_voice(int voice)
351 {
352         if (voice < 0 || voice > 31)
353                 return;
354         outb((voice), u_Voice);
355 }
356
357 static void gus_select_max_voices(int nvoices)
358 {
359         if (iw_mode)
360                 nvoices = 32;
361         if (nvoices < 14)
362                 nvoices = 14;
363         if (nvoices > 32)
364                 nvoices = 32;
365
366         voice_alloc->max_voice = nr_voices = nvoices;
367         gus_write8(0x0e, (nvoices - 1) | 0xc0);
368 }
369
370 static void gus_voice_on(unsigned int mode)
371 {
372         gus_write8(0x00, (unsigned char) (mode & 0xfc));
373         gus_delay();
374         gus_write8(0x00, (unsigned char) (mode & 0xfc));
375 }
376
377 static void gus_voice_off(void)
378 {
379         gus_write8(0x00, gus_read8(0x00) | 0x03);
380 }
381
382 static void gus_voice_mode(unsigned int m)
383 {
384         unsigned char   mode = (unsigned char) (m & 0xff);
385
386         gus_write8(0x00, (gus_read8(0x00) & 0x03) |
387                    (mode & 0xfc));      /* Don't touch last two bits */
388         gus_delay();
389         gus_write8(0x00, (gus_read8(0x00) & 0x03) | (mode & 0xfc));
390 }
391
392 static void gus_voice_freq(unsigned long freq)
393 {
394         unsigned long   divisor = freq_div_table[nr_voices - 14];
395         unsigned short  fc;
396
397         /* Interwave plays at 44100 Hz with any number of voices */
398         if (iw_mode)
399                 fc = (unsigned short) (((freq << 9) + (44100 >> 1)) / 44100);
400         else
401                 fc = (unsigned short) (((freq << 9) + (divisor >> 1)) / divisor);
402         fc = fc << 1;
403
404         gus_write16(0x01, fc);
405 }
406
407 static void gus_voice_volume(unsigned int vol)
408 {
409         gus_write8(0x0d, 0x03); /* Stop ramp before setting volume */
410         gus_write16(0x09, (unsigned short) (vol << 4));
411 }
412
413 static void gus_voice_balance(unsigned int balance)
414 {
415         gus_write8(0x0c, (unsigned char) (balance & 0xff));
416 }
417
418 static void gus_ramp_range(unsigned int low, unsigned int high)
419 {
420         gus_write8(0x07, (unsigned char) ((low >> 4) & 0xff));
421         gus_write8(0x08, (unsigned char) ((high >> 4) & 0xff));
422 }
423
424 static void gus_ramp_rate(unsigned int scale, unsigned int rate)
425 {
426         gus_write8(0x06, (unsigned char) (((scale & 0x03) << 6) | (rate & 0x3f)));
427 }
428
429 static void gus_rampon(unsigned int m)
430 {
431         unsigned char   mode = (unsigned char) (m & 0xff);
432
433         gus_write8(0x0d, mode & 0xfc);
434         gus_delay();
435         gus_write8(0x0d, mode & 0xfc);
436 }
437
438 static void gus_ramp_mode(unsigned int m)
439 {
440         unsigned char mode = (unsigned char) (m & 0xff);
441
442         gus_write8(0x0d, (gus_read8(0x0d) & 0x03) |
443                    (mode & 0xfc));      /* Leave the last 2 bits alone */
444         gus_delay();
445         gus_write8(0x0d, (gus_read8(0x0d) & 0x03) | (mode & 0xfc));
446 }
447
448 static void gus_rampoff(void)
449 {
450         gus_write8(0x0d, 0x03);
451 }
452
453 static void gus_set_voice_pos(int voice, long position)
454 {
455         int sample_no;
456
457         if ((sample_no = sample_map[voice]) != -1) {
458                 if (position < samples[sample_no].len) {
459                         if (voices[voice].volume_irq_mode == VMODE_START_NOTE)
460                                 voices[voice].offset_pending = position;
461                         else
462                                 gus_write_addr(0x0a, sample_ptrs[sample_no] + position, 0,
463                                  samples[sample_no].mode & WAVE_16_BITS);
464                 }
465         }
466 }
467
468 static void gus_voice_init(int voice)
469 {
470         unsigned long   flags;
471
472         spin_lock_irqsave(&gus_lock,flags);
473         gus_select_voice(voice);
474         gus_voice_volume(0);
475         gus_voice_off();
476         gus_write_addr(0x0a, 0, 0, 0);  /* Set current position to 0 */
477         gus_write8(0x00, 0x03); /* Voice off */
478         gus_write8(0x0d, 0x03); /* Ramping off */
479         voice_alloc->map[voice] = 0;
480         voice_alloc->alloc_times[voice] = 0;
481         spin_unlock_irqrestore(&gus_lock,flags);
482
483 }
484
485 static void gus_voice_init2(int voice)
486 {
487         voices[voice].panning = 0;
488         voices[voice].mode = 0;
489         voices[voice].orig_freq = 20000;
490         voices[voice].current_freq = 20000;
491         voices[voice].bender = 0;
492         voices[voice].bender_range = 200;
493         voices[voice].initial_volume = 0;
494         voices[voice].current_volume = 0;
495         voices[voice].loop_irq_mode = 0;
496         voices[voice].loop_irq_parm = 0;
497         voices[voice].volume_irq_mode = 0;
498         voices[voice].volume_irq_parm = 0;
499         voices[voice].env_phase = 0;
500         voices[voice].main_vol = 127;
501         voices[voice].patch_vol = 127;
502         voices[voice].expression_vol = 127;
503         voices[voice].sample_pending = -1;
504         voices[voice].fixed_pitch = 0;
505 }
506
507 static void step_envelope(int voice)
508 {
509         unsigned        vol, prev_vol, phase;
510         unsigned char   rate;
511         unsigned long flags;
512
513         if (voices[voice].mode & WAVE_SUSTAIN_ON && voices[voice].env_phase == 2)
514         {
515                 spin_lock_irqsave(&gus_lock,flags);
516                 gus_select_voice(voice);
517                 gus_rampoff();
518                 spin_unlock_irqrestore(&gus_lock,flags);
519                 return;
520                 /*
521                  * Sustain phase begins. Continue envelope after receiving note off.
522                  */
523         }
524         if (voices[voice].env_phase >= 5)
525         {
526                 /* Envelope finished. Shoot the voice down */
527                 gus_voice_init(voice);
528                 return;
529         }
530         prev_vol = voices[voice].current_volume;
531         phase = ++voices[voice].env_phase;
532         compute_volume(voice, voices[voice].midi_volume);
533         vol = voices[voice].initial_volume * voices[voice].env_offset[phase] / 255;
534         rate = voices[voice].env_rate[phase];
535
536         spin_lock_irqsave(&gus_lock,flags);
537         gus_select_voice(voice);
538
539         gus_voice_volume(prev_vol);
540
541
542         gus_write8(0x06, rate); /* Ramping rate */
543
544         voices[voice].volume_irq_mode = VMODE_ENVELOPE;
545
546         if (((vol - prev_vol) / 64) == 0)       /* No significant volume change */
547         {
548                 spin_unlock_irqrestore(&gus_lock,flags);
549                 step_envelope(voice);           /* Continue the envelope on the next step */
550                 return;
551         }
552         if (vol > prev_vol)
553         {
554                 if (vol >= (4096 - 64))
555                         vol = 4096 - 65;
556                 gus_ramp_range(0, vol);
557                 gus_rampon(0x20);       /* Increasing volume, with IRQ */
558         }
559         else
560         {
561                 if (vol <= 64)
562                         vol = 65;
563                 gus_ramp_range(vol, 4030);
564                 gus_rampon(0x60);       /* Decreasing volume, with IRQ */
565         }
566         voices[voice].current_volume = vol;
567         spin_unlock_irqrestore(&gus_lock,flags);
568 }
569
570 static void init_envelope(int voice)
571 {
572         voices[voice].env_phase = -1;
573         voices[voice].current_volume = 64;
574
575         step_envelope(voice);
576 }
577
578 static void start_release(int voice)
579 {
580         if (gus_read8(0x00) & 0x03)
581                 return;         /* Voice already stopped */
582
583         voices[voice].env_phase = 2;    /* Will be incremented by step_envelope */
584
585         voices[voice].current_volume = voices[voice].initial_volume =
586                                                 gus_read16(0x09) >> 4;  /* Get current volume */
587
588         voices[voice].mode &= ~WAVE_SUSTAIN_ON;
589         gus_rampoff();
590         step_envelope(voice);
591 }
592
593 static void gus_voice_fade(int voice)
594 {
595         int instr_no = sample_map[voice], is16bits;
596         unsigned long flags;
597
598         spin_lock_irqsave(&gus_lock,flags);
599         gus_select_voice(voice);
600
601         if (instr_no < 0 || instr_no > MAX_SAMPLE)
602         {
603                 gus_write8(0x00, 0x03); /* Hard stop */
604                 voice_alloc->map[voice] = 0;
605                 spin_unlock_irqrestore(&gus_lock,flags);
606                 return;
607         }
608         is16bits = (samples[instr_no].mode & WAVE_16_BITS) ? 1 : 0;     /* 8 or 16 bits */
609
610         if (voices[voice].mode & WAVE_ENVELOPES)
611         {
612                 start_release(voice);
613                 spin_unlock_irqrestore(&gus_lock,flags);
614                 return;
615         }
616         /*
617          * Ramp the volume down but not too quickly.
618          */
619         if ((int) (gus_read16(0x09) >> 4) < 100)        /* Get current volume */
620         {
621                 gus_voice_off();
622                 gus_rampoff();
623                 gus_voice_init(voice);
624                 spin_unlock_irqrestore(&gus_lock,flags);
625                 return;
626         }
627         gus_ramp_range(65, 4030);
628         gus_ramp_rate(2, 4);
629         gus_rampon(0x40 | 0x20);        /* Down, once, with IRQ */
630         voices[voice].volume_irq_mode = VMODE_HALT;
631         spin_unlock_irqrestore(&gus_lock,flags);
632 }
633
634 static void gus_reset(void)
635 {
636         int i;
637
638         gus_select_max_voices(24);
639         volume_base = 3071;
640         volume_scale = 4;
641         volume_method = VOL_METHOD_ADAGIO;
642
643         for (i = 0; i < 32; i++)
644         {
645                 gus_voice_init(i);      /* Turn voice off */
646                 gus_voice_init2(i);
647         }
648 }
649
650 static void gus_initialize(void)
651 {
652         unsigned long flags;
653         unsigned char dma_image, irq_image, tmp;
654
655         static unsigned char gus_irq_map[16] =  {
656                 0, 0, 0, 3, 0, 2, 0, 4, 0, 1, 0, 5, 6, 0, 0, 7
657         };
658
659         static unsigned char gus_dma_map[8] = {
660                 0, 1, 0, 2, 0, 3, 4, 5
661         };
662
663         spin_lock_irqsave(&gus_lock,flags);
664         gus_write8(0x4c, 0);    /* Reset GF1 */
665         gus_delay();
666         gus_delay();
667
668         gus_write8(0x4c, 1);    /* Release Reset */
669         gus_delay();
670         gus_delay();
671
672         /*
673          * Clear all interrupts
674          */
675
676         gus_write8(0x41, 0);    /* DMA control */
677         gus_write8(0x45, 0);    /* Timer control */
678         gus_write8(0x49, 0);    /* Sample control */
679
680         gus_select_max_voices(24);
681
682         inb(u_Status);          /* Touch the status register */
683
684         gus_look8(0x41);        /* Clear any pending DMA IRQs */
685         gus_look8(0x49);        /* Clear any pending sample IRQs */
686         gus_read8(0x0f);        /* Clear pending IRQs */
687
688         gus_reset();            /* Resets all voices */
689
690         gus_look8(0x41);        /* Clear any pending DMA IRQs */
691         gus_look8(0x49);        /* Clear any pending sample IRQs */
692         gus_read8(0x0f);        /* Clear pending IRQs */
693
694         gus_write8(0x4c, 7);    /* Master reset | DAC enable | IRQ enable */
695
696         /*
697          * Set up for Digital ASIC
698          */
699
700         outb((0x05), gus_base + 0x0f);
701
702         mix_image |= 0x02;      /* Disable line out (for a moment) */
703         outb((mix_image), u_Mixer);
704
705         outb((0x00), u_IRQDMAControl);
706
707         outb((0x00), gus_base + 0x0f);
708
709         /*
710          * Now set up the DMA and IRQ interface
711          *
712          * The GUS supports two IRQs and two DMAs.
713          *
714          * Just one DMA channel is used. This prevents simultaneous ADC and DAC.
715          * Adding this support requires significant changes to the dmabuf.c, dsp.c
716          * and audio.c also.
717          */
718
719         irq_image = 0;
720         tmp = gus_irq_map[gus_irq];
721         if (!gus_pnp_flag && !tmp)
722                 printk(KERN_WARNING "Warning! GUS IRQ not selected\n");
723         irq_image |= tmp;
724         irq_image |= 0x40;      /* Combine IRQ1 (GF1) and IRQ2 (Midi) */
725
726         dual_dma_mode = 1;
727         if (gus_dma2 == gus_dma || gus_dma2 == -1)
728         {
729                 dual_dma_mode = 0;
730                 dma_image = 0x40;       /* Combine DMA1 (DRAM) and IRQ2 (ADC) */
731
732                 tmp = gus_dma_map[gus_dma];
733                 if (!tmp)
734                         printk(KERN_WARNING "Warning! GUS DMA not selected\n");
735
736                 dma_image |= tmp;
737         }
738         else
739         {
740                 /* Setup dual DMA channel mode for GUS MAX */
741
742                 dma_image = gus_dma_map[gus_dma];
743                 if (!dma_image)
744                         printk(KERN_WARNING "Warning! GUS DMA not selected\n");
745
746                 tmp = gus_dma_map[gus_dma2] << 3;
747                 if (!tmp)
748                 {
749                         printk(KERN_WARNING "Warning! Invalid GUS MAX DMA\n");
750                         tmp = 0x40;             /* Combine DMA channels */
751                             dual_dma_mode = 0;
752                 }
753                 dma_image |= tmp;
754         }
755
756         /*
757          * For some reason the IRQ and DMA addresses must be written twice
758          */
759
760         /*
761          * Doing it first time
762          */
763
764         outb((mix_image), u_Mixer);     /* Select DMA control */
765         outb((dma_image | 0x80), u_IRQDMAControl);      /* Set DMA address */
766
767         outb((mix_image | 0x40), u_Mixer);      /* Select IRQ control */
768         outb((irq_image), u_IRQDMAControl);     /* Set IRQ address */
769
770         /*
771          * Doing it second time
772          */
773
774         outb((mix_image), u_Mixer);     /* Select DMA control */
775         outb((dma_image), u_IRQDMAControl);     /* Set DMA address */
776
777         outb((mix_image | 0x40), u_Mixer);      /* Select IRQ control */
778         outb((irq_image), u_IRQDMAControl);     /* Set IRQ address */
779
780         gus_select_voice(0);    /* This disables writes to IRQ/DMA reg */
781
782         mix_image &= ~0x02;     /* Enable line out */
783         mix_image |= 0x08;      /* Enable IRQ */
784         outb((mix_image), u_Mixer);     /*
785                                          * Turn mixer channels on
786                                          * Note! Mic in is left off.
787                                          */
788
789         gus_select_voice(0);    /* This disables writes to IRQ/DMA reg */
790
791         gusintr(gus_irq, (void *)gus_hw_config, NULL);  /* Serve pending interrupts */
792
793         inb(u_Status);          /* Touch the status register */
794
795         gus_look8(0x41);        /* Clear any pending DMA IRQs */
796         gus_look8(0x49);        /* Clear any pending sample IRQs */
797
798         gus_read8(0x0f);        /* Clear pending IRQs */
799
800         if (iw_mode)
801                 gus_write8(0x19, gus_read8(0x19) | 0x01);
802         spin_unlock_irqrestore(&gus_lock,flags);
803 }
804
805
806 static void __init pnp_mem_init(void)
807 {
808 #include "iwmem.h"
809 #define CHUNK_SIZE (256*1024)
810 #define BANK_SIZE (4*1024*1024)
811 #define CHUNKS_PER_BANK (BANK_SIZE/CHUNK_SIZE)
812
813         int bank, chunk, addr, total = 0;
814         int bank_sizes[4];
815         int i, j, bits = -1, testbits = -1, nbanks = 0;
816
817         /*
818          * This routine determines what kind of RAM is installed in each of the four
819          * SIMM banks and configures the DRAM address decode logic accordingly.
820          */
821
822         /*
823          *    Place the chip into enhanced mode
824          */
825         gus_write8(0x19, gus_read8(0x19) | 0x01);
826         gus_write8(0x53, gus_look8(0x53) & ~0x02);      /* Select DRAM I/O access */
827
828         /*
829          * Set memory configuration to 4 DRAM banks of 4M in each (16M total).
830          */
831
832         gus_write16(0x52, (gus_look16(0x52) & 0xfff0) | 0x000c);
833
834         /*
835          * Perform the DRAM size detection for each bank individually.
836          */
837         for (bank = 0; bank < 4; bank++)
838         {
839                 int size = 0;
840
841                 addr = bank * BANK_SIZE;
842
843                 /* Clean check points of each chunk */
844                 for (chunk = 0; chunk < CHUNKS_PER_BANK; chunk++)
845                 {
846                         gus_poke(addr + chunk * CHUNK_SIZE + 0L, 0x00);
847                         gus_poke(addr + chunk * CHUNK_SIZE + 1L, 0x00);
848                 }
849
850                 /* Write a value to each chunk point and verify the result */
851                 for (chunk = 0; chunk < CHUNKS_PER_BANK; chunk++)
852                 {
853                         gus_poke(addr + chunk * CHUNK_SIZE + 0L, 0x55);
854                         gus_poke(addr + chunk * CHUNK_SIZE + 1L, 0xAA);
855
856                         if (gus_peek(addr + chunk * CHUNK_SIZE + 0L) == 0x55 &&
857                                 gus_peek(addr + chunk * CHUNK_SIZE + 1L) == 0xAA)
858                         {
859                                 /* OK. There is RAM. Now check for possible shadows */
860                                 int ok = 1, chunk2;
861
862                                 for (chunk2 = 0; ok && chunk2 < chunk; chunk2++)
863                                         if (gus_peek(addr + chunk2 * CHUNK_SIZE + 0L) ||
864                                                         gus_peek(addr + chunk2 * CHUNK_SIZE + 1L))
865                                                 ok = 0; /* Addressing wraps */
866
867                                 if (ok)
868                                         size = (chunk + 1) * CHUNK_SIZE;
869                         }
870                         gus_poke(addr + chunk * CHUNK_SIZE + 0L, 0x00);
871                         gus_poke(addr + chunk * CHUNK_SIZE + 1L, 0x00);
872                 }
873                 bank_sizes[bank] = size;
874                 if (size)
875                         nbanks = bank + 1;
876                 DDB(printk("Interwave: Bank %d, size=%dk\n", bank, size / 1024));
877         }
878
879         if (nbanks == 0)        /* No RAM - Give up */
880         {
881                 printk(KERN_ERR "Sound: An Interwave audio chip detected but no DRAM\n");
882                 printk(KERN_ERR "Sound: Unable to work with this card.\n");
883                 gus_write8(0x19, gus_read8(0x19) & ~0x01);
884                 gus_mem_size = 0;
885                 return;
886         }
887
888         /*
889          * Now we know how much DRAM there is in each bank. The next step is
890          * to find a DRAM size encoding (0 to 12) which is best for the combination
891          * we have.
892          *
893          * First try if any of the possible alternatives matches exactly the amount
894          * of memory we have.
895          */
896
897         for (i = 0; bits == -1 && i < 13; i++)
898         {
899                 bits = i;
900
901                 for (j = 0; bits != -1 && j < 4; j++)
902                         if (mem_decode[i][j] != bank_sizes[j])
903                                 bits = -1;      /* No hit */
904         }
905
906         /*
907          * If necessary, try to find a combination where other than the last
908          * bank matches our configuration and the last bank is left oversized.
909          * In this way we don't leave holes in the middle of memory.
910          */
911
912         if (bits == -1)         /* No luck yet */
913         {
914                 for (i = 0; bits == -1 && i < 13; i++)
915                 {
916                         bits = i;
917
918                         for (j = 0; bits != -1 && j < nbanks - 1; j++)
919                                 if (mem_decode[i][j] != bank_sizes[j])
920                                         bits = -1;      /* No hit */
921                         if (mem_decode[i][nbanks - 1] < bank_sizes[nbanks - 1])
922                                 bits = -1;      /* The last bank is too small */
923                 }
924         }
925         /*
926          * The last resort is to search for a combination where the banks are
927          * smaller than the actual SIMMs. This leaves some memory in the banks
928          * unused but doesn't leave holes in the DRAM address space.
929          */
930         if (bits == -1)         /* No luck yet */
931         {
932                 for (i = 0; i < 13; i++)
933                 {
934                         testbits = i;
935                         for (j = 0; testbits != -1 && j < nbanks - 1; j++)
936                                 if (mem_decode[i][j] > bank_sizes[j]) {
937                                         testbits = -1;
938                                 }
939                         if(testbits > bits) bits = testbits;
940                 }
941                 if (bits != -1)
942                 {
943                         printk(KERN_INFO "Interwave: Can't use all installed RAM.\n");
944                         printk(KERN_INFO "Interwave: Try reordering SIMMS.\n");
945                 }
946                 printk(KERN_INFO "Interwave: Can't find working DRAM encoding.\n");
947                 printk(KERN_INFO "Interwave: Defaulting to 256k. Try reordering SIMMS.\n");
948                 bits = 0;
949         }
950         DDB(printk("Interwave: Selecting DRAM addressing mode %d\n", bits));
951
952         for (bank = 0; bank < 4; bank++)
953         {
954                 DDB(printk("  Bank %d, mem=%dk (limit %dk)\n", bank, bank_sizes[bank] / 1024, mem_decode[bits][bank] / 1024));
955
956                 if (bank_sizes[bank] > mem_decode[bits][bank])
957                         total += mem_decode[bits][bank];
958                 else
959                         total += bank_sizes[bank];
960         }
961
962         DDB(printk("Total %dk of DRAM (enhanced mode)\n", total / 1024));
963
964         /*
965          *    Set the memory addressing mode.
966          */
967         gus_write16(0x52, (gus_look16(0x52) & 0xfff0) | bits);
968
969 /*      Leave the chip into enhanced mode. Disable LFO  */
970         gus_mem_size = total;
971         iw_mode = 1;
972         gus_write8(0x19, (gus_read8(0x19) | 0x01) & ~0x02);
973 }
974
975 int __init gus_wave_detect(int baseaddr)
976 {
977         unsigned long   i, max_mem = 1024L;
978         unsigned long   loc;
979         unsigned char   val;
980
981         gus_base = baseaddr;
982
983         gus_write8(0x4c, 0);    /* Reset GF1 */
984         gus_delay();
985         gus_delay();
986
987         gus_write8(0x4c, 1);    /* Release Reset */
988         gus_delay();
989         gus_delay();
990
991 #ifdef GUSPNP_AUTODETECT
992         val = gus_look8(0x5b);  /* Version number register */
993         gus_write8(0x5b, ~val); /* Invert all bits */
994
995         if ((gus_look8(0x5b) & 0xf0) == (val & 0xf0))   /* No change */
996         {
997                 if ((gus_look8(0x5b) & 0x0f) == ((~val) & 0x0f))        /* Change */
998                 {
999                         DDB(printk("Interwave chip version %d detected\n", (val & 0xf0) >> 4));
1000                         gus_pnp_flag = 1;
1001                 }
1002                 else
1003                 {
1004                         DDB(printk("Not an Interwave chip (%x)\n", gus_look8(0x5b)));
1005                         gus_pnp_flag = 0;
1006                 }
1007         }
1008         gus_write8(0x5b, val);  /* Restore all bits */
1009 #endif
1010
1011         if (gus_pnp_flag)
1012                 pnp_mem_init();
1013         if (iw_mode)
1014                 return 1;
1015
1016         /* See if there is first block there.... */
1017         gus_poke(0L, 0xaa);
1018         if (gus_peek(0L) != 0xaa)
1019                 return (0);
1020
1021         /* Now zero it out so that I can check for mirroring .. */
1022         gus_poke(0L, 0x00);
1023         for (i = 1L; i < max_mem; i++)
1024         {
1025                 int n, failed;
1026
1027                 /* check for mirroring ... */
1028                 if (gus_peek(0L) != 0)
1029                         break;
1030                 loc = i << 10;
1031
1032                 for (n = loc - 1, failed = 0; n <= loc; n++)
1033                 {
1034                         gus_poke(loc, 0xaa);
1035                         if (gus_peek(loc) != 0xaa)
1036                                 failed = 1;
1037                         gus_poke(loc, 0x55);
1038                         if (gus_peek(loc) != 0x55)
1039                                 failed = 1;
1040                 }
1041                 if (failed)
1042                         break;
1043         }
1044         gus_mem_size = i << 10;
1045         return 1;
1046 }
1047
1048 static int guswave_ioctl(int dev, unsigned int cmd, void __user *arg)
1049 {
1050
1051         switch (cmd) 
1052         {
1053                 case SNDCTL_SYNTH_INFO:
1054                         gus_info.nr_voices = nr_voices;
1055                         if (copy_to_user(arg, &gus_info, sizeof(gus_info)))
1056                                 return -EFAULT;
1057                         return 0;
1058
1059                 case SNDCTL_SEQ_RESETSAMPLES:
1060                         reset_sample_memory();
1061                         return 0;
1062
1063                 case SNDCTL_SEQ_PERCMODE:
1064                         return 0;
1065
1066                 case SNDCTL_SYNTH_MEMAVL:
1067                         return (gus_mem_size == 0) ? 0 : gus_mem_size - free_mem_ptr - 32;
1068
1069                 default:
1070                         return -EINVAL;
1071         }
1072 }
1073
1074 static int guswave_set_instr(int dev, int voice, int instr_no)
1075 {
1076         int sample_no;
1077
1078         if (instr_no < 0 || instr_no > MAX_PATCH)
1079                 instr_no = 0;   /* Default to acoustic piano */
1080
1081         if (voice < 0 || voice > 31)
1082                 return -EINVAL;
1083
1084         if (voices[voice].volume_irq_mode == VMODE_START_NOTE)
1085         {
1086                 voices[voice].sample_pending = instr_no;
1087                 return 0;
1088         }
1089         sample_no = patch_table[instr_no];
1090         patch_map[voice] = -1;
1091
1092         if (sample_no == NOT_SAMPLE)
1093         {
1094 /*              printk("GUS: Undefined patch %d for voice %d\n", instr_no, voice);*/
1095                 return -EINVAL; /* Patch not defined */
1096         }
1097         if (sample_ptrs[sample_no] == -1)       /* Sample not loaded */
1098         {
1099 /*              printk("GUS: Sample #%d not loaded for patch %d (voice %d)\n", sample_no, instr_no, voice);*/
1100                 return -EINVAL;
1101         }
1102         sample_map[voice] = sample_no;
1103         patch_map[voice] = instr_no;
1104         return 0;
1105 }
1106
1107 static int guswave_kill_note(int dev, int voice, int note, int velocity)
1108 {
1109         unsigned long flags;
1110
1111         spin_lock_irqsave(&gus_lock,flags);
1112         /* voice_alloc->map[voice] = 0xffff; */
1113         if (voices[voice].volume_irq_mode == VMODE_START_NOTE)
1114         {
1115                 voices[voice].kill_pending = 1;
1116                 spin_unlock_irqrestore(&gus_lock,flags);
1117         }
1118         else
1119         {
1120                 spin_unlock_irqrestore(&gus_lock,flags);
1121                 gus_voice_fade(voice);
1122         }
1123
1124         return 0;
1125 }
1126
1127 static void guswave_aftertouch(int dev, int voice, int pressure)
1128 {
1129 }
1130
1131 static void guswave_panning(int dev, int voice, int value)
1132 {
1133         if (voice >= 0 || voice < 32)
1134                 voices[voice].panning = value;
1135 }
1136
1137 static void guswave_volume_method(int dev, int mode)
1138 {
1139         if (mode == VOL_METHOD_LINEAR || mode == VOL_METHOD_ADAGIO)
1140                 volume_method = mode;
1141 }
1142
1143 static void compute_volume(int voice, int volume)
1144 {
1145         if (volume < 128)
1146                 voices[voice].midi_volume = volume;
1147
1148         switch (volume_method)
1149         {
1150                 case VOL_METHOD_ADAGIO:
1151                         voices[voice].initial_volume =
1152                                 gus_adagio_vol(voices[voice].midi_volume, voices[voice].main_vol,
1153                                         voices[voice].expression_vol,
1154                                         voices[voice].patch_vol);
1155                         break;
1156
1157                 case VOL_METHOD_LINEAR: /* Totally ignores patch-volume and expression */
1158                         voices[voice].initial_volume = gus_linear_vol(volume, voices[voice].main_vol);
1159                         break;
1160
1161                 default:
1162                         voices[voice].initial_volume = volume_base +
1163                                 (voices[voice].midi_volume * volume_scale);
1164         }
1165
1166         if (voices[voice].initial_volume > 4030)
1167                 voices[voice].initial_volume = 4030;
1168 }
1169
1170 static void compute_and_set_volume(int voice, int volume, int ramp_time)
1171 {
1172         int curr, target, rate;
1173         unsigned long flags;
1174
1175         compute_volume(voice, volume);
1176         voices[voice].current_volume = voices[voice].initial_volume;
1177
1178         spin_lock_irqsave(&gus_lock,flags);
1179         /*
1180          * CAUTION! Interrupts disabled. Enable them before returning
1181          */
1182
1183         gus_select_voice(voice);
1184
1185         curr = gus_read16(0x09) >> 4;
1186         target = voices[voice].initial_volume;
1187
1188         if (ramp_time == INSTANT_RAMP)
1189         {
1190                 gus_rampoff();
1191                 gus_voice_volume(target);
1192                 spin_unlock_irqrestore(&gus_lock,flags);
1193                 return;
1194         }
1195         if (ramp_time == FAST_RAMP)
1196                 rate = 63;
1197         else
1198                 rate = 16;
1199         gus_ramp_rate(0, rate);
1200
1201         if ((target - curr) / 64 == 0)  /* Close enough to target. */
1202         {
1203                 gus_rampoff();
1204                 gus_voice_volume(target);
1205                 spin_unlock_irqrestore(&gus_lock,flags);
1206                 return;
1207         }
1208         if (target > curr)
1209         {
1210                 if (target > (4095 - 65))
1211                         target = 4095 - 65;
1212                 gus_ramp_range(curr, target);
1213                 gus_rampon(0x00);       /* Ramp up, once, no IRQ */
1214         }
1215         else
1216         {
1217                 if (target < 65)
1218                         target = 65;
1219
1220                 gus_ramp_range(target, curr);
1221                 gus_rampon(0x40);       /* Ramp down, once, no irq */
1222         }
1223         spin_unlock_irqrestore(&gus_lock,flags);
1224 }
1225
1226 static void dynamic_volume_change(int voice)
1227 {
1228         unsigned char status;
1229         unsigned long flags;
1230
1231         spin_lock_irqsave(&gus_lock,flags);
1232         gus_select_voice(voice);
1233         status = gus_read8(0x00);       /* Get voice status */
1234         spin_unlock_irqrestore(&gus_lock,flags);
1235
1236         if (status & 0x03)
1237                 return;         /* Voice was not running */
1238
1239         if (!(voices[voice].mode & WAVE_ENVELOPES))
1240         {
1241                 compute_and_set_volume(voice, voices[voice].midi_volume, 1);
1242                 return;
1243         }
1244         
1245         /*
1246          * Voice is running and has envelopes.
1247          */
1248
1249         spin_lock_irqsave(&gus_lock,flags);
1250         gus_select_voice(voice);
1251         status = gus_read8(0x0d);       /* Ramping status */
1252         spin_unlock_irqrestore(&gus_lock,flags);
1253
1254         if (status & 0x03)      /* Sustain phase? */
1255         {
1256                 compute_and_set_volume(voice, voices[voice].midi_volume, 1);
1257                 return;
1258         }
1259         if (voices[voice].env_phase < 0)
1260                 return;
1261
1262         compute_volume(voice, voices[voice].midi_volume);
1263
1264 }
1265
1266 static void guswave_controller(int dev, int voice, int ctrl_num, int value)
1267 {
1268         unsigned long   flags;
1269         unsigned long   freq;
1270
1271         if (voice < 0 || voice > 31)
1272                 return;
1273
1274         switch (ctrl_num)
1275         {
1276                 case CTRL_PITCH_BENDER:
1277                         voices[voice].bender = value;
1278
1279                         if (voices[voice].volume_irq_mode != VMODE_START_NOTE)
1280                         {
1281                                 freq = compute_finetune(voices[voice].orig_freq, value, voices[voice].bender_range, 0);
1282                                 voices[voice].current_freq = freq;
1283
1284                                 spin_lock_irqsave(&gus_lock,flags);
1285                                 gus_select_voice(voice);
1286                                 gus_voice_freq(freq);
1287                                 spin_unlock_irqrestore(&gus_lock,flags);
1288                         }
1289                         break;
1290
1291                 case CTRL_PITCH_BENDER_RANGE:
1292                         voices[voice].bender_range = value;
1293                         break;
1294                 case CTL_EXPRESSION:
1295                         value /= 128;
1296                 case CTRL_EXPRESSION:
1297                         if (volume_method == VOL_METHOD_ADAGIO)
1298                         {
1299                                 voices[voice].expression_vol = value;
1300                                 if (voices[voice].volume_irq_mode != VMODE_START_NOTE)
1301                                         dynamic_volume_change(voice);
1302                         }
1303                         break;
1304
1305                 case CTL_PAN:
1306                         voices[voice].panning = (value * 2) - 128;
1307                         break;
1308
1309                 case CTL_MAIN_VOLUME:
1310                         value = (value * 100) / 16383;
1311
1312                 case CTRL_MAIN_VOLUME:
1313                         voices[voice].main_vol = value;
1314                         if (voices[voice].volume_irq_mode != VMODE_START_NOTE)
1315                                 dynamic_volume_change(voice);
1316                         break;
1317
1318                 default:
1319                         break;
1320         }
1321 }
1322
1323 static int guswave_start_note2(int dev, int voice, int note_num, int volume)
1324 {
1325         int sample, best_sample, best_delta, delta_freq;
1326         int is16bits, samplep, patch, pan;
1327         unsigned long   note_freq, base_note, freq, flags;
1328         unsigned char   mode = 0;
1329
1330         if (voice < 0 || voice > 31)
1331         {
1332 /*              printk("GUS: Invalid voice\n");*/
1333                 return -EINVAL;
1334         }
1335         if (note_num == 255)
1336         {
1337                 if (voices[voice].mode & WAVE_ENVELOPES)
1338                 {
1339                         voices[voice].midi_volume = volume;
1340                         dynamic_volume_change(voice);
1341                         return 0;
1342                 }
1343                 compute_and_set_volume(voice, volume, 1);
1344                 return 0;
1345         }
1346         if ((patch = patch_map[voice]) == -1)
1347                 return -EINVAL;
1348         if ((samplep = patch_table[patch]) == NOT_SAMPLE)
1349         {
1350                 return -EINVAL;
1351         }
1352         note_freq = note_to_freq(note_num);
1353
1354         /*
1355          * Find a sample within a patch so that the note_freq is between low_note
1356          * and high_note.
1357          */
1358         sample = -1;
1359
1360         best_sample = samplep;
1361         best_delta = 1000000;
1362         while (samplep != 0 && samplep != NOT_SAMPLE && sample == -1)
1363         {
1364                 delta_freq = note_freq - samples[samplep].base_note;
1365                 if (delta_freq < 0)
1366                         delta_freq = -delta_freq;
1367                 if (delta_freq < best_delta)
1368                 {
1369                         best_sample = samplep;
1370                         best_delta = delta_freq;
1371                 }
1372                 if (samples[samplep].low_note <= note_freq &&
1373                         note_freq <= samples[samplep].high_note)
1374                 {
1375                         sample = samplep;
1376                 }
1377                 else
1378                         samplep = samples[samplep].key; /* Link to next sample */
1379           }
1380         if (sample == -1)
1381                 sample = best_sample;
1382
1383         if (sample == -1)
1384         {
1385 /*              printk("GUS: Patch %d not defined for note %d\n", patch, note_num);*/
1386                 return 0;       /* Should play default patch ??? */
1387         }
1388         is16bits = (samples[sample].mode & WAVE_16_BITS) ? 1 : 0;
1389         voices[voice].mode = samples[sample].mode;
1390         voices[voice].patch_vol = samples[sample].volume;
1391
1392         if (iw_mode)
1393                 gus_write8(0x15, 0x00);         /* RAM, Reset voice deactivate bit of SMSI */
1394
1395         if (voices[voice].mode & WAVE_ENVELOPES)
1396         {
1397                 int i;
1398
1399                 for (i = 0; i < 6; i++)
1400                 {
1401                         voices[voice].env_rate[i] = samples[sample].env_rate[i];
1402                         voices[voice].env_offset[i] = samples[sample].env_offset[i];
1403                 }
1404         }
1405         sample_map[voice] = sample;
1406
1407         if (voices[voice].fixed_pitch)  /* Fixed pitch */
1408         {
1409                   freq = samples[sample].base_freq;
1410         }
1411         else
1412         {
1413                 base_note = samples[sample].base_note / 100;
1414                 note_freq /= 100;
1415
1416                 freq = samples[sample].base_freq * note_freq / base_note;
1417         }
1418
1419         voices[voice].orig_freq = freq;
1420
1421         /*
1422          * Since the pitch bender may have been set before playing the note, we
1423          * have to calculate the bending now.
1424          */
1425
1426         freq = compute_finetune(voices[voice].orig_freq, voices[voice].bender,
1427                                 voices[voice].bender_range, 0);
1428         voices[voice].current_freq = freq;
1429
1430         pan = (samples[sample].panning + voices[voice].panning) / 32;
1431         pan += 7;
1432         if (pan < 0)
1433                 pan = 0;
1434         if (pan > 15)
1435                 pan = 15;
1436
1437         if (samples[sample].mode & WAVE_16_BITS)
1438         {
1439                 mode |= 0x04;   /* 16 bits */
1440                 if ((sample_ptrs[sample] / GUS_BANK_SIZE) !=
1441                         ((sample_ptrs[sample] + samples[sample].len) / GUS_BANK_SIZE))
1442                                 printk(KERN_ERR "GUS: Sample address error\n");
1443         }
1444         spin_lock_irqsave(&gus_lock,flags);
1445         gus_select_voice(voice);
1446         gus_voice_off();
1447         gus_rampoff();
1448
1449         spin_unlock_irqrestore(&gus_lock,flags);
1450
1451         if (voices[voice].mode & WAVE_ENVELOPES)
1452         {
1453                 compute_volume(voice, volume);
1454                 init_envelope(voice);
1455         }
1456         else
1457         {
1458                 compute_and_set_volume(voice, volume, 0);
1459         }
1460
1461         spin_lock_irqsave(&gus_lock,flags);
1462         gus_select_voice(voice);
1463
1464         if (samples[sample].mode & WAVE_LOOP_BACK)
1465                 gus_write_addr(0x0a, sample_ptrs[sample] + samples[sample].len -
1466                         voices[voice].offset_pending, 0, is16bits);     /* start=end */
1467         else
1468                 gus_write_addr(0x0a, sample_ptrs[sample] + voices[voice].offset_pending, 0, is16bits);  /* Sample start=begin */
1469
1470         if (samples[sample].mode & WAVE_LOOPING)
1471         {
1472                 mode |= 0x08;
1473
1474                 if (samples[sample].mode & WAVE_BIDIR_LOOP)
1475                         mode |= 0x10;
1476
1477                 if (samples[sample].mode & WAVE_LOOP_BACK)
1478                 {
1479                         gus_write_addr(0x0a, sample_ptrs[sample] + samples[sample].loop_end -
1480                                            voices[voice].offset_pending,
1481                                            (samples[sample].fractions >> 4) & 0x0f, is16bits);
1482                         mode |= 0x40;
1483                 }
1484                 gus_write_addr(0x02, sample_ptrs[sample] + samples[sample].loop_start,
1485                         samples[sample].fractions & 0x0f, is16bits);    /* Loop start location */
1486                 gus_write_addr(0x04, sample_ptrs[sample] + samples[sample].loop_end,
1487                         (samples[sample].fractions >> 4) & 0x0f, is16bits);     /* Loop end location */
1488         }
1489         else
1490         {
1491                 mode |= 0x20;   /* Loop IRQ at the end */
1492                 voices[voice].loop_irq_mode = LMODE_FINISH;     /* Ramp down at the end */
1493                 voices[voice].loop_irq_parm = 1;
1494                 gus_write_addr(0x02, sample_ptrs[sample], 0, is16bits); /* Loop start location */
1495                 gus_write_addr(0x04, sample_ptrs[sample] + samples[sample].len - 1,
1496                         (samples[sample].fractions >> 4) & 0x0f, is16bits);     /* Loop end location */
1497         }
1498         gus_voice_freq(freq);
1499         gus_voice_balance(pan);
1500         gus_voice_on(mode);
1501         spin_unlock_irqrestore(&gus_lock,flags);
1502
1503         return 0;
1504 }
1505
1506 /*
1507  * New guswave_start_note by Andrew J. Robinson attempts to minimize clicking
1508  * when the note playing on the voice is changed.  It uses volume
1509  * ramping.
1510  */
1511
1512 static int guswave_start_note(int dev, int voice, int note_num, int volume)
1513 {
1514         unsigned long flags;
1515         int mode;
1516         int ret_val = 0;
1517
1518         spin_lock_irqsave(&gus_lock,flags);
1519         if (note_num == 255)
1520         {
1521                 if (voices[voice].volume_irq_mode == VMODE_START_NOTE)
1522                 {
1523                         voices[voice].volume_pending = volume;
1524                 }
1525                 else
1526                 {
1527                         ret_val = guswave_start_note2(dev, voice, note_num, volume);
1528                 }
1529         }
1530         else
1531         {
1532                 gus_select_voice(voice);
1533                 mode = gus_read8(0x00);
1534                 if (mode & 0x20)
1535                         gus_write8(0x00, mode & 0xdf);  /* No interrupt! */
1536
1537                 voices[voice].offset_pending = 0;
1538                 voices[voice].kill_pending = 0;
1539                 voices[voice].volume_irq_mode = 0;
1540                 voices[voice].loop_irq_mode = 0;
1541
1542                 if (voices[voice].sample_pending >= 0)
1543                 {
1544                         spin_unlock_irqrestore(&gus_lock,flags);        /* Run temporarily with interrupts enabled */
1545                         guswave_set_instr(voices[voice].dev_pending, voice, voices[voice].sample_pending);
1546                         voices[voice].sample_pending = -1;
1547                         spin_lock_irqsave(&gus_lock,flags);
1548                         gus_select_voice(voice);        /* Reselect the voice (just to be sure) */
1549                 }
1550                 if ((mode & 0x01) || (int) ((gus_read16(0x09) >> 4) < (unsigned) 2065))
1551                 {
1552                         ret_val = guswave_start_note2(dev, voice, note_num, volume);
1553                 }
1554                 else
1555                 {
1556                         voices[voice].dev_pending = dev;
1557                         voices[voice].note_pending = note_num;
1558                         voices[voice].volume_pending = volume;
1559                         voices[voice].volume_irq_mode = VMODE_START_NOTE;
1560
1561                         gus_rampoff();
1562                         gus_ramp_range(2000, 4065);
1563                         gus_ramp_rate(0, 63);   /* Fastest possible rate */
1564                         gus_rampon(0x20 | 0x40);        /* Ramp down, once, irq */
1565                 }
1566         }
1567         spin_unlock_irqrestore(&gus_lock,flags);
1568         return ret_val;
1569 }
1570
1571 static void guswave_reset(int dev)
1572 {
1573         int i;
1574
1575         for (i = 0; i < 32; i++)
1576         {
1577                 gus_voice_init(i);
1578                 gus_voice_init2(i);
1579         }
1580 }
1581
1582 static int guswave_open(int dev, int mode)
1583 {
1584         int err;
1585
1586         if (gus_busy)
1587                 return -EBUSY;
1588
1589         voice_alloc->timestamp = 0;
1590
1591         if (gus_no_wave_dma) {
1592                 gus_no_dma = 1;
1593         } else {
1594                 if ((err = DMAbuf_open_dma(gus_devnum)) < 0)
1595                 {
1596                         /* printk( "GUS: Loading samples without DMA\n"); */
1597                         gus_no_dma = 1; /* Upload samples using PIO */
1598                 }
1599                 else
1600                         gus_no_dma = 0;
1601         }
1602
1603         init_waitqueue_head(&dram_sleeper);
1604         gus_busy = 1;
1605         active_device = GUS_DEV_WAVE;
1606
1607         gusintr(gus_irq, (void *)gus_hw_config, NULL);  /* Serve pending interrupts */
1608         gus_initialize();
1609         gus_reset();
1610         gusintr(gus_irq, (void *)gus_hw_config, NULL);  /* Serve pending interrupts */
1611
1612         return 0;
1613 }
1614
1615 static void guswave_close(int dev)
1616 {
1617         gus_busy = 0;
1618         active_device = 0;
1619         gus_reset();
1620
1621         if (!gus_no_dma)
1622                 DMAbuf_close_dma(gus_devnum);
1623 }
1624
1625 static int guswave_load_patch(int dev, int format, const char __user *addr,
1626                    int offs, int count, int pmgr_flag)
1627 {
1628         struct patch_info patch;
1629         int instr;
1630         long sizeof_patch;
1631
1632         unsigned long blk_sz, blk_end, left, src_offs, target;
1633
1634         sizeof_patch = (long) &patch.data[0] - (long) &patch;   /* Header size */
1635
1636         if (format != GUS_PATCH)
1637         {
1638 /*              printk("GUS Error: Invalid patch format (key) 0x%x\n", format);*/
1639                 return -EINVAL;
1640         }
1641         if (count < sizeof_patch)
1642         {
1643 /*                printk("GUS Error: Patch header too short\n");*/
1644                   return -EINVAL;
1645         }
1646         count -= sizeof_patch;
1647
1648         if (free_sample >= MAX_SAMPLE)
1649         {
1650 /*                printk("GUS: Sample table full\n");*/
1651                   return -ENOSPC;
1652         }
1653         /*
1654          * Copy the header from user space but ignore the first bytes which have
1655          * been transferred already.
1656          */
1657
1658         if (copy_from_user(&((char *) &patch)[offs], &(addr)[offs],
1659                            sizeof_patch - offs))
1660                 return -EFAULT;
1661
1662         if (patch.mode & WAVE_ROM)
1663                 return -EINVAL;
1664         if (gus_mem_size == 0)
1665                 return -ENOSPC;
1666
1667         instr = patch.instr_no;
1668
1669         if (instr < 0 || instr > MAX_PATCH)
1670         {
1671 /*              printk(KERN_ERR "GUS: Invalid patch number %d\n", instr);*/
1672                 return -EINVAL;
1673         }
1674         if (count < patch.len)
1675         {
1676 /*              printk(KERN_ERR "GUS Warning: Patch record too short (%d<%d)\n", count, (int) patch.len);*/
1677                 patch.len = count;
1678         }
1679         if (patch.len <= 0 || patch.len > gus_mem_size)
1680         {
1681 /*              printk(KERN_ERR "GUS: Invalid sample length %d\n", (int) patch.len);*/
1682                 return -EINVAL;
1683         }
1684         if (patch.mode & WAVE_LOOPING)
1685         {
1686                 if (patch.loop_start < 0 || patch.loop_start >= patch.len)
1687                 {
1688 /*                      printk(KERN_ERR "GUS: Invalid loop start\n");*/
1689                         return -EINVAL;
1690                 }
1691                 if (patch.loop_end < patch.loop_start || patch.loop_end > patch.len)
1692                 {
1693 /*                      printk(KERN_ERR "GUS: Invalid loop end\n");*/
1694                         return -EINVAL;
1695                 }
1696         }
1697         free_mem_ptr = (free_mem_ptr + 31) & ~31;       /* 32 byte alignment */
1698
1699         if (patch.mode & WAVE_16_BITS)
1700         {
1701                 /*
1702                  * 16 bit samples must fit one 256k bank.
1703                  */
1704                 if (patch.len >= GUS_BANK_SIZE)
1705                 {
1706 /*                       printk("GUS: Sample (16 bit) too long %d\n", (int) patch.len);*/
1707                         return -ENOSPC;
1708                 }
1709                 if ((free_mem_ptr / GUS_BANK_SIZE) !=
1710                         ((free_mem_ptr + patch.len) / GUS_BANK_SIZE))
1711                 {
1712                         unsigned long   tmp_mem =       
1713                                 /* Align to 256K */
1714                                         ((free_mem_ptr / GUS_BANK_SIZE) + 1) * GUS_BANK_SIZE;
1715
1716                         if ((tmp_mem + patch.len) > gus_mem_size)
1717                                 return -ENOSPC;
1718
1719                         free_mem_ptr = tmp_mem;         /* This leaves unusable memory */
1720                 }
1721         }
1722         if ((free_mem_ptr + patch.len) > gus_mem_size)
1723                 return -ENOSPC;
1724
1725         sample_ptrs[free_sample] = free_mem_ptr;
1726
1727         /*
1728          * Tremolo is not possible with envelopes
1729          */
1730
1731         if (patch.mode & WAVE_ENVELOPES)
1732                 patch.mode &= ~WAVE_TREMOLO;
1733
1734         if (!(patch.mode & WAVE_FRACTIONS))
1735         {
1736                   patch.fractions = 0;
1737         }
1738         memcpy((char *) &samples[free_sample], &patch, sizeof_patch);
1739
1740         /*
1741          * Link this_one sample to the list of samples for patch 'instr'.
1742          */
1743
1744         samples[free_sample].key = patch_table[instr];
1745         patch_table[instr] = free_sample;
1746
1747         /*
1748          * Use DMA to transfer the wave data to the DRAM
1749          */
1750
1751         left = patch.len;
1752         src_offs = 0;
1753         target = free_mem_ptr;
1754
1755         while (left)            /* Not completely transferred yet */
1756         {
1757                 blk_sz = audio_devs[gus_devnum]->dmap_out->bytes_in_use;
1758                 if (blk_sz > left)
1759                         blk_sz = left;
1760
1761                 /*
1762                  * DMA cannot cross bank (256k) boundaries. Check for that.
1763                  */
1764                  
1765                 blk_end = target + blk_sz;
1766
1767                 if ((target / GUS_BANK_SIZE) != (blk_end / GUS_BANK_SIZE))
1768                 {
1769                         /* Split the block */
1770                         blk_end &= ~(GUS_BANK_SIZE - 1);
1771                         blk_sz = blk_end - target;
1772                 }
1773                 if (gus_no_dma)
1774                 {
1775                         /*
1776                          * For some reason the DMA is not possible. We have to use PIO.
1777                          */
1778                         long i;
1779                         unsigned char data;
1780
1781                         for (i = 0; i < blk_sz; i++)
1782                         {
1783                                 get_user(*(unsigned char *) &data, (unsigned char __user *) &((addr)[sizeof_patch + i]));
1784                                 if (patch.mode & WAVE_UNSIGNED)
1785                                         if (!(patch.mode & WAVE_16_BITS) || (i & 0x01))
1786                                                 data ^= 0x80;   /* Convert to signed */
1787                                 gus_poke(target + i, data);
1788                         }
1789                 }
1790                 else
1791                 {
1792                         unsigned long address, hold_address;
1793                         unsigned char dma_command;
1794                         unsigned long flags;
1795
1796                         if (audio_devs[gus_devnum]->dmap_out->raw_buf == NULL)
1797                         {
1798                                 printk(KERN_ERR "GUS: DMA buffer == NULL\n");
1799                                 return -ENOSPC;
1800                         }
1801                         /*
1802                          * OK, move now. First in and then out.
1803                          */
1804
1805                         if (copy_from_user(audio_devs[gus_devnum]->dmap_out->raw_buf,
1806                                            &(addr)[sizeof_patch + src_offs],
1807                                            blk_sz))
1808                                 return -EFAULT;
1809
1810                         spin_lock_irqsave(&gus_lock,flags);
1811                         gus_write8(0x41, 0);    /* Disable GF1 DMA */
1812                         DMAbuf_start_dma(gus_devnum, audio_devs[gus_devnum]->dmap_out->raw_buf_phys,
1813                                 blk_sz, DMA_MODE_WRITE);
1814
1815                         /*
1816                          * Set the DRAM address for the wave data
1817                          */
1818
1819                         if (iw_mode)
1820                         {
1821                                 /* Different address translation in enhanced mode */
1822
1823                                 unsigned char   hi;
1824
1825                                 if (gus_dma > 4)
1826                                         address = target >> 1;  /* Convert to 16 bit word address */
1827                                 else
1828                                         address = target;
1829
1830                                 hi = (unsigned char) ((address >> 16) & 0xf0);
1831                                 hi += (unsigned char) (address & 0x0f);
1832
1833                                 gus_write16(0x42, (address >> 4) & 0xffff);     /* DMA address (low) */
1834                                 gus_write8(0x50, hi);
1835                         }
1836                         else
1837                         {
1838                                 address = target;
1839                                 if (audio_devs[gus_devnum]->dmap_out->dma > 3)
1840                                 {
1841                                         hold_address = address;
1842                                         address = address >> 1;
1843                                         address &= 0x0001ffffL;
1844                                         address |= (hold_address & 0x000c0000L);
1845                                 }
1846                                 gus_write16(0x42, (address >> 4) & 0xffff);     /* DRAM DMA address */
1847                         }
1848
1849                         /*
1850                          * Start the DMA transfer
1851                          */
1852
1853                         dma_command = 0x21;             /* IRQ enable, DMA start */
1854                         if (patch.mode & WAVE_UNSIGNED)
1855                                 dma_command |= 0x80;    /* Invert MSB */
1856                         if (patch.mode & WAVE_16_BITS)
1857                                 dma_command |= 0x40;    /* 16 bit _DATA_ */
1858                         if (audio_devs[gus_devnum]->dmap_out->dma > 3)
1859                                 dma_command |= 0x04;    /* 16 bit DMA _channel_ */
1860                         
1861                         /*
1862                          * Sleep here until the DRAM DMA done interrupt is served
1863                          */
1864                         active_device = GUS_DEV_WAVE;
1865                         gus_write8(0x41, dma_command);  /* Lets go luteet (=bugs) */
1866
1867                         spin_unlock_irqrestore(&gus_lock,flags); /* opens a race */
1868                         if (!interruptible_sleep_on_timeout(&dram_sleeper, HZ))
1869                                 printk("GUS: DMA Transfer timed out\n");
1870                 }
1871
1872                 /*
1873                  * Now the next part
1874                  */
1875
1876                 left -= blk_sz;
1877                 src_offs += blk_sz;
1878                 target += blk_sz;
1879
1880                 gus_write8(0x41, 0);    /* Stop DMA */
1881         }
1882
1883         free_mem_ptr += patch.len;
1884         free_sample++;
1885         return 0;
1886 }
1887
1888 static void guswave_hw_control(int dev, unsigned char *event_rec)
1889 {
1890         int voice, cmd;
1891         unsigned short p1, p2;
1892         unsigned int plong;
1893         unsigned long flags;
1894
1895         cmd = event_rec[2];
1896         voice = event_rec[3];
1897         p1 = *(unsigned short *) &event_rec[4];
1898         p2 = *(unsigned short *) &event_rec[6];
1899         plong = *(unsigned int *) &event_rec[4];
1900
1901         if ((voices[voice].volume_irq_mode == VMODE_START_NOTE) &&
1902                 (cmd != _GUS_VOICESAMPLE) && (cmd != _GUS_VOICE_POS))
1903                 do_volume_irq(voice);
1904
1905         switch (cmd)
1906         {
1907                 case _GUS_NUMVOICES:
1908                         spin_lock_irqsave(&gus_lock,flags);
1909                         gus_select_voice(voice);
1910                         gus_select_max_voices(p1);
1911                         spin_unlock_irqrestore(&gus_lock,flags);
1912                         break;
1913
1914                 case _GUS_VOICESAMPLE:
1915                         guswave_set_instr(dev, voice, p1);
1916                         break;
1917
1918                 case _GUS_VOICEON:
1919                         spin_lock_irqsave(&gus_lock,flags);
1920                         gus_select_voice(voice);
1921                         p1 &= ~0x20;    /* Don't allow interrupts */
1922                         gus_voice_on(p1);
1923                         spin_unlock_irqrestore(&gus_lock,flags);
1924                         break;
1925
1926                 case _GUS_VOICEOFF:
1927                         spin_lock_irqsave(&gus_lock,flags);
1928                         gus_select_voice(voice);
1929                         gus_voice_off();
1930                         spin_unlock_irqrestore(&gus_lock,flags);
1931                         break;
1932
1933                 case _GUS_VOICEFADE:
1934                         gus_voice_fade(voice);
1935                         break;
1936
1937                 case _GUS_VOICEMODE:
1938                         spin_lock_irqsave(&gus_lock,flags);
1939                         gus_select_voice(voice);
1940                         p1 &= ~0x20;    /* Don't allow interrupts */
1941                         gus_voice_mode(p1);
1942                         spin_unlock_irqrestore(&gus_lock,flags);
1943                         break;
1944
1945                 case _GUS_VOICEBALA:
1946                         spin_lock_irqsave(&gus_lock,flags);
1947                         gus_select_voice(voice);
1948                         gus_voice_balance(p1);
1949                         spin_unlock_irqrestore(&gus_lock,flags);
1950                         break;
1951
1952                 case _GUS_VOICEFREQ:
1953                         spin_lock_irqsave(&gus_lock,flags);
1954                         gus_select_voice(voice);
1955                         gus_voice_freq(plong);
1956                         spin_unlock_irqrestore(&gus_lock,flags);
1957                         break;
1958
1959                 case _GUS_VOICEVOL:
1960                         spin_lock_irqsave(&gus_lock,flags);
1961                         gus_select_voice(voice);
1962                         gus_voice_volume(p1);
1963                         spin_unlock_irqrestore(&gus_lock,flags);
1964                         break;
1965
1966                 case _GUS_VOICEVOL2:    /* Just update the software voice level */
1967                         voices[voice].initial_volume = voices[voice].current_volume = p1;
1968                         break;
1969
1970                 case _GUS_RAMPRANGE:
1971                         if (voices[voice].mode & WAVE_ENVELOPES)
1972                                 break;  /* NO-NO */
1973                         spin_lock_irqsave(&gus_lock,flags);
1974                         gus_select_voice(voice);
1975                         gus_ramp_range(p1, p2);
1976                         spin_unlock_irqrestore(&gus_lock,flags);
1977                         break;
1978
1979                 case _GUS_RAMPRATE:
1980                         if (voices[voice].mode & WAVE_ENVELOPES)
1981                                 break;  /* NJET-NJET */
1982                         spin_lock_irqsave(&gus_lock,flags);
1983                         gus_select_voice(voice);
1984                         gus_ramp_rate(p1, p2);
1985                         spin_unlock_irqrestore(&gus_lock,flags);
1986                         break;
1987
1988                 case _GUS_RAMPMODE:
1989                         if (voices[voice].mode & WAVE_ENVELOPES)
1990                                 break;  /* NO-NO */
1991                         spin_lock_irqsave(&gus_lock,flags);
1992                         gus_select_voice(voice);
1993                         p1 &= ~0x20;    /* Don't allow interrupts */
1994                         gus_ramp_mode(p1);
1995                         spin_unlock_irqrestore(&gus_lock,flags);
1996                         break;
1997
1998                 case _GUS_RAMPON:
1999                         if (voices[voice].mode & WAVE_ENVELOPES)
2000                                 break;  /* EI-EI */
2001                         spin_lock_irqsave(&gus_lock,flags);
2002                         gus_select_voice(voice);
2003                         p1 &= ~0x20;    /* Don't allow interrupts */
2004                         gus_rampon(p1);
2005                         spin_unlock_irqrestore(&gus_lock,flags);
2006                         break;
2007
2008                 case _GUS_RAMPOFF:
2009                         if (voices[voice].mode & WAVE_ENVELOPES)
2010                                 break;  /* NEJ-NEJ */
2011                         spin_lock_irqsave(&gus_lock,flags);
2012                         gus_select_voice(voice);
2013                         gus_rampoff();
2014                         spin_unlock_irqrestore(&gus_lock,flags);
2015                         break;
2016
2017                 case _GUS_VOLUME_SCALE:
2018                         volume_base = p1;
2019                         volume_scale = p2;
2020                         break;
2021
2022                 case _GUS_VOICE_POS:
2023                         spin_lock_irqsave(&gus_lock,flags);
2024                         gus_select_voice(voice);
2025                         gus_set_voice_pos(voice, plong);
2026                         spin_unlock_irqrestore(&gus_lock,flags);
2027                         break;
2028
2029                 default:
2030                         break;
2031         }
2032 }
2033
2034 static int gus_audio_set_speed(int speed)
2035 {
2036         if (speed <= 0)
2037                 speed = gus_audio_speed;
2038
2039         if (speed < 4000)
2040                 speed = 4000;
2041
2042         if (speed > 44100)
2043                 speed = 44100;
2044
2045         gus_audio_speed = speed;
2046
2047         if (only_read_access)
2048         {
2049                 /* Compute nearest valid recording speed  and return it */
2050
2051                 /* speed = (9878400 / (gus_audio_speed + 2)) / 16; */
2052                 speed = (((9878400 + gus_audio_speed / 2) / (gus_audio_speed + 2)) + 8) / 16;
2053                 speed = (9878400 / (speed * 16)) - 2;
2054         }
2055         return speed;
2056 }
2057
2058 static int gus_audio_set_channels(int channels)
2059 {
2060         if (!channels)
2061                 return gus_audio_channels;
2062         if (channels > 2)
2063                 channels = 2;
2064         if (channels < 1)
2065                 channels = 1;
2066         gus_audio_channels = channels;
2067         return channels;
2068 }
2069
2070 static int gus_audio_set_bits(int bits)
2071 {
2072         if (!bits)
2073                 return gus_audio_bits;
2074
2075         if (bits != 8 && bits != 16)
2076                 bits = 8;
2077
2078         if (only_8_bits)
2079                 bits = 8;
2080
2081         gus_audio_bits = bits;
2082         return bits;
2083 }
2084
2085 static int gus_audio_ioctl(int dev, unsigned int cmd, void __user *arg)
2086 {
2087         int val;
2088
2089         switch (cmd) 
2090         {
2091                 case SOUND_PCM_WRITE_RATE:
2092                         if (get_user(val, (int __user*)arg))
2093                                 return -EFAULT;
2094                         val = gus_audio_set_speed(val);
2095                         break;
2096
2097                 case SOUND_PCM_READ_RATE:
2098                         val = gus_audio_speed;
2099                         break;
2100
2101                 case SNDCTL_DSP_STEREO:
2102                         if (get_user(val, (int __user *)arg))
2103                                 return -EFAULT;
2104                         val = gus_audio_set_channels(val + 1) - 1;
2105                         break;
2106
2107                 case SOUND_PCM_WRITE_CHANNELS:
2108                         if (get_user(val, (int __user *)arg))
2109                                 return -EFAULT;
2110                         val = gus_audio_set_channels(val);
2111                         break;
2112
2113                 case SOUND_PCM_READ_CHANNELS:
2114                         val = gus_audio_channels;
2115                         break;
2116                 
2117                 case SNDCTL_DSP_SETFMT:
2118                         if (get_user(val, (int __user *)arg))
2119                                 return -EFAULT;
2120                         val = gus_audio_set_bits(val);
2121                         break;
2122                 
2123                 case SOUND_PCM_READ_BITS:
2124                         val = gus_audio_bits;
2125                         break;
2126                 
2127                 case SOUND_PCM_WRITE_FILTER:            /* NOT POSSIBLE */
2128                 case SOUND_PCM_READ_FILTER:
2129                         val = -EINVAL;
2130                         break;
2131                 default:
2132                         return -EINVAL;
2133         }
2134         return put_user(val, (int __user *)arg);
2135 }
2136
2137 static void gus_audio_reset(int dev)
2138 {
2139         if (recording_active)
2140         {
2141                 gus_write8(0x49, 0x00); /* Halt recording */
2142                 set_input_volumes();
2143         }
2144 }
2145
2146 static int saved_iw_mode;       /* A hack hack hack */
2147
2148 static int gus_audio_open(int dev, int mode)
2149 {
2150         if (gus_busy)
2151                 return -EBUSY;
2152
2153         if (gus_pnp_flag && mode & OPEN_READ)
2154         {
2155 /*              printk(KERN_ERR "GUS: Audio device #%d is playback only.\n", dev);*/
2156                 return -EIO;
2157         }
2158         gus_initialize();
2159
2160         gus_busy = 1;
2161         active_device = 0;
2162
2163         saved_iw_mode = iw_mode;
2164         if (iw_mode)
2165         {
2166                 /* There are some problems with audio in enhanced mode so disable it */
2167                 gus_write8(0x19, gus_read8(0x19) & ~0x01);      /* Disable enhanced mode */
2168                 iw_mode = 0;
2169         }
2170
2171         gus_reset();
2172         reset_sample_memory();
2173         gus_select_max_voices(14);
2174
2175         pcm_active = 0;
2176         dma_active = 0;
2177         pcm_opened = 1;
2178         if (mode & OPEN_READ)
2179         {
2180                 recording_active = 1;
2181                 set_input_volumes();
2182         }
2183         only_read_access = !(mode & OPEN_WRITE);
2184         only_8_bits = mode & OPEN_READ;
2185         if (only_8_bits)
2186                 audio_devs[dev]->format_mask = AFMT_U8;
2187         else
2188                 audio_devs[dev]->format_mask = AFMT_U8 | AFMT_S16_LE;
2189
2190         return 0;
2191 }
2192
2193 static void gus_audio_close(int dev)
2194 {
2195         iw_mode = saved_iw_mode;
2196         gus_reset();
2197         gus_busy = 0;
2198         pcm_opened = 0;
2199         active_device = 0;
2200
2201         if (recording_active)
2202         {
2203                 gus_write8(0x49, 0x00); /* Halt recording */
2204                 set_input_volumes();
2205         }
2206         recording_active = 0;
2207 }
2208
2209 static void gus_audio_update_volume(void)
2210 {
2211         unsigned long flags;
2212         int voice;
2213
2214         if (pcm_active && pcm_opened)
2215                 for (voice = 0; voice < gus_audio_channels; voice++)
2216                 {
2217                         spin_lock_irqsave(&gus_lock,flags);
2218                         gus_select_voice(voice);
2219                         gus_rampoff();
2220                         gus_voice_volume(1530 + (25 * gus_pcm_volume));
2221                         gus_ramp_range(65, 1530 + (25 * gus_pcm_volume));
2222                         spin_unlock_irqrestore(&gus_lock,flags);
2223                 }
2224 }
2225
2226 static void play_next_pcm_block(void)
2227 {
2228         unsigned long flags;
2229         int speed = gus_audio_speed;
2230         int this_one, is16bits, chn;
2231         unsigned long dram_loc;
2232         unsigned char mode[2], ramp_mode[2];
2233
2234         if (!pcm_qlen)
2235                 return;
2236
2237         this_one = pcm_head;
2238
2239         for (chn = 0; chn < gus_audio_channels; chn++)
2240         {
2241                 mode[chn] = 0x00;
2242                 ramp_mode[chn] = 0x03;  /* Ramping and rollover off */
2243
2244                 if (chn == 0)
2245                 {
2246                         mode[chn] |= 0x20;      /* Loop IRQ */
2247                         voices[chn].loop_irq_mode = LMODE_PCM;
2248                 }
2249                 if (gus_audio_bits != 8)
2250                 {
2251                         is16bits = 1;
2252                         mode[chn] |= 0x04;      /* 16 bit data */
2253                 }
2254                 else
2255                         is16bits = 0;
2256
2257                 dram_loc = this_one * pcm_bsize;
2258                 dram_loc += chn * pcm_banksize;
2259
2260                 if (this_one == (pcm_nblk - 1)) /* Last fragment of the DRAM buffer */
2261                 {
2262                         mode[chn] |= 0x08;      /* Enable loop */
2263                         ramp_mode[chn] = 0x03;  /* Disable rollover bit */
2264                 }
2265                 else
2266                 {
2267                         if (chn == 0)
2268                                 ramp_mode[chn] = 0x04;  /* Enable rollover bit */
2269                 }
2270                 spin_lock_irqsave(&gus_lock,flags);
2271                 gus_select_voice(chn);
2272                 gus_voice_freq(speed);
2273
2274                 if (gus_audio_channels == 1)
2275                         gus_voice_balance(7);           /* mono */
2276                 else if (chn == 0)
2277                         gus_voice_balance(0);           /* left */
2278                 else
2279                         gus_voice_balance(15);          /* right */
2280
2281                 if (!pcm_active)        /* Playback not already active */
2282                 {
2283                         /*
2284                          * The playback was not started yet (or there has been a pause).
2285                          * Start the voice (again) and ask for a rollover irq at the end of
2286                          * this_one block. If this_one one is last of the buffers, use just
2287                          * the normal loop with irq.
2288                          */
2289
2290                         gus_voice_off();
2291                         gus_rampoff();
2292                         gus_voice_volume(1530 + (25 * gus_pcm_volume));
2293                         gus_ramp_range(65, 1530 + (25 * gus_pcm_volume));
2294
2295                         gus_write_addr(0x0a, chn * pcm_banksize, 0, is16bits);  /* Starting position */
2296                         gus_write_addr(0x02, chn * pcm_banksize, 0, is16bits);  /* Loop start */
2297
2298                         if (chn != 0)
2299                                 gus_write_addr(0x04, pcm_banksize + (pcm_bsize * pcm_nblk) - 1,
2300                                                    0, is16bits);        /* Loop end location */
2301                 }
2302                 if (chn == 0)
2303                         gus_write_addr(0x04, dram_loc + pcm_bsize - 1,
2304                                          0, is16bits);  /* Loop end location */
2305                 else
2306                         mode[chn] |= 0x08;      /* Enable looping */
2307                 spin_unlock_irqrestore(&gus_lock,flags);
2308         }
2309         for (chn = 0; chn < gus_audio_channels; chn++)
2310         {
2311                 spin_lock_irqsave(&gus_lock,flags);
2312                 gus_select_voice(chn);
2313                 gus_write8(0x0d, ramp_mode[chn]);
2314                 if (iw_mode)
2315                         gus_write8(0x15, 0x00); /* Reset voice deactivate bit of SMSI */
2316                 gus_voice_on(mode[chn]);
2317                 spin_unlock_irqrestore(&gus_lock,flags);
2318         }
2319         pcm_active = 1;
2320 }
2321
2322 static void gus_transfer_output_block(int dev, unsigned long buf,
2323                           int total_count, int intrflag, int chn)
2324 {
2325         /*
2326          * This routine transfers one block of audio data to the DRAM. In mono mode
2327          * it's called just once. When in stereo mode, this_one routine is called
2328          * once for both channels.
2329          *
2330          * The left/mono channel data is transferred to the beginning of dram and the
2331          * right data to the area pointed by gus_page_size.
2332          */
2333
2334         int this_one, count;
2335         unsigned long flags;
2336         unsigned char dma_command;
2337         unsigned long address, hold_address;
2338
2339         spin_lock_irqsave(&gus_lock,flags);
2340
2341         count = total_count / gus_audio_channels;
2342
2343         if (chn == 0)
2344         {
2345                 if (pcm_qlen >= pcm_nblk)
2346                         printk(KERN_WARNING "GUS Warning: PCM buffers out of sync\n");
2347
2348                 this_one = pcm_current_block = pcm_tail;
2349                 pcm_qlen++;
2350                 pcm_tail = (pcm_tail + 1) % pcm_nblk;
2351                 pcm_datasize[this_one] = count;
2352         }
2353         else
2354                 this_one = pcm_current_block;
2355
2356         gus_write8(0x41, 0);    /* Disable GF1 DMA */
2357         DMAbuf_start_dma(dev, buf + (chn * count), count, DMA_MODE_WRITE);
2358
2359         address = this_one * pcm_bsize;
2360         address += chn * pcm_banksize;
2361
2362         if (audio_devs[dev]->dmap_out->dma > 3)
2363         {
2364                 hold_address = address;
2365                 address = address >> 1;
2366                 address &= 0x0001ffffL;
2367                 address |= (hold_address & 0x000c0000L);
2368         }
2369         gus_write16(0x42, (address >> 4) & 0xffff);     /* DRAM DMA address */
2370
2371         dma_command = 0x21;     /* IRQ enable, DMA start */
2372
2373         if (gus_audio_bits != 8)
2374                 dma_command |= 0x40;    /* 16 bit _DATA_ */
2375         else
2376                 dma_command |= 0x80;    /* Invert MSB */
2377
2378         if (audio_devs[dev]->dmap_out->dma > 3)
2379                 dma_command |= 0x04;    /* 16 bit DMA channel */
2380
2381         gus_write8(0x41, dma_command);  /* Kick start */
2382
2383         if (chn == (gus_audio_channels - 1))    /* Last channel */
2384         {
2385                 /*
2386                  * Last (right or mono) channel data
2387                  */
2388                 dma_active = 1; /* DMA started. There is a unacknowledged buffer */
2389                 active_device = GUS_DEV_PCM_DONE;
2390                 if (!pcm_active && (pcm_qlen > 1 || count < pcm_bsize))
2391                 {
2392                         play_next_pcm_block();
2393                 }
2394         }
2395         else
2396         {
2397                 /*
2398                  * Left channel data. The right channel
2399                  * is transferred after DMA interrupt
2400                  */
2401                 active_device = GUS_DEV_PCM_CONTINUE;
2402         }
2403
2404         spin_unlock_irqrestore(&gus_lock,flags);
2405 }
2406
2407 static void gus_uninterleave8(char *buf, int l)
2408 {
2409 /* This routine uninterleaves 8 bit stereo output (LRLRLR->LLLRRR) */
2410         int i, p = 0, halfsize = l / 2;
2411         char *buf2 = buf + halfsize, *src = bounce_buf;
2412
2413         memcpy(bounce_buf, buf, l);
2414
2415         for (i = 0; i < halfsize; i++)
2416         {
2417                 buf[i] = src[p++];      /* Left channel */
2418                 buf2[i] = src[p++];     /* Right channel */
2419         }
2420 }
2421
2422 static void gus_uninterleave16(short *buf, int l)
2423 {
2424 /* This routine uninterleaves 16 bit stereo output (LRLRLR->LLLRRR) */
2425         int i, p = 0, halfsize = l / 2;
2426         short *buf2 = buf + halfsize, *src = (short *) bounce_buf;
2427
2428         memcpy(bounce_buf, (char *) buf, l * 2);
2429
2430         for (i = 0; i < halfsize; i++)
2431         {
2432                 buf[i] = src[p++];      /* Left channel */
2433                 buf2[i] = src[p++];     /* Right channel */
2434         }
2435 }
2436
2437 static void gus_audio_output_block(int dev, unsigned long buf, int total_count,
2438                        int intrflag)
2439 {
2440         struct dma_buffparms *dmap = audio_devs[dev]->dmap_out;
2441
2442         dmap->flags |= DMA_NODMA | DMA_NOTIMEOUT;
2443
2444         pcm_current_buf = buf;
2445         pcm_current_count = total_count;
2446         pcm_current_intrflag = intrflag;
2447         pcm_current_dev = dev;
2448         if (gus_audio_channels == 2)
2449         {
2450                 char *b = dmap->raw_buf + (buf - dmap->raw_buf_phys);
2451
2452                 if (gus_audio_bits == 8)
2453                         gus_uninterleave8(b, total_count);
2454                 else
2455                         gus_uninterleave16((short *) b, total_count / 2);
2456         }
2457         gus_transfer_output_block(dev, buf, total_count, intrflag, 0);
2458 }
2459
2460 static void gus_audio_start_input(int dev, unsigned long buf, int count,
2461                       int intrflag)
2462 {
2463         unsigned long flags;
2464         unsigned char mode;
2465
2466         spin_lock_irqsave(&gus_lock,flags);
2467
2468         DMAbuf_start_dma(dev, buf, count, DMA_MODE_READ);
2469         mode = 0xa0;            /* DMA IRQ enabled, invert MSB */
2470
2471         if (audio_devs[dev]->dmap_in->dma > 3)
2472                 mode |= 0x04;   /* 16 bit DMA channel */
2473         if (gus_audio_channels > 1)
2474                 mode |= 0x02;   /* Stereo */
2475         mode |= 0x01;           /* DMA enable */
2476
2477         gus_write8(0x49, mode);
2478         spin_unlock_irqrestore(&gus_lock,flags);
2479 }
2480
2481 static int gus_audio_prepare_for_input(int dev, int bsize, int bcount)
2482 {
2483         unsigned int rate;
2484
2485         gus_audio_bsize = bsize;
2486         audio_devs[dev]->dmap_in->flags |= DMA_NODMA;
2487         rate = (((9878400 + gus_audio_speed / 2) / (gus_audio_speed + 2)) + 8) / 16;
2488
2489         gus_write8(0x48, rate & 0xff);  /* Set sampling rate */
2490
2491         if (gus_audio_bits != 8)
2492         {
2493 /*              printk("GUS Error: 16 bit recording not supported\n");*/
2494                 return -EINVAL;
2495         }
2496         return 0;
2497 }
2498
2499 static int gus_audio_prepare_for_output(int dev, int bsize, int bcount)
2500 {
2501         int i;
2502
2503         long mem_ptr, mem_size;
2504
2505         audio_devs[dev]->dmap_out->flags |= DMA_NODMA | DMA_NOTIMEOUT;
2506         mem_ptr = 0;
2507         mem_size = gus_mem_size / gus_audio_channels;
2508
2509         if (mem_size > (256 * 1024))
2510                 mem_size = 256 * 1024;
2511
2512         pcm_bsize = bsize / gus_audio_channels;
2513         pcm_head = pcm_tail = pcm_qlen = 0;
2514
2515         pcm_nblk = 2;           /* MAX_PCM_BUFFERS; */
2516         if ((pcm_bsize * pcm_nblk) > mem_size)
2517                 pcm_nblk = mem_size / pcm_bsize;
2518
2519         for (i = 0; i < pcm_nblk; i++)
2520                 pcm_datasize[i] = 0;
2521
2522         pcm_banksize = pcm_nblk * pcm_bsize;
2523
2524         if (gus_audio_bits != 8 && pcm_banksize == (256 * 1024))
2525                 pcm_nblk--;
2526         gus_write8(0x41, 0);    /* Disable GF1 DMA */
2527         return 0;
2528 }
2529
2530 static int gus_local_qlen(int dev)
2531 {
2532         return pcm_qlen;
2533 }
2534
2535
2536 static struct audio_driver gus_audio_driver =
2537 {
2538         .owner                  = THIS_MODULE,
2539         .open                   = gus_audio_open,
2540         .close                  = gus_audio_close,
2541         .output_block           = gus_audio_output_block,
2542         .start_input            = gus_audio_start_input,
2543         .ioctl                  = gus_audio_ioctl,
2544         .prepare_for_input      = gus_audio_prepare_for_input,
2545         .prepare_for_output     = gus_audio_prepare_for_output,
2546         .halt_io                = gus_audio_reset,
2547         .local_qlen             = gus_local_qlen,
2548 };
2549
2550 static void guswave_setup_voice(int dev, int voice, int chn)
2551 {
2552         struct channel_info *info = &synth_devs[dev]->chn_info[chn];
2553
2554         guswave_set_instr(dev, voice, info->pgm_num);
2555         voices[voice].expression_vol = info->controllers[CTL_EXPRESSION];       /* Just MSB */
2556         voices[voice].main_vol = (info->controllers[CTL_MAIN_VOLUME] * 100) / (unsigned) 128;
2557         voices[voice].panning = (info->controllers[CTL_PAN] * 2) - 128;
2558         voices[voice].bender = 0;
2559         voices[voice].bender_range = info->bender_range;
2560
2561         if (chn == 9)
2562                 voices[voice].fixed_pitch = 1;
2563 }
2564
2565 static void guswave_bender(int dev, int voice, int value)
2566 {
2567         int freq;
2568         unsigned long   flags;
2569
2570         voices[voice].bender = value - 8192;
2571         freq = compute_finetune(voices[voice].orig_freq, value - 8192, voices[voice].bender_range, 0);
2572         voices[voice].current_freq = freq;
2573
2574         spin_lock_irqsave(&gus_lock,flags);
2575         gus_select_voice(voice);
2576         gus_voice_freq(freq);
2577         spin_unlock_irqrestore(&gus_lock,flags);
2578 }
2579
2580 static int guswave_alloc(int dev, int chn, int note, struct voice_alloc_info *alloc)
2581 {
2582         int i, p, best = -1, best_time = 0x7fffffff;
2583
2584         p = alloc->ptr;
2585         /*
2586          * First look for a completely stopped voice
2587          */
2588
2589         for (i = 0; i < alloc->max_voice; i++)
2590         {
2591                 if (alloc->map[p] == 0)
2592                 {
2593                         alloc->ptr = p;
2594                         return p;
2595                 }
2596                 if (alloc->alloc_times[p] < best_time)
2597                 {
2598                         best = p;
2599                         best_time = alloc->alloc_times[p];
2600                 }
2601                 p = (p + 1) % alloc->max_voice;
2602         }
2603
2604         /*
2605          * Then look for a releasing voice
2606          */
2607
2608         for (i = 0; i < alloc->max_voice; i++)
2609         {
2610                 if (alloc->map[p] == 0xffff)
2611                 {
2612                         alloc->ptr = p;
2613                         return p;
2614                 }
2615                 p = (p + 1) % alloc->max_voice;
2616         }
2617         if (best >= 0)
2618                 p = best;
2619
2620         alloc->ptr = p;
2621         return p;
2622 }
2623
2624 static struct synth_operations guswave_operations =
2625 {
2626         .owner          = THIS_MODULE,
2627         .id             = "GUS",
2628         .info           = &gus_info,
2629         .midi_dev       = 0,
2630         .synth_type     = SYNTH_TYPE_SAMPLE,
2631         .synth_subtype  = SAMPLE_TYPE_GUS,
2632         .open           = guswave_open,
2633         .close          = guswave_close,
2634         .ioctl          = guswave_ioctl,
2635         .kill_note      = guswave_kill_note,
2636         .start_note     = guswave_start_note,
2637         .set_instr      = guswave_set_instr,
2638         .reset          = guswave_reset,
2639         .hw_control     = guswave_hw_control,
2640         .load_patch     = guswave_load_patch,
2641         .aftertouch     = guswave_aftertouch,
2642         .controller     = guswave_controller,
2643         .panning        = guswave_panning,
2644         .volume_method  = guswave_volume_method,
2645         .bender         = guswave_bender,
2646         .alloc_voice    = guswave_alloc,
2647         .setup_voice    = guswave_setup_voice
2648 };
2649
2650 static void set_input_volumes(void)
2651 {
2652         unsigned long flags;
2653         unsigned char mask = 0xff & ~0x06;      /* Just line out enabled */
2654
2655         if (have_gus_max)       /* Don't disturb GUS MAX */
2656                 return;
2657
2658         spin_lock_irqsave(&gus_lock,flags);
2659
2660         /*
2661          *    Enable channels having vol > 10%
2662          *      Note! bit 0x01 means the line in DISABLED while 0x04 means
2663          *            the mic in ENABLED.
2664          */
2665         if (gus_line_vol > 10)
2666                 mask &= ~0x01;
2667         if (gus_mic_vol > 10)
2668                 mask |= 0x04;
2669
2670         if (recording_active)
2671         {
2672                 /*
2673                  *    Disable channel, if not selected for recording
2674                  */
2675                 if (!(gus_recmask & SOUND_MASK_LINE))
2676                         mask |= 0x01;
2677                 if (!(gus_recmask & SOUND_MASK_MIC))
2678                         mask &= ~0x04;
2679         }
2680         mix_image &= ~0x07;
2681         mix_image |= mask & 0x07;
2682         outb((mix_image), u_Mixer);
2683
2684         spin_unlock_irqrestore(&gus_lock,flags);
2685 }
2686
2687 #define MIX_DEVS        (SOUND_MASK_MIC|SOUND_MASK_LINE| \
2688                          SOUND_MASK_SYNTH|SOUND_MASK_PCM)
2689
2690 int gus_default_mixer_ioctl(int dev, unsigned int cmd, void __user *arg)
2691 {
2692         int vol, val;
2693
2694         if (((cmd >> 8) & 0xff) != 'M')
2695                 return -EINVAL;
2696
2697         if (!access_ok(VERIFY_WRITE, arg, sizeof(int)))
2698                 return -EFAULT;
2699
2700         if (_SIOC_DIR(cmd) & _SIOC_WRITE) 
2701         {
2702                 if (__get_user(val, (int __user *) arg))
2703                         return -EFAULT;
2704
2705                 switch (cmd & 0xff) 
2706                 {
2707                         case SOUND_MIXER_RECSRC:
2708                                 gus_recmask = val & MIX_DEVS;
2709                                 if (!(gus_recmask & (SOUND_MASK_MIC | SOUND_MASK_LINE)))
2710                                         gus_recmask = SOUND_MASK_MIC;
2711                                 /* Note! Input volumes are updated during next open for recording */
2712                                 val = gus_recmask;
2713                                 break;
2714
2715                         case SOUND_MIXER_MIC:
2716                                 vol = val & 0xff;
2717                                 if (vol < 0)
2718                                         vol = 0;
2719                                 if (vol > 100)
2720                                         vol = 100;
2721                                 gus_mic_vol = vol;
2722                                 set_input_volumes();
2723                                 val = vol | (vol << 8);
2724                                 break;
2725                                 
2726                         case SOUND_MIXER_LINE:
2727                                 vol = val & 0xff;
2728                                 if (vol < 0)
2729                                         vol = 0;
2730                                 if (vol > 100)
2731                                         vol = 100;
2732                                 gus_line_vol = vol;
2733                                 set_input_volumes();
2734                                 val = vol | (vol << 8);
2735                                 break;
2736
2737                         case SOUND_MIXER_PCM:
2738                                 gus_pcm_volume = val & 0xff;
2739                                 if (gus_pcm_volume < 0)
2740                                         gus_pcm_volume = 0;
2741                                 if (gus_pcm_volume > 100)
2742                                         gus_pcm_volume = 100;
2743                                 gus_audio_update_volume();
2744                                 val = gus_pcm_volume | (gus_pcm_volume << 8);
2745                                 break;
2746
2747                         case SOUND_MIXER_SYNTH:
2748                                 gus_wave_volume = val & 0xff;
2749                                 if (gus_wave_volume < 0)
2750                                         gus_wave_volume = 0;
2751                                 if (gus_wave_volume > 100)
2752                                         gus_wave_volume = 100;
2753                                 if (active_device == GUS_DEV_WAVE) 
2754                                 {
2755                                         int voice;
2756                                         for (voice = 0; voice < nr_voices; voice++)
2757                                         dynamic_volume_change(voice);   /* Apply the new vol */
2758                                 }
2759                                 val = gus_wave_volume | (gus_wave_volume << 8);
2760                                 break;
2761
2762                         default:
2763                                 return -EINVAL;
2764                 }
2765         }
2766         else
2767         {
2768                 switch (cmd & 0xff) 
2769                 {
2770                         /*
2771                          * Return parameters
2772                          */
2773                         case SOUND_MIXER_RECSRC:
2774                                 val = gus_recmask;
2775                                 break;
2776                                         
2777                         case SOUND_MIXER_DEVMASK:
2778                                 val = MIX_DEVS;
2779                                 break;
2780
2781                         case SOUND_MIXER_STEREODEVS:
2782                                 val = 0;
2783                                 break;
2784
2785                         case SOUND_MIXER_RECMASK:
2786                                 val = SOUND_MASK_MIC | SOUND_MASK_LINE;
2787                                 break;
2788
2789                         case SOUND_MIXER_CAPS:
2790                                 val = 0;
2791                                 break;
2792
2793                         case SOUND_MIXER_MIC:
2794                                 val = gus_mic_vol | (gus_mic_vol << 8);
2795                                 break;
2796
2797                         case SOUND_MIXER_LINE:
2798                                 val = gus_line_vol | (gus_line_vol << 8);
2799                                 break;
2800
2801                         case SOUND_MIXER_PCM:
2802                                 val = gus_pcm_volume | (gus_pcm_volume << 8);
2803                                 break;
2804
2805                         case SOUND_MIXER_SYNTH:
2806                                 val = gus_wave_volume | (gus_wave_volume << 8);
2807                                 break;
2808
2809                         default:
2810                                 return -EINVAL;
2811                 }
2812         }
2813         return __put_user(val, (int __user *)arg);
2814 }
2815
2816 static struct mixer_operations gus_mixer_operations =
2817 {
2818         .owner  = THIS_MODULE,
2819         .id     = "GUS",
2820         .name   = "Gravis Ultrasound",
2821         .ioctl  = gus_default_mixer_ioctl
2822 };
2823
2824 static int __init gus_default_mixer_init(void)
2825 {
2826         int n;
2827
2828         if ((n = sound_alloc_mixerdev()) != -1)
2829         {       
2830                 /*
2831                  * Don't install if there is another
2832                  * mixer
2833                  */
2834                 mixer_devs[n] = &gus_mixer_operations;
2835         }
2836         if (have_gus_max)
2837         {
2838                 /*
2839                  *  Enable all mixer channels on the GF1 side. Otherwise recording will
2840                  *  not be possible using GUS MAX.
2841                  */
2842                 mix_image &= ~0x07;
2843                 mix_image |= 0x04;      /* All channels enabled */
2844                 outb((mix_image), u_Mixer);
2845         }
2846         return n;
2847 }
2848
2849 void __init gus_wave_init(struct address_info *hw_config)
2850 {
2851         unsigned long flags;
2852         unsigned char val;
2853         char *model_num = "2.4";
2854         char tmp[64];
2855         int gus_type = 0x24;    /* 2.4 */
2856
2857         int irq = hw_config->irq, dma = hw_config->dma, dma2 = hw_config->dma2;
2858         int sdev;
2859
2860         hw_config->slots[0] = -1;       /* No wave */
2861         hw_config->slots[1] = -1;       /* No ad1848 */
2862         hw_config->slots[4] = -1;       /* No audio */
2863         hw_config->slots[5] = -1;       /* No mixer */
2864
2865         if (!gus_pnp_flag)
2866         {
2867                 if (irq < 0 || irq > 15)
2868                 {
2869                         printk(KERN_ERR "ERROR! Invalid IRQ#%d. GUS Disabled", irq);
2870                         return;
2871                 }
2872         }
2873         
2874         if (dma < 0 || dma > 7 || dma == 4)
2875         {
2876                 printk(KERN_ERR "ERROR! Invalid DMA#%d. GUS Disabled", dma);
2877                 return;
2878         }
2879         gus_irq = irq;
2880         gus_dma = dma;
2881         gus_dma2 = dma2;
2882         gus_hw_config = hw_config;
2883
2884         if (gus_dma2 == -1)
2885                 gus_dma2 = dma;
2886
2887         /*
2888          * Try to identify the GUS model.
2889          *
2890          *  Versions < 3.6 don't have the digital ASIC. Try to probe it first.
2891          */
2892
2893         spin_lock_irqsave(&gus_lock,flags);
2894         outb((0x20), gus_base + 0x0f);
2895         val = inb(gus_base + 0x0f);
2896         spin_unlock_irqrestore(&gus_lock,flags);
2897
2898         if (gus_pnp_flag || (val != 0xff && (val & 0x06)))      /* Should be 0x02?? */
2899         {
2900                 int             ad_flags = 0;
2901
2902                 if (gus_pnp_flag)
2903                         ad_flags = 0x12345678;  /* Interwave "magic" */
2904                 /*
2905                  * It has the digital ASIC so the card is at least v3.4.
2906                  * Next try to detect the true model.
2907                  */
2908
2909                 if (gus_pnp_flag)       /* Hack hack hack */
2910                         val = 10;
2911                 else
2912                         val = inb(u_MixSelect);
2913
2914                 /*
2915                  * Value 255 means pre-3.7 which don't have mixer.
2916                  * Values 5 thru 9 mean v3.7 which has a ICS2101 mixer.
2917                  * 10 and above is GUS MAX which has the CS4231 codec/mixer.
2918                  *
2919                  */
2920
2921                 if (val == 255 || val < 5)
2922                 {
2923                         model_num = "3.4";
2924                         gus_type = 0x34;
2925                 }
2926                 else if (val < 10)
2927                 {
2928                         model_num = "3.7";
2929                         gus_type = 0x37;
2930                         mixer_type = ICS2101;
2931                         request_region(u_MixSelect, 1, "GUS mixer");
2932                 }
2933                 else
2934                 {
2935                         model_num = "MAX";
2936                         gus_type = 0x40;
2937                         mixer_type = CS4231;
2938 #ifdef CONFIG_SOUND_GUSMAX
2939                         {
2940                                 unsigned char   max_config = 0x40;      /* Codec enable */
2941
2942                                 if (gus_dma2 == -1)
2943                                         gus_dma2 = gus_dma;
2944
2945                                 if (gus_dma > 3)
2946                                         max_config |= 0x10;             /* 16 bit capture DMA */
2947
2948                                 if (gus_dma2 > 3)
2949                                         max_config |= 0x20;             /* 16 bit playback DMA */
2950
2951                                 max_config |= (gus_base >> 4) & 0x0f;   /* Extract the X from 2X0 */
2952
2953                                 outb((max_config), gus_base + 0x106);   /* UltraMax control */
2954                         }
2955
2956                         if (ad1848_detect(gus_base + 0x10c, &ad_flags, hw_config->osp))
2957                         {
2958                                 char           *name = "GUS MAX";
2959                                 int             old_num_mixers = num_mixers;
2960
2961                                 if (gus_pnp_flag)
2962                                         name = "GUS PnP";
2963
2964                                 gus_mic_vol = gus_line_vol = gus_pcm_volume = 100;
2965                                 gus_wave_volume = 90;
2966                                 have_gus_max = 1;
2967                                 if (hw_config->name)
2968                                         name = hw_config->name;
2969
2970                                 hw_config->slots[1] = ad1848_init(name, gus_base + 0x10c,
2971                                                         -irq, gus_dma2, /* Playback DMA */
2972                                                         gus_dma,        /* Capture DMA */
2973                                                         1,              /* Share DMA channels with GF1 */
2974                                                         hw_config->osp,
2975                                                         THIS_MODULE);
2976
2977                                 if (num_mixers > old_num_mixers)
2978                                 {
2979                                         /* GUS has it's own mixer map */
2980                                         AD1848_REROUTE(SOUND_MIXER_LINE1, SOUND_MIXER_SYNTH);
2981                                         AD1848_REROUTE(SOUND_MIXER_LINE2, SOUND_MIXER_CD);
2982                                         AD1848_REROUTE(SOUND_MIXER_LINE3, SOUND_MIXER_LINE);
2983                                 }
2984                         }
2985                         else
2986                                 printk(KERN_WARNING "GUS: No CS4231 ??");
2987 #else
2988                         printk(KERN_ERR "GUS MAX found, but not compiled in\n");
2989 #endif
2990                 }
2991         }
2992         else
2993         {
2994                 /*
2995                  * ASIC not detected so the card must be 2.2 or 2.4.
2996                  * There could still be the 16-bit/mixer daughter card.
2997                  */
2998         }
2999
3000         if (hw_config->name)
3001                 snprintf(tmp, sizeof(tmp), "%s (%dk)", hw_config->name,
3002                          (int) gus_mem_size / 1024);
3003         else if (gus_pnp_flag)
3004                 snprintf(tmp, sizeof(tmp), "Gravis UltraSound PnP (%dk)",
3005                          (int) gus_mem_size / 1024);
3006         else
3007                 snprintf(tmp, sizeof(tmp), "Gravis UltraSound %s (%dk)", model_num,
3008                          (int) gus_mem_size / 1024);
3009
3010
3011         samples = (struct patch_info *)vmalloc((MAX_SAMPLE + 1) * sizeof(*samples));
3012         if (samples == NULL)
3013         {
3014                 printk(KERN_WARNING "gus_init: Cant allocate memory for instrument tables\n");
3015                 return;
3016         }
3017         conf_printf(tmp, hw_config);
3018         strlcpy(gus_info.name, tmp, sizeof(gus_info.name));
3019
3020         if ((sdev = sound_alloc_synthdev()) == -1)
3021                 printk(KERN_WARNING "gus_init: Too many synthesizers\n");
3022         else
3023         {
3024                 voice_alloc = &guswave_operations.alloc;
3025                 if (iw_mode)
3026                         guswave_operations.id = "IWAVE";
3027                 hw_config->slots[0] = sdev;
3028                 synth_devs[sdev] = &guswave_operations;
3029                 sequencer_init();
3030                 gus_tmr_install(gus_base + 8);
3031         }
3032
3033         reset_sample_memory();
3034
3035         gus_initialize();
3036         
3037         if ((gus_mem_size > 0) && !gus_no_wave_dma)
3038         {
3039                 hw_config->slots[4] = -1;
3040                 if ((gus_devnum = sound_install_audiodrv(AUDIO_DRIVER_VERSION,
3041                                         "Ultrasound",
3042                                         &gus_audio_driver,
3043                                         sizeof(struct audio_driver),
3044                                         NEEDS_RESTART |
3045                                         ((!iw_mode && dma2 != dma && dma2 != -1) ?
3046                                                 DMA_DUPLEX : 0),
3047                                         AFMT_U8 | AFMT_S16_LE,
3048                                         NULL, dma, dma2)) < 0)
3049                 {
3050                         return;
3051                 }
3052
3053                 hw_config->slots[4] = gus_devnum;
3054                 audio_devs[gus_devnum]->min_fragment = 9;       /* 512k */
3055                 audio_devs[gus_devnum]->max_fragment = 11;      /* 8k (must match size of bounce_buf */
3056                 audio_devs[gus_devnum]->mixer_dev = -1; /* Next mixer# */
3057                 audio_devs[gus_devnum]->flags |= DMA_HARDSTOP;
3058         }
3059         
3060         /*
3061          *  Mixer dependent initialization.
3062          */
3063
3064         switch (mixer_type)
3065         {
3066                 case ICS2101:
3067                         gus_mic_vol = gus_line_vol = gus_pcm_volume = 100;
3068                         gus_wave_volume = 90;
3069                         request_region(u_MixSelect, 1, "GUS mixer");
3070                         hw_config->slots[5] = ics2101_mixer_init();
3071                         audio_devs[gus_devnum]->mixer_dev = hw_config->slots[5];        /* Next mixer# */
3072                         return;
3073
3074                 case CS4231:
3075                         /* Initialized elsewhere (ad1848.c) */
3076                 default:
3077                         hw_config->slots[5] = gus_default_mixer_init();
3078                         audio_devs[gus_devnum]->mixer_dev = hw_config->slots[5];        /* Next mixer# */
3079                         return;
3080         }
3081 }
3082
3083 void __exit gus_wave_unload(struct address_info *hw_config)
3084 {
3085 #ifdef CONFIG_SOUND_GUSMAX
3086         if (have_gus_max)
3087         {
3088                 ad1848_unload(gus_base + 0x10c,
3089                                 -gus_irq,
3090                                 gus_dma2,       /* Playback DMA */
3091                                 gus_dma,        /* Capture DMA */
3092                                 1);     /* Share DMA channels with GF1 */
3093         }
3094 #endif
3095
3096         if (mixer_type == ICS2101)
3097         {
3098                 release_region(u_MixSelect, 1);
3099         }
3100         if (hw_config->slots[0] != -1)
3101                 sound_unload_synthdev(hw_config->slots[0]);
3102         if (hw_config->slots[1] != -1)
3103                 sound_unload_audiodev(hw_config->slots[1]);
3104         if (hw_config->slots[2] != -1)
3105                 sound_unload_mididev(hw_config->slots[2]);
3106         if (hw_config->slots[4] != -1)
3107                 sound_unload_audiodev(hw_config->slots[4]);
3108         if (hw_config->slots[5] != -1)
3109                 sound_unload_mixerdev(hw_config->slots[5]);
3110         
3111         if(samples)
3112                 vfree(samples);
3113         samples=NULL;
3114 }
3115 /* called in interrupt context */
3116 static void do_loop_irq(int voice)
3117 {
3118         unsigned char   tmp;
3119         int             mode, parm;
3120
3121         spin_lock(&gus_lock);
3122         gus_select_voice(voice);
3123
3124         tmp = gus_read8(0x00);
3125         tmp &= ~0x20;           /*
3126                                  * Disable wave IRQ for this_one voice
3127                                  */
3128         gus_write8(0x00, tmp);
3129
3130         if (tmp & 0x03)         /* Voice stopped */
3131                 voice_alloc->map[voice] = 0;
3132
3133         mode = voices[voice].loop_irq_mode;
3134         voices[voice].loop_irq_mode = 0;
3135         parm = voices[voice].loop_irq_parm;
3136
3137         switch (mode)
3138         {
3139                 case LMODE_FINISH:      /*
3140                                          * Final loop finished, shoot volume down
3141                                          */
3142
3143                         if ((int) (gus_read16(0x09) >> 4) < 100)        /*
3144                                                                          * Get current volume
3145                                                                          */
3146                         {
3147                                 gus_voice_off();
3148                                 gus_rampoff();
3149                                 gus_voice_init(voice);
3150                                 break;
3151                         }
3152                         gus_ramp_range(65, 4065);
3153                         gus_ramp_rate(0, 63);           /*
3154                                                          * Fastest possible rate
3155                                                          */
3156                         gus_rampon(0x20 | 0x40);        /*
3157                                                          * Ramp down, once, irq
3158                                                          */
3159                         voices[voice].volume_irq_mode = VMODE_HALT;
3160                         break;
3161
3162                 case LMODE_PCM_STOP:
3163                         pcm_active = 0; /* Signal to the play_next_pcm_block routine */
3164                 case LMODE_PCM:
3165                 {
3166                         pcm_qlen--;
3167                         pcm_head = (pcm_head + 1) % pcm_nblk;
3168                         if (pcm_qlen && pcm_active)
3169                         {
3170                                 play_next_pcm_block();
3171                         }
3172                         else
3173                         {
3174                                 /* Underrun. Just stop the voice */
3175                                 gus_select_voice(0);    /* Left channel */
3176                                 gus_voice_off();
3177                                 gus_rampoff();
3178                                 gus_select_voice(1);    /* Right channel */
3179                                 gus_voice_off();
3180                                 gus_rampoff();
3181                                 pcm_active = 0;
3182                         }
3183
3184                         /*
3185                          * If the queue was full before this interrupt, the DMA transfer was
3186                          * suspended. Let it continue now.
3187                          */
3188                         
3189                         if (audio_devs[gus_devnum]->dmap_out->qlen > 0)
3190                                 DMAbuf_outputintr(gus_devnum, 0);
3191                 }
3192                 break;
3193
3194                 default:
3195                         break;
3196         }
3197         spin_unlock(&gus_lock);
3198 }
3199
3200 static void do_volume_irq(int voice)
3201 {
3202         unsigned char tmp;
3203         int mode, parm;
3204         unsigned long flags;
3205
3206         spin_lock_irqsave(&gus_lock,flags);
3207
3208         gus_select_voice(voice);
3209         tmp = gus_read8(0x0d);
3210         tmp &= ~0x20;           /*
3211                                  * Disable volume ramp IRQ
3212                                  */
3213         gus_write8(0x0d, tmp);
3214
3215         mode = voices[voice].volume_irq_mode;
3216         voices[voice].volume_irq_mode = 0;
3217         parm = voices[voice].volume_irq_parm;
3218
3219         switch (mode)
3220         {
3221                 case VMODE_HALT:        /* Decay phase finished */
3222                         if (iw_mode)
3223                                 gus_write8(0x15, 0x02); /* Set voice deactivate bit of SMSI */
3224                         spin_unlock_irqrestore(&gus_lock,flags);
3225                         gus_voice_init(voice);
3226                         break;
3227
3228                 case VMODE_ENVELOPE:
3229                         gus_rampoff();
3230                         spin_unlock_irqrestore(&gus_lock,flags);
3231                         step_envelope(voice);
3232                         break;
3233
3234                 case VMODE_START_NOTE:
3235                         spin_unlock_irqrestore(&gus_lock,flags);
3236                         guswave_start_note2(voices[voice].dev_pending, voice,
3237                                       voices[voice].note_pending, voices[voice].volume_pending);
3238                         if (voices[voice].kill_pending)
3239                                 guswave_kill_note(voices[voice].dev_pending, voice,
3240                                           voices[voice].note_pending, 0);
3241
3242                         if (voices[voice].sample_pending >= 0)
3243                         {
3244                                 guswave_set_instr(voices[voice].dev_pending, voice,
3245                                         voices[voice].sample_pending);
3246                                 voices[voice].sample_pending = -1;
3247                         }
3248                         break;
3249
3250                 default:
3251                         spin_unlock_irqrestore(&gus_lock,flags);
3252         }
3253 }
3254 /* called in irq context */
3255 void gus_voice_irq(void)
3256 {
3257         unsigned long wave_ignore = 0, volume_ignore = 0;
3258         unsigned long voice_bit;
3259
3260         unsigned char src, voice;
3261
3262         while (1)
3263         {
3264                 src = gus_read8(0x0f);  /*
3265                                          * Get source info
3266                                          */
3267                 voice = src & 0x1f;
3268                 src &= 0xc0;
3269
3270                 if (src == (0x80 | 0x40))
3271                         return; /*
3272                                  * No interrupt
3273                                  */
3274
3275                 voice_bit = 1 << voice;
3276
3277                 if (!(src & 0x80))      /*
3278                                          * Wave IRQ pending
3279                                          */
3280                         if (!(wave_ignore & voice_bit) && (int) voice < nr_voices)      /*
3281                                                                                          * Not done
3282                                                                                          * yet
3283                                                                                          */
3284                         {
3285                                 wave_ignore |= voice_bit;
3286                                 do_loop_irq(voice);
3287                         }
3288                 if (!(src & 0x40))      /*
3289                                          * Volume IRQ pending
3290                                          */
3291                         if (!(volume_ignore & voice_bit) && (int) voice < nr_voices)    /*
3292                                                                                            * Not done
3293                                                                                            * yet
3294                                                                                          */
3295                         {
3296                                 volume_ignore |= voice_bit;
3297                                 do_volume_irq(voice);
3298                         }
3299         }
3300 }
3301
3302 void guswave_dma_irq(void)
3303 {
3304         unsigned char   status;
3305
3306         status = gus_look8(0x41);       /* Get DMA IRQ Status */
3307         if (status & 0x40)      /* DMA interrupt pending */
3308                 switch (active_device)
3309                 {
3310                         case GUS_DEV_WAVE:
3311                                 wake_up(&dram_sleeper);
3312                                 break;
3313
3314                         case GUS_DEV_PCM_CONTINUE:      /* Left channel data transferred */
3315                                 gus_write8(0x41, 0);    /* Disable GF1 DMA */
3316                                 gus_transfer_output_block(pcm_current_dev, pcm_current_buf,
3317                                                 pcm_current_count,
3318                                                 pcm_current_intrflag, 1);
3319                                 break;
3320
3321                         case GUS_DEV_PCM_DONE:  /* Right or mono channel data transferred */
3322                                 gus_write8(0x41, 0);    /* Disable GF1 DMA */
3323                                 if (pcm_qlen < pcm_nblk)
3324                                 {
3325                                         dma_active = 0;
3326                                         if (gus_busy)
3327                                         {
3328                                                 if (audio_devs[gus_devnum]->dmap_out->qlen > 0)
3329                                                         DMAbuf_outputintr(gus_devnum, 0);
3330                                         }
3331                                 }
3332                                 break;
3333
3334                         default:
3335                                 break;
3336         }
3337         status = gus_look8(0x49);       /*
3338                                          * Get Sampling IRQ Status
3339                                          */
3340         if (status & 0x40)      /*
3341                                  * Sampling Irq pending
3342                                  */
3343         {
3344                 DMAbuf_inputintr(gus_devnum);
3345         }
3346 }
3347
3348 /*
3349  * Timer stuff
3350  */
3351
3352 static volatile int select_addr, data_addr;
3353 static volatile int curr_timer;
3354
3355 void gus_timer_command(unsigned int addr, unsigned int val)
3356 {
3357         int i;
3358
3359         outb(((unsigned char) (addr & 0xff)), select_addr);
3360
3361         for (i = 0; i < 2; i++)
3362                 inb(select_addr);
3363
3364         outb(((unsigned char) (val & 0xff)), data_addr);
3365
3366         for (i = 0; i < 2; i++)
3367                 inb(select_addr);
3368 }
3369
3370 static void arm_timer(int timer, unsigned int interval)
3371 {
3372         curr_timer = timer;
3373
3374         if (timer == 1)
3375         {
3376                 gus_write8(0x46, 256 - interval);       /* Set counter for timer 1 */
3377                 gus_write8(0x45, 0x04);                 /* Enable timer 1 IRQ */
3378                 gus_timer_command(0x04, 0x01);          /* Start timer 1 */
3379         }
3380         else
3381         {
3382                 gus_write8(0x47, 256 - interval);       /* Set counter for timer 2 */
3383                 gus_write8(0x45, 0x08);                 /* Enable timer 2 IRQ */
3384                 gus_timer_command(0x04, 0x02);          /* Start timer 2 */
3385         }
3386
3387         gus_timer_enabled = 1;
3388 }
3389
3390 static unsigned int gus_tmr_start(int dev, unsigned int usecs_per_tick)
3391 {
3392         int timer_no, resolution;
3393         int divisor;
3394
3395         if (usecs_per_tick > (256 * 80))
3396         {
3397                 timer_no = 2;
3398                 resolution = 320;       /* usec */
3399         }
3400         else
3401         {
3402                 timer_no = 1;
3403                 resolution = 80;        /* usec */
3404         }
3405         divisor = (usecs_per_tick + (resolution / 2)) / resolution;
3406         arm_timer(timer_no, divisor);
3407
3408         return divisor * resolution;
3409 }
3410
3411 static void gus_tmr_disable(int dev)
3412 {
3413         gus_write8(0x45, 0);    /* Disable both timers */
3414         gus_timer_enabled = 0;
3415 }
3416
3417 static void gus_tmr_restart(int dev)
3418 {
3419         if (curr_timer == 1)
3420                 gus_write8(0x45, 0x04);         /* Start timer 1 again */
3421         else
3422                 gus_write8(0x45, 0x08);         /* Start timer 2 again */
3423         gus_timer_enabled = 1;
3424 }
3425
3426 static struct sound_lowlev_timer gus_tmr =
3427 {
3428         0,
3429         1,
3430         gus_tmr_start,
3431         gus_tmr_disable,
3432         gus_tmr_restart
3433 };
3434
3435 static void gus_tmr_install(int io_base)
3436 {
3437         struct sound_lowlev_timer *tmr;
3438
3439         select_addr = io_base;
3440         data_addr = io_base + 1;
3441
3442         tmr = &gus_tmr;
3443
3444 #ifdef THIS_GETS_FIXED
3445         sound_timer_init(&gus_tmr, "GUS");
3446 #endif
3447 }