Home | History | Annotate | Line # | Download | only in dev
      1 /*	$NetBSD: audio.c,v 1.290 2017/01/14 20:05:37 nat Exp $	*/
      2 
      3 /*-
      4  * Copyright (c) 2016 Nathanial Sloss <nathanialsloss (at) yahoo.com.au>
      5  * All rights reserved.
      6  *
      7  * Copyright (c) 2008 The NetBSD Foundation, Inc.
      8  * All rights reserved.
      9  *
     10  * This code is derived from software contributed to The NetBSD Foundation
     11  * by Andrew Doran.
     12  *
     13  * Redistribution and use in source and binary forms, with or without
     14  * modification, are permitted provided that the following conditions
     15  * are met:
     16  * 1. Redistributions of source code must retain the above copyright
     17  *    notice, this list of conditions and the following disclaimer.
     18  * 2. Redistributions in binary form must reproduce the above copyright
     19  *    notice, this list of conditions and the following disclaimer in the
     20  *    documentation and/or other materials provided with the distribution.
     21  *
     22  * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
     23  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
     24  * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
     25  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
     26  * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
     27  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
     28  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
     29  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
     30  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
     31  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
     32  * POSSIBILITY OF SUCH DAMAGE.
     33  */
     34 
     35 /*
     36  * Copyright (c) 1991-1993 Regents of the University of California.
     37  * All rights reserved.
     38  *
     39  * Redistribution and use in source and binary forms, with or without
     40  * modification, are permitted provided that the following conditions
     41  * are met:
     42  * 1. Redistributions of source code must retain the above copyright
     43  *    notice, this list of conditions and the following disclaimer.
     44  * 2. Redistributions in binary form must reproduce the above copyright
     45  *    notice, this list of conditions and the following disclaimer in the
     46  *    documentation and/or other materials provided with the distribution.
     47  * 3. All advertising materials mentioning features or use of this software
     48  *    must display the following acknowledgement:
     49  *	This product includes software developed by the Computer Systems
     50  *	Engineering Group at Lawrence Berkeley Laboratory.
     51  * 4. Neither the name of the University nor of the Laboratory may be used
     52  *    to endorse or promote products derived from this software without
     53  *    specific prior written permission.
     54  *
     55  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
     56  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
     57  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
     58  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
     59  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
     60  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
     61  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
     62  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
     63  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
     64  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
     65  * SUCH DAMAGE.
     66  */
     67 
     68 /*
     69  * This is a (partially) SunOS-compatible /dev/audio driver for NetBSD.
     70  *
     71  * This code tries to do something half-way sensible with
     72  * half-duplex hardware, such as with the SoundBlaster hardware.  With
     73  * half-duplex hardware allowing O_RDWR access doesn't really make
     74  * sense.  However, closing and opening the device to "turn around the
     75  * line" is relatively expensive and costs a card reset (which can
     76  * take some time, at least for the SoundBlaster hardware).  Instead
     77  * we allow O_RDWR access, and provide an ioctl to set the "mode",
     78  * i.e. playing or recording.
     79  *
     80  * If you write to a half-duplex device in record mode, the data is
     81  * tossed.  If you read from the device in play mode, you get silence
     82  * filled buffers at the rate at which samples are naturally
     83  * generated.
     84  *
     85  * If you try to set both play and record mode on a half-duplex
     86  * device, playing takes precedence.
     87  */
     88 
     89 /*
     90  * Locking: there are two locks.
     91  *
     92  * - sc_lock, provided by the underlying driver.  This is an adaptive lock,
     93  *   returned in the second parameter to hw_if->get_locks().  It is known
     94  *   as the "thread lock".
     95  *
     96  *   It serializes access to state in all places except the
     97  *   driver's interrupt service routine.  This lock is taken from process
     98  *   context (example: access to /dev/audio).  It is also taken from soft
     99  *   interrupt handlers in this module, primarily to serialize delivery of
    100  *   wakeups.  This lock may be used/provided by modules external to the
    101  *   audio subsystem, so take care not to introduce a lock order problem.
    102  *   LONG TERM SLEEPS MUST NOT OCCUR WITH THIS LOCK HELD.
    103  *
    104  * - sc_intr_lock, provided by the underlying driver.  This may be either a
    105  *   spinlock (at IPL_SCHED or IPL_VM) or an adaptive lock (IPL_NONE or
    106  *   IPL_SOFT*), returned in the first parameter to hw_if->get_locks().  It
    107  *   is known as the "interrupt lock".
    108  *
    109  *   It provides atomic access to the device's hardware state, and to audio
    110  *   channel data that may be accessed by the hardware driver's ISR.
    111  *   In all places outside the ISR, sc_lock must be held before taking
    112  *   sc_intr_lock.  This is to ensure that groups of hardware operations are
    113  *   made atomically.  SLEEPS CANNOT OCCUR WITH THIS LOCK HELD.
    114  *
    115  * List of hardware interface methods, and which locks are held when each
    116  * is called by this module:
    117  *
    118  *	METHOD			INTR	THREAD  NOTES
    119  *	----------------------- ------- -------	-------------------------
    120  *	open 			x	x
    121  *	close 			x	x
    122  *	drain 			x	x
    123  *	query_encoding		-	x
    124  *	set_params 		-	x
    125  *	round_blocksize		-	x
    126  *	commit_settings		-	x
    127  *	init_output 		x	x
    128  *	init_input 		x	x
    129  *	start_output 		x	x
    130  *	start_input 		x	x
    131  *	halt_output 		x	x
    132  *	halt_input 		x	x
    133  *	speaker_ctl 		x	x
    134  *	getdev 			-	x
    135  *	setfd 			-	x
    136  *	set_port 		-	x
    137  *	get_port 		-	x
    138  *	query_devinfo 		-	x
    139  *	allocm 			-	-	Called at attach time
    140  *	freem 			-	-	Called at attach time
    141  *	round_buffersize 	-	x
    142  *	mappage 		-	-	Mem. unchanged after attach
    143  *	get_props 		-	x
    144  *	trigger_output 		x	x
    145  *	trigger_input 		x	x
    146  *	dev_ioctl 		-	x
    147  *	get_locks 		-	-	Called at attach time
    148  */
    149 
    150 #include <sys/cdefs.h>
    151 __KERNEL_RCSID(0, "$NetBSD: audio.c,v 1.290 2017/01/14 20:05:37 nat Exp $");
    152 
    153 #include "audio.h"
    154 #if NAUDIO > 0
    155 
    156 #include <sys/types.h>
    157 #include <sys/param.h>
    158 #include <sys/ioctl.h>
    159 #include <sys/fcntl.h>
    160 #include <sys/vnode.h>
    161 #include <sys/select.h>
    162 #include <sys/poll.h>
    163 #include <sys/kmem.h>
    164 #include <sys/malloc.h>
    165 #include <sys/proc.h>
    166 #include <sys/systm.h>
    167 #include <sys/sysctl.h>
    168 #include <sys/syslog.h>
    169 #include <sys/kernel.h>
    170 #include <sys/signalvar.h>
    171 #include <sys/conf.h>
    172 #include <sys/audioio.h>
    173 #include <sys/device.h>
    174 #include <sys/intr.h>
    175 #include <sys/kthread.h>
    176 #include <sys/cpu.h>
    177 
    178 #include <dev/audio_if.h>
    179 #include <dev/audiovar.h>
    180 #include <dev/auconv.h>
    181 #include <dev/auvolconv.h>
    182 
    183 #include <machine/endian.h>
    184 
    185 /* #define AUDIO_DEBUG	1 */
    186 #ifdef AUDIO_DEBUG
    187 #define DPRINTF(x)	if (audiodebug) printf x
    188 #define DPRINTFN(n,x)	if (audiodebug>(n)) printf x
    189 int	audiodebug = AUDIO_DEBUG;
    190 #else
    191 #define DPRINTF(x)
    192 #define DPRINTFN(n,x)
    193 #endif
    194 
    195 #define ROUNDSIZE(x)	x &= -16	/* round to nice boundary */
    196 #define SPECIFIED(x)	(x != ~0)
    197 #define SPECIFIED_CH(x)	(x != (u_char)~0)
    198 
    199 /* #define AUDIO_PM_IDLE */
    200 #ifdef AUDIO_PM_IDLE
    201 int	audio_idle_timeout = 30;
    202 #endif
    203 
    204 int	audio_blk_ms = AUDIO_BLK_MS;
    205 
    206 int	audiosetinfo(struct audio_softc *, struct audio_info *, bool, int);
    207 int	audiogetinfo(struct audio_softc *, struct audio_info *, int, int);
    208 
    209 int	audio_open(dev_t, struct audio_softc *, int, int, struct lwp *);
    210 int	audio_close(struct audio_softc *, int, int, struct lwp *, int);
    211 int	audio_read(struct audio_softc *, struct uio *, int);
    212 int	audio_write(struct audio_softc *, struct uio *, int);
    213 int	audio_ioctl(dev_t, struct audio_softc *, u_long, void *, int,
    214 		    struct lwp *);
    215 int	audio_poll(struct audio_softc *, int, struct lwp *);
    216 int	audio_kqfilter(struct audio_softc *, struct knote *);
    217 paddr_t	audio_mmap(struct audio_softc *, off_t, int);
    218 
    219 int	mixer_open(dev_t, struct audio_softc *, int, int, struct lwp *);
    220 int	mixer_close(struct audio_softc *, int, int, struct lwp *);
    221 int	mixer_ioctl(struct audio_softc *, u_long, void *, int, struct lwp *);
    222 static	void mixer_remove(struct audio_softc *);
    223 static	void mixer_signal(struct audio_softc *);
    224 
    225 void	audio_init_record(struct audio_softc *, int);
    226 void	audio_init_play(struct audio_softc *, int);
    227 int	audiostartr(struct audio_softc *, int);
    228 int	audiostartp(struct audio_softc *, int);
    229 void	audio_rint(void *);
    230 void	audio_pint(void *);
    231 void	audio_mix(void *);
    232 void	audio_upmix(void *);
    233 void	audio_play_thread(void *);
    234 void	audio_rec_thread(void *);
    235 void	recswvol_func(struct audio_softc *, struct audio_ringbuffer *, int,
    236 		      size_t);
    237 void	recswvol_func8(struct audio_softc *, struct audio_ringbuffer *, int,
    238 		       size_t);
    239 void	recswvol_func16(struct audio_softc *, struct audio_ringbuffer *, int,
    240 			size_t);
    241 void	recswvol_func32(struct audio_softc *, struct audio_ringbuffer *, int,
    242 			size_t);
    243 void	saturate_func(struct audio_softc *);
    244 void	saturate_func8(struct audio_softc *);
    245 void	saturate_func16(struct audio_softc *);
    246 void	saturate_func32(struct audio_softc *);
    247 void	mix_func(struct audio_softc *, struct audio_ringbuffer *, int);
    248 void	mix_func8(struct audio_softc *, struct audio_ringbuffer *, int);
    249 void	mix_func16(struct audio_softc *, struct audio_ringbuffer *, int);
    250 void	mix_func32(struct audio_softc *, struct audio_ringbuffer *, int);
    251 void	mix_write(void *);
    252 void	mix_read(void *);
    253 int	audio_check_params(struct audio_params *);
    254 
    255 void	audio_calc_blksize(struct audio_softc *, int, int);
    256 void	audio_fill_silence(struct audio_params *, uint8_t *, int);
    257 int	audio_silence_copyout(struct audio_softc *, int, struct uio *);
    258 
    259 void	audio_init_ringbuffer(struct audio_softc *,
    260 			      struct audio_ringbuffer *, int);
    261 int	audio_initbufs(struct audio_softc *, int);
    262 void	audio_calcwater(struct audio_softc *, int);
    263 int	audio_drain(struct audio_softc *, int);
    264 void	audio_clear(struct audio_softc *, int);
    265 void	audio_clear_intr_unlocked(struct audio_softc *sc, int);
    266 static inline void
    267 	audio_pint_silence(struct audio_softc *, struct audio_ringbuffer *,
    268 			   uint8_t *, int, int);
    269 int	audio_alloc_ring(struct audio_softc *, struct audio_ringbuffer *, int,
    270 			 size_t);
    271 void	audio_free_ring(struct audio_softc *, struct audio_ringbuffer *);
    272 static int audio_setup_pfilters(struct audio_softc *, const audio_params_t *,
    273 				stream_filter_list_t *, int);
    274 static int audio_setup_rfilters(struct audio_softc *, const audio_params_t *,
    275 				stream_filter_list_t *, int);
    276 static void audio_stream_dtor(audio_stream_t *);
    277 static int audio_stream_ctor(audio_stream_t *, const audio_params_t *, int);
    278 static void stream_filter_list_append
    279 	(stream_filter_list_t *, stream_filter_factory_t,
    280 	 const audio_params_t *);
    281 static void stream_filter_list_prepend
    282 	(stream_filter_list_t *, stream_filter_factory_t,
    283 	 const audio_params_t *);
    284 static void stream_filter_list_set
    285 	(stream_filter_list_t *, int, stream_filter_factory_t,
    286 	 const audio_params_t *);
    287 int	audio_set_defaults(struct audio_softc *, u_int, int);
    288 static int audio_sysctl_frequency(SYSCTLFN_PROTO);
    289 static int audio_sysctl_precision(SYSCTLFN_PROTO);
    290 static int audio_sysctl_channels(SYSCTLFN_PROTO);
    291 
    292 int	audioprobe(device_t, cfdata_t, void *);
    293 void	audioattach(device_t, device_t, void *);
    294 int	audiodetach(device_t, int);
    295 int	audioactivate(device_t, enum devact);
    296 void	audiochilddet(device_t, device_t);
    297 int	audiorescan(device_t, const char *, const int *);
    298 
    299 #ifdef AUDIO_PM_IDLE
    300 static void	audio_idle(void *);
    301 static void	audio_activity(device_t, devactive_t);
    302 #endif
    303 
    304 static bool	audio_suspend(device_t dv, const pmf_qual_t *);
    305 static bool	audio_resume(device_t dv, const pmf_qual_t *);
    306 static void	audio_volume_down(device_t);
    307 static void	audio_volume_up(device_t);
    308 static void	audio_volume_toggle(device_t);
    309 
    310 static void	audio_mixer_capture(struct audio_softc *);
    311 static void	audio_mixer_restore(struct audio_softc *);
    312 
    313 static int	audio_get_props(struct audio_softc *);
    314 static bool	audio_can_playback(struct audio_softc *);
    315 static bool	audio_can_capture(struct audio_softc *);
    316 
    317 static void	audio_softintr_rd(void *);
    318 static void	audio_softintr_wr(void *);
    319 
    320 static int	audio_enter(dev_t, krw_t, struct audio_softc **);
    321 static void	audio_exit(struct audio_softc *);
    322 static int	audio_waitio(struct audio_softc *, kcondvar_t *);
    323 
    324 #define AUDIO_OUTPUT_CLASS 0
    325 #define AUDIO_INPUT_CLASS 1
    326 
    327 struct portname {
    328 	const char *name;
    329 	int mask;
    330 };
    331 static const struct portname itable[] = {
    332 	{ AudioNmicrophone,	AUDIO_MICROPHONE },
    333 	{ AudioNline,		AUDIO_LINE_IN },
    334 	{ AudioNcd,		AUDIO_CD },
    335 	{ 0, 0 }
    336 };
    337 static const struct portname otable[] = {
    338 	{ AudioNspeaker,	AUDIO_SPEAKER },
    339 	{ AudioNheadphone,	AUDIO_HEADPHONE },
    340 	{ AudioNline,		AUDIO_LINE_OUT },
    341 	{ 0, 0 }
    342 };
    343 void	au_setup_ports(struct audio_softc *, struct au_mixer_ports *,
    344 			mixer_devinfo_t *, const struct portname *);
    345 int	au_set_gain(struct audio_softc *, struct au_mixer_ports *,
    346 			int, int);
    347 void	au_get_gain(struct audio_softc *, struct au_mixer_ports *,
    348 			u_int *, u_char *);
    349 int	au_set_port(struct audio_softc *, struct au_mixer_ports *,
    350 			u_int);
    351 int	au_get_port(struct audio_softc *, struct au_mixer_ports *);
    352 static int
    353 	audio_get_port(struct audio_softc *, mixer_ctrl_t *);
    354 static int
    355 	audio_set_port(struct audio_softc *, mixer_ctrl_t *);
    356 static int
    357 	audio_query_devinfo(struct audio_softc *, mixer_devinfo_t *);
    358 static int audio_set_params
    359 	(struct audio_softc *, int, int, audio_params_t *, audio_params_t *,
    360 	 stream_filter_list_t *, stream_filter_list_t *, int);
    361 static int
    362 audio_query_encoding(struct audio_softc *, struct audio_encoding *);
    363 static int audio_set_vchan_defaults
    364 	(struct audio_softc *, u_int, const struct audio_format *, int);
    365 int	au_get_lr_value(struct audio_softc *, mixer_ctrl_t *, int *, int *);
    366 int	au_set_lr_value(struct audio_softc *, mixer_ctrl_t *, int, int);
    367 int	au_portof(struct audio_softc *, char *, int);
    368 
    369 typedef struct uio_fetcher {
    370 	stream_fetcher_t base;
    371 	struct uio *uio;
    372 	int usedhigh;
    373 	int last_used;
    374 } uio_fetcher_t;
    375 
    376 static void	uio_fetcher_ctor(uio_fetcher_t *, struct uio *, int);
    377 static int	uio_fetcher_fetch_to(struct audio_softc *, stream_fetcher_t *,
    378 				     audio_stream_t *, int);
    379 static int	null_fetcher_fetch_to(struct audio_softc *, stream_fetcher_t *,
    380 				      audio_stream_t *, int);
    381 
    382 dev_type_open(audioopen);
    383 dev_type_close(audioclose);
    384 dev_type_read(audioread);
    385 dev_type_write(audiowrite);
    386 dev_type_ioctl(audioioctl);
    387 dev_type_poll(audiopoll);
    388 dev_type_mmap(audiommap);
    389 dev_type_kqfilter(audiokqfilter);
    390 
    391 const struct cdevsw audio_cdevsw = {
    392 	.d_open = audioopen,
    393 	.d_close = audioclose,
    394 	.d_read = audioread,
    395 	.d_write = audiowrite,
    396 	.d_ioctl = audioioctl,
    397 	.d_stop = nostop,
    398 	.d_tty = notty,
    399 	.d_poll = audiopoll,
    400 	.d_mmap = audiommap,
    401 	.d_kqfilter = audiokqfilter,
    402 	.d_discard = nodiscard,
    403 	.d_flag = D_MCLOSE | D_MPSAFE
    404 };
    405 
    406 /* The default audio mode: 8 kHz mono mu-law */
    407 const struct audio_params audio_default = {
    408 	.sample_rate = 8000,
    409 	.encoding = AUDIO_ENCODING_ULAW,
    410 	.precision = 8,
    411 	.validbits = 8,
    412 	.channels = 1,
    413 };
    414 
    415 CFATTACH_DECL3_NEW(audio, sizeof(struct audio_softc),
    416     audioprobe, audioattach, audiodetach, audioactivate, audiorescan,
    417     audiochilddet, DVF_DETACH_SHUTDOWN);
    418 
    419 extern struct cfdriver audio_cd;
    420 
    421 int
    422 audioprobe(device_t parent, cfdata_t match, void *aux)
    423 {
    424 	struct audio_attach_args *sa;
    425 
    426 	sa = aux;
    427 	DPRINTF(("audioprobe: type=%d sa=%p hw=%p\n",
    428 		 sa->type, sa, sa->hwif));
    429 	return (sa->type == AUDIODEV_TYPE_AUDIO) ? 1 : 0;
    430 }
    431 
    432 void
    433 audioattach(device_t parent, device_t self, void *aux)
    434 {
    435 	struct audio_softc *sc;
    436 	struct audio_attach_args *sa;
    437 	struct virtual_channel *vc;
    438 	const struct audio_hw_if *hwp;
    439 	const struct sysctlnode *node;
    440 	void *hdlp;
    441 	int error;
    442 	mixer_devinfo_t mi;
    443 	int iclass, mclass, oclass, rclass, props;
    444 	int record_master_found, record_source_found;
    445 	bool can_capture, can_playback;
    446 
    447 	sc = device_private(self);
    448 	sc->dev = self;
    449 	sa = aux;
    450 	hwp = sa->hwif;
    451 	hdlp = sa->hdl;
    452 	sc->sc_opens = 0;
    453 	sc->sc_recopens = 0;
    454 	sc->sc_aivalid = false;
    455  	sc->sc_ready = true;
    456 
    457  	sc->sc_format[0].mode = AUMODE_PLAY | AUMODE_RECORD;
    458  	sc->sc_format[0].encoding =
    459 #if BYTE_ORDER == LITTLE_ENDIAN
    460 		 AUDIO_ENCODING_SLINEAR_LE;
    461 #else
    462 		 AUDIO_ENCODING_SLINEAR_BE;
    463 #endif
    464  	sc->sc_format[0].precision = 16;
    465  	sc->sc_format[0].validbits = 16;
    466  	sc->sc_format[0].channels = 2;
    467  	sc->sc_format[0].channel_mask = AUFMT_STEREO;
    468  	sc->sc_format[0].frequency_type = 1;
    469  	sc->sc_format[0].frequency[0] = 44100;
    470 
    471 	sc->sc_vchan_params.sample_rate = 44100;
    472 #if BYTE_ORDER == LITTLE_ENDIAN
    473 	sc->sc_vchan_params.encoding = AUDIO_ENCODING_SLINEAR_LE;
    474 #else
    475 	sc->sc_vchan_params.encoding = AUDIO_ENCODING_SLINEAR_BE;
    476 #endif
    477 	sc->sc_vchan_params.precision = 16;
    478 	sc->sc_vchan_params.validbits = 16;
    479 	sc->sc_vchan_params.channels = 2;
    480 
    481 	sc->sc_trigger_started = false;
    482 	sc->sc_rec_started = false;
    483 	sc->sc_dying = false;
    484 	sc->sc_vchan[0] = kmem_zalloc(sizeof(struct virtual_channel), KM_SLEEP);
    485 	vc = sc->sc_vchan[0];
    486 	memset(sc->sc_audiopid, -1, sizeof(sc->sc_audiopid));
    487 	memset(sc->sc_despid, -1, sizeof(sc->sc_despid));
    488 	vc->sc_open = 0;
    489 	vc->sc_mode = 0;
    490 	vc->sc_npfilters = 0;
    491 	memset(vc->sc_pfilters, 0,
    492 	    sizeof(vc->sc_pfilters));
    493 	vc->sc_lastinfovalid = false;
    494 	vc->sc_swvol = 255;
    495 	vc->sc_recswvol = 255;
    496 	sc->sc_iffreq = 44100;
    497 	sc->sc_precision = 16;
    498 	sc->sc_channels = 2;
    499 
    500 	if (auconv_create_encodings(sc->sc_format, VAUDIO_NFORMATS,
    501 	    &sc->sc_encodings) != 0) {
    502 		aprint_error_dev(self, "couldn't create encodings\n");
    503 		return;
    504 	}
    505 
    506 	cv_init(&sc->sc_rchan, "audiord");
    507 	cv_init(&sc->sc_wchan, "audiowr");
    508 	cv_init(&sc->sc_lchan, "audiolk");
    509 	cv_init(&sc->sc_condvar,"play");
    510 	cv_init(&sc->sc_rcondvar,"record");
    511 
    512 	if (hwp == 0 || hwp->get_locks == 0) {
    513 		aprint_error(": missing method\n");
    514 		panic("audioattach");
    515 	}
    516 
    517 	hwp->get_locks(hdlp, &sc->sc_intr_lock, &sc->sc_lock);
    518 
    519 #ifdef DIAGNOSTIC
    520 	if (hwp->query_encoding == 0 ||
    521 	    hwp->set_params == 0 ||
    522 	    (hwp->start_output == 0 && hwp->trigger_output == 0) ||
    523 	    (hwp->start_input == 0 && hwp->trigger_input == 0) ||
    524 	    hwp->halt_output == 0 ||
    525 	    hwp->halt_input == 0 ||
    526 	    hwp->getdev == 0 ||
    527 	    hwp->set_port == 0 ||
    528 	    hwp->get_port == 0 ||
    529 	    hwp->query_devinfo == 0 ||
    530 	    hwp->get_props == 0) {
    531 		aprint_error(": missing method\n");
    532 		sc->hw_if = NULL;
    533 		return;
    534 	}
    535 #endif
    536 
    537 	sc->hw_if = hwp;
    538 	sc->hw_hdl = hdlp;
    539 	sc->sc_dev = parent;
    540 
    541 	mutex_enter(sc->sc_lock);
    542 	props = audio_get_props(sc);
    543 	mutex_exit(sc->sc_lock);
    544 
    545 	if (props & AUDIO_PROP_FULLDUPLEX)
    546 		aprint_normal(": full duplex");
    547 	else
    548 		aprint_normal(": half duplex");
    549 
    550 	if (props & AUDIO_PROP_PLAYBACK)
    551 		aprint_normal(", playback");
    552 	if (props & AUDIO_PROP_CAPTURE)
    553 		aprint_normal(", capture");
    554 	if (props & AUDIO_PROP_MMAP)
    555 		aprint_normal(", mmap");
    556 	if (props & AUDIO_PROP_INDEPENDENT)
    557 		aprint_normal(", independent");
    558 
    559 	aprint_naive("\n");
    560 	aprint_normal("\n");
    561 
    562 	mutex_enter(sc->sc_lock);
    563 	can_playback = audio_can_playback(sc);
    564 	can_capture = audio_can_capture(sc);
    565 
    566 	if (can_playback) {
    567 		error = audio_alloc_ring(sc, &sc->sc_pr,
    568 	    	    AUMODE_PLAY, AU_RING_SIZE);
    569 		if (error)
    570 			goto bad_play;
    571 
    572 		error = audio_alloc_ring(sc, &sc->sc_vchan[0]->sc_mpr,
    573 	    	    AUMODE_PLAY, AU_RING_SIZE);
    574 bad_play:
    575 		if (error) {
    576 			if (sc->sc_pr.s.start != NULL)
    577 				audio_free_ring(sc, &sc->sc_pr);
    578 			sc->hw_if = NULL;
    579 			aprint_error_dev(sc->sc_dev, "could not allocate play "
    580 			    "buffer\n");
    581 			return;
    582 		}
    583 	}
    584 	if (can_capture) {
    585 		error = audio_alloc_ring(sc, &sc->sc_rr,
    586 		    AUMODE_RECORD, AU_RING_SIZE);
    587 		if (error)
    588 			goto bad_rec;
    589 
    590 		error = audio_alloc_ring(sc, &sc->sc_vchan[0]->sc_mrr,
    591 		    AUMODE_RECORD, AU_RING_SIZE);
    592 bad_rec:
    593 		if (error) {
    594 			if (sc->sc_vchan[0]->sc_mrr.s.start != NULL)
    595 				audio_free_ring(sc, &sc->sc_vchan[0]->sc_mrr);
    596 			if (sc->sc_pr.s.start != NULL)
    597 				audio_free_ring(sc, &sc->sc_pr);
    598 			if (sc->sc_vchan[0]->sc_mpr.s.start != 0)
    599 				audio_free_ring(sc, &sc->sc_vchan[0]->sc_mpr);
    600 			sc->hw_if = NULL;
    601 			aprint_error_dev(sc->sc_dev, "could not allocate record"
    602 			   " buffer\n");
    603 			return;
    604 		}
    605 	}
    606 
    607 	sc->sc_lastgain = 128;
    608 	sc->sc_saturate = true;
    609 
    610 	error = audio_set_vchan_defaults(sc, AUMODE_PLAY | AUMODE_PLAY_ALL |
    611 	    AUMODE_RECORD, &sc->sc_format[0], 0);
    612 	mutex_exit(sc->sc_lock);
    613 	if (error != 0) {
    614 		aprint_error_dev(sc->sc_dev, "%s: audio_set_vchan_defaults() "
    615 		    "failed\n", __func__);
    616 	}
    617 
    618 	sc->sc_pr.blksize = sc->sc_vchan[0]->sc_mpr.blksize;
    619 	sc->sc_rr.blksize = sc->sc_vchan[0]->sc_mrr.blksize;
    620 	sc->sc_sih_rd = softint_establish(SOFTINT_SERIAL | SOFTINT_MPSAFE,
    621 	    audio_softintr_rd, sc);
    622 	sc->sc_sih_wr = softint_establish(SOFTINT_SERIAL | SOFTINT_MPSAFE,
    623 	    audio_softintr_wr, sc);
    624 
    625 	iclass = mclass = oclass = rclass = -1;
    626 	sc->sc_inports.index = -1;
    627 	sc->sc_inports.master = -1;
    628 	sc->sc_inports.nports = 0;
    629 	sc->sc_inports.isenum = false;
    630 	sc->sc_inports.allports = 0;
    631 	sc->sc_inports.isdual = false;
    632 	sc->sc_inports.mixerout = -1;
    633 	sc->sc_inports.cur_port = -1;
    634 	sc->sc_outports.index = -1;
    635 	sc->sc_outports.master = -1;
    636 	sc->sc_outports.nports = 0;
    637 	sc->sc_outports.isenum = false;
    638 	sc->sc_outports.allports = 0;
    639 	sc->sc_outports.isdual = false;
    640 	sc->sc_outports.mixerout = -1;
    641 	sc->sc_outports.cur_port = -1;
    642 	sc->sc_monitor_port = -1;
    643 	/*
    644 	 * Read through the underlying driver's list, picking out the class
    645 	 * names from the mixer descriptions. We'll need them to decode the
    646 	 * mixer descriptions on the next pass through the loop.
    647 	 */
    648 	mutex_enter(sc->sc_lock);
    649 	for(mi.index = 0; ; mi.index++) {
    650 		if (audio_query_devinfo(sc, &mi) != 0)
    651 			break;
    652 		 /*
    653 		  * The type of AUDIO_MIXER_CLASS merely introduces a class.
    654 		  * All the other types describe an actual mixer.
    655 		  */
    656 		if (mi.type == AUDIO_MIXER_CLASS) {
    657 			if (strcmp(mi.label.name, AudioCinputs) == 0)
    658 				iclass = mi.mixer_class;
    659 			if (strcmp(mi.label.name, AudioCmonitor) == 0)
    660 				mclass = mi.mixer_class;
    661 			if (strcmp(mi.label.name, AudioCoutputs) == 0)
    662 				oclass = mi.mixer_class;
    663 			if (strcmp(mi.label.name, AudioCrecord) == 0)
    664 				rclass = mi.mixer_class;
    665 		}
    666 	}
    667 	mutex_exit(sc->sc_lock);
    668 
    669 	/* Allocate save area.  Ensure non-zero allocation. */
    670 	sc->sc_nmixer_states = mi.index;
    671 	sc->sc_static_nmixer_states = mi.index;
    672 	sc->sc_mixer_state = kmem_zalloc(sizeof(mixer_ctrl_t) *
    673 	    (sc->sc_nmixer_states + (VAUDIOCHANS + 1) * 2), KM_SLEEP);
    674 
    675 	/*
    676 	 * This is where we assign each control in the "audio" model, to the
    677 	 * underlying "mixer" control.  We walk through the whole list once,
    678 	 * assigning likely candidates as we come across them.
    679 	 */
    680 	record_master_found = 0;
    681 	record_source_found = 0;
    682 	mutex_enter(sc->sc_lock);
    683 	for(mi.index = 0; ; mi.index++) {
    684 		if (audio_query_devinfo(sc, &mi) != 0)
    685 			break;
    686 		KASSERT(mi.index < sc->sc_nmixer_states);
    687 		if (mi.type == AUDIO_MIXER_CLASS)
    688 			continue;
    689 		if (mi.mixer_class == iclass) {
    690 			/*
    691 			 * AudioCinputs is only a fallback, when we don't
    692 			 * find what we're looking for in AudioCrecord, so
    693 			 * check the flags before accepting one of these.
    694 			 */
    695 			if (strcmp(mi.label.name, AudioNmaster) == 0
    696 			    && record_master_found == 0)
    697 				sc->sc_inports.master = mi.index;
    698 			if (strcmp(mi.label.name, AudioNsource) == 0
    699 			    && record_source_found == 0) {
    700 				if (mi.type == AUDIO_MIXER_ENUM) {
    701 				    int i;
    702 				    for(i = 0; i < mi.un.e.num_mem; i++)
    703 					if (strcmp(mi.un.e.member[i].label.name,
    704 						    AudioNmixerout) == 0)
    705 						sc->sc_inports.mixerout =
    706 						    mi.un.e.member[i].ord;
    707 				}
    708 				au_setup_ports(sc, &sc->sc_inports, &mi,
    709 				    itable);
    710 			}
    711 			if (strcmp(mi.label.name, AudioNdac) == 0 &&
    712 			    sc->sc_outports.master == -1)
    713 				sc->sc_outports.master = mi.index;
    714 		} else if (mi.mixer_class == mclass) {
    715 			if (strcmp(mi.label.name, AudioNmonitor) == 0)
    716 				sc->sc_monitor_port = mi.index;
    717 		} else if (mi.mixer_class == oclass) {
    718 			if (strcmp(mi.label.name, AudioNmaster) == 0)
    719 				sc->sc_outports.master = mi.index;
    720 			if (strcmp(mi.label.name, AudioNselect) == 0)
    721 				au_setup_ports(sc, &sc->sc_outports, &mi,
    722 				    otable);
    723 		} else if (mi.mixer_class == rclass) {
    724 			/*
    725 			 * These are the preferred mixers for the audio record
    726 			 * controls, so set the flags here, but don't check.
    727 			 */
    728 			if (strcmp(mi.label.name, AudioNmaster) == 0) {
    729 				sc->sc_inports.master = mi.index;
    730 				record_master_found = 1;
    731 			}
    732 #if 1	/* Deprecated. Use AudioNmaster. */
    733 			if (strcmp(mi.label.name, AudioNrecord) == 0) {
    734 				sc->sc_inports.master = mi.index;
    735 				record_master_found = 1;
    736 			}
    737 			if (strcmp(mi.label.name, AudioNvolume) == 0) {
    738 				sc->sc_inports.master = mi.index;
    739 				record_master_found = 1;
    740 			}
    741 #endif
    742 			if (strcmp(mi.label.name, AudioNsource) == 0) {
    743 				if (mi.type == AUDIO_MIXER_ENUM) {
    744 				    int i;
    745 				    for(i = 0; i < mi.un.e.num_mem; i++)
    746 					if (strcmp(mi.un.e.member[i].label.name,
    747 						    AudioNmixerout) == 0)
    748 						sc->sc_inports.mixerout =
    749 						    mi.un.e.member[i].ord;
    750 				}
    751 				au_setup_ports(sc, &sc->sc_inports, &mi,
    752 				    itable);
    753 				record_source_found = 1;
    754 			}
    755 		}
    756 	}
    757 	mutex_exit(sc->sc_lock);
    758 	DPRINTF(("audio_attach: inputs ports=0x%x, input master=%d, "
    759 		 "output ports=0x%x, output master=%d\n",
    760 		 sc->sc_inports.allports, sc->sc_inports.master,
    761 		 sc->sc_outports.allports, sc->sc_outports.master));
    762 
    763 	/* sysctl set-up for alternate configs */
    764 	sysctl_createv(&sc->sc_log, 0, NULL, &node,
    765 		0,
    766 		CTLTYPE_NODE, device_xname(sc->sc_dev),
    767 		SYSCTL_DESCR("audio format information"),
    768 		NULL, 0,
    769 		NULL, 0,
    770 		CTL_HW,
    771 		CTL_CREATE, CTL_EOL);
    772 
    773 	if (node != NULL) {
    774 		sysctl_createv(&sc->sc_log, 0, NULL, NULL,
    775 			CTLFLAG_READWRITE,
    776 			CTLTYPE_INT, "frequency",
    777 			SYSCTL_DESCR("intermediate frequency"),
    778 			audio_sysctl_frequency, 0,
    779 			(void *)sc, 0,
    780 			CTL_HW, node->sysctl_num,
    781 			CTL_CREATE, CTL_EOL);
    782 
    783 		sysctl_createv(&sc->sc_log, 0, NULL, NULL,
    784 			CTLFLAG_READWRITE,
    785 			CTLTYPE_INT, "precision",
    786 			SYSCTL_DESCR("intermediate precision"),
    787 			audio_sysctl_precision, 0,
    788 			(void *)sc, 0,
    789 			CTL_HW, node->sysctl_num,
    790 			CTL_CREATE, CTL_EOL);
    791 
    792 		sysctl_createv(&sc->sc_log, 0, NULL, NULL,
    793 			CTLFLAG_READWRITE,
    794 			CTLTYPE_INT, "channels",
    795 			SYSCTL_DESCR("intermediate channels"),
    796 			audio_sysctl_channels, 0,
    797 			(void *)sc, 0,
    798 			CTL_HW, node->sysctl_num,
    799 			CTL_CREATE, CTL_EOL);
    800 
    801 		sysctl_createv(&sc->sc_log, 0, NULL, NULL,
    802 			CTLFLAG_READWRITE,
    803 			CTLTYPE_BOOL, "saturate",
    804 			SYSCTL_DESCR("saturate to max. volume"),
    805 			NULL, 0,
    806 			&sc->sc_saturate, 0,
    807 			CTL_HW, node->sysctl_num,
    808 			CTL_CREATE, CTL_EOL);
    809 	}
    810 
    811 	selinit(&sc->sc_rsel);
    812 	selinit(&sc->sc_wsel);
    813 
    814 #ifdef AUDIO_PM_IDLE
    815 	callout_init(&sc->sc_idle_counter, 0);
    816 	callout_setfunc(&sc->sc_idle_counter, audio_idle, self);
    817 #endif
    818 
    819 	if (!pmf_device_register(self, audio_suspend, audio_resume))
    820 		aprint_error_dev(self, "couldn't establish power handler\n");
    821 #ifdef AUDIO_PM_IDLE
    822 	if (!device_active_register(self, audio_activity))
    823 		aprint_error_dev(self, "couldn't register activity handler\n");
    824 #endif
    825 
    826 	if (!pmf_event_register(self, PMFE_AUDIO_VOLUME_DOWN,
    827 	    audio_volume_down, true))
    828 		aprint_error_dev(self, "couldn't add volume down handler\n");
    829 	if (!pmf_event_register(self, PMFE_AUDIO_VOLUME_UP,
    830 	    audio_volume_up, true))
    831 		aprint_error_dev(self, "couldn't add volume up handler\n");
    832 	if (!pmf_event_register(self, PMFE_AUDIO_VOLUME_TOGGLE,
    833 	    audio_volume_toggle, true))
    834 		aprint_error_dev(self, "couldn't add volume toggle handler\n");
    835 
    836 #ifdef AUDIO_PM_IDLE
    837 	callout_schedule(&sc->sc_idle_counter, audio_idle_timeout * hz);
    838 #endif
    839 	kthread_create(PRI_NONE, KTHREAD_MPSAFE | KTHREAD_MUSTJOIN, NULL,
    840 	    audio_rec_thread, sc, &sc->sc_recthread, "audiorec");
    841 	kthread_create(PRI_NONE, KTHREAD_MPSAFE | KTHREAD_MUSTJOIN, NULL,
    842 	    audio_play_thread, sc, &sc->sc_playthread, "audiomix");
    843 	audiorescan(self, "audio", NULL);
    844 }
    845 
    846 int
    847 audioactivate(device_t self, enum devact act)
    848 {
    849 	struct audio_softc *sc = device_private(self);
    850 
    851 	switch (act) {
    852 	case DVACT_DEACTIVATE:
    853 		mutex_enter(sc->sc_lock);
    854 		sc->sc_dying = true;
    855 		cv_broadcast(&sc->sc_condvar);
    856 		mutex_exit(sc->sc_lock);
    857 		return 0;
    858 	default:
    859 		return EOPNOTSUPP;
    860 	}
    861 }
    862 
    863 int
    864 audiodetach(device_t self, int flags)
    865 {
    866 	struct audio_softc *sc;
    867 	int maj, mn, i, n, rc;
    868 
    869 	sc = device_private(self);
    870 	DPRINTF(("audio_detach: sc=%p flags=%d\n", sc, flags));
    871 
    872 	/* Start draining existing accessors of the device. */
    873 	if ((rc = config_detach_children(self, flags)) != 0)
    874 		return rc;
    875 	mutex_enter(sc->sc_lock);
    876 	sc->sc_dying = true;
    877 	cv_broadcast(&sc->sc_wchan);
    878 	cv_broadcast(&sc->sc_rchan);
    879 	cv_broadcast(&sc->sc_condvar);
    880 	cv_broadcast(&sc->sc_rcondvar);
    881 	mutex_exit(sc->sc_lock);
    882 	kthread_join(sc->sc_playthread);
    883 	kthread_join(sc->sc_recthread);
    884 	mutex_enter(sc->sc_lock);
    885 	cv_destroy(&sc->sc_condvar);
    886 	cv_destroy(&sc->sc_rcondvar);
    887 	mutex_exit(sc->sc_lock);
    888 
    889 	/* delete sysctl nodes */
    890 	sysctl_teardown(&sc->sc_log);
    891 
    892 	/* locate the major number */
    893 	maj = cdevsw_lookup_major(&audio_cdevsw);
    894 
    895 	/*
    896 	 * Nuke the vnodes for any open instances (calls close).
    897 	 * Will wait until any activity on the device nodes has ceased.
    898 	 *
    899 	 * XXXAD NOT YET.
    900 	 *
    901 	 * XXXAD NEED TO PREVENT NEW REFERENCES THROUGH AUDIO_ENTER().
    902 	 */
    903 	mn = device_unit(self);
    904 	vdevgone(maj, mn | SOUND_DEVICE,    mn | SOUND_DEVICE, VCHR);
    905 	vdevgone(maj, mn | AUDIO_DEVICE,    mn | AUDIO_DEVICE, VCHR);
    906 	vdevgone(maj, mn | AUDIOCTL_DEVICE, mn | AUDIOCTL_DEVICE, VCHR);
    907 	vdevgone(maj, mn | MIXER_DEVICE,    mn | MIXER_DEVICE, VCHR);
    908 
    909 	pmf_event_deregister(self, PMFE_AUDIO_VOLUME_DOWN,
    910 	    audio_volume_down, true);
    911 	pmf_event_deregister(self, PMFE_AUDIO_VOLUME_UP,
    912 	    audio_volume_up, true);
    913 	pmf_event_deregister(self, PMFE_AUDIO_VOLUME_TOGGLE,
    914 	    audio_volume_toggle, true);
    915 
    916 #ifdef AUDIO_PM_IDLE
    917 	callout_halt(&sc->sc_idle_counter, sc->sc_lock);
    918 
    919 	device_active_deregister(self, audio_activity);
    920 #endif
    921 
    922 	pmf_device_deregister(self);
    923 
    924 	/* free resources */
    925 	for (n = 0; n < VAUDIOCHANS; n++) {
    926 		if (n != 0 && sc->sc_audiopid[n].pid == -1)
    927 			continue;
    928 		audio_free_ring(sc, &sc->sc_vchan[n]->sc_mpr);
    929 		audio_free_ring(sc, &sc->sc_vchan[n]->sc_mrr);
    930 	}
    931 	audio_free_ring(sc, &sc->sc_pr);
    932 	audio_free_ring(sc, &sc->sc_rr);
    933 	for (n = 0; n < VAUDIOCHANS; n++) {
    934 		if (n != 0 && sc->sc_audiopid[n].pid == -1)
    935 			continue;
    936 		for (i = 0; i < sc->sc_vchan[n]->sc_npfilters; i++) {
    937 			sc->sc_vchan[n]->sc_pfilters[i]->dtor
    938 			    (sc->sc_vchan[n]->sc_pfilters[i]);
    939 			sc->sc_vchan[n]->sc_pfilters[i] = NULL;
    940 			audio_stream_dtor(&sc->sc_vchan[n]->sc_pstreams[i]);
    941 		}
    942 		sc->sc_vchan[n]->sc_npfilters = 0;
    943 
    944 		for (i = 0; i < sc->sc_vchan[n]->sc_nrfilters; i++) {
    945 			sc->sc_vchan[n]->sc_rfilters[i]->dtor
    946 			    (sc->sc_vchan[n]->sc_rfilters[i]);
    947 			sc->sc_vchan[n]->sc_rfilters[i] = NULL;
    948 			audio_stream_dtor(&sc->sc_vchan[n]->sc_rstreams[i]);
    949 		}
    950 		sc->sc_vchan[n]->sc_nrfilters = 0;
    951 	}
    952 
    953 	auconv_delete_encodings(sc->sc_encodings);
    954 
    955 	if (sc->sc_sih_rd) {
    956 		softint_disestablish(sc->sc_sih_rd);
    957 		sc->sc_sih_rd = NULL;
    958 	}
    959 	if (sc->sc_sih_wr) {
    960 		softint_disestablish(sc->sc_sih_wr);
    961 		sc->sc_sih_wr = NULL;
    962 	}
    963 
    964 	kmem_free(sc->sc_vchan[0], sizeof(struct virtual_channel));
    965 
    966 #ifdef AUDIO_PM_IDLE
    967 	callout_destroy(&sc->sc_idle_counter);
    968 #endif
    969 	seldestroy(&sc->sc_rsel);
    970 	seldestroy(&sc->sc_wsel);
    971 
    972 	cv_destroy(&sc->sc_rchan);
    973 	cv_destroy(&sc->sc_wchan);
    974 	cv_destroy(&sc->sc_lchan);
    975 
    976 	return 0;
    977 }
    978 
    979 void
    980 audiochilddet(device_t self, device_t child)
    981 {
    982 
    983 	/* we hold no child references, so do nothing */
    984 }
    985 
    986 static int
    987 audiosearch(device_t parent, cfdata_t cf, const int *locs, void *aux)
    988 {
    989 
    990 	if (config_match(parent, cf, aux))
    991 		config_attach_loc(parent, cf, locs, aux, NULL);
    992 
    993 	return 0;
    994 }
    995 
    996 int
    997 audiorescan(device_t self, const char *ifattr, const int *flags)
    998 {
    999 	struct audio_softc *sc = device_private(self);
   1000 
   1001 	if (!ifattr_match(ifattr, "audio"))
   1002 		return 0;
   1003 
   1004 	config_search_loc(audiosearch, sc->dev, "audio", NULL, NULL);
   1005 
   1006 	return 0;
   1007 }
   1008 
   1009 
   1010 int
   1011 au_portof(struct audio_softc *sc, char *name, int class)
   1012 {
   1013 	mixer_devinfo_t mi;
   1014 
   1015 	for (mi.index = 0; audio_query_devinfo(sc, &mi) == 0; mi.index++) {
   1016 		if (mi.mixer_class == class && strcmp(mi.label.name, name) == 0)
   1017 			return mi.index;
   1018 	}
   1019 	return -1;
   1020 }
   1021 
   1022 void
   1023 au_setup_ports(struct audio_softc *sc, struct au_mixer_ports *ports,
   1024 	       mixer_devinfo_t *mi, const struct portname *tbl)
   1025 {
   1026 	int i, j;
   1027 
   1028 	ports->index = mi->index;
   1029 	if (mi->type == AUDIO_MIXER_ENUM) {
   1030 		ports->isenum = true;
   1031 		for(i = 0; tbl[i].name; i++)
   1032 		    for(j = 0; j < mi->un.e.num_mem; j++)
   1033 			if (strcmp(mi->un.e.member[j].label.name,
   1034 						    tbl[i].name) == 0) {
   1035 				ports->allports |= tbl[i].mask;
   1036 				ports->aumask[ports->nports] = tbl[i].mask;
   1037 				ports->misel[ports->nports] =
   1038 				    mi->un.e.member[j].ord;
   1039 				ports->miport[ports->nports] =
   1040 				    au_portof(sc, mi->un.e.member[j].label.name,
   1041 				    mi->mixer_class);
   1042 				if (ports->mixerout != -1 &&
   1043 				    ports->miport[ports->nports] != -1)
   1044 					ports->isdual = true;
   1045 				++ports->nports;
   1046 			}
   1047 	} else if (mi->type == AUDIO_MIXER_SET) {
   1048 		for(i = 0; tbl[i].name; i++)
   1049 		    for(j = 0; j < mi->un.s.num_mem; j++)
   1050 			if (strcmp(mi->un.s.member[j].label.name,
   1051 						tbl[i].name) == 0) {
   1052 				ports->allports |= tbl[i].mask;
   1053 				ports->aumask[ports->nports] = tbl[i].mask;
   1054 				ports->misel[ports->nports] =
   1055 				    mi->un.s.member[j].mask;
   1056 				ports->miport[ports->nports] =
   1057 				    au_portof(sc, mi->un.s.member[j].label.name,
   1058 				    mi->mixer_class);
   1059 				++ports->nports;
   1060 			}
   1061 	}
   1062 }
   1063 
   1064 /*
   1065  * Called from hardware driver.  This is where the MI audio driver gets
   1066  * probed/attached to the hardware driver.
   1067  */
   1068 device_t
   1069 audio_attach_mi(const struct audio_hw_if *ahwp, void *hdlp, device_t dev)
   1070 {
   1071 	struct audio_attach_args arg;
   1072 
   1073 #ifdef DIAGNOSTIC
   1074 	if (ahwp == NULL) {
   1075 		aprint_error("audio_attach_mi: NULL\n");
   1076 		return 0;
   1077 	}
   1078 #endif
   1079 	arg.type = AUDIODEV_TYPE_AUDIO;
   1080 	arg.hwif = ahwp;
   1081 	arg.hdl = hdlp;
   1082 	return config_found(dev, &arg, audioprint);
   1083 }
   1084 
   1085 #ifdef AUDIO_DEBUG
   1086 void	audio_printsc(struct audio_softc *);
   1087 void	audio_print_params(const char *, struct audio_params *);
   1088 
   1089 void
   1090 audio_printsc(struct audio_softc *sc)
   1091 {
   1092 	int n;
   1093 
   1094 	for (n = 1; n < VAUDIOCHANS; n++) {
   1095 		if (sc->sc_audiopid[n].pid == curproc->p_pid)
   1096 			break;
   1097 	}
   1098 
   1099 	if (n == VAUDIOCHANS)
   1100 		return;
   1101 
   1102 	printf("hwhandle %p hw_if %p ", sc->hw_hdl, sc->hw_if);
   1103 	printf("open 0x%x mode 0x%x\n", sc->sc_vchan[n]->sc_open,
   1104 	    sc->sc_vchan[n]->sc_mode);
   1105 	printf("rchan 0x%x wchan 0x%x ", cv_has_waiters(&sc->sc_rchan),
   1106 	    cv_has_waiters(&sc->sc_wchan));
   1107 	printf("rring used 0x%x pring used=%d\n",
   1108 	       audio_stream_get_used(&sc->sc_vchan[n]->sc_mrr.s),
   1109 	       audio_stream_get_used(&sc->sc_vchan[n]->sc_mpr.s));
   1110 	printf("rbus 0x%x pbus 0x%x ", sc->sc_vchan[n]->sc_rbus,
   1111 	    sc->sc_vchan[n]->sc_pbus);
   1112 	printf("blksize %d", sc->sc_vchan[n]->sc_mpr.blksize);
   1113 	printf("hiwat %d lowat %d\n", sc->sc_vchan[n]->sc_mpr.usedhigh,
   1114 	    sc->sc_vchan[n]->sc_mpr.usedlow);
   1115 }
   1116 
   1117 void
   1118 audio_print_params(const char *s, struct audio_params *p)
   1119 {
   1120 	printf("%s enc=%u %uch %u/%ubit %uHz\n", s, p->encoding, p->channels,
   1121 	       p->validbits, p->precision, p->sample_rate);
   1122 }
   1123 #endif
   1124 
   1125 int
   1126 audio_alloc_ring(struct audio_softc *sc, struct audio_ringbuffer *r,
   1127 		 int direction, size_t bufsize)
   1128 {
   1129 	const struct audio_hw_if *hw;
   1130 	void *hdl;
   1131 
   1132 	hw = sc->hw_if;
   1133 	hdl = sc->hw_hdl;
   1134 	/*
   1135 	 * Alloc DMA play and record buffers
   1136 	 */
   1137 	if (bufsize < AUMINBUF)
   1138 		bufsize = AUMINBUF;
   1139 	ROUNDSIZE(bufsize);
   1140 	if (hw->round_buffersize) {
   1141 		bufsize = hw->round_buffersize(hdl, direction, bufsize);
   1142 	}
   1143 	if (hw->allocm && (r == &sc->sc_vchan[0]->sc_mpr ||
   1144 	    r == &sc->sc_vchan[0]->sc_mrr))
   1145 		r->s.start = hw->allocm(hdl, direction, bufsize);
   1146 	else
   1147 		r->s.start = kmem_zalloc(bufsize, KM_SLEEP);
   1148 	if (r->s.start == NULL)
   1149 		return ENOMEM;
   1150 	r->s.bufsize = bufsize;
   1151 
   1152 	return 0;
   1153 }
   1154 
   1155 void
   1156 audio_free_ring(struct audio_softc *sc, struct audio_ringbuffer *r)
   1157 {
   1158 	if (r->s.start == NULL)
   1159 		return;
   1160 
   1161 	if (sc->hw_if->freem && (r == &sc->sc_vchan[0]->sc_mpr ||
   1162 	    r == &sc->sc_vchan[0]->sc_mrr))
   1163 		sc->hw_if->freem(sc->hw_hdl, r->s.start, r->s.bufsize);
   1164 	else
   1165 		kmem_free(r->s.start, r->s.bufsize);
   1166 	r->s.start = NULL;
   1167 }
   1168 
   1169 static int
   1170 audio_setup_pfilters(struct audio_softc *sc, const audio_params_t *pp,
   1171 		     stream_filter_list_t *pfilters, int m)
   1172 {
   1173 	stream_filter_t *pf[AUDIO_MAX_FILTERS], *of[AUDIO_MAX_FILTERS];
   1174 	audio_stream_t ps[AUDIO_MAX_FILTERS], os[AUDIO_MAX_FILTERS];
   1175 	struct virtual_channel *vc;
   1176 	const audio_params_t *from_param;
   1177 	audio_params_t *to_param;
   1178 	int i, n, onfilters;
   1179 
   1180 	KASSERT(mutex_owned(sc->sc_lock));
   1181 	vc = sc->sc_vchan[m];
   1182 
   1183 	/* Construct new filters. */
   1184 	mutex_exit(sc->sc_lock);
   1185 	memset(pf, 0, sizeof(pf));
   1186 	memset(ps, 0, sizeof(ps));
   1187 	from_param = pp;
   1188 	for (i = 0; i < pfilters->req_size; i++) {
   1189 		n = pfilters->req_size - i - 1;
   1190 		to_param = &pfilters->filters[n].param;
   1191 		audio_check_params(to_param);
   1192 		pf[i] = pfilters->filters[n].factory(sc, from_param, to_param);
   1193 		if (pf[i] == NULL)
   1194 			break;
   1195 		if (audio_stream_ctor(&ps[i], from_param, AU_RING_SIZE))
   1196 			break;
   1197 		if (i > 0)
   1198 			pf[i]->set_fetcher(pf[i], &pf[i - 1]->base);
   1199 		from_param = to_param;
   1200 	}
   1201 	if (i < pfilters->req_size) { /* failure */
   1202 		DPRINTF(("%s: pfilters failure\n", __func__));
   1203 		for (; i >= 0; i--) {
   1204 			if (pf[i] != NULL)
   1205 				pf[i]->dtor(pf[i]);
   1206 			audio_stream_dtor(&ps[i]);
   1207 		}
   1208 		mutex_enter(sc->sc_lock);
   1209 		return EINVAL;
   1210 	}
   1211 	mutex_enter(sc->sc_lock);
   1212 
   1213 	/* Swap in new filters. */
   1214 	mutex_enter(sc->sc_intr_lock);
   1215 	memcpy(of, vc->sc_pfilters, sizeof(of));
   1216 	memcpy(os, vc->sc_pstreams, sizeof(os));
   1217 	onfilters = vc->sc_npfilters;
   1218 	memcpy(vc->sc_pfilters, pf, sizeof(pf));
   1219 	memcpy(vc->sc_pstreams, ps, sizeof(ps));
   1220 	vc->sc_npfilters = pfilters->req_size;
   1221 	for (i = 0; i < pfilters->req_size; i++)
   1222 		pf[i]->set_inputbuffer(pf[i], &vc->sc_pstreams[i]);
   1223 
   1224 	/* hardware format and the buffer near to userland */
   1225 	if (pfilters->req_size <= 0) {
   1226 		vc->sc_mpr.s.param = *pp;
   1227 		vc->sc_pustream = &vc->sc_mpr.s;
   1228 	} else {
   1229 		vc->sc_mpr.s.param = pfilters->filters[0].param;
   1230 		vc->sc_pustream = &vc->sc_pstreams[0];
   1231 	}
   1232 	mutex_exit(sc->sc_intr_lock);
   1233 
   1234 	/* Destroy old filters. */
   1235 	mutex_exit(sc->sc_lock);
   1236 	for (i = 0; i < onfilters; i++) {
   1237 		of[i]->dtor(of[i]);
   1238 		audio_stream_dtor(&os[i]);
   1239 	}
   1240 	mutex_enter(sc->sc_lock);
   1241 
   1242 #ifdef AUDIO_DEBUG
   1243 	printf("%s: HW-buffer=%p pustream=%p\n",
   1244 	       __func__, &vc->sc_mpr.s, vc->sc_pustream);
   1245 	for (i = 0; i < pfilters->req_size; i++) {
   1246 		char num[100];
   1247 		snprintf(num, 100, "[%d]", i);
   1248 		audio_print_params(num, &vc->sc_pstreams[i].param);
   1249 	}
   1250 	audio_print_params("[HW]", &vc->sc_mpr.s.param);
   1251 #endif /* AUDIO_DEBUG */
   1252 
   1253 	return 0;
   1254 }
   1255 
   1256 static int
   1257 audio_setup_rfilters(struct audio_softc *sc, const audio_params_t *rp,
   1258 		     stream_filter_list_t *rfilters, int m)
   1259 {
   1260 	stream_filter_t *rf[AUDIO_MAX_FILTERS], *of[AUDIO_MAX_FILTERS];
   1261 	audio_stream_t rs[AUDIO_MAX_FILTERS], os[AUDIO_MAX_FILTERS];
   1262 	struct virtual_channel *vc;
   1263 	const audio_params_t *to_param;
   1264 	audio_params_t *from_param;
   1265 	int i, onfilters;
   1266 
   1267 	KASSERT(mutex_owned(sc->sc_lock));
   1268 	vc = sc->sc_vchan[m];
   1269 
   1270 	/* Construct new filters. */
   1271 	mutex_exit(sc->sc_lock);
   1272 	memset(rf, 0, sizeof(rf));
   1273 	memset(rs, 0, sizeof(rs));
   1274 	for (i = 0; i < rfilters->req_size; i++) {
   1275 		from_param = &rfilters->filters[i].param;
   1276 		audio_check_params(from_param);
   1277 		to_param = i + 1 < rfilters->req_size
   1278 			? &rfilters->filters[i + 1].param : rp;
   1279 		rf[i] = rfilters->filters[i].factory(sc, from_param, to_param);
   1280 		if (rf[i] == NULL)
   1281 			break;
   1282 		if (audio_stream_ctor(&rs[i], to_param, AU_RING_SIZE))
   1283 			break;
   1284 		if (i > 0) {
   1285 			rf[i]->set_fetcher(rf[i], &rf[i - 1]->base);
   1286 		} else {
   1287 			/* rf[0] has no previous fetcher because
   1288 			 * the audio hardware fills data to the
   1289 			 * input buffer. */
   1290 			rf[0]->set_inputbuffer(rf[0], &vc->sc_mrr.s);
   1291 		}
   1292 	}
   1293 	if (i < rfilters->req_size) { /* failure */
   1294 		DPRINTF(("%s: rfilters failure\n", __func__));
   1295 		for (; i >= 0; i--) {
   1296 			if (rf[i] != NULL)
   1297 				rf[i]->dtor(rf[i]);
   1298 			audio_stream_dtor(&rs[i]);
   1299 		}
   1300 		mutex_enter(sc->sc_lock);
   1301 		return EINVAL;
   1302 	}
   1303 	mutex_enter(sc->sc_lock);
   1304 
   1305 	/* Swap in new filters. */
   1306 	mutex_enter(sc->sc_intr_lock);
   1307 	memcpy(of, vc->sc_rfilters, sizeof(of));
   1308 	memcpy(os, vc->sc_rstreams, sizeof(os));
   1309 	onfilters = vc->sc_nrfilters;
   1310 	memcpy(vc->sc_rfilters, rf, sizeof(rf));
   1311 	memcpy(vc->sc_rstreams, rs, sizeof(rs));
   1312 	vc->sc_nrfilters = rfilters->req_size;
   1313 	for (i = 1; i < rfilters->req_size; i++)
   1314 		rf[i]->set_inputbuffer(rf[i], &vc->sc_rstreams[i - 1]);
   1315 
   1316 	/* hardware format and the buffer near to userland */
   1317 	if (rfilters->req_size <= 0) {
   1318 		vc->sc_mrr.s.param = *rp;
   1319 		vc->sc_rustream = &vc->sc_mrr.s;
   1320 	} else {
   1321 		vc->sc_mrr.s.param = rfilters->filters[0].param;
   1322 		vc->sc_rustream = &vc->sc_rstreams[rfilters->req_size - 1];
   1323 	}
   1324 	mutex_exit(sc->sc_intr_lock);
   1325 
   1326 #ifdef AUDIO_DEBUG
   1327 	printf("%s: HW-buffer=%p pustream=%p\n",
   1328 	       __func__, &vc->sc_mrr.s, vc->sc_rustream);
   1329 	audio_print_params("[HW]", &vc->sc_mrr.s.param);
   1330 	for (i = 0; i < rfilters->req_size; i++) {
   1331 		char num[100];
   1332 		snprintf(num, 100, "[%d]", i);
   1333 		audio_print_params(num, &vc->sc_rstreams[i].param);
   1334 	}
   1335 #endif /* AUDIO_DEBUG */
   1336 
   1337 	/* Destroy old filters. */
   1338 	mutex_exit(sc->sc_lock);
   1339 	for (i = 0; i < onfilters; i++) {
   1340 		of[i]->dtor(of[i]);
   1341 		audio_stream_dtor(&os[i]);
   1342 	}
   1343 	mutex_enter(sc->sc_lock);
   1344 
   1345 	return 0;
   1346 }
   1347 
   1348 static void
   1349 audio_stream_dtor(audio_stream_t *stream)
   1350 {
   1351 
   1352 	if (stream->start != NULL)
   1353 		kmem_free(stream->start, stream->bufsize);
   1354 	memset(stream, 0, sizeof(audio_stream_t));
   1355 }
   1356 
   1357 static int
   1358 audio_stream_ctor(audio_stream_t *stream, const audio_params_t *param, int size)
   1359 {
   1360 	int frame_size;
   1361 
   1362 	size = min(size, AU_RING_SIZE);
   1363 	stream->bufsize = size;
   1364 	stream->start = kmem_zalloc(size, KM_SLEEP);
   1365 	frame_size = (param->precision + 7) / 8 * param->channels;
   1366 	size = (size / frame_size) * frame_size;
   1367 	stream->end = stream->start + size;
   1368 	stream->inp = stream->start;
   1369 	stream->outp = stream->start;
   1370 	stream->used = 0;
   1371 	stream->param = *param;
   1372 	stream->loop = false;
   1373 	return 0;
   1374 }
   1375 
   1376 static void
   1377 stream_filter_list_append(stream_filter_list_t *list,
   1378 			  stream_filter_factory_t factory,
   1379 			  const audio_params_t *param)
   1380 {
   1381 
   1382 	if (list->req_size >= AUDIO_MAX_FILTERS) {
   1383 		printf("%s: increase AUDIO_MAX_FILTERS in sys/dev/audio_if.h\n",
   1384 		       __func__);
   1385 		return;
   1386 	}
   1387 	list->filters[list->req_size].factory = factory;
   1388 	list->filters[list->req_size].param = *param;
   1389 	list->req_size++;
   1390 }
   1391 
   1392 static void
   1393 stream_filter_list_set(stream_filter_list_t *list, int i,
   1394 		       stream_filter_factory_t factory,
   1395 		       const audio_params_t *param)
   1396 {
   1397 
   1398 	if (i < 0 || i >= AUDIO_MAX_FILTERS) {
   1399 		printf("%s: invalid index: %d\n", __func__, i);
   1400 		return;
   1401 	}
   1402 
   1403 	list->filters[i].factory = factory;
   1404 	list->filters[i].param = *param;
   1405 	if (list->req_size <= i)
   1406 		list->req_size = i + 1;
   1407 }
   1408 
   1409 static void
   1410 stream_filter_list_prepend(stream_filter_list_t *list,
   1411 			   stream_filter_factory_t factory,
   1412 			   const audio_params_t *param)
   1413 {
   1414 
   1415 	if (list->req_size >= AUDIO_MAX_FILTERS) {
   1416 		printf("%s: increase AUDIO_MAX_FILTERS in sys/dev/audio_if.h\n",
   1417 		       __func__);
   1418 		return;
   1419 	}
   1420 	memmove(&list->filters[1], &list->filters[0],
   1421 		sizeof(struct stream_filter_req) * list->req_size);
   1422 	list->filters[0].factory = factory;
   1423 	list->filters[0].param = *param;
   1424 	list->req_size++;
   1425 }
   1426 
   1427 /*
   1428  * Look up audio device and acquire locks for device access.
   1429  */
   1430 static int
   1431 audio_enter(dev_t dev, krw_t rw, struct audio_softc **scp)
   1432 {
   1433 
   1434 	struct audio_softc *sc;
   1435 
   1436 	/* First, find the device and take sc_lock. */
   1437 	sc = device_lookup_private(&audio_cd, AUDIOUNIT(dev));
   1438 	if (sc == NULL || sc->hw_if == NULL)
   1439 		return ENXIO;
   1440 	mutex_enter(sc->sc_lock);
   1441 	if (sc->sc_dying) {
   1442 		mutex_exit(sc->sc_lock);
   1443 		return EIO;
   1444 	}
   1445 
   1446 	*scp = sc;
   1447 	return 0;
   1448 }
   1449 
   1450 /*
   1451  * Release reference to device acquired with audio_enter().
   1452  */
   1453 static void
   1454 audio_exit(struct audio_softc *sc)
   1455 {
   1456 	cv_broadcast(&sc->sc_lchan);
   1457 	mutex_exit(sc->sc_lock);
   1458 }
   1459 
   1460 /*
   1461  * Wait for I/O to complete, releasing device lock.
   1462  */
   1463 static int
   1464 audio_waitio(struct audio_softc *sc, kcondvar_t *chan)
   1465 {
   1466 	int error;
   1467 
   1468 	KASSERT(mutex_owned(sc->sc_lock));
   1469 	cv_broadcast(&sc->sc_lchan);
   1470 
   1471 	/* Wait for pending I/O to complete. */
   1472 	error = cv_wait_sig(chan, sc->sc_lock);
   1473 
   1474 	return error;
   1475 }
   1476 
   1477 int
   1478 audioopen(dev_t dev, int flags, int ifmt, struct lwp *l)
   1479 {
   1480 	struct audio_softc *sc;
   1481 	int error;
   1482 
   1483 	if ((error = audio_enter(dev, RW_WRITER, &sc)) != 0)
   1484 		return error;
   1485 	device_active(sc->dev, DVA_SYSTEM);
   1486 	switch (AUDIODEV(dev)) {
   1487 	case SOUND_DEVICE:
   1488 	case AUDIO_DEVICE:
   1489 	case AUDIOCTL_DEVICE:
   1490 		error = audio_open(dev, sc, flags, ifmt, l);
   1491 		break;
   1492 	case MIXER_DEVICE:
   1493 		error = mixer_open(dev, sc, flags, ifmt, l);
   1494 		break;
   1495 	default:
   1496 		error = ENXIO;
   1497 		break;
   1498 	}
   1499 	audio_exit(sc);
   1500 
   1501 	return error;
   1502 }
   1503 
   1504 int
   1505 audioclose(dev_t dev, int flags, int ifmt, struct lwp *l)
   1506 {
   1507 	struct audio_softc *sc;
   1508 	int error, n;
   1509 
   1510 	if ((error = audio_enter(dev, RW_WRITER, &sc)) != 0)
   1511 		return error;
   1512 	device_active(sc->dev, DVA_SYSTEM);
   1513 	switch (AUDIODEV(dev)) {
   1514 	case SOUND_DEVICE:
   1515 	case AUDIO_DEVICE:
   1516 	case AUDIOCTL_DEVICE:
   1517 		for (n = 1; n < VAUDIOCHANS; n++) {
   1518 			if (sc->sc_audiopid[n].pid == curproc->p_pid)
   1519 				break;
   1520 		}
   1521 		if (n == VAUDIOCHANS) {
   1522 			error = EIO;
   1523 			break;
   1524 		}
   1525 		error = audio_close(sc, flags, ifmt, l, n);
   1526 		break;
   1527 	case MIXER_DEVICE:
   1528 		error = mixer_close(sc, flags, ifmt, l);
   1529 		break;
   1530 	default:
   1531 		error = ENXIO;
   1532 		break;
   1533 	}
   1534 	audio_exit(sc);
   1535 
   1536 	return error;
   1537 }
   1538 
   1539 int
   1540 audioread(dev_t dev, struct uio *uio, int ioflag)
   1541 {
   1542 	struct audio_softc *sc;
   1543 	int error;
   1544 
   1545 	if ((error = audio_enter(dev, RW_READER, &sc)) != 0)
   1546 		return error;
   1547 	switch (AUDIODEV(dev)) {
   1548 	case SOUND_DEVICE:
   1549 	case AUDIO_DEVICE:
   1550 		error = audio_read(sc, uio, ioflag);
   1551 		break;
   1552 	case AUDIOCTL_DEVICE:
   1553 	case MIXER_DEVICE:
   1554 		error = ENODEV;
   1555 		break;
   1556 	default:
   1557 		error = ENXIO;
   1558 		break;
   1559 	}
   1560 	audio_exit(sc);
   1561 
   1562 	return error;
   1563 }
   1564 
   1565 int
   1566 audiowrite(dev_t dev, struct uio *uio, int ioflag)
   1567 {
   1568 	struct audio_softc *sc;
   1569 	int error;
   1570 
   1571 	if ((error = audio_enter(dev, RW_READER, &sc)) != 0)
   1572 		return error;
   1573 	switch (AUDIODEV(dev)) {
   1574 	case SOUND_DEVICE:
   1575 	case AUDIO_DEVICE:
   1576 		error = audio_write(sc, uio, ioflag);
   1577 		break;
   1578 	case AUDIOCTL_DEVICE:
   1579 	case MIXER_DEVICE:
   1580 		error = ENODEV;
   1581 		break;
   1582 	default:
   1583 		error = ENXIO;
   1584 		break;
   1585 	}
   1586 	audio_exit(sc);
   1587 
   1588 	return error;
   1589 }
   1590 
   1591 int
   1592 audioioctl(dev_t dev, u_long cmd, void *addr, int flag, struct lwp *l)
   1593 {
   1594 	struct audio_softc *sc;
   1595 	int error;
   1596 	krw_t rw;
   1597 
   1598 	/* Figure out which lock type we need. */
   1599 	switch (cmd) {
   1600 	case AUDIO_FLUSH:
   1601 	case AUDIO_SETINFO:
   1602 	case AUDIO_DRAIN:
   1603 	case AUDIO_SETFD:
   1604 		rw = RW_WRITER;
   1605 		break;
   1606 	default:
   1607 		rw = RW_READER;
   1608 		break;
   1609 	}
   1610 
   1611 	if ((error = audio_enter(dev, rw, &sc)) != 0)
   1612 		return error;
   1613 	switch (AUDIODEV(dev)) {
   1614 	case SOUND_DEVICE:
   1615 	case AUDIO_DEVICE:
   1616 	case AUDIOCTL_DEVICE:
   1617 		device_active(sc->dev, DVA_SYSTEM);
   1618 		if (IOCGROUP(cmd) == IOCGROUP(AUDIO_MIXER_READ))
   1619 			error = mixer_ioctl(sc, cmd, addr, flag, l);
   1620 		else
   1621 			error = audio_ioctl(dev, sc, cmd, addr, flag, l);
   1622 		break;
   1623 	case MIXER_DEVICE:
   1624 		error = mixer_ioctl(sc, cmd, addr, flag, l);
   1625 		break;
   1626 	default:
   1627 		error = ENXIO;
   1628 		break;
   1629 	}
   1630 	audio_exit(sc);
   1631 
   1632 	return error;
   1633 }
   1634 
   1635 int
   1636 audiopoll(dev_t dev, int events, struct lwp *l)
   1637 {
   1638 	struct audio_softc *sc;
   1639 	int revents;
   1640 
   1641 	/* Don't bother with device level lock here. */
   1642 	sc = device_lookup_private(&audio_cd, AUDIOUNIT(dev));
   1643 	if (sc == NULL)
   1644 		return ENXIO;
   1645 	mutex_enter(sc->sc_lock);
   1646 	if (sc->sc_dying) {
   1647 		mutex_exit(sc->sc_lock);
   1648 		return EIO;
   1649 	}
   1650 	switch (AUDIODEV(dev)) {
   1651 	case SOUND_DEVICE:
   1652 	case AUDIO_DEVICE:
   1653 		revents = audio_poll(sc, events, l);
   1654 		break;
   1655 	case AUDIOCTL_DEVICE:
   1656 	case MIXER_DEVICE:
   1657 		revents = 0;
   1658 		break;
   1659 	default:
   1660 		revents = POLLERR;
   1661 		break;
   1662 	}
   1663 	mutex_exit(sc->sc_lock);
   1664 
   1665 	return revents;
   1666 }
   1667 
   1668 int
   1669 audiokqfilter(dev_t dev, struct knote *kn)
   1670 {
   1671 	struct audio_softc *sc;
   1672 	int rv;
   1673 
   1674 	/* Don't bother with device level lock here. */
   1675 	sc = device_lookup_private(&audio_cd, AUDIOUNIT(dev));
   1676 	if (sc == NULL)
   1677 		return ENXIO;
   1678 	mutex_enter(sc->sc_lock);
   1679 	if (sc->sc_dying) {
   1680 		mutex_exit(sc->sc_lock);
   1681 		return EIO;
   1682 	}
   1683 	switch (AUDIODEV(dev)) {
   1684 	case SOUND_DEVICE:
   1685 	case AUDIO_DEVICE:
   1686 		rv = audio_kqfilter(sc, kn);
   1687 		break;
   1688 	case AUDIOCTL_DEVICE:
   1689 	case MIXER_DEVICE:
   1690 		rv = 1;
   1691 		break;
   1692 	default:
   1693 		rv = 1;
   1694 	}
   1695 	mutex_exit(sc->sc_lock);
   1696 
   1697 	return rv;
   1698 }
   1699 
   1700 paddr_t
   1701 audiommap(dev_t dev, off_t off, int prot)
   1702 {
   1703 	struct audio_softc *sc;
   1704 	paddr_t error;
   1705 
   1706 	/*
   1707 	 * Acquire a reader lock.  audio_mmap() will drop sc_lock
   1708 	 * in order to allow the device's mmap routine to sleep.
   1709 	 * Although not yet possible, we want to prevent memory
   1710 	 * from being allocated or freed out from under us.
   1711 	 */
   1712 	if ((error = audio_enter(dev, RW_READER, &sc)) != 0)
   1713 		return 1;
   1714 	device_active(sc->dev, DVA_SYSTEM); /* XXXJDM */
   1715 	switch (AUDIODEV(dev)) {
   1716 	case SOUND_DEVICE:
   1717 	case AUDIO_DEVICE:
   1718 		error = audio_mmap(sc, off, prot);
   1719 		break;
   1720 	case AUDIOCTL_DEVICE:
   1721 	case MIXER_DEVICE:
   1722 		error = -1;
   1723 		break;
   1724 	default:
   1725 		error = -1;
   1726 		break;
   1727 	}
   1728 	audio_exit(sc);
   1729 	return error;
   1730 }
   1731 
   1732 /*
   1733  * Audio driver
   1734  */
   1735 void
   1736 audio_init_ringbuffer(struct audio_softc *sc, struct audio_ringbuffer *rp,
   1737 		      int mode)
   1738 {
   1739 	int nblks;
   1740 	int blksize;
   1741 
   1742 	blksize = rp->blksize;
   1743 	if (blksize < AUMINBLK)
   1744 		blksize = AUMINBLK;
   1745 	if (blksize > rp->s.bufsize / AUMINNOBLK)
   1746 		blksize = rp->s.bufsize / AUMINNOBLK;
   1747 	ROUNDSIZE(blksize);
   1748 	DPRINTF(("audio_init_ringbuffer: MI blksize=%d\n", blksize));
   1749 	if (sc->hw_if->round_blocksize)
   1750 		blksize = sc->hw_if->round_blocksize(sc->hw_hdl, blksize,
   1751 						     mode, &rp->s.param);
   1752 	if (blksize <= 0)
   1753 		panic("audio_init_ringbuffer: blksize=%d", blksize);
   1754 	nblks = rp->s.bufsize / blksize;
   1755 
   1756 	DPRINTF(("audio_init_ringbuffer: final blksize=%d\n", blksize));
   1757 	rp->blksize = blksize;
   1758 	rp->maxblks = nblks;
   1759 	rp->s.end = rp->s.start + nblks * blksize;
   1760 	rp->s.outp = rp->s.inp = rp->s.start;
   1761 	rp->s.used = 0;
   1762 	rp->stamp = 0;
   1763 	rp->stamp_last = 0;
   1764 	rp->fstamp = 0;
   1765 	rp->drops = 0;
   1766 	rp->copying = false;
   1767 	rp->needfill = false;
   1768 	rp->mmapped = false;
   1769 	memset(rp->s.start, 0, blksize * 2);
   1770 }
   1771 
   1772 int
   1773 audio_initbufs(struct audio_softc *sc, int n)
   1774 {
   1775 	const struct audio_hw_if *hw;
   1776 	struct virtual_channel *vc;
   1777 	int error;
   1778 
   1779 	DPRINTF(("audio_initbufs: mode=0x%x\n", sc->sc_vchan[n]->sc_mode));
   1780 	vc = sc->sc_vchan[0];
   1781 	hw = sc->hw_if;
   1782 	if ((audio_can_capture(sc) && n == 0) ||
   1783 	    (sc->sc_vchan[n]->sc_open & AUOPEN_READ)) {
   1784 		audio_init_ringbuffer(sc, &sc->sc_vchan[n]->sc_mrr,
   1785 		    AUMODE_RECORD);
   1786 		if (sc->sc_opens == 0 && hw->init_input &&
   1787 		    (sc->sc_vchan[n]->sc_mode & AUMODE_RECORD)) {
   1788 			error = hw->init_input(sc->hw_hdl, vc->sc_mrr.s.start,
   1789 				       vc->sc_mrr.s.end - vc->sc_mrr.s.start);
   1790 			if (error)
   1791 				return error;
   1792 		}
   1793 	}
   1794 
   1795 	if ((audio_can_playback(sc) && n == 0) ||
   1796 	    (sc->sc_vchan[n]->sc_open & AUOPEN_WRITE)) {
   1797 		audio_init_ringbuffer(sc, &sc->sc_vchan[n]->sc_mpr,
   1798 		    AUMODE_PLAY);
   1799 		sc->sc_vchan[n]->sc_sil_count = 0;
   1800 		if (sc->sc_opens == 0 && hw->init_output &&
   1801 		    (sc->sc_vchan[n]->sc_mode & AUMODE_PLAY)) {
   1802 			error = hw->init_output(sc->hw_hdl, vc->sc_mpr.s.start,
   1803 					vc->sc_mpr.s.end - vc->sc_mpr.s.start);
   1804 			if (error)
   1805 				return error;
   1806 		}
   1807 	}
   1808 
   1809 #ifdef AUDIO_INTR_TIME
   1810 #define double u_long
   1811 	if (audio_can_playback(sc)) {
   1812 		sc->sc_pnintr = 0;
   1813 		sc->sc_pblktime = (u_long)(
   1814 		    (double)sc->sc_vchan[n]->sc_mpr.blksize * 100000 /
   1815 		    (double)(sc->sc_vchan[n]->sc_pparams.precision / NBBY *
   1816 			     sc->sc_vchan[n].sc_pparams.channels *
   1817 			     sc->sc_vchan[n].sc_pparams.sample_rate)) * 10;
   1818 		DPRINTF(("audio: play blktime = %lu for %d\n",
   1819 			 sc->sc_pblktime, sc->sc_vchan[n].sc_mpr.blksize));
   1820 	}
   1821 	if (audio_can_capture(sc)) {
   1822 		sc->sc_rnintr = 0;
   1823 		sc->sc_rblktime = (u_long)(
   1824 		    (double)sc->sc_vchan[n]->sc_mrr.blksize * 100000 /
   1825 		    (double)(sc->sc_vchan[n]->sc_rparams.precision / NBBY *
   1826 			     sc->sc_vchan[n]->sc_rparams.channels *
   1827 			     sc->sc_vchan[n]->sc_rparams.sample_rate)) * 10;
   1828 		DPRINTF(("audio: record blktime = %lu for %d\n",
   1829 			 sc->sc_rblktime, sc->sc_vchan[n]->sc_mrr.blksize));
   1830 	}
   1831 #undef double
   1832 #endif
   1833 
   1834 	return 0;
   1835 }
   1836 
   1837 void
   1838 audio_calcwater(struct audio_softc *sc, int n)
   1839 {
   1840 	struct virtual_channel *vc = sc->sc_vchan[n];
   1841 
   1842 	/* set high at 100% */
   1843 	if (audio_can_playback(sc) && vc && vc->sc_pustream) {
   1844 		vc->sc_mpr.usedhigh =
   1845 		    vc->sc_pustream->end - vc->sc_pustream->start;
   1846 		/* set low at 75% of usedhigh */
   1847 		vc->sc_mpr.usedlow = vc->sc_mpr.usedhigh * 3 / 4;
   1848 		if (vc->sc_mpr.usedlow == vc->sc_mpr.usedhigh)
   1849 			vc->sc_mpr.usedlow -= vc->sc_mpr.blksize;
   1850 	}
   1851 
   1852 	if (audio_can_capture(sc) && vc && vc->sc_rustream) {
   1853 		vc->sc_mrr.usedhigh =
   1854 		    vc->sc_rustream->end - vc->sc_rustream->start -
   1855 		    vc->sc_mrr.blksize;
   1856 		vc->sc_mrr.usedlow = 0;
   1857 		DPRINTF(("%s: plow=%d phigh=%d rlow=%d rhigh=%d\n", __func__,
   1858 			 vc->sc_mpr.usedlow, vc->sc_mpr.usedhigh,
   1859 			 vc->sc_mrr.usedlow, vc->sc_mrr.usedhigh));
   1860 	}
   1861 }
   1862 
   1863 int
   1864 audio_open(dev_t dev, struct audio_softc *sc, int flags, int ifmt,
   1865     struct lwp *l)
   1866 {
   1867 	int error, i, n;
   1868 	u_int mode;
   1869 	const struct audio_hw_if *hw;
   1870 	struct virtual_channel *vc;
   1871 
   1872 	KASSERT(mutex_owned(sc->sc_lock));
   1873 
   1874 	if (sc->sc_ready == false || sc->sc_opens >= VAUDIOCHANS)
   1875 		return ENXIO;
   1876 
   1877 	for (n = 1; n < VAUDIOCHANS; n++) {
   1878 		if (sc->sc_audiopid[n].pid == curproc->p_pid)
   1879 			break;
   1880 	}
   1881 	if (n < VAUDIOCHANS)
   1882 		return ENXIO;
   1883 
   1884 	for (n = 1; n < VAUDIOCHANS; n++) {
   1885 		if (sc->sc_audiopid[n].pid == -1)
   1886 			break;
   1887 	}
   1888 	if (n == VAUDIOCHANS)
   1889 		return ENXIO;
   1890 
   1891 	hw = sc->hw_if;
   1892 	if (hw == NULL)
   1893 		return ENXIO;
   1894 
   1895 	sc->sc_vchan[n] = kmem_zalloc(sizeof(struct virtual_channel), KM_SLEEP);
   1896 	vc = sc->sc_vchan[n];
   1897 
   1898 	vc->sc_open = 0;
   1899 	vc->sc_mode = 0;
   1900 	vc->sc_sil_count = 0;
   1901 	vc->sc_nrfilters = 0;
   1902 	memset(vc->sc_rfilters, 0,
   1903 	    sizeof(vc->sc_rfilters));
   1904 	vc->sc_rbus = false;
   1905 	vc->sc_npfilters = 0;
   1906 	memset(vc->sc_pfilters, 0,
   1907 	    sizeof(vc->sc_pfilters));
   1908 	vc->sc_draining = false;
   1909 	vc->sc_pbus = false;
   1910 	vc->sc_blkset = false;
   1911 	vc->sc_lastinfovalid = false;
   1912 	vc->sc_swvol = 255;
   1913 	vc->sc_recswvol = 255;
   1914 
   1915 	DPRINTF(("audio_open: flags=0x%x sc=%p hdl=%p\n",
   1916 		 flags, sc, sc->hw_hdl));
   1917 
   1918 	if (((flags & FREAD) && (vc->sc_open & AUOPEN_READ)) ||
   1919 	    ((flags & FWRITE) && (vc->sc_open & AUOPEN_WRITE))) {
   1920 		kmem_free(vc, sizeof(struct virtual_channel));
   1921 		return EBUSY;
   1922 	}
   1923 
   1924 	error = audio_alloc_ring(sc, &vc->sc_mpr,
   1925 	    	    AUMODE_PLAY, AU_RING_SIZE);
   1926 	if (!error) {
   1927 		error = audio_alloc_ring(sc, &vc->sc_mrr,
   1928 	    	    AUMODE_RECORD, AU_RING_SIZE);
   1929 	}
   1930 	if (error) {
   1931 		kmem_free(vc, sizeof(struct virtual_channel));
   1932 		return error;
   1933 	}
   1934 
   1935 	if (sc->sc_opens == 0) {
   1936 		if (hw->open != NULL) {
   1937 			mutex_enter(sc->sc_intr_lock);
   1938 			error = hw->open(sc->hw_hdl, flags);
   1939 			mutex_exit(sc->sc_intr_lock);
   1940 			if (error) {
   1941 				kmem_free(vc,
   1942 				    sizeof(struct virtual_channel));
   1943 				return error;
   1944 			}
   1945 		}
   1946 		audio_init_ringbuffer(sc, &sc->sc_pr, AUMODE_PLAY);
   1947 		audio_init_ringbuffer(sc, &sc->sc_rr, AUMODE_RECORD);
   1948 		audio_initbufs(sc, 0);
   1949 		sc->schedule_wih = false;
   1950 		sc->schedule_rih = false;
   1951 		sc->sc_eof = 0;
   1952 		vc->sc_rbus = false;
   1953 		sc->sc_async_audio = 0;
   1954 	}
   1955 
   1956 	mutex_enter(sc->sc_intr_lock);
   1957 	vc->sc_full_duplex =
   1958 		(flags & (FWRITE|FREAD)) == (FWRITE|FREAD) &&
   1959 		(audio_get_props(sc) & AUDIO_PROP_FULLDUPLEX);
   1960 	mutex_exit(sc->sc_intr_lock);
   1961 
   1962 	mode = 0;
   1963 	if (flags & FREAD) {
   1964 		vc->sc_open |= AUOPEN_READ;
   1965 		mode |= AUMODE_RECORD;
   1966 	}
   1967 	if (flags & FWRITE) {
   1968 		vc->sc_open |= AUOPEN_WRITE;
   1969 		mode |= AUMODE_PLAY | AUMODE_PLAY_ALL;
   1970 	}
   1971 
   1972 	/*
   1973 	 * Multiplex device: /dev/audio (MU-Law) and /dev/sound (linear)
   1974 	 * The /dev/audio is always (re)set to 8-bit MU-Law mono
   1975 	 * For the other devices, you get what they were last set to.
   1976 	 */
   1977 	error = audio_set_defaults(sc, mode, n);
   1978 	if (!error && ISDEVSOUND(dev) && sc->sc_aivalid == true) {
   1979 		sc->sc_ai.mode = mode;
   1980 		error = audiosetinfo(sc, &sc->sc_ai, true, n);
   1981 	}
   1982 	if (error)
   1983 		goto bad;
   1984 	vc->sc_mrr.blksize = sc->sc_vchan[0]->sc_mrr.blksize;
   1985 	vc->sc_mpr.blksize = sc->sc_vchan[0]->sc_mpr.blksize;
   1986 
   1987 #ifdef DIAGNOSTIC
   1988 	/*
   1989 	 * Sample rate and precision are supposed to be set to proper
   1990 	 * default values by the hardware driver, so that it may give
   1991 	 * us these values.
   1992 	 */
   1993 	if (vc->sc_rparams.precision == 0 || vc->sc_pparams.precision == 0) {
   1994 		printf("audio_open: 0 precision\n");
   1995 		goto bad;
   1996 	}
   1997 #endif
   1998 
   1999 	/* audio_close() decreases sc_mpr[n].usedlow, recalculate here */
   2000 	audio_calcwater(sc, n);
   2001 
   2002 	DPRINTF(("audio_open: done sc_mode = 0x%x\n", vc->sc_mode));
   2003 
   2004 	mutex_enter(sc->sc_intr_lock);
   2005 	if (flags & FREAD)
   2006 		sc->sc_recopens++;
   2007 	sc->sc_opens++;
   2008 	sc->sc_audiopid[n].pid = curproc->p_pid;
   2009 	sc->sc_despid[n].pid = curproc->p_pid;
   2010 	sc->sc_nmixer_states += 2;
   2011 	mutex_exit(sc->sc_intr_lock);
   2012 
   2013 	return 0;
   2014 
   2015 bad:
   2016 	for (i = 0; i < vc->sc_npfilters; i++) {
   2017 		vc->sc_pfilters[i]->dtor(vc->sc_pfilters[i]);
   2018 		vc->sc_pfilters[i] = NULL;
   2019 		audio_stream_dtor(&vc->sc_pstreams[i]);
   2020 	}
   2021 	vc->sc_npfilters = 0;
   2022 	for (i = 0; i < vc->sc_nrfilters; i++) {
   2023 		vc->sc_rfilters[i]->dtor(vc->sc_rfilters[i]);
   2024 		vc->sc_rfilters[i] = NULL;
   2025 		audio_stream_dtor(&vc->sc_rstreams[i]);
   2026 	}
   2027 	vc->sc_nrfilters = 0;
   2028 	if (hw->close != NULL && sc->sc_opens == 0)
   2029 		hw->close(sc->hw_hdl);
   2030 	mutex_exit(sc->sc_lock);
   2031 	audio_free_ring(sc, &vc->sc_mpr);
   2032 	audio_free_ring(sc, &vc->sc_mrr);
   2033 	mutex_enter(sc->sc_lock);
   2034 	kmem_free(sc->sc_vchan[n], sizeof(struct virtual_channel));
   2035 	return error;
   2036 }
   2037 
   2038 /*
   2039  * Must be called from task context.
   2040  */
   2041 void
   2042 audio_init_record(struct audio_softc *sc, int n)
   2043 {
   2044 
   2045 	KASSERT(mutex_owned(sc->sc_lock));
   2046 
   2047 	struct virtual_channel *vc = sc->sc_vchan[n];
   2048 
   2049 	if (sc->sc_opens != 0)
   2050 		return;
   2051 
   2052 	mutex_enter(sc->sc_intr_lock);
   2053 	if (sc->hw_if->speaker_ctl &&
   2054 	    (!vc->sc_full_duplex || (vc->sc_mode & AUMODE_PLAY) == 0))
   2055 		sc->hw_if->speaker_ctl(sc->hw_hdl, SPKR_OFF);
   2056 	mutex_exit(sc->sc_intr_lock);
   2057 }
   2058 
   2059 /*
   2060  * Must be called from task context.
   2061  */
   2062 void
   2063 audio_init_play(struct audio_softc *sc, int n)
   2064 {
   2065 
   2066 	KASSERT(mutex_owned(sc->sc_lock));
   2067 
   2068 	if (sc->sc_opens != 0)
   2069 		return;
   2070 
   2071 	mutex_enter(sc->sc_intr_lock);
   2072 	sc->sc_vchan[n]->sc_wstamp = sc->sc_vchan[n]->sc_mpr.stamp;
   2073 	if (sc->hw_if->speaker_ctl)
   2074 		sc->hw_if->speaker_ctl(sc->hw_hdl, SPKR_ON);
   2075 	mutex_exit(sc->sc_intr_lock);
   2076 }
   2077 
   2078 int
   2079 audio_drain(struct audio_softc *sc, int n)
   2080 {
   2081 	struct audio_ringbuffer *cb;
   2082 	int error, drops;
   2083 	int cc, i, used;
   2084 
   2085 	KASSERT(mutex_owned(sc->sc_lock));
   2086 	KASSERT(mutex_owned(sc->sc_intr_lock));
   2087 
   2088 	error = 0;
   2089 	DPRINTF(("audio_drain: enter busy=%d\n", sc->sc_vchan[n]->sc_pbus));
   2090 	cb = &sc->sc_vchan[n]->sc_mpr;
   2091 	if (cb->mmapped)
   2092 		return 0;
   2093 
   2094 	used = audio_stream_get_used(&cb->s);
   2095 	for (i = 0; i < sc->sc_vchan[n]->sc_npfilters; i++)
   2096 		used += audio_stream_get_used(&sc->sc_vchan[n]->sc_pstreams[i]);
   2097 	if (used <= 0)
   2098 		return 0;
   2099 
   2100 	if (n != 0 && !sc->sc_vchan[n]->sc_pbus) {
   2101 		/* We've never started playing, probably because the
   2102 		 * block was too short.  Pad it and start now.
   2103 		 */
   2104 		uint8_t *inp = cb->s.inp;
   2105 
   2106 		cc = cb->blksize - (inp - cb->s.start) % cb->blksize;
   2107 		audio_fill_silence(&cb->s.param, inp, cc);
   2108 		cb->s.inp = audio_stream_add_inp(&cb->s, inp, cc);
   2109 		error = audiostartp(sc, n);
   2110 		if (error)
   2111 			return error;
   2112 	} else if (n == 0)
   2113 		goto silence_buffer;
   2114 	/*
   2115 	 * Play until a silence block has been played, then we
   2116 	 * know all has been drained.
   2117 	 * XXX This should be done some other way to avoid
   2118 	 * playing silence.
   2119 	 */
   2120 #ifdef DIAGNOSTIC
   2121 	if (cb->copying) {
   2122 		DPRINTF(("audio_drain: copying in progress!?!\n"));
   2123 		cb->copying = false;
   2124 	}
   2125 #endif
   2126 	sc->sc_vchan[n]->sc_draining = true;
   2127 	drops = cb->drops;
   2128 	error = 0;
   2129 	while (cb->drops == drops && !error) {
   2130 		DPRINTF(("audio_drain: n=%d, used=%d, drops=%ld\n", n,
   2131 			audio_stream_get_used(&sc->sc_vchan[n]->sc_mpr.s),
   2132 			cb->drops));
   2133 		mutex_exit(sc->sc_intr_lock);
   2134 		error = audio_waitio(sc, &sc->sc_wchan);
   2135 		mutex_enter(sc->sc_intr_lock);
   2136 		if (sc->sc_dying)
   2137 			error = EIO;
   2138 	}
   2139 
   2140 silence_buffer:
   2141 
   2142 	used = 0;
   2143 	if (sc->sc_opens == 1) {
   2144 		cb = &sc->sc_pr;
   2145 		cc = cb->blksize;
   2146 
   2147 		while (used < cb->s.bufsize) {
   2148 			memset(sc->sc_pr.s.start, 0, cc);
   2149 			mix_write(sc);
   2150 			used += cc;
   2151 		}
   2152 	}
   2153 	sc->sc_vchan[n]->sc_draining = false;
   2154 	return error;
   2155 }
   2156 
   2157 /*
   2158  * Close an audio chip.
   2159  */
   2160 /* ARGSUSED */
   2161 int
   2162 audio_close(struct audio_softc *sc, int flags, int ifmt,
   2163     struct lwp *l, int n)
   2164 {
   2165 	struct virtual_channel *vc;
   2166 	const struct audio_hw_if *hw;
   2167 	int o;
   2168 
   2169 	KASSERT(mutex_owned(sc->sc_lock));
   2170 
   2171 	if (sc->sc_opens == 0 || n == 0)
   2172 		return ENXIO;
   2173 
   2174 	vc = sc->sc_vchan[n];
   2175 
   2176 	hw = sc->hw_if;
   2177 	if (hw == NULL)
   2178 		return ENXIO;
   2179 	mutex_enter(sc->sc_intr_lock);
   2180 	DPRINTF(("audio_close: sc=%p\n", sc));
   2181 	/* Stop recording. */
   2182 	if (sc->sc_recopens == 1 && (flags & FREAD) && vc->sc_rbus) {
   2183 		/*
   2184 		 * XXX Some drivers (e.g. SB) use the same routine
   2185 		 * to halt input and output so don't halt input if
   2186 		 * in full duplex mode.  These drivers should be fixed.
   2187 		 */
   2188 		if (!vc->sc_full_duplex || hw->halt_input != hw->halt_output)
   2189 			hw->halt_input(sc->hw_hdl);
   2190 		vc->sc_rbus = false;
   2191 	}
   2192 	/*
   2193 	 * Block until output drains, but allow ^C interrupt.
   2194 	 */
   2195 	vc->sc_mpr.usedlow = vc->sc_mpr.blksize;  /* avoid excessive wakeups */
   2196 	/*
   2197 	 * If there is pending output, let it drain (unless
   2198 	 * the output is paused).
   2199 	 */
   2200 	if ((flags & FWRITE) && vc->sc_pbus) {
   2201 		if (!vc->sc_mpr.pause)
   2202 			audio_drain(sc, n);
   2203 		vc->sc_pbus = false;
   2204 	}
   2205 	if (sc->sc_opens == 1) {
   2206 		audio_drain(sc, 0);
   2207 		if (hw->drain)
   2208 			(void)hw->drain(sc->hw_hdl);
   2209 		hw->halt_output(sc->hw_hdl);
   2210 		sc->sc_trigger_started = false;
   2211 	}
   2212 	if ((flags & FREAD) && (sc->sc_recopens == 1))
   2213 		sc->sc_rec_started = false;
   2214 
   2215 	if (sc->sc_opens == 1 && hw->close != NULL)
   2216 		hw->close(sc->hw_hdl);
   2217 	if (sc->sc_opens == 1)
   2218 		sc->sc_async_audio = 0;
   2219 
   2220 	vc->sc_open = 0;
   2221 	vc->sc_mode = 0;
   2222 	vc->sc_full_duplex = 0;
   2223 
   2224 	for (o = 0; o < vc->sc_npfilters; o++) {
   2225 		vc->sc_pfilters[o]->dtor(vc->sc_pfilters[o]);
   2226 		vc->sc_pfilters[o] = NULL;
   2227 		audio_stream_dtor(&vc->sc_pstreams[o]);
   2228 	}
   2229 	vc->sc_npfilters = 0;
   2230 	for (o = 0; o < vc->sc_nrfilters; o++) {
   2231 		vc->sc_rfilters[o]->dtor(vc->sc_rfilters[o]);
   2232 		vc->sc_rfilters[o] = NULL;
   2233 		audio_stream_dtor(&vc->sc_rstreams[o]);
   2234 	}
   2235 	vc->sc_nrfilters = 0;
   2236 
   2237 	if (flags & FREAD)
   2238 		sc->sc_recopens--;
   2239 	sc->sc_opens--;
   2240 	sc->sc_nmixer_states -= 2;
   2241 	sc->sc_audiopid[n].pid = -1;
   2242 	sc->sc_despid[n].pid = -1;
   2243 	mutex_exit(sc->sc_intr_lock);
   2244 	mutex_exit(sc->sc_lock);
   2245 	audio_free_ring(sc, &vc->sc_mpr);
   2246 	audio_free_ring(sc, &vc->sc_mrr);
   2247 	mutex_enter(sc->sc_lock);
   2248 	kmem_free(sc->sc_vchan[n], sizeof(struct virtual_channel));
   2249 
   2250 	return 0;
   2251 }
   2252 
   2253 int
   2254 audio_read(struct audio_softc *sc, struct uio *uio, int ioflag)
   2255 {
   2256 	struct audio_ringbuffer *cb;
   2257 	struct virtual_channel *vc;
   2258 	const uint8_t *outp;
   2259 	uint8_t *inp;
   2260 	int error, used, cc, n, m;
   2261 
   2262 	KASSERT(mutex_owned(sc->sc_lock));
   2263 
   2264 	for (m = 1; m < VAUDIOCHANS; m++) {
   2265 		if (sc->sc_audiopid[m].pid == curproc->p_pid)
   2266 			break;
   2267 	}
   2268 	if (m == VAUDIOCHANS)
   2269 		return EINVAL;
   2270 
   2271 	if (sc->hw_if == NULL)
   2272 		return ENXIO;
   2273 	vc = sc->sc_vchan[m];
   2274 
   2275 	cb = &vc->sc_mrr;
   2276 	if (cb->mmapped)
   2277 		return EINVAL;
   2278 
   2279 	DPRINTFN(1,("audio_read: cc=%zu mode=%d\n",
   2280 		    uio->uio_resid, vc->sc_mode));
   2281 
   2282 #ifdef AUDIO_PM_IDLE
   2283 	if (device_is_active(&sc->dev) || sc->sc_idle)
   2284 		device_active(&sc->dev, DVA_SYSTEM);
   2285 #endif
   2286 
   2287 	error = 0;
   2288 	/*
   2289 	 * If hardware is half-duplex and currently playing, return
   2290 	 * silence blocks based on the number of blocks we have output.
   2291 	 */
   2292 	if (!vc->sc_full_duplex && (vc->sc_mode & AUMODE_PLAY)) {
   2293 		while (uio->uio_resid > 0 && !error) {
   2294 			for(;;) {
   2295 				/*
   2296 				 * No need to lock, as any wakeup will be
   2297 				 * held for us while holding sc_lock.
   2298 				 */
   2299 				cc = vc->sc_mpr.stamp - vc->sc_wstamp;
   2300 				if (cc > 0)
   2301 					break;
   2302 				DPRINTF(("audio_read: stamp=%lu, wstamp=%lu\n",
   2303 					 vc->sc_mpr.stamp, vc->sc_wstamp));
   2304 				if (ioflag & IO_NDELAY)
   2305 					return EWOULDBLOCK;
   2306 				error = audio_waitio(sc, &sc->sc_rchan);
   2307 				if (sc->sc_dying)
   2308 					error = EIO;
   2309 				if (error)
   2310 					return error;
   2311 			}
   2312 
   2313 			if (uio->uio_resid < cc)
   2314 				cc = uio->uio_resid;
   2315 			DPRINTFN(1,("audio_read: reading in write mode, "
   2316 				    "cc=%d\n", cc));
   2317 			error = audio_silence_copyout(sc, cc, uio);
   2318 			vc->sc_wstamp += cc;
   2319 		}
   2320 		return error;
   2321 	}
   2322 
   2323 	mutex_enter(sc->sc_intr_lock);
   2324 	while (uio->uio_resid > 0 && !error) {
   2325 		while ((used = audio_stream_get_used(vc->sc_rustream)) <= 0) {
   2326 			if (!vc->sc_rbus && !vc->sc_mrr.pause)
   2327 				error = audiostartr(sc, m);
   2328 			mutex_exit(sc->sc_intr_lock);
   2329 			if (error)
   2330 				return error;
   2331 			if (ioflag & IO_NDELAY)
   2332 				return EWOULDBLOCK;
   2333 			DPRINTFN(2, ("audio_read: sleep used=%d\n", used));
   2334 			error = audio_waitio(sc, &sc->sc_rchan);
   2335 			if (sc->sc_dying)
   2336 				error = EIO;
   2337 			if (error)
   2338 				return error;
   2339 			mutex_enter(sc->sc_intr_lock);
   2340 		}
   2341 
   2342 		outp = vc->sc_rustream->outp;
   2343 		inp = vc->sc_rustream->inp;
   2344 		cb->copying = true;
   2345 
   2346 		/*
   2347 		 * cc is the amount of data in the sc_rustream excluding
   2348 		 * wrapped data.  Note the tricky case of inp == outp, which
   2349 		 * must mean the buffer is full, not empty, because used > 0.
   2350 		 */
   2351 		cc = outp < inp ? inp - outp :vc->sc_rustream->end - outp;
   2352 		DPRINTFN(1,("audio_read: outp=%p, cc=%d\n", outp, cc));
   2353 
   2354 		n = uio->uio_resid;
   2355 		mutex_exit(sc->sc_intr_lock);
   2356 		mutex_exit(sc->sc_lock);
   2357 		error = uiomove(__UNCONST(outp), cc, uio);
   2358 		mutex_enter(sc->sc_lock);
   2359 		mutex_enter(sc->sc_intr_lock);
   2360 		n -= uio->uio_resid; /* number of bytes actually moved */
   2361 
   2362 		vc->sc_rustream->outp = audio_stream_add_outp
   2363 			(vc->sc_rustream, outp, n);
   2364 		cb->copying = false;
   2365 	}
   2366 	mutex_exit(sc->sc_intr_lock);
   2367 	return error;
   2368 }
   2369 
   2370 void
   2371 audio_clear(struct audio_softc *sc, int n)
   2372 {
   2373 
   2374 	struct virtual_channel *vc = sc->sc_vchan[n];
   2375 
   2376 	KASSERT(mutex_owned(sc->sc_intr_lock));
   2377 
   2378 	if (vc->sc_rbus) {
   2379 		cv_broadcast(&sc->sc_rchan);
   2380 		if (sc->sc_recopens == 1) {
   2381 			sc->hw_if->halt_input(sc->hw_hdl);
   2382 			sc->sc_rec_started = false;
   2383 		}
   2384 		vc->sc_rbus = false;
   2385 		vc->sc_mrr.pause = false;
   2386 	}
   2387 	if (vc->sc_pbus) {
   2388 		cv_broadcast(&sc->sc_wchan);
   2389 		vc->sc_pbus = false;
   2390 		vc->sc_mpr.pause = false;
   2391 	}
   2392 }
   2393 
   2394 void
   2395 audio_clear_intr_unlocked(struct audio_softc *sc, int n)
   2396 {
   2397 
   2398 	mutex_enter(sc->sc_intr_lock);
   2399 	audio_clear(sc, n);
   2400 	mutex_exit(sc->sc_intr_lock);
   2401 }
   2402 
   2403 void
   2404 audio_calc_blksize(struct audio_softc *sc, int mode, int n)
   2405 {
   2406 	const audio_params_t *parm;
   2407 	struct audio_ringbuffer *rb;
   2408 
   2409 	if (sc->sc_vchan[n]->sc_blkset)
   2410 		return;
   2411 
   2412 	if (mode == AUMODE_PLAY) {
   2413 		rb = &sc->sc_vchan[n]->sc_mpr;
   2414 		parm = &rb->s.param;
   2415 	} else {
   2416 		rb = &sc->sc_vchan[n]->sc_mrr;
   2417 		parm = &rb->s.param;
   2418 	}
   2419 
   2420 	rb->blksize = parm->sample_rate * audio_blk_ms / 1000 *
   2421 	     parm->channels * parm->precision / NBBY;
   2422 
   2423 	DPRINTF(("audio_calc_blksize: %s blksize=%d\n",
   2424 		 mode == AUMODE_PLAY ? "play" : "record", rb->blksize));
   2425 }
   2426 
   2427 void
   2428 audio_fill_silence(struct audio_params *params, uint8_t *p, int n)
   2429 {
   2430 	uint8_t auzero0, auzero1;
   2431 	int nfill;
   2432 
   2433 	auzero1 = 0;		/* initialize to please gcc */
   2434 	nfill = 1;
   2435 	switch (params->encoding) {
   2436 	case AUDIO_ENCODING_ULAW:
   2437 		auzero0 = 0x7f;
   2438 		break;
   2439 	case AUDIO_ENCODING_ALAW:
   2440 		auzero0 = 0x55;
   2441 		break;
   2442 	case AUDIO_ENCODING_MPEG_L1_STREAM:
   2443 	case AUDIO_ENCODING_MPEG_L1_PACKETS:
   2444 	case AUDIO_ENCODING_MPEG_L1_SYSTEM:
   2445 	case AUDIO_ENCODING_MPEG_L2_STREAM:
   2446 	case AUDIO_ENCODING_MPEG_L2_PACKETS:
   2447 	case AUDIO_ENCODING_MPEG_L2_SYSTEM:
   2448 	case AUDIO_ENCODING_AC3:
   2449 	case AUDIO_ENCODING_ADPCM: /* is this right XXX */
   2450 	case AUDIO_ENCODING_SLINEAR_LE:
   2451 	case AUDIO_ENCODING_SLINEAR_BE:
   2452 		auzero0 = 0;/* fortunately this works for any number of bits */
   2453 		break;
   2454 	case AUDIO_ENCODING_ULINEAR_LE:
   2455 	case AUDIO_ENCODING_ULINEAR_BE:
   2456 		if (params->precision > 8) {
   2457 			nfill = (params->precision + NBBY - 1)/ NBBY;
   2458 			auzero0 = 0x80;
   2459 			auzero1 = 0;
   2460 		} else
   2461 			auzero0 = 0x80;
   2462 		break;
   2463 	default:
   2464 		DPRINTF(("audio: bad encoding %d\n", params->encoding));
   2465 		auzero0 = 0;
   2466 		break;
   2467 	}
   2468 	if (nfill == 1) {
   2469 		while (--n >= 0)
   2470 			*p++ = auzero0; /* XXX memset */
   2471 	} else /* nfill must no longer be 2 */ {
   2472 		if (params->encoding == AUDIO_ENCODING_ULINEAR_LE) {
   2473 			int k = nfill;
   2474 			while (--k > 0)
   2475 				*p++ = auzero1;
   2476 			n -= nfill - 1;
   2477 		}
   2478 		while (n >= nfill) {
   2479 			int k = nfill;
   2480 			*p++ = auzero0;
   2481 			while (--k > 0)
   2482 				*p++ = auzero1;
   2483 
   2484 			n -= nfill;
   2485 		}
   2486 		if (n-- > 0)	/* XXX must be 1 - DIAGNOSTIC check? */
   2487 			*p++ = auzero0;
   2488 	}
   2489 }
   2490 
   2491 int
   2492 audio_silence_copyout(struct audio_softc *sc, int n, struct uio *uio)
   2493 {
   2494 	struct virtual_channel *vc;
   2495 	uint8_t zerobuf[128];
   2496 	int error;
   2497 	int k;
   2498 
   2499 	vc = sc->sc_vchan[0];
   2500 	audio_fill_silence(&vc->sc_rparams, zerobuf, sizeof zerobuf);
   2501 
   2502 	error = 0;
   2503 	while (n > 0 && uio->uio_resid > 0 && !error) {
   2504 		k = min(n, min(uio->uio_resid, sizeof zerobuf));
   2505 		mutex_exit(sc->sc_lock);
   2506 		error = uiomove(zerobuf, k, uio);
   2507 		mutex_enter(sc->sc_lock);
   2508 		n -= k;
   2509 	}
   2510 
   2511 	return error;
   2512 }
   2513 
   2514 static int
   2515 uio_fetcher_fetch_to(struct audio_softc *sc, stream_fetcher_t *self,
   2516     audio_stream_t *p, int max_used)
   2517 {
   2518 	uio_fetcher_t *this;
   2519 	int size;
   2520 	int stream_space;
   2521 	int error;
   2522 
   2523 	KASSERT(mutex_owned(sc->sc_lock));
   2524 	KASSERT(!cpu_intr_p());
   2525 	KASSERT(!cpu_softintr_p());
   2526 
   2527 	this = (uio_fetcher_t *)self;
   2528 	this->last_used = audio_stream_get_used(p);
   2529 	if (this->last_used >= this->usedhigh)
   2530 		return 0;
   2531 	/*
   2532 	 * uio_fetcher ignores max_used and move the data as
   2533 	 * much as possible in order to return the correct value
   2534 	 * for audio_prinfo::seek and kfilters.
   2535 	 */
   2536 	stream_space = audio_stream_get_space(p);
   2537 	size = min(this->uio->uio_resid, stream_space);
   2538 
   2539 	/* the first fragment of the space */
   2540 	stream_space = p->end - p->inp;
   2541 	if (stream_space >= size) {
   2542 		mutex_exit(sc->sc_lock);
   2543 		error = uiomove(p->inp, size, this->uio);
   2544 		mutex_enter(sc->sc_lock);
   2545 		if (error)
   2546 			return error;
   2547 		p->inp = audio_stream_add_inp(p, p->inp, size);
   2548 	} else {
   2549 		mutex_exit(sc->sc_lock);
   2550 		error = uiomove(p->inp, stream_space, this->uio);
   2551 		mutex_enter(sc->sc_lock);
   2552 		if (error)
   2553 			return error;
   2554 		p->inp = audio_stream_add_inp(p, p->inp, stream_space);
   2555 		mutex_exit(sc->sc_lock);
   2556 		error = uiomove(p->start, size - stream_space, this->uio);
   2557 		mutex_enter(sc->sc_lock);
   2558 		if (error)
   2559 			return error;
   2560 		p->inp = audio_stream_add_inp(p, p->inp, size - stream_space);
   2561 	}
   2562 	this->last_used = audio_stream_get_used(p);
   2563 	return 0;
   2564 }
   2565 
   2566 static int
   2567 null_fetcher_fetch_to(struct audio_softc *sc, stream_fetcher_t *self,
   2568     audio_stream_t *p, int max_used)
   2569 {
   2570 
   2571 	return 0;
   2572 }
   2573 
   2574 static void
   2575 uio_fetcher_ctor(uio_fetcher_t *this, struct uio *u, int h)
   2576 {
   2577 
   2578 	this->base.fetch_to = uio_fetcher_fetch_to;
   2579 	this->uio = u;
   2580 	this->usedhigh = h;
   2581 }
   2582 
   2583 int
   2584 audio_write(struct audio_softc *sc, struct uio *uio, int ioflag)
   2585 {
   2586 	uio_fetcher_t ufetcher;
   2587 	audio_stream_t stream;
   2588 	struct audio_ringbuffer *cb;
   2589 	struct virtual_channel *vc;
   2590 	stream_fetcher_t *fetcher;
   2591 	stream_filter_t *filter;
   2592 	uint8_t *inp, *einp;
   2593 	int saveerror, error, n, m, cc, used;
   2594 
   2595 	KASSERT(mutex_owned(sc->sc_lock));
   2596 
   2597 	for (n = 1; n < VAUDIOCHANS; n++) {
   2598 		if (sc->sc_audiopid[n].pid == curproc->p_pid)
   2599 			break;
   2600 	}
   2601 	if (n == VAUDIOCHANS)
   2602 		return EINVAL;
   2603 
   2604 	if (sc->hw_if == NULL)
   2605 		return ENXIO;
   2606 
   2607 	vc = sc->sc_vchan[n];
   2608 	cb = &vc->sc_mpr;
   2609 
   2610 	DPRINTFN(2,("audio_write: sc=%p count=%zu used=%d(hi=%d)\n",
   2611 		    sc, uio->uio_resid, audio_stream_get_used(vc->sc_pustream),
   2612 		    vc->sc_mpr.usedhigh));
   2613 	if (vc->sc_mpr.mmapped)
   2614 		return EINVAL;
   2615 
   2616 	if (uio->uio_resid == 0) {
   2617 		sc->sc_eof++;
   2618 		return 0;
   2619 	}
   2620 
   2621 #ifdef AUDIO_PM_IDLE
   2622 	if (device_is_active(&sc->dev) || sc->sc_idle)
   2623 		device_active(&sc->dev, DVA_SYSTEM);
   2624 #endif
   2625 
   2626 	/*
   2627 	 * If half-duplex and currently recording, throw away data.
   2628 	 */
   2629 	if (!vc->sc_full_duplex &&
   2630 	    (vc->sc_mode & AUMODE_RECORD)) {
   2631 		uio->uio_offset += uio->uio_resid;
   2632 		uio->uio_resid = 0;
   2633 		DPRINTF(("audio_write: half-dpx read busy\n"));
   2634 		return 0;
   2635 	}
   2636 
   2637 	if (!(vc->sc_mode & AUMODE_PLAY_ALL) && vc->sc_playdrop > 0) {
   2638 		m = min(vc->sc_playdrop, uio->uio_resid);
   2639 		DPRINTF(("audio_write: playdrop %d\n", m));
   2640 		uio->uio_offset += m;
   2641 		uio->uio_resid -= m;
   2642 		vc->sc_playdrop -= m;
   2643 		if (uio->uio_resid == 0)
   2644 			return 0;
   2645 	}
   2646 
   2647 	/**
   2648 	 * setup filter pipeline
   2649 	 */
   2650 	uio_fetcher_ctor(&ufetcher, uio, vc->sc_mpr.usedhigh);
   2651 	if (vc->sc_npfilters > 0) {
   2652 		fetcher = &vc->sc_pfilters[vc->sc_npfilters - 1]->base;
   2653 	} else {
   2654 		fetcher = &ufetcher.base;
   2655 	}
   2656 
   2657 	error = 0;
   2658 	mutex_enter(sc->sc_intr_lock);
   2659 	while (uio->uio_resid > 0 && !error) {
   2660 		/* wait if the first buffer is occupied */
   2661 		while ((used = audio_stream_get_used(vc->sc_pustream)) >=
   2662 							 cb->usedhigh) {
   2663 			DPRINTFN(2, ("audio_write: sleep used=%d lowat=%d "
   2664 				     "hiwat=%d\n", used,
   2665 				     cb->usedlow, cb->usedhigh));
   2666 			mutex_exit(sc->sc_intr_lock);
   2667 			if (ioflag & IO_NDELAY)
   2668 				return EWOULDBLOCK;
   2669 			error = audio_waitio(sc, &sc->sc_wchan);
   2670 			if (sc->sc_dying)
   2671 				error = EIO;
   2672 			if (error)
   2673 				return error;
   2674 			mutex_enter(sc->sc_intr_lock);
   2675 		}
   2676 		inp = cb->s.inp;
   2677 		cb->copying = true;
   2678 		stream = cb->s;
   2679 		used = stream.used;
   2680 
   2681 		/* Write to the sc_pustream as much as possible. */
   2682 		mutex_exit(sc->sc_intr_lock);
   2683 		if (vc->sc_npfilters > 0) {
   2684 			filter = vc->sc_pfilters[0];
   2685 			filter->set_fetcher(filter, &ufetcher.base);
   2686 			fetcher = &vc->sc_pfilters[vc->sc_npfilters - 1]->base;
   2687 			cc = cb->blksize * 2;
   2688 			error = fetcher->fetch_to(sc, fetcher, &stream, cc);
   2689 			if (error != 0) {
   2690 				fetcher = &ufetcher.base;
   2691 				cc = vc->sc_pustream->end -
   2692 				    vc->sc_pustream->start;
   2693 				error = fetcher->fetch_to(sc, fetcher,
   2694 				    vc->sc_pustream, cc);
   2695 			}
   2696 		} else {
   2697 			fetcher = &ufetcher.base;
   2698 			cc = stream.end - stream.start;
   2699 			error = fetcher->fetch_to(sc, fetcher, &stream, cc);
   2700 		}
   2701 		mutex_enter(sc->sc_intr_lock);
   2702 		if (vc->sc_npfilters > 0) {
   2703 			cb->fstamp += ufetcher.last_used
   2704 			    - audio_stream_get_used(vc->sc_pustream);
   2705 		}
   2706 		cb->s.used += stream.used - used;
   2707 		cb->s.inp = stream.inp;
   2708 		einp = cb->s.inp;
   2709 
   2710 		/*
   2711 		 * This is a very suboptimal way of keeping track of
   2712 		 * silence in the buffer, but it is simple.
   2713 		 */
   2714 		vc->sc_sil_count = 0;
   2715 
   2716 		/*
   2717 		 * If the interrupt routine wants the last block filled AND
   2718 		 * the copy did not fill the last block completely it needs to
   2719 		 * be padded.
   2720 		 */
   2721 		if (cb->needfill && inp < einp &&
   2722 		    (inp  - cb->s.start) / cb->blksize ==
   2723 		    (einp - cb->s.start) / cb->blksize) {
   2724 			/* Figure out how many bytes to a block boundary. */
   2725 			cc = cb->blksize - (einp - cb->s.start) % cb->blksize;
   2726 			DPRINTF(("audio_write: partial fill %d\n", cc));
   2727 		} else
   2728 			cc = 0;
   2729 		cb->needfill = false;
   2730 		cb->copying = false;
   2731 		if (!vc->sc_pbus && !cb->pause) {
   2732 			saveerror = error;
   2733 			error = audiostartp(sc, n);
   2734 			if (saveerror != 0) {
   2735 				/* Report the first error that occurred. */
   2736 				error = saveerror;
   2737 			}
   2738 		}
   2739 		if (cc != 0) {
   2740 			DPRINTFN(1, ("audio_write: fill %d\n", cc));
   2741 			audio_fill_silence(&cb->s.param, einp, cc);
   2742 		}
   2743 	}
   2744 	mutex_exit(sc->sc_intr_lock);
   2745 
   2746 	return error;
   2747 }
   2748 
   2749 int
   2750 audio_ioctl(dev_t dev, struct audio_softc *sc, u_long cmd, void *addr, int flag,
   2751 	    struct lwp *l)
   2752 {
   2753 	const struct audio_hw_if *hw;
   2754 	struct virtual_channel *vc;
   2755 	struct audio_offset *ao;
   2756 	u_long stamp;
   2757 	int error, offs, fd, m, n;
   2758 	bool rbus, pbus;
   2759 
   2760 	KASSERT(mutex_owned(sc->sc_lock));
   2761 	for (n = 1; n < VAUDIOCHANS; n++) {
   2762 		if (sc->sc_audiopid[n].pid == curproc->p_pid)
   2763 			break;
   2764 	}
   2765 	m = n;
   2766 	for (n = 1; n < VAUDIOCHANS; n++) {
   2767 		if (sc->sc_despid[m].pid >= 0 && sc->sc_audiopid[n].pid ==
   2768 		    sc->sc_despid[m].pid)
   2769 				break;
   2770 	}
   2771 
   2772 	if (m >= VAUDIOCHANS || n >= VAUDIOCHANS)
   2773 		return ENXIO;
   2774 
   2775 	vc = sc->sc_vchan[n];
   2776 
   2777 	DPRINTF(("audio_ioctl(%lu,'%c',%lu)\n",
   2778 		 IOCPARM_LEN(cmd), (char)IOCGROUP(cmd), cmd&0xff));
   2779 	hw = sc->hw_if;
   2780 	if (hw == NULL)
   2781 		return ENXIO;
   2782 	error = 0;
   2783 	switch (cmd) {
   2784 	case AUDIO_SETPROC:
   2785 		if ((struct audio_pid *)addr != NULL)
   2786 			sc->sc_despid[m] = *(struct audio_pid *)addr;
   2787 		break;
   2788 	case FIONBIO:
   2789 		/* All handled in the upper FS layer. */
   2790 		break;
   2791 
   2792 	case FIONREAD:
   2793 		*(int *)addr = audio_stream_get_used(vc->sc_rustream);
   2794 		break;
   2795 
   2796 	case FIOASYNC:
   2797 		if (*(int *)addr) {
   2798 			if (sc->sc_async_audio != 0)
   2799 				error = EBUSY;
   2800 			else
   2801 				sc->sc_async_audio = sc->sc_audiopid[n].pid;
   2802 			DPRINTF(("audio_ioctl: FIOASYNC pid %d\n",
   2803 			    sc->sc_audiopid[n].pid));
   2804 		} else
   2805 			sc->sc_async_audio = 0;
   2806 		break;
   2807 
   2808 	case AUDIO_FLUSH:
   2809 		DPRINTF(("AUDIO_FLUSH\n"));
   2810 		rbus = vc->sc_rbus;
   2811 		pbus = vc->sc_pbus;
   2812 		mutex_enter(sc->sc_intr_lock);
   2813 		audio_clear(sc, n);
   2814 		error = audio_initbufs(sc, n);
   2815 		if (error) {
   2816 			mutex_exit(sc->sc_intr_lock);
   2817 			return error;
   2818 		}
   2819 		if ((vc->sc_mode & AUMODE_PLAY) && !vc->sc_pbus && pbus)
   2820 			error = audiostartp(sc, n);
   2821 		if (!error &&
   2822 		    (vc->sc_mode & AUMODE_RECORD) && !vc->sc_rbus && rbus)
   2823 			error = audiostartr(sc, n);
   2824 		mutex_exit(sc->sc_intr_lock);
   2825 		break;
   2826 
   2827 	/*
   2828 	 * Number of read (write) samples dropped.  We don't know where or
   2829 	 * when they were dropped.
   2830 	 */
   2831 	case AUDIO_RERROR:
   2832 		*(int *)addr = vc->sc_mrr.drops;
   2833 		break;
   2834 
   2835 	case AUDIO_PERROR:
   2836 		*(int *)addr = vc->sc_mpr.drops;
   2837 		break;
   2838 
   2839 	/*
   2840 	 * Offsets into buffer.
   2841 	 */
   2842 	case AUDIO_GETIOFFS:
   2843 		ao = (struct audio_offset *)addr;
   2844 		mutex_enter(sc->sc_intr_lock);
   2845 		/* figure out where next DMA will start */
   2846 		stamp = vc->sc_rustream == &vc->sc_mrr.s
   2847 			? vc->sc_mrr.stamp : vc->sc_mrr.fstamp;
   2848 		offs = vc->sc_rustream->inp - vc->sc_rustream->start;
   2849 		mutex_exit(sc->sc_intr_lock);
   2850 		ao->samples = stamp;
   2851 		ao->deltablks =
   2852 		  (stamp / vc->sc_mrr.blksize) -
   2853 		  (vc->sc_mrr.stamp_last / vc->sc_mrr.blksize);
   2854 		vc->sc_mrr.stamp_last = stamp;
   2855 		ao->offset = offs;
   2856 		break;
   2857 
   2858 	case AUDIO_GETOOFFS:
   2859 		ao = (struct audio_offset *)addr;
   2860 		mutex_enter(sc->sc_intr_lock);
   2861 		/* figure out where next DMA will start */
   2862 		stamp = vc->sc_pustream == &vc->sc_mpr.s
   2863 			? vc->sc_mpr.stamp : vc->sc_mpr.fstamp;
   2864 		offs = vc->sc_pustream->outp - vc->sc_pustream->start
   2865 			+ vc->sc_mpr.blksize;
   2866 		mutex_exit(sc->sc_intr_lock);
   2867 		ao->samples = stamp;
   2868 		ao->deltablks =
   2869 		  (stamp / vc->sc_mpr.blksize) -
   2870 		  (vc->sc_mpr.stamp_last / vc->sc_mpr.blksize);
   2871 		vc->sc_mpr.stamp_last = stamp;
   2872 		if (vc->sc_pustream->start + offs >= vc->sc_pustream->end)
   2873 			offs = 0;
   2874 		ao->offset = offs;
   2875 		break;
   2876 
   2877 	/*
   2878 	 * How many bytes will elapse until mike hears the first
   2879 	 * sample of what we write next?
   2880 	 */
   2881 	case AUDIO_WSEEK:
   2882 		*(u_long *)addr = audio_stream_get_used(vc->sc_pustream);
   2883 		break;
   2884 
   2885 	case AUDIO_SETINFO:
   2886 		DPRINTF(("AUDIO_SETINFO mode=0x%x\n", vc->sc_mode));
   2887 		error = audiosetinfo(sc, (struct audio_info *)addr, false, n);
   2888 		if (!error && ISDEVSOUND(dev)) {
   2889 			error = audiogetinfo(sc, &sc->sc_ai, 0, n);
   2890 			sc->sc_aivalid = true;
   2891 		}
   2892 		break;
   2893 
   2894 	case AUDIO_GETINFO:
   2895 		DPRINTF(("AUDIO_GETINFO\n"));
   2896 		error = audiogetinfo(sc, (struct audio_info *)addr, 0, n);
   2897 		break;
   2898 
   2899 	case AUDIO_GETBUFINFO:
   2900 		DPRINTF(("AUDIO_GETBUFINFO\n"));
   2901 		error = audiogetinfo(sc, (struct audio_info *)addr, 1, n);
   2902 		break;
   2903 
   2904 	case AUDIO_DRAIN:
   2905 		DPRINTF(("AUDIO_DRAIN\n"));
   2906 		mutex_enter(sc->sc_intr_lock);
   2907 		error = audio_drain(sc, n);
   2908 		if (!error && sc->sc_opens == 1 && hw->drain)
   2909 		    error = hw->drain(sc->hw_hdl);
   2910 		mutex_exit(sc->sc_intr_lock);
   2911 		break;
   2912 
   2913 	case AUDIO_GETDEV:
   2914 		DPRINTF(("AUDIO_GETDEV\n"));
   2915 		error = hw->getdev(sc->hw_hdl, (audio_device_t *)addr);
   2916 		break;
   2917 
   2918 	case AUDIO_GETENC:
   2919 		DPRINTF(("AUDIO_GETENC\n"));
   2920 		error = audio_query_encoding(sc,
   2921 		    (struct audio_encoding *)addr);
   2922 		break;
   2923 
   2924 	case AUDIO_GETFD:
   2925 		DPRINTF(("AUDIO_GETFD\n"));
   2926 		*(int *)addr = vc->sc_full_duplex;
   2927 		break;
   2928 
   2929 	case AUDIO_SETFD:
   2930 		DPRINTF(("AUDIO_SETFD\n"));
   2931 		fd = *(int *)addr;
   2932 		if (audio_get_props(sc) & AUDIO_PROP_FULLDUPLEX) {
   2933 			if (hw->setfd)
   2934 				error = hw->setfd(sc->hw_hdl, fd);
   2935 			else
   2936 				error = 0;
   2937 			if (!error)
   2938 				vc->sc_full_duplex = fd;
   2939 		} else {
   2940 			if (fd)
   2941 				error = ENOTTY;
   2942 			else
   2943 				error = 0;
   2944 		}
   2945 		break;
   2946 
   2947 	case AUDIO_GETPROPS:
   2948 		DPRINTF(("AUDIO_GETPROPS\n"));
   2949 		*(int *)addr = audio_get_props(sc);
   2950 		break;
   2951 
   2952 	default:
   2953 		if (hw->dev_ioctl) {
   2954 			error = hw->dev_ioctl(sc->hw_hdl, cmd, addr, flag, l);
   2955 		} else {
   2956 			DPRINTF(("audio_ioctl: unknown ioctl\n"));
   2957 			error = EINVAL;
   2958 		}
   2959 		break;
   2960 	}
   2961 	DPRINTF(("audio_ioctl(%lu,'%c',%lu) result %d\n",
   2962 		 IOCPARM_LEN(cmd), (char)IOCGROUP(cmd), cmd&0xff, error));
   2963 	return error;
   2964 }
   2965 
   2966 int
   2967 audio_poll(struct audio_softc *sc, int events, struct lwp *l)
   2968 {
   2969 	struct virtual_channel *vc;
   2970 	int revents;
   2971 	int used, n;
   2972 
   2973 	KASSERT(mutex_owned(sc->sc_lock));
   2974 	for (n = 1; n < VAUDIOCHANS; n++) {
   2975 		if (sc->sc_audiopid[n].pid == curproc->p_pid)
   2976 			break;
   2977 	}
   2978 	if (n == VAUDIOCHANS)
   2979 		return ENXIO;
   2980 	vc = sc->sc_vchan[n];
   2981 
   2982 	DPRINTF(("audio_poll: events=0x%x mode=%d\n", events, vc->sc_mode));
   2983 
   2984 	revents = 0;
   2985 	mutex_enter(sc->sc_intr_lock);
   2986 	if (events & (POLLIN | POLLRDNORM)) {
   2987 		used = audio_stream_get_used(vc->sc_rustream);
   2988 		/*
   2989 		 * If half duplex and playing, audio_read() will generate
   2990 		 * silence at the play rate; poll for silence being
   2991 		 * available.  Otherwise, poll for recorded sound.
   2992 		 */
   2993 		if ((!vc->sc_full_duplex && (vc->sc_mode & AUMODE_PLAY))
   2994 		     ? vc->sc_mpr.stamp > vc->sc_wstamp :
   2995 		    used > vc->sc_mrr.usedlow)
   2996 			revents |= events & (POLLIN | POLLRDNORM);
   2997 	}
   2998 
   2999 	if (events & (POLLOUT | POLLWRNORM)) {
   3000 		used = audio_stream_get_used(vc->sc_pustream);
   3001 		/*
   3002 		 * If half duplex and recording, audio_write() will throw
   3003 		 * away play data, which means we are always ready to write.
   3004 		 * Otherwise, poll for play buffer being below its low water
   3005 		 * mark.
   3006 		 */
   3007 		if ((!vc->sc_full_duplex && (vc->sc_mode & AUMODE_RECORD)) ||
   3008 		    (!(vc->sc_mode & AUMODE_PLAY_ALL) && vc->sc_playdrop > 0) ||
   3009 		    (used <= vc->sc_mpr.usedlow))
   3010 			revents |= events & (POLLOUT | POLLWRNORM);
   3011 	}
   3012 	mutex_exit(sc->sc_intr_lock);
   3013 
   3014 	if (revents == 0) {
   3015 		if (events & (POLLIN | POLLRDNORM))
   3016 			selrecord(l, &sc->sc_rsel);
   3017 
   3018 		if (events & (POLLOUT | POLLWRNORM))
   3019 			selrecord(l, &sc->sc_wsel);
   3020 	}
   3021 
   3022 	return revents;
   3023 }
   3024 
   3025 static void
   3026 filt_audiordetach(struct knote *kn)
   3027 {
   3028 	struct audio_softc *sc;
   3029 
   3030 	sc = kn->kn_hook;
   3031 	mutex_enter(sc->sc_intr_lock);
   3032 	SLIST_REMOVE(&sc->sc_rsel.sel_klist, kn, knote, kn_selnext);
   3033 	mutex_exit(sc->sc_intr_lock);
   3034 }
   3035 
   3036 static int
   3037 filt_audioread(struct knote *kn, long hint)
   3038 {
   3039 	struct audio_softc *sc;
   3040 	struct virtual_channel *vc;
   3041 	int n;
   3042 
   3043 	sc = kn->kn_hook;
   3044 	for (n = 1; n < VAUDIOCHANS; n++) {
   3045 		if (sc->sc_audiopid[n].pid == curproc->p_pid)
   3046 			break;
   3047 	}
   3048 	if (n == VAUDIOCHANS)
   3049 		return ENXIO;
   3050 
   3051 	vc = sc->sc_vchan[n];
   3052 	mutex_enter(sc->sc_intr_lock);
   3053 	if (!vc->sc_full_duplex && (vc->sc_mode & AUMODE_PLAY))
   3054 		kn->kn_data = vc->sc_mpr.stamp - vc->sc_wstamp;
   3055 	else
   3056 		kn->kn_data = audio_stream_get_used(vc->sc_rustream)
   3057 			- vc->sc_mrr.usedlow;
   3058 	mutex_exit(sc->sc_intr_lock);
   3059 
   3060 	return kn->kn_data > 0;
   3061 }
   3062 
   3063 static const struct filterops audioread_filtops =
   3064 	{ 1, NULL, filt_audiordetach, filt_audioread };
   3065 
   3066 static void
   3067 filt_audiowdetach(struct knote *kn)
   3068 {
   3069 	struct audio_softc *sc;
   3070 
   3071 	sc = kn->kn_hook;
   3072 	mutex_enter(sc->sc_intr_lock);
   3073 	SLIST_REMOVE(&sc->sc_wsel.sel_klist, kn, knote, kn_selnext);
   3074 	mutex_exit(sc->sc_intr_lock);
   3075 }
   3076 
   3077 static int
   3078 filt_audiowrite(struct knote *kn, long hint)
   3079 {
   3080 	struct audio_softc *sc;
   3081 	audio_stream_t *stream;
   3082 	int n;
   3083 
   3084 	sc = kn->kn_hook;
   3085 	mutex_enter(sc->sc_intr_lock);
   3086 	for (n = 1; n < VAUDIOCHANS; n++) {
   3087 		if (sc->sc_audiopid[n].pid == curproc->p_pid)
   3088 			break;
   3089 	}
   3090 	if (n == VAUDIOCHANS)
   3091 		return ENXIO;
   3092 
   3093 	stream = sc->sc_vchan[n]->sc_pustream;
   3094 	kn->kn_data = (stream->end - stream->start)
   3095 		- audio_stream_get_used(stream);
   3096 	mutex_exit(sc->sc_intr_lock);
   3097 
   3098 	return kn->kn_data > 0;
   3099 }
   3100 
   3101 static const struct filterops audiowrite_filtops =
   3102 	{ 1, NULL, filt_audiowdetach, filt_audiowrite };
   3103 
   3104 int
   3105 audio_kqfilter(struct audio_softc *sc, struct knote *kn)
   3106 {
   3107 	struct klist *klist;
   3108 
   3109 	switch (kn->kn_filter) {
   3110 	case EVFILT_READ:
   3111 		klist = &sc->sc_rsel.sel_klist;
   3112 		kn->kn_fop = &audioread_filtops;
   3113 		break;
   3114 
   3115 	case EVFILT_WRITE:
   3116 		klist = &sc->sc_wsel.sel_klist;
   3117 		kn->kn_fop = &audiowrite_filtops;
   3118 		break;
   3119 
   3120 	default:
   3121 		return EINVAL;
   3122 	}
   3123 
   3124 	kn->kn_hook = sc;
   3125 
   3126 	mutex_enter(sc->sc_intr_lock);
   3127 	SLIST_INSERT_HEAD(klist, kn, kn_selnext);
   3128 	mutex_exit(sc->sc_intr_lock);
   3129 
   3130 	return 0;
   3131 }
   3132 
   3133 paddr_t
   3134 audio_mmap(struct audio_softc *sc, off_t off, int prot)
   3135 {
   3136 	struct audio_ringbuffer *cb;
   3137 	struct virtual_channel *vc;
   3138 	paddr_t rv;
   3139 	int n;
   3140 
   3141 	KASSERT(mutex_owned(sc->sc_lock));
   3142 
   3143 	for (n = 1; n < VAUDIOCHANS; n++) {
   3144 		if (sc->sc_audiopid[n].pid == curproc->p_pid)
   3145 			break;
   3146 	}
   3147 	if (n == VAUDIOCHANS)
   3148 		return -1;
   3149 
   3150 	if (sc->hw_if == NULL)
   3151 		return ENXIO;
   3152 
   3153 	DPRINTF(("audio_mmap: off=%lld, prot=%d\n", (long long)off, prot));
   3154 	vc = sc->sc_vchan[n];
   3155 	if (!(audio_get_props(sc) & AUDIO_PROP_MMAP))
   3156 		return -1;
   3157 #if 0
   3158 /* XXX
   3159  * The idea here was to use the protection to determine if
   3160  * we are mapping the read or write buffer, but it fails.
   3161  * The VM system is broken in (at least) two ways.
   3162  * 1) If you map memory VM_PROT_WRITE you SIGSEGV
   3163  *    when writing to it, so VM_PROT_READ|VM_PROT_WRITE
   3164  *    has to be used for mmapping the play buffer.
   3165  * 2) Even if calling mmap() with VM_PROT_READ|VM_PROT_WRITE
   3166  *    audio_mmap will get called at some point with VM_PROT_READ
   3167  *    only.
   3168  * So, alas, we always map the play buffer for now.
   3169  */
   3170 	if (prot == (VM_PROT_READ|VM_PROT_WRITE) ||
   3171 	    prot == VM_PROT_WRITE)
   3172 		cb = &sc->sc_vchan[n]->sc_mpr;
   3173 	else if (prot == VM_PROT_READ)
   3174 		cb = &sc->sc_vchan[n]->sc_mrr;
   3175 	else
   3176 		return -1;
   3177 #else
   3178 	cb = &sc->sc_vchan[n]->sc_mpr;
   3179 #endif
   3180 
   3181 	if ((u_int)off >= cb->s.bufsize)
   3182 		return -1;
   3183 	if (!cb->mmapped) {
   3184 		cb->mmapped = true;
   3185 		if (cb != &sc->sc_rr) {
   3186 			audio_fill_silence(&cb->s.param, cb->s.start,
   3187 					   cb->s.bufsize);
   3188 			mutex_enter(sc->sc_intr_lock);
   3189 			vc->sc_pustream = &cb->s;
   3190 			if (!vc->sc_pbus && !vc->sc_mpr.pause)
   3191 				(void)audiostartp(sc, n);
   3192 			mutex_exit(sc->sc_intr_lock);
   3193 		} else {
   3194 			mutex_enter(sc->sc_intr_lock);
   3195 			vc->sc_rustream = &cb->s;
   3196 			if (!vc->sc_rbus && !sc->sc_rr.pause)
   3197 				(void)audiostartr(sc, n);
   3198 			mutex_exit(sc->sc_intr_lock);
   3199 		}
   3200 	}
   3201 
   3202 	mutex_exit(sc->sc_lock);
   3203 	rv = (paddr_t)(uintptr_t)(cb->s.start + off);
   3204 	mutex_enter(sc->sc_lock);
   3205 
   3206 	return rv;
   3207 }
   3208 
   3209 int
   3210 audiostartr(struct audio_softc *sc, int n)
   3211 {
   3212 	struct virtual_channel *vc;
   3213 
   3214 	KASSERT(mutex_owned(sc->sc_lock));
   3215 	KASSERT(mutex_owned(sc->sc_intr_lock));
   3216 
   3217 	vc = sc->sc_vchan[n];
   3218 	DPRINTF(("audiostartr: start=%p used=%d(hi=%d) mmapped=%d\n",
   3219 		 vc->sc_mrr.s.start, audio_stream_get_used(&vc->sc_mrr.s),
   3220 		 vc->sc_mrr.usedhigh, vc->sc_mrr.mmapped));
   3221 
   3222 	if (!audio_can_capture(sc))
   3223 		return EINVAL;
   3224 
   3225 	if (sc->sc_rec_started == false) {
   3226 		mix_read(sc);
   3227 		cv_broadcast(&sc->sc_rcondvar);
   3228 	}
   3229 	vc->sc_rbus = true;
   3230 
   3231 	return 0;
   3232 }
   3233 
   3234 int
   3235 audiostartp(struct audio_softc *sc, int n)
   3236 {
   3237 	struct virtual_channel *vc = sc->sc_vchan[n];
   3238 	int used, error;
   3239 
   3240 	KASSERT(mutex_owned(sc->sc_lock));
   3241 	KASSERT(mutex_owned(sc->sc_intr_lock));
   3242 
   3243 	error = 0;
   3244 	used = audio_stream_get_used(&vc->sc_mpr.s);
   3245 	DPRINTF(("audiostartp: start=%p used=%d(hi=%d blk=%d) mmapped=%d\n",
   3246 		 vc->sc_mpr.s.start, used, vc->sc_mpr.usedhigh,
   3247 		 vc->sc_mpr.blksize, vc->sc_mpr.mmapped));
   3248 
   3249 	if (!audio_can_playback(sc))
   3250 		return EINVAL;
   3251 
   3252 	if (!vc->sc_mpr.mmapped && used < vc->sc_mpr.blksize) {
   3253 		cv_broadcast(&sc->sc_wchan);
   3254 		DPRINTF(("%s: wakeup and return\n", __func__));
   3255 		return 0;
   3256 	}
   3257 
   3258 	vc->sc_pbus = true;
   3259 	if (sc->sc_opens > 0) {
   3260 		mix_func(sc, &vc->sc_mpr, n);
   3261 
   3262 		if (sc->sc_trigger_started == false) {
   3263 			mix_write(sc);
   3264 			audio_mix(sc);
   3265 			vc = sc->sc_vchan[0];
   3266 			vc->sc_mpr.s.outp = audio_stream_add_outp(&vc->sc_mpr.s,
   3267 			    vc->sc_mpr.s.outp, vc->sc_mpr.blksize);
   3268 			mix_write(sc);
   3269 
   3270 			cv_broadcast(&sc->sc_condvar);
   3271 		}
   3272 	}
   3273 
   3274 	return error;
   3275 }
   3276 
   3277 /*
   3278  * When the play interrupt routine finds that the write isn't keeping
   3279  * the buffer filled it will insert silence in the buffer to make up
   3280  * for this.  The part of the buffer that is filled with silence
   3281  * is kept track of in a very approximate way: it starts at sc_sil_start
   3282  * and extends sc_sil_count bytes.  If there is already silence in
   3283  * the requested area nothing is done; so when the whole buffer is
   3284  * silent nothing happens.  When the writer starts again sc_sil_count
   3285  * is set to 0.
   3286  *
   3287  * XXX
   3288  * Putting silence into the output buffer should not really be done
   3289  * from the device interrupt handler.  Consider deferring to the soft
   3290  * interrupt.
   3291  */
   3292 static inline void
   3293 audio_pint_silence(struct audio_softc *sc, struct audio_ringbuffer *cb,
   3294 		   uint8_t *inp, int cc, int n)
   3295 {
   3296 	struct virtual_channel *vc = sc->sc_vchan[n];
   3297 	uint8_t *s, *e, *p, *q;
   3298 
   3299 	KASSERT(mutex_owned(sc->sc_lock));
   3300 
   3301 	if (vc->sc_sil_count > 0) {
   3302 		s = vc->sc_sil_start; /* start of silence */
   3303 		e = s + vc->sc_sil_count; /* end of sil., may be beyond end */
   3304 		p = inp;	/* adjusted pointer to area to fill */
   3305 		if (p < s)
   3306 			p += cb->s.end - cb->s.start;
   3307 		q = p + cc;
   3308 		/* Check if there is already silence. */
   3309 		if (!(s <= p && p <  e &&
   3310 		      s <= q && q <= e)) {
   3311 			if (s <= p)
   3312 				vc->sc_sil_count = max(vc->sc_sil_count, q-s);
   3313 			DPRINTFN(5,("audio_pint_silence: fill cc=%d inp=%p, "
   3314 				    "count=%d size=%d\n",
   3315 				    cc, inp, vc->sc_sil_count,
   3316 				    (int)(cb->s.end - cb->s.start)));
   3317 			audio_fill_silence(&cb->s.param, inp, cc);
   3318 		} else {
   3319 			DPRINTFN(5,("audio_pint_silence: already silent "
   3320 				    "cc=%d inp=%p\n", cc, inp));
   3321 
   3322 		}
   3323 	} else {
   3324 		vc->sc_sil_start = inp;
   3325 		vc->sc_sil_count = cc;
   3326 		DPRINTFN(5, ("audio_pint_silence: start fill %p %d\n",
   3327 			     inp, cc));
   3328 		audio_fill_silence(&cb->s.param, inp, cc);
   3329 	}
   3330 }
   3331 
   3332 static void
   3333 audio_softintr_rd(void *cookie)
   3334 {
   3335 	struct audio_softc *sc = cookie;
   3336 	proc_t *p;
   3337 	pid_t pid;
   3338 
   3339 	mutex_enter(sc->sc_lock);
   3340 	cv_broadcast(&sc->sc_rchan);
   3341 	selnotify(&sc->sc_rsel, 0, NOTE_SUBMIT);
   3342 	if ((pid = sc->sc_async_audio) != 0) {
   3343 		DPRINTFN(3, ("audio_softintr_rd: sending SIGIO %d\n", pid));
   3344 		mutex_enter(proc_lock);
   3345 		if ((p = proc_find(pid)) != NULL)
   3346 			psignal(p, SIGIO);
   3347 		mutex_exit(proc_lock);
   3348 	}
   3349 	mutex_exit(sc->sc_lock);
   3350 }
   3351 
   3352 static void
   3353 audio_softintr_wr(void *cookie)
   3354 {
   3355 	struct audio_softc *sc = cookie;
   3356 	proc_t *p;
   3357 	pid_t pid;
   3358 
   3359 	mutex_enter(sc->sc_lock);
   3360 	cv_broadcast(&sc->sc_wchan);
   3361 	selnotify(&sc->sc_wsel, 0, NOTE_SUBMIT);
   3362 	if ((pid = sc->sc_async_audio) != 0) {
   3363 		DPRINTFN(3, ("audio_softintr_wr: sending SIGIO %d\n", pid));
   3364 		mutex_enter(proc_lock);
   3365 		if ((p = proc_find(pid)) != NULL)
   3366 			psignal(p, SIGIO);
   3367 		mutex_exit(proc_lock);
   3368 	}
   3369 	mutex_exit(sc->sc_lock);
   3370 }
   3371 
   3372 /*
   3373  * Called from HW driver module on completion of DMA output.
   3374  * Start output of new block, wrap in ring buffer if needed.
   3375  * If no more buffers to play, output zero instead.
   3376  * Do a wakeup if necessary.
   3377  */
   3378 void
   3379 audio_pint(void *v)
   3380 {
   3381 	struct audio_softc *sc;
   3382 	struct virtual_channel *vc;
   3383 
   3384 	sc = v;
   3385 	vc = sc->sc_vchan[0];
   3386 
   3387 	if (sc->sc_dying == true)
   3388 		return;
   3389 
   3390 	vc->sc_mpr.s.outp = audio_stream_add_outp(&vc->sc_mpr.s,
   3391 	    vc->sc_mpr.s.outp, vc->sc_mpr.blksize);
   3392 	mix_write(sc);
   3393 
   3394 	cv_broadcast(&sc->sc_condvar);
   3395 }
   3396 
   3397 void
   3398 audio_mix(void *v)
   3399 {
   3400 	stream_fetcher_t null_fetcher;
   3401 	struct audio_softc *sc;
   3402 	struct virtual_channel *vc;
   3403 	struct audio_ringbuffer *cb;
   3404 	stream_fetcher_t *fetcher;
   3405 	uint8_t *inp;
   3406 	int cc, used;
   3407 	int blksize;
   3408 	int n, i;
   3409 
   3410 	sc = v;
   3411 
   3412 	DPRINTF(("PINT MIX\n"));
   3413 	sc->schedule_rih = false;
   3414 	sc->schedule_wih = false;
   3415 	sc->sc_writeme = false;
   3416 
   3417 	if (sc->sc_dying == true)
   3418 		return;
   3419 
   3420 	i = sc->sc_opens;
   3421 	for (n = 1; n < VAUDIOCHANS; n++) {
   3422 		if (!sc->sc_opens || i <= 0)
   3423 			break;		/* ignore interrupt if not open */
   3424 
   3425 		if (sc->sc_audiopid[n].pid == -1)
   3426 			continue;
   3427 		i--;
   3428 		vc = sc->sc_vchan[n];
   3429 		if (!vc->sc_open)
   3430 			continue;
   3431 		if (!vc->sc_pbus)
   3432 			continue;
   3433 
   3434 		cb = &vc->sc_mpr;
   3435 		blksize = sc->sc_vchan[0]->sc_mpr.blksize;
   3436 
   3437 		sc->sc_writeme = true;
   3438 
   3439 		inp = cb->s.inp;
   3440 		cb->stamp += blksize;
   3441 		if (cb->mmapped) {
   3442 			DPRINTF(("audio_pint: mmapped outp=%p cc=%d inp=%p\n",
   3443 				     cb->s.outp, blksize, cb->s.inp));
   3444 			mix_func(sc, cb, n);
   3445 			continue;
   3446 		}
   3447 
   3448 #ifdef AUDIO_INTR_TIME
   3449 		{
   3450 			struct timeval tv;
   3451 			u_long t;
   3452 			microtime(&tv);
   3453 			t = tv.tv_usec + 1000000 * tv.tv_sec;
   3454 			if (sc->sc_pnintr) {
   3455 				long lastdelta, totdelta;
   3456 				lastdelta = t - sc->sc_plastintr -
   3457 				    sc->sc_pblktime;
   3458 				if (lastdelta > sc->sc_pblktime / 3) {
   3459 					printf("audio: play interrupt(%d) off "
   3460 				       "relative by %ld us (%lu)\n",
   3461 					       sc->sc_pnintr, lastdelta,
   3462 					       sc->sc_pblktime);
   3463 				}
   3464 				totdelta = t - sc->sc_pfirstintr -
   3465 					sc->sc_pblktime * sc->sc_pnintr;
   3466 				if (totdelta > sc->sc_pblktime) {
   3467 					printf("audio: play interrupt(%d) "
   3468 					       "off absolute by %ld us (%lu) "
   3469 					       "(LOST)\n", sc->sc_pnintr,
   3470 					       totdelta, sc->sc_pblktime);
   3471 					sc->sc_pnintr++;
   3472 					/* avoid repeated messages */
   3473 				}
   3474 			} else
   3475 				sc->sc_pfirstintr = t;
   3476 			sc->sc_plastintr = t;
   3477 			sc->sc_pnintr++;
   3478 		}
   3479 #endif
   3480 
   3481 		used = audio_stream_get_used(&cb->s);
   3482 		/*
   3483 		 * "used <= cb->usedlow" should be "used < blksize" ideally.
   3484 		 * Some HW drivers such as uaudio(4) does not call audio_pint()
   3485 		 * at accurate timing.  If used < blksize, uaudio(4) already
   3486 		 * request transfer of garbage data.
   3487 		 */
   3488 		if (used <= cb->usedlow && !cb->copying &&
   3489 		    vc->sc_npfilters > 0) {
   3490 			/* we might have data in filter pipeline */
   3491 			null_fetcher.fetch_to = null_fetcher_fetch_to;
   3492 			fetcher = &vc->sc_pfilters[vc->sc_npfilters - 1]->base;
   3493 			vc->sc_pfilters[0]->set_fetcher(vc->sc_pfilters[0],
   3494 							&null_fetcher);
   3495 			used = audio_stream_get_used(vc->sc_pustream);
   3496 			cc = cb->s.end - cb->s.start;
   3497 			if (blksize * 2 < cc)
   3498 				cc = blksize * 2;
   3499 			fetcher->fetch_to(sc, fetcher, &cb->s, cc);
   3500 			cb->fstamp += used -
   3501 			    audio_stream_get_used(vc->sc_pustream);
   3502 			used = audio_stream_get_used(&cb->s);
   3503 		}
   3504 		if (used < blksize) {
   3505 			/* we don't have a full block to use */
   3506 			if (cb->copying) {
   3507 				/* writer is in progress, don't disturb */
   3508 				cb->needfill = true;
   3509 				DPRINTFN(1, ("audio_pint: copying in "
   3510 					 "progress\n"));
   3511 			} else {
   3512 				inp = cb->s.inp;
   3513 				cc = blksize - (inp - cb->s.start) % blksize;
   3514 				if (cb->pause)
   3515 					cb->pdrops += cc;
   3516 				else {
   3517 					cb->drops += cc;
   3518 					vc->sc_playdrop += cc;
   3519 				}
   3520 
   3521 				audio_pint_silence(sc, cb, inp, cc, n);
   3522 				cb->s.inp = audio_stream_add_inp(&cb->s, inp,
   3523 				    cc);
   3524 
   3525 				/* Clear next block to keep ahead of the DMA. */
   3526 				used = audio_stream_get_used(&cb->s);
   3527 				if (used + blksize < cb->s.end - cb->s.start) {
   3528 					audio_pint_silence(sc, cb, cb->s.inp,
   3529 					    blksize, n);
   3530 				}
   3531 			}
   3532 		}
   3533 
   3534 		DPRINTFN(5, ("audio_pint: outp=%p cc=%d\n", cb->s.outp,
   3535 			 blksize));
   3536 		cb->s.outp = audio_stream_add_outp(&cb->s, cb->s.outp, blksize);
   3537 		mix_func(sc, cb, n);
   3538 
   3539 		DPRINTFN(2, ("audio_pint: mode=%d pause=%d used=%d lowat=%d\n",
   3540 			     vc->sc_mode, cb->pause,
   3541 			     audio_stream_get_used(vc->sc_pustream),
   3542 			     cb->usedlow));
   3543 
   3544 		if ((vc->sc_mode & AUMODE_PLAY) && !cb->pause) {
   3545 			if (audio_stream_get_used(&cb->s) <= cb->usedlow)
   3546 				sc->schedule_wih = true;
   3547 		}
   3548 		/* Possible to return one or more "phantom blocks" now. */
   3549 		if (!vc->sc_full_duplex && vc->sc_mode & AUMODE_RECORD)
   3550 				sc->schedule_rih = true;
   3551 	}
   3552 	if (sc->sc_saturate == true && sc->sc_opens > 1)
   3553 		saturate_func(sc);
   3554 
   3555 	kpreempt_disable();
   3556 	if (sc->schedule_wih == true)
   3557 		softint_schedule(sc->sc_sih_wr);
   3558 
   3559 	if (sc->schedule_rih == true)
   3560 		softint_schedule(sc->sc_sih_rd);
   3561 	kpreempt_enable();
   3562 
   3563 	cc = sc->sc_vchan[0]->sc_mpr.blksize;
   3564 	if (sc->sc_writeme == false) {
   3565 		sc->sc_vchan[0]->sc_mpr.drops += cc;
   3566 		cv_broadcast(&sc->sc_wchan);
   3567 	}
   3568 }
   3569 
   3570 /*
   3571  * Called from HW driver module on completion of DMA input.
   3572  * Mark it as input in the ring buffer (fiddle pointers).
   3573  * Do a wakeup if necessary.
   3574  */
   3575 void
   3576 audio_rint(void *v)
   3577 {
   3578 	struct audio_softc *sc;
   3579 	int blksize;
   3580 
   3581 	sc = v;
   3582 
   3583 	if (sc->sc_dying == true)
   3584 		return;
   3585 
   3586 	blksize = audio_stream_get_used(&sc->sc_rr.s);
   3587 	sc->sc_rr.s.outp = audio_stream_add_outp(&sc->sc_rr.s,
   3588 	    sc->sc_rr.s.outp, blksize);
   3589 	mix_read(sc);
   3590 
   3591 	cv_broadcast(&sc->sc_rcondvar);
   3592 }
   3593 
   3594 void
   3595 audio_upmix(void *v)
   3596 {
   3597 	stream_fetcher_t null_fetcher;
   3598 	struct audio_softc *sc;
   3599 	struct audio_ringbuffer *cb;
   3600 	stream_fetcher_t *last_fetcher;
   3601 	struct virtual_channel *vc;
   3602 	int cc;
   3603 	int used;
   3604 	int blksize;
   3605 	int i;
   3606 	int n;
   3607 	int cc1;
   3608 
   3609 	sc = v;
   3610 	i = sc->sc_opens;
   3611 	blksize = sc->sc_vchan[0]->sc_mrr.blksize;
   3612 
   3613 	for (n = 1; n < VAUDIOCHANS; n++) {
   3614 		if (!sc->sc_opens || i <= 0)
   3615 			break;		/* ignore interrupt if not open */
   3616 
   3617 		if (sc->sc_audiopid[n].pid == -1)
   3618 			continue;
   3619 		i--;
   3620 		vc = sc->sc_vchan[n];
   3621 		if (!(vc->sc_open & AUOPEN_READ))
   3622 			continue;
   3623 		if (!vc->sc_rbus)
   3624 			continue;
   3625 
   3626 		cb = &vc->sc_mrr;
   3627 
   3628 		blksize = audio_stream_get_used(&sc->sc_rr.s);
   3629 		if (audio_stream_get_space(&cb->s) < blksize) {
   3630 			cb->drops += blksize;
   3631 			cb->s.outp = audio_stream_add_outp(&cb->s, cb->s.outp,
   3632 			    sc->sc_rr.blksize);
   3633 			continue;
   3634 		}
   3635 
   3636 		cc = blksize;
   3637 		if (cb->s.inp + blksize > cb->s.end)
   3638 			cc = cb->s.end - cb->s.inp;
   3639 		memcpy(cb->s.inp, sc->sc_rr.s.start, cc);
   3640 		if (cc < blksize && cc != 0) {
   3641 			cc1 = cc;
   3642 			cc = blksize - cc;
   3643 			memcpy(cb->s.start, sc->sc_rr.s.start + cc1, cc);
   3644 		}
   3645 
   3646 		cc = blksize;
   3647 		recswvol_func(sc, cb, n, blksize);
   3648 
   3649 		cb->s.inp = audio_stream_add_inp(&cb->s, cb->s.inp, blksize);
   3650 		cb->stamp += blksize;
   3651 		if (cb->mmapped) {
   3652 			DPRINTFN(2, ("audio_rint: mmapped inp=%p cc=%d\n",
   3653 			     	cb->s.inp, blksize));
   3654 			continue;
   3655 		}
   3656 
   3657 #ifdef AUDIO_INTR_TIME
   3658 		{
   3659 			struct timeval tv;
   3660 			u_long t;
   3661 			microtime(&tv);
   3662 			t = tv.tv_usec + 1000000 * tv.tv_sec;
   3663 			if (sc->sc_rnintr) {
   3664 				long lastdelta, totdelta;
   3665 				lastdelta = t - sc->sc_rlastintr -
   3666 				    sc->sc_rblktime;
   3667 				if (lastdelta > sc->sc_rblktime / 5) {
   3668 					printf("audio: record interrupt(%d) "
   3669 					       "off relative by %ld us (%lu)\n",
   3670 					       sc->sc_rnintr, lastdelta,
   3671 					       sc->sc_rblktime);
   3672 				}
   3673 				totdelta = t - sc->sc_rfirstintr -
   3674 					sc->sc_rblktime * sc->sc_rnintr;
   3675 				if (totdelta > sc->sc_rblktime / 2) {
   3676 					sc->sc_rnintr++;
   3677 					printf("audio: record interrupt(%d) "
   3678 					       "off absolute by %ld us (%lu)\n",
   3679 					       sc->sc_rnintr, totdelta,
   3680 					       sc->sc_rblktime);
   3681 					sc->sc_rnintr++;
   3682 					/* avoid repeated messages */
   3683 				}
   3684 			} else
   3685 				sc->sc_rfirstintr = t;
   3686 			sc->sc_rlastintr = t;
   3687 			sc->sc_rnintr++;
   3688 		}
   3689 #endif
   3690 
   3691 		if (!cb->pause && vc->sc_nrfilters > 0) {
   3692 			null_fetcher.fetch_to = null_fetcher_fetch_to;
   3693 			last_fetcher =
   3694 			    &vc->sc_rfilters[vc->sc_nrfilters - 1]->base;
   3695 			vc->sc_rfilters[0]->set_fetcher(vc->sc_rfilters[0],
   3696 							&null_fetcher);
   3697 			used = audio_stream_get_used(vc->sc_rustream);
   3698 			cc = vc->sc_rustream->end - vc->sc_rustream->start;
   3699 			last_fetcher->fetch_to
   3700 				(sc, last_fetcher, vc->sc_rustream, cc);
   3701 			cb->fstamp += audio_stream_get_used(vc->sc_rustream) -
   3702 			    used;
   3703 			/* XXX what should do for error? */
   3704 		}
   3705 		used = audio_stream_get_used(&vc->sc_mrr.s);
   3706 		if (cb->pause) {
   3707 			DPRINTFN(1, ("audio_rint: pdrops %lu\n", cb->pdrops));
   3708 			cb->pdrops += blksize;
   3709 			cb->s.outp = audio_stream_add_outp(&cb->s, cb->s.outp,
   3710 			    blksize);
   3711 		} else if (used + blksize > cb->s.end - cb->s.start &&
   3712 								!cb->copying) {
   3713 			DPRINTFN(1, ("audio_rint: drops %lu\n", cb->drops));
   3714 			cb->drops += blksize;
   3715 			cb->s.outp = audio_stream_add_outp(&cb->s, cb->s.outp,
   3716 			    blksize);
   3717 		}
   3718 	}
   3719 	kpreempt_disable();
   3720 	softint_schedule(sc->sc_sih_rd);
   3721 	kpreempt_enable();
   3722 }
   3723 
   3724 int
   3725 audio_check_params(struct audio_params *p)
   3726 {
   3727 
   3728 	if (p->encoding == AUDIO_ENCODING_PCM16) {
   3729 		if (p->precision == 8)
   3730 			p->encoding = AUDIO_ENCODING_ULINEAR;
   3731 		else
   3732 			p->encoding = AUDIO_ENCODING_SLINEAR;
   3733 	} else if (p->encoding == AUDIO_ENCODING_PCM8) {
   3734 		if (p->precision == 8)
   3735 			p->encoding = AUDIO_ENCODING_ULINEAR;
   3736 		else
   3737 			return EINVAL;
   3738 	}
   3739 
   3740 	if (p->encoding == AUDIO_ENCODING_SLINEAR)
   3741 #if BYTE_ORDER == LITTLE_ENDIAN
   3742 		p->encoding = AUDIO_ENCODING_SLINEAR_LE;
   3743 #else
   3744 		p->encoding = AUDIO_ENCODING_SLINEAR_BE;
   3745 #endif
   3746 	if (p->encoding == AUDIO_ENCODING_ULINEAR)
   3747 #if BYTE_ORDER == LITTLE_ENDIAN
   3748 		p->encoding = AUDIO_ENCODING_ULINEAR_LE;
   3749 #else
   3750 		p->encoding = AUDIO_ENCODING_ULINEAR_BE;
   3751 #endif
   3752 
   3753 	switch (p->encoding) {
   3754 	case AUDIO_ENCODING_ULAW:
   3755 	case AUDIO_ENCODING_ALAW:
   3756 		if (p->precision != 8)
   3757 			return EINVAL;
   3758 		break;
   3759 	case AUDIO_ENCODING_ADPCM:
   3760 		if (p->precision != 4 && p->precision != 8)
   3761 			return EINVAL;
   3762 		break;
   3763 	case AUDIO_ENCODING_SLINEAR_LE:
   3764 	case AUDIO_ENCODING_SLINEAR_BE:
   3765 	case AUDIO_ENCODING_ULINEAR_LE:
   3766 	case AUDIO_ENCODING_ULINEAR_BE:
   3767 		/* XXX is: our zero-fill can handle any multiple of 8 */
   3768 		if (p->precision !=  8 && p->precision != 16 &&
   3769 		    p->precision != 24 && p->precision != 32)
   3770 			return EINVAL;
   3771 		if (p->precision == 8 && p->encoding ==
   3772 		    AUDIO_ENCODING_SLINEAR_BE)
   3773 			p->encoding = AUDIO_ENCODING_SLINEAR_LE;
   3774 		if (p->precision == 8 && p->encoding ==
   3775 		    AUDIO_ENCODING_ULINEAR_BE)
   3776 			p->encoding = AUDIO_ENCODING_ULINEAR_LE;
   3777 		if (p->validbits > p->precision)
   3778 			return EINVAL;
   3779 		break;
   3780 	case AUDIO_ENCODING_MPEG_L1_STREAM:
   3781 	case AUDIO_ENCODING_MPEG_L1_PACKETS:
   3782 	case AUDIO_ENCODING_MPEG_L1_SYSTEM:
   3783 	case AUDIO_ENCODING_MPEG_L2_STREAM:
   3784 	case AUDIO_ENCODING_MPEG_L2_PACKETS:
   3785 	case AUDIO_ENCODING_MPEG_L2_SYSTEM:
   3786 	case AUDIO_ENCODING_AC3:
   3787 		break;
   3788 	default:
   3789 		return EINVAL;
   3790 	}
   3791 
   3792 	/* sanity check # of channels*/
   3793 	if (p->channels < 1 || p->channels > AUDIO_MAX_CHANNELS)
   3794 		return EINVAL;
   3795 
   3796 	return 0;
   3797 }
   3798 
   3799 static int
   3800 audio_set_vchan_defaults(struct audio_softc *sc, u_int mode,
   3801      const struct audio_format *format, int n)
   3802 {
   3803 	struct virtual_channel *vc = sc->sc_vchan[n];
   3804 	struct audio_info ai;
   3805 	int error;
   3806 
   3807 	KASSERT(mutex_owned(sc->sc_lock));
   3808 
   3809 	sc->sc_vchan_params.sample_rate = sc->sc_iffreq;
   3810 #if BYTE_ORDER == LITTLE_ENDIAN
   3811 	sc->sc_vchan_params.encoding = AUDIO_ENCODING_SLINEAR_LE;
   3812 #else
   3813 	sc->sc_vchan_params.encoding = AUDIO_ENCODING_SLINEAR_BE;
   3814 #endif
   3815 	sc->sc_vchan_params.precision = sc->sc_precision;
   3816 	sc->sc_vchan_params.validbits = sc->sc_precision;
   3817 	sc->sc_vchan_params.channels = sc->sc_channels;
   3818 
   3819 	/* default parameters */
   3820 	vc->sc_rparams = sc->sc_vchan_params;
   3821 	vc->sc_pparams = sc->sc_vchan_params;
   3822 	vc->sc_blkset = false;
   3823 
   3824 	AUDIO_INITINFO(&ai);
   3825 	ai.record.sample_rate = sc->sc_iffreq;
   3826 	ai.record.encoding    = format->encoding;
   3827 	ai.record.channels    = sc->sc_channels;
   3828 	ai.record.precision   = sc->sc_precision;
   3829 	ai.record.pause	      = false;
   3830 	ai.play.sample_rate   = sc->sc_iffreq;
   3831 	ai.play.encoding      = format->encoding;
   3832 	ai.play.channels      = sc->sc_channels;
   3833 	ai.play.precision     = sc->sc_precision;
   3834 	ai.play.pause         = false;
   3835 	ai.mode		      = mode;
   3836 
   3837 	sc->sc_format->channels = sc->sc_channels;
   3838 	sc->sc_format->precision = sc->sc_precision;
   3839 	sc->sc_format->validbits = sc->sc_precision;
   3840 	sc->sc_format->frequency[0] = sc->sc_iffreq;
   3841 
   3842 	auconv_delete_encodings(sc->sc_encodings);
   3843 	error = auconv_create_encodings(sc->sc_format, VAUDIO_NFORMATS,
   3844 	    &sc->sc_encodings);
   3845 
   3846 	if (error == 0)
   3847 		error = audiosetinfo(sc, &ai, true, n);
   3848 
   3849 	if (error)
   3850 		aprint_error("Invalid channel format, please check hardware "
   3851 			     "capabilities\n");
   3852 	return error;
   3853 }
   3854 
   3855 int
   3856 audio_set_defaults(struct audio_softc *sc, u_int mode, int n)
   3857 {
   3858 	struct virtual_channel *vc = sc->sc_vchan[n];
   3859 	struct audio_info ai;
   3860 
   3861 	KASSERT(mutex_owned(sc->sc_lock));
   3862 
   3863 	/* default parameters */
   3864 	vc->sc_rparams = audio_default;
   3865 	vc->sc_pparams = audio_default;
   3866 	vc->sc_blkset = false;
   3867 
   3868 	AUDIO_INITINFO(&ai);
   3869 	ai.record.sample_rate = vc->sc_rparams.sample_rate;
   3870 	ai.record.encoding    = vc->sc_rparams.encoding;
   3871 	ai.record.channels    = vc->sc_rparams.channels;
   3872 	ai.record.precision   = vc->sc_rparams.precision;
   3873 	ai.record.pause	      = false;
   3874 	ai.play.sample_rate   = vc->sc_pparams.sample_rate;
   3875 	ai.play.encoding      = vc->sc_pparams.encoding;
   3876 	ai.play.channels      = vc->sc_pparams.channels;
   3877 	ai.play.precision     = vc->sc_pparams.precision;
   3878 	ai.play.pause         = false;
   3879 	ai.mode		      = mode;
   3880 
   3881 	return audiosetinfo(sc, &ai, true, n);
   3882 }
   3883 
   3884 int
   3885 au_set_lr_value(struct	audio_softc *sc, mixer_ctrl_t *ct, int l, int r)
   3886 {
   3887 
   3888 	KASSERT(mutex_owned(sc->sc_lock));
   3889 
   3890 	ct->type = AUDIO_MIXER_VALUE;
   3891 	ct->un.value.num_channels = 2;
   3892 	ct->un.value.level[AUDIO_MIXER_LEVEL_LEFT] = l;
   3893 	ct->un.value.level[AUDIO_MIXER_LEVEL_RIGHT] = r;
   3894 	if (audio_set_port(sc, ct) == 0)
   3895 		return 0;
   3896 	ct->un.value.num_channels = 1;
   3897 	ct->un.value.level[AUDIO_MIXER_LEVEL_MONO] = (l+r)/2;
   3898 	return audio_set_port(sc, ct);
   3899 }
   3900 
   3901 int
   3902 au_set_gain(struct audio_softc *sc, struct au_mixer_ports *ports,
   3903 	    int gain, int balance)
   3904 {
   3905 	mixer_ctrl_t ct;
   3906 	int i, error;
   3907 	int l, r;
   3908 	u_int mask;
   3909 	int nset;
   3910 
   3911 	KASSERT(mutex_owned(sc->sc_lock));
   3912 
   3913 	if (balance == AUDIO_MID_BALANCE) {
   3914 		l = r = gain;
   3915 	} else if (balance < AUDIO_MID_BALANCE) {
   3916 		l = gain;
   3917 		r = (balance * gain) / AUDIO_MID_BALANCE;
   3918 	} else {
   3919 		r = gain;
   3920 		l = ((AUDIO_RIGHT_BALANCE - balance) * gain)
   3921 		    / AUDIO_MID_BALANCE;
   3922 	}
   3923 	DPRINTF(("au_set_gain: gain=%d balance=%d, l=%d r=%d\n",
   3924 		 gain, balance, l, r));
   3925 
   3926 	if (ports->index == -1) {
   3927 	usemaster:
   3928 		if (ports->master == -1)
   3929 			return 0; /* just ignore it silently */
   3930 		ct.dev = ports->master;
   3931 		error = au_set_lr_value(sc, &ct, l, r);
   3932 	} else {
   3933 		ct.dev = ports->index;
   3934 		if (ports->isenum) {
   3935 			ct.type = AUDIO_MIXER_ENUM;
   3936 			error = audio_get_port(sc, &ct);
   3937 			if (error)
   3938 				return error;
   3939 			if (ports->isdual) {
   3940 				if (ports->cur_port == -1)
   3941 					ct.dev = ports->master;
   3942 				else
   3943 					ct.dev = ports->miport[ports->cur_port];
   3944 				error = au_set_lr_value(sc, &ct, l, r);
   3945 			} else {
   3946 				for(i = 0; i < ports->nports; i++)
   3947 				    if (ports->misel[i] == ct.un.ord) {
   3948 					    ct.dev = ports->miport[i];
   3949 					    if (ct.dev == -1 ||
   3950 						au_set_lr_value(sc, &ct, l, r))
   3951 						    goto usemaster;
   3952 					    else
   3953 						    break;
   3954 				    }
   3955 			}
   3956 		} else {
   3957 			ct.type = AUDIO_MIXER_SET;
   3958 			error = audio_get_port(sc, &ct);
   3959 			if (error)
   3960 				return error;
   3961 			mask = ct.un.mask;
   3962 			nset = 0;
   3963 			for(i = 0; i < ports->nports; i++) {
   3964 				if (ports->misel[i] & mask) {
   3965 				    ct.dev = ports->miport[i];
   3966 				    if (ct.dev != -1 &&
   3967 					au_set_lr_value(sc, &ct, l, r) == 0)
   3968 					    nset++;
   3969 				}
   3970 			}
   3971 			if (nset == 0)
   3972 				goto usemaster;
   3973 		}
   3974 	}
   3975 	if (!error)
   3976 		mixer_signal(sc);
   3977 	return error;
   3978 }
   3979 
   3980 int
   3981 au_get_lr_value(struct	audio_softc *sc, mixer_ctrl_t *ct, int *l, int *r)
   3982 {
   3983 	int error;
   3984 
   3985 	KASSERT(mutex_owned(sc->sc_lock));
   3986 
   3987 	ct->un.value.num_channels = 2;
   3988 	if (audio_get_port(sc, ct) == 0) {
   3989 		*l = ct->un.value.level[AUDIO_MIXER_LEVEL_LEFT];
   3990 		*r = ct->un.value.level[AUDIO_MIXER_LEVEL_RIGHT];
   3991 	} else {
   3992 		ct->un.value.num_channels = 1;
   3993 		error = audio_get_port(sc, ct);
   3994 		if (error)
   3995 			return error;
   3996 		*r = *l = ct->un.value.level[AUDIO_MIXER_LEVEL_MONO];
   3997 	}
   3998 	return 0;
   3999 }
   4000 
   4001 void
   4002 au_get_gain(struct audio_softc *sc, struct au_mixer_ports *ports,
   4003 	    u_int *pgain, u_char *pbalance)
   4004 {
   4005 	mixer_ctrl_t ct;
   4006 	int i, l, r, n;
   4007 	int lgain, rgain;
   4008 
   4009 	KASSERT(mutex_owned(sc->sc_lock));
   4010 
   4011 	lgain = AUDIO_MAX_GAIN / 2;
   4012 	rgain = AUDIO_MAX_GAIN / 2;
   4013 	if (ports->index == -1) {
   4014 	usemaster:
   4015 		if (ports->master == -1)
   4016 			goto bad;
   4017 		ct.dev = ports->master;
   4018 		ct.type = AUDIO_MIXER_VALUE;
   4019 		if (au_get_lr_value(sc, &ct, &lgain, &rgain))
   4020 			goto bad;
   4021 	} else {
   4022 		ct.dev = ports->index;
   4023 		if (ports->isenum) {
   4024 			ct.type = AUDIO_MIXER_ENUM;
   4025 			if (audio_get_port(sc, &ct))
   4026 				goto bad;
   4027 			ct.type = AUDIO_MIXER_VALUE;
   4028 			if (ports->isdual) {
   4029 				if (ports->cur_port == -1)
   4030 					ct.dev = ports->master;
   4031 				else
   4032 					ct.dev = ports->miport[ports->cur_port];
   4033 				au_get_lr_value(sc, &ct, &lgain, &rgain);
   4034 			} else {
   4035 				for(i = 0; i < ports->nports; i++)
   4036 				    if (ports->misel[i] == ct.un.ord) {
   4037 					    ct.dev = ports->miport[i];
   4038 					    if (ct.dev == -1 ||
   4039 						au_get_lr_value(sc, &ct,
   4040 								&lgain, &rgain))
   4041 						    goto usemaster;
   4042 					    else
   4043 						    break;
   4044 				    }
   4045 			}
   4046 		} else {
   4047 			ct.type = AUDIO_MIXER_SET;
   4048 			if (audio_get_port(sc, &ct))
   4049 				goto bad;
   4050 			ct.type = AUDIO_MIXER_VALUE;
   4051 			lgain = rgain = n = 0;
   4052 			for(i = 0; i < ports->nports; i++) {
   4053 				if (ports->misel[i] & ct.un.mask) {
   4054 					ct.dev = ports->miport[i];
   4055 					if (ct.dev == -1 ||
   4056 					    au_get_lr_value(sc, &ct, &l, &r))
   4057 						goto usemaster;
   4058 					else {
   4059 						lgain += l;
   4060 						rgain += r;
   4061 						n++;
   4062 					}
   4063 				}
   4064 			}
   4065 			if (n != 0) {
   4066 				lgain /= n;
   4067 				rgain /= n;
   4068 			}
   4069 		}
   4070 	}
   4071 bad:
   4072 	if (lgain == rgain) {	/* handles lgain==rgain==0 */
   4073 		*pgain = lgain;
   4074 		*pbalance = AUDIO_MID_BALANCE;
   4075 	} else if (lgain < rgain) {
   4076 		*pgain = rgain;
   4077 		/* balance should be > AUDIO_MID_BALANCE */
   4078 		*pbalance = AUDIO_RIGHT_BALANCE -
   4079 			(AUDIO_MID_BALANCE * lgain) / rgain;
   4080 	} else /* lgain > rgain */ {
   4081 		*pgain = lgain;
   4082 		/* balance should be < AUDIO_MID_BALANCE */
   4083 		*pbalance = (AUDIO_MID_BALANCE * rgain) / lgain;
   4084 	}
   4085 }
   4086 
   4087 int
   4088 au_set_port(struct audio_softc *sc, struct au_mixer_ports *ports, u_int port)
   4089 {
   4090 	mixer_ctrl_t ct;
   4091 	int i, error, use_mixerout;
   4092 
   4093 	KASSERT(mutex_owned(sc->sc_lock));
   4094 
   4095 	use_mixerout = 1;
   4096 	if (port == 0) {
   4097 		if (ports->allports == 0)
   4098 			return 0;		/* Allow this special case. */
   4099 		else if (ports->isdual) {
   4100 			if (ports->cur_port == -1) {
   4101 				return 0;
   4102 			} else {
   4103 				port = ports->aumask[ports->cur_port];
   4104 				ports->cur_port = -1;
   4105 				use_mixerout = 0;
   4106 			}
   4107 		}
   4108 	}
   4109 	if (ports->index == -1)
   4110 		return EINVAL;
   4111 	ct.dev = ports->index;
   4112 	if (ports->isenum) {
   4113 		if (port & (port-1))
   4114 			return EINVAL; /* Only one port allowed */
   4115 		ct.type = AUDIO_MIXER_ENUM;
   4116 		error = EINVAL;
   4117 		for(i = 0; i < ports->nports; i++)
   4118 			if (ports->aumask[i] == port) {
   4119 				if (ports->isdual && use_mixerout) {
   4120 					ct.un.ord = ports->mixerout;
   4121 					ports->cur_port = i;
   4122 				} else {
   4123 					ct.un.ord = ports->misel[i];
   4124 				}
   4125 				error = audio_set_port(sc, &ct);
   4126 				break;
   4127 			}
   4128 	} else {
   4129 		ct.type = AUDIO_MIXER_SET;
   4130 		ct.un.mask = 0;
   4131 		for(i = 0; i < ports->nports; i++)
   4132 			if (ports->aumask[i] & port)
   4133 				ct.un.mask |= ports->misel[i];
   4134 		if (port != 0 && ct.un.mask == 0)
   4135 			error = EINVAL;
   4136 		else
   4137 			error = audio_set_port(sc, &ct);
   4138 	}
   4139 	if (!error)
   4140 		mixer_signal(sc);
   4141 	return error;
   4142 }
   4143 
   4144 int
   4145 au_get_port(struct audio_softc *sc, struct au_mixer_ports *ports)
   4146 {
   4147 	mixer_ctrl_t ct;
   4148 	int i, aumask;
   4149 
   4150 	KASSERT(mutex_owned(sc->sc_lock));
   4151 
   4152 	if (ports->index == -1)
   4153 		return 0;
   4154 	ct.dev = ports->index;
   4155 	ct.type = ports->isenum ? AUDIO_MIXER_ENUM : AUDIO_MIXER_SET;
   4156 	if (audio_get_port(sc, &ct))
   4157 		return 0;
   4158 	aumask = 0;
   4159 	if (ports->isenum) {
   4160 		if (ports->isdual && ports->cur_port != -1) {
   4161 			if (ports->mixerout == ct.un.ord)
   4162 				aumask = ports->aumask[ports->cur_port];
   4163 			else
   4164 				ports->cur_port = -1;
   4165 		}
   4166 		if (aumask == 0)
   4167 			for(i = 0; i < ports->nports; i++)
   4168 				if (ports->misel[i] == ct.un.ord)
   4169 					aumask = ports->aumask[i];
   4170 	} else {
   4171 		for(i = 0; i < ports->nports; i++)
   4172 			if (ct.un.mask & ports->misel[i])
   4173 				aumask |= ports->aumask[i];
   4174 	}
   4175 	return aumask;
   4176 }
   4177 
   4178 int
   4179 audiosetinfo(struct audio_softc *sc, struct audio_info *ai, bool reset, int n)
   4180 {
   4181 	stream_filter_list_t pfilters, rfilters;
   4182 	audio_params_t pp, rp;
   4183 	struct audio_prinfo *r, *p;
   4184 	const struct audio_hw_if *hw;
   4185 	struct virtual_channel *vc;
   4186 	audio_stream_t *oldpus, *oldrus;
   4187 	int setmode;
   4188 	int error;
   4189 	int np, nr;
   4190 	unsigned int blks;
   4191 	int oldpblksize, oldrblksize;
   4192 	u_int gain;
   4193 	bool rbus, pbus;
   4194 	bool cleared, modechange, pausechange;
   4195 	u_char balance;
   4196 
   4197 	KASSERT(mutex_owned(sc->sc_lock));
   4198 
   4199 	vc = sc->sc_vchan[n];
   4200 	hw = sc->hw_if;
   4201 	if (hw == NULL)		/* HW has not attached */
   4202 		return ENXIO;
   4203 
   4204 	DPRINTF(("%s sc=%p ai=%p\n", __func__, sc, ai));
   4205 	r = &ai->record;
   4206 	p = &ai->play;
   4207 	rbus = vc->sc_rbus;
   4208 	pbus = vc->sc_pbus;
   4209 	error = 0;
   4210 	cleared = false;
   4211 	modechange = false;
   4212 	pausechange = false;
   4213 
   4214 	pp = vc->sc_pparams;	/* Temporary encoding storage in */
   4215 	rp = vc->sc_rparams;	/* case setting the modes fails. */
   4216 	nr = np = 0;
   4217 
   4218 	if (SPECIFIED(p->sample_rate)) {
   4219 		pp.sample_rate = p->sample_rate;
   4220 		np++;
   4221 	}
   4222 	if (SPECIFIED(r->sample_rate)) {
   4223 		rp.sample_rate = r->sample_rate;
   4224 		nr++;
   4225 	}
   4226 	if (SPECIFIED(p->encoding)) {
   4227 		pp.encoding = p->encoding;
   4228 		np++;
   4229 	}
   4230 	if (SPECIFIED(r->encoding)) {
   4231 		rp.encoding = r->encoding;
   4232 		nr++;
   4233 	}
   4234 	if (SPECIFIED(p->precision)) {
   4235 		pp.precision = p->precision;
   4236 		/* we don't have API to specify validbits */
   4237 		pp.validbits = p->precision;
   4238 		np++;
   4239 	}
   4240 	if (SPECIFIED(r->precision)) {
   4241 		rp.precision = r->precision;
   4242 		/* we don't have API to specify validbits */
   4243 		rp.validbits = r->precision;
   4244 		nr++;
   4245 	}
   4246 	if (SPECIFIED(p->channels)) {
   4247 		pp.channels = p->channels;
   4248 		np++;
   4249 	}
   4250 	if (SPECIFIED(r->channels)) {
   4251 		rp.channels = r->channels;
   4252 		nr++;
   4253 	}
   4254 
   4255 	if (!audio_can_capture(sc))
   4256 		nr = 0;
   4257 	if (!audio_can_playback(sc))
   4258 		np = 0;
   4259 
   4260 #ifdef AUDIO_DEBUG
   4261 	if (audiodebug && nr > 0)
   4262 	    audio_print_params("audiosetinfo() Setting record params:", &rp);
   4263 	if (audiodebug && np > 0)
   4264 	    audio_print_params("audiosetinfo() Setting play params:", &pp);
   4265 #endif
   4266 	if (nr > 0 && (error = audio_check_params(&rp)))
   4267 		return error;
   4268 	if (np > 0 && (error = audio_check_params(&pp)))
   4269 		return error;
   4270 
   4271 	oldpblksize = vc->sc_mpr.blksize;
   4272 	oldrblksize = vc->sc_mrr.blksize;
   4273 
   4274 	setmode = 0;
   4275 	if (nr > 0) {
   4276 		if (!cleared) {
   4277 			audio_clear_intr_unlocked(sc, n);
   4278 			cleared = true;
   4279 		}
   4280 		modechange = true;
   4281 		setmode |= AUMODE_RECORD;
   4282 	}
   4283 	if (np > 0) {
   4284 		if (!cleared) {
   4285 			audio_clear_intr_unlocked(sc, n);
   4286 			cleared = true;
   4287 		}
   4288 		modechange = true;
   4289 		setmode |= AUMODE_PLAY;
   4290 	}
   4291 
   4292 	if (SPECIFIED(ai->mode)) {
   4293 		if (!cleared) {
   4294 			audio_clear_intr_unlocked(sc, n);
   4295 			cleared = true;
   4296 		}
   4297 		modechange = true;
   4298 		vc->sc_mode = ai->mode;
   4299 		if (vc->sc_mode & AUMODE_PLAY_ALL)
   4300 			vc->sc_mode |= AUMODE_PLAY;
   4301 		if ((vc->sc_mode & AUMODE_PLAY) && !vc->sc_full_duplex)
   4302 			/* Play takes precedence */
   4303 			vc->sc_mode &= ~AUMODE_RECORD;
   4304 	}
   4305 
   4306 	oldpus = vc->sc_pustream;
   4307 	oldrus = vc->sc_rustream;
   4308 	if (modechange || reset) {
   4309 		int indep;
   4310 
   4311 		indep = audio_get_props(sc) & AUDIO_PROP_INDEPENDENT;
   4312 		if (!indep) {
   4313 			if (setmode == AUMODE_RECORD)
   4314 				pp = rp;
   4315 			else if (setmode == AUMODE_PLAY)
   4316 				rp = pp;
   4317 		}
   4318 		memset(&pfilters, 0, sizeof(pfilters));
   4319 		memset(&rfilters, 0, sizeof(rfilters));
   4320 		pfilters.append = stream_filter_list_append;
   4321 		pfilters.prepend = stream_filter_list_prepend;
   4322 		pfilters.set = stream_filter_list_set;
   4323 		rfilters.append = stream_filter_list_append;
   4324 		rfilters.prepend = stream_filter_list_prepend;
   4325 		rfilters.set = stream_filter_list_set;
   4326 		/* Some device drivers change channels/sample_rate and change
   4327 		 * no channels/sample_rate. */
   4328 		error = audio_set_params(sc, setmode,
   4329 		    vc->sc_mode & (AUMODE_PLAY | AUMODE_RECORD), &pp, &rp,
   4330 		    &pfilters, &rfilters, n);
   4331 		if (error) {
   4332 			DPRINTF(("%s: audio_set_params() failed with %d\n",
   4333 			    __func__, error));
   4334 			goto cleanup;
   4335 		}
   4336 
   4337 		audio_check_params(&pp);
   4338 		audio_check_params(&rp);
   4339 		if (!indep) {
   4340 			/* XXX for !indep device, we have to use the same
   4341 			 * parameters for the hardware, not userland */
   4342 			if (setmode == AUMODE_RECORD) {
   4343 				pp = rp;
   4344 			} else if (setmode == AUMODE_PLAY) {
   4345 				rp = pp;
   4346 			}
   4347 		}
   4348 
   4349 		if (vc->sc_mpr.mmapped && pfilters.req_size > 0) {
   4350 			DPRINTF(("%s: mmapped, and filters are requested.\n",
   4351 				 __func__));
   4352 			error = EINVAL;
   4353 			goto cleanup;
   4354 		}
   4355 
   4356 		/* construct new filter chain */
   4357 		if (setmode & AUMODE_PLAY) {
   4358 			error = audio_setup_pfilters(sc, &pp, &pfilters, n);
   4359 			if (error)
   4360 				goto cleanup;
   4361 		}
   4362 		if (setmode & AUMODE_RECORD) {
   4363 			error = audio_setup_rfilters(sc, &rp, &rfilters, n);
   4364 			if (error)
   4365 				goto cleanup;
   4366 		}
   4367 		DPRINTF(("%s: filter setup is completed.\n", __func__));
   4368 
   4369 		/* userland formats */
   4370 		vc->sc_pparams = pp;
   4371 		vc->sc_rparams = rp;
   4372 	}
   4373 
   4374 	/* Play params can affect the record params, so recalculate blksize. */
   4375 	if (nr > 0 || np > 0 || reset) {
   4376 		vc->sc_blkset = false;
   4377 		audio_calc_blksize(sc, AUMODE_RECORD, n);
   4378 		audio_calc_blksize(sc, AUMODE_PLAY, n);
   4379 	}
   4380 #ifdef AUDIO_DEBUG
   4381 	if (audiodebug > 1 && nr > 0) {
   4382 	    audio_print_params("audiosetinfo() After setting record params:",
   4383 		&vc->sc_rparams);
   4384 	}
   4385 	if (audiodebug > 1 && np > 0) {
   4386 	    audio_print_params("audiosetinfo() After setting play params:",
   4387 		&vc->sc_pparams);
   4388 	}
   4389 #endif
   4390 
   4391 	if (SPECIFIED(p->port)) {
   4392 		if (!cleared) {
   4393 			audio_clear_intr_unlocked(sc, n);
   4394 			cleared = true;
   4395 		}
   4396 		error = au_set_port(sc, &sc->sc_outports, p->port);
   4397 		if (error)
   4398 			goto cleanup;
   4399 	}
   4400 	if (SPECIFIED(r->port)) {
   4401 		if (!cleared) {
   4402 			audio_clear_intr_unlocked(sc, n);
   4403 			cleared = true;
   4404 		}
   4405 		error = au_set_port(sc, &sc->sc_inports, r->port);
   4406 		if (error)
   4407 			goto cleanup;
   4408 	}
   4409 	if (SPECIFIED(p->gain)) {
   4410 		au_get_gain(sc, &sc->sc_outports, &gain, &balance);
   4411 		error = au_set_gain(sc, &sc->sc_outports, p->gain, balance);
   4412 		if (error)
   4413 			goto cleanup;
   4414 	}
   4415 	if (SPECIFIED(r->gain)) {
   4416 		au_get_gain(sc, &sc->sc_inports, &gain, &balance);
   4417 		error = au_set_gain(sc, &sc->sc_inports, r->gain, balance);
   4418 		if (error)
   4419 			goto cleanup;
   4420 	}
   4421 
   4422 	if (SPECIFIED_CH(p->balance)) {
   4423 		au_get_gain(sc, &sc->sc_outports, &gain, &balance);
   4424 		error = au_set_gain(sc, &sc->sc_outports, gain, p->balance);
   4425 		if (error)
   4426 			goto cleanup;
   4427 	}
   4428 	if (SPECIFIED_CH(r->balance)) {
   4429 		au_get_gain(sc, &sc->sc_inports, &gain, &balance);
   4430 		error = au_set_gain(sc, &sc->sc_inports, gain, r->balance);
   4431 		if (error)
   4432 			goto cleanup;
   4433 	}
   4434 
   4435 	if (SPECIFIED(ai->monitor_gain) && sc->sc_monitor_port != -1) {
   4436 		mixer_ctrl_t ct;
   4437 
   4438 		ct.dev = sc->sc_monitor_port;
   4439 		ct.type = AUDIO_MIXER_VALUE;
   4440 		ct.un.value.num_channels = 1;
   4441 		ct.un.value.level[AUDIO_MIXER_LEVEL_MONO] = ai->monitor_gain;
   4442 		error = audio_set_port(sc, &ct);
   4443 		if (error)
   4444 			goto cleanup;
   4445 	}
   4446 
   4447 	if (SPECIFIED_CH(p->pause)) {
   4448 		vc->sc_mpr.pause = p->pause;
   4449 		pbus = !p->pause;
   4450 		pausechange = true;
   4451 	}
   4452 	if (SPECIFIED_CH(r->pause)) {
   4453 		vc->sc_mrr.pause = r->pause;
   4454 		rbus = !r->pause;
   4455 		pausechange = true;
   4456 	}
   4457 
   4458 	if (SPECIFIED(ai->blocksize) || reset) {
   4459 		int pblksize, rblksize;
   4460 
   4461 		/* Block size specified explicitly. */
   4462 		if (ai->blocksize == 0 || reset) {
   4463 			if (!cleared) {
   4464 				audio_clear_intr_unlocked(sc, n);
   4465 				cleared = true;
   4466 			}
   4467 			vc->sc_blkset = false;
   4468 			audio_calc_blksize(sc, AUMODE_RECORD, n);
   4469 			audio_calc_blksize(sc, AUMODE_PLAY, n);
   4470 		} else {
   4471 			vc->sc_blkset = true;
   4472 			/* check whether new blocksize changes actually */
   4473 			if (hw->round_blocksize == NULL) {
   4474 				if (!cleared) {
   4475 					audio_clear_intr_unlocked(sc, n);
   4476 					cleared = true;
   4477 				}
   4478 				vc->sc_mpr.blksize = ai->blocksize;
   4479 				vc->sc_mrr.blksize = ai->blocksize;
   4480 			} else {
   4481 				pblksize = hw->round_blocksize(sc->hw_hdl,
   4482 				    ai->blocksize, AUMODE_PLAY,
   4483 				    &vc->sc_mpr.s.param);
   4484 				rblksize = hw->round_blocksize(sc->hw_hdl,
   4485 				    ai->blocksize, AUMODE_RECORD,
   4486 				    &vc->sc_mrr.s.param);
   4487 				if ((pblksize != vc->sc_mpr.blksize &&
   4488 				    pblksize > sc->sc_vchan[0]->sc_mpr.blksize)
   4489 				    || (rblksize != vc->sc_mrr.blksize &&
   4490 				    rblksize >
   4491 					sc->sc_vchan[0]->sc_mrr.blksize)) {
   4492 					if (!cleared) {
   4493 					    audio_clear_intr_unlocked(sc, n);
   4494 					    cleared = true;
   4495 					}
   4496 					vc->sc_mpr.blksize = pblksize;
   4497 					vc->sc_mrr.blksize = rblksize;
   4498 				}
   4499 			}
   4500 		}
   4501 	}
   4502 
   4503 	if (SPECIFIED(ai->mode)) {
   4504 		if (vc->sc_mode & AUMODE_PLAY)
   4505 			audio_init_play(sc, n);
   4506 		if (vc->sc_mode & AUMODE_RECORD)
   4507 			audio_init_record(sc, n);
   4508 	}
   4509 
   4510 	if (hw->commit_settings && sc->sc_opens == 0) {
   4511 		error = hw->commit_settings(sc->hw_hdl);
   4512 		if (error)
   4513 			goto cleanup;
   4514 	}
   4515 
   4516 	vc->sc_lastinfo = *ai;
   4517 	vc->sc_lastinfovalid = true;
   4518 
   4519 cleanup:
   4520 	if (cleared || pausechange|| reset) {
   4521 		int init_error;
   4522 
   4523 		mutex_enter(sc->sc_intr_lock);
   4524 		init_error = (pausechange == 1 && reset == 0) ? 0 :
   4525 		    audio_initbufs(sc, n);
   4526 		if (init_error) goto err;
   4527 		if (vc->sc_mpr.blksize != oldpblksize ||
   4528 		    vc->sc_mrr.blksize != oldrblksize ||
   4529 		    vc->sc_pustream != oldpus ||
   4530 		    vc->sc_rustream != oldrus)
   4531 			audio_calcwater(sc, n);
   4532 		if ((vc->sc_mode & AUMODE_PLAY) &&
   4533 		    pbus && !vc->sc_pbus)
   4534 			init_error = audiostartp(sc, n);
   4535 		if (!init_error &&
   4536 		    (vc->sc_mode & AUMODE_RECORD) &&
   4537 		    rbus && !vc->sc_rbus)
   4538 			init_error = audiostartr(sc, n);
   4539 	err:
   4540 		mutex_exit(sc->sc_intr_lock);
   4541 		if (init_error)
   4542 			return init_error;
   4543 	}
   4544 
   4545 	/* Change water marks after initializing the buffers. */
   4546 	if (SPECIFIED(ai->hiwat)) {
   4547 		blks = ai->hiwat;
   4548 		if (blks > vc->sc_mpr.maxblks)
   4549 			blks = vc->sc_mpr.maxblks;
   4550 		if (blks < 2)
   4551 			blks = 2;
   4552 		vc->sc_mpr.usedhigh = blks * vc->sc_mpr.blksize;
   4553 	}
   4554 	if (SPECIFIED(ai->lowat)) {
   4555 		blks = ai->lowat;
   4556 		if (blks > vc->sc_mpr.maxblks - 1)
   4557 			blks = vc->sc_mpr.maxblks - 1;
   4558 		vc->sc_mpr.usedlow = blks * vc->sc_mpr.blksize;
   4559 	}
   4560 	if (SPECIFIED(ai->hiwat) || SPECIFIED(ai->lowat)) {
   4561 		if (vc->sc_mpr.usedlow > vc->sc_mpr.usedhigh -
   4562 		    vc->sc_mpr.blksize) {
   4563 			vc->sc_mpr.usedlow =
   4564 				vc->sc_mpr.usedhigh - vc->sc_mpr.blksize;
   4565 		}
   4566 	}
   4567 
   4568 	return error;
   4569 }
   4570 
   4571 int
   4572 audiogetinfo(struct audio_softc *sc, struct audio_info *ai, int buf_only_mode,
   4573     int n)
   4574 {
   4575 	struct audio_prinfo *r, *p;
   4576 	const struct audio_hw_if *hw;
   4577 	struct virtual_channel *vc;
   4578 
   4579 	KASSERT(mutex_owned(sc->sc_lock));
   4580 
   4581 	r = &ai->record;
   4582 	p = &ai->play;
   4583 	vc = sc->sc_vchan[n];
   4584 	hw = sc->hw_if;
   4585 	if (hw == NULL)		/* HW has not attached */
   4586 		return ENXIO;
   4587 
   4588 	p->sample_rate = vc->sc_pparams.sample_rate;
   4589 	r->sample_rate = vc->sc_rparams.sample_rate;
   4590 	p->channels = vc->sc_pparams.channels;
   4591 	r->channels = vc->sc_rparams.channels;
   4592 	p->precision = vc->sc_pparams.precision;
   4593 	r->precision = vc->sc_rparams.precision;
   4594 	p->encoding = vc->sc_pparams.encoding;
   4595 	r->encoding = vc->sc_rparams.encoding;
   4596 
   4597 	if (buf_only_mode) {
   4598 		r->port = 0;
   4599 		p->port = 0;
   4600 
   4601 		r->avail_ports = 0;
   4602 		p->avail_ports = 0;
   4603 
   4604 		r->gain = 0;
   4605 		r->balance = 0;
   4606 
   4607 		p->gain = 0;
   4608 		p->balance = 0;
   4609 	} else {
   4610 		r->port = au_get_port(sc, &sc->sc_inports);
   4611 		p->port = au_get_port(sc, &sc->sc_outports);
   4612 
   4613 		r->avail_ports = sc->sc_inports.allports;
   4614 		p->avail_ports = sc->sc_outports.allports;
   4615 
   4616 		au_get_gain(sc, &sc->sc_inports, &r->gain, &r->balance);
   4617 		au_get_gain(sc, &sc->sc_outports, &p->gain, &p->balance);
   4618 	}
   4619 
   4620 	if (sc->sc_monitor_port != -1 && buf_only_mode == 0) {
   4621 		mixer_ctrl_t ct;
   4622 
   4623 		ct.dev = sc->sc_monitor_port;
   4624 		ct.type = AUDIO_MIXER_VALUE;
   4625 		ct.un.value.num_channels = 1;
   4626 		if (audio_get_port(sc, &ct))
   4627 			ai->monitor_gain = 0;
   4628 		else
   4629 			ai->monitor_gain =
   4630 				ct.un.value.level[AUDIO_MIXER_LEVEL_MONO];
   4631 	} else
   4632 		ai->monitor_gain = 0;
   4633 
   4634 	p->seek = audio_stream_get_used(vc->sc_pustream);
   4635 	r->seek = audio_stream_get_used(vc->sc_rustream);
   4636 
   4637 	/*
   4638 	 * XXX samples should be a value for userland data.
   4639 	 * But drops is a value for HW data.
   4640 	 */
   4641 	p->samples = (vc->sc_pustream == &vc->sc_mpr.s
   4642 	    ? vc->sc_mpr.stamp : vc->sc_mpr.fstamp) - vc->sc_mpr.drops;
   4643 	r->samples = (vc->sc_rustream == &vc->sc_mrr.s
   4644 	    ? vc->sc_mrr.stamp : vc->sc_mrr.fstamp) - vc->sc_mrr.drops;
   4645 
   4646 	p->eof = sc->sc_eof;
   4647 	r->eof = 0;
   4648 
   4649 	p->pause = vc->sc_mpr.pause;
   4650 	r->pause = vc->sc_mrr.pause;
   4651 
   4652 	p->error = vc->sc_mpr.drops != 0;
   4653 	r->error = vc->sc_mrr.drops != 0;
   4654 
   4655 	p->waiting = r->waiting = 0;		/* open never hangs */
   4656 
   4657 	p->open = (vc->sc_open & AUOPEN_WRITE) != 0;
   4658 	r->open = (vc->sc_open & AUOPEN_READ) != 0;
   4659 
   4660 	p->active = vc->sc_pbus;
   4661 	r->active = vc->sc_rbus;
   4662 
   4663 	p->buffer_size = vc->sc_pustream ? vc->sc_pustream->bufsize : 0;
   4664 	r->buffer_size = vc->sc_rustream ? vc->sc_rustream->bufsize : 0;
   4665 
   4666 	ai->blocksize = vc->sc_mpr.blksize;
   4667 	if (vc->sc_mpr.blksize > 0) {
   4668 		ai->hiwat = vc->sc_mpr.usedhigh / vc->sc_mpr.blksize;
   4669 		ai->lowat = vc->sc_mpr.usedlow / vc->sc_mpr.blksize;
   4670 	} else
   4671 		ai->hiwat = ai->lowat = 0;
   4672 	ai->mode = vc->sc_mode;
   4673 
   4674 	return 0;
   4675 }
   4676 
   4677 /*
   4678  * Mixer driver
   4679  */
   4680 int
   4681 mixer_open(dev_t dev, struct audio_softc *sc, int flags,
   4682     int ifmt, struct lwp *l)
   4683 {
   4684 
   4685 	KASSERT(mutex_owned(sc->sc_lock));
   4686 
   4687 	if (sc->hw_if == NULL)
   4688 		return  ENXIO;
   4689 
   4690 	DPRINTF(("mixer_open: flags=0x%x sc=%p\n", flags, sc));
   4691 
   4692 	return 0;
   4693 }
   4694 
   4695 /*
   4696  * Remove a process from those to be signalled on mixer activity.
   4697  */
   4698 static void
   4699 mixer_remove(struct audio_softc *sc)
   4700 {
   4701 	struct mixer_asyncs **pm, *m;
   4702 	pid_t pid;
   4703 
   4704 	KASSERT(mutex_owned(sc->sc_lock));
   4705 
   4706 	pid = curproc->p_pid;
   4707 	for (pm = &sc->sc_async_mixer; *pm; pm = &(*pm)->next) {
   4708 		if ((*pm)->pid == pid) {
   4709 			m = *pm;
   4710 			*pm = m->next;
   4711 			kmem_free(m, sizeof(*m));
   4712 			return;
   4713 		}
   4714 	}
   4715 }
   4716 
   4717 /*
   4718  * Signal all processes waiting for the mixer.
   4719  */
   4720 static void
   4721 mixer_signal(struct audio_softc *sc)
   4722 {
   4723 	struct mixer_asyncs *m;
   4724 	proc_t *p;
   4725 
   4726 	for (m = sc->sc_async_mixer; m; m = m->next) {
   4727 		mutex_enter(proc_lock);
   4728 		if ((p = proc_find(m->pid)) != NULL)
   4729 			psignal(p, SIGIO);
   4730 		mutex_exit(proc_lock);
   4731 	}
   4732 }
   4733 
   4734 /*
   4735  * Close a mixer device
   4736  */
   4737 /* ARGSUSED */
   4738 int
   4739 mixer_close(struct audio_softc *sc, int flags, int ifmt, struct lwp *l)
   4740 {
   4741 
   4742 	KASSERT(mutex_owned(sc->sc_lock));
   4743 	if (sc->hw_if == NULL)
   4744 		return ENXIO;
   4745 
   4746 	DPRINTF(("mixer_close: sc %p\n", sc));
   4747 	mixer_remove(sc);
   4748 	return 0;
   4749 }
   4750 
   4751 int
   4752 mixer_ioctl(struct audio_softc *sc, u_long cmd, void *addr, int flag,
   4753 	    struct lwp *l)
   4754 {
   4755 	const struct audio_hw_if *hw;
   4756 	struct mixer_asyncs *ma;
   4757 	mixer_ctrl_t *mc;
   4758 	int error;
   4759 
   4760 	DPRINTF(("mixer_ioctl(%lu,'%c',%lu)\n",
   4761 		 IOCPARM_LEN(cmd), (char)IOCGROUP(cmd), cmd&0xff));
   4762 	hw = sc->hw_if;
   4763 	if (hw == NULL)
   4764 		return ENXIO;
   4765 	error = EINVAL;
   4766 
   4767 	/* we can return cached values if we are sleeping */
   4768 	if (cmd != AUDIO_MIXER_READ)
   4769 		device_active(sc->dev, DVA_SYSTEM);
   4770 
   4771 	switch (cmd) {
   4772 	case FIOASYNC:
   4773 		if (*(int *)addr) {
   4774 			mutex_exit(sc->sc_lock);
   4775 			ma = kmem_alloc(sizeof(struct mixer_asyncs), KM_SLEEP);
   4776 			mutex_enter(sc->sc_lock);
   4777 		} else {
   4778 			ma = NULL;
   4779 		}
   4780 		mixer_remove(sc);	/* remove old entry */
   4781 		if (ma != NULL) {
   4782 			ma->next = sc->sc_async_mixer;
   4783 			ma->pid = curproc->p_pid;
   4784 			sc->sc_async_mixer = ma;
   4785 		}
   4786 		error = 0;
   4787 		break;
   4788 
   4789 	case AUDIO_GETDEV:
   4790 		DPRINTF(("AUDIO_GETDEV\n"));
   4791 		error = hw->getdev(sc->hw_hdl, (audio_device_t *)addr);
   4792 		break;
   4793 
   4794 	case AUDIO_MIXER_DEVINFO:
   4795 		DPRINTF(("AUDIO_MIXER_DEVINFO\n"));
   4796 		((mixer_devinfo_t *)addr)->un.v.delta = 0; /* default */
   4797 		error = audio_query_devinfo(sc, (mixer_devinfo_t *)addr);
   4798 		break;
   4799 
   4800 	case AUDIO_MIXER_READ:
   4801 		DPRINTF(("AUDIO_MIXER_READ\n"));
   4802 		mc = (mixer_ctrl_t *)addr;
   4803 
   4804 		if (device_is_active(sc->sc_dev))
   4805 			error = audio_get_port(sc, mc);
   4806 		else if (mc->dev >= sc->sc_nmixer_states)
   4807 			error = ENXIO;
   4808 		else {
   4809 			int dev = mc->dev;
   4810 			memcpy(mc, &sc->sc_mixer_state[dev],
   4811 			    sizeof(mixer_ctrl_t));
   4812 			error = 0;
   4813 		}
   4814 		break;
   4815 
   4816 	case AUDIO_MIXER_WRITE:
   4817 		DPRINTF(("AUDIO_MIXER_WRITE\n"));
   4818 		error = audio_set_port(sc, (mixer_ctrl_t *)addr);
   4819 		if (!error && hw->commit_settings)
   4820 			error = hw->commit_settings(sc->hw_hdl);
   4821 		if (!error)
   4822 			mixer_signal(sc);
   4823 		break;
   4824 
   4825 	default:
   4826 		if (hw->dev_ioctl)
   4827 			error = hw->dev_ioctl(sc->hw_hdl, cmd, addr, flag, l);
   4828 		else
   4829 			error = EINVAL;
   4830 		break;
   4831 	}
   4832 	DPRINTF(("mixer_ioctl(%lu,'%c',%lu) result %d\n",
   4833 		 IOCPARM_LEN(cmd), (char)IOCGROUP(cmd), cmd&0xff, error));
   4834 	return error;
   4835 }
   4836 #endif /* NAUDIO > 0 */
   4837 
   4838 #include "midi.h"
   4839 
   4840 #if NAUDIO == 0 && (NMIDI > 0 || NMIDIBUS > 0)
   4841 #include <sys/param.h>
   4842 #include <sys/systm.h>
   4843 #include <sys/device.h>
   4844 #include <sys/audioio.h>
   4845 #include <dev/audio_if.h>
   4846 #endif
   4847 
   4848 #if NAUDIO > 0 || (NMIDI > 0 || NMIDIBUS > 0)
   4849 int
   4850 audioprint(void *aux, const char *pnp)
   4851 {
   4852 	struct audio_attach_args *arg;
   4853 	const char *type;
   4854 
   4855 	if (pnp != NULL) {
   4856 		arg = aux;
   4857 		switch (arg->type) {
   4858 		case AUDIODEV_TYPE_AUDIO:
   4859 			type = "audio";
   4860 			break;
   4861 		case AUDIODEV_TYPE_MIDI:
   4862 			type = "midi";
   4863 			break;
   4864 		case AUDIODEV_TYPE_OPL:
   4865 			type = "opl";
   4866 			break;
   4867 		case AUDIODEV_TYPE_MPU:
   4868 			type = "mpu";
   4869 			break;
   4870 		default:
   4871 			panic("audioprint: unknown type %d", arg->type);
   4872 		}
   4873 		aprint_normal("%s at %s", type, pnp);
   4874 	}
   4875 	return UNCONF;
   4876 }
   4877 
   4878 #endif /* NAUDIO > 0 || (NMIDI > 0 || NMIDIBUS > 0) */
   4879 
   4880 #if NAUDIO > 0
   4881 device_t
   4882 audio_get_device(struct audio_softc *sc)
   4883 {
   4884 	return sc->sc_dev;
   4885 }
   4886 #endif
   4887 
   4888 #if NAUDIO > 0
   4889 static void
   4890 audio_mixer_capture(struct audio_softc *sc)
   4891 {
   4892 	mixer_devinfo_t mi;
   4893 	mixer_ctrl_t *mc;
   4894 
   4895 	KASSERT(mutex_owned(sc->sc_lock));
   4896 
   4897 	for (mi.index = 0;; mi.index++) {
   4898 		if (audio_query_devinfo(sc, &mi) != 0)
   4899 			break;
   4900 		KASSERT(mi.index < sc->sc_nmixer_states);
   4901 		if (mi.type == AUDIO_MIXER_CLASS)
   4902 			continue;
   4903 		mc = &sc->sc_mixer_state[mi.index];
   4904 		mc->dev = mi.index;
   4905 		mc->type = mi.type;
   4906 		mc->un.value.num_channels = mi.un.v.num_channels;
   4907 		(void)audio_get_port(sc, mc);
   4908 	}
   4909 
   4910 	return;
   4911 }
   4912 
   4913 static void
   4914 audio_mixer_restore(struct audio_softc *sc)
   4915 {
   4916 	mixer_devinfo_t mi;
   4917 	mixer_ctrl_t *mc;
   4918 
   4919 	KASSERT(mutex_owned(sc->sc_lock));
   4920 
   4921 	for (mi.index = 0; ; mi.index++) {
   4922 		if (audio_query_devinfo(sc, &mi) != 0)
   4923 			break;
   4924 		if (mi.type == AUDIO_MIXER_CLASS)
   4925 			continue;
   4926 		mc = &sc->sc_mixer_state[mi.index];
   4927 		(void)audio_set_port(sc, mc);
   4928 	}
   4929 	if (sc->hw_if->commit_settings)
   4930 		sc->hw_if->commit_settings(sc->hw_hdl);
   4931 
   4932 	return;
   4933 }
   4934 
   4935 #ifdef AUDIO_PM_IDLE
   4936 static void
   4937 audio_idle(void *arg)
   4938 {
   4939 	device_t dv = arg;
   4940 	struct audio_softc *sc = device_private(dv);
   4941 
   4942 #ifdef PNP_DEBUG
   4943 	extern int pnp_debug_idle;
   4944 	if (pnp_debug_idle)
   4945 		printf("%s: idle handler called\n", device_xname(dv));
   4946 #endif
   4947 
   4948 	sc->sc_idle = true;
   4949 
   4950 	/* XXX joerg Make pmf_device_suspend handle children? */
   4951 	if (!pmf_device_suspend(dv, PMF_Q_SELF))
   4952 		return;
   4953 
   4954 	if (!pmf_device_suspend(sc->sc_dev, PMF_Q_SELF))
   4955 		pmf_device_resume(dv, PMF_Q_SELF);
   4956 }
   4957 
   4958 static void
   4959 audio_activity(device_t dv, devactive_t type)
   4960 {
   4961 	struct audio_softc *sc = device_private(dv);
   4962 
   4963 	if (type != DVA_SYSTEM)
   4964 		return;
   4965 
   4966 	callout_schedule(&sc->sc_idle_counter, audio_idle_timeout * hz);
   4967 
   4968 	sc->sc_idle = false;
   4969 	if (!device_is_active(dv)) {
   4970 		/* XXX joerg How to deal with a failing resume... */
   4971 		pmf_device_resume(sc->sc_dev, PMF_Q_SELF);
   4972 		pmf_device_resume(dv, PMF_Q_SELF);
   4973 	}
   4974 }
   4975 #endif
   4976 
   4977 static bool
   4978 audio_suspend(device_t dv, const pmf_qual_t *qual)
   4979 {
   4980 	struct audio_softc *sc = device_private(dv);
   4981 	const struct audio_hw_if *hwp = sc->hw_if;
   4982 	struct virtual_channel *vc;
   4983 	int n;
   4984 	bool pbus, rbus;
   4985 
   4986 	pbus = rbus = false;
   4987 	mutex_enter(sc->sc_lock);
   4988 	audio_mixer_capture(sc);
   4989 	for (n = 1; n < VAUDIOCHANS; n++) {
   4990 		if (sc->sc_audiopid[n].pid == -1)
   4991 			continue;
   4992 
   4993 		vc = sc->sc_vchan[n];
   4994 		if (vc->sc_pbus && !pbus)
   4995 			pbus = true;
   4996 		if (vc->sc_rbus && !rbus)
   4997 			rbus = true;
   4998 	}
   4999 	mutex_enter(sc->sc_intr_lock);
   5000 	if (pbus == true)
   5001 		hwp->halt_output(sc->hw_hdl);
   5002 	if (rbus == true)
   5003 		hwp->halt_input(sc->hw_hdl);
   5004 	mutex_exit(sc->sc_intr_lock);
   5005 #ifdef AUDIO_PM_IDLE
   5006 	callout_halt(&sc->sc_idle_counter, sc->sc_lock);
   5007 #endif
   5008 	mutex_exit(sc->sc_lock);
   5009 
   5010 	return true;
   5011 }
   5012 
   5013 static bool
   5014 audio_resume(device_t dv, const pmf_qual_t *qual)
   5015 {
   5016 	struct audio_softc *sc = device_private(dv);
   5017 	struct virtual_channel *vc;
   5018 	int n;
   5019 
   5020 	mutex_enter(sc->sc_lock);
   5021 	sc->sc_trigger_started = false;
   5022 	sc->sc_rec_started = false;
   5023 
   5024 	audio_set_vchan_defaults(sc, AUMODE_PLAY | AUMODE_PLAY_ALL |
   5025 	    AUMODE_RECORD, &sc->sc_format[0], 0);
   5026 
   5027 	audio_mixer_restore(sc);
   5028 	for (n = 1; n < VAUDIOCHANS; n++) {
   5029 		if (sc->sc_audiopid[n].pid == -1)
   5030 			continue;
   5031 		vc = sc->sc_vchan[n];
   5032 
   5033 		if (vc->sc_lastinfovalid == true)
   5034 			audiosetinfo(sc, &vc->sc_lastinfo, true, n);
   5035 		mutex_enter(sc->sc_intr_lock);
   5036 		if (vc->sc_pbus == true && !vc->sc_mpr.pause)
   5037 			audiostartp(sc, n);
   5038 		if (vc->sc_rbus == true && !vc->sc_mrr.pause)
   5039 			audiostartr(sc, n);
   5040 		mutex_exit(sc->sc_intr_lock);
   5041 	}
   5042 	mutex_exit(sc->sc_lock);
   5043 
   5044 	return true;
   5045 }
   5046 
   5047 static void
   5048 audio_volume_down(device_t dv)
   5049 {
   5050 	struct audio_softc *sc = device_private(dv);
   5051 	mixer_devinfo_t mi;
   5052 	int newgain;
   5053 	u_int gain;
   5054 	u_char balance;
   5055 
   5056 	mutex_enter(sc->sc_lock);
   5057 	if (sc->sc_outports.index == -1 && sc->sc_outports.master != -1) {
   5058 		mi.index = sc->sc_outports.master;
   5059 		mi.un.v.delta = 0;
   5060 		if (audio_query_devinfo(sc, &mi) == 0) {
   5061 			au_get_gain(sc, &sc->sc_outports, &gain, &balance);
   5062 			newgain = gain - mi.un.v.delta;
   5063 			if (newgain < AUDIO_MIN_GAIN)
   5064 				newgain = AUDIO_MIN_GAIN;
   5065 			au_set_gain(sc, &sc->sc_outports, newgain, balance);
   5066 		}
   5067 	}
   5068 	mutex_exit(sc->sc_lock);
   5069 }
   5070 
   5071 static void
   5072 audio_volume_up(device_t dv)
   5073 {
   5074 	struct audio_softc *sc = device_private(dv);
   5075 	mixer_devinfo_t mi;
   5076 	u_int gain, newgain;
   5077 	u_char balance;
   5078 
   5079 	mutex_enter(sc->sc_lock);
   5080 	if (sc->sc_outports.index == -1 && sc->sc_outports.master != -1) {
   5081 		mi.index = sc->sc_outports.master;
   5082 		mi.un.v.delta = 0;
   5083 		if (audio_query_devinfo(sc, &mi) == 0) {
   5084 			au_get_gain(sc, &sc->sc_outports, &gain, &balance);
   5085 			newgain = gain + mi.un.v.delta;
   5086 			if (newgain > AUDIO_MAX_GAIN)
   5087 				newgain = AUDIO_MAX_GAIN;
   5088 			au_set_gain(sc, &sc->sc_outports, newgain, balance);
   5089 		}
   5090 	}
   5091 	mutex_exit(sc->sc_lock);
   5092 }
   5093 
   5094 static void
   5095 audio_volume_toggle(device_t dv)
   5096 {
   5097 	struct audio_softc *sc = device_private(dv);
   5098 	u_int gain, newgain;
   5099 	u_char balance;
   5100 
   5101 	mutex_enter(sc->sc_lock);
   5102 	au_get_gain(sc, &sc->sc_outports, &gain, &balance);
   5103 	if (gain != 0) {
   5104 		sc->sc_lastgain = gain;
   5105 		newgain = 0;
   5106 	} else
   5107 		newgain = sc->sc_lastgain;
   5108 	au_set_gain(sc, &sc->sc_outports, newgain, balance);
   5109 	mutex_exit(sc->sc_lock);
   5110 }
   5111 
   5112 static int
   5113 audio_get_props(struct audio_softc *sc)
   5114 {
   5115 	const struct audio_hw_if *hw;
   5116 	int props;
   5117 
   5118 	KASSERT(mutex_owned(sc->sc_lock));
   5119 
   5120 	hw = sc->hw_if;
   5121 	props = hw->get_props(sc->hw_hdl);
   5122 
   5123 	/*
   5124 	 * if neither playback nor capture properties are reported,
   5125 	 * assume both are supported by the device driver
   5126 	 */
   5127 	if ((props & (AUDIO_PROP_PLAYBACK|AUDIO_PROP_CAPTURE)) == 0)
   5128 		props |= (AUDIO_PROP_PLAYBACK | AUDIO_PROP_CAPTURE);
   5129 
   5130 	return props;
   5131 }
   5132 
   5133 static bool
   5134 audio_can_playback(struct audio_softc *sc)
   5135 {
   5136 	return audio_get_props(sc) & AUDIO_PROP_PLAYBACK ? true : false;
   5137 }
   5138 
   5139 static bool
   5140 audio_can_capture(struct audio_softc *sc)
   5141 {
   5142 	return audio_get_props(sc) & AUDIO_PROP_CAPTURE ? true : false;
   5143 }
   5144 
   5145 void
   5146 mix_read(void *arg)
   5147 {
   5148 	struct audio_softc *sc = arg;
   5149 	struct virtual_channel *vc;
   5150 	stream_filter_t *filter;
   5151 	stream_fetcher_t *fetcher;
   5152 	stream_fetcher_t null_fetcher;
   5153 	int cc, cc1, blksize, error;
   5154 	uint8_t *inp;
   5155 
   5156 	vc = sc->sc_vchan[0];
   5157 	blksize = vc->sc_mrr.blksize;
   5158 	cc = blksize;
   5159 
   5160 	if (sc->hw_if->trigger_input && sc->sc_rec_started == false) {
   5161 		DPRINTF(("%s: call trigger_input\n", __func__));
   5162 		error = sc->hw_if->trigger_input(sc->hw_hdl, vc->sc_mrr.s.start,
   5163 		    vc->sc_mrr.s.end, blksize,
   5164 		    audio_rint, (void *)sc, &vc->sc_mrr.s.param);
   5165 	} else if (sc->hw_if->start_input) {
   5166 		DPRINTF(("%s: call start_input\n", __func__));
   5167 		error = sc->hw_if->start_input(sc->hw_hdl,
   5168 		    vc->sc_mrr.s.inp, blksize,
   5169 		    audio_rint, (void *)sc);
   5170 		if (error) {
   5171 			/* XXX does this really help? */
   5172 			DPRINTF(("audio_upmix restart failed: %d\n", error));
   5173 			audio_clear(sc, 0);
   5174 		}
   5175 	}
   5176 	sc->sc_rec_started = true;
   5177 
   5178 	inp = vc->sc_mrr.s.inp;
   5179 	vc->sc_mrr.s.inp = audio_stream_add_inp(&vc->sc_mrr.s, inp, cc);
   5180 
   5181 	if (vc->sc_nrfilters > 0) {
   5182 		cc = vc->sc_rustream->end - vc->sc_rustream->start;
   5183 		null_fetcher.fetch_to = null_fetcher_fetch_to;
   5184 		filter = vc->sc_rfilters[0];
   5185 		filter->set_fetcher(filter, &null_fetcher);
   5186 		fetcher = &vc->sc_rfilters[vc->sc_nrfilters - 1]->base;
   5187 		fetcher->fetch_to(sc, fetcher, vc->sc_rustream, cc);
   5188 	}
   5189 
   5190 	blksize = audio_stream_get_used(vc->sc_rustream);
   5191 	cc1 = blksize;
   5192 	if (vc->sc_rustream->outp + blksize > vc->sc_rustream->end)
   5193 		cc1 = vc->sc_rustream->end - vc->sc_rustream->outp;
   5194 	memcpy(sc->sc_rr.s.start, vc->sc_rustream->outp, cc1);
   5195 	if (cc1 < blksize) {
   5196 		memcpy(sc->sc_rr.s.start + cc1, vc->sc_rustream->start,
   5197 		    blksize - cc1);
   5198 	}
   5199 	sc->sc_rr.s.inp = audio_stream_add_inp(&sc->sc_rr.s, sc->sc_rr.s.inp,
   5200 	    blksize);
   5201 	vc->sc_rustream->outp = audio_stream_add_outp(vc->sc_rustream,
   5202 	    vc->sc_rustream->outp, blksize);
   5203 }
   5204 
   5205 void
   5206 mix_write(void *arg)
   5207 {
   5208 	struct audio_softc *sc = arg;
   5209 	struct virtual_channel *vc;
   5210 	stream_filter_t *filter;
   5211 	stream_fetcher_t *fetcher;
   5212 	stream_fetcher_t null_fetcher;
   5213 	int cc, cc1, blksize, error;
   5214 	uint8_t *inp;
   5215 
   5216 	vc = sc->sc_vchan[0];
   5217 	blksize = vc->sc_mpr.blksize;
   5218 	cc = blksize;
   5219 	error = 0;
   5220 
   5221 	cc1 = cc;
   5222 	if (vc->sc_pustream->inp + cc > vc->sc_pustream->end)
   5223 		cc1 = vc->sc_pustream->end - vc->sc_pustream->inp;
   5224 	memcpy(vc->sc_pustream->inp, sc->sc_pr.s.start, cc1);
   5225 	if (cc1 < cc) {
   5226 		memcpy(vc->sc_pustream->start, sc->sc_pr.s.start + cc1,
   5227 		    cc - cc1);
   5228 	}
   5229 	memset(sc->sc_pr.s.start, 0, cc);
   5230 
   5231 	inp = vc->sc_pustream->inp;
   5232 	vc->sc_pustream->inp = audio_stream_add_inp(vc->sc_pustream, inp, cc);
   5233 
   5234 	if (vc->sc_npfilters > 0) {
   5235 		null_fetcher.fetch_to = null_fetcher_fetch_to;
   5236 		filter = vc->sc_pfilters[0];
   5237 		filter->set_fetcher(filter, &null_fetcher);
   5238 		fetcher = &vc->sc_pfilters[vc->sc_npfilters - 1]->base;
   5239 		fetcher->fetch_to(sc, fetcher, &vc->sc_mpr.s, cc);
   5240  	}
   5241 
   5242 	if (sc->hw_if->trigger_output && sc->sc_trigger_started == false) {
   5243 		DPRINTF(("%s: call trigger_output\n", __func__));
   5244 		error = sc->hw_if->trigger_output(sc->hw_hdl,
   5245 		    vc->sc_mpr.s.start, vc->sc_mpr.s.end, blksize,
   5246 		    audio_pint, (void *)sc, &vc->sc_mpr.s.param);
   5247 	} else if (sc->hw_if->start_output) {
   5248 		DPRINTF(("%s: call start_output\n", __func__));
   5249 		error = sc->hw_if->start_output(sc->hw_hdl,
   5250 		    __UNCONST(vc->sc_mpr.s.outp), blksize,
   5251 		    audio_pint, (void *)sc);
   5252 	}
   5253 	sc->sc_trigger_started = true;
   5254 
   5255 	if (error) {
   5256 		/* XXX does this really help? */
   5257 		DPRINTF(("audio_mix restart failed: %d\n", error));
   5258 		audio_clear(sc, 0);
   5259 		sc->sc_trigger_started = false;
   5260 	}
   5261 }
   5262 
   5263 void
   5264 mix_func8(struct audio_softc *sc, struct audio_ringbuffer *cb, int n)
   5265 {
   5266 	int blksize, cc, cc1, cc2, m, resid;
   5267 	int8_t *orig, *tomix;
   5268 
   5269 	blksize = sc->sc_vchan[0]->sc_mpr.blksize;
   5270 	resid = blksize;
   5271 
   5272 	tomix = __UNCONST(cb->s.outp);
   5273 	orig = (int8_t *)(sc->sc_pr.s.start);
   5274 
   5275 	while (resid > 0) {
   5276 		cc = resid;
   5277 		cc1 = sc->sc_pr.s.end - (uint8_t *)orig;
   5278 		cc2 = cb->s.end - (uint8_t *)tomix;
   5279 		if (cc > cc1)
   5280 			cc = cc1;
   5281 		if (cc > cc2)
   5282 			cc = cc2;
   5283 
   5284 		for (m = 0; m < cc;  m++) {
   5285 			orig[m] += (int8_t)((int32_t)(tomix[m] *
   5286 			    ((sc->sc_vchan[n]->sc_swvol + 1) * 16)) /
   5287 			    (sc->sc_opens * VAUDIOCHANS));
   5288 		}
   5289 
   5290 		if (&orig[m] >= (int8_t *)sc->sc_pr.s.end)
   5291 			orig = (int8_t *)sc->sc_pr.s.start;
   5292 		if (&tomix[m] >= (int8_t *)cb->s.end)
   5293 			tomix = (int8_t *)cb->s.start;
   5294 
   5295 		resid -= cc;
   5296 	}
   5297 }
   5298 
   5299 void
   5300 mix_func16(struct audio_softc *sc, struct audio_ringbuffer *cb, int n)
   5301 {
   5302 	int blksize, cc, cc1, cc2, m, resid;
   5303 	int16_t *orig, *tomix;
   5304 
   5305 	blksize = sc->sc_vchan[0]->sc_mpr.blksize;
   5306 	resid = blksize;
   5307 
   5308 	tomix = __UNCONST(cb->s.outp);
   5309 	orig = (int16_t *)(sc->sc_pr.s.start);
   5310 
   5311 	while (resid > 0) {
   5312 		cc = resid;
   5313 		cc1 = sc->sc_pr.s.end - (uint8_t *)orig;
   5314 		cc2 = cb->s.end - (uint8_t *)tomix;
   5315 		if (cc > cc1)
   5316 			cc = cc1;
   5317 		if (cc > cc2)
   5318 			cc = cc2;
   5319 
   5320 		for (m = 0; m < cc / 2; m++) {
   5321 			orig[m] += (int16_t)((int32_t)(tomix[m] *
   5322 			    ((sc->sc_vchan[n]->sc_swvol + 1) * 16)) /
   5323 			    (sc->sc_opens * VAUDIOCHANS));
   5324 		}
   5325 
   5326 		if (&orig[m] >= (int16_t *)sc->sc_pr.s.end)
   5327 			orig = (int16_t *)sc->sc_pr.s.start;
   5328 		if (&tomix[m] >= (int16_t *)cb->s.end)
   5329 			tomix = (int16_t *)cb->s.start;
   5330 
   5331 		resid -= cc;
   5332 	}
   5333 }
   5334 
   5335 void
   5336 mix_func32(struct audio_softc *sc, struct audio_ringbuffer *cb, int n)
   5337 {
   5338 	int blksize, cc, cc1, cc2, m, resid;
   5339 	int32_t *orig, *tomix;
   5340 
   5341 	blksize = sc->sc_vchan[0]->sc_mpr.blksize;
   5342 	resid = blksize;
   5343 
   5344 	tomix = __UNCONST(cb->s.outp);
   5345 	orig = (int32_t *)(sc->sc_pr.s.start);
   5346 
   5347 	while (resid > 0) {
   5348 		cc = resid;
   5349 		cc1 = sc->sc_pr.s.end - (uint8_t *)orig;
   5350 		cc2 = cb->s.end - (uint8_t *)tomix;
   5351 		if (cc > cc1)
   5352 			cc = cc1;
   5353 		if (cc > cc2)
   5354 			cc = cc2;
   5355 
   5356 		for (m = 0; m < cc / 4; m++) {
   5357 			orig[m] += (int32_t)((int32_t)(tomix[m] *
   5358 			    ((sc->sc_vchan[n]->sc_swvol + 1) * 16)) /
   5359 			    (sc->sc_opens * VAUDIOCHANS));
   5360 		}
   5361 
   5362 		if (&orig[m] >= (int32_t *)sc->sc_pr.s.end)
   5363 			orig = (int32_t *)sc->sc_pr.s.start;
   5364 		if (&tomix[m] >= (int32_t *)cb->s.end)
   5365 			tomix = (int32_t *)cb->s.start;
   5366 
   5367 		resid -= cc;
   5368 	}
   5369 }
   5370 
   5371 void
   5372 mix_func(struct audio_softc *sc, struct audio_ringbuffer *cb, int n)
   5373 {
   5374 	switch (sc->sc_precision) {
   5375 	case 8:
   5376 		mix_func8(sc, cb, n);
   5377 		break;
   5378 	case 16:
   5379 		mix_func16(sc, cb, n);
   5380 		break;
   5381 	case 24:
   5382 	case 32:
   5383 		mix_func32(sc, cb, n);
   5384 		break;
   5385 	default:
   5386 		break;
   5387 	}
   5388 }
   5389 
   5390 void
   5391 saturate_func8(struct audio_softc *sc)
   5392 {
   5393 	int blksize, m, i, resid;
   5394 	int8_t *orig;
   5395 
   5396 	blksize = sc->sc_vchan[0]->sc_mpr.blksize;
   5397 	resid = blksize;
   5398 	if (sc->sc_trigger_started == false)
   5399 		resid *= 2;
   5400 
   5401 	orig = (int8_t *)(sc->sc_pr.s.start);
   5402 
   5403 	for (m = 0; m < resid;  m++) {
   5404 		i = 0;
   5405 		if (orig[m] != 0) {
   5406 			if (orig[m] > 0)
   5407 				i = INT8_MAX / orig[m];
   5408 			else
   5409 				i = INT8_MIN / orig[m];
   5410 		}
   5411 		if (i > sc->sc_opens)
   5412 			i = sc->sc_opens;
   5413 		orig[m] *= i;
   5414 	}
   5415 }
   5416 
   5417 void
   5418 saturate_func16(struct audio_softc *sc)
   5419 {
   5420 	int blksize, m, i, resid;
   5421 	int16_t *orig;
   5422 
   5423 	blksize = sc->sc_vchan[0]->sc_mpr.blksize;
   5424 	resid = blksize;
   5425 	if (sc->sc_trigger_started == false)
   5426 		resid *= 2;
   5427 
   5428 	orig = (int16_t *)(sc->sc_pr.s.start);
   5429 
   5430 	for (m = 0; m < resid;  m++) {
   5431 		i = 0;
   5432 		if (orig[m] != 0) {
   5433 			if (orig[m] > 0)
   5434 				i = INT16_MAX / orig[m];
   5435 			else
   5436 				i = INT16_MIN / orig[m];
   5437 		}
   5438 		if (i > sc->sc_opens)
   5439 			i = sc->sc_opens;
   5440 		orig[m] *= i;
   5441 	}
   5442 }
   5443 
   5444 void
   5445 saturate_func32(struct audio_softc *sc)
   5446 {
   5447 	int blksize, m, i, resid;
   5448 	int32_t *orig;
   5449 
   5450 	blksize = sc->sc_vchan[0]->sc_mpr.blksize;
   5451 	resid = blksize;
   5452 	if (sc->sc_trigger_started == false)
   5453 		resid *= 2;
   5454 
   5455 	orig = (int32_t *)(sc->sc_pr.s.start);
   5456 
   5457 	for (m = 0; m < resid;  m++) {
   5458 		i = 0;
   5459 		if (orig[m] != 0) {
   5460 			if (orig[m] > 0)
   5461 				i = INT32_MAX / orig[m];
   5462 			else
   5463 				i = INT32_MIN / orig[m];
   5464 		}
   5465 		if (i > sc->sc_opens)
   5466 			i = sc->sc_opens;
   5467 		orig[m] *= i;
   5468 	}
   5469 }
   5470 
   5471 void
   5472 saturate_func(struct audio_softc *sc)
   5473 {
   5474 	switch (sc->sc_precision) {
   5475 	case 8:
   5476 		saturate_func8(sc);
   5477 		break;
   5478 	case 16:
   5479 		saturate_func16(sc);
   5480 		break;
   5481 	case 24:
   5482 	case 32:
   5483 		saturate_func32(sc);
   5484 		break;
   5485 	default:
   5486 		break;
   5487 	}
   5488 }
   5489 
   5490 void
   5491 recswvol_func8(struct audio_softc *sc, struct audio_ringbuffer *cb, int n,
   5492     size_t blksize)
   5493 {
   5494 	int cc, cc1, m, resid;
   5495 	int8_t *orig;
   5496 
   5497 	orig = cb->s.inp;
   5498 	resid = blksize;
   5499 
   5500 	while (resid > 0) {
   5501 		cc = resid;
   5502 		cc1 = cb->s.end - (uint8_t *)orig;
   5503 		if (cc > cc1)
   5504 			cc = cc1;
   5505 
   5506 		for (m = 0; m < cc; m++) {
   5507 			orig[m] = (int16_t)(orig[m] *
   5508 			    (int16_t)(sc->sc_vchan[n]->sc_recswvol) / 256);
   5509 		}
   5510 		orig = cb->s.start;
   5511 
   5512 		resid -= cc;
   5513 	}
   5514 }
   5515 
   5516 void
   5517 recswvol_func16(struct audio_softc *sc, struct audio_ringbuffer *cb, int n,
   5518     size_t blksize)
   5519 {
   5520 	int cc, cc1, m, resid;
   5521 	int16_t *orig;
   5522 
   5523 	orig = (int16_t *)cb->s.inp;
   5524 	resid = blksize;
   5525 
   5526 	while (resid > 0) {
   5527 		cc = resid;
   5528 		cc1 = cb->s.end - (uint8_t *)orig;
   5529 		if (cc > cc1)
   5530 			cc = cc1;
   5531 
   5532 		for (m = 0; m < cc / 2; m++) {
   5533 			orig[m] = (int32_t)(orig[m] *
   5534 			    (int32_t)(sc->sc_vchan[n]->sc_recswvol) / 256);
   5535 		}
   5536 		orig = (uint16_t *)cb->s.start;
   5537 
   5538 		resid -= cc;
   5539 	}
   5540 }
   5541 
   5542 void
   5543 recswvol_func32(struct audio_softc *sc, struct audio_ringbuffer *cb, int n,
   5544     size_t blksize)
   5545 {
   5546 	int cc, cc1, m, resid;
   5547 	int32_t *orig;
   5548 
   5549 	orig = (int32_t *)cb->s.inp;
   5550 	resid = blksize;
   5551 
   5552 	while (resid > 0) {
   5553 		cc = resid;
   5554 		cc1 = cb->s.end - (uint8_t *)orig;
   5555 		if (cc > cc1)
   5556 			cc = cc1;
   5557 
   5558 		for (m = 0; m < cc / 2; m++) {
   5559 			orig[m] = (int64_t)(orig[m] *
   5560 			    (int64_t)(sc->sc_vchan[n]->sc_recswvol) / 256);
   5561 		}
   5562 		orig = (uint32_t *)cb->s.start;
   5563 
   5564 		resid -= cc;
   5565 	}
   5566 }
   5567 
   5568 void
   5569 recswvol_func(struct audio_softc *sc, struct audio_ringbuffer *cb, int n,
   5570     size_t blksize)
   5571 {
   5572 	switch (sc->sc_precision) {
   5573 	case 8:
   5574 		recswvol_func8(sc, cb, n, blksize);
   5575 		break;
   5576 	case 16:
   5577 		recswvol_func16(sc, cb, n, blksize);
   5578 		break;
   5579 	case 24:
   5580 	case 32:
   5581 		recswvol_func32(sc, cb, n, blksize);
   5582 		break;
   5583 	default:
   5584 		break;
   5585 	}
   5586 }
   5587 
   5588 static uint8_t *
   5589 find_vchan_vol(struct audio_softc *sc, int d)
   5590 {
   5591 	size_t j, n = (size_t)d / 2;
   5592 
   5593 	for (size_t i = j = 0; i <= n; i++)
   5594 		if (sc->sc_audiopid[i].pid != -1)
   5595 			j++;
   5596 
   5597 	return (d & 1) == 0 ?
   5598 	    &sc->sc_vchan[j]->sc_swvol : &sc->sc_vchan[j]->sc_recswvol;
   5599 }
   5600 
   5601 static int
   5602 audio_set_port(struct audio_softc *sc, mixer_ctrl_t *mc)
   5603 {
   5604 	KASSERT(mutex_owned(sc->sc_lock));
   5605 
   5606 	int d = mc->dev - sc->sc_static_nmixer_states;
   5607 
   5608 	if (d < 0)
   5609 		return sc->hw_if->set_port(sc->hw_hdl, mc);
   5610 
   5611 	uint8_t *level = &mc->un.value.level[AUDIO_MIXER_LEVEL_MONO];
   5612 	uint8_t *vol = find_vchan_vol(sc, d);
   5613 	*vol = *level;
   5614 	return 0;
   5615 }
   5616 
   5617 
   5618 static int
   5619 audio_get_port(struct audio_softc *sc, mixer_ctrl_t *mc)
   5620 {
   5621 
   5622 	KASSERT(mutex_owned(sc->sc_lock));
   5623 
   5624 	int d = mc->dev - sc->sc_static_nmixer_states;
   5625 
   5626 	if (d < 0)
   5627 		return sc->hw_if->get_port(sc->hw_hdl, mc);
   5628 
   5629 	u_char *level = &mc->un.value.level[AUDIO_MIXER_LEVEL_MONO];
   5630 	uint8_t *vol = find_vchan_vol(sc, d);
   5631 	*level = *vol;
   5632 	return 0;
   5633 
   5634 }
   5635 
   5636 static int
   5637 audio_query_devinfo(struct audio_softc *sc, mixer_devinfo_t *di)
   5638 {
   5639 	char mixLabel[255];
   5640 
   5641 	KASSERT(mutex_owned(sc->sc_lock));
   5642 
   5643 	if (di->index >= sc->sc_static_nmixer_states && di->index <
   5644 	    sc->sc_nmixer_states) {
   5645 		if ((di->index - sc->sc_static_nmixer_states) % 2 == 0) {
   5646 			di->mixer_class = AUDIO_OUTPUT_CLASS;
   5647 			snprintf(mixLabel, sizeof(mixLabel), AudioNdac"%d",
   5648 			    (di->index - sc->sc_static_nmixer_states) / 2);
   5649 			strcpy(di->label.name, mixLabel);
   5650 			di->type = AUDIO_MIXER_VALUE;
   5651 			di->next = di->prev = AUDIO_MIXER_LAST;
   5652 			di->un.v.num_channels = 1;
   5653 			strcpy(di->un.v.units.name, AudioNvolume);
   5654 		} else {
   5655 			di->mixer_class = AUDIO_INPUT_CLASS;
   5656 			snprintf(mixLabel, sizeof(mixLabel), AudioNmicrophone
   5657 			    "%d", (di->index - sc->sc_static_nmixer_states) /
   5658 			     2);
   5659 			strcpy(di->label.name, mixLabel);
   5660 			di->type = AUDIO_MIXER_VALUE;
   5661 			di->next = di->prev = AUDIO_MIXER_LAST;
   5662 			di->un.v.num_channels = 1;
   5663 			strcpy(di->un.v.units.name, AudioNvolume);
   5664 		}
   5665 
   5666 		return 0;
   5667 	}
   5668 
   5669 
   5670 	return sc->hw_if->query_devinfo(sc->hw_hdl, di);
   5671 }
   5672 
   5673 static int
   5674 audio_set_params(struct audio_softc *sc, int setmode, int usemode,
   5675     audio_params_t *play, audio_params_t *rec,
   5676     stream_filter_list_t *pfil, stream_filter_list_t *rfil, int n)
   5677 {
   5678 	int error = 0;
   5679 	KASSERT(mutex_owned(sc->sc_lock));
   5680 
   5681 	if (n == 0 && sc->hw_if->set_params != NULL) {
   5682 		sc->sc_ready = true;
   5683 		if (sc->sc_precision == 8)
   5684 			play->encoding = rec->encoding = AUDIO_ENCODING_SLINEAR;
   5685 		error = sc->hw_if->set_params(sc->hw_hdl, setmode, usemode,
   5686  		    play, rec, pfil, rfil);
   5687 		if (error != 0)
   5688 			sc->sc_ready = false;
   5689 
   5690 		return error;
   5691 	}
   5692 
   5693 	if (setmode & AUMODE_PLAY && auconv_set_converter(sc->sc_format,
   5694 	    VAUDIO_NFORMATS, AUMODE_PLAY, play, true, pfil) < 0)
   5695 		return EINVAL;
   5696 
   5697 	if (pfil->req_size > 0)
   5698 		play = &pfil->filters[0].param;
   5699 
   5700 	if (setmode & AUMODE_RECORD && auconv_set_converter(sc->sc_format,
   5701 	    VAUDIO_NFORMATS, AUMODE_RECORD, rec, true, rfil) < 0)
   5702 		return EINVAL;
   5703 
   5704 	if (rfil->req_size > 0)
   5705 		rec = &rfil->filters[0].param;
   5706 
   5707 	return 0;
   5708 }
   5709 
   5710 static int
   5711 audio_query_encoding(struct audio_softc *sc, struct audio_encoding *ae)
   5712 {
   5713 	KASSERT(mutex_owned(sc->sc_lock));
   5714 
   5715 	return auconv_query_encoding(sc->sc_encodings, ae);
   5716 }
   5717 
   5718 void
   5719 audio_play_thread(void *v)
   5720 {
   5721 	struct audio_softc *sc;
   5722 
   5723 	sc = (struct audio_softc *)v;
   5724 
   5725 	mutex_enter(sc->sc_lock);
   5726 	for (;;) {
   5727 		cv_wait_sig(&sc->sc_condvar, sc->sc_lock);
   5728 		if (sc->sc_dying) {
   5729 			mutex_exit(sc->sc_lock);
   5730 			kthrea