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