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