Home | History | Annotate | Line # | Download | only in dev
      1 /*	$NetBSD: audio.c,v 1.316 2017/03/20 22:42:39 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.316 2017/03/20 22:42:39 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	saturate_func(struct audio_softc *);
    261 void	mix_func(struct audio_softc *, struct audio_ringbuffer *,
    262 		 struct virtual_channel *);
    263 void	mix_write(void *);
    264 void	mix_read(void *);
    265 int	audio_check_params(struct audio_params *);
    266 
    267 void	audio_calc_blksize(struct audio_softc *, int, struct virtual_channel *);
    268 void	audio_fill_silence(struct audio_params *, uint8_t *, int);
    269 int	audio_silence_copyout(struct audio_softc *, int, struct uio *);
    270 
    271 void	audio_init_ringbuffer(struct audio_softc *,
    272 			      struct audio_ringbuffer *, int);
    273 int	audio_initbufs(struct audio_softc *, struct virtual_channel *);
    274 void	audio_calcwater(struct audio_softc *, struct virtual_channel *);
    275 int	audio_drain(struct audio_softc *, struct audio_chan *);
    276 void	audio_clear(struct audio_softc *, struct virtual_channel *);
    277 void	audio_clear_intr_unlocked(struct audio_softc *sc,
    278 				  struct virtual_channel *);
    279 static inline void
    280 	audio_pint_silence(struct audio_softc *, struct audio_ringbuffer *,
    281 			   uint8_t *, int, struct virtual_channel *);
    282 int	audio_alloc_ring(struct audio_softc *, struct audio_ringbuffer *, int,
    283 			 size_t);
    284 void	audio_free_ring(struct audio_softc *, struct audio_ringbuffer *);
    285 static int audio_setup_pfilters(struct audio_softc *, const audio_params_t *,
    286 			      stream_filter_list_t *, struct virtual_channel *);
    287 static int audio_setup_rfilters(struct audio_softc *, const audio_params_t *,
    288 			      stream_filter_list_t *, struct virtual_channel *);
    289 static void audio_stream_dtor(audio_stream_t *);
    290 static int audio_stream_ctor(audio_stream_t *, const audio_params_t *, int);
    291 static void stream_filter_list_append(stream_filter_list_t *,
    292 		stream_filter_factory_t, const audio_params_t *);
    293 static void stream_filter_list_prepend(stream_filter_list_t *,
    294 	    	stream_filter_factory_t, const audio_params_t *);
    295 static void stream_filter_list_set(stream_filter_list_t *, int,
    296 		stream_filter_factory_t, const audio_params_t *);
    297 int	audio_set_defaults(struct audio_softc *, u_int,
    298 						struct virtual_channel *);
    299 static int audio_sysctl_frequency(SYSCTLFN_PROTO);
    300 static int audio_sysctl_precision(SYSCTLFN_PROTO);
    301 static int audio_sysctl_channels(SYSCTLFN_PROTO);
    302 
    303 static int	audiomatch(device_t, cfdata_t, void *);
    304 static void	audioattach(device_t, device_t, void *);
    305 static int	audiodetach(device_t, int);
    306 static int	audioactivate(device_t, enum devact);
    307 static void	audiochilddet(device_t, device_t);
    308 static int	audiorescan(device_t, const char *, const int *);
    309 
    310 #ifdef AUDIO_PM_IDLE
    311 static void	audio_idle(void *);
    312 static void	audio_activity(device_t, devactive_t);
    313 #endif
    314 
    315 static bool	audio_suspend(device_t dv, const pmf_qual_t *);
    316 static bool	audio_resume(device_t dv, const pmf_qual_t *);
    317 static void	audio_volume_down(device_t);
    318 static void	audio_volume_up(device_t);
    319 static void	audio_volume_toggle(device_t);
    320 
    321 static void	audio_mixer_capture(struct audio_softc *);
    322 static void	audio_mixer_restore(struct audio_softc *);
    323 
    324 static int	audio_get_props(struct audio_softc *);
    325 static bool	audio_can_playback(struct audio_softc *);
    326 static bool	audio_can_capture(struct audio_softc *);
    327 
    328 static void	audio_softintr_rd(void *);
    329 static void	audio_softintr_wr(void *);
    330 
    331 static int	audio_enter(dev_t, krw_t, struct audio_softc **);
    332 static void	audio_exit(struct audio_softc *);
    333 static int	audio_waitio(struct audio_softc *, kcondvar_t *,
    334 			     struct virtual_channel *);
    335 
    336 static int audioclose(struct file *);
    337 static int audioread(struct file *, off_t *, struct uio *, kauth_cred_t, int);
    338 static int audiowrite(struct file *, off_t *, struct uio *, kauth_cred_t, int);
    339 static int audioioctl(struct file *, u_long, void *);
    340 static int audiopoll(struct file *, int);
    341 static int audiokqfilter(struct file *, struct knote *);
    342 static int audiostat(struct file *, struct stat *);
    343 
    344 struct portname {
    345 	const char *name;
    346 	int mask;
    347 };
    348 static const struct portname itable[] = {
    349 	{ AudioNmicrophone,	AUDIO_MICROPHONE },
    350 	{ AudioNline,		AUDIO_LINE_IN },
    351 	{ AudioNcd,		AUDIO_CD },
    352 	{ 0, 0 }
    353 };
    354 static const struct portname otable[] = {
    355 	{ AudioNspeaker,	AUDIO_SPEAKER },
    356 	{ AudioNheadphone,	AUDIO_HEADPHONE },
    357 	{ AudioNline,		AUDIO_LINE_OUT },
    358 	{ 0, 0 }
    359 };
    360 void	au_setup_ports(struct audio_softc *, struct au_mixer_ports *,
    361 			mixer_devinfo_t *, const struct portname *);
    362 int	au_set_gain(struct audio_softc *, struct au_mixer_ports *,
    363 			int, int);
    364 void	au_get_gain(struct audio_softc *, struct au_mixer_ports *,
    365 			u_int *, u_char *);
    366 int	au_set_port(struct audio_softc *, struct au_mixer_ports *,
    367 			u_int);
    368 int	au_get_port(struct audio_softc *, struct au_mixer_ports *);
    369 static int
    370 	audio_get_port(struct audio_softc *, mixer_ctrl_t *);
    371 static int
    372 	audio_set_port(struct audio_softc *, mixer_ctrl_t *);
    373 static int
    374 	audio_query_devinfo(struct audio_softc *, mixer_devinfo_t *);
    375 static int audio_set_params (struct audio_softc *, int, int,
    376 		 audio_params_t *, audio_params_t *,
    377 		 stream_filter_list_t *, stream_filter_list_t *,
    378 		 struct virtual_channel *);
    379 static int
    380 audio_query_encoding(struct audio_softc *, struct audio_encoding *);
    381 static int audio_set_vchan_defaults
    382 	(struct audio_softc *, u_int, const struct audio_format *);
    383 static int vchan_autoconfig(struct audio_softc *);
    384 int	au_get_lr_value(struct audio_softc *, mixer_ctrl_t *, int *, int *);
    385 int	au_set_lr_value(struct audio_softc *, mixer_ctrl_t *, int, int);
    386 int	au_portof(struct audio_softc *, char *, int);
    387 
    388 typedef struct uio_fetcher {
    389 	stream_fetcher_t base;
    390 	struct uio *uio;
    391 	int usedhigh;
    392 	int last_used;
    393 } uio_fetcher_t;
    394 
    395 static void	uio_fetcher_ctor(uio_fetcher_t *, struct uio *, int);
    396 static int	uio_fetcher_fetch_to(struct audio_softc *, stream_fetcher_t *,
    397 				     audio_stream_t *, int);
    398 static int	null_fetcher_fetch_to(struct audio_softc *, stream_fetcher_t *,
    399 				      audio_stream_t *, int);
    400 
    401 static dev_type_open(audioopen);
    402 /* XXXMRG use more dev_type_xxx */
    403 
    404 const struct cdevsw audio_cdevsw = {
    405 	.d_open = audioopen,
    406 	.d_close = noclose,
    407 	.d_read = noread,
    408 	.d_write = nowrite,
    409 	.d_ioctl = noioctl,
    410 	.d_stop = nostop,
    411 	.d_tty = notty,
    412 	.d_poll = nopoll,
    413 	.d_mmap = nommap,
    414 	.d_kqfilter = nokqfilter,
    415 	.d_discard = nodiscard,
    416 	.d_flag = D_OTHER | D_MPSAFE
    417 };
    418 
    419 const struct fileops audio_fileops = {
    420 	.fo_read = audioread,
    421 	.fo_write = audiowrite,
    422 	.fo_ioctl = audioioctl,
    423 	.fo_fcntl = fnullop_fcntl,
    424 	.fo_stat = audiostat,
    425 	.fo_poll = audiopoll,
    426 	.fo_close = audioclose,
    427 	.fo_mmap = audio_fop_mmap,
    428 	.fo_kqfilter = audiokqfilter,
    429 	.fo_restart = fnullop_restart
    430 };
    431 
    432 /* The default audio mode: 8 kHz mono mu-law */
    433 const struct audio_params audio_default = {
    434 	.sample_rate = 8000,
    435 	.encoding = AUDIO_ENCODING_ULAW,
    436 	.precision = 8,
    437 	.validbits = 8,
    438 	.channels = 1,
    439 };
    440 
    441 int auto_config_precision[] = { 32, 24, 16, 8 };
    442 int auto_config_channels[] = { 32, 24, 16, 8, 6, 4, 2, 1};
    443 int auto_config_freq[] = { 48000, 44100, 96000, 192000, 32000,
    444 			   22050, 16000, 11025, 8000, 4000 };
    445 
    446 CFATTACH_DECL3_NEW(audio, sizeof(struct audio_softc),
    447     audiomatch, audioattach, audiodetach, audioactivate, audiorescan,
    448     audiochilddet, DVF_DETACH_SHUTDOWN);
    449 
    450 extern struct cfdriver audio_cd;
    451 
    452 static int
    453 audiomatch(device_t parent, cfdata_t match, void *aux)
    454 {
    455 	struct audio_attach_args *sa;
    456 
    457 	sa = aux;
    458 	DPRINTF(("%s: type=%d sa=%p hw=%p\n",
    459 		 __func__, sa->type, sa, sa->hwif));
    460 	return (sa->type == AUDIODEV_TYPE_AUDIO) ? 1 : 0;
    461 }
    462 
    463 static void
    464 audioattach(device_t parent, device_t self, void *aux)
    465 {
    466 	struct audio_softc *sc;
    467 	struct audio_attach_args *sa;
    468 	struct virtual_channel *vc;
    469 	struct audio_chan *chan;
    470 	const struct audio_hw_if *hwp;
    471 	const struct sysctlnode *node;
    472 	void *hdlp;
    473 	int error;
    474 	mixer_devinfo_t mi;
    475 	int iclass, mclass, oclass, rclass, props;
    476 	int record_master_found, record_source_found;
    477 	bool can_capture, can_playback;
    478 
    479 	sc = device_private(self);
    480 	sc->dev = self;
    481 	sa = aux;
    482 	hwp = sa->hwif;
    483 	hdlp = sa->hdl;
    484 	sc->sc_opens = 0;
    485 	sc->sc_recopens = 0;
    486 	sc->sc_aivalid = false;
    487  	sc->sc_ready = true;
    488 
    489  	sc->sc_format[0].mode = AUMODE_PLAY | AUMODE_RECORD;
    490  	sc->sc_format[0].encoding =
    491 #if BYTE_ORDER == LITTLE_ENDIAN
    492 		 AUDIO_ENCODING_SLINEAR_LE;
    493 #else
    494 		 AUDIO_ENCODING_SLINEAR_BE;
    495 #endif
    496  	sc->sc_format[0].precision = 16;
    497  	sc->sc_format[0].validbits = 16;
    498  	sc->sc_format[0].channels = 2;
    499  	sc->sc_format[0].channel_mask = AUFMT_STEREO;
    500  	sc->sc_format[0].frequency_type = 1;
    501  	sc->sc_format[0].frequency[0] = 44100;
    502 
    503 	sc->sc_vchan_params.sample_rate = 44100;
    504 #if BYTE_ORDER == LITTLE_ENDIAN
    505 	sc->sc_vchan_params.encoding = AUDIO_ENCODING_SLINEAR_LE;
    506 #else
    507 	sc->sc_vchan_params.encoding = AUDIO_ENCODING_SLINEAR_BE;
    508 #endif
    509 	sc->sc_vchan_params.precision = 16;
    510 	sc->sc_vchan_params.validbits = 16;
    511 	sc->sc_vchan_params.channels = 2;
    512 
    513 	sc->sc_trigger_started = false;
    514 	sc->sc_rec_started = false;
    515 	sc->sc_dying = false;
    516 	chan = kmem_zalloc(sizeof(struct audio_chan), KM_SLEEP);
    517 	vc = kmem_zalloc(sizeof(struct virtual_channel), KM_SLEEP);
    518 	chan->vc = vc;
    519 	SIMPLEQ_INIT(&sc->sc_audiochan);
    520 	SIMPLEQ_INSERT_HEAD(&sc->sc_audiochan, chan, entries);
    521 	vc->sc_open = 0;
    522 	vc->sc_mode = 0;
    523 	vc->sc_npfilters = 0;
    524 	memset(vc->sc_pfilters, 0,
    525 	    sizeof(vc->sc_pfilters));
    526 	vc->sc_lastinfovalid = false;
    527 	vc->sc_swvol = 255;
    528 	vc->sc_recswvol = 255;
    529 	sc->sc_iffreq = 44100;
    530 	sc->sc_precision = 16;
    531 	sc->sc_channels = 2;
    532 
    533 	if (auconv_create_encodings(sc->sc_format, VAUDIO_NFORMATS,
    534 	    &sc->sc_encodings) != 0) {
    535 		aprint_error_dev(self, "couldn't create encodings\n");
    536 		return;
    537 	}
    538 
    539 	cv_init(&sc->sc_rchan, "audiord");
    540 	cv_init(&sc->sc_wchan, "audiowr");
    541 	cv_init(&sc->sc_lchan, "audiolk");
    542 	cv_init(&sc->sc_condvar,"play");
    543 	cv_init(&sc->sc_rcondvar,"record");
    544 
    545 	if (hwp == 0 || hwp->get_locks == 0) {
    546 		aprint_error(": missing method\n");
    547 		panic("audioattach");
    548 	}
    549 
    550 	hwp->get_locks(hdlp, &sc->sc_intr_lock, &sc->sc_lock);
    551 
    552 #ifdef DIAGNOSTIC
    553 	if (hwp->query_encoding == 0 ||
    554 	    hwp->set_params == 0 ||
    555 	    (hwp->start_output == 0 && hwp->trigger_output == 0) ||
    556 	    (hwp->start_input == 0 && hwp->trigger_input == 0) ||
    557 	    hwp->halt_output == 0 ||
    558 	    hwp->halt_input == 0 ||
    559 	    hwp->getdev == 0 ||
    560 	    hwp->set_port == 0 ||
    561 	    hwp->get_port == 0 ||
    562 	    hwp->query_devinfo == 0 ||
    563 	    hwp->get_props == 0) {
    564 		aprint_error(": missing method\n");
    565 		sc->hw_if = NULL;
    566 		return;
    567 	}
    568 #endif
    569 
    570 	sc->hw_if = hwp;
    571 	sc->hw_hdl = hdlp;
    572 	sc->sc_dev = parent;
    573 
    574 	mutex_enter(sc->sc_lock);
    575 	props = audio_get_props(sc);
    576 	mutex_exit(sc->sc_lock);
    577 
    578 	if (props & AUDIO_PROP_FULLDUPLEX)
    579 		aprint_normal(": full duplex");
    580 	else
    581 		aprint_normal(": half duplex");
    582 
    583 	if (props & AUDIO_PROP_PLAYBACK)
    584 		aprint_normal(", playback");
    585 	if (props & AUDIO_PROP_CAPTURE)
    586 		aprint_normal(", capture");
    587 	if (props & AUDIO_PROP_MMAP)
    588 		aprint_normal(", mmap");
    589 	if (props & AUDIO_PROP_INDEPENDENT)
    590 		aprint_normal(", independent");
    591 
    592 	aprint_naive("\n");
    593 	aprint_normal("\n");
    594 
    595 	mutex_enter(sc->sc_lock);
    596 	can_playback = audio_can_playback(sc);
    597 	can_capture = audio_can_capture(sc);
    598 
    599 	if (can_playback) {
    600 		error = audio_alloc_ring(sc, &sc->sc_pr,
    601 	    	    AUMODE_PLAY, AU_RING_SIZE);
    602 		if (error)
    603 			goto bad_play;
    604 
    605 		error = audio_alloc_ring(sc, &vc->sc_mpr,
    606 	    	    AUMODE_PLAY, AU_RING_SIZE);
    607 bad_play:
    608 		if (error) {
    609 			if (sc->sc_pr.s.start != NULL)
    610 				audio_free_ring(sc, &sc->sc_pr);
    611 			sc->hw_if = NULL;
    612 			if (vc->sc_mpr.s.start != 0)
    613 				audio_free_ring(sc, &vc->sc_mpr);
    614 			sc->hw_if = NULL;
    615 			aprint_error_dev(sc->sc_dev, "could not allocate play "
    616 			    "buffer\n");
    617 			return;
    618 		}
    619 	}
    620 	if (can_capture) {
    621 		error = audio_alloc_ring(sc, &sc->sc_rr,
    622 		    AUMODE_RECORD, AU_RING_SIZE);
    623 		if (error)
    624 			goto bad_rec;
    625 
    626 		error = audio_alloc_ring(sc, &vc->sc_mrr,
    627 		    AUMODE_RECORD, AU_RING_SIZE);
    628 bad_rec:
    629 		if (error) {
    630 			if (vc->sc_mrr.s.start != NULL)
    631 				audio_free_ring(sc, &vc->sc_mrr);
    632 			if (sc->sc_pr.s.start != NULL)
    633 				audio_free_ring(sc, &sc->sc_pr);
    634 			if (vc->sc_mpr.s.start != 0)
    635 				audio_free_ring(sc, &vc->sc_mpr);
    636 			sc->hw_if = NULL;
    637 			aprint_error_dev(sc->sc_dev, "could not allocate record"
    638 			   " buffer\n");
    639 			return;
    640 		}
    641 	}
    642 
    643 	sc->sc_lastgain = 128;
    644 	sc->sc_saturate = true;
    645 	sc->sc_multiuser = false;
    646 	mutex_exit(sc->sc_lock);
    647 
    648 	error = vchan_autoconfig(sc);
    649 	if (error != 0) {
    650 		aprint_error_dev(sc->sc_dev, "%s: audio_set_vchan_defaults() "
    651 		    "failed\n", __func__);
    652 	}
    653 
    654 	sc->sc_pr.blksize = vc->sc_mpr.blksize;
    655 	sc->sc_rr.blksize = vc->sc_mrr.blksize;
    656 	sc->sc_sih_rd = softint_establish(SOFTINT_SERIAL | SOFTINT_MPSAFE,
    657 	    audio_softintr_rd, sc);
    658 	sc->sc_sih_wr = softint_establish(SOFTINT_SERIAL | SOFTINT_MPSAFE,
    659 	    audio_softintr_wr, sc);
    660 
    661 	iclass = mclass = oclass = rclass = -1;
    662 	sc->sc_inports.index = -1;
    663 	sc->sc_inports.master = -1;
    664 	sc->sc_inports.nports = 0;
    665 	sc->sc_inports.isenum = false;
    666 	sc->sc_inports.allports = 0;
    667 	sc->sc_inports.isdual = false;
    668 	sc->sc_inports.mixerout = -1;
    669 	sc->sc_inports.cur_port = -1;
    670 	sc->sc_outports.index = -1;
    671 	sc->sc_outports.master = -1;
    672 	sc->sc_outports.nports = 0;
    673 	sc->sc_outports.isenum = false;
    674 	sc->sc_outports.allports = 0;
    675 	sc->sc_outports.isdual = false;
    676 	sc->sc_outports.mixerout = -1;
    677 	sc->sc_outports.cur_port = -1;
    678 	sc->sc_monitor_port = -1;
    679 	/*
    680 	 * Read through the underlying driver's list, picking out the class
    681 	 * names from the mixer descriptions. We'll need them to decode the
    682 	 * mixer descriptions on the next pass through the loop.
    683 	 */
    684 	mutex_enter(sc->sc_lock);
    685 	for(mi.index = 0; ; mi.index++) {
    686 		if (audio_query_devinfo(sc, &mi) != 0)
    687 			break;
    688 		 /*
    689 		  * The type of AUDIO_MIXER_CLASS merely introduces a class.
    690 		  * All the other types describe an actual mixer.
    691 		  */
    692 		if (mi.type == AUDIO_MIXER_CLASS) {
    693 			if (strcmp(mi.label.name, AudioCinputs) == 0)
    694 				iclass = mi.mixer_class;
    695 			if (strcmp(mi.label.name, AudioCmonitor) == 0)
    696 				mclass = mi.mixer_class;
    697 			if (strcmp(mi.label.name, AudioCoutputs) == 0)
    698 				oclass = mi.mixer_class;
    699 			if (strcmp(mi.label.name, AudioCrecord) == 0)
    700 				rclass = mi.mixer_class;
    701 		}
    702 	}
    703 	mutex_exit(sc->sc_lock);
    704 
    705 	/* Allocate save area.  Ensure non-zero allocation. */
    706 	sc->sc_static_nmixer_states = mi.index;
    707 	sc->sc_static_nmixer_states++;
    708 	sc->sc_nmixer_states = sc->sc_static_nmixer_states;
    709 	sc->sc_mixer_state = kmem_zalloc(sizeof(mixer_ctrl_t) *
    710 	    (sc->sc_nmixer_states + 1), KM_SLEEP);
    711 
    712 	/*
    713 	 * This is where we assign each control in the "audio" model, to the
    714 	 * underlying "mixer" control.  We walk through the whole list once,
    715 	 * assigning likely candidates as we come across them.
    716 	 */
    717 	record_master_found = 0;
    718 	record_source_found = 0;
    719 	mutex_enter(sc->sc_lock);
    720 	for(mi.index = 0; ; mi.index++) {
    721 		if (audio_query_devinfo(sc, &mi) != 0)
    722 			break;
    723 		KASSERT(mi.index < sc->sc_nmixer_states);
    724 		if (mi.type == AUDIO_MIXER_CLASS)
    725 			continue;
    726 		if (mi.mixer_class == iclass) {
    727 			/*
    728 			 * AudioCinputs is only a fallback, when we don't
    729 			 * find what we're looking for in AudioCrecord, so
    730 			 * check the flags before accepting one of these.
    731 			 */
    732 			if (strcmp(mi.label.name, AudioNmaster) == 0
    733 			    && record_master_found == 0)
    734 				sc->sc_inports.master = mi.index;
    735 			if (strcmp(mi.label.name, AudioNsource) == 0
    736 			    && record_source_found == 0) {
    737 				if (mi.type == AUDIO_MIXER_ENUM) {
    738 				    int i;
    739 				    for(i = 0; i < mi.un.e.num_mem; i++)
    740 					if (strcmp(mi.un.e.member[i].label.name,
    741 						    AudioNmixerout) == 0)
    742 						sc->sc_inports.mixerout =
    743 						    mi.un.e.member[i].ord;
    744 				}
    745 				au_setup_ports(sc, &sc->sc_inports, &mi,
    746 				    itable);
    747 			}
    748 			if (strcmp(mi.label.name, AudioNdac) == 0 &&
    749 			    sc->sc_outports.master == -1)
    750 				sc->sc_outports.master = mi.index;
    751 		} else if (mi.mixer_class == mclass) {
    752 			if (strcmp(mi.label.name, AudioNmonitor) == 0)
    753 				sc->sc_monitor_port = mi.index;
    754 		} else if (mi.mixer_class == oclass) {
    755 			if (strcmp(mi.label.name, AudioNmaster) == 0)
    756 				sc->sc_outports.master = mi.index;
    757 			if (strcmp(mi.label.name, AudioNselect) == 0)
    758 				au_setup_ports(sc, &sc->sc_outports, &mi,
    759 				    otable);
    760 		} else if (mi.mixer_class == rclass) {
    761 			/*
    762 			 * These are the preferred mixers for the audio record
    763 			 * controls, so set the flags here, but don't check.
    764 			 */
    765 			if (strcmp(mi.label.name, AudioNmaster) == 0) {
    766 				sc->sc_inports.master = mi.index;
    767 				record_master_found = 1;
    768 			}
    769 #if 1	/* Deprecated. Use AudioNmaster. */
    770 			if (strcmp(mi.label.name, AudioNrecord) == 0) {
    771 				sc->sc_inports.master = mi.index;
    772 				record_master_found = 1;
    773 			}
    774 			if (strcmp(mi.label.name, AudioNvolume) == 0) {
    775 				sc->sc_inports.master = mi.index;
    776 				record_master_found = 1;
    777 			}
    778 #endif
    779 			if (strcmp(mi.label.name, AudioNsource) == 0) {
    780 				if (mi.type == AUDIO_MIXER_ENUM) {
    781 				    int i;
    782 				    for(i = 0; i < mi.un.e.num_mem; i++)
    783 					if (strcmp(mi.un.e.member[i].label.name,
    784 						    AudioNmixerout) == 0)
    785 						sc->sc_inports.mixerout =
    786 						    mi.un.e.member[i].ord;
    787 				}
    788 				au_setup_ports(sc, &sc->sc_inports, &mi,
    789 				    itable);
    790 				record_source_found = 1;
    791 			}
    792 		}
    793 	}
    794 	mutex_exit(sc->sc_lock);
    795 	DPRINTF(("audio_attach: inputs ports=0x%x, input master=%d, "
    796 		 "output ports=0x%x, output master=%d\n",
    797 		 sc->sc_inports.allports, sc->sc_inports.master,
    798 		 sc->sc_outports.allports, sc->sc_outports.master));
    799 
    800 	/* sysctl set-up for alternate configs */
    801 	sysctl_createv(&sc->sc_log, 0, NULL, &node,
    802 		0,
    803 		CTLTYPE_NODE, device_xname(sc->sc_dev),
    804 		SYSCTL_DESCR("audio format information"),
    805 		NULL, 0,
    806 		NULL, 0,
    807 		CTL_HW,
    808 		CTL_CREATE, CTL_EOL);
    809 
    810 	if (node != NULL) {
    811 		sysctl_createv(&sc->sc_log, 0, NULL, NULL,
    812 			CTLFLAG_READWRITE,
    813 			CTLTYPE_INT, "frequency",
    814 			SYSCTL_DESCR("intermediate frequency"),
    815 			audio_sysctl_frequency, 0,
    816 			(void *)sc, 0,
    817 			CTL_HW, node->sysctl_num,
    818 			CTL_CREATE, CTL_EOL);
    819 
    820 		sysctl_createv(&sc->sc_log, 0, NULL, NULL,
    821 			CTLFLAG_READWRITE,
    822 			CTLTYPE_INT, "precision",
    823 			SYSCTL_DESCR("intermediate precision"),
    824 			audio_sysctl_precision, 0,
    825 			(void *)sc, 0,
    826 			CTL_HW, node->sysctl_num,
    827 			CTL_CREATE, CTL_EOL);
    828 
    829 		sysctl_createv(&sc->sc_log, 0, NULL, NULL,
    830 			CTLFLAG_READWRITE,
    831 			CTLTYPE_INT, "channels",
    832 			SYSCTL_DESCR("intermediate channels"),
    833 			audio_sysctl_channels, 0,
    834 			(void *)sc, 0,
    835 			CTL_HW, node->sysctl_num,
    836 			CTL_CREATE, CTL_EOL);
    837 
    838 		sysctl_createv(&sc->sc_log, 0, NULL, NULL,
    839 			CTLFLAG_READWRITE,
    840 			CTLTYPE_BOOL, "saturate",
    841 			SYSCTL_DESCR("saturate to max. volume"),
    842 			NULL, 0,
    843 			&sc->sc_saturate, 0,
    844 			CTL_HW, node->sysctl_num,
    845 			CTL_CREATE, CTL_EOL);
    846 
    847 		sysctl_createv(&sc->sc_log, 0, NULL, NULL,
    848 			CTLFLAG_READWRITE,
    849 			CTLTYPE_BOOL, "multiuser",
    850 			SYSCTL_DESCR("allow multiple user acess"),
    851 			NULL, 0,
    852 			&sc->sc_multiuser, 0,
    853 			CTL_HW, node->sysctl_num,
    854 			CTL_CREATE, CTL_EOL);
    855 	}
    856 
    857 	selinit(&sc->sc_rsel);
    858 	selinit(&sc->sc_wsel);
    859 
    860 #ifdef AUDIO_PM_IDLE
    861 	callout_init(&sc->sc_idle_counter, 0);
    862 	callout_setfunc(&sc->sc_idle_counter, audio_idle, self);
    863 #endif
    864 
    865 	if (!pmf_device_register(self, audio_suspend, audio_resume))
    866 		aprint_error_dev(self, "couldn't establish power handler\n");
    867 #ifdef AUDIO_PM_IDLE
    868 	if (!device_active_register(self, audio_activity))
    869 		aprint_error_dev(self, "couldn't register activity handler\n");
    870 #endif
    871 
    872 	if (!pmf_event_register(self, PMFE_AUDIO_VOLUME_DOWN,
    873 	    audio_volume_down, true))
    874 		aprint_error_dev(self, "couldn't add volume down handler\n");
    875 	if (!pmf_event_register(self, PMFE_AUDIO_VOLUME_UP,
    876 	    audio_volume_up, true))
    877 		aprint_error_dev(self, "couldn't add volume up handler\n");
    878 	if (!pmf_event_register(self, PMFE_AUDIO_VOLUME_TOGGLE,
    879 	    audio_volume_toggle, true))
    880 		aprint_error_dev(self, "couldn't add volume toggle handler\n");
    881 
    882 #ifdef AUDIO_PM_IDLE
    883 	callout_schedule(&sc->sc_idle_counter, audio_idle_timeout * hz);
    884 #endif
    885 	kthread_create(PRI_NONE, KTHREAD_MPSAFE | KTHREAD_MUSTJOIN, NULL,
    886 	    audio_rec_thread, sc, &sc->sc_recthread, "audiorec");
    887 	kthread_create(PRI_NONE, KTHREAD_MPSAFE | KTHREAD_MUSTJOIN, NULL,
    888 	    audio_play_thread, sc, &sc->sc_playthread, "audiomix");
    889 	audiorescan(self, "audio", NULL);
    890 }
    891 
    892 static int
    893 audioactivate(device_t self, enum devact act)
    894 {
    895 	struct audio_softc *sc = device_private(self);
    896 
    897 	switch (act) {
    898 	case DVACT_DEACTIVATE:
    899 		mutex_enter(sc->sc_lock);
    900 		sc->sc_dying = true;
    901 		mutex_enter(sc->sc_intr_lock);
    902 		cv_broadcast(&sc->sc_condvar);
    903 		mutex_exit(sc->sc_intr_lock);
    904 		mutex_exit(sc->sc_lock);
    905 		return 0;
    906 	default:
    907 		return EOPNOTSUPP;
    908 	}
    909 }
    910 
    911 static int
    912 audiodetach(device_t self, int flags)
    913 {
    914 	struct audio_softc *sc;
    915 	struct audio_chan *chan;
    916 	int maj, mn, i, rc;
    917 
    918 	sc = device_private(self);
    919 	DPRINTF(("audio_detach: sc=%p flags=%d\n", sc, flags));
    920 
    921 	/* Start draining existing accessors of the device. */
    922 	if ((rc = config_detach_children(self, flags)) != 0)
    923 		return rc;
    924 	mutex_enter(sc->sc_lock);
    925 	sc->sc_dying = true;
    926 	cv_broadcast(&sc->sc_wchan);
    927 	cv_broadcast(&sc->sc_rchan);
    928 	mutex_enter(sc->sc_intr_lock);
    929 	cv_broadcast(&sc->sc_condvar);
    930 	cv_broadcast(&sc->sc_rcondvar);
    931 	mutex_exit(sc->sc_intr_lock);
    932 	mutex_exit(sc->sc_lock);
    933 	kthread_join(sc->sc_playthread);
    934 	kthread_join(sc->sc_recthread);
    935 	mutex_enter(sc->sc_lock);
    936 	cv_destroy(&sc->sc_condvar);
    937 	cv_destroy(&sc->sc_rcondvar);
    938 	mutex_exit(sc->sc_lock);
    939 
    940 	/* delete sysctl nodes */
    941 	sysctl_teardown(&sc->sc_log);
    942 
    943 	/* locate the major number */
    944 	maj = cdevsw_lookup_major(&audio_cdevsw);
    945 
    946 	/*
    947 	 * Nuke the vnodes for any open instances (calls close).
    948 	 * Will wait until any activity on the device nodes has ceased.
    949 	 *
    950 	 * XXXAD NOT YET.
    951 	 *
    952 	 * XXXAD NEED TO PREVENT NEW REFERENCES THROUGH AUDIO_ENTER().
    953 	 */
    954 	mn = device_unit(self);
    955 	vdevgone(maj, mn | SOUND_DEVICE,    mn | SOUND_DEVICE, VCHR);
    956 	vdevgone(maj, mn | AUDIO_DEVICE,    mn | AUDIO_DEVICE, VCHR);
    957 	vdevgone(maj, mn | AUDIOCTL_DEVICE, mn | AUDIOCTL_DEVICE, VCHR);
    958 	vdevgone(maj, mn | MIXER_DEVICE,    mn | MIXER_DEVICE, VCHR);
    959 
    960 	pmf_event_deregister(self, PMFE_AUDIO_VOLUME_DOWN,
    961 	    audio_volume_down, true);
    962 	pmf_event_deregister(self, PMFE_AUDIO_VOLUME_UP,
    963 	    audio_volume_up, true);
    964 	pmf_event_deregister(self, PMFE_AUDIO_VOLUME_TOGGLE,
    965 	    audio_volume_toggle, true);
    966 
    967 #ifdef AUDIO_PM_IDLE
    968 	callout_halt(&sc->sc_idle_counter, sc->sc_lock);
    969 
    970 	device_active_deregister(self, audio_activity);
    971 #endif
    972 
    973 	pmf_device_deregister(self);
    974 
    975 	/* free resources */
    976 	SIMPLEQ_FOREACH(chan, &sc->sc_audiochan, entries) {
    977 		if (chan == NULL)
    978 			break;
    979 
    980 		if (chan->chan == MIXER_INUSE)
    981 			continue;
    982 		audio_free_ring(sc, &chan->vc->sc_mpr);
    983 		audio_free_ring(sc, &chan->vc->sc_mrr);
    984 	}
    985 	audio_free_ring(sc, &sc->sc_pr);
    986 	audio_free_ring(sc, &sc->sc_rr);
    987 	SIMPLEQ_FOREACH(chan, &sc->sc_audiochan, entries) {
    988 		if (chan == NULL)
    989 			break;
    990 
    991 		if (chan->chan == MIXER_INUSE)
    992 			continue;
    993 		for (i = 0; i < chan->vc->sc_npfilters; i++) {
    994 			chan->vc->sc_pfilters[i]->dtor
    995 			    (chan->vc->sc_pfilters[i]);
    996 			chan->vc->sc_pfilters[i] = NULL;
    997 			audio_stream_dtor(&chan->vc->sc_pstreams[i]);
    998 		}
    999 		chan->vc->sc_npfilters = 0;
   1000 
   1001 		for (i = 0; i < chan->vc->sc_nrfilters; i++) {
   1002 			chan->vc->sc_rfilters[i]->dtor
   1003 			    (chan->vc->sc_rfilters[i]);
   1004 			chan->vc->sc_rfilters[i] = NULL;
   1005 			audio_stream_dtor(&chan->vc->sc_rstreams[i]);
   1006 		}
   1007 		chan->vc->sc_nrfilters = 0;
   1008 	}
   1009 
   1010 	auconv_delete_encodings(sc->sc_encodings);
   1011 
   1012 	if (sc->sc_sih_rd) {
   1013 		softint_disestablish(sc->sc_sih_rd);
   1014 		sc->sc_sih_rd = NULL;
   1015 	}
   1016 	if (sc->sc_sih_wr) {
   1017 		softint_disestablish(sc->sc_sih_wr);
   1018 		sc->sc_sih_wr = NULL;
   1019 	}
   1020 
   1021 	chan = SIMPLEQ_FIRST(&sc->sc_audiochan);
   1022 	kmem_free(chan->vc, sizeof(struct virtual_channel));
   1023 	SIMPLEQ_REMOVE(&sc->sc_audiochan, chan, audio_chan, entries);
   1024 	kmem_free(chan, sizeof(struct audio_chan));
   1025 	kmem_free(sc->sc_mixer_state, sizeof(mixer_ctrl_t) *
   1026 	    (sc->sc_nmixer_states + 1));
   1027 
   1028 #ifdef AUDIO_PM_IDLE
   1029 	callout_destroy(&sc->sc_idle_counter);
   1030 #endif
   1031 	seldestroy(&sc->sc_rsel);
   1032 	seldestroy(&sc->sc_wsel);
   1033 
   1034 	cv_destroy(&sc->sc_rchan);
   1035 	cv_destroy(&sc->sc_wchan);
   1036 	cv_destroy(&sc->sc_lchan);
   1037 
   1038 	return 0;
   1039 }
   1040 
   1041 static void
   1042 audiochilddet(device_t self, device_t child)
   1043 {
   1044 
   1045 	/* we hold no child references, so do nothing */
   1046 }
   1047 
   1048 static int
   1049 audiosearch(device_t parent, cfdata_t cf, const int *locs, void *aux)
   1050 {
   1051 
   1052 	if (config_match(parent, cf, aux))
   1053 		config_attach_loc(parent, cf, locs, aux, NULL);
   1054 
   1055 	return 0;
   1056 }
   1057 
   1058 static int
   1059 audiorescan(device_t self, const char *ifattr, const int *flags)
   1060 {
   1061 	struct audio_softc *sc = device_private(self);
   1062 
   1063 	if (!ifattr_match(ifattr, "audio"))
   1064 		return 0;
   1065 
   1066 	config_search_loc(audiosearch, sc->dev, "audio", NULL, NULL);
   1067 
   1068 	return 0;
   1069 }
   1070 
   1071 
   1072 int
   1073 au_portof(struct audio_softc *sc, char *name, int class)
   1074 {
   1075 	mixer_devinfo_t mi;
   1076 
   1077 	for (mi.index = 0; audio_query_devinfo(sc, &mi) == 0; mi.index++) {
   1078 		if (mi.mixer_class == class && strcmp(mi.label.name, name) == 0)
   1079 			return mi.index;
   1080 	}
   1081 	return -1;
   1082 }
   1083 
   1084 void
   1085 au_setup_ports(struct audio_softc *sc, struct au_mixer_ports *ports,
   1086 	       mixer_devinfo_t *mi, const struct portname *tbl)
   1087 {
   1088 	int i, j;
   1089 
   1090 	ports->index = mi->index;
   1091 	if (mi->type == AUDIO_MIXER_ENUM) {
   1092 		ports->isenum = true;
   1093 		for(i = 0; tbl[i].name; i++)
   1094 		    for(j = 0; j < mi->un.e.num_mem; j++)
   1095 			if (strcmp(mi->un.e.member[j].label.name,
   1096 						    tbl[i].name) == 0) {
   1097 				ports->allports |= tbl[i].mask;
   1098 				ports->aumask[ports->nports] = tbl[i].mask;
   1099 				ports->misel[ports->nports] =
   1100 				    mi->un.e.member[j].ord;
   1101 				ports->miport[ports->nports] =
   1102 				    au_portof(sc, mi->un.e.member[j].label.name,
   1103 				    mi->mixer_class);
   1104 				if (ports->mixerout != -1 &&
   1105 				    ports->miport[ports->nports] != -1)
   1106 					ports->isdual = true;
   1107 				++ports->nports;
   1108 			}
   1109 	} else if (mi->type == AUDIO_MIXER_SET) {
   1110 		for(i = 0; tbl[i].name; i++)
   1111 		    for(j = 0; j < mi->un.s.num_mem; j++)
   1112 			if (strcmp(mi->un.s.member[j].label.name,
   1113 						tbl[i].name) == 0) {
   1114 				ports->allports |= tbl[i].mask;
   1115 				ports->aumask[ports->nports] = tbl[i].mask;
   1116 				ports->misel[ports->nports] =
   1117 				    mi->un.s.member[j].mask;
   1118 				ports->miport[ports->nports] =
   1119 				    au_portof(sc, mi->un.s.member[j].label.name,
   1120 				    mi->mixer_class);
   1121 				++ports->nports;
   1122 			}
   1123 	}
   1124 }
   1125 
   1126 /*
   1127  * Called from hardware driver.  This is where the MI audio driver gets
   1128  * probed/attached to the hardware driver.
   1129  */
   1130 device_t
   1131 audio_attach_mi(const struct audio_hw_if *ahwp, void *hdlp, device_t dev)
   1132 {
   1133 	struct audio_attach_args arg;
   1134 
   1135 #ifdef DIAGNOSTIC
   1136 	if (ahwp == NULL) {
   1137 		aprint_error("audio_attach_mi: NULL\n");
   1138 		return 0;
   1139 	}
   1140 #endif
   1141 	arg.type = AUDIODEV_TYPE_AUDIO;
   1142 	arg.hwif = ahwp;
   1143 	arg.hdl = hdlp;
   1144 	return config_found(dev, &arg, audioprint);
   1145 }
   1146 
   1147 #ifdef AUDIO_DEBUG
   1148 void	audio_printsc(struct audio_softc *);
   1149 void	audio_print_params(const char *, struct audio_params *);
   1150 
   1151 void
   1152 audio_printsc(struct audio_softc *sc)
   1153 {
   1154 	struct audio_chan *chan;
   1155 
   1156 	chan = SIMPLEQ_FIRST(&sc->sc_audiochan);
   1157 
   1158 	if (chan == NULL)
   1159 		return;
   1160 
   1161 	printf("hwhandle %p hw_if %p ", sc->hw_hdl, sc->hw_if);
   1162 	printf("open 0x%x mode 0x%x\n", chan->vc->sc_open,
   1163 	    chan->vc->sc_mode);
   1164 	printf("rchan 0x%x wchan 0x%x ", cv_has_waiters(&sc->sc_rchan),
   1165 	    cv_has_waiters(&sc->sc_wchan));
   1166 	printf("rring used 0x%x pring used=%d\n",
   1167 	       audio_stream_get_used(&chan->vc->sc_mrr.s),
   1168 	       audio_stream_get_used(&chan->vc->sc_mpr.s));
   1169 	printf("rbus 0x%x pbus 0x%x ", chan->vc->sc_rbus,
   1170 	    chan->vc->sc_pbus);
   1171 	printf("blksize %d", chan->vc->sc_mpr.blksize);
   1172 	printf("hiwat %d lowat %d\n", chan->vc->sc_mpr.usedhigh,
   1173 	    chan->vc->sc_mpr.usedlow);
   1174 }
   1175 
   1176 void
   1177 audio_print_params(const char *s, struct audio_params *p)
   1178 {
   1179 	printf("%s enc=%u %uch %u/%ubit %uHz\n", s, p->encoding, p->channels,
   1180 	       p->validbits, p->precision, p->sample_rate);
   1181 }
   1182 #endif
   1183 
   1184 int
   1185 audio_alloc_ring(struct audio_softc *sc, struct audio_ringbuffer *r,
   1186 		 int direction, size_t bufsize)
   1187 {
   1188 	const struct audio_hw_if *hw;
   1189 	struct audio_chan *chan;
   1190 	void *hdl;
   1191 
   1192 	chan = SIMPLEQ_FIRST(&sc->sc_audiochan);
   1193 	hw = sc->hw_if;
   1194 	hdl = sc->hw_hdl;
   1195 	/*
   1196 	 * Alloc DMA play and record buffers
   1197 	 */
   1198 	if (bufsize < AUMINBUF)
   1199 		bufsize = AUMINBUF;
   1200 	ROUNDSIZE(bufsize);
   1201 	if (hw->round_buffersize) {
   1202 		bufsize = hw->round_buffersize(hdl, direction, bufsize);
   1203 	}
   1204 	if (hw->allocm && (r == &chan->vc->sc_mpr || r == &chan->vc->sc_mrr))
   1205 		r->s.start = hw->allocm(hdl, direction, bufsize);
   1206 	else
   1207 		r->s.start = kmem_zalloc(bufsize, KM_SLEEP);
   1208 	if (r->s.start == NULL)
   1209 		return ENOMEM;
   1210 	r->s.bufsize = bufsize;
   1211 
   1212 	return 0;
   1213 }
   1214 
   1215 void
   1216 audio_free_ring(struct audio_softc *sc, struct audio_ringbuffer *r)
   1217 {
   1218 	struct audio_chan *chan;
   1219 
   1220 	if (r->s.start == NULL)
   1221 		return;
   1222 
   1223 	chan = SIMPLEQ_FIRST(&sc->sc_audiochan);
   1224 
   1225 	if (sc->hw_if->freem && (r == &chan->vc->sc_mpr ||
   1226 						r == &chan->vc->sc_mrr))
   1227 		sc->hw_if->freem(sc->hw_hdl, r->s.start, r->s.bufsize);
   1228 	else
   1229 		kmem_free(r->s.start, r->s.bufsize);
   1230 	r->s.start = NULL;
   1231 }
   1232 
   1233 static int
   1234 audio_setup_pfilters(struct audio_softc *sc, const audio_params_t *pp,
   1235 		     stream_filter_list_t *pfilters, struct virtual_channel *vc)
   1236 {
   1237 	stream_filter_t *pf[AUDIO_MAX_FILTERS], *of[AUDIO_MAX_FILTERS];
   1238 	audio_stream_t ps[AUDIO_MAX_FILTERS], os[AUDIO_MAX_FILTERS];
   1239 	const audio_params_t *from_param;
   1240 	audio_params_t *to_param;
   1241 	int i, n, onfilters;
   1242 
   1243 	KASSERT(mutex_owned(sc->sc_lock));
   1244 
   1245 	/* Construct new filters. */
   1246 	memset(pf, 0, sizeof(pf));
   1247 	memset(ps, 0, sizeof(ps));
   1248 	from_param = pp;
   1249 	for (i = 0; i < pfilters->req_size; i++) {
   1250 		n = pfilters->req_size - i - 1;
   1251 		to_param = &pfilters->filters[n].param;
   1252 		audio_check_params(to_param);
   1253 		pf[i] = pfilters->filters[n].factory(sc, from_param, to_param);
   1254 		if (pf[i] == NULL)
   1255 			break;
   1256 		if (audio_stream_ctor(&ps[i], from_param, AU_RING_SIZE))
   1257 			break;
   1258 		if (i > 0)
   1259 			pf[i]->set_fetcher(pf[i], &pf[i - 1]->base);
   1260 		from_param = to_param;
   1261 	}
   1262 	if (i < pfilters->req_size) { /* failure */
   1263 		DPRINTF(("%s: pfilters failure\n", __func__));
   1264 		for (; i >= 0; i--) {
   1265 			if (pf[i] != NULL)
   1266 				pf[i]->dtor(pf[i]);
   1267 			audio_stream_dtor(&ps[i]);
   1268 		}
   1269 		return EINVAL;
   1270 	}
   1271 
   1272 	/* Swap in new filters. */
   1273 	HW_LOCK(vc);
   1274 	memcpy(of, vc->sc_pfilters, sizeof(of));
   1275 	memcpy(os, vc->sc_pstreams, sizeof(os));
   1276 	onfilters = vc->sc_npfilters;
   1277 	memcpy(vc->sc_pfilters, pf, sizeof(pf));
   1278 	memcpy(vc->sc_pstreams, ps, sizeof(ps));
   1279 	vc->sc_npfilters = pfilters->req_size;
   1280 	for (i = 0; i < pfilters->req_size; i++)
   1281 		pf[i]->set_inputbuffer(pf[i], &vc->sc_pstreams[i]);
   1282 
   1283 	/* hardware format and the buffer near to userland */
   1284 	if (pfilters->req_size <= 0) {
   1285 		vc->sc_mpr.s.param = *pp;
   1286 		vc->sc_pustream = &vc->sc_mpr.s;
   1287 	} else {
   1288 		vc->sc_mpr.s.param = pfilters->filters[0].param;
   1289 		vc->sc_pustream = &vc->sc_pstreams[0];
   1290 	}
   1291 	HW_UNLOCK(vc);
   1292 
   1293 	/* Destroy old filters. */
   1294 	for (i = 0; i < onfilters; i++) {
   1295 		of[i]->dtor(of[i]);
   1296 		audio_stream_dtor(&os[i]);
   1297 	}
   1298 
   1299 #ifdef AUDIO_DEBUG
   1300 	printf("%s: HW-buffer=%p pustream=%p\n",
   1301 	       __func__, &vc->sc_mpr.s, vc->sc_pustream);
   1302 	for (i = 0; i < pfilters->req_size; i++) {
   1303 		char num[100];
   1304 		snprintf(num, 100, "[%d]", i);
   1305 		audio_print_params(num, &vc->sc_pstreams[i].param);
   1306 	}
   1307 	audio_print_params("[HW]", &vc->sc_mpr.s.param);
   1308 #endif /* AUDIO_DEBUG */
   1309 
   1310 	return 0;
   1311 }
   1312 
   1313 static int
   1314 audio_setup_rfilters(struct audio_softc *sc, const audio_params_t *rp,
   1315 		     stream_filter_list_t *rfilters, struct virtual_channel *vc)
   1316 {
   1317 	stream_filter_t *rf[AUDIO_MAX_FILTERS], *of[AUDIO_MAX_FILTERS];
   1318 	audio_stream_t rs[AUDIO_MAX_FILTERS], os[AUDIO_MAX_FILTERS];
   1319 	const audio_params_t *to_param;
   1320 	audio_params_t *from_param;
   1321 	int i, onfilters;
   1322 
   1323 	KASSERT(mutex_owned(sc->sc_lock));
   1324 
   1325 	/* Construct new filters. */
   1326 	memset(rf, 0, sizeof(rf));
   1327 	memset(rs, 0, sizeof(rs));
   1328 	for (i = 0; i < rfilters->req_size; i++) {
   1329 		from_param = &rfilters->filters[i].param;
   1330 		audio_check_params(from_param);
   1331 		to_param = i + 1 < rfilters->req_size
   1332 			? &rfilters->filters[i + 1].param : rp;
   1333 		rf[i] = rfilters->filters[i].factory(sc, from_param, to_param);
   1334 		if (rf[i] == NULL)
   1335 			break;
   1336 		if (audio_stream_ctor(&rs[i], to_param, AU_RING_SIZE))
   1337 			break;
   1338 		if (i > 0) {
   1339 			rf[i]->set_fetcher(rf[i], &rf[i - 1]->base);
   1340 		} else {
   1341 			/* rf[0] has no previous fetcher because
   1342 			 * the audio hardware fills data to the
   1343 			 * input buffer. */
   1344 			rf[0]->set_inputbuffer(rf[0], &vc->sc_mrr.s);
   1345 		}
   1346 	}
   1347 	if (i < rfilters->req_size) { /* failure */
   1348 		DPRINTF(("%s: rfilters failure\n", __func__));
   1349 		for (; i >= 0; i--) {
   1350 			if (rf[i] != NULL)
   1351 				rf[i]->dtor(rf[i]);
   1352 			audio_stream_dtor(&rs[i]);
   1353 		}
   1354 		return EINVAL;
   1355 	}
   1356 
   1357 	/* Swap in new filters. */
   1358 	HW_LOCK(vc);
   1359 	memcpy(of, vc->sc_rfilters, sizeof(of));
   1360 	memcpy(os, vc->sc_rstreams, sizeof(os));
   1361 	onfilters = vc->sc_nrfilters;
   1362 	memcpy(vc->sc_rfilters, rf, sizeof(rf));
   1363 	memcpy(vc->sc_rstreams, rs, sizeof(rs));
   1364 	vc->sc_nrfilters = rfilters->req_size;
   1365 	for (i = 1; i < rfilters->req_size; i++)
   1366 		rf[i]->set_inputbuffer(rf[i], &vc->sc_rstreams[i - 1]);
   1367 
   1368 	/* hardware format and the buffer near to userland */
   1369 	if (rfilters->req_size <= 0) {
   1370 		vc->sc_mrr.s.param = *rp;
   1371 		vc->sc_rustream = &vc->sc_mrr.s;
   1372 	} else {
   1373 		vc->sc_mrr.s.param = rfilters->filters[0].param;
   1374 		vc->sc_rustream = &vc->sc_rstreams[rfilters->req_size - 1];
   1375 	}
   1376 	HW_UNLOCK(vc);
   1377 
   1378 #ifdef AUDIO_DEBUG
   1379 	printf("%s: HW-buffer=%p pustream=%p\n",
   1380 	       __func__, &vc->sc_mrr.s, vc->sc_rustream);
   1381 	audio_print_params("[HW]", &vc->sc_mrr.s.param);
   1382 	for (i = 0; i < rfilters->req_size; i++) {
   1383 		char num[100];
   1384 		snprintf(num, 100, "[%d]", i);
   1385 		audio_print_params(num, &vc->sc_rstreams[i].param);
   1386 	}
   1387 #endif /* AUDIO_DEBUG */
   1388 
   1389 	/* Destroy old filters. */
   1390 	for (i = 0; i < onfilters; i++) {
   1391 		of[i]->dtor(of[i]);
   1392 		audio_stream_dtor(&os[i]);
   1393 	}
   1394 
   1395 	return 0;
   1396 }
   1397 
   1398 static void
   1399 audio_stream_dtor(audio_stream_t *stream)
   1400 {
   1401 
   1402 	if (stream->start != NULL)
   1403 		kmem_free(stream->start, stream->bufsize);
   1404 	memset(stream, 0, sizeof(audio_stream_t));
   1405 }
   1406 
   1407 static int
   1408 audio_stream_ctor(audio_stream_t *stream, const audio_params_t *param, int size)
   1409 {
   1410 	int frame_size;
   1411 
   1412 	size = min(size, AU_RING_SIZE);
   1413 	stream->bufsize = size;
   1414 	stream->start = kmem_zalloc(size, KM_SLEEP);
   1415 	frame_size = (param->precision + 7) / 8 * param->channels;
   1416 	size = (size / frame_size) * frame_size;
   1417 	stream->end = stream->start + size;
   1418 	stream->inp = stream->start;
   1419 	stream->outp = stream->start;
   1420 	stream->used = 0;
   1421 	stream->param = *param;
   1422 	stream->loop = false;
   1423 	return 0;
   1424 }
   1425 
   1426 static void
   1427 stream_filter_list_append(stream_filter_list_t *list,
   1428 			  stream_filter_factory_t factory,
   1429 			  const audio_params_t *param)
   1430 {
   1431 
   1432 	if (list->req_size >= AUDIO_MAX_FILTERS) {
   1433 		printf("%s: increase AUDIO_MAX_FILTERS in sys/dev/audio_if.h\n",
   1434 		       __func__);
   1435 		return;
   1436 	}
   1437 	list->filters[list->req_size].factory = factory;
   1438 	list->filters[list->req_size].param = *param;
   1439 	list->req_size++;
   1440 }
   1441 
   1442 static void
   1443 stream_filter_list_set(stream_filter_list_t *list, int i,
   1444 		       stream_filter_factory_t factory,
   1445 		       const audio_params_t *param)
   1446 {
   1447 
   1448 	if (i < 0 || i >= AUDIO_MAX_FILTERS) {
   1449 		printf("%s: invalid index: %d\n", __func__, i);
   1450 		return;
   1451 	}
   1452 
   1453 	list->filters[i].factory = factory;
   1454 	list->filters[i].param = *param;
   1455 	if (list->req_size <= i)
   1456 		list->req_size = i + 1;
   1457 }
   1458 
   1459 static void
   1460 stream_filter_list_prepend(stream_filter_list_t *list,
   1461 			   stream_filter_factory_t factory,
   1462 			   const audio_params_t *param)
   1463 {
   1464 
   1465 	if (list->req_size >= AUDIO_MAX_FILTERS) {
   1466 		printf("%s: increase AUDIO_MAX_FILTERS in sys/dev/audio_if.h\n",
   1467 		       __func__);
   1468 		return;
   1469 	}
   1470 	memmove(&list->filters[1], &list->filters[0],
   1471 		sizeof(struct stream_filter_req) * list->req_size);
   1472 	list->filters[0].factory = factory;
   1473 	list->filters[0].param = *param;
   1474 	list->req_size++;
   1475 }
   1476 
   1477 /*
   1478  * Look up audio device and acquire locks for device access.
   1479  */
   1480 static int
   1481 audio_enter(dev_t dev, krw_t rw, struct audio_softc **scp)
   1482 {
   1483 
   1484 	struct audio_softc *sc;
   1485 
   1486 	/* First, find the device and take sc_lock. */
   1487 	sc = device_lookup_private(&audio_cd, AUDIOUNIT(dev));
   1488 	if (sc == NULL || sc->hw_if == NULL)
   1489 		return ENXIO;
   1490 	mutex_enter(sc->sc_lock);
   1491 	if (sc->sc_dying) {
   1492 		mutex_exit(sc->sc_lock);
   1493 		return EIO;
   1494 	}
   1495 
   1496 	*scp = sc;
   1497 	return 0;
   1498 }
   1499 
   1500 /*
   1501  * Release reference to device acquired with audio_enter().
   1502  */
   1503 static void
   1504 audio_exit(struct audio_softc *sc)
   1505 {
   1506 	cv_broadcast(&sc->sc_lchan);
   1507 	mutex_exit(sc->sc_lock);
   1508 }
   1509 
   1510 /*
   1511  * Wait for I/O to complete, releasing device lock.
   1512  */
   1513 static int
   1514 audio_waitio(struct audio_softc *sc, kcondvar_t *chan, struct virtual_channel *vc)
   1515 {
   1516 	struct audio_chan *vchan;
   1517 	bool found = false;
   1518 	int error;
   1519 
   1520 	KASSERT(mutex_owned(sc->sc_lock));
   1521 	cv_broadcast(&sc->sc_lchan);
   1522 
   1523 	/* Wait for pending I/O to complete. */
   1524 	error = cv_wait_sig(chan, sc->sc_lock);
   1525 
   1526 	found = false;
   1527 	SIMPLEQ_FOREACH(vchan, &sc->sc_audiochan, entries) {
   1528 		if (vchan == SIMPLEQ_FIRST(&sc->sc_audiochan))
   1529 			continue;
   1530 		if (vchan->vc == vc) {
   1531 			found = true;
   1532 			break;
   1533 		}
   1534 	}
   1535 	if (found == false)
   1536 		error = EIO;
   1537 
   1538 	return error;
   1539 }
   1540 
   1541 /* Exported interfaces for audiobell. */
   1542 int
   1543 audiobellopen(dev_t dev, int flags, int ifmt, struct lwp *l,
   1544 	      struct file **fp)
   1545 {
   1546 	struct audio_softc *sc;
   1547 	int error;
   1548 
   1549 	if ((error = audio_enter(dev, RW_WRITER, &sc)) != 0)
   1550 		return error;
   1551 	device_active(sc->dev, DVA_SYSTEM);
   1552 	switch (AUDIODEV(dev)) {
   1553 	case AUDIO_DEVICE:
   1554 		error = audio_open(dev, sc, flags, ifmt, l, fp);
   1555 		break;
   1556 	default:
   1557 		error = EINVAL;
   1558 		break;
   1559 	}
   1560 	audio_exit(sc);
   1561 
   1562 	return error;
   1563 }
   1564 
   1565 int
   1566 audiobellclose(struct file *fp)
   1567 {
   1568 
   1569 	return audioclose(fp);
   1570 }
   1571 
   1572 int
   1573 audiobellwrite(struct file *fp, off_t *offp, struct uio *uio, kauth_cred_t cred,
   1574 	   int ioflag)
   1575 {
   1576 
   1577 	return audiowrite(fp, offp, uio, cred, ioflag);
   1578 }
   1579 
   1580 int
   1581 audiobellioctl(struct file *fp, u_long cmd, void *addr)
   1582 {
   1583 
   1584 	return audioioctl(fp, cmd, addr);
   1585 }
   1586 
   1587 static int
   1588 audioopen(dev_t dev, int flags, int ifmt, struct lwp *l)
   1589 {
   1590 	struct audio_softc *sc;
   1591 	struct file *fp;
   1592 	int error;
   1593 
   1594 	if ((error = audio_enter(dev, RW_WRITER, &sc)) != 0)
   1595 		return error;
   1596 	device_active(sc->dev, DVA_SYSTEM);
   1597 	switch (AUDIODEV(dev)) {
   1598 	case SOUND_DEVICE:
   1599 	case AUDIO_DEVICE:
   1600 	case AUDIOCTL_DEVICE:
   1601 		error = audio_open(dev, sc, flags, ifmt, l, &fp);
   1602 		break;
   1603 	case MIXER_DEVICE:
   1604 		error = mixer_open(dev, sc, flags, ifmt, l, &fp);
   1605 		break;
   1606 	default:
   1607 		error = ENXIO;
   1608 		break;
   1609 	}
   1610 	audio_exit(sc);
   1611 
   1612 	return error;
   1613 }
   1614 
   1615 static int
   1616 audioclose(struct file *fp)
   1617 {
   1618 	struct audio_softc *sc;
   1619 	struct audio_chan *chan;
   1620 	int error;
   1621 	dev_t dev;
   1622 
   1623 	chan = fp->f_audioctx;
   1624 	if (chan == NULL)	/* XXX:NS Why is this needed. */
   1625 		return EIO;
   1626 
   1627 	dev = chan->dev;
   1628 
   1629 	if ((error = audio_enter(dev, RW_WRITER, &sc)) != 0)
   1630 		return error;
   1631 
   1632 	device_active(sc->dev, DVA_SYSTEM);
   1633 	switch (AUDIODEV(dev)) {
   1634 	case SOUND_DEVICE:
   1635 	case AUDIO_DEVICE:
   1636 	case AUDIOCTL_DEVICE:
   1637 		error = audio_close(sc, fp->f_flag, chan);
   1638 		break;
   1639 	case MIXER_DEVICE:
   1640 		error = mixer_close(sc, fp->f_flag, chan);
   1641 		break;
   1642 	default:
   1643 		error = ENXIO;
   1644 		break;
   1645 	}
   1646 	if (error == 0) {
   1647 		kmem_free(fp->f_audioctx, sizeof(struct audio_chan));
   1648 		fp->f_audioctx = NULL;
   1649 	}
   1650 
   1651 	audio_exit(sc);
   1652 
   1653 	return error;
   1654 }
   1655 
   1656 static int
   1657 audioread(struct file *fp, off_t *offp, struct uio *uio, kauth_cred_t cred,
   1658 	  int ioflag)
   1659 {
   1660 	struct audio_softc *sc;
   1661 	struct virtual_channel *vc;
   1662 	int error;
   1663 	dev_t dev;
   1664 
   1665 	if (fp->f_audioctx == NULL)
   1666 		return EIO;
   1667 
   1668 	dev = fp->f_audioctx->dev;
   1669 
   1670 	if ((error = audio_enter(dev, RW_READER, &sc)) != 0)
   1671 		return error;
   1672 
   1673 	switch (AUDIODEV(dev)) {
   1674 	case SOUND_DEVICE:
   1675 	case AUDIO_DEVICE:
   1676 		vc = fp->f_audioctx->vc;
   1677 		error = audio_read(sc, uio, ioflag, vc);
   1678 		break;
   1679 	case AUDIOCTL_DEVICE:
   1680 	case MIXER_DEVICE:
   1681 		error = ENODEV;
   1682 		break;
   1683 	default:
   1684 		error = ENXIO;
   1685 		break;
   1686 	}
   1687 	audio_exit(sc);
   1688 
   1689 	return error;
   1690 }
   1691 
   1692 static int
   1693 audiowrite(struct file *fp, off_t *offp, struct uio *uio, kauth_cred_t cred,
   1694 	   int ioflag)
   1695 {
   1696 	struct audio_softc *sc;
   1697 	struct virtual_channel *vc;
   1698 	int error;
   1699 	dev_t dev;
   1700 
   1701 	if (fp->f_audioctx == NULL)
   1702 		return EIO;
   1703 
   1704 	dev = fp->f_audioctx->dev;
   1705 
   1706 	if ((error = audio_enter(dev, RW_READER, &sc)) != 0)
   1707 		return error;
   1708 
   1709 	switch (AUDIODEV(dev)) {
   1710 	case SOUND_DEVICE:
   1711 	case AUDIO_DEVICE:
   1712 		vc = fp->f_audioctx->vc;
   1713 		error = audio_write(sc, uio, ioflag, vc);
   1714 		break;
   1715 	case AUDIOCTL_DEVICE:
   1716 	case MIXER_DEVICE:
   1717 		error = ENODEV;
   1718 		break;
   1719 	default:
   1720 		error = ENXIO;
   1721 		break;
   1722 	}
   1723 	audio_exit(sc);
   1724 
   1725 	return error;
   1726 }
   1727 
   1728 static int
   1729 audioioctl(struct file *fp, u_long cmd, void *addr)
   1730 {
   1731 	struct audio_softc *sc;
   1732 	struct audio_chan *chan;
   1733 	struct lwp *l = curlwp;
   1734 	int error;
   1735 	krw_t rw;
   1736 	dev_t dev;
   1737 
   1738 	if (fp->f_audioctx == NULL)
   1739 		return EIO;
   1740 
   1741 	chan = fp->f_audioctx;
   1742 	dev = chan->dev;
   1743 
   1744 	/* Figure out which lock type we need. */
   1745 	switch (cmd) {
   1746 	case AUDIO_FLUSH:
   1747 	case AUDIO_SETINFO:
   1748 	case AUDIO_DRAIN:
   1749 	case AUDIO_SETFD:
   1750 		rw = RW_WRITER;
   1751 		break;
   1752 	default:
   1753 		rw = RW_READER;
   1754 		break;
   1755 	}
   1756 
   1757 	if ((error = audio_enter(dev, rw, &sc)) != 0)
   1758 		return error;
   1759 	chan = fp->f_audioctx;
   1760 
   1761 	switch (AUDIODEV(dev)) {
   1762 	case SOUND_DEVICE:
   1763 	case AUDIO_DEVICE:
   1764 	case AUDIOCTL_DEVICE:
   1765 		device_active(sc->dev, DVA_SYSTEM);
   1766 		if (IOCGROUP(cmd) == IOCGROUP(AUDIO_MIXER_READ))
   1767 			error = mixer_ioctl(sc, cmd, addr, fp->f_flag, l);
   1768 		else
   1769 			error = audio_ioctl(dev, sc, cmd, addr, fp->f_flag, l,
   1770 			    chan);
   1771 		break;
   1772 	case MIXER_DEVICE:
   1773 		error = mixer_ioctl(sc, cmd, addr, fp->f_flag, l);
   1774 		break;
   1775 	default:
   1776 		error = ENXIO;
   1777 		break;
   1778 	}
   1779 	audio_exit(sc);
   1780 
   1781 	return error;
   1782 }
   1783 
   1784 static int
   1785 audiostat(struct file *fp, struct stat *st)
   1786 {
   1787 	if (fp->f_audioctx == NULL)
   1788 		return EIO;
   1789 
   1790 	memset(st, 0, sizeof(*st));
   1791 
   1792 	st->st_dev = fp->f_audioctx->dev;
   1793 
   1794 	st->st_uid = kauth_cred_geteuid(fp->f_cred);
   1795 	st->st_gid = kauth_cred_getegid(fp->f_cred);
   1796 	st->st_mode = S_IFCHR;
   1797 	return 0;
   1798 }
   1799 
   1800 static int
   1801 audiopoll(struct file *fp, int events)
   1802 {
   1803 	struct audio_softc *sc;
   1804 	struct virtual_channel *vc;
   1805 	struct lwp *l = curlwp;
   1806 	int revents;
   1807 	dev_t dev;
   1808 
   1809 	if (fp->f_audioctx == NULL)
   1810 		return EIO;
   1811 
   1812 	dev = fp->f_audioctx->dev;
   1813 
   1814 	/* Don't bother with device level lock here. */
   1815 	sc = device_lookup_private(&audio_cd, AUDIOUNIT(dev));
   1816 	if (sc == NULL)
   1817 		return ENXIO;
   1818 	mutex_enter(sc->sc_lock);
   1819 	if (sc->sc_dying) {
   1820 		mutex_exit(sc->sc_lock);
   1821 		return EIO;
   1822 	}
   1823 
   1824 	switch (AUDIODEV(dev)) {
   1825 	case SOUND_DEVICE:
   1826 	case AUDIO_DEVICE:
   1827 		vc = fp->f_audioctx->vc;
   1828 		revents = audio_poll(sc, events, l, vc);
   1829 		break;
   1830 	case AUDIOCTL_DEVICE:
   1831 	case MIXER_DEVICE:
   1832 		revents = 0;
   1833 		break;
   1834 	default:
   1835 		revents = POLLERR;
   1836 		break;
   1837 	}
   1838 	mutex_exit(sc->sc_lock);
   1839 
   1840 	return revents;
   1841 }
   1842 
   1843 static int
   1844 audiokqfilter(struct file *fp, struct knote *kn)
   1845 {
   1846 	struct audio_softc *sc;
   1847 	int rv;
   1848 	struct audio_chan *chan;
   1849 	dev_t dev;
   1850 
   1851 	chan = fp->f_audioctx;
   1852 	dev = chan->dev;
   1853 
   1854 	/* Don't bother with device level lock here. */
   1855 	sc = device_lookup_private(&audio_cd, AUDIOUNIT(dev));
   1856 	if (sc == NULL)
   1857 		return ENXIO;
   1858 	mutex_enter(sc->sc_lock);
   1859 	if (sc->sc_dying) {
   1860 		mutex_exit(sc->sc_lock);
   1861 		return EIO;
   1862 	}
   1863 	switch (AUDIODEV(dev)) {
   1864 	case SOUND_DEVICE:
   1865 	case AUDIO_DEVICE:
   1866 		rv = audio_kqfilter(chan, kn);
   1867 		break;
   1868 	case AUDIOCTL_DEVICE:
   1869 	case MIXER_DEVICE:
   1870 		rv = 1;
   1871 		break;
   1872 	default:
   1873 		rv = 1;
   1874 	}
   1875 	mutex_exit(sc->sc_lock);
   1876 
   1877 	return rv;
   1878 }
   1879 
   1880 /* XXX:NS mmap is disabled. */
   1881 static int
   1882 audio_fop_mmap(struct file *fp, off_t *offp, size_t len, int prot, int *flagsp,
   1883 	     int *advicep, struct uvm_object **uobjp, int *maxprotp)
   1884 {
   1885 	struct audio_chan *chan;
   1886 	struct virtual_channel *vc;
   1887 	dev_t dev;
   1888 
   1889 	return -1;
   1890 
   1891 	chan = fp->f_audioctx;
   1892 	dev = chan->dev;
   1893 	vc = chan->vc;
   1894 
   1895 	*offp = audiommap(dev, *offp, prot, vc);
   1896 	*maxprotp = prot;
   1897 	*advicep = UVM_ADV_RANDOM;
   1898 	return -1;
   1899 }
   1900 
   1901 paddr_t
   1902 audiommap(dev_t dev, off_t off, int prot, struct virtual_channel *vc)
   1903 {
   1904 	struct audio_softc *sc;
   1905 	paddr_t error;
   1906 
   1907 	return -1;
   1908 
   1909 	/*
   1910 	 * Acquire a reader lock.  audio_mmap() will drop sc_lock
   1911 	 * in order to allow the device's mmap routine to sleep.
   1912 	 * Although not yet possible, we want to prevent memory
   1913 	 * from being allocated or freed out from under us.
   1914 	 */
   1915 	if ((error = audio_enter(dev, RW_READER, &sc)) != 0)
   1916 		return 1;
   1917 	device_active(sc->dev, DVA_SYSTEM); /* XXXJDM */
   1918 
   1919 	switch (AUDIODEV(dev)) {
   1920 	case SOUND_DEVICE:
   1921 	case AUDIO_DEVICE:
   1922 		error = audio_mmap(sc, off, prot, vc);
   1923 		break;
   1924 	case AUDIOCTL_DEVICE:
   1925 	case MIXER_DEVICE:
   1926 		error = -1;
   1927 		break;
   1928 	default:
   1929 		error = -1;
   1930 		break;
   1931 	}
   1932 	audio_exit(sc);
   1933 	return error;
   1934 }
   1935 
   1936 /*
   1937  * Audio driver
   1938  */
   1939 void
   1940 audio_init_ringbuffer(struct audio_softc *sc, struct audio_ringbuffer *rp,
   1941 		      int mode)
   1942 {
   1943 	int nblks;
   1944 	int blksize;
   1945 
   1946 	blksize = rp->blksize;
   1947 	if (blksize < AUMINBLK)
   1948 		blksize = AUMINBLK;
   1949 	if (blksize > rp->s.bufsize / AUMINNOBLK)
   1950 		blksize = rp->s.bufsize / AUMINNOBLK;
   1951 	ROUNDSIZE(blksize);
   1952 	DPRINTF(("audio_init_ringbuffer: MI blksize=%d\n", blksize));
   1953 	if (sc->hw_if->round_blocksize)
   1954 		blksize = sc->hw_if->round_blocksize(sc->hw_hdl, blksize,
   1955 						     mode, &rp->s.param);
   1956 	if (blksize <= 0)
   1957 		panic("audio_init_ringbuffer: blksize=%d", blksize);
   1958 	nblks = rp->s.bufsize / blksize;
   1959 
   1960 	DPRINTF(("audio_init_ringbuffer: final blksize=%d\n", blksize));
   1961 	rp->blksize = blksize;
   1962 	rp->maxblks = nblks;
   1963 	rp->s.end = rp->s.start + nblks * blksize;
   1964 	rp->s.outp = rp->s.inp = rp->s.start;
   1965 	rp->s.used = 0;
   1966 	rp->stamp = 0;
   1967 	rp->stamp_last = 0;
   1968 	rp->fstamp = 0;
   1969 	rp->drops = 0;
   1970 	rp->copying = false;
   1971 	rp->needfill = false;
   1972 	rp->mmapped = false;
   1973 	memset(rp->s.start, 0, blksize * 2);
   1974 }
   1975 
   1976 int
   1977 audio_initbufs(struct audio_softc *sc, struct virtual_channel *vc)
   1978 {
   1979 	const struct audio_hw_if *hw;
   1980 	struct audio_chan *chan;
   1981 	int error;
   1982 
   1983 	if (vc == NULL) {
   1984 		chan = SIMPLEQ_FIRST(&sc->sc_audiochan);
   1985 		vc = chan->vc;
   1986 	}
   1987 
   1988 	DPRINTF(("audio_initbufs: mode=0x%x\n", vc->sc_mode));
   1989 	hw = sc->hw_if;
   1990 	if (audio_can_capture(sc) || (vc->sc_open & AUOPEN_READ)) {
   1991 		audio_init_ringbuffer(sc, &vc->sc_mrr,
   1992 		    AUMODE_RECORD);
   1993 		if (sc->sc_opens == 0 && hw->init_input &&
   1994 		    (vc->sc_mode & AUMODE_RECORD)) {
   1995 			error = hw->init_input(sc->hw_hdl, vc->sc_mrr.s.start,
   1996 				       vc->sc_mrr.s.end - vc->sc_mrr.s.start);
   1997 			if (error)
   1998 				return error;
   1999 		}
   2000 	}
   2001 
   2002 	if (audio_can_playback(sc) || (vc->sc_open & AUOPEN_WRITE)) {
   2003 		audio_init_ringbuffer(sc, &vc->sc_mpr,
   2004 		    AUMODE_PLAY);
   2005 		vc->sc_sil_count = 0;
   2006 		if (sc->sc_opens == 0 && hw->init_output &&
   2007 		    (vc->sc_mode & AUMODE_PLAY)) {
   2008 			error = hw->init_output(sc->hw_hdl, vc->sc_mpr.s.start,
   2009 					vc->sc_mpr.s.end - vc->sc_mpr.s.start);
   2010 			if (error)
   2011 				return error;
   2012 		}
   2013 	}
   2014 
   2015 #ifdef AUDIO_INTR_TIME
   2016 #define double u_long
   2017 	if (audio_can_playback(sc)) {
   2018 		sc->sc_pnintr = 0;
   2019 		sc->sc_pblktime = (u_long)(
   2020 		    (double)vc->sc_mpr.blksize * 100000 /
   2021 		    (double)(vc->sc_pparams.precision / NBBY *
   2022 			     vc->sc_pparams.channels *
   2023 			     vc->sc_pparams.sample_rate)) * 10;
   2024 		DPRINTF(("audio: play blktime = %lu for %d\n",
   2025 			 sc->sc_pblktime, vc->sc_mpr.blksize));
   2026 	}
   2027 	if (audio_can_capture(sc)) {
   2028 		sc->sc_rnintr = 0;
   2029 		sc->sc_rblktime = (u_long)(
   2030 		    (double)vc->sc_mrr.blksize * 100000 /
   2031 		    (double)(vc->sc_rparams.precision / NBBY *
   2032 			     vc->sc_rparams.channels *
   2033 			     vc->sc_rparams.sample_rate)) * 10;
   2034 		DPRINTF(("audio: record blktime = %lu for %d\n",
   2035 			 sc->sc_rblktime, vc->sc_mrr.blksize));
   2036 	}
   2037 #undef double
   2038 #endif
   2039 
   2040 	return 0;
   2041 }
   2042 
   2043 void
   2044 audio_calcwater(struct audio_softc *sc, struct virtual_channel *vc)
   2045 {
   2046 	/* set high at 100% */
   2047 	if (audio_can_playback(sc) && vc && vc->sc_pustream) {
   2048 		vc->sc_mpr.usedhigh =
   2049 		    vc->sc_pustream->end - vc->sc_pustream->start;
   2050 		/* set low at 75% of usedhigh */
   2051 		vc->sc_mpr.usedlow = vc->sc_mpr.usedhigh * 3 / 4;
   2052 		if (vc->sc_mpr.usedlow == vc->sc_mpr.usedhigh)
   2053 			vc->sc_mpr.usedlow -= vc->sc_mpr.blksize;
   2054 	}
   2055 
   2056 	if (audio_can_capture(sc) && vc && vc->sc_rustream) {
   2057 		vc->sc_mrr.usedhigh =
   2058 		    vc->sc_rustream->end - vc->sc_rustream->start -
   2059 		    vc->sc_mrr.blksize;
   2060 		vc->sc_mrr.usedlow = 0;
   2061 		DPRINTF(("%s: plow=%d phigh=%d rlow=%d rhigh=%d\n", __func__,
   2062 			 vc->sc_mpr.usedlow, vc->sc_mpr.usedhigh,
   2063 			 vc->sc_mrr.usedlow, vc->sc_mrr.usedhigh));
   2064 	}
   2065 }
   2066 
   2067 int
   2068 audio_open(dev_t dev, struct audio_softc *sc, int flags, int ifmt,
   2069     struct lwp *l, struct file **nfp)
   2070 {
   2071 	struct file *fp;
   2072 	int error, fd, i, n;
   2073 	u_int mode;
   2074 	const struct audio_hw_if *hw;
   2075 	struct virtual_channel *vc;
   2076 	struct audio_chan *chan;
   2077 
   2078 	KASSERT(mutex_owned(sc->sc_lock));
   2079 
   2080 	if (sc->sc_ready == false)
   2081 		return ENXIO;
   2082 
   2083 	hw = sc->hw_if;
   2084 	if (hw == NULL)
   2085 		return ENXIO;
   2086 	n = 0;
   2087 	SIMPLEQ_FOREACH(chan, &sc->sc_audiochan, entries)
   2088 		n++;
   2089 
   2090 	chan = kmem_zalloc(sizeof(struct audio_chan), KM_SLEEP);
   2091 	vc = kmem_zalloc(sizeof(struct virtual_channel), KM_SLEEP);
   2092 	chan->vc = vc;
   2093 
   2094 	vc->sc_open = 0;
   2095 	vc->sc_mode = 0;
   2096 	vc->sc_sil_count = 0;
   2097 	vc->sc_nrfilters = 0;
   2098 	memset(vc->sc_rfilters, 0,
   2099 	    sizeof(vc->sc_rfilters));
   2100 	vc->sc_rbus = false;
   2101 	vc->sc_npfilters = 0;
   2102 	memset(vc->sc_pfilters, 0,
   2103 	    sizeof(vc->sc_pfilters));
   2104 	vc->sc_draining = false;
   2105 	vc->sc_pbus = false;
   2106 	vc->sc_blkset = false;
   2107 	vc->sc_lastinfovalid = false;
   2108 	vc->sc_swvol = 255;
   2109 	vc->sc_recswvol = 255;
   2110 
   2111 	DPRINTF(("audio_open: flags=0x%x sc=%p hdl=%p\n",
   2112 		 flags, sc, sc->hw_hdl));
   2113 
   2114 	if (((flags & FREAD) && (vc->sc_open & AUOPEN_READ)) ||
   2115 	    ((flags & FWRITE) && (vc->sc_open & AUOPEN_WRITE))) {
   2116 		kmem_free(vc, sizeof(struct virtual_channel));
   2117 		kmem_free(chan, sizeof(struct audio_chan));
   2118 		return EBUSY;
   2119 	}
   2120 
   2121 	error = audio_alloc_ring(sc, &vc->sc_mpr,
   2122 	    	    AUMODE_PLAY, AU_RING_SIZE);
   2123 	if (!error) {
   2124 		error = audio_alloc_ring(sc, &vc->sc_mrr,
   2125 	    	    AUMODE_RECORD, AU_RING_SIZE);
   2126 	}
   2127 	if (error) {
   2128 		kmem_free(vc, sizeof(struct virtual_channel));
   2129 		kmem_free(chan, sizeof(struct audio_chan));
   2130 		return error;
   2131 	}
   2132 
   2133 	if (sc->sc_opens == 0) {
   2134 		sc->sc_credentials = kauth_cred_get();
   2135 		kauth_cred_hold(sc->sc_credentials);
   2136 		if (hw->open != NULL) {
   2137 			mutex_enter(sc->sc_intr_lock);
   2138 			error = hw->open(sc->hw_hdl, flags);
   2139 			mutex_exit(sc->sc_intr_lock);
   2140 			if (error) {
   2141 				kmem_free(vc,
   2142 				    sizeof(struct virtual_channel));
   2143 				kmem_free(chan,
   2144 				    sizeof(struct audio_chan));
   2145 				return error;
   2146 			}
   2147 		}
   2148 		audio_init_ringbuffer(sc, &sc->sc_pr, AUMODE_PLAY);
   2149 		audio_init_ringbuffer(sc, &sc->sc_rr, AUMODE_RECORD);
   2150 		audio_initbufs(sc, NULL);
   2151 		sc->schedule_wih = false;
   2152 		sc->schedule_rih = false;
   2153 		sc->sc_eof = 0;
   2154 		vc->sc_rbus = false;
   2155 		sc->sc_async_audio = 0;
   2156 	} else if (sc->sc_multiuser == false) {
   2157 		/* XXX:NS Should be handled correctly. */
   2158 		/* Do we allow multi user access */
   2159 		if (kauth_cred_geteuid(sc->sc_credentials) !=
   2160 		    kauth_cred_geteuid(kauth_cred_get()) &&
   2161 		    kauth_cred_geteuid(kauth_cred_get()) != 0) {
   2162 			error = EPERM;
   2163 			goto bad;
   2164 		}
   2165 	}
   2166 
   2167 	mutex_enter(sc->sc_intr_lock);
   2168 	vc->sc_full_duplex =
   2169 		(flags & (FWRITE|FREAD)) == (FWRITE|FREAD) &&
   2170 		(audio_get_props(sc) & AUDIO_PROP_FULLDUPLEX);
   2171 	mutex_exit(sc->sc_intr_lock);
   2172 
   2173 	mode = 0;
   2174 	if (flags & FREAD) {
   2175 		vc->sc_open |= AUOPEN_READ;
   2176 		mode |= AUMODE_RECORD;
   2177 	}
   2178 	if (flags & FWRITE) {
   2179 		vc->sc_open |= AUOPEN_WRITE;
   2180 		mode |= AUMODE_PLAY | AUMODE_PLAY_ALL;
   2181 	}
   2182 
   2183 	vc->sc_mrr.blksize = sc->sc_rr.blksize;
   2184 	vc->sc_mpr.blksize = sc->sc_pr.blksize;
   2185 
   2186 	/*
   2187 	 * Multiplex device: /dev/audio (MU-Law) and /dev/sound (linear)
   2188 	 * The /dev/audio is always (re)set to 8-bit MU-Law mono
   2189 	 * For the other devices, you get what they were last set to.
   2190 	 */
   2191 	error = audio_set_defaults(sc, mode, vc);
   2192 	if (!error && ISDEVSOUND(dev) && sc->sc_aivalid == true) {
   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)
   3594 		return;
   3595 
   3596 	if (vc->sc_draining == true) {
   3597 		vc->sc_mpr.drops += blksize;
   3598 		cv_broadcast(&sc->sc_wchan);
   3599 	}
   3600 
   3601 	if (audio_stream_get_used(&sc->sc_pr.s) < blksize)
   3602 		goto wake_mix;
   3603 
   3604 	vc->sc_mpr.s.outp = audio_stream_add_outp(&vc->sc_mpr.s,
   3605 	    vc->sc_mpr.s.outp, blksize);
   3606 
   3607 	mix_write(sc);
   3608 
   3609 wake_mix:
   3610 	cv_broadcast(&sc->sc_condvar);
   3611 }
   3612 
   3613 void
   3614 audio_mix(void *v)
   3615 {
   3616 	stream_fetcher_t null_fetcher;
   3617 	struct audio_softc *sc;
   3618 	struct audio_chan *chan;
   3619 	struct virtual_channel *vc;
   3620 	struct audio_ringbuffer *cb;
   3621 	stream_fetcher_t *fetcher;
   3622 	uint8_t *inp;
   3623 	int cc, used, blksize;
   3624 
   3625 	sc = v;
   3626 
   3627 	DPRINTF(("PINT MIX\n"));
   3628 	sc->schedule_rih = false;
   3629 	sc->schedule_wih = false;
   3630 	sc->sc_writeme = false;
   3631 
   3632 	if (sc->sc_dying == true)
   3633 		return;
   3634 
   3635 	blksize = sc->sc_pr.blksize;
   3636 	SIMPLEQ_FOREACH(chan, &sc->sc_audiochan, entries) {
   3637 		if (!sc->sc_opens)
   3638 			break;		/* ignore interrupt if not open */
   3639 
   3640 		if (chan == NULL)
   3641 			break;
   3642 
   3643 		if (chan == SIMPLEQ_FIRST(&sc->sc_audiochan))
   3644 			continue;
   3645 
   3646 		if (chan->chan == MIXER_INUSE)
   3647 			continue;
   3648 
   3649 		vc = chan->vc;
   3650 
   3651 		if (!vc->sc_open)
   3652 			continue;
   3653 		if (!vc->sc_pbus)
   3654 			continue;
   3655 
   3656 		cb = &vc->sc_mpr;
   3657 
   3658 		sc->sc_writeme = true;
   3659 
   3660 		inp = cb->s.inp;
   3661 		cb->stamp += blksize;
   3662 		if (cb->mmapped) {
   3663 			DPRINTF(("audio_pint: mmapped outp=%p cc=%d inp=%p\n",
   3664 				     cb->s.outp, blksize, cb->s.inp));
   3665 			mutex_enter(sc->sc_intr_lock);
   3666 			mix_func(sc, cb, vc);
   3667 			mutex_exit(sc->sc_intr_lock);
   3668 			continue;
   3669 		}
   3670 
   3671 #ifdef AUDIO_INTR_TIME
   3672 		{
   3673 			struct timeval tv;
   3674 			u_long t;
   3675 			microtime(&tv);
   3676 			t = tv.tv_usec + 1000000 * tv.tv_sec;
   3677 			if (sc->sc_pnintr) {
   3678 				long lastdelta, totdelta;
   3679 				lastdelta = t - sc->sc_plastintr -
   3680 				    sc->sc_pblktime;
   3681 				if (lastdelta > sc->sc_pblktime / 3) {
   3682 					printf("audio: play interrupt(%d) off "
   3683 				       "relative by %ld us (%lu)\n",
   3684 					       sc->sc_pnintr, lastdelta,
   3685 					       sc->sc_pblktime);
   3686 				}
   3687 				totdelta = t - sc->sc_pfirstintr -
   3688 					sc->sc_pblktime * sc->sc_pnintr;
   3689 				if (totdelta > sc->sc_pblktime) {
   3690 					printf("audio: play interrupt(%d) "
   3691 					       "off absolute by %ld us (%lu) "
   3692 					       "(LOST)\n", sc->sc_pnintr,
   3693 					       totdelta, sc->sc_pblktime);
   3694 					sc->sc_pnintr++;
   3695 					/* avoid repeated messages */
   3696 				}
   3697 			} else
   3698 				sc->sc_pfirstintr = t;
   3699 			sc->sc_plastintr = t;
   3700 			sc->sc_pnintr++;
   3701 		}
   3702 #endif
   3703 
   3704 		used = audio_stream_get_used(&cb->s);
   3705 		/*
   3706 		 * "used <= cb->usedlow" should be "used < blksize" ideally.
   3707 		 * Some HW drivers such as uaudio(4) does not call audio_pint()
   3708 		 * at accurate timing.  If used < blksize, uaudio(4) already
   3709 		 * request transfer of garbage data.
   3710 		 */
   3711 		if (used <= cb->usedlow && !cb->copying &&
   3712 		    vc->sc_npfilters > 0) {
   3713 			/* we might have data in filter pipeline */
   3714 			null_fetcher.fetch_to = null_fetcher_fetch_to;
   3715 			fetcher = &vc->sc_pfilters[vc->sc_npfilters - 1]->base;
   3716 			vc->sc_pfilters[0]->set_fetcher(vc->sc_pfilters[0],
   3717 							&null_fetcher);
   3718 			used = audio_stream_get_used(vc->sc_pustream);
   3719 			cc = cb->s.end - cb->s.start;
   3720 			if (blksize * 2 < cc)
   3721 				cc = blksize * 2;
   3722 			fetcher->fetch_to(sc, fetcher, &cb->s, cc);
   3723 			cb->fstamp += used -
   3724 			    audio_stream_get_used(vc->sc_pustream);
   3725 			used = audio_stream_get_used(&cb->s);
   3726 		}
   3727 		if (used < blksize) {
   3728 			/* we don't have a full block to use */
   3729 			if (cb->copying) {
   3730 				/* writer is in progress, don't disturb */
   3731 				cb->needfill = true;
   3732 				DPRINTFN(1, ("audio_pint: copying in "
   3733 					 "progress\n"));
   3734 			} else {
   3735 				inp = cb->s.inp;
   3736 				cc = blksize - (inp - cb->s.start) % blksize;
   3737 				if (cb->pause)
   3738 					cb->pdrops += cc;
   3739 				else {
   3740 					cb->drops += cc;
   3741 					vc->sc_playdrop += cc;
   3742 				}
   3743 
   3744 				audio_pint_silence(sc, cb, inp, cc, vc);
   3745 				cb->s.inp = audio_stream_add_inp(&cb->s, inp,
   3746 				    cc);
   3747 
   3748 				/* Clear next block to keep ahead of the DMA. */
   3749 				used = audio_stream_get_used(&cb->s);
   3750 				if (used + blksize < cb->s.end - cb->s.start) {
   3751 					audio_pint_silence(sc, cb, cb->s.inp,
   3752 					    blksize, vc);
   3753 				}
   3754 			}
   3755 		}
   3756 
   3757 		DPRINTFN(5, ("audio_pint: outp=%p cc=%d\n", cb->s.outp,
   3758 			 blksize));
   3759 		mutex_enter(sc->sc_intr_lock);
   3760 		mix_func(sc, cb, vc);
   3761 		mutex_exit(sc->sc_intr_lock);
   3762 		cb->s.outp = audio_stream_add_outp(&cb->s, cb->s.outp, blksize);
   3763 
   3764 		DPRINTFN(2, ("audio_pint: mode=%d pause=%d used=%d lowat=%d\n",
   3765 			     vc->sc_mode, cb->pause,
   3766 			     audio_stream_get_used(vc->sc_pustream),
   3767 			     cb->usedlow));
   3768 
   3769 		if ((vc->sc_mode & AUMODE_PLAY) && !cb->pause) {
   3770 			if (audio_stream_get_used(&cb->s) <= cb->usedlow)
   3771 				sc->schedule_wih = true;
   3772 		}
   3773 		/* Possible to return one or more "phantom blocks" now. */
   3774 		if (!vc->sc_full_duplex && vc->sc_mode & AUMODE_RECORD)
   3775 				sc->schedule_rih = true;
   3776 	}
   3777 	mutex_enter(sc->sc_intr_lock);
   3778 	if (sc->sc_saturate == true && sc->sc_opens > 1)
   3779 		saturate_func(sc);
   3780 
   3781 	cb = &sc->sc_pr;
   3782 	if (sc->sc_writeme == true)
   3783 		cb->s.inp = audio_stream_add_inp(&cb->s, cb->s.inp, blksize);
   3784 	mutex_exit(sc->sc_intr_lock);
   3785 
   3786 	kpreempt_disable();
   3787 	if (sc->schedule_wih == true)
   3788 		softint_schedule(sc->sc_sih_wr);
   3789 
   3790 	if (sc->schedule_rih == true)
   3791 		softint_schedule(sc->sc_sih_rd);
   3792 	kpreempt_enable();
   3793 }
   3794 
   3795 /*
   3796  * Called from HW driver module on completion of DMA input.
   3797  * Mark it as input in the ring buffer (fiddle pointers).
   3798  * Do a wakeup if necessary.
   3799  */
   3800 void
   3801 audio_rint(void *v)
   3802 {
   3803 	struct audio_softc *sc;
   3804 	int blksize;
   3805 
   3806 	sc = v;
   3807 
   3808 	KASSERT(mutex_owned(sc->sc_intr_lock));
   3809 
   3810 	if (sc->sc_dying == true)
   3811 		return;
   3812 
   3813 	blksize = audio_stream_get_used(&sc->sc_rr.s);
   3814 	sc->sc_rr.s.outp = audio_stream_add_outp(&sc->sc_rr.s,
   3815 	    sc->sc_rr.s.outp, blksize);
   3816 	mix_read(sc);
   3817 
   3818 	cv_broadcast(&sc->sc_rcondvar);
   3819 }
   3820 
   3821 void
   3822 audio_upmix(void *v)
   3823 {
   3824 	stream_fetcher_t null_fetcher;
   3825 	struct audio_softc *sc;
   3826 	struct audio_chan *chan;
   3827 	struct audio_ringbuffer *cb;
   3828 	stream_fetcher_t *last_fetcher;
   3829 	struct virtual_channel *vc;
   3830 	int cc, used, blksize, cc1;
   3831 
   3832 	sc = v;
   3833 	blksize = sc->sc_rr.blksize;
   3834 
   3835 	SIMPLEQ_FOREACH(chan, &sc->sc_audiochan, entries) {
   3836 		if (!sc->sc_opens)
   3837 			break;		/* ignore interrupt if not open */
   3838 
   3839 		if (chan == NULL)
   3840 			break;
   3841 
   3842 		if (chan == SIMPLEQ_FIRST(&sc->sc_audiochan))
   3843 			continue;
   3844 
   3845 		if (chan->chan == MIXER_INUSE)
   3846 			continue;
   3847 
   3848 		vc = chan->vc;
   3849 
   3850 		if (!(vc->sc_open & AUOPEN_READ))
   3851 			continue;
   3852 		if (!vc->sc_rbus)
   3853 			continue;
   3854 
   3855 		cb = &vc->sc_mrr;
   3856 
   3857 		blksize = audio_stream_get_used(&sc->sc_rr.s);
   3858 		if (audio_stream_get_space(&cb->s) < blksize) {
   3859 			cb->drops += blksize;
   3860 			cb->s.outp = audio_stream_add_outp(&cb->s, cb->s.outp,
   3861 			    sc->sc_rr.blksize);
   3862 			continue;
   3863 		}
   3864 
   3865 		cc = blksize;
   3866 		if (cb->s.inp + blksize > cb->s.end)
   3867 			cc = cb->s.end - cb->s.inp;
   3868 		mutex_enter(sc->sc_intr_lock);
   3869 		memcpy(cb->s.inp, sc->sc_rr.s.start, cc);
   3870 		if (cc < blksize && cc != 0) {
   3871 			cc1 = cc;
   3872 			cc = blksize - cc;
   3873 			memcpy(cb->s.start, sc->sc_rr.s.start + cc1, cc);
   3874 		}
   3875 		mutex_exit(sc->sc_intr_lock);
   3876 
   3877 		cc = blksize;
   3878 		recswvol_func(sc, cb, blksize, vc);
   3879 
   3880 		cb->s.inp = audio_stream_add_inp(&cb->s, cb->s.inp, blksize);
   3881 		cb->stamp += blksize;
   3882 		if (cb->mmapped) {
   3883 			DPRINTFN(2, ("audio_rint: mmapped inp=%p cc=%d\n",
   3884 			     	cb->s.inp, blksize));
   3885 			continue;
   3886 		}
   3887 
   3888 #ifdef AUDIO_INTR_TIME
   3889 		{
   3890 			struct timeval tv;
   3891 			u_long t;
   3892 			microtime(&tv);
   3893 			t = tv.tv_usec + 1000000 * tv.tv_sec;
   3894 			if (sc->sc_rnintr) {
   3895 				long lastdelta, totdelta;
   3896 				lastdelta = t - sc->sc_rlastintr -
   3897 				    sc->sc_rblktime;
   3898 				if (lastdelta > sc->sc_rblktime / 5) {
   3899 					printf("audio: record interrupt(%d) "
   3900 					       "off relative by %ld us (%lu)\n",
   3901 					       sc->sc_rnintr, lastdelta,
   3902 					       sc->sc_rblktime);
   3903 				}
   3904 				totdelta = t - sc->sc_rfirstintr -
   3905 					sc->sc_rblktime * sc->sc_rnintr;
   3906 				if (totdelta > sc->sc_rblktime / 2) {
   3907 					sc->sc_rnintr++;
   3908 					printf("audio: record interrupt(%d) "
   3909 					       "off absolute by %ld us (%lu)\n",
   3910 					       sc->sc_rnintr, totdelta,
   3911 					       sc->sc_rblktime);
   3912 					sc->sc_rnintr++;
   3913 					/* avoid repeated messages */
   3914 				}
   3915 			} else
   3916 				sc->sc_rfirstintr = t;
   3917 			sc->sc_rlastintr = t;
   3918 			sc->sc_rnintr++;
   3919 		}
   3920 #endif
   3921 
   3922 		if (!cb->pause && vc->sc_nrfilters > 0) {
   3923 			null_fetcher.fetch_to = null_fetcher_fetch_to;
   3924 			last_fetcher =
   3925 			    &vc->sc_rfilters[vc->sc_nrfilters - 1]->base;
   3926 			vc->sc_rfilters[0]->set_fetcher(vc->sc_rfilters[0],
   3927 							&null_fetcher);
   3928 			used = audio_stream_get_used(vc->sc_rustream);
   3929 			cc = vc->sc_rustream->end - vc->sc_rustream->start;
   3930 			last_fetcher->fetch_to
   3931 				(sc, last_fetcher, vc->sc_rustream, cc);
   3932 			cb->fstamp += audio_stream_get_used(vc->sc_rustream) -
   3933 			    used;
   3934 			/* XXX what should do for error? */
   3935 		}
   3936 		used = audio_stream_get_used(&vc->sc_mrr.s);
   3937 		if (cb->pause) {
   3938 			DPRINTFN(1, ("audio_rint: pdrops %lu\n", cb->pdrops));
   3939 			cb->pdrops += blksize;
   3940 			cb->s.outp = audio_stream_add_outp(&cb->s, cb->s.outp,
   3941 			    blksize);
   3942 		} else if (used + blksize > cb->s.end - cb->s.start &&
   3943 								!cb->copying) {
   3944 			DPRINTFN(1, ("audio_rint: drops %lu\n", cb->drops));
   3945 			cb->drops += blksize;
   3946 			cb->s.outp = audio_stream_add_outp(&cb->s, cb->s.outp,
   3947 			    blksize);
   3948 		}
   3949 	}
   3950 	kpreempt_disable();
   3951 	softint_schedule(sc->sc_sih_rd);
   3952 	kpreempt_enable();
   3953 }
   3954 
   3955 int
   3956 audio_check_params(struct audio_params *p)
   3957 {
   3958 
   3959 	if (p->encoding == AUDIO_ENCODING_PCM16) {
   3960 		if (p->precision == 8)
   3961 			p->encoding = AUDIO_ENCODING_ULINEAR;
   3962 		else
   3963 			p->encoding = AUDIO_ENCODING_SLINEAR;
   3964 	} else if (p->encoding == AUDIO_ENCODING_PCM8) {
   3965 		if (p->precision == 8)
   3966 			p->encoding = AUDIO_ENCODING_ULINEAR;
   3967 		else
   3968 			return EINVAL;
   3969 	}
   3970 
   3971 	if (p->encoding == AUDIO_ENCODING_SLINEAR)
   3972 #if BYTE_ORDER == LITTLE_ENDIAN
   3973 		p->encoding = AUDIO_ENCODING_SLINEAR_LE;
   3974 #else
   3975 		p->encoding = AUDIO_ENCODING_SLINEAR_BE;
   3976 #endif
   3977 	if (p->encoding == AUDIO_ENCODING_ULINEAR)
   3978 #if BYTE_ORDER == LITTLE_ENDIAN
   3979 		p->encoding = AUDIO_ENCODING_ULINEAR_LE;
   3980 #else
   3981 		p->encoding = AUDIO_ENCODING_ULINEAR_BE;
   3982 #endif
   3983 
   3984 	switch (p->encoding) {
   3985 	case AUDIO_ENCODING_ULAW:
   3986 	case AUDIO_ENCODING_ALAW:
   3987 		if (p->precision != 8)
   3988 			return EINVAL;
   3989 		break;
   3990 	case AUDIO_ENCODING_ADPCM:
   3991 		if (p->precision != 4 && p->precision != 8)
   3992 			return EINVAL;
   3993 		break;
   3994 	case AUDIO_ENCODING_SLINEAR_LE:
   3995 	case AUDIO_ENCODING_SLINEAR_BE:
   3996 	case AUDIO_ENCODING_ULINEAR_LE:
   3997 	case AUDIO_ENCODING_ULINEAR_BE:
   3998 		/* XXX is: our zero-fill can handle any multiple of 8 */
   3999 		if (p->precision !=  8 && p->precision != 16 &&
   4000 		    p->precision != 24 && p->precision != 32)
   4001 			return EINVAL;
   4002 		if (p->precision == 8 && p->encoding ==
   4003 		    AUDIO_ENCODING_SLINEAR_BE)
   4004 			p->encoding = AUDIO_ENCODING_SLINEAR_LE;
   4005 		if (p->precision == 8 && p->encoding ==
   4006 		    AUDIO_ENCODING_ULINEAR_BE)
   4007 			p->encoding = AUDIO_ENCODING_ULINEAR_LE;
   4008 		if (p->validbits > p->precision)
   4009 			return EINVAL;
   4010 		break;
   4011 	case AUDIO_ENCODING_MPEG_L1_STREAM:
   4012 	case AUDIO_ENCODING_MPEG_L1_PACKETS:
   4013 	case AUDIO_ENCODING_MPEG_L1_SYSTEM:
   4014 	case AUDIO_ENCODING_MPEG_L2_STREAM:
   4015 	case AUDIO_ENCODING_MPEG_L2_PACKETS:
   4016 	case AUDIO_ENCODING_MPEG_L2_SYSTEM:
   4017 	case AUDIO_ENCODING_AC3:
   4018 		break;
   4019 	default:
   4020 		return EINVAL;
   4021 	}
   4022 
   4023 	/* sanity check # of channels*/
   4024 	if (p->channels < 1 || p->channels > AUDIO_MAX_CHANNELS)
   4025 		return EINVAL;
   4026 
   4027 	return 0;
   4028 }
   4029 
   4030 static int
   4031 audio_set_vchan_defaults(struct audio_softc *sc, u_int mode,
   4032      const struct audio_format *format)
   4033 {
   4034 	struct audio_chan *chan;
   4035 	struct virtual_channel *vc;
   4036 	struct audio_info ai;
   4037 	int error;
   4038 
   4039 	KASSERT(mutex_owned(sc->sc_lock));
   4040 
   4041 	chan = SIMPLEQ_FIRST(&sc->sc_audiochan);
   4042 	if (chan == NULL)
   4043 		return EINVAL;
   4044 	vc = chan->vc;
   4045 
   4046 	sc->sc_vchan_params.sample_rate = sc->sc_iffreq;
   4047 #if BYTE_ORDER == LITTLE_ENDIAN
   4048 	sc->sc_vchan_params.encoding = AUDIO_ENCODING_SLINEAR_LE;
   4049 #else
   4050 	sc->sc_vchan_params.encoding = AUDIO_ENCODING_SLINEAR_BE;
   4051 #endif
   4052 	sc->sc_vchan_params.precision = sc->sc_precision;
   4053 	sc->sc_vchan_params.validbits = sc->sc_precision;
   4054 	sc->sc_vchan_params.channels = sc->sc_channels;
   4055 
   4056 	/* default parameters */
   4057 	vc->sc_rparams = sc->sc_vchan_params;
   4058 	vc->sc_pparams = sc->sc_vchan_params;
   4059 	vc->sc_blkset = false;
   4060 
   4061 	AUDIO_INITINFO(&ai);
   4062 	ai.record.sample_rate = sc->sc_iffreq;
   4063 	ai.record.encoding    = format->encoding;
   4064 	ai.record.channels    = sc->sc_channels;
   4065 	ai.record.precision   = sc->sc_precision;
   4066 	ai.record.pause	      = false;
   4067 	ai.play.sample_rate   = sc->sc_iffreq;
   4068 	ai.play.encoding      = format->encoding;
   4069 	ai.play.channels      = sc->sc_channels;
   4070 	ai.play.precision     = sc->sc_precision;
   4071 	ai.play.pause         = false;
   4072 	ai.mode		      = mode;
   4073 
   4074 	sc->sc_format->channels = sc->sc_channels;
   4075 	sc->sc_format->precision = sc->sc_precision;
   4076 	sc->sc_format->validbits = sc->sc_precision;
   4077 	sc->sc_format->frequency[0] = sc->sc_iffreq;
   4078 
   4079 	auconv_delete_encodings(sc->sc_encodings);
   4080 	error = auconv_create_encodings(sc->sc_format, VAUDIO_NFORMATS,
   4081 	    &sc->sc_encodings);
   4082 
   4083 	if (error == 0)
   4084 		error = audiosetinfo(sc, &ai, true, vc);
   4085 
   4086 	sc->sc_pr.blksize = vc->sc_mpr.blksize;
   4087 	sc->sc_rr.blksize = vc->sc_mrr.blksize;
   4088 
   4089 	return error;
   4090 }
   4091 
   4092 int
   4093 audio_set_defaults(struct audio_softc *sc, u_int mode,
   4094 		   struct virtual_channel *vc)
   4095 {
   4096 	struct audio_info ai;
   4097 
   4098 	KASSERT(mutex_owned(sc->sc_lock));
   4099 
   4100 	/* default parameters */
   4101 	vc->sc_rparams = audio_default;
   4102 	vc->sc_pparams = audio_default;
   4103 	vc->sc_blkset = false;
   4104 
   4105 	AUDIO_INITINFO(&ai);
   4106 	ai.record.sample_rate = vc->sc_rparams.sample_rate;
   4107 	ai.record.encoding    = vc->sc_rparams.encoding;
   4108 	ai.record.channels    = vc->sc_rparams.channels;
   4109 	ai.record.precision   = vc->sc_rparams.precision;
   4110 	ai.record.pause	      = false;
   4111 	ai.play.sample_rate   = vc->sc_pparams.sample_rate;
   4112 	ai.play.encoding      = vc->sc_pparams.encoding;
   4113 	ai.play.channels      = vc->sc_pparams.channels;
   4114 	ai.play.precision     = vc->sc_pparams.precision;
   4115 	ai.play.pause         = false;
   4116 	ai.mode		      = mode;
   4117 
   4118 	return audiosetinfo(sc, &ai, true, vc);
   4119 }
   4120 
   4121 int
   4122 au_set_lr_value(struct	audio_softc *sc, mixer_ctrl_t *ct, int l, int r)
   4123 {
   4124 
   4125 	KASSERT(mutex_owned(sc->sc_lock));
   4126 
   4127 	ct->type = AUDIO_MIXER_VALUE;
   4128 	ct->un.value.num_channels = 2;
   4129 	ct->un.value.level[AUDIO_MIXER_LEVEL_LEFT] = l;
   4130 	ct->un.value.level[AUDIO_MIXER_LEVEL_RIGHT] = r;
   4131 	if (audio_set_port(sc, ct) == 0)
   4132 		return 0;
   4133 	ct->un.value.num_channels = 1;
   4134 	ct->un.value.level[AUDIO_MIXER_LEVEL_MONO] = (l+r)/2;
   4135 	return audio_set_port(sc, ct);
   4136 }
   4137 
   4138 int
   4139 au_set_gain(struct audio_softc *sc, struct au_mixer_ports *ports,
   4140 	    int gain, int balance)
   4141 {
   4142 	mixer_ctrl_t ct;
   4143 	int i, error;
   4144 	int l, r;
   4145 	u_int mask;
   4146 	int nset;
   4147 
   4148 	KASSERT(mutex_owned(sc->sc_lock));
   4149 
   4150 	if (balance == AUDIO_MID_BALANCE) {
   4151 		l = r = gain;
   4152 	} else if (balance < AUDIO_MID_BALANCE) {
   4153 		l = gain;
   4154 		r = (balance * gain) / AUDIO_MID_BALANCE;
   4155 	} else {
   4156 		r = gain;
   4157 		l = ((AUDIO_RIGHT_BALANCE - balance) * gain)
   4158 		    / AUDIO_MID_BALANCE;
   4159 	}
   4160 	DPRINTF(("au_set_gain: gain=%d balance=%d, l=%d r=%d\n",
   4161 		 gain, balance, l, r));
   4162 
   4163 	if (ports->index == -1) {
   4164 	usemaster:
   4165 		if (ports->master == -1)
   4166 			return 0; /* just ignore it silently */
   4167 		ct.dev = ports->master;
   4168 		error = au_set_lr_value(sc, &ct, l, r);
   4169 	} else {
   4170 		ct.dev = ports->index;
   4171 		if (ports->isenum) {
   4172 			ct.type = AUDIO_MIXER_ENUM;
   4173 			error = audio_get_port(sc, &ct);
   4174 			if (error)
   4175 				return error;
   4176 			if (ports->isdual) {
   4177 				if (ports->cur_port == -1)
   4178 					ct.dev = ports->master;
   4179 				else
   4180 					ct.dev = ports->miport[ports->cur_port];
   4181 				error = au_set_lr_value(sc, &ct, l, r);
   4182 			} else {
   4183 				for(i = 0; i < ports->nports; i++)
   4184 				    if (ports->misel[i] == ct.un.ord) {
   4185 					    ct.dev = ports->miport[i];
   4186 					    if (ct.dev == -1 ||
   4187 						au_set_lr_value(sc, &ct, l, r))
   4188 						    goto usemaster;
   4189 					    else
   4190 						    break;
   4191 				    }
   4192 			}
   4193 		} else {
   4194 			ct.type = AUDIO_MIXER_SET;
   4195 			error = audio_get_port(sc, &ct);
   4196 			if (error)
   4197 				return error;
   4198 			mask = ct.un.mask;
   4199 			nset = 0;
   4200 			for(i = 0; i < ports->nports; i++) {
   4201 				if (ports->misel[i] & mask) {
   4202 				    ct.dev = ports->miport[i];
   4203 				    if (ct.dev != -1 &&
   4204 					au_set_lr_value(sc, &ct, l, r) == 0)
   4205 					    nset++;
   4206 				}
   4207 			}
   4208 			if (nset == 0)
   4209 				goto usemaster;
   4210 		}
   4211 	}
   4212 	if (!error)
   4213 		mixer_signal(sc);
   4214 	return error;
   4215 }
   4216 
   4217 int
   4218 au_get_lr_value(struct	audio_softc *sc, mixer_ctrl_t *ct, int *l, int *r)
   4219 {
   4220 	int error;
   4221 
   4222 	KASSERT(mutex_owned(sc->sc_lock));
   4223 
   4224 	ct->un.value.num_channels = 2;
   4225 	if (audio_get_port(sc, ct) == 0) {
   4226 		*l = ct->un.value.level[AUDIO_MIXER_LEVEL_LEFT];
   4227 		*r = ct->un.value.level[AUDIO_MIXER_LEVEL_RIGHT];
   4228 	} else {
   4229 		ct->un.value.num_channels = 1;
   4230 		error = audio_get_port(sc, ct);
   4231 		if (error)
   4232 			return error;
   4233 		*r = *l = ct->un.value.level[AUDIO_MIXER_LEVEL_MONO];
   4234 	}
   4235 	return 0;
   4236 }
   4237 
   4238 void
   4239 au_get_gain(struct audio_softc *sc, struct au_mixer_ports *ports,
   4240 	    u_int *pgain, u_char *pbalance)
   4241 {
   4242 	mixer_ctrl_t ct;
   4243 	int i, l, r, n;
   4244 	int lgain, rgain;
   4245 
   4246 	KASSERT(mutex_owned(sc->sc_lock));
   4247 
   4248 	lgain = AUDIO_MAX_GAIN / 2;
   4249 	rgain = AUDIO_MAX_GAIN / 2;
   4250 	if (ports->index == -1) {
   4251 	usemaster:
   4252 		if (ports->master == -1)
   4253 			goto bad;
   4254 		ct.dev = ports->master;
   4255 		ct.type = AUDIO_MIXER_VALUE;
   4256 		if (au_get_lr_value(sc, &ct, &lgain, &rgain))
   4257 			goto bad;
   4258 	} else {
   4259 		ct.dev = ports->index;
   4260 		if (ports->isenum) {
   4261 			ct.type = AUDIO_MIXER_ENUM;
   4262 			if (audio_get_port(sc, &ct))
   4263 				goto bad;
   4264 			ct.type = AUDIO_MIXER_VALUE;
   4265 			if (ports->isdual) {
   4266 				if (ports->cur_port == -1)
   4267 					ct.dev = ports->master;
   4268 				else
   4269 					ct.dev = ports->miport[ports->cur_port];
   4270 				au_get_lr_value(sc, &ct, &lgain, &rgain);
   4271 			} else {
   4272 				for(i = 0; i < ports->nports; i++)
   4273 				    if (ports->misel[i] == ct.un.ord) {
   4274 					    ct.dev = ports->miport[i];
   4275 					    if (ct.dev == -1 ||
   4276 						au_get_lr_value(sc, &ct,
   4277 								&lgain, &rgain))
   4278 						    goto usemaster;
   4279 					    else
   4280 						    break;
   4281 				    }
   4282 			}
   4283 		} else {
   4284 			ct.type = AUDIO_MIXER_SET;
   4285 			if (audio_get_port(sc, &ct))
   4286 				goto bad;
   4287 			ct.type = AUDIO_MIXER_VALUE;
   4288 			lgain = rgain = n = 0;
   4289 			for(i = 0; i < ports->nports; i++) {
   4290 				if (ports->misel[i] & ct.un.mask) {
   4291 					ct.dev = ports->miport[i];
   4292 					if (ct.dev == -1 ||
   4293 					    au_get_lr_value(sc, &ct, &l, &r))
   4294 						goto usemaster;
   4295 					else {
   4296 						lgain += l;
   4297 						rgain += r;
   4298 						n++;
   4299 					}
   4300 				}
   4301 			}
   4302 			if (n != 0) {
   4303 				lgain /= n;
   4304 				rgain /= n;
   4305 			}
   4306 		}
   4307 	}
   4308 bad:
   4309 	if (lgain == rgain) {	/* handles lgain==rgain==0 */
   4310 		*pgain = lgain;
   4311 		*pbalance = AUDIO_MID_BALANCE;
   4312 	} else if (lgain < rgain) {
   4313 		*pgain = rgain;
   4314 		/* balance should be > AUDIO_MID_BALANCE */
   4315 		*pbalance = AUDIO_RIGHT_BALANCE -
   4316 			(AUDIO_MID_BALANCE * lgain) / rgain;
   4317 	} else /* lgain > rgain */ {
   4318 		*pgain = lgain;
   4319 		/* balance should be < AUDIO_MID_BALANCE */
   4320 		*pbalance = (AUDIO_MID_BALANCE * rgain) / lgain;
   4321 	}
   4322 }
   4323 
   4324 int
   4325 au_set_port(struct audio_softc *sc, struct au_mixer_ports *ports, u_int port)
   4326 {
   4327 	mixer_ctrl_t ct;
   4328 	int i, error, use_mixerout;
   4329 
   4330 	KASSERT(mutex_owned(sc->sc_lock));
   4331 
   4332 	use_mixerout = 1;
   4333 	if (port == 0) {
   4334 		if (ports->allports == 0)
   4335 			return 0;		/* Allow this special case. */
   4336 		else if (ports->isdual) {
   4337 			if (ports->cur_port == -1) {
   4338 				return 0;
   4339 			} else {
   4340 				port = ports->aumask[ports->cur_port];
   4341 				ports->cur_port = -1;
   4342 				use_mixerout = 0;
   4343 			}
   4344 		}
   4345 	}
   4346 	if (ports->index == -1)
   4347 		return EINVAL;
   4348 	ct.dev = ports->index;
   4349 	if (ports->isenum) {
   4350 		if (port & (port-1))
   4351 			return EINVAL; /* Only one port allowed */
   4352 		ct.type = AUDIO_MIXER_ENUM;
   4353 		error = EINVAL;
   4354 		for(i = 0; i < ports->nports; i++)
   4355 			if (ports->aumask[i] == port) {
   4356 				if (ports->isdual && use_mixerout) {
   4357 					ct.un.ord = ports->mixerout;
   4358 					ports->cur_port = i;
   4359 				} else {
   4360 					ct.un.ord = ports->misel[i];
   4361 				}
   4362 				error = audio_set_port(sc, &ct);
   4363 				break;
   4364 			}
   4365 	} else {
   4366 		ct.type = AUDIO_MIXER_SET;
   4367 		ct.un.mask = 0;
   4368 		for(i = 0; i < ports->nports; i++)
   4369 			if (ports->aumask[i] & port)
   4370 				ct.un.mask |= ports->misel[i];
   4371 		if (port != 0 && ct.un.mask == 0)
   4372 			error = EINVAL;
   4373 		else
   4374 			error = audio_set_port(sc, &ct);
   4375 	}
   4376 	if (!error)
   4377 		mixer_signal(sc);
   4378 	return error;
   4379 }
   4380 
   4381 int
   4382 au_get_port(struct audio_softc *sc, struct au_mixer_ports *ports)
   4383 {
   4384 	mixer_ctrl_t ct;
   4385 	int i, aumask;
   4386 
   4387 	KASSERT(mutex_owned(sc->sc_lock));
   4388 
   4389 	if (ports->index == -1)
   4390 		return 0;
   4391 	ct.dev = ports->index;
   4392 	ct.type = ports->isenum ? AUDIO_MIXER_ENUM : AUDIO_MIXER_SET;
   4393 	if (audio_get_port(sc, &ct))
   4394 		return 0;
   4395 	aumask = 0;
   4396 	if (ports->isenum) {
   4397 		if (ports->isdual && ports->cur_port != -1) {
   4398 			if (ports->mixerout == ct.un.ord)
   4399 				aumask = ports->aumask[ports->cur_port];
   4400 			else
   4401 				ports->cur_port = -1;
   4402 		}
   4403 		if (aumask == 0)
   4404 			for(i = 0; i < ports->nports; i++)
   4405 				if (ports->misel[i] == ct.un.ord)
   4406 					aumask = ports->aumask[i];
   4407 	} else {
   4408 		for(i = 0; i < ports->nports; i++)
   4409 			if (ct.un.mask & ports->misel[i])
   4410 				aumask |= ports->aumask[i];
   4411 	}
   4412 	return aumask;
   4413 }
   4414 
   4415 int
   4416 audiosetinfo(struct audio_softc *sc, struct audio_info *ai, bool reset,
   4417 	     struct virtual_channel *vc)
   4418 {
   4419 	stream_filter_list_t pfilters, rfilters;
   4420 	audio_params_t pp, rp;
   4421 	struct audio_prinfo *r, *p;
   4422 	const struct audio_hw_if *hw;
   4423 	audio_stream_t *oldpus, *oldrus;
   4424 	int setmode;
   4425 	int error;
   4426 	int np, nr;
   4427 	unsigned int blks;
   4428 	int oldpblksize, oldrblksize;
   4429 	u_int gain;
   4430 	bool rbus, pbus;
   4431 	bool cleared, modechange, pausechange;
   4432 	u_char balance;
   4433 
   4434 	KASSERT(mutex_owned(sc->sc_lock));
   4435 
   4436 	hw = sc->hw_if;
   4437 	if (hw == NULL)		/* HW has not attached */
   4438 		return ENXIO;
   4439 
   4440 	DPRINTF(("%s sc=%p ai=%p\n", __func__, sc, ai));
   4441 	r = &ai->record;
   4442 	p = &ai->play;
   4443 	rbus = vc->sc_rbus;
   4444 	pbus = vc->sc_pbus;
   4445 	error = 0;
   4446 	cleared = false;
   4447 	modechange = false;
   4448 	pausechange = false;
   4449 
   4450 	pp = vc->sc_pparams;	/* Temporary encoding storage in */
   4451 	rp = vc->sc_rparams;	/* case setting the modes fails. */
   4452 	nr = np = 0;
   4453 
   4454 	if (SPECIFIED(p->sample_rate)) {
   4455 		pp.sample_rate = p->sample_rate;
   4456 		np++;
   4457 	}
   4458 	if (SPECIFIED(r->sample_rate)) {
   4459 		rp.sample_rate = r->sample_rate;
   4460 		nr++;
   4461 	}
   4462 	if (SPECIFIED(p->encoding)) {
   4463 		pp.encoding = p->encoding;
   4464 		np++;
   4465 	}
   4466 	if (SPECIFIED(r->encoding)) {
   4467 		rp.encoding = r->encoding;
   4468 		nr++;
   4469 	}
   4470 	if (SPECIFIED(p->precision)) {
   4471 		pp.precision = p->precision;
   4472 		/* we don't have API to specify validbits */
   4473 		pp.validbits = p->precision;
   4474 		np++;
   4475 	}
   4476 	if (SPECIFIED(r->precision)) {
   4477 		rp.precision = r->precision;
   4478 		/* we don't have API to specify validbits */
   4479 		rp.validbits = r->precision;
   4480 		nr++;
   4481 	}
   4482 	if (SPECIFIED(p->channels)) {
   4483 		pp.channels = p->channels;
   4484 		np++;
   4485 	}
   4486 	if (SPECIFIED(r->channels)) {
   4487 		rp.channels = r->channels;
   4488 		nr++;
   4489 	}
   4490 
   4491 	if (!audio_can_capture(sc))
   4492 		nr = 0;
   4493 	if (!audio_can_playback(sc))
   4494 		np = 0;
   4495 
   4496 #ifdef AUDIO_DEBUG
   4497 	if (audiodebug && nr > 0)
   4498 	    audio_print_params("audiosetinfo() Setting record params:", &rp);
   4499 	if (audiodebug && np > 0)
   4500 	    audio_print_params("audiosetinfo() Setting play params:", &pp);
   4501 #endif
   4502 	if (nr > 0 && (error = audio_check_params(&rp)))
   4503 		return error;
   4504 	if (np > 0 && (error = audio_check_params(&pp)))
   4505 		return error;
   4506 
   4507 	oldpblksize = vc->sc_mpr.blksize;
   4508 	oldrblksize = vc->sc_mrr.blksize;
   4509 
   4510 	setmode = 0;
   4511 	if (nr > 0) {
   4512 		if (!cleared) {
   4513 			audio_clear_intr_unlocked(sc, vc);
   4514 			cleared = true;
   4515 		}
   4516 		modechange = true;
   4517 		setmode |= AUMODE_RECORD;
   4518 	}
   4519 	if (np > 0) {
   4520 		if (!cleared) {
   4521 			audio_clear_intr_unlocked(sc, vc);
   4522 			cleared = true;
   4523 		}
   4524 		modechange = true;
   4525 		setmode |= AUMODE_PLAY;
   4526 	}
   4527 
   4528 	if (SPECIFIED(ai->mode)) {
   4529 		if (!cleared) {
   4530 			audio_clear_intr_unlocked(sc, vc);
   4531 			cleared = true;
   4532 		}
   4533 		modechange = true;
   4534 		vc->sc_mode = ai->mode;
   4535 		if (vc->sc_mode & AUMODE_PLAY_ALL)
   4536 			vc->sc_mode |= AUMODE_PLAY;
   4537 		if ((vc->sc_mode & AUMODE_PLAY) && !vc->sc_full_duplex)
   4538 			/* Play takes precedence */
   4539 			vc->sc_mode &= ~AUMODE_RECORD;
   4540 	}
   4541 
   4542 	oldpus = vc->sc_pustream;
   4543 	oldrus = vc->sc_rustream;
   4544 	if (modechange || reset) {
   4545 		int indep;
   4546 
   4547 		indep = audio_get_props(sc) & AUDIO_PROP_INDEPENDENT;
   4548 		if (!indep) {
   4549 			if (setmode == AUMODE_RECORD)
   4550 				pp = rp;
   4551 			else if (setmode == AUMODE_PLAY)
   4552 				rp = pp;
   4553 		}
   4554 		memset(&pfilters, 0, sizeof(pfilters));
   4555 		memset(&rfilters, 0, sizeof(rfilters));
   4556 		pfilters.append = stream_filter_list_append;
   4557 		pfilters.prepend = stream_filter_list_prepend;
   4558 		pfilters.set = stream_filter_list_set;
   4559 		rfilters.append = stream_filter_list_append;
   4560 		rfilters.prepend = stream_filter_list_prepend;
   4561 		rfilters.set = stream_filter_list_set;
   4562 		/* Some device drivers change channels/sample_rate and change
   4563 		 * no channels/sample_rate. */
   4564 		error = audio_set_params(sc, setmode,
   4565 		    vc->sc_mode & (AUMODE_PLAY | AUMODE_RECORD), &pp, &rp,
   4566 		    &pfilters, &rfilters, vc);
   4567 		if (error) {
   4568 			DPRINTF(("%s: audio_set_params() failed with %d\n",
   4569 			    __func__, error));
   4570 			goto cleanup;
   4571 		}
   4572 
   4573 		audio_check_params(&pp);
   4574 		audio_check_params(&rp);
   4575 		if (!indep) {
   4576 			/* XXX for !indep device, we have to use the same
   4577 			 * parameters for the hardware, not userland */
   4578 			if (setmode == AUMODE_RECORD) {
   4579 				pp = rp;
   4580 			} else if (setmode == AUMODE_PLAY) {
   4581 				rp = pp;
   4582 			}
   4583 		}
   4584 
   4585 		if (vc->sc_mpr.mmapped && pfilters.req_size > 0) {
   4586 			DPRINTF(("%s: mmapped, and filters are requested.\n",
   4587 				 __func__));
   4588 			error = EINVAL;
   4589 			goto cleanup;
   4590 		}
   4591 
   4592 		/* construct new filter chain */
   4593 		if (setmode & AUMODE_PLAY) {
   4594 			error = audio_setup_pfilters(sc, &pp, &pfilters, vc);
   4595 			if (error)
   4596 				goto cleanup;
   4597 		}
   4598 		if (setmode & AUMODE_RECORD) {
   4599 			error = audio_setup_rfilters(sc, &rp, &rfilters, vc);
   4600 			if (error)
   4601 				goto cleanup;
   4602 		}
   4603 		DPRINTF(("%s: filter setup is completed.\n", __func__));
   4604 
   4605 		/* userland formats */
   4606 		vc->sc_pparams = pp;
   4607 		vc->sc_rparams = rp;
   4608 	}
   4609 
   4610 	/* Play params can affect the record params, so recalculate blksize. */
   4611 	if (nr > 0 || np > 0 || reset) {
   4612 		vc->sc_blkset = false;
   4613 		audio_calc_blksize(sc, AUMODE_RECORD, vc);
   4614 		audio_calc_blksize(sc, AUMODE_PLAY, vc);
   4615 	}
   4616 #ifdef AUDIO_DEBUG
   4617 	if (audiodebug > 1 && nr > 0) {
   4618 	    audio_print_params("audiosetinfo() After setting record params:",
   4619 		&vc->sc_rparams);
   4620 	}
   4621 	if (audiodebug > 1 && np > 0) {
   4622 	    audio_print_params("audiosetinfo() After setting play params:",
   4623 		&vc->sc_pparams);
   4624 	}
   4625 #endif
   4626 
   4627 	if (SPECIFIED(p->port)) {
   4628 		if (!cleared) {
   4629 			audio_clear_intr_unlocked(sc, vc);
   4630 			cleared = true;
   4631 		}
   4632 		error = au_set_port(sc, &sc->sc_outports, p->port);
   4633 		if (error)
   4634 			goto cleanup;
   4635 	}
   4636 	if (SPECIFIED(r->port)) {
   4637 		if (!cleared) {
   4638 			audio_clear_intr_unlocked(sc, vc);
   4639 			cleared = true;
   4640 		}
   4641 		error = au_set_port(sc, &sc->sc_inports, r->port);
   4642 		if (error)
   4643 			goto cleanup;
   4644 	}
   4645 	if (SPECIFIED(p->gain)) {
   4646 		au_get_gain(sc, &sc->sc_outports, &gain, &balance);
   4647 		error = au_set_gain(sc, &sc->sc_outports, p->gain, balance);
   4648 		if (error)
   4649 			goto cleanup;
   4650 	}
   4651 	if (SPECIFIED(r->gain)) {
   4652 		au_get_gain(sc, &sc->sc_inports, &gain, &balance);
   4653 		error = au_set_gain(sc, &sc->sc_inports, r->gain, balance);
   4654 		if (error)
   4655 			goto cleanup;
   4656 	}
   4657 
   4658 	if (SPECIFIED_CH(p->balance)) {
   4659 		au_get_gain(sc, &sc->sc_outports, &gain, &balance);
   4660 		error = au_set_gain(sc, &sc->sc_outports, gain, p->balance);
   4661 		if (error)
   4662 			goto cleanup;
   4663 	}
   4664 	if (SPECIFIED_CH(r->balance)) {
   4665 		au_get_gain(sc, &sc->sc_inports, &gain, &balance);
   4666 		error = au_set_gain(sc, &sc->sc_inports, gain, r->balance);
   4667 		if (error)
   4668 			goto cleanup;
   4669 	}
   4670 
   4671 	if (SPECIFIED(ai->monitor_gain) && sc->sc_monitor_port != -1) {
   4672 		mixer_ctrl_t ct;
   4673 
   4674 		ct.dev = sc->sc_monitor_port;
   4675 		ct.type = AUDIO_MIXER_VALUE;
   4676 		ct.un.value.num_channels = 1;
   4677 		ct.un.value.level[AUDIO_MIXER_LEVEL_MONO] = ai->monitor_gain;
   4678 		error = audio_set_port(sc, &ct);
   4679 		if (error)
   4680 			goto cleanup;
   4681 	}
   4682 
   4683 	if (SPECIFIED_CH(p->pause)) {
   4684 		vc->sc_mpr.pause = p->pause;
   4685 		pbus = !p->pause;
   4686 		pausechange = true;
   4687 	}
   4688 	if (SPECIFIED_CH(r->pause)) {
   4689 		vc->sc_mrr.pause = r->pause;
   4690 		rbus = !r->pause;
   4691 		pausechange = true;
   4692 	}
   4693 
   4694 	if (SPECIFIED(ai->blocksize)) {
   4695 		int pblksize, rblksize;
   4696 
   4697 		/* Block size specified explicitly. */
   4698 		if (ai->blocksize == 0) {
   4699 			if (!cleared) {
   4700 				audio_clear_intr_unlocked(sc, vc);
   4701 				cleared = true;
   4702 			}
   4703 			vc->sc_blkset = false;
   4704 			audio_calc_blksize(sc, AUMODE_RECORD, vc);
   4705 			audio_calc_blksize(sc, AUMODE_PLAY, vc);
   4706 		} else {
   4707 			vc->sc_blkset = true;
   4708 			/* check whether new blocksize changes actually */
   4709 			if (hw->round_blocksize == NULL) {
   4710 				if (!cleared) {
   4711 					audio_clear_intr_unlocked(sc, vc);
   4712 					cleared = true;
   4713 				}
   4714 				vc->sc_mpr.blksize = ai->blocksize;
   4715 				vc->sc_mrr.blksize = ai->blocksize;
   4716 			} else {
   4717 				pblksize = hw->round_blocksize(sc->hw_hdl,
   4718 				    ai->blocksize, AUMODE_PLAY,
   4719 				    &vc->sc_mpr.s.param);
   4720 				rblksize = hw->round_blocksize(sc->hw_hdl,
   4721 				    ai->blocksize, AUMODE_RECORD,
   4722 				    &vc->sc_mrr.s.param);
   4723 				if ((pblksize != vc->sc_mpr.blksize &&
   4724 				    pblksize > sc->sc_pr.blksize)
   4725 				    || (rblksize != vc->sc_mrr.blksize &&
   4726 				    rblksize > sc->sc_rr.blksize)) {
   4727 					if (!cleared) {
   4728 					    audio_clear_intr_unlocked(sc, vc);
   4729 					    cleared = true;
   4730 					}
   4731 					vc->sc_mpr.blksize = pblksize;
   4732 					vc->sc_mrr.blksize = rblksize;
   4733 				}
   4734 			}
   4735 		}
   4736 	}
   4737 
   4738 	if (SPECIFIED(ai->mode)) {
   4739 		if (vc->sc_mode & AUMODE_PLAY)
   4740 			audio_init_play(sc, vc);
   4741 		if (vc->sc_mode & AUMODE_RECORD)
   4742 			audio_init_record(sc, vc);
   4743 	}
   4744 
   4745 	if (hw->commit_settings && sc->sc_opens == 0) {
   4746 		error = hw->commit_settings(sc->hw_hdl);
   4747 		if (error)
   4748 			goto cleanup;
   4749 	}
   4750 
   4751 	vc->sc_lastinfo = *ai;
   4752 	vc->sc_lastinfovalid = true;
   4753 
   4754 cleanup:
   4755 	if (error == 0 && (cleared || pausechange|| reset)) {
   4756 		int init_error;
   4757 
   4758 		init_error = (pausechange == 1 && reset == 0) ? 0 :
   4759 		    audio_initbufs(sc, vc);
   4760 		if (init_error) goto err;
   4761 		if (vc->sc_mpr.blksize != oldpblksize ||
   4762 		    vc->sc_mrr.blksize != oldrblksize ||
   4763 		    vc->sc_pustream != oldpus ||
   4764 		    vc->sc_rustream != oldrus)
   4765 			audio_calcwater(sc, vc);
   4766 		if ((vc->sc_mode & AUMODE_PLAY) &&
   4767 		    pbus && !vc->sc_pbus)
   4768 			init_error = audiostartp(sc, vc);
   4769 		if (!init_error &&
   4770 		    (vc->sc_mode & AUMODE_RECORD) &&
   4771 		    rbus && !vc->sc_rbus)
   4772 			init_error = audiostartr(sc, vc);
   4773 	err:
   4774 		if (init_error)
   4775 			return init_error;
   4776 	}
   4777 
   4778 	/* Change water marks after initializing the buffers. */
   4779 	if (SPECIFIED(ai->hiwat)) {
   4780 		blks = ai->hiwat;
   4781 		if (blks > vc->sc_mpr.maxblks)
   4782 			blks = vc->sc_mpr.maxblks;
   4783 		if (blks < 2)
   4784 			blks = 2;
   4785 		vc->sc_mpr.usedhigh = blks * vc->sc_mpr.blksize;
   4786 	}
   4787 	if (SPECIFIED(ai->lowat)) {
   4788 		blks = ai->lowat;
   4789 		if (blks > vc->sc_mpr.maxblks - 1)
   4790 			blks = vc->sc_mpr.maxblks - 1;
   4791 		vc->sc_mpr.usedlow = blks * vc->sc_mpr.blksize;
   4792 	}
   4793 	if (SPECIFIED(ai->hiwat) || SPECIFIED(ai->lowat)) {
   4794 		if (vc->sc_mpr.usedlow > vc->sc_mpr.usedhigh -
   4795 		    vc->sc_mpr.blksize) {
   4796 			vc->sc_mpr.usedlow =
   4797 				vc->sc_mpr.usedhigh - vc->sc_mpr.blksize;
   4798 		}
   4799 	}
   4800 
   4801 	return error;
   4802 }
   4803 
   4804 int
   4805 audiogetinfo(struct audio_softc *sc, struct audio_info *ai, int buf_only_mode,
   4806 	     struct virtual_channel *vc)
   4807 {
   4808 	struct audio_prinfo *r, *p;
   4809 	const struct audio_hw_if *hw;
   4810 
   4811 	KASSERT(mutex_owned(sc->sc_lock));
   4812 
   4813 	r = &ai->record;
   4814 	p = &ai->play;
   4815 	hw = sc->hw_if;
   4816 	if (hw == NULL)		/* HW has not attached */
   4817 		return ENXIO;
   4818 
   4819 	p->sample_rate = vc->sc_pparams.sample_rate;
   4820 	r->sample_rate = vc->sc_rparams.sample_rate;
   4821 	p->channels = vc->sc_pparams.channels;
   4822 	r->channels = vc->sc_rparams.channels;
   4823 	p->precision = vc->sc_pparams.precision;
   4824 	r->precision = vc->sc_rparams.precision;
   4825 	p->encoding = vc->sc_pparams.encoding;
   4826 	r->encoding = vc->sc_rparams.encoding;
   4827 
   4828 	if (buf_only_mode) {
   4829 		r->port = 0;
   4830 		p->port = 0;
   4831 
   4832 		r->avail_ports = 0;
   4833 		p->avail_ports = 0;
   4834 
   4835 		r->gain = 0;
   4836 		r->balance = 0;
   4837 
   4838 		p->gain = 0;
   4839 		p->balance = 0;
   4840 	} else {
   4841 		r->port = au_get_port(sc, &sc->sc_inports);
   4842 		p->port = au_get_port(sc, &sc->sc_outports);
   4843 
   4844 		r->avail_ports = sc->sc_inports.allports;
   4845 		p->avail_ports = sc->sc_outports.allports;
   4846 
   4847 		au_get_gain(sc, &sc->sc_inports, &r->gain, &r->balance);
   4848 		au_get_gain(sc, &sc->sc_outports, &p->gain, &p->balance);
   4849 	}
   4850 
   4851 	if (sc->sc_monitor_port != -1 && buf_only_mode == 0) {
   4852 		mixer_ctrl_t ct;
   4853 
   4854 		ct.dev = sc->sc_monitor_port;
   4855 		ct.type = AUDIO_MIXER_VALUE;
   4856 		ct.un.value.num_channels = 1;
   4857 		if (audio_get_port(sc, &ct))
   4858 			ai->monitor_gain = 0;
   4859 		else
   4860 			ai->monitor_gain =
   4861 				ct.un.value.level[AUDIO_MIXER_LEVEL_MONO];
   4862 	} else
   4863 		ai->monitor_gain = 0;
   4864 
   4865 	p->seek = audio_stream_get_used(vc->sc_pustream);
   4866 	r->seek = audio_stream_get_used(vc->sc_rustream);
   4867 
   4868 	/*
   4869 	 * XXX samples should be a value for userland data.
   4870 	 * But drops is a value for HW data.
   4871 	 */
   4872 	p->samples = (vc->sc_pustream == &vc->sc_mpr.s
   4873 	    ? vc->sc_mpr.stamp : vc->sc_mpr.fstamp) - vc->sc_mpr.drops;
   4874 	r->samples = (vc->sc_rustream == &vc->sc_mrr.s
   4875 	    ? vc->sc_mrr.stamp : vc->sc_mrr.fstamp) - vc->sc_mrr.drops;
   4876 
   4877 	p->eof = sc->sc_eof;
   4878 	r->eof = 0;
   4879 
   4880 	p->pause = vc->sc_mpr.pause;
   4881 	r->pause = vc->sc_mrr.pause;
   4882 
   4883 	p->error = vc->sc_mpr.drops != 0;
   4884 	r->error = vc->sc_mrr.drops != 0;
   4885 
   4886 	p->waiting = r->waiting = 0;		/* open never hangs */
   4887 
   4888 	p->open = (vc->sc_open & AUOPEN_WRITE) != 0;
   4889 	r->open = (vc->sc_open & AUOPEN_READ) != 0;
   4890 
   4891 	p->active = vc->sc_pbus;
   4892 	r->active = vc->sc_rbus;
   4893 
   4894 	p->buffer_size = vc->sc_pustream ? vc->sc_pustream->bufsize : 0;
   4895 	r->buffer_size = vc->sc_rustream ? vc->sc_rustream->bufsize : 0;
   4896 
   4897 	ai->blocksize = vc->sc_mpr.blksize;
   4898 	if (vc->sc_mpr.blksize > 0) {
   4899 		ai->hiwat = vc->sc_mpr.usedhigh / vc->sc_mpr.blksize;
   4900 		ai->lowat = vc->sc_mpr.usedlow / vc->sc_mpr.blksize;
   4901 	} else
   4902 		ai->hiwat = ai->lowat = 0;
   4903 	ai->mode = vc->sc_mode;
   4904 
   4905 	return 0;
   4906 }
   4907 
   4908 /*
   4909  * Mixer driver
   4910  */
   4911 int
   4912 mixer_open(dev_t dev, struct audio_softc *sc, int flags,
   4913     int ifmt, struct lwp *l, struct file **nfp)
   4914 {
   4915 	struct file *fp;
   4916 	struct audio_chan *chan;
   4917 	int error, fd;
   4918 
   4919 	KASSERT(mutex_owned(sc->sc_lock));
   4920 
   4921 	if (sc->hw_if == NULL)
   4922 		return  ENXIO;
   4923 
   4924 	DPRINTF(("mixer_open: flags=0x%x sc=%p\n", flags, sc));
   4925 
   4926 	chan = kmem_zalloc(sizeof(struct audio_chan), KM_SLEEP);
   4927 
   4928 	error = fd_allocfile(&fp, &fd);
   4929 	if (error)
   4930 		return error;
   4931 
   4932 	chan->dev = dev;
   4933 	chan->chan = MIXER_INUSE;
   4934 
   4935 	SIMPLEQ_INSERT_TAIL(&sc->sc_audiochan, chan, entries);
   4936 
   4937 	error = fd_clone(fp, fd, flags, &audio_fileops, chan);
   4938 	KASSERT(error == EMOVEFD);
   4939 
   4940 	*nfp = fp;
   4941 	return error;
   4942 }
   4943 
   4944 /*
   4945  * Remove a process from those to be signalled on mixer activity.
   4946  */
   4947 static void
   4948 mixer_remove(struct audio_softc *sc)
   4949 {
   4950 	struct mixer_asyncs **pm, *m;
   4951 	pid_t pid;
   4952 
   4953 	KASSERT(mutex_owned(sc->sc_lock));
   4954 
   4955 	pid = curproc->p_pid;
   4956 	for (pm = &sc->sc_async_mixer; *pm; pm = &(*pm)->next) {
   4957 		if ((*pm)->pid == pid) {
   4958 			m = *pm;
   4959 			*pm = m->next;
   4960 			kmem_free(m, sizeof(*m));
   4961 			return;
   4962 		}
   4963 	}
   4964 }
   4965 
   4966 /*
   4967  * Signal all processes waiting for the mixer.
   4968  */
   4969 static void
   4970 mixer_signal(struct audio_softc *sc)
   4971 {
   4972 	struct mixer_asyncs *m;
   4973 	proc_t *p;
   4974 
   4975 	for (m = sc->sc_async_mixer; m; m = m->next) {
   4976 		mutex_enter(proc_lock);
   4977 		if ((p = proc_find(m->pid)) != NULL)
   4978 			psignal(p, SIGIO);
   4979 		mutex_exit(proc_lock);
   4980 	}
   4981 }
   4982 
   4983 /*
   4984  * Close a mixer device
   4985  */
   4986 /* ARGSUSED */
   4987 int
   4988 mixer_close(struct audio_softc *sc, int flags, struct audio_chan *chan)
   4989 {
   4990 
   4991 	KASSERT(mutex_owned(sc->sc_lock));
   4992 	if (sc->hw_if == NULL)
   4993 		return ENXIO;
   4994 
   4995 	DPRINTF(("mixer_close: sc %p\n", sc));
   4996 	mixer_remove(sc);
   4997 	SIMPLEQ_REMOVE(&sc->sc_audiochan, chan, audio_chan, entries);
   4998 
   4999 	return 0;
   5000 }
   5001 
   5002 int
   5003 mixer_ioctl(struct audio_softc *sc, u_long cmd, void *addr, int flag,
   5004 	    struct lwp *l)
   5005 {
   5006 	const struct audio_hw_if *hw;
   5007 	struct mixer_asyncs *ma;
   5008 	mixer_ctrl_t *mc;
   5009 	int error;
   5010 
   5011 	DPRINTF(("mixer_ioctl(%lu,'%c',%lu)\n",
   5012 		 IOCPARM_LEN(cmd), (char)IOCGROUP(cmd), cmd&0xff));
   5013 	hw = sc->hw_if;
   5014 	if (hw == NULL)
   5015 		return ENXIO;
   5016 	error = EINVAL;
   5017 
   5018 	/* we can return cached values if we are sleeping */
   5019 	if (cmd != AUDIO_MIXER_READ)
   5020 		device_active(sc->dev, DVA_SYSTEM);
   5021 
   5022 	switch (cmd) {
   5023 	case FIOASYNC:
   5024 		if (*(int *)addr) {
   5025 			ma = kmem_alloc(sizeof(struct mixer_asyncs), KM_SLEEP);
   5026 		} else {
   5027 			ma = NULL;
   5028 		}
   5029 		mixer_remove(sc);	/* remove old entry */
   5030 		if (ma != NULL) {
   5031 			ma->next = sc->sc_async_mixer;
   5032 			ma->pid = curproc->p_pid;
   5033 			sc->sc_async_mixer = ma;
   5034 		}
   5035 		error = 0;
   5036 		break;
   5037 
   5038 	case AUDIO_GETDEV:
   5039 		DPRINTF(("AUDIO_GETDEV\n"));
   5040 		error = hw->getdev(sc->hw_hdl, (audio_device_t *)addr);
   5041 		break;
   5042 
   5043 	case AUDIO_MIXER_DEVINFO:
   5044 		DPRINTF(("AUDIO_MIXER_DEVINFO\n"));
   5045 		((mixer_devinfo_t *)addr)->un.v.delta = 0; /* default */
   5046 		error = audio_query_devinfo(sc, (mixer_devinfo_t *)addr);
   5047 		break;
   5048 
   5049 	case AUDIO_MIXER_READ:
   5050 		DPRINTF(("AUDIO_MIXER_READ\n"));
   5051 		mc = (mixer_ctrl_t *)addr;
   5052 
   5053 		if (device_is_active(sc->sc_dev))
   5054 			error = audio_get_port(sc, mc);
   5055 		else if (mc->dev >= sc->sc_nmixer_states)
   5056 			error = ENXIO;
   5057 		else {
   5058 			int dev = mc->dev;
   5059 			memcpy(mc, &sc->sc_mixer_state[dev],
   5060 			    sizeof(mixer_ctrl_t));
   5061 			error = 0;
   5062 		}
   5063 		break;
   5064 
   5065 	case AUDIO_MIXER_WRITE:
   5066 		DPRINTF(("AUDIO_MIXER_WRITE\n"));
   5067 		error = audio_set_port(sc, (mixer_ctrl_t *)addr);
   5068 		if (!error && hw->commit_settings)
   5069 			error = hw->commit_settings(sc->hw_hdl);
   5070 		if (!error)
   5071 			mixer_signal(sc);
   5072 		break;
   5073 
   5074 	default:
   5075 		if (hw->dev_ioctl) {
   5076 			error = hw->dev_ioctl(sc->hw_hdl, cmd, addr, flag, l);
   5077 		} else
   5078 			error = EINVAL;
   5079 		break;
   5080 	}
   5081 	DPRINTF(("mixer_ioctl(%lu,'%c',%lu) result %d\n",
   5082 		 IOCPARM_LEN(cmd), (char)IOCGROUP(cmd), cmd&0xff, error));
   5083 	return error;
   5084 }
   5085 #endif /* NAUDIO > 0 */
   5086 
   5087 #include "midi.h"
   5088 
   5089 #if NAUDIO == 0 && (NMIDI > 0 || NMIDIBUS > 0)
   5090 #include <sys/param.h>
   5091 #include <sys/systm.h>
   5092 #include <sys/device.h>
   5093 #include <sys/audioio.h>
   5094 #include <dev/audio_if.h>
   5095 #endif
   5096 
   5097 #if NAUDIO > 0 || (NMIDI > 0 || NMIDIBUS > 0)
   5098 int
   5099 audioprint(void *aux, const char *pnp)
   5100 {
   5101 	struct audio_attach_args *arg;
   5102 	const char *type;
   5103 
   5104 	if (pnp != NULL) {
   5105 		arg = aux;
   5106 		switch (arg->type) {
   5107 		case AUDIODEV_TYPE_AUDIO:
   5108 			type = "audio";
   5109 			break;
   5110 		case AUDIODEV_TYPE_MIDI:
   5111 			type = "midi";
   5112 			break;
   5113 		case AUDIODEV_TYPE_OPL:
   5114 			type = "opl";
   5115 			break;
   5116 		case AUDIODEV_TYPE_MPU:
   5117 			type = "mpu";
   5118 			break;
   5119 		default:
   5120 			panic("audioprint: unknown type %d", arg->type);
   5121 		}
   5122 		aprint_normal("%s at %s", type, pnp);
   5123 	}
   5124 	return UNCONF;
   5125 }
   5126 
   5127 #endif /* NAUDIO > 0 || (NMIDI > 0 || NMIDIBUS > 0) */
   5128 
   5129 #if NAUDIO > 0
   5130 device_t
   5131 audio_get_device(struct audio_softc *sc)
   5132 {
   5133 	return sc->sc_dev;
   5134 }
   5135 #endif
   5136 
   5137 #if NAUDIO > 0
   5138 static void
   5139 audio_mixer_capture(struct audio_softc *sc)
   5140 {
   5141 	mixer_devinfo_t mi;
   5142 	mixer_ctrl_t *mc;
   5143 
   5144 	KASSERT(mutex_owned(sc->sc_lock));
   5145 
   5146 	for (mi.index = 0;; mi.index++) {
   5147 		if (audio_query_devinfo(sc, &mi) != 0)
   5148 			break;
   5149 		KASSERT(mi.index < sc->sc_nmixer_states);
   5150 		if (mi.type == AUDIO_MIXER_CLASS)
   5151 			continue;
   5152 		mc = &sc->sc_mixer_state[mi.index];
   5153 		mc->dev = mi.index;
   5154 		mc->type = mi.type;
   5155 		mc->un.value.num_channels = mi.un.v.num_channels;
   5156 		(void)audio_get_port(sc, mc);
   5157 	}
   5158 
   5159 	return;
   5160 }
   5161 
   5162 static void
   5163 audio_mixer_restore(struct audio_softc *sc)
   5164 {
   5165 	mixer_devinfo_t mi;
   5166 	mixer_ctrl_t *mc;
   5167 
   5168 	KASSERT(mutex_owned(sc->sc_lock));
   5169 
   5170 	for (mi.index = 0; ; mi.index++) {
   5171 		if (audio_query_devinfo(sc, &mi) != 0)
   5172 			break;
   5173 		if (mi.type == AUDIO_MIXER_CLASS)
   5174 			continue;
   5175 		mc = &sc->sc_mixer_state[mi.index];
   5176 		(void)audio_set_port(sc, mc);
   5177 	}
   5178 	if (sc->hw_if->commit_settings)
   5179 		sc->hw_if->commit_settings(sc->hw_hdl);
   5180 
   5181 	return;
   5182 }
   5183 
   5184 #ifdef AUDIO_PM_IDLE
   5185 static void
   5186 audio_idle(void *arg)
   5187 {
   5188 	device_t dv = arg;
   5189 	struct audio_softc *sc = device_private(dv);
   5190 
   5191 #ifdef PNP_DEBUG
   5192 	extern int pnp_debug_idle;
   5193 	if (pnp_debug_idle)
   5194 		printf("%s: idle handler called\n", device_xname(dv));
   5195 #endif
   5196 
   5197 	sc->sc_idle = true;
   5198 
   5199 	/* XXX joerg Make pmf_device_suspend handle children? */
   5200 	if (!pmf_device_suspend(dv, PMF_Q_SELF))
   5201 		return;
   5202 
   5203 	if (!pmf_device_suspend(sc->sc_dev, PMF_Q_SELF))
   5204 		pmf_device_resume(dv, PMF_Q_SELF);
   5205 }
   5206 
   5207 static void
   5208 audio_activity(device_t dv, devactive_t type)
   5209 {
   5210 	struct audio_softc *sc = device_private(dv);
   5211 
   5212 	if (type != DVA_SYSTEM)
   5213 		return;
   5214 
   5215 	callout_schedule(&sc->sc_idle_counter, audio_idle_timeout * hz);
   5216 
   5217 	sc->sc_idle = false;
   5218 	if (!device_is_active(dv)) {
   5219 		/* XXX joerg How to deal with a failing resume... */
   5220 		pmf_device_resume(sc->sc_dev, PMF_Q_SELF);
   5221 		pmf_device_resume(dv, PMF_Q_SELF);
   5222 	}
   5223 }
   5224 #endif
   5225 
   5226 static bool
   5227 audio_suspend(device_t dv, const pmf_qual_t *qual)
   5228 {
   5229 	struct audio_softc *sc = device_private(dv);
   5230 	struct audio_chan *chan;
   5231 	const struct audio_hw_if *hwp = sc->hw_if;
   5232 	struct virtual_channel *vc;
   5233 	bool pbus, rbus;
   5234 
   5235 	pbus = rbus = false;
   5236 	mutex_enter(sc->sc_lock);
   5237 	audio_mixer_capture(sc);
   5238 	SIMPLEQ_FOREACH(chan, &sc->sc_audiochan, entries) {
   5239 		if (chan == SIMPLEQ_FIRST(&sc->sc_audiochan) ||
   5240 			chan->chan == MIXER_INUSE)
   5241 			continue;
   5242 
   5243 		vc = chan->vc;
   5244 		if (vc->sc_pbus && !pbus)
   5245 			pbus = true;
   5246 		if (vc->sc_rbus && !rbus)
   5247 			rbus = true;
   5248 	}
   5249 	mutex_enter(sc->sc_intr_lock);
   5250 	if (pbus == true)
   5251 		hwp->halt_output(sc->hw_hdl);
   5252 	if (rbus == true)
   5253 		hwp->halt_input(sc->hw_hdl);
   5254 	mutex_exit(sc->sc_intr_lock);
   5255 #ifdef AUDIO_PM_IDLE
   5256 	callout_halt(&sc->sc_idle_counter, sc->sc_lock);
   5257 #endif
   5258 	mutex_exit(sc->sc_lock);
   5259 
   5260 	return true;
   5261 }
   5262 
   5263 static bool
   5264 audio_resume(device_t dv, const pmf_qual_t *qual)
   5265 {
   5266 	struct audio_softc *sc = device_private(dv);
   5267 	struct audio_chan *chan;
   5268 	struct virtual_channel *vc;
   5269 
   5270 	mutex_enter(sc->sc_lock);
   5271 	sc->sc_trigger_started = false;
   5272 	sc->sc_rec_started = false;
   5273 
   5274 	audio_set_vchan_defaults(sc, AUMODE_PLAY | AUMODE_PLAY_ALL |
   5275 	    AUMODE_RECORD, &sc->sc_format[0]);
   5276 
   5277 	audio_mixer_restore(sc);
   5278 	SIMPLEQ_FOREACH(chan, &sc->sc_audiochan, entries) {
   5279 		if (chan == SIMPLEQ_FIRST(&sc->sc_audiochan) ||
   5280 				chan->chan == MIXER_INUSE)
   5281 			continue;
   5282 		vc = chan->vc;
   5283 
   5284 		if (vc->sc_lastinfovalid == true)
   5285 			audiosetinfo(sc, &vc->sc_lastinfo, true, vc);
   5286 		if (vc->sc_pbus == true && !vc->sc_mpr.pause)
   5287 			audiostartp(sc, vc);
   5288 		if (vc->sc_rbus == true && !vc->sc_mrr.pause)
   5289 			audiostartr(sc, vc);
   5290 	}
   5291 	mutex_exit(sc->sc_lock);
   5292 
   5293 	return true;
   5294 }
   5295 
   5296 static void
   5297 audio_volume_down(device_t dv)
   5298 {
   5299 	struct audio_softc *sc = device_private(dv);
   5300 	mixer_devinfo_t mi;
   5301 	int newgain;
   5302 	u_int gain;
   5303 	u_char balance;
   5304 
   5305 	mutex_enter(sc->sc_lock);
   5306 	if (sc->sc_outports.index == -1 && sc->sc_outports.master != -1) {
   5307 		mi.index = sc->sc_outports.master;
   5308 		mi.un.v.delta = 0;
   5309 		if (audio_query_devinfo(sc, &mi) == 0) {
   5310 			au_get_gain(sc, &sc->sc_outports, &gain, &balance);
   5311 			newgain = gain - mi.un.v.delta;
   5312 			if (newgain < AUDIO_MIN_GAIN)
   5313 				newgain = AUDIO_MIN_GAIN;
   5314 			au_set_gain(sc, &sc->sc_outports, newgain, balance);
   5315 		}
   5316 	}
   5317 	mutex_exit(sc->sc_lock);
   5318 }
   5319 
   5320 static void
   5321 audio_volume_up(device_t dv)
   5322 {
   5323 	struct audio_softc *sc = device_private(dv);
   5324 	mixer_devinfo_t mi;
   5325 	u_int gain, newgain;
   5326 	u_char balance;
   5327 
   5328 	mutex_enter(sc->sc_lock);
   5329 	if (sc->sc_outports.index == -1 && sc->sc_outports.master != -1) {
   5330 		mi.index = sc->sc_outports.master;
   5331 		mi.un.v.delta = 0;
   5332 		if (audio_query_devinfo(sc, &mi) == 0) {
   5333 			au_get_gain(sc, &sc->sc_outports, &gain, &balance);
   5334 			newgain = gain + mi.un.v.delta;
   5335 			if (newgain > AUDIO_MAX_GAIN)
   5336 				newgain = AUDIO_MAX_GAIN;
   5337 			au_set_gain(sc, &sc->sc_outports, newgain, balance);
   5338 		}
   5339 	}
   5340 	mutex_exit(sc->sc_lock);
   5341 }
   5342 
   5343 static void
   5344 audio_volume_toggle(device_t dv)
   5345 {
   5346 	struct audio_softc *sc = device_private(dv);
   5347 	u_int gain, newgain;
   5348 	u_char balance;
   5349 
   5350 	mutex_enter(sc->sc_lock);
   5351 	au_get_gain(sc, &sc->sc_outports, &gain, &balance);
   5352 	if (gain != 0) {
   5353 		sc->sc_lastgain = gain;
   5354 		newgain = 0;
   5355 	} else
   5356 		newgain = sc->sc_lastgain;
   5357 	au_set_gain(sc, &sc->sc_outports, newgain, balance);
   5358 	mutex_exit(sc->sc_lock);
   5359 }
   5360 
   5361 static int
   5362 audio_get_props(struct audio_softc *sc)
   5363 {
   5364 	const struct audio_hw_if *hw;
   5365 	int props;
   5366 
   5367 	KASSERT(mutex_owned(sc->sc_lock));
   5368 
   5369 	hw = sc->hw_if;
   5370 	props = hw->get_props(sc->hw_hdl);
   5371 
   5372 	/*
   5373 	 * if neither playback nor capture properties are reported,
   5374 	 * assume both are supported by the device driver
   5375 	 */
   5376 	if ((props & (AUDIO_PROP_PLAYBACK|AUDIO_PROP_CAPTURE)) == 0)
   5377 		props |= (AUDIO_PROP_PLAYBACK | AUDIO_PROP_CAPTURE);
   5378 
   5379 	return props;
   5380 }
   5381 
   5382 static bool
   5383 audio_can_playback(struct audio_softc *sc)
   5384 {
   5385 	return audio_get_props(sc) & AUDIO_PROP_PLAYBACK ? true : false;
   5386 }
   5387 
   5388 static bool
   5389 audio_can_capture(struct audio_softc *sc)
   5390 {
   5391 	return audio_get_props(sc) & AUDIO_PROP_CAPTURE ? true : false;
   5392 }
   5393 
   5394 void
   5395 mix_read(void *arg)
   5396 {
   5397 	struct audio_softc *sc = arg;
   5398 	struct audio_chan *chan;
   5399 	struct virtual_channel *vc;
   5400 	stream_filter_t *filter;
   5401 	stream_fetcher_t *fetcher;
   5402 	stream_fetcher_t null_fetcher;
   5403 	int cc, cc1, blksize, error;
   5404 	uint8_t *inp;
   5405 
   5406 	chan = SIMPLEQ_FIRST(&sc->sc_audiochan);
   5407 	vc = chan->vc;
   5408 	blksize = vc->sc_mrr.blksize;
   5409 	cc = blksize;
   5410 
   5411 	if (sc->hw_if->trigger_input && sc->sc_rec_started == false) {
   5412 		DPRINTF(("%s: call trigger_input\n", __func__));
   5413 		error = sc->hw_if->trigger_input(sc->hw_hdl, vc->sc_mrr.s.start,
   5414 		    vc->sc_mrr.s.end, blksize,
   5415 		    audio_rint, (void *)sc, &vc->sc_mrr.s.param);
   5416 	} else if (sc->hw_if->start_input) {
   5417 		DPRINTF(("%s: call start_input\n", __func__));
   5418 		error = sc->hw_if->start_input(sc->hw_hdl,
   5419 		    vc->sc_mrr.s.inp, blksize,
   5420 		    audio_rint, (void *)sc);
   5421 		if (error) {
   5422 			/* XXX does this really help? */
   5423 			DPRINTF(("audio_upmix restart failed: %d\n", error));
   5424 			audio_clear(sc, 0);
   5425 		}
   5426 	}
   5427 	sc->sc_rec_started = true;
   5428 
   5429 	inp = vc->sc_mrr.s.inp;
   5430 	vc->sc_mrr.s.inp = audio_stream_add_inp(&vc->sc_mrr.s, inp, cc);
   5431 
   5432 	if (vc->sc_nrfilters > 0) {
   5433 		cc = vc->sc_rustream->end - vc->sc_rustream->start;
   5434 		null_fetcher.fetch_to = null_fetcher_fetch_to;
   5435 		filter = vc->sc_rfilters[0];
   5436 		filter->set_fetcher(filter, &null_fetcher);
   5437 		fetcher = &vc->sc_rfilters[vc->sc_nrfilters - 1]->base;
   5438 		fetcher->fetch_to(sc, fetcher, vc->sc_rustream, cc);
   5439 	}
   5440 
   5441 	blksize = audio_stream_get_used(vc->sc_rustream);
   5442 	cc1 = blksize;
   5443 	if (vc->sc_rustream->outp + blksize > vc->sc_rustream->end)
   5444 		cc1 = vc->sc_rustream->end - vc->sc_rustream->outp;
   5445 	memcpy(sc->sc_rr.s.start, vc->sc_rustream->outp, cc1);
   5446 	if (cc1 < blksize) {
   5447 		memcpy(sc->sc_rr.s.start + cc1, vc->sc_rustream->start,
   5448 		    blksize - cc1);
   5449 	}
   5450 	sc->sc_rr.s.inp = audio_stream_add_inp(&sc->sc_rr.s, sc->sc_rr.s.inp,
   5451 	    blksize);
   5452 	vc->sc_rustream->outp = audio_stream_add_outp(vc->sc_rustream,
   5453 	    vc->sc_rustream->outp, blksize);
   5454 }
   5455 
   5456 void
   5457 mix_write(void *arg)
   5458 {
   5459 	struct audio_softc *sc = arg;
   5460 	struct audio_chan *chan;
   5461 	struct virtual_channel *vc;
   5462 	stream_filter_t *filter;
   5463 	stream_fetcher_t *fetcher;
   5464 	stream_fetcher_t null_fetcher;
   5465 	int cc, cc1, cc2, blksize, error, used;
   5466 	uint8_t *inp, *orig, *tocopy;
   5467 
   5468 	chan = SIMPLEQ_FIRST(&sc->sc_audiochan);
   5469 	vc = chan->vc;
   5470 	blksize = vc->sc_mpr.blksize;
   5471 	cc = blksize;
   5472 	error = 0;
   5473 
   5474 	tocopy = vc->sc_pustream->inp;
   5475 	orig = __UNCONST(sc->sc_pr.s.outp);
   5476 	used = blksize;
   5477 	while (used > 0) {
   5478 		cc = used;
   5479 		cc1 = vc->sc_pustream->end - tocopy;
   5480 		cc2 = sc->sc_pr.s.end - orig;
   5481 		if (cc2 < cc1)
   5482 			cc = cc2;
   5483 		else
   5484 			cc = cc1;
   5485 		if (cc > used)
   5486 			cc = used;
   5487 		memcpy(tocopy, orig, cc);
   5488 		orig += cc;
   5489 		tocopy += cc;
   5490 
   5491 		if (tocopy >= vc->sc_pustream->end)
   5492 			tocopy = vc->sc_pustream->start;
   5493 		if (orig >= sc->sc_pr.s.end)
   5494 			orig = sc->sc_pr.s.start;
   5495 
   5496 		used -= cc;
   5497  	}
   5498 
   5499 	inp = vc->sc_pustream->inp;
   5500 	vc->sc_pustream->inp = audio_stream_add_inp(vc->sc_pustream,
   5501 	    inp, blksize);
   5502 
   5503 	cc = blksize;
   5504 	cc2 = sc->sc_pr.s.end - sc->sc_pr.s.inp;
   5505 	if (cc2 < cc) {
   5506 		memset(sc->sc_pr.s.inp, 0, cc2);
   5507 		cc -= cc2;
   5508 		memset(sc->sc_pr.s.start, 0, cc);
   5509 	} else
   5510 		memset(sc->sc_pr.s.inp, 0, cc);
   5511 
   5512 	sc->sc_pr.s.outp = audio_stream_add_outp(&sc->sc_pr.s,
   5513 	    sc->sc_pr.s.outp, blksize);
   5514 
   5515 	if (vc->sc_npfilters > 0) {
   5516 		null_fetcher.fetch_to = null_fetcher_fetch_to;
   5517 		filter = vc->sc_pfilters[0];
   5518 		filter->set_fetcher(filter, &null_fetcher);
   5519 		fetcher = &vc->sc_pfilters[vc->sc_npfilters - 1]->base;
   5520 		fetcher->fetch_to(sc, fetcher, &vc->sc_mpr.s, blksize);
   5521  	}
   5522 
   5523 	if (sc->hw_if->trigger_output && sc->sc_trigger_started == false) {
   5524 		DPRINTF(("%s: call trigger_output\n", __func__));
   5525 		error = sc->hw_if->trigger_output(sc->hw_hdl,
   5526 		    vc->sc_mpr.s.start, vc->sc_mpr.s.end, blksize,
   5527 		    audio_pint, (void *)sc, &vc->sc_mpr.s.param);
   5528 	} else if (sc->hw_if->start_output) {
   5529 		DPRINTF(("%s: call start_output\n", __func__));
   5530 		error = sc->hw_if->start_output(sc->hw_hdl,
   5531 		    __UNCONST(vc->sc_mpr.s.outp), blksize,
   5532 		    audio_pint, (void *)sc);
   5533 	}
   5534 	sc->sc_trigger_started = true;
   5535 
   5536 	if (error) {
   5537 		/* XXX does this really help? */
   5538 		DPRINTF(("audio_mix restart failed: %d\n", error));
   5539 		audio_clear(sc, 0);
   5540 		sc->sc_trigger_started = false;
   5541 	}
   5542 }
   5543 
   5544 #define DEF_MIX_FUNC(name, type)					\
   5545 	static void						\
   5546 	mix_func##name(struct audio_softc *sc, struct audio_ringbuffer *cb, \
   5547 		  struct virtual_channel *vc)				\
   5548 	{								\
   5549 		int blksize, cc, cc1, cc2, m, resid;			\
   5550 		type *orig, *tomix;					\
   5551 									\
   5552 		blksize = sc->sc_pr.blksize;				\
   5553 		resid = blksize;					\
   5554 									\
   5555 		tomix = __UNCONST(cb->s.outp);				\
   5556 		orig = (type *)(sc->sc_pr.s.inp);			\
   5557 									\
   5558 		while (resid > 0) {					\
   5559 			cc = resid;					\
   5560 			cc1 = sc->sc_pr.s.end - (uint8_t *)orig;	\
   5561 			cc2 = cb->s.end - (uint8_t *)tomix;		\
   5562 			if (cc > cc1)					\
   5563 				cc = cc1;				\
   5564 			if (cc > cc2)					\
   5565 				cc = cc2;				\
   5566 									\
   5567 			for (m = 0; m < (cc / (name / 8)); m++) {	\
   5568 				orig[m] += (type)((int32_t)(tomix[m] *	\
   5569 				    (vc->sc_swvol + 1)) / (sc->sc_opens * \
   5570 				    256));				\
   5571 			}						\
   5572 									\
   5573 			if (&orig[m] >= (type *)sc->sc_pr.s.end)	\
   5574 				orig = (type *)sc->sc_pr.s.start;	\
   5575 			if (&tomix[m] >= (type *)cb->s.end)		\
   5576 				tomix = (type *)cb->s.start;		\
   5577 									\
   5578 			resid -= cc;					\
   5579 		}							\
   5580 	}								\
   5581 
   5582 DEF_MIX_FUNC(8, int8_t);
   5583 DEF_MIX_FUNC(16, int16_t);
   5584 DEF_MIX_FUNC(32, int32_t);
   5585 
   5586 void
   5587 mix_func(struct audio_softc *sc, struct audio_ringbuffer *cb,
   5588 	 struct virtual_channel *vc)
   5589 {
   5590 	switch (sc->sc_precision) {
   5591 	case 8:
   5592 		mix_func8(sc, cb, vc);
   5593 		break;
   5594 	case 16:
   5595 		mix_func16(sc, cb, vc);
   5596 		break;
   5597 	case 24:
   5598 	case 32:
   5599 		mix_func32(sc, cb, vc);
   5600 		break;
   5601 	default:
   5602 		break;
   5603 	}
   5604 }
   5605 
   5606 #define DEF_SATURATE_FUNC(name, type, max_type, min_type)		\
   5607 	static void						\
   5608 	saturate_func##name(struct audio_softc *sc)			\
   5609 	{								\
   5610 		int blksize, m, i, resid;				\
   5611 		type *orig;						\
   5612 									\
   5613 		blksize = sc->sc_pr.blksize;				\
   5614 		resid = blksize;					\
   5615 		if (sc->sc_trigger_started == false)			\
   5616 			resid *= 2;					\
   5617 									\
   5618 		orig = (type *)(sc->sc_pr.s.inp);			\
   5619 									\
   5620 		for (m = 0; m < (resid / (name / 8));m++) {		\
   5621 			i = 0;						\
   5622 			if (&orig[m] >= (type *)sc->sc_pr.s.end) {	\
   5623 				orig = (type *)sc->sc_pr.s.start;	\
   5624 				resid -= m;				\
   5625 				m = 0;					\
   5626 			}						\
   5627 			if (orig[m] != 0) {				\
   5628 				if (orig[m] > 0)			\
   5629 					i = max_type / orig[m];		\
   5630 				else					\
   5631 					i = min_type / orig[m];	 	\
   5632 			}						\
   5633 			if (i > sc->sc_opens)				\
   5634 				i = sc->sc_opens;			\
   5635 			orig[m] *= i;					\
   5636 		}							\
   5637 	}								\
   5638 
   5639 
   5640 DEF_SATURATE_FUNC(8, int8_t, INT8_MAX, INT8_MIN);
   5641 DEF_SATURATE_FUNC(16, int16_t, INT16_MAX, INT16_MIN);
   5642 DEF_SATURATE_FUNC(32, int32_t, INT32_MAX, INT32_MIN);
   5643 
   5644 void
   5645 saturate_func(struct audio_softc *sc)
   5646 {
   5647 	switch (sc->sc_precision) {
   5648 	case 8:
   5649 		saturate_func8(sc);
   5650 		break;
   5651 	case 16:
   5652 		saturate_func16(sc);
   5653 		break;
   5654 	case 24:
   5655 	case 32:
   5656 		saturate_func32(sc);
   5657 		break;
   5658 	default:
   5659 		break;
   5660 	}
   5661 }
   5662 
   5663 #define DEF_RECSWVOL_FUNC(name, type, bigger_type)			\
   5664 	static void						\
   5665 	recswvol_func##name(struct audio_softc *sc,			\
   5666 	    struct audio_ringbuffer *cb, size_t blksize,		\
   5667 	    struct virtual_channel *vc)					\
   5668 	{								\
   5669 		int cc, cc1, m, resid;					\
   5670 		type *orig;						\
   5671 									\
   5672 		orig = (type *) cb->s.inp;				\
   5673 		resid = blksize;					\
   5674 									\
   5675 		while (resid > 0) {					\
   5676 			cc = resid;					\
   5677 			cc1 = cb->s.end - (uint8_t *)orig;		\
   5678 			if (cc > cc1)					\
   5679 				cc = cc1;				\
   5680 									\
   5681 			for (m = 0; m < (cc / (name / 8)); m++) {	\
   5682 				orig[m] = (bigger_type)(orig[m] *	\
   5683 				    (bigger_type)(vc->sc_recswvol) / 256);\
   5684 			}						\
   5685 			orig = (type *) cb->s.start;			\
   5686 									\
   5687 			resid -= cc;					\
   5688 		}							\
   5689 	}								\
   5690 
   5691 DEF_RECSWVOL_FUNC(8, int8_t, int16_t);
   5692 DEF_RECSWVOL_FUNC(16, int16_t, int32_t);
   5693 DEF_RECSWVOL_FUNC(32, int32_t, int64_t);
   5694 
   5695 void
   5696 recswvol_func(struct audio_softc *sc, struct audio_ringbuffer *cb,
   5697     size_t blksize, struct virtual_channel *vc)
   5698 {
   5699 	switch (sc->sc_precision) {
   5700 	case 8:
   5701 		recswvol_func8(sc, cb, blksize, vc);
   5702 		break;
   5703 	case 16:
   5704 		recswvol_func16(sc, cb, blksize, vc);
   5705 		break;
   5706 	case 24:
   5707 	case 32:
   5708 		recswvol_func32(sc, cb, blksize, vc);
   5709 		break;
   5710 	default:
   5711 		break;
   5712 	}
   5713 }
   5714 
   5715 static uint8_t *
   5716 find_vchan_vol(struct audio_softc *sc, int d)
   5717 {
   5718 	struct audio_chan *chan;
   5719 	size_t j, n = (size_t)d / 2;
   5720 
   5721 	j = 0;
   5722 	SIMPLEQ_FOREACH(chan, &sc->sc_audiochan, entries) {
   5723 		if (chan == SIMPLEQ_FIRST(&sc->sc_audiochan) ||
   5724 		    chan->chan == MIXER_INUSE)
   5725 			continue;
   5726 		if (j == n)
   5727 			break;
   5728 		j++;
  &nb