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