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