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