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