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