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