Merge master.kernel.org:/pub/scm/linux/kernel/git/mchehab/v4l-dvb
[linux-2.6] / 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 static 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 DEFINE_SPINLOCK(gus_lock);
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         if (!request_region(baseaddr, 16, "GUS"))
982                 return 0;
983         if (!request_region(baseaddr + 0x100, 12, "GUS")) { /* 0x10c-> is MAX */
984                 release_region(baseaddr, 16);
985                 return 0;
986         }
987
988         gus_base = baseaddr;
989
990         gus_write8(0x4c, 0);    /* Reset GF1 */
991         gus_delay();
992         gus_delay();
993
994         gus_write8(0x4c, 1);    /* Release Reset */
995         gus_delay();
996         gus_delay();
997
998 #ifdef GUSPNP_AUTODETECT
999         val = gus_look8(0x5b);  /* Version number register */
1000         gus_write8(0x5b, ~val); /* Invert all bits */
1001
1002         if ((gus_look8(0x5b) & 0xf0) == (val & 0xf0))   /* No change */
1003         {
1004                 if ((gus_look8(0x5b) & 0x0f) == ((~val) & 0x0f))        /* Change */
1005                 {
1006                         DDB(printk("Interwave chip version %d detected\n", (val & 0xf0) >> 4));
1007                         gus_pnp_flag = 1;
1008                 }
1009                 else
1010                 {
1011                         DDB(printk("Not an Interwave chip (%x)\n", gus_look8(0x5b)));
1012                         gus_pnp_flag = 0;
1013                 }
1014         }
1015         gus_write8(0x5b, val);  /* Restore all bits */
1016 #endif
1017
1018         if (gus_pnp_flag)
1019                 pnp_mem_init();
1020         if (iw_mode)
1021                 return 1;
1022
1023         /* See if there is first block there.... */
1024         gus_poke(0L, 0xaa);
1025         if (gus_peek(0L) != 0xaa) {
1026                 release_region(baseaddr + 0x100, 12);
1027                 release_region(baseaddr, 16);
1028                 return 0;
1029         }
1030
1031         /* Now zero it out so that I can check for mirroring .. */
1032         gus_poke(0L, 0x00);
1033         for (i = 1L; i < max_mem; i++)
1034         {
1035                 int n, failed;
1036
1037                 /* check for mirroring ... */
1038                 if (gus_peek(0L) != 0)
1039                         break;
1040                 loc = i << 10;
1041
1042                 for (n = loc - 1, failed = 0; n <= loc; n++)
1043                 {
1044                         gus_poke(loc, 0xaa);
1045                         if (gus_peek(loc) != 0xaa)
1046                                 failed = 1;
1047                         gus_poke(loc, 0x55);
1048                         if (gus_peek(loc) != 0x55)
1049                                 failed = 1;
1050                 }
1051                 if (failed)
1052                         break;
1053         }
1054         gus_mem_size = i << 10;
1055         return 1;
1056 }
1057
1058 static int guswave_ioctl(int dev, unsigned int cmd, void __user *arg)
1059 {
1060
1061         switch (cmd) 
1062         {
1063                 case SNDCTL_SYNTH_INFO:
1064                         gus_info.nr_voices = nr_voices;
1065                         if (copy_to_user(arg, &gus_info, sizeof(gus_info)))
1066                                 return -EFAULT;
1067                         return 0;
1068
1069                 case SNDCTL_SEQ_RESETSAMPLES:
1070                         reset_sample_memory();
1071                         return 0;
1072
1073                 case SNDCTL_SEQ_PERCMODE:
1074                         return 0;
1075
1076                 case SNDCTL_SYNTH_MEMAVL:
1077                         return (gus_mem_size == 0) ? 0 : gus_mem_size - free_mem_ptr - 32;
1078
1079                 default:
1080                         return -EINVAL;
1081         }
1082 }
1083
1084 static int guswave_set_instr(int dev, int voice, int instr_no)
1085 {
1086         int sample_no;
1087
1088         if (instr_no < 0 || instr_no > MAX_PATCH)
1089                 instr_no = 0;   /* Default to acoustic piano */
1090
1091         if (voice < 0 || voice > 31)
1092                 return -EINVAL;
1093
1094         if (voices[voice].volume_irq_mode == VMODE_START_NOTE)
1095         {
1096                 voices[voice].sample_pending = instr_no;
1097                 return 0;
1098         }
1099         sample_no = patch_table[instr_no];
1100         patch_map[voice] = -1;
1101
1102         if (sample_no == NOT_SAMPLE)
1103         {
1104 /*              printk("GUS: Undefined patch %d for voice %d\n", instr_no, voice);*/
1105                 return -EINVAL; /* Patch not defined */
1106         }
1107         if (sample_ptrs[sample_no] == -1)       /* Sample not loaded */
1108         {
1109 /*              printk("GUS: Sample #%d not loaded for patch %d (voice %d)\n", sample_no, instr_no, voice);*/
1110                 return -EINVAL;
1111         }
1112         sample_map[voice] = sample_no;
1113         patch_map[voice] = instr_no;
1114         return 0;
1115 }
1116
1117 static int guswave_kill_note(int dev, int voice, int note, int velocity)
1118 {
1119         unsigned long flags;
1120
1121         spin_lock_irqsave(&gus_lock,flags);
1122         /* voice_alloc->map[voice] = 0xffff; */
1123         if (voices[voice].volume_irq_mode == VMODE_START_NOTE)
1124         {
1125                 voices[voice].kill_pending = 1;
1126                 spin_unlock_irqrestore(&gus_lock,flags);
1127         }
1128         else
1129         {
1130                 spin_unlock_irqrestore(&gus_lock,flags);
1131                 gus_voice_fade(voice);
1132         }
1133
1134         return 0;
1135 }
1136
1137 static void guswave_aftertouch(int dev, int voice, int pressure)
1138 {
1139 }
1140
1141 static void guswave_panning(int dev, int voice, int value)
1142 {
1143         if (voice >= 0 || voice < 32)
1144                 voices[voice].panning = value;
1145 }
1146
1147 static void guswave_volume_method(int dev, int mode)
1148 {
1149         if (mode == VOL_METHOD_LINEAR || mode == VOL_METHOD_ADAGIO)
1150                 volume_method = mode;
1151 }
1152
1153 static void compute_volume(int voice, int volume)
1154 {
1155         if (volume < 128)
1156                 voices[voice].midi_volume = volume;
1157
1158         switch (volume_method)
1159         {
1160                 case VOL_METHOD_ADAGIO:
1161                         voices[voice].initial_volume =
1162                                 gus_adagio_vol(voices[voice].midi_volume, voices[voice].main_vol,
1163                                         voices[voice].expression_vol,
1164                                         voices[voice].patch_vol);
1165                         break;
1166
1167                 case VOL_METHOD_LINEAR: /* Totally ignores patch-volume and expression */
1168                         voices[voice].initial_volume = gus_linear_vol(volume, voices[voice].main_vol);
1169                         break;
1170
1171                 default:
1172                         voices[voice].initial_volume = volume_base +
1173                                 (voices[voice].midi_volume * volume_scale);
1174         }
1175
1176         if (voices[voice].initial_volume > 4030)
1177                 voices[voice].initial_volume = 4030;
1178 }
1179
1180 static void compute_and_set_volume(int voice, int volume, int ramp_time)
1181 {
1182         int curr, target, rate;
1183         unsigned long flags;
1184
1185         compute_volume(voice, volume);
1186         voices[voice].current_volume = voices[voice].initial_volume;
1187
1188         spin_lock_irqsave(&gus_lock,flags);
1189         /*
1190          * CAUTION! Interrupts disabled. Enable them before returning
1191          */
1192
1193         gus_select_voice(voice);
1194
1195         curr = gus_read16(0x09) >> 4;
1196         target = voices[voice].initial_volume;
1197
1198         if (ramp_time == INSTANT_RAMP)
1199         {
1200                 gus_rampoff();
1201                 gus_voice_volume(target);
1202                 spin_unlock_irqrestore(&gus_lock,flags);
1203                 return;
1204         }
1205         if (ramp_time == FAST_RAMP)
1206                 rate = 63;
1207         else
1208                 rate = 16;
1209         gus_ramp_rate(0, rate);
1210
1211         if ((target - curr) / 64 == 0)  /* Close enough to target. */
1212         {
1213                 gus_rampoff();
1214                 gus_voice_volume(target);
1215                 spin_unlock_irqrestore(&gus_lock,flags);
1216                 return;
1217         }
1218         if (target > curr)
1219         {
1220                 if (target > (4095 - 65))
1221                         target = 4095 - 65;
1222                 gus_ramp_range(curr, target);
1223                 gus_rampon(0x00);       /* Ramp up, once, no IRQ */
1224         }
1225         else
1226         {
1227                 if (target < 65)
1228                         target = 65;
1229
1230                 gus_ramp_range(target, curr);
1231                 gus_rampon(0x40);       /* Ramp down, once, no irq */
1232         }
1233         spin_unlock_irqrestore(&gus_lock,flags);
1234 }
1235
1236 static void dynamic_volume_change(int voice)
1237 {
1238         unsigned char status;
1239         unsigned long flags;
1240
1241         spin_lock_irqsave(&gus_lock,flags);
1242         gus_select_voice(voice);
1243         status = gus_read8(0x00);       /* Get voice status */
1244         spin_unlock_irqrestore(&gus_lock,flags);
1245
1246         if (status & 0x03)
1247                 return;         /* Voice was not running */
1248
1249         if (!(voices[voice].mode & WAVE_ENVELOPES))
1250         {
1251                 compute_and_set_volume(voice, voices[voice].midi_volume, 1);
1252                 return;
1253         }
1254         
1255         /*
1256          * Voice is running and has envelopes.
1257          */
1258
1259         spin_lock_irqsave(&gus_lock,flags);
1260         gus_select_voice(voice);
1261         status = gus_read8(0x0d);       /* Ramping status */
1262         spin_unlock_irqrestore(&gus_lock,flags);
1263
1264         if (status & 0x03)      /* Sustain phase? */
1265         {
1266                 compute_and_set_volume(voice, voices[voice].midi_volume, 1);
1267                 return;
1268         }
1269         if (voices[voice].env_phase < 0)
1270                 return;
1271
1272         compute_volume(voice, voices[voice].midi_volume);
1273
1274 }
1275
1276 static void guswave_controller(int dev, int voice, int ctrl_num, int value)
1277 {
1278         unsigned long   flags;
1279         unsigned long   freq;
1280
1281         if (voice < 0 || voice > 31)
1282                 return;
1283
1284         switch (ctrl_num)
1285         {
1286                 case CTRL_PITCH_BENDER:
1287                         voices[voice].bender = value;
1288
1289                         if (voices[voice].volume_irq_mode != VMODE_START_NOTE)
1290                         {
1291                                 freq = compute_finetune(voices[voice].orig_freq, value, voices[voice].bender_range, 0);
1292                                 voices[voice].current_freq = freq;
1293
1294                                 spin_lock_irqsave(&gus_lock,flags);
1295                                 gus_select_voice(voice);
1296                                 gus_voice_freq(freq);
1297                                 spin_unlock_irqrestore(&gus_lock,flags);
1298                         }
1299                         break;
1300
1301                 case CTRL_PITCH_BENDER_RANGE:
1302                         voices[voice].bender_range = value;
1303                         break;
1304                 case CTL_EXPRESSION:
1305                         value /= 128;
1306                 case CTRL_EXPRESSION:
1307                         if (volume_method == VOL_METHOD_ADAGIO)
1308                         {
1309                                 voices[voice].expression_vol = value;
1310                                 if (voices[voice].volume_irq_mode != VMODE_START_NOTE)
1311                                         dynamic_volume_change(voice);
1312                         }
1313                         break;
1314
1315                 case CTL_PAN:
1316                         voices[voice].panning = (value * 2) - 128;
1317                         break;
1318
1319                 case CTL_MAIN_VOLUME:
1320                         value = (value * 100) / 16383;
1321
1322                 case CTRL_MAIN_VOLUME:
1323                         voices[voice].main_vol = value;
1324                         if (voices[voice].volume_irq_mode != VMODE_START_NOTE)
1325                                 dynamic_volume_change(voice);
1326                         break;
1327
1328                 default:
1329                         break;
1330         }
1331 }
1332
1333 static int guswave_start_note2(int dev, int voice, int note_num, int volume)
1334 {
1335         int sample, best_sample, best_delta, delta_freq;
1336         int is16bits, samplep, patch, pan;
1337         unsigned long   note_freq, base_note, freq, flags;
1338         unsigned char   mode = 0;
1339
1340         if (voice < 0 || voice > 31)
1341         {
1342 /*              printk("GUS: Invalid voice\n");*/
1343                 return -EINVAL;
1344         }
1345         if (note_num == 255)
1346         {
1347                 if (voices[voice].mode & WAVE_ENVELOPES)
1348                 {
1349                         voices[voice].midi_volume = volume;
1350                         dynamic_volume_change(voice);
1351                         return 0;
1352                 }
1353                 compute_and_set_volume(voice, volume, 1);
1354                 return 0;
1355         }
1356         if ((patch = patch_map[voice]) == -1)
1357                 return -EINVAL;
1358         if ((samplep = patch_table[patch]) == NOT_SAMPLE)
1359         {
1360                 return -EINVAL;
1361         }
1362         note_freq = note_to_freq(note_num);
1363
1364         /*
1365          * Find a sample within a patch so that the note_freq is between low_note
1366          * and high_note.
1367          */
1368         sample = -1;
1369
1370         best_sample = samplep;
1371         best_delta = 1000000;
1372         while (samplep != 0 && samplep != NOT_SAMPLE && sample == -1)
1373         {
1374                 delta_freq = note_freq - samples[samplep].base_note;
1375                 if (delta_freq < 0)
1376                         delta_freq = -delta_freq;
1377                 if (delta_freq < best_delta)
1378                 {
1379                         best_sample = samplep;
1380                         best_delta = delta_freq;
1381                 }
1382                 if (samples[samplep].low_note <= note_freq &&
1383                         note_freq <= samples[samplep].high_note)
1384                 {
1385                         sample = samplep;
1386                 }
1387                 else
1388                         samplep = samples[samplep].key; /* Link to next sample */
1389           }
1390         if (sample == -1)
1391                 sample = best_sample;
1392
1393         if (sample == -1)
1394         {
1395 /*              printk("GUS: Patch %d not defined for note %d\n", patch, note_num);*/
1396                 return 0;       /* Should play default patch ??? */
1397         }
1398         is16bits = (samples[sample].mode & WAVE_16_BITS) ? 1 : 0;
1399         voices[voice].mode = samples[sample].mode;
1400         voices[voice].patch_vol = samples[sample].volume;
1401
1402         if (iw_mode)
1403                 gus_write8(0x15, 0x00);         /* RAM, Reset voice deactivate bit of SMSI */
1404
1405         if (voices[voice].mode & WAVE_ENVELOPES)
1406         {
1407                 int i;
1408
1409                 for (i = 0; i < 6; i++)
1410                 {
1411                         voices[voice].env_rate[i] = samples[sample].env_rate[i];
1412                         voices[voice].env_offset[i] = samples[sample].env_offset[i];
1413                 }
1414         }
1415         sample_map[voice] = sample;
1416
1417         if (voices[voice].fixed_pitch)  /* Fixed pitch */
1418         {
1419                   freq = samples[sample].base_freq;
1420         }
1421         else
1422         {
1423                 base_note = samples[sample].base_note / 100;
1424                 note_freq /= 100;
1425
1426                 freq = samples[sample].base_freq * note_freq / base_note;
1427         }
1428
1429         voices[voice].orig_freq = freq;
1430
1431         /*
1432          * Since the pitch bender may have been set before playing the note, we
1433          * have to calculate the bending now.
1434          */
1435
1436         freq = compute_finetune(voices[voice].orig_freq, voices[voice].bender,
1437                                 voices[voice].bender_range, 0);
1438         voices[voice].current_freq = freq;
1439
1440         pan = (samples[sample].panning + voices[voice].panning) / 32;
1441         pan += 7;
1442         if (pan < 0)
1443                 pan = 0;
1444         if (pan > 15)
1445                 pan = 15;
1446
1447         if (samples[sample].mode & WAVE_16_BITS)
1448         {
1449                 mode |= 0x04;   /* 16 bits */
1450                 if ((sample_ptrs[sample] / GUS_BANK_SIZE) !=
1451                         ((sample_ptrs[sample] + samples[sample].len) / GUS_BANK_SIZE))
1452                                 printk(KERN_ERR "GUS: Sample address error\n");
1453         }
1454         spin_lock_irqsave(&gus_lock,flags);
1455         gus_select_voice(voice);
1456         gus_voice_off();
1457         gus_rampoff();
1458
1459         spin_unlock_irqrestore(&gus_lock,flags);
1460
1461         if (voices[voice].mode & WAVE_ENVELOPES)
1462         {
1463                 compute_volume(voice, volume);
1464                 init_envelope(voice);
1465         }
1466         else
1467         {
1468                 compute_and_set_volume(voice, volume, 0);
1469         }
1470
1471         spin_lock_irqsave(&gus_lock,flags);
1472         gus_select_voice(voice);
1473
1474         if (samples[sample].mode & WAVE_LOOP_BACK)
1475                 gus_write_addr(0x0a, sample_ptrs[sample] + samples[sample].len -
1476                         voices[voice].offset_pending, 0, is16bits);     /* start=end */
1477         else
1478                 gus_write_addr(0x0a, sample_ptrs[sample] + voices[voice].offset_pending, 0, is16bits);  /* Sample start=begin */
1479
1480         if (samples[sample].mode & WAVE_LOOPING)
1481         {
1482                 mode |= 0x08;
1483
1484                 if (samples[sample].mode & WAVE_BIDIR_LOOP)
1485                         mode |= 0x10;
1486
1487                 if (samples[sample].mode & WAVE_LOOP_BACK)
1488                 {
1489                         gus_write_addr(0x0a, sample_ptrs[sample] + samples[sample].loop_end -
1490                                            voices[voice].offset_pending,
1491                                            (samples[sample].fractions >> 4) & 0x0f, is16bits);
1492                         mode |= 0x40;
1493                 }
1494                 gus_write_addr(0x02, sample_ptrs[sample] + samples[sample].loop_start,
1495                         samples[sample].fractions & 0x0f, is16bits);    /* Loop start location */
1496                 gus_write_addr(0x04, sample_ptrs[sample] + samples[sample].loop_end,
1497                         (samples[sample].fractions >> 4) & 0x0f, is16bits);     /* Loop end location */
1498         }
1499         else
1500         {
1501                 mode |= 0x20;   /* Loop IRQ at the end */
1502                 voices[voice].loop_irq_mode = LMODE_FINISH;     /* Ramp down at the end */
1503                 voices[voice].loop_irq_parm = 1;
1504                 gus_write_addr(0x02, sample_ptrs[sample], 0, is16bits); /* Loop start location */
1505                 gus_write_addr(0x04, sample_ptrs[sample] + samples[sample].len - 1,
1506                         (samples[sample].fractions >> 4) & 0x0f, is16bits);     /* Loop end location */
1507         }
1508         gus_voice_freq(freq);
1509         gus_voice_balance(pan);
1510         gus_voice_on(mode);
1511         spin_unlock_irqrestore(&gus_lock,flags);
1512
1513         return 0;
1514 }
1515
1516 /*
1517  * New guswave_start_note by Andrew J. Robinson attempts to minimize clicking
1518  * when the note playing on the voice is changed.  It uses volume
1519  * ramping.
1520  */
1521
1522 static int guswave_start_note(int dev, int voice, int note_num, int volume)
1523 {
1524         unsigned long flags;
1525         int mode;
1526         int ret_val = 0;
1527
1528         spin_lock_irqsave(&gus_lock,flags);
1529         if (note_num == 255)
1530         {
1531                 if (voices[voice].volume_irq_mode == VMODE_START_NOTE)
1532                 {
1533                         voices[voice].volume_pending = volume;
1534                 }
1535                 else
1536                 {
1537                         ret_val = guswave_start_note2(dev, voice, note_num, volume);
1538                 }
1539         }
1540         else
1541         {
1542                 gus_select_voice(voice);
1543                 mode = gus_read8(0x00);
1544                 if (mode & 0x20)
1545                         gus_write8(0x00, mode & 0xdf);  /* No interrupt! */
1546
1547                 voices[voice].offset_pending = 0;
1548                 voices[voice].kill_pending = 0;
1549                 voices[voice].volume_irq_mode = 0;
1550                 voices[voice].loop_irq_mode = 0;
1551
1552                 if (voices[voice].sample_pending >= 0)
1553                 {
1554                         spin_unlock_irqrestore(&gus_lock,flags);        /* Run temporarily with interrupts enabled */
1555                         guswave_set_instr(voices[voice].dev_pending, voice, voices[voice].sample_pending);
1556                         voices[voice].sample_pending = -1;
1557                         spin_lock_irqsave(&gus_lock,flags);
1558                         gus_select_voice(voice);        /* Reselect the voice (just to be sure) */
1559                 }
1560                 if ((mode & 0x01) || (int) ((gus_read16(0x09) >> 4) < (unsigned) 2065))
1561                 {
1562                         ret_val = guswave_start_note2(dev, voice, note_num, volume);
1563                 }
1564                 else
1565                 {
1566                         voices[voice].dev_pending = dev;
1567                         voices[voice].note_pending = note_num;
1568                         voices[voice].volume_pending = volume;
1569                         voices[voice].volume_irq_mode = VMODE_START_NOTE;
1570
1571                         gus_rampoff();
1572                         gus_ramp_range(2000, 4065);
1573                         gus_ramp_rate(0, 63);   /* Fastest possible rate */
1574                         gus_rampon(0x20 | 0x40);        /* Ramp down, once, irq */
1575                 }
1576         }
1577         spin_unlock_irqrestore(&gus_lock,flags);
1578         return ret_val;
1579 }
1580
1581 static void guswave_reset(int dev)
1582 {
1583         int i;
1584
1585         for (i = 0; i < 32; i++)
1586         {
1587                 gus_voice_init(i);
1588                 gus_voice_init2(i);
1589         }
1590 }
1591
1592 static int guswave_open(int dev, int mode)
1593 {
1594         int err;
1595
1596         if (gus_busy)
1597                 return -EBUSY;
1598
1599         voice_alloc->timestamp = 0;
1600
1601         if (gus_no_wave_dma) {
1602                 gus_no_dma = 1;
1603         } else {
1604                 if ((err = DMAbuf_open_dma(gus_devnum)) < 0)
1605                 {
1606                         /* printk( "GUS: Loading samples without DMA\n"); */
1607                         gus_no_dma = 1; /* Upload samples using PIO */
1608                 }
1609                 else
1610                         gus_no_dma = 0;
1611         }
1612
1613         init_waitqueue_head(&dram_sleeper);
1614         gus_busy = 1;
1615         active_device = GUS_DEV_WAVE;
1616
1617         gusintr(gus_irq, (void *)gus_hw_config, NULL);  /* Serve pending interrupts */
1618         gus_initialize();
1619         gus_reset();
1620         gusintr(gus_irq, (void *)gus_hw_config, NULL);  /* Serve pending interrupts */
1621
1622         return 0;
1623 }
1624
1625 static void guswave_close(int dev)
1626 {
1627         gus_busy = 0;
1628         active_device = 0;
1629         gus_reset();
1630
1631         if (!gus_no_dma)
1632                 DMAbuf_close_dma(gus_devnum);
1633 }
1634
1635 static int guswave_load_patch(int dev, int format, const char __user *addr,
1636                    int offs, int count, int pmgr_flag)
1637 {
1638         struct patch_info patch;
1639         int instr;
1640         long sizeof_patch;
1641
1642         unsigned long blk_sz, blk_end, left, src_offs, target;
1643
1644         sizeof_patch = (long) &patch.data[0] - (long) &patch;   /* Header size */
1645
1646         if (format != GUS_PATCH)
1647         {
1648 /*              printk("GUS Error: Invalid patch format (key) 0x%x\n", format);*/
1649                 return -EINVAL;
1650         }
1651         if (count < sizeof_patch)
1652         {
1653 /*                printk("GUS Error: Patch header too short\n");*/
1654                   return -EINVAL;
1655         }
1656         count -= sizeof_patch;
1657
1658         if (free_sample >= MAX_SAMPLE)
1659         {
1660 /*                printk("GUS: Sample table full\n");*/
1661                   return -ENOSPC;
1662         }
1663         /*
1664          * Copy the header from user space but ignore the first bytes which have
1665          * been transferred already.
1666          */
1667
1668         if (copy_from_user(&((char *) &patch)[offs], &(addr)[offs],
1669                            sizeof_patch - offs))
1670                 return -EFAULT;
1671
1672         if (patch.mode & WAVE_ROM)
1673                 return -EINVAL;
1674         if (gus_mem_size == 0)
1675                 return -ENOSPC;
1676
1677         instr = patch.instr_no;
1678
1679         if (instr < 0 || instr > MAX_PATCH)
1680         {
1681 /*              printk(KERN_ERR "GUS: Invalid patch number %d\n", instr);*/
1682                 return -EINVAL;
1683         }
1684         if (count < patch.len)
1685         {
1686 /*              printk(KERN_ERR "GUS Warning: Patch record too short (%d<%d)\n", count, (int) patch.len);*/
1687                 patch.len = count;
1688         }
1689         if (patch.len <= 0 || patch.len > gus_mem_size)
1690         {
1691 /*              printk(KERN_ERR "GUS: Invalid sample length %d\n", (int) patch.len);*/
1692                 return -EINVAL;
1693         }
1694         if (patch.mode & WAVE_LOOPING)
1695         {
1696                 if (patch.loop_start < 0 || patch.loop_start >= patch.len)
1697                 {
1698 /*                      printk(KERN_ERR "GUS: Invalid loop start\n");*/
1699                         return -EINVAL;
1700                 }
1701                 if (patch.loop_end < patch.loop_start || patch.loop_end > patch.len)
1702                 {
1703 /*                      printk(KERN_ERR "GUS: Invalid loop end\n");*/
1704                         return -EINVAL;
1705                 }
1706         }
1707         free_mem_ptr = (free_mem_ptr + 31) & ~31;       /* 32 byte alignment */
1708
1709         if (patch.mode & WAVE_16_BITS)
1710         {
1711                 /*
1712                  * 16 bit samples must fit one 256k bank.
1713                  */
1714                 if (patch.len >= GUS_BANK_SIZE)
1715                 {
1716 /*                       printk("GUS: Sample (16 bit) too long %d\n", (int) patch.len);*/
1717                         return -ENOSPC;
1718                 }
1719                 if ((free_mem_ptr / GUS_BANK_SIZE) !=
1720                         ((free_mem_ptr + patch.len) / GUS_BANK_SIZE))
1721                 {
1722                         unsigned long   tmp_mem =       
1723                                 /* Align to 256K */
1724                                         ((free_mem_ptr / GUS_BANK_SIZE) + 1) * GUS_BANK_SIZE;
1725
1726                         if ((tmp_mem + patch.len) > gus_mem_size)
1727                                 return -ENOSPC;
1728
1729                         free_mem_ptr = tmp_mem;         /* This leaves unusable memory */
1730                 }
1731         }
1732         if ((free_mem_ptr + patch.len) > gus_mem_size)
1733                 return -ENOSPC;
1734
1735         sample_ptrs[free_sample] = free_mem_ptr;
1736
1737         /*
1738          * Tremolo is not possible with envelopes
1739          */
1740
1741         if (patch.mode & WAVE_ENVELOPES)
1742                 patch.mode &= ~WAVE_TREMOLO;
1743
1744         if (!(patch.mode & WAVE_FRACTIONS))
1745         {
1746                   patch.fractions = 0;
1747         }
1748         memcpy((char *) &samples[free_sample], &patch, sizeof_patch);
1749
1750         /*
1751          * Link this_one sample to the list of samples for patch 'instr'.
1752          */
1753
1754         samples[free_sample].key = patch_table[instr];
1755         patch_table[instr] = free_sample;
1756
1757         /*
1758          * Use DMA to transfer the wave data to the DRAM
1759          */
1760
1761         left = patch.len;
1762         src_offs = 0;
1763         target = free_mem_ptr;
1764
1765         while (left)            /* Not completely transferred yet */
1766         {
1767                 blk_sz = audio_devs[gus_devnum]->dmap_out->bytes_in_use;
1768                 if (blk_sz > left)
1769                         blk_sz = left;
1770
1771                 /*
1772                  * DMA cannot cross bank (256k) boundaries. Check for that.
1773                  */
1774                  
1775                 blk_end = target + blk_sz;
1776
1777                 if ((target / GUS_BANK_SIZE) != (blk_end / GUS_BANK_SIZE))
1778                 {
1779                         /* Split the block */
1780                         blk_end &= ~(GUS_BANK_SIZE - 1);
1781                         blk_sz = blk_end - target;
1782                 }
1783                 if (gus_no_dma)
1784                 {
1785                         /*
1786                          * For some reason the DMA is not possible. We have to use PIO.
1787                          */
1788                         long i;
1789                         unsigned char data;
1790
1791                         for (i = 0; i < blk_sz; i++)
1792                         {
1793                                 get_user(*(unsigned char *) &data, (unsigned char __user *) &((addr)[sizeof_patch + i]));
1794                                 if (patch.mode & WAVE_UNSIGNED)
1795                                         if (!(patch.mode & WAVE_16_BITS) || (i & 0x01))
1796                                                 data ^= 0x80;   /* Convert to signed */
1797                                 gus_poke(target + i, data);
1798                         }
1799                 }
1800                 else
1801                 {
1802                         unsigned long address, hold_address;
1803                         unsigned char dma_command;
1804                         unsigned long flags;
1805
1806                         if (audio_devs[gus_devnum]->dmap_out->raw_buf == NULL)
1807                         {
1808                                 printk(KERN_ERR "GUS: DMA buffer == NULL\n");
1809                                 return -ENOSPC;
1810                         }
1811                         /*
1812                          * OK, move now. First in and then out.
1813                          */
1814
1815                         if (copy_from_user(audio_devs[gus_devnum]->dmap_out->raw_buf,
1816                                            &(addr)[sizeof_patch + src_offs],
1817                                            blk_sz))
1818                                 return -EFAULT;
1819
1820                         spin_lock_irqsave(&gus_lock,flags);
1821                         gus_write8(0x41, 0);    /* Disable GF1 DMA */
1822                         DMAbuf_start_dma(gus_devnum, audio_devs[gus_devnum]->dmap_out->raw_buf_phys,
1823                                 blk_sz, DMA_MODE_WRITE);
1824
1825                         /*
1826                          * Set the DRAM address for the wave data
1827                          */
1828
1829                         if (iw_mode)
1830                         {
1831                                 /* Different address translation in enhanced mode */
1832
1833                                 unsigned char   hi;
1834
1835                                 if (gus_dma > 4)
1836                                         address = target >> 1;  /* Convert to 16 bit word address */
1837                                 else
1838                                         address = target;
1839
1840                                 hi = (unsigned char) ((address >> 16) & 0xf0);
1841                                 hi += (unsigned char) (address & 0x0f);
1842
1843                                 gus_write16(0x42, (address >> 4) & 0xffff);     /* DMA address (low) */
1844                                 gus_write8(0x50, hi);
1845                         }
1846                         else
1847                         {
1848                                 address = target;
1849                                 if (audio_devs[gus_devnum]->dmap_out->dma > 3)
1850                                 {
1851                                         hold_address = address;
1852                                         address = address >> 1;
1853                                         address &= 0x0001ffffL;
1854                                         address |= (hold_address & 0x000c0000L);
1855                                 }
1856                                 gus_write16(0x42, (address >> 4) & 0xffff);     /* DRAM DMA address */
1857                         }
1858
1859                         /*
1860                          * Start the DMA transfer
1861                          */
1862
1863                         dma_command = 0x21;             /* IRQ enable, DMA start */
1864                         if (patch.mode & WAVE_UNSIGNED)
1865                                 dma_command |= 0x80;    /* Invert MSB */
1866                         if (patch.mode & WAVE_16_BITS)
1867                                 dma_command |= 0x40;    /* 16 bit _DATA_ */
1868                         if (audio_devs[gus_devnum]->dmap_out->dma > 3)
1869                                 dma_command |= 0x04;    /* 16 bit DMA _channel_ */
1870                         
1871                         /*
1872                          * Sleep here until the DRAM DMA done interrupt is served
1873                          */
1874                         active_device = GUS_DEV_WAVE;
1875                         gus_write8(0x41, dma_command);  /* Lets go luteet (=bugs) */
1876
1877                         spin_unlock_irqrestore(&gus_lock,flags); /* opens a race */
1878                         if (!interruptible_sleep_on_timeout(&dram_sleeper, HZ))
1879                                 printk("GUS: DMA Transfer timed out\n");
1880                 }
1881
1882                 /*
1883                  * Now the next part
1884                  */
1885
1886                 left -= blk_sz;
1887                 src_offs += blk_sz;
1888                 target += blk_sz;
1889
1890                 gus_write8(0x41, 0);    /* Stop DMA */
1891         }
1892
1893         free_mem_ptr += patch.len;
1894         free_sample++;
1895         return 0;
1896 }
1897
1898 static void guswave_hw_control(int dev, unsigned char *event_rec)
1899 {
1900         int voice, cmd;
1901         unsigned short p1, p2;
1902         unsigned int plong;
1903         unsigned long flags;
1904
1905         cmd = event_rec[2];
1906         voice = event_rec[3];
1907         p1 = *(unsigned short *) &event_rec[4];
1908         p2 = *(unsigned short *) &event_rec[6];
1909         plong = *(unsigned int *) &event_rec[4];
1910
1911         if ((voices[voice].volume_irq_mode == VMODE_START_NOTE) &&
1912                 (cmd != _GUS_VOICESAMPLE) && (cmd != _GUS_VOICE_POS))
1913                 do_volume_irq(voice);
1914
1915         switch (cmd)
1916         {
1917                 case _GUS_NUMVOICES:
1918                         spin_lock_irqsave(&gus_lock,flags);
1919                         gus_select_voice(voice);
1920                         gus_select_max_voices(p1);
1921                         spin_unlock_irqrestore(&gus_lock,flags);
1922                         break;
1923
1924                 case _GUS_VOICESAMPLE:
1925                         guswave_set_instr(dev, voice, p1);
1926                         break;
1927
1928                 case _GUS_VOICEON:
1929                         spin_lock_irqsave(&gus_lock,flags);
1930                         gus_select_voice(voice);
1931                         p1 &= ~0x20;    /* Don't allow interrupts */
1932                         gus_voice_on(p1);
1933                         spin_unlock_irqrestore(&gus_lock,flags);
1934                         break;
1935
1936                 case _GUS_VOICEOFF:
1937                         spin_lock_irqsave(&gus_lock,flags);
1938                         gus_select_voice(voice);
1939                         gus_voice_off();
1940                         spin_unlock_irqrestore(&gus_lock,flags);
1941                         break;
1942
1943                 case _GUS_VOICEFADE:
1944                         gus_voice_fade(voice);
1945                         break;
1946
1947                 case _GUS_VOICEMODE:
1948                         spin_lock_irqsave(&gus_lock,flags);
1949                         gus_select_voice(voice);
1950                         p1 &= ~0x20;    /* Don't allow interrupts */
1951                         gus_voice_mode(p1);
1952                         spin_unlock_irqrestore(&gus_lock,flags);
1953                         break;
1954
1955                 case _GUS_VOICEBALA:
1956                         spin_lock_irqsave(&gus_lock,flags);
1957                         gus_select_voice(voice);
1958                         gus_voice_balance(p1);
1959                         spin_unlock_irqrestore(&gus_lock,flags);
1960                         break;
1961
1962                 case _GUS_VOICEFREQ:
1963                         spin_lock_irqsave(&gus_lock,flags);
1964                         gus_select_voice(voice);
1965                         gus_voice_freq(plong);
1966                         spin_unlock_irqrestore(&gus_lock,flags);
1967                         break;
1968
1969                 case _GUS_VOICEVOL:
1970                         spin_lock_irqsave(&gus_lock,flags);
1971                         gus_select_voice(voice);
1972                         gus_voice_volume(p1);
1973                         spin_unlock_irqrestore(&gus_lock,flags);
1974                         break;
1975
1976                 case _GUS_VOICEVOL2:    /* Just update the software voice level */
1977                         voices[voice].initial_volume = voices[voice].current_volume = p1;
1978                         break;
1979
1980                 case _GUS_RAMPRANGE:
1981                         if (voices[voice].mode & WAVE_ENVELOPES)
1982                                 break;  /* NO-NO */
1983                         spin_lock_irqsave(&gus_lock,flags);
1984                         gus_select_voice(voice);
1985                         gus_ramp_range(p1, p2);
1986                         spin_unlock_irqrestore(&gus_lock,flags);
1987                         break;
1988
1989                 case _GUS_RAMPRATE:
1990                         if (voices[voice].mode & WAVE_ENVELOPES)
1991                                 break;  /* NJET-NJET */
1992                         spin_lock_irqsave(&gus_lock,flags);
1993                         gus_select_voice(voice);
1994                         gus_ramp_rate(p1, p2);
1995                         spin_unlock_irqrestore(&gus_lock,flags);
1996                         break;
1997
1998                 case _GUS_RAMPMODE:
1999                         if (voices[voice].mode & WAVE_ENVELOPES)
2000                                 break;  /* NO-NO */
2001                         spin_lock_irqsave(&gus_lock,flags);
2002                         gus_select_voice(voice);
2003                         p1 &= ~0x20;    /* Don't allow interrupts */
2004                         gus_ramp_mode(p1);
2005                         spin_unlock_irqrestore(&gus_lock,flags);
2006                         break;
2007
2008                 case _GUS_RAMPON:
2009                         if (voices[voice].mode & WAVE_ENVELOPES)
2010                                 break;  /* EI-EI */
2011                         spin_lock_irqsave(&gus_lock,flags);
2012                         gus_select_voice(voice);
2013                         p1 &= ~0x20;    /* Don't allow interrupts */
2014                         gus_rampon(p1);
2015                         spin_unlock_irqrestore(&gus_lock,flags);
2016                         break;
2017
2018                 case _GUS_RAMPOFF:
2019                         if (voices[voice].mode & WAVE_ENVELOPES)
2020                                 break;  /* NEJ-NEJ */
2021                         spin_lock_irqsave(&gus_lock,flags);
2022                         gus_select_voice(voice);
2023                         gus_rampoff();
2024                         spin_unlock_irqrestore(&gus_lock,flags);
2025                         break;
2026
2027                 case _GUS_VOLUME_SCALE:
2028                         volume_base = p1;
2029                         volume_scale = p2;
2030                         break;
2031
2032                 case _GUS_VOICE_POS:
2033                         spin_lock_irqsave(&gus_lock,flags);
2034                         gus_select_voice(voice);
2035                         gus_set_voice_pos(voice, plong);
2036                         spin_unlock_irqrestore(&gus_lock,flags);
2037                         break;
2038
2039                 default:
2040                         break;
2041         }
2042 }
2043
2044 static int gus_audio_set_speed(int speed)
2045 {
2046         if (speed <= 0)
2047                 speed = gus_audio_speed;
2048
2049         if (speed < 4000)
2050                 speed = 4000;
2051
2052         if (speed > 44100)
2053                 speed = 44100;
2054
2055         gus_audio_speed = speed;
2056
2057         if (only_read_access)
2058         {
2059                 /* Compute nearest valid recording speed  and return it */
2060
2061                 /* speed = (9878400 / (gus_audio_speed + 2)) / 16; */
2062                 speed = (((9878400 + gus_audio_speed / 2) / (gus_audio_speed + 2)) + 8) / 16;
2063                 speed = (9878400 / (speed * 16)) - 2;
2064         }
2065         return speed;
2066 }
2067
2068 static int gus_audio_set_channels(int channels)
2069 {
2070         if (!channels)
2071                 return gus_audio_channels;
2072         if (channels > 2)
2073                 channels = 2;
2074         if (channels < 1)
2075                 channels = 1;
2076         gus_audio_channels = channels;
2077         return channels;
2078 }
2079
2080 static int gus_audio_set_bits(int bits)
2081 {
2082         if (!bits)
2083                 return gus_audio_bits;
2084
2085         if (bits != 8 && bits != 16)
2086                 bits = 8;
2087
2088         if (only_8_bits)
2089                 bits = 8;
2090
2091         gus_audio_bits = bits;
2092         return bits;
2093 }
2094
2095 static int gus_audio_ioctl(int dev, unsigned int cmd, void __user *arg)
2096 {
2097         int val;
2098
2099         switch (cmd) 
2100         {
2101                 case SOUND_PCM_WRITE_RATE:
2102                         if (get_user(val, (int __user*)arg))
2103                                 return -EFAULT;
2104                         val = gus_audio_set_speed(val);
2105                         break;
2106
2107                 case SOUND_PCM_READ_RATE:
2108                         val = gus_audio_speed;
2109                         break;
2110
2111                 case SNDCTL_DSP_STEREO:
2112                         if (get_user(val, (int __user *)arg))
2113                                 return -EFAULT;
2114                         val = gus_audio_set_channels(val + 1) - 1;
2115                         break;
2116
2117                 case SOUND_PCM_WRITE_CHANNELS:
2118                         if (get_user(val, (int __user *)arg))
2119                                 return -EFAULT;
2120                         val = gus_audio_set_channels(val);
2121                         break;
2122
2123                 case SOUND_PCM_READ_CHANNELS:
2124                         val = gus_audio_channels;
2125                         break;
2126                 
2127                 case SNDCTL_DSP_SETFMT:
2128                         if (get_user(val, (int __user *)arg))
2129                                 return -EFAULT;
2130                         val = gus_audio_set_bits(val);
2131                         break;
2132                 
2133                 case SOUND_PCM_READ_BITS:
2134                         val = gus_audio_bits;
2135                         break;
2136                 
2137                 case SOUND_PCM_WRITE_FILTER:            /* NOT POSSIBLE */
2138                 case SOUND_PCM_READ_FILTER:
2139                         val = -EINVAL;
2140                         break;
2141                 default:
2142                         return -EINVAL;
2143         }
2144         return put_user(val, (int __user *)arg);
2145 }
2146
2147 static void gus_audio_reset(int dev)
2148 {
2149         if (recording_active)
2150         {
2151                 gus_write8(0x49, 0x00); /* Halt recording */
2152                 set_input_volumes();
2153         }
2154 }
2155
2156 static int saved_iw_mode;       /* A hack hack hack */
2157
2158 static int gus_audio_open(int dev, int mode)
2159 {
2160         if (gus_busy)
2161                 return -EBUSY;
2162
2163         if (gus_pnp_flag && mode & OPEN_READ)
2164         {
2165 /*              printk(KERN_ERR "GUS: Audio device #%d is playback only.\n", dev);*/
2166                 return -EIO;
2167         }
2168         gus_initialize();
2169
2170         gus_busy = 1;
2171         active_device = 0;
2172
2173         saved_iw_mode = iw_mode;
2174         if (iw_mode)
2175         {
2176                 /* There are some problems with audio in enhanced mode so disable it */
2177                 gus_write8(0x19, gus_read8(0x19) & ~0x01);      /* Disable enhanced mode */
2178                 iw_mode = 0;
2179         }
2180
2181         gus_reset();
2182         reset_sample_memory();
2183         gus_select_max_voices(14);
2184
2185         pcm_active = 0;
2186         dma_active = 0;
2187         pcm_opened = 1;
2188         if (mode & OPEN_READ)
2189         {
2190                 recording_active = 1;
2191                 set_input_volumes();
2192         }
2193         only_read_access = !(mode & OPEN_WRITE);
2194         only_8_bits = mode & OPEN_READ;
2195         if (only_8_bits)
2196                 audio_devs[dev]->format_mask = AFMT_U8;
2197         else
2198                 audio_devs[dev]->format_mask = AFMT_U8 | AFMT_S16_LE;
2199
2200         return 0;
2201 }
2202
2203 static void gus_audio_close(int dev)
2204 {
2205         iw_mode = saved_iw_mode;
2206         gus_reset();
2207         gus_busy = 0;
2208         pcm_opened = 0;
2209         active_device = 0;
2210
2211         if (recording_active)
2212         {
2213                 gus_write8(0x49, 0x00); /* Halt recording */
2214                 set_input_volumes();
2215         }
2216         recording_active = 0;
2217 }
2218
2219 static void gus_audio_update_volume(void)
2220 {
2221         unsigned long flags;
2222         int voice;
2223
2224         if (pcm_active && pcm_opened)
2225                 for (voice = 0; voice < gus_audio_channels; voice++)
2226                 {
2227                         spin_lock_irqsave(&gus_lock,flags);
2228                         gus_select_voice(voice);
2229                         gus_rampoff();
2230                         gus_voice_volume(1530 + (25 * gus_pcm_volume));
2231                         gus_ramp_range(65, 1530 + (25 * gus_pcm_volume));
2232                         spin_unlock_irqrestore(&gus_lock,flags);
2233                 }
2234 }
2235
2236 static void play_next_pcm_block(void)
2237 {
2238         unsigned long flags;
2239         int speed = gus_audio_speed;
2240         int this_one, is16bits, chn;
2241         unsigned long dram_loc;
2242         unsigned char mode[2], ramp_mode[2];
2243
2244         if (!pcm_qlen)
2245                 return;
2246
2247         this_one = pcm_head;
2248
2249         for (chn = 0; chn < gus_audio_channels; chn++)
2250         {
2251                 mode[chn] = 0x00;
2252                 ramp_mode[chn] = 0x03;  /* Ramping and rollover off */
2253
2254                 if (chn == 0)
2255                 {
2256                         mode[chn] |= 0x20;      /* Loop IRQ */
2257                         voices[chn].loop_irq_mode = LMODE_PCM;
2258                 }
2259                 if (gus_audio_bits != 8)
2260                 {
2261                         is16bits = 1;
2262                         mode[chn] |= 0x04;      /* 16 bit data */
2263                 }
2264                 else
2265                         is16bits = 0;
2266
2267                 dram_loc = this_one * pcm_bsize;
2268                 dram_loc += chn * pcm_banksize;
2269
2270                 if (this_one == (pcm_nblk - 1)) /* Last fragment of the DRAM buffer */
2271                 {
2272                         mode[chn] |= 0x08;      /* Enable loop */
2273                         ramp_mode[chn] = 0x03;  /* Disable rollover bit */
2274                 }
2275                 else
2276                 {
2277                         if (chn == 0)
2278                                 ramp_mode[chn] = 0x04;  /* Enable rollover bit */
2279                 }
2280                 spin_lock_irqsave(&gus_lock,flags);
2281                 gus_select_voice(chn);
2282                 gus_voice_freq(speed);
2283
2284                 if (gus_audio_channels == 1)
2285                         gus_voice_balance(7);           /* mono */
2286                 else if (chn == 0)
2287                         gus_voice_balance(0);           /* left */
2288                 else
2289                         gus_voice_balance(15);          /* right */
2290
2291                 if (!pcm_active)        /* Playback not already active */
2292                 {
2293                         /*
2294                          * The playback was not started yet (or there has been a pause).
2295                          * Start the voice (again) and ask for a rollover irq at the end of
2296                          * this_one block. If this_one one is last of the buffers, use just
2297                          * the normal loop with irq.
2298                          */
2299
2300                         gus_voice_off();
2301                         gus_rampoff();
2302                         gus_voice_volume(1530 + (25 * gus_pcm_volume));
2303                         gus_ramp_range(65, 1530 + (25 * gus_pcm_volume));
2304
2305                         gus_write_addr(0x0a, chn * pcm_banksize, 0, is16bits);  /* Starting position */
2306                         gus_write_addr(0x02, chn * pcm_banksize, 0, is16bits);  /* Loop start */
2307
2308                         if (chn != 0)
2309                                 gus_write_addr(0x04, pcm_banksize + (pcm_bsize * pcm_nblk) - 1,
2310                                                    0, is16bits);        /* Loop end location */
2311                 }
2312                 if (chn == 0)
2313                         gus_write_addr(0x04, dram_loc + pcm_bsize - 1,
2314                                          0, is16bits);  /* Loop end location */
2315                 else
2316                         mode[chn] |= 0x08;      /* Enable looping */
2317                 spin_unlock_irqrestore(&gus_lock,flags);
2318         }
2319         for (chn = 0; chn < gus_audio_channels; chn++)
2320         {
2321                 spin_lock_irqsave(&gus_lock,flags);
2322                 gus_select_voice(chn);
2323                 gus_write8(0x0d, ramp_mode[chn]);
2324                 if (iw_mode)
2325                         gus_write8(0x15, 0x00); /* Reset voice deactivate bit of SMSI */
2326                 gus_voice_on(mode[chn]);
2327                 spin_unlock_irqrestore(&gus_lock,flags);
2328         }
2329         pcm_active = 1;
2330 }
2331
2332 static void gus_transfer_output_block(int dev, unsigned long buf,
2333                           int total_count, int intrflag, int chn)
2334 {
2335         /*
2336          * This routine transfers one block of audio data to the DRAM. In mono mode
2337          * it's called just once. When in stereo mode, this_one routine is called
2338          * once for both channels.
2339          *
2340          * The left/mono channel data is transferred to the beginning of dram and the
2341          * right data to the area pointed by gus_page_size.
2342          */
2343
2344         int this_one, count;
2345         unsigned long flags;
2346         unsigned char dma_command;
2347         unsigned long address, hold_address;
2348
2349         spin_lock_irqsave(&gus_lock,flags);
2350
2351         count = total_count / gus_audio_channels;
2352
2353         if (chn == 0)
2354         {
2355                 if (pcm_qlen >= pcm_nblk)
2356                         printk(KERN_WARNING "GUS Warning: PCM buffers out of sync\n");
2357
2358                 this_one = pcm_current_block = pcm_tail;
2359                 pcm_qlen++;
2360                 pcm_tail = (pcm_tail + 1) % pcm_nblk;
2361                 pcm_datasize[this_one] = count;
2362         }
2363         else
2364                 this_one = pcm_current_block;
2365
2366         gus_write8(0x41, 0);    /* Disable GF1 DMA */
2367         DMAbuf_start_dma(dev, buf + (chn * count), count, DMA_MODE_WRITE);
2368
2369         address = this_one * pcm_bsize;
2370         address += chn * pcm_banksize;
2371
2372         if (audio_devs[dev]->dmap_out->dma > 3)
2373         {
2374                 hold_address = address;
2375                 address = address >> 1;
2376                 address &= 0x0001ffffL;
2377                 address |= (hold_address & 0x000c0000L);
2378         }
2379         gus_write16(0x42, (address >> 4) & 0xffff);     /* DRAM DMA address */
2380
2381         dma_command = 0x21;     /* IRQ enable, DMA start */
2382
2383         if (gus_audio_bits != 8)
2384                 dma_command |= 0x40;    /* 16 bit _DATA_ */
2385         else
2386                 dma_command |= 0x80;    /* Invert MSB */
2387
2388         if (audio_devs[dev]->dmap_out->dma > 3)
2389                 dma_command |= 0x04;    /* 16 bit DMA channel */
2390
2391         gus_write8(0x41, dma_command);  /* Kick start */
2392
2393         if (chn == (gus_audio_channels - 1))    /* Last channel */
2394         {
2395                 /*
2396                  * Last (right or mono) channel data
2397                  */
2398                 dma_active = 1; /* DMA started. There is a unacknowledged buffer */
2399                 active_device = GUS_DEV_PCM_DONE;
2400                 if (!pcm_active && (pcm_qlen > 1 || count < pcm_bsize))
2401                 {
2402                         play_next_pcm_block();
2403                 }
2404         }
2405         else
2406         {
2407                 /*
2408                  * Left channel data. The right channel
2409                  * is transferred after DMA interrupt
2410                  */
2411                 active_device = GUS_DEV_PCM_CONTINUE;
2412         }
2413
2414         spin_unlock_irqrestore(&gus_lock,flags);
2415 }
2416
2417 static void gus_uninterleave8(char *buf, int l)
2418 {
2419 /* This routine uninterleaves 8 bit stereo output (LRLRLR->LLLRRR) */
2420         int i, p = 0, halfsize = l / 2;
2421         char *buf2 = buf + halfsize, *src = bounce_buf;
2422
2423         memcpy(bounce_buf, buf, l);
2424
2425         for (i = 0; i < halfsize; i++)
2426         {
2427                 buf[i] = src[p++];      /* Left channel */
2428                 buf2[i] = src[p++];     /* Right channel */
2429         }
2430 }
2431
2432 static void gus_uninterleave16(short *buf, int l)
2433 {
2434 /* This routine uninterleaves 16 bit stereo output (LRLRLR->LLLRRR) */
2435         int i, p = 0, halfsize = l / 2;
2436         short *buf2 = buf + halfsize, *src = (short *) bounce_buf;
2437
2438         memcpy(bounce_buf, (char *) buf, l * 2);
2439
2440         for (i = 0; i < halfsize; i++)
2441         {
2442                 buf[i] = src[p++];      /* Left channel */
2443                 buf2[i] = src[p++];     /* Right channel */
2444         }
2445 }
2446
2447 static void gus_audio_output_block(int dev, unsigned long buf, int total_count,
2448                        int intrflag)
2449 {
2450         struct dma_buffparms *dmap = audio_devs[dev]->dmap_out;
2451
2452         dmap->flags |= DMA_NODMA | DMA_NOTIMEOUT;
2453
2454         pcm_current_buf = buf;
2455         pcm_current_count = total_count;
2456         pcm_current_intrflag = intrflag;
2457         pcm_current_dev = dev;
2458         if (gus_audio_channels == 2)
2459         {
2460                 char *b = dmap->raw_buf + (buf - dmap->raw_buf_phys);
2461
2462                 if (gus_audio_bits == 8)
2463                         gus_uninterleave8(b, total_count);
2464                 else
2465                         gus_uninterleave16((short *) b, total_count / 2);
2466         }
2467         gus_transfer_output_block(dev, buf, total_count, intrflag, 0);
2468 }
2469
2470 static void gus_audio_start_input(int dev, unsigned long buf, int count,
2471                       int intrflag)
2472 {
2473         unsigned long flags;
2474         unsigned char mode;
2475
2476         spin_lock_irqsave(&gus_lock,flags);
2477
2478         DMAbuf_start_dma(dev, buf, count, DMA_MODE_READ);
2479         mode = 0xa0;            /* DMA IRQ enabled, invert MSB */
2480
2481         if (audio_devs[dev]->dmap_in->dma > 3)
2482                 mode |= 0x04;   /* 16 bit DMA channel */
2483         if (gus_audio_channels > 1)
2484                 mode |= 0x02;   /* Stereo */
2485         mode |= 0x01;           /* DMA enable */
2486
2487         gus_write8(0x49, mode);
2488         spin_unlock_irqrestore(&gus_lock,flags);
2489 }
2490
2491 static int gus_audio_prepare_for_input(int dev, int bsize, int bcount)
2492 {
2493         unsigned int rate;
2494
2495         gus_audio_bsize = bsize;
2496         audio_devs[dev]->dmap_in->flags |= DMA_NODMA;
2497         rate = (((9878400 + gus_audio_speed / 2) / (gus_audio_speed + 2)) + 8) / 16;
2498
2499         gus_write8(0x48, rate & 0xff);  /* Set sampling rate */
2500
2501         if (gus_audio_bits != 8)
2502         {
2503 /*              printk("GUS Error: 16 bit recording not supported\n");*/
2504                 return -EINVAL;
2505         }
2506         return 0;
2507 }
2508
2509 static int gus_audio_prepare_for_output(int dev, int bsize, int bcount)
2510 {
2511         int i;
2512
2513         long mem_ptr, mem_size;
2514
2515         audio_devs[dev]->dmap_out->flags |= DMA_NODMA | DMA_NOTIMEOUT;
2516         mem_ptr = 0;
2517         mem_size = gus_mem_size / gus_audio_channels;
2518
2519         if (mem_size > (256 * 1024))
2520                 mem_size = 256 * 1024;
2521
2522         pcm_bsize = bsize / gus_audio_channels;
2523         pcm_head = pcm_tail = pcm_qlen = 0;
2524
2525         pcm_nblk = 2;           /* MAX_PCM_BUFFERS; */
2526         if ((pcm_bsize * pcm_nblk) > mem_size)
2527                 pcm_nblk = mem_size / pcm_bsize;
2528
2529         for (i = 0; i < pcm_nblk; i++)
2530                 pcm_datasize[i] = 0;
2531
2532         pcm_banksize = pcm_nblk * pcm_bsize;
2533
2534         if (gus_audio_bits != 8 && pcm_banksize == (256 * 1024))
2535                 pcm_nblk--;
2536         gus_write8(0x41, 0);    /* Disable GF1 DMA */
2537         return 0;
2538 }
2539
2540 static int gus_local_qlen(int dev)
2541 {
2542         return pcm_qlen;
2543 }
2544
2545
2546 static struct audio_driver gus_audio_driver =
2547 {
2548         .owner                  = THIS_MODULE,
2549         .open                   = gus_audio_open,
2550         .close                  = gus_audio_close,
2551         .output_block           = gus_audio_output_block,
2552         .start_input            = gus_audio_start_input,
2553         .ioctl                  = gus_audio_ioctl,
2554         .prepare_for_input      = gus_audio_prepare_for_input,
2555         .prepare_for_output     = gus_audio_prepare_for_output,
2556         .halt_io                = gus_audio_reset,
2557         .local_qlen             = gus_local_qlen,
2558 };
2559
2560 static void guswave_setup_voice(int dev, int voice, int chn)
2561 {
2562         struct channel_info *info = &synth_devs[dev]->chn_info[chn];
2563
2564         guswave_set_instr(dev, voice, info->pgm_num);
2565         voices[voice].expression_vol = info->controllers[CTL_EXPRESSION];       /* Just MSB */
2566         voices[voice].main_vol = (info->controllers[CTL_MAIN_VOLUME] * 100) / (unsigned) 128;
2567         voices[voice].panning = (info->controllers[CTL_PAN] * 2) - 128;
2568         voices[voice].bender = 0;
2569         voices[voice].bender_range = info->bender_range;
2570
2571         if (chn == 9)
2572                 voices[voice].fixed_pitch = 1;
2573 }
2574
2575 static void guswave_bender(int dev, int voice, int value)
2576 {
2577         int freq;
2578         unsigned long   flags;
2579
2580         voices[voice].bender = value - 8192;
2581         freq = compute_finetune(voices[voice].orig_freq, value - 8192, voices[voice].bender_range, 0);
2582         voices[voice].current_freq = freq;
2583
2584         spin_lock_irqsave(&gus_lock,flags);
2585         gus_select_voice(voice);
2586         gus_voice_freq(freq);
2587         spin_unlock_irqrestore(&gus_lock,flags);
2588 }
2589
2590 static int guswave_alloc(int dev, int chn, int note, struct voice_alloc_info *alloc)
2591 {
2592         int i, p, best = -1, best_time = 0x7fffffff;
2593
2594         p = alloc->ptr;
2595         /*
2596          * First look for a completely stopped voice
2597          */
2598
2599         for (i = 0; i < alloc->max_voice; i++)
2600         {
2601                 if (alloc->map[p] == 0)
2602                 {
2603                         alloc->ptr = p;
2604                         return p;
2605                 }
2606                 if (alloc->alloc_times[p] < best_time)
2607                 {
2608                         best = p;
2609                         best_time = alloc->alloc_times[p];
2610                 }
2611                 p = (p + 1) % alloc->max_voice;
2612         }
2613
2614         /*
2615          * Then look for a releasing voice
2616          */
2617
2618         for (i = 0; i < alloc->max_voice; i++)
2619         {
2620                 if (alloc->map[p] == 0xffff)
2621                 {
2622                         alloc->ptr = p;
2623                         return p;
2624                 }
2625                 p = (p + 1) % alloc->max_voice;
2626         }
2627         if (best >= 0)
2628                 p = best;
2629
2630         alloc->ptr = p;
2631         return p;
2632 }
2633
2634 static struct synth_operations guswave_operations =
2635 {
2636         .owner          = THIS_MODULE,
2637         .id             = "GUS",
2638         .info           = &gus_info,
2639         .midi_dev       = 0,
2640         .synth_type     = SYNTH_TYPE_SAMPLE,
2641         .synth_subtype  = SAMPLE_TYPE_GUS,
2642         .open           = guswave_open,
2643         .close          = guswave_close,
2644         .ioctl          = guswave_ioctl,
2645         .kill_note      = guswave_kill_note,
2646         .start_note     = guswave_start_note,
2647         .set_instr      = guswave_set_instr,
2648         .reset          = guswave_reset,
2649         .hw_control     = guswave_hw_control,
2650         .load_patch     = guswave_load_patch,
2651         .aftertouch     = guswave_aftertouch,
2652         .controller     = guswave_controller,
2653         .panning        = guswave_panning,
2654         .volume_method  = guswave_volume_method,
2655         .bender         = guswave_bender,
2656         .alloc_voice    = guswave_alloc,
2657         .setup_voice    = guswave_setup_voice
2658 };
2659
2660 static void set_input_volumes(void)
2661 {
2662         unsigned long flags;
2663         unsigned char mask = 0xff & ~0x06;      /* Just line out enabled */
2664
2665         if (have_gus_max)       /* Don't disturb GUS MAX */
2666                 return;
2667
2668         spin_lock_irqsave(&gus_lock,flags);
2669
2670         /*
2671          *    Enable channels having vol > 10%
2672          *      Note! bit 0x01 means the line in DISABLED while 0x04 means
2673          *            the mic in ENABLED.
2674          */
2675         if (gus_line_vol > 10)
2676                 mask &= ~0x01;
2677         if (gus_mic_vol > 10)
2678                 mask |= 0x04;
2679
2680         if (recording_active)
2681         {
2682                 /*
2683                  *    Disable channel, if not selected for recording
2684                  */
2685                 if (!(gus_recmask & SOUND_MASK_LINE))
2686                         mask |= 0x01;
2687                 if (!(gus_recmask & SOUND_MASK_MIC))
2688                         mask &= ~0x04;
2689         }
2690         mix_image &= ~0x07;
2691         mix_image |= mask & 0x07;
2692         outb((mix_image), u_Mixer);
2693
2694         spin_unlock_irqrestore(&gus_lock,flags);
2695 }
2696
2697 #define MIX_DEVS        (SOUND_MASK_MIC|SOUND_MASK_LINE| \
2698                          SOUND_MASK_SYNTH|SOUND_MASK_PCM)
2699
2700 int gus_default_mixer_ioctl(int dev, unsigned int cmd, void __user *arg)
2701 {
2702         int vol, val;
2703
2704         if (((cmd >> 8) & 0xff) != 'M')
2705                 return -EINVAL;
2706
2707         if (!access_ok(VERIFY_WRITE, arg, sizeof(int)))
2708                 return -EFAULT;
2709
2710         if (_SIOC_DIR(cmd) & _SIOC_WRITE) 
2711         {
2712                 if (__get_user(val, (int __user *) arg))
2713                         return -EFAULT;
2714
2715                 switch (cmd & 0xff) 
2716                 {
2717                         case SOUND_MIXER_RECSRC:
2718                                 gus_recmask = val & MIX_DEVS;
2719                                 if (!(gus_recmask & (SOUND_MASK_MIC | SOUND_MASK_LINE)))
2720                                         gus_recmask = SOUND_MASK_MIC;
2721                                 /* Note! Input volumes are updated during next open for recording */
2722                                 val = gus_recmask;
2723                                 break;
2724
2725                         case SOUND_MIXER_MIC:
2726                                 vol = val & 0xff;
2727                                 if (vol < 0)
2728                                         vol = 0;
2729                                 if (vol > 100)
2730                                         vol = 100;
2731                                 gus_mic_vol = vol;
2732                                 set_input_volumes();
2733                                 val = vol | (vol << 8);
2734                                 break;
2735                                 
2736                         case SOUND_MIXER_LINE:
2737                                 vol = val & 0xff;
2738                                 if (vol < 0)
2739                                         vol = 0;
2740                                 if (vol > 100)
2741                                         vol = 100;
2742                                 gus_line_vol = vol;
2743                                 set_input_volumes();
2744                                 val = vol | (vol << 8);
2745                                 break;
2746
2747                         case SOUND_MIXER_PCM:
2748                                 gus_pcm_volume = val & 0xff;
2749                                 if (gus_pcm_volume < 0)
2750                                         gus_pcm_volume = 0;
2751                                 if (gus_pcm_volume > 100)
2752                                         gus_pcm_volume = 100;
2753                                 gus_audio_update_volume();
2754                                 val = gus_pcm_volume | (gus_pcm_volume << 8);
2755                                 break;
2756
2757                         case SOUND_MIXER_SYNTH:
2758                                 gus_wave_volume = val & 0xff;
2759                                 if (gus_wave_volume < 0)
2760                                         gus_wave_volume = 0;
2761                                 if (gus_wave_volume > 100)
2762                                         gus_wave_volume = 100;
2763                                 if (active_device == GUS_DEV_WAVE) 
2764                                 {
2765                                         int voice;
2766                                         for (voice = 0; voice < nr_voices; voice++)
2767                                         dynamic_volume_change(voice);   /* Apply the new vol */
2768                                 }
2769                                 val = gus_wave_volume | (gus_wave_volume << 8);
2770                                 break;
2771
2772                         default:
2773                                 return -EINVAL;
2774                 }
2775         }
2776         else
2777         {
2778                 switch (cmd & 0xff) 
2779                 {
2780                         /*
2781                          * Return parameters
2782                          */
2783                         case SOUND_MIXER_RECSRC:
2784                                 val = gus_recmask;
2785                                 break;
2786                                         
2787                         case SOUND_MIXER_DEVMASK:
2788                                 val = MIX_DEVS;
2789                                 break;
2790
2791                         case SOUND_MIXER_STEREODEVS:
2792                                 val = 0;
2793                                 break;
2794
2795                         case SOUND_MIXER_RECMASK:
2796                                 val = SOUND_MASK_MIC | SOUND_MASK_LINE;
2797                                 break;
2798
2799                         case SOUND_MIXER_CAPS:
2800                                 val = 0;
2801                                 break;
2802
2803                         case SOUND_MIXER_MIC:
2804                                 val = gus_mic_vol | (gus_mic_vol << 8);
2805                                 break;
2806
2807                         case SOUND_MIXER_LINE:
2808                                 val = gus_line_vol | (gus_line_vol << 8);
2809                                 break;
2810
2811                         case SOUND_MIXER_PCM:
2812                                 val = gus_pcm_volume | (gus_pcm_volume << 8);
2813                                 break;
2814
2815                         case SOUND_MIXER_SYNTH:
2816                                 val = gus_wave_volume | (gus_wave_volume << 8);
2817                                 break;
2818
2819                         default:
2820                                 return -EINVAL;
2821                 }
2822         }
2823         return __put_user(val, (int __user *)arg);
2824 }
2825
2826 static struct mixer_operations gus_mixer_operations =
2827 {
2828         .owner  = THIS_MODULE,
2829         .id     = "GUS",
2830         .name   = "Gravis Ultrasound",
2831         .ioctl  = gus_default_mixer_ioctl
2832 };
2833
2834 static int __init gus_default_mixer_init(void)
2835 {
2836         int n;
2837
2838         if ((n = sound_alloc_mixerdev()) != -1)
2839         {       
2840                 /*
2841                  * Don't install if there is another
2842                  * mixer
2843                  */
2844                 mixer_devs[n] = &gus_mixer_operations;
2845         }
2846         if (have_gus_max)
2847         {
2848                 /*
2849                  *  Enable all mixer channels on the GF1 side. Otherwise recording will
2850                  *  not be possible using GUS MAX.
2851                  */
2852                 mix_image &= ~0x07;
2853                 mix_image |= 0x04;      /* All channels enabled */
2854                 outb((mix_image), u_Mixer);
2855         }
2856         return n;
2857 }
2858
2859 void __init gus_wave_init(struct address_info *hw_config)
2860 {
2861         unsigned long flags;
2862         unsigned char val;
2863         char *model_num = "2.4";
2864         char tmp[64];
2865         int gus_type = 0x24;    /* 2.4 */
2866
2867         int irq = hw_config->irq, dma = hw_config->dma, dma2 = hw_config->dma2;
2868         int sdev;
2869
2870         hw_config->slots[0] = -1;       /* No wave */
2871         hw_config->slots[1] = -1;       /* No ad1848 */
2872         hw_config->slots[4] = -1;       /* No audio */
2873         hw_config->slots[5] = -1;       /* No mixer */
2874
2875         if (!gus_pnp_flag)
2876         {
2877                 if (irq < 0 || irq > 15)
2878                 {
2879                         printk(KERN_ERR "ERROR! Invalid IRQ#%d. GUS Disabled", irq);
2880                         return;
2881                 }
2882         }
2883         
2884         if (dma < 0 || dma > 7 || dma == 4)
2885         {
2886                 printk(KERN_ERR "ERROR! Invalid DMA#%d. GUS Disabled", dma);
2887                 return;
2888         }
2889         gus_irq = irq;
2890         gus_dma = dma;
2891         gus_dma2 = dma2;
2892         gus_hw_config = hw_config;
2893
2894         if (gus_dma2 == -1)
2895                 gus_dma2 = dma;
2896
2897         /*
2898          * Try to identify the GUS model.
2899          *
2900          *  Versions < 3.6 don't have the digital ASIC. Try to probe it first.
2901          */
2902
2903         spin_lock_irqsave(&gus_lock,flags);
2904         outb((0x20), gus_base + 0x0f);
2905         val = inb(gus_base + 0x0f);
2906         spin_unlock_irqrestore(&gus_lock,flags);
2907
2908         if (gus_pnp_flag || (val != 0xff && (val & 0x06)))      /* Should be 0x02?? */
2909         {
2910                 int             ad_flags = 0;
2911
2912                 if (gus_pnp_flag)
2913                         ad_flags = 0x12345678;  /* Interwave "magic" */
2914                 /*
2915                  * It has the digital ASIC so the card is at least v3.4.
2916                  * Next try to detect the true model.
2917                  */
2918
2919                 if (gus_pnp_flag)       /* Hack hack hack */
2920                         val = 10;
2921                 else
2922                         val = inb(u_MixSelect);
2923
2924                 /*
2925                  * Value 255 means pre-3.7 which don't have mixer.
2926                  * Values 5 thru 9 mean v3.7 which has a ICS2101 mixer.
2927                  * 10 and above is GUS MAX which has the CS4231 codec/mixer.
2928                  *
2929                  */
2930
2931                 if (val == 255 || val < 5)
2932                 {
2933                         model_num = "3.4";
2934                         gus_type = 0x34;
2935                 }
2936                 else if (val < 10)
2937                 {
2938                         model_num = "3.7";
2939                         gus_type = 0x37;
2940                         mixer_type = ICS2101;
2941                         request_region(u_MixSelect, 1, "GUS mixer");
2942                 }
2943                 else
2944                 {
2945                         struct resource *ports;
2946                         ports = request_region(gus_base + 0x10c, 4, "ad1848");
2947                         model_num = "MAX";
2948                         gus_type = 0x40;
2949                         mixer_type = CS4231;
2950 #ifdef CONFIG_SOUND_GUSMAX
2951                         {
2952                                 unsigned char   max_config = 0x40;      /* Codec enable */
2953
2954                                 if (gus_dma2 == -1)
2955                                         gus_dma2 = gus_dma;
2956
2957                                 if (gus_dma > 3)
2958                                         max_config |= 0x10;             /* 16 bit capture DMA */
2959
2960                                 if (gus_dma2 > 3)
2961                                         max_config |= 0x20;             /* 16 bit playback DMA */
2962
2963                                 max_config |= (gus_base >> 4) & 0x0f;   /* Extract the X from 2X0 */
2964
2965                                 outb((max_config), gus_base + 0x106);   /* UltraMax control */
2966                         }
2967
2968                         if (!ports)
2969                                 goto no_cs4231;
2970
2971                         if (ad1848_detect(ports, &ad_flags, hw_config->osp))
2972                         {
2973                                 char           *name = "GUS MAX";
2974                                 int             old_num_mixers = num_mixers;
2975
2976                                 if (gus_pnp_flag)
2977                                         name = "GUS PnP";
2978
2979                                 gus_mic_vol = gus_line_vol = gus_pcm_volume = 100;
2980                                 gus_wave_volume = 90;
2981                                 have_gus_max = 1;
2982                                 if (hw_config->name)
2983                                         name = hw_config->name;
2984
2985                                 hw_config->slots[1] = ad1848_init(name, ports,
2986                                                         -irq, gus_dma2, /* Playback DMA */
2987                                                         gus_dma,        /* Capture DMA */
2988                                                         1,              /* Share DMA channels with GF1 */
2989                                                         hw_config->osp,
2990                                                         THIS_MODULE);
2991
2992                                 if (num_mixers > old_num_mixers)
2993                                 {
2994                                         /* GUS has it's own mixer map */
2995                                         AD1848_REROUTE(SOUND_MIXER_LINE1, SOUND_MIXER_SYNTH);
2996                                         AD1848_REROUTE(SOUND_MIXER_LINE2, SOUND_MIXER_CD);
2997                                         AD1848_REROUTE(SOUND_MIXER_LINE3, SOUND_MIXER_LINE);
2998                                 }
2999                         }
3000                         else {
3001                                 release_region(gus_base + 0x10c, 4);
3002                         no_cs4231:
3003                                 printk(KERN_WARNING "GUS: No CS4231 ??");
3004                         }
3005 #else
3006                         printk(KERN_ERR "GUS MAX found, but not compiled in\n");
3007 #endif
3008                 }
3009         }
3010         else
3011         {
3012                 /*
3013                  * ASIC not detected so the card must be 2.2 or 2.4.
3014                  * There could still be the 16-bit/mixer daughter card.
3015                  */
3016         }
3017
3018         if (hw_config->name)
3019                 snprintf(tmp, sizeof(tmp), "%s (%dk)", hw_config->name,
3020                          (int) gus_mem_size / 1024);
3021         else if (gus_pnp_flag)
3022                 snprintf(tmp, sizeof(tmp), "Gravis UltraSound PnP (%dk)",
3023                          (int) gus_mem_size / 1024);
3024         else
3025                 snprintf(tmp, sizeof(tmp), "Gravis UltraSound %s (%dk)", model_num,
3026                          (int) gus_mem_size / 1024);
3027
3028
3029         samples = (struct patch_info *)vmalloc((MAX_SAMPLE + 1) * sizeof(*samples));
3030         if (samples == NULL)
3031         {
3032                 printk(KERN_WARNING "gus_init: Cant allocate memory for instrument tables\n");
3033                 return;
3034         }
3035         conf_printf(tmp, hw_config);
3036         strlcpy(gus_info.name, tmp, sizeof(gus_info.name));
3037
3038         if ((sdev = sound_alloc_synthdev()) == -1)
3039                 printk(KERN_WARNING "gus_init: Too many synthesizers\n");
3040         else
3041         {
3042                 voice_alloc = &guswave_operations.alloc;
3043                 if (iw_mode)
3044                         guswave_operations.id = "IWAVE";
3045                 hw_config->slots[0] = sdev;
3046                 synth_devs[sdev] = &guswave_operations;
3047                 sequencer_init();
3048                 gus_tmr_install(gus_base + 8);
3049         }
3050
3051         reset_sample_memory();
3052
3053         gus_initialize();
3054         
3055         if ((gus_mem_size > 0) && !gus_no_wave_dma)
3056         {
3057                 hw_config->slots[4] = -1;
3058                 if ((gus_devnum = sound_install_audiodrv(AUDIO_DRIVER_VERSION,
3059                                         "Ultrasound",
3060                                         &gus_audio_driver,
3061                                         sizeof(struct audio_driver),
3062                                         NEEDS_RESTART |
3063                                         ((!iw_mode && dma2 != dma && dma2 != -1) ?
3064                                                 DMA_DUPLEX : 0),
3065                                         AFMT_U8 | AFMT_S16_LE,
3066                                         NULL, dma, dma2)) < 0)
3067                 {
3068                         return;
3069                 }
3070
3071                 hw_config->slots[4] = gus_devnum;
3072                 audio_devs[gus_devnum]->min_fragment = 9;       /* 512k */
3073                 audio_devs[gus_devnum]->max_fragment = 11;      /* 8k (must match size of bounce_buf */
3074                 audio_devs[gus_devnum]->mixer_dev = -1; /* Next mixer# */
3075                 audio_devs[gus_devnum]->flags |= DMA_HARDSTOP;
3076         }
3077         
3078         /*
3079          *  Mixer dependent initialization.
3080          */
3081
3082         switch (mixer_type)
3083         {
3084                 case ICS2101:
3085                         gus_mic_vol = gus_line_vol = gus_pcm_volume = 100;
3086                         gus_wave_volume = 90;
3087                         request_region(u_MixSelect, 1, "GUS mixer");
3088                         hw_config->slots[5] = ics2101_mixer_init();
3089                         audio_devs[gus_devnum]->mixer_dev = hw_config->slots[5];        /* Next mixer# */
3090                         return;
3091
3092                 case CS4231:
3093                         /* Initialized elsewhere (ad1848.c) */
3094                 default:
3095                         hw_config->slots[5] = gus_default_mixer_init();
3096                         audio_devs[gus_devnum]->mixer_dev = hw_config->slots[5];        /* Next mixer# */
3097                         return;
3098         }
3099 }
3100
3101 void __exit gus_wave_unload(struct address_info *hw_config)
3102 {
3103 #ifdef CONFIG_SOUND_GUSMAX
3104         if (have_gus_max)
3105         {
3106                 ad1848_unload(gus_base + 0x10c,
3107                                 -gus_irq,
3108                                 gus_dma2,       /* Playback DMA */
3109                                 gus_dma,        /* Capture DMA */
3110                                 1);     /* Share DMA channels with GF1 */
3111         }
3112 #endif
3113
3114         if (mixer_type == ICS2101)
3115         {
3116                 release_region(u_MixSelect, 1);
3117         }
3118         if (hw_config->slots[0] != -1)
3119                 sound_unload_synthdev(hw_config->slots[0]);
3120         if (hw_config->slots[1] != -1)
3121                 sound_unload_audiodev(hw_config->slots[1]);
3122         if (hw_config->slots[2] != -1)
3123                 sound_unload_mididev(hw_config->slots[2]);
3124         if (hw_config->slots[4] != -1)
3125                 sound_unload_audiodev(hw_config->slots[4]);
3126         if (hw_config->slots[5] != -1)
3127                 sound_unload_mixerdev(hw_config->slots[5]);
3128         
3129         vfree(samples);
3130         samples=NULL;
3131 }
3132 /* called in interrupt context */
3133 static void do_loop_irq(int voice)
3134 {
3135         unsigned char   tmp;
3136         int             mode, parm;
3137
3138         spin_lock(&gus_lock);
3139         gus_select_voice(voice);
3140
3141         tmp = gus_read8(0x00);
3142         tmp &= ~0x20;           /*
3143                                  * Disable wave IRQ for this_one voice
3144                                  */
3145         gus_write8(0x00, tmp);
3146
3147         if (tmp & 0x03)         /* Voice stopped */
3148                 voice_alloc->map[voice] = 0;
3149
3150         mode = voices[voice].loop_irq_mode;
3151         voices[voice].loop_irq_mode = 0;
3152         parm = voices[voice].loop_irq_parm;
3153
3154         switch (mode)
3155         {
3156                 case LMODE_FINISH:      /*
3157                                          * Final loop finished, shoot volume down
3158                                          */
3159
3160                         if ((int) (gus_read16(0x09) >> 4) < 100)        /*
3161                                                                          * Get current volume
3162                                                                          */
3163                         {
3164                                 gus_voice_off();
3165                                 gus_rampoff();
3166                                 gus_voice_init(voice);
3167                                 break;
3168                         }
3169                         gus_ramp_range(65, 4065);
3170                         gus_ramp_rate(0, 63);           /*
3171                                                          * Fastest possible rate
3172                                                          */
3173                         gus_rampon(0x20 | 0x40);        /*
3174                                                          * Ramp down, once, irq
3175                                                          */
3176                         voices[voice].volume_irq_mode = VMODE_HALT;
3177                         break;
3178
3179                 case LMODE_PCM_STOP:
3180                         pcm_active = 0; /* Signal to the play_next_pcm_block routine */
3181                 case LMODE_PCM:
3182                 {
3183                         pcm_qlen--;
3184                         pcm_head = (pcm_head + 1) % pcm_nblk;
3185                         if (pcm_qlen && pcm_active)
3186                         {
3187                                 play_next_pcm_block();
3188                         }
3189                         else
3190                         {
3191                                 /* Underrun. Just stop the voice */
3192                                 gus_select_voice(0);    /* Left channel */
3193                                 gus_voice_off();
3194                                 gus_rampoff();
3195                                 gus_select_voice(1);    /* Right channel */
3196                                 gus_voice_off();
3197                                 gus_rampoff();
3198                                 pcm_active = 0;
3199                         }
3200
3201                         /*
3202                          * If the queue was full before this interrupt, the DMA transfer was
3203                          * suspended. Let it continue now.
3204                          */
3205                         
3206                         if (audio_devs[gus_devnum]->dmap_out->qlen > 0)
3207                                 DMAbuf_outputintr(gus_devnum, 0);
3208                 }
3209                 break;
3210
3211                 default:
3212                         break;
3213         }
3214         spin_unlock(&gus_lock);
3215 }
3216
3217 static void do_volume_irq(int voice)
3218 {
3219         unsigned char tmp;
3220         int mode, parm;
3221         unsigned long flags;
3222
3223         spin_lock_irqsave(&gus_lock,flags);
3224
3225         gus_select_voice(voice);
3226         tmp = gus_read8(0x0d);
3227         tmp &= ~0x20;           /*
3228                                  * Disable volume ramp IRQ
3229                                  */
3230         gus_write8(0x0d, tmp);
3231
3232         mode = voices[voice].volume_irq_mode;
3233         voices[voice].volume_irq_mode = 0;
3234         parm = voices[voice].volume_irq_parm;
3235
3236         switch (mode)
3237         {
3238                 case VMODE_HALT:        /* Decay phase finished */
3239                         if (iw_mode)
3240                                 gus_write8(0x15, 0x02); /* Set voice deactivate bit of SMSI */
3241                         spin_unlock_irqrestore(&gus_lock,flags);
3242                         gus_voice_init(voice);
3243                         break;
3244
3245                 case VMODE_ENVELOPE:
3246                         gus_rampoff();
3247                         spin_unlock_irqrestore(&gus_lock,flags);
3248                         step_envelope(voice);
3249                         break;
3250
3251                 case VMODE_START_NOTE:
3252                         spin_unlock_irqrestore(&gus_lock,flags);
3253                         guswave_start_note2(voices[voice].dev_pending, voice,
3254                                       voices[voice].note_pending, voices[voice].volume_pending);
3255                         if (voices[voice].kill_pending)
3256                                 guswave_kill_note(voices[voice].dev_pending, voice,
3257                                           voices[voice].note_pending, 0);
3258
3259                         if (voices[voice].sample_pending >= 0)
3260                         {
3261                                 guswave_set_instr(voices[voice].dev_pending, voice,
3262                                         voices[voice].sample_pending);
3263                                 voices[voice].sample_pending = -1;
3264                         }
3265                         break;
3266
3267                 default:
3268                         spin_unlock_irqrestore(&gus_lock,flags);
3269         }
3270 }
3271 /* called in irq context */
3272 void gus_voice_irq(void)
3273 {
3274         unsigned long wave_ignore = 0, volume_ignore = 0;
3275         unsigned long voice_bit;
3276
3277         unsigned char src, voice;
3278
3279         while (1)
3280         {
3281                 src = gus_read8(0x0f);  /*
3282                                          * Get source info
3283                                          */
3284                 voice = src & 0x1f;
3285                 src &= 0xc0;
3286
3287                 if (src == (0x80 | 0x40))
3288                         return; /*
3289                                  * No interrupt
3290                                  */
3291
3292                 voice_bit = 1 << voice;
3293
3294                 if (!(src & 0x80))      /*
3295                                          * Wave IRQ pending
3296                                          */
3297                         if (!(wave_ignore & voice_bit) && (int) voice < nr_voices)      /*
3298                                                                                          * Not done
3299                                                                                          * yet
3300                                                                                          */
3301                         {
3302                                 wave_ignore |= voice_bit;
3303                                 do_loop_irq(voice);
3304                         }
3305                 if (!(src & 0x40))      /*
3306                                          * Volume IRQ pending
3307                                          */
3308                         if (!(volume_ignore & voice_bit) && (int) voice < nr_voices)    /*
3309                                                                                            * Not done
3310                                                                                            * yet
3311                                                                                          */
3312                         {
3313                                 volume_ignore |= voice_bit;
3314                                 do_volume_irq(voice);
3315                         }
3316         }
3317 }
3318
3319 void guswave_dma_irq(void)
3320 {
3321         unsigned char   status;
3322
3323         status = gus_look8(0x41);       /* Get DMA IRQ Status */
3324         if (status & 0x40)      /* DMA interrupt pending */
3325                 switch (active_device)
3326                 {
3327                         case GUS_DEV_WAVE:
3328                                 wake_up(&dram_sleeper);
3329                                 break;
3330
3331                         case GUS_DEV_PCM_CONTINUE:      /* Left channel data transferred */
3332                                 gus_write8(0x41, 0);    /* Disable GF1 DMA */
3333                                 gus_transfer_output_block(pcm_current_dev, pcm_current_buf,
3334                                                 pcm_current_count,
3335                                                 pcm_current_intrflag, 1);
3336                                 break;
3337
3338                         case GUS_DEV_PCM_DONE:  /* Right or mono channel data transferred */
3339                                 gus_write8(0x41, 0);    /* Disable GF1 DMA */
3340                                 if (pcm_qlen < pcm_nblk)
3341                                 {
3342                                         dma_active = 0;
3343                                         if (gus_busy)
3344                                         {
3345                                                 if (audio_devs[gus_devnum]->dmap_out->qlen > 0)
3346                                                         DMAbuf_outputintr(gus_devnum, 0);
3347                                         }
3348                                 }
3349                                 break;
3350
3351                         default:
3352                                 break;
3353         }
3354         status = gus_look8(0x49);       /*
3355                                          * Get Sampling IRQ Status
3356                                          */
3357         if (status & 0x40)      /*
3358                                  * Sampling Irq pending
3359                                  */
3360         {
3361                 DMAbuf_inputintr(gus_devnum);
3362         }
3363 }
3364
3365 /*
3366  * Timer stuff
3367  */
3368
3369 static volatile int select_addr, data_addr;
3370 static volatile int curr_timer;
3371
3372 void gus_timer_command(unsigned int addr, unsigned int val)
3373 {
3374         int i;
3375
3376         outb(((unsigned char) (addr & 0xff)), select_addr);
3377
3378         for (i = 0; i < 2; i++)
3379                 inb(select_addr);
3380
3381         outb(((unsigned char) (val & 0xff)), data_addr);
3382
3383         for (i = 0; i < 2; i++)
3384                 inb(select_addr);
3385 }
3386
3387 static void arm_timer(int timer, unsigned int interval)
3388 {
3389         curr_timer = timer;
3390
3391         if (timer == 1)
3392         {
3393                 gus_write8(0x46, 256 - interval);       /* Set counter for timer 1 */
3394                 gus_write8(0x45, 0x04);                 /* Enable timer 1 IRQ */
3395                 gus_timer_command(0x04, 0x01);          /* Start timer 1 */
3396         }
3397         else
3398         {
3399                 gus_write8(0x47, 256 - interval);       /* Set counter for timer 2 */
3400                 gus_write8(0x45, 0x08);                 /* Enable timer 2 IRQ */
3401                 gus_timer_command(0x04, 0x02);          /* Start timer 2 */
3402         }
3403
3404         gus_timer_enabled = 1;
3405 }
3406
3407 static unsigned int gus_tmr_start(int dev, unsigned int usecs_per_tick)
3408 {
3409         int timer_no, resolution;
3410         int divisor;
3411
3412         if (usecs_per_tick > (256 * 80))
3413         {
3414                 timer_no = 2;
3415                 resolution = 320;       /* usec */
3416         }
3417         else
3418         {
3419                 timer_no = 1;
3420                 resolution = 80;        /* usec */
3421         }
3422         divisor = (usecs_per_tick + (resolution / 2)) / resolution;
3423         arm_timer(timer_no, divisor);
3424
3425         return divisor * resolution;
3426 }
3427
3428 static void gus_tmr_disable(int dev)
3429 {
3430         gus_write8(0x45, 0);    /* Disable both timers */
3431         gus_timer_enabled = 0;
3432 }
3433
3434 static void gus_tmr_restart(int dev)
3435 {
3436         if (curr_timer == 1)
3437                 gus_write8(0x45, 0x04);         /* Start timer 1 again */
3438         else
3439                 gus_write8(0x45, 0x08);         /* Start timer 2 again */
3440         gus_timer_enabled = 1;
3441 }
3442
3443 static struct sound_lowlev_timer gus_tmr =
3444 {
3445         0,
3446         1,
3447         gus_tmr_start,
3448         gus_tmr_disable,
3449         gus_tmr_restart
3450 };
3451
3452 static void gus_tmr_install(int io_base)
3453 {
3454         struct sound_lowlev_timer *tmr;
3455
3456         select_addr = io_base;
3457         data_addr = io_base + 1;
3458
3459         tmr = &gus_tmr;
3460
3461 #ifdef THIS_GETS_FIXED
3462         sound_timer_init(&gus_tmr, "GUS");
3463 #endif
3464 }