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