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