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