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