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