sequencer.c revision 1.65 1 /* $NetBSD: sequencer.c,v 1.65 2017/06/01 02:45:09 chs Exp $ */
2
3 /*
4 * Copyright (c) 1998, 2008 The NetBSD Foundation, Inc.
5 * All rights reserved.
6 *
7 * This code is derived from software contributed to The NetBSD Foundation
8 * by Lennart Augustsson (augustss (at) NetBSD.org) and by Andrew Doran.
9 *
10 * Redistribution and use in source and binary forms, with or without
11 * modification, are permitted provided that the following conditions
12 * are met:
13 * 1. Redistributions of source code must retain the above copyright
14 * notice, this list of conditions and the following disclaimer.
15 * 2. Redistributions in binary form must reproduce the above copyright
16 * notice, this list of conditions and the following disclaimer in the
17 * documentation and/or other materials provided with the distribution.
18 *
19 * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
20 * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
21 * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
22 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
23 * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
24 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
25 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
26 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
27 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
28 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
29 * POSSIBILITY OF SUCH DAMAGE.
30 */
31
32 /*
33 * Locking:
34 *
35 * o sc_lock: provides atomic access to all data structures. Taken from
36 * both process and soft interrupt context.
37 *
38 * o sc_dvlock: serializes operations on /dev/sequencer. Taken from
39 * process context. Dropped while waiting for data in sequencerread()
40 * to allow concurrent reads/writes while no data available.
41 *
42 * o sc_isopen: we allow only one concurrent open, only to prevent user
43 * and/or application error.
44 *
45 * o MIDI softc locks. These can be spinlocks and there can be many of
46 * them, because we can open many MIDI devices. We take these only in two
47 * places: when enabling redirection from the MIDI device and when
48 * disabling it (open/close). midiseq_in() is called by the MIDI driver
49 * with its own lock held when passing data into this module. To avoid
50 * lock order and context problems, we package the received message as a
51 * sequencer_pcqitem_t and put onto a producer-consumer queue. A soft
52 * interrupt is scheduled to dequeue and decode the message later where we
53 * can safely acquire the sequencer device's sc_lock. PCQ is lockless for
54 * multiple producer, single consumer settings like this one.
55 */
56
57 #include <sys/cdefs.h>
58 __KERNEL_RCSID(0, "$NetBSD: sequencer.c,v 1.65 2017/06/01 02:45:09 chs Exp $");
59
60 #include "sequencer.h"
61
62 #include <sys/param.h>
63 #include <sys/ioctl.h>
64 #include <sys/fcntl.h>
65 #include <sys/vnode.h>
66 #include <sys/select.h>
67 #include <sys/poll.h>
68 #include <sys/kmem.h>
69 #include <sys/proc.h>
70 #include <sys/systm.h>
71 #include <sys/syslog.h>
72 #include <sys/kernel.h>
73 #include <sys/signalvar.h>
74 #include <sys/conf.h>
75 #include <sys/audioio.h>
76 #include <sys/midiio.h>
77 #include <sys/device.h>
78 #include <sys/intr.h>
79 #include <sys/atomic.h>
80 #include <sys/pcq.h>
81 #include <sys/vnode.h>
82 #include <sys/kauth.h>
83
84 #include <dev/midi_if.h>
85 #include <dev/midivar.h>
86 #include <dev/sequencervar.h>
87
88 #include "ioconf.h"
89
90 #define ADDTIMEVAL(a, b) ( \
91 (a)->tv_sec += (b)->tv_sec, \
92 (a)->tv_usec += (b)->tv_usec, \
93 (a)->tv_usec > 1000000 ? ((a)->tv_sec++, (a)->tv_usec -= 1000000) : 0\
94 )
95
96 #define SUBTIMEVAL(a, b) ( \
97 (a)->tv_sec -= (b)->tv_sec, \
98 (a)->tv_usec -= (b)->tv_usec, \
99 (a)->tv_usec < 0 ? ((a)->tv_sec--, (a)->tv_usec += 1000000) : 0\
100 )
101
102 #ifdef AUDIO_DEBUG
103 #define DPRINTF(x) if (sequencerdebug) printf x
104 #define DPRINTFN(n,x) if (sequencerdebug >= (n)) printf x
105 int sequencerdebug = 0;
106 #else
107 #define DPRINTF(x)
108 #define DPRINTFN(n,x)
109 #endif
110
111 #define SEQ_NOTE_MAX 128
112 #define SEQ_NOTE_XXX 255
113
114 #define RECALC_USPERDIV(t) \
115 ((t)->usperdiv = 60*1000000L/((t)->tempo_beatpermin*(t)->timebase_divperbeat))
116
117 typedef union sequencer_pcqitem {
118 void *qi_ptr;
119 char qi_msg[4];
120 } sequencer_pcqitem_t;
121
122 static void seq_reset(struct sequencer_softc *);
123 static int seq_do_command(struct sequencer_softc *, seq_event_t *);
124 static int seq_do_chnvoice(struct sequencer_softc *, seq_event_t *);
125 static int seq_do_chncommon(struct sequencer_softc *, seq_event_t *);
126 static void seq_timer_waitabs(struct sequencer_softc *, uint32_t);
127 static int seq_do_timing(struct sequencer_softc *, seq_event_t *);
128 static int seq_do_local(struct sequencer_softc *, seq_event_t *);
129 static int seq_do_sysex(struct sequencer_softc *, seq_event_t *);
130 static int seq_do_fullsize(struct sequencer_softc *, seq_event_t *, struct uio *);
131 static int seq_input_event(struct sequencer_softc *, seq_event_t *);
132 static int seq_drain(struct sequencer_softc *);
133 static void seq_startoutput(struct sequencer_softc *);
134 static void seq_timeout(void *);
135 static int seq_to_new(seq_event_t *, struct uio *);
136 static void seq_softintr(void *);
137
138 static int midiseq_out(struct midi_dev *, u_char *, u_int, int);
139 static struct midi_dev *midiseq_open(int, int);
140 static void midiseq_close(struct midi_dev *);
141 static void midiseq_reset(struct midi_dev *);
142 static int midiseq_noteon(struct midi_dev *, int, int, seq_event_t *);
143 static int midiseq_noteoff(struct midi_dev *, int, int, seq_event_t *);
144 static int midiseq_keypressure(struct midi_dev *, int, int, seq_event_t *);
145 static int midiseq_pgmchange(struct midi_dev *, int, seq_event_t *);
146 static int midiseq_chnpressure(struct midi_dev *, int, seq_event_t *);
147 static int midiseq_ctlchange(struct midi_dev *, int, seq_event_t *);
148 static int midiseq_pitchbend(struct midi_dev *, int, seq_event_t *);
149 static int midiseq_loadpatch(struct midi_dev *, struct sysex_info *, struct uio *);
150 void midiseq_in(struct midi_dev *, u_char *, int);
151
152 static dev_type_open(sequenceropen);
153 static dev_type_close(sequencerclose);
154 static dev_type_read(sequencerread);
155 static dev_type_write(sequencerwrite);
156 static dev_type_ioctl(sequencerioctl);
157 static dev_type_poll(sequencerpoll);
158 static dev_type_kqfilter(sequencerkqfilter);
159
160 const struct cdevsw sequencer_cdevsw = {
161 .d_open = sequenceropen,
162 .d_close = sequencerclose,
163 .d_read = sequencerread,
164 .d_write = sequencerwrite,
165 .d_ioctl = sequencerioctl,
166 .d_stop = nostop,
167 .d_tty = notty,
168 .d_poll = sequencerpoll,
169 .d_mmap = nommap,
170 .d_kqfilter = sequencerkqfilter,
171 .d_discard = nodiscard,
172 .d_flag = D_OTHER | D_MPSAFE
173 };
174 static LIST_HEAD(, sequencer_softc) sequencers = LIST_HEAD_INITIALIZER(sequencers);
175 static kmutex_t sequencer_lock;
176
177 static void
178 sequencerdestroy(struct sequencer_softc *sc)
179 {
180 callout_halt(&sc->sc_callout, &sc->lock);
181 callout_destroy(&sc->sc_callout);
182 softint_disestablish(sc->sih);
183 cv_destroy(&sc->rchan);
184 cv_destroy(&sc->wchan);
185 cv_destroy(&sc->lchan);
186 if (sc->pcq)
187 pcq_destroy(sc->pcq);
188 kmem_free(sc, sizeof(*sc));
189 }
190
191 static struct sequencer_softc *
192 sequencercreate(int unit)
193 {
194 struct sequencer_softc *sc = kmem_zalloc(sizeof(*sc), KM_SLEEP);
195 sc->sc_unit = unit;
196 callout_init(&sc->sc_callout, CALLOUT_MPSAFE);
197 sc->sih = softint_establish(SOFTINT_NET | SOFTINT_MPSAFE,
198 seq_softintr, sc);
199 mutex_init(&sc->lock, MUTEX_DEFAULT, IPL_NONE);
200 cv_init(&sc->rchan, "midiseqr");
201 cv_init(&sc->wchan, "midiseqw");
202 cv_init(&sc->lchan, "midiseql");
203 sc->pcq = pcq_create(SEQ_MAXQ, KM_SLEEP);
204 if (sc->pcq == NULL) {
205 sequencerdestroy(sc);
206 return NULL;
207 }
208 return sc;
209 }
210
211
212 static struct sequencer_softc *
213 sequencerget(int unit)
214 {
215 struct sequencer_softc *sc;
216 if (unit < 0) {
217 #ifdef DIAGNOSTIC
218 panic("%s: unit %d!", __func__, unit);
219 #endif
220 return NULL;
221 }
222 mutex_enter(&sequencer_lock);
223 LIST_FOREACH(sc, &sequencers, sc_link) {
224 if (sc->sc_unit == unit) {
225 mutex_exit(&sequencer_lock);
226 return sc;
227 }
228 }
229 mutex_exit(&sequencer_lock);
230 if ((sc = sequencercreate(unit)) == NULL)
231 return NULL;
232 mutex_enter(&sequencer_lock);
233 LIST_INSERT_HEAD(&sequencers, sc, sc_link);
234 mutex_exit(&sequencer_lock);
235 return sc;
236 }
237
238 #ifdef notyet
239 static void
240 sequencerput(struct sequencer_softc *sc)
241 {
242 mutex_enter(&sequencer_lock);
243 LIST_REMOVE(sc, sc_link);
244 mutex_exit(&sequencer_lock);
245 sequencerdestroy(sc);
246 }
247 #endif
248
249 void
250 sequencerattach(int n)
251 {
252 mutex_init(&sequencer_lock, MUTEX_DEFAULT, IPL_NONE);
253 }
254
255 /*
256 * Release reference to device acquired with sequencer_enter().
257 */
258 static void
259 sequencer_exit(struct sequencer_softc *sc)
260 {
261
262 sc->dvlock--;
263 cv_broadcast(&sc->lchan);
264 mutex_exit(&sc->lock);
265 }
266
267 /*
268 * Look up sequencer device and acquire locks for device access.
269 */
270 static int
271 sequencer_enter(dev_t dev, struct sequencer_softc **scp)
272 {
273 struct sequencer_softc *sc;
274
275 /* First, find the device and take sc_lock. */
276 if ((sc = sequencerget(SEQUENCERUNIT(dev))) == NULL)
277 return ENXIO;
278 mutex_enter(&sc->lock);
279 while (sc->dvlock) {
280 cv_wait(&sc->lchan, &sc->lock);
281 }
282 sc->dvlock++;
283 if (sc->dying) {
284 sequencer_exit(sc);
285 return EIO;
286 }
287 *scp = sc;
288 return 0;
289 }
290
291 static int
292 sequenceropen(dev_t dev, int flags, int ifmt, struct lwp *l)
293 {
294 struct sequencer_softc *sc;
295 struct midi_dev *md;
296 struct midi_softc *msc;
297 int error, unit, mdno;
298
299 DPRINTF(("sequenceropen\n"));
300
301 if ((error = sequencer_enter(dev, &sc)) != 0)
302 return error;
303 if (sc->isopen != 0) {
304 sequencer_exit(sc);
305 return EBUSY;
306 }
307
308 if (SEQ_IS_OLD(SEQUENCERUNIT(dev)))
309 sc->mode = SEQ_OLD;
310 else
311 sc->mode = SEQ_NEW;
312 sc->isopen++;
313 sc->flags = flags & (FREAD|FWRITE);
314 sc->pbus = 0;
315 sc->async = 0;
316 sc->input_stamp = ~0;
317
318 sc->nmidi = 0;
319 sc->ndevs = midi_unit_count();
320 sc->timer.timebase_divperbeat = 100;
321 sc->timer.tempo_beatpermin = 60;
322 RECALC_USPERDIV(&sc->timer);
323 sc->timer.divs_lastevent = sc->timer.divs_lastchange = 0;
324 microtime(&sc->timer.reftime);
325
326 SEQ_QINIT(&sc->inq);
327 SEQ_QINIT(&sc->outq);
328 sc->lowat = SEQ_MAXQ / 2;
329
330 if (sc->ndevs > 0) {
331 mutex_exit(&sc->lock);
332 sc->devs = kmem_alloc(sc->ndevs * sizeof(struct midi_dev *),
333 KM_SLEEP);
334 for (unit = 0; unit < sc->ndevs; unit++) {
335 md = midiseq_open(unit, flags);
336 if (md) {
337 sc->devs[sc->nmidi++] = md;
338 md->seq = sc;
339 md->doingsysex = 0;
340 DPRINTF(("%s: midi unit %d opened as seq %p\n",
341 __func__, unit, md));
342 } else {
343 DPRINTF(("%s: midi unit %d not opened as seq\n",
344 __func__, unit));
345 }
346 }
347 mutex_enter(&sc->lock);
348 } else {
349 sc->devs = NULL;
350 }
351
352 /* Only now redirect input from MIDI devices. */
353 for (mdno = 0; mdno < sc->nmidi; mdno++) {
354 extern struct cfdriver midi_cd;
355
356 msc = device_lookup_private(&midi_cd, sc->devs[mdno]->unit);
357 if (msc) {
358 mutex_enter(msc->lock);
359 msc->seqopen = 1;
360 mutex_exit(msc->lock);
361 }
362 }
363
364 seq_reset(sc);
365 sequencer_exit(sc);
366
367 DPRINTF(("%s: mode=%d, nmidi=%d\n", __func__, sc->mode, sc->nmidi));
368 return 0;
369 }
370
371 static int
372 seq_drain(struct sequencer_softc *sc)
373 {
374 int error;
375
376 KASSERT(mutex_owned(&sc->lock));
377
378 DPRINTFN(3, ("seq_drain: %p, len=%d\n", sc, SEQ_QLEN(&sc->outq)));
379 seq_startoutput(sc);
380 error = 0;
381 while (!SEQ_QEMPTY(&sc->outq) && !error)
382 error = cv_timedwait_sig(&sc->wchan, &sc->lock, 60*hz);
383 return (error);
384 }
385
386 static void
387 seq_timeout(void *addr)
388 {
389 struct sequencer_softc *sc = addr;
390 proc_t *p;
391 pid_t pid;
392
393 DPRINTFN(4, ("seq_timeout: %p\n", sc));
394
395 mutex_enter(&sc->lock);
396 if (sc->timeout == 0) {
397 mutex_spin_exit(&sc->lock);
398 return;
399 }
400 sc->timeout = 0;
401 seq_startoutput(sc);
402 if (SEQ_QLEN(&sc->outq) >= sc->lowat) {
403 mutex_exit(&sc->lock);
404 return;
405 }
406 cv_broadcast(&sc->wchan);
407 selnotify(&sc->wsel, 0, NOTE_SUBMIT);
408 if ((pid = sc->async) != 0) {
409 mutex_enter(proc_lock);
410 if ((p = proc_find(pid)) != NULL)
411 psignal(p, SIGIO);
412 mutex_exit(proc_lock);
413 }
414 mutex_exit(&sc->lock);
415 }
416
417 static void
418 seq_startoutput(struct sequencer_softc *sc)
419 {
420 struct sequencer_queue *q = &sc->outq;
421 seq_event_t cmd;
422
423 KASSERT(mutex_owned(&sc->lock));
424
425 if (sc->timeout)
426 return;
427 DPRINTFN(4, ("seq_startoutput: %p, len=%d\n", sc, SEQ_QLEN(q)));
428 while (!SEQ_QEMPTY(q) && !sc->timeout) {
429 SEQ_QGET(q, cmd);
430 seq_do_command(sc, &cmd);
431 }
432 }
433
434 static int
435 sequencerclose(dev_t dev, int flags, int ifmt, struct lwp *l)
436 {
437 struct sequencer_softc *sc;
438 struct midi_softc *msc;
439 int unit, error;
440
441 DPRINTF(("%s: %"PRIx64"\n", __func__, dev));
442
443 if ((error = sequencer_enter(dev, &sc)) != 0)
444 return error;
445 seq_drain(sc);
446 if (sc->timeout) {
447 callout_halt(&sc->sc_callout, &sc->lock);
448 sc->timeout = 0;
449 }
450 /* Bin input from MIDI devices. */
451 for (unit = 0; unit < sc->nmidi; unit++) {
452 extern struct cfdriver midi_cd;
453
454 msc = device_lookup_private(&midi_cd, unit);
455 if (msc) {
456 mutex_enter(msc->lock);
457 msc->seqopen = 0;
458 mutex_exit(msc->lock);
459 }
460 }
461 mutex_exit(&sc->lock);
462
463 for (unit = 0; unit < sc->nmidi; unit++)
464 if (sc->devs[unit] != NULL)
465 midiseq_close(sc->devs[unit]);
466 if (sc->devs != NULL) {
467 KASSERT(sc->ndevs > 0);
468 kmem_free(sc->devs, sc->ndevs * sizeof(struct midi_dev *));
469 sc->devs = NULL;
470 }
471
472 mutex_enter(&sc->lock);
473 sc->isopen = 0;
474 sequencer_exit(sc);
475
476 DPRINTF(("%s: %"PRIx64" done\n", __func__, dev));
477
478 return (0);
479 }
480
481 static int
482 seq_input_event(struct sequencer_softc *sc, seq_event_t *cmd)
483 {
484 struct sequencer_queue *q;
485
486 KASSERT(mutex_owned(&sc->lock));
487
488 DPRINTFN(2, ("seq_input_event: %02x %02x %02x %02x %02x "
489 "%02x %02x %02x\n", cmd->tag,
490 cmd->unknown.byte[0], cmd->unknown.byte[1],
491 cmd->unknown.byte[2], cmd->unknown.byte[3],
492 cmd->unknown.byte[4], cmd->unknown.byte[5],
493 cmd->unknown.byte[6]));
494 q = &sc->inq;
495 if (SEQ_QFULL(q))
496 return (ENOMEM);
497 SEQ_QPUT(q, *cmd);
498 cv_broadcast(&sc->rchan);
499 selnotify(&sc->rsel, 0, NOTE_SUBMIT);
500 if (sc->async != 0) {
501 proc_t *p;
502
503 mutex_enter(proc_lock);
504 if ((p = proc_find(sc->async)) != NULL)
505 psignal(p, SIGIO);
506 mutex_exit(proc_lock);
507 }
508 return 0;
509 }
510
511 static void
512 seq_softintr(void *addr)
513 {
514 struct sequencer_softc *sc;
515 struct timeval now;
516 seq_event_t ev;
517 int status, chan, unit;
518 sequencer_pcqitem_t qi;
519 u_long t;
520
521 sc = addr;
522
523 mutex_enter(&sc->lock);
524
525 qi.qi_ptr = pcq_get(sc->pcq);
526 if (qi.qi_ptr == NULL) {
527 mutex_exit(&sc->lock);
528 return;
529 }
530 KASSERT((qi.qi_msg[3] & 0x80) != 0);
531 unit = qi.qi_msg[3] & ~0x80;
532 status = MIDI_GET_STATUS(qi.qi_msg[0]);
533 chan = MIDI_GET_CHAN(qi.qi_msg[0]);
534 switch (status) {
535 case MIDI_NOTEON: /* midi(4) always canonicalizes hidden note-off */
536 ev = SEQ_MK_CHN(NOTEON, .device=unit, .channel=chan,
537 .key=qi.qi_msg[1], .velocity=qi.qi_msg[2]);
538 break;
539 case MIDI_NOTEOFF:
540 ev = SEQ_MK_CHN(NOTEOFF, .device=unit, .channel=chan,
541 .key=qi.qi_msg[1], .velocity=qi.qi_msg[2]);
542 break;
543 case MIDI_KEY_PRESSURE:
544 ev = SEQ_MK_CHN(KEY_PRESSURE, .device=unit, .channel=chan,
545 .key=qi.qi_msg[1], .pressure=qi.qi_msg[2]);
546 break;
547 case MIDI_CTL_CHANGE: /* XXX not correct for MSB */
548 ev = SEQ_MK_CHN(CTL_CHANGE, .device=unit, .channel=chan,
549 .controller=qi.qi_msg[1], .value=qi.qi_msg[2]);
550 break;
551 case MIDI_PGM_CHANGE:
552 ev = SEQ_MK_CHN(PGM_CHANGE, .device=unit, .channel=chan,
553 .program=qi.qi_msg[1]);
554 break;
555 case MIDI_CHN_PRESSURE:
556 ev = SEQ_MK_CHN(CHN_PRESSURE, .device=unit, .channel=chan,
557 .pressure=qi.qi_msg[1]);
558 break;
559 case MIDI_PITCH_BEND:
560 ev = SEQ_MK_CHN(PITCH_BEND, .device=unit, .channel=chan,
561 .value=(qi.qi_msg[1] & 0x7f) | ((qi.qi_msg[2] & 0x7f) << 7));
562 break;
563 default: /* this is now the point where MIDI_ACKs disappear */
564 mutex_exit(&sc->lock);
565 return;
566 }
567 microtime(&now);
568 if (!sc->timer.running)
569 now = sc->timer.stoptime;
570 SUBTIMEVAL(&now, &sc->timer.reftime);
571 t = now.tv_sec * 1000000 + now.tv_usec;
572 t /= sc->timer.usperdiv;
573 t += sc->timer.divs_lastchange;
574 if (t != sc->input_stamp) {
575 seq_input_event(sc, &SEQ_MK_TIMING(WAIT_ABS, .divisions=t));
576 sc->input_stamp = t; /* XXX what happens if timer is reset? */
577 }
578 seq_input_event(sc, &ev);
579 mutex_exit(&sc->lock);
580 }
581
582 static int
583 sequencerread(dev_t dev, struct uio *uio, int ioflag)
584 {
585 struct sequencer_softc *sc;
586 struct sequencer_queue *q;
587 seq_event_t ev;
588 int error;
589
590 DPRINTFN(2, ("sequencerread: %"PRIx64", count=%d, ioflag=%x\n",
591 dev, (int)uio->uio_resid, ioflag));
592
593 if ((error = sequencer_enter(dev, &sc)) != 0)
594 return error;
595 q = &sc->inq;
596
597 if (sc->mode == SEQ_OLD) {
598 sequencer_exit(sc);
599 DPRINTFN(-1,("sequencerread: old read\n"));
600 return EINVAL; /* XXX unimplemented */
601 }
602 while (SEQ_QEMPTY(q)) {
603 if (ioflag & IO_NDELAY) {
604 error = EWOULDBLOCK;
605 break;
606 }
607 /* Drop lock to allow concurrent read/write. */
608 KASSERT(sc->dvlock != 0);
609 sc->dvlock--;
610 error = cv_wait_sig(&sc->rchan, &sc->lock);
611 while (sc->dvlock != 0) {
612 cv_wait(&sc->lchan, &sc->lock);
613 }
614 sc->dvlock++;
615 if (error) {
616 break;
617 }
618 }
619 while (uio->uio_resid >= sizeof(ev) && !error && !SEQ_QEMPTY(q)) {
620 SEQ_QGET(q, ev);
621 mutex_exit(&sc->lock);
622 error = uiomove(&ev, sizeof(ev), uio);
623 mutex_enter(&sc->lock);
624 }
625 sequencer_exit(sc);
626 return error;
627 }
628
629 static int
630 sequencerwrite(dev_t dev, struct uio *uio, int ioflag)
631 {
632 struct sequencer_softc *sc;
633 struct sequencer_queue *q;
634 int error;
635 seq_event_t cmdbuf;
636 int size;
637
638 DPRINTFN(2, ("sequencerwrite: %"PRIx64", count=%d\n", dev,
639 (int)uio->uio_resid));
640
641 if ((error = sequencer_enter(dev, &sc)) != 0)
642 return error;
643 q = &sc->outq;
644
645 size = sc->mode == SEQ_NEW ? sizeof cmdbuf : SEQOLD_CMDSIZE;
646 while (uio->uio_resid >= size && error == 0) {
647 mutex_exit(&sc->lock);
648 error = uiomove(&cmdbuf, size, uio);
649 if (error == 0) {
650 if (sc->mode == SEQ_OLD && seq_to_new(&cmdbuf, uio)) {
651 mutex_enter(&sc->lock);
652 continue;
653 }
654 if (cmdbuf.tag == SEQ_FULLSIZE) {
655 /* We do it like OSS does, asynchronously */
656 error = seq_do_fullsize(sc, &cmdbuf, uio);
657 if (error == 0) {
658 mutex_enter(&sc->lock);
659 continue;
660 }
661 }
662 }
663 mutex_enter(&sc->lock);
664 if (error != 0) {
665 break;
666 }
667 while (SEQ_QFULL(q)) {
668 seq_startoutput(sc);
669 if (SEQ_QFULL(q)) {
670 if (ioflag & IO_NDELAY) {
671 error = EWOULDBLOCK;
672 break;
673 }
674 error = cv_wait_sig(&sc->wchan, &sc->lock);
675 if (error) {
676 break;
677 }
678 }
679 }
680 if (error == 0) {
681 SEQ_QPUT(q, cmdbuf);
682 }
683 }
684 if (error == 0) {
685 seq_startoutput(sc);
686 } else {
687 DPRINTFN(2, ("sequencerwrite: error=%d\n", error));
688 }
689 sequencer_exit(sc);
690 return error;
691 }
692
693 static int
694 sequencerioctl(dev_t dev, u_long cmd, void *addr, int flag, struct lwp *l)
695 {
696 struct sequencer_softc *sc;
697 struct synth_info *si;
698 struct midi_dev *md;
699 int devno, error, t;
700 struct timeval now;
701 u_long tx;
702
703 DPRINTFN(2, ("sequencerioctl: %"PRIx64" cmd=0x%08lx\n", dev, cmd));
704
705 if ((error = sequencer_enter(dev, &sc)) != 0)
706 return error;
707 switch (cmd) {
708 case FIONBIO:
709 /* All handled in the upper FS layer. */
710 break;
711
712 case FIOASYNC:
713 if (*(int *)addr) {
714 if (sc->async != 0)
715 return EBUSY;
716 sc->async = curproc->p_pid;
717 DPRINTF(("%s: FIOASYNC %d\n", __func__,
718 sc->async));
719 } else {
720 sc->async = 0;
721 }
722 break;
723
724 case SEQUENCER_RESET:
725 seq_reset(sc);
726 break;
727
728 case SEQUENCER_PANIC:
729 seq_reset(sc);
730 /* Do more? OSS doesn't */
731 break;
732
733 case SEQUENCER_SYNC:
734 if (sc->flags != FREAD)
735 seq_drain(sc);
736 break;
737
738 case SEQUENCER_INFO:
739 si = (struct synth_info*)addr;
740 devno = si->device;
741 if (devno < 0 || devno >= sc->nmidi) {
742 error = EINVAL;
743 break;
744 }
745 md = sc->devs[devno];
746 strncpy(si->name, md->name, sizeof si->name);
747 si->synth_type = SYNTH_TYPE_MIDI;
748 si->synth_subtype = md->subtype;
749 si->nr_voices = md->nr_voices;
750 si->instr_bank_size = md->instr_bank_size;
751 si->capabilities = md->capabilities;
752 break;
753
754 case SEQUENCER_NRSYNTHS:
755 *(int *)addr = sc->nmidi;
756 break;
757
758 case SEQUENCER_NRMIDIS:
759 *(int *)addr = sc->nmidi;
760 break;
761
762 case SEQUENCER_OUTOFBAND:
763 DPRINTFN(3, ("sequencer_ioctl: OOB=%02x %02x %02x %02x %02x %02x %02x %02x\n",
764 *(u_char *)addr, *((u_char *)addr+1),
765 *((u_char *)addr+2), *((u_char *)addr+3),
766 *((u_char *)addr+4), *((u_char *)addr+5),
767 *((u_char *)addr+6), *((u_char *)addr+7)));
768 if ((sc->flags & FWRITE) == 0) {
769 error = EBADF;
770 } else {
771 error = seq_do_command(sc, (seq_event_t *)addr);
772 }
773 break;
774
775 case SEQUENCER_TMR_TIMEBASE:
776 t = *(int *)addr;
777 if (t < 1)
778 t = 1;
779 if (t > 10000)
780 t = 10000;
781 *(int *)addr = t;
782 sc->timer.timebase_divperbeat = t;
783 sc->timer.divs_lastchange = sc->timer.divs_lastevent;
784 microtime(&sc->timer.reftime);
785 RECALC_USPERDIV(&sc->timer);
786 break;
787
788 case SEQUENCER_TMR_START:
789 error = seq_do_timing(sc, &SEQ_MK_TIMING(START));
790 break;
791
792 case SEQUENCER_TMR_STOP:
793 error = seq_do_timing(sc, &SEQ_MK_TIMING(STOP));
794 break;
795
796 case SEQUENCER_TMR_CONTINUE:
797 error = seq_do_timing(sc, &SEQ_MK_TIMING(CONTINUE));
798 break;
799
800 case SEQUENCER_TMR_TEMPO:
801 error = seq_do_timing(sc,
802 &SEQ_MK_TIMING(TEMPO, .bpm=*(int *)addr));
803 RECALC_USPERDIV(&sc->timer);
804 if (error == 0)
805 *(int *)addr = sc->timer.tempo_beatpermin;
806 break;
807
808 case SEQUENCER_TMR_SOURCE:
809 *(int *)addr = SEQUENCER_TMR_INTERNAL;
810 break;
811
812 case SEQUENCER_TMR_METRONOME:
813 /* noop */
814 break;
815
816 case SEQUENCER_THRESHOLD:
817 t = SEQ_MAXQ - *(int *)addr / sizeof (seq_event_rec);
818 if (t < 1)
819 t = 1;
820 if (t > SEQ_MAXQ)
821 t = SEQ_MAXQ;
822 sc->lowat = t;
823 break;
824
825 case SEQUENCER_CTRLRATE:
826 *(int *)addr = (sc->timer.tempo_beatpermin
827 *sc->timer.timebase_divperbeat + 30) / 60;
828 break;
829
830 case SEQUENCER_GETTIME:
831 microtime(&now);
832 SUBTIMEVAL(&now, &sc->timer.reftime);
833 tx = now.tv_sec * 1000000 + now.tv_usec;
834 tx /= sc->timer.usperdiv;
835 tx += sc->timer.divs_lastchange;
836 *(int *)addr = tx;
837 break;
838
839 default:
840 DPRINTFN(-1,("sequencer_ioctl: unimpl %08lx\n", cmd));
841 error = EINVAL;
842 break;
843 }
844 sequencer_exit(sc);
845
846 return error;
847 }
848
849 static int
850 sequencerpoll(dev_t dev, int events, struct lwp *l)
851 {
852 struct sequencer_softc *sc;
853 int revents = 0;
854 if ((sc = sequencerget(SEQUENCERUNIT(dev))) == NULL)
855 return ENXIO;
856
857 DPRINTF(("%s: %p events=0x%x\n", __func__, sc, events));
858
859 mutex_enter(&sc->lock);
860 if (events & (POLLIN | POLLRDNORM))
861 if ((sc->flags&FREAD) && !SEQ_QEMPTY(&sc->inq))
862 revents |= events & (POLLIN | POLLRDNORM);
863
864 if (events & (POLLOUT | POLLWRNORM))
865 if ((sc->flags&FWRITE) && SEQ_QLEN(&sc->outq) < sc->lowat)
866 revents |= events & (POLLOUT | POLLWRNORM);
867
868 if (revents == 0) {
869 if ((sc->flags&FREAD) && (events & (POLLIN | POLLRDNORM)))
870 selrecord(l, &sc->rsel);
871
872 if ((sc->flags&FWRITE) && (events & (POLLOUT | POLLWRNORM)))
873 selrecord(l, &sc->wsel);
874 }
875 mutex_exit(&sc->lock);
876
877 return revents;
878 }
879
880 static void
881 filt_sequencerrdetach(struct knote *kn)
882 {
883 struct sequencer_softc *sc = kn->kn_hook;
884
885 mutex_enter(&sc->lock);
886 SLIST_REMOVE(&sc->rsel.sel_klist, kn, knote, kn_selnext);
887 mutex_exit(&sc->lock);
888 }
889
890 static int
891 filt_sequencerread(struct knote *kn, long hint)
892 {
893 struct sequencer_softc *sc = kn->kn_hook;
894 int rv;
895
896 if (hint != NOTE_SUBMIT) {
897 mutex_enter(&sc->lock);
898 }
899 if (SEQ_QEMPTY(&sc->inq)) {
900 rv = 0;
901 } else {
902 kn->kn_data = sizeof(seq_event_rec);
903 rv = 1;
904 }
905 if (hint != NOTE_SUBMIT) {
906 mutex_exit(&sc->lock);
907 }
908 return rv;
909 }
910
911 static const struct filterops sequencerread_filtops =
912 { 1, NULL, filt_sequencerrdetach, filt_sequencerread };
913
914 static void
915 filt_sequencerwdetach(struct knote *kn)
916 {
917 struct sequencer_softc *sc = kn->kn_hook;
918
919 mutex_enter(&sc->lock);
920 SLIST_REMOVE(&sc->wsel.sel_klist, kn, knote, kn_selnext);
921 mutex_exit(&sc->lock);
922 }
923
924 static int
925 filt_sequencerwrite(struct knote *kn, long hint)
926 {
927 struct sequencer_softc *sc = kn->kn_hook;
928 int rv;
929
930 if (hint != NOTE_SUBMIT) {
931 mutex_enter(&sc->lock);
932 }
933 if (SEQ_QLEN(&sc->outq) >= sc->lowat) {
934 rv = 0;
935 } else {
936 kn->kn_data = sizeof(seq_event_rec);
937 rv = 1;
938 }
939 if (hint != NOTE_SUBMIT) {
940 mutex_exit(&sc->lock);
941 }
942 return rv;
943 }
944
945 static const struct filterops sequencerwrite_filtops =
946 { 1, NULL, filt_sequencerwdetach, filt_sequencerwrite };
947
948 static int
949 sequencerkqfilter(dev_t dev, struct knote *kn)
950 {
951 struct sequencer_softc *sc;
952 struct klist *klist;
953 if ((sc = sequencerget(SEQUENCERUNIT(dev))) == NULL)
954 return ENXIO;
955
956 switch (kn->kn_filter) {
957 case EVFILT_READ:
958 klist = &sc->rsel.sel_klist;
959 kn->kn_fop = &sequencerread_filtops;
960 break;
961
962 case EVFILT_WRITE:
963 klist = &sc->wsel.sel_klist;
964 kn->kn_fop = &sequencerwrite_filtops;
965 break;
966
967 default:
968 return (EINVAL);
969 }
970
971 kn->kn_hook = sc;
972
973 mutex_enter(&sc->lock);
974 SLIST_INSERT_HEAD(klist, kn, kn_selnext);
975 mutex_exit(&sc->lock);
976
977 return (0);
978 }
979
980 static void
981 seq_reset(struct sequencer_softc *sc)
982 {
983 int i, chn;
984 struct midi_dev *md;
985
986 KASSERT(mutex_owned(&sc->lock));
987
988 if (!(sc->flags & FWRITE))
989 return;
990 for (i = 0; i < sc->nmidi; i++) {
991 md = sc->devs[i];
992 midiseq_reset(md);
993 for (chn = 0; chn < MAXCHAN; chn++) {
994 midiseq_ctlchange(md, chn, &SEQ_MK_CHN(CTL_CHANGE,
995 .controller=MIDI_CTRL_NOTES_OFF));
996 midiseq_ctlchange(md, chn, &SEQ_MK_CHN(CTL_CHANGE,
997 .controller=MIDI_CTRL_RESET));
998 midiseq_pitchbend(md, chn, &SEQ_MK_CHN(PITCH_BEND,
999 .value=MIDI_BEND_NEUTRAL));
1000 }
1001 }
1002 }
1003
1004 static int
1005 seq_do_command(struct sequencer_softc *sc, seq_event_t *b)
1006 {
1007 int dev;
1008
1009 KASSERT(mutex_owned(&sc->lock));
1010
1011 DPRINTFN(4, ("seq_do_command: %p cmd=0x%02x\n", sc, b->timing.op));
1012
1013 switch(b->tag) {
1014 case SEQ_LOCAL:
1015 return seq_do_local(sc, b);
1016 case SEQ_TIMING:
1017 return seq_do_timing(sc, b);
1018 case SEQ_CHN_VOICE:
1019 return seq_do_chnvoice(sc, b);
1020 case SEQ_CHN_COMMON:
1021 return seq_do_chncommon(sc, b);
1022 case SEQ_SYSEX:
1023 return seq_do_sysex(sc, b);
1024 /* COMPAT */
1025 case SEQOLD_MIDIPUTC:
1026 dev = b->putc.device;
1027 if (dev < 0 || dev >= sc->nmidi)
1028 return (ENXIO);
1029 return midiseq_out(sc->devs[dev], &b->putc.byte, 1, 0);
1030 default:
1031 DPRINTFN(-1,("seq_do_command: unimpl command %02x\n", b->tag));
1032 return (EINVAL);
1033 }
1034 }
1035
1036 static int
1037 seq_do_chnvoice(struct sequencer_softc *sc, seq_event_t *b)
1038 {
1039 int dev;
1040 int error;
1041 struct midi_dev *md;
1042
1043 KASSERT(mutex_owned(&sc->lock));
1044
1045 dev = b->voice.device;
1046 if (dev < 0 || dev >= sc->nmidi ||
1047 b->voice.channel > 15 ||
1048 b->voice.key >= SEQ_NOTE_MAX)
1049 return ENXIO;
1050 md = sc->devs[dev];
1051 switch(b->voice.op) {
1052 case MIDI_NOTEON: /* no need to special-case hidden noteoff here */
1053 error = midiseq_noteon(md, b->voice.channel, b->voice.key, b);
1054 break;
1055 case MIDI_NOTEOFF:
1056 error = midiseq_noteoff(md, b->voice.channel, b->voice.key, b);
1057 break;
1058 case MIDI_KEY_PRESSURE:
1059 error = midiseq_keypressure(md,
1060 b->voice.channel, b->voice.key, b);
1061 break;
1062 default:
1063 DPRINTFN(-1,("seq_do_chnvoice: unimpl command %02x\n",
1064 b->voice.op));
1065 error = EINVAL;
1066 break;
1067 }
1068 return error;
1069 }
1070
1071 static int
1072 seq_do_chncommon(struct sequencer_softc *sc, seq_event_t *b)
1073 {
1074 int dev;
1075 int error;
1076 struct midi_dev *md;
1077
1078 KASSERT(mutex_owned(&sc->lock));
1079
1080 dev = b->common.device;
1081 if (dev < 0 || dev >= sc->nmidi ||
1082 b->common.channel > 15)
1083 return ENXIO;
1084 md = sc->devs[dev];
1085 DPRINTFN(2,("seq_do_chncommon: %02x\n", b->common.op));
1086
1087 error = 0;
1088 switch(b->common.op) {
1089 case MIDI_PGM_CHANGE:
1090 error = midiseq_pgmchange(md, b->common.channel, b);
1091 break;
1092 case MIDI_CTL_CHANGE:
1093 error = midiseq_ctlchange(md, b->common.channel, b);
1094 break;
1095 case MIDI_PITCH_BEND:
1096 error = midiseq_pitchbend(md, b->common.channel, b);
1097 break;
1098 case MIDI_CHN_PRESSURE:
1099 error = midiseq_chnpressure(md, b->common.channel, b);
1100 break;
1101 default:
1102 DPRINTFN(-1,("seq_do_chncommon: unimpl command %02x\n",
1103 b->common.op));
1104 error = EINVAL;
1105 break;
1106 }
1107 return error;
1108 }
1109
1110 static int
1111 seq_do_local(struct sequencer_softc *sc, seq_event_t *b)
1112 {
1113
1114 KASSERT(mutex_owned(&sc->lock));
1115
1116 return (EINVAL);
1117 }
1118
1119 static int
1120 seq_do_sysex(struct sequencer_softc *sc, seq_event_t *b)
1121 {
1122 int dev, i;
1123 struct midi_dev *md;
1124 uint8_t *bf = b->sysex.buffer;
1125
1126 KASSERT(mutex_owned(&sc->lock));
1127
1128 dev = b->sysex.device;
1129 if (dev < 0 || dev >= sc->nmidi)
1130 return (ENXIO);
1131 DPRINTF(("%s: dev=%d\n", __func__, dev));
1132 md = sc->devs[dev];
1133
1134 if (!md->doingsysex) {
1135 midiseq_out(md, (uint8_t[]){MIDI_SYSEX_START}, 1, 0);
1136 md->doingsysex = 1;
1137 }
1138
1139 for (i = 0; i < 6 && bf[i] != 0xff; i++)
1140 ;
1141 midiseq_out(md, bf, i, 0);
1142 if (i < 6 || (i > 0 && bf[i-1] == MIDI_SYSEX_END))
1143 md->doingsysex = 0;
1144 return 0;
1145 }
1146
1147 static void
1148 seq_timer_waitabs(struct sequencer_softc *sc, uint32_t divs)
1149 {
1150 struct timeval when;
1151 long long usec;
1152 struct syn_timer *t;
1153 int ticks;
1154
1155 KASSERT(mutex_owned(&sc->lock));
1156
1157 t = &sc->timer;
1158 t->divs_lastevent = divs;
1159 divs -= t->divs_lastchange;
1160 usec = (long long)divs * (long long)t->usperdiv; /* convert to usec */
1161 when.tv_sec = usec / 1000000;
1162 when.tv_usec = usec % 1000000;
1163 DPRINTFN(4, ("seq_timer_waitabs: adjdivs=%d, sleep when=%"PRId64".%06"PRId64,
1164 divs, when.tv_sec, (uint64_t)when.tv_usec));
1165 ADDTIMEVAL(&when, &t->reftime); /* abstime for end */
1166 ticks = tvhzto(&when);
1167 DPRINTFN(4, (" when+start=%"PRId64".%06"PRId64", tick=%d\n",
1168 when.tv_sec, (uint64_t)when.tv_usec, ticks));
1169 if (ticks > 0) {
1170 #ifdef DIAGNOSTIC
1171 if (ticks > 20 * hz) {
1172 /* Waiting more than 20s */
1173 printf("seq_timer_waitabs: funny ticks=%d, "
1174 "usec=%lld\n", ticks, usec);
1175 }
1176 #endif
1177 sc->timeout = 1;
1178 callout_reset(&sc->sc_callout, ticks,
1179 seq_timeout, sc);
1180 }
1181 #ifdef SEQUENCER_DEBUG
1182 else if (tick < 0)
1183 DPRINTF(("%s: ticks = %d\n", __func__, ticks));
1184 #endif
1185 }
1186
1187 static int
1188 seq_do_timing(struct sequencer_softc *sc, seq_event_t *b)
1189 {
1190 struct syn_timer *t = &sc->timer;
1191 struct timeval when;
1192 int error;
1193
1194 KASSERT(mutex_owned(&sc->lock));
1195
1196 error = 0;
1197 switch(b->timing.op) {
1198 case TMR_WAIT_REL:
1199 seq_timer_waitabs(sc,
1200 b->t_WAIT_REL.divisions + t->divs_lastevent);
1201 break;
1202 case TMR_WAIT_ABS:
1203 seq_timer_waitabs(sc, b->t_WAIT_ABS.divisions);
1204 break;
1205 case TMR_START:
1206 microtime(&t->reftime);
1207 t->divs_lastevent = t->divs_lastchange = 0;
1208 t->running = 1;
1209 break;
1210 case TMR_STOP:
1211 microtime(&t->stoptime);
1212 t->running = 0;
1213 break;
1214 case TMR_CONTINUE:
1215 if (t->running)
1216 break;
1217 microtime(&when);
1218 SUBTIMEVAL(&when, &t->stoptime);
1219 ADDTIMEVAL(&t->reftime, &when);
1220 t->running = 1;
1221 break;
1222 case TMR_TEMPO:
1223 /* bpm is unambiguously MIDI clocks per minute / 24 */
1224 /* (24 MIDI clocks are usually but not always a quarter note) */
1225 if (b->t_TEMPO.bpm < 8) /* where are these limits specified? */
1226 t->tempo_beatpermin = 8;
1227 else if (b->t_TEMPO.bpm > 360) /* ? */
1228 t->tempo_beatpermin = 360;
1229 else
1230 t->tempo_beatpermin = b->t_TEMPO.bpm;
1231 t->divs_lastchange = t->divs_lastevent;
1232 microtime(&t->reftime);
1233 RECALC_USPERDIV(t);
1234 break;
1235 case TMR_ECHO:
1236 error = seq_input_event(sc, b);
1237 break;
1238 case TMR_RESET:
1239 t->divs_lastevent = t->divs_lastchange = 0;
1240 microtime(&t->reftime);
1241 break;
1242 case TMR_SPP:
1243 case TMR_TIMESIG:
1244 DPRINTF(("%s: unimplemented %02x\n", __func__, b->timing.op));
1245 error = EINVAL; /* not quite accurate... */
1246 break;
1247 default:
1248 DPRINTF(("%s: unknown %02x\n", __func__, b->timing.op));
1249 error = EINVAL;
1250 break;
1251 }
1252 return (error);
1253 }
1254
1255 static int
1256 seq_do_fullsize(struct sequencer_softc *sc, seq_event_t *b, struct uio *uio)
1257 {
1258 struct sysex_info sysex;
1259 u_int dev;
1260
1261 #ifdef DIAGNOSTIC
1262 if (sizeof(seq_event_rec) != SEQ_SYSEX_HDRSIZE) {
1263 printf("seq_do_fullsize: sysex size ??\n");
1264 return EINVAL;
1265 }
1266 #endif
1267 memcpy(&sysex, b, sizeof sysex);
1268 dev = sysex.device_no;
1269 if (/* dev < 0 || */ dev >= sc->nmidi)
1270 return (ENXIO);
1271 DPRINTFN(2, ("seq_do_fullsize: fmt=%04x, dev=%d, len=%d\n",
1272 sysex.key, dev, sysex.len));
1273 return (midiseq_loadpatch(sc->devs[dev], &sysex, uio));
1274 }
1275
1276 /*
1277 * Convert an old sequencer event to a new one.
1278 * NOTE: on entry, *ev may contain valid data only in the first 4 bytes.
1279 * That may be true even on exit (!) in the case of SEQOLD_MIDIPUTC; the
1280 * caller will only look at the first bytes in that case anyway. Ugly? Sure.
1281 */
1282 static int
1283 seq_to_new(seq_event_t *ev, struct uio *uio)
1284 {
1285 int cmd, chan, note, parm;
1286 uint32_t tmp_delay;
1287 int error;
1288 uint8_t *bfp;
1289
1290 cmd = ev->tag;
1291 bfp = ev->unknown.byte;
1292 chan = *bfp++;
1293 note = *bfp++;
1294 parm = *bfp++;
1295 DPRINTFN(3, ("seq_to_new: 0x%02x %d %d %d\n", cmd, chan, note, parm));
1296
1297 if (cmd >= 0x80) {
1298 /* Fill the event record */
1299 if (uio->uio_resid >= sizeof *ev - SEQOLD_CMDSIZE) {
1300 error = uiomove(bfp, sizeof *ev - SEQOLD_CMDSIZE, uio);
1301 if (error)
1302 return error;
1303 } else
1304 return EINVAL;
1305 }
1306
1307 switch(cmd) {
1308 case SEQOLD_NOTEOFF:
1309 /*
1310 * What's with the SEQ_NOTE_XXX? In OSS this seems to have
1311 * been undocumented magic for messing with the overall volume
1312 * of a 'voice', equated precariously with 'channel' and
1313 * pretty much unimplementable except by directly frobbing a
1314 * synth chip. For us, who treat everything as interfaced over
1315 * MIDI, this will just be unceremoniously discarded as
1316 * invalid in midiseq_noteoff, making the whole event an
1317 * elaborate no-op, and that doesn't seem to be any different
1318 * from what happens on linux with a MIDI-interfaced device,
1319 * by the way. The moral is ... use the new /dev/music API, ok?
1320 */
1321 *ev = SEQ_MK_CHN(NOTEOFF, .device=0, .channel=chan,
1322 .key=SEQ_NOTE_XXX, .velocity=parm);
1323 break;
1324 case SEQOLD_NOTEON:
1325 *ev = SEQ_MK_CHN(NOTEON,
1326 .device=0, .channel=chan, .key=note, .velocity=parm);
1327 break;
1328 case SEQOLD_WAIT:
1329 /*
1330 * This event cannot even /exist/ on non-littleendian machines,
1331 * and so help me, that's exactly the way OSS defined it.
1332 * Also, the OSS programmer's guide states (p. 74, v1.11)
1333 * that seqold time units are system clock ticks, unlike
1334 * the new 'divisions' which are determined by timebase. In
1335 * that case we would need to do scaling here - but no such
1336 * behavior is visible in linux either--which also treats this
1337 * value, surprisingly, as an absolute, not relative, time.
1338 * My guess is that this event has gone unused so long that
1339 * nobody could agree we got it wrong no matter what we do.
1340 */
1341 tmp_delay = *(uint32_t *)ev >> 8;
1342 *ev = SEQ_MK_TIMING(WAIT_ABS, .divisions=tmp_delay);
1343 break;
1344 case SEQOLD_SYNCTIMER:
1345 /*
1346 * The TMR_RESET event is not defined in any OSS materials
1347 * I can find; it may have been invented here just to provide
1348 * an accurate _to_new translation of this event.
1349 */
1350 *ev = SEQ_MK_TIMING(RESET);
1351 break;
1352 case SEQOLD_PGMCHANGE:
1353 *ev = SEQ_MK_CHN(PGM_CHANGE,
1354 .device=0, .channel=chan, .program=note);
1355 break;
1356 case SEQOLD_MIDIPUTC:
1357 break; /* interpret in normal mode */
1358 case SEQOLD_ECHO:
1359 case SEQOLD_PRIVATE:
1360 case SEQOLD_EXTENDED:
1361 default:
1362 DPRINTF(("%s: not impl 0x%02x\n", __func__, cmd));
1363 return EINVAL;
1364 /* In case new-style events show up */
1365 case SEQ_TIMING:
1366 case SEQ_CHN_VOICE:
1367 case SEQ_CHN_COMMON:
1368 case SEQ_FULLSIZE:
1369 break;
1370 }
1371 return 0;
1372 }
1373
1374 /**********************************************/
1375
1376 void
1377 midiseq_in(struct midi_dev *md, u_char *msg, int len)
1378 {
1379 struct sequencer_softc *sc;
1380 sequencer_pcqitem_t qi;
1381
1382 DPRINTFN(2, ("midiseq_in: %p %02x %02x %02x\n",
1383 md, msg[0], msg[1], msg[2]));
1384
1385 sc = md->seq;
1386
1387 qi.qi_msg[0] = msg[0];
1388 qi.qi_msg[1] = msg[1];
1389 qi.qi_msg[2] = msg[2];
1390 qi.qi_msg[3] = md->unit | 0x80; /* ensure non-zero value of qi_ptr */
1391 pcq_put(sc->pcq, qi.qi_ptr);
1392 softint_schedule(sc->sih);
1393 }
1394
1395 static struct midi_dev *
1396 midiseq_open(int unit, int flags)
1397 {
1398 extern struct cfdriver midi_cd;
1399 int error;
1400 struct midi_dev *md;
1401 struct midi_softc *sc;
1402 struct midi_info mi;
1403 int major;
1404 dev_t dev;
1405 vnode_t *vp;
1406 int oflags;
1407
1408 major = devsw_name2chr("midi", NULL, 0);
1409 dev = makedev(major, unit);
1410
1411 DPRINTFN(2, ("midiseq_open: %d %d\n", unit, flags));
1412
1413 error = cdevvp(dev, &vp);
1414 if (error)
1415 return NULL;
1416 vn_lock(vp, LK_EXCLUSIVE | LK_RETRY);
1417 error = VOP_OPEN(vp, flags, kauth_cred_get());
1418 VOP_UNLOCK(vp);
1419 if (error) {
1420 vrele(vp);
1421 return NULL;
1422 }
1423
1424 /* Only after we have acquired reference via VOP_OPEN(). */
1425 midi_getinfo(dev, &mi);
1426 oflags = flags;
1427 if ((mi.props & MIDI_PROP_CAN_INPUT) == 0)
1428 flags &= ~FREAD;
1429 if ((flags & (FREAD|FWRITE)) == 0) {
1430 VOP_CLOSE(vp, oflags, kauth_cred_get());
1431 vrele(vp);
1432 return NULL;
1433 }
1434
1435 sc = device_lookup_private(&midi_cd, unit);
1436 md = kmem_zalloc(sizeof(*md), KM_SLEEP);
1437 md->unit = unit;
1438 md->name = mi.name;
1439 md->subtype = 0;
1440 md->nr_voices = 128; /* XXX */
1441 md->instr_bank_size = 128; /* XXX */
1442 md->vp = vp;
1443 if (mi.props & MIDI_PROP_CAN_INPUT)
1444 md->capabilities |= SYNTH_CAP_INPUT;
1445 sc->seq_md = md;
1446 return (md);
1447 }
1448
1449 static void
1450 midiseq_close(struct midi_dev *md)
1451 {
1452 DPRINTFN(2, ("midiseq_close: %d\n", md->unit));
1453 (void)vn_close(md->vp, 0, kauth_cred_get());
1454 kmem_free(md, sizeof(*md));
1455 }
1456
1457 static void
1458 midiseq_reset(struct midi_dev *md)
1459 {
1460 /* XXX send GM reset? */
1461 DPRINTFN(3, ("midiseq_reset: %d\n", md->unit));
1462 }
1463
1464 static int
1465 midiseq_out(struct midi_dev *md, u_char *bf, u_int cc, int chk)
1466 {
1467 DPRINTFN(5, ("midiseq_out: md=%p, unit=%d, bf[0]=0x%02x, cc=%d\n",
1468 md, md->unit, bf[0], cc));
1469
1470 /* midi(4) does running status compression where appropriate. */
1471 return midi_writebytes(md->unit, bf, cc);
1472 }
1473
1474 /*
1475 * If the writing process hands us a hidden note-off in a note-on event,
1476 * we will simply write it that way; no need to special case it here,
1477 * as midi(4) will always canonicalize or compress as appropriate anyway.
1478 */
1479 static int
1480 midiseq_noteon(struct midi_dev *md, int chan, int key, seq_event_t *ev)
1481 {
1482 return midiseq_out(md, (uint8_t[]){
1483 MIDI_NOTEON | chan, key, ev->c_NOTEON.velocity & 0x7f}, 3, 1);
1484 }
1485
1486 static int
1487 midiseq_noteoff(struct midi_dev *md, int chan, int key, seq_event_t *ev)
1488 {
1489 return midiseq_out(md, (uint8_t[]){
1490 MIDI_NOTEOFF | chan, key, ev->c_NOTEOFF.velocity & 0x7f}, 3, 1);
1491 }
1492
1493 static int
1494 midiseq_keypressure(struct midi_dev *md, int chan, int key, seq_event_t *ev)
1495 {
1496 return midiseq_out(md, (uint8_t[]){
1497 MIDI_KEY_PRESSURE | chan, key,
1498 ev->c_KEY_PRESSURE.pressure & 0x7f}, 3, 1);
1499 }
1500
1501 static int
1502 midiseq_pgmchange(struct midi_dev *md, int chan, seq_event_t *ev)
1503 {
1504 if (ev->c_PGM_CHANGE.program > 127)
1505 return EINVAL;
1506 return midiseq_out(md, (uint8_t[]){
1507 MIDI_PGM_CHANGE | chan, ev->c_PGM_CHANGE.program}, 2, 1);
1508 }
1509
1510 static int
1511 midiseq_chnpressure(struct midi_dev *md, int chan, seq_event_t *ev)
1512 {
1513 if (ev->c_CHN_PRESSURE.pressure > 127)
1514 return EINVAL;
1515 return midiseq_out(md, (uint8_t[]){
1516 MIDI_CHN_PRESSURE | chan, ev->c_CHN_PRESSURE.pressure}, 2, 1);
1517 }
1518
1519 static int
1520 midiseq_ctlchange(struct midi_dev *md, int chan, seq_event_t *ev)
1521 {
1522 if (ev->c_CTL_CHANGE.controller > 127)
1523 return EINVAL;
1524 return midiseq_out( md, (uint8_t[]){
1525 MIDI_CTL_CHANGE | chan, ev->c_CTL_CHANGE.controller,
1526 ev->c_CTL_CHANGE.value & 0x7f /* XXX this is SO wrong */
1527 }, 3, 1);
1528 }
1529
1530 static int
1531 midiseq_pitchbend(struct midi_dev *md, int chan, seq_event_t *ev)
1532 {
1533 return midiseq_out(md, (uint8_t[]){
1534 MIDI_PITCH_BEND | chan,
1535 ev->c_PITCH_BEND.value & 0x7f,
1536 (ev->c_PITCH_BEND.value >> 7) & 0x7f}, 3, 1);
1537 }
1538
1539 static int
1540 midiseq_loadpatch(struct midi_dev *md,
1541 struct sysex_info *sysex, struct uio *uio)
1542 {
1543 struct sequencer_softc *sc;
1544 u_char c, bf[128];
1545 int i, cc, error;
1546
1547 if (sysex->key != SEQ_SYSEX_PATCH) {
1548 DPRINTFN(-1,("midiseq_loadpatch: bad patch key 0x%04x\n",
1549 sysex->key));
1550 return (EINVAL);
1551 }
1552 if (uio->uio_resid < sysex->len)
1553 /* adjust length, should be an error */
1554 sysex->len = uio->uio_resid;
1555
1556 DPRINTFN(2, ("midiseq_loadpatch: len=%d\n", sysex->len));
1557 if (sysex->len == 0)
1558 return EINVAL;
1559 error = uiomove(&c, 1, uio);
1560 if (error)
1561 return error;
1562 if (c != MIDI_SYSEX_START) /* must start like this */
1563 return EINVAL;
1564 sc = md->seq;
1565 mutex_enter(&sc->lock);
1566 error = midiseq_out(md, &c, 1, 0);
1567 mutex_exit(&sc->lock);
1568 if (error)
1569 return error;
1570 --sysex->len;
1571 while (sysex->len > 0) {
1572 cc = sysex->len;
1573 if (cc > sizeof bf)
1574 cc = sizeof bf;
1575 error = uiomove(bf, cc, uio);
1576 if (error)
1577 break;
1578 for(i = 0; i < cc && !MIDI_IS_STATUS(bf[i]); i++)
1579 ;
1580 /*
1581 * XXX midi(4)'s buffer might not accommodate this, and the
1582 * function will not block us (though in this case we have
1583 * a process and could in principle block).
1584 */
1585 mutex_enter(&sc->lock);
1586 error = midiseq_out(md, bf, i, 0);
1587 mutex_exit(&sc->lock);
1588 if (error)
1589 break;
1590 sysex->len -= i;
1591 if (i != cc)
1592 break;
1593 }
1594 /*
1595 * Any leftover data in uio is rubbish;
1596 * the SYSEX should be one write ending in SYSEX_END.
1597 */
1598 uio->uio_resid = 0;
1599 c = MIDI_SYSEX_END;
1600 mutex_enter(&sc->lock);
1601 error = midiseq_out(md, &c, 1, 0);
1602 mutex_exit(&sc->lock);
1603 return error;
1604 }
1605
1606 #include "midi.h"
1607 #if NMIDI == 0
1608 static dev_type_open(midiopen);
1609 static dev_type_close(midiclose);
1610
1611 const struct cdevsw midi_cdevsw = {
1612 .d_open = midiopen,
1613 .d_close = midiclose,
1614 .d_read = noread,
1615 .d_write = nowrite,
1616 .d_ioctl = noioctl,
1617 .d_stop = nostop,
1618 .d_tty = notty,
1619 .d_poll = nopoll,
1620 .d_mmap = nommap,
1621 .d_kqfilter = nokqfilter,
1622 .d_discard = nodiscard,
1623 .d_flag = D_OTHER | D_MPSAFE
1624 };
1625
1626 /*
1627 * If someone has a sequencer, but no midi devices there will
1628 * be unresolved references, so we provide little stubs.
1629 */
1630
1631 int
1632 midi_unit_count(void)
1633 {
1634 return (0);
1635 }
1636
1637 static int
1638 midiopen(dev_t dev, int flags, int ifmt, struct lwp *l)
1639 {
1640 return (ENXIO);
1641 }
1642
1643 struct cfdriver midi_cd;
1644
1645 void
1646 midi_getinfo(dev_t dev, struct midi_info *mi)
1647 {
1648 mi->name = "Dummy MIDI device";
1649 mi->props = 0;
1650 }
1651
1652 static int
1653 midiclose(dev_t dev, int flags, int ifmt, struct lwp *l)
1654 {
1655 return (ENXIO);
1656 }
1657
1658 int
1659 midi_writebytes(int unit, u_char *bf, int cc)
1660 {
1661 return (ENXIO);
1662 }
1663 #endif /* NMIDI == 0 */
1664