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