Home | History | Annotate | Line # | Download | only in audio
audio.c revision 1.47
      1 /*	$NetBSD: audio.c,v 1.47 2020/02/22 06:58:39 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.47 2020/02/22 06:58:39 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 		KASSERTMSG(error == EMOVEFD, "error=%d", error);
   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 	KASSERTMSG(error == EMOVEFD, "error=%d", error);
   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 	KASSERTMSG(arg->srcfmt->channels == arg->dstfmt->channels,
   3217 	    "arg->srcfmt->channels=%d, arg->dstfmt->channels=%d",
   3218 	    arg->srcfmt->channels, arg->dstfmt->channels);
   3219 	KASSERT(arg->context != NULL);
   3220 	KASSERTMSG(arg->srcfmt->channels <= AUDIO_MAX_CHANNELS,
   3221 	    "arg->srcfmt->channels=%d", arg->srcfmt->channels);
   3222 
   3223 	s = arg->src;
   3224 	d = arg->dst;
   3225 	ch_volume = arg->context;
   3226 
   3227 	channels = arg->srcfmt->channels;
   3228 	for (i = 0; i < arg->count; i++) {
   3229 		for (ch = 0; ch < channels; ch++) {
   3230 			aint2_t val;
   3231 			val = *s++;
   3232 			val = AUDIO_SCALEDOWN(val * ch_volume[ch], 8);
   3233 			*d++ = (aint_t)val;
   3234 		}
   3235 	}
   3236 }
   3237 
   3238 /*
   3239  * This filter performs conversion from stereo (or more channels) to mono.
   3240  */
   3241 static void
   3242 audio_track_chmix_mixLR(audio_filter_arg_t *arg)
   3243 {
   3244 	const aint_t *s;
   3245 	aint_t *d;
   3246 	u_int i;
   3247 
   3248 	DIAGNOSTIC_filter_arg(arg);
   3249 
   3250 	s = arg->src;
   3251 	d = arg->dst;
   3252 
   3253 	for (i = 0; i < arg->count; i++) {
   3254 		*d++ = AUDIO_SCALEDOWN(s[0], 1) + AUDIO_SCALEDOWN(s[1], 1);
   3255 		s += arg->srcfmt->channels;
   3256 	}
   3257 }
   3258 
   3259 /*
   3260  * This filter performs conversion from mono to stereo (or more channels).
   3261  */
   3262 static void
   3263 audio_track_chmix_dupLR(audio_filter_arg_t *arg)
   3264 {
   3265 	const aint_t *s;
   3266 	aint_t *d;
   3267 	u_int i;
   3268 	u_int ch;
   3269 	u_int dstchannels;
   3270 
   3271 	DIAGNOSTIC_filter_arg(arg);
   3272 
   3273 	s = arg->src;
   3274 	d = arg->dst;
   3275 	dstchannels = arg->dstfmt->channels;
   3276 
   3277 	for (i = 0; i < arg->count; i++) {
   3278 		d[0] = s[0];
   3279 		d[1] = s[0];
   3280 		s++;
   3281 		d += dstchannels;
   3282 	}
   3283 	if (dstchannels > 2) {
   3284 		d = arg->dst;
   3285 		for (i = 0; i < arg->count; i++) {
   3286 			for (ch = 2; ch < dstchannels; ch++) {
   3287 				d[ch] = 0;
   3288 			}
   3289 			d += dstchannels;
   3290 		}
   3291 	}
   3292 }
   3293 
   3294 /*
   3295  * This filter shrinks M channels into N channels.
   3296  * Extra channels are discarded.
   3297  */
   3298 static void
   3299 audio_track_chmix_shrink(audio_filter_arg_t *arg)
   3300 {
   3301 	const aint_t *s;
   3302 	aint_t *d;
   3303 	u_int i;
   3304 	u_int ch;
   3305 
   3306 	DIAGNOSTIC_filter_arg(arg);
   3307 
   3308 	s = arg->src;
   3309 	d = arg->dst;
   3310 
   3311 	for (i = 0; i < arg->count; i++) {
   3312 		for (ch = 0; ch < arg->dstfmt->channels; ch++) {
   3313 			*d++ = s[ch];
   3314 		}
   3315 		s += arg->srcfmt->channels;
   3316 	}
   3317 }
   3318 
   3319 /*
   3320  * This filter expands M channels into N channels.
   3321  * Silence is inserted for missing channels.
   3322  */
   3323 static void
   3324 audio_track_chmix_expand(audio_filter_arg_t *arg)
   3325 {
   3326 	const aint_t *s;
   3327 	aint_t *d;
   3328 	u_int i;
   3329 	u_int ch;
   3330 	u_int srcchannels;
   3331 	u_int dstchannels;
   3332 
   3333 	DIAGNOSTIC_filter_arg(arg);
   3334 
   3335 	s = arg->src;
   3336 	d = arg->dst;
   3337 
   3338 	srcchannels = arg->srcfmt->channels;
   3339 	dstchannels = arg->dstfmt->channels;
   3340 	for (i = 0; i < arg->count; i++) {
   3341 		for (ch = 0; ch < srcchannels; ch++) {
   3342 			*d++ = *s++;
   3343 		}
   3344 		for (; ch < dstchannels; ch++) {
   3345 			*d++ = 0;
   3346 		}
   3347 	}
   3348 }
   3349 
   3350 /*
   3351  * This filter performs frequency conversion (up sampling).
   3352  * It uses linear interpolation.
   3353  */
   3354 static void
   3355 audio_track_freq_up(audio_filter_arg_t *arg)
   3356 {
   3357 	audio_track_t *track;
   3358 	audio_ring_t *src;
   3359 	audio_ring_t *dst;
   3360 	const aint_t *s;
   3361 	aint_t *d;
   3362 	aint_t prev[AUDIO_MAX_CHANNELS];
   3363 	aint_t curr[AUDIO_MAX_CHANNELS];
   3364 	aint_t grad[AUDIO_MAX_CHANNELS];
   3365 	u_int i;
   3366 	u_int t;
   3367 	u_int step;
   3368 	u_int channels;
   3369 	u_int ch;
   3370 	int srcused;
   3371 
   3372 	track = arg->context;
   3373 	KASSERT(track);
   3374 	src = &track->freq.srcbuf;
   3375 	dst = track->freq.dst;
   3376 	DIAGNOSTIC_ring(dst);
   3377 	DIAGNOSTIC_ring(src);
   3378 	KASSERT(src->used > 0);
   3379 	KASSERTMSG(src->fmt.channels == dst->fmt.channels,
   3380 	    "src->fmt.channels=%d dst->fmt.channels=%d",
   3381 	    src->fmt.channels, dst->fmt.channels);
   3382 	KASSERTMSG(src->head % track->mixer->frames_per_block == 0,
   3383 	    "src->head=%d track->mixer->frames_per_block=%d",
   3384 	    src->head, track->mixer->frames_per_block);
   3385 
   3386 	s = arg->src;
   3387 	d = arg->dst;
   3388 
   3389 	/*
   3390 	 * In order to faciliate interpolation for each block, slide (delay)
   3391 	 * input by one sample.  As a result, strictly speaking, the output
   3392 	 * phase is delayed by 1/dstfreq.  However, I believe there is no
   3393 	 * observable impact.
   3394 	 *
   3395 	 * Example)
   3396 	 * srcfreq:dstfreq = 1:3
   3397 	 *
   3398 	 *  A - -
   3399 	 *  |
   3400 	 *  |
   3401 	 *  |     B - -
   3402 	 *  +-----+-----> input timeframe
   3403 	 *  0     1
   3404 	 *
   3405 	 *  0     1
   3406 	 *  +-----+-----> input timeframe
   3407 	 *  |     A
   3408 	 *  |   x   x
   3409 	 *  | x       x
   3410 	 *  x          (B)
   3411 	 *  +-+-+-+-+-+-> output timeframe
   3412 	 *  0 1 2 3 4 5
   3413 	 */
   3414 
   3415 	/* Last samples in previous block */
   3416 	channels = src->fmt.channels;
   3417 	for (ch = 0; ch < channels; ch++) {
   3418 		prev[ch] = track->freq_prev[ch];
   3419 		curr[ch] = track->freq_curr[ch];
   3420 		grad[ch] = curr[ch] - prev[ch];
   3421 	}
   3422 
   3423 	step = track->freq_step;
   3424 	t = track->freq_current;
   3425 //#define FREQ_DEBUG
   3426 #if defined(FREQ_DEBUG)
   3427 #define PRINTF(fmt...)	printf(fmt)
   3428 #else
   3429 #define PRINTF(fmt...)	do { } while (0)
   3430 #endif
   3431 	srcused = src->used;
   3432 	PRINTF("upstart step=%d leap=%d", step, track->freq_leap);
   3433 	PRINTF(" srcused=%d arg->count=%u", src->used, arg->count);
   3434 	PRINTF(" prev=%d curr=%d grad=%d", prev[0], curr[0], grad[0]);
   3435 	PRINTF(" t=%d\n", t);
   3436 
   3437 	for (i = 0; i < arg->count; i++) {
   3438 		PRINTF("i=%d t=%5d", i, t);
   3439 		if (t >= 65536) {
   3440 			for (ch = 0; ch < channels; ch++) {
   3441 				prev[ch] = curr[ch];
   3442 				curr[ch] = *s++;
   3443 				grad[ch] = curr[ch] - prev[ch];
   3444 			}
   3445 			PRINTF(" prev=%d s[%d]=%d",
   3446 			    prev[0], src->used - srcused, curr[0]);
   3447 
   3448 			/* Update */
   3449 			t -= 65536;
   3450 			srcused--;
   3451 			if (srcused < 0) {
   3452 				PRINTF(" break\n");
   3453 				break;
   3454 			}
   3455 		}
   3456 
   3457 		for (ch = 0; ch < channels; ch++) {
   3458 			*d++ = prev[ch] + (aint2_t)grad[ch] * t / 65536;
   3459 #if defined(FREQ_DEBUG)
   3460 			if (ch == 0)
   3461 				printf(" t=%5d *d=%d", t, d[-1]);
   3462 #endif
   3463 		}
   3464 		t += step;
   3465 
   3466 		PRINTF("\n");
   3467 	}
   3468 	PRINTF("end prev=%d curr=%d\n", prev[0], curr[0]);
   3469 
   3470 	auring_take(src, src->used);
   3471 	auring_push(dst, i);
   3472 
   3473 	/* Adjust */
   3474 	t += track->freq_leap;
   3475 
   3476 	track->freq_current = t;
   3477 	for (ch = 0; ch < channels; ch++) {
   3478 		track->freq_prev[ch] = prev[ch];
   3479 		track->freq_curr[ch] = curr[ch];
   3480 	}
   3481 }
   3482 
   3483 /*
   3484  * This filter performs frequency conversion (down sampling).
   3485  * It uses simple thinning.
   3486  */
   3487 static void
   3488 audio_track_freq_down(audio_filter_arg_t *arg)
   3489 {
   3490 	audio_track_t *track;
   3491 	audio_ring_t *src;
   3492 	audio_ring_t *dst;
   3493 	const aint_t *s0;
   3494 	aint_t *d;
   3495 	u_int i;
   3496 	u_int t;
   3497 	u_int step;
   3498 	u_int ch;
   3499 	u_int channels;
   3500 
   3501 	track = arg->context;
   3502 	KASSERT(track);
   3503 	src = &track->freq.srcbuf;
   3504 	dst = track->freq.dst;
   3505 
   3506 	DIAGNOSTIC_ring(dst);
   3507 	DIAGNOSTIC_ring(src);
   3508 	KASSERT(src->used > 0);
   3509 	KASSERTMSG(src->fmt.channels == dst->fmt.channels,
   3510 	    "src->fmt.channels=%d dst->fmt.channels=%d",
   3511 	    src->fmt.channels, dst->fmt.channels);
   3512 	KASSERTMSG(src->head % track->mixer->frames_per_block == 0,
   3513 	    "src->head=%d track->mixer->frames_per_block=%d",
   3514 	    src->head, track->mixer->frames_per_block);
   3515 
   3516 	s0 = arg->src;
   3517 	d = arg->dst;
   3518 	t = track->freq_current;
   3519 	step = track->freq_step;
   3520 	channels = dst->fmt.channels;
   3521 	PRINTF("downstart step=%d leap=%d", step, track->freq_leap);
   3522 	PRINTF(" srcused=%d arg->count=%u", src->used, arg->count);
   3523 	PRINTF(" t=%d\n", t);
   3524 
   3525 	for (i = 0; i < arg->count && t / 65536 < src->used; i++) {
   3526 		const aint_t *s;
   3527 		PRINTF("i=%4d t=%10d", i, t);
   3528 		s = s0 + (t / 65536) * channels;
   3529 		PRINTF(" s=%5ld", (s - s0) / channels);
   3530 		for (ch = 0; ch < channels; ch++) {
   3531 			if (ch == 0) PRINTF(" *s=%d", s[ch]);
   3532 			*d++ = s[ch];
   3533 		}
   3534 		PRINTF("\n");
   3535 		t += step;
   3536 	}
   3537 	t += track->freq_leap;
   3538 	PRINTF("end t=%d\n", t);
   3539 	auring_take(src, src->used);
   3540 	auring_push(dst, i);
   3541 	track->freq_current = t % 65536;
   3542 }
   3543 
   3544 /*
   3545  * Creates track and returns it.
   3546  */
   3547 audio_track_t *
   3548 audio_track_create(struct audio_softc *sc, audio_trackmixer_t *mixer)
   3549 {
   3550 	audio_track_t *track;
   3551 	static int newid = 0;
   3552 
   3553 	track = kmem_zalloc(sizeof(*track), KM_SLEEP);
   3554 
   3555 	track->id = newid++;
   3556 	track->mixer = mixer;
   3557 	track->mode = mixer->mode;
   3558 
   3559 	/* Do TRACE after id is assigned. */
   3560 	TRACET(3, track, "for %s",
   3561 	    mixer->mode == AUMODE_PLAY ? "playback" : "recording");
   3562 
   3563 #if defined(AUDIO_SUPPORT_TRACK_VOLUME)
   3564 	track->volume = 256;
   3565 #endif
   3566 	for (int i = 0; i < AUDIO_MAX_CHANNELS; i++) {
   3567 		track->ch_volume[i] = 256;
   3568 	}
   3569 
   3570 	return track;
   3571 }
   3572 
   3573 /*
   3574  * Release all resources of the track and track itself.
   3575  * track must not be NULL.  Don't specify the track within the file
   3576  * structure linked from sc->sc_files.
   3577  */
   3578 static void
   3579 audio_track_destroy(audio_track_t *track)
   3580 {
   3581 
   3582 	KASSERT(track);
   3583 
   3584 	audio_free_usrbuf(track);
   3585 	audio_free(track->codec.srcbuf.mem);
   3586 	audio_free(track->chvol.srcbuf.mem);
   3587 	audio_free(track->chmix.srcbuf.mem);
   3588 	audio_free(track->freq.srcbuf.mem);
   3589 	audio_free(track->outbuf.mem);
   3590 
   3591 	kmem_free(track, sizeof(*track));
   3592 }
   3593 
   3594 /*
   3595  * It returns encoding conversion filter according to src and dst format.
   3596  * If it is not a convertible pair, it returns NULL.  Either src or dst
   3597  * must be internal format.
   3598  */
   3599 static audio_filter_t
   3600 audio_track_get_codec(audio_track_t *track, const audio_format2_t *src,
   3601 	const audio_format2_t *dst)
   3602 {
   3603 
   3604 	if (audio_format2_is_internal(src)) {
   3605 		if (dst->encoding == AUDIO_ENCODING_ULAW) {
   3606 			return audio_internal_to_mulaw;
   3607 		} else if (dst->encoding == AUDIO_ENCODING_ALAW) {
   3608 			return audio_internal_to_alaw;
   3609 		} else if (audio_format2_is_linear(dst)) {
   3610 			switch (dst->stride) {
   3611 			case 8:
   3612 				return audio_internal_to_linear8;
   3613 			case 16:
   3614 				return audio_internal_to_linear16;
   3615 #if defined(AUDIO_SUPPORT_LINEAR24)
   3616 			case 24:
   3617 				return audio_internal_to_linear24;
   3618 #endif
   3619 			case 32:
   3620 				return audio_internal_to_linear32;
   3621 			default:
   3622 				TRACET(1, track, "unsupported %s stride %d",
   3623 				    "dst", dst->stride);
   3624 				goto abort;
   3625 			}
   3626 		}
   3627 	} else if (audio_format2_is_internal(dst)) {
   3628 		if (src->encoding == AUDIO_ENCODING_ULAW) {
   3629 			return audio_mulaw_to_internal;
   3630 		} else if (src->encoding == AUDIO_ENCODING_ALAW) {
   3631 			return audio_alaw_to_internal;
   3632 		} else if (audio_format2_is_linear(src)) {
   3633 			switch (src->stride) {
   3634 			case 8:
   3635 				return audio_linear8_to_internal;
   3636 			case 16:
   3637 				return audio_linear16_to_internal;
   3638 #if defined(AUDIO_SUPPORT_LINEAR24)
   3639 			case 24:
   3640 				return audio_linear24_to_internal;
   3641 #endif
   3642 			case 32:
   3643 				return audio_linear32_to_internal;
   3644 			default:
   3645 				TRACET(1, track, "unsupported %s stride %d",
   3646 				    "src", src->stride);
   3647 				goto abort;
   3648 			}
   3649 		}
   3650 	}
   3651 
   3652 	TRACET(1, track, "unsupported encoding");
   3653 abort:
   3654 #if defined(AUDIO_DEBUG)
   3655 	if (audiodebug >= 2) {
   3656 		char buf[100];
   3657 		audio_format2_tostr(buf, sizeof(buf), src);
   3658 		TRACET(2, track, "src %s", buf);
   3659 		audio_format2_tostr(buf, sizeof(buf), dst);
   3660 		TRACET(2, track, "dst %s", buf);
   3661 	}
   3662 #endif
   3663 	return NULL;
   3664 }
   3665 
   3666 /*
   3667  * Initialize the codec stage of this track as necessary.
   3668  * If successful, it initializes the codec stage as necessary, stores updated
   3669  * last_dst in *last_dstp in any case, and returns 0.
   3670  * Otherwise, it returns errno without modifying *last_dstp.
   3671  */
   3672 static int
   3673 audio_track_init_codec(audio_track_t *track, audio_ring_t **last_dstp)
   3674 {
   3675 	audio_ring_t *last_dst;
   3676 	audio_ring_t *srcbuf;
   3677 	audio_format2_t *srcfmt;
   3678 	audio_format2_t *dstfmt;
   3679 	audio_filter_arg_t *arg;
   3680 	u_int len;
   3681 	int error;
   3682 
   3683 	KASSERT(track);
   3684 
   3685 	last_dst = *last_dstp;
   3686 	dstfmt = &last_dst->fmt;
   3687 	srcfmt = &track->inputfmt;
   3688 	srcbuf = &track->codec.srcbuf;
   3689 	error = 0;
   3690 
   3691 	if (srcfmt->encoding != dstfmt->encoding
   3692 	 || srcfmt->precision != dstfmt->precision
   3693 	 || srcfmt->stride != dstfmt->stride) {
   3694 		track->codec.dst = last_dst;
   3695 
   3696 		srcbuf->fmt = *dstfmt;
   3697 		srcbuf->fmt.encoding = srcfmt->encoding;
   3698 		srcbuf->fmt.precision = srcfmt->precision;
   3699 		srcbuf->fmt.stride = srcfmt->stride;
   3700 
   3701 		track->codec.filter = audio_track_get_codec(track,
   3702 		    &srcbuf->fmt, dstfmt);
   3703 		if (track->codec.filter == NULL) {
   3704 			error = EINVAL;
   3705 			goto abort;
   3706 		}
   3707 
   3708 		srcbuf->head = 0;
   3709 		srcbuf->used = 0;
   3710 		srcbuf->capacity = frame_per_block(track->mixer, &srcbuf->fmt);
   3711 		len = auring_bytelen(srcbuf);
   3712 		srcbuf->mem = audio_realloc(srcbuf->mem, len);
   3713 
   3714 		arg = &track->codec.arg;
   3715 		arg->srcfmt = &srcbuf->fmt;
   3716 		arg->dstfmt = dstfmt;
   3717 		arg->context = NULL;
   3718 
   3719 		*last_dstp = srcbuf;
   3720 		return 0;
   3721 	}
   3722 
   3723 abort:
   3724 	track->codec.filter = NULL;
   3725 	audio_free(srcbuf->mem);
   3726 	return error;
   3727 }
   3728 
   3729 /*
   3730  * Initialize the chvol stage of this track as necessary.
   3731  * If successful, it initializes the chvol stage as necessary, stores updated
   3732  * last_dst in *last_dstp in any case, and returns 0.
   3733  * Otherwise, it returns errno without modifying *last_dstp.
   3734  */
   3735 static int
   3736 audio_track_init_chvol(audio_track_t *track, audio_ring_t **last_dstp)
   3737 {
   3738 	audio_ring_t *last_dst;
   3739 	audio_ring_t *srcbuf;
   3740 	audio_format2_t *srcfmt;
   3741 	audio_format2_t *dstfmt;
   3742 	audio_filter_arg_t *arg;
   3743 	u_int len;
   3744 	int error;
   3745 
   3746 	KASSERT(track);
   3747 
   3748 	last_dst = *last_dstp;
   3749 	dstfmt = &last_dst->fmt;
   3750 	srcfmt = &track->inputfmt;
   3751 	srcbuf = &track->chvol.srcbuf;
   3752 	error = 0;
   3753 
   3754 	/* Check whether channel volume conversion is necessary. */
   3755 	bool use_chvol = false;
   3756 	for (int ch = 0; ch < srcfmt->channels; ch++) {
   3757 		if (track->ch_volume[ch] != 256) {
   3758 			use_chvol = true;
   3759 			break;
   3760 		}
   3761 	}
   3762 
   3763 	if (use_chvol == true) {
   3764 		track->chvol.dst = last_dst;
   3765 		track->chvol.filter = audio_track_chvol;
   3766 
   3767 		srcbuf->fmt = *dstfmt;
   3768 		/* no format conversion occurs */
   3769 
   3770 		srcbuf->head = 0;
   3771 		srcbuf->used = 0;
   3772 		srcbuf->capacity = frame_per_block(track->mixer, &srcbuf->fmt);
   3773 		len = auring_bytelen(srcbuf);
   3774 		srcbuf->mem = audio_realloc(srcbuf->mem, len);
   3775 
   3776 		arg = &track->chvol.arg;
   3777 		arg->srcfmt = &srcbuf->fmt;
   3778 		arg->dstfmt = dstfmt;
   3779 		arg->context = track->ch_volume;
   3780 
   3781 		*last_dstp = srcbuf;
   3782 		return 0;
   3783 	}
   3784 
   3785 	track->chvol.filter = NULL;
   3786 	audio_free(srcbuf->mem);
   3787 	return error;
   3788 }
   3789 
   3790 /*
   3791  * Initialize the chmix stage of this track as necessary.
   3792  * If successful, it initializes the chmix stage as necessary, stores updated
   3793  * last_dst in *last_dstp in any case, and returns 0.
   3794  * Otherwise, it returns errno without modifying *last_dstp.
   3795  */
   3796 static int
   3797 audio_track_init_chmix(audio_track_t *track, audio_ring_t **last_dstp)
   3798 {
   3799 	audio_ring_t *last_dst;
   3800 	audio_ring_t *srcbuf;
   3801 	audio_format2_t *srcfmt;
   3802 	audio_format2_t *dstfmt;
   3803 	audio_filter_arg_t *arg;
   3804 	u_int srcch;
   3805 	u_int dstch;
   3806 	u_int len;
   3807 	int error;
   3808 
   3809 	KASSERT(track);
   3810 
   3811 	last_dst = *last_dstp;
   3812 	dstfmt = &last_dst->fmt;
   3813 	srcfmt = &track->inputfmt;
   3814 	srcbuf = &track->chmix.srcbuf;
   3815 	error = 0;
   3816 
   3817 	srcch = srcfmt->channels;
   3818 	dstch = dstfmt->channels;
   3819 	if (srcch != dstch) {
   3820 		track->chmix.dst = last_dst;
   3821 
   3822 		if (srcch >= 2 && dstch == 1) {
   3823 			track->chmix.filter = audio_track_chmix_mixLR;
   3824 		} else if (srcch == 1 && dstch >= 2) {
   3825 			track->chmix.filter = audio_track_chmix_dupLR;
   3826 		} else if (srcch > dstch) {
   3827 			track->chmix.filter = audio_track_chmix_shrink;
   3828 		} else {
   3829 			track->chmix.filter = audio_track_chmix_expand;
   3830 		}
   3831 
   3832 		srcbuf->fmt = *dstfmt;
   3833 		srcbuf->fmt.channels = srcch;
   3834 
   3835 		srcbuf->head = 0;
   3836 		srcbuf->used = 0;
   3837 		/* XXX The buffer size should be able to calculate. */
   3838 		srcbuf->capacity = frame_per_block(track->mixer, &srcbuf->fmt);
   3839 		len = auring_bytelen(srcbuf);
   3840 		srcbuf->mem = audio_realloc(srcbuf->mem, len);
   3841 
   3842 		arg = &track->chmix.arg;
   3843 		arg->srcfmt = &srcbuf->fmt;
   3844 		arg->dstfmt = dstfmt;
   3845 		arg->context = NULL;
   3846 
   3847 		*last_dstp = srcbuf;
   3848 		return 0;
   3849 	}
   3850 
   3851 	track->chmix.filter = NULL;
   3852 	audio_free(srcbuf->mem);
   3853 	return error;
   3854 }
   3855 
   3856 /*
   3857  * Initialize the freq stage of this track as necessary.
   3858  * If successful, it initializes the freq stage as necessary, stores updated
   3859  * last_dst in *last_dstp in any case, and returns 0.
   3860  * Otherwise, it returns errno without modifying *last_dstp.
   3861  */
   3862 static int
   3863 audio_track_init_freq(audio_track_t *track, audio_ring_t **last_dstp)
   3864 {
   3865 	audio_ring_t *last_dst;
   3866 	audio_ring_t *srcbuf;
   3867 	audio_format2_t *srcfmt;
   3868 	audio_format2_t *dstfmt;
   3869 	audio_filter_arg_t *arg;
   3870 	uint32_t srcfreq;
   3871 	uint32_t dstfreq;
   3872 	u_int dst_capacity;
   3873 	u_int mod;
   3874 	u_int len;
   3875 	int error;
   3876 
   3877 	KASSERT(track);
   3878 
   3879 	last_dst = *last_dstp;
   3880 	dstfmt = &last_dst->fmt;
   3881 	srcfmt = &track->inputfmt;
   3882 	srcbuf = &track->freq.srcbuf;
   3883 	error = 0;
   3884 
   3885 	srcfreq = srcfmt->sample_rate;
   3886 	dstfreq = dstfmt->sample_rate;
   3887 	if (srcfreq != dstfreq) {
   3888 		track->freq.dst = last_dst;
   3889 
   3890 		memset(track->freq_prev, 0, sizeof(track->freq_prev));
   3891 		memset(track->freq_curr, 0, sizeof(track->freq_curr));
   3892 
   3893 		/* freq_step is the ratio of src/dst when let dst 65536. */
   3894 		track->freq_step = (uint64_t)srcfreq * 65536 / dstfreq;
   3895 
   3896 		dst_capacity = frame_per_block(track->mixer, dstfmt);
   3897 		mod = (uint64_t)srcfreq * 65536 % dstfreq;
   3898 		track->freq_leap = (mod * dst_capacity + dstfreq / 2) / dstfreq;
   3899 
   3900 		if (track->freq_step < 65536) {
   3901 			track->freq.filter = audio_track_freq_up;
   3902 			/* In order to carry at the first time. */
   3903 			track->freq_current = 65536;
   3904 		} else {
   3905 			track->freq.filter = audio_track_freq_down;
   3906 			track->freq_current = 0;
   3907 		}
   3908 
   3909 		srcbuf->fmt = *dstfmt;
   3910 		srcbuf->fmt.sample_rate = srcfreq;
   3911 
   3912 		srcbuf->head = 0;
   3913 		srcbuf->used = 0;
   3914 		srcbuf->capacity = frame_per_block(track->mixer, &srcbuf->fmt);
   3915 		len = auring_bytelen(srcbuf);
   3916 		srcbuf->mem = audio_realloc(srcbuf->mem, len);
   3917 
   3918 		arg = &track->freq.arg;
   3919 		arg->srcfmt = &srcbuf->fmt;
   3920 		arg->dstfmt = dstfmt;/*&last_dst->fmt;*/
   3921 		arg->context = track;
   3922 
   3923 		*last_dstp = srcbuf;
   3924 		return 0;
   3925 	}
   3926 
   3927 	track->freq.filter = NULL;
   3928 	audio_free(srcbuf->mem);
   3929 	return error;
   3930 }
   3931 
   3932 /*
   3933  * When playing back: (e.g. if codec and freq stage are valid)
   3934  *
   3935  *               write
   3936  *                | uiomove
   3937  *                v
   3938  *  usrbuf      [...............]  byte ring buffer (mmap-able)
   3939  *                | memcpy
   3940  *                v
   3941  *  codec.srcbuf[....]             1 block (ring) buffer   <-- stage input
   3942  *       .dst ----+
   3943  *                | convert
   3944  *                v
   3945  *  freq.srcbuf [....]             1 block (ring) buffer
   3946  *      .dst  ----+
   3947  *                | convert
   3948  *                v
   3949  *  outbuf      [...............]  NBLKOUT blocks ring buffer
   3950  *
   3951  *
   3952  * When recording:
   3953  *
   3954  *  freq.srcbuf [...............]  NBLKOUT blocks ring buffer <-- stage input
   3955  *      .dst  ----+
   3956  *                | convert
   3957  *                v
   3958  *  codec.srcbuf[.....]            1 block (ring) buffer
   3959  *       .dst ----+
   3960  *                | convert
   3961  *                v
   3962  *  outbuf      [.....]            1 block (ring) buffer
   3963  *                | memcpy
   3964  *                v
   3965  *  usrbuf      [...............]  byte ring buffer (mmap-able *)
   3966  *                | uiomove
   3967  *                v
   3968  *               read
   3969  *
   3970  *    *: usrbuf for recording is also mmap-able due to symmetry with
   3971  *       playback buffer, but for now mmap will never happen for recording.
   3972  */
   3973 
   3974 /*
   3975  * Set the userland format of this track.
   3976  * usrfmt argument should be parameter verified with audio_check_params().
   3977  * It will release and reallocate all internal conversion buffers.
   3978  * It returns 0 if successful.  Otherwise it returns errno with clearing all
   3979  * internal buffers.
   3980  * It must be called without sc_intr_lock since uvm_* routines require non
   3981  * intr_lock state.
   3982  * It must be called with track lock held since it may release and reallocate
   3983  * outbuf.
   3984  */
   3985 static int
   3986 audio_track_set_format(audio_track_t *track, audio_format2_t *usrfmt)
   3987 {
   3988 	struct audio_softc *sc;
   3989 	u_int newbufsize;
   3990 	u_int oldblksize;
   3991 	u_int len;
   3992 	int error;
   3993 
   3994 	KASSERT(track);
   3995 	sc = track->mixer->sc;
   3996 
   3997 	/* usrbuf is the closest buffer to the userland. */
   3998 	track->usrbuf.fmt = *usrfmt;
   3999 
   4000 	/*
   4001 	 * For references, one block size (in 40msec) is:
   4002 	 *  320 bytes    = 204 blocks/64KB for mulaw/8kHz/1ch
   4003 	 *  7680 bytes   = 8 blocks/64KB for s16/48kHz/2ch
   4004 	 *  30720 bytes  = 90 KB/3blocks for s16/48kHz/8ch
   4005 	 *  61440 bytes  = 180 KB/3blocks for s16/96kHz/8ch
   4006 	 *  245760 bytes = 720 KB/3blocks for s32/192kHz/8ch
   4007 	 *
   4008 	 * For example,
   4009 	 * 1) If usrbuf_blksize = 7056 (s16/44.1k/2ch) and PAGE_SIZE = 8192,
   4010 	 *     newbufsize = rounddown(65536 / 7056) = 63504
   4011 	 *     newvsize = roundup2(63504, PAGE_SIZE) = 65536
   4012 	 *    Therefore it maps 8 * 8K pages and usrbuf->capacity = 63504.
   4013 	 *
   4014 	 * 2) If usrbuf_blksize = 7680 (s16/48k/2ch) and PAGE_SIZE = 4096,
   4015 	 *     newbufsize = rounddown(65536 / 7680) = 61440
   4016 	 *     newvsize = roundup2(61440, PAGE_SIZE) = 61440 (= 15 pages)
   4017 	 *    Therefore it maps 15 * 4K pages and usrbuf->capacity = 61440.
   4018 	 */
   4019 	oldblksize = track->usrbuf_blksize;
   4020 	track->usrbuf_blksize = frametobyte(&track->usrbuf.fmt,
   4021 	    frame_per_block(track->mixer, &track->usrbuf.fmt));
   4022 	track->usrbuf.head = 0;
   4023 	track->usrbuf.used = 0;
   4024 	newbufsize = MAX(track->usrbuf_blksize * AUMINNOBLK, 65536);
   4025 	newbufsize = rounddown(newbufsize, track->usrbuf_blksize);
   4026 	error = audio_realloc_usrbuf(track, newbufsize);
   4027 	if (error) {
   4028 		device_printf(sc->sc_dev, "malloc usrbuf(%d) failed\n",
   4029 		    newbufsize);
   4030 		goto error;
   4031 	}
   4032 
   4033 	/* Recalc water mark. */
   4034 	if (track->usrbuf_blksize != oldblksize) {
   4035 		if (audio_track_is_playback(track)) {
   4036 			/* Set high at 100%, low at 75%.  */
   4037 			track->usrbuf_usedhigh = track->usrbuf.capacity;
   4038 			track->usrbuf_usedlow = track->usrbuf.capacity * 3 / 4;
   4039 		} else {
   4040 			/* Set high at 100% minus 1block(?), low at 0% */
   4041 			track->usrbuf_usedhigh = track->usrbuf.capacity -
   4042 			    track->usrbuf_blksize;
   4043 			track->usrbuf_usedlow = 0;
   4044 		}
   4045 	}
   4046 
   4047 	/* Stage buffer */
   4048 	audio_ring_t *last_dst = &track->outbuf;
   4049 	if (audio_track_is_playback(track)) {
   4050 		/* On playback, initialize from the mixer side in order. */
   4051 		track->inputfmt = *usrfmt;
   4052 		track->outbuf.fmt =  track->mixer->track_fmt;
   4053 
   4054 		if ((error = audio_track_init_freq(track, &last_dst)) != 0)
   4055 			goto error;
   4056 		if ((error = audio_track_init_chmix(track, &last_dst)) != 0)
   4057 			goto error;
   4058 		if ((error = audio_track_init_chvol(track, &last_dst)) != 0)
   4059 			goto error;
   4060 		if ((error = audio_track_init_codec(track, &last_dst)) != 0)
   4061 			goto error;
   4062 	} else {
   4063 		/* On recording, initialize from userland side in order. */
   4064 		track->inputfmt = track->mixer->track_fmt;
   4065 		track->outbuf.fmt = *usrfmt;
   4066 
   4067 		if ((error = audio_track_init_codec(track, &last_dst)) != 0)
   4068 			goto error;
   4069 		if ((error = audio_track_init_chvol(track, &last_dst)) != 0)
   4070 			goto error;
   4071 		if ((error = audio_track_init_chmix(track, &last_dst)) != 0)
   4072 			goto error;
   4073 		if ((error = audio_track_init_freq(track, &last_dst)) != 0)
   4074 			goto error;
   4075 	}
   4076 #if 0
   4077 	/* debug */
   4078 	if (track->freq.filter) {
   4079 		audio_print_format2("freq src", &track->freq.srcbuf.fmt);
   4080 		audio_print_format2("freq dst", &track->freq.dst->fmt);
   4081 	}
   4082 	if (track->chmix.filter) {
   4083 		audio_print_format2("chmix src", &track->chmix.srcbuf.fmt);
   4084 		audio_print_format2("chmix dst", &track->chmix.dst->fmt);
   4085 	}
   4086 	if (track->chvol.filter) {
   4087 		audio_print_format2("chvol src", &track->chvol.srcbuf.fmt);
   4088 		audio_print_format2("chvol dst", &track->chvol.dst->fmt);
   4089 	}
   4090 	if (track->codec.filter) {
   4091 		audio_print_format2("codec src", &track->codec.srcbuf.fmt);
   4092 		audio_print_format2("codec dst", &track->codec.dst->fmt);
   4093 	}
   4094 #endif
   4095 
   4096 	/* Stage input buffer */
   4097 	track->input = last_dst;
   4098 
   4099 	/*
   4100 	 * On the recording track, make the first stage a ring buffer.
   4101 	 * XXX is there a better way?
   4102 	 */
   4103 	if (audio_track_is_record(track)) {
   4104 		track->input->capacity = NBLKOUT *
   4105 		    frame_per_block(track->mixer, &track->input->fmt);
   4106 		len = auring_bytelen(track->input);
   4107 		track->input->mem = audio_realloc(track->input->mem, len);
   4108 	}
   4109 
   4110 	/*
   4111 	 * Output buffer.
   4112 	 * On the playback track, its capacity is NBLKOUT blocks.
   4113 	 * On the recording track, its capacity is 1 block.
   4114 	 */
   4115 	track->outbuf.head = 0;
   4116 	track->outbuf.used = 0;
   4117 	track->outbuf.capacity = frame_per_block(track->mixer,
   4118 	    &track->outbuf.fmt);
   4119 	if (audio_track_is_playback(track))
   4120 		track->outbuf.capacity *= NBLKOUT;
   4121 	len = auring_bytelen(&track->outbuf);
   4122 	track->outbuf.mem = audio_realloc(track->outbuf.mem, len);
   4123 	if (track->outbuf.mem == NULL) {
   4124 		device_printf(sc->sc_dev, "malloc outbuf(%d) failed\n", len);
   4125 		error = ENOMEM;
   4126 		goto error;
   4127 	}
   4128 
   4129 #if defined(AUDIO_DEBUG)
   4130 	if (audiodebug >= 3) {
   4131 		struct audio_track_debugbuf m;
   4132 
   4133 		memset(&m, 0, sizeof(m));
   4134 		snprintf(m.outbuf, sizeof(m.outbuf), " out=%d",
   4135 		    track->outbuf.capacity * frametobyte(&track->outbuf.fmt,1));
   4136 		if (track->freq.filter)
   4137 			snprintf(m.freq, sizeof(m.freq), " freq=%d",
   4138 			    track->freq.srcbuf.capacity *
   4139 			    frametobyte(&track->freq.srcbuf.fmt, 1));
   4140 		if (track->chmix.filter)
   4141 			snprintf(m.chmix, sizeof(m.chmix), " chmix=%d",
   4142 			    track->chmix.srcbuf.capacity *
   4143 			    frametobyte(&track->chmix.srcbuf.fmt, 1));
   4144 		if (track->chvol.filter)
   4145 			snprintf(m.chvol, sizeof(m.chvol), " chvol=%d",
   4146 			    track->chvol.srcbuf.capacity *
   4147 			    frametobyte(&track->chvol.srcbuf.fmt, 1));
   4148 		if (track->codec.filter)
   4149 			snprintf(m.codec, sizeof(m.codec), " codec=%d",
   4150 			    track->codec.srcbuf.capacity *
   4151 			    frametobyte(&track->codec.srcbuf.fmt, 1));
   4152 		snprintf(m.usrbuf, sizeof(m.usrbuf),
   4153 		    " usr=%d", track->usrbuf.capacity);
   4154 
   4155 		if (audio_track_is_playback(track)) {
   4156 			TRACET(0, track, "bufsize%s%s%s%s%s%s",
   4157 			    m.outbuf, m.freq, m.chmix,
   4158 			    m.chvol, m.codec, m.usrbuf);
   4159 		} else {
   4160 			TRACET(0, track, "bufsize%s%s%s%s%s%s",
   4161 			    m.freq, m.chmix, m.chvol,
   4162 			    m.codec, m.outbuf, m.usrbuf);
   4163 		}
   4164 	}
   4165 #endif
   4166 	return 0;
   4167 
   4168 error:
   4169 	audio_free_usrbuf(track);
   4170 	audio_free(track->codec.srcbuf.mem);
   4171 	audio_free(track->chvol.srcbuf.mem);
   4172 	audio_free(track->chmix.srcbuf.mem);
   4173 	audio_free(track->freq.srcbuf.mem);
   4174 	audio_free(track->outbuf.mem);
   4175 	return error;
   4176 }
   4177 
   4178 /*
   4179  * Fill silence frames (as the internal format) up to 1 block
   4180  * if the ring is not empty and less than 1 block.
   4181  * It returns the number of appended frames.
   4182  */
   4183 static int
   4184 audio_append_silence(audio_track_t *track, audio_ring_t *ring)
   4185 {
   4186 	int fpb;
   4187 	int n;
   4188 
   4189 	KASSERT(track);
   4190 	KASSERT(audio_format2_is_internal(&ring->fmt));
   4191 
   4192 	/* XXX is n correct? */
   4193 	/* XXX memset uses frametobyte()? */
   4194 
   4195 	if (ring->used == 0)
   4196 		return 0;
   4197 
   4198 	fpb = frame_per_block(track->mixer, &ring->fmt);
   4199 	if (ring->used >= fpb)
   4200 		return 0;
   4201 
   4202 	n = (ring->capacity - ring->used) % fpb;
   4203 
   4204 	KASSERTMSG(auring_get_contig_free(ring) >= n,
   4205 	    "auring_get_contig_free(ring)=%d n=%d",
   4206 	    auring_get_contig_free(ring), n);
   4207 
   4208 	memset(auring_tailptr_aint(ring), 0,
   4209 	    n * ring->fmt.channels * sizeof(aint_t));
   4210 	auring_push(ring, n);
   4211 	return n;
   4212 }
   4213 
   4214 /*
   4215  * Execute the conversion stage.
   4216  * It prepares arg from this stage and executes stage->filter.
   4217  * It must be called only if stage->filter is not NULL.
   4218  *
   4219  * For stages other than frequency conversion, the function increments
   4220  * src and dst counters here.  For frequency conversion stage, on the
   4221  * other hand, the function does not touch src and dst counters and
   4222  * filter side has to increment them.
   4223  */
   4224 static void
   4225 audio_apply_stage(audio_track_t *track, audio_stage_t *stage, bool isfreq)
   4226 {
   4227 	audio_filter_arg_t *arg;
   4228 	int srccount;
   4229 	int dstcount;
   4230 	int count;
   4231 
   4232 	KASSERT(track);
   4233 	KASSERT(stage->filter);
   4234 
   4235 	srccount = auring_get_contig_used(&stage->srcbuf);
   4236 	dstcount = auring_get_contig_free(stage->dst);
   4237 
   4238 	if (isfreq) {
   4239 		KASSERTMSG(srccount > 0, "freq but srccount=%d", srccount);
   4240 		count = uimin(dstcount, track->mixer->frames_per_block);
   4241 	} else {
   4242 		count = uimin(srccount, dstcount);
   4243 	}
   4244 
   4245 	if (count > 0) {
   4246 		arg = &stage->arg;
   4247 		arg->src = auring_headptr(&stage->srcbuf);
   4248 		arg->dst = auring_tailptr(stage->dst);
   4249 		arg->count = count;
   4250 
   4251 		stage->filter(arg);
   4252 
   4253 		if (!isfreq) {
   4254 			auring_take(&stage->srcbuf, count);
   4255 			auring_push(stage->dst, count);
   4256 		}
   4257 	}
   4258 }
   4259 
   4260 /*
   4261  * Produce output buffer for playback from user input buffer.
   4262  * It must be called only if usrbuf is not empty and outbuf is
   4263  * available at least one free block.
   4264  */
   4265 static void
   4266 audio_track_play(audio_track_t *track)
   4267 {
   4268 	audio_ring_t *usrbuf;
   4269 	audio_ring_t *input;
   4270 	int count;
   4271 	int framesize;
   4272 	int bytes;
   4273 
   4274 	KASSERT(track);
   4275 	KASSERT(track->lock);
   4276 	TRACET(4, track, "start pstate=%d", track->pstate);
   4277 
   4278 	/* At this point usrbuf must not be empty. */
   4279 	KASSERT(track->usrbuf.used > 0);
   4280 	/* Also, outbuf must be available at least one block. */
   4281 	count = auring_get_contig_free(&track->outbuf);
   4282 	KASSERTMSG(count >= frame_per_block(track->mixer, &track->outbuf.fmt),
   4283 	    "count=%d fpb=%d",
   4284 	    count, frame_per_block(track->mixer, &track->outbuf.fmt));
   4285 
   4286 	/* XXX TODO: is this necessary for now? */
   4287 	int track_count_0 = track->outbuf.used;
   4288 
   4289 	usrbuf = &track->usrbuf;
   4290 	input = track->input;
   4291 
   4292 	/*
   4293 	 * framesize is always 1 byte or more since all formats supported as
   4294 	 * usrfmt(=input) have 8bit or more stride.
   4295 	 */
   4296 	framesize = frametobyte(&input->fmt, 1);
   4297 	KASSERT(framesize >= 1);
   4298 
   4299 	/* The next stage of usrbuf (=input) must be available. */
   4300 	KASSERT(auring_get_contig_free(input) > 0);
   4301 
   4302 	/*
   4303 	 * Copy usrbuf up to 1block to input buffer.
   4304 	 * count is the number of frames to copy from usrbuf.
   4305 	 * bytes is the number of bytes to copy from usrbuf.  However it is
   4306 	 * not copied less than one frame.
   4307 	 */
   4308 	count = uimin(usrbuf->used, track->usrbuf_blksize) / framesize;
   4309 	bytes = count * framesize;
   4310 
   4311 	track->usrbuf_stamp += bytes;
   4312 
   4313 	if (usrbuf->head + bytes < usrbuf->capacity) {
   4314 		memcpy((uint8_t *)input->mem + auring_tail(input) * framesize,
   4315 		    (uint8_t *)usrbuf->mem + usrbuf->head,
   4316 		    bytes);
   4317 		auring_push(input, count);
   4318 		auring_take(usrbuf, bytes);
   4319 	} else {
   4320 		int bytes1;
   4321 		int bytes2;
   4322 
   4323 		bytes1 = auring_get_contig_used(usrbuf);
   4324 		KASSERTMSG(bytes1 % framesize == 0,
   4325 		    "bytes1=%d framesize=%d", bytes1, framesize);
   4326 		memcpy((uint8_t *)input->mem + auring_tail(input) * framesize,
   4327 		    (uint8_t *)usrbuf->mem + usrbuf->head,
   4328 		    bytes1);
   4329 		auring_push(input, bytes1 / framesize);
   4330 		auring_take(usrbuf, bytes1);
   4331 
   4332 		bytes2 = bytes - bytes1;
   4333 		memcpy((uint8_t *)input->mem + auring_tail(input) * framesize,
   4334 		    (uint8_t *)usrbuf->mem + usrbuf->head,
   4335 		    bytes2);
   4336 		auring_push(input, bytes2 / framesize);
   4337 		auring_take(usrbuf, bytes2);
   4338 	}
   4339 
   4340 	/* Encoding conversion */
   4341 	if (track->codec.filter)
   4342 		audio_apply_stage(track, &track->codec, false);
   4343 
   4344 	/* Channel volume */
   4345 	if (track->chvol.filter)
   4346 		audio_apply_stage(track, &track->chvol, false);
   4347 
   4348 	/* Channel mix */
   4349 	if (track->chmix.filter)
   4350 		audio_apply_stage(track, &track->chmix, false);
   4351 
   4352 	/* Frequency conversion */
   4353 	/*
   4354 	 * Since the frequency conversion needs correction for each block,
   4355 	 * it rounds up to 1 block.
   4356 	 */
   4357 	if (track->freq.filter) {
   4358 		int n;
   4359 		n = audio_append_silence(track, &track->freq.srcbuf);
   4360 		if (n > 0) {
   4361 			TRACET(4, track,
   4362 			    "freq.srcbuf add silence %d -> %d/%d/%d",
   4363 			    n,
   4364 			    track->freq.srcbuf.head,
   4365 			    track->freq.srcbuf.used,
   4366 			    track->freq.srcbuf.capacity);
   4367 		}
   4368 		if (track->freq.srcbuf.used > 0) {
   4369 			audio_apply_stage(track, &track->freq, true);
   4370 		}
   4371 	}
   4372 
   4373 	if (bytes < track->usrbuf_blksize) {
   4374 		/*
   4375 		 * Clear all conversion buffer pointer if the conversion was
   4376 		 * not exactly one block.  These conversion stage buffers are
   4377 		 * certainly circular buffers because of symmetry with the
   4378 		 * previous and next stage buffer.  However, since they are
   4379 		 * treated as simple contiguous buffers in operation, so head
   4380 		 * always should point 0.  This may happen during drain-age.
   4381 		 */
   4382 		TRACET(4, track, "reset stage");
   4383 		if (track->codec.filter) {
   4384 			KASSERT(track->codec.srcbuf.used == 0);
   4385 			track->codec.srcbuf.head = 0;
   4386 		}
   4387 		if (track->chvol.filter) {
   4388 			KASSERT(track->chvol.srcbuf.used == 0);
   4389 			track->chvol.srcbuf.head = 0;
   4390 		}
   4391 		if (track->chmix.filter) {
   4392 			KASSERT(track->chmix.srcbuf.used == 0);
   4393 			track->chmix.srcbuf.head = 0;
   4394 		}
   4395 		if (track->freq.filter) {
   4396 			KASSERT(track->freq.srcbuf.used == 0);
   4397 			track->freq.srcbuf.head = 0;
   4398 		}
   4399 	}
   4400 
   4401 	if (track->input == &track->outbuf) {
   4402 		track->outputcounter = track->inputcounter;
   4403 	} else {
   4404 		track->outputcounter += track->outbuf.used - track_count_0;
   4405 	}
   4406 
   4407 #if defined(AUDIO_DEBUG)
   4408 	if (audiodebug >= 3) {
   4409 		struct audio_track_debugbuf m;
   4410 		audio_track_bufstat(track, &m);
   4411 		TRACET(0, track, "end%s%s%s%s%s%s",
   4412 		    m.outbuf, m.freq, m.chvol, m.chmix, m.codec, m.usrbuf);
   4413 	}
   4414 #endif
   4415 }
   4416 
   4417 /*
   4418  * Produce user output buffer for recording from input buffer.
   4419  */
   4420 static void
   4421 audio_track_record(audio_track_t *track)
   4422 {
   4423 	audio_ring_t *outbuf;
   4424 	audio_ring_t *usrbuf;
   4425 	int count;
   4426 	int bytes;
   4427 	int framesize;
   4428 
   4429 	KASSERT(track);
   4430 	KASSERT(track->lock);
   4431 
   4432 	/* Number of frames to process */
   4433 	count = auring_get_contig_used(track->input);
   4434 	count = uimin(count, track->mixer->frames_per_block);
   4435 	if (count == 0) {
   4436 		TRACET(4, track, "count == 0");
   4437 		return;
   4438 	}
   4439 
   4440 	/* Frequency conversion */
   4441 	if (track->freq.filter) {
   4442 		if (track->freq.srcbuf.used > 0) {
   4443 			audio_apply_stage(track, &track->freq, true);
   4444 			/* XXX should input of freq be from beginning of buf? */
   4445 		}
   4446 	}
   4447 
   4448 	/* Channel mix */
   4449 	if (track->chmix.filter)
   4450 		audio_apply_stage(track, &track->chmix, false);
   4451 
   4452 	/* Channel volume */
   4453 	if (track->chvol.filter)
   4454 		audio_apply_stage(track, &track->chvol, false);
   4455 
   4456 	/* Encoding conversion */
   4457 	if (track->codec.filter)
   4458 		audio_apply_stage(track, &track->codec, false);
   4459 
   4460 	/* Copy outbuf to usrbuf */
   4461 	outbuf = &track->outbuf;
   4462 	usrbuf = &track->usrbuf;
   4463 	/*
   4464 	 * framesize is always 1 byte or more since all formats supported
   4465 	 * as usrfmt(=output) have 8bit or more stride.
   4466 	 */
   4467 	framesize = frametobyte(&outbuf->fmt, 1);
   4468 	KASSERT(framesize >= 1);
   4469 	/*
   4470 	 * count is the number of frames to copy to usrbuf.
   4471 	 * bytes is the number of bytes to copy to usrbuf.
   4472 	 */
   4473 	count = outbuf->used;
   4474 	count = uimin(count,
   4475 	    (track->usrbuf_usedhigh - usrbuf->used) / framesize);
   4476 	bytes = count * framesize;
   4477 	if (auring_tail(usrbuf) + bytes < usrbuf->capacity) {
   4478 		memcpy((uint8_t *)usrbuf->mem + auring_tail(usrbuf),
   4479 		    (uint8_t *)outbuf->mem + outbuf->head * framesize,
   4480 		    bytes);
   4481 		auring_push(usrbuf, bytes);
   4482 		auring_take(outbuf, count);
   4483 	} else {
   4484 		int bytes1;
   4485 		int bytes2;
   4486 
   4487 		bytes1 = auring_get_contig_free(usrbuf);
   4488 		KASSERTMSG(bytes1 % framesize == 0,
   4489 		    "bytes1=%d framesize=%d", bytes1, framesize);
   4490 		memcpy((uint8_t *)usrbuf->mem + auring_tail(usrbuf),
   4491 		    (uint8_t *)outbuf->mem + outbuf->head * framesize,
   4492 		    bytes1);
   4493 		auring_push(usrbuf, bytes1);
   4494 		auring_take(outbuf, bytes1 / framesize);
   4495 
   4496 		bytes2 = bytes - bytes1;
   4497 		memcpy((uint8_t *)usrbuf->mem + auring_tail(usrbuf),
   4498 		    (uint8_t *)outbuf->mem + outbuf->head * framesize,
   4499 		    bytes2);
   4500 		auring_push(usrbuf, bytes2);
   4501 		auring_take(outbuf, bytes2 / framesize);
   4502 	}
   4503 
   4504 	/* XXX TODO: any counters here? */
   4505 
   4506 #if defined(AUDIO_DEBUG)
   4507 	if (audiodebug >= 3) {
   4508 		struct audio_track_debugbuf m;
   4509 		audio_track_bufstat(track, &m);
   4510 		TRACET(0, track, "end%s%s%s%s%s%s",
   4511 		    m.freq, m.chvol, m.chmix, m.codec, m.outbuf, m.usrbuf);
   4512 	}
   4513 #endif
   4514 }
   4515 
   4516 /*
   4517  * Calcurate blktime [msec] from mixer(.hwbuf.fmt).
   4518  * Must be called with sc_lock held.
   4519  */
   4520 static u_int
   4521 audio_mixer_calc_blktime(struct audio_softc *sc, audio_trackmixer_t *mixer)
   4522 {
   4523 	audio_format2_t *fmt;
   4524 	u_int blktime;
   4525 	u_int frames_per_block;
   4526 
   4527 	KASSERT(mutex_owned(sc->sc_lock));
   4528 
   4529 	fmt = &mixer->hwbuf.fmt;
   4530 	blktime = sc->sc_blk_ms;
   4531 
   4532 	/*
   4533 	 * If stride is not multiples of 8, special treatment is necessary.
   4534 	 * For now, it is only x68k's vs(4), 4 bit/sample ADPCM.
   4535 	 */
   4536 	if (fmt->stride == 4) {
   4537 		frames_per_block = fmt->sample_rate * blktime / 1000;
   4538 		if ((frames_per_block & 1) != 0)
   4539 			blktime *= 2;
   4540 	}
   4541 #ifdef DIAGNOSTIC
   4542 	else if (fmt->stride % NBBY != 0) {
   4543 		panic("unsupported HW stride %d", fmt->stride);
   4544 	}
   4545 #endif
   4546 
   4547 	return blktime;
   4548 }
   4549 
   4550 /*
   4551  * Initialize the mixer corresponding to the mode.
   4552  * Set AUMODE_PLAY to the 'mode' for playback or AUMODE_RECORD for recording.
   4553  * sc->sc_[pr]mixer (corresponding to the 'mode') must be zero-filled.
   4554  * This function returns 0 on successful.  Otherwise returns errno.
   4555  * Must be called with sc_lock held.
   4556  */
   4557 static int
   4558 audio_mixer_init(struct audio_softc *sc, int mode,
   4559 	const audio_format2_t *hwfmt, const audio_filter_reg_t *reg)
   4560 {
   4561 	char codecbuf[64];
   4562 	audio_trackmixer_t *mixer;
   4563 	void (*softint_handler)(void *);
   4564 	int len;
   4565 	int blksize;
   4566 	int capacity;
   4567 	size_t bufsize;
   4568 	int hwblks;
   4569 	int blkms;
   4570 	int error;
   4571 
   4572 	KASSERT(hwfmt != NULL);
   4573 	KASSERT(reg != NULL);
   4574 	KASSERT(mutex_owned(sc->sc_lock));
   4575 
   4576 	error = 0;
   4577 	if (mode == AUMODE_PLAY)
   4578 		mixer = sc->sc_pmixer;
   4579 	else
   4580 		mixer = sc->sc_rmixer;
   4581 
   4582 	mixer->sc = sc;
   4583 	mixer->mode = mode;
   4584 
   4585 	mixer->hwbuf.fmt = *hwfmt;
   4586 	mixer->volume = 256;
   4587 	mixer->blktime_d = 1000;
   4588 	mixer->blktime_n = audio_mixer_calc_blktime(sc, mixer);
   4589 	sc->sc_blk_ms = mixer->blktime_n;
   4590 	hwblks = NBLKHW;
   4591 
   4592 	mixer->frames_per_block = frame_per_block(mixer, &mixer->hwbuf.fmt);
   4593 	blksize = frametobyte(&mixer->hwbuf.fmt, mixer->frames_per_block);
   4594 	if (sc->hw_if->round_blocksize) {
   4595 		int rounded;
   4596 		audio_params_t p = format2_to_params(&mixer->hwbuf.fmt);
   4597 		rounded = sc->hw_if->round_blocksize(sc->hw_hdl, blksize,
   4598 		    mode, &p);
   4599 		TRACE(1, "round_blocksize %d -> %d", blksize, rounded);
   4600 		if (rounded != blksize) {
   4601 			if ((rounded * NBBY) % (mixer->hwbuf.fmt.stride *
   4602 			    mixer->hwbuf.fmt.channels) != 0) {
   4603 				device_printf(sc->sc_dev,
   4604 				    "blksize not configured %d -> %d\n",
   4605 				    blksize, rounded);
   4606 				return EINVAL;
   4607 			}
   4608 			/* Recalculation */
   4609 			blksize = rounded;
   4610 			mixer->frames_per_block = blksize * NBBY /
   4611 			    (mixer->hwbuf.fmt.stride *
   4612 			     mixer->hwbuf.fmt.channels);
   4613 		}
   4614 	}
   4615 	mixer->blktime_n = mixer->frames_per_block;
   4616 	mixer->blktime_d = mixer->hwbuf.fmt.sample_rate;
   4617 
   4618 	capacity = mixer->frames_per_block * hwblks;
   4619 	bufsize = frametobyte(&mixer->hwbuf.fmt, capacity);
   4620 	if (sc->hw_if->round_buffersize) {
   4621 		size_t rounded;
   4622 		rounded = sc->hw_if->round_buffersize(sc->hw_hdl, mode,
   4623 		    bufsize);
   4624 		TRACE(1, "round_buffersize %zd -> %zd", bufsize, rounded);
   4625 		if (rounded < bufsize) {
   4626 			/* buffersize needs NBLKHW blocks at least. */
   4627 			device_printf(sc->sc_dev,
   4628 			    "buffersize too small: buffersize=%zd blksize=%d\n",
   4629 			    rounded, blksize);
   4630 			return EINVAL;
   4631 		}
   4632 		if (rounded % blksize != 0) {
   4633 			/* buffersize/blksize constraint mismatch? */
   4634 			device_printf(sc->sc_dev,
   4635 			    "buffersize must be multiple of blksize: "
   4636 			    "buffersize=%zu blksize=%d\n",
   4637 			    rounded, blksize);
   4638 			return EINVAL;
   4639 		}
   4640 		if (rounded != bufsize) {
   4641 			/* Recalcuration */
   4642 			bufsize = rounded;
   4643 			hwblks = bufsize / blksize;
   4644 			capacity = mixer->frames_per_block * hwblks;
   4645 		}
   4646 	}
   4647 	TRACE(1, "buffersize for %s = %zu",
   4648 	    (mode == AUMODE_PLAY) ? "playback" : "recording",
   4649 	    bufsize);
   4650 	mixer->hwbuf.capacity = capacity;
   4651 
   4652 	/*
   4653 	 * XXX need to release sc_lock for compatibility?
   4654 	 */
   4655 	if (sc->hw_if->allocm) {
   4656 		mixer->hwbuf.mem = sc->hw_if->allocm(sc->hw_hdl, mode, bufsize);
   4657 		if (mixer->hwbuf.mem == NULL) {
   4658 			device_printf(sc->sc_dev, "%s: allocm(%zu) failed\n",
   4659 			    __func__, bufsize);
   4660 			return ENOMEM;
   4661 		}
   4662 	} else {
   4663 		mixer->hwbuf.mem = kmem_alloc(bufsize, KM_SLEEP);
   4664 	}
   4665 
   4666 	/* From here, audio_mixer_destroy is necessary to exit. */
   4667 	if (mode == AUMODE_PLAY) {
   4668 		cv_init(&mixer->outcv, "audiowr");
   4669 	} else {
   4670 		cv_init(&mixer->outcv, "audiord");
   4671 	}
   4672 
   4673 	if (mode == AUMODE_PLAY) {
   4674 		softint_handler = audio_softintr_wr;
   4675 	} else {
   4676 		softint_handler = audio_softintr_rd;
   4677 	}
   4678 	mixer->sih = softint_establish(SOFTINT_SERIAL | SOFTINT_MPSAFE,
   4679 	    softint_handler, sc);
   4680 	if (mixer->sih == NULL) {
   4681 		device_printf(sc->sc_dev, "softint_establish failed\n");
   4682 		goto abort;
   4683 	}
   4684 
   4685 	mixer->track_fmt.encoding = AUDIO_ENCODING_SLINEAR_NE;
   4686 	mixer->track_fmt.precision = AUDIO_INTERNAL_BITS;
   4687 	mixer->track_fmt.stride = AUDIO_INTERNAL_BITS;
   4688 	mixer->track_fmt.channels = mixer->hwbuf.fmt.channels;
   4689 	mixer->track_fmt.sample_rate = mixer->hwbuf.fmt.sample_rate;
   4690 
   4691 	if (mixer->hwbuf.fmt.encoding == AUDIO_ENCODING_SLINEAR_OE &&
   4692 	    mixer->hwbuf.fmt.precision == AUDIO_INTERNAL_BITS) {
   4693 		mixer->swap_endian = true;
   4694 		TRACE(1, "swap_endian");
   4695 	}
   4696 
   4697 	if (mode == AUMODE_PLAY) {
   4698 		/* Mixing buffer */
   4699 		mixer->mixfmt = mixer->track_fmt;
   4700 		mixer->mixfmt.precision *= 2;
   4701 		mixer->mixfmt.stride *= 2;
   4702 		/* XXX TODO: use some macros? */
   4703 		len = mixer->frames_per_block * mixer->mixfmt.channels *
   4704 		    mixer->mixfmt.stride / NBBY;
   4705 		mixer->mixsample = audio_realloc(mixer->mixsample, len);
   4706 	} else {
   4707 		/* No mixing buffer for recording */
   4708 	}
   4709 
   4710 	if (reg->codec) {
   4711 		mixer->codec = reg->codec;
   4712 		mixer->codecarg.context = reg->context;
   4713 		if (mode == AUMODE_PLAY) {
   4714 			mixer->codecarg.srcfmt = &mixer->track_fmt;
   4715 			mixer->codecarg.dstfmt = &mixer->hwbuf.fmt;
   4716 		} else {
   4717 			mixer->codecarg.srcfmt = &mixer->hwbuf.fmt;
   4718 			mixer->codecarg.dstfmt = &mixer->track_fmt;
   4719 		}
   4720 		mixer->codecbuf.fmt = mixer->track_fmt;
   4721 		mixer->codecbuf.capacity = mixer->frames_per_block;
   4722 		len = auring_bytelen(&mixer->codecbuf);
   4723 		mixer->codecbuf.mem = audio_realloc(mixer->codecbuf.mem, len);
   4724 		if (mixer->codecbuf.mem == NULL) {
   4725 			device_printf(sc->sc_dev,
   4726 			    "%s: malloc codecbuf(%d) failed\n",
   4727 			    __func__, len);
   4728 			error = ENOMEM;
   4729 			goto abort;
   4730 		}
   4731 	}
   4732 
   4733 	/* Succeeded so display it. */
   4734 	codecbuf[0] = '\0';
   4735 	if (mixer->codec || mixer->swap_endian) {
   4736 		snprintf(codecbuf, sizeof(codecbuf), " %s %s:%d",
   4737 		    (mode == AUMODE_PLAY) ? "->" : "<-",
   4738 		    audio_encoding_name(mixer->hwbuf.fmt.encoding),
   4739 		    mixer->hwbuf.fmt.precision);
   4740 	}
   4741 	blkms = mixer->blktime_n * 1000 / mixer->blktime_d;
   4742 	aprint_normal_dev(sc->sc_dev, "%s:%d%s %dch %dHz, blk %dms for %s\n",
   4743 	    audio_encoding_name(mixer->track_fmt.encoding),
   4744 	    mixer->track_fmt.precision,
   4745 	    codecbuf,
   4746 	    mixer->track_fmt.channels,
   4747 	    mixer->track_fmt.sample_rate,
   4748 	    blkms,
   4749 	    (mode == AUMODE_PLAY) ? "playback" : "recording");
   4750 
   4751 	return 0;
   4752 
   4753 abort:
   4754 	audio_mixer_destroy(sc, mixer);
   4755 	return error;
   4756 }
   4757 
   4758 /*
   4759  * Releases all resources of 'mixer'.
   4760  * Note that it does not release the memory area of 'mixer' itself.
   4761  * Must be called with sc_lock held.
   4762  */
   4763 static void
   4764 audio_mixer_destroy(struct audio_softc *sc, audio_trackmixer_t *mixer)
   4765 {
   4766 	int bufsize;
   4767 
   4768 	KASSERT(mutex_owned(sc->sc_lock));
   4769 
   4770 	bufsize = frametobyte(&mixer->hwbuf.fmt, mixer->hwbuf.capacity);
   4771 
   4772 	if (mixer->hwbuf.mem != NULL) {
   4773 		if (sc->hw_if->freem) {
   4774 			sc->hw_if->freem(sc->hw_hdl, mixer->hwbuf.mem, bufsize);
   4775 		} else {
   4776 			kmem_free(mixer->hwbuf.mem, bufsize);
   4777 		}
   4778 		mixer->hwbuf.mem = NULL;
   4779 	}
   4780 
   4781 	audio_free(mixer->codecbuf.mem);
   4782 	audio_free(mixer->mixsample);
   4783 
   4784 	cv_destroy(&mixer->outcv);
   4785 
   4786 	if (mixer->sih) {
   4787 		softint_disestablish(mixer->sih);
   4788 		mixer->sih = NULL;
   4789 	}
   4790 }
   4791 
   4792 /*
   4793  * Starts playback mixer.
   4794  * Must be called only if sc_pbusy is false.
   4795  * Must be called with sc_lock held.
   4796  * Must not be called from the interrupt context.
   4797  */
   4798 static void
   4799 audio_pmixer_start(struct audio_softc *sc, bool force)
   4800 {
   4801 	audio_trackmixer_t *mixer;
   4802 	int minimum;
   4803 
   4804 	KASSERT(mutex_owned(sc->sc_lock));
   4805 	KASSERT(sc->sc_pbusy == false);
   4806 
   4807 	mutex_enter(sc->sc_intr_lock);
   4808 
   4809 	mixer = sc->sc_pmixer;
   4810 	TRACE(2, "%smixseq=%d hwseq=%d hwbuf=%d/%d/%d%s",
   4811 	    (audiodebug >= 3) ? "begin " : "",
   4812 	    (int)mixer->mixseq, (int)mixer->hwseq,
   4813 	    mixer->hwbuf.head, mixer->hwbuf.used, mixer->hwbuf.capacity,
   4814 	    force ? " force" : "");
   4815 
   4816 	/* Need two blocks to start normally. */
   4817 	minimum = (force) ? 1 : 2;
   4818 	while (mixer->hwbuf.used < mixer->frames_per_block * minimum) {
   4819 		audio_pmixer_process(sc);
   4820 	}
   4821 
   4822 	/* Start output */
   4823 	audio_pmixer_output(sc);
   4824 	sc->sc_pbusy = true;
   4825 
   4826 	TRACE(3, "end   mixseq=%d hwseq=%d hwbuf=%d/%d/%d",
   4827 	    (int)mixer->mixseq, (int)mixer->hwseq,
   4828 	    mixer->hwbuf.head, mixer->hwbuf.used, mixer->hwbuf.capacity);
   4829 
   4830 	mutex_exit(sc->sc_intr_lock);
   4831 }
   4832 
   4833 /*
   4834  * When playing back with MD filter:
   4835  *
   4836  *           track track ...
   4837  *               v v
   4838  *                +  mix (with aint2_t)
   4839  *                |  master volume (with aint2_t)
   4840  *                v
   4841  *    mixsample [::::]                  wide-int 1 block (ring) buffer
   4842  *                |
   4843  *                |  convert aint2_t -> aint_t
   4844  *                v
   4845  *    codecbuf  [....]                  1 block (ring) buffer
   4846  *                |
   4847  *                |  convert to hw format
   4848  *                v
   4849  *    hwbuf     [............]          NBLKHW blocks ring buffer
   4850  *
   4851  * When playing back without MD filter:
   4852  *
   4853  *    mixsample [::::]                  wide-int 1 block (ring) buffer
   4854  *                |
   4855  *                |  convert aint2_t -> aint_t
   4856  *                |  (with byte swap if necessary)
   4857  *                v
   4858  *    hwbuf     [............]          NBLKHW blocks ring buffer
   4859  *
   4860  * mixsample: slinear_NE, wide internal precision, HW ch, HW freq.
   4861  * codecbuf:  slinear_NE, internal precision,      HW ch, HW freq.
   4862  * hwbuf:     HW encoding, HW precision,           HW ch, HW freq.
   4863  */
   4864 
   4865 /*
   4866  * Performs track mixing and converts it to hwbuf.
   4867  * Note that this function doesn't transfer hwbuf to hardware.
   4868  * Must be called with sc_intr_lock held.
   4869  */
   4870 static void
   4871 audio_pmixer_process(struct audio_softc *sc)
   4872 {
   4873 	audio_trackmixer_t *mixer;
   4874 	audio_file_t *f;
   4875 	int frame_count;
   4876 	int sample_count;
   4877 	int mixed;
   4878 	int i;
   4879 	aint2_t *m;
   4880 	aint_t *h;
   4881 
   4882 	mixer = sc->sc_pmixer;
   4883 
   4884 	frame_count = mixer->frames_per_block;
   4885 	KASSERTMSG(auring_get_contig_free(&mixer->hwbuf) >= frame_count,
   4886 	    "auring_get_contig_free()=%d frame_count=%d",
   4887 	    auring_get_contig_free(&mixer->hwbuf), frame_count);
   4888 	sample_count = frame_count * mixer->mixfmt.channels;
   4889 
   4890 	mixer->mixseq++;
   4891 
   4892 	/* Mix all tracks */
   4893 	mixed = 0;
   4894 	SLIST_FOREACH(f, &sc->sc_files, entry) {
   4895 		audio_track_t *track = f->ptrack;
   4896 
   4897 		if (track == NULL)
   4898 			continue;
   4899 
   4900 		if (track->is_pause) {
   4901 			TRACET(4, track, "skip; paused");
   4902 			continue;
   4903 		}
   4904 
   4905 		/* Skip if the track is used by process context. */
   4906 		if (audio_track_lock_tryenter(track) == false) {
   4907 			TRACET(4, track, "skip; in use");
   4908 			continue;
   4909 		}
   4910 
   4911 		/* Emulate mmap'ped track */
   4912 		if (track->mmapped) {
   4913 			auring_push(&track->usrbuf, track->usrbuf_blksize);
   4914 			TRACET(4, track, "mmap; usr=%d/%d/C%d",
   4915 			    track->usrbuf.head,
   4916 			    track->usrbuf.used,
   4917 			    track->usrbuf.capacity);
   4918 		}
   4919 
   4920 		if (track->outbuf.used < mixer->frames_per_block &&
   4921 		    track->usrbuf.used > 0) {
   4922 			TRACET(4, track, "process");
   4923 			audio_track_play(track);
   4924 		}
   4925 
   4926 		if (track->outbuf.used > 0) {
   4927 			mixed = audio_pmixer_mix_track(mixer, track, mixed);
   4928 		} else {
   4929 			TRACET(4, track, "skip; empty");
   4930 		}
   4931 
   4932 		audio_track_lock_exit(track);
   4933 	}
   4934 
   4935 	if (mixed == 0) {
   4936 		/* Silence */
   4937 		memset(mixer->mixsample, 0,
   4938 		    frametobyte(&mixer->mixfmt, frame_count));
   4939 	} else {
   4940 		if (mixed > 1) {
   4941 			/* If there are multiple tracks, do auto gain control */
   4942 			audio_pmixer_agc(mixer, sample_count);
   4943 		}
   4944 
   4945 		/* Apply master volume */
   4946 		if (mixer->volume < 256) {
   4947 			m = mixer->mixsample;
   4948 			for (i = 0; i < sample_count; i++) {
   4949 				*m = AUDIO_SCALEDOWN(*m * mixer->volume, 8);
   4950 				m++;
   4951 			}
   4952 
   4953 			/*
   4954 			 * Recover the volume gradually at the pace of
   4955 			 * several times per second.  If it's too fast, you
   4956 			 * can recognize that the volume changes up and down
   4957 			 * quickly and it's not so comfortable.
   4958 			 */
   4959 			mixer->voltimer += mixer->blktime_n;
   4960 			if (mixer->voltimer * 4 >= mixer->blktime_d) {
   4961 				mixer->volume++;
   4962 				mixer->voltimer = 0;
   4963 #if defined(AUDIO_DEBUG_AGC)
   4964 				TRACE(1, "volume recover: %d", mixer->volume);
   4965 #endif
   4966 			}
   4967 		}
   4968 	}
   4969 
   4970 	/*
   4971 	 * The rest is the hardware part.
   4972 	 */
   4973 
   4974 	if (mixer->codec) {
   4975 		h = auring_tailptr_aint(&mixer->codecbuf);
   4976 	} else {
   4977 		h = auring_tailptr_aint(&mixer->hwbuf);
   4978 	}
   4979 
   4980 	m = mixer->mixsample;
   4981 	if (mixer->swap_endian) {
   4982 		for (i = 0; i < sample_count; i++) {
   4983 			*h++ = bswap16(*m++);
   4984 		}
   4985 	} else {
   4986 		for (i = 0; i < sample_count; i++) {
   4987 			*h++ = *m++;
   4988 		}
   4989 	}
   4990 
   4991 	/* Hardware driver's codec */
   4992 	if (mixer->codec) {
   4993 		auring_push(&mixer->codecbuf, frame_count);
   4994 		mixer->codecarg.src = auring_headptr(&mixer->codecbuf);
   4995 		mixer->codecarg.dst = auring_tailptr(&mixer->hwbuf);
   4996 		mixer->codecarg.count = frame_count;
   4997 		mixer->codec(&mixer->codecarg);
   4998 		auring_take(&mixer->codecbuf, mixer->codecarg.count);
   4999 	}
   5000 
   5001 	auring_push(&mixer->hwbuf, frame_count);
   5002 
   5003 	TRACE(4, "done mixseq=%d hwbuf=%d/%d/%d%s",
   5004 	    (int)mixer->mixseq,
   5005 	    mixer->hwbuf.head, mixer->hwbuf.used, mixer->hwbuf.capacity,
   5006 	    (mixed == 0) ? " silent" : "");
   5007 }
   5008 
   5009 /*
   5010  * Do auto gain control.
   5011  * Must be called sc_intr_lock held.
   5012  */
   5013 static void
   5014 audio_pmixer_agc(audio_trackmixer_t *mixer, int sample_count)
   5015 {
   5016 	struct audio_softc *sc __unused;
   5017 	aint2_t val;
   5018 	aint2_t maxval;
   5019 	aint2_t minval;
   5020 	aint2_t over_plus;
   5021 	aint2_t over_minus;
   5022 	aint2_t *m;
   5023 	int newvol;
   5024 	int i;
   5025 
   5026 	sc = mixer->sc;
   5027 
   5028 	/* Overflow detection */
   5029 	maxval = AINT_T_MAX;
   5030 	minval = AINT_T_MIN;
   5031 	m = mixer->mixsample;
   5032 	for (i = 0; i < sample_count; i++) {
   5033 		val = *m++;
   5034 		if (val > maxval)
   5035 			maxval = val;
   5036 		else if (val < minval)
   5037 			minval = val;
   5038 	}
   5039 
   5040 	/* Absolute value of overflowed amount */
   5041 	over_plus = maxval - AINT_T_MAX;
   5042 	over_minus = AINT_T_MIN - minval;
   5043 
   5044 	if (over_plus > 0 || over_minus > 0) {
   5045 		if (over_plus > over_minus) {
   5046 			newvol = (int)((aint2_t)AINT_T_MAX * 256 / maxval);
   5047 		} else {
   5048 			newvol = (int)((aint2_t)AINT_T_MIN * 256 / minval);
   5049 		}
   5050 
   5051 		/*
   5052 		 * Change the volume only if new one is smaller.
   5053 		 * Reset the timer even if the volume isn't changed.
   5054 		 */
   5055 		if (newvol <= mixer->volume) {
   5056 			mixer->volume = newvol;
   5057 			mixer->voltimer = 0;
   5058 #if defined(AUDIO_DEBUG_AGC)
   5059 			TRACE(1, "auto volume adjust: %d", mixer->volume);
   5060 #endif
   5061 		}
   5062 	}
   5063 }
   5064 
   5065 /*
   5066  * Mix one track.
   5067  * 'mixed' specifies the number of tracks mixed so far.
   5068  * It returns the number of tracks mixed.  In other words, it returns
   5069  * mixed + 1 if this track is mixed.
   5070  */
   5071 static int
   5072 audio_pmixer_mix_track(audio_trackmixer_t *mixer, audio_track_t *track,
   5073 	int mixed)
   5074 {
   5075 	int count;
   5076 	int sample_count;
   5077 	int remain;
   5078 	int i;
   5079 	const aint_t *s;
   5080 	aint2_t *d;
   5081 
   5082 	/* XXX TODO: Is this necessary for now? */
   5083 	if (mixer->mixseq < track->seq)
   5084 		return mixed;
   5085 
   5086 	count = auring_get_contig_used(&track->outbuf);
   5087 	count = uimin(count, mixer->frames_per_block);
   5088 
   5089 	s = auring_headptr_aint(&track->outbuf);
   5090 	d = mixer->mixsample;
   5091 
   5092 	/*
   5093 	 * Apply track volume with double-sized integer and perform
   5094 	 * additive synthesis.
   5095 	 *
   5096 	 * XXX If you limit the track volume to 1.0 or less (<= 256),
   5097 	 *     it would be better to do this in the track conversion stage
   5098 	 *     rather than here.  However, if you accept the volume to
   5099 	 *     be greater than 1.0 (> 256), it's better to do it here.
   5100 	 *     Because the operation here is done by double-sized integer.
   5101 	 */
   5102 	sample_count = count * mixer->mixfmt.channels;
   5103 	if (mixed == 0) {
   5104 		/* If this is the first track, assignment can be used. */
   5105 #if defined(AUDIO_SUPPORT_TRACK_VOLUME)
   5106 		if (track->volume != 256) {
   5107 			for (i = 0; i < sample_count; i++) {
   5108 				aint2_t v;
   5109 				v = *s++;
   5110 				*d++ = AUDIO_SCALEDOWN(v * track->volume, 8)
   5111 			}
   5112 		} else
   5113 #endif
   5114 		{
   5115 			for (i = 0; i < sample_count; i++) {
   5116 				*d++ = ((aint2_t)*s++);
   5117 			}
   5118 		}
   5119 		/* Fill silence if the first track is not filled. */
   5120 		for (; i < mixer->frames_per_block * mixer->mixfmt.channels; i++)
   5121 			*d++ = 0;
   5122 	} else {
   5123 		/* If this is the second or later, add it. */
   5124 #if defined(AUDIO_SUPPORT_TRACK_VOLUME)
   5125 		if (track->volume != 256) {
   5126 			for (i = 0; i < sample_count; i++) {
   5127 				aint2_t v;
   5128 				v = *s++;
   5129 				*d++ += AUDIO_SCALEDOWN(v * track->volume, 8);
   5130 			}
   5131 		} else
   5132 #endif
   5133 		{
   5134 			for (i = 0; i < sample_count; i++) {
   5135 				*d++ += ((aint2_t)*s++);
   5136 			}
   5137 		}
   5138 	}
   5139 
   5140 	auring_take(&track->outbuf, count);
   5141 	/*
   5142 	 * The counters have to align block even if outbuf is less than
   5143 	 * one block. XXX Is this still necessary?
   5144 	 */
   5145 	remain = mixer->frames_per_block - count;
   5146 	if (__predict_false(remain != 0)) {
   5147 		auring_push(&track->outbuf, remain);
   5148 		auring_take(&track->outbuf, remain);
   5149 	}
   5150 
   5151 	/*
   5152 	 * Update track sequence.
   5153 	 * mixseq has previous value yet at this point.
   5154 	 */
   5155 	track->seq = mixer->mixseq + 1;
   5156 
   5157 	return mixed + 1;
   5158 }
   5159 
   5160 /*
   5161  * Output one block from hwbuf to HW.
   5162  * Must be called with sc_intr_lock held.
   5163  */
   5164 static void
   5165 audio_pmixer_output(struct audio_softc *sc)
   5166 {
   5167 	audio_trackmixer_t *mixer;
   5168 	audio_params_t params;
   5169 	void *start;
   5170 	void *end;
   5171 	int blksize;
   5172 	int error;
   5173 
   5174 	mixer = sc->sc_pmixer;
   5175 	TRACE(4, "pbusy=%d hwbuf=%d/%d/%d",
   5176 	    sc->sc_pbusy,
   5177 	    mixer->hwbuf.head, mixer->hwbuf.used, mixer->hwbuf.capacity);
   5178 	KASSERTMSG(mixer->hwbuf.used >= mixer->frames_per_block,
   5179 	    "mixer->hwbuf.used=%d mixer->frames_per_block=%d",
   5180 	    mixer->hwbuf.used, mixer->frames_per_block);
   5181 
   5182 	blksize = frametobyte(&mixer->hwbuf.fmt, mixer->frames_per_block);
   5183 
   5184 	if (sc->hw_if->trigger_output) {
   5185 		/* trigger (at once) */
   5186 		if (!sc->sc_pbusy) {
   5187 			start = mixer->hwbuf.mem;
   5188 			end = (uint8_t *)start + auring_bytelen(&mixer->hwbuf);
   5189 			params = format2_to_params(&mixer->hwbuf.fmt);
   5190 
   5191 			error = sc->hw_if->trigger_output(sc->hw_hdl,
   5192 			    start, end, blksize, audio_pintr, sc, &params);
   5193 			if (error) {
   5194 				device_printf(sc->sc_dev,
   5195 				    "trigger_output failed with %d\n", error);
   5196 				return;
   5197 			}
   5198 		}
   5199 	} else {
   5200 		/* start (everytime) */
   5201 		start = auring_headptr(&mixer->hwbuf);
   5202 
   5203 		error = sc->hw_if->start_output(sc->hw_hdl,
   5204 		    start, blksize, audio_pintr, sc);
   5205 		if (error) {
   5206 			device_printf(sc->sc_dev,
   5207 			    "start_output failed with %d\n", error);
   5208 			return;
   5209 		}
   5210 	}
   5211 }
   5212 
   5213 /*
   5214  * This is an interrupt handler for playback.
   5215  * It is called with sc_intr_lock held.
   5216  *
   5217  * It is usually called from hardware interrupt.  However, note that
   5218  * for some drivers (e.g. uaudio) it is called from software interrupt.
   5219  */
   5220 static void
   5221 audio_pintr(void *arg)
   5222 {
   5223 	struct audio_softc *sc;
   5224 	audio_trackmixer_t *mixer;
   5225 
   5226 	sc = arg;
   5227 	KASSERT(mutex_owned(sc->sc_intr_lock));
   5228 
   5229 	if (sc->sc_dying)
   5230 		return;
   5231 #if defined(DIAGNOSTIC)
   5232 	if (sc->sc_pbusy == false) {
   5233 		device_printf(sc->sc_dev, "stray interrupt\n");
   5234 		return;
   5235 	}
   5236 #endif
   5237 
   5238 	mixer = sc->sc_pmixer;
   5239 	mixer->hw_complete_counter += mixer->frames_per_block;
   5240 	mixer->hwseq++;
   5241 
   5242 	auring_take(&mixer->hwbuf, mixer->frames_per_block);
   5243 
   5244 	TRACE(4,
   5245 	    "HW_INT ++hwseq=%" PRIu64 " cmplcnt=%" PRIu64 " hwbuf=%d/%d/%d",
   5246 	    mixer->hwseq, mixer->hw_complete_counter,
   5247 	    mixer->hwbuf.head, mixer->hwbuf.used, mixer->hwbuf.capacity);
   5248 
   5249 #if defined(AUDIO_HW_SINGLE_BUFFER)
   5250 	/*
   5251 	 * Create a new block here and output it immediately.
   5252 	 * It makes a latency lower but needs machine power.
   5253 	 */
   5254 	audio_pmixer_process(sc);
   5255 	audio_pmixer_output(sc);
   5256 #else
   5257 	/*
   5258 	 * It is called when block N output is done.
   5259 	 * Output immediately block N+1 created by the last interrupt.
   5260 	 * And then create block N+2 for the next interrupt.
   5261 	 * This method makes playback robust even on slower machines.
   5262 	 * Instead the latency is increased by one block.
   5263 	 */
   5264 
   5265 	/* At first, output ready block. */
   5266 	if (mixer->hwbuf.used >= mixer->frames_per_block) {
   5267 		audio_pmixer_output(sc);
   5268 	}
   5269 
   5270 	bool later = false;
   5271 
   5272 	if (mixer->hwbuf.used < mixer->frames_per_block) {
   5273 		later = true;
   5274 	}
   5275 
   5276 	/* Then, process next block. */
   5277 	audio_pmixer_process(sc);
   5278 
   5279 	if (later) {
   5280 		audio_pmixer_output(sc);
   5281 	}
   5282 #endif
   5283 
   5284 	/*
   5285 	 * When this interrupt is the real hardware interrupt, disabling
   5286 	 * preemption here is not necessary.  But some drivers (e.g. uaudio)
   5287 	 * emulate it by software interrupt, so kpreempt_disable is necessary.
   5288 	 */
   5289 	kpreempt_disable();
   5290 	softint_schedule(mixer->sih);
   5291 	kpreempt_enable();
   5292 }
   5293 
   5294 /*
   5295  * Starts record mixer.
   5296  * Must be called only if sc_rbusy is false.
   5297  * Must be called with sc_lock held.
   5298  * Must not be called from the interrupt context.
   5299  */
   5300 static void
   5301 audio_rmixer_start(struct audio_softc *sc)
   5302 {
   5303 
   5304 	KASSERT(mutex_owned(sc->sc_lock));
   5305 	KASSERT(sc->sc_rbusy == false);
   5306 
   5307 	mutex_enter(sc->sc_intr_lock);
   5308 
   5309 	TRACE(2, "%s", (audiodebug >= 3) ? "begin" : "");
   5310 	audio_rmixer_input(sc);
   5311 	sc->sc_rbusy = true;
   5312 	TRACE(3, "end");
   5313 
   5314 	mutex_exit(sc->sc_intr_lock);
   5315 }
   5316 
   5317 /*
   5318  * When recording with MD filter:
   5319  *
   5320  *    hwbuf     [............]          NBLKHW blocks ring buffer
   5321  *                |
   5322  *                | convert from hw format
   5323  *                v
   5324  *    codecbuf  [....]                  1 block (ring) buffer
   5325  *               |  |
   5326  *               v  v
   5327  *            track track ...
   5328  *
   5329  * When recording without MD filter:
   5330  *
   5331  *    hwbuf     [............]          NBLKHW blocks ring buffer
   5332  *               |  |
   5333  *               v  v
   5334  *            track track ...
   5335  *
   5336  * hwbuf:     HW encoding, HW precision, HW ch, HW freq.
   5337  * codecbuf:  slinear_NE, internal precision, HW ch, HW freq.
   5338  */
   5339 
   5340 /*
   5341  * Distribute a recorded block to all recording tracks.
   5342  */
   5343 static void
   5344 audio_rmixer_process(struct audio_softc *sc)
   5345 {
   5346 	audio_trackmixer_t *mixer;
   5347 	audio_ring_t *mixersrc;
   5348 	audio_file_t *f;
   5349 	aint_t *p;
   5350 	int count;
   5351 	int bytes;
   5352 	int i;
   5353 
   5354 	mixer = sc->sc_rmixer;
   5355 
   5356 	/*
   5357 	 * count is the number of frames to be retrieved this time.
   5358 	 * count should be one block.
   5359 	 */
   5360 	count = auring_get_contig_used(&mixer->hwbuf);
   5361 	count = uimin(count, mixer->frames_per_block);
   5362 	if (count <= 0) {
   5363 		TRACE(4, "count %d: too short", count);
   5364 		return;
   5365 	}
   5366 	bytes = frametobyte(&mixer->track_fmt, count);
   5367 
   5368 	/* Hardware driver's codec */
   5369 	if (mixer->codec) {
   5370 		mixer->codecarg.src = auring_headptr(&mixer->hwbuf);
   5371 		mixer->codecarg.dst = auring_tailptr(&mixer->codecbuf);
   5372 		mixer->codecarg.count = count;
   5373 		mixer->codec(&mixer->codecarg);
   5374 		auring_take(&mixer->hwbuf, mixer->codecarg.count);
   5375 		auring_push(&mixer->codecbuf, mixer->codecarg.count);
   5376 		mixersrc = &mixer->codecbuf;
   5377 	} else {
   5378 		mixersrc = &mixer->hwbuf;
   5379 	}
   5380 
   5381 	if (mixer->swap_endian) {
   5382 		/* inplace conversion */
   5383 		p = auring_headptr_aint(mixersrc);
   5384 		for (i = 0; i < count * mixer->track_fmt.channels; i++, p++) {
   5385 			*p = bswap16(*p);
   5386 		}
   5387 	}
   5388 
   5389 	/* Distribute to all tracks. */
   5390 	SLIST_FOREACH(f, &sc->sc_files, entry) {
   5391 		audio_track_t *track = f->rtrack;
   5392 		audio_ring_t *input;
   5393 
   5394 		if (track == NULL)
   5395 			continue;
   5396 
   5397 		if (track->is_pause) {
   5398 			TRACET(4, track, "skip; paused");
   5399 			continue;
   5400 		}
   5401 
   5402 		if (audio_track_lock_tryenter(track) == false) {
   5403 			TRACET(4, track, "skip; in use");
   5404 			continue;
   5405 		}
   5406 
   5407 		/* If the track buffer is full, discard the oldest one? */
   5408 		input = track->input;
   5409 		if (input->capacity - input->used < mixer->frames_per_block) {
   5410 			int drops = mixer->frames_per_block -
   5411 			    (input->capacity - input->used);
   5412 			track->dropframes += drops;
   5413 			TRACET(4, track, "drop %d frames: inp=%d/%d/%d",
   5414 			    drops,
   5415 			    input->head, input->used, input->capacity);
   5416 			auring_take(input, drops);
   5417 		}
   5418 		KASSERTMSG(input->used % mixer->frames_per_block == 0,
   5419 		    "input->used=%d mixer->frames_per_block=%d",
   5420 		    input->used, mixer->frames_per_block);
   5421 
   5422 		memcpy(auring_tailptr_aint(input),
   5423 		    auring_headptr_aint(mixersrc),
   5424 		    bytes);
   5425 		auring_push(input, count);
   5426 
   5427 		/* XXX sequence counter? */
   5428 
   5429 		audio_track_lock_exit(track);
   5430 	}
   5431 
   5432 	auring_take(mixersrc, count);
   5433 }
   5434 
   5435 /*
   5436  * Input one block from HW to hwbuf.
   5437  * Must be called with sc_intr_lock held.
   5438  */
   5439 static void
   5440 audio_rmixer_input(struct audio_softc *sc)
   5441 {
   5442 	audio_trackmixer_t *mixer;
   5443 	audio_params_t params;
   5444 	void *start;
   5445 	void *end;
   5446 	int blksize;
   5447 	int error;
   5448 
   5449 	mixer = sc->sc_rmixer;
   5450 	blksize = frametobyte(&mixer->hwbuf.fmt, mixer->frames_per_block);
   5451 
   5452 	if (sc->hw_if->trigger_input) {
   5453 		/* trigger (at once) */
   5454 		if (!sc->sc_rbusy) {
   5455 			start = mixer->hwbuf.mem;
   5456 			end = (uint8_t *)start + auring_bytelen(&mixer->hwbuf);
   5457 			params = format2_to_params(&mixer->hwbuf.fmt);
   5458 
   5459 			error = sc->hw_if->trigger_input(sc->hw_hdl,
   5460 			    start, end, blksize, audio_rintr, sc, &params);
   5461 			if (error) {
   5462 				device_printf(sc->sc_dev,
   5463 				    "trigger_input failed with %d\n", error);
   5464 				return;
   5465 			}
   5466 		}
   5467 	} else {
   5468 		/* start (everytime) */
   5469 		start = auring_tailptr(&mixer->hwbuf);
   5470 
   5471 		error = sc->hw_if->start_input(sc->hw_hdl,
   5472 		    start, blksize, audio_rintr, sc);
   5473 		if (error) {
   5474 			device_printf(sc->sc_dev,
   5475 			    "start_input failed with %d\n", error);
   5476 			return;
   5477 		}
   5478 	}
   5479 }
   5480 
   5481 /*
   5482  * This is an interrupt handler for recording.
   5483  * It is called with sc_intr_lock.
   5484  *
   5485  * It is usually called from hardware interrupt.  However, note that
   5486  * for some drivers (e.g. uaudio) it is called from software interrupt.
   5487  */
   5488 static void
   5489 audio_rintr(void *arg)
   5490 {
   5491 	struct audio_softc *sc;
   5492 	audio_trackmixer_t *mixer;
   5493 
   5494 	sc = arg;
   5495 	KASSERT(mutex_owned(sc->sc_intr_lock));
   5496 
   5497 	if (sc->sc_dying)
   5498 		return;
   5499 #if defined(DIAGNOSTIC)
   5500 	if (sc->sc_rbusy == false) {
   5501 		device_printf(sc->sc_dev, "stray interrupt\n");
   5502 		return;
   5503 	}
   5504 #endif
   5505 
   5506 	mixer = sc->sc_rmixer;
   5507 	mixer->hw_complete_counter += mixer->frames_per_block;
   5508 	mixer->hwseq++;
   5509 
   5510 	auring_push(&mixer->hwbuf, mixer->frames_per_block);
   5511 
   5512 	TRACE(4,
   5513 	    "HW_INT ++hwseq=%" PRIu64 " cmplcnt=%" PRIu64 " hwbuf=%d/%d/%d",
   5514 	    mixer->hwseq, mixer->hw_complete_counter,
   5515 	    mixer->hwbuf.head, mixer->hwbuf.used, mixer->hwbuf.capacity);
   5516 
   5517 	/* Distrubute recorded block */
   5518 	audio_rmixer_process(sc);
   5519 
   5520 	/* Request next block */
   5521 	audio_rmixer_input(sc);
   5522 
   5523 	/*
   5524 	 * When this interrupt is the real hardware interrupt, disabling
   5525 	 * preemption here is not necessary.  But some drivers (e.g. uaudio)
   5526 	 * emulate it by software interrupt, so kpreempt_disable is necessary.
   5527 	 */
   5528 	kpreempt_disable();
   5529 	softint_schedule(mixer->sih);
   5530 	kpreempt_enable();
   5531 }
   5532 
   5533 /*
   5534  * Halts playback mixer.
   5535  * This function also clears related parameters, so call this function
   5536  * instead of calling halt_output directly.
   5537  * Must be called only if sc_pbusy is true.
   5538  * Must be called with sc_lock && sc_exlock held.
   5539  */
   5540 static int
   5541 audio_pmixer_halt(struct audio_softc *sc)
   5542 {
   5543 	int error;
   5544 
   5545 	TRACE(2, "");
   5546 	KASSERT(mutex_owned(sc->sc_lock));
   5547 	KASSERT(sc->sc_exlock);
   5548 
   5549 	mutex_enter(sc->sc_intr_lock);
   5550 	error = sc->hw_if->halt_output(sc->hw_hdl);
   5551 	mutex_exit(sc->sc_intr_lock);
   5552 
   5553 	/* Halts anyway even if some error has occurred. */
   5554 	sc->sc_pbusy = false;
   5555 	sc->sc_pmixer->hwbuf.head = 0;
   5556 	sc->sc_pmixer->hwbuf.used = 0;
   5557 	sc->sc_pmixer->mixseq = 0;
   5558 	sc->sc_pmixer->hwseq = 0;
   5559 
   5560 	return error;
   5561 }
   5562 
   5563 /*
   5564  * Halts recording mixer.
   5565  * This function also clears related parameters, so call this function
   5566  * instead of calling halt_input directly.
   5567  * Must be called only if sc_rbusy is true.
   5568  * Must be called with sc_lock && sc_exlock held.
   5569  */
   5570 static int
   5571 audio_rmixer_halt(struct audio_softc *sc)
   5572 {
   5573 	int error;
   5574 
   5575 	TRACE(2, "");
   5576 	KASSERT(mutex_owned(sc->sc_lock));
   5577 	KASSERT(sc->sc_exlock);
   5578 
   5579 	mutex_enter(sc->sc_intr_lock);
   5580 	error = sc->hw_if->halt_input(sc->hw_hdl);
   5581 	mutex_exit(sc->sc_intr_lock);
   5582 
   5583 	/* Halts anyway even if some error has occurred. */
   5584 	sc->sc_rbusy = false;
   5585 	sc->sc_rmixer->hwbuf.head = 0;
   5586 	sc->sc_rmixer->hwbuf.used = 0;
   5587 	sc->sc_rmixer->mixseq = 0;
   5588 	sc->sc_rmixer->hwseq = 0;
   5589 
   5590 	return error;
   5591 }
   5592 
   5593 /*
   5594  * Flush this track.
   5595  * Halts all operations, clears all buffers, reset error counters.
   5596  * XXX I'm not sure...
   5597  */
   5598 static void
   5599 audio_track_clear(struct audio_softc *sc, audio_track_t *track)
   5600 {
   5601 
   5602 	KASSERT(track);
   5603 	TRACET(3, track, "clear");
   5604 
   5605 	audio_track_lock_enter(track);
   5606 
   5607 	track->usrbuf.used = 0;
   5608 	/* Clear all internal parameters. */
   5609 	if (track->codec.filter) {
   5610 		track->codec.srcbuf.used = 0;
   5611 		track->codec.srcbuf.head = 0;
   5612 	}
   5613 	if (track->chvol.filter) {
   5614 		track->chvol.srcbuf.used = 0;
   5615 		track->chvol.srcbuf.head = 0;
   5616 	}
   5617 	if (track->chmix.filter) {
   5618 		track->chmix.srcbuf.used = 0;
   5619 		track->chmix.srcbuf.head = 0;
   5620 	}
   5621 	if (track->freq.filter) {
   5622 		track->freq.srcbuf.used = 0;
   5623 		track->freq.srcbuf.head = 0;
   5624 		if (track->freq_step < 65536)
   5625 			track->freq_current = 65536;
   5626 		else
   5627 			track->freq_current = 0;
   5628 		memset(track->freq_prev, 0, sizeof(track->freq_prev));
   5629 		memset(track->freq_curr, 0, sizeof(track->freq_curr));
   5630 	}
   5631 	/* Clear buffer, then operation halts naturally. */
   5632 	track->outbuf.used = 0;
   5633 
   5634 	/* Clear counters. */
   5635 	track->dropframes = 0;
   5636 
   5637 	audio_track_lock_exit(track);
   5638 }
   5639 
   5640 /*
   5641  * Drain the track.
   5642  * track must be present and for playback.
   5643  * If successful, it returns 0.  Otherwise returns errno.
   5644  * Must be called with sc_lock held.
   5645  */
   5646 static int
   5647 audio_track_drain(struct audio_softc *sc, audio_track_t *track)
   5648 {
   5649 	audio_trackmixer_t *mixer;
   5650 	int done;
   5651 	int error;
   5652 
   5653 	KASSERT(track);
   5654 	TRACET(3, track, "start");
   5655 	mixer = track->mixer;
   5656 	KASSERT(mutex_owned(sc->sc_lock));
   5657 
   5658 	/* Ignore them if pause. */
   5659 	if (track->is_pause) {
   5660 		TRACET(3, track, "pause -> clear");
   5661 		track->pstate = AUDIO_STATE_CLEAR;
   5662 	}
   5663 	/* Terminate early here if there is no data in the track. */
   5664 	if (track->pstate == AUDIO_STATE_CLEAR) {
   5665 		TRACET(3, track, "no need to drain");
   5666 		return 0;
   5667 	}
   5668 	track->pstate = AUDIO_STATE_DRAINING;
   5669 
   5670 	for (;;) {
   5671 		/* I want to display it before condition evaluation. */
   5672 		TRACET(3, track, "pid=%d.%d trkseq=%d hwseq=%d out=%d/%d/%d",
   5673 		    (int)curproc->p_pid, (int)curlwp->l_lid,
   5674 		    (int)track->seq, (int)mixer->hwseq,
   5675 		    track->outbuf.head, track->outbuf.used,
   5676 		    track->outbuf.capacity);
   5677 
   5678 		/* Condition to terminate */
   5679 		audio_track_lock_enter(track);
   5680 		done = (track->usrbuf.used < frametobyte(&track->inputfmt, 1) &&
   5681 		    track->outbuf.used == 0 &&
   5682 		    track->seq <= mixer->hwseq);
   5683 		audio_track_lock_exit(track);
   5684 		if (done)
   5685 			break;
   5686 
   5687 		TRACET(3, track, "sleep");
   5688 		error = audio_track_waitio(sc, track);
   5689 		if (error)
   5690 			return error;
   5691 
   5692 		/* XXX call audio_track_play here ? */
   5693 	}
   5694 
   5695 	track->pstate = AUDIO_STATE_CLEAR;
   5696 	TRACET(3, track, "done trk_inp=%d trk_out=%d",
   5697 		(int)track->inputcounter, (int)track->outputcounter);
   5698 	return 0;
   5699 }
   5700 
   5701 /*
   5702  * Send signal to process.
   5703  * This is intended to be called only from audio_softintr_{rd,wr}.
   5704  * Must be called with sc_lock && sc_intr_lock held.
   5705  */
   5706 static inline void
   5707 audio_psignal(struct audio_softc *sc, pid_t pid, int signum)
   5708 {
   5709 	proc_t *p;
   5710 
   5711 	KASSERT(mutex_owned(sc->sc_lock));
   5712 	KASSERT(mutex_owned(sc->sc_intr_lock));
   5713 	KASSERT(pid != 0);
   5714 
   5715 	/*
   5716 	 * psignal() must be called without spin lock held.
   5717 	 * So leave intr_lock temporarily here.
   5718 	 */
   5719 	mutex_exit(sc->sc_intr_lock);
   5720 
   5721 	mutex_enter(proc_lock);
   5722 	p = proc_find(pid);
   5723 	if (p)
   5724 		psignal(p, signum);
   5725 	mutex_exit(proc_lock);
   5726 
   5727 	/* Enter intr_lock again */
   5728 	mutex_enter(sc->sc_intr_lock);
   5729 }
   5730 
   5731 /*
   5732  * This is software interrupt handler for record.
   5733  * It is called from recording hardware interrupt everytime.
   5734  * It does:
   5735  * - Deliver SIGIO for all async processes.
   5736  * - Notify to audio_read() that data has arrived.
   5737  * - selnotify() for select/poll-ing processes.
   5738  */
   5739 /*
   5740  * XXX If a process issues FIOASYNC between hardware interrupt and
   5741  *     software interrupt, (stray) SIGIO will be sent to the process
   5742  *     despite the fact that it has not receive recorded data yet.
   5743  */
   5744 static void
   5745 audio_softintr_rd(void *cookie)
   5746 {
   5747 	struct audio_softc *sc = cookie;
   5748 	audio_file_t *f;
   5749 	pid_t pid;
   5750 
   5751 	mutex_enter(sc->sc_lock);
   5752 	mutex_enter(sc->sc_intr_lock);
   5753 
   5754 	SLIST_FOREACH(f, &sc->sc_files, entry) {
   5755 		audio_track_t *track = f->rtrack;
   5756 
   5757 		if (track == NULL)
   5758 			continue;
   5759 
   5760 		TRACET(4, track, "broadcast; inp=%d/%d/%d",
   5761 		    track->input->head,
   5762 		    track->input->used,
   5763 		    track->input->capacity);
   5764 
   5765 		pid = f->async_audio;
   5766 		if (pid != 0) {
   5767 			TRACEF(4, f, "sending SIGIO %d", pid);
   5768 			audio_psignal(sc, pid, SIGIO);
   5769 		}
   5770 	}
   5771 	mutex_exit(sc->sc_intr_lock);
   5772 
   5773 	/* Notify that data has arrived. */
   5774 	selnotify(&sc->sc_rsel, 0, NOTE_SUBMIT);
   5775 	KNOTE(&sc->sc_rsel.sel_klist, 0);
   5776 	cv_broadcast(&sc->sc_rmixer->outcv);
   5777 
   5778 	mutex_exit(sc->sc_lock);
   5779 }
   5780 
   5781 /*
   5782  * This is software interrupt handler for playback.
   5783  * It is called from playback hardware interrupt everytime.
   5784  * It does:
   5785  * - Deliver SIGIO for all async and writable (used < lowat) processes.
   5786  * - Notify to audio_write() that outbuf block available.
   5787  * - selnotify() for select/poll-ing processes if there are any writable
   5788  *   (used < lowat) processes.  Checking each descriptor will be done by
   5789  *   filt_audiowrite_event().
   5790  */
   5791 static void
   5792 audio_softintr_wr(void *cookie)
   5793 {
   5794 	struct audio_softc *sc = cookie;
   5795 	audio_file_t *f;
   5796 	bool found;
   5797 	pid_t pid;
   5798 
   5799 	TRACE(4, "called");
   5800 	found = false;
   5801 
   5802 	mutex_enter(sc->sc_lock);
   5803 	mutex_enter(sc->sc_intr_lock);
   5804 
   5805 	SLIST_FOREACH(f, &sc->sc_files, entry) {
   5806 		audio_track_t *track = f->ptrack;
   5807 
   5808 		if (track == NULL)
   5809 			continue;
   5810 
   5811 		TRACET(4, track, "broadcast; trseq=%d out=%d/%d/%d",
   5812 		    (int)track->seq,
   5813 		    track->outbuf.head,
   5814 		    track->outbuf.used,
   5815 		    track->outbuf.capacity);
   5816 
   5817 		/*
   5818 		 * Send a signal if the process is async mode and
   5819 		 * used is lower than lowat.
   5820 		 */
   5821 		if (track->usrbuf.used <= track->usrbuf_usedlow &&
   5822 		    !track->is_pause) {
   5823 			/* For selnotify */
   5824 			found = true;
   5825 			/* For SIGIO */
   5826 			pid = f->async_audio;
   5827 			if (pid != 0) {
   5828 				TRACEF(4, f, "sending SIGIO %d", pid);
   5829 				audio_psignal(sc, pid, SIGIO);
   5830 			}
   5831 		}
   5832 	}
   5833 	mutex_exit(sc->sc_intr_lock);
   5834 
   5835 	/*
   5836 	 * Notify for select/poll when someone become writable.
   5837 	 * It needs sc_lock (and not sc_intr_lock).
   5838 	 */
   5839 	if (found) {
   5840 		TRACE(4, "selnotify");
   5841 		selnotify(&sc->sc_wsel, 0, NOTE_SUBMIT);
   5842 		KNOTE(&sc->sc_wsel.sel_klist, 0);
   5843 	}
   5844 
   5845 	/* Notify to audio_write() that outbuf available. */
   5846 	cv_broadcast(&sc->sc_pmixer->outcv);
   5847 
   5848 	mutex_exit(sc->sc_lock);
   5849 }
   5850 
   5851 /*
   5852  * Check (and convert) the format *p came from userland.
   5853  * If successful, it writes back the converted format to *p if necessary
   5854  * and returns 0.  Otherwise returns errno (*p may change even this case).
   5855  */
   5856 static int
   5857 audio_check_params(audio_format2_t *p)
   5858 {
   5859 
   5860 	/* Convert obsoleted AUDIO_ENCODING_PCM* */
   5861 	/* XXX Is this conversion right? */
   5862 	if (p->encoding == AUDIO_ENCODING_PCM16) {
   5863 		if (p->precision == 8)
   5864 			p->encoding = AUDIO_ENCODING_ULINEAR;
   5865 		else
   5866 			p->encoding = AUDIO_ENCODING_SLINEAR;
   5867 	} else if (p->encoding == AUDIO_ENCODING_PCM8) {
   5868 		if (p->precision == 8)
   5869 			p->encoding = AUDIO_ENCODING_ULINEAR;
   5870 		else
   5871 			return EINVAL;
   5872 	}
   5873 
   5874 	/*
   5875 	 * Convert obsoleted AUDIO_ENCODING_[SU]LINEAR without endianness
   5876 	 * suffix.
   5877 	 */
   5878 	if (p->encoding == AUDIO_ENCODING_SLINEAR)
   5879 		p->encoding = AUDIO_ENCODING_SLINEAR_NE;
   5880 	if (p->encoding == AUDIO_ENCODING_ULINEAR)
   5881 		p->encoding = AUDIO_ENCODING_ULINEAR_NE;
   5882 
   5883 	switch (p->encoding) {
   5884 	case AUDIO_ENCODING_ULAW:
   5885 	case AUDIO_ENCODING_ALAW:
   5886 		if (p->precision != 8)
   5887 			return EINVAL;
   5888 		break;
   5889 	case AUDIO_ENCODING_ADPCM:
   5890 		if (p->precision != 4 && p->precision != 8)
   5891 			return EINVAL;
   5892 		break;
   5893 	case AUDIO_ENCODING_SLINEAR_LE:
   5894 	case AUDIO_ENCODING_SLINEAR_BE:
   5895 	case AUDIO_ENCODING_ULINEAR_LE:
   5896 	case AUDIO_ENCODING_ULINEAR_BE:
   5897 		if (p->precision !=  8 && p->precision != 16 &&
   5898 		    p->precision != 24 && p->precision != 32)
   5899 			return EINVAL;
   5900 
   5901 		/* 8bit format does not have endianness. */
   5902 		if (p->precision == 8) {
   5903 			if (p->encoding == AUDIO_ENCODING_SLINEAR_OE)
   5904 				p->encoding = AUDIO_ENCODING_SLINEAR_NE;
   5905 			if (p->encoding == AUDIO_ENCODING_ULINEAR_OE)
   5906 				p->encoding = AUDIO_ENCODING_ULINEAR_NE;
   5907 		}
   5908 
   5909 		if (p->precision > p->stride)
   5910 			return EINVAL;
   5911 		break;
   5912 	case AUDIO_ENCODING_MPEG_L1_STREAM:
   5913 	case AUDIO_ENCODING_MPEG_L1_PACKETS:
   5914 	case AUDIO_ENCODING_MPEG_L1_SYSTEM:
   5915 	case AUDIO_ENCODING_MPEG_L2_STREAM:
   5916 	case AUDIO_ENCODING_MPEG_L2_PACKETS:
   5917 	case AUDIO_ENCODING_MPEG_L2_SYSTEM:
   5918 	case AUDIO_ENCODING_AC3:
   5919 		break;
   5920 	default:
   5921 		return EINVAL;
   5922 	}
   5923 
   5924 	/* sanity check # of channels*/
   5925 	if (p->channels < 1 || p->channels > AUDIO_MAX_CHANNELS)
   5926 		return EINVAL;
   5927 
   5928 	return 0;
   5929 }
   5930 
   5931 /*
   5932  * Initialize playback and record mixers.
   5933  * mode (AUMODE_{PLAY,RECORD}) indicates the mixer to be initialized.
   5934  * phwfmt and rhwfmt indicate the hardware format.  pfil and rfil indicate
   5935  * the filter registration information.  These four must not be NULL.
   5936  * If successful returns 0.  Otherwise returns errno.
   5937  * Must be called with sc_lock held.
   5938  * Must not be called if there are any tracks.
   5939  * Caller should check that the initialization succeed by whether
   5940  * sc_[pr]mixer is not NULL.
   5941  */
   5942 static int
   5943 audio_mixers_init(struct audio_softc *sc, int mode,
   5944 	const audio_format2_t *phwfmt, const audio_format2_t *rhwfmt,
   5945 	const audio_filter_reg_t *pfil, const audio_filter_reg_t *rfil)
   5946 {
   5947 	int error;
   5948 
   5949 	KASSERT(phwfmt != NULL);
   5950 	KASSERT(rhwfmt != NULL);
   5951 	KASSERT(pfil != NULL);
   5952 	KASSERT(rfil != NULL);
   5953 	KASSERT(mutex_owned(sc->sc_lock));
   5954 
   5955 	if ((mode & AUMODE_PLAY)) {
   5956 		if (sc->sc_pmixer == NULL) {
   5957 			sc->sc_pmixer = kmem_zalloc(sizeof(*sc->sc_pmixer),
   5958 			    KM_SLEEP);
   5959 		} else {
   5960 			/* destroy() doesn't free memory. */
   5961 			audio_mixer_destroy(sc, sc->sc_pmixer);
   5962 			memset(sc->sc_pmixer, 0, sizeof(*sc->sc_pmixer));
   5963 		}
   5964 		error = audio_mixer_init(sc, AUMODE_PLAY, phwfmt, pfil);
   5965 		if (error) {
   5966 			device_printf(sc->sc_dev,
   5967 			    "configuring playback mode failed with %d\n",
   5968 			    error);
   5969 			kmem_free(sc->sc_pmixer, sizeof(*sc->sc_pmixer));
   5970 			sc->sc_pmixer = NULL;
   5971 			return error;
   5972 		}
   5973 	}
   5974 	if ((mode & AUMODE_RECORD)) {
   5975 		if (sc->sc_rmixer == NULL) {
   5976 			sc->sc_rmixer = kmem_zalloc(sizeof(*sc->sc_rmixer),
   5977 			    KM_SLEEP);
   5978 		} else {
   5979 			/* destroy() doesn't free memory. */
   5980 			audio_mixer_destroy(sc, sc->sc_rmixer);
   5981 			memset(sc->sc_rmixer, 0, sizeof(*sc->sc_rmixer));
   5982 		}
   5983 		error = audio_mixer_init(sc, AUMODE_RECORD, rhwfmt, rfil);
   5984 		if (error) {
   5985 			device_printf(sc->sc_dev,
   5986 			    "configuring record mode failed with %d\n",
   5987 			    error);
   5988 			kmem_free(sc->sc_rmixer, sizeof(*sc->sc_rmixer));
   5989 			sc->sc_rmixer = NULL;
   5990 			return error;
   5991 		}
   5992 	}
   5993 
   5994 	return 0;
   5995 }
   5996 
   5997 /*
   5998  * Select a frequency.
   5999  * Prioritize 48kHz and 44.1kHz.  Otherwise choose the highest one.
   6000  * XXX Better algorithm?
   6001  */
   6002 static int
   6003 audio_select_freq(const struct audio_format *fmt)
   6004 {
   6005 	int freq;
   6006 	int high;
   6007 	int low;
   6008 	int j;
   6009 
   6010 	if (fmt->frequency_type == 0) {
   6011 		low = fmt->frequency[0];
   6012 		high = fmt->frequency[1];
   6013 		freq = 48000;
   6014 		if (low <= freq && freq <= high) {
   6015 			return freq;
   6016 		}
   6017 		freq = 44100;
   6018 		if (low <= freq && freq <= high) {
   6019 			return freq;
   6020 		}
   6021 		return high;
   6022 	} else {
   6023 		for (j = 0; j < fmt->frequency_type; j++) {
   6024 			if (fmt->frequency[j] == 48000) {
   6025 				return fmt->frequency[j];
   6026 			}
   6027 		}
   6028 		high = 0;
   6029 		for (j = 0; j < fmt->frequency_type; j++) {
   6030 			if (fmt->frequency[j] == 44100) {
   6031 				return fmt->frequency[j];
   6032 			}
   6033 			if (fmt->frequency[j] > high) {
   6034 				high = fmt->frequency[j];
   6035 			}
   6036 		}
   6037 		return high;
   6038 	}
   6039 }
   6040 
   6041 /*
   6042  * Probe playback and/or recording format (depending on *modep).
   6043  * *modep is an in-out parameter.  It indicates the direction to configure
   6044  * as an argument, and the direction configured is written back as out
   6045  * parameter.
   6046  * If successful, probed hardware format is stored into *phwfmt, *rhwfmt
   6047  * depending on *modep, and return 0.  Otherwise it returns errno.
   6048  * Must be called with sc_lock held.
   6049  */
   6050 static int
   6051 audio_hw_probe(struct audio_softc *sc, int is_indep, int *modep,
   6052 	audio_format2_t *phwfmt, audio_format2_t *rhwfmt)
   6053 {
   6054 	audio_format2_t fmt;
   6055 	int mode;
   6056 	int error = 0;
   6057 
   6058 	KASSERT(mutex_owned(sc->sc_lock));
   6059 
   6060 	mode = *modep;
   6061 	KASSERTMSG((mode & (AUMODE_PLAY | AUMODE_RECORD)) != 0, "mode=0x%x", mode);
   6062 
   6063 	if (is_indep) {
   6064 		int errorp = 0, errorr = 0;
   6065 
   6066 		/* On independent devices, probe separately. */
   6067 		if ((mode & AUMODE_PLAY) != 0) {
   6068 			errorp = audio_hw_probe_fmt(sc, phwfmt, AUMODE_PLAY);
   6069 			if (errorp)
   6070 				mode &= ~AUMODE_PLAY;
   6071 		}
   6072 		if ((mode & AUMODE_RECORD) != 0) {
   6073 			errorr = audio_hw_probe_fmt(sc, rhwfmt, AUMODE_RECORD);
   6074 			if (errorr)
   6075 				mode &= ~AUMODE_RECORD;
   6076 		}
   6077 
   6078 		/* Return error if both play and record probes failed. */
   6079 		if (errorp && errorr)
   6080 			error = errorp;
   6081 	} else {
   6082 		/* On non independent devices, probe simultaneously. */
   6083 		error = audio_hw_probe_fmt(sc, &fmt, mode);
   6084 		if (error) {
   6085 			mode = 0;
   6086 		} else {
   6087 			*phwfmt = fmt;
   6088 			*rhwfmt = fmt;
   6089 		}
   6090 	}
   6091 
   6092 	*modep = mode;
   6093 	return error;
   6094 }
   6095 
   6096 /*
   6097  * Choose the most preferred hardware format.
   6098  * If successful, it will store the chosen format into *cand and return 0.
   6099  * Otherwise, return errno.
   6100  * Must be called with sc_lock held.
   6101  */
   6102 static int
   6103 audio_hw_probe_fmt(struct audio_softc *sc, audio_format2_t *cand, int mode)
   6104 {
   6105 	audio_format_query_t query;
   6106 	int cand_score;
   6107 	int score;
   6108 	int i;
   6109 	int error;
   6110 
   6111 	KASSERT(mutex_owned(sc->sc_lock));
   6112 
   6113 	/*
   6114 	 * Score each formats and choose the highest one.
   6115 	 *
   6116 	 *                 +---- priority(0-3)
   6117 	 *                 |+--- encoding/precision
   6118 	 *                 ||+-- channels
   6119 	 * score = 0x000000PEC
   6120 	 */
   6121 
   6122 	cand_score = 0;
   6123 	for (i = 0; ; i++) {
   6124 		memset(&query, 0, sizeof(query));
   6125 		query.index = i;
   6126 
   6127 		error = sc->hw_if->query_format(sc->hw_hdl, &query);
   6128 		if (error == EINVAL)
   6129 			break;
   6130 		if (error)
   6131 			return error;
   6132 
   6133 #if defined(AUDIO_DEBUG)
   6134 		DPRINTF(1, "fmt[%d] %c%c pri=%d %s,%d/%dbit,%dch,", i,
   6135 		    (query.fmt.mode & AUMODE_PLAY)   ? 'P' : '-',
   6136 		    (query.fmt.mode & AUMODE_RECORD) ? 'R' : '-',
   6137 		    query.fmt.priority,
   6138 		    audio_encoding_name(query.fmt.encoding),
   6139 		    query.fmt.validbits,
   6140 		    query.fmt.precision,
   6141 		    query.fmt.channels);
   6142 		if (query.fmt.frequency_type == 0) {
   6143 			DPRINTF(1, "{%d-%d",
   6144 			    query.fmt.frequency[0], query.fmt.frequency[1]);
   6145 		} else {
   6146 			int j;
   6147 			for (j = 0; j < query.fmt.frequency_type; j++) {
   6148 				DPRINTF(1, "%c%d",
   6149 				    (j == 0) ? '{' : ',',
   6150 				    query.fmt.frequency[j]);
   6151 			}
   6152 		}
   6153 		DPRINTF(1, "}\n");
   6154 #endif
   6155 
   6156 		if ((query.fmt.mode & mode) == 0) {
   6157 			DPRINTF(1, "fmt[%d] skip; mode not match %d\n", i,
   6158 			    mode);
   6159 			continue;
   6160 		}
   6161 
   6162 		if (query.fmt.priority < 0) {
   6163 			DPRINTF(1, "fmt[%d] skip; unsupported encoding\n", i);
   6164 			continue;
   6165 		}
   6166 
   6167 		/* Score */
   6168 		score = (query.fmt.priority & 3) * 0x100;
   6169 		if (query.fmt.encoding == AUDIO_ENCODING_SLINEAR_NE &&
   6170 		    query.fmt.validbits == AUDIO_INTERNAL_BITS &&
   6171 		    query.fmt.precision == AUDIO_INTERNAL_BITS) {
   6172 			score += 0x20;
   6173 		} else if (query.fmt.encoding == AUDIO_ENCODING_SLINEAR_OE &&
   6174 		    query.fmt.validbits == AUDIO_INTERNAL_BITS &&
   6175 		    query.fmt.precision == AUDIO_INTERNAL_BITS) {
   6176 			score += 0x10;
   6177 		}
   6178 		score += query.fmt.channels;
   6179 
   6180 		if (score < cand_score) {
   6181 			DPRINTF(1, "fmt[%d] skip; score 0x%x < 0x%x\n", i,
   6182 			    score, cand_score);
   6183 			continue;
   6184 		}
   6185 
   6186 		/* Update candidate */
   6187 		cand_score = score;
   6188 		cand->encoding    = query.fmt.encoding;
   6189 		cand->precision   = query.fmt.validbits;
   6190 		cand->stride      = query.fmt.precision;
   6191 		cand->channels    = query.fmt.channels;
   6192 		cand->sample_rate = audio_select_freq(&query.fmt);
   6193 		DPRINTF(1, "fmt[%d] candidate (score=0x%x)"
   6194 		    " pri=%d %s,%d/%d,%dch,%dHz\n", i,
   6195 		    cand_score, query.fmt.priority,
   6196 		    audio_encoding_name(query.fmt.encoding),
   6197 		    cand->precision, cand->stride,
   6198 		    cand->channels, cand->sample_rate);
   6199 	}
   6200 
   6201 	if (cand_score == 0) {
   6202 		DPRINTF(1, "%s no fmt\n", __func__);
   6203 		return ENXIO;
   6204 	}
   6205 	DPRINTF(1, "%s selected: %s,%d/%d,%dch,%dHz\n", __func__,
   6206 	    audio_encoding_name(cand->encoding),
   6207 	    cand->precision, cand->stride, cand->channels, cand->sample_rate);
   6208 	return 0;
   6209 }
   6210 
   6211 /*
   6212  * Validate fmt with query_format.
   6213  * If fmt is included in the result of query_format, returns 0.
   6214  * Otherwise returns EINVAL.
   6215  * Must be called with sc_lock held.
   6216  */
   6217 static int
   6218 audio_hw_validate_format(struct audio_softc *sc, int mode,
   6219 	const audio_format2_t *fmt)
   6220 {
   6221 	audio_format_query_t query;
   6222 	struct audio_format *q;
   6223 	int index;
   6224 	int error;
   6225 	int j;
   6226 
   6227 	KASSERT(mutex_owned(sc->sc_lock));
   6228 
   6229 	/*
   6230 	 * If query_format is not supported by hardware driver,
   6231 	 * a rough check instead will be performed.
   6232 	 * XXX This will gone in the future.
   6233 	 */
   6234 	if (sc->hw_if->query_format == NULL) {
   6235 		if (fmt->encoding != AUDIO_ENCODING_SLINEAR_NE)
   6236 			return EINVAL;
   6237 		if (fmt->precision != AUDIO_INTERNAL_BITS)
   6238 			return EINVAL;
   6239 		if (fmt->stride != AUDIO_INTERNAL_BITS)
   6240 			return EINVAL;
   6241 		return 0;
   6242 	}
   6243 
   6244 	for (index = 0; ; index++) {
   6245 		query.index = index;
   6246 		error = sc->hw_if->query_format(sc->hw_hdl, &query);
   6247 		if (error == EINVAL)
   6248 			break;
   6249 		if (error)
   6250 			return error;
   6251 
   6252 		q = &query.fmt;
   6253 		/*
   6254 		 * Note that fmt is audio_format2_t (precision/stride) but
   6255 		 * q is audio_format_t (validbits/precision).
   6256 		 */
   6257 		if ((q->mode & mode) == 0) {
   6258 			continue;
   6259 		}
   6260 		if (fmt->encoding != q->encoding) {
   6261 			continue;
   6262 		}
   6263 		if (fmt->precision != q->validbits) {
   6264 			continue;
   6265 		}
   6266 		if (fmt->stride != q->precision) {
   6267 			continue;
   6268 		}
   6269 		if (fmt->channels != q->channels) {
   6270 			continue;
   6271 		}
   6272 		if (q->frequency_type == 0) {
   6273 			if (fmt->sample_rate < q->frequency[0] ||
   6274 			    fmt->sample_rate > q->frequency[1]) {
   6275 				continue;
   6276 			}
   6277 		} else {
   6278 			for (j = 0; j < q->frequency_type; j++) {
   6279 				if (fmt->sample_rate == q->frequency[j])
   6280 					break;
   6281 			}
   6282 			if (j == query.fmt.frequency_type) {
   6283 				continue;
   6284 			}
   6285 		}
   6286 
   6287 		/* Matched. */
   6288 		return 0;
   6289 	}
   6290 
   6291 	return EINVAL;
   6292 }
   6293 
   6294 /*
   6295  * Set track mixer's format depending on ai->mode.
   6296  * If AUMODE_PLAY is set in ai->mode, it set up the playback mixer
   6297  * with ai.play.*.
   6298  * If AUMODE_RECORD is set in ai->mode, it set up the recording mixer
   6299  * with ai.record.*.
   6300  * All other fields in ai are ignored.
   6301  * If successful returns 0.  Otherwise returns errno.
   6302  * This function does not roll back even if it fails.
   6303  * Must be called with sc_lock held.
   6304  */
   6305 static int
   6306 audio_mixers_set_format(struct audio_softc *sc, const struct audio_info *ai)
   6307 {
   6308 	audio_format2_t phwfmt;
   6309 	audio_format2_t rhwfmt;
   6310 	audio_filter_reg_t pfil;
   6311 	audio_filter_reg_t rfil;
   6312 	int mode;
   6313 	int error;
   6314 
   6315 	KASSERT(mutex_owned(sc->sc_lock));
   6316 
   6317 	/*
   6318 	 * Even when setting either one of playback and recording,
   6319 	 * both must be halted.
   6320 	 */
   6321 	if (sc->sc_popens + sc->sc_ropens > 0)
   6322 		return EBUSY;
   6323 
   6324 	if (!SPECIFIED(ai->mode) || ai->mode == 0)
   6325 		return ENOTTY;
   6326 
   6327 	mode = ai->mode;
   6328 	if ((mode & AUMODE_PLAY)) {
   6329 		phwfmt.encoding    = ai->play.encoding;
   6330 		phwfmt.precision   = ai->play.precision;
   6331 		phwfmt.stride      = ai->play.precision;
   6332 		phwfmt.channels    = ai->play.channels;
   6333 		phwfmt.sample_rate = ai->play.sample_rate;
   6334 	}
   6335 	if ((mode & AUMODE_RECORD)) {
   6336 		rhwfmt.encoding    = ai->record.encoding;
   6337 		rhwfmt.precision   = ai->record.precision;
   6338 		rhwfmt.stride      = ai->record.precision;
   6339 		rhwfmt.channels    = ai->record.channels;
   6340 		rhwfmt.sample_rate = ai->record.sample_rate;
   6341 	}
   6342 
   6343 	/* On non-independent devices, use the same format for both. */
   6344 	if ((sc->sc_props & AUDIO_PROP_INDEPENDENT) == 0) {
   6345 		if (mode == AUMODE_RECORD) {
   6346 			phwfmt = rhwfmt;
   6347 		} else {
   6348 			rhwfmt = phwfmt;
   6349 		}
   6350 		mode = AUMODE_PLAY | AUMODE_RECORD;
   6351 	}
   6352 
   6353 	/* Then, unset the direction not exist on the hardware. */
   6354 	if ((sc->sc_props & AUDIO_PROP_PLAYBACK) == 0)
   6355 		mode &= ~AUMODE_PLAY;
   6356 	if ((sc->sc_props & AUDIO_PROP_CAPTURE) == 0)
   6357 		mode &= ~AUMODE_RECORD;
   6358 
   6359 	/* debug */
   6360 	if ((mode & AUMODE_PLAY)) {
   6361 		TRACE(1, "play=%s/%d/%d/%dch/%dHz",
   6362 		    audio_encoding_name(phwfmt.encoding),
   6363 		    phwfmt.precision,
   6364 		    phwfmt.stride,
   6365 		    phwfmt.channels,
   6366 		    phwfmt.sample_rate);
   6367 	}
   6368 	if ((mode & AUMODE_RECORD)) {
   6369 		TRACE(1, "rec =%s/%d/%d/%dch/%dHz",
   6370 		    audio_encoding_name(rhwfmt.encoding),
   6371 		    rhwfmt.precision,
   6372 		    rhwfmt.stride,
   6373 		    rhwfmt.channels,
   6374 		    rhwfmt.sample_rate);
   6375 	}
   6376 
   6377 	/* Check the format */
   6378 	if ((mode & AUMODE_PLAY)) {
   6379 		if (audio_hw_validate_format(sc, AUMODE_PLAY, &phwfmt)) {
   6380 			TRACE(1, "invalid format");
   6381 			return EINVAL;
   6382 		}
   6383 	}
   6384 	if ((mode & AUMODE_RECORD)) {
   6385 		if (audio_hw_validate_format(sc, AUMODE_RECORD, &rhwfmt)) {
   6386 			TRACE(1, "invalid format");
   6387 			return EINVAL;
   6388 		}
   6389 	}
   6390 
   6391 	/* Configure the mixers. */
   6392 	memset(&pfil, 0, sizeof(pfil));
   6393 	memset(&rfil, 0, sizeof(rfil));
   6394 	error = audio_hw_set_format(sc, mode, &phwfmt, &rhwfmt, &pfil, &rfil);
   6395 	if (error)
   6396 		return error;
   6397 
   6398 	error = audio_mixers_init(sc, mode, &phwfmt, &rhwfmt, &pfil, &rfil);
   6399 	if (error)
   6400 		return error;
   6401 
   6402 	return 0;
   6403 }
   6404 
   6405 /*
   6406  * Store current mixers format into *ai.
   6407  */
   6408 static void
   6409 audio_mixers_get_format(struct audio_softc *sc, struct audio_info *ai)
   6410 {
   6411 	/*
   6412 	 * There is no stride information in audio_info but it doesn't matter.
   6413 	 * trackmixer always treats stride and precision as the same.
   6414 	 */
   6415 	AUDIO_INITINFO(ai);
   6416 	ai->mode = 0;
   6417 	if (sc->sc_pmixer) {
   6418 		audio_format2_t *fmt = &sc->sc_pmixer->track_fmt;
   6419 		ai->play.encoding    = fmt->encoding;
   6420 		ai->play.precision   = fmt->precision;
   6421 		ai->play.channels    = fmt->channels;
   6422 		ai->play.sample_rate = fmt->sample_rate;
   6423 		ai->mode |= AUMODE_PLAY;
   6424 	}
   6425 	if (sc->sc_rmixer) {
   6426 		audio_format2_t *fmt = &sc->sc_rmixer->track_fmt;
   6427 		ai->record.encoding    = fmt->encoding;
   6428 		ai->record.precision   = fmt->precision;
   6429 		ai->record.channels    = fmt->channels;
   6430 		ai->record.sample_rate = fmt->sample_rate;
   6431 		ai->mode |= AUMODE_RECORD;
   6432 	}
   6433 }
   6434 
   6435 /*
   6436  * audio_info details:
   6437  *
   6438  * ai.{play,record}.sample_rate		(R/W)
   6439  * ai.{play,record}.encoding		(R/W)
   6440  * ai.{play,record}.precision		(R/W)
   6441  * ai.{play,record}.channels		(R/W)
   6442  *	These specify the playback or recording format.
   6443  *	Ignore members within an inactive track.
   6444  *
   6445  * ai.mode				(R/W)
   6446  *	It specifies the playback or recording mode, AUMODE_*.
   6447  *	Currently, a mode change operation by ai.mode after opening is
   6448  *	prohibited.  In addition, AUMODE_PLAY_ALL no longer makes sense.
   6449  *	However, it's possible to get or to set for backward compatibility.
   6450  *
   6451  * ai.{hiwat,lowat}			(R/W)
   6452  *	These specify the high water mark and low water mark for playback
   6453  *	track.  The unit is block.
   6454  *
   6455  * ai.{play,record}.gain		(R/W)
   6456  *	It specifies the HW mixer volume in 0-255.
   6457  *	It is historical reason that the gain is connected to HW mixer.
   6458  *
   6459  * ai.{play,record}.balance		(R/W)
   6460  *	It specifies the left-right balance of HW mixer in 0-64.
   6461  *	32 means the center.
   6462  *	It is historical reason that the balance is connected to HW mixer.
   6463  *
   6464  * ai.{play,record}.port		(R/W)
   6465  *	It specifies the input/output port of HW mixer.
   6466  *
   6467  * ai.monitor_gain			(R/W)
   6468  *	It specifies the recording monitor gain(?) of HW mixer.
   6469  *
   6470  * ai.{play,record}.pause		(R/W)
   6471  *	Non-zero means the track is paused.
   6472  *
   6473  * ai.play.seek				(R/-)
   6474  *	It indicates the number of bytes written but not processed.
   6475  * ai.record.seek			(R/-)
   6476  *	It indicates the number of bytes to be able to read.
   6477  *
   6478  * ai.{play,record}.avail_ports		(R/-)
   6479  *	Mixer info.
   6480  *
   6481  * ai.{play,record}.buffer_size		(R/-)
   6482  *	It indicates the buffer size in bytes.  Internally it means usrbuf.
   6483  *
   6484  * ai.{play,record}.samples		(R/-)
   6485  *	It indicates the total number of bytes played or recorded.
   6486  *
   6487  * ai.{play,record}.eof			(R/-)
   6488  *	It indicates the number of times reached EOF(?).
   6489  *
   6490  * ai.{play,record}.error		(R/-)
   6491  *	Non-zero indicates overflow/underflow has occured.
   6492  *
   6493  * ai.{play,record}.waiting		(R/-)
   6494  *	Non-zero indicates that other process waits to open.
   6495  *	It will never happen anymore.
   6496  *
   6497  * ai.{play,record}.open		(R/-)
   6498  *	Non-zero indicates the direction is opened by this process(?).
   6499  *	XXX Is this better to indicate that "the device is opened by
   6500  *	at least one process"?
   6501  *
   6502  * ai.{play,record}.active		(R/-)
   6503  *	Non-zero indicates that I/O is currently active.
   6504  *
   6505  * ai.blocksize				(R/-)
   6506  *	It indicates the block size in bytes.
   6507  *	XXX The blocksize of playback and recording may be different.
   6508  */
   6509 
   6510 /*
   6511  * Pause consideration:
   6512  *
   6513  * The introduction of these two behavior makes pause/unpause operation
   6514  * simple.
   6515  * 1. The first read/write access of the first track makes mixer start.
   6516  * 2. A pause of the last track doesn't make mixer stop.
   6517  */
   6518 
   6519 /*
   6520  * Set both track's parameters within a file depending on ai.
   6521  * Update sc_sound_[pr]* if set.
   6522  * Must be called with sc_lock and sc_exlock held.
   6523  */
   6524 static int
   6525 audio_file_setinfo(struct audio_softc *sc, audio_file_t *file,
   6526 	const struct audio_info *ai)
   6527 {
   6528 	const struct audio_prinfo *pi;
   6529 	const struct audio_prinfo *ri;
   6530 	audio_track_t *ptrack;
   6531 	audio_track_t *rtrack;
   6532 	audio_format2_t pfmt;
   6533 	audio_format2_t rfmt;
   6534 	int pchanges;
   6535 	int rchanges;
   6536 	int mode;
   6537 	struct audio_info saved_ai;
   6538 	audio_format2_t saved_pfmt;
   6539 	audio_format2_t saved_rfmt;
   6540 	int error;
   6541 
   6542 	KASSERT(mutex_owned(sc->sc_lock));
   6543 	KASSERT(sc->sc_exlock);
   6544 
   6545 	pi = &ai->play;
   6546 	ri = &ai->record;
   6547 	pchanges = 0;
   6548 	rchanges = 0;
   6549 
   6550 	ptrack = file->ptrack;
   6551 	rtrack = file->rtrack;
   6552 
   6553 #if defined(AUDIO_DEBUG)
   6554 	if (audiodebug >= 2) {
   6555 		char buf[256];
   6556 		char p[64];
   6557 		int buflen;
   6558 		int plen;
   6559 #define SPRINTF(var, fmt...) do {	\
   6560 	var##len += snprintf(var + var##len, sizeof(var) - var##len, fmt); \
   6561 } while (0)
   6562 
   6563 		buflen = 0;
   6564 		plen = 0;
   6565 		if (SPECIFIED(pi->encoding))
   6566 			SPRINTF(p, "/%s", audio_encoding_name(pi->encoding));
   6567 		if (SPECIFIED(pi->precision))
   6568 			SPRINTF(p, "/%dbit", pi->precision);
   6569 		if (SPECIFIED(pi->channels))
   6570 			SPRINTF(p, "/%dch", pi->channels);
   6571 		if (SPECIFIED(pi->sample_rate))
   6572 			SPRINTF(p, "/%dHz", pi->sample_rate);
   6573 		if (plen > 0)
   6574 			SPRINTF(buf, ",play.param=%s", p + 1);
   6575 
   6576 		plen = 0;
   6577 		if (SPECIFIED(ri->encoding))
   6578 			SPRINTF(p, "/%s", audio_encoding_name(ri->encoding));
   6579 		if (SPECIFIED(ri->precision))
   6580 			SPRINTF(p, "/%dbit", ri->precision);
   6581 		if (SPECIFIED(ri->channels))
   6582 			SPRINTF(p, "/%dch", ri->channels);
   6583 		if (SPECIFIED(ri->sample_rate))
   6584 			SPRINTF(p, "/%dHz", ri->sample_rate);
   6585 		if (plen > 0)
   6586 			SPRINTF(buf, ",record.param=%s", p + 1);
   6587 
   6588 		if (SPECIFIED(ai->mode))
   6589 			SPRINTF(buf, ",mode=%d", ai->mode);
   6590 		if (SPECIFIED(ai->hiwat))
   6591 			SPRINTF(buf, ",hiwat=%d", ai->hiwat);
   6592 		if (SPECIFIED(ai->lowat))
   6593 			SPRINTF(buf, ",lowat=%d", ai->lowat);
   6594 		if (SPECIFIED(ai->play.gain))
   6595 			SPRINTF(buf, ",play.gain=%d", ai->play.gain);
   6596 		if (SPECIFIED(ai->record.gain))
   6597 			SPRINTF(buf, ",record.gain=%d", ai->record.gain);
   6598 		if (SPECIFIED_CH(ai->play.balance))
   6599 			SPRINTF(buf, ",play.balance=%d", ai->play.balance);
   6600 		if (SPECIFIED_CH(ai->record.balance))
   6601 			SPRINTF(buf, ",record.balance=%d", ai->record.balance);
   6602 		if (SPECIFIED(ai->play.port))
   6603 			SPRINTF(buf, ",play.port=%d", ai->play.port);
   6604 		if (SPECIFIED(ai->record.port))
   6605 			SPRINTF(buf, ",record.port=%d", ai->record.port);
   6606 		if (SPECIFIED(ai->monitor_gain))
   6607 			SPRINTF(buf, ",monitor_gain=%d", ai->monitor_gain);
   6608 		if (SPECIFIED_CH(ai->play.pause))
   6609 			SPRINTF(buf, ",play.pause=%d", ai->play.pause);
   6610 		if (SPECIFIED_CH(ai->record.pause))
   6611 			SPRINTF(buf, ",record.pause=%d", ai->record.pause);
   6612 
   6613 		if (buflen > 0)
   6614 			TRACE(2, "specified %s", buf + 1);
   6615 	}
   6616 #endif
   6617 
   6618 	AUDIO_INITINFO(&saved_ai);
   6619 	/* XXX shut up gcc */
   6620 	memset(&saved_pfmt, 0, sizeof(saved_pfmt));
   6621 	memset(&saved_rfmt, 0, sizeof(saved_rfmt));
   6622 
   6623 	/* Set default value and save current parameters */
   6624 	if (ptrack) {
   6625 		pfmt = ptrack->usrbuf.fmt;
   6626 		saved_pfmt = ptrack->usrbuf.fmt;
   6627 		saved_ai.play.pause = ptrack->is_pause;
   6628 	}
   6629 	if (rtrack) {
   6630 		rfmt = rtrack->usrbuf.fmt;
   6631 		saved_rfmt = rtrack->usrbuf.fmt;
   6632 		saved_ai.record.pause = rtrack->is_pause;
   6633 	}
   6634 	saved_ai.mode = file->mode;
   6635 
   6636 	/* Overwrite if specified */
   6637 	mode = file->mode;
   6638 	if (SPECIFIED(ai->mode)) {
   6639 		/*
   6640 		 * Setting ai->mode no longer does anything because it's
   6641 		 * prohibited to change playback/recording mode after open
   6642 		 * and AUMODE_PLAY_ALL is obsoleted.  However, it still
   6643 		 * keeps the state of AUMODE_PLAY_ALL itself for backward
   6644 		 * compatibility.
   6645 		 * In the internal, only file->mode has the state of
   6646 		 * AUMODE_PLAY_ALL flag and track->mode in both track does
   6647 		 * not have.
   6648 		 */
   6649 		if ((file->mode & AUMODE_PLAY)) {
   6650 			mode = (file->mode & (AUMODE_PLAY | AUMODE_RECORD))
   6651 			    | (ai->mode & AUMODE_PLAY_ALL);
   6652 		}
   6653 	}
   6654 
   6655 	if (ptrack) {
   6656 		pchanges = audio_track_setinfo_check(&pfmt, pi,
   6657 		    &sc->sc_pmixer->hwbuf.fmt);
   6658 		if (pchanges == -1) {
   6659 #if defined(AUDIO_DEBUG)
   6660 			char fmtbuf[64];
   6661 			audio_format2_tostr(fmtbuf, sizeof(fmtbuf), &pfmt);
   6662 			TRACET(1, ptrack, "check play.params failed: %s",
   6663 			    fmtbuf);
   6664 #endif
   6665 			return EINVAL;
   6666 		}
   6667 		if (SPECIFIED(ai->mode))
   6668 			pchanges = 1;
   6669 	}
   6670 	if (rtrack) {
   6671 		rchanges = audio_track_setinfo_check(&rfmt, ri,
   6672 		    &sc->sc_rmixer->hwbuf.fmt);
   6673 		if (rchanges == -1) {
   6674 #if defined(AUDIO_DEBUG)
   6675 			char fmtbuf[64];
   6676 			audio_format2_tostr(fmtbuf, sizeof(fmtbuf), &rfmt);
   6677 			TRACET(1, rtrack, "check record.params failed: %s",
   6678 			    fmtbuf);
   6679 #endif
   6680 			return EINVAL;
   6681 		}
   6682 		if (SPECIFIED(ai->mode))
   6683 			rchanges = 1;
   6684 	}
   6685 
   6686 	/*
   6687 	 * Even when setting either one of playback and recording,
   6688 	 * both track must be halted.
   6689 	 */
   6690 	if (pchanges || rchanges) {
   6691 		audio_file_clear(sc, file);
   6692 #if defined(AUDIO_DEBUG)
   6693 		char fmtbuf[64];
   6694 		if (pchanges) {
   6695 			audio_format2_tostr(fmtbuf, sizeof(fmtbuf), &pfmt);
   6696 			DPRINTF(1, "audio track#%d play mode: %s\n",
   6697 			    ptrack->id, fmtbuf);
   6698 		}
   6699 		if (rchanges) {
   6700 			audio_format2_tostr(fmtbuf, sizeof(fmtbuf), &rfmt);
   6701 			DPRINTF(1, "audio track#%d rec  mode: %s\n",
   6702 			    rtrack->id, fmtbuf);
   6703 		}
   6704 #endif
   6705 	}
   6706 
   6707 	/* Set mixer parameters */
   6708 	error = audio_hw_setinfo(sc, ai, &saved_ai);
   6709 	if (error)
   6710 		goto abort1;
   6711 
   6712 	/* Set to track and update sticky parameters */
   6713 	error = 0;
   6714 	file->mode = mode;
   6715 	if (ptrack) {
   6716 		if (SPECIFIED_CH(pi->pause)) {
   6717 			ptrack->is_pause = pi->pause;
   6718 			sc->sc_sound_ppause = pi->pause;
   6719 		}
   6720 		if (pchanges) {
   6721 			audio_track_lock_enter(ptrack);
   6722 			error = audio_track_set_format(ptrack, &pfmt);
   6723 			audio_track_lock_exit(ptrack);
   6724 			if (error) {
   6725 				TRACET(1, ptrack, "set play.params failed");
   6726 				goto abort2;
   6727 			}
   6728 			sc->sc_sound_pparams = pfmt;
   6729 		}
   6730 		/* Change water marks after initializing the buffers. */
   6731 		if (SPECIFIED(ai->hiwat) || SPECIFIED(ai->lowat))
   6732 			audio_track_setinfo_water(ptrack, ai);
   6733 	}
   6734 	if (rtrack) {
   6735 		if (SPECIFIED_CH(ri->pause)) {
   6736 			rtrack->is_pause = ri->pause;
   6737 			sc->sc_sound_rpause = ri->pause;
   6738 		}
   6739 		if (rchanges) {
   6740 			audio_track_lock_enter(rtrack);
   6741 			error = audio_track_set_format(rtrack, &rfmt);
   6742 			audio_track_lock_exit(rtrack);
   6743 			if (error) {
   6744 				TRACET(1, rtrack, "set record.params failed");
   6745 				goto abort3;
   6746 			}
   6747 			sc->sc_sound_rparams = rfmt;
   6748 		}
   6749 	}
   6750 
   6751 	return 0;
   6752 
   6753 	/* Rollback */
   6754 abort3:
   6755 	if (error != ENOMEM) {
   6756 		rtrack->is_pause = saved_ai.record.pause;
   6757 		audio_track_lock_enter(rtrack);
   6758 		audio_track_set_format(rtrack, &saved_rfmt);
   6759 		audio_track_lock_exit(rtrack);
   6760 	}
   6761 abort2:
   6762 	if (ptrack && error != ENOMEM) {
   6763 		ptrack->is_pause = saved_ai.play.pause;
   6764 		audio_track_lock_enter(ptrack);
   6765 		audio_track_set_format(ptrack, &saved_pfmt);
   6766 		audio_track_lock_exit(ptrack);
   6767 		sc->sc_sound_pparams = saved_pfmt;
   6768 		sc->sc_sound_ppause = saved_ai.play.pause;
   6769 	}
   6770 	file->mode = saved_ai.mode;
   6771 abort1:
   6772 	audio_hw_setinfo(sc, &saved_ai, NULL);
   6773 
   6774 	return error;
   6775 }
   6776 
   6777 /*
   6778  * Write SPECIFIED() parameters within info back to fmt.
   6779  * Return value of 1 indicates that fmt is modified.
   6780  * Return value of 0 indicates that fmt is not modified.
   6781  * Return value of -1 indicates that error EINVAL has occurred.
   6782  */
   6783 static int
   6784 audio_track_setinfo_check(audio_format2_t *fmt, const struct audio_prinfo *info,
   6785 	const audio_format2_t *hwfmt)
   6786 {
   6787 	int changes;
   6788 
   6789 	changes = 0;
   6790 	if (SPECIFIED(info->sample_rate)) {
   6791 		if (info->sample_rate < AUDIO_MIN_FREQUENCY)
   6792 			return -1;
   6793 		if (info->sample_rate > AUDIO_MAX_FREQUENCY)
   6794 			return -1;
   6795 		fmt->sample_rate = info->sample_rate;
   6796 		changes = 1;
   6797 	}
   6798 	if (SPECIFIED(info->encoding)) {
   6799 		fmt->encoding = info->encoding;
   6800 		changes = 1;
   6801 	}
   6802 	if (SPECIFIED(info->precision)) {
   6803 		fmt->precision = info->precision;
   6804 		/* we don't have API to specify stride */
   6805 		fmt->stride = info->precision;
   6806 		changes = 1;
   6807 	}
   6808 	if (SPECIFIED(info->channels)) {
   6809 		/*
   6810 		 * We can convert between monaural and stereo each other.
   6811 		 * We can reduce than the number of channels that the hardware
   6812 		 * supports.
   6813 		 */
   6814 		if (info->channels > 2 && info->channels > hwfmt->channels)
   6815 			return -1;
   6816 		fmt->channels = info->channels;
   6817 		changes = 1;
   6818 	}
   6819 
   6820 	if (changes) {
   6821 		if (audio_check_params(fmt) != 0)
   6822 			return -1;
   6823 	}
   6824 
   6825 	return changes;
   6826 }
   6827 
   6828 /*
   6829  * Change water marks for playback track if specfied.
   6830  */
   6831 static void
   6832 audio_track_setinfo_water(audio_track_t *track, const struct audio_info *ai)
   6833 {
   6834 	u_int blks;
   6835 	u_int maxblks;
   6836 	u_int blksize;
   6837 
   6838 	KASSERT(audio_track_is_playback(track));
   6839 
   6840 	blksize = track->usrbuf_blksize;
   6841 	maxblks = track->usrbuf.capacity / blksize;
   6842 
   6843 	if (SPECIFIED(ai->hiwat)) {
   6844 		blks = ai->hiwat;
   6845 		if (blks > maxblks)
   6846 			blks = maxblks;
   6847 		if (blks < 2)
   6848 			blks = 2;
   6849 		track->usrbuf_usedhigh = blks * blksize;
   6850 	}
   6851 	if (SPECIFIED(ai->lowat)) {
   6852 		blks = ai->lowat;
   6853 		if (blks > maxblks - 1)
   6854 			blks = maxblks - 1;
   6855 		track->usrbuf_usedlow = blks * blksize;
   6856 	}
   6857 	if (SPECIFIED(ai->hiwat) || SPECIFIED(ai->lowat)) {
   6858 		if (track->usrbuf_usedlow > track->usrbuf_usedhigh - blksize) {
   6859 			track->usrbuf_usedlow = track->usrbuf_usedhigh -
   6860 			    blksize;
   6861 		}
   6862 	}
   6863 }
   6864 
   6865 /*
   6866  * Set hardware part of *newai.
   6867  * The parameters handled here are *.port, *.gain, *.balance and monitor_gain.
   6868  * If oldai is specified, previous parameters are stored.
   6869  * This function itself does not roll back if error occurred.
   6870  * Must be called with sc_lock and sc_exlock held.
   6871  */
   6872 static int
   6873 audio_hw_setinfo(struct audio_softc *sc, const struct audio_info *newai,
   6874 	struct audio_info *oldai)
   6875 {
   6876 	const struct audio_prinfo *newpi;
   6877 	const struct audio_prinfo *newri;
   6878 	struct audio_prinfo *oldpi;
   6879 	struct audio_prinfo *oldri;
   6880 	u_int pgain;
   6881 	u_int rgain;
   6882 	u_char pbalance;
   6883 	u_char rbalance;
   6884 	int error;
   6885 
   6886 	KASSERT(mutex_owned(sc->sc_lock));
   6887 	KASSERT(sc->sc_exlock);
   6888 
   6889 	/* XXX shut up gcc */
   6890 	oldpi = NULL;
   6891 	oldri = NULL;
   6892 
   6893 	newpi = &newai->play;
   6894 	newri = &newai->record;
   6895 	if (oldai) {
   6896 		oldpi = &oldai->play;
   6897 		oldri = &oldai->record;
   6898 	}
   6899 	error = 0;
   6900 
   6901 	/*
   6902 	 * It looks like unnecessary to halt HW mixers to set HW mixers.
   6903 	 * mixer_ioctl(MIXER_WRITE) also doesn't halt.
   6904 	 */
   6905 
   6906 	if (SPECIFIED(newpi->port)) {
   6907 		if (oldai)
   6908 			oldpi->port = au_get_port(sc, &sc->sc_outports);
   6909 		error = au_set_port(sc, &sc->sc_outports, newpi->port);
   6910 		if (error) {
   6911 			device_printf(sc->sc_dev,
   6912 			    "setting play.port=%d failed with %d\n",
   6913 			    newpi->port, error);
   6914 			goto abort;
   6915 		}
   6916 	}
   6917 	if (SPECIFIED(newri->port)) {
   6918 		if (oldai)
   6919 			oldri->port = au_get_port(sc, &sc->sc_inports);
   6920 		error = au_set_port(sc, &sc->sc_inports, newri->port);
   6921 		if (error) {
   6922 			device_printf(sc->sc_dev,
   6923 			    "setting record.port=%d failed with %d\n",
   6924 			    newri->port, error);
   6925 			goto abort;
   6926 		}
   6927 	}
   6928 
   6929 	/* Backup play.{gain,balance} */
   6930 	if (SPECIFIED(newpi->gain) || SPECIFIED_CH(newpi->balance)) {
   6931 		au_get_gain(sc, &sc->sc_outports, &pgain, &pbalance);
   6932 		if (oldai) {
   6933 			oldpi->gain = pgain;
   6934 			oldpi->balance = pbalance;
   6935 		}
   6936 	}
   6937 	/* Backup record.{gain,balance} */
   6938 	if (SPECIFIED(newri->gain) || SPECIFIED_CH(newri->balance)) {
   6939 		au_get_gain(sc, &sc->sc_inports, &rgain, &rbalance);
   6940 		if (oldai) {
   6941 			oldri->gain = rgain;
   6942 			oldri->balance = rbalance;
   6943 		}
   6944 	}
   6945 	if (SPECIFIED(newpi->gain)) {
   6946 		error = au_set_gain(sc, &sc->sc_outports,
   6947 		    newpi->gain, pbalance);
   6948 		if (error) {
   6949 			device_printf(sc->sc_dev,
   6950 			    "setting play.gain=%d failed with %d\n",
   6951 			    newpi->gain, error);
   6952 			goto abort;
   6953 		}
   6954 	}
   6955 	if (SPECIFIED(newri->gain)) {
   6956 		error = au_set_gain(sc, &sc->sc_inports,
   6957 		    newri->gain, rbalance);
   6958 		if (error) {
   6959 			device_printf(sc->sc_dev,
   6960 			    "setting record.gain=%d failed with %d\n",
   6961 			    newri->gain, error);
   6962 			goto abort;
   6963 		}
   6964 	}
   6965 	if (SPECIFIED_CH(newpi->balance)) {
   6966 		error = au_set_gain(sc, &sc->sc_outports,
   6967 		    pgain, newpi->balance);
   6968 		if (error) {
   6969 			device_printf(sc->sc_dev,
   6970 			    "setting play.balance=%d failed with %d\n",
   6971 			    newpi->balance, error);
   6972 			goto abort;
   6973 		}
   6974 	}
   6975 	if (SPECIFIED_CH(newri->balance)) {
   6976 		error = au_set_gain(sc, &sc->sc_inports,
   6977 		    rgain, newri->balance);
   6978 		if (error) {
   6979 			device_printf(sc->sc_dev,
   6980 			    "setting record.balance=%d failed with %d\n",
   6981 			    newri->balance, error);
   6982 			goto abort;
   6983 		}
   6984 	}
   6985 
   6986 	if (SPECIFIED(newai->monitor_gain) && sc->sc_monitor_port != -1) {
   6987 		if (oldai)
   6988 			oldai->monitor_gain = au_get_monitor_gain(sc);
   6989 		error = au_set_monitor_gain(sc, newai->monitor_gain);
   6990 		if (error) {
   6991 			device_printf(sc->sc_dev,
   6992 			    "setting monitor_gain=%d failed with %d\n",
   6993 			    newai->monitor_gain, error);
   6994 			goto abort;
   6995 		}
   6996 	}
   6997 
   6998 	/* XXX TODO */
   6999 	/* sc->sc_ai = *ai; */
   7000 
   7001 	error = 0;
   7002 abort:
   7003 	return error;
   7004 }
   7005 
   7006 /*
   7007  * Setup the hardware with mixer format phwfmt, rhwfmt.
   7008  * The arguments have following restrictions:
   7009  * - setmode is the direction you want to set, AUMODE_PLAY or AUMODE_RECORD,
   7010  *   or both.
   7011  * - phwfmt and rhwfmt must not be NULL regardless of setmode.
   7012  * - On non-independent devices, phwfmt and rhwfmt must have the same
   7013  *   parameters.
   7014  * - pfil and rfil must be zero-filled.
   7015  * If successful,
   7016  * - pfil, rfil will be filled with filter information specified by the
   7017  *   hardware driver.
   7018  * and then returns 0.  Otherwise returns errno.
   7019  * Must be called with sc_lock held.
   7020  */
   7021 static int
   7022 audio_hw_set_format(struct audio_softc *sc, int setmode,
   7023 	const audio_format2_t *phwfmt, const audio_format2_t *rhwfmt,
   7024 	audio_filter_reg_t *pfil, audio_filter_reg_t *rfil)
   7025 {
   7026 	audio_params_t pp, rp;
   7027 	int error;
   7028 
   7029 	KASSERT(mutex_owned(sc->sc_lock));
   7030 	KASSERT(phwfmt != NULL);
   7031 	KASSERT(rhwfmt != NULL);
   7032 
   7033 	pp = format2_to_params(phwfmt);
   7034 	rp = format2_to_params(rhwfmt);
   7035 
   7036 	error = sc->hw_if->set_format(sc->hw_hdl, setmode,
   7037 	    &pp, &rp, pfil, rfil);
   7038 	if (error) {
   7039 		device_printf(sc->sc_dev,
   7040 		    "set_format failed with %d\n", error);
   7041 		return error;
   7042 	}
   7043 
   7044 	if (sc->hw_if->commit_settings) {
   7045 		error = sc->hw_if->commit_settings(sc->hw_hdl);
   7046 		if (error) {
   7047 			device_printf(sc->sc_dev,
   7048 			    "commit_settings failed with %d\n", error);
   7049 			return error;
   7050 		}
   7051 	}
   7052 
   7053 	return 0;
   7054 }
   7055 
   7056 /*
   7057  * Fill audio_info structure.  If need_mixerinfo is true, it will also
   7058  * fill the hardware mixer information.
   7059  * Must be called with sc_lock held.
   7060  * Must be called with sc_exlock held, in addition, if need_mixerinfo is
   7061  * true.
   7062  */
   7063 static int
   7064 audiogetinfo(struct audio_softc *sc, struct audio_info *ai, int need_mixerinfo,
   7065 	audio_file_t *file)
   7066 {
   7067 	struct audio_prinfo *ri, *pi;
   7068 	audio_track_t *track;
   7069 	audio_track_t *ptrack;
   7070 	audio_track_t *rtrack;
   7071 	int gain;
   7072 
   7073 	KASSERT(mutex_owned(sc->sc_lock));
   7074 
   7075 	ri = &ai->record;
   7076 	pi = &ai->play;
   7077 	ptrack = file->ptrack;
   7078 	rtrack = file->rtrack;
   7079 
   7080 	memset(ai, 0, sizeof(*ai));
   7081 
   7082 	if (ptrack) {
   7083 		pi->sample_rate = ptrack->usrbuf.fmt.sample_rate;
   7084 		pi->channels    = ptrack->usrbuf.fmt.channels;
   7085 		pi->precision   = ptrack->usrbuf.fmt.precision;
   7086 		pi->encoding    = ptrack->usrbuf.fmt.encoding;
   7087 	} else {
   7088 		/* Set default parameters if the track is not available. */
   7089 		if (ISDEVAUDIO(file->dev)) {
   7090 			pi->sample_rate = audio_default.sample_rate;
   7091 			pi->channels    = audio_default.channels;
   7092 			pi->precision   = audio_default.precision;
   7093 			pi->encoding    = audio_default.encoding;
   7094 		} else {
   7095 			pi->sample_rate = sc->sc_sound_pparams.sample_rate;
   7096 			pi->channels    = sc->sc_sound_pparams.channels;
   7097 			pi->precision   = sc->sc_sound_pparams.precision;
   7098 			pi->encoding    = sc->sc_sound_pparams.encoding;
   7099 		}
   7100 	}
   7101 	if (rtrack) {
   7102 		ri->sample_rate = rtrack->usrbuf.fmt.sample_rate;
   7103 		ri->channels    = rtrack->usrbuf.fmt.channels;
   7104 		ri->precision   = rtrack->usrbuf.fmt.precision;
   7105 		ri->encoding    = rtrack->usrbuf.fmt.encoding;
   7106 	} else {
   7107 		/* Set default parameters if the track is not available. */
   7108 		if (ISDEVAUDIO(file->dev)) {
   7109 			ri->sample_rate = audio_default.sample_rate;
   7110 			ri->channels    = audio_default.channels;
   7111 			ri->precision   = audio_default.precision;
   7112 			ri->encoding    = audio_default.encoding;
   7113 		} else {
   7114 			ri->sample_rate = sc->sc_sound_rparams.sample_rate;
   7115 			ri->channels    = sc->sc_sound_rparams.channels;
   7116 			ri->precision   = sc->sc_sound_rparams.precision;
   7117 			ri->encoding    = sc->sc_sound_rparams.encoding;
   7118 		}
   7119 	}
   7120 
   7121 	if (ptrack) {
   7122 		pi->seek = ptrack->usrbuf.used;
   7123 		pi->samples = ptrack->usrbuf_stamp;
   7124 		pi->eof = ptrack->eofcounter;
   7125 		pi->pause = ptrack->is_pause;
   7126 		pi->error = (ptrack->dropframes != 0) ? 1 : 0;
   7127 		pi->waiting = 0;		/* open never hangs */
   7128 		pi->open = 1;
   7129 		pi->active = sc->sc_pbusy;
   7130 		pi->buffer_size = ptrack->usrbuf.capacity;
   7131 	}
   7132 	if (rtrack) {
   7133 		ri->seek = rtrack->usrbuf.used;
   7134 		ri->samples = rtrack->usrbuf_stamp;
   7135 		ri->eof = 0;
   7136 		ri->pause = rtrack->is_pause;
   7137 		ri->error = (rtrack->dropframes != 0) ? 1 : 0;
   7138 		ri->waiting = 0;		/* open never hangs */
   7139 		ri->open = 1;
   7140 		ri->active = sc->sc_rbusy;
   7141 		ri->buffer_size = rtrack->usrbuf.capacity;
   7142 	}
   7143 
   7144 	/*
   7145 	 * XXX There may be different number of channels between playback
   7146 	 *     and recording, so that blocksize also may be different.
   7147 	 *     But struct audio_info has an united blocksize...
   7148 	 *     Here, I use play info precedencely if ptrack is available,
   7149 	 *     otherwise record info.
   7150 	 *
   7151 	 * XXX hiwat/lowat is a playback-only parameter.  What should I
   7152 	 *     return for a record-only descriptor?
   7153 	 */
   7154 	track = ptrack ? ptrack : rtrack;
   7155 	if (track) {
   7156 		ai->blocksize = track->usrbuf_blksize;
   7157 		ai->hiwat = track->usrbuf_usedhigh / track->usrbuf_blksize;
   7158 		ai->lowat = track->usrbuf_usedlow / track->usrbuf_blksize;
   7159 	}
   7160 	ai->mode = file->mode;
   7161 
   7162 	if (need_mixerinfo) {
   7163 		KASSERT(sc->sc_exlock);
   7164 
   7165 		pi->port = au_get_port(sc, &sc->sc_outports);
   7166 		ri->port = au_get_port(sc, &sc->sc_inports);
   7167 
   7168 		pi->avail_ports = sc->sc_outports.allports;
   7169 		ri->avail_ports = sc->sc_inports.allports;
   7170 
   7171 		au_get_gain(sc, &sc->sc_outports, &pi->gain, &pi->balance);
   7172 		au_get_gain(sc, &sc->sc_inports, &ri->gain, &ri->balance);
   7173 
   7174 		if (sc->sc_monitor_port != -1) {
   7175 			gain = au_get_monitor_gain(sc);
   7176 			if (gain != -1)
   7177 				ai->monitor_gain = gain;
   7178 		}
   7179 	}
   7180 
   7181 	return 0;
   7182 }
   7183 
   7184 /*
   7185  * Return true if playback is configured.
   7186  * This function can be used after audioattach.
   7187  */
   7188 static bool
   7189 audio_can_playback(struct audio_softc *sc)
   7190 {
   7191 
   7192 	return (sc->sc_pmixer != NULL);
   7193 }
   7194 
   7195 /*
   7196  * Return true if recording is configured.
   7197  * This function can be used after audioattach.
   7198  */
   7199 static bool
   7200 audio_can_capture(struct audio_softc *sc)
   7201 {
   7202 
   7203 	return (sc->sc_rmixer != NULL);
   7204 }
   7205 
   7206 /*
   7207  * Get the afp->index'th item from the valid one of format[].
   7208  * If found, stores it to afp->fmt and returns 0.  Otherwise return EINVAL.
   7209  *
   7210  * This is common routines for query_format.
   7211  * If your hardware driver has struct audio_format[], the simplest case
   7212  * you can write your query_format interface as follows:
   7213  *
   7214  * struct audio_format foo_format[] = { ... };
   7215  *
   7216  * int
   7217  * foo_query_format(void *hdl, audio_format_query_t *afp)
   7218  * {
   7219  *   return audio_query_format(foo_format, __arraycount(foo_format), afp);
   7220  * }
   7221  */
   7222 int
   7223 audio_query_format(const struct audio_format *format, int nformats,
   7224 	audio_format_query_t *afp)
   7225 {
   7226 	const struct audio_format *f;
   7227 	int idx;
   7228 	int i;
   7229 
   7230 	idx = 0;
   7231 	for (i = 0; i < nformats; i++) {
   7232 		f = &format[i];
   7233 		if (!AUFMT_IS_VALID(f))
   7234 			continue;
   7235 		if (afp->index == idx) {
   7236 			afp->fmt = *f;
   7237 			return 0;
   7238 		}
   7239 		idx++;
   7240 	}
   7241 	return EINVAL;
   7242 }
   7243 
   7244 /*
   7245  * This function is provided for the hardware driver's set_format() to
   7246  * find index matches with 'param' from array of audio_format_t 'formats'.
   7247  * 'mode' is either of AUMODE_PLAY or AUMODE_RECORD.
   7248  * It returns the matched index and never fails.  Because param passed to
   7249  * set_format() is selected from query_format().
   7250  * This function will be an alternative to auconv_set_converter() to
   7251  * find index.
   7252  */
   7253 int
   7254 audio_indexof_format(const struct audio_format *formats, int nformats,
   7255 	int mode, const audio_params_t *param)
   7256 {
   7257 	const struct audio_format *f;
   7258 	int index;
   7259 	int j;
   7260 
   7261 	for (index = 0; index < nformats; index++) {
   7262 		f = &formats[index];
   7263 
   7264 		if (!AUFMT_IS_VALID(f))
   7265 			continue;
   7266 		if ((f->mode & mode) == 0)
   7267 			continue;
   7268 		if (f->encoding != param->encoding)
   7269 			continue;
   7270 		if (f->validbits != param->precision)
   7271 			continue;
   7272 		if (f->channels != param->channels)
   7273 			continue;
   7274 
   7275 		if (f->frequency_type == 0) {
   7276 			if (param->sample_rate < f->frequency[0] ||
   7277 			    param->sample_rate > f->frequency[1])
   7278 				continue;
   7279 		} else {
   7280 			for (j = 0; j < f->frequency_type; j++) {
   7281 				if (param->sample_rate == f->frequency[j])
   7282 					break;
   7283 			}
   7284 			if (j == f->frequency_type)
   7285 				continue;
   7286 		}
   7287 
   7288 		/* Then, matched */
   7289 		return index;
   7290 	}
   7291 
   7292 	/* Not matched.  This should not be happened. */
   7293 	panic("%s: cannot find matched format\n", __func__);
   7294 }
   7295 
   7296 /*
   7297  * Get or set hardware blocksize in msec.
   7298  * XXX It's for debug.
   7299  */
   7300 static int
   7301 audio_sysctl_blk_ms(SYSCTLFN_ARGS)
   7302 {
   7303 	struct sysctlnode node;
   7304 	struct audio_softc *sc;
   7305 	audio_format2_t phwfmt;
   7306 	audio_format2_t rhwfmt;
   7307 	audio_filter_reg_t pfil;
   7308 	audio_filter_reg_t rfil;
   7309 	int t;
   7310 	int old_blk_ms;
   7311 	int mode;
   7312 	int error;
   7313 
   7314 	node = *rnode;
   7315 	sc = node.sysctl_data;
   7316 
   7317 	mutex_enter(sc->sc_lock);
   7318 
   7319 	old_blk_ms = sc->sc_blk_ms;
   7320 	t = old_blk_ms;
   7321 	node.sysctl_data = &t;
   7322 	error = sysctl_lookup(SYSCTLFN_CALL(&node));
   7323 	if (error || newp == NULL)
   7324 		goto abort;
   7325 
   7326 	if (t < 0) {
   7327 		error = EINVAL;
   7328 		goto abort;
   7329 	}
   7330 
   7331 	if (sc->sc_popens + sc->sc_ropens > 0) {
   7332 		error = EBUSY;
   7333 		goto abort;
   7334 	}
   7335 	sc->sc_blk_ms = t;
   7336 	mode = 0;
   7337 	if (sc->sc_pmixer) {
   7338 		mode |= AUMODE_PLAY;
   7339 		phwfmt = sc->sc_pmixer->hwbuf.fmt;
   7340 	}
   7341 	if (sc->sc_rmixer) {
   7342 		mode |= AUMODE_RECORD;
   7343 		rhwfmt = sc->sc_rmixer->hwbuf.fmt;
   7344 	}
   7345 
   7346 	/* re-init hardware */
   7347 	memset(&pfil, 0, sizeof(pfil));
   7348 	memset(&rfil, 0, sizeof(rfil));
   7349 	error = audio_hw_set_format(sc, mode, &phwfmt, &rhwfmt, &pfil, &rfil);
   7350 	if (error) {
   7351 		goto abort;
   7352 	}
   7353 
   7354 	/* re-init track mixer */
   7355 	error = audio_mixers_init(sc, mode, &phwfmt, &rhwfmt, &pfil, &rfil);
   7356 	if (error) {
   7357 		/* Rollback */
   7358 		sc->sc_blk_ms = old_blk_ms;
   7359 		audio_mixers_init(sc, mode, &phwfmt, &rhwfmt, &pfil, &rfil);
   7360 		goto abort;
   7361 	}
   7362 	error = 0;
   7363 abort:
   7364 	mutex_exit(sc->sc_lock);
   7365 	return error;
   7366 }
   7367 
   7368 /*
   7369  * Get or set multiuser mode.
   7370  */
   7371 static int
   7372 audio_sysctl_multiuser(SYSCTLFN_ARGS)
   7373 {
   7374 	struct sysctlnode node;
   7375 	struct audio_softc *sc;
   7376 	bool t;
   7377 	int error;
   7378 
   7379 	node = *rnode;
   7380 	sc = node.sysctl_data;
   7381 
   7382 	mutex_enter(sc->sc_lock);
   7383 
   7384 	t = sc->sc_multiuser;
   7385 	node.sysctl_data = &t;
   7386 	error = sysctl_lookup(SYSCTLFN_CALL(&node));
   7387 	if (error || newp == NULL)
   7388 		goto abort;
   7389 
   7390 	sc->sc_multiuser = t;
   7391 	error = 0;
   7392 abort:
   7393 	mutex_exit(sc->sc_lock);
   7394 	return error;
   7395 }
   7396 
   7397 #if defined(AUDIO_DEBUG)
   7398 /*
   7399  * Get or set debug verbose level. (0..4)
   7400  * XXX It's for debug.
   7401  * XXX It is not separated per device.
   7402  */
   7403 static int
   7404 audio_sysctl_debug(SYSCTLFN_ARGS)
   7405 {
   7406 	struct sysctlnode node;
   7407 	int t;
   7408 	int error;
   7409 
   7410 	node = *rnode;
   7411 	t = audiodebug;
   7412 	node.sysctl_data = &t;
   7413 	error = sysctl_lookup(SYSCTLFN_CALL(&node));
   7414 	if (error || newp == NULL)
   7415 		return error;
   7416 
   7417 	if (t < 0 || t > 4)
   7418 		return EINVAL;
   7419 	audiodebug = t;
   7420 	printf("audio: audiodebug = %d\n", audiodebug);
   7421 	return 0;
   7422 }
   7423 #endif /* AUDIO_DEBUG */
   7424 
   7425 #ifdef AUDIO_PM_IDLE
   7426 static void
   7427 audio_idle(void *arg)
   7428 {
   7429 	device_t dv = arg;
   7430 	struct audio_softc *sc = device_private(dv);
   7431 
   7432 #ifdef PNP_DEBUG
   7433 	extern int pnp_debug_idle;
   7434 	if (pnp_debug_idle)
   7435 		printf("%s: idle handler called\n", device_xname(dv));
   7436 #endif
   7437 
   7438 	sc->sc_idle = true;
   7439 
   7440 	/* XXX joerg Make pmf_device_suspend handle children? */
   7441 	if (!pmf_device_suspend(dv, PMF_Q_SELF))
   7442 		return;
   7443 
   7444 	if (!pmf_device_suspend(sc->hw_dev, PMF_Q_SELF))
   7445 		pmf_device_resume(dv, PMF_Q_SELF);
   7446 }
   7447 
   7448 static void
   7449 audio_activity(device_t dv, devactive_t type)
   7450 {
   7451 	struct audio_softc *sc = device_private(dv);
   7452 
   7453 	if (type != DVA_SYSTEM)
   7454 		return;
   7455 
   7456 	callout_schedule(&sc->sc_idle_counter, audio_idle_timeout * hz);
   7457 
   7458 	sc->sc_idle = false;
   7459 	if (!device_is_active(dv)) {
   7460 		/* XXX joerg How to deal with a failing resume... */
   7461 		pmf_device_resume(sc->hw_dev, PMF_Q_SELF);
   7462 		pmf_device_resume(dv, PMF_Q_SELF);
   7463 	}
   7464 }
   7465 #endif
   7466 
   7467 static bool
   7468 audio_suspend(device_t dv, const pmf_qual_t *qual)
   7469 {
   7470 	struct audio_softc *sc = device_private(dv);
   7471 	int error;
   7472 
   7473 	error = audio_enter_exclusive(sc);
   7474 	if (error)
   7475 		return error;
   7476 	audio_mixer_capture(sc);
   7477 
   7478 	/* Halts mixers but don't clear busy flag for resume */
   7479 	if (sc->sc_pbusy) {
   7480 		audio_pmixer_halt(sc);
   7481 		sc->sc_pbusy = true;
   7482 	}
   7483 	if (sc->sc_rbusy) {
   7484 		audio_rmixer_halt(sc);
   7485 		sc->sc_rbusy = true;
   7486 	}
   7487 
   7488 #ifdef AUDIO_PM_IDLE
   7489 	callout_halt(&sc->sc_idle_counter, sc->sc_lock);
   7490 #endif
   7491 	audio_exit_exclusive(sc);
   7492 
   7493 	return true;
   7494 }
   7495 
   7496 static bool
   7497 audio_resume(device_t dv, const pmf_qual_t *qual)
   7498 {
   7499 	struct audio_softc *sc = device_private(dv);
   7500 	struct audio_info ai;
   7501 	int error;
   7502 
   7503 	error = audio_enter_exclusive(sc);
   7504 	if (error)
   7505 		return error;
   7506 
   7507 	audio_mixer_restore(sc);
   7508 	/* XXX ? */
   7509 	AUDIO_INITINFO(&ai);
   7510 	audio_hw_setinfo(sc, &ai, NULL);
   7511 
   7512 	if (sc->sc_pbusy)
   7513 		audio_pmixer_start(sc, true);
   7514 	if (sc->sc_rbusy)
   7515 		audio_rmixer_start(sc);
   7516 
   7517 	audio_exit_exclusive(sc);
   7518 
   7519 	return true;
   7520 }
   7521 
   7522 #if defined(AUDIO_DEBUG)
   7523 static void
   7524 audio_format2_tostr(char *buf, size_t bufsize, const audio_format2_t *fmt)
   7525 {
   7526 	int n;
   7527 
   7528 	n = 0;
   7529 	n += snprintf(buf + n, bufsize - n, "%s",
   7530 	    audio_encoding_name(fmt->encoding));
   7531 	if (fmt->precision == fmt->stride) {
   7532 		n += snprintf(buf + n, bufsize - n, " %dbit", fmt->precision);
   7533 	} else {
   7534 		n += snprintf(buf + n, bufsize - n, " %d/%dbit",
   7535 			fmt->precision, fmt->stride);
   7536 	}
   7537 
   7538 	snprintf(buf + n, bufsize - n, " %uch %uHz",
   7539 	    fmt->channels, fmt->sample_rate);
   7540 }
   7541 #endif
   7542 
   7543 #if defined(AUDIO_DEBUG)
   7544 static void
   7545 audio_print_format2(const char *s, const audio_format2_t *fmt)
   7546 {
   7547 	char fmtstr[64];
   7548 
   7549 	audio_format2_tostr(fmtstr, sizeof(fmtstr), fmt);
   7550 	printf("%s %s\n", s, fmtstr);
   7551 }
   7552 #endif
   7553 
   7554 #ifdef DIAGNOSTIC
   7555 void
   7556 audio_diagnostic_format2(const char *where, const audio_format2_t *fmt)
   7557 {
   7558 
   7559 	KASSERTMSG(fmt, "called from %s", where);
   7560 
   7561 	/* XXX MSM6258 vs(4) only has 4bit stride format. */
   7562 	if (fmt->encoding == AUDIO_ENCODING_ADPCM) {
   7563 		KASSERTMSG(fmt->stride == 4 || fmt->stride == 8,
   7564 		    "called from %s: fmt->stride=%d", where, fmt->stride);
   7565 	} else {
   7566 		KASSERTMSG(fmt->stride % NBBY == 0,
   7567 		    "called from %s: fmt->stride=%d", where, fmt->stride);
   7568 	}
   7569 	KASSERTMSG(fmt->precision <= fmt->stride,
   7570 	    "called from %s: fmt->precision=%d fmt->stride=%d",
   7571 	    where, fmt->precision, fmt->stride);
   7572 	KASSERTMSG(1 <= fmt->channels && fmt->channels <= AUDIO_MAX_CHANNELS,
   7573 	    "called from %s: fmt->channels=%d", where, fmt->channels);
   7574 
   7575 	/* XXX No check for encodings? */
   7576 }
   7577 
   7578 void
   7579 audio_diagnostic_filter_arg(const char *where, const audio_filter_arg_t *arg)
   7580 {
   7581 
   7582 	KASSERT(arg != NULL);
   7583 	KASSERT(arg->src != NULL);
   7584 	KASSERT(arg->dst != NULL);
   7585 	audio_diagnostic_format2(where, arg->srcfmt);
   7586 	audio_diagnostic_format2(where, arg->dstfmt);
   7587 	KASSERT(arg->count > 0);
   7588 }
   7589 
   7590 void
   7591 audio_diagnostic_ring(const char *where, const audio_ring_t *ring)
   7592 {
   7593 
   7594 	KASSERTMSG(ring, "called from %s", where);
   7595 	audio_diagnostic_format2(where, &ring->fmt);
   7596 	KASSERTMSG(0 <= ring->capacity && ring->capacity < INT_MAX / 2,
   7597 	    "called from %s: ring->capacity=%d", where, ring->capacity);
   7598 	KASSERTMSG(0 <= ring->used && ring->used <= ring->capacity,
   7599 	    "called from %s: ring->used=%d ring->capacity=%d",
   7600 	    where, ring->used, ring->capacity);
   7601 	if (ring->capacity == 0) {
   7602 		KASSERTMSG(ring->mem == NULL,
   7603 		    "called from %s: capacity == 0 but mem != NULL", where);
   7604 	} else {
   7605 		KASSERTMSG(ring->mem != NULL,
   7606 		    "called from %s: capacity != 0 but mem == NULL", where);
   7607 		KASSERTMSG(0 <= ring->head && ring->head < ring->capacity,
   7608 		    "called from %s: ring->head=%d ring->capacity=%d",
   7609 		    where, ring->head, ring->capacity);
   7610 	}
   7611 }
   7612 #endif /* DIAGNOSTIC */
   7613 
   7614 
   7615 /*
   7616  * Mixer driver
   7617  */
   7618 int
   7619 mixer_open(dev_t dev, struct audio_softc *sc, int flags, int ifmt,
   7620 	struct lwp *l)
   7621 {
   7622 	struct file *fp;
   7623 	audio_file_t *af;
   7624 	int error, fd;
   7625 
   7626 	KASSERT(mutex_owned(sc->sc_lock));
   7627 
   7628 	TRACE(1, "flags=0x%x", flags);
   7629 
   7630 	error = fd_allocfile(&fp, &fd);
   7631 	if (error)
   7632 		return error;
   7633 
   7634 	af = kmem_zalloc(sizeof(*af), KM_SLEEP);
   7635 	af->sc = sc;
   7636 	af->dev = dev;
   7637 
   7638 	error = fd_clone(fp, fd, flags, &audio_fileops, af);
   7639 	KASSERT(error == EMOVEFD);
   7640 
   7641 	return error;
   7642 }
   7643 
   7644 /*
   7645  * Add a process to those to be signalled on mixer activity.
   7646  * If the process has already been added, do nothing.
   7647  * Must be called with sc_lock held.
   7648  */
   7649 static void
   7650 mixer_async_add(struct audio_softc *sc, pid_t pid)
   7651 {
   7652 	int i;
   7653 
   7654 	KASSERT(mutex_owned(sc->sc_lock));
   7655 
   7656 	/* If already exists, returns without doing anything. */
   7657 	for (i = 0; i < sc->sc_am_used; i++) {
   7658 		if (sc->sc_am[i] == pid)
   7659 			return;
   7660 	}
   7661 
   7662 	/* Extend array if necessary. */
   7663 	if (sc->sc_am_used >= sc->sc_am_capacity) {
   7664 		sc->sc_am_capacity += AM_CAPACITY;
   7665 		sc->sc_am = kern_realloc(sc->sc_am,
   7666 		    sc->sc_am_capacity * sizeof(pid_t), M_WAITOK);
   7667 		TRACE(2, "realloc am_capacity=%d", sc->sc_am_capacity);
   7668 	}
   7669 
   7670 	TRACE(2, "am[%d]=%d", sc->sc_am_used, (int)pid);
   7671 	sc->sc_am[sc->sc_am_used++] = pid;
   7672 }
   7673 
   7674 /*
   7675  * Remove a process from those to be signalled on mixer activity.
   7676  * If the process has not been added, do nothing.
   7677  * Must be called with sc_lock held.
   7678  */
   7679 static void
   7680 mixer_async_remove(struct audio_softc *sc, pid_t pid)
   7681 {
   7682 	int i;
   7683 
   7684 	KASSERT(mutex_owned(sc->sc_lock));
   7685 
   7686 	for (i = 0; i < sc->sc_am_used; i++) {
   7687 		if (sc->sc_am[i] == pid) {
   7688 			sc->sc_am[i] = sc->sc_am[--sc->sc_am_used];
   7689 			TRACE(2, "am[%d](%d) removed, used=%d",
   7690 			    i, (int)pid, sc->sc_am_used);
   7691 
   7692 			/* Empty array if no longer necessary. */
   7693 			if (sc->sc_am_used == 0) {
   7694 				kern_free(sc->sc_am);
   7695 				sc->sc_am = NULL;
   7696 				sc->sc_am_capacity = 0;
   7697 				TRACE(2, "released");
   7698 			}
   7699 			return;
   7700 		}
   7701 	}
   7702 }
   7703 
   7704 /*
   7705  * Signal all processes waiting for the mixer.
   7706  * Must be called with sc_lock held.
   7707  */
   7708 static void
   7709 mixer_signal(struct audio_softc *sc)
   7710 {
   7711 	proc_t *p;
   7712 	int i;
   7713 
   7714 	KASSERT(mutex_owned(sc->sc_lock));
   7715 
   7716 	for (i = 0; i < sc->sc_am_used; i++) {
   7717 		mutex_enter(proc_lock);
   7718 		p = proc_find(sc->sc_am[i]);
   7719 		if (p)
   7720 			psignal(p, SIGIO);
   7721 		mutex_exit(proc_lock);
   7722 	}
   7723 }
   7724 
   7725 /*
   7726  * Close a mixer device
   7727  */
   7728 int
   7729 mixer_close(struct audio_softc *sc, audio_file_t *file)
   7730 {
   7731 
   7732 	mutex_enter(sc->sc_lock);
   7733 	TRACE(1, "");
   7734 	mixer_async_remove(sc, curproc->p_pid);
   7735 	mutex_exit(sc->sc_lock);
   7736 
   7737 	kmem_free(file, sizeof(*file));
   7738 	return 0;
   7739 }
   7740 
   7741 /*
   7742  * Must be called without sc_lock nor sc_exlock held.
   7743  */
   7744 int
   7745 mixer_ioctl(struct audio_softc *sc, u_long cmd, void *addr, int flag,
   7746 	struct lwp *l)
   7747 {
   7748 	mixer_devinfo_t *mi;
   7749 	mixer_ctrl_t *mc;
   7750 	int error;
   7751 
   7752 	TRACE(2, "(%lu,'%c',%lu)",
   7753 	    IOCPARM_LEN(cmd), (char)IOCGROUP(cmd), cmd & 0xff);
   7754 	error = EINVAL;
   7755 
   7756 	/* we can return cached values if we are sleeping */
   7757 	if (cmd != AUDIO_MIXER_READ) {
   7758 		mutex_enter(sc->sc_lock);
   7759 		device_active(sc->sc_dev, DVA_SYSTEM);
   7760 		mutex_exit(sc->sc_lock);
   7761 	}
   7762 
   7763 	switch (cmd) {
   7764 	case FIOASYNC:
   7765 		mutex_enter(sc->sc_lock);
   7766 		if (*(int *)addr) {
   7767 			mixer_async_add(sc, curproc->p_pid);
   7768 		} else {
   7769 			mixer_async_remove(sc, curproc->p_pid);
   7770 		}
   7771 		mutex_exit(sc->sc_lock);
   7772 		error = 0;
   7773 		break;
   7774 
   7775 	case AUDIO_GETDEV:
   7776 		TRACE(2, "AUDIO_GETDEV");
   7777 		error = audio_enter_exclusive(sc);
   7778 		if (error)
   7779 			break;
   7780 		error = sc->hw_if->getdev(sc->hw_hdl, (audio_device_t *)addr);
   7781 		audio_exit_exclusive(sc);
   7782 		break;
   7783 
   7784 	case AUDIO_MIXER_DEVINFO:
   7785 		TRACE(2, "AUDIO_MIXER_DEVINFO");
   7786 		mi = (mixer_devinfo_t *)addr;
   7787 
   7788 		mi->un.v.delta = 0; /* default */
   7789 		mutex_enter(sc->sc_lock);
   7790 		error = audio_query_devinfo(sc, mi);
   7791 		mutex_exit(sc->sc_lock);
   7792 		break;
   7793 
   7794 	case AUDIO_MIXER_READ:
   7795 		TRACE(2, "AUDIO_MIXER_READ");
   7796 		mc = (mixer_ctrl_t *)addr;
   7797 
   7798 		error = audio_enter_exclusive(sc);
   7799 		if (error)
   7800 			break;
   7801 		if (device_is_active(sc->hw_dev))
   7802 			error = audio_get_port(sc, mc);
   7803 		else if (mc->dev < 0 || mc->dev >= sc->sc_nmixer_states)
   7804 			error = ENXIO;
   7805 		else {
   7806 			int dev = mc->dev;
   7807 			memcpy(mc, &sc->sc_mixer_state[dev],
   7808 			    sizeof(mixer_ctrl_t));
   7809 			error = 0;
   7810 		}
   7811 		audio_exit_exclusive(sc);
   7812 		break;
   7813 
   7814 	case AUDIO_MIXER_WRITE:
   7815 		TRACE(2, "AUDIO_MIXER_WRITE");
   7816 		error = audio_enter_exclusive(sc);
   7817 		if (error)
   7818 			break;
   7819 		error = audio_set_port(sc, (mixer_ctrl_t *)addr);
   7820 		if (error) {
   7821 			audio_exit_exclusive(sc);
   7822 			break;
   7823 		}
   7824 
   7825 		if (sc->hw_if->commit_settings) {
   7826 			error = sc->hw_if->commit_settings(sc->hw_hdl);
   7827 			if (error) {
   7828 				audio_exit_exclusive(sc);
   7829 				break;
   7830 			}
   7831 		}
   7832 		mixer_signal(sc);
   7833 		audio_exit_exclusive(sc);
   7834 		break;
   7835 
   7836 	default:
   7837 		if (sc->hw_if->dev_ioctl) {
   7838 			error = audio_enter_exclusive(sc);
   7839 			if (error)
   7840 				break;
   7841 			error = sc->hw_if->dev_ioctl(sc->hw_hdl,
   7842 			    cmd, addr, flag, l);
   7843 			audio_exit_exclusive(sc);
   7844 		} else
   7845 			error = EINVAL;
   7846 		break;
   7847 	}
   7848 	TRACE(2, "(%lu,'%c',%lu) result %d",
   7849 	    IOCPARM_LEN(cmd), (char)IOCGROUP(cmd), cmd & 0xff, error);
   7850 	return error;
   7851 }
   7852 
   7853 /*
   7854  * Must be called with sc_lock held.
   7855  */
   7856 int
   7857 au_portof(struct audio_softc *sc, char *name, int class)
   7858 {
   7859 	mixer_devinfo_t mi;
   7860 
   7861 	KASSERT(mutex_owned(sc->sc_lock));
   7862 
   7863 	for (mi.index = 0; audio_query_devinfo(sc, &mi) == 0; mi.index++) {
   7864 		if (mi.mixer_class == class && strcmp(mi.label.name, name) == 0)
   7865 			return mi.index;
   7866 	}
   7867 	return -1;
   7868 }
   7869 
   7870 /*
   7871  * Must be called with sc_lock held.
   7872  */
   7873 void
   7874 au_setup_ports(struct audio_softc *sc, struct au_mixer_ports *ports,
   7875 	mixer_devinfo_t *mi, const struct portname *tbl)
   7876 {
   7877 	int i, j;
   7878 
   7879 	KASSERT(mutex_owned(sc->sc_lock));
   7880 
   7881 	ports->index = mi->index;
   7882 	if (mi->type == AUDIO_MIXER_ENUM) {
   7883 		ports->isenum = true;
   7884 		for(i = 0; tbl[i].name; i++)
   7885 		    for(j = 0; j < mi->un.e.num_mem; j++)
   7886 			if (strcmp(mi->un.e.member[j].label.name,
   7887 						    tbl[i].name) == 0) {
   7888 				ports->allports |= tbl[i].mask;
   7889 				ports->aumask[ports->nports] = tbl[i].mask;
   7890 				ports->misel[ports->nports] =
   7891 				    mi->un.e.member[j].ord;
   7892 				ports->miport[ports->nports] =
   7893 				    au_portof(sc, mi->un.e.member[j].label.name,
   7894 				    mi->mixer_class);
   7895 				if (ports->mixerout != -1 &&
   7896 				    ports->miport[ports->nports] != -1)
   7897 					ports->isdual = true;
   7898 				++ports->nports;
   7899 			}
   7900 	} else if (mi->type == AUDIO_MIXER_SET) {
   7901 		for(i = 0; tbl[i].name; i++)
   7902 		    for(j = 0; j < mi->un.s.num_mem; j++)
   7903 			if (strcmp(mi->un.s.member[j].label.name,
   7904 						tbl[i].name) == 0) {
   7905 				ports->allports |= tbl[i].mask;
   7906 				ports->aumask[ports->nports] = tbl[i].mask;
   7907 				ports->misel[ports->nports] =
   7908 				    mi->un.s.member[j].mask;
   7909 				ports->miport[ports->nports] =
   7910 				    au_portof(sc, mi->un.s.member[j].label.name,
   7911 				    mi->mixer_class);
   7912 				++ports->nports;
   7913 			}
   7914 	}
   7915 }
   7916 
   7917 /*
   7918  * Must be called with sc_lock && sc_exlock held.
   7919  */
   7920 int
   7921 au_set_lr_value(struct audio_softc *sc, mixer_ctrl_t *ct, int l, int r)
   7922 {
   7923 
   7924 	KASSERT(mutex_owned(sc->sc_lock));
   7925 	KASSERT(sc->sc_exlock);
   7926 
   7927 	ct->type = AUDIO_MIXER_VALUE;
   7928 	ct->un.value.num_channels = 2;
   7929 	ct->un.value.level[AUDIO_MIXER_LEVEL_LEFT] = l;
   7930 	ct->un.value.level[AUDIO_MIXER_LEVEL_RIGHT] = r;
   7931 	if (audio_set_port(sc, ct) == 0)
   7932 		return 0;
   7933 	ct->un.value.num_channels = 1;
   7934 	ct->un.value.level[AUDIO_MIXER_LEVEL_MONO] = (l+r)/2;
   7935 	return audio_set_port(sc, ct);
   7936 }
   7937 
   7938 /*
   7939  * Must be called with sc_lock && sc_exlock held.
   7940  */
   7941 int
   7942 au_get_lr_value(struct audio_softc *sc, mixer_ctrl_t *ct, int *l, int *r)
   7943 {
   7944 	int error;
   7945 
   7946 	KASSERT(mutex_owned(sc->sc_lock));
   7947 	KASSERT(sc->sc_exlock);
   7948 
   7949 	ct->un.value.num_channels = 2;
   7950 	if (audio_get_port(sc, ct) == 0) {
   7951 		*l = ct->un.value.level[AUDIO_MIXER_LEVEL_LEFT];
   7952 		*r = ct->un.value.level[AUDIO_MIXER_LEVEL_RIGHT];
   7953 	} else {
   7954 		ct->un.value.num_channels = 1;
   7955 		error = audio_get_port(sc, ct);
   7956 		if (error)
   7957 			return error;
   7958 		*r = *l = ct->un.value.level[AUDIO_MIXER_LEVEL_MONO];
   7959 	}
   7960 	return 0;
   7961 }
   7962 
   7963 /*
   7964  * Must be called with sc_lock && sc_exlock held.
   7965  */
   7966 int
   7967 au_set_gain(struct audio_softc *sc, struct au_mixer_ports *ports,
   7968 	int gain, int balance)
   7969 {
   7970 	mixer_ctrl_t ct;
   7971 	int i, error;
   7972 	int l, r;
   7973 	u_int mask;
   7974 	int nset;
   7975 
   7976 	KASSERT(mutex_owned(sc->sc_lock));
   7977 	KASSERT(sc->sc_exlock);
   7978 
   7979 	if (balance == AUDIO_MID_BALANCE) {
   7980 		l = r = gain;
   7981 	} else if (balance < AUDIO_MID_BALANCE) {
   7982 		l = gain;
   7983 		r = (balance * gain) / AUDIO_MID_BALANCE;
   7984 	} else {
   7985 		r = gain;
   7986 		l = ((AUDIO_RIGHT_BALANCE - balance) * gain)
   7987 		    / AUDIO_MID_BALANCE;
   7988 	}
   7989 	TRACE(2, "gain=%d balance=%d, l=%d r=%d", gain, balance, l, r);
   7990 
   7991 	if (ports->index == -1) {
   7992 	usemaster:
   7993 		if (ports->master == -1)
   7994 			return 0; /* just ignore it silently */
   7995 		ct.dev = ports->master;
   7996 		error = au_set_lr_value(sc, &ct, l, r);
   7997 	} else {
   7998 		ct.dev = ports->index;
   7999 		if (ports->isenum) {
   8000 			ct.type = AUDIO_MIXER_ENUM;
   8001 			error = audio_get_port(sc, &ct);
   8002 			if (error)
   8003 				return error;
   8004 			if (ports->isdual) {
   8005 				if (ports->cur_port == -1)
   8006 					ct.dev = ports->master;
   8007 				else
   8008 					ct.dev = ports->miport[ports->cur_port];
   8009 				error = au_set_lr_value(sc, &ct, l, r);
   8010 			} else {
   8011 				for(i = 0; i < ports->nports; i++)
   8012 				    if (ports->misel[i] == ct.un.ord) {
   8013 					    ct.dev = ports->miport[i];
   8014 					    if (ct.dev == -1 ||
   8015 						au_set_lr_value(sc, &ct, l, r))
   8016 						    goto usemaster;
   8017 					    else
   8018 						    break;
   8019 				    }
   8020 			}
   8021 		} else {
   8022 			ct.type = AUDIO_MIXER_SET;
   8023 			error = audio_get_port(sc, &ct);
   8024 			if (error)
   8025 				return error;
   8026 			mask = ct.un.mask;
   8027 			nset = 0;
   8028 			for(i = 0; i < ports->nports; i++) {
   8029 				if (ports->misel[i] & mask) {
   8030 				    ct.dev = ports->miport[i];
   8031 				    if (ct.dev != -1 &&
   8032 					au_set_lr_value(sc, &ct, l, r) == 0)
   8033 					    nset++;
   8034 				}
   8035 			}
   8036 			if (nset == 0)
   8037 				goto usemaster;
   8038 		}
   8039 	}
   8040 	if (!error)
   8041 		mixer_signal(sc);
   8042 	return error;
   8043 }
   8044 
   8045 /*
   8046  * Must be called with sc_lock && sc_exlock held.
   8047  */
   8048 void
   8049 au_get_gain(struct audio_softc *sc, struct au_mixer_ports *ports,
   8050 	u_int *pgain, u_char *pbalance)
   8051 {
   8052 	mixer_ctrl_t ct;
   8053 	int i, l, r, n;
   8054 	int lgain, rgain;
   8055 
   8056 	KASSERT(mutex_owned(sc->sc_lock));
   8057 	KASSERT(sc->sc_exlock);
   8058 
   8059 	lgain = AUDIO_MAX_GAIN / 2;
   8060 	rgain = AUDIO_MAX_GAIN / 2;
   8061 	if (ports->index == -1) {
   8062 	usemaster:
   8063 		if (ports->master == -1)
   8064 			goto bad;
   8065 		ct.dev = ports->master;
   8066 		ct.type = AUDIO_MIXER_VALUE;
   8067 		if (au_get_lr_value(sc, &ct, &lgain, &rgain))
   8068 			goto bad;
   8069 	} else {
   8070 		ct.dev = ports->index;
   8071 		if (ports->isenum) {
   8072 			ct.type = AUDIO_MIXER_ENUM;
   8073 			if (audio_get_port(sc, &ct))
   8074 				goto bad;
   8075 			ct.type = AUDIO_MIXER_VALUE;
   8076 			if (ports->isdual) {
   8077 				if (ports->cur_port == -1)
   8078 					ct.dev = ports->master;
   8079 				else
   8080 					ct.dev = ports->miport[ports->cur_port];
   8081 				au_get_lr_value(sc, &ct, &lgain, &rgain);
   8082 			} else {
   8083 				for(i = 0; i < ports->nports; i++)
   8084 				    if (ports->misel[i] == ct.un.ord) {
   8085 					    ct.dev = ports->miport[i];
   8086 					    if (ct.dev == -1 ||
   8087 						au_get_lr_value(sc, &ct,
   8088 								&lgain, &rgain))
   8089 						    goto usemaster;
   8090 					    else
   8091 						    break;
   8092 				    }
   8093 			}
   8094 		} else {
   8095 			ct.type = AUDIO_MIXER_SET;
   8096 			if (audio_get_port(sc, &ct))
   8097 				goto bad;
   8098 			ct.type = AUDIO_MIXER_VALUE;
   8099 			lgain = rgain = n = 0;
   8100 			for(i = 0; i < ports->nports; i++) {
   8101 				if (ports->misel[i] & ct.un.mask) {
   8102 					ct.dev = ports->miport[i];
   8103 					if (ct.dev == -1 ||
   8104 					    au_get_lr_value(sc, &ct, &l, &r))
   8105 						goto usemaster;
   8106 					else {
   8107 						lgain += l;
   8108 						rgain += r;
   8109 						n++;
   8110 					}
   8111 				}
   8112 			}
   8113 			if (n != 0) {
   8114 				lgain /= n;
   8115 				rgain /= n;
   8116 			}
   8117 		}
   8118 	}
   8119 bad:
   8120 	if (lgain == rgain) {	/* handles lgain==rgain==0 */
   8121 		*pgain = lgain;
   8122 		*pbalance = AUDIO_MID_BALANCE;
   8123 	} else if (lgain < rgain) {
   8124 		*pgain = rgain;
   8125 		/* balance should be > AUDIO_MID_BALANCE */
   8126 		*pbalance = AUDIO_RIGHT_BALANCE -
   8127 			(AUDIO_MID_BALANCE * lgain) / rgain;
   8128 	} else /* lgain > rgain */ {
   8129 		*pgain = lgain;
   8130 		/* balance should be < AUDIO_MID_BALANCE */
   8131 		*pbalance = (AUDIO_MID_BALANCE * rgain) / lgain;
   8132 	}
   8133 }
   8134 
   8135 /*
   8136  * Must be called with sc_lock && sc_exlock held.
   8137  */
   8138 int
   8139 au_set_port(struct audio_softc *sc, struct au_mixer_ports *ports, u_int port)
   8140 {
   8141 	mixer_ctrl_t ct;
   8142 	int i, error, use_mixerout;
   8143 
   8144 	KASSERT(mutex_owned(sc->sc_lock));
   8145 	KASSERT(sc->sc_exlock);
   8146 
   8147 	use_mixerout = 1;
   8148 	if (port == 0) {
   8149 		if (ports->allports == 0)
   8150 			return 0;		/* Allow this special case. */
   8151 		else if (ports->isdual) {
   8152 			if (ports->cur_port == -1) {
   8153 				return 0;
   8154 			} else {
   8155 				port = ports->aumask[ports->cur_port];
   8156 				ports->cur_port = -1;
   8157 				use_mixerout = 0;
   8158 			}
   8159 		}
   8160 	}
   8161 	if (ports->index == -1)
   8162 		return EINVAL;
   8163 	ct.dev = ports->index;
   8164 	if (ports->isenum) {
   8165 		if (port & (port-1))
   8166 			return EINVAL; /* Only one port allowed */
   8167 		ct.type = AUDIO_MIXER_ENUM;
   8168 		error = EINVAL;
   8169 		for(i = 0; i < ports->nports; i++)
   8170 			if (ports->aumask[i] == port) {
   8171 				if (ports->isdual && use_mixerout) {
   8172 					ct.un.ord = ports->mixerout;
   8173 					ports->cur_port = i;
   8174 				} else {
   8175 					ct.un.ord = ports->misel[i];
   8176 				}
   8177 				error = audio_set_port(sc, &ct);
   8178 				break;
   8179 			}
   8180 	} else {
   8181 		ct.type = AUDIO_MIXER_SET;
   8182 		ct.un.mask = 0;
   8183 		for(i = 0; i < ports->nports; i++)
   8184 			if (ports->aumask[i] & port)
   8185 				ct.un.mask |= ports->misel[i];
   8186 		if (port != 0 && ct.un.mask == 0)
   8187 			error = EINVAL;
   8188 		else
   8189 			error = audio_set_port(sc, &ct);
   8190 	}
   8191 	if (!error)
   8192 		mixer_signal(sc);
   8193 	return error;
   8194 }
   8195 
   8196 /*
   8197  * Must be called with sc_lock && sc_exlock held.
   8198  */
   8199 int
   8200 au_get_port(struct audio_softc *sc, struct au_mixer_ports *ports)
   8201 {
   8202 	mixer_ctrl_t ct;
   8203 	int i, aumask;
   8204 
   8205 	KASSERT(mutex_owned(sc->sc_lock));
   8206 	KASSERT(sc->sc_exlock);
   8207 
   8208 	if (ports->index == -1)
   8209 		return 0;
   8210 	ct.dev = ports->index;
   8211 	ct.type = ports->isenum ? AUDIO_MIXER_ENUM : AUDIO_MIXER_SET;
   8212 	if (audio_get_port(sc, &ct))
   8213 		return 0;
   8214 	aumask = 0;
   8215 	if (ports->isenum) {
   8216 		if (ports->isdual && ports->cur_port != -1) {
   8217 			if (ports->mixerout == ct.un.ord)
   8218 				aumask = ports->aumask[ports->cur_port];
   8219 			else
   8220 				ports->cur_port = -1;
   8221 		}
   8222 		if (aumask == 0)
   8223 			for(i = 0; i < ports->nports; i++)
   8224 				if (ports->misel[i] == ct.un.ord)
   8225 					aumask = ports->aumask[i];
   8226 	} else {
   8227 		for(i = 0; i < ports->nports; i++)
   8228 			if (ct.un.mask & ports->misel[i])
   8229 				aumask |= ports->aumask[i];
   8230 	}
   8231 	return aumask;
   8232 }
   8233 
   8234 /*
   8235  * It returns 0 if success, otherwise errno.
   8236  * Must be called only if sc->sc_monitor_port != -1.
   8237  * Must be called with sc_lock && sc_exlock held.
   8238  */
   8239 static int
   8240 au_set_monitor_gain(struct audio_softc *sc, int monitor_gain)
   8241 {
   8242 	mixer_ctrl_t ct;
   8243 
   8244 	KASSERT(mutex_owned(sc->sc_lock));
   8245 	KASSERT(sc->sc_exlock);
   8246 
   8247 	ct.dev = sc->sc_monitor_port;
   8248 	ct.type = AUDIO_MIXER_VALUE;
   8249 	ct.un.value.num_channels = 1;
   8250 	ct.un.value.level[AUDIO_MIXER_LEVEL_MONO] = monitor_gain;
   8251 	return audio_set_port(sc, &ct);
   8252 }
   8253 
   8254 /*
   8255  * It returns monitor gain if success, otherwise -1.
   8256  * Must be called only if sc->sc_monitor_port != -1.
   8257  * Must be called with sc_lock && sc_exlock held.
   8258  */
   8259 static int
   8260 au_get_monitor_gain(struct audio_softc *sc)
   8261 {
   8262 	mixer_ctrl_t ct;
   8263 
   8264 	KASSERT(mutex_owned(sc->sc_lock));
   8265 	KASSERT(sc->sc_exlock);
   8266 
   8267 	ct.dev = sc->sc_monitor_port;
   8268 	ct.type = AUDIO_MIXER_VALUE;
   8269 	ct.un.value.num_channels = 1;
   8270 	if (audio_get_port(sc, &ct))
   8271 		return -1;
   8272 	return ct.un.value.level[AUDIO_MIXER_LEVEL_MONO];
   8273 }
   8274 
   8275 /*
   8276  * Must be called with sc_lock && sc_exlock held.
   8277  */
   8278 static int
   8279 audio_set_port(struct audio_softc *sc, mixer_ctrl_t *mc)
   8280 {
   8281 
   8282 	KASSERT(mutex_owned(sc->sc_lock));
   8283 	KASSERT(sc->sc_exlock);
   8284 
   8285 	return sc->hw_if->set_port(sc->hw_hdl, mc);
   8286 }
   8287 
   8288 /*
   8289  * Must be called with sc_lock && sc_exlock held.
   8290  */
   8291 static int
   8292 audio_get_port(struct audio_softc *sc, mixer_ctrl_t *mc)
   8293 {
   8294 
   8295 	KASSERT(mutex_owned(sc->sc_lock));
   8296 	KASSERT(sc->sc_exlock);
   8297 
   8298 	return sc->hw_if->get_port(sc->hw_hdl, mc);
   8299 }
   8300 
   8301 /*
   8302  * Must be called with sc_lock && sc_exlock held.
   8303  */
   8304 static void
   8305 audio_mixer_capture(struct audio_softc *sc)
   8306 {
   8307 	mixer_devinfo_t mi;
   8308 	mixer_ctrl_t *mc;
   8309 
   8310 	KASSERT(mutex_owned(sc->sc_lock));
   8311 	KASSERT(sc->sc_exlock);
   8312 
   8313 	for (mi.index = 0;; mi.index++) {
   8314 		if (audio_query_devinfo(sc, &mi) != 0)
   8315 			break;
   8316 		KASSERT(mi.index < sc->sc_nmixer_states);
   8317 		if (mi.type == AUDIO_MIXER_CLASS)
   8318 			continue;
   8319 		mc = &sc->sc_mixer_state[mi.index];
   8320 		mc->dev = mi.index;
   8321 		mc->type = mi.type;
   8322 		mc->un.value.num_channels = mi.un.v.num_channels;
   8323 		(void)audio_get_port(sc, mc);
   8324 	}
   8325 
   8326 	return;
   8327 }
   8328 
   8329 /*
   8330  * Must be called with sc_lock && sc_exlock held.
   8331  */
   8332 static void
   8333 audio_mixer_restore(struct audio_softc *sc)
   8334 {
   8335 	mixer_devinfo_t mi;
   8336 	mixer_ctrl_t *mc;
   8337 
   8338 	KASSERT(mutex_owned(sc->sc_lock));
   8339 	KASSERT(sc->sc_exlock);
   8340 
   8341 	for (mi.index = 0; ; mi.index++) {
   8342 		if (audio_query_devinfo(sc, &mi) != 0)
   8343 			break;
   8344 		if (mi.type == AUDIO_MIXER_CLASS)
   8345 			continue;
   8346 		mc = &sc->sc_mixer_state[mi.index];
   8347 		(void)audio_set_port(sc, mc);
   8348 	}
   8349 	if (sc->hw_if->commit_settings)
   8350 		sc->hw_if->commit_settings(sc->hw_hdl);
   8351 
   8352 	return;
   8353 }
   8354 
   8355 static void
   8356 audio_volume_down(device_t dv)
   8357 {
   8358 	struct audio_softc *sc = device_private(dv);
   8359 	mixer_devinfo_t mi;
   8360 	int newgain;
   8361 	u_int gain;
   8362 	u_char balance;
   8363 
   8364 	if (audio_enter_exclusive(sc) != 0)
   8365 		return;
   8366 	if (sc->sc_outports.index == -1 && sc->sc_outports.master != -1) {
   8367 		mi.index = sc->sc_outports.master;
   8368 		mi.un.v.delta = 0;
   8369 		if (audio_query_devinfo(sc, &mi) == 0) {
   8370 			au_get_gain(sc, &sc->sc_outports, &gain, &balance);
   8371 			newgain = gain - mi.un.v.delta;
   8372 			if (newgain < AUDIO_MIN_GAIN)
   8373 				newgain = AUDIO_MIN_GAIN;
   8374 			au_set_gain(sc, &sc->sc_outports, newgain, balance);
   8375 		}
   8376 	}
   8377 	audio_exit_exclusive(sc);
   8378 }
   8379 
   8380 static void
   8381 audio_volume_up(device_t dv)
   8382 {
   8383 	struct audio_softc *sc = device_private(dv);
   8384 	mixer_devinfo_t mi;
   8385 	u_int gain, newgain;
   8386 	u_char balance;
   8387 
   8388 	if (audio_enter_exclusive(sc) != 0)
   8389 		return;
   8390 	if (sc->sc_outports.index == -1 && sc->sc_outports.master != -1) {
   8391 		mi.index = sc->sc_outports.master;
   8392 		mi.un.v.delta = 0;
   8393 		if (audio_query_devinfo(sc, &mi) == 0) {
   8394 			au_get_gain(sc, &sc->sc_outports, &gain, &balance);
   8395 			newgain = gain + mi.un.v.delta;
   8396 			if (newgain > AUDIO_MAX_GAIN)
   8397 				newgain = AUDIO_MAX_GAIN;
   8398 			au_set_gain(sc, &sc->sc_outports, newgain, balance);
   8399 		}
   8400 	}
   8401 	audio_exit_exclusive(sc);
   8402 }
   8403 
   8404 static void
   8405 audio_volume_toggle(device_t dv)
   8406 {
   8407 	struct audio_softc *sc = device_private(dv);
   8408 	u_int gain, newgain;
   8409 	u_char balance;
   8410 
   8411 	if (audio_enter_exclusive(sc) != 0)
   8412 		return;
   8413 	au_get_gain(sc, &sc->sc_outports, &gain, &balance);
   8414 	if (gain != 0) {
   8415 		sc->sc_lastgain = gain;
   8416 		newgain = 0;
   8417 	} else
   8418 		newgain = sc->sc_lastgain;
   8419 	au_set_gain(sc, &sc->sc_outports, newgain, balance);
   8420 	audio_exit_exclusive(sc);
   8421 }
   8422 
   8423 static int
   8424 audio_query_devinfo(struct audio_softc *sc, mixer_devinfo_t *di)
   8425 {
   8426 
   8427 	KASSERT(mutex_owned(sc->sc_lock));
   8428 
   8429 	return sc->hw_if->query_devinfo(sc->hw_hdl, di);
   8430 }
   8431 
   8432 #endif /* NAUDIO > 0 */
   8433 
   8434 #if NAUDIO == 0 && (NMIDI > 0 || NMIDIBUS > 0)
   8435 #include <sys/param.h>
   8436 #include <sys/systm.h>
   8437 #include <sys/device.h>
   8438 #include <sys/audioio.h>
   8439 #include <dev/audio/audio_if.h>
   8440 #endif
   8441 
   8442 #if NAUDIO > 0 || (NMIDI > 0 || NMIDIBUS > 0)
   8443 int
   8444 audioprint(void *aux, const char *pnp)
   8445 {
   8446 	struct audio_attach_args *arg;
   8447 	const char *type;
   8448 
   8449 	if (pnp != NULL) {
   8450 		arg = aux;
   8451 		switch (arg->type) {
   8452 		case AUDIODEV_TYPE_AUDIO:
   8453 			type = "audio";
   8454 			break;
   8455 		case AUDIODEV_TYPE_MIDI:
   8456 			type = "midi";
   8457 			break;
   8458 		case AUDIODEV_TYPE_OPL:
   8459 			type = "opl";
   8460 			break;
   8461 		case AUDIODEV_TYPE_MPU:
   8462 			type = "mpu";
   8463 			break;
   8464 		default:
   8465 			panic("audioprint: unknown type %d", arg->type);
   8466 		}
   8467 		aprint_normal("%s at %s", type, pnp);
   8468 	}
   8469 	return UNCONF;
   8470 }
   8471 
   8472 #endif /* NAUDIO > 0 || (NMIDI > 0 || NMIDIBUS > 0) */
   8473 
   8474 #ifdef _MODULE
   8475 
   8476 devmajor_t audio_bmajor = -1, audio_cmajor = -1;
   8477 
   8478 #include "ioconf.c"
   8479 
   8480 #endif
   8481 
   8482 MODULE(MODULE_CLASS_DRIVER, audio, NULL);
   8483 
   8484 static int
   8485 audio_modcmd(modcmd_t cmd, void *arg)
   8486 {
   8487 	int error = 0;
   8488 
   8489 #ifdef _MODULE
   8490 	switch (cmd) {
   8491 	case MODULE_CMD_INIT:
   8492 		error = devsw_attach(audio_cd.cd_name, NULL, &audio_bmajor,
   8493 		    &audio_cdevsw, &audio_cmajor);
   8494 		if (error)
   8495 			break;
   8496 
   8497 		error = config_init_component(cfdriver_ioconf_audio,
   8498 		    cfattach_ioconf_audio, cfdata_ioconf_audio);
   8499 		if (error) {
   8500 			devsw_detach(NULL, &audio_cdevsw);
   8501 		}
   8502 		break;
   8503 	case MODULE_CMD_FINI:
   8504 		devsw_detach(NULL, &audio_cdevsw);
   8505 		error = config_fini_component(cfdriver_ioconf_audio,
   8506 		   cfattach_ioconf_audio, cfdata_ioconf_audio);
   8507 		if (error)
   8508 			devsw_attach(audio_cd.cd_name, NULL, &audio_bmajor,
   8509 			    &audio_cdevsw, &audio_cmajor);
   8510 		break;
   8511 	default:
   8512 		error = ENOTTY;
   8513 		break;
   8514 	}
   8515 #endif
   8516 
   8517 	return error;
   8518 }
   8519