xref: /freebsd/sys/dev/sound/pcm/dsp.c (revision 4ed925457ab06e83238a5db33e89ccc94b99a713)
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 			return (0);
1075 		}
1076 		ret = dsp_ioctl_channel(i_dev, PCM_VOLCH(i_dev), cmd, arg);
1077 		if (ret != -1) {
1078 			PCM_GIANT_EXIT(d);
1079 			return (ret);
1080 		}
1081 
1082 		if (d->mixer_dev != NULL) {
1083 			PCM_ACQUIRE_QUICK(d);
1084 			ret = mixer_ioctl_cmd(d->mixer_dev, cmd, arg, -1, td,
1085 			    MIXER_CMD_DIRECT);
1086 			PCM_RELEASE_QUICK(d);
1087 		} else
1088 			ret = EBADF;
1089 
1090 		PCM_GIANT_EXIT(d);
1091 
1092 		return (ret);
1093 	}
1094 
1095 	/*
1096 	 * Certain ioctls may be made on any type of device (audio, mixer,
1097 	 * and MIDI).  Handle those special cases here.
1098 	 */
1099 	if (IOCGROUP(cmd) == 'X') {
1100 		PCM_ACQUIRE_QUICK(d);
1101 		switch(cmd) {
1102 		case SNDCTL_SYSINFO:
1103 			sound_oss_sysinfo((oss_sysinfo *)arg);
1104 			break;
1105 		case SNDCTL_CARDINFO:
1106 			ret = sound_oss_card_info((oss_card_info *)arg);
1107 			break;
1108 		case SNDCTL_AUDIOINFO:
1109 		case SNDCTL_AUDIOINFO_EX:
1110 		case SNDCTL_ENGINEINFO:
1111 			ret = dsp_oss_audioinfo(i_dev, (oss_audioinfo *)arg);
1112 			break;
1113 		case SNDCTL_MIXERINFO:
1114 			ret = mixer_oss_mixerinfo(i_dev, (oss_mixerinfo *)arg);
1115 			break;
1116 		default:
1117 			ret = EINVAL;
1118 		}
1119 		PCM_RELEASE_QUICK(d);
1120 		PCM_GIANT_EXIT(d);
1121 		return (ret);
1122 	}
1123 
1124 	getchns(i_dev, &rdch, &wrch, 0);
1125 
1126 	if (wrch != NULL && (wrch->flags & CHN_F_DEAD))
1127 		wrch = NULL;
1128 	if (rdch != NULL && (rdch->flags & CHN_F_DEAD))
1129 		rdch = NULL;
1130 
1131 	if (wrch == NULL && rdch == NULL) {
1132 		PCM_GIANT_EXIT(d);
1133 		return (EINVAL);
1134 	}
1135 
1136     	switch(cmd) {
1137 #ifdef OLDPCM_IOCTL
1138     	/*
1139      	 * we start with the new ioctl interface.
1140      	 */
1141     	case AIONWRITE:	/* how many bytes can write ? */
1142 		if (wrch) {
1143 			CHN_LOCK(wrch);
1144 /*
1145 		if (wrch && wrch->bufhard.dl)
1146 			while (chn_wrfeed(wrch) == 0);
1147 */
1148 			*arg_i = sndbuf_getfree(wrch->bufsoft);
1149 			CHN_UNLOCK(wrch);
1150 		} else {
1151 			*arg_i = 0;
1152 			ret = EINVAL;
1153 		}
1154 		break;
1155 
1156     	case AIOSSIZE:     /* set the current blocksize */
1157 		{
1158 	    		struct snd_size *p = (struct snd_size *)arg;
1159 
1160 			p->play_size = 0;
1161 			p->rec_size = 0;
1162 			PCM_ACQUIRE_QUICK(d);
1163 	    		if (wrch) {
1164 				CHN_LOCK(wrch);
1165 				chn_setblocksize(wrch, 2, p->play_size);
1166 				p->play_size = sndbuf_getblksz(wrch->bufsoft);
1167 				CHN_UNLOCK(wrch);
1168 			}
1169 	    		if (rdch) {
1170 				CHN_LOCK(rdch);
1171 				chn_setblocksize(rdch, 2, p->rec_size);
1172 				p->rec_size = sndbuf_getblksz(rdch->bufsoft);
1173 				CHN_UNLOCK(rdch);
1174 			}
1175 			PCM_RELEASE_QUICK(d);
1176 		}
1177 		break;
1178     	case AIOGSIZE:	/* get the current blocksize */
1179 		{
1180 	    		struct snd_size *p = (struct snd_size *)arg;
1181 
1182 	    		if (wrch) {
1183 				CHN_LOCK(wrch);
1184 				p->play_size = sndbuf_getblksz(wrch->bufsoft);
1185 				CHN_UNLOCK(wrch);
1186 			}
1187 	    		if (rdch) {
1188 				CHN_LOCK(rdch);
1189 				p->rec_size = sndbuf_getblksz(rdch->bufsoft);
1190 				CHN_UNLOCK(rdch);
1191 			}
1192 		}
1193 		break;
1194 
1195     	case AIOSFMT:
1196     	case AIOGFMT:
1197 		{
1198 	    		snd_chan_param *p = (snd_chan_param *)arg;
1199 
1200 			if (cmd == AIOSFMT &&
1201 			    ((p->play_format != 0 && p->play_rate == 0) ||
1202 			    (p->rec_format != 0 && p->rec_rate == 0))) {
1203 				ret = EINVAL;
1204 				break;
1205 			}
1206 			PCM_ACQUIRE_QUICK(d);
1207 	    		if (wrch) {
1208 				CHN_LOCK(wrch);
1209 				if (cmd == AIOSFMT && p->play_format != 0) {
1210 					chn_setformat(wrch,
1211 					    SND_FORMAT(p->play_format,
1212 					    AFMT_CHANNEL(wrch->format),
1213 					    AFMT_EXTCHANNEL(wrch->format)));
1214 					chn_setspeed(wrch, p->play_rate);
1215 				}
1216 	    			p->play_rate = wrch->speed;
1217 	    			p->play_format = AFMT_ENCODING(wrch->format);
1218 				CHN_UNLOCK(wrch);
1219 			} else {
1220 	    			p->play_rate = 0;
1221 	    			p->play_format = 0;
1222 	    		}
1223 	    		if (rdch) {
1224 				CHN_LOCK(rdch);
1225 				if (cmd == AIOSFMT && p->rec_format != 0) {
1226 					chn_setformat(rdch,
1227 					    SND_FORMAT(p->rec_format,
1228 					    AFMT_CHANNEL(rdch->format),
1229 					    AFMT_EXTCHANNEL(rdch->format)));
1230 					chn_setspeed(rdch, p->rec_rate);
1231 				}
1232 				p->rec_rate = rdch->speed;
1233 				p->rec_format = AFMT_ENCODING(rdch->format);
1234 				CHN_UNLOCK(rdch);
1235 			} else {
1236 	    			p->rec_rate = 0;
1237 	    			p->rec_format = 0;
1238 	    		}
1239 			PCM_RELEASE_QUICK(d);
1240 		}
1241 		break;
1242 
1243     	case AIOGCAP:     /* get capabilities */
1244 		{
1245 	    		snd_capabilities *p = (snd_capabilities *)arg;
1246 			struct pcmchan_caps *pcaps = NULL, *rcaps = NULL;
1247 			struct cdev *pdev;
1248 
1249 			PCM_LOCK(d);
1250 			if (rdch) {
1251 				CHN_LOCK(rdch);
1252 				rcaps = chn_getcaps(rdch);
1253 			}
1254 			if (wrch) {
1255 				CHN_LOCK(wrch);
1256 				pcaps = chn_getcaps(wrch);
1257 			}
1258 	    		p->rate_min = max(rcaps? rcaps->minspeed : 0,
1259 	                      		  pcaps? pcaps->minspeed : 0);
1260 	    		p->rate_max = min(rcaps? rcaps->maxspeed : 1000000,
1261 	                      		  pcaps? pcaps->maxspeed : 1000000);
1262 	    		p->bufsize = min(rdch? sndbuf_getsize(rdch->bufsoft) : 1000000,
1263 	                     		 wrch? sndbuf_getsize(wrch->bufsoft) : 1000000);
1264 			/* XXX bad on sb16 */
1265 	    		p->formats = (rdch? chn_getformats(rdch) : 0xffffffff) &
1266 			 	     (wrch? chn_getformats(wrch) : 0xffffffff);
1267 			if (rdch && wrch)
1268 				p->formats |= (dsp_get_flags(i_dev) & SD_F_SIMPLEX)? 0 : AFMT_FULLDUPLEX;
1269 			pdev = d->mixer_dev;
1270 	    		p->mixers = 1; /* default: one mixer */
1271 	    		p->inputs = pdev->si_drv1? mix_getdevs(pdev->si_drv1) : 0;
1272 	    		p->left = p->right = 100;
1273 			if (wrch)
1274 				CHN_UNLOCK(wrch);
1275 			if (rdch)
1276 				CHN_UNLOCK(rdch);
1277 			PCM_UNLOCK(d);
1278 		}
1279 		break;
1280 
1281     	case AIOSTOP:
1282 		if (*arg_i == AIOSYNC_PLAY && wrch) {
1283 			CHN_LOCK(wrch);
1284 			*arg_i = chn_abort(wrch);
1285 			CHN_UNLOCK(wrch);
1286 		} else if (*arg_i == AIOSYNC_CAPTURE && rdch) {
1287 			CHN_LOCK(rdch);
1288 			*arg_i = chn_abort(rdch);
1289 			CHN_UNLOCK(rdch);
1290 		} else {
1291 	   	 	printf("AIOSTOP: bad channel 0x%x\n", *arg_i);
1292 	    		*arg_i = 0;
1293 		}
1294 		break;
1295 
1296     	case AIOSYNC:
1297 		printf("AIOSYNC chan 0x%03lx pos %lu unimplemented\n",
1298 	    		((snd_sync_parm *)arg)->chan, ((snd_sync_parm *)arg)->pos);
1299 		break;
1300 #endif
1301 	/*
1302 	 * here follow the standard ioctls (filio.h etc.)
1303 	 */
1304     	case FIONREAD: /* get # bytes to read */
1305 		if (rdch) {
1306 			CHN_LOCK(rdch);
1307 /*			if (rdch && rdch->bufhard.dl)
1308 				while (chn_rdfeed(rdch) == 0);
1309 */
1310 			*arg_i = sndbuf_getready(rdch->bufsoft);
1311 			CHN_UNLOCK(rdch);
1312 		} else {
1313 			*arg_i = 0;
1314 			ret = EINVAL;
1315 		}
1316 		break;
1317 
1318     	case FIOASYNC: /*set/clear async i/o */
1319 		DEB( printf("FIOASYNC\n") ; )
1320 		break;
1321 
1322     	case SNDCTL_DSP_NONBLOCK: /* set non-blocking i/o */
1323     	case FIONBIO: /* set/clear non-blocking i/o */
1324 		if (rdch) {
1325 			CHN_LOCK(rdch);
1326 			if (cmd == SNDCTL_DSP_NONBLOCK || *arg_i)
1327 				rdch->flags |= CHN_F_NBIO;
1328 			else
1329 				rdch->flags &= ~CHN_F_NBIO;
1330 			CHN_UNLOCK(rdch);
1331 		}
1332 		if (wrch) {
1333 			CHN_LOCK(wrch);
1334 			if (cmd == SNDCTL_DSP_NONBLOCK || *arg_i)
1335 				wrch->flags |= CHN_F_NBIO;
1336 			else
1337 				wrch->flags &= ~CHN_F_NBIO;
1338 			CHN_UNLOCK(wrch);
1339 		}
1340 		break;
1341 
1342     	/*
1343 	 * Finally, here is the linux-compatible ioctl interface
1344 	 */
1345 #define THE_REAL_SNDCTL_DSP_GETBLKSIZE _IOWR('P', 4, int)
1346     	case THE_REAL_SNDCTL_DSP_GETBLKSIZE:
1347     	case SNDCTL_DSP_GETBLKSIZE:
1348 		chn = wrch ? wrch : rdch;
1349 		if (chn) {
1350 			CHN_LOCK(chn);
1351 			*arg_i = sndbuf_getblksz(chn->bufsoft);
1352 			CHN_UNLOCK(chn);
1353 		} else {
1354 			*arg_i = 0;
1355 			ret = EINVAL;
1356 		}
1357 		break;
1358 
1359     	case SNDCTL_DSP_SETBLKSIZE:
1360 		RANGE(*arg_i, 16, 65536);
1361 		PCM_ACQUIRE_QUICK(d);
1362 		if (wrch) {
1363 			CHN_LOCK(wrch);
1364 			chn_setblocksize(wrch, 2, *arg_i);
1365 			CHN_UNLOCK(wrch);
1366 		}
1367 		if (rdch) {
1368 			CHN_LOCK(rdch);
1369 			chn_setblocksize(rdch, 2, *arg_i);
1370 			CHN_UNLOCK(rdch);
1371 		}
1372 		PCM_RELEASE_QUICK(d);
1373 		break;
1374 
1375     	case SNDCTL_DSP_RESET:
1376 		DEB(printf("dsp reset\n"));
1377 		if (wrch) {
1378 			CHN_LOCK(wrch);
1379 			chn_abort(wrch);
1380 			chn_resetbuf(wrch);
1381 			CHN_UNLOCK(wrch);
1382 		}
1383 		if (rdch) {
1384 			CHN_LOCK(rdch);
1385 			chn_abort(rdch);
1386 			chn_resetbuf(rdch);
1387 			CHN_UNLOCK(rdch);
1388 		}
1389 		break;
1390 
1391     	case SNDCTL_DSP_SYNC:
1392 		DEB(printf("dsp sync\n"));
1393 		/* chn_sync may sleep */
1394 		if (wrch) {
1395 			CHN_LOCK(wrch);
1396 			chn_sync(wrch, 0);
1397 			CHN_UNLOCK(wrch);
1398 		}
1399 		break;
1400 
1401     	case SNDCTL_DSP_SPEED:
1402 		/* chn_setspeed may sleep */
1403 		tmp = 0;
1404 		PCM_ACQUIRE_QUICK(d);
1405 		if (wrch) {
1406 			CHN_LOCK(wrch);
1407 			ret = chn_setspeed(wrch, *arg_i);
1408 			tmp = wrch->speed;
1409 			CHN_UNLOCK(wrch);
1410 		}
1411 		if (rdch && ret == 0) {
1412 			CHN_LOCK(rdch);
1413 			ret = chn_setspeed(rdch, *arg_i);
1414 			if (tmp == 0)
1415 				tmp = rdch->speed;
1416 			CHN_UNLOCK(rdch);
1417 		}
1418 		PCM_RELEASE_QUICK(d);
1419 		*arg_i = tmp;
1420 		break;
1421 
1422     	case SOUND_PCM_READ_RATE:
1423 		chn = wrch ? wrch : rdch;
1424 		if (chn) {
1425 			CHN_LOCK(chn);
1426 			*arg_i = chn->speed;
1427 			CHN_UNLOCK(chn);
1428 		} else {
1429 			*arg_i = 0;
1430 			ret = EINVAL;
1431 		}
1432 		break;
1433 
1434     	case SNDCTL_DSP_STEREO:
1435 		tmp = -1;
1436 		*arg_i = (*arg_i)? 2 : 1;
1437 		PCM_ACQUIRE_QUICK(d);
1438 		if (wrch) {
1439 			CHN_LOCK(wrch);
1440 			ret = chn_setformat(wrch,
1441 			    SND_FORMAT(wrch->format, *arg_i, 0));
1442 			tmp = (AFMT_CHANNEL(wrch->format) > 1)? 1 : 0;
1443 			CHN_UNLOCK(wrch);
1444 		}
1445 		if (rdch && ret == 0) {
1446 			CHN_LOCK(rdch);
1447 			ret = chn_setformat(rdch,
1448 			    SND_FORMAT(rdch->format, *arg_i, 0));
1449 			if (tmp == -1)
1450 				tmp = (AFMT_CHANNEL(rdch->format) > 1)? 1 : 0;
1451 			CHN_UNLOCK(rdch);
1452 		}
1453 		PCM_RELEASE_QUICK(d);
1454 		*arg_i = tmp;
1455 		break;
1456 
1457     	case SOUND_PCM_WRITE_CHANNELS:
1458 /*	case SNDCTL_DSP_CHANNELS: ( == SOUND_PCM_WRITE_CHANNELS) */
1459 		if (*arg_i < 0) {
1460 			*arg_i = 0;
1461 			ret = EINVAL;
1462 			break;
1463 		}
1464 		if (*arg_i != 0) {
1465 			struct pcmchan_matrix *m;
1466 			uint32_t ext;
1467 
1468 			tmp = 0;
1469 			if (*arg_i > SND_CHN_MAX)
1470 				*arg_i = SND_CHN_MAX;
1471 
1472 			m = feeder_matrix_default_channel_map(*arg_i);
1473 			if (m != NULL)
1474 				ext = m->ext;
1475 			else
1476 				ext = 0;
1477 
1478 			PCM_ACQUIRE_QUICK(d);
1479 	  		if (wrch) {
1480 				CHN_LOCK(wrch);
1481 				ret = chn_setformat(wrch,
1482 				    SND_FORMAT(wrch->format, *arg_i, ext));
1483 				tmp = AFMT_CHANNEL(wrch->format);
1484 				CHN_UNLOCK(wrch);
1485 			}
1486 			if (rdch && ret == 0) {
1487 				CHN_LOCK(rdch);
1488 				ret = chn_setformat(rdch,
1489 				    SND_FORMAT(rdch->format, *arg_i, ext));
1490 				if (tmp == 0)
1491 					tmp = AFMT_CHANNEL(rdch->format);
1492 				CHN_UNLOCK(rdch);
1493 			}
1494 			PCM_RELEASE_QUICK(d);
1495 			*arg_i = tmp;
1496 		} else {
1497 			chn = wrch ? wrch : rdch;
1498 			CHN_LOCK(chn);
1499 			*arg_i = AFMT_CHANNEL(chn->format);
1500 			CHN_UNLOCK(chn);
1501 		}
1502 		break;
1503 
1504     	case SOUND_PCM_READ_CHANNELS:
1505 		chn = wrch ? wrch : rdch;
1506 		if (chn) {
1507 			CHN_LOCK(chn);
1508 			*arg_i = AFMT_CHANNEL(chn->format);
1509 			CHN_UNLOCK(chn);
1510 		} else {
1511 			*arg_i = 0;
1512 			ret = EINVAL;
1513 		}
1514 		break;
1515 
1516     	case SNDCTL_DSP_GETFMTS:	/* returns a mask of supported fmts */
1517 		chn = wrch ? wrch : rdch;
1518 		if (chn) {
1519 			CHN_LOCK(chn);
1520 			*arg_i = chn_getformats(chn);
1521 			CHN_UNLOCK(chn);
1522 		} else {
1523 			*arg_i = 0;
1524 			ret = EINVAL;
1525 		}
1526 		break;
1527 
1528     	case SNDCTL_DSP_SETFMT:	/* sets _one_ format */
1529 		if (*arg_i != AFMT_QUERY) {
1530 			tmp = 0;
1531 			PCM_ACQUIRE_QUICK(d);
1532 			if (wrch) {
1533 				CHN_LOCK(wrch);
1534 				ret = chn_setformat(wrch, SND_FORMAT(*arg_i,
1535 				    AFMT_CHANNEL(wrch->format),
1536 				    AFMT_EXTCHANNEL(wrch->format)));
1537 				tmp = wrch->format;
1538 				CHN_UNLOCK(wrch);
1539 			}
1540 			if (rdch && ret == 0) {
1541 				CHN_LOCK(rdch);
1542 				ret = chn_setformat(rdch, SND_FORMAT(*arg_i,
1543 				    AFMT_CHANNEL(rdch->format),
1544 				    AFMT_EXTCHANNEL(rdch->format)));
1545 				if (tmp == 0)
1546 					tmp = rdch->format;
1547 				CHN_UNLOCK(rdch);
1548 			}
1549 			PCM_RELEASE_QUICK(d);
1550 			*arg_i = AFMT_ENCODING(tmp);
1551 		} else {
1552 			chn = wrch ? wrch : rdch;
1553 			CHN_LOCK(chn);
1554 			*arg_i = AFMT_ENCODING(chn->format);
1555 			CHN_UNLOCK(chn);
1556 		}
1557 		break;
1558 
1559     	case SNDCTL_DSP_SETFRAGMENT:
1560 		DEB(printf("SNDCTL_DSP_SETFRAGMENT 0x%08x\n", *(int *)arg));
1561 		{
1562 			uint32_t fragln = (*arg_i) & 0x0000ffff;
1563 			uint32_t maxfrags = ((*arg_i) & 0xffff0000) >> 16;
1564 			uint32_t fragsz;
1565 			uint32_t r_maxfrags, r_fragsz;
1566 
1567 			RANGE(fragln, 4, 16);
1568 			fragsz = 1 << fragln;
1569 
1570 			if (maxfrags == 0)
1571 				maxfrags = CHN_2NDBUFMAXSIZE / fragsz;
1572 			if (maxfrags < 2)
1573 				maxfrags = 2;
1574 			if (maxfrags * fragsz > CHN_2NDBUFMAXSIZE)
1575 				maxfrags = CHN_2NDBUFMAXSIZE / fragsz;
1576 
1577 			DEB(printf("SNDCTL_DSP_SETFRAGMENT %d frags, %d sz\n", maxfrags, fragsz));
1578 			PCM_ACQUIRE_QUICK(d);
1579 		    	if (rdch) {
1580 				CHN_LOCK(rdch);
1581 				ret = chn_setblocksize(rdch, maxfrags, fragsz);
1582 				r_maxfrags = sndbuf_getblkcnt(rdch->bufsoft);
1583 				r_fragsz = sndbuf_getblksz(rdch->bufsoft);
1584 				CHN_UNLOCK(rdch);
1585 			} else {
1586 				r_maxfrags = maxfrags;
1587 				r_fragsz = fragsz;
1588 			}
1589 		    	if (wrch && ret == 0) {
1590 				CHN_LOCK(wrch);
1591 				ret = chn_setblocksize(wrch, maxfrags, fragsz);
1592  				maxfrags = sndbuf_getblkcnt(wrch->bufsoft);
1593 				fragsz = sndbuf_getblksz(wrch->bufsoft);
1594 				CHN_UNLOCK(wrch);
1595 			} else { /* use whatever came from the read channel */
1596 				maxfrags = r_maxfrags;
1597 				fragsz = r_fragsz;
1598 			}
1599 			PCM_RELEASE_QUICK(d);
1600 
1601 			fragln = 0;
1602 			while (fragsz > 1) {
1603 				fragln++;
1604 				fragsz >>= 1;
1605 			}
1606 	    		*arg_i = (maxfrags << 16) | fragln;
1607 		}
1608 		break;
1609 
1610     	case SNDCTL_DSP_GETISPACE:
1611 		/* return the size of data available in the input queue */
1612 		{
1613 	    		audio_buf_info *a = (audio_buf_info *)arg;
1614 	    		if (rdch) {
1615 	        		struct snd_dbuf *bs = rdch->bufsoft;
1616 
1617 				CHN_LOCK(rdch);
1618 				a->bytes = sndbuf_getready(bs);
1619 	        		a->fragments = a->bytes / sndbuf_getblksz(bs);
1620 	        		a->fragstotal = sndbuf_getblkcnt(bs);
1621 	        		a->fragsize = sndbuf_getblksz(bs);
1622 				CHN_UNLOCK(rdch);
1623 	    		} else
1624 				ret = EINVAL;
1625 		}
1626 		break;
1627 
1628     	case SNDCTL_DSP_GETOSPACE:
1629 		/* return space available in the output queue */
1630 		{
1631 	    		audio_buf_info *a = (audio_buf_info *)arg;
1632 	    		if (wrch) {
1633 	        		struct snd_dbuf *bs = wrch->bufsoft;
1634 
1635 				CHN_LOCK(wrch);
1636 				/* XXX abusive DMA update: chn_wrupdate(wrch); */
1637 				a->bytes = sndbuf_getfree(bs);
1638 	        		a->fragments = a->bytes / sndbuf_getblksz(bs);
1639 	        		a->fragstotal = sndbuf_getblkcnt(bs);
1640 	        		a->fragsize = sndbuf_getblksz(bs);
1641 				CHN_UNLOCK(wrch);
1642 	    		} else
1643 				ret = EINVAL;
1644 		}
1645 		break;
1646 
1647     	case SNDCTL_DSP_GETIPTR:
1648 		{
1649 	    		count_info *a = (count_info *)arg;
1650 	    		if (rdch) {
1651 	        		struct snd_dbuf *bs = rdch->bufsoft;
1652 
1653 				CHN_LOCK(rdch);
1654 				/* XXX abusive DMA update: chn_rdupdate(rdch); */
1655 	        		a->bytes = sndbuf_gettotal(bs);
1656 	        		a->blocks = sndbuf_getblocks(bs) - rdch->blocks;
1657 	        		a->ptr = sndbuf_getreadyptr(bs);
1658 				rdch->blocks = sndbuf_getblocks(bs);
1659 				CHN_UNLOCK(rdch);
1660 	    		} else
1661 				ret = EINVAL;
1662 		}
1663 		break;
1664 
1665     	case SNDCTL_DSP_GETOPTR:
1666 		{
1667 	    		count_info *a = (count_info *)arg;
1668 	    		if (wrch) {
1669 	        		struct snd_dbuf *bs = wrch->bufsoft;
1670 
1671 				CHN_LOCK(wrch);
1672 				/* XXX abusive DMA update: chn_wrupdate(wrch); */
1673 	        		a->bytes = sndbuf_gettotal(bs);
1674 	        		a->blocks = sndbuf_getblocks(bs) - wrch->blocks;
1675 	        		a->ptr = sndbuf_getreadyptr(bs);
1676 				wrch->blocks = sndbuf_getblocks(bs);
1677 				CHN_UNLOCK(wrch);
1678 	    		} else
1679 				ret = EINVAL;
1680 		}
1681 		break;
1682 
1683     	case SNDCTL_DSP_GETCAPS:
1684 		PCM_LOCK(d);
1685 		*arg_i = PCM_CAP_REALTIME | PCM_CAP_MMAP | PCM_CAP_TRIGGER;
1686 		if (rdch && wrch && !(dsp_get_flags(i_dev) & SD_F_SIMPLEX))
1687 			*arg_i |= PCM_CAP_DUPLEX;
1688 		PCM_UNLOCK(d);
1689 		break;
1690 
1691     	case SOUND_PCM_READ_BITS:
1692 		chn = wrch ? wrch : rdch;
1693 		if (chn) {
1694 			CHN_LOCK(chn);
1695 			if (chn->format & AFMT_8BIT)
1696 				*arg_i = 8;
1697 			else if (chn->format & AFMT_16BIT)
1698 				*arg_i = 16;
1699 			else if (chn->format & AFMT_24BIT)
1700 				*arg_i = 24;
1701 			else if (chn->format & AFMT_32BIT)
1702 				*arg_i = 32;
1703 			else
1704 				ret = EINVAL;
1705 			CHN_UNLOCK(chn);
1706 		} else {
1707 			*arg_i = 0;
1708 			ret = EINVAL;
1709 		}
1710 		break;
1711 
1712     	case SNDCTL_DSP_SETTRIGGER:
1713 		if (rdch) {
1714 			CHN_LOCK(rdch);
1715 			rdch->flags &= ~CHN_F_NOTRIGGER;
1716 		    	if (*arg_i & PCM_ENABLE_INPUT)
1717 				chn_start(rdch, 1);
1718 			else {
1719 				chn_abort(rdch);
1720 				chn_resetbuf(rdch);
1721 				rdch->flags |= CHN_F_NOTRIGGER;
1722 			}
1723 			CHN_UNLOCK(rdch);
1724 		}
1725 		if (wrch) {
1726 			CHN_LOCK(wrch);
1727 			wrch->flags &= ~CHN_F_NOTRIGGER;
1728 		    	if (*arg_i & PCM_ENABLE_OUTPUT)
1729 				chn_start(wrch, 1);
1730 			else {
1731 				chn_abort(wrch);
1732 				chn_resetbuf(wrch);
1733 				wrch->flags |= CHN_F_NOTRIGGER;
1734 			}
1735 			CHN_UNLOCK(wrch);
1736 		}
1737 		break;
1738 
1739     	case SNDCTL_DSP_GETTRIGGER:
1740 		*arg_i = 0;
1741 		if (wrch) {
1742 			CHN_LOCK(wrch);
1743 			if (wrch->flags & CHN_F_TRIGGERED)
1744 				*arg_i |= PCM_ENABLE_OUTPUT;
1745 			CHN_UNLOCK(wrch);
1746 		}
1747 		if (rdch) {
1748 			CHN_LOCK(rdch);
1749 			if (rdch->flags & CHN_F_TRIGGERED)
1750 				*arg_i |= PCM_ENABLE_INPUT;
1751 			CHN_UNLOCK(rdch);
1752 		}
1753 		break;
1754 
1755 	case SNDCTL_DSP_GETODELAY:
1756 		if (wrch) {
1757 	        	struct snd_dbuf *bs = wrch->bufsoft;
1758 
1759 			CHN_LOCK(wrch);
1760 			/* XXX abusive DMA update: chn_wrupdate(wrch); */
1761 			*arg_i = sndbuf_getready(bs);
1762 			CHN_UNLOCK(wrch);
1763 		} else
1764 			ret = EINVAL;
1765 		break;
1766 
1767     	case SNDCTL_DSP_POST:
1768 		if (wrch) {
1769 			CHN_LOCK(wrch);
1770 			wrch->flags &= ~CHN_F_NOTRIGGER;
1771 			chn_start(wrch, 1);
1772 			CHN_UNLOCK(wrch);
1773 		}
1774 		break;
1775 
1776 	case SNDCTL_DSP_SETDUPLEX:
1777 		/*
1778 		 * switch to full-duplex mode if card is in half-duplex
1779 		 * mode and is able to work in full-duplex mode
1780 		 */
1781 		PCM_LOCK(d);
1782 		if (rdch && wrch && (dsp_get_flags(i_dev) & SD_F_SIMPLEX))
1783 			dsp_set_flags(i_dev, dsp_get_flags(i_dev)^SD_F_SIMPLEX);
1784 		PCM_UNLOCK(d);
1785 		break;
1786 
1787 	/*
1788 	 * The following four ioctls are simple wrappers around mixer_ioctl
1789 	 * with no further processing.  xcmd is short for "translated
1790 	 * command".
1791 	 */
1792 	case SNDCTL_DSP_GETRECVOL:
1793 		if (xcmd == 0) {
1794 			xcmd = SOUND_MIXER_READ_RECLEV;
1795 			chn = rdch;
1796 		}
1797 		/* FALLTHROUGH */
1798 	case SNDCTL_DSP_SETRECVOL:
1799 		if (xcmd == 0) {
1800 			xcmd = SOUND_MIXER_WRITE_RECLEV;
1801 			chn = rdch;
1802 		}
1803 		/* FALLTHROUGH */
1804 	case SNDCTL_DSP_GETPLAYVOL:
1805 		if (xcmd == 0) {
1806 			xcmd = SOUND_MIXER_READ_PCM;
1807 			chn = wrch;
1808 		}
1809 		/* FALLTHROUGH */
1810 	case SNDCTL_DSP_SETPLAYVOL:
1811 		if (xcmd == 0) {
1812 			xcmd = SOUND_MIXER_WRITE_PCM;
1813 			chn = wrch;
1814 		}
1815 
1816 		ret = dsp_ioctl_channel(i_dev, chn, xcmd, arg);
1817 		if (ret != -1) {
1818 			PCM_GIANT_EXIT(d);
1819 			return (ret);
1820 		}
1821 
1822 		if (d->mixer_dev != NULL) {
1823 			PCM_ACQUIRE_QUICK(d);
1824 			ret = mixer_ioctl_cmd(d->mixer_dev, xcmd, arg, -1, td,
1825 			    MIXER_CMD_DIRECT);
1826 			PCM_RELEASE_QUICK(d);
1827 		} else
1828 			ret = ENOTSUP;
1829 
1830 		break;
1831 
1832 	case SNDCTL_DSP_GET_RECSRC_NAMES:
1833 	case SNDCTL_DSP_GET_RECSRC:
1834 	case SNDCTL_DSP_SET_RECSRC:
1835 		if (d->mixer_dev != NULL) {
1836 			PCM_ACQUIRE_QUICK(d);
1837 			ret = mixer_ioctl_cmd(d->mixer_dev, cmd, arg, -1, td,
1838 			    MIXER_CMD_DIRECT);
1839 			PCM_RELEASE_QUICK(d);
1840 		} else
1841 			ret = ENOTSUP;
1842 		break;
1843 
1844 	/*
1845 	 * The following 3 ioctls aren't very useful at the moment.  For
1846 	 * now, only a single channel is associated with a cdev (/dev/dspN
1847 	 * instance), so there's only a single output routing to use (i.e.,
1848 	 * the wrch bound to this cdev).
1849 	 */
1850 	case SNDCTL_DSP_GET_PLAYTGT_NAMES:
1851 		{
1852 			oss_mixer_enuminfo *ei;
1853 			ei = (oss_mixer_enuminfo *)arg;
1854 			ei->dev = 0;
1855 			ei->ctrl = 0;
1856 			ei->version = 0; /* static for now */
1857 			ei->strindex[0] = 0;
1858 
1859 			if (wrch != NULL) {
1860 				ei->nvalues = 1;
1861 				strlcpy(ei->strings, wrch->name,
1862 					sizeof(ei->strings));
1863 			} else {
1864 				ei->nvalues = 0;
1865 				ei->strings[0] = '\0';
1866 			}
1867 		}
1868 		break;
1869 	case SNDCTL_DSP_GET_PLAYTGT:
1870 	case SNDCTL_DSP_SET_PLAYTGT:	/* yes, they are the same for now */
1871 		/*
1872 		 * Re: SET_PLAYTGT
1873 		 *   OSSv4: "The value that was accepted by the device will
1874 		 *   be returned back in the variable pointed by the
1875 		 *   argument."
1876 		 */
1877 		if (wrch != NULL)
1878 			*arg_i = 0;
1879 		else
1880 			ret = EINVAL;
1881 		break;
1882 
1883 	case SNDCTL_DSP_SILENCE:
1884 	/*
1885 	 * Flush the software (pre-feed) buffer, but try to minimize playback
1886 	 * interruption.  (I.e., record unplayed samples with intent to
1887 	 * restore by SNDCTL_DSP_SKIP.) Intended for application "pause"
1888 	 * functionality.
1889 	 */
1890 		if (wrch == NULL)
1891 			ret = EINVAL;
1892 		else {
1893 			struct snd_dbuf *bs;
1894 			CHN_LOCK(wrch);
1895 			while (wrch->inprog != 0)
1896 				cv_wait(&wrch->cv, wrch->lock);
1897 			bs = wrch->bufsoft;
1898 			if ((bs->shadbuf != NULL) && (sndbuf_getready(bs) > 0)) {
1899 				bs->sl = sndbuf_getready(bs);
1900 				sndbuf_dispose(bs, bs->shadbuf, sndbuf_getready(bs));
1901 				sndbuf_fillsilence(bs);
1902 				chn_start(wrch, 0);
1903 			}
1904 			CHN_UNLOCK(wrch);
1905 		}
1906 		break;
1907 
1908 	case SNDCTL_DSP_SKIP:
1909 	/*
1910 	 * OSSv4 docs: "This ioctl call discards all unplayed samples in the
1911 	 * playback buffer by moving the current write position immediately
1912 	 * before the point where the device is currently reading the samples."
1913 	 */
1914 		if (wrch == NULL)
1915 			ret = EINVAL;
1916 		else {
1917 			struct snd_dbuf *bs;
1918 			CHN_LOCK(wrch);
1919 			while (wrch->inprog != 0)
1920 				cv_wait(&wrch->cv, wrch->lock);
1921 			bs = wrch->bufsoft;
1922 			if ((bs->shadbuf != NULL) && (bs->sl > 0)) {
1923 				sndbuf_softreset(bs);
1924 				sndbuf_acquire(bs, bs->shadbuf, bs->sl);
1925 				bs->sl = 0;
1926 				chn_start(wrch, 0);
1927 			}
1928 			CHN_UNLOCK(wrch);
1929 		}
1930 		break;
1931 
1932 	case SNDCTL_DSP_CURRENT_OPTR:
1933 	case SNDCTL_DSP_CURRENT_IPTR:
1934 	/**
1935 	 * @note Changing formats resets the buffer counters, which differs
1936 	 * 	 from the 4Front drivers.  However, I don't expect this to be
1937 	 * 	 much of a problem.
1938 	 *
1939 	 * @note In a test where @c CURRENT_OPTR is called immediately after write
1940 	 * 	 returns, this driver is about 32K samples behind whereas
1941 	 * 	 4Front's is about 8K samples behind.  Should determine source
1942 	 * 	 of discrepancy, even if only out of curiosity.
1943 	 *
1944 	 * @todo Actually test SNDCTL_DSP_CURRENT_IPTR.
1945 	 */
1946 		chn = (cmd == SNDCTL_DSP_CURRENT_OPTR) ? wrch : rdch;
1947 		if (chn == NULL)
1948 			ret = EINVAL;
1949 		else {
1950 			struct snd_dbuf *bs;
1951 			/* int tmp; */
1952 
1953 			oss_count_t *oc = (oss_count_t *)arg;
1954 
1955 			CHN_LOCK(chn);
1956 			bs = chn->bufsoft;
1957 #if 0
1958 			tmp = (sndbuf_getsize(b) + chn_getptr(chn) - sndbuf_gethwptr(b)) % sndbuf_getsize(b);
1959 			oc->samples = (sndbuf_gettotal(b) + tmp) / sndbuf_getalign(b);
1960 			oc->fifo_samples = (sndbuf_getready(b) - tmp) / sndbuf_getalign(b);
1961 #else
1962 			oc->samples = sndbuf_gettotal(bs) / sndbuf_getalign(bs);
1963 			oc->fifo_samples = sndbuf_getready(bs) / sndbuf_getalign(bs);
1964 #endif
1965 			CHN_UNLOCK(chn);
1966 		}
1967 		break;
1968 
1969 	case SNDCTL_DSP_HALT_OUTPUT:
1970 	case SNDCTL_DSP_HALT_INPUT:
1971 		chn = (cmd == SNDCTL_DSP_HALT_OUTPUT) ? wrch : rdch;
1972 		if (chn == NULL)
1973 			ret = EINVAL;
1974 		else {
1975 			CHN_LOCK(chn);
1976 			chn_abort(chn);
1977 			CHN_UNLOCK(chn);
1978 		}
1979 		break;
1980 
1981 	case SNDCTL_DSP_LOW_WATER:
1982 	/*
1983 	 * Set the number of bytes required to attract attention by
1984 	 * select/poll.
1985 	 */
1986 		if (wrch != NULL) {
1987 			CHN_LOCK(wrch);
1988 			wrch->lw = (*arg_i > 1) ? *arg_i : 1;
1989 			CHN_UNLOCK(wrch);
1990 		}
1991 		if (rdch != NULL) {
1992 			CHN_LOCK(rdch);
1993 			rdch->lw = (*arg_i > 1) ? *arg_i : 1;
1994 			CHN_UNLOCK(rdch);
1995 		}
1996 		break;
1997 
1998 	case SNDCTL_DSP_GETERROR:
1999 	/*
2000 	 * OSSv4 docs:  "All errors and counters will automatically be
2001 	 * cleared to zeroes after the call so each call will return only
2002 	 * the errors that occurred after the previous invocation. ... The
2003 	 * play_underruns and rec_overrun fields are the only usefull fields
2004 	 * returned by OSS 4.0."
2005 	 */
2006 		{
2007 			audio_errinfo *ei = (audio_errinfo *)arg;
2008 
2009 			bzero((void *)ei, sizeof(*ei));
2010 
2011 			if (wrch != NULL) {
2012 				CHN_LOCK(wrch);
2013 				ei->play_underruns = wrch->xruns;
2014 				wrch->xruns = 0;
2015 				CHN_UNLOCK(wrch);
2016 			}
2017 			if (rdch != NULL) {
2018 				CHN_LOCK(rdch);
2019 				ei->rec_overruns = rdch->xruns;
2020 				rdch->xruns = 0;
2021 				CHN_UNLOCK(rdch);
2022 			}
2023 		}
2024 		break;
2025 
2026 	case SNDCTL_DSP_SYNCGROUP:
2027 		PCM_ACQUIRE_QUICK(d);
2028 		ret = dsp_oss_syncgroup(wrch, rdch, (oss_syncgroup *)arg);
2029 		PCM_RELEASE_QUICK(d);
2030 		break;
2031 
2032 	case SNDCTL_DSP_SYNCSTART:
2033 		PCM_ACQUIRE_QUICK(d);
2034 		ret = dsp_oss_syncstart(*arg_i);
2035 		PCM_RELEASE_QUICK(d);
2036 		break;
2037 
2038 	case SNDCTL_DSP_POLICY:
2039 		PCM_ACQUIRE_QUICK(d);
2040 		ret = dsp_oss_policy(wrch, rdch, *arg_i);
2041 		PCM_RELEASE_QUICK(d);
2042 		break;
2043 
2044 	case SNDCTL_DSP_COOKEDMODE:
2045 		PCM_ACQUIRE_QUICK(d);
2046 		if (!(dsp_get_flags(i_dev) & SD_F_BITPERFECT))
2047 			ret = dsp_oss_cookedmode(wrch, rdch, *arg_i);
2048 		PCM_RELEASE_QUICK(d);
2049 		break;
2050 	case SNDCTL_DSP_GET_CHNORDER:
2051 		PCM_ACQUIRE_QUICK(d);
2052 		ret = dsp_oss_getchnorder(wrch, rdch, (unsigned long long *)arg);
2053 		PCM_RELEASE_QUICK(d);
2054 		break;
2055 	case SNDCTL_DSP_SET_CHNORDER:
2056 		PCM_ACQUIRE_QUICK(d);
2057 		ret = dsp_oss_setchnorder(wrch, rdch, (unsigned long long *)arg);
2058 		PCM_RELEASE_QUICK(d);
2059 		break;
2060 	case SNDCTL_DSP_GETCHANNELMASK:		/* XXX vlc */
2061 		PCM_ACQUIRE_QUICK(d);
2062 		ret = dsp_oss_getchannelmask(wrch, rdch, (int *)arg);
2063 		PCM_RELEASE_QUICK(d);
2064 		break;
2065 	case SNDCTL_DSP_BIND_CHANNEL:		/* XXX what?!? */
2066 		ret = EINVAL;
2067 		break;
2068 #ifdef	OSSV4_EXPERIMENT
2069 	/*
2070 	 * XXX The following ioctls are not yet supported and just return
2071 	 * EINVAL.
2072 	 */
2073 	case SNDCTL_DSP_GETOPEAKS:
2074 	case SNDCTL_DSP_GETIPEAKS:
2075 		chn = (cmd == SNDCTL_DSP_GETOPEAKS) ? wrch : rdch;
2076 		if (chn == NULL)
2077 			ret = EINVAL;
2078 		else {
2079 			oss_peaks_t *op = (oss_peaks_t *)arg;
2080 			int lpeak, rpeak;
2081 
2082 			CHN_LOCK(chn);
2083 			ret = chn_getpeaks(chn, &lpeak, &rpeak);
2084 			if (ret == -1)
2085 				ret = EINVAL;
2086 			else {
2087 				(*op)[0] = lpeak;
2088 				(*op)[1] = rpeak;
2089 			}
2090 			CHN_UNLOCK(chn);
2091 		}
2092 		break;
2093 
2094 	/*
2095 	 * XXX Once implemented, revisit this for proper cv protection
2096 	 *     (if necessary).
2097 	 */
2098 	case SNDCTL_GETLABEL:
2099 		ret = dsp_oss_getlabel(wrch, rdch, (oss_label_t *)arg);
2100 		break;
2101 	case SNDCTL_SETLABEL:
2102 		ret = dsp_oss_setlabel(wrch, rdch, (oss_label_t *)arg);
2103 		break;
2104 	case SNDCTL_GETSONG:
2105 		ret = dsp_oss_getsong(wrch, rdch, (oss_longname_t *)arg);
2106 		break;
2107 	case SNDCTL_SETSONG:
2108 		ret = dsp_oss_setsong(wrch, rdch, (oss_longname_t *)arg);
2109 		break;
2110 	case SNDCTL_SETNAME:
2111 		ret = dsp_oss_setname(wrch, rdch, (oss_longname_t *)arg);
2112 		break;
2113 #if 0
2114 	/**
2115 	 * @note The S/PDIF interface ioctls, @c SNDCTL_DSP_READCTL and
2116 	 * @c SNDCTL_DSP_WRITECTL have been omitted at the suggestion of
2117 	 * 4Front Technologies.
2118 	 */
2119 	case SNDCTL_DSP_READCTL:
2120 	case SNDCTL_DSP_WRITECTL:
2121 		ret = EINVAL;
2122 		break;
2123 #endif	/* !0 (explicitly omitted ioctls) */
2124 
2125 #endif	/* !OSSV4_EXPERIMENT */
2126     	case SNDCTL_DSP_MAPINBUF:
2127     	case SNDCTL_DSP_MAPOUTBUF:
2128     	case SNDCTL_DSP_SETSYNCRO:
2129 		/* undocumented */
2130 
2131     	case SNDCTL_DSP_SUBDIVIDE:
2132     	case SOUND_PCM_WRITE_FILTER:
2133     	case SOUND_PCM_READ_FILTER:
2134 		/* dunno what these do, don't sound important */
2135 
2136     	default:
2137 		DEB(printf("default ioctl fn 0x%08lx fail\n", cmd));
2138 		ret = EINVAL;
2139 		break;
2140     	}
2141 
2142 	PCM_GIANT_LEAVE(d);
2143 
2144     	return (ret);
2145 }
2146 
2147 static int
2148 dsp_poll(struct cdev *i_dev, int events, struct thread *td)
2149 {
2150 	struct snddev_info *d;
2151 	struct pcm_channel *wrch, *rdch;
2152 	int ret, e;
2153 
2154 	d = dsp_get_info(i_dev);
2155 	if (!DSP_REGISTERED(d, i_dev))
2156 		return (EBADF);
2157 
2158 	PCM_GIANT_ENTER(d);
2159 
2160 	wrch = NULL;
2161 	rdch = NULL;
2162 	ret = 0;
2163 
2164 	getchns(i_dev, &rdch, &wrch, SD_F_PRIO_RD | SD_F_PRIO_WR);
2165 
2166 	if (wrch != NULL && !(wrch->flags & CHN_F_DEAD)) {
2167 		e = (events & (POLLOUT | POLLWRNORM));
2168 		if (e)
2169 			ret |= chn_poll(wrch, e, td);
2170 	}
2171 
2172 	if (rdch != NULL && !(rdch->flags & CHN_F_DEAD)) {
2173 		e = (events & (POLLIN | POLLRDNORM));
2174 		if (e)
2175 			ret |= chn_poll(rdch, e, td);
2176 	}
2177 
2178 	relchns(i_dev, rdch, wrch, SD_F_PRIO_RD | SD_F_PRIO_WR);
2179 
2180 	PCM_GIANT_LEAVE(d);
2181 
2182 	return (ret);
2183 }
2184 
2185 static int
2186 dsp_mmap(struct cdev *i_dev, vm_ooffset_t offset, vm_paddr_t *paddr,
2187     int nprot, vm_memattr_t *memattr)
2188 {
2189 	struct snddev_info *d;
2190 	struct pcm_channel *wrch, *rdch, *c;
2191 
2192 	/*
2193 	 * Reject PROT_EXEC by default. It just doesn't makes sense.
2194 	 * Unfortunately, we have to give up this one due to linux_mmap
2195 	 * changes.
2196 	 *
2197 	 * http://lists.freebsd.org/pipermail/freebsd-emulation/2007-June/003698.html
2198 	 *
2199 	 */
2200 #ifdef SV_ABI_LINUX
2201 	if ((nprot & PROT_EXEC) && (dsp_mmap_allow_prot_exec < 0 ||
2202 	    (dsp_mmap_allow_prot_exec == 0 &&
2203 	    SV_CURPROC_ABI() != SV_ABI_LINUX)))
2204 #else
2205 	if ((nprot & PROT_EXEC) && dsp_mmap_allow_prot_exec < 1)
2206 #endif
2207 		return (-1);
2208 
2209 	d = dsp_get_info(i_dev);
2210 	if (!DSP_REGISTERED(d, i_dev))
2211 		return (-1);
2212 
2213 	PCM_GIANT_ENTER(d);
2214 
2215 	getchns(i_dev, &rdch, &wrch, SD_F_PRIO_RD | SD_F_PRIO_WR);
2216 
2217 	/*
2218 	 * XXX The linux api uses the nprot to select read/write buffer
2219 	 *     our vm system doesn't allow this, so force write buffer.
2220 	 *
2221 	 *     This is just a quack to fool full-duplex mmap, so that at
2222 	 *     least playback _or_ recording works. If you really got the
2223 	 *     urge to make _both_ work at the same time, avoid O_RDWR.
2224 	 *     Just open each direction separately and mmap() it.
2225 	 *
2226 	 *     Failure is not an option due to INVARIANTS check within
2227 	 *     device_pager.c, which means, we have to give up one over
2228 	 *     another.
2229 	 */
2230 	c = (wrch != NULL) ? wrch : rdch;
2231 
2232 	if (c == NULL || (c->flags & CHN_F_MMAP_INVALID) ||
2233 	    offset >= sndbuf_getsize(c->bufsoft) ||
2234 	    (wrch != NULL && (wrch->flags & CHN_F_MMAP_INVALID)) ||
2235 	    (rdch != NULL && (rdch->flags & CHN_F_MMAP_INVALID))) {
2236 		relchns(i_dev, rdch, wrch, SD_F_PRIO_RD | SD_F_PRIO_WR);
2237 		PCM_GIANT_EXIT(d);
2238 		return (-1);
2239 	}
2240 
2241 	/* XXX full-duplex quack. */
2242 	if (wrch != NULL)
2243 		wrch->flags |= CHN_F_MMAP;
2244 	if (rdch != NULL)
2245 		rdch->flags |= CHN_F_MMAP;
2246 
2247 	*paddr = vtophys(sndbuf_getbufofs(c->bufsoft, offset));
2248 	relchns(i_dev, rdch, wrch, SD_F_PRIO_RD | SD_F_PRIO_WR);
2249 
2250 	PCM_GIANT_LEAVE(d);
2251 
2252 	return (0);
2253 }
2254 
2255 /* So much for dev_stdclone() */
2256 static int
2257 dsp_stdclone(char *name, char *namep, char *sep, int use_sep, int *u, int *c)
2258 {
2259 	size_t len;
2260 
2261 	len = strlen(namep);
2262 
2263 	if (bcmp(name, namep, len) != 0)
2264 		return (ENODEV);
2265 
2266 	name += len;
2267 
2268 	if (isdigit(*name) == 0)
2269 		return (ENODEV);
2270 
2271 	len = strlen(sep);
2272 
2273 	if (*name == '0' && !(name[1] == '\0' || bcmp(name + 1, sep, len) == 0))
2274 		return (ENODEV);
2275 
2276 	for (*u = 0; isdigit(*name) != 0; name++) {
2277 		*u *= 10;
2278 		*u += *name - '0';
2279 		if (*u > dsp_umax)
2280 			return (ENODEV);
2281 	}
2282 
2283 	if (*name == '\0')
2284 		return ((use_sep == 0) ? 0 : ENODEV);
2285 
2286 	if (bcmp(name, sep, len) != 0 || isdigit(name[len]) == 0)
2287 		return (ENODEV);
2288 
2289 	name += len;
2290 
2291 	if (*name == '0' && name[1] != '\0')
2292 		return (ENODEV);
2293 
2294 	for (*c = 0; isdigit(*name) != 0; name++) {
2295 		*c *= 10;
2296 		*c += *name - '0';
2297 		if (*c > dsp_cmax)
2298 			return (ENODEV);
2299 	}
2300 
2301 	if (*name != '\0')
2302 		return (ENODEV);
2303 
2304 	return (0);
2305 }
2306 
2307 static void
2308 dsp_clone(void *arg,
2309 #if __FreeBSD_version >= 600034
2310     struct ucred *cred,
2311 #endif
2312     char *name, int namelen, struct cdev **dev)
2313 {
2314 	struct snddev_info *d;
2315 	struct snd_clone_entry *ce;
2316 	struct pcm_channel *c;
2317 	int i, unit, udcmask, cunit, devtype, devhw, devcmax, tumax;
2318 	char *devname, *devcmp, *devsep;
2319 
2320 	KASSERT(dsp_umax >= 0 && dsp_cmax >= 0, ("Uninitialized unit!"));
2321 
2322 	if (*dev != NULL)
2323 		return;
2324 
2325 	unit = -1;
2326 	cunit = -1;
2327 	devtype = -1;
2328 	devhw = 0;
2329 	devcmax = -1;
2330 	tumax = -1;
2331 	devname = NULL;
2332 	devsep = NULL;
2333 
2334 	for (i = 0; unit == -1 &&
2335 	    i < (sizeof(dsp_cdevs) / sizeof(dsp_cdevs[0])); i++) {
2336 		devtype = dsp_cdevs[i].type;
2337 		devcmp = dsp_cdevs[i].name;
2338 		devsep = dsp_cdevs[i].sep;
2339 		devname = dsp_cdevs[i].alias;
2340 		if (devname == NULL)
2341 			devname = devcmp;
2342 		devhw = dsp_cdevs[i].hw;
2343 		devcmax = dsp_cdevs[i].max - 1;
2344 		if (strcmp(name, devcmp) == 0)
2345 			unit = snd_unit;
2346 		else if (dsp_stdclone(name, devcmp, devsep,
2347 		    dsp_cdevs[i].use_sep, &unit, &cunit) != 0) {
2348 			unit = -1;
2349 			cunit = -1;
2350 		}
2351 	}
2352 
2353 	d = devclass_get_softc(pcm_devclass, unit);
2354 	if (!PCM_REGISTERED(d) || d->clones == NULL)
2355 		return;
2356 
2357 	/* XXX Need Giant magic entry ??? */
2358 
2359 	PCM_LOCK(d);
2360 	if (snd_clone_disabled(d->clones)) {
2361 		PCM_UNLOCK(d);
2362 		return;
2363 	}
2364 
2365 	PCM_WAIT(d);
2366 	PCM_ACQUIRE(d);
2367 	PCM_UNLOCK(d);
2368 
2369 	udcmask = snd_u2unit(unit) | snd_d2unit(devtype);
2370 
2371 	if (devhw != 0) {
2372 		KASSERT(devcmax <= dsp_cmax,
2373 		    ("overflow: devcmax=%d, dsp_cmax=%d", devcmax, dsp_cmax));
2374 		if (cunit > devcmax) {
2375 			PCM_RELEASE_QUICK(d);
2376 			return;
2377 		}
2378 		udcmask |= snd_c2unit(cunit);
2379 		CHN_FOREACH(c, d, channels.pcm) {
2380 			CHN_LOCK(c);
2381 			if (c->unit != udcmask) {
2382 				CHN_UNLOCK(c);
2383 				continue;
2384 			}
2385 			CHN_UNLOCK(c);
2386 			udcmask &= ~snd_c2unit(cunit);
2387 			/*
2388 			 * Temporarily increase clone maxunit to overcome
2389 			 * vchan flexibility.
2390 			 *
2391 			 * # sysctl dev.pcm.0.play.vchans=256
2392 			 * dev.pcm.0.play.vchans: 1 -> 256
2393 			 * # cat /dev/zero > /dev/dsp0.vp255 &
2394 			 * [1] 17296
2395 			 * # sysctl dev.pcm.0.play.vchans=0
2396 			 * dev.pcm.0.play.vchans: 256 -> 1
2397 			 * # fg
2398 			 * [1]  + running    cat /dev/zero > /dev/dsp0.vp255
2399 			 * ^C
2400 			 * # cat /dev/zero > /dev/dsp0.vp255
2401 			 * zsh: operation not supported: /dev/dsp0.vp255
2402 			 */
2403 			tumax = snd_clone_getmaxunit(d->clones);
2404 			if (cunit > tumax)
2405 				snd_clone_setmaxunit(d->clones, cunit);
2406 			else
2407 				tumax = -1;
2408 			goto dsp_clone_alloc;
2409 		}
2410 		/*
2411 		 * Ok, so we're requesting unallocated vchan, but still
2412 		 * within maximum vchan limit.
2413 		 */
2414 		if (((devtype == SND_DEV_DSPHW_VPLAY && d->pvchancount > 0) ||
2415 		    (devtype == SND_DEV_DSPHW_VREC && d->rvchancount > 0)) &&
2416 		    cunit < snd_maxautovchans) {
2417 			udcmask &= ~snd_c2unit(cunit);
2418 			tumax = snd_clone_getmaxunit(d->clones);
2419 			if (cunit > tumax)
2420 				snd_clone_setmaxunit(d->clones, cunit);
2421 			else
2422 				tumax = -1;
2423 			goto dsp_clone_alloc;
2424 		}
2425 		PCM_RELEASE_QUICK(d);
2426 		return;
2427 	}
2428 
2429 dsp_clone_alloc:
2430 	ce = snd_clone_alloc(d->clones, dev, &cunit, udcmask);
2431 	if (tumax != -1)
2432 		snd_clone_setmaxunit(d->clones, tumax);
2433 	if (ce != NULL) {
2434 		udcmask |= snd_c2unit(cunit);
2435 		*dev = make_dev(&dsp_cdevsw, PCMMINOR(udcmask),
2436 		    UID_ROOT, GID_WHEEL, 0666, "%s%d%s%d",
2437 		    devname, unit, devsep, cunit);
2438 		snd_clone_register(ce, *dev);
2439 	}
2440 
2441 	PCM_RELEASE_QUICK(d);
2442 
2443 	if (*dev != NULL)
2444 		dev_ref(*dev);
2445 }
2446 
2447 static void
2448 dsp_sysinit(void *p)
2449 {
2450 	if (dsp_ehtag != NULL)
2451 		return;
2452 	/* initialize unit numbering */
2453 	snd_unit_init();
2454 	dsp_umax = PCMMAXUNIT;
2455 	dsp_cmax = PCMMAXCHAN;
2456 	dsp_ehtag = EVENTHANDLER_REGISTER(dev_clone, dsp_clone, 0, 1000);
2457 }
2458 
2459 static void
2460 dsp_sysuninit(void *p)
2461 {
2462 	if (dsp_ehtag == NULL)
2463 		return;
2464 	EVENTHANDLER_DEREGISTER(dev_clone, dsp_ehtag);
2465 	dsp_ehtag = NULL;
2466 }
2467 
2468 SYSINIT(dsp_sysinit, SI_SUB_DRIVERS, SI_ORDER_MIDDLE, dsp_sysinit, NULL);
2469 SYSUNINIT(dsp_sysuninit, SI_SUB_DRIVERS, SI_ORDER_MIDDLE, dsp_sysuninit, NULL);
2470 
2471 char *
2472 dsp_unit2name(char *buf, size_t len, int unit)
2473 {
2474 	int i, dtype;
2475 
2476 	KASSERT(buf != NULL && len != 0,
2477 	    ("bogus buf=%p len=%ju", buf, (uintmax_t)len));
2478 
2479 	dtype = snd_unit2d(unit);
2480 
2481 	for (i = 0; i < (sizeof(dsp_cdevs) / sizeof(dsp_cdevs[0])); i++) {
2482 		if (dtype != dsp_cdevs[i].type || dsp_cdevs[i].alias != NULL)
2483 			continue;
2484 		snprintf(buf, len, "%s%d%s%d", dsp_cdevs[i].name,
2485 		    snd_unit2u(unit), dsp_cdevs[i].sep, snd_unit2c(unit));
2486 		return (buf);
2487 	}
2488 
2489 	return (NULL);
2490 }
2491 
2492 /**
2493  * @brief Handler for SNDCTL_AUDIOINFO.
2494  *
2495  * Gathers information about the audio device specified in ai->dev.  If
2496  * ai->dev == -1, then this function gathers information about the current
2497  * device.  If the call comes in on a non-audio device and ai->dev == -1,
2498  * return EINVAL.
2499  *
2500  * This routine is supposed to go practically straight to the hardware,
2501  * getting capabilities directly from the sound card driver, side-stepping
2502  * the intermediate channel interface.
2503  *
2504  * Note, however, that the usefulness of this command is significantly
2505  * decreased when requesting info about any device other than the one serving
2506  * the request. While each snddev_channel refers to a specific device node,
2507  * the converse is *not* true.  Currently, when a sound device node is opened,
2508  * the sound subsystem scans for an available audio channel (or channels, if
2509  * opened in read+write) and then assigns them to the si_drv[12] private
2510  * data fields.  As a result, any information returned linking a channel to
2511  * a specific character device isn't necessarily accurate.
2512  *
2513  * @note
2514  * Calling threads must not hold any snddev_info or pcm_channel locks.
2515  *
2516  * @param dev		device on which the ioctl was issued
2517  * @param ai		ioctl request data container
2518  *
2519  * @retval 0		success
2520  * @retval EINVAL	ai->dev specifies an invalid device
2521  *
2522  * @todo Verify correctness of Doxygen tags.  ;)
2523  */
2524 int
2525 dsp_oss_audioinfo(struct cdev *i_dev, oss_audioinfo *ai)
2526 {
2527 	struct pcmchan_caps *caps;
2528 	struct pcm_channel *ch;
2529 	struct snddev_info *d;
2530 	uint32_t fmts;
2531 	int i, nchan, *rates, minch, maxch;
2532 	char *devname, buf[CHN_NAMELEN];
2533 
2534 	/*
2535 	 * If probing the device that received the ioctl, make sure it's a
2536 	 * DSP device.  (Users may use this ioctl with /dev/mixer and
2537 	 * /dev/midi.)
2538 	 */
2539 	if (ai->dev == -1 && i_dev->si_devsw != &dsp_cdevsw)
2540 		return (EINVAL);
2541 
2542 	ch = NULL;
2543 	devname = NULL;
2544 	nchan = 0;
2545 	bzero(buf, sizeof(buf));
2546 
2547 	/*
2548 	 * Search for the requested audio device (channel).  Start by
2549 	 * iterating over pcm devices.
2550 	 */
2551 	for (i = 0; pcm_devclass != NULL &&
2552 	    i < devclass_get_maxunit(pcm_devclass); i++) {
2553 		d = devclass_get_softc(pcm_devclass, i);
2554 		if (!PCM_REGISTERED(d))
2555 			continue;
2556 
2557 		/* XXX Need Giant magic entry ??? */
2558 
2559 		/* See the note in function docblock */
2560 		PCM_UNLOCKASSERT(d);
2561 		PCM_LOCK(d);
2562 
2563 		CHN_FOREACH(ch, d, channels.pcm) {
2564 			CHN_UNLOCKASSERT(ch);
2565 			CHN_LOCK(ch);
2566 			if (ai->dev == -1) {
2567 				if (DSP_REGISTERED(d, i_dev) &&
2568 				    (ch == PCM_RDCH(i_dev) ||	/* record ch */
2569 				    ch == PCM_WRCH(i_dev))) {	/* playback ch */
2570 					devname = dsp_unit2name(buf,
2571 					    sizeof(buf), ch->unit);
2572 				}
2573 			} else if (ai->dev == nchan) {
2574 				devname = dsp_unit2name(buf, sizeof(buf),
2575 				    ch->unit);
2576 			}
2577 			if (devname != NULL)
2578 				break;
2579 			CHN_UNLOCK(ch);
2580 			++nchan;
2581 		}
2582 
2583 		if (devname != NULL) {
2584 			/*
2585 			 * At this point, the following synchronization stuff
2586 			 * has happened:
2587 			 * - a specific PCM device is locked.
2588 			 * - a specific audio channel has been locked, so be
2589 			 *   sure to unlock when exiting;
2590 			 */
2591 
2592 			caps = chn_getcaps(ch);
2593 
2594 			/*
2595 			 * With all handles collected, zero out the user's
2596 			 * container and begin filling in its fields.
2597 			 */
2598 			bzero((void *)ai, sizeof(oss_audioinfo));
2599 
2600 			ai->dev = nchan;
2601 			strlcpy(ai->name, ch->name,  sizeof(ai->name));
2602 
2603 			if ((ch->flags & CHN_F_BUSY) == 0)
2604 				ai->busy = 0;
2605 			else
2606 				ai->busy = (ch->direction == PCMDIR_PLAY) ? OPEN_WRITE : OPEN_READ;
2607 
2608 			/**
2609 			 * @note
2610 			 * @c cmd - OSSv4 docs: "Only supported under Linux at
2611 			 *    this moment." Cop-out, I know, but I'll save
2612 			 *    running around in the process table for later.
2613 			 *    Is there a risk of leaking information?
2614 			 */
2615 			ai->pid = ch->pid;
2616 
2617 			/*
2618 			 * These flags stolen from SNDCTL_DSP_GETCAPS handler.
2619 			 * Note, however, that a single channel operates in
2620 			 * only one direction, so PCM_CAP_DUPLEX is out.
2621 			 */
2622 			/**
2623 			 * @todo @c SNDCTL_AUDIOINFO::caps - Make drivers keep
2624 			 *       these in pcmchan::caps?
2625 			 */
2626 			ai->caps = PCM_CAP_REALTIME | PCM_CAP_MMAP | PCM_CAP_TRIGGER |
2627 			    ((ch->direction == PCMDIR_PLAY) ? PCM_CAP_OUTPUT : PCM_CAP_INPUT);
2628 
2629 			/*
2630 			 * Collect formats supported @b natively by the
2631 			 * device.  Also determine min/max channels.  (I.e.,
2632 			 * mono, stereo, or both?)
2633 			 *
2634 			 * If any channel is stereo, maxch = 2;
2635 			 * if all channels are stereo, minch = 2, too;
2636 			 * if any channel is mono, minch = 1;
2637 			 * and if all channels are mono, maxch = 1.
2638 			 */
2639 			minch = 0;
2640 			maxch = 0;
2641 			fmts = 0;
2642 			for (i = 0; caps->fmtlist[i]; i++) {
2643 				fmts |= caps->fmtlist[i];
2644 				if (AFMT_CHANNEL(caps->fmtlist[i]) > 1) {
2645 					minch = (minch == 0) ? 2 : minch;
2646 					maxch = 2;
2647 				} else {
2648 					minch = 1;
2649 					maxch = (maxch == 0) ? 1 : maxch;
2650 				}
2651 			}
2652 
2653 			if (ch->direction == PCMDIR_PLAY)
2654 				ai->oformats = fmts;
2655 			else
2656 				ai->iformats = fmts;
2657 
2658 			/**
2659 			 * @note
2660 			 * @c magic - OSSv4 docs: "Reserved for internal use
2661 			 *    by OSS."
2662 			 *
2663 			 * @par
2664 			 * @c card_number - OSSv4 docs: "Number of the sound
2665 			 *    card where this device belongs or -1 if this
2666 			 *    information is not available.  Applications
2667 			 *    should normally not use this field for any
2668 			 *    purpose."
2669 			 */
2670 			ai->card_number = -1;
2671 			/**
2672 			 * @todo @c song_name - depends first on
2673 			 *          SNDCTL_[GS]ETSONG @todo @c label - depends
2674 			 *          on SNDCTL_[GS]ETLABEL
2675 			 * @todo @c port_number - routing information?
2676 			 */
2677 			ai->port_number = -1;
2678 			ai->mixer_dev = (d->mixer_dev != NULL) ? PCMUNIT(d->mixer_dev) : -1;
2679 			/**
2680 			 * @note
2681 			 * @c real_device - OSSv4 docs:  "Obsolete."
2682 			 */
2683 			ai->real_device = -1;
2684 			strlcpy(ai->devnode, "/dev/", sizeof(ai->devnode));
2685 			strlcat(ai->devnode, devname, sizeof(ai->devnode));
2686 			ai->enabled = device_is_attached(d->dev) ? 1 : 0;
2687 			/**
2688 			 * @note
2689 			 * @c flags - OSSv4 docs: "Reserved for future use."
2690 			 *
2691 			 * @note
2692 			 * @c binding - OSSv4 docs: "Reserved for future use."
2693 			 *
2694 			 * @todo @c handle - haven't decided how to generate
2695 			 *       this yet; bus, vendor, device IDs?
2696 			 */
2697 			ai->min_rate = caps->minspeed;
2698 			ai->max_rate = caps->maxspeed;
2699 
2700 			ai->min_channels = minch;
2701 			ai->max_channels = maxch;
2702 
2703 			ai->nrates = chn_getrates(ch, &rates);
2704 			if (ai->nrates > OSS_MAX_SAMPLE_RATES)
2705 				ai->nrates = OSS_MAX_SAMPLE_RATES;
2706 
2707 			for (i = 0; i < ai->nrates; i++)
2708 				ai->rates[i] = rates[i];
2709 
2710 			ai->next_play_engine = 0;
2711 			ai->next_rec_engine = 0;
2712 
2713 			CHN_UNLOCK(ch);
2714 		}
2715 
2716 		PCM_UNLOCK(d);
2717 
2718 		if (devname != NULL)
2719 			return (0);
2720 	}
2721 
2722 	/* Exhausted the search -- nothing is locked, so return. */
2723 	return (EINVAL);
2724 }
2725 
2726 /**
2727  * @brief Assigns a PCM channel to a sync group.
2728  *
2729  * Sync groups are used to enable audio operations on multiple devices
2730  * simultaneously.  They may be used with any number of devices and may
2731  * span across applications.  Devices are added to groups with
2732  * the SNDCTL_DSP_SYNCGROUP ioctl, and operations are triggered with the
2733  * SNDCTL_DSP_SYNCSTART ioctl.
2734  *
2735  * If the @c id field of the @c group parameter is set to zero, then a new
2736  * sync group is created.  Otherwise, wrch and rdch (if set) are added to
2737  * the group specified.
2738  *
2739  * @todo As far as memory allocation, should we assume that things are
2740  * 	 okay and allocate with M_WAITOK before acquiring channel locks,
2741  * 	 freeing later if not?
2742  *
2743  * @param wrch	output channel associated w/ device (if any)
2744  * @param rdch	input channel associated w/ device (if any)
2745  * @param group Sync group parameters
2746  *
2747  * @retval 0		success
2748  * @retval non-zero	error to be propagated upstream
2749  */
2750 static int
2751 dsp_oss_syncgroup(struct pcm_channel *wrch, struct pcm_channel *rdch, oss_syncgroup *group)
2752 {
2753 	struct pcmchan_syncmember *smrd, *smwr;
2754 	struct pcmchan_syncgroup *sg;
2755 	int ret, sg_ids[3];
2756 
2757 	smrd = NULL;
2758 	smwr = NULL;
2759 	sg = NULL;
2760 	ret = 0;
2761 
2762 	/*
2763 	 * Free_unr() may sleep, so store released syncgroup IDs until after
2764 	 * all locks are released.
2765 	 */
2766 	sg_ids[0] = sg_ids[1] = sg_ids[2] = 0;
2767 
2768 	PCM_SG_LOCK();
2769 
2770 	/*
2771 	 * - Insert channel(s) into group's member list.
2772 	 * - Set CHN_F_NOTRIGGER on channel(s).
2773 	 * - Stop channel(s).
2774 	 */
2775 
2776 	/*
2777 	 * If device's channels are already mapped to a group, unmap them.
2778 	 */
2779 	if (wrch) {
2780 		CHN_LOCK(wrch);
2781 		sg_ids[0] = chn_syncdestroy(wrch);
2782 	}
2783 
2784 	if (rdch) {
2785 		CHN_LOCK(rdch);
2786 		sg_ids[1] = chn_syncdestroy(rdch);
2787 	}
2788 
2789 	/*
2790 	 * Verify that mode matches character device properites.
2791 	 *  - Bail if PCM_ENABLE_OUTPUT && wrch == NULL.
2792 	 *  - Bail if PCM_ENABLE_INPUT && rdch == NULL.
2793 	 */
2794 	if (((wrch == NULL) && (group->mode & PCM_ENABLE_OUTPUT)) ||
2795 	    ((rdch == NULL) && (group->mode & PCM_ENABLE_INPUT))) {
2796 		ret = EINVAL;
2797 		goto out;
2798 	}
2799 
2800 	/*
2801 	 * An id of zero indicates the user wants to create a new
2802 	 * syncgroup.
2803 	 */
2804 	if (group->id == 0) {
2805 		sg = (struct pcmchan_syncgroup *)malloc(sizeof(*sg), M_DEVBUF, M_NOWAIT);
2806 		if (sg != NULL) {
2807 			SLIST_INIT(&sg->members);
2808 			sg->id = alloc_unr(pcmsg_unrhdr);
2809 
2810 			group->id = sg->id;
2811 			SLIST_INSERT_HEAD(&snd_pcm_syncgroups, sg, link);
2812 		} else
2813 			ret = ENOMEM;
2814 	} else {
2815 		SLIST_FOREACH(sg, &snd_pcm_syncgroups, link) {
2816 			if (sg->id == group->id)
2817 				break;
2818 		}
2819 		if (sg == NULL)
2820 			ret = EINVAL;
2821 	}
2822 
2823 	/* Couldn't create or find a syncgroup.  Fail. */
2824 	if (sg == NULL)
2825 		goto out;
2826 
2827 	/*
2828 	 * Allocate a syncmember, assign it and a channel together, and
2829 	 * insert into syncgroup.
2830 	 */
2831 	if (group->mode & PCM_ENABLE_INPUT) {
2832 		smrd = (struct pcmchan_syncmember *)malloc(sizeof(*smrd), M_DEVBUF, M_NOWAIT);
2833 		if (smrd == NULL) {
2834 			ret = ENOMEM;
2835 			goto out;
2836 		}
2837 
2838 		SLIST_INSERT_HEAD(&sg->members, smrd, link);
2839 		smrd->parent = sg;
2840 		smrd->ch = rdch;
2841 
2842 		chn_abort(rdch);
2843 		rdch->flags |= CHN_F_NOTRIGGER;
2844 		rdch->sm = smrd;
2845 	}
2846 
2847 	if (group->mode & PCM_ENABLE_OUTPUT) {
2848 		smwr = (struct pcmchan_syncmember *)malloc(sizeof(*smwr), M_DEVBUF, M_NOWAIT);
2849 		if (smwr == NULL) {
2850 			ret = ENOMEM;
2851 			goto out;
2852 		}
2853 
2854 		SLIST_INSERT_HEAD(&sg->members, smwr, link);
2855 		smwr->parent = sg;
2856 		smwr->ch = wrch;
2857 
2858 		chn_abort(wrch);
2859 		wrch->flags |= CHN_F_NOTRIGGER;
2860 		wrch->sm = smwr;
2861 	}
2862 
2863 
2864 out:
2865 	if (ret != 0) {
2866 		if (smrd != NULL)
2867 			free(smrd, M_DEVBUF);
2868 		if ((sg != NULL) && SLIST_EMPTY(&sg->members)) {
2869 			sg_ids[2] = sg->id;
2870 			SLIST_REMOVE(&snd_pcm_syncgroups, sg, pcmchan_syncgroup, link);
2871 			free(sg, M_DEVBUF);
2872 		}
2873 
2874 		if (wrch)
2875 			wrch->sm = NULL;
2876 		if (rdch)
2877 			rdch->sm = NULL;
2878 	}
2879 
2880 	if (wrch)
2881 		CHN_UNLOCK(wrch);
2882 	if (rdch)
2883 		CHN_UNLOCK(rdch);
2884 
2885 	PCM_SG_UNLOCK();
2886 
2887 	if (sg_ids[0])
2888 		free_unr(pcmsg_unrhdr, sg_ids[0]);
2889 	if (sg_ids[1])
2890 		free_unr(pcmsg_unrhdr, sg_ids[1]);
2891 	if (sg_ids[2])
2892 		free_unr(pcmsg_unrhdr, sg_ids[2]);
2893 
2894 	return (ret);
2895 }
2896 
2897 /**
2898  * @brief Launch a sync group into action
2899  *
2900  * Sync groups are established via SNDCTL_DSP_SYNCGROUP.  This function
2901  * iterates over all members, triggering them along the way.
2902  *
2903  * @note Caller must not hold any channel locks.
2904  *
2905  * @param sg_id	sync group identifier
2906  *
2907  * @retval 0	success
2908  * @retval non-zero	error worthy of propagating upstream to user
2909  */
2910 static int
2911 dsp_oss_syncstart(int sg_id)
2912 {
2913 	struct pcmchan_syncmember *sm, *sm_tmp;
2914 	struct pcmchan_syncgroup *sg;
2915 	struct pcm_channel *c;
2916 	int ret, needlocks;
2917 
2918 	/* Get the synclists lock */
2919 	PCM_SG_LOCK();
2920 
2921 	do {
2922 		ret = 0;
2923 		needlocks = 0;
2924 
2925 		/* Search for syncgroup by ID */
2926 		SLIST_FOREACH(sg, &snd_pcm_syncgroups, link) {
2927 			if (sg->id == sg_id)
2928 				break;
2929 		}
2930 
2931 		/* Return EINVAL if not found */
2932 		if (sg == NULL) {
2933 			ret = EINVAL;
2934 			break;
2935 		}
2936 
2937 		/* Any removals resulting in an empty group should've handled this */
2938 		KASSERT(!SLIST_EMPTY(&sg->members), ("found empty syncgroup"));
2939 
2940 		/*
2941 		 * Attempt to lock all member channels - if any are already
2942 		 * locked, unlock those acquired, sleep for a bit, and try
2943 		 * again.
2944 		 */
2945 		SLIST_FOREACH(sm, &sg->members, link) {
2946 			if (CHN_TRYLOCK(sm->ch) == 0) {
2947 				int timo = hz * 5/1000;
2948 				if (timo < 1)
2949 					timo = 1;
2950 
2951 				/* Release all locked channels so far, retry */
2952 				SLIST_FOREACH(sm_tmp, &sg->members, link) {
2953 					/* sm is the member already locked */
2954 					if (sm == sm_tmp)
2955 						break;
2956 					CHN_UNLOCK(sm_tmp->ch);
2957 				}
2958 
2959 				/** @todo Is PRIBIO correct/ */
2960 				ret = msleep(sm, &snd_pcm_syncgroups_mtx,
2961 				    PRIBIO | PCATCH, "pcmsg", timo);
2962 				if (ret == EINTR || ret == ERESTART)
2963 					break;
2964 
2965 				needlocks = 1;
2966 				ret = 0; /* Assumes ret == EAGAIN... */
2967 			}
2968 		}
2969 	} while (needlocks && ret == 0);
2970 
2971 	/* Proceed only if no errors encountered. */
2972 	if (ret == 0) {
2973 		/* Launch channels */
2974 		while ((sm = SLIST_FIRST(&sg->members)) != NULL) {
2975 			SLIST_REMOVE_HEAD(&sg->members, link);
2976 
2977 			c = sm->ch;
2978 			c->sm = NULL;
2979 			chn_start(c, 1);
2980 			c->flags &= ~CHN_F_NOTRIGGER;
2981 			CHN_UNLOCK(c);
2982 
2983 			free(sm, M_DEVBUF);
2984 		}
2985 
2986 		SLIST_REMOVE(&snd_pcm_syncgroups, sg, pcmchan_syncgroup, link);
2987 		free(sg, M_DEVBUF);
2988 	}
2989 
2990 	PCM_SG_UNLOCK();
2991 
2992 	/*
2993 	 * Free_unr() may sleep, so be sure to give up the syncgroup lock
2994 	 * first.
2995 	 */
2996 	if (ret == 0)
2997 		free_unr(pcmsg_unrhdr, sg_id);
2998 
2999 	return (ret);
3000 }
3001 
3002 /**
3003  * @brief Handler for SNDCTL_DSP_POLICY
3004  *
3005  * The SNDCTL_DSP_POLICY ioctl is a simpler interface to control fragment
3006  * size and count like with SNDCTL_DSP_SETFRAGMENT.  Instead of the user
3007  * specifying those two parameters, s/he simply selects a number from 0..10
3008  * which corresponds to a buffer size.  Smaller numbers request smaller
3009  * buffers with lower latencies (at greater overhead from more frequent
3010  * interrupts), while greater numbers behave in the opposite manner.
3011  *
3012  * The 4Front spec states that a value of 5 should be the default.  However,
3013  * this implementation deviates slightly by using a linear scale without
3014  * consulting drivers.  I.e., even though drivers may have different default
3015  * buffer sizes, a policy argument of 5 will have the same result across
3016  * all drivers.
3017  *
3018  * See http://manuals.opensound.com/developer/SNDCTL_DSP_POLICY.html for
3019  * more information.
3020  *
3021  * @todo When SNDCTL_DSP_COOKEDMODE is supported, it'll be necessary to
3022  * 	 work with hardware drivers directly.
3023  *
3024  * @note PCM channel arguments must not be locked by caller.
3025  *
3026  * @param wrch	Pointer to opened playback channel (optional; may be NULL)
3027  * @param rdch	" recording channel (optional; may be NULL)
3028  * @param policy Integer from [0:10]
3029  *
3030  * @retval 0	constant (for now)
3031  */
3032 static int
3033 dsp_oss_policy(struct pcm_channel *wrch, struct pcm_channel *rdch, int policy)
3034 {
3035 	int ret;
3036 
3037 	if (policy < CHN_POLICY_MIN || policy > CHN_POLICY_MAX)
3038 		return (EIO);
3039 
3040 	/* Default: success */
3041 	ret = 0;
3042 
3043 	if (rdch) {
3044 		CHN_LOCK(rdch);
3045 		ret = chn_setlatency(rdch, policy);
3046 		CHN_UNLOCK(rdch);
3047 	}
3048 
3049 	if (wrch && ret == 0) {
3050 		CHN_LOCK(wrch);
3051 		ret = chn_setlatency(wrch, policy);
3052 		CHN_UNLOCK(wrch);
3053 	}
3054 
3055 	if (ret)
3056 		ret = EIO;
3057 
3058 	return (ret);
3059 }
3060 
3061 /**
3062  * @brief Enable or disable "cooked" mode
3063  *
3064  * This is a handler for @c SNDCTL_DSP_COOKEDMODE.  When in cooked mode, which
3065  * is the default, the sound system handles rate and format conversions
3066  * automatically (ex: user writing 11025Hz/8 bit/unsigned but card only
3067  * operates with 44100Hz/16bit/signed samples).
3068  *
3069  * Disabling cooked mode is intended for applications wanting to mmap()
3070  * a sound card's buffer space directly, bypassing the FreeBSD 2-stage
3071  * feeder architecture, presumably to gain as much control over audio
3072  * hardware as possible.
3073  *
3074  * See @c http://manuals.opensound.com/developer/SNDCTL_DSP_COOKEDMODE.html
3075  * for more details.
3076  *
3077  * @param wrch		playback channel (optional; may be NULL)
3078  * @param rdch		recording channel (optional; may be NULL)
3079  * @param enabled	0 = raw mode, 1 = cooked mode
3080  *
3081  * @retval EINVAL	Operation not yet supported.
3082  */
3083 static int
3084 dsp_oss_cookedmode(struct pcm_channel *wrch, struct pcm_channel *rdch, int enabled)
3085 {
3086 
3087 	/*
3088 	 * XXX I just don't get it. Why don't they call it
3089 	 * "BITPERFECT" ~ SNDCTL_DSP_BITPERFECT !?!?.
3090 	 * This is just plain so confusing, incoherent,
3091 	 * <insert any non-printable characters here>.
3092 	 */
3093 	if (!(enabled == 1 || enabled == 0))
3094 		return (EINVAL);
3095 
3096 	/*
3097 	 * I won't give in. I'm inverting its logic here and now.
3098 	 * Brag all you want, but "BITPERFECT" should be the better
3099 	 * term here.
3100 	 */
3101 	enabled ^= 0x00000001;
3102 
3103 	if (wrch != NULL) {
3104 		CHN_LOCK(wrch);
3105 		wrch->flags &= ~CHN_F_BITPERFECT;
3106 		wrch->flags |= (enabled != 0) ? CHN_F_BITPERFECT : 0x00000000;
3107 		CHN_UNLOCK(wrch);
3108 	}
3109 
3110 	if (rdch != NULL) {
3111 		CHN_LOCK(rdch);
3112 		rdch->flags &= ~CHN_F_BITPERFECT;
3113 		rdch->flags |= (enabled != 0) ? CHN_F_BITPERFECT : 0x00000000;
3114 		CHN_UNLOCK(rdch);
3115 	}
3116 
3117 	return (0);
3118 }
3119 
3120 /**
3121  * @brief Retrieve channel interleaving order
3122  *
3123  * This is the handler for @c SNDCTL_DSP_GET_CHNORDER.
3124  *
3125  * See @c http://manuals.opensound.com/developer/SNDCTL_DSP_GET_CHNORDER.html
3126  * for more details.
3127  *
3128  * @note As the ioctl definition is still under construction, FreeBSD
3129  * 	 does not currently support SNDCTL_DSP_GET_CHNORDER.
3130  *
3131  * @param wrch	playback channel (optional; may be NULL)
3132  * @param rdch	recording channel (optional; may be NULL)
3133  * @param map	channel map (result will be stored there)
3134  *
3135  * @retval EINVAL	Operation not yet supported.
3136  */
3137 static int
3138 dsp_oss_getchnorder(struct pcm_channel *wrch, struct pcm_channel *rdch, unsigned long long *map)
3139 {
3140 	struct pcm_channel *ch;
3141 	int ret;
3142 
3143 	ch = (wrch != NULL) ? wrch : rdch;
3144 	if (ch != NULL) {
3145 		CHN_LOCK(ch);
3146 		ret = chn_oss_getorder(ch, map);
3147 		CHN_UNLOCK(ch);
3148 	} else
3149 		ret = EINVAL;
3150 
3151 	return (ret);
3152 }
3153 
3154 /**
3155  * @brief Specify channel interleaving order
3156  *
3157  * This is the handler for @c SNDCTL_DSP_SET_CHNORDER.
3158  *
3159  * @note As the ioctl definition is still under construction, FreeBSD
3160  * 	 does not currently support @c SNDCTL_DSP_SET_CHNORDER.
3161  *
3162  * @param wrch	playback channel (optional; may be NULL)
3163  * @param rdch	recording channel (optional; may be NULL)
3164  * @param map	channel map
3165  *
3166  * @retval EINVAL	Operation not yet supported.
3167  */
3168 static int
3169 dsp_oss_setchnorder(struct pcm_channel *wrch, struct pcm_channel *rdch, unsigned long long *map)
3170 {
3171 	int ret;
3172 
3173 	ret = 0;
3174 
3175 	if (wrch != NULL) {
3176 		CHN_LOCK(wrch);
3177 		ret = chn_oss_setorder(wrch, map);
3178 		CHN_UNLOCK(wrch);
3179 	}
3180 
3181 	if (ret == 0 && rdch != NULL) {
3182 		CHN_LOCK(rdch);
3183 		ret = chn_oss_setorder(rdch, map);
3184 		CHN_UNLOCK(rdch);
3185 	}
3186 
3187 	return (ret);
3188 }
3189 
3190 static int
3191 dsp_oss_getchannelmask(struct pcm_channel *wrch, struct pcm_channel *rdch,
3192     int *mask)
3193 {
3194 	struct pcm_channel *ch;
3195 	uint32_t chnmask;
3196 	int ret;
3197 
3198 	chnmask = 0;
3199 	ch = (wrch != NULL) ? wrch : rdch;
3200 
3201 	if (ch != NULL) {
3202 		CHN_LOCK(ch);
3203 		ret = chn_oss_getmask(ch, &chnmask);
3204 		CHN_UNLOCK(ch);
3205 	} else
3206 		ret = EINVAL;
3207 
3208 	if (ret == 0)
3209 		*mask = chnmask;
3210 
3211 	return (ret);
3212 }
3213 
3214 #ifdef OSSV4_EXPERIMENT
3215 /**
3216  * @brief Retrieve an audio device's label
3217  *
3218  * This is a handler for the @c SNDCTL_GETLABEL ioctl.
3219  *
3220  * See @c http://manuals.opensound.com/developer/SNDCTL_GETLABEL.html
3221  * for more details.
3222  *
3223  * From Hannu@4Front:  "For example ossxmix (just like some HW mixer
3224  * consoles) can show variable "labels" for certain controls. By default
3225  * the application name (say quake) is shown as the label but
3226  * applications may change the labels themselves."
3227  *
3228  * @note As the ioctl definition is still under construction, FreeBSD
3229  * 	 does not currently support @c SNDCTL_GETLABEL.
3230  *
3231  * @param wrch	playback channel (optional; may be NULL)
3232  * @param rdch	recording channel (optional; may be NULL)
3233  * @param label	label gets copied here
3234  *
3235  * @retval EINVAL	Operation not yet supported.
3236  */
3237 static int
3238 dsp_oss_getlabel(struct pcm_channel *wrch, struct pcm_channel *rdch, oss_label_t *label)
3239 {
3240 	return (EINVAL);
3241 }
3242 
3243 /**
3244  * @brief Specify an audio device's label
3245  *
3246  * This is a handler for the @c SNDCTL_SETLABEL ioctl.  Please see the
3247  * comments for @c dsp_oss_getlabel immediately above.
3248  *
3249  * See @c http://manuals.opensound.com/developer/SNDCTL_GETLABEL.html
3250  * for more details.
3251  *
3252  * @note As the ioctl definition is still under construction, FreeBSD
3253  * 	 does not currently support SNDCTL_SETLABEL.
3254  *
3255  * @param wrch	playback channel (optional; may be NULL)
3256  * @param rdch	recording channel (optional; may be NULL)
3257  * @param label	label gets copied from here
3258  *
3259  * @retval EINVAL	Operation not yet supported.
3260  */
3261 static int
3262 dsp_oss_setlabel(struct pcm_channel *wrch, struct pcm_channel *rdch, oss_label_t *label)
3263 {
3264 	return (EINVAL);
3265 }
3266 
3267 /**
3268  * @brief Retrieve name of currently played song
3269  *
3270  * This is a handler for the @c SNDCTL_GETSONG ioctl.  Audio players could
3271  * tell the system the name of the currently playing song, which would be
3272  * visible in @c /dev/sndstat.
3273  *
3274  * See @c http://manuals.opensound.com/developer/SNDCTL_GETSONG.html
3275  * for more details.
3276  *
3277  * @note As the ioctl definition is still under construction, FreeBSD
3278  * 	 does not currently support SNDCTL_GETSONG.
3279  *
3280  * @param wrch	playback channel (optional; may be NULL)
3281  * @param rdch	recording channel (optional; may be NULL)
3282  * @param song	song name gets copied here
3283  *
3284  * @retval EINVAL	Operation not yet supported.
3285  */
3286 static int
3287 dsp_oss_getsong(struct pcm_channel *wrch, struct pcm_channel *rdch, oss_longname_t *song)
3288 {
3289 	return (EINVAL);
3290 }
3291 
3292 /**
3293  * @brief Retrieve name of currently played song
3294  *
3295  * This is a handler for the @c SNDCTL_SETSONG ioctl.  Audio players could
3296  * tell the system the name of the currently playing song, which would be
3297  * visible in @c /dev/sndstat.
3298  *
3299  * See @c http://manuals.opensound.com/developer/SNDCTL_SETSONG.html
3300  * for more details.
3301  *
3302  * @note As the ioctl definition is still under construction, FreeBSD
3303  * 	 does not currently support SNDCTL_SETSONG.
3304  *
3305  * @param wrch	playback channel (optional; may be NULL)
3306  * @param rdch	recording channel (optional; may be NULL)
3307  * @param song	song name gets copied from here
3308  *
3309  * @retval EINVAL	Operation not yet supported.
3310  */
3311 static int
3312 dsp_oss_setsong(struct pcm_channel *wrch, struct pcm_channel *rdch, oss_longname_t *song)
3313 {
3314 	return (EINVAL);
3315 }
3316 
3317 /**
3318  * @brief Rename a device
3319  *
3320  * This is a handler for the @c SNDCTL_SETNAME ioctl.
3321  *
3322  * See @c http://manuals.opensound.com/developer/SNDCTL_SETNAME.html for
3323  * more details.
3324  *
3325  * From Hannu@4Front:  "This call is used to change the device name
3326  * reported in /dev/sndstat and ossinfo. So instead of  using some generic
3327  * 'OSS loopback audio (MIDI) driver' the device may be given a meaningfull
3328  * name depending on the current context (for example 'OSS virtual wave table
3329  * synth' or 'VoIP link to London')."
3330  *
3331  * @note As the ioctl definition is still under construction, FreeBSD
3332  * 	 does not currently support SNDCTL_SETNAME.
3333  *
3334  * @param wrch	playback channel (optional; may be NULL)
3335  * @param rdch	recording channel (optional; may be NULL)
3336  * @param name	new device name gets copied from here
3337  *
3338  * @retval EINVAL	Operation not yet supported.
3339  */
3340 static int
3341 dsp_oss_setname(struct pcm_channel *wrch, struct pcm_channel *rdch, oss_longname_t *name)
3342 {
3343 	return (EINVAL);
3344 }
3345 #endif	/* !OSSV4_EXPERIMENT */
3346