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