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