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