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