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