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