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