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