xref: /freebsd/sys/dev/sound/usb/uaudio.c (revision ee7b0571c2c18bdec848ed2044223cc88db29bd8)
1 /*	$NetBSD: uaudio.c,v 1.91 2004/11/05 17:46:14 kent Exp $	*/
2 /*	$FreeBSD$ */
3 
4 /*-
5  * Copyright (c) 1999 The NetBSD Foundation, Inc.
6  * All rights reserved.
7  *
8  * This code is derived from software contributed to The NetBSD Foundation
9  * by Lennart Augustsson (lennart@augustsson.net) at
10  * Carlstedt Research & Technology.
11  *
12  * Redistribution and use in source and binary forms, with or without
13  * modification, are permitted provided that the following conditions
14  * are met:
15  * 1. Redistributions of source code must retain the above copyright
16  *    notice, this list of conditions and the following disclaimer.
17  * 2. Redistributions in binary form must reproduce the above copyright
18  *    notice, this list of conditions and the following disclaimer in the
19  *    documentation and/or other materials provided with the distribution.
20  *
21  * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
22  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
23  * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
24  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
25  * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
26  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
27  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
28  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
29  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
30  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
31  * POSSIBILITY OF SUCH DAMAGE.
32  */
33 
34 #include <sys/cdefs.h>
35 __FBSDID("$FreeBSD$");
36 
37 /*
38  * USB audio specs: http://www.usb.org/developers/devclass_docs/audio10.pdf
39  *                  http://www.usb.org/developers/devclass_docs/frmts10.pdf
40  *                  http://www.usb.org/developers/devclass_docs/termt10.pdf
41  */
42 
43 /*
44  * Also merged:
45  *  $NetBSD: uaudio.c,v 1.94 2005/01/15 15:19:53 kent Exp $
46  *  $NetBSD: uaudio.c,v 1.95 2005/01/16 06:02:19 dsainty Exp $
47  *  $NetBSD: uaudio.c,v 1.96 2005/01/16 12:46:00 kent Exp $
48  *  $NetBSD: uaudio.c,v 1.97 2005/02/24 08:19:38 martin Exp $
49  */
50 
51 #include <sys/stdint.h>
52 #include <sys/stddef.h>
53 #include <sys/param.h>
54 #include <sys/queue.h>
55 #include <sys/types.h>
56 #include <sys/systm.h>
57 #include <sys/kernel.h>
58 #include <sys/bus.h>
59 #include <sys/module.h>
60 #include <sys/lock.h>
61 #include <sys/mutex.h>
62 #include <sys/condvar.h>
63 #include <sys/sysctl.h>
64 #include <sys/sx.h>
65 #include <sys/unistd.h>
66 #include <sys/callout.h>
67 #include <sys/malloc.h>
68 #include <sys/priv.h>
69 
70 #include "usbdevs.h"
71 #include <dev/usb/usb.h>
72 #include <dev/usb/usbdi.h>
73 #include <dev/usb/usbdi_util.h>
74 #include <dev/usb/usbhid.h>
75 #include <dev/usb/usb_request.h>
76 #include <dev/usb/usb_process.h>
77 
78 #define	USB_DEBUG_VAR uaudio_debug
79 #include <dev/usb/usb_debug.h>
80 
81 #include <dev/usb/quirk/usb_quirk.h>
82 
83 #include <sys/reboot.h>			/* for bootverbose */
84 
85 #ifdef HAVE_KERNEL_OPTION_HEADERS
86 #include "opt_snd.h"
87 #endif
88 
89 #include <dev/sound/pcm/sound.h>
90 #include <dev/sound/usb/uaudioreg.h>
91 #include <dev/sound/usb/uaudio.h>
92 #include <dev/sound/chip.h>
93 #include "feeder_if.h"
94 
95 static int uaudio_default_rate = 0;		/* use rate list */
96 static int uaudio_default_bits = 32;
97 static int uaudio_default_channels = 0;		/* use default */
98 
99 #ifdef USB_DEBUG
100 static int uaudio_debug = 0;
101 
102 static SYSCTL_NODE(_hw_usb, OID_AUTO, uaudio, CTLFLAG_RW, 0, "USB uaudio");
103 
104 SYSCTL_INT(_hw_usb_uaudio, OID_AUTO, debug, CTLFLAG_RW,
105     &uaudio_debug, 0, "uaudio debug level");
106 SYSCTL_INT(_hw_usb_uaudio, OID_AUTO, default_rate, CTLFLAG_RWTUN,
107     &uaudio_default_rate, 0, "uaudio default sample rate");
108 SYSCTL_INT(_hw_usb_uaudio, OID_AUTO, default_bits, CTLFLAG_RWTUN,
109     &uaudio_default_bits, 0, "uaudio default sample bits");
110 SYSCTL_INT(_hw_usb_uaudio, OID_AUTO, default_channels, CTLFLAG_RWTUN,
111     &uaudio_default_channels, 0, "uaudio default sample channels");
112 #endif
113 
114 #define	UAUDIO_NFRAMES		64	/* must be factor of 8 due HS-USB */
115 #define	UAUDIO_NCHANBUFS	2	/* number of outstanding request */
116 #define	UAUDIO_RECURSE_LIMIT	255	/* rounds */
117 
118 #define	MAKE_WORD(h,l) (((h) << 8) | (l))
119 #define	BIT_TEST(bm,bno) (((bm)[(bno) / 8] >> (7 - ((bno) % 8))) & 1)
120 #define	UAUDIO_MAX_CHAN(x) (x)
121 #define	MIX(sc) ((sc)->sc_mixer_node)
122 
123 union uaudio_asid {
124 	const struct usb_audio_streaming_interface_descriptor *v1;
125 	const struct usb_audio20_streaming_interface_descriptor *v2;
126 };
127 
128 union uaudio_asf1d {
129 	const struct usb_audio_streaming_type1_descriptor *v1;
130 	const struct usb_audio20_streaming_type1_descriptor *v2;
131 };
132 
133 union uaudio_sed {
134 	const struct usb_audio_streaming_endpoint_descriptor *v1;
135 	const struct usb_audio20_streaming_endpoint_descriptor *v2;
136 };
137 
138 struct uaudio_mixer_node {
139 	const char *name;
140 
141 	int32_t	minval;
142 	int32_t	maxval;
143 #define	MIX_MAX_CHAN 16
144 	int32_t	wValue[MIX_MAX_CHAN];	/* using nchan */
145 	uint32_t mul;
146 	uint32_t ctl;
147 
148 	int wData[MIX_MAX_CHAN];	/* using nchan */
149 	uint16_t wIndex;
150 
151 	uint8_t	update[(MIX_MAX_CHAN + 7) / 8];
152 	uint8_t	nchan;
153 	uint8_t	type;
154 #define	MIX_ON_OFF	1
155 #define	MIX_SIGNED_16	2
156 #define	MIX_UNSIGNED_16	3
157 #define	MIX_SIGNED_8	4
158 #define	MIX_SELECTOR	5
159 #define	MIX_UNKNOWN     6
160 #define	MIX_SIZE(n) ((((n) == MIX_SIGNED_16) || \
161 		      ((n) == MIX_UNSIGNED_16)) ? 2 : 1)
162 #define	MIX_UNSIGNED(n) ((n) == MIX_UNSIGNED_16)
163 
164 #define	MAX_SELECTOR_INPUT_PIN 256
165 	uint8_t	slctrtype[MAX_SELECTOR_INPUT_PIN];
166 	uint8_t	class;
167 	uint8_t val_default;
168 
169 	uint8_t desc[64];
170 
171 	struct uaudio_mixer_node *next;
172 };
173 
174 struct uaudio_configure_msg {
175 	struct usb_proc_msg hdr;
176 	struct uaudio_softc *sc;
177 };
178 
179 #define	CHAN_MAX_ALT 24
180 
181 struct uaudio_chan_alt {
182 	union uaudio_asf1d p_asf1d;
183 	union uaudio_sed p_sed;
184 	const usb_endpoint_descriptor_audio_t *p_ed1;
185 	const struct uaudio_format *p_fmt;
186 	const struct usb_config *usb_cfg;
187 	uint32_t sample_rate;	/* in Hz */
188 	uint16_t sample_size;
189 	uint8_t	iface_index;
190 	uint8_t	iface_alt_index;
191 	uint8_t channels;
192 };
193 
194 struct uaudio_chan {
195 	struct pcmchan_caps pcm_cap;	/* capabilities */
196 	struct uaudio_chan_alt usb_alt[CHAN_MAX_ALT];
197 	struct snd_dbuf *pcm_buf;
198 	struct mtx *pcm_mtx;		/* lock protecting this structure */
199 	struct uaudio_softc *priv_sc;
200 	struct pcm_channel *pcm_ch;
201 	struct usb_xfer *xfer[UAUDIO_NCHANBUFS + 1];
202 
203 	uint8_t *buf;			/* pointer to buffer */
204 	uint8_t *start;			/* upper layer buffer start */
205 	uint8_t *end;			/* upper layer buffer end */
206 	uint8_t *cur;			/* current position in upper layer
207 					 * buffer */
208 
209 	uint32_t intr_frames;		/* in units */
210 	uint32_t frames_per_second;
211 	uint32_t sample_rem;
212 	uint32_t sample_curr;
213 	uint32_t max_buf;
214 
215 	uint32_t pcm_format[2];
216 
217 	uint16_t bytes_per_frame[2];
218 
219 	uint8_t	num_alt;
220 	uint8_t cur_alt;
221 	uint8_t set_alt;
222 	uint8_t operation;
223 #define	CHAN_OP_NONE 0
224 #define	CHAN_OP_START 1
225 #define	CHAN_OP_STOP 2
226 #define	CHAN_OP_DRAIN 3
227 
228 	uint8_t last_sync_time;
229 	uint8_t last_sync_state;
230 #define	UAUDIO_SYNC_NONE 0
231 #define	UAUDIO_SYNC_MORE 1
232 #define	UAUDIO_SYNC_LESS 2
233 };
234 
235 #define	UMIDI_CABLES_MAX   16		/* units */
236 #define	UMIDI_TX_FRAMES	   256		/* units */
237 #define	UMIDI_TX_BUFFER    (UMIDI_TX_FRAMES * 4)	/* bytes */
238 
239 enum {
240 	UMIDI_TX_TRANSFER,
241 	UMIDI_RX_TRANSFER,
242 	UMIDI_N_TRANSFER,
243 };
244 
245 struct umidi_sub_chan {
246 	struct usb_fifo_sc fifo;
247 	uint8_t *temp_cmd;
248 	uint8_t	temp_0[4];
249 	uint8_t	temp_1[4];
250 	uint8_t	state;
251 #define	UMIDI_ST_UNKNOWN   0		/* scan for command */
252 #define	UMIDI_ST_1PARAM    1
253 #define	UMIDI_ST_2PARAM_1  2
254 #define	UMIDI_ST_2PARAM_2  3
255 #define	UMIDI_ST_SYSEX_0   4
256 #define	UMIDI_ST_SYSEX_1   5
257 #define	UMIDI_ST_SYSEX_2   6
258 
259 	uint8_t	read_open:1;
260 	uint8_t	write_open:1;
261 	uint8_t	unused:6;
262 };
263 
264 struct umidi_chan {
265 
266 	struct umidi_sub_chan sub[UMIDI_CABLES_MAX];
267 	struct mtx mtx;
268 
269 	struct usb_xfer *xfer[UMIDI_N_TRANSFER];
270 
271 	uint8_t	iface_index;
272 	uint8_t	iface_alt_index;
273 
274 	uint8_t	read_open_refcount;
275 	uint8_t	write_open_refcount;
276 
277 	uint8_t	curr_cable;
278 	uint8_t	max_cable;
279 	uint8_t	valid;
280 	uint8_t single_command;
281 };
282 
283 struct uaudio_search_result {
284 	uint8_t	bit_input[(256 + 7) / 8];
285 	uint8_t	bit_output[(256 + 7) / 8];
286 	uint8_t	recurse_level;
287 	uint8_t	id_max;
288 	uint8_t is_input;
289 };
290 
291 enum {
292 	UAUDIO_HID_RX_TRANSFER,
293 	UAUDIO_HID_N_TRANSFER,
294 };
295 
296 struct uaudio_hid {
297 	struct usb_xfer *xfer[UAUDIO_HID_N_TRANSFER];
298 	struct hid_location volume_up_loc;
299 	struct hid_location volume_down_loc;
300 	struct hid_location mute_loc;
301 	uint32_t flags;
302 #define	UAUDIO_HID_VALID		0x0001
303 #define	UAUDIO_HID_HAS_ID		0x0002
304 #define	UAUDIO_HID_HAS_VOLUME_UP	0x0004
305 #define	UAUDIO_HID_HAS_VOLUME_DOWN	0x0008
306 #define	UAUDIO_HID_HAS_MUTE		0x0010
307 	uint8_t iface_index;
308 	uint8_t volume_up_id;
309 	uint8_t volume_down_id;
310 	uint8_t mute_id;
311 };
312 
313 struct uaudio_softc {
314 	struct sbuf sc_sndstat;
315 	struct sndcard_func sc_sndcard_func;
316 	struct uaudio_chan sc_rec_chan;
317 	struct uaudio_chan sc_play_chan;
318 	struct umidi_chan sc_midi_chan;
319 	struct uaudio_hid sc_hid;
320 	struct uaudio_search_result sc_mixer_clocks;
321 	struct uaudio_mixer_node sc_mixer_node;
322 	struct uaudio_configure_msg sc_config_msg[2];
323 
324 	struct mtx *sc_mixer_lock;
325 	struct snd_mixer *sc_mixer_dev;
326 	struct usb_device *sc_udev;
327 	struct usb_xfer *sc_mixer_xfer[1];
328 	struct uaudio_mixer_node *sc_mixer_root;
329 	struct uaudio_mixer_node *sc_mixer_curr;
330 
331 	uint32_t sc_mix_info;
332 	uint32_t sc_recsrc_info;
333 
334 	uint16_t sc_audio_rev;
335 	uint16_t sc_mixer_count;
336 
337 	uint8_t	sc_sndstat_valid;
338 	uint8_t	sc_mixer_iface_index;
339 	uint8_t	sc_mixer_iface_no;
340 	uint8_t	sc_mixer_chan;
341 	uint8_t	sc_pcm_registered:1;
342 	uint8_t	sc_mixer_init:1;
343 	uint8_t	sc_uq_audio_swap_lr:1;
344 	uint8_t	sc_uq_au_inp_async:1;
345 	uint8_t	sc_uq_au_no_xu:1;
346 	uint8_t	sc_uq_bad_adc:1;
347 	uint8_t	sc_uq_au_vendor_class:1;
348 };
349 
350 struct uaudio_terminal_node {
351 	union {
352 		const struct usb_descriptor *desc;
353 		const struct usb_audio_input_terminal *it_v1;
354 		const struct usb_audio_output_terminal *ot_v1;
355 		const struct usb_audio_mixer_unit_0 *mu_v1;
356 		const struct usb_audio_selector_unit *su_v1;
357 		const struct usb_audio_feature_unit *fu_v1;
358 		const struct usb_audio_processing_unit_0 *pu_v1;
359 		const struct usb_audio_extension_unit_0 *eu_v1;
360 		const struct usb_audio20_clock_source_unit *csrc_v2;
361 		const struct usb_audio20_clock_selector_unit_0 *csel_v2;
362 		const struct usb_audio20_clock_multiplier_unit *cmul_v2;
363 		const struct usb_audio20_input_terminal *it_v2;
364 		const struct usb_audio20_output_terminal *ot_v2;
365 		const struct usb_audio20_mixer_unit_0 *mu_v2;
366 		const struct usb_audio20_selector_unit *su_v2;
367 		const struct usb_audio20_feature_unit *fu_v2;
368 		const struct usb_audio20_sample_rate_unit *ru_v2;
369 		const struct usb_audio20_processing_unit_0 *pu_v2;
370 		const struct usb_audio20_extension_unit_0 *eu_v2;
371 		const struct usb_audio20_effect_unit *ef_v2;
372 	}	u;
373 	struct uaudio_search_result usr;
374 	struct uaudio_terminal_node *root;
375 };
376 
377 struct uaudio_format {
378 	uint16_t wFormat;
379 	uint8_t	bPrecision;
380 	uint32_t freebsd_fmt;
381 	const char *description;
382 };
383 
384 static const struct uaudio_format uaudio10_formats[] = {
385 
386 	{UA_FMT_PCM8, 8, AFMT_U8, "8-bit U-LE PCM"},
387 	{UA_FMT_PCM8, 16, AFMT_U16_LE, "16-bit U-LE PCM"},
388 	{UA_FMT_PCM8, 24, AFMT_U24_LE, "24-bit U-LE PCM"},
389 	{UA_FMT_PCM8, 32, AFMT_U32_LE, "32-bit U-LE PCM"},
390 
391 	{UA_FMT_PCM, 8, AFMT_S8, "8-bit S-LE PCM"},
392 	{UA_FMT_PCM, 16, AFMT_S16_LE, "16-bit S-LE PCM"},
393 	{UA_FMT_PCM, 24, AFMT_S24_LE, "24-bit S-LE PCM"},
394 	{UA_FMT_PCM, 32, AFMT_S32_LE, "32-bit S-LE PCM"},
395 
396 	{UA_FMT_ALAW, 8, AFMT_A_LAW, "8-bit A-Law"},
397 	{UA_FMT_MULAW, 8, AFMT_MU_LAW, "8-bit mu-Law"},
398 
399 	{0, 0, 0, NULL}
400 };
401 
402 static const struct uaudio_format uaudio20_formats[] = {
403 
404 	{UA20_FMT_PCM, 8, AFMT_S8, "8-bit S-LE PCM"},
405 	{UA20_FMT_PCM, 16, AFMT_S16_LE, "16-bit S-LE PCM"},
406 	{UA20_FMT_PCM, 24, AFMT_S24_LE, "24-bit S-LE PCM"},
407 	{UA20_FMT_PCM, 32, AFMT_S32_LE, "32-bit S-LE PCM"},
408 
409 	{UA20_FMT_PCM8, 8, AFMT_U8, "8-bit U-LE PCM"},
410 	{UA20_FMT_PCM8, 16, AFMT_U16_LE, "16-bit U-LE PCM"},
411 	{UA20_FMT_PCM8, 24, AFMT_U24_LE, "24-bit U-LE PCM"},
412 	{UA20_FMT_PCM8, 32, AFMT_U32_LE, "32-bit U-LE PCM"},
413 
414 	{UA20_FMT_ALAW, 8, AFMT_A_LAW, "8-bit A-Law"},
415 	{UA20_FMT_MULAW, 8, AFMT_MU_LAW, "8-bit mu-Law"},
416 
417 	{0, 0, 0, NULL}
418 };
419 
420 #define	UAC_OUTPUT	0
421 #define	UAC_INPUT	1
422 #define	UAC_EQUAL	2
423 #define	UAC_RECORD	3
424 #define	UAC_NCLASSES	4
425 
426 #ifdef USB_DEBUG
427 static const char *uac_names[] = {
428 	"outputs", "inputs", "equalization", "record"
429 };
430 
431 #endif
432 
433 /* prototypes */
434 
435 static device_probe_t uaudio_probe;
436 static device_attach_t uaudio_attach;
437 static device_detach_t uaudio_detach;
438 
439 static usb_callback_t uaudio_chan_play_callback;
440 static usb_callback_t uaudio_chan_play_sync_callback;
441 static usb_callback_t uaudio_chan_record_callback;
442 static usb_callback_t uaudio_chan_record_sync_callback;
443 static usb_callback_t uaudio_mixer_write_cfg_callback;
444 static usb_callback_t umidi_bulk_read_callback;
445 static usb_callback_t umidi_bulk_write_callback;
446 static usb_callback_t uaudio_hid_rx_callback;
447 
448 static usb_proc_callback_t uaudio_configure_msg;
449 
450 /* ==== USB mixer ==== */
451 
452 static int uaudio_mixer_sysctl_handler(SYSCTL_HANDLER_ARGS);
453 static void uaudio_mixer_ctl_free(struct uaudio_softc *);
454 static void uaudio_mixer_register_sysctl(struct uaudio_softc *, device_t);
455 static void uaudio_mixer_reload_all(struct uaudio_softc *);
456 static void uaudio_mixer_controls_create_ftu(struct uaudio_softc *);
457 
458 /* ==== USB audio v1.0 ==== */
459 
460 static void	uaudio_mixer_add_mixer(struct uaudio_softc *,
461 		    const struct uaudio_terminal_node *, int);
462 static void	uaudio_mixer_add_selector(struct uaudio_softc *,
463 		    const struct uaudio_terminal_node *, int);
464 static uint32_t	uaudio_mixer_feature_get_bmaControls(
465 		    const struct usb_audio_feature_unit *, uint8_t);
466 static void	uaudio_mixer_add_feature(struct uaudio_softc *,
467 		    const struct uaudio_terminal_node *, int);
468 static void	uaudio_mixer_add_processing_updown(struct uaudio_softc *,
469 		    const struct uaudio_terminal_node *, int);
470 static void	uaudio_mixer_add_processing(struct uaudio_softc *,
471 		    const struct uaudio_terminal_node *, int);
472 static void	uaudio_mixer_add_extension(struct uaudio_softc *,
473 		    const struct uaudio_terminal_node *, int);
474 static struct	usb_audio_cluster uaudio_mixer_get_cluster(uint8_t,
475 		    const struct uaudio_terminal_node *);
476 static uint16_t	uaudio_mixer_determine_class(const struct uaudio_terminal_node *,
477 		    struct uaudio_mixer_node *);
478 static uint16_t	uaudio_mixer_feature_name(const struct uaudio_terminal_node *,
479 		    struct uaudio_mixer_node *);
480 static void	uaudio_mixer_find_inputs_sub(struct uaudio_terminal_node *,
481 		    const uint8_t *, uint8_t, struct uaudio_search_result *);
482 static const void *uaudio_mixer_verify_desc(const void *, uint32_t);
483 static usb_error_t uaudio_set_speed(struct usb_device *, uint8_t, uint32_t);
484 static int	uaudio_mixer_get(struct usb_device *, uint16_t, uint8_t,
485 		    struct uaudio_mixer_node *);
486 
487 /* ==== USB audio v2.0 ==== */
488 
489 static void	uaudio20_mixer_add_mixer(struct uaudio_softc *,
490 		    const struct uaudio_terminal_node *, int);
491 static void	uaudio20_mixer_add_selector(struct uaudio_softc *,
492 		    const struct uaudio_terminal_node *, int);
493 static void	uaudio20_mixer_add_feature(struct uaudio_softc *,
494 		    const struct uaudio_terminal_node *, int);
495 static struct	usb_audio20_cluster uaudio20_mixer_get_cluster(uint8_t,
496 		    const struct uaudio_terminal_node *);
497 static uint16_t	uaudio20_mixer_determine_class(const struct uaudio_terminal_node *,
498 		    struct uaudio_mixer_node *);
499 static uint16_t	uaudio20_mixer_feature_name(const struct uaudio_terminal_node *,
500 		    struct uaudio_mixer_node *);
501 static void	uaudio20_mixer_find_inputs_sub(struct uaudio_terminal_node *,
502 		    const uint8_t *, uint8_t, struct uaudio_search_result *);
503 static const void *uaudio20_mixer_verify_desc(const void *, uint32_t);
504 static usb_error_t uaudio20_set_speed(struct usb_device *, uint8_t,
505 		    uint8_t, uint32_t);
506 
507 /* USB audio v1.0 and v2.0 */
508 
509 static void	uaudio_chan_fill_info_sub(struct uaudio_softc *,
510 		    struct usb_device *, uint32_t, uint8_t, uint8_t);
511 static void	uaudio_chan_fill_info(struct uaudio_softc *,
512 		    struct usb_device *);
513 static void	uaudio_mixer_add_ctl_sub(struct uaudio_softc *,
514 		    struct uaudio_mixer_node *);
515 static void	uaudio_mixer_add_ctl(struct uaudio_softc *,
516 		    struct uaudio_mixer_node *);
517 static void	uaudio_mixer_fill_info(struct uaudio_softc *,
518 		    struct usb_device *, void *);
519 static void	uaudio_mixer_ctl_set(struct uaudio_softc *,
520 		    struct uaudio_mixer_node *, uint8_t, int32_t val);
521 static int	uaudio_mixer_signext(uint8_t, int);
522 static int	uaudio_mixer_bsd2value(struct uaudio_mixer_node *, int32_t val);
523 static void	uaudio_mixer_init(struct uaudio_softc *);
524 static const struct uaudio_terminal_node *uaudio_mixer_get_input(
525 		    const struct uaudio_terminal_node *, uint8_t);
526 static const struct uaudio_terminal_node *uaudio_mixer_get_output(
527 		    const struct uaudio_terminal_node *, uint8_t);
528 static void	uaudio_mixer_find_outputs_sub(struct uaudio_terminal_node *,
529 		    uint8_t, uint8_t, struct uaudio_search_result *);
530 static uint8_t	umidi_convert_to_usb(struct umidi_sub_chan *, uint8_t, uint8_t);
531 static struct	umidi_sub_chan *umidi_sub_by_fifo(struct usb_fifo *);
532 static void	umidi_start_read(struct usb_fifo *);
533 static void	umidi_stop_read(struct usb_fifo *);
534 static void	umidi_start_write(struct usb_fifo *);
535 static void	umidi_stop_write(struct usb_fifo *);
536 static int	umidi_open(struct usb_fifo *, int);
537 static int	umidi_ioctl(struct usb_fifo *, u_long cmd, void *, int);
538 static void	umidi_close(struct usb_fifo *, int);
539 static void	umidi_init(device_t dev);
540 static int	umidi_probe(device_t dev);
541 static int	umidi_detach(device_t dev);
542 static int	uaudio_hid_probe(struct uaudio_softc *sc,
543 		    struct usb_attach_arg *uaa);
544 static void	uaudio_hid_detach(struct uaudio_softc *sc);
545 
546 #ifdef USB_DEBUG
547 static void	uaudio_chan_dump_ep_desc(
548 		    const usb_endpoint_descriptor_audio_t *);
549 #endif
550 
551 static const struct usb_config
552 	uaudio_cfg_record[UAUDIO_NCHANBUFS + 1] = {
553 	[0] = {
554 		.type = UE_ISOCHRONOUS,
555 		.endpoint = UE_ADDR_ANY,
556 		.direction = UE_DIR_IN,
557 		.bufsize = 0,	/* use "wMaxPacketSize * frames" */
558 		.frames = UAUDIO_NFRAMES,
559 		.flags = {.short_xfer_ok = 1,},
560 		.callback = &uaudio_chan_record_callback,
561 	},
562 
563 	[1] = {
564 		.type = UE_ISOCHRONOUS,
565 		.endpoint = UE_ADDR_ANY,
566 		.direction = UE_DIR_IN,
567 		.bufsize = 0,	/* use "wMaxPacketSize * frames" */
568 		.frames = UAUDIO_NFRAMES,
569 		.flags = {.short_xfer_ok = 1,},
570 		.callback = &uaudio_chan_record_callback,
571 	},
572 
573 	[2] = {
574 		.type = UE_ISOCHRONOUS,
575 		.endpoint = UE_ADDR_ANY,
576 		.direction = UE_DIR_OUT,
577 		.bufsize = 0,	/* use "wMaxPacketSize * frames" */
578 		.frames = 1,
579 		.flags = {.no_pipe_ok = 1,.short_xfer_ok = 1,},
580 		.callback = &uaudio_chan_record_sync_callback,
581 	},
582 };
583 
584 static const struct usb_config
585 	uaudio_cfg_play[UAUDIO_NCHANBUFS + 1] = {
586 	[0] = {
587 		.type = UE_ISOCHRONOUS,
588 		.endpoint = UE_ADDR_ANY,
589 		.direction = UE_DIR_OUT,
590 		.bufsize = 0,	/* use "wMaxPacketSize * frames" */
591 		.frames = UAUDIO_NFRAMES,
592 		.flags = {.short_xfer_ok = 1,},
593 		.callback = &uaudio_chan_play_callback,
594 	},
595 
596 	[1] = {
597 		.type = UE_ISOCHRONOUS,
598 		.endpoint = UE_ADDR_ANY,
599 		.direction = UE_DIR_OUT,
600 		.bufsize = 0,	/* use "wMaxPacketSize * frames" */
601 		.frames = UAUDIO_NFRAMES,
602 		.flags = {.short_xfer_ok = 1,},
603 		.callback = &uaudio_chan_play_callback,
604 	},
605 
606 	[2] = {
607 		.type = UE_ISOCHRONOUS,
608 		.endpoint = UE_ADDR_ANY,
609 		.direction = UE_DIR_IN,
610 		.bufsize = 0,	/* use "wMaxPacketSize * frames" */
611 		.frames = 1,
612 		.flags = {.no_pipe_ok = 1,.short_xfer_ok = 1,},
613 		.callback = &uaudio_chan_play_sync_callback,
614 	},
615 };
616 
617 static const struct usb_config
618 	uaudio_mixer_config[1] = {
619 	[0] = {
620 		.type = UE_CONTROL,
621 		.endpoint = 0x00,	/* Control pipe */
622 		.direction = UE_DIR_ANY,
623 		.bufsize = (sizeof(struct usb_device_request) + 4),
624 		.callback = &uaudio_mixer_write_cfg_callback,
625 		.timeout = 1000,	/* 1 second */
626 	},
627 };
628 
629 static const
630 uint8_t	umidi_cmd_to_len[16] = {
631 	[0x0] = 0,			/* reserved */
632 	[0x1] = 0,			/* reserved */
633 	[0x2] = 2,			/* bytes */
634 	[0x3] = 3,			/* bytes */
635 	[0x4] = 3,			/* bytes */
636 	[0x5] = 1,			/* bytes */
637 	[0x6] = 2,			/* bytes */
638 	[0x7] = 3,			/* bytes */
639 	[0x8] = 3,			/* bytes */
640 	[0x9] = 3,			/* bytes */
641 	[0xA] = 3,			/* bytes */
642 	[0xB] = 3,			/* bytes */
643 	[0xC] = 2,			/* bytes */
644 	[0xD] = 2,			/* bytes */
645 	[0xE] = 3,			/* bytes */
646 	[0xF] = 1,			/* bytes */
647 };
648 
649 static const struct usb_config
650 	umidi_config[UMIDI_N_TRANSFER] = {
651 	[UMIDI_TX_TRANSFER] = {
652 		.type = UE_BULK,
653 		.endpoint = UE_ADDR_ANY,
654 		.direction = UE_DIR_OUT,
655 		.bufsize = UMIDI_TX_BUFFER,
656 		.callback = &umidi_bulk_write_callback,
657 	},
658 
659 	[UMIDI_RX_TRANSFER] = {
660 		.type = UE_BULK,
661 		.endpoint = UE_ADDR_ANY,
662 		.direction = UE_DIR_IN,
663 		.bufsize = 4,	/* bytes */
664 		.flags = {.short_xfer_ok = 1,.proxy_buffer = 1,},
665 		.callback = &umidi_bulk_read_callback,
666 	},
667 };
668 
669 static const struct usb_config
670 	uaudio_hid_config[UAUDIO_HID_N_TRANSFER] = {
671 	[UAUDIO_HID_RX_TRANSFER] = {
672 		.type = UE_INTERRUPT,
673 		.endpoint = UE_ADDR_ANY,
674 		.direction = UE_DIR_IN,
675 		.bufsize = 0,	/* use wMaxPacketSize */
676 		.flags = {.short_xfer_ok = 1,},
677 		.callback = &uaudio_hid_rx_callback,
678 	},
679 };
680 
681 static devclass_t uaudio_devclass;
682 
683 static device_method_t uaudio_methods[] = {
684 	DEVMETHOD(device_probe, uaudio_probe),
685 	DEVMETHOD(device_attach, uaudio_attach),
686 	DEVMETHOD(device_detach, uaudio_detach),
687 	DEVMETHOD(device_suspend, bus_generic_suspend),
688 	DEVMETHOD(device_resume, bus_generic_resume),
689 	DEVMETHOD(device_shutdown, bus_generic_shutdown),
690 
691 	DEVMETHOD_END
692 };
693 
694 static driver_t uaudio_driver = {
695 	.name = "uaudio",
696 	.methods = uaudio_methods,
697 	.size = sizeof(struct uaudio_softc),
698 };
699 
700 /* The following table is derived from Linux's quirks-table.h */
701 static const STRUCT_USB_HOST_ID uaudio_vendor_midi[] = {
702 	{ USB_VPI(USB_VENDOR_YAMAHA, 0x1000, 0) }, /* UX256 */
703 	{ USB_VPI(USB_VENDOR_YAMAHA, 0x1001, 0) }, /* MU1000 */
704 	{ USB_VPI(USB_VENDOR_YAMAHA, 0x1002, 0) }, /* MU2000 */
705 	{ USB_VPI(USB_VENDOR_YAMAHA, 0x1003, 0) }, /* MU500 */
706 	{ USB_VPI(USB_VENDOR_YAMAHA, 0x1004, 3) }, /* UW500 */
707 	{ USB_VPI(USB_VENDOR_YAMAHA, 0x1005, 0) }, /* MOTIF6 */
708 	{ USB_VPI(USB_VENDOR_YAMAHA, 0x1006, 0) }, /* MOTIF7 */
709 	{ USB_VPI(USB_VENDOR_YAMAHA, 0x1007, 0) }, /* MOTIF8 */
710 	{ USB_VPI(USB_VENDOR_YAMAHA, 0x1008, 0) }, /* UX96 */
711 	{ USB_VPI(USB_VENDOR_YAMAHA, 0x1009, 0) }, /* UX16 */
712 	{ USB_VPI(USB_VENDOR_YAMAHA, 0x100a, 3) }, /* EOS BX */
713 	{ USB_VPI(USB_VENDOR_YAMAHA, 0x100c, 0) }, /* UC-MX */
714 	{ USB_VPI(USB_VENDOR_YAMAHA, 0x100d, 0) }, /* UC-KX */
715 	{ USB_VPI(USB_VENDOR_YAMAHA, 0x100e, 0) }, /* S08 */
716 	{ USB_VPI(USB_VENDOR_YAMAHA, 0x100f, 0) }, /* CLP-150 */
717 	{ USB_VPI(USB_VENDOR_YAMAHA, 0x1010, 0) }, /* CLP-170 */
718 	{ USB_VPI(USB_VENDOR_YAMAHA, 0x1011, 0) }, /* P-250 */
719 	{ USB_VPI(USB_VENDOR_YAMAHA, 0x1012, 0) }, /* TYROS */
720 	{ USB_VPI(USB_VENDOR_YAMAHA, 0x1013, 0) }, /* PF-500 */
721 	{ USB_VPI(USB_VENDOR_YAMAHA, 0x1014, 0) }, /* S90 */
722 	{ USB_VPI(USB_VENDOR_YAMAHA, 0x1015, 0) }, /* MOTIF-R */
723 	{ USB_VPI(USB_VENDOR_YAMAHA, 0x1016, 0) }, /* MDP-5 */
724 	{ USB_VPI(USB_VENDOR_YAMAHA, 0x1017, 0) }, /* CVP-204 */
725 	{ USB_VPI(USB_VENDOR_YAMAHA, 0x1018, 0) }, /* CVP-206 */
726 	{ USB_VPI(USB_VENDOR_YAMAHA, 0x1019, 0) }, /* CVP-208 */
727 	{ USB_VPI(USB_VENDOR_YAMAHA, 0x101a, 0) }, /* CVP-210 */
728 	{ USB_VPI(USB_VENDOR_YAMAHA, 0x101b, 0) }, /* PSR-1100 */
729 	{ USB_VPI(USB_VENDOR_YAMAHA, 0x101c, 0) }, /* PSR-2100 */
730 	{ USB_VPI(USB_VENDOR_YAMAHA, 0x101d, 0) }, /* CLP-175 */
731 	{ USB_VPI(USB_VENDOR_YAMAHA, 0x101e, 0) }, /* PSR-K1 */
732 	{ USB_VPI(USB_VENDOR_YAMAHA, 0x101f, 0) }, /* EZ-J24 */
733 	{ USB_VPI(USB_VENDOR_YAMAHA, 0x1020, 0) }, /* EZ-250i */
734 	{ USB_VPI(USB_VENDOR_YAMAHA, 0x1021, 0) }, /* MOTIF ES 6 */
735 	{ USB_VPI(USB_VENDOR_YAMAHA, 0x1022, 0) }, /* MOTIF ES 7 */
736 	{ USB_VPI(USB_VENDOR_YAMAHA, 0x1023, 0) }, /* MOTIF ES 8 */
737 	{ USB_VPI(USB_VENDOR_YAMAHA, 0x1024, 0) }, /* CVP-301 */
738 	{ USB_VPI(USB_VENDOR_YAMAHA, 0x1025, 0) }, /* CVP-303 */
739 	{ USB_VPI(USB_VENDOR_YAMAHA, 0x1026, 0) }, /* CVP-305 */
740 	{ USB_VPI(USB_VENDOR_YAMAHA, 0x1027, 0) }, /* CVP-307 */
741 	{ USB_VPI(USB_VENDOR_YAMAHA, 0x1028, 0) }, /* CVP-309 */
742 	{ USB_VPI(USB_VENDOR_YAMAHA, 0x1029, 0) }, /* CVP-309GP */
743 	{ USB_VPI(USB_VENDOR_YAMAHA, 0x102a, 0) }, /* PSR-1500 */
744 	{ USB_VPI(USB_VENDOR_YAMAHA, 0x102b, 0) }, /* PSR-3000 */
745 	{ USB_VPI(USB_VENDOR_YAMAHA, 0x102e, 0) }, /* ELS-01/01C */
746 	{ USB_VPI(USB_VENDOR_YAMAHA, 0x1030, 0) }, /* PSR-295/293 */
747 	{ USB_VPI(USB_VENDOR_YAMAHA, 0x1031, 0) }, /* DGX-205/203 */
748 	{ USB_VPI(USB_VENDOR_YAMAHA, 0x1032, 0) }, /* DGX-305 */
749 	{ USB_VPI(USB_VENDOR_YAMAHA, 0x1033, 0) }, /* DGX-505 */
750 	{ USB_VPI(USB_VENDOR_YAMAHA, 0x1034, 0) }, /* NULL */
751 	{ USB_VPI(USB_VENDOR_YAMAHA, 0x1035, 0) }, /* NULL */
752 	{ USB_VPI(USB_VENDOR_YAMAHA, 0x1036, 0) }, /* NULL */
753 	{ USB_VPI(USB_VENDOR_YAMAHA, 0x1037, 0) }, /* NULL */
754 	{ USB_VPI(USB_VENDOR_YAMAHA, 0x1038, 0) }, /* NULL */
755 	{ USB_VPI(USB_VENDOR_YAMAHA, 0x1039, 0) }, /* NULL */
756 	{ USB_VPI(USB_VENDOR_YAMAHA, 0x103a, 0) }, /* NULL */
757 	{ USB_VPI(USB_VENDOR_YAMAHA, 0x103b, 0) }, /* NULL */
758 	{ USB_VPI(USB_VENDOR_YAMAHA, 0x103c, 0) }, /* NULL */
759 	{ USB_VPI(USB_VENDOR_YAMAHA, 0x103d, 0) }, /* NULL */
760 	{ USB_VPI(USB_VENDOR_YAMAHA, 0x103e, 0) }, /* NULL */
761 	{ USB_VPI(USB_VENDOR_YAMAHA, 0x103f, 0) }, /* NULL */
762 	{ USB_VPI(USB_VENDOR_YAMAHA, 0x1040, 0) }, /* NULL */
763 	{ USB_VPI(USB_VENDOR_YAMAHA, 0x1041, 0) }, /* NULL */
764 	{ USB_VPI(USB_VENDOR_YAMAHA, 0x1042, 0) }, /* NULL */
765 	{ USB_VPI(USB_VENDOR_YAMAHA, 0x1043, 0) }, /* NULL */
766 	{ USB_VPI(USB_VENDOR_YAMAHA, 0x1044, 0) }, /* NULL */
767 	{ USB_VPI(USB_VENDOR_YAMAHA, 0x1045, 0) }, /* NULL */
768 	{ USB_VPI(USB_VENDOR_YAMAHA, 0x104e, 0) }, /* NULL */
769 	{ USB_VPI(USB_VENDOR_YAMAHA, 0x104f, 0) }, /* NULL */
770 	{ USB_VPI(USB_VENDOR_YAMAHA, 0x1050, 0) }, /* NULL */
771 	{ USB_VPI(USB_VENDOR_YAMAHA, 0x1051, 0) }, /* NULL */
772 	{ USB_VPI(USB_VENDOR_YAMAHA, 0x1052, 0) }, /* NULL */
773 	{ USB_VPI(USB_VENDOR_YAMAHA, 0x1053, 0) }, /* NULL */
774 	{ USB_VPI(USB_VENDOR_YAMAHA, 0x1054, 0) }, /* NULL */
775 	{ USB_VPI(USB_VENDOR_YAMAHA, 0x1055, 0) }, /* NULL */
776 	{ USB_VPI(USB_VENDOR_YAMAHA, 0x1056, 0) }, /* NULL */
777 	{ USB_VPI(USB_VENDOR_YAMAHA, 0x1057, 0) }, /* NULL */
778 	{ USB_VPI(USB_VENDOR_YAMAHA, 0x1058, 0) }, /* NULL */
779 	{ USB_VPI(USB_VENDOR_YAMAHA, 0x1059, 0) }, /* NULL */
780 	{ USB_VPI(USB_VENDOR_YAMAHA, 0x105a, 0) }, /* NULL */
781 	{ USB_VPI(USB_VENDOR_YAMAHA, 0x105b, 0) }, /* NULL */
782 	{ USB_VPI(USB_VENDOR_YAMAHA, 0x105c, 0) }, /* NULL */
783 	{ USB_VPI(USB_VENDOR_YAMAHA, 0x105d, 0) }, /* NULL */
784 	{ USB_VPI(USB_VENDOR_YAMAHA, 0x1503, 3) }, /* MOX6/MOX8 */
785 	{ USB_VPI(USB_VENDOR_YAMAHA, 0x2000, 0) }, /* DGP-7 */
786 	{ USB_VPI(USB_VENDOR_YAMAHA, 0x2001, 0) }, /* DGP-5 */
787 	{ USB_VPI(USB_VENDOR_YAMAHA, 0x2002, 0) }, /* NULL */
788 	{ USB_VPI(USB_VENDOR_YAMAHA, 0x2003, 0) }, /* NULL */
789 	{ USB_VPI(USB_VENDOR_YAMAHA, 0x5000, 0) }, /* CS1D */
790 	{ USB_VPI(USB_VENDOR_YAMAHA, 0x5001, 0) }, /* DSP1D */
791 	{ USB_VPI(USB_VENDOR_YAMAHA, 0x5002, 0) }, /* DME32 */
792 	{ USB_VPI(USB_VENDOR_YAMAHA, 0x5003, 0) }, /* DM2000 */
793 	{ USB_VPI(USB_VENDOR_YAMAHA, 0x5004, 0) }, /* 02R96 */
794 	{ USB_VPI(USB_VENDOR_YAMAHA, 0x5005, 0) }, /* ACU16-C */
795 	{ USB_VPI(USB_VENDOR_YAMAHA, 0x5006, 0) }, /* NHB32-C */
796 	{ USB_VPI(USB_VENDOR_YAMAHA, 0x5007, 0) }, /* DM1000 */
797 	{ USB_VPI(USB_VENDOR_YAMAHA, 0x5008, 0) }, /* 01V96 */
798 	{ USB_VPI(USB_VENDOR_YAMAHA, 0x5009, 0) }, /* SPX2000 */
799 	{ USB_VPI(USB_VENDOR_YAMAHA, 0x500a, 0) }, /* PM5D */
800 	{ USB_VPI(USB_VENDOR_YAMAHA, 0x500b, 0) }, /* DME64N */
801 	{ USB_VPI(USB_VENDOR_YAMAHA, 0x500c, 0) }, /* DME24N */
802 	{ USB_VPI(USB_VENDOR_YAMAHA, 0x500d, 0) }, /* NULL */
803 	{ USB_VPI(USB_VENDOR_YAMAHA, 0x500e, 0) }, /* NULL */
804 	{ USB_VPI(USB_VENDOR_YAMAHA, 0x500f, 0) }, /* NULL */
805 	{ USB_VPI(USB_VENDOR_YAMAHA, 0x7000, 0) }, /* DTX */
806 	{ USB_VPI(USB_VENDOR_YAMAHA, 0x7010, 0) }, /* UB99 */
807 };
808 
809 static const STRUCT_USB_HOST_ID __used uaudio_devs[] = {
810 	/* Generic USB audio class match */
811 	{USB_IFACE_CLASS(UICLASS_AUDIO),
812 	 USB_IFACE_SUBCLASS(UISUBCLASS_AUDIOCONTROL),},
813 	/* Generic USB MIDI class match */
814 	{USB_IFACE_CLASS(UICLASS_AUDIO),
815 	 USB_IFACE_SUBCLASS(UISUBCLASS_MIDISTREAM),},
816 };
817 
818 static int
819 uaudio_probe(device_t dev)
820 {
821 	struct usb_attach_arg *uaa = device_get_ivars(dev);
822 
823 	if (uaa->usb_mode != USB_MODE_HOST)
824 		return (ENXIO);
825 
826 	/* lookup non-standard device(s) */
827 
828 	if (usbd_lookup_id_by_uaa(uaudio_vendor_midi,
829 	    sizeof(uaudio_vendor_midi), uaa) == 0) {
830 		return (BUS_PROBE_SPECIFIC);
831 	}
832 
833 	if (uaa->info.bInterfaceClass != UICLASS_AUDIO) {
834 		if (uaa->info.bInterfaceClass != UICLASS_VENDOR ||
835 		    usb_test_quirk(uaa, UQ_AU_VENDOR_CLASS) == 0)
836 			return (ENXIO);
837 	}
838 
839 	/* check for AUDIO control interface */
840 
841 	if (uaa->info.bInterfaceSubClass == UISUBCLASS_AUDIOCONTROL) {
842 		if (usb_test_quirk(uaa, UQ_BAD_AUDIO))
843 			return (ENXIO);
844 		else
845 			return (BUS_PROBE_GENERIC);
846 	}
847 
848 	/* check for MIDI stream */
849 
850 	if (uaa->info.bInterfaceSubClass == UISUBCLASS_MIDISTREAM) {
851 		if (usb_test_quirk(uaa, UQ_BAD_MIDI))
852 			return (ENXIO);
853 		else
854 			return (BUS_PROBE_GENERIC);
855 	}
856 	return (ENXIO);
857 }
858 
859 static int
860 uaudio_attach(device_t dev)
861 {
862 	struct usb_attach_arg *uaa = device_get_ivars(dev);
863 	struct uaudio_softc *sc = device_get_softc(dev);
864 	struct usb_interface_descriptor *id;
865 	usb_error_t err;
866 	device_t child;
867 
868 	sc->sc_play_chan.priv_sc = sc;
869 	sc->sc_rec_chan.priv_sc = sc;
870 	sc->sc_udev = uaa->device;
871 	sc->sc_mixer_iface_index = uaa->info.bIfaceIndex;
872 	sc->sc_mixer_iface_no = uaa->info.bIfaceNum;
873 	sc->sc_config_msg[0].hdr.pm_callback = &uaudio_configure_msg;
874 	sc->sc_config_msg[0].sc = sc;
875 	sc->sc_config_msg[1].hdr.pm_callback = &uaudio_configure_msg;
876 	sc->sc_config_msg[1].sc = sc;
877 
878 	if (usb_test_quirk(uaa, UQ_AUDIO_SWAP_LR))
879 		sc->sc_uq_audio_swap_lr = 1;
880 
881 	if (usb_test_quirk(uaa, UQ_AU_INP_ASYNC))
882 		sc->sc_uq_au_inp_async = 1;
883 
884 	if (usb_test_quirk(uaa, UQ_AU_NO_XU))
885 		sc->sc_uq_au_no_xu = 1;
886 
887 	if (usb_test_quirk(uaa, UQ_BAD_ADC))
888 		sc->sc_uq_bad_adc = 1;
889 
890 	if (usb_test_quirk(uaa, UQ_AU_VENDOR_CLASS))
891 		sc->sc_uq_au_vendor_class = 1;
892 
893 	umidi_init(dev);
894 
895 	device_set_usb_desc(dev);
896 
897 	id = usbd_get_interface_descriptor(uaa->iface);
898 
899 	/* must fill mixer info before channel info */
900 	uaudio_mixer_fill_info(sc, uaa->device, id);
901 
902 	/* fill channel info */
903 	uaudio_chan_fill_info(sc, uaa->device);
904 
905 	DPRINTF("audio rev %d.%02x\n",
906 	    sc->sc_audio_rev >> 8,
907 	    sc->sc_audio_rev & 0xff);
908 
909 	if (sc->sc_mixer_count == 0) {
910 		if (uaa->info.idVendor == USB_VENDOR_MAUDIO &&
911 		    (uaa->info.idProduct == USB_PRODUCT_MAUDIO_FASTTRACKULTRA ||
912 		    uaa->info.idProduct == USB_PRODUCT_MAUDIO_FASTTRACKULTRA8R)) {
913 			DPRINTF("Generating mixer descriptors\n");
914 			uaudio_mixer_controls_create_ftu(sc);
915 		}
916 	}
917 
918 	DPRINTF("%d mixer controls\n",
919 	    sc->sc_mixer_count);
920 
921 	if (sc->sc_play_chan.num_alt > 0) {
922 		uint8_t x;
923 
924 		/*
925 		 * Need to set a default alternate interface, else
926 		 * some USB audio devices might go into an infinte
927 		 * re-enumeration loop:
928 		 */
929 		err = usbd_set_alt_interface_index(sc->sc_udev,
930 		    sc->sc_play_chan.usb_alt[0].iface_index,
931 		    sc->sc_play_chan.usb_alt[0].iface_alt_index);
932 		if (err) {
933 			DPRINTF("setting of alternate index failed: %s!\n",
934 			    usbd_errstr(err));
935 		}
936 		for (x = 0; x != sc->sc_play_chan.num_alt; x++) {
937 			device_printf(dev, "Play: %d Hz, %d ch, %s format, "
938 			    "2x8ms buffer.\n",
939 			    sc->sc_play_chan.usb_alt[x].sample_rate,
940 			    sc->sc_play_chan.usb_alt[x].channels,
941 			    sc->sc_play_chan.usb_alt[x].p_fmt->description);
942 		}
943 	} else {
944 		device_printf(dev, "No playback.\n");
945 	}
946 
947 	if (sc->sc_rec_chan.num_alt > 0) {
948 		uint8_t x;
949 
950 		/*
951 		 * Need to set a default alternate interface, else
952 		 * some USB audio devices might go into an infinte
953 		 * re-enumeration loop:
954 		 */
955 		err = usbd_set_alt_interface_index(sc->sc_udev,
956 		    sc->sc_rec_chan.usb_alt[0].iface_index,
957 		    sc->sc_rec_chan.usb_alt[0].iface_alt_index);
958 		if (err) {
959 			DPRINTF("setting of alternate index failed: %s!\n",
960 			    usbd_errstr(err));
961 		}
962 		for (x = 0; x != sc->sc_rec_chan.num_alt; x++) {
963 			device_printf(dev, "Record: %d Hz, %d ch, %s format, "
964 			    "2x8ms buffer.\n",
965 			    sc->sc_rec_chan.usb_alt[x].sample_rate,
966 			    sc->sc_rec_chan.usb_alt[x].channels,
967 			    sc->sc_rec_chan.usb_alt[x].p_fmt->description);
968 		}
969 	} else {
970 		device_printf(dev, "No recording.\n");
971 	}
972 
973 	if (sc->sc_midi_chan.valid == 0) {
974 		if (usbd_lookup_id_by_uaa(uaudio_vendor_midi,
975 		    sizeof(uaudio_vendor_midi), uaa) == 0) {
976 			sc->sc_midi_chan.iface_index =
977 			    (uint8_t)uaa->driver_info;
978 			sc->sc_midi_chan.iface_alt_index = 0;
979 			sc->sc_midi_chan.valid = 1;
980 		}
981 	}
982 
983 	if (sc->sc_midi_chan.valid) {
984 
985 		if (umidi_probe(dev)) {
986 			goto detach;
987 		}
988 		device_printf(dev, "MIDI sequencer.\n");
989 	} else {
990 		device_printf(dev, "No MIDI sequencer.\n");
991 	}
992 
993 	DPRINTF("doing child attach\n");
994 
995 	/* attach the children */
996 
997 	sc->sc_sndcard_func.func = SCF_PCM;
998 
999 	/*
1000 	 * Only attach a PCM device if we have a playback, recording
1001 	 * or mixer device present:
1002 	 */
1003 	if (sc->sc_play_chan.num_alt > 0 ||
1004 	    sc->sc_rec_chan.num_alt > 0 ||
1005 	    sc->sc_mix_info) {
1006 		child = device_add_child(dev, "pcm", -1);
1007 
1008 		if (child == NULL) {
1009 			DPRINTF("out of memory\n");
1010 			goto detach;
1011 		}
1012 		device_set_ivars(child, &sc->sc_sndcard_func);
1013 	}
1014 
1015 	if (bus_generic_attach(dev)) {
1016 		DPRINTF("child attach failed\n");
1017 		goto detach;
1018 	}
1019 
1020 	if (uaudio_hid_probe(sc, uaa) == 0) {
1021 		device_printf(dev, "HID volume keys found.\n");
1022 	} else {
1023 		device_printf(dev, "No HID volume keys found.\n");
1024 	}
1025 
1026 	/* reload all mixer settings */
1027 	uaudio_mixer_reload_all(sc);
1028 
1029 	return (0);			/* success */
1030 
1031 detach:
1032 	uaudio_detach(dev);
1033 	return (ENXIO);
1034 }
1035 
1036 static void
1037 uaudio_pcm_setflags(device_t dev, uint32_t flags)
1038 {
1039 	pcm_setflags(dev, pcm_getflags(dev) | flags);
1040 }
1041 
1042 int
1043 uaudio_attach_sub(device_t dev, kobj_class_t mixer_class, kobj_class_t chan_class)
1044 {
1045 	struct uaudio_softc *sc = device_get_softc(device_get_parent(dev));
1046 	char status[SND_STATUSLEN];
1047 
1048 	uaudio_mixer_init(sc);
1049 
1050 	if (sc->sc_uq_audio_swap_lr) {
1051 		DPRINTF("hardware has swapped left and right\n");
1052 		/* uaudio_pcm_setflags(dev, SD_F_PSWAPLR); */
1053 	}
1054 	if (!(sc->sc_mix_info & SOUND_MASK_PCM)) {
1055 
1056 		DPRINTF("emulating master volume\n");
1057 
1058 		/*
1059 		 * Emulate missing pcm mixer controller
1060 		 * through FEEDER_VOLUME
1061 		 */
1062 		uaudio_pcm_setflags(dev, SD_F_SOFTPCMVOL);
1063 	}
1064 	if (mixer_init(dev, mixer_class, sc))
1065 		goto detach;
1066 	sc->sc_mixer_init = 1;
1067 
1068 	mixer_hwvol_init(dev);
1069 
1070 	snprintf(status, sizeof(status), "at ? %s", PCM_KLDSTRING(snd_uaudio));
1071 
1072 	if (pcm_register(dev, sc,
1073 	    (sc->sc_play_chan.num_alt > 0) ? 1 : 0,
1074 	    (sc->sc_rec_chan.num_alt > 0) ? 1 : 0)) {
1075 		goto detach;
1076 	}
1077 
1078 	uaudio_pcm_setflags(dev, SD_F_MPSAFE);
1079 	sc->sc_pcm_registered = 1;
1080 
1081 	if (sc->sc_play_chan.num_alt > 0) {
1082 		pcm_addchan(dev, PCMDIR_PLAY, chan_class, sc);
1083 	}
1084 	if (sc->sc_rec_chan.num_alt > 0) {
1085 		pcm_addchan(dev, PCMDIR_REC, chan_class, sc);
1086 	}
1087 	pcm_setstatus(dev, status);
1088 
1089 	uaudio_mixer_register_sysctl(sc, dev);
1090 
1091 	return (0);			/* success */
1092 
1093 detach:
1094 	uaudio_detach_sub(dev);
1095 	return (ENXIO);
1096 }
1097 
1098 int
1099 uaudio_detach_sub(device_t dev)
1100 {
1101 	struct uaudio_softc *sc = device_get_softc(device_get_parent(dev));
1102 	int error = 0;
1103 
1104 repeat:
1105 	if (sc->sc_pcm_registered) {
1106 		error = pcm_unregister(dev);
1107 	} else {
1108 		if (sc->sc_mixer_init) {
1109 			error = mixer_uninit(dev);
1110 		}
1111 	}
1112 
1113 	if (error) {
1114 		device_printf(dev, "Waiting for sound application to exit!\n");
1115 		usb_pause_mtx(NULL, 2 * hz);
1116 		goto repeat;		/* try again */
1117 	}
1118 	return (0);			/* success */
1119 }
1120 
1121 static int
1122 uaudio_detach(device_t dev)
1123 {
1124 	struct uaudio_softc *sc = device_get_softc(dev);
1125 
1126 	/*
1127 	 * Stop USB transfers early so that any audio applications
1128 	 * will time out and close opened /dev/dspX.Y device(s), if
1129 	 * any.
1130 	 */
1131 	usb_proc_explore_lock(sc->sc_udev);
1132 	sc->sc_play_chan.operation = CHAN_OP_DRAIN;
1133 	sc->sc_rec_chan.operation = CHAN_OP_DRAIN;
1134 	usb_proc_explore_mwait(sc->sc_udev,
1135 	    &sc->sc_config_msg[0], &sc->sc_config_msg[1]);
1136 	usb_proc_explore_unlock(sc->sc_udev);
1137 
1138 	usbd_transfer_unsetup(sc->sc_play_chan.xfer, UAUDIO_NCHANBUFS + 1);
1139 	usbd_transfer_unsetup(sc->sc_rec_chan.xfer, UAUDIO_NCHANBUFS + 1);
1140 
1141 	uaudio_hid_detach(sc);
1142 
1143 	if (bus_generic_detach(dev) != 0) {
1144 		DPRINTF("detach failed!\n");
1145 	}
1146 	sbuf_delete(&sc->sc_sndstat);
1147 	sc->sc_sndstat_valid = 0;
1148 
1149 	umidi_detach(dev);
1150 
1151 	/* free mixer data */
1152 
1153 	uaudio_mixer_ctl_free(sc);
1154 
1155 	return (0);
1156 }
1157 
1158 static uint32_t
1159 uaudio_get_buffer_size(struct uaudio_chan *ch, uint8_t alt)
1160 {
1161 	struct uaudio_chan_alt *chan_alt = &ch->usb_alt[alt];
1162 	/* We use 2 times 8ms of buffer */
1163 	uint32_t buf_size = (((chan_alt->sample_rate * (UAUDIO_NFRAMES / 8)) +
1164 	    1000 - 1) / 1000) * chan_alt->sample_size;
1165 	return (buf_size);
1166 }
1167 
1168 static void
1169 uaudio_configure_msg_sub(struct uaudio_softc *sc,
1170     struct uaudio_chan *chan, int dir)
1171 {
1172 	struct uaudio_chan_alt *chan_alt;
1173 	uint32_t frames;
1174 	uint32_t buf_size;
1175 	uint16_t fps;
1176 	uint8_t set_alt;
1177 	uint8_t fps_shift;
1178 	uint8_t operation;
1179 	usb_error_t err;
1180 
1181 	if (chan->num_alt <= 0)
1182 		return;
1183 
1184 	DPRINTF("\n");
1185 
1186 	usb_proc_explore_lock(sc->sc_udev);
1187 	operation = chan->operation;
1188 	chan->operation = CHAN_OP_NONE;
1189 	usb_proc_explore_unlock(sc->sc_udev);
1190 
1191 	mtx_lock(chan->pcm_mtx);
1192 	if (chan->cur_alt != chan->set_alt)
1193 		set_alt = chan->set_alt;
1194 	else
1195 		set_alt = CHAN_MAX_ALT;
1196 	mtx_unlock(chan->pcm_mtx);
1197 
1198 	if (set_alt >= chan->num_alt)
1199 		goto done;
1200 
1201 	chan_alt = chan->usb_alt + set_alt;
1202 
1203 	usbd_transfer_unsetup(chan->xfer, UAUDIO_NCHANBUFS + 1);
1204 
1205 	err = usbd_set_alt_interface_index(sc->sc_udev,
1206 	    chan_alt->iface_index, chan_alt->iface_alt_index);
1207 	if (err) {
1208 		DPRINTF("setting of alternate index failed: %s!\n",
1209 		    usbd_errstr(err));
1210 		goto error;
1211 	}
1212 
1213 	/*
1214 	 * Only set the sample rate if the channel reports that it
1215 	 * supports the frequency control.
1216 	 */
1217 
1218 	if (sc->sc_audio_rev >= UAUDIO_VERSION_30) {
1219 		/* FALLTHROUGH */
1220 	} else if (sc->sc_audio_rev >= UAUDIO_VERSION_20) {
1221 		unsigned int x;
1222 
1223 		for (x = 0; x != 256; x++) {
1224 			if (dir == PCMDIR_PLAY) {
1225 				if (!(sc->sc_mixer_clocks.bit_output[x / 8] &
1226 				    (1 << (x % 8)))) {
1227 					continue;
1228 				}
1229 			} else {
1230 				if (!(sc->sc_mixer_clocks.bit_input[x / 8] &
1231 				    (1 << (x % 8)))) {
1232 					continue;
1233 				}
1234 			}
1235 
1236 			if (uaudio20_set_speed(sc->sc_udev,
1237 			    sc->sc_mixer_iface_no, x, chan_alt->sample_rate)) {
1238 				/*
1239 				 * If the endpoint is adaptive setting
1240 				 * the speed may fail.
1241 				 */
1242 				DPRINTF("setting of sample rate failed! "
1243 				    "(continuing anyway)\n");
1244 			}
1245 		}
1246 	} else if (chan_alt->p_sed.v1->bmAttributes & UA_SED_FREQ_CONTROL) {
1247 		if (uaudio_set_speed(sc->sc_udev,
1248 		    chan_alt->p_ed1->bEndpointAddress, chan_alt->sample_rate)) {
1249 			/*
1250 			 * If the endpoint is adaptive setting the
1251 			 * speed may fail.
1252 			 */
1253 			DPRINTF("setting of sample rate failed! "
1254 			    "(continuing anyway)\n");
1255 		}
1256 	}
1257 	if (usbd_transfer_setup(sc->sc_udev, &chan_alt->iface_index, chan->xfer,
1258 	    chan_alt->usb_cfg, UAUDIO_NCHANBUFS + 1, chan, chan->pcm_mtx)) {
1259 		DPRINTF("could not allocate USB transfers!\n");
1260 		goto error;
1261 	}
1262 
1263 	fps = usbd_get_isoc_fps(sc->sc_udev);
1264 
1265 	if (fps < 8000) {
1266 		/* FULL speed USB */
1267 		frames = 8;
1268 	} else {
1269 		/* HIGH speed USB */
1270 		frames = UAUDIO_NFRAMES;
1271 	}
1272 
1273 	fps_shift = usbd_xfer_get_fps_shift(chan->xfer[0]);
1274 
1275 	/* down shift number of frames per second, if any */
1276 	fps >>= fps_shift;
1277 	frames >>= fps_shift;
1278 
1279 	/* bytes per frame should not be zero */
1280 	chan->bytes_per_frame[0] =
1281 	    ((chan_alt->sample_rate / fps) * chan_alt->sample_size);
1282 	chan->bytes_per_frame[1] =
1283 	    (((chan_alt->sample_rate + fps - 1) / fps) * chan_alt->sample_size);
1284 
1285 	/* setup data rate dithering, if any */
1286 	chan->frames_per_second = fps;
1287 	chan->sample_rem = chan_alt->sample_rate % fps;
1288 	chan->sample_curr = 0;
1289 	chan->frames_per_second = fps;
1290 
1291 	/* compute required buffer size */
1292 	buf_size = (chan->bytes_per_frame[1] * frames);
1293 
1294 	if (buf_size > (chan->end - chan->start)) {
1295 		DPRINTF("buffer size is too big\n");
1296 		goto error;
1297 	}
1298 
1299 	chan->intr_frames = frames;
1300 
1301 	DPRINTF("fps=%d sample_rem=%d\n", (int)fps, (int)chan->sample_rem);
1302 
1303 	if (chan->intr_frames == 0) {
1304 		DPRINTF("frame shift is too high!\n");
1305 		goto error;
1306 	}
1307 
1308 	mtx_lock(chan->pcm_mtx);
1309 	chan->cur_alt = set_alt;
1310 	mtx_unlock(chan->pcm_mtx);
1311 
1312 done:
1313 #if (UAUDIO_NCHANBUFS != 2)
1314 #error "please update code"
1315 #endif
1316 	switch (operation) {
1317 	case CHAN_OP_START:
1318 		mtx_lock(chan->pcm_mtx);
1319 		usbd_transfer_start(chan->xfer[0]);
1320 		usbd_transfer_start(chan->xfer[1]);
1321 		mtx_unlock(chan->pcm_mtx);
1322 		break;
1323 	case CHAN_OP_STOP:
1324 		mtx_lock(chan->pcm_mtx);
1325 		usbd_transfer_stop(chan->xfer[0]);
1326 		usbd_transfer_stop(chan->xfer[1]);
1327 		mtx_unlock(chan->pcm_mtx);
1328 		break;
1329 	default:
1330 		break;
1331 	}
1332 	return;
1333 
1334 error:
1335 	usbd_transfer_unsetup(chan->xfer, UAUDIO_NCHANBUFS + 1);
1336 
1337 	mtx_lock(chan->pcm_mtx);
1338 	chan->cur_alt = CHAN_MAX_ALT;
1339 	mtx_unlock(chan->pcm_mtx);
1340 }
1341 
1342 static void
1343 uaudio_configure_msg(struct usb_proc_msg *pm)
1344 {
1345 	struct uaudio_softc *sc = ((struct uaudio_configure_msg *)pm)->sc;
1346 
1347 	usb_proc_explore_unlock(sc->sc_udev);
1348 	uaudio_configure_msg_sub(sc, &sc->sc_play_chan, PCMDIR_PLAY);
1349 	uaudio_configure_msg_sub(sc, &sc->sc_rec_chan, PCMDIR_REC);
1350 	usb_proc_explore_lock(sc->sc_udev);
1351 }
1352 
1353 /*========================================================================*
1354  * AS - Audio Stream - routines
1355  *========================================================================*/
1356 
1357 #ifdef USB_DEBUG
1358 static void
1359 uaudio_chan_dump_ep_desc(const usb_endpoint_descriptor_audio_t *ed)
1360 {
1361 	if (ed) {
1362 		DPRINTF("endpoint=%p bLength=%d bDescriptorType=%d \n"
1363 		    "bEndpointAddress=%d bmAttributes=0x%x \n"
1364 		    "wMaxPacketSize=%d bInterval=%d \n"
1365 		    "bRefresh=%d bSynchAddress=%d\n",
1366 		    ed, ed->bLength, ed->bDescriptorType,
1367 		    ed->bEndpointAddress, ed->bmAttributes,
1368 		    UGETW(ed->wMaxPacketSize), ed->bInterval,
1369 		    UEP_HAS_REFRESH(ed) ? ed->bRefresh : 0,
1370 		    UEP_HAS_SYNCADDR(ed) ? ed->bSynchAddress : 0);
1371 	}
1372 }
1373 
1374 #endif
1375 
1376 /*
1377  * The following is a workaround for broken no-name USB audio devices
1378  * sold by dealextreme called "3D sound". The problem is that the
1379  * manufacturer computed wMaxPacketSize is too small to hold the
1380  * actual data sent. In other words the device sometimes sends more
1381  * data than it actually reports it can send in a single isochronous
1382  * packet.
1383  */
1384 static void
1385 uaudio_record_fix_fs(usb_endpoint_descriptor_audio_t *ep,
1386     uint32_t xps, uint32_t add)
1387 {
1388 	uint32_t mps;
1389 
1390 	mps = UGETW(ep->wMaxPacketSize);
1391 
1392 	/*
1393 	 * If the device indicates it can send more data than what the
1394 	 * sample rate indicates, we apply the workaround.
1395 	 */
1396 	if (mps > xps) {
1397 
1398 		/* allow additional data */
1399 		xps += add;
1400 
1401 		/* check against the maximum USB 1.x length */
1402 		if (xps > 1023)
1403 			xps = 1023;
1404 
1405 		/* check if we should do an update */
1406 		if (mps < xps) {
1407 			/* simply update the wMaxPacketSize field */
1408 			USETW(ep->wMaxPacketSize, xps);
1409 			DPRINTF("Workaround: Updated wMaxPacketSize "
1410 			    "from %d to %d bytes.\n",
1411 			    (int)mps, (int)xps);
1412 		}
1413 	}
1414 }
1415 
1416 static usb_error_t
1417 uaudio20_check_rate(struct usb_device *udev, uint8_t iface_no,
1418     uint8_t clockid, uint32_t rate)
1419 {
1420 	struct usb_device_request req;
1421 	usb_error_t error;
1422 	uint8_t data[255];
1423 	uint16_t actlen;
1424 	uint16_t rates;
1425 	uint16_t x;
1426 
1427 	DPRINTFN(6, "ifaceno=%d clockid=%d rate=%u\n",
1428 	    iface_no, clockid, rate);
1429 
1430 	req.bmRequestType = UT_READ_CLASS_INTERFACE;
1431 	req.bRequest = UA20_CS_RANGE;
1432 	USETW2(req.wValue, UA20_CS_SAM_FREQ_CONTROL, 0);
1433 	USETW2(req.wIndex, clockid, iface_no);
1434 	USETW(req.wLength, 255);
1435 
1436         error = usbd_do_request_flags(udev, NULL, &req, data,
1437 	    USB_SHORT_XFER_OK, &actlen, USB_DEFAULT_TIMEOUT);
1438 
1439 	if (error != 0 || actlen < 2)
1440 		return (USB_ERR_INVAL);
1441 
1442 	rates = data[0] | (data[1] << 8);
1443 	actlen = (actlen - 2) / 12;
1444 
1445 	if (rates > actlen) {
1446 		DPRINTF("Too many rates\n");
1447 		rates = actlen;
1448 	}
1449 
1450 	for (x = 0; x != rates; x++) {
1451 		uint32_t min = UGETDW(data + 2 + (12 * x));
1452 		uint32_t max = UGETDW(data + 6 + (12 * x));
1453 		uint32_t res = UGETDW(data + 10 + (12 * x));
1454 
1455 		if (res == 0) {
1456 			DPRINTF("Zero residue\n");
1457 			res = 1;
1458 		}
1459 
1460 		if (min > max) {
1461 			DPRINTF("Swapped max and min\n");
1462 			uint32_t temp;
1463 			temp = min;
1464 			min = max;
1465 			max = temp;
1466 		}
1467 
1468 		if (rate >= min && rate <= max &&
1469 		    (((rate - min) % res) == 0)) {
1470 			return (0);
1471 		}
1472 	}
1473 	return (USB_ERR_INVAL);
1474 }
1475 
1476 static void
1477 uaudio_chan_fill_info_sub(struct uaudio_softc *sc, struct usb_device *udev,
1478     uint32_t rate, uint8_t channels, uint8_t bit_resolution)
1479 {
1480 	struct usb_descriptor *desc = NULL;
1481 	union uaudio_asid asid = { NULL };
1482 	union uaudio_asf1d asf1d = { NULL };
1483 	union uaudio_sed sed = { NULL };
1484 	usb_endpoint_descriptor_audio_t *ed1 = NULL;
1485 	const struct usb_audio_control_descriptor *acdp = NULL;
1486 	struct usb_config_descriptor *cd = usbd_get_config_descriptor(udev);
1487 	struct usb_interface_descriptor *id;
1488 	const struct uaudio_format *p_fmt = NULL;
1489 	struct uaudio_chan *chan;
1490 	struct uaudio_chan_alt *chan_alt;
1491 	uint32_t format;
1492 	uint16_t curidx = 0xFFFF;
1493 	uint16_t lastidx = 0xFFFF;
1494 	uint16_t alt_index = 0;
1495 	uint16_t audio_rev = 0;
1496 	uint16_t x;
1497 	uint8_t ep_dir;
1498 	uint8_t bChannels;
1499 	uint8_t bBitResolution;
1500 	uint8_t audio_if = 0;
1501 	uint8_t uma_if_class;
1502 
1503 	while ((desc = usb_desc_foreach(cd, desc))) {
1504 
1505 		if ((desc->bDescriptorType == UDESC_INTERFACE) &&
1506 		    (desc->bLength >= sizeof(*id))) {
1507 
1508 			id = (void *)desc;
1509 
1510 			if (id->bInterfaceNumber != lastidx) {
1511 				lastidx = id->bInterfaceNumber;
1512 				curidx++;
1513 				alt_index = 0;
1514 
1515 			} else {
1516 				alt_index++;
1517 			}
1518 
1519 			if ((!(sc->sc_hid.flags & UAUDIO_HID_VALID)) &&
1520 			    (id->bInterfaceClass == UICLASS_HID) &&
1521 			    (id->bInterfaceSubClass == 0) &&
1522 			    (id->bInterfaceProtocol == 0) &&
1523 			    (alt_index == 0) &&
1524 			    usbd_get_iface(udev, curidx) != NULL) {
1525 				DPRINTF("Found HID interface at %d\n",
1526 				    curidx);
1527 				sc->sc_hid.flags |= UAUDIO_HID_VALID;
1528 				sc->sc_hid.iface_index = curidx;
1529 			}
1530 
1531 			uma_if_class =
1532 			    ((id->bInterfaceClass == UICLASS_AUDIO) ||
1533 			    ((id->bInterfaceClass == UICLASS_VENDOR) &&
1534 			    (sc->sc_uq_au_vendor_class != 0)));
1535 
1536 			if ((uma_if_class != 0) && (id->bInterfaceSubClass == UISUBCLASS_AUDIOSTREAM)) {
1537 				audio_if = 1;
1538 			} else {
1539 				audio_if = 0;
1540 			}
1541 
1542 			if ((uma_if_class != 0) &&
1543 			    (id->bInterfaceSubClass == UISUBCLASS_MIDISTREAM)) {
1544 
1545 				/*
1546 				 * XXX could allow multiple MIDI interfaces
1547 				 */
1548 
1549 				if ((sc->sc_midi_chan.valid == 0) &&
1550 				    usbd_get_iface(udev, curidx)) {
1551 					sc->sc_midi_chan.iface_index = curidx;
1552 					sc->sc_midi_chan.iface_alt_index = alt_index;
1553 					sc->sc_midi_chan.valid = 1;
1554 				}
1555 			}
1556 			asid.v1 = NULL;
1557 			asf1d.v1 = NULL;
1558 			ed1 = NULL;
1559 			sed.v1 = NULL;
1560 		}
1561 
1562 		if (audio_if == 0) {
1563 			if ((acdp == NULL) &&
1564 			    (desc->bDescriptorType == UDESC_CS_INTERFACE) &&
1565 			    (desc->bDescriptorSubtype == UDESCSUB_AC_HEADER) &&
1566 			    (desc->bLength >= sizeof(*acdp))) {
1567 				acdp = (void *)desc;
1568 				audio_rev = UGETW(acdp->bcdADC);
1569 			}
1570 
1571 			/*
1572 			 * Don't collect any USB audio descriptors if
1573 			 * this is not an USB audio stream interface.
1574 			 */
1575 			continue;
1576 		}
1577 
1578 		if ((acdp != NULL) &&
1579 		    (desc->bDescriptorType == UDESC_CS_INTERFACE) &&
1580 		    (desc->bDescriptorSubtype == AS_GENERAL) &&
1581 		    (asid.v1 == NULL)) {
1582 			if (audio_rev >= UAUDIO_VERSION_30) {
1583 				/* FALLTHROUGH */
1584 			} else if (audio_rev >= UAUDIO_VERSION_20) {
1585 				if (desc->bLength >= sizeof(*asid.v2)) {
1586 					asid.v2 = (void *)desc;
1587 				}
1588 			} else {
1589 				if (desc->bLength >= sizeof(*asid.v1)) {
1590 					asid.v1 = (void *)desc;
1591 				}
1592 			}
1593 		}
1594 		if ((acdp != NULL) &&
1595 		    (desc->bDescriptorType == UDESC_CS_INTERFACE) &&
1596 		    (desc->bDescriptorSubtype == FORMAT_TYPE) &&
1597 		    (asf1d.v1 == NULL)) {
1598 			if (audio_rev >= UAUDIO_VERSION_30) {
1599 				/* FALLTHROUGH */
1600 			} else if (audio_rev >= UAUDIO_VERSION_20) {
1601 				if (desc->bLength >= sizeof(*asf1d.v2))
1602 					asf1d.v2 = (void *)desc;
1603 			} else {
1604 				if (desc->bLength >= sizeof(*asf1d.v1)) {
1605 					asf1d.v1 = (void *)desc;
1606 
1607 					if (asf1d.v1->bFormatType != FORMAT_TYPE_I) {
1608 						DPRINTFN(11, "ignored bFormatType = %d\n",
1609 						    asf1d.v1->bFormatType);
1610 						asf1d.v1 = NULL;
1611 						continue;
1612 					}
1613 					if (desc->bLength < (sizeof(*asf1d.v1) +
1614 					    ((asf1d.v1->bSamFreqType == 0) ? 6 :
1615 					    (asf1d.v1->bSamFreqType * 3)))) {
1616 						DPRINTFN(11, "invalid descriptor, "
1617 						    "too short\n");
1618 						asf1d.v1 = NULL;
1619 						continue;
1620 					}
1621 				}
1622 			}
1623 		}
1624 		if ((desc->bDescriptorType == UDESC_ENDPOINT) &&
1625 		    (desc->bLength >= UEP_MINSIZE) &&
1626 		    (ed1 == NULL)) {
1627 			ed1 = (void *)desc;
1628 			if (UE_GET_XFERTYPE(ed1->bmAttributes) != UE_ISOCHRONOUS) {
1629 				ed1 = NULL;
1630 				continue;
1631 			}
1632 		}
1633 		if ((acdp != NULL) &&
1634 		    (desc->bDescriptorType == UDESC_CS_ENDPOINT) &&
1635 		    (desc->bDescriptorSubtype == AS_GENERAL) &&
1636 		    (sed.v1 == NULL)) {
1637 			if (audio_rev >= UAUDIO_VERSION_30) {
1638 				/* FALLTHROUGH */
1639 			} else if (audio_rev >= UAUDIO_VERSION_20) {
1640 				if (desc->bLength >= sizeof(*sed.v2))
1641 					sed.v2 = (void *)desc;
1642 			} else {
1643 				if (desc->bLength >= sizeof(*sed.v1))
1644 					sed.v1 = (void *)desc;
1645 			}
1646 		}
1647 		if (asid.v1 == NULL || asf1d.v1 == NULL ||
1648 		    ed1 == NULL || sed.v1 == NULL) {
1649 			/* need more descriptors */
1650 			continue;
1651 		}
1652 
1653 		ep_dir = UE_GET_DIR(ed1->bEndpointAddress);
1654 
1655 		/* We ignore sync endpoint information until further. */
1656 
1657 		if (audio_rev >= UAUDIO_VERSION_30) {
1658 			goto next_ep;
1659 		} else if (audio_rev >= UAUDIO_VERSION_20) {
1660 
1661 			uint32_t dwFormat;
1662 			uint8_t bSubslotSize;
1663 
1664 			dwFormat = UGETDW(asid.v2->bmFormats);
1665 			bChannels = asid.v2->bNrChannels;
1666 			bBitResolution = asf1d.v2->bBitResolution;
1667 			bSubslotSize = asf1d.v2->bSubslotSize;
1668 
1669 			/* Map 4-byte aligned 24-bit samples into 32-bit */
1670 			if (bBitResolution == 24 && bSubslotSize == 4)
1671 				bBitResolution = 32;
1672 
1673 			if (bBitResolution != (bSubslotSize * 8)) {
1674 				DPRINTF("Invalid bSubslotSize\n");
1675 				goto next_ep;
1676 			}
1677 
1678 			if ((bChannels != channels) ||
1679 			    (bBitResolution != bit_resolution)) {
1680 				DPRINTF("Wrong number of channels\n");
1681 				goto next_ep;
1682 			}
1683 
1684 			for (p_fmt = uaudio20_formats;
1685 			    p_fmt->wFormat != 0; p_fmt++) {
1686 				if ((p_fmt->wFormat & dwFormat) &&
1687 				    (p_fmt->bPrecision == bBitResolution))
1688 					break;
1689 			}
1690 
1691 			if (p_fmt->wFormat == 0) {
1692 				DPRINTF("Unsupported audio format\n");
1693 				goto next_ep;
1694 			}
1695 
1696 			for (x = 0; x != 256; x++) {
1697 				if (ep_dir == UE_DIR_OUT) {
1698 					if (!(sc->sc_mixer_clocks.bit_output[x / 8] &
1699 					    (1 << (x % 8)))) {
1700 						continue;
1701 					}
1702 				} else {
1703 					if (!(sc->sc_mixer_clocks.bit_input[x / 8] &
1704 					    (1 << (x % 8)))) {
1705 						continue;
1706 					}
1707 				}
1708 
1709 				DPRINTF("Checking clock ID=%d\n", x);
1710 
1711 				if (uaudio20_check_rate(udev,
1712 				    sc->sc_mixer_iface_no, x, rate)) {
1713 					DPRINTF("Unsupported sampling "
1714 					    "rate, id=%d\n", x);
1715 					goto next_ep;
1716 				}
1717 			}
1718 		} else {
1719 			uint16_t wFormat;
1720 
1721 			wFormat = UGETW(asid.v1->wFormatTag);
1722 			bChannels = UAUDIO_MAX_CHAN(asf1d.v1->bNrChannels);
1723 			bBitResolution = asf1d.v1->bBitResolution;
1724 
1725 			if (asf1d.v1->bSamFreqType == 0) {
1726 				DPRINTFN(16, "Sample rate: %d-%dHz\n",
1727 				    UA_SAMP_LO(asf1d.v1),
1728 				    UA_SAMP_HI(asf1d.v1));
1729 
1730 				if ((rate >= UA_SAMP_LO(asf1d.v1)) &&
1731 				    (rate <= UA_SAMP_HI(asf1d.v1)))
1732 					goto found_rate;
1733 			} else {
1734 
1735 				for (x = 0; x < asf1d.v1->bSamFreqType; x++) {
1736 					DPRINTFN(16, "Sample rate = %dHz\n",
1737 					    UA_GETSAMP(asf1d.v1, x));
1738 
1739 					if (rate == UA_GETSAMP(asf1d.v1, x))
1740 						goto found_rate;
1741 				}
1742 			}
1743 			goto next_ep;
1744 
1745 	found_rate:
1746 			for (p_fmt = uaudio10_formats;
1747 			    p_fmt->wFormat != 0; p_fmt++) {
1748 				if ((p_fmt->wFormat == wFormat) &&
1749 				    (p_fmt->bPrecision == bBitResolution))
1750 					break;
1751 			}
1752 			if (p_fmt->wFormat == 0) {
1753 				DPRINTF("Unsupported audio format\n");
1754 				goto next_ep;
1755 			}
1756 
1757 			if ((bChannels != channels) ||
1758 			    (bBitResolution != bit_resolution)) {
1759 				DPRINTF("Wrong number of channels\n");
1760 				goto next_ep;
1761 			}
1762 		}
1763 
1764 		chan = (ep_dir == UE_DIR_IN) ?
1765 		    &sc->sc_rec_chan : &sc->sc_play_chan;
1766 
1767 		if (usbd_get_iface(udev, curidx) == NULL) {
1768 			DPRINTF("Interface is not valid\n");
1769 			goto next_ep;
1770 		}
1771 		if (chan->num_alt == CHAN_MAX_ALT) {
1772 			DPRINTF("Too many alternate settings\n");
1773 			goto next_ep;
1774 		}
1775 		chan->set_alt = 0;
1776 		chan->cur_alt = CHAN_MAX_ALT;
1777 
1778 		chan_alt = &chan->usb_alt[chan->num_alt++];
1779 
1780 #ifdef USB_DEBUG
1781 		uaudio_chan_dump_ep_desc(ed1);
1782 #endif
1783 		DPRINTF("Sample rate = %dHz, channels = %d, "
1784 		    "bits = %d, format = %s\n", rate, channels,
1785 		    bit_resolution, p_fmt->description);
1786 
1787 		chan_alt->sample_rate = rate;
1788 		chan_alt->p_asf1d = asf1d;
1789 		chan_alt->p_ed1 = ed1;
1790 		chan_alt->p_fmt = p_fmt;
1791 		chan_alt->p_sed = sed;
1792 		chan_alt->iface_index = curidx;
1793 		chan_alt->iface_alt_index = alt_index;
1794 
1795 		usbd_set_parent_iface(sc->sc_udev, curidx,
1796 		    sc->sc_mixer_iface_index);
1797 
1798 		if (ep_dir == UE_DIR_IN)
1799 			chan_alt->usb_cfg = uaudio_cfg_record;
1800 		else
1801 			chan_alt->usb_cfg = uaudio_cfg_play;
1802 
1803 		chan_alt->sample_size = (UAUDIO_MAX_CHAN(channels) *
1804 		    p_fmt->bPrecision) / 8;
1805 		chan_alt->channels = channels;
1806 
1807 		if (ep_dir == UE_DIR_IN &&
1808 		    usbd_get_speed(udev) == USB_SPEED_FULL) {
1809 			uaudio_record_fix_fs(ed1,
1810 			    chan_alt->sample_size * (rate / 1000),
1811 			    chan_alt->sample_size * (rate / 4000));
1812 		}
1813 
1814 		/* setup play/record format */
1815 
1816 		format = chan_alt->p_fmt->freebsd_fmt;
1817 
1818 		switch (chan_alt->channels) {
1819 		case 2:
1820 			/* stereo */
1821 			format = SND_FORMAT(format, 2, 0);
1822 			break;
1823 		case 1:
1824 			/* mono */
1825 			format = SND_FORMAT(format, 1, 0);
1826 			break;
1827 		default:
1828 			/* surround and more */
1829 			format = feeder_matrix_default_format(
1830 			    SND_FORMAT(format, chan_alt->channels, 0));
1831 			break;
1832 		}
1833 
1834 		/* check if format is not supported */
1835 		if (format == 0) {
1836 			DPRINTF("The selected audio format is not supported\n");
1837 			chan->num_alt--;
1838 			goto next_ep;
1839 		}
1840 		if (chan->num_alt > 1) {
1841 			/* we only accumulate one format at different sample rates */
1842 			if (chan->pcm_format[0] != format) {
1843 				DPRINTF("Multiple formats is not supported\n");
1844 				chan->num_alt--;
1845 				goto next_ep;
1846 			}
1847 			/* ignore if duplicate sample rate entry */
1848 			if (rate == chan->usb_alt[chan->num_alt - 2].sample_rate) {
1849 				DPRINTF("Duplicate sample rate detected\n");
1850 				chan->num_alt--;
1851 				goto next_ep;
1852 			}
1853 		}
1854 		chan->pcm_cap.fmtlist = chan->pcm_format;
1855 		chan->pcm_cap.fmtlist[0] = format;
1856 
1857 		if (rate < chan->pcm_cap.minspeed || chan->pcm_cap.minspeed == 0)
1858 			chan->pcm_cap.minspeed = rate;
1859 		if (rate > chan->pcm_cap.maxspeed || chan->pcm_cap.maxspeed == 0)
1860 			chan->pcm_cap.maxspeed = rate;
1861 
1862 		if (sc->sc_sndstat_valid != 0) {
1863 			sbuf_printf(&sc->sc_sndstat, "\n\t"
1864 			    "mode %d.%d:(%s) %dch, %dbit, %s, %dHz",
1865 			    curidx, alt_index,
1866 			    (ep_dir == UE_DIR_IN) ? "input" : "output",
1867 				    channels, p_fmt->bPrecision,
1868 				    p_fmt->description, rate);
1869 		}
1870 
1871 	next_ep:
1872 		sed.v1 = NULL;
1873 		ed1 = NULL;
1874 	}
1875 }
1876 
1877 /* This structure defines all the supported rates. */
1878 
1879 static const uint32_t uaudio_rate_list[CHAN_MAX_ALT] = {
1880 	384000,
1881 	352800,
1882 	192000,
1883 	176400,
1884 	96000,
1885 	88200,
1886 	88000,
1887 	80000,
1888 	72000,
1889 	64000,
1890 	56000,
1891 	48000,
1892 	44100,
1893 	40000,
1894 	32000,
1895 	24000,
1896 	22050,
1897 	16000,
1898 	11025,
1899 	8000,
1900 	0
1901 };
1902 
1903 static void
1904 uaudio_chan_fill_info(struct uaudio_softc *sc, struct usb_device *udev)
1905 {
1906 	uint32_t rate = uaudio_default_rate;
1907 	uint8_t z;
1908 	uint8_t bits = uaudio_default_bits;
1909 	uint8_t y;
1910 	uint8_t channels = uaudio_default_channels;
1911 	uint8_t x;
1912 
1913 	bits -= (bits % 8);
1914 	if ((bits == 0) || (bits > 32)) {
1915 		/* set a valid value */
1916 		bits = 32;
1917 	}
1918 	if (channels == 0) {
1919 		switch (usbd_get_speed(udev)) {
1920 		case USB_SPEED_LOW:
1921 		case USB_SPEED_FULL:
1922 			/*
1923 			 * Due to high bandwidth usage and problems
1924 			 * with HIGH-speed split transactions we
1925 			 * disable surround setups on FULL-speed USB
1926 			 * by default
1927 			 */
1928 			channels = 4;
1929 			break;
1930 		default:
1931 			channels = 16;
1932 			break;
1933 		}
1934 	} else if (channels > 16) {
1935 		channels = 16;
1936 	}
1937 	if (sbuf_new(&sc->sc_sndstat, NULL, 4096, SBUF_AUTOEXTEND)) {
1938 		sc->sc_sndstat_valid = 1;
1939 	}
1940 	/* try to search for a valid config */
1941 
1942 	for (x = channels; x; x--) {
1943 		for (y = bits; y; y -= 8) {
1944 
1945 			/* try user defined rate, if any */
1946 			if (rate != 0)
1947 				uaudio_chan_fill_info_sub(sc, udev, rate, x, y);
1948 
1949 			/* try find a matching rate, if any */
1950 			for (z = 0; uaudio_rate_list[z]; z++)
1951 				uaudio_chan_fill_info_sub(sc, udev, uaudio_rate_list[z], x, y);
1952 		}
1953 	}
1954 	if (sc->sc_sndstat_valid)
1955 		sbuf_finish(&sc->sc_sndstat);
1956 }
1957 
1958 static void
1959 uaudio_chan_play_sync_callback(struct usb_xfer *xfer, usb_error_t error)
1960 {
1961 	struct uaudio_chan *ch = usbd_xfer_softc(xfer);
1962 	struct usb_page_cache *pc;
1963 	uint64_t sample_rate = ch->usb_alt[ch->cur_alt].sample_rate;
1964 	uint8_t buf[4];
1965 	uint64_t temp;
1966 	int len;
1967 	int actlen;
1968 	int nframes;
1969 
1970 	usbd_xfer_status(xfer, &actlen, NULL, NULL, &nframes);
1971 
1972 	switch (USB_GET_STATE(xfer)) {
1973 	case USB_ST_TRANSFERRED:
1974 
1975 		DPRINTFN(6, "transferred %d bytes\n", actlen);
1976 
1977 		if (nframes == 0)
1978 			break;
1979 		len = usbd_xfer_frame_len(xfer, 0);
1980 		if (len == 0)
1981 			break;
1982 		if (len > sizeof(buf))
1983 			len = sizeof(buf);
1984 
1985 		memset(buf, 0, sizeof(buf));
1986 
1987 		pc = usbd_xfer_get_frame(xfer, 0);
1988 		usbd_copy_out(pc, 0, buf, len);
1989 
1990 		temp = UGETDW(buf);
1991 
1992 		DPRINTF("Value = 0x%08x\n", (int)temp);
1993 
1994 		/* auto-detect SYNC format */
1995 
1996 		if (len == 4)
1997 			temp &= 0x0fffffff;
1998 
1999 		/* check for no data */
2000 
2001 		if (temp == 0)
2002 			break;
2003 
2004 		/* correctly scale value */
2005 
2006 		temp = (temp * 125ULL) - 64;
2007 
2008 		/* auto adjust */
2009 
2010 		while (temp < (sample_rate - (sample_rate / 4)))
2011 			temp *= 2;
2012 
2013 		while (temp > (sample_rate + (sample_rate / 2)))
2014 			temp /= 2;
2015 
2016 		/* compare */
2017 
2018 		DPRINTF("Comparing %d < %d\n",
2019 		    (int)temp, (int)sample_rate);
2020 
2021 		if (temp == sample_rate)
2022 			ch->last_sync_state = UAUDIO_SYNC_NONE;
2023 		else if (temp > sample_rate)
2024 			ch->last_sync_state = UAUDIO_SYNC_MORE;
2025 		else
2026 			ch->last_sync_state = UAUDIO_SYNC_LESS;
2027 		break;
2028 
2029 	case USB_ST_SETUP:
2030 		usbd_xfer_set_frames(xfer, 1);
2031 		usbd_xfer_set_frame_len(xfer, 0, usbd_xfer_max_framelen(xfer));
2032 		usbd_transfer_submit(xfer);
2033 		break;
2034 
2035 	default:			/* Error */
2036 		break;
2037 	}
2038 }
2039 
2040 static void
2041 uaudio_chan_play_callback(struct usb_xfer *xfer, usb_error_t error)
2042 {
2043 	struct uaudio_chan *ch = usbd_xfer_softc(xfer);
2044 	struct usb_page_cache *pc;
2045 	uint32_t sample_size = ch->usb_alt[ch->cur_alt].sample_size;
2046 	uint32_t mfl;
2047 	uint32_t total;
2048 	uint32_t blockcount;
2049 	uint32_t n;
2050 	uint32_t offset;
2051 	int actlen;
2052 	int sumlen;
2053 
2054 	usbd_xfer_status(xfer, &actlen, &sumlen, NULL, NULL);
2055 
2056 	if (ch->end == ch->start) {
2057 		DPRINTF("no buffer!\n");
2058 		return;
2059 	}
2060 
2061 	switch (USB_GET_STATE(xfer)) {
2062 	case USB_ST_TRANSFERRED:
2063 tr_transferred:
2064 		if (actlen < sumlen) {
2065 			DPRINTF("short transfer, "
2066 			    "%d of %d bytes\n", actlen, sumlen);
2067 		}
2068 		chn_intr(ch->pcm_ch);
2069 
2070 		/* start SYNC transfer, if any */
2071 		if ((ch->last_sync_time++ & 7) == 0)
2072 			usbd_transfer_start(ch->xfer[UAUDIO_NCHANBUFS]);
2073 
2074 	case USB_ST_SETUP:
2075 		mfl = usbd_xfer_max_framelen(xfer);
2076 
2077 		if (ch->bytes_per_frame[1] > mfl) {
2078 			DPRINTF("bytes per transfer, %d, "
2079 			    "exceeds maximum, %d!\n",
2080 			    ch->bytes_per_frame[1],
2081 			    mfl);
2082 			break;
2083 		}
2084 
2085 		blockcount = ch->intr_frames;
2086 
2087 		/* setup number of frames */
2088 		usbd_xfer_set_frames(xfer, blockcount);
2089 
2090 		/* reset total length */
2091 		total = 0;
2092 
2093 		/* setup frame lengths */
2094 		for (n = 0; n != blockcount; n++) {
2095 			uint32_t frame_len;
2096 
2097 			ch->sample_curr += ch->sample_rem;
2098 			if (ch->sample_curr >= ch->frames_per_second) {
2099 				ch->sample_curr -= ch->frames_per_second;
2100 				frame_len = ch->bytes_per_frame[1];
2101 			} else {
2102 				frame_len = ch->bytes_per_frame[0];
2103 			}
2104 
2105 			if (n == (blockcount - 1)) {
2106 				switch (ch->last_sync_state) {
2107 				case UAUDIO_SYNC_MORE:
2108 					DPRINTFN(6, "sending one sample more\n");
2109 					if ((frame_len + sample_size) <= mfl)
2110 						frame_len += sample_size;
2111 					ch->last_sync_state = UAUDIO_SYNC_NONE;
2112 					break;
2113 				case UAUDIO_SYNC_LESS:
2114 					DPRINTFN(6, "sending one sample less\n");
2115 					if (frame_len >= sample_size)
2116 						frame_len -= sample_size;
2117 					ch->last_sync_state = UAUDIO_SYNC_NONE;
2118 					break;
2119 				default:
2120 					break;
2121 				}
2122 			}
2123 
2124 			usbd_xfer_set_frame_len(xfer, n, frame_len);
2125 			total += frame_len;
2126 		}
2127 
2128 		DPRINTFN(6, "transfer %d bytes\n", total);
2129 
2130 		offset = 0;
2131 
2132 		pc = usbd_xfer_get_frame(xfer, 0);
2133 		while (total > 0) {
2134 
2135 			n = (ch->end - ch->cur);
2136 			if (n > total) {
2137 				n = total;
2138 			}
2139 			usbd_copy_in(pc, offset, ch->cur, n);
2140 
2141 			total -= n;
2142 			ch->cur += n;
2143 			offset += n;
2144 
2145 			if (ch->cur >= ch->end) {
2146 				ch->cur = ch->start;
2147 			}
2148 		}
2149 
2150 		usbd_transfer_submit(xfer);
2151 		break;
2152 
2153 	default:			/* Error */
2154 		if (error == USB_ERR_CANCELLED) {
2155 			break;
2156 		}
2157 		goto tr_transferred;
2158 	}
2159 }
2160 
2161 static void
2162 uaudio_chan_record_sync_callback(struct usb_xfer *xfer, usb_error_t error)
2163 {
2164 	/* TODO */
2165 }
2166 
2167 static void
2168 uaudio_chan_record_callback(struct usb_xfer *xfer, usb_error_t error)
2169 {
2170 	struct uaudio_chan *ch = usbd_xfer_softc(xfer);
2171 	struct usb_page_cache *pc;
2172 	uint32_t offset0;
2173 	uint32_t offset1;
2174 	uint32_t mfl;
2175 	int m;
2176 	int n;
2177 	int len;
2178 	int actlen;
2179 	int nframes;
2180 	int blockcount;
2181 
2182 	usbd_xfer_status(xfer, &actlen, NULL, NULL, &nframes);
2183 	mfl = usbd_xfer_max_framelen(xfer);
2184 
2185 	if (ch->end == ch->start) {
2186 		DPRINTF("no buffer!\n");
2187 		return;
2188 	}
2189 
2190 	switch (USB_GET_STATE(xfer)) {
2191 	case USB_ST_TRANSFERRED:
2192 
2193 		DPRINTFN(6, "transferred %d bytes\n", actlen);
2194 
2195 		offset0 = 0;
2196 		pc = usbd_xfer_get_frame(xfer, 0);
2197 
2198 		for (n = 0; n != nframes; n++) {
2199 
2200 			offset1 = offset0;
2201 			len = usbd_xfer_frame_len(xfer, n);
2202 
2203 			while (len > 0) {
2204 
2205 				m = (ch->end - ch->cur);
2206 
2207 				if (m > len)
2208 					m = len;
2209 
2210 				usbd_copy_out(pc, offset1, ch->cur, m);
2211 
2212 				len -= m;
2213 				offset1 += m;
2214 				ch->cur += m;
2215 
2216 				if (ch->cur >= ch->end) {
2217 					ch->cur = ch->start;
2218 				}
2219 			}
2220 
2221 			offset0 += mfl;
2222 		}
2223 
2224 		chn_intr(ch->pcm_ch);
2225 
2226 	case USB_ST_SETUP:
2227 tr_setup:
2228 		blockcount = ch->intr_frames;
2229 
2230 		usbd_xfer_set_frames(xfer, blockcount);
2231 		for (n = 0; n < blockcount; n++) {
2232 			usbd_xfer_set_frame_len(xfer, n, mfl);
2233 		}
2234 
2235 		usbd_transfer_submit(xfer);
2236 		break;
2237 
2238 	default:			/* Error */
2239 		if (error == USB_ERR_CANCELLED) {
2240 			break;
2241 		}
2242 		goto tr_setup;
2243 	}
2244 }
2245 
2246 void   *
2247 uaudio_chan_init(struct uaudio_softc *sc, struct snd_dbuf *b,
2248     struct pcm_channel *c, int dir)
2249 {
2250 	struct uaudio_chan *ch = ((dir == PCMDIR_PLAY) ?
2251 	    &sc->sc_play_chan : &sc->sc_rec_chan);
2252 	uint32_t buf_size;
2253 	uint8_t x;
2254 
2255 	/* store mutex and PCM channel */
2256 
2257 	ch->pcm_ch = c;
2258 	ch->pcm_mtx = c->lock;
2259 
2260 	/* compute worst case buffer */
2261 
2262 	buf_size = 0;
2263 	for (x = 0; x != ch->num_alt; x++) {
2264 		uint32_t temp = uaudio_get_buffer_size(ch, x);
2265 		if (temp > buf_size)
2266 			buf_size = temp;
2267 	}
2268 
2269 	/* allow double buffering */
2270 	buf_size *= 2;
2271 
2272 	DPRINTF("Worst case buffer is %d bytes\n", (int)buf_size);
2273 
2274 	ch->buf = malloc(buf_size, M_DEVBUF, M_WAITOK | M_ZERO);
2275 	if (ch->buf == NULL)
2276 		goto error;
2277 	if (sndbuf_setup(b, ch->buf, buf_size) != 0)
2278 		goto error;
2279 
2280 	ch->start = ch->buf;
2281 	ch->end = ch->buf + buf_size;
2282 	ch->cur = ch->buf;
2283 	ch->pcm_buf = b;
2284 	ch->max_buf = buf_size;
2285 
2286 	if (ch->pcm_mtx == NULL) {
2287 		DPRINTF("ERROR: PCM channels does not have a mutex!\n");
2288 		goto error;
2289 	}
2290 	return (ch);
2291 
2292 error:
2293 	uaudio_chan_free(ch);
2294 	return (NULL);
2295 }
2296 
2297 int
2298 uaudio_chan_free(struct uaudio_chan *ch)
2299 {
2300 	if (ch->buf != NULL) {
2301 		free(ch->buf, M_DEVBUF);
2302 		ch->buf = NULL;
2303 	}
2304 	usbd_transfer_unsetup(ch->xfer, UAUDIO_NCHANBUFS + 1);
2305 
2306 	ch->num_alt = 0;
2307 
2308 	return (0);
2309 }
2310 
2311 int
2312 uaudio_chan_set_param_blocksize(struct uaudio_chan *ch, uint32_t blocksize)
2313 {
2314 	uint32_t temp = 2 * uaudio_get_buffer_size(ch, ch->set_alt);
2315 
2316 	sndbuf_setup(ch->pcm_buf, ch->buf, temp);
2317 
2318 	ch->start = ch->buf;
2319 	ch->end = ch->buf + temp;
2320 	ch->cur = ch->buf;
2321 
2322 	return (temp / 2);
2323 }
2324 
2325 int
2326 uaudio_chan_set_param_fragments(struct uaudio_chan *ch, uint32_t blocksize,
2327     uint32_t blockcount)
2328 {
2329 	return (1);
2330 }
2331 
2332 int
2333 uaudio_chan_set_param_speed(struct uaudio_chan *ch, uint32_t speed)
2334 {
2335 	uint8_t x;
2336 
2337 	for (x = 0; x < ch->num_alt; x++) {
2338 		if (ch->usb_alt[x].sample_rate < speed) {
2339 			/* sample rate is too low */
2340 			break;
2341 		}
2342 	}
2343 
2344 	if (x != 0)
2345 		x--;
2346 
2347 	ch->set_alt = x;
2348 
2349 	DPRINTF("Selecting alt %d\n", (int)x);
2350 
2351 	return (ch->usb_alt[x].sample_rate);
2352 }
2353 
2354 int
2355 uaudio_chan_getptr(struct uaudio_chan *ch)
2356 {
2357 	return (ch->cur - ch->start);
2358 }
2359 
2360 struct pcmchan_caps *
2361 uaudio_chan_getcaps(struct uaudio_chan *ch)
2362 {
2363 	return (&ch->pcm_cap);
2364 }
2365 
2366 static struct pcmchan_matrix uaudio_chan_matrix_swap_2_0 = {
2367 	.id = SND_CHN_MATRIX_DRV,
2368 	.channels = 2,
2369 	.ext = 0,
2370 	.map = {
2371 		/* Right */
2372 		[0] = {
2373 			.type = SND_CHN_T_FR,
2374 			.members =
2375 			    SND_CHN_T_MASK_FR | SND_CHN_T_MASK_FC |
2376 			    SND_CHN_T_MASK_LF | SND_CHN_T_MASK_BR |
2377 			    SND_CHN_T_MASK_BC | SND_CHN_T_MASK_SR
2378 		},
2379 		/* Left */
2380 		[1] = {
2381 			.type = SND_CHN_T_FL,
2382 			.members =
2383 			    SND_CHN_T_MASK_FL | SND_CHN_T_MASK_FC |
2384 			    SND_CHN_T_MASK_LF | SND_CHN_T_MASK_BL |
2385 			    SND_CHN_T_MASK_BC | SND_CHN_T_MASK_SL
2386 		},
2387 		[2] = {
2388 			.type = SND_CHN_T_MAX,
2389 			.members = 0
2390 		}
2391 	},
2392 	.mask = SND_CHN_T_MASK_FR | SND_CHN_T_MASK_FL,
2393 	.offset = {  1,  0, -1, -1, -1, -1, -1, -1, -1,
2394 		    -1, -1, -1, -1, -1, -1, -1, -1, -1  }
2395 };
2396 
2397 struct pcmchan_matrix *
2398 uaudio_chan_getmatrix(struct uaudio_chan *ch, uint32_t format)
2399 {
2400 	struct uaudio_softc *sc;
2401 
2402 	sc = ch->priv_sc;
2403 
2404 	if (sc != NULL && sc->sc_uq_audio_swap_lr != 0 &&
2405 	    AFMT_CHANNEL(format) == 2)
2406 		return (&uaudio_chan_matrix_swap_2_0);
2407 
2408 	return (feeder_matrix_format_map(format));
2409 }
2410 
2411 int
2412 uaudio_chan_set_param_format(struct uaudio_chan *ch, uint32_t format)
2413 {
2414 	DPRINTF("Selecting format 0x%08x\n", (unsigned int)format);
2415 	return (0);
2416 }
2417 
2418 int
2419 uaudio_chan_start(struct uaudio_chan *ch)
2420 {
2421 	struct uaudio_softc *sc = ch->priv_sc;
2422 	int do_start = 0;
2423 
2424 	usb_proc_explore_lock(sc->sc_udev);
2425 	if (ch->operation != CHAN_OP_DRAIN) {
2426 		if (ch->cur_alt == ch->set_alt &&
2427 		    ch->operation == CHAN_OP_NONE) {
2428 			/* save doing the explore task */
2429 			do_start = 1;
2430 		} else {
2431 			ch->operation = CHAN_OP_START;
2432 			(void)usb_proc_explore_msignal(sc->sc_udev,
2433 			    &sc->sc_config_msg[0], &sc->sc_config_msg[1]);
2434 		}
2435 	}
2436 	usb_proc_explore_unlock(sc->sc_udev);
2437 
2438 	if (do_start) {
2439 		usbd_transfer_start(ch->xfer[0]);
2440 		usbd_transfer_start(ch->xfer[1]);
2441 	}
2442 	return (0);
2443 }
2444 
2445 int
2446 uaudio_chan_stop(struct uaudio_chan *ch)
2447 {
2448 	struct uaudio_softc *sc = ch->priv_sc;
2449 	int do_stop = 0;
2450 
2451 	usb_proc_explore_lock(sc->sc_udev);
2452 	if (ch->operation != CHAN_OP_DRAIN) {
2453 		if (ch->cur_alt == ch->set_alt &&
2454 		    ch->operation == CHAN_OP_NONE) {
2455 			/* save doing the explore task */
2456 			do_stop = 1;
2457 		} else {
2458 			ch->operation = CHAN_OP_STOP;
2459 			(void)usb_proc_explore_msignal(sc->sc_udev,
2460 			    &sc->sc_config_msg[0], &sc->sc_config_msg[1]);
2461 		}
2462 	}
2463 	usb_proc_explore_unlock(sc->sc_udev);
2464 
2465 	if (do_stop) {
2466 		usbd_transfer_stop(ch->xfer[0]);
2467 		usbd_transfer_stop(ch->xfer[1]);
2468 	}
2469 	return (0);
2470 }
2471 
2472 /*========================================================================*
2473  * AC - Audio Controller - routines
2474  *========================================================================*/
2475 
2476 static int
2477 uaudio_mixer_sysctl_handler(SYSCTL_HANDLER_ARGS)
2478 {
2479 	struct uaudio_softc *sc;
2480 	struct uaudio_mixer_node *pmc;
2481 	int hint;
2482 	int error;
2483 	int temp = 0;
2484 	int chan = 0;
2485 
2486 	sc = (struct uaudio_softc *)oidp->oid_arg1;
2487 	hint = oidp->oid_arg2;
2488 
2489 	if (sc->sc_mixer_lock == NULL)
2490 		return (ENXIO);
2491 
2492 	/* lookup mixer node */
2493 
2494 	mtx_lock(sc->sc_mixer_lock);
2495 	for (pmc = sc->sc_mixer_root; pmc != NULL; pmc = pmc->next) {
2496 		for (chan = 0; chan != (int)pmc->nchan; chan++) {
2497 			if (pmc->wValue[chan] != -1 &&
2498 			    pmc->wValue[chan] == hint) {
2499 				temp = pmc->wData[chan];
2500 				goto found;
2501 			}
2502 		}
2503 	}
2504 found:
2505 	mtx_unlock(sc->sc_mixer_lock);
2506 
2507 	error = sysctl_handle_int(oidp, &temp, 0, req);
2508 	if (error != 0 || req->newptr == NULL)
2509 		return (error);
2510 
2511 	/* update mixer value */
2512 
2513 	mtx_lock(sc->sc_mixer_lock);
2514 	if (pmc != NULL &&
2515 	    temp >= pmc->minval &&
2516 	    temp <= pmc->maxval) {
2517 
2518 		pmc->wData[chan] = temp;
2519 		pmc->update[(chan / 8)] |= (1 << (chan % 8));
2520 
2521 		/* start the transfer, if not already started */
2522 		usbd_transfer_start(sc->sc_mixer_xfer[0]);
2523 	}
2524 	mtx_unlock(sc->sc_mixer_lock);
2525 
2526 	return (0);
2527 }
2528 
2529 static void
2530 uaudio_mixer_ctl_free(struct uaudio_softc *sc)
2531 {
2532 	struct uaudio_mixer_node *p_mc;
2533 
2534 	while ((p_mc = sc->sc_mixer_root) != NULL) {
2535 		sc->sc_mixer_root = p_mc->next;
2536 		free(p_mc, M_USBDEV);
2537 	}
2538 }
2539 
2540 static void
2541 uaudio_mixer_register_sysctl(struct uaudio_softc *sc, device_t dev)
2542 {
2543 	struct uaudio_mixer_node *pmc;
2544 	struct sysctl_oid *mixer_tree;
2545 	struct sysctl_oid *control_tree;
2546 	char buf[32];
2547 	int chan;
2548 	int n;
2549 
2550 	mixer_tree = SYSCTL_ADD_NODE(device_get_sysctl_ctx(dev),
2551 	    SYSCTL_CHILDREN(device_get_sysctl_tree(dev)), OID_AUTO, "mixer",
2552 	    CTLFLAG_RD, NULL, "");
2553 
2554 	if (mixer_tree == NULL)
2555 		return;
2556 
2557 	for (n = 0, pmc = sc->sc_mixer_root; pmc != NULL;
2558 	    pmc = pmc->next, n++) {
2559 
2560 		for (chan = 0; chan < pmc->nchan; chan++) {
2561 
2562 			if (pmc->nchan > 1) {
2563 				snprintf(buf, sizeof(buf), "%s_%d_%d",
2564 				    pmc->name, n, chan);
2565 			} else {
2566 				snprintf(buf, sizeof(buf), "%s_%d",
2567 				    pmc->name, n);
2568 			}
2569 
2570 			control_tree = SYSCTL_ADD_NODE(device_get_sysctl_ctx(dev),
2571 			    SYSCTL_CHILDREN(mixer_tree), OID_AUTO, buf,
2572 			    CTLFLAG_RD, NULL, "Mixer control nodes");
2573 
2574 			if (control_tree == NULL)
2575 				continue;
2576 
2577 			SYSCTL_ADD_PROC(device_get_sysctl_ctx(dev),
2578 			    SYSCTL_CHILDREN(control_tree),
2579 			    OID_AUTO, "val", CTLTYPE_INT | CTLFLAG_RW, sc,
2580 			    pmc->wValue[chan],
2581 			    uaudio_mixer_sysctl_handler, "I", "Current value");
2582 
2583 			SYSCTL_ADD_INT(device_get_sysctl_ctx(dev),
2584 			    SYSCTL_CHILDREN(control_tree),
2585 			    OID_AUTO, "min", CTLFLAG_RD, 0, pmc->minval,
2586 			    "Minimum value");
2587 
2588 			SYSCTL_ADD_INT(device_get_sysctl_ctx(dev),
2589 			    SYSCTL_CHILDREN(control_tree),
2590 			    OID_AUTO, "max", CTLFLAG_RD, 0, pmc->maxval,
2591 			    "Maximum value");
2592 
2593 			SYSCTL_ADD_STRING(device_get_sysctl_ctx(dev),
2594 			    SYSCTL_CHILDREN(control_tree),
2595 			    OID_AUTO, "desc", CTLFLAG_RD, pmc->desc, 0,
2596 			    "Description");
2597 		}
2598 	}
2599 }
2600 
2601 /* M-Audio FastTrack Ultra Mixer Description */
2602 /* Origin: Linux USB Audio driver */
2603 static void
2604 uaudio_mixer_controls_create_ftu(struct uaudio_softc *sc)
2605 {
2606 	int chx;
2607 	int chy;
2608 
2609 	memset(&MIX(sc), 0, sizeof(MIX(sc)));
2610 	MIX(sc).wIndex = MAKE_WORD(6, sc->sc_mixer_iface_no);
2611 	MIX(sc).wValue[0] = MAKE_WORD(8, 0);
2612 	MIX(sc).class = UAC_OUTPUT;
2613 	MIX(sc).type = MIX_UNSIGNED_16;
2614 	MIX(sc).ctl = SOUND_MIXER_NRDEVICES;
2615 	MIX(sc).name = "effect";
2616 	MIX(sc).minval = 0;
2617 	MIX(sc).maxval = 7;
2618 	MIX(sc).mul = 7;
2619 	MIX(sc).nchan = 1;
2620 	MIX(sc).update[0] = 1;
2621 	strlcpy(MIX(sc).desc, "Room1,2,3,Hall1,2,Plate,Delay,Echo", sizeof(MIX(sc).desc));
2622 	uaudio_mixer_add_ctl_sub(sc, &MIX(sc));
2623 
2624 	memset(&MIX(sc), 0, sizeof(MIX(sc)));
2625 	MIX(sc).wIndex = MAKE_WORD(5, sc->sc_mixer_iface_no);
2626 
2627 	for (chx = 0; chx != 8; chx++) {
2628 		for (chy = 0; chy != 8; chy++) {
2629 
2630 			MIX(sc).wValue[0] = MAKE_WORD(chx + 1, chy + 1);
2631 			MIX(sc).type = MIX_SIGNED_16;
2632 			MIX(sc).ctl = SOUND_MIXER_NRDEVICES;
2633 			MIX(sc).name = "mix_rec";
2634 			MIX(sc).nchan = 1;
2635 			MIX(sc).update[0] = 1;
2636 			MIX(sc).val_default = 0;
2637 			snprintf(MIX(sc).desc, sizeof(MIX(sc).desc),
2638 			    "AIn%d - Out%d Record Volume", chy + 1, chx + 1);
2639 
2640 			uaudio_mixer_add_ctl(sc, &MIX(sc));
2641 
2642 			MIX(sc).wValue[0] = MAKE_WORD(chx + 1, chy + 1 + 8);
2643 			MIX(sc).type = MIX_SIGNED_16;
2644 			MIX(sc).ctl = SOUND_MIXER_NRDEVICES;
2645 			MIX(sc).name = "mix_play";
2646 			MIX(sc).nchan = 1;
2647 			MIX(sc).update[0] = 1;
2648 			MIX(sc).val_default = (chx == chy) ? 2 : 0;
2649 			snprintf(MIX(sc).desc, sizeof(MIX(sc).desc),
2650 			    "DIn%d - Out%d Playback Volume", chy + 1, chx + 1);
2651 
2652 			uaudio_mixer_add_ctl(sc, &MIX(sc));
2653 		}
2654 	}
2655 
2656 	memset(&MIX(sc), 0, sizeof(MIX(sc)));
2657 	MIX(sc).wIndex = MAKE_WORD(6, sc->sc_mixer_iface_no);
2658 	MIX(sc).wValue[0] = MAKE_WORD(2, 0);
2659 	MIX(sc).class = UAC_OUTPUT;
2660 	MIX(sc).type = MIX_SIGNED_8;
2661 	MIX(sc).ctl = SOUND_MIXER_NRDEVICES;
2662 	MIX(sc).name = "effect_vol";
2663 	MIX(sc).nchan = 1;
2664 	MIX(sc).update[0] = 1;
2665 	MIX(sc).minval = 0;
2666 	MIX(sc).maxval = 0x7f;
2667 	MIX(sc).mul = 0x7f;
2668 	MIX(sc).nchan = 1;
2669 	MIX(sc).update[0] = 1;
2670 	strlcpy(MIX(sc).desc, "Effect Volume", sizeof(MIX(sc).desc));
2671 	uaudio_mixer_add_ctl_sub(sc, &MIX(sc));
2672 
2673 	memset(&MIX(sc), 0, sizeof(MIX(sc)));
2674 	MIX(sc).wIndex = MAKE_WORD(6, sc->sc_mixer_iface_no);
2675 	MIX(sc).wValue[0] = MAKE_WORD(3, 0);
2676 	MIX(sc).class = UAC_OUTPUT;
2677 	MIX(sc).type = MIX_SIGNED_16;
2678 	MIX(sc).ctl = SOUND_MIXER_NRDEVICES;
2679 	MIX(sc).name = "effect_dur";
2680 	MIX(sc).nchan = 1;
2681 	MIX(sc).update[0] = 1;
2682 	MIX(sc).minval = 0;
2683 	MIX(sc).maxval = 0x7f00;
2684 	MIX(sc).mul = 0x7f00;
2685 	MIX(sc).nchan = 1;
2686 	MIX(sc).update[0] = 1;
2687 	strlcpy(MIX(sc).desc, "Effect Duration", sizeof(MIX(sc).desc));
2688 	uaudio_mixer_add_ctl_sub(sc, &MIX(sc));
2689 
2690 	memset(&MIX(sc), 0, sizeof(MIX(sc)));
2691 	MIX(sc).wIndex = MAKE_WORD(6, sc->sc_mixer_iface_no);
2692 	MIX(sc).wValue[0] = MAKE_WORD(4, 0);
2693 	MIX(sc).class = UAC_OUTPUT;
2694 	MIX(sc).type = MIX_SIGNED_8;
2695 	MIX(sc).ctl = SOUND_MIXER_NRDEVICES;
2696 	MIX(sc).name = "effect_fb";
2697 	MIX(sc).nchan = 1;
2698 	MIX(sc).update[0] = 1;
2699 	MIX(sc).minval = 0;
2700 	MIX(sc).maxval = 0x7f;
2701 	MIX(sc).mul = 0x7f;
2702 	MIX(sc).nchan = 1;
2703 	MIX(sc).update[0] = 1;
2704 	strlcpy(MIX(sc).desc, "Effect Feedback Volume", sizeof(MIX(sc).desc));
2705 	uaudio_mixer_add_ctl_sub(sc, &MIX(sc));
2706 
2707 	memset(&MIX(sc), 0, sizeof(MIX(sc)));
2708 	MIX(sc).wIndex = MAKE_WORD(7, sc->sc_mixer_iface_no);
2709 	for (chy = 0; chy != 4; chy++) {
2710 
2711 		MIX(sc).wValue[0] = MAKE_WORD(7, chy + 1);
2712 		MIX(sc).type = MIX_SIGNED_16;
2713 		MIX(sc).ctl = SOUND_MIXER_NRDEVICES;
2714 		MIX(sc).name = "effect_ret";
2715 		MIX(sc).nchan = 1;
2716 		MIX(sc).update[0] = 1;
2717 		snprintf(MIX(sc).desc, sizeof(MIX(sc).desc),
2718 		    "Effect Return %d Volume", chy + 1);
2719 
2720 		uaudio_mixer_add_ctl(sc, &MIX(sc));
2721 	}
2722 
2723 	memset(&MIX(sc), 0, sizeof(MIX(sc)));
2724 	MIX(sc).wIndex = MAKE_WORD(5, sc->sc_mixer_iface_no);
2725 
2726 	for (chy = 0; chy != 8; chy++) {
2727 		MIX(sc).wValue[0] = MAKE_WORD(9, chy + 1);
2728 		MIX(sc).type = MIX_SIGNED_16;
2729 		MIX(sc).ctl = SOUND_MIXER_NRDEVICES;
2730 		MIX(sc).name = "effect_send";
2731 		MIX(sc).nchan = 1;
2732 		MIX(sc).update[0] = 1;
2733 		snprintf(MIX(sc).desc, sizeof(MIX(sc).desc),
2734 		    "Effect Send AIn%d Volume", chy + 1);
2735 
2736 		uaudio_mixer_add_ctl(sc, &MIX(sc));
2737 
2738 		MIX(sc).wValue[0] = MAKE_WORD(9, chy + 1);
2739 		MIX(sc).type = MIX_SIGNED_16;
2740 		MIX(sc).ctl = SOUND_MIXER_NRDEVICES;
2741 		MIX(sc).name = "effect_send";
2742 		MIX(sc).nchan = 1;
2743 		MIX(sc).update[0] = 1;
2744 		snprintf(MIX(sc).desc, sizeof(MIX(sc).desc),
2745 		    "Effect Send DIn%d Volume", chy + 1 + 8);
2746 
2747 		uaudio_mixer_add_ctl(sc, &MIX(sc));
2748 	}
2749 }
2750 
2751 static void
2752 uaudio_mixer_reload_all(struct uaudio_softc *sc)
2753 {
2754 	struct uaudio_mixer_node *pmc;
2755 	int chan;
2756 
2757 	if (sc->sc_mixer_lock == NULL)
2758 		return;
2759 
2760 	mtx_lock(sc->sc_mixer_lock);
2761 	for (pmc = sc->sc_mixer_root; pmc != NULL; pmc = pmc->next) {
2762 		/* use reset defaults for non-oss controlled settings */
2763 		if (pmc->ctl == SOUND_MIXER_NRDEVICES)
2764 			continue;
2765 		for (chan = 0; chan < pmc->nchan; chan++)
2766 			pmc->update[chan / 8] |= (1 << (chan % 8));
2767 	}
2768 	usbd_transfer_start(sc->sc_mixer_xfer[0]);
2769 
2770 	/* start HID volume keys, if any */
2771 	usbd_transfer_start(sc->sc_hid.xfer[0]);
2772 	mtx_unlock(sc->sc_mixer_lock);
2773 }
2774 
2775 static void
2776 uaudio_mixer_add_ctl_sub(struct uaudio_softc *sc, struct uaudio_mixer_node *mc)
2777 {
2778 	struct uaudio_mixer_node *p_mc_new =
2779 	    malloc(sizeof(*p_mc_new), M_USBDEV, M_WAITOK);
2780 	int ch;
2781 
2782 	if (p_mc_new != NULL) {
2783 		memcpy(p_mc_new, mc, sizeof(*p_mc_new));
2784 		p_mc_new->next = sc->sc_mixer_root;
2785 		sc->sc_mixer_root = p_mc_new;
2786 		sc->sc_mixer_count++;
2787 
2788 		/* set default value for all channels */
2789 		for (ch = 0; ch < p_mc_new->nchan; ch++) {
2790 			switch (p_mc_new->val_default) {
2791 			case 1:
2792 				/* 50% */
2793 				p_mc_new->wData[ch] = (p_mc_new->maxval + p_mc_new->minval) / 2;
2794 				break;
2795 			case 2:
2796 				/* 100% */
2797 				p_mc_new->wData[ch] = p_mc_new->maxval;
2798 				break;
2799 			default:
2800 				/* 0% */
2801 				p_mc_new->wData[ch] = p_mc_new->minval;
2802 				break;
2803 			}
2804 		}
2805 	} else {
2806 		DPRINTF("out of memory\n");
2807 	}
2808 }
2809 
2810 static void
2811 uaudio_mixer_add_ctl(struct uaudio_softc *sc, struct uaudio_mixer_node *mc)
2812 {
2813 	int32_t res;
2814 
2815 	if (mc->class < UAC_NCLASSES) {
2816 		DPRINTF("adding %s.%d\n",
2817 		    uac_names[mc->class], mc->ctl);
2818 	} else {
2819 		DPRINTF("adding %d\n", mc->ctl);
2820 	}
2821 
2822 	if (mc->type == MIX_ON_OFF) {
2823 		mc->minval = 0;
2824 		mc->maxval = 1;
2825 	} else if (mc->type == MIX_SELECTOR) {
2826 	} else {
2827 
2828 		/* determine min and max values */
2829 
2830 		mc->minval = uaudio_mixer_get(sc->sc_udev,
2831 		    sc->sc_audio_rev, GET_MIN, mc);
2832 		mc->maxval = uaudio_mixer_get(sc->sc_udev,
2833 		    sc->sc_audio_rev, GET_MAX, mc);
2834 
2835 		/* check if max and min was swapped */
2836 
2837 		if (mc->maxval < mc->minval) {
2838 			res = mc->maxval;
2839 			mc->maxval = mc->minval;
2840 			mc->minval = res;
2841 		}
2842 
2843 		/* compute value range */
2844 		mc->mul = mc->maxval - mc->minval;
2845 		if (mc->mul == 0)
2846 			mc->mul = 1;
2847 
2848 		/* compute value alignment */
2849 		res = uaudio_mixer_get(sc->sc_udev,
2850 		    sc->sc_audio_rev, GET_RES, mc);
2851 
2852 		DPRINTF("Resolution = %d\n", (int)res);
2853 	}
2854 
2855 	uaudio_mixer_add_ctl_sub(sc, mc);
2856 
2857 #ifdef USB_DEBUG
2858 	if (uaudio_debug > 2) {
2859 		uint8_t i;
2860 
2861 		for (i = 0; i < mc->nchan; i++) {
2862 			DPRINTF("[mix] wValue=%04x\n", mc->wValue[0]);
2863 		}
2864 		DPRINTF("[mix] wIndex=%04x type=%d ctl='%d' "
2865 		    "min=%d max=%d\n",
2866 		    mc->wIndex, mc->type, mc->ctl,
2867 		    mc->minval, mc->maxval);
2868 	}
2869 #endif
2870 }
2871 
2872 static void
2873 uaudio_mixer_add_mixer(struct uaudio_softc *sc,
2874     const struct uaudio_terminal_node *iot, int id)
2875 {
2876 	const struct usb_audio_mixer_unit_0 *d0 = iot[id].u.mu_v1;
2877 	const struct usb_audio_mixer_unit_1 *d1;
2878 
2879 	uint32_t bno;			/* bit number */
2880 	uint32_t p;			/* bit number accumulator */
2881 	uint32_t mo;			/* matching outputs */
2882 	uint32_t mc;			/* matching channels */
2883 	uint32_t ichs;			/* input channels */
2884 	uint32_t ochs;			/* output channels */
2885 	uint32_t c;
2886 	uint32_t chs;			/* channels */
2887 	uint32_t i;
2888 	uint32_t o;
2889 
2890 	DPRINTFN(3, "bUnitId=%d bNrInPins=%d\n",
2891 	    d0->bUnitId, d0->bNrInPins);
2892 
2893 	/* compute the number of input channels */
2894 
2895 	ichs = 0;
2896 	for (i = 0; i < d0->bNrInPins; i++) {
2897 		ichs += uaudio_mixer_get_cluster(
2898 		    d0->baSourceId[i], iot).bNrChannels;
2899 	}
2900 
2901 	d1 = (const void *)(d0->baSourceId + d0->bNrInPins);
2902 
2903 	/* and the number of output channels */
2904 
2905 	ochs = d1->bNrChannels;
2906 
2907 	DPRINTFN(3, "ichs=%d ochs=%d\n", ichs, ochs);
2908 
2909 	memset(&MIX(sc), 0, sizeof(MIX(sc)));
2910 
2911 	MIX(sc).wIndex = MAKE_WORD(d0->bUnitId, sc->sc_mixer_iface_no);
2912 	uaudio_mixer_determine_class(&iot[id], &MIX(sc));
2913 	MIX(sc).type = MIX_SIGNED_16;
2914 
2915 	if (uaudio_mixer_verify_desc(d0, ((ichs * ochs) + 7) / 8) == NULL)
2916 		return;
2917 
2918 	for (p = i = 0; i < d0->bNrInPins; i++) {
2919 		chs = uaudio_mixer_get_cluster(
2920 		    d0->baSourceId[i], iot).bNrChannels;
2921 		mc = 0;
2922 		for (c = 0; c < chs; c++) {
2923 			mo = 0;
2924 			for (o = 0; o < ochs; o++) {
2925 				bno = ((p + c) * ochs) + o;
2926 				if (BIT_TEST(d1->bmControls, bno))
2927 					mo++;
2928 			}
2929 			if (mo == 1)
2930 				mc++;
2931 		}
2932 		if ((mc == chs) && (chs <= MIX_MAX_CHAN)) {
2933 
2934 			/* repeat bit-scan */
2935 
2936 			mc = 0;
2937 			for (c = 0; c < chs; c++) {
2938 				for (o = 0; o < ochs; o++) {
2939 					bno = ((p + c) * ochs) + o;
2940 					if (BIT_TEST(d1->bmControls, bno))
2941 						MIX(sc).wValue[mc++] = MAKE_WORD(p + c + 1, o + 1);
2942 				}
2943 			}
2944 			MIX(sc).nchan = chs;
2945 			uaudio_mixer_add_ctl(sc, &MIX(sc));
2946 		}
2947 		p += chs;
2948 	}
2949 }
2950 
2951 static void
2952 uaudio20_mixer_add_mixer(struct uaudio_softc *sc,
2953     const struct uaudio_terminal_node *iot, int id)
2954 {
2955 	const struct usb_audio20_mixer_unit_0 *d0 = iot[id].u.mu_v2;
2956 	const struct usb_audio20_mixer_unit_1 *d1;
2957 
2958 	uint32_t bno;			/* bit number */
2959 	uint32_t p;			/* bit number accumulator */
2960 	uint32_t mo;			/* matching outputs */
2961 	uint32_t mc;			/* matching channels */
2962 	uint32_t ichs;			/* input channels */
2963 	uint32_t ochs;			/* output channels */
2964 	uint32_t c;
2965 	uint32_t chs;			/* channels */
2966 	uint32_t i;
2967 	uint32_t o;
2968 
2969 	DPRINTFN(3, "bUnitId=%d bNrInPins=%d\n",
2970 	    d0->bUnitId, d0->bNrInPins);
2971 
2972 	/* compute the number of input channels */
2973 
2974 	ichs = 0;
2975 	for (i = 0; i < d0->bNrInPins; i++) {
2976 		ichs += uaudio20_mixer_get_cluster(
2977 		    d0->baSourceId[i], iot).bNrChannels;
2978 	}
2979 
2980 	d1 = (const void *)(d0->baSourceId + d0->bNrInPins);
2981 
2982 	/* and the number of output channels */
2983 
2984 	ochs = d1->bNrChannels;
2985 
2986 	DPRINTFN(3, "ichs=%d ochs=%d\n", ichs, ochs);
2987 
2988 	memset(&MIX(sc), 0, sizeof(MIX(sc)));
2989 
2990 	MIX(sc).wIndex = MAKE_WORD(d0->bUnitId, sc->sc_mixer_iface_no);
2991 	uaudio20_mixer_determine_class(&iot[id], &MIX(sc));
2992 	MIX(sc).type = MIX_SIGNED_16;
2993 
2994 	if (uaudio20_mixer_verify_desc(d0, ((ichs * ochs) + 7) / 8) == NULL)
2995 		return;
2996 
2997 	for (p = i = 0; i < d0->bNrInPins; i++) {
2998 		chs = uaudio20_mixer_get_cluster(
2999 		    d0->baSourceId[i], iot).bNrChannels;
3000 		mc = 0;
3001 		for (c = 0; c < chs; c++) {
3002 			mo = 0;
3003 			for (o = 0; o < ochs; o++) {
3004 				bno = ((p + c) * ochs) + o;
3005 				if (BIT_TEST(d1->bmControls, bno))
3006 					mo++;
3007 			}
3008 			if (mo == 1)
3009 				mc++;
3010 		}
3011 		if ((mc == chs) && (chs <= MIX_MAX_CHAN)) {
3012 
3013 			/* repeat bit-scan */
3014 
3015 			mc = 0;
3016 			for (c = 0; c < chs; c++) {
3017 				for (o = 0; o < ochs; o++) {
3018 					bno = ((p + c) * ochs) + o;
3019 					if (BIT_TEST(d1->bmControls, bno))
3020 						MIX(sc).wValue[mc++] = MAKE_WORD(p + c + 1, o + 1);
3021 				}
3022 			}
3023 			MIX(sc).nchan = chs;
3024 			uaudio_mixer_add_ctl(sc, &MIX(sc));
3025 		}
3026 		p += chs;
3027 	}
3028 }
3029 
3030 static void
3031 uaudio_mixer_add_selector(struct uaudio_softc *sc,
3032     const struct uaudio_terminal_node *iot, int id)
3033 {
3034 	const struct usb_audio_selector_unit *d = iot[id].u.su_v1;
3035 	uint16_t i;
3036 
3037 	DPRINTFN(3, "bUnitId=%d bNrInPins=%d\n",
3038 	    d->bUnitId, d->bNrInPins);
3039 
3040 	if (d->bNrInPins == 0)
3041 		return;
3042 
3043 	memset(&MIX(sc), 0, sizeof(MIX(sc)));
3044 
3045 	MIX(sc).wIndex = MAKE_WORD(d->bUnitId, sc->sc_mixer_iface_no);
3046 	MIX(sc).wValue[0] = MAKE_WORD(0, 0);
3047 	uaudio_mixer_determine_class(&iot[id], &MIX(sc));
3048 	MIX(sc).nchan = 1;
3049 	MIX(sc).type = MIX_SELECTOR;
3050 	MIX(sc).ctl = SOUND_MIXER_NRDEVICES;
3051 	MIX(sc).minval = 1;
3052 	MIX(sc).maxval = d->bNrInPins;
3053 	MIX(sc).name = "selector";
3054 
3055 	i = d->baSourceId[d->bNrInPins];
3056 	if (i == 0 ||
3057 	    usbd_req_get_string_any(sc->sc_udev, NULL,
3058 	    MIX(sc).desc, sizeof(MIX(sc).desc), i) != 0) {
3059 		MIX(sc).desc[0] = 0;
3060 	}
3061 
3062 	if (MIX(sc).maxval > MAX_SELECTOR_INPUT_PIN) {
3063 		MIX(sc).maxval = MAX_SELECTOR_INPUT_PIN;
3064 	}
3065 	MIX(sc).mul = (MIX(sc).maxval - MIX(sc).minval);
3066 	for (i = 0; i < MAX_SELECTOR_INPUT_PIN; i++) {
3067 		MIX(sc).slctrtype[i] = SOUND_MIXER_NRDEVICES;
3068 	}
3069 
3070 	for (i = 0; i < MIX(sc).maxval; i++) {
3071 		MIX(sc).slctrtype[i] = uaudio_mixer_feature_name(
3072 		    &iot[d->baSourceId[i]], &MIX(sc));
3073 	}
3074 
3075 	MIX(sc).class = 0;			/* not used */
3076 
3077 	uaudio_mixer_add_ctl(sc, &MIX(sc));
3078 }
3079 
3080 static void
3081 uaudio20_mixer_add_selector(struct uaudio_softc *sc,
3082     const struct uaudio_terminal_node *iot, int id)
3083 {
3084 	const struct usb_audio20_selector_unit *d = iot[id].u.su_v2;
3085 	uint16_t i;
3086 
3087 	DPRINTFN(3, "bUnitId=%d bNrInPins=%d\n",
3088 	    d->bUnitId, d->bNrInPins);
3089 
3090 	if (d->bNrInPins == 0)
3091 		return;
3092 
3093 	memset(&MIX(sc), 0, sizeof(MIX(sc)));
3094 
3095 	MIX(sc).wIndex = MAKE_WORD(d->bUnitId, sc->sc_mixer_iface_no);
3096 	MIX(sc).wValue[0] = MAKE_WORD(0, 0);
3097 	uaudio20_mixer_determine_class(&iot[id], &MIX(sc));
3098 	MIX(sc).nchan = 1;
3099 	MIX(sc).type = MIX_SELECTOR;
3100 	MIX(sc).ctl = SOUND_MIXER_NRDEVICES;
3101 	MIX(sc).minval = 1;
3102 	MIX(sc).maxval = d->bNrInPins;
3103 	MIX(sc).name = "selector";
3104 
3105 	i = d->baSourceId[d->bNrInPins];
3106 	if (i == 0 ||
3107 	    usbd_req_get_string_any(sc->sc_udev, NULL,
3108 	    MIX(sc).desc, sizeof(MIX(sc).desc), i) != 0) {
3109 		MIX(sc).desc[0] = 0;
3110 	}
3111 
3112 	if (MIX(sc).maxval > MAX_SELECTOR_INPUT_PIN)
3113 		MIX(sc).maxval = MAX_SELECTOR_INPUT_PIN;
3114 
3115 	MIX(sc).mul = (MIX(sc).maxval - MIX(sc).minval);
3116 	for (i = 0; i < MAX_SELECTOR_INPUT_PIN; i++)
3117 		MIX(sc).slctrtype[i] = SOUND_MIXER_NRDEVICES;
3118 
3119 	for (i = 0; i < MIX(sc).maxval; i++) {
3120 		MIX(sc).slctrtype[i] = uaudio20_mixer_feature_name(
3121 		    &iot[d->baSourceId[i]], &MIX(sc));
3122 	}
3123 
3124 	MIX(sc).class = 0;			/* not used */
3125 
3126 	uaudio_mixer_add_ctl(sc, &MIX(sc));
3127 }
3128 
3129 static uint32_t
3130 uaudio_mixer_feature_get_bmaControls(const struct usb_audio_feature_unit *d,
3131     uint8_t i)
3132 {
3133 	uint32_t temp = 0;
3134 	uint32_t offset = (i * d->bControlSize);
3135 
3136 	if (d->bControlSize > 0) {
3137 		temp |= d->bmaControls[offset];
3138 		if (d->bControlSize > 1) {
3139 			temp |= d->bmaControls[offset + 1] << 8;
3140 			if (d->bControlSize > 2) {
3141 				temp |= d->bmaControls[offset + 2] << 16;
3142 				if (d->bControlSize > 3) {
3143 					temp |= d->bmaControls[offset + 3] << 24;
3144 				}
3145 			}
3146 		}
3147 	}
3148 	return (temp);
3149 }
3150 
3151 static void
3152 uaudio_mixer_add_feature(struct uaudio_softc *sc,
3153     const struct uaudio_terminal_node *iot, int id)
3154 {
3155 	const struct usb_audio_feature_unit *d = iot[id].u.fu_v1;
3156 	uint32_t fumask;
3157 	uint32_t mmask;
3158 	uint32_t cmask;
3159 	uint16_t mixernumber;
3160 	uint8_t nchan;
3161 	uint8_t chan;
3162 	uint8_t ctl;
3163 	uint8_t i;
3164 
3165 	if (d->bControlSize == 0)
3166 		return;
3167 
3168 	memset(&MIX(sc), 0, sizeof(MIX(sc)));
3169 
3170 	nchan = (d->bLength - 7) / d->bControlSize;
3171 	mmask = uaudio_mixer_feature_get_bmaControls(d, 0);
3172 	cmask = 0;
3173 
3174 	if (nchan == 0)
3175 		return;
3176 
3177 	/* figure out what we can control */
3178 
3179 	for (chan = 1; chan < nchan; chan++) {
3180 		DPRINTFN(10, "chan=%d mask=%x\n",
3181 		    chan, uaudio_mixer_feature_get_bmaControls(d, chan));
3182 
3183 		cmask |= uaudio_mixer_feature_get_bmaControls(d, chan);
3184 	}
3185 
3186 	if (nchan > MIX_MAX_CHAN) {
3187 		nchan = MIX_MAX_CHAN;
3188 	}
3189 	MIX(sc).wIndex = MAKE_WORD(d->bUnitId, sc->sc_mixer_iface_no);
3190 
3191 	i = d->bmaControls[d->bControlSize];
3192 	if (i == 0 ||
3193 	    usbd_req_get_string_any(sc->sc_udev, NULL,
3194 	    MIX(sc).desc, sizeof(MIX(sc).desc), i) != 0) {
3195 		MIX(sc).desc[0] = 0;
3196 	}
3197 
3198 	for (ctl = 1; ctl <= LOUDNESS_CONTROL; ctl++) {
3199 
3200 		fumask = FU_MASK(ctl);
3201 
3202 		DPRINTFN(5, "ctl=%d fumask=0x%04x\n",
3203 		    ctl, fumask);
3204 
3205 		if (mmask & fumask) {
3206 			MIX(sc).nchan = 1;
3207 			MIX(sc).wValue[0] = MAKE_WORD(ctl, 0);
3208 		} else if (cmask & fumask) {
3209 			MIX(sc).nchan = nchan - 1;
3210 			for (i = 1; i < nchan; i++) {
3211 				if (uaudio_mixer_feature_get_bmaControls(d, i) & fumask)
3212 					MIX(sc).wValue[i - 1] = MAKE_WORD(ctl, i);
3213 				else
3214 					MIX(sc).wValue[i - 1] = -1;
3215 			}
3216 		} else {
3217 			continue;
3218 		}
3219 
3220 		mixernumber = uaudio_mixer_feature_name(&iot[id], &MIX(sc));
3221 
3222 		switch (ctl) {
3223 		case MUTE_CONTROL:
3224 			MIX(sc).type = MIX_ON_OFF;
3225 			MIX(sc).ctl = SOUND_MIXER_NRDEVICES;
3226 			MIX(sc).name = "mute";
3227 			break;
3228 
3229 		case VOLUME_CONTROL:
3230 			MIX(sc).type = MIX_SIGNED_16;
3231 			MIX(sc).ctl = mixernumber;
3232 			MIX(sc).name = "vol";
3233 			break;
3234 
3235 		case BASS_CONTROL:
3236 			MIX(sc).type = MIX_SIGNED_8;
3237 			MIX(sc).ctl = SOUND_MIXER_BASS;
3238 			MIX(sc).name = "bass";
3239 			break;
3240 
3241 		case MID_CONTROL:
3242 			MIX(sc).type = MIX_SIGNED_8;
3243 			MIX(sc).ctl = SOUND_MIXER_NRDEVICES;	/* XXXXX */
3244 			MIX(sc).name = "mid";
3245 			break;
3246 
3247 		case TREBLE_CONTROL:
3248 			MIX(sc).type = MIX_SIGNED_8;
3249 			MIX(sc).ctl = SOUND_MIXER_TREBLE;
3250 			MIX(sc).name = "treble";
3251 			break;
3252 
3253 		case GRAPHIC_EQUALIZER_CONTROL:
3254 			continue;	/* XXX don't add anything */
3255 
3256 		case AGC_CONTROL:
3257 			MIX(sc).type = MIX_ON_OFF;
3258 			MIX(sc).ctl = SOUND_MIXER_NRDEVICES;	/* XXXXX */
3259 			MIX(sc).name = "agc";
3260 			break;
3261 
3262 		case DELAY_CONTROL:
3263 			MIX(sc).type = MIX_UNSIGNED_16;
3264 			MIX(sc).ctl = SOUND_MIXER_NRDEVICES;	/* XXXXX */
3265 			MIX(sc).name = "delay";
3266 			break;
3267 
3268 		case BASS_BOOST_CONTROL:
3269 			MIX(sc).type = MIX_ON_OFF;
3270 			MIX(sc).ctl = SOUND_MIXER_NRDEVICES;	/* XXXXX */
3271 			MIX(sc).name = "boost";
3272 			break;
3273 
3274 		case LOUDNESS_CONTROL:
3275 			MIX(sc).type = MIX_ON_OFF;
3276 			MIX(sc).ctl = SOUND_MIXER_LOUD;	/* Is this correct ? */
3277 			MIX(sc).name = "loudness";
3278 			break;
3279 
3280 		default:
3281 			MIX(sc).type = MIX_UNKNOWN;
3282 			break;
3283 		}
3284 
3285 		if (MIX(sc).type != MIX_UNKNOWN)
3286 			uaudio_mixer_add_ctl(sc, &MIX(sc));
3287 	}
3288 }
3289 
3290 static void
3291 uaudio20_mixer_add_feature(struct uaudio_softc *sc,
3292     const struct uaudio_terminal_node *iot, int id)
3293 {
3294 	const struct usb_audio20_feature_unit *d = iot[id].u.fu_v2;
3295 	uint32_t ctl;
3296 	uint32_t mmask;
3297 	uint32_t cmask;
3298 	uint16_t mixernumber;
3299 	uint8_t nchan;
3300 	uint8_t chan;
3301 	uint8_t i;
3302 	uint8_t what;
3303 
3304 	if (UGETDW(d->bmaControls[0]) == 0)
3305 		return;
3306 
3307 	memset(&MIX(sc), 0, sizeof(MIX(sc)));
3308 
3309 	nchan = (d->bLength - 6) / 4;
3310 	mmask = UGETDW(d->bmaControls[0]);
3311 	cmask = 0;
3312 
3313 	if (nchan == 0)
3314 		return;
3315 
3316 	/* figure out what we can control */
3317 
3318 	for (chan = 1; chan < nchan; chan++)
3319 		cmask |= UGETDW(d->bmaControls[chan]);
3320 
3321 	if (nchan > MIX_MAX_CHAN)
3322 		nchan = MIX_MAX_CHAN;
3323 
3324 	MIX(sc).wIndex = MAKE_WORD(d->bUnitId, sc->sc_mixer_iface_no);
3325 
3326 	i = d->bmaControls[nchan][0];
3327 	if (i == 0 ||
3328 	    usbd_req_get_string_any(sc->sc_udev, NULL,
3329 	    MIX(sc).desc, sizeof(MIX(sc).desc), i) != 0) {
3330 		MIX(sc).desc[0] = 0;
3331 	}
3332 
3333 	for (ctl = 3; ctl != 0; ctl <<= 2) {
3334 
3335 		mixernumber = uaudio20_mixer_feature_name(&iot[id], &MIX(sc));
3336 
3337 		switch (ctl) {
3338 		case (3 << 0):
3339 			MIX(sc).type = MIX_ON_OFF;
3340 			MIX(sc).ctl = SOUND_MIXER_NRDEVICES;
3341 			MIX(sc).name = "mute";
3342 			what = MUTE_CONTROL;
3343 			break;
3344 		case (3 << 2):
3345 			MIX(sc).type = MIX_SIGNED_16;
3346 			MIX(sc).ctl = mixernumber;
3347 			MIX(sc).name = "vol";
3348 			what = VOLUME_CONTROL;
3349 			break;
3350 		case (3 << 4):
3351 			MIX(sc).type = MIX_SIGNED_8;
3352 			MIX(sc).ctl = SOUND_MIXER_BASS;
3353 			MIX(sc).name = "bass";
3354 			what = BASS_CONTROL;
3355 			break;
3356 		case (3 << 6):
3357 			MIX(sc).type = MIX_SIGNED_8;
3358 			MIX(sc).ctl = SOUND_MIXER_NRDEVICES;	/* XXXXX */
3359 			MIX(sc).name = "mid";
3360 			what = MID_CONTROL;
3361 			break;
3362 		case (3 << 8):
3363 			MIX(sc).type = MIX_SIGNED_8;
3364 			MIX(sc).ctl = SOUND_MIXER_TREBLE;
3365 			MIX(sc).name = "treble";
3366 			what = TREBLE_CONTROL;
3367 			break;
3368 		case (3 << 12):
3369 			MIX(sc).type = MIX_ON_OFF;
3370 			MIX(sc).ctl = SOUND_MIXER_NRDEVICES;	/* XXXXX */
3371 			MIX(sc).name = "agc";
3372 			what = AGC_CONTROL;
3373 			break;
3374 		case (3 << 14):
3375 			MIX(sc).type = MIX_UNSIGNED_16;
3376 			MIX(sc).ctl = SOUND_MIXER_NRDEVICES;	/* XXXXX */
3377 			MIX(sc).name = "delay";
3378 			what = DELAY_CONTROL;
3379 			break;
3380 		case (3 << 16):
3381 			MIX(sc).type = MIX_ON_OFF;
3382 			MIX(sc).ctl = SOUND_MIXER_NRDEVICES;	/* XXXXX */
3383 			MIX(sc).name = "boost";
3384 			what = BASS_BOOST_CONTROL;
3385 			break;
3386 		case (3 << 18):
3387 			MIX(sc).type = MIX_ON_OFF;
3388 			MIX(sc).ctl = SOUND_MIXER_LOUD;	/* Is this correct ? */
3389 			MIX(sc).name = "loudness";
3390 			what = LOUDNESS_CONTROL;
3391 			break;
3392 		case (3 << 20):
3393 			MIX(sc).type = MIX_SIGNED_16;
3394 			MIX(sc).ctl = mixernumber;
3395 			MIX(sc).name = "igain";
3396 			what = INPUT_GAIN_CONTROL;
3397 			break;
3398 		case (3 << 22):
3399 			MIX(sc).type = MIX_SIGNED_16;
3400 			MIX(sc).ctl = mixernumber;
3401 			MIX(sc).name = "igainpad";
3402 			what = INPUT_GAIN_PAD_CONTROL;
3403 			break;
3404 		default:
3405 			continue;
3406 		}
3407 
3408 		if ((mmask & ctl) == ctl) {
3409 			MIX(sc).nchan = 1;
3410 			MIX(sc).wValue[0] = MAKE_WORD(what, 0);
3411 		} else if ((cmask & ctl) == ctl) {
3412 			MIX(sc).nchan = nchan - 1;
3413 			for (i = 1; i < nchan; i++) {
3414 				if ((UGETDW(d->bmaControls[i]) & ctl) == ctl)
3415 					MIX(sc).wValue[i - 1] = MAKE_WORD(what, i);
3416 				else
3417 					MIX(sc).wValue[i - 1] = -1;
3418 			}
3419 		} else {
3420 			continue;
3421 		}
3422 
3423 		if (MIX(sc).type != MIX_UNKNOWN)
3424 			uaudio_mixer_add_ctl(sc, &MIX(sc));
3425 	}
3426 }
3427 
3428 static void
3429 uaudio_mixer_add_processing_updown(struct uaudio_softc *sc,
3430     const struct uaudio_terminal_node *iot, int id)
3431 {
3432 	const struct usb_audio_processing_unit_0 *d0 = iot[id].u.pu_v1;
3433 	const struct usb_audio_processing_unit_1 *d1 =
3434 	    (const void *)(d0->baSourceId + d0->bNrInPins);
3435 	const struct usb_audio_processing_unit_updown *ud =
3436 	    (const void *)(d1->bmControls + d1->bControlSize);
3437 	uint8_t i;
3438 
3439 	if (uaudio_mixer_verify_desc(d0, sizeof(*ud)) == NULL) {
3440 		return;
3441 	}
3442 	if (uaudio_mixer_verify_desc(d0, sizeof(*ud) + (2 * ud->bNrModes))
3443 	    == NULL) {
3444 		return;
3445 	}
3446 	DPRINTFN(3, "bUnitId=%d bNrModes=%d\n",
3447 	    d0->bUnitId, ud->bNrModes);
3448 
3449 	if (!(d1->bmControls[0] & UA_PROC_MASK(UD_MODE_SELECT_CONTROL))) {
3450 		DPRINTF("no mode select\n");
3451 		return;
3452 	}
3453 	memset(&MIX(sc), 0, sizeof(MIX(sc)));
3454 
3455 	MIX(sc).wIndex = MAKE_WORD(d0->bUnitId, sc->sc_mixer_iface_no);
3456 	MIX(sc).nchan = 1;
3457 	MIX(sc).wValue[0] = MAKE_WORD(UD_MODE_SELECT_CONTROL, 0);
3458 	uaudio_mixer_determine_class(&iot[id], &MIX(sc));
3459 	MIX(sc).type = MIX_ON_OFF;		/* XXX */
3460 
3461 	for (i = 0; i < ud->bNrModes; i++) {
3462 		DPRINTFN(3, "i=%d bm=0x%x\n", i, UGETW(ud->waModes[i]));
3463 		/* XXX */
3464 	}
3465 
3466 	uaudio_mixer_add_ctl(sc, &MIX(sc));
3467 }
3468 
3469 static void
3470 uaudio_mixer_add_processing(struct uaudio_softc *sc,
3471     const struct uaudio_terminal_node *iot, int id)
3472 {
3473 	const struct usb_audio_processing_unit_0 *d0 = iot[id].u.pu_v1;
3474 	const struct usb_audio_processing_unit_1 *d1 =
3475 	    (const void *)(d0->baSourceId + d0->bNrInPins);
3476 	uint16_t ptype;
3477 
3478 	memset(&MIX(sc), 0, sizeof(MIX(sc)));
3479 
3480 	ptype = UGETW(d0->wProcessType);
3481 
3482 	DPRINTFN(3, "wProcessType=%d bUnitId=%d "
3483 	    "bNrInPins=%d\n", ptype, d0->bUnitId, d0->bNrInPins);
3484 
3485 	if (d1->bControlSize == 0) {
3486 		return;
3487 	}
3488 	if (d1->bmControls[0] & UA_PROC_ENABLE_MASK) {
3489 		MIX(sc).wIndex = MAKE_WORD(d0->bUnitId, sc->sc_mixer_iface_no);
3490 		MIX(sc).nchan = 1;
3491 		MIX(sc).wValue[0] = MAKE_WORD(XX_ENABLE_CONTROL, 0);
3492 		uaudio_mixer_determine_class(&iot[id], &MIX(sc));
3493 		MIX(sc).type = MIX_ON_OFF;
3494 		uaudio_mixer_add_ctl(sc, &MIX(sc));
3495 	}
3496 	switch (ptype) {
3497 	case UPDOWNMIX_PROCESS:
3498 		uaudio_mixer_add_processing_updown(sc, iot, id);
3499 		break;
3500 
3501 	case DOLBY_PROLOGIC_PROCESS:
3502 	case P3D_STEREO_EXTENDER_PROCESS:
3503 	case REVERBATION_PROCESS:
3504 	case CHORUS_PROCESS:
3505 	case DYN_RANGE_COMP_PROCESS:
3506 	default:
3507 		DPRINTF("unit %d, type=%d is not implemented\n",
3508 		    d0->bUnitId, ptype);
3509 		break;
3510 	}
3511 }
3512 
3513 static void
3514 uaudio_mixer_add_extension(struct uaudio_softc *sc,
3515     const struct uaudio_terminal_node *iot, int id)
3516 {
3517 	const struct usb_audio_extension_unit_0 *d0 = iot[id].u.eu_v1;
3518 	const struct usb_audio_extension_unit_1 *d1 =
3519 	    (const void *)(d0->baSourceId + d0->bNrInPins);
3520 
3521 	DPRINTFN(3, "bUnitId=%d bNrInPins=%d\n",
3522 	    d0->bUnitId, d0->bNrInPins);
3523 
3524 	if (sc->sc_uq_au_no_xu) {
3525 		return;
3526 	}
3527 	if (d1->bControlSize == 0) {
3528 		return;
3529 	}
3530 	if (d1->bmControls[0] & UA_EXT_ENABLE_MASK) {
3531 
3532 		memset(&MIX(sc), 0, sizeof(MIX(sc)));
3533 
3534 		MIX(sc).wIndex = MAKE_WORD(d0->bUnitId, sc->sc_mixer_iface_no);
3535 		MIX(sc).nchan = 1;
3536 		MIX(sc).wValue[0] = MAKE_WORD(UA_EXT_ENABLE, 0);
3537 		uaudio_mixer_determine_class(&iot[id], &MIX(sc));
3538 		MIX(sc).type = MIX_ON_OFF;
3539 
3540 		uaudio_mixer_add_ctl(sc, &MIX(sc));
3541 	}
3542 }
3543 
3544 static const void *
3545 uaudio_mixer_verify_desc(const void *arg, uint32_t len)
3546 {
3547 	const struct usb_audio_mixer_unit_1 *d1;
3548 	const struct usb_audio_extension_unit_1 *e1;
3549 	const struct usb_audio_processing_unit_1 *u1;
3550 
3551 	union {
3552 		const struct usb_descriptor *desc;
3553 		const struct usb_audio_input_terminal *it;
3554 		const struct usb_audio_output_terminal *ot;
3555 		const struct usb_audio_mixer_unit_0 *mu;
3556 		const struct usb_audio_selector_unit *su;
3557 		const struct usb_audio_feature_unit *fu;
3558 		const struct usb_audio_processing_unit_0 *pu;
3559 		const struct usb_audio_extension_unit_0 *eu;
3560 	}     u;
3561 
3562 	u.desc = arg;
3563 
3564 	if (u.desc == NULL) {
3565 		goto error;
3566 	}
3567 	if (u.desc->bDescriptorType != UDESC_CS_INTERFACE) {
3568 		goto error;
3569 	}
3570 	switch (u.desc->bDescriptorSubtype) {
3571 	case UDESCSUB_AC_INPUT:
3572 		len += sizeof(*u.it);
3573 		break;
3574 
3575 	case UDESCSUB_AC_OUTPUT:
3576 		len += sizeof(*u.ot);
3577 		break;
3578 
3579 	case UDESCSUB_AC_MIXER:
3580 		len += sizeof(*u.mu);
3581 
3582 		if (u.desc->bLength < len) {
3583 			goto error;
3584 		}
3585 		len += u.mu->bNrInPins;
3586 
3587 		if (u.desc->bLength < len) {
3588 			goto error;
3589 		}
3590 		d1 = (const void *)(u.mu->baSourceId + u.mu->bNrInPins);
3591 
3592 		len += sizeof(*d1);
3593 		break;
3594 
3595 	case UDESCSUB_AC_SELECTOR:
3596 		len += sizeof(*u.su);
3597 
3598 		if (u.desc->bLength < len) {
3599 			goto error;
3600 		}
3601 		len += u.su->bNrInPins + 1;
3602 		break;
3603 
3604 	case UDESCSUB_AC_FEATURE:
3605 		len += sizeof(*u.fu) + 1;
3606 
3607 		if (u.desc->bLength < len)
3608 			goto error;
3609 
3610 		len += u.fu->bControlSize;
3611 		break;
3612 
3613 	case UDESCSUB_AC_PROCESSING:
3614 		len += sizeof(*u.pu);
3615 
3616 		if (u.desc->bLength < len) {
3617 			goto error;
3618 		}
3619 		len += u.pu->bNrInPins;
3620 
3621 		if (u.desc->bLength < len) {
3622 			goto error;
3623 		}
3624 		u1 = (const void *)(u.pu->baSourceId + u.pu->bNrInPins);
3625 
3626 		len += sizeof(*u1);
3627 
3628 		if (u.desc->bLength < len) {
3629 			goto error;
3630 		}
3631 		len += u1->bControlSize;
3632 
3633 		break;
3634 
3635 	case UDESCSUB_AC_EXTENSION:
3636 		len += sizeof(*u.eu);
3637 
3638 		if (u.desc->bLength < len) {
3639 			goto error;
3640 		}
3641 		len += u.eu->bNrInPins;
3642 
3643 		if (u.desc->bLength < len) {
3644 			goto error;
3645 		}
3646 		e1 = (const void *)(u.eu->baSourceId + u.eu->bNrInPins);
3647 
3648 		len += sizeof(*e1);
3649 
3650 		if (u.desc->bLength < len) {
3651 			goto error;
3652 		}
3653 		len += e1->bControlSize;
3654 		break;
3655 
3656 	default:
3657 		goto error;
3658 	}
3659 
3660 	if (u.desc->bLength < len) {
3661 		goto error;
3662 	}
3663 	return (u.desc);
3664 
3665 error:
3666 	if (u.desc) {
3667 		DPRINTF("invalid descriptor, type=%d, "
3668 		    "sub_type=%d, len=%d of %d bytes\n",
3669 		    u.desc->bDescriptorType,
3670 		    u.desc->bDescriptorSubtype,
3671 		    u.desc->bLength, len);
3672 	}
3673 	return (NULL);
3674 }
3675 
3676 static const void *
3677 uaudio20_mixer_verify_desc(const void *arg, uint32_t len)
3678 {
3679 	const struct usb_audio20_mixer_unit_1 *d1;
3680 	const struct usb_audio20_extension_unit_1 *e1;
3681 	const struct usb_audio20_processing_unit_1 *u1;
3682 	const struct usb_audio20_clock_selector_unit_1 *c1;
3683 
3684 	union {
3685 		const struct usb_descriptor *desc;
3686 		const struct usb_audio20_clock_source_unit *csrc;
3687 		const struct usb_audio20_clock_selector_unit_0 *csel;
3688 		const struct usb_audio20_clock_multiplier_unit *cmul;
3689 		const struct usb_audio20_input_terminal *it;
3690 		const struct usb_audio20_output_terminal *ot;
3691 		const struct usb_audio20_mixer_unit_0 *mu;
3692 		const struct usb_audio20_selector_unit *su;
3693 		const struct usb_audio20_feature_unit *fu;
3694 		const struct usb_audio20_sample_rate_unit *ru;
3695 		const struct usb_audio20_processing_unit_0 *pu;
3696 		const struct usb_audio20_extension_unit_0 *eu;
3697 		const struct usb_audio20_effect_unit *ef;
3698 	}     u;
3699 
3700 	u.desc = arg;
3701 
3702 	if (u.desc == NULL)
3703 		goto error;
3704 
3705 	if (u.desc->bDescriptorType != UDESC_CS_INTERFACE)
3706 		goto error;
3707 
3708 	switch (u.desc->bDescriptorSubtype) {
3709 	case UDESCSUB_AC_INPUT:
3710 		len += sizeof(*u.it);
3711 		break;
3712 
3713 	case UDESCSUB_AC_OUTPUT:
3714 		len += sizeof(*u.ot);
3715 		break;
3716 
3717 	case UDESCSUB_AC_MIXER:
3718 		len += sizeof(*u.mu);
3719 
3720 		if (u.desc->bLength < len)
3721 			goto error;
3722 		len += u.mu->bNrInPins;
3723 
3724 		if (u.desc->bLength < len)
3725 			goto error;
3726 
3727 		d1 = (const void *)(u.mu->baSourceId + u.mu->bNrInPins);
3728 
3729 		len += sizeof(*d1) + d1->bNrChannels;
3730 		break;
3731 
3732 	case UDESCSUB_AC_SELECTOR:
3733 		len += sizeof(*u.su);
3734 
3735 		if (u.desc->bLength < len)
3736 			goto error;
3737 
3738 		len += u.su->bNrInPins + 1;
3739 		break;
3740 
3741 	case UDESCSUB_AC_FEATURE:
3742 		len += sizeof(*u.fu) + 1;
3743 		break;
3744 
3745 	case UDESCSUB_AC_EFFECT:
3746 		len += sizeof(*u.ef) + 4;
3747 		break;
3748 
3749 	case UDESCSUB_AC_PROCESSING_V2:
3750 		len += sizeof(*u.pu);
3751 
3752 		if (u.desc->bLength < len)
3753 			goto error;
3754 
3755 		len += u.pu->bNrInPins;
3756 
3757 		if (u.desc->bLength < len)
3758 			goto error;
3759 
3760 		u1 = (const void *)(u.pu->baSourceId + u.pu->bNrInPins);
3761 
3762 		len += sizeof(*u1);
3763 		break;
3764 
3765 	case UDESCSUB_AC_EXTENSION_V2:
3766 		len += sizeof(*u.eu);
3767 
3768 		if (u.desc->bLength < len)
3769 			goto error;
3770 
3771 		len += u.eu->bNrInPins;
3772 
3773 		if (u.desc->bLength < len)
3774 			goto error;
3775 
3776 		e1 = (const void *)(u.eu->baSourceId + u.eu->bNrInPins);
3777 
3778 		len += sizeof(*e1);
3779 		break;
3780 
3781 	case UDESCSUB_AC_CLOCK_SRC:
3782 		len += sizeof(*u.csrc);
3783 		break;
3784 
3785 	case UDESCSUB_AC_CLOCK_SEL:
3786 		len += sizeof(*u.csel);
3787 
3788 		if (u.desc->bLength < len)
3789 			goto error;
3790 
3791 		len += u.csel->bNrInPins;
3792 
3793 		if (u.desc->bLength < len)
3794 			goto error;
3795 
3796 		c1 = (const void *)(u.csel->baCSourceId + u.csel->bNrInPins);
3797 
3798 		len += sizeof(*c1);
3799 		break;
3800 
3801 	case UDESCSUB_AC_CLOCK_MUL:
3802 		len += sizeof(*u.cmul);
3803 		break;
3804 
3805 	case UDESCSUB_AC_SAMPLE_RT:
3806 		len += sizeof(*u.ru);
3807 		break;
3808 
3809 	default:
3810 		goto error;
3811 	}
3812 
3813 	if (u.desc->bLength < len)
3814 		goto error;
3815 
3816 	return (u.desc);
3817 
3818 error:
3819 	if (u.desc) {
3820 		DPRINTF("invalid descriptor, type=%d, "
3821 		    "sub_type=%d, len=%d of %d bytes\n",
3822 		    u.desc->bDescriptorType,
3823 		    u.desc->bDescriptorSubtype,
3824 		    u.desc->bLength, len);
3825 	}
3826 	return (NULL);
3827 }
3828 
3829 static struct usb_audio_cluster
3830 uaudio_mixer_get_cluster(uint8_t id, const struct uaudio_terminal_node *iot)
3831 {
3832 	struct usb_audio_cluster r;
3833 	const struct usb_descriptor *dp;
3834 	uint8_t i;
3835 
3836 	for (i = 0; i < UAUDIO_RECURSE_LIMIT; i++) {	/* avoid infinite loops */
3837 		dp = iot[id].u.desc;
3838 		if (dp == NULL) {
3839 			goto error;
3840 		}
3841 		switch (dp->bDescriptorSubtype) {
3842 		case UDESCSUB_AC_INPUT:
3843 			r.bNrChannels = iot[id].u.it_v1->bNrChannels;
3844 			r.wChannelConfig[0] = iot[id].u.it_v1->wChannelConfig[0];
3845 			r.wChannelConfig[1] = iot[id].u.it_v1->wChannelConfig[1];
3846 			r.iChannelNames = iot[id].u.it_v1->iChannelNames;
3847 			goto done;
3848 
3849 		case UDESCSUB_AC_OUTPUT:
3850 			id = iot[id].u.ot_v1->bSourceId;
3851 			break;
3852 
3853 		case UDESCSUB_AC_MIXER:
3854 			r = *(const struct usb_audio_cluster *)
3855 			    &iot[id].u.mu_v1->baSourceId[
3856 			    iot[id].u.mu_v1->bNrInPins];
3857 			goto done;
3858 
3859 		case UDESCSUB_AC_SELECTOR:
3860 			if (iot[id].u.su_v1->bNrInPins > 0) {
3861 				/* XXX This is not really right */
3862 				id = iot[id].u.su_v1->baSourceId[0];
3863 			}
3864 			break;
3865 
3866 		case UDESCSUB_AC_FEATURE:
3867 			id = iot[id].u.fu_v1->bSourceId;
3868 			break;
3869 
3870 		case UDESCSUB_AC_PROCESSING:
3871 			r = *((const struct usb_audio_cluster *)
3872 			    &iot[id].u.pu_v1->baSourceId[
3873 			    iot[id].u.pu_v1->bNrInPins]);
3874 			goto done;
3875 
3876 		case UDESCSUB_AC_EXTENSION:
3877 			r = *((const struct usb_audio_cluster *)
3878 			    &iot[id].u.eu_v1->baSourceId[
3879 			    iot[id].u.eu_v1->bNrInPins]);
3880 			goto done;
3881 
3882 		default:
3883 			goto error;
3884 		}
3885 	}
3886 error:
3887 	DPRINTF("bad data\n");
3888 	memset(&r, 0, sizeof(r));
3889 done:
3890 	return (r);
3891 }
3892 
3893 static struct usb_audio20_cluster
3894 uaudio20_mixer_get_cluster(uint8_t id, const struct uaudio_terminal_node *iot)
3895 {
3896 	struct usb_audio20_cluster r;
3897 	const struct usb_descriptor *dp;
3898 	uint8_t i;
3899 
3900 	for (i = 0; i < UAUDIO_RECURSE_LIMIT; i++) {	/* avoid infinite loops */
3901 		dp = iot[id].u.desc;
3902 		if (dp == NULL)
3903 			goto error;
3904 
3905 		switch (dp->bDescriptorSubtype) {
3906 		case UDESCSUB_AC_INPUT:
3907 			r.bNrChannels = iot[id].u.it_v2->bNrChannels;
3908 			r.bmChannelConfig[0] = iot[id].u.it_v2->bmChannelConfig[0];
3909 			r.bmChannelConfig[1] = iot[id].u.it_v2->bmChannelConfig[1];
3910 			r.bmChannelConfig[2] = iot[id].u.it_v2->bmChannelConfig[2];
3911 			r.bmChannelConfig[3] = iot[id].u.it_v2->bmChannelConfig[3];
3912 			r.iChannelNames = iot[id].u.it_v2->iTerminal;
3913 			goto done;
3914 
3915 		case UDESCSUB_AC_OUTPUT:
3916 			id = iot[id].u.ot_v2->bSourceId;
3917 			break;
3918 
3919 		case UDESCSUB_AC_MIXER:
3920 			r = *(const struct usb_audio20_cluster *)
3921 			    &iot[id].u.mu_v2->baSourceId[
3922 			    iot[id].u.mu_v2->bNrInPins];
3923 			goto done;
3924 
3925 		case UDESCSUB_AC_SELECTOR:
3926 			if (iot[id].u.su_v2->bNrInPins > 0) {
3927 				/* XXX This is not really right */
3928 				id = iot[id].u.su_v2->baSourceId[0];
3929 			}
3930 			break;
3931 
3932 		case UDESCSUB_AC_SAMPLE_RT:
3933 			id = iot[id].u.ru_v2->bSourceId;
3934 			break;
3935 
3936 		case UDESCSUB_AC_EFFECT:
3937 			id = iot[id].u.ef_v2->bSourceId;
3938 			break;
3939 
3940 		case UDESCSUB_AC_FEATURE:
3941 			id = iot[id].u.fu_v2->bSourceId;
3942 			break;
3943 
3944 		case UDESCSUB_AC_PROCESSING_V2:
3945 			r = *((const struct usb_audio20_cluster *)
3946 			    &iot[id].u.pu_v2->baSourceId[
3947 			    iot[id].u.pu_v2->bNrInPins]);
3948 			goto done;
3949 
3950 		case UDESCSUB_AC_EXTENSION_V2:
3951 			r = *((const struct usb_audio20_cluster *)
3952 			    &iot[id].u.eu_v2->baSourceId[
3953 			    iot[id].u.eu_v2->bNrInPins]);
3954 			goto done;
3955 
3956 		default:
3957 			goto error;
3958 		}
3959 	}
3960 error:
3961 	DPRINTF("Bad data!\n");
3962 	memset(&r, 0, sizeof(r));
3963 done:
3964 	return (r);
3965 }
3966 
3967 static uint16_t
3968 uaudio_mixer_determine_class(const struct uaudio_terminal_node *iot,
3969     struct uaudio_mixer_node *mix)
3970 {
3971 	uint16_t terminal_type = 0x0000;
3972 	const struct uaudio_terminal_node *input[2];
3973 	const struct uaudio_terminal_node *output[2];
3974 
3975 	input[0] = uaudio_mixer_get_input(iot, 0);
3976 	input[1] = uaudio_mixer_get_input(iot, 1);
3977 
3978 	output[0] = uaudio_mixer_get_output(iot, 0);
3979 	output[1] = uaudio_mixer_get_output(iot, 1);
3980 
3981 	/*
3982 	 * check if there is only
3983 	 * one output terminal:
3984 	 */
3985 	if (output[0] && (!output[1])) {
3986 		terminal_type =
3987 		    UGETW(output[0]->u.ot_v1->wTerminalType);
3988 	}
3989 	/*
3990 	 * If the only output terminal is USB,
3991 	 * the class is UAC_RECORD.
3992 	 */
3993 	if ((terminal_type & 0xff00) == (UAT_UNDEFINED & 0xff00)) {
3994 
3995 		mix->class = UAC_RECORD;
3996 		if (input[0] && (!input[1])) {
3997 			terminal_type =
3998 			    UGETW(input[0]->u.it_v1->wTerminalType);
3999 		} else {
4000 			terminal_type = 0;
4001 		}
4002 		goto done;
4003 	}
4004 	/*
4005 	 * if the unit is connected to just
4006 	 * one input terminal, the
4007 	 * class is UAC_INPUT:
4008 	 */
4009 	if (input[0] && (!input[1])) {
4010 		mix->class = UAC_INPUT;
4011 		terminal_type =
4012 		    UGETW(input[0]->u.it_v1->wTerminalType);
4013 		goto done;
4014 	}
4015 	/*
4016 	 * Otherwise, the class is UAC_OUTPUT.
4017 	 */
4018 	mix->class = UAC_OUTPUT;
4019 done:
4020 	return (terminal_type);
4021 }
4022 
4023 static uint16_t
4024 uaudio20_mixer_determine_class(const struct uaudio_terminal_node *iot,
4025     struct uaudio_mixer_node *mix)
4026 {
4027 	uint16_t terminal_type = 0x0000;
4028 	const struct uaudio_terminal_node *input[2];
4029 	const struct uaudio_terminal_node *output[2];
4030 
4031 	input[0] = uaudio_mixer_get_input(iot, 0);
4032 	input[1] = uaudio_mixer_get_input(iot, 1);
4033 
4034 	output[0] = uaudio_mixer_get_output(iot, 0);
4035 	output[1] = uaudio_mixer_get_output(iot, 1);
4036 
4037 	/*
4038 	 * check if there is only
4039 	 * one output terminal:
4040 	 */
4041 	if (output[0] && (!output[1]))
4042 		terminal_type = UGETW(output[0]->u.ot_v2->wTerminalType);
4043 	/*
4044 	 * If the only output terminal is USB,
4045 	 * the class is UAC_RECORD.
4046 	 */
4047 	if ((terminal_type & 0xff00) == (UAT_UNDEFINED & 0xff00)) {
4048 
4049 		mix->class = UAC_RECORD;
4050 		if (input[0] && (!input[1])) {
4051 			terminal_type =
4052 			    UGETW(input[0]->u.it_v2->wTerminalType);
4053 		} else {
4054 			terminal_type = 0;
4055 		}
4056 		goto done;
4057 	}
4058 	/*
4059 	 * if the unit is connected to just
4060 	 * one input terminal, the
4061 	 * class is UAC_INPUT:
4062 	 */
4063 	if (input[0] && (!input[1])) {
4064 		mix->class = UAC_INPUT;
4065 		terminal_type =
4066 		    UGETW(input[0]->u.it_v2->wTerminalType);
4067 		goto done;
4068 	}
4069 	/*
4070 	 * Otherwise, the class is UAC_OUTPUT.
4071 	 */
4072 	mix->class = UAC_OUTPUT;
4073 done:
4074 	return (terminal_type);
4075 }
4076 
4077 struct uaudio_tt_to_feature {
4078 	uint16_t terminal_type;
4079 	uint16_t feature;
4080 };
4081 
4082 static const struct uaudio_tt_to_feature uaudio_tt_to_feature[] = {
4083 
4084 	{UAT_STREAM, SOUND_MIXER_PCM},
4085 
4086 	{UATI_MICROPHONE, SOUND_MIXER_MIC},
4087 	{UATI_DESKMICROPHONE, SOUND_MIXER_MIC},
4088 	{UATI_PERSONALMICROPHONE, SOUND_MIXER_MIC},
4089 	{UATI_OMNIMICROPHONE, SOUND_MIXER_MIC},
4090 	{UATI_MICROPHONEARRAY, SOUND_MIXER_MIC},
4091 	{UATI_PROCMICROPHONEARR, SOUND_MIXER_MIC},
4092 
4093 	{UATO_SPEAKER, SOUND_MIXER_SPEAKER},
4094 	{UATO_DESKTOPSPEAKER, SOUND_MIXER_SPEAKER},
4095 	{UATO_ROOMSPEAKER, SOUND_MIXER_SPEAKER},
4096 	{UATO_COMMSPEAKER, SOUND_MIXER_SPEAKER},
4097 
4098 	{UATE_ANALOGCONN, SOUND_MIXER_LINE},
4099 	{UATE_LINECONN, SOUND_MIXER_LINE},
4100 	{UATE_LEGACYCONN, SOUND_MIXER_LINE},
4101 
4102 	{UATE_DIGITALAUIFC, SOUND_MIXER_ALTPCM},
4103 	{UATE_SPDIF, SOUND_MIXER_ALTPCM},
4104 	{UATE_1394DA, SOUND_MIXER_ALTPCM},
4105 	{UATE_1394DV, SOUND_MIXER_ALTPCM},
4106 
4107 	{UATF_CDPLAYER, SOUND_MIXER_CD},
4108 
4109 	{UATF_SYNTHESIZER, SOUND_MIXER_SYNTH},
4110 
4111 	{UATF_VIDEODISCAUDIO, SOUND_MIXER_VIDEO},
4112 	{UATF_DVDAUDIO, SOUND_MIXER_VIDEO},
4113 	{UATF_TVTUNERAUDIO, SOUND_MIXER_VIDEO},
4114 
4115 	/* telephony terminal types */
4116 	{UATT_UNDEFINED, SOUND_MIXER_PHONEIN},	/* SOUND_MIXER_PHONEOUT */
4117 	{UATT_PHONELINE, SOUND_MIXER_PHONEIN},	/* SOUND_MIXER_PHONEOUT */
4118 	{UATT_TELEPHONE, SOUND_MIXER_PHONEIN},	/* SOUND_MIXER_PHONEOUT */
4119 	{UATT_DOWNLINEPHONE, SOUND_MIXER_PHONEIN},	/* SOUND_MIXER_PHONEOUT */
4120 
4121 	{UATF_RADIORECV, SOUND_MIXER_RADIO},
4122 	{UATF_RADIOXMIT, SOUND_MIXER_RADIO},
4123 
4124 	{UAT_UNDEFINED, SOUND_MIXER_VOLUME},
4125 	{UAT_VENDOR, SOUND_MIXER_VOLUME},
4126 	{UATI_UNDEFINED, SOUND_MIXER_VOLUME},
4127 
4128 	/* output terminal types */
4129 	{UATO_UNDEFINED, SOUND_MIXER_VOLUME},
4130 	{UATO_DISPLAYAUDIO, SOUND_MIXER_VOLUME},
4131 	{UATO_SUBWOOFER, SOUND_MIXER_VOLUME},
4132 	{UATO_HEADPHONES, SOUND_MIXER_VOLUME},
4133 
4134 	/* bidir terminal types */
4135 	{UATB_UNDEFINED, SOUND_MIXER_VOLUME},
4136 	{UATB_HANDSET, SOUND_MIXER_VOLUME},
4137 	{UATB_HEADSET, SOUND_MIXER_VOLUME},
4138 	{UATB_SPEAKERPHONE, SOUND_MIXER_VOLUME},
4139 	{UATB_SPEAKERPHONEESUP, SOUND_MIXER_VOLUME},
4140 	{UATB_SPEAKERPHONEECANC, SOUND_MIXER_VOLUME},
4141 
4142 	/* external terminal types */
4143 	{UATE_UNDEFINED, SOUND_MIXER_VOLUME},
4144 
4145 	/* embedded function terminal types */
4146 	{UATF_UNDEFINED, SOUND_MIXER_VOLUME},
4147 	{UATF_CALIBNOISE, SOUND_MIXER_VOLUME},
4148 	{UATF_EQUNOISE, SOUND_MIXER_VOLUME},
4149 	{UATF_DAT, SOUND_MIXER_VOLUME},
4150 	{UATF_DCC, SOUND_MIXER_VOLUME},
4151 	{UATF_MINIDISK, SOUND_MIXER_VOLUME},
4152 	{UATF_ANALOGTAPE, SOUND_MIXER_VOLUME},
4153 	{UATF_PHONOGRAPH, SOUND_MIXER_VOLUME},
4154 	{UATF_VCRAUDIO, SOUND_MIXER_VOLUME},
4155 	{UATF_SATELLITE, SOUND_MIXER_VOLUME},
4156 	{UATF_CABLETUNER, SOUND_MIXER_VOLUME},
4157 	{UATF_DSS, SOUND_MIXER_VOLUME},
4158 	{UATF_MULTITRACK, SOUND_MIXER_VOLUME},
4159 	{0xffff, SOUND_MIXER_VOLUME},
4160 
4161 	/* default */
4162 	{0x0000, SOUND_MIXER_VOLUME},
4163 };
4164 
4165 static uint16_t
4166 uaudio_mixer_feature_name(const struct uaudio_terminal_node *iot,
4167     struct uaudio_mixer_node *mix)
4168 {
4169 	const struct uaudio_tt_to_feature *uat = uaudio_tt_to_feature;
4170 	uint16_t terminal_type = uaudio_mixer_determine_class(iot, mix);
4171 
4172 	if ((mix->class == UAC_RECORD) && (terminal_type == 0)) {
4173 		return (SOUND_MIXER_IMIX);
4174 	}
4175 	while (uat->terminal_type) {
4176 		if (uat->terminal_type == terminal_type) {
4177 			break;
4178 		}
4179 		uat++;
4180 	}
4181 
4182 	DPRINTF("terminal_type=0x%04x -> %d\n",
4183 	    terminal_type, uat->feature);
4184 
4185 	return (uat->feature);
4186 }
4187 
4188 static uint16_t
4189 uaudio20_mixer_feature_name(const struct uaudio_terminal_node *iot,
4190     struct uaudio_mixer_node *mix)
4191 {
4192 	const struct uaudio_tt_to_feature *uat;
4193 	uint16_t terminal_type = uaudio20_mixer_determine_class(iot, mix);
4194 
4195 	if ((mix->class == UAC_RECORD) && (terminal_type == 0))
4196 		return (SOUND_MIXER_IMIX);
4197 
4198 	for (uat = uaudio_tt_to_feature; uat->terminal_type != 0; uat++) {
4199 		if (uat->terminal_type == terminal_type)
4200 			break;
4201 	}
4202 
4203 	DPRINTF("terminal_type=0x%04x -> %d\n",
4204 	    terminal_type, uat->feature);
4205 
4206 	return (uat->feature);
4207 }
4208 
4209 static const struct uaudio_terminal_node *
4210 uaudio_mixer_get_input(const struct uaudio_terminal_node *iot, uint8_t i)
4211 {
4212 	struct uaudio_terminal_node *root = iot->root;
4213 	uint8_t n;
4214 
4215 	n = iot->usr.id_max;
4216 	do {
4217 		if (iot->usr.bit_input[n / 8] & (1 << (n % 8))) {
4218 			if (!i--)
4219 				return (root + n);
4220 		}
4221 	} while (n--);
4222 
4223 	return (NULL);
4224 }
4225 
4226 static const struct uaudio_terminal_node *
4227 uaudio_mixer_get_output(const struct uaudio_terminal_node *iot, uint8_t i)
4228 {
4229 	struct uaudio_terminal_node *root = iot->root;
4230 	uint8_t n;
4231 
4232 	n = iot->usr.id_max;
4233 	do {
4234 		if (iot->usr.bit_output[n / 8] & (1 << (n % 8))) {
4235 			if (!i--)
4236 				return (root + n);
4237 		}
4238 	} while (n--);
4239 
4240 	return (NULL);
4241 }
4242 
4243 static void
4244 uaudio_mixer_find_inputs_sub(struct uaudio_terminal_node *root,
4245     const uint8_t *p_id, uint8_t n_id,
4246     struct uaudio_search_result *info)
4247 {
4248 	struct uaudio_terminal_node *iot;
4249 	uint8_t n;
4250 	uint8_t i;
4251 	uint8_t is_last;
4252 
4253 top:
4254 	for (n = 0; n < n_id; n++) {
4255 
4256 		i = p_id[n];
4257 
4258 		if (info->recurse_level == UAUDIO_RECURSE_LIMIT) {
4259 			DPRINTF("avoided going into a circle at id=%d!\n", i);
4260 			return;
4261 		}
4262 
4263 		info->recurse_level++;
4264 
4265 		iot = (root + i);
4266 
4267 		if (iot->u.desc == NULL)
4268 			continue;
4269 
4270 		is_last = ((n + 1) == n_id);
4271 
4272 		switch (iot->u.desc->bDescriptorSubtype) {
4273 		case UDESCSUB_AC_INPUT:
4274 			info->bit_input[i / 8] |= (1 << (i % 8));
4275 			break;
4276 
4277 		case UDESCSUB_AC_FEATURE:
4278 			if (is_last) {
4279 				p_id = &iot->u.fu_v1->bSourceId;
4280 				n_id = 1;
4281 				goto top;
4282 			}
4283 			uaudio_mixer_find_inputs_sub(
4284 			    root, &iot->u.fu_v1->bSourceId, 1, info);
4285 			break;
4286 
4287 		case UDESCSUB_AC_OUTPUT:
4288 			if (is_last) {
4289 				p_id = &iot->u.ot_v1->bSourceId;
4290 				n_id = 1;
4291 				goto top;
4292 			}
4293 			uaudio_mixer_find_inputs_sub(
4294 			    root, &iot->u.ot_v1->bSourceId, 1, info);
4295 			break;
4296 
4297 		case UDESCSUB_AC_MIXER:
4298 			if (is_last) {
4299 				p_id = iot->u.mu_v1->baSourceId;
4300 				n_id = iot->u.mu_v1->bNrInPins;
4301 				goto top;
4302 			}
4303 			uaudio_mixer_find_inputs_sub(
4304 			    root, iot->u.mu_v1->baSourceId,
4305 			    iot->u.mu_v1->bNrInPins, info);
4306 			break;
4307 
4308 		case UDESCSUB_AC_SELECTOR:
4309 			if (is_last) {
4310 				p_id = iot->u.su_v1->baSourceId;
4311 				n_id = iot->u.su_v1->bNrInPins;
4312 				goto top;
4313 			}
4314 			uaudio_mixer_find_inputs_sub(
4315 			    root, iot->u.su_v1->baSourceId,
4316 			    iot->u.su_v1->bNrInPins, info);
4317 			break;
4318 
4319 		case UDESCSUB_AC_PROCESSING:
4320 			if (is_last) {
4321 				p_id = iot->u.pu_v1->baSourceId;
4322 				n_id = iot->u.pu_v1->bNrInPins;
4323 				goto top;
4324 			}
4325 			uaudio_mixer_find_inputs_sub(
4326 			    root, iot->u.pu_v1->baSourceId,
4327 			    iot->u.pu_v1->bNrInPins, info);
4328 			break;
4329 
4330 		case UDESCSUB_AC_EXTENSION:
4331 			if (is_last) {
4332 				p_id = iot->u.eu_v1->baSourceId;
4333 				n_id = iot->u.eu_v1->bNrInPins;
4334 				goto top;
4335 			}
4336 			uaudio_mixer_find_inputs_sub(
4337 			    root, iot->u.eu_v1->baSourceId,
4338 			    iot->u.eu_v1->bNrInPins, info);
4339 			break;
4340 
4341 		default:
4342 			break;
4343 		}
4344 	}
4345 }
4346 
4347 static void
4348 uaudio20_mixer_find_inputs_sub(struct uaudio_terminal_node *root,
4349     const uint8_t *p_id, uint8_t n_id,
4350     struct uaudio_search_result *info)
4351 {
4352 	struct uaudio_terminal_node *iot;
4353 	uint8_t n;
4354 	uint8_t i;
4355 	uint8_t is_last;
4356 
4357 top:
4358 	for (n = 0; n < n_id; n++) {
4359 
4360 		i = p_id[n];
4361 
4362 		if (info->recurse_level == UAUDIO_RECURSE_LIMIT) {
4363 			DPRINTF("avoided going into a circle at id=%d!\n", i);
4364 			return;
4365 		}
4366 
4367 		info->recurse_level++;
4368 
4369 		iot = (root + i);
4370 
4371 		if (iot->u.desc == NULL)
4372 			continue;
4373 
4374 		is_last = ((n + 1) == n_id);
4375 
4376 		switch (iot->u.desc->bDescriptorSubtype) {
4377 		case UDESCSUB_AC_INPUT:
4378 			info->bit_input[i / 8] |= (1 << (i % 8));
4379 			break;
4380 
4381 		case UDESCSUB_AC_OUTPUT:
4382 			if (is_last) {
4383 				p_id = &iot->u.ot_v2->bSourceId;
4384 				n_id = 1;
4385 				goto top;
4386 			}
4387 			uaudio20_mixer_find_inputs_sub(
4388 			    root, &iot->u.ot_v2->bSourceId, 1, info);
4389 			break;
4390 
4391 		case UDESCSUB_AC_MIXER:
4392 			if (is_last) {
4393 				p_id = iot->u.mu_v2->baSourceId;
4394 				n_id = iot->u.mu_v2->bNrInPins;
4395 				goto top;
4396 			}
4397 			uaudio20_mixer_find_inputs_sub(
4398 			    root, iot->u.mu_v2->baSourceId,
4399 			    iot->u.mu_v2->bNrInPins, info);
4400 			break;
4401 
4402 		case UDESCSUB_AC_SELECTOR:
4403 			if (is_last) {
4404 				p_id = iot->u.su_v2->baSourceId;
4405 				n_id = iot->u.su_v2->bNrInPins;
4406 				goto top;
4407 			}
4408 			uaudio20_mixer_find_inputs_sub(
4409 			    root, iot->u.su_v2->baSourceId,
4410 			    iot->u.su_v2->bNrInPins, info);
4411 			break;
4412 
4413 		case UDESCSUB_AC_SAMPLE_RT:
4414 			if (is_last) {
4415 				p_id = &iot->u.ru_v2->bSourceId;
4416 				n_id = 1;
4417 				goto top;
4418 			}
4419 			uaudio20_mixer_find_inputs_sub(
4420 			    root, &iot->u.ru_v2->bSourceId,
4421 			    1, info);
4422 			break;
4423 
4424 		case UDESCSUB_AC_EFFECT:
4425 			if (is_last) {
4426 				p_id = &iot->u.ef_v2->bSourceId;
4427 				n_id = 1;
4428 				goto top;
4429 			}
4430 			uaudio20_mixer_find_inputs_sub(
4431 			    root, &iot->u.ef_v2->bSourceId,
4432 			    1, info);
4433 			break;
4434 
4435 		case UDESCSUB_AC_FEATURE:
4436 			if (is_last) {
4437 				p_id = &iot->u.fu_v2->bSourceId;
4438 				n_id = 1;
4439 				goto top;
4440 			}
4441 			uaudio20_mixer_find_inputs_sub(
4442 			    root, &iot->u.fu_v2->bSourceId, 1, info);
4443 			break;
4444 
4445 		case UDESCSUB_AC_PROCESSING_V2:
4446 			if (is_last) {
4447 				p_id = iot->u.pu_v2->baSourceId;
4448 				n_id = iot->u.pu_v2->bNrInPins;
4449 				goto top;
4450 			}
4451 			uaudio20_mixer_find_inputs_sub(
4452 			    root, iot->u.pu_v2->baSourceId,
4453 			    iot->u.pu_v2->bNrInPins, info);
4454 			break;
4455 
4456 		case UDESCSUB_AC_EXTENSION_V2:
4457 			if (is_last) {
4458 				p_id = iot->u.eu_v2->baSourceId;
4459 				n_id = iot->u.eu_v2->bNrInPins;
4460 				goto top;
4461 			}
4462 			uaudio20_mixer_find_inputs_sub(
4463 			    root, iot->u.eu_v2->baSourceId,
4464 			    iot->u.eu_v2->bNrInPins, info);
4465 			break;
4466 		default:
4467 			break;
4468 		}
4469 	}
4470 }
4471 
4472 static void
4473 uaudio20_mixer_find_clocks_sub(struct uaudio_terminal_node *root,
4474     const uint8_t *p_id, uint8_t n_id,
4475     struct uaudio_search_result *info)
4476 {
4477 	struct uaudio_terminal_node *iot;
4478 	uint8_t n;
4479 	uint8_t i;
4480 	uint8_t is_last;
4481 	uint8_t id;
4482 
4483 top:
4484 	for (n = 0; n < n_id; n++) {
4485 
4486 		i = p_id[n];
4487 
4488 		if (info->recurse_level == UAUDIO_RECURSE_LIMIT) {
4489 			DPRINTF("avoided going into a circle at id=%d!\n", i);
4490 			return;
4491 		}
4492 
4493 		info->recurse_level++;
4494 
4495 		iot = (root + i);
4496 
4497 		if (iot->u.desc == NULL)
4498 			continue;
4499 
4500 		is_last = ((n + 1) == n_id);
4501 
4502 		switch (iot->u.desc->bDescriptorSubtype) {
4503 		case UDESCSUB_AC_INPUT:
4504 			info->is_input = 1;
4505 			if (is_last) {
4506 				p_id = &iot->u.it_v2->bCSourceId;
4507 				n_id = 1;
4508 				goto top;
4509 			}
4510 			uaudio20_mixer_find_clocks_sub(root,
4511 			    &iot->u.it_v2->bCSourceId, 1, info);
4512 			break;
4513 
4514 		case UDESCSUB_AC_OUTPUT:
4515 			info->is_input = 0;
4516 			if (is_last) {
4517 				p_id = &iot->u.ot_v2->bCSourceId;
4518 				n_id = 1;
4519 				goto top;
4520 			}
4521 			uaudio20_mixer_find_clocks_sub(root,
4522 			    &iot->u.ot_v2->bCSourceId, 1, info);
4523 			break;
4524 
4525 		case UDESCSUB_AC_CLOCK_SEL:
4526 			if (is_last) {
4527 				p_id = iot->u.csel_v2->baCSourceId;
4528 				n_id = iot->u.csel_v2->bNrInPins;
4529 				goto top;
4530 			}
4531 			uaudio20_mixer_find_clocks_sub(root,
4532 			    iot->u.csel_v2->baCSourceId,
4533 			    iot->u.csel_v2->bNrInPins, info);
4534 			break;
4535 
4536 		case UDESCSUB_AC_CLOCK_MUL:
4537 			if (is_last) {
4538 				p_id = &iot->u.cmul_v2->bCSourceId;
4539 				n_id = 1;
4540 				goto top;
4541 			}
4542 			uaudio20_mixer_find_clocks_sub(root,
4543 			    &iot->u.cmul_v2->bCSourceId,
4544 			    1, info);
4545 			break;
4546 
4547 		case UDESCSUB_AC_CLOCK_SRC:
4548 
4549 			id = iot->u.csrc_v2->bClockId;
4550 
4551 			switch (info->is_input) {
4552 			case 0:
4553 				info->bit_output[id / 8] |= (1 << (id % 8));
4554 				break;
4555 			case 1:
4556 				info->bit_input[id / 8] |= (1 << (id % 8));
4557 				break;
4558 			default:
4559 				break;
4560 			}
4561 			break;
4562 
4563 		default:
4564 			break;
4565 		}
4566 	}
4567 }
4568 
4569 static void
4570 uaudio_mixer_find_outputs_sub(struct uaudio_terminal_node *root, uint8_t id,
4571     uint8_t n_id, struct uaudio_search_result *info)
4572 {
4573 	struct uaudio_terminal_node *iot = (root + id);
4574 	uint8_t j;
4575 
4576 	j = n_id;
4577 	do {
4578 		if ((j != id) && ((root + j)->u.desc) &&
4579 		    ((root + j)->u.desc->bDescriptorSubtype == UDESCSUB_AC_OUTPUT)) {
4580 
4581 			/*
4582 			 * "j" (output) <--- virtual wire <--- "id" (input)
4583 			 *
4584 			 * if "j" has "id" on the input, then "id" have "j" on
4585 			 * the output, because they are connected:
4586 			 */
4587 			if ((root + j)->usr.bit_input[id / 8] & (1 << (id % 8))) {
4588 				iot->usr.bit_output[j / 8] |= (1 << (j % 8));
4589 			}
4590 		}
4591 	} while (j--);
4592 }
4593 
4594 static void
4595 uaudio_mixer_fill_info(struct uaudio_softc *sc,
4596     struct usb_device *udev, void *desc)
4597 {
4598 	const struct usb_audio_control_descriptor *acdp;
4599 	struct usb_config_descriptor *cd = usbd_get_config_descriptor(udev);
4600 	const struct usb_descriptor *dp;
4601 	const struct usb_audio_unit *au;
4602 	struct uaudio_terminal_node *iot = NULL;
4603 	uint16_t wTotalLen;
4604 	uint8_t ID_max = 0;		/* inclusive */
4605 	uint8_t i;
4606 
4607 	desc = usb_desc_foreach(cd, desc);
4608 
4609 	if (desc == NULL) {
4610 		DPRINTF("no Audio Control header\n");
4611 		goto done;
4612 	}
4613 	acdp = desc;
4614 
4615 	if ((acdp->bLength < sizeof(*acdp)) ||
4616 	    (acdp->bDescriptorType != UDESC_CS_INTERFACE) ||
4617 	    (acdp->bDescriptorSubtype != UDESCSUB_AC_HEADER)) {
4618 		DPRINTF("invalid Audio Control header\n");
4619 		goto done;
4620 	}
4621 	/* "wTotalLen" is allowed to be corrupt */
4622 	wTotalLen = UGETW(acdp->wTotalLength) - acdp->bLength;
4623 
4624 	/* get USB audio revision */
4625 	sc->sc_audio_rev = UGETW(acdp->bcdADC);
4626 
4627 	DPRINTFN(3, "found AC header, vers=%03x, len=%d\n",
4628 	    sc->sc_audio_rev, wTotalLen);
4629 
4630 	iot = malloc(sizeof(struct uaudio_terminal_node) * 256, M_TEMP,
4631 	    M_WAITOK | M_ZERO);
4632 
4633 	if (iot == NULL) {
4634 		DPRINTF("no memory!\n");
4635 		goto done;
4636 	}
4637 	while ((desc = usb_desc_foreach(cd, desc))) {
4638 
4639 		dp = desc;
4640 
4641 		if (dp->bLength > wTotalLen) {
4642 			break;
4643 		} else {
4644 			wTotalLen -= dp->bLength;
4645 		}
4646 
4647 		if (sc->sc_audio_rev >= UAUDIO_VERSION_30)
4648 			au = NULL;
4649 		else if (sc->sc_audio_rev >= UAUDIO_VERSION_20)
4650 			au = uaudio20_mixer_verify_desc(dp, 0);
4651 		else
4652 			au = uaudio_mixer_verify_desc(dp, 0);
4653 
4654 		if (au) {
4655 			iot[au->bUnitId].u.desc = (const void *)au;
4656 			if (au->bUnitId > ID_max)
4657 				ID_max = au->bUnitId;
4658 		}
4659 	}
4660 
4661 	DPRINTF("Maximum ID=%d\n", ID_max);
4662 
4663 	/*
4664 	 * determine sourcing inputs for
4665 	 * all nodes in the tree:
4666 	 */
4667 	i = ID_max;
4668 	do {
4669 		if (sc->sc_audio_rev >= UAUDIO_VERSION_30) {
4670 			/* FALLTHROUGH */
4671 		} else if (sc->sc_audio_rev >= UAUDIO_VERSION_20) {
4672 			uaudio20_mixer_find_inputs_sub(iot,
4673 			    &i, 1, &((iot + i)->usr));
4674 
4675 			sc->sc_mixer_clocks.is_input = 255;
4676 			sc->sc_mixer_clocks.recurse_level = 0;
4677 
4678 			uaudio20_mixer_find_clocks_sub(iot,
4679 			    &i, 1, &sc->sc_mixer_clocks);
4680 		} else {
4681 			uaudio_mixer_find_inputs_sub(iot,
4682 			    &i, 1, &((iot + i)->usr));
4683 		}
4684 	} while (i--);
4685 
4686 	/*
4687 	 * determine outputs for
4688 	 * all nodes in the tree:
4689 	 */
4690 	i = ID_max;
4691 	do {
4692 		uaudio_mixer_find_outputs_sub(iot,
4693 		    i, ID_max, &((iot + i)->usr));
4694 	} while (i--);
4695 
4696 	/* set "id_max" and "root" */
4697 
4698 	i = ID_max;
4699 	do {
4700 		(iot + i)->usr.id_max = ID_max;
4701 		(iot + i)->root = iot;
4702 	} while (i--);
4703 
4704 	/*
4705 	 * Scan the config to create a linked list of "mixer" nodes:
4706 	 */
4707 
4708 	i = ID_max;
4709 	do {
4710 		dp = iot[i].u.desc;
4711 
4712 		if (dp == NULL)
4713 			continue;
4714 
4715 		DPRINTFN(11, "id=%d subtype=%d\n",
4716 		    i, dp->bDescriptorSubtype);
4717 
4718 		if (sc->sc_audio_rev >= UAUDIO_VERSION_30) {
4719 			continue;
4720 		} else if (sc->sc_audio_rev >= UAUDIO_VERSION_20) {
4721 
4722 			switch (dp->bDescriptorSubtype) {
4723 			case UDESCSUB_AC_HEADER:
4724 				DPRINTF("unexpected AC header\n");
4725 				break;
4726 
4727 			case UDESCSUB_AC_INPUT:
4728 			case UDESCSUB_AC_OUTPUT:
4729 			case UDESCSUB_AC_PROCESSING_V2:
4730 			case UDESCSUB_AC_EXTENSION_V2:
4731 			case UDESCSUB_AC_EFFECT:
4732 			case UDESCSUB_AC_CLOCK_SRC:
4733 			case UDESCSUB_AC_CLOCK_SEL:
4734 			case UDESCSUB_AC_CLOCK_MUL:
4735 			case UDESCSUB_AC_SAMPLE_RT:
4736 				break;
4737 
4738 			case UDESCSUB_AC_MIXER:
4739 				uaudio20_mixer_add_mixer(sc, iot, i);
4740 				break;
4741 
4742 			case UDESCSUB_AC_SELECTOR:
4743 				uaudio20_mixer_add_selector(sc, iot, i);
4744 				break;
4745 
4746 			case UDESCSUB_AC_FEATURE:
4747 				uaudio20_mixer_add_feature(sc, iot, i);
4748 				break;
4749 
4750 			default:
4751 				DPRINTF("bad AC desc subtype=0x%02x\n",
4752 				    dp->bDescriptorSubtype);
4753 				break;
4754 			}
4755 			continue;
4756 		}
4757 
4758 		switch (dp->bDescriptorSubtype) {
4759 		case UDESCSUB_AC_HEADER:
4760 			DPRINTF("unexpected AC header\n");
4761 			break;
4762 
4763 		case UDESCSUB_AC_INPUT:
4764 		case UDESCSUB_AC_OUTPUT:
4765 			break;
4766 
4767 		case UDESCSUB_AC_MIXER:
4768 			uaudio_mixer_add_mixer(sc, iot, i);
4769 			break;
4770 
4771 		case UDESCSUB_AC_SELECTOR:
4772 			uaudio_mixer_add_selector(sc, iot, i);
4773 			break;
4774 
4775 		case UDESCSUB_AC_FEATURE:
4776 			uaudio_mixer_add_feature(sc, iot, i);
4777 			break;
4778 
4779 		case UDESCSUB_AC_PROCESSING:
4780 			uaudio_mixer_add_processing(sc, iot, i);
4781 			break;
4782 
4783 		case UDESCSUB_AC_EXTENSION:
4784 			uaudio_mixer_add_extension(sc, iot, i);
4785 			break;
4786 
4787 		default:
4788 			DPRINTF("bad AC desc subtype=0x%02x\n",
4789 			    dp->bDescriptorSubtype);
4790 			break;
4791 		}
4792 
4793 	} while (i--);
4794 
4795 done:
4796 	free(iot, M_TEMP);
4797 }
4798 
4799 static int
4800 uaudio_mixer_get(struct usb_device *udev, uint16_t audio_rev,
4801     uint8_t what, struct uaudio_mixer_node *mc)
4802 {
4803 	struct usb_device_request req;
4804 	int val;
4805 	uint8_t data[2 + (2 * 3)];
4806 	usb_error_t err;
4807 
4808 	if (mc->wValue[0] == -1)
4809 		return (0);
4810 
4811 	if (audio_rev >= UAUDIO_VERSION_30)
4812 		return (0);
4813 	else if (audio_rev >= UAUDIO_VERSION_20) {
4814 		if (what == GET_CUR) {
4815 			req.bRequest = UA20_CS_CUR;
4816 			USETW(req.wLength, 2);
4817 		} else {
4818 			req.bRequest = UA20_CS_RANGE;
4819 			USETW(req.wLength, 8);
4820 		}
4821 	} else {
4822 		uint16_t len = MIX_SIZE(mc->type);
4823 
4824 		req.bRequest = what;
4825 		USETW(req.wLength, len);
4826 	}
4827 
4828 	req.bmRequestType = UT_READ_CLASS_INTERFACE;
4829 	USETW(req.wValue, mc->wValue[0]);
4830 	USETW(req.wIndex, mc->wIndex);
4831 
4832 	memset(data, 0, sizeof(data));
4833 
4834 	err = usbd_do_request(udev, NULL, &req, data);
4835 	if (err) {
4836 		DPRINTF("err=%s\n", usbd_errstr(err));
4837 		return (0);
4838 	}
4839 
4840 	if (audio_rev >= UAUDIO_VERSION_30) {
4841 		val = 0;
4842 	} else if (audio_rev >= UAUDIO_VERSION_20) {
4843 		switch (what) {
4844 		case GET_CUR:
4845 			val = (data[0] | (data[1] << 8));
4846 			break;
4847 		case GET_MIN:
4848 			val = (data[2] | (data[3] << 8));
4849 			break;
4850 		case GET_MAX:
4851 			val = (data[4] | (data[5] << 8));
4852 			break;
4853 		case GET_RES:
4854 			val = (data[6] | (data[7] << 8));
4855 			break;
4856 		default:
4857 			val = 0;
4858 			break;
4859 		}
4860 	} else {
4861 		val = (data[0] | (data[1] << 8));
4862 	}
4863 
4864 	if (what == GET_CUR || what == GET_MIN || what == GET_MAX)
4865 		val = uaudio_mixer_signext(mc->type, val);
4866 
4867 	DPRINTFN(3, "val=%d\n", val);
4868 
4869 	return (val);
4870 }
4871 
4872 static void
4873 uaudio_mixer_write_cfg_callback(struct usb_xfer *xfer, usb_error_t error)
4874 {
4875 	struct usb_device_request req;
4876 	struct uaudio_softc *sc = usbd_xfer_softc(xfer);
4877 	struct uaudio_mixer_node *mc = sc->sc_mixer_curr;
4878 	struct usb_page_cache *pc;
4879 	uint16_t len;
4880 	uint8_t repeat = 1;
4881 	uint8_t update;
4882 	uint8_t chan;
4883 	uint8_t buf[2];
4884 
4885 	DPRINTF("\n");
4886 
4887 	switch (USB_GET_STATE(xfer)) {
4888 	case USB_ST_TRANSFERRED:
4889 tr_transferred:
4890 	case USB_ST_SETUP:
4891 tr_setup:
4892 
4893 		if (mc == NULL) {
4894 			mc = sc->sc_mixer_root;
4895 			sc->sc_mixer_curr = mc;
4896 			sc->sc_mixer_chan = 0;
4897 			repeat = 0;
4898 		}
4899 		while (mc) {
4900 			while (sc->sc_mixer_chan < mc->nchan) {
4901 
4902 				chan = sc->sc_mixer_chan;
4903 
4904 				sc->sc_mixer_chan++;
4905 
4906 				update = ((mc->update[chan / 8] & (1 << (chan % 8))) &&
4907 				    (mc->wValue[chan] != -1));
4908 
4909 				mc->update[chan / 8] &= ~(1 << (chan % 8));
4910 
4911 				if (update) {
4912 
4913 					req.bmRequestType = UT_WRITE_CLASS_INTERFACE;
4914 					USETW(req.wValue, mc->wValue[chan]);
4915 					USETW(req.wIndex, mc->wIndex);
4916 
4917 					if (sc->sc_audio_rev >= UAUDIO_VERSION_30) {
4918 						return;
4919 					} else if (sc->sc_audio_rev >= UAUDIO_VERSION_20) {
4920 						len = 2;
4921 						req.bRequest = UA20_CS_CUR;
4922 						USETW(req.wLength, len);
4923 					} else {
4924 						len = MIX_SIZE(mc->type);
4925 						req.bRequest = SET_CUR;
4926 						USETW(req.wLength, len);
4927 					}
4928 
4929 					buf[0] = (mc->wData[chan] & 0xFF);
4930 					buf[1] = (mc->wData[chan] >> 8) & 0xFF;
4931 
4932 					pc = usbd_xfer_get_frame(xfer, 0);
4933 					usbd_copy_in(pc, 0, &req, sizeof(req));
4934 					pc = usbd_xfer_get_frame(xfer, 1);
4935 					usbd_copy_in(pc, 0, buf, len);
4936 
4937 					usbd_xfer_set_frame_len(xfer, 0, sizeof(req));
4938 					usbd_xfer_set_frame_len(xfer, 1, len);
4939 					usbd_xfer_set_frames(xfer, len ? 2 : 1);
4940 					usbd_transfer_submit(xfer);
4941 					return;
4942 				}
4943 			}
4944 
4945 			mc = mc->next;
4946 			sc->sc_mixer_curr = mc;
4947 			sc->sc_mixer_chan = 0;
4948 		}
4949 
4950 		if (repeat) {
4951 			goto tr_setup;
4952 		}
4953 		break;
4954 
4955 	default:			/* Error */
4956 		DPRINTF("error=%s\n", usbd_errstr(error));
4957 		if (error == USB_ERR_CANCELLED) {
4958 			/* do nothing - we are detaching */
4959 			break;
4960 		}
4961 		goto tr_transferred;
4962 	}
4963 }
4964 
4965 static usb_error_t
4966 uaudio_set_speed(struct usb_device *udev, uint8_t endpt, uint32_t speed)
4967 {
4968 	struct usb_device_request req;
4969 	uint8_t data[3];
4970 
4971 	DPRINTFN(6, "endpt=%d speed=%u\n", endpt, speed);
4972 
4973 	req.bmRequestType = UT_WRITE_CLASS_ENDPOINT;
4974 	req.bRequest = SET_CUR;
4975 	USETW2(req.wValue, SAMPLING_FREQ_CONTROL, 0);
4976 	USETW(req.wIndex, endpt);
4977 	USETW(req.wLength, 3);
4978 	data[0] = speed;
4979 	data[1] = speed >> 8;
4980 	data[2] = speed >> 16;
4981 
4982 	return (usbd_do_request(udev, NULL, &req, data));
4983 }
4984 
4985 static usb_error_t
4986 uaudio20_set_speed(struct usb_device *udev, uint8_t iface_no,
4987     uint8_t clockid, uint32_t speed)
4988 {
4989 	struct usb_device_request req;
4990 	uint8_t data[4];
4991 
4992 	DPRINTFN(6, "ifaceno=%d clockid=%d speed=%u\n",
4993 	    iface_no, clockid, speed);
4994 
4995 	req.bmRequestType = UT_WRITE_CLASS_INTERFACE;
4996 	req.bRequest = UA20_CS_CUR;
4997 	USETW2(req.wValue, UA20_CS_SAM_FREQ_CONTROL, 0);
4998 	USETW2(req.wIndex, clockid, iface_no);
4999 	USETW(req.wLength, 4);
5000 	data[0] = speed;
5001 	data[1] = speed >> 8;
5002 	data[2] = speed >> 16;
5003 	data[3] = speed >> 24;
5004 
5005 	return (usbd_do_request(udev, NULL, &req, data));
5006 }
5007 
5008 static int
5009 uaudio_mixer_signext(uint8_t type, int val)
5010 {
5011 	if (!MIX_UNSIGNED(type)) {
5012 		if (MIX_SIZE(type) == 2) {
5013 			val = (int16_t)val;
5014 		} else {
5015 			val = (int8_t)val;
5016 		}
5017 	}
5018 	return (val);
5019 }
5020 
5021 static int
5022 uaudio_mixer_bsd2value(struct uaudio_mixer_node *mc, int32_t val)
5023 {
5024 	if (mc->type == MIX_ON_OFF) {
5025 		val = (val != 0);
5026 	} else if (mc->type == MIX_SELECTOR) {
5027 		if ((val < mc->minval) ||
5028 		    (val > mc->maxval)) {
5029 			val = mc->minval;
5030 		}
5031 	} else {
5032 
5033 		/* compute actual volume */
5034 		val = (val * mc->mul) / 255;
5035 
5036 		/* add lower offset */
5037 		val = val + mc->minval;
5038 
5039 		/* make sure we don't write a value out of range */
5040 		if (val > mc->maxval)
5041 			val = mc->maxval;
5042 		else if (val < mc->minval)
5043 			val = mc->minval;
5044 	}
5045 
5046 	DPRINTFN(6, "type=0x%03x val=%d min=%d max=%d val=%d\n",
5047 	    mc->type, val, mc->minval, mc->maxval, val);
5048 	return (val);
5049 }
5050 
5051 static void
5052 uaudio_mixer_ctl_set(struct uaudio_softc *sc, struct uaudio_mixer_node *mc,
5053     uint8_t chan, int32_t val)
5054 {
5055 	val = uaudio_mixer_bsd2value(mc, val);
5056 
5057 	mc->update[chan / 8] |= (1 << (chan % 8));
5058 	mc->wData[chan] = val;
5059 
5060 	/* start the transfer, if not already started */
5061 
5062 	usbd_transfer_start(sc->sc_mixer_xfer[0]);
5063 }
5064 
5065 static void
5066 uaudio_mixer_init(struct uaudio_softc *sc)
5067 {
5068 	struct uaudio_mixer_node *mc;
5069 	int32_t i;
5070 
5071 	for (mc = sc->sc_mixer_root; mc;
5072 	    mc = mc->next) {
5073 
5074 		if (mc->ctl != SOUND_MIXER_NRDEVICES) {
5075 			/*
5076 			 * Set device mask bits. See
5077 			 * /usr/include/machine/soundcard.h
5078 			 */
5079 			sc->sc_mix_info |= (1 << mc->ctl);
5080 		}
5081 		if ((mc->ctl == SOUND_MIXER_NRDEVICES) &&
5082 		    (mc->type == MIX_SELECTOR)) {
5083 
5084 			for (i = mc->minval; (i > 0) && (i <= mc->maxval); i++) {
5085 				if (mc->slctrtype[i - 1] == SOUND_MIXER_NRDEVICES) {
5086 					continue;
5087 				}
5088 				sc->sc_recsrc_info |= 1 << mc->slctrtype[i - 1];
5089 			}
5090 		}
5091 	}
5092 }
5093 
5094 int
5095 uaudio_mixer_init_sub(struct uaudio_softc *sc, struct snd_mixer *m)
5096 {
5097 	DPRINTF("\n");
5098 
5099 	sc->sc_mixer_lock = mixer_get_lock(m);
5100 	sc->sc_mixer_dev = m;
5101 
5102 	if (usbd_transfer_setup(sc->sc_udev, &sc->sc_mixer_iface_index,
5103 	    sc->sc_mixer_xfer, uaudio_mixer_config, 1, sc,
5104 	    sc->sc_mixer_lock)) {
5105 		DPRINTFN(0, "could not allocate USB "
5106 		    "transfer for audio mixer!\n");
5107 		return (ENOMEM);
5108 	}
5109 	if (!(sc->sc_mix_info & SOUND_MASK_VOLUME)) {
5110 		mix_setparentchild(m, SOUND_MIXER_VOLUME, SOUND_MASK_PCM);
5111 		mix_setrealdev(m, SOUND_MIXER_VOLUME, SOUND_MIXER_NONE);
5112 	}
5113 	mix_setdevs(m, sc->sc_mix_info);
5114 	mix_setrecdevs(m, sc->sc_recsrc_info);
5115 	return (0);
5116 }
5117 
5118 int
5119 uaudio_mixer_uninit_sub(struct uaudio_softc *sc)
5120 {
5121 	DPRINTF("\n");
5122 
5123 	usbd_transfer_unsetup(sc->sc_mixer_xfer, 1);
5124 
5125 	sc->sc_mixer_lock = NULL;
5126 
5127 	return (0);
5128 }
5129 
5130 void
5131 uaudio_mixer_set(struct uaudio_softc *sc, unsigned type,
5132     unsigned left, unsigned right)
5133 {
5134 	struct uaudio_mixer_node *mc;
5135 	int chan;
5136 
5137 	for (mc = sc->sc_mixer_root; mc != NULL; mc = mc->next) {
5138 
5139 		if (mc->ctl == type) {
5140 			for (chan = 0; chan < mc->nchan; chan++) {
5141 				uaudio_mixer_ctl_set(sc, mc, chan,
5142 				    (int)((chan == 0 ? left : right) *
5143 				    255) / 100);
5144 			}
5145 		}
5146 	}
5147 }
5148 
5149 uint32_t
5150 uaudio_mixer_setrecsrc(struct uaudio_softc *sc, uint32_t src)
5151 {
5152 	struct uaudio_mixer_node *mc;
5153 	uint32_t mask;
5154 	uint32_t temp;
5155 	int32_t i;
5156 
5157 	for (mc = sc->sc_mixer_root; mc;
5158 	    mc = mc->next) {
5159 
5160 		if ((mc->ctl == SOUND_MIXER_NRDEVICES) &&
5161 		    (mc->type == MIX_SELECTOR)) {
5162 
5163 			/* compute selector mask */
5164 
5165 			mask = 0;
5166 			for (i = mc->minval; (i > 0) && (i <= mc->maxval); i++) {
5167 				mask |= (1 << mc->slctrtype[i - 1]);
5168 			}
5169 
5170 			temp = mask & src;
5171 			if (temp == 0) {
5172 				continue;
5173 			}
5174 			/* find the first set bit */
5175 			temp = (-temp) & temp;
5176 
5177 			/* update "src" */
5178 			src &= ~mask;
5179 			src |= temp;
5180 
5181 			for (i = mc->minval; (i > 0) && (i <= mc->maxval); i++) {
5182 				if (temp != (1 << mc->slctrtype[i - 1])) {
5183 					continue;
5184 				}
5185 				uaudio_mixer_ctl_set(sc, mc, 0, i);
5186 				break;
5187 			}
5188 		}
5189 	}
5190 	return (src);
5191 }
5192 
5193 /*========================================================================*
5194  * MIDI support routines
5195  *========================================================================*/
5196 
5197 static void
5198 umidi_bulk_read_callback(struct usb_xfer *xfer, usb_error_t error)
5199 {
5200 	struct umidi_chan *chan = usbd_xfer_softc(xfer);
5201 	struct umidi_sub_chan *sub;
5202 	struct usb_page_cache *pc;
5203 	uint8_t buf[4];
5204 	uint8_t cmd_len;
5205 	uint8_t cn;
5206 	uint16_t pos;
5207 	int actlen;
5208 
5209 	usbd_xfer_status(xfer, &actlen, NULL, NULL, NULL);
5210 
5211 	switch (USB_GET_STATE(xfer)) {
5212 	case USB_ST_TRANSFERRED:
5213 
5214 		DPRINTF("actlen=%d bytes\n", actlen);
5215 
5216 		pos = 0;
5217 		pc = usbd_xfer_get_frame(xfer, 0);
5218 
5219 		while (actlen >= 4) {
5220 
5221 			/* copy out the MIDI data */
5222 			usbd_copy_out(pc, pos, buf, 4);
5223 			/* command length */
5224 			cmd_len = umidi_cmd_to_len[buf[0] & 0xF];
5225 			/* cable number */
5226 			cn = buf[0] >> 4;
5227 			/*
5228 			 * Lookup sub-channel. The index is range
5229 			 * checked below.
5230 			 */
5231 			sub = &chan->sub[cn];
5232 
5233 			if ((cmd_len != 0) &&
5234 			    (cn < chan->max_cable) &&
5235 			    (sub->read_open != 0)) {
5236 
5237 				/* Send data to the application */
5238 				usb_fifo_put_data_linear(
5239 				    sub->fifo.fp[USB_FIFO_RX],
5240 				    buf + 1, cmd_len, 1);
5241 			}
5242 			actlen -= 4;
5243 			pos += 4;
5244 		}
5245 
5246 	case USB_ST_SETUP:
5247 		DPRINTF("start\n");
5248 tr_setup:
5249 		usbd_xfer_set_frame_len(xfer, 0, usbd_xfer_max_len(xfer));
5250 		usbd_transfer_submit(xfer);
5251 		break;
5252 
5253 	default:
5254 		DPRINTF("error=%s\n", usbd_errstr(error));
5255 
5256 		if (error != USB_ERR_CANCELLED) {
5257 			/* try to clear stall first */
5258 			usbd_xfer_set_stall(xfer);
5259 			goto tr_setup;
5260 		}
5261 		break;
5262 	}
5263 }
5264 
5265 /*
5266  * The following statemachine, that converts MIDI commands to
5267  * USB MIDI packets, derives from Linux's usbmidi.c, which
5268  * was written by "Clemens Ladisch":
5269  *
5270  * Returns:
5271  *    0: No command
5272  * Else: Command is complete
5273  */
5274 static uint8_t
5275 umidi_convert_to_usb(struct umidi_sub_chan *sub, uint8_t cn, uint8_t b)
5276 {
5277 	uint8_t p0 = (cn << 4);
5278 
5279 	if (b >= 0xf8) {
5280 		sub->temp_0[0] = p0 | 0x0f;
5281 		sub->temp_0[1] = b;
5282 		sub->temp_0[2] = 0;
5283 		sub->temp_0[3] = 0;
5284 		sub->temp_cmd = sub->temp_0;
5285 		return (1);
5286 
5287 	} else if (b >= 0xf0) {
5288 		switch (b) {
5289 		case 0xf0:		/* system exclusive begin */
5290 			sub->temp_1[1] = b;
5291 			sub->state = UMIDI_ST_SYSEX_1;
5292 			break;
5293 		case 0xf1:		/* MIDI time code */
5294 		case 0xf3:		/* song select */
5295 			sub->temp_1[1] = b;
5296 			sub->state = UMIDI_ST_1PARAM;
5297 			break;
5298 		case 0xf2:		/* song position pointer */
5299 			sub->temp_1[1] = b;
5300 			sub->state = UMIDI_ST_2PARAM_1;
5301 			break;
5302 		case 0xf4:		/* unknown */
5303 		case 0xf5:		/* unknown */
5304 			sub->state = UMIDI_ST_UNKNOWN;
5305 			break;
5306 		case 0xf6:		/* tune request */
5307 			sub->temp_1[0] = p0 | 0x05;
5308 			sub->temp_1[1] = 0xf6;
5309 			sub->temp_1[2] = 0;
5310 			sub->temp_1[3] = 0;
5311 			sub->temp_cmd = sub->temp_1;
5312 			sub->state = UMIDI_ST_UNKNOWN;
5313 			return (1);
5314 
5315 		case 0xf7:		/* system exclusive end */
5316 			switch (sub->state) {
5317 			case UMIDI_ST_SYSEX_0:
5318 				sub->temp_1[0] = p0 | 0x05;
5319 				sub->temp_1[1] = 0xf7;
5320 				sub->temp_1[2] = 0;
5321 				sub->temp_1[3] = 0;
5322 				sub->temp_cmd = sub->temp_1;
5323 				sub->state = UMIDI_ST_UNKNOWN;
5324 				return (1);
5325 			case UMIDI_ST_SYSEX_1:
5326 				sub->temp_1[0] = p0 | 0x06;
5327 				sub->temp_1[2] = 0xf7;
5328 				sub->temp_1[3] = 0;
5329 				sub->temp_cmd = sub->temp_1;
5330 				sub->state = UMIDI_ST_UNKNOWN;
5331 				return (1);
5332 			case UMIDI_ST_SYSEX_2:
5333 				sub->temp_1[0] = p0 | 0x07;
5334 				sub->temp_1[3] = 0xf7;
5335 				sub->temp_cmd = sub->temp_1;
5336 				sub->state = UMIDI_ST_UNKNOWN;
5337 				return (1);
5338 			}
5339 			sub->state = UMIDI_ST_UNKNOWN;
5340 			break;
5341 		}
5342 	} else if (b >= 0x80) {
5343 		sub->temp_1[1] = b;
5344 		if ((b >= 0xc0) && (b <= 0xdf)) {
5345 			sub->state = UMIDI_ST_1PARAM;
5346 		} else {
5347 			sub->state = UMIDI_ST_2PARAM_1;
5348 		}
5349 	} else {			/* b < 0x80 */
5350 		switch (sub->state) {
5351 		case UMIDI_ST_1PARAM:
5352 			if (sub->temp_1[1] < 0xf0) {
5353 				p0 |= sub->temp_1[1] >> 4;
5354 			} else {
5355 				p0 |= 0x02;
5356 				sub->state = UMIDI_ST_UNKNOWN;
5357 			}
5358 			sub->temp_1[0] = p0;
5359 			sub->temp_1[2] = b;
5360 			sub->temp_1[3] = 0;
5361 			sub->temp_cmd = sub->temp_1;
5362 			return (1);
5363 		case UMIDI_ST_2PARAM_1:
5364 			sub->temp_1[2] = b;
5365 			sub->state = UMIDI_ST_2PARAM_2;
5366 			break;
5367 		case UMIDI_ST_2PARAM_2:
5368 			if (sub->temp_1[1] < 0xf0) {
5369 				p0 |= sub->temp_1[1] >> 4;
5370 				sub->state = UMIDI_ST_2PARAM_1;
5371 			} else {
5372 				p0 |= 0x03;
5373 				sub->state = UMIDI_ST_UNKNOWN;
5374 			}
5375 			sub->temp_1[0] = p0;
5376 			sub->temp_1[3] = b;
5377 			sub->temp_cmd = sub->temp_1;
5378 			return (1);
5379 		case UMIDI_ST_SYSEX_0:
5380 			sub->temp_1[1] = b;
5381 			sub->state = UMIDI_ST_SYSEX_1;
5382 			break;
5383 		case UMIDI_ST_SYSEX_1:
5384 			sub->temp_1[2] = b;
5385 			sub->state = UMIDI_ST_SYSEX_2;
5386 			break;
5387 		case UMIDI_ST_SYSEX_2:
5388 			sub->temp_1[0] = p0 | 0x04;
5389 			sub->temp_1[3] = b;
5390 			sub->temp_cmd = sub->temp_1;
5391 			sub->state = UMIDI_ST_SYSEX_0;
5392 			return (1);
5393 		default:
5394 			break;
5395 		}
5396 	}
5397 	return (0);
5398 }
5399 
5400 static void
5401 umidi_bulk_write_callback(struct usb_xfer *xfer, usb_error_t error)
5402 {
5403 	struct umidi_chan *chan = usbd_xfer_softc(xfer);
5404 	struct umidi_sub_chan *sub;
5405 	struct usb_page_cache *pc;
5406 	uint32_t actlen;
5407 	uint16_t nframes;
5408 	uint8_t buf;
5409 	uint8_t start_cable;
5410 	uint8_t tr_any;
5411 	int len;
5412 
5413 	usbd_xfer_status(xfer, &len, NULL, NULL, NULL);
5414 
5415 	/*
5416 	 * NOTE: Some MIDI devices only accept 4 bytes of data per
5417 	 * short terminated USB transfer.
5418 	 */
5419 	switch (USB_GET_STATE(xfer)) {
5420 	case USB_ST_TRANSFERRED:
5421 		DPRINTF("actlen=%d bytes\n", len);
5422 
5423 	case USB_ST_SETUP:
5424 tr_setup:
5425 		DPRINTF("start\n");
5426 
5427 		nframes = 0;	/* reset */
5428 		start_cable = chan->curr_cable;
5429 		tr_any = 0;
5430 		pc = usbd_xfer_get_frame(xfer, 0);
5431 
5432 		while (1) {
5433 
5434 			/* round robin de-queueing */
5435 
5436 			sub = &chan->sub[chan->curr_cable];
5437 
5438 			if (sub->write_open) {
5439 				usb_fifo_get_data_linear(sub->fifo.fp[USB_FIFO_TX],
5440 				    &buf, 1, &actlen, 0);
5441 			} else {
5442 				actlen = 0;
5443 			}
5444 
5445 			if (actlen) {
5446 
5447 				tr_any = 1;
5448 
5449 				DPRINTF("byte=0x%02x from FIFO %u\n", buf,
5450 				    (unsigned int)chan->curr_cable);
5451 
5452 				if (umidi_convert_to_usb(sub, chan->curr_cable, buf)) {
5453 
5454 					DPRINTF("sub=0x%02x 0x%02x 0x%02x 0x%02x\n",
5455 					    sub->temp_cmd[0], sub->temp_cmd[1],
5456 					    sub->temp_cmd[2], sub->temp_cmd[3]);
5457 
5458 					usbd_copy_in(pc, nframes * 4, sub->temp_cmd, 4);
5459 
5460 					nframes++;
5461 
5462 					if ((nframes >= UMIDI_TX_FRAMES) || (chan->single_command != 0))
5463 						break;
5464 				} else {
5465 					continue;
5466 				}
5467 			}
5468 
5469 			chan->curr_cable++;
5470 			if (chan->curr_cable >= chan->max_cable)
5471 				chan->curr_cable = 0;
5472 
5473 			if (chan->curr_cable == start_cable) {
5474 				if (tr_any == 0)
5475 					break;
5476 				tr_any = 0;
5477 			}
5478 		}
5479 
5480 		if (nframes != 0) {
5481 			DPRINTF("Transferring %d frames\n", (int)nframes);
5482 			usbd_xfer_set_frame_len(xfer, 0, 4 * nframes);
5483 			usbd_transfer_submit(xfer);
5484 		}
5485 		break;
5486 
5487 	default:			/* Error */
5488 
5489 		DPRINTF("error=%s\n", usbd_errstr(error));
5490 
5491 		if (error != USB_ERR_CANCELLED) {
5492 			/* try to clear stall first */
5493 			usbd_xfer_set_stall(xfer);
5494 			goto tr_setup;
5495 		}
5496 		break;
5497 	}
5498 }
5499 
5500 static struct umidi_sub_chan *
5501 umidi_sub_by_fifo(struct usb_fifo *fifo)
5502 {
5503 	struct umidi_chan *chan = usb_fifo_softc(fifo);
5504 	struct umidi_sub_chan *sub;
5505 	uint32_t n;
5506 
5507 	for (n = 0; n < UMIDI_CABLES_MAX; n++) {
5508 		sub = &chan->sub[n];
5509 		if ((sub->fifo.fp[USB_FIFO_RX] == fifo) ||
5510 		    (sub->fifo.fp[USB_FIFO_TX] == fifo)) {
5511 			return (sub);
5512 		}
5513 	}
5514 
5515 	panic("%s:%d cannot find usb_fifo!\n",
5516 	    __FILE__, __LINE__);
5517 
5518 	return (NULL);
5519 }
5520 
5521 static void
5522 umidi_start_read(struct usb_fifo *fifo)
5523 {
5524 	struct umidi_chan *chan = usb_fifo_softc(fifo);
5525 
5526 	usbd_transfer_start(chan->xfer[UMIDI_RX_TRANSFER]);
5527 }
5528 
5529 static void
5530 umidi_stop_read(struct usb_fifo *fifo)
5531 {
5532 	struct umidi_chan *chan = usb_fifo_softc(fifo);
5533 	struct umidi_sub_chan *sub = umidi_sub_by_fifo(fifo);
5534 
5535 	DPRINTF("\n");
5536 
5537 	sub->read_open = 0;
5538 
5539 	if (--(chan->read_open_refcount) == 0) {
5540 		/*
5541 		 * XXX don't stop the read transfer here, hence that causes
5542 		 * problems with some MIDI adapters
5543 		 */
5544 		DPRINTF("(stopping read transfer)\n");
5545 	}
5546 }
5547 
5548 static void
5549 umidi_start_write(struct usb_fifo *fifo)
5550 {
5551 	struct umidi_chan *chan = usb_fifo_softc(fifo);
5552 
5553 	usbd_transfer_start(chan->xfer[UMIDI_TX_TRANSFER]);
5554 }
5555 
5556 static void
5557 umidi_stop_write(struct usb_fifo *fifo)
5558 {
5559 	struct umidi_chan *chan = usb_fifo_softc(fifo);
5560 	struct umidi_sub_chan *sub = umidi_sub_by_fifo(fifo);
5561 
5562 	DPRINTF("\n");
5563 
5564 	sub->write_open = 0;
5565 
5566 	if (--(chan->write_open_refcount) == 0) {
5567 		DPRINTF("(stopping write transfer)\n");
5568 		usbd_transfer_stop(chan->xfer[UMIDI_TX_TRANSFER]);
5569 	}
5570 }
5571 
5572 static int
5573 umidi_open(struct usb_fifo *fifo, int fflags)
5574 {
5575 	struct umidi_chan *chan = usb_fifo_softc(fifo);
5576 	struct umidi_sub_chan *sub = umidi_sub_by_fifo(fifo);
5577 
5578 	if (fflags & FREAD) {
5579 		if (usb_fifo_alloc_buffer(fifo, 4, (1024 / 4))) {
5580 			return (ENOMEM);
5581 		}
5582 		mtx_lock(&chan->mtx);
5583 		chan->read_open_refcount++;
5584 		sub->read_open = 1;
5585 		mtx_unlock(&chan->mtx);
5586 	}
5587 	if (fflags & FWRITE) {
5588 		if (usb_fifo_alloc_buffer(fifo, 32, (1024 / 32))) {
5589 			return (ENOMEM);
5590 		}
5591 		/* clear stall first */
5592 		mtx_lock(&chan->mtx);
5593 		chan->write_open_refcount++;
5594 		sub->write_open = 1;
5595 
5596 		/* reset */
5597 		sub->state = UMIDI_ST_UNKNOWN;
5598 		mtx_unlock(&chan->mtx);
5599 	}
5600 	return (0);			/* success */
5601 }
5602 
5603 static void
5604 umidi_close(struct usb_fifo *fifo, int fflags)
5605 {
5606 	if (fflags & FREAD) {
5607 		usb_fifo_free_buffer(fifo);
5608 	}
5609 	if (fflags & FWRITE) {
5610 		usb_fifo_free_buffer(fifo);
5611 	}
5612 }
5613 
5614 
5615 static int
5616 umidi_ioctl(struct usb_fifo *fifo, u_long cmd, void *data,
5617     int fflags)
5618 {
5619 	return (ENODEV);
5620 }
5621 
5622 static void
5623 umidi_init(device_t dev)
5624 {
5625 	struct uaudio_softc *sc = device_get_softc(dev);
5626 	struct umidi_chan *chan = &sc->sc_midi_chan;
5627 
5628 	mtx_init(&chan->mtx, "umidi lock", NULL, MTX_DEF | MTX_RECURSE);
5629 }
5630 
5631 static struct usb_fifo_methods umidi_fifo_methods = {
5632 	.f_start_read = &umidi_start_read,
5633 	.f_start_write = &umidi_start_write,
5634 	.f_stop_read = &umidi_stop_read,
5635 	.f_stop_write = &umidi_stop_write,
5636 	.f_open = &umidi_open,
5637 	.f_close = &umidi_close,
5638 	.f_ioctl = &umidi_ioctl,
5639 	.basename[0] = "umidi",
5640 };
5641 
5642 static int
5643 umidi_probe(device_t dev)
5644 {
5645 	struct uaudio_softc *sc = device_get_softc(dev);
5646 	struct usb_attach_arg *uaa = device_get_ivars(dev);
5647 	struct umidi_chan *chan = &sc->sc_midi_chan;
5648 	struct umidi_sub_chan *sub;
5649 	int unit = device_get_unit(dev);
5650 	int error;
5651 	uint32_t n;
5652 
5653 	if (usb_test_quirk(uaa, UQ_SINGLE_CMD_MIDI))
5654 		chan->single_command = 1;
5655 
5656 	if (usbd_set_alt_interface_index(sc->sc_udev, chan->iface_index,
5657 	    chan->iface_alt_index)) {
5658 		DPRINTF("setting of alternate index failed!\n");
5659 		goto detach;
5660 	}
5661 	usbd_set_parent_iface(sc->sc_udev, chan->iface_index,
5662 	    sc->sc_mixer_iface_index);
5663 
5664 	error = usbd_transfer_setup(uaa->device, &chan->iface_index,
5665 	    chan->xfer, umidi_config, UMIDI_N_TRANSFER,
5666 	    chan, &chan->mtx);
5667 	if (error) {
5668 		DPRINTF("error=%s\n", usbd_errstr(error));
5669 		goto detach;
5670 	}
5671 
5672 	/*
5673 	 * Some USB MIDI device makers couldn't resist using
5674 	 * wMaxPacketSize = 4 for RX and TX BULK endpoints, although
5675 	 * that size is an unsupported value for FULL speed BULK
5676 	 * endpoints. The same applies to some HIGH speed MIDI devices
5677 	 * which are using a wMaxPacketSize different from 512 bytes.
5678 	 *
5679 	 * Refer to section 5.8.3 in USB 2.0 PDF: Cite: "All Host
5680 	 * Controllers are required to have support for 8-, 16-, 32-,
5681 	 * and 64-byte maximum packet sizes for full-speed bulk
5682 	 * endpoints and 512 bytes for high-speed bulk endpoints."
5683 	 */
5684 	if (usbd_xfer_maxp_was_clamped(chan->xfer[UMIDI_TX_TRANSFER]))
5685 		chan->single_command = 1;
5686 
5687 	if (chan->single_command != 0)
5688 		device_printf(dev, "Single command MIDI quirk enabled\n");
5689 
5690 	if ((chan->max_cable > UMIDI_CABLES_MAX) ||
5691 	    (chan->max_cable == 0)) {
5692 		chan->max_cable = UMIDI_CABLES_MAX;
5693 	}
5694 
5695 	for (n = 0; n < chan->max_cable; n++) {
5696 
5697 		sub = &chan->sub[n];
5698 
5699 		error = usb_fifo_attach(sc->sc_udev, chan, &chan->mtx,
5700 		    &umidi_fifo_methods, &sub->fifo, unit, n,
5701 		    chan->iface_index,
5702 		    UID_ROOT, GID_OPERATOR, 0644);
5703 		if (error) {
5704 			goto detach;
5705 		}
5706 	}
5707 
5708 	mtx_lock(&chan->mtx);
5709 
5710 	/*
5711 	 * NOTE: At least one device will not work properly unless the
5712 	 * BULK IN pipe is open all the time. This might have to do
5713 	 * about that the internal queues of the device overflow if we
5714 	 * don't read them regularly.
5715 	 */
5716 	usbd_transfer_start(chan->xfer[UMIDI_RX_TRANSFER]);
5717 
5718 	mtx_unlock(&chan->mtx);
5719 
5720 	return (0);			/* success */
5721 
5722 detach:
5723 	return (ENXIO);			/* failure */
5724 }
5725 
5726 static int
5727 umidi_detach(device_t dev)
5728 {
5729 	struct uaudio_softc *sc = device_get_softc(dev);
5730 	struct umidi_chan *chan = &sc->sc_midi_chan;
5731 	uint32_t n;
5732 
5733 	for (n = 0; n < UMIDI_CABLES_MAX; n++) {
5734 		usb_fifo_detach(&chan->sub[n].fifo);
5735 	}
5736 
5737 	mtx_lock(&chan->mtx);
5738 
5739 	usbd_transfer_stop(chan->xfer[UMIDI_RX_TRANSFER]);
5740 
5741 	mtx_unlock(&chan->mtx);
5742 
5743 	usbd_transfer_unsetup(chan->xfer, UMIDI_N_TRANSFER);
5744 
5745 	mtx_destroy(&chan->mtx);
5746 
5747 	return (0);
5748 }
5749 
5750 static void
5751 uaudio_hid_rx_callback(struct usb_xfer *xfer, usb_error_t error)
5752 {
5753 	struct uaudio_softc *sc = usbd_xfer_softc(xfer);
5754 	const uint8_t *buffer = usbd_xfer_get_frame_buffer(xfer, 0);
5755 	struct snd_mixer *m;
5756 	uint8_t id;
5757 	int actlen;
5758 
5759 	usbd_xfer_status(xfer, &actlen, NULL, NULL, NULL);
5760 
5761 	switch (USB_GET_STATE(xfer)) {
5762 	case USB_ST_TRANSFERRED:
5763 		DPRINTF("actlen=%d\n", actlen);
5764 
5765 		if (actlen != 0 &&
5766 		    (sc->sc_hid.flags & UAUDIO_HID_HAS_ID)) {
5767 			id = *buffer;
5768 			buffer++;
5769 			actlen--;
5770 		} else {
5771 			id = 0;
5772 		}
5773 
5774 		m = sc->sc_mixer_dev;
5775 
5776 		if ((sc->sc_hid.flags & UAUDIO_HID_HAS_MUTE) &&
5777 		    (sc->sc_hid.mute_id == id) &&
5778 		    hid_get_data(buffer, actlen,
5779 		    &sc->sc_hid.mute_loc)) {
5780 
5781 			DPRINTF("Mute toggle\n");
5782 
5783 			mixer_hwvol_mute_locked(m);
5784 		}
5785 
5786 		if ((sc->sc_hid.flags & UAUDIO_HID_HAS_VOLUME_UP) &&
5787 		    (sc->sc_hid.volume_up_id == id) &&
5788 		    hid_get_data(buffer, actlen,
5789 		    &sc->sc_hid.volume_up_loc)) {
5790 
5791 			DPRINTF("Volume Up\n");
5792 
5793 			mixer_hwvol_step_locked(m, 1, 1);
5794 		}
5795 
5796 		if ((sc->sc_hid.flags & UAUDIO_HID_HAS_VOLUME_DOWN) &&
5797 		    (sc->sc_hid.volume_down_id == id) &&
5798 		    hid_get_data(buffer, actlen,
5799 		    &sc->sc_hid.volume_down_loc)) {
5800 
5801 			DPRINTF("Volume Down\n");
5802 
5803 			mixer_hwvol_step_locked(m, -1, -1);
5804 		}
5805 
5806 	case USB_ST_SETUP:
5807 tr_setup:
5808 		/* check if we can put more data into the FIFO */
5809 		usbd_xfer_set_frame_len(xfer, 0, usbd_xfer_max_len(xfer));
5810 		usbd_transfer_submit(xfer);
5811 		break;
5812 
5813 	default:			/* Error */
5814 
5815 		DPRINTF("error=%s\n", usbd_errstr(error));
5816 
5817 		if (error != USB_ERR_CANCELLED) {
5818 			/* try to clear stall first */
5819 			usbd_xfer_set_stall(xfer);
5820 			goto tr_setup;
5821 		}
5822 		break;
5823 	}
5824 }
5825 
5826 static int
5827 uaudio_hid_probe(struct uaudio_softc *sc,
5828     struct usb_attach_arg *uaa)
5829 {
5830 	void *d_ptr;
5831 	uint32_t flags;
5832 	uint16_t d_len;
5833 	uint8_t id;
5834 	int error;
5835 
5836 	if (!(sc->sc_hid.flags & UAUDIO_HID_VALID))
5837 		return (-1);
5838 
5839 	if (sc->sc_mixer_lock == NULL)
5840 		return (-1);
5841 
5842 	/* Get HID descriptor */
5843 	error = usbd_req_get_hid_desc(uaa->device, NULL, &d_ptr,
5844 	    &d_len, M_TEMP, sc->sc_hid.iface_index);
5845 
5846 	if (error) {
5847 		DPRINTF("error reading report description\n");
5848 		return (-1);
5849 	}
5850 
5851 	/* check if there is an ID byte */
5852 	hid_report_size(d_ptr, d_len, hid_input, &id);
5853 
5854 	if (id != 0)
5855 		sc->sc_hid.flags |= UAUDIO_HID_HAS_ID;
5856 
5857 	if (hid_locate(d_ptr, d_len,
5858 	    HID_USAGE2(HUP_CONSUMER, 0xE9 /* Volume Increment */),
5859 	    hid_input, 0, &sc->sc_hid.volume_up_loc, &flags,
5860 	    &sc->sc_hid.volume_up_id)) {
5861 		if (flags & HIO_VARIABLE)
5862 			sc->sc_hid.flags |= UAUDIO_HID_HAS_VOLUME_UP;
5863 		DPRINTFN(1, "Found Volume Up key\n");
5864 	}
5865 
5866 	if (hid_locate(d_ptr, d_len,
5867 	    HID_USAGE2(HUP_CONSUMER, 0xEA /* Volume Decrement */),
5868 	    hid_input, 0, &sc->sc_hid.volume_down_loc, &flags,
5869 	    &sc->sc_hid.volume_down_id)) {
5870 		if (flags & HIO_VARIABLE)
5871 			sc->sc_hid.flags |= UAUDIO_HID_HAS_VOLUME_DOWN;
5872 		DPRINTFN(1, "Found Volume Down key\n");
5873 	}
5874 
5875 	if (hid_locate(d_ptr, d_len,
5876 	    HID_USAGE2(HUP_CONSUMER, 0xE2 /* Mute */),
5877 	    hid_input, 0, &sc->sc_hid.mute_loc, &flags,
5878 	    &sc->sc_hid.mute_id)) {
5879 		if (flags & HIO_VARIABLE)
5880 			sc->sc_hid.flags |= UAUDIO_HID_HAS_MUTE;
5881 		DPRINTFN(1, "Found Mute key\n");
5882 	}
5883 
5884 	free(d_ptr, M_TEMP);
5885 
5886 	if (!(sc->sc_hid.flags & (UAUDIO_HID_HAS_VOLUME_UP |
5887 	    UAUDIO_HID_HAS_VOLUME_DOWN |
5888 	    UAUDIO_HID_HAS_MUTE))) {
5889 		DPRINTFN(1, "Did not find any volume related keys\n");
5890 		return (-1);
5891 	}
5892 
5893 	/* prevent the uhid driver from attaching */
5894 	usbd_set_parent_iface(uaa->device, sc->sc_hid.iface_index,
5895 	    sc->sc_mixer_iface_index);
5896 
5897 	/* allocate USB transfers */
5898 	error = usbd_transfer_setup(uaa->device, &sc->sc_hid.iface_index,
5899 	    sc->sc_hid.xfer, uaudio_hid_config, UAUDIO_HID_N_TRANSFER,
5900 	    sc, sc->sc_mixer_lock);
5901 	if (error) {
5902 		DPRINTF("error=%s\n", usbd_errstr(error));
5903 		return (-1);
5904 	}
5905 	return (0);
5906 }
5907 
5908 static void
5909 uaudio_hid_detach(struct uaudio_softc *sc)
5910 {
5911 	usbd_transfer_unsetup(sc->sc_hid.xfer, UAUDIO_HID_N_TRANSFER);
5912 }
5913 
5914 DRIVER_MODULE_ORDERED(uaudio, uhub, uaudio_driver, uaudio_devclass, NULL, 0, SI_ORDER_ANY);
5915 MODULE_DEPEND(uaudio, usb, 1, 1, 1);
5916 MODULE_DEPEND(uaudio, sound, SOUND_MINVER, SOUND_PREFVER, SOUND_MAXVER);
5917 MODULE_VERSION(uaudio, 1);
5918