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