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