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