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