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