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