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