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