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