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