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