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