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