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