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