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