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