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