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