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