xref: /netbsd-src/sys/dev/sequencer.c (revision deb6f0161a9109e7de9b519dc8dfb9478668dcdd)
1 /*	$NetBSD: sequencer.c,v 1.70 2017/10/29 17:57:21 riastradh Exp $	*/
2 
3 /*
4  * Copyright (c) 1998, 2008 The NetBSD Foundation, Inc.
5  * All rights reserved.
6  *
7  * This code is derived from software contributed to The NetBSD Foundation
8  * by Lennart Augustsson (augustss@NetBSD.org) and by Andrew Doran.
9  *
10  * Redistribution and use in source and binary forms, with or without
11  * modification, are permitted provided that the following conditions
12  * are met:
13  * 1. Redistributions of source code must retain the above copyright
14  *    notice, this list of conditions and the following disclaimer.
15  * 2. Redistributions in binary form must reproduce the above copyright
16  *    notice, this list of conditions and the following disclaimer in the
17  *    documentation and/or other materials provided with the distribution.
18  *
19  * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
20  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
21  * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
22  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
23  * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
24  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
25  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
26  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
27  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
28  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
29  * POSSIBILITY OF SUCH DAMAGE.
30  */
31 
32 /*
33  * Locking:
34  *
35  * o sc_lock: provides atomic access to all data structures.  Taken from
36  *   both process and soft interrupt context.
37  *
38  * o sc_dvlock: serializes operations on /dev/sequencer.  Taken from
39  *   process context.  Dropped while waiting for data in sequencerread()
40  *   to allow concurrent reads/writes while no data available.
41  *
42  * o sc_isopen: we allow only one concurrent open, only to prevent user
43  *   and/or application error.
44  *
45  * o MIDI softc locks.  These can be spinlocks and there can be many of
46  *   them, because we can open many MIDI devices.  We take these only in two
47  *   places: when enabling redirection from the MIDI device and when
48  *   disabling it (open/close).  midiseq_in() is called by the MIDI driver
49  *   with its own lock held when passing data into this module.  To avoid
50  *   lock order and context problems, we package the received message as a
51  *   sequencer_pcqitem_t and put onto a producer-consumer queue.  A soft
52  *   interrupt is scheduled to dequeue and decode the message later where we
53  *   can safely acquire the sequencer device's sc_lock.  PCQ is lockless for
54  *   multiple producer, single consumer settings like this one.
55  */
56 
57 #include <sys/cdefs.h>
58 __KERNEL_RCSID(0, "$NetBSD: sequencer.c,v 1.70 2017/10/29 17:57:21 riastradh Exp $");
59 
60 #ifdef _KERNEL_OPT
61 #include "sequencer.h"
62 #include "midi.h"
63 #endif
64 
65 #include <sys/param.h>
66 #include <sys/ioctl.h>
67 #include <sys/fcntl.h>
68 #include <sys/vnode.h>
69 #include <sys/select.h>
70 #include <sys/poll.h>
71 #include <sys/kmem.h>
72 #include <sys/proc.h>
73 #include <sys/systm.h>
74 #include <sys/syslog.h>
75 #include <sys/kernel.h>
76 #include <sys/signalvar.h>
77 #include <sys/conf.h>
78 #include <sys/audioio.h>
79 #include <sys/midiio.h>
80 #include <sys/device.h>
81 #include <sys/intr.h>
82 #include <sys/atomic.h>
83 #include <sys/pcq.h>
84 #include <sys/vnode.h>
85 #include <sys/kauth.h>
86 #include <sys/module.h>
87 
88 #include <dev/midi_if.h>
89 #include <dev/midivar.h>
90 #include <dev/sequencervar.h>
91 
92 #include "ioconf.h"
93 
94 /*
95  * XXX Kludge.  This module uses midi_cd, and depends on the `midi'
96  * module, but there's no obvious way to get midi_cd declared in
97  * ioconf.h without actually pulling MIDI into the module in
98  * sys/modules/sequencer/sequencer.ioconf.  Please fix me!
99  *
100  * XXX XXX XXX Apparently sequencer.ioconf doesn't actually make the
101  * sequencer cdev!  Did this ever work?
102  *
103  * XXX XXX XXX Apparently there are even some kernels that include a
104  * sequencer pseudo-device but exclude any midi device.  How do they
105  * even link??
106  */
107 extern struct cfdriver midi_cd;
108 #ifdef _MODULE
109 extern struct cfdriver sequencer_cd;
110 #endif
111 
112 #define ADDTIMEVAL(a, b) ( \
113 	(a)->tv_sec += (b)->tv_sec, \
114 	(a)->tv_usec += (b)->tv_usec, \
115 	(a)->tv_usec > 1000000 ? ((a)->tv_sec++, (a)->tv_usec -= 1000000) : 0\
116 	)
117 
118 #define SUBTIMEVAL(a, b) ( \
119 	(a)->tv_sec -= (b)->tv_sec, \
120 	(a)->tv_usec -= (b)->tv_usec, \
121 	(a)->tv_usec < 0 ? ((a)->tv_sec--, (a)->tv_usec += 1000000) : 0\
122 	)
123 
124 #ifdef AUDIO_DEBUG
125 #define DPRINTF(x)	if (sequencerdebug) printf x
126 #define DPRINTFN(n,x)	if (sequencerdebug >= (n)) printf x
127 int	sequencerdebug = 0;
128 #else
129 #define DPRINTF(x)
130 #define DPRINTFN(n,x)
131 #endif
132 
133 #define SEQ_NOTE_MAX 128
134 #define SEQ_NOTE_XXX 255
135 
136 #define RECALC_USPERDIV(t) \
137 ((t)->usperdiv = 60*1000000L/((t)->tempo_beatpermin*(t)->timebase_divperbeat))
138 
139 typedef union sequencer_pcqitem {
140 	void	*qi_ptr;
141 	char	qi_msg[4];
142 } sequencer_pcqitem_t;
143 
144 static void seq_reset(struct sequencer_softc *);
145 static int seq_do_command(struct sequencer_softc *, seq_event_t *);
146 static int seq_do_chnvoice(struct sequencer_softc *, seq_event_t *);
147 static int seq_do_chncommon(struct sequencer_softc *, seq_event_t *);
148 static void seq_timer_waitabs(struct sequencer_softc *, uint32_t);
149 static int seq_do_timing(struct sequencer_softc *, seq_event_t *);
150 static int seq_do_local(struct sequencer_softc *, seq_event_t *);
151 static int seq_do_sysex(struct sequencer_softc *, seq_event_t *);
152 static int seq_do_fullsize(struct sequencer_softc *, seq_event_t *, struct uio *);
153 static int seq_input_event(struct sequencer_softc *, seq_event_t *);
154 static int seq_drain(struct sequencer_softc *);
155 static void seq_startoutput(struct sequencer_softc *);
156 static void seq_timeout(void *);
157 static int seq_to_new(seq_event_t *, struct uio *);
158 static void seq_softintr(void *);
159 
160 static int midiseq_out(struct midi_dev *, u_char *, u_int, int);
161 static struct midi_dev *midiseq_open(int, int);
162 static void midiseq_close(struct midi_dev *);
163 static void midiseq_reset(struct midi_dev *);
164 static int midiseq_noteon(struct midi_dev *, int, int, seq_event_t *);
165 static int midiseq_noteoff(struct midi_dev *, int, int, seq_event_t *);
166 static int midiseq_keypressure(struct midi_dev *, int, int, seq_event_t *);
167 static int midiseq_pgmchange(struct midi_dev *, int, seq_event_t *);
168 static int midiseq_chnpressure(struct midi_dev *, int, seq_event_t *);
169 static int midiseq_ctlchange(struct midi_dev *, int, seq_event_t *);
170 static int midiseq_pitchbend(struct midi_dev *, int, seq_event_t *);
171 static int midiseq_loadpatch(struct midi_dev *, struct sysex_info *, struct uio *);
172 void midiseq_in(struct midi_dev *, u_char *, int);
173 
174 static dev_type_open(sequenceropen);
175 static dev_type_close(sequencerclose);
176 static dev_type_read(sequencerread);
177 static dev_type_write(sequencerwrite);
178 static dev_type_ioctl(sequencerioctl);
179 static dev_type_poll(sequencerpoll);
180 static dev_type_kqfilter(sequencerkqfilter);
181 
182 const struct cdevsw sequencer_cdevsw = {
183 	.d_open = sequenceropen,
184 	.d_close = sequencerclose,
185 	.d_read = sequencerread,
186 	.d_write = sequencerwrite,
187 	.d_ioctl = sequencerioctl,
188 	.d_stop = nostop,
189 	.d_tty = notty,
190 	.d_poll = sequencerpoll,
191 	.d_mmap = nommap,
192 	.d_kqfilter = sequencerkqfilter,
193 	.d_discard = nodiscard,
194 	.d_flag = D_OTHER | D_MPSAFE
195 };
196 static LIST_HEAD(, sequencer_softc) sequencers = LIST_HEAD_INITIALIZER(sequencers);
197 static kmutex_t sequencer_lock;
198 
199 static void
200 sequencerdestroy(struct sequencer_softc *sc)
201 {
202 	callout_halt(&sc->sc_callout, &sc->lock);
203 	callout_destroy(&sc->sc_callout);
204 	softint_disestablish(sc->sih);
205 	cv_destroy(&sc->rchan);
206 	cv_destroy(&sc->wchan);
207 	cv_destroy(&sc->lchan);
208 	if (sc->pcq)
209 		pcq_destroy(sc->pcq);
210 	kmem_free(sc, sizeof(*sc));
211 }
212 
213 static struct sequencer_softc *
214 sequencercreate(int unit)
215 {
216 	struct sequencer_softc *sc = kmem_zalloc(sizeof(*sc), KM_SLEEP);
217 	sc->sc_unit = unit;
218 	callout_init(&sc->sc_callout, CALLOUT_MPSAFE);
219 	sc->sih = softint_establish(SOFTINT_NET | SOFTINT_MPSAFE,
220 	    seq_softintr, sc);
221 	mutex_init(&sc->lock, MUTEX_DEFAULT, IPL_NONE);
222 	cv_init(&sc->rchan, "midiseqr");
223 	cv_init(&sc->wchan, "midiseqw");
224 	cv_init(&sc->lchan, "midiseql");
225 	sc->pcq = pcq_create(SEQ_MAXQ, KM_SLEEP);
226 	if (sc->pcq == NULL) {
227 		sequencerdestroy(sc);
228 		return NULL;
229 	}
230 	return sc;
231 }
232 
233 
234 static struct sequencer_softc *
235 sequencerget(int unit)
236 {
237 	struct sequencer_softc *sc;
238 	if (unit < 0) {
239 #ifdef DIAGNOSTIC
240 		panic("%s: unit %d!", __func__, unit);
241 #endif
242 		return NULL;
243 	}
244 	mutex_enter(&sequencer_lock);
245 	LIST_FOREACH(sc, &sequencers, sc_link) {
246 		if (sc->sc_unit == unit) {
247 			mutex_exit(&sequencer_lock);
248 			return sc;
249 		}
250 	}
251 	mutex_exit(&sequencer_lock);
252 	if ((sc = sequencercreate(unit)) == NULL)
253 		return NULL;
254 	mutex_enter(&sequencer_lock);
255 	LIST_INSERT_HEAD(&sequencers, sc, sc_link);
256 	mutex_exit(&sequencer_lock);
257 	return sc;
258 }
259 
260 #ifdef notyet
261 static void
262 sequencerput(struct sequencer_softc *sc)
263 {
264 	mutex_enter(&sequencer_lock);
265 	LIST_REMOVE(sc, sc_link);
266 	mutex_exit(&sequencer_lock);
267 	sequencerdestroy(sc);
268 }
269 #endif
270 
271 void
272 sequencerattach(int n)
273 {
274 	mutex_init(&sequencer_lock, MUTEX_DEFAULT, IPL_NONE);
275 }
276 
277 /*
278  * Release reference to device acquired with sequencer_enter().
279  */
280 static void
281 sequencer_exit(struct sequencer_softc *sc)
282 {
283 
284 	sc->dvlock--;
285 	cv_broadcast(&sc->lchan);
286 	mutex_exit(&sc->lock);
287 }
288 
289 /*
290  * Look up sequencer device and acquire locks for device access.
291  */
292 static int
293 sequencer_enter(dev_t dev, struct sequencer_softc **scp)
294 {
295 	struct sequencer_softc *sc;
296 
297 	/* First, find the device and take sc_lock. */
298 	if ((sc = sequencerget(SEQUENCERUNIT(dev))) == NULL)
299 		return ENXIO;
300 	mutex_enter(&sc->lock);
301 	while (sc->dvlock) {
302 		cv_wait(&sc->lchan, &sc->lock);
303 	}
304 	sc->dvlock++;
305 	if (sc->dying) {
306 		sequencer_exit(sc);
307 		return EIO;
308 	}
309 	*scp = sc;
310 	return 0;
311 }
312 
313 static int
314 sequenceropen(dev_t dev, int flags, int ifmt, struct lwp *l)
315 {
316 	struct sequencer_softc *sc;
317 	struct midi_dev *md;
318 	struct midi_softc *msc;
319 	int error, unit, mdno;
320 
321 	DPRINTF(("sequenceropen\n"));
322 
323 	if ((error = sequencer_enter(dev, &sc)) != 0)
324 		return error;
325 	if (sc->isopen != 0) {
326 		sequencer_exit(sc);
327 		return EBUSY;
328 	}
329 
330 	if (SEQ_IS_OLD(SEQUENCERUNIT(dev)))
331 		sc->mode = SEQ_OLD;
332 	else
333 		sc->mode = SEQ_NEW;
334 	sc->isopen++;
335 	sc->flags = flags & (FREAD|FWRITE);
336 	sc->pbus = 0;
337 	sc->async = 0;
338 	sc->input_stamp = ~0;
339 
340 	sc->nmidi = 0;
341 	sc->ndevs = midi_unit_count();
342 	sc->timer.timebase_divperbeat = 100;
343 	sc->timer.tempo_beatpermin = 60;
344 	RECALC_USPERDIV(&sc->timer);
345 	sc->timer.divs_lastevent = sc->timer.divs_lastchange = 0;
346 	microtime(&sc->timer.reftime);
347 
348 	SEQ_QINIT(&sc->inq);
349 	SEQ_QINIT(&sc->outq);
350 	sc->lowat = SEQ_MAXQ / 2;
351 
352 	if (sc->ndevs > 0) {
353 		mutex_exit(&sc->lock);
354 		sc->devs = kmem_alloc(sc->ndevs * sizeof(struct midi_dev *),
355 		    KM_SLEEP);
356 		for (unit = 0; unit < sc->ndevs; unit++) {
357 			md = midiseq_open(unit, flags);
358 			if (md) {
359 				sc->devs[sc->nmidi++] = md;
360 				md->seq = sc;
361 				md->doingsysex = 0;
362 				DPRINTF(("%s: midi unit %d opened as seq %p\n",
363 				    __func__, unit, md));
364 			} else {
365 				DPRINTF(("%s: midi unit %d not opened as seq\n",
366 				    __func__, unit));
367 			}
368 		}
369 		mutex_enter(&sc->lock);
370 	} else {
371 		sc->devs = NULL;
372 	}
373 
374 	/* Only now redirect input from MIDI devices. */
375 	for (mdno = 0; mdno < sc->nmidi; mdno++) {
376 		msc = device_lookup_private(&midi_cd, sc->devs[mdno]->unit);
377 		if (msc) {
378 			mutex_enter(msc->lock);
379 			msc->seqopen = 1;
380 			mutex_exit(msc->lock);
381 		}
382 	}
383 
384 	seq_reset(sc);
385 	sequencer_exit(sc);
386 
387 	DPRINTF(("%s: mode=%d, nmidi=%d\n", __func__, sc->mode, sc->nmidi));
388 	return 0;
389 }
390 
391 static int
392 seq_drain(struct sequencer_softc *sc)
393 {
394 	int error;
395 
396 	KASSERT(mutex_owned(&sc->lock));
397 
398 	DPRINTFN(3, ("seq_drain: %p, len=%d\n", sc, SEQ_QLEN(&sc->outq)));
399 	seq_startoutput(sc);
400 	error = 0;
401 	while (!SEQ_QEMPTY(&sc->outq) && !error)
402 		error = cv_timedwait_sig(&sc->wchan, &sc->lock, 60*hz);
403 	return (error);
404 }
405 
406 static void
407 seq_timeout(void *addr)
408 {
409 	struct sequencer_softc *sc = addr;
410 	proc_t *p;
411 	pid_t pid;
412 
413 	DPRINTFN(4, ("seq_timeout: %p\n", sc));
414 
415 	mutex_enter(&sc->lock);
416 	if (sc->timeout == 0) {
417 		mutex_spin_exit(&sc->lock);
418 		return;
419 	}
420 	sc->timeout = 0;
421 	seq_startoutput(sc);
422 	if (SEQ_QLEN(&sc->outq) >= sc->lowat) {
423 		mutex_exit(&sc->lock);
424 		return;
425 	}
426 	cv_broadcast(&sc->wchan);
427 	selnotify(&sc->wsel, 0, NOTE_SUBMIT);
428 	if ((pid = sc->async) != 0) {
429 		mutex_enter(proc_lock);
430 		if ((p = proc_find(pid)) != NULL)
431 			psignal(p, SIGIO);
432 		mutex_exit(proc_lock);
433 	}
434 	mutex_exit(&sc->lock);
435 }
436 
437 static void
438 seq_startoutput(struct sequencer_softc *sc)
439 {
440 	struct sequencer_queue *q = &sc->outq;
441 	seq_event_t cmd;
442 
443 	KASSERT(mutex_owned(&sc->lock));
444 
445 	if (sc->timeout)
446 		return;
447 	DPRINTFN(4, ("seq_startoutput: %p, len=%d\n", sc, SEQ_QLEN(q)));
448 	while (!SEQ_QEMPTY(q) && !sc->timeout) {
449 		SEQ_QGET(q, cmd);
450 		seq_do_command(sc, &cmd);
451 	}
452 }
453 
454 static int
455 sequencerclose(dev_t dev, int flags, int ifmt, struct lwp *l)
456 {
457 	struct sequencer_softc *sc;
458 	struct midi_softc *msc;
459 	int unit, error;
460 
461 	DPRINTF(("%s: %"PRIx64"\n", __func__, dev));
462 
463 	if ((error = sequencer_enter(dev, &sc)) != 0)
464 		return error;
465 	seq_drain(sc);
466 	if (sc->timeout) {
467 		callout_halt(&sc->sc_callout, &sc->lock);
468 		sc->timeout = 0;
469 	}
470 	/* Bin input from MIDI devices. */
471 	for (unit = 0; unit < sc->nmidi; unit++) {
472 		msc = device_lookup_private(&midi_cd, unit);
473 		if (msc) {
474 			mutex_enter(msc->lock);
475 			msc->seqopen = 0;
476 			mutex_exit(msc->lock);
477 		}
478 	}
479 	mutex_exit(&sc->lock);
480 
481 	for (unit = 0; unit < sc->nmidi; unit++)
482 		if (sc->devs[unit] != NULL)
483 			midiseq_close(sc->devs[unit]);
484 	if (sc->devs != NULL) {
485 		KASSERT(sc->ndevs > 0);
486 		kmem_free(sc->devs, sc->ndevs * sizeof(struct midi_dev *));
487 		sc->devs = NULL;
488 	}
489 
490 	mutex_enter(&sc->lock);
491 	sc->isopen = 0;
492 	sequencer_exit(sc);
493 
494 	DPRINTF(("%s: %"PRIx64" done\n", __func__, dev));
495 
496 	return (0);
497 }
498 
499 static int
500 seq_input_event(struct sequencer_softc *sc, seq_event_t *cmd)
501 {
502 	struct sequencer_queue *q;
503 
504 	KASSERT(mutex_owned(&sc->lock));
505 
506 	DPRINTFN(2, ("seq_input_event: %02x %02x %02x %02x %02x "
507 	    "%02x %02x %02x\n", cmd->tag,
508 	    cmd->unknown.byte[0], cmd->unknown.byte[1],
509 	    cmd->unknown.byte[2], cmd->unknown.byte[3],
510 	    cmd->unknown.byte[4], cmd->unknown.byte[5],
511 	    cmd->unknown.byte[6]));
512 	q = &sc->inq;
513 	if (SEQ_QFULL(q))
514 		return (ENOMEM);
515 	SEQ_QPUT(q, *cmd);
516 	cv_broadcast(&sc->rchan);
517 	selnotify(&sc->rsel, 0, NOTE_SUBMIT);
518 	if (sc->async != 0) {
519 		proc_t *p;
520 
521 		mutex_enter(proc_lock);
522 		if ((p = proc_find(sc->async)) != NULL)
523 			psignal(p, SIGIO);
524 		mutex_exit(proc_lock);
525 	}
526 	return 0;
527 }
528 
529 static void
530 seq_softintr(void *addr)
531 {
532 	struct sequencer_softc *sc;
533 	struct timeval now;
534 	seq_event_t ev;
535 	int status, chan, unit;
536 	sequencer_pcqitem_t qi;
537 	u_long t;
538 
539 	sc = addr;
540 
541 	mutex_enter(&sc->lock);
542 
543 	qi.qi_ptr = pcq_get(sc->pcq);
544 	if (qi.qi_ptr == NULL) {
545 		mutex_exit(&sc->lock);
546 		return;
547 	}
548 	KASSERT((qi.qi_msg[3] & 0x80) != 0);
549 	unit = qi.qi_msg[3] & ~0x80;
550 	status = MIDI_GET_STATUS(qi.qi_msg[0]);
551 	chan = MIDI_GET_CHAN(qi.qi_msg[0]);
552 	switch (status) {
553 	case MIDI_NOTEON: /* midi(4) always canonicalizes hidden note-off */
554 		ev = SEQ_MK_CHN(NOTEON, .device=unit, .channel=chan,
555 		    .key=qi.qi_msg[1], .velocity=qi.qi_msg[2]);
556 		break;
557 	case MIDI_NOTEOFF:
558 		ev = SEQ_MK_CHN(NOTEOFF, .device=unit, .channel=chan,
559 		    .key=qi.qi_msg[1], .velocity=qi.qi_msg[2]);
560 		break;
561 	case MIDI_KEY_PRESSURE:
562 		ev = SEQ_MK_CHN(KEY_PRESSURE, .device=unit, .channel=chan,
563 		    .key=qi.qi_msg[1], .pressure=qi.qi_msg[2]);
564 		break;
565 	case MIDI_CTL_CHANGE: /* XXX not correct for MSB */
566 		ev = SEQ_MK_CHN(CTL_CHANGE, .device=unit, .channel=chan,
567 		    .controller=qi.qi_msg[1], .value=qi.qi_msg[2]);
568 		break;
569 	case MIDI_PGM_CHANGE:
570 		ev = SEQ_MK_CHN(PGM_CHANGE, .device=unit, .channel=chan,
571 		    .program=qi.qi_msg[1]);
572 		break;
573 	case MIDI_CHN_PRESSURE:
574 		ev = SEQ_MK_CHN(CHN_PRESSURE, .device=unit, .channel=chan,
575 		    .pressure=qi.qi_msg[1]);
576 		break;
577 	case MIDI_PITCH_BEND:
578 		ev = SEQ_MK_CHN(PITCH_BEND, .device=unit, .channel=chan,
579 		    .value=(qi.qi_msg[1] & 0x7f) | ((qi.qi_msg[2] & 0x7f) << 7));
580 		break;
581 	default: /* this is now the point where MIDI_ACKs disappear */
582 		mutex_exit(&sc->lock);
583 		return;
584 	}
585 	microtime(&now);
586 	if (!sc->timer.running)
587 		now = sc->timer.stoptime;
588 	SUBTIMEVAL(&now, &sc->timer.reftime);
589 	t = now.tv_sec * 1000000 + now.tv_usec;
590 	t /= sc->timer.usperdiv;
591 	t += sc->timer.divs_lastchange;
592 	if (t != sc->input_stamp) {
593 		seq_input_event(sc, &SEQ_MK_TIMING(WAIT_ABS, .divisions=t));
594 		sc->input_stamp = t; /* XXX what happens if timer is reset? */
595 	}
596 	seq_input_event(sc, &ev);
597 	mutex_exit(&sc->lock);
598 }
599 
600 static int
601 sequencerread(dev_t dev, struct uio *uio, int ioflag)
602 {
603 	struct sequencer_softc *sc;
604 	struct sequencer_queue *q;
605 	seq_event_t ev;
606 	int error;
607 
608 	DPRINTFN(2, ("sequencerread: %"PRIx64", count=%d, ioflag=%x\n",
609 	   dev, (int)uio->uio_resid, ioflag));
610 
611 	if ((error = sequencer_enter(dev, &sc)) != 0)
612 		return error;
613 	q = &sc->inq;
614 
615 	if (sc->mode == SEQ_OLD) {
616 		sequencer_exit(sc);
617 		DPRINTFN(-1,("sequencerread: old read\n"));
618 		return EINVAL; /* XXX unimplemented */
619 	}
620 	while (SEQ_QEMPTY(q)) {
621 		if (ioflag & IO_NDELAY) {
622 			error = EWOULDBLOCK;
623 			break;
624 		}
625 		/* Drop lock to allow concurrent read/write. */
626 		KASSERT(sc->dvlock != 0);
627 		sc->dvlock--;
628 		error = cv_wait_sig(&sc->rchan, &sc->lock);
629 		while (sc->dvlock != 0) {
630 			cv_wait(&sc->lchan, &sc->lock);
631 		}
632 		sc->dvlock++;
633 		if (error) {
634 			break;
635 		}
636 	}
637 	while (uio->uio_resid >= sizeof(ev) && !error && !SEQ_QEMPTY(q)) {
638 		SEQ_QGET(q, ev);
639 		mutex_exit(&sc->lock);
640 		error = uiomove(&ev, sizeof(ev), uio);
641 		mutex_enter(&sc->lock);
642 	}
643 	sequencer_exit(sc);
644 	return error;
645 }
646 
647 static int
648 sequencerwrite(dev_t dev, struct uio *uio, int ioflag)
649 {
650 	struct sequencer_softc *sc;
651 	struct sequencer_queue *q;
652 	int error;
653 	seq_event_t cmdbuf;
654 	int size;
655 
656 	DPRINTFN(2, ("sequencerwrite: %"PRIx64", count=%d\n", dev,
657 	    (int)uio->uio_resid));
658 
659 	if ((error = sequencer_enter(dev, &sc)) != 0)
660 		return error;
661 	q = &sc->outq;
662 
663 	size = sc->mode == SEQ_NEW ? sizeof cmdbuf : SEQOLD_CMDSIZE;
664 	while (uio->uio_resid >= size && error == 0) {
665 		mutex_exit(&sc->lock);
666 		error = uiomove(&cmdbuf, size, uio);
667 		if (error == 0) {
668 			if (sc->mode == SEQ_OLD && seq_to_new(&cmdbuf, uio)) {
669 				mutex_enter(&sc->lock);
670 				continue;
671 			}
672 			if (cmdbuf.tag == SEQ_FULLSIZE) {
673 				/* We do it like OSS does, asynchronously */
674 				error = seq_do_fullsize(sc, &cmdbuf, uio);
675 				if (error == 0) {
676 					mutex_enter(&sc->lock);
677 					continue;
678 				}
679 			}
680 		}
681 		mutex_enter(&sc->lock);
682 		if (error != 0) {
683 			break;
684 		}
685 		while (SEQ_QFULL(q)) {
686 			seq_startoutput(sc);
687 			if (SEQ_QFULL(q)) {
688 				if (ioflag & IO_NDELAY) {
689 					error = EWOULDBLOCK;
690 					break;
691 				}
692 				error = cv_wait_sig(&sc->wchan, &sc->lock);
693 				if (error) {
694 					 break;
695 				}
696 			}
697 		}
698 		if (error == 0) {
699 			SEQ_QPUT(q, cmdbuf);
700 		}
701 	}
702 	if (error == 0) {
703 		seq_startoutput(sc);
704 	} else {
705 		DPRINTFN(2, ("sequencerwrite: error=%d\n", error));
706 	}
707 	sequencer_exit(sc);
708 	return error;
709 }
710 
711 static int
712 sequencerioctl(dev_t dev, u_long cmd, void *addr, int flag, struct lwp *l)
713 {
714 	struct sequencer_softc *sc;
715 	struct synth_info *si;
716 	struct midi_dev *md;
717 	int devno, error, t;
718 	struct timeval now;
719 	u_long tx;
720 
721 	DPRINTFN(2, ("sequencerioctl: %"PRIx64" cmd=0x%08lx\n", dev, cmd));
722 
723 	if ((error = sequencer_enter(dev, &sc)) != 0)
724 		return error;
725 	switch (cmd) {
726 	case FIONBIO:
727 		/* All handled in the upper FS layer. */
728 		break;
729 
730 	case FIOASYNC:
731 		if (*(int *)addr) {
732 			if (sc->async != 0)
733 				return EBUSY;
734 			sc->async = curproc->p_pid;
735 			DPRINTF(("%s: FIOASYNC %d\n", __func__,
736 			    sc->async));
737 		} else {
738 			sc->async = 0;
739 		}
740 		break;
741 
742 	case SEQUENCER_RESET:
743 		seq_reset(sc);
744 		break;
745 
746 	case SEQUENCER_PANIC:
747 		seq_reset(sc);
748 		/* Do more?  OSS doesn't */
749 		break;
750 
751 	case SEQUENCER_SYNC:
752 		if (sc->flags != FREAD)
753 			seq_drain(sc);
754 		break;
755 
756 	case SEQUENCER_INFO:
757 		si = (struct synth_info*)addr;
758 		devno = si->device;
759 		if (devno < 0 || devno >= sc->nmidi) {
760 			error = EINVAL;
761 			break;
762 		}
763 		md = sc->devs[devno];
764 		strncpy(si->name, md->name, sizeof si->name);
765 		si->synth_type = SYNTH_TYPE_MIDI;
766 		si->synth_subtype = md->subtype;
767 		si->nr_voices = md->nr_voices;
768 		si->instr_bank_size = md->instr_bank_size;
769 		si->capabilities = md->capabilities;
770 		break;
771 
772 	case SEQUENCER_NRSYNTHS:
773 		*(int *)addr = sc->nmidi;
774 		break;
775 
776 	case SEQUENCER_NRMIDIS:
777 		*(int *)addr = sc->nmidi;
778 		break;
779 
780 	case SEQUENCER_OUTOFBAND:
781 		DPRINTFN(3, ("sequencer_ioctl: OOB=%02x %02x %02x %02x %02x %02x %02x %02x\n",
782 		    *(u_char *)addr, *((u_char *)addr+1),
783 		    *((u_char *)addr+2), *((u_char *)addr+3),
784 		    *((u_char *)addr+4), *((u_char *)addr+5),
785 		    *((u_char *)addr+6), *((u_char *)addr+7)));
786 		if ((sc->flags & FWRITE) == 0) {
787 			error = EBADF;
788 		} else {
789 			error = seq_do_command(sc, (seq_event_t *)addr);
790 		}
791 		break;
792 
793 	case SEQUENCER_TMR_TIMEBASE:
794 		t = *(int *)addr;
795 		if (t < 1)
796 			t = 1;
797 		if (t > 10000)
798 			t = 10000;
799 		*(int *)addr = t;
800 		sc->timer.timebase_divperbeat = t;
801 		sc->timer.divs_lastchange = sc->timer.divs_lastevent;
802 		microtime(&sc->timer.reftime);
803 		RECALC_USPERDIV(&sc->timer);
804 		break;
805 
806 	case SEQUENCER_TMR_START:
807 		error = seq_do_timing(sc, &SEQ_MK_TIMING(START));
808 		break;
809 
810 	case SEQUENCER_TMR_STOP:
811 		error = seq_do_timing(sc, &SEQ_MK_TIMING(STOP));
812 		break;
813 
814 	case SEQUENCER_TMR_CONTINUE:
815 		error = seq_do_timing(sc, &SEQ_MK_TIMING(CONTINUE));
816 		break;
817 
818 	case SEQUENCER_TMR_TEMPO:
819 		error = seq_do_timing(sc,
820 		    &SEQ_MK_TIMING(TEMPO, .bpm=*(int *)addr));
821 		RECALC_USPERDIV(&sc->timer);
822 		if (error == 0)
823 			*(int *)addr = sc->timer.tempo_beatpermin;
824 		break;
825 
826 	case SEQUENCER_TMR_SOURCE:
827 		*(int *)addr = SEQUENCER_TMR_INTERNAL;
828 		break;
829 
830 	case SEQUENCER_TMR_METRONOME:
831 		/* noop */
832 		break;
833 
834 	case SEQUENCER_THRESHOLD:
835 		t = SEQ_MAXQ - *(int *)addr / sizeof (seq_event_rec);
836 		if (t < 1)
837 			t = 1;
838 		if (t > SEQ_MAXQ)
839 			t = SEQ_MAXQ;
840 		sc->lowat = t;
841 		break;
842 
843 	case SEQUENCER_CTRLRATE:
844 		*(int *)addr = (sc->timer.tempo_beatpermin
845 		    *sc->timer.timebase_divperbeat + 30) / 60;
846 		break;
847 
848 	case SEQUENCER_GETTIME:
849 		microtime(&now);
850 		SUBTIMEVAL(&now, &sc->timer.reftime);
851 		tx = now.tv_sec * 1000000 + now.tv_usec;
852 		tx /= sc->timer.usperdiv;
853 		tx += sc->timer.divs_lastchange;
854 		*(int *)addr = tx;
855 		break;
856 
857 	default:
858 		DPRINTFN(-1,("sequencer_ioctl: unimpl %08lx\n", cmd));
859 		error = EINVAL;
860 		break;
861 	}
862 	sequencer_exit(sc);
863 
864 	return error;
865 }
866 
867 static int
868 sequencerpoll(dev_t dev, int events, struct lwp *l)
869 {
870 	struct sequencer_softc *sc;
871 	int revents = 0;
872 	if ((sc = sequencerget(SEQUENCERUNIT(dev))) == NULL)
873 		return ENXIO;
874 
875 	DPRINTF(("%s: %p events=0x%x\n", __func__, sc, events));
876 
877 	mutex_enter(&sc->lock);
878 	if (events & (POLLIN | POLLRDNORM))
879 		if ((sc->flags&FREAD) && !SEQ_QEMPTY(&sc->inq))
880 			revents |= events & (POLLIN | POLLRDNORM);
881 
882 	if (events & (POLLOUT | POLLWRNORM))
883 		if ((sc->flags&FWRITE) && SEQ_QLEN(&sc->outq) < sc->lowat)
884 			revents |= events & (POLLOUT | POLLWRNORM);
885 
886 	if (revents == 0) {
887 		if ((sc->flags&FREAD) && (events & (POLLIN | POLLRDNORM)))
888 			selrecord(l, &sc->rsel);
889 
890 		if ((sc->flags&FWRITE) && (events & (POLLOUT | POLLWRNORM)))
891 			selrecord(l, &sc->wsel);
892 	}
893 	mutex_exit(&sc->lock);
894 
895 	return revents;
896 }
897 
898 static void
899 filt_sequencerrdetach(struct knote *kn)
900 {
901 	struct sequencer_softc *sc = kn->kn_hook;
902 
903 	mutex_enter(&sc->lock);
904 	SLIST_REMOVE(&sc->rsel.sel_klist, kn, knote, kn_selnext);
905 	mutex_exit(&sc->lock);
906 }
907 
908 static int
909 filt_sequencerread(struct knote *kn, long hint)
910 {
911 	struct sequencer_softc *sc = kn->kn_hook;
912 	int rv;
913 
914 	if (hint != NOTE_SUBMIT) {
915 		mutex_enter(&sc->lock);
916 	}
917 	if (SEQ_QEMPTY(&sc->inq)) {
918 		rv = 0;
919 	} else {
920 		kn->kn_data = sizeof(seq_event_rec);
921 		rv = 1;
922 	}
923 	if (hint != NOTE_SUBMIT) {
924 		mutex_exit(&sc->lock);
925 	}
926 	return rv;
927 }
928 
929 static const struct filterops sequencerread_filtops = {
930 	.f_isfd = 1,
931 	.f_attach = NULL,
932 	.f_detach = filt_sequencerrdetach,
933 	.f_event = filt_sequencerread,
934 };
935 
936 static void
937 filt_sequencerwdetach(struct knote *kn)
938 {
939 	struct sequencer_softc *sc = kn->kn_hook;
940 
941 	mutex_enter(&sc->lock);
942 	SLIST_REMOVE(&sc->wsel.sel_klist, kn, knote, kn_selnext);
943 	mutex_exit(&sc->lock);
944 }
945 
946 static int
947 filt_sequencerwrite(struct knote *kn, long hint)
948 {
949 	struct sequencer_softc *sc = kn->kn_hook;
950 	int rv;
951 
952 	if (hint != NOTE_SUBMIT) {
953 		mutex_enter(&sc->lock);
954 	}
955 	if (SEQ_QLEN(&sc->outq) >= sc->lowat) {
956 		rv = 0;
957 	} else {
958 		kn->kn_data = sizeof(seq_event_rec);
959 		rv = 1;
960 	}
961 	if (hint != NOTE_SUBMIT) {
962 		mutex_exit(&sc->lock);
963 	}
964 	return rv;
965 }
966 
967 static const struct filterops sequencerwrite_filtops = {
968 	.f_isfd = 1,
969 	.f_attach = NULL,
970 	.f_detach = filt_sequencerwdetach,
971 	.f_event = filt_sequencerwrite,
972 };
973 
974 static int
975 sequencerkqfilter(dev_t dev, struct knote *kn)
976 {
977 	struct sequencer_softc *sc;
978 	struct klist *klist;
979 	if ((sc = sequencerget(SEQUENCERUNIT(dev))) == NULL)
980 		return ENXIO;
981 
982 	switch (kn->kn_filter) {
983 	case EVFILT_READ:
984 		klist = &sc->rsel.sel_klist;
985 		kn->kn_fop = &sequencerread_filtops;
986 		break;
987 
988 	case EVFILT_WRITE:
989 		klist = &sc->wsel.sel_klist;
990 		kn->kn_fop = &sequencerwrite_filtops;
991 		break;
992 
993 	default:
994 		return (EINVAL);
995 	}
996 
997 	kn->kn_hook = sc;
998 
999 	mutex_enter(&sc->lock);
1000 	SLIST_INSERT_HEAD(klist, kn, kn_selnext);
1001 	mutex_exit(&sc->lock);
1002 
1003 	return (0);
1004 }
1005 
1006 static void
1007 seq_reset(struct sequencer_softc *sc)
1008 {
1009 	int i, chn;
1010 	struct midi_dev *md;
1011 
1012 	KASSERT(mutex_owned(&sc->lock));
1013 
1014 	if (!(sc->flags & FWRITE))
1015 	        return;
1016 	for (i = 0; i < sc->nmidi; i++) {
1017 		md = sc->devs[i];
1018 		midiseq_reset(md);
1019 		for (chn = 0; chn < MAXCHAN; chn++) {
1020 			midiseq_ctlchange(md, chn, &SEQ_MK_CHN(CTL_CHANGE,
1021 			    .controller=MIDI_CTRL_NOTES_OFF));
1022 			midiseq_ctlchange(md, chn, &SEQ_MK_CHN(CTL_CHANGE,
1023 			    .controller=MIDI_CTRL_RESET));
1024 			midiseq_pitchbend(md, chn, &SEQ_MK_CHN(PITCH_BEND,
1025 			    .value=MIDI_BEND_NEUTRAL));
1026 		}
1027 	}
1028 }
1029 
1030 static int
1031 seq_do_command(struct sequencer_softc *sc, seq_event_t *b)
1032 {
1033 	int dev;
1034 
1035 	KASSERT(mutex_owned(&sc->lock));
1036 
1037 	DPRINTFN(4, ("seq_do_command: %p cmd=0x%02x\n", sc, b->timing.op));
1038 
1039 	switch(b->tag) {
1040 	case SEQ_LOCAL:
1041 		return seq_do_local(sc, b);
1042 	case SEQ_TIMING:
1043 		return seq_do_timing(sc, b);
1044 	case SEQ_CHN_VOICE:
1045 		return seq_do_chnvoice(sc, b);
1046 	case SEQ_CHN_COMMON:
1047 		return seq_do_chncommon(sc, b);
1048 	case SEQ_SYSEX:
1049 		return seq_do_sysex(sc, b);
1050 	/* COMPAT */
1051 	case SEQOLD_MIDIPUTC:
1052 		dev = b->putc.device;
1053 		if (dev < 0 || dev >= sc->nmidi)
1054 			return (ENXIO);
1055 		return midiseq_out(sc->devs[dev], &b->putc.byte, 1, 0);
1056 	default:
1057 		DPRINTFN(-1,("seq_do_command: unimpl command %02x\n", b->tag));
1058 		return (EINVAL);
1059 	}
1060 }
1061 
1062 static int
1063 seq_do_chnvoice(struct sequencer_softc *sc, seq_event_t *b)
1064 {
1065 	int dev;
1066 	int error;
1067 	struct midi_dev *md;
1068 
1069 	KASSERT(mutex_owned(&sc->lock));
1070 
1071 	dev = b->voice.device;
1072 	if (dev < 0 || dev >= sc->nmidi ||
1073 	    b->voice.channel > 15 ||
1074 	    b->voice.key >= SEQ_NOTE_MAX)
1075 		return ENXIO;
1076 	md = sc->devs[dev];
1077 	switch(b->voice.op) {
1078 	case MIDI_NOTEON: /* no need to special-case hidden noteoff here */
1079 		error = midiseq_noteon(md, b->voice.channel, b->voice.key, b);
1080 		break;
1081 	case MIDI_NOTEOFF:
1082 		error = midiseq_noteoff(md, b->voice.channel, b->voice.key, b);
1083 		break;
1084 	case MIDI_KEY_PRESSURE:
1085 		error = midiseq_keypressure(md,
1086 		    b->voice.channel, b->voice.key, b);
1087 		break;
1088 	default:
1089 		DPRINTFN(-1,("seq_do_chnvoice: unimpl command %02x\n",
1090 			b->voice.op));
1091 		error = EINVAL;
1092 		break;
1093 	}
1094 	return error;
1095 }
1096 
1097 static int
1098 seq_do_chncommon(struct sequencer_softc *sc, seq_event_t *b)
1099 {
1100 	int dev;
1101 	int error;
1102 	struct midi_dev *md;
1103 
1104 	KASSERT(mutex_owned(&sc->lock));
1105 
1106 	dev = b->common.device;
1107 	if (dev < 0 || dev >= sc->nmidi ||
1108 	    b->common.channel > 15)
1109 		return ENXIO;
1110 	md = sc->devs[dev];
1111 	DPRINTFN(2,("seq_do_chncommon: %02x\n", b->common.op));
1112 
1113 	error = 0;
1114 	switch(b->common.op) {
1115 	case MIDI_PGM_CHANGE:
1116 		error = midiseq_pgmchange(md, b->common.channel, b);
1117 		break;
1118 	case MIDI_CTL_CHANGE:
1119 		error = midiseq_ctlchange(md, b->common.channel, b);
1120 		break;
1121 	case MIDI_PITCH_BEND:
1122 		error = midiseq_pitchbend(md, b->common.channel, b);
1123 		break;
1124 	case MIDI_CHN_PRESSURE:
1125 		error = midiseq_chnpressure(md, b->common.channel, b);
1126 		break;
1127 	default:
1128 		DPRINTFN(-1,("seq_do_chncommon: unimpl command %02x\n",
1129 			b->common.op));
1130 		error = EINVAL;
1131 		break;
1132 	}
1133 	return error;
1134 }
1135 
1136 static int
1137 seq_do_local(struct sequencer_softc *sc, seq_event_t *b)
1138 {
1139 
1140 	KASSERT(mutex_owned(&sc->lock));
1141 
1142 	return (EINVAL);
1143 }
1144 
1145 static int
1146 seq_do_sysex(struct sequencer_softc *sc, seq_event_t *b)
1147 {
1148 	int dev, i;
1149 	struct midi_dev *md;
1150 	uint8_t *bf = b->sysex.buffer;
1151 
1152 	KASSERT(mutex_owned(&sc->lock));
1153 
1154 	dev = b->sysex.device;
1155 	if (dev < 0 || dev >= sc->nmidi)
1156 		return (ENXIO);
1157 	DPRINTF(("%s: dev=%d\n", __func__, dev));
1158 	md = sc->devs[dev];
1159 
1160 	if (!md->doingsysex) {
1161 		midiseq_out(md, (uint8_t[]){MIDI_SYSEX_START}, 1, 0);
1162 		md->doingsysex = 1;
1163 	}
1164 
1165 	for (i = 0; i < 6 && bf[i] != 0xff; i++)
1166 		;
1167 	midiseq_out(md, bf, i, 0);
1168 	if (i < 6 || (i > 0 && bf[i-1] == MIDI_SYSEX_END))
1169 		md->doingsysex = 0;
1170 	return 0;
1171 }
1172 
1173 static void
1174 seq_timer_waitabs(struct sequencer_softc *sc, uint32_t divs)
1175 {
1176 	struct timeval when;
1177 	long long usec;
1178 	struct syn_timer *t;
1179 	int ticks;
1180 
1181 	KASSERT(mutex_owned(&sc->lock));
1182 
1183 	t = &sc->timer;
1184 	t->divs_lastevent = divs;
1185 	divs -= t->divs_lastchange;
1186 	usec = (long long)divs * (long long)t->usperdiv; /* convert to usec */
1187 	when.tv_sec = usec / 1000000;
1188 	when.tv_usec = usec % 1000000;
1189 	DPRINTFN(4, ("seq_timer_waitabs: adjdivs=%d, sleep when=%"PRId64".%06"PRId64,
1190 	             divs, when.tv_sec, (uint64_t)when.tv_usec));
1191 	ADDTIMEVAL(&when, &t->reftime); /* abstime for end */
1192 	ticks = tvhzto(&when);
1193 	DPRINTFN(4, (" when+start=%"PRId64".%06"PRId64", tick=%d\n",
1194 		     when.tv_sec, (uint64_t)when.tv_usec, ticks));
1195 	if (ticks > 0) {
1196 #ifdef DIAGNOSTIC
1197 		if (ticks > 20 * hz) {
1198 			/* Waiting more than 20s */
1199 			printf("seq_timer_waitabs: funny ticks=%d, "
1200 			       "usec=%lld\n", ticks, usec);
1201 		}
1202 #endif
1203 		sc->timeout = 1;
1204 		callout_reset(&sc->sc_callout, ticks,
1205 		    seq_timeout, sc);
1206 	}
1207 #ifdef SEQUENCER_DEBUG
1208 	else if (tick < 0)
1209 		DPRINTF(("%s: ticks = %d\n", __func__, ticks));
1210 #endif
1211 }
1212 
1213 static int
1214 seq_do_timing(struct sequencer_softc *sc, seq_event_t *b)
1215 {
1216 	struct syn_timer *t = &sc->timer;
1217 	struct timeval when;
1218 	int error;
1219 
1220 	KASSERT(mutex_owned(&sc->lock));
1221 
1222 	error = 0;
1223 	switch(b->timing.op) {
1224 	case TMR_WAIT_REL:
1225 		seq_timer_waitabs(sc,
1226 		    b->t_WAIT_REL.divisions + t->divs_lastevent);
1227 		break;
1228 	case TMR_WAIT_ABS:
1229 		seq_timer_waitabs(sc, b->t_WAIT_ABS.divisions);
1230 		break;
1231 	case TMR_START:
1232 		microtime(&t->reftime);
1233 		t->divs_lastevent = t->divs_lastchange = 0;
1234 		t->running = 1;
1235 		break;
1236 	case TMR_STOP:
1237 		microtime(&t->stoptime);
1238 		t->running = 0;
1239 		break;
1240 	case TMR_CONTINUE:
1241 		if (t->running)
1242 			break;
1243 		microtime(&when);
1244 		SUBTIMEVAL(&when, &t->stoptime);
1245 		ADDTIMEVAL(&t->reftime, &when);
1246 		t->running = 1;
1247 		break;
1248 	case TMR_TEMPO:
1249 		/* bpm is unambiguously MIDI clocks per minute / 24 */
1250 		/* (24 MIDI clocks are usually but not always a quarter note) */
1251 		if (b->t_TEMPO.bpm < 8) /* where are these limits specified? */
1252 			t->tempo_beatpermin = 8;
1253 		else if (b->t_TEMPO.bpm > 360) /* ? */
1254 			t->tempo_beatpermin = 360;
1255 		else
1256 			t->tempo_beatpermin = b->t_TEMPO.bpm;
1257 		t->divs_lastchange = t->divs_lastevent;
1258 		microtime(&t->reftime);
1259 		RECALC_USPERDIV(t);
1260 		break;
1261 	case TMR_ECHO:
1262 		error = seq_input_event(sc, b);
1263 		break;
1264 	case TMR_RESET:
1265 		t->divs_lastevent = t->divs_lastchange = 0;
1266 		microtime(&t->reftime);
1267 		break;
1268 	case TMR_SPP:
1269 	case TMR_TIMESIG:
1270 		DPRINTF(("%s: unimplemented %02x\n", __func__, b->timing.op));
1271 		error = EINVAL; /* not quite accurate... */
1272 		break;
1273 	default:
1274 		DPRINTF(("%s: unknown %02x\n", __func__, b->timing.op));
1275 		error = EINVAL;
1276 		break;
1277 	}
1278 	return (error);
1279 }
1280 
1281 static int
1282 seq_do_fullsize(struct sequencer_softc *sc, seq_event_t *b, struct uio *uio)
1283 {
1284 	struct sysex_info sysex;
1285 	u_int dev;
1286 
1287 #ifdef DIAGNOSTIC
1288 	if (sizeof(seq_event_rec) != SEQ_SYSEX_HDRSIZE) {
1289 		printf("seq_do_fullsize: sysex size ??\n");
1290 		return EINVAL;
1291 	}
1292 #endif
1293 	memcpy(&sysex, b, sizeof sysex);
1294 	dev = sysex.device_no;
1295 	if (/* dev < 0 || */ dev >= sc->nmidi)
1296 		return (ENXIO);
1297 	DPRINTFN(2, ("seq_do_fullsize: fmt=%04x, dev=%d, len=%d\n",
1298 		     sysex.key, dev, sysex.len));
1299 	return (midiseq_loadpatch(sc->devs[dev], &sysex, uio));
1300 }
1301 
1302 /*
1303  * Convert an old sequencer event to a new one.
1304  * NOTE: on entry, *ev may contain valid data only in the first 4 bytes.
1305  * That may be true even on exit (!) in the case of SEQOLD_MIDIPUTC; the
1306  * caller will only look at the first bytes in that case anyway. Ugly? Sure.
1307  */
1308 static int
1309 seq_to_new(seq_event_t *ev, struct uio *uio)
1310 {
1311 	int cmd, chan, note, parm;
1312 	uint32_t tmp_delay;
1313 	int error;
1314 	uint8_t *bfp;
1315 
1316 	cmd = ev->tag;
1317 	bfp = ev->unknown.byte;
1318 	chan = *bfp++;
1319 	note = *bfp++;
1320 	parm = *bfp++;
1321 	DPRINTFN(3, ("seq_to_new: 0x%02x %d %d %d\n", cmd, chan, note, parm));
1322 
1323 	if (cmd >= 0x80) {
1324 		/* Fill the event record */
1325 		if (uio->uio_resid >= sizeof *ev - SEQOLD_CMDSIZE) {
1326 			error = uiomove(bfp, sizeof *ev - SEQOLD_CMDSIZE, uio);
1327 			if (error)
1328 				return error;
1329 		} else
1330 			return EINVAL;
1331 	}
1332 
1333 	switch(cmd) {
1334 	case SEQOLD_NOTEOFF:
1335 		/*
1336 		 * What's with the SEQ_NOTE_XXX?  In OSS this seems to have
1337 		 * been undocumented magic for messing with the overall volume
1338 		 * of a 'voice', equated precariously with 'channel' and
1339 		 * pretty much unimplementable except by directly frobbing a
1340 		 * synth chip. For us, who treat everything as interfaced over
1341 		 * MIDI, this will just be unceremoniously discarded as
1342 		 * invalid in midiseq_noteoff, making the whole event an
1343 		 * elaborate no-op, and that doesn't seem to be any different
1344 		 * from what happens on linux with a MIDI-interfaced device,
1345 		 * by the way. The moral is ... use the new /dev/music API, ok?
1346 		 */
1347 		*ev = SEQ_MK_CHN(NOTEOFF, .device=0, .channel=chan,
1348 		    .key=SEQ_NOTE_XXX, .velocity=parm);
1349 		break;
1350 	case SEQOLD_NOTEON:
1351 		*ev = SEQ_MK_CHN(NOTEON,
1352 		    .device=0, .channel=chan, .key=note, .velocity=parm);
1353 		break;
1354 	case SEQOLD_WAIT:
1355 		/*
1356 		 * This event cannot even /exist/ on non-littleendian machines,
1357 		 * and so help me, that's exactly the way OSS defined it.
1358 		 * Also, the OSS programmer's guide states (p. 74, v1.11)
1359 		 * that seqold time units are system clock ticks, unlike
1360 		 * the new 'divisions' which are determined by timebase. In
1361 		 * that case we would need to do scaling here - but no such
1362 		 * behavior is visible in linux either--which also treats this
1363 		 * value, surprisingly, as an absolute, not relative, time.
1364 		 * My guess is that this event has gone unused so long that
1365 		 * nobody could agree we got it wrong no matter what we do.
1366 		 */
1367 		tmp_delay = *(uint32_t *)ev >> 8;
1368 		*ev = SEQ_MK_TIMING(WAIT_ABS, .divisions=tmp_delay);
1369 		break;
1370 	case SEQOLD_SYNCTIMER:
1371 		/*
1372 		 * The TMR_RESET event is not defined in any OSS materials
1373 		 * I can find; it may have been invented here just to provide
1374 		 * an accurate _to_new translation of this event.
1375 		 */
1376 		*ev = SEQ_MK_TIMING(RESET);
1377 		break;
1378 	case SEQOLD_PGMCHANGE:
1379 		*ev = SEQ_MK_CHN(PGM_CHANGE,
1380 		    .device=0, .channel=chan, .program=note);
1381 		break;
1382 	case SEQOLD_MIDIPUTC:
1383 		break;		/* interpret in normal mode */
1384 	case SEQOLD_ECHO:
1385 	case SEQOLD_PRIVATE:
1386 	case SEQOLD_EXTENDED:
1387 	default:
1388 		DPRINTF(("%s: not impl 0x%02x\n", __func__, cmd));
1389 		return EINVAL;
1390 	/* In case new-style events show up */
1391 	case SEQ_TIMING:
1392 	case SEQ_CHN_VOICE:
1393 	case SEQ_CHN_COMMON:
1394 	case SEQ_FULLSIZE:
1395 		break;
1396 	}
1397 	return 0;
1398 }
1399 
1400 /**********************************************/
1401 
1402 void
1403 midiseq_in(struct midi_dev *md, u_char *msg, int len)
1404 {
1405 	struct sequencer_softc *sc;
1406 	sequencer_pcqitem_t qi;
1407 
1408 	DPRINTFN(2, ("midiseq_in: %p %02x %02x %02x\n",
1409 		     md, msg[0], msg[1], msg[2]));
1410 
1411 	sc = md->seq;
1412 
1413 	qi.qi_msg[0] = msg[0];
1414 	qi.qi_msg[1] = msg[1];
1415 	qi.qi_msg[2] = msg[2];
1416 	qi.qi_msg[3] = md->unit | 0x80;	/* ensure non-zero value of qi_ptr */
1417 	pcq_put(sc->pcq, qi.qi_ptr);
1418 	softint_schedule(sc->sih);
1419 }
1420 
1421 static struct midi_dev *
1422 midiseq_open(int unit, int flags)
1423 {
1424 	int error;
1425 	struct midi_dev *md;
1426 	struct midi_softc *sc;
1427 	struct midi_info mi;
1428 	int major;
1429 	dev_t dev;
1430 	vnode_t *vp;
1431 	int oflags;
1432 
1433 	major = devsw_name2chr("midi", NULL, 0);
1434 	dev = makedev(major, unit);
1435 
1436 	DPRINTFN(2, ("midiseq_open: %d %d\n", unit, flags));
1437 
1438 	error = cdevvp(dev, &vp);
1439 	if (error)
1440 		return NULL;
1441 	vn_lock(vp, LK_EXCLUSIVE | LK_RETRY);
1442 	error = VOP_OPEN(vp, flags, kauth_cred_get());
1443 	VOP_UNLOCK(vp);
1444 	if (error) {
1445 		vrele(vp);
1446 		return NULL;
1447 	}
1448 
1449 	/* Only after we have acquired reference via VOP_OPEN(). */
1450 	midi_getinfo(dev, &mi);
1451 	oflags = flags;
1452 	if ((mi.props & MIDI_PROP_CAN_INPUT) == 0)
1453 	        flags &= ~FREAD;
1454 	if ((flags & (FREAD|FWRITE)) == 0) {
1455 		VOP_CLOSE(vp, oflags, kauth_cred_get());
1456 		vrele(vp);
1457 	        return NULL;
1458 	}
1459 
1460 	sc = device_lookup_private(&midi_cd, unit);
1461 	md = kmem_zalloc(sizeof(*md), KM_SLEEP);
1462 	md->unit = unit;
1463 	md->name = mi.name;
1464 	md->subtype = 0;
1465 	md->nr_voices = 128;	/* XXX */
1466 	md->instr_bank_size = 128; /* XXX */
1467 	md->vp = vp;
1468 	if (mi.props & MIDI_PROP_CAN_INPUT)
1469 		md->capabilities |= SYNTH_CAP_INPUT;
1470 	sc->seq_md = md;
1471 	return (md);
1472 }
1473 
1474 static void
1475 midiseq_close(struct midi_dev *md)
1476 {
1477 	DPRINTFN(2, ("midiseq_close: %d\n", md->unit));
1478 	(void)vn_close(md->vp, 0, kauth_cred_get());
1479 	kmem_free(md, sizeof(*md));
1480 }
1481 
1482 static void
1483 midiseq_reset(struct midi_dev *md)
1484 {
1485 	/* XXX send GM reset? */
1486 	DPRINTFN(3, ("midiseq_reset: %d\n", md->unit));
1487 }
1488 
1489 static int
1490 midiseq_out(struct midi_dev *md, u_char *bf, u_int cc, int chk)
1491 {
1492 	DPRINTFN(5, ("midiseq_out: md=%p, unit=%d, bf[0]=0x%02x, cc=%d\n",
1493 		     md, md->unit, bf[0], cc));
1494 
1495 	/* midi(4) does running status compression where appropriate. */
1496 	return midi_writebytes(md->unit, bf, cc);
1497 }
1498 
1499 /*
1500  * If the writing process hands us a hidden note-off in a note-on event,
1501  * we will simply write it that way; no need to special case it here,
1502  * as midi(4) will always canonicalize or compress as appropriate anyway.
1503  */
1504 static int
1505 midiseq_noteon(struct midi_dev *md, int chan, int key, seq_event_t *ev)
1506 {
1507 	return midiseq_out(md, (uint8_t[]){
1508 	    MIDI_NOTEON | chan, key, ev->c_NOTEON.velocity & 0x7f}, 3, 1);
1509 }
1510 
1511 static int
1512 midiseq_noteoff(struct midi_dev *md, int chan, int key, seq_event_t *ev)
1513 {
1514 	return midiseq_out(md, (uint8_t[]){
1515 	    MIDI_NOTEOFF | chan, key, ev->c_NOTEOFF.velocity & 0x7f}, 3, 1);
1516 }
1517 
1518 static int
1519 midiseq_keypressure(struct midi_dev *md, int chan, int key, seq_event_t *ev)
1520 {
1521 	return midiseq_out(md, (uint8_t[]){
1522 	    MIDI_KEY_PRESSURE | chan, key,
1523 	    ev->c_KEY_PRESSURE.pressure & 0x7f}, 3, 1);
1524 }
1525 
1526 static int
1527 midiseq_pgmchange(struct midi_dev *md, int chan, seq_event_t *ev)
1528 {
1529 	if (ev->c_PGM_CHANGE.program > 127)
1530 		return EINVAL;
1531 	return midiseq_out(md, (uint8_t[]){
1532 	    MIDI_PGM_CHANGE | chan, ev->c_PGM_CHANGE.program}, 2, 1);
1533 }
1534 
1535 static int
1536 midiseq_chnpressure(struct midi_dev *md, int chan, seq_event_t *ev)
1537 {
1538 	if (ev->c_CHN_PRESSURE.pressure > 127)
1539 		return EINVAL;
1540 	return midiseq_out(md, (uint8_t[]){
1541 	    MIDI_CHN_PRESSURE | chan, ev->c_CHN_PRESSURE.pressure}, 2, 1);
1542 }
1543 
1544 static int
1545 midiseq_ctlchange(struct midi_dev *md, int chan, seq_event_t *ev)
1546 {
1547 	if (ev->c_CTL_CHANGE.controller > 127)
1548 		return EINVAL;
1549 	return midiseq_out( md, (uint8_t[]){
1550 	    MIDI_CTL_CHANGE | chan, ev->c_CTL_CHANGE.controller,
1551 	    ev->c_CTL_CHANGE.value & 0x7f /* XXX this is SO wrong */
1552 	    }, 3, 1);
1553 }
1554 
1555 static int
1556 midiseq_pitchbend(struct midi_dev *md, int chan, seq_event_t *ev)
1557 {
1558 	return midiseq_out(md, (uint8_t[]){
1559 	    MIDI_PITCH_BEND | chan,
1560 	    ev->c_PITCH_BEND.value & 0x7f,
1561 	    (ev->c_PITCH_BEND.value >> 7) & 0x7f}, 3, 1);
1562 }
1563 
1564 static int
1565 midiseq_loadpatch(struct midi_dev *md,
1566                   struct sysex_info *sysex, struct uio *uio)
1567 {
1568 	struct sequencer_softc *sc;
1569 	u_char c, bf[128];
1570 	int i, cc, error;
1571 
1572 	if (sysex->key != SEQ_SYSEX_PATCH) {
1573 		DPRINTFN(-1,("midiseq_loadpatch: bad patch key 0x%04x\n",
1574 			     sysex->key));
1575 		return (EINVAL);
1576 	}
1577 	if (uio->uio_resid < sysex->len)
1578 		/* adjust length, should be an error */
1579 		sysex->len = uio->uio_resid;
1580 
1581 	DPRINTFN(2, ("midiseq_loadpatch: len=%d\n", sysex->len));
1582 	if (sysex->len == 0)
1583 		return EINVAL;
1584 	error = uiomove(&c, 1, uio);
1585 	if (error)
1586 		return error;
1587 	if (c != MIDI_SYSEX_START)		/* must start like this */
1588 		return EINVAL;
1589 	sc = md->seq;
1590 	mutex_enter(&sc->lock);
1591 	error = midiseq_out(md, &c, 1, 0);
1592 	mutex_exit(&sc->lock);
1593 	if (error)
1594 		return error;
1595 	--sysex->len;
1596 	while (sysex->len > 0) {
1597 		cc = sysex->len;
1598 		if (cc > sizeof bf)
1599 			cc = sizeof bf;
1600 		error = uiomove(bf, cc, uio);
1601 		if (error)
1602 			break;
1603 		for(i = 0; i < cc && !MIDI_IS_STATUS(bf[i]); i++)
1604 			;
1605 		/*
1606 		 * XXX midi(4)'s buffer might not accommodate this, and the
1607 		 * function will not block us (though in this case we have
1608 		 * a process and could in principle block).
1609 		 */
1610 		mutex_enter(&sc->lock);
1611 		error = midiseq_out(md, bf, i, 0);
1612 		mutex_exit(&sc->lock);
1613 		if (error)
1614 			break;
1615 		sysex->len -= i;
1616 		if (i != cc)
1617 			break;
1618 	}
1619 	/*
1620 	 * Any leftover data in uio is rubbish;
1621 	 * the SYSEX should be one write ending in SYSEX_END.
1622 	 */
1623 	uio->uio_resid = 0;
1624 	c = MIDI_SYSEX_END;
1625 	mutex_enter(&sc->lock);
1626 	error = midiseq_out(md, &c, 1, 0);
1627 	mutex_exit(&sc->lock);
1628 	return error;
1629 }
1630 
1631 #if NMIDI == 0
1632 static dev_type_open(midiopen);
1633 static dev_type_close(midiclose);
1634 
1635 const struct cdevsw midi_cdevsw = {
1636 	.d_open = midiopen,
1637 	.d_close = midiclose,
1638 	.d_read = noread,
1639 	.d_write = nowrite,
1640 	.d_ioctl = noioctl,
1641 	.d_stop = nostop,
1642 	.d_tty = notty,
1643 	.d_poll = nopoll,
1644 	.d_mmap = nommap,
1645 	.d_kqfilter = nokqfilter,
1646 	.d_discard = nodiscard,
1647 	.d_flag = D_OTHER | D_MPSAFE
1648 };
1649 
1650 /*
1651  * If someone has a sequencer, but no midi devices there will
1652  * be unresolved references, so we provide little stubs.
1653  */
1654 
1655 int
1656 midi_unit_count(void)
1657 {
1658 	return (0);
1659 }
1660 
1661 static int
1662 midiopen(dev_t dev, int flags, int ifmt, struct lwp *l)
1663 {
1664 	return (ENXIO);
1665 }
1666 
1667 struct cfdriver midi_cd;
1668 
1669 void
1670 midi_getinfo(dev_t dev, struct midi_info *mi)
1671 {
1672         mi->name = "Dummy MIDI device";
1673 	mi->props = 0;
1674 }
1675 
1676 static int
1677 midiclose(dev_t dev, int flags, int ifmt, struct lwp *l)
1678 {
1679 	return (ENXIO);
1680 }
1681 
1682 int
1683 midi_writebytes(int unit, u_char *bf, int cc)
1684 {
1685 	return (ENXIO);
1686 }
1687 #endif /* NMIDI == 0 */
1688 
1689 #ifdef _MODULE
1690 #include "ioconf.c"
1691 
1692 devmajor_t sequencer_bmajor = -1, sequencer_cmajor = -1;
1693 #endif
1694 
1695 MODULE(MODULE_CLASS_DRIVER, sequencer, "midi");
1696 
1697 static int
1698 sequencer_modcmd(modcmd_t cmd, void *arg)
1699 {
1700 	int error = 0;
1701 
1702 #ifdef _MODULE
1703 	switch (cmd) {
1704 	case MODULE_CMD_INIT:
1705 		error = devsw_attach(sequencer_cd.cd_name,
1706 		    NULL, &sequencer_bmajor,
1707 		    &sequencer_cdevsw, &sequencer_cmajor);
1708 		if (error)
1709 			break;
1710 
1711 		error = config_init_component(cfdriver_ioconf_sequencer,
1712 		    cfattach_ioconf_sequencer, cfdata_ioconf_sequencer);
1713 		if (error) {
1714 			devsw_detach(NULL, &sequencer_cdevsw);
1715 		}
1716 		break;
1717 	case MODULE_CMD_FINI:
1718 		devsw_detach(NULL, &sequencer_cdevsw);
1719 		error = config_fini_component(cfdriver_ioconf_sequencer,
1720 		   cfattach_ioconf_sequencer, cfdata_ioconf_sequencer);
1721 		if (error)
1722 			devsw_attach(sequencer_cd.cd_name,
1723 			    NULL, &sequencer_bmajor,
1724 			    &sequencer_cdevsw, &sequencer_cmajor);
1725 		break;
1726 	default:
1727 		error = ENOTTY;
1728 		break;
1729 	}
1730 #endif
1731 
1732 	return error;
1733 }
1734