xref: /freebsd/sys/dev/sound/midi/sequencer.c (revision 2357939bc239bd5334a169b62313806178dd8f30)
1 /*
2  * The sequencer personality manager.
3  *
4  * Copyright by Hannu Savolainen 1993
5  *
6  * Redistribution and use in source and binary forms, with or without
7  * modification, are permitted provided that the following conditions are
8  * met: 1. Redistributions of source code must retain the above copyright
9  * notice, this list of conditions and the following disclaimer. 2.
10  * Redistributions in binary form must reproduce the above copyright notice,
11  * this list of conditions and the following disclaimer in the documentation
12  * and/or other materials provided with the distribution.
13  *
14  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND ANY
15  * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
16  * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
17  * DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR
18  * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
19  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
20  * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
21  * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
22  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
23  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
24  * SUCH DAMAGE.
25  *
26  * $FreeBSD$
27  *
28  */
29 
30 /*
31  * This is the newmidi sequencer driver. This driver handles io against
32  * /dev/sequencer, midi input and output event queues and event transmittion
33  * to and from a midi device or synthesizer.
34  */
35 
36 #include <dev/sound/midi/midi.h>
37 #include <dev/sound/midi/sequencer.h>
38 
39 #define SND_DEV_SEQ	1	/* Sequencer output /dev/sequencer (FM
40 				   synthesizer and MIDI output) */
41 #define SND_DEV_MIDIN	2	/* Raw midi access */
42 #define SND_DEV_MUSIC	8	/* /dev/music, level 2 interface */
43 
44 #define MIDIDEV_MODE 0x2000
45 
46 /* Length of a sequencer event. */
47 #define EV_SZ 8
48 #define IEV_SZ 8
49 
50 /* Lookup modes */
51 #define LOOKUP_EXIST	(0)
52 #define LOOKUP_OPEN	(1)
53 #define LOOKUP_CLOSE	(2)
54 
55 /*
56  * These functions goes into seq_op_desc to get called
57  * from sound.c.
58  */
59 
60 static midi_intr_t seq_intr;
61 static midi_callback_t seq_callback;
62 
63 /* These are the entries to the sequencer driver. */
64 static d_open_t seq_open;
65 static d_close_t seq_close;
66 static d_ioctl_t seq_ioctl;
67 static d_read_t seq_read;
68 static d_write_t seq_write;
69 static d_poll_t seq_poll;
70 
71 /*
72  * This is the device descriptor for the midi sequencer.
73  */
74 seqdev_info seq_op_desc = {
75 	"midi sequencer",
76 
77 	0,
78 
79 	seq_open,
80 	seq_close,
81 	seq_read,
82 	seq_write,
83 	seq_ioctl,
84 	seq_poll,
85 
86 	seq_callback,
87 
88 	SEQ_BUFFSIZE, /* Queue Length */
89 
90 	0, /* XXX This is not an *audio* device! */
91 };
92 
93 
94 /* Here is the parameter structure per a device. */
95 struct seq_softc {
96 	seqdev_info	*devinfo;		/* sequencer device information */
97 
98 	/* Flags (protected by flag_mtx of mididev_info) */
99 	int		fflags;			/* Access mode */
100 	int		queueout_pending;	/* Pending for the output queue */
101 	int		seq_mode;		/* Sequencer mode */
102 
103 	/* Timer counters */
104 	u_long		seq_time;		/* The beggining time of this sequence */
105 	u_long		prev_event_time;	/* The time of the previous event output */
106 	u_long		prev_input_time;	/* The time of the previous event input */
107 	u_long		prev_wakeup_time;	/* The time of the previous wakeup */
108 	struct callout	timeout_ch;		/* Timer callout handler */
109 	long		timer_current;		/* Current timer value */
110 	int		timer_running;		/* State of timer */
111 	int		pending_timer;		/* Timer change operation */
112 	int		pre_event_timeout;	/* Time to wait event input */
113 
114 	/* Devices */
115 	TAILQ_HEAD(,_mididev_info)	midi_open;	/* Midi devices opened by this sequencer. */
116 	timerdev_info	*timer;			/* A timer device for /dev/music */
117 
118 	/*
119 	 * XXX not sure to which category these belong.
120 	 * (and some might be no-op)
121 	 */
122 	int		output_threshould;	/* Sequence output threshould */
123 	snd_sync_parm	sync_parm;		/* AIOSYNC parameter set */
124 	struct thread	*sync_thread;		/* AIOSYNCing thread */
125 };
126 
127 typedef struct seq_softc *sc_p;
128 
129 static d_open_t seqopen;
130 static d_close_t seqclose;
131 static d_ioctl_t seqioctl;
132 static d_read_t seqread;
133 static d_write_t seqwrite;
134 static d_poll_t seqpoll;
135 
136 #define CDEV_MAJOR SEQ_CDEV_MAJOR
137 static struct cdevsw seq_cdevsw = {
138 	.d_version =	D_VERSION,
139 	.d_flags =	D_NEEDGIANT,
140 	.d_open =	seqopen,
141 	.d_close =	seqclose,
142 	.d_read =	seqread,
143 	.d_write =	seqwrite,
144 	.d_ioctl =	seqioctl,
145 	.d_poll =	seqpoll,
146 	.d_name =	"midi", /* XXX */
147 	.d_maj =	CDEV_MAJOR,
148 };
149 
150 
151 static TAILQ_HEAD(,_seqdev_info)	seq_info;
152 /* Mutex to protect seq_info and nseq. */
153 static struct mtx			seqinfo_mtx;
154 /* total number of sequencers */
155 static u_long				nseq;
156 static dev_t				seq_alias = NODEV;
157 static dev_t				music_alias = NODEV;
158 
159 SYSCTL_NODE(_hw_midi, OID_AUTO, seq, CTLFLAG_RD, 0, "Midi sequencer");
160 
161 int					seq_debug;
162 SYSCTL_INT(_hw_midi_seq, OID_AUTO, debug, CTLFLAG_RW, &seq_debug, 0, "");
163 
164 static 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_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 static 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 static 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 
262 /* The followings are the local function. */
263 static int seq_init(void);
264 static int seq_initunit(int unit);
265 static int seq_queue(sc_p scp, u_char *note);
266 static void seq_startplay(sc_p scp);
267 static int seq_playevent(sc_p scp, u_char *event);
268 static u_long seq_gettime(void);
269 static int seq_requesttimer(sc_p scp, int delay);
270 static void seq_stoptimer(sc_p scp);
271 static void seq_midiinput(sc_p scp, mididev_info *md);
272 static int seq_extended(sc_p scp, u_char *event);
273 static int seq_chnvoice(sc_p scp, u_char *event);
274 static int seq_findvoice(mididev_info *md, int chn, int note) __unused;
275 static int seq_allocvoice(sc_p scp, mididev_info *md, int chn, int note) __unused;
276 static int seq_chncommon(sc_p scp, u_char *event);
277 static int seq_timing(sc_p scp, u_char *event);
278 static int seq_local(sc_p scp, u_char *event);
279 static int seq_sysex(sc_p scp, u_char *event);
280 static int seq_reset(sc_p scp);
281 static int seq_openmidi(sc_p scp, mididev_info *md, int flags, int mode, struct thread *p);
282 static int seq_closemidi(sc_p scp, mididev_info *md, int flags, int mode, struct thread *p);
283 static void seq_panic(sc_p scp);
284 static int seq_sync(sc_p scp);
285 
286 static seqdev_info *get_seqdev_info(dev_t i_dev, int *unit);
287 static seqdev_info *get_seqdev_info_unit(int unit);
288 static seqdev_info *create_seqdev_info_unit(int unit, seqdev_info *seq);
289 static int lookup_mididev(sc_p scp, int unit, int mode, mididev_info **mdp);
290 static int lookup_mididev_midi(sc_p scp, int unit, int mode, mididev_info **mdp);
291 static void seq_clone(void *arg, char *name, int namelen, dev_t *dev);
292 
293 /*
294  * Here are the main functions to interact to the user process.
295  * These are called from snd* functions in sys/i386/isa/snd/sound.c.
296  */
297 
298 static int
299 seq_init(void)
300 {
301 	SEQ_DEBUG(printf("seq: initing.\n"));
302 
303 	mtx_init(&seqinfo_mtx, "seqinf", NULL, MTX_DEF);
304 	TAILQ_INIT(&seq_info);
305 
306 	seq_initunit(0);
307 	EVENTHANDLER_REGISTER(dev_clone, seq_clone, 0, 1000);
308 
309 	SEQ_DEBUG(printf("seq: inited.\n"));
310 
311 	return (0);
312 }
313 
314 static int
315 seq_initunit(int unit)
316 {
317 	sc_p scp;
318 	seqdev_info *devinfo;
319 	dev_t seqdev, musicdev;
320 
321 	/* Allocate the softc. */
322 	scp = malloc(sizeof(*scp), M_DEVBUF, M_WAITOK | M_ZERO);
323 	if (scp == (sc_p)NULL) {
324 		printf("seq_initunit: unit %d, softc allocation failed.\n", unit);
325 		return (1);
326 	}
327 
328 	/* Fill the softc and the seq_info for this unit. */
329 	scp->seq_time = seq_gettime();
330 	scp->prev_event_time = 0;
331 	scp->prev_input_time = 0;
332 	scp->prev_wakeup_time = scp->seq_time;
333 #if defined(MIDI_OUTOFGIANT)
334 	callout_init(&scp->timeout_ch, 1);
335 #else
336 	callout_init(&scp->timeout_ch, 0);
337 #endif /* MIDI_OUTOFGIANT */
338 	scp->timer_current = 0;
339 	scp->timer_running = 0;
340 	scp->queueout_pending = 0;
341 	TAILQ_INIT(&scp->midi_open);
342 	scp->pending_timer = -1;
343 
344 	scp->devinfo = devinfo = create_seqdev_info_unit(unit, &seq_op_desc);
345 	devinfo->midi_dbuf_in.unit_size = devinfo->midi_dbuf_out.unit_size = EV_SZ;
346 	devinfo->softc = scp;
347 	devinfo->flags = 0;
348 	mtx_unlock(&devinfo->flagqueue_mtx);
349 
350 	seqdev = make_dev(&seq_cdevsw, MIDIMKMINOR(unit, SND_DEV_SEQ),
351 			  UID_ROOT, GID_WHEEL, 0666, "sequencer%d", unit);
352 	musicdev = make_dev(&seq_cdevsw, MIDIMKMINOR(unit, SND_DEV_MUSIC),
353 			    UID_ROOT, GID_WHEEL, 0666, "music%d", unit);
354 
355 	mtx_lock(&seqinfo_mtx);
356 	if (seq_alias != NODEV) {
357 		destroy_dev(seq_alias);
358 		seq_alias = NODEV;
359 	}
360 	seq_alias = make_dev_alias(seqdev, "sequencer");
361 	if (music_alias != NODEV) {
362 		destroy_dev(music_alias);
363 		music_alias = NODEV;
364 	}
365 	music_alias = make_dev_alias(musicdev, "music");
366 	mtx_unlock(&seqinfo_mtx);
367 
368 	if (timerdev_install() != 0)
369 		printf("seq_initunit: timerdev_install failed.\n");
370 
371 	return (0);
372 }
373 
374 int
375 seq_open(dev_t i_dev, int flags, int mode, struct thread *td)
376 {
377 	int unit;
378 	sc_p scp;
379 	seqdev_info *sd;
380 
381 	unit = MIDIUNIT(i_dev);
382 
383 	SEQ_DEBUG(printf("seq_open: unit %d, flags 0x%x.\n", unit, flags));
384 
385 	if (unit >= NSEQ_MAX) {
386 		SEQ_DEBUG(printf("seq_open: unit %d does not exist.\n", unit));
387 		return (ENXIO);
388 	}
389 
390 	sd = get_seqdev_info(i_dev, &unit);
391 	if (sd == NULL) {
392 		SEQ_DEBUG(printf("seq_open: unit %d is not configured.\n", unit));
393 		return (ENXIO);
394 	}
395 	scp = sd->softc;
396 
397 	/* Mark this device busy. */
398 	mtx_lock(&sd->flagqueue_mtx);
399 	if ((sd->flags & SEQ_F_BUSY) != 0) {
400 		mtx_unlock(&sd->flagqueue_mtx);
401 		SEQ_DEBUG(printf("seq_open: unit %d is busy.\n", unit));
402 		return (EBUSY);
403 	}
404 	scp->fflags = flags;
405 	sd->flags |= SEQ_F_BUSY;
406 	sd->flags &= ~(SEQ_F_READING | SEQ_F_WRITING);
407 	if ((scp->fflags & O_NONBLOCK) != 0)
408 		sd->flags |= SEQ_F_NBIO;
409 	scp->seq_mode = MIDIDEV(i_dev);
410 
411 	/* Init the queue. */
412 	midibuf_clear(&sd->midi_dbuf_in);
413 	midibuf_clear(&sd->midi_dbuf_out);
414 
415 	/* Init timestamp. */
416 	scp->seq_time = seq_gettime();
417 	scp->prev_event_time = 0;
418 	scp->prev_input_time = 0;
419 	scp->prev_wakeup_time = scp->seq_time;
420 
421 	if (scp->pending_timer != -1) {
422 		scp->timer = get_timerdev_info_unit(scp->pending_timer);
423 		scp->pending_timer = -1;
424 	}
425 	if (scp->timer == NULL)
426 		scp->timer = get_timerdev_info();
427 	if (scp->timer != NULL) {
428 		scp->timer->seq = scp;
429 		mtx_unlock(&scp->timer->mtx);
430 	} else if (scp->seq_mode == SND_DEV_MUSIC) {
431 		mtx_unlock(&sd->flagqueue_mtx);
432 		printf("seq_open: no timer available.\n");
433 		sd->flags &= ~SEQ_F_BUSY;
434 		return (ENXIO);
435 	}
436 
437 	if (scp->seq_mode == SND_DEV_MUSIC)
438 		scp->timer->open(scp->timer, flags, mode, td);
439 
440 	/* Begin recording if nonblocking. */
441 	if ((sd->flags & (SEQ_F_READING | SEQ_F_NBIO)) == SEQ_F_NBIO && (scp->fflags & FREAD) != 0)
442 		sd->callback(sd, SEQ_CB_START | SEQ_CB_RD);
443 
444 	mtx_unlock(&sd->flagqueue_mtx);
445 
446 	SEQ_DEBUG(printf("seq_open: opened, mode %d.\n", scp->seq_mode == SND_DEV_MUSIC ? 2 : 1));
447 
448 	return (0);
449 }
450 
451 int
452 seq_close(dev_t i_dev, int flags, int mode, struct thread *td)
453 {
454 	int unit;
455 	sc_p scp;
456 	seqdev_info *sd;
457 	mididev_info *md;
458 	timerdev_info *tmd;
459 
460 	unit = MIDIUNIT(i_dev);
461 
462 	SEQ_DEBUG(printf("seq_close: unit %d.\n", unit));
463 
464 	if (unit >= NSEQ_MAX) {
465 		SEQ_DEBUG(printf("seq_close: unit %d does not exist.\n", unit));
466 		return (ENXIO);
467 	}
468 
469 	sd = get_seqdev_info(i_dev, &unit);
470 	if (sd == NULL) {
471 		SEQ_DEBUG(printf("seq_close: unit %d is not configured.\n", unit));
472 		return (ENXIO);
473 	}
474 	scp = sd->softc;
475 
476 	mtx_lock(&sd->flagqueue_mtx);
477 
478 	if (!(sd->flags & MIDI_F_NBIO))
479 		seq_sync(scp);
480 
481 	/* Stop the timer. */
482 	seq_stoptimer(scp);
483 
484 	/* Reset the sequencer. */
485 	seq_reset(scp);
486 	seq_sync(scp);
487 
488 	/* Clean up the midi device. */
489 	TAILQ_FOREACH(md, &scp->midi_open, md_linkseq)
490 		lookup_mididev(scp, md->unit, LOOKUP_CLOSE, NULL);
491 
492 	/* Stop playing and unmark this device busy. */
493 	sd->flags &= ~(SEQ_F_BUSY | SEQ_F_READING | SEQ_F_WRITING | SEQ_F_INSYNC);
494 
495 	if (scp->seq_mode == SND_DEV_MUSIC)
496 		scp->timer->close(scp->timer, flags, mode, td);
497 
498 	if (scp->timer != NULL) {
499 		tmd = scp->timer;
500 		mtx_lock(&tmd->mtx);
501 		scp->timer = NULL;
502 		tmd->seq = NULL;
503 		mtx_unlock(&tmd->mtx);
504 	}
505 
506 	mtx_unlock(&sd->flagqueue_mtx);
507 
508 	SEQ_DEBUG(printf("seq_close: closed.\n"));
509 
510 	return (0);
511 }
512 
513 int
514 seq_read(dev_t i_dev, struct uio *buf, int flag)
515 {
516 	int unit, ret, len, lenr;
517 	sc_p scp;
518 	seqdev_info *sd;
519 	u_char *uiobuf;
520 
521 	unit = MIDIUNIT(i_dev);
522 
523 	SEQ_DEBUG(printf("seq_read: unit %d, resid %d.\n", unit, buf->uio_resid));
524 
525 	if (unit >= NSEQ_MAX) {
526 		SEQ_DEBUG(printf("seq_read: unit %d does not exist.\n", unit));
527 		return (ENXIO);
528 	}
529 
530 	sd = get_seqdev_info(i_dev, &unit);
531 	if (sd == NULL) {
532 		SEQ_DEBUG(printf("seq_read: unit %d is not configured.\n", unit));
533 		return (ENXIO);
534 	}
535 	scp = sd->softc;
536 	if ((scp->fflags & FREAD) == 0) {
537 		SEQ_DEBUG(printf("seq_read: unit %d is not for reading.\n", unit));
538 		return (EIO);
539 	}
540 
541 	len = buf->uio_resid;
542 	lenr = 0;
543 
544 	uiobuf = (u_char *)malloc(len, M_DEVBUF, M_WAITOK | M_ZERO);
545 	if (uiobuf == NULL)
546 		return (ENOMEM);
547 
548 	mtx_lock(&sd->flagqueue_mtx);
549 
550 	/* Begin recording. */
551 	if ((sd->flags & SEQ_F_READING) == 0)
552 		sd->callback(sd, SEQ_CB_START | SEQ_CB_RD);
553 
554 	/* Have we got the data to read? */
555 	if ((sd->flags & SEQ_F_NBIO) != 0 && sd->midi_dbuf_in.rl == 0)
556 		ret = EAGAIN;
557 	else {
558 		if ((sd->flags & SEQ_F_NBIO) != 0 && len > sd->midi_dbuf_in.rl)
559 			len = sd->midi_dbuf_in.rl;
560 		ret = midibuf_seqread(&sd->midi_dbuf_in, uiobuf, len, &lenr,
561 				      sd->callback, sd, SEQ_CB_START | SEQ_CB_RD,
562 				      &sd->flagqueue_mtx);
563 	}
564 
565 	mtx_unlock(&sd->flagqueue_mtx);
566 
567 	if (ret == 0 && lenr > 0)
568 		ret = uiomove(uiobuf, lenr, buf);
569 
570 	free(uiobuf, M_DEVBUF);
571 
572 	SEQ_DEBUG(printf("seq_read: ret %d, resid %d.\n", ret, buf->uio_resid));
573 
574 	return (ret);
575 }
576 
577 int
578 seq_write(dev_t i_dev, struct uio *buf, int flag)
579 {
580 	u_char event[EV_SZ], ev_code;
581 	int unit, count, countorg, midiunit, ev_size, p, ret;
582 	sc_p scp;
583 	seqdev_info *sd;
584 	mididev_info *md;
585 
586 	unit = MIDIUNIT(i_dev);
587 
588 	SEQ_DEBUG(printf("seq_write: unit %d, resid %d.\n", unit, buf->uio_resid));
589 
590 	if (unit >= NSEQ_MAX) {
591 		SEQ_DEBUG(printf("seq_write: unit %d does not exist.\n", unit));
592 		return (ENXIO);
593 	}
594 
595 	sd = get_seqdev_info(i_dev, &unit);
596 	if (sd == NULL) {
597 		SEQ_DEBUG(printf("seq_write: unit %d is not configured.\n", unit));
598 		return (ENXIO);
599 	}
600 	scp = sd->softc;
601 	if ((scp->fflags & FWRITE) == 0) {
602 		SEQ_DEBUG(printf("seq_write: unit %d is not for writing.\n", unit));
603 		return (EIO);
604 	}
605 
606 	p = 0;
607 	countorg = buf->uio_resid;
608 	count = countorg;
609 
610 	/* Pick up an event. */
611 	while (count >= 4) {
612 		if (uiomove((caddr_t)event, 4, buf))
613 			printf("seq_write: user memory mangled?\n");
614 		ev_code = event[0];
615 		SEQ_DEBUG(printf("seq_write: unit %d, event %s.\n", unit, midi_cmdname(ev_code, cmdtab_seqevent)));
616 
617 		/* Have a look at the event code. */
618 		if (ev_code == SEQ_FULLSIZE) {
619 
620 			/* A long event, these are the patches/samples for a synthesizer. */
621 			midiunit = *(u_short *)&event[2];
622 			mtx_lock(&sd->flagqueue_mtx);
623 			ret = lookup_mididev(scp, midiunit, LOOKUP_OPEN, &md);
624 			mtx_unlock(&sd->flagqueue_mtx);
625 			if (ret != 0)
626 				return (ret);
627 
628 			SEQ_DEBUG(printf("seq_write: loading a patch to the unit %d.\n", midiunit));
629 
630 			ret = md->synth.loadpatch(md, *(short *)&event[0], buf, p + 4, count, 0);
631 			return (ret);
632 		}
633 
634 		if (ev_code >= 128) {
635 
636 			/* Some sort of an extended event. The size is eight bytes. */
637 			if (scp->seq_mode == SND_DEV_MUSIC && ev_code == SEQ_EXTENDED) {
638 				printf("seq_write: invalid level two event %x.\n", ev_code);
639 				return (EINVAL);
640 			}
641 			ev_size = 8;
642 
643 			if (count < ev_size) {
644 				/* No more data. Start playing now. */
645 				mtx_lock(&sd->flagqueue_mtx);
646 				if ((sd->flags & SEQ_F_WRITING) == 0)
647 					sd->callback(sd, SEQ_CB_START | SEQ_CB_WR);
648 				mtx_unlock(&sd->flagqueue_mtx);
649 				buf->uio_resid += 4;
650 
651 				return (0);
652 			}
653 			if (uiomove((caddr_t)&event[4], 4, buf))
654 				printf("seq_write: user memory mangled?\n");
655 		} else {
656 
657 			/* Not an extended event. The size is four bytes. */
658 			if (scp->seq_mode == SND_DEV_MUSIC) {
659 				printf("seq_write: four byte event in level two mode.\n");
660 				return (EINVAL);
661 			}
662 			ev_size = 4;
663 		}
664 		if (ev_code == SEQ_MIDIPUTC) {
665 			/* An event passed to the midi device itself. */
666 			midiunit = event[2];
667 			mtx_lock(&sd->flagqueue_mtx);
668 			ret = lookup_mididev_midi(scp, midiunit, LOOKUP_OPEN, &md);
669 			mtx_unlock(&sd->flagqueue_mtx);
670 			if (ret != 0)
671 				return (ret);
672 		}
673 
674 		SEQ_DEBUG(printf("seq_write: queueing event %s.\n", midi_cmdname(event[0], cmdtab_seqevent)));
675 		/* Now we queue the event. */
676 		mtx_lock(&sd->flagqueue_mtx);
677 		switch (seq_queue(scp, event)) {
678 		case EAGAIN:
679 			/* The queue is full. Start playing now. */
680 			if ((sd->flags & SEQ_F_WRITING) == 0)
681 				sd->callback(sd, SEQ_CB_START | SEQ_CB_WR);
682 			mtx_unlock(&sd->flagqueue_mtx);
683 			buf->uio_resid = count;
684 			SEQ_DEBUG(printf("seq_write: resid %d.\n", buf->uio_resid));
685 			if (count < countorg)
686 				return (0);
687 			return (EAGAIN);
688 		case EINTR:
689 			mtx_unlock(&sd->flagqueue_mtx);
690 			SEQ_DEBUG(printf("seq_write: resid %d.\n", buf->uio_resid));
691 			return (EINTR);
692 		case ERESTART:
693 			mtx_unlock(&sd->flagqueue_mtx);
694 			SEQ_DEBUG(printf("seq_write: resid %d.\n", buf->uio_resid));
695 			return (ERESTART);
696 		}
697 		mtx_unlock(&sd->flagqueue_mtx);
698 		p += ev_size;
699 		count -= ev_size;
700 	}
701 
702 	/* We have written every single data. Start playing now. */
703 	mtx_lock(&sd->flagqueue_mtx);
704 	if ((sd->flags & SEQ_F_WRITING) == 0)
705 		sd->callback(sd, SEQ_CB_START | SEQ_CB_WR);
706 	mtx_unlock(&sd->flagqueue_mtx);
707 
708 	SEQ_DEBUG(printf("seq_write: resid %d.\n", buf->uio_resid));
709 
710 	return (0);
711 }
712 
713 int
714 seq_ioctl(dev_t i_dev, u_long cmd, caddr_t arg, int mode, struct thread *td)
715 {
716 	int unit, midiunit, ret, tmp;
717 	sc_p scp;
718 	seqdev_info *sd;
719 	mididev_info *md;
720 	struct synth_info *synthinfo;
721 	struct midi_info *midiinfo;
722 	struct patmgr_info *patinfo;
723 	struct seq_event_rec *event;
724 	struct snd_size *sndsize;
725 
726 	unit = MIDIUNIT(i_dev);
727 
728 	SEQ_DEBUG(printf("seq_ioctl: unit %d, cmd %s.\n", unit, midi_cmdname(cmd, cmdtab_seqioctl)));
729 
730 	if (unit >= NSEQ_MAX) {
731 		SEQ_DEBUG(printf("seq_ioctl: unit %d does not exist.\n", unit));
732 		return (ENXIO);
733 	}
734 	sd = get_seqdev_info(i_dev, &unit);
735 	if (sd == NULL) {
736 		SEQ_DEBUG(printf("seq_ioctl: unit %d is not configured.\n", unit));
737 		return (ENXIO);
738 	}
739 	scp = sd->softc;
740 
741 	ret = 0;
742 
743 	switch (cmd) {
744 
745 		/*
746 		 * we start with the new ioctl interface.
747 		 */
748 	case AIONWRITE:	/* how many bytes can be written ? */
749 		mtx_lock(&sd->flagqueue_mtx);
750 		*(int *)arg = sd->midi_dbuf_out.fl;
751 		mtx_unlock(&sd->flagqueue_mtx);
752 		SEQ_DEBUG(printf("seq_ioctl: fl %d.\n", *(int *)arg));
753 		break;
754 
755 	case AIOSSIZE:     /* set the current blocksize */
756 		sndsize = (struct snd_size *)arg;
757 		SEQ_DEBUG(printf("seq_ioctl: play %d, rec %d.\n", sndsize->play_size, sndsize->rec_size));
758 		mtx_lock(&sd->flagqueue_mtx);
759 		if (sndsize->play_size <= sd->midi_dbuf_out.unit_size && sndsize->rec_size <= sd->midi_dbuf_in.unit_size) {
760 			sd->midi_dbuf_out.blocksize = sd->midi_dbuf_out.unit_size;
761 			sd->midi_dbuf_in.blocksize = sd->midi_dbuf_in.unit_size;
762 			sndsize->play_size = sd->midi_dbuf_out.blocksize;
763 			sndsize->rec_size = sd->midi_dbuf_in.blocksize;
764 			sd->flags &= ~MIDI_F_HAS_SIZE;
765 			mtx_unlock(&sd->flagqueue_mtx);
766 		}
767 		else {
768 			if (sndsize->play_size > sd->midi_dbuf_out.bufsize / 4)
769 				sndsize->play_size = sd->midi_dbuf_out.bufsize / 4;
770 			if (sndsize->rec_size > sd->midi_dbuf_in.bufsize / 4)
771 				sndsize->rec_size = sd->midi_dbuf_in.bufsize / 4;
772 			/* Round up the size to the multiple of EV_SZ. */
773 			sd->midi_dbuf_out.blocksize =
774 			    ((sndsize->play_size + sd->midi_dbuf_out.unit_size - 1)
775 			     / sd->midi_dbuf_out.unit_size) * sd->midi_dbuf_out.unit_size;
776 			sd->midi_dbuf_in.blocksize =
777 			    ((sndsize->rec_size + sd->midi_dbuf_in.unit_size - 1)
778 			     / sd->midi_dbuf_in.unit_size) * sd->midi_dbuf_in.unit_size;
779 			sndsize->play_size = sd->midi_dbuf_out.blocksize;
780 			sndsize->rec_size = sd->midi_dbuf_in.blocksize;
781 			sd->flags |= MIDI_F_HAS_SIZE;
782 			mtx_unlock(&sd->flagqueue_mtx);
783 		}
784 
785 		ret = 0;
786 		break;
787 
788 	case AIOGSIZE:	/* get the current blocksize */
789 		sndsize = (struct snd_size *)arg;
790 		mtx_lock(&sd->flagqueue_mtx);
791 		sndsize->play_size = sd->midi_dbuf_out.blocksize;
792 		sndsize->rec_size = sd->midi_dbuf_in.blocksize;
793 		mtx_unlock(&sd->flagqueue_mtx);
794 		SEQ_DEBUG(printf("seq_ioctl: play %d, rec %d.\n", sndsize->play_size, sndsize->rec_size));
795 
796 		ret = 0;
797 		break;
798 
799 	case AIOSTOP:
800 		if (*(int *)arg == AIOSYNC_PLAY) {
801 
802 			/* Stop writing. */
803 			mtx_lock(&sd->flagqueue_mtx);
804 			sd->callback(sd, SEQ_CB_ABORT | SEQ_CB_WR);
805 			mtx_unlock(&sd->flagqueue_mtx);
806 
807 			/* Pass the ioctl to the midi devices. */
808 			TAILQ_FOREACH(md, &scp->midi_open, md_linkseq) {
809 				if ((md->flags & MIDI_F_WRITING) != 0)
810 					midi_ioctl(MIDIMKDEV(major(i_dev), md->unit, SND_DEV_MIDIN), cmd, (caddr_t)arg, mode, td);
811 			}
812 
813 			mtx_lock(&sd->flagqueue_mtx);
814 			*(int *)arg = sd->midi_dbuf_out.rl;
815 			mtx_unlock(&sd->flagqueue_mtx);
816 		}
817 		else if (*(int *)arg == AIOSYNC_CAPTURE) {
818 
819 			/* Stop reading. */
820 			mtx_lock(&sd->flagqueue_mtx);
821 			sd->callback(sd, SEQ_CB_ABORT | SEQ_CB_RD);
822 			mtx_unlock(&sd->flagqueue_mtx);
823 
824 			/* Pass the ioctl to the midi devices. */
825 			TAILQ_FOREACH(md, &scp->midi_open, md_linkseq) {
826 				if ((md->flags & MIDI_F_WRITING) != 0)
827 					midi_ioctl(MIDIMKDEV(major(i_dev), md->unit, SND_DEV_MIDIN), cmd, (caddr_t)arg, mode, td);
828 			}
829 
830 			mtx_lock(&sd->flagqueue_mtx);
831 			*(int *)arg = sd->midi_dbuf_in.rl;
832 			mtx_unlock(&sd->flagqueue_mtx);
833 		}
834 
835 		ret = 0;
836 		break;
837 
838 	case AIOSYNC:
839 		mtx_lock(&sd->flagqueue_mtx);
840 		scp->sync_parm = *(snd_sync_parm *)arg;
841 		mtx_unlock(&sd->flagqueue_mtx);
842 
843 		/* XXX Should select(2) against us watch the blocksize, or sync_parm? */
844 
845 		ret = 0;
846 		break;
847 
848 	case FIONBIO: /* set/clear non-blocking i/o */
849 		mtx_lock(&sd->flagqueue_mtx);
850 		if (*(int *)arg == 0)
851 			sd->flags &= ~SEQ_F_NBIO ;
852 		else
853 			sd->flags |= SEQ_F_NBIO ;
854 		mtx_unlock(&sd->flagqueue_mtx);
855 		MIDI_DEBUG(printf("seq_ioctl: arg %d.\n", *(int *)arg));
856 		break ;
857 
858 	case SNDCTL_TMR_TIMEBASE:
859 	case SNDCTL_TMR_TEMPO:
860 	case SNDCTL_TMR_START:
861 	case SNDCTL_TMR_STOP:
862 	case SNDCTL_TMR_CONTINUE:
863 	case SNDCTL_TMR_METRONOME:
864 	case SNDCTL_TMR_SOURCE:
865 		mtx_lock(&sd->flagqueue_mtx);
866 		if (scp->seq_mode != SND_DEV_MUSIC) {
867 			ret = EINVAL;
868 			mtx_unlock(&sd->flagqueue_mtx);
869 			break;
870 		}
871 		mtx_unlock(&sd->flagqueue_mtx);
872 		/* XXX We should adopt am sx to protect scp->timer */
873 		ret = scp->timer->ioctl(scp->timer, cmd, arg, mode, td);
874 		break;
875 	case SNDCTL_TMR_SELECT:
876 		mtx_lock(&sd->flagqueue_mtx);
877 		if (scp->seq_mode != SND_DEV_MUSIC) {
878 			ret = EINVAL;
879 			mtx_unlock(&sd->flagqueue_mtx);
880 			break;
881 		}
882 		mtx_unlock(&sd->flagqueue_mtx);
883 		scp->pending_timer = *(int *)arg;
884 		mtx_lock(&sd->flagqueue_mtx);
885 		if (scp->pending_timer < 0) {
886 			scp->pending_timer = -1;
887 			ret = EINVAL;
888 			mtx_unlock(&sd->flagqueue_mtx);
889 			break;
890 		}
891 		mtx_unlock(&sd->flagqueue_mtx);
892 		SEQ_DEBUG(printf("seq_ioctl: new timer %d.\n", *(int *)arg));
893 		ret = 0;
894 		break;
895 	case SNDCTL_SEQ_PANIC:
896 		mtx_lock(&sd->flagqueue_mtx);
897 		seq_panic(scp);
898 		mtx_unlock(&sd->flagqueue_mtx);
899 		ret = 0;
900 		break;
901 	case SNDCTL_SEQ_SYNC:
902 		if (mode == O_RDONLY) {
903 			ret = 0;
904 			break;
905 		}
906 		mtx_lock(&scp->devinfo->flagqueue_mtx);
907 		ret = seq_sync(scp);
908 		mtx_unlock(&scp->devinfo->flagqueue_mtx);
909 		break;
910 	case SNDCTL_SEQ_RESET:
911 		mtx_lock(&scp->devinfo->flagqueue_mtx);
912 		seq_reset(scp);
913 		mtx_unlock(&scp->devinfo->flagqueue_mtx);
914 		ret = 0;
915 		break;
916 	case SNDCTL_SEQ_TESTMIDI:
917 		mtx_lock(&sd->flagqueue_mtx);
918 		ret = lookup_mididev_midi(scp, *(int *)arg, LOOKUP_OPEN, &md);
919 		mtx_unlock(&sd->flagqueue_mtx);
920 		break;
921 	case SNDCTL_SEQ_GETINCOUNT:
922 		if (mode == O_WRONLY)
923 			*(int *)arg = 0;
924 		else {
925 			mtx_lock(&sd->flagqueue_mtx);
926 			*(int *)arg = sd->midi_dbuf_in.rl;
927 			mtx_unlock(&sd->flagqueue_mtx);
928 			SEQ_DEBUG(printf("seq_ioctl: incount %d.\n", *(int *)arg));
929 		}
930 		ret = 0;
931 		break;
932 	case SNDCTL_SEQ_GETOUTCOUNT:
933 		if (mode == O_RDONLY)
934 			*(int *)arg = 0;
935 		else {
936 			mtx_lock(&sd->flagqueue_mtx);
937 			*(int *)arg = sd->midi_dbuf_out.fl;
938 			mtx_unlock(&sd->flagqueue_mtx);
939 			SEQ_DEBUG(printf("seq_ioctl: outcount %d.\n", *(int *)arg));
940 		}
941 		ret = 0;
942 		break;
943 	case SNDCTL_SEQ_CTRLRATE:
944 		mtx_lock(&sd->flagqueue_mtx);
945 		if (scp->seq_mode == SND_DEV_MUSIC) {
946 			mtx_unlock(&sd->flagqueue_mtx);
947 			ret = scp->timer->ioctl(scp->timer, cmd, arg, mode, td);
948 			break;
949 		}
950 		mtx_unlock(&sd->flagqueue_mtx);
951 		if (*(int *)arg != 0) {
952 			ret = EINVAL;
953 			break;
954 		}
955 		*(int *)arg = hz;
956 		SEQ_DEBUG(printf("seq_ioctl: ctrlrate %d.\n", *(int *)arg));
957 		ret = 0;
958 		break;
959 	case SNDCTL_SEQ_RESETSAMPLES:
960 		mtx_lock(&sd->flagqueue_mtx);
961 		ret = lookup_mididev(scp, *(int *)arg, LOOKUP_OPEN, &md);
962 		mtx_unlock(&sd->flagqueue_mtx);
963 		if (ret != 0)
964 			break;
965 		ret = midi_ioctl(MIDIMKDEV(major(i_dev), *(int *)arg, SND_DEV_MIDIN), cmd, arg, mode, td);
966 		break;
967 	case SNDCTL_SEQ_NRSYNTHS:
968 		mtx_lock(&sd->flagqueue_mtx);
969 		if (scp->seq_mode == SND_DEV_MUSIC)
970 			*(int *)arg = mididev_synth_number() + mididev_midi_number();
971 		else
972 			*(int *)arg = mididev_synth_number();
973 		mtx_unlock(&sd->flagqueue_mtx);
974 		SEQ_DEBUG(printf("seq_ioctl: synths %d.\n", *(int *)arg));
975 		ret = 0;
976 		break;
977 	case SNDCTL_SEQ_NRMIDIS:
978 		mtx_lock(&sd->flagqueue_mtx);
979 		if (scp->seq_mode == SND_DEV_MUSIC)
980 			*(int *)arg = 0;
981 		else
982 			*(int *)arg = mididev_midi_number();
983 		mtx_unlock(&sd->flagqueue_mtx);
984 		SEQ_DEBUG(printf("seq_ioctl: midis %d.\n", *(int *)arg));
985 		ret = 0;
986 		break;
987 	case SNDCTL_SYNTH_MEMAVL:
988 		mtx_lock(&sd->flagqueue_mtx);
989 		ret = lookup_mididev(scp, *(int *)arg, LOOKUP_OPEN, &md);
990 		mtx_unlock(&sd->flagqueue_mtx);
991 		if (ret != 0)
992 			break;
993 		ret = midi_ioctl(MIDIMKDEV(major(i_dev), *(int *)arg, SND_DEV_MIDIN), cmd, arg, mode, td);
994 		break;
995 	case SNDCTL_FM_4OP_ENABLE:
996 		mtx_lock(&sd->flagqueue_mtx);
997 		ret = lookup_mididev(scp, *(int *)arg, LOOKUP_OPEN, &md);
998 		mtx_unlock(&sd->flagqueue_mtx);
999 		if (ret != 0)
1000 			break;
1001 		ret = midi_ioctl(MIDIMKDEV(major(i_dev), *(int *)arg, SND_DEV_MIDIN), cmd, arg, mode, td);
1002 		break;
1003 	case SNDCTL_SYNTH_INFO:
1004 		synthinfo = (struct synth_info *)arg;
1005 		midiunit = synthinfo->device;
1006 		mtx_lock(&sd->flagqueue_mtx);
1007 		ret = lookup_mididev(scp, midiunit, LOOKUP_OPEN, &md);
1008 		mtx_unlock(&sd->flagqueue_mtx);
1009 		if (ret != 0)
1010 			break;
1011 		ret = midi_ioctl(MIDIMKDEV(major(i_dev), midiunit, SND_DEV_MIDIN), cmd, arg, mode, td);
1012 		break;
1013 	case SNDCTL_SEQ_OUTOFBAND:
1014 		event = (struct seq_event_rec *)arg;
1015 		mtx_lock(&sd->flagqueue_mtx);
1016 		ret = seq_playevent(scp, event->arr);
1017 		mtx_unlock(&sd->flagqueue_mtx);
1018 		break;
1019 	case SNDCTL_MIDI_INFO:
1020 		midiinfo = (struct midi_info *)arg;
1021 		midiunit = midiinfo->device;
1022 		mtx_lock(&sd->flagqueue_mtx);
1023 		ret = lookup_mididev_midi(scp, midiunit, LOOKUP_OPEN, &md);
1024 		mtx_unlock(&sd->flagqueue_mtx);
1025 		if (ret != 0)
1026 			break;
1027 		ret = midi_ioctl(MIDIMKDEV(major(i_dev), midiunit, SND_DEV_MIDIN), cmd, arg, mode, td);
1028 		break;
1029 	case SNDCTL_PMGR_IFACE:
1030 		patinfo = (struct patmgr_info *)arg;
1031 		midiunit = patinfo->device;
1032 		mtx_lock(&sd->flagqueue_mtx);
1033 		ret = lookup_mididev(scp, midiunit, LOOKUP_OPEN, &md);
1034 		mtx_unlock(&sd->flagqueue_mtx);
1035 		if (ret != 0)
1036 			break;
1037 		ret = midi_ioctl(MIDIMKDEV(major(i_dev), midiunit, SND_DEV_MIDIN), cmd, arg, mode, td);
1038 		break;
1039 	case SNDCTL_PMGR_ACCESS:
1040 		patinfo = (struct patmgr_info *)arg;
1041 		midiunit = patinfo->device;
1042 		mtx_lock(&sd->flagqueue_mtx);
1043 		ret = lookup_mididev(scp, midiunit, LOOKUP_OPEN, &md);
1044 		mtx_unlock(&sd->flagqueue_mtx);
1045 		if (ret != 0)
1046 			break;
1047 		ret = midi_ioctl(MIDIMKDEV(major(i_dev), midiunit, SND_DEV_MIDIN), cmd, arg, mode, td);
1048 		break;
1049 	case SNDCTL_SEQ_THRESHOLD:
1050 		mtx_lock(&sd->flagqueue_mtx);
1051 		RANGE(*(int *)arg, 1, sd->midi_dbuf_out.bufsize - 1);
1052 		scp->output_threshould = *(int *)arg;
1053 		mtx_unlock(&sd->flagqueue_mtx);
1054 		SEQ_DEBUG(printf("seq_ioctl: threshold %d.\n", *(int *)arg));
1055 		ret = 0;
1056 		break;
1057 	case SNDCTL_MIDI_PRETIME:
1058 		tmp = *(int *)arg;
1059 		if (tmp < 0)
1060 			tmp = 0;
1061 		mtx_lock(&sd->flagqueue_mtx);
1062 		scp->pre_event_timeout = (hz * tmp) / 10;
1063 		*(int *)arg = scp->pre_event_timeout;
1064 		mtx_unlock(&sd->flagqueue_mtx);
1065 		SEQ_DEBUG(printf("seq_ioctl: pretime %d.\n", *(int *)arg));
1066 		ret = 0;
1067 		break;
1068 	default:
1069 		if ((scp->fflags & O_ACCMODE) == FREAD) {
1070 			ret = EIO;
1071 			break;
1072 		}
1073 		mtx_lock(&sd->flagqueue_mtx);
1074 		ret = lookup_mididev(scp, 0, LOOKUP_OPEN, &md);
1075 		mtx_unlock(&sd->flagqueue_mtx);
1076 		if (ret != 0)
1077 			break;
1078 		ret = midi_ioctl(MIDIMKDEV(major(i_dev), 0, SND_DEV_MIDIN), cmd, arg, mode, td);
1079 		break;
1080 	}
1081 
1082 	return (ret);
1083 }
1084 
1085 int
1086 seq_poll(dev_t i_dev, int events, struct thread *td)
1087 {
1088 	int unit, ret, lim;
1089 	sc_p scp;
1090 	seqdev_info *sd;
1091 
1092 	unit = MIDIUNIT(i_dev);
1093 
1094 	SEQ_DEBUG(printf("seq_poll: unit %d.\n", unit));
1095 
1096 	if (unit >= NSEQ_MAX) {
1097 		SEQ_DEBUG(printf("seq_poll: unit %d does not exist.\n", unit));
1098 		return (ENXIO);
1099 	}
1100 	sd = get_seqdev_info(i_dev, &unit);
1101 	if (sd == NULL) {
1102 		SEQ_DEBUG(printf("seq_poll: unit %d is not configured.\n", unit));
1103 		return (ENXIO);
1104 	}
1105 	scp = sd->softc;
1106 
1107 	mtx_lock(&sd->flagqueue_mtx);
1108 
1109 	ret = 0;
1110 
1111 	/* Look up the apropriate queue and select it. */
1112 	if ((events & (POLLOUT | POLLWRNORM)) != 0) {
1113 		/* Start playing. */
1114 		sd->callback(sd, SEQ_CB_START | SEQ_CB_WR);
1115 
1116 		/* Find out the boundary. */
1117 		if ((sd->flags & SEQ_F_HAS_SIZE) != 0)
1118 			lim = sd->midi_dbuf_out.blocksize;
1119 		else
1120 			lim = sd->midi_dbuf_out.unit_size;
1121 		if (sd->midi_dbuf_out.fl < lim)
1122 			/* No enough space, record select. */
1123 			selrecord(td, &sd->midi_dbuf_out.sel);
1124 		else
1125 			/* We can write now. */
1126 			ret |= events & (POLLOUT | POLLWRNORM);
1127 	}
1128 	if ((events & (POLLIN | POLLRDNORM)) != 0) {
1129 		/* Start recording. */
1130 		sd->callback(sd, SEQ_CB_START | SEQ_CB_RD);
1131 
1132 		/* Find out the boundary. */
1133 		if ((sd->flags & SEQ_F_HAS_SIZE) != 0)
1134 			lim = sd->midi_dbuf_in.blocksize;
1135 		else
1136 			lim = sd->midi_dbuf_in.unit_size;
1137 		if (sd->midi_dbuf_in.rl < lim)
1138 			/* No data ready, record select. */
1139 			selrecord(td, &sd->midi_dbuf_in.sel);
1140 		else
1141 			/* We can write now. */
1142 			ret |= events & (POLLIN | POLLRDNORM);
1143 	}
1144 
1145 	mtx_unlock(&sd->flagqueue_mtx);
1146 
1147 	return (ret);
1148 }
1149 
1150 static void
1151 seq_intr(void *p, mididev_info *md)
1152 {
1153 	sc_p scp;
1154 	seqdev_info *sd;
1155 
1156 	sd = (seqdev_info *)p;
1157 	scp = sd->softc;
1158 
1159 	mtx_lock(&sd->flagqueue_mtx);
1160 
1161 	/* Restart playing if we have the data to output. */
1162 	if (scp->queueout_pending)
1163 		sd->callback(sd, SEQ_CB_START | SEQ_CB_WR);
1164 	/* Check the midi device if we are reading. */
1165 	if ((sd->flags & SEQ_F_READING) != 0)
1166 		seq_midiinput(scp, md);
1167 
1168 	mtx_unlock(&sd->flagqueue_mtx);
1169 }
1170 
1171 static int
1172 seq_callback(void *d, int reason)
1173 {
1174 	int unit;
1175 	sc_p scp;
1176 	seqdev_info *sd;
1177 
1178 	sd = (seqdev_info *)d;
1179 
1180 	SEQ_DEBUG(printf("seq_callback: reason 0x%x.\n", reason));
1181 
1182 	if (sd == NULL) {
1183 		SEQ_DEBUG(printf("seq_callback: device not configured.\n"));
1184 		return (ENXIO);
1185 	}
1186 	scp = sd->softc;
1187 	unit = sd->unit;
1188 
1189 	mtx_assert(&sd->flagqueue_mtx, MA_OWNED);
1190 
1191 	switch (reason & SEQ_CB_REASON_MASK) {
1192 	case SEQ_CB_START:
1193 		if ((reason & SEQ_CB_RD) != 0 && (sd->flags & SEQ_F_READING) == 0)
1194 			/* Begin recording. */
1195 			sd->flags |= SEQ_F_READING;
1196 		if ((reason & SEQ_CB_WR) != 0 && (sd->flags & SEQ_F_WRITING) == 0)
1197 			/* Start playing. */
1198 			seq_startplay(scp);
1199 		break;
1200 	case SEQ_CB_STOP:
1201 	case SEQ_CB_ABORT:
1202 		if ((reason & SEQ_CB_RD) != 0 && (sd->flags & SEQ_F_READING) != 0) {
1203 			/* Stop recording. */
1204 			sd->flags &= ~SEQ_F_READING;
1205 			scp->seq_time = seq_gettime();
1206 			scp->prev_input_time = 0;
1207 		}
1208 		if ((reason & SEQ_CB_WR) != 0 && (sd->flags & SEQ_F_WRITING) != 0) {
1209 			/* Stop Playing. */
1210 			sd->flags &= ~SEQ_F_WRITING;
1211 			scp->queueout_pending = 0;
1212 			scp->seq_time = seq_gettime();
1213 			scp->prev_input_time = 0;
1214 
1215 			/* Stop the timer. */
1216 			seq_stoptimer(scp);
1217 		}
1218 	}
1219 
1220 	return (0);
1221 }
1222 
1223 /*
1224  * The functions below here are the libraries for the above ones.
1225  */
1226 
1227 static int
1228 seq_queue(sc_p scp, u_char *note)
1229 {
1230 	int unit, err, lenw;
1231 	seqdev_info *sd;
1232 
1233 	sd = scp->devinfo;
1234 	unit = sd->unit;
1235 
1236 	mtx_assert(&sd->flagqueue_mtx, MA_OWNED);
1237 
1238 	SEQ_DEBUG(printf("seq_queue: unit %d.\n", unit));
1239 
1240 	if ((sd->flags & SEQ_F_INSYNC) != 0)
1241 		cv_wait(&sd->insync_cv, &sd->flagqueue_mtx);
1242 
1243 	if (sd->midi_dbuf_out.fl < EV_SZ) {
1244 		/* We have no space. Start playing if not yet. */
1245 		if ((sd->flags & SEQ_F_WRITING) == 0)
1246 			sd->callback(sd, SEQ_CB_START | SEQ_CB_WR);
1247 		if ((sd->flags & SEQ_F_NBIO) != 0 && sd->midi_dbuf_out.fl < EV_SZ)
1248 			/* We would block. */
1249 			return (EAGAIN);
1250 	}
1251 
1252 	/* Write to the queue. */
1253 	err = midibuf_seqwrite(&sd->midi_dbuf_out, note, EV_SZ, &lenw,
1254 			       sd->callback, sd, SEQ_CB_START | SEQ_CB_WR,
1255 			       &sd->flagqueue_mtx);
1256 
1257 	if (err == 0) {
1258 		/* Start playing if we have some data in the queue. */
1259 		if (sd->midi_dbuf_out.rl >= EV_SZ && ((sd->flags & SEQ_F_WRITING) == 0))
1260 			sd->callback(sd, SEQ_CB_START | SEQ_CB_WR);
1261 	}
1262 
1263 	return (err);
1264 }
1265 
1266 static void
1267 seq_startplay(sc_p scp)
1268 {
1269 	int unit, lenr;
1270 	u_char event[EV_SZ];
1271 	seqdev_info *sd;
1272 
1273 	sd = scp->devinfo;
1274 	unit = sd->unit;
1275 
1276 	mtx_assert(&sd->flagqueue_mtx, MA_OWNED);
1277 
1278 	sd->flags |= SEQ_F_WRITING;
1279 
1280 	/* Dequeue the events to play. */
1281 	while (sd->midi_dbuf_out.rl >= EV_SZ) {
1282 
1283 		midibuf_seqcopy(&sd->midi_dbuf_out, event, EV_SZ, &lenr,
1284 				NULL, NULL, 0,
1285 				&sd->flagqueue_mtx);
1286 
1287 		switch (seq_playevent(scp, event)) {
1288 		case TIMERARMED:
1289 			midibuf_seqdelete(&sd->midi_dbuf_out, EV_SZ, &lenr,
1290 					  NULL, NULL, 0,
1291 					  &sd->flagqueue_mtx);
1292 			return;
1293 		case QUEUEFULL:
1294 			/* We cannot play any further. */
1295 			return;
1296 		case MORE:
1297 			midibuf_seqdelete(&sd->midi_dbuf_out, EV_SZ, &lenr,
1298 					  NULL, NULL, 0,
1299 					  &sd->flagqueue_mtx);
1300 			break;
1301 		}
1302 	}
1303 
1304 	/* Played every event in the queue. */
1305 	sd->flags &= ~SEQ_F_WRITING;
1306 }
1307 
1308 static int
1309 seq_playevent(sc_p scp, u_char *event)
1310 {
1311 	int unit, ret, lenw;
1312 	long *delay;
1313 	seqdev_info *sd;
1314 	mididev_info *md;
1315 
1316 	sd = scp->devinfo;
1317 	unit = sd->unit;
1318 
1319 	mtx_assert(&sd->flagqueue_mtx, MA_OWNED);
1320 
1321 	ret = lookup_mididev(scp, 0, LOOKUP_OPEN, &md);
1322 	if (ret != 0)
1323 		return (MORE);
1324 
1325 	SEQ_DEBUG(printf("seq_playevent: unit %d, event %s.\n", sd->unit, midi_cmdname(event[0], cmdtab_seqevent)));
1326 
1327 	switch(event[0]) {
1328 	case SEQ_NOTEOFF:
1329 		mtx_unlock(&sd->flagqueue_mtx);
1330 		SEQ_DEBUG(printf("seq_playevent: chn %d, note %d, vel %d.\n", event[1], event[2], event[3]));
1331 		if (md->synth.killnote(md, event[1], 255, event[3]) == EAGAIN) {
1332 			mtx_lock(&sd->flagqueue_mtx);
1333 			ret = QUEUEFULL;
1334 			break;
1335 		}
1336 		mtx_lock(&sd->flagqueue_mtx);
1337 		ret = MORE;
1338 		break;
1339 	case SEQ_NOTEON:
1340 		mtx_unlock(&sd->flagqueue_mtx);
1341 		SEQ_DEBUG(printf("seq_playevent: chn %d, note %d, vel %d, aux %d.\n", event[1], event[2], event[3], event[4]));
1342 		if ((event[4] < 128 || event[4] == 255) && md->synth.startnote(md, event[1], event[2], event[3]) == EAGAIN) {
1343 			mtx_lock(&sd->flagqueue_mtx);
1344 			ret = QUEUEFULL;
1345 			break;
1346 		}
1347 		mtx_lock(&sd->flagqueue_mtx);
1348 		ret = MORE;
1349 		break;
1350 	case SEQ_WAIT:
1351 
1352 		/* Extract the delay. */
1353 		delay = (long *)event;
1354 		*delay = (*delay >> 8) & 0xffffff;
1355 		SEQ_DEBUG(printf("seq_playevent: delay %ld.\n", *delay));
1356 		if (*delay > 0) {
1357 			/* Arm the timer. */
1358 			sd->flags |= SEQ_F_WRITING;
1359 			if (seq_requesttimer(scp, *delay)) {
1360 				ret = TIMERARMED;
1361 				break;
1362 			}
1363 		}
1364 		ret = MORE;
1365 		break;
1366 	case SEQ_PGMCHANGE:
1367 		SEQ_DEBUG(printf("seq_playevent: chn %d, instr %d.\n", event[1], event[2]));
1368 		mtx_unlock(&sd->flagqueue_mtx);
1369 		if (md->synth.setinstr(md, event[1], event[2]) == EAGAIN) {
1370 			mtx_lock(&sd->flagqueue_mtx);
1371 			ret = QUEUEFULL;
1372 			break;
1373 		}
1374 		mtx_lock(&sd->flagqueue_mtx);
1375 		ret = MORE;
1376 		break;
1377 	case SEQ_SYNCTIMER:
1378 		/* Reset the timer. */
1379 		scp->seq_time = seq_gettime();
1380 		scp->prev_input_time = 0;
1381 		scp->prev_event_time = 0;
1382 		scp->prev_wakeup_time = scp->seq_time;
1383 		ret = MORE;
1384 		break;
1385 	case SEQ_MIDIPUTC:
1386 		SEQ_DEBUG(printf("seq_playevent: data 0x%02x, unit %d.\n", event[1], event[2]));
1387 		/* Pass through to the midi device. */
1388 		ret = lookup_mididev_midi(scp, event[2], LOOKUP_OPEN, &md);
1389 		if (ret != 0) {
1390 			ret = MORE;
1391 			break;
1392 		}
1393 		mtx_unlock(&sd->flagqueue_mtx);
1394 		if (md->synth.writeraw(md, &event[1], sizeof(event[1]), &lenw, 1) == EAGAIN)
1395 			/* The queue was full. Try again later. */
1396 			ret = QUEUEFULL;
1397 		else
1398 			ret = MORE;
1399 		mtx_lock(&sd->flagqueue_mtx);
1400 		break;
1401 	case SEQ_ECHO:
1402 		/* Echo this event back. */
1403 		if (seq_copytoinput(scp, event, 4) == EAGAIN) {
1404 			ret = QUEUEFULL;
1405 			break;
1406 		}
1407 		ret = MORE;
1408 		break;
1409 	case SEQ_PRIVATE:
1410 		ret = lookup_mididev(scp, event[1], LOOKUP_OPEN, &md);
1411 		if (ret != 0) {
1412 			ret = MORE;
1413 			break;
1414 		}
1415 		mtx_unlock(&sd->flagqueue_mtx);
1416 		if (md->synth.hwcontrol(md, event) == EAGAIN) {
1417 			mtx_lock(&sd->flagqueue_mtx);
1418 			ret = QUEUEFULL;
1419 			break;
1420 		}
1421 		mtx_lock(&sd->flagqueue_mtx);
1422 		ret = MORE;
1423 		break;
1424 	case SEQ_EXTENDED:
1425 		ret = seq_extended(scp, event);
1426 		break;
1427 	case EV_CHN_VOICE:
1428 		ret = seq_chnvoice(scp, event);
1429 		break;
1430 	case EV_CHN_COMMON:
1431 		ret = seq_chncommon(scp, event);
1432 		break;
1433 	case EV_TIMING:
1434 		ret = seq_timing(scp, event);
1435 		break;
1436 	case EV_SEQ_LOCAL:
1437 		ret = seq_local(scp, event);
1438 		break;
1439 	case EV_SYSEX:
1440 		ret = seq_sysex(scp, event);
1441 		break;
1442 	default:
1443 		ret = MORE;
1444 		break;
1445 	}
1446 
1447 	switch (ret) {
1448 	case QUEUEFULL:
1449 		SEQ_DEBUG(printf("seq_playevent: the queue is full.\n"));
1450 		/* The queue was full. Try again on the interrupt by the midi device. */
1451 		sd->flags |= SEQ_F_WRITING;
1452 		scp->queueout_pending = 1;
1453 		break;
1454 	case TIMERARMED:
1455 		SEQ_DEBUG(printf("seq_playevent: armed timer.\n"));
1456 		sd->flags |= SEQ_F_WRITING;
1457 		/* FALLTHRU */
1458 	case MORE:
1459 		scp->queueout_pending = 0;
1460 		break;
1461 	}
1462 
1463 	return (ret);
1464 }
1465 
1466 static u_long
1467 seq_gettime(void)
1468 {
1469 	struct timeval  timecopy;
1470 
1471 	getmicrotime(&timecopy);
1472 	return timecopy.tv_usec / (1000000 / hz) + (u_long) timecopy.tv_sec * hz;
1473 }
1474 
1475 static int
1476 seq_requesttimer(sc_p scp, int delay)
1477 {
1478 	u_long cur_time, rel_base;
1479 
1480 	SEQ_DEBUG(printf("seq_requesttimer: unit %d, delay %d.\n", scp->devinfo->unit, delay));
1481 
1482 	mtx_assert(&scp->devinfo->flagqueue_mtx, MA_OWNED);
1483 
1484 	cur_time = seq_gettime();
1485 
1486 	scp->prev_event_time = delay;
1487 	if (delay < 0)
1488 		/* Request a new timer. */
1489 		delay = -delay;
1490 	else {
1491 		rel_base = cur_time - scp->seq_time;
1492 		if (delay <= rel_base) {
1493 			seq_stoptimer(scp);
1494 			return 0;
1495 		}
1496 		delay -= rel_base;
1497 	}
1498 
1499 #if notdef
1500 	/*
1501 	 * Compensate the delay of midi message transmission.
1502 	 * XXX Do we have to consider the accumulation of errors
1503 	 * less than 1/hz second?
1504 	 */
1505 	delay -= (cur_time - scp->prev_wakeup_time);
1506 	if (delay < 1) {
1507 		printf("sequencer: prev = %lu, cur = %lu, delay = %d, skip sleeping.\n",
1508 			scp->prev_wakeup_time, cur_time, delay);
1509 		seq_stoptimer(scp);
1510 		return 0;
1511 	}
1512 #endif /* notdef */
1513 
1514 	callout_reset(&scp->timeout_ch, delay, seq_timer, (void *)scp);
1515 	scp->timer_running = 1;
1516 
1517 	return 1;
1518 }
1519 
1520 static void
1521 seq_stoptimer(sc_p scp)
1522 {
1523 	SEQ_DEBUG(printf("seq_stoptimer: unit %d.\n", scp->devinfo->unit));
1524 
1525 	mtx_assert(&scp->devinfo->flagqueue_mtx, MA_OWNED);
1526 
1527 	if (scp->timer_running) {
1528 		callout_stop(&scp->timeout_ch);
1529 		scp->timer_running = 0;
1530 	}
1531 }
1532 
1533 static void
1534 seq_midiinput(sc_p scp, mididev_info *md)
1535 {
1536 	int unit, midiunit, lenr;
1537 	u_long tstamp;
1538 	u_char event[4];
1539 	seqdev_info *sd;
1540 
1541 	mtx_assert(&scp->devinfo->flagqueue_mtx, MA_OWNED);
1542 
1543 	sd = scp->devinfo;
1544 	unit = sd->unit;
1545 
1546 	/* Can this midi device interrupt for input? */
1547 	midiunit = md->midiunit;
1548 	if (lookup_mididev_midi(scp, midiunit, LOOKUP_EXIST, NULL) != 0)
1549 		return;
1550 
1551 	if ((md->flags & MIDI_F_READING) != 0 && md->intrarg == sd) {
1552 		/* Read the input data. */
1553 		mtx_unlock(&scp->devinfo->flagqueue_mtx);
1554 		while (md->synth.readraw(md, &event[1], sizeof(event[1]), &lenr, 1) == 0) {
1555 			mtx_lock(&scp->devinfo->flagqueue_mtx);
1556 			tstamp = seq_gettime() - scp->seq_time;
1557 			if (tstamp != scp->prev_input_time) {
1558 				/* Insert a wait between events. */
1559 				tstamp = (tstamp << 8) | SEQ_WAIT;
1560 				seq_copytoinput(scp, (u_char *)&tstamp, 4);
1561 				scp->prev_input_time = tstamp;
1562 			}
1563 			bzero(event, sizeof(event));
1564 			event[0] = SEQ_MIDIPUTC;
1565 			event[2] = midiunit;
1566 			event[3] = 0;
1567 			seq_copytoinput(scp, event, sizeof(event));
1568 			mtx_unlock(&scp->devinfo->flagqueue_mtx);
1569 		}
1570 		mtx_lock(&scp->devinfo->flagqueue_mtx);
1571 	}
1572 }
1573 
1574 int
1575 seq_copytoinput(void *arg, u_char *event, int len)
1576 {
1577 	int ret, leni;
1578 	sc_p scp;
1579 	seqdev_info *sd;
1580 
1581 	scp = arg;
1582 	sd = scp->devinfo;
1583 
1584 	mtx_assert(&sd->flagqueue_mtx, MA_OWNED);
1585 
1586 	if (len != 4 && len != 8)
1587 		return (EINVAL);
1588 	if (scp->seq_mode == SND_DEV_MUSIC && len != 8)
1589 		return (EINVAL);
1590 
1591 	ret = midibuf_input_intr(&sd->midi_dbuf_in, event, len, &leni);
1592 	if (ret == EAGAIN)
1593 		ret = 0;
1594 
1595 	return (ret);
1596 }
1597 
1598 static int
1599 seq_extended(sc_p scp, u_char *event)
1600 {
1601 	int unit;
1602 	seqdev_info *sd;
1603 	mididev_info *md;
1604 
1605 	sd = scp->devinfo;
1606 	unit = sd->unit;
1607 
1608 	mtx_assert(&sd->flagqueue_mtx, MA_OWNED);
1609 
1610 	if (lookup_mididev(scp, event[2], LOOKUP_OPEN, &md) != 0)
1611 		return (MORE);
1612 
1613 	SEQ_DEBUG(printf("seq_extended: unit %d, event %s, midiunit %d.\n", unit, midi_cmdname(event[1], cmdtab_seqevent), event[2]));
1614 
1615 	switch (event[1]) {
1616 	case SEQ_NOTEOFF:
1617 		mtx_unlock(&sd->flagqueue_mtx);
1618 		SEQ_DEBUG(printf("seq_extended: chn %d, note %d, vel %d.\n", event[3], event[4], event[5]));
1619 		if (md->synth.killnote(md, event[3], event[4], event[5]) == EAGAIN) {
1620 			mtx_lock(&sd->flagqueue_mtx);
1621 			return (QUEUEFULL);
1622 		}
1623 		mtx_lock(&sd->flagqueue_mtx);
1624 		break;
1625 	case SEQ_NOTEON:
1626 		mtx_unlock(&sd->flagqueue_mtx);
1627 		SEQ_DEBUG(printf("seq_extended: chn %d, note %d, vel %d.\n", event[3], event[4], event[5]));
1628 		if ((event[4] < 128 || event[4] == 255) && md->synth.startnote(md, event[3], event[4], event[5]) == EAGAIN) {
1629 			mtx_lock(&sd->flagqueue_mtx);
1630 			return (QUEUEFULL);
1631 		}
1632 		mtx_lock(&sd->flagqueue_mtx);
1633 		break;
1634 	case SEQ_PGMCHANGE:
1635 		mtx_unlock(&sd->flagqueue_mtx);
1636 		SEQ_DEBUG(printf("seq_extended: chn %d, instr %d.\n", event[3], event[4]));
1637 		if (md->synth.setinstr(md, event[3], event[4]) == EAGAIN) {
1638 			mtx_lock(&sd->flagqueue_mtx);
1639 			return (QUEUEFULL);
1640 		}
1641 		mtx_lock(&sd->flagqueue_mtx);
1642 		break;
1643 	case SEQ_AFTERTOUCH:
1644 		mtx_unlock(&sd->flagqueue_mtx);
1645 		SEQ_DEBUG(printf("seq_extended: chn %d, press %d.\n", event[3], event[4]));
1646 		if (md->synth.aftertouch(md, event[3], event[4]) == EAGAIN) {
1647 			mtx_lock(&sd->flagqueue_mtx);
1648 			return (QUEUEFULL);
1649 		}
1650 		mtx_lock(&sd->flagqueue_mtx);
1651 		break;
1652 	case SEQ_BALANCE:
1653 		mtx_unlock(&sd->flagqueue_mtx);
1654 		SEQ_DEBUG(printf("seq_extended: chn %d, pan %d.\n", event[3], event[4]));
1655 		if (md->synth.panning(md, event[3], (char)event[4]) == EAGAIN) {
1656 			mtx_lock(&sd->flagqueue_mtx);
1657 			return (QUEUEFULL);
1658 		}
1659 		mtx_lock(&sd->flagqueue_mtx);
1660 		break;
1661 	case SEQ_CONTROLLER:
1662 		mtx_unlock(&sd->flagqueue_mtx);
1663 		SEQ_DEBUG(printf("seq_extended: chn %d, ctrlnum %d, val %d.\n", event[3], event[4], *(short *)&event[5]));
1664 		if (md->synth.controller(md, event[3], event[4], *(short *)&event[5]) == EAGAIN) {
1665 			mtx_lock(&sd->flagqueue_mtx);
1666 			return (QUEUEFULL);
1667 		}
1668 		mtx_lock(&sd->flagqueue_mtx);
1669 		break;
1670 	case SEQ_VOLMODE:
1671 		mtx_unlock(&sd->flagqueue_mtx);
1672 		SEQ_DEBUG(printf("seq_extended: mode %d.\n", event[3]));
1673 		if (md->synth.volumemethod != NULL && md->synth.volumemethod(md, event[3]) == EAGAIN) {
1674 			mtx_lock(&sd->flagqueue_mtx);
1675 			return (QUEUEFULL);
1676 		}
1677 		mtx_lock(&sd->flagqueue_mtx);
1678 		break;
1679 	}
1680 
1681 	return (MORE);
1682 }
1683 
1684 static int
1685 seq_chnvoice(sc_p scp, u_char *event)
1686 {
1687 	int voice;
1688 	seqdev_info *sd;
1689 	mididev_info *md;
1690 	u_char dev, cmd, chn, note, parm;
1691 
1692 	voice = -1;
1693 	dev = event[1];
1694 	cmd = event[2];
1695 	chn = event[3];
1696 	note = event[4];
1697 	parm = event[5];
1698 
1699 	sd = scp->devinfo;
1700 
1701 	mtx_assert(&sd->flagqueue_mtx, MA_OWNED);
1702 
1703 	if (lookup_mididev(scp, dev, LOOKUP_OPEN, &md) != 0)
1704 		return (MORE);
1705 
1706 	SEQ_DEBUG(printf("seq_chnvoice: unit %d, dev %d, cmd %s, chn %d, note %d, parm %d.\n",
1707 			 sd->unit,
1708 			 dev,
1709 			 midi_cmdname(cmd, cmdtab_seqcv),
1710 			 chn,
1711 			 note,
1712 			 parm));
1713 
1714 	if (scp->seq_mode == SND_DEV_MUSIC && md->synth.allocvoice != NULL)
1715 		voice = seq_allocvoice(scp, md, chn, note);
1716 	switch (cmd) {
1717 	case MIDI_NOTEON:
1718 		if (note < 128 || note == 255) {
1719 			if (voice == -1 && scp->seq_mode == SND_DEV_MUSIC && md->synth.allocvoice)
1720 				/* This is an internal synthesizer. (FM, GUS, etc) */
1721 				if ((voice = seq_allocvoice(scp, md, chn, note)) == EAGAIN)
1722 					return (QUEUEFULL);
1723 			if (voice == -1)
1724 				voice = chn;
1725 
1726 			if (scp->seq_mode == SND_DEV_MUSIC && chn == 9) {
1727 				/* This channel is a percussion. The note number is the patch number. */
1728 				mtx_unlock(&sd->flagqueue_mtx);
1729 				if (md->synth.setinstr(md, voice, 128 + note) == EAGAIN) {
1730 					mtx_lock(&sd->flagqueue_mtx);
1731 					return (QUEUEFULL);
1732 				}
1733 				mtx_lock(&sd->flagqueue_mtx);
1734 
1735 				note = 60; /* Middle C. */
1736 			}
1737 			if (scp->seq_mode == SND_DEV_MUSIC) {
1738 				mtx_unlock(&sd->flagqueue_mtx);
1739 				if (md->synth.setupvoice(md, voice, chn) == EAGAIN) {
1740 					mtx_lock(&sd->flagqueue_mtx);
1741 					return (QUEUEFULL);
1742 				}
1743 				mtx_lock(&sd->flagqueue_mtx);
1744 			}
1745 			mtx_unlock(&sd->flagqueue_mtx);
1746 			if (md->synth.startnote(md, voice, note, parm) == EAGAIN) {
1747 				mtx_lock(&sd->flagqueue_mtx);
1748 				return (QUEUEFULL);
1749 			}
1750 			mtx_lock(&sd->flagqueue_mtx);
1751 		}
1752 		break;
1753 	case MIDI_NOTEOFF:
1754 		if (voice == -1)
1755 			voice = chn;
1756 		mtx_unlock(&sd->flagqueue_mtx);
1757 		if (md->synth.killnote(md, voice, note, parm) == EAGAIN) {
1758 			mtx_lock(&sd->flagqueue_mtx);
1759 			return (QUEUEFULL);
1760 		}
1761 		mtx_lock(&sd->flagqueue_mtx);
1762 		break;
1763 	case MIDI_KEY_PRESSURE:
1764 		if (voice == -1)
1765 			voice = chn;
1766 		mtx_unlock(&sd->flagqueue_mtx);
1767 		if (md->synth.aftertouch(md, voice, parm) == EAGAIN) {
1768 			mtx_lock(&sd->flagqueue_mtx);
1769 			return (QUEUEFULL);
1770 		}
1771 		mtx_lock(&sd->flagqueue_mtx);
1772 		break;
1773 	}
1774 
1775 	return (MORE);
1776 }
1777 
1778 static int
1779 seq_findvoice(mididev_info *md, int chn, int note)
1780 {
1781 	int i;
1782 	u_short key;
1783 
1784 	key = (chn << 8) | (note + 1);
1785 
1786 	mtx_lock(&md->synth.vc_mtx);
1787 	for (i = 0 ; i < md->synth.alloc.max_voice ; i++)
1788 		if (md->synth.alloc.map[i] == key) {
1789 			mtx_unlock(&md->synth.vc_mtx);
1790 			return (i);
1791 		}
1792 	mtx_unlock(&md->synth.vc_mtx);
1793 
1794 	return (-1);
1795 }
1796 
1797 static int
1798 seq_allocvoice(sc_p scp, mididev_info *md, int chn, int note)
1799 {
1800 	int voice;
1801 	u_short key;
1802 
1803 	mtx_assert(&scp->devinfo->flagqueue_mtx, MA_OWNED);
1804 
1805 	key = (chn << 8) | (note + 1);
1806 
1807 	mtx_unlock(&scp->devinfo->flagqueue_mtx);
1808 	if ((voice = md->synth.allocvoice(md, chn, note, &md->synth.alloc)) == EAGAIN) {
1809 		mtx_lock(&scp->devinfo->flagqueue_mtx);
1810 		return (EAGAIN);
1811 	}
1812 	mtx_lock(&scp->devinfo->flagqueue_mtx);
1813 
1814 	mtx_lock(&md->synth.vc_mtx);
1815 	md->synth.alloc.map[voice] = key;
1816 	md->synth.alloc.alloc_times[voice] = md->synth.alloc.timestamp++;
1817 	mtx_unlock(&md->synth.vc_mtx);
1818 
1819 	return (voice);
1820 }
1821 
1822 static int
1823 seq_chncommon(sc_p scp, u_char *event)
1824 {
1825 	int unit, i, val, key;
1826 	u_short w14;
1827 	u_char dev, cmd, chn, p1;
1828 	seqdev_info *sd;
1829 	mididev_info *md;
1830 
1831 	dev = event[1];
1832 	cmd = event[2];
1833 	chn = event[3];
1834 	p1 = event[4];
1835 	w14 = *(u_short *)&event[6];
1836 
1837 	sd = scp->devinfo;
1838 	unit = sd->unit;
1839 
1840 	mtx_assert(&sd->flagqueue_mtx, MA_OWNED);
1841 
1842 	if (lookup_mididev(scp, dev, LOOKUP_OPEN, &md) != 0)
1843 		return (MORE);
1844 
1845 	SEQ_DEBUG(printf("seq_chnvoice: unit %d, dev %d, cmd %s, chn %d, p1 %d, w14 %d.\n",
1846 			 sd->unit,
1847 			 dev,
1848 			 midi_cmdname(cmd, cmdtab_seqccmn),
1849 			 chn,
1850 			 p1,
1851 			 w14));
1852 
1853 	switch (cmd) {
1854 	case MIDI_PGM_CHANGE:
1855 		if (scp->seq_mode == SND_DEV_MUSIC) {
1856 			mtx_lock(&md->synth.vc_mtx);
1857 			md->synth.chn_info[chn].pgm_num = p1;
1858 			mtx_unlock(&md->synth.vc_mtx);
1859 			mtx_unlock(&sd->flagqueue_mtx);
1860 			if (md->midiunit >= 0) {
1861 				if (md->synth.setinstr(md, chn, p1) == EAGAIN) {
1862 					mtx_lock(&sd->flagqueue_mtx);
1863 					return (QUEUEFULL);
1864 				}
1865 			}
1866 			mtx_lock(&sd->flagqueue_mtx);
1867 		} else {
1868 			/* For Mode 1. */
1869 			mtx_unlock(&sd->flagqueue_mtx);
1870 			if (md->synth.setinstr(md, chn, p1) == EAGAIN) {
1871 				mtx_lock(&sd->flagqueue_mtx);
1872 				return (QUEUEFULL);
1873 			}
1874 			mtx_lock(&sd->flagqueue_mtx);
1875 		}
1876 		break;
1877 	case MIDI_CTL_CHANGE:
1878 		/* mtx_lock(&md->giant); */
1879 		if (scp->seq_mode == SND_DEV_MUSIC) {
1880 			if (chn < 16 && p1 < 128) {
1881 				mtx_lock(&md->synth.vc_mtx);
1882 				md->synth.chn_info[chn].controllers[p1] = w14 & 0x7f;
1883 				if (p1 < 32)
1884 					/* We have set the MSB, clear the LSB. */
1885 					md->synth.chn_info[chn].controllers[p1 + 32] = 0;
1886 				if (md->midiunit >= 0) {
1887 					val = w14 & 0x7f;
1888 					if (p1 < 64) {
1889 						/* Combine the MSB and the LSB. */
1890 						val = ((md->synth.chn_info[chn].controllers[p1 & ~32] & 0x7f) << 7)
1891 						    | (md->synth.chn_info[chn].controllers[p1 | 32] & 0x7f);
1892 						p1 &= ~32;
1893 					}
1894 					/* Handle all of the notes playing on this channel. */
1895 					key = ((int)chn << 8);
1896 					for (i = 0 ; i < md->synth.alloc.max_voice ; i++)
1897 						if ((md->synth.alloc.map[i] & 0xff00) == key) {
1898 							mtx_unlock(&md->synth.vc_mtx);
1899 							mtx_unlock(&sd->flagqueue_mtx);
1900 							if (md->synth.controller(md, i, p1, val) == EAGAIN) {
1901 								mtx_lock(&sd->flagqueue_mtx);
1902 								return (QUEUEFULL);
1903 							}
1904 							mtx_lock(&sd->flagqueue_mtx);
1905 							mtx_lock(&md->synth.vc_mtx);
1906 						}
1907 					mtx_unlock(&md->synth.vc_mtx);
1908 				} else {
1909 					mtx_unlock(&md->synth.vc_mtx);
1910 					mtx_unlock(&sd->flagqueue_mtx);
1911 					if (md->synth.controller(md, chn, p1, w14) == EAGAIN) {
1912 						mtx_lock(&sd->flagqueue_mtx);
1913 						return (QUEUEFULL);
1914 					}
1915 					mtx_lock(&sd->flagqueue_mtx);
1916 				}
1917 			}
1918 		} else {
1919 			/* For Mode 1. */
1920 			mtx_unlock(&sd->flagqueue_mtx);
1921 			if (md->synth.controller(md, chn, p1, w14) == EAGAIN) {
1922 				mtx_lock(&sd->flagqueue_mtx);
1923 				return (QUEUEFULL);
1924 			}
1925 			mtx_lock(&sd->flagqueue_mtx);
1926 		}
1927 		break;
1928 	case MIDI_PITCH_BEND:
1929 		if (scp->seq_mode == SND_DEV_MUSIC) {
1930 			mtx_lock(&md->synth.vc_mtx);
1931 			md->synth.chn_info[chn].bender_value = w14;
1932 			if (md->midiunit >= 0) {
1933 				/* Handle all of the notes playing on this channel. */
1934 				key = ((int)chn << 8);
1935 				for (i = 0 ; i < md->synth.alloc.max_voice ; i++)
1936 					if ((md->synth.alloc.map[i] & 0xff00) == key) {
1937 						mtx_unlock(&md->synth.vc_mtx);
1938 						mtx_unlock(&sd->flagqueue_mtx);
1939 						if (md->synth.bender(md, i, w14) == EAGAIN) {
1940 							mtx_lock(&sd->flagqueue_mtx);
1941 							return (QUEUEFULL);
1942 						}
1943 						mtx_lock(&sd->flagqueue_mtx);
1944 					}
1945 			} else {
1946 				mtx_unlock(&md->synth.vc_mtx);
1947 				mtx_unlock(&sd->flagqueue_mtx);
1948 				if (md->synth.bender(md, chn, w14) == EAGAIN) {
1949 					mtx_lock(&sd->flagqueue_mtx);
1950 					return (QUEUEFULL);
1951 				}
1952 				mtx_lock(&sd->flagqueue_mtx);
1953 			}
1954 		} else {
1955 			/* For Mode 1. */
1956 			mtx_unlock(&sd->flagqueue_mtx);
1957 			if (md->synth.bender(md, chn, w14) == EAGAIN) {
1958 				mtx_lock(&sd->flagqueue_mtx);
1959 				return (QUEUEFULL);
1960 			}
1961 			mtx_lock(&sd->flagqueue_mtx);
1962 		}
1963 		break;
1964 	}
1965 
1966 	return (MORE);
1967 }
1968 
1969 static int
1970 seq_timing(sc_p scp, u_char *event)
1971 {
1972 	int unit, ret;
1973 	long parm;
1974 	seqdev_info *sd;
1975 
1976 	sd = scp->devinfo;
1977 	unit = sd->unit;
1978 
1979 	mtx_assert(&sd->flagqueue_mtx, MA_OWNED);
1980 
1981 	parm = *(long *)&event[4];
1982 
1983 	if (scp->seq_mode == SND_DEV_MUSIC) {
1984 		ret = scp->timer->event(scp->timer, event);
1985 		if (ret == TIMERARMED)
1986 			sd->flags |= SEQ_F_WRITING;
1987 		return (ret);
1988 	}
1989 
1990 	SEQ_DEBUG(printf("seq_timing: unit %d, cmd %s, parm %lu.\n",
1991 			 unit, midi_cmdname(event[1], cmdtab_timer), parm));
1992 
1993 	ret = MORE;
1994 	switch (event[1]) {
1995 	case TMR_WAIT_REL:
1996 		parm += scp->prev_event_time;
1997 		/* FALLTHRU */
1998 	case TMR_WAIT_ABS:
1999 		if (parm > 0) {
2000 			sd->flags |= SEQ_F_WRITING;
2001 			if (seq_requesttimer(scp, parm))
2002 				ret = TIMERARMED;
2003 		}
2004 		break;
2005 	case TMR_START:
2006 		scp->seq_time = seq_gettime();
2007 		scp->prev_input_time = 0;
2008 		scp->prev_event_time = 0;
2009 		scp->prev_wakeup_time = scp->seq_time;
2010 		break;
2011 	case TMR_STOP:
2012 		break;
2013 	case TMR_CONTINUE:
2014 		break;
2015 	case TMR_TEMPO:
2016 		break;
2017 	case TMR_ECHO:
2018 		if (scp->seq_mode == SND_DEV_MUSIC)
2019 			seq_copytoinput(scp, event, 8);
2020 		else {
2021 			parm = (parm << 8 | SEQ_ECHO);
2022 			seq_copytoinput(scp, (u_char *)&parm, 4);
2023 		}
2024 		break;
2025 	}
2026 
2027 	SEQ_DEBUG(printf("seq_timing: timer %s.\n",
2028 			 ret == TIMERARMED ? "armed" : "not armed"));
2029 
2030 	return (ret);
2031 }
2032 
2033 static int
2034 seq_local(sc_p scp, u_char *event)
2035 {
2036 	int unit;
2037 	seqdev_info *sd;
2038 
2039 	sd = scp->devinfo;
2040 	unit = sd->unit;
2041 
2042 	mtx_assert(&sd->flagqueue_mtx, MA_OWNED);
2043 
2044 	switch (event[1]) {
2045 	case LOCL_STARTAUDIO:
2046 #if notyet
2047 		DMAbuf_start_devices(*(u_int *)&event[4]);
2048 #endif /* notyet */
2049 		break;
2050 	}
2051 
2052 	return (MORE);
2053 }
2054 
2055 static int
2056 seq_sysex(sc_p scp, u_char *event)
2057 {
2058 	int unit, i, l;
2059 	seqdev_info *sd;
2060 	mididev_info *md;
2061 
2062 	sd = scp->devinfo;
2063 	unit = sd->unit;
2064 
2065 	mtx_assert(&sd->flagqueue_mtx, MA_OWNED);
2066 
2067 	if (lookup_mididev(scp, event[1], LOOKUP_OPEN, &md) != 0)
2068 		return (MORE);
2069 
2070 	l = 0;
2071 	for (i = 0 ; i < 6 && event[i + 2] != 0xff ; i++)
2072 		l = i + 1;
2073 	if (l > 0) {
2074 		mtx_unlock(&sd->flagqueue_mtx);
2075 		if (md->synth.sendsysex(md, &event[2], l) == EAGAIN) {
2076 			mtx_lock(&sd->flagqueue_mtx);
2077 			return (QUEUEFULL);
2078 		}
2079 		mtx_lock(&sd->flagqueue_mtx);
2080 	}
2081 
2082 	return (MORE);
2083 }
2084 
2085 void
2086 seq_timer(void *arg)
2087 {
2088 	sc_p scp;
2089 	seqdev_info *sd;
2090 
2091 	scp = arg;
2092 	sd = scp->devinfo;
2093 
2094 	SEQ_DEBUG(printf("seq_timer: unit %d, timer fired.\n", sd->unit));
2095 
2096 	/* Record the current timestamp. */
2097 	mtx_lock(&sd->flagqueue_mtx);
2098 
2099 	scp->timer_running = 0;
2100 	scp->prev_wakeup_time = seq_gettime();
2101 	seq_startplay(scp);
2102 
2103 	mtx_unlock(&sd->flagqueue_mtx);
2104 }
2105 
2106 static int
2107 seq_openmidi(sc_p scp, mididev_info *md, int flags, int mode, struct thread *td)
2108 {
2109 	int midiunit, err, insync, chn;
2110 
2111 	mtx_assert(&scp->devinfo->flagqueue_mtx, MA_OWNED);
2112 
2113 	midiunit = md->unit;
2114 
2115 	SEQ_DEBUG(printf("seq_openmidi: opening midi unit %d.\n", midiunit));
2116 
2117 	err = midi_open(MIDIMKDEV(MIDI_CDEV_MAJOR, midiunit, SND_DEV_MIDIN), flags, mode, td);
2118 	if (err != 0) {
2119 		printf("seq_openmidi: failed to open midi device %d.\n", midiunit);
2120 		return (err);
2121 	}
2122 	mtx_lock(&md->synth.status_mtx);
2123 	mtx_lock(&md->flagqueue_mtx);
2124 	md->intr = seq_intr;
2125 	md->intrarg = scp->devinfo;
2126 	mtx_unlock(&md->flagqueue_mtx);
2127 	md->synth.sysex_state = 0;
2128 	if (scp->seq_mode == SND_DEV_MUSIC) {
2129 		for (chn = 0 ; chn < 16 ; chn++) {
2130 			md->synth.chn_info[chn].pgm_num = 0;
2131 			md->synth.reset(md);
2132 			md->synth.chn_info[chn].bender_value = (1 << 7);
2133 		}
2134 	}
2135 	mtx_unlock(&md->synth.status_mtx);
2136 
2137 	insync = 0;
2138 	if ((scp->devinfo->flags & SEQ_F_INSYNC) != 0) {
2139 		insync = 1;
2140 		cv_wait(&scp->devinfo->insync_cv, &scp->devinfo->flagqueue_mtx);
2141 	}
2142 
2143 	TAILQ_INSERT_TAIL(&scp->midi_open, md, md_linkseq);
2144 
2145 	if (insync)
2146 		cv_broadcast(&scp->devinfo->insync_cv);
2147 
2148 	return (0);
2149 }
2150 
2151 static int
2152 seq_closemidi(sc_p scp, mididev_info *md, int flags, int mode, struct thread *td)
2153 {
2154 	int midiunit, insync;
2155 
2156 	mtx_assert(&scp->devinfo->flagqueue_mtx, MA_OWNED);
2157 
2158 	if (md == NULL || !MIDICONFED(md)) {
2159 		SEQ_DEBUG(printf("seq_closemidi: midi device does not exist.\n"));
2160 		return (ENXIO);
2161 	}
2162 	midiunit = md->unit;
2163 
2164 	SEQ_DEBUG(printf("seq_closemidi: closing midi unit %d.\n", midiunit));
2165 
2166 	midi_close(MIDIMKDEV(MIDI_CDEV_MAJOR, midiunit, SND_DEV_MIDIN), flags, mode, td);
2167 	mtx_lock(&md->flagqueue_mtx);
2168 	md->intr = NULL;
2169 	md->intrarg = NULL;
2170 	mtx_unlock(&md->flagqueue_mtx);
2171 
2172 	insync = 0;
2173 	if ((scp->devinfo->flags & SEQ_F_INSYNC) != 0) {
2174 		insync = 1;
2175 		cv_wait(&scp->devinfo->insync_cv, &scp->devinfo->flagqueue_mtx);
2176 	}
2177 
2178 	TAILQ_REMOVE(&scp->midi_open, md, md_linkseq);
2179 
2180 	if (insync)
2181 		cv_broadcast(&scp->devinfo->insync_cv);
2182 
2183 	return (0);
2184 }
2185 
2186 static void
2187 seq_panic(sc_p scp)
2188 {
2189 	mtx_assert(&scp->devinfo->flagqueue_mtx, MA_OWNED);
2190 
2191 	seq_reset(scp);
2192 }
2193 
2194 static int
2195 seq_reset(sc_p scp)
2196 {
2197 	int unit, chn, lenw, ret;
2198 	seqdev_info *sd;
2199 	mididev_info *md;
2200 	u_char c[3];
2201 
2202 	sd = scp->devinfo;
2203 	unit = sd->unit;
2204 
2205 	mtx_assert(&sd->flagqueue_mtx, MA_OWNED);
2206 
2207 	SEQ_DEBUG(printf("seq_reset: unit %d.\n", unit));
2208 
2209 	if ((sd->flags & SEQ_F_INSYNC) != 0)
2210 		cv_wait(&sd->insync_cv, &sd->flagqueue_mtx);
2211 
2212 	/* Stop reading and writing. */
2213 	sd->callback(sd, SEQ_CB_ABORT | SEQ_CB_RD | SEQ_CB_WR);
2214 
2215 	/* Clear the queues. */
2216 	midibuf_clear(&sd->midi_dbuf_in);
2217 	midibuf_clear(&sd->midi_dbuf_out);
2218 
2219 	/* Reset the synthesizers. */
2220 	TAILQ_FOREACH(md, &scp->midi_open, md_linkseq)
2221 		md->synth.reset(md);
2222 
2223 	if (scp->seq_mode == SND_DEV_MUSIC) {
2224 		for (chn = 0 ; chn < 16 ; chn++) {
2225 			TAILQ_FOREACH(md, &scp->midi_open, md_linkseq) {
2226 				mtx_unlock(&sd->flagqueue_mtx);
2227 				ret = 0;
2228 				if (md->synth.controller(md, chn, 123, 0) == EAGAIN /* All notes off. */
2229 				    || md->synth.controller(md, chn, 121, 0) == EAGAIN /* Reset all controllers. */
2230 				    || md->synth.bender(md, chn, 1 << 13) == EAGAIN) /* Reset pitch bend. */
2231 					ret = EAGAIN;
2232 				mtx_lock(&sd->flagqueue_mtx);
2233 				return (ret);
2234 			}
2235 		}
2236 	} else {
2237 		TAILQ_FOREACH(md, &scp->midi_open, md_linkseq) {
2238 			for (chn = 0 ; chn < 16 ; chn++) {
2239 				mtx_unlock(&sd->flagqueue_mtx);
2240 				c[0] = 0xb0 | (chn & 0x0f);
2241 				c[1] = (u_char)0x78; /* All sound off */
2242 				c[2] = (u_char)0;
2243 				md->synth.writeraw(md, c, 3, &lenw, 0);
2244 				c[1] = (u_char)0x7b; /* All note off */
2245 				md->synth.writeraw(md, c, 3, &lenw, 0);
2246 				c[1] = (u_char)0x79; /* Reset all controller */
2247 				md->synth.writeraw(md, c, 3, &lenw, 0);
2248 				mtx_lock(&sd->flagqueue_mtx);
2249 			}
2250 		}
2251 		seq_sync(scp);
2252 		TAILQ_FOREACH(md, &scp->midi_open, md_linkseq)
2253 			lookup_mididev(scp, md->unit, LOOKUP_CLOSE, NULL);
2254 	}
2255 
2256 	return (0);
2257 }
2258 
2259 #define SEQ_SYNC_TIMEOUT 8
2260 static int
2261 seq_sync(sc_p scp)
2262 {
2263 	int i, rl;
2264 	seqdev_info *sd;
2265 	mididev_info *md;
2266 
2267 	sd = scp->devinfo;
2268 
2269 	mtx_assert(&sd->flagqueue_mtx, MA_OWNED);
2270 
2271 	SEQ_DEBUG(printf("seq_sync: unit %d.\n", sd->unit));
2272 	sd->flags |= SEQ_F_INSYNC;
2273 
2274 	while (sd->midi_dbuf_out.rl >= EV_SZ) {
2275 		if ((sd->flags & SEQ_F_WRITING) == 0)
2276 			sd->callback(sd, SEQ_CB_START | SEQ_CB_WR);
2277 		rl = sd->midi_dbuf_out.rl;
2278 		i = cv_timedwait_sig(&sd->midi_dbuf_out.cv_out, &sd->flagqueue_mtx, SEQ_SYNC_TIMEOUT * hz);
2279 		if (i == EINTR || i == ERESTART) {
2280 			if (i == EINTR)
2281 				sd->callback(sd, SEQ_CB_STOP | SEQ_CB_WR);
2282 			sd->flags &= ~SEQ_F_INSYNC;
2283 			return (i);
2284 		}
2285 		if (i == EWOULDBLOCK && rl == sd->midi_dbuf_out.rl && !scp->timer_running) {
2286 			/* A queue seems to be stuck up. Give up and clear queues. */
2287 			sd->callback(sd, SEQ_CB_STOP | SEQ_CB_WR);
2288 			midibuf_clear(&sd->midi_dbuf_out);
2289 			TAILQ_FOREACH(md, &scp->midi_open, md_linkseq) {
2290 				mtx_lock(&md->flagqueue_mtx);
2291 				md->callback(md, MIDI_CB_ABORT | MIDI_CB_WR);
2292 				midibuf_clear(&md->midi_dbuf_out);
2293 				mtx_unlock(&md->flagqueue_mtx);
2294 			}
2295 			break;
2296 		}
2297 	}
2298 
2299 	/*
2300 	 * Since syncing a midi device might block, unlock sd->flagqueue_mtx.
2301 	 * Keep sd->midi_dbuf_out from writing by setting SEQ_F_INSYNC.
2302 	 * sd->insync_cv is signalled when sync is finished.
2303 	 */
2304 	mtx_unlock(&sd->flagqueue_mtx);
2305 
2306 	TAILQ_FOREACH(md, &scp->midi_open, md_linkseq) {
2307 		mtx_lock(&md->flagqueue_mtx);
2308 		midi_sync(md);
2309 		mtx_unlock(&md->flagqueue_mtx);
2310 	}
2311 
2312 	mtx_lock(&sd->flagqueue_mtx);
2313 	sd->flags &= ~SEQ_F_INSYNC;
2314 	cv_broadcast(&sd->insync_cv);
2315 
2316 	return (0);
2317 }
2318 
2319 /*
2320  * a small utility function which, given a device number, returns
2321  * a pointer to the associated seqdev_info struct, and sets the unit
2322  * number.
2323  */
2324 static seqdev_info *
2325 get_seqdev_info(dev_t i_dev, int *unit)
2326 {
2327 	int u;
2328 
2329 	if (MIDIDEV(i_dev) != SND_DEV_SEQ && MIDIDEV(i_dev) != SND_DEV_MUSIC)
2330 		return NULL;
2331 	u = MIDIUNIT(i_dev);
2332 	if (unit)
2333 		*unit = u ;
2334 
2335 	return get_seqdev_info_unit(u);
2336 }
2337 
2338 /*
2339  * a small utility function which, given a unit number, returns
2340  * a pointer to the associated mididev_info struct.
2341  */
2342 seqdev_info *
2343 get_seqdev_info_unit(int unit)
2344 {
2345 	seqdev_info *sd;
2346 
2347 	mtx_lock(&seqinfo_mtx);
2348 	TAILQ_FOREACH(sd, &seq_info, sd_link) {
2349 		if (sd->unit == unit)
2350 			break;
2351 	}
2352 	mtx_unlock(&seqinfo_mtx);
2353 
2354 	return sd;
2355 }
2356 
2357 /* Create a new sequencer device info structure. */
2358 seqdev_info *
2359 create_seqdev_info_unit(int unit, seqdev_info *seq)
2360 {
2361 	seqdev_info *sd, *sdnew;
2362 
2363 	/* As malloc(9) might block, allocate seqdev_info now. */
2364 	sdnew = malloc(sizeof(seqdev_info), M_DEVBUF, M_WAITOK | M_ZERO);
2365 	if (sdnew == NULL)
2366 		return NULL;
2367 	bcopy(seq, sdnew, sizeof(seqdev_info));
2368 	sdnew->unit = unit;
2369 	midibuf_init(&sdnew->midi_dbuf_in);
2370 	midibuf_init(&sdnew->midi_dbuf_out);
2371 	mtx_init(&sdnew->flagqueue_mtx, "seqflq", NULL, MTX_DEF);
2372 	cv_init(&sdnew->insync_cv, "seqins");
2373 
2374 	mtx_lock(&seqinfo_mtx);
2375 
2376 	TAILQ_FOREACH(sd, &seq_info, sd_link) {
2377 		if (sd->unit == unit) {
2378 			mtx_unlock(&seqinfo_mtx);
2379 			midibuf_destroy(&sdnew->midi_dbuf_in);
2380 			midibuf_destroy(&sdnew->midi_dbuf_out);
2381 			mtx_destroy(&sdnew->flagqueue_mtx);
2382 			cv_destroy(&sdnew->insync_cv);
2383 			free(sdnew, M_DEVBUF);
2384 			return sd;
2385 		}
2386 	}
2387 
2388 	mtx_lock(&sdnew->flagqueue_mtx);
2389 	TAILQ_INSERT_TAIL(&seq_info, sdnew, sd_link);
2390 	nseq++;
2391 
2392 	mtx_unlock(&seqinfo_mtx);
2393 
2394 	return sdnew;
2395 }
2396 
2397 /*
2398  * Look up a midi device by its unit number opened by this sequencer.
2399  * If the device is not opened and mode is LOOKUP_OPEN, open the device.
2400  */
2401 static int
2402 lookup_mididev(sc_p scp, int unit, int mode, mididev_info **mdp)
2403 {
2404 	int ret;
2405 	mididev_info *md;
2406 
2407 	if (mdp == NULL)
2408 		mdp = &md;
2409 
2410 	*mdp = NULL;
2411 
2412 	mtx_assert(&scp->devinfo->flagqueue_mtx, MA_OWNED);
2413 
2414 	TAILQ_FOREACH(md, &scp->midi_open, md_linkseq) {
2415 		if (scp->seq_mode == SND_DEV_MUSIC ? md->unit == unit : md->synthunit == unit) {
2416 			*mdp = md;
2417 			if (mode == LOOKUP_CLOSE)
2418 				return seq_closemidi(scp, md, scp->fflags, MIDIDEV_MODE, curthread);
2419 
2420 			return (md != NULL && MIDICONFED(md)) ? 0 : ENXIO;
2421 		}
2422 	}
2423 
2424 	if (mode == LOOKUP_OPEN) {
2425 		if (scp->seq_mode == SND_DEV_MUSIC)
2426 			md = get_mididev_info_unit(unit);
2427 		else
2428 			md = get_mididev_synth_unit(unit);
2429 		if (md != NULL) {
2430 			*mdp = md;
2431 			ret = seq_openmidi(scp, md, scp->fflags, MIDIDEV_MODE, curthread);
2432 			return ret;
2433 		}
2434 	}
2435 
2436 	return ENXIO;
2437 }
2438 
2439 /*
2440  * Look up a midi device by its midi unit number opened by this sequencer.
2441  * If the device is not opened and mode is LOOKUP_OPEN, open the device.
2442  */
2443 static int
2444 lookup_mididev_midi(sc_p scp, int unit, int mode, mididev_info **mdp)
2445 {
2446 	int ret;
2447 	mididev_info *md;
2448 
2449 	if (mdp == NULL)
2450 		mdp = &md;
2451 
2452 	*mdp = NULL;
2453 
2454 	if (scp->seq_mode == SND_DEV_MUSIC)
2455 		return (ENXIO);
2456 
2457 	mtx_assert(&scp->devinfo->flagqueue_mtx, MA_OWNED);
2458 
2459 	TAILQ_FOREACH(md, &scp->midi_open, md_linkseq) {
2460 		if (md->midiunit == unit) {
2461 			*mdp = md;
2462 			if (mode == LOOKUP_CLOSE)
2463 				return seq_closemidi(scp, md, scp->fflags, MIDIDEV_MODE, curthread);
2464 
2465 			return (md != NULL && MIDICONFED(md)) ? 0 : ENXIO;
2466 		}
2467 	}
2468 
2469 	if (mode == LOOKUP_OPEN) {
2470 		md = get_mididev_midi_unit(unit);
2471 		if (md != NULL) {
2472 			*mdp = md;
2473 			ret = seq_openmidi(scp, md, scp->fflags, MIDIDEV_MODE, curthread);
2474 			return ret;
2475 		}
2476 	}
2477 
2478 	return ENXIO;
2479 }
2480 
2481 /* XXX These functions are actually redundant. */
2482 static int
2483 seqopen(dev_t i_dev, int flags, int mode, struct thread *td)
2484 {
2485 	switch (MIDIDEV(i_dev)) {
2486 	case MIDI_DEV_SEQ:
2487 	case MIDI_DEV_MUSIC:
2488 		return seq_open(i_dev, flags, mode, td);
2489 	}
2490 
2491 	return (ENXIO);
2492 }
2493 
2494 static int
2495 seqclose(dev_t i_dev, int flags, int mode, struct thread *td)
2496 {
2497 	switch (MIDIDEV(i_dev)) {
2498 	case MIDI_DEV_SEQ:
2499 	case MIDI_DEV_MUSIC:
2500 		return seq_close(i_dev, flags, mode, td);
2501 	}
2502 
2503 	return (ENXIO);
2504 }
2505 
2506 static int
2507 seqread(dev_t i_dev, struct uio * buf, int flag)
2508 {
2509 	switch (MIDIDEV(i_dev)) {
2510 	case MIDI_DEV_SEQ:
2511 	case MIDI_DEV_MUSIC:
2512 		return seq_read(i_dev, buf, flag);
2513 	}
2514 
2515 	return (ENXIO);
2516 }
2517 
2518 static int
2519 seqwrite(dev_t i_dev, struct uio * buf, int flag)
2520 {
2521 	switch (MIDIDEV(i_dev)) {
2522 	case MIDI_DEV_SEQ:
2523 	case MIDI_DEV_MUSIC:
2524 		return seq_write(i_dev, buf, flag);
2525 	}
2526 
2527 	return (ENXIO);
2528 }
2529 
2530 static int
2531 seqioctl(dev_t i_dev, u_long cmd, caddr_t arg, int mode, struct thread *td)
2532 {
2533 	switch (MIDIDEV(i_dev)) {
2534 	case MIDI_DEV_SEQ:
2535 	case MIDI_DEV_MUSIC:
2536 		return seq_ioctl(i_dev, cmd, arg, mode, td);
2537 	}
2538 
2539 	return (ENXIO);
2540 }
2541 
2542 static int
2543 seqpoll(dev_t i_dev, int events, struct thread *td)
2544 {
2545 	switch (MIDIDEV(i_dev)) {
2546 	case MIDI_DEV_SEQ:
2547 	case MIDI_DEV_MUSIC:
2548 		return seq_poll(i_dev, events, td);
2549 	}
2550 
2551 	return (ENXIO);
2552 }
2553 
2554 static int
2555 seq_modevent(module_t mod, int type, void *data)
2556 {
2557 	int retval;
2558 
2559 	retval = 0;
2560 
2561 	switch (type) {
2562 	case MOD_LOAD:
2563 		seq_init();
2564 		break;
2565 
2566 	case MOD_UNLOAD:
2567 		printf("sequencer: unload not supported yet.\n");
2568 		retval = EOPNOTSUPP;
2569 		break;
2570 
2571 	default:
2572 		break;
2573 	}
2574 
2575 	return retval;
2576 }
2577 
2578 DEV_MODULE(seq, seq_modevent, NULL);
2579 
2580 static void
2581 seq_clone(arg, name, namelen, dev)
2582 	void *arg;
2583 	char *name;
2584 	int namelen;
2585 	dev_t *dev;
2586 {
2587 	int u;
2588 
2589 	if (*dev != NODEV)
2590 		return;
2591 	if (bcmp(name, "sequencer", 9) != 0)
2592 		return;
2593 	if (name[10] != '\0' && name[11] != '\0')
2594 		return;
2595 	u = name[9] - '0';
2596 	if (name[10] != '\0') {
2597 		u *= 10;
2598 		u += name[10] - '0';
2599 	}
2600 	seq_initunit(u);
2601 	*dev = MIDIMKDEV(SEQ_CDEV_MAJOR, u, MIDI_DEV_SEQ);
2602 	return;
2603 }
2604