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