1/* Copyright (C) by Paul Barton-Davis 1998-1999
2 *
3 * Some portions of this file are taken from work that is
4 * copyright (C) by Hannu Savolainen 1993-1996
5 *
6 * This program is distributed under the GNU GENERAL PUBLIC LICENSE (GPL)
7 * Version 2 (June 1991). See the "COPYING" file distributed with this software
8 * for more info.
9 */
10
11/*
12 * An ALSA lowlevel driver for Turtle Beach ICS2115 wavetable synth
13 *                                             (Maui, Tropez, Tropez Plus)
14 *
15 * This driver supports the onboard wavetable synthesizer (an ICS2115),
16 * including patch, sample and program loading and unloading, conversion
17 * of GUS patches during loading, and full user-level access to all
18 * WaveFront commands. It tries to provide semi-intelligent patch and
19 * sample management as well.
20 *
21 */
22
23#include <linux/io.h>
24#include <linux/interrupt.h>
25#include <linux/init.h>
26#include <linux/delay.h>
27#include <linux/time.h>
28#include <linux/wait.h>
29#include <linux/firmware.h>
30#include <linux/moduleparam.h>
31#include <linux/slab.h>
32#include <linux/module.h>
33#include <sound/core.h>
34#include <sound/snd_wavefront.h>
35#include <sound/initval.h>
36
37static int wf_raw = 0; /* we normally check for "raw state" to firmware
38			  loading. if non-zero, then during driver loading, the
39			  state of the board is ignored, and we reset the
40			  board and load the firmware anyway.
41		       */
42
43static int fx_raw = 1; /* if this is zero, we'll leave the FX processor in
44			  whatever state it is when the driver is loaded.
45			  The default is to download the microprogram and
46			  associated coefficients to set it up for "default"
47			  operation, whatever that means.
48		       */
49
50static int debug_default = 0;  /* you can set this to control debugging
51				  during driver loading. it takes any combination
52				  of the WF_DEBUG_* flags defined in
53				  wavefront.h
54			       */
55
56/* XXX this needs to be made firmware and hardware version dependent */
57
58#define DEFAULT_OSPATH	"wavefront.os"
59static char *ospath = DEFAULT_OSPATH; /* the firmware file name */
60
61static int wait_usecs = 150; /* This magic number seems to give pretty optimal
62				throughput based on my limited experimentation.
63				If you want to play around with it and find a better
64				value, be my guest. Remember, the idea is to
65				get a number that causes us to just busy wait
66				for as many WaveFront commands as possible, without
67				coming up with a number so large that we hog the
68				whole CPU.
69
70				Specifically, with this number, out of about 134,000
71				status waits, only about 250 result in a sleep.
72			    */
73
74static int sleep_interval = 100;   /* HZ/sleep_interval seconds per sleep */
75static int sleep_tries = 50;       /* number of times we'll try to sleep */
76
77static int reset_time = 2;        /* hundreths of a second we wait after a HW
78				     reset for the expected interrupt.
79				  */
80
81static int ramcheck_time = 20;    /* time in seconds to wait while ROM code
82				     checks on-board RAM.
83				  */
84
85static int osrun_time = 10;       /* time in seconds we wait for the OS to
86				     start running.
87				  */
88module_param(wf_raw, int, 0444);
89MODULE_PARM_DESC(wf_raw, "if non-zero, assume that we need to boot the OS");
90module_param(fx_raw, int, 0444);
91MODULE_PARM_DESC(fx_raw, "if non-zero, assume that the FX process needs help");
92module_param(debug_default, int, 0444);
93MODULE_PARM_DESC(debug_default, "debug parameters for card initialization");
94module_param(wait_usecs, int, 0444);
95MODULE_PARM_DESC(wait_usecs, "how long to wait without sleeping, usecs");
96module_param(sleep_interval, int, 0444);
97MODULE_PARM_DESC(sleep_interval, "how long to sleep when waiting for reply");
98module_param(sleep_tries, int, 0444);
99MODULE_PARM_DESC(sleep_tries, "how many times to try sleeping during a wait");
100module_param(ospath, charp, 0444);
101MODULE_PARM_DESC(ospath, "pathname to processed ICS2115 OS firmware");
102module_param(reset_time, int, 0444);
103MODULE_PARM_DESC(reset_time, "how long to wait for a reset to take effect");
104module_param(ramcheck_time, int, 0444);
105MODULE_PARM_DESC(ramcheck_time, "how many seconds to wait for the RAM test");
106module_param(osrun_time, int, 0444);
107MODULE_PARM_DESC(osrun_time, "how many seconds to wait for the ICS2115 OS");
108
109/* if WF_DEBUG not defined, no run-time debugging messages will
110   be available via the debug flag setting. Given the current
111   beta state of the driver, this will remain set until a future
112   version.
113*/
114
115#define WF_DEBUG 1
116
117#ifdef WF_DEBUG
118
119#define DPRINT(cond, ...) \
120       if ((dev->debug & (cond)) == (cond)) { \
121	     snd_printk (__VA_ARGS__); \
122       }
123#else
124#define DPRINT(cond, args...)
125#endif /* WF_DEBUG */
126
127#define LOGNAME "WaveFront: "
128
129/* bitmasks for WaveFront status port value */
130
131#define STAT_RINTR_ENABLED	0x01
132#define STAT_CAN_READ		0x02
133#define STAT_INTR_READ		0x04
134#define STAT_WINTR_ENABLED	0x10
135#define STAT_CAN_WRITE		0x20
136#define STAT_INTR_WRITE		0x40
137
138static int wavefront_delete_sample (snd_wavefront_t *, int sampnum);
139static int wavefront_find_free_sample (snd_wavefront_t *);
140
141struct wavefront_command {
142	int cmd;
143	char *action;
144	unsigned int read_cnt;
145	unsigned int write_cnt;
146	int need_ack;
147};
148
149static struct {
150	int errno;
151	const char *errstr;
152} wavefront_errors[] = {
153	{ 0x01, "Bad sample number" },
154	{ 0x02, "Out of sample memory" },
155	{ 0x03, "Bad patch number" },
156	{ 0x04, "Error in number of voices" },
157	{ 0x06, "Sample load already in progress" },
158	{ 0x0B, "No sample load request pending" },
159	{ 0x0E, "Bad MIDI channel number" },
160	{ 0x10, "Download Record Error" },
161	{ 0x80, "Success" },
162	{ 0x0 }
163};
164
165#define NEEDS_ACK 1
166
167static struct wavefront_command wavefront_commands[] = {
168	{ WFC_SET_SYNTHVOL, "set synthesizer volume", 0, 1, NEEDS_ACK },
169	{ WFC_GET_SYNTHVOL, "get synthesizer volume", 1, 0, 0},
170	{ WFC_SET_NVOICES, "set number of voices", 0, 1, NEEDS_ACK },
171	{ WFC_GET_NVOICES, "get number of voices", 1, 0, 0 },
172	{ WFC_SET_TUNING, "set synthesizer tuning", 0, 2, NEEDS_ACK },
173	{ WFC_GET_TUNING, "get synthesizer tuning", 2, 0, 0 },
174	{ WFC_DISABLE_CHANNEL, "disable synth channel", 0, 1, NEEDS_ACK },
175	{ WFC_ENABLE_CHANNEL, "enable synth channel", 0, 1, NEEDS_ACK },
176	{ WFC_GET_CHANNEL_STATUS, "get synth channel status", 3, 0, 0 },
177	{ WFC_MISYNTH_OFF, "disable midi-in to synth", 0, 0, NEEDS_ACK },
178	{ WFC_MISYNTH_ON, "enable midi-in to synth", 0, 0, NEEDS_ACK },
179	{ WFC_VMIDI_ON, "enable virtual midi mode", 0, 0, NEEDS_ACK },
180	{ WFC_VMIDI_OFF, "disable virtual midi mode", 0, 0, NEEDS_ACK },
181	{ WFC_MIDI_STATUS, "report midi status", 1, 0, 0 },
182	{ WFC_FIRMWARE_VERSION, "report firmware version", 2, 0, 0 },
183	{ WFC_HARDWARE_VERSION, "report hardware version", 2, 0, 0 },
184	{ WFC_GET_NSAMPLES, "report number of samples", 2, 0, 0 },
185	{ WFC_INSTOUT_LEVELS, "report instantaneous output levels", 7, 0, 0 },
186	{ WFC_PEAKOUT_LEVELS, "report peak output levels", 7, 0, 0 },
187	{ WFC_DOWNLOAD_SAMPLE, "download sample",
188	  0, WF_SAMPLE_BYTES, NEEDS_ACK },
189	{ WFC_DOWNLOAD_BLOCK, "download block", 0, 0, NEEDS_ACK},
190	{ WFC_DOWNLOAD_SAMPLE_HEADER, "download sample header",
191	  0, WF_SAMPLE_HDR_BYTES, NEEDS_ACK },
192	{ WFC_UPLOAD_SAMPLE_HEADER, "upload sample header", 13, 2, 0 },
193
194	/* This command requires a variable number of bytes to be written.
195	   There is a hack in snd_wavefront_cmd() to support this. The actual
196	   count is passed in as the read buffer ptr, cast appropriately.
197	   Ugh.
198	*/
199
200	{ WFC_DOWNLOAD_MULTISAMPLE, "download multisample", 0, 0, NEEDS_ACK },
201
202	/* This one is a hack as well. We just read the first byte of the
203	   response, don't fetch an ACK, and leave the rest to the
204	   calling function. Ugly, ugly, ugly.
205	*/
206
207	{ WFC_UPLOAD_MULTISAMPLE, "upload multisample", 2, 1, 0 },
208	{ WFC_DOWNLOAD_SAMPLE_ALIAS, "download sample alias",
209	  0, WF_ALIAS_BYTES, NEEDS_ACK },
210	{ WFC_UPLOAD_SAMPLE_ALIAS, "upload sample alias", WF_ALIAS_BYTES, 2, 0},
211	{ WFC_DELETE_SAMPLE, "delete sample", 0, 2, NEEDS_ACK },
212	{ WFC_IDENTIFY_SAMPLE_TYPE, "identify sample type", 5, 2, 0 },
213	{ WFC_UPLOAD_SAMPLE_PARAMS, "upload sample parameters" },
214	{ WFC_REPORT_FREE_MEMORY, "report free memory", 4, 0, 0 },
215	{ WFC_DOWNLOAD_PATCH, "download patch", 0, 134, NEEDS_ACK },
216	{ WFC_UPLOAD_PATCH, "upload patch", 132, 2, 0 },
217	{ WFC_DOWNLOAD_PROGRAM, "download program", 0, 33, NEEDS_ACK },
218	{ WFC_UPLOAD_PROGRAM, "upload program", 32, 1, 0 },
219	{ WFC_DOWNLOAD_EDRUM_PROGRAM, "download enhanced drum program", 0, 9,
220	  NEEDS_ACK},
221	{ WFC_UPLOAD_EDRUM_PROGRAM, "upload enhanced drum program", 8, 1, 0},
222	{ WFC_SET_EDRUM_CHANNEL, "set enhanced drum program channel",
223	  0, 1, NEEDS_ACK },
224	{ WFC_DISABLE_DRUM_PROGRAM, "disable drum program", 0, 1, NEEDS_ACK },
225	{ WFC_REPORT_CHANNEL_PROGRAMS, "report channel program numbers",
226	  32, 0, 0 },
227	{ WFC_NOOP, "the no-op command", 0, 0, NEEDS_ACK },
228	{ 0x00 }
229};
230
231static const char *
232wavefront_errorstr (int errnum)
233
234{
235	int i;
236
237	for (i = 0; wavefront_errors[i].errstr; i++) {
238		if (wavefront_errors[i].errno == errnum) {
239			return wavefront_errors[i].errstr;
240		}
241	}
242
243	return "Unknown WaveFront error";
244}
245
246static struct wavefront_command *
247wavefront_get_command (int cmd)
248
249{
250	int i;
251
252	for (i = 0; wavefront_commands[i].cmd != 0; i++) {
253		if (cmd == wavefront_commands[i].cmd) {
254			return &wavefront_commands[i];
255		}
256	}
257
258	return NULL;
259}
260
261static inline int
262wavefront_status (snd_wavefront_t *dev)
263
264{
265	return inb (dev->status_port);
266}
267
268static int
269wavefront_sleep (int limit)
270
271{
272	schedule_timeout_interruptible(limit);
273
274	return signal_pending(current);
275}
276
277static int
278wavefront_wait (snd_wavefront_t *dev, int mask)
279
280{
281	int             i;
282
283	/* Spin for a short period of time, because >99% of all
284	   requests to the WaveFront can be serviced inline like this.
285	*/
286
287	for (i = 0; i < wait_usecs; i += 5) {
288		if (wavefront_status (dev) & mask) {
289			return 1;
290		}
291		udelay(5);
292	}
293
294	for (i = 0; i < sleep_tries; i++) {
295
296		if (wavefront_status (dev) & mask) {
297			return 1;
298		}
299
300		if (wavefront_sleep (HZ/sleep_interval)) {
301			return (0);
302		}
303	}
304
305	return (0);
306}
307
308static int
309wavefront_read (snd_wavefront_t *dev)
310
311{
312	if (wavefront_wait (dev, STAT_CAN_READ))
313		return inb (dev->data_port);
314
315	DPRINT (WF_DEBUG_DATA, "read timeout.\n");
316
317	return -1;
318}
319
320static int
321wavefront_write (snd_wavefront_t *dev, unsigned char data)
322
323{
324	if (wavefront_wait (dev, STAT_CAN_WRITE)) {
325		outb (data, dev->data_port);
326		return 0;
327	}
328
329	DPRINT (WF_DEBUG_DATA, "write timeout.\n");
330
331	return -1;
332}
333
334int
335snd_wavefront_cmd (snd_wavefront_t *dev,
336		   int cmd, unsigned char *rbuf, unsigned char *wbuf)
337
338{
339	int ack;
340	unsigned int i;
341	int c;
342	struct wavefront_command *wfcmd;
343
344	if ((wfcmd = wavefront_get_command (cmd)) == NULL) {
345		snd_printk ("command 0x%x not supported.\n",
346			cmd);
347		return 1;
348	}
349
350	/* Hack to handle the one variable-size write command. See
351	   wavefront_send_multisample() for the other half of this
352	   gross and ugly strategy.
353	*/
354
355	if (cmd == WFC_DOWNLOAD_MULTISAMPLE) {
356		wfcmd->write_cnt = (unsigned long) rbuf;
357		rbuf = NULL;
358	}
359
360	DPRINT (WF_DEBUG_CMD, "0x%x [%s] (%d,%d,%d)\n",
361			       cmd, wfcmd->action, wfcmd->read_cnt,
362			       wfcmd->write_cnt, wfcmd->need_ack);
363
364	if (wavefront_write (dev, cmd)) {
365		DPRINT ((WF_DEBUG_IO|WF_DEBUG_CMD), "cannot request "
366						     "0x%x [%s].\n",
367						     cmd, wfcmd->action);
368		return 1;
369	}
370
371	if (wfcmd->write_cnt > 0) {
372		DPRINT (WF_DEBUG_DATA, "writing %d bytes "
373					"for 0x%x\n",
374					wfcmd->write_cnt, cmd);
375
376		for (i = 0; i < wfcmd->write_cnt; i++) {
377			if (wavefront_write (dev, wbuf[i])) {
378				DPRINT (WF_DEBUG_IO, "bad write for byte "
379						      "%d of 0x%x [%s].\n",
380						      i, cmd, wfcmd->action);
381				return 1;
382			}
383
384			DPRINT (WF_DEBUG_DATA, "write[%d] = 0x%x\n",
385						i, wbuf[i]);
386		}
387	}
388
389	if (wfcmd->read_cnt > 0) {
390		DPRINT (WF_DEBUG_DATA, "reading %d ints "
391					"for 0x%x\n",
392					wfcmd->read_cnt, cmd);
393
394		for (i = 0; i < wfcmd->read_cnt; i++) {
395
396			if ((c = wavefront_read (dev)) == -1) {
397				DPRINT (WF_DEBUG_IO, "bad read for byte "
398						      "%d of 0x%x [%s].\n",
399						      i, cmd, wfcmd->action);
400				return 1;
401			}
402
403			/* Now handle errors. Lots of special cases here */
404
405			if (c == 0xff) {
406				if ((c = wavefront_read (dev)) == -1) {
407					DPRINT (WF_DEBUG_IO, "bad read for "
408							      "error byte at "
409							      "read byte %d "
410							      "of 0x%x [%s].\n",
411							      i, cmd,
412							      wfcmd->action);
413					return 1;
414				}
415
416				/* Can you believe this madness ? */
417
418				if (c == 1 &&
419				    wfcmd->cmd == WFC_IDENTIFY_SAMPLE_TYPE) {
420					rbuf[0] = WF_ST_EMPTY;
421					return (0);
422
423				} else if (c == 3 &&
424					   wfcmd->cmd == WFC_UPLOAD_PATCH) {
425
426					return 3;
427
428				} else if (c == 1 &&
429					   wfcmd->cmd == WFC_UPLOAD_PROGRAM) {
430
431					return 1;
432
433				} else {
434
435					DPRINT (WF_DEBUG_IO, "error %d (%s) "
436							      "during "
437							      "read for byte "
438							      "%d of 0x%x "
439							      "[%s].\n",
440							      c,
441							      wavefront_errorstr (c),
442							      i, cmd,
443							      wfcmd->action);
444					return 1;
445
446				}
447
448		} else {
449				rbuf[i] = c;
450			}
451
452			DPRINT (WF_DEBUG_DATA, "read[%d] = 0x%x\n",i, rbuf[i]);
453		}
454	}
455
456	if ((wfcmd->read_cnt == 0 && wfcmd->write_cnt == 0) || wfcmd->need_ack) {
457
458		DPRINT (WF_DEBUG_CMD, "reading ACK for 0x%x\n", cmd);
459
460		/* Some commands need an ACK, but return zero instead
461		   of the standard value.
462		*/
463
464		if ((ack = wavefront_read (dev)) == 0) {
465			ack = WF_ACK;
466		}
467
468		if (ack != WF_ACK) {
469			if (ack == -1) {
470				DPRINT (WF_DEBUG_IO, "cannot read ack for "
471						      "0x%x [%s].\n",
472						      cmd, wfcmd->action);
473				return 1;
474
475			} else {
476				int err = -1; /* something unknown */
477
478				if (ack == 0xff) { /* explicit error */
479
480					if ((err = wavefront_read (dev)) == -1) {
481						DPRINT (WF_DEBUG_DATA,
482							"cannot read err "
483							"for 0x%x [%s].\n",
484							cmd, wfcmd->action);
485					}
486				}
487
488				DPRINT (WF_DEBUG_IO, "0x%x [%s] "
489					"failed (0x%x, 0x%x, %s)\n",
490					cmd, wfcmd->action, ack, err,
491					wavefront_errorstr (err));
492
493				return -err;
494			}
495		}
496
497		DPRINT (WF_DEBUG_DATA, "ack received "
498					"for 0x%x [%s]\n",
499					cmd, wfcmd->action);
500	} else {
501
502		DPRINT (WF_DEBUG_CMD, "0x%x [%s] does not need "
503				       "ACK (%d,%d,%d)\n",
504				       cmd, wfcmd->action, wfcmd->read_cnt,
505				       wfcmd->write_cnt, wfcmd->need_ack);
506	}
507
508	return 0;
509
510}
511
512/***********************************************************************
513WaveFront data munging
514
515Things here are weird. All data written to the board cannot
516have its most significant bit set. Any data item with values
517potentially > 0x7F (127) must be split across multiple bytes.
518
519Sometimes, we need to munge numeric values that are represented on
520the x86 side as 8-32 bit values. Sometimes, we need to munge data
521that is represented on the x86 side as an array of bytes. The most
522efficient approach to handling both cases seems to be to use 2
523different functions for munging and 2 for de-munging. This avoids
524weird casting and worrying about bit-level offsets.
525
526**********************************************************************/
527
528static unsigned char *
529munge_int32 (unsigned int src,
530	     unsigned char *dst,
531	     unsigned int dst_size)
532{
533	unsigned int i;
534
535	for (i = 0; i < dst_size; i++) {
536		*dst = src & 0x7F;  /* Mask high bit of LSB */
537		src = src >> 7;     /* Rotate Right 7 bits  */
538	                            /* Note: we leave the upper bits in place */
539
540		dst++;
541	}
542	return dst;
543};
544
545static int
546demunge_int32 (unsigned char* src, int src_size)
547
548{
549	int i;
550 	int outval = 0;
551
552 	for (i = src_size - 1; i >= 0; i--) {
553		outval=(outval<<7)+src[i];
554	}
555
556	return outval;
557};
558
559static
560unsigned char *
561munge_buf (unsigned char *src, unsigned char *dst, unsigned int dst_size)
562
563{
564	unsigned int i;
565	unsigned int last = dst_size / 2;
566
567	for (i = 0; i < last; i++) {
568		*dst++ = src[i] & 0x7f;
569		*dst++ = src[i] >> 7;
570	}
571	return dst;
572}
573
574static
575unsigned char *
576demunge_buf (unsigned char *src, unsigned char *dst, unsigned int src_bytes)
577
578{
579	int i;
580	unsigned char *end = src + src_bytes;
581
582	end = src + src_bytes;
583
584	/* NOTE: src and dst *CAN* point to the same address */
585
586	for (i = 0; src != end; i++) {
587		dst[i] = *src++;
588		dst[i] |= (*src++)<<7;
589	}
590
591	return dst;
592}
593
594/***********************************************************************
595WaveFront: sample, patch and program management.
596***********************************************************************/
597
598static int
599wavefront_delete_sample (snd_wavefront_t *dev, int sample_num)
600
601{
602	unsigned char wbuf[2];
603	int x;
604
605	wbuf[0] = sample_num & 0x7f;
606	wbuf[1] = sample_num >> 7;
607
608	if ((x = snd_wavefront_cmd (dev, WFC_DELETE_SAMPLE, NULL, wbuf)) == 0) {
609		dev->sample_status[sample_num] = WF_ST_EMPTY;
610	}
611
612	return x;
613}
614
615static int
616wavefront_get_sample_status (snd_wavefront_t *dev, int assume_rom)
617
618{
619	int i;
620	unsigned char rbuf[32], wbuf[32];
621	unsigned int    sc_real, sc_alias, sc_multi;
622
623	/* check sample status */
624
625	if (snd_wavefront_cmd (dev, WFC_GET_NSAMPLES, rbuf, wbuf)) {
626		snd_printk ("cannot request sample count.\n");
627		return -1;
628	}
629
630	sc_real = sc_alias = sc_multi = dev->samples_used = 0;
631
632	for (i = 0; i < WF_MAX_SAMPLE; i++) {
633
634		wbuf[0] = i & 0x7f;
635		wbuf[1] = i >> 7;
636
637		if (snd_wavefront_cmd (dev, WFC_IDENTIFY_SAMPLE_TYPE, rbuf, wbuf)) {
638			snd_printk(KERN_WARNING "cannot identify sample "
639				   "type of slot %d\n", i);
640			dev->sample_status[i] = WF_ST_EMPTY;
641			continue;
642		}
643
644		dev->sample_status[i] = (WF_SLOT_FILLED|rbuf[0]);
645
646		if (assume_rom) {
647			dev->sample_status[i] |= WF_SLOT_ROM;
648		}
649
650		switch (rbuf[0] & WF_ST_MASK) {
651		case WF_ST_SAMPLE:
652			sc_real++;
653			break;
654		case WF_ST_MULTISAMPLE:
655			sc_multi++;
656			break;
657		case WF_ST_ALIAS:
658			sc_alias++;
659			break;
660		case WF_ST_EMPTY:
661			break;
662
663		default:
664			snd_printk ("unknown sample type for "
665				    "slot %d (0x%x)\n",
666				    i, rbuf[0]);
667		}
668
669		if (rbuf[0] != WF_ST_EMPTY) {
670			dev->samples_used++;
671		}
672	}
673
674	snd_printk ("%d samples used (%d real, %d aliases, %d multi), "
675		    "%d empty\n", dev->samples_used, sc_real, sc_alias, sc_multi,
676		    WF_MAX_SAMPLE - dev->samples_used);
677
678
679	return (0);
680
681}
682
683static int
684wavefront_get_patch_status (snd_wavefront_t *dev)
685
686{
687	unsigned char patchbuf[WF_PATCH_BYTES];
688	unsigned char patchnum[2];
689	wavefront_patch *p;
690	int i, x, cnt, cnt2;
691
692	for (i = 0; i < WF_MAX_PATCH; i++) {
693		patchnum[0] = i & 0x7f;
694		patchnum[1] = i >> 7;
695
696		if ((x = snd_wavefront_cmd (dev, WFC_UPLOAD_PATCH, patchbuf,
697					patchnum)) == 0) {
698
699			dev->patch_status[i] |= WF_SLOT_FILLED;
700			p = (wavefront_patch *) patchbuf;
701			dev->sample_status
702				[p->sample_number|(p->sample_msb<<7)] |=
703				WF_SLOT_USED;
704
705		} else if (x == 3) { /* Bad patch number */
706			dev->patch_status[i] = 0;
707		} else {
708			snd_printk ("upload patch "
709				    "error 0x%x\n", x);
710			dev->patch_status[i] = 0;
711			return 1;
712		}
713	}
714
715	/* program status has already filled in slot_used bits */
716
717	for (i = 0, cnt = 0, cnt2 = 0; i < WF_MAX_PATCH; i++) {
718		if (dev->patch_status[i] & WF_SLOT_FILLED) {
719			cnt++;
720		}
721		if (dev->patch_status[i] & WF_SLOT_USED) {
722			cnt2++;
723		}
724
725	}
726	snd_printk ("%d patch slots filled, %d in use\n", cnt, cnt2);
727
728	return (0);
729}
730
731static int
732wavefront_get_program_status (snd_wavefront_t *dev)
733
734{
735	unsigned char progbuf[WF_PROGRAM_BYTES];
736	wavefront_program prog;
737	unsigned char prognum;
738	int i, x, l, cnt;
739
740	for (i = 0; i < WF_MAX_PROGRAM; i++) {
741		prognum = i;
742
743		if ((x = snd_wavefront_cmd (dev, WFC_UPLOAD_PROGRAM, progbuf,
744					&prognum)) == 0) {
745
746			dev->prog_status[i] |= WF_SLOT_USED;
747
748			demunge_buf (progbuf, (unsigned char *) &prog,
749				     WF_PROGRAM_BYTES);
750
751			for (l = 0; l < WF_NUM_LAYERS; l++) {
752				if (prog.layer[l].mute) {
753					dev->patch_status
754						[prog.layer[l].patch_number] |=
755						WF_SLOT_USED;
756				}
757			}
758		} else if (x == 1) { /* Bad program number */
759			dev->prog_status[i] = 0;
760		} else {
761			snd_printk ("upload program "
762				    "error 0x%x\n", x);
763			dev->prog_status[i] = 0;
764		}
765	}
766
767	for (i = 0, cnt = 0; i < WF_MAX_PROGRAM; i++) {
768		if (dev->prog_status[i]) {
769			cnt++;
770		}
771	}
772
773	snd_printk ("%d programs slots in use\n", cnt);
774
775	return (0);
776}
777
778static int
779wavefront_send_patch (snd_wavefront_t *dev, wavefront_patch_info *header)
780
781{
782	unsigned char buf[WF_PATCH_BYTES+2];
783	unsigned char *bptr;
784
785	DPRINT (WF_DEBUG_LOAD_PATCH, "downloading patch %d\n",
786				      header->number);
787
788	dev->patch_status[header->number] |= WF_SLOT_FILLED;
789
790	bptr = buf;
791	bptr = munge_int32 (header->number, buf, 2);
792	munge_buf ((unsigned char *)&header->hdr.p, bptr, WF_PATCH_BYTES);
793
794	if (snd_wavefront_cmd (dev, WFC_DOWNLOAD_PATCH, NULL, buf)) {
795		snd_printk ("download patch failed\n");
796		return -EIO;
797	}
798
799	return (0);
800}
801
802static int
803wavefront_send_program (snd_wavefront_t *dev, wavefront_patch_info *header)
804
805{
806	unsigned char buf[WF_PROGRAM_BYTES+1];
807	int i;
808
809	DPRINT (WF_DEBUG_LOAD_PATCH, "downloading program %d\n",
810		header->number);
811
812	dev->prog_status[header->number] = WF_SLOT_USED;
813
814	/* XXX need to zero existing SLOT_USED bit for program_status[i]
815	   where `i' is the program that's being (potentially) overwritten.
816	*/
817
818	for (i = 0; i < WF_NUM_LAYERS; i++) {
819		if (header->hdr.pr.layer[i].mute) {
820			dev->patch_status[header->hdr.pr.layer[i].patch_number] |=
821				WF_SLOT_USED;
822
823			/* XXX need to mark SLOT_USED for sample used by
824			   patch_number, but this means we have to load it. Ick.
825			*/
826		}
827	}
828
829	buf[0] = header->number;
830	munge_buf ((unsigned char *)&header->hdr.pr, &buf[1], WF_PROGRAM_BYTES);
831
832	if (snd_wavefront_cmd (dev, WFC_DOWNLOAD_PROGRAM, NULL, buf)) {
833		snd_printk ("download patch failed\n");
834		return -EIO;
835	}
836
837	return (0);
838}
839
840static int
841wavefront_freemem (snd_wavefront_t *dev)
842
843{
844	char rbuf[8];
845
846	if (snd_wavefront_cmd (dev, WFC_REPORT_FREE_MEMORY, rbuf, NULL)) {
847		snd_printk ("can't get memory stats.\n");
848		return -1;
849	} else {
850		return demunge_int32 (rbuf, 4);
851	}
852}
853
854static int
855wavefront_send_sample (snd_wavefront_t *dev,
856		       wavefront_patch_info *header,
857		       u16 __user *dataptr,
858		       int data_is_unsigned)
859
860{
861	/* samples are downloaded via a 16-bit wide i/o port
862	   (you could think of it as 2 adjacent 8-bit wide ports
863	   but its less efficient that way). therefore, all
864	   the blocksizes and so forth listed in the documentation,
865	   and used conventionally to refer to sample sizes,
866	   which are given in 8-bit units (bytes), need to be
867	   divided by 2.
868        */
869
870	u16 sample_short = 0;
871	u32 length;
872	u16 __user *data_end = NULL;
873	unsigned int i;
874	const unsigned int max_blksize = 4096/2;
875	unsigned int written;
876	unsigned int blocksize;
877	int dma_ack;
878	int blocknum;
879	unsigned char sample_hdr[WF_SAMPLE_HDR_BYTES];
880	unsigned char *shptr;
881	int skip = 0;
882	int initial_skip = 0;
883
884	DPRINT (WF_DEBUG_LOAD_PATCH, "sample %sdownload for slot %d, "
885				      "type %d, %d bytes from 0x%lx\n",
886				      header->size ? "" : "header ",
887				      header->number, header->subkey,
888				      header->size,
889				      (unsigned long) header->dataptr);
890
891	if (header->number == WAVEFRONT_FIND_FREE_SAMPLE_SLOT) {
892		int x;
893
894		if ((x = wavefront_find_free_sample (dev)) < 0) {
895			return -ENOMEM;
896		}
897		snd_printk ("unspecified sample => %d\n", x);
898		header->number = x;
899	}
900
901	if (header->size) {
902
903		/* XXX it's a debatable point whether or not RDONLY semantics
904		   on the ROM samples should cover just the sample data or
905		   the sample header. For now, it only covers the sample data,
906		   so anyone is free at all times to rewrite sample headers.
907
908		   My reason for this is that we have the sample headers
909		   available in the WFB file for General MIDI, and so these
910		   can always be reset if needed. The sample data, however,
911		   cannot be recovered without a complete reset and firmware
912		   reload of the ICS2115, which is a very expensive operation.
913
914		   So, doing things this way allows us to honor the notion of
915		   "RESETSAMPLES" reasonably cheaply. Note however, that this
916		   is done purely at user level: there is no WFB parser in
917		   this driver, and so a complete reset (back to General MIDI,
918		   or theoretically some other configuration) is the
919		   responsibility of the user level library.
920
921		   To try to do this in the kernel would be a little
922		   crazy: we'd need 158K of kernel space just to hold
923		   a copy of the patch/program/sample header data.
924		*/
925
926		if (dev->rom_samples_rdonly) {
927			if (dev->sample_status[header->number] & WF_SLOT_ROM) {
928				snd_printk ("sample slot %d "
929					    "write protected\n",
930					    header->number);
931				return -EACCES;
932			}
933		}
934
935		wavefront_delete_sample (dev, header->number);
936	}
937
938	if (header->size) {
939		dev->freemem = wavefront_freemem (dev);
940
941		if (dev->freemem < (int)header->size) {
942			snd_printk ("insufficient memory to "
943				    "load %d byte sample.\n",
944				    header->size);
945			return -ENOMEM;
946		}
947
948	}
949
950	skip = WF_GET_CHANNEL(&header->hdr.s);
951
952	if (skip > 0 && header->hdr.s.SampleResolution != LINEAR_16BIT) {
953		snd_printk ("channel selection only "
954			    "possible on 16-bit samples");
955		return -EINVAL;
956	}
957
958	switch (skip) {
959	case 0:
960		initial_skip = 0;
961		skip = 1;
962		break;
963	case 1:
964		initial_skip = 0;
965		skip = 2;
966		break;
967	case 2:
968		initial_skip = 1;
969		skip = 2;
970		break;
971	case 3:
972		initial_skip = 2;
973		skip = 3;
974		break;
975	case 4:
976		initial_skip = 3;
977		skip = 4;
978		break;
979	case 5:
980		initial_skip = 4;
981		skip = 5;
982		break;
983	case 6:
984		initial_skip = 5;
985		skip = 6;
986		break;
987	}
988
989	DPRINT (WF_DEBUG_LOAD_PATCH, "channel selection: %d => "
990				      "initial skip = %d, skip = %d\n",
991				      WF_GET_CHANNEL (&header->hdr.s),
992				      initial_skip, skip);
993
994	/* Be safe, and zero the "Unused" bits ... */
995
996	WF_SET_CHANNEL(&header->hdr.s, 0);
997
998	/* adjust size for 16 bit samples by dividing by two.  We always
999	   send 16 bits per write, even for 8 bit samples, so the length
1000	   is always half the size of the sample data in bytes.
1001	*/
1002
1003	length = header->size / 2;
1004
1005	/* the data we're sent has not been munged, and in fact, the
1006	   header we have to send isn't just a munged copy either.
1007	   so, build the sample header right here.
1008	*/
1009
1010	shptr = &sample_hdr[0];
1011
1012	shptr = munge_int32 (header->number, shptr, 2);
1013
1014	if (header->size) {
1015		shptr = munge_int32 (length, shptr, 4);
1016	}
1017
1018	/* Yes, a 4 byte result doesn't contain all of the offset bits,
1019	   but the offset only uses 24 bits.
1020	*/
1021
1022	shptr = munge_int32 (*((u32 *) &header->hdr.s.sampleStartOffset),
1023			     shptr, 4);
1024	shptr = munge_int32 (*((u32 *) &header->hdr.s.loopStartOffset),
1025			     shptr, 4);
1026	shptr = munge_int32 (*((u32 *) &header->hdr.s.loopEndOffset),
1027			     shptr, 4);
1028	shptr = munge_int32 (*((u32 *) &header->hdr.s.sampleEndOffset),
1029			     shptr, 4);
1030
1031	/* This one is truly weird. What kind of weirdo decided that in
1032	   a system dominated by 16 and 32 bit integers, they would use
1033	   a just 12 bits ?
1034	*/
1035
1036	shptr = munge_int32 (header->hdr.s.FrequencyBias, shptr, 3);
1037
1038	/* Why is this nybblified, when the MSB is *always* zero ?
1039	   Anyway, we can't take address of bitfield, so make a
1040	   good-faith guess at where it starts.
1041	*/
1042
1043	shptr = munge_int32 (*(&header->hdr.s.FrequencyBias+1),
1044			     shptr, 2);
1045
1046	if (snd_wavefront_cmd (dev,
1047			   header->size ?
1048			   WFC_DOWNLOAD_SAMPLE : WFC_DOWNLOAD_SAMPLE_HEADER,
1049			   NULL, sample_hdr)) {
1050		snd_printk ("sample %sdownload refused.\n",
1051			    header->size ? "" : "header ");
1052		return -EIO;
1053	}
1054
1055	if (header->size == 0) {
1056		goto sent; /* Sorry. Just had to have one somewhere */
1057	}
1058
1059	data_end = dataptr + length;
1060
1061	/* Do any initial skip over an unused channel's data */
1062
1063	dataptr += initial_skip;
1064
1065	for (written = 0, blocknum = 0;
1066	     written < length; written += max_blksize, blocknum++) {
1067
1068		if ((length - written) > max_blksize) {
1069			blocksize = max_blksize;
1070		} else {
1071			/* round to nearest 16-byte value */
1072			blocksize = ALIGN(length - written, 8);
1073		}
1074
1075		if (snd_wavefront_cmd (dev, WFC_DOWNLOAD_BLOCK, NULL, NULL)) {
1076			snd_printk ("download block "
1077				    "request refused.\n");
1078			return -EIO;
1079		}
1080
1081		for (i = 0; i < blocksize; i++) {
1082
1083			if (dataptr < data_end) {
1084
1085				__get_user (sample_short, dataptr);
1086				dataptr += skip;
1087
1088				if (data_is_unsigned) { /* GUS ? */
1089
1090					if (WF_SAMPLE_IS_8BIT(&header->hdr.s)) {
1091
1092						/* 8 bit sample
1093						 resolution, sign
1094						 extend both bytes.
1095						*/
1096
1097						((unsigned char*)
1098						 &sample_short)[0] += 0x7f;
1099						((unsigned char*)
1100						 &sample_short)[1] += 0x7f;
1101
1102					} else {
1103
1104						/* 16 bit sample
1105						 resolution, sign
1106						 extend the MSB.
1107						*/
1108
1109						sample_short += 0x7fff;
1110					}
1111				}
1112
1113			} else {
1114
1115				/* In padding section of final block:
1116
1117				   Don't fetch unsupplied data from
1118				   user space, just continue with
1119				   whatever the final value was.
1120				*/
1121			}
1122
1123			if (i < blocksize - 1) {
1124				outw (sample_short, dev->block_port);
1125			} else {
1126				outw (sample_short, dev->last_block_port);
1127			}
1128		}
1129
1130		/* Get "DMA page acknowledge", even though its really
1131		   nothing to do with DMA at all.
1132		*/
1133
1134		if ((dma_ack = wavefront_read (dev)) != WF_DMA_ACK) {
1135			if (dma_ack == -1) {
1136				snd_printk ("upload sample "
1137					    "DMA ack timeout\n");
1138				return -EIO;
1139			} else {
1140				snd_printk ("upload sample "
1141					    "DMA ack error 0x%x\n",
1142					    dma_ack);
1143				return -EIO;
1144			}
1145		}
1146	}
1147
1148	dev->sample_status[header->number] = (WF_SLOT_FILLED|WF_ST_SAMPLE);
1149
1150	/* Note, label is here because sending the sample header shouldn't
1151	   alter the sample_status info at all.
1152	*/
1153
1154 sent:
1155	return (0);
1156}
1157
1158static int
1159wavefront_send_alias (snd_wavefront_t *dev, wavefront_patch_info *header)
1160
1161{
1162	unsigned char alias_hdr[WF_ALIAS_BYTES];
1163
1164	DPRINT (WF_DEBUG_LOAD_PATCH, "download alias, %d is "
1165				      "alias for %d\n",
1166				      header->number,
1167				      header->hdr.a.OriginalSample);
1168
1169	munge_int32 (header->number, &alias_hdr[0], 2);
1170	munge_int32 (header->hdr.a.OriginalSample, &alias_hdr[2], 2);
1171	munge_int32 (*((unsigned int *)&header->hdr.a.sampleStartOffset),
1172		     &alias_hdr[4], 4);
1173	munge_int32 (*((unsigned int *)&header->hdr.a.loopStartOffset),
1174		     &alias_hdr[8], 4);
1175	munge_int32 (*((unsigned int *)&header->hdr.a.loopEndOffset),
1176		     &alias_hdr[12], 4);
1177	munge_int32 (*((unsigned int *)&header->hdr.a.sampleEndOffset),
1178		     &alias_hdr[16], 4);
1179	munge_int32 (header->hdr.a.FrequencyBias, &alias_hdr[20], 3);
1180	munge_int32 (*(&header->hdr.a.FrequencyBias+1), &alias_hdr[23], 2);
1181
1182	if (snd_wavefront_cmd (dev, WFC_DOWNLOAD_SAMPLE_ALIAS, NULL, alias_hdr)) {
1183		snd_printk ("download alias failed.\n");
1184		return -EIO;
1185	}
1186
1187	dev->sample_status[header->number] = (WF_SLOT_FILLED|WF_ST_ALIAS);
1188
1189	return (0);
1190}
1191
1192static int
1193wavefront_send_multisample (snd_wavefront_t *dev, wavefront_patch_info *header)
1194{
1195	int i;
1196	int num_samples;
1197	unsigned char *msample_hdr;
1198
1199	msample_hdr = kmalloc(WF_MSAMPLE_BYTES, GFP_KERNEL);
1200	if (! msample_hdr)
1201		return -ENOMEM;
1202
1203	munge_int32 (header->number, &msample_hdr[0], 2);
1204
1205	/* You'll recall at this point that the "number of samples" value
1206	   in a wavefront_multisample struct is actually the log2 of the
1207	   real number of samples.
1208	*/
1209
1210	num_samples = (1<<(header->hdr.ms.NumberOfSamples&7));
1211	msample_hdr[2] = (unsigned char) header->hdr.ms.NumberOfSamples;
1212
1213	DPRINT (WF_DEBUG_LOAD_PATCH, "multi %d with %d=%d samples\n",
1214				      header->number,
1215				      header->hdr.ms.NumberOfSamples,
1216				      num_samples);
1217
1218	for (i = 0; i < num_samples; i++) {
1219		DPRINT(WF_DEBUG_LOAD_PATCH|WF_DEBUG_DATA, "sample[%d] = %d\n",
1220		       i, header->hdr.ms.SampleNumber[i]);
1221		munge_int32 (header->hdr.ms.SampleNumber[i],
1222		     &msample_hdr[3+(i*2)], 2);
1223	}
1224
1225	/* Need a hack here to pass in the number of bytes
1226	   to be written to the synth. This is ugly, and perhaps
1227	   one day, I'll fix it.
1228	*/
1229
1230	if (snd_wavefront_cmd (dev, WFC_DOWNLOAD_MULTISAMPLE,
1231			   (unsigned char *) (long) ((num_samples*2)+3),
1232			   msample_hdr)) {
1233		snd_printk ("download of multisample failed.\n");
1234		kfree(msample_hdr);
1235		return -EIO;
1236	}
1237
1238	dev->sample_status[header->number] = (WF_SLOT_FILLED|WF_ST_MULTISAMPLE);
1239
1240	kfree(msample_hdr);
1241	return (0);
1242}
1243
1244static int
1245wavefront_fetch_multisample (snd_wavefront_t *dev,
1246			     wavefront_patch_info *header)
1247{
1248	int i;
1249	unsigned char log_ns[1];
1250	unsigned char number[2];
1251	int num_samples;
1252
1253	munge_int32 (header->number, number, 2);
1254
1255	if (snd_wavefront_cmd (dev, WFC_UPLOAD_MULTISAMPLE, log_ns, number)) {
1256		snd_printk ("upload multisample failed.\n");
1257		return -EIO;
1258	}
1259
1260	DPRINT (WF_DEBUG_DATA, "msample %d has %d samples\n",
1261				header->number, log_ns[0]);
1262
1263	header->hdr.ms.NumberOfSamples = log_ns[0];
1264
1265	/* get the number of samples ... */
1266
1267	num_samples = (1 << log_ns[0]);
1268
1269	for (i = 0; i < num_samples; i++) {
1270		char d[2];
1271		int val;
1272
1273		if ((val = wavefront_read (dev)) == -1) {
1274			snd_printk ("upload multisample failed "
1275				    "during sample loop.\n");
1276			return -EIO;
1277		}
1278		d[0] = val;
1279
1280		if ((val = wavefront_read (dev)) == -1) {
1281			snd_printk ("upload multisample failed "
1282				    "during sample loop.\n");
1283			return -EIO;
1284		}
1285		d[1] = val;
1286
1287		header->hdr.ms.SampleNumber[i] =
1288			demunge_int32 ((unsigned char *) d, 2);
1289
1290		DPRINT (WF_DEBUG_DATA, "msample sample[%d] = %d\n",
1291					i, header->hdr.ms.SampleNumber[i]);
1292	}
1293
1294	return (0);
1295}
1296
1297
1298static int
1299wavefront_send_drum (snd_wavefront_t *dev, wavefront_patch_info *header)
1300
1301{
1302	unsigned char drumbuf[WF_DRUM_BYTES];
1303	wavefront_drum *drum = &header->hdr.d;
1304	int i;
1305
1306	DPRINT (WF_DEBUG_LOAD_PATCH, "downloading edrum for MIDI "
1307		"note %d, patch = %d\n",
1308		header->number, drum->PatchNumber);
1309
1310	drumbuf[0] = header->number & 0x7f;
1311
1312	for (i = 0; i < 4; i++) {
1313		munge_int32 (((unsigned char *)drum)[i], &drumbuf[1+(i*2)], 2);
1314	}
1315
1316	if (snd_wavefront_cmd (dev, WFC_DOWNLOAD_EDRUM_PROGRAM, NULL, drumbuf)) {
1317		snd_printk ("download drum failed.\n");
1318		return -EIO;
1319	}
1320
1321	return (0);
1322}
1323
1324static int
1325wavefront_find_free_sample (snd_wavefront_t *dev)
1326
1327{
1328	int i;
1329
1330	for (i = 0; i < WF_MAX_SAMPLE; i++) {
1331		if (!(dev->sample_status[i] & WF_SLOT_FILLED)) {
1332			return i;
1333		}
1334	}
1335	snd_printk ("no free sample slots!\n");
1336	return -1;
1337}
1338
1339#if 0
1340static int
1341wavefront_find_free_patch (snd_wavefront_t *dev)
1342
1343{
1344	int i;
1345
1346	for (i = 0; i < WF_MAX_PATCH; i++) {
1347		if (!(dev->patch_status[i] & WF_SLOT_FILLED)) {
1348			return i;
1349		}
1350	}
1351	snd_printk ("no free patch slots!\n");
1352	return -1;
1353}
1354#endif
1355
1356static int
1357wavefront_load_patch (snd_wavefront_t *dev, const char __user *addr)
1358{
1359	wavefront_patch_info *header;
1360	int err;
1361
1362	header = kmalloc(sizeof(*header), GFP_KERNEL);
1363	if (! header)
1364		return -ENOMEM;
1365
1366	if (copy_from_user (header, addr, sizeof(wavefront_patch_info) -
1367			    sizeof(wavefront_any))) {
1368		snd_printk ("bad address for load patch.\n");
1369		err = -EFAULT;
1370		goto __error;
1371	}
1372
1373	DPRINT (WF_DEBUG_LOAD_PATCH, "download "
1374				      "Sample type: %d "
1375				      "Sample number: %d "
1376				      "Sample size: %d\n",
1377				      header->subkey,
1378				      header->number,
1379				      header->size);
1380
1381	switch (header->subkey) {
1382	case WF_ST_SAMPLE:  /* sample or sample_header, based on patch->size */
1383
1384		if (copy_from_user (&header->hdr.s, header->hdrptr,
1385				    sizeof (wavefront_sample))) {
1386			err = -EFAULT;
1387			break;
1388		}
1389
1390		err = wavefront_send_sample (dev, header, header->dataptr, 0);
1391		break;
1392
1393	case WF_ST_MULTISAMPLE:
1394
1395		if (copy_from_user (&header->hdr.s, header->hdrptr,
1396				    sizeof (wavefront_multisample))) {
1397			err = -EFAULT;
1398			break;
1399		}
1400
1401		err = wavefront_send_multisample (dev, header);
1402		break;
1403
1404	case WF_ST_ALIAS:
1405
1406		if (copy_from_user (&header->hdr.a, header->hdrptr,
1407				    sizeof (wavefront_alias))) {
1408			err = -EFAULT;
1409			break;
1410		}
1411
1412		err = wavefront_send_alias (dev, header);
1413		break;
1414
1415	case WF_ST_DRUM:
1416		if (copy_from_user (&header->hdr.d, header->hdrptr,
1417				    sizeof (wavefront_drum))) {
1418			err = -EFAULT;
1419			break;
1420		}
1421
1422		err = wavefront_send_drum (dev, header);
1423		break;
1424
1425	case WF_ST_PATCH:
1426		if (copy_from_user (&header->hdr.p, header->hdrptr,
1427				    sizeof (wavefront_patch))) {
1428			err = -EFAULT;
1429			break;
1430		}
1431
1432		err = wavefront_send_patch (dev, header);
1433		break;
1434
1435	case WF_ST_PROGRAM:
1436		if (copy_from_user (&header->hdr.pr, header->hdrptr,
1437				    sizeof (wavefront_program))) {
1438			err = -EFAULT;
1439			break;
1440		}
1441
1442		err = wavefront_send_program (dev, header);
1443		break;
1444
1445	default:
1446		snd_printk ("unknown patch type %d.\n",
1447			    header->subkey);
1448		err = -EINVAL;
1449		break;
1450	}
1451
1452 __error:
1453	kfree(header);
1454	return err;
1455}
1456
1457/***********************************************************************
1458WaveFront: hardware-dependent interface
1459***********************************************************************/
1460
1461static void
1462process_sample_hdr (u8 *buf)
1463
1464{
1465	wavefront_sample s;
1466	u8 *ptr;
1467
1468	ptr = buf;
1469
1470	/* The board doesn't send us an exact copy of a "wavefront_sample"
1471	   in response to an Upload Sample Header command. Instead, we
1472	   have to convert the data format back into our data structure,
1473	   just as in the Download Sample command, where we have to do
1474	   something very similar in the reverse direction.
1475	*/
1476
1477	*((u32 *) &s.sampleStartOffset) = demunge_int32 (ptr, 4); ptr += 4;
1478	*((u32 *) &s.loopStartOffset) = demunge_int32 (ptr, 4); ptr += 4;
1479	*((u32 *) &s.loopEndOffset) = demunge_int32 (ptr, 4); ptr += 4;
1480	*((u32 *) &s.sampleEndOffset) = demunge_int32 (ptr, 4); ptr += 4;
1481	*((u32 *) &s.FrequencyBias) = demunge_int32 (ptr, 3); ptr += 3;
1482
1483	s.SampleResolution = *ptr & 0x3;
1484	s.Loop = *ptr & 0x8;
1485	s.Bidirectional = *ptr & 0x10;
1486	s.Reverse = *ptr & 0x40;
1487
1488	/* Now copy it back to where it came from */
1489
1490	memcpy (buf, (unsigned char *) &s, sizeof (wavefront_sample));
1491}
1492
1493static int
1494wavefront_synth_control (snd_wavefront_card_t *acard,
1495			 wavefront_control *wc)
1496
1497{
1498	snd_wavefront_t *dev = &acard->wavefront;
1499	unsigned char patchnumbuf[2];
1500	int i;
1501
1502	DPRINT (WF_DEBUG_CMD, "synth control with "
1503		"cmd 0x%x\n", wc->cmd);
1504
1505	/* Pre-handling of or for various commands */
1506
1507	switch (wc->cmd) {
1508
1509	case WFC_DISABLE_INTERRUPTS:
1510		snd_printk ("interrupts disabled.\n");
1511		outb (0x80|0x20, dev->control_port);
1512		dev->interrupts_are_midi = 1;
1513		return 0;
1514
1515	case WFC_ENABLE_INTERRUPTS:
1516		snd_printk ("interrupts enabled.\n");
1517		outb (0x80|0x40|0x20, dev->control_port);
1518		dev->interrupts_are_midi = 1;
1519		return 0;
1520
1521	case WFC_INTERRUPT_STATUS:
1522		wc->rbuf[0] = dev->interrupts_are_midi;
1523		return 0;
1524
1525	case WFC_ROMSAMPLES_RDONLY:
1526		dev->rom_samples_rdonly = wc->wbuf[0];
1527		wc->status = 0;
1528		return 0;
1529
1530	case WFC_IDENTIFY_SLOT_TYPE:
1531		i = wc->wbuf[0] | (wc->wbuf[1] << 7);
1532		if (i <0 || i >= WF_MAX_SAMPLE) {
1533			snd_printk ("invalid slot ID %d\n",
1534				i);
1535			wc->status = EINVAL;
1536			return -EINVAL;
1537		}
1538		wc->rbuf[0] = dev->sample_status[i];
1539		wc->status = 0;
1540		return 0;
1541
1542	case WFC_DEBUG_DRIVER:
1543		dev->debug = wc->wbuf[0];
1544		snd_printk ("debug = 0x%x\n", dev->debug);
1545		return 0;
1546
1547	case WFC_UPLOAD_PATCH:
1548		munge_int32 (*((u32 *) wc->wbuf), patchnumbuf, 2);
1549		memcpy (wc->wbuf, patchnumbuf, 2);
1550		break;
1551
1552	case WFC_UPLOAD_MULTISAMPLE:
1553		/* multisamples have to be handled differently, and
1554		   cannot be dealt with properly by snd_wavefront_cmd() alone.
1555		*/
1556		wc->status = wavefront_fetch_multisample
1557			(dev, (wavefront_patch_info *) wc->rbuf);
1558		return 0;
1559
1560	case WFC_UPLOAD_SAMPLE_ALIAS:
1561		snd_printk ("support for sample alias upload "
1562			"being considered.\n");
1563		wc->status = EINVAL;
1564		return -EINVAL;
1565	}
1566
1567	wc->status = snd_wavefront_cmd (dev, wc->cmd, wc->rbuf, wc->wbuf);
1568
1569	/* Post-handling of certain commands.
1570
1571	   In particular, if the command was an upload, demunge the data
1572	   so that the user-level doesn't have to think about it.
1573	*/
1574
1575	if (wc->status == 0) {
1576		switch (wc->cmd) {
1577			/* intercept any freemem requests so that we know
1578			   we are always current with the user-level view
1579			   of things.
1580			*/
1581
1582		case WFC_REPORT_FREE_MEMORY:
1583			dev->freemem = demunge_int32 (wc->rbuf, 4);
1584			break;
1585
1586		case WFC_UPLOAD_PATCH:
1587			demunge_buf (wc->rbuf, wc->rbuf, WF_PATCH_BYTES);
1588			break;
1589
1590		case WFC_UPLOAD_PROGRAM:
1591			demunge_buf (wc->rbuf, wc->rbuf, WF_PROGRAM_BYTES);
1592			break;
1593
1594		case WFC_UPLOAD_EDRUM_PROGRAM:
1595			demunge_buf (wc->rbuf, wc->rbuf, WF_DRUM_BYTES - 1);
1596			break;
1597
1598		case WFC_UPLOAD_SAMPLE_HEADER:
1599			process_sample_hdr (wc->rbuf);
1600			break;
1601
1602		case WFC_UPLOAD_SAMPLE_ALIAS:
1603			snd_printk ("support for "
1604				    "sample aliases still "
1605				    "being considered.\n");
1606			break;
1607
1608		case WFC_VMIDI_OFF:
1609			snd_wavefront_midi_disable_virtual (acard);
1610			break;
1611
1612		case WFC_VMIDI_ON:
1613			snd_wavefront_midi_enable_virtual (acard);
1614			break;
1615		}
1616	}
1617
1618	return 0;
1619}
1620
1621int
1622snd_wavefront_synth_open (struct snd_hwdep *hw, struct file *file)
1623
1624{
1625	if (!try_module_get(hw->card->module))
1626		return -EFAULT;
1627	file->private_data = hw;
1628	return 0;
1629}
1630
1631int
1632snd_wavefront_synth_release (struct snd_hwdep *hw, struct file *file)
1633
1634{
1635	module_put(hw->card->module);
1636	return 0;
1637}
1638
1639int
1640snd_wavefront_synth_ioctl (struct snd_hwdep *hw, struct file *file,
1641			   unsigned int cmd, unsigned long arg)
1642
1643{
1644	struct snd_card *card;
1645	snd_wavefront_t *dev;
1646	snd_wavefront_card_t *acard;
1647	wavefront_control *wc;
1648	void __user *argp = (void __user *)arg;
1649	int err;
1650
1651	card = (struct snd_card *) hw->card;
1652
1653	if (snd_BUG_ON(!card))
1654		return -ENODEV;
1655	if (snd_BUG_ON(!card->private_data))
1656		return -ENODEV;
1657
1658	acard = card->private_data;
1659	dev = &acard->wavefront;
1660
1661	switch (cmd) {
1662	case WFCTL_LOAD_SPP:
1663		if (wavefront_load_patch (dev, argp) != 0) {
1664			return -EIO;
1665		}
1666		break;
1667
1668	case WFCTL_WFCMD:
1669		wc = memdup_user(argp, sizeof(*wc));
1670		if (IS_ERR(wc))
1671			return PTR_ERR(wc);
1672
1673		if (wavefront_synth_control (acard, wc) < 0)
1674			err = -EIO;
1675		else if (copy_to_user (argp, wc, sizeof (*wc)))
1676			err = -EFAULT;
1677		else
1678			err = 0;
1679		kfree(wc);
1680		return err;
1681
1682	default:
1683		return -EINVAL;
1684	}
1685
1686	return 0;
1687}
1688
1689
1690/***********************************************************************/
1691/*  WaveFront: interface for card-level wavefront module               */
1692/***********************************************************************/
1693
1694void
1695snd_wavefront_internal_interrupt (snd_wavefront_card_t *card)
1696{
1697	snd_wavefront_t *dev = &card->wavefront;
1698
1699	/*
1700	   Some comments on interrupts. I attempted a version of this
1701	   driver that used interrupts throughout the code instead of
1702	   doing busy and/or sleep-waiting. Alas, it appears that once
1703	   the Motorola firmware is downloaded, the card *never*
1704	   generates an RX interrupt. These are successfully generated
1705	   during firmware loading, and after that wavefront_status()
1706	   reports that an interrupt is pending on the card from time
1707	   to time, but it never seems to be delivered to this
1708	   driver. Note also that wavefront_status() continues to
1709	   report that RX interrupts are enabled, suggesting that I
1710	   didn't goof up and disable them by mistake.
1711
1712	   Thus, I stepped back to a prior version of
1713	   wavefront_wait(), the only place where this really
1714	   matters. Its sad, but I've looked through the code to check
1715	   on things, and I really feel certain that the Motorola
1716	   firmware prevents RX-ready interrupts.
1717	*/
1718
1719	if ((wavefront_status(dev) & (STAT_INTR_READ|STAT_INTR_WRITE)) == 0) {
1720		return;
1721	}
1722
1723	spin_lock(&dev->irq_lock);
1724	dev->irq_ok = 1;
1725	dev->irq_cnt++;
1726	spin_unlock(&dev->irq_lock);
1727	wake_up(&dev->interrupt_sleeper);
1728}
1729
1730/* STATUS REGISTER
1731
17320 Host Rx Interrupt Enable (1=Enabled)
17331 Host Rx Register Full (1=Full)
17342 Host Rx Interrupt Pending (1=Interrupt)
17353 Unused
17364 Host Tx Interrupt (1=Enabled)
17375 Host Tx Register empty (1=Empty)
17386 Host Tx Interrupt Pending (1=Interrupt)
17397 Unused
1740*/
1741
1742static int
1743snd_wavefront_interrupt_bits (int irq)
1744
1745{
1746	int bits;
1747
1748	switch (irq) {
1749	case 9:
1750		bits = 0x00;
1751		break;
1752	case 5:
1753		bits = 0x08;
1754		break;
1755	case 12:
1756		bits = 0x10;
1757		break;
1758	case 15:
1759		bits = 0x18;
1760		break;
1761
1762	default:
1763		snd_printk ("invalid IRQ %d\n", irq);
1764		bits = -1;
1765	}
1766
1767	return bits;
1768}
1769
1770static void
1771wavefront_should_cause_interrupt (snd_wavefront_t *dev,
1772				  int val, int port, unsigned long timeout)
1773
1774{
1775	wait_queue_t wait;
1776
1777	init_waitqueue_entry(&wait, current);
1778	spin_lock_irq(&dev->irq_lock);
1779	add_wait_queue(&dev->interrupt_sleeper, &wait);
1780	dev->irq_ok = 0;
1781	outb (val,port);
1782	spin_unlock_irq(&dev->irq_lock);
1783	while (!dev->irq_ok && time_before(jiffies, timeout)) {
1784		schedule_timeout_uninterruptible(1);
1785		barrier();
1786	}
1787}
1788
1789static int
1790wavefront_reset_to_cleanliness (snd_wavefront_t *dev)
1791
1792{
1793	int bits;
1794	int hwv[2];
1795
1796	/* IRQ already checked */
1797
1798	bits = snd_wavefront_interrupt_bits (dev->irq);
1799
1800	/* try reset of port */
1801
1802	outb (0x0, dev->control_port);
1803
1804	/* At this point, the board is in reset, and the H/W initialization
1805	   register is accessed at the same address as the data port.
1806
1807	   Bit 7 - Enable IRQ Driver
1808	   0 - Tri-state the Wave-Board drivers for the PC Bus IRQs
1809	   1 - Enable IRQ selected by bits 5:3 to be driven onto the PC Bus.
1810
1811	   Bit 6 - MIDI Interface Select
1812
1813	   0 - Use the MIDI Input from the 26-pin WaveBlaster
1814	   compatible header as the serial MIDI source
1815	   1 - Use the MIDI Input from the 9-pin D connector as the
1816	   serial MIDI source.
1817
1818	   Bits 5:3 - IRQ Selection
1819	   0 0 0 - IRQ 2/9
1820	   0 0 1 - IRQ 5
1821	   0 1 0 - IRQ 12
1822	   0 1 1 - IRQ 15
1823	   1 0 0 - Reserved
1824	   1 0 1 - Reserved
1825	   1 1 0 - Reserved
1826	   1 1 1 - Reserved
1827
1828	   Bits 2:1 - Reserved
1829	   Bit 0 - Disable Boot ROM
1830	   0 - memory accesses to 03FC30-03FFFFH utilize the internal Boot ROM
1831	   1 - memory accesses to 03FC30-03FFFFH are directed to external
1832	   storage.
1833
1834	*/
1835
1836	/* configure hardware: IRQ, enable interrupts,
1837	   plus external 9-pin MIDI interface selected
1838	*/
1839
1840	outb (0x80 | 0x40 | bits, dev->data_port);
1841
1842	/* CONTROL REGISTER
1843
1844	   0 Host Rx Interrupt Enable (1=Enabled)      0x1
1845	   1 Unused                                    0x2
1846	   2 Unused                                    0x4
1847	   3 Unused                                    0x8
1848	   4 Host Tx Interrupt Enable                 0x10
1849	   5 Mute (0=Mute; 1=Play)                    0x20
1850	   6 Master Interrupt Enable (1=Enabled)      0x40
1851	   7 Master Reset (0=Reset; 1=Run)            0x80
1852
1853	   Take us out of reset, mute output, master + TX + RX interrupts on.
1854
1855	   We'll get an interrupt presumably to tell us that the TX
1856	   register is clear.
1857	*/
1858
1859	wavefront_should_cause_interrupt(dev, 0x80|0x40|0x10|0x1,
1860					 dev->control_port,
1861					 (reset_time*HZ)/100);
1862
1863	/* Note: data port is now the data port, not the h/w initialization
1864	   port.
1865	 */
1866
1867	if (!dev->irq_ok) {
1868		snd_printk ("intr not received after h/w un-reset.\n");
1869		goto gone_bad;
1870	}
1871
1872	/* Note: data port is now the data port, not the h/w initialization
1873	   port.
1874
1875	   At this point, only "HW VERSION" or "DOWNLOAD OS" commands
1876	   will work. So, issue one of them, and wait for TX
1877	   interrupt. This can take a *long* time after a cold boot,
1878	   while the ISC ROM does its RAM test. The SDK says up to 4
1879	   seconds - with 12MB of RAM on a Tropez+, it takes a lot
1880	   longer than that (~16secs). Note that the card understands
1881	   the difference between a warm and a cold boot, so
1882	   subsequent ISC2115 reboots (say, caused by module
1883	   reloading) will get through this much faster.
1884
1885	   XXX Interesting question: why is no RX interrupt received first ?
1886	*/
1887
1888	wavefront_should_cause_interrupt(dev, WFC_HARDWARE_VERSION,
1889					 dev->data_port, ramcheck_time*HZ);
1890
1891	if (!dev->irq_ok) {
1892		snd_printk ("post-RAM-check interrupt not received.\n");
1893		goto gone_bad;
1894	}
1895
1896	if (!wavefront_wait (dev, STAT_CAN_READ)) {
1897		snd_printk ("no response to HW version cmd.\n");
1898		goto gone_bad;
1899	}
1900
1901	if ((hwv[0] = wavefront_read (dev)) == -1) {
1902		snd_printk ("board not responding correctly.\n");
1903		goto gone_bad;
1904	}
1905
1906	if (hwv[0] == 0xFF) { /* NAK */
1907
1908		/* Board's RAM test failed. Try to read error code,
1909		   and tell us about it either way.
1910		*/
1911
1912		if ((hwv[0] = wavefront_read (dev)) == -1) {
1913			snd_printk ("on-board RAM test failed "
1914				    "(bad error code).\n");
1915		} else {
1916			snd_printk ("on-board RAM test failed "
1917				    "(error code: 0x%x).\n",
1918				hwv[0]);
1919		}
1920		goto gone_bad;
1921	}
1922
1923	/* We're OK, just get the next byte of the HW version response */
1924
1925	if ((hwv[1] = wavefront_read (dev)) == -1) {
1926		snd_printk ("incorrect h/w response.\n");
1927		goto gone_bad;
1928	}
1929
1930	snd_printk ("hardware version %d.%d\n",
1931		    hwv[0], hwv[1]);
1932
1933	return 0;
1934
1935
1936     gone_bad:
1937	return (1);
1938}
1939
1940static int
1941wavefront_download_firmware (snd_wavefront_t *dev, char *path)
1942
1943{
1944	const unsigned char *buf;
1945	int len, err;
1946	int section_cnt_downloaded = 0;
1947	const struct firmware *firmware;
1948
1949	err = request_firmware(&firmware, path, dev->card->dev);
1950	if (err < 0) {
1951		snd_printk(KERN_ERR "firmware (%s) download failed!!!\n", path);
1952		return 1;
1953	}
1954
1955	len = 0;
1956	buf = firmware->data;
1957	for (;;) {
1958		int section_length = *(signed char *)buf;
1959		if (section_length == 0)
1960			break;
1961		if (section_length < 0 || section_length > WF_SECTION_MAX) {
1962			snd_printk(KERN_ERR
1963				   "invalid firmware section length %d\n",
1964				   section_length);
1965			goto failure;
1966		}
1967		buf++;
1968		len++;
1969
1970		if (firmware->size < len + section_length) {
1971			snd_printk(KERN_ERR "firmware section read error.\n");
1972			goto failure;
1973		}
1974
1975		/* Send command */
1976		if (wavefront_write(dev, WFC_DOWNLOAD_OS))
1977			goto failure;
1978
1979		for (; section_length; section_length--) {
1980			if (wavefront_write(dev, *buf))
1981				goto failure;
1982			buf++;
1983			len++;
1984		}
1985
1986		/* get ACK */
1987		if (!wavefront_wait(dev, STAT_CAN_READ)) {
1988			snd_printk(KERN_ERR "time out for firmware ACK.\n");
1989			goto failure;
1990		}
1991		err = inb(dev->data_port);
1992		if (err != WF_ACK) {
1993			snd_printk(KERN_ERR
1994				   "download of section #%d not "
1995				   "acknowledged, ack = 0x%x\n",
1996				   section_cnt_downloaded + 1, err);
1997			goto failure;
1998		}
1999
2000		section_cnt_downloaded++;
2001	}
2002
2003	release_firmware(firmware);
2004	return 0;
2005
2006 failure:
2007	release_firmware(firmware);
2008	snd_printk(KERN_ERR "firmware download failed!!!\n");
2009	return 1;
2010}
2011
2012
2013static int
2014wavefront_do_reset (snd_wavefront_t *dev)
2015
2016{
2017	char voices[1];
2018
2019	if (wavefront_reset_to_cleanliness (dev)) {
2020		snd_printk ("hw reset failed.\n");
2021		goto gone_bad;
2022	}
2023
2024	if (dev->israw) {
2025		if (wavefront_download_firmware (dev, ospath)) {
2026			goto gone_bad;
2027		}
2028
2029		dev->israw = 0;
2030
2031		/* Wait for the OS to get running. The protocol for
2032		   this is non-obvious, and was determined by
2033		   using port-IO tracing in DOSemu and some
2034		   experimentation here.
2035
2036		   Rather than using timed waits, use interrupts creatively.
2037		*/
2038
2039		wavefront_should_cause_interrupt (dev, WFC_NOOP,
2040						  dev->data_port,
2041						  (osrun_time*HZ));
2042
2043		if (!dev->irq_ok) {
2044			snd_printk ("no post-OS interrupt.\n");
2045			goto gone_bad;
2046		}
2047
2048		/* Now, do it again ! */
2049
2050		wavefront_should_cause_interrupt (dev, WFC_NOOP,
2051						  dev->data_port, (10*HZ));
2052
2053		if (!dev->irq_ok) {
2054			snd_printk ("no post-OS interrupt(2).\n");
2055			goto gone_bad;
2056		}
2057
2058		/* OK, no (RX/TX) interrupts any more, but leave mute
2059		   in effect.
2060		*/
2061
2062		outb (0x80|0x40, dev->control_port);
2063	}
2064
2065	/* SETUPSND.EXE asks for sample memory config here, but since i
2066	   have no idea how to interpret the result, we'll forget
2067	   about it.
2068	*/
2069
2070	if ((dev->freemem = wavefront_freemem (dev)) < 0) {
2071		goto gone_bad;
2072	}
2073
2074	snd_printk ("available DRAM %dk\n", dev->freemem / 1024);
2075
2076	if (wavefront_write (dev, 0xf0) ||
2077	    wavefront_write (dev, 1) ||
2078	    (wavefront_read (dev) < 0)) {
2079		dev->debug = 0;
2080		snd_printk ("MPU emulation mode not set.\n");
2081		goto gone_bad;
2082	}
2083
2084	voices[0] = 32;
2085
2086	if (snd_wavefront_cmd (dev, WFC_SET_NVOICES, NULL, voices)) {
2087		snd_printk ("cannot set number of voices to 32.\n");
2088		goto gone_bad;
2089	}
2090
2091
2092	return 0;
2093
2094 gone_bad:
2095	/* reset that sucker so that it doesn't bother us. */
2096
2097	outb (0x0, dev->control_port);
2098	dev->interrupts_are_midi = 0;
2099	return 1;
2100}
2101
2102int
2103snd_wavefront_start (snd_wavefront_t *dev)
2104
2105{
2106	int samples_are_from_rom;
2107
2108	/* IMPORTANT: assumes that snd_wavefront_detect() and/or
2109	   wavefront_reset_to_cleanliness() has already been called
2110	*/
2111
2112	if (dev->israw) {
2113		samples_are_from_rom = 1;
2114	} else {
2115		/* XXX is this always true ? */
2116		samples_are_from_rom = 0;
2117	}
2118
2119	if (dev->israw || fx_raw) {
2120		if (wavefront_do_reset (dev)) {
2121			return -1;
2122		}
2123	}
2124	/* Check for FX device, present only on Tropez+ */
2125
2126	dev->has_fx = (snd_wavefront_fx_detect (dev) == 0);
2127
2128	if (dev->has_fx && fx_raw) {
2129		snd_wavefront_fx_start (dev);
2130	}
2131
2132	wavefront_get_sample_status (dev, samples_are_from_rom);
2133	wavefront_get_program_status (dev);
2134	wavefront_get_patch_status (dev);
2135
2136	/* Start normal operation: unreset, master interrupt enabled, no mute
2137	*/
2138
2139	outb (0x80|0x40|0x20, dev->control_port);
2140
2141	return (0);
2142}
2143
2144int
2145snd_wavefront_detect (snd_wavefront_card_t *card)
2146
2147{
2148	unsigned char   rbuf[4], wbuf[4];
2149	snd_wavefront_t *dev = &card->wavefront;
2150
2151	/* returns zero if a WaveFront card is successfully detected.
2152	   negative otherwise.
2153	*/
2154
2155	dev->israw = 0;
2156	dev->has_fx = 0;
2157	dev->debug = debug_default;
2158	dev->interrupts_are_midi = 0;
2159	dev->irq_cnt = 0;
2160	dev->rom_samples_rdonly = 1;
2161
2162	if (snd_wavefront_cmd (dev, WFC_FIRMWARE_VERSION, rbuf, wbuf) == 0) {
2163
2164		dev->fw_version[0] = rbuf[0];
2165		dev->fw_version[1] = rbuf[1];
2166
2167		snd_printk ("firmware %d.%d already loaded.\n",
2168			    rbuf[0], rbuf[1]);
2169
2170		/* check that a command actually works */
2171
2172		if (snd_wavefront_cmd (dev, WFC_HARDWARE_VERSION,
2173				       rbuf, wbuf) == 0) {
2174			dev->hw_version[0] = rbuf[0];
2175			dev->hw_version[1] = rbuf[1];
2176		} else {
2177			snd_printk ("not raw, but no "
2178				    "hardware version!\n");
2179			return -1;
2180		}
2181
2182		if (!wf_raw) {
2183			return 0;
2184		} else {
2185			snd_printk ("reloading firmware as you requested.\n");
2186			dev->israw = 1;
2187		}
2188
2189	} else {
2190
2191		dev->israw = 1;
2192		snd_printk ("no response to firmware probe, assume raw.\n");
2193
2194	}
2195
2196	return 0;
2197}
2198
2199MODULE_FIRMWARE(DEFAULT_OSPATH);
2200