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