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