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