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