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