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