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