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