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