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