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