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