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