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