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