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