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