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