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