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