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