audio.c revision 1.117 1 /* $NetBSD: audio.c,v 1.117 2022/03/26 06:36:06 isaki Exp $ */
2
3 /*-
4 * Copyright (c) 2008 The NetBSD Foundation, Inc.
5 * All rights reserved.
6 *
7 * This code is derived from software contributed to The NetBSD Foundation
8 * by Andrew Doran.
9 *
10 * Redistribution and use in source and binary forms, with or without
11 * modification, are permitted provided that the following conditions
12 * are met:
13 * 1. Redistributions of source code must retain the above copyright
14 * notice, this list of conditions and the following disclaimer.
15 * 2. Redistributions in binary form must reproduce the above copyright
16 * notice, this list of conditions and the following disclaimer in the
17 * documentation and/or other materials provided with the distribution.
18 *
19 * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
20 * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
21 * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
22 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
23 * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
24 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
25 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
26 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
27 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
28 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
29 * POSSIBILITY OF SUCH DAMAGE.
30 */
31
32 /*
33 * Copyright (c) 1991-1993 Regents of the University of California.
34 * All rights reserved.
35 *
36 * Redistribution and use in source and binary forms, with or without
37 * modification, are permitted provided that the following conditions
38 * are met:
39 * 1. Redistributions of source code must retain the above copyright
40 * notice, this list of conditions and the following disclaimer.
41 * 2. Redistributions in binary form must reproduce the above copyright
42 * notice, this list of conditions and the following disclaimer in the
43 * documentation and/or other materials provided with the distribution.
44 * 3. All advertising materials mentioning features or use of this software
45 * must display the following acknowledgement:
46 * This product includes software developed by the Computer Systems
47 * Engineering Group at Lawrence Berkeley Laboratory.
48 * 4. Neither the name of the University nor of the Laboratory may be used
49 * to endorse or promote products derived from this software without
50 * specific prior written permission.
51 *
52 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
53 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
54 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
55 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
56 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
57 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
58 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
59 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
60 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
61 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
62 * SUCH DAMAGE.
63 */
64
65 /*
66 * Locking: there are three locks per device.
67 *
68 * - sc_lock, provided by the underlying driver. This is an adaptive lock,
69 * returned in the second parameter to hw_if->get_locks(). It is known
70 * as the "thread lock".
71 *
72 * It serializes access to state in all places except the
73 * driver's interrupt service routine. This lock is taken from process
74 * context (example: access to /dev/audio). It is also taken from soft
75 * interrupt handlers in this module, primarily to serialize delivery of
76 * wakeups. This lock may be used/provided by modules external to the
77 * audio subsystem, so take care not to introduce a lock order problem.
78 * LONG TERM SLEEPS MUST NOT OCCUR WITH THIS LOCK HELD.
79 *
80 * - sc_intr_lock, provided by the underlying driver. This may be either a
81 * spinlock (at IPL_SCHED or IPL_VM) or an adaptive lock (IPL_NONE or
82 * IPL_SOFT*), returned in the first parameter to hw_if->get_locks(). It
83 * is known as the "interrupt lock".
84 *
85 * It provides atomic access to the device's hardware state, and to audio
86 * channel data that may be accessed by the hardware driver's ISR.
87 * In all places outside the ISR, sc_lock must be held before taking
88 * sc_intr_lock. This is to ensure that groups of hardware operations are
89 * made atomically. SLEEPS CANNOT OCCUR WITH THIS LOCK HELD.
90 *
91 * - sc_exlock, private to this module. This is a variable protected by
92 * sc_lock. It is known as the "critical section".
93 * Some operations release sc_lock in order to allocate memory, to wait
94 * for in-flight I/O to complete, to copy to/from user context, etc.
95 * sc_exlock provides a critical section even under the circumstance.
96 * "+" in following list indicates the interfaces which necessary to be
97 * protected by sc_exlock.
98 *
99 * List of hardware interface methods, and which locks are held when each
100 * is called by this module:
101 *
102 * METHOD INTR THREAD NOTES
103 * ----------------------- ------- ------- -------------------------
104 * open x x +
105 * close x x +
106 * query_format - x
107 * set_format - x
108 * round_blocksize - x
109 * commit_settings - x
110 * init_output x x
111 * init_input x x
112 * start_output x x +
113 * start_input x x +
114 * halt_output x x +
115 * halt_input x x +
116 * speaker_ctl x x
117 * getdev - -
118 * set_port - x +
119 * get_port - x +
120 * query_devinfo - x
121 * allocm - - +
122 * freem - - +
123 * round_buffersize - x
124 * get_props - - Called at attach time
125 * trigger_output x x +
126 * trigger_input x x +
127 * dev_ioctl - x
128 * get_locks - - Called at attach time
129 *
130 * In addition, there is an additional lock.
131 *
132 * - track->lock. This is an atomic variable and is similar to the
133 * "interrupt lock". This is one for each track. If any thread context
134 * (and software interrupt context) and hardware interrupt context who
135 * want to access some variables on this track, they must acquire this
136 * lock before. It protects track's consistency between hardware
137 * interrupt context and others.
138 */
139
140 #include <sys/cdefs.h>
141 __KERNEL_RCSID(0, "$NetBSD: audio.c,v 1.117 2022/03/26 06:36:06 isaki Exp $");
142
143 #ifdef _KERNEL_OPT
144 #include "audio.h"
145 #include "midi.h"
146 #endif
147
148 #if NAUDIO > 0
149
150 #include <sys/types.h>
151 #include <sys/param.h>
152 #include <sys/atomic.h>
153 #include <sys/audioio.h>
154 #include <sys/conf.h>
155 #include <sys/cpu.h>
156 #include <sys/device.h>
157 #include <sys/fcntl.h>
158 #include <sys/file.h>
159 #include <sys/filedesc.h>
160 #include <sys/intr.h>
161 #include <sys/ioctl.h>
162 #include <sys/kauth.h>
163 #include <sys/kernel.h>
164 #include <sys/kmem.h>
165 #include <sys/lock.h>
166 #include <sys/malloc.h>
167 #include <sys/mman.h>
168 #include <sys/module.h>
169 #include <sys/poll.h>
170 #include <sys/proc.h>
171 #include <sys/queue.h>
172 #include <sys/select.h>
173 #include <sys/signalvar.h>
174 #include <sys/stat.h>
175 #include <sys/sysctl.h>
176 #include <sys/systm.h>
177 #include <sys/syslog.h>
178 #include <sys/vnode.h>
179
180 #include <dev/audio/audio_if.h>
181 #include <dev/audio/audiovar.h>
182 #include <dev/audio/audiodef.h>
183 #include <dev/audio/linear.h>
184 #include <dev/audio/mulaw.h>
185
186 #include <machine/endian.h>
187
188 #include <uvm/uvm_extern.h>
189
190 #include "ioconf.h"
191
192 /*
193 * 0: No debug logs
194 * 1: action changes like open/close/set_format...
195 * 2: + normal operations like read/write/ioctl...
196 * 3: + TRACEs except interrupt
197 * 4: + TRACEs including interrupt
198 */
199 //#define AUDIO_DEBUG 1
200
201 #if defined(AUDIO_DEBUG)
202
203 int audiodebug = AUDIO_DEBUG;
204 static void audio_vtrace(struct audio_softc *sc, const char *, const char *,
205 const char *, va_list);
206 static void audio_trace(struct audio_softc *sc, const char *, const char *, ...)
207 __printflike(3, 4);
208 static void audio_tracet(const char *, audio_track_t *, const char *, ...)
209 __printflike(3, 4);
210 static void audio_tracef(const char *, audio_file_t *, const char *, ...)
211 __printflike(3, 4);
212
213 /* XXX sloppy memory logger */
214 static void audio_mlog_init(void);
215 static void audio_mlog_free(void);
216 static void audio_mlog_softintr(void *);
217 extern void audio_mlog_flush(void);
218 extern void audio_mlog_printf(const char *, ...);
219
220 static int mlog_refs; /* reference counter */
221 static char *mlog_buf[2]; /* double buffer */
222 static int mlog_buflen; /* buffer length */
223 static int mlog_used; /* used length */
224 static int mlog_full; /* number of dropped lines by buffer full */
225 static int mlog_drop; /* number of dropped lines by busy */
226 static volatile uint32_t mlog_inuse; /* in-use */
227 static int mlog_wpage; /* active page */
228 static void *mlog_sih; /* softint handle */
229
230 static void
231 audio_mlog_init(void)
232 {
233 mlog_refs++;
234 if (mlog_refs > 1)
235 return;
236 mlog_buflen = 4096;
237 mlog_buf[0] = kmem_zalloc(mlog_buflen, KM_SLEEP);
238 mlog_buf[1] = kmem_zalloc(mlog_buflen, KM_SLEEP);
239 mlog_used = 0;
240 mlog_full = 0;
241 mlog_drop = 0;
242 mlog_inuse = 0;
243 mlog_wpage = 0;
244 mlog_sih = softint_establish(SOFTINT_SERIAL, audio_mlog_softintr, NULL);
245 if (mlog_sih == NULL)
246 printf("%s: softint_establish failed\n", __func__);
247 }
248
249 static void
250 audio_mlog_free(void)
251 {
252 mlog_refs--;
253 if (mlog_refs > 0)
254 return;
255
256 audio_mlog_flush();
257 if (mlog_sih)
258 softint_disestablish(mlog_sih);
259 kmem_free(mlog_buf[0], mlog_buflen);
260 kmem_free(mlog_buf[1], mlog_buflen);
261 }
262
263 /*
264 * Flush memory buffer.
265 * It must not be called from hardware interrupt context.
266 */
267 void
268 audio_mlog_flush(void)
269 {
270 if (mlog_refs == 0)
271 return;
272
273 /* Nothing to do if already in use ? */
274 if (atomic_swap_32(&mlog_inuse, 1) == 1)
275 return;
276 membar_enter();
277
278 int rpage = mlog_wpage;
279 mlog_wpage ^= 1;
280 mlog_buf[mlog_wpage][0] = '\0';
281 mlog_used = 0;
282
283 atomic_store_release(&mlog_inuse, 0);
284
285 if (mlog_buf[rpage][0] != '\0') {
286 printf("%s", mlog_buf[rpage]);
287 if (mlog_drop > 0)
288 printf("mlog_drop %d\n", mlog_drop);
289 if (mlog_full > 0)
290 printf("mlog_full %d\n", mlog_full);
291 }
292 mlog_full = 0;
293 mlog_drop = 0;
294 }
295
296 static void
297 audio_mlog_softintr(void *cookie)
298 {
299 audio_mlog_flush();
300 }
301
302 void
303 audio_mlog_printf(const char *fmt, ...)
304 {
305 int len;
306 va_list ap;
307
308 if (atomic_swap_32(&mlog_inuse, 1) == 1) {
309 /* already inuse */
310 mlog_drop++;
311 return;
312 }
313 membar_enter();
314
315 va_start(ap, fmt);
316 len = vsnprintf(
317 mlog_buf[mlog_wpage] + mlog_used,
318 mlog_buflen - mlog_used,
319 fmt, ap);
320 va_end(ap);
321
322 mlog_used += len;
323 if (mlog_buflen - mlog_used <= 1) {
324 mlog_full++;
325 }
326
327 atomic_store_release(&mlog_inuse, 0);
328
329 if (mlog_sih)
330 softint_schedule(mlog_sih);
331 }
332
333 /* trace functions */
334 static void
335 audio_vtrace(struct audio_softc *sc, const char *funcname, const char *header,
336 const char *fmt, va_list ap)
337 {
338 char buf[256];
339 int n;
340
341 n = 0;
342 buf[0] = '\0';
343 n += snprintf(buf + n, sizeof(buf) - n, "%s@%d %s",
344 funcname, device_unit(sc->sc_dev), header);
345 n += vsnprintf(buf + n, sizeof(buf) - n, fmt, ap);
346
347 if (cpu_intr_p()) {
348 audio_mlog_printf("%s\n", buf);
349 } else {
350 audio_mlog_flush();
351 printf("%s\n", buf);
352 }
353 }
354
355 static void
356 audio_trace(struct audio_softc *sc, const char *funcname, const char *fmt, ...)
357 {
358 va_list ap;
359
360 va_start(ap, fmt);
361 audio_vtrace(sc, funcname, "", fmt, ap);
362 va_end(ap);
363 }
364
365 static void
366 audio_tracet(const char *funcname, audio_track_t *track, const char *fmt, ...)
367 {
368 char hdr[16];
369 va_list ap;
370
371 snprintf(hdr, sizeof(hdr), "#%d ", track->id);
372 va_start(ap, fmt);
373 audio_vtrace(track->mixer->sc, funcname, hdr, fmt, ap);
374 va_end(ap);
375 }
376
377 static void
378 audio_tracef(const char *funcname, audio_file_t *file, const char *fmt, ...)
379 {
380 char hdr[32];
381 char phdr[16], rhdr[16];
382 va_list ap;
383
384 phdr[0] = '\0';
385 rhdr[0] = '\0';
386 if (file->ptrack)
387 snprintf(phdr, sizeof(phdr), "#%d", file->ptrack->id);
388 if (file->rtrack)
389 snprintf(rhdr, sizeof(rhdr), "#%d", file->rtrack->id);
390 snprintf(hdr, sizeof(hdr), "{%s,%s} ", phdr, rhdr);
391
392 va_start(ap, fmt);
393 audio_vtrace(file->sc, funcname, hdr, fmt, ap);
394 va_end(ap);
395 }
396
397 #define DPRINTF(n, fmt...) do { \
398 if (audiodebug >= (n)) { \
399 audio_mlog_flush(); \
400 printf(fmt); \
401 } \
402 } while (0)
403 #define TRACE(n, fmt...) do { \
404 if (audiodebug >= (n)) audio_trace(sc, __func__, fmt); \
405 } while (0)
406 #define TRACET(n, t, fmt...) do { \
407 if (audiodebug >= (n)) audio_tracet(__func__, t, fmt); \
408 } while (0)
409 #define TRACEF(n, f, fmt...) do { \
410 if (audiodebug >= (n)) audio_tracef(__func__, f, fmt); \
411 } while (0)
412
413 struct audio_track_debugbuf {
414 char usrbuf[32];
415 char codec[32];
416 char chvol[32];
417 char chmix[32];
418 char freq[32];
419 char outbuf[32];
420 };
421
422 static void
423 audio_track_bufstat(audio_track_t *track, struct audio_track_debugbuf *buf)
424 {
425
426 memset(buf, 0, sizeof(*buf));
427
428 snprintf(buf->outbuf, sizeof(buf->outbuf), " out=%d/%d/%d",
429 track->outbuf.head, track->outbuf.used, track->outbuf.capacity);
430 if (track->freq.filter)
431 snprintf(buf->freq, sizeof(buf->freq), " f=%d/%d/%d",
432 track->freq.srcbuf.head,
433 track->freq.srcbuf.used,
434 track->freq.srcbuf.capacity);
435 if (track->chmix.filter)
436 snprintf(buf->chmix, sizeof(buf->chmix), " m=%d",
437 track->chmix.srcbuf.used);
438 if (track->chvol.filter)
439 snprintf(buf->chvol, sizeof(buf->chvol), " v=%d",
440 track->chvol.srcbuf.used);
441 if (track->codec.filter)
442 snprintf(buf->codec, sizeof(buf->codec), " e=%d",
443 track->codec.srcbuf.used);
444 snprintf(buf->usrbuf, sizeof(buf->usrbuf), " usr=%d/%d/H%d",
445 track->usrbuf.head, track->usrbuf.used, track->usrbuf_usedhigh);
446 }
447 #else
448 #define DPRINTF(n, fmt...) do { } while (0)
449 #define TRACE(n, fmt, ...) do { } while (0)
450 #define TRACET(n, t, fmt, ...) do { } while (0)
451 #define TRACEF(n, f, fmt, ...) do { } while (0)
452 #endif
453
454 #define SPECIFIED(x) ((x) != ~0)
455 #define SPECIFIED_CH(x) ((x) != (u_char)~0)
456
457 /*
458 * Default hardware blocksize in msec.
459 *
460 * We use 10 msec for most modern platforms. This period is good enough to
461 * play audio and video synchronizely.
462 * In contrast, for very old platforms, this is usually too short and too
463 * severe. Also such platforms usually can not play video confortably, so
464 * it's not so important to make the blocksize shorter. If the platform
465 * defines its own value as __AUDIO_BLK_MS in its <machine/param.h>, it
466 * uses this instead.
467 *
468 * In either case, you can overwrite AUDIO_BLK_MS by your kernel
469 * configuration file if you wish.
470 */
471 #if !defined(AUDIO_BLK_MS)
472 # if defined(__AUDIO_BLK_MS)
473 # define AUDIO_BLK_MS __AUDIO_BLK_MS
474 # else
475 # define AUDIO_BLK_MS (10)
476 # endif
477 #endif
478
479 /* Device timeout in msec */
480 #define AUDIO_TIMEOUT (3000)
481
482 /* #define AUDIO_PM_IDLE */
483 #ifdef AUDIO_PM_IDLE
484 int audio_idle_timeout = 30;
485 #endif
486
487 /* Number of elements of async mixer's pid */
488 #define AM_CAPACITY (4)
489
490 struct portname {
491 const char *name;
492 int mask;
493 };
494
495 static int audiomatch(device_t, cfdata_t, void *);
496 static void audioattach(device_t, device_t, void *);
497 static int audiodetach(device_t, int);
498 static int audioactivate(device_t, enum devact);
499 static void audiochilddet(device_t, device_t);
500 static int audiorescan(device_t, const char *, const int *);
501
502 static int audio_modcmd(modcmd_t, void *);
503
504 #ifdef AUDIO_PM_IDLE
505 static void audio_idle(void *);
506 static void audio_activity(device_t, devactive_t);
507 #endif
508
509 static bool audio_suspend(device_t dv, const pmf_qual_t *);
510 static bool audio_resume(device_t dv, const pmf_qual_t *);
511 static void audio_volume_down(device_t);
512 static void audio_volume_up(device_t);
513 static void audio_volume_toggle(device_t);
514
515 static void audio_mixer_capture(struct audio_softc *);
516 static void audio_mixer_restore(struct audio_softc *);
517
518 static void audio_softintr_rd(void *);
519 static void audio_softintr_wr(void *);
520
521 static void audio_printf(struct audio_softc *, const char *, ...)
522 __printflike(2, 3);
523 static int audio_exlock_mutex_enter(struct audio_softc *);
524 static void audio_exlock_mutex_exit(struct audio_softc *);
525 static int audio_exlock_enter(struct audio_softc *);
526 static void audio_exlock_exit(struct audio_softc *);
527 static void audio_sc_acquire_foropen(struct audio_softc *, struct psref *);
528 static struct audio_softc *audio_sc_acquire_fromfile(audio_file_t *,
529 struct psref *);
530 static void audio_sc_release(struct audio_softc *, struct psref *);
531 static int audio_track_waitio(struct audio_softc *, audio_track_t *);
532
533 static int audioclose(struct file *);
534 static int audioread(struct file *, off_t *, struct uio *, kauth_cred_t, int);
535 static int audiowrite(struct file *, off_t *, struct uio *, kauth_cred_t, int);
536 static int audioioctl(struct file *, u_long, void *);
537 static int audiopoll(struct file *, int);
538 static int audiokqfilter(struct file *, struct knote *);
539 static int audiommap(struct file *, off_t *, size_t, int, int *, int *,
540 struct uvm_object **, int *);
541 static int audiostat(struct file *, struct stat *);
542
543 static void filt_audiowrite_detach(struct knote *);
544 static int filt_audiowrite_event(struct knote *, long);
545 static void filt_audioread_detach(struct knote *);
546 static int filt_audioread_event(struct knote *, long);
547
548 static int audio_open(dev_t, struct audio_softc *, int, int, struct lwp *,
549 audio_file_t **);
550 static int audio_close(struct audio_softc *, audio_file_t *);
551 static void audio_unlink(struct audio_softc *, audio_file_t *);
552 static int audio_read(struct audio_softc *, struct uio *, int, audio_file_t *);
553 static int audio_write(struct audio_softc *, struct uio *, int, audio_file_t *);
554 static void audio_file_clear(struct audio_softc *, audio_file_t *);
555 static int audio_ioctl(dev_t, struct audio_softc *, u_long, void *, int,
556 struct lwp *, audio_file_t *);
557 static int audio_poll(struct audio_softc *, int, struct lwp *, audio_file_t *);
558 static int audio_kqfilter(struct audio_softc *, audio_file_t *, struct knote *);
559 static int audio_mmap(struct audio_softc *, off_t *, size_t, int, int *, int *,
560 struct uvm_object **, int *, audio_file_t *);
561
562 static int audioctl_open(dev_t, struct audio_softc *, int, int, struct lwp *);
563
564 static void audio_pintr(void *);
565 static void audio_rintr(void *);
566
567 static int audio_query_devinfo(struct audio_softc *, mixer_devinfo_t *);
568
569 static __inline int audio_track_readablebytes(const audio_track_t *);
570 static int audio_file_setinfo(struct audio_softc *, audio_file_t *,
571 const struct audio_info *);
572 static int audio_track_setinfo_check(audio_track_t *,
573 audio_format2_t *, const struct audio_prinfo *);
574 static void audio_track_setinfo_water(audio_track_t *,
575 const struct audio_info *);
576 static int audio_hw_setinfo(struct audio_softc *, const struct audio_info *,
577 struct audio_info *);
578 static int audio_hw_set_format(struct audio_softc *, int,
579 const audio_format2_t *, const audio_format2_t *,
580 audio_filter_reg_t *, audio_filter_reg_t *);
581 static int audiogetinfo(struct audio_softc *, struct audio_info *, int,
582 audio_file_t *);
583 static bool audio_can_playback(struct audio_softc *);
584 static bool audio_can_capture(struct audio_softc *);
585 static int audio_check_params(audio_format2_t *);
586 static int audio_mixers_init(struct audio_softc *sc, int,
587 const audio_format2_t *, const audio_format2_t *,
588 const audio_filter_reg_t *, const audio_filter_reg_t *);
589 static int audio_select_freq(const struct audio_format *);
590 static int audio_hw_probe(struct audio_softc *, audio_format2_t *, int);
591 static int audio_hw_validate_format(struct audio_softc *, int,
592 const audio_format2_t *);
593 static int audio_mixers_set_format(struct audio_softc *,
594 const struct audio_info *);
595 static void audio_mixers_get_format(struct audio_softc *, struct audio_info *);
596 static int audio_sysctl_blk_ms(SYSCTLFN_PROTO);
597 static int audio_sysctl_multiuser(SYSCTLFN_PROTO);
598 #if defined(AUDIO_DEBUG)
599 static int audio_sysctl_debug(SYSCTLFN_PROTO);
600 static void audio_format2_tostr(char *, size_t, const audio_format2_t *);
601 static void audio_print_format2(const char *, const audio_format2_t *) __unused;
602 #endif
603
604 static void *audio_realloc(void *, size_t);
605 static int audio_realloc_usrbuf(audio_track_t *, int);
606 static void audio_free_usrbuf(audio_track_t *);
607
608 static audio_track_t *audio_track_create(struct audio_softc *,
609 audio_trackmixer_t *);
610 static void audio_track_destroy(audio_track_t *);
611 static audio_filter_t audio_track_get_codec(audio_track_t *,
612 const audio_format2_t *, const audio_format2_t *);
613 static int audio_track_set_format(audio_track_t *, audio_format2_t *);
614 static void audio_track_play(audio_track_t *);
615 static int audio_track_drain(struct audio_softc *, audio_track_t *);
616 static void audio_track_record(audio_track_t *);
617 static void audio_track_clear(struct audio_softc *, audio_track_t *);
618
619 static int audio_mixer_init(struct audio_softc *, int,
620 const audio_format2_t *, const audio_filter_reg_t *);
621 static void audio_mixer_destroy(struct audio_softc *, audio_trackmixer_t *);
622 static void audio_pmixer_start(struct audio_softc *, bool);
623 static void audio_pmixer_process(struct audio_softc *);
624 static void audio_pmixer_agc(audio_trackmixer_t *, int);
625 static int audio_pmixer_mix_track(audio_trackmixer_t *, audio_track_t *, int);
626 static void audio_pmixer_output(struct audio_softc *);
627 static int audio_pmixer_halt(struct audio_softc *);
628 static void audio_rmixer_start(struct audio_softc *);
629 static void audio_rmixer_process(struct audio_softc *);
630 static void audio_rmixer_input(struct audio_softc *);
631 static int audio_rmixer_halt(struct audio_softc *);
632
633 static void mixer_init(struct audio_softc *);
634 static int mixer_open(dev_t, struct audio_softc *, int, int, struct lwp *);
635 static int mixer_close(struct audio_softc *, audio_file_t *);
636 static int mixer_ioctl(struct audio_softc *, u_long, void *, int, struct lwp *);
637 static void mixer_async_add(struct audio_softc *, pid_t);
638 static void mixer_async_remove(struct audio_softc *, pid_t);
639 static void mixer_signal(struct audio_softc *);
640
641 static int au_portof(struct audio_softc *, char *, int);
642
643 static void au_setup_ports(struct audio_softc *, struct au_mixer_ports *,
644 mixer_devinfo_t *, const struct portname *);
645 static int au_set_lr_value(struct audio_softc *, mixer_ctrl_t *, int, int);
646 static int au_get_lr_value(struct audio_softc *, mixer_ctrl_t *, int *, int *);
647 static int au_set_gain(struct audio_softc *, struct au_mixer_ports *, int, int);
648 static void au_get_gain(struct audio_softc *, struct au_mixer_ports *,
649 u_int *, u_char *);
650 static int au_set_port(struct audio_softc *, struct au_mixer_ports *, u_int);
651 static int au_get_port(struct audio_softc *, struct au_mixer_ports *);
652 static int au_set_monitor_gain(struct audio_softc *, int);
653 static int au_get_monitor_gain(struct audio_softc *);
654 static int audio_get_port(struct audio_softc *, mixer_ctrl_t *);
655 static int audio_set_port(struct audio_softc *, mixer_ctrl_t *);
656
657 static __inline struct audio_params
658 format2_to_params(const audio_format2_t *f2)
659 {
660 audio_params_t p;
661
662 /* validbits/precision <-> precision/stride */
663 p.sample_rate = f2->sample_rate;
664 p.channels = f2->channels;
665 p.encoding = f2->encoding;
666 p.validbits = f2->precision;
667 p.precision = f2->stride;
668 return p;
669 }
670
671 static __inline audio_format2_t
672 params_to_format2(const struct audio_params *p)
673 {
674 audio_format2_t f2;
675
676 /* precision/stride <-> validbits/precision */
677 f2.sample_rate = p->sample_rate;
678 f2.channels = p->channels;
679 f2.encoding = p->encoding;
680 f2.precision = p->validbits;
681 f2.stride = p->precision;
682 return f2;
683 }
684
685 /* Return true if this track is a playback track. */
686 static __inline bool
687 audio_track_is_playback(const audio_track_t *track)
688 {
689
690 return ((track->mode & AUMODE_PLAY) != 0);
691 }
692
693 /* Return true if this track is a recording track. */
694 static __inline bool
695 audio_track_is_record(const audio_track_t *track)
696 {
697
698 return ((track->mode & AUMODE_RECORD) != 0);
699 }
700
701 #if 0 /* XXX Not used yet */
702 /*
703 * Convert 0..255 volume used in userland to internal presentation 0..256.
704 */
705 static __inline u_int
706 audio_volume_to_inner(u_int v)
707 {
708
709 return v < 127 ? v : v + 1;
710 }
711
712 /*
713 * Convert 0..256 internal presentation to 0..255 volume used in userland.
714 */
715 static __inline u_int
716 audio_volume_to_outer(u_int v)
717 {
718
719 return v < 127 ? v : v - 1;
720 }
721 #endif /* 0 */
722
723 static dev_type_open(audioopen);
724 /* XXXMRG use more dev_type_xxx */
725
726 const struct cdevsw audio_cdevsw = {
727 .d_open = audioopen,
728 .d_close = noclose,
729 .d_read = noread,
730 .d_write = nowrite,
731 .d_ioctl = noioctl,
732 .d_stop = nostop,
733 .d_tty = notty,
734 .d_poll = nopoll,
735 .d_mmap = nommap,
736 .d_kqfilter = nokqfilter,
737 .d_discard = nodiscard,
738 .d_flag = D_OTHER | D_MPSAFE
739 };
740
741 const struct fileops audio_fileops = {
742 .fo_name = "audio",
743 .fo_read = audioread,
744 .fo_write = audiowrite,
745 .fo_ioctl = audioioctl,
746 .fo_fcntl = fnullop_fcntl,
747 .fo_stat = audiostat,
748 .fo_poll = audiopoll,
749 .fo_close = audioclose,
750 .fo_mmap = audiommap,
751 .fo_kqfilter = audiokqfilter,
752 .fo_restart = fnullop_restart
753 };
754
755 /* The default audio mode: 8 kHz mono mu-law */
756 static const struct audio_params audio_default = {
757 .sample_rate = 8000,
758 .encoding = AUDIO_ENCODING_ULAW,
759 .precision = 8,
760 .validbits = 8,
761 .channels = 1,
762 };
763
764 static const char *encoding_names[] = {
765 "none",
766 AudioEmulaw,
767 AudioEalaw,
768 "pcm16",
769 "pcm8",
770 AudioEadpcm,
771 AudioEslinear_le,
772 AudioEslinear_be,
773 AudioEulinear_le,
774 AudioEulinear_be,
775 AudioEslinear,
776 AudioEulinear,
777 AudioEmpeg_l1_stream,
778 AudioEmpeg_l1_packets,
779 AudioEmpeg_l1_system,
780 AudioEmpeg_l2_stream,
781 AudioEmpeg_l2_packets,
782 AudioEmpeg_l2_system,
783 AudioEac3,
784 };
785
786 /*
787 * Returns encoding name corresponding to AUDIO_ENCODING_*.
788 * Note that it may return a local buffer because it is mainly for debugging.
789 */
790 const char *
791 audio_encoding_name(int encoding)
792 {
793 static char buf[16];
794
795 if (0 <= encoding && encoding < __arraycount(encoding_names)) {
796 return encoding_names[encoding];
797 } else {
798 snprintf(buf, sizeof(buf), "enc=%d", encoding);
799 return buf;
800 }
801 }
802
803 /*
804 * Supported encodings used by AUDIO_GETENC.
805 * index and flags are set by code.
806 * XXX is there any needs for SLINEAR_OE:>=16/ULINEAR_OE:>=16 ?
807 */
808 static const audio_encoding_t audio_encodings[] = {
809 { 0, AudioEmulaw, AUDIO_ENCODING_ULAW, 8, 0 },
810 { 0, AudioEalaw, AUDIO_ENCODING_ALAW, 8, 0 },
811 { 0, AudioEslinear, AUDIO_ENCODING_SLINEAR, 8, 0 },
812 { 0, AudioEulinear, AUDIO_ENCODING_ULINEAR, 8, 0 },
813 { 0, AudioEslinear_le, AUDIO_ENCODING_SLINEAR_LE, 16, 0 },
814 { 0, AudioEulinear_le, AUDIO_ENCODING_ULINEAR_LE, 16, 0 },
815 { 0, AudioEslinear_be, AUDIO_ENCODING_SLINEAR_BE, 16, 0 },
816 { 0, AudioEulinear_be, AUDIO_ENCODING_ULINEAR_BE, 16, 0 },
817 #if defined(AUDIO_SUPPORT_LINEAR24)
818 { 0, AudioEslinear_le, AUDIO_ENCODING_SLINEAR_LE, 24, 0 },
819 { 0, AudioEulinear_le, AUDIO_ENCODING_ULINEAR_LE, 24, 0 },
820 { 0, AudioEslinear_be, AUDIO_ENCODING_SLINEAR_BE, 24, 0 },
821 { 0, AudioEulinear_be, AUDIO_ENCODING_ULINEAR_BE, 24, 0 },
822 #endif
823 { 0, AudioEslinear_le, AUDIO_ENCODING_SLINEAR_LE, 32, 0 },
824 { 0, AudioEulinear_le, AUDIO_ENCODING_ULINEAR_LE, 32, 0 },
825 { 0, AudioEslinear_be, AUDIO_ENCODING_SLINEAR_BE, 32, 0 },
826 { 0, AudioEulinear_be, AUDIO_ENCODING_ULINEAR_BE, 32, 0 },
827 };
828
829 static const struct portname itable[] = {
830 { AudioNmicrophone, AUDIO_MICROPHONE },
831 { AudioNline, AUDIO_LINE_IN },
832 { AudioNcd, AUDIO_CD },
833 { 0, 0 }
834 };
835 static const struct portname otable[] = {
836 { AudioNspeaker, AUDIO_SPEAKER },
837 { AudioNheadphone, AUDIO_HEADPHONE },
838 { AudioNline, AUDIO_LINE_OUT },
839 { 0, 0 }
840 };
841
842 static struct psref_class *audio_psref_class __read_mostly;
843
844 CFATTACH_DECL3_NEW(audio, sizeof(struct audio_softc),
845 audiomatch, audioattach, audiodetach, audioactivate, audiorescan,
846 audiochilddet, DVF_DETACH_SHUTDOWN);
847
848 static int
849 audiomatch(device_t parent, cfdata_t match, void *aux)
850 {
851 struct audio_attach_args *sa;
852
853 sa = aux;
854 DPRINTF(1, "%s: type=%d sa=%p hw=%p\n",
855 __func__, sa->type, sa, sa->hwif);
856 return (sa->type == AUDIODEV_TYPE_AUDIO) ? 1 : 0;
857 }
858
859 static void
860 audioattach(device_t parent, device_t self, void *aux)
861 {
862 struct audio_softc *sc;
863 struct audio_attach_args *sa;
864 const struct audio_hw_if *hw_if;
865 audio_format2_t phwfmt;
866 audio_format2_t rhwfmt;
867 audio_filter_reg_t pfil;
868 audio_filter_reg_t rfil;
869 const struct sysctlnode *node;
870 void *hdlp;
871 bool has_playback;
872 bool has_capture;
873 bool has_indep;
874 bool has_fulldup;
875 int mode;
876 int error;
877
878 sc = device_private(self);
879 sc->sc_dev = self;
880 sa = (struct audio_attach_args *)aux;
881 hw_if = sa->hwif;
882 hdlp = sa->hdl;
883
884 if (hw_if == NULL) {
885 panic("audioattach: missing hw_if method");
886 }
887 if (hw_if->get_locks == NULL || hw_if->get_props == NULL) {
888 aprint_error(": missing mandatory method\n");
889 return;
890 }
891
892 hw_if->get_locks(hdlp, &sc->sc_intr_lock, &sc->sc_lock);
893 sc->sc_props = hw_if->get_props(hdlp);
894
895 has_playback = (sc->sc_props & AUDIO_PROP_PLAYBACK);
896 has_capture = (sc->sc_props & AUDIO_PROP_CAPTURE);
897 has_indep = (sc->sc_props & AUDIO_PROP_INDEPENDENT);
898 has_fulldup = (sc->sc_props & AUDIO_PROP_FULLDUPLEX);
899
900 #ifdef DIAGNOSTIC
901 if (hw_if->query_format == NULL ||
902 hw_if->set_format == NULL ||
903 hw_if->getdev == NULL ||
904 hw_if->set_port == NULL ||
905 hw_if->get_port == NULL ||
906 hw_if->query_devinfo == NULL) {
907 aprint_error(": missing mandatory method\n");
908 return;
909 }
910 if (has_playback) {
911 if ((hw_if->start_output == NULL &&
912 hw_if->trigger_output == NULL) ||
913 hw_if->halt_output == NULL) {
914 aprint_error(": missing playback method\n");
915 }
916 }
917 if (has_capture) {
918 if ((hw_if->start_input == NULL &&
919 hw_if->trigger_input == NULL) ||
920 hw_if->halt_input == NULL) {
921 aprint_error(": missing capture method\n");
922 }
923 }
924 #endif
925
926 sc->hw_if = hw_if;
927 sc->hw_hdl = hdlp;
928 sc->hw_dev = parent;
929
930 sc->sc_exlock = 1;
931 sc->sc_blk_ms = AUDIO_BLK_MS;
932 SLIST_INIT(&sc->sc_files);
933 cv_init(&sc->sc_exlockcv, "audiolk");
934 sc->sc_am_capacity = 0;
935 sc->sc_am_used = 0;
936 sc->sc_am = NULL;
937
938 /* MMAP is now supported by upper layer. */
939 sc->sc_props |= AUDIO_PROP_MMAP;
940
941 KASSERT(has_playback || has_capture);
942 /* Unidirectional device must have neither FULLDUP nor INDEPENDENT. */
943 if (!has_playback || !has_capture) {
944 KASSERT(!has_indep);
945 KASSERT(!has_fulldup);
946 }
947
948 mode = 0;
949 if (has_playback) {
950 aprint_normal(": playback");
951 mode |= AUMODE_PLAY;
952 }
953 if (has_capture) {
954 aprint_normal("%c capture", has_playback ? ',' : ':');
955 mode |= AUMODE_RECORD;
956 }
957 if (has_playback && has_capture) {
958 if (has_fulldup)
959 aprint_normal(", full duplex");
960 else
961 aprint_normal(", half duplex");
962
963 if (has_indep)
964 aprint_normal(", independent");
965 }
966
967 aprint_naive("\n");
968 aprint_normal("\n");
969
970 /* probe hw params */
971 memset(&phwfmt, 0, sizeof(phwfmt));
972 memset(&rhwfmt, 0, sizeof(rhwfmt));
973 memset(&pfil, 0, sizeof(pfil));
974 memset(&rfil, 0, sizeof(rfil));
975 if (has_indep) {
976 int perror, rerror;
977
978 /* On independent devices, probe separately. */
979 perror = audio_hw_probe(sc, &phwfmt, AUMODE_PLAY);
980 rerror = audio_hw_probe(sc, &rhwfmt, AUMODE_RECORD);
981 if (perror && rerror) {
982 aprint_error_dev(self,
983 "audio_hw_probe failed: perror=%d, rerror=%d\n",
984 perror, rerror);
985 goto bad;
986 }
987 if (perror) {
988 mode &= ~AUMODE_PLAY;
989 aprint_error_dev(self, "audio_hw_probe failed: "
990 "errno=%d, playback disabled\n", perror);
991 }
992 if (rerror) {
993 mode &= ~AUMODE_RECORD;
994 aprint_error_dev(self, "audio_hw_probe failed: "
995 "errno=%d, capture disabled\n", rerror);
996 }
997 } else {
998 /*
999 * On non independent devices or uni-directional devices,
1000 * probe once (simultaneously).
1001 */
1002 audio_format2_t *fmt = has_playback ? &phwfmt : &rhwfmt;
1003 error = audio_hw_probe(sc, fmt, mode);
1004 if (error) {
1005 aprint_error_dev(self,
1006 "audio_hw_probe failed: errno=%d\n", error);
1007 goto bad;
1008 }
1009 if (has_playback && has_capture)
1010 rhwfmt = phwfmt;
1011 }
1012
1013 /* Init hardware. */
1014 /* hw_probe() also validates [pr]hwfmt. */
1015 error = audio_hw_set_format(sc, mode, &phwfmt, &rhwfmt, &pfil, &rfil);
1016 if (error) {
1017 aprint_error_dev(self,
1018 "audio_hw_set_format failed: errno=%d\n", error);
1019 goto bad;
1020 }
1021
1022 /*
1023 * Init track mixers. If at least one direction is available on
1024 * attach time, we assume a success.
1025 */
1026 error = audio_mixers_init(sc, mode, &phwfmt, &rhwfmt, &pfil, &rfil);
1027 if (sc->sc_pmixer == NULL && sc->sc_rmixer == NULL) {
1028 aprint_error_dev(self,
1029 "audio_mixers_init failed: errno=%d\n", error);
1030 goto bad;
1031 }
1032
1033 sc->sc_psz = pserialize_create();
1034 psref_target_init(&sc->sc_psref, audio_psref_class);
1035
1036 selinit(&sc->sc_wsel);
1037 selinit(&sc->sc_rsel);
1038
1039 /* Initial parameter of /dev/sound */
1040 sc->sc_sound_pparams = params_to_format2(&audio_default);
1041 sc->sc_sound_rparams = params_to_format2(&audio_default);
1042 sc->sc_sound_ppause = false;
1043 sc->sc_sound_rpause = false;
1044
1045 /* XXX TODO: consider about sc_ai */
1046
1047 mixer_init(sc);
1048 TRACE(2, "inputs ports=0x%x, input master=%d, "
1049 "output ports=0x%x, output master=%d",
1050 sc->sc_inports.allports, sc->sc_inports.master,
1051 sc->sc_outports.allports, sc->sc_outports.master);
1052
1053 sysctl_createv(&sc->sc_log, 0, NULL, &node,
1054 0,
1055 CTLTYPE_NODE, device_xname(sc->sc_dev),
1056 SYSCTL_DESCR("audio test"),
1057 NULL, 0,
1058 NULL, 0,
1059 CTL_HW,
1060 CTL_CREATE, CTL_EOL);
1061
1062 if (node != NULL) {
1063 sysctl_createv(&sc->sc_log, 0, NULL, NULL,
1064 CTLFLAG_READWRITE,
1065 CTLTYPE_INT, "blk_ms",
1066 SYSCTL_DESCR("blocksize in msec"),
1067 audio_sysctl_blk_ms, 0, (void *)sc, 0,
1068 CTL_HW, node->sysctl_num, CTL_CREATE, CTL_EOL);
1069
1070 sysctl_createv(&sc->sc_log, 0, NULL, NULL,
1071 CTLFLAG_READWRITE,
1072 CTLTYPE_BOOL, "multiuser",
1073 SYSCTL_DESCR("allow multiple user access"),
1074 audio_sysctl_multiuser, 0, (void *)sc, 0,
1075 CTL_HW, node->sysctl_num, CTL_CREATE, CTL_EOL);
1076
1077 #if defined(AUDIO_DEBUG)
1078 sysctl_createv(&sc->sc_log, 0, NULL, NULL,
1079 CTLFLAG_READWRITE,
1080 CTLTYPE_INT, "debug",
1081 SYSCTL_DESCR("debug level (0..4)"),
1082 audio_sysctl_debug, 0, (void *)sc, 0,
1083 CTL_HW, node->sysctl_num, CTL_CREATE, CTL_EOL);
1084 #endif
1085 }
1086
1087 #ifdef AUDIO_PM_IDLE
1088 callout_init(&sc->sc_idle_counter, 0);
1089 callout_setfunc(&sc->sc_idle_counter, audio_idle, self);
1090 #endif
1091
1092 if (!pmf_device_register(self, audio_suspend, audio_resume))
1093 aprint_error_dev(self, "couldn't establish power handler\n");
1094 #ifdef AUDIO_PM_IDLE
1095 if (!device_active_register(self, audio_activity))
1096 aprint_error_dev(self, "couldn't register activity handler\n");
1097 #endif
1098
1099 if (!pmf_event_register(self, PMFE_AUDIO_VOLUME_DOWN,
1100 audio_volume_down, true))
1101 aprint_error_dev(self, "couldn't add volume down handler\n");
1102 if (!pmf_event_register(self, PMFE_AUDIO_VOLUME_UP,
1103 audio_volume_up, true))
1104 aprint_error_dev(self, "couldn't add volume up handler\n");
1105 if (!pmf_event_register(self, PMFE_AUDIO_VOLUME_TOGGLE,
1106 audio_volume_toggle, true))
1107 aprint_error_dev(self, "couldn't add volume toggle handler\n");
1108
1109 #ifdef AUDIO_PM_IDLE
1110 callout_schedule(&sc->sc_idle_counter, audio_idle_timeout * hz);
1111 #endif
1112
1113 #if defined(AUDIO_DEBUG)
1114 audio_mlog_init();
1115 #endif
1116
1117 audiorescan(self, NULL, NULL);
1118 sc->sc_exlock = 0;
1119 return;
1120
1121 bad:
1122 /* Clearing hw_if means that device is attached but disabled. */
1123 sc->hw_if = NULL;
1124 sc->sc_exlock = 0;
1125 aprint_error_dev(sc->sc_dev, "disabled\n");
1126 return;
1127 }
1128
1129 /*
1130 * Initialize hardware mixer.
1131 * This function is called from audioattach().
1132 */
1133 static void
1134 mixer_init(struct audio_softc *sc)
1135 {
1136 mixer_devinfo_t mi;
1137 int iclass, mclass, oclass, rclass;
1138 int record_master_found, record_source_found;
1139
1140 iclass = mclass = oclass = rclass = -1;
1141 sc->sc_inports.index = -1;
1142 sc->sc_inports.master = -1;
1143 sc->sc_inports.nports = 0;
1144 sc->sc_inports.isenum = false;
1145 sc->sc_inports.allports = 0;
1146 sc->sc_inports.isdual = false;
1147 sc->sc_inports.mixerout = -1;
1148 sc->sc_inports.cur_port = -1;
1149 sc->sc_outports.index = -1;
1150 sc->sc_outports.master = -1;
1151 sc->sc_outports.nports = 0;
1152 sc->sc_outports.isenum = false;
1153 sc->sc_outports.allports = 0;
1154 sc->sc_outports.isdual = false;
1155 sc->sc_outports.mixerout = -1;
1156 sc->sc_outports.cur_port = -1;
1157 sc->sc_monitor_port = -1;
1158 /*
1159 * Read through the underlying driver's list, picking out the class
1160 * names from the mixer descriptions. We'll need them to decode the
1161 * mixer descriptions on the next pass through the loop.
1162 */
1163 mutex_enter(sc->sc_lock);
1164 for(mi.index = 0; ; mi.index++) {
1165 if (audio_query_devinfo(sc, &mi) != 0)
1166 break;
1167 /*
1168 * The type of AUDIO_MIXER_CLASS merely introduces a class.
1169 * All the other types describe an actual mixer.
1170 */
1171 if (mi.type == AUDIO_MIXER_CLASS) {
1172 if (strcmp(mi.label.name, AudioCinputs) == 0)
1173 iclass = mi.mixer_class;
1174 if (strcmp(mi.label.name, AudioCmonitor) == 0)
1175 mclass = mi.mixer_class;
1176 if (strcmp(mi.label.name, AudioCoutputs) == 0)
1177 oclass = mi.mixer_class;
1178 if (strcmp(mi.label.name, AudioCrecord) == 0)
1179 rclass = mi.mixer_class;
1180 }
1181 }
1182 mutex_exit(sc->sc_lock);
1183
1184 /* Allocate save area. Ensure non-zero allocation. */
1185 sc->sc_nmixer_states = mi.index;
1186 sc->sc_mixer_state = kmem_zalloc(sizeof(sc->sc_mixer_state[0]) *
1187 (sc->sc_nmixer_states + 1), KM_SLEEP);
1188
1189 /*
1190 * This is where we assign each control in the "audio" model, to the
1191 * underlying "mixer" control. We walk through the whole list once,
1192 * assigning likely candidates as we come across them.
1193 */
1194 record_master_found = 0;
1195 record_source_found = 0;
1196 mutex_enter(sc->sc_lock);
1197 for(mi.index = 0; ; mi.index++) {
1198 if (audio_query_devinfo(sc, &mi) != 0)
1199 break;
1200 KASSERT(mi.index < sc->sc_nmixer_states);
1201 if (mi.type == AUDIO_MIXER_CLASS)
1202 continue;
1203 if (mi.mixer_class == iclass) {
1204 /*
1205 * AudioCinputs is only a fallback, when we don't
1206 * find what we're looking for in AudioCrecord, so
1207 * check the flags before accepting one of these.
1208 */
1209 if (strcmp(mi.label.name, AudioNmaster) == 0
1210 && record_master_found == 0)
1211 sc->sc_inports.master = mi.index;
1212 if (strcmp(mi.label.name, AudioNsource) == 0
1213 && record_source_found == 0) {
1214 if (mi.type == AUDIO_MIXER_ENUM) {
1215 int i;
1216 for(i = 0; i < mi.un.e.num_mem; i++)
1217 if (strcmp(mi.un.e.member[i].label.name,
1218 AudioNmixerout) == 0)
1219 sc->sc_inports.mixerout =
1220 mi.un.e.member[i].ord;
1221 }
1222 au_setup_ports(sc, &sc->sc_inports, &mi,
1223 itable);
1224 }
1225 if (strcmp(mi.label.name, AudioNdac) == 0 &&
1226 sc->sc_outports.master == -1)
1227 sc->sc_outports.master = mi.index;
1228 } else if (mi.mixer_class == mclass) {
1229 if (strcmp(mi.label.name, AudioNmonitor) == 0)
1230 sc->sc_monitor_port = mi.index;
1231 } else if (mi.mixer_class == oclass) {
1232 if (strcmp(mi.label.name, AudioNmaster) == 0)
1233 sc->sc_outports.master = mi.index;
1234 if (strcmp(mi.label.name, AudioNselect) == 0)
1235 au_setup_ports(sc, &sc->sc_outports, &mi,
1236 otable);
1237 } else if (mi.mixer_class == rclass) {
1238 /*
1239 * These are the preferred mixers for the audio record
1240 * controls, so set the flags here, but don't check.
1241 */
1242 if (strcmp(mi.label.name, AudioNmaster) == 0) {
1243 sc->sc_inports.master = mi.index;
1244 record_master_found = 1;
1245 }
1246 #if 1 /* Deprecated. Use AudioNmaster. */
1247 if (strcmp(mi.label.name, AudioNrecord) == 0) {
1248 sc->sc_inports.master = mi.index;
1249 record_master_found = 1;
1250 }
1251 if (strcmp(mi.label.name, AudioNvolume) == 0) {
1252 sc->sc_inports.master = mi.index;
1253 record_master_found = 1;
1254 }
1255 #endif
1256 if (strcmp(mi.label.name, AudioNsource) == 0) {
1257 if (mi.type == AUDIO_MIXER_ENUM) {
1258 int i;
1259 for(i = 0; i < mi.un.e.num_mem; i++)
1260 if (strcmp(mi.un.e.member[i].label.name,
1261 AudioNmixerout) == 0)
1262 sc->sc_inports.mixerout =
1263 mi.un.e.member[i].ord;
1264 }
1265 au_setup_ports(sc, &sc->sc_inports, &mi,
1266 itable);
1267 record_source_found = 1;
1268 }
1269 }
1270 }
1271 mutex_exit(sc->sc_lock);
1272 }
1273
1274 static int
1275 audioactivate(device_t self, enum devact act)
1276 {
1277 struct audio_softc *sc = device_private(self);
1278
1279 switch (act) {
1280 case DVACT_DEACTIVATE:
1281 mutex_enter(sc->sc_lock);
1282 sc->sc_dying = true;
1283 cv_broadcast(&sc->sc_exlockcv);
1284 mutex_exit(sc->sc_lock);
1285 return 0;
1286 default:
1287 return EOPNOTSUPP;
1288 }
1289 }
1290
1291 static int
1292 audiodetach(device_t self, int flags)
1293 {
1294 struct audio_softc *sc;
1295 struct audio_file *file;
1296 int error;
1297
1298 sc = device_private(self);
1299 TRACE(2, "flags=%d", flags);
1300
1301 /* device is not initialized */
1302 if (sc->hw_if == NULL)
1303 return 0;
1304
1305 /* Start draining existing accessors of the device. */
1306 error = config_detach_children(self, flags);
1307 if (error)
1308 return error;
1309
1310 /*
1311 * This waits currently running sysctls to finish if exists.
1312 * After this, no more new sysctls will come.
1313 */
1314 sysctl_teardown(&sc->sc_log);
1315
1316 mutex_enter(sc->sc_lock);
1317 sc->sc_dying = true;
1318 cv_broadcast(&sc->sc_exlockcv);
1319 if (sc->sc_pmixer)
1320 cv_broadcast(&sc->sc_pmixer->outcv);
1321 if (sc->sc_rmixer)
1322 cv_broadcast(&sc->sc_rmixer->outcv);
1323
1324 /* Prevent new users */
1325 SLIST_FOREACH(file, &sc->sc_files, entry) {
1326 atomic_store_relaxed(&file->dying, true);
1327 }
1328 mutex_exit(sc->sc_lock);
1329
1330 /*
1331 * Wait for existing users to drain.
1332 * - pserialize_perform waits for all pserialize_read sections on
1333 * all CPUs; after this, no more new psref_acquire can happen.
1334 * - psref_target_destroy waits for all extant acquired psrefs to
1335 * be psref_released.
1336 */
1337 pserialize_perform(sc->sc_psz);
1338 psref_target_destroy(&sc->sc_psref, audio_psref_class);
1339
1340 /*
1341 * We are now guaranteed that there are no calls to audio fileops
1342 * that hold sc, and any new calls with files that were for sc will
1343 * fail. Thus, we now have exclusive access to the softc.
1344 */
1345 sc->sc_exlock = 1;
1346
1347 /*
1348 * Clean up all open instances.
1349 */
1350 mutex_enter(sc->sc_lock);
1351 while ((file = SLIST_FIRST(&sc->sc_files)) != NULL) {
1352 mutex_enter(sc->sc_intr_lock);
1353 SLIST_REMOVE_HEAD(&sc->sc_files, entry);
1354 mutex_exit(sc->sc_intr_lock);
1355 if (file->ptrack || file->rtrack) {
1356 mutex_exit(sc->sc_lock);
1357 audio_unlink(sc, file);
1358 mutex_enter(sc->sc_lock);
1359 }
1360 }
1361 mutex_exit(sc->sc_lock);
1362
1363 pmf_event_deregister(self, PMFE_AUDIO_VOLUME_DOWN,
1364 audio_volume_down, true);
1365 pmf_event_deregister(self, PMFE_AUDIO_VOLUME_UP,
1366 audio_volume_up, true);
1367 pmf_event_deregister(self, PMFE_AUDIO_VOLUME_TOGGLE,
1368 audio_volume_toggle, true);
1369
1370 #ifdef AUDIO_PM_IDLE
1371 callout_halt(&sc->sc_idle_counter, sc->sc_lock);
1372
1373 device_active_deregister(self, audio_activity);
1374 #endif
1375
1376 pmf_device_deregister(self);
1377
1378 /* Free resources */
1379 if (sc->sc_pmixer) {
1380 audio_mixer_destroy(sc, sc->sc_pmixer);
1381 kmem_free(sc->sc_pmixer, sizeof(*sc->sc_pmixer));
1382 }
1383 if (sc->sc_rmixer) {
1384 audio_mixer_destroy(sc, sc->sc_rmixer);
1385 kmem_free(sc->sc_rmixer, sizeof(*sc->sc_rmixer));
1386 }
1387 if (sc->sc_am)
1388 kern_free(sc->sc_am);
1389
1390 seldestroy(&sc->sc_wsel);
1391 seldestroy(&sc->sc_rsel);
1392
1393 #ifdef AUDIO_PM_IDLE
1394 callout_destroy(&sc->sc_idle_counter);
1395 #endif
1396
1397 cv_destroy(&sc->sc_exlockcv);
1398
1399 #if defined(AUDIO_DEBUG)
1400 audio_mlog_free();
1401 #endif
1402
1403 return 0;
1404 }
1405
1406 static void
1407 audiochilddet(device_t self, device_t child)
1408 {
1409
1410 /* we hold no child references, so do nothing */
1411 }
1412
1413 static int
1414 audiosearch(device_t parent, cfdata_t cf, const int *locs, void *aux)
1415 {
1416
1417 if (config_probe(parent, cf, aux))
1418 config_attach(parent, cf, aux, NULL,
1419 CFARGS_NONE);
1420
1421 return 0;
1422 }
1423
1424 static int
1425 audiorescan(device_t self, const char *ifattr, const int *locators)
1426 {
1427 struct audio_softc *sc = device_private(self);
1428
1429 config_search(sc->sc_dev, NULL,
1430 CFARGS(.search = audiosearch));
1431
1432 return 0;
1433 }
1434
1435 /*
1436 * Called from hardware driver. This is where the MI audio driver gets
1437 * probed/attached to the hardware driver.
1438 */
1439 device_t
1440 audio_attach_mi(const struct audio_hw_if *ahwp, void *hdlp, device_t dev)
1441 {
1442 struct audio_attach_args arg;
1443
1444 #ifdef DIAGNOSTIC
1445 if (ahwp == NULL) {
1446 aprint_error("audio_attach_mi: NULL\n");
1447 return 0;
1448 }
1449 #endif
1450 arg.type = AUDIODEV_TYPE_AUDIO;
1451 arg.hwif = ahwp;
1452 arg.hdl = hdlp;
1453 return config_found(dev, &arg, audioprint,
1454 CFARGS(.iattr = "audiobus"));
1455 }
1456
1457 /*
1458 * audio_printf() outputs fmt... with the audio device name and MD device
1459 * name prefixed. If the message is considered to be related to the MD
1460 * driver, use this one instead of device_printf().
1461 */
1462 static void
1463 audio_printf(struct audio_softc *sc, const char *fmt, ...)
1464 {
1465 va_list ap;
1466
1467 printf("%s(%s): ", device_xname(sc->sc_dev), device_xname(sc->hw_dev));
1468 va_start(ap, fmt);
1469 vprintf(fmt, ap);
1470 va_end(ap);
1471 }
1472
1473 /*
1474 * Enter critical section and also keep sc_lock.
1475 * If successful, returns 0 with sc_lock held. Otherwise returns errno.
1476 * Must be called without sc_lock held.
1477 */
1478 static int
1479 audio_exlock_mutex_enter(struct audio_softc *sc)
1480 {
1481 int error;
1482
1483 mutex_enter(sc->sc_lock);
1484 if (sc->sc_dying) {
1485 mutex_exit(sc->sc_lock);
1486 return EIO;
1487 }
1488
1489 while (__predict_false(sc->sc_exlock != 0)) {
1490 error = cv_wait_sig(&sc->sc_exlockcv, sc->sc_lock);
1491 if (sc->sc_dying)
1492 error = EIO;
1493 if (error) {
1494 mutex_exit(sc->sc_lock);
1495 return error;
1496 }
1497 }
1498
1499 /* Acquire */
1500 sc->sc_exlock = 1;
1501 return 0;
1502 }
1503
1504 /*
1505 * Exit critical section and exit sc_lock.
1506 * Must be called with sc_lock held.
1507 */
1508 static void
1509 audio_exlock_mutex_exit(struct audio_softc *sc)
1510 {
1511
1512 KASSERT(mutex_owned(sc->sc_lock));
1513
1514 sc->sc_exlock = 0;
1515 cv_broadcast(&sc->sc_exlockcv);
1516 mutex_exit(sc->sc_lock);
1517 }
1518
1519 /*
1520 * Enter critical section.
1521 * If successful, it returns 0. Otherwise returns errno.
1522 * Must be called without sc_lock held.
1523 * This function returns without sc_lock held.
1524 */
1525 static int
1526 audio_exlock_enter(struct audio_softc *sc)
1527 {
1528 int error;
1529
1530 error = audio_exlock_mutex_enter(sc);
1531 if (error)
1532 return error;
1533 mutex_exit(sc->sc_lock);
1534 return 0;
1535 }
1536
1537 /*
1538 * Exit critical section.
1539 * Must be called without sc_lock held.
1540 */
1541 static void
1542 audio_exlock_exit(struct audio_softc *sc)
1543 {
1544
1545 mutex_enter(sc->sc_lock);
1546 audio_exlock_mutex_exit(sc);
1547 }
1548
1549 /*
1550 * Increment reference counter for this sc.
1551 * This is intended to be used for open.
1552 */
1553 void
1554 audio_sc_acquire_foropen(struct audio_softc *sc, struct psref *refp)
1555 {
1556 int s;
1557
1558 /* Block audiodetach while we acquire a reference */
1559 s = pserialize_read_enter();
1560
1561 /*
1562 * We don't examine sc_dying here. However, all open methods
1563 * call audio_exlock_enter() right after this, so we can examine
1564 * sc_dying in it.
1565 */
1566
1567 /* Acquire a reference */
1568 psref_acquire(refp, &sc->sc_psref, audio_psref_class);
1569
1570 /* Now sc won't go away until we drop the reference count */
1571 pserialize_read_exit(s);
1572 }
1573
1574 /*
1575 * Get sc from file, and increment reference counter for this sc.
1576 * This is intended to be used for methods other than open.
1577 * If successful, returns sc. Otherwise returns NULL.
1578 */
1579 struct audio_softc *
1580 audio_sc_acquire_fromfile(audio_file_t *file, struct psref *refp)
1581 {
1582 int s;
1583 bool dying;
1584
1585 /* Block audiodetach while we acquire a reference */
1586 s = pserialize_read_enter();
1587
1588 /* If close or audiodetach already ran, tough -- no more audio */
1589 dying = atomic_load_relaxed(&file->dying);
1590 if (dying) {
1591 pserialize_read_exit(s);
1592 return NULL;
1593 }
1594
1595 /* Acquire a reference */
1596 psref_acquire(refp, &file->sc->sc_psref, audio_psref_class);
1597
1598 /* Now sc won't go away until we drop the reference count */
1599 pserialize_read_exit(s);
1600
1601 return file->sc;
1602 }
1603
1604 /*
1605 * Decrement reference counter for this sc.
1606 */
1607 void
1608 audio_sc_release(struct audio_softc *sc, struct psref *refp)
1609 {
1610
1611 psref_release(refp, &sc->sc_psref, audio_psref_class);
1612 }
1613
1614 /*
1615 * Wait for I/O to complete, releasing sc_lock.
1616 * Must be called with sc_lock held.
1617 */
1618 static int
1619 audio_track_waitio(struct audio_softc *sc, audio_track_t *track)
1620 {
1621 int error;
1622
1623 KASSERT(track);
1624 KASSERT(mutex_owned(sc->sc_lock));
1625
1626 /* Wait for pending I/O to complete. */
1627 error = cv_timedwait_sig(&track->mixer->outcv, sc->sc_lock,
1628 mstohz(AUDIO_TIMEOUT));
1629 if (sc->sc_suspending) {
1630 /* If it's about to suspend, ignore timeout error. */
1631 if (error == EWOULDBLOCK) {
1632 TRACET(2, track, "timeout (suspending)");
1633 return 0;
1634 }
1635 }
1636 if (sc->sc_dying) {
1637 error = EIO;
1638 }
1639 if (error) {
1640 TRACET(2, track, "cv_timedwait_sig failed %d", error);
1641 if (error == EWOULDBLOCK)
1642 audio_printf(sc, "device timeout\n");
1643 } else {
1644 TRACET(3, track, "wakeup");
1645 }
1646 return error;
1647 }
1648
1649 /*
1650 * Try to acquire track lock.
1651 * It doesn't block if the track lock is already acquired.
1652 * Returns true if the track lock was acquired, or false if the track
1653 * lock was already acquired.
1654 */
1655 static __inline bool
1656 audio_track_lock_tryenter(audio_track_t *track)
1657 {
1658
1659 if (atomic_swap_uint(&track->lock, 1) != 0)
1660 return false;
1661 membar_enter();
1662 return true;
1663 }
1664
1665 /*
1666 * Acquire track lock.
1667 */
1668 static __inline void
1669 audio_track_lock_enter(audio_track_t *track)
1670 {
1671
1672 /* Don't sleep here. */
1673 while (audio_track_lock_tryenter(track) == false)
1674 SPINLOCK_BACKOFF_HOOK;
1675 }
1676
1677 /*
1678 * Release track lock.
1679 */
1680 static __inline void
1681 audio_track_lock_exit(audio_track_t *track)
1682 {
1683
1684 atomic_store_release(&track->lock, 0);
1685 }
1686
1687
1688 static int
1689 audioopen(dev_t dev, int flags, int ifmt, struct lwp *l)
1690 {
1691 struct audio_softc *sc;
1692 struct psref sc_ref;
1693 int bound;
1694 int error;
1695
1696 /* Find the device */
1697 sc = device_lookup_private(&audio_cd, AUDIOUNIT(dev));
1698 if (sc == NULL || sc->hw_if == NULL)
1699 return ENXIO;
1700
1701 bound = curlwp_bind();
1702 audio_sc_acquire_foropen(sc, &sc_ref);
1703
1704 error = audio_exlock_enter(sc);
1705 if (error)
1706 goto done;
1707
1708 device_active(sc->sc_dev, DVA_SYSTEM);
1709 switch (AUDIODEV(dev)) {
1710 case SOUND_DEVICE:
1711 case AUDIO_DEVICE:
1712 error = audio_open(dev, sc, flags, ifmt, l, NULL);
1713 break;
1714 case AUDIOCTL_DEVICE:
1715 error = audioctl_open(dev, sc, flags, ifmt, l);
1716 break;
1717 case MIXER_DEVICE:
1718 error = mixer_open(dev, sc, flags, ifmt, l);
1719 break;
1720 default:
1721 error = ENXIO;
1722 break;
1723 }
1724 audio_exlock_exit(sc);
1725
1726 done:
1727 audio_sc_release(sc, &sc_ref);
1728 curlwp_bindx(bound);
1729 return error;
1730 }
1731
1732 static int
1733 audioclose(struct file *fp)
1734 {
1735 struct audio_softc *sc;
1736 struct psref sc_ref;
1737 audio_file_t *file;
1738 int bound;
1739 int error;
1740 dev_t dev;
1741
1742 KASSERT(fp->f_audioctx);
1743 file = fp->f_audioctx;
1744 dev = file->dev;
1745 error = 0;
1746
1747 /*
1748 * audioclose() must
1749 * - unplug track from the trackmixer (and unplug anything from softc),
1750 * if sc exists.
1751 * - free all memory objects, regardless of sc.
1752 */
1753
1754 bound = curlwp_bind();
1755 sc = audio_sc_acquire_fromfile(file, &sc_ref);
1756 if (sc) {
1757 switch (AUDIODEV(dev)) {
1758 case SOUND_DEVICE:
1759 case AUDIO_DEVICE:
1760 error = audio_close(sc, file);
1761 break;
1762 case AUDIOCTL_DEVICE:
1763 mutex_enter(sc->sc_lock);
1764 mutex_enter(sc->sc_intr_lock);
1765 SLIST_REMOVE(&sc->sc_files, file, audio_file, entry);
1766 mutex_exit(sc->sc_intr_lock);
1767 mutex_exit(sc->sc_lock);
1768 error = 0;
1769 break;
1770 case MIXER_DEVICE:
1771 mutex_enter(sc->sc_lock);
1772 mutex_enter(sc->sc_intr_lock);
1773 SLIST_REMOVE(&sc->sc_files, file, audio_file, entry);
1774 mutex_exit(sc->sc_intr_lock);
1775 mutex_exit(sc->sc_lock);
1776 error = mixer_close(sc, file);
1777 break;
1778 default:
1779 error = ENXIO;
1780 break;
1781 }
1782
1783 audio_sc_release(sc, &sc_ref);
1784 }
1785 curlwp_bindx(bound);
1786
1787 /* Free memory objects anyway */
1788 TRACEF(2, file, "free memory");
1789 if (file->ptrack)
1790 audio_track_destroy(file->ptrack);
1791 if (file->rtrack)
1792 audio_track_destroy(file->rtrack);
1793 kmem_free(file, sizeof(*file));
1794 fp->f_audioctx = NULL;
1795
1796 return error;
1797 }
1798
1799 static int
1800 audioread(struct file *fp, off_t *offp, struct uio *uio, kauth_cred_t cred,
1801 int ioflag)
1802 {
1803 struct audio_softc *sc;
1804 struct psref sc_ref;
1805 audio_file_t *file;
1806 int bound;
1807 int error;
1808 dev_t dev;
1809
1810 KASSERT(fp->f_audioctx);
1811 file = fp->f_audioctx;
1812 dev = file->dev;
1813
1814 bound = curlwp_bind();
1815 sc = audio_sc_acquire_fromfile(file, &sc_ref);
1816 if (sc == NULL) {
1817 error = EIO;
1818 goto done;
1819 }
1820
1821 if (fp->f_flag & O_NONBLOCK)
1822 ioflag |= IO_NDELAY;
1823
1824 switch (AUDIODEV(dev)) {
1825 case SOUND_DEVICE:
1826 case AUDIO_DEVICE:
1827 error = audio_read(sc, uio, ioflag, file);
1828 break;
1829 case AUDIOCTL_DEVICE:
1830 case MIXER_DEVICE:
1831 error = ENODEV;
1832 break;
1833 default:
1834 error = ENXIO;
1835 break;
1836 }
1837
1838 audio_sc_release(sc, &sc_ref);
1839 done:
1840 curlwp_bindx(bound);
1841 return error;
1842 }
1843
1844 static int
1845 audiowrite(struct file *fp, off_t *offp, struct uio *uio, kauth_cred_t cred,
1846 int ioflag)
1847 {
1848 struct audio_softc *sc;
1849 struct psref sc_ref;
1850 audio_file_t *file;
1851 int bound;
1852 int error;
1853 dev_t dev;
1854
1855 KASSERT(fp->f_audioctx);
1856 file = fp->f_audioctx;
1857 dev = file->dev;
1858
1859 bound = curlwp_bind();
1860 sc = audio_sc_acquire_fromfile(file, &sc_ref);
1861 if (sc == NULL) {
1862 error = EIO;
1863 goto done;
1864 }
1865
1866 if (fp->f_flag & O_NONBLOCK)
1867 ioflag |= IO_NDELAY;
1868
1869 switch (AUDIODEV(dev)) {
1870 case SOUND_DEVICE:
1871 case AUDIO_DEVICE:
1872 error = audio_write(sc, uio, ioflag, file);
1873 break;
1874 case AUDIOCTL_DEVICE:
1875 case MIXER_DEVICE:
1876 error = ENODEV;
1877 break;
1878 default:
1879 error = ENXIO;
1880 break;
1881 }
1882
1883 audio_sc_release(sc, &sc_ref);
1884 done:
1885 curlwp_bindx(bound);
1886 return error;
1887 }
1888
1889 static int
1890 audioioctl(struct file *fp, u_long cmd, void *addr)
1891 {
1892 struct audio_softc *sc;
1893 struct psref sc_ref;
1894 audio_file_t *file;
1895 struct lwp *l = curlwp;
1896 int bound;
1897 int error;
1898 dev_t dev;
1899
1900 KASSERT(fp->f_audioctx);
1901 file = fp->f_audioctx;
1902 dev = file->dev;
1903
1904 bound = curlwp_bind();
1905 sc = audio_sc_acquire_fromfile(file, &sc_ref);
1906 if (sc == NULL) {
1907 error = EIO;
1908 goto done;
1909 }
1910
1911 switch (AUDIODEV(dev)) {
1912 case SOUND_DEVICE:
1913 case AUDIO_DEVICE:
1914 case AUDIOCTL_DEVICE:
1915 mutex_enter(sc->sc_lock);
1916 device_active(sc->sc_dev, DVA_SYSTEM);
1917 mutex_exit(sc->sc_lock);
1918 if (IOCGROUP(cmd) == IOCGROUP(AUDIO_MIXER_READ))
1919 error = mixer_ioctl(sc, cmd, addr, fp->f_flag, l);
1920 else
1921 error = audio_ioctl(dev, sc, cmd, addr, fp->f_flag, l,
1922 file);
1923 break;
1924 case MIXER_DEVICE:
1925 error = mixer_ioctl(sc, cmd, addr, fp->f_flag, l);
1926 break;
1927 default:
1928 error = ENXIO;
1929 break;
1930 }
1931
1932 audio_sc_release(sc, &sc_ref);
1933 done:
1934 curlwp_bindx(bound);
1935 return error;
1936 }
1937
1938 static int
1939 audiostat(struct file *fp, struct stat *st)
1940 {
1941 struct audio_softc *sc;
1942 struct psref sc_ref;
1943 audio_file_t *file;
1944 int bound;
1945 int error;
1946
1947 KASSERT(fp->f_audioctx);
1948 file = fp->f_audioctx;
1949
1950 bound = curlwp_bind();
1951 sc = audio_sc_acquire_fromfile(file, &sc_ref);
1952 if (sc == NULL) {
1953 error = EIO;
1954 goto done;
1955 }
1956
1957 error = 0;
1958 memset(st, 0, sizeof(*st));
1959
1960 st->st_dev = file->dev;
1961 st->st_uid = kauth_cred_geteuid(fp->f_cred);
1962 st->st_gid = kauth_cred_getegid(fp->f_cred);
1963 st->st_mode = S_IFCHR;
1964
1965 audio_sc_release(sc, &sc_ref);
1966 done:
1967 curlwp_bindx(bound);
1968 return error;
1969 }
1970
1971 static int
1972 audiopoll(struct file *fp, int events)
1973 {
1974 struct audio_softc *sc;
1975 struct psref sc_ref;
1976 audio_file_t *file;
1977 struct lwp *l = curlwp;
1978 int bound;
1979 int revents;
1980 dev_t dev;
1981
1982 KASSERT(fp->f_audioctx);
1983 file = fp->f_audioctx;
1984 dev = file->dev;
1985
1986 bound = curlwp_bind();
1987 sc = audio_sc_acquire_fromfile(file, &sc_ref);
1988 if (sc == NULL) {
1989 revents = POLLERR;
1990 goto done;
1991 }
1992
1993 switch (AUDIODEV(dev)) {
1994 case SOUND_DEVICE:
1995 case AUDIO_DEVICE:
1996 revents = audio_poll(sc, events, l, file);
1997 break;
1998 case AUDIOCTL_DEVICE:
1999 case MIXER_DEVICE:
2000 revents = 0;
2001 break;
2002 default:
2003 revents = POLLERR;
2004 break;
2005 }
2006
2007 audio_sc_release(sc, &sc_ref);
2008 done:
2009 curlwp_bindx(bound);
2010 return revents;
2011 }
2012
2013 static int
2014 audiokqfilter(struct file *fp, struct knote *kn)
2015 {
2016 struct audio_softc *sc;
2017 struct psref sc_ref;
2018 audio_file_t *file;
2019 dev_t dev;
2020 int bound;
2021 int error;
2022
2023 KASSERT(fp->f_audioctx);
2024 file = fp->f_audioctx;
2025 dev = file->dev;
2026
2027 bound = curlwp_bind();
2028 sc = audio_sc_acquire_fromfile(file, &sc_ref);
2029 if (sc == NULL) {
2030 error = EIO;
2031 goto done;
2032 }
2033
2034 switch (AUDIODEV(dev)) {
2035 case SOUND_DEVICE:
2036 case AUDIO_DEVICE:
2037 error = audio_kqfilter(sc, file, kn);
2038 break;
2039 case AUDIOCTL_DEVICE:
2040 case MIXER_DEVICE:
2041 error = ENODEV;
2042 break;
2043 default:
2044 error = ENXIO;
2045 break;
2046 }
2047
2048 audio_sc_release(sc, &sc_ref);
2049 done:
2050 curlwp_bindx(bound);
2051 return error;
2052 }
2053
2054 static int
2055 audiommap(struct file *fp, off_t *offp, size_t len, int prot, int *flagsp,
2056 int *advicep, struct uvm_object **uobjp, int *maxprotp)
2057 {
2058 struct audio_softc *sc;
2059 struct psref sc_ref;
2060 audio_file_t *file;
2061 dev_t dev;
2062 int bound;
2063 int error;
2064
2065 KASSERT(fp->f_audioctx);
2066 file = fp->f_audioctx;
2067 dev = file->dev;
2068
2069 bound = curlwp_bind();
2070 sc = audio_sc_acquire_fromfile(file, &sc_ref);
2071 if (sc == NULL) {
2072 error = EIO;
2073 goto done;
2074 }
2075
2076 mutex_enter(sc->sc_lock);
2077 device_active(sc->sc_dev, DVA_SYSTEM); /* XXXJDM */
2078 mutex_exit(sc->sc_lock);
2079
2080 switch (AUDIODEV(dev)) {
2081 case SOUND_DEVICE:
2082 case AUDIO_DEVICE:
2083 error = audio_mmap(sc, offp, len, prot, flagsp, advicep,
2084 uobjp, maxprotp, file);
2085 break;
2086 case AUDIOCTL_DEVICE:
2087 case MIXER_DEVICE:
2088 default:
2089 error = ENOTSUP;
2090 break;
2091 }
2092
2093 audio_sc_release(sc, &sc_ref);
2094 done:
2095 curlwp_bindx(bound);
2096 return error;
2097 }
2098
2099
2100 /* Exported interfaces for audiobell. */
2101
2102 /*
2103 * Open for audiobell.
2104 * It stores allocated file to *filep.
2105 * If successful returns 0, otherwise errno.
2106 */
2107 int
2108 audiobellopen(dev_t dev, audio_file_t **filep)
2109 {
2110 struct audio_softc *sc;
2111 struct psref sc_ref;
2112 int bound;
2113 int error;
2114
2115 /* Find the device */
2116 sc = device_lookup_private(&audio_cd, AUDIOUNIT(dev));
2117 if (sc == NULL || sc->hw_if == NULL)
2118 return ENXIO;
2119
2120 bound = curlwp_bind();
2121 audio_sc_acquire_foropen(sc, &sc_ref);
2122
2123 error = audio_exlock_enter(sc);
2124 if (error)
2125 goto done;
2126
2127 device_active(sc->sc_dev, DVA_SYSTEM);
2128 error = audio_open(dev, sc, FWRITE, 0, curlwp, filep);
2129
2130 audio_exlock_exit(sc);
2131 done:
2132 audio_sc_release(sc, &sc_ref);
2133 curlwp_bindx(bound);
2134 return error;
2135 }
2136
2137 /* Close for audiobell */
2138 int
2139 audiobellclose(audio_file_t *file)
2140 {
2141 struct audio_softc *sc;
2142 struct psref sc_ref;
2143 int bound;
2144 int error;
2145
2146 error = 0;
2147 /*
2148 * audiobellclose() must
2149 * - unplug track from the trackmixer if sc exist.
2150 * - free all memory objects, regardless of sc.
2151 */
2152 bound = curlwp_bind();
2153 sc = audio_sc_acquire_fromfile(file, &sc_ref);
2154 if (sc) {
2155 error = audio_close(sc, file);
2156 audio_sc_release(sc, &sc_ref);
2157 }
2158 curlwp_bindx(bound);
2159
2160 /* Free memory objects anyway */
2161 KASSERT(file->ptrack);
2162 audio_track_destroy(file->ptrack);
2163 KASSERT(file->rtrack == NULL);
2164 kmem_free(file, sizeof(*file));
2165 return error;
2166 }
2167
2168 /* Set sample rate for audiobell */
2169 int
2170 audiobellsetrate(audio_file_t *file, u_int sample_rate)
2171 {
2172 struct audio_softc *sc;
2173 struct psref sc_ref;
2174 struct audio_info ai;
2175 int bound;
2176 int error;
2177
2178 bound = curlwp_bind();
2179 sc = audio_sc_acquire_fromfile(file, &sc_ref);
2180 if (sc == NULL) {
2181 error = EIO;
2182 goto done1;
2183 }
2184
2185 AUDIO_INITINFO(&ai);
2186 ai.play.sample_rate = sample_rate;
2187
2188 error = audio_exlock_enter(sc);
2189 if (error)
2190 goto done2;
2191 error = audio_file_setinfo(sc, file, &ai);
2192 audio_exlock_exit(sc);
2193
2194 done2:
2195 audio_sc_release(sc, &sc_ref);
2196 done1:
2197 curlwp_bindx(bound);
2198 return error;
2199 }
2200
2201 /* Playback for audiobell */
2202 int
2203 audiobellwrite(audio_file_t *file, struct uio *uio)
2204 {
2205 struct audio_softc *sc;
2206 struct psref sc_ref;
2207 int bound;
2208 int error;
2209
2210 bound = curlwp_bind();
2211 sc = audio_sc_acquire_fromfile(file, &sc_ref);
2212 if (sc == NULL) {
2213 error = EIO;
2214 goto done;
2215 }
2216
2217 error = audio_write(sc, uio, 0, file);
2218
2219 audio_sc_release(sc, &sc_ref);
2220 done:
2221 curlwp_bindx(bound);
2222 return error;
2223 }
2224
2225
2226 /*
2227 * Audio driver
2228 */
2229
2230 /*
2231 * Must be called with sc_exlock held and without sc_lock held.
2232 */
2233 int
2234 audio_open(dev_t dev, struct audio_softc *sc, int flags, int ifmt,
2235 struct lwp *l, audio_file_t **bellfile)
2236 {
2237 struct audio_info ai;
2238 struct file *fp;
2239 audio_file_t *af;
2240 audio_ring_t *hwbuf;
2241 bool fullduplex;
2242 bool cred_held;
2243 bool hw_opened;
2244 bool rmixer_started;
2245 bool inserted;
2246 int fd;
2247 int error;
2248
2249 KASSERT(sc->sc_exlock);
2250
2251 TRACE(1, "%sdev=%s flags=0x%x po=%d ro=%d",
2252 (audiodebug >= 3) ? "start " : "",
2253 ISDEVSOUND(dev) ? "sound" : "audio",
2254 flags, sc->sc_popens, sc->sc_ropens);
2255
2256 fp = NULL;
2257 cred_held = false;
2258 hw_opened = false;
2259 rmixer_started = false;
2260 inserted = false;
2261
2262 af = kmem_zalloc(sizeof(*af), KM_SLEEP);
2263 af->sc = sc;
2264 af->dev = dev;
2265 if ((flags & FWRITE) != 0 && audio_can_playback(sc))
2266 af->mode |= AUMODE_PLAY | AUMODE_PLAY_ALL;
2267 if ((flags & FREAD) != 0 && audio_can_capture(sc))
2268 af->mode |= AUMODE_RECORD;
2269 if (af->mode == 0) {
2270 error = ENXIO;
2271 goto bad;
2272 }
2273
2274 fullduplex = (sc->sc_props & AUDIO_PROP_FULLDUPLEX);
2275
2276 /*
2277 * On half duplex hardware,
2278 * 1. if mode is (PLAY | REC), let mode PLAY.
2279 * 2. if mode is PLAY, let mode PLAY if no rec tracks, otherwise error.
2280 * 3. if mode is REC, let mode REC if no play tracks, otherwise error.
2281 */
2282 if (fullduplex == false) {
2283 if ((af->mode & AUMODE_PLAY)) {
2284 if (sc->sc_ropens != 0) {
2285 TRACE(1, "record track already exists");
2286 error = ENODEV;
2287 goto bad;
2288 }
2289 /* Play takes precedence */
2290 af->mode &= ~AUMODE_RECORD;
2291 }
2292 if ((af->mode & AUMODE_RECORD)) {
2293 if (sc->sc_popens != 0) {
2294 TRACE(1, "play track already exists");
2295 error = ENODEV;
2296 goto bad;
2297 }
2298 }
2299 }
2300
2301 /* Create tracks */
2302 if ((af->mode & AUMODE_PLAY))
2303 af->ptrack = audio_track_create(sc, sc->sc_pmixer);
2304 if ((af->mode & AUMODE_RECORD))
2305 af->rtrack = audio_track_create(sc, sc->sc_rmixer);
2306
2307 /* Set parameters */
2308 AUDIO_INITINFO(&ai);
2309 if (bellfile) {
2310 /* If audiobell, only sample_rate will be set later. */
2311 ai.play.sample_rate = audio_default.sample_rate;
2312 ai.play.encoding = AUDIO_ENCODING_SLINEAR_NE;
2313 ai.play.channels = 1;
2314 ai.play.precision = 16;
2315 ai.play.pause = 0;
2316 } else if (ISDEVAUDIO(dev)) {
2317 /* If /dev/audio, initialize everytime. */
2318 ai.play.sample_rate = audio_default.sample_rate;
2319 ai.play.encoding = audio_default.encoding;
2320 ai.play.channels = audio_default.channels;
2321 ai.play.precision = audio_default.precision;
2322 ai.play.pause = 0;
2323 ai.record.sample_rate = audio_default.sample_rate;
2324 ai.record.encoding = audio_default.encoding;
2325 ai.record.channels = audio_default.channels;
2326 ai.record.precision = audio_default.precision;
2327 ai.record.pause = 0;
2328 } else {
2329 /* If /dev/sound, take over the previous parameters. */
2330 ai.play.sample_rate = sc->sc_sound_pparams.sample_rate;
2331 ai.play.encoding = sc->sc_sound_pparams.encoding;
2332 ai.play.channels = sc->sc_sound_pparams.channels;
2333 ai.play.precision = sc->sc_sound_pparams.precision;
2334 ai.play.pause = sc->sc_sound_ppause;
2335 ai.record.sample_rate = sc->sc_sound_rparams.sample_rate;
2336 ai.record.encoding = sc->sc_sound_rparams.encoding;
2337 ai.record.channels = sc->sc_sound_rparams.channels;
2338 ai.record.precision = sc->sc_sound_rparams.precision;
2339 ai.record.pause = sc->sc_sound_rpause;
2340 }
2341 error = audio_file_setinfo(sc, af, &ai);
2342 if (error)
2343 goto bad;
2344
2345 if (sc->sc_popens + sc->sc_ropens == 0) {
2346 /* First open */
2347
2348 sc->sc_cred = kauth_cred_get();
2349 kauth_cred_hold(sc->sc_cred);
2350 cred_held = true;
2351
2352 if (sc->hw_if->open) {
2353 int hwflags;
2354
2355 /*
2356 * Call hw_if->open() only at first open of
2357 * combination of playback and recording.
2358 * On full duplex hardware, the flags passed to
2359 * hw_if->open() is always (FREAD | FWRITE)
2360 * regardless of this open()'s flags.
2361 * see also dev/isa/aria.c
2362 * On half duplex hardware, the flags passed to
2363 * hw_if->open() is either FREAD or FWRITE.
2364 * see also arch/evbarm/mini2440/audio_mini2440.c
2365 */
2366 if (fullduplex) {
2367 hwflags = FREAD | FWRITE;
2368 } else {
2369 /* Construct hwflags from af->mode. */
2370 hwflags = 0;
2371 if ((af->mode & AUMODE_PLAY) != 0)
2372 hwflags |= FWRITE;
2373 if ((af->mode & AUMODE_RECORD) != 0)
2374 hwflags |= FREAD;
2375 }
2376
2377 mutex_enter(sc->sc_lock);
2378 mutex_enter(sc->sc_intr_lock);
2379 error = sc->hw_if->open(sc->hw_hdl, hwflags);
2380 mutex_exit(sc->sc_intr_lock);
2381 mutex_exit(sc->sc_lock);
2382 if (error)
2383 goto bad;
2384 }
2385 /*
2386 * Regardless of whether we called hw_if->open (whether
2387 * hw_if->open exists) or not, we move to the Opened phase
2388 * here. Therefore from this point, we have to call
2389 * hw_if->close (if exists) whenever abort.
2390 * Note that both of hw_if->{open,close} are optional.
2391 */
2392 hw_opened = true;
2393
2394 /*
2395 * Set speaker mode when a half duplex.
2396 * XXX I'm not sure this is correct.
2397 */
2398 if (1/*XXX*/) {
2399 if (sc->hw_if->speaker_ctl) {
2400 int on;
2401 if (af->ptrack) {
2402 on = 1;
2403 } else {
2404 on = 0;
2405 }
2406 mutex_enter(sc->sc_lock);
2407 mutex_enter(sc->sc_intr_lock);
2408 error = sc->hw_if->speaker_ctl(sc->hw_hdl, on);
2409 mutex_exit(sc->sc_intr_lock);
2410 mutex_exit(sc->sc_lock);
2411 if (error)
2412 goto bad;
2413 }
2414 }
2415 } else if (sc->sc_multiuser == false) {
2416 uid_t euid = kauth_cred_geteuid(kauth_cred_get());
2417 if (euid != 0 && euid != kauth_cred_geteuid(sc->sc_cred)) {
2418 error = EPERM;
2419 goto bad;
2420 }
2421 }
2422
2423 /* Call init_output if this is the first playback open. */
2424 if (af->ptrack && sc->sc_popens == 0) {
2425 if (sc->hw_if->init_output) {
2426 hwbuf = &sc->sc_pmixer->hwbuf;
2427 mutex_enter(sc->sc_lock);
2428 mutex_enter(sc->sc_intr_lock);
2429 error = sc->hw_if->init_output(sc->hw_hdl,
2430 hwbuf->mem,
2431 hwbuf->capacity *
2432 hwbuf->fmt.channels * hwbuf->fmt.stride / NBBY);
2433 mutex_exit(sc->sc_intr_lock);
2434 mutex_exit(sc->sc_lock);
2435 if (error)
2436 goto bad;
2437 }
2438 }
2439 /*
2440 * Call init_input and start rmixer, if this is the first recording
2441 * open. See pause consideration notes.
2442 */
2443 if (af->rtrack && sc->sc_ropens == 0) {
2444 if (sc->hw_if->init_input) {
2445 hwbuf = &sc->sc_rmixer->hwbuf;
2446 mutex_enter(sc->sc_lock);
2447 mutex_enter(sc->sc_intr_lock);
2448 error = sc->hw_if->init_input(sc->hw_hdl,
2449 hwbuf->mem,
2450 hwbuf->capacity *
2451 hwbuf->fmt.channels * hwbuf->fmt.stride / NBBY);
2452 mutex_exit(sc->sc_intr_lock);
2453 mutex_exit(sc->sc_lock);
2454 if (error)
2455 goto bad;
2456 }
2457
2458 mutex_enter(sc->sc_lock);
2459 audio_rmixer_start(sc);
2460 mutex_exit(sc->sc_lock);
2461 rmixer_started = true;
2462 }
2463
2464 /*
2465 * This is the last sc_lock section in the function, so we have to
2466 * examine sc_dying again before starting the rest tasks. Because
2467 * audiodeatch() may have been invoked (and it would set sc_dying)
2468 * from the time audioopen() was executed until now. If it happens,
2469 * audiodetach() may already have set file->dying for all sc_files
2470 * that exist at that point, so that audioopen() must abort without
2471 * inserting af to sc_files, in order to keep consistency.
2472 */
2473 mutex_enter(sc->sc_lock);
2474 if (sc->sc_dying) {
2475 mutex_exit(sc->sc_lock);
2476 error = ENXIO;
2477 goto bad;
2478 }
2479
2480 /* Count up finally */
2481 if (af->ptrack)
2482 sc->sc_popens++;
2483 if (af->rtrack)
2484 sc->sc_ropens++;
2485 mutex_enter(sc->sc_intr_lock);
2486 SLIST_INSERT_HEAD(&sc->sc_files, af, entry);
2487 mutex_exit(sc->sc_intr_lock);
2488 mutex_exit(sc->sc_lock);
2489 inserted = true;
2490
2491 if (bellfile) {
2492 *bellfile = af;
2493 } else {
2494 error = fd_allocfile(&fp, &fd);
2495 if (error)
2496 goto bad;
2497
2498 error = fd_clone(fp, fd, flags, &audio_fileops, af);
2499 KASSERTMSG(error == EMOVEFD, "error=%d", error);
2500 }
2501
2502 /* Be nothing else after fd_clone */
2503
2504 TRACEF(3, af, "done");
2505 return error;
2506
2507 bad:
2508 if (inserted) {
2509 mutex_enter(sc->sc_lock);
2510 mutex_enter(sc->sc_intr_lock);
2511 SLIST_REMOVE(&sc->sc_files, af, audio_file, entry);
2512 mutex_exit(sc->sc_intr_lock);
2513 if (af->ptrack)
2514 sc->sc_popens--;
2515 if (af->rtrack)
2516 sc->sc_ropens--;
2517 mutex_exit(sc->sc_lock);
2518 }
2519
2520 if (rmixer_started) {
2521 mutex_enter(sc->sc_lock);
2522 audio_rmixer_halt(sc);
2523 mutex_exit(sc->sc_lock);
2524 }
2525
2526 if (hw_opened) {
2527 if (sc->hw_if->close) {
2528 mutex_enter(sc->sc_lock);
2529 mutex_enter(sc->sc_intr_lock);
2530 sc->hw_if->close(sc->hw_hdl);
2531 mutex_exit(sc->sc_intr_lock);
2532 mutex_exit(sc->sc_lock);
2533 }
2534 }
2535 if (cred_held) {
2536 kauth_cred_free(sc->sc_cred);
2537 }
2538
2539 /*
2540 * Since track here is not yet linked to sc_files,
2541 * you can call track_destroy() without sc_intr_lock.
2542 */
2543 if (af->rtrack) {
2544 audio_track_destroy(af->rtrack);
2545 af->rtrack = NULL;
2546 }
2547 if (af->ptrack) {
2548 audio_track_destroy(af->ptrack);
2549 af->ptrack = NULL;
2550 }
2551
2552 kmem_free(af, sizeof(*af));
2553 return error;
2554 }
2555
2556 /*
2557 * Must be called without sc_lock nor sc_exlock held.
2558 */
2559 int
2560 audio_close(struct audio_softc *sc, audio_file_t *file)
2561 {
2562 int error;
2563
2564 /*
2565 * Drain first.
2566 * It must be done before unlinking(acquiring exlock).
2567 */
2568 if (file->ptrack) {
2569 mutex_enter(sc->sc_lock);
2570 audio_track_drain(sc, file->ptrack);
2571 mutex_exit(sc->sc_lock);
2572 }
2573
2574 mutex_enter(sc->sc_lock);
2575 mutex_enter(sc->sc_intr_lock);
2576 SLIST_REMOVE(&sc->sc_files, file, audio_file, entry);
2577 mutex_exit(sc->sc_intr_lock);
2578 mutex_exit(sc->sc_lock);
2579
2580 error = audio_exlock_enter(sc);
2581 if (error) {
2582 /*
2583 * If EIO, this sc is about to detach. In this case, even if
2584 * we don't do subsequent _unlink(), audiodetach() will do it.
2585 */
2586 if (error == EIO)
2587 return error;
2588
2589 /* XXX This should not happen but what should I do ? */
2590 panic("%s: can't acquire exlock: errno=%d", __func__, error);
2591 }
2592 audio_unlink(sc, file);
2593 audio_exlock_exit(sc);
2594
2595 return 0;
2596 }
2597
2598 /*
2599 * Unlink this file, but not freeing memory here.
2600 * Must be called with sc_exlock held and without sc_lock held.
2601 */
2602 static void
2603 audio_unlink(struct audio_softc *sc, audio_file_t *file)
2604 {
2605 kauth_cred_t cred = NULL;
2606 int error;
2607
2608 mutex_enter(sc->sc_lock);
2609
2610 TRACEF(1, file, "%spid=%d.%d po=%d ro=%d",
2611 (audiodebug >= 3) ? "start " : "",
2612 (int)curproc->p_pid, (int)curlwp->l_lid,
2613 sc->sc_popens, sc->sc_ropens);
2614 KASSERTMSG(sc->sc_popens + sc->sc_ropens > 0,
2615 "sc->sc_popens=%d, sc->sc_ropens=%d",
2616 sc->sc_popens, sc->sc_ropens);
2617
2618 device_active(sc->sc_dev, DVA_SYSTEM);
2619
2620 if (file->ptrack) {
2621 TRACET(3, file->ptrack, "dropframes=%" PRIu64,
2622 file->ptrack->dropframes);
2623
2624 KASSERT(sc->sc_popens > 0);
2625 sc->sc_popens--;
2626
2627 /* Call hw halt_output if this is the last playback track. */
2628 if (sc->sc_popens == 0 && sc->sc_pbusy) {
2629 error = audio_pmixer_halt(sc);
2630 if (error) {
2631 audio_printf(sc,
2632 "halt_output failed: errno=%d (ignored)\n",
2633 error);
2634 }
2635 }
2636
2637 /* Restore mixing volume if all tracks are gone. */
2638 if (sc->sc_popens == 0) {
2639 /* intr_lock is not necessary, but just manners. */
2640 mutex_enter(sc->sc_intr_lock);
2641 sc->sc_pmixer->volume = 256;
2642 sc->sc_pmixer->voltimer = 0;
2643 mutex_exit(sc->sc_intr_lock);
2644 }
2645 }
2646 if (file->rtrack) {
2647 TRACET(3, file->rtrack, "dropframes=%" PRIu64,
2648 file->rtrack->dropframes);
2649
2650 KASSERT(sc->sc_ropens > 0);
2651 sc->sc_ropens--;
2652
2653 /* Call hw halt_input if this is the last recording track. */
2654 if (sc->sc_ropens == 0 && sc->sc_rbusy) {
2655 error = audio_rmixer_halt(sc);
2656 if (error) {
2657 audio_printf(sc,
2658 "halt_input failed: errno=%d (ignored)\n",
2659 error);
2660 }
2661 }
2662
2663 }
2664
2665 /* Call hw close if this is the last track. */
2666 if (sc->sc_popens + sc->sc_ropens == 0) {
2667 if (sc->hw_if->close) {
2668 TRACE(2, "hw_if close");
2669 mutex_enter(sc->sc_intr_lock);
2670 sc->hw_if->close(sc->hw_hdl);
2671 mutex_exit(sc->sc_intr_lock);
2672 }
2673 cred = sc->sc_cred;
2674 sc->sc_cred = NULL;
2675 }
2676
2677 mutex_exit(sc->sc_lock);
2678 if (cred)
2679 kauth_cred_free(cred);
2680
2681 TRACE(3, "done");
2682 }
2683
2684 /*
2685 * Must be called without sc_lock nor sc_exlock held.
2686 */
2687 int
2688 audio_read(struct audio_softc *sc, struct uio *uio, int ioflag,
2689 audio_file_t *file)
2690 {
2691 audio_track_t *track;
2692 audio_ring_t *usrbuf;
2693 audio_ring_t *input;
2694 int error;
2695
2696 /*
2697 * On half-duplex hardware, O_RDWR is treated as O_WRONLY.
2698 * However read() system call itself can be called because it's
2699 * opened with O_RDWR. So in this case, deny this read().
2700 */
2701 track = file->rtrack;
2702 if (track == NULL) {
2703 return EBADF;
2704 }
2705
2706 /* I think it's better than EINVAL. */
2707 if (track->mmapped)
2708 return EPERM;
2709
2710 TRACET(2, track, "resid=%zd ioflag=0x%x", uio->uio_resid, ioflag);
2711
2712 #ifdef AUDIO_PM_IDLE
2713 error = audio_exlock_mutex_enter(sc);
2714 if (error)
2715 return error;
2716
2717 if (device_is_active(&sc->sc_dev) || sc->sc_idle)
2718 device_active(&sc->sc_dev, DVA_SYSTEM);
2719
2720 /* In recording, unlike playback, read() never operates rmixer. */
2721
2722 audio_exlock_mutex_exit(sc);
2723 #endif
2724
2725 usrbuf = &track->usrbuf;
2726 input = track->input;
2727 error = 0;
2728
2729 while (uio->uio_resid > 0 && error == 0) {
2730 int bytes;
2731
2732 TRACET(3, track,
2733 "while resid=%zd input=%d/%d/%d usrbuf=%d/%d/H%d",
2734 uio->uio_resid,
2735 input->head, input->used, input->capacity,
2736 usrbuf->head, usrbuf->used, track->usrbuf_usedhigh);
2737
2738 /* Wait when buffers are empty. */
2739 mutex_enter(sc->sc_lock);
2740 for (;;) {
2741 bool empty;
2742 audio_track_lock_enter(track);
2743 empty = (input->used == 0 && usrbuf->used == 0);
2744 audio_track_lock_exit(track);
2745 if (!empty)
2746 break;
2747
2748 if ((ioflag & IO_NDELAY)) {
2749 mutex_exit(sc->sc_lock);
2750 return EWOULDBLOCK;
2751 }
2752
2753 TRACET(3, track, "sleep");
2754 error = audio_track_waitio(sc, track);
2755 if (error) {
2756 mutex_exit(sc->sc_lock);
2757 return error;
2758 }
2759 }
2760 mutex_exit(sc->sc_lock);
2761
2762 audio_track_lock_enter(track);
2763 /* Convert as many blocks as possible. */
2764 while (usrbuf->used <=
2765 track->usrbuf_usedhigh - track->usrbuf_blksize &&
2766 input->used > 0) {
2767 audio_track_record(track);
2768 }
2769
2770 /* uiomove from usrbuf as much as possible. */
2771 bytes = uimin(usrbuf->used, uio->uio_resid);
2772 while (bytes > 0) {
2773 int head = usrbuf->head;
2774 int len = uimin(bytes, usrbuf->capacity - head);
2775 error = uiomove((uint8_t *)usrbuf->mem + head, len,
2776 uio);
2777 if (error) {
2778 audio_track_lock_exit(track);
2779 device_printf(sc->sc_dev,
2780 "%s: uiomove(%d) failed: errno=%d\n",
2781 __func__, len, error);
2782 goto abort;
2783 }
2784 auring_take(usrbuf, len);
2785 track->useriobytes += len;
2786 TRACET(3, track, "uiomove(len=%d) usrbuf=%d/%d/C%d",
2787 len,
2788 usrbuf->head, usrbuf->used, usrbuf->capacity);
2789 bytes -= len;
2790 }
2791
2792 audio_track_lock_exit(track);
2793 }
2794
2795 abort:
2796 return error;
2797 }
2798
2799
2800 /*
2801 * Clear file's playback and/or record track buffer immediately.
2802 */
2803 static void
2804 audio_file_clear(struct audio_softc *sc, audio_file_t *file)
2805 {
2806
2807 if (file->ptrack)
2808 audio_track_clear(sc, file->ptrack);
2809 if (file->rtrack)
2810 audio_track_clear(sc, file->rtrack);
2811 }
2812
2813 /*
2814 * Must be called without sc_lock nor sc_exlock held.
2815 */
2816 int
2817 audio_write(struct audio_softc *sc, struct uio *uio, int ioflag,
2818 audio_file_t *file)
2819 {
2820 audio_track_t *track;
2821 audio_ring_t *usrbuf;
2822 audio_ring_t *outbuf;
2823 int error;
2824
2825 track = file->ptrack;
2826 if (track == NULL)
2827 return EPERM;
2828
2829 /* I think it's better than EINVAL. */
2830 if (track->mmapped)
2831 return EPERM;
2832
2833 TRACET(2, track, "%sresid=%zd pid=%d.%d ioflag=0x%x",
2834 audiodebug >= 3 ? "begin " : "",
2835 uio->uio_resid, (int)curproc->p_pid, (int)curlwp->l_lid, ioflag);
2836
2837 if (uio->uio_resid == 0) {
2838 track->eofcounter++;
2839 return 0;
2840 }
2841
2842 error = audio_exlock_mutex_enter(sc);
2843 if (error)
2844 return error;
2845
2846 #ifdef AUDIO_PM_IDLE
2847 if (device_is_active(&sc->sc_dev) || sc->sc_idle)
2848 device_active(&sc->sc_dev, DVA_SYSTEM);
2849 #endif
2850
2851 /*
2852 * The first write starts pmixer.
2853 */
2854 if (sc->sc_pbusy == false)
2855 audio_pmixer_start(sc, false);
2856 audio_exlock_mutex_exit(sc);
2857
2858 usrbuf = &track->usrbuf;
2859 outbuf = &track->outbuf;
2860 track->pstate = AUDIO_STATE_RUNNING;
2861 error = 0;
2862
2863 while (uio->uio_resid > 0 && error == 0) {
2864 int bytes;
2865
2866 TRACET(3, track, "while resid=%zd usrbuf=%d/%d/H%d",
2867 uio->uio_resid,
2868 usrbuf->head, usrbuf->used, track->usrbuf_usedhigh);
2869
2870 /* Wait when buffers are full. */
2871 mutex_enter(sc->sc_lock);
2872 for (;;) {
2873 bool full;
2874 audio_track_lock_enter(track);
2875 full = (usrbuf->used >= track->usrbuf_usedhigh &&
2876 outbuf->used >= outbuf->capacity);
2877 audio_track_lock_exit(track);
2878 if (!full)
2879 break;
2880
2881 if ((ioflag & IO_NDELAY)) {
2882 error = EWOULDBLOCK;
2883 mutex_exit(sc->sc_lock);
2884 goto abort;
2885 }
2886
2887 TRACET(3, track, "sleep usrbuf=%d/H%d",
2888 usrbuf->used, track->usrbuf_usedhigh);
2889 error = audio_track_waitio(sc, track);
2890 if (error) {
2891 mutex_exit(sc->sc_lock);
2892 goto abort;
2893 }
2894 }
2895 mutex_exit(sc->sc_lock);
2896
2897 audio_track_lock_enter(track);
2898
2899 /* uiomove to usrbuf as much as possible. */
2900 bytes = uimin(track->usrbuf_usedhigh - usrbuf->used,
2901 uio->uio_resid);
2902 while (bytes > 0) {
2903 int tail = auring_tail(usrbuf);
2904 int len = uimin(bytes, usrbuf->capacity - tail);
2905 error = uiomove((uint8_t *)usrbuf->mem + tail, len,
2906 uio);
2907 if (error) {
2908 audio_track_lock_exit(track);
2909 device_printf(sc->sc_dev,
2910 "%s: uiomove(%d) failed: errno=%d\n",
2911 __func__, len, error);
2912 goto abort;
2913 }
2914 auring_push(usrbuf, len);
2915 track->useriobytes += len;
2916 TRACET(3, track, "uiomove(len=%d) usrbuf=%d/%d/C%d",
2917 len,
2918 usrbuf->head, usrbuf->used, usrbuf->capacity);
2919 bytes -= len;
2920 }
2921
2922 /* Convert them as much as possible. */
2923 while (usrbuf->used >= track->usrbuf_blksize &&
2924 outbuf->used < outbuf->capacity) {
2925 audio_track_play(track);
2926 }
2927
2928 audio_track_lock_exit(track);
2929 }
2930
2931 abort:
2932 TRACET(3, track, "done error=%d", error);
2933 return error;
2934 }
2935
2936 /*
2937 * Must be called without sc_lock nor sc_exlock held.
2938 */
2939 int
2940 audio_ioctl(dev_t dev, struct audio_softc *sc, u_long cmd, void *addr, int flag,
2941 struct lwp *l, audio_file_t *file)
2942 {
2943 struct audio_offset *ao;
2944 struct audio_info ai;
2945 audio_track_t *track;
2946 audio_encoding_t *ae;
2947 audio_format_query_t *query;
2948 u_int stamp;
2949 u_int offs;
2950 int fd;
2951 int index;
2952 int error;
2953
2954 #if defined(AUDIO_DEBUG)
2955 const char *ioctlnames[] = {
2956 " AUDIO_GETINFO", /* 21 */
2957 " AUDIO_SETINFO", /* 22 */
2958 " AUDIO_DRAIN", /* 23 */
2959 " AUDIO_FLUSH", /* 24 */
2960 " AUDIO_WSEEK", /* 25 */
2961 " AUDIO_RERROR", /* 26 */
2962 " AUDIO_GETDEV", /* 27 */
2963 " AUDIO_GETENC", /* 28 */
2964 " AUDIO_GETFD", /* 29 */
2965 " AUDIO_SETFD", /* 30 */
2966 " AUDIO_PERROR", /* 31 */
2967 " AUDIO_GETIOFFS", /* 32 */
2968 " AUDIO_GETOOFFS", /* 33 */
2969 " AUDIO_GETPROPS", /* 34 */
2970 " AUDIO_GETBUFINFO", /* 35 */
2971 " AUDIO_SETCHAN", /* 36 */
2972 " AUDIO_GETCHAN", /* 37 */
2973 " AUDIO_QUERYFORMAT", /* 38 */
2974 " AUDIO_GETFORMAT", /* 39 */
2975 " AUDIO_SETFORMAT", /* 40 */
2976 };
2977 int nameidx = (cmd & 0xff);
2978 const char *ioctlname = "";
2979 if (21 <= nameidx && nameidx <= 21 + __arraycount(ioctlnames))
2980 ioctlname = ioctlnames[nameidx - 21];
2981 TRACEF(2, file, "(%lu,'%c',%lu)%s pid=%d.%d",
2982 IOCPARM_LEN(cmd), (char)IOCGROUP(cmd), cmd&0xff, ioctlname,
2983 (int)curproc->p_pid, (int)l->l_lid);
2984 #endif
2985
2986 error = 0;
2987 switch (cmd) {
2988 case FIONBIO:
2989 /* All handled in the upper FS layer. */
2990 break;
2991
2992 case FIONREAD:
2993 /* Get the number of bytes that can be read. */
2994 if (file->rtrack) {
2995 *(int *)addr = audio_track_readablebytes(file->rtrack);
2996 } else {
2997 *(int *)addr = 0;
2998 }
2999 break;
3000
3001 case FIOASYNC:
3002 /* Set/Clear ASYNC I/O. */
3003 if (*(int *)addr) {
3004 file->async_audio = curproc->p_pid;
3005 TRACEF(2, file, "FIOASYNC pid %d", file->async_audio);
3006 } else {
3007 file->async_audio = 0;
3008 TRACEF(2, file, "FIOASYNC off");
3009 }
3010 break;
3011
3012 case AUDIO_FLUSH:
3013 /* XXX TODO: clear errors and restart? */
3014 audio_file_clear(sc, file);
3015 break;
3016
3017 case AUDIO_RERROR:
3018 /*
3019 * Number of read bytes dropped. We don't know where
3020 * or when they were dropped (including conversion stage).
3021 * Therefore, the number of accurate bytes or samples is
3022 * also unknown.
3023 */
3024 track = file->rtrack;
3025 if (track) {
3026 *(int *)addr = frametobyte(&track->usrbuf.fmt,
3027 track->dropframes);
3028 }
3029 break;
3030
3031 case AUDIO_PERROR:
3032 /*
3033 * Number of write bytes dropped. We don't know where
3034 * or when they were dropped (including conversion stage).
3035 * Therefore, the number of accurate bytes or samples is
3036 * also unknown.
3037 */
3038 track = file->ptrack;
3039 if (track) {
3040 *(int *)addr = frametobyte(&track->usrbuf.fmt,
3041 track->dropframes);
3042 }
3043 break;
3044
3045 case AUDIO_GETIOFFS:
3046 /* XXX TODO */
3047 ao = (struct audio_offset *)addr;
3048 ao->samples = 0;
3049 ao->deltablks = 0;
3050 ao->offset = 0;
3051 break;
3052
3053 case AUDIO_GETOOFFS:
3054 ao = (struct audio_offset *)addr;
3055 track = file->ptrack;
3056 if (track == NULL) {
3057 ao->samples = 0;
3058 ao->deltablks = 0;
3059 ao->offset = 0;
3060 break;
3061 }
3062 mutex_enter(sc->sc_lock);
3063 mutex_enter(sc->sc_intr_lock);
3064 /* figure out where next DMA will start */
3065 stamp = track->usrbuf_stamp;
3066 offs = track->usrbuf.head;
3067 mutex_exit(sc->sc_intr_lock);
3068 mutex_exit(sc->sc_lock);
3069
3070 ao->samples = stamp;
3071 ao->deltablks = (stamp / track->usrbuf_blksize) -
3072 (track->usrbuf_stamp_last / track->usrbuf_blksize);
3073 track->usrbuf_stamp_last = stamp;
3074 offs = rounddown(offs, track->usrbuf_blksize)
3075 + track->usrbuf_blksize;
3076 if (offs >= track->usrbuf.capacity)
3077 offs -= track->usrbuf.capacity;
3078 ao->offset = offs;
3079
3080 TRACET(3, track, "GETOOFFS: samples=%u deltablks=%u offset=%u",
3081 ao->samples, ao->deltablks, ao->offset);
3082 break;
3083
3084 case AUDIO_WSEEK:
3085 /* XXX return value does not include outbuf one. */
3086 if (file->ptrack)
3087 *(u_long *)addr = file->ptrack->usrbuf.used;
3088 break;
3089
3090 case AUDIO_SETINFO:
3091 error = audio_exlock_enter(sc);
3092 if (error)
3093 break;
3094 error = audio_file_setinfo(sc, file, (struct audio_info *)addr);
3095 if (error) {
3096 audio_exlock_exit(sc);
3097 break;
3098 }
3099 /* XXX TODO: update last_ai if /dev/sound ? */
3100 if (ISDEVSOUND(dev))
3101 error = audiogetinfo(sc, &sc->sc_ai, 0, file);
3102 audio_exlock_exit(sc);
3103 break;
3104
3105 case AUDIO_GETINFO:
3106 error = audio_exlock_enter(sc);
3107 if (error)
3108 break;
3109 error = audiogetinfo(sc, (struct audio_info *)addr, 1, file);
3110 audio_exlock_exit(sc);
3111 break;
3112
3113 case AUDIO_GETBUFINFO:
3114 error = audio_exlock_enter(sc);
3115 if (error)
3116 break;
3117 error = audiogetinfo(sc, (struct audio_info *)addr, 0, file);
3118 audio_exlock_exit(sc);
3119 break;
3120
3121 case AUDIO_DRAIN:
3122 if (file->ptrack) {
3123 mutex_enter(sc->sc_lock);
3124 error = audio_track_drain(sc, file->ptrack);
3125 mutex_exit(sc->sc_lock);
3126 }
3127 break;
3128
3129 case AUDIO_GETDEV:
3130 error = sc->hw_if->getdev(sc->hw_hdl, (audio_device_t *)addr);
3131 break;
3132
3133 case AUDIO_GETENC:
3134 ae = (audio_encoding_t *)addr;
3135 index = ae->index;
3136 if (index < 0 || index >= __arraycount(audio_encodings)) {
3137 error = EINVAL;
3138 break;
3139 }
3140 *ae = audio_encodings[index];
3141 ae->index = index;
3142 /*
3143 * EMULATED always.
3144 * EMULATED flag at that time used to mean that it could
3145 * not be passed directly to the hardware as-is. But
3146 * currently, all formats including hardware native is not
3147 * passed directly to the hardware. So I set EMULATED
3148 * flag for all formats.
3149 */
3150 ae->flags = AUDIO_ENCODINGFLAG_EMULATED;
3151 break;
3152
3153 case AUDIO_GETFD:
3154 /*
3155 * Returns the current setting of full duplex mode.
3156 * If HW has full duplex mode and there are two mixers,
3157 * it is full duplex. Otherwise half duplex.
3158 */
3159 error = audio_exlock_enter(sc);
3160 if (error)
3161 break;
3162 fd = (sc->sc_props & AUDIO_PROP_FULLDUPLEX)
3163 && (sc->sc_pmixer && sc->sc_rmixer);
3164 audio_exlock_exit(sc);
3165 *(int *)addr = fd;
3166 break;
3167
3168 case AUDIO_GETPROPS:
3169 *(int *)addr = sc->sc_props;
3170 break;
3171
3172 case AUDIO_QUERYFORMAT:
3173 query = (audio_format_query_t *)addr;
3174 mutex_enter(sc->sc_lock);
3175 error = sc->hw_if->query_format(sc->hw_hdl, query);
3176 mutex_exit(sc->sc_lock);
3177 /* Hide internal information */
3178 query->fmt.driver_data = NULL;
3179 break;
3180
3181 case AUDIO_GETFORMAT:
3182 error = audio_exlock_enter(sc);
3183 if (error)
3184 break;
3185 audio_mixers_get_format(sc, (struct audio_info *)addr);
3186 audio_exlock_exit(sc);
3187 break;
3188
3189 case AUDIO_SETFORMAT:
3190 error = audio_exlock_enter(sc);
3191 audio_mixers_get_format(sc, &ai);
3192 error = audio_mixers_set_format(sc, (struct audio_info *)addr);
3193 if (error) {
3194 /* Rollback */
3195 audio_mixers_set_format(sc, &ai);
3196 }
3197 audio_exlock_exit(sc);
3198 break;
3199
3200 case AUDIO_SETFD:
3201 case AUDIO_SETCHAN:
3202 case AUDIO_GETCHAN:
3203 /* Obsoleted */
3204 break;
3205
3206 default:
3207 if (sc->hw_if->dev_ioctl) {
3208 mutex_enter(sc->sc_lock);
3209 error = sc->hw_if->dev_ioctl(sc->hw_hdl,
3210 cmd, addr, flag, l);
3211 mutex_exit(sc->sc_lock);
3212 } else {
3213 TRACEF(2, file, "unknown ioctl");
3214 error = EINVAL;
3215 }
3216 break;
3217 }
3218 TRACEF(2, file, "(%lu,'%c',%lu)%s result %d",
3219 IOCPARM_LEN(cmd), (char)IOCGROUP(cmd), cmd&0xff, ioctlname,
3220 error);
3221 return error;
3222 }
3223
3224 /*
3225 * Returns the number of bytes that can be read on recording buffer.
3226 */
3227 static __inline int
3228 audio_track_readablebytes(const audio_track_t *track)
3229 {
3230 int bytes;
3231
3232 KASSERT(track);
3233 KASSERT(track->mode == AUMODE_RECORD);
3234
3235 /*
3236 * Although usrbuf is primarily readable data, recorded data
3237 * also stays in track->input until reading. So it is necessary
3238 * to add it. track->input is in frame, usrbuf is in byte.
3239 */
3240 bytes = track->usrbuf.used +
3241 track->input->used * frametobyte(&track->usrbuf.fmt, 1);
3242 return bytes;
3243 }
3244
3245 /*
3246 * Must be called without sc_lock nor sc_exlock held.
3247 */
3248 int
3249 audio_poll(struct audio_softc *sc, int events, struct lwp *l,
3250 audio_file_t *file)
3251 {
3252 audio_track_t *track;
3253 int revents;
3254 bool in_is_valid;
3255 bool out_is_valid;
3256
3257 #if defined(AUDIO_DEBUG)
3258 #define POLLEV_BITMAP "\177\020" \
3259 "b\10WRBAND\0" \
3260 "b\7RDBAND\0" "b\6RDNORM\0" "b\5NVAL\0" "b\4HUP\0" \
3261 "b\3ERR\0" "b\2OUT\0" "b\1PRI\0" "b\0IN\0"
3262 char evbuf[64];
3263 snprintb(evbuf, sizeof(evbuf), POLLEV_BITMAP, events);
3264 TRACEF(2, file, "pid=%d.%d events=%s",
3265 (int)curproc->p_pid, (int)l->l_lid, evbuf);
3266 #endif
3267
3268 revents = 0;
3269 in_is_valid = false;
3270 out_is_valid = false;
3271 if (events & (POLLIN | POLLRDNORM)) {
3272 track = file->rtrack;
3273 if (track) {
3274 int used;
3275 in_is_valid = true;
3276 used = audio_track_readablebytes(track);
3277 if (used > 0)
3278 revents |= events & (POLLIN | POLLRDNORM);
3279 }
3280 }
3281 if (events & (POLLOUT | POLLWRNORM)) {
3282 track = file->ptrack;
3283 if (track) {
3284 out_is_valid = true;
3285 if (track->usrbuf.used <= track->usrbuf_usedlow)
3286 revents |= events & (POLLOUT | POLLWRNORM);
3287 }
3288 }
3289
3290 if (revents == 0) {
3291 mutex_enter(sc->sc_lock);
3292 if (in_is_valid) {
3293 TRACEF(3, file, "selrecord rsel");
3294 selrecord(l, &sc->sc_rsel);
3295 }
3296 if (out_is_valid) {
3297 TRACEF(3, file, "selrecord wsel");
3298 selrecord(l, &sc->sc_wsel);
3299 }
3300 mutex_exit(sc->sc_lock);
3301 }
3302
3303 #if defined(AUDIO_DEBUG)
3304 snprintb(evbuf, sizeof(evbuf), POLLEV_BITMAP, revents);
3305 TRACEF(2, file, "revents=%s", evbuf);
3306 #endif
3307 return revents;
3308 }
3309
3310 static const struct filterops audioread_filtops = {
3311 .f_flags = FILTEROP_ISFD,
3312 .f_attach = NULL,
3313 .f_detach = filt_audioread_detach,
3314 .f_event = filt_audioread_event,
3315 };
3316
3317 static void
3318 filt_audioread_detach(struct knote *kn)
3319 {
3320 struct audio_softc *sc;
3321 audio_file_t *file;
3322
3323 file = kn->kn_hook;
3324 sc = file->sc;
3325 TRACEF(3, file, "called");
3326
3327 mutex_enter(sc->sc_lock);
3328 selremove_knote(&sc->sc_rsel, kn);
3329 mutex_exit(sc->sc_lock);
3330 }
3331
3332 static int
3333 filt_audioread_event(struct knote *kn, long hint)
3334 {
3335 audio_file_t *file;
3336 audio_track_t *track;
3337
3338 file = kn->kn_hook;
3339 track = file->rtrack;
3340
3341 /*
3342 * kn_data must contain the number of bytes can be read.
3343 * The return value indicates whether the event occurs or not.
3344 */
3345
3346 if (track == NULL) {
3347 /* can not read with this descriptor. */
3348 kn->kn_data = 0;
3349 return 0;
3350 }
3351
3352 kn->kn_data = audio_track_readablebytes(track);
3353 TRACEF(3, file, "data=%" PRId64, kn->kn_data);
3354 return kn->kn_data > 0;
3355 }
3356
3357 static const struct filterops audiowrite_filtops = {
3358 .f_flags = FILTEROP_ISFD,
3359 .f_attach = NULL,
3360 .f_detach = filt_audiowrite_detach,
3361 .f_event = filt_audiowrite_event,
3362 };
3363
3364 static void
3365 filt_audiowrite_detach(struct knote *kn)
3366 {
3367 struct audio_softc *sc;
3368 audio_file_t *file;
3369
3370 file = kn->kn_hook;
3371 sc = file->sc;
3372 TRACEF(3, file, "called");
3373
3374 mutex_enter(sc->sc_lock);
3375 selremove_knote(&sc->sc_wsel, kn);
3376 mutex_exit(sc->sc_lock);
3377 }
3378
3379 static int
3380 filt_audiowrite_event(struct knote *kn, long hint)
3381 {
3382 audio_file_t *file;
3383 audio_track_t *track;
3384
3385 file = kn->kn_hook;
3386 track = file->ptrack;
3387
3388 /*
3389 * kn_data must contain the number of bytes can be write.
3390 * The return value indicates whether the event occurs or not.
3391 */
3392
3393 if (track == NULL) {
3394 /* can not write with this descriptor. */
3395 kn->kn_data = 0;
3396 return 0;
3397 }
3398
3399 kn->kn_data = track->usrbuf_usedhigh - track->usrbuf.used;
3400 TRACEF(3, file, "data=%" PRId64, kn->kn_data);
3401 return (track->usrbuf.used < track->usrbuf_usedlow);
3402 }
3403
3404 /*
3405 * Must be called without sc_lock nor sc_exlock held.
3406 */
3407 int
3408 audio_kqfilter(struct audio_softc *sc, audio_file_t *file, struct knote *kn)
3409 {
3410 struct selinfo *sip;
3411
3412 TRACEF(3, file, "kn=%p kn_filter=%x", kn, (int)kn->kn_filter);
3413
3414 switch (kn->kn_filter) {
3415 case EVFILT_READ:
3416 sip = &sc->sc_rsel;
3417 kn->kn_fop = &audioread_filtops;
3418 break;
3419
3420 case EVFILT_WRITE:
3421 sip = &sc->sc_wsel;
3422 kn->kn_fop = &audiowrite_filtops;
3423 break;
3424
3425 default:
3426 return EINVAL;
3427 }
3428
3429 kn->kn_hook = file;
3430
3431 mutex_enter(sc->sc_lock);
3432 selrecord_knote(sip, kn);
3433 mutex_exit(sc->sc_lock);
3434
3435 return 0;
3436 }
3437
3438 /*
3439 * Must be called without sc_lock nor sc_exlock held.
3440 */
3441 int
3442 audio_mmap(struct audio_softc *sc, off_t *offp, size_t len, int prot,
3443 int *flagsp, int *advicep, struct uvm_object **uobjp, int *maxprotp,
3444 audio_file_t *file)
3445 {
3446 audio_track_t *track;
3447 vsize_t vsize;
3448 int error;
3449
3450 TRACEF(2, file, "off=%lld, prot=%d", (long long)(*offp), prot);
3451
3452 if (*offp < 0)
3453 return EINVAL;
3454
3455 #if 0
3456 /* XXX
3457 * The idea here was to use the protection to determine if
3458 * we are mapping the read or write buffer, but it fails.
3459 * The VM system is broken in (at least) two ways.
3460 * 1) If you map memory VM_PROT_WRITE you SIGSEGV
3461 * when writing to it, so VM_PROT_READ|VM_PROT_WRITE
3462 * has to be used for mmapping the play buffer.
3463 * 2) Even if calling mmap() with VM_PROT_READ|VM_PROT_WRITE
3464 * audio_mmap will get called at some point with VM_PROT_READ
3465 * only.
3466 * So, alas, we always map the play buffer for now.
3467 */
3468 if (prot == (VM_PROT_READ|VM_PROT_WRITE) ||
3469 prot == VM_PROT_WRITE)
3470 track = file->ptrack;
3471 else if (prot == VM_PROT_READ)
3472 track = file->rtrack;
3473 else
3474 return EINVAL;
3475 #else
3476 track = file->ptrack;
3477 #endif
3478 if (track == NULL)
3479 return EACCES;
3480
3481 vsize = roundup2(MAX(track->usrbuf.capacity, PAGE_SIZE), PAGE_SIZE);
3482 if (len > vsize)
3483 return EOVERFLOW;
3484 if (*offp > (uint)(vsize - len))
3485 return EOVERFLOW;
3486
3487 /* XXX TODO: what happens when mmap twice. */
3488 if (!track->mmapped) {
3489 track->mmapped = true;
3490
3491 if (!track->is_pause) {
3492 error = audio_exlock_mutex_enter(sc);
3493 if (error)
3494 return error;
3495 if (sc->sc_pbusy == false)
3496 audio_pmixer_start(sc, true);
3497 audio_exlock_mutex_exit(sc);
3498 }
3499 /* XXX mmapping record buffer is not supported */
3500 }
3501
3502 /* get ringbuffer */
3503 *uobjp = track->uobj;
3504
3505 /* Acquire a reference for the mmap. munmap will release. */
3506 uao_reference(*uobjp);
3507 *maxprotp = prot;
3508 *advicep = UVM_ADV_RANDOM;
3509 *flagsp = MAP_SHARED;
3510 return 0;
3511 }
3512
3513 /*
3514 * /dev/audioctl has to be able to open at any time without interference
3515 * with any /dev/audio or /dev/sound.
3516 * Must be called with sc_exlock held and without sc_lock held.
3517 */
3518 static int
3519 audioctl_open(dev_t dev, struct audio_softc *sc, int flags, int ifmt,
3520 struct lwp *l)
3521 {
3522 struct file *fp;
3523 audio_file_t *af;
3524 int fd;
3525 int error;
3526
3527 KASSERT(sc->sc_exlock);
3528
3529 TRACE(1, "called");
3530
3531 error = fd_allocfile(&fp, &fd);
3532 if (error)
3533 return error;
3534
3535 af = kmem_zalloc(sizeof(*af), KM_SLEEP);
3536 af->sc = sc;
3537 af->dev = dev;
3538
3539 mutex_enter(sc->sc_lock);
3540 if (sc->sc_dying) {
3541 mutex_exit(sc->sc_lock);
3542 kmem_free(af, sizeof(*af));
3543 fd_abort(curproc, fp, fd);
3544 return ENXIO;
3545 }
3546 mutex_enter(sc->sc_intr_lock);
3547 SLIST_INSERT_HEAD(&sc->sc_files, af, entry);
3548 mutex_exit(sc->sc_intr_lock);
3549 mutex_exit(sc->sc_lock);
3550
3551 error = fd_clone(fp, fd, flags, &audio_fileops, af);
3552 KASSERTMSG(error == EMOVEFD, "error=%d", error);
3553
3554 return error;
3555 }
3556
3557 /*
3558 * Free 'mem' if available, and initialize the pointer.
3559 * For this reason, this is implemented as macro.
3560 */
3561 #define audio_free(mem) do { \
3562 if (mem != NULL) { \
3563 kern_free(mem); \
3564 mem = NULL; \
3565 } \
3566 } while (0)
3567
3568 /*
3569 * (Re)allocate 'memblock' with specified 'bytes'.
3570 * bytes must not be 0.
3571 * This function never returns NULL.
3572 */
3573 static void *
3574 audio_realloc(void *memblock, size_t bytes)
3575 {
3576
3577 KASSERT(bytes != 0);
3578 audio_free(memblock);
3579 return kern_malloc(bytes, M_WAITOK);
3580 }
3581
3582 /*
3583 * (Re)allocate usrbuf with 'newbufsize' bytes.
3584 * Use this function for usrbuf because only usrbuf can be mmapped.
3585 * If successful, it updates track->usrbuf.mem, track->usrbuf.capacity and
3586 * returns 0. Otherwise, it clears track->usrbuf.mem, track->usrbuf.capacity
3587 * and returns errno.
3588 * It must be called before updating usrbuf.capacity.
3589 */
3590 static int
3591 audio_realloc_usrbuf(audio_track_t *track, int newbufsize)
3592 {
3593 struct audio_softc *sc;
3594 vaddr_t vstart;
3595 vsize_t oldvsize;
3596 vsize_t newvsize;
3597 int error;
3598
3599 KASSERT(newbufsize > 0);
3600 sc = track->mixer->sc;
3601
3602 /* Get a nonzero multiple of PAGE_SIZE */
3603 newvsize = roundup2(MAX(newbufsize, PAGE_SIZE), PAGE_SIZE);
3604
3605 if (track->usrbuf.mem != NULL) {
3606 oldvsize = roundup2(MAX(track->usrbuf.capacity, PAGE_SIZE),
3607 PAGE_SIZE);
3608 if (oldvsize == newvsize) {
3609 track->usrbuf.capacity = newbufsize;
3610 return 0;
3611 }
3612 vstart = (vaddr_t)track->usrbuf.mem;
3613 uvm_unmap(kernel_map, vstart, vstart + oldvsize);
3614 /* uvm_unmap also detach uobj */
3615 track->uobj = NULL; /* paranoia */
3616 track->usrbuf.mem = NULL;
3617 }
3618
3619 /* Create a uvm anonymous object */
3620 track->uobj = uao_create(newvsize, 0);
3621
3622 /* Map it into the kernel virtual address space */
3623 vstart = 0;
3624 error = uvm_map(kernel_map, &vstart, newvsize, track->uobj, 0, 0,
3625 UVM_MAPFLAG(UVM_PROT_RW, UVM_PROT_RW, UVM_INH_NONE,
3626 UVM_ADV_RANDOM, 0));
3627 if (error) {
3628 device_printf(sc->sc_dev, "uvm_map failed: errno=%d\n", error);
3629 uao_detach(track->uobj); /* release reference */
3630 goto abort;
3631 }
3632
3633 error = uvm_map_pageable(kernel_map, vstart, vstart + newvsize,
3634 false, 0);
3635 if (error) {
3636 device_printf(sc->sc_dev, "uvm_map_pageable failed: errno=%d\n",
3637 error);
3638 uvm_unmap(kernel_map, vstart, vstart + newvsize);
3639 /* uvm_unmap also detach uobj */
3640 goto abort;
3641 }
3642
3643 track->usrbuf.mem = (void *)vstart;
3644 track->usrbuf.capacity = newbufsize;
3645 memset(track->usrbuf.mem, 0, newvsize);
3646 return 0;
3647
3648 /* failure */
3649 abort:
3650 track->uobj = NULL; /* paranoia */
3651 track->usrbuf.mem = NULL;
3652 track->usrbuf.capacity = 0;
3653 return error;
3654 }
3655
3656 /*
3657 * Free usrbuf (if available).
3658 */
3659 static void
3660 audio_free_usrbuf(audio_track_t *track)
3661 {
3662 vaddr_t vstart;
3663 vsize_t vsize;
3664
3665 vstart = (vaddr_t)track->usrbuf.mem;
3666 vsize = roundup2(MAX(track->usrbuf.capacity, PAGE_SIZE), PAGE_SIZE);
3667 if (track->usrbuf.mem != NULL) {
3668 /*
3669 * Unmap the kernel mapping. uvm_unmap releases the
3670 * reference to the uvm object, and this should be the
3671 * last virtual mapping of the uvm object, so no need
3672 * to explicitly release (`detach') the object.
3673 */
3674 uvm_unmap(kernel_map, vstart, vstart + vsize);
3675
3676 track->uobj = NULL;
3677 track->usrbuf.mem = NULL;
3678 track->usrbuf.capacity = 0;
3679 }
3680 }
3681
3682 /*
3683 * This filter changes the volume for each channel.
3684 * arg->context points track->ch_volume[].
3685 */
3686 static void
3687 audio_track_chvol(audio_filter_arg_t *arg)
3688 {
3689 int16_t *ch_volume;
3690 const aint_t *s;
3691 aint_t *d;
3692 u_int i;
3693 u_int ch;
3694 u_int channels;
3695
3696 DIAGNOSTIC_filter_arg(arg);
3697 KASSERTMSG(arg->srcfmt->channels == arg->dstfmt->channels,
3698 "arg->srcfmt->channels=%d, arg->dstfmt->channels=%d",
3699 arg->srcfmt->channels, arg->dstfmt->channels);
3700 KASSERT(arg->context != NULL);
3701 KASSERTMSG(arg->srcfmt->channels <= AUDIO_MAX_CHANNELS,
3702 "arg->srcfmt->channels=%d", arg->srcfmt->channels);
3703
3704 s = arg->src;
3705 d = arg->dst;
3706 ch_volume = arg->context;
3707
3708 channels = arg->srcfmt->channels;
3709 for (i = 0; i < arg->count; i++) {
3710 for (ch = 0; ch < channels; ch++) {
3711 aint2_t val;
3712 val = *s++;
3713 val = AUDIO_SCALEDOWN(val * ch_volume[ch], 8);
3714 *d++ = (aint_t)val;
3715 }
3716 }
3717 }
3718
3719 /*
3720 * This filter performs conversion from stereo (or more channels) to mono.
3721 */
3722 static void
3723 audio_track_chmix_mixLR(audio_filter_arg_t *arg)
3724 {
3725 const aint_t *s;
3726 aint_t *d;
3727 u_int i;
3728
3729 DIAGNOSTIC_filter_arg(arg);
3730
3731 s = arg->src;
3732 d = arg->dst;
3733
3734 for (i = 0; i < arg->count; i++) {
3735 *d++ = AUDIO_SCALEDOWN(s[0], 1) + AUDIO_SCALEDOWN(s[1], 1);
3736 s += arg->srcfmt->channels;
3737 }
3738 }
3739
3740 /*
3741 * This filter performs conversion from mono to stereo (or more channels).
3742 */
3743 static void
3744 audio_track_chmix_dupLR(audio_filter_arg_t *arg)
3745 {
3746 const aint_t *s;
3747 aint_t *d;
3748 u_int i;
3749 u_int ch;
3750 u_int dstchannels;
3751
3752 DIAGNOSTIC_filter_arg(arg);
3753
3754 s = arg->src;
3755 d = arg->dst;
3756 dstchannels = arg->dstfmt->channels;
3757
3758 for (i = 0; i < arg->count; i++) {
3759 d[0] = s[0];
3760 d[1] = s[0];
3761 s++;
3762 d += dstchannels;
3763 }
3764 if (dstchannels > 2) {
3765 d = arg->dst;
3766 for (i = 0; i < arg->count; i++) {
3767 for (ch = 2; ch < dstchannels; ch++) {
3768 d[ch] = 0;
3769 }
3770 d += dstchannels;
3771 }
3772 }
3773 }
3774
3775 /*
3776 * This filter shrinks M channels into N channels.
3777 * Extra channels are discarded.
3778 */
3779 static void
3780 audio_track_chmix_shrink(audio_filter_arg_t *arg)
3781 {
3782 const aint_t *s;
3783 aint_t *d;
3784 u_int i;
3785 u_int ch;
3786
3787 DIAGNOSTIC_filter_arg(arg);
3788
3789 s = arg->src;
3790 d = arg->dst;
3791
3792 for (i = 0; i < arg->count; i++) {
3793 for (ch = 0; ch < arg->dstfmt->channels; ch++) {
3794 *d++ = s[ch];
3795 }
3796 s += arg->srcfmt->channels;
3797 }
3798 }
3799
3800 /*
3801 * This filter expands M channels into N channels.
3802 * Silence is inserted for missing channels.
3803 */
3804 static void
3805 audio_track_chmix_expand(audio_filter_arg_t *arg)
3806 {
3807 const aint_t *s;
3808 aint_t *d;
3809 u_int i;
3810 u_int ch;
3811 u_int srcchannels;
3812 u_int dstchannels;
3813
3814 DIAGNOSTIC_filter_arg(arg);
3815
3816 s = arg->src;
3817 d = arg->dst;
3818
3819 srcchannels = arg->srcfmt->channels;
3820 dstchannels = arg->dstfmt->channels;
3821 for (i = 0; i < arg->count; i++) {
3822 for (ch = 0; ch < srcchannels; ch++) {
3823 *d++ = *s++;
3824 }
3825 for (; ch < dstchannels; ch++) {
3826 *d++ = 0;
3827 }
3828 }
3829 }
3830
3831 /*
3832 * This filter performs frequency conversion (up sampling).
3833 * It uses linear interpolation.
3834 */
3835 static void
3836 audio_track_freq_up(audio_filter_arg_t *arg)
3837 {
3838 audio_track_t *track;
3839 audio_ring_t *src;
3840 audio_ring_t *dst;
3841 const aint_t *s;
3842 aint_t *d;
3843 aint_t prev[AUDIO_MAX_CHANNELS];
3844 aint_t curr[AUDIO_MAX_CHANNELS];
3845 aint_t grad[AUDIO_MAX_CHANNELS];
3846 u_int i;
3847 u_int t;
3848 u_int step;
3849 u_int channels;
3850 u_int ch;
3851 int srcused;
3852
3853 track = arg->context;
3854 KASSERT(track);
3855 src = &track->freq.srcbuf;
3856 dst = track->freq.dst;
3857 DIAGNOSTIC_ring(dst);
3858 DIAGNOSTIC_ring(src);
3859 KASSERT(src->used > 0);
3860 KASSERTMSG(src->fmt.channels == dst->fmt.channels,
3861 "src->fmt.channels=%d dst->fmt.channels=%d",
3862 src->fmt.channels, dst->fmt.channels);
3863 KASSERTMSG(src->head % track->mixer->frames_per_block == 0,
3864 "src->head=%d track->mixer->frames_per_block=%d",
3865 src->head, track->mixer->frames_per_block);
3866
3867 s = arg->src;
3868 d = arg->dst;
3869
3870 /*
3871 * In order to facilitate interpolation for each block, slide (delay)
3872 * input by one sample. As a result, strictly speaking, the output
3873 * phase is delayed by 1/dstfreq. However, I believe there is no
3874 * observable impact.
3875 *
3876 * Example)
3877 * srcfreq:dstfreq = 1:3
3878 *
3879 * A - -
3880 * |
3881 * |
3882 * | B - -
3883 * +-----+-----> input timeframe
3884 * 0 1
3885 *
3886 * 0 1
3887 * +-----+-----> input timeframe
3888 * | A
3889 * | x x
3890 * | x x
3891 * x (B)
3892 * +-+-+-+-+-+-> output timeframe
3893 * 0 1 2 3 4 5
3894 */
3895
3896 /* Last samples in previous block */
3897 channels = src->fmt.channels;
3898 for (ch = 0; ch < channels; ch++) {
3899 prev[ch] = track->freq_prev[ch];
3900 curr[ch] = track->freq_curr[ch];
3901 grad[ch] = curr[ch] - prev[ch];
3902 }
3903
3904 step = track->freq_step;
3905 t = track->freq_current;
3906 //#define FREQ_DEBUG
3907 #if defined(FREQ_DEBUG)
3908 #define PRINTF(fmt...) printf(fmt)
3909 #else
3910 #define PRINTF(fmt...) do { } while (0)
3911 #endif
3912 srcused = src->used;
3913 PRINTF("upstart step=%d leap=%d", step, track->freq_leap);
3914 PRINTF(" srcused=%d arg->count=%u", src->used, arg->count);
3915 PRINTF(" prev=%d curr=%d grad=%d", prev[0], curr[0], grad[0]);
3916 PRINTF(" t=%d\n", t);
3917
3918 for (i = 0; i < arg->count; i++) {
3919 PRINTF("i=%d t=%5d", i, t);
3920 if (t >= 65536) {
3921 for (ch = 0; ch < channels; ch++) {
3922 prev[ch] = curr[ch];
3923 curr[ch] = *s++;
3924 grad[ch] = curr[ch] - prev[ch];
3925 }
3926 PRINTF(" prev=%d s[%d]=%d",
3927 prev[0], src->used - srcused, curr[0]);
3928
3929 /* Update */
3930 t -= 65536;
3931 srcused--;
3932 if (srcused < 0) {
3933 PRINTF(" break\n");
3934 break;
3935 }
3936 }
3937
3938 for (ch = 0; ch < channels; ch++) {
3939 *d++ = prev[ch] + (aint2_t)grad[ch] * t / 65536;
3940 #if defined(FREQ_DEBUG)
3941 if (ch == 0)
3942 printf(" t=%5d *d=%d", t, d[-1]);
3943 #endif
3944 }
3945 t += step;
3946
3947 PRINTF("\n");
3948 }
3949 PRINTF("end prev=%d curr=%d\n", prev[0], curr[0]);
3950
3951 auring_take(src, src->used);
3952 auring_push(dst, i);
3953
3954 /* Adjust */
3955 t += track->freq_leap;
3956
3957 track->freq_current = t;
3958 for (ch = 0; ch < channels; ch++) {
3959 track->freq_prev[ch] = prev[ch];
3960 track->freq_curr[ch] = curr[ch];
3961 }
3962 }
3963
3964 /*
3965 * This filter performs frequency conversion (down sampling).
3966 * It uses simple thinning.
3967 */
3968 static void
3969 audio_track_freq_down(audio_filter_arg_t *arg)
3970 {
3971 audio_track_t *track;
3972 audio_ring_t *src;
3973 audio_ring_t *dst;
3974 const aint_t *s0;
3975 aint_t *d;
3976 u_int i;
3977 u_int t;
3978 u_int step;
3979 u_int ch;
3980 u_int channels;
3981
3982 track = arg->context;
3983 KASSERT(track);
3984 src = &track->freq.srcbuf;
3985 dst = track->freq.dst;
3986
3987 DIAGNOSTIC_ring(dst);
3988 DIAGNOSTIC_ring(src);
3989 KASSERT(src->used > 0);
3990 KASSERTMSG(src->fmt.channels == dst->fmt.channels,
3991 "src->fmt.channels=%d dst->fmt.channels=%d",
3992 src->fmt.channels, dst->fmt.channels);
3993 KASSERTMSG(src->head % track->mixer->frames_per_block == 0,
3994 "src->head=%d track->mixer->frames_per_block=%d",
3995 src->head, track->mixer->frames_per_block);
3996
3997 s0 = arg->src;
3998 d = arg->dst;
3999 t = track->freq_current;
4000 step = track->freq_step;
4001 channels = dst->fmt.channels;
4002 PRINTF("downstart step=%d leap=%d", step, track->freq_leap);
4003 PRINTF(" srcused=%d arg->count=%u", src->used, arg->count);
4004 PRINTF(" t=%d\n", t);
4005
4006 for (i = 0; i < arg->count && t / 65536 < src->used; i++) {
4007 const aint_t *s;
4008 PRINTF("i=%4d t=%10d", i, t);
4009 s = s0 + (t / 65536) * channels;
4010 PRINTF(" s=%5ld", (s - s0) / channels);
4011 for (ch = 0; ch < channels; ch++) {
4012 if (ch == 0) PRINTF(" *s=%d", s[ch]);
4013 *d++ = s[ch];
4014 }
4015 PRINTF("\n");
4016 t += step;
4017 }
4018 t += track->freq_leap;
4019 PRINTF("end t=%d\n", t);
4020 auring_take(src, src->used);
4021 auring_push(dst, i);
4022 track->freq_current = t % 65536;
4023 }
4024
4025 /*
4026 * Creates track and returns it.
4027 * Must be called without sc_lock held.
4028 */
4029 audio_track_t *
4030 audio_track_create(struct audio_softc *sc, audio_trackmixer_t *mixer)
4031 {
4032 audio_track_t *track;
4033 static int newid = 0;
4034
4035 track = kmem_zalloc(sizeof(*track), KM_SLEEP);
4036
4037 track->id = newid++;
4038 track->mixer = mixer;
4039 track->mode = mixer->mode;
4040
4041 /* Do TRACE after id is assigned. */
4042 TRACET(3, track, "for %s",
4043 mixer->mode == AUMODE_PLAY ? "playback" : "recording");
4044
4045 #if defined(AUDIO_SUPPORT_TRACK_VOLUME)
4046 track->volume = 256;
4047 #endif
4048 for (int i = 0; i < AUDIO_MAX_CHANNELS; i++) {
4049 track->ch_volume[i] = 256;
4050 }
4051
4052 return track;
4053 }
4054
4055 /*
4056 * Release all resources of the track and track itself.
4057 * track must not be NULL. Don't specify the track within the file
4058 * structure linked from sc->sc_files.
4059 */
4060 static void
4061 audio_track_destroy(audio_track_t *track)
4062 {
4063
4064 KASSERT(track);
4065
4066 audio_free_usrbuf(track);
4067 audio_free(track->codec.srcbuf.mem);
4068 audio_free(track->chvol.srcbuf.mem);
4069 audio_free(track->chmix.srcbuf.mem);
4070 audio_free(track->freq.srcbuf.mem);
4071 audio_free(track->outbuf.mem);
4072
4073 kmem_free(track, sizeof(*track));
4074 }
4075
4076 /*
4077 * It returns encoding conversion filter according to src and dst format.
4078 * If it is not a convertible pair, it returns NULL. Either src or dst
4079 * must be internal format.
4080 */
4081 static audio_filter_t
4082 audio_track_get_codec(audio_track_t *track, const audio_format2_t *src,
4083 const audio_format2_t *dst)
4084 {
4085
4086 if (audio_format2_is_internal(src)) {
4087 if (dst->encoding == AUDIO_ENCODING_ULAW) {
4088 return audio_internal_to_mulaw;
4089 } else if (dst->encoding == AUDIO_ENCODING_ALAW) {
4090 return audio_internal_to_alaw;
4091 } else if (audio_format2_is_linear(dst)) {
4092 switch (dst->stride) {
4093 case 8:
4094 return audio_internal_to_linear8;
4095 case 16:
4096 return audio_internal_to_linear16;
4097 #if defined(AUDIO_SUPPORT_LINEAR24)
4098 case 24:
4099 return audio_internal_to_linear24;
4100 #endif
4101 case 32:
4102 return audio_internal_to_linear32;
4103 default:
4104 TRACET(1, track, "unsupported %s stride %d",
4105 "dst", dst->stride);
4106 goto abort;
4107 }
4108 }
4109 } else if (audio_format2_is_internal(dst)) {
4110 if (src->encoding == AUDIO_ENCODING_ULAW) {
4111 return audio_mulaw_to_internal;
4112 } else if (src->encoding == AUDIO_ENCODING_ALAW) {
4113 return audio_alaw_to_internal;
4114 } else if (audio_format2_is_linear(src)) {
4115 switch (src->stride) {
4116 case 8:
4117 return audio_linear8_to_internal;
4118 case 16:
4119 return audio_linear16_to_internal;
4120 #if defined(AUDIO_SUPPORT_LINEAR24)
4121 case 24:
4122 return audio_linear24_to_internal;
4123 #endif
4124 case 32:
4125 return audio_linear32_to_internal;
4126 default:
4127 TRACET(1, track, "unsupported %s stride %d",
4128 "src", src->stride);
4129 goto abort;
4130 }
4131 }
4132 }
4133
4134 TRACET(1, track, "unsupported encoding");
4135 abort:
4136 #if defined(AUDIO_DEBUG)
4137 if (audiodebug >= 2) {
4138 char buf[100];
4139 audio_format2_tostr(buf, sizeof(buf), src);
4140 TRACET(2, track, "src %s", buf);
4141 audio_format2_tostr(buf, sizeof(buf), dst);
4142 TRACET(2, track, "dst %s", buf);
4143 }
4144 #endif
4145 return NULL;
4146 }
4147
4148 /*
4149 * Initialize the codec stage of this track as necessary.
4150 * If successful, it initializes the codec stage as necessary, stores updated
4151 * last_dst in *last_dstp in any case, and returns 0.
4152 * Otherwise, it returns errno without modifying *last_dstp.
4153 */
4154 static int
4155 audio_track_init_codec(audio_track_t *track, audio_ring_t **last_dstp)
4156 {
4157 audio_ring_t *last_dst;
4158 audio_ring_t *srcbuf;
4159 audio_format2_t *srcfmt;
4160 audio_format2_t *dstfmt;
4161 audio_filter_arg_t *arg;
4162 u_int len;
4163 int error;
4164
4165 KASSERT(track);
4166
4167 last_dst = *last_dstp;
4168 dstfmt = &last_dst->fmt;
4169 srcfmt = &track->inputfmt;
4170 srcbuf = &track->codec.srcbuf;
4171 error = 0;
4172
4173 if (srcfmt->encoding != dstfmt->encoding
4174 || srcfmt->precision != dstfmt->precision
4175 || srcfmt->stride != dstfmt->stride) {
4176 track->codec.dst = last_dst;
4177
4178 srcbuf->fmt = *dstfmt;
4179 srcbuf->fmt.encoding = srcfmt->encoding;
4180 srcbuf->fmt.precision = srcfmt->precision;
4181 srcbuf->fmt.stride = srcfmt->stride;
4182
4183 track->codec.filter = audio_track_get_codec(track,
4184 &srcbuf->fmt, dstfmt);
4185 if (track->codec.filter == NULL) {
4186 error = EINVAL;
4187 goto abort;
4188 }
4189
4190 srcbuf->head = 0;
4191 srcbuf->used = 0;
4192 srcbuf->capacity = frame_per_block(track->mixer, &srcbuf->fmt);
4193 len = auring_bytelen(srcbuf);
4194 srcbuf->mem = audio_realloc(srcbuf->mem, len);
4195
4196 arg = &track->codec.arg;
4197 arg->srcfmt = &srcbuf->fmt;
4198 arg->dstfmt = dstfmt;
4199 arg->context = NULL;
4200
4201 *last_dstp = srcbuf;
4202 return 0;
4203 }
4204
4205 abort:
4206 track->codec.filter = NULL;
4207 audio_free(srcbuf->mem);
4208 return error;
4209 }
4210
4211 /*
4212 * Initialize the chvol stage of this track as necessary.
4213 * If successful, it initializes the chvol stage as necessary, stores updated
4214 * last_dst in *last_dstp in any case, and returns 0.
4215 * Otherwise, it returns errno without modifying *last_dstp.
4216 */
4217 static int
4218 audio_track_init_chvol(audio_track_t *track, audio_ring_t **last_dstp)
4219 {
4220 audio_ring_t *last_dst;
4221 audio_ring_t *srcbuf;
4222 audio_format2_t *srcfmt;
4223 audio_format2_t *dstfmt;
4224 audio_filter_arg_t *arg;
4225 u_int len;
4226 int error;
4227
4228 KASSERT(track);
4229
4230 last_dst = *last_dstp;
4231 dstfmt = &last_dst->fmt;
4232 srcfmt = &track->inputfmt;
4233 srcbuf = &track->chvol.srcbuf;
4234 error = 0;
4235
4236 /* Check whether channel volume conversion is necessary. */
4237 bool use_chvol = false;
4238 for (int ch = 0; ch < srcfmt->channels; ch++) {
4239 if (track->ch_volume[ch] != 256) {
4240 use_chvol = true;
4241 break;
4242 }
4243 }
4244
4245 if (use_chvol == true) {
4246 track->chvol.dst = last_dst;
4247 track->chvol.filter = audio_track_chvol;
4248
4249 srcbuf->fmt = *dstfmt;
4250 /* no format conversion occurs */
4251
4252 srcbuf->head = 0;
4253 srcbuf->used = 0;
4254 srcbuf->capacity = frame_per_block(track->mixer, &srcbuf->fmt);
4255 len = auring_bytelen(srcbuf);
4256 srcbuf->mem = audio_realloc(srcbuf->mem, len);
4257
4258 arg = &track->chvol.arg;
4259 arg->srcfmt = &srcbuf->fmt;
4260 arg->dstfmt = dstfmt;
4261 arg->context = track->ch_volume;
4262
4263 *last_dstp = srcbuf;
4264 return 0;
4265 }
4266
4267 track->chvol.filter = NULL;
4268 audio_free(srcbuf->mem);
4269 return error;
4270 }
4271
4272 /*
4273 * Initialize the chmix stage of this track as necessary.
4274 * If successful, it initializes the chmix stage as necessary, stores updated
4275 * last_dst in *last_dstp in any case, and returns 0.
4276 * Otherwise, it returns errno without modifying *last_dstp.
4277 */
4278 static int
4279 audio_track_init_chmix(audio_track_t *track, audio_ring_t **last_dstp)
4280 {
4281 audio_ring_t *last_dst;
4282 audio_ring_t *srcbuf;
4283 audio_format2_t *srcfmt;
4284 audio_format2_t *dstfmt;
4285 audio_filter_arg_t *arg;
4286 u_int srcch;
4287 u_int dstch;
4288 u_int len;
4289 int error;
4290
4291 KASSERT(track);
4292
4293 last_dst = *last_dstp;
4294 dstfmt = &last_dst->fmt;
4295 srcfmt = &track->inputfmt;
4296 srcbuf = &track->chmix.srcbuf;
4297 error = 0;
4298
4299 srcch = srcfmt->channels;
4300 dstch = dstfmt->channels;
4301 if (srcch != dstch) {
4302 track->chmix.dst = last_dst;
4303
4304 if (srcch >= 2 && dstch == 1) {
4305 track->chmix.filter = audio_track_chmix_mixLR;
4306 } else if (srcch == 1 && dstch >= 2) {
4307 track->chmix.filter = audio_track_chmix_dupLR;
4308 } else if (srcch > dstch) {
4309 track->chmix.filter = audio_track_chmix_shrink;
4310 } else {
4311 track->chmix.filter = audio_track_chmix_expand;
4312 }
4313
4314 srcbuf->fmt = *dstfmt;
4315 srcbuf->fmt.channels = srcch;
4316
4317 srcbuf->head = 0;
4318 srcbuf->used = 0;
4319 /* XXX The buffer size should be able to calculate. */
4320 srcbuf->capacity = frame_per_block(track->mixer, &srcbuf->fmt);
4321 len = auring_bytelen(srcbuf);
4322 srcbuf->mem = audio_realloc(srcbuf->mem, len);
4323
4324 arg = &track->chmix.arg;
4325 arg->srcfmt = &srcbuf->fmt;
4326 arg->dstfmt = dstfmt;
4327 arg->context = NULL;
4328
4329 *last_dstp = srcbuf;
4330 return 0;
4331 }
4332
4333 track->chmix.filter = NULL;
4334 audio_free(srcbuf->mem);
4335 return error;
4336 }
4337
4338 /*
4339 * Initialize the freq stage of this track as necessary.
4340 * If successful, it initializes the freq stage as necessary, stores updated
4341 * last_dst in *last_dstp in any case, and returns 0.
4342 * Otherwise, it returns errno without modifying *last_dstp.
4343 */
4344 static int
4345 audio_track_init_freq(audio_track_t *track, audio_ring_t **last_dstp)
4346 {
4347 audio_ring_t *last_dst;
4348 audio_ring_t *srcbuf;
4349 audio_format2_t *srcfmt;
4350 audio_format2_t *dstfmt;
4351 audio_filter_arg_t *arg;
4352 uint32_t srcfreq;
4353 uint32_t dstfreq;
4354 u_int dst_capacity;
4355 u_int mod;
4356 u_int len;
4357 int error;
4358
4359 KASSERT(track);
4360
4361 last_dst = *last_dstp;
4362 dstfmt = &last_dst->fmt;
4363 srcfmt = &track->inputfmt;
4364 srcbuf = &track->freq.srcbuf;
4365 error = 0;
4366
4367 srcfreq = srcfmt->sample_rate;
4368 dstfreq = dstfmt->sample_rate;
4369 if (srcfreq != dstfreq) {
4370 track->freq.dst = last_dst;
4371
4372 memset(track->freq_prev, 0, sizeof(track->freq_prev));
4373 memset(track->freq_curr, 0, sizeof(track->freq_curr));
4374
4375 /* freq_step is the ratio of src/dst when let dst 65536. */
4376 track->freq_step = (uint64_t)srcfreq * 65536 / dstfreq;
4377
4378 dst_capacity = frame_per_block(track->mixer, dstfmt);
4379 mod = (uint64_t)srcfreq * 65536 % dstfreq;
4380 track->freq_leap = (mod * dst_capacity + dstfreq / 2) / dstfreq;
4381
4382 if (track->freq_step < 65536) {
4383 track->freq.filter = audio_track_freq_up;
4384 /* In order to carry at the first time. */
4385 track->freq_current = 65536;
4386 } else {
4387 track->freq.filter = audio_track_freq_down;
4388 track->freq_current = 0;
4389 }
4390
4391 srcbuf->fmt = *dstfmt;
4392 srcbuf->fmt.sample_rate = srcfreq;
4393
4394 srcbuf->head = 0;
4395 srcbuf->used = 0;
4396 srcbuf->capacity = frame_per_block(track->mixer, &srcbuf->fmt);
4397 len = auring_bytelen(srcbuf);
4398 srcbuf->mem = audio_realloc(srcbuf->mem, len);
4399
4400 arg = &track->freq.arg;
4401 arg->srcfmt = &srcbuf->fmt;
4402 arg->dstfmt = dstfmt;/*&last_dst->fmt;*/
4403 arg->context = track;
4404
4405 *last_dstp = srcbuf;
4406 return 0;
4407 }
4408
4409 track->freq.filter = NULL;
4410 audio_free(srcbuf->mem);
4411 return error;
4412 }
4413
4414 /*
4415 * When playing back: (e.g. if codec and freq stage are valid)
4416 *
4417 * write
4418 * | uiomove
4419 * v
4420 * usrbuf [...............] byte ring buffer (mmap-able)
4421 * | memcpy
4422 * v
4423 * codec.srcbuf[....] 1 block (ring) buffer <-- stage input
4424 * .dst ----+
4425 * | convert
4426 * v
4427 * freq.srcbuf [....] 1 block (ring) buffer
4428 * .dst ----+
4429 * | convert
4430 * v
4431 * outbuf [...............] NBLKOUT blocks ring buffer
4432 *
4433 *
4434 * When recording:
4435 *
4436 * freq.srcbuf [...............] NBLKOUT blocks ring buffer <-- stage input
4437 * .dst ----+
4438 * | convert
4439 * v
4440 * codec.srcbuf[.....] 1 block (ring) buffer
4441 * .dst ----+
4442 * | convert
4443 * v
4444 * outbuf [.....] 1 block (ring) buffer
4445 * | memcpy
4446 * v
4447 * usrbuf [...............] byte ring buffer (mmap-able *)
4448 * | uiomove
4449 * v
4450 * read
4451 *
4452 * *: usrbuf for recording is also mmap-able due to symmetry with
4453 * playback buffer, but for now mmap will never happen for recording.
4454 */
4455
4456 /*
4457 * Set the userland format of this track.
4458 * usrfmt argument should have been previously verified by
4459 * audio_track_setinfo_check().
4460 * This function may release and reallocate all internal conversion buffers.
4461 * It returns 0 if successful. Otherwise it returns errno with clearing all
4462 * internal buffers.
4463 * It must be called without sc_intr_lock since uvm_* routines require non
4464 * intr_lock state.
4465 * It must be called with track lock held since it may release and reallocate
4466 * outbuf.
4467 */
4468 static int
4469 audio_track_set_format(audio_track_t *track, audio_format2_t *usrfmt)
4470 {
4471 struct audio_softc *sc;
4472 u_int newbufsize;
4473 u_int oldblksize;
4474 u_int len;
4475 int error;
4476
4477 KASSERT(track);
4478 sc = track->mixer->sc;
4479
4480 /* usrbuf is the closest buffer to the userland. */
4481 track->usrbuf.fmt = *usrfmt;
4482
4483 /*
4484 * For references, one block size (in 40msec) is:
4485 * 320 bytes = 204 blocks/64KB for mulaw/8kHz/1ch
4486 * 7680 bytes = 8 blocks/64KB for s16/48kHz/2ch
4487 * 30720 bytes = 90 KB/3blocks for s16/48kHz/8ch
4488 * 61440 bytes = 180 KB/3blocks for s16/96kHz/8ch
4489 * 245760 bytes = 720 KB/3blocks for s32/192kHz/8ch
4490 *
4491 * For example,
4492 * 1) If usrbuf_blksize = 7056 (s16/44.1k/2ch) and PAGE_SIZE = 8192,
4493 * newbufsize = rounddown(65536 / 7056) = 63504
4494 * newvsize = roundup2(63504, PAGE_SIZE) = 65536
4495 * Therefore it maps 8 * 8K pages and usrbuf->capacity = 63504.
4496 *
4497 * 2) If usrbuf_blksize = 7680 (s16/48k/2ch) and PAGE_SIZE = 4096,
4498 * newbufsize = rounddown(65536 / 7680) = 61440
4499 * newvsize = roundup2(61440, PAGE_SIZE) = 61440 (= 15 pages)
4500 * Therefore it maps 15 * 4K pages and usrbuf->capacity = 61440.
4501 */
4502 oldblksize = track->usrbuf_blksize;
4503 track->usrbuf_blksize = frametobyte(&track->usrbuf.fmt,
4504 frame_per_block(track->mixer, &track->usrbuf.fmt));
4505 track->usrbuf.head = 0;
4506 track->usrbuf.used = 0;
4507 newbufsize = MAX(track->usrbuf_blksize * AUMINNOBLK, 65536);
4508 newbufsize = rounddown(newbufsize, track->usrbuf_blksize);
4509 error = audio_realloc_usrbuf(track, newbufsize);
4510 if (error) {
4511 device_printf(sc->sc_dev, "malloc usrbuf(%d) failed\n",
4512 newbufsize);
4513 goto error;
4514 }
4515
4516 /* Recalc water mark. */
4517 if (track->usrbuf_blksize != oldblksize) {
4518 if (audio_track_is_playback(track)) {
4519 /* Set high at 100%, low at 75%. */
4520 track->usrbuf_usedhigh = track->usrbuf.capacity;
4521 track->usrbuf_usedlow = track->usrbuf.capacity * 3 / 4;
4522 } else {
4523 /* Set high at 100% minus 1block(?), low at 0% */
4524 track->usrbuf_usedhigh = track->usrbuf.capacity -
4525 track->usrbuf_blksize;
4526 track->usrbuf_usedlow = 0;
4527 }
4528 }
4529
4530 /* Stage buffer */
4531 audio_ring_t *last_dst = &track->outbuf;
4532 if (audio_track_is_playback(track)) {
4533 /* On playback, initialize from the mixer side in order. */
4534 track->inputfmt = *usrfmt;
4535 track->outbuf.fmt = track->mixer->track_fmt;
4536
4537 if ((error = audio_track_init_freq(track, &last_dst)) != 0)
4538 goto error;
4539 if ((error = audio_track_init_chmix(track, &last_dst)) != 0)
4540 goto error;
4541 if ((error = audio_track_init_chvol(track, &last_dst)) != 0)
4542 goto error;
4543 if ((error = audio_track_init_codec(track, &last_dst)) != 0)
4544 goto error;
4545 } else {
4546 /* On recording, initialize from userland side in order. */
4547 track->inputfmt = track->mixer->track_fmt;
4548 track->outbuf.fmt = *usrfmt;
4549
4550 if ((error = audio_track_init_codec(track, &last_dst)) != 0)
4551 goto error;
4552 if ((error = audio_track_init_chvol(track, &last_dst)) != 0)
4553 goto error;
4554 if ((error = audio_track_init_chmix(track, &last_dst)) != 0)
4555 goto error;
4556 if ((error = audio_track_init_freq(track, &last_dst)) != 0)
4557 goto error;
4558 }
4559 #if 0
4560 /* debug */
4561 if (track->freq.filter) {
4562 audio_print_format2("freq src", &track->freq.srcbuf.fmt);
4563 audio_print_format2("freq dst", &track->freq.dst->fmt);
4564 }
4565 if (track->chmix.filter) {
4566 audio_print_format2("chmix src", &track->chmix.srcbuf.fmt);
4567 audio_print_format2("chmix dst", &track->chmix.dst->fmt);
4568 }
4569 if (track->chvol.filter) {
4570 audio_print_format2("chvol src", &track->chvol.srcbuf.fmt);
4571 audio_print_format2("chvol dst", &track->chvol.dst->fmt);
4572 }
4573 if (track->codec.filter) {
4574 audio_print_format2("codec src", &track->codec.srcbuf.fmt);
4575 audio_print_format2("codec dst", &track->codec.dst->fmt);
4576 }
4577 #endif
4578
4579 /* Stage input buffer */
4580 track->input = last_dst;
4581
4582 /*
4583 * On the recording track, make the first stage a ring buffer.
4584 * XXX is there a better way?
4585 */
4586 if (audio_track_is_record(track)) {
4587 track->input->capacity = NBLKOUT *
4588 frame_per_block(track->mixer, &track->input->fmt);
4589 len = auring_bytelen(track->input);
4590 track->input->mem = audio_realloc(track->input->mem, len);
4591 }
4592
4593 /*
4594 * Output buffer.
4595 * On the playback track, its capacity is NBLKOUT blocks.
4596 * On the recording track, its capacity is 1 block.
4597 */
4598 track->outbuf.head = 0;
4599 track->outbuf.used = 0;
4600 track->outbuf.capacity = frame_per_block(track->mixer,
4601 &track->outbuf.fmt);
4602 if (audio_track_is_playback(track))
4603 track->outbuf.capacity *= NBLKOUT;
4604 len = auring_bytelen(&track->outbuf);
4605 track->outbuf.mem = audio_realloc(track->outbuf.mem, len);
4606 if (track->outbuf.mem == NULL) {
4607 device_printf(sc->sc_dev, "malloc outbuf(%d) failed\n", len);
4608 error = ENOMEM;
4609 goto error;
4610 }
4611
4612 #if defined(AUDIO_DEBUG)
4613 if (audiodebug >= 3) {
4614 struct audio_track_debugbuf m;
4615
4616 memset(&m, 0, sizeof(m));
4617 snprintf(m.outbuf, sizeof(m.outbuf), " out=%d",
4618 track->outbuf.capacity * frametobyte(&track->outbuf.fmt,1));
4619 if (track->freq.filter)
4620 snprintf(m.freq, sizeof(m.freq), " freq=%d",
4621 track->freq.srcbuf.capacity *
4622 frametobyte(&track->freq.srcbuf.fmt, 1));
4623 if (track->chmix.filter)
4624 snprintf(m.chmix, sizeof(m.chmix), " chmix=%d",
4625 track->chmix.srcbuf.capacity *
4626 frametobyte(&track->chmix.srcbuf.fmt, 1));
4627 if (track->chvol.filter)
4628 snprintf(m.chvol, sizeof(m.chvol), " chvol=%d",
4629 track->chvol.srcbuf.capacity *
4630 frametobyte(&track->chvol.srcbuf.fmt, 1));
4631 if (track->codec.filter)
4632 snprintf(m.codec, sizeof(m.codec), " codec=%d",
4633 track->codec.srcbuf.capacity *
4634 frametobyte(&track->codec.srcbuf.fmt, 1));
4635 snprintf(m.usrbuf, sizeof(m.usrbuf),
4636 " usr=%d", track->usrbuf.capacity);
4637
4638 if (audio_track_is_playback(track)) {
4639 TRACET(0, track, "bufsize%s%s%s%s%s%s",
4640 m.outbuf, m.freq, m.chmix,
4641 m.chvol, m.codec, m.usrbuf);
4642 } else {
4643 TRACET(0, track, "bufsize%s%s%s%s%s%s",
4644 m.freq, m.chmix, m.chvol,
4645 m.codec, m.outbuf, m.usrbuf);
4646 }
4647 }
4648 #endif
4649 return 0;
4650
4651 error:
4652 audio_free_usrbuf(track);
4653 audio_free(track->codec.srcbuf.mem);
4654 audio_free(track->chvol.srcbuf.mem);
4655 audio_free(track->chmix.srcbuf.mem);
4656 audio_free(track->freq.srcbuf.mem);
4657 audio_free(track->outbuf.mem);
4658 return error;
4659 }
4660
4661 /*
4662 * Fill silence frames (as the internal format) up to 1 block
4663 * if the ring is not empty and less than 1 block.
4664 * It returns the number of appended frames.
4665 */
4666 static int
4667 audio_append_silence(audio_track_t *track, audio_ring_t *ring)
4668 {
4669 int fpb;
4670 int n;
4671
4672 KASSERT(track);
4673 KASSERT(audio_format2_is_internal(&ring->fmt));
4674
4675 /* XXX is n correct? */
4676 /* XXX memset uses frametobyte()? */
4677
4678 if (ring->used == 0)
4679 return 0;
4680
4681 fpb = frame_per_block(track->mixer, &ring->fmt);
4682 if (ring->used >= fpb)
4683 return 0;
4684
4685 n = (ring->capacity - ring->used) % fpb;
4686
4687 KASSERTMSG(auring_get_contig_free(ring) >= n,
4688 "auring_get_contig_free(ring)=%d n=%d",
4689 auring_get_contig_free(ring), n);
4690
4691 memset(auring_tailptr_aint(ring), 0,
4692 n * ring->fmt.channels * sizeof(aint_t));
4693 auring_push(ring, n);
4694 return n;
4695 }
4696
4697 /*
4698 * Execute the conversion stage.
4699 * It prepares arg from this stage and executes stage->filter.
4700 * It must be called only if stage->filter is not NULL.
4701 *
4702 * For stages other than frequency conversion, the function increments
4703 * src and dst counters here. For frequency conversion stage, on the
4704 * other hand, the function does not touch src and dst counters and
4705 * filter side has to increment them.
4706 */
4707 static void
4708 audio_apply_stage(audio_track_t *track, audio_stage_t *stage, bool isfreq)
4709 {
4710 audio_filter_arg_t *arg;
4711 int srccount;
4712 int dstcount;
4713 int count;
4714
4715 KASSERT(track);
4716 KASSERT(stage->filter);
4717
4718 srccount = auring_get_contig_used(&stage->srcbuf);
4719 dstcount = auring_get_contig_free(stage->dst);
4720
4721 if (isfreq) {
4722 KASSERTMSG(srccount > 0, "freq but srccount=%d", srccount);
4723 count = uimin(dstcount, track->mixer->frames_per_block);
4724 } else {
4725 count = uimin(srccount, dstcount);
4726 }
4727
4728 if (count > 0) {
4729 arg = &stage->arg;
4730 arg->src = auring_headptr(&stage->srcbuf);
4731 arg->dst = auring_tailptr(stage->dst);
4732 arg->count = count;
4733
4734 stage->filter(arg);
4735
4736 if (!isfreq) {
4737 auring_take(&stage->srcbuf, count);
4738 auring_push(stage->dst, count);
4739 }
4740 }
4741 }
4742
4743 /*
4744 * Produce output buffer for playback from user input buffer.
4745 * It must be called only if usrbuf is not empty and outbuf is
4746 * available at least one free block.
4747 */
4748 static void
4749 audio_track_play(audio_track_t *track)
4750 {
4751 audio_ring_t *usrbuf;
4752 audio_ring_t *input;
4753 int count;
4754 int framesize;
4755 int bytes;
4756
4757 KASSERT(track);
4758 KASSERT(track->lock);
4759 TRACET(4, track, "start pstate=%d", track->pstate);
4760
4761 /* At this point usrbuf must not be empty. */
4762 KASSERT(track->usrbuf.used > 0);
4763 /* Also, outbuf must be available at least one block. */
4764 count = auring_get_contig_free(&track->outbuf);
4765 KASSERTMSG(count >= frame_per_block(track->mixer, &track->outbuf.fmt),
4766 "count=%d fpb=%d",
4767 count, frame_per_block(track->mixer, &track->outbuf.fmt));
4768
4769 /* XXX TODO: is this necessary for now? */
4770 int track_count_0 = track->outbuf.used;
4771
4772 usrbuf = &track->usrbuf;
4773 input = track->input;
4774
4775 /*
4776 * framesize is always 1 byte or more since all formats supported as
4777 * usrfmt(=input) have 8bit or more stride.
4778 */
4779 framesize = frametobyte(&input->fmt, 1);
4780 KASSERT(framesize >= 1);
4781
4782 /* The next stage of usrbuf (=input) must be available. */
4783 KASSERT(auring_get_contig_free(input) > 0);
4784
4785 /*
4786 * Copy usrbuf up to 1block to input buffer.
4787 * count is the number of frames to copy from usrbuf.
4788 * bytes is the number of bytes to copy from usrbuf. However it is
4789 * not copied less than one frame.
4790 */
4791 count = uimin(usrbuf->used, track->usrbuf_blksize) / framesize;
4792 bytes = count * framesize;
4793
4794 track->usrbuf_stamp += bytes;
4795
4796 if (usrbuf->head + bytes < usrbuf->capacity) {
4797 memcpy((uint8_t *)input->mem + auring_tail(input) * framesize,
4798 (uint8_t *)usrbuf->mem + usrbuf->head,
4799 bytes);
4800 auring_push(input, count);
4801 auring_take(usrbuf, bytes);
4802 } else {
4803 int bytes1;
4804 int bytes2;
4805
4806 bytes1 = auring_get_contig_used(usrbuf);
4807 KASSERTMSG(bytes1 % framesize == 0,
4808 "bytes1=%d framesize=%d", bytes1, framesize);
4809 memcpy((uint8_t *)input->mem + auring_tail(input) * framesize,
4810 (uint8_t *)usrbuf->mem + usrbuf->head,
4811 bytes1);
4812 auring_push(input, bytes1 / framesize);
4813 auring_take(usrbuf, bytes1);
4814
4815 bytes2 = bytes - bytes1;
4816 memcpy((uint8_t *)input->mem + auring_tail(input) * framesize,
4817 (uint8_t *)usrbuf->mem + usrbuf->head,
4818 bytes2);
4819 auring_push(input, bytes2 / framesize);
4820 auring_take(usrbuf, bytes2);
4821 }
4822
4823 /* Encoding conversion */
4824 if (track->codec.filter)
4825 audio_apply_stage(track, &track->codec, false);
4826
4827 /* Channel volume */
4828 if (track->chvol.filter)
4829 audio_apply_stage(track, &track->chvol, false);
4830
4831 /* Channel mix */
4832 if (track->chmix.filter)
4833 audio_apply_stage(track, &track->chmix, false);
4834
4835 /* Frequency conversion */
4836 /*
4837 * Since the frequency conversion needs correction for each block,
4838 * it rounds up to 1 block.
4839 */
4840 if (track->freq.filter) {
4841 int n;
4842 n = audio_append_silence(track, &track->freq.srcbuf);
4843 if (n > 0) {
4844 TRACET(4, track,
4845 "freq.srcbuf add silence %d -> %d/%d/%d",
4846 n,
4847 track->freq.srcbuf.head,
4848 track->freq.srcbuf.used,
4849 track->freq.srcbuf.capacity);
4850 }
4851 if (track->freq.srcbuf.used > 0) {
4852 audio_apply_stage(track, &track->freq, true);
4853 }
4854 }
4855
4856 if (bytes < track->usrbuf_blksize) {
4857 /*
4858 * Clear all conversion buffer pointer if the conversion was
4859 * not exactly one block. These conversion stage buffers are
4860 * certainly circular buffers because of symmetry with the
4861 * previous and next stage buffer. However, since they are
4862 * treated as simple contiguous buffers in operation, so head
4863 * always should point 0. This may happen during drain-age.
4864 */
4865 TRACET(4, track, "reset stage");
4866 if (track->codec.filter) {
4867 KASSERT(track->codec.srcbuf.used == 0);
4868 track->codec.srcbuf.head = 0;
4869 }
4870 if (track->chvol.filter) {
4871 KASSERT(track->chvol.srcbuf.used == 0);
4872 track->chvol.srcbuf.head = 0;
4873 }
4874 if (track->chmix.filter) {
4875 KASSERT(track->chmix.srcbuf.used == 0);
4876 track->chmix.srcbuf.head = 0;
4877 }
4878 if (track->freq.filter) {
4879 KASSERT(track->freq.srcbuf.used == 0);
4880 track->freq.srcbuf.head = 0;
4881 }
4882 }
4883
4884 if (track->input == &track->outbuf) {
4885 track->outputcounter = track->inputcounter;
4886 } else {
4887 track->outputcounter += track->outbuf.used - track_count_0;
4888 }
4889
4890 #if defined(AUDIO_DEBUG)
4891 if (audiodebug >= 3) {
4892 struct audio_track_debugbuf m;
4893 audio_track_bufstat(track, &m);
4894 TRACET(0, track, "end%s%s%s%s%s%s",
4895 m.outbuf, m.freq, m.chvol, m.chmix, m.codec, m.usrbuf);
4896 }
4897 #endif
4898 }
4899
4900 /*
4901 * Produce user output buffer for recording from input buffer.
4902 */
4903 static void
4904 audio_track_record(audio_track_t *track)
4905 {
4906 audio_ring_t *outbuf;
4907 audio_ring_t *usrbuf;
4908 int count;
4909 int bytes;
4910 int framesize;
4911
4912 KASSERT(track);
4913 KASSERT(track->lock);
4914
4915 /* Number of frames to process */
4916 count = auring_get_contig_used(track->input);
4917 count = uimin(count, track->mixer->frames_per_block);
4918 if (count == 0) {
4919 TRACET(4, track, "count == 0");
4920 return;
4921 }
4922
4923 /* Frequency conversion */
4924 if (track->freq.filter) {
4925 if (track->freq.srcbuf.used > 0) {
4926 audio_apply_stage(track, &track->freq, true);
4927 /* XXX should input of freq be from beginning of buf? */
4928 }
4929 }
4930
4931 /* Channel mix */
4932 if (track->chmix.filter)
4933 audio_apply_stage(track, &track->chmix, false);
4934
4935 /* Channel volume */
4936 if (track->chvol.filter)
4937 audio_apply_stage(track, &track->chvol, false);
4938
4939 /* Encoding conversion */
4940 if (track->codec.filter)
4941 audio_apply_stage(track, &track->codec, false);
4942
4943 /* Copy outbuf to usrbuf */
4944 outbuf = &track->outbuf;
4945 usrbuf = &track->usrbuf;
4946 /* usrbuf must have at least one free block. */
4947 KASSERT(usrbuf->used <= track->usrbuf_usedhigh - track->usrbuf_blksize);
4948 /*
4949 * framesize is always 1 byte or more since all formats supported
4950 * as usrfmt(=output) have 8bit or more stride.
4951 */
4952 framesize = frametobyte(&outbuf->fmt, 1);
4953 KASSERT(framesize >= 1);
4954 /*
4955 * count is the number of frames to copy to usrbuf.
4956 * bytes is the number of bytes to copy to usrbuf.
4957 */
4958 count = outbuf->used;
4959 count = uimin(count, track->usrbuf_blksize / framesize);
4960 bytes = count * framesize;
4961 if (auring_tail(usrbuf) + bytes < usrbuf->capacity) {
4962 memcpy((uint8_t *)usrbuf->mem + auring_tail(usrbuf),
4963 (uint8_t *)outbuf->mem + outbuf->head * framesize,
4964 bytes);
4965 auring_push(usrbuf, bytes);
4966 auring_take(outbuf, count);
4967 } else {
4968 int bytes1;
4969 int bytes2;
4970
4971 bytes1 = auring_get_contig_free(usrbuf);
4972 KASSERTMSG(bytes1 % framesize == 0,
4973 "bytes1=%d framesize=%d", bytes1, framesize);
4974 memcpy((uint8_t *)usrbuf->mem + auring_tail(usrbuf),
4975 (uint8_t *)outbuf->mem + outbuf->head * framesize,
4976 bytes1);
4977 auring_push(usrbuf, bytes1);
4978 auring_take(outbuf, bytes1 / framesize);
4979
4980 bytes2 = bytes - bytes1;
4981 memcpy((uint8_t *)usrbuf->mem + auring_tail(usrbuf),
4982 (uint8_t *)outbuf->mem + outbuf->head * framesize,
4983 bytes2);
4984 auring_push(usrbuf, bytes2);
4985 auring_take(outbuf, bytes2 / framesize);
4986 }
4987
4988 /* XXX TODO: any counters here? */
4989
4990 #if defined(AUDIO_DEBUG)
4991 if (audiodebug >= 3) {
4992 struct audio_track_debugbuf m;
4993 audio_track_bufstat(track, &m);
4994 TRACET(0, track, "end%s%s%s%s%s%s",
4995 m.freq, m.chvol, m.chmix, m.codec, m.outbuf, m.usrbuf);
4996 }
4997 #endif
4998 }
4999
5000 /*
5001 * Calculate blktime [msec] from mixer(.hwbuf.fmt).
5002 * Must be called with sc_exlock held.
5003 */
5004 static u_int
5005 audio_mixer_calc_blktime(struct audio_softc *sc, audio_trackmixer_t *mixer)
5006 {
5007 audio_format2_t *fmt;
5008 u_int blktime;
5009 u_int frames_per_block;
5010
5011 KASSERT(sc->sc_exlock);
5012
5013 fmt = &mixer->hwbuf.fmt;
5014 blktime = sc->sc_blk_ms;
5015
5016 /*
5017 * If stride is not multiples of 8, special treatment is necessary.
5018 * For now, it is only x68k's vs(4), 4 bit/sample ADPCM.
5019 */
5020 if (fmt->stride == 4) {
5021 frames_per_block = fmt->sample_rate * blktime / 1000;
5022 if ((frames_per_block & 1) != 0)
5023 blktime *= 2;
5024 }
5025 #ifdef DIAGNOSTIC
5026 else if (fmt->stride % NBBY != 0) {
5027 panic("unsupported HW stride %d", fmt->stride);
5028 }
5029 #endif
5030
5031 return blktime;
5032 }
5033
5034 /*
5035 * Initialize the mixer corresponding to the mode.
5036 * Set AUMODE_PLAY to the 'mode' for playback or AUMODE_RECORD for recording.
5037 * sc->sc_[pr]mixer (corresponding to the 'mode') must be zero-filled.
5038 * This function returns 0 on successful. Otherwise returns errno.
5039 * Must be called with sc_exlock held and without sc_lock held.
5040 */
5041 static int
5042 audio_mixer_init(struct audio_softc *sc, int mode,
5043 const audio_format2_t *hwfmt, const audio_filter_reg_t *reg)
5044 {
5045 char codecbuf[64];
5046 char blkdmsbuf[8];
5047 audio_trackmixer_t *mixer;
5048 void (*softint_handler)(void *);
5049 int len;
5050 int blksize;
5051 int capacity;
5052 size_t bufsize;
5053 int hwblks;
5054 int blkms;
5055 int blkdms;
5056 int error;
5057
5058 KASSERT(hwfmt != NULL);
5059 KASSERT(reg != NULL);
5060 KASSERT(sc->sc_exlock);
5061
5062 error = 0;
5063 if (mode == AUMODE_PLAY)
5064 mixer = sc->sc_pmixer;
5065 else
5066 mixer = sc->sc_rmixer;
5067
5068 mixer->sc = sc;
5069 mixer->mode = mode;
5070
5071 mixer->hwbuf.fmt = *hwfmt;
5072 mixer->volume = 256;
5073 mixer->blktime_d = 1000;
5074 mixer->blktime_n = audio_mixer_calc_blktime(sc, mixer);
5075 sc->sc_blk_ms = mixer->blktime_n;
5076 hwblks = NBLKHW;
5077
5078 mixer->frames_per_block = frame_per_block(mixer, &mixer->hwbuf.fmt);
5079 blksize = frametobyte(&mixer->hwbuf.fmt, mixer->frames_per_block);
5080 if (sc->hw_if->round_blocksize) {
5081 int rounded;
5082 audio_params_t p = format2_to_params(&mixer->hwbuf.fmt);
5083 mutex_enter(sc->sc_lock);
5084 rounded = sc->hw_if->round_blocksize(sc->hw_hdl, blksize,
5085 mode, &p);
5086 mutex_exit(sc->sc_lock);
5087 TRACE(1, "round_blocksize %d -> %d", blksize, rounded);
5088 if (rounded != blksize) {
5089 if ((rounded * NBBY) % (mixer->hwbuf.fmt.stride *
5090 mixer->hwbuf.fmt.channels) != 0) {
5091 audio_printf(sc,
5092 "round_blocksize returned blocksize "
5093 "indivisible by framesize: "
5094 "blksize=%d rounded=%d "
5095 "stride=%ubit channels=%u\n",
5096 blksize, rounded,
5097 mixer->hwbuf.fmt.stride,
5098 mixer->hwbuf.fmt.channels);
5099 return EINVAL;
5100 }
5101 /* Recalculation */
5102 blksize = rounded;
5103 mixer->frames_per_block = blksize * NBBY /
5104 (mixer->hwbuf.fmt.stride *
5105 mixer->hwbuf.fmt.channels);
5106 }
5107 }
5108 mixer->blktime_n = mixer->frames_per_block;
5109 mixer->blktime_d = mixer->hwbuf.fmt.sample_rate;
5110
5111 capacity = mixer->frames_per_block * hwblks;
5112 bufsize = frametobyte(&mixer->hwbuf.fmt, capacity);
5113 if (sc->hw_if->round_buffersize) {
5114 size_t rounded;
5115 mutex_enter(sc->sc_lock);
5116 rounded = sc->hw_if->round_buffersize(sc->hw_hdl, mode,
5117 bufsize);
5118 mutex_exit(sc->sc_lock);
5119 TRACE(1, "round_buffersize %zd -> %zd", bufsize, rounded);
5120 if (rounded < bufsize) {
5121 /* buffersize needs NBLKHW blocks at least. */
5122 audio_printf(sc,
5123 "round_buffersize returned too small buffersize: "
5124 "buffersize=%zd blksize=%d\n",
5125 rounded, blksize);
5126 return EINVAL;
5127 }
5128 if (rounded % blksize != 0) {
5129 /* buffersize/blksize constraint mismatch? */
5130 audio_printf(sc,
5131 "round_buffersize returned buffersize indivisible "
5132 "by blksize: buffersize=%zu blksize=%d\n",
5133 rounded, blksize);
5134 return EINVAL;
5135 }
5136 if (rounded != bufsize) {
5137 /* Recalculation */
5138 bufsize = rounded;
5139 hwblks = bufsize / blksize;
5140 capacity = mixer->frames_per_block * hwblks;
5141 }
5142 }
5143 TRACE(1, "buffersize for %s = %zu",
5144 (mode == AUMODE_PLAY) ? "playback" : "recording",
5145 bufsize);
5146 mixer->hwbuf.capacity = capacity;
5147
5148 if (sc->hw_if->allocm) {
5149 /* sc_lock is not necessary for allocm */
5150 mixer->hwbuf.mem = sc->hw_if->allocm(sc->hw_hdl, mode, bufsize);
5151 if (mixer->hwbuf.mem == NULL) {
5152 audio_printf(sc, "allocm(%zu) failed\n", bufsize);
5153 return ENOMEM;
5154 }
5155 } else {
5156 mixer->hwbuf.mem = kmem_alloc(bufsize, KM_SLEEP);
5157 }
5158
5159 /* From here, audio_mixer_destroy is necessary to exit. */
5160 if (mode == AUMODE_PLAY) {
5161 cv_init(&mixer->outcv, "audiowr");
5162 } else {
5163 cv_init(&mixer->outcv, "audiord");
5164 }
5165
5166 if (mode == AUMODE_PLAY) {
5167 softint_handler = audio_softintr_wr;
5168 } else {
5169 softint_handler = audio_softintr_rd;
5170 }
5171 mixer->sih = softint_establish(SOFTINT_SERIAL | SOFTINT_MPSAFE,
5172 softint_handler, sc);
5173 if (mixer->sih == NULL) {
5174 device_printf(sc->sc_dev, "softint_establish failed\n");
5175 goto abort;
5176 }
5177
5178 mixer->track_fmt.encoding = AUDIO_ENCODING_SLINEAR_NE;
5179 mixer->track_fmt.precision = AUDIO_INTERNAL_BITS;
5180 mixer->track_fmt.stride = AUDIO_INTERNAL_BITS;
5181 mixer->track_fmt.channels = mixer->hwbuf.fmt.channels;
5182 mixer->track_fmt.sample_rate = mixer->hwbuf.fmt.sample_rate;
5183
5184 if (mixer->hwbuf.fmt.encoding == AUDIO_ENCODING_SLINEAR_OE &&
5185 mixer->hwbuf.fmt.precision == AUDIO_INTERNAL_BITS) {
5186 mixer->swap_endian = true;
5187 TRACE(1, "swap_endian");
5188 }
5189
5190 if (mode == AUMODE_PLAY) {
5191 /* Mixing buffer */
5192 mixer->mixfmt = mixer->track_fmt;
5193 mixer->mixfmt.precision *= 2;
5194 mixer->mixfmt.stride *= 2;
5195 /* XXX TODO: use some macros? */
5196 len = mixer->frames_per_block * mixer->mixfmt.channels *
5197 mixer->mixfmt.stride / NBBY;
5198 mixer->mixsample = audio_realloc(mixer->mixsample, len);
5199 } else {
5200 /* No mixing buffer for recording */
5201 }
5202
5203 if (reg->codec) {
5204 mixer->codec = reg->codec;
5205 mixer->codecarg.context = reg->context;
5206 if (mode == AUMODE_PLAY) {
5207 mixer->codecarg.srcfmt = &mixer->track_fmt;
5208 mixer->codecarg.dstfmt = &mixer->hwbuf.fmt;
5209 } else {
5210 mixer->codecarg.srcfmt = &mixer->hwbuf.fmt;
5211 mixer->codecarg.dstfmt = &mixer->track_fmt;
5212 }
5213 mixer->codecbuf.fmt = mixer->track_fmt;
5214 mixer->codecbuf.capacity = mixer->frames_per_block;
5215 len = auring_bytelen(&mixer->codecbuf);
5216 mixer->codecbuf.mem = audio_realloc(mixer->codecbuf.mem, len);
5217 if (mixer->codecbuf.mem == NULL) {
5218 device_printf(sc->sc_dev,
5219 "malloc codecbuf(%d) failed\n", len);
5220 error = ENOMEM;
5221 goto abort;
5222 }
5223 }
5224
5225 /* Succeeded so display it. */
5226 codecbuf[0] = '\0';
5227 if (mixer->codec || mixer->swap_endian) {
5228 snprintf(codecbuf, sizeof(codecbuf), " %s %s:%d",
5229 (mode == AUMODE_PLAY) ? "->" : "<-",
5230 audio_encoding_name(mixer->hwbuf.fmt.encoding),
5231 mixer->hwbuf.fmt.precision);
5232 }
5233 blkms = mixer->blktime_n * 1000 / mixer->blktime_d;
5234 blkdms = (mixer->blktime_n * 10000 / mixer->blktime_d) % 10;
5235 blkdmsbuf[0] = '\0';
5236 if (blkdms != 0) {
5237 snprintf(blkdmsbuf, sizeof(blkdmsbuf), ".%1d", blkdms);
5238 }
5239 aprint_normal_dev(sc->sc_dev,
5240 "%s:%d%s %dch %dHz, blk %d bytes (%d%sms) for %s\n",
5241 audio_encoding_name(mixer->track_fmt.encoding),
5242 mixer->track_fmt.precision,
5243 codecbuf,
5244 mixer->track_fmt.channels,
5245 mixer->track_fmt.sample_rate,
5246 blksize,
5247 blkms, blkdmsbuf,
5248 (mode == AUMODE_PLAY) ? "playback" : "recording");
5249
5250 return 0;
5251
5252 abort:
5253 audio_mixer_destroy(sc, mixer);
5254 return error;
5255 }
5256
5257 /*
5258 * Releases all resources of 'mixer'.
5259 * Note that it does not release the memory area of 'mixer' itself.
5260 * Must be called with sc_exlock held and without sc_lock held.
5261 */
5262 static void
5263 audio_mixer_destroy(struct audio_softc *sc, audio_trackmixer_t *mixer)
5264 {
5265 int bufsize;
5266
5267 KASSERT(sc->sc_exlock == 1);
5268
5269 bufsize = frametobyte(&mixer->hwbuf.fmt, mixer->hwbuf.capacity);
5270
5271 if (mixer->hwbuf.mem != NULL) {
5272 if (sc->hw_if->freem) {
5273 /* sc_lock is not necessary for freem */
5274 sc->hw_if->freem(sc->hw_hdl, mixer->hwbuf.mem, bufsize);
5275 } else {
5276 kmem_free(mixer->hwbuf.mem, bufsize);
5277 }
5278 mixer->hwbuf.mem = NULL;
5279 }
5280
5281 audio_free(mixer->codecbuf.mem);
5282 audio_free(mixer->mixsample);
5283
5284 cv_destroy(&mixer->outcv);
5285
5286 if (mixer->sih) {
5287 softint_disestablish(mixer->sih);
5288 mixer->sih = NULL;
5289 }
5290 }
5291
5292 /*
5293 * Starts playback mixer.
5294 * Must be called only if sc_pbusy is false.
5295 * Must be called with sc_lock && sc_exlock held.
5296 * Must not be called from the interrupt context.
5297 */
5298 static void
5299 audio_pmixer_start(struct audio_softc *sc, bool force)
5300 {
5301 audio_trackmixer_t *mixer;
5302 int minimum;
5303
5304 KASSERT(mutex_owned(sc->sc_lock));
5305 KASSERT(sc->sc_exlock);
5306 KASSERT(sc->sc_pbusy == false);
5307
5308 mutex_enter(sc->sc_intr_lock);
5309
5310 mixer = sc->sc_pmixer;
5311 TRACE(2, "%smixseq=%d hwseq=%d hwbuf=%d/%d/%d%s",
5312 (audiodebug >= 3) ? "begin " : "",
5313 (int)mixer->mixseq, (int)mixer->hwseq,
5314 mixer->hwbuf.head, mixer->hwbuf.used, mixer->hwbuf.capacity,
5315 force ? " force" : "");
5316
5317 /* Need two blocks to start normally. */
5318 minimum = (force) ? 1 : 2;
5319 while (mixer->hwbuf.used < mixer->frames_per_block * minimum) {
5320 audio_pmixer_process(sc);
5321 }
5322
5323 /* Start output */
5324 audio_pmixer_output(sc);
5325 sc->sc_pbusy = true;
5326
5327 TRACE(3, "end mixseq=%d hwseq=%d hwbuf=%d/%d/%d",
5328 (int)mixer->mixseq, (int)mixer->hwseq,
5329 mixer->hwbuf.head, mixer->hwbuf.used, mixer->hwbuf.capacity);
5330
5331 mutex_exit(sc->sc_intr_lock);
5332 }
5333
5334 /*
5335 * When playing back with MD filter:
5336 *
5337 * track track ...
5338 * v v
5339 * + mix (with aint2_t)
5340 * | master volume (with aint2_t)
5341 * v
5342 * mixsample [::::] wide-int 1 block (ring) buffer
5343 * |
5344 * | convert aint2_t -> aint_t
5345 * v
5346 * codecbuf [....] 1 block (ring) buffer
5347 * |
5348 * | convert to hw format
5349 * v
5350 * hwbuf [............] NBLKHW blocks ring buffer
5351 *
5352 * When playing back without MD filter:
5353 *
5354 * mixsample [::::] wide-int 1 block (ring) buffer
5355 * |
5356 * | convert aint2_t -> aint_t
5357 * | (with byte swap if necessary)
5358 * v
5359 * hwbuf [............] NBLKHW blocks ring buffer
5360 *
5361 * mixsample: slinear_NE, wide internal precision, HW ch, HW freq.
5362 * codecbuf: slinear_NE, internal precision, HW ch, HW freq.
5363 * hwbuf: HW encoding, HW precision, HW ch, HW freq.
5364 */
5365
5366 /*
5367 * Performs track mixing and converts it to hwbuf.
5368 * Note that this function doesn't transfer hwbuf to hardware.
5369 * Must be called with sc_intr_lock held.
5370 */
5371 static void
5372 audio_pmixer_process(struct audio_softc *sc)
5373 {
5374 audio_trackmixer_t *mixer;
5375 audio_file_t *f;
5376 int frame_count;
5377 int sample_count;
5378 int mixed;
5379 int i;
5380 aint2_t *m;
5381 aint_t *h;
5382
5383 mixer = sc->sc_pmixer;
5384
5385 frame_count = mixer->frames_per_block;
5386 KASSERTMSG(auring_get_contig_free(&mixer->hwbuf) >= frame_count,
5387 "auring_get_contig_free()=%d frame_count=%d",
5388 auring_get_contig_free(&mixer->hwbuf), frame_count);
5389 sample_count = frame_count * mixer->mixfmt.channels;
5390
5391 mixer->mixseq++;
5392
5393 /* Mix all tracks */
5394 mixed = 0;
5395 SLIST_FOREACH(f, &sc->sc_files, entry) {
5396 audio_track_t *track = f->ptrack;
5397
5398 if (track == NULL)
5399 continue;
5400
5401 if (track->is_pause) {
5402 TRACET(4, track, "skip; paused");
5403 continue;
5404 }
5405
5406 /* Skip if the track is used by process context. */
5407 if (audio_track_lock_tryenter(track) == false) {
5408 TRACET(4, track, "skip; in use");
5409 continue;
5410 }
5411
5412 /* Emulate mmap'ped track */
5413 if (track->mmapped) {
5414 auring_push(&track->usrbuf, track->usrbuf_blksize);
5415 TRACET(4, track, "mmap; usr=%d/%d/C%d",
5416 track->usrbuf.head,
5417 track->usrbuf.used,
5418 track->usrbuf.capacity);
5419 }
5420
5421 if (track->outbuf.used < mixer->frames_per_block &&
5422 track->usrbuf.used > 0) {
5423 TRACET(4, track, "process");
5424 audio_track_play(track);
5425 }
5426
5427 if (track->outbuf.used > 0) {
5428 mixed = audio_pmixer_mix_track(mixer, track, mixed);
5429 } else {
5430 TRACET(4, track, "skip; empty");
5431 }
5432
5433 audio_track_lock_exit(track);
5434 }
5435
5436 if (mixed == 0) {
5437 /* Silence */
5438 memset(mixer->mixsample, 0,
5439 frametobyte(&mixer->mixfmt, frame_count));
5440 } else {
5441 if (mixed > 1) {
5442 /* If there are multiple tracks, do auto gain control */
5443 audio_pmixer_agc(mixer, sample_count);
5444 }
5445
5446 /* Apply master volume */
5447 if (mixer->volume < 256) {
5448 m = mixer->mixsample;
5449 for (i = 0; i < sample_count; i++) {
5450 *m = AUDIO_SCALEDOWN(*m * mixer->volume, 8);
5451 m++;
5452 }
5453
5454 /*
5455 * Recover the volume gradually at the pace of
5456 * several times per second. If it's too fast, you
5457 * can recognize that the volume changes up and down
5458 * quickly and it's not so comfortable.
5459 */
5460 mixer->voltimer += mixer->blktime_n;
5461 if (mixer->voltimer * 4 >= mixer->blktime_d) {
5462 mixer->volume++;
5463 mixer->voltimer = 0;
5464 #if defined(AUDIO_DEBUG_AGC)
5465 TRACE(1, "volume recover: %d", mixer->volume);
5466 #endif
5467 }
5468 }
5469 }
5470
5471 /*
5472 * The rest is the hardware part.
5473 */
5474
5475 if (mixer->codec) {
5476 h = auring_tailptr_aint(&mixer->codecbuf);
5477 } else {
5478 h = auring_tailptr_aint(&mixer->hwbuf);
5479 }
5480
5481 m = mixer->mixsample;
5482 if (mixer->swap_endian) {
5483 for (i = 0; i < sample_count; i++) {
5484 *h++ = bswap16(*m++);
5485 }
5486 } else {
5487 for (i = 0; i < sample_count; i++) {
5488 *h++ = *m++;
5489 }
5490 }
5491
5492 /* Hardware driver's codec */
5493 if (mixer->codec) {
5494 auring_push(&mixer->codecbuf, frame_count);
5495 mixer->codecarg.src = auring_headptr(&mixer->codecbuf);
5496 mixer->codecarg.dst = auring_tailptr(&mixer->hwbuf);
5497 mixer->codecarg.count = frame_count;
5498 mixer->codec(&mixer->codecarg);
5499 auring_take(&mixer->codecbuf, mixer->codecarg.count);
5500 }
5501
5502 auring_push(&mixer->hwbuf, frame_count);
5503
5504 TRACE(4, "done mixseq=%d hwbuf=%d/%d/%d%s",
5505 (int)mixer->mixseq,
5506 mixer->hwbuf.head, mixer->hwbuf.used, mixer->hwbuf.capacity,
5507 (mixed == 0) ? " silent" : "");
5508 }
5509
5510 /*
5511 * Do auto gain control.
5512 * Must be called sc_intr_lock held.
5513 */
5514 static void
5515 audio_pmixer_agc(audio_trackmixer_t *mixer, int sample_count)
5516 {
5517 struct audio_softc *sc __unused;
5518 aint2_t val;
5519 aint2_t maxval;
5520 aint2_t minval;
5521 aint2_t over_plus;
5522 aint2_t over_minus;
5523 aint2_t *m;
5524 int newvol;
5525 int i;
5526
5527 sc = mixer->sc;
5528
5529 /* Overflow detection */
5530 maxval = AINT_T_MAX;
5531 minval = AINT_T_MIN;
5532 m = mixer->mixsample;
5533 for (i = 0; i < sample_count; i++) {
5534 val = *m++;
5535 if (val > maxval)
5536 maxval = val;
5537 else if (val < minval)
5538 minval = val;
5539 }
5540
5541 /* Absolute value of overflowed amount */
5542 over_plus = maxval - AINT_T_MAX;
5543 over_minus = AINT_T_MIN - minval;
5544
5545 if (over_plus > 0 || over_minus > 0) {
5546 if (over_plus > over_minus) {
5547 newvol = (int)((aint2_t)AINT_T_MAX * 256 / maxval);
5548 } else {
5549 newvol = (int)((aint2_t)AINT_T_MIN * 256 / minval);
5550 }
5551
5552 /*
5553 * Change the volume only if new one is smaller.
5554 * Reset the timer even if the volume isn't changed.
5555 */
5556 if (newvol <= mixer->volume) {
5557 mixer->volume = newvol;
5558 mixer->voltimer = 0;
5559 #if defined(AUDIO_DEBUG_AGC)
5560 TRACE(1, "auto volume adjust: %d", mixer->volume);
5561 #endif
5562 }
5563 }
5564 }
5565
5566 /*
5567 * Mix one track.
5568 * 'mixed' specifies the number of tracks mixed so far.
5569 * It returns the number of tracks mixed. In other words, it returns
5570 * mixed + 1 if this track is mixed.
5571 */
5572 static int
5573 audio_pmixer_mix_track(audio_trackmixer_t *mixer, audio_track_t *track,
5574 int mixed)
5575 {
5576 int count;
5577 int sample_count;
5578 int remain;
5579 int i;
5580 const aint_t *s;
5581 aint2_t *d;
5582
5583 /* XXX TODO: Is this necessary for now? */
5584 if (mixer->mixseq < track->seq)
5585 return mixed;
5586
5587 count = auring_get_contig_used(&track->outbuf);
5588 count = uimin(count, mixer->frames_per_block);
5589
5590 s = auring_headptr_aint(&track->outbuf);
5591 d = mixer->mixsample;
5592
5593 /*
5594 * Apply track volume with double-sized integer and perform
5595 * additive synthesis.
5596 *
5597 * XXX If you limit the track volume to 1.0 or less (<= 256),
5598 * it would be better to do this in the track conversion stage
5599 * rather than here. However, if you accept the volume to
5600 * be greater than 1.0 (> 256), it's better to do it here.
5601 * Because the operation here is done by double-sized integer.
5602 */
5603 sample_count = count * mixer->mixfmt.channels;
5604 if (mixed == 0) {
5605 /* If this is the first track, assignment can be used. */
5606 #if defined(AUDIO_SUPPORT_TRACK_VOLUME)
5607 if (track->volume != 256) {
5608 for (i = 0; i < sample_count; i++) {
5609 aint2_t v;
5610 v = *s++;
5611 *d++ = AUDIO_SCALEDOWN(v * track->volume, 8)
5612 }
5613 } else
5614 #endif
5615 {
5616 for (i = 0; i < sample_count; i++) {
5617 *d++ = ((aint2_t)*s++);
5618 }
5619 }
5620 /* Fill silence if the first track is not filled. */
5621 for (; i < mixer->frames_per_block * mixer->mixfmt.channels; i++)
5622 *d++ = 0;
5623 } else {
5624 /* If this is the second or later, add it. */
5625 #if defined(AUDIO_SUPPORT_TRACK_VOLUME)
5626 if (track->volume != 256) {
5627 for (i = 0; i < sample_count; i++) {
5628 aint2_t v;
5629 v = *s++;
5630 *d++ += AUDIO_SCALEDOWN(v * track->volume, 8);
5631 }
5632 } else
5633 #endif
5634 {
5635 for (i = 0; i < sample_count; i++) {
5636 *d++ += ((aint2_t)*s++);
5637 }
5638 }
5639 }
5640
5641 auring_take(&track->outbuf, count);
5642 /*
5643 * The counters have to align block even if outbuf is less than
5644 * one block. XXX Is this still necessary?
5645 */
5646 remain = mixer->frames_per_block - count;
5647 if (__predict_false(remain != 0)) {
5648 auring_push(&track->outbuf, remain);
5649 auring_take(&track->outbuf, remain);
5650 }
5651
5652 /*
5653 * Update track sequence.
5654 * mixseq has previous value yet at this point.
5655 */
5656 track->seq = mixer->mixseq + 1;
5657
5658 return mixed + 1;
5659 }
5660
5661 /*
5662 * Output one block from hwbuf to HW.
5663 * Must be called with sc_intr_lock held.
5664 */
5665 static void
5666 audio_pmixer_output(struct audio_softc *sc)
5667 {
5668 audio_trackmixer_t *mixer;
5669 audio_params_t params;
5670 void *start;
5671 void *end;
5672 int blksize;
5673 int error;
5674
5675 mixer = sc->sc_pmixer;
5676 TRACE(4, "pbusy=%d hwbuf=%d/%d/%d",
5677 sc->sc_pbusy,
5678 mixer->hwbuf.head, mixer->hwbuf.used, mixer->hwbuf.capacity);
5679 KASSERTMSG(mixer->hwbuf.used >= mixer->frames_per_block,
5680 "mixer->hwbuf.used=%d mixer->frames_per_block=%d",
5681 mixer->hwbuf.used, mixer->frames_per_block);
5682
5683 blksize = frametobyte(&mixer->hwbuf.fmt, mixer->frames_per_block);
5684
5685 if (sc->hw_if->trigger_output) {
5686 /* trigger (at once) */
5687 if (!sc->sc_pbusy) {
5688 start = mixer->hwbuf.mem;
5689 end = (uint8_t *)start + auring_bytelen(&mixer->hwbuf);
5690 params = format2_to_params(&mixer->hwbuf.fmt);
5691
5692 error = sc->hw_if->trigger_output(sc->hw_hdl,
5693 start, end, blksize, audio_pintr, sc, ¶ms);
5694 if (error) {
5695 audio_printf(sc,
5696 "trigger_output failed: errno=%d\n",
5697 error);
5698 return;
5699 }
5700 }
5701 } else {
5702 /* start (everytime) */
5703 start = auring_headptr(&mixer->hwbuf);
5704
5705 error = sc->hw_if->start_output(sc->hw_hdl,
5706 start, blksize, audio_pintr, sc);
5707 if (error) {
5708 audio_printf(sc,
5709 "start_output failed: errno=%d\n", error);
5710 return;
5711 }
5712 }
5713 }
5714
5715 /*
5716 * This is an interrupt handler for playback.
5717 * It is called with sc_intr_lock held.
5718 *
5719 * It is usually called from hardware interrupt. However, note that
5720 * for some drivers (e.g. uaudio) it is called from software interrupt.
5721 */
5722 static void
5723 audio_pintr(void *arg)
5724 {
5725 struct audio_softc *sc;
5726 audio_trackmixer_t *mixer;
5727
5728 sc = arg;
5729 KASSERT(mutex_owned(sc->sc_intr_lock));
5730
5731 if (sc->sc_dying)
5732 return;
5733 if (sc->sc_pbusy == false) {
5734 #if defined(DIAGNOSTIC)
5735 audio_printf(sc, "DIAGNOSTIC: %s raised stray interrupt\n",
5736 device_xname(sc->hw_dev));
5737 #endif
5738 return;
5739 }
5740
5741 mixer = sc->sc_pmixer;
5742 mixer->hw_complete_counter += mixer->frames_per_block;
5743 mixer->hwseq++;
5744
5745 auring_take(&mixer->hwbuf, mixer->frames_per_block);
5746
5747 TRACE(4,
5748 "HW_INT ++hwseq=%" PRIu64 " cmplcnt=%" PRIu64 " hwbuf=%d/%d/%d",
5749 mixer->hwseq, mixer->hw_complete_counter,
5750 mixer->hwbuf.head, mixer->hwbuf.used, mixer->hwbuf.capacity);
5751
5752 #if defined(AUDIO_HW_SINGLE_BUFFER)
5753 /*
5754 * Create a new block here and output it immediately.
5755 * It makes a latency lower but needs machine power.
5756 */
5757 audio_pmixer_process(sc);
5758 audio_pmixer_output(sc);
5759 #else
5760 /*
5761 * It is called when block N output is done.
5762 * Output immediately block N+1 created by the last interrupt.
5763 * And then create block N+2 for the next interrupt.
5764 * This method makes playback robust even on slower machines.
5765 * Instead the latency is increased by one block.
5766 */
5767
5768 /* At first, output ready block. */
5769 if (mixer->hwbuf.used >= mixer->frames_per_block) {
5770 audio_pmixer_output(sc);
5771 }
5772
5773 bool later = false;
5774
5775 if (mixer->hwbuf.used < mixer->frames_per_block) {
5776 later = true;
5777 }
5778
5779 /* Then, process next block. */
5780 audio_pmixer_process(sc);
5781
5782 if (later) {
5783 audio_pmixer_output(sc);
5784 }
5785 #endif
5786
5787 /*
5788 * When this interrupt is the real hardware interrupt, disabling
5789 * preemption here is not necessary. But some drivers (e.g. uaudio)
5790 * emulate it by software interrupt, so kpreempt_disable is necessary.
5791 */
5792 kpreempt_disable();
5793 softint_schedule(mixer->sih);
5794 kpreempt_enable();
5795 }
5796
5797 /*
5798 * Starts record mixer.
5799 * Must be called only if sc_rbusy is false.
5800 * Must be called with sc_lock && sc_exlock held.
5801 * Must not be called from the interrupt context.
5802 */
5803 static void
5804 audio_rmixer_start(struct audio_softc *sc)
5805 {
5806
5807 KASSERT(mutex_owned(sc->sc_lock));
5808 KASSERT(sc->sc_exlock);
5809 KASSERT(sc->sc_rbusy == false);
5810
5811 mutex_enter(sc->sc_intr_lock);
5812
5813 TRACE(2, "%s", (audiodebug >= 3) ? "begin" : "");
5814 audio_rmixer_input(sc);
5815 sc->sc_rbusy = true;
5816 TRACE(3, "end");
5817
5818 mutex_exit(sc->sc_intr_lock);
5819 }
5820
5821 /*
5822 * When recording with MD filter:
5823 *
5824 * hwbuf [............] NBLKHW blocks ring buffer
5825 * |
5826 * | convert from hw format
5827 * v
5828 * codecbuf [....] 1 block (ring) buffer
5829 * | |
5830 * v v
5831 * track track ...
5832 *
5833 * When recording without MD filter:
5834 *
5835 * hwbuf [............] NBLKHW blocks ring buffer
5836 * | |
5837 * v v
5838 * track track ...
5839 *
5840 * hwbuf: HW encoding, HW precision, HW ch, HW freq.
5841 * codecbuf: slinear_NE, internal precision, HW ch, HW freq.
5842 */
5843
5844 /*
5845 * Distribute a recorded block to all recording tracks.
5846 */
5847 static void
5848 audio_rmixer_process(struct audio_softc *sc)
5849 {
5850 audio_trackmixer_t *mixer;
5851 audio_ring_t *mixersrc;
5852 audio_file_t *f;
5853 aint_t *p;
5854 int count;
5855 int bytes;
5856 int i;
5857
5858 mixer = sc->sc_rmixer;
5859
5860 /*
5861 * count is the number of frames to be retrieved this time.
5862 * count should be one block.
5863 */
5864 count = auring_get_contig_used(&mixer->hwbuf);
5865 count = uimin(count, mixer->frames_per_block);
5866 if (count <= 0) {
5867 TRACE(4, "count %d: too short", count);
5868 return;
5869 }
5870 bytes = frametobyte(&mixer->track_fmt, count);
5871
5872 /* Hardware driver's codec */
5873 if (mixer->codec) {
5874 mixer->codecarg.src = auring_headptr(&mixer->hwbuf);
5875 mixer->codecarg.dst = auring_tailptr(&mixer->codecbuf);
5876 mixer->codecarg.count = count;
5877 mixer->codec(&mixer->codecarg);
5878 auring_take(&mixer->hwbuf, mixer->codecarg.count);
5879 auring_push(&mixer->codecbuf, mixer->codecarg.count);
5880 mixersrc = &mixer->codecbuf;
5881 } else {
5882 mixersrc = &mixer->hwbuf;
5883 }
5884
5885 if (mixer->swap_endian) {
5886 /* inplace conversion */
5887 p = auring_headptr_aint(mixersrc);
5888 for (i = 0; i < count * mixer->track_fmt.channels; i++, p++) {
5889 *p = bswap16(*p);
5890 }
5891 }
5892
5893 /* Distribute to all tracks. */
5894 SLIST_FOREACH(f, &sc->sc_files, entry) {
5895 audio_track_t *track = f->rtrack;
5896 audio_ring_t *input;
5897
5898 if (track == NULL)
5899 continue;
5900
5901 if (track->is_pause) {
5902 TRACET(4, track, "skip; paused");
5903 continue;
5904 }
5905
5906 if (audio_track_lock_tryenter(track) == false) {
5907 TRACET(4, track, "skip; in use");
5908 continue;
5909 }
5910
5911 /* If the track buffer is full, discard the oldest one? */
5912 input = track->input;
5913 if (input->capacity - input->used < mixer->frames_per_block) {
5914 int drops = mixer->frames_per_block -
5915 (input->capacity - input->used);
5916 track->dropframes += drops;
5917 TRACET(4, track, "drop %d frames: inp=%d/%d/%d",
5918 drops,
5919 input->head, input->used, input->capacity);
5920 auring_take(input, drops);
5921 }
5922
5923 KASSERTMSG(auring_tail(input) % mixer->frames_per_block == 0,
5924 "inputtail=%d mixer->frames_per_block=%d",
5925 auring_tail(input), mixer->frames_per_block);
5926 memcpy(auring_tailptr_aint(input),
5927 auring_headptr_aint(mixersrc),
5928 bytes);
5929 auring_push(input, count);
5930
5931 /* XXX sequence counter? */
5932
5933 audio_track_lock_exit(track);
5934 }
5935
5936 auring_take(mixersrc, count);
5937 }
5938
5939 /*
5940 * Input one block from HW to hwbuf.
5941 * Must be called with sc_intr_lock held.
5942 */
5943 static void
5944 audio_rmixer_input(struct audio_softc *sc)
5945 {
5946 audio_trackmixer_t *mixer;
5947 audio_params_t params;
5948 void *start;
5949 void *end;
5950 int blksize;
5951 int error;
5952
5953 mixer = sc->sc_rmixer;
5954 blksize = frametobyte(&mixer->hwbuf.fmt, mixer->frames_per_block);
5955
5956 if (sc->hw_if->trigger_input) {
5957 /* trigger (at once) */
5958 if (!sc->sc_rbusy) {
5959 start = mixer->hwbuf.mem;
5960 end = (uint8_t *)start + auring_bytelen(&mixer->hwbuf);
5961 params = format2_to_params(&mixer->hwbuf.fmt);
5962
5963 error = sc->hw_if->trigger_input(sc->hw_hdl,
5964 start, end, blksize, audio_rintr, sc, ¶ms);
5965 if (error) {
5966 audio_printf(sc,
5967 "trigger_input failed: errno=%d\n",
5968 error);
5969 return;
5970 }
5971 }
5972 } else {
5973 /* start (everytime) */
5974 start = auring_tailptr(&mixer->hwbuf);
5975
5976 error = sc->hw_if->start_input(sc->hw_hdl,
5977 start, blksize, audio_rintr, sc);
5978 if (error) {
5979 audio_printf(sc,
5980 "start_input failed: errno=%d\n", error);
5981 return;
5982 }
5983 }
5984 }
5985
5986 /*
5987 * This is an interrupt handler for recording.
5988 * It is called with sc_intr_lock.
5989 *
5990 * It is usually called from hardware interrupt. However, note that
5991 * for some drivers (e.g. uaudio) it is called from software interrupt.
5992 */
5993 static void
5994 audio_rintr(void *arg)
5995 {
5996 struct audio_softc *sc;
5997 audio_trackmixer_t *mixer;
5998
5999 sc = arg;
6000 KASSERT(mutex_owned(sc->sc_intr_lock));
6001
6002 if (sc->sc_dying)
6003 return;
6004 if (sc->sc_rbusy == false) {
6005 #if defined(DIAGNOSTIC)
6006 audio_printf(sc, "DIAGNOSTIC: %s raised stray interrupt\n",
6007 device_xname(sc->hw_dev));
6008 #endif
6009 return;
6010 }
6011
6012 mixer = sc->sc_rmixer;
6013 mixer->hw_complete_counter += mixer->frames_per_block;
6014 mixer->hwseq++;
6015
6016 auring_push(&mixer->hwbuf, mixer->frames_per_block);
6017
6018 TRACE(4,
6019 "HW_INT ++hwseq=%" PRIu64 " cmplcnt=%" PRIu64 " hwbuf=%d/%d/%d",
6020 mixer->hwseq, mixer->hw_complete_counter,
6021 mixer->hwbuf.head, mixer->hwbuf.used, mixer->hwbuf.capacity);
6022
6023 /* Distrubute recorded block */
6024 audio_rmixer_process(sc);
6025
6026 /* Request next block */
6027 audio_rmixer_input(sc);
6028
6029 /*
6030 * When this interrupt is the real hardware interrupt, disabling
6031 * preemption here is not necessary. But some drivers (e.g. uaudio)
6032 * emulate it by software interrupt, so kpreempt_disable is necessary.
6033 */
6034 kpreempt_disable();
6035 softint_schedule(mixer->sih);
6036 kpreempt_enable();
6037 }
6038
6039 /*
6040 * Halts playback mixer.
6041 * This function also clears related parameters, so call this function
6042 * instead of calling halt_output directly.
6043 * Must be called only if sc_pbusy is true.
6044 * Must be called with sc_lock && sc_exlock held.
6045 */
6046 static int
6047 audio_pmixer_halt(struct audio_softc *sc)
6048 {
6049 int error;
6050
6051 TRACE(2, "called");
6052 KASSERT(mutex_owned(sc->sc_lock));
6053 KASSERT(sc->sc_exlock);
6054
6055 mutex_enter(sc->sc_intr_lock);
6056 error = sc->hw_if->halt_output(sc->hw_hdl);
6057
6058 /* Halts anyway even if some error has occurred. */
6059 sc->sc_pbusy = false;
6060 sc->sc_pmixer->hwbuf.head = 0;
6061 sc->sc_pmixer->hwbuf.used = 0;
6062 sc->sc_pmixer->mixseq = 0;
6063 sc->sc_pmixer->hwseq = 0;
6064 mutex_exit(sc->sc_intr_lock);
6065
6066 return error;
6067 }
6068
6069 /*
6070 * Halts recording mixer.
6071 * This function also clears related parameters, so call this function
6072 * instead of calling halt_input directly.
6073 * Must be called only if sc_rbusy is true.
6074 * Must be called with sc_lock && sc_exlock held.
6075 */
6076 static int
6077 audio_rmixer_halt(struct audio_softc *sc)
6078 {
6079 int error;
6080
6081 TRACE(2, "called");
6082 KASSERT(mutex_owned(sc->sc_lock));
6083 KASSERT(sc->sc_exlock);
6084
6085 mutex_enter(sc->sc_intr_lock);
6086 error = sc->hw_if->halt_input(sc->hw_hdl);
6087
6088 /* Halts anyway even if some error has occurred. */
6089 sc->sc_rbusy = false;
6090 sc->sc_rmixer->hwbuf.head = 0;
6091 sc->sc_rmixer->hwbuf.used = 0;
6092 sc->sc_rmixer->mixseq = 0;
6093 sc->sc_rmixer->hwseq = 0;
6094 mutex_exit(sc->sc_intr_lock);
6095
6096 return error;
6097 }
6098
6099 /*
6100 * Flush this track.
6101 * Halts all operations, clears all buffers, reset error counters.
6102 * XXX I'm not sure...
6103 */
6104 static void
6105 audio_track_clear(struct audio_softc *sc, audio_track_t *track)
6106 {
6107
6108 KASSERT(track);
6109 TRACET(3, track, "clear");
6110
6111 audio_track_lock_enter(track);
6112
6113 track->usrbuf.used = 0;
6114 /* Clear all internal parameters. */
6115 if (track->codec.filter) {
6116 track->codec.srcbuf.used = 0;
6117 track->codec.srcbuf.head = 0;
6118 }
6119 if (track->chvol.filter) {
6120 track->chvol.srcbuf.used = 0;
6121 track->chvol.srcbuf.head = 0;
6122 }
6123 if (track->chmix.filter) {
6124 track->chmix.srcbuf.used = 0;
6125 track->chmix.srcbuf.head = 0;
6126 }
6127 if (track->freq.filter) {
6128 track->freq.srcbuf.used = 0;
6129 track->freq.srcbuf.head = 0;
6130 if (track->freq_step < 65536)
6131 track->freq_current = 65536;
6132 else
6133 track->freq_current = 0;
6134 memset(track->freq_prev, 0, sizeof(track->freq_prev));
6135 memset(track->freq_curr, 0, sizeof(track->freq_curr));
6136 }
6137 /* Clear buffer, then operation halts naturally. */
6138 track->outbuf.used = 0;
6139
6140 /* Clear counters. */
6141 track->dropframes = 0;
6142
6143 audio_track_lock_exit(track);
6144 }
6145
6146 /*
6147 * Drain the track.
6148 * track must be present and for playback.
6149 * If successful, it returns 0. Otherwise returns errno.
6150 * Must be called with sc_lock held.
6151 */
6152 static int
6153 audio_track_drain(struct audio_softc *sc, audio_track_t *track)
6154 {
6155 audio_trackmixer_t *mixer;
6156 int done;
6157 int error;
6158
6159 KASSERT(track);
6160 TRACET(3, track, "start");
6161 mixer = track->mixer;
6162 KASSERT(mutex_owned(sc->sc_lock));
6163
6164 /* Ignore them if pause. */
6165 if (track->is_pause) {
6166 TRACET(3, track, "pause -> clear");
6167 track->pstate = AUDIO_STATE_CLEAR;
6168 }
6169 /* Terminate early here if there is no data in the track. */
6170 if (track->pstate == AUDIO_STATE_CLEAR) {
6171 TRACET(3, track, "no need to drain");
6172 return 0;
6173 }
6174 track->pstate = AUDIO_STATE_DRAINING;
6175
6176 for (;;) {
6177 /* I want to display it before condition evaluation. */
6178 TRACET(3, track, "pid=%d.%d trkseq=%d hwseq=%d out=%d/%d/%d",
6179 (int)curproc->p_pid, (int)curlwp->l_lid,
6180 (int)track->seq, (int)mixer->hwseq,
6181 track->outbuf.head, track->outbuf.used,
6182 track->outbuf.capacity);
6183
6184 /* Condition to terminate */
6185 audio_track_lock_enter(track);
6186 done = (track->usrbuf.used < frametobyte(&track->inputfmt, 1) &&
6187 track->outbuf.used == 0 &&
6188 track->seq <= mixer->hwseq);
6189 audio_track_lock_exit(track);
6190 if (done)
6191 break;
6192
6193 TRACET(3, track, "sleep");
6194 error = audio_track_waitio(sc, track);
6195 if (error)
6196 return error;
6197
6198 /* XXX call audio_track_play here ? */
6199 }
6200
6201 track->pstate = AUDIO_STATE_CLEAR;
6202 TRACET(3, track, "done trk_inp=%d trk_out=%d",
6203 (int)track->inputcounter, (int)track->outputcounter);
6204 return 0;
6205 }
6206
6207 /*
6208 * Send signal to process.
6209 * This is intended to be called only from audio_softintr_{rd,wr}.
6210 * Must be called without sc_intr_lock held.
6211 */
6212 static inline void
6213 audio_psignal(struct audio_softc *sc, pid_t pid, int signum)
6214 {
6215 proc_t *p;
6216
6217 KASSERT(pid != 0);
6218
6219 /*
6220 * psignal() must be called without spin lock held.
6221 */
6222
6223 mutex_enter(&proc_lock);
6224 p = proc_find(pid);
6225 if (p)
6226 psignal(p, signum);
6227 mutex_exit(&proc_lock);
6228 }
6229
6230 /*
6231 * This is software interrupt handler for record.
6232 * It is called from recording hardware interrupt everytime.
6233 * It does:
6234 * - Deliver SIGIO for all async processes.
6235 * - Notify to audio_read() that data has arrived.
6236 * - selnotify() for select/poll-ing processes.
6237 */
6238 /*
6239 * XXX If a process issues FIOASYNC between hardware interrupt and
6240 * software interrupt, (stray) SIGIO will be sent to the process
6241 * despite the fact that it has not receive recorded data yet.
6242 */
6243 static void
6244 audio_softintr_rd(void *cookie)
6245 {
6246 struct audio_softc *sc = cookie;
6247 audio_file_t *f;
6248 pid_t pid;
6249
6250 mutex_enter(sc->sc_lock);
6251
6252 SLIST_FOREACH(f, &sc->sc_files, entry) {
6253 audio_track_t *track = f->rtrack;
6254
6255 if (track == NULL)
6256 continue;
6257
6258 TRACET(4, track, "broadcast; inp=%d/%d/%d",
6259 track->input->head,
6260 track->input->used,
6261 track->input->capacity);
6262
6263 pid = f->async_audio;
6264 if (pid != 0) {
6265 TRACEF(4, f, "sending SIGIO %d", pid);
6266 audio_psignal(sc, pid, SIGIO);
6267 }
6268 }
6269
6270 /* Notify that data has arrived. */
6271 selnotify(&sc->sc_rsel, 0, NOTE_SUBMIT);
6272 cv_broadcast(&sc->sc_rmixer->outcv);
6273
6274 mutex_exit(sc->sc_lock);
6275 }
6276
6277 /*
6278 * This is software interrupt handler for playback.
6279 * It is called from playback hardware interrupt everytime.
6280 * It does:
6281 * - Deliver SIGIO for all async and writable (used < lowat) processes.
6282 * - Notify to audio_write() that outbuf block available.
6283 * - selnotify() for select/poll-ing processes if there are any writable
6284 * (used < lowat) processes. Checking each descriptor will be done by
6285 * filt_audiowrite_event().
6286 */
6287 static void
6288 audio_softintr_wr(void *cookie)
6289 {
6290 struct audio_softc *sc = cookie;
6291 audio_file_t *f;
6292 bool found;
6293 pid_t pid;
6294
6295 TRACE(4, "called");
6296 found = false;
6297
6298 mutex_enter(sc->sc_lock);
6299
6300 SLIST_FOREACH(f, &sc->sc_files, entry) {
6301 audio_track_t *track = f->ptrack;
6302
6303 if (track == NULL)
6304 continue;
6305
6306 TRACET(4, track, "broadcast; trkseq=%d out=%d/%d/%d",
6307 (int)track->seq,
6308 track->outbuf.head,
6309 track->outbuf.used,
6310 track->outbuf.capacity);
6311
6312 /*
6313 * Send a signal if the process is async mode and
6314 * used is lower than lowat.
6315 */
6316 if (track->usrbuf.used <= track->usrbuf_usedlow &&
6317 !track->is_pause) {
6318 /* For selnotify */
6319 found = true;
6320 /* For SIGIO */
6321 pid = f->async_audio;
6322 if (pid != 0) {
6323 TRACEF(4, f, "sending SIGIO %d", pid);
6324 audio_psignal(sc, pid, SIGIO);
6325 }
6326 }
6327 }
6328
6329 /*
6330 * Notify for select/poll when someone become writable.
6331 * It needs sc_lock (and not sc_intr_lock).
6332 */
6333 if (found) {
6334 TRACE(4, "selnotify");
6335 selnotify(&sc->sc_wsel, 0, NOTE_SUBMIT);
6336 }
6337
6338 /* Notify to audio_write() that outbuf available. */
6339 cv_broadcast(&sc->sc_pmixer->outcv);
6340
6341 mutex_exit(sc->sc_lock);
6342 }
6343
6344 /*
6345 * Check (and convert) the format *p came from userland.
6346 * If successful, it writes back the converted format to *p if necessary and
6347 * returns 0. Otherwise returns errno (*p may be changed even in this case).
6348 */
6349 static int
6350 audio_check_params(audio_format2_t *p)
6351 {
6352
6353 /*
6354 * Convert obsolete AUDIO_ENCODING_PCM encodings.
6355 *
6356 * AUDIO_ENCODING_PCM16 == AUDIO_ENCODING_LINEAR
6357 * So, it's always signed, as in SunOS.
6358 *
6359 * AUDIO_ENCODING_PCM8 == AUDIO_ENCODING_LINEAR8
6360 * So, it's always unsigned, as in SunOS.
6361 */
6362 if (p->encoding == AUDIO_ENCODING_PCM16) {
6363 p->encoding = AUDIO_ENCODING_SLINEAR;
6364 } else if (p->encoding == AUDIO_ENCODING_PCM8) {
6365 if (p->precision == 8)
6366 p->encoding = AUDIO_ENCODING_ULINEAR;
6367 else
6368 return EINVAL;
6369 }
6370
6371 /*
6372 * Convert obsoleted AUDIO_ENCODING_[SU]LINEAR without endianness
6373 * suffix.
6374 */
6375 if (p->encoding == AUDIO_ENCODING_SLINEAR)
6376 p->encoding = AUDIO_ENCODING_SLINEAR_NE;
6377 if (p->encoding == AUDIO_ENCODING_ULINEAR)
6378 p->encoding = AUDIO_ENCODING_ULINEAR_NE;
6379
6380 switch (p->encoding) {
6381 case AUDIO_ENCODING_ULAW:
6382 case AUDIO_ENCODING_ALAW:
6383 if (p->precision != 8)
6384 return EINVAL;
6385 break;
6386 case AUDIO_ENCODING_ADPCM:
6387 if (p->precision != 4 && p->precision != 8)
6388 return EINVAL;
6389 break;
6390 case AUDIO_ENCODING_SLINEAR_LE:
6391 case AUDIO_ENCODING_SLINEAR_BE:
6392 case AUDIO_ENCODING_ULINEAR_LE:
6393 case AUDIO_ENCODING_ULINEAR_BE:
6394 if (p->precision != 8 && p->precision != 16 &&
6395 p->precision != 24 && p->precision != 32)
6396 return EINVAL;
6397
6398 /* 8bit format does not have endianness. */
6399 if (p->precision == 8) {
6400 if (p->encoding == AUDIO_ENCODING_SLINEAR_OE)
6401 p->encoding = AUDIO_ENCODING_SLINEAR_NE;
6402 if (p->encoding == AUDIO_ENCODING_ULINEAR_OE)
6403 p->encoding = AUDIO_ENCODING_ULINEAR_NE;
6404 }
6405
6406 if (p->precision > p->stride)
6407 return EINVAL;
6408 break;
6409 case AUDIO_ENCODING_MPEG_L1_STREAM:
6410 case AUDIO_ENCODING_MPEG_L1_PACKETS:
6411 case AUDIO_ENCODING_MPEG_L1_SYSTEM:
6412 case AUDIO_ENCODING_MPEG_L2_STREAM:
6413 case AUDIO_ENCODING_MPEG_L2_PACKETS:
6414 case AUDIO_ENCODING_MPEG_L2_SYSTEM:
6415 case AUDIO_ENCODING_AC3:
6416 break;
6417 default:
6418 return EINVAL;
6419 }
6420
6421 /* sanity check # of channels*/
6422 if (p->channels < 1 || p->channels > AUDIO_MAX_CHANNELS)
6423 return EINVAL;
6424
6425 return 0;
6426 }
6427
6428 /*
6429 * Initialize playback and record mixers.
6430 * mode (AUMODE_{PLAY,RECORD}) indicates the mixer to be initialized.
6431 * phwfmt and rhwfmt indicate the hardware format. pfil and rfil indicate
6432 * the filter registration information. These four must not be NULL.
6433 * If successful returns 0. Otherwise returns errno.
6434 * Must be called with sc_exlock held and without sc_lock held.
6435 * Must not be called if there are any tracks.
6436 * Caller should check that the initialization succeed by whether
6437 * sc_[pr]mixer is not NULL.
6438 */
6439 static int
6440 audio_mixers_init(struct audio_softc *sc, int mode,
6441 const audio_format2_t *phwfmt, const audio_format2_t *rhwfmt,
6442 const audio_filter_reg_t *pfil, const audio_filter_reg_t *rfil)
6443 {
6444 int error;
6445
6446 KASSERT(phwfmt != NULL);
6447 KASSERT(rhwfmt != NULL);
6448 KASSERT(pfil != NULL);
6449 KASSERT(rfil != NULL);
6450 KASSERT(sc->sc_exlock);
6451
6452 if ((mode & AUMODE_PLAY)) {
6453 if (sc->sc_pmixer == NULL) {
6454 sc->sc_pmixer = kmem_zalloc(sizeof(*sc->sc_pmixer),
6455 KM_SLEEP);
6456 } else {
6457 /* destroy() doesn't free memory. */
6458 audio_mixer_destroy(sc, sc->sc_pmixer);
6459 memset(sc->sc_pmixer, 0, sizeof(*sc->sc_pmixer));
6460 }
6461 error = audio_mixer_init(sc, AUMODE_PLAY, phwfmt, pfil);
6462 if (error) {
6463 /* audio_mixer_init already displayed error code */
6464 audio_printf(sc, "configuring playback mode failed\n");
6465 kmem_free(sc->sc_pmixer, sizeof(*sc->sc_pmixer));
6466 sc->sc_pmixer = NULL;
6467 return error;
6468 }
6469 }
6470 if ((mode & AUMODE_RECORD)) {
6471 if (sc->sc_rmixer == NULL) {
6472 sc->sc_rmixer = kmem_zalloc(sizeof(*sc->sc_rmixer),
6473 KM_SLEEP);
6474 } else {
6475 /* destroy() doesn't free memory. */
6476 audio_mixer_destroy(sc, sc->sc_rmixer);
6477 memset(sc->sc_rmixer, 0, sizeof(*sc->sc_rmixer));
6478 }
6479 error = audio_mixer_init(sc, AUMODE_RECORD, rhwfmt, rfil);
6480 if (error) {
6481 /* audio_mixer_init already displayed error code */
6482 audio_printf(sc, "configuring record mode failed\n");
6483 kmem_free(sc->sc_rmixer, sizeof(*sc->sc_rmixer));
6484 sc->sc_rmixer = NULL;
6485 return error;
6486 }
6487 }
6488
6489 return 0;
6490 }
6491
6492 /*
6493 * Select a frequency.
6494 * Prioritize 48kHz and 44.1kHz. Otherwise choose the highest one.
6495 * XXX Better algorithm?
6496 */
6497 static int
6498 audio_select_freq(const struct audio_format *fmt)
6499 {
6500 int freq;
6501 int high;
6502 int low;
6503 int j;
6504
6505 if (fmt->frequency_type == 0) {
6506 low = fmt->frequency[0];
6507 high = fmt->frequency[1];
6508 freq = 48000;
6509 if (low <= freq && freq <= high) {
6510 return freq;
6511 }
6512 freq = 44100;
6513 if (low <= freq && freq <= high) {
6514 return freq;
6515 }
6516 return high;
6517 } else {
6518 for (j = 0; j < fmt->frequency_type; j++) {
6519 if (fmt->frequency[j] == 48000) {
6520 return fmt->frequency[j];
6521 }
6522 }
6523 high = 0;
6524 for (j = 0; j < fmt->frequency_type; j++) {
6525 if (fmt->frequency[j] == 44100) {
6526 return fmt->frequency[j];
6527 }
6528 if (fmt->frequency[j] > high) {
6529 high = fmt->frequency[j];
6530 }
6531 }
6532 return high;
6533 }
6534 }
6535
6536 /*
6537 * Choose the most preferred hardware format.
6538 * If successful, it will store the chosen format into *cand and return 0.
6539 * Otherwise, return errno.
6540 * Must be called without sc_lock held.
6541 */
6542 static int
6543 audio_hw_probe(struct audio_softc *sc, audio_format2_t *cand, int mode)
6544 {
6545 audio_format_query_t query;
6546 int cand_score;
6547 int score;
6548 int i;
6549 int error;
6550
6551 /*
6552 * Score each formats and choose the highest one.
6553 *
6554 * +---- priority(0-3)
6555 * |+--- encoding/precision
6556 * ||+-- channels
6557 * score = 0x000000PEC
6558 */
6559
6560 cand_score = 0;
6561 for (i = 0; ; i++) {
6562 memset(&query, 0, sizeof(query));
6563 query.index = i;
6564
6565 mutex_enter(sc->sc_lock);
6566 error = sc->hw_if->query_format(sc->hw_hdl, &query);
6567 mutex_exit(sc->sc_lock);
6568 if (error == EINVAL)
6569 break;
6570 if (error)
6571 return error;
6572
6573 #if defined(AUDIO_DEBUG)
6574 DPRINTF(1, "fmt[%d] %c%c pri=%d %s,%d/%dbit,%dch,", i,
6575 (query.fmt.mode & AUMODE_PLAY) ? 'P' : '-',
6576 (query.fmt.mode & AUMODE_RECORD) ? 'R' : '-',
6577 query.fmt.priority,
6578 audio_encoding_name(query.fmt.encoding),
6579 query.fmt.validbits,
6580 query.fmt.precision,
6581 query.fmt.channels);
6582 if (query.fmt.frequency_type == 0) {
6583 DPRINTF(1, "{%d-%d",
6584 query.fmt.frequency[0], query.fmt.frequency[1]);
6585 } else {
6586 int j;
6587 for (j = 0; j < query.fmt.frequency_type; j++) {
6588 DPRINTF(1, "%c%d",
6589 (j == 0) ? '{' : ',',
6590 query.fmt.frequency[j]);
6591 }
6592 }
6593 DPRINTF(1, "}\n");
6594 #endif
6595
6596 if ((query.fmt.mode & mode) == 0) {
6597 DPRINTF(1, "fmt[%d] skip; mode not match %d\n", i,
6598 mode);
6599 continue;
6600 }
6601
6602 if (query.fmt.priority < 0) {
6603 DPRINTF(1, "fmt[%d] skip; unsupported encoding\n", i);
6604 continue;
6605 }
6606
6607 /* Score */
6608 score = (query.fmt.priority & 3) * 0x100;
6609 if (query.fmt.encoding == AUDIO_ENCODING_SLINEAR_NE &&
6610 query.fmt.validbits == AUDIO_INTERNAL_BITS &&
6611 query.fmt.precision == AUDIO_INTERNAL_BITS) {
6612 score += 0x20;
6613 } else if (query.fmt.encoding == AUDIO_ENCODING_SLINEAR_OE &&
6614 query.fmt.validbits == AUDIO_INTERNAL_BITS &&
6615 query.fmt.precision == AUDIO_INTERNAL_BITS) {
6616 score += 0x10;
6617 }
6618
6619 /* Do not prefer surround formats */
6620 if (query.fmt.channels <= 2)
6621 score += query.fmt.channels;
6622
6623 if (score < cand_score) {
6624 DPRINTF(1, "fmt[%d] skip; score 0x%x < 0x%x\n", i,
6625 score, cand_score);
6626 continue;
6627 }
6628
6629 /* Update candidate */
6630 cand_score = score;
6631 cand->encoding = query.fmt.encoding;
6632 cand->precision = query.fmt.validbits;
6633 cand->stride = query.fmt.precision;
6634 cand->channels = query.fmt.channels;
6635 cand->sample_rate = audio_select_freq(&query.fmt);
6636 DPRINTF(1, "fmt[%d] candidate (score=0x%x)"
6637 " pri=%d %s,%d/%d,%dch,%dHz\n", i,
6638 cand_score, query.fmt.priority,
6639 audio_encoding_name(query.fmt.encoding),
6640 cand->precision, cand->stride,
6641 cand->channels, cand->sample_rate);
6642 }
6643
6644 if (cand_score == 0) {
6645 DPRINTF(1, "%s no fmt\n", __func__);
6646 return ENXIO;
6647 }
6648 DPRINTF(1, "%s selected: %s,%d/%d,%dch,%dHz\n", __func__,
6649 audio_encoding_name(cand->encoding),
6650 cand->precision, cand->stride, cand->channels, cand->sample_rate);
6651 return 0;
6652 }
6653
6654 /*
6655 * Validate fmt with query_format.
6656 * If fmt is included in the result of query_format, returns 0.
6657 * Otherwise returns EINVAL.
6658 * Must be called without sc_lock held.
6659 */
6660 static int
6661 audio_hw_validate_format(struct audio_softc *sc, int mode,
6662 const audio_format2_t *fmt)
6663 {
6664 audio_format_query_t query;
6665 struct audio_format *q;
6666 int index;
6667 int error;
6668 int j;
6669
6670 for (index = 0; ; index++) {
6671 query.index = index;
6672 mutex_enter(sc->sc_lock);
6673 error = sc->hw_if->query_format(sc->hw_hdl, &query);
6674 mutex_exit(sc->sc_lock);
6675 if (error == EINVAL)
6676 break;
6677 if (error)
6678 return error;
6679
6680 q = &query.fmt;
6681 /*
6682 * Note that fmt is audio_format2_t (precision/stride) but
6683 * q is audio_format_t (validbits/precision).
6684 */
6685 if ((q->mode & mode) == 0) {
6686 continue;
6687 }
6688 if (fmt->encoding != q->encoding) {
6689 continue;
6690 }
6691 if (fmt->precision != q->validbits) {
6692 continue;
6693 }
6694 if (fmt->stride != q->precision) {
6695 continue;
6696 }
6697 if (fmt->channels != q->channels) {
6698 continue;
6699 }
6700 if (q->frequency_type == 0) {
6701 if (fmt->sample_rate < q->frequency[0] ||
6702 fmt->sample_rate > q->frequency[1]) {
6703 continue;
6704 }
6705 } else {
6706 for (j = 0; j < q->frequency_type; j++) {
6707 if (fmt->sample_rate == q->frequency[j])
6708 break;
6709 }
6710 if (j == query.fmt.frequency_type) {
6711 continue;
6712 }
6713 }
6714
6715 /* Matched. */
6716 return 0;
6717 }
6718
6719 return EINVAL;
6720 }
6721
6722 /*
6723 * Set track mixer's format depending on ai->mode.
6724 * If AUMODE_PLAY is set in ai->mode, it set up the playback mixer
6725 * with ai.play.*.
6726 * If AUMODE_RECORD is set in ai->mode, it set up the recording mixer
6727 * with ai.record.*.
6728 * All other fields in ai are ignored.
6729 * If successful returns 0. Otherwise returns errno.
6730 * This function does not roll back even if it fails.
6731 * Must be called with sc_exlock held and without sc_lock held.
6732 */
6733 static int
6734 audio_mixers_set_format(struct audio_softc *sc, const struct audio_info *ai)
6735 {
6736 audio_format2_t phwfmt;
6737 audio_format2_t rhwfmt;
6738 audio_filter_reg_t pfil;
6739 audio_filter_reg_t rfil;
6740 int mode;
6741 int error;
6742
6743 KASSERT(sc->sc_exlock);
6744
6745 /*
6746 * Even when setting either one of playback and recording,
6747 * both must be halted.
6748 */
6749 if (sc->sc_popens + sc->sc_ropens > 0)
6750 return EBUSY;
6751
6752 if (!SPECIFIED(ai->mode) || ai->mode == 0)
6753 return ENOTTY;
6754
6755 mode = ai->mode;
6756 if ((mode & AUMODE_PLAY)) {
6757 phwfmt.encoding = ai->play.encoding;
6758 phwfmt.precision = ai->play.precision;
6759 phwfmt.stride = ai->play.precision;
6760 phwfmt.channels = ai->play.channels;
6761 phwfmt.sample_rate = ai->play.sample_rate;
6762 }
6763 if ((mode & AUMODE_RECORD)) {
6764 rhwfmt.encoding = ai->record.encoding;
6765 rhwfmt.precision = ai->record.precision;
6766 rhwfmt.stride = ai->record.precision;
6767 rhwfmt.channels = ai->record.channels;
6768 rhwfmt.sample_rate = ai->record.sample_rate;
6769 }
6770
6771 /* On non-independent devices, use the same format for both. */
6772 if ((sc->sc_props & AUDIO_PROP_INDEPENDENT) == 0) {
6773 if (mode == AUMODE_RECORD) {
6774 phwfmt = rhwfmt;
6775 } else {
6776 rhwfmt = phwfmt;
6777 }
6778 mode = AUMODE_PLAY | AUMODE_RECORD;
6779 }
6780
6781 /* Then, unset the direction not exist on the hardware. */
6782 if ((sc->sc_props & AUDIO_PROP_PLAYBACK) == 0)
6783 mode &= ~AUMODE_PLAY;
6784 if ((sc->sc_props & AUDIO_PROP_CAPTURE) == 0)
6785 mode &= ~AUMODE_RECORD;
6786
6787 /* debug */
6788 if ((mode & AUMODE_PLAY)) {
6789 TRACE(1, "play=%s/%d/%d/%dch/%dHz",
6790 audio_encoding_name(phwfmt.encoding),
6791 phwfmt.precision,
6792 phwfmt.stride,
6793 phwfmt.channels,
6794 phwfmt.sample_rate);
6795 }
6796 if ((mode & AUMODE_RECORD)) {
6797 TRACE(1, "rec =%s/%d/%d/%dch/%dHz",
6798 audio_encoding_name(rhwfmt.encoding),
6799 rhwfmt.precision,
6800 rhwfmt.stride,
6801 rhwfmt.channels,
6802 rhwfmt.sample_rate);
6803 }
6804
6805 /* Check the format */
6806 if ((mode & AUMODE_PLAY)) {
6807 if (audio_hw_validate_format(sc, AUMODE_PLAY, &phwfmt)) {
6808 TRACE(1, "invalid format");
6809 return EINVAL;
6810 }
6811 }
6812 if ((mode & AUMODE_RECORD)) {
6813 if (audio_hw_validate_format(sc, AUMODE_RECORD, &rhwfmt)) {
6814 TRACE(1, "invalid format");
6815 return EINVAL;
6816 }
6817 }
6818
6819 /* Configure the mixers. */
6820 memset(&pfil, 0, sizeof(pfil));
6821 memset(&rfil, 0, sizeof(rfil));
6822 error = audio_hw_set_format(sc, mode, &phwfmt, &rhwfmt, &pfil, &rfil);
6823 if (error)
6824 return error;
6825
6826 error = audio_mixers_init(sc, mode, &phwfmt, &rhwfmt, &pfil, &rfil);
6827 if (error)
6828 return error;
6829
6830 /*
6831 * Reinitialize the sticky parameters for /dev/sound.
6832 * If the number of the hardware channels becomes less than the number
6833 * of channels that sticky parameters remember, subsequent /dev/sound
6834 * open will fail. To prevent this, reinitialize the sticky
6835 * parameters whenever the hardware format is changed.
6836 */
6837 sc->sc_sound_pparams = params_to_format2(&audio_default);
6838 sc->sc_sound_rparams = params_to_format2(&audio_default);
6839 sc->sc_sound_ppause = false;
6840 sc->sc_sound_rpause = false;
6841
6842 return 0;
6843 }
6844
6845 /*
6846 * Store current mixers format into *ai.
6847 * Must be called with sc_exlock held.
6848 */
6849 static void
6850 audio_mixers_get_format(struct audio_softc *sc, struct audio_info *ai)
6851 {
6852
6853 KASSERT(sc->sc_exlock);
6854
6855 /*
6856 * There is no stride information in audio_info but it doesn't matter.
6857 * trackmixer always treats stride and precision as the same.
6858 */
6859 AUDIO_INITINFO(ai);
6860 ai->mode = 0;
6861 if (sc->sc_pmixer) {
6862 audio_format2_t *fmt = &sc->sc_pmixer->track_fmt;
6863 ai->play.encoding = fmt->encoding;
6864 ai->play.precision = fmt->precision;
6865 ai->play.channels = fmt->channels;
6866 ai->play.sample_rate = fmt->sample_rate;
6867 ai->mode |= AUMODE_PLAY;
6868 }
6869 if (sc->sc_rmixer) {
6870 audio_format2_t *fmt = &sc->sc_rmixer->track_fmt;
6871 ai->record.encoding = fmt->encoding;
6872 ai->record.precision = fmt->precision;
6873 ai->record.channels = fmt->channels;
6874 ai->record.sample_rate = fmt->sample_rate;
6875 ai->mode |= AUMODE_RECORD;
6876 }
6877 }
6878
6879 /*
6880 * audio_info details:
6881 *
6882 * ai.{play,record}.sample_rate (R/W)
6883 * ai.{play,record}.encoding (R/W)
6884 * ai.{play,record}.precision (R/W)
6885 * ai.{play,record}.channels (R/W)
6886 * These specify the playback or recording format.
6887 * Ignore members within an inactive track.
6888 *
6889 * ai.mode (R/W)
6890 * It specifies the playback or recording mode, AUMODE_*.
6891 * Currently, a mode change operation by ai.mode after opening is
6892 * prohibited. In addition, AUMODE_PLAY_ALL no longer makes sense.
6893 * However, it's possible to get or to set for backward compatibility.
6894 *
6895 * ai.{hiwat,lowat} (R/W)
6896 * These specify the high water mark and low water mark for playback
6897 * track. The unit is block.
6898 *
6899 * ai.{play,record}.gain (R/W)
6900 * It specifies the HW mixer volume in 0-255.
6901 * It is historical reason that the gain is connected to HW mixer.
6902 *
6903 * ai.{play,record}.balance (R/W)
6904 * It specifies the left-right balance of HW mixer in 0-64.
6905 * 32 means the center.
6906 * It is historical reason that the balance is connected to HW mixer.
6907 *
6908 * ai.{play,record}.port (R/W)
6909 * It specifies the input/output port of HW mixer.
6910 *
6911 * ai.monitor_gain (R/W)
6912 * It specifies the recording monitor gain(?) of HW mixer.
6913 *
6914 * ai.{play,record}.pause (R/W)
6915 * Non-zero means the track is paused.
6916 *
6917 * ai.play.seek (R/-)
6918 * It indicates the number of bytes written but not processed.
6919 * ai.record.seek (R/-)
6920 * It indicates the number of bytes to be able to read.
6921 *
6922 * ai.{play,record}.avail_ports (R/-)
6923 * Mixer info.
6924 *
6925 * ai.{play,record}.buffer_size (R/-)
6926 * It indicates the buffer size in bytes. Internally it means usrbuf.
6927 *
6928 * ai.{play,record}.samples (R/-)
6929 * It indicates the total number of bytes played or recorded.
6930 *
6931 * ai.{play,record}.eof (R/-)
6932 * It indicates the number of times reached EOF(?).
6933 *
6934 * ai.{play,record}.error (R/-)
6935 * Non-zero indicates overflow/underflow has occurred.
6936 *
6937 * ai.{play,record}.waiting (R/-)
6938 * Non-zero indicates that other process waits to open.
6939 * It will never happen anymore.
6940 *
6941 * ai.{play,record}.open (R/-)
6942 * Non-zero indicates the direction is opened by this process(?).
6943 * XXX Is this better to indicate that "the device is opened by
6944 * at least one process"?
6945 *
6946 * ai.{play,record}.active (R/-)
6947 * Non-zero indicates that I/O is currently active.
6948 *
6949 * ai.blocksize (R/-)
6950 * It indicates the block size in bytes.
6951 * XXX The blocksize of playback and recording may be different.
6952 */
6953
6954 /*
6955 * Pause consideration:
6956 *
6957 * Pausing/unpausing never affect [pr]mixer. This single rule makes
6958 * operation simple. Note that playback and recording are asymmetric.
6959 *
6960 * For playback,
6961 * 1. Any playback open doesn't start pmixer regardless of initial pause
6962 * state of this track.
6963 * 2. The first write access among playback tracks only starts pmixer
6964 * regardless of this track's pause state.
6965 * 3. Even a pause of the last playback track doesn't stop pmixer.
6966 * 4. The last close of all playback tracks only stops pmixer.
6967 *
6968 * For recording,
6969 * 1. The first recording open only starts rmixer regardless of initial
6970 * pause state of this track.
6971 * 2. Even a pause of the last track doesn't stop rmixer.
6972 * 3. The last close of all recording tracks only stops rmixer.
6973 */
6974
6975 /*
6976 * Set both track's parameters within a file depending on ai.
6977 * Update sc_sound_[pr]* if set.
6978 * Must be called with sc_exlock held and without sc_lock held.
6979 */
6980 static int
6981 audio_file_setinfo(struct audio_softc *sc, audio_file_t *file,
6982 const struct audio_info *ai)
6983 {
6984 const struct audio_prinfo *pi;
6985 const struct audio_prinfo *ri;
6986 audio_track_t *ptrack;
6987 audio_track_t *rtrack;
6988 audio_format2_t pfmt;
6989 audio_format2_t rfmt;
6990 int pchanges;
6991 int rchanges;
6992 int mode;
6993 struct audio_info saved_ai;
6994 audio_format2_t saved_pfmt;
6995 audio_format2_t saved_rfmt;
6996 int error;
6997
6998 KASSERT(sc->sc_exlock);
6999
7000 pi = &ai->play;
7001 ri = &ai->record;
7002 pchanges = 0;
7003 rchanges = 0;
7004
7005 ptrack = file->ptrack;
7006 rtrack = file->rtrack;
7007
7008 #if defined(AUDIO_DEBUG)
7009 if (audiodebug >= 2) {
7010 char buf[256];
7011 char p[64];
7012 int buflen;
7013 int plen;
7014 #define SPRINTF(var, fmt...) do { \
7015 var##len += snprintf(var + var##len, sizeof(var) - var##len, fmt); \
7016 } while (0)
7017
7018 buflen = 0;
7019 plen = 0;
7020 if (SPECIFIED(pi->encoding))
7021 SPRINTF(p, "/%s", audio_encoding_name(pi->encoding));
7022 if (SPECIFIED(pi->precision))
7023 SPRINTF(p, "/%dbit", pi->precision);
7024 if (SPECIFIED(pi->channels))
7025 SPRINTF(p, "/%dch", pi->channels);
7026 if (SPECIFIED(pi->sample_rate))
7027 SPRINTF(p, "/%dHz", pi->sample_rate);
7028 if (plen > 0)
7029 SPRINTF(buf, ",play.param=%s", p + 1);
7030
7031 plen = 0;
7032 if (SPECIFIED(ri->encoding))
7033 SPRINTF(p, "/%s", audio_encoding_name(ri->encoding));
7034 if (SPECIFIED(ri->precision))
7035 SPRINTF(p, "/%dbit", ri->precision);
7036 if (SPECIFIED(ri->channels))
7037 SPRINTF(p, "/%dch", ri->channels);
7038 if (SPECIFIED(ri->sample_rate))
7039 SPRINTF(p, "/%dHz", ri->sample_rate);
7040 if (plen > 0)
7041 SPRINTF(buf, ",record.param=%s", p + 1);
7042
7043 if (SPECIFIED(ai->mode))
7044 SPRINTF(buf, ",mode=%d", ai->mode);
7045 if (SPECIFIED(ai->hiwat))
7046 SPRINTF(buf, ",hiwat=%d", ai->hiwat);
7047 if (SPECIFIED(ai->lowat))
7048 SPRINTF(buf, ",lowat=%d", ai->lowat);
7049 if (SPECIFIED(ai->play.gain))
7050 SPRINTF(buf, ",play.gain=%d", ai->play.gain);
7051 if (SPECIFIED(ai->record.gain))
7052 SPRINTF(buf, ",record.gain=%d", ai->record.gain);
7053 if (SPECIFIED_CH(ai->play.balance))
7054 SPRINTF(buf, ",play.balance=%d", ai->play.balance);
7055 if (SPECIFIED_CH(ai->record.balance))
7056 SPRINTF(buf, ",record.balance=%d", ai->record.balance);
7057 if (SPECIFIED(ai->play.port))
7058 SPRINTF(buf, ",play.port=%d", ai->play.port);
7059 if (SPECIFIED(ai->record.port))
7060 SPRINTF(buf, ",record.port=%d", ai->record.port);
7061 if (SPECIFIED(ai->monitor_gain))
7062 SPRINTF(buf, ",monitor_gain=%d", ai->monitor_gain);
7063 if (SPECIFIED_CH(ai->play.pause))
7064 SPRINTF(buf, ",play.pause=%d", ai->play.pause);
7065 if (SPECIFIED_CH(ai->record.pause))
7066 SPRINTF(buf, ",record.pause=%d", ai->record.pause);
7067
7068 if (buflen > 0)
7069 TRACE(2, "specified %s", buf + 1);
7070 }
7071 #endif
7072
7073 AUDIO_INITINFO(&saved_ai);
7074 /* XXX shut up gcc */
7075 memset(&saved_pfmt, 0, sizeof(saved_pfmt));
7076 memset(&saved_rfmt, 0, sizeof(saved_rfmt));
7077
7078 /*
7079 * Set default value and save current parameters.
7080 * For backward compatibility, use sticky parameters for nonexistent
7081 * track.
7082 */
7083 if (ptrack) {
7084 pfmt = ptrack->usrbuf.fmt;
7085 saved_pfmt = ptrack->usrbuf.fmt;
7086 saved_ai.play.pause = ptrack->is_pause;
7087 } else {
7088 pfmt = sc->sc_sound_pparams;
7089 }
7090 if (rtrack) {
7091 rfmt = rtrack->usrbuf.fmt;
7092 saved_rfmt = rtrack->usrbuf.fmt;
7093 saved_ai.record.pause = rtrack->is_pause;
7094 } else {
7095 rfmt = sc->sc_sound_rparams;
7096 }
7097 saved_ai.mode = file->mode;
7098
7099 /*
7100 * Overwrite if specified.
7101 */
7102 mode = file->mode;
7103 if (SPECIFIED(ai->mode)) {
7104 /*
7105 * Setting ai->mode no longer does anything because it's
7106 * prohibited to change playback/recording mode after open
7107 * and AUMODE_PLAY_ALL is obsoleted. However, it still
7108 * keeps the state of AUMODE_PLAY_ALL itself for backward
7109 * compatibility.
7110 * In the internal, only file->mode has the state of
7111 * AUMODE_PLAY_ALL flag and track->mode in both track does
7112 * not have.
7113 */
7114 if ((file->mode & AUMODE_PLAY)) {
7115 mode = (file->mode & (AUMODE_PLAY | AUMODE_RECORD))
7116 | (ai->mode & AUMODE_PLAY_ALL);
7117 }
7118 }
7119
7120 pchanges = audio_track_setinfo_check(ptrack, &pfmt, pi);
7121 if (pchanges == -1) {
7122 #if defined(AUDIO_DEBUG)
7123 TRACEF(1, file, "check play.params failed: "
7124 "%s %ubit %uch %uHz",
7125 audio_encoding_name(pi->encoding),
7126 pi->precision,
7127 pi->channels,
7128 pi->sample_rate);
7129 #endif
7130 return EINVAL;
7131 }
7132
7133 rchanges = audio_track_setinfo_check(rtrack, &rfmt, ri);
7134 if (rchanges == -1) {
7135 #if defined(AUDIO_DEBUG)
7136 TRACEF(1, file, "check record.params failed: "
7137 "%s %ubit %uch %uHz",
7138 audio_encoding_name(ri->encoding),
7139 ri->precision,
7140 ri->channels,
7141 ri->sample_rate);
7142 #endif
7143 return EINVAL;
7144 }
7145
7146 if (SPECIFIED(ai->mode)) {
7147 pchanges = 1;
7148 rchanges = 1;
7149 }
7150
7151 /*
7152 * Even when setting either one of playback and recording,
7153 * both track must be halted.
7154 */
7155 if (pchanges || rchanges) {
7156 audio_file_clear(sc, file);
7157 #if defined(AUDIO_DEBUG)
7158 char nbuf[16];
7159 char fmtbuf[64];
7160 if (pchanges) {
7161 if (ptrack) {
7162 snprintf(nbuf, sizeof(nbuf), "%d", ptrack->id);
7163 } else {
7164 snprintf(nbuf, sizeof(nbuf), "-");
7165 }
7166 audio_format2_tostr(fmtbuf, sizeof(fmtbuf), &pfmt);
7167 DPRINTF(1, "audio track#%s play mode: %s\n",
7168 nbuf, fmtbuf);
7169 }
7170 if (rchanges) {
7171 if (rtrack) {
7172 snprintf(nbuf, sizeof(nbuf), "%d", rtrack->id);
7173 } else {
7174 snprintf(nbuf, sizeof(nbuf), "-");
7175 }
7176 audio_format2_tostr(fmtbuf, sizeof(fmtbuf), &rfmt);
7177 DPRINTF(1, "audio track#%s rec mode: %s\n",
7178 nbuf, fmtbuf);
7179 }
7180 #endif
7181 }
7182
7183 /* Set mixer parameters */
7184 mutex_enter(sc->sc_lock);
7185 error = audio_hw_setinfo(sc, ai, &saved_ai);
7186 mutex_exit(sc->sc_lock);
7187 if (error)
7188 goto abort1;
7189
7190 /*
7191 * Set to track and update sticky parameters.
7192 */
7193 error = 0;
7194 file->mode = mode;
7195
7196 if (SPECIFIED_CH(pi->pause)) {
7197 if (ptrack)
7198 ptrack->is_pause = pi->pause;
7199 sc->sc_sound_ppause = pi->pause;
7200 }
7201 if (pchanges) {
7202 if (ptrack) {
7203 audio_track_lock_enter(ptrack);
7204 error = audio_track_set_format(ptrack, &pfmt);
7205 audio_track_lock_exit(ptrack);
7206 if (error) {
7207 TRACET(1, ptrack, "set play.params failed");
7208 goto abort2;
7209 }
7210 }
7211 sc->sc_sound_pparams = pfmt;
7212 }
7213 /* Change water marks after initializing the buffers. */
7214 if (SPECIFIED(ai->hiwat) || SPECIFIED(ai->lowat)) {
7215 if (ptrack)
7216 audio_track_setinfo_water(ptrack, ai);
7217 }
7218
7219 if (SPECIFIED_CH(ri->pause)) {
7220 if (rtrack)
7221 rtrack->is_pause = ri->pause;
7222 sc->sc_sound_rpause = ri->pause;
7223 }
7224 if (rchanges) {
7225 if (rtrack) {
7226 audio_track_lock_enter(rtrack);
7227 error = audio_track_set_format(rtrack, &rfmt);
7228 audio_track_lock_exit(rtrack);
7229 if (error) {
7230 TRACET(1, rtrack, "set record.params failed");
7231 goto abort3;
7232 }
7233 }
7234 sc->sc_sound_rparams = rfmt;
7235 }
7236
7237 return 0;
7238
7239 /* Rollback */
7240 abort3:
7241 if (error != ENOMEM) {
7242 rtrack->is_pause = saved_ai.record.pause;
7243 audio_track_lock_enter(rtrack);
7244 audio_track_set_format(rtrack, &saved_rfmt);
7245 audio_track_lock_exit(rtrack);
7246 }
7247 sc->sc_sound_rpause = saved_ai.record.pause;
7248 sc->sc_sound_rparams = saved_rfmt;
7249 abort2:
7250 if (ptrack && error != ENOMEM) {
7251 ptrack->is_pause = saved_ai.play.pause;
7252 audio_track_lock_enter(ptrack);
7253 audio_track_set_format(ptrack, &saved_pfmt);
7254 audio_track_lock_exit(ptrack);
7255 }
7256 sc->sc_sound_ppause = saved_ai.play.pause;
7257 sc->sc_sound_pparams = saved_pfmt;
7258 file->mode = saved_ai.mode;
7259 abort1:
7260 mutex_enter(sc->sc_lock);
7261 audio_hw_setinfo(sc, &saved_ai, NULL);
7262 mutex_exit(sc->sc_lock);
7263
7264 return error;
7265 }
7266
7267 /*
7268 * Write SPECIFIED() parameters within info back to fmt.
7269 * Note that track can be NULL here.
7270 * Return value of 1 indicates that fmt is modified.
7271 * Return value of 0 indicates that fmt is not modified.
7272 * Return value of -1 indicates that error EINVAL has occurred.
7273 */
7274 static int
7275 audio_track_setinfo_check(audio_track_t *track,
7276 audio_format2_t *fmt, const struct audio_prinfo *info)
7277 {
7278 const audio_format2_t *hwfmt;
7279 int changes;
7280
7281 changes = 0;
7282 if (SPECIFIED(info->sample_rate)) {
7283 if (info->sample_rate < AUDIO_MIN_FREQUENCY)
7284 return -1;
7285 if (info->sample_rate > AUDIO_MAX_FREQUENCY)
7286 return -1;
7287 fmt->sample_rate = info->sample_rate;
7288 changes = 1;
7289 }
7290 if (SPECIFIED(info->encoding)) {
7291 fmt->encoding = info->encoding;
7292 changes = 1;
7293 }
7294 if (SPECIFIED(info->precision)) {
7295 fmt->precision = info->precision;
7296 /* we don't have API to specify stride */
7297 fmt->stride = info->precision;
7298 changes = 1;
7299 }
7300 if (SPECIFIED(info->channels)) {
7301 /*
7302 * We can convert between monaural and stereo each other.
7303 * We can reduce than the number of channels that the hardware
7304 * supports.
7305 */
7306 if (info->channels > 2) {
7307 if (track) {
7308 hwfmt = &track->mixer->hwbuf.fmt;
7309 if (info->channels > hwfmt->channels)
7310 return -1;
7311 } else {
7312 /*
7313 * This should never happen.
7314 * If track == NULL, channels should be <= 2.
7315 */
7316 return -1;
7317 }
7318 }
7319 fmt->channels = info->channels;
7320 changes = 1;
7321 }
7322
7323 if (changes) {
7324 if (audio_check_params(fmt) != 0)
7325 return -1;
7326 }
7327
7328 return changes;
7329 }
7330
7331 /*
7332 * Change water marks for playback track if specified.
7333 */
7334 static void
7335 audio_track_setinfo_water(audio_track_t *track, const struct audio_info *ai)
7336 {
7337 u_int blks;
7338 u_int maxblks;
7339 u_int blksize;
7340
7341 KASSERT(audio_track_is_playback(track));
7342
7343 blksize = track->usrbuf_blksize;
7344 maxblks = track->usrbuf.capacity / blksize;
7345
7346 if (SPECIFIED(ai->hiwat)) {
7347 blks = ai->hiwat;
7348 if (blks > maxblks)
7349 blks = maxblks;
7350 if (blks < 2)
7351 blks = 2;
7352 track->usrbuf_usedhigh = blks * blksize;
7353 }
7354 if (SPECIFIED(ai->lowat)) {
7355 blks = ai->lowat;
7356 if (blks > maxblks - 1)
7357 blks = maxblks - 1;
7358 track->usrbuf_usedlow = blks * blksize;
7359 }
7360 if (SPECIFIED(ai->hiwat) || SPECIFIED(ai->lowat)) {
7361 if (track->usrbuf_usedlow > track->usrbuf_usedhigh - blksize) {
7362 track->usrbuf_usedlow = track->usrbuf_usedhigh -
7363 blksize;
7364 }
7365 }
7366 }
7367
7368 /*
7369 * Set hardware part of *newai.
7370 * The parameters handled here are *.port, *.gain, *.balance and monitor_gain.
7371 * If oldai is specified, previous parameters are stored.
7372 * This function itself does not roll back if error occurred.
7373 * Must be called with sc_lock && sc_exlock held.
7374 */
7375 static int
7376 audio_hw_setinfo(struct audio_softc *sc, const struct audio_info *newai,
7377 struct audio_info *oldai)
7378 {
7379 const struct audio_prinfo *newpi;
7380 const struct audio_prinfo *newri;
7381 struct audio_prinfo *oldpi;
7382 struct audio_prinfo *oldri;
7383 u_int pgain;
7384 u_int rgain;
7385 u_char pbalance;
7386 u_char rbalance;
7387 int error;
7388
7389 KASSERT(mutex_owned(sc->sc_lock));
7390 KASSERT(sc->sc_exlock);
7391
7392 /* XXX shut up gcc */
7393 oldpi = NULL;
7394 oldri = NULL;
7395
7396 newpi = &newai->play;
7397 newri = &newai->record;
7398 if (oldai) {
7399 oldpi = &oldai->play;
7400 oldri = &oldai->record;
7401 }
7402 error = 0;
7403
7404 /*
7405 * It looks like unnecessary to halt HW mixers to set HW mixers.
7406 * mixer_ioctl(MIXER_WRITE) also doesn't halt.
7407 */
7408
7409 if (SPECIFIED(newpi->port)) {
7410 if (oldai)
7411 oldpi->port = au_get_port(sc, &sc->sc_outports);
7412 error = au_set_port(sc, &sc->sc_outports, newpi->port);
7413 if (error) {
7414 audio_printf(sc,
7415 "setting play.port=%d failed: errno=%d\n",
7416 newpi->port, error);
7417 goto abort;
7418 }
7419 }
7420 if (SPECIFIED(newri->port)) {
7421 if (oldai)
7422 oldri->port = au_get_port(sc, &sc->sc_inports);
7423 error = au_set_port(sc, &sc->sc_inports, newri->port);
7424 if (error) {
7425 audio_printf(sc,
7426 "setting record.port=%d failed: errno=%d\n",
7427 newri->port, error);
7428 goto abort;
7429 }
7430 }
7431
7432 /* play.{gain,balance} */
7433 if (SPECIFIED(newpi->gain) || SPECIFIED_CH(newpi->balance)) {
7434 au_get_gain(sc, &sc->sc_outports, &pgain, &pbalance);
7435 if (oldai) {
7436 oldpi->gain = pgain;
7437 oldpi->balance = pbalance;
7438 }
7439
7440 if (SPECIFIED(newpi->gain))
7441 pgain = newpi->gain;
7442 if (SPECIFIED_CH(newpi->balance))
7443 pbalance = newpi->balance;
7444 error = au_set_gain(sc, &sc->sc_outports, pgain, pbalance);
7445 if (error) {
7446 audio_printf(sc,
7447 "setting play.gain=%d/balance=%d failed: "
7448 "errno=%d\n",
7449 pgain, pbalance, error);
7450 goto abort;
7451 }
7452 }
7453
7454 /* record.{gain,balance} */
7455 if (SPECIFIED(newri->gain) || SPECIFIED_CH(newri->balance)) {
7456 au_get_gain(sc, &sc->sc_inports, &rgain, &rbalance);
7457 if (oldai) {
7458 oldri->gain = rgain;
7459 oldri->balance = rbalance;
7460 }
7461
7462 if (SPECIFIED(newri->gain))
7463 rgain = newri->gain;
7464 if (SPECIFIED_CH(newri->balance))
7465 rbalance = newri->balance;
7466 error = au_set_gain(sc, &sc->sc_inports, rgain, rbalance);
7467 if (error) {
7468 audio_printf(sc,
7469 "setting record.gain=%d/balance=%d failed: "
7470 "errno=%d\n",
7471 rgain, rbalance, error);
7472 goto abort;
7473 }
7474 }
7475
7476 if (SPECIFIED(newai->monitor_gain) && sc->sc_monitor_port != -1) {
7477 if (oldai)
7478 oldai->monitor_gain = au_get_monitor_gain(sc);
7479 error = au_set_monitor_gain(sc, newai->monitor_gain);
7480 if (error) {
7481 audio_printf(sc,
7482 "setting monitor_gain=%d failed: errno=%d\n",
7483 newai->monitor_gain, error);
7484 goto abort;
7485 }
7486 }
7487
7488 /* XXX TODO */
7489 /* sc->sc_ai = *ai; */
7490
7491 error = 0;
7492 abort:
7493 return error;
7494 }
7495
7496 /*
7497 * Setup the hardware with mixer format phwfmt, rhwfmt.
7498 * The arguments have following restrictions:
7499 * - setmode is the direction you want to set, AUMODE_PLAY or AUMODE_RECORD,
7500 * or both.
7501 * - phwfmt and rhwfmt must not be NULL regardless of setmode.
7502 * - On non-independent devices, phwfmt and rhwfmt must have the same
7503 * parameters.
7504 * - pfil and rfil must be zero-filled.
7505 * If successful,
7506 * - pfil, rfil will be filled with filter information specified by the
7507 * hardware driver if necessary.
7508 * and then returns 0. Otherwise returns errno.
7509 * Must be called without sc_lock held.
7510 */
7511 static int
7512 audio_hw_set_format(struct audio_softc *sc, int setmode,
7513 const audio_format2_t *phwfmt, const audio_format2_t *rhwfmt,
7514 audio_filter_reg_t *pfil, audio_filter_reg_t *rfil)
7515 {
7516 audio_params_t pp, rp;
7517 int error;
7518
7519 KASSERT(phwfmt != NULL);
7520 KASSERT(rhwfmt != NULL);
7521
7522 pp = format2_to_params(phwfmt);
7523 rp = format2_to_params(rhwfmt);
7524
7525 mutex_enter(sc->sc_lock);
7526 error = sc->hw_if->set_format(sc->hw_hdl, setmode,
7527 &pp, &rp, pfil, rfil);
7528 if (error) {
7529 mutex_exit(sc->sc_lock);
7530 audio_printf(sc, "set_format failed: errno=%d\n", error);
7531 return error;
7532 }
7533
7534 if (sc->hw_if->commit_settings) {
7535 error = sc->hw_if->commit_settings(sc->hw_hdl);
7536 if (error) {
7537 mutex_exit(sc->sc_lock);
7538 audio_printf(sc,
7539 "commit_settings failed: errno=%d\n", error);
7540 return error;
7541 }
7542 }
7543 mutex_exit(sc->sc_lock);
7544
7545 return 0;
7546 }
7547
7548 /*
7549 * Fill audio_info structure. If need_mixerinfo is true, it will also
7550 * fill the hardware mixer information.
7551 * Must be called with sc_exlock held and without sc_lock held.
7552 */
7553 static int
7554 audiogetinfo(struct audio_softc *sc, struct audio_info *ai, int need_mixerinfo,
7555 audio_file_t *file)
7556 {
7557 struct audio_prinfo *ri, *pi;
7558 audio_track_t *track;
7559 audio_track_t *ptrack;
7560 audio_track_t *rtrack;
7561 int gain;
7562
7563 KASSERT(sc->sc_exlock);
7564
7565 ri = &ai->record;
7566 pi = &ai->play;
7567 ptrack = file->ptrack;
7568 rtrack = file->rtrack;
7569
7570 memset(ai, 0, sizeof(*ai));
7571
7572 if (ptrack) {
7573 pi->sample_rate = ptrack->usrbuf.fmt.sample_rate;
7574 pi->channels = ptrack->usrbuf.fmt.channels;
7575 pi->precision = ptrack->usrbuf.fmt.precision;
7576 pi->encoding = ptrack->usrbuf.fmt.encoding;
7577 pi->pause = ptrack->is_pause;
7578 } else {
7579 /* Use sticky parameters if the track is not available. */
7580 pi->sample_rate = sc->sc_sound_pparams.sample_rate;
7581 pi->channels = sc->sc_sound_pparams.channels;
7582 pi->precision = sc->sc_sound_pparams.precision;
7583 pi->encoding = sc->sc_sound_pparams.encoding;
7584 pi->pause = sc->sc_sound_ppause;
7585 }
7586 if (rtrack) {
7587 ri->sample_rate = rtrack->usrbuf.fmt.sample_rate;
7588 ri->channels = rtrack->usrbuf.fmt.channels;
7589 ri->precision = rtrack->usrbuf.fmt.precision;
7590 ri->encoding = rtrack->usrbuf.fmt.encoding;
7591 ri->pause = rtrack->is_pause;
7592 } else {
7593 /* Use sticky parameters if the track is not available. */
7594 ri->sample_rate = sc->sc_sound_rparams.sample_rate;
7595 ri->channels = sc->sc_sound_rparams.channels;
7596 ri->precision = sc->sc_sound_rparams.precision;
7597 ri->encoding = sc->sc_sound_rparams.encoding;
7598 ri->pause = sc->sc_sound_rpause;
7599 }
7600
7601 if (ptrack) {
7602 pi->seek = ptrack->usrbuf.used;
7603 pi->samples = ptrack->usrbuf_stamp;
7604 pi->eof = ptrack->eofcounter;
7605 pi->error = (ptrack->dropframes != 0) ? 1 : 0;
7606 pi->open = 1;
7607 pi->buffer_size = ptrack->usrbuf.capacity;
7608 }
7609 pi->waiting = 0; /* open never hangs */
7610 pi->active = sc->sc_pbusy;
7611
7612 if (rtrack) {
7613 ri->seek = rtrack->usrbuf.used;
7614 ri->samples = rtrack->usrbuf_stamp;
7615 ri->eof = 0;
7616 ri->error = (rtrack->dropframes != 0) ? 1 : 0;
7617 ri->open = 1;
7618 ri->buffer_size = rtrack->usrbuf.capacity;
7619 }
7620 ri->waiting = 0; /* open never hangs */
7621 ri->active = sc->sc_rbusy;
7622
7623 /*
7624 * XXX There may be different number of channels between playback
7625 * and recording, so that blocksize also may be different.
7626 * But struct audio_info has an united blocksize...
7627 * Here, I use play info precedencely if ptrack is available,
7628 * otherwise record info.
7629 *
7630 * XXX hiwat/lowat is a playback-only parameter. What should I
7631 * return for a record-only descriptor?
7632 */
7633 track = ptrack ? ptrack : rtrack;
7634 if (track) {
7635 ai->blocksize = track->usrbuf_blksize;
7636 ai->hiwat = track->usrbuf_usedhigh / track->usrbuf_blksize;
7637 ai->lowat = track->usrbuf_usedlow / track->usrbuf_blksize;
7638 }
7639 ai->mode = file->mode;
7640
7641 /*
7642 * For backward compatibility, we have to pad these five fields
7643 * a fake non-zero value even if there are no tracks.
7644 */
7645 if (ptrack == NULL)
7646 pi->buffer_size = 65536;
7647 if (rtrack == NULL)
7648 ri->buffer_size = 65536;
7649 if (ptrack == NULL && rtrack == NULL) {
7650 ai->blocksize = 2048;
7651 ai->hiwat = ai->play.buffer_size / ai->blocksize;
7652 ai->lowat = ai->hiwat * 3 / 4;
7653 }
7654
7655 if (need_mixerinfo) {
7656 mutex_enter(sc->sc_lock);
7657
7658 pi->port = au_get_port(sc, &sc->sc_outports);
7659 ri->port = au_get_port(sc, &sc->sc_inports);
7660
7661 pi->avail_ports = sc->sc_outports.allports;
7662 ri->avail_ports = sc->sc_inports.allports;
7663
7664 au_get_gain(sc, &sc->sc_outports, &pi->gain, &pi->balance);
7665 au_get_gain(sc, &sc->sc_inports, &ri->gain, &ri->balance);
7666
7667 if (sc->sc_monitor_port != -1) {
7668 gain = au_get_monitor_gain(sc);
7669 if (gain != -1)
7670 ai->monitor_gain = gain;
7671 }
7672 mutex_exit(sc->sc_lock);
7673 }
7674
7675 return 0;
7676 }
7677
7678 /*
7679 * Return true if playback is configured.
7680 * This function can be used after audioattach.
7681 */
7682 static bool
7683 audio_can_playback(struct audio_softc *sc)
7684 {
7685
7686 return (sc->sc_pmixer != NULL);
7687 }
7688
7689 /*
7690 * Return true if recording is configured.
7691 * This function can be used after audioattach.
7692 */
7693 static bool
7694 audio_can_capture(struct audio_softc *sc)
7695 {
7696
7697 return (sc->sc_rmixer != NULL);
7698 }
7699
7700 /*
7701 * Get the afp->index'th item from the valid one of format[].
7702 * If found, stores it to afp->fmt and returns 0. Otherwise return EINVAL.
7703 *
7704 * This is common routines for query_format.
7705 * If your hardware driver has struct audio_format[], the simplest case
7706 * you can write your query_format interface as follows:
7707 *
7708 * struct audio_format foo_format[] = { ... };
7709 *
7710 * int
7711 * foo_query_format(void *hdl, audio_format_query_t *afp)
7712 * {
7713 * return audio_query_format(foo_format, __arraycount(foo_format), afp);
7714 * }
7715 */
7716 int
7717 audio_query_format(const struct audio_format *format, int nformats,
7718 audio_format_query_t *afp)
7719 {
7720 const struct audio_format *f;
7721 int idx;
7722 int i;
7723
7724 idx = 0;
7725 for (i = 0; i < nformats; i++) {
7726 f = &format[i];
7727 if (!AUFMT_IS_VALID(f))
7728 continue;
7729 if (afp->index == idx) {
7730 afp->fmt = *f;
7731 return 0;
7732 }
7733 idx++;
7734 }
7735 return EINVAL;
7736 }
7737
7738 /*
7739 * This function is provided for the hardware driver's set_format() to
7740 * find index matches with 'param' from array of audio_format_t 'formats'.
7741 * 'mode' is either of AUMODE_PLAY or AUMODE_RECORD.
7742 * It returns the matched index and never fails. Because param passed to
7743 * set_format() is selected from query_format().
7744 * This function will be an alternative to auconv_set_converter() to
7745 * find index.
7746 */
7747 int
7748 audio_indexof_format(const struct audio_format *formats, int nformats,
7749 int mode, const audio_params_t *param)
7750 {
7751 const struct audio_format *f;
7752 int index;
7753 int j;
7754
7755 for (index = 0; index < nformats; index++) {
7756 f = &formats[index];
7757
7758 if (!AUFMT_IS_VALID(f))
7759 continue;
7760 if ((f->mode & mode) == 0)
7761 continue;
7762 if (f->encoding != param->encoding)
7763 continue;
7764 if (f->validbits != param->precision)
7765 continue;
7766 if (f->channels != param->channels)
7767 continue;
7768
7769 if (f->frequency_type == 0) {
7770 if (param->sample_rate < f->frequency[0] ||
7771 param->sample_rate > f->frequency[1])
7772 continue;
7773 } else {
7774 for (j = 0; j < f->frequency_type; j++) {
7775 if (param->sample_rate == f->frequency[j])
7776 break;
7777 }
7778 if (j == f->frequency_type)
7779 continue;
7780 }
7781
7782 /* Then, matched */
7783 return index;
7784 }
7785
7786 /* Not matched. This should not be happened. */
7787 panic("%s: cannot find matched format\n", __func__);
7788 }
7789
7790 /*
7791 * Get or set hardware blocksize in msec.
7792 * XXX It's for debug.
7793 */
7794 static int
7795 audio_sysctl_blk_ms(SYSCTLFN_ARGS)
7796 {
7797 struct sysctlnode node;
7798 struct audio_softc *sc;
7799 audio_format2_t phwfmt;
7800 audio_format2_t rhwfmt;
7801 audio_filter_reg_t pfil;
7802 audio_filter_reg_t rfil;
7803 int t;
7804 int old_blk_ms;
7805 int mode;
7806 int error;
7807
7808 node = *rnode;
7809 sc = node.sysctl_data;
7810
7811 error = audio_exlock_enter(sc);
7812 if (error)
7813 return error;
7814
7815 old_blk_ms = sc->sc_blk_ms;
7816 t = old_blk_ms;
7817 node.sysctl_data = &t;
7818 error = sysctl_lookup(SYSCTLFN_CALL(&node));
7819 if (error || newp == NULL)
7820 goto abort;
7821
7822 if (t < 0) {
7823 error = EINVAL;
7824 goto abort;
7825 }
7826
7827 if (sc->sc_popens + sc->sc_ropens > 0) {
7828 error = EBUSY;
7829 goto abort;
7830 }
7831 sc->sc_blk_ms = t;
7832 mode = 0;
7833 if (sc->sc_pmixer) {
7834 mode |= AUMODE_PLAY;
7835 phwfmt = sc->sc_pmixer->hwbuf.fmt;
7836 }
7837 if (sc->sc_rmixer) {
7838 mode |= AUMODE_RECORD;
7839 rhwfmt = sc->sc_rmixer->hwbuf.fmt;
7840 }
7841
7842 /* re-init hardware */
7843 memset(&pfil, 0, sizeof(pfil));
7844 memset(&rfil, 0, sizeof(rfil));
7845 error = audio_hw_set_format(sc, mode, &phwfmt, &rhwfmt, &pfil, &rfil);
7846 if (error) {
7847 goto abort;
7848 }
7849
7850 /* re-init track mixer */
7851 error = audio_mixers_init(sc, mode, &phwfmt, &rhwfmt, &pfil, &rfil);
7852 if (error) {
7853 /* Rollback */
7854 sc->sc_blk_ms = old_blk_ms;
7855 audio_mixers_init(sc, mode, &phwfmt, &rhwfmt, &pfil, &rfil);
7856 goto abort;
7857 }
7858 error = 0;
7859 abort:
7860 audio_exlock_exit(sc);
7861 return error;
7862 }
7863
7864 /*
7865 * Get or set multiuser mode.
7866 */
7867 static int
7868 audio_sysctl_multiuser(SYSCTLFN_ARGS)
7869 {
7870 struct sysctlnode node;
7871 struct audio_softc *sc;
7872 bool t;
7873 int error;
7874
7875 node = *rnode;
7876 sc = node.sysctl_data;
7877
7878 error = audio_exlock_enter(sc);
7879 if (error)
7880 return error;
7881
7882 t = sc->sc_multiuser;
7883 node.sysctl_data = &t;
7884 error = sysctl_lookup(SYSCTLFN_CALL(&node));
7885 if (error || newp == NULL)
7886 goto abort;
7887
7888 sc->sc_multiuser = t;
7889 error = 0;
7890 abort:
7891 audio_exlock_exit(sc);
7892 return error;
7893 }
7894
7895 #if defined(AUDIO_DEBUG)
7896 /*
7897 * Get or set debug verbose level. (0..4)
7898 * XXX It's for debug.
7899 * XXX It is not separated per device.
7900 */
7901 static int
7902 audio_sysctl_debug(SYSCTLFN_ARGS)
7903 {
7904 struct sysctlnode node;
7905 int t;
7906 int error;
7907
7908 node = *rnode;
7909 t = audiodebug;
7910 node.sysctl_data = &t;
7911 error = sysctl_lookup(SYSCTLFN_CALL(&node));
7912 if (error || newp == NULL)
7913 return error;
7914
7915 if (t < 0 || t > 4)
7916 return EINVAL;
7917 audiodebug = t;
7918 printf("audio: audiodebug = %d\n", audiodebug);
7919 return 0;
7920 }
7921 #endif /* AUDIO_DEBUG */
7922
7923 #ifdef AUDIO_PM_IDLE
7924 static void
7925 audio_idle(void *arg)
7926 {
7927 device_t dv = arg;
7928 struct audio_softc *sc = device_private(dv);
7929
7930 #ifdef PNP_DEBUG
7931 extern int pnp_debug_idle;
7932 if (pnp_debug_idle)
7933 printf("%s: idle handler called\n", device_xname(dv));
7934 #endif
7935
7936 sc->sc_idle = true;
7937
7938 /* XXX joerg Make pmf_device_suspend handle children? */
7939 if (!pmf_device_suspend(dv, PMF_Q_SELF))
7940 return;
7941
7942 if (!pmf_device_suspend(sc->hw_dev, PMF_Q_SELF))
7943 pmf_device_resume(dv, PMF_Q_SELF);
7944 }
7945
7946 static void
7947 audio_activity(device_t dv, devactive_t type)
7948 {
7949 struct audio_softc *sc = device_private(dv);
7950
7951 if (type != DVA_SYSTEM)
7952 return;
7953
7954 callout_schedule(&sc->sc_idle_counter, audio_idle_timeout * hz);
7955
7956 sc->sc_idle = false;
7957 if (!device_is_active(dv)) {
7958 /* XXX joerg How to deal with a failing resume... */
7959 pmf_device_resume(sc->hw_dev, PMF_Q_SELF);
7960 pmf_device_resume(dv, PMF_Q_SELF);
7961 }
7962 }
7963 #endif
7964
7965 static bool
7966 audio_suspend(device_t dv, const pmf_qual_t *qual)
7967 {
7968 struct audio_softc *sc = device_private(dv);
7969 int error;
7970
7971 error = audio_exlock_mutex_enter(sc);
7972 if (error)
7973 return error;
7974 sc->sc_suspending = true;
7975 audio_mixer_capture(sc);
7976
7977 if (sc->sc_pbusy) {
7978 audio_pmixer_halt(sc);
7979 /* Reuse this as need-to-restart flag while suspending */
7980 sc->sc_pbusy = true;
7981 }
7982 if (sc->sc_rbusy) {
7983 audio_rmixer_halt(sc);
7984 /* Reuse this as need-to-restart flag while suspending */
7985 sc->sc_rbusy = true;
7986 }
7987
7988 #ifdef AUDIO_PM_IDLE
7989 callout_halt(&sc->sc_idle_counter, sc->sc_lock);
7990 #endif
7991 audio_exlock_mutex_exit(sc);
7992
7993 return true;
7994 }
7995
7996 static bool
7997 audio_resume(device_t dv, const pmf_qual_t *qual)
7998 {
7999 struct audio_softc *sc = device_private(dv);
8000 struct audio_info ai;
8001 int error;
8002
8003 error = audio_exlock_mutex_enter(sc);
8004 if (error)
8005 return error;
8006
8007 sc->sc_suspending = false;
8008 audio_mixer_restore(sc);
8009 /* XXX ? */
8010 AUDIO_INITINFO(&ai);
8011 audio_hw_setinfo(sc, &ai, NULL);
8012
8013 /*
8014 * During from suspend to resume here, sc_[pr]busy is used as
8015 * need-to-restart flag temporarily. After this point,
8016 * sc_[pr]busy is returned to its original usage (busy flag).
8017 * And note that sc_[pr]busy must be false to call [pr]mixer_start().
8018 */
8019 if (sc->sc_pbusy) {
8020 /* pmixer_start() requires pbusy is false */
8021 sc->sc_pbusy = false;
8022 audio_pmixer_start(sc, true);
8023 }
8024 if (sc->sc_rbusy) {
8025 /* rmixer_start() requires rbusy is false */
8026 sc->sc_rbusy = false;
8027 audio_rmixer_start(sc);
8028 }
8029
8030 audio_exlock_mutex_exit(sc);
8031
8032 return true;
8033 }
8034
8035 #if defined(AUDIO_DEBUG)
8036 static void
8037 audio_format2_tostr(char *buf, size_t bufsize, const audio_format2_t *fmt)
8038 {
8039 int n;
8040
8041 n = 0;
8042 n += snprintf(buf + n, bufsize - n, "%s",
8043 audio_encoding_name(fmt->encoding));
8044 if (fmt->precision == fmt->stride) {
8045 n += snprintf(buf + n, bufsize - n, " %dbit", fmt->precision);
8046 } else {
8047 n += snprintf(buf + n, bufsize - n, " %d/%dbit",
8048 fmt->precision, fmt->stride);
8049 }
8050
8051 snprintf(buf + n, bufsize - n, " %uch %uHz",
8052 fmt->channels, fmt->sample_rate);
8053 }
8054 #endif
8055
8056 #if defined(AUDIO_DEBUG)
8057 static void
8058 audio_print_format2(const char *s, const audio_format2_t *fmt)
8059 {
8060 char fmtstr[64];
8061
8062 audio_format2_tostr(fmtstr, sizeof(fmtstr), fmt);
8063 printf("%s %s\n", s, fmtstr);
8064 }
8065 #endif
8066
8067 #ifdef DIAGNOSTIC
8068 void
8069 audio_diagnostic_format2(const char *where, const audio_format2_t *fmt)
8070 {
8071
8072 KASSERTMSG(fmt, "called from %s", where);
8073
8074 /* XXX MSM6258 vs(4) only has 4bit stride format. */
8075 if (fmt->encoding == AUDIO_ENCODING_ADPCM) {
8076 KASSERTMSG(fmt->stride == 4 || fmt->stride == 8,
8077 "called from %s: fmt->stride=%d", where, fmt->stride);
8078 } else {
8079 KASSERTMSG(fmt->stride % NBBY == 0,
8080 "called from %s: fmt->stride=%d", where, fmt->stride);
8081 }
8082 KASSERTMSG(fmt->precision <= fmt->stride,
8083 "called from %s: fmt->precision=%d fmt->stride=%d",
8084 where, fmt->precision, fmt->stride);
8085 KASSERTMSG(1 <= fmt->channels && fmt->channels <= AUDIO_MAX_CHANNELS,
8086 "called from %s: fmt->channels=%d", where, fmt->channels);
8087
8088 /* XXX No check for encodings? */
8089 }
8090
8091 void
8092 audio_diagnostic_filter_arg(const char *where, const audio_filter_arg_t *arg)
8093 {
8094
8095 KASSERT(arg != NULL);
8096 KASSERT(arg->src != NULL);
8097 KASSERT(arg->dst != NULL);
8098 audio_diagnostic_format2(where, arg->srcfmt);
8099 audio_diagnostic_format2(where, arg->dstfmt);
8100 KASSERT(arg->count > 0);
8101 }
8102
8103 void
8104 audio_diagnostic_ring(const char *where, const audio_ring_t *ring)
8105 {
8106
8107 KASSERTMSG(ring, "called from %s", where);
8108 audio_diagnostic_format2(where, &ring->fmt);
8109 KASSERTMSG(0 <= ring->capacity && ring->capacity < INT_MAX / 2,
8110 "called from %s: ring->capacity=%d", where, ring->capacity);
8111 KASSERTMSG(0 <= ring->used && ring->used <= ring->capacity,
8112 "called from %s: ring->used=%d ring->capacity=%d",
8113 where, ring->used, ring->capacity);
8114 if (ring->capacity == 0) {
8115 KASSERTMSG(ring->mem == NULL,
8116 "called from %s: capacity == 0 but mem != NULL", where);
8117 } else {
8118 KASSERTMSG(ring->mem != NULL,
8119 "called from %s: capacity != 0 but mem == NULL", where);
8120 KASSERTMSG(0 <= ring->head && ring->head < ring->capacity,
8121 "called from %s: ring->head=%d ring->capacity=%d",
8122 where, ring->head, ring->capacity);
8123 }
8124 }
8125 #endif /* DIAGNOSTIC */
8126
8127
8128 /*
8129 * Mixer driver
8130 */
8131
8132 /*
8133 * Must be called without sc_lock held.
8134 */
8135 int
8136 mixer_open(dev_t dev, struct audio_softc *sc, int flags, int ifmt,
8137 struct lwp *l)
8138 {
8139 struct file *fp;
8140 audio_file_t *af;
8141 int error, fd;
8142
8143 TRACE(1, "flags=0x%x", flags);
8144
8145 error = fd_allocfile(&fp, &fd);
8146 if (error)
8147 return error;
8148
8149 af = kmem_zalloc(sizeof(*af), KM_SLEEP);
8150 af->sc = sc;
8151 af->dev = dev;
8152
8153 mutex_enter(sc->sc_lock);
8154 if (sc->sc_dying) {
8155 mutex_exit(sc->sc_lock);
8156 kmem_free(af, sizeof(*af));
8157 fd_abort(curproc, fp, fd);
8158 return ENXIO;
8159 }
8160 mutex_enter(sc->sc_intr_lock);
8161 SLIST_INSERT_HEAD(&sc->sc_files, af, entry);
8162 mutex_exit(sc->sc_intr_lock);
8163 mutex_exit(sc->sc_lock);
8164
8165 error = fd_clone(fp, fd, flags, &audio_fileops, af);
8166 KASSERT(error == EMOVEFD);
8167
8168 return error;
8169 }
8170
8171 /*
8172 * Add a process to those to be signalled on mixer activity.
8173 * If the process has already been added, do nothing.
8174 * Must be called with sc_exlock held and without sc_lock held.
8175 */
8176 static void
8177 mixer_async_add(struct audio_softc *sc, pid_t pid)
8178 {
8179 int i;
8180
8181 KASSERT(sc->sc_exlock);
8182
8183 /* If already exists, returns without doing anything. */
8184 for (i = 0; i < sc->sc_am_used; i++) {
8185 if (sc->sc_am[i] == pid)
8186 return;
8187 }
8188
8189 /* Extend array if necessary. */
8190 if (sc->sc_am_used >= sc->sc_am_capacity) {
8191 sc->sc_am_capacity += AM_CAPACITY;
8192 sc->sc_am = kern_realloc(sc->sc_am,
8193 sc->sc_am_capacity * sizeof(pid_t), M_WAITOK);
8194 TRACE(2, "realloc am_capacity=%d", sc->sc_am_capacity);
8195 }
8196
8197 TRACE(2, "am[%d]=%d", sc->sc_am_used, (int)pid);
8198 sc->sc_am[sc->sc_am_used++] = pid;
8199 }
8200
8201 /*
8202 * Remove a process from those to be signalled on mixer activity.
8203 * If the process has not been added, do nothing.
8204 * Must be called with sc_exlock held and without sc_lock held.
8205 */
8206 static void
8207 mixer_async_remove(struct audio_softc *sc, pid_t pid)
8208 {
8209 int i;
8210
8211 KASSERT(sc->sc_exlock);
8212
8213 for (i = 0; i < sc->sc_am_used; i++) {
8214 if (sc->sc_am[i] == pid) {
8215 sc->sc_am[i] = sc->sc_am[--sc->sc_am_used];
8216 TRACE(2, "am[%d](%d) removed, used=%d",
8217 i, (int)pid, sc->sc_am_used);
8218
8219 /* Empty array if no longer necessary. */
8220 if (sc->sc_am_used == 0) {
8221 kern_free(sc->sc_am);
8222 sc->sc_am = NULL;
8223 sc->sc_am_capacity = 0;
8224 TRACE(2, "released");
8225 }
8226 return;
8227 }
8228 }
8229 }
8230
8231 /*
8232 * Signal all processes waiting for the mixer.
8233 * Must be called with sc_exlock held.
8234 */
8235 static void
8236 mixer_signal(struct audio_softc *sc)
8237 {
8238 proc_t *p;
8239 int i;
8240
8241 KASSERT(sc->sc_exlock);
8242
8243 for (i = 0; i < sc->sc_am_used; i++) {
8244 mutex_enter(&proc_lock);
8245 p = proc_find(sc->sc_am[i]);
8246 if (p)
8247 psignal(p, SIGIO);
8248 mutex_exit(&proc_lock);
8249 }
8250 }
8251
8252 /*
8253 * Close a mixer device
8254 */
8255 int
8256 mixer_close(struct audio_softc *sc, audio_file_t *file)
8257 {
8258 int error;
8259
8260 error = audio_exlock_enter(sc);
8261 if (error)
8262 return error;
8263 TRACE(1, "called");
8264 mixer_async_remove(sc, curproc->p_pid);
8265 audio_exlock_exit(sc);
8266
8267 return 0;
8268 }
8269
8270 /*
8271 * Must be called without sc_lock nor sc_exlock held.
8272 */
8273 int
8274 mixer_ioctl(struct audio_softc *sc, u_long cmd, void *addr, int flag,
8275 struct lwp *l)
8276 {
8277 mixer_devinfo_t *mi;
8278 mixer_ctrl_t *mc;
8279 int error;
8280
8281 TRACE(2, "(%lu,'%c',%lu)",
8282 IOCPARM_LEN(cmd), (char)IOCGROUP(cmd), cmd & 0xff);
8283 error = EINVAL;
8284
8285 /* we can return cached values if we are sleeping */
8286 if (cmd != AUDIO_MIXER_READ) {
8287 mutex_enter(sc->sc_lock);
8288 device_active(sc->sc_dev, DVA_SYSTEM);
8289 mutex_exit(sc->sc_lock);
8290 }
8291
8292 switch (cmd) {
8293 case FIOASYNC:
8294 error = audio_exlock_enter(sc);
8295 if (error)
8296 break;
8297 if (*(int *)addr) {
8298 mixer_async_add(sc, curproc->p_pid);
8299 } else {
8300 mixer_async_remove(sc, curproc->p_pid);
8301 }
8302 audio_exlock_exit(sc);
8303 break;
8304
8305 case AUDIO_GETDEV:
8306 TRACE(2, "AUDIO_GETDEV");
8307 error = sc->hw_if->getdev(sc->hw_hdl, (audio_device_t *)addr);
8308 break;
8309
8310 case AUDIO_MIXER_DEVINFO:
8311 TRACE(2, "AUDIO_MIXER_DEVINFO");
8312 mi = (mixer_devinfo_t *)addr;
8313
8314 mi->un.v.delta = 0; /* default */
8315 mutex_enter(sc->sc_lock);
8316 error = audio_query_devinfo(sc, mi);
8317 mutex_exit(sc->sc_lock);
8318 break;
8319
8320 case AUDIO_MIXER_READ:
8321 TRACE(2, "AUDIO_MIXER_READ");
8322 mc = (mixer_ctrl_t *)addr;
8323
8324 error = audio_exlock_mutex_enter(sc);
8325 if (error)
8326 break;
8327 if (device_is_active(sc->hw_dev))
8328 error = audio_get_port(sc, mc);
8329 else if (mc->dev < 0 || mc->dev >= sc->sc_nmixer_states)
8330 error = ENXIO;
8331 else {
8332 int dev = mc->dev;
8333 memcpy(mc, &sc->sc_mixer_state[dev],
8334 sizeof(mixer_ctrl_t));
8335 error = 0;
8336 }
8337 audio_exlock_mutex_exit(sc);
8338 break;
8339
8340 case AUDIO_MIXER_WRITE:
8341 TRACE(2, "AUDIO_MIXER_WRITE");
8342 error = audio_exlock_mutex_enter(sc);
8343 if (error)
8344 break;
8345 error = audio_set_port(sc, (mixer_ctrl_t *)addr);
8346 if (error) {
8347 audio_exlock_mutex_exit(sc);
8348 break;
8349 }
8350
8351 if (sc->hw_if->commit_settings) {
8352 error = sc->hw_if->commit_settings(sc->hw_hdl);
8353 if (error) {
8354 audio_exlock_mutex_exit(sc);
8355 break;
8356 }
8357 }
8358 mutex_exit(sc->sc_lock);
8359 mixer_signal(sc);
8360 audio_exlock_exit(sc);
8361 break;
8362
8363 default:
8364 if (sc->hw_if->dev_ioctl) {
8365 mutex_enter(sc->sc_lock);
8366 error = sc->hw_if->dev_ioctl(sc->hw_hdl,
8367 cmd, addr, flag, l);
8368 mutex_exit(sc->sc_lock);
8369 } else
8370 error = EINVAL;
8371 break;
8372 }
8373 TRACE(2, "(%lu,'%c',%lu) result %d",
8374 IOCPARM_LEN(cmd), (char)IOCGROUP(cmd), cmd & 0xff, error);
8375 return error;
8376 }
8377
8378 /*
8379 * Must be called with sc_lock held.
8380 */
8381 int
8382 au_portof(struct audio_softc *sc, char *name, int class)
8383 {
8384 mixer_devinfo_t mi;
8385
8386 KASSERT(mutex_owned(sc->sc_lock));
8387
8388 for (mi.index = 0; audio_query_devinfo(sc, &mi) == 0; mi.index++) {
8389 if (mi.mixer_class == class && strcmp(mi.label.name, name) == 0)
8390 return mi.index;
8391 }
8392 return -1;
8393 }
8394
8395 /*
8396 * Must be called with sc_lock held.
8397 */
8398 void
8399 au_setup_ports(struct audio_softc *sc, struct au_mixer_ports *ports,
8400 mixer_devinfo_t *mi, const struct portname *tbl)
8401 {
8402 int i, j;
8403
8404 KASSERT(mutex_owned(sc->sc_lock));
8405
8406 ports->index = mi->index;
8407 if (mi->type == AUDIO_MIXER_ENUM) {
8408 ports->isenum = true;
8409 for(i = 0; tbl[i].name; i++)
8410 for(j = 0; j < mi->un.e.num_mem; j++)
8411 if (strcmp(mi->un.e.member[j].label.name,
8412 tbl[i].name) == 0) {
8413 ports->allports |= tbl[i].mask;
8414 ports->aumask[ports->nports] = tbl[i].mask;
8415 ports->misel[ports->nports] =
8416 mi->un.e.member[j].ord;
8417 ports->miport[ports->nports] =
8418 au_portof(sc, mi->un.e.member[j].label.name,
8419 mi->mixer_class);
8420 if (ports->mixerout != -1 &&
8421 ports->miport[ports->nports] != -1)
8422 ports->isdual = true;
8423 ++ports->nports;
8424 }
8425 } else if (mi->type == AUDIO_MIXER_SET) {
8426 for(i = 0; tbl[i].name; i++)
8427 for(j = 0; j < mi->un.s.num_mem; j++)
8428 if (strcmp(mi->un.s.member[j].label.name,
8429 tbl[i].name) == 0) {
8430 ports->allports |= tbl[i].mask;
8431 ports->aumask[ports->nports] = tbl[i].mask;
8432 ports->misel[ports->nports] =
8433 mi->un.s.member[j].mask;
8434 ports->miport[ports->nports] =
8435 au_portof(sc, mi->un.s.member[j].label.name,
8436 mi->mixer_class);
8437 ++ports->nports;
8438 }
8439 }
8440 }
8441
8442 /*
8443 * Must be called with sc_lock && sc_exlock held.
8444 */
8445 int
8446 au_set_lr_value(struct audio_softc *sc, mixer_ctrl_t *ct, int l, int r)
8447 {
8448
8449 KASSERT(mutex_owned(sc->sc_lock));
8450 KASSERT(sc->sc_exlock);
8451
8452 ct->type = AUDIO_MIXER_VALUE;
8453 ct->un.value.num_channels = 2;
8454 ct->un.value.level[AUDIO_MIXER_LEVEL_LEFT] = l;
8455 ct->un.value.level[AUDIO_MIXER_LEVEL_RIGHT] = r;
8456 if (audio_set_port(sc, ct) == 0)
8457 return 0;
8458 ct->un.value.num_channels = 1;
8459 ct->un.value.level[AUDIO_MIXER_LEVEL_MONO] = (l+r)/2;
8460 return audio_set_port(sc, ct);
8461 }
8462
8463 /*
8464 * Must be called with sc_lock && sc_exlock held.
8465 */
8466 int
8467 au_get_lr_value(struct audio_softc *sc, mixer_ctrl_t *ct, int *l, int *r)
8468 {
8469 int error;
8470
8471 KASSERT(mutex_owned(sc->sc_lock));
8472 KASSERT(sc->sc_exlock);
8473
8474 ct->un.value.num_channels = 2;
8475 if (audio_get_port(sc, ct) == 0) {
8476 *l = ct->un.value.level[AUDIO_MIXER_LEVEL_LEFT];
8477 *r = ct->un.value.level[AUDIO_MIXER_LEVEL_RIGHT];
8478 } else {
8479 ct->un.value.num_channels = 1;
8480 error = audio_get_port(sc, ct);
8481 if (error)
8482 return error;
8483 *r = *l = ct->un.value.level[AUDIO_MIXER_LEVEL_MONO];
8484 }
8485 return 0;
8486 }
8487
8488 /*
8489 * Must be called with sc_lock && sc_exlock held.
8490 */
8491 int
8492 au_set_gain(struct audio_softc *sc, struct au_mixer_ports *ports,
8493 int gain, int balance)
8494 {
8495 mixer_ctrl_t ct;
8496 int i, error;
8497 int l, r;
8498 u_int mask;
8499 int nset;
8500
8501 KASSERT(mutex_owned(sc->sc_lock));
8502 KASSERT(sc->sc_exlock);
8503
8504 if (balance == AUDIO_MID_BALANCE) {
8505 l = r = gain;
8506 } else if (balance < AUDIO_MID_BALANCE) {
8507 l = gain;
8508 r = (balance * gain) / AUDIO_MID_BALANCE;
8509 } else {
8510 r = gain;
8511 l = ((AUDIO_RIGHT_BALANCE - balance) * gain)
8512 / AUDIO_MID_BALANCE;
8513 }
8514 TRACE(2, "gain=%d balance=%d, l=%d r=%d", gain, balance, l, r);
8515
8516 if (ports->index == -1) {
8517 usemaster:
8518 if (ports->master == -1)
8519 return 0; /* just ignore it silently */
8520 ct.dev = ports->master;
8521 error = au_set_lr_value(sc, &ct, l, r);
8522 } else {
8523 ct.dev = ports->index;
8524 if (ports->isenum) {
8525 ct.type = AUDIO_MIXER_ENUM;
8526 error = audio_get_port(sc, &ct);
8527 if (error)
8528 return error;
8529 if (ports->isdual) {
8530 if (ports->cur_port == -1)
8531 ct.dev = ports->master;
8532 else
8533 ct.dev = ports->miport[ports->cur_port];
8534 error = au_set_lr_value(sc, &ct, l, r);
8535 } else {
8536 for(i = 0; i < ports->nports; i++)
8537 if (ports->misel[i] == ct.un.ord) {
8538 ct.dev = ports->miport[i];
8539 if (ct.dev == -1 ||
8540 au_set_lr_value(sc, &ct, l, r))
8541 goto usemaster;
8542 else
8543 break;
8544 }
8545 }
8546 } else {
8547 ct.type = AUDIO_MIXER_SET;
8548 error = audio_get_port(sc, &ct);
8549 if (error)
8550 return error;
8551 mask = ct.un.mask;
8552 nset = 0;
8553 for(i = 0; i < ports->nports; i++) {
8554 if (ports->misel[i] & mask) {
8555 ct.dev = ports->miport[i];
8556 if (ct.dev != -1 &&
8557 au_set_lr_value(sc, &ct, l, r) == 0)
8558 nset++;
8559 }
8560 }
8561 if (nset == 0)
8562 goto usemaster;
8563 }
8564 }
8565 if (!error)
8566 mixer_signal(sc);
8567 return error;
8568 }
8569
8570 /*
8571 * Must be called with sc_lock && sc_exlock held.
8572 */
8573 void
8574 au_get_gain(struct audio_softc *sc, struct au_mixer_ports *ports,
8575 u_int *pgain, u_char *pbalance)
8576 {
8577 mixer_ctrl_t ct;
8578 int i, l, r, n;
8579 int lgain, rgain;
8580
8581 KASSERT(mutex_owned(sc->sc_lock));
8582 KASSERT(sc->sc_exlock);
8583
8584 lgain = AUDIO_MAX_GAIN / 2;
8585 rgain = AUDIO_MAX_GAIN / 2;
8586 if (ports->index == -1) {
8587 usemaster:
8588 if (ports->master == -1)
8589 goto bad;
8590 ct.dev = ports->master;
8591 ct.type = AUDIO_MIXER_VALUE;
8592 if (au_get_lr_value(sc, &ct, &lgain, &rgain))
8593 goto bad;
8594 } else {
8595 ct.dev = ports->index;
8596 if (ports->isenum) {
8597 ct.type = AUDIO_MIXER_ENUM;
8598 if (audio_get_port(sc, &ct))
8599 goto bad;
8600 ct.type = AUDIO_MIXER_VALUE;
8601 if (ports->isdual) {
8602 if (ports->cur_port == -1)
8603 ct.dev = ports->master;
8604 else
8605 ct.dev = ports->miport[ports->cur_port];
8606 au_get_lr_value(sc, &ct, &lgain, &rgain);
8607 } else {
8608 for(i = 0; i < ports->nports; i++)
8609 if (ports->misel[i] == ct.un.ord) {
8610 ct.dev = ports->miport[i];
8611 if (ct.dev == -1 ||
8612 au_get_lr_value(sc, &ct,
8613 &lgain, &rgain))
8614 goto usemaster;
8615 else
8616 break;
8617 }
8618 }
8619 } else {
8620 ct.type = AUDIO_MIXER_SET;
8621 if (audio_get_port(sc, &ct))
8622 goto bad;
8623 ct.type = AUDIO_MIXER_VALUE;
8624 lgain = rgain = n = 0;
8625 for(i = 0; i < ports->nports; i++) {
8626 if (ports->misel[i] & ct.un.mask) {
8627 ct.dev = ports->miport[i];
8628 if (ct.dev == -1 ||
8629 au_get_lr_value(sc, &ct, &l, &r))
8630 goto usemaster;
8631 else {
8632 lgain += l;
8633 rgain += r;
8634 n++;
8635 }
8636 }
8637 }
8638 if (n != 0) {
8639 lgain /= n;
8640 rgain /= n;
8641 }
8642 }
8643 }
8644 bad:
8645 if (lgain == rgain) { /* handles lgain==rgain==0 */
8646 *pgain = lgain;
8647 *pbalance = AUDIO_MID_BALANCE;
8648 } else if (lgain < rgain) {
8649 *pgain = rgain;
8650 /* balance should be > AUDIO_MID_BALANCE */
8651 *pbalance = AUDIO_RIGHT_BALANCE -
8652 (AUDIO_MID_BALANCE * lgain) / rgain;
8653 } else /* lgain > rgain */ {
8654 *pgain = lgain;
8655 /* balance should be < AUDIO_MID_BALANCE */
8656 *pbalance = (AUDIO_MID_BALANCE * rgain) / lgain;
8657 }
8658 }
8659
8660 /*
8661 * Must be called with sc_lock && sc_exlock held.
8662 */
8663 int
8664 au_set_port(struct audio_softc *sc, struct au_mixer_ports *ports, u_int port)
8665 {
8666 mixer_ctrl_t ct;
8667 int i, error, use_mixerout;
8668
8669 KASSERT(mutex_owned(sc->sc_lock));
8670 KASSERT(sc->sc_exlock);
8671
8672 use_mixerout = 1;
8673 if (port == 0) {
8674 if (ports->allports == 0)
8675 return 0; /* Allow this special case. */
8676 else if (ports->isdual) {
8677 if (ports->cur_port == -1) {
8678 return 0;
8679 } else {
8680 port = ports->aumask[ports->cur_port];
8681 ports->cur_port = -1;
8682 use_mixerout = 0;
8683 }
8684 }
8685 }
8686 if (ports->index == -1)
8687 return EINVAL;
8688 ct.dev = ports->index;
8689 if (ports->isenum) {
8690 if (port & (port-1))
8691 return EINVAL; /* Only one port allowed */
8692 ct.type = AUDIO_MIXER_ENUM;
8693 error = EINVAL;
8694 for(i = 0; i < ports->nports; i++)
8695 if (ports->aumask[i] == port) {
8696 if (ports->isdual && use_mixerout) {
8697 ct.un.ord = ports->mixerout;
8698 ports->cur_port = i;
8699 } else {
8700 ct.un.ord = ports->misel[i];
8701 }
8702 error = audio_set_port(sc, &ct);
8703 break;
8704 }
8705 } else {
8706 ct.type = AUDIO_MIXER_SET;
8707 ct.un.mask = 0;
8708 for(i = 0; i < ports->nports; i++)
8709 if (ports->aumask[i] & port)
8710 ct.un.mask |= ports->misel[i];
8711 if (port != 0 && ct.un.mask == 0)
8712 error = EINVAL;
8713 else
8714 error = audio_set_port(sc, &ct);
8715 }
8716 if (!error)
8717 mixer_signal(sc);
8718 return error;
8719 }
8720
8721 /*
8722 * Must be called with sc_lock && sc_exlock held.
8723 */
8724 int
8725 au_get_port(struct audio_softc *sc, struct au_mixer_ports *ports)
8726 {
8727 mixer_ctrl_t ct;
8728 int i, aumask;
8729
8730 KASSERT(mutex_owned(sc->sc_lock));
8731 KASSERT(sc->sc_exlock);
8732
8733 if (ports->index == -1)
8734 return 0;
8735 ct.dev = ports->index;
8736 ct.type = ports->isenum ? AUDIO_MIXER_ENUM : AUDIO_MIXER_SET;
8737 if (audio_get_port(sc, &ct))
8738 return 0;
8739 aumask = 0;
8740 if (ports->isenum) {
8741 if (ports->isdual && ports->cur_port != -1) {
8742 if (ports->mixerout == ct.un.ord)
8743 aumask = ports->aumask[ports->cur_port];
8744 else
8745 ports->cur_port = -1;
8746 }
8747 if (aumask == 0)
8748 for(i = 0; i < ports->nports; i++)
8749 if (ports->misel[i] == ct.un.ord)
8750 aumask = ports->aumask[i];
8751 } else {
8752 for(i = 0; i < ports->nports; i++)
8753 if (ct.un.mask & ports->misel[i])
8754 aumask |= ports->aumask[i];
8755 }
8756 return aumask;
8757 }
8758
8759 /*
8760 * It returns 0 if success, otherwise errno.
8761 * Must be called only if sc->sc_monitor_port != -1.
8762 * Must be called with sc_lock && sc_exlock held.
8763 */
8764 static int
8765 au_set_monitor_gain(struct audio_softc *sc, int monitor_gain)
8766 {
8767 mixer_ctrl_t ct;
8768
8769 KASSERT(mutex_owned(sc->sc_lock));
8770 KASSERT(sc->sc_exlock);
8771
8772 ct.dev = sc->sc_monitor_port;
8773 ct.type = AUDIO_MIXER_VALUE;
8774 ct.un.value.num_channels = 1;
8775 ct.un.value.level[AUDIO_MIXER_LEVEL_MONO] = monitor_gain;
8776 return audio_set_port(sc, &ct);
8777 }
8778
8779 /*
8780 * It returns monitor gain if success, otherwise -1.
8781 * Must be called only if sc->sc_monitor_port != -1.
8782 * Must be called with sc_lock && sc_exlock held.
8783 */
8784 static int
8785 au_get_monitor_gain(struct audio_softc *sc)
8786 {
8787 mixer_ctrl_t ct;
8788
8789 KASSERT(mutex_owned(sc->sc_lock));
8790 KASSERT(sc->sc_exlock);
8791
8792 ct.dev = sc->sc_monitor_port;
8793 ct.type = AUDIO_MIXER_VALUE;
8794 ct.un.value.num_channels = 1;
8795 if (audio_get_port(sc, &ct))
8796 return -1;
8797 return ct.un.value.level[AUDIO_MIXER_LEVEL_MONO];
8798 }
8799
8800 /*
8801 * Must be called with sc_lock && sc_exlock held.
8802 */
8803 static int
8804 audio_set_port(struct audio_softc *sc, mixer_ctrl_t *mc)
8805 {
8806
8807 KASSERT(mutex_owned(sc->sc_lock));
8808 KASSERT(sc->sc_exlock);
8809
8810 return sc->hw_if->set_port(sc->hw_hdl, mc);
8811 }
8812
8813 /*
8814 * Must be called with sc_lock && sc_exlock held.
8815 */
8816 static int
8817 audio_get_port(struct audio_softc *sc, mixer_ctrl_t *mc)
8818 {
8819
8820 KASSERT(mutex_owned(sc->sc_lock));
8821 KASSERT(sc->sc_exlock);
8822
8823 return sc->hw_if->get_port(sc->hw_hdl, mc);
8824 }
8825
8826 /*
8827 * Must be called with sc_lock && sc_exlock held.
8828 */
8829 static void
8830 audio_mixer_capture(struct audio_softc *sc)
8831 {
8832 mixer_devinfo_t mi;
8833 mixer_ctrl_t *mc;
8834
8835 KASSERT(mutex_owned(sc->sc_lock));
8836 KASSERT(sc->sc_exlock);
8837
8838 for (mi.index = 0;; mi.index++) {
8839 if (audio_query_devinfo(sc, &mi) != 0)
8840 break;
8841 KASSERT(mi.index < sc->sc_nmixer_states);
8842 if (mi.type == AUDIO_MIXER_CLASS)
8843 continue;
8844 mc = &sc->sc_mixer_state[mi.index];
8845 mc->dev = mi.index;
8846 mc->type = mi.type;
8847 mc->un.value.num_channels = mi.un.v.num_channels;
8848 (void)audio_get_port(sc, mc);
8849 }
8850
8851 return;
8852 }
8853
8854 /*
8855 * Must be called with sc_lock && sc_exlock held.
8856 */
8857 static void
8858 audio_mixer_restore(struct audio_softc *sc)
8859 {
8860 mixer_devinfo_t mi;
8861 mixer_ctrl_t *mc;
8862
8863 KASSERT(mutex_owned(sc->sc_lock));
8864 KASSERT(sc->sc_exlock);
8865
8866 for (mi.index = 0; ; mi.index++) {
8867 if (audio_query_devinfo(sc, &mi) != 0)
8868 break;
8869 if (mi.type == AUDIO_MIXER_CLASS)
8870 continue;
8871 mc = &sc->sc_mixer_state[mi.index];
8872 (void)audio_set_port(sc, mc);
8873 }
8874 if (sc->hw_if->commit_settings)
8875 sc->hw_if->commit_settings(sc->hw_hdl);
8876
8877 return;
8878 }
8879
8880 static void
8881 audio_volume_down(device_t dv)
8882 {
8883 struct audio_softc *sc = device_private(dv);
8884 mixer_devinfo_t mi;
8885 int newgain;
8886 u_int gain;
8887 u_char balance;
8888
8889 if (audio_exlock_mutex_enter(sc) != 0)
8890 return;
8891 if (sc->sc_outports.index == -1 && sc->sc_outports.master != -1) {
8892 mi.index = sc->sc_outports.master;
8893 mi.un.v.delta = 0;
8894 if (audio_query_devinfo(sc, &mi) == 0) {
8895 au_get_gain(sc, &sc->sc_outports, &gain, &balance);
8896 newgain = gain - mi.un.v.delta;
8897 if (newgain < AUDIO_MIN_GAIN)
8898 newgain = AUDIO_MIN_GAIN;
8899 au_set_gain(sc, &sc->sc_outports, newgain, balance);
8900 }
8901 }
8902 audio_exlock_mutex_exit(sc);
8903 }
8904
8905 static void
8906 audio_volume_up(device_t dv)
8907 {
8908 struct audio_softc *sc = device_private(dv);
8909 mixer_devinfo_t mi;
8910 u_int gain, newgain;
8911 u_char balance;
8912
8913 if (audio_exlock_mutex_enter(sc) != 0)
8914 return;
8915 if (sc->sc_outports.index == -1 && sc->sc_outports.master != -1) {
8916 mi.index = sc->sc_outports.master;
8917 mi.un.v.delta = 0;
8918 if (audio_query_devinfo(sc, &mi) == 0) {
8919 au_get_gain(sc, &sc->sc_outports, &gain, &balance);
8920 newgain = gain + mi.un.v.delta;
8921 if (newgain > AUDIO_MAX_GAIN)
8922 newgain = AUDIO_MAX_GAIN;
8923 au_set_gain(sc, &sc->sc_outports, newgain, balance);
8924 }
8925 }
8926 audio_exlock_mutex_exit(sc);
8927 }
8928
8929 static void
8930 audio_volume_toggle(device_t dv)
8931 {
8932 struct audio_softc *sc = device_private(dv);
8933 u_int gain, newgain;
8934 u_char balance;
8935
8936 if (audio_exlock_mutex_enter(sc) != 0)
8937 return;
8938 au_get_gain(sc, &sc->sc_outports, &gain, &balance);
8939 if (gain != 0) {
8940 sc->sc_lastgain = gain;
8941 newgain = 0;
8942 } else
8943 newgain = sc->sc_lastgain;
8944 au_set_gain(sc, &sc->sc_outports, newgain, balance);
8945 audio_exlock_mutex_exit(sc);
8946 }
8947
8948 /*
8949 * Must be called with sc_lock held.
8950 */
8951 static int
8952 audio_query_devinfo(struct audio_softc *sc, mixer_devinfo_t *di)
8953 {
8954
8955 KASSERT(mutex_owned(sc->sc_lock));
8956
8957 return sc->hw_if->query_devinfo(sc->hw_hdl, di);
8958 }
8959
8960 #endif /* NAUDIO > 0 */
8961
8962 #if NAUDIO == 0 && (NMIDI > 0 || NMIDIBUS > 0)
8963 #include <sys/param.h>
8964 #include <sys/systm.h>
8965 #include <sys/device.h>
8966 #include <sys/audioio.h>
8967 #include <dev/audio/audio_if.h>
8968 #endif
8969
8970 #if NAUDIO > 0 || (NMIDI > 0 || NMIDIBUS > 0)
8971 int
8972 audioprint(void *aux, const char *pnp)
8973 {
8974 struct audio_attach_args *arg;
8975 const char *type;
8976
8977 if (pnp != NULL) {
8978 arg = aux;
8979 switch (arg->type) {
8980 case AUDIODEV_TYPE_AUDIO:
8981 type = "audio";
8982 break;
8983 case AUDIODEV_TYPE_MIDI:
8984 type = "midi";
8985 break;
8986 case AUDIODEV_TYPE_OPL:
8987 type = "opl";
8988 break;
8989 case AUDIODEV_TYPE_MPU:
8990 type = "mpu";
8991 break;
8992 case AUDIODEV_TYPE_AUX:
8993 type = "aux";
8994 break;
8995 default:
8996 panic("audioprint: unknown type %d", arg->type);
8997 }
8998 aprint_normal("%s at %s", type, pnp);
8999 }
9000 return UNCONF;
9001 }
9002
9003 #endif /* NAUDIO > 0 || (NMIDI > 0 || NMIDIBUS > 0) */
9004
9005 #ifdef _MODULE
9006
9007 devmajor_t audio_bmajor = -1, audio_cmajor = -1;
9008
9009 #include "ioconf.c"
9010
9011 #endif
9012
9013 MODULE(MODULE_CLASS_DRIVER, audio, NULL);
9014
9015 static int
9016 audio_modcmd(modcmd_t cmd, void *arg)
9017 {
9018 int error = 0;
9019
9020 switch (cmd) {
9021 case MODULE_CMD_INIT:
9022 /* XXX interrupt level? */
9023 audio_psref_class = psref_class_create("audio", IPL_SOFTSERIAL);
9024 #ifdef _MODULE
9025 error = devsw_attach(audio_cd.cd_name, NULL, &audio_bmajor,
9026 &audio_cdevsw, &audio_cmajor);
9027 if (error)
9028 break;
9029
9030 error = config_init_component(cfdriver_ioconf_audio,
9031 cfattach_ioconf_audio, cfdata_ioconf_audio);
9032 if (error) {
9033 devsw_detach(NULL, &audio_cdevsw);
9034 }
9035 #endif
9036 break;
9037 case MODULE_CMD_FINI:
9038 #ifdef _MODULE
9039 devsw_detach(NULL, &audio_cdevsw);
9040 error = config_fini_component(cfdriver_ioconf_audio,
9041 cfattach_ioconf_audio, cfdata_ioconf_audio);
9042 if (error)
9043 devsw_attach(audio_cd.cd_name, NULL, &audio_bmajor,
9044 &audio_cdevsw, &audio_cmajor);
9045 #endif
9046 psref_class_destroy(audio_psref_class);
9047 break;
9048 default:
9049 error = ENOTTY;
9050 break;
9051 }
9052
9053 return error;
9054 }
9055