Home | History | Annotate | Line # | Download | only in dev
midi.c revision 1.82
      1 /*	$NetBSD: midi.c,v 1.82 2014/12/22 07:02:22 mrg 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), (MIDI FST and Active
      9  * Sense handling) Chapman Flack (chap (at) NetBSD.org), and Andrew Doran.
     10  *
     11  * Redistribution and use in source and binary forms, with or without
     12  * modification, are permitted provided that the following conditions
     13  * are met:
     14  * 1. Redistributions of source code must retain the above copyright
     15  *    notice, this list of conditions and the following disclaimer.
     16  * 2. Redistributions in binary form must reproduce the above copyright
     17  *    notice, this list of conditions and the following disclaimer in the
     18  *    documentation and/or other materials provided with the distribution.
     19  *
     20  * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
     21  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
     22  * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
     23  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
     24  * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
     25  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
     26  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
     27  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
     28  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
     29  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
     30  * POSSIBILITY OF SUCH DAMAGE.
     31  */
     32 
     33 #include <sys/cdefs.h>
     34 __KERNEL_RCSID(0, "$NetBSD: midi.c,v 1.82 2014/12/22 07:02:22 mrg Exp $");
     35 
     36 #include "midi.h"
     37 #include "sequencer.h"
     38 
     39 #include <sys/param.h>
     40 #include <sys/ioctl.h>
     41 #include <sys/fcntl.h>
     42 #include <sys/vnode.h>
     43 #include <sys/select.h>
     44 #include <sys/poll.h>
     45 #include <sys/proc.h>
     46 #include <sys/systm.h>
     47 #include <sys/callout.h>
     48 #include <sys/syslog.h>
     49 #include <sys/kernel.h>
     50 #include <sys/signalvar.h>
     51 #include <sys/conf.h>
     52 #include <sys/audioio.h>
     53 #include <sys/midiio.h>
     54 #include <sys/device.h>
     55 #include <sys/intr.h>
     56 
     57 #include <dev/audio_if.h>
     58 #include <dev/midi_if.h>
     59 #include <dev/midivar.h>
     60 
     61 #if NMIDI > 0
     62 
     63 #ifdef AUDIO_DEBUG
     64 #define DPRINTF(x)	if (mididebug) printf x
     65 #define DPRINTFN(n,x)	if (mididebug >= (n)) printf x
     66 int	mididebug = 0;
     67 /*
     68  *      1: detected protocol errors and buffer overflows
     69  *      2: probe, attach, detach
     70  *      3: open, close
     71  *      4: data received except realtime
     72  *      5: ioctl
     73  *      6: read, write, poll
     74  *      7: data transmitted
     75  *      8: uiomoves, synchronization
     76  *      9: realtime data received
     77  */
     78 #else
     79 #define DPRINTF(x)
     80 #define DPRINTFN(n,x)
     81 #endif
     82 
     83 static	struct midi_softc *hwif_softc = NULL;
     84 static	kmutex_t hwif_softc_lock;
     85 
     86 static void	midi_in(void *, int);
     87 static void	midi_out(void *);
     88 static int	midi_poll_out(struct midi_softc *);
     89 static int	midi_intr_out(struct midi_softc *);
     90 static int 	midi_msg_out(struct midi_softc *, u_char **, u_char **,
     91 			     u_char **, u_char **);
     92 static int	midi_start_output(struct midi_softc *);
     93 static void	midi_initbuf(struct midi_buffer *);
     94 static void	midi_xmt_asense(void *);
     95 static void	midi_rcv_asense(void *);
     96 static void	midi_softint(void *);
     97 
     98 static int	midiprobe(device_t, cfdata_t, void *);
     99 static void	midiattach(device_t, device_t, void *);
    100 int		mididetach(device_t, int);
    101 static int	midiactivate(device_t, enum devact);
    102 
    103 static dev_type_open(midiopen);
    104 static dev_type_close(midiclose);
    105 static dev_type_read(midiread);
    106 static dev_type_write(midiwrite);
    107 static dev_type_ioctl(midiioctl);
    108 static dev_type_poll(midipoll);
    109 static dev_type_kqfilter(midikqfilter);
    110 
    111 const struct cdevsw midi_cdevsw = {
    112 	.d_open = midiopen,
    113 	.d_close = midiclose,
    114 	.d_read = midiread,
    115 	.d_write = midiwrite,
    116 	.d_ioctl = midiioctl,
    117 	.d_stop = nostop,
    118 	.d_tty = notty,
    119 	.d_poll = midipoll,
    120 	.d_mmap = nommap,
    121 	.d_kqfilter = midikqfilter,
    122 	.d_discard = nodiscard,
    123 	.d_flag = D_OTHER | D_MPSAFE
    124 };
    125 
    126 CFATTACH_DECL_NEW(midi, sizeof(struct midi_softc),
    127     midiprobe, midiattach, mididetach, midiactivate);
    128 
    129 #define MIDI_XMT_ASENSE_PERIOD mstohz(275)
    130 #define MIDI_RCV_ASENSE_PERIOD mstohz(300)
    131 
    132 extern struct cfdriver midi_cd;
    133 
    134 static int
    135 midiprobe(device_t parent, cfdata_t match, void *aux)
    136 {
    137 	struct audio_attach_args *sa;
    138 
    139 	sa = aux;
    140 
    141 	DPRINTFN(2,("midiprobe: type=%d sa=%p hw=%p\n", sa->type, sa,
    142 	    sa->hwif));
    143 
    144 	return sa->type == AUDIODEV_TYPE_MIDI;
    145 }
    146 
    147 static void
    148 midiattach(device_t parent, device_t self, void *aux)
    149 {
    150 	struct midi_softc *sc = device_private(self);
    151 	struct audio_attach_args *sa = aux;
    152 	const struct midi_hw_if *hwp;
    153 	void *hdlp;
    154 
    155 	hwp = sa->hwif;
    156 	hdlp = sa->hdl;
    157 
    158 	aprint_naive("\n");
    159 
    160 	DPRINTFN(2, ("MIDI attach\n"));
    161 
    162 #ifdef DIAGNOSTIC
    163 	if (hwp == 0 ||
    164 	    hwp->open == 0 ||
    165 	    hwp->close == 0 ||
    166 	    hwp->output == 0 ||
    167 	    hwp->getinfo == 0) {
    168 		printf("midi: missing method\n");
    169 		return;
    170 	}
    171 #endif
    172 
    173 	sc->dev = self;
    174 	sc->hw_if = hwp;
    175 	sc->hw_hdl = hdlp;
    176 	midi_attach(sc);
    177 }
    178 
    179 static int
    180 midiactivate(device_t self, enum devact act)
    181 {
    182 	struct midi_softc *sc = device_private(self);
    183 
    184 	switch (act) {
    185 	case DVACT_DEACTIVATE:
    186 		mutex_enter(sc->lock);
    187 		sc->dying = 1;
    188 		mutex_exit(sc->lock);
    189 		return 0;
    190 	default:
    191 		return EOPNOTSUPP;
    192 	}
    193 }
    194 
    195 int
    196 mididetach(device_t self, int flags)
    197 {
    198 	struct midi_softc *sc = device_private(self);
    199 	int maj, mn;
    200 
    201 	DPRINTFN(2,("%s: sc=%p flags=%d\n", __func__, sc, flags));
    202 
    203 	pmf_device_deregister(self);
    204 
    205 	mutex_enter(sc->lock);
    206 	sc->dying = 1;
    207 
    208 	if (--sc->refcnt >= 0) {
    209 		/* Wake anything? */
    210 		(void)cv_timedwait(&sc->detach_cv, sc->lock, hz * 60);
    211 	}
    212 	cv_broadcast(&sc->wchan);
    213 	cv_broadcast(&sc->rchan);
    214 	mutex_exit(sc->lock);
    215 
    216 	/* locate the major number */
    217 	maj = cdevsw_lookup_major(&midi_cdevsw);
    218 
    219 	/*
    220 	 * Nuke the vnodes for any open instances (calls close).
    221 	 * Will wait until any activity on the device nodes has ceased.
    222 	 *
    223 	 * XXXAD NOT YET.
    224 	 *
    225 	 * XXXAD NEED TO PREVENT NEW REFERENCES THROUGH AUDIO_ENTER().
    226 	 */
    227 	mn = device_unit(self);
    228 	vdevgone(maj, mn, mn, VCHR);
    229 
    230 	if (!(sc->props & MIDI_PROP_NO_OUTPUT)) {
    231 		evcnt_detach(&sc->xmt.bytesDiscarded);
    232 		evcnt_detach(&sc->xmt.incompleteMessages);
    233 	}
    234 	if (sc->props & MIDI_PROP_CAN_INPUT) {
    235 		evcnt_detach(&sc->rcv.bytesDiscarded);
    236 		evcnt_detach(&sc->rcv.incompleteMessages);
    237 	}
    238 
    239 	if (sc->sih != NULL) {
    240 		softint_disestablish(sc->sih);
    241 		sc->sih = NULL;
    242 	}
    243 
    244 	mutex_enter(sc->lock);
    245 	callout_halt(&sc->xmt_asense_co, sc->lock);
    246 	callout_halt(&sc->rcv_asense_co, sc->lock);
    247 	mutex_exit(sc->lock);
    248 
    249 	callout_destroy(&sc->xmt_asense_co);
    250 	callout_destroy(&sc->rcv_asense_co);
    251 
    252 	cv_destroy(&sc->wchan);
    253 	cv_destroy(&sc->rchan);
    254 	cv_destroy(&sc->detach_cv);
    255 
    256 	return (0);
    257 }
    258 
    259 void
    260 midi_attach(struct midi_softc *sc)
    261 {
    262 	struct midi_info mi;
    263 	kmutex_t *dummy;
    264 	static int first = 1;
    265 
    266 	if (first) {
    267 		mutex_init(&hwif_softc_lock, MUTEX_DEFAULT, IPL_NONE);
    268 		first = 0;
    269 	}
    270 
    271 	sc->hw_if->get_locks(sc->hw_hdl, &sc->lock, &dummy);
    272 
    273 	callout_init(&sc->xmt_asense_co, CALLOUT_MPSAFE);
    274 	callout_init(&sc->rcv_asense_co, CALLOUT_MPSAFE);
    275 	callout_setfunc(&sc->xmt_asense_co, midi_xmt_asense, sc);
    276 	callout_setfunc(&sc->rcv_asense_co, midi_rcv_asense, sc);
    277 
    278 	sc->sih = softint_establish(SOFTINT_CLOCK | SOFTINT_MPSAFE,
    279 	    midi_softint, sc);
    280 
    281 	cv_init(&sc->rchan, "midird");
    282 	cv_init(&sc->wchan, "midiwr");
    283 	cv_init(&sc->detach_cv, "mididet");
    284 
    285 	sc->dying = 0;
    286 	sc->isopen = 0;
    287 	sc->refcnt = 0;
    288 
    289 	mutex_enter(&hwif_softc_lock);
    290 	mutex_enter(sc->lock);
    291 	hwif_softc = sc;
    292 	sc->hw_if->getinfo(sc->hw_hdl, &mi);
    293 	hwif_softc = NULL;
    294 	mutex_exit(sc->lock);
    295 	mutex_exit(&hwif_softc_lock);
    296 
    297 	sc->props = mi.props;
    298 
    299 	if (!(sc->props & MIDI_PROP_NO_OUTPUT)) {
    300 		evcnt_attach_dynamic(&sc->xmt.bytesDiscarded,
    301 			EVCNT_TYPE_MISC, NULL,
    302 			device_xname(sc->dev), "xmt bytes discarded");
    303 		evcnt_attach_dynamic(&sc->xmt.incompleteMessages,
    304 			EVCNT_TYPE_MISC, NULL,
    305 			device_xname(sc->dev), "xmt incomplete msgs");
    306 	}
    307 	if (sc->props & MIDI_PROP_CAN_INPUT) {
    308 		evcnt_attach_dynamic(&sc->rcv.bytesDiscarded,
    309 			EVCNT_TYPE_MISC, NULL,
    310 			device_xname(sc->dev), "rcv bytes discarded");
    311 		evcnt_attach_dynamic(&sc->rcv.incompleteMessages,
    312 			EVCNT_TYPE_MISC, NULL,
    313 			device_xname(sc->dev), "rcv incomplete msgs");
    314 	}
    315 
    316 	aprint_naive("\n");
    317 	aprint_normal(": %s\n", mi.name);
    318 
    319 	if (!pmf_device_register(sc->dev, NULL, NULL))
    320 		aprint_error_dev(sc->dev, "couldn't establish power handler\n");
    321 }
    322 
    323 void
    324 midi_register_hw_if_ext(struct midi_hw_if_ext *exthw)
    325 {
    326 	if (hwif_softc != NULL) /* ignore calls resulting from non-init */
    327 		hwif_softc->hw_if_ext = exthw; /* uses of getinfo */
    328 }
    329 
    330 int
    331 midi_unit_count(void)
    332 {
    333 	int i;
    334 	for ( i = 0; i < midi_cd.cd_ndevs; ++i)
    335 	        if (NULL == device_lookup(&midi_cd, i))
    336 		        break;
    337         return i;
    338 }
    339 
    340 static void
    341 midi_initbuf(struct midi_buffer *mb)
    342 {
    343 	mb->idx_producerp = mb->idx_consumerp = mb->idx;
    344 	mb->buf_producerp = mb->buf_consumerp = mb->buf;
    345 }
    346 
    347 #define PACK_MB_IDX(cat,len) (((cat)<<4)|(len))
    348 #define MB_IDX_CAT(idx) ((idx)>>4)
    349 #define MB_IDX_LEN(idx) ((idx)&0xf)
    350 
    351 static char const midi_cats[] = "\0\0\0\0\0\0\0\0\2\2\2\2\1\1\2\3";
    352 #define MIDI_CAT(d) (midi_cats[((d)>>4)&15])
    353 #define FST_RETURN(offp,endp,ret) \
    354 	return (s->pos=s->msg+(offp)), (s->end=s->msg+(endp)), (ret)
    355 
    356 enum fst_ret { FST_CHN, FST_CHV, FST_COM, FST_SYX, FST_RT, FST_MORE, FST_ERR,
    357                FST_HUH, FST_SXP };
    358 enum fst_form { FST_CANON, FST_COMPR, FST_VCOMP };
    359 static struct {
    360 	int off;
    361 	enum fst_ret tag;
    362 } const midi_forms[] = {
    363 	[FST_CANON] = { .off=0, .tag=FST_CHN },
    364 	[FST_COMPR] = { .off=1, .tag=FST_CHN },
    365 	[FST_VCOMP] = { .off=0, .tag=FST_CHV }
    366 };
    367 #define FST_CRETURN(endp) \
    368 	FST_RETURN(midi_forms[form].off,endp,midi_forms[form].tag)
    369 
    370 /*
    371  * A MIDI finite state transducer suitable for receiving or transmitting. It
    372  * will accept correct MIDI input that uses, doesn't use, or sometimes uses the
    373  * 'running status' compression technique, and transduce it to fully expanded
    374  * (form=FST_CANON) or fully compressed (form=FST_COMPR or FST_VCOMP) form.
    375  *
    376  * Returns FST_MORE if a complete message has not been parsed yet (SysEx
    377  * messages are the exception), FST_ERR or FST_HUH if the input does not
    378  * conform to the protocol, or FST_CHN (channel messages), FST_COM (System
    379  * Common messages), FST_RT (System Real-Time messages), or FST_SYX (System
    380  * Exclusive) to broadly categorize the message parsed. s->pos and s->end
    381  * locate the parsed message; while (s->pos<s->end) putchar(*(s->pos++));
    382  * would output it.
    383  *
    384  * FST_HUH means the character c wasn't valid in the original state, but the
    385  * state has now been reset to START and the caller should try again passing
    386  * the same c. FST_ERR means c isn't valid in the start state; the caller
    387  * should kiss it goodbye and continue to try successive characters from the
    388  * input until something other than FST_ERR or FST_HUH is returned, at which
    389  * point things are resynchronized.
    390  *
    391  * A FST_SYX return means that between pos and end are from 1 to 3
    392  * bytes of a system exclusive message. A SysEx message will be delivered in
    393  * one or more chunks of that form, where the first begins with 0xf0 and the
    394  * last (which is the only one that might have length < 3) ends with 0xf7.
    395  *
    396  * Messages corrupted by a protocol error are discarded and won't be seen at
    397  * all; again SysEx is the exception, as one or more chunks of it may already
    398  * have been parsed.
    399  *
    400  * For FST_CHN messages, s->msg[0] always contains the status byte even if
    401  * FST_COMPR form was requested (pos then points to msg[1]). That way, the
    402  * caller can always identify the exact message if there is a need to do so.
    403  * For all other message types except FST_SYX, the status byte is at *pos
    404  * (which may not necessarily be msg[0]!). There is only one SysEx status
    405  * byte, so the return value FST_SYX is sufficient to identify it.
    406  *
    407  * To simplify some use cases, compression can also be requested with
    408  * form=FST_VCOMP. In this form a compressible channel message is indicated
    409  * by returning a classification of FST_CHV instead of FST_CHN, and pos points
    410  * to the status byte rather than being advanced past it. If the caller in this
    411  * case saves the bytes from pos to end, it will have saved the entire message,
    412  * and can act on the FST_CHV tag to drop the first byte later. In this form,
    413  * unlike FST_CANON, hidden note-off (i.e. note-on with velocity 0) may occur.
    414  *
    415  * Two obscure points in the MIDI protocol complicate things further, both to
    416  * do with the EndSysEx code, 0xf7. First, this code is permitted (and
    417  * meaningless) outside of a System Exclusive message, anywhere a status byte
    418  * could appear. Second, it is allowed to be absent at the end of a System
    419  * Exclusive message (!) - any status byte at all (non-realtime) is allowed to
    420  * terminate the message. Both require accomodation in the interface to
    421  * midi_fst's caller. A stray 0xf7 should be ignored BUT should count as a
    422  * message received for purposes of Active Sense timeout; the case is
    423  * represented by a return of FST_COM with a length of zero (pos == end). A
    424  * status byte other than 0xf7 during a system exclusive message will cause an
    425  * FST_SXP (sysex plus) return; the bytes from pos to end are the end of the
    426  * system exclusive message, and after handling those the caller should call
    427  * midi_fst again with the same input byte.
    428  *
    429  * midi(4) will never produce either such form of rubbish.
    430  */
    431 static enum fst_ret
    432 midi_fst(struct midi_state *s, u_char c, enum fst_form form)
    433 {
    434 	int syxpos = 0;
    435 
    436 	if (c >= 0xf8) { /* All realtime messages bypass state machine */
    437 	        if (c == 0xf9 || c == 0xfd) {
    438 			DPRINTF( ("midi_fst: s=%p c=0x%02x undefined\n",
    439 			    s, c));
    440 			s->bytesDiscarded.ev_count++;
    441 			return FST_ERR;
    442 		}
    443 		DPRINTFN(9, ("midi_fst: s=%p System Real-Time data=0x%02x\n",
    444 		    s, c));
    445 		s->msg[2] = c;
    446 		FST_RETURN(2,3,FST_RT);
    447 	}
    448 
    449 	DPRINTFN(4, ("midi_fst: s=%p data=0x%02x state=%d\n",
    450 	    s, c, s->state));
    451 
    452         switch (s->state | MIDI_CAT(c)) { /* break ==> return FST_MORE */
    453 	case MIDI_IN_START  | MIDI_CAT_COMMON:
    454 	case MIDI_IN_RUN1_1 | MIDI_CAT_COMMON:
    455 	case MIDI_IN_RUN2_2 | MIDI_CAT_COMMON:
    456 	case MIDI_IN_RXX2_2 | MIDI_CAT_COMMON:
    457 	        s->msg[0] = c;
    458 	        switch ( c) {
    459 		case 0xf0: s->state = MIDI_IN_SYX1_3; break;
    460 		case 0xf1: s->state = MIDI_IN_COM0_1; break;
    461 		case 0xf2: s->state = MIDI_IN_COM0_2; break;
    462 		case 0xf3: s->state = MIDI_IN_COM0_1; break;
    463 		case 0xf6: s->state = MIDI_IN_START;  FST_RETURN(0,1,FST_COM);
    464 		case 0xf7: s->state = MIDI_IN_START;  FST_RETURN(0,0,FST_COM);
    465 		default: goto protocol_violation;
    466 		}
    467 		break;
    468 
    469 	case MIDI_IN_RUN1_1 | MIDI_CAT_STATUS1:
    470 		if (c == s->msg[0]) {
    471 			s->state = MIDI_IN_RNX0_1;
    472 			break;
    473 		}
    474 		/* FALLTHROUGH */
    475 	case MIDI_IN_RUN2_2 | MIDI_CAT_STATUS1:
    476 	case MIDI_IN_RXX2_2 | MIDI_CAT_STATUS1:
    477 	case MIDI_IN_START  | MIDI_CAT_STATUS1:
    478 	        s->state = MIDI_IN_RUN0_1;
    479 	        s->msg[0] = c;
    480 		break;
    481 
    482 	case MIDI_IN_RUN2_2 | MIDI_CAT_STATUS2:
    483 	case MIDI_IN_RXX2_2 | MIDI_CAT_STATUS2:
    484 		if (c == s->msg[0]) {
    485 			s->state = MIDI_IN_RNX0_2;
    486 			break;
    487 		}
    488 		if ((c ^ s->msg[0]) == 0x10 && (c & 0xe0) == 0x80) {
    489 			s->state = MIDI_IN_RXX0_2;
    490 			s->msg[0] = c;
    491 			break;
    492 		}
    493 		/* FALLTHROUGH */
    494 	case MIDI_IN_RUN1_1 | MIDI_CAT_STATUS2:
    495 	case MIDI_IN_START  | MIDI_CAT_STATUS2:
    496 	        s->state = MIDI_IN_RUN0_2;
    497 	        s->msg[0] = c;
    498 		break;
    499 
    500         case MIDI_IN_COM0_1 | MIDI_CAT_DATA:
    501 		s->state = MIDI_IN_START;
    502 	        s->msg[1] = c;
    503 		FST_RETURN(0,2,FST_COM);
    504 
    505         case MIDI_IN_COM0_2 | MIDI_CAT_DATA:
    506 	        s->state = MIDI_IN_COM1_2;
    507 	        s->msg[1] = c;
    508 		break;
    509 
    510         case MIDI_IN_COM1_2 | MIDI_CAT_DATA:
    511 		s->state = MIDI_IN_START;
    512 	        s->msg[2] = c;
    513 		FST_RETURN(0,3,FST_COM);
    514 
    515         case MIDI_IN_RUN0_1 | MIDI_CAT_DATA:
    516 		s->state = MIDI_IN_RUN1_1;
    517 	        s->msg[1] = c;
    518 		FST_RETURN(0,2,FST_CHN);
    519 
    520         case MIDI_IN_RUN1_1 | MIDI_CAT_DATA:
    521         case MIDI_IN_RNX0_1 | MIDI_CAT_DATA:
    522 		s->state = MIDI_IN_RUN1_1;
    523 	        s->msg[1] = c;
    524 		FST_CRETURN(2);
    525 
    526         case MIDI_IN_RUN0_2 | MIDI_CAT_DATA:
    527 	        s->state = MIDI_IN_RUN1_2;
    528 	        s->msg[1] = c;
    529 		break;
    530 
    531         case MIDI_IN_RUN1_2 | MIDI_CAT_DATA:
    532 		if (FST_CANON == form && 0 == c && (s->msg[0]&0xf0) == 0x90) {
    533 			s->state = MIDI_IN_RXX2_2;
    534 			s->msg[0] ^= 0x10;
    535 			s->msg[2] = 64;
    536 		} else {
    537 			s->state = MIDI_IN_RUN2_2;
    538 	        	s->msg[2] = c;
    539 		}
    540 		FST_RETURN(0,3,FST_CHN);
    541 
    542         case MIDI_IN_RUN2_2 | MIDI_CAT_DATA:
    543 	        s->state = MIDI_IN_RNX1_2;
    544 	        s->msg[1] = c;
    545 		break;
    546 
    547         case MIDI_IN_RXX2_2 | MIDI_CAT_DATA:
    548 	        s->state = MIDI_IN_RXX1_2;
    549 		s->msg[0] ^= 0x10;
    550 	        s->msg[1] = c;
    551 		break;
    552 
    553         case MIDI_IN_RNX0_2 | MIDI_CAT_DATA:
    554 	        s->state = MIDI_IN_RNY1_2;
    555 	        s->msg[1] = c;
    556 		break;
    557 
    558         case MIDI_IN_RXX0_2 | MIDI_CAT_DATA:
    559 	        s->state = MIDI_IN_RXY1_2;
    560 	        s->msg[1] = c;
    561 		break;
    562 
    563         case MIDI_IN_RNX1_2 | MIDI_CAT_DATA:
    564         case MIDI_IN_RNY1_2 | MIDI_CAT_DATA:
    565 		if (FST_CANON == form && 0 == c && (s->msg[0]&0xf0) == 0x90) {
    566 			s->state = MIDI_IN_RXX2_2;
    567 			s->msg[0] ^= 0x10;
    568 			s->msg[2] = 64;
    569 			FST_RETURN(0,3,FST_CHN);
    570 		}
    571 		s->state = MIDI_IN_RUN2_2;
    572 	        s->msg[2] = c;
    573 		FST_CRETURN(3);
    574 
    575         case MIDI_IN_RXX1_2 | MIDI_CAT_DATA:
    576         case MIDI_IN_RXY1_2 | MIDI_CAT_DATA:
    577 		if (( 0 == c && (s->msg[0]&0xf0) == 0x90)
    578 		  || (64 == c && (s->msg[0]&0xf0) == 0x80
    579 		      && FST_CANON != form)) {
    580 			s->state = MIDI_IN_RXX2_2;
    581 			s->msg[0] ^= 0x10;
    582 			s->msg[2] = 64 - c;
    583 			FST_CRETURN(3);
    584 		}
    585 		s->state = MIDI_IN_RUN2_2;
    586 	        s->msg[2] = c;
    587 		FST_RETURN(0,3,FST_CHN);
    588 
    589         case MIDI_IN_SYX1_3 | MIDI_CAT_DATA:
    590 		s->state = MIDI_IN_SYX2_3;
    591 	        s->msg[1] = c;
    592 		break;
    593 
    594         case MIDI_IN_SYX2_3 | MIDI_CAT_DATA:
    595 		s->state = MIDI_IN_SYX0_3;
    596 	        s->msg[2] = c;
    597 		FST_RETURN(0,3,FST_SYX);
    598 
    599         case MIDI_IN_SYX0_3 | MIDI_CAT_DATA:
    600 		s->state = MIDI_IN_SYX1_3;
    601 	        s->msg[0] = c;
    602 		break;
    603 
    604         case MIDI_IN_SYX2_3 | MIDI_CAT_COMMON:
    605         case MIDI_IN_SYX2_3 | MIDI_CAT_STATUS1:
    606         case MIDI_IN_SYX2_3 | MIDI_CAT_STATUS2:
    607 		++ syxpos;
    608 		/* FALLTHROUGH */
    609         case MIDI_IN_SYX1_3 | MIDI_CAT_COMMON:
    610         case MIDI_IN_SYX1_3 | MIDI_CAT_STATUS1:
    611         case MIDI_IN_SYX1_3 | MIDI_CAT_STATUS2:
    612 		++ syxpos;
    613 		/* FALLTHROUGH */
    614         case MIDI_IN_SYX0_3 | MIDI_CAT_COMMON:
    615         case MIDI_IN_SYX0_3 | MIDI_CAT_STATUS1:
    616         case MIDI_IN_SYX0_3 | MIDI_CAT_STATUS2:
    617 		s->state = MIDI_IN_START;
    618 	        if (c == 0xf7) {
    619 			s->msg[syxpos] = c;
    620 		        FST_RETURN(0,1+syxpos,FST_SYX);
    621 		}
    622 		s->msg[syxpos] = 0xf7;
    623 		FST_RETURN(0,1+syxpos,FST_SXP);
    624 
    625         default:
    626 protocol_violation:
    627                 DPRINTF(("midi_fst: unexpected %#02x in state %u\n",
    628 		    c, s->state));
    629 		switch ( s->state) {
    630 		case MIDI_IN_RUN1_1: /* can only get here by seeing an */
    631 		case MIDI_IN_RUN2_2: /* INVALID System Common message */
    632 		case MIDI_IN_RXX2_2:
    633 		        s->state = MIDI_IN_START;
    634 			/* FALLTHROUGH */
    635 		case MIDI_IN_START:
    636 			s->bytesDiscarded.ev_count++;
    637 			return FST_ERR;
    638 		case MIDI_IN_COM1_2:
    639 		case MIDI_IN_RUN1_2:
    640 		case MIDI_IN_RNY1_2:
    641 		case MIDI_IN_RXY1_2:
    642 			s->bytesDiscarded.ev_count++;
    643 			/* FALLTHROUGH */
    644 		case MIDI_IN_COM0_1:
    645 		case MIDI_IN_RUN0_1:
    646 		case MIDI_IN_RNX0_1:
    647 		case MIDI_IN_COM0_2:
    648 		case MIDI_IN_RUN0_2:
    649 		case MIDI_IN_RNX0_2:
    650 		case MIDI_IN_RXX0_2:
    651 		case MIDI_IN_RNX1_2:
    652 		case MIDI_IN_RXX1_2:
    653 			s->bytesDiscarded.ev_count++;
    654 		        s->incompleteMessages.ev_count++;
    655 			break;
    656 		default:
    657 		        DPRINTF(("midi_fst: mishandled %#02x(%u) in state %u?!\n",
    658 			    c, MIDI_CAT(c), s->state));
    659 			break;
    660 		}
    661 		s->state = MIDI_IN_START;
    662 		return FST_HUH;
    663 	}
    664 	return FST_MORE;
    665 }
    666 
    667 static void
    668 midi_softint(void *cookie)
    669 {
    670 	struct midi_softc *sc;
    671 	proc_t *p;
    672 	pid_t pid;
    673 
    674 	sc = cookie;
    675 
    676 	mutex_enter(proc_lock);
    677 	pid = sc->async;
    678 	if (pid != 0 && (p = proc_find(pid)) != NULL)
    679 		psignal(p, SIGIO);
    680 	mutex_exit(proc_lock);
    681 }
    682 
    683 static void
    684 midi_in(void *addr, int data)
    685 {
    686 	struct midi_softc *sc;
    687 	struct midi_buffer *mb;
    688 	int i, count;
    689 	enum fst_ret got;
    690 	MIDI_BUF_DECLARE(idx);
    691 	MIDI_BUF_DECLARE(buf);
    692 
    693 	sc = addr;
    694 	mb = &sc->inbuf;
    695 
    696 	KASSERT(mutex_owned(sc->lock));
    697 
    698 	if (!sc->isopen)
    699 		return;
    700 
    701 	if ((sc->flags & FREAD) == 0)
    702 		return;		/* discard data if not reading */
    703 
    704 sxp_again:
    705 	do {
    706 		got = midi_fst(&sc->rcv, data, FST_CANON);
    707 	} while (got == FST_HUH);
    708 
    709 	switch (got) {
    710 	case FST_MORE:
    711 	case FST_ERR:
    712 		return;
    713 	case FST_CHN:
    714 	case FST_COM:
    715 	case FST_RT:
    716 #if NSEQUENCER > 0
    717 		if (sc->seqopen) {
    718 			extern void midiseq_in(struct midi_dev *,u_char *,int);
    719 			count = sc->rcv.end - sc->rcv.pos;
    720 			midiseq_in(sc->seq_md, sc->rcv.pos, count);
    721 			return;
    722 		}
    723 #endif
    724         	/*
    725 		 * Pass Active Sense to the sequencer if it's open, but not to
    726 		 * a raw reader. (Really should do something intelligent with
    727 		 * it then, though....)
    728 		 */
    729 		if (got == FST_RT && MIDI_ACK == sc->rcv.pos[0]) {
    730 			if (!sc->rcv_expect_asense) {
    731 				sc->rcv_expect_asense = 1;
    732 				callout_schedule(&sc->rcv_asense_co,
    733 				    MIDI_RCV_ASENSE_PERIOD);
    734 			}
    735 			sc->rcv_quiescent = 0;
    736 			sc->rcv_eof = 0;
    737 			return;
    738 		}
    739 		/* FALLTHROUGH */
    740 	/*
    741 	 * Ultimately SysEx msgs should be offered to the sequencer also; the
    742 	 * sequencer API addresses them - but maybe our sequencer can't handle
    743 	 * them yet, so offer only to raw reader. (Which means, ultimately,
    744 	 * discard them if the sequencer's open, as it's not doing reads!)
    745 	 * -> When SysEx support is added to the sequencer, be sure to handle
    746 	 *    FST_SXP there too.
    747 	 */
    748 	case FST_SYX:
    749 	case FST_SXP:
    750 		count = sc->rcv.end - sc->rcv.pos;
    751 		sc->rcv_quiescent = 0;
    752 		sc->rcv_eof = 0;
    753 		if (0 == count)
    754 			break;
    755 		MIDI_BUF_PRODUCER_INIT(mb,idx);
    756 		MIDI_BUF_PRODUCER_INIT(mb,buf);
    757 		if (count > buf_lim - buf_cur
    758 		     || 1 > idx_lim - idx_cur) {
    759 			sc->rcv.bytesDiscarded.ev_count += count;
    760 			DPRINTF(("midi_in: buffer full, discard data=0x%02x\n",
    761 				 sc->rcv.pos[0]));
    762 			return;
    763 		}
    764 		for (i = 0; i < count; i++) {
    765 			*buf_cur++ = sc->rcv.pos[i];
    766 			MIDI_BUF_WRAP(buf);
    767 		}
    768 		*idx_cur++ = PACK_MB_IDX(got,count);
    769 		MIDI_BUF_WRAP(idx);
    770 		MIDI_BUF_PRODUCER_WBACK(mb,buf);
    771 		MIDI_BUF_PRODUCER_WBACK(mb,idx);
    772 		cv_broadcast(&sc->rchan);
    773 		selnotify(&sc->rsel, 0, NOTE_SUBMIT);
    774 		if (sc->async != 0)
    775 			softint_schedule(sc->sih);
    776 		break;
    777 	default: /* don't #ifdef this away, gcc will say FST_HUH not handled */
    778 		printf("midi_in: midi_fst returned %d?!\n", got);
    779 	}
    780 	if (FST_SXP == got)
    781 		goto sxp_again;
    782 }
    783 
    784 static void
    785 midi_out(void *addr)
    786 {
    787 	struct midi_softc *sc = addr;
    788 
    789 	KASSERT(mutex_owned(sc->lock));
    790 
    791 	if (!sc->isopen)
    792 		return;
    793 	DPRINTFN(8, ("midi_out: %p\n", sc));
    794 	midi_intr_out(sc);
    795 }
    796 
    797 static int
    798 midiopen(dev_t dev, int flags, int ifmt, struct lwp *l)
    799 {
    800 	struct midi_softc *sc;
    801 	const struct midi_hw_if *hw;
    802 	int error;
    803 
    804 	sc = device_lookup_private(&midi_cd, MIDIUNIT(dev));
    805 	if (sc == NULL)
    806 		return (ENXIO);
    807 	DPRINTFN(3,("midiopen %p\n", sc));
    808 
    809 	mutex_enter(sc->lock);
    810 	if (sc->dying) {
    811 		mutex_exit(sc->lock);
    812 		return (EIO);
    813 	}
    814 	hw = sc->hw_if;
    815 	if (hw == NULL) {
    816 		mutex_exit(sc->lock);
    817 		return ENXIO;
    818 	}
    819 	if (sc->isopen) {
    820 		mutex_exit(sc->lock);
    821 		return EBUSY;
    822 	}
    823 
    824 	/* put both state machines into known states */
    825 	sc->rcv.state = MIDI_IN_START;
    826 	sc->rcv.pos = sc->rcv.msg;
    827 	sc->rcv.end = sc->rcv.msg;
    828 	sc->xmt.state = MIDI_IN_START;
    829 	sc->xmt.pos = sc->xmt.msg;
    830 	sc->xmt.end = sc->xmt.msg;
    831 
    832 	/* copy error counters so an ioctl (TBA) can give since-open stats */
    833 	sc->rcv.atOpen.bytesDiscarded  = sc->rcv.bytesDiscarded.ev_count;
    834 	sc->rcv.atQuery.bytesDiscarded = sc->rcv.bytesDiscarded.ev_count;
    835 
    836 	sc->xmt.atOpen.bytesDiscarded  = sc->xmt.bytesDiscarded.ev_count;
    837 	sc->xmt.atQuery.bytesDiscarded = sc->xmt.bytesDiscarded.ev_count;
    838 
    839 	/* and the buffers */
    840 	midi_initbuf(&sc->outbuf);
    841 	midi_initbuf(&sc->inbuf);
    842 
    843 	/* and the receive flags */
    844 	sc->rcv_expect_asense = 0;
    845 	sc->rcv_quiescent = 0;
    846 	sc->rcv_eof = 0;
    847 	sc->isopen++;
    848 	sc->flags = flags;
    849 	sc->pbus = 0;
    850 	sc->async = 0;
    851 
    852 #ifdef MIDI_SAVE
    853 	if (midicnt != 0) {
    854 		midisave.cnt = midicnt;
    855 		midicnt = 0;
    856 	}
    857 #endif
    858 
    859 	error = hw->open(sc->hw_hdl, flags, midi_in, midi_out, sc);
    860 	if (error) {
    861 		mutex_exit(sc->lock);
    862 		return error;
    863 	}
    864 
    865 	mutex_exit(sc->lock);
    866 	return 0;
    867 }
    868 
    869 static int
    870 midiclose(dev_t dev, int flags, int ifmt, struct lwp *l)
    871 {
    872 	struct midi_softc *sc;
    873 	const struct midi_hw_if *hw;
    874 
    875 	sc = device_lookup_private(&midi_cd, MIDIUNIT(dev));
    876 	hw = sc->hw_if;
    877 
    878 	DPRINTFN(3,("midiclose %p\n", sc));
    879 
    880 	mutex_enter(sc->lock);
    881 	/* midi_start_output(sc); anything buffered => pbus already set! */
    882 	while (sc->pbus) {
    883 		DPRINTFN(8,("midiclose sleep ...\n"));
    884 		cv_wait(&sc->wchan, sc->lock);
    885 	}
    886 	sc->isopen = 0;
    887 	callout_halt(&sc->xmt_asense_co, sc->lock);
    888 	callout_halt(&sc->rcv_asense_co, sc->lock);
    889 	hw->close(sc->hw_hdl);
    890 	sc->seqopen = 0;
    891 	sc->seq_md = 0;
    892 	mutex_exit(sc->lock);
    893 
    894 	return 0;
    895 }
    896 
    897 static int
    898 midiread(dev_t dev, struct uio *uio, int ioflag)
    899 {
    900 	struct midi_softc *sc;
    901 	struct midi_buffer *mb;
    902 	int appetite, error, first;
    903 	MIDI_BUF_DECLARE(idx);
    904 	MIDI_BUF_DECLARE(buf);
    905 
    906 	sc = device_lookup_private(&midi_cd, MIDIUNIT(dev));
    907 	mb = &sc->inbuf;
    908 	first = 1;
    909 
    910 	DPRINTFN(6,("midiread: %p, count=%lu\n", sc,
    911 	    (unsigned long)uio->uio_resid));
    912 
    913 	mutex_enter(sc->lock);
    914 	if (sc->dying) {
    915 		mutex_exit(sc->lock);
    916 		return EIO;
    917 	}
    918 	if ((sc->props & MIDI_PROP_CAN_INPUT) == 0) {
    919 		mutex_exit(sc->lock);
    920 		return ENXIO;
    921 	}
    922 	MIDI_BUF_CONSUMER_INIT(mb,idx);
    923 	MIDI_BUF_CONSUMER_INIT(mb,buf);
    924 	error = 0;
    925 	for (;;) {
    926 		/*
    927 		 * If the used portion of idx wraps around the end, just take
    928 		 * the first part on this iteration, and we'll get the rest on
    929 		 * the next.
    930 		 */
    931 		if (idx_lim > idx_end)
    932 			idx_lim = idx_end;
    933 		/*
    934 		 * Count bytes through the last complete message that will
    935 		 * fit in the requested read.
    936 		 */
    937 		for (appetite = uio->uio_resid; idx_cur < idx_lim; ++idx_cur) {
    938 			if (appetite < MB_IDX_LEN(*idx_cur))
    939 				break;
    940 			appetite -= MB_IDX_LEN(*idx_cur);
    941 		}
    942 		appetite = uio->uio_resid - appetite;
    943 
    944 		/*
    945 		 * Only if the read is too small to hold even the first
    946 		 * complete message will we return a partial one (updating idx
    947 		 * to reflect the remaining length of the message).
    948 		 */
    949 		if (appetite == 0 && idx_cur < idx_lim) {
    950 			if (!first)
    951 				break;
    952 			appetite = uio->uio_resid;
    953 			*idx_cur = PACK_MB_IDX(MB_IDX_CAT(*idx_cur),
    954 			    MB_IDX_LEN(*idx_cur) - appetite);
    955 		}
    956 		KASSERT(buf_cur + appetite <= buf_lim);
    957 
    958 		/* move the bytes */
    959 		if (appetite > 0) {
    960 			first = 0;  /* we know we won't return empty-handed */
    961 			/* do two uiomoves if data wrap around end of buf */
    962 			if (buf_cur + appetite > buf_end) {
    963 				DPRINTFN(8,
    964 					("midiread: uiomove cc=%td (prewrap)\n",
    965 					buf_end - buf_cur));
    966 				mutex_exit(sc->lock);
    967 				error = uiomove(buf_cur, buf_end - buf_cur, uio);
    968 				mutex_enter(sc->lock);
    969 				if (error)
    970 					break;
    971 				if (sc->dying) {
    972 					error = EIO;
    973 					break;
    974 				}
    975 				appetite -= buf_end - buf_cur;
    976 				buf_cur = mb->buf;
    977 			}
    978 			DPRINTFN(8, ("midiread: uiomove cc=%d\n", appetite));
    979 			mutex_exit(sc->lock);
    980 			error = uiomove(buf_cur, appetite, uio);
    981 			mutex_enter(sc->lock);
    982 			if (error)
    983 				break;
    984 			if (sc->dying) {
    985 				error = EIO;
    986 				break;
    987 			}
    988 			buf_cur += appetite;
    989 		}
    990 
    991 		MIDI_BUF_WRAP(idx);
    992 		MIDI_BUF_WRAP(buf);
    993 		MIDI_BUF_CONSUMER_WBACK(mb,idx);
    994 		MIDI_BUF_CONSUMER_WBACK(mb,buf);
    995 		if (0 == uio->uio_resid) /* if read satisfied, we're done */
    996 			break;
    997 		MIDI_BUF_CONSUMER_REFRESH(mb,idx);
    998 		if (idx_cur == idx_lim) { /* need to wait for data? */
    999 			if (!first || sc->rcv_eof) /* never block reader if */
   1000 				break;            /* any data already in hand */
   1001 			if (ioflag & IO_NDELAY) {
   1002 				error = EWOULDBLOCK;
   1003 				break;
   1004 			}
   1005 			error = cv_wait_sig(&sc->rchan, sc->lock);
   1006 			if (error)
   1007 				break;
   1008 			MIDI_BUF_CONSUMER_REFRESH(mb,idx); /* what'd we get? */
   1009 		}
   1010 		MIDI_BUF_CONSUMER_REFRESH(mb,buf);
   1011 		if (sc->dying) {
   1012 			error = EIO;
   1013 			break;
   1014 		}
   1015 	}
   1016 	mutex_exit(sc->lock);
   1017 
   1018 	return error;
   1019 }
   1020 
   1021 static void
   1022 midi_rcv_asense(void *arg)
   1023 {
   1024 	struct midi_softc *sc;
   1025 
   1026 	sc = arg;
   1027 
   1028 	mutex_enter(sc->lock);
   1029 	if (sc->dying || !sc->isopen) {
   1030 		mutex_exit(sc->lock);
   1031 		return;
   1032 	}
   1033 	if (sc->rcv_quiescent) {
   1034 		sc->rcv_eof = 1;
   1035 		sc->rcv_quiescent = 0;
   1036 		sc->rcv_expect_asense = 0;
   1037 		cv_broadcast(&sc->rchan);
   1038 		selnotify(&sc->rsel, 0, NOTE_SUBMIT);
   1039 		if (sc->async)
   1040 			softint_schedule(sc->sih);
   1041 		mutex_exit(sc->lock);
   1042 		return;
   1043 	}
   1044 	sc->rcv_quiescent = 1;
   1045 	callout_schedule(&sc->rcv_asense_co, MIDI_RCV_ASENSE_PERIOD);
   1046 	mutex_exit(sc->lock);
   1047 }
   1048 
   1049 static void
   1050 midi_xmt_asense(void *arg)
   1051 {
   1052 	struct midi_softc *sc;
   1053 	int error, armed;
   1054 
   1055 	sc = arg;
   1056 
   1057 	mutex_enter(sc->lock);
   1058 	if (sc->pbus || sc->dying || !sc->isopen) {
   1059 		mutex_exit(sc->lock);
   1060 		return;
   1061 	}
   1062 	sc->pbus = 1;
   1063 	if (sc->props & MIDI_PROP_OUT_INTR) {
   1064 		error = sc->hw_if->output(sc->hw_hdl, MIDI_ACK);
   1065 		armed = (error == 0);
   1066 	} else {
   1067 		error = sc->hw_if->output(sc->hw_hdl, MIDI_ACK);
   1068 		armed = 0;
   1069 	}
   1070 	if (!armed) {
   1071 		sc->pbus = 0;
   1072 		callout_schedule(&sc->xmt_asense_co, MIDI_XMT_ASENSE_PERIOD);
   1073 	}
   1074 	mutex_exit(sc->lock);
   1075 }
   1076 
   1077 /*
   1078  * The way this function was hacked up to plug into poll_out and intr_out
   1079  * after they were written won't win it any beauty contests, but it'll work
   1080  * (code in haste, refactor at leisure).
   1081  */
   1082 static int
   1083 midi_msg_out(struct midi_softc *sc, u_char **idx, u_char **idxl, u_char **buf,
   1084 	     u_char **bufl)
   1085 {
   1086 	MIDI_BUF_DECLARE(idx);
   1087 	MIDI_BUF_DECLARE(buf);
   1088 	MIDI_BUF_EXTENT_INIT(&sc->outbuf,idx);
   1089 	MIDI_BUF_EXTENT_INIT(&sc->outbuf,buf);
   1090 	int length;
   1091 	int error;
   1092 	u_char contig[3];
   1093 	u_char *cp;
   1094 	u_char *ep;
   1095 
   1096 	KASSERT(mutex_owned(sc->lock));
   1097 
   1098 	idx_cur = *idx;
   1099 	idx_lim = *idxl;
   1100 	buf_cur = *buf;
   1101 	buf_lim = *bufl;
   1102 
   1103 	length = MB_IDX_LEN(*idx_cur);
   1104 
   1105 	for ( cp = contig, ep = cp + length; cp < ep;) {
   1106 		*cp++ = *buf_cur++;
   1107 		MIDI_BUF_WRAP(buf);
   1108 	}
   1109 	cp = contig;
   1110 
   1111 	switch ( MB_IDX_CAT(*idx_cur)) {
   1112 	case FST_CHV: /* chnmsg to be compressed (for device that wants it) */
   1113 		++ cp;
   1114 		-- length;
   1115 		/* FALLTHROUGH */
   1116 	case FST_CHN:
   1117 		error = sc->hw_if_ext->channel(sc->hw_hdl,
   1118 		    MIDI_GET_STATUS(contig[0]), MIDI_GET_CHAN(contig[0]),
   1119 		    cp, length);
   1120 		break;
   1121 	case FST_COM:
   1122 		error = sc->hw_if_ext->common(sc->hw_hdl,
   1123 		    MIDI_GET_STATUS(contig[0]), cp, length);
   1124 		break;
   1125 	case FST_SYX:
   1126 	case FST_SXP:
   1127 		error = sc->hw_if_ext->sysex(sc->hw_hdl, cp, length);
   1128 		break;
   1129 	case FST_RT:
   1130 		error = sc->hw_if->output(sc->hw_hdl, *cp);
   1131 		break;
   1132 	default:
   1133 		error = EIO;
   1134 	}
   1135 
   1136 	if (!error) {
   1137 		++ idx_cur;
   1138 		MIDI_BUF_WRAP(idx);
   1139 		*idx  = idx_cur;
   1140 		*idxl = idx_lim;
   1141 		*buf  = buf_cur;
   1142 		*bufl = buf_lim;
   1143 	}
   1144 
   1145 	return error;
   1146 }
   1147 
   1148 /*
   1149  * midi_poll_out is intended for the midi hw (the vast majority of MIDI UARTs
   1150  * on sound cards, apparently) that _do not have transmit-ready interrupts_.
   1151  * Every call to hw_if->output for one of these may busy-wait to output the
   1152  * byte; at the standard midi data rate that'll be 320us per byte. The
   1153  * technique of writing only MIDI_MAX_WRITE bytes in a row and then waiting
   1154  * for MIDI_WAIT does not reduce the total time spent busy-waiting, and it
   1155  * adds arbitrary delays in transmission (and, since MIDI_WAIT is roughly the
   1156  * same as the time to send MIDI_MAX_WRITE bytes, it effectively halves the
   1157  * data rate). Here, a somewhat bolder approach is taken. Since midi traffic
   1158  * is bursty but time-sensitive--most of the time there will be none at all,
   1159  * but when there is it should go out ASAP--the strategy is to just get it
   1160  * over with, and empty the buffer in one go. The effect this can have on
   1161  * the rest of the system will be limited by the size of the buffer and the
   1162  * sparseness of the traffic. But some precautions are in order. Interrupts
   1163  * should all be unmasked when this is called, and midiwrite should not fill
   1164  * the buffer more than once (when MIDI_PROP_CAN_INTR is false) without a
   1165  * yield() so some other process can get scheduled. If the write is nonblocking,
   1166  * midiwrite should return a short count rather than yield.
   1167  *
   1168  * Someday when there is fine-grained MP support, this should be reworked to
   1169  * run in a callout so the writing process really could proceed concurrently.
   1170  * But obviously where performance is a concern, interrupt-driven hardware
   1171  * such as USB midi or (apparently) clcs will always be preferable. And it
   1172  * seems (kern/32651) that many of the devices currently working in poll mode
   1173  * may really have tx interrupt capability and want only implementation; that
   1174  * ought to happen.
   1175  */
   1176 static int
   1177 midi_poll_out(struct midi_softc *sc)
   1178 {
   1179 	struct midi_buffer *mb = &sc->outbuf;
   1180 	int error;
   1181 	int msglen;
   1182 	MIDI_BUF_DECLARE(idx);
   1183 	MIDI_BUF_DECLARE(buf);
   1184 
   1185 	KASSERT(mutex_owned(sc->lock));
   1186 
   1187 	error = 0;
   1188 	MIDI_BUF_CONSUMER_INIT(mb,idx);
   1189 	MIDI_BUF_CONSUMER_INIT(mb,buf);
   1190 
   1191 	for (;;) {
   1192 		while (idx_cur != idx_lim) {
   1193 			if (sc->hw_if_ext) {
   1194 				error = midi_msg_out(sc, &idx_cur, &idx_lim,
   1195 				    &buf_cur, &buf_lim);
   1196 				if (error != 0) {
   1197 					break;
   1198 				}
   1199 				continue;
   1200 			}
   1201 			/* or, lacking hw_if_ext ... */
   1202 			msglen = MB_IDX_LEN(*idx_cur);
   1203 			DPRINTFN(7,("midi_poll_out: %p <- %#02x\n",
   1204 			    sc->hw_hdl, *buf_cur));
   1205 			error = sc->hw_if->output(sc->hw_hdl, *buf_cur);
   1206 			if (error) {
   1207 				break;
   1208 			}
   1209 			buf_cur++;
   1210 			MIDI_BUF_WRAP(buf);
   1211 			msglen--;
   1212 			if (msglen) {
   1213 				*idx_cur = PACK_MB_IDX(MB_IDX_CAT(*idx_cur),
   1214 				    msglen);
   1215 			} else {
   1216 				idx_cur++;
   1217 				MIDI_BUF_WRAP(idx);
   1218 			}
   1219 		}
   1220 		if (error != 0) {
   1221 			break;
   1222 		}
   1223 		KASSERT(buf_cur == buf_lim);
   1224 		MIDI_BUF_CONSUMER_WBACK(mb,idx);
   1225 		MIDI_BUF_CONSUMER_WBACK(mb,buf);
   1226 		MIDI_BUF_CONSUMER_REFRESH(mb,idx); /* any more to transmit? */
   1227 		MIDI_BUF_CONSUMER_REFRESH(mb,buf);
   1228 		if (idx_lim == idx_cur)
   1229 			break;
   1230 	}
   1231 
   1232 	if (error != 0) {
   1233 		DPRINTF(("midi_poll_output error %d\n", error));
   1234 		MIDI_BUF_CONSUMER_WBACK(mb,idx);
   1235 		MIDI_BUF_CONSUMER_WBACK(mb,buf);
   1236 	}
   1237 	sc->pbus = 0;
   1238 	callout_schedule(&sc->xmt_asense_co, MIDI_XMT_ASENSE_PERIOD);
   1239 	return error;
   1240 }
   1241 
   1242 /*
   1243  * The interrupt flavor acquires spl and lock once and releases at the end,
   1244  * as it expects to write only one byte or message. The interface convention
   1245  * is that if hw_if->output returns 0, it has initiated transmission and the
   1246  * completion interrupt WILL be forthcoming; if it has not returned 0, NO
   1247  * interrupt will be forthcoming, and if it returns EINPROGRESS it wants
   1248  * another byte right away.
   1249  */
   1250 static int
   1251 midi_intr_out(struct midi_softc *sc)
   1252 {
   1253 	struct midi_buffer *mb;
   1254 	int error, msglen;
   1255 	MIDI_BUF_DECLARE(idx);
   1256 	MIDI_BUF_DECLARE(buf);
   1257 	int armed = 0;
   1258 
   1259 	KASSERT(mutex_owned(sc->lock));
   1260 
   1261 	error = 0;
   1262 	mb = &sc->outbuf;
   1263 
   1264 	MIDI_BUF_CONSUMER_INIT(mb,idx);
   1265 	MIDI_BUF_CONSUMER_INIT(mb,buf);
   1266 
   1267 	while (idx_cur != idx_lim) {
   1268 		if (sc->hw_if_ext) {
   1269 			error = midi_msg_out(sc, &idx_cur, &idx_lim,
   1270 			    &buf_cur, &buf_lim);
   1271 			if (!error ) /* no EINPROGRESS from extended hw_if */
   1272 				armed = 1;
   1273 			break;
   1274 		}
   1275 		/* or, lacking hw_if_ext ... */
   1276 		msglen = MB_IDX_LEN(*idx_cur);
   1277 		error = sc->hw_if->output(sc->hw_hdl, *buf_cur);
   1278 		if (error &&  error != EINPROGRESS)
   1279 			break;
   1280 		++ buf_cur;
   1281 		MIDI_BUF_WRAP(buf);
   1282 		-- msglen;
   1283 		if (msglen)
   1284 			*idx_cur = PACK_MB_IDX(MB_IDX_CAT(*idx_cur),msglen);
   1285 		else {
   1286 			++ idx_cur;
   1287 			MIDI_BUF_WRAP(idx);
   1288 		}
   1289 		if (!error) {
   1290 			armed = 1;
   1291 			break;
   1292 		}
   1293 	}
   1294 	MIDI_BUF_CONSUMER_WBACK(mb,idx);
   1295 	MIDI_BUF_CONSUMER_WBACK(mb,buf);
   1296 	if (!armed) {
   1297 		sc->pbus = 0;
   1298 		callout_schedule(&sc->xmt_asense_co, MIDI_XMT_ASENSE_PERIOD);
   1299 	}
   1300 	cv_broadcast(&sc->wchan);
   1301 	selnotify(&sc->wsel, 0, NOTE_SUBMIT);
   1302 	if (sc->async) {
   1303 		softint_schedule(sc->sih);
   1304 	}
   1305 	if (error) {
   1306 		DPRINTF(("midi_intr_output error %d\n", error));
   1307 	}
   1308 	return error;
   1309 }
   1310 
   1311 static int
   1312 midi_start_output(struct midi_softc *sc)
   1313 {
   1314 
   1315 	KASSERT(mutex_owned(sc->lock));
   1316 
   1317 	if (sc->dying)
   1318 		return EIO;
   1319 	if (sc->props & MIDI_PROP_OUT_INTR)
   1320 		return midi_intr_out(sc);
   1321 	return midi_poll_out(sc);
   1322 }
   1323 
   1324 static int
   1325 real_writebytes(struct midi_softc *sc, u_char *ibuf, int cc)
   1326 {
   1327 	u_char *iend;
   1328 	struct midi_buffer *mb;
   1329 	int arming, count, got;
   1330 	enum fst_form form;
   1331 	MIDI_BUF_DECLARE(idx);
   1332 	MIDI_BUF_DECLARE(buf);
   1333 	int error;
   1334 
   1335 	KASSERT(mutex_owned(sc->lock));
   1336 
   1337 	if (sc->dying || !sc->isopen)
   1338 		return EIO;
   1339 
   1340 	sc->refcnt++;
   1341 
   1342 	iend = ibuf + cc;
   1343 	mb = &sc->outbuf;
   1344 	arming = 0;
   1345 
   1346 	/*
   1347 	 * If the hardware uses the extended hw_if, pass it canonicalized
   1348 	 * messages (or compressed ones if it specifically requests, using
   1349 	 * VCOMP form so the bottom half can still pass the op and chan along);
   1350 	 * if it does not, send it compressed messages (using COMPR form as
   1351 	 * there is no need to preserve the status for the bottom half).
   1352 	 */
   1353 	if (NULL == sc->hw_if_ext)
   1354 		form = FST_COMPR;
   1355 	else if (sc->hw_if_ext->compress)
   1356 		form = FST_VCOMP;
   1357 	else
   1358 		form = FST_CANON;
   1359 
   1360 	MIDI_BUF_PRODUCER_INIT(mb,idx);
   1361 	MIDI_BUF_PRODUCER_INIT(mb,buf);
   1362 
   1363 	while (ibuf < iend) {
   1364 		got = midi_fst(&sc->xmt, *ibuf, form);
   1365 		++ ibuf;
   1366 		switch ( got) {
   1367 		case FST_MORE:
   1368 			continue;
   1369 		case FST_ERR:
   1370 		case FST_HUH:
   1371 			error = EPROTO;
   1372 			goto out;
   1373 		case FST_CHN:
   1374 		case FST_CHV: /* only occurs in VCOMP form */
   1375 		case FST_COM:
   1376 		case FST_RT:
   1377 		case FST_SYX:
   1378 		case FST_SXP:
   1379 			break; /* go add to buffer */
   1380 #if defined(AUDIO_DEBUG) || defined(DIAGNOSTIC)
   1381 		default:
   1382 			printf("midi_wr: midi_fst returned %d?!\n", got);
   1383 #endif
   1384 		}
   1385 		count = sc->xmt.end - sc->xmt.pos;
   1386 		if (0 == count ) /* can happen with stray 0xf7; see midi_fst */
   1387 			continue;
   1388 		/*
   1389 		 * return EWOULDBLOCK if the data passed will not fit in
   1390 		 * the buffer; the caller should have taken steps to avoid that.
   1391 		 * If got==FST_SXP we lose the new status byte, but we're losing
   1392 		 * anyway, so c'est la vie.
   1393 		 */
   1394 		if (idx_cur == idx_lim || count > buf_lim - buf_cur) {
   1395 			MIDI_BUF_PRODUCER_REFRESH(mb,idx); /* get the most */
   1396 			MIDI_BUF_PRODUCER_REFRESH(mb,buf); /*  current facts */
   1397 			if (idx_cur == idx_lim || count > buf_lim - buf_cur) {
   1398 				error = EWOULDBLOCK; /* caller's problem */
   1399 				goto out;
   1400 			}
   1401 		}
   1402 		*idx_cur++ = PACK_MB_IDX(got,count);
   1403 		MIDI_BUF_WRAP(idx);
   1404 		while (count) {
   1405 			*buf_cur++ = *(sc->xmt.pos)++;
   1406 			MIDI_BUF_WRAP(buf);
   1407 			-- count;
   1408 		}
   1409 		if (FST_SXP == got)
   1410 			-- ibuf; /* again with same status byte */
   1411 	}
   1412 	MIDI_BUF_PRODUCER_WBACK(mb,buf);
   1413 	MIDI_BUF_PRODUCER_WBACK(mb,idx);
   1414 	/*
   1415 	 * If the output transfer is not already busy, and there is a message
   1416 	 * buffered, mark it busy, stop the Active Sense callout (what if we're
   1417 	 * too late and it's expired already? No big deal, an extra Active Sense
   1418 	 * never hurt anybody) and start the output transfer once we're out of
   1419 	 * the critical section (pbus==1 will stop anyone else doing the same).
   1420 	 */
   1421 	MIDI_BUF_CONSUMER_INIT(mb,idx); /* check what consumer's got to read */
   1422 	if (!sc->pbus && idx_cur < idx_lim) {
   1423 		sc->pbus = 1;
   1424 		callout_stop(&sc->xmt_asense_co);
   1425 		arming = 1;
   1426 	}
   1427 
   1428 	error = arming ? midi_start_output(sc) : 0;
   1429 
   1430 out:
   1431 	if (--sc->refcnt < 0)
   1432 		cv_broadcast(&sc->detach_cv);
   1433 
   1434 	return error;
   1435 }
   1436 
   1437 static int
   1438 midiwrite(dev_t dev, struct uio *uio, int ioflag)
   1439 {
   1440 	struct midi_softc *sc;
   1441 	struct midi_buffer *mb;
   1442 	int error;
   1443 	u_char inp[256];
   1444 	MIDI_BUF_DECLARE(idx);
   1445 	MIDI_BUF_DECLARE(buf);
   1446 	size_t idxspace;
   1447 	size_t bufspace;
   1448 	size_t xfrcount;
   1449 	int pollout = 0;
   1450 
   1451 	(void)buf_end; (void)idx_end;
   1452 	sc = device_lookup_private(&midi_cd, MIDIUNIT(dev));
   1453 
   1454 	DPRINTFN(6,("midiwrite: %p, unit=%d, count=%lu\n", sc, (int)minor(dev),
   1455 	    (unsigned long)uio->uio_resid));
   1456 
   1457 	mutex_enter(sc->lock);
   1458 	if (sc->dying) {
   1459 		mutex_exit(sc->lock);
   1460 		return EIO;
   1461 	}
   1462 
   1463 	sc->refcnt++;
   1464 
   1465 	mb = &sc->outbuf;
   1466 	error = 0;
   1467 	while (uio->uio_resid > 0 && !error) {
   1468 		/*
   1469 		 * block if necessary for the minimum buffer space to guarantee
   1470 		 * we can write something.
   1471 		 */
   1472 		MIDI_BUF_PRODUCER_INIT(mb,idx); /* init can't go above loop; */
   1473 		MIDI_BUF_PRODUCER_INIT(mb,buf); /* real_writebytes moves cur */
   1474 		for (;;) {
   1475 			idxspace = MIDI_BUF_PRODUCER_REFRESH(mb,idx) - idx_cur;
   1476 			bufspace = MIDI_BUF_PRODUCER_REFRESH(mb,buf) - buf_cur;
   1477 			if (idxspace >= 1 && bufspace >= 3 && !pollout)
   1478 				break;
   1479 			DPRINTFN(8,("midi_write: sleep idx=%zd buf=%zd\n",
   1480 				 idxspace, bufspace));
   1481 			if (ioflag & IO_NDELAY) {
   1482 				/*
   1483 				 * If some amount has already been transferred,
   1484 				 * the common syscall code will automagically
   1485 				 * convert this to success with a short count.
   1486 				 */
   1487 				mutex_exit(sc->lock);
   1488 				error = EWOULDBLOCK;
   1489 				goto out;
   1490 			}
   1491 			if (pollout) {
   1492 				mutex_exit(sc->lock);
   1493 				yield(); /* see midi_poll_output */
   1494 				mutex_enter(sc->lock);
   1495 				pollout = 0;
   1496 			} else
   1497 				error = cv_wait_sig(&sc->wchan, sc->lock);
   1498 			if (error) {
   1499 				/*
   1500 				 * Similarly, the common code will handle
   1501 				 * EINTR and ERESTART properly here, changing to
   1502 				 * a short count if something transferred.
   1503 				 */
   1504 				goto out;
   1505 			}
   1506 		}
   1507 
   1508 		/*
   1509 		 * The number of bytes we can safely extract from the uio
   1510 		 * depends on the available idx and buf space. Worst case,
   1511 		 * every byte is a message so 1 idx is required per byte.
   1512 		 * Worst case, the first byte completes a 3-byte msg in prior
   1513 		 * state, and every subsequent byte is a Program Change or
   1514 		 * Channel Pressure msg with running status and expands to 2
   1515 		 * bytes, so the buf space reqd is 3+2(n-1) or 2n+1. So limit
   1516 		 * the transfer to the min of idxspace and (bufspace-1)>>1.
   1517 		 */
   1518 		xfrcount = (bufspace - 1) >> 1;
   1519 		if (xfrcount > idxspace)
   1520 			xfrcount = idxspace;
   1521 		if (xfrcount > sizeof inp)
   1522 			xfrcount = sizeof inp;
   1523 		if (xfrcount > uio->uio_resid)
   1524 			xfrcount = uio->uio_resid;
   1525 
   1526 		mutex_exit(sc->lock);
   1527 		error = uiomove(inp, xfrcount, uio);
   1528 		mutex_enter(sc->lock);
   1529 #ifdef MIDI_DEBUG
   1530 		if (error)
   1531 		        printf("midi_write:(1) uiomove failed %d; "
   1532 			       "xfrcount=%zu inp=%p\n",
   1533 			       error, xfrcount, inp);
   1534 #endif
   1535 		if ( error )
   1536 			break;
   1537 
   1538 		/*
   1539 		 * The number of bytes we extracted being calculated to
   1540 		 * definitely fit in the buffer even with canonicalization,
   1541 		 * there is no excuse for real_writebytes to return EWOULDBLOCK.
   1542 		 */
   1543 		error = real_writebytes(sc, inp, xfrcount);
   1544 		KASSERT(error != EWOULDBLOCK);
   1545 		if (error)
   1546 			break;
   1547 
   1548 		/*
   1549 		 * If this is a polling device and we just sent a buffer, let's
   1550 		 * not send another without giving some other process a chance.
   1551 		 */
   1552 		if ((sc->props & MIDI_PROP_OUT_INTR) == 0)
   1553 			pollout = 1;
   1554 		DPRINTFN(8,("midiwrite: uio_resid now %zu, props=%d\n",
   1555 		    uio->uio_resid, sc->props));
   1556 	}
   1557 
   1558 out:
   1559 	if (--sc->refcnt < 0)
   1560 		cv_broadcast(&sc->detach_cv);
   1561 
   1562 	mutex_exit(sc->lock);
   1563 	return error;
   1564 }
   1565 
   1566 /*
   1567  * This write routine is only called from sequencer code and expects
   1568  * a write that is smaller than the MIDI buffer.
   1569  */
   1570 int
   1571 midi_writebytes(int unit, u_char *bf, int cc)
   1572 {
   1573 	struct midi_softc *sc =
   1574 	    device_lookup_private(&midi_cd, unit);
   1575 	int error;
   1576 
   1577 	if (!sc)
   1578 		return EIO;
   1579 
   1580 	DPRINTFN(7, ("midi_writebytes: %p, unit=%d, cc=%d %#02x %#02x %#02x\n",
   1581                     sc, unit, cc, bf[0], bf[1], bf[2]));
   1582 
   1583 	mutex_enter(sc->lock);
   1584 	error = real_writebytes(sc, bf, cc);
   1585 	mutex_exit(sc->lock);
   1586 
   1587 	return error;
   1588 }
   1589 
   1590 static int
   1591 midiioctl(dev_t dev, u_long cmd, void *addr, int flag, struct lwp *l)
   1592 {
   1593 	struct midi_softc *sc;
   1594 	const struct midi_hw_if *hw;
   1595 	int error;
   1596 	MIDI_BUF_DECLARE(buf);
   1597 
   1598 	(void)buf_end;
   1599 	sc = device_lookup_private(&midi_cd, MIDIUNIT(dev));;
   1600 	if (sc->dying)
   1601 		return EIO;
   1602 	hw = sc->hw_if;
   1603 	error = 0;
   1604 
   1605 	mutex_enter(sc->lock);
   1606 	sc->refcnt++;
   1607 
   1608 	DPRINTFN(5,("midiioctl: %p cmd=0x%08lx\n", sc, cmd));
   1609 
   1610 	switch (cmd) {
   1611 	case FIONBIO:
   1612 		/* All handled in the upper layer. */
   1613 		break;
   1614 
   1615 	case FIONREAD:
   1616 		/*
   1617 		 * This code relies on the current implementation of midi_in
   1618 		 * always updating buf and idx together in a critical section,
   1619 		 * so buf always ends at a message boundary. Document this
   1620 		 * ioctl as always returning a value such that the last message
   1621 		 * included is complete (SysEx the only exception), and then
   1622 		 * make sure the implementation doesn't regress.  NB that
   1623 		 * means if this ioctl returns n and the proc then issues a
   1624 		 * read of n, n bytes will be read, but if the proc issues a
   1625 		 * read of m < n, fewer than m bytes may be read to ensure the
   1626 		 * read ends at a message boundary.
   1627 		 */
   1628 		MIDI_BUF_CONSUMER_INIT(&sc->inbuf,buf);
   1629 		*(int *)addr = buf_lim - buf_cur;
   1630 		break;
   1631 
   1632 	case FIOASYNC:
   1633 		mutex_exit(sc->lock);
   1634 		mutex_enter(proc_lock);
   1635 		if (*(int *)addr) {
   1636 			if (sc->async) {
   1637 				error = EBUSY;
   1638 			} else {
   1639 				sc->async = curproc->p_pid;
   1640 			}
   1641 			DPRINTFN(5,("midi_ioctl: FIOASYNC %d\n",
   1642 			    curproc->p_pid));
   1643 		} else {
   1644 			sc->async = 0;
   1645 		}
   1646 		mutex_exit(proc_lock);
   1647 		mutex_enter(sc->lock);
   1648 		break;
   1649 
   1650 #if 0
   1651 	case MIDI_PRETIME:
   1652 		/* XXX OSS
   1653 		 * This should set up a read timeout, but that's
   1654 		 * why we have poll(), so there's nothing yet. */
   1655 		error = EINVAL;
   1656 		break;
   1657 #endif
   1658 
   1659 #ifdef MIDI_SAVE
   1660 	case MIDI_GETSAVE:
   1661 		mutex_exit(sc->lock);
   1662 		error = copyout(&midisave, *(void **)addr, sizeof midisave);
   1663 		mutex_enter(sc->lock);
   1664   		break;
   1665 #endif
   1666 
   1667 	default:
   1668 		if (hw->ioctl != NULL) {
   1669 			error = hw->ioctl(sc->hw_hdl, cmd, addr, flag, l);
   1670 		} else {
   1671 			error = EINVAL;
   1672 		}
   1673 		break;
   1674 	}
   1675 
   1676 	if (--sc->refcnt < 0)
   1677 		cv_broadcast(&sc->detach_cv);
   1678 	mutex_exit(sc->lock);
   1679 	return error;
   1680 }
   1681 
   1682 static int
   1683 midipoll(dev_t dev, int events, struct lwp *l)
   1684 {
   1685 	struct midi_softc *sc;
   1686 	int revents;
   1687 	MIDI_BUF_DECLARE(idx);
   1688 	MIDI_BUF_DECLARE(buf);
   1689 
   1690 	(void)buf_end; (void)idx_end;
   1691 	sc = device_lookup_private(&midi_cd, MIDIUNIT(dev));
   1692 	revents = 0;
   1693 
   1694 	DPRINTFN(6,("midipoll: %p events=0x%x\n", sc, events));
   1695 
   1696 	mutex_enter(sc->lock);
   1697 	if (sc->dying) {
   1698 		mutex_exit(sc->lock);
   1699 		return POLLHUP;
   1700 	}
   1701 
   1702 	sc->refcnt++;
   1703 
   1704 	if ((events & (POLLIN | POLLRDNORM)) != 0) {
   1705 		MIDI_BUF_CONSUMER_INIT(&sc->inbuf, idx);
   1706 		if (idx_cur < idx_lim)
   1707 			revents |= events & (POLLIN | POLLRDNORM);
   1708 		else
   1709 			selrecord(l, &sc->rsel);
   1710 	}
   1711 	if ((events & (POLLOUT | POLLWRNORM)) != 0) {
   1712 		MIDI_BUF_PRODUCER_INIT(&sc->outbuf, idx);
   1713 		MIDI_BUF_PRODUCER_INIT(&sc->outbuf, buf);
   1714 		if (idx_lim - idx_cur >= 1 && buf_lim - buf_cur >= 3)
   1715 			revents |= events & (POLLOUT | POLLWRNORM);
   1716 		else
   1717 			selrecord(l, &sc->wsel);
   1718 	}
   1719 
   1720 	if (--sc->refcnt < 0)
   1721 		cv_broadcast(&sc->detach_cv);
   1722 
   1723 	mutex_exit(sc->lock);
   1724 
   1725 	return revents;
   1726 }
   1727 
   1728 static void
   1729 filt_midirdetach(struct knote *kn)
   1730 {
   1731 	struct midi_softc *sc = kn->kn_hook;
   1732 
   1733 	mutex_enter(sc->lock);
   1734 	SLIST_REMOVE(&sc->rsel.sel_klist, kn, knote, kn_selnext);
   1735 	mutex_exit(sc->lock);
   1736 }
   1737 
   1738 static int
   1739 filt_midiread(struct knote *kn, long hint)
   1740 {
   1741 	struct midi_softc *sc = kn->kn_hook;
   1742 	MIDI_BUF_DECLARE(buf);
   1743 
   1744 	(void)buf_end;
   1745 	if (hint != NOTE_SUBMIT)
   1746 		mutex_enter(sc->lock);
   1747 	MIDI_BUF_CONSUMER_INIT(&sc->inbuf,buf);
   1748 	kn->kn_data = buf_lim - buf_cur;
   1749 	if (hint != NOTE_SUBMIT)
   1750 		mutex_exit(sc->lock);
   1751 	return (kn->kn_data > 0);
   1752 }
   1753 
   1754 static const struct filterops midiread_filtops =
   1755 	{ 1, NULL, filt_midirdetach, filt_midiread };
   1756 
   1757 static void
   1758 filt_midiwdetach(struct knote *kn)
   1759 {
   1760 	struct midi_softc *sc = kn->kn_hook;
   1761 
   1762 	mutex_enter(sc->lock);
   1763 	SLIST_REMOVE(&sc->wsel.sel_klist, kn, knote, kn_selnext);
   1764 	mutex_exit(sc->lock);
   1765 }
   1766 
   1767 static int
   1768 filt_midiwrite(struct knote *kn, long hint)
   1769 {
   1770 	struct midi_softc *sc = kn->kn_hook;
   1771 	MIDI_BUF_DECLARE(idx);
   1772 	MIDI_BUF_DECLARE(buf);
   1773 
   1774 	mutex_exit(sc->lock);
   1775 	sc->refcnt++;
   1776 	mutex_enter(sc->lock);
   1777 
   1778 	(void)idx_end; (void)buf_end;
   1779 	if (hint != NOTE_SUBMIT)
   1780 		mutex_enter(sc->lock);
   1781 	MIDI_BUF_PRODUCER_INIT(&sc->outbuf,idx);
   1782 	MIDI_BUF_PRODUCER_INIT(&sc->outbuf,buf);
   1783 	kn->kn_data = ((buf_lim - buf_cur)-1)>>1;
   1784 	if (kn->kn_data > idx_lim - idx_cur)
   1785 		kn->kn_data = idx_lim - idx_cur;
   1786 	if (hint != NOTE_SUBMIT)
   1787 		mutex_exit(sc->lock);
   1788 
   1789 	// XXXMRG -- move this up, avoid the relock?
   1790 	mutex_enter(sc->lock);
   1791 	if (--sc->refcnt < 0)
   1792 		cv_broadcast(&sc->detach_cv);
   1793 	mutex_exit(sc->lock);
   1794 
   1795 	return (kn->kn_data > 0);
   1796 }
   1797 
   1798 static const struct filterops midiwrite_filtops =
   1799 	{ 1, NULL, filt_midiwdetach, filt_midiwrite };
   1800 
   1801 int
   1802 midikqfilter(dev_t dev, struct knote *kn)
   1803 {
   1804 	struct midi_softc *sc =
   1805 	    device_lookup_private(&midi_cd, MIDIUNIT(dev));
   1806 	struct klist *klist;
   1807 
   1808 	mutex_exit(sc->lock);
   1809 	sc->refcnt++;
   1810 	mutex_enter(sc->lock);
   1811 
   1812 	switch (kn->kn_filter) {
   1813 	case EVFILT_READ:
   1814 		klist = &sc->rsel.sel_klist;
   1815 		kn->kn_fop = &midiread_filtops;
   1816 		break;
   1817 
   1818 	case EVFILT_WRITE:
   1819 		klist = &sc->wsel.sel_klist;
   1820 		kn->kn_fop = &midiwrite_filtops;
   1821 		break;
   1822 
   1823 	default:
   1824 		return (EINVAL);
   1825 	}
   1826 
   1827 	kn->kn_hook = sc;
   1828 
   1829 	mutex_enter(sc->lock);
   1830 	SLIST_INSERT_HEAD(klist, kn, kn_selnext);
   1831 	if (--sc->refcnt < 0)
   1832 		cv_broadcast(&sc->detach_cv);
   1833 	mutex_exit(sc->lock);
   1834 
   1835 	return (0);
   1836 }
   1837 
   1838 void
   1839 midi_getinfo(dev_t dev, struct midi_info *mi)
   1840 {
   1841 	struct midi_softc *sc;
   1842 
   1843 	sc = device_lookup_private(&midi_cd, MIDIUNIT(dev));
   1844 	if (sc == NULL)
   1845 		return;
   1846 	mutex_enter(sc->lock);
   1847 	sc->hw_if->getinfo(sc->hw_hdl, mi);
   1848 	mutex_exit(sc->lock);
   1849 }
   1850 
   1851 #elif NMIDIBUS > 0 /* but NMIDI == 0 */
   1852 
   1853 void
   1854 midi_register_hw_if_ext(struct midi_hw_if_ext *exthw)
   1855 {
   1856 
   1857 	/* nothing */
   1858 }
   1859 
   1860 #endif /* NMIDI > 0 */
   1861 
   1862 #if NMIDI > 0 || NMIDIBUS > 0
   1863 
   1864 device_t
   1865 midi_attach_mi(const struct midi_hw_if *mhwp, void *hdlp, device_t dev)
   1866 {
   1867 	struct audio_attach_args arg;
   1868 
   1869 	if (mhwp == NULL) {
   1870 		panic("midi_attach_mi: NULL\n");
   1871 		return (0);
   1872 	}
   1873 
   1874 	arg.type = AUDIODEV_TYPE_MIDI;
   1875 	arg.hwif = mhwp;
   1876 	arg.hdl = hdlp;
   1877 	return (config_found(dev, &arg, audioprint));
   1878 }
   1879 
   1880 #endif /* NMIDI > 0 || NMIDIBUS > 0 */
   1881