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