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