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