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