v2.4.8 -> v2.4.8.1
[opensuse:kernel.git] / drivers / sound / wavfront.c
1 /*  -*- linux-c -*-
2  *
3  * sound/wavfront.c
4  *
5  * A Linux driver for Turtle Beach WaveFront Series (Maui, Tropez, Tropez Plus)
6  *
7  * This driver supports the onboard wavetable synthesizer (an ICS2115),
8  * including patch, sample and program loading and unloading, conversion
9  * of GUS patches during loading, and full user-level access to all
10  * WaveFront commands. It tries to provide semi-intelligent patch and
11  * sample management as well.
12  *
13  * It also provides support for the ICS emulation of an MPU-401.  Full
14  * support for the ICS emulation's "virtual MIDI mode" is provided in
15  * wf_midi.c.
16  *
17  * Support is also provided for the Tropez Plus' onboard FX processor,
18  * a Yamaha YSS225. Currently, code exists to configure the YSS225,
19  * and there is an interface allowing tweaking of any of its memory
20  * addresses. However, I have been unable to decipher the logical
21  * positioning of the configuration info for various effects, so for
22  * now, you just get the YSS225 in the same state as Turtle Beach's
23  * "SETUPSND.EXE" utility leaves it.
24  *
25  * The boards' DAC/ADC (a Crystal CS4232) is supported by cs4232.[co],
26  * This chip also controls the configuration of the card: the wavefront
27  * synth is logical unit 4.
28  *
29  *
30  * Supported devices:
31  *
32  *   /dev/dsp                      - using cs4232+ad1848 modules, OSS compatible
33  *   /dev/midiNN and /dev/midiNN+1 - using wf_midi code, OSS compatible
34  *   /dev/synth00                  - raw synth interface
35  * 
36  **********************************************************************
37  *
38  * Copyright (C) by Paul Barton-Davis 1998
39  *
40  * Some portions of this file are taken from work that is
41  * copyright (C) by Hannu Savolainen 1993-1996
42  *
43  * Although the relevant code here is all new, the handling of
44  * sample/alias/multi- samples is entirely based on a driver by Matt
45  * Martin and Rutger Nijlunsing which demonstrated how to get things
46  * to work correctly. The GUS patch loading code has been almost
47  * unaltered by me, except to fit formatting and function names in the
48  * rest of the file. Many thanks to them.
49  *
50  * Appreciation and thanks to Hannu Savolainen for his early work on the Maui
51  * driver, and answering a few questions while this one was developed.
52  *
53  * Absolutely NO thanks to Turtle Beach/Voyetra and Yamaha for their
54  * complete lack of help in developing this driver, and in particular
55  * for their utter silence in response to questions about undocumented
56  * aspects of configuring a WaveFront soundcard, particularly the
57  * effects processor.
58  *
59  * $Id: wavfront.c,v 0.7 1998/09/09 15:47:36 pbd Exp $
60  *
61  * This program is distributed under the GNU GENERAL PUBLIC LICENSE (GPL)
62  * Version 2 (June 1991). See the "COPYING" file distributed with this software
63  * for more info.
64  *
65  * Changes:
66  * 11-10-2000   Bartlomiej Zolnierkiewicz <bkz@linux-ide.org>
67  *              Added some __init and __initdata to entries in yss225.c
68  */
69
70 #include <linux/module.h>
71
72 #include <linux/kernel.h>
73 #include <linux/init.h>
74 #include <linux/sched.h>
75 #include <linux/smp_lock.h>
76 #include <linux/ptrace.h>
77 #include <linux/fcntl.h>
78 #include <linux/ioport.h>    
79
80 #include <linux/interrupt.h>
81 #include <linux/config.h>
82
83 #include <linux/delay.h>
84
85 #include "sound_config.h"
86
87 #include <linux/wavefront.h>
88
89 /*
90  *      This sucks, hopefully it'll get standardised
91  */
92  
93 #if defined(__alpha__)
94 #ifdef CONFIG_SMP
95 #define LOOPS_PER_TICK cpu_data[smp_processor_id()].loops_per_jiffy
96 #else
97 #define LOOPS_PER_TICK  loops_per_jiffy
98 #endif
99 #endif
100
101 #if defined(__i386__)
102 #define LOOPS_PER_TICK current_cpu_data.loops_per_jiffy
103 #endif
104  
105 #define _MIDI_SYNTH_C_
106 #define MIDI_SYNTH_NAME "WaveFront MIDI"
107 #define MIDI_SYNTH_CAPS SYNTH_CAP_INPUT
108 #include "midi_synth.h"
109
110 /* Compile-time control of the extent to which OSS is supported.
111
112    I consider /dev/sequencer to be an anachronism, but given its
113    widespread usage by various Linux MIDI software, it seems worth
114    offering support to it if its not too painful. Instead of using
115    /dev/sequencer, I recommend:
116
117      for synth programming and patch loading: /dev/synthNN
118      for kernel-synchronized MIDI sequencing: the ALSA sequencer
119      for direct MIDI control: /dev/midiNN
120
121    I have never tried static compilation into the kernel. The #if's
122    for this are really just notes to myself about what the code is
123    for.
124 */
125
126 #define OSS_SUPPORT_SEQ            0x1  /* use of /dev/sequencer */
127 #define OSS_SUPPORT_STATIC_INSTALL 0x2  /* static compilation into kernel */
128
129 #define OSS_SUPPORT_LEVEL          0x1  /* just /dev/sequencer for now */
130
131 #if    OSS_SUPPORT_LEVEL & OSS_SUPPORT_SEQ
132 static int (*midi_load_patch) (int devno, int format, const char *addr,
133                                int offs, int count, int pmgr_flag) = NULL;
134 #endif /* OSS_SUPPORT_SEQ */
135
136 /* if WF_DEBUG not defined, no run-time debugging messages will
137    be available via the debug flag setting. Given the current
138    beta state of the driver, this will remain set until a future 
139    version.
140 */
141
142 #define WF_DEBUG 1
143
144 #ifdef WF_DEBUG
145
146 /* Thank goodness for gcc's preprocessor ... */
147
148 #define DPRINT(cond, format, args...) \
149        if ((dev.debug & (cond)) == (cond)) { \
150              printk (KERN_DEBUG LOGNAME format, ## args); \
151        }
152 #else
153 #define DPRINT(cond, format, args...)
154 #endif
155
156 #define LOGNAME "WaveFront: "
157
158 /* bitmasks for WaveFront status port value */
159
160 #define STAT_RINTR_ENABLED      0x01
161 #define STAT_CAN_READ           0x02
162 #define STAT_INTR_READ          0x04
163 #define STAT_WINTR_ENABLED      0x10
164 #define STAT_CAN_WRITE          0x20
165 #define STAT_INTR_WRITE         0x40
166
167 /*** Module-accessible parameters ***************************************/
168
169 int wf_raw;     /* we normally check for "raw state" to firmware
170                    loading. if set, then during driver loading, the
171                    state of the board is ignored, and we reset the
172                    board and load the firmware anyway.
173                 */
174                    
175 int fx_raw = 1; /* if this is zero, we'll leave the FX processor in
176                    whatever state it is when the driver is loaded.
177                    The default is to download the microprogram and
178                    associated coefficients to set it up for "default"
179                    operation, whatever that means.
180                 */
181
182 int debug_default;      /* you can set this to control debugging
183                               during driver loading. it takes any combination
184                               of the WF_DEBUG_* flags defined in
185                               wavefront.h
186                            */
187
188 /* XXX this needs to be made firmware and hardware version dependent */
189
190 char *ospath = "/etc/sound/wavefront.os"; /* where to find a processed
191                                              version of the WaveFront OS
192                                           */
193
194 int wait_usecs = 150; /* This magic number seems to give pretty optimal
195                          throughput based on my limited experimentation.
196                          If you want to play around with it and find a better
197                          value, be my guest. Remember, the idea is to
198                          get a number that causes us to just busy wait
199                          for as many WaveFront commands as possible, without
200                          coming up with a number so large that we hog the
201                          whole CPU.
202
203                          Specifically, with this number, out of about 134,000
204                          status waits, only about 250 result in a sleep.
205                       */
206
207 int sleep_interval = 100;     /* HZ/sleep_interval seconds per sleep */
208 int sleep_tries = 50;       /* number of times we'll try to sleep */
209
210 int reset_time = 2;        /* hundreths of a second we wait after a HW reset for
211                               the expected interrupt.
212                            */
213
214 int ramcheck_time = 20;    /* time in seconds to wait while ROM code
215                               checks on-board RAM.
216                            */
217
218 int osrun_time = 10;       /* time in seconds we wait for the OS to
219                               start running.
220                            */
221
222 MODULE_PARM(wf_raw,"i");
223 MODULE_PARM(fx_raw,"i");
224 MODULE_PARM(debug_default,"i");
225 MODULE_PARM(wait_usecs,"i");
226 MODULE_PARM(sleep_interval,"i");
227 MODULE_PARM(sleep_tries,"i");
228 MODULE_PARM(ospath,"s");
229 MODULE_PARM(reset_time,"i");
230 MODULE_PARM(ramcheck_time,"i");
231 MODULE_PARM(osrun_time,"i");
232
233 /***************************************************************************/
234
235 /* Note: because this module doesn't export any symbols, this really isn't
236    a global variable, even if it looks like one. I was quite confused by
237    this when I started writing this as a (newer) module -- pbd.
238 */
239
240 struct wf_config {
241         int devno;            /* device number from kernel */
242         int irq;              /* "you were one, one of the few ..." */
243         int base;             /* low i/o port address */
244
245 #define mpu_data_port    base 
246 #define mpu_command_port base + 1 /* write semantics */
247 #define mpu_status_port  base + 1 /* read semantics */
248 #define data_port        base + 2 
249 #define status_port      base + 3 /* read semantics */
250 #define control_port     base + 3 /* write semantics  */
251 #define block_port       base + 4 /* 16 bit, writeonly */
252 #define last_block_port  base + 6 /* 16 bit, writeonly */
253
254         /* FX ports. These are mapped through the ICS2115 to the YS225.
255            The ICS2115 takes care of flipping the relevant pins on the
256            YS225 so that access to each of these ports does the right
257            thing. Note: these are NOT documented by Turtle Beach.
258         */
259
260 #define fx_status       base + 8 
261 #define fx_op           base + 8 
262 #define fx_lcr          base + 9 
263 #define fx_dsp_addr     base + 0xa
264 #define fx_dsp_page     base + 0xb 
265 #define fx_dsp_lsb      base + 0xc 
266 #define fx_dsp_msb      base + 0xd 
267 #define fx_mod_addr     base + 0xe
268 #define fx_mod_data     base + 0xf 
269
270         volatile int irq_ok;               /* set by interrupt handler */
271         volatile int irq_cnt;              /* ditto */
272         int opened;                        /* flag, holds open(2) mode */
273         char debug;                        /* debugging flags */
274         int freemem;                       /* installed RAM, in bytes */ 
275
276         int synth_dev;                     /* devno for "raw" synth */
277         int mididev;                       /* devno for internal MIDI */
278         int ext_mididev;                   /* devno for external MIDI */ 
279         int fx_mididev;                    /* devno for FX MIDI interface */
280 #if OSS_SUPPORT_LEVEL & OSS_SUPPORT_SEQ
281         int oss_dev;                      /* devno for OSS sequencer synth */
282 #endif /* OSS_SUPPORT_SEQ */
283
284         char fw_version[2];                /* major = [0], minor = [1] */
285         char hw_version[2];                /* major = [0], minor = [1] */
286         char israw;                        /* needs Motorola microcode */
287         char has_fx;                       /* has FX processor (Tropez+) */
288         char prog_status[WF_MAX_PROGRAM];  /* WF_SLOT_* */
289         char patch_status[WF_MAX_PATCH];   /* WF_SLOT_* */
290         char sample_status[WF_MAX_SAMPLE]; /* WF_ST_* | WF_SLOT_* */
291         int samples_used;                  /* how many */
292         char interrupts_on;                /* h/w MPU interrupts enabled ? */
293         char rom_samples_rdonly;           /* can we write on ROM samples */
294         wait_queue_head_t interrupt_sleeper; 
295 } dev;
296
297 static int  detect_wffx(void);
298 static int  wffx_ioctl (wavefront_fx_info *);
299 static int  wffx_init (void);
300
301 static int wavefront_delete_sample (int sampnum);
302 static int wavefront_find_free_sample (void);
303
304 /* From wf_midi.c */
305
306 extern int  virtual_midi_enable  (void);
307 extern int  virtual_midi_disable (void);
308 extern int  detect_wf_mpu (int, int);
309 extern int  install_wf_mpu (void);
310 extern int  uninstall_wf_mpu (void);
311
312 typedef struct {
313         int cmd;
314         char *action;
315         unsigned int read_cnt;
316         unsigned int write_cnt;
317         int need_ack;
318 } wavefront_command;
319
320 static struct {
321         int errno;
322         const char *errstr;
323 } wavefront_errors[] = {
324         { 0x01, "Bad sample number" },
325         { 0x02, "Out of sample memory" },
326         { 0x03, "Bad patch number" },
327         { 0x04, "Error in number of voices" },
328         { 0x06, "Sample load already in progress" },
329         { 0x0B, "No sample load request pending" },
330         { 0x0E, "Bad MIDI channel number" },
331         { 0x10, "Download Record Error" },
332         { 0x80, "Success" },
333         { 0x0, 0x0 }
334 };
335
336 #define NEEDS_ACK 1
337
338 static wavefront_command wavefront_commands[] = {
339         { WFC_SET_SYNTHVOL, "set synthesizer volume", 0, 1, NEEDS_ACK },
340         { WFC_GET_SYNTHVOL, "get synthesizer volume", 1, 0, 0},
341         { WFC_SET_NVOICES, "set number of voices", 0, 1, NEEDS_ACK },
342         { WFC_GET_NVOICES, "get number of voices", 1, 0, 0 },
343         { WFC_SET_TUNING, "set synthesizer tuning", 0, 2, NEEDS_ACK },
344         { WFC_GET_TUNING, "get synthesizer tuning", 2, 0, 0 },
345         { WFC_DISABLE_CHANNEL, "disable synth channel", 0, 1, NEEDS_ACK },
346         { WFC_ENABLE_CHANNEL, "enable synth channel", 0, 1, NEEDS_ACK },
347         { WFC_GET_CHANNEL_STATUS, "get synth channel status", 3, 0, 0 },
348         { WFC_MISYNTH_OFF, "disable midi-in to synth", 0, 0, NEEDS_ACK },
349         { WFC_MISYNTH_ON, "enable midi-in to synth", 0, 0, NEEDS_ACK },
350         { WFC_VMIDI_ON, "enable virtual midi mode", 0, 0, NEEDS_ACK },
351         { WFC_VMIDI_OFF, "disable virtual midi mode", 0, 0, NEEDS_ACK },
352         { WFC_MIDI_STATUS, "report midi status", 1, 0, 0 },
353         { WFC_FIRMWARE_VERSION, "report firmware version", 2, 0, 0 },
354         { WFC_HARDWARE_VERSION, "report hardware version", 2, 0, 0 },
355         { WFC_GET_NSAMPLES, "report number of samples", 2, 0, 0 },
356         { WFC_INSTOUT_LEVELS, "report instantaneous output levels", 7, 0, 0 },
357         { WFC_PEAKOUT_LEVELS, "report peak output levels", 7, 0, 0 },
358         { WFC_DOWNLOAD_SAMPLE, "download sample",
359           0, WF_SAMPLE_BYTES, NEEDS_ACK },
360         { WFC_DOWNLOAD_BLOCK, "download block", 0, 0, NEEDS_ACK},
361         { WFC_DOWNLOAD_SAMPLE_HEADER, "download sample header",
362           0, WF_SAMPLE_HDR_BYTES, NEEDS_ACK },
363         { WFC_UPLOAD_SAMPLE_HEADER, "upload sample header", 13, 2, 0 },
364
365         /* This command requires a variable number of bytes to be written.
366            There is a hack in wavefront_cmd() to support this. The actual
367            count is passed in as the read buffer ptr, cast appropriately.
368            Ugh.
369         */
370
371         { WFC_DOWNLOAD_MULTISAMPLE, "download multisample", 0, 0, NEEDS_ACK },
372
373         /* This one is a hack as well. We just read the first byte of the
374            response, don't fetch an ACK, and leave the rest to the 
375            calling function. Ugly, ugly, ugly.
376         */
377
378         { WFC_UPLOAD_MULTISAMPLE, "upload multisample", 2, 1, 0 },
379         { WFC_DOWNLOAD_SAMPLE_ALIAS, "download sample alias",
380           0, WF_ALIAS_BYTES, NEEDS_ACK },
381         { WFC_UPLOAD_SAMPLE_ALIAS, "upload sample alias", WF_ALIAS_BYTES, 2, 0},
382         { WFC_DELETE_SAMPLE, "delete sample", 0, 2, NEEDS_ACK },
383         { WFC_IDENTIFY_SAMPLE_TYPE, "identify sample type", 5, 2, 0 },
384         { WFC_UPLOAD_SAMPLE_PARAMS, "upload sample parameters" },
385         { WFC_REPORT_FREE_MEMORY, "report free memory", 4, 0, 0 },
386         { WFC_DOWNLOAD_PATCH, "download patch", 0, 134, NEEDS_ACK },
387         { WFC_UPLOAD_PATCH, "upload patch", 132, 2, 0 },
388         { WFC_DOWNLOAD_PROGRAM, "download program", 0, 33, NEEDS_ACK },
389         { WFC_UPLOAD_PROGRAM, "upload program", 32, 1, 0 },
390         { WFC_DOWNLOAD_EDRUM_PROGRAM, "download enhanced drum program", 0, 9,
391           NEEDS_ACK},
392         { WFC_UPLOAD_EDRUM_PROGRAM, "upload enhanced drum program", 8, 1, 0},
393         { WFC_SET_EDRUM_CHANNEL, "set enhanced drum program channel",
394           0, 1, NEEDS_ACK },
395         { WFC_DISABLE_DRUM_PROGRAM, "disable drum program", 0, 1, NEEDS_ACK },
396         { WFC_REPORT_CHANNEL_PROGRAMS, "report channel program numbers",
397           32, 0, 0 },
398         { WFC_NOOP, "the no-op command", 0, 0, NEEDS_ACK },
399         { 0x00 }
400 };
401
402 static const char *
403 wavefront_errorstr (int errnum)
404
405 {
406         int i;
407
408         for (i = 0; wavefront_errors[i].errstr; i++) {
409                 if (wavefront_errors[i].errno == errnum) {
410                         return wavefront_errors[i].errstr;
411                 }
412         }
413
414         return "Unknown WaveFront error";
415 }
416
417 static wavefront_command *
418 wavefront_get_command (int cmd) 
419
420 {
421         int i;
422
423         for (i = 0; wavefront_commands[i].cmd != 0; i++) {
424                 if (cmd == wavefront_commands[i].cmd) {
425                         return &wavefront_commands[i];
426                 }
427         }
428
429         return (wavefront_command *) 0;
430 }
431
432 static inline int
433 wavefront_status (void) 
434
435 {
436         return inb (dev.status_port);
437 }
438
439 static int
440 wavefront_sleep (int limit)
441
442 {
443         current->state = TASK_INTERRUPTIBLE;
444         schedule_timeout(limit);
445
446         return signal_pending(current);
447 }
448
449 static int
450 wavefront_wait (int mask)
451
452 {
453         int             i;
454         static int      short_loop_cnt = 0;
455
456         /* Compute the loop count that lets us sleep for about the
457            right amount of time, cache issues, bus speeds and all
458            other issues being unequal but largely irrelevant.
459         */
460
461         if (short_loop_cnt == 0) {
462                 short_loop_cnt = wait_usecs *
463                         (LOOPS_PER_TICK / (1000000 / HZ));
464         }
465
466         /* Spin for a short period of time, because >99% of all
467            requests to the WaveFront can be serviced inline like this.
468         */
469
470         for (i = 0; i < short_loop_cnt; i++) {
471                 if (wavefront_status() & mask) {
472                         return 1;
473                 }
474         }
475
476         for (i = 0; i < sleep_tries; i++) {
477
478                 if (wavefront_status() & mask) {
479                         return 1;
480                 }
481
482                 if (wavefront_sleep (HZ/sleep_interval)) {
483                         return (0);
484                 }
485         }
486
487         return (0);
488 }
489
490 static int
491 wavefront_read (void)
492
493 {
494         if (wavefront_wait (STAT_CAN_READ))
495                 return inb (dev.data_port);
496
497         DPRINT (WF_DEBUG_DATA, "read timeout.\n");
498
499         return -1;
500 }
501
502 static int
503 wavefront_write (unsigned char data)
504
505 {
506         if (wavefront_wait (STAT_CAN_WRITE)) {
507                 outb (data, dev.data_port);
508                 return 0;
509         }
510
511         DPRINT (WF_DEBUG_DATA, "write timeout.\n");
512
513         return -1;
514 }
515
516 static int
517 wavefront_cmd (int cmd, unsigned char *rbuf, unsigned char *wbuf)
518
519 {
520         int ack;
521         int i;
522         int c;
523         wavefront_command *wfcmd;
524
525         if ((wfcmd = wavefront_get_command (cmd)) == (wavefront_command *) 0) {
526                 printk (KERN_WARNING LOGNAME "command 0x%x not supported.\n",
527                         cmd);
528                 return 1;
529         }
530
531         /* Hack to handle the one variable-size write command. See
532            wavefront_send_multisample() for the other half of this
533            gross and ugly strategy.
534         */
535
536         if (cmd == WFC_DOWNLOAD_MULTISAMPLE) {
537                 wfcmd->write_cnt = (unsigned int) rbuf;
538                 rbuf = 0;
539         }
540
541         DPRINT (WF_DEBUG_CMD, "0x%x [%s] (%d,%d,%d)\n",
542                                cmd, wfcmd->action, wfcmd->read_cnt,
543                                wfcmd->write_cnt, wfcmd->need_ack);
544     
545         if (wavefront_write (cmd)) { 
546                 DPRINT ((WF_DEBUG_IO|WF_DEBUG_CMD), "cannot request "
547                                                      "0x%x [%s].\n",
548                                                      cmd, wfcmd->action);
549                 return 1;
550         } 
551
552         if (wfcmd->write_cnt > 0) {
553                 DPRINT (WF_DEBUG_DATA, "writing %d bytes "
554                                         "for 0x%x\n",
555                                         wfcmd->write_cnt, cmd);
556
557                 for (i = 0; i < wfcmd->write_cnt; i++) {
558                         if (wavefront_write (wbuf[i])) {
559                                 DPRINT (WF_DEBUG_IO, "bad write for byte "
560                                                       "%d of 0x%x [%s].\n",
561                                                       i, cmd, wfcmd->action);
562                                 return 1;
563                         }
564
565                         DPRINT (WF_DEBUG_DATA, "write[%d] = 0x%x\n",
566                                                 i, wbuf[i]);
567                 }
568         }
569
570         if (wfcmd->read_cnt > 0) {
571                 DPRINT (WF_DEBUG_DATA, "reading %d ints "
572                                         "for 0x%x\n",
573                                         wfcmd->read_cnt, cmd);
574
575                 for (i = 0; i < wfcmd->read_cnt; i++) {
576
577                         if ((c = wavefront_read()) == -1) {
578                                 DPRINT (WF_DEBUG_IO, "bad read for byte "
579                                                       "%d of 0x%x [%s].\n",
580                                                       i, cmd, wfcmd->action);
581                                 return 1;
582                         }
583
584                         /* Now handle errors. Lots of special cases here */
585             
586                         if (c == 0xff) { 
587                                 if ((c = wavefront_read ()) == -1) {
588                                         DPRINT (WF_DEBUG_IO, "bad read for "
589                                                               "error byte at "
590                                                               "read byte %d "
591                                                               "of 0x%x [%s].\n",
592                                                               i, cmd,
593                                                               wfcmd->action);
594                                         return 1;
595                                 }
596
597                                 /* Can you believe this madness ? */
598
599                                 if (c == 1 &&
600                                     wfcmd->cmd == WFC_IDENTIFY_SAMPLE_TYPE) {
601                                         rbuf[0] = WF_ST_EMPTY;
602                                         return (0);
603
604                                 } else if (c == 3 &&
605                                            wfcmd->cmd == WFC_UPLOAD_PATCH) {
606
607                                         return 3;
608
609                                 } else if (c == 1 &&
610                                            wfcmd->cmd == WFC_UPLOAD_PROGRAM) {
611
612                                         return 1;
613
614                                 } else {
615
616                                         DPRINT (WF_DEBUG_IO, "error %d (%s) "
617                                                               "during "
618                                                               "read for byte "
619                                                               "%d of 0x%x "
620                                                               "[%s].\n",
621                                                               c,
622                                                               wavefront_errorstr (c),
623                                                               i, cmd,
624                                                               wfcmd->action);
625                                         return 1;
626
627                                 }
628                 
629                 } else {
630                                 rbuf[i] = c;
631                         }
632                         
633                         DPRINT (WF_DEBUG_DATA, "read[%d] = 0x%x\n",i, rbuf[i]);
634                 }
635         }
636         
637         if ((wfcmd->read_cnt == 0 && wfcmd->write_cnt == 0) || wfcmd->need_ack) {
638
639                 DPRINT (WF_DEBUG_CMD, "reading ACK for 0x%x\n", cmd);
640
641                 /* Some commands need an ACK, but return zero instead
642                    of the standard value.
643                 */
644             
645                 if ((ack = wavefront_read()) == 0) {
646                         ack = WF_ACK;
647                 }
648         
649                 if (ack != WF_ACK) {
650                         if (ack == -1) {
651                                 DPRINT (WF_DEBUG_IO, "cannot read ack for "
652                                                       "0x%x [%s].\n",
653                                                       cmd, wfcmd->action);
654                                 return 1;
655                 
656                         } else {
657                                 int err = -1; /* something unknown */
658
659                                 if (ack == 0xff) { /* explicit error */
660                     
661                                         if ((err = wavefront_read ()) == -1) {
662                                                 DPRINT (WF_DEBUG_DATA,
663                                                         "cannot read err "
664                                                         "for 0x%x [%s].\n",
665                                                         cmd, wfcmd->action);
666                                         }
667                                 }
668                                 
669                                 DPRINT (WF_DEBUG_IO, "0x%x [%s] "
670                                         "failed (0x%x, 0x%x, %s)\n",
671                                         cmd, wfcmd->action, ack, err,
672                                         wavefront_errorstr (err));
673                                 
674                                 return -err;
675                         }
676                 }
677                 
678                 DPRINT (WF_DEBUG_DATA, "ack received "
679                                         "for 0x%x [%s]\n",
680                                         cmd, wfcmd->action);
681         } else {
682
683                 DPRINT (WF_DEBUG_CMD, "0x%x [%s] does not need "
684                                        "ACK (%d,%d,%d)\n",
685                                        cmd, wfcmd->action, wfcmd->read_cnt,
686                                        wfcmd->write_cnt, wfcmd->need_ack);
687         }
688
689         return 0;
690         
691 }
692 \f
693 /***********************************************************************
694 WaveFront: data munging   
695
696 Things here are weird. All data written to the board cannot 
697 have its most significant bit set. Any data item with values 
698 potentially > 0x7F (127) must be split across multiple bytes.
699
700 Sometimes, we need to munge numeric values that are represented on
701 the x86 side as 8-32 bit values. Sometimes, we need to munge data
702 that is represented on the x86 side as an array of bytes. The most
703 efficient approach to handling both cases seems to be to use 2
704 different functions for munging and 2 for de-munging. This avoids
705 weird casting and worrying about bit-level offsets.
706
707 **********************************************************************/
708
709 static 
710 unsigned char *
711 munge_int32 (unsigned int src,
712              unsigned char *dst,
713              unsigned int dst_size)
714 {
715         int i;
716
717         for (i = 0;i < dst_size; i++) {
718                 *dst = src & 0x7F;  /* Mask high bit of LSB */
719                 src = src >> 7;     /* Rotate Right 7 bits  */
720                                     /* Note: we leave the upper bits in place */ 
721
722                 dst++;
723         };
724         return dst;
725 };
726
727 static int 
728 demunge_int32 (unsigned char* src, int src_size)
729
730 {
731         int i;
732         int outval = 0;
733         
734         for (i = src_size - 1; i >= 0; i--) {
735                 outval=(outval<<7)+src[i];
736         }
737
738         return outval;
739 };
740
741 static 
742 unsigned char *
743 munge_buf (unsigned char *src, unsigned char *dst, unsigned int dst_size)
744
745 {
746         int i;
747         unsigned int last = dst_size / 2;
748
749         for (i = 0; i < last; i++) {
750                 *dst++ = src[i] & 0x7f;
751                 *dst++ = src[i] >> 7;
752         }
753         return dst;
754 }
755
756 static 
757 unsigned char *
758 demunge_buf (unsigned char *src, unsigned char *dst, unsigned int src_bytes)
759
760 {
761         int i;
762         unsigned char *end = src + src_bytes;
763     
764         end = src + src_bytes;
765
766         /* NOTE: src and dst *CAN* point to the same address */
767
768         for (i = 0; src != end; i++) {
769                 dst[i] = *src++;
770                 dst[i] |= (*src++)<<7;
771         }
772
773         return dst;
774 }
775 \f
776 /***********************************************************************
777 WaveFront: sample, patch and program management.
778 ***********************************************************************/
779
780 static int
781 wavefront_delete_sample (int sample_num)
782
783 {
784         unsigned char wbuf[2];
785         int x;
786
787         wbuf[0] = sample_num & 0x7f;
788         wbuf[1] = sample_num >> 7;
789
790         if ((x = wavefront_cmd (WFC_DELETE_SAMPLE, 0, wbuf)) == 0) {
791                 dev.sample_status[sample_num] = WF_ST_EMPTY;
792         }
793
794         return x;
795 }
796
797 static int
798 wavefront_get_sample_status (int assume_rom)
799
800 {
801         int i;
802         unsigned char rbuf[32], wbuf[32];
803         unsigned int    sc_real, sc_alias, sc_multi;
804
805         /* check sample status */
806     
807         if (wavefront_cmd (WFC_GET_NSAMPLES, rbuf, wbuf)) {
808                 printk (KERN_WARNING LOGNAME "cannot request sample count.\n");
809                 return -1;
810         } 
811     
812         sc_real = sc_alias = sc_multi = dev.samples_used = 0;
813     
814         for (i = 0; i < WF_MAX_SAMPLE; i++) {
815         
816                 wbuf[0] = i & 0x7f;
817                 wbuf[1] = i >> 7;
818
819                 if (wavefront_cmd (WFC_IDENTIFY_SAMPLE_TYPE, rbuf, wbuf)) {
820                         printk (KERN_WARNING LOGNAME
821                                 "cannot identify sample "
822                                 "type of slot %d\n", i);
823                         dev.sample_status[i] = WF_ST_EMPTY;
824                         continue;
825                 }
826
827                 dev.sample_status[i] = (WF_SLOT_FILLED|rbuf[0]);
828
829                 if (assume_rom) {
830                         dev.sample_status[i] |= WF_SLOT_ROM;
831                 }
832
833                 switch (rbuf[0] & WF_ST_MASK) {
834                 case WF_ST_SAMPLE:
835                         sc_real++;
836                         break;
837                 case WF_ST_MULTISAMPLE:
838                         sc_multi++;
839                         break;
840                 case WF_ST_ALIAS:
841                         sc_alias++;
842                         break;
843                 case WF_ST_EMPTY:
844                         break;
845
846                 default:
847                         printk (KERN_WARNING LOGNAME "unknown sample type for "
848                                 "slot %d (0x%x)\n", 
849                                 i, rbuf[0]);
850                 }
851
852                 if (rbuf[0] != WF_ST_EMPTY) {
853                         dev.samples_used++;
854                 } 
855         }
856
857         printk (KERN_INFO LOGNAME
858                 "%d samples used (%d real, %d aliases, %d multi), "
859                 "%d empty\n", dev.samples_used, sc_real, sc_alias, sc_multi,
860                 WF_MAX_SAMPLE - dev.samples_used);
861
862
863         return (0);
864
865 }
866
867 static int
868 wavefront_get_patch_status (void)
869
870 {
871         unsigned char patchbuf[WF_PATCH_BYTES];
872         unsigned char patchnum[2];
873         wavefront_patch *p;
874         int i, x, cnt, cnt2;
875
876         for (i = 0; i < WF_MAX_PATCH; i++) {
877                 patchnum[0] = i & 0x7f;
878                 patchnum[1] = i >> 7;
879
880                 if ((x = wavefront_cmd (WFC_UPLOAD_PATCH, patchbuf,
881                                         patchnum)) == 0) {
882
883                         dev.patch_status[i] |= WF_SLOT_FILLED;
884                         p = (wavefront_patch *) patchbuf;
885                         dev.sample_status
886                                 [p->sample_number|(p->sample_msb<<7)] |=
887                                 WF_SLOT_USED;
888             
889                 } else if (x == 3) { /* Bad patch number */
890                         dev.patch_status[i] = 0;
891                 } else {
892                         printk (KERN_ERR LOGNAME "upload patch "
893                                 "error 0x%x\n", x);
894                         dev.patch_status[i] = 0;
895                         return 1;
896                 }
897         }
898
899         /* program status has already filled in slot_used bits */
900
901         for (i = 0, cnt = 0, cnt2 = 0; i < WF_MAX_PATCH; i++) {
902                 if (dev.patch_status[i] & WF_SLOT_FILLED) {
903                         cnt++;
904                 }
905                 if (dev.patch_status[i] & WF_SLOT_USED) {
906                         cnt2++;
907                 }
908         
909         }
910         printk (KERN_INFO LOGNAME
911                 "%d patch slots filled, %d in use\n", cnt, cnt2);
912
913         return (0);
914 }
915
916 static int
917 wavefront_get_program_status (void)
918
919 {
920         unsigned char progbuf[WF_PROGRAM_BYTES];
921         wavefront_program prog;
922         unsigned char prognum;
923         int i, x, l, cnt;
924
925         for (i = 0; i < WF_MAX_PROGRAM; i++) {
926                 prognum = i;
927
928                 if ((x = wavefront_cmd (WFC_UPLOAD_PROGRAM, progbuf,
929                                         &prognum)) == 0) {
930
931                         dev.prog_status[i] |= WF_SLOT_USED;
932
933                         demunge_buf (progbuf, (unsigned char *) &prog,
934                                      WF_PROGRAM_BYTES);
935
936                         for (l = 0; l < WF_NUM_LAYERS; l++) {
937                                 if (prog.layer[l].mute) {
938                                         dev.patch_status
939                                                 [prog.layer[l].patch_number] |=
940                                                 WF_SLOT_USED;
941                                 }
942                         }
943                 } else if (x == 1) { /* Bad program number */
944                         dev.prog_status[i] = 0;
945                 } else {
946                         printk (KERN_ERR LOGNAME "upload program "
947                                 "error 0x%x\n", x);
948                         dev.prog_status[i] = 0;
949                 }
950         }
951
952         for (i = 0, cnt = 0; i < WF_MAX_PROGRAM; i++) {
953                 if (dev.prog_status[i]) {
954                         cnt++;
955                 }
956         }
957
958         printk (KERN_INFO LOGNAME "%d programs slots in use\n", cnt);
959
960         return (0);
961 }
962
963 static int
964 wavefront_send_patch (wavefront_patch_info *header)
965
966 {
967         unsigned char buf[WF_PATCH_BYTES+2];
968         unsigned char *bptr;
969
970         DPRINT (WF_DEBUG_LOAD_PATCH, "downloading patch %d\n",
971                                       header->number);
972
973         dev.patch_status[header->number] |= WF_SLOT_FILLED;
974
975         bptr = buf;
976         bptr = munge_int32 (header->number, buf, 2);
977         munge_buf ((unsigned char *)&header->hdr.p, bptr, WF_PATCH_BYTES);
978     
979         if (wavefront_cmd (WFC_DOWNLOAD_PATCH, 0, buf)) {
980                 printk (KERN_ERR LOGNAME "download patch failed\n");
981                 return -(EIO);
982         }
983
984         return (0);
985 }
986
987 static int
988 wavefront_send_program (wavefront_patch_info *header)
989
990 {
991         unsigned char buf[WF_PROGRAM_BYTES+1];
992         int i;
993
994         DPRINT (WF_DEBUG_LOAD_PATCH, "downloading program %d\n",
995                 header->number);
996
997         dev.prog_status[header->number] = WF_SLOT_USED;
998
999         /* XXX need to zero existing SLOT_USED bit for program_status[i]
1000            where `i' is the program that's being (potentially) overwritten.
1001         */
1002     
1003         for (i = 0; i < WF_NUM_LAYERS; i++) {
1004                 if (header->hdr.pr.layer[i].mute) {
1005                         dev.patch_status[header->hdr.pr.layer[i].patch_number] |=
1006                                 WF_SLOT_USED;
1007
1008                         /* XXX need to mark SLOT_USED for sample used by
1009                            patch_number, but this means we have to load it. Ick.
1010                         */
1011                 }
1012         }
1013
1014         buf[0] = header->number;
1015         munge_buf ((unsigned char *)&header->hdr.pr, &buf[1], WF_PROGRAM_BYTES);
1016     
1017         if (wavefront_cmd (WFC_DOWNLOAD_PROGRAM, 0, buf)) {
1018                 printk (KERN_WARNING LOGNAME "download patch failed\n");        
1019                 return -(EIO);
1020         }
1021
1022         return (0);
1023 }
1024
1025 static int
1026 wavefront_freemem (void)
1027
1028 {
1029         char rbuf[8];
1030
1031         if (wavefront_cmd (WFC_REPORT_FREE_MEMORY, rbuf, 0)) {
1032                 printk (KERN_WARNING LOGNAME "can't get memory stats.\n");
1033                 return -1;
1034         } else {
1035                 return demunge_int32 (rbuf, 4);
1036         }
1037 }
1038
1039 static int
1040 wavefront_send_sample (wavefront_patch_info *header,
1041                        UINT16 *dataptr,
1042                        int data_is_unsigned)
1043
1044 {
1045         /* samples are downloaded via a 16-bit wide i/o port
1046            (you could think of it as 2 adjacent 8-bit wide ports
1047            but its less efficient that way). therefore, all
1048            the blocksizes and so forth listed in the documentation,
1049            and used conventionally to refer to sample sizes,
1050            which are given in 8-bit units (bytes), need to be
1051            divided by 2.
1052         */
1053
1054         UINT16 sample_short;
1055         UINT32 length;
1056         UINT16 *data_end = 0;
1057         unsigned int i;
1058         const int max_blksize = 4096/2;
1059         unsigned int written;
1060         unsigned int blocksize;
1061         int dma_ack;
1062         int blocknum;
1063         unsigned char sample_hdr[WF_SAMPLE_HDR_BYTES];
1064         unsigned char *shptr;
1065         int skip = 0;
1066         int initial_skip = 0;
1067
1068         DPRINT (WF_DEBUG_LOAD_PATCH, "sample %sdownload for slot %d, "
1069                                       "type %d, %d bytes from 0x%x\n",
1070                                       header->size ? "" : "header ", 
1071                                       header->number, header->subkey,
1072                                       header->size,
1073                                       (int) header->dataptr);
1074
1075         if (header->number == WAVEFRONT_FIND_FREE_SAMPLE_SLOT) {
1076                 int x;
1077
1078                 if ((x = wavefront_find_free_sample ()) < 0) {
1079                         return -ENOMEM;
1080                 }
1081                 printk (KERN_DEBUG LOGNAME "unspecified sample => %d\n", x);
1082                 header->number = x;
1083         }
1084
1085         if (header->size) {
1086
1087                 /* XXX its a debatable point whether or not RDONLY semantics
1088                    on the ROM samples should cover just the sample data or
1089                    the sample header. For now, it only covers the sample data,
1090                    so anyone is free at all times to rewrite sample headers.
1091
1092                    My reason for this is that we have the sample headers
1093                    available in the WFB file for General MIDI, and so these
1094                    can always be reset if needed. The sample data, however,
1095                    cannot be recovered without a complete reset and firmware
1096                    reload of the ICS2115, which is a very expensive operation.
1097
1098                    So, doing things this way allows us to honor the notion of
1099                    "RESETSAMPLES" reasonably cheaply. Note however, that this
1100                    is done purely at user level: there is no WFB parser in
1101                    this driver, and so a complete reset (back to General MIDI,
1102                    or theoretically some other configuration) is the
1103                    responsibility of the user level library. 
1104
1105                    To try to do this in the kernel would be a little
1106                    crazy: we'd need 158K of kernel space just to hold
1107                    a copy of the patch/program/sample header data.
1108                 */
1109
1110                 if (dev.rom_samples_rdonly) {
1111                         if (dev.sample_status[header->number] & WF_SLOT_ROM) {
1112                                 printk (KERN_ERR LOGNAME "sample slot %d "
1113                                         "write protected\n",
1114                                         header->number);
1115                                 return -EACCES;
1116                         }
1117                 }
1118
1119                 wavefront_delete_sample (header->number);
1120         }
1121
1122         if (header->size) {
1123                 dev.freemem = wavefront_freemem ();
1124
1125                 if (dev.freemem < header->size) {
1126                         printk (KERN_ERR LOGNAME
1127                                 "insufficient memory to "
1128                                 "load %d byte sample.\n",
1129                                 header->size);
1130                         return -ENOMEM;
1131                 }
1132         
1133         }
1134
1135         skip = WF_GET_CHANNEL(&header->hdr.s);
1136
1137         if (skip > 0 && header->hdr.s.SampleResolution != LINEAR_16BIT) {
1138                 printk (KERN_ERR LOGNAME "channel selection only "
1139                         "possible on 16-bit samples");
1140                 return -(EINVAL);
1141         }
1142
1143         switch (skip) {
1144         case 0:
1145                 initial_skip = 0;
1146                 skip = 1;
1147                 break;
1148         case 1:
1149                 initial_skip = 0;
1150                 skip = 2;
1151                 break;
1152         case 2:
1153                 initial_skip = 1;
1154                 skip = 2;
1155                 break;
1156         case 3:
1157                 initial_skip = 2;
1158                 skip = 3;
1159                 break;
1160         case 4:
1161                 initial_skip = 3;
1162                 skip = 4;
1163                 break;
1164         case 5:
1165                 initial_skip = 4;
1166                 skip = 5;
1167                 break;
1168         case 6:
1169                 initial_skip = 5;
1170                 skip = 6;
1171                 break;
1172         }
1173
1174         DPRINT (WF_DEBUG_LOAD_PATCH, "channel selection: %d => "
1175                                       "initial skip = %d, skip = %d\n",
1176                                       WF_GET_CHANNEL (&header->hdr.s),
1177                                       initial_skip, skip);
1178     
1179         /* Be safe, and zero the "Unused" bits ... */
1180
1181         WF_SET_CHANNEL(&header->hdr.s, 0);
1182
1183         /* adjust size for 16 bit samples by dividing by two.  We always
1184            send 16 bits per write, even for 8 bit samples, so the length
1185            is always half the size of the sample data in bytes.
1186         */
1187
1188         length = header->size / 2;
1189
1190         /* the data we're sent has not been munged, and in fact, the
1191            header we have to send isn't just a munged copy either.
1192            so, build the sample header right here.
1193         */
1194
1195         shptr = &sample_hdr[0];
1196
1197         shptr = munge_int32 (header->number, shptr, 2);
1198
1199         if (header->size) {
1200                 shptr = munge_int32 (length, shptr, 4);
1201         }
1202
1203         /* Yes, a 4 byte result doesn't contain all of the offset bits,
1204            but the offset only uses 24 bits.
1205         */
1206
1207         shptr = munge_int32 (*((UINT32 *) &header->hdr.s.sampleStartOffset),
1208                              shptr, 4);
1209         shptr = munge_int32 (*((UINT32 *) &header->hdr.s.loopStartOffset),
1210                              shptr, 4);
1211         shptr = munge_int32 (*((UINT32 *) &header->hdr.s.loopEndOffset),
1212                              shptr, 4);
1213         shptr = munge_int32 (*((UINT32 *) &header->hdr.s.sampleEndOffset),
1214                              shptr, 4);
1215         
1216         /* This one is truly weird. What kind of weirdo decided that in
1217            a system dominated by 16 and 32 bit integers, they would use
1218            a just 12 bits ?
1219         */
1220         
1221         shptr = munge_int32 (header->hdr.s.FrequencyBias, shptr, 3);
1222         
1223         /* Why is this nybblified, when the MSB is *always* zero ? 
1224            Anyway, we can't take address of bitfield, so make a
1225            good-faith guess at where it starts.
1226         */
1227         
1228         shptr = munge_int32 (*(&header->hdr.s.FrequencyBias+1),
1229                              shptr, 2);
1230
1231         if (wavefront_cmd (header->size ?
1232                            WFC_DOWNLOAD_SAMPLE : WFC_DOWNLOAD_SAMPLE_HEADER,
1233                            0, sample_hdr)) {
1234                 printk (KERN_WARNING LOGNAME "sample %sdownload refused.\n",
1235                         header->size ? "" : "header ");
1236                 return -(EIO);
1237         }
1238
1239         if (header->size == 0) {
1240                 goto sent; /* Sorry. Just had to have one somewhere */
1241         }
1242     
1243         data_end = dataptr + length;
1244
1245         /* Do any initial skip over an unused channel's data */
1246
1247         dataptr += initial_skip;
1248     
1249         for (written = 0, blocknum = 0;
1250              written < length; written += max_blksize, blocknum++) {
1251         
1252                 if ((length - written) > max_blksize) {
1253                         blocksize = max_blksize;
1254                 } else {
1255                         /* round to nearest 16-byte value */
1256                         blocksize = ((length-written+7)&~0x7);
1257                 }
1258
1259                 if (wavefront_cmd (WFC_DOWNLOAD_BLOCK, 0, 0)) {
1260                         printk (KERN_WARNING LOGNAME "download block "
1261                                 "request refused.\n");
1262                         return -(EIO);
1263                 }
1264
1265                 for (i = 0; i < blocksize; i++) {
1266
1267                         if (dataptr < data_end) {
1268                 
1269                                 __get_user (sample_short, dataptr);
1270                                 dataptr += skip;
1271                 
1272                                 if (data_is_unsigned) { /* GUS ? */
1273
1274                                         if (WF_SAMPLE_IS_8BIT(&header->hdr.s)) {
1275                         
1276                                                 /* 8 bit sample
1277                                                  resolution, sign
1278                                                  extend both bytes.
1279                                                 */
1280                         
1281                                                 ((unsigned char*)
1282                                                  &sample_short)[0] += 0x7f;
1283                                                 ((unsigned char*)
1284                                                  &sample_short)[1] += 0x7f;
1285                         
1286                                         } else {
1287                         
1288                                                 /* 16 bit sample
1289                                                  resolution, sign
1290                                                  extend the MSB.
1291                                                 */
1292                         
1293                                                 sample_short += 0x7fff;
1294                                         }
1295                                 }
1296
1297                         } else {
1298
1299                                 /* In padding section of final block:
1300
1301                                    Don't fetch unsupplied data from
1302                                    user space, just continue with
1303                                    whatever the final value was.
1304                                 */
1305                         }
1306             
1307                         if (i < blocksize - 1) {
1308                                 outw (sample_short, dev.block_port);
1309                         } else {
1310                                 outw (sample_short, dev.last_block_port);
1311                         }
1312                 }
1313
1314                 /* Get "DMA page acknowledge", even though its really
1315                    nothing to do with DMA at all.
1316                 */
1317         
1318                 if ((dma_ack = wavefront_read ()) != WF_DMA_ACK) {
1319                         if (dma_ack == -1) {
1320                                 printk (KERN_ERR LOGNAME "upload sample "
1321                                         "DMA ack timeout\n");
1322                                 return -(EIO);
1323                         } else {
1324                                 printk (KERN_ERR LOGNAME "upload sample "
1325                                         "DMA ack error 0x%x\n",
1326                                         dma_ack);
1327                                 return -(EIO);
1328                         }
1329                 }
1330         }
1331
1332         dev.sample_status[header->number] = (WF_SLOT_FILLED|WF_ST_SAMPLE);
1333
1334         /* Note, label is here because sending the sample header shouldn't
1335            alter the sample_status info at all.
1336         */
1337
1338  sent:
1339         return (0);
1340 }
1341
1342 static int
1343 wavefront_send_alias (wavefront_patch_info *header)
1344
1345 {
1346         unsigned char alias_hdr[WF_ALIAS_BYTES];
1347
1348         DPRINT (WF_DEBUG_LOAD_PATCH, "download alias, %d is "
1349                                       "alias for %d\n",
1350                                       header->number,
1351                                       header->hdr.a.OriginalSample);
1352     
1353         munge_int32 (header->number, &alias_hdr[0], 2);
1354         munge_int32 (header->hdr.a.OriginalSample, &alias_hdr[2], 2);
1355         munge_int32 (*((unsigned int *)&header->hdr.a.sampleStartOffset),
1356                      &alias_hdr[4], 4);
1357         munge_int32 (*((unsigned int *)&header->hdr.a.loopStartOffset),
1358                      &alias_hdr[8], 4);
1359         munge_int32 (*((unsigned int *)&header->hdr.a.loopEndOffset),
1360                      &alias_hdr[12], 4);
1361         munge_int32 (*((unsigned int *)&header->hdr.a.sampleEndOffset),
1362                      &alias_hdr[16], 4);
1363         munge_int32 (header->hdr.a.FrequencyBias, &alias_hdr[20], 3);
1364         munge_int32 (*(&header->hdr.a.FrequencyBias+1), &alias_hdr[23], 2);
1365
1366         if (wavefront_cmd (WFC_DOWNLOAD_SAMPLE_ALIAS, 0, alias_hdr)) {
1367                 printk (KERN_ERR LOGNAME "download alias failed.\n");
1368                 return -(EIO);
1369         }
1370
1371         dev.sample_status[header->number] = (WF_SLOT_FILLED|WF_ST_ALIAS);
1372
1373         return (0);
1374 }
1375
1376 static int
1377 wavefront_send_multisample (wavefront_patch_info *header)
1378 {
1379         int i;
1380         int num_samples;
1381         unsigned char msample_hdr[WF_MSAMPLE_BYTES];
1382
1383         munge_int32 (header->number, &msample_hdr[0], 2);
1384
1385         /* You'll recall at this point that the "number of samples" value
1386            in a wavefront_multisample struct is actually the log2 of the
1387            real number of samples.
1388         */
1389
1390         num_samples = (1<<(header->hdr.ms.NumberOfSamples&7));
1391         msample_hdr[2] = (unsigned char) header->hdr.ms.NumberOfSamples;
1392
1393         DPRINT (WF_DEBUG_LOAD_PATCH, "multi %d with %d=%d samples\n",
1394                                       header->number,
1395                                       header->hdr.ms.NumberOfSamples,
1396                                       num_samples);
1397
1398         for (i = 0; i < num_samples; i++) {
1399                 DPRINT(WF_DEBUG_LOAD_PATCH|WF_DEBUG_DATA, "sample[%d] = %d\n",
1400                        i, header->hdr.ms.SampleNumber[i]);
1401                 munge_int32 (header->hdr.ms.SampleNumber[i],
1402                      &msample_hdr[3+(i*2)], 2);
1403         }
1404     
1405         /* Need a hack here to pass in the number of bytes
1406            to be written to the synth. This is ugly, and perhaps
1407            one day, I'll fix it.
1408         */
1409
1410         if (wavefront_cmd (WFC_DOWNLOAD_MULTISAMPLE, 
1411                            (unsigned char *) ((num_samples*2)+3),
1412                            msample_hdr)) {
1413                 printk (KERN_ERR LOGNAME "download of multisample failed.\n");
1414                 return -(EIO);
1415         }
1416
1417         dev.sample_status[header->number] = (WF_SLOT_FILLED|WF_ST_MULTISAMPLE);
1418
1419         return (0);
1420 }
1421
1422 static int
1423 wavefront_fetch_multisample (wavefront_patch_info *header)
1424 {
1425         int i;
1426         unsigned char log_ns[1];
1427         unsigned char number[2];
1428         int num_samples;
1429
1430         munge_int32 (header->number, number, 2);
1431     
1432         if (wavefront_cmd (WFC_UPLOAD_MULTISAMPLE, log_ns, number)) {
1433                 printk (KERN_ERR LOGNAME "upload multisample failed.\n");
1434                 return -(EIO);
1435         }
1436     
1437         DPRINT (WF_DEBUG_DATA, "msample %d has %d samples\n",
1438                                 header->number, log_ns[0]);
1439
1440         header->hdr.ms.NumberOfSamples = log_ns[0];
1441
1442         /* get the number of samples ... */
1443
1444         num_samples = (1 << log_ns[0]);
1445     
1446         for (i = 0; i < num_samples; i++) {
1447                 char d[2];
1448         
1449                 if ((d[0] = wavefront_read ()) == -1) {
1450                         printk (KERN_ERR LOGNAME "upload multisample failed "
1451                                 "during sample loop.\n");
1452                         return -(EIO);
1453                 }
1454
1455                 if ((d[1] = wavefront_read ()) == -1) {
1456                         printk (KERN_ERR LOGNAME "upload multisample failed "
1457                                 "during sample loop.\n");
1458                         return -(EIO);
1459                 }
1460         
1461                 header->hdr.ms.SampleNumber[i] =
1462                         demunge_int32 ((unsigned char *) d, 2);
1463         
1464                 DPRINT (WF_DEBUG_DATA, "msample sample[%d] = %d\n",
1465                                         i, header->hdr.ms.SampleNumber[i]);
1466         }
1467
1468         return (0);
1469 }
1470
1471
1472 static int
1473 wavefront_send_drum (wavefront_patch_info *header)
1474
1475 {
1476         unsigned char drumbuf[WF_DRUM_BYTES];
1477         wavefront_drum *drum = &header->hdr.d;
1478         int i;
1479
1480         DPRINT (WF_DEBUG_LOAD_PATCH, "downloading edrum for MIDI "
1481                 "note %d, patch = %d\n", 
1482                 header->number, drum->PatchNumber);
1483
1484         drumbuf[0] = header->number & 0x7f;
1485
1486         for (i = 0; i < 4; i++) {
1487                 munge_int32 (((unsigned char *)drum)[i], &drumbuf[1+(i*2)], 2);
1488         }
1489
1490         if (wavefront_cmd (WFC_DOWNLOAD_EDRUM_PROGRAM, 0, drumbuf)) {
1491                 printk (KERN_ERR LOGNAME "download drum failed.\n");
1492                 return -(EIO);
1493         }
1494
1495         return (0);
1496 }
1497
1498 static int 
1499 wavefront_find_free_sample (void)
1500
1501 {
1502         int i;
1503
1504         for (i = 0; i < WF_MAX_SAMPLE; i++) {
1505                 if (!(dev.sample_status[i] & WF_SLOT_FILLED)) {
1506                         return i;
1507                 }
1508         }
1509         printk (KERN_WARNING LOGNAME "no free sample slots!\n");
1510         return -1;
1511 }
1512
1513 static int 
1514 wavefront_find_free_patch (void)
1515
1516 {
1517         int i;
1518
1519         for (i = 0; i < WF_MAX_PATCH; i++) {
1520                 if (!(dev.patch_status[i] & WF_SLOT_FILLED)) {
1521                         return i;
1522                 }
1523         }
1524         printk (KERN_WARNING LOGNAME "no free patch slots!\n");
1525         return -1;
1526 }
1527
1528 static int 
1529 log2_2048(int n)
1530
1531 {
1532         int tbl[]={0, 0, 2048, 3246, 4096, 4755, 5294, 5749, 6143,
1533                    6492, 6803, 7084, 7342, 7578, 7797, 8001, 8192,
1534                    8371, 8540, 8699, 8851, 8995, 9132, 9264, 9390,
1535                    9510, 9626, 9738, 9845, 9949, 10049, 10146};
1536         int i;
1537
1538         /* Returns 2048*log2(n) */
1539
1540         /* FIXME: this is like doing integer math
1541            on quantum particles (RuN) */
1542
1543         i=0;
1544         while(n>=32*256) {
1545                 n>>=8;
1546                 i+=2048*8;
1547         }
1548         while(n>=32) {
1549                 n>>=1;
1550                 i+=2048;
1551         }
1552         i+=tbl[n];
1553         return(i);
1554 }
1555
1556 static int
1557 wavefront_load_gus_patch (int devno, int format, const char *addr,
1558                           int offs, int count, int pmgr_flag)
1559 {
1560         struct patch_info guspatch;
1561         wavefront_patch_info samp, pat, prog;
1562         wavefront_patch *patp;
1563         wavefront_sample *sampp;
1564         wavefront_program *progp;
1565
1566         int i,base_note;
1567         long sizeof_patch;
1568
1569         /* Copy in the header of the GUS patch */
1570
1571         sizeof_patch = (long) &guspatch.data[0] - (long) &guspatch; 
1572         copy_from_user (&((char *) &guspatch)[offs],
1573                         &(addr)[offs], sizeof_patch - offs);
1574
1575         if ((i = wavefront_find_free_patch ()) == -1) {
1576                 return -EBUSY;
1577         }
1578         pat.number = i;
1579         pat.subkey = WF_ST_PATCH;
1580         patp = &pat.hdr.p;
1581
1582         if ((i = wavefront_find_free_sample ()) == -1) {
1583                 return -EBUSY;
1584         }
1585         samp.number = i;
1586         samp.subkey = WF_ST_SAMPLE;
1587         samp.size = guspatch.len;
1588         sampp = &samp.hdr.s;
1589
1590         prog.number = guspatch.instr_no;
1591         progp = &prog.hdr.pr;
1592
1593         /* Setup the patch structure */
1594
1595         patp->amplitude_bias=guspatch.volume;
1596         patp->portamento=0;
1597         patp->sample_number= samp.number & 0xff;
1598         patp->sample_msb= samp.number>>8;
1599         patp->pitch_bend= /*12*/ 0;
1600         patp->mono=1;
1601         patp->retrigger=1;
1602         patp->nohold=(guspatch.mode & WAVE_SUSTAIN_ON) ? 0:1;
1603         patp->frequency_bias=0;
1604         patp->restart=0;
1605         patp->reuse=0;
1606         patp->reset_lfo=1;
1607         patp->fm_src2=0;
1608         patp->fm_src1=WF_MOD_MOD_WHEEL;
1609         patp->am_src=WF_MOD_PRESSURE;
1610         patp->am_amount=127;
1611         patp->fc1_mod_amount=0;
1612         patp->fc2_mod_amount=0; 
1613         patp->fm_amount1=0;
1614         patp->fm_amount2=0;
1615         patp->envelope1.attack_level=127;
1616         patp->envelope1.decay1_level=127;
1617         patp->envelope1.decay2_level=127;
1618         patp->envelope1.sustain_level=127;
1619         patp->envelope1.release_level=0;
1620         patp->envelope2.attack_velocity=127;
1621         patp->envelope2.attack_level=127;
1622         patp->envelope2.decay1_level=127;
1623         patp->envelope2.decay2_level=127;
1624         patp->envelope2.sustain_level=127;
1625         patp->envelope2.release_level=0;
1626         patp->envelope2.attack_velocity=127;
1627         patp->randomizer=0;
1628
1629         /* Program for this patch */
1630
1631         progp->layer[0].patch_number= pat.number; /* XXX is this right ? */
1632         progp->layer[0].mute=1;
1633         progp->layer[0].pan_or_mod=1;
1634         progp->layer[0].pan=7;
1635         progp->layer[0].mix_level=127  /* guspatch.volume */;
1636         progp->layer[0].split_type=0;
1637         progp->layer[0].split_point=0;
1638         progp->layer[0].play_below=0;
1639
1640         for (i = 1; i < 4; i++) {
1641                 progp->layer[i].mute=0;
1642         }
1643
1644         /* Sample data */
1645
1646         sampp->SampleResolution=((~guspatch.mode & WAVE_16_BITS)<<1);
1647
1648         for (base_note=0;
1649              note_to_freq (base_note) < guspatch.base_note;
1650              base_note++);
1651
1652         if ((guspatch.base_note-note_to_freq(base_note))
1653             >(note_to_freq(base_note)-guspatch.base_note))
1654                 base_note++;
1655
1656         printk(KERN_DEBUG "ref freq=%d,base note=%d\n",
1657                guspatch.base_freq,
1658                base_note);
1659
1660         sampp->FrequencyBias = (29550 - log2_2048(guspatch.base_freq)
1661                                 + base_note*171);
1662         printk(KERN_DEBUG "Freq Bias is %d\n", sampp->FrequencyBias);
1663         sampp->Loop=(guspatch.mode & WAVE_LOOPING) ? 1:0;
1664         sampp->sampleStartOffset.Fraction=0;
1665         sampp->sampleStartOffset.Integer=0;
1666         sampp->loopStartOffset.Fraction=0;
1667         sampp->loopStartOffset.Integer=guspatch.loop_start
1668                 >>((guspatch.mode&WAVE_16_BITS) ? 1:0);
1669         sampp->loopEndOffset.Fraction=0;
1670         sampp->loopEndOffset.Integer=guspatch.loop_end
1671                 >>((guspatch.mode&WAVE_16_BITS) ? 1:0);
1672         sampp->sampleEndOffset.Fraction=0;
1673         sampp->sampleEndOffset.Integer=guspatch.len >> (guspatch.mode&1);
1674         sampp->Bidirectional=(guspatch.mode&WAVE_BIDIR_LOOP) ? 1:0;
1675         sampp->Reverse=(guspatch.mode&WAVE_LOOP_BACK) ? 1:0;
1676
1677         /* Now ship it down */
1678
1679         wavefront_send_sample (&samp, 
1680                                (unsigned short *) &(addr)[sizeof_patch],
1681                                (guspatch.mode & WAVE_UNSIGNED) ? 1:0);
1682         wavefront_send_patch (&pat);
1683         wavefront_send_program (&prog);
1684
1685         /* Now pan as best we can ... use the slave/internal MIDI device
1686            number if it exists (since it talks to the WaveFront), or the
1687            master otherwise.
1688         */
1689
1690         if (dev.mididev > 0) {
1691                 midi_synth_controller (dev.mididev, guspatch.instr_no, 10,
1692                                        ((guspatch.panning << 4) > 127) ?
1693                                        127 : (guspatch.panning << 4));
1694         }
1695
1696         return(0);
1697 }
1698
1699 static int
1700 wavefront_load_patch (const char *addr)
1701
1702
1703 {
1704         wavefront_patch_info header;
1705         
1706         if (copy_from_user (&header, addr, sizeof(wavefront_patch_info) -
1707                             sizeof(wavefront_any))) {
1708                 printk (KERN_WARNING LOGNAME "bad address for load patch.\n");
1709                 return -(EINVAL);
1710         }
1711
1712         DPRINT (WF_DEBUG_LOAD_PATCH, "download "
1713                                       "Sample type: %d "
1714                                       "Sample number: %d "
1715                                       "Sample size: %d\n",
1716                                       header.subkey,
1717                                       header.number,
1718                                       header.size);
1719
1720         switch (header.subkey) {
1721         case WF_ST_SAMPLE:  /* sample or sample_header, based on patch->size */
1722
1723                 copy_from_user ((unsigned char *) &header.hdr.s,
1724                                 (unsigned char *) header.hdrptr,
1725                                 sizeof (wavefront_sample));
1726
1727                 return wavefront_send_sample (&header, header.dataptr, 0);
1728
1729         case WF_ST_MULTISAMPLE:
1730
1731                 copy_from_user ((unsigned char *) &header.hdr.s,
1732                                 (unsigned char *) header.hdrptr,
1733                                 sizeof (wavefront_multisample));
1734
1735                 return wavefront_send_multisample (&header);
1736
1737
1738         case WF_ST_ALIAS:
1739
1740                 copy_from_user ((unsigned char *) &header.hdr.a,
1741                                 (unsigned char *) header.hdrptr,
1742                                 sizeof (wavefront_alias));
1743
1744                 return wavefront_send_alias (&header);
1745
1746         case WF_ST_DRUM:
1747                 copy_from_user ((unsigned char *) &header.hdr.d, 
1748                                 (unsigned char *) header.hdrptr,
1749                                 sizeof (wavefront_drum));
1750
1751                 return wavefront_send_drum (&header);
1752
1753         case WF_ST_PATCH:
1754                 copy_from_user ((unsigned char *) &header.hdr.p, 
1755                                 (unsigned char *) header.hdrptr,
1756                                 sizeof (wavefront_patch));
1757
1758                 return wavefront_send_patch (&header);
1759
1760         case WF_ST_PROGRAM:
1761                 copy_from_user ((unsigned char *) &header.hdr.pr, 
1762                                 (unsigned char *) header.hdrptr,
1763                                 sizeof (wavefront_program));
1764
1765                 return wavefront_send_program (&header);
1766
1767         default:
1768                 printk (KERN_ERR LOGNAME "unknown patch type %d.\n",
1769                         header.subkey);
1770                 return -(EINVAL);
1771         }
1772
1773         return 0;
1774 }
1775 \f
1776 /***********************************************************************
1777 WaveFront: /dev/sequencer{,2} and other hardware-dependent interfaces
1778 ***********************************************************************/
1779
1780 static void
1781 process_sample_hdr (UCHAR8 *buf)
1782
1783 {
1784         wavefront_sample s;
1785         UCHAR8 *ptr;
1786
1787         ptr = buf;
1788
1789         /* The board doesn't send us an exact copy of a "wavefront_sample"
1790            in response to an Upload Sample Header command. Instead, we 
1791            have to convert the data format back into our data structure,
1792            just as in the Download Sample command, where we have to do
1793            something very similar in the reverse direction.
1794         */
1795
1796         *((UINT32 *) &s.sampleStartOffset) = demunge_int32 (ptr, 4); ptr += 4;
1797         *((UINT32 *) &s.loopStartOffset) = demunge_int32 (ptr, 4); ptr += 4;
1798         *((UINT32 *) &s.loopEndOffset) = demunge_int32 (ptr, 4); ptr += 4;
1799         *((UINT32 *) &s.sampleEndOffset) = demunge_int32 (ptr, 4); ptr += 4;
1800         *((UINT32 *) &s.FrequencyBias) = demunge_int32 (ptr, 3); ptr += 3;
1801
1802         s.SampleResolution = *ptr & 0x3;
1803         s.Loop = *ptr & 0x8;
1804         s.Bidirectional = *ptr & 0x10;
1805         s.Reverse = *ptr & 0x40;
1806
1807         /* Now copy it back to where it came from */
1808
1809         memcpy (buf, (unsigned char *) &s, sizeof (wavefront_sample));
1810 }
1811
1812 static int
1813 wavefront_synth_control (int cmd, wavefront_control *wc)
1814
1815 {
1816         unsigned char patchnumbuf[2];
1817         int i;
1818
1819         DPRINT (WF_DEBUG_CMD, "synth control with "
1820                 "cmd 0x%x\n", wc->cmd);
1821
1822         /* Pre-handling of or for various commands */
1823
1824         switch (wc->cmd) {
1825         case WFC_DISABLE_INTERRUPTS:
1826                 printk (KERN_INFO LOGNAME "interrupts disabled.\n");
1827                 outb (0x80|0x20, dev.control_port);
1828                 dev.interrupts_on = 0;
1829                 return 0;
1830
1831         case WFC_ENABLE_INTERRUPTS:
1832                 printk (KERN_INFO LOGNAME "interrupts enabled.\n");
1833                 outb (0x80|0x40|0x20, dev.control_port);
1834                 dev.interrupts_on = 1;
1835                 return 0;
1836
1837         case WFC_INTERRUPT_STATUS:
1838                 wc->rbuf[0] = dev.interrupts_on;
1839                 return 0;
1840
1841         case WFC_ROMSAMPLES_RDONLY:
1842                 dev.rom_samples_rdonly = wc->wbuf[0];
1843                 wc->status = 0;
1844                 return 0;
1845
1846         case WFC_IDENTIFY_SLOT_TYPE:
1847                 i = wc->wbuf[0] | (wc->wbuf[1] << 7);
1848                 if (i <0 || i >= WF_MAX_SAMPLE) {
1849                         printk (KERN_WARNING LOGNAME "invalid slot ID %d\n",
1850                                 i);
1851                         wc->status = EINVAL;
1852                         return 0;
1853                 }
1854                 wc->rbuf[0] = dev.sample_status[i];
1855                 wc->status = 0;
1856                 return 0;
1857
1858         case WFC_DEBUG_DRIVER:
1859                 dev.debug = wc->wbuf[0];
1860                 printk (KERN_INFO LOGNAME "debug = 0x%x\n", dev.debug);
1861                 return 0;
1862
1863         case WFC_FX_IOCTL:
1864                 wffx_ioctl ((wavefront_fx_info *) &wc->wbuf[0]);
1865                 return 0;
1866
1867         case WFC_UPLOAD_PATCH:
1868                 munge_int32 (*((UINT32 *) wc->wbuf), patchnumbuf, 2);
1869                 memcpy (wc->wbuf, patchnumbuf, 2);
1870                 break;
1871
1872         case WFC_UPLOAD_MULTISAMPLE:
1873                 /* multisamples have to be handled differently, and
1874                    cannot be dealt with properly by wavefront_cmd() alone.
1875                 */
1876                 wc->status = wavefront_fetch_multisample
1877                         ((wavefront_patch_info *) wc->rbuf);
1878                 return 0;
1879
1880         case WFC_UPLOAD_SAMPLE_ALIAS:
1881                 printk (KERN_INFO LOGNAME "support for sample alias upload "
1882                         "being considered.\n");
1883                 wc->status = EINVAL;
1884                 return -EINVAL;
1885         }
1886
1887         wc->status = wavefront_cmd (wc->cmd, wc->rbuf, wc->wbuf);
1888
1889         /* Post-handling of certain commands.
1890
1891            In particular, if the command was an upload, demunge the data
1892            so that the user-level doesn't have to think about it.
1893         */
1894
1895         if (wc->status == 0) {
1896                 switch (wc->cmd) {
1897                         /* intercept any freemem requests so that we know
1898                            we are always current with the user-level view
1899                            of things.
1900                         */
1901
1902                 case WFC_REPORT_FREE_MEMORY:
1903                         dev.freemem = demunge_int32 (wc->rbuf, 4);
1904                         break;
1905
1906                 case WFC_UPLOAD_PATCH:
1907                         demunge_buf (wc->rbuf, wc->rbuf, WF_PATCH_BYTES);
1908                         break;
1909
1910                 case WFC_UPLOAD_PROGRAM:
1911                         demunge_buf (wc->rbuf, wc->rbuf, WF_PROGRAM_BYTES);
1912                         break;
1913
1914                 case WFC_UPLOAD_EDRUM_PROGRAM:
1915                         demunge_buf (wc->rbuf, wc->rbuf, WF_DRUM_BYTES - 1);
1916                         break;
1917
1918                 case WFC_UPLOAD_SAMPLE_HEADER:
1919                         process_sample_hdr (wc->rbuf);
1920                         break;
1921
1922                 case WFC_UPLOAD_SAMPLE_ALIAS:
1923                         printk (KERN_INFO LOGNAME "support for "
1924                                 "sample aliases still "
1925                                 "being considered.\n");
1926                         break;
1927
1928                 case WFC_VMIDI_OFF:
1929                         if (virtual_midi_disable () < 0) {
1930                                 return -(EIO);
1931                         }
1932                         break;
1933
1934                 case WFC_VMIDI_ON:
1935                         if (virtual_midi_enable () < 0) {
1936                                 return -(EIO);
1937                         }
1938                         break;
1939                 }
1940         }
1941
1942         return 0;
1943 }
1944
1945 \f
1946 /***********************************************************************/
1947 /* WaveFront: Linux file system interface (for access via raw synth)    */
1948 /***********************************************************************/
1949
1950 static int 
1951 wavefront_open (struct inode *inode, struct file *file)
1952 {
1953         /* XXX fix me */
1954         dev.opened = file->f_flags;
1955         return 0;
1956 }
1957
1958 static int
1959 wavefront_release(struct inode *inode, struct file *file)
1960 {
1961         lock_kernel();
1962         dev.opened = 0;
1963         dev.debug = 0;
1964         unlock_kernel();
1965         return 0;
1966 }
1967
1968 static int
1969 wavefront_ioctl(struct inode *inode, struct file *file,
1970                 unsigned int cmd, unsigned long arg)
1971 {
1972         wavefront_control wc;
1973         int err;
1974
1975         switch (cmd) {
1976
1977         case WFCTL_WFCMD:
1978                 copy_from_user (&wc, (void *) arg, sizeof (wc));
1979                 
1980                 if ((err = wavefront_synth_control (cmd, &wc)) == 0) {
1981                         copy_to_user ((void *) arg, &wc, sizeof (wc));
1982                 }
1983
1984                 return err;
1985                 
1986         case WFCTL_LOAD_SPP:
1987                 return wavefront_load_patch ((const char *) arg);
1988                 
1989         default:
1990                 printk (KERN_WARNING LOGNAME "invalid ioctl %#x\n", cmd);
1991                 return -(EINVAL);
1992
1993         }
1994         return 0;
1995 }
1996
1997 static /*const*/ struct file_operations wavefront_fops = {
1998         owner:          THIS_MODULE,
1999         llseek:         no_llseek,
2000         ioctl:          wavefront_ioctl,
2001         open:           wavefront_open,
2002         release:        wavefront_release,
2003 };
2004
2005 \f
2006 /***********************************************************************/
2007 /* WaveFront: OSS installation and support interface                   */
2008 /***********************************************************************/
2009
2010 #if OSS_SUPPORT_LEVEL & OSS_SUPPORT_SEQ
2011
2012 static struct synth_info wavefront_info =
2013 {"Turtle Beach WaveFront", 0, SYNTH_TYPE_SAMPLE, SAMPLE_TYPE_WAVEFRONT,
2014  0, 32, 0, 0, SYNTH_CAP_INPUT};
2015
2016 static int
2017 wavefront_oss_open (int devno, int mode)
2018
2019 {
2020         dev.opened = mode;
2021         return 0;
2022 }
2023
2024 static void
2025 wavefront_oss_close (int devno)
2026
2027 {
2028         dev.opened = 0;
2029         dev.debug = 0;
2030         return;
2031 }
2032
2033 static int
2034 wavefront_oss_ioctl (int devno, unsigned int cmd, caddr_t arg)
2035
2036 {
2037         wavefront_control wc;
2038         int err;
2039
2040         switch (cmd) {
2041         case SNDCTL_SYNTH_INFO:
2042                 if(copy_to_user(&((char *) arg)[0], &wavefront_info,
2043                         sizeof (wavefront_info)))
2044                         return -EFAULT;
2045                 return 0;
2046
2047         case SNDCTL_SEQ_RESETSAMPLES:
2048 //              printk (KERN_WARNING LOGNAME "driver cannot reset samples.\n");
2049                 return 0; /* don't force an error */
2050
2051         case SNDCTL_SEQ_PERCMODE:
2052                 return 0; /* don't force an error */
2053
2054         case SNDCTL_SYNTH_MEMAVL:
2055                 if ((dev.freemem = wavefront_freemem ()) < 0) {
2056                         printk (KERN_ERR LOGNAME "cannot get memory size\n");
2057                         return -EIO;
2058                 } else {
2059                         return dev.freemem;
2060                 }
2061                 break;
2062
2063         case SNDCTL_SYNTH_CONTROL:
2064                 if(copy_from_user (&wc, arg, sizeof (wc)))
2065                         err = -EFAULT;
2066                 else if ((err = wavefront_synth_control (cmd, &wc)) == 0) {
2067                         if(copy_to_user (arg, &wc, sizeof (wc)))
2068                                 err = -EFAULT;
2069                 }
2070
2071                 return err;
2072
2073         default:
2074                 return -(EINVAL);
2075         }
2076 }
2077
2078 int
2079 wavefront_oss_load_patch (int devno, int format, const char *addr,
2080                           int offs, int count, int pmgr_flag)
2081 {
2082
2083         if (format == SYSEX_PATCH) {    /* Handled by midi_synth.c */
2084                 if (midi_load_patch == NULL) {
2085                         printk (KERN_ERR LOGNAME
2086                                 "SYSEX not loadable: "
2087                                 "no midi patch loader!\n");
2088                         return -(EINVAL);
2089                 }
2090
2091                 return midi_load_patch (devno, format, addr,
2092                                         offs, count, pmgr_flag);
2093
2094         } else if (format == GUS_PATCH) {
2095                 return wavefront_load_gus_patch (devno, format,
2096                                                  addr, offs, count, pmgr_flag);
2097
2098         } else if (format != WAVEFRONT_PATCH) {
2099                 printk (KERN_ERR LOGNAME "unknown patch format %d\n", format);
2100                 return -(EINVAL);
2101         }
2102
2103         if (count < sizeof (wavefront_patch_info)) {
2104                 printk (KERN_ERR LOGNAME "sample header too short\n");
2105                 return -(EINVAL);
2106         }
2107
2108         /* "addr" points to a user-space wavefront_patch_info */
2109
2110         return wavefront_load_patch (addr);
2111 }       
2112
2113 static struct synth_operations wavefront_operations =
2114 {
2115         owner:          THIS_MODULE,
2116         id:             "WaveFront",
2117         info:           &wavefront_info,
2118         midi_dev:       0,
2119         synth_type:     SYNTH_TYPE_SAMPLE,
2120         synth_subtype:  SAMPLE_TYPE_WAVEFRONT,
2121         open:           wavefront_oss_open,
2122         close:          wavefront_oss_close,
2123         ioctl:          wavefront_oss_ioctl,
2124         kill_note:      midi_synth_kill_note,
2125         start_note:     midi_synth_start_note,
2126         set_instr:      midi_synth_set_instr,
2127         reset:          midi_synth_reset,
2128         load_patch:     midi_synth_load_patch,
2129         aftertouch:     midi_synth_aftertouch,
2130         controller:     midi_synth_controller,
2131         panning:        midi_synth_panning,
2132         bender:         midi_synth_bender,
2133         setup_voice:    midi_synth_setup_voice
2134 };
2135 #endif /* OSS_SUPPORT_SEQ */
2136
2137 #if OSS_SUPPORT_LEVEL & OSS_SUPPORT_STATIC_INSTALL
2138
2139 static void __init attach_wavefront (struct address_info *hw_config)
2140 {
2141     (void) install_wavefront ();
2142 }
2143
2144 static int __init probe_wavefront (struct address_info *hw_config)
2145 {
2146     return !detect_wavefront (hw_config->irq, hw_config->io_base);
2147 }
2148
2149 static void __exit unload_wavefront (struct address_info *hw_config) 
2150 {
2151     (void) uninstall_wavefront ();
2152 }
2153
2154 #endif /* OSS_SUPPORT_STATIC_INSTALL */
2155
2156 /***********************************************************************/
2157 /* WaveFront: Linux modular sound kernel installation interface        */
2158 /***********************************************************************/
2159
2160 void
2161 wavefrontintr (int irq, void *dev_id, struct pt_regs *dummy)
2162 {
2163         struct wf_config *hw = dev_id;
2164
2165         /*
2166            Some comments on interrupts. I attempted a version of this
2167            driver that used interrupts throughout the code instead of
2168            doing busy and/or sleep-waiting. Alas, it appears that once
2169            the Motorola firmware is downloaded, the card *never*
2170            generates an RX interrupt. These are successfully generated
2171            during firmware loading, and after that wavefront_status()
2172            reports that an interrupt is pending on the card from time
2173            to time, but it never seems to be delivered to this
2174            driver. Note also that wavefront_status() continues to
2175            report that RX interrupts are enabled, suggesting that I
2176            didn't goof up and disable them by mistake.
2177
2178            Thus, I stepped back to a prior version of
2179            wavefront_wait(), the only place where this really
2180            matters. Its sad, but I've looked through the code to check
2181            on things, and I really feel certain that the Motorola
2182            firmware prevents RX-ready interrupts.
2183         */
2184
2185         if ((wavefront_status() & (STAT_INTR_READ|STAT_INTR_WRITE)) == 0) {
2186                 return;
2187         }
2188
2189         hw->irq_ok = 1;
2190         hw->irq_cnt++;
2191         wake_up_interruptible (&hw->interrupt_sleeper);
2192 }
2193
2194 /* STATUS REGISTER 
2195
2196 0 Host Rx Interrupt Enable (1=Enabled)
2197 1 Host Rx Register Full (1=Full)
2198 2 Host Rx Interrupt Pending (1=Interrupt)
2199 3 Unused
2200 4 Host Tx Interrupt (1=Enabled)
2201 5 Host Tx Register empty (1=Empty)
2202 6 Host Tx Interrupt Pending (1=Interrupt)
2203 7 Unused
2204 */
2205
2206 int
2207 wavefront_interrupt_bits (int irq)
2208
2209 {
2210         int bits;
2211
2212         switch (irq) {
2213         case 9:
2214                 bits = 0x00;
2215                 break;
2216         case 5:
2217                 bits = 0x08;
2218                 break;
2219         case 12:
2220                 bits = 0x10;
2221                 break;
2222         case 15:
2223                 bits = 0x18;
2224                 break;
2225         
2226         default:
2227                 printk (KERN_WARNING LOGNAME "invalid IRQ %d\n", irq);
2228                 bits = -1;
2229         }
2230
2231         return bits;
2232 }
2233
2234 void
2235 wavefront_should_cause_interrupt (int val, int port, int timeout)
2236
2237 {
2238         unsigned long flags;
2239
2240         save_flags (flags);
2241         cli();
2242         dev.irq_ok = 0;
2243         outb (val,port);
2244         interruptible_sleep_on_timeout (&dev.interrupt_sleeper, timeout);
2245         restore_flags (flags);
2246 }
2247
2248 static int __init wavefront_hw_reset (void)
2249 {
2250         int bits;
2251         int hwv[2];
2252         unsigned long irq_mask;
2253         short reported_irq;
2254
2255         /* IRQ already checked in init_module() */
2256
2257         bits = wavefront_interrupt_bits (dev.irq);
2258
2259         printk (KERN_DEBUG LOGNAME "autodetecting WaveFront IRQ\n");
2260
2261         sti ();
2262
2263         irq_mask = probe_irq_on ();
2264
2265         outb (0x0, dev.control_port); 
2266         outb (0x80 | 0x40 | bits, dev.data_port);       
2267         wavefront_should_cause_interrupt(0x80|0x40|0x10|0x1,
2268                                          dev.control_port,
2269                                          (reset_time*HZ)/100);
2270
2271         reported_irq = probe_irq_off (irq_mask);
2272
2273         if (reported_irq != dev.irq) {
2274                 if (reported_irq == 0) {
2275                         printk (KERN_ERR LOGNAME
2276                                 "No unassigned interrupts detected "
2277                                 "after h/w reset\n");
2278                 } else if (reported_irq < 0) {
2279                         printk (KERN_ERR LOGNAME
2280                                 "Multiple unassigned interrupts detected "
2281                                 "after h/w reset\n");
2282                 } else {
2283                         printk (KERN_ERR LOGNAME "autodetected IRQ %d not the "
2284                                 "value provided (%d)\n", reported_irq,
2285                                 dev.irq);
2286                 }
2287                 dev.irq = -1;
2288                 return 1;
2289         } else {
2290                 printk (KERN_INFO LOGNAME "autodetected IRQ at %d\n",
2291                         reported_irq);
2292         }
2293
2294         if (request_irq (dev.irq, wavefrontintr,
2295                          SA_INTERRUPT|SA_SHIRQ,
2296                          "wavefront synth", &dev) < 0) {
2297                 printk (KERN_WARNING LOGNAME "IRQ %d not available!\n",
2298                         dev.irq);
2299                 return 1;
2300         }
2301
2302         /* try reset of port */
2303       
2304         outb (0x0, dev.control_port); 
2305   
2306         /* At this point, the board is in reset, and the H/W initialization
2307            register is accessed at the same address as the data port.
2308      
2309            Bit 7 - Enable IRQ Driver    
2310            0 - Tri-state the Wave-Board drivers for the PC Bus IRQs
2311            1 - Enable IRQ selected by bits 5:3 to be driven onto the PC Bus.
2312      
2313            Bit 6 - MIDI Interface Select
2314
2315            0 - Use the MIDI Input from the 26-pin WaveBlaster
2316            compatible header as the serial MIDI source
2317            1 - Use the MIDI Input from the 9-pin D connector as the
2318            serial MIDI source.
2319      
2320            Bits 5:3 - IRQ Selection
2321            0 0 0 - IRQ 2/9
2322            0 0 1 - IRQ 5
2323            0 1 0 - IRQ 12
2324            0 1 1 - IRQ 15
2325            1 0 0 - Reserved
2326            1 0 1 - Reserved
2327            1 1 0 - Reserved
2328            1 1 1 - Reserved
2329      
2330            Bits 2:1 - Reserved
2331            Bit 0 - Disable Boot ROM
2332            0 - memory accesses to 03FC30-03FFFFH utilize the internal Boot ROM
2333            1 - memory accesses to 03FC30-03FFFFH are directed to external 
2334            storage.
2335      
2336         */
2337
2338         /* configure hardware: IRQ, enable interrupts, 
2339            plus external 9-pin MIDI interface selected
2340         */
2341
2342         outb (0x80 | 0x40 | bits, dev.data_port);       
2343   
2344         /* CONTROL REGISTER
2345
2346            0 Host Rx Interrupt Enable (1=Enabled)      0x1
2347            1 Unused                                    0x2
2348            2 Unused                                    0x4
2349            3 Unused                                    0x8
2350            4 Host Tx Interrupt Enable                 0x10
2351            5 Mute (0=Mute; 1=Play)                    0x20
2352            6 Master Interrupt Enable (1=Enabled)      0x40
2353            7 Master Reset (0=Reset; 1=Run)            0x80
2354
2355            Take us out of reset, mute output, master + TX + RX interrupts on.
2356            
2357            We'll get an interrupt presumably to tell us that the TX
2358            register is clear.
2359         */
2360
2361         wavefront_should_cause_interrupt(0x80|0x40|0x10|0x1,
2362                                          dev.control_port,
2363                                          (reset_time*HZ)/100);
2364
2365         /* Note: data port is now the data port, not the h/w initialization
2366            port.
2367          */
2368
2369         if (!dev.irq_ok) {
2370                 printk (KERN_WARNING LOGNAME
2371                         "intr not received after h/w un-reset.\n");
2372                 goto gone_bad;
2373         } 
2374
2375         dev.interrupts_on = 1;
2376         
2377         /* Note: data port is now the data port, not the h/w initialization
2378            port.
2379
2380            At this point, only "HW VERSION" or "DOWNLOAD OS" commands
2381            will work. So, issue one of them, and wait for TX
2382            interrupt. This can take a *long* time after a cold boot,
2383            while the ISC ROM does its RAM test. The SDK says up to 4
2384            seconds - with 12MB of RAM on a Tropez+, it takes a lot
2385            longer than that (~16secs). Note that the card understands
2386            the difference between a warm and a cold boot, so
2387            subsequent ISC2115 reboots (say, caused by module
2388            reloading) will get through this much faster.
2389
2390            XXX Interesting question: why is no RX interrupt received first ?
2391         */
2392
2393         wavefront_should_cause_interrupt(WFC_HARDWARE_VERSION, 
2394                                          dev.data_port, ramcheck_time*HZ);
2395
2396         if (!dev.irq_ok) {
2397                 printk (KERN_WARNING LOGNAME
2398                         "post-RAM-check interrupt not received.\n");
2399                 goto gone_bad;
2400         } 
2401
2402         if (!wavefront_wait (STAT_CAN_READ)) {
2403                 printk (KERN_WARNING LOGNAME
2404                         "no response to HW version cmd.\n");
2405                 goto gone_bad;
2406         }
2407         
2408         if ((hwv[0] = wavefront_read ()) == -1) {
2409                 printk (KERN_WARNING LOGNAME
2410                         "board not responding correctly.\n");
2411                 goto gone_bad;
2412         }
2413
2414         if (hwv[0] == 0xFF) { /* NAK */
2415
2416                 /* Board's RAM test failed. Try to read error code,
2417                    and tell us about it either way.
2418                 */
2419                 
2420                 if ((hwv[0] = wavefront_read ()) == -1) {
2421                         printk (KERN_WARNING LOGNAME "on-board RAM test failed "
2422                                 "(bad error code).\n");
2423                 } else {
2424                         printk (KERN_WARNING LOGNAME "on-board RAM test failed "
2425                                 "(error code: 0x%x).\n",
2426                                 hwv[0]);
2427                 }
2428                 goto gone_bad;
2429         }
2430
2431         /* We're OK, just get the next byte of the HW version response */
2432
2433         if ((hwv[1] = wavefront_read ()) == -1) {
2434                 printk (KERN_WARNING LOGNAME "incorrect h/w response.\n");
2435                 goto gone_bad;
2436         }
2437
2438         printk (KERN_INFO LOGNAME "hardware version %d.%d\n",
2439                 hwv[0], hwv[1]);
2440
2441         return 0;
2442
2443
2444      gone_bad:
2445         if (dev.irq >= 0) {
2446                 free_irq (dev.irq, &dev);
2447                 dev.irq = -1;
2448         }
2449         return (1);
2450 }
2451
2452 static int __init detect_wavefront (int irq, int io_base)
2453 {
2454         unsigned char   rbuf[4], wbuf[4];
2455
2456         /* TB docs say the device takes up 8 ports, but we know that
2457            if there is an FX device present (i.e. a Tropez+) it really
2458            consumes 16.
2459         */
2460
2461         if (check_region (io_base, 16)) {
2462                 printk (KERN_ERR LOGNAME "IO address range 0x%x - 0x%x "
2463                         "already in use - ignored\n", dev.base,
2464                         dev.base+15);
2465                 return -1;
2466         }
2467   
2468         dev.irq = irq;
2469         dev.base = io_base;
2470         dev.israw = 0;
2471         dev.debug = debug_default;
2472         dev.interrupts_on = 0;
2473         dev.irq_cnt = 0;
2474         dev.rom_samples_rdonly = 1; /* XXX default lock on ROM sample slots */
2475
2476         if (wavefront_cmd (WFC_FIRMWARE_VERSION, rbuf, wbuf) == 0) {
2477
2478                 dev.fw_version[0] = rbuf[0];
2479                 dev.fw_version[1] = rbuf[1];
2480                 printk (KERN_INFO LOGNAME
2481                         "firmware %d.%d already loaded.\n",
2482                         rbuf[0], rbuf[1]);
2483
2484                 /* check that a command actually works */
2485       
2486                 if (wavefront_cmd (WFC_HARDWARE_VERSION,
2487                                    rbuf, wbuf) == 0) {
2488                         dev.hw_version[0] = rbuf[0];
2489                         dev.hw_version[1] = rbuf[1];
2490                 } else {
2491                         printk (KERN_WARNING LOGNAME "not raw, but no "
2492                                 "hardware version!\n");
2493                         return 0;
2494                 }
2495
2496                 if (!wf_raw) {
2497                         return 1;
2498                 } else {
2499                         printk (KERN_INFO LOGNAME
2500                                 "reloading firmware anyway.\n");
2501                         dev.israw = 1;
2502                 }
2503
2504         } else {
2505
2506                 dev.israw = 1;
2507                 printk (KERN_INFO LOGNAME
2508                         "no response to firmware probe, assume raw.\n");
2509
2510         }
2511
2512         init_waitqueue_head (&dev.interrupt_sleeper);
2513
2514         if (wavefront_hw_reset ()) {
2515                 printk (KERN_WARNING LOGNAME "hardware reset failed\n");
2516                 return 0;
2517         }
2518
2519         /* Check for FX device, present only on Tropez+ */
2520
2521         dev.has_fx = (detect_wffx () == 0);
2522
2523         return 1;
2524 }
2525
2526 #include "os.h"
2527 #define __KERNEL_SYSCALLS__
2528 #include <linux/fs.h>
2529 #include <linux/mm.h>
2530 #include <linux/slab.h>
2531 #include <linux/unistd.h>
2532 #include <asm/uaccess.h>
2533
2534 static int errno; 
2535
2536 static int
2537 wavefront_download_firmware (char *path)
2538
2539 {
2540         unsigned char section[WF_SECTION_MAX];
2541         char section_length; /* yes, just a char; max value is WF_SECTION_MAX */
2542         int section_cnt_downloaded = 0;
2543         int fd;
2544         int c;
2545         int i;
2546         mm_segment_t fs;
2547
2548         /* This tries to be a bit cleverer than the stuff Alan Cox did for
2549            the generic sound firmware, in that it actually knows
2550            something about the structure of the Motorola firmware. In
2551            particular, it uses a version that has been stripped of the
2552            20K of useless header information, and had section lengths
2553            added, making it possible to load the entire OS without any
2554            [kv]malloc() activity, since the longest entity we ever read is
2555            42 bytes (well, WF_SECTION_MAX) long.
2556         */
2557
2558         fs = get_fs();
2559         set_fs (get_ds());
2560
2561         if ((fd = open (path, 0, 0)) < 0) {
2562                 printk (KERN_WARNING LOGNAME "Unable to load \"%s\".\n",
2563                         path);
2564                 return 1;
2565         }
2566
2567         while (1) {
2568                 int x;
2569
2570                 if ((x = read (fd, &section_length, sizeof (section_length))) !=
2571                     sizeof (section_length)) {
2572                         printk (KERN_ERR LOGNAME "firmware read error.\n");
2573                         goto failure;
2574                 }
2575
2576                 if (section_length == 0) {
2577                         break;
2578                 }
2579
2580                 if (read (fd, section, section_length) != section_length) {
2581                         printk (KERN_ERR LOGNAME "firmware section "
2582                                 "read error.\n");
2583                         goto failure;
2584                 }
2585
2586                 /* Send command */
2587         
2588                 if (wavefront_write (WFC_DOWNLOAD_OS)) {
2589                         goto failure;
2590                 }
2591         
2592                 for (i = 0; i < section_length; i++) {
2593                         if (wavefront_write (section[i])) {
2594                                 goto failure;
2595                         }
2596                 }
2597         
2598                 /* get ACK */
2599         
2600                 if (wavefront_wait (STAT_CAN_READ)) {
2601
2602                         if ((c = inb (dev.data_port)) != WF_ACK) {
2603
2604                                 printk (KERN_ERR LOGNAME "download "
2605                                         "of section #%d not "
2606                                         "acknowledged, ack = 0x%x\n",
2607                                         section_cnt_downloaded + 1, c);
2608                                 goto failure;
2609                 
2610                         }
2611
2612                 } else {
2613                         printk (KERN_ERR LOGNAME "time out for firmware ACK.\n");
2614                         goto failure;
2615                 }
2616
2617         }
2618
2619         close (fd);
2620         set_fs (fs);
2621         return 0;
2622
2623  failure:
2624         close (fd);
2625         set_fs (fs);
2626         printk (KERN_ERR "\nWaveFront: firmware download failed!!!\n");
2627         return 1;
2628 }
2629
2630 static int __init wavefront_config_midi (void)
2631 {
2632         unsigned char rbuf[4], wbuf[4];
2633     
2634         if (detect_wf_mpu (dev.irq, dev.base) < 0) {
2635                 printk (KERN_WARNING LOGNAME
2636                         "could not find working MIDI device\n");
2637                 return -1;
2638         } 
2639
2640         if ((dev.mididev = install_wf_mpu ()) < 0) {
2641                 printk (KERN_WARNING LOGNAME
2642                         "MIDI interfaces not configured\n");
2643                 return -1;
2644         }
2645
2646         /* Route external MIDI to WaveFront synth (by default) */
2647     
2648         if (wavefront_cmd (WFC_MISYNTH_ON, rbuf, wbuf)) {
2649                 printk (KERN_WARNING LOGNAME
2650                         "cannot enable MIDI-IN to synth routing.\n");
2651                 /* XXX error ? */
2652         }
2653
2654
2655 #if OSS_SUPPORT_LEVEL & OSS_SUPPORT_SEQ
2656         /* Get the regular MIDI patch loading function, so we can
2657            use it if we ever get handed a SYSEX patch. This is
2658            unlikely, because its so damn slow, but we may as well
2659            leave this functionality from maui.c behind, since it
2660            could be useful for sequencer applications that can
2661            only use MIDI to do patch loading.
2662         */
2663
2664         if (midi_devs[dev.mididev]->converter != NULL) {
2665                 midi_load_patch = midi_devs[dev.mididev]->converter->load_patch;
2666                 midi_devs[dev.mididev]->converter->load_patch =
2667                     &wavefront_oss_load_patch;
2668         }
2669
2670 #endif /* OSS_SUPPORT_SEQ */
2671         
2672         /* Turn on Virtual MIDI, but first *always* turn it off,
2673            since otherwise consectutive reloads of the driver will
2674            never cause the hardware to generate the initial "internal" or 
2675            "external" source bytes in the MIDI data stream. This
2676            is pretty important, since the internal hardware generally will
2677            be used to generate none or very little MIDI output, and
2678            thus the only source of MIDI data is actually external. Without
2679            the switch bytes, the driver will think it all comes from
2680            the internal interface. Duh.
2681         */
2682
2683         if (wavefront_cmd (WFC_VMIDI_OFF, rbuf, wbuf)) { 
2684                 printk (KERN_WARNING LOGNAME
2685                         "virtual MIDI mode not disabled\n");
2686                 return 0; /* We're OK, but missing the external MIDI dev */
2687         }
2688
2689         if ((dev.ext_mididev = virtual_midi_enable ()) < 0) {
2690                 printk (KERN_WARNING LOGNAME "no virtual MIDI access.\n");
2691         } else {
2692                 if (wavefront_cmd (WFC_VMIDI_ON, rbuf, wbuf)) {
2693                         printk (KERN_WARNING LOGNAME
2694                                 "cannot enable virtual MIDI mode.\n");
2695                         virtual_midi_disable ();
2696                 } 
2697         }
2698     
2699         return 0;
2700 }
2701
2702 static int __init wavefront_do_reset (int atboot)
2703 {
2704         char voices[1];
2705
2706         if (!atboot && wavefront_hw_reset ()) {
2707                 printk (KERN_WARNING LOGNAME "hw reset failed.\n");
2708                 goto gone_bad;