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