Home | History | Annotate | Line # | Download | only in dev
sequencer.c revision 1.30.14.18
      1 /*	$NetBSD: sequencer.c,v 1.30.14.18 2006/05/25 20:14:47 chap Exp $	*/
      2 
      3 /*
      4  * Copyright (c) 1998 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).
      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  * 3. All advertising materials mentioning features or use of this software
     19  *    must display the following acknowledgement:
     20  *        This product includes software developed by the NetBSD
     21  *        Foundation, Inc. and its contributors.
     22  * 4. Neither the name of The NetBSD Foundation nor the names of its
     23  *    contributors may be used to endorse or promote products derived
     24  *    from this software without specific prior written permission.
     25  *
     26  * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
     27  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
     28  * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
     29  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
     30  * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
     31  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
     32  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
     33  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
     34  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
     35  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
     36  * POSSIBILITY OF SUCH DAMAGE.
     37  */
     38 
     39 #include <sys/cdefs.h>
     40 __KERNEL_RCSID(0, "$NetBSD: sequencer.c,v 1.30.14.18 2006/05/25 20:14:47 chap Exp $");
     41 
     42 #include "sequencer.h"
     43 
     44 #include <sys/param.h>
     45 #include <sys/ioctl.h>
     46 #include <sys/fcntl.h>
     47 #include <sys/vnode.h>
     48 #include <sys/select.h>
     49 #include <sys/poll.h>
     50 #include <sys/malloc.h>
     51 #include <sys/proc.h>
     52 #include <sys/systm.h>
     53 #include <sys/syslog.h>
     54 #include <sys/kernel.h>
     55 #include <sys/signalvar.h>
     56 #include <sys/conf.h>
     57 #include <sys/audioio.h>
     58 #include <sys/midiio.h>
     59 #include <sys/device.h>
     60 
     61 #include <dev/midi_if.h>
     62 #include <dev/midivar.h>
     63 #include <dev/sequencervar.h>
     64 
     65 #define ADDTIMEVAL(a, b) ( \
     66 	(a)->tv_sec += (b)->tv_sec, \
     67 	(a)->tv_usec += (b)->tv_usec, \
     68 	(a)->tv_usec > 1000000 ? ((a)->tv_sec++, (a)->tv_usec -= 1000000) : 0\
     69 	)
     70 
     71 #define SUBTIMEVAL(a, b) ( \
     72 	(a)->tv_sec -= (b)->tv_sec, \
     73 	(a)->tv_usec -= (b)->tv_usec, \
     74 	(a)->tv_usec < 0 ? ((a)->tv_sec--, (a)->tv_usec += 1000000) : 0\
     75 	)
     76 
     77 #ifdef AUDIO_DEBUG
     78 #define DPRINTF(x)	if (sequencerdebug) printf x
     79 #define DPRINTFN(n,x)	if (sequencerdebug >= (n)) printf x
     80 int	sequencerdebug = 0;
     81 #else
     82 #define DPRINTF(x)
     83 #define DPRINTFN(n,x)
     84 #endif
     85 
     86 #define SEQ_NOTE_MAX 128
     87 #define SEQ_NOTE_XXX 255
     88 
     89 #define RECALC_TICK(t) ((t)->tick = 60 * 1000000L / ((t)->tempo * (t)->timebase))
     90 
     91 struct sequencer_softc seqdevs[NSEQUENCER];
     92 
     93 void sequencerattach(int);
     94 void seq_reset(struct sequencer_softc *);
     95 int seq_do_command(struct sequencer_softc *, seq_event_t *);
     96 int seq_do_extcommand(struct sequencer_softc *, seq_event_t *);
     97 int seq_do_chnvoice(struct sequencer_softc *, seq_event_t *);
     98 int seq_do_chncommon(struct sequencer_softc *, seq_event_t *);
     99 void seq_timer_waitabs(struct sequencer_softc *, uint32_t);
    100 int seq_do_timing(struct sequencer_softc *, seq_event_t *);
    101 int seq_do_local(struct sequencer_softc *, seq_event_t *);
    102 int seq_do_sysex(struct sequencer_softc *, seq_event_t *);
    103 int seq_do_fullsize(struct sequencer_softc *, seq_event_t *, struct uio *);
    104 static int seq_input_event(struct sequencer_softc *, seq_event_t *);
    105 int seq_drain(struct sequencer_softc *);
    106 void seq_startoutput(struct sequencer_softc *);
    107 void seq_timeout(void *);
    108 int seq_to_new(seq_event_t *, struct uio *);
    109 static int seq_sleep_timo(int *, const char *, int);
    110 static int seq_sleep(int *, const char *);
    111 static void seq_wakeup(int *);
    112 
    113 struct midi_softc;
    114 int midiseq_out(struct midi_dev *, u_char *, u_int, int);
    115 struct midi_dev *midiseq_open(int, int);
    116 void midiseq_close(struct midi_dev *);
    117 void midiseq_reset(struct midi_dev *);
    118 int midiseq_noteon(struct midi_dev *, int, int, seq_event_t *);
    119 int midiseq_noteoff(struct midi_dev *, int, int, seq_event_t *);
    120 int midiseq_keypressure(struct midi_dev *, int, int, seq_event_t *);
    121 int midiseq_pgmchange(struct midi_dev *, int, seq_event_t *);
    122 int midiseq_chnpressure(struct midi_dev *, int, seq_event_t *);
    123 int midiseq_ctlchange(struct midi_dev *, int, seq_event_t *);
    124 int midiseq_pitchbend(struct midi_dev *, int, seq_event_t *);
    125 int midiseq_loadpatch(struct midi_dev *, struct sysex_info *, struct uio *);
    126 void midiseq_in(struct midi_dev *, u_char *, int);
    127 
    128 dev_type_open(sequenceropen);
    129 dev_type_close(sequencerclose);
    130 dev_type_read(sequencerread);
    131 dev_type_write(sequencerwrite);
    132 dev_type_ioctl(sequencerioctl);
    133 dev_type_poll(sequencerpoll);
    134 dev_type_kqfilter(sequencerkqfilter);
    135 
    136 const struct cdevsw sequencer_cdevsw = {
    137 	sequenceropen, sequencerclose, sequencerread, sequencerwrite,
    138 	sequencerioctl, nostop, notty, sequencerpoll, nommap,
    139 	sequencerkqfilter,
    140 };
    141 
    142 void
    143 sequencerattach(int n)
    144 {
    145 
    146 	for (n = 0; n < NSEQUENCER; n++)
    147 		callout_init(&seqdevs[n].sc_callout);
    148 }
    149 
    150 int
    151 sequenceropen(dev_t dev, int flags, int ifmt, struct lwp *l)
    152 {
    153 	int unit = SEQUENCERUNIT(dev);
    154 	struct sequencer_softc *sc;
    155 	struct midi_dev *md;
    156 	int nmidi;
    157 
    158 	DPRINTF(("sequenceropen\n"));
    159 
    160 	if (unit >= NSEQUENCER)
    161 		return (ENXIO);
    162 	sc = &seqdevs[unit];
    163 	if (sc->isopen)
    164 		return EBUSY;
    165 	if (SEQ_IS_OLD(unit))
    166 		sc->mode = SEQ_OLD;
    167 	else
    168 		sc->mode = SEQ_NEW;
    169 	sc->isopen++;
    170 	sc->flags = flags & (FREAD|FWRITE);
    171 	sc->rchan = 0;
    172 	sc->wchan = 0;
    173 	sc->pbus = 0;
    174 	sc->async = 0;
    175 	sc->input_stamp = ~0;
    176 
    177 	sc->nmidi = 0;
    178 	nmidi = midi_unit_count();
    179 
    180 	sc->devs = malloc(nmidi * sizeof(struct midi_dev *),
    181 			  M_DEVBUF, M_WAITOK);
    182 	for (unit = 0; unit < nmidi; unit++) {
    183 		md = midiseq_open(unit, flags);
    184 		if (md) {
    185 			sc->devs[sc->nmidi++] = md;
    186 			md->seq = sc;
    187 		}
    188 	}
    189 
    190 	sc->timer.timebase = 100;
    191 	sc->timer.tempo = 60;
    192 	sc->doingsysex = 0;
    193 	RECALC_TICK(&sc->timer);
    194 	sc->timer.last = 0;
    195 	microtime(&sc->timer.start);
    196 
    197 	SEQ_QINIT(&sc->inq);
    198 	SEQ_QINIT(&sc->outq);
    199 	sc->lowat = SEQ_MAXQ / 2;
    200 
    201 	seq_reset(sc);
    202 
    203 	DPRINTF(("sequenceropen: mode=%d, nmidi=%d\n", sc->mode, sc->nmidi));
    204 	return 0;
    205 }
    206 
    207 static int
    208 seq_sleep_timo(int *chan, const char *label, int timo)
    209 {
    210 	int st;
    211 
    212 	if (!label)
    213 		label = "seq";
    214 
    215 	DPRINTFN(5, ("seq_sleep_timo: %p %s %d\n", chan, label, timo));
    216 	*chan = 1;
    217 	st = tsleep(chan, PWAIT | PCATCH, label, timo);
    218 	*chan = 0;
    219 #ifdef MIDI_DEBUG
    220 	if (st != 0)
    221 	    printf("seq_sleep: %d\n", st);
    222 #endif
    223 	return st;
    224 }
    225 
    226 static int
    227 seq_sleep(int *chan, const char *label)
    228 {
    229 	return seq_sleep_timo(chan, label, 0);
    230 }
    231 
    232 static void
    233 seq_wakeup(int *chan)
    234 {
    235 	if (*chan) {
    236 		DPRINTFN(5, ("seq_wakeup: %p\n", chan));
    237 		wakeup(chan);
    238 		*chan = 0;
    239 	}
    240 }
    241 
    242 int
    243 seq_drain(struct sequencer_softc *sc)
    244 {
    245 	int error;
    246 
    247 	DPRINTFN(3, ("seq_drain: %p, len=%d\n", sc, SEQ_QLEN(&sc->outq)));
    248 	seq_startoutput(sc);
    249 	error = 0;
    250 	while(!SEQ_QEMPTY(&sc->outq) && !error)
    251 		error = seq_sleep_timo(&sc->wchan, "seq_dr", 60*hz);
    252 	return (error);
    253 }
    254 
    255 void
    256 seq_timeout(void *addr)
    257 {
    258 	struct sequencer_softc *sc = addr;
    259 	DPRINTFN(4, ("seq_timeout: %p\n", sc));
    260 	sc->timeout = 0;
    261 	seq_startoutput(sc);
    262 	if (SEQ_QLEN(&sc->outq) < sc->lowat) {
    263 		seq_wakeup(&sc->wchan);
    264 		selnotify(&sc->wsel, 0);
    265 		if (sc->async)
    266 			psignal(sc->async, SIGIO);
    267 	}
    268 
    269 }
    270 
    271 void
    272 seq_startoutput(struct sequencer_softc *sc)
    273 {
    274 	struct sequencer_queue *q = &sc->outq;
    275 	seq_event_t cmd;
    276 
    277 	if (sc->timeout)
    278 		return;
    279 	DPRINTFN(4, ("seq_startoutput: %p, len=%d\n", sc, SEQ_QLEN(q)));
    280 	while(!SEQ_QEMPTY(q) && !sc->timeout) {
    281 		SEQ_QGET(q, cmd);
    282 		seq_do_command(sc, &cmd);
    283 	}
    284 }
    285 
    286 int
    287 sequencerclose(dev_t dev, int flags, int ifmt, struct lwp *l)
    288 {
    289 	struct sequencer_softc *sc = &seqdevs[SEQUENCERUNIT(dev)];
    290 	int n, s;
    291 
    292 	DPRINTF(("sequencerclose: %p\n", sc));
    293 
    294 	seq_drain(sc);
    295 	s = splaudio();
    296 	if (sc->timeout) {
    297 		callout_stop(&sc->sc_callout);
    298 		sc->timeout = 0;
    299 	}
    300 	splx(s);
    301 
    302 	for (n = 0; n < sc->nmidi; n++)
    303 		midiseq_close(sc->devs[n]);
    304 	free(sc->devs, M_DEVBUF);
    305 	sc->isopen = 0;
    306 	return (0);
    307 }
    308 
    309 static int
    310 seq_input_event(struct sequencer_softc *sc, seq_event_t *cmd)
    311 {
    312 	struct sequencer_queue *q = &sc->inq;
    313 
    314 	DPRINTFN(2, ("seq_input_event: %02x %02x %02x %02x %02x %02x %02x %02x\n",
    315 		     cmd->tag,
    316 		     cmd->unknown.byte[0], cmd->unknown.byte[1],
    317 		     cmd->unknown.byte[2], cmd->unknown.byte[3],
    318 		     cmd->unknown.byte[4], cmd->unknown.byte[5],
    319 		     cmd->unknown.byte[6]));
    320 	if (SEQ_QFULL(q))
    321 		return (ENOMEM);
    322 	SEQ_QPUT(q, *cmd);
    323 	seq_wakeup(&sc->rchan);
    324 	selnotify(&sc->rsel, 0);
    325 	if (sc->async)
    326 		psignal(sc->async, SIGIO);
    327 	return 0;
    328 }
    329 
    330 void
    331 seq_event_intr(void *addr, seq_event_t *iev)
    332 {
    333 	struct sequencer_softc *sc = addr;
    334 	u_long t;
    335 	struct timeval now;
    336 
    337 	microtime(&now);
    338 	SUBTIMEVAL(&now, &sc->timer.start);
    339 	t = now.tv_sec * 1000000 + now.tv_usec;
    340 	t /= sc->timer.tick;
    341 	if (t != sc->input_stamp) {
    342 		seq_input_event(sc, &SEQ_MK_TIMING(WAIT_ABS, .divisions=t));
    343 		sc->input_stamp = t;
    344 	}
    345 	seq_input_event(sc, iev);
    346 }
    347 
    348 int
    349 sequencerread(dev_t dev, struct uio *uio, int ioflag)
    350 {
    351 	struct sequencer_softc *sc = &seqdevs[SEQUENCERUNIT(dev)];
    352 	struct sequencer_queue *q = &sc->inq;
    353 	seq_event_t ev;
    354 	int error, s;
    355 
    356 	DPRINTFN(20, ("sequencerread: %p, count=%d, ioflag=%x\n",
    357 		     sc, (int) uio->uio_resid, ioflag));
    358 
    359 	if (sc->mode == SEQ_OLD) {
    360 		DPRINTFN(-1,("sequencerread: old read\n"));
    361 		return (EINVAL); /* XXX unimplemented */
    362 	}
    363 
    364 	error = 0;
    365 	while (SEQ_QEMPTY(q)) {
    366 		if (ioflag & IO_NDELAY)
    367 			return EWOULDBLOCK;
    368 		else {
    369 			error = seq_sleep(&sc->rchan, "seq rd");
    370 			if (error)
    371 				return error;
    372 		}
    373 	}
    374 	s = splaudio();
    375 	while (uio->uio_resid >= sizeof ev && !error && !SEQ_QEMPTY(q)) {
    376 		SEQ_QGET(q, ev);
    377 		error = uiomove(&ev, sizeof ev, uio);
    378 	}
    379 	splx(s);
    380 	return error;
    381 }
    382 
    383 int
    384 sequencerwrite(dev_t dev, struct uio *uio, int ioflag)
    385 {
    386 	struct sequencer_softc *sc = &seqdevs[SEQUENCERUNIT(dev)];
    387 	struct sequencer_queue *q = &sc->outq;
    388 	int error;
    389 	seq_event_t cmdbuf;
    390 	int size;
    391 
    392 	DPRINTFN(2, ("sequencerwrite: %p, count=%d\n", sc, (int) uio->uio_resid));
    393 
    394 	error = 0;
    395 	size = sc->mode == SEQ_NEW ? sizeof cmdbuf : SEQOLD_CMDSIZE;
    396 	while (uio->uio_resid >= size) {
    397 		error = uiomove(&cmdbuf, size, uio);
    398 		if (error)
    399 			break;
    400 		if (sc->mode == SEQ_OLD)
    401 			if (seq_to_new(&cmdbuf, uio))
    402 				continue;
    403 		if (cmdbuf.tag == SEQ_FULLSIZE) {
    404 			/* We do it like OSS does, asynchronously */
    405 			error = seq_do_fullsize(sc, &cmdbuf, uio);
    406 			if (error)
    407 				break;
    408 			continue;
    409 		}
    410 		while (SEQ_QFULL(q)) {
    411 			seq_startoutput(sc);
    412 			if (SEQ_QFULL(q)) {
    413 				if (ioflag & IO_NDELAY)
    414 					return EWOULDBLOCK;
    415 				error = seq_sleep(&sc->wchan, "seq_wr");
    416 				if (error)
    417 					return error;
    418 			}
    419 		}
    420 		SEQ_QPUT(q, cmdbuf);
    421 	}
    422 	seq_startoutput(sc);
    423 
    424 #ifdef SEQUENCER_DEBUG
    425 	if (error)
    426 		DPRINTFN(2, ("sequencerwrite: error=%d\n", error));
    427 #endif
    428 	return error;
    429 }
    430 
    431 int
    432 sequencerioctl(dev_t dev, u_long cmd, caddr_t addr, int flag, struct lwp *l)
    433 {
    434 	struct sequencer_softc *sc = &seqdevs[SEQUENCERUNIT(dev)];
    435 	struct synth_info *si;
    436 	struct midi_dev *md;
    437 	int devno;
    438 	int error;
    439 	int t;
    440 
    441 	DPRINTFN(2, ("sequencerioctl: %p cmd=0x%08lx\n", sc, cmd));
    442 
    443 	error = 0;
    444 	switch (cmd) {
    445 	case FIONBIO:
    446 		/* All handled in the upper FS layer. */
    447 		break;
    448 
    449 	case FIOASYNC:
    450 		if (*(int *)addr) {
    451 			if (sc->async)
    452 				return EBUSY;
    453 			sc->async = l->l_proc;
    454 			DPRINTF(("sequencer_ioctl: FIOASYNC %p\n", l));
    455 		} else
    456 			sc->async = 0;
    457 		break;
    458 
    459 	case SEQUENCER_RESET:
    460 		seq_reset(sc);
    461 		break;
    462 
    463 	case SEQUENCER_PANIC:
    464 		seq_reset(sc);
    465 		/* Do more?  OSS doesn't */
    466 		break;
    467 
    468 	case SEQUENCER_SYNC:
    469 		if (sc->flags == FREAD)
    470 			return 0;
    471 		seq_drain(sc);
    472 		error = 0;
    473 		break;
    474 
    475 	case SEQUENCER_INFO:
    476 		si = (struct synth_info*)addr;
    477 		devno = si->device;
    478 		if (devno < 0 || devno >= sc->nmidi)
    479 			return EINVAL;
    480 		md = sc->devs[devno];
    481 		strncpy(si->name, md->name, sizeof si->name);
    482 		si->synth_type = SYNTH_TYPE_MIDI;
    483 		si->synth_subtype = md->subtype;
    484 		si->nr_voices = md->nr_voices;
    485 		si->instr_bank_size = md->instr_bank_size;
    486 		si->capabilities = md->capabilities;
    487 		break;
    488 
    489 	case SEQUENCER_NRSYNTHS:
    490 		*(int *)addr = sc->nmidi;
    491 		break;
    492 
    493 	case SEQUENCER_NRMIDIS:
    494 		*(int *)addr = sc->nmidi;
    495 		break;
    496 
    497 	case SEQUENCER_OUTOFBAND:
    498 		DPRINTFN(3, ("sequencer_ioctl: OOB=%02x %02x %02x %02x %02x %02x %02x %02x\n",
    499 			     *(u_char *)addr, *(u_char *)(addr+1),
    500 			     *(u_char *)(addr+2), *(u_char *)(addr+3),
    501 			     *(u_char *)(addr+4), *(u_char *)(addr+5),
    502 			     *(u_char *)(addr+6), *(u_char *)(addr+7)));
    503 		if ( !(sc->flags & FWRITE ) )
    504 		        return EBADF;
    505 		error = seq_do_command(sc, (seq_event_t *)addr);
    506 		break;
    507 
    508 	case SEQUENCER_TMR_TIMEBASE:
    509 		t = *(int *)addr;
    510 		if (t < 1)
    511 			t = 1;
    512 		if (t > 10000)
    513 			t = 10000;
    514 		sc->timer.timebase = t;
    515 		*(int *)addr = t;
    516 		RECALC_TICK(&sc->timer);
    517 		break;
    518 
    519 	case SEQUENCER_TMR_START:
    520 		error = seq_do_timing(sc, &SEQ_MK_TIMING(START));
    521 		break;
    522 
    523 	case SEQUENCER_TMR_STOP:
    524 		error = seq_do_timing(sc, &SEQ_MK_TIMING(STOP));
    525 		break;
    526 
    527 	case SEQUENCER_TMR_CONTINUE:
    528 		error = seq_do_timing(sc, &SEQ_MK_TIMING(CONTINUE));
    529 		break;
    530 
    531 	case SEQUENCER_TMR_TEMPO:
    532 		error = seq_do_timing(sc,
    533 		    &SEQ_MK_TIMING(TEMPO, .bpm=*(int *)addr));
    534 		if (!error)
    535 		    *(int *)addr = sc->timer.tempo;
    536 		break;
    537 
    538 	case SEQUENCER_TMR_SOURCE:
    539 		*(int *)addr = SEQUENCER_TMR_INTERNAL;
    540 		break;
    541 
    542 	case SEQUENCER_TMR_METRONOME:
    543 		/* noop */
    544 		break;
    545 
    546 	case SEQUENCER_THRESHOLD:
    547 		t = SEQ_MAXQ - *(int *)addr / sizeof (seq_event_rec);
    548 		if (t < 1)
    549 			t = 1;
    550 		if (t > SEQ_MAXQ)
    551 			t = SEQ_MAXQ;
    552 		sc->lowat = t;
    553 		break;
    554 
    555 	case SEQUENCER_CTRLRATE:
    556 		*(int *)addr = (sc->timer.tempo*sc->timer.timebase + 30) / 60;
    557 		break;
    558 
    559 	case SEQUENCER_GETTIME:
    560 	{
    561 		struct timeval now;
    562 		u_long tx;
    563 		microtime(&now);
    564 		SUBTIMEVAL(&now, &sc->timer.start);
    565 		tx = now.tv_sec * 1000000 + now.tv_usec;
    566 		tx /= sc->timer.tick;
    567 		*(int *)addr = tx;
    568 		break;
    569 	}
    570 
    571 	default:
    572 		DPRINTFN(-1,("sequencer_ioctl: unimpl %08lx\n", cmd));
    573 		error = EINVAL;
    574 		break;
    575 	}
    576 	return error;
    577 }
    578 
    579 int
    580 sequencerpoll(dev_t dev, int events, struct lwp *l)
    581 {
    582 	struct sequencer_softc *sc = &seqdevs[SEQUENCERUNIT(dev)];
    583 	int revents = 0;
    584 
    585 	DPRINTF(("sequencerpoll: %p events=0x%x\n", sc, events));
    586 
    587 	if (events & (POLLIN | POLLRDNORM))
    588 		if ((sc->flags&FREAD) && !SEQ_QEMPTY(&sc->inq))
    589 			revents |= events & (POLLIN | POLLRDNORM);
    590 
    591 	if (events & (POLLOUT | POLLWRNORM))
    592 		if ((sc->flags&FWRITE) && SEQ_QLEN(&sc->outq) < sc->lowat)
    593 			revents |= events & (POLLOUT | POLLWRNORM);
    594 
    595 	if (revents == 0) {
    596 		if ((sc->flags&FREAD) && (events & (POLLIN | POLLRDNORM)))
    597 			selrecord(l, &sc->rsel);
    598 
    599 		if ((sc->flags&FWRITE) && (events & (POLLOUT | POLLWRNORM)))
    600 			selrecord(l, &sc->wsel);
    601 	}
    602 
    603 	return revents;
    604 }
    605 
    606 static void
    607 filt_sequencerrdetach(struct knote *kn)
    608 {
    609 	struct sequencer_softc *sc = kn->kn_hook;
    610 	int s;
    611 
    612 	s = splaudio();
    613 	SLIST_REMOVE(&sc->rsel.sel_klist, kn, knote, kn_selnext);
    614 	splx(s);
    615 }
    616 
    617 static int
    618 filt_sequencerread(struct knote *kn, long hint)
    619 {
    620 	struct sequencer_softc *sc = kn->kn_hook;
    621 
    622 	/* XXXLUKEM (thorpej): make sure this is correct */
    623 
    624 	if (SEQ_QEMPTY(&sc->inq))
    625 		return (0);
    626 	kn->kn_data = sizeof(seq_event_rec);
    627 	return (1);
    628 }
    629 
    630 static const struct filterops sequencerread_filtops =
    631 	{ 1, NULL, filt_sequencerrdetach, filt_sequencerread };
    632 
    633 static void
    634 filt_sequencerwdetach(struct knote *kn)
    635 {
    636 	struct sequencer_softc *sc = kn->kn_hook;
    637 	int s;
    638 
    639 	s = splaudio();
    640 	SLIST_REMOVE(&sc->wsel.sel_klist, kn, knote, kn_selnext);
    641 	splx(s);
    642 }
    643 
    644 static int
    645 filt_sequencerwrite(struct knote *kn, long hint)
    646 {
    647 	struct sequencer_softc *sc = kn->kn_hook;
    648 
    649 	/* XXXLUKEM (thorpej): make sure this is correct */
    650 
    651 	if (SEQ_QLEN(&sc->outq) >= sc->lowat)
    652 		return (0);
    653 	kn->kn_data = sizeof(seq_event_rec);
    654 	return (1);
    655 }
    656 
    657 static const struct filterops sequencerwrite_filtops =
    658 	{ 1, NULL, filt_sequencerwdetach, filt_sequencerwrite };
    659 
    660 int
    661 sequencerkqfilter(dev_t dev, struct knote *kn)
    662 {
    663 	struct sequencer_softc *sc = &seqdevs[SEQUENCERUNIT(dev)];
    664 	struct klist *klist;
    665 	int s;
    666 
    667 	switch (kn->kn_filter) {
    668 	case EVFILT_READ:
    669 		klist = &sc->rsel.sel_klist;
    670 		kn->kn_fop = &sequencerread_filtops;
    671 		break;
    672 
    673 	case EVFILT_WRITE:
    674 		klist = &sc->wsel.sel_klist;
    675 		kn->kn_fop = &sequencerwrite_filtops;
    676 		break;
    677 
    678 	default:
    679 		return (1);
    680 	}
    681 
    682 	kn->kn_hook = sc;
    683 
    684 	s = splaudio();
    685 	SLIST_INSERT_HEAD(klist, kn, kn_selnext);
    686 	splx(s);
    687 
    688 	return (0);
    689 }
    690 
    691 void
    692 seq_reset(struct sequencer_softc *sc)
    693 {
    694 	int i, chn;
    695 	struct midi_dev *md;
    696 
    697 	if ( !(sc->flags & FWRITE) )
    698 	        return;
    699 	for (i = 0; i < sc->nmidi; i++) {
    700 		md = sc->devs[i];
    701 		midiseq_reset(md);
    702 		for (chn = 0; chn < MAXCHAN; chn++) {
    703 			midiseq_ctlchange(md, chn, &SEQ_MK_CHN(CTL_CHANGE,
    704 			    .controller=MIDI_CTRL_ALLOFF));
    705 			midiseq_ctlchange(md, chn, &SEQ_MK_CHN(CTL_CHANGE,
    706 			    .controller=MIDI_CTRL_RESET));
    707 			midiseq_pitchbend(md, chn, &SEQ_MK_CHN(PITCH_BEND,
    708 			    .value=MIDI_BEND_NEUTRAL));
    709 		}
    710 	}
    711 }
    712 
    713 int
    714 seq_do_command(struct sequencer_softc *sc, seq_event_t *b)
    715 {
    716 	int dev;
    717 
    718 	DPRINTFN(4, ("seq_do_command: %p cmd=0x%02x\n", sc, SEQ_CMD(b)));
    719 
    720 	switch(b->tag) {
    721 	case SEQ_LOCAL:
    722 		return seq_do_local(sc, b);
    723 	case SEQ_TIMING:
    724 		return seq_do_timing(sc, b);
    725 	case SEQ_CHN_VOICE:
    726 		return seq_do_chnvoice(sc, b);
    727 	case SEQ_CHN_COMMON:
    728 		return seq_do_chncommon(sc, b);
    729 	case SEQ_SYSEX:
    730 		return seq_do_sysex(sc, b);
    731 	/* COMPAT */
    732 	case SEQOLD_MIDIPUTC:
    733 		dev = b->unknown.byte[1];
    734 		if (dev < 0 || dev >= sc->nmidi)
    735 			return (ENXIO);
    736 		return midiseq_out(sc->devs[dev], b->unknown.byte, 1, 0);
    737 	default:
    738 		DPRINTFN(-1,("seq_do_command: unimpl command %02x\n", b->tag));
    739 		return (EINVAL);
    740 	}
    741 }
    742 
    743 int
    744 seq_do_chnvoice(struct sequencer_softc *sc, seq_event_t *b)
    745 {
    746 	int dev;
    747 	int error;
    748 	struct midi_dev *md;
    749 
    750 	dev = b->voice.device;
    751 	if (dev < 0 || dev >= sc->nmidi ||
    752 	    b->voice.channel > 15 ||
    753 	    b->voice.key >= SEQ_NOTE_MAX)
    754 		return ENXIO;
    755 	md = sc->devs[dev];
    756 	switch(b->voice.op) {
    757 	case MIDI_NOTEON: /* no need to special-case hidden noteoff here */
    758 		error = midiseq_noteon(md, b->voice.channel, b->voice.key, b);
    759 		break;
    760 	case MIDI_NOTEOFF:
    761 		error = midiseq_noteoff(md, b->voice.channel, b->voice.key, b);
    762 		break;
    763 	case MIDI_KEY_PRESSURE:
    764 		error = midiseq_keypressure(md,
    765 		    b->voice.channel, b->voice.key, b);
    766 		break;
    767 	default:
    768 		DPRINTFN(-1,("seq_do_chnvoice: unimpl command %02x\n",
    769 			b->voice.op));
    770 		error = EINVAL;
    771 		break;
    772 	}
    773 	return error;
    774 }
    775 
    776 int
    777 seq_do_chncommon(struct sequencer_softc *sc, seq_event_t *b)
    778 {
    779 	int dev;
    780 	int error;
    781 	struct midi_dev *md;
    782 
    783 	dev = b->common.device;
    784 	if (dev < 0 || dev >= sc->nmidi ||
    785 	    b->common.channel > 15)
    786 		return ENXIO;
    787 	md = sc->devs[dev];
    788 	DPRINTFN(2,("seq_do_chncommon: %02x\n", b->common.op));
    789 
    790 	error = 0;
    791 	switch(b->common.op) {
    792 	case MIDI_PGM_CHANGE:
    793 		error = midiseq_pgmchange(md, b->common.channel, b);
    794 		break;
    795 	case MIDI_CTL_CHANGE:
    796 		error = midiseq_ctlchange(md, b->common.channel, b);
    797 		break;
    798 	case MIDI_PITCH_BEND:
    799 		error = midiseq_pitchbend(md, b->common.channel, b);
    800 		break;
    801 	case MIDI_CHN_PRESSURE:
    802 		error = midiseq_chnpressure(md, b->common.channel, b);
    803 		break;
    804 	default:
    805 		DPRINTFN(-1,("seq_do_chncommon: unimpl command %02x\n",
    806 			b->common.op));
    807 		error = EINVAL;
    808 		break;
    809 	}
    810 	return error;
    811 }
    812 
    813 int
    814 seq_do_local(struct sequencer_softc *sc, seq_event_t *b)
    815 {
    816 	return (EINVAL);
    817 }
    818 
    819 int
    820 seq_do_sysex(struct sequencer_softc *sc, seq_event_t *b)
    821 {
    822 	int dev, i;
    823 	struct midi_dev *md;
    824 	uint8_t *bf = b->sysex.buffer;
    825 
    826 	dev = b->sysex.device;
    827 	if (dev < 0 || dev >= sc->nmidi)
    828 		return (ENXIO);
    829 	DPRINTF(("seq_do_sysex: dev=%d\n", dev));
    830 	md = sc->devs[dev];
    831 
    832 	if (!sc->doingsysex) {
    833 		midiseq_out(md, (uint8_t[]){MIDI_SYSEX_START}, 1, 0);
    834 		sc->doingsysex = 1;
    835 	}
    836 
    837 	for (i = 0; i < 6 && bf[i] != 0xff; i++)
    838 		;
    839 	midiseq_out(md, bf, i, 0);
    840 	if (i < 6 || (i > 0 && bf[i-1] == MIDI_SYSEX_END))
    841 		sc->doingsysex = 0;
    842 	return 0;
    843 }
    844 
    845 void
    846 seq_timer_waitabs(struct sequencer_softc *sc, uint32_t divs)
    847 {
    848 	struct timeval when;
    849 	long long usec;
    850 	struct syn_timer *t;
    851 	int ticks;
    852 
    853 	t = &sc->timer;
    854 	t->last = divs;
    855 	usec = (long long)divs * (long long)t->tick; /* convert to usec */
    856 	when.tv_sec = usec / 1000000;
    857 	when.tv_usec = usec % 1000000;
    858 	DPRINTFN(4, ("seq_timer_waitabs: divs=%d, sleep when=%ld.%06ld", divs,
    859 		     when.tv_sec, when.tv_usec));
    860 	ADDTIMEVAL(&when, &t->start); /* abstime for end */
    861 	ticks = hzto(&when);
    862 	DPRINTFN(4, (" when+start=%ld.%06ld, tick=%d\n",
    863 		     when.tv_sec, when.tv_usec, ticks));
    864 	if (ticks > 0) {
    865 #ifdef DIAGNOSTIC
    866 		if (ticks > 20 * hz) {
    867 			/* Waiting more than 20s */
    868 			printf("seq_timer_waitabs: funny ticks=%d, "
    869 			       "usec=%lld, parm=%d, tick=%ld\n",
    870 			       ticks, usec, parm, t->tick);
    871 		}
    872 #endif
    873 		sc->timeout = 1;
    874 		callout_reset(&sc->sc_callout, ticks,
    875 		    seq_timeout, sc);
    876 	}
    877 #ifdef SEQUENCER_DEBUG
    878 	else if (tick < 0)
    879 		DPRINTF(("seq_timer_waitabs: ticks = %d\n", ticks));
    880 #endif
    881 }
    882 
    883 int
    884 seq_do_timing(struct sequencer_softc *sc, seq_event_t *b)
    885 {
    886 	struct syn_timer *t = &sc->timer;
    887 	struct timeval when;
    888 	int error;
    889 
    890 	error = 0;
    891 	switch(b->timing.op) {
    892 	case TMR_WAIT_REL:
    893 		seq_timer_waitabs(sc, b->t_WAIT_REL.divisions + t->last);
    894 		break;
    895 	case TMR_WAIT_ABS:
    896 		seq_timer_waitabs(sc, b->t_WAIT_ABS.divisions);
    897 		break;
    898 	case TMR_START:
    899 		microtime(&t->start);
    900 		t->running = 1;
    901 		break;
    902 	case TMR_STOP:
    903 		microtime(&t->stop);
    904 		t->running = 0;
    905 		break;
    906 	case TMR_CONTINUE:
    907 		microtime(&when);
    908 		SUBTIMEVAL(&when, &t->stop);
    909 		ADDTIMEVAL(&t->start, &when);
    910 		t->running = 1;
    911 		break;
    912 	case TMR_TEMPO:
    913 		/* bpm is unambiguously MIDI clocks per minute / 24 */
    914 		/* (24 MIDI clocks are usually but not always a quarter note) */
    915 		if (b->t_TEMPO.bpm < 8) /* where are these limits specified? */
    916 			t->tempo = 8;
    917 		else if (b->t_TEMPO.bpm > 360) /* ? */
    918 			t->tempo = 360;
    919 		else
    920 			t->tempo = b->t_TEMPO.bpm;
    921 		RECALC_TICK(t);
    922 		break;
    923 	case TMR_ECHO:
    924 		error = seq_input_event(sc, b);
    925 		break;
    926 	case TMR_RESET:
    927 		t->last = 0;
    928 		microtime(&t->start);
    929 		break;
    930 	case TMR_SPP:
    931 	case TMR_TIMESIG:
    932 		DPRINTF(("seq_do_timing: unimplemented %02x\n", b->timing.op));
    933 		error = EINVAL; /* not quite accurate... */
    934 		break;
    935 	default:
    936 		DPRINTF(("seq_timer: unknown %02x\n", cmd));
    937 		error = EINVAL;
    938 		break;
    939 	}
    940 	return (error);
    941 }
    942 
    943 int
    944 seq_do_fullsize(struct sequencer_softc *sc, seq_event_t *b, struct uio *uio)
    945 {
    946 	struct sysex_info sysex;
    947 	u_int dev;
    948 
    949 #ifdef DIAGNOSTIC
    950 	if (sizeof(seq_event_rec) != SEQ_SYSEX_HDRSIZE) {
    951 		printf("seq_do_fullsize: sysex size ??\n");
    952 		return EINVAL;
    953 	}
    954 #endif
    955 	memcpy(&sysex, b, sizeof sysex);
    956 	dev = sysex.device_no;
    957 	if (dev < 0 || dev >= sc->nmidi)
    958 		return (ENXIO);
    959 	DPRINTFN(2, ("seq_do_fullsize: fmt=%04x, dev=%d, len=%d\n",
    960 		     sysex.key, dev, sysex.len));
    961 	return (midiseq_loadpatch(sc->devs[dev], &sysex, uio));
    962 }
    963 
    964 /* Convert an old sequencer event to a new one. */
    965 int
    966 seq_to_new(seq_event_t *ev, struct uio *uio)
    967 {
    968 	int cmd, chan, note, parm;
    969 	uint32_t tmp_delay;
    970 	int error;
    971 	uint8_t *bfp;
    972 
    973 	cmd = ev->tag;
    974 	bfp = ev->unknown.byte;
    975 	chan = *bfp++;
    976 	note = *bfp++;
    977 	parm = *bfp++;
    978 	DPRINTFN(3, ("seq_to_new: 0x%02x %d %d %d\n", cmd, chan, note, parm));
    979 
    980 	if (cmd >= 0x80) {
    981 		/* Fill the event record */
    982 		if (uio->uio_resid >= sizeof *ev - SEQOLD_CMDSIZE) {
    983 			error = uiomove(bfp, sizeof *ev - SEQOLD_CMDSIZE, uio);
    984 			if (error)
    985 				return error;
    986 		} else
    987 			return EINVAL;
    988 	}
    989 
    990 	switch(cmd) {
    991 	case SEQOLD_NOTEOFF:
    992 		/*
    993 		 * What's with the SEQ_NOTE_XXX?  In OSS this seems to have
    994 		 * been undocumented magic for messing with the overall volume
    995 		 * of a 'voice', equated precariously with 'channel' and
    996 		 * pretty much unimplementable except by directly frobbing a
    997 		 * synth chip. For us, who treat everything as interfaced over
    998 		 * MIDI, this will just be unceremoniously discarded as
    999 		 * invalid in midiseq_noteoff, making the whole event an
   1000 		 * elaborate no-op, and that doesn't seem to be any different
   1001 		 * from what happens on linux with a MIDI-interfaced device,
   1002 		 * by the way. The moral is ... use the new /dev/music API, ok?
   1003 		 */
   1004 		*ev = SEQ_MK_CHN(NOTEOFF, .device=0, .channel=chan,
   1005 		    .key=SEQ_NOTE_XXX, .velocity=parm);
   1006 		break;
   1007 	case SEQOLD_NOTEON:
   1008 		*ev = SEQ_MK_CHN(NOTEON,
   1009 		    .device=0, .channel=chan, .key=note, .velocity=parm);
   1010 		break;
   1011 	case SEQOLD_WAIT:
   1012 		/*
   1013 		 * This event cannot even /exist/ on non-littleendian machines,
   1014 		 * and so help me, that's exactly the way OSS defined it.
   1015 		 * Also, the OSS programmer's guide states (p. 74, v1.11)
   1016 		 * that seqold time units are system clock ticks, unlike
   1017 		 * the new 'divisions' which are determined by timebase. In
   1018 		 * that case we would need to do scaling here - but no such
   1019 		 * behavior is visible in linux either--which also treats this
   1020 		 * value, surprisingly, as an absolute, not relative, time.
   1021 		 * My guess is that this event has gone unused so long that
   1022 		 * nobody could agree we got it wrong no matter what we do.
   1023 		 */
   1024 		tmp_delay = *(uint32_t *)ev >> 8;
   1025 		*ev = SEQ_MK_TIMING(WAIT_ABS, .divisions=tmp_delay);
   1026 		break;
   1027 	case SEQOLD_SYNCTIMER:
   1028 		/*
   1029 		 * The TMR_RESET event is not defined in any OSS materials
   1030 		 * I can find; it may have been invented here just to provide
   1031 		 * an accurate _to_new translation of this event.
   1032 		 */
   1033 		*ev = SEQ_MK_TIMING(RESET);
   1034 		break;
   1035 	case SEQOLD_PGMCHANGE:
   1036 		*ev = SEQ_MK_CHN(PGM_CHANGE,
   1037 		    .device=0, .channel=chan, .program=note);
   1038 		break;
   1039 	case SEQOLD_MIDIPUTC:
   1040 		break;		/* interpret in normal mode */
   1041 	case SEQOLD_ECHO:
   1042 	case SEQOLD_PRIVATE:
   1043 	case SEQOLD_EXTENDED:
   1044 	default:
   1045 		DPRINTF(("seq_to_new: not impl 0x%02x\n", cmd));
   1046 		return EINVAL;
   1047 	/* In case new-style events show up */
   1048 	case SEQ_TIMING:
   1049 	case SEQ_CHN_VOICE:
   1050 	case SEQ_CHN_COMMON:
   1051 	case SEQ_FULLSIZE:
   1052 		break;
   1053 	}
   1054 	return 0;
   1055 }
   1056 
   1057 /**********************************************/
   1058 
   1059 void
   1060 midiseq_in(struct midi_dev *md, u_char *msg, int len)
   1061 {
   1062 	int unit = md->unit;
   1063 	seq_event_t ev;
   1064 	int status, chan;
   1065 
   1066 	DPRINTFN(2, ("midiseq_in: %p %02x %02x %02x\n",
   1067 		     md, msg[0], msg[1], msg[2]));
   1068 
   1069 	status = MIDI_GET_STATUS(msg[0]);
   1070 	chan = MIDI_GET_CHAN(msg[0]);
   1071 	switch (status) {
   1072 	case MIDI_NOTEON: /* midi(4) always canonicalizes hidden note-off */
   1073 		ev = SEQ_MK_CHN(NOTEON, .device=unit, .channel=chan,
   1074 		    .key=msg[1], .velocity=msg[2]);
   1075 		break;
   1076 	case MIDI_NOTEOFF:
   1077 		ev = SEQ_MK_CHN(NOTEOFF, .device=unit, .channel=chan,
   1078 		    .key=msg[1], .velocity=msg[2]);
   1079 		break;
   1080 	case MIDI_KEY_PRESSURE:
   1081 		ev = SEQ_MK_CHN(KEY_PRESSURE, .device=unit, .channel=chan,
   1082 		    .key=msg[1], .pressure=msg[2]);
   1083 		break;
   1084 	case MIDI_CTL_CHANGE: /* XXX not correct for MSB */
   1085 		ev = SEQ_MK_CHN(CTL_CHANGE, .device=unit, .channel=chan,
   1086 		    .controller=msg[1], .value=msg[2]);
   1087 		break;
   1088 	case MIDI_PGM_CHANGE:
   1089 		ev = SEQ_MK_CHN(PGM_CHANGE, .device=unit, .channel=chan,
   1090 		    .program=msg[1]);
   1091 		break;
   1092 	case MIDI_CHN_PRESSURE:
   1093 		ev = SEQ_MK_CHN(CHN_PRESSURE, .device=unit, .channel=chan,
   1094 		    .pressure=msg[1]);
   1095 		break;
   1096 	case MIDI_PITCH_BEND:
   1097 		ev = SEQ_MK_CHN(PITCH_BEND, .device=unit, .channel=chan,
   1098 		    .value=(msg[1] & 0x7f) | ((msg[2] & 0x7f) << 7));
   1099 		break;
   1100 	default: /* this is now the point where MIDI_ACKs disappear */
   1101 		return;
   1102 	}
   1103 	seq_event_intr(md->seq, &ev);
   1104 }
   1105 
   1106 struct midi_dev *
   1107 midiseq_open(int unit, int flags)
   1108 {
   1109 	extern struct cfdriver midi_cd;
   1110 	extern const struct cdevsw midi_cdevsw;
   1111 	int error;
   1112 	struct midi_dev *md;
   1113 	struct midi_softc *sc;
   1114 	struct midi_info mi;
   1115 
   1116 	midi_getinfo(makedev(0, unit), &mi);
   1117 	if ( !(mi.props & MIDI_PROP_CAN_INPUT) )
   1118 	        flags &= ~FREAD;
   1119 	if ( 0 == ( flags & ( FREAD | FWRITE ) ) )
   1120 	        return 0;
   1121 	DPRINTFN(2, ("midiseq_open: %d %d\n", unit, flags));
   1122 	error = (*midi_cdevsw.d_open)(makedev(0, unit), flags, 0, 0);
   1123 	if (error)
   1124 		return (0);
   1125 	sc = midi_cd.cd_devs[unit];
   1126 	sc->seqopen = 1;
   1127 	md = malloc(sizeof *md, M_DEVBUF, M_WAITOK|M_ZERO);
   1128 	sc->seq_md = md;
   1129 	md->msc = sc;
   1130 	md->unit = unit;
   1131 	md->name = mi.name;
   1132 	md->subtype = 0;
   1133 	md->nr_voices = 128;	/* XXX */
   1134 	md->instr_bank_size = 128; /* XXX */
   1135 	if (mi.props & MIDI_PROP_CAN_INPUT)
   1136 		md->capabilities |= SYNTH_CAP_INPUT;
   1137 	return (md);
   1138 }
   1139 
   1140 void
   1141 midiseq_close(struct midi_dev *md)
   1142 {
   1143 	extern const struct cdevsw midi_cdevsw;
   1144 
   1145 	DPRINTFN(2, ("midiseq_close: %d\n", md->unit));
   1146 	(*midi_cdevsw.d_close)(makedev(0, md->unit), 0, 0, 0);
   1147 	free(md, M_DEVBUF);
   1148 }
   1149 
   1150 void
   1151 midiseq_reset(struct midi_dev *md)
   1152 {
   1153 	/* XXX send GM reset? */
   1154 	DPRINTFN(3, ("midiseq_reset: %d\n", md->unit));
   1155 }
   1156 
   1157 int
   1158 midiseq_out(struct midi_dev *md, u_char *bf, u_int cc, int chk)
   1159 {
   1160 	DPRINTFN(5, ("midiseq_out: m=%p, unit=%d, bf[0]=0x%02x, cc=%d\n",
   1161 		     md->msc, md->unit, bf[0], cc));
   1162 
   1163 	/* midi(4) does running status compression where appropriate. */
   1164 	return midi_writebytes(md->unit, bf, cc);
   1165 }
   1166 
   1167 /*
   1168  * If the writing process hands us a hidden note-off in a note-on event,
   1169  * we will simply write it that way; no need to special case it here,
   1170  * as midi(4) will always canonicalize or compress as appropriate anyway.
   1171  */
   1172 int
   1173 midiseq_noteon(struct midi_dev *md, int chan, int key, seq_event_t *ev)
   1174 {
   1175 	return midiseq_out(md, (uint8_t[]){
   1176 	    MIDI_NOTEON | chan, key, ev->c_NOTEON.velocity & 0x7f}, 3, 1);
   1177 }
   1178 
   1179 int
   1180 midiseq_noteoff(struct midi_dev *md, int chan, int key, seq_event_t *ev)
   1181 {
   1182 	return midiseq_out(md, (uint8_t[]){
   1183 	    MIDI_NOTEOFF | chan, key, ev->c_NOTEOFF.velocity & 0x7f}, 3, 1);
   1184 }
   1185 
   1186 int
   1187 midiseq_keypressure(struct midi_dev *md, int chan, int key, seq_event_t *ev)
   1188 {
   1189 	return midiseq_out(md, (uint8_t[]){
   1190 	    MIDI_KEY_PRESSURE | chan, key,
   1191 	    ev->c_KEY_PRESSURE.pressure & 0x7f}, 3, 1);
   1192 }
   1193 
   1194 int
   1195 midiseq_pgmchange(struct midi_dev *md, int chan, seq_event_t *ev)
   1196 {
   1197 	if (ev->c_PGM_CHANGE.program > 127)
   1198 		return EINVAL;
   1199 	return midiseq_out(md, (uint8_t[]){
   1200 	    MIDI_PGM_CHANGE | chan, ev->c_PGM_CHANGE.program}, 2, 1);
   1201 }
   1202 
   1203 int
   1204 midiseq_chnpressure(struct midi_dev *md, int chan, seq_event_t *ev)
   1205 {
   1206 	if (ev->c_CHN_PRESSURE.pressure > 127)
   1207 		return EINVAL;
   1208 	return midiseq_out(md, (uint8_t[]){
   1209 	    MIDI_CHN_PRESSURE | chan, ev->c_CHN_PRESSURE.pressure}, 2, 1);
   1210 }
   1211 
   1212 int
   1213 midiseq_ctlchange(struct midi_dev *md, int chan, seq_event_t *ev)
   1214 {
   1215 	if (ev->c_CTL_CHANGE.controller > 127)
   1216 		return EINVAL;
   1217 	return midiseq_out( md, (uint8_t[]){
   1218 	    MIDI_CTL_CHANGE | chan, ev->c_CTL_CHANGE.controller,
   1219 	    ev->c_CTL_CHANGE.value & 0x7f /* XXX this is SO wrong */
   1220 	    }, 3, 1);
   1221 }
   1222 
   1223 int
   1224 midiseq_pitchbend(struct midi_dev *md, int chan, seq_event_t *ev)
   1225 {
   1226 	return midiseq_out(md, (uint8_t[]){
   1227 	    MIDI_PITCH_BEND | chan,
   1228 	    ev->c_PITCH_BEND.value & 0x7f,
   1229 	    (ev->c_PITCH_BEND.value >> 7) & 0x7f}, 3, 1);
   1230 }
   1231 
   1232 int
   1233 midiseq_loadpatch(struct midi_dev *md,
   1234                   struct sysex_info *sysex, struct uio *uio)
   1235 {
   1236 	u_char c, bf[128];
   1237 	int i, cc, error;
   1238 
   1239 	if (sysex->key != SEQ_SYSEX_PATCH) {
   1240 		DPRINTFN(-1,("midiseq_loadpatch: bad patch key 0x%04x\n",
   1241 			     sysex->key));
   1242 		return (EINVAL);
   1243 	}
   1244 	if (uio->uio_resid < sysex->len)
   1245 		/* adjust length, should be an error */
   1246 		sysex->len = uio->uio_resid;
   1247 
   1248 	DPRINTFN(2, ("midiseq_loadpatch: len=%d\n", sysex->len));
   1249 	if (sysex->len == 0)
   1250 		return EINVAL;
   1251 	error = uiomove(&c, 1, uio);
   1252 	if (error)
   1253 		return error;
   1254 	if (c != MIDI_SYSEX_START)		/* must start like this */
   1255 		return EINVAL;
   1256 	error = midiseq_out(md, &c, 1, 0);
   1257 	if (error)
   1258 		return error;
   1259 	--sysex->len;
   1260 	while (sysex->len > 0) {
   1261 		cc = sysex->len;
   1262 		if (cc > sizeof bf)
   1263 			cc = sizeof bf;
   1264 		error = uiomove(bf, cc, uio);
   1265 		if (error)
   1266 			break;
   1267 		for(i = 0; i < cc && !MIDI_IS_STATUS(bf[i]); i++)
   1268 			;
   1269 		/*
   1270 		 * XXX midi(4)'s buffer might not accomodate this, and the
   1271 		 * function will not block us (though in this case we have
   1272 		 * a process and could in principle block).
   1273 		 */
   1274 		error = midiseq_out(md, bf, i, 0);
   1275 		if (error)
   1276 			break;
   1277 		sysex->len -= i;
   1278 		if (i != cc)
   1279 			break;
   1280 	}
   1281 	/*
   1282 	 * Any leftover data in uio is rubbish;
   1283 	 * the SYSEX should be one write ending in SYSEX_END.
   1284 	 */
   1285 	uio->uio_resid = 0;
   1286 	c = MIDI_SYSEX_END;
   1287 	return midiseq_out(md, &c, 1, 0);
   1288 }
   1289 
   1290 #include "midi.h"
   1291 #if NMIDI == 0
   1292 dev_type_open(midiopen);
   1293 dev_type_close(midiclose);
   1294 
   1295 const struct cdevsw midi_cdevsw = {
   1296 	midiopen, midiclose, noread, nowrite, noioctl,
   1297 	nostop, notty, nopoll, nommap,
   1298 };
   1299 
   1300 /*
   1301  * If someone has a sequencer, but no midi devices there will
   1302  * be unresolved references, so we provide little stubs.
   1303  */
   1304 
   1305 int
   1306 midi_unit_count()
   1307 {
   1308 	return (0);
   1309 }
   1310 
   1311 int
   1312 midiopen(dev_t dev, int flags, int ifmt, struct lwp *l)
   1313 {
   1314 	return (ENXIO);
   1315 }
   1316 
   1317 struct cfdriver midi_cd;
   1318 
   1319 void
   1320 midi_getinfo(dev_t dev, struct midi_info *mi)
   1321 {
   1322 }
   1323 
   1324 int
   1325 midiclose(dev_t dev, int flags, int ifmt, struct lwp *l)
   1326 {
   1327 	return (ENXIO);
   1328 }
   1329 
   1330 int
   1331 midi_writebytes(int unit, u_char *bf, int cc)
   1332 {
   1333 	return (ENXIO);
   1334 }
   1335 #endif /* NMIDI == 0 */
   1336