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