xref: /freebsd/sys/dev/sound/pcm/dsp.c (revision 2e3507c25e42292b45a5482e116d278f5515d04d)
1 /*-
2  * SPDX-License-Identifier: BSD-2-Clause
3  *
4  * Copyright (c) 2005-2009 Ariff Abdullah <ariff@FreeBSD.org>
5  * Portions Copyright (c) Ryan Beasley <ryan.beasley@gmail.com> - GSoC 2006
6  * Copyright (c) 1999 Cameron Grant <cg@FreeBSD.org>
7  * All rights reserved.
8  *
9  * Redistribution and use in source and binary forms, with or without
10  * modification, are permitted provided that the following conditions
11  * are met:
12  * 1. Redistributions of source code must retain the above copyright
13  *    notice, this list of conditions and the following disclaimer.
14  * 2. Redistributions in binary form must reproduce the above copyright
15  *    notice, this list of conditions and the following disclaimer in the
16  *    documentation and/or other materials provided with the distribution.
17  *
18  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
19  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
20  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
21  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
22  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
23  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
24  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
25  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
26  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
27  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
28  * SUCH DAMAGE.
29  */
30 
31 #ifdef HAVE_KERNEL_OPTION_HEADERS
32 #include "opt_snd.h"
33 #endif
34 
35 #include <dev/sound/pcm/sound.h>
36 #include <sys/ctype.h>
37 #include <sys/lock.h>
38 #include <sys/rwlock.h>
39 #include <sys/sysent.h>
40 
41 #include <vm/vm.h>
42 #include <vm/vm_object.h>
43 #include <vm/vm_page.h>
44 #include <vm/vm_pager.h>
45 
46 static int dsp_mmap_allow_prot_exec = 0;
47 SYSCTL_INT(_hw_snd, OID_AUTO, compat_linux_mmap, CTLFLAG_RWTUN,
48     &dsp_mmap_allow_prot_exec, 0,
49     "linux mmap compatibility (-1=force disable 0=auto 1=force enable)");
50 
51 static int dsp_basename_clone = 1;
52 SYSCTL_INT(_hw_snd, OID_AUTO, basename_clone, CTLFLAG_RWTUN,
53     &dsp_basename_clone, 0,
54     "DSP basename cloning (0: Disable; 1: Enabled)");
55 
56 struct dsp_cdevinfo {
57 	struct pcm_channel *rdch, *wrch;
58 	struct pcm_channel *volch;
59 	int busy, simplex;
60 	TAILQ_ENTRY(dsp_cdevinfo) link;
61 };
62 
63 #define PCM_RDCH(x)		(((struct dsp_cdevinfo *)(x)->si_drv1)->rdch)
64 #define PCM_WRCH(x)		(((struct dsp_cdevinfo *)(x)->si_drv1)->wrch)
65 #define PCM_VOLCH(x)		(((struct dsp_cdevinfo *)(x)->si_drv1)->volch)
66 #define PCM_SIMPLEX(x)		(((struct dsp_cdevinfo *)(x)->si_drv1)->simplex)
67 
68 #define DSP_CDEVINFO_CACHESIZE	8
69 
70 #define DSP_REGISTERED(x, y)	(PCM_REGISTERED(x) &&			\
71 				 (y) != NULL && (y)->si_drv1 != NULL)
72 
73 #define OLDPCM_IOCTL
74 
75 static d_open_t dsp_open;
76 static d_close_t dsp_close;
77 static d_read_t dsp_read;
78 static d_write_t dsp_write;
79 static d_ioctl_t dsp_ioctl;
80 static d_poll_t dsp_poll;
81 static d_mmap_t dsp_mmap;
82 static d_mmap_single_t dsp_mmap_single;
83 
84 struct cdevsw dsp_cdevsw = {
85 	.d_version =	D_VERSION,
86 	.d_open =	dsp_open,
87 	.d_close =	dsp_close,
88 	.d_read =	dsp_read,
89 	.d_write =	dsp_write,
90 	.d_ioctl =	dsp_ioctl,
91 	.d_poll =	dsp_poll,
92 	.d_mmap =	dsp_mmap,
93 	.d_mmap_single = dsp_mmap_single,
94 	.d_name =	"dsp",
95 };
96 
97 static eventhandler_tag dsp_ehtag = NULL;
98 static int dsp_umax = -1;
99 static int dsp_cmax = -1;
100 
101 static int dsp_oss_syncgroup(struct pcm_channel *wrch, struct pcm_channel *rdch, oss_syncgroup *group);
102 static int dsp_oss_syncstart(int sg_id);
103 static int dsp_oss_policy(struct pcm_channel *wrch, struct pcm_channel *rdch, int policy);
104 static int dsp_oss_cookedmode(struct pcm_channel *wrch, struct pcm_channel *rdch, int enabled);
105 static int dsp_oss_getchnorder(struct pcm_channel *wrch, struct pcm_channel *rdch, unsigned long long *map);
106 static int dsp_oss_setchnorder(struct pcm_channel *wrch, struct pcm_channel *rdch, unsigned long long *map);
107 static int dsp_oss_getchannelmask(struct pcm_channel *wrch, struct pcm_channel *rdch, int *mask);
108 #ifdef OSSV4_EXPERIMENT
109 static int dsp_oss_getlabel(struct pcm_channel *wrch, struct pcm_channel *rdch, oss_label_t *label);
110 static int dsp_oss_setlabel(struct pcm_channel *wrch, struct pcm_channel *rdch, oss_label_t *label);
111 static int dsp_oss_getsong(struct pcm_channel *wrch, struct pcm_channel *rdch, oss_longname_t *song);
112 static int dsp_oss_setsong(struct pcm_channel *wrch, struct pcm_channel *rdch, oss_longname_t *song);
113 static int dsp_oss_setname(struct pcm_channel *wrch, struct pcm_channel *rdch, oss_longname_t *name);
114 #endif
115 
116 static struct snddev_info *
117 dsp_get_info(struct cdev *dev)
118 {
119 	return (devclass_get_softc(pcm_devclass, PCMUNIT(dev)));
120 }
121 
122 static uint32_t
123 dsp_get_flags(struct cdev *dev)
124 {
125 	device_t bdev;
126 
127 	bdev = devclass_get_device(pcm_devclass, PCMUNIT(dev));
128 
129 	return ((bdev != NULL) ? pcm_getflags(bdev) : 0xffffffff);
130 }
131 
132 static void
133 dsp_set_flags(struct cdev *dev, uint32_t flags)
134 {
135 	device_t bdev;
136 
137 	bdev = devclass_get_device(pcm_devclass, PCMUNIT(dev));
138 
139 	if (bdev != NULL)
140 		pcm_setflags(bdev, flags);
141 }
142 
143 /*
144  * return the channels associated with an open device instance.
145  * lock channels specified.
146  */
147 static int
148 getchns(struct cdev *dev, struct pcm_channel **rdch, struct pcm_channel **wrch,
149     uint32_t prio)
150 {
151 	struct snddev_info *d;
152 	struct pcm_channel *ch;
153 	uint32_t flags;
154 
155 	if (PCM_SIMPLEX(dev) != 0) {
156 		d = dsp_get_info(dev);
157 		if (!PCM_REGISTERED(d))
158 			return (ENXIO);
159 		PCM_LOCK(d);
160 		PCM_WAIT(d);
161 		PCM_ACQUIRE(d);
162 		/*
163 		 * Note: order is important -
164 		 *       pcm flags -> prio query flags -> wild guess
165 		 */
166 		ch = NULL;
167 		flags = dsp_get_flags(dev);
168 		if (flags & SD_F_PRIO_WR) {
169 			ch = PCM_RDCH(dev);
170 			PCM_RDCH(dev) = NULL;
171 		} else if (flags & SD_F_PRIO_RD) {
172 			ch = PCM_WRCH(dev);
173 			PCM_WRCH(dev) = NULL;
174 		} else if (prio & SD_F_PRIO_WR) {
175 			ch = PCM_RDCH(dev);
176 			PCM_RDCH(dev) = NULL;
177 			flags |= SD_F_PRIO_WR;
178 		} else if (prio & SD_F_PRIO_RD) {
179 			ch = PCM_WRCH(dev);
180 			PCM_WRCH(dev) = NULL;
181 			flags |= SD_F_PRIO_RD;
182 		} else if (PCM_WRCH(dev) != NULL) {
183 			ch = PCM_RDCH(dev);
184 			PCM_RDCH(dev) = NULL;
185 			flags |= SD_F_PRIO_WR;
186 		} else if (PCM_RDCH(dev) != NULL) {
187 			ch = PCM_WRCH(dev);
188 			PCM_WRCH(dev) = NULL;
189 			flags |= SD_F_PRIO_RD;
190 		}
191 		PCM_SIMPLEX(dev) = 0;
192 		dsp_set_flags(dev, flags);
193 		if (ch != NULL) {
194 			CHN_LOCK(ch);
195 			pcm_chnref(ch, -1);
196 			pcm_chnrelease(ch);
197 		}
198 		PCM_RELEASE(d);
199 		PCM_UNLOCK(d);
200 	}
201 
202 	*rdch = PCM_RDCH(dev);
203 	*wrch = PCM_WRCH(dev);
204 
205 	if (*rdch != NULL && (prio & SD_F_PRIO_RD))
206 		CHN_LOCK(*rdch);
207 	if (*wrch != NULL && (prio & SD_F_PRIO_WR))
208 		CHN_LOCK(*wrch);
209 
210 	return (0);
211 }
212 
213 /* unlock specified channels */
214 static void
215 relchns(struct cdev *dev, struct pcm_channel *rdch, struct pcm_channel *wrch,
216     uint32_t prio)
217 {
218 	if (wrch != NULL && (prio & SD_F_PRIO_WR))
219 		CHN_UNLOCK(wrch);
220 	if (rdch != NULL && (prio & SD_F_PRIO_RD))
221 		CHN_UNLOCK(rdch);
222 }
223 
224 static void
225 dsp_cdevinfo_alloc(struct cdev *dev,
226     struct pcm_channel *rdch, struct pcm_channel *wrch,
227     struct pcm_channel *volch)
228 {
229 	struct snddev_info *d;
230 	struct dsp_cdevinfo *cdi;
231 	int simplex;
232 
233 	d = dsp_get_info(dev);
234 
235 	KASSERT(PCM_REGISTERED(d) && dev != NULL && dev->si_drv1 == NULL &&
236 	    ((rdch == NULL && wrch == NULL) || rdch != wrch),
237 	    ("bogus %s(), what are you trying to accomplish here?", __func__));
238 	PCM_BUSYASSERT(d);
239 	PCM_LOCKASSERT(d);
240 
241 	simplex = (dsp_get_flags(dev) & SD_F_SIMPLEX) ? 1 : 0;
242 
243 	/*
244 	 * Scan for free instance entry and put it into the end of list.
245 	 * Create new one if necessary.
246 	 */
247 	TAILQ_FOREACH(cdi, &d->dsp_cdevinfo_pool, link) {
248 		if (cdi->busy != 0)
249 			break;
250 		cdi->rdch = rdch;
251 		cdi->wrch = wrch;
252 		cdi->volch = volch;
253 		cdi->simplex = simplex;
254 		cdi->busy = 1;
255 		TAILQ_REMOVE(&d->dsp_cdevinfo_pool, cdi, link);
256 		TAILQ_INSERT_TAIL(&d->dsp_cdevinfo_pool, cdi, link);
257 		dev->si_drv1 = cdi;
258 		return;
259 	}
260 	PCM_UNLOCK(d);
261 	cdi = malloc(sizeof(*cdi), M_DEVBUF, M_WAITOK | M_ZERO);
262 	PCM_LOCK(d);
263 	cdi->rdch = rdch;
264 	cdi->wrch = wrch;
265 	cdi->volch = volch;
266 	cdi->simplex = simplex;
267 	cdi->busy = 1;
268 	TAILQ_INSERT_TAIL(&d->dsp_cdevinfo_pool, cdi, link);
269 	dev->si_drv1 = cdi;
270 }
271 
272 static void
273 dsp_cdevinfo_free(struct cdev *dev)
274 {
275 	struct snddev_info *d;
276 	struct dsp_cdevinfo *cdi, *tmp;
277 	uint32_t flags;
278 	int i;
279 
280 	d = dsp_get_info(dev);
281 
282 	KASSERT(PCM_REGISTERED(d) && dev != NULL && dev->si_drv1 != NULL &&
283 	    PCM_RDCH(dev) == NULL && PCM_WRCH(dev) == NULL &&
284 	    PCM_VOLCH(dev) == NULL,
285 	    ("bogus %s(), what are you trying to accomplish here?", __func__));
286 	PCM_BUSYASSERT(d);
287 	PCM_LOCKASSERT(d);
288 
289 	cdi = dev->si_drv1;
290 	dev->si_drv1 = NULL;
291 	cdi->rdch = NULL;
292 	cdi->wrch = NULL;
293 	cdi->volch = NULL;
294 	cdi->simplex = 0;
295 	cdi->busy = 0;
296 
297 	/*
298 	 * Once it is free, move it back to the beginning of list for
299 	 * faster new entry allocation.
300 	 */
301 	TAILQ_REMOVE(&d->dsp_cdevinfo_pool, cdi, link);
302 	TAILQ_INSERT_HEAD(&d->dsp_cdevinfo_pool, cdi, link);
303 
304 	/*
305 	 * Scan the list, cache free entries up to DSP_CDEVINFO_CACHESIZE.
306 	 * Reset simplex flags.
307 	 */
308 	flags = dsp_get_flags(dev) & ~SD_F_PRIO_SET;
309 	i = DSP_CDEVINFO_CACHESIZE;
310 	TAILQ_FOREACH_SAFE(cdi, &d->dsp_cdevinfo_pool, link, tmp) {
311 		if (cdi->busy != 0) {
312 			if (cdi->simplex == 0) {
313 				if (cdi->rdch != NULL)
314 					flags |= SD_F_PRIO_RD;
315 				if (cdi->wrch != NULL)
316 					flags |= SD_F_PRIO_WR;
317 			}
318 		} else {
319 			if (i == 0) {
320 				TAILQ_REMOVE(&d->dsp_cdevinfo_pool, cdi, link);
321 				free(cdi, M_DEVBUF);
322 			} else
323 				i--;
324 		}
325 	}
326 	dsp_set_flags(dev, flags);
327 }
328 
329 void
330 dsp_cdevinfo_init(struct snddev_info *d)
331 {
332 	struct dsp_cdevinfo *cdi;
333 	int i;
334 
335 	KASSERT(d != NULL, ("NULL snddev_info"));
336 	PCM_BUSYASSERT(d);
337 	PCM_UNLOCKASSERT(d);
338 
339 	TAILQ_INIT(&d->dsp_cdevinfo_pool);
340 	for (i = 0; i < DSP_CDEVINFO_CACHESIZE; i++) {
341 		cdi = malloc(sizeof(*cdi), M_DEVBUF, M_WAITOK | M_ZERO);
342 		TAILQ_INSERT_HEAD(&d->dsp_cdevinfo_pool, cdi, link);
343 	}
344 }
345 
346 void
347 dsp_cdevinfo_flush(struct snddev_info *d)
348 {
349 	struct dsp_cdevinfo *cdi, *tmp;
350 
351 	KASSERT(d != NULL, ("NULL snddev_info"));
352 	PCM_BUSYASSERT(d);
353 	PCM_UNLOCKASSERT(d);
354 
355 	cdi = TAILQ_FIRST(&d->dsp_cdevinfo_pool);
356 	while (cdi != NULL) {
357 		tmp = TAILQ_NEXT(cdi, link);
358 		free(cdi, M_DEVBUF);
359 		cdi = tmp;
360 	}
361 	TAILQ_INIT(&d->dsp_cdevinfo_pool);
362 }
363 
364 /* duplex / simplex cdev type */
365 enum {
366 	DSP_CDEV_TYPE_RDONLY,		/* simplex read-only (record)   */
367 	DSP_CDEV_TYPE_WRONLY,		/* simplex write-only (play)    */
368 	DSP_CDEV_TYPE_RDWR		/* duplex read, write, or both  */
369 };
370 
371 enum {
372 	DSP_CDEV_VOLCTL_NONE,
373 	DSP_CDEV_VOLCTL_READ,
374 	DSP_CDEV_VOLCTL_WRITE
375 };
376 
377 #define DSP_F_VALID(x)		((x) & (FREAD | FWRITE))
378 #define DSP_F_DUPLEX(x)		(((x) & (FREAD | FWRITE)) == (FREAD | FWRITE))
379 #define DSP_F_SIMPLEX(x)	(!DSP_F_DUPLEX(x))
380 #define DSP_F_READ(x)		((x) & FREAD)
381 #define DSP_F_WRITE(x)		((x) & FWRITE)
382 
383 static const struct {
384 	int type;
385 	char *name;
386 	char *sep;
387 	char *alias;
388 	int use_sep;
389 	int hw;
390 	int max;
391 	int volctl;
392 	uint32_t fmt, spd;
393 	int query;
394 } dsp_cdevs[] = {
395 	{ SND_DEV_DSP,         "dsp",    ".", NULL, 0, 0, 0, 0,
396 	  SND_FORMAT(AFMT_U8, 1, 0),     DSP_DEFAULT_SPEED,
397 	  DSP_CDEV_TYPE_RDWR },
398 	{ SND_DEV_AUDIO,       "audio",  ".", NULL, 0, 0, 0, 0,
399 	  SND_FORMAT(AFMT_MU_LAW, 1, 0), DSP_DEFAULT_SPEED,
400 	  DSP_CDEV_TYPE_RDWR },
401 	{ SND_DEV_DSP16,       "dspW",   ".", NULL, 0, 0, 0, 0,
402 	  SND_FORMAT(AFMT_S16_LE, 1, 0), DSP_DEFAULT_SPEED,
403 	  DSP_CDEV_TYPE_RDWR },
404 	{ SND_DEV_DSPHW_PLAY,  "dsp",   ".p", NULL, 1, 1, SND_MAXHWCHAN, 1,
405 	  SND_FORMAT(AFMT_S16_LE, 2, 0), 48000, DSP_CDEV_TYPE_WRONLY },
406 	{ SND_DEV_DSPHW_VPLAY, "dsp",  ".vp", NULL, 1, 1, SND_MAXVCHANS, 1,
407 	  SND_FORMAT(AFMT_S16_LE, 2, 0), 48000, DSP_CDEV_TYPE_WRONLY },
408 	{ SND_DEV_DSPHW_REC,   "dsp",   ".r", NULL, 1, 1, SND_MAXHWCHAN, 1,
409 	  SND_FORMAT(AFMT_S16_LE, 2, 0), 48000, DSP_CDEV_TYPE_RDONLY },
410 	{ SND_DEV_DSPHW_VREC,  "dsp",  ".vr", NULL, 1, 1, SND_MAXVCHANS, 1,
411 	  SND_FORMAT(AFMT_S16_LE, 2, 0), 48000, DSP_CDEV_TYPE_RDONLY },
412 	{ SND_DEV_DSPHW_CD,    "dspcd",  ".", NULL, 0, 0, 0, 0,
413 	  SND_FORMAT(AFMT_S16_LE, 2, 0), 44100, DSP_CDEV_TYPE_RDWR   },
414 	/* Low priority, OSSv4 aliases. */
415 	{ SND_DEV_DSP,      "dsp_ac3",   ".", "dsp", 0, 0, 0, 0,
416 	  SND_FORMAT(AFMT_U8, 1, 0),     DSP_DEFAULT_SPEED,
417 	  DSP_CDEV_TYPE_RDWR },
418 	{ SND_DEV_DSP,     "dsp_mmap",   ".", "dsp", 0, 0, 0, 0,
419 	  SND_FORMAT(AFMT_U8, 1, 0),     DSP_DEFAULT_SPEED,
420 	  DSP_CDEV_TYPE_RDWR },
421 	{ SND_DEV_DSP,  "dsp_multich",   ".", "dsp", 0, 0, 0, 0,
422 	  SND_FORMAT(AFMT_U8, 1, 0),     DSP_DEFAULT_SPEED,
423 	  DSP_CDEV_TYPE_RDWR },
424 	{ SND_DEV_DSP, "dsp_spdifout",   ".", "dsp", 0, 0, 0, 0,
425 	  SND_FORMAT(AFMT_U8, 1, 0),     DSP_DEFAULT_SPEED,
426 	  DSP_CDEV_TYPE_RDWR },
427 	{ SND_DEV_DSP,  "dsp_spdifin",   ".", "dsp", 0, 0, 0, 0,
428 	  SND_FORMAT(AFMT_U8, 1, 0),     DSP_DEFAULT_SPEED,
429 	  DSP_CDEV_TYPE_RDWR },
430 };
431 
432 #define DSP_FIXUP_ERROR()		do {				\
433 	prio = dsp_get_flags(i_dev);					\
434 	if (!DSP_F_VALID(flags))					\
435 		error = EINVAL;						\
436 	if (!DSP_F_DUPLEX(flags) &&					\
437 	    ((DSP_F_READ(flags) && d->reccount == 0) ||			\
438 	    (DSP_F_WRITE(flags) && d->playcount == 0)))			\
439 		error = ENOTSUP;					\
440 	else if (!DSP_F_DUPLEX(flags) && (prio & SD_F_SIMPLEX) &&	\
441 	    ((DSP_F_READ(flags) && (prio & SD_F_PRIO_WR)) ||		\
442 	    (DSP_F_WRITE(flags) && (prio & SD_F_PRIO_RD))))		\
443 		error = EBUSY;						\
444 	else if (DSP_REGISTERED(d, i_dev))				\
445 		error = EBUSY;						\
446 } while (0)
447 
448 static int
449 dsp_open(struct cdev *i_dev, int flags, int mode, struct thread *td)
450 {
451 	struct pcm_channel *rdch, *wrch;
452 	struct snddev_info *d;
453 	uint32_t fmt, spd, prio, volctl;
454 	int i, error, rderror, wrerror, devtype, wdevunit, rdevunit;
455 
456 	/* Kind of impossible.. */
457 	if (i_dev == NULL || td == NULL)
458 		return (ENODEV);
459 
460 	d = dsp_get_info(i_dev);
461 	if (PCM_DETACHING(d) || !PCM_REGISTERED(d))
462 		return (EBADF);
463 
464 	PCM_GIANT_ENTER(d);
465 
466 	/* Lock snddev so nobody else can monkey with it. */
467 	PCM_LOCK(d);
468 	PCM_WAIT(d);
469 
470 	/*
471 	 * Try to acquire cloned device before someone else pick it.
472 	 * ENODEV means this is not a cloned droids.
473 	 */
474 	error = snd_clone_acquire(i_dev);
475 	if (!(error == 0 || error == ENODEV)) {
476 		DSP_FIXUP_ERROR();
477 		PCM_UNLOCK(d);
478 		PCM_GIANT_EXIT(d);
479 		return (error);
480 	}
481 
482 	error = 0;
483 	DSP_FIXUP_ERROR();
484 
485 	if (error != 0) {
486 		(void)snd_clone_release(i_dev);
487 		PCM_UNLOCK(d);
488 		PCM_GIANT_EXIT(d);
489 		return (error);
490 	}
491 
492 	/*
493 	 * That is just enough. Acquire and unlock pcm lock so
494 	 * the other will just have to wait until we finish doing
495 	 * everything.
496 	 */
497 	PCM_ACQUIRE(d);
498 	PCM_UNLOCK(d);
499 
500 	devtype = PCMDEV(i_dev);
501 	wdevunit = -1;
502 	rdevunit = -1;
503 	fmt = 0;
504 	spd = 0;
505 	volctl = DSP_CDEV_VOLCTL_NONE;
506 
507 	for (i = 0; i < (sizeof(dsp_cdevs) / sizeof(dsp_cdevs[0])); i++) {
508 		if (devtype != dsp_cdevs[i].type || dsp_cdevs[i].alias != NULL)
509 			continue;
510 		/*
511 		 * Volume control only valid for DSPHW devices,
512 		 * and it must be opened in opposite direction be it
513 		 * simplex or duplex. Anything else will be handled
514 		 * as usual.
515 		 */
516 		if (dsp_cdevs[i].query == DSP_CDEV_TYPE_WRONLY) {
517 			if (dsp_cdevs[i].volctl != 0 &&
518 			    DSP_F_READ(flags)) {
519 				volctl = DSP_CDEV_VOLCTL_WRITE;
520 				flags &= ~FREAD;
521 				flags |= FWRITE;
522 			}
523 			if (DSP_F_READ(flags)) {
524 				(void)snd_clone_release(i_dev);
525 				PCM_RELEASE_QUICK(d);
526 				PCM_GIANT_EXIT(d);
527 				return (ENOTSUP);
528 			}
529 			wdevunit = dev2unit(i_dev);
530 		} else if (dsp_cdevs[i].query == DSP_CDEV_TYPE_RDONLY) {
531 			if (dsp_cdevs[i].volctl != 0 &&
532 			    DSP_F_WRITE(flags)) {
533 				volctl = DSP_CDEV_VOLCTL_READ;
534 				flags &= ~FWRITE;
535 				flags |= FREAD;
536 			}
537 			if (DSP_F_WRITE(flags)) {
538 				(void)snd_clone_release(i_dev);
539 				PCM_RELEASE_QUICK(d);
540 				PCM_GIANT_EXIT(d);
541 				return (ENOTSUP);
542 			}
543 			rdevunit = dev2unit(i_dev);
544 		}
545 		fmt = dsp_cdevs[i].fmt;
546 		spd = dsp_cdevs[i].spd;
547 		break;
548 	}
549 
550 	/* No matching devtype? */
551 	if (fmt == 0 || spd == 0)
552 		panic("impossible devtype %d", devtype);
553 
554 	rdch = NULL;
555 	wrch = NULL;
556 	rderror = 0;
557 	wrerror = 0;
558 
559 	/*
560 	 * if we get here, the open request is valid- either:
561 	 *   * we were previously not open
562 	 *   * we were open for play xor record and the opener wants
563 	 *     the non-open direction
564 	 */
565 	if (DSP_F_READ(flags)) {
566 		/* open for read */
567 		rderror = pcm_chnalloc(d, &rdch, PCMDIR_REC,
568 		    td->td_proc->p_pid, td->td_proc->p_comm, rdevunit);
569 
570 		if (rderror == 0 && chn_reset(rdch, fmt, spd) != 0)
571 			rderror = ENXIO;
572 
573 		if (volctl == DSP_CDEV_VOLCTL_READ)
574 			rderror = 0;
575 
576 		if (rderror != 0) {
577 			if (rdch != NULL)
578 				pcm_chnrelease(rdch);
579 			if (!DSP_F_DUPLEX(flags)) {
580 				(void)snd_clone_release(i_dev);
581 				PCM_RELEASE_QUICK(d);
582 				PCM_GIANT_EXIT(d);
583 				return (rderror);
584 			}
585 			rdch = NULL;
586 		} else if (volctl == DSP_CDEV_VOLCTL_READ) {
587 			if (rdch != NULL) {
588 				pcm_chnref(rdch, 1);
589 				pcm_chnrelease(rdch);
590 			}
591 		} else {
592 			if (flags & O_NONBLOCK)
593 				rdch->flags |= CHN_F_NBIO;
594 			if (flags & O_EXCL)
595 				rdch->flags |= CHN_F_EXCLUSIVE;
596 			pcm_chnref(rdch, 1);
597 			if (volctl == DSP_CDEV_VOLCTL_NONE)
598 				chn_vpc_reset(rdch, SND_VOL_C_PCM, 0);
599 		 	CHN_UNLOCK(rdch);
600 		}
601 	}
602 
603 	if (DSP_F_WRITE(flags)) {
604 		/* open for write */
605 		wrerror = pcm_chnalloc(d, &wrch, PCMDIR_PLAY,
606 		    td->td_proc->p_pid, td->td_proc->p_comm, wdevunit);
607 
608 		if (wrerror == 0 && chn_reset(wrch, fmt, spd) != 0)
609 			wrerror = ENXIO;
610 
611 		if (volctl == DSP_CDEV_VOLCTL_WRITE)
612 			wrerror = 0;
613 
614 		if (wrerror != 0) {
615 			if (wrch != NULL)
616 				pcm_chnrelease(wrch);
617 			if (!DSP_F_DUPLEX(flags)) {
618 				if (rdch != NULL) {
619 					/*
620 					 * Lock, deref and release previously
621 					 * created record channel
622 					 */
623 					CHN_LOCK(rdch);
624 					pcm_chnref(rdch, -1);
625 					pcm_chnrelease(rdch);
626 				}
627 				(void)snd_clone_release(i_dev);
628 				PCM_RELEASE_QUICK(d);
629 				PCM_GIANT_EXIT(d);
630 				return (wrerror);
631 			}
632 			wrch = NULL;
633 		} else if (volctl == DSP_CDEV_VOLCTL_WRITE) {
634 			if (wrch != NULL) {
635 				pcm_chnref(wrch, 1);
636 				pcm_chnrelease(wrch);
637 			}
638 		} else {
639 			if (flags & O_NONBLOCK)
640 				wrch->flags |= CHN_F_NBIO;
641 			if (flags & O_EXCL)
642 				wrch->flags |= CHN_F_EXCLUSIVE;
643 			pcm_chnref(wrch, 1);
644 			if (volctl == DSP_CDEV_VOLCTL_NONE)
645 				chn_vpc_reset(wrch, SND_VOL_C_PCM, 0);
646 			CHN_UNLOCK(wrch);
647 		}
648 	}
649 
650 	PCM_LOCK(d);
651 
652 	/*
653 	 * We're done. Allocate channels information for this cdev.
654 	 */
655 	switch (volctl) {
656 	case DSP_CDEV_VOLCTL_READ:
657 		KASSERT(wrch == NULL, ("wrch=%p not null!", wrch));
658 		dsp_cdevinfo_alloc(i_dev, NULL, NULL, rdch);
659 		break;
660 	case DSP_CDEV_VOLCTL_WRITE:
661 		KASSERT(rdch == NULL, ("rdch=%p not null!", rdch));
662 		dsp_cdevinfo_alloc(i_dev, NULL, NULL, wrch);
663 		break;
664 	case DSP_CDEV_VOLCTL_NONE:
665 	default:
666 		if (wrch == NULL && rdch == NULL) {
667 			(void)snd_clone_release(i_dev);
668 			PCM_RELEASE(d);
669 			PCM_UNLOCK(d);
670 			PCM_GIANT_EXIT(d);
671 			if (wrerror != 0)
672 				return (wrerror);
673 			if (rderror != 0)
674 				return (rderror);
675 			return (EINVAL);
676 		}
677 		dsp_cdevinfo_alloc(i_dev, rdch, wrch, NULL);
678 		if (rdch != NULL)
679 			CHN_INSERT_HEAD(d, rdch, channels.pcm.opened);
680 		if (wrch != NULL)
681 			CHN_INSERT_HEAD(d, wrch, channels.pcm.opened);
682 		break;
683 	}
684 
685 	/*
686 	 * Increase clone refcount for its automatic garbage collector.
687 	 */
688 	(void)snd_clone_ref(i_dev);
689 
690 	PCM_RELEASE(d);
691 	PCM_UNLOCK(d);
692 
693 	PCM_GIANT_LEAVE(d);
694 
695 	return (0);
696 }
697 
698 static int
699 dsp_close(struct cdev *i_dev, int flags, int mode, struct thread *td)
700 {
701 	struct pcm_channel *rdch, *wrch, *volch;
702 	struct snddev_info *d;
703 	int sg_ids, rdref, wdref;
704 
705 	d = dsp_get_info(i_dev);
706 	if (!DSP_REGISTERED(d, i_dev))
707 		return (EBADF);
708 
709 	PCM_GIANT_ENTER(d);
710 
711 	PCM_LOCK(d);
712 	PCM_WAIT(d);
713 	PCM_ACQUIRE(d);
714 
715 	rdch = PCM_RDCH(i_dev);
716 	wrch = PCM_WRCH(i_dev);
717 	volch = PCM_VOLCH(i_dev);
718 
719 	PCM_RDCH(i_dev) = NULL;
720 	PCM_WRCH(i_dev) = NULL;
721 	PCM_VOLCH(i_dev) = NULL;
722 
723 	rdref = -1;
724 	wdref = -1;
725 
726 	if (volch != NULL) {
727 		if (volch == rdch)
728 			rdref--;
729 		else if (volch == wrch)
730 			wdref--;
731 		else {
732 			CHN_LOCK(volch);
733 			pcm_chnref(volch, -1);
734 			CHN_UNLOCK(volch);
735 		}
736 	}
737 
738 	if (rdch != NULL)
739 		CHN_REMOVE(d, rdch, channels.pcm.opened);
740 	if (wrch != NULL)
741 		CHN_REMOVE(d, wrch, channels.pcm.opened);
742 
743 	if (rdch != NULL || wrch != NULL) {
744 		PCM_UNLOCK(d);
745 		if (rdch != NULL) {
746 			/*
747 			 * The channel itself need not be locked because:
748 			 *   a)  Adding a channel to a syncgroup happens only
749 			 *       in dsp_ioctl(), which cannot run concurrently
750 			 *       to dsp_close().
751 			 *   b)  The syncmember pointer (sm) is protected by
752 			 *       the global syncgroup list lock.
753 			 *   c)  A channel can't just disappear, invalidating
754 			 *       pointers, unless it's closed/dereferenced
755 			 *       first.
756 			 */
757 			PCM_SG_LOCK();
758 			sg_ids = chn_syncdestroy(rdch);
759 			PCM_SG_UNLOCK();
760 			if (sg_ids != 0)
761 				free_unr(pcmsg_unrhdr, sg_ids);
762 
763 			CHN_LOCK(rdch);
764 			pcm_chnref(rdch, rdref);
765 			chn_abort(rdch); /* won't sleep */
766 			rdch->flags &= ~(CHN_F_RUNNING | CHN_F_MMAP |
767 			    CHN_F_DEAD | CHN_F_EXCLUSIVE);
768 			chn_reset(rdch, 0, 0);
769 			pcm_chnrelease(rdch);
770 		}
771 		if (wrch != NULL) {
772 			/*
773 			 * Please see block above.
774 			 */
775 			PCM_SG_LOCK();
776 			sg_ids = chn_syncdestroy(wrch);
777 			PCM_SG_UNLOCK();
778 			if (sg_ids != 0)
779 				free_unr(pcmsg_unrhdr, sg_ids);
780 
781 			CHN_LOCK(wrch);
782 			pcm_chnref(wrch, wdref);
783 			chn_flush(wrch); /* may sleep */
784 			wrch->flags &= ~(CHN_F_RUNNING | CHN_F_MMAP |
785 			    CHN_F_DEAD | CHN_F_EXCLUSIVE);
786 			chn_reset(wrch, 0, 0);
787 			pcm_chnrelease(wrch);
788 		}
789 		PCM_LOCK(d);
790 	}
791 
792 	dsp_cdevinfo_free(i_dev);
793 	/*
794 	 * Release clone busy state and unref it so the automatic
795 	 * garbage collector will get the hint and do the remaining
796 	 * cleanup process.
797 	 */
798 	(void)snd_clone_release(i_dev);
799 
800 	/*
801 	 * destroy_dev() might sleep, so release pcm lock
802 	 * here and rely on pcm cv serialization.
803 	 */
804 	PCM_UNLOCK(d);
805 	(void)snd_clone_unref(i_dev);
806 	PCM_LOCK(d);
807 
808 	PCM_RELEASE(d);
809 	PCM_UNLOCK(d);
810 
811 	PCM_GIANT_LEAVE(d);
812 
813 	return (0);
814 }
815 
816 static __inline int
817 dsp_io_ops(struct cdev *i_dev, struct uio *buf)
818 {
819 	struct snddev_info *d;
820 	struct pcm_channel **ch, *rdch, *wrch;
821 	int (*chn_io)(struct pcm_channel *, struct uio *);
822 	int prio, ret;
823 	pid_t runpid;
824 
825 	KASSERT(i_dev != NULL && buf != NULL &&
826 	    (buf->uio_rw == UIO_READ || buf->uio_rw == UIO_WRITE),
827 	    ("%s(): io train wreck!", __func__));
828 
829 	d = dsp_get_info(i_dev);
830 	if (PCM_DETACHING(d) || !DSP_REGISTERED(d, i_dev))
831 		return (EBADF);
832 
833 	PCM_GIANT_ENTER(d);
834 
835 	switch (buf->uio_rw) {
836 	case UIO_READ:
837 		prio = SD_F_PRIO_RD;
838 		ch = &rdch;
839 		chn_io = chn_read;
840 		break;
841 	case UIO_WRITE:
842 		prio = SD_F_PRIO_WR;
843 		ch = &wrch;
844 		chn_io = chn_write;
845 		break;
846 	default:
847 		panic("invalid/corrupted uio direction: %d", buf->uio_rw);
848 		break;
849 	}
850 
851 	rdch = NULL;
852 	wrch = NULL;
853 	runpid = buf->uio_td->td_proc->p_pid;
854 
855 	getchns(i_dev, &rdch, &wrch, prio);
856 
857 	if (*ch == NULL || !((*ch)->flags & CHN_F_BUSY)) {
858 		if (rdch != NULL || wrch != NULL)
859 			relchns(i_dev, rdch, wrch, prio);
860 		PCM_GIANT_EXIT(d);
861 		return (EBADF);
862 	}
863 
864 	if (((*ch)->flags & (CHN_F_MMAP | CHN_F_DEAD)) ||
865 	    (((*ch)->flags & CHN_F_RUNNING) && (*ch)->pid != runpid)) {
866 		relchns(i_dev, rdch, wrch, prio);
867 		PCM_GIANT_EXIT(d);
868 		return (EINVAL);
869 	} else if (!((*ch)->flags & CHN_F_RUNNING)) {
870 		(*ch)->flags |= CHN_F_RUNNING;
871 		(*ch)->pid = runpid;
872 	}
873 
874 	/*
875 	 * chn_read/write must give up channel lock in order to copy bytes
876 	 * from/to userland, so up the "in progress" counter to make sure
877 	 * someone else doesn't come along and muss up the buffer.
878 	 */
879 	++(*ch)->inprog;
880 	ret = chn_io(*ch, buf);
881 	--(*ch)->inprog;
882 
883 	CHN_BROADCAST(&(*ch)->cv);
884 
885 	relchns(i_dev, rdch, wrch, prio);
886 
887 	PCM_GIANT_LEAVE(d);
888 
889 	return (ret);
890 }
891 
892 static int
893 dsp_read(struct cdev *i_dev, struct uio *buf, int flag)
894 {
895 	return (dsp_io_ops(i_dev, buf));
896 }
897 
898 static int
899 dsp_write(struct cdev *i_dev, struct uio *buf, int flag)
900 {
901 	return (dsp_io_ops(i_dev, buf));
902 }
903 
904 static int
905 dsp_get_volume_channel(struct cdev *dev, struct pcm_channel **volch)
906 {
907 	struct snddev_info *d;
908 	struct pcm_channel *c;
909 	int unit;
910 
911 	KASSERT(dev != NULL && volch != NULL,
912 	    ("%s(): NULL query dev=%p volch=%p", __func__, dev, volch));
913 
914 	d = dsp_get_info(dev);
915 	if (!PCM_REGISTERED(d)) {
916 		*volch = NULL;
917 		return (EINVAL);
918 	}
919 
920 	PCM_UNLOCKASSERT(d);
921 
922 	*volch = NULL;
923 
924 	c = PCM_VOLCH(dev);
925 	if (c != NULL) {
926 		if (!(c->feederflags & (1 << FEEDER_VOLUME)))
927 			return (-1);
928 		*volch = c;
929 		return (0);
930 	}
931 
932 	PCM_LOCK(d);
933 	PCM_WAIT(d);
934 	PCM_ACQUIRE(d);
935 
936 	unit = dev2unit(dev);
937 
938 	CHN_FOREACH(c, d, channels.pcm) {
939 		CHN_LOCK(c);
940 		if (c->unit != unit) {
941 			CHN_UNLOCK(c);
942 			continue;
943 		}
944 		*volch = c;
945 		pcm_chnref(c, 1);
946 		PCM_VOLCH(dev) = c;
947 		CHN_UNLOCK(c);
948 		PCM_RELEASE(d);
949 		PCM_UNLOCK(d);
950 		return ((c->feederflags & (1 << FEEDER_VOLUME)) ? 0 : -1);
951 	}
952 
953 	PCM_RELEASE(d);
954 	PCM_UNLOCK(d);
955 
956 	return (EINVAL);
957 }
958 
959 static int
960 dsp_ioctl_channel(struct cdev *dev, struct pcm_channel *volch, u_long cmd,
961     caddr_t arg)
962 {
963 	struct snddev_info *d;
964 	struct pcm_channel *rdch, *wrch;
965 	int j, devtype, ret;
966 	int left, right, center, mute;
967 
968 	d = dsp_get_info(dev);
969 	if (!PCM_REGISTERED(d) || !(dsp_get_flags(dev) & SD_F_VPC))
970 		return (-1);
971 
972 	PCM_UNLOCKASSERT(d);
973 
974 	j = cmd & 0xff;
975 
976 	rdch = PCM_RDCH(dev);
977 	wrch = PCM_WRCH(dev);
978 
979 	/* No specific channel, look into cache */
980 	if (volch == NULL)
981 		volch = PCM_VOLCH(dev);
982 
983 	/* Look harder */
984 	if (volch == NULL) {
985 		if (j == SOUND_MIXER_RECLEV && rdch != NULL)
986 			volch = rdch;
987 		else if (j == SOUND_MIXER_PCM && wrch != NULL)
988 			volch = wrch;
989 	}
990 
991 	devtype = PCMDEV(dev);
992 
993 	/* Look super harder */
994 	if (volch == NULL &&
995 	    (devtype == SND_DEV_DSPHW_PLAY || devtype == SND_DEV_DSPHW_VPLAY ||
996 	    devtype == SND_DEV_DSPHW_REC || devtype == SND_DEV_DSPHW_VREC)) {
997 		ret = dsp_get_volume_channel(dev, &volch);
998 		if (ret != 0)
999 			return (ret);
1000 		if (volch == NULL)
1001 			return (EINVAL);
1002 	}
1003 
1004 	/* Final validation */
1005 	if (volch == NULL)
1006 		return (EINVAL);
1007 
1008 	CHN_LOCK(volch);
1009 	if (!(volch->feederflags & (1 << FEEDER_VOLUME))) {
1010 		CHN_UNLOCK(volch);
1011 		return (EINVAL);
1012 	}
1013 
1014 	switch (cmd & ~0xff) {
1015 	case MIXER_WRITE(0):
1016 		switch (j) {
1017 		case SOUND_MIXER_MUTE:
1018 			if (volch->direction == PCMDIR_REC) {
1019 				chn_setmute_multi(volch, SND_VOL_C_PCM, (*(int *)arg & SOUND_MASK_RECLEV) != 0);
1020 			} else {
1021 				chn_setmute_multi(volch, SND_VOL_C_PCM, (*(int *)arg & SOUND_MASK_PCM) != 0);
1022 			}
1023 			break;
1024 		case SOUND_MIXER_PCM:
1025 			if (volch->direction != PCMDIR_PLAY)
1026 				break;
1027 			left = *(int *)arg & 0x7f;
1028 			right = ((*(int *)arg) >> 8) & 0x7f;
1029 			center = (left + right) >> 1;
1030 			chn_setvolume_multi(volch, SND_VOL_C_PCM,
1031 			    left, right, center);
1032 			break;
1033 		case SOUND_MIXER_RECLEV:
1034 			if (volch->direction != PCMDIR_REC)
1035 				break;
1036 			left = *(int *)arg & 0x7f;
1037 			right = ((*(int *)arg) >> 8) & 0x7f;
1038 			center = (left + right) >> 1;
1039 			chn_setvolume_multi(volch, SND_VOL_C_PCM,
1040 			    left, right, center);
1041 			break;
1042 		default:
1043 			/* ignore all other mixer writes */
1044 			break;
1045 		}
1046 		break;
1047 
1048 	case MIXER_READ(0):
1049 		switch (j) {
1050 		case SOUND_MIXER_MUTE:
1051 			mute = CHN_GETMUTE(volch, SND_VOL_C_PCM, SND_CHN_T_FL) ||
1052 			    CHN_GETMUTE(volch, SND_VOL_C_PCM, SND_CHN_T_FR);
1053 			if (volch->direction == PCMDIR_REC) {
1054 				*(int *)arg = mute << SOUND_MIXER_RECLEV;
1055 			} else {
1056 				*(int *)arg = mute << SOUND_MIXER_PCM;
1057 			}
1058 			break;
1059 		case SOUND_MIXER_PCM:
1060 			if (volch->direction != PCMDIR_PLAY)
1061 				break;
1062 			*(int *)arg = CHN_GETVOLUME(volch,
1063 			    SND_VOL_C_PCM, SND_CHN_T_FL);
1064 			*(int *)arg |= CHN_GETVOLUME(volch,
1065 			    SND_VOL_C_PCM, SND_CHN_T_FR) << 8;
1066 			break;
1067 		case SOUND_MIXER_RECLEV:
1068 			if (volch->direction != PCMDIR_REC)
1069 				break;
1070 			*(int *)arg = CHN_GETVOLUME(volch,
1071 			    SND_VOL_C_PCM, SND_CHN_T_FL);
1072 			*(int *)arg |= CHN_GETVOLUME(volch,
1073 			    SND_VOL_C_PCM, SND_CHN_T_FR) << 8;
1074 			break;
1075 		case SOUND_MIXER_DEVMASK:
1076 		case SOUND_MIXER_CAPS:
1077 		case SOUND_MIXER_STEREODEVS:
1078 			if (volch->direction == PCMDIR_REC)
1079 				*(int *)arg = SOUND_MASK_RECLEV;
1080 			else
1081 				*(int *)arg = SOUND_MASK_PCM;
1082 			break;
1083 		default:
1084 			*(int *)arg = 0;
1085 			break;
1086 		}
1087 		break;
1088 
1089 	default:
1090 		break;
1091 	}
1092 	CHN_UNLOCK(volch);
1093 	return (0);
1094 }
1095 
1096 static int
1097 dsp_ioctl(struct cdev *i_dev, u_long cmd, caddr_t arg, int mode,
1098     struct thread *td)
1099 {
1100     	struct pcm_channel *chn, *rdch, *wrch;
1101 	struct snddev_info *d;
1102 	u_long xcmd;
1103 	int *arg_i, ret, tmp;
1104 
1105 	d = dsp_get_info(i_dev);
1106 	if (PCM_DETACHING(d) || !DSP_REGISTERED(d, i_dev))
1107 		return (EBADF);
1108 
1109 	PCM_GIANT_ENTER(d);
1110 
1111 	arg_i = (int *)arg;
1112 	ret = 0;
1113 	xcmd = 0;
1114 	chn = NULL;
1115 
1116 	if (IOCGROUP(cmd) == 'M') {
1117 		if (cmd == OSS_GETVERSION) {
1118 			*arg_i = SOUND_VERSION;
1119 			PCM_GIANT_EXIT(d);
1120 			return (0);
1121 		}
1122 		ret = dsp_ioctl_channel(i_dev, PCM_VOLCH(i_dev), cmd, arg);
1123 		if (ret != -1) {
1124 			PCM_GIANT_EXIT(d);
1125 			return (ret);
1126 		}
1127 
1128 		if (d->mixer_dev != NULL) {
1129 			PCM_ACQUIRE_QUICK(d);
1130 			ret = mixer_ioctl_cmd(d->mixer_dev, cmd, arg, -1, td,
1131 			    MIXER_CMD_DIRECT);
1132 			PCM_RELEASE_QUICK(d);
1133 		} else
1134 			ret = EBADF;
1135 
1136 		PCM_GIANT_EXIT(d);
1137 
1138 		return (ret);
1139 	}
1140 
1141 	/*
1142 	 * Certain ioctls may be made on any type of device (audio, mixer,
1143 	 * and MIDI).  Handle those special cases here.
1144 	 */
1145 	if (IOCGROUP(cmd) == 'X') {
1146 		PCM_ACQUIRE_QUICK(d);
1147 		switch(cmd) {
1148 		case SNDCTL_SYSINFO:
1149 			sound_oss_sysinfo((oss_sysinfo *)arg);
1150 			break;
1151 		case SNDCTL_CARDINFO:
1152 			ret = sound_oss_card_info((oss_card_info *)arg);
1153 			break;
1154 		case SNDCTL_AUDIOINFO:
1155 		case SNDCTL_AUDIOINFO_EX:
1156 		case SNDCTL_ENGINEINFO:
1157 			ret = dsp_oss_audioinfo(i_dev, (oss_audioinfo *)arg);
1158 			break;
1159 		case SNDCTL_MIXERINFO:
1160 			ret = mixer_oss_mixerinfo(i_dev, (oss_mixerinfo *)arg);
1161 			break;
1162 		default:
1163 			ret = EINVAL;
1164 		}
1165 		PCM_RELEASE_QUICK(d);
1166 		PCM_GIANT_EXIT(d);
1167 		return (ret);
1168 	}
1169 
1170 	getchns(i_dev, &rdch, &wrch, 0);
1171 
1172 	if (wrch != NULL && (wrch->flags & CHN_F_DEAD))
1173 		wrch = NULL;
1174 	if (rdch != NULL && (rdch->flags & CHN_F_DEAD))
1175 		rdch = NULL;
1176 
1177 	if (wrch == NULL && rdch == NULL) {
1178 		PCM_GIANT_EXIT(d);
1179 		return (EINVAL);
1180 	}
1181 
1182     	switch(cmd) {
1183 #ifdef OLDPCM_IOCTL
1184     	/*
1185      	 * we start with the new ioctl interface.
1186      	 */
1187     	case AIONWRITE:	/* how many bytes can write ? */
1188 		if (wrch) {
1189 			CHN_LOCK(wrch);
1190 /*
1191 		if (wrch && wrch->bufhard.dl)
1192 			while (chn_wrfeed(wrch) == 0);
1193 */
1194 			*arg_i = sndbuf_getfree(wrch->bufsoft);
1195 			CHN_UNLOCK(wrch);
1196 		} else {
1197 			*arg_i = 0;
1198 			ret = EINVAL;
1199 		}
1200 		break;
1201 
1202     	case AIOSSIZE:     /* set the current blocksize */
1203 		{
1204 	    		struct snd_size *p = (struct snd_size *)arg;
1205 
1206 			p->play_size = 0;
1207 			p->rec_size = 0;
1208 			PCM_ACQUIRE_QUICK(d);
1209 	    		if (wrch) {
1210 				CHN_LOCK(wrch);
1211 				chn_setblocksize(wrch, 2, p->play_size);
1212 				p->play_size = sndbuf_getblksz(wrch->bufsoft);
1213 				CHN_UNLOCK(wrch);
1214 			}
1215 	    		if (rdch) {
1216 				CHN_LOCK(rdch);
1217 				chn_setblocksize(rdch, 2, p->rec_size);
1218 				p->rec_size = sndbuf_getblksz(rdch->bufsoft);
1219 				CHN_UNLOCK(rdch);
1220 			}
1221 			PCM_RELEASE_QUICK(d);
1222 		}
1223 		break;
1224     	case AIOGSIZE:	/* get the current blocksize */
1225 		{
1226 	    		struct snd_size *p = (struct snd_size *)arg;
1227 
1228 	    		if (wrch) {
1229 				CHN_LOCK(wrch);
1230 				p->play_size = sndbuf_getblksz(wrch->bufsoft);
1231 				CHN_UNLOCK(wrch);
1232 			}
1233 	    		if (rdch) {
1234 				CHN_LOCK(rdch);
1235 				p->rec_size = sndbuf_getblksz(rdch->bufsoft);
1236 				CHN_UNLOCK(rdch);
1237 			}
1238 		}
1239 		break;
1240 
1241     	case AIOSFMT:
1242     	case AIOGFMT:
1243 		{
1244 	    		snd_chan_param *p = (snd_chan_param *)arg;
1245 
1246 			if (cmd == AIOSFMT &&
1247 			    ((p->play_format != 0 && p->play_rate == 0) ||
1248 			    (p->rec_format != 0 && p->rec_rate == 0))) {
1249 				ret = EINVAL;
1250 				break;
1251 			}
1252 			PCM_ACQUIRE_QUICK(d);
1253 	    		if (wrch) {
1254 				CHN_LOCK(wrch);
1255 				if (cmd == AIOSFMT && p->play_format != 0) {
1256 					chn_setformat(wrch,
1257 					    SND_FORMAT(p->play_format,
1258 					    AFMT_CHANNEL(wrch->format),
1259 					    AFMT_EXTCHANNEL(wrch->format)));
1260 					chn_setspeed(wrch, p->play_rate);
1261 				}
1262 	    			p->play_rate = wrch->speed;
1263 	    			p->play_format = AFMT_ENCODING(wrch->format);
1264 				CHN_UNLOCK(wrch);
1265 			} else {
1266 	    			p->play_rate = 0;
1267 	    			p->play_format = 0;
1268 	    		}
1269 	    		if (rdch) {
1270 				CHN_LOCK(rdch);
1271 				if (cmd == AIOSFMT && p->rec_format != 0) {
1272 					chn_setformat(rdch,
1273 					    SND_FORMAT(p->rec_format,
1274 					    AFMT_CHANNEL(rdch->format),
1275 					    AFMT_EXTCHANNEL(rdch->format)));
1276 					chn_setspeed(rdch, p->rec_rate);
1277 				}
1278 				p->rec_rate = rdch->speed;
1279 				p->rec_format = AFMT_ENCODING(rdch->format);
1280 				CHN_UNLOCK(rdch);
1281 			} else {
1282 	    			p->rec_rate = 0;
1283 	    			p->rec_format = 0;
1284 	    		}
1285 			PCM_RELEASE_QUICK(d);
1286 		}
1287 		break;
1288 
1289     	case AIOGCAP:     /* get capabilities */
1290 		{
1291 	    		snd_capabilities *p = (snd_capabilities *)arg;
1292 			struct pcmchan_caps *pcaps = NULL, *rcaps = NULL;
1293 			struct cdev *pdev;
1294 
1295 			PCM_LOCK(d);
1296 			if (rdch) {
1297 				CHN_LOCK(rdch);
1298 				rcaps = chn_getcaps(rdch);
1299 			}
1300 			if (wrch) {
1301 				CHN_LOCK(wrch);
1302 				pcaps = chn_getcaps(wrch);
1303 			}
1304 	    		p->rate_min = max(rcaps? rcaps->minspeed : 0,
1305 	                      		  pcaps? pcaps->minspeed : 0);
1306 	    		p->rate_max = min(rcaps? rcaps->maxspeed : 1000000,
1307 	                      		  pcaps? pcaps->maxspeed : 1000000);
1308 	    		p->bufsize = min(rdch? sndbuf_getsize(rdch->bufsoft) : 1000000,
1309 	                     		 wrch? sndbuf_getsize(wrch->bufsoft) : 1000000);
1310 			/* XXX bad on sb16 */
1311 	    		p->formats = (rdch? chn_getformats(rdch) : 0xffffffff) &
1312 			 	     (wrch? chn_getformats(wrch) : 0xffffffff);
1313 			if (rdch && wrch)
1314 				p->formats |= (dsp_get_flags(i_dev) & SD_F_SIMPLEX)? 0 : AFMT_FULLDUPLEX;
1315 			pdev = d->mixer_dev;
1316 	    		p->mixers = 1; /* default: one mixer */
1317 	    		p->inputs = pdev->si_drv1? mix_getdevs(pdev->si_drv1) : 0;
1318 	    		p->left = p->right = 100;
1319 			if (wrch)
1320 				CHN_UNLOCK(wrch);
1321 			if (rdch)
1322 				CHN_UNLOCK(rdch);
1323 			PCM_UNLOCK(d);
1324 		}
1325 		break;
1326 
1327     	case AIOSTOP:
1328 		if (*arg_i == AIOSYNC_PLAY && wrch) {
1329 			CHN_LOCK(wrch);
1330 			*arg_i = chn_abort(wrch);
1331 			CHN_UNLOCK(wrch);
1332 		} else if (*arg_i == AIOSYNC_CAPTURE && rdch) {
1333 			CHN_LOCK(rdch);
1334 			*arg_i = chn_abort(rdch);
1335 			CHN_UNLOCK(rdch);
1336 		} else {
1337 	   	 	printf("AIOSTOP: bad channel 0x%x\n", *arg_i);
1338 	    		*arg_i = 0;
1339 		}
1340 		break;
1341 
1342     	case AIOSYNC:
1343 		printf("AIOSYNC chan 0x%03lx pos %lu unimplemented\n",
1344 	    		((snd_sync_parm *)arg)->chan, ((snd_sync_parm *)arg)->pos);
1345 		break;
1346 #endif
1347 	/*
1348 	 * here follow the standard ioctls (filio.h etc.)
1349 	 */
1350     	case FIONREAD: /* get # bytes to read */
1351 		if (rdch) {
1352 			CHN_LOCK(rdch);
1353 /*			if (rdch && rdch->bufhard.dl)
1354 				while (chn_rdfeed(rdch) == 0);
1355 */
1356 			*arg_i = sndbuf_getready(rdch->bufsoft);
1357 			CHN_UNLOCK(rdch);
1358 		} else {
1359 			*arg_i = 0;
1360 			ret = EINVAL;
1361 		}
1362 		break;
1363 
1364     	case FIOASYNC: /*set/clear async i/o */
1365 		DEB( printf("FIOASYNC\n") ; )
1366 		break;
1367 
1368     	case SNDCTL_DSP_NONBLOCK: /* set non-blocking i/o */
1369     	case FIONBIO: /* set/clear non-blocking i/o */
1370 		if (rdch) {
1371 			CHN_LOCK(rdch);
1372 			if (cmd == SNDCTL_DSP_NONBLOCK || *arg_i)
1373 				rdch->flags |= CHN_F_NBIO;
1374 			else
1375 				rdch->flags &= ~CHN_F_NBIO;
1376 			CHN_UNLOCK(rdch);
1377 		}
1378 		if (wrch) {
1379 			CHN_LOCK(wrch);
1380 			if (cmd == SNDCTL_DSP_NONBLOCK || *arg_i)
1381 				wrch->flags |= CHN_F_NBIO;
1382 			else
1383 				wrch->flags &= ~CHN_F_NBIO;
1384 			CHN_UNLOCK(wrch);
1385 		}
1386 		break;
1387 
1388     	/*
1389 	 * Finally, here is the linux-compatible ioctl interface
1390 	 */
1391 #define THE_REAL_SNDCTL_DSP_GETBLKSIZE _IOWR('P', 4, int)
1392     	case THE_REAL_SNDCTL_DSP_GETBLKSIZE:
1393     	case SNDCTL_DSP_GETBLKSIZE:
1394 		chn = wrch ? wrch : rdch;
1395 		if (chn) {
1396 			CHN_LOCK(chn);
1397 			*arg_i = sndbuf_getblksz(chn->bufsoft);
1398 			CHN_UNLOCK(chn);
1399 		} else {
1400 			*arg_i = 0;
1401 			ret = EINVAL;
1402 		}
1403 		break;
1404 
1405     	case SNDCTL_DSP_SETBLKSIZE:
1406 		RANGE(*arg_i, 16, 65536);
1407 		PCM_ACQUIRE_QUICK(d);
1408 		if (wrch) {
1409 			CHN_LOCK(wrch);
1410 			chn_setblocksize(wrch, 2, *arg_i);
1411 			CHN_UNLOCK(wrch);
1412 		}
1413 		if (rdch) {
1414 			CHN_LOCK(rdch);
1415 			chn_setblocksize(rdch, 2, *arg_i);
1416 			CHN_UNLOCK(rdch);
1417 		}
1418 		PCM_RELEASE_QUICK(d);
1419 		break;
1420 
1421     	case SNDCTL_DSP_RESET:
1422 		DEB(printf("dsp reset\n"));
1423 		if (wrch) {
1424 			CHN_LOCK(wrch);
1425 			chn_abort(wrch);
1426 			chn_resetbuf(wrch);
1427 			CHN_UNLOCK(wrch);
1428 		}
1429 		if (rdch) {
1430 			CHN_LOCK(rdch);
1431 			chn_abort(rdch);
1432 			chn_resetbuf(rdch);
1433 			CHN_UNLOCK(rdch);
1434 		}
1435 		break;
1436 
1437     	case SNDCTL_DSP_SYNC:
1438 		DEB(printf("dsp sync\n"));
1439 		/* chn_sync may sleep */
1440 		if (wrch) {
1441 			CHN_LOCK(wrch);
1442 			chn_sync(wrch, 0);
1443 			CHN_UNLOCK(wrch);
1444 		}
1445 		break;
1446 
1447     	case SNDCTL_DSP_SPEED:
1448 		/* chn_setspeed may sleep */
1449 		tmp = 0;
1450 		PCM_ACQUIRE_QUICK(d);
1451 		if (wrch) {
1452 			CHN_LOCK(wrch);
1453 			ret = chn_setspeed(wrch, *arg_i);
1454 			tmp = wrch->speed;
1455 			CHN_UNLOCK(wrch);
1456 		}
1457 		if (rdch && ret == 0) {
1458 			CHN_LOCK(rdch);
1459 			ret = chn_setspeed(rdch, *arg_i);
1460 			if (tmp == 0)
1461 				tmp = rdch->speed;
1462 			CHN_UNLOCK(rdch);
1463 		}
1464 		PCM_RELEASE_QUICK(d);
1465 		*arg_i = tmp;
1466 		break;
1467 
1468     	case SOUND_PCM_READ_RATE:
1469 		chn = wrch ? wrch : rdch;
1470 		if (chn) {
1471 			CHN_LOCK(chn);
1472 			*arg_i = chn->speed;
1473 			CHN_UNLOCK(chn);
1474 		} else {
1475 			*arg_i = 0;
1476 			ret = EINVAL;
1477 		}
1478 		break;
1479 
1480     	case SNDCTL_DSP_STEREO:
1481 		tmp = -1;
1482 		*arg_i = (*arg_i)? 2 : 1;
1483 		PCM_ACQUIRE_QUICK(d);
1484 		if (wrch) {
1485 			CHN_LOCK(wrch);
1486 			ret = chn_setformat(wrch,
1487 			    SND_FORMAT(wrch->format, *arg_i, 0));
1488 			tmp = (AFMT_CHANNEL(wrch->format) > 1)? 1 : 0;
1489 			CHN_UNLOCK(wrch);
1490 		}
1491 		if (rdch && ret == 0) {
1492 			CHN_LOCK(rdch);
1493 			ret = chn_setformat(rdch,
1494 			    SND_FORMAT(rdch->format, *arg_i, 0));
1495 			if (tmp == -1)
1496 				tmp = (AFMT_CHANNEL(rdch->format) > 1)? 1 : 0;
1497 			CHN_UNLOCK(rdch);
1498 		}
1499 		PCM_RELEASE_QUICK(d);
1500 		*arg_i = tmp;
1501 		break;
1502 
1503     	case SOUND_PCM_WRITE_CHANNELS:
1504 /*	case SNDCTL_DSP_CHANNELS: ( == SOUND_PCM_WRITE_CHANNELS) */
1505 		if (*arg_i < 0) {
1506 			*arg_i = 0;
1507 			ret = EINVAL;
1508 			break;
1509 		}
1510 		if (*arg_i != 0) {
1511 			struct pcmchan_matrix *m;
1512 			uint32_t ext;
1513 
1514 			tmp = 0;
1515 			if (*arg_i > SND_CHN_MAX)
1516 				*arg_i = SND_CHN_MAX;
1517 
1518 			m = feeder_matrix_default_channel_map(*arg_i);
1519 			if (m != NULL)
1520 				ext = m->ext;
1521 			else
1522 				ext = 0;
1523 
1524 			PCM_ACQUIRE_QUICK(d);
1525 	  		if (wrch) {
1526 				CHN_LOCK(wrch);
1527 				ret = chn_setformat(wrch,
1528 				    SND_FORMAT(wrch->format, *arg_i, ext));
1529 				tmp = AFMT_CHANNEL(wrch->format);
1530 				CHN_UNLOCK(wrch);
1531 			}
1532 			if (rdch && ret == 0) {
1533 				CHN_LOCK(rdch);
1534 				ret = chn_setformat(rdch,
1535 				    SND_FORMAT(rdch->format, *arg_i, ext));
1536 				if (tmp == 0)
1537 					tmp = AFMT_CHANNEL(rdch->format);
1538 				CHN_UNLOCK(rdch);
1539 			}
1540 			PCM_RELEASE_QUICK(d);
1541 			*arg_i = tmp;
1542 		} else {
1543 			chn = wrch ? wrch : rdch;
1544 			CHN_LOCK(chn);
1545 			*arg_i = AFMT_CHANNEL(chn->format);
1546 			CHN_UNLOCK(chn);
1547 		}
1548 		break;
1549 
1550     	case SOUND_PCM_READ_CHANNELS:
1551 		chn = wrch ? wrch : rdch;
1552 		if (chn) {
1553 			CHN_LOCK(chn);
1554 			*arg_i = AFMT_CHANNEL(chn->format);
1555 			CHN_UNLOCK(chn);
1556 		} else {
1557 			*arg_i = 0;
1558 			ret = EINVAL;
1559 		}
1560 		break;
1561 
1562     	case SNDCTL_DSP_GETFMTS:	/* returns a mask of supported fmts */
1563 		chn = wrch ? wrch : rdch;
1564 		if (chn) {
1565 			CHN_LOCK(chn);
1566 			*arg_i = chn_getformats(chn);
1567 			CHN_UNLOCK(chn);
1568 		} else {
1569 			*arg_i = 0;
1570 			ret = EINVAL;
1571 		}
1572 		break;
1573 
1574     	case SNDCTL_DSP_SETFMT:	/* sets _one_ format */
1575 		if (*arg_i != AFMT_QUERY) {
1576 			tmp = 0;
1577 			PCM_ACQUIRE_QUICK(d);
1578 			if (wrch) {
1579 				CHN_LOCK(wrch);
1580 				ret = chn_setformat(wrch, SND_FORMAT(*arg_i,
1581 				    AFMT_CHANNEL(wrch->format),
1582 				    AFMT_EXTCHANNEL(wrch->format)));
1583 				tmp = wrch->format;
1584 				CHN_UNLOCK(wrch);
1585 			}
1586 			if (rdch && ret == 0) {
1587 				CHN_LOCK(rdch);
1588 				ret = chn_setformat(rdch, SND_FORMAT(*arg_i,
1589 				    AFMT_CHANNEL(rdch->format),
1590 				    AFMT_EXTCHANNEL(rdch->format)));
1591 				if (tmp == 0)
1592 					tmp = rdch->format;
1593 				CHN_UNLOCK(rdch);
1594 			}
1595 			PCM_RELEASE_QUICK(d);
1596 			*arg_i = AFMT_ENCODING(tmp);
1597 		} else {
1598 			chn = wrch ? wrch : rdch;
1599 			CHN_LOCK(chn);
1600 			*arg_i = AFMT_ENCODING(chn->format);
1601 			CHN_UNLOCK(chn);
1602 		}
1603 		break;
1604 
1605     	case SNDCTL_DSP_SETFRAGMENT:
1606 		DEB(printf("SNDCTL_DSP_SETFRAGMENT 0x%08x\n", *(int *)arg));
1607 		{
1608 			uint32_t fragln = (*arg_i) & 0x0000ffff;
1609 			uint32_t maxfrags = ((*arg_i) & 0xffff0000) >> 16;
1610 			uint32_t fragsz;
1611 			uint32_t r_maxfrags, r_fragsz;
1612 
1613 			RANGE(fragln, 4, 16);
1614 			fragsz = 1 << fragln;
1615 
1616 			if (maxfrags == 0)
1617 				maxfrags = CHN_2NDBUFMAXSIZE / fragsz;
1618 			if (maxfrags < 2)
1619 				maxfrags = 2;
1620 			if (maxfrags * fragsz > CHN_2NDBUFMAXSIZE)
1621 				maxfrags = CHN_2NDBUFMAXSIZE / fragsz;
1622 
1623 			DEB(printf("SNDCTL_DSP_SETFRAGMENT %d frags, %d sz\n", maxfrags, fragsz));
1624 			PCM_ACQUIRE_QUICK(d);
1625 		    	if (rdch) {
1626 				CHN_LOCK(rdch);
1627 				ret = chn_setblocksize(rdch, maxfrags, fragsz);
1628 				r_maxfrags = sndbuf_getblkcnt(rdch->bufsoft);
1629 				r_fragsz = sndbuf_getblksz(rdch->bufsoft);
1630 				CHN_UNLOCK(rdch);
1631 			} else {
1632 				r_maxfrags = maxfrags;
1633 				r_fragsz = fragsz;
1634 			}
1635 		    	if (wrch && ret == 0) {
1636 				CHN_LOCK(wrch);
1637 				ret = chn_setblocksize(wrch, maxfrags, fragsz);
1638  				maxfrags = sndbuf_getblkcnt(wrch->bufsoft);
1639 				fragsz = sndbuf_getblksz(wrch->bufsoft);
1640 				CHN_UNLOCK(wrch);
1641 			} else { /* use whatever came from the read channel */
1642 				maxfrags = r_maxfrags;
1643 				fragsz = r_fragsz;
1644 			}
1645 			PCM_RELEASE_QUICK(d);
1646 
1647 			fragln = 0;
1648 			while (fragsz > 1) {
1649 				fragln++;
1650 				fragsz >>= 1;
1651 			}
1652 	    		*arg_i = (maxfrags << 16) | fragln;
1653 		}
1654 		break;
1655 
1656     	case SNDCTL_DSP_GETISPACE:
1657 		/* return the size of data available in the input queue */
1658 		{
1659 	    		audio_buf_info *a = (audio_buf_info *)arg;
1660 	    		if (rdch) {
1661 	        		struct snd_dbuf *bs = rdch->bufsoft;
1662 
1663 				CHN_LOCK(rdch);
1664 				a->bytes = sndbuf_getready(bs);
1665 	        		a->fragments = a->bytes / sndbuf_getblksz(bs);
1666 	        		a->fragstotal = sndbuf_getblkcnt(bs);
1667 	        		a->fragsize = sndbuf_getblksz(bs);
1668 				CHN_UNLOCK(rdch);
1669 	    		} else
1670 				ret = EINVAL;
1671 		}
1672 		break;
1673 
1674     	case SNDCTL_DSP_GETOSPACE:
1675 		/* return space available in the output queue */
1676 		{
1677 	    		audio_buf_info *a = (audio_buf_info *)arg;
1678 	    		if (wrch) {
1679 	        		struct snd_dbuf *bs = wrch->bufsoft;
1680 
1681 				CHN_LOCK(wrch);
1682 				/* XXX abusive DMA update: chn_wrupdate(wrch); */
1683 				a->bytes = sndbuf_getfree(bs);
1684 	        		a->fragments = a->bytes / sndbuf_getblksz(bs);
1685 	        		a->fragstotal = sndbuf_getblkcnt(bs);
1686 	        		a->fragsize = sndbuf_getblksz(bs);
1687 				CHN_UNLOCK(wrch);
1688 	    		} else
1689 				ret = EINVAL;
1690 		}
1691 		break;
1692 
1693     	case SNDCTL_DSP_GETIPTR:
1694 		{
1695 	    		count_info *a = (count_info *)arg;
1696 	    		if (rdch) {
1697 	        		struct snd_dbuf *bs = rdch->bufsoft;
1698 
1699 				CHN_LOCK(rdch);
1700 				/* XXX abusive DMA update: chn_rdupdate(rdch); */
1701 	        		a->bytes = sndbuf_gettotal(bs);
1702 	        		a->blocks = sndbuf_getblocks(bs) - rdch->blocks;
1703 	        		a->ptr = sndbuf_getfreeptr(bs);
1704 				rdch->blocks = sndbuf_getblocks(bs);
1705 				CHN_UNLOCK(rdch);
1706 	    		} else
1707 				ret = EINVAL;
1708 		}
1709 		break;
1710 
1711     	case SNDCTL_DSP_GETOPTR:
1712 		{
1713 	    		count_info *a = (count_info *)arg;
1714 	    		if (wrch) {
1715 	        		struct snd_dbuf *bs = wrch->bufsoft;
1716 
1717 				CHN_LOCK(wrch);
1718 				/* XXX abusive DMA update: chn_wrupdate(wrch); */
1719 	        		a->bytes = sndbuf_gettotal(bs);
1720 	        		a->blocks = sndbuf_getblocks(bs) - wrch->blocks;
1721 	        		a->ptr = sndbuf_getreadyptr(bs);
1722 				wrch->blocks = sndbuf_getblocks(bs);
1723 				CHN_UNLOCK(wrch);
1724 	    		} else
1725 				ret = EINVAL;
1726 		}
1727 		break;
1728 
1729     	case SNDCTL_DSP_GETCAPS:
1730 		PCM_LOCK(d);
1731 		*arg_i = PCM_CAP_REALTIME | PCM_CAP_MMAP | PCM_CAP_TRIGGER;
1732 		if (rdch && wrch && !(dsp_get_flags(i_dev) & SD_F_SIMPLEX))
1733 			*arg_i |= PCM_CAP_DUPLEX;
1734 		if (rdch && (rdch->flags & CHN_F_VIRTUAL) != 0)
1735 			*arg_i |= PCM_CAP_VIRTUAL;
1736 		if (wrch && (wrch->flags & CHN_F_VIRTUAL) != 0)
1737 			*arg_i |= PCM_CAP_VIRTUAL;
1738 		PCM_UNLOCK(d);
1739 		break;
1740 
1741     	case SOUND_PCM_READ_BITS:
1742 		chn = wrch ? wrch : rdch;
1743 		if (chn) {
1744 			CHN_LOCK(chn);
1745 			if (chn->format & AFMT_8BIT)
1746 				*arg_i = 8;
1747 			else if (chn->format & AFMT_16BIT)
1748 				*arg_i = 16;
1749 			else if (chn->format & AFMT_24BIT)
1750 				*arg_i = 24;
1751 			else if (chn->format & AFMT_32BIT)
1752 				*arg_i = 32;
1753 			else
1754 				ret = EINVAL;
1755 			CHN_UNLOCK(chn);
1756 		} else {
1757 			*arg_i = 0;
1758 			ret = EINVAL;
1759 		}
1760 		break;
1761 
1762     	case SNDCTL_DSP_SETTRIGGER:
1763 		if (rdch) {
1764 			CHN_LOCK(rdch);
1765 			rdch->flags &= ~CHN_F_NOTRIGGER;
1766 		    	if (*arg_i & PCM_ENABLE_INPUT)
1767 				chn_start(rdch, 1);
1768 			else {
1769 				chn_abort(rdch);
1770 				chn_resetbuf(rdch);
1771 				rdch->flags |= CHN_F_NOTRIGGER;
1772 			}
1773 			CHN_UNLOCK(rdch);
1774 		}
1775 		if (wrch) {
1776 			CHN_LOCK(wrch);
1777 			wrch->flags &= ~CHN_F_NOTRIGGER;
1778 		    	if (*arg_i & PCM_ENABLE_OUTPUT)
1779 				chn_start(wrch, 1);
1780 			else {
1781 				chn_abort(wrch);
1782 				chn_resetbuf(wrch);
1783 				wrch->flags |= CHN_F_NOTRIGGER;
1784 			}
1785 			CHN_UNLOCK(wrch);
1786 		}
1787 		break;
1788 
1789     	case SNDCTL_DSP_GETTRIGGER:
1790 		*arg_i = 0;
1791 		if (wrch) {
1792 			CHN_LOCK(wrch);
1793 			if (wrch->flags & CHN_F_TRIGGERED)
1794 				*arg_i |= PCM_ENABLE_OUTPUT;
1795 			CHN_UNLOCK(wrch);
1796 		}
1797 		if (rdch) {
1798 			CHN_LOCK(rdch);
1799 			if (rdch->flags & CHN_F_TRIGGERED)
1800 				*arg_i |= PCM_ENABLE_INPUT;
1801 			CHN_UNLOCK(rdch);
1802 		}
1803 		break;
1804 
1805 	case SNDCTL_DSP_GETODELAY:
1806 		if (wrch) {
1807 	        	struct snd_dbuf *bs = wrch->bufsoft;
1808 
1809 			CHN_LOCK(wrch);
1810 			/* XXX abusive DMA update: chn_wrupdate(wrch); */
1811 			*arg_i = sndbuf_getready(bs);
1812 			CHN_UNLOCK(wrch);
1813 		} else
1814 			ret = EINVAL;
1815 		break;
1816 
1817     	case SNDCTL_DSP_POST:
1818 		if (wrch) {
1819 			CHN_LOCK(wrch);
1820 			wrch->flags &= ~CHN_F_NOTRIGGER;
1821 			chn_start(wrch, 1);
1822 			CHN_UNLOCK(wrch);
1823 		}
1824 		break;
1825 
1826 	case SNDCTL_DSP_SETDUPLEX:
1827 		/*
1828 		 * switch to full-duplex mode if card is in half-duplex
1829 		 * mode and is able to work in full-duplex mode
1830 		 */
1831 		PCM_LOCK(d);
1832 		if (rdch && wrch && (dsp_get_flags(i_dev) & SD_F_SIMPLEX))
1833 			dsp_set_flags(i_dev, dsp_get_flags(i_dev)^SD_F_SIMPLEX);
1834 		PCM_UNLOCK(d);
1835 		break;
1836 
1837 	/*
1838 	 * The following four ioctls are simple wrappers around mixer_ioctl
1839 	 * with no further processing.  xcmd is short for "translated
1840 	 * command".
1841 	 */
1842 	case SNDCTL_DSP_GETRECVOL:
1843 		if (xcmd == 0) {
1844 			xcmd = SOUND_MIXER_READ_RECLEV;
1845 			chn = rdch;
1846 		}
1847 		/* FALLTHROUGH */
1848 	case SNDCTL_DSP_SETRECVOL:
1849 		if (xcmd == 0) {
1850 			xcmd = SOUND_MIXER_WRITE_RECLEV;
1851 			chn = rdch;
1852 		}
1853 		/* FALLTHROUGH */
1854 	case SNDCTL_DSP_GETPLAYVOL:
1855 		if (xcmd == 0) {
1856 			xcmd = SOUND_MIXER_READ_PCM;
1857 			chn = wrch;
1858 		}
1859 		/* FALLTHROUGH */
1860 	case SNDCTL_DSP_SETPLAYVOL:
1861 		if (xcmd == 0) {
1862 			xcmd = SOUND_MIXER_WRITE_PCM;
1863 			chn = wrch;
1864 		}
1865 
1866 		ret = dsp_ioctl_channel(i_dev, chn, xcmd, arg);
1867 		if (ret != -1) {
1868 			PCM_GIANT_EXIT(d);
1869 			return (ret);
1870 		}
1871 
1872 		if (d->mixer_dev != NULL) {
1873 			PCM_ACQUIRE_QUICK(d);
1874 			ret = mixer_ioctl_cmd(d->mixer_dev, xcmd, arg, -1, td,
1875 			    MIXER_CMD_DIRECT);
1876 			PCM_RELEASE_QUICK(d);
1877 		} else
1878 			ret = ENOTSUP;
1879 
1880 		break;
1881 
1882 	case SNDCTL_DSP_GET_RECSRC_NAMES:
1883 	case SNDCTL_DSP_GET_RECSRC:
1884 	case SNDCTL_DSP_SET_RECSRC:
1885 		if (d->mixer_dev != NULL) {
1886 			PCM_ACQUIRE_QUICK(d);
1887 			ret = mixer_ioctl_cmd(d->mixer_dev, cmd, arg, -1, td,
1888 			    MIXER_CMD_DIRECT);
1889 			PCM_RELEASE_QUICK(d);
1890 		} else
1891 			ret = ENOTSUP;
1892 		break;
1893 
1894 	/*
1895 	 * The following 3 ioctls aren't very useful at the moment.  For
1896 	 * now, only a single channel is associated with a cdev (/dev/dspN
1897 	 * instance), so there's only a single output routing to use (i.e.,
1898 	 * the wrch bound to this cdev).
1899 	 */
1900 	case SNDCTL_DSP_GET_PLAYTGT_NAMES:
1901 		{
1902 			oss_mixer_enuminfo *ei;
1903 			ei = (oss_mixer_enuminfo *)arg;
1904 			ei->dev = 0;
1905 			ei->ctrl = 0;
1906 			ei->version = 0; /* static for now */
1907 			ei->strindex[0] = 0;
1908 
1909 			if (wrch != NULL) {
1910 				ei->nvalues = 1;
1911 				strlcpy(ei->strings, wrch->name,
1912 					sizeof(ei->strings));
1913 			} else {
1914 				ei->nvalues = 0;
1915 				ei->strings[0] = '\0';
1916 			}
1917 		}
1918 		break;
1919 	case SNDCTL_DSP_GET_PLAYTGT:
1920 	case SNDCTL_DSP_SET_PLAYTGT:	/* yes, they are the same for now */
1921 		/*
1922 		 * Re: SET_PLAYTGT
1923 		 *   OSSv4: "The value that was accepted by the device will
1924 		 *   be returned back in the variable pointed by the
1925 		 *   argument."
1926 		 */
1927 		if (wrch != NULL)
1928 			*arg_i = 0;
1929 		else
1930 			ret = EINVAL;
1931 		break;
1932 
1933 	case SNDCTL_DSP_SILENCE:
1934 	/*
1935 	 * Flush the software (pre-feed) buffer, but try to minimize playback
1936 	 * interruption.  (I.e., record unplayed samples with intent to
1937 	 * restore by SNDCTL_DSP_SKIP.) Intended for application "pause"
1938 	 * functionality.
1939 	 */
1940 		if (wrch == NULL)
1941 			ret = EINVAL;
1942 		else {
1943 			struct snd_dbuf *bs;
1944 			CHN_LOCK(wrch);
1945 			while (wrch->inprog != 0)
1946 				cv_wait(&wrch->cv, wrch->lock);
1947 			bs = wrch->bufsoft;
1948 			if ((bs->shadbuf != NULL) && (sndbuf_getready(bs) > 0)) {
1949 				bs->sl = sndbuf_getready(bs);
1950 				sndbuf_dispose(bs, bs->shadbuf, sndbuf_getready(bs));
1951 				sndbuf_fillsilence(bs);
1952 				chn_start(wrch, 0);
1953 			}
1954 			CHN_UNLOCK(wrch);
1955 		}
1956 		break;
1957 
1958 	case SNDCTL_DSP_SKIP:
1959 	/*
1960 	 * OSSv4 docs: "This ioctl call discards all unplayed samples in the
1961 	 * playback buffer by moving the current write position immediately
1962 	 * before the point where the device is currently reading the samples."
1963 	 */
1964 		if (wrch == NULL)
1965 			ret = EINVAL;
1966 		else {
1967 			struct snd_dbuf *bs;
1968 			CHN_LOCK(wrch);
1969 			while (wrch->inprog != 0)
1970 				cv_wait(&wrch->cv, wrch->lock);
1971 			bs = wrch->bufsoft;
1972 			if ((bs->shadbuf != NULL) && (bs->sl > 0)) {
1973 				sndbuf_softreset(bs);
1974 				sndbuf_acquire(bs, bs->shadbuf, bs->sl);
1975 				bs->sl = 0;
1976 				chn_start(wrch, 0);
1977 			}
1978 			CHN_UNLOCK(wrch);
1979 		}
1980 		break;
1981 
1982 	case SNDCTL_DSP_CURRENT_OPTR:
1983 	case SNDCTL_DSP_CURRENT_IPTR:
1984 	/**
1985 	 * @note Changing formats resets the buffer counters, which differs
1986 	 * 	 from the 4Front drivers.  However, I don't expect this to be
1987 	 * 	 much of a problem.
1988 	 *
1989 	 * @note In a test where @c CURRENT_OPTR is called immediately after write
1990 	 * 	 returns, this driver is about 32K samples behind whereas
1991 	 * 	 4Front's is about 8K samples behind.  Should determine source
1992 	 * 	 of discrepancy, even if only out of curiosity.
1993 	 *
1994 	 * @todo Actually test SNDCTL_DSP_CURRENT_IPTR.
1995 	 */
1996 		chn = (cmd == SNDCTL_DSP_CURRENT_OPTR) ? wrch : rdch;
1997 		if (chn == NULL)
1998 			ret = EINVAL;
1999 		else {
2000 			struct snd_dbuf *bs;
2001 			/* int tmp; */
2002 
2003 			oss_count_t *oc = (oss_count_t *)arg;
2004 
2005 			CHN_LOCK(chn);
2006 			bs = chn->bufsoft;
2007 #if 0
2008 			tmp = (sndbuf_getsize(b) + chn_getptr(chn) - sndbuf_gethwptr(b)) % sndbuf_getsize(b);
2009 			oc->samples = (sndbuf_gettotal(b) + tmp) / sndbuf_getalign(b);
2010 			oc->fifo_samples = (sndbuf_getready(b) - tmp) / sndbuf_getalign(b);
2011 #else
2012 			oc->samples = sndbuf_gettotal(bs) / sndbuf_getalign(bs);
2013 			oc->fifo_samples = sndbuf_getready(bs) / sndbuf_getalign(bs);
2014 #endif
2015 			CHN_UNLOCK(chn);
2016 		}
2017 		break;
2018 
2019 	case SNDCTL_DSP_HALT_OUTPUT:
2020 	case SNDCTL_DSP_HALT_INPUT:
2021 		chn = (cmd == SNDCTL_DSP_HALT_OUTPUT) ? wrch : rdch;
2022 		if (chn == NULL)
2023 			ret = EINVAL;
2024 		else {
2025 			CHN_LOCK(chn);
2026 			chn_abort(chn);
2027 			CHN_UNLOCK(chn);
2028 		}
2029 		break;
2030 
2031 	case SNDCTL_DSP_LOW_WATER:
2032 	/*
2033 	 * Set the number of bytes required to attract attention by
2034 	 * select/poll.
2035 	 */
2036 		if (wrch != NULL) {
2037 			CHN_LOCK(wrch);
2038 			wrch->lw = (*arg_i > 1) ? *arg_i : 1;
2039 			CHN_UNLOCK(wrch);
2040 		}
2041 		if (rdch != NULL) {
2042 			CHN_LOCK(rdch);
2043 			rdch->lw = (*arg_i > 1) ? *arg_i : 1;
2044 			CHN_UNLOCK(rdch);
2045 		}
2046 		break;
2047 
2048 	case SNDCTL_DSP_GETERROR:
2049 	/*
2050 	 * OSSv4 docs:  "All errors and counters will automatically be
2051 	 * cleared to zeroes after the call so each call will return only
2052 	 * the errors that occurred after the previous invocation. ... The
2053 	 * play_underruns and rec_overrun fields are the only useful fields
2054 	 * returned by OSS 4.0."
2055 	 */
2056 		{
2057 			audio_errinfo *ei = (audio_errinfo *)arg;
2058 
2059 			bzero((void *)ei, sizeof(*ei));
2060 
2061 			if (wrch != NULL) {
2062 				CHN_LOCK(wrch);
2063 				ei->play_underruns = wrch->xruns;
2064 				wrch->xruns = 0;
2065 				CHN_UNLOCK(wrch);
2066 			}
2067 			if (rdch != NULL) {
2068 				CHN_LOCK(rdch);
2069 				ei->rec_overruns = rdch->xruns;
2070 				rdch->xruns = 0;
2071 				CHN_UNLOCK(rdch);
2072 			}
2073 		}
2074 		break;
2075 
2076 	case SNDCTL_DSP_SYNCGROUP:
2077 		PCM_ACQUIRE_QUICK(d);
2078 		ret = dsp_oss_syncgroup(wrch, rdch, (oss_syncgroup *)arg);
2079 		PCM_RELEASE_QUICK(d);
2080 		break;
2081 
2082 	case SNDCTL_DSP_SYNCSTART:
2083 		PCM_ACQUIRE_QUICK(d);
2084 		ret = dsp_oss_syncstart(*arg_i);
2085 		PCM_RELEASE_QUICK(d);
2086 		break;
2087 
2088 	case SNDCTL_DSP_POLICY:
2089 		PCM_ACQUIRE_QUICK(d);
2090 		ret = dsp_oss_policy(wrch, rdch, *arg_i);
2091 		PCM_RELEASE_QUICK(d);
2092 		break;
2093 
2094 	case SNDCTL_DSP_COOKEDMODE:
2095 		PCM_ACQUIRE_QUICK(d);
2096 		if (!(dsp_get_flags(i_dev) & SD_F_BITPERFECT))
2097 			ret = dsp_oss_cookedmode(wrch, rdch, *arg_i);
2098 		PCM_RELEASE_QUICK(d);
2099 		break;
2100 	case SNDCTL_DSP_GET_CHNORDER:
2101 		PCM_ACQUIRE_QUICK(d);
2102 		ret = dsp_oss_getchnorder(wrch, rdch, (unsigned long long *)arg);
2103 		PCM_RELEASE_QUICK(d);
2104 		break;
2105 	case SNDCTL_DSP_SET_CHNORDER:
2106 		PCM_ACQUIRE_QUICK(d);
2107 		ret = dsp_oss_setchnorder(wrch, rdch, (unsigned long long *)arg);
2108 		PCM_RELEASE_QUICK(d);
2109 		break;
2110 	case SNDCTL_DSP_GETCHANNELMASK:		/* XXX vlc */
2111 		PCM_ACQUIRE_QUICK(d);
2112 		ret = dsp_oss_getchannelmask(wrch, rdch, (int *)arg);
2113 		PCM_RELEASE_QUICK(d);
2114 		break;
2115 	case SNDCTL_DSP_BIND_CHANNEL:		/* XXX what?!? */
2116 		ret = EINVAL;
2117 		break;
2118 #ifdef	OSSV4_EXPERIMENT
2119 	/*
2120 	 * XXX The following ioctls are not yet supported and just return
2121 	 * EINVAL.
2122 	 */
2123 	case SNDCTL_DSP_GETOPEAKS:
2124 	case SNDCTL_DSP_GETIPEAKS:
2125 		chn = (cmd == SNDCTL_DSP_GETOPEAKS) ? wrch : rdch;
2126 		if (chn == NULL)
2127 			ret = EINVAL;
2128 		else {
2129 			oss_peaks_t *op = (oss_peaks_t *)arg;
2130 			int lpeak, rpeak;
2131 
2132 			CHN_LOCK(chn);
2133 			ret = chn_getpeaks(chn, &lpeak, &rpeak);
2134 			if (ret == -1)
2135 				ret = EINVAL;
2136 			else {
2137 				(*op)[0] = lpeak;
2138 				(*op)[1] = rpeak;
2139 			}
2140 			CHN_UNLOCK(chn);
2141 		}
2142 		break;
2143 
2144 	/*
2145 	 * XXX Once implemented, revisit this for proper cv protection
2146 	 *     (if necessary).
2147 	 */
2148 	case SNDCTL_GETLABEL:
2149 		ret = dsp_oss_getlabel(wrch, rdch, (oss_label_t *)arg);
2150 		break;
2151 	case SNDCTL_SETLABEL:
2152 		ret = dsp_oss_setlabel(wrch, rdch, (oss_label_t *)arg);
2153 		break;
2154 	case SNDCTL_GETSONG:
2155 		ret = dsp_oss_getsong(wrch, rdch, (oss_longname_t *)arg);
2156 		break;
2157 	case SNDCTL_SETSONG:
2158 		ret = dsp_oss_setsong(wrch, rdch, (oss_longname_t *)arg);
2159 		break;
2160 	case SNDCTL_SETNAME:
2161 		ret = dsp_oss_setname(wrch, rdch, (oss_longname_t *)arg);
2162 		break;
2163 #if 0
2164 	/**
2165 	 * @note The S/PDIF interface ioctls, @c SNDCTL_DSP_READCTL and
2166 	 * @c SNDCTL_DSP_WRITECTL have been omitted at the suggestion of
2167 	 * 4Front Technologies.
2168 	 */
2169 	case SNDCTL_DSP_READCTL:
2170 	case SNDCTL_DSP_WRITECTL:
2171 		ret = EINVAL;
2172 		break;
2173 #endif	/* !0 (explicitly omitted ioctls) */
2174 
2175 #endif	/* !OSSV4_EXPERIMENT */
2176     	case SNDCTL_DSP_MAPINBUF:
2177     	case SNDCTL_DSP_MAPOUTBUF:
2178     	case SNDCTL_DSP_SETSYNCRO:
2179 		/* undocumented */
2180 
2181     	case SNDCTL_DSP_SUBDIVIDE:
2182     	case SOUND_PCM_WRITE_FILTER:
2183     	case SOUND_PCM_READ_FILTER:
2184 		/* dunno what these do, don't sound important */
2185 
2186     	default:
2187 		DEB(printf("default ioctl fn 0x%08lx fail\n", cmd));
2188 		ret = EINVAL;
2189 		break;
2190     	}
2191 
2192 	PCM_GIANT_LEAVE(d);
2193 
2194     	return (ret);
2195 }
2196 
2197 static int
2198 dsp_poll(struct cdev *i_dev, int events, struct thread *td)
2199 {
2200 	struct snddev_info *d;
2201 	struct pcm_channel *wrch, *rdch;
2202 	int ret, e;
2203 
2204 	d = dsp_get_info(i_dev);
2205 	if (PCM_DETACHING(d) || !DSP_REGISTERED(d, i_dev)) {
2206 		/* XXX many clients don't understand POLLNVAL */
2207 		return (events & (POLLHUP | POLLPRI | POLLIN |
2208 		    POLLRDNORM | POLLOUT | POLLWRNORM));
2209 	}
2210 	PCM_GIANT_ENTER(d);
2211 
2212 	wrch = NULL;
2213 	rdch = NULL;
2214 	ret = 0;
2215 
2216 	getchns(i_dev, &rdch, &wrch, SD_F_PRIO_RD | SD_F_PRIO_WR);
2217 
2218 	if (wrch != NULL && !(wrch->flags & CHN_F_DEAD)) {
2219 		e = (events & (POLLOUT | POLLWRNORM));
2220 		if (e)
2221 			ret |= chn_poll(wrch, e, td);
2222 	}
2223 
2224 	if (rdch != NULL && !(rdch->flags & CHN_F_DEAD)) {
2225 		e = (events & (POLLIN | POLLRDNORM));
2226 		if (e)
2227 			ret |= chn_poll(rdch, e, td);
2228 	}
2229 
2230 	relchns(i_dev, rdch, wrch, SD_F_PRIO_RD | SD_F_PRIO_WR);
2231 
2232 	PCM_GIANT_LEAVE(d);
2233 
2234 	return (ret);
2235 }
2236 
2237 static int
2238 dsp_mmap(struct cdev *i_dev, vm_ooffset_t offset, vm_paddr_t *paddr,
2239     int nprot, vm_memattr_t *memattr)
2240 {
2241 
2242 	/*
2243 	 * offset is in range due to checks in dsp_mmap_single().
2244 	 * XXX memattr is not honored.
2245 	 */
2246 	*paddr = vtophys(offset);
2247 	return (0);
2248 }
2249 
2250 static int
2251 dsp_mmap_single(struct cdev *i_dev, vm_ooffset_t *offset,
2252     vm_size_t size, struct vm_object **object, int nprot)
2253 {
2254 	struct snddev_info *d;
2255 	struct pcm_channel *wrch, *rdch, *c;
2256 
2257 	/*
2258 	 * Reject PROT_EXEC by default. It just doesn't makes sense.
2259 	 * Unfortunately, we have to give up this one due to linux_mmap
2260 	 * changes.
2261 	 *
2262 	 * https://lists.freebsd.org/pipermail/freebsd-emulation/2007-June/003698.html
2263 	 *
2264 	 */
2265 #ifdef SV_ABI_LINUX
2266 	if ((nprot & PROT_EXEC) && (dsp_mmap_allow_prot_exec < 0 ||
2267 	    (dsp_mmap_allow_prot_exec == 0 &&
2268 	    SV_CURPROC_ABI() != SV_ABI_LINUX)))
2269 #else
2270 	if ((nprot & PROT_EXEC) && dsp_mmap_allow_prot_exec < 1)
2271 #endif
2272 		return (EINVAL);
2273 
2274 	/*
2275 	 * PROT_READ (alone) selects the input buffer.
2276 	 * PROT_WRITE (alone) selects the output buffer.
2277 	 * PROT_WRITE|PROT_READ together select the output buffer.
2278 	 */
2279 	if ((nprot & (PROT_READ | PROT_WRITE)) == 0)
2280 		return (EINVAL);
2281 
2282 	d = dsp_get_info(i_dev);
2283 	if (PCM_DETACHING(d) || !DSP_REGISTERED(d, i_dev))
2284 		return (EINVAL);
2285 
2286 	PCM_GIANT_ENTER(d);
2287 
2288 	getchns(i_dev, &rdch, &wrch, SD_F_PRIO_RD | SD_F_PRIO_WR);
2289 
2290 	c = ((nprot & PROT_WRITE) != 0) ? wrch : rdch;
2291 	if (c == NULL || (c->flags & CHN_F_MMAP_INVALID) ||
2292 	    (*offset  + size) > sndbuf_getallocsize(c->bufsoft) ||
2293 	    (wrch != NULL && (wrch->flags & CHN_F_MMAP_INVALID)) ||
2294 	    (rdch != NULL && (rdch->flags & CHN_F_MMAP_INVALID))) {
2295 		relchns(i_dev, rdch, wrch, SD_F_PRIO_RD | SD_F_PRIO_WR);
2296 		PCM_GIANT_EXIT(d);
2297 		return (EINVAL);
2298 	}
2299 
2300 	if (wrch != NULL)
2301 		wrch->flags |= CHN_F_MMAP;
2302 	if (rdch != NULL)
2303 		rdch->flags |= CHN_F_MMAP;
2304 
2305 	*offset = (uintptr_t)sndbuf_getbufofs(c->bufsoft, *offset);
2306 	relchns(i_dev, rdch, wrch, SD_F_PRIO_RD | SD_F_PRIO_WR);
2307 	*object = vm_pager_allocate(OBJT_DEVICE, i_dev,
2308 	    size, nprot, *offset, curthread->td_ucred);
2309 
2310 	PCM_GIANT_LEAVE(d);
2311 
2312 	if (*object == NULL)
2313 		 return (EINVAL);
2314 	return (0);
2315 }
2316 
2317 /* So much for dev_stdclone() */
2318 static int
2319 dsp_stdclone(char *name, char *namep, char *sep, int use_sep, int *u, int *c)
2320 {
2321 	size_t len;
2322 
2323 	len = strlen(namep);
2324 	if (strncmp(name, namep, len) != 0)
2325 		return (ENODEV);
2326 
2327 	name += len;
2328 
2329 	if (isdigit(*name) == 0)
2330 		return (ENODEV);
2331 
2332 	len = strlen(sep);
2333 
2334 	if (*name == '0' && !(name[1] == '\0' || bcmp(name + 1, sep, len) == 0))
2335 		return (ENODEV);
2336 
2337 	for (*u = 0; isdigit(*name) != 0; name++) {
2338 		*u *= 10;
2339 		*u += *name - '0';
2340 		if (*u > dsp_umax)
2341 			return (ENODEV);
2342 	}
2343 
2344 	if (*name == '\0')
2345 		return ((use_sep == 0) ? 0 : ENODEV);
2346 
2347 	if (bcmp(name, sep, len) != 0 || isdigit(name[len]) == 0)
2348 		return (ENODEV);
2349 
2350 	name += len;
2351 
2352 	if (*name == '0' && name[1] != '\0')
2353 		return (ENODEV);
2354 
2355 	for (*c = 0; isdigit(*name) != 0; name++) {
2356 		*c *= 10;
2357 		*c += *name - '0';
2358 		if (*c > dsp_cmax)
2359 			return (ENODEV);
2360 	}
2361 
2362 	if (*name != '\0')
2363 		return (ENODEV);
2364 
2365 	return (0);
2366 }
2367 
2368 static void
2369 dsp_clone(void *arg,
2370     struct ucred *cred,
2371     char *name, int namelen, struct cdev **dev)
2372 {
2373 	struct snddev_info *d;
2374 	struct snd_clone_entry *ce;
2375 	struct pcm_channel *c;
2376 	int i, unit, udcmask, cunit, devtype, devhw, devcmax, tumax;
2377 	char *devname, *devcmp, *devsep;
2378 
2379 	KASSERT(dsp_umax >= 0 && dsp_cmax >= 0, ("Uninitialized unit!"));
2380 
2381 	if (*dev != NULL)
2382 		return;
2383 
2384 	unit = -1;
2385 	cunit = -1;
2386 	devtype = -1;
2387 	devhw = 0;
2388 	devcmax = -1;
2389 	tumax = -1;
2390 	devname = NULL;
2391 	devsep = NULL;
2392 
2393 	for (i = 0; unit == -1 &&
2394 	    i < (sizeof(dsp_cdevs) / sizeof(dsp_cdevs[0])); i++) {
2395 		devtype = dsp_cdevs[i].type;
2396 		devcmp = dsp_cdevs[i].name;
2397 		devsep = dsp_cdevs[i].sep;
2398 		devname = dsp_cdevs[i].alias;
2399 		if (devname == NULL)
2400 			devname = devcmp;
2401 		devhw = dsp_cdevs[i].hw;
2402 		devcmax = dsp_cdevs[i].max - 1;
2403 		if (strcmp(name, devcmp) == 0) {
2404 			if (dsp_basename_clone != 0)
2405 				unit = snd_unit;
2406 		} else if (dsp_stdclone(name, devcmp, devsep,
2407 		    dsp_cdevs[i].use_sep, &unit, &cunit) != 0) {
2408 			unit = -1;
2409 			cunit = -1;
2410 		}
2411 	}
2412 
2413 	d = devclass_get_softc(pcm_devclass, unit);
2414 	if (!PCM_REGISTERED(d) || d->clones == NULL)
2415 		return;
2416 
2417 	/* XXX Need Giant magic entry ??? */
2418 
2419 	PCM_LOCK(d);
2420 	if (snd_clone_disabled(d->clones)) {
2421 		PCM_UNLOCK(d);
2422 		return;
2423 	}
2424 
2425 	PCM_WAIT(d);
2426 	PCM_ACQUIRE(d);
2427 	PCM_UNLOCK(d);
2428 
2429 	udcmask = snd_u2unit(unit) | snd_d2unit(devtype);
2430 
2431 	if (devhw != 0) {
2432 		KASSERT(devcmax <= dsp_cmax,
2433 		    ("overflow: devcmax=%d, dsp_cmax=%d", devcmax, dsp_cmax));
2434 		if (cunit > devcmax) {
2435 			PCM_RELEASE_QUICK(d);
2436 			return;
2437 		}
2438 		udcmask |= snd_c2unit(cunit);
2439 		CHN_FOREACH(c, d, channels.pcm) {
2440 			CHN_LOCK(c);
2441 			if (c->unit != udcmask) {
2442 				CHN_UNLOCK(c);
2443 				continue;
2444 			}
2445 			CHN_UNLOCK(c);
2446 			udcmask &= ~snd_c2unit(cunit);
2447 			/*
2448 			 * Temporarily increase clone maxunit to overcome
2449 			 * vchan flexibility.
2450 			 *
2451 			 * # sysctl dev.pcm.0.play.vchans=256
2452 			 * dev.pcm.0.play.vchans: 1 -> 256
2453 			 * # cat /dev/zero > /dev/dsp0.vp255 &
2454 			 * [1] 17296
2455 			 * # sysctl dev.pcm.0.play.vchans=0
2456 			 * dev.pcm.0.play.vchans: 256 -> 1
2457 			 * # fg
2458 			 * [1]  + running    cat /dev/zero > /dev/dsp0.vp255
2459 			 * ^C
2460 			 * # cat /dev/zero > /dev/dsp0.vp255
2461 			 * zsh: operation not supported: /dev/dsp0.vp255
2462 			 */
2463 			tumax = snd_clone_getmaxunit(d->clones);
2464 			if (cunit > tumax)
2465 				snd_clone_setmaxunit(d->clones, cunit);
2466 			else
2467 				tumax = -1;
2468 			goto dsp_clone_alloc;
2469 		}
2470 		/*
2471 		 * Ok, so we're requesting unallocated vchan, but still
2472 		 * within maximum vchan limit.
2473 		 */
2474 		if (((devtype == SND_DEV_DSPHW_VPLAY && d->pvchancount > 0) ||
2475 		    (devtype == SND_DEV_DSPHW_VREC && d->rvchancount > 0)) &&
2476 		    cunit < snd_maxautovchans) {
2477 			udcmask &= ~snd_c2unit(cunit);
2478 			tumax = snd_clone_getmaxunit(d->clones);
2479 			if (cunit > tumax)
2480 				snd_clone_setmaxunit(d->clones, cunit);
2481 			else
2482 				tumax = -1;
2483 			goto dsp_clone_alloc;
2484 		}
2485 		PCM_RELEASE_QUICK(d);
2486 		return;
2487 	}
2488 
2489 dsp_clone_alloc:
2490 	ce = snd_clone_alloc(d->clones, dev, &cunit, udcmask);
2491 	if (tumax != -1)
2492 		snd_clone_setmaxunit(d->clones, tumax);
2493 	if (ce != NULL) {
2494 		udcmask |= snd_c2unit(cunit);
2495 		*dev = make_dev(&dsp_cdevsw, PCMMINOR(udcmask),
2496 		    UID_ROOT, GID_WHEEL, 0666, "%s%d%s%d",
2497 		    devname, unit, devsep, cunit);
2498 		snd_clone_register(ce, *dev);
2499 	}
2500 
2501 	PCM_RELEASE_QUICK(d);
2502 
2503 	if (*dev != NULL)
2504 		dev_ref(*dev);
2505 }
2506 
2507 static void
2508 dsp_sysinit(void *p)
2509 {
2510 	if (dsp_ehtag != NULL)
2511 		return;
2512 	/* initialize unit numbering */
2513 	snd_unit_init();
2514 	dsp_umax = PCMMAXUNIT;
2515 	dsp_cmax = PCMMAXCHAN;
2516 	dsp_ehtag = EVENTHANDLER_REGISTER(dev_clone, dsp_clone, 0, 1000);
2517 }
2518 
2519 static void
2520 dsp_sysuninit(void *p)
2521 {
2522 	if (dsp_ehtag == NULL)
2523 		return;
2524 	EVENTHANDLER_DEREGISTER(dev_clone, dsp_ehtag);
2525 	dsp_ehtag = NULL;
2526 }
2527 
2528 SYSINIT(dsp_sysinit, SI_SUB_DRIVERS, SI_ORDER_MIDDLE, dsp_sysinit, NULL);
2529 SYSUNINIT(dsp_sysuninit, SI_SUB_DRIVERS, SI_ORDER_MIDDLE, dsp_sysuninit, NULL);
2530 
2531 char *
2532 dsp_unit2name(char *buf, size_t len, int unit)
2533 {
2534 	int i, dtype;
2535 
2536 	KASSERT(buf != NULL && len != 0,
2537 	    ("bogus buf=%p len=%ju", buf, (uintmax_t)len));
2538 
2539 	dtype = snd_unit2d(unit);
2540 
2541 	for (i = 0; i < (sizeof(dsp_cdevs) / sizeof(dsp_cdevs[0])); i++) {
2542 		if (dtype != dsp_cdevs[i].type || dsp_cdevs[i].alias != NULL)
2543 			continue;
2544 		snprintf(buf, len, "%s%d%s%d", dsp_cdevs[i].name,
2545 		    snd_unit2u(unit), dsp_cdevs[i].sep, snd_unit2c(unit));
2546 		return (buf);
2547 	}
2548 
2549 	return (NULL);
2550 }
2551 
2552 /**
2553  * @brief Handler for SNDCTL_AUDIOINFO.
2554  *
2555  * Gathers information about the audio device specified in ai->dev.  If
2556  * ai->dev == -1, then this function gathers information about the current
2557  * device.  If the call comes in on a non-audio device and ai->dev == -1,
2558  * return EINVAL.
2559  *
2560  * This routine is supposed to go practically straight to the hardware,
2561  * getting capabilities directly from the sound card driver, side-stepping
2562  * the intermediate channel interface.
2563  *
2564  * Note, however, that the usefulness of this command is significantly
2565  * decreased when requesting info about any device other than the one serving
2566  * the request. While each snddev_channel refers to a specific device node,
2567  * the converse is *not* true.  Currently, when a sound device node is opened,
2568  * the sound subsystem scans for an available audio channel (or channels, if
2569  * opened in read+write) and then assigns them to the si_drv[12] private
2570  * data fields.  As a result, any information returned linking a channel to
2571  * a specific character device isn't necessarily accurate.
2572  *
2573  * @note
2574  * Calling threads must not hold any snddev_info or pcm_channel locks.
2575  *
2576  * @param dev		device on which the ioctl was issued
2577  * @param ai		ioctl request data container
2578  *
2579  * @retval 0		success
2580  * @retval EINVAL	ai->dev specifies an invalid device
2581  *
2582  * @todo Verify correctness of Doxygen tags.  ;)
2583  */
2584 int
2585 dsp_oss_audioinfo(struct cdev *i_dev, oss_audioinfo *ai)
2586 {
2587 	struct pcmchan_caps *caps;
2588 	struct pcm_channel *ch;
2589 	struct snddev_info *d;
2590 	uint32_t fmts;
2591 	int i, nchan, *rates, minch, maxch;
2592 	char *devname, buf[CHN_NAMELEN];
2593 
2594 	/*
2595 	 * If probing the device that received the ioctl, make sure it's a
2596 	 * DSP device.  (Users may use this ioctl with /dev/mixer and
2597 	 * /dev/midi.)
2598 	 */
2599 	if (ai->dev == -1 && i_dev->si_devsw != &dsp_cdevsw)
2600 		return (EINVAL);
2601 
2602 	ch = NULL;
2603 	devname = NULL;
2604 	nchan = 0;
2605 	bzero(buf, sizeof(buf));
2606 
2607 	/*
2608 	 * Search for the requested audio device (channel).  Start by
2609 	 * iterating over pcm devices.
2610 	 */
2611 	for (i = 0; pcm_devclass != NULL &&
2612 	    i < devclass_get_maxunit(pcm_devclass); i++) {
2613 		d = devclass_get_softc(pcm_devclass, i);
2614 		if (!PCM_REGISTERED(d))
2615 			continue;
2616 
2617 		/* XXX Need Giant magic entry ??? */
2618 
2619 		/* See the note in function docblock */
2620 		PCM_UNLOCKASSERT(d);
2621 		PCM_LOCK(d);
2622 
2623 		CHN_FOREACH(ch, d, channels.pcm) {
2624 			CHN_UNLOCKASSERT(ch);
2625 			CHN_LOCK(ch);
2626 			if (ai->dev == -1) {
2627 				if (DSP_REGISTERED(d, i_dev) &&
2628 				    (ch == PCM_RDCH(i_dev) ||	/* record ch */
2629 				    ch == PCM_WRCH(i_dev))) {	/* playback ch */
2630 					devname = dsp_unit2name(buf,
2631 					    sizeof(buf), ch->unit);
2632 				}
2633 			} else if (ai->dev == nchan) {
2634 				devname = dsp_unit2name(buf, sizeof(buf),
2635 				    ch->unit);
2636 			}
2637 			if (devname != NULL)
2638 				break;
2639 			CHN_UNLOCK(ch);
2640 			++nchan;
2641 		}
2642 
2643 		if (devname != NULL) {
2644 			/*
2645 			 * At this point, the following synchronization stuff
2646 			 * has happened:
2647 			 * - a specific PCM device is locked.
2648 			 * - a specific audio channel has been locked, so be
2649 			 *   sure to unlock when exiting;
2650 			 */
2651 
2652 			caps = chn_getcaps(ch);
2653 
2654 			/*
2655 			 * With all handles collected, zero out the user's
2656 			 * container and begin filling in its fields.
2657 			 */
2658 			bzero((void *)ai, sizeof(oss_audioinfo));
2659 
2660 			ai->dev = nchan;
2661 			strlcpy(ai->name, ch->name,  sizeof(ai->name));
2662 
2663 			if ((ch->flags & CHN_F_BUSY) == 0)
2664 				ai->busy = 0;
2665 			else
2666 				ai->busy = (ch->direction == PCMDIR_PLAY) ? OPEN_WRITE : OPEN_READ;
2667 
2668 			/**
2669 			 * @note
2670 			 * @c cmd - OSSv4 docs: "Only supported under Linux at
2671 			 *    this moment." Cop-out, I know, but I'll save
2672 			 *    running around in the process table for later.
2673 			 *    Is there a risk of leaking information?
2674 			 */
2675 			ai->pid = ch->pid;
2676 
2677 			/*
2678 			 * These flags stolen from SNDCTL_DSP_GETCAPS handler.
2679 			 * Note, however, that a single channel operates in
2680 			 * only one direction, so PCM_CAP_DUPLEX is out.
2681 			 */
2682 			/**
2683 			 * @todo @c SNDCTL_AUDIOINFO::caps - Make drivers keep
2684 			 *       these in pcmchan::caps?
2685 			 */
2686 			ai->caps = PCM_CAP_REALTIME | PCM_CAP_MMAP | PCM_CAP_TRIGGER |
2687 			    ((ch->flags & CHN_F_VIRTUAL) ? PCM_CAP_VIRTUAL : 0) |
2688 			    ((ch->direction == PCMDIR_PLAY) ? PCM_CAP_OUTPUT : PCM_CAP_INPUT);
2689 
2690 			/*
2691 			 * Collect formats supported @b natively by the
2692 			 * device.  Also determine min/max channels.  (I.e.,
2693 			 * mono, stereo, or both?)
2694 			 *
2695 			 * If any channel is stereo, maxch = 2;
2696 			 * if all channels are stereo, minch = 2, too;
2697 			 * if any channel is mono, minch = 1;
2698 			 * and if all channels are mono, maxch = 1.
2699 			 */
2700 			minch = 0;
2701 			maxch = 0;
2702 			fmts = 0;
2703 			for (i = 0; caps->fmtlist[i]; i++) {
2704 				fmts |= caps->fmtlist[i];
2705 				if (AFMT_CHANNEL(caps->fmtlist[i]) > 1) {
2706 					minch = (minch == 0) ? 2 : minch;
2707 					maxch = 2;
2708 				} else {
2709 					minch = 1;
2710 					maxch = (maxch == 0) ? 1 : maxch;
2711 				}
2712 			}
2713 
2714 			if (ch->direction == PCMDIR_PLAY)
2715 				ai->oformats = fmts;
2716 			else
2717 				ai->iformats = fmts;
2718 
2719 			/**
2720 			 * @note
2721 			 * @c magic - OSSv4 docs: "Reserved for internal use
2722 			 *    by OSS."
2723 			 *
2724 			 * @par
2725 			 * @c card_number - OSSv4 docs: "Number of the sound
2726 			 *    card where this device belongs or -1 if this
2727 			 *    information is not available.  Applications
2728 			 *    should normally not use this field for any
2729 			 *    purpose."
2730 			 */
2731 			ai->card_number = -1;
2732 			/**
2733 			 * @todo @c song_name - depends first on
2734 			 *          SNDCTL_[GS]ETSONG @todo @c label - depends
2735 			 *          on SNDCTL_[GS]ETLABEL
2736 			 * @todo @c port_number - routing information?
2737 			 */
2738 			ai->port_number = -1;
2739 			ai->mixer_dev = (d->mixer_dev != NULL) ? PCMUNIT(d->mixer_dev) : -1;
2740 			/**
2741 			 * @note
2742 			 * @c real_device - OSSv4 docs:  "Obsolete."
2743 			 */
2744 			ai->real_device = -1;
2745 			strlcpy(ai->devnode, "/dev/", sizeof(ai->devnode));
2746 			strlcat(ai->devnode, devname, sizeof(ai->devnode));
2747 			ai->enabled = device_is_attached(d->dev) ? 1 : 0;
2748 			/**
2749 			 * @note
2750 			 * @c flags - OSSv4 docs: "Reserved for future use."
2751 			 *
2752 			 * @note
2753 			 * @c binding - OSSv4 docs: "Reserved for future use."
2754 			 *
2755 			 * @todo @c handle - haven't decided how to generate
2756 			 *       this yet; bus, vendor, device IDs?
2757 			 */
2758 			ai->min_rate = caps->minspeed;
2759 			ai->max_rate = caps->maxspeed;
2760 
2761 			ai->min_channels = minch;
2762 			ai->max_channels = maxch;
2763 
2764 			ai->nrates = chn_getrates(ch, &rates);
2765 			if (ai->nrates > OSS_MAX_SAMPLE_RATES)
2766 				ai->nrates = OSS_MAX_SAMPLE_RATES;
2767 
2768 			for (i = 0; i < ai->nrates; i++)
2769 				ai->rates[i] = rates[i];
2770 
2771 			ai->next_play_engine = 0;
2772 			ai->next_rec_engine = 0;
2773 
2774 			CHN_UNLOCK(ch);
2775 		}
2776 
2777 		PCM_UNLOCK(d);
2778 
2779 		if (devname != NULL)
2780 			return (0);
2781 	}
2782 
2783 	/* Exhausted the search -- nothing is locked, so return. */
2784 	return (EINVAL);
2785 }
2786 
2787 /**
2788  * @brief Assigns a PCM channel to a sync group.
2789  *
2790  * Sync groups are used to enable audio operations on multiple devices
2791  * simultaneously.  They may be used with any number of devices and may
2792  * span across applications.  Devices are added to groups with
2793  * the SNDCTL_DSP_SYNCGROUP ioctl, and operations are triggered with the
2794  * SNDCTL_DSP_SYNCSTART ioctl.
2795  *
2796  * If the @c id field of the @c group parameter is set to zero, then a new
2797  * sync group is created.  Otherwise, wrch and rdch (if set) are added to
2798  * the group specified.
2799  *
2800  * @todo As far as memory allocation, should we assume that things are
2801  * 	 okay and allocate with M_WAITOK before acquiring channel locks,
2802  * 	 freeing later if not?
2803  *
2804  * @param wrch	output channel associated w/ device (if any)
2805  * @param rdch	input channel associated w/ device (if any)
2806  * @param group Sync group parameters
2807  *
2808  * @retval 0		success
2809  * @retval non-zero	error to be propagated upstream
2810  */
2811 static int
2812 dsp_oss_syncgroup(struct pcm_channel *wrch, struct pcm_channel *rdch, oss_syncgroup *group)
2813 {
2814 	struct pcmchan_syncmember *smrd, *smwr;
2815 	struct pcmchan_syncgroup *sg;
2816 	int ret, sg_ids[3];
2817 
2818 	smrd = NULL;
2819 	smwr = NULL;
2820 	sg = NULL;
2821 	ret = 0;
2822 
2823 	/*
2824 	 * Free_unr() may sleep, so store released syncgroup IDs until after
2825 	 * all locks are released.
2826 	 */
2827 	sg_ids[0] = sg_ids[1] = sg_ids[2] = 0;
2828 
2829 	PCM_SG_LOCK();
2830 
2831 	/*
2832 	 * - Insert channel(s) into group's member list.
2833 	 * - Set CHN_F_NOTRIGGER on channel(s).
2834 	 * - Stop channel(s).
2835 	 */
2836 
2837 	/*
2838 	 * If device's channels are already mapped to a group, unmap them.
2839 	 */
2840 	if (wrch) {
2841 		CHN_LOCK(wrch);
2842 		sg_ids[0] = chn_syncdestroy(wrch);
2843 	}
2844 
2845 	if (rdch) {
2846 		CHN_LOCK(rdch);
2847 		sg_ids[1] = chn_syncdestroy(rdch);
2848 	}
2849 
2850 	/*
2851 	 * Verify that mode matches character device properites.
2852 	 *  - Bail if PCM_ENABLE_OUTPUT && wrch == NULL.
2853 	 *  - Bail if PCM_ENABLE_INPUT && rdch == NULL.
2854 	 */
2855 	if (((wrch == NULL) && (group->mode & PCM_ENABLE_OUTPUT)) ||
2856 	    ((rdch == NULL) && (group->mode & PCM_ENABLE_INPUT))) {
2857 		ret = EINVAL;
2858 		goto out;
2859 	}
2860 
2861 	/*
2862 	 * An id of zero indicates the user wants to create a new
2863 	 * syncgroup.
2864 	 */
2865 	if (group->id == 0) {
2866 		sg = (struct pcmchan_syncgroup *)malloc(sizeof(*sg), M_DEVBUF, M_NOWAIT);
2867 		if (sg != NULL) {
2868 			SLIST_INIT(&sg->members);
2869 			sg->id = alloc_unr(pcmsg_unrhdr);
2870 
2871 			group->id = sg->id;
2872 			SLIST_INSERT_HEAD(&snd_pcm_syncgroups, sg, link);
2873 		} else
2874 			ret = ENOMEM;
2875 	} else {
2876 		SLIST_FOREACH(sg, &snd_pcm_syncgroups, link) {
2877 			if (sg->id == group->id)
2878 				break;
2879 		}
2880 		if (sg == NULL)
2881 			ret = EINVAL;
2882 	}
2883 
2884 	/* Couldn't create or find a syncgroup.  Fail. */
2885 	if (sg == NULL)
2886 		goto out;
2887 
2888 	/*
2889 	 * Allocate a syncmember, assign it and a channel together, and
2890 	 * insert into syncgroup.
2891 	 */
2892 	if (group->mode & PCM_ENABLE_INPUT) {
2893 		smrd = (struct pcmchan_syncmember *)malloc(sizeof(*smrd), M_DEVBUF, M_NOWAIT);
2894 		if (smrd == NULL) {
2895 			ret = ENOMEM;
2896 			goto out;
2897 		}
2898 
2899 		SLIST_INSERT_HEAD(&sg->members, smrd, link);
2900 		smrd->parent = sg;
2901 		smrd->ch = rdch;
2902 
2903 		chn_abort(rdch);
2904 		rdch->flags |= CHN_F_NOTRIGGER;
2905 		rdch->sm = smrd;
2906 	}
2907 
2908 	if (group->mode & PCM_ENABLE_OUTPUT) {
2909 		smwr = (struct pcmchan_syncmember *)malloc(sizeof(*smwr), M_DEVBUF, M_NOWAIT);
2910 		if (smwr == NULL) {
2911 			ret = ENOMEM;
2912 			goto out;
2913 		}
2914 
2915 		SLIST_INSERT_HEAD(&sg->members, smwr, link);
2916 		smwr->parent = sg;
2917 		smwr->ch = wrch;
2918 
2919 		chn_abort(wrch);
2920 		wrch->flags |= CHN_F_NOTRIGGER;
2921 		wrch->sm = smwr;
2922 	}
2923 
2924 out:
2925 	if (ret != 0) {
2926 		if (smrd != NULL)
2927 			free(smrd, M_DEVBUF);
2928 		if ((sg != NULL) && SLIST_EMPTY(&sg->members)) {
2929 			sg_ids[2] = sg->id;
2930 			SLIST_REMOVE(&snd_pcm_syncgroups, sg, pcmchan_syncgroup, link);
2931 			free(sg, M_DEVBUF);
2932 		}
2933 
2934 		if (wrch)
2935 			wrch->sm = NULL;
2936 		if (rdch)
2937 			rdch->sm = NULL;
2938 	}
2939 
2940 	if (wrch)
2941 		CHN_UNLOCK(wrch);
2942 	if (rdch)
2943 		CHN_UNLOCK(rdch);
2944 
2945 	PCM_SG_UNLOCK();
2946 
2947 	if (sg_ids[0])
2948 		free_unr(pcmsg_unrhdr, sg_ids[0]);
2949 	if (sg_ids[1])
2950 		free_unr(pcmsg_unrhdr, sg_ids[1]);
2951 	if (sg_ids[2])
2952 		free_unr(pcmsg_unrhdr, sg_ids[2]);
2953 
2954 	return (ret);
2955 }
2956 
2957 /**
2958  * @brief Launch a sync group into action
2959  *
2960  * Sync groups are established via SNDCTL_DSP_SYNCGROUP.  This function
2961  * iterates over all members, triggering them along the way.
2962  *
2963  * @note Caller must not hold any channel locks.
2964  *
2965  * @param sg_id	sync group identifier
2966  *
2967  * @retval 0	success
2968  * @retval non-zero	error worthy of propagating upstream to user
2969  */
2970 static int
2971 dsp_oss_syncstart(int sg_id)
2972 {
2973 	struct pcmchan_syncmember *sm, *sm_tmp;
2974 	struct pcmchan_syncgroup *sg;
2975 	struct pcm_channel *c;
2976 	int ret, needlocks;
2977 
2978 	/* Get the synclists lock */
2979 	PCM_SG_LOCK();
2980 
2981 	do {
2982 		ret = 0;
2983 		needlocks = 0;
2984 
2985 		/* Search for syncgroup by ID */
2986 		SLIST_FOREACH(sg, &snd_pcm_syncgroups, link) {
2987 			if (sg->id == sg_id)
2988 				break;
2989 		}
2990 
2991 		/* Return EINVAL if not found */
2992 		if (sg == NULL) {
2993 			ret = EINVAL;
2994 			break;
2995 		}
2996 
2997 		/* Any removals resulting in an empty group should've handled this */
2998 		KASSERT(!SLIST_EMPTY(&sg->members), ("found empty syncgroup"));
2999 
3000 		/*
3001 		 * Attempt to lock all member channels - if any are already
3002 		 * locked, unlock those acquired, sleep for a bit, and try
3003 		 * again.
3004 		 */
3005 		SLIST_FOREACH(sm, &sg->members, link) {
3006 			if (CHN_TRYLOCK(sm->ch) == 0) {
3007 				int timo = hz * 5/1000;
3008 				if (timo < 1)
3009 					timo = 1;
3010 
3011 				/* Release all locked channels so far, retry */
3012 				SLIST_FOREACH(sm_tmp, &sg->members, link) {
3013 					/* sm is the member already locked */
3014 					if (sm == sm_tmp)
3015 						break;
3016 					CHN_UNLOCK(sm_tmp->ch);
3017 				}
3018 
3019 				/** @todo Is PRIBIO correct/ */
3020 				ret = msleep(sm, &snd_pcm_syncgroups_mtx,
3021 				    PRIBIO | PCATCH, "pcmsg", timo);
3022 				if (ret == EINTR || ret == ERESTART)
3023 					break;
3024 
3025 				needlocks = 1;
3026 				ret = 0; /* Assumes ret == EAGAIN... */
3027 			}
3028 		}
3029 	} while (needlocks && ret == 0);
3030 
3031 	/* Proceed only if no errors encountered. */
3032 	if (ret == 0) {
3033 		/* Launch channels */
3034 		while ((sm = SLIST_FIRST(&sg->members)) != NULL) {
3035 			SLIST_REMOVE_HEAD(&sg->members, link);
3036 
3037 			c = sm->ch;
3038 			c->sm = NULL;
3039 			chn_start(c, 1);
3040 			c->flags &= ~CHN_F_NOTRIGGER;
3041 			CHN_UNLOCK(c);
3042 
3043 			free(sm, M_DEVBUF);
3044 		}
3045 
3046 		SLIST_REMOVE(&snd_pcm_syncgroups, sg, pcmchan_syncgroup, link);
3047 		free(sg, M_DEVBUF);
3048 	}
3049 
3050 	PCM_SG_UNLOCK();
3051 
3052 	/*
3053 	 * Free_unr() may sleep, so be sure to give up the syncgroup lock
3054 	 * first.
3055 	 */
3056 	if (ret == 0)
3057 		free_unr(pcmsg_unrhdr, sg_id);
3058 
3059 	return (ret);
3060 }
3061 
3062 /**
3063  * @brief Handler for SNDCTL_DSP_POLICY
3064  *
3065  * The SNDCTL_DSP_POLICY ioctl is a simpler interface to control fragment
3066  * size and count like with SNDCTL_DSP_SETFRAGMENT.  Instead of the user
3067  * specifying those two parameters, s/he simply selects a number from 0..10
3068  * which corresponds to a buffer size.  Smaller numbers request smaller
3069  * buffers with lower latencies (at greater overhead from more frequent
3070  * interrupts), while greater numbers behave in the opposite manner.
3071  *
3072  * The 4Front spec states that a value of 5 should be the default.  However,
3073  * this implementation deviates slightly by using a linear scale without
3074  * consulting drivers.  I.e., even though drivers may have different default
3075  * buffer sizes, a policy argument of 5 will have the same result across
3076  * all drivers.
3077  *
3078  * See http://manuals.opensound.com/developer/SNDCTL_DSP_POLICY.html for
3079  * more information.
3080  *
3081  * @todo When SNDCTL_DSP_COOKEDMODE is supported, it'll be necessary to
3082  * 	 work with hardware drivers directly.
3083  *
3084  * @note PCM channel arguments must not be locked by caller.
3085  *
3086  * @param wrch	Pointer to opened playback channel (optional; may be NULL)
3087  * @param rdch	" recording channel (optional; may be NULL)
3088  * @param policy Integer from [0:10]
3089  *
3090  * @retval 0	constant (for now)
3091  */
3092 static int
3093 dsp_oss_policy(struct pcm_channel *wrch, struct pcm_channel *rdch, int policy)
3094 {
3095 	int ret;
3096 
3097 	if (policy < CHN_POLICY_MIN || policy > CHN_POLICY_MAX)
3098 		return (EIO);
3099 
3100 	/* Default: success */
3101 	ret = 0;
3102 
3103 	if (rdch) {
3104 		CHN_LOCK(rdch);
3105 		ret = chn_setlatency(rdch, policy);
3106 		CHN_UNLOCK(rdch);
3107 	}
3108 
3109 	if (wrch && ret == 0) {
3110 		CHN_LOCK(wrch);
3111 		ret = chn_setlatency(wrch, policy);
3112 		CHN_UNLOCK(wrch);
3113 	}
3114 
3115 	if (ret)
3116 		ret = EIO;
3117 
3118 	return (ret);
3119 }
3120 
3121 /**
3122  * @brief Enable or disable "cooked" mode
3123  *
3124  * This is a handler for @c SNDCTL_DSP_COOKEDMODE.  When in cooked mode, which
3125  * is the default, the sound system handles rate and format conversions
3126  * automatically (ex: user writing 11025Hz/8 bit/unsigned but card only
3127  * operates with 44100Hz/16bit/signed samples).
3128  *
3129  * Disabling cooked mode is intended for applications wanting to mmap()
3130  * a sound card's buffer space directly, bypassing the FreeBSD 2-stage
3131  * feeder architecture, presumably to gain as much control over audio
3132  * hardware as possible.
3133  *
3134  * See @c http://manuals.opensound.com/developer/SNDCTL_DSP_COOKEDMODE.html
3135  * for more details.
3136  *
3137  * @param wrch		playback channel (optional; may be NULL)
3138  * @param rdch		recording channel (optional; may be NULL)
3139  * @param enabled	0 = raw mode, 1 = cooked mode
3140  *
3141  * @retval EINVAL	Operation not yet supported.
3142  */
3143 static int
3144 dsp_oss_cookedmode(struct pcm_channel *wrch, struct pcm_channel *rdch, int enabled)
3145 {
3146 
3147 	/*
3148 	 * XXX I just don't get it. Why don't they call it
3149 	 * "BITPERFECT" ~ SNDCTL_DSP_BITPERFECT !?!?.
3150 	 * This is just plain so confusing, incoherent,
3151 	 * <insert any non-printable characters here>.
3152 	 */
3153 	if (!(enabled == 1 || enabled == 0))
3154 		return (EINVAL);
3155 
3156 	/*
3157 	 * I won't give in. I'm inverting its logic here and now.
3158 	 * Brag all you want, but "BITPERFECT" should be the better
3159 	 * term here.
3160 	 */
3161 	enabled ^= 0x00000001;
3162 
3163 	if (wrch != NULL) {
3164 		CHN_LOCK(wrch);
3165 		wrch->flags &= ~CHN_F_BITPERFECT;
3166 		wrch->flags |= (enabled != 0) ? CHN_F_BITPERFECT : 0x00000000;
3167 		CHN_UNLOCK(wrch);
3168 	}
3169 
3170 	if (rdch != NULL) {
3171 		CHN_LOCK(rdch);
3172 		rdch->flags &= ~CHN_F_BITPERFECT;
3173 		rdch->flags |= (enabled != 0) ? CHN_F_BITPERFECT : 0x00000000;
3174 		CHN_UNLOCK(rdch);
3175 	}
3176 
3177 	return (0);
3178 }
3179 
3180 /**
3181  * @brief Retrieve channel interleaving order
3182  *
3183  * This is the handler for @c SNDCTL_DSP_GET_CHNORDER.
3184  *
3185  * See @c http://manuals.opensound.com/developer/SNDCTL_DSP_GET_CHNORDER.html
3186  * for more details.
3187  *
3188  * @note As the ioctl definition is still under construction, FreeBSD
3189  * 	 does not currently support SNDCTL_DSP_GET_CHNORDER.
3190  *
3191  * @param wrch	playback channel (optional; may be NULL)
3192  * @param rdch	recording channel (optional; may be NULL)
3193  * @param map	channel map (result will be stored there)
3194  *
3195  * @retval EINVAL	Operation not yet supported.
3196  */
3197 static int
3198 dsp_oss_getchnorder(struct pcm_channel *wrch, struct pcm_channel *rdch, unsigned long long *map)
3199 {
3200 	struct pcm_channel *ch;
3201 	int ret;
3202 
3203 	ch = (wrch != NULL) ? wrch : rdch;
3204 	if (ch != NULL) {
3205 		CHN_LOCK(ch);
3206 		ret = chn_oss_getorder(ch, map);
3207 		CHN_UNLOCK(ch);
3208 	} else
3209 		ret = EINVAL;
3210 
3211 	return (ret);
3212 }
3213 
3214 /**
3215  * @brief Specify channel interleaving order
3216  *
3217  * This is the handler for @c SNDCTL_DSP_SET_CHNORDER.
3218  *
3219  * @note As the ioctl definition is still under construction, FreeBSD
3220  * 	 does not currently support @c SNDCTL_DSP_SET_CHNORDER.
3221  *
3222  * @param wrch	playback channel (optional; may be NULL)
3223  * @param rdch	recording channel (optional; may be NULL)
3224  * @param map	channel map
3225  *
3226  * @retval EINVAL	Operation not yet supported.
3227  */
3228 static int
3229 dsp_oss_setchnorder(struct pcm_channel *wrch, struct pcm_channel *rdch, unsigned long long *map)
3230 {
3231 	int ret;
3232 
3233 	ret = 0;
3234 
3235 	if (wrch != NULL) {
3236 		CHN_LOCK(wrch);
3237 		ret = chn_oss_setorder(wrch, map);
3238 		CHN_UNLOCK(wrch);
3239 	}
3240 
3241 	if (ret == 0 && rdch != NULL) {
3242 		CHN_LOCK(rdch);
3243 		ret = chn_oss_setorder(rdch, map);
3244 		CHN_UNLOCK(rdch);
3245 	}
3246 
3247 	return (ret);
3248 }
3249 
3250 static int
3251 dsp_oss_getchannelmask(struct pcm_channel *wrch, struct pcm_channel *rdch,
3252     int *mask)
3253 {
3254 	struct pcm_channel *ch;
3255 	uint32_t chnmask;
3256 	int ret;
3257 
3258 	chnmask = 0;
3259 	ch = (wrch != NULL) ? wrch : rdch;
3260 
3261 	if (ch != NULL) {
3262 		CHN_LOCK(ch);
3263 		ret = chn_oss_getmask(ch, &chnmask);
3264 		CHN_UNLOCK(ch);
3265 	} else
3266 		ret = EINVAL;
3267 
3268 	if (ret == 0)
3269 		*mask = chnmask;
3270 
3271 	return (ret);
3272 }
3273 
3274 #ifdef OSSV4_EXPERIMENT
3275 /**
3276  * @brief Retrieve an audio device's label
3277  *
3278  * This is a handler for the @c SNDCTL_GETLABEL ioctl.
3279  *
3280  * See @c http://manuals.opensound.com/developer/SNDCTL_GETLABEL.html
3281  * for more details.
3282  *
3283  * From Hannu@4Front:  "For example ossxmix (just like some HW mixer
3284  * consoles) can show variable "labels" for certain controls. By default
3285  * the application name (say quake) is shown as the label but
3286  * applications may change the labels themselves."
3287  *
3288  * @note As the ioctl definition is still under construction, FreeBSD
3289  * 	 does not currently support @c SNDCTL_GETLABEL.
3290  *
3291  * @param wrch	playback channel (optional; may be NULL)
3292  * @param rdch	recording channel (optional; may be NULL)
3293  * @param label	label gets copied here
3294  *
3295  * @retval EINVAL	Operation not yet supported.
3296  */
3297 static int
3298 dsp_oss_getlabel(struct pcm_channel *wrch, struct pcm_channel *rdch, oss_label_t *label)
3299 {
3300 	return (EINVAL);
3301 }
3302 
3303 /**
3304  * @brief Specify an audio device's label
3305  *
3306  * This is a handler for the @c SNDCTL_SETLABEL ioctl.  Please see the
3307  * comments for @c dsp_oss_getlabel immediately above.
3308  *
3309  * See @c http://manuals.opensound.com/developer/SNDCTL_GETLABEL.html
3310  * for more details.
3311  *
3312  * @note As the ioctl definition is still under construction, FreeBSD
3313  * 	 does not currently support SNDCTL_SETLABEL.
3314  *
3315  * @param wrch	playback channel (optional; may be NULL)
3316  * @param rdch	recording channel (optional; may be NULL)
3317  * @param label	label gets copied from here
3318  *
3319  * @retval EINVAL	Operation not yet supported.
3320  */
3321 static int
3322 dsp_oss_setlabel(struct pcm_channel *wrch, struct pcm_channel *rdch, oss_label_t *label)
3323 {
3324 	return (EINVAL);
3325 }
3326 
3327 /**
3328  * @brief Retrieve name of currently played song
3329  *
3330  * This is a handler for the @c SNDCTL_GETSONG ioctl.  Audio players could
3331  * tell the system the name of the currently playing song, which would be
3332  * visible in @c /dev/sndstat.
3333  *
3334  * See @c http://manuals.opensound.com/developer/SNDCTL_GETSONG.html
3335  * for more details.
3336  *
3337  * @note As the ioctl definition is still under construction, FreeBSD
3338  * 	 does not currently support SNDCTL_GETSONG.
3339  *
3340  * @param wrch	playback channel (optional; may be NULL)
3341  * @param rdch	recording channel (optional; may be NULL)
3342  * @param song	song name gets copied here
3343  *
3344  * @retval EINVAL	Operation not yet supported.
3345  */
3346 static int
3347 dsp_oss_getsong(struct pcm_channel *wrch, struct pcm_channel *rdch, oss_longname_t *song)
3348 {
3349 	return (EINVAL);
3350 }
3351 
3352 /**
3353  * @brief Retrieve name of currently played song
3354  *
3355  * This is a handler for the @c SNDCTL_SETSONG ioctl.  Audio players could
3356  * tell the system the name of the currently playing song, which would be
3357  * visible in @c /dev/sndstat.
3358  *
3359  * See @c http://manuals.opensound.com/developer/SNDCTL_SETSONG.html
3360  * for more details.
3361  *
3362  * @note As the ioctl definition is still under construction, FreeBSD
3363  * 	 does not currently support SNDCTL_SETSONG.
3364  *
3365  * @param wrch	playback channel (optional; may be NULL)
3366  * @param rdch	recording channel (optional; may be NULL)
3367  * @param song	song name gets copied from here
3368  *
3369  * @retval EINVAL	Operation not yet supported.
3370  */
3371 static int
3372 dsp_oss_setsong(struct pcm_channel *wrch, struct pcm_channel *rdch, oss_longname_t *song)
3373 {
3374 	return (EINVAL);
3375 }
3376 
3377 /**
3378  * @brief Rename a device
3379  *
3380  * This is a handler for the @c SNDCTL_SETNAME ioctl.
3381  *
3382  * See @c http://manuals.opensound.com/developer/SNDCTL_SETNAME.html for
3383  * more details.
3384  *
3385  * From Hannu@4Front:  "This call is used to change the device name
3386  * reported in /dev/sndstat and ossinfo. So instead of  using some generic
3387  * 'OSS loopback audio (MIDI) driver' the device may be given a meaningfull
3388  * name depending on the current context (for example 'OSS virtual wave table
3389  * synth' or 'VoIP link to London')."
3390  *
3391  * @note As the ioctl definition is still under construction, FreeBSD
3392  * 	 does not currently support SNDCTL_SETNAME.
3393  *
3394  * @param wrch	playback channel (optional; may be NULL)
3395  * @param rdch	recording channel (optional; may be NULL)
3396  * @param name	new device name gets copied from here
3397  *
3398  * @retval EINVAL	Operation not yet supported.
3399  */
3400 static int
3401 dsp_oss_setname(struct pcm_channel *wrch, struct pcm_channel *rdch, oss_longname_t *name)
3402 {
3403 	return (EINVAL);
3404 }
3405 #endif	/* !OSSV4_EXPERIMENT */
3406