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