Home | History | Annotate | Line # | Download | only in dev
midi.c revision 1.47.2.3
      1 /*	$NetBSD: midi.c,v 1.47.2.3 2007/01/19 10:35:48 ad Exp $	*/
      2 
      3 /*
      4  * Copyright (c) 1998 The NetBSD Foundation, Inc.
      5  * All rights reserved.
      6  *
      7  * This code is derived from software contributed to The NetBSD Foundation
      8  * by Lennart Augustsson (augustss (at) NetBSD.org) 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.47.2.3 2007/01/19 10:35:48 ad 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, struct cfdata *match,
    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)
    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 			mutex_enter(&proclist_mutex);
    743 			psignal(sc->async, SIGIO);
    744 			mutex_exit(&proclist_mutex);
    745 		}
    746 		MIDI_IN_UNLOCK(sc,s);
    747 		selnotify(&sc->rsel, 0); /* filter will spin if locked */
    748 		break;
    749 	default: /* don't #ifdef this away, gcc will say FST_HUH not handled */
    750 		printf("midi_in: midi_fst returned %d?!\n", got);
    751 	}
    752 	if ( FST_SXP == got )
    753 		goto sxp_again;
    754 }
    755 
    756 void
    757 midi_out(void *addr)
    758 {
    759 	struct midi_softc *sc = addr;
    760 
    761 	if (!sc->isopen)
    762 		return;
    763 	DPRINTFN(8, ("midi_out: %p\n", sc));
    764 	midi_intr_out(sc);
    765 }
    766 
    767 int
    768 midiopen(dev_t dev, int flags, int ifmt, struct lwp *l)
    769 {
    770 	struct midi_softc *sc;
    771 	const struct midi_hw_if *hw;
    772 	int error;
    773 
    774 	sc = device_lookup(&midi_cd, MIDIUNIT(dev));
    775 	if (sc == NULL)
    776 		return (ENXIO);
    777 	if (sc->dying)
    778 		return (EIO);
    779 
    780 	DPRINTFN(3,("midiopen %p\n", sc));
    781 
    782 	hw = sc->hw_if;
    783 	if (!hw)
    784 		return ENXIO;
    785 	if (sc->isopen)
    786 		return EBUSY;
    787 
    788 	/* put both state machines into known states */
    789 	sc->rcv.state = MIDI_IN_START;
    790 	sc->rcv.pos = sc->rcv.msg;
    791 	sc->rcv.end = sc->rcv.msg;
    792 	sc->xmt.state = MIDI_IN_START;
    793 	sc->xmt.pos = sc->xmt.msg;
    794 	sc->xmt.end = sc->xmt.msg;
    795 
    796 	/* copy error counters so an ioctl (TBA) can give since-open stats */
    797 	sc->rcv.atOpen.bytesDiscarded  = sc->rcv.bytesDiscarded.ev_count;
    798 	sc->rcv.atQuery.bytesDiscarded = sc->rcv.bytesDiscarded.ev_count;
    799 
    800 	sc->xmt.atOpen.bytesDiscarded  = sc->xmt.bytesDiscarded.ev_count;
    801 	sc->xmt.atQuery.bytesDiscarded = sc->xmt.bytesDiscarded.ev_count;
    802 
    803 	/* and the buffers */
    804 	midi_initbuf(&sc->outbuf);
    805 	midi_initbuf(&sc->inbuf);
    806 
    807 	/* and the receive flags */
    808 	sc->rcv_expect_asense = 0;
    809 	sc->rcv_quiescent = 0;
    810 	sc->rcv_eof = 0;
    811 
    812 	error = hw->open(sc->hw_hdl, flags, midi_in, midi_out, sc);
    813 	if (error)
    814 		return error;
    815 	sc->isopen++;
    816 	sc->flags = flags;
    817 	sc->rchan = 0;
    818 	sc->wchan = 0;
    819 	sc->pbus = 0;
    820 	sc->async = 0;
    821 
    822 #ifdef MIDI_SAVE
    823 	if (midicnt != 0) {
    824 		midisave.cnt = midicnt;
    825 		midicnt = 0;
    826 	}
    827 #endif
    828 
    829 	return 0;
    830 }
    831 
    832 int
    833 midiclose(dev_t dev, int flags, int ifmt,
    834     struct lwp *l)
    835 {
    836 	int unit = MIDIUNIT(dev);
    837 	struct midi_softc *sc = midi_cd.cd_devs[unit];
    838 	const struct midi_hw_if *hw = sc->hw_if;
    839 	int s, error;
    840 
    841 	DPRINTFN(3,("midiclose %p\n", sc));
    842 
    843 	/* midi_start_output(sc); anything buffered => pbus already set! */
    844 	error = 0;
    845 	MIDI_OUT_LOCK(sc,s);
    846 	while (sc->pbus) {
    847 		DPRINTFN(8,("midiclose sleep ...\n"));
    848 		error =
    849 		midi_sleep_timo(&sc->wchan, "mid_dr", 30*hz, &sc->out_lock);
    850 	}
    851 	sc->isopen = 0;
    852 	MIDI_OUT_UNLOCK(sc,s);
    853 	callout_stop(&sc->xmt_asense_co); /* xxx fix this - sleep? */
    854 	callout_stop(&sc->rcv_asense_co);
    855 	hw->close(sc->hw_hdl);
    856 #if NSEQUENCER > 0
    857 	sc->seqopen = 0;
    858 	sc->seq_md = 0;
    859 #endif
    860 	return 0;
    861 }
    862 
    863 int
    864 midiread(dev_t dev, struct uio *uio, int ioflag)
    865 {
    866 	int unit = MIDIUNIT(dev);
    867 	struct midi_softc *sc = midi_cd.cd_devs[unit];
    868 	struct midi_buffer *mb = &sc->inbuf;
    869 	int error;
    870 	int s;
    871 	MIDI_BUF_DECLARE(idx);
    872 	MIDI_BUF_DECLARE(buf);
    873 	int appetite;
    874 	int first = 1;
    875 
    876 	DPRINTFN(6,("midiread: %p, count=%lu\n", sc,
    877 		 (unsigned long)uio->uio_resid));
    878 
    879 	if (sc->dying)
    880 		return EIO;
    881         if ( !(sc->props & MIDI_PROP_CAN_INPUT) )
    882 	        return ENXIO;
    883 
    884 	MIDI_IN_LOCK(sc,s);
    885 	MIDI_BUF_CONSUMER_INIT(mb,idx);
    886 	MIDI_BUF_CONSUMER_INIT(mb,buf);
    887 	MIDI_IN_UNLOCK(sc,s);
    888 
    889 	error = 0;
    890 	for ( ;; ) {
    891 		/*
    892 		 * If the used portion of idx wraps around the end, just take
    893 		 * the first part on this iteration, and we'll get the rest on
    894 		 * the next.
    895 		 */
    896 		if ( idx_lim > idx_end )
    897 			idx_lim = idx_end;
    898 		/*
    899 		 * Count bytes through the last complete message that will
    900 		 * fit in the requested read.
    901 		 */
    902 		for (appetite = uio->uio_resid; idx_cur < idx_lim; ++idx_cur) {
    903 			if ( appetite < MB_IDX_LEN(*idx_cur) )
    904 				break;
    905 			appetite -= MB_IDX_LEN(*idx_cur);
    906 		}
    907 		appetite = uio->uio_resid - appetite;
    908 		/*
    909 		 * Only if the read is too small to hold even the first
    910 		 * complete message will we return a partial one (updating idx
    911 		 * to reflect the remaining length of the message).
    912 		 */
    913 		if ( appetite == 0 && idx_cur < idx_lim ) {
    914 			if ( !first )
    915 				goto unlocked_exit; /* idx_cur not advanced */
    916 			appetite = uio->uio_resid;
    917 			*idx_cur = PACK_MB_IDX(MB_IDX_CAT(*idx_cur),
    918 					       MB_IDX_LEN(*idx_cur) - appetite);
    919 		}
    920 		KASSERT(buf_cur + appetite <= buf_lim);
    921 
    922 		/* move the bytes */
    923 		if ( appetite > 0 ) {
    924 			first = 0;  /* we know we won't return empty-handed */
    925 			/* do two uiomoves if data wrap around end of buf */
    926 			if ( buf_cur + appetite > buf_end ) {
    927 				DPRINTFN(8,
    928 					("midiread: uiomove cc=%d (prewrap)\n",
    929 					buf_end - buf_cur));
    930 				error = uiomove(buf_cur, buf_end-buf_cur, uio);
    931 				if ( error )
    932 					goto unlocked_exit;
    933 				appetite -= buf_end - buf_cur;
    934 				buf_cur = mb->buf;
    935 			}
    936 			DPRINTFN(8, ("midiread: uiomove cc=%d\n", appetite));
    937 			error = uiomove(buf_cur, appetite, uio);
    938 			if ( error )
    939 				goto unlocked_exit;
    940 			buf_cur += appetite;
    941 		}
    942 
    943 		MIDI_BUF_WRAP(idx);
    944 		MIDI_BUF_WRAP(buf);
    945 
    946 		MIDI_IN_LOCK(sc,s);
    947 		MIDI_BUF_CONSUMER_WBACK(mb,idx);
    948 		MIDI_BUF_CONSUMER_WBACK(mb,buf);
    949 		if ( 0 == uio->uio_resid ) /* if read satisfied, we're done */
    950 			break;
    951 		MIDI_BUF_CONSUMER_REFRESH(mb,idx);
    952 		if ( idx_cur == idx_lim ) { /* need to wait for data? */
    953 			if ( !first || sc->rcv_eof ) /* never block reader if */
    954 				break;            /* any data already in hand */
    955 			if (ioflag & IO_NDELAY) {
    956 				error = EWOULDBLOCK;
    957 				break;
    958 			}
    959 			error = midi_sleep(&sc->rchan, "mid rd", &sc->in_lock);
    960 			if ( error )
    961 				break;
    962 			MIDI_BUF_CONSUMER_REFRESH(mb,idx); /* what'd we get? */
    963 		}
    964 		MIDI_BUF_CONSUMER_REFRESH(mb,buf);
    965 		MIDI_IN_UNLOCK(sc,s);
    966 		if ( sc->dying )
    967 			return EIO;
    968 	}
    969 	MIDI_IN_UNLOCK(sc,s);
    970 
    971 unlocked_exit:
    972 	return error;
    973 }
    974 
    975 void
    976 midi_rcv_asense(void *arg)
    977 {
    978 	struct midi_softc *sc = arg;
    979 	int s;
    980 
    981 	if ( sc->dying || !sc->isopen )
    982 		return;
    983 
    984 	if ( sc->rcv_quiescent ) {
    985 		MIDI_IN_LOCK(sc,s);
    986 		sc->rcv_eof = 1;
    987 		sc->rcv_quiescent = 0;
    988 		sc->rcv_expect_asense = 0;
    989 		midi_wakeup(&sc->rchan);
    990 		if (sc->async) {
    991 			mutex_enter(&proclist_mutex);
    992 			psignal(sc->async, SIGIO);
    993 			mutex_exit(&proclist_mutex);
    994 		}
    995 		MIDI_IN_UNLOCK(sc,s);
    996 		selnotify(&sc->rsel, 0); /* filter will spin if locked */
    997 		return;
    998 	}
    999 
   1000 	sc->rcv_quiescent = 1;
   1001 	callout_schedule(&sc->rcv_asense_co, MIDI_RCV_ASENSE_PERIOD);
   1002 }
   1003 
   1004 void
   1005 midi_xmt_asense(void *arg)
   1006 {
   1007 	struct midi_softc *sc = arg;
   1008 	int s;
   1009 	int error;
   1010 	int armed;
   1011 
   1012 	if ( sc->dying || !sc->isopen )
   1013 		return;
   1014 
   1015 	MIDI_OUT_LOCK(sc,s);
   1016 	if ( sc->pbus || sc->dying || !sc->isopen ) {
   1017 		MIDI_OUT_UNLOCK(sc,s);
   1018 		return;
   1019 	}
   1020 	sc->pbus = 1;
   1021 	DPRINTFN(8,("midi_xmt_asense: %p\n", sc));
   1022 
   1023 	if ( sc->props & MIDI_PROP_OUT_INTR ) {
   1024 		error = sc->hw_if->output(sc->hw_hdl, MIDI_ACK);
   1025 		armed = (error == 0);
   1026 	} else { /* polled output, do with interrupts unmasked */
   1027 		MIDI_OUT_UNLOCK(sc,s);
   1028 		/* running from softclock, so top half won't sneak in here */
   1029 		error = sc->hw_if->output(sc->hw_hdl, MIDI_ACK);
   1030 		MIDI_OUT_LOCK(sc,s);
   1031 		armed = 0;
   1032 	}
   1033 
   1034 	if ( !armed ) {
   1035 		sc->pbus = 0;
   1036 		callout_schedule(&sc->xmt_asense_co, MIDI_XMT_ASENSE_PERIOD);
   1037 	}
   1038 
   1039 	MIDI_OUT_UNLOCK(sc,s);
   1040 }
   1041 
   1042 /*
   1043  * The way this function was hacked up to plug into poll_out and intr_out
   1044  * after they were written won't win it any beauty contests, but it'll work
   1045  * (code in haste, refactor at leisure). This may be called with the lock
   1046  * (by intr_out) or without the lock (by poll_out) so it only does what could
   1047  * be safe either way.
   1048  */
   1049 int midi_msg_out(struct midi_softc *sc,
   1050                  u_char **idx, u_char **idxl, u_char **buf, u_char **bufl) {
   1051 	MIDI_BUF_DECLARE(idx);
   1052 	MIDI_BUF_DECLARE(buf);
   1053 	MIDI_BUF_EXTENT_INIT(&sc->outbuf,idx);
   1054 	MIDI_BUF_EXTENT_INIT(&sc->outbuf,buf);
   1055 	int length;
   1056 	int error;
   1057 	u_char contig[3];
   1058 	u_char *cp;
   1059 	u_char *ep;
   1060 
   1061 	idx_cur = *idx;
   1062 	idx_lim = *idxl;
   1063 	buf_cur = *buf;
   1064 	buf_lim = *bufl;
   1065 
   1066 	length = MB_IDX_LEN(*idx_cur);
   1067 
   1068 	for ( cp = contig, ep = cp + length; cp < ep; ) {
   1069 		*cp++ = *buf_cur++;
   1070 		MIDI_BUF_WRAP(buf);
   1071 	}
   1072 	cp = contig;
   1073 
   1074 	switch ( MB_IDX_CAT(*idx_cur) ) {
   1075 	case FST_CHV: /* chnmsg to be compressed (for device that wants it) */
   1076 		++ cp;
   1077 		-- length;
   1078 		/* FALLTHROUGH */
   1079 	case FST_CHN:
   1080 		error = sc->hw_if_ext->channel(sc->hw_hdl,
   1081 		                               MIDI_GET_STATUS(contig[0]),
   1082 					       MIDI_GET_CHAN(contig[0]),
   1083 					       cp, length);
   1084 		break;
   1085 	case FST_COM:
   1086 		error = sc->hw_if_ext->common(sc->hw_hdl,
   1087 		                              MIDI_GET_STATUS(contig[0]),
   1088 					      cp, length);
   1089 		break;
   1090 	case FST_SYX:
   1091 	case FST_SXP:
   1092 		error = sc->hw_if_ext->sysex(sc->hw_hdl,
   1093 					     cp, length);
   1094 		break;
   1095 	case FST_RT:
   1096 		error = sc->hw_if->output(sc->hw_hdl, *cp);
   1097 		break;
   1098 	default:
   1099 		error = EIO;
   1100 	}
   1101 
   1102 	if ( !error ) {
   1103 		++ idx_cur;
   1104 		MIDI_BUF_WRAP(idx);
   1105 		*idx  = idx_cur;
   1106 		*idxl = idx_lim;
   1107 		*buf  = buf_cur;
   1108 		*bufl = buf_lim;
   1109 	}
   1110 
   1111 	return error;
   1112 }
   1113 
   1114 /*
   1115  * midi_poll_out is intended for the midi hw (the vast majority of MIDI UARTs
   1116  * on sound cards, apparently) that _do not have transmit-ready interrupts_.
   1117  * Every call to hw_if->output for one of these may busy-wait to output the
   1118  * byte; at the standard midi data rate that'll be 320us per byte. The
   1119  * technique of writing only MIDI_MAX_WRITE bytes in a row and then waiting
   1120  * for MIDI_WAIT does not reduce the total time spent busy-waiting, and it
   1121  * adds arbitrary delays in transmission (and, since MIDI_WAIT is roughly the
   1122  * same as the time to send MIDI_MAX_WRITE bytes, it effectively halves the
   1123  * data rate). Here, a somewhat bolder approach is taken. Since midi traffic
   1124  * is bursty but time-sensitive--most of the time there will be none at all,
   1125  * but when there is it should go out ASAP--the strategy is to just get it
   1126  * over with, and empty the buffer in one go. The effect this can have on
   1127  * the rest of the system will be limited by the size of the buffer and the
   1128  * sparseness of the traffic. But some precautions are in order. Interrupts
   1129  * should all be unmasked when this is called, and midiwrite should not fill
   1130  * the buffer more than once (when MIDI_PROP_CAN_INTR is false) without a
   1131  * yield() so some other process can get scheduled. If the write is nonblocking,
   1132  * midiwrite should return a short count rather than yield.
   1133  *
   1134  * Someday when there is fine-grained MP support, this should be reworked to
   1135  * run in a callout so the writing process really could proceed concurrently.
   1136  * But obviously where performance is a concern, interrupt-driven hardware
   1137  * such as USB midi or (apparently) clcs will always be preferable. And it
   1138  * seems (kern/32651) that many of the devices currently working in poll mode
   1139  * may really have tx interrupt capability and want only implementation; that
   1140  * ought to happen.
   1141  */
   1142 int
   1143 midi_poll_out(struct midi_softc *sc)
   1144 {
   1145 	struct midi_buffer *mb = &sc->outbuf;
   1146 	int error;
   1147 	int msglen;
   1148 	int s;
   1149 	MIDI_BUF_DECLARE(idx);
   1150 	MIDI_BUF_DECLARE(buf);
   1151 
   1152 	error = 0;
   1153 
   1154 	MIDI_OUT_LOCK(sc,s);
   1155 	MIDI_BUF_CONSUMER_INIT(mb,idx);
   1156 	MIDI_BUF_CONSUMER_INIT(mb,buf);
   1157 	MIDI_OUT_UNLOCK(sc,s);
   1158 
   1159 	for ( ;; ) {
   1160 		while ( idx_cur != idx_lim ) {
   1161 			if ( sc->hw_if_ext ) {
   1162 				error = midi_msg_out(sc, &idx_cur, &idx_lim,
   1163 				                         &buf_cur, &buf_lim);
   1164 				if ( error )
   1165 					goto ioerror;
   1166 				continue;
   1167 			}
   1168 			/* or, lacking hw_if_ext ... */
   1169 			msglen = MB_IDX_LEN(*idx_cur);
   1170 			DPRINTFN(7,("midi_poll_out: %p <- %#02x\n",
   1171 				   sc->hw_hdl, *buf_cur));
   1172 			error = sc->hw_if->output(sc->hw_hdl, *buf_cur);
   1173 			if ( error )
   1174 				goto ioerror;
   1175 			++ buf_cur;
   1176 			MIDI_BUF_WRAP(buf);
   1177 			-- msglen;
   1178 			if ( msglen )
   1179 				*idx_cur = PACK_MB_IDX(MB_IDX_CAT(*idx_cur),
   1180 				                       msglen);
   1181 			else {
   1182 				++ idx_cur;
   1183 				MIDI_BUF_WRAP(idx);
   1184 			}
   1185 		}
   1186 		KASSERT(buf_cur == buf_lim);
   1187 		MIDI_OUT_LOCK(sc,s);
   1188 		MIDI_BUF_CONSUMER_WBACK(mb,idx);
   1189 		MIDI_BUF_CONSUMER_WBACK(mb,buf);
   1190 		MIDI_BUF_CONSUMER_REFRESH(mb,idx); /* any more to transmit? */
   1191 		MIDI_BUF_CONSUMER_REFRESH(mb,buf);
   1192 		if ( idx_lim == idx_cur )
   1193 			break; /* still holding lock */
   1194 		MIDI_OUT_UNLOCK(sc,s);
   1195 	}
   1196 	goto disarm; /* lock held */
   1197 
   1198 ioerror:
   1199 #if defined(AUDIO_DEBUG) || defined(DIAGNOSTIC)
   1200 	printf("%s: midi_poll_output error %d\n",
   1201 	      sc->dev.dv_xname, error);
   1202 #endif
   1203 	MIDI_OUT_LOCK(sc,s);
   1204 	MIDI_BUF_CONSUMER_WBACK(mb,idx);
   1205 	MIDI_BUF_CONSUMER_WBACK(mb,buf);
   1206 
   1207 disarm:
   1208 	sc->pbus = 0;
   1209 	callout_schedule(&sc->xmt_asense_co, MIDI_XMT_ASENSE_PERIOD);
   1210 	MIDI_OUT_UNLOCK(sc,s);
   1211 	return error;
   1212 }
   1213 
   1214 /*
   1215  * The interrupt flavor acquires spl and lock once and releases at the end,
   1216  * as it expects to write only one byte or message. The interface convention
   1217  * is that if hw_if->output returns 0, it has initiated transmission and the
   1218  * completion interrupt WILL be forthcoming; if it has not returned 0, NO
   1219  * interrupt will be forthcoming, and if it returns EINPROGRESS it wants
   1220  * another byte right away.
   1221  */
   1222 int
   1223 midi_intr_out(struct midi_softc *sc)
   1224 {
   1225 	struct midi_buffer *mb = &sc->outbuf;
   1226 	int error;
   1227 	int msglen;
   1228 	int s;
   1229 	MIDI_BUF_DECLARE(idx);
   1230 	MIDI_BUF_DECLARE(buf);
   1231 	int armed = 0;
   1232 
   1233 	error = 0;
   1234 
   1235 	MIDI_OUT_LOCK(sc,s);
   1236 	MIDI_BUF_CONSUMER_INIT(mb,idx);
   1237 	MIDI_BUF_CONSUMER_INIT(mb,buf);
   1238 
   1239 	while ( idx_cur != idx_lim ) {
   1240 		if ( sc->hw_if_ext ) {
   1241 			error = midi_msg_out(sc, &idx_cur, &idx_lim,
   1242 				                 &buf_cur, &buf_lim);
   1243 			if ( !error ) /* no EINPROGRESS from extended hw_if */
   1244 				armed = 1;
   1245 			break;
   1246 		}
   1247 		/* or, lacking hw_if_ext ... */
   1248 		msglen = MB_IDX_LEN(*idx_cur);
   1249 		error = sc->hw_if->output(sc->hw_hdl, *buf_cur);
   1250 		if ( error  &&  error != EINPROGRESS )
   1251 			break;
   1252 		++ buf_cur;
   1253 		MIDI_BUF_WRAP(buf);
   1254 		-- msglen;
   1255 		if ( msglen )
   1256 			*idx_cur = PACK_MB_IDX(MB_IDX_CAT(*idx_cur),msglen);
   1257 		else {
   1258 			++ idx_cur;
   1259 			MIDI_BUF_WRAP(idx);
   1260 		}
   1261 		if ( !error ) {
   1262 			armed = 1;
   1263 			break;
   1264 		}
   1265 	}
   1266 	MIDI_BUF_CONSUMER_WBACK(mb,idx);
   1267 	MIDI_BUF_CONSUMER_WBACK(mb,buf);
   1268 	if ( !armed ) {
   1269 		sc->pbus = 0;
   1270 		callout_schedule(&sc->xmt_asense_co, MIDI_XMT_ASENSE_PERIOD);
   1271 	}
   1272 	midi_wakeup(&sc->wchan);
   1273 	if ( sc->async ) {
   1274 		mutex_enter(&proclist_mutex);
   1275 		psignal(sc->async, SIGIO);
   1276 		mutex_exit(&proclist_mutex);
   1277 	}
   1278 	MIDI_OUT_UNLOCK(sc,s);
   1279 	selnotify(&sc->wsel, 0); /* filter will spin if locked */
   1280 
   1281 #if defined(AUDIO_DEBUG) || defined(DIAGNOSTIC)
   1282 	if ( error )
   1283 		printf("%s: midi_intr_output error %d\n",
   1284 	               sc->dev.dv_xname, error);
   1285 #endif
   1286 	return error;
   1287 }
   1288 
   1289 int
   1290 midi_start_output(struct midi_softc *sc)
   1291 {
   1292 	if (sc->dying)
   1293 		return EIO;
   1294 
   1295 	if ( sc->props & MIDI_PROP_OUT_INTR )
   1296 		return midi_intr_out(sc);
   1297 	return midi_poll_out(sc);
   1298 }
   1299 
   1300 static int
   1301 real_writebytes(struct midi_softc *sc, u_char *ibuf, int cc)
   1302 {
   1303 	u_char *iend = ibuf + cc;
   1304 	struct midi_buffer *mb = &sc->outbuf;
   1305 	int arming = 0;
   1306 	int count;
   1307 	int s;
   1308 	int got;
   1309 	enum fst_form form;
   1310 	MIDI_BUF_DECLARE(idx);
   1311 	MIDI_BUF_DECLARE(buf);
   1312 
   1313 	/*
   1314 	 * If the hardware uses the extended hw_if, pass it canonicalized
   1315 	 * messages (or compressed ones if it specifically requests, using
   1316 	 * VCOMP form so the bottom half can still pass the op and chan along);
   1317 	 * if it does not, send it compressed messages (using COMPR form as
   1318 	 * there is no need to preserve the status for the bottom half).
   1319 	 */
   1320 	if ( NULL == sc->hw_if_ext )
   1321 		form = FST_COMPR;
   1322 	else if ( sc->hw_if_ext->compress )
   1323 		form = FST_VCOMP;
   1324 	else
   1325 		form = FST_CANON;
   1326 
   1327 	MIDI_OUT_LOCK(sc,s);
   1328 	MIDI_BUF_PRODUCER_INIT(mb,idx);
   1329 	MIDI_BUF_PRODUCER_INIT(mb,buf);
   1330 	MIDI_OUT_UNLOCK(sc,s);
   1331 
   1332 	if (sc->dying)
   1333 		return EIO;
   1334 
   1335 	while ( ibuf < iend ) {
   1336 		got = midi_fst(&sc->xmt, *ibuf, form);
   1337 		++ ibuf;
   1338 		switch ( got ) {
   1339 		case FST_MORE:
   1340 			continue;
   1341 		case FST_ERR:
   1342 		case FST_HUH:
   1343 			return EPROTO;
   1344 		case FST_CHN:
   1345 		case FST_CHV: /* only occurs in VCOMP form */
   1346 		case FST_COM:
   1347 		case FST_RT:
   1348 		case FST_SYX:
   1349 		case FST_SXP:
   1350 			break; /* go add to buffer */
   1351 #if defined(AUDIO_DEBUG) || defined(DIAGNOSTIC)
   1352 		default:
   1353 			printf("midi_wr: midi_fst returned %d?!\n", got);
   1354 #endif
   1355 		}
   1356 		count = sc->xmt.end - sc->xmt.pos;
   1357 		if ( 0 == count ) /* can happen with stray 0xf7; see midi_fst */
   1358 			continue;
   1359 		/*
   1360 		 * return EWOULDBLOCK if the data passed will not fit in
   1361 		 * the buffer; the caller should have taken steps to avoid that.
   1362 		 * If got==FST_SXP we lose the new status byte, but we're losing
   1363 		 * anyway, so c'est la vie.
   1364 		 */
   1365 		if ( idx_cur == idx_lim || count > buf_lim - buf_cur ) {
   1366 			MIDI_OUT_LOCK(sc,s);
   1367 			MIDI_BUF_PRODUCER_REFRESH(mb,idx); /* get the most */
   1368 			MIDI_BUF_PRODUCER_REFRESH(mb,buf); /*  current facts */
   1369 			MIDI_OUT_UNLOCK(sc,s);
   1370 			if ( idx_cur == idx_lim || count > buf_lim - buf_cur )
   1371 				return EWOULDBLOCK; /* caller's problem */
   1372 		}
   1373 		*idx_cur++ = PACK_MB_IDX(got,count);
   1374 		MIDI_BUF_WRAP(idx);
   1375 		while ( count ) {
   1376 			*buf_cur++ = *(sc->xmt.pos)++;
   1377 			MIDI_BUF_WRAP(buf);
   1378 			-- count;
   1379 		}
   1380 		if ( FST_SXP == got )
   1381 			-- ibuf; /* again with same status byte */
   1382 	}
   1383 	MIDI_OUT_LOCK(sc,s);
   1384 	MIDI_BUF_PRODUCER_WBACK(mb,buf);
   1385 	MIDI_BUF_PRODUCER_WBACK(mb,idx);
   1386 	/*
   1387 	 * If the output transfer is not already busy, and there is a message
   1388 	 * buffered, mark it busy, stop the Active Sense callout (what if we're
   1389 	 * too late and it's expired already? No big deal, an extra Active Sense
   1390 	 * never hurt anybody) and start the output transfer once we're out of
   1391 	 * the critical section (pbus==1 will stop anyone else doing the same).
   1392 	 */
   1393 	MIDI_BUF_CONSUMER_INIT(mb,idx); /* check what consumer's got to read */
   1394 	if ( !sc->pbus && idx_cur < idx_lim ) {
   1395 		sc->pbus = 1;
   1396 		callout_stop(&sc->xmt_asense_co);
   1397 		arming = 1;
   1398 	}
   1399 	MIDI_OUT_UNLOCK(sc,s);
   1400 	return arming ? midi_start_output(sc) : 0;
   1401 }
   1402 
   1403 int
   1404 midiwrite(dev_t dev, struct uio *uio, int ioflag)
   1405 {
   1406 	int unit = MIDIUNIT(dev);
   1407 	struct midi_softc *sc = midi_cd.cd_devs[unit];
   1408 	struct midi_buffer *mb = &sc->outbuf;
   1409 	int error;
   1410 	u_char inp[256];
   1411 	int s;
   1412 	MIDI_BUF_DECLARE(idx);
   1413 	MIDI_BUF_DECLARE(buf);
   1414 	size_t idxspace;
   1415 	size_t bufspace;
   1416 	size_t xfrcount;
   1417 	int pollout = 0;
   1418 
   1419 	DPRINTFN(6, ("midiwrite: %p, unit=%d, count=%lu\n", sc, unit,
   1420 		     (unsigned long)uio->uio_resid));
   1421 
   1422 	if (sc->dying)
   1423 		return EIO;
   1424 
   1425 	error = 0;
   1426 	while (uio->uio_resid > 0 && !error) {
   1427 
   1428 		/*
   1429 		 * block if necessary for the minimum buffer space to guarantee
   1430 		 * we can write something.
   1431 		 */
   1432 		MIDI_OUT_LOCK(sc,s);
   1433 		MIDI_BUF_PRODUCER_INIT(mb,idx); /* init can't go above loop; */
   1434 		MIDI_BUF_PRODUCER_INIT(mb,buf); /* real_writebytes moves cur */
   1435 		for ( ;; ) {
   1436 			idxspace = MIDI_BUF_PRODUCER_REFRESH(mb,idx) - idx_cur;
   1437 			bufspace = MIDI_BUF_PRODUCER_REFRESH(mb,buf) - buf_cur;
   1438 			if ( idxspace >= 1  &&  bufspace >= 3  && !pollout )
   1439 				break;
   1440 			DPRINTFN(8,("midi_write: sleep idx=%d buf=%d\n",
   1441 				 idxspace, bufspace));
   1442 			if (ioflag & IO_NDELAY) {
   1443 				error = EWOULDBLOCK;
   1444 				/*
   1445 				 * If some amount has already been transferred,
   1446 				 * the common syscall code will automagically
   1447 				 * convert this to success with a short count.
   1448 				 */
   1449 				goto locked_exit;
   1450 			}
   1451 			if ( pollout ) {
   1452 				preempt(0); /* see midi_poll_output */
   1453 				pollout = 0;
   1454 			} else
   1455 				error = midi_sleep(&sc->wchan, "mid wr",
   1456 				                   &sc->out_lock);
   1457 			if (error)
   1458 				/*
   1459 				 * Similarly, the common code will handle
   1460 				 * EINTR and ERESTART properly here, changing to
   1461 				 * a short count if something transferred.
   1462 				 */
   1463 				goto locked_exit;
   1464 		}
   1465 		MIDI_OUT_UNLOCK(sc,s);
   1466 
   1467 		/*
   1468 		 * The number of bytes we can safely extract from the uio
   1469 		 * depends on the available idx and buf space. Worst case,
   1470 		 * every byte is a message so 1 idx is required per byte.
   1471 		 * Worst case, the first byte completes a 3-byte msg in prior
   1472 		 * state, and every subsequent byte is a Program Change or
   1473 		 * Channel Pressure msg with running status and expands to 2
   1474 		 * bytes, so the buf space reqd is 3+2(n-1) or 2n+1. So limit
   1475 		 * the transfer to the min of idxspace and (bufspace-1)>>1.
   1476 		 */
   1477 		xfrcount = (bufspace - 1) >> 1;
   1478 		if ( xfrcount > idxspace )
   1479 			xfrcount = idxspace;
   1480 		if ( xfrcount > sizeof inp )
   1481 			xfrcount = sizeof inp;
   1482 		if ( xfrcount > uio->uio_resid )
   1483 			xfrcount = uio->uio_resid;
   1484 
   1485 		error = uiomove(inp, xfrcount, uio);
   1486 #ifdef MIDI_DEBUG
   1487 		if (error)
   1488 		        printf("midi_write:(1) uiomove failed %d; "
   1489 			       "xfrcount=%d inp=%p\n",
   1490 			       error, xfrcount, inp);
   1491 #endif
   1492 		if ( error )
   1493 			break;
   1494 
   1495 		/*
   1496 		 * The number of bytes we extracted being calculated to
   1497 		 * definitely fit in the buffer even with canonicalization,
   1498 		 * there is no excuse for real_writebytes to return EWOULDBLOCK.
   1499 		 */
   1500 		error = real_writebytes(sc, inp, xfrcount);
   1501 		KASSERT(error != EWOULDBLOCK);
   1502 
   1503 		if ( error )
   1504 			break;
   1505 		/*
   1506 		 * If this is a polling device and we just sent a buffer, let's
   1507 		 * not send another without giving some other process a chance.
   1508 		 */
   1509 		if ( ! (sc->props & MIDI_PROP_OUT_INTR) )
   1510 			pollout = 1;
   1511 		DPRINTFN(8,("midiwrite: uio_resid now %u, props=%d\n",
   1512                         uio->uio_resid, sc->props));
   1513 	}
   1514 	return error;
   1515 
   1516 locked_exit:
   1517 	MIDI_OUT_UNLOCK(sc,s);
   1518 	return error;
   1519 }
   1520 
   1521 /*
   1522  * This write routine is only called from sequencer code and expects
   1523  * a write that is smaller than the MIDI buffer.
   1524  */
   1525 int
   1526 midi_writebytes(int unit, u_char *bf, int cc)
   1527 {
   1528 	struct midi_softc *sc = midi_cd.cd_devs[unit];
   1529 
   1530 	DPRINTFN(7, ("midi_writebytes: %p, unit=%d, cc=%d %#02x %#02x %#02x\n",
   1531                     sc, unit, cc, bf[0], bf[1], bf[2]));
   1532 	return real_writebytes(sc, bf, cc);
   1533 }
   1534 
   1535 int
   1536 midiioctl(dev_t dev, u_long cmd, caddr_t addr, int flag, struct lwp *l)
   1537 {
   1538 	int unit = MIDIUNIT(dev);
   1539 	struct midi_softc *sc = midi_cd.cd_devs[unit];
   1540 	const struct midi_hw_if *hw = sc->hw_if;
   1541 	int error;
   1542 	int s;
   1543 	MIDI_BUF_DECLARE(buf);
   1544 
   1545 	DPRINTFN(5,("midiioctl: %p cmd=0x%08lx\n", sc, cmd));
   1546 
   1547 	if (sc->dying)
   1548 		return EIO;
   1549 
   1550 	error = 0;
   1551 	switch (cmd) {
   1552 	case FIONBIO:
   1553 		/* All handled in the upper FS layer. */
   1554 		break;
   1555 
   1556 	case FIONREAD:
   1557 		/*
   1558 		 * This code relies on the current implementation of midi_in
   1559 		 * always updating buf and idx together in a critical section,
   1560 		 * so buf always ends at a message boundary. Document this
   1561 		 * ioctl as always returning a value such that the last message
   1562 		 * included is complete (SysEx the only exception), and then
   1563 		 * make sure the implementation doesn't regress.  NB that
   1564 		 * means if this ioctl returns n and the proc then issues a
   1565 		 * read of n, n bytes will be read, but if the proc issues a
   1566 		 * read of m < n, fewer than m bytes may be read to ensure the
   1567 		 * read ends at a message boundary.
   1568 		 */
   1569 		MIDI_IN_LOCK(sc,s);
   1570 		MIDI_BUF_CONSUMER_INIT(&sc->inbuf,buf);
   1571 		MIDI_IN_UNLOCK(sc,s);
   1572 		*(int *)addr = buf_lim - buf_cur;
   1573 		break;
   1574 
   1575 	case FIOASYNC:
   1576 		if (*(int *)addr) {
   1577 			if (sc->async)
   1578 				return EBUSY;
   1579 			sc->async = l->l_proc;
   1580 			DPRINTFN(5,("midi_ioctl: FIOASYNC %p\n", l->l_proc));
   1581 		} else
   1582 			sc->async = 0;
   1583 		break;
   1584 
   1585 #if 0
   1586 	case MIDI_PRETIME:
   1587 		/* XXX OSS
   1588 		 * This should set up a read timeout, but that's
   1589 		 * why we have poll(), so there's nothing yet. */
   1590 		error = EINVAL;
   1591 		break;
   1592 #endif
   1593 
   1594 #ifdef MIDI_SAVE
   1595 	case MIDI_GETSAVE:
   1596 		error = copyout(&midisave, *(void **)addr, sizeof midisave);
   1597   		break;
   1598 #endif
   1599 
   1600 	default:
   1601 		if (hw->ioctl)
   1602 			error = hw->ioctl(sc->hw_hdl, cmd, addr, flag, l);
   1603 		else
   1604 			error = EINVAL;
   1605 		break;
   1606 	}
   1607 	return error;
   1608 }
   1609 
   1610 int
   1611 midipoll(dev_t dev, int events, struct lwp *l)
   1612 {
   1613 	int unit = MIDIUNIT(dev);
   1614 	struct midi_softc *sc = midi_cd.cd_devs[unit];
   1615 	int revents = 0;
   1616 	int s;
   1617 	MIDI_BUF_DECLARE(idx);
   1618 	MIDI_BUF_DECLARE(buf);
   1619 
   1620 	DPRINTFN(6,("midipoll: %p events=0x%x\n", sc, events));
   1621 
   1622 	if (sc->dying)
   1623 		return POLLHUP;
   1624 
   1625 	s = splaudio();
   1626 
   1627 	if ((sc->flags&FREAD) && (events & (POLLIN | POLLRDNORM))) {
   1628 		simple_lock(&sc->in_lock);
   1629 		MIDI_BUF_CONSUMER_INIT(&sc->inbuf,idx);
   1630 		if (idx_cur < idx_lim)
   1631 			revents |= events & (POLLIN | POLLRDNORM);
   1632 		else
   1633 			selrecord(l, &sc->rsel);
   1634 		simple_unlock(&sc->in_lock);
   1635 	}
   1636 
   1637 	if ((sc->flags&FWRITE) && (events & (POLLOUT | POLLWRNORM))) {
   1638 		simple_lock(&sc->out_lock);
   1639 		MIDI_BUF_PRODUCER_INIT(&sc->outbuf,idx);
   1640 		MIDI_BUF_PRODUCER_INIT(&sc->outbuf,buf);
   1641 		if ( idx_lim - idx_cur >= 1  &&  buf_lim - buf_cur >= 3 )
   1642 			revents |= events & (POLLOUT | POLLWRNORM);
   1643 		else
   1644 			selrecord(l, &sc->wsel);
   1645 		simple_unlock(&sc->out_lock);
   1646 	}
   1647 
   1648 	splx(s);
   1649 	return revents;
   1650 }
   1651 
   1652 static void
   1653 filt_midirdetach(struct knote *kn)
   1654 {
   1655 	struct midi_softc *sc = kn->kn_hook;
   1656 	int s;
   1657 
   1658 	s = splaudio();
   1659 	SLIST_REMOVE(&sc->rsel.sel_klist, kn, knote, kn_selnext);
   1660 	splx(s);
   1661 }
   1662 
   1663 static int
   1664 filt_midiread(struct knote *kn, long hint)
   1665 {
   1666 	struct midi_softc *sc = kn->kn_hook;
   1667 	int s;
   1668 	MIDI_BUF_DECLARE(buf);
   1669 
   1670 	/* XXXLUKEM (thorpej): please make sure this is correct. */
   1671 
   1672 	MIDI_IN_LOCK(sc,s);
   1673 	MIDI_BUF_CONSUMER_INIT(&sc->inbuf,buf);
   1674 	kn->kn_data = buf_lim - buf_cur;
   1675 	MIDI_IN_UNLOCK(sc,s);
   1676 	return (kn->kn_data > 0);
   1677 }
   1678 
   1679 static const struct filterops midiread_filtops =
   1680 	{ 1, NULL, filt_midirdetach, filt_midiread };
   1681 
   1682 static void
   1683 filt_midiwdetach(struct knote *kn)
   1684 {
   1685 	struct midi_softc *sc = kn->kn_hook;
   1686 	int s;
   1687 
   1688 	s = splaudio();
   1689 	SLIST_REMOVE(&sc->wsel.sel_klist, kn, knote, kn_selnext);
   1690 	splx(s);
   1691 }
   1692 
   1693 static int
   1694 filt_midiwrite(struct knote *kn, long hint)
   1695 {
   1696 	struct midi_softc *sc = kn->kn_hook;
   1697 	int s;
   1698 	MIDI_BUF_DECLARE(idx);
   1699 	MIDI_BUF_DECLARE(buf);
   1700 
   1701 	/* XXXLUKEM (thorpej): please make sure this is correct. */
   1702 
   1703 	MIDI_OUT_LOCK(sc,s);
   1704 	MIDI_BUF_PRODUCER_INIT(&sc->outbuf,idx);
   1705 	MIDI_BUF_PRODUCER_INIT(&sc->outbuf,buf);
   1706 	kn->kn_data = ((buf_lim - buf_cur)-1)>>1;
   1707 	if ( kn->kn_data > idx_lim - idx_cur )
   1708 		kn->kn_data = idx_lim - idx_cur;
   1709 	MIDI_OUT_UNLOCK(sc,s);
   1710 	return (kn->kn_data > 0);
   1711 }
   1712 
   1713 static const struct filterops midiwrite_filtops =
   1714 	{ 1, NULL, filt_midiwdetach, filt_midiwrite };
   1715 
   1716 int
   1717 midikqfilter(dev_t dev, struct knote *kn)
   1718 {
   1719 	int unit = MIDIUNIT(dev);
   1720 	struct midi_softc *sc = midi_cd.cd_devs[unit];
   1721 	struct klist *klist;
   1722 	int s;
   1723 
   1724 	switch (kn->kn_filter) {
   1725 	case EVFILT_READ:
   1726 		klist = &sc->rsel.sel_klist;
   1727 		kn->kn_fop = &midiread_filtops;
   1728 		break;
   1729 
   1730 	case EVFILT_WRITE:
   1731 		klist = &sc->wsel.sel_klist;
   1732 		kn->kn_fop = &midiwrite_filtops;
   1733 		break;
   1734 
   1735 	default:
   1736 		return (1);
   1737 	}
   1738 
   1739 	kn->kn_hook = sc;
   1740 
   1741 	s = splaudio();
   1742 	SLIST_INSERT_HEAD(klist, kn, kn_selnext);
   1743 	splx(s);
   1744 
   1745 	return (0);
   1746 }
   1747 
   1748 void
   1749 midi_getinfo(dev_t dev, struct midi_info *mi)
   1750 {
   1751 	struct midi_softc *sc;
   1752 
   1753 	sc = device_lookup(&midi_cd, MIDIUNIT(dev));
   1754 	if (sc == NULL)
   1755 		return;
   1756 	if (sc->dying)
   1757 		return;
   1758 
   1759 	sc->hw_if->getinfo(sc->hw_hdl, mi);
   1760 }
   1761 
   1762 #elif NMIDIBUS > 0 /* but NMIDI == 0 */
   1763 
   1764 void midi_register_hw_if_ext(struct midi_hw_if_ext *exthw) { /* stub */
   1765 }
   1766 
   1767 #endif /* NMIDI > 0 */
   1768 
   1769 #if NMIDI > 0 || NMIDIBUS > 0
   1770 
   1771 int	audioprint(void *, const char *);
   1772 
   1773 struct device *
   1774 midi_attach_mi(const struct midi_hw_if *mhwp, void *hdlp, struct device *dev)
   1775 {
   1776 	struct audio_attach_args arg;
   1777 
   1778 #ifdef DIAGNOSTIC
   1779 	if (mhwp == NULL) {
   1780 		aprint_error("midi_attach_mi: NULL\n");
   1781 		return (0);
   1782 	}
   1783 #endif
   1784 	arg.type = AUDIODEV_TYPE_MIDI;
   1785 	arg.hwif = mhwp;
   1786 	arg.hdl = hdlp;
   1787 	return (config_found(dev, &arg, audioprint));
   1788 }
   1789 
   1790 #endif /* NMIDI > 0 || NMIDIBUS > 0 */
   1791