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