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