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