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