xref: /freebsd/sys/dev/sound/midi/sequencer.c (revision 1e413cf93298b5b97441a21d9a50fdcd0ee9945e)
1 /*-
2  * Copyright (c) 2003 Mathew Kanner
3  * Copyright (c) 1993 Hannu Savolainen
4  * All rights reserved.
5  *
6  * Redistribution and use in source and binary forms, with or without
7  * modification, are permitted provided that the following conditions
8  * are met:
9  * 1. Redistributions of source code must retain the above copyright
10  *    notice, this list of conditions and the following disclaimer.
11  * 2. Redistributions in binary form must reproduce the above copyright
12  *    notice, this list of conditions and the following disclaimer in the
13  *    documentation and/or other materials provided with the distribution.
14  *
15  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
16  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
17  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
18  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
19  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
20  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
21  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
22  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
23  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
24  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
25  * SUCH DAMAGE.
26  */
27 
28 /*
29  * The sequencer personality manager.
30  */
31 
32 #include <sys/cdefs.h>
33 __FBSDID("$FreeBSD$");
34 
35 #include <sys/param.h>
36 #include <sys/systm.h>
37 #include <sys/ioccom.h>
38 
39 #include <sys/filio.h>
40 #include <sys/lock.h>
41 #include <sys/sockio.h>
42 #include <sys/fcntl.h>
43 #include <sys/tty.h>
44 #include <sys/proc.h>
45 #include <sys/sysctl.h>
46 
47 #include <sys/kernel.h>			/* for DATA_SET */
48 
49 #include <sys/module.h>
50 #include <sys/conf.h>
51 #include <sys/file.h>
52 #include <sys/uio.h>
53 #include <sys/syslog.h>
54 #include <sys/errno.h>
55 #include <sys/malloc.h>
56 #include <sys/bus.h>
57 #include <machine/resource.h>
58 #include <machine/bus.h>
59 #include <machine/clock.h>		/* for DELAY */
60 #include <sys/soundcard.h>
61 #include <sys/rman.h>
62 #include <sys/mman.h>
63 #include <sys/poll.h>
64 #include <sys/mutex.h>
65 #include <sys/condvar.h>
66 #include <sys/kthread.h>
67 #include <sys/unistd.h>
68 #include <sys/selinfo.h>
69 
70 
71 #include <dev/sound/midi/midi.h>
72 #include <dev/sound/midi/midiq.h>
73 #include "synth_if.h"
74 
75 #include <dev/sound/midi/sequencer.h>
76 
77 #define TMR_TIMERBASE 13
78 
79 #define SND_DEV_SEQ	1		/* Sequencer output /dev/sequencer (FM
80 					 * synthesizer and MIDI output) */
81 #define SND_DEV_MUSIC	8		/* /dev/music, level 2 interface */
82 
83 /* Length of a sequencer event. */
84 #define EV_SZ 8
85 #define IEV_SZ 8
86 
87 /* Lookup modes */
88 #define LOOKUP_EXIST	(0)
89 #define LOOKUP_OPEN	(1)
90 #define LOOKUP_CLOSE	(2)
91 
92 #define PCMMKMINOR(u, d, c) \
93 	    ((((c) & 0xff) << 16) | (((u) & 0x0f) << 4) | ((d) & 0x0f))
94 #define MIDIMKMINOR(u, d, c) PCMMKMINOR(u, d, c)
95 #define MIDIUNIT(y) ((minor(y) >> 4) & 0x0f)
96 #define MIDIDEV(y) (minor(y) & 0x0f)
97 
98 /* These are the entries to the sequencer driver. */
99 static d_open_t seq_open;
100 static d_close_t seq_close;
101 static d_ioctl_t seq_ioctl;
102 static d_read_t seq_read;
103 static d_write_t seq_write;
104 static d_poll_t seq_poll;
105 
106 static struct cdevsw seq_cdevsw = {
107 	.d_version = D_VERSION,
108 	.d_open = seq_open,
109 	.d_close = seq_close,
110 	.d_read = seq_read,
111 	.d_write = seq_write,
112 	.d_ioctl = seq_ioctl,
113 	.d_poll = seq_poll,
114 	.d_name = "sequencer",
115 };
116 
117 struct seq_softc {
118 	KOBJ_FIELDS;
119 
120 	struct mtx seq_lock, q_lock;
121 	struct cv empty_cv, reset_cv, in_cv, out_cv, state_cv, th_cv;
122 
123 	MIDIQ_HEAD(, u_char) in_q, out_q;
124 
125 	u_long	flags;
126 	/* Flags (protected by flag_mtx of mididev_info) */
127 	int	fflags;			/* Access mode */
128 	int	music;
129 
130 	int	out_water;		/* Sequence output threshould */
131 	snd_sync_parm sync_parm;	/* AIOSYNC parameter set */
132 	struct thread *sync_thread;	/* AIOSYNCing thread */
133 	struct selinfo in_sel, out_sel;
134 	int	midi_number;
135 	struct cdev *seqdev, *musicdev;
136 	int	unit;
137 	int	maxunits;
138 	kobj_t *midis;
139 	int    *midi_flags;
140 	kobj_t	mapper;
141 	void   *mapper_cookie;
142 	struct timeval timerstop, timersub;
143 	int	timerbase, tempo;
144 	int	timerrun;
145 	int	done;
146 	int	playing;
147 	int	recording;
148 	int	busy;
149 	int	pre_event_timeout;
150 	int	waiting;
151 };
152 
153 /*
154  * Module specific stuff, including how many sequecers
155  * we currently own.
156  */
157 
158 SYSCTL_NODE(_hw_midi, OID_AUTO, seq, CTLFLAG_RD, 0, "Midi sequencer");
159 
160 int					seq_debug;
161 /* XXX: should this be moved into debug.midi? */
162 SYSCTL_INT(_hw_midi_seq, OID_AUTO, debug, CTLFLAG_RW, &seq_debug, 0, "");
163 
164 midi_cmdtab	cmdtab_seqevent[] = {
165 	{SEQ_NOTEOFF,		"SEQ_NOTEOFF"},
166 	{SEQ_NOTEON,		"SEQ_NOTEON"},
167 	{SEQ_WAIT,		"SEQ_WAIT"},
168 	{SEQ_PGMCHANGE,		"SEQ_PGMCHANGE"},
169 	{SEQ_SYNCTIMER,		"SEQ_SYNCTIMER"},
170 	{SEQ_MIDIPUTC,		"SEQ_MIDIPUTC"},
171 	{SEQ_DRUMON,		"SEQ_DRUMON"},
172 	{SEQ_DRUMOFF,		"SEQ_DRUMOFF"},
173 	{SEQ_ECHO,		"SEQ_ECHO"},
174 	{SEQ_AFTERTOUCH,	"SEQ_AFTERTOUCH"},
175 	{SEQ_CONTROLLER,	"SEQ_CONTROLLER"},
176 	{SEQ_BALANCE,		"SEQ_BALANCE"},
177 	{SEQ_VOLMODE,		"SEQ_VOLMODE"},
178 	{SEQ_FULLSIZE,		"SEQ_FULLSIZE"},
179 	{SEQ_PRIVATE,		"SEQ_PRIVATE"},
180 	{SEQ_EXTENDED,		"SEQ_EXTENDED"},
181 	{EV_SEQ_LOCAL,		"EV_SEQ_LOCAL"},
182 	{EV_TIMING,		"EV_TIMING"},
183 	{EV_CHN_COMMON,		"EV_CHN_COMMON"},
184 	{EV_CHN_VOICE,		"EV_CHN_VOICE"},
185 	{EV_SYSEX,		"EV_SYSEX"},
186 	{-1,			NULL},
187 };
188 
189 midi_cmdtab	cmdtab_seqioctl[] = {
190 	{SNDCTL_SEQ_RESET,	"SNDCTL_SEQ_RESET"},
191 	{SNDCTL_SEQ_SYNC,	"SNDCTL_SEQ_SYNC"},
192 	{SNDCTL_SYNTH_INFO,	"SNDCTL_SYNTH_INFO"},
193 	{SNDCTL_SEQ_CTRLRATE,	"SNDCTL_SEQ_CTRLRATE"},
194 	{SNDCTL_SEQ_GETOUTCOUNT,	"SNDCTL_SEQ_GETOUTCOUNT"},
195 	{SNDCTL_SEQ_GETINCOUNT,	"SNDCTL_SEQ_GETINCOUNT"},
196 	{SNDCTL_SEQ_PERCMODE,	"SNDCTL_SEQ_PERCMODE"},
197 	{SNDCTL_FM_LOAD_INSTR,	"SNDCTL_FM_LOAD_INSTR"},
198 	{SNDCTL_SEQ_TESTMIDI,	"SNDCTL_SEQ_TESTMIDI"},
199 	{SNDCTL_SEQ_RESETSAMPLES,	"SNDCTL_SEQ_RESETSAMPLES"},
200 	{SNDCTL_SEQ_NRSYNTHS,	"SNDCTL_SEQ_NRSYNTHS"},
201 	{SNDCTL_SEQ_NRMIDIS,	"SNDCTL_SEQ_NRMIDIS"},
202 	{SNDCTL_SEQ_GETTIME,	"SNDCTL_SEQ_GETTIME"},
203 	{SNDCTL_MIDI_INFO,	"SNDCTL_MIDI_INFO"},
204 	{SNDCTL_SEQ_THRESHOLD,	"SNDCTL_SEQ_THRESHOLD"},
205 	{SNDCTL_SYNTH_MEMAVL,	"SNDCTL_SYNTH_MEMAVL"},
206 	{SNDCTL_FM_4OP_ENABLE,	"SNDCTL_FM_4OP_ENABLE"},
207 	{SNDCTL_PMGR_ACCESS,	"SNDCTL_PMGR_ACCESS"},
208 	{SNDCTL_SEQ_PANIC,	"SNDCTL_SEQ_PANIC"},
209 	{SNDCTL_SEQ_OUTOFBAND,	"SNDCTL_SEQ_OUTOFBAND"},
210 	{SNDCTL_TMR_TIMEBASE,	"SNDCTL_TMR_TIMEBASE"},
211 	{SNDCTL_TMR_START,	"SNDCTL_TMR_START"},
212 	{SNDCTL_TMR_STOP,	"SNDCTL_TMR_STOP"},
213 	{SNDCTL_TMR_CONTINUE,	"SNDCTL_TMR_CONTINUE"},
214 	{SNDCTL_TMR_TEMPO,	"SNDCTL_TMR_TEMPO"},
215 	{SNDCTL_TMR_SOURCE,	"SNDCTL_TMR_SOURCE"},
216 	{SNDCTL_TMR_METRONOME,	"SNDCTL_TMR_METRONOME"},
217 	{SNDCTL_TMR_SELECT,	"SNDCTL_TMR_SELECT"},
218 	{SNDCTL_MIDI_PRETIME,	"SNDCTL_MIDI_PRETIME"},
219 	{AIONWRITE,		"AIONWRITE"},
220 	{AIOGSIZE,		"AIOGSIZE"},
221 	{AIOSSIZE,		"AIOSSIZE"},
222 	{AIOGFMT,		"AIOGFMT"},
223 	{AIOSFMT,		"AIOSFMT"},
224 	{AIOGMIX,		"AIOGMIX"},
225 	{AIOSMIX,		"AIOSMIX"},
226 	{AIOSTOP,		"AIOSTOP"},
227 	{AIOSYNC,		"AIOSYNC"},
228 	{AIOGCAP,		"AIOGCAP"},
229 	{-1,			NULL},
230 };
231 
232 midi_cmdtab	cmdtab_timer[] = {
233 	{TMR_WAIT_REL,	"TMR_WAIT_REL"},
234 	{TMR_WAIT_ABS,	"TMR_WAIT_ABS"},
235 	{TMR_STOP,	"TMR_STOP"},
236 	{TMR_START,	"TMR_START"},
237 	{TMR_CONTINUE,	"TMR_CONTINUE"},
238 	{TMR_TEMPO,	"TMR_TEMPO"},
239 	{TMR_ECHO,	"TMR_ECHO"},
240 	{TMR_CLOCK,	"TMR_CLOCK"},
241 	{TMR_SPP,	"TMR_SPP"},
242 	{TMR_TIMESIG,	"TMR_TIMESIG"},
243 	{-1,		NULL},
244 };
245 
246 midi_cmdtab	cmdtab_seqcv[] = {
247 	{MIDI_NOTEOFF,		"MIDI_NOTEOFF"},
248 	{MIDI_NOTEON,		"MIDI_NOTEON"},
249 	{MIDI_KEY_PRESSURE,	"MIDI_KEY_PRESSURE"},
250 	{-1,			NULL},
251 };
252 
253 midi_cmdtab	cmdtab_seqccmn[] = {
254 	{MIDI_CTL_CHANGE,	"MIDI_CTL_CHANGE"},
255 	{MIDI_PGM_CHANGE,	"MIDI_PGM_CHANGE"},
256 	{MIDI_CHN_PRESSURE,	"MIDI_CHN_PRESSURE"},
257 	{MIDI_PITCH_BEND,	"MIDI_PITCH_BEND"},
258 	{MIDI_SYSTEM_PREFIX,	"MIDI_SYSTEM_PREFIX"},
259 	{-1,			NULL},
260 };
261 
262 /*
263  * static const char *mpu401_mprovider(kobj_t obj, struct mpu401 *m);
264  */
265 
266 static kobj_method_t seq_methods[] = {
267 	/* KOBJMETHOD(mpu_provider,mpu401_mprovider), */
268 	{0, 0}
269 };
270 
271 DEFINE_CLASS(sequencer, seq_methods, 0);
272 
273 /* The followings are the local function. */
274 static int seq_convertold(u_char *event, u_char *out);
275 
276 /*
277  * static void seq_midiinput(struct seq_softc * scp, void *md);
278  */
279 static void seq_reset(struct seq_softc *scp);
280 static int seq_sync(struct seq_softc *scp);
281 
282 static int seq_processevent(struct seq_softc *scp, u_char *event);
283 
284 static int seq_timing(struct seq_softc *scp, u_char *event);
285 static int seq_local(struct seq_softc *scp, u_char *event);
286 
287 static int seq_chnvoice(struct seq_softc *scp, kobj_t md, u_char *event);
288 static int seq_chncommon(struct seq_softc *scp, kobj_t md, u_char *event);
289 static int seq_sysex(struct seq_softc *scp, kobj_t md, u_char *event);
290 
291 static int seq_fetch_mid(struct seq_softc *scp, int unit, kobj_t *md);
292 void	seq_copytoinput(struct seq_softc *scp, u_char *event, int len);
293 int	seq_modevent(module_t mod, int type, void *data);
294 struct seq_softc *seqs[10];
295 static struct mtx seqinfo_mtx;
296 static u_long nseq = 0;
297 
298 static void timer_start(struct seq_softc *t);
299 static void timer_stop(struct seq_softc *t);
300 static void timer_setvals(struct seq_softc *t, int tempo, int timerbase);
301 static void timer_wait(struct seq_softc *t, int ticks, int wait_abs);
302 static int timer_now(struct seq_softc *t);
303 
304 
305 static void
306 timer_start(struct seq_softc *t)
307 {
308 	t->timerrun = 1;
309 	getmicrotime(&t->timersub);
310 }
311 
312 static void
313 timer_continue(struct seq_softc *t)
314 {
315 	struct timeval now;
316 
317 	if (t->timerrun == 1)
318 		return;
319 	t->timerrun = 1;
320 	getmicrotime(&now);
321 	timevalsub(&now, &t->timerstop);
322 	timevaladd(&t->timersub, &now);
323 }
324 
325 static void
326 timer_stop(struct seq_softc *t)
327 {
328 	t->timerrun = 0;
329 	getmicrotime(&t->timerstop);
330 }
331 
332 static void
333 timer_setvals(struct seq_softc *t, int tempo, int timerbase)
334 {
335 	t->tempo = tempo;
336 	t->timerbase = timerbase;
337 }
338 
339 static void
340 timer_wait(struct seq_softc *t, int ticks, int wait_abs)
341 {
342 	struct timeval now, when;
343 	int ret;
344 	unsigned long long i;
345 
346 	while (t->timerrun == 0) {
347 		SEQ_DEBUG(2, printf("Timer wait when timer isn't running\n"));
348 		/*
349 	         * The old sequencer used timeouts that only increased
350 	         * the timer when the timer was running.
351 	         * Hence the sequencer would stick (?) if the
352 	         * timer was disabled.
353 	         */
354 		cv_wait(&t->reset_cv, &t->seq_lock);
355 		if (t->playing == 0)
356 			return;
357 	}
358 
359 	i = ticks * 60ull * 1000000ull / (t->tempo * t->timerbase);
360 
361 	when.tv_sec = i / 1000000;
362 	when.tv_usec = i % 1000000;
363 
364 #if 0
365 	printf("timer_wait tempo %d timerbase %d ticks %d abs %d u_sec %llu\n",
366 	    t->tempo, t->timerbase, ticks, wait_abs, i);
367 #endif
368 
369 	if (wait_abs != 0) {
370 		getmicrotime(&now);
371 		timevalsub(&now, &t->timersub);
372 		timevalsub(&when, &now);
373 	}
374 	if (when.tv_sec < 0 || when.tv_usec < 0) {
375 		SEQ_DEBUG(3,
376 		    printf("seq_timer error negative time %lds.%06lds\n",
377 		    (long)when.tv_sec, (long)when.tv_usec));
378 		return;
379 	}
380 	i = when.tv_sec * 1000000ull;
381 	i += when.tv_usec;
382 	i *= hz;
383 	i /= 1000000ull;
384 #if 0
385 	printf("seq_timer usec %llu ticks %llu\n",
386 	    when.tv_sec * 1000000ull + when.tv_usec, i);
387 #endif
388 	t->waiting = 1;
389 	ret = cv_timedwait(&t->reset_cv, &t->seq_lock, i + 1);
390 	t->waiting = 0;
391 
392 	if (ret != EWOULDBLOCK)
393 		SEQ_DEBUG(3, printf("seq_timer didn't timeout\n"));
394 
395 }
396 
397 static int
398 timer_now(struct seq_softc *t)
399 {
400 	struct timeval now;
401 	unsigned long long i;
402 	int ret;
403 
404 	if (t->timerrun == 0)
405 		now = t->timerstop;
406 	else
407 		getmicrotime(&now);
408 
409 	timevalsub(&now, &t->timersub);
410 
411 	i = now.tv_sec * 1000000ull;
412 	i += now.tv_usec;
413 	i *= t->timerbase;
414 /*	i /= t->tempo; */
415 	i /= 1000000ull;
416 
417 	ret = i;
418 	/*
419 	 * printf("timer_now: %llu %d\n", i, ret);
420 	 */
421 
422 	return ret;
423 }
424 
425 static void
426 seq_eventthread(void *arg)
427 {
428 	struct seq_softc *scp = arg;
429 	char event[EV_SZ];
430 
431 	mtx_lock(&scp->seq_lock);
432 	SEQ_DEBUG(2, printf("seq_eventthread started\n"));
433 	while (scp->done == 0) {
434 restart:
435 		while (scp->playing == 0) {
436 			cv_wait(&scp->state_cv, &scp->seq_lock);
437 			if (scp->done)
438 				goto done;
439 		}
440 
441 		while (MIDIQ_EMPTY(scp->out_q)) {
442 			cv_broadcast(&scp->empty_cv);
443 			cv_wait(&scp->out_cv, &scp->seq_lock);
444 			if (scp->playing == 0)
445 				goto restart;
446 			if (scp->done)
447 				goto done;
448 		}
449 
450 		MIDIQ_DEQ(scp->out_q, event, EV_SZ);
451 
452 		if (MIDIQ_AVAIL(scp->out_q) < scp->out_water) {
453 			cv_broadcast(&scp->out_cv);
454 			selwakeup(&scp->out_sel);
455 		}
456 		seq_processevent(scp, event);
457 	}
458 
459 done:
460 	cv_broadcast(&scp->th_cv);
461 	mtx_unlock(&scp->seq_lock);
462 	mtx_lock(&Giant);
463 	SEQ_DEBUG(2, printf("seq_eventthread finished\n"));
464 	kproc_exit(0);
465 }
466 
467 /*
468  * seq_processevent:  This maybe called by the event thread or the IOCTL
469  * handler for queued and out of band events respectively.
470  */
471 static int
472 seq_processevent(struct seq_softc *scp, u_char *event)
473 {
474 	int ret;
475 	kobj_t m;
476 
477 	ret = 0;
478 
479 	if (event[0] == EV_SEQ_LOCAL)
480 		ret = seq_local(scp, event);
481 	else if (event[0] == EV_TIMING)
482 		ret = seq_timing(scp, event);
483 	else if (event[0] != EV_CHN_VOICE &&
484 		    event[0] != EV_CHN_COMMON &&
485 		    event[0] != EV_SYSEX &&
486 	    event[0] != SEQ_MIDIPUTC) {
487 		ret = 1;
488 		SEQ_DEBUG(2, printf("seq_processevent not known %d\n",
489 		    event[0]));
490 	} else if (seq_fetch_mid(scp, event[1], &m) != 0) {
491 		ret = 1;
492 		SEQ_DEBUG(2, printf("seq_processevent midi unit not found %d\n",
493 		    event[1]));
494 	} else
495 		switch (event[0]) {
496 		case EV_CHN_VOICE:
497 			ret = seq_chnvoice(scp, m, event);
498 			break;
499 		case EV_CHN_COMMON:
500 			ret = seq_chncommon(scp, m, event);
501 			break;
502 		case EV_SYSEX:
503 			ret = seq_sysex(scp, m, event);
504 			break;
505 		case SEQ_MIDIPUTC:
506 			mtx_unlock(&scp->seq_lock);
507 			ret = SYNTH_WRITERAW(m, &event[2], 1);
508 			mtx_lock(&scp->seq_lock);
509 			break;
510 		}
511 	return ret;
512 }
513 
514 static int
515 seq_addunit(void)
516 {
517 	struct seq_softc *scp;
518 	int ret;
519 	u_char *buf;
520 
521 	/* Allocate the softc. */
522 	ret = ENOMEM;
523 	scp = malloc(sizeof(*scp), M_DEVBUF, M_NOWAIT | M_ZERO);
524 	if (scp == NULL) {
525 		SEQ_DEBUG(1, printf("seq_addunit: softc allocation failed.\n"));
526 		goto err;
527 	}
528 	kobj_init((kobj_t)scp, &sequencer_class);
529 
530 	buf = malloc(sizeof(*buf) * EV_SZ * 1024, M_TEMP, M_NOWAIT | M_ZERO);
531 	if (buf == NULL)
532 		goto err;
533 	MIDIQ_INIT(scp->in_q, buf, EV_SZ * 1024);
534 	buf = malloc(sizeof(*buf) * EV_SZ * 1024, M_TEMP, M_NOWAIT | M_ZERO);
535 	if (buf == NULL)
536 		goto err;
537 	MIDIQ_INIT(scp->out_q, buf, EV_SZ * 1024);
538 	ret = EINVAL;
539 
540 	scp->midis = malloc(sizeof(kobj_t) * 32, M_TEMP, M_NOWAIT | M_ZERO);
541 	scp->midi_flags = malloc(sizeof(*scp->midi_flags) * 32, M_TEMP,
542 	    M_NOWAIT | M_ZERO);
543 
544 	if (scp->midis == NULL || scp->midi_flags == NULL)
545 		goto err;
546 
547 	scp->flags = 0;
548 
549 	mtx_init(&scp->seq_lock, "seqflq", NULL, 0);
550 	cv_init(&scp->state_cv, "seqstate");
551 	cv_init(&scp->empty_cv, "seqempty");
552 	cv_init(&scp->reset_cv, "seqtimer");
553 	cv_init(&scp->out_cv, "seqqout");
554 	cv_init(&scp->in_cv, "seqqin");
555 	cv_init(&scp->th_cv, "seqstart");
556 
557 	/*
558 	 * Init the damn timer
559 	 */
560 
561 	scp->mapper = midimapper_addseq(scp, &scp->unit, &scp->mapper_cookie);
562 	if (scp->mapper == NULL)
563 		goto err;
564 
565 	scp->seqdev = make_dev(&seq_cdevsw,
566 	    MIDIMKMINOR(scp->unit, SND_DEV_SEQ, 0), UID_ROOT,
567 	    GID_WHEEL, 0666, "sequencer%d", scp->unit);
568 
569 	scp->musicdev = make_dev(&seq_cdevsw,
570 	    MIDIMKMINOR(scp->unit, SND_DEV_MUSIC, 0), UID_ROOT,
571 	    GID_WHEEL, 0666, "music%d", scp->unit);
572 
573 	if (scp->seqdev == NULL || scp->musicdev == NULL)
574 		goto err;
575 	/*
576 	 * TODO: Add to list of sequencers this module provides
577 	 */
578 
579 	ret = kproc_create(seq_eventthread, scp, NULL, RFHIGHPID, 0,
580 	    "sequencer %02d", scp->unit);
581 
582 	if (ret)
583 		goto err;
584 
585 	scp->seqdev->si_drv1 = scp->musicdev->si_drv1 = scp;
586 
587 	SEQ_DEBUG(2, printf("sequencer %d created scp %p\n", scp->unit, scp));
588 
589 	ret = 0;
590 
591 	mtx_lock(&seqinfo_mtx);
592 	seqs[nseq++] = scp;
593 	mtx_unlock(&seqinfo_mtx);
594 
595 	goto ok;
596 
597 err:
598 	if (scp != NULL) {
599 		if (scp->seqdev != NULL)
600 			destroy_dev(scp->seqdev);
601 		if (scp->musicdev != NULL)
602 			destroy_dev(scp->musicdev);
603 		/*
604 	         * TODO: Destroy mutex and cv
605 	         */
606 		if (scp->midis != NULL)
607 			free(scp->midis, M_TEMP);
608 		if (scp->midi_flags != NULL)
609 			free(scp->midi_flags, M_TEMP);
610 		if (scp->out_q.b)
611 			free(scp->out_q.b, M_TEMP);
612 		if (scp->in_q.b)
613 			free(scp->in_q.b, M_TEMP);
614 		free(scp, M_DEVBUF);
615 	}
616 ok:
617 	return ret;
618 }
619 
620 static int
621 seq_delunit(int unit)
622 {
623 	struct seq_softc *scp = seqs[unit];
624 	int i;
625 
626 	//SEQ_DEBUG(4, printf("seq_delunit: %d\n", unit));
627 	SEQ_DEBUG(1, printf("seq_delunit: 1 \n"));
628 	mtx_lock(&scp->seq_lock);
629 
630 	scp->playing = 0;
631 	scp->done = 1;
632 	cv_broadcast(&scp->out_cv);
633 	cv_broadcast(&scp->state_cv);
634 	cv_broadcast(&scp->reset_cv);
635 	SEQ_DEBUG(1, printf("seq_delunit: 2 \n"));
636 	cv_wait(&scp->th_cv, &scp->seq_lock);
637 	SEQ_DEBUG(1, printf("seq_delunit: 3.0 \n"));
638 	mtx_unlock(&scp->seq_lock);
639 	SEQ_DEBUG(1, printf("seq_delunit: 3.1 \n"));
640 
641 	cv_destroy(&scp->state_cv);
642 	SEQ_DEBUG(1, printf("seq_delunit: 4 \n"));
643 	cv_destroy(&scp->empty_cv);
644 	SEQ_DEBUG(1, printf("seq_delunit: 5 \n"));
645 	cv_destroy(&scp->reset_cv);
646 	SEQ_DEBUG(1, printf("seq_delunit: 6 \n"));
647 	cv_destroy(&scp->out_cv);
648 	SEQ_DEBUG(1, printf("seq_delunit: 7 \n"));
649 	cv_destroy(&scp->in_cv);
650 	SEQ_DEBUG(1, printf("seq_delunit: 8 \n"));
651 	cv_destroy(&scp->th_cv);
652 
653 	SEQ_DEBUG(1, printf("seq_delunit: 10 \n"));
654 	if (scp->seqdev)
655 		destroy_dev(scp->seqdev);
656 	SEQ_DEBUG(1, printf("seq_delunit: 11 \n"));
657 	if (scp->musicdev)
658 		destroy_dev(scp->musicdev);
659 	SEQ_DEBUG(1, printf("seq_delunit: 12 \n"));
660 	scp->seqdev = scp->musicdev = NULL;
661 	if (scp->midis != NULL)
662 		free(scp->midis, M_TEMP);
663 	SEQ_DEBUG(1, printf("seq_delunit: 13 \n"));
664 	if (scp->midi_flags != NULL)
665 		free(scp->midi_flags, M_TEMP);
666 	SEQ_DEBUG(1, printf("seq_delunit: 14 \n"));
667 	free(scp->out_q.b, M_TEMP);
668 	SEQ_DEBUG(1, printf("seq_delunit: 15 \n"));
669 	free(scp->in_q.b, M_TEMP);
670 
671 	SEQ_DEBUG(1, printf("seq_delunit: 16 \n"));
672 
673 	mtx_destroy(&scp->seq_lock);
674 	SEQ_DEBUG(1, printf("seq_delunit: 17 \n"));
675 	free(scp, M_DEVBUF);
676 
677 	mtx_lock(&seqinfo_mtx);
678 	for (i = unit; i < (nseq - 1); i++)
679 		seqs[i] = seqs[i + 1];
680 	nseq--;
681 	mtx_unlock(&seqinfo_mtx);
682 
683 	return 0;
684 }
685 
686 int
687 seq_modevent(module_t mod, int type, void *data)
688 {
689 	int retval, r;
690 
691 	retval = 0;
692 
693 	switch (type) {
694 	case MOD_LOAD:
695 		mtx_init(&seqinfo_mtx, "seqmod", NULL, 0);
696 		retval = seq_addunit();
697 		break;
698 
699 	case MOD_UNLOAD:
700 		while (nseq) {
701 			r = seq_delunit(nseq - 1);
702 			if (r) {
703 				retval = r;
704 				break;
705 			}
706 		}
707 		if (nseq == 0) {
708 			retval = 0;
709 			mtx_destroy(&seqinfo_mtx);
710 		}
711 		break;
712 
713 	default:
714 		break;
715 	}
716 
717 	return retval;
718 }
719 
720 static int
721 seq_fetch_mid(struct seq_softc *scp, int unit, kobj_t *md)
722 {
723 
724 	if (unit > scp->midi_number || unit < 0)
725 		return EINVAL;
726 
727 	*md = scp->midis[unit];
728 
729 	return 0;
730 }
731 
732 int
733 seq_open(struct cdev *i_dev, int flags, int mode, struct thread *td)
734 {
735 	struct seq_softc *scp = i_dev->si_drv1;
736 	int i;
737 
738 	if (scp == NULL)
739 		return ENXIO;
740 
741 	SEQ_DEBUG(3, printf("seq_open: scp %p unit %d, flags 0x%x.\n",
742 	    scp, scp->unit, flags));
743 
744 	/*
745 	 * Mark this device busy.
746 	 */
747 
748 	mtx_lock(&scp->seq_lock);
749 	if (scp->busy) {
750 		mtx_unlock(&scp->seq_lock);
751 		SEQ_DEBUG(2, printf("seq_open: unit %d is busy.\n", scp->unit));
752 		return EBUSY;
753 	}
754 	scp->fflags = flags;
755 	/*
756 	if ((scp->fflags & O_NONBLOCK) != 0)
757 		scp->flags |= SEQ_F_NBIO;
758 		*/
759 	scp->music = MIDIDEV(i_dev) == SND_DEV_MUSIC;
760 
761 	/*
762 	 * Enumerate the available midi devices
763 	 */
764 	scp->midi_number = 0;
765 	scp->maxunits = midimapper_open(scp->mapper, &scp->mapper_cookie);
766 
767 	if (scp->maxunits == 0)
768 		SEQ_DEBUG(2, printf("seq_open: no midi devices\n"));
769 
770 	for (i = 0; i < scp->maxunits; i++) {
771 		scp->midis[scp->midi_number] =
772 		    midimapper_fetch_synth(scp->mapper, scp->mapper_cookie, i);
773 		if (scp->midis[scp->midi_number]) {
774 			if (SYNTH_OPEN(scp->midis[scp->midi_number], scp,
775 				scp->fflags) != 0)
776 				scp->midis[scp->midi_number] = NULL;
777 			else {
778 				scp->midi_flags[scp->midi_number] =
779 				    SYNTH_QUERY(scp->midis[scp->midi_number]);
780 				scp->midi_number++;
781 			}
782 		}
783 	}
784 
785 	timer_setvals(scp, 60, 100);
786 
787 	timer_start(scp);
788 	timer_stop(scp);
789 	/*
790 	 * actually, if we're in rdonly mode, we should start the timer
791 	 */
792 	/*
793 	 * TODO: Handle recording now
794 	 */
795 
796 	scp->out_water = MIDIQ_SIZE(scp->out_q) / 2;
797 
798 	scp->busy = 1;
799 	mtx_unlock(&scp->seq_lock);
800 
801 	SEQ_DEBUG(2, printf("seq_open: opened, mode %s.\n",
802 	    scp->music ? "music" : "sequencer"));
803 	SEQ_DEBUG(2,
804 	    printf("Sequencer %d %p opened maxunits %d midi_number %d:\n",
805 		scp->unit, scp, scp->maxunits, scp->midi_number));
806 	for (i = 0; i < scp->midi_number; i++)
807 		SEQ_DEBUG(3, printf("  midi %d %p\n", i, scp->midis[i]));
808 
809 	return 0;
810 }
811 
812 /*
813  * seq_close
814  */
815 int
816 seq_close(struct cdev *i_dev, int flags, int mode, struct thread *td)
817 {
818 	int i;
819 	struct seq_softc *scp = i_dev->si_drv1;
820 	int ret;
821 
822 	if (scp == NULL)
823 		return ENXIO;
824 
825 	SEQ_DEBUG(2, printf("seq_close: unit %d.\n", scp->unit));
826 
827 	mtx_lock(&scp->seq_lock);
828 
829 	ret = ENXIO;
830 	if (scp->busy == 0)
831 		goto err;
832 
833 	seq_reset(scp);
834 	seq_sync(scp);
835 
836 	for (i = 0; i < scp->midi_number; i++)
837 		if (scp->midis[i])
838 			SYNTH_CLOSE(scp->midis[i]);
839 
840 	midimapper_close(scp->mapper, scp->mapper_cookie);
841 
842 	timer_stop(scp);
843 
844 	scp->busy = 0;
845 	ret = 0;
846 
847 err:
848 	SEQ_DEBUG(3, printf("seq_close: closed ret = %d.\n", ret));
849 	mtx_unlock(&scp->seq_lock);
850 	return ret;
851 }
852 
853 int
854 seq_read(struct cdev *i_dev, struct uio *uio, int ioflag)
855 {
856 	int retval, used;
857 	struct seq_softc *scp = i_dev->si_drv1;
858 
859 #define SEQ_RSIZE 32
860 	u_char buf[SEQ_RSIZE];
861 
862 	if (scp == NULL)
863 		return ENXIO;
864 
865 	SEQ_DEBUG(7, printf("seq_read: unit %d, resid %d.\n",
866 	    scp->unit, uio->uio_resid));
867 
868 	mtx_lock(&scp->seq_lock);
869 	if ((scp->fflags & FREAD) == 0) {
870 		SEQ_DEBUG(2, printf("seq_read: unit %d is not for reading.\n",
871 		    scp->unit));
872 		retval = EIO;
873 		goto err1;
874 	}
875 	/*
876 	 * Begin recording.
877 	 */
878 	/*
879 	 * if ((scp->flags & SEQ_F_READING) == 0)
880 	 */
881 	/*
882 	 * TODO, start recording if not alread
883 	 */
884 
885 	/*
886 	 * I think the semantics are to return as soon
887 	 * as possible.
888 	 * Second thought, it doens't seem like midimoutain
889 	 * expects that at all.
890 	 * TODO: Look up in some sort of spec
891 	 */
892 
893 	while (uio->uio_resid > 0) {
894 		while (MIDIQ_EMPTY(scp->in_q)) {
895 			retval = EWOULDBLOCK;
896 			/*
897 			 * I wish I knew which one to care about
898 			 */
899 
900 			if (scp->fflags & O_NONBLOCK)
901 				goto err1;
902 			if (ioflag & O_NONBLOCK)
903 				goto err1;
904 
905 			retval = cv_wait_sig(&scp->in_cv, &scp->seq_lock);
906 			if (retval == EINTR)
907 				goto err1;
908 		}
909 
910 		used = MIN(MIDIQ_LEN(scp->in_q), uio->uio_resid);
911 		used = MIN(used, SEQ_RSIZE);
912 
913 		SEQ_DEBUG(8, printf("midiread: uiomove cc=%d\n", used));
914 		MIDIQ_DEQ(scp->in_q, buf, used);
915 		retval = uiomove(buf, used, uio);
916 		if (retval)
917 			goto err1;
918 	}
919 
920 	retval = 0;
921 err1:
922 	mtx_unlock(&scp->seq_lock);
923 	SEQ_DEBUG(6, printf("seq_read: ret %d, resid %d.\n",
924 	    retval, uio->uio_resid));
925 
926 	return retval;
927 }
928 
929 int
930 seq_write(struct cdev *i_dev, struct uio *uio, int ioflag)
931 {
932 	u_char event[EV_SZ], newevent[EV_SZ], ev_code;
933 	struct seq_softc *scp = i_dev->si_drv1;
934 	int retval;
935 	int used;
936 
937 	SEQ_DEBUG(7, printf("seq_write: unit %d, resid %d.\n",
938 	    scp->unit, uio->uio_resid));
939 
940 	if (scp == NULL)
941 		return ENXIO;
942 
943 	mtx_lock(&scp->seq_lock);
944 
945 	if ((scp->fflags & FWRITE) == 0) {
946 		SEQ_DEBUG(2, printf("seq_write: unit %d is not for writing.\n",
947 		    scp->unit));
948 		retval = EIO;
949 		goto err0;
950 	}
951 	while (uio->uio_resid > 0) {
952 		while (MIDIQ_AVAIL(scp->out_q) == 0) {
953 			retval = EWOULDBLOCK;
954 			if (scp->fflags & O_NONBLOCK)
955 				goto err0;
956 			if (ioflag & O_NONBLOCK)
957 				goto err0;
958 			SEQ_DEBUG(8, printf("seq_write cvwait\n"));
959 
960 			scp->playing = 1;
961 			cv_broadcast(&scp->out_cv);
962 			cv_broadcast(&scp->state_cv);
963 
964 			retval = cv_wait_sig(&scp->out_cv, &scp->seq_lock);
965 			/*
966 		         * We slept, maybe things have changed since last
967 		         * dying check
968 		         */
969 			if (retval == EINTR)
970 				goto err0;
971 #if 0
972 			/*
973 		         * Useless test
974 		         */
975 			if (scp != i_dev->si_drv1)
976 				retval = ENXIO;
977 #endif
978 		}
979 
980 		used = MIN(uio->uio_resid, 4);
981 
982 		SEQ_DEBUG(8, printf("seqout: resid %d len %jd avail %jd\n",
983 		    uio->uio_resid, (intmax_t)MIDIQ_LEN(scp->out_q),
984 		    (intmax_t)MIDIQ_AVAIL(scp->out_q)));
985 
986 		if (used != 4) {
987 			retval = ENXIO;
988 			goto err0;
989 		}
990 		retval = uiomove(event, used, uio);
991 		if (retval)
992 			goto err0;
993 
994 		ev_code = event[0];
995 		SEQ_DEBUG(8, printf("seq_write: unit %d, event %s.\n",
996 		    scp->unit, midi_cmdname(ev_code, cmdtab_seqevent)));
997 
998 		/* Have a look at the event code. */
999 		if (ev_code == SEQ_FULLSIZE) {
1000 
1001 			/*
1002 			 * TODO: restore code for SEQ_FULLSIZE
1003 			 */
1004 #if 0
1005 			/*
1006 			 * A long event, these are the patches/samples for a
1007 			 * synthesizer.
1008 			 */
1009 			midiunit = *(u_short *)&event[2];
1010 			mtx_lock(&sd->seq_lock);
1011 			ret = lookup_mididev(scp, midiunit, LOOKUP_OPEN, &md);
1012 			mtx_unlock(&sd->seq_lock);
1013 			if (ret != 0)
1014 				return (ret);
1015 
1016 			SEQ_DEBUG(printf("seq_write: loading a patch to the unit %d.\n", midiunit));
1017 
1018 			ret = md->synth.loadpatch(md, *(short *)&event[0], buf,
1019 			    p + 4, count, 0);
1020 			return (ret);
1021 #else
1022 			/*
1023 			 * For now, just flush the darn buffer
1024 			 */
1025 			SEQ_DEBUG(2,
1026 			   printf("seq_write: SEQ_FULLSIZE flusing buffer.\n"));
1027 			while (uio->uio_resid > 0) {
1028 				retval = uiomove(event, EV_SZ, uio);
1029 				if (retval)
1030 					goto err0;
1031 
1032 			}
1033 			retval = 0;
1034 			goto err0;
1035 #endif
1036 		}
1037 		retval = EINVAL;
1038 		if (ev_code >= 128) {
1039 
1040 			/*
1041 			 * Some sort of an extended event. The size is eight
1042 			 * bytes. scoop extra info.
1043 			 */
1044 			if (scp->music && ev_code == SEQ_EXTENDED) {
1045 				SEQ_DEBUG(2, printf("seq_write: invalid level two event %x.\n", ev_code));
1046 				goto err0;
1047 			}
1048 			if (uiomove((caddr_t)&event[4], 4, uio)) {
1049 				SEQ_DEBUG(2,
1050 				   printf("seq_write: user memory mangled?\n"));
1051 				goto err0;
1052 			}
1053 		} else {
1054 			/*
1055 			 * Size four event.
1056 			 */
1057 			if (scp->music) {
1058 				SEQ_DEBUG(2, printf("seq_write: four byte event in music mode.\n"));
1059 				goto err0;
1060 			}
1061 		}
1062 		if (ev_code == SEQ_MIDIPUTC) {
1063 			/*
1064 			 * TODO: event[2] is unit number to receive char.
1065 			 * Range check it.
1066 			 */
1067 		}
1068 		if (scp->music) {
1069 #ifdef not_ever_ever
1070 			if (event[0] == EV_TIMING &&
1071 			    (event[1] == TMR_START || event[1] == TMR_STOP)) {
1072 				/*
1073 			         * For now, try to make midimoutain work by
1074 			         * forcing these events to be processed
1075 				 * immediatly.
1076 			         */
1077 				seq_processevent(scp, event);
1078 			} else
1079 				MIDIQ_ENQ(scp->out_q, event, EV_SZ);
1080 #else
1081 			MIDIQ_ENQ(scp->out_q, event, EV_SZ);
1082 #endif
1083 		} else {
1084 			if (seq_convertold(event, newevent) > 0)
1085 				MIDIQ_ENQ(scp->out_q, newevent, EV_SZ);
1086 #if 0
1087 			else
1088 				goto err0;
1089 #endif
1090 		}
1091 
1092 	}
1093 
1094 	scp->playing = 1;
1095 	cv_broadcast(&scp->state_cv);
1096 	cv_broadcast(&scp->out_cv);
1097 
1098 	retval = 0;
1099 
1100 err0:
1101 	SEQ_DEBUG(6,
1102 	    printf("seq_write done: leftover buffer length %d retval %d\n",
1103 	    uio->uio_resid, retval));
1104 	mtx_unlock(&scp->seq_lock);
1105 	return retval;
1106 }
1107 
1108 int
1109 seq_ioctl(struct cdev *i_dev, u_long cmd, caddr_t arg, int mode,
1110     struct thread *td)
1111 {
1112 	int midiunit, ret, tmp;
1113 	struct seq_softc *scp = i_dev->si_drv1;
1114 	struct synth_info *synthinfo;
1115 	struct midi_info *midiinfo;
1116 	u_char event[EV_SZ];
1117 	u_char newevent[EV_SZ];
1118 
1119 	kobj_t md;
1120 
1121 	/*
1122 	 * struct snd_size *sndsize;
1123 	 */
1124 
1125 	if (scp == NULL)
1126 		return ENXIO;
1127 
1128 	SEQ_DEBUG(6, printf("seq_ioctl: unit %d, cmd %s.\n",
1129 	    scp->unit, midi_cmdname(cmd, cmdtab_seqioctl)));
1130 
1131 	ret = 0;
1132 
1133 	switch (cmd) {
1134 	case SNDCTL_SEQ_GETTIME:
1135 		/*
1136 		 * ioctl needed by libtse
1137 		 */
1138 		mtx_lock(&scp->seq_lock);
1139 		*(int *)arg = timer_now(scp);
1140 		mtx_unlock(&scp->seq_lock);
1141 		SEQ_DEBUG(6, printf("seq_ioctl: gettime %d.\n", *(int *)arg));
1142 		ret = 0;
1143 		break;
1144 	case SNDCTL_TMR_METRONOME:
1145 		/* fallthrough */
1146 	case SNDCTL_TMR_SOURCE:
1147 		/*
1148 		 * Not implemented
1149 		 */
1150 		ret = 0;
1151 		break;
1152 	case SNDCTL_TMR_TEMPO:
1153 		event[1] = TMR_TEMPO;
1154 		event[4] = *(int *)arg & 0xFF;
1155 		event[5] = (*(int *)arg >> 8) & 0xFF;
1156 		event[6] = (*(int *)arg >> 16) & 0xFF;
1157 		event[7] = (*(int *)arg >> 24) & 0xFF;
1158 		goto timerevent;
1159 	case SNDCTL_TMR_TIMEBASE:
1160 		event[1] = TMR_TIMERBASE;
1161 		event[4] = *(int *)arg & 0xFF;
1162 		event[5] = (*(int *)arg >> 8) & 0xFF;
1163 		event[6] = (*(int *)arg >> 16) & 0xFF;
1164 		event[7] = (*(int *)arg >> 24) & 0xFF;
1165 		goto timerevent;
1166 	case SNDCTL_TMR_START:
1167 		event[1] = TMR_START;
1168 		goto timerevent;
1169 	case SNDCTL_TMR_STOP:
1170 		event[1] = TMR_STOP;
1171 		goto timerevent;
1172 	case SNDCTL_TMR_CONTINUE:
1173 		event[1] = TMR_CONTINUE;
1174 timerevent:
1175 		event[0] = EV_TIMING;
1176 		mtx_lock(&scp->seq_lock);
1177 		if (!scp->music) {
1178 			ret = EINVAL;
1179 			mtx_unlock(&scp->seq_lock);
1180 			break;
1181 		}
1182 		seq_processevent(scp, event);
1183 		mtx_unlock(&scp->seq_lock);
1184 		break;
1185 	case SNDCTL_TMR_SELECT:
1186 		SEQ_DEBUG(2,
1187 		    printf("seq_ioctl: SNDCTL_TMR_SELECT not supported\n"));
1188 		ret = EINVAL;
1189 		break;
1190 	case SNDCTL_SEQ_SYNC:
1191 		if (mode == O_RDONLY) {
1192 			ret = 0;
1193 			break;
1194 		}
1195 		mtx_lock(&scp->seq_lock);
1196 		ret = seq_sync(scp);
1197 		mtx_unlock(&scp->seq_lock);
1198 		break;
1199 	case SNDCTL_SEQ_PANIC:
1200 		/* fallthrough */
1201 	case SNDCTL_SEQ_RESET:
1202 		/*
1203 		 * SNDCTL_SEQ_PANIC == SNDCTL_SEQ_RESET
1204 		 */
1205 		mtx_lock(&scp->seq_lock);
1206 		seq_reset(scp);
1207 		mtx_unlock(&scp->seq_lock);
1208 		ret = 0;
1209 		break;
1210 	case SNDCTL_SEQ_TESTMIDI:
1211 		mtx_lock(&scp->seq_lock);
1212 		/*
1213 		 * TODO: SNDCTL_SEQ_TESTMIDI now means "can I write to the
1214 		 * device?".
1215 		 */
1216 		mtx_unlock(&scp->seq_lock);
1217 		break;
1218 #if 0
1219 	case SNDCTL_SEQ_GETINCOUNT:
1220 		if (mode == O_WRONLY)
1221 			*(int *)arg = 0;
1222 		else {
1223 			mtx_lock(&scp->seq_lock);
1224 			*(int *)arg = scp->in_q.rl;
1225 			mtx_unlock(&scp->seq_lock);
1226 			SEQ_DEBUG(printf("seq_ioctl: incount %d.\n",
1227 			    *(int *)arg));
1228 		}
1229 		ret = 0;
1230 		break;
1231 	case SNDCTL_SEQ_GETOUTCOUNT:
1232 		if (mode == O_RDONLY)
1233 			*(int *)arg = 0;
1234 		else {
1235 			mtx_lock(&scp->seq_lock);
1236 			*(int *)arg = scp->out_q.fl;
1237 			mtx_unlock(&scp->seq_lock);
1238 			SEQ_DEBUG(printf("seq_ioctl: outcount %d.\n",
1239 			    *(int *)arg));
1240 		}
1241 		ret = 0;
1242 		break;
1243 #endif
1244 	case SNDCTL_SEQ_CTRLRATE:
1245 		if (*(int *)arg != 0) {
1246 			ret = EINVAL;
1247 			break;
1248 		}
1249 		mtx_lock(&scp->seq_lock);
1250 		*(int *)arg = scp->timerbase;
1251 		mtx_unlock(&scp->seq_lock);
1252 		SEQ_DEBUG(3, printf("seq_ioctl: ctrlrate %d.\n", *(int *)arg));
1253 		ret = 0;
1254 		break;
1255 		/*
1256 		 * TODO: ioctl SNDCTL_SEQ_RESETSAMPLES
1257 		 */
1258 #if 0
1259 	case SNDCTL_SEQ_RESETSAMPLES:
1260 		mtx_lock(&scp->seq_lock);
1261 		ret = lookup_mididev(scp, *(int *)arg, LOOKUP_OPEN, &md);
1262 		mtx_unlock(&scp->seq_lock);
1263 		if (ret != 0)
1264 			break;
1265 		ret = midi_ioctl(MIDIMKDEV(major(i_dev), *(int *)arg,
1266 		    SND_DEV_MIDIN), cmd, arg, mode, td);
1267 		break;
1268 #endif
1269 	case SNDCTL_SEQ_NRSYNTHS:
1270 		mtx_lock(&scp->seq_lock);
1271 		*(int *)arg = scp->midi_number;
1272 		mtx_unlock(&scp->seq_lock);
1273 		SEQ_DEBUG(3, printf("seq_ioctl: synths %d.\n", *(int *)arg));
1274 		ret = 0;
1275 		break;
1276 	case SNDCTL_SEQ_NRMIDIS:
1277 		mtx_lock(&scp->seq_lock);
1278 		if (scp->music)
1279 			*(int *)arg = 0;
1280 		else {
1281 			/*
1282 		         * TODO: count the numbder of devices that can WRITERAW
1283 		         */
1284 			*(int *)arg = scp->midi_number;
1285 		}
1286 		mtx_unlock(&scp->seq_lock);
1287 		SEQ_DEBUG(3, printf("seq_ioctl: midis %d.\n", *(int *)arg));
1288 		ret = 0;
1289 		break;
1290 		/*
1291 		 * TODO: ioctl SNDCTL_SYNTH_MEMAVL
1292 		 */
1293 #if 0
1294 	case SNDCTL_SYNTH_MEMAVL:
1295 		mtx_lock(&scp->seq_lock);
1296 		ret = lookup_mididev(scp, *(int *)arg, LOOKUP_OPEN, &md);
1297 		mtx_unlock(&scp->seq_lock);
1298 		if (ret != 0)
1299 			break;
1300 		ret = midi_ioctl(MIDIMKDEV(major(i_dev), *(int *)arg,
1301 		    SND_DEV_MIDIN), cmd, arg, mode, td);
1302 		break;
1303 #endif
1304 	case SNDCTL_SEQ_OUTOFBAND:
1305 		for (ret = 0; ret < EV_SZ; ret++)
1306 			event[ret] = (u_char)arg[0];
1307 
1308 		mtx_lock(&scp->seq_lock);
1309 		if (scp->music)
1310 			ret = seq_processevent(scp, event);
1311 		else {
1312 			if (seq_convertold(event, newevent) > 0)
1313 				ret = seq_processevent(scp, newevent);
1314 			else
1315 				ret = EINVAL;
1316 		}
1317 		mtx_unlock(&scp->seq_lock);
1318 		break;
1319 	case SNDCTL_SYNTH_INFO:
1320 		synthinfo = (struct synth_info *)arg;
1321 		midiunit = synthinfo->device;
1322 		mtx_lock(&scp->seq_lock);
1323 		if (seq_fetch_mid(scp, midiunit, &md) == 0) {
1324 			bzero(synthinfo, sizeof(*synthinfo));
1325 			synthinfo->name[0] = 'f';
1326 			synthinfo->name[1] = 'a';
1327 			synthinfo->name[2] = 'k';
1328 			synthinfo->name[3] = 'e';
1329 			synthinfo->name[4] = 's';
1330 			synthinfo->name[5] = 'y';
1331 			synthinfo->name[6] = 'n';
1332 			synthinfo->name[7] = 't';
1333 			synthinfo->name[8] = 'h';
1334 			synthinfo->device = midiunit;
1335 			synthinfo->synth_type = SYNTH_TYPE_MIDI;
1336 			synthinfo->capabilities = scp->midi_flags[midiunit];
1337 			ret = 0;
1338 		} else
1339 			ret = EINVAL;
1340 		mtx_unlock(&scp->seq_lock);
1341 		break;
1342 	case SNDCTL_MIDI_INFO:
1343 		midiinfo = (struct midi_info *)arg;
1344 		midiunit = midiinfo->device;
1345 		mtx_lock(&scp->seq_lock);
1346 		if (seq_fetch_mid(scp, midiunit, &md) == 0) {
1347 			bzero(midiinfo, sizeof(*midiinfo));
1348 			midiinfo->name[0] = 'f';
1349 			midiinfo->name[1] = 'a';
1350 			midiinfo->name[2] = 'k';
1351 			midiinfo->name[3] = 'e';
1352 			midiinfo->name[4] = 'm';
1353 			midiinfo->name[5] = 'i';
1354 			midiinfo->name[6] = 'd';
1355 			midiinfo->name[7] = 'i';
1356 			midiinfo->device = midiunit;
1357 			midiinfo->capabilities = scp->midi_flags[midiunit];
1358 			/*
1359 		         * TODO: What devtype?
1360 		         */
1361 			midiinfo->dev_type = 0x01;
1362 			ret = 0;
1363 		} else
1364 			ret = EINVAL;
1365 		mtx_unlock(&scp->seq_lock);
1366 		break;
1367 	case SNDCTL_SEQ_THRESHOLD:
1368 		mtx_lock(&scp->seq_lock);
1369 		RANGE(*(int *)arg, 1, MIDIQ_SIZE(scp->out_q) - 1);
1370 		scp->out_water = *(int *)arg;
1371 		mtx_unlock(&scp->seq_lock);
1372 		SEQ_DEBUG(3, printf("seq_ioctl: water %d.\n", *(int *)arg));
1373 		ret = 0;
1374 		break;
1375 	case SNDCTL_MIDI_PRETIME:
1376 		tmp = *(int *)arg;
1377 		if (tmp < 0)
1378 			tmp = 0;
1379 		mtx_lock(&scp->seq_lock);
1380 		scp->pre_event_timeout = (hz * tmp) / 10;
1381 		*(int *)arg = scp->pre_event_timeout;
1382 		mtx_unlock(&scp->seq_lock);
1383 		SEQ_DEBUG(3, printf("seq_ioctl: pretime %d.\n", *(int *)arg));
1384 		ret = 0;
1385 		break;
1386 	case SNDCTL_FM_4OP_ENABLE:
1387 	case SNDCTL_PMGR_IFACE:
1388 	case SNDCTL_PMGR_ACCESS:
1389 		/*
1390 		 * Patch manager and fm are ded, ded, ded.
1391 		 */
1392 		/* fallthrough */
1393 	default:
1394 		/*
1395 		 * TODO: Consider ioctl default case.
1396 		 * Old code used to
1397 		 * if ((scp->fflags & O_ACCMODE) == FREAD) {
1398 		 *	ret = EIO;
1399 		 *	break;
1400 		 * }
1401 		 * Then pass on the ioctl to device 0
1402 		 */
1403 		SEQ_DEBUG(2,
1404 		    printf("seq_ioctl: unsupported IOCTL %ld.\n", cmd));
1405 		ret = EINVAL;
1406 		break;
1407 	}
1408 
1409 	return ret;
1410 }
1411 
1412 int
1413 seq_poll(struct cdev *i_dev, int events, struct thread *td)
1414 {
1415 	int ret, lim;
1416 	struct seq_softc *scp = i_dev->si_drv1;
1417 
1418 	SEQ_DEBUG(3, printf("seq_poll: unit %d.\n", scp->unit));
1419 	SEQ_DEBUG(1, printf("seq_poll: unit %d.\n", scp->unit));
1420 
1421 	mtx_lock(&scp->seq_lock);
1422 
1423 	ret = 0;
1424 
1425 	/* Look up the apropriate queue and select it. */
1426 	if ((events & (POLLOUT | POLLWRNORM)) != 0) {
1427 		/* Start playing. */
1428 		scp->playing = 1;
1429 		cv_broadcast(&scp->state_cv);
1430 		cv_broadcast(&scp->out_cv);
1431 
1432 		lim = scp->out_water;
1433 
1434 		if (MIDIQ_AVAIL(scp->out_q) < lim)
1435 			/* No enough space, record select. */
1436 			selrecord(td, &scp->out_sel);
1437 		else
1438 			/* We can write now. */
1439 			ret |= events & (POLLOUT | POLLWRNORM);
1440 	}
1441 	if ((events & (POLLIN | POLLRDNORM)) != 0) {
1442 		/* TODO: Start recording. */
1443 
1444 		/* Find out the boundary. */
1445 		lim = 1;
1446 		if (MIDIQ_LEN(scp->in_q) < lim)
1447 			/* No data ready, record select. */
1448 			selrecord(td, &scp->in_sel);
1449 		else
1450 			/* We can read now. */
1451 			ret |= events & (POLLIN | POLLRDNORM);
1452 	}
1453 	mtx_unlock(&scp->seq_lock);
1454 
1455 	return (ret);
1456 }
1457 
1458 #if 0
1459 static void
1460 sein_qtr(void *p, void /* mididev_info */ *md)
1461 {
1462 	struct seq_softc *scp;
1463 
1464 	scp = (struct seq_softc *)p;
1465 
1466 	mtx_lock(&scp->seq_lock);
1467 
1468 	/* Restart playing if we have the data to output. */
1469 	if (scp->queueout_pending)
1470 		seq_callback(scp, SEQ_CB_START | SEQ_CB_WR);
1471 	/* Check the midi device if we are reading. */
1472 	if ((scp->flags & SEQ_F_READING) != 0)
1473 		seq_midiinput(scp, md);
1474 
1475 	mtx_unlock(&scp->seq_lock);
1476 }
1477 
1478 #endif
1479 /*
1480  * seq_convertold
1481  * Was the old playevent.  Use this to convert and old
1482  * style /dev/sequencer event to a /dev/music event
1483  */
1484 static int
1485 seq_convertold(u_char *event, u_char *out)
1486 {
1487 	int used;
1488 	u_char dev, chn, note, vel;
1489 
1490 	out[0] = out[1] = out[2] = out[3] = out[4] = out[5] = out[6] =
1491 	    out[7] = 0;
1492 
1493 	dev = 0;
1494 	chn = event[1];
1495 	note = event[2];
1496 	vel = event[3];
1497 
1498 	used = 0;
1499 
1500 restart:
1501 	/*
1502 	 * TODO: Debug statement
1503 	 */
1504 	switch (event[0]) {
1505 	case EV_TIMING:
1506 	case EV_CHN_VOICE:
1507 	case EV_CHN_COMMON:
1508 	case EV_SYSEX:
1509 	case EV_SEQ_LOCAL:
1510 		out[0] = event[0];
1511 		out[1] = event[1];
1512 		out[2] = event[2];
1513 		out[3] = event[3];
1514 		out[4] = event[4];
1515 		out[5] = event[5];
1516 		out[6] = event[6];
1517 		out[7] = event[7];
1518 		used += 8;
1519 		break;
1520 	case SEQ_NOTEOFF:
1521 		out[0] = EV_CHN_VOICE;
1522 		out[1] = dev;
1523 		out[2] = MIDI_NOTEOFF;
1524 		out[3] = chn;
1525 		out[4] = note;
1526 		out[5] = 255;
1527 		used += 4;
1528 		break;
1529 
1530 	case SEQ_NOTEON:
1531 		out[0] = EV_CHN_VOICE;
1532 		out[1] = dev;
1533 		out[2] = MIDI_NOTEON;
1534 		out[3] = chn;
1535 		out[4] = note;
1536 		out[5] = vel;
1537 		used += 4;
1538 		break;
1539 
1540 		/*
1541 		 * wait delay = (event[2] << 16) + (event[3] << 8) + event[4]
1542 		 */
1543 
1544 	case SEQ_PGMCHANGE:
1545 		out[0] = EV_CHN_COMMON;
1546 		out[1] = dev;
1547 		out[2] = MIDI_PGM_CHANGE;
1548 		out[3] = chn;
1549 		out[4] = note;
1550 		out[5] = vel;
1551 		used += 4;
1552 		break;
1553 /*
1554 		out[0] = EV_TIMING;
1555 		out[1] = dev;
1556 		out[2] = MIDI_PGM_CHANGE;
1557 		out[3] = chn;
1558 		out[4] = note;
1559 		out[5] = vel;
1560 		SEQ_DEBUG(4,printf("seq_playevent: synctimer\n"));
1561 		break;
1562 */
1563 
1564 	case SEQ_MIDIPUTC:
1565 		SEQ_DEBUG(4,
1566 		    printf("seq_playevent: put data 0x%02x, unit %d.\n",
1567 		    event[1], event[2]));
1568 		/*
1569 		 * Pass through to the midi device.
1570 		 * device = event[2]
1571 		 * data = event[1]
1572 		 */
1573 		out[0] = SEQ_MIDIPUTC;
1574 		out[1] = dev;
1575 		out[2] = chn;
1576 		used += 4;
1577 		break;
1578 #ifdef notyet
1579 	case SEQ_ECHO:
1580 		/*
1581 		 * This isn't handled here yet because I don't know if I can
1582 		 * just use four bytes events.  There might be consequences
1583 		 * in the _read routing
1584 		 */
1585 		if (seq_copytoinput(scp, event, 4) == EAGAIN) {
1586 			ret = QUEUEFULL;
1587 			break;
1588 		}
1589 		ret = MORE;
1590 		break;
1591 #endif
1592 	case SEQ_EXTENDED:
1593 		switch (event[1]) {
1594 		case SEQ_NOTEOFF:
1595 		case SEQ_NOTEON:
1596 		case SEQ_PGMCHANGE:
1597 			event++;
1598 			used = 4;
1599 			goto restart;
1600 			break;
1601 		case SEQ_AFTERTOUCH:
1602 			/*
1603 			 * SYNTH_AFTERTOUCH(md, event[3], event[4])
1604 			 */
1605 		case SEQ_BALANCE:
1606 			/*
1607 			 * SYNTH_PANNING(md, event[3], (char)event[4])
1608 			 */
1609 		case SEQ_CONTROLLER:
1610 			/*
1611 			 * SYNTH_CONTROLLER(md, event[3], event[4], *(short *)&event[5])
1612 			 */
1613 		case SEQ_VOLMODE:
1614 			/*
1615 			 * SYNTH_VOLUMEMETHOD(md, event[3])
1616 			 */
1617 		default:
1618 			SEQ_DEBUG(2,
1619 			    printf("seq_convertold: SEQ_EXTENDED type %d"
1620 			    "not handled\n", event[1]));
1621 			break;
1622 		}
1623 		break;
1624 	case SEQ_WAIT:
1625 		out[0] = EV_TIMING;
1626 		out[1] = TMR_WAIT_REL;
1627 		out[4] = event[2];
1628 		out[5] = event[3];
1629 		out[6] = event[4];
1630 
1631 		SEQ_DEBUG(5, printf("SEQ_WAIT %d",
1632 		    event[2] + (event[3] << 8) + (event[4] << 24)));
1633 
1634 		used += 4;
1635 		break;
1636 
1637 	case SEQ_ECHO:
1638 	case SEQ_SYNCTIMER:
1639 	case SEQ_PRIVATE:
1640 	default:
1641 		SEQ_DEBUG(2,
1642 		  printf("seq_convertold: event type %d not handled %d %d %d\n",
1643 		    event[0], event[1], event[2], event[3]));
1644 		break;
1645 	}
1646 	return used;
1647 }
1648 
1649 /*
1650  * Writting to the sequencer buffer never blocks and drops
1651  * input which cannot be queued
1652  */
1653 void
1654 seq_copytoinput(struct seq_softc *scp, u_char *event, int len)
1655 {
1656 
1657 	mtx_assert(&scp->seq_lock, MA_OWNED);
1658 
1659 	if (MIDIQ_AVAIL(scp->in_q) < len) {
1660 		/*
1661 	         * ENOROOM?  EINPUTDROPPED? ETOUGHLUCK?
1662 	         */
1663 		SEQ_DEBUG(2, printf("seq_copytoinput: queue full\n"));
1664 	} else {
1665 		MIDIQ_ENQ(scp->in_q, event, len);
1666 		selwakeup(&scp->in_sel);
1667 		cv_broadcast(&scp->in_cv);
1668 	}
1669 
1670 }
1671 
1672 static int
1673 seq_chnvoice(struct seq_softc *scp, kobj_t md, u_char *event)
1674 {
1675 	int ret, voice;
1676 	u_char cmd, chn, note, parm;
1677 
1678 	ret = 0;
1679 	cmd = event[2];
1680 	chn = event[3];
1681 	note = event[4];
1682 	parm = event[5];
1683 
1684 	mtx_assert(&scp->seq_lock, MA_OWNED);
1685 
1686 	SEQ_DEBUG(5, printf("seq_chnvoice: unit %d, dev %d, cmd %s,"
1687 	    " chn %d, note %d, parm %d.\n", scp->unit, event[1],
1688 	    midi_cmdname(cmd, cmdtab_seqcv), chn, note, parm));
1689 
1690 	voice = SYNTH_ALLOC(md, chn, note);
1691 
1692 	mtx_unlock(&scp->seq_lock);
1693 
1694 	switch (cmd) {
1695 	case MIDI_NOTEON:
1696 		if (note < 128 || note == 255) {
1697 #if 0
1698 			if (scp->music && chn == 9) {
1699 				/*
1700 				 * This channel is a percussion. The note
1701 				 * number is the patch number.
1702 				 */
1703 				/*
1704 				mtx_unlock(&scp->seq_lock);
1705 				if (SYNTH_SETINSTR(md, voice, 128 + note)
1706 				    == EAGAIN) {
1707 					mtx_lock(&scp->seq_lock);
1708 					return (QUEUEFULL);
1709 				}
1710 				mtx_lock(&scp->seq_lock);
1711 				*/
1712 				note = 60;	/* Middle C. */
1713 			}
1714 #endif
1715 			if (scp->music) {
1716 				/*
1717 				mtx_unlock(&scp->seq_lock);
1718 				if (SYNTH_SETUPVOICE(md, voice, chn)
1719 				    == EAGAIN) {
1720 					mtx_lock(&scp->seq_lock);
1721 					return (QUEUEFULL);
1722 				}
1723 				mtx_lock(&scp->seq_lock);
1724 				*/
1725 			}
1726 			SYNTH_STARTNOTE(md, voice, note, parm);
1727 		}
1728 		break;
1729 	case MIDI_NOTEOFF:
1730 		SYNTH_KILLNOTE(md, voice, note, parm);
1731 		break;
1732 	case MIDI_KEY_PRESSURE:
1733 		SYNTH_AFTERTOUCH(md, voice, parm);
1734 		break;
1735 	default:
1736 		ret = 1;
1737 		SEQ_DEBUG(2, printf("seq_chnvoice event type %d not handled\n",
1738 		    event[1]));
1739 		break;
1740 	}
1741 
1742 	mtx_lock(&scp->seq_lock);
1743 	return ret;
1744 }
1745 
1746 static int
1747 seq_chncommon(struct seq_softc *scp, kobj_t md, u_char *event)
1748 {
1749 	int ret;
1750 	u_short w14;
1751 	u_char cmd, chn, p1;
1752 
1753 	ret = 0;
1754 	cmd = event[2];
1755 	chn = event[3];
1756 	p1 = event[4];
1757 	w14 = *(u_short *)&event[6];
1758 
1759 	SEQ_DEBUG(5, printf("seq_chncommon: unit %d, dev %d, cmd %s, chn %d,"
1760 	    " p1 %d, w14 %d.\n", scp->unit, event[1],
1761 	    midi_cmdname(cmd, cmdtab_seqccmn), chn, p1, w14));
1762 	mtx_unlock(&scp->seq_lock);
1763 	switch (cmd) {
1764 	case MIDI_PGM_CHANGE:
1765 		SEQ_DEBUG(4, printf("seq_chncommon pgmchn chn %d pg %d\n",
1766 		    chn, p1));
1767 		SYNTH_SETINSTR(md, chn, p1);
1768 		break;
1769 	case MIDI_CTL_CHANGE:
1770 		SEQ_DEBUG(4, printf("seq_chncommon ctlch chn %d pg %d %d\n",
1771 		    chn, p1, w14));
1772 		SYNTH_CONTROLLER(md, chn, p1, w14);
1773 		break;
1774 	case MIDI_PITCH_BEND:
1775 		if (scp->music) {
1776 			/*
1777 		         * TODO: MIDI_PITCH_BEND
1778 		         */
1779 #if 0
1780 			mtx_lock(&md->synth.vc_mtx);
1781 			md->synth.chn_info[chn].bender_value = w14;
1782 			if (md->midiunit >= 0) {
1783 				/*
1784 				 * Handle all of the notes playing on this
1785 				 * channel.
1786 				 */
1787 				key = ((int)chn << 8);
1788 				for (i = 0; i < md->synth.alloc.max_voice; i++)
1789 					if ((md->synth.alloc.map[i] & 0xff00) == key) {
1790 						mtx_unlock(&md->synth.vc_mtx);
1791 						mtx_unlock(&scp->seq_lock);
1792 						if (md->synth.bender(md, i, w14) == EAGAIN) {
1793 							mtx_lock(&scp->seq_lock);
1794 							return (QUEUEFULL);
1795 						}
1796 						mtx_lock(&scp->seq_lock);
1797 					}
1798 			} else {
1799 				mtx_unlock(&md->synth.vc_mtx);
1800 				mtx_unlock(&scp->seq_lock);
1801 				if (md->synth.bender(md, chn, w14) == EAGAIN) {
1802 					mtx_lock(&scp->seq_lock);
1803 					return (QUEUEFULL);
1804 				}
1805 				mtx_lock(&scp->seq_lock);
1806 			}
1807 #endif
1808 		} else
1809 			SYNTH_BENDER(md, chn, w14);
1810 		break;
1811 	default:
1812 		ret = 1;
1813 		SEQ_DEBUG(2,
1814 		    printf("seq_chncommon event type %d not handled.\n",
1815 		    event[1]));
1816 		break;
1817 
1818 	}
1819 	mtx_lock(&scp->seq_lock);
1820 	return ret;
1821 }
1822 
1823 static int
1824 seq_timing(struct seq_softc *scp, u_char *event)
1825 {
1826 	int param;
1827 	int ret;
1828 
1829 	ret = 0;
1830 	param = event[4] + (event[5] << 8) +
1831 	    (event[6] << 16) + (event[7] << 24);
1832 
1833 	SEQ_DEBUG(5, printf("seq_timing: unit %d, cmd %d, param %d.\n",
1834 	    scp->unit, event[1], param));
1835 	switch (event[1]) {
1836 	case TMR_WAIT_REL:
1837 		timer_wait(scp, param, 0);
1838 		break;
1839 	case TMR_WAIT_ABS:
1840 		timer_wait(scp, param, 1);
1841 		break;
1842 	case TMR_START:
1843 		timer_start(scp);
1844 		cv_broadcast(&scp->reset_cv);
1845 		break;
1846 	case TMR_STOP:
1847 		timer_stop(scp);
1848 		/*
1849 		 * The following cv_broadcast isn't needed since we only
1850 		 * wait for 0->1 transitions.  It probably won't hurt
1851 		 */
1852 		cv_broadcast(&scp->reset_cv);
1853 		break;
1854 	case TMR_CONTINUE:
1855 		timer_continue(scp);
1856 		cv_broadcast(&scp->reset_cv);
1857 		break;
1858 	case TMR_TEMPO:
1859 		if (param < 8)
1860 			param = 8;
1861 		if (param > 360)
1862 			param = 360;
1863 		SEQ_DEBUG(4, printf("Timer set tempo %d\n", param));
1864 		timer_setvals(scp, param, scp->timerbase);
1865 		break;
1866 	case TMR_TIMERBASE:
1867 		if (param < 1)
1868 			param = 1;
1869 		if (param > 1000)
1870 			param = 1000;
1871 		SEQ_DEBUG(4, printf("Timer set timerbase %d\n", param));
1872 		timer_setvals(scp, scp->tempo, param);
1873 		break;
1874 	case TMR_ECHO:
1875 		/*
1876 		 * TODO: Consider making 4-byte events for /dev/sequencer
1877 		 * PRO: Maybe needed by legacy apps
1878 		 * CON: soundcard.h has been warning for a while many years
1879 		 * to expect 8 byte events.
1880 		 */
1881 #if 0
1882 		if (scp->music)
1883 			seq_copytoinput(scp, event, 8);
1884 		else {
1885 			param = (param << 8 | SEQ_ECHO);
1886 			seq_copytoinput(scp, (u_char *)&param, 4);
1887 		}
1888 #else
1889 		seq_copytoinput(scp, event, 8);
1890 #endif
1891 		break;
1892 	default:
1893 		SEQ_DEBUG(2, printf("seq_timing event type %d not handled.\n",
1894 		    event[1]));
1895 		ret = 1;
1896 		break;
1897 	}
1898 	return ret;
1899 }
1900 
1901 static int
1902 seq_local(struct seq_softc *scp, u_char *event)
1903 {
1904 	int ret;
1905 
1906 	ret = 0;
1907 	mtx_assert(&scp->seq_lock, MA_OWNED);
1908 
1909 	SEQ_DEBUG(5, printf("seq_local: unit %d, cmd %d\n", scp->unit,
1910 	    event[1]));
1911 	switch (event[1]) {
1912 	default:
1913 		SEQ_DEBUG(1, printf("seq_local event type %d not handled\n",
1914 		    event[1]));
1915 		ret = 1;
1916 		break;
1917 	}
1918 	return ret;
1919 }
1920 
1921 static int
1922 seq_sysex(struct seq_softc *scp, kobj_t md, u_char *event)
1923 {
1924 	int i, l;
1925 
1926 	mtx_assert(&scp->seq_lock, MA_OWNED);
1927 	SEQ_DEBUG(5, printf("seq_sysex: unit %d device %d\n", scp->unit,
1928 	    event[1]));
1929 	l = 0;
1930 	for (i = 0; i < 6 && event[i + 2] != 0xff; i++)
1931 		l = i + 1;
1932 	if (l > 0) {
1933 		mtx_unlock(&scp->seq_lock);
1934 		if (SYNTH_SENDSYSEX(md, &event[2], l) == EAGAIN) {
1935 			mtx_lock(&scp->seq_lock);
1936 			return 1;
1937 		}
1938 		mtx_lock(&scp->seq_lock);
1939 	}
1940 	return 0;
1941 }
1942 
1943 /*
1944  * Reset no longer closes the raw devices nor seq_sync's
1945  * Callers are IOCTL and seq_close
1946  */
1947 static void
1948 seq_reset(struct seq_softc *scp)
1949 {
1950 	int chn, i;
1951 	kobj_t m;
1952 
1953 	mtx_assert(&scp->seq_lock, MA_OWNED);
1954 
1955 	SEQ_DEBUG(5, printf("seq_reset: unit %d.\n", scp->unit));
1956 
1957 	/*
1958 	 * Stop reading and writing.
1959 	 */
1960 
1961 	/* scp->recording = 0; */
1962 	scp->playing = 0;
1963 	cv_broadcast(&scp->state_cv);
1964 	cv_broadcast(&scp->out_cv);
1965 	cv_broadcast(&scp->reset_cv);
1966 
1967 	/*
1968 	 * For now, don't reset the timers.
1969 	 */
1970 	MIDIQ_CLEAR(scp->in_q);
1971 	MIDIQ_CLEAR(scp->out_q);
1972 
1973 	for (i = 0; i < scp->midi_number; i++) {
1974 		m = scp->midis[i];
1975 		mtx_unlock(&scp->seq_lock);
1976 		SYNTH_RESET(m);
1977 		for (chn = 0; chn < 16; chn++) {
1978 			SYNTH_CONTROLLER(m, chn, 123, 0);
1979 			SYNTH_CONTROLLER(m, chn, 121, 0);
1980 			SYNTH_BENDER(m, chn, 1 << 13);
1981 		}
1982 		mtx_lock(&scp->seq_lock);
1983 	}
1984 }
1985 
1986 /*
1987  * seq_sync
1988  * *really* flush the output queue
1989  * flush the event queue, then flush the synthsisers.
1990  * Callers are IOCTL and close
1991  */
1992 
1993 #define SEQ_SYNC_TIMEOUT 8
1994 static int
1995 seq_sync(struct seq_softc *scp)
1996 {
1997 	int i, rl, sync[16], done;
1998 
1999 	mtx_assert(&scp->seq_lock, MA_OWNED);
2000 
2001 	SEQ_DEBUG(4, printf("seq_sync: unit %d.\n", scp->unit));
2002 
2003 	/*
2004 	 * Wait until output queue is empty.  Check every so often to see if
2005 	 * the queue is moving along.  If it isn't just abort.
2006 	 */
2007 	while (!MIDIQ_EMPTY(scp->out_q)) {
2008 
2009 		if (!scp->playing) {
2010 			scp->playing = 1;
2011 			cv_broadcast(&scp->state_cv);
2012 			cv_broadcast(&scp->out_cv);
2013 		}
2014 		rl = MIDIQ_LEN(scp->out_q);
2015 
2016 		i = cv_timedwait_sig(&scp->out_cv,
2017 		    &scp->seq_lock, SEQ_SYNC_TIMEOUT * hz);
2018 
2019 		if (i == EINTR || i == ERESTART) {
2020 			if (i == EINTR) {
2021 				/*
2022 			         * XXX: I don't know why we stop playing
2023 			         */
2024 				scp->playing = 0;
2025 				cv_broadcast(&scp->out_cv);
2026 			}
2027 			return i;
2028 		}
2029 		if (i == EWOULDBLOCK && rl == MIDIQ_LEN(scp->out_q) &&
2030 		    scp->waiting == 0) {
2031 			/*
2032 			 * A queue seems to be stuck up. Give up and clear
2033 			 * queues.
2034 			 */
2035 			MIDIQ_CLEAR(scp->out_q);
2036 			scp->playing = 0;
2037 			cv_broadcast(&scp->state_cv);
2038 			cv_broadcast(&scp->out_cv);
2039 			cv_broadcast(&scp->reset_cv);
2040 
2041 			/*
2042 			 * TODO: Consider if the raw devices need to be flushed
2043 			 */
2044 
2045 			SEQ_DEBUG(1, printf("seq_sync queue stuck, aborting\n"));
2046 
2047 			return i;
2048 		}
2049 	}
2050 
2051 	scp->playing = 0;
2052 	/*
2053 	 * Since syncing a midi device might block, unlock scp->seq_lock.
2054 	 */
2055 
2056 	mtx_unlock(&scp->seq_lock);
2057 	for (i = 0; i < scp->midi_number; i++)
2058 		sync[i] = 1;
2059 
2060 	do {
2061 		done = 1;
2062 		for (i = 0; i < scp->midi_number; i++)
2063 			if (sync[i]) {
2064 				if (SYNTH_INSYNC(scp->midis[i]) == 0)
2065 					sync[i] = 0;
2066 				else
2067 					done = 0;
2068 			}
2069 		if (!done)
2070 			DELAY(5000);
2071 
2072 	} while (!done);
2073 
2074 	mtx_lock(&scp->seq_lock);
2075 	return 0;
2076 }
2077 
2078 char   *
2079 midi_cmdname(int cmd, midi_cmdtab *tab)
2080 {
2081 	while (tab->name != NULL) {
2082 		if (cmd == tab->cmd)
2083 			return (tab->name);
2084 		tab++;
2085 	}
2086 
2087 	return ("unknown");
2088 }
2089