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