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