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