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