Home | History | Annotate | Line # | Download | only in usb
uaudio.c revision 1.138
      1 /*	$NetBSD: uaudio.c,v 1.138 2013/09/15 15:04:47 martin Exp $	*/
      2 
      3 /*
      4  * Copyright (c) 1999, 2012 The NetBSD Foundation, Inc.
      5  * All rights reserved.
      6  *
      7  * This code is derived from software contributed to The NetBSD Foundation
      8  * by Lennart Augustsson (lennart (at) augustsson.net) at
      9  * Carlstedt Research & Technology, and Matthew R. Green (mrg (at) eterna.com.au).
     10  *
     11  * Redistribution and use in source and binary forms, with or without
     12  * modification, are permitted provided that the following conditions
     13  * are met:
     14  * 1. Redistributions of source code must retain the above copyright
     15  *    notice, this list of conditions and the following disclaimer.
     16  * 2. Redistributions in binary form must reproduce the above copyright
     17  *    notice, this list of conditions and the following disclaimer in the
     18  *    documentation and/or other materials provided with the distribution.
     19  *
     20  * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
     21  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
     22  * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
     23  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
     24  * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
     25  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
     26  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
     27  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
     28  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
     29  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
     30  * POSSIBILITY OF SUCH DAMAGE.
     31  */
     32 
     33 /*
     34  * USB audio specs: http://www.usb.org/developers/devclass_docs/audio10.pdf
     35  *                  http://www.usb.org/developers/devclass_docs/frmts10.pdf
     36  *                  http://www.usb.org/developers/devclass_docs/termt10.pdf
     37  */
     38 
     39 #include <sys/cdefs.h>
     40 __KERNEL_RCSID(0, "$NetBSD: uaudio.c,v 1.138 2013/09/15 15:04:47 martin Exp $");
     41 
     42 #include <sys/param.h>
     43 #include <sys/systm.h>
     44 #include <sys/kernel.h>
     45 #include <sys/malloc.h>
     46 #include <sys/device.h>
     47 #include <sys/ioctl.h>
     48 #include <sys/file.h>
     49 #include <sys/reboot.h>		/* for bootverbose */
     50 #include <sys/select.h>
     51 #include <sys/proc.h>
     52 #include <sys/vnode.h>
     53 #include <sys/poll.h>
     54 #include <sys/module.h>
     55 #include <sys/bus.h>
     56 #include <sys/cpu.h>
     57 #include <sys/atomic.h>
     58 
     59 #include <sys/audioio.h>
     60 #include <dev/audio_if.h>
     61 #include <dev/audiovar.h>
     62 #include <dev/mulaw.h>
     63 #include <dev/auconv.h>
     64 
     65 #include <dev/usb/usb.h>
     66 #include <dev/usb/usbdi.h>
     67 #include <dev/usb/usbdivar.h>
     68 #include <dev/usb/usbdi_util.h>
     69 #include <dev/usb/usb_quirks.h>
     70 
     71 #include <dev/usb/usbdevs.h>
     72 
     73 #include <dev/usb/uaudioreg.h>
     74 
     75 /* #define UAUDIO_DEBUG */
     76 /* #define UAUDIO_MULTIPLE_ENDPOINTS */
     77 #ifdef UAUDIO_DEBUG
     78 #define DPRINTF(x,y...)		do { \
     79 		if (uaudiodebug) { \
     80 			struct lwp *l = curlwp; \
     81 			printf("%s[%d:%d]: "x, __func__, l->l_proc->p_pid, l->l_lid, y); \
     82 		} \
     83 	} while (0)
     84 #define DPRINTFN_CLEAN(n,x...)	do { \
     85 		if (uaudiodebug > (n)) \
     86 			printf(x); \
     87 	} while (0)
     88 #define DPRINTFN(n,x,y...)	do { \
     89 		if (uaudiodebug > (n)) { \
     90 			struct lwp *l = curlwp; \
     91 			printf("%s[%d:%d]: "x, __func__, l->l_proc->p_pid, l->l_lid, y); \
     92 		} \
     93 	} while (0)
     94 int	uaudiodebug = 0;
     95 #else
     96 #define DPRINTF(x,y...)
     97 #define DPRINTFN_CLEAN(n,x...)
     98 #define DPRINTFN(n,x,y...)
     99 #endif
    100 
    101 #define UAUDIO_NCHANBUFS 6	/* number of outstanding request */
    102 #define UAUDIO_NFRAMES   10	/* ms of sound in each request */
    103 
    104 
    105 #define MIX_MAX_CHAN 8
    106 struct mixerctl {
    107 	uint16_t	wValue[MIX_MAX_CHAN]; /* using nchan */
    108 	uint16_t	wIndex;
    109 	uint8_t		nchan;
    110 	uint8_t		type;
    111 #define MIX_ON_OFF	1
    112 #define MIX_SIGNED_16	2
    113 #define MIX_UNSIGNED_16	3
    114 #define MIX_SIGNED_8	4
    115 #define MIX_SELECTOR	5
    116 #define MIX_SIZE(n) ((n) == MIX_SIGNED_16 || (n) == MIX_UNSIGNED_16 ? 2 : 1)
    117 #define MIX_UNSIGNED(n) ((n) == MIX_UNSIGNED_16)
    118 	int		minval, maxval;
    119 	u_int		delta;
    120 	u_int		mul;
    121 	uint8_t		class;
    122 	char		ctlname[MAX_AUDIO_DEV_LEN];
    123 	const char	*ctlunit;
    124 };
    125 #define MAKE(h,l) (((h) << 8) | (l))
    126 
    127 struct as_info {
    128 	uint8_t		alt;
    129 	uint8_t		encoding;
    130 	uint8_t		attributes; /* Copy of bmAttributes of
    131 				     * usb_audio_streaming_endpoint_descriptor
    132 				     */
    133 	usbd_interface_handle	ifaceh;
    134 	const usb_interface_descriptor_t *idesc;
    135 	const usb_endpoint_descriptor_audio_t *edesc;
    136 	const usb_endpoint_descriptor_audio_t *edesc1;
    137 	const struct usb_audio_streaming_type1_descriptor *asf1desc;
    138 	struct audio_format *aformat;
    139 	int		sc_busy;	/* currently used */
    140 };
    141 
    142 struct chan {
    143 	void	(*intr)(void *);	/* DMA completion intr handler */
    144 	void	*arg;		/* arg for intr() */
    145 	usbd_pipe_handle pipe;
    146 	usbd_pipe_handle sync_pipe;
    147 
    148 	u_int	sample_size;
    149 	u_int	sample_rate;
    150 	u_int	bytes_per_frame;
    151 	u_int	fraction;	/* fraction/1000 is the extra samples/frame */
    152 	u_int	residue;	/* accumulates the fractional samples */
    153 
    154 	u_char	*start;		/* upper layer buffer start */
    155 	u_char	*end;		/* upper layer buffer end */
    156 	u_char	*cur;		/* current position in upper layer buffer */
    157 	int	blksize;	/* chunk size to report up */
    158 	int	transferred;	/* transferred bytes not reported up */
    159 
    160 	int	altidx;		/* currently used altidx */
    161 
    162 	int	curchanbuf;
    163 	struct chanbuf {
    164 		struct chan	*chan;
    165 		usbd_xfer_handle xfer;
    166 		u_char		*buffer;
    167 		uint16_t	sizes[UAUDIO_NFRAMES];
    168 		uint16_t	offsets[UAUDIO_NFRAMES];
    169 		uint16_t	size;
    170 	} chanbufs[UAUDIO_NCHANBUFS];
    171 
    172 	struct uaudio_softc *sc; /* our softc */
    173 };
    174 
    175 /*
    176  * XXX Locking notes:
    177  *
    178  *    The MI USB audio subsystem is not MP-SAFE.  Our strategy here
    179  *    is to ensure we have the kernel lock held when calling into
    180  *    usbd, and, generally, to have dropped the sc_intr_lock during
    181  *    these sections as well since the usb code will sleep.
    182  */
    183 struct uaudio_softc {
    184 	device_t	sc_dev;		/* base device */
    185 	kmutex_t	sc_lock;
    186 	kmutex_t	sc_intr_lock;
    187 	usbd_device_handle sc_udev;	/* USB device */
    188 	int		sc_ac_iface;	/* Audio Control interface */
    189 	usbd_interface_handle	sc_ac_ifaceh;
    190 	struct chan	sc_playchan;	/* play channel */
    191 	struct chan	sc_recchan;	/* record channel */
    192 	int		sc_nullalt;
    193 	int		sc_audio_rev;
    194 	struct as_info	*sc_alts;	/* alternate settings */
    195 	int		sc_nalts;	/* # of alternate settings */
    196 	int		sc_altflags;
    197 #define HAS_8		0x01
    198 #define HAS_16		0x02
    199 #define HAS_8U		0x04
    200 #define HAS_ALAW	0x08
    201 #define HAS_MULAW	0x10
    202 #define UA_NOFRAC	0x20		/* don't do sample rate adjustment */
    203 #define HAS_24		0x40
    204 	int		sc_mode;	/* play/record capability */
    205 	struct mixerctl *sc_ctls;	/* mixer controls */
    206 	int		sc_nctls;	/* # of mixer controls */
    207 	device_t	sc_audiodev;
    208 	struct audio_format *sc_formats;
    209 	int		sc_nformats;
    210 	struct audio_encoding_set *sc_encodings;
    211 	u_int		sc_channel_config;
    212 	char		sc_dying;
    213 	struct audio_device sc_adev;
    214 };
    215 
    216 struct terminal_list {
    217 	int size;
    218 	uint16_t terminals[1];
    219 };
    220 #define TERMINAL_LIST_SIZE(N)	(offsetof(struct terminal_list, terminals) \
    221 				+ sizeof(uint16_t) * (N))
    222 
    223 struct io_terminal {
    224 	union {
    225 		const uaudio_cs_descriptor_t *desc;
    226 		const struct usb_audio_input_terminal *it;
    227 		const struct usb_audio_output_terminal *ot;
    228 		const struct usb_audio_mixer_unit *mu;
    229 		const struct usb_audio_selector_unit *su;
    230 		const struct usb_audio_feature_unit *fu;
    231 		const struct usb_audio_processing_unit *pu;
    232 		const struct usb_audio_extension_unit *eu;
    233 	} d;
    234 	int inputs_size;
    235 	struct terminal_list **inputs; /* list of source input terminals */
    236 	struct terminal_list *output; /* list of destination output terminals */
    237 	int direct;		/* directly connected to an output terminal */
    238 };
    239 
    240 #define UAC_OUTPUT	0
    241 #define UAC_INPUT	1
    242 #define UAC_EQUAL	2
    243 #define UAC_RECORD	3
    244 #define UAC_NCLASSES	4
    245 #ifdef UAUDIO_DEBUG
    246 Static const char *uac_names[] = {
    247 	AudioCoutputs, AudioCinputs, AudioCequalization, AudioCrecord,
    248 };
    249 #endif
    250 
    251 Static usbd_status uaudio_identify_ac
    252 	(struct uaudio_softc *, const usb_config_descriptor_t *);
    253 Static usbd_status uaudio_identify_as
    254 	(struct uaudio_softc *, const usb_config_descriptor_t *);
    255 Static usbd_status uaudio_process_as
    256 	(struct uaudio_softc *, const char *, int *, int,
    257 	 const usb_interface_descriptor_t *);
    258 
    259 Static void	uaudio_add_alt(struct uaudio_softc *, const struct as_info *);
    260 
    261 Static const usb_interface_descriptor_t *uaudio_find_iface
    262 	(const char *, int, int *, int);
    263 
    264 Static void	uaudio_mixer_add_ctl(struct uaudio_softc *, struct mixerctl *);
    265 Static char	*uaudio_id_name
    266 	(struct uaudio_softc *, const struct io_terminal *, int);
    267 #ifdef UAUDIO_DEBUG
    268 Static void	uaudio_dump_cluster(const struct usb_audio_cluster *);
    269 #endif
    270 Static struct usb_audio_cluster uaudio_get_cluster
    271 	(int, const struct io_terminal *);
    272 Static void	uaudio_add_input
    273 	(struct uaudio_softc *, const struct io_terminal *, int);
    274 Static void	uaudio_add_output
    275 	(struct uaudio_softc *, const struct io_terminal *, int);
    276 Static void	uaudio_add_mixer
    277 	(struct uaudio_softc *, const struct io_terminal *, int);
    278 Static void	uaudio_add_selector
    279 	(struct uaudio_softc *, const struct io_terminal *, int);
    280 #ifdef UAUDIO_DEBUG
    281 Static const char *uaudio_get_terminal_name(int);
    282 #endif
    283 Static int	uaudio_determine_class
    284 	(const struct io_terminal *, struct mixerctl *);
    285 Static const char *uaudio_feature_name
    286 	(const struct io_terminal *, struct mixerctl *);
    287 Static void	uaudio_add_feature
    288 	(struct uaudio_softc *, const struct io_terminal *, int);
    289 Static void	uaudio_add_processing_updown
    290 	(struct uaudio_softc *, const struct io_terminal *, int);
    291 Static void	uaudio_add_processing
    292 	(struct uaudio_softc *, const struct io_terminal *, int);
    293 Static void	uaudio_add_extension
    294 	(struct uaudio_softc *, const struct io_terminal *, int);
    295 Static struct terminal_list *uaudio_merge_terminal_list
    296 	(const struct io_terminal *);
    297 Static struct terminal_list *uaudio_io_terminaltype
    298 	(int, struct io_terminal *, int);
    299 Static usbd_status uaudio_identify
    300 	(struct uaudio_softc *, const usb_config_descriptor_t *);
    301 
    302 Static int	uaudio_signext(int, int);
    303 Static int	uaudio_value2bsd(struct mixerctl *, int);
    304 Static int	uaudio_bsd2value(struct mixerctl *, int);
    305 Static int	uaudio_get(struct uaudio_softc *, int, int, int, int, int);
    306 Static int	uaudio_ctl_get
    307 	(struct uaudio_softc *, int, struct mixerctl *, int);
    308 Static void	uaudio_set
    309 	(struct uaudio_softc *, int, int, int, int, int, int);
    310 Static void	uaudio_ctl_set
    311 	(struct uaudio_softc *, int, struct mixerctl *, int, int);
    312 
    313 Static usbd_status uaudio_set_speed(struct uaudio_softc *, int, u_int);
    314 
    315 Static usbd_status uaudio_chan_open(struct uaudio_softc *, struct chan *);
    316 Static void	uaudio_chan_close(struct uaudio_softc *, struct chan *);
    317 Static usbd_status uaudio_chan_alloc_buffers
    318 	(struct uaudio_softc *, struct chan *);
    319 Static void	uaudio_chan_free_buffers(struct uaudio_softc *, struct chan *);
    320 Static void	uaudio_chan_init
    321 	(struct chan *, int, const struct audio_params *, int);
    322 Static void	uaudio_chan_set_param(struct chan *, u_char *, u_char *, int);
    323 Static void	uaudio_chan_ptransfer(struct chan *);
    324 Static void	uaudio_chan_pintr
    325 	(usbd_xfer_handle, usbd_private_handle, usbd_status);
    326 
    327 Static void	uaudio_chan_rtransfer(struct chan *);
    328 Static void	uaudio_chan_rintr
    329 	(usbd_xfer_handle, usbd_private_handle, usbd_status);
    330 
    331 Static int	uaudio_open(void *, int);
    332 Static void	uaudio_close(void *);
    333 Static int	uaudio_drain(void *);
    334 Static int	uaudio_query_encoding(void *, struct audio_encoding *);
    335 Static int	uaudio_set_params
    336 	(void *, int, int, struct audio_params *, struct audio_params *,
    337 	 stream_filter_list_t *, stream_filter_list_t *);
    338 Static int	uaudio_round_blocksize(void *, int, int, const audio_params_t *);
    339 Static int	uaudio_trigger_output
    340 	(void *, void *, void *, int, void (*)(void *), void *,
    341 	 const audio_params_t *);
    342 Static int	uaudio_trigger_input
    343 	(void *, void *, void *, int, void (*)(void *), void *,
    344 	 const audio_params_t *);
    345 Static int	uaudio_halt_in_dma(void *);
    346 Static int	uaudio_halt_out_dma(void *);
    347 Static int	uaudio_getdev(void *, struct audio_device *);
    348 Static int	uaudio_mixer_set_port(void *, mixer_ctrl_t *);
    349 Static int	uaudio_mixer_get_port(void *, mixer_ctrl_t *);
    350 Static int	uaudio_query_devinfo(void *, mixer_devinfo_t *);
    351 Static int	uaudio_get_props(void *);
    352 Static void	uaudio_get_locks(void *, kmutex_t **, kmutex_t **);
    353 
    354 Static const struct audio_hw_if uaudio_hw_if = {
    355 	uaudio_open,
    356 	uaudio_close,
    357 	uaudio_drain,
    358 	uaudio_query_encoding,
    359 	uaudio_set_params,
    360 	uaudio_round_blocksize,
    361 	NULL,
    362 	NULL,
    363 	NULL,
    364 	NULL,
    365 	NULL,
    366 	uaudio_halt_out_dma,
    367 	uaudio_halt_in_dma,
    368 	NULL,
    369 	uaudio_getdev,
    370 	NULL,
    371 	uaudio_mixer_set_port,
    372 	uaudio_mixer_get_port,
    373 	uaudio_query_devinfo,
    374 	NULL,
    375 	NULL,
    376 	NULL,
    377 	NULL,
    378 	uaudio_get_props,
    379 	uaudio_trigger_output,
    380 	uaudio_trigger_input,
    381 	NULL,
    382 	uaudio_get_locks,
    383 };
    384 
    385 int uaudio_match(device_t, cfdata_t, void *);
    386 void uaudio_attach(device_t, device_t, void *);
    387 int uaudio_detach(device_t, int);
    388 void uaudio_childdet(device_t, device_t);
    389 int uaudio_activate(device_t, enum devact);
    390 
    391 extern struct cfdriver uaudio_cd;
    392 
    393 CFATTACH_DECL2_NEW(uaudio, sizeof(struct uaudio_softc),
    394     uaudio_match, uaudio_attach, uaudio_detach, uaudio_activate, NULL,
    395     uaudio_childdet);
    396 
    397 int
    398 uaudio_match(device_t parent, cfdata_t match, void *aux)
    399 {
    400 	struct usbif_attach_arg *uaa = aux;
    401 
    402 	/* Trigger on the control interface. */
    403 	if (uaa->class != UICLASS_AUDIO ||
    404 	    uaa->subclass != UISUBCLASS_AUDIOCONTROL ||
    405 	    (usbd_get_quirks(uaa->device)->uq_flags & UQ_BAD_AUDIO))
    406 		return UMATCH_NONE;
    407 
    408 	return UMATCH_IFACECLASS_IFACESUBCLASS;
    409 }
    410 
    411 void
    412 uaudio_attach(device_t parent, device_t self, void *aux)
    413 {
    414 	struct uaudio_softc *sc = device_private(self);
    415 	struct usbif_attach_arg *uaa = aux;
    416 	usb_interface_descriptor_t *id;
    417 	usb_config_descriptor_t *cdesc;
    418 	char *devinfop;
    419 	usbd_status err;
    420 	int i, j, found;
    421 
    422 	sc->sc_dev = self;
    423 	sc->sc_udev = uaa->device;
    424 	mutex_init(&sc->sc_lock, MUTEX_DEFAULT, IPL_NONE);
    425 	mutex_init(&sc->sc_intr_lock, MUTEX_DEFAULT, IPL_SCHED);
    426 
    427 	strlcpy(sc->sc_adev.name, "USB audio", sizeof(sc->sc_adev.name));
    428 	strlcpy(sc->sc_adev.version, "", sizeof(sc->sc_adev.version));
    429 	snprintf(sc->sc_adev.config, sizeof(sc->sc_adev.config), "usb:%08x",
    430 	    sc->sc_udev->cookie.cookie);
    431 
    432 	aprint_naive("\n");
    433 	aprint_normal("\n");
    434 
    435 	devinfop = usbd_devinfo_alloc(uaa->device, 0);
    436 	aprint_normal_dev(self, "%s\n", devinfop);
    437 	usbd_devinfo_free(devinfop);
    438 
    439 	cdesc = usbd_get_config_descriptor(sc->sc_udev);
    440 	if (cdesc == NULL) {
    441 		aprint_error_dev(self,
    442 		    "failed to get configuration descriptor\n");
    443 		return;
    444 	}
    445 
    446 	err = uaudio_identify(sc, cdesc);
    447 	if (err) {
    448 		aprint_error_dev(self,
    449 		    "audio descriptors make no sense, error=%d\n", err);
    450 		return;
    451 	}
    452 
    453 	sc->sc_ac_ifaceh = uaa->iface;
    454 	/* Pick up the AS interface. */
    455 	for (i = 0; i < uaa->nifaces; i++) {
    456 		if (uaa->ifaces[i] == NULL)
    457 			continue;
    458 		id = usbd_get_interface_descriptor(uaa->ifaces[i]);
    459 		if (id == NULL)
    460 			continue;
    461 		found = 0;
    462 		for (j = 0; j < sc->sc_nalts; j++) {
    463 			if (id->bInterfaceNumber ==
    464 			    sc->sc_alts[j].idesc->bInterfaceNumber) {
    465 				sc->sc_alts[j].ifaceh = uaa->ifaces[i];
    466 				found = 1;
    467 			}
    468 		}
    469 		if (found)
    470 			uaa->ifaces[i] = NULL;
    471 	}
    472 
    473 	for (j = 0; j < sc->sc_nalts; j++) {
    474 		if (sc->sc_alts[j].ifaceh == NULL) {
    475 			aprint_error_dev(self,
    476 			    "alt %d missing AS interface(s)\n", j);
    477 			return;
    478 		}
    479 	}
    480 
    481 	aprint_normal_dev(self, "audio rev %d.%02x\n",
    482 	       sc->sc_audio_rev >> 8, sc->sc_audio_rev & 0xff);
    483 
    484 	sc->sc_playchan.sc = sc->sc_recchan.sc = sc;
    485 	sc->sc_playchan.altidx = -1;
    486 	sc->sc_recchan.altidx = -1;
    487 
    488 	if (usbd_get_quirks(sc->sc_udev)->uq_flags & UQ_AU_NO_FRAC)
    489 		sc->sc_altflags |= UA_NOFRAC;
    490 
    491 #ifndef UAUDIO_DEBUG
    492 	if (bootverbose)
    493 #endif
    494 		aprint_normal_dev(self, "%d mixer controls\n",
    495 		    sc->sc_nctls);
    496 
    497 	usbd_add_drv_event(USB_EVENT_DRIVER_ATTACH, sc->sc_udev,
    498 			   sc->sc_dev);
    499 
    500 	DPRINTF("%s", "doing audio_attach_mi\n");
    501 	sc->sc_audiodev = audio_attach_mi(&uaudio_hw_if, sc, sc->sc_dev);
    502 
    503 	return;
    504 }
    505 
    506 int
    507 uaudio_activate(device_t self, enum devact act)
    508 {
    509 	struct uaudio_softc *sc = device_private(self);
    510 
    511 	switch (act) {
    512 	case DVACT_DEACTIVATE:
    513 		sc->sc_dying = 1;
    514 		return 0;
    515 	default:
    516 		return EOPNOTSUPP;
    517 	}
    518 }
    519 
    520 void
    521 uaudio_childdet(device_t self, device_t child)
    522 {
    523 	struct uaudio_softc *sc = device_private(self);
    524 
    525 	KASSERT(sc->sc_audiodev == child);
    526 	sc->sc_audiodev = NULL;
    527 }
    528 
    529 int
    530 uaudio_detach(device_t self, int flags)
    531 {
    532 	struct uaudio_softc *sc = device_private(self);
    533 	int rv;
    534 
    535 	rv = 0;
    536 	/* Wait for outstanding requests to complete. */
    537 	usbd_delay_ms(sc->sc_udev, UAUDIO_NCHANBUFS * UAUDIO_NFRAMES);
    538 
    539 	if (sc->sc_audiodev != NULL)
    540 		rv = config_detach(sc->sc_audiodev, flags);
    541 
    542 	usbd_add_drv_event(USB_EVENT_DRIVER_DETACH, sc->sc_udev,
    543 			   sc->sc_dev);
    544 
    545 	if (sc->sc_formats != NULL)
    546 		free(sc->sc_formats, M_USBDEV);
    547 	auconv_delete_encodings(sc->sc_encodings);
    548 
    549 	mutex_destroy(&sc->sc_lock);
    550 	mutex_destroy(&sc->sc_intr_lock);
    551 
    552 	return rv;
    553 }
    554 
    555 Static int
    556 uaudio_query_encoding(void *addr, struct audio_encoding *fp)
    557 {
    558 	struct uaudio_softc *sc;
    559 	int flags;
    560 
    561 	sc = addr;
    562 	flags = sc->sc_altflags;
    563 	if (sc->sc_dying)
    564 		return EIO;
    565 
    566 	if (sc->sc_nalts == 0 || flags == 0)
    567 		return ENXIO;
    568 
    569 	return auconv_query_encoding(sc->sc_encodings, fp);
    570 }
    571 
    572 Static const usb_interface_descriptor_t *
    573 uaudio_find_iface(const char *tbuf, int size, int *offsp, int subtype)
    574 {
    575 	const usb_interface_descriptor_t *d;
    576 
    577 	while (*offsp < size) {
    578 		d = (const void *)(tbuf + *offsp);
    579 		*offsp += d->bLength;
    580 		if (d->bDescriptorType == UDESC_INTERFACE &&
    581 		    d->bInterfaceClass == UICLASS_AUDIO &&
    582 		    d->bInterfaceSubClass == subtype)
    583 			return d;
    584 	}
    585 	return NULL;
    586 }
    587 
    588 Static void
    589 uaudio_mixer_add_ctl(struct uaudio_softc *sc, struct mixerctl *mc)
    590 {
    591 	int res;
    592 	size_t len;
    593 	struct mixerctl *nmc;
    594 
    595 	if (mc->class < UAC_NCLASSES) {
    596 		DPRINTF("adding %s.%s\n", uac_names[mc->class], mc->ctlname);
    597 	} else {
    598 		DPRINTF("adding %s\n", mc->ctlname);
    599 	}
    600 	len = sizeof(*mc) * (sc->sc_nctls + 1);
    601 	nmc = malloc(len, M_USBDEV, M_NOWAIT);
    602 	if (nmc == NULL) {
    603 		aprint_error("uaudio_mixer_add_ctl: no memory\n");
    604 		return;
    605 	}
    606 	/* Copy old data, if there was any */
    607 	if (sc->sc_nctls != 0) {
    608 		memcpy(nmc, sc->sc_ctls, sizeof(*mc) * (sc->sc_nctls));
    609 		free(sc->sc_ctls, M_USBDEV);
    610 	}
    611 	sc->sc_ctls = nmc;
    612 
    613 	mc->delta = 0;
    614 	if (mc->type == MIX_ON_OFF) {
    615 		mc->minval = 0;
    616 		mc->maxval = 1;
    617 	} else if (mc->type == MIX_SELECTOR) {
    618 		;
    619 	} else {
    620 		/* Determine min and max values. */
    621 		mc->minval = uaudio_signext(mc->type,
    622 			uaudio_get(sc, GET_MIN, UT_READ_CLASS_INTERFACE,
    623 				   mc->wValue[0], mc->wIndex,
    624 				   MIX_SIZE(mc->type)));
    625 		mc->maxval = 1 + uaudio_signext(mc->type,
    626 			uaudio_get(sc, GET_MAX, UT_READ_CLASS_INTERFACE,
    627 				   mc->wValue[0], mc->wIndex,
    628 				   MIX_SIZE(mc->type)));
    629 		mc->mul = mc->maxval - mc->minval;
    630 		if (mc->mul == 0)
    631 			mc->mul = 1;
    632 		res = uaudio_get(sc, GET_RES, UT_READ_CLASS_INTERFACE,
    633 				 mc->wValue[0], mc->wIndex,
    634 				 MIX_SIZE(mc->type));
    635 		if (res > 0)
    636 			mc->delta = (res * 255 + mc->mul/2) / mc->mul;
    637 	}
    638 
    639 	sc->sc_ctls[sc->sc_nctls++] = *mc;
    640 
    641 #ifdef UAUDIO_DEBUG
    642 	if (uaudiodebug > 2) {
    643 		int i;
    644 
    645 		DPRINTFN_CLEAN(2, "wValue=%04x", mc->wValue[0]);
    646 		for (i = 1; i < mc->nchan; i++)
    647 			DPRINTFN_CLEAN(2, ",%04x", mc->wValue[i]);
    648 		DPRINTFN_CLEAN(2, " wIndex=%04x type=%d name='%s' unit='%s' "
    649 			 "min=%d max=%d\n",
    650 			 mc->wIndex, mc->type, mc->ctlname, mc->ctlunit,
    651 			 mc->minval, mc->maxval);
    652 	}
    653 #endif
    654 }
    655 
    656 Static char *
    657 uaudio_id_name(struct uaudio_softc *sc,
    658     const struct io_terminal *iot, int id)
    659 {
    660 	static char tbuf[32];
    661 
    662 	snprintf(tbuf, sizeof(tbuf), "i%d", id);
    663 	return tbuf;
    664 }
    665 
    666 #ifdef UAUDIO_DEBUG
    667 Static void
    668 uaudio_dump_cluster(const struct usb_audio_cluster *cl)
    669 {
    670 	static const char *channel_names[16] = {
    671 		"LEFT", "RIGHT", "CENTER", "LFE",
    672 		"LEFT_SURROUND", "RIGHT_SURROUND", "LEFT_CENTER", "RIGHT_CENTER",
    673 		"SURROUND", "LEFT_SIDE", "RIGHT_SIDE", "TOP",
    674 		"RESERVED12", "RESERVED13", "RESERVED14", "RESERVED15",
    675 	};
    676 	int cc, i, first;
    677 
    678 	cc = UGETW(cl->wChannelConfig);
    679 	printf("cluster: bNrChannels=%u wChannelConfig=0x%.4x",
    680 		  cl->bNrChannels, cc);
    681 	first = TRUE;
    682 	for (i = 0; cc != 0; i++) {
    683 		if (cc & 1) {
    684 			printf("%c%s", first ? '<' : ',', channel_names[i]);
    685 			first = FALSE;
    686 		}
    687 		cc = cc >> 1;
    688 	}
    689 	printf("> iChannelNames=%u", cl->iChannelNames);
    690 }
    691 #endif
    692 
    693 Static struct usb_audio_cluster
    694 uaudio_get_cluster(int id, const struct io_terminal *iot)
    695 {
    696 	struct usb_audio_cluster r;
    697 	const uaudio_cs_descriptor_t *dp;
    698 	int i;
    699 
    700 	for (i = 0; i < 25; i++) { /* avoid infinite loops */
    701 		dp = iot[id].d.desc;
    702 		if (dp == 0)
    703 			goto bad;
    704 		switch (dp->bDescriptorSubtype) {
    705 		case UDESCSUB_AC_INPUT:
    706 			r.bNrChannels = iot[id].d.it->bNrChannels;
    707 			USETW(r.wChannelConfig, UGETW(iot[id].d.it->wChannelConfig));
    708 			r.iChannelNames = iot[id].d.it->iChannelNames;
    709 			return r;
    710 		case UDESCSUB_AC_OUTPUT:
    711 			id = iot[id].d.ot->bSourceId;
    712 			break;
    713 		case UDESCSUB_AC_MIXER:
    714 			r = *(const struct usb_audio_cluster *)
    715 				&iot[id].d.mu->baSourceId[iot[id].d.mu->bNrInPins];
    716 			return r;
    717 		case UDESCSUB_AC_SELECTOR:
    718 			/* XXX This is not really right */
    719 			id = iot[id].d.su->baSourceId[0];
    720 			break;
    721 		case UDESCSUB_AC_FEATURE:
    722 			id = iot[id].d.fu->bSourceId;
    723 			break;
    724 		case UDESCSUB_AC_PROCESSING:
    725 			r = *(const struct usb_audio_cluster *)
    726 				&iot[id].d.pu->baSourceId[iot[id].d.pu->bNrInPins];
    727 			return r;
    728 		case UDESCSUB_AC_EXTENSION:
    729 			r = *(const struct usb_audio_cluster *)
    730 				&iot[id].d.eu->baSourceId[iot[id].d.eu->bNrInPins];
    731 			return r;
    732 		default:
    733 			goto bad;
    734 		}
    735 	}
    736  bad:
    737 	aprint_error("uaudio_get_cluster: bad data\n");
    738 	memset(&r, 0, sizeof r);
    739 	return r;
    740 
    741 }
    742 
    743 Static void
    744 uaudio_add_input(struct uaudio_softc *sc, const struct io_terminal *iot, int id)
    745 {
    746 	const struct usb_audio_input_terminal *d;
    747 
    748 	d = iot[id].d.it;
    749 #ifdef UAUDIO_DEBUG
    750 	DPRINTFN(2,"bTerminalId=%d wTerminalType=0x%04x "
    751 		    "bAssocTerminal=%d bNrChannels=%d wChannelConfig=%d "
    752 		    "iChannelNames=%d iTerminal=%d\n",
    753 		    d->bTerminalId, UGETW(d->wTerminalType), d->bAssocTerminal,
    754 		    d->bNrChannels, UGETW(d->wChannelConfig),
    755 		    d->iChannelNames, d->iTerminal);
    756 #endif
    757 	/* If USB input terminal, record wChannelConfig */
    758 	if ((UGETW(d->wTerminalType) & 0xff00) != 0x0100)
    759 		return;
    760 	sc->sc_channel_config = UGETW(d->wChannelConfig);
    761 }
    762 
    763 Static void
    764 uaudio_add_output(struct uaudio_softc *sc,
    765     const struct io_terminal *iot, int id)
    766 {
    767 #ifdef UAUDIO_DEBUG
    768 	const struct usb_audio_output_terminal *d;
    769 
    770 	d = iot[id].d.ot;
    771 	DPRINTFN(2,"bTerminalId=%d wTerminalType=0x%04x "
    772 		    "bAssocTerminal=%d bSourceId=%d iTerminal=%d\n",
    773 		    d->bTerminalId, UGETW(d->wTerminalType), d->bAssocTerminal,
    774 		    d->bSourceId, d->iTerminal);
    775 #endif
    776 }
    777 
    778 Static void
    779 uaudio_add_mixer(struct uaudio_softc *sc, const struct io_terminal *iot, int id)
    780 {
    781 	const struct usb_audio_mixer_unit *d;
    782 	const struct usb_audio_mixer_unit_1 *d1;
    783 	int c, chs, ichs, ochs, i, o, bno, p, mo, mc, k;
    784 	const uByte *bm;
    785 	struct mixerctl mix;
    786 
    787 	d = iot[id].d.mu;
    788 	DPRINTFN(2,"bUnitId=%d bNrInPins=%d\n",
    789 		    d->bUnitId, d->bNrInPins);
    790 
    791 	/* Compute the number of input channels */
    792 	ichs = 0;
    793 	for (i = 0; i < d->bNrInPins; i++)
    794 		ichs += uaudio_get_cluster(d->baSourceId[i], iot).bNrChannels;
    795 
    796 	/* and the number of output channels */
    797 	d1 = (const struct usb_audio_mixer_unit_1 *)&d->baSourceId[d->bNrInPins];
    798 	ochs = d1->bNrChannels;
    799 	DPRINTFN(2,"ichs=%d ochs=%d\n", ichs, ochs);
    800 
    801 	bm = d1->bmControls;
    802 	mix.wIndex = MAKE(d->bUnitId, sc->sc_ac_iface);
    803 	uaudio_determine_class(&iot[id], &mix);
    804 	mix.type = MIX_SIGNED_16;
    805 	mix.ctlunit = AudioNvolume;
    806 #define _BIT(bno) ((bm[bno / 8] >> (7 - bno % 8)) & 1)
    807 	for (p = i = 0; i < d->bNrInPins; i++) {
    808 		chs = uaudio_get_cluster(d->baSourceId[i], iot).bNrChannels;
    809 		mc = 0;
    810 		for (c = 0; c < chs; c++) {
    811 			mo = 0;
    812 			for (o = 0; o < ochs; o++) {
    813 				bno = (p + c) * ochs + o;
    814 				if (_BIT(bno))
    815 					mo++;
    816 			}
    817 			if (mo == 1)
    818 				mc++;
    819 		}
    820 		if (mc == chs && chs <= MIX_MAX_CHAN) {
    821 			k = 0;
    822 			for (c = 0; c < chs; c++)
    823 				for (o = 0; o < ochs; o++) {
    824 					bno = (p + c) * ochs + o;
    825 					if (_BIT(bno))
    826 						mix.wValue[k++] =
    827 							MAKE(p+c+1, o+1);
    828 				}
    829 			snprintf(mix.ctlname, sizeof(mix.ctlname), "mix%d-%s",
    830 			    d->bUnitId, uaudio_id_name(sc, iot,
    831 			    d->baSourceId[i]));
    832 			mix.nchan = chs;
    833 			uaudio_mixer_add_ctl(sc, &mix);
    834 		} else {
    835 			/* XXX */
    836 		}
    837 #undef _BIT
    838 		p += chs;
    839 	}
    840 
    841 }
    842 
    843 Static void
    844 uaudio_add_selector(struct uaudio_softc *sc, const struct io_terminal *iot, int id)
    845 {
    846 	const struct usb_audio_selector_unit *d;
    847 	struct mixerctl mix;
    848 	int i, wp;
    849 
    850 	d = iot[id].d.su;
    851 	DPRINTFN(2,"bUnitId=%d bNrInPins=%d\n",
    852 		    d->bUnitId, d->bNrInPins);
    853 	mix.wIndex = MAKE(d->bUnitId, sc->sc_ac_iface);
    854 	mix.wValue[0] = MAKE(0, 0);
    855 	uaudio_determine_class(&iot[id], &mix);
    856 	mix.nchan = 1;
    857 	mix.type = MIX_SELECTOR;
    858 	mix.ctlunit = "";
    859 	mix.minval = 1;
    860 	mix.maxval = d->bNrInPins;
    861 	mix.mul = mix.maxval - mix.minval;
    862 	wp = snprintf(mix.ctlname, MAX_AUDIO_DEV_LEN, "sel%d-", d->bUnitId);
    863 	for (i = 1; i <= d->bNrInPins; i++) {
    864 		wp += snprintf(mix.ctlname + wp, MAX_AUDIO_DEV_LEN - wp,
    865 			       "i%d", d->baSourceId[i - 1]);
    866 		if (wp > MAX_AUDIO_DEV_LEN - 1)
    867 			break;
    868 	}
    869 	uaudio_mixer_add_ctl(sc, &mix);
    870 }
    871 
    872 #ifdef UAUDIO_DEBUG
    873 Static const char *
    874 uaudio_get_terminal_name(int terminal_type)
    875 {
    876 	static char tbuf[100];
    877 
    878 	switch (terminal_type) {
    879 	/* USB terminal types */
    880 	case UAT_UNDEFINED:	return "UAT_UNDEFINED";
    881 	case UAT_STREAM:	return "UAT_STREAM";
    882 	case UAT_VENDOR:	return "UAT_VENDOR";
    883 	/* input terminal types */
    884 	case UATI_UNDEFINED:	return "UATI_UNDEFINED";
    885 	case UATI_MICROPHONE:	return "UATI_MICROPHONE";
    886 	case UATI_DESKMICROPHONE:	return "UATI_DESKMICROPHONE";
    887 	case UATI_PERSONALMICROPHONE:	return "UATI_PERSONALMICROPHONE";
    888 	case UATI_OMNIMICROPHONE:	return "UATI_OMNIMICROPHONE";
    889 	case UATI_MICROPHONEARRAY:	return "UATI_MICROPHONEARRAY";
    890 	case UATI_PROCMICROPHONEARR:	return "UATI_PROCMICROPHONEARR";
    891 	/* output terminal types */
    892 	case UATO_UNDEFINED:	return "UATO_UNDEFINED";
    893 	case UATO_SPEAKER:	return "UATO_SPEAKER";
    894 	case UATO_HEADPHONES:	return "UATO_HEADPHONES";
    895 	case UATO_DISPLAYAUDIO:	return "UATO_DISPLAYAUDIO";
    896 	case UATO_DESKTOPSPEAKER:	return "UATO_DESKTOPSPEAKER";
    897 	case UATO_ROOMSPEAKER:	return "UATO_ROOMSPEAKER";
    898 	case UATO_COMMSPEAKER:	return "UATO_COMMSPEAKER";
    899 	case UATO_SUBWOOFER:	return "UATO_SUBWOOFER";
    900 	/* bidir terminal types */
    901 	case UATB_UNDEFINED:	return "UATB_UNDEFINED";
    902 	case UATB_HANDSET:	return "UATB_HANDSET";
    903 	case UATB_HEADSET:	return "UATB_HEADSET";
    904 	case UATB_SPEAKERPHONE:	return "UATB_SPEAKERPHONE";
    905 	case UATB_SPEAKERPHONEESUP:	return "UATB_SPEAKERPHONEESUP";
    906 	case UATB_SPEAKERPHONEECANC:	return "UATB_SPEAKERPHONEECANC";
    907 	/* telephony terminal types */
    908 	case UATT_UNDEFINED:	return "UATT_UNDEFINED";
    909 	case UATT_PHONELINE:	return "UATT_PHONELINE";
    910 	case UATT_TELEPHONE:	return "UATT_TELEPHONE";
    911 	case UATT_DOWNLINEPHONE:	return "UATT_DOWNLINEPHONE";
    912 	/* external terminal types */
    913 	case UATE_UNDEFINED:	return "UATE_UNDEFINED";
    914 	case UATE_ANALOGCONN:	return "UATE_ANALOGCONN";
    915 	case UATE_LINECONN:	return "UATE_LINECONN";
    916 	case UATE_LEGACYCONN:	return "UATE_LEGACYCONN";
    917 	case UATE_DIGITALAUIFC:	return "UATE_DIGITALAUIFC";
    918 	case UATE_SPDIF:	return "UATE_SPDIF";
    919 	case UATE_1394DA:	return "UATE_1394DA";
    920 	case UATE_1394DV:	return "UATE_1394DV";
    921 	/* embedded function terminal types */
    922 	case UATF_UNDEFINED:	return "UATF_UNDEFINED";
    923 	case UATF_CALIBNOISE:	return "UATF_CALIBNOISE";
    924 	case UATF_EQUNOISE:	return "UATF_EQUNOISE";
    925 	case UATF_CDPLAYER:	return "UATF_CDPLAYER";
    926 	case UATF_DAT:	return "UATF_DAT";
    927 	case UATF_DCC:	return "UATF_DCC";
    928 	case UATF_MINIDISK:	return "UATF_MINIDISK";
    929 	case UATF_ANALOGTAPE:	return "UATF_ANALOGTAPE";
    930 	case UATF_PHONOGRAPH:	return "UATF_PHONOGRAPH";
    931 	case UATF_VCRAUDIO:	return "UATF_VCRAUDIO";
    932 	case UATF_VIDEODISCAUDIO:	return "UATF_VIDEODISCAUDIO";
    933 	case UATF_DVDAUDIO:	return "UATF_DVDAUDIO";
    934 	case UATF_TVTUNERAUDIO:	return "UATF_TVTUNERAUDIO";
    935 	case UATF_SATELLITE:	return "UATF_SATELLITE";
    936 	case UATF_CABLETUNER:	return "UATF_CABLETUNER";
    937 	case UATF_DSS:	return "UATF_DSS";
    938 	case UATF_RADIORECV:	return "UATF_RADIORECV";
    939 	case UATF_RADIOXMIT:	return "UATF_RADIOXMIT";
    940 	case UATF_MULTITRACK:	return "UATF_MULTITRACK";
    941 	case UATF_SYNTHESIZER:	return "UATF_SYNTHESIZER";
    942 	default:
    943 		snprintf(tbuf, sizeof(tbuf), "unknown type (0x%.4x)", terminal_type);
    944 		return tbuf;
    945 	}
    946 }
    947 #endif
    948 
    949 Static int
    950 uaudio_determine_class(const struct io_terminal *iot, struct mixerctl *mix)
    951 {
    952 	int terminal_type;
    953 
    954 	if (iot == NULL || iot->output == NULL) {
    955 		mix->class = UAC_OUTPUT;
    956 		return 0;
    957 	}
    958 	terminal_type = 0;
    959 	if (iot->output->size == 1)
    960 		terminal_type = iot->output->terminals[0];
    961 	/*
    962 	 * If the only output terminal is USB,
    963 	 * the class is UAC_RECORD.
    964 	 */
    965 	if ((terminal_type & 0xff00) == (UAT_UNDEFINED & 0xff00)) {
    966 		mix->class = UAC_RECORD;
    967 		if (iot->inputs_size == 1
    968 		    && iot->inputs[0] != NULL
    969 		    && iot->inputs[0]->size == 1)
    970 			return iot->inputs[0]->terminals[0];
    971 		else
    972 			return 0;
    973 	}
    974 	/*
    975 	 * If the ultimate destination of the unit is just one output
    976 	 * terminal and the unit is connected to the output terminal
    977 	 * directly, the class is UAC_OUTPUT.
    978 	 */
    979 	if (terminal_type != 0 && iot->direct) {
    980 		mix->class = UAC_OUTPUT;
    981 		return terminal_type;
    982 	}
    983 	/*
    984 	 * If the unit is connected to just one input terminal,
    985 	 * the class is UAC_INPUT.
    986 	 */
    987 	if (iot->inputs_size == 1 && iot->inputs[0] != NULL
    988 	    && iot->inputs[0]->size == 1) {
    989 		mix->class = UAC_INPUT;
    990 		return iot->inputs[0]->terminals[0];
    991 	}
    992 	/*
    993 	 * Otherwise, the class is UAC_OUTPUT.
    994 	 */
    995 	mix->class = UAC_OUTPUT;
    996 	return terminal_type;
    997 }
    998 
    999 Static const char *
   1000 uaudio_feature_name(const struct io_terminal *iot, struct mixerctl *mix)
   1001 {
   1002 	int terminal_type;
   1003 
   1004 	terminal_type = uaudio_determine_class(iot, mix);
   1005 	if (mix->class == UAC_RECORD && terminal_type == 0)
   1006 		return AudioNmixerout;
   1007 	DPRINTF("terminal_type=%s\n", uaudio_get_terminal_name(terminal_type));
   1008 	switch (terminal_type) {
   1009 	case UAT_STREAM:
   1010 		return AudioNdac;
   1011 
   1012 	case UATI_MICROPHONE:
   1013 	case UATI_DESKMICROPHONE:
   1014 	case UATI_PERSONALMICROPHONE:
   1015 	case UATI_OMNIMICROPHONE:
   1016 	case UATI_MICROPHONEARRAY:
   1017 	case UATI_PROCMICROPHONEARR:
   1018 		return AudioNmicrophone;
   1019 
   1020 	case UATO_SPEAKER:
   1021 	case UATO_DESKTOPSPEAKER:
   1022 	case UATO_ROOMSPEAKER:
   1023 	case UATO_COMMSPEAKER:
   1024 		return AudioNspeaker;
   1025 
   1026 	case UATO_HEADPHONES:
   1027 		return AudioNheadphone;
   1028 
   1029 	case UATO_SUBWOOFER:
   1030 		return AudioNlfe;
   1031 
   1032 	/* telephony terminal types */
   1033 	case UATT_UNDEFINED:
   1034 	case UATT_PHONELINE:
   1035 	case UATT_TELEPHONE:
   1036 	case UATT_DOWNLINEPHONE:
   1037 		return "phone";
   1038 
   1039 	case UATE_ANALOGCONN:
   1040 	case UATE_LINECONN:
   1041 	case UATE_LEGACYCONN:
   1042 		return AudioNline;
   1043 
   1044 	case UATE_DIGITALAUIFC:
   1045 	case UATE_SPDIF:
   1046 	case UATE_1394DA:
   1047 	case UATE_1394DV:
   1048 		return AudioNaux;
   1049 
   1050 	case UATF_CDPLAYER:
   1051 		return AudioNcd;
   1052 
   1053 	case UATF_SYNTHESIZER:
   1054 		return AudioNfmsynth;
   1055 
   1056 	case UATF_VIDEODISCAUDIO:
   1057 	case UATF_DVDAUDIO:
   1058 	case UATF_TVTUNERAUDIO:
   1059 		return AudioNvideo;
   1060 
   1061 	case UAT_UNDEFINED:
   1062 	case UAT_VENDOR:
   1063 	case UATI_UNDEFINED:
   1064 /* output terminal types */
   1065 	case UATO_UNDEFINED:
   1066 	case UATO_DISPLAYAUDIO:
   1067 /* bidir terminal types */
   1068 	case UATB_UNDEFINED:
   1069 	case UATB_HANDSET:
   1070 	case UATB_HEADSET:
   1071 	case UATB_SPEAKERPHONE:
   1072 	case UATB_SPEAKERPHONEESUP:
   1073 	case UATB_SPEAKERPHONEECANC:
   1074 /* external terminal types */
   1075 	case UATE_UNDEFINED:
   1076 /* embedded function terminal types */
   1077 	case UATF_UNDEFINED:
   1078 	case UATF_CALIBNOISE:
   1079 	case UATF_EQUNOISE:
   1080 	case UATF_DAT:
   1081 	case UATF_DCC:
   1082 	case UATF_MINIDISK:
   1083 	case UATF_ANALOGTAPE:
   1084 	case UATF_PHONOGRAPH:
   1085 	case UATF_VCRAUDIO:
   1086 	case UATF_SATELLITE:
   1087 	case UATF_CABLETUNER:
   1088 	case UATF_DSS:
   1089 	case UATF_RADIORECV:
   1090 	case UATF_RADIOXMIT:
   1091 	case UATF_MULTITRACK:
   1092 	case 0xffff:
   1093 	default:
   1094 		DPRINTF("'master' for 0x%.4x\n", terminal_type);
   1095 		return AudioNmaster;
   1096 	}
   1097 	return AudioNmaster;
   1098 }
   1099 
   1100 Static void
   1101 uaudio_add_feature(struct uaudio_softc *sc, const struct io_terminal *iot, int id)
   1102 {
   1103 	const struct usb_audio_feature_unit *d;
   1104 	const uByte *ctls;
   1105 	int ctlsize;
   1106 	int nchan;
   1107 	u_int fumask, mmask, cmask;
   1108 	struct mixerctl mix;
   1109 	int chan, ctl, i, unit;
   1110 	const char *mixername;
   1111 
   1112 #define GET(i) (ctls[(i)*ctlsize] | \
   1113 		(ctlsize > 1 ? ctls[(i)*ctlsize+1] << 8 : 0))
   1114 	d = iot[id].d.fu;
   1115 	ctls = d->bmaControls;
   1116 	ctlsize = d->bControlSize;
   1117 	nchan = (d->bLength - 7) / ctlsize;
   1118 	mmask = GET(0);
   1119 	/* Figure out what we can control */
   1120 	for (cmask = 0, chan = 1; chan < nchan; chan++) {
   1121 		DPRINTFN(9,"chan=%d mask=%x\n",
   1122 			    chan, GET(chan));
   1123 		cmask |= GET(chan);
   1124 	}
   1125 
   1126 	DPRINTFN(1,"bUnitId=%d, "
   1127 		    "%d channels, mmask=0x%04x, cmask=0x%04x\n",
   1128 		    d->bUnitId, nchan, mmask, cmask);
   1129 
   1130 	if (nchan > MIX_MAX_CHAN)
   1131 		nchan = MIX_MAX_CHAN;
   1132 	unit = d->bUnitId;
   1133 	mix.wIndex = MAKE(unit, sc->sc_ac_iface);
   1134 	for (ctl = MUTE_CONTROL; ctl < LOUDNESS_CONTROL; ctl++) {
   1135 		fumask = FU_MASK(ctl);
   1136 		DPRINTFN(4,"ctl=%d fumask=0x%04x\n",
   1137 			    ctl, fumask);
   1138 		if (mmask & fumask) {
   1139 			mix.nchan = 1;
   1140 			mix.wValue[0] = MAKE(ctl, 0);
   1141 		} else if (cmask & fumask) {
   1142 			mix.nchan = nchan - 1;
   1143 			for (i = 1; i < nchan; i++) {
   1144 				if (GET(i) & fumask)
   1145 					mix.wValue[i-1] = MAKE(ctl, i);
   1146 				else
   1147 					mix.wValue[i-1] = -1;
   1148 			}
   1149 		} else {
   1150 			continue;
   1151 		}
   1152 #undef GET
   1153 		mixername = uaudio_feature_name(&iot[id], &mix);
   1154 		switch (ctl) {
   1155 		case MUTE_CONTROL:
   1156 			mix.type = MIX_ON_OFF;
   1157 			mix.ctlunit = "";
   1158 			snprintf(mix.ctlname, sizeof(mix.ctlname),
   1159 				 "%s.%s", mixername, AudioNmute);
   1160 			break;
   1161 		case VOLUME_CONTROL:
   1162 			mix.type = MIX_SIGNED_16;
   1163 			mix.ctlunit = AudioNvolume;
   1164 			strlcpy(mix.ctlname, mixername, sizeof(mix.ctlname));
   1165 			break;
   1166 		case BASS_CONTROL:
   1167 			mix.type = MIX_SIGNED_8;
   1168 			mix.ctlunit = AudioNbass;
   1169 			snprintf(mix.ctlname, sizeof(mix.ctlname),
   1170 				 "%s.%s", mixername, AudioNbass);
   1171 			break;
   1172 		case MID_CONTROL:
   1173 			mix.type = MIX_SIGNED_8;
   1174 			mix.ctlunit = AudioNmid;
   1175 			snprintf(mix.ctlname, sizeof(mix.ctlname),
   1176 				 "%s.%s", mixername, AudioNmid);
   1177 			break;
   1178 		case TREBLE_CONTROL:
   1179 			mix.type = MIX_SIGNED_8;
   1180 			mix.ctlunit = AudioNtreble;
   1181 			snprintf(mix.ctlname, sizeof(mix.ctlname),
   1182 				 "%s.%s", mixername, AudioNtreble);
   1183 			break;
   1184 		case GRAPHIC_EQUALIZER_CONTROL:
   1185 			continue; /* XXX don't add anything */
   1186 			break;
   1187 		case AGC_CONTROL:
   1188 			mix.type = MIX_ON_OFF;
   1189 			mix.ctlunit = "";
   1190 			snprintf(mix.ctlname, sizeof(mix.ctlname), "%s.%s",
   1191 				 mixername, AudioNagc);
   1192 			break;
   1193 		case DELAY_CONTROL:
   1194 			mix.type = MIX_UNSIGNED_16;
   1195 			mix.ctlunit = "4 ms";
   1196 			snprintf(mix.ctlname, sizeof(mix.ctlname),
   1197 				 "%s.%s", mixername, AudioNdelay);
   1198 			break;
   1199 		case BASS_BOOST_CONTROL:
   1200 			mix.type = MIX_ON_OFF;
   1201 			mix.ctlunit = "";
   1202 			snprintf(mix.ctlname, sizeof(mix.ctlname),
   1203 				 "%s.%s", mixername, AudioNbassboost);
   1204 			break;
   1205 		case LOUDNESS_CONTROL:
   1206 			mix.type = MIX_ON_OFF;
   1207 			mix.ctlunit = "";
   1208 			snprintf(mix.ctlname, sizeof(mix.ctlname),
   1209 				 "%s.%s", mixername, AudioNloudness);
   1210 			break;
   1211 		}
   1212 		uaudio_mixer_add_ctl(sc, &mix);
   1213 	}
   1214 }
   1215 
   1216 Static void
   1217 uaudio_add_processing_updown(struct uaudio_softc *sc,
   1218 			     const struct io_terminal *iot, int id)
   1219 {
   1220 	const struct usb_audio_processing_unit *d;
   1221 	const struct usb_audio_processing_unit_1 *d1;
   1222 	const struct usb_audio_processing_unit_updown *ud;
   1223 	struct mixerctl mix;
   1224 	int i;
   1225 
   1226 	d = iot[id].d.pu;
   1227 	d1 = (const struct usb_audio_processing_unit_1 *)
   1228 	    &d->baSourceId[d->bNrInPins];
   1229 	ud = (const struct usb_audio_processing_unit_updown *)
   1230 	    &d1->bmControls[d1->bControlSize];
   1231 	DPRINTFN(2,"bUnitId=%d bNrModes=%d\n",
   1232 		    d->bUnitId, ud->bNrModes);
   1233 
   1234 	if (!(d1->bmControls[0] & UA_PROC_MASK(UD_MODE_SELECT_CONTROL))) {
   1235 		DPRINTF("%s", "no mode select\n");
   1236 		return;
   1237 	}
   1238 
   1239 	mix.wIndex = MAKE(d->bUnitId, sc->sc_ac_iface);
   1240 	mix.nchan = 1;
   1241 	mix.wValue[0] = MAKE(UD_MODE_SELECT_CONTROL, 0);
   1242 	uaudio_determine_class(&iot[id], &mix);
   1243 	mix.type = MIX_ON_OFF;	/* XXX */
   1244 	mix.ctlunit = "";
   1245 	snprintf(mix.ctlname, sizeof(mix.ctlname), "pro%d-mode", d->bUnitId);
   1246 
   1247 	for (i = 0; i < ud->bNrModes; i++) {
   1248 		DPRINTFN(2,"i=%d bm=0x%x\n",
   1249 			    i, UGETW(ud->waModes[i]));
   1250 		/* XXX */
   1251 	}
   1252 	uaudio_mixer_add_ctl(sc, &mix);
   1253 }
   1254 
   1255 Static void
   1256 uaudio_add_processing(struct uaudio_softc *sc, const struct io_terminal *iot, int id)
   1257 {
   1258 	const struct usb_audio_processing_unit *d;
   1259 	const struct usb_audio_processing_unit_1 *d1;
   1260 	int ptype;
   1261 	struct mixerctl mix;
   1262 
   1263 	d = iot[id].d.pu;
   1264 	d1 = (const struct usb_audio_processing_unit_1 *)
   1265 	    &d->baSourceId[d->bNrInPins];
   1266 	ptype = UGETW(d->wProcessType);
   1267 	DPRINTFN(2,"wProcessType=%d bUnitId=%d "
   1268 		    "bNrInPins=%d\n", ptype, d->bUnitId, d->bNrInPins);
   1269 
   1270 	if (d1->bmControls[0] & UA_PROC_ENABLE_MASK) {
   1271 		mix.wIndex = MAKE(d->bUnitId, sc->sc_ac_iface);
   1272 		mix.nchan = 1;
   1273 		mix.wValue[0] = MAKE(XX_ENABLE_CONTROL, 0);
   1274 		uaudio_determine_class(&iot[id], &mix);
   1275 		mix.type = MIX_ON_OFF;
   1276 		mix.ctlunit = "";
   1277 		snprintf(mix.ctlname, sizeof(mix.ctlname), "pro%d.%d-enable",
   1278 		    d->bUnitId, ptype);
   1279 		uaudio_mixer_add_ctl(sc, &mix);
   1280 	}
   1281 
   1282 	switch(ptype) {
   1283 	case UPDOWNMIX_PROCESS:
   1284 		uaudio_add_processing_updown(sc, iot, id);
   1285 		break;
   1286 	case DOLBY_PROLOGIC_PROCESS:
   1287 	case P3D_STEREO_EXTENDER_PROCESS:
   1288 	case REVERBATION_PROCESS:
   1289 	case CHORUS_PROCESS:
   1290 	case DYN_RANGE_COMP_PROCESS:
   1291 	default:
   1292 #ifdef UAUDIO_DEBUG
   1293 		aprint_debug(
   1294 		    "uaudio_add_processing: unit %d, type=%d not impl.\n",
   1295 		    d->bUnitId, ptype);
   1296 #endif
   1297 		break;
   1298 	}
   1299 }
   1300 
   1301 Static void
   1302 uaudio_add_extension(struct uaudio_softc *sc, const struct io_terminal *iot, int id)
   1303 {
   1304 	const struct usb_audio_extension_unit *d;
   1305 	const struct usb_audio_extension_unit_1 *d1;
   1306 	struct mixerctl mix;
   1307 
   1308 	d = iot[id].d.eu;
   1309 	d1 = (const struct usb_audio_extension_unit_1 *)
   1310 	    &d->baSourceId[d->bNrInPins];
   1311 	DPRINTFN(2,"bUnitId=%d bNrInPins=%d\n",
   1312 		    d->bUnitId, d->bNrInPins);
   1313 
   1314 	if (usbd_get_quirks(sc->sc_udev)->uq_flags & UQ_AU_NO_XU)
   1315 		return;
   1316 
   1317 	if (d1->bmControls[0] & UA_EXT_ENABLE_MASK) {
   1318 		mix.wIndex = MAKE(d->bUnitId, sc->sc_ac_iface);
   1319 		mix.nchan = 1;
   1320 		mix.wValue[0] = MAKE(UA_EXT_ENABLE, 0);
   1321 		uaudio_determine_class(&iot[id], &mix);
   1322 		mix.type = MIX_ON_OFF;
   1323 		mix.ctlunit = "";
   1324 		snprintf(mix.ctlname, sizeof(mix.ctlname), "ext%d-enable",
   1325 		    d->bUnitId);
   1326 		uaudio_mixer_add_ctl(sc, &mix);
   1327 	}
   1328 }
   1329 
   1330 Static struct terminal_list*
   1331 uaudio_merge_terminal_list(const struct io_terminal *iot)
   1332 {
   1333 	struct terminal_list *tml;
   1334 	uint16_t *ptm;
   1335 	int i, len;
   1336 
   1337 	len = 0;
   1338 	if (iot->inputs == NULL)
   1339 		return NULL;
   1340 	for (i = 0; i < iot->inputs_size; i++) {
   1341 		if (iot->inputs[i] != NULL)
   1342 			len += iot->inputs[i]->size;
   1343 	}
   1344 	tml = malloc(TERMINAL_LIST_SIZE(len), M_TEMP, M_NOWAIT);
   1345 	if (tml == NULL) {
   1346 		aprint_error("uaudio_merge_terminal_list: no memory\n");
   1347 		return NULL;
   1348 	}
   1349 	tml->size = 0;
   1350 	ptm = tml->terminals;
   1351 	for (i = 0; i < iot->inputs_size; i++) {
   1352 		if (iot->inputs[i] == NULL)
   1353 			continue;
   1354 		if (iot->inputs[i]->size > len)
   1355 			break;
   1356 		memcpy(ptm, iot->inputs[i]->terminals,
   1357 		       iot->inputs[i]->size * sizeof(uint16_t));
   1358 		tml->size += iot->inputs[i]->size;
   1359 		ptm += iot->inputs[i]->size;
   1360 		len -= iot->inputs[i]->size;
   1361 	}
   1362 	return tml;
   1363 }
   1364 
   1365 Static struct terminal_list *
   1366 uaudio_io_terminaltype(int outtype, struct io_terminal *iot, int id)
   1367 {
   1368 	struct terminal_list *tml;
   1369 	struct io_terminal *it;
   1370 	int src_id, i;
   1371 
   1372 	it = &iot[id];
   1373 	if (it->output != NULL) {
   1374 		/* already has outtype? */
   1375 		for (i = 0; i < it->output->size; i++)
   1376 			if (it->output->terminals[i] == outtype)
   1377 				return uaudio_merge_terminal_list(it);
   1378 		tml = malloc(TERMINAL_LIST_SIZE(it->output->size + 1),
   1379 			     M_TEMP, M_NOWAIT);
   1380 		if (tml == NULL) {
   1381 			aprint_error("uaudio_io_terminaltype: no memory\n");
   1382 			return uaudio_merge_terminal_list(it);
   1383 		}
   1384 		memcpy(tml, it->output, TERMINAL_LIST_SIZE(it->output->size));
   1385 		tml->terminals[it->output->size] = outtype;
   1386 		tml->size++;
   1387 		free(it->output, M_TEMP);
   1388 		it->output = tml;
   1389 		if (it->inputs != NULL) {
   1390 			for (i = 0; i < it->inputs_size; i++)
   1391 				if (it->inputs[i] != NULL)
   1392 					free(it->inputs[i], M_TEMP);
   1393 			free(it->inputs, M_TEMP);
   1394 		}
   1395 		it->inputs_size = 0;
   1396 		it->inputs = NULL;
   1397 	} else {		/* end `iot[id] != NULL' */
   1398 		it->inputs_size = 0;
   1399 		it->inputs = NULL;
   1400 		it->output = malloc(TERMINAL_LIST_SIZE(1), M_TEMP, M_NOWAIT);
   1401 		if (it->output == NULL) {
   1402 			aprint_error("uaudio_io_terminaltype: no memory\n");
   1403 			return NULL;
   1404 		}
   1405 		it->output->terminals[0] = outtype;
   1406 		it->output->size = 1;
   1407 		it->direct = FALSE;
   1408 	}
   1409 
   1410 	switch (it->d.desc->bDescriptorSubtype) {
   1411 	case UDESCSUB_AC_INPUT:
   1412 		it->inputs = malloc(sizeof(struct terminal_list *), M_TEMP, M_NOWAIT);
   1413 		if (it->inputs == NULL) {
   1414 			aprint_error("uaudio_io_terminaltype: no memory\n");
   1415 			return NULL;
   1416 		}
   1417 		tml = malloc(TERMINAL_LIST_SIZE(1), M_TEMP, M_NOWAIT);
   1418 		if (tml == NULL) {
   1419 			aprint_error("uaudio_io_terminaltype: no memory\n");
   1420 			free(it->inputs, M_TEMP);
   1421 			it->inputs = NULL;
   1422 			return NULL;
   1423 		}
   1424 		it->inputs[0] = tml;
   1425 		tml->terminals[0] = UGETW(it->d.it->wTerminalType);
   1426 		tml->size = 1;
   1427 		it->inputs_size = 1;
   1428 		return uaudio_merge_terminal_list(it);
   1429 	case UDESCSUB_AC_FEATURE:
   1430 		src_id = it->d.fu->bSourceId;
   1431 		it->inputs = malloc(sizeof(struct terminal_list *), M_TEMP, M_NOWAIT);
   1432 		if (it->inputs == NULL) {
   1433 			aprint_error("uaudio_io_terminaltype: no memory\n");
   1434 			return uaudio_io_terminaltype(outtype, iot, src_id);
   1435 		}
   1436 		it->inputs[0] = uaudio_io_terminaltype(outtype, iot, src_id);
   1437 		it->inputs_size = 1;
   1438 		return uaudio_merge_terminal_list(it);
   1439 	case UDESCSUB_AC_OUTPUT:
   1440 		it->inputs = malloc(sizeof(struct terminal_list *), M_TEMP, M_NOWAIT);
   1441 		if (it->inputs == NULL) {
   1442 			aprint_error("uaudio_io_terminaltype: no memory\n");
   1443 			return NULL;
   1444 		}
   1445 		src_id = it->d.ot->bSourceId;
   1446 		it->inputs[0] = uaudio_io_terminaltype(outtype, iot, src_id);
   1447 		it->inputs_size = 1;
   1448 		iot[src_id].direct = TRUE;
   1449 		return NULL;
   1450 	case UDESCSUB_AC_MIXER:
   1451 		it->inputs_size = 0;
   1452 		it->inputs = malloc(sizeof(struct terminal_list *)
   1453 				    * it->d.mu->bNrInPins, M_TEMP, M_NOWAIT);
   1454 		if (it->inputs == NULL) {
   1455 			aprint_error("uaudio_io_terminaltype: no memory\n");
   1456 			return NULL;
   1457 		}
   1458 		for (i = 0; i < it->d.mu->bNrInPins; i++) {
   1459 			src_id = it->d.mu->baSourceId[i];
   1460 			it->inputs[i] = uaudio_io_terminaltype(outtype, iot,
   1461 							       src_id);
   1462 			it->inputs_size++;
   1463 		}
   1464 		return uaudio_merge_terminal_list(it);
   1465 	case UDESCSUB_AC_SELECTOR:
   1466 		it->inputs_size = 0;
   1467 		it->inputs = malloc(sizeof(struct terminal_list *)
   1468 				    * it->d.su->bNrInPins, M_TEMP, M_NOWAIT);
   1469 		if (it->inputs == NULL) {
   1470 			aprint_error("uaudio_io_terminaltype: no memory\n");
   1471 			return NULL;
   1472 		}
   1473 		for (i = 0; i < it->d.su->bNrInPins; i++) {
   1474 			src_id = it->d.su->baSourceId[i];
   1475 			it->inputs[i] = uaudio_io_terminaltype(outtype, iot,
   1476 							       src_id);
   1477 			it->inputs_size++;
   1478 		}
   1479 		return uaudio_merge_terminal_list(it);
   1480 	case UDESCSUB_AC_PROCESSING:
   1481 		it->inputs_size = 0;
   1482 		it->inputs = malloc(sizeof(struct terminal_list *)
   1483 				    * it->d.pu->bNrInPins, M_TEMP, M_NOWAIT);
   1484 		if (it->inputs == NULL) {
   1485 			aprint_error("uaudio_io_terminaltype: no memory\n");
   1486 			return NULL;
   1487 		}
   1488 		for (i = 0; i < it->d.pu->bNrInPins; i++) {
   1489 			src_id = it->d.pu->baSourceId[i];
   1490 			it->inputs[i] = uaudio_io_terminaltype(outtype, iot,
   1491 							       src_id);
   1492 			it->inputs_size++;
   1493 		}
   1494 		return uaudio_merge_terminal_list(it);
   1495 	case UDESCSUB_AC_EXTENSION:
   1496 		it->inputs_size = 0;
   1497 		it->inputs = malloc(sizeof(struct terminal_list *)
   1498 				    * it->d.eu->bNrInPins, M_TEMP, M_NOWAIT);
   1499 		if (it->inputs == NULL) {
   1500 			aprint_error("uaudio_io_terminaltype: no memory\n");
   1501 			return NULL;
   1502 		}
   1503 		for (i = 0; i < it->d.eu->bNrInPins; i++) {
   1504 			src_id = it->d.eu->baSourceId[i];
   1505 			it->inputs[i] = uaudio_io_terminaltype(outtype, iot,
   1506 							       src_id);
   1507 			it->inputs_size++;
   1508 		}
   1509 		return uaudio_merge_terminal_list(it);
   1510 	case UDESCSUB_AC_HEADER:
   1511 	default:
   1512 		return NULL;
   1513 	}
   1514 }
   1515 
   1516 Static usbd_status
   1517 uaudio_identify(struct uaudio_softc *sc, const usb_config_descriptor_t *cdesc)
   1518 {
   1519 	usbd_status err;
   1520 
   1521 	err = uaudio_identify_ac(sc, cdesc);
   1522 	if (err)
   1523 		return err;
   1524 	return uaudio_identify_as(sc, cdesc);
   1525 }
   1526 
   1527 Static void
   1528 uaudio_add_alt(struct uaudio_softc *sc, const struct as_info *ai)
   1529 {
   1530 	size_t len;
   1531 	struct as_info *nai;
   1532 
   1533 	len = sizeof(*ai) * (sc->sc_nalts + 1);
   1534 	nai = malloc(len, M_USBDEV, M_NOWAIT);
   1535 	if (nai == NULL) {
   1536 		aprint_error("uaudio_add_alt: no memory\n");
   1537 		return;
   1538 	}
   1539 	/* Copy old data, if there was any */
   1540 	if (sc->sc_nalts != 0) {
   1541 		memcpy(nai, sc->sc_alts, sizeof(*ai) * (sc->sc_nalts));
   1542 		free(sc->sc_alts, M_USBDEV);
   1543 	}
   1544 	sc->sc_alts = nai;
   1545 	DPRINTFN(2,"adding alt=%d, enc=%d\n",
   1546 		    ai->alt, ai->encoding);
   1547 	sc->sc_alts[sc->sc_nalts++] = *ai;
   1548 }
   1549 
   1550 Static usbd_status
   1551 uaudio_process_as(struct uaudio_softc *sc, const char *tbuf, int *offsp,
   1552 		  int size, const usb_interface_descriptor_t *id)
   1553 #define offs (*offsp)
   1554 {
   1555 	const struct usb_audio_streaming_interface_descriptor *asid;
   1556 	const struct usb_audio_streaming_type1_descriptor *asf1d;
   1557 	const usb_endpoint_descriptor_audio_t *ed;
   1558 	const usb_endpoint_descriptor_audio_t *epdesc1;
   1559 	const struct usb_audio_streaming_endpoint_descriptor *sed;
   1560 	int format, chan __unused, prec, enc;
   1561 	int dir, type, sync;
   1562 	struct as_info ai;
   1563 	const char *format_str __unused;
   1564 
   1565 	asid = (const void *)(tbuf + offs);
   1566 	if (asid->bDescriptorType != UDESC_CS_INTERFACE ||
   1567 	    asid->bDescriptorSubtype != AS_GENERAL)
   1568 		return USBD_INVAL;
   1569 	DPRINTF("asid: bTerminakLink=%d wFormatTag=%d\n",
   1570 		 asid->bTerminalLink, UGETW(asid->wFormatTag));
   1571 	offs += asid->bLength;
   1572 	if (offs > size)
   1573 		return USBD_INVAL;
   1574 
   1575 	asf1d = (const void *)(tbuf + offs);
   1576 	if (asf1d->bDescriptorType != UDESC_CS_INTERFACE ||
   1577 	    asf1d->bDescriptorSubtype != FORMAT_TYPE)
   1578 		return USBD_INVAL;
   1579 	offs += asf1d->bLength;
   1580 	if (offs > size)
   1581 		return USBD_INVAL;
   1582 
   1583 	if (asf1d->bFormatType != FORMAT_TYPE_I) {
   1584 		aprint_error_dev(sc->sc_dev,
   1585 		    "ignored setting with type %d format\n", UGETW(asid->wFormatTag));
   1586 		return USBD_NORMAL_COMPLETION;
   1587 	}
   1588 
   1589 	ed = (const void *)(tbuf + offs);
   1590 	if (ed->bDescriptorType != UDESC_ENDPOINT)
   1591 		return USBD_INVAL;
   1592 	DPRINTF("endpoint[0] bLength=%d bDescriptorType=%d "
   1593 		 "bEndpointAddress=%d bmAttributes=0x%x wMaxPacketSize=%d "
   1594 		 "bInterval=%d bRefresh=%d bSynchAddress=%d\n",
   1595 		 ed->bLength, ed->bDescriptorType, ed->bEndpointAddress,
   1596 		 ed->bmAttributes, UGETW(ed->wMaxPacketSize),
   1597 		 ed->bInterval, ed->bRefresh, ed->bSynchAddress);
   1598 	offs += ed->bLength;
   1599 	if (offs > size)
   1600 		return USBD_INVAL;
   1601 	if (UE_GET_XFERTYPE(ed->bmAttributes) != UE_ISOCHRONOUS)
   1602 		return USBD_INVAL;
   1603 
   1604 	dir = UE_GET_DIR(ed->bEndpointAddress);
   1605 	type = UE_GET_ISO_TYPE(ed->bmAttributes);
   1606 	if ((usbd_get_quirks(sc->sc_udev)->uq_flags & UQ_AU_INP_ASYNC) &&
   1607 	    dir == UE_DIR_IN && type == UE_ISO_ADAPT)
   1608 		type = UE_ISO_ASYNC;
   1609 
   1610 	/* We can't handle endpoints that need a sync pipe yet. */
   1611 	sync = FALSE;
   1612 	if (dir == UE_DIR_IN && type == UE_ISO_ADAPT) {
   1613 		sync = TRUE;
   1614 #ifndef UAUDIO_MULTIPLE_ENDPOINTS
   1615 		aprint_error_dev(sc->sc_dev,
   1616 		    "ignored input endpoint of type adaptive\n");
   1617 		return USBD_NORMAL_COMPLETION;
   1618 #endif
   1619 	}
   1620 	if (dir != UE_DIR_IN && type == UE_ISO_ASYNC) {
   1621 		sync = TRUE;
   1622 #ifndef UAUDIO_MULTIPLE_ENDPOINTS
   1623 		aprint_error_dev(sc->sc_dev,
   1624 		    "ignored output endpoint of type async\n");
   1625 		return USBD_NORMAL_COMPLETION;
   1626 #endif
   1627 	}
   1628 
   1629 	sed = (const void *)(tbuf + offs);
   1630 	if (sed->bDescriptorType != UDESC_CS_ENDPOINT ||
   1631 	    sed->bDescriptorSubtype != AS_GENERAL)
   1632 		return USBD_INVAL;
   1633 	DPRINTF(" streadming_endpoint: offset=%d bLength=%d\n", offs, sed->bLength);
   1634 	offs += sed->bLength;
   1635 	if (offs > size)
   1636 		return USBD_INVAL;
   1637 
   1638 #ifdef UAUDIO_MULTIPLE_ENDPOINTS
   1639 	if (sync && id->bNumEndpoints <= 1) {
   1640 		aprint_error_dev(sc->sc_dev,
   1641 		    "a sync-pipe endpoint but no other endpoint\n");
   1642 		return USBD_INVAL;
   1643 	}
   1644 #endif
   1645 	if (!sync && id->bNumEndpoints > 1) {
   1646 		aprint_error_dev(sc->sc_dev,
   1647 		    "non sync-pipe endpoint but multiple endpoints\n");
   1648 		return USBD_INVAL;
   1649 	}
   1650 	epdesc1 = NULL;
   1651 	if (id->bNumEndpoints > 1) {
   1652 		epdesc1 = (const void*)(tbuf + offs);
   1653 		if (epdesc1->bDescriptorType != UDESC_ENDPOINT)
   1654 			return USBD_INVAL;
   1655 		DPRINTF("endpoint[1] bLength=%d "
   1656 			 "bDescriptorType=%d bEndpointAddress=%d "
   1657 			 "bmAttributes=0x%x wMaxPacketSize=%d bInterval=%d "
   1658 			 "bRefresh=%d bSynchAddress=%d\n",
   1659 			 epdesc1->bLength, epdesc1->bDescriptorType,
   1660 			 epdesc1->bEndpointAddress, epdesc1->bmAttributes,
   1661 			 UGETW(epdesc1->wMaxPacketSize), epdesc1->bInterval,
   1662 			 epdesc1->bRefresh, epdesc1->bSynchAddress);
   1663 		offs += epdesc1->bLength;
   1664 		if (offs > size)
   1665 			return USBD_INVAL;
   1666 		if (epdesc1->bSynchAddress != 0) {
   1667 			aprint_error_dev(sc->sc_dev,
   1668 			    "invalid endpoint: bSynchAddress=0\n");
   1669 			return USBD_INVAL;
   1670 		}
   1671 		if (UE_GET_XFERTYPE(epdesc1->bmAttributes) != UE_ISOCHRONOUS) {
   1672 			aprint_error_dev(sc->sc_dev,
   1673 			    "invalid endpoint: bmAttributes=0x%x\n",
   1674 			     epdesc1->bmAttributes);
   1675 			return USBD_INVAL;
   1676 		}
   1677 		if (epdesc1->bEndpointAddress != ed->bSynchAddress) {
   1678 			aprint_error_dev(sc->sc_dev,
   1679 			    "invalid endpoint addresses: "
   1680 			    "ep[0]->bSynchAddress=0x%x "
   1681 			    "ep[1]->bEndpointAddress=0x%x\n",
   1682 			    ed->bSynchAddress, epdesc1->bEndpointAddress);
   1683 			return USBD_INVAL;
   1684 		}
   1685 		/* UE_GET_ADDR(epdesc1->bEndpointAddress), and epdesc1->bRefresh */
   1686 	}
   1687 
   1688 	format = UGETW(asid->wFormatTag);
   1689 	chan = asf1d->bNrChannels;
   1690 	prec = asf1d->bBitResolution;
   1691 	if (prec != 8 && prec != 16 && prec != 24) {
   1692 		aprint_error_dev(sc->sc_dev,
   1693 		    "ignored setting with precision %d\n", prec);
   1694 		return USBD_NORMAL_COMPLETION;
   1695 	}
   1696 	switch (format) {
   1697 	case UA_FMT_PCM:
   1698 		if (prec == 8) {
   1699 			sc->sc_altflags |= HAS_8;
   1700 		} else if (prec == 16) {
   1701 			sc->sc_altflags |= HAS_16;
   1702 		} else if (prec == 24) {
   1703 			sc->sc_altflags |= HAS_24;
   1704 		}
   1705 		enc = AUDIO_ENCODING_SLINEAR_LE;
   1706 		format_str = "pcm";
   1707 		break;
   1708 	case UA_FMT_PCM8:
   1709 		enc = AUDIO_ENCODING_ULINEAR_LE;
   1710 		sc->sc_altflags |= HAS_8U;
   1711 		format_str = "pcm8";
   1712 		break;
   1713 	case UA_FMT_ALAW:
   1714 		enc = AUDIO_ENCODING_ALAW;
   1715 		sc->sc_altflags |= HAS_ALAW;
   1716 		format_str = "alaw";
   1717 		break;
   1718 	case UA_FMT_MULAW:
   1719 		enc = AUDIO_ENCODING_ULAW;
   1720 		sc->sc_altflags |= HAS_MULAW;
   1721 		format_str = "mulaw";
   1722 		break;
   1723 	case UA_FMT_IEEE_FLOAT:
   1724 	default:
   1725 		aprint_error_dev(sc->sc_dev,
   1726 		    "ignored setting with format %d\n", format);
   1727 		return USBD_NORMAL_COMPLETION;
   1728 	}
   1729 #ifdef UAUDIO_DEBUG
   1730 	aprint_debug_dev(sc->sc_dev, "%s: %dch, %d/%dbit, %s,",
   1731 	       dir == UE_DIR_IN ? "recording" : "playback",
   1732 	       chan, prec, asf1d->bSubFrameSize * 8, format_str);
   1733 	if (asf1d->bSamFreqType == UA_SAMP_CONTNUOUS) {
   1734 		aprint_debug(" %d-%dHz\n", UA_SAMP_LO(asf1d),
   1735 		    UA_SAMP_HI(asf1d));
   1736 	} else {
   1737 		int r;
   1738 		aprint_debug(" %d", UA_GETSAMP(asf1d, 0));
   1739 		for (r = 1; r < asf1d->bSamFreqType; r++)
   1740 			aprint_debug(",%d", UA_GETSAMP(asf1d, r));
   1741 		aprint_debug("Hz\n");
   1742 	}
   1743 #endif
   1744 	ai.alt = id->bAlternateSetting;
   1745 	ai.encoding = enc;
   1746 	ai.attributes = sed->bmAttributes;
   1747 	ai.idesc = id;
   1748 	ai.edesc = ed;
   1749 	ai.edesc1 = epdesc1;
   1750 	ai.asf1desc = asf1d;
   1751 	ai.sc_busy = 0;
   1752 	ai.aformat = NULL;
   1753 	ai.ifaceh = NULL;
   1754 	uaudio_add_alt(sc, &ai);
   1755 #ifdef UAUDIO_DEBUG
   1756 	if (ai.attributes & UA_SED_FREQ_CONTROL)
   1757 		DPRINTFN(1, "%s", "FREQ_CONTROL\n");
   1758 	if (ai.attributes & UA_SED_PITCH_CONTROL)
   1759 		DPRINTFN(1, "%s", "PITCH_CONTROL\n");
   1760 #endif
   1761 	sc->sc_mode |= (dir == UE_DIR_OUT) ? AUMODE_PLAY : AUMODE_RECORD;
   1762 
   1763 	return USBD_NORMAL_COMPLETION;
   1764 }
   1765 #undef offs
   1766 
   1767 Static usbd_status
   1768 uaudio_identify_as(struct uaudio_softc *sc,
   1769 		   const usb_config_descriptor_t *cdesc)
   1770 {
   1771 	const usb_interface_descriptor_t *id;
   1772 	const char *tbuf;
   1773 	struct audio_format *auf;
   1774 	const struct usb_audio_streaming_type1_descriptor *t1desc;
   1775 	int size, offs;
   1776 	int i, j;
   1777 
   1778 	size = UGETW(cdesc->wTotalLength);
   1779 	tbuf = (const char *)cdesc;
   1780 
   1781 	/* Locate the AudioStreaming interface descriptor. */
   1782 	offs = 0;
   1783 	id = uaudio_find_iface(tbuf, size, &offs, UISUBCLASS_AUDIOSTREAM);
   1784 	if (id == NULL)
   1785 		return USBD_INVAL;
   1786 
   1787 	/* Loop through all the alternate settings. */
   1788 	while (offs <= size) {
   1789 		DPRINTFN(2, "interface=%d offset=%d\n",
   1790 		    id->bInterfaceNumber, offs);
   1791 		switch (id->bNumEndpoints) {
   1792 		case 0:
   1793 			DPRINTFN(2, "AS null alt=%d\n",
   1794 				     id->bAlternateSetting);
   1795 			sc->sc_nullalt = id->bAlternateSetting;
   1796 			break;
   1797 		case 1:
   1798 #ifdef UAUDIO_MULTIPLE_ENDPOINTS
   1799 		case 2:
   1800 #endif
   1801 			uaudio_process_as(sc, tbuf, &offs, size, id);
   1802 			break;
   1803 		default:
   1804 			aprint_error_dev(sc->sc_dev,
   1805 			    "ignored audio interface with %d endpoints\n",
   1806 			     id->bNumEndpoints);
   1807 			break;
   1808 		}
   1809 		id = uaudio_find_iface(tbuf, size, &offs,UISUBCLASS_AUDIOSTREAM);
   1810 		if (id == NULL)
   1811 			break;
   1812 	}
   1813 	if (offs > size)
   1814 		return USBD_INVAL;
   1815 	DPRINTF("%d alts available\n", sc->sc_nalts);
   1816 
   1817 	if (sc->sc_mode == 0) {
   1818 		aprint_error_dev(sc->sc_dev, "no usable endpoint found\n");
   1819 		return USBD_INVAL;
   1820 	}
   1821 
   1822 	/* build audio_format array */
   1823 	sc->sc_formats = malloc(sizeof(struct audio_format) * sc->sc_nalts,
   1824 				M_USBDEV, M_NOWAIT);
   1825 	if (sc->sc_formats == NULL)
   1826 		return USBD_NOMEM;
   1827 	sc->sc_nformats = sc->sc_nalts;
   1828 	for (i = 0; i < sc->sc_nalts; i++) {
   1829 		auf = &sc->sc_formats[i];
   1830 		t1desc = sc->sc_alts[i].asf1desc;
   1831 		auf->driver_data = NULL;
   1832 		if (UE_GET_DIR(sc->sc_alts[i].edesc->bEndpointAddress) == UE_DIR_OUT)
   1833 			auf->mode = AUMODE_PLAY;
   1834 		else
   1835 			auf->mode = AUMODE_RECORD;
   1836 		auf->encoding = sc->sc_alts[i].encoding;
   1837 		auf->validbits = t1desc->bBitResolution;
   1838 		auf->precision = t1desc->bSubFrameSize * 8;
   1839 		auf->channels = t1desc->bNrChannels;
   1840 		auf->channel_mask = sc->sc_channel_config;
   1841 		auf->frequency_type = t1desc->bSamFreqType;
   1842 		if (t1desc->bSamFreqType == UA_SAMP_CONTNUOUS) {
   1843 			auf->frequency[0] = UA_SAMP_LO(t1desc);
   1844 			auf->frequency[1] = UA_SAMP_HI(t1desc);
   1845 		} else {
   1846 			for (j = 0; j  < t1desc->bSamFreqType; j++) {
   1847 				if (j >= AUFMT_MAX_FREQUENCIES) {
   1848 					aprint_error("%s: please increase "
   1849 					       "AUFMT_MAX_FREQUENCIES to %d\n",
   1850 					       __func__, t1desc->bSamFreqType);
   1851 					auf->frequency_type =
   1852 					    AUFMT_MAX_FREQUENCIES;
   1853 					break;
   1854 				}
   1855 				auf->frequency[j] = UA_GETSAMP(t1desc, j);
   1856 			}
   1857 		}
   1858 		sc->sc_alts[i].aformat = auf;
   1859 	}
   1860 
   1861 	if (0 != auconv_create_encodings(sc->sc_formats, sc->sc_nformats,
   1862 					 &sc->sc_encodings)) {
   1863 		free(sc->sc_formats, M_DEVBUF);
   1864 		sc->sc_formats = NULL;
   1865 		return ENOMEM;
   1866 	}
   1867 
   1868 	return USBD_NORMAL_COMPLETION;
   1869 }
   1870 
   1871 Static usbd_status
   1872 uaudio_identify_ac(struct uaudio_softc *sc, const usb_config_descriptor_t *cdesc)
   1873 {
   1874 	struct io_terminal* iot;
   1875 	const usb_interface_descriptor_t *id;
   1876 	const struct usb_audio_control_descriptor *acdp;
   1877 	const uaudio_cs_descriptor_t *dp;
   1878 	const struct usb_audio_output_terminal *pot;
   1879 	struct terminal_list *tml;
   1880 	const char *tbuf, *ibuf, *ibufend;
   1881 	int size, offs, ndps, i, j;
   1882 
   1883 	size = UGETW(cdesc->wTotalLength);
   1884 	tbuf = (const char *)cdesc;
   1885 
   1886 	/* Locate the AudioControl interface descriptor. */
   1887 	offs = 0;
   1888 	id = uaudio_find_iface(tbuf, size, &offs, UISUBCLASS_AUDIOCONTROL);
   1889 	if (id == NULL)
   1890 		return USBD_INVAL;
   1891 	if (offs + sizeof *acdp > size)
   1892 		return USBD_INVAL;
   1893 	sc->sc_ac_iface = id->bInterfaceNumber;
   1894 	DPRINTFN(2,"AC interface is %d\n", sc->sc_ac_iface);
   1895 
   1896 	/* A class-specific AC interface header should follow. */
   1897 	ibuf = tbuf + offs;
   1898 	ibufend = tbuf + size;
   1899 	acdp = (const struct usb_audio_control_descriptor *)ibuf;
   1900 	if (acdp->bDescriptorType != UDESC_CS_INTERFACE ||
   1901 	    acdp->bDescriptorSubtype != UDESCSUB_AC_HEADER)
   1902 		return USBD_INVAL;
   1903 
   1904 	if (!(usbd_get_quirks(sc->sc_udev)->uq_flags & UQ_BAD_ADC) &&
   1905 	     UGETW(acdp->bcdADC) != UAUDIO_VERSION)
   1906 		return USBD_INVAL;
   1907 
   1908 	sc->sc_audio_rev = UGETW(acdp->bcdADC);
   1909 	DPRINTFN(2, "found AC header, vers=%03x\n", sc->sc_audio_rev);
   1910 
   1911 	sc->sc_nullalt = -1;
   1912 
   1913 	/* Scan through all the AC specific descriptors */
   1914 	dp = (const uaudio_cs_descriptor_t *)ibuf;
   1915 	ndps = 0;
   1916 	iot = malloc(sizeof(struct io_terminal) * 256, M_TEMP, M_NOWAIT | M_ZERO);
   1917 	if (iot == NULL) {
   1918 		aprint_error("%s: no memory\n", __func__);
   1919 		return USBD_NOMEM;
   1920 	}
   1921 	for (;;) {
   1922 		ibuf += dp->bLength;
   1923 		if (ibuf >= ibufend)
   1924 			break;
   1925 		dp = (const uaudio_cs_descriptor_t *)ibuf;
   1926 		if (ibuf + dp->bLength > ibufend) {
   1927 			free(iot, M_TEMP);
   1928 			return USBD_INVAL;
   1929 		}
   1930 		if (dp->bDescriptorType != UDESC_CS_INTERFACE)
   1931 			break;
   1932 		i = ((const struct usb_audio_input_terminal *)dp)->bTerminalId;
   1933 		iot[i].d.desc = dp;
   1934 		if (i > ndps)
   1935 			ndps = i;
   1936 	}
   1937 	ndps++;
   1938 
   1939 	/* construct io_terminal */
   1940 	for (i = 0; i < ndps; i++) {
   1941 		dp = iot[i].d.desc;
   1942 		if (dp == NULL)
   1943 			continue;
   1944 		if (dp->bDescriptorSubtype != UDESCSUB_AC_OUTPUT)
   1945 			continue;
   1946 		pot = iot[i].d.ot;
   1947 		tml = uaudio_io_terminaltype(UGETW(pot->wTerminalType), iot, i);
   1948 		if (tml != NULL)
   1949 			free(tml, M_TEMP);
   1950 	}
   1951 
   1952 #ifdef UAUDIO_DEBUG
   1953 	for (i = 0; i < 256; i++) {
   1954 		struct usb_audio_cluster cluster;
   1955 
   1956 		if (iot[i].d.desc == NULL)
   1957 			continue;
   1958 		printf("id %d:\t", i);
   1959 		switch (iot[i].d.desc->bDescriptorSubtype) {
   1960 		case UDESCSUB_AC_INPUT:
   1961 			printf("AC_INPUT type=%s\n", uaudio_get_terminal_name
   1962 				  (UGETW(iot[i].d.it->wTerminalType)));
   1963 			printf("\t");
   1964 			cluster = uaudio_get_cluster(i, iot);
   1965 			uaudio_dump_cluster(&cluster);
   1966 			printf("\n");
   1967 			break;
   1968 		case UDESCSUB_AC_OUTPUT:
   1969 			printf("AC_OUTPUT type=%s ", uaudio_get_terminal_name
   1970 				  (UGETW(iot[i].d.ot->wTerminalType)));
   1971 			printf("src=%d\n", iot[i].d.ot->bSourceId);
   1972 			break;
   1973 		case UDESCSUB_AC_MIXER:
   1974 			printf("AC_MIXER src=");
   1975 			for (j = 0; j < iot[i].d.mu->bNrInPins; j++)
   1976 				printf("%d ", iot[i].d.mu->baSourceId[j]);
   1977 			printf("\n\t");
   1978 			cluster = uaudio_get_cluster(i, iot);
   1979 			uaudio_dump_cluster(&cluster);
   1980 			printf("\n");
   1981 			break;
   1982 		case UDESCSUB_AC_SELECTOR:
   1983 			printf("AC_SELECTOR src=");
   1984 			for (j = 0; j < iot[i].d.su->bNrInPins; j++)
   1985 				printf("%d ", iot[i].d.su->baSourceId[j]);
   1986 			printf("\n");
   1987 			break;
   1988 		case UDESCSUB_AC_FEATURE:
   1989 			printf("AC_FEATURE src=%d\n", iot[i].d.fu->bSourceId);
   1990 			break;
   1991 		case UDESCSUB_AC_PROCESSING:
   1992 			printf("AC_PROCESSING src=");
   1993 			for (j = 0; j < iot[i].d.pu->bNrInPins; j++)
   1994 				printf("%d ", iot[i].d.pu->baSourceId[j]);
   1995 			printf("\n\t");
   1996 			cluster = uaudio_get_cluster(i, iot);
   1997 			uaudio_dump_cluster(&cluster);
   1998 			printf("\n");
   1999 			break;
   2000 		case UDESCSUB_AC_EXTENSION:
   2001 			printf("AC_EXTENSION src=");
   2002 			for (j = 0; j < iot[i].d.eu->bNrInPins; j++)
   2003 				printf("%d ", iot[i].d.eu->baSourceId[j]);
   2004 			printf("\n\t");
   2005 			cluster = uaudio_get_cluster(i, iot);
   2006 			uaudio_dump_cluster(&cluster);
   2007 			printf("\n");
   2008 			break;
   2009 		default:
   2010 			printf("unknown audio control (subtype=%d)\n",
   2011 				  iot[i].d.desc->bDescriptorSubtype);
   2012 		}
   2013 		for (j = 0; j < iot[i].inputs_size; j++) {
   2014 			int k;
   2015 			printf("\tinput%d: ", j);
   2016 			tml = iot[i].inputs[j];
   2017 			if (tml == NULL) {
   2018 				printf("NULL\n");
   2019 				continue;
   2020 			}
   2021 			for (k = 0; k < tml->size; k++)
   2022 				printf("%s ", uaudio_get_terminal_name
   2023 					  (tml->terminals[k]));
   2024 			printf("\n");
   2025 		}
   2026 		printf("\toutput: ");
   2027 		tml = iot[i].output;
   2028 		for (j = 0; j < tml->size; j++)
   2029 			printf("%s ", uaudio_get_terminal_name(tml->terminals[j]));
   2030 		printf("\n");
   2031 	}
   2032 #endif
   2033 
   2034 	for (i = 0; i < ndps; i++) {
   2035 		dp = iot[i].d.desc;
   2036 		if (dp == NULL)
   2037 			continue;
   2038 		DPRINTF("id=%d subtype=%d\n", i, dp->bDescriptorSubtype);
   2039 		switch (dp->bDescriptorSubtype) {
   2040 		case UDESCSUB_AC_HEADER:
   2041 			aprint_error("uaudio_identify_ac: unexpected AC header\n");
   2042 			break;
   2043 		case UDESCSUB_AC_INPUT:
   2044 			uaudio_add_input(sc, iot, i);
   2045 			break;
   2046 		case UDESCSUB_AC_OUTPUT:
   2047 			uaudio_add_output(sc, iot, i);
   2048 			break;
   2049 		case UDESCSUB_AC_MIXER:
   2050 			uaudio_add_mixer(sc, iot, i);
   2051 			break;
   2052 		case UDESCSUB_AC_SELECTOR:
   2053 			uaudio_add_selector(sc, iot, i);
   2054 			break;
   2055 		case UDESCSUB_AC_FEATURE:
   2056 			uaudio_add_feature(sc, iot, i);
   2057 			break;
   2058 		case UDESCSUB_AC_PROCESSING:
   2059 			uaudio_add_processing(sc, iot, i);
   2060 			break;
   2061 		case UDESCSUB_AC_EXTENSION:
   2062 			uaudio_add_extension(sc, iot, i);
   2063 			break;
   2064 		default:
   2065 			aprint_error(
   2066 			    "uaudio_identify_ac: bad AC desc subtype=0x%02x\n",
   2067 			    dp->bDescriptorSubtype);
   2068 			break;
   2069 		}
   2070 	}
   2071 
   2072 	/* delete io_terminal */
   2073 	for (i = 0; i < 256; i++) {
   2074 		if (iot[i].d.desc == NULL)
   2075 			continue;
   2076 		if (iot[i].inputs != NULL) {
   2077 			for (j = 0; j < iot[i].inputs_size; j++) {
   2078 				if (iot[i].inputs[j] != NULL)
   2079 					free(iot[i].inputs[j], M_TEMP);
   2080 			}
   2081 			free(iot[i].inputs, M_TEMP);
   2082 		}
   2083 		if (iot[i].output != NULL)
   2084 			free(iot[i].output, M_TEMP);
   2085 		iot[i].d.desc = NULL;
   2086 	}
   2087 	free(iot, M_TEMP);
   2088 
   2089 	return USBD_NORMAL_COMPLETION;
   2090 }
   2091 
   2092 Static int
   2093 uaudio_query_devinfo(void *addr, mixer_devinfo_t *mi)
   2094 {
   2095 	struct uaudio_softc *sc;
   2096 	struct mixerctl *mc;
   2097 	int n, nctls, i;
   2098 
   2099 	DPRINTFN(7, "index=%d\n", mi->index);
   2100 	sc = addr;
   2101 	if (sc->sc_dying)
   2102 		return EIO;
   2103 
   2104 	n = mi->index;
   2105 	nctls = sc->sc_nctls;
   2106 
   2107 	switch (n) {
   2108 	case UAC_OUTPUT:
   2109 		mi->type = AUDIO_MIXER_CLASS;
   2110 		mi->mixer_class = UAC_OUTPUT;
   2111 		mi->next = mi->prev = AUDIO_MIXER_LAST;
   2112 		strlcpy(mi->label.name, AudioCoutputs, sizeof(mi->label.name));
   2113 		return 0;
   2114 	case UAC_INPUT:
   2115 		mi->type = AUDIO_MIXER_CLASS;
   2116 		mi->mixer_class = UAC_INPUT;
   2117 		mi->next = mi->prev = AUDIO_MIXER_LAST;
   2118 		strlcpy(mi->label.name, AudioCinputs, sizeof(mi->label.name));
   2119 		return 0;
   2120 	case UAC_EQUAL:
   2121 		mi->type = AUDIO_MIXER_CLASS;
   2122 		mi->mixer_class = UAC_EQUAL;
   2123 		mi->next = mi->prev = AUDIO_MIXER_LAST;
   2124 		strlcpy(mi->label.name, AudioCequalization,
   2125 		    sizeof(mi->label.name));
   2126 		return 0;
   2127 	case UAC_RECORD:
   2128 		mi->type = AUDIO_MIXER_CLASS;
   2129 		mi->mixer_class = UAC_RECORD;
   2130 		mi->next = mi->prev = AUDIO_MIXER_LAST;
   2131 		strlcpy(mi->label.name, AudioCrecord, sizeof(mi->label.name));
   2132 		return 0;
   2133 	default:
   2134 		break;
   2135 	}
   2136 
   2137 	n -= UAC_NCLASSES;
   2138 	if (n < 0 || n >= nctls)
   2139 		return ENXIO;
   2140 
   2141 	mc = &sc->sc_ctls[n];
   2142 	strlcpy(mi->label.name, mc->ctlname, sizeof(mi->label.name));
   2143 	mi->mixer_class = mc->class;
   2144 	mi->next = mi->prev = AUDIO_MIXER_LAST;	/* XXX */
   2145 	switch (mc->type) {
   2146 	case MIX_ON_OFF:
   2147 		mi->type = AUDIO_MIXER_ENUM;
   2148 		mi->un.e.num_mem = 2;
   2149 		strlcpy(mi->un.e.member[0].label.name, AudioNoff,
   2150 		    sizeof(mi->un.e.member[0].label.name));
   2151 		mi->un.e.member[0].ord = 0;
   2152 		strlcpy(mi->un.e.member[1].label.name, AudioNon,
   2153 		    sizeof(mi->un.e.member[1].label.name));
   2154 		mi->un.e.member[1].ord = 1;
   2155 		break;
   2156 	case MIX_SELECTOR:
   2157 		mi->type = AUDIO_MIXER_ENUM;
   2158 		mi->un.e.num_mem = mc->maxval - mc->minval + 1;
   2159 		for (i = 0; i <= mc->maxval - mc->minval; i++) {
   2160 			snprintf(mi->un.e.member[i].label.name,
   2161 				 sizeof(mi->un.e.member[i].label.name),
   2162 				 "%d", i + mc->minval);
   2163 			mi->un.e.member[i].ord = i + mc->minval;
   2164 		}
   2165 		break;
   2166 	default:
   2167 		mi->type = AUDIO_MIXER_VALUE;
   2168 		strncpy(mi->un.v.units.name, mc->ctlunit, MAX_AUDIO_DEV_LEN);
   2169 		mi->un.v.num_channels = mc->nchan;
   2170 		mi->un.v.delta = mc->delta;
   2171 		break;
   2172 	}
   2173 	return 0;
   2174 }
   2175 
   2176 Static int
   2177 uaudio_open(void *addr, int flags)
   2178 {
   2179 	struct uaudio_softc *sc;
   2180 
   2181 	sc = addr;
   2182 	DPRINTF("sc=%p\n", sc);
   2183 	if (sc->sc_dying)
   2184 		return EIO;
   2185 
   2186 	if ((flags & FWRITE) && !(sc->sc_mode & AUMODE_PLAY))
   2187 		return EACCES;
   2188 	if ((flags & FREAD) && !(sc->sc_mode & AUMODE_RECORD))
   2189 		return EACCES;
   2190 
   2191 	return 0;
   2192 }
   2193 
   2194 /*
   2195  * Close function is called at splaudio().
   2196  */
   2197 Static void
   2198 uaudio_close(void *addr)
   2199 {
   2200 }
   2201 
   2202 Static int
   2203 uaudio_drain(void *addr)
   2204 {
   2205 	struct uaudio_softc *sc = addr;
   2206 
   2207 	KASSERT(mutex_owned(&sc->sc_intr_lock));
   2208 
   2209 	kpause("uaudiodr", false,
   2210 	    mstohz(UAUDIO_NCHANBUFS * UAUDIO_NFRAMES), &sc->sc_intr_lock);
   2211 
   2212 	return 0;
   2213 }
   2214 
   2215 Static int
   2216 uaudio_halt_out_dma(void *addr)
   2217 {
   2218 	struct uaudio_softc *sc = addr;
   2219 
   2220 	DPRINTF("%s", "enter\n");
   2221 
   2222 	mutex_spin_exit(&sc->sc_intr_lock);
   2223 	if (sc->sc_playchan.pipe != NULL) {
   2224 		uaudio_chan_close(sc, &sc->sc_playchan);
   2225 		uaudio_chan_free_buffers(sc, &sc->sc_playchan);
   2226 		sc->sc_playchan.intr = NULL;
   2227 	}
   2228 	mutex_spin_enter(&sc->sc_intr_lock);
   2229 
   2230 	return 0;
   2231 }
   2232 
   2233 Static int
   2234 uaudio_halt_in_dma(void *addr)
   2235 {
   2236 	struct uaudio_softc *sc = addr;
   2237 
   2238 	DPRINTF("%s", "enter\n");
   2239 
   2240 	mutex_spin_exit(&sc->sc_intr_lock);
   2241 	if (sc->sc_recchan.pipe != NULL) {
   2242 		uaudio_chan_close(sc, &sc->sc_recchan);
   2243 		uaudio_chan_free_buffers(sc, &sc->sc_recchan);
   2244 		sc->sc_recchan.intr = NULL;
   2245 	}
   2246 	mutex_spin_enter(&sc->sc_intr_lock);
   2247 
   2248 	return 0;
   2249 }
   2250 
   2251 Static int
   2252 uaudio_getdev(void *addr, struct audio_device *retp)
   2253 {
   2254 	struct uaudio_softc *sc;
   2255 
   2256 	DPRINTF("%s", "\n");
   2257 	sc = addr;
   2258 	if (sc->sc_dying)
   2259 		return EIO;
   2260 
   2261 	*retp = sc->sc_adev;
   2262 	return 0;
   2263 }
   2264 
   2265 /*
   2266  * Make sure the block size is large enough to hold all outstanding transfers.
   2267  */
   2268 Static int
   2269 uaudio_round_blocksize(void *addr, int blk,
   2270 		       int mode, const audio_params_t *param)
   2271 {
   2272 	struct uaudio_softc *sc;
   2273 	int b;
   2274 
   2275 	sc = addr;
   2276 	DPRINTF("blk=%d mode=%s\n", blk,
   2277 	    mode == AUMODE_PLAY ? "AUMODE_PLAY" : "AUMODE_RECORD");
   2278 
   2279 	/* chan.bytes_per_frame can be 0. */
   2280 	if (mode == AUMODE_PLAY || sc->sc_recchan.bytes_per_frame <= 0) {
   2281 		b = param->sample_rate * UAUDIO_NFRAMES * UAUDIO_NCHANBUFS;
   2282 
   2283 		/*
   2284 		 * This does not make accurate value in the case
   2285 		 * of b % USB_FRAMES_PER_SECOND != 0
   2286 		 */
   2287 		b /= USB_FRAMES_PER_SECOND;
   2288 
   2289 		b *= param->precision / 8 * param->channels;
   2290 	} else {
   2291 		/*
   2292 		 * use wMaxPacketSize in bytes_per_frame.
   2293 		 * See uaudio_set_params() and uaudio_chan_init()
   2294 		 */
   2295 		b = sc->sc_recchan.bytes_per_frame
   2296 		    * UAUDIO_NFRAMES * UAUDIO_NCHANBUFS;
   2297 	}
   2298 
   2299 	if (b <= 0)
   2300 		b = 1;
   2301 	blk = blk <= b ? b : blk / b * b;
   2302 
   2303 #ifdef DIAGNOSTIC
   2304 	if (blk <= 0) {
   2305 		aprint_debug("uaudio_round_blocksize: blk=%d\n", blk);
   2306 		blk = 512;
   2307 	}
   2308 #endif
   2309 
   2310 	DPRINTF("resultant blk=%d\n", blk);
   2311 	return blk;
   2312 }
   2313 
   2314 Static int
   2315 uaudio_get_props(void *addr)
   2316 {
   2317 	return AUDIO_PROP_FULLDUPLEX | AUDIO_PROP_INDEPENDENT;
   2318 
   2319 }
   2320 
   2321 Static void
   2322 uaudio_get_locks(void *addr, kmutex_t **intr, kmutex_t **thread)
   2323 {
   2324 	struct uaudio_softc *sc;
   2325 
   2326 	sc = addr;
   2327 	*intr = &sc->sc_intr_lock;
   2328 	*thread = &sc->sc_lock;
   2329 }
   2330 
   2331 Static int
   2332 uaudio_get(struct uaudio_softc *sc, int which, int type, int wValue,
   2333 	   int wIndex, int len)
   2334 {
   2335 	usb_device_request_t req;
   2336 	u_int8_t data[4];
   2337 	usbd_status err;
   2338 	int val;
   2339 
   2340 	if (wValue == -1)
   2341 		return 0;
   2342 
   2343 	req.bmRequestType = type;
   2344 	req.bRequest = which;
   2345 	USETW(req.wValue, wValue);
   2346 	USETW(req.wIndex, wIndex);
   2347 	USETW(req.wLength, len);
   2348 	DPRINTFN(2,"type=0x%02x req=0x%02x wValue=0x%04x "
   2349 		    "wIndex=0x%04x len=%d\n",
   2350 		    type, which, wValue, wIndex, len);
   2351 	err = usbd_do_request(sc->sc_udev, &req, data);
   2352 	if (err) {
   2353 		DPRINTF("err=%s\n", usbd_errstr(err));
   2354 		return -1;
   2355 	}
   2356 	switch (len) {
   2357 	case 1:
   2358 		val = data[0];
   2359 		break;
   2360 	case 2:
   2361 		val = data[0] | (data[1] << 8);
   2362 		break;
   2363 	default:
   2364 		DPRINTF("bad length=%d\n", len);
   2365 		return -1;
   2366 	}
   2367 	DPRINTFN(2,"val=%d\n", val);
   2368 	return val;
   2369 }
   2370 
   2371 Static void
   2372 uaudio_set(struct uaudio_softc *sc, int which, int type, int wValue,
   2373 	   int wIndex, int len, int val)
   2374 {
   2375 	usb_device_request_t req;
   2376 	u_int8_t data[4];
   2377 	int err __unused;
   2378 
   2379 	if (wValue == -1)
   2380 		return;
   2381 
   2382 	req.bmRequestType = type;
   2383 	req.bRequest = which;
   2384 	USETW(req.wValue, wValue);
   2385 	USETW(req.wIndex, wIndex);
   2386 	USETW(req.wLength, len);
   2387 	switch (len) {
   2388 	case 1:
   2389 		data[0] = val;
   2390 		break;
   2391 	case 2:
   2392 		data[0] = val;
   2393 		data[1] = val >> 8;
   2394 		break;
   2395 	default:
   2396 		return;
   2397 	}
   2398 	DPRINTFN(2,"type=0x%02x req=0x%02x wValue=0x%04x "
   2399 		    "wIndex=0x%04x len=%d, val=%d\n",
   2400 		    type, which, wValue, wIndex, len, val & 0xffff);
   2401 	err = usbd_do_request(sc->sc_udev, &req, data);
   2402 #ifdef UAUDIO_DEBUG
   2403 	if (err)
   2404 		DPRINTF("err=%d\n", err);
   2405 #endif
   2406 }
   2407 
   2408 Static int
   2409 uaudio_signext(int type, int val)
   2410 {
   2411 	if (!MIX_UNSIGNED(type)) {
   2412 		if (MIX_SIZE(type) == 2)
   2413 			val = (int16_t)val;
   2414 		else
   2415 			val = (int8_t)val;
   2416 	}
   2417 	return val;
   2418 }
   2419 
   2420 Static int
   2421 uaudio_value2bsd(struct mixerctl *mc, int val)
   2422 {
   2423 	DPRINTFN(5, "type=%03x val=%d min=%d max=%d ",
   2424 		     mc->type, val, mc->minval, mc->maxval);
   2425 	if (mc->type == MIX_ON_OFF) {
   2426 		val = (val != 0);
   2427 	} else if (mc->type == MIX_SELECTOR) {
   2428 		if (val < mc->minval || val > mc->maxval)
   2429 			val = mc->minval;
   2430 	} else
   2431 		val = ((uaudio_signext(mc->type, val) - mc->minval) * 255
   2432 			+ mc->mul/2) / mc->mul;
   2433 	DPRINTFN_CLEAN(5, "val'=%d\n", val);
   2434 	return val;
   2435 }
   2436 
   2437 int
   2438 uaudio_bsd2value(struct mixerctl *mc, int val)
   2439 {
   2440 	DPRINTFN(5,"type=%03x val=%d min=%d max=%d ",
   2441 		    mc->type, val, mc->minval, mc->maxval);
   2442 	if (mc->type == MIX_ON_OFF) {
   2443 		val = (val != 0);
   2444 	} else if (mc->type == MIX_SELECTOR) {
   2445 		if (val < mc->minval || val > mc->maxval)
   2446 			val = mc->minval;
   2447 	} else
   2448 		val = (val + mc->delta/2) * mc->mul / 255 + mc->minval;
   2449 	DPRINTFN_CLEAN(5, "val'=%d\n", val);
   2450 	return val;
   2451 }
   2452 
   2453 Static int
   2454 uaudio_ctl_get(struct uaudio_softc *sc, int which, struct mixerctl *mc,
   2455 	       int chan)
   2456 {
   2457 	int val;
   2458 
   2459 	DPRINTFN(5,"which=%d chan=%d\n", which, chan);
   2460 	mutex_exit(&sc->sc_lock);
   2461 	val = uaudio_get(sc, which, UT_READ_CLASS_INTERFACE, mc->wValue[chan],
   2462 			 mc->wIndex, MIX_SIZE(mc->type));
   2463 	mutex_enter(&sc->sc_lock);
   2464 	return uaudio_value2bsd(mc, val);
   2465 }
   2466 
   2467 Static void
   2468 uaudio_ctl_set(struct uaudio_softc *sc, int which, struct mixerctl *mc,
   2469 	       int chan, int val)
   2470 {
   2471 
   2472 	val = uaudio_bsd2value(mc, val);
   2473 	mutex_exit(&sc->sc_lock);
   2474 	uaudio_set(sc, which, UT_WRITE_CLASS_INTERFACE, mc->wValue[chan],
   2475 		   mc->wIndex, MIX_SIZE(mc->type), val);
   2476 	mutex_enter(&sc->sc_lock);
   2477 }
   2478 
   2479 Static int
   2480 uaudio_mixer_get_port(void *addr, mixer_ctrl_t *cp)
   2481 {
   2482 	struct uaudio_softc *sc;
   2483 	struct mixerctl *mc;
   2484 	int i, n, vals[MIX_MAX_CHAN], val;
   2485 
   2486 	DPRINTFN(2, "index=%d\n", cp->dev);
   2487 	sc = addr;
   2488 	if (sc->sc_dying)
   2489 		return EIO;
   2490 
   2491 	n = cp->dev - UAC_NCLASSES;
   2492 	if (n < 0 || n >= sc->sc_nctls)
   2493 		return ENXIO;
   2494 	mc = &sc->sc_ctls[n];
   2495 
   2496 	if (mc->type == MIX_ON_OFF) {
   2497 		if (cp->type != AUDIO_MIXER_ENUM)
   2498 			return EINVAL;
   2499 		cp->un.ord = uaudio_ctl_get(sc, GET_CUR, mc, 0);
   2500 	} else if (mc->type == MIX_SELECTOR) {
   2501 		if (cp->type != AUDIO_MIXER_ENUM)
   2502 			return EINVAL;
   2503 		cp->un.ord = uaudio_ctl_get(sc, GET_CUR, mc, 0);
   2504 	} else {
   2505 		if (cp->type != AUDIO_MIXER_VALUE)
   2506 			return EINVAL;
   2507 		if (cp->un.value.num_channels != 1 &&
   2508 		    cp->un.value.num_channels != mc->nchan)
   2509 			return EINVAL;
   2510 		for (i = 0; i < mc->nchan; i++)
   2511 			vals[i] = uaudio_ctl_get(sc, GET_CUR, mc, i);
   2512 		if (cp->un.value.num_channels == 1 && mc->nchan != 1) {
   2513 			for (val = 0, i = 0; i < mc->nchan; i++)
   2514 				val += vals[i];
   2515 			vals[0] = val / mc->nchan;
   2516 		}
   2517 		for (i = 0; i < cp->un.value.num_channels; i++)
   2518 			cp->un.value.level[i] = vals[i];
   2519 	}
   2520 
   2521 	return 0;
   2522 }
   2523 
   2524 Static int
   2525 uaudio_mixer_set_port(void *addr, mixer_ctrl_t *cp)
   2526 {
   2527 	struct uaudio_softc *sc;
   2528 	struct mixerctl *mc;
   2529 	int i, n, vals[MIX_MAX_CHAN];
   2530 
   2531 	DPRINTFN(2, "index = %d\n", cp->dev);
   2532 	sc = addr;
   2533 	if (sc->sc_dying)
   2534 		return EIO;
   2535 
   2536 	n = cp->dev - UAC_NCLASSES;
   2537 	if (n < 0 || n >= sc->sc_nctls)
   2538 		return ENXIO;
   2539 	mc = &sc->sc_ctls[n];
   2540 
   2541 	if (mc->type == MIX_ON_OFF) {
   2542 		if (cp->type != AUDIO_MIXER_ENUM)
   2543 			return EINVAL;
   2544 		uaudio_ctl_set(sc, SET_CUR, mc, 0, cp->un.ord);
   2545 	} else if (mc->type == MIX_SELECTOR) {
   2546 		if (cp->type != AUDIO_MIXER_ENUM)
   2547 			return EINVAL;
   2548 		uaudio_ctl_set(sc, SET_CUR, mc, 0, cp->un.ord);
   2549 	} else {
   2550 		if (cp->type != AUDIO_MIXER_VALUE)
   2551 			return EINVAL;
   2552 		if (cp->un.value.num_channels == 1)
   2553 			for (i = 0; i < mc->nchan; i++)
   2554 				vals[i] = cp->un.value.level[0];
   2555 		else if (cp->un.value.num_channels == mc->nchan)
   2556 			for (i = 0; i < mc->nchan; i++)
   2557 				vals[i] = cp->un.value.level[i];
   2558 		else
   2559 			return EINVAL;
   2560 		for (i = 0; i < mc->nchan; i++)
   2561 			uaudio_ctl_set(sc, SET_CUR, mc, i, vals[i]);
   2562 	}
   2563 	return 0;
   2564 }
   2565 
   2566 Static int
   2567 uaudio_trigger_input(void *addr, void *start, void *end, int blksize,
   2568 		     void (*intr)(void *), void *arg,
   2569 		     const audio_params_t *param)
   2570 {
   2571 	struct uaudio_softc *sc;
   2572 	struct chan *ch;
   2573 	usbd_status err;
   2574 	int i;
   2575 
   2576 	sc = addr;
   2577 	if (sc->sc_dying)
   2578 		return EIO;
   2579 
   2580 	DPRINTFN(3, "sc=%p start=%p end=%p "
   2581 		    "blksize=%d\n", sc, start, end, blksize);
   2582 	ch = &sc->sc_recchan;
   2583 	uaudio_chan_set_param(ch, start, end, blksize);
   2584 	DPRINTFN(3, "sample_size=%d bytes/frame=%d "
   2585 		    "fraction=0.%03d\n", ch->sample_size, ch->bytes_per_frame,
   2586 		    ch->fraction);
   2587 
   2588 	mutex_spin_exit(&sc->sc_intr_lock);
   2589 	err = uaudio_chan_alloc_buffers(sc, ch);
   2590 	if (err) {
   2591 		mutex_spin_enter(&sc->sc_intr_lock);
   2592 		return EIO;
   2593 	}
   2594 
   2595 	err = uaudio_chan_open(sc, ch);
   2596 	if (err) {
   2597 		uaudio_chan_free_buffers(sc, ch);
   2598 		mutex_spin_enter(&sc->sc_intr_lock);
   2599 		return EIO;
   2600 	}
   2601 
   2602 	ch->intr = intr;
   2603 	ch->arg = arg;
   2604 
   2605 	mutex_spin_exit(&sc->sc_intr_lock);
   2606 	for (i = 0; i < UAUDIO_NCHANBUFS-1; i++) /* XXX -1 shouldn't be needed */
   2607 		uaudio_chan_rtransfer(ch);
   2608 	mutex_spin_enter(&sc->sc_intr_lock);
   2609 
   2610 	return 0;
   2611 }
   2612 
   2613 Static int
   2614 uaudio_trigger_output(void *addr, void *start, void *end, int blksize,
   2615 		      void (*intr)(void *), void *arg,
   2616 		      const audio_params_t *param)
   2617 {
   2618 	struct uaudio_softc *sc;
   2619 	struct chan *ch;
   2620 	usbd_status err;
   2621 	int i;
   2622 
   2623 	sc = addr;
   2624 	if (sc->sc_dying)
   2625 		return EIO;
   2626 
   2627 	DPRINTFN(3, "sc=%p start=%p end=%p "
   2628 		    "blksize=%d\n", sc, start, end, blksize);
   2629 	ch = &sc->sc_playchan;
   2630 	uaudio_chan_set_param(ch, start, end, blksize);
   2631 	DPRINTFN(3, "sample_size=%d bytes/frame=%d "
   2632 		    "fraction=0.%03d\n", ch->sample_size, ch->bytes_per_frame,
   2633 		    ch->fraction);
   2634 
   2635 	mutex_spin_exit(&sc->sc_intr_lock);
   2636 	err = uaudio_chan_alloc_buffers(sc, ch);
   2637 	if (err) {
   2638 		mutex_spin_enter(&sc->sc_intr_lock);
   2639 		return EIO;
   2640 	}
   2641 
   2642 	err = uaudio_chan_open(sc, ch);
   2643 	if (err) {
   2644 		uaudio_chan_free_buffers(sc, ch);
   2645 		mutex_spin_enter(&sc->sc_intr_lock);
   2646 		return EIO;
   2647 	}
   2648 
   2649 	ch->intr = intr;
   2650 	ch->arg = arg;
   2651 
   2652 	mutex_spin_exit(&sc->sc_intr_lock);
   2653 	for (i = 0; i < UAUDIO_NCHANBUFS-1; i++) /* XXX */
   2654 		uaudio_chan_ptransfer(ch);
   2655 	mutex_spin_enter(&sc->sc_intr_lock);
   2656 
   2657 	return 0;
   2658 }
   2659 
   2660 /* Set up a pipe for a channel. */
   2661 Static usbd_status
   2662 uaudio_chan_open(struct uaudio_softc *sc, struct chan *ch)
   2663 {
   2664 	struct as_info *as;
   2665 	usb_device_descriptor_t *ddesc;
   2666 	int endpt;
   2667 	usbd_status err;
   2668 
   2669 	as = &sc->sc_alts[ch->altidx];
   2670 	endpt = as->edesc->bEndpointAddress;
   2671 	DPRINTF("endpt=0x%02x, speed=%d, alt=%d\n",
   2672 		 endpt, ch->sample_rate, as->alt);
   2673 
   2674 	/* Set alternate interface corresponding to the mode. */
   2675 	err = usbd_set_interface(as->ifaceh, as->alt);
   2676 	if (err)
   2677 		return err;
   2678 
   2679 	/*
   2680 	 * Roland SD-90 freezes by a SAMPLING_FREQ_CONTROL request.
   2681 	 */
   2682 	ddesc = usbd_get_device_descriptor(sc->sc_udev);
   2683 	if ((UGETW(ddesc->idVendor) != USB_VENDOR_ROLAND) &&
   2684 	    (UGETW(ddesc->idProduct) != USB_PRODUCT_ROLAND_SD90)) {
   2685 		err = uaudio_set_speed(sc, endpt, ch->sample_rate);
   2686 		if (err) {
   2687 			DPRINTF("set_speed failed err=%s\n", usbd_errstr(err));
   2688 		}
   2689 	}
   2690 
   2691 	DPRINTF("create pipe to 0x%02x\n", endpt);
   2692 	err = usbd_open_pipe(as->ifaceh, endpt, USBD_MPSAFE, &ch->pipe);
   2693 	if (err)
   2694 		return err;
   2695 	if (as->edesc1 != NULL) {
   2696 		endpt = as->edesc1->bEndpointAddress;
   2697 		DPRINTF("create sync-pipe to 0x%02x\n", endpt);
   2698 		err = usbd_open_pipe(as->ifaceh, endpt, USBD_MPSAFE,
   2699 		    &ch->sync_pipe);
   2700 	}
   2701 	return err;
   2702 }
   2703 
   2704 Static void
   2705 uaudio_chan_close(struct uaudio_softc *sc, struct chan *ch)
   2706 {
   2707 	usbd_pipe_handle pipe;
   2708 	struct as_info *as;
   2709 
   2710 	as = &sc->sc_alts[ch->altidx];
   2711 	as->sc_busy = 0;
   2712 	AUFMT_VALIDATE(as->aformat);
   2713 	if (sc->sc_nullalt >= 0) {
   2714 		DPRINTF("set null alt=%d\n", sc->sc_nullalt);
   2715 		usbd_set_interface(as->ifaceh, sc->sc_nullalt);
   2716 	}
   2717 	pipe = atomic_swap_ptr(&ch->pipe, NULL);
   2718 	if (pipe) {
   2719 		usbd_abort_pipe(pipe);
   2720 		usbd_close_pipe(pipe);
   2721 	}
   2722 	pipe = atomic_swap_ptr(&ch->sync_pipe, NULL);
   2723 	if (pipe) {
   2724 		usbd_abort_pipe(pipe);
   2725 		usbd_close_pipe(pipe);
   2726 	}
   2727 }
   2728 
   2729 Static usbd_status
   2730 uaudio_chan_alloc_buffers(struct uaudio_softc *sc, struct chan *ch)
   2731 {
   2732 	usbd_xfer_handle xfer;
   2733 	void *tbuf;
   2734 	int i, size;
   2735 
   2736 	size = (ch->bytes_per_frame + ch->sample_size) * UAUDIO_NFRAMES;
   2737 	for (i = 0; i < UAUDIO_NCHANBUFS; i++) {
   2738 		xfer = usbd_alloc_xfer(sc->sc_udev);
   2739 		if (xfer == 0)
   2740 			goto bad;
   2741 		ch->chanbufs[i].xfer = xfer;
   2742 		tbuf = usbd_alloc_buffer(xfer, size);
   2743 		if (tbuf == 0) {
   2744 			i++;
   2745 			goto bad;
   2746 		}
   2747 		ch->chanbufs[i].buffer = tbuf;
   2748 		ch->chanbufs[i].chan = ch;
   2749 	}
   2750 
   2751 	return USBD_NORMAL_COMPLETION;
   2752 
   2753 bad:
   2754 	while (--i >= 0)
   2755 		/* implicit buffer free */
   2756 		usbd_free_xfer(ch->chanbufs[i].xfer);
   2757 	return USBD_NOMEM;
   2758 }
   2759 
   2760 Static void
   2761 uaudio_chan_free_buffers(struct uaudio_softc *sc, struct chan *ch)
   2762 {
   2763 	int i;
   2764 
   2765 	for (i = 0; i < UAUDIO_NCHANBUFS; i++)
   2766 		usbd_free_xfer(ch->chanbufs[i].xfer);
   2767 }
   2768 
   2769 /* Called with USB lock held. */
   2770 Static void
   2771 uaudio_chan_ptransfer(struct chan *ch)
   2772 {
   2773 	struct chanbuf *cb;
   2774 	int i, n, size, residue, total;
   2775 
   2776 	if (ch->sc->sc_dying)
   2777 		return;
   2778 
   2779 	/* Pick the next channel buffer. */
   2780 	cb = &ch->chanbufs[ch->curchanbuf];
   2781 	if (++ch->curchanbuf >= UAUDIO_NCHANBUFS)
   2782 		ch->curchanbuf = 0;
   2783 
   2784 	/* Compute the size of each frame in the next transfer. */
   2785 	residue = ch->residue;
   2786 	total = 0;
   2787 	for (i = 0; i < UAUDIO_NFRAMES; i++) {
   2788 		size = ch->bytes_per_frame;
   2789 		residue += ch->fraction;
   2790 		if (residue >= USB_FRAMES_PER_SECOND) {
   2791 			if ((ch->sc->sc_altflags & UA_NOFRAC) == 0)
   2792 				size += ch->sample_size;
   2793 			residue -= USB_FRAMES_PER_SECOND;
   2794 		}
   2795 		cb->sizes[i] = size;
   2796 		total += size;
   2797 	}
   2798 	ch->residue = residue;
   2799 	cb->size = total;
   2800 
   2801 	/*
   2802 	 * Transfer data from upper layer buffer to channel buffer, taking
   2803 	 * care of wrapping the upper layer buffer.
   2804 	 */
   2805 	n = min(total, ch->end - ch->cur);
   2806 	memcpy(cb->buffer, ch->cur, n);
   2807 	ch->cur += n;
   2808 	if (ch->cur >= ch->end)
   2809 		ch->cur = ch->start;
   2810 	if (total > n) {
   2811 		total -= n;
   2812 		memcpy(cb->buffer + n, ch->cur, total);
   2813 		ch->cur += total;
   2814 	}
   2815 
   2816 #ifdef UAUDIO_DEBUG
   2817 	if (uaudiodebug > 8) {
   2818 		DPRINTF("buffer=%p, residue=0.%03d\n", cb->buffer, ch->residue);
   2819 		for (i = 0; i < UAUDIO_NFRAMES; i++) {
   2820 			DPRINTF("   [%d] length %d\n", i, cb->sizes[i]);
   2821 		}
   2822 	}
   2823 #endif
   2824 
   2825 	//DPRINTFN(5, "ptransfer xfer=%p\n", cb->xfer);
   2826 	/* Fill the request */
   2827 	usbd_setup_isoc_xfer(cb->xfer, ch->pipe, cb, cb->sizes,
   2828 			     UAUDIO_NFRAMES, USBD_NO_COPY,
   2829 			     uaudio_chan_pintr);
   2830 
   2831 	(void)usbd_transfer(cb->xfer);
   2832 }
   2833 
   2834 Static void
   2835 uaudio_chan_pintr(usbd_xfer_handle xfer, usbd_private_handle priv,
   2836 		  usbd_status status)
   2837 {
   2838 	struct chanbuf *cb;
   2839 	struct chan *ch;
   2840 	uint32_t count;
   2841 
   2842 	cb = priv;
   2843 	ch = cb->chan;
   2844 	/* Return if we are aborting. */
   2845 	if (status == USBD_CANCELLED)
   2846 		return;
   2847 
   2848 	usbd_get_xfer_status(xfer, NULL, NULL, &count, NULL);
   2849 	DPRINTFN(5, "count=%d, transferred=%d\n",
   2850 		    count, ch->transferred);
   2851 #ifdef DIAGNOSTIC
   2852 	if (count != cb->size) {
   2853 		aprint_error("uaudio_chan_pintr: count(%d) != size(%d)\n",
   2854 		       count, cb->size);
   2855 	}
   2856 #endif
   2857 
   2858 	ch->transferred += cb->size;
   2859 	mutex_spin_enter(&ch->sc->sc_intr_lock);
   2860 	/* Call back to upper layer */
   2861 	while (ch->transferred >= ch->blksize) {
   2862 		ch->transferred -= ch->blksize;
   2863 		DPRINTFN(5, "call %p(%p)\n", ch->intr, ch->arg);
   2864 		ch->intr(ch->arg);
   2865 	}
   2866 	mutex_spin_exit(&ch->sc->sc_intr_lock);
   2867 
   2868 	/* start next transfer */
   2869 	uaudio_chan_ptransfer(ch);
   2870 }
   2871 
   2872 /* Called with USB lock held. */
   2873 Static void
   2874 uaudio_chan_rtransfer(struct chan *ch)
   2875 {
   2876 	struct chanbuf *cb;
   2877 	int i, size, residue, total;
   2878 
   2879 	if (ch->sc->sc_dying)
   2880 		return;
   2881 
   2882 	/* Pick the next channel buffer. */
   2883 	cb = &ch->chanbufs[ch->curchanbuf];
   2884 	if (++ch->curchanbuf >= UAUDIO_NCHANBUFS)
   2885 		ch->curchanbuf = 0;
   2886 
   2887 	/* Compute the size of each frame in the next transfer. */
   2888 	residue = ch->residue;
   2889 	total = 0;
   2890 	for (i = 0; i < UAUDIO_NFRAMES; i++) {
   2891 		size = ch->bytes_per_frame;
   2892 		cb->sizes[i] = size;
   2893 		cb->offsets[i] = total;
   2894 		total += size;
   2895 	}
   2896 	ch->residue = residue;
   2897 	cb->size = total;
   2898 
   2899 #ifdef UAUDIO_DEBUG
   2900 	if (uaudiodebug > 8) {
   2901 		DPRINTF("buffer=%p, residue=0.%03d\n", cb->buffer, ch->residue);
   2902 		for (i = 0; i < UAUDIO_NFRAMES; i++) {
   2903 			DPRINTF("   [%d] length %d\n", i, cb->sizes[i]);
   2904 		}
   2905 	}
   2906 #endif
   2907 
   2908 	DPRINTFN(5, "transfer xfer=%p\n", cb->xfer);
   2909 	/* Fill the request */
   2910 	usbd_setup_isoc_xfer(cb->xfer, ch->pipe, cb, cb->sizes,
   2911 			     UAUDIO_NFRAMES, USBD_NO_COPY,
   2912 			     uaudio_chan_rintr);
   2913 
   2914 	(void)usbd_transfer(cb->xfer);
   2915 }
   2916 
   2917 Static void
   2918 uaudio_chan_rintr(usbd_xfer_handle xfer, usbd_private_handle priv,
   2919 		  usbd_status status)
   2920 {
   2921 	struct chanbuf *cb;
   2922 	struct chan *ch;
   2923 	uint32_t count;
   2924 	int i, n, frsize;
   2925 
   2926 	cb = priv;
   2927 	ch = cb->chan;
   2928 	/* Return if we are aborting. */
   2929 	if (status == USBD_CANCELLED)
   2930 		return;
   2931 
   2932 	usbd_get_xfer_status(xfer, NULL, NULL, &count, NULL);
   2933 	DPRINTFN(5, "count=%d, transferred=%d\n", count, ch->transferred);
   2934 
   2935 	/* count < cb->size is normal for asynchronous source */
   2936 #ifdef DIAGNOSTIC
   2937 	if (count > cb->size) {
   2938 		aprint_error("uaudio_chan_rintr: count(%d) > size(%d)\n",
   2939 		       count, cb->size);
   2940 	}
   2941 #endif
   2942 
   2943 	/*
   2944 	 * Transfer data from channel buffer to upper layer buffer, taking
   2945 	 * care of wrapping the upper layer buffer.
   2946 	 */
   2947 	for(i = 0; i < UAUDIO_NFRAMES; i++) {
   2948 		frsize = cb->sizes[i];
   2949 		n = min(frsize, ch->end - ch->cur);
   2950 		memcpy(ch->cur, cb->buffer + cb->offsets[i], n);
   2951 		ch->cur += n;
   2952 		if (ch->cur >= ch->end)
   2953 			ch->cur = ch->start;
   2954 		if (frsize > n) {
   2955 			memcpy(ch->cur, cb->buffer + cb->offsets[i] + n,
   2956 			    frsize - n);
   2957 			ch->cur += frsize - n;
   2958 		}
   2959 	}
   2960 
   2961 	/* Call back to upper layer */
   2962 	ch->transferred += count;
   2963 	mutex_spin_enter(&ch->sc->sc_intr_lock);
   2964 	while (ch->transferred >= ch->blksize) {
   2965 		ch->transferred -= ch->blksize;
   2966 		DPRINTFN(5, "call %p(%p)\n", ch->intr, ch->arg);
   2967 		ch->intr(ch->arg);
   2968 	}
   2969 	mutex_spin_exit(&ch->sc->sc_intr_lock);
   2970 
   2971 	/* start next transfer */
   2972 	uaudio_chan_rtransfer(ch);
   2973 }
   2974 
   2975 Static void
   2976 uaudio_chan_init(struct chan *ch, int altidx, const struct audio_params *param,
   2977     int maxpktsize)
   2978 {
   2979 	int samples_per_frame, sample_size;
   2980 
   2981 	ch->altidx = altidx;
   2982 	sample_size = param->precision * param->channels / 8;
   2983 	samples_per_frame = param->sample_rate / USB_FRAMES_PER_SECOND;
   2984 	ch->sample_size = sample_size;
   2985 	ch->sample_rate = param->sample_rate;
   2986 	if (maxpktsize == 0) {
   2987 		ch->fraction = param->sample_rate % USB_FRAMES_PER_SECOND;
   2988 		ch->bytes_per_frame = samples_per_frame * sample_size;
   2989 	} else {
   2990 		ch->fraction = 0;
   2991 		ch->bytes_per_frame = maxpktsize;
   2992 	}
   2993 	ch->residue = 0;
   2994 }
   2995 
   2996 Static void
   2997 uaudio_chan_set_param(struct chan *ch, u_char *start, u_char *end, int blksize)
   2998 {
   2999 
   3000 	ch->start = start;
   3001 	ch->end = end;
   3002 	ch->cur = start;
   3003 	ch->blksize = blksize;
   3004 	ch->transferred = 0;
   3005 	ch->curchanbuf = 0;
   3006 }
   3007 
   3008 Static int
   3009 uaudio_set_params(void *addr, int setmode, int usemode,
   3010 		  struct audio_params *play, struct audio_params *rec,
   3011 		  stream_filter_list_t *pfil, stream_filter_list_t *rfil)
   3012 {
   3013 	struct uaudio_softc *sc;
   3014 	int paltidx, raltidx;
   3015 	struct audio_params *p;
   3016 	stream_filter_list_t *fil;
   3017 	int mode, i;
   3018 
   3019 	sc = addr;
   3020 	paltidx = -1;
   3021 	raltidx = -1;
   3022 	if (sc->sc_dying)
   3023 		return EIO;
   3024 
   3025 	if (((usemode & AUMODE_PLAY) && sc->sc_playchan.pipe != NULL) ||
   3026 	    ((usemode & AUMODE_RECORD) && sc->sc_recchan.pipe != NULL))
   3027 		return EBUSY;
   3028 
   3029 	if ((usemode & AUMODE_PLAY) && sc->sc_playchan.altidx != -1) {
   3030 		sc->sc_alts[sc->sc_playchan.altidx].sc_busy = 0;
   3031 		AUFMT_VALIDATE(sc->sc_alts[sc->sc_playchan.altidx].aformat);
   3032 	}
   3033 	if ((usemode & AUMODE_RECORD) && sc->sc_recchan.altidx != -1) {
   3034 		sc->sc_alts[sc->sc_recchan.altidx].sc_busy = 0;
   3035 		AUFMT_VALIDATE(sc->sc_alts[sc->sc_recchan.altidx].aformat);
   3036 	}
   3037 
   3038 	/* Some uaudio devices are unidirectional.  Don't try to find a
   3039 	   matching mode for the unsupported direction. */
   3040 	setmode &= sc->sc_mode;
   3041 
   3042 	for (mode = AUMODE_RECORD; mode != -1;
   3043 	     mode = mode == AUMODE_RECORD ? AUMODE_PLAY : -1) {
   3044 		if ((setmode & mode) == 0)
   3045 			continue;
   3046 
   3047 		if (mode == AUMODE_PLAY) {
   3048 			p = play;
   3049 			fil = pfil;
   3050 		} else {
   3051 			p = rec;
   3052 			fil = rfil;
   3053 		}
   3054 		i = auconv_set_converter(sc->sc_formats, sc->sc_nformats,
   3055 					 mode, p, TRUE, fil);
   3056 		if (i < 0)
   3057 			return EINVAL;
   3058 
   3059 		if (mode == AUMODE_PLAY)
   3060 			paltidx = i;
   3061 		else
   3062 			raltidx = i;
   3063 	}
   3064 
   3065 	if ((setmode & AUMODE_PLAY)) {
   3066 		p = pfil->req_size > 0 ? &pfil->filters[0].param : play;
   3067 		/* XXX abort transfer if currently happening? */
   3068 		uaudio_chan_init(&sc->sc_playchan, paltidx, p, 0);
   3069 	}
   3070 	if ((setmode & AUMODE_RECORD)) {
   3071 		p = rfil->req_size > 0 ? &pfil->filters[0].param : rec;
   3072 		/* XXX abort transfer if currently happening? */
   3073 		uaudio_chan_init(&sc->sc_recchan, raltidx, p,
   3074 		    UGETW(sc->sc_alts[raltidx].edesc->wMaxPacketSize));
   3075 	}
   3076 
   3077 	if ((usemode & AUMODE_PLAY) && sc->sc_playchan.altidx != -1) {
   3078 		sc->sc_alts[sc->sc_playchan.altidx].sc_busy = 1;
   3079 		AUFMT_INVALIDATE(sc->sc_alts[sc->sc_playchan.altidx].aformat);
   3080 	}
   3081 	if ((usemode & AUMODE_RECORD) && sc->sc_recchan.altidx != -1) {
   3082 		sc->sc_alts[sc->sc_recchan.altidx].sc_busy = 1;
   3083 		AUFMT_INVALIDATE(sc->sc_alts[sc->sc_recchan.altidx].aformat);
   3084 	}
   3085 
   3086 	DPRINTF("use altidx=p%d/r%d, altno=p%d/r%d\n",
   3087 		 sc->sc_playchan.altidx, sc->sc_recchan.altidx,
   3088 		 (sc->sc_playchan.altidx >= 0)
   3089 		   ?sc->sc_alts[sc->sc_playchan.altidx].idesc->bAlternateSetting
   3090 		   : -1,
   3091 		 (sc->sc_recchan.altidx >= 0)
   3092 		   ? sc->sc_alts[sc->sc_recchan.altidx].idesc->bAlternateSetting
   3093 		   : -1);
   3094 
   3095 	return 0;
   3096 }
   3097 
   3098 Static usbd_status
   3099 uaudio_set_speed(struct uaudio_softc *sc, int endpt, u_int speed)
   3100 {
   3101 	usb_device_request_t req;
   3102 	usbd_status err;
   3103 	uint8_t data[3];
   3104 
   3105 	DPRINTFN(5, "endpt=%d speed=%u\n", endpt, speed);
   3106 	req.bmRequestType = UT_WRITE_CLASS_ENDPOINT;
   3107 	req.bRequest = SET_CUR;
   3108 	USETW2(req.wValue, SAMPLING_FREQ_CONTROL, 0);
   3109 	USETW(req.wIndex, endpt);
   3110 	USETW(req.wLength, 3);
   3111 	data[0] = speed;
   3112 	data[1] = speed >> 8;
   3113 	data[2] = speed >> 16;
   3114 
   3115 	err = usbd_do_request(sc->sc_udev, &req, data);
   3116 
   3117 	return err;
   3118 }
   3119 
   3120 #ifdef _MODULE
   3121 
   3122 MODULE(MODULE_CLASS_DRIVER, uaudio, NULL);
   3123 
   3124 static const struct cfiattrdata audiobuscf_iattrdata = {
   3125 	"audiobus", 0, { { NULL, NULL, 0 }, }
   3126 };
   3127 static const struct cfiattrdata * const uaudio_attrs[] = {
   3128 	&audiobuscf_iattrdata, NULL
   3129 };
   3130 CFDRIVER_DECL(uaudio, DV_DULL, uaudio_attrs);
   3131 extern struct cfattach uaudio_ca;
   3132 static int uaudioloc[6/*USBIFIFCF_NLOCS*/] = {
   3133 	-1/*USBIFIFCF_PORT_DEFAULT*/,
   3134 	-1/*USBIFIFCF_CONFIGURATION_DEFAULT*/,
   3135 	-1/*USBIFIFCF_INTERFACE_DEFAULT*/,
   3136 	-1/*USBIFIFCF_VENDOR_DEFAULT*/,
   3137 	-1/*USBIFIFCF_PRODUCT_DEFAULT*/,
   3138 	-1/*USBIFIFCF_RELEASE_DEFAULT*/};
   3139 static struct cfparent uhubparent = {
   3140 	"usbifif", NULL, DVUNIT_ANY
   3141 };
   3142 static struct cfdata uaudio_cfdata[] = {
   3143 	{
   3144 		.cf_name = "uaudio",
   3145 		.cf_atname = "uaudio",
   3146 		.cf_unit = 0,
   3147 		.cf_fstate = FSTATE_STAR,
   3148 		.cf_loc = uaudioloc,
   3149 		.cf_flags = 0,
   3150 		.cf_pspec = &uhubparent,
   3151 	},
   3152 	{ NULL }
   3153 };
   3154 
   3155 static int
   3156 uaudio_modcmd(modcmd_t cmd, void *arg)
   3157 {
   3158 	int err;
   3159 
   3160 	switch (cmd) {
   3161 	case MODULE_CMD_INIT:
   3162 		err = config_cfdriver_attach(&uaudio_cd);
   3163 		if (err) {
   3164 			return err;
   3165 		}
   3166 		err = config_cfattach_attach("uaudio", &uaudio_ca);
   3167 		if (err) {
   3168 			config_cfdriver_detach(&uaudio_cd);
   3169 			return err;
   3170 		}
   3171 		err = config_cfdata_attach(uaudio_cfdata, 1);
   3172 		if (err) {
   3173 			config_cfattach_detach("uaudio", &uaudio_ca);
   3174 			config_cfdriver_detach(&uaudio_cd);
   3175 			return err;
   3176 		}
   3177 		return 0;
   3178 	case MODULE_CMD_FINI:
   3179 		err = config_cfdata_detach(uaudio_cfdata);
   3180 		if (err)
   3181 			return err;
   3182 		config_cfattach_detach("uaudio", &uaudio_ca);
   3183 		config_cfdriver_detach(&uaudio_cd);
   3184 		return 0;
   3185 	default:
   3186 		return ENOTTY;
   3187 	}
   3188 }
   3189 
   3190 #endif
   3191