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