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