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