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