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