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