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