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