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