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