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