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