xref: /freebsd/sys/dev/sound/usb/uaudio.c (revision 69718b786d3943ea9a99eeeb5f5f6162f11c78b7)
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 			int32_t jitter_max = howmany(sample_rate, 16000);
2083 
2084 			/*
2085 			 * Range check the jitter values to avoid
2086 			 * bogus sample rate adjustments. The expected
2087 			 * deviation should not be more than 1Hz per
2088 			 * second. The USB v2.0 specification also
2089 			 * mandates this requirement. Refer to chapter
2090 			 * 5.12.4.2 about feedback.
2091 			 */
2092 			ch->jitter_curr = temp - sample_rate;
2093 			if (ch->jitter_curr > jitter_max)
2094 				ch->jitter_curr = jitter_max;
2095 			else if (ch->jitter_curr < -jitter_max)
2096 				ch->jitter_curr = -jitter_max;
2097 		}
2098 		ch->feedback_rate = temp;
2099 		break;
2100 
2101 	case USB_ST_SETUP:
2102 		usbd_xfer_set_frames(xfer, 1);
2103 		usbd_xfer_set_frame_len(xfer, 0, usbd_xfer_max_framelen(xfer));
2104 		usbd_transfer_submit(xfer);
2105 		break;
2106 
2107 	default:			/* Error */
2108 		break;
2109 	}
2110 }
2111 
2112 static int
2113 uaudio_chan_is_async(struct uaudio_chan *ch, uint8_t alt)
2114 {
2115 	uint8_t attr = ch->usb_alt[alt].p_ed1->bmAttributes;
2116 	return (UE_GET_ISO_TYPE(attr) == UE_ISO_ASYNC);
2117 }
2118 
2119 static void
2120 uaudio_chan_play_callback(struct usb_xfer *xfer, usb_error_t error)
2121 {
2122 	struct uaudio_chan *ch = usbd_xfer_softc(xfer);
2123 	struct uaudio_chan *ch_rec;
2124 	struct usb_page_cache *pc;
2125 	uint32_t mfl;
2126 	uint32_t total;
2127 	uint32_t blockcount;
2128 	uint32_t n;
2129 	uint32_t offset;
2130 	int sample_size;
2131 	int actlen;
2132 	int sumlen;
2133 
2134 	if (ch->running == 0 || ch->start == ch->end) {
2135 		DPRINTF("not running or no buffer!\n");
2136 		return;
2137 	}
2138 
2139 	/* check if there is a record channel */
2140 	if (ch->priv_sc->sc_rec_chan.num_alt > 0)
2141 		ch_rec = &ch->priv_sc->sc_rec_chan;
2142 	else
2143 		ch_rec = NULL;
2144 
2145 	usbd_xfer_status(xfer, &actlen, &sumlen, NULL, NULL);
2146 
2147 	switch (USB_GET_STATE(xfer)) {
2148 	case USB_ST_SETUP:
2149 tr_setup:
2150 		if (ch_rec != NULL) {
2151 			/* reset receive jitter counters */
2152 			mtx_lock(ch_rec->pcm_mtx);
2153 			ch_rec->jitter_curr = 0;
2154 			ch_rec->jitter_rem = 0;
2155 			mtx_unlock(ch_rec->pcm_mtx);
2156 		}
2157 
2158 		/* reset transmit jitter counters */
2159 		ch->jitter_curr = 0;
2160 		ch->jitter_rem = 0;
2161 
2162 		/* FALLTHROUGH */
2163 	case USB_ST_TRANSFERRED:
2164 		if (actlen < sumlen) {
2165 			DPRINTF("short transfer, "
2166 			    "%d of %d bytes\n", actlen, sumlen);
2167 		}
2168 		chn_intr(ch->pcm_ch);
2169 
2170 		/*
2171 		 * Check for asynchronous playback endpoint and that
2172 		 * the playback endpoint is properly configured:
2173 		 */
2174 		if (ch_rec != NULL &&
2175 		    uaudio_chan_is_async(ch, ch->cur_alt) != 0) {
2176 			mtx_lock(ch_rec->pcm_mtx);
2177 			if (ch_rec->cur_alt < ch_rec->num_alt) {
2178 				int64_t tx_jitter;
2179 				int64_t rx_rate;
2180 
2181 				/* translate receive jitter into transmit jitter */
2182 				tx_jitter = ch->usb_alt[ch->cur_alt].sample_rate;
2183 				tx_jitter = (tx_jitter * ch_rec->jitter_curr) +
2184 				    ch->jitter_rem;
2185 
2186 				/* reset receive jitter counters */
2187 				ch_rec->jitter_curr = 0;
2188 				ch_rec->jitter_rem = 0;
2189 
2190 				/* compute exact number of transmit jitter samples */
2191 				rx_rate = ch_rec->usb_alt[ch_rec->cur_alt].sample_rate;
2192 				ch->jitter_curr += tx_jitter / rx_rate;
2193 				ch->jitter_rem = tx_jitter % rx_rate;
2194 			}
2195 			mtx_unlock(ch_rec->pcm_mtx);
2196 		}
2197 
2198 		/* start the SYNC transfer one time per second, if any */
2199 		ch->intr_counter += ch->intr_frames;
2200 		if (ch->intr_counter >= ch->frames_per_second) {
2201 			ch->intr_counter -= ch->frames_per_second;
2202 			usbd_transfer_start(ch->xfer[UAUDIO_NCHANBUFS]);
2203 		}
2204 
2205 		mfl = usbd_xfer_max_framelen(xfer);
2206 
2207 		if (ch->bytes_per_frame[1] > mfl) {
2208 			DPRINTF("bytes per transfer, %d, "
2209 			    "exceeds maximum, %d!\n",
2210 			    ch->bytes_per_frame[1],
2211 			    mfl);
2212 			break;
2213 		}
2214 
2215 		blockcount = ch->intr_frames;
2216 
2217 		/* setup number of frames */
2218 		usbd_xfer_set_frames(xfer, blockcount);
2219 
2220 		/* get sample size */
2221 		sample_size = ch->usb_alt[ch->cur_alt].sample_size;
2222 
2223 		/* reset total length */
2224 		total = 0;
2225 
2226 		/* setup frame lengths */
2227 		for (n = 0; n != blockcount; n++) {
2228 			uint32_t frame_len;
2229 
2230 			ch->sample_curr += ch->sample_rem;
2231 			if (ch->sample_curr >= ch->frames_per_second) {
2232 				ch->sample_curr -= ch->frames_per_second;
2233 				frame_len = ch->bytes_per_frame[1];
2234 			} else {
2235 				frame_len = ch->bytes_per_frame[0];
2236 			}
2237 
2238 			/* handle free running clock case */
2239 			if (ch->jitter_curr > 0 &&
2240 			    (frame_len + sample_size) <= mfl) {
2241 				DPRINTFN(6, "sending one sample more\n");
2242 				ch->jitter_curr--;
2243 				frame_len += sample_size;
2244 			} else if (ch->jitter_curr < 0 &&
2245 			    frame_len >= sample_size) {
2246 				DPRINTFN(6, "sending one sample less\n");
2247 				ch->jitter_curr++;
2248 				frame_len -= sample_size;
2249 			}
2250 			usbd_xfer_set_frame_len(xfer, n, frame_len);
2251 			total += frame_len;
2252 		}
2253 
2254 		DPRINTFN(6, "transferring %d bytes\n", total);
2255 
2256 		offset = 0;
2257 
2258 		pc = usbd_xfer_get_frame(xfer, 0);
2259 		while (total > 0) {
2260 
2261 			n = (ch->end - ch->cur);
2262 			if (n > total)
2263 				n = total;
2264 
2265 			usbd_copy_in(pc, offset, ch->cur, n);
2266 
2267 			total -= n;
2268 			ch->cur += n;
2269 			offset += n;
2270 
2271 			if (ch->cur >= ch->end)
2272 				ch->cur = ch->start;
2273 		}
2274 		usbd_transfer_submit(xfer);
2275 		break;
2276 
2277 	default:			/* Error */
2278 		if (error != USB_ERR_CANCELLED)
2279 			goto tr_setup;
2280 		break;
2281 	}
2282 }
2283 
2284 static void
2285 uaudio_chan_record_sync_callback(struct usb_xfer *xfer, usb_error_t error)
2286 {
2287 	/* TODO */
2288 }
2289 
2290 static void
2291 uaudio_chan_record_callback(struct usb_xfer *xfer, usb_error_t error)
2292 {
2293 	struct uaudio_chan *ch = usbd_xfer_softc(xfer);
2294 	struct usb_page_cache *pc;
2295 	uint32_t offset0;
2296 	uint32_t mfl;
2297 	int m;
2298 	int n;
2299 	int len;
2300 	int actlen;
2301 	int nframes;
2302 	int expected_bytes;
2303 	int sample_size;
2304 
2305 	if (ch->start == ch->end) {
2306 		DPRINTF("no buffer!\n");
2307 		return;
2308 	}
2309 
2310 	usbd_xfer_status(xfer, &actlen, NULL, NULL, &nframes);
2311 	mfl = usbd_xfer_max_framelen(xfer);
2312 
2313 	switch (USB_GET_STATE(xfer)) {
2314 	case USB_ST_TRANSFERRED:
2315 
2316 		offset0 = 0;
2317 		pc = usbd_xfer_get_frame(xfer, 0);
2318 
2319 		/* try to compute the number of expected bytes */
2320 		ch->sample_curr += (ch->sample_rem * ch->intr_frames);
2321 
2322 		/* compute number of expected bytes */
2323 		expected_bytes = (ch->intr_frames * ch->bytes_per_frame[0]) +
2324 		    ((ch->sample_curr / ch->frames_per_second) *
2325 		    (ch->bytes_per_frame[1] - ch->bytes_per_frame[0]));
2326 
2327 		/* keep remainder */
2328 		ch->sample_curr %= ch->frames_per_second;
2329 
2330 		/* get current sample size */
2331 		sample_size = ch->usb_alt[ch->cur_alt].sample_size;
2332 
2333 		for (n = 0; n != nframes; n++) {
2334 			uint32_t offset1 = offset0;
2335 
2336 			len = usbd_xfer_frame_len(xfer, n);
2337 
2338 			/* make sure we only receive complete samples */
2339 			len = len - (len % sample_size);
2340 
2341 			/* subtract bytes received from expected payload */
2342 			expected_bytes -= len;
2343 
2344 			/* don't receive data when not ready */
2345 			if (ch->running == 0 || ch->cur_alt != ch->set_alt)
2346 				continue;
2347 
2348 			/* fill ring buffer with samples, if any */
2349 			while (len > 0) {
2350 
2351 				m = (ch->end - ch->cur);
2352 
2353 				if (m > len)
2354 					m = len;
2355 
2356 				usbd_copy_out(pc, offset1, ch->cur, m);
2357 
2358 				len -= m;
2359 				offset1 += m;
2360 				ch->cur += m;
2361 
2362 				if (ch->cur >= ch->end)
2363 					ch->cur = ch->start;
2364 			}
2365 
2366 			offset0 += mfl;
2367 		}
2368 
2369 		/* update current jitter */
2370 		ch->jitter_curr -= (expected_bytes / sample_size);
2371 
2372 		/* don't allow a huge amount of jitter to accumulate */
2373 		nframes = 2 * ch->intr_frames;
2374 
2375 		/* range check current jitter */
2376 		if (ch->jitter_curr < -nframes)
2377 			ch->jitter_curr = -nframes;
2378 		else if (ch->jitter_curr > nframes)
2379 			ch->jitter_curr = nframes;
2380 
2381 		DPRINTFN(6, "transferred %d bytes, jitter %d samples\n",
2382 		    actlen, ch->jitter_curr);
2383 
2384 		if (ch->running != 0)
2385 			chn_intr(ch->pcm_ch);
2386 
2387 	case USB_ST_SETUP:
2388 tr_setup:
2389 		nframes = ch->intr_frames;
2390 
2391 		usbd_xfer_set_frames(xfer, nframes);
2392 		for (n = 0; n != nframes; n++)
2393 			usbd_xfer_set_frame_len(xfer, n, mfl);
2394 
2395 		usbd_transfer_submit(xfer);
2396 		break;
2397 
2398 	default:			/* Error */
2399 		if (error != USB_ERR_CANCELLED)
2400 			goto tr_setup;
2401 		break;
2402 	}
2403 }
2404 
2405 void   *
2406 uaudio_chan_init(struct uaudio_softc *sc, struct snd_dbuf *b,
2407     struct pcm_channel *c, int dir)
2408 {
2409 	struct uaudio_chan *ch = ((dir == PCMDIR_PLAY) ?
2410 	    &sc->sc_play_chan : &sc->sc_rec_chan);
2411 	uint32_t buf_size;
2412 	uint8_t x;
2413 
2414 	/* store mutex and PCM channel */
2415 
2416 	ch->pcm_ch = c;
2417 	ch->pcm_mtx = c->lock;
2418 
2419 	/* compute worst case buffer */
2420 
2421 	buf_size = 0;
2422 	for (x = 0; x != ch->num_alt; x++) {
2423 		uint32_t temp = uaudio_get_buffer_size(ch, x);
2424 		if (temp > buf_size)
2425 			buf_size = temp;
2426 	}
2427 
2428 	/* allow double buffering */
2429 	buf_size *= 2;
2430 
2431 	DPRINTF("Worst case buffer is %d bytes\n", (int)buf_size);
2432 
2433 	ch->buf = malloc(buf_size, M_DEVBUF, M_WAITOK | M_ZERO);
2434 	if (ch->buf == NULL)
2435 		goto error;
2436 	if (sndbuf_setup(b, ch->buf, buf_size) != 0)
2437 		goto error;
2438 
2439 	ch->start = ch->buf;
2440 	ch->end = ch->buf + buf_size;
2441 	ch->cur = ch->buf;
2442 	ch->pcm_buf = b;
2443 	ch->max_buf = buf_size;
2444 
2445 	if (ch->pcm_mtx == NULL) {
2446 		DPRINTF("ERROR: PCM channels does not have a mutex!\n");
2447 		goto error;
2448 	}
2449 	return (ch);
2450 
2451 error:
2452 	uaudio_chan_free(ch);
2453 	return (NULL);
2454 }
2455 
2456 int
2457 uaudio_chan_free(struct uaudio_chan *ch)
2458 {
2459 	if (ch->buf != NULL) {
2460 		free(ch->buf, M_DEVBUF);
2461 		ch->buf = NULL;
2462 	}
2463 	usbd_transfer_unsetup(ch->xfer, UAUDIO_NCHANBUFS + 1);
2464 
2465 	ch->num_alt = 0;
2466 
2467 	return (0);
2468 }
2469 
2470 int
2471 uaudio_chan_set_param_blocksize(struct uaudio_chan *ch, uint32_t blocksize)
2472 {
2473 	uint32_t temp = 2 * uaudio_get_buffer_size(ch, ch->set_alt);
2474 	sndbuf_setup(ch->pcm_buf, ch->buf, temp);
2475 	return (temp / 2);
2476 }
2477 
2478 int
2479 uaudio_chan_set_param_fragments(struct uaudio_chan *ch, uint32_t blocksize,
2480     uint32_t blockcount)
2481 {
2482 	return (1);
2483 }
2484 
2485 int
2486 uaudio_chan_set_param_speed(struct uaudio_chan *ch, uint32_t speed)
2487 {
2488 	struct uaudio_softc *sc;
2489 	uint8_t x;
2490 
2491 	sc = ch->priv_sc;
2492 
2493 	for (x = 0; x < ch->num_alt; x++) {
2494 		if (ch->usb_alt[x].sample_rate < speed) {
2495 			/* sample rate is too low */
2496 			break;
2497 		}
2498 	}
2499 
2500 	if (x != 0)
2501 		x--;
2502 
2503 	usb_proc_explore_lock(sc->sc_udev);
2504 	ch->set_alt = x;
2505 	usb_proc_explore_unlock(sc->sc_udev);
2506 
2507 	DPRINTF("Selecting alt %d\n", (int)x);
2508 
2509 	return (ch->usb_alt[x].sample_rate);
2510 }
2511 
2512 int
2513 uaudio_chan_getptr(struct uaudio_chan *ch)
2514 {
2515 	return (ch->cur - ch->start);
2516 }
2517 
2518 struct pcmchan_caps *
2519 uaudio_chan_getcaps(struct uaudio_chan *ch)
2520 {
2521 	return (&ch->pcm_cap);
2522 }
2523 
2524 static struct pcmchan_matrix uaudio_chan_matrix_swap_2_0 = {
2525 	.id = SND_CHN_MATRIX_DRV,
2526 	.channels = 2,
2527 	.ext = 0,
2528 	.map = {
2529 		/* Right */
2530 		[0] = {
2531 			.type = SND_CHN_T_FR,
2532 			.members =
2533 			    SND_CHN_T_MASK_FR | SND_CHN_T_MASK_FC |
2534 			    SND_CHN_T_MASK_LF | SND_CHN_T_MASK_BR |
2535 			    SND_CHN_T_MASK_BC | SND_CHN_T_MASK_SR
2536 		},
2537 		/* Left */
2538 		[1] = {
2539 			.type = SND_CHN_T_FL,
2540 			.members =
2541 			    SND_CHN_T_MASK_FL | SND_CHN_T_MASK_FC |
2542 			    SND_CHN_T_MASK_LF | SND_CHN_T_MASK_BL |
2543 			    SND_CHN_T_MASK_BC | SND_CHN_T_MASK_SL
2544 		},
2545 		[2] = {
2546 			.type = SND_CHN_T_MAX,
2547 			.members = 0
2548 		}
2549 	},
2550 	.mask = SND_CHN_T_MASK_FR | SND_CHN_T_MASK_FL,
2551 	.offset = {  1,  0, -1, -1, -1, -1, -1, -1, -1,
2552 		    -1, -1, -1, -1, -1, -1, -1, -1, -1  }
2553 };
2554 
2555 struct pcmchan_matrix *
2556 uaudio_chan_getmatrix(struct uaudio_chan *ch, uint32_t format)
2557 {
2558 	struct uaudio_softc *sc;
2559 
2560 	sc = ch->priv_sc;
2561 
2562 	if (sc != NULL && sc->sc_uq_audio_swap_lr != 0 &&
2563 	    AFMT_CHANNEL(format) == 2)
2564 		return (&uaudio_chan_matrix_swap_2_0);
2565 
2566 	return (feeder_matrix_format_map(format));
2567 }
2568 
2569 int
2570 uaudio_chan_set_param_format(struct uaudio_chan *ch, uint32_t format)
2571 {
2572 	DPRINTF("Selecting format 0x%08x\n", (unsigned int)format);
2573 	return (0);
2574 }
2575 
2576 static void
2577 uaudio_chan_start_sub(struct uaudio_chan *ch)
2578 {
2579 	struct uaudio_softc *sc = ch->priv_sc;
2580 	int do_start = 0;
2581 
2582 	if (ch->operation != CHAN_OP_DRAIN) {
2583 		if (ch->cur_alt == ch->set_alt &&
2584 		    ch->operation == CHAN_OP_NONE &&
2585 		    mtx_owned(ch->pcm_mtx) != 0) {
2586 			/* save doing the explore task */
2587 			do_start = 1;
2588 		} else {
2589 			ch->operation = CHAN_OP_START;
2590 			(void)usb_proc_explore_msignal(sc->sc_udev,
2591 			    &sc->sc_config_msg[0], &sc->sc_config_msg[1]);
2592 		}
2593 	}
2594 	if (do_start) {
2595 		usbd_transfer_start(ch->xfer[0]);
2596 		usbd_transfer_start(ch->xfer[1]);
2597 	}
2598 }
2599 
2600 static int
2601 uaudio_chan_need_both(struct uaudio_softc *sc)
2602 {
2603 	return (sc->sc_play_chan.num_alt > 0 &&
2604 	    sc->sc_play_chan.running != 0 &&
2605 	    uaudio_chan_is_async(&sc->sc_play_chan,
2606 	    sc->sc_play_chan.set_alt) != 0 &&
2607 	    sc->sc_rec_chan.num_alt > 0 &&
2608 	    sc->sc_rec_chan.running == 0);
2609 }
2610 
2611 static int
2612 uaudio_chan_need_none(struct uaudio_softc *sc)
2613 {
2614 	return (sc->sc_play_chan.num_alt > 0 &&
2615 	    sc->sc_play_chan.running == 0 &&
2616 	    sc->sc_rec_chan.num_alt > 0 &&
2617 	    sc->sc_rec_chan.running == 0);
2618 }
2619 
2620 void
2621 uaudio_chan_start(struct uaudio_chan *ch)
2622 {
2623 	struct uaudio_softc *sc = ch->priv_sc;
2624 
2625 	/* make operation atomic */
2626 	usb_proc_explore_lock(sc->sc_udev);
2627 
2628 	/* check if not running */
2629 	if (ch->running == 0) {
2630 	  	uint32_t temp;
2631 
2632 		/* get current buffer size */
2633 		temp = 2 * uaudio_get_buffer_size(ch, ch->set_alt);
2634 
2635 		/* set running flag */
2636 		ch->running = 1;
2637 
2638 		/* ensure the hardware buffer is reset */
2639 		ch->start = ch->buf;
2640 		ch->end = ch->buf + temp;
2641 		ch->cur = ch->buf;
2642 
2643 		if (uaudio_chan_need_both(sc)) {
2644 			/*
2645 			 * Start both endpoints because of need for
2646 			 * jitter information:
2647 			 */
2648 			uaudio_chan_start_sub(&sc->sc_rec_chan);
2649 			uaudio_chan_start_sub(&sc->sc_play_chan);
2650 		} else {
2651 			uaudio_chan_start_sub(ch);
2652 		}
2653 	}
2654 
2655 	/* exit atomic operation */
2656 	usb_proc_explore_unlock(sc->sc_udev);
2657 }
2658 
2659 static void
2660 uaudio_chan_stop_sub(struct uaudio_chan *ch)
2661 {
2662 	struct uaudio_softc *sc = ch->priv_sc;
2663 	int do_stop = 0;
2664 
2665 	if (ch->operation != CHAN_OP_DRAIN) {
2666 		if (ch->cur_alt == ch->set_alt &&
2667 		    ch->operation == CHAN_OP_NONE &&
2668 		    mtx_owned(ch->pcm_mtx) != 0) {
2669 			/* save doing the explore task */
2670 			do_stop = 1;
2671 		} else {
2672 			ch->operation = CHAN_OP_STOP;
2673 			(void)usb_proc_explore_msignal(sc->sc_udev,
2674 			    &sc->sc_config_msg[0], &sc->sc_config_msg[1]);
2675 		}
2676 	}
2677 	if (do_stop) {
2678 		usbd_transfer_stop(ch->xfer[0]);
2679 		usbd_transfer_stop(ch->xfer[1]);
2680 	}
2681 }
2682 
2683 void
2684 uaudio_chan_stop(struct uaudio_chan *ch)
2685 {
2686 	struct uaudio_softc *sc = ch->priv_sc;
2687 
2688 	/* make operation atomic */
2689 	usb_proc_explore_lock(sc->sc_udev);
2690 
2691 	/* check if running */
2692 	if (ch->running != 0) {
2693 		/* clear running flag */
2694 		ch->running = 0;
2695 
2696 		if (uaudio_chan_need_both(sc)) {
2697 			/*
2698 			 * Leave the endpoints running because we need
2699 			 * information about jitter!
2700 			 */
2701 		} else if (uaudio_chan_need_none(sc)) {
2702 			/*
2703 			 * Stop both endpoints in case the one was used for
2704 			 * jitter information:
2705 			 */
2706 			uaudio_chan_stop_sub(&sc->sc_rec_chan);
2707 			uaudio_chan_stop_sub(&sc->sc_play_chan);
2708 		} else {
2709 			uaudio_chan_stop_sub(ch);
2710 		}
2711 	}
2712 
2713 	/* exit atomic operation */
2714 	usb_proc_explore_unlock(sc->sc_udev);
2715 }
2716 
2717 /*========================================================================*
2718  * AC - Audio Controller - routines
2719  *========================================================================*/
2720 
2721 static int
2722 uaudio_mixer_sysctl_handler(SYSCTL_HANDLER_ARGS)
2723 {
2724 	struct uaudio_softc *sc;
2725 	struct uaudio_mixer_node *pmc;
2726 	int hint;
2727 	int error;
2728 	int temp = 0;
2729 	int chan = 0;
2730 
2731 	sc = (struct uaudio_softc *)oidp->oid_arg1;
2732 	hint = oidp->oid_arg2;
2733 
2734 	if (sc->sc_mixer_lock == NULL)
2735 		return (ENXIO);
2736 
2737 	/* lookup mixer node */
2738 
2739 	mtx_lock(sc->sc_mixer_lock);
2740 	for (pmc = sc->sc_mixer_root; pmc != NULL; pmc = pmc->next) {
2741 		for (chan = 0; chan != (int)pmc->nchan; chan++) {
2742 			if (pmc->wValue[chan] != -1 &&
2743 			    pmc->wValue[chan] == hint) {
2744 				temp = pmc->wData[chan];
2745 				goto found;
2746 			}
2747 		}
2748 	}
2749 found:
2750 	mtx_unlock(sc->sc_mixer_lock);
2751 
2752 	error = sysctl_handle_int(oidp, &temp, 0, req);
2753 	if (error != 0 || req->newptr == NULL)
2754 		return (error);
2755 
2756 	/* update mixer value */
2757 
2758 	mtx_lock(sc->sc_mixer_lock);
2759 	if (pmc != NULL &&
2760 	    temp >= pmc->minval &&
2761 	    temp <= pmc->maxval) {
2762 
2763 		pmc->wData[chan] = temp;
2764 		pmc->update[(chan / 8)] |= (1 << (chan % 8));
2765 
2766 		/* start the transfer, if not already started */
2767 		usbd_transfer_start(sc->sc_mixer_xfer[0]);
2768 	}
2769 	mtx_unlock(sc->sc_mixer_lock);
2770 
2771 	return (0);
2772 }
2773 
2774 static void
2775 uaudio_mixer_ctl_free(struct uaudio_softc *sc)
2776 {
2777 	struct uaudio_mixer_node *p_mc;
2778 
2779 	while ((p_mc = sc->sc_mixer_root) != NULL) {
2780 		sc->sc_mixer_root = p_mc->next;
2781 		free(p_mc, M_USBDEV);
2782 	}
2783 }
2784 
2785 static void
2786 uaudio_mixer_register_sysctl(struct uaudio_softc *sc, device_t dev)
2787 {
2788 	struct uaudio_mixer_node *pmc;
2789 	struct sysctl_oid *mixer_tree;
2790 	struct sysctl_oid *control_tree;
2791 	char buf[32];
2792 	int chan;
2793 	int n;
2794 
2795 	mixer_tree = SYSCTL_ADD_NODE(device_get_sysctl_ctx(dev),
2796 	    SYSCTL_CHILDREN(device_get_sysctl_tree(dev)), OID_AUTO, "mixer",
2797 	    CTLFLAG_RD, NULL, "");
2798 
2799 	if (mixer_tree == NULL)
2800 		return;
2801 
2802 	for (n = 0, pmc = sc->sc_mixer_root; pmc != NULL;
2803 	    pmc = pmc->next, n++) {
2804 
2805 		for (chan = 0; chan < pmc->nchan; chan++) {
2806 
2807 			if (pmc->nchan > 1) {
2808 				snprintf(buf, sizeof(buf), "%s_%d_%d",
2809 				    pmc->name, n, chan);
2810 			} else {
2811 				snprintf(buf, sizeof(buf), "%s_%d",
2812 				    pmc->name, n);
2813 			}
2814 
2815 			control_tree = SYSCTL_ADD_NODE(device_get_sysctl_ctx(dev),
2816 			    SYSCTL_CHILDREN(mixer_tree), OID_AUTO, buf,
2817 			    CTLFLAG_RD, NULL, "Mixer control nodes");
2818 
2819 			if (control_tree == NULL)
2820 				continue;
2821 
2822 			SYSCTL_ADD_PROC(device_get_sysctl_ctx(dev),
2823 			    SYSCTL_CHILDREN(control_tree),
2824 			    OID_AUTO, "val", CTLTYPE_INT | CTLFLAG_RWTUN, sc,
2825 			    pmc->wValue[chan],
2826 			    uaudio_mixer_sysctl_handler, "I", "Current value");
2827 
2828 			SYSCTL_ADD_INT(device_get_sysctl_ctx(dev),
2829 			    SYSCTL_CHILDREN(control_tree),
2830 			    OID_AUTO, "min", CTLFLAG_RD, 0, pmc->minval,
2831 			    "Minimum value");
2832 
2833 			SYSCTL_ADD_INT(device_get_sysctl_ctx(dev),
2834 			    SYSCTL_CHILDREN(control_tree),
2835 			    OID_AUTO, "max", CTLFLAG_RD, 0, pmc->maxval,
2836 			    "Maximum value");
2837 
2838 			SYSCTL_ADD_STRING(device_get_sysctl_ctx(dev),
2839 			    SYSCTL_CHILDREN(control_tree),
2840 			    OID_AUTO, "desc", CTLFLAG_RD, pmc->desc, 0,
2841 			    "Description");
2842 		}
2843 	}
2844 }
2845 
2846 /* M-Audio FastTrack Ultra Mixer Description */
2847 /* Origin: Linux USB Audio driver */
2848 static void
2849 uaudio_mixer_controls_create_ftu(struct uaudio_softc *sc)
2850 {
2851 	int chx;
2852 	int chy;
2853 
2854 	memset(&MIX(sc), 0, sizeof(MIX(sc)));
2855 	MIX(sc).wIndex = MAKE_WORD(6, sc->sc_mixer_iface_no);
2856 	MIX(sc).wValue[0] = MAKE_WORD(8, 0);
2857 	MIX(sc).class = UAC_OUTPUT;
2858 	MIX(sc).type = MIX_UNSIGNED_16;
2859 	MIX(sc).ctl = SOUND_MIXER_NRDEVICES;
2860 	MIX(sc).name = "effect";
2861 	MIX(sc).minval = 0;
2862 	MIX(sc).maxval = 7;
2863 	MIX(sc).mul = 7;
2864 	MIX(sc).nchan = 1;
2865 	MIX(sc).update[0] = 1;
2866 	strlcpy(MIX(sc).desc, "Room1,2,3,Hall1,2,Plate,Delay,Echo", sizeof(MIX(sc).desc));
2867 	uaudio_mixer_add_ctl_sub(sc, &MIX(sc));
2868 
2869 	memset(&MIX(sc), 0, sizeof(MIX(sc)));
2870 	MIX(sc).wIndex = MAKE_WORD(5, sc->sc_mixer_iface_no);
2871 
2872 	for (chx = 0; chx != 8; chx++) {
2873 		for (chy = 0; chy != 8; chy++) {
2874 
2875 			MIX(sc).wValue[0] = MAKE_WORD(chx + 1, chy + 1);
2876 			MIX(sc).type = MIX_SIGNED_16;
2877 			MIX(sc).ctl = SOUND_MIXER_NRDEVICES;
2878 			MIX(sc).name = "mix_rec";
2879 			MIX(sc).nchan = 1;
2880 			MIX(sc).update[0] = 1;
2881 			MIX(sc).val_default = 0;
2882 			snprintf(MIX(sc).desc, sizeof(MIX(sc).desc),
2883 			    "AIn%d - Out%d Record Volume", chy + 1, chx + 1);
2884 
2885 			uaudio_mixer_add_ctl(sc, &MIX(sc));
2886 
2887 			MIX(sc).wValue[0] = MAKE_WORD(chx + 1, chy + 1 + 8);
2888 			MIX(sc).type = MIX_SIGNED_16;
2889 			MIX(sc).ctl = SOUND_MIXER_NRDEVICES;
2890 			MIX(sc).name = "mix_play";
2891 			MIX(sc).nchan = 1;
2892 			MIX(sc).update[0] = 1;
2893 			MIX(sc).val_default = (chx == chy) ? 2 : 0;
2894 			snprintf(MIX(sc).desc, sizeof(MIX(sc).desc),
2895 			    "DIn%d - Out%d Playback Volume", chy + 1, chx + 1);
2896 
2897 			uaudio_mixer_add_ctl(sc, &MIX(sc));
2898 		}
2899 	}
2900 
2901 	memset(&MIX(sc), 0, sizeof(MIX(sc)));
2902 	MIX(sc).wIndex = MAKE_WORD(6, sc->sc_mixer_iface_no);
2903 	MIX(sc).wValue[0] = MAKE_WORD(2, 0);
2904 	MIX(sc).class = UAC_OUTPUT;
2905 	MIX(sc).type = MIX_SIGNED_8;
2906 	MIX(sc).ctl = SOUND_MIXER_NRDEVICES;
2907 	MIX(sc).name = "effect_vol";
2908 	MIX(sc).nchan = 1;
2909 	MIX(sc).update[0] = 1;
2910 	MIX(sc).minval = 0;
2911 	MIX(sc).maxval = 0x7f;
2912 	MIX(sc).mul = 0x7f;
2913 	MIX(sc).nchan = 1;
2914 	MIX(sc).update[0] = 1;
2915 	strlcpy(MIX(sc).desc, "Effect Volume", sizeof(MIX(sc).desc));
2916 	uaudio_mixer_add_ctl_sub(sc, &MIX(sc));
2917 
2918 	memset(&MIX(sc), 0, sizeof(MIX(sc)));
2919 	MIX(sc).wIndex = MAKE_WORD(6, sc->sc_mixer_iface_no);
2920 	MIX(sc).wValue[0] = MAKE_WORD(3, 0);
2921 	MIX(sc).class = UAC_OUTPUT;
2922 	MIX(sc).type = MIX_SIGNED_16;
2923 	MIX(sc).ctl = SOUND_MIXER_NRDEVICES;
2924 	MIX(sc).name = "effect_dur";
2925 	MIX(sc).nchan = 1;
2926 	MIX(sc).update[0] = 1;
2927 	MIX(sc).minval = 0;
2928 	MIX(sc).maxval = 0x7f00;
2929 	MIX(sc).mul = 0x7f00;
2930 	MIX(sc).nchan = 1;
2931 	MIX(sc).update[0] = 1;
2932 	strlcpy(MIX(sc).desc, "Effect Duration", sizeof(MIX(sc).desc));
2933 	uaudio_mixer_add_ctl_sub(sc, &MIX(sc));
2934 
2935 	memset(&MIX(sc), 0, sizeof(MIX(sc)));
2936 	MIX(sc).wIndex = MAKE_WORD(6, sc->sc_mixer_iface_no);
2937 	MIX(sc).wValue[0] = MAKE_WORD(4, 0);
2938 	MIX(sc).class = UAC_OUTPUT;
2939 	MIX(sc).type = MIX_SIGNED_8;
2940 	MIX(sc).ctl = SOUND_MIXER_NRDEVICES;
2941 	MIX(sc).name = "effect_fb";
2942 	MIX(sc).nchan = 1;
2943 	MIX(sc).update[0] = 1;
2944 	MIX(sc).minval = 0;
2945 	MIX(sc).maxval = 0x7f;
2946 	MIX(sc).mul = 0x7f;
2947 	MIX(sc).nchan = 1;
2948 	MIX(sc).update[0] = 1;
2949 	strlcpy(MIX(sc).desc, "Effect Feedback Volume", sizeof(MIX(sc).desc));
2950 	uaudio_mixer_add_ctl_sub(sc, &MIX(sc));
2951 
2952 	memset(&MIX(sc), 0, sizeof(MIX(sc)));
2953 	MIX(sc).wIndex = MAKE_WORD(7, sc->sc_mixer_iface_no);
2954 	for (chy = 0; chy != 4; chy++) {
2955 
2956 		MIX(sc).wValue[0] = MAKE_WORD(7, chy + 1);
2957 		MIX(sc).type = MIX_SIGNED_16;
2958 		MIX(sc).ctl = SOUND_MIXER_NRDEVICES;
2959 		MIX(sc).name = "effect_ret";
2960 		MIX(sc).nchan = 1;
2961 		MIX(sc).update[0] = 1;
2962 		snprintf(MIX(sc).desc, sizeof(MIX(sc).desc),
2963 		    "Effect Return %d Volume", chy + 1);
2964 
2965 		uaudio_mixer_add_ctl(sc, &MIX(sc));
2966 	}
2967 
2968 	memset(&MIX(sc), 0, sizeof(MIX(sc)));
2969 	MIX(sc).wIndex = MAKE_WORD(5, sc->sc_mixer_iface_no);
2970 
2971 	for (chy = 0; chy != 8; chy++) {
2972 		MIX(sc).wValue[0] = MAKE_WORD(9, chy + 1);
2973 		MIX(sc).type = MIX_SIGNED_16;
2974 		MIX(sc).ctl = SOUND_MIXER_NRDEVICES;
2975 		MIX(sc).name = "effect_send";
2976 		MIX(sc).nchan = 1;
2977 		MIX(sc).update[0] = 1;
2978 		snprintf(MIX(sc).desc, sizeof(MIX(sc).desc),
2979 		    "Effect Send AIn%d Volume", chy + 1);
2980 
2981 		uaudio_mixer_add_ctl(sc, &MIX(sc));
2982 
2983 		MIX(sc).wValue[0] = MAKE_WORD(9, chy + 1 + 8);
2984 		MIX(sc).type = MIX_SIGNED_16;
2985 		MIX(sc).ctl = SOUND_MIXER_NRDEVICES;
2986 		MIX(sc).name = "effect_send";
2987 		MIX(sc).nchan = 1;
2988 		MIX(sc).update[0] = 1;
2989 		snprintf(MIX(sc).desc, sizeof(MIX(sc).desc),
2990 		    "Effect Send DIn%d Volume", chy + 1);
2991 
2992 		uaudio_mixer_add_ctl(sc, &MIX(sc));
2993 	}
2994 }
2995 
2996 static void
2997 uaudio_mixer_reload_all(struct uaudio_softc *sc)
2998 {
2999 	struct uaudio_mixer_node *pmc;
3000 	int chan;
3001 
3002 	if (sc->sc_mixer_lock == NULL)
3003 		return;
3004 
3005 	mtx_lock(sc->sc_mixer_lock);
3006 	for (pmc = sc->sc_mixer_root; pmc != NULL; pmc = pmc->next) {
3007 		/* use reset defaults for non-oss controlled settings */
3008 		if (pmc->ctl == SOUND_MIXER_NRDEVICES)
3009 			continue;
3010 		for (chan = 0; chan < pmc->nchan; chan++)
3011 			pmc->update[chan / 8] |= (1 << (chan % 8));
3012 	}
3013 	usbd_transfer_start(sc->sc_mixer_xfer[0]);
3014 
3015 	/* start HID volume keys, if any */
3016 	usbd_transfer_start(sc->sc_hid.xfer[0]);
3017 	mtx_unlock(sc->sc_mixer_lock);
3018 }
3019 
3020 static void
3021 uaudio_mixer_add_ctl_sub(struct uaudio_softc *sc, struct uaudio_mixer_node *mc)
3022 {
3023 	struct uaudio_mixer_node *p_mc_new =
3024 	    malloc(sizeof(*p_mc_new), M_USBDEV, M_WAITOK);
3025 	int ch;
3026 
3027 	if (p_mc_new != NULL) {
3028 		memcpy(p_mc_new, mc, sizeof(*p_mc_new));
3029 		p_mc_new->next = sc->sc_mixer_root;
3030 		sc->sc_mixer_root = p_mc_new;
3031 		sc->sc_mixer_count++;
3032 
3033 		/* set default value for all channels */
3034 		for (ch = 0; ch < p_mc_new->nchan; ch++) {
3035 			switch (p_mc_new->val_default) {
3036 			case 1:
3037 				/* 50% */
3038 				p_mc_new->wData[ch] = (p_mc_new->maxval + p_mc_new->minval) / 2;
3039 				break;
3040 			case 2:
3041 				/* 100% */
3042 				p_mc_new->wData[ch] = p_mc_new->maxval;
3043 				break;
3044 			default:
3045 				/* 0% */
3046 				p_mc_new->wData[ch] = p_mc_new->minval;
3047 				break;
3048 			}
3049 		}
3050 	} else {
3051 		DPRINTF("out of memory\n");
3052 	}
3053 }
3054 
3055 static void
3056 uaudio_mixer_add_ctl(struct uaudio_softc *sc, struct uaudio_mixer_node *mc)
3057 {
3058 	int32_t res;
3059 
3060 	if (mc->class < UAC_NCLASSES) {
3061 		DPRINTF("adding %s.%d\n",
3062 		    uac_names[mc->class], mc->ctl);
3063 	} else {
3064 		DPRINTF("adding %d\n", mc->ctl);
3065 	}
3066 
3067 	if (mc->type == MIX_ON_OFF) {
3068 		mc->minval = 0;
3069 		mc->maxval = 1;
3070 	} else if (mc->type == MIX_SELECTOR) {
3071 	} else {
3072 
3073 		/* determine min and max values */
3074 
3075 		mc->minval = uaudio_mixer_get(sc->sc_udev,
3076 		    sc->sc_audio_rev, GET_MIN, mc);
3077 		mc->maxval = uaudio_mixer_get(sc->sc_udev,
3078 		    sc->sc_audio_rev, GET_MAX, mc);
3079 
3080 		/* check if max and min was swapped */
3081 
3082 		if (mc->maxval < mc->minval) {
3083 			res = mc->maxval;
3084 			mc->maxval = mc->minval;
3085 			mc->minval = res;
3086 		}
3087 
3088 		/* compute value range */
3089 		mc->mul = mc->maxval - mc->minval;
3090 		if (mc->mul == 0)
3091 			mc->mul = 1;
3092 
3093 		/* compute value alignment */
3094 		res = uaudio_mixer_get(sc->sc_udev,
3095 		    sc->sc_audio_rev, GET_RES, mc);
3096 
3097 		DPRINTF("Resolution = %d\n", (int)res);
3098 	}
3099 
3100 	uaudio_mixer_add_ctl_sub(sc, mc);
3101 
3102 #ifdef USB_DEBUG
3103 	if (uaudio_debug > 2) {
3104 		uint8_t i;
3105 
3106 		for (i = 0; i < mc->nchan; i++) {
3107 			DPRINTF("[mix] wValue=%04x\n", mc->wValue[0]);
3108 		}
3109 		DPRINTF("[mix] wIndex=%04x type=%d ctl='%d' "
3110 		    "min=%d max=%d\n",
3111 		    mc->wIndex, mc->type, mc->ctl,
3112 		    mc->minval, mc->maxval);
3113 	}
3114 #endif
3115 }
3116 
3117 static void
3118 uaudio_mixer_add_mixer(struct uaudio_softc *sc,
3119     const struct uaudio_terminal_node *iot, int id)
3120 {
3121 	const struct usb_audio_mixer_unit_0 *d0 = iot[id].u.mu_v1;
3122 	const struct usb_audio_mixer_unit_1 *d1;
3123 
3124 	uint32_t bno;			/* bit number */
3125 	uint32_t p;			/* bit number accumulator */
3126 	uint32_t mo;			/* matching outputs */
3127 	uint32_t mc;			/* matching channels */
3128 	uint32_t ichs;			/* input channels */
3129 	uint32_t ochs;			/* output channels */
3130 	uint32_t c;
3131 	uint32_t chs;			/* channels */
3132 	uint32_t i;
3133 	uint32_t o;
3134 
3135 	DPRINTFN(3, "bUnitId=%d bNrInPins=%d\n",
3136 	    d0->bUnitId, d0->bNrInPins);
3137 
3138 	/* compute the number of input channels */
3139 
3140 	ichs = 0;
3141 	for (i = 0; i < d0->bNrInPins; i++) {
3142 		ichs += uaudio_mixer_get_cluster(
3143 		    d0->baSourceId[i], iot).bNrChannels;
3144 	}
3145 
3146 	d1 = (const void *)(d0->baSourceId + d0->bNrInPins);
3147 
3148 	/* and the number of output channels */
3149 
3150 	ochs = d1->bNrChannels;
3151 
3152 	DPRINTFN(3, "ichs=%d ochs=%d\n", ichs, ochs);
3153 
3154 	memset(&MIX(sc), 0, sizeof(MIX(sc)));
3155 
3156 	MIX(sc).wIndex = MAKE_WORD(d0->bUnitId, sc->sc_mixer_iface_no);
3157 	uaudio_mixer_determine_class(&iot[id], &MIX(sc));
3158 	MIX(sc).type = MIX_SIGNED_16;
3159 
3160 	if (uaudio_mixer_verify_desc(d0, ((ichs * ochs) + 7) / 8) == NULL)
3161 		return;
3162 
3163 	for (p = i = 0; i < d0->bNrInPins; i++) {
3164 		chs = uaudio_mixer_get_cluster(
3165 		    d0->baSourceId[i], iot).bNrChannels;
3166 		mc = 0;
3167 		for (c = 0; c < chs; c++) {
3168 			mo = 0;
3169 			for (o = 0; o < ochs; o++) {
3170 				bno = ((p + c) * ochs) + o;
3171 				if (BIT_TEST(d1->bmControls, bno))
3172 					mo++;
3173 			}
3174 			if (mo == 1)
3175 				mc++;
3176 		}
3177 		if ((mc == chs) && (chs <= MIX_MAX_CHAN)) {
3178 
3179 			/* repeat bit-scan */
3180 
3181 			mc = 0;
3182 			for (c = 0; c < chs; c++) {
3183 				for (o = 0; o < ochs; o++) {
3184 					bno = ((p + c) * ochs) + o;
3185 					if (BIT_TEST(d1->bmControls, bno))
3186 						MIX(sc).wValue[mc++] = MAKE_WORD(p + c + 1, o + 1);
3187 				}
3188 			}
3189 			MIX(sc).nchan = chs;
3190 			uaudio_mixer_add_ctl(sc, &MIX(sc));
3191 		}
3192 		p += chs;
3193 	}
3194 }
3195 
3196 static void
3197 uaudio20_mixer_add_mixer(struct uaudio_softc *sc,
3198     const struct uaudio_terminal_node *iot, int id)
3199 {
3200 	const struct usb_audio20_mixer_unit_0 *d0 = iot[id].u.mu_v2;
3201 	const struct usb_audio20_mixer_unit_1 *d1;
3202 
3203 	uint32_t bno;			/* bit number */
3204 	uint32_t p;			/* bit number accumulator */
3205 	uint32_t mo;			/* matching outputs */
3206 	uint32_t mc;			/* matching channels */
3207 	uint32_t ichs;			/* input channels */
3208 	uint32_t ochs;			/* output channels */
3209 	uint32_t c;
3210 	uint32_t chs;			/* channels */
3211 	uint32_t i;
3212 	uint32_t o;
3213 
3214 	DPRINTFN(3, "bUnitId=%d bNrInPins=%d\n",
3215 	    d0->bUnitId, d0->bNrInPins);
3216 
3217 	/* compute the number of input channels */
3218 
3219 	ichs = 0;
3220 	for (i = 0; i < d0->bNrInPins; i++) {
3221 		ichs += uaudio20_mixer_get_cluster(
3222 		    d0->baSourceId[i], iot).bNrChannels;
3223 	}
3224 
3225 	d1 = (const void *)(d0->baSourceId + d0->bNrInPins);
3226 
3227 	/* and the number of output channels */
3228 
3229 	ochs = d1->bNrChannels;
3230 
3231 	DPRINTFN(3, "ichs=%d ochs=%d\n", ichs, ochs);
3232 
3233 	memset(&MIX(sc), 0, sizeof(MIX(sc)));
3234 
3235 	MIX(sc).wIndex = MAKE_WORD(d0->bUnitId, sc->sc_mixer_iface_no);
3236 	uaudio20_mixer_determine_class(&iot[id], &MIX(sc));
3237 	MIX(sc).type = MIX_SIGNED_16;
3238 
3239 	if (uaudio20_mixer_verify_desc(d0, ((ichs * ochs) + 7) / 8) == NULL)
3240 		return;
3241 
3242 	for (p = i = 0; i < d0->bNrInPins; i++) {
3243 		chs = uaudio20_mixer_get_cluster(
3244 		    d0->baSourceId[i], iot).bNrChannels;
3245 		mc = 0;
3246 		for (c = 0; c < chs; c++) {
3247 			mo = 0;
3248 			for (o = 0; o < ochs; o++) {
3249 				bno = ((p + c) * ochs) + o;
3250 				if (BIT_TEST(d1->bmControls, bno))
3251 					mo++;
3252 			}
3253 			if (mo == 1)
3254 				mc++;
3255 		}
3256 		if ((mc == chs) && (chs <= MIX_MAX_CHAN)) {
3257 
3258 			/* repeat bit-scan */
3259 
3260 			mc = 0;
3261 			for (c = 0; c < chs; c++) {
3262 				for (o = 0; o < ochs; o++) {
3263 					bno = ((p + c) * ochs) + o;
3264 					if (BIT_TEST(d1->bmControls, bno))
3265 						MIX(sc).wValue[mc++] = MAKE_WORD(p + c + 1, o + 1);
3266 				}
3267 			}
3268 			MIX(sc).nchan = chs;
3269 			uaudio_mixer_add_ctl(sc, &MIX(sc));
3270 		}
3271 		p += chs;
3272 	}
3273 }
3274 
3275 static void
3276 uaudio_mixer_add_selector(struct uaudio_softc *sc,
3277     const struct uaudio_terminal_node *iot, int id)
3278 {
3279 	const struct usb_audio_selector_unit *d = iot[id].u.su_v1;
3280 	uint16_t i;
3281 
3282 	DPRINTFN(3, "bUnitId=%d bNrInPins=%d\n",
3283 	    d->bUnitId, d->bNrInPins);
3284 
3285 	if (d->bNrInPins == 0)
3286 		return;
3287 
3288 	memset(&MIX(sc), 0, sizeof(MIX(sc)));
3289 
3290 	MIX(sc).wIndex = MAKE_WORD(d->bUnitId, sc->sc_mixer_iface_no);
3291 	MIX(sc).wValue[0] = MAKE_WORD(0, 0);
3292 	uaudio_mixer_determine_class(&iot[id], &MIX(sc));
3293 	MIX(sc).nchan = 1;
3294 	MIX(sc).type = MIX_SELECTOR;
3295 	MIX(sc).ctl = SOUND_MIXER_NRDEVICES;
3296 	MIX(sc).minval = 1;
3297 	MIX(sc).maxval = d->bNrInPins;
3298 	MIX(sc).name = "selector";
3299 
3300 	i = d->baSourceId[d->bNrInPins];
3301 	if (i == 0 ||
3302 	    usbd_req_get_string_any(sc->sc_udev, NULL,
3303 	    MIX(sc).desc, sizeof(MIX(sc).desc), i) != 0) {
3304 		MIX(sc).desc[0] = 0;
3305 	}
3306 
3307 	if (MIX(sc).maxval > MAX_SELECTOR_INPUT_PIN) {
3308 		MIX(sc).maxval = MAX_SELECTOR_INPUT_PIN;
3309 	}
3310 	MIX(sc).mul = (MIX(sc).maxval - MIX(sc).minval);
3311 	for (i = 0; i < MAX_SELECTOR_INPUT_PIN; i++) {
3312 		MIX(sc).slctrtype[i] = SOUND_MIXER_NRDEVICES;
3313 	}
3314 
3315 	for (i = 0; i < MIX(sc).maxval; i++) {
3316 		MIX(sc).slctrtype[i] = uaudio_mixer_feature_name(
3317 		    &iot[d->baSourceId[i]], &MIX(sc));
3318 	}
3319 
3320 	MIX(sc).class = 0;			/* not used */
3321 
3322 	uaudio_mixer_add_ctl(sc, &MIX(sc));
3323 }
3324 
3325 static void
3326 uaudio20_mixer_add_selector(struct uaudio_softc *sc,
3327     const struct uaudio_terminal_node *iot, int id)
3328 {
3329 	const struct usb_audio20_selector_unit *d = iot[id].u.su_v2;
3330 	uint16_t i;
3331 
3332 	DPRINTFN(3, "bUnitId=%d bNrInPins=%d\n",
3333 	    d->bUnitId, d->bNrInPins);
3334 
3335 	if (d->bNrInPins == 0)
3336 		return;
3337 
3338 	memset(&MIX(sc), 0, sizeof(MIX(sc)));
3339 
3340 	MIX(sc).wIndex = MAKE_WORD(d->bUnitId, sc->sc_mixer_iface_no);
3341 	MIX(sc).wValue[0] = MAKE_WORD(0, 0);
3342 	uaudio20_mixer_determine_class(&iot[id], &MIX(sc));
3343 	MIX(sc).nchan = 1;
3344 	MIX(sc).type = MIX_SELECTOR;
3345 	MIX(sc).ctl = SOUND_MIXER_NRDEVICES;
3346 	MIX(sc).minval = 1;
3347 	MIX(sc).maxval = d->bNrInPins;
3348 	MIX(sc).name = "selector";
3349 
3350 	i = d->baSourceId[d->bNrInPins];
3351 	if (i == 0 ||
3352 	    usbd_req_get_string_any(sc->sc_udev, NULL,
3353 	    MIX(sc).desc, sizeof(MIX(sc).desc), i) != 0) {
3354 		MIX(sc).desc[0] = 0;
3355 	}
3356 
3357 	if (MIX(sc).maxval > MAX_SELECTOR_INPUT_PIN)
3358 		MIX(sc).maxval = MAX_SELECTOR_INPUT_PIN;
3359 
3360 	MIX(sc).mul = (MIX(sc).maxval - MIX(sc).minval);
3361 	for (i = 0; i < MAX_SELECTOR_INPUT_PIN; i++)
3362 		MIX(sc).slctrtype[i] = SOUND_MIXER_NRDEVICES;
3363 
3364 	for (i = 0; i < MIX(sc).maxval; i++) {
3365 		MIX(sc).slctrtype[i] = uaudio20_mixer_feature_name(
3366 		    &iot[d->baSourceId[i]], &MIX(sc));
3367 	}
3368 
3369 	MIX(sc).class = 0;			/* not used */
3370 
3371 	uaudio_mixer_add_ctl(sc, &MIX(sc));
3372 }
3373 
3374 static uint32_t
3375 uaudio_mixer_feature_get_bmaControls(const struct usb_audio_feature_unit *d,
3376     uint8_t i)
3377 {
3378 	uint32_t temp = 0;
3379 	uint32_t offset = (i * d->bControlSize);
3380 
3381 	if (d->bControlSize > 0) {
3382 		temp |= d->bmaControls[offset];
3383 		if (d->bControlSize > 1) {
3384 			temp |= d->bmaControls[offset + 1] << 8;
3385 			if (d->bControlSize > 2) {
3386 				temp |= d->bmaControls[offset + 2] << 16;
3387 				if (d->bControlSize > 3) {
3388 					temp |= d->bmaControls[offset + 3] << 24;
3389 				}
3390 			}
3391 		}
3392 	}
3393 	return (temp);
3394 }
3395 
3396 static void
3397 uaudio_mixer_add_feature(struct uaudio_softc *sc,
3398     const struct uaudio_terminal_node *iot, int id)
3399 {
3400 	const struct usb_audio_feature_unit *d = iot[id].u.fu_v1;
3401 	uint32_t fumask;
3402 	uint32_t mmask;
3403 	uint32_t cmask;
3404 	uint16_t mixernumber;
3405 	uint8_t nchan;
3406 	uint8_t chan;
3407 	uint8_t ctl;
3408 	uint8_t i;
3409 
3410 	if (d->bControlSize == 0)
3411 		return;
3412 
3413 	memset(&MIX(sc), 0, sizeof(MIX(sc)));
3414 
3415 	nchan = (d->bLength - 7) / d->bControlSize;
3416 	mmask = uaudio_mixer_feature_get_bmaControls(d, 0);
3417 	cmask = 0;
3418 
3419 	if (nchan == 0)
3420 		return;
3421 
3422 	/* figure out what we can control */
3423 
3424 	for (chan = 1; chan < nchan; chan++) {
3425 		DPRINTFN(10, "chan=%d mask=%x\n",
3426 		    chan, uaudio_mixer_feature_get_bmaControls(d, chan));
3427 
3428 		cmask |= uaudio_mixer_feature_get_bmaControls(d, chan);
3429 	}
3430 
3431 	if (nchan > MIX_MAX_CHAN) {
3432 		nchan = MIX_MAX_CHAN;
3433 	}
3434 	MIX(sc).wIndex = MAKE_WORD(d->bUnitId, sc->sc_mixer_iface_no);
3435 
3436 	i = d->bmaControls[d->bControlSize];
3437 	if (i == 0 ||
3438 	    usbd_req_get_string_any(sc->sc_udev, NULL,
3439 	    MIX(sc).desc, sizeof(MIX(sc).desc), i) != 0) {
3440 		MIX(sc).desc[0] = 0;
3441 	}
3442 
3443 	for (ctl = 1; ctl <= LOUDNESS_CONTROL; ctl++) {
3444 
3445 		fumask = FU_MASK(ctl);
3446 
3447 		DPRINTFN(5, "ctl=%d fumask=0x%04x\n",
3448 		    ctl, fumask);
3449 
3450 		if (mmask & fumask) {
3451 			MIX(sc).nchan = 1;
3452 			MIX(sc).wValue[0] = MAKE_WORD(ctl, 0);
3453 		} else if (cmask & fumask) {
3454 			MIX(sc).nchan = nchan - 1;
3455 			for (i = 1; i < nchan; i++) {
3456 				if (uaudio_mixer_feature_get_bmaControls(d, i) & fumask)
3457 					MIX(sc).wValue[i - 1] = MAKE_WORD(ctl, i);
3458 				else
3459 					MIX(sc).wValue[i - 1] = -1;
3460 			}
3461 		} else {
3462 			continue;
3463 		}
3464 
3465 		mixernumber = uaudio_mixer_feature_name(&iot[id], &MIX(sc));
3466 
3467 		switch (ctl) {
3468 		case MUTE_CONTROL:
3469 			MIX(sc).type = MIX_ON_OFF;
3470 			MIX(sc).ctl = SOUND_MIXER_NRDEVICES;
3471 			MIX(sc).name = "mute";
3472 			break;
3473 
3474 		case VOLUME_CONTROL:
3475 			MIX(sc).type = MIX_SIGNED_16;
3476 			MIX(sc).ctl = mixernumber;
3477 			MIX(sc).name = "vol";
3478 			break;
3479 
3480 		case BASS_CONTROL:
3481 			MIX(sc).type = MIX_SIGNED_8;
3482 			MIX(sc).ctl = SOUND_MIXER_BASS;
3483 			MIX(sc).name = "bass";
3484 			break;
3485 
3486 		case MID_CONTROL:
3487 			MIX(sc).type = MIX_SIGNED_8;
3488 			MIX(sc).ctl = SOUND_MIXER_NRDEVICES;	/* XXXXX */
3489 			MIX(sc).name = "mid";
3490 			break;
3491 
3492 		case TREBLE_CONTROL:
3493 			MIX(sc).type = MIX_SIGNED_8;
3494 			MIX(sc).ctl = SOUND_MIXER_TREBLE;
3495 			MIX(sc).name = "treble";
3496 			break;
3497 
3498 		case GRAPHIC_EQUALIZER_CONTROL:
3499 			continue;	/* XXX don't add anything */
3500 
3501 		case AGC_CONTROL:
3502 			MIX(sc).type = MIX_ON_OFF;
3503 			MIX(sc).ctl = SOUND_MIXER_NRDEVICES;	/* XXXXX */
3504 			MIX(sc).name = "agc";
3505 			break;
3506 
3507 		case DELAY_CONTROL:
3508 			MIX(sc).type = MIX_UNSIGNED_16;
3509 			MIX(sc).ctl = SOUND_MIXER_NRDEVICES;	/* XXXXX */
3510 			MIX(sc).name = "delay";
3511 			break;
3512 
3513 		case BASS_BOOST_CONTROL:
3514 			MIX(sc).type = MIX_ON_OFF;
3515 			MIX(sc).ctl = SOUND_MIXER_NRDEVICES;	/* XXXXX */
3516 			MIX(sc).name = "boost";
3517 			break;
3518 
3519 		case LOUDNESS_CONTROL:
3520 			MIX(sc).type = MIX_ON_OFF;
3521 			MIX(sc).ctl = SOUND_MIXER_LOUD;	/* Is this correct ? */
3522 			MIX(sc).name = "loudness";
3523 			break;
3524 
3525 		default:
3526 			MIX(sc).type = MIX_UNKNOWN;
3527 			break;
3528 		}
3529 
3530 		if (MIX(sc).type != MIX_UNKNOWN)
3531 			uaudio_mixer_add_ctl(sc, &MIX(sc));
3532 	}
3533 }
3534 
3535 static void
3536 uaudio20_mixer_add_feature(struct uaudio_softc *sc,
3537     const struct uaudio_terminal_node *iot, int id)
3538 {
3539 	const struct usb_audio20_feature_unit *d = iot[id].u.fu_v2;
3540 	uint32_t ctl;
3541 	uint32_t mmask;
3542 	uint32_t cmask;
3543 	uint16_t mixernumber;
3544 	uint8_t nchan;
3545 	uint8_t chan;
3546 	uint8_t i;
3547 	uint8_t what;
3548 
3549 	if (UGETDW(d->bmaControls[0]) == 0)
3550 		return;
3551 
3552 	memset(&MIX(sc), 0, sizeof(MIX(sc)));
3553 
3554 	nchan = (d->bLength - 6) / 4;
3555 	mmask = UGETDW(d->bmaControls[0]);
3556 	cmask = 0;
3557 
3558 	if (nchan == 0)
3559 		return;
3560 
3561 	/* figure out what we can control */
3562 
3563 	for (chan = 1; chan < nchan; chan++)
3564 		cmask |= UGETDW(d->bmaControls[chan]);
3565 
3566 	if (nchan > MIX_MAX_CHAN)
3567 		nchan = MIX_MAX_CHAN;
3568 
3569 	MIX(sc).wIndex = MAKE_WORD(d->bUnitId, sc->sc_mixer_iface_no);
3570 
3571 	i = d->bmaControls[nchan][0];
3572 	if (i == 0 ||
3573 	    usbd_req_get_string_any(sc->sc_udev, NULL,
3574 	    MIX(sc).desc, sizeof(MIX(sc).desc), i) != 0) {
3575 		MIX(sc).desc[0] = 0;
3576 	}
3577 
3578 	for (ctl = 3; ctl != 0; ctl <<= 2) {
3579 
3580 		mixernumber = uaudio20_mixer_feature_name(&iot[id], &MIX(sc));
3581 
3582 		switch (ctl) {
3583 		case (3 << 0):
3584 			MIX(sc).type = MIX_ON_OFF;
3585 			MIX(sc).ctl = SOUND_MIXER_NRDEVICES;
3586 			MIX(sc).name = "mute";
3587 			what = MUTE_CONTROL;
3588 			break;
3589 		case (3 << 2):
3590 			MIX(sc).type = MIX_SIGNED_16;
3591 			MIX(sc).ctl = mixernumber;
3592 			MIX(sc).name = "vol";
3593 			what = VOLUME_CONTROL;
3594 			break;
3595 		case (3 << 4):
3596 			MIX(sc).type = MIX_SIGNED_8;
3597 			MIX(sc).ctl = SOUND_MIXER_BASS;
3598 			MIX(sc).name = "bass";
3599 			what = BASS_CONTROL;
3600 			break;
3601 		case (3 << 6):
3602 			MIX(sc).type = MIX_SIGNED_8;
3603 			MIX(sc).ctl = SOUND_MIXER_NRDEVICES;	/* XXXXX */
3604 			MIX(sc).name = "mid";
3605 			what = MID_CONTROL;
3606 			break;
3607 		case (3 << 8):
3608 			MIX(sc).type = MIX_SIGNED_8;
3609 			MIX(sc).ctl = SOUND_MIXER_TREBLE;
3610 			MIX(sc).name = "treble";
3611 			what = TREBLE_CONTROL;
3612 			break;
3613 		case (3 << 12):
3614 			MIX(sc).type = MIX_ON_OFF;
3615 			MIX(sc).ctl = SOUND_MIXER_NRDEVICES;	/* XXXXX */
3616 			MIX(sc).name = "agc";
3617 			what = AGC_CONTROL;
3618 			break;
3619 		case (3 << 14):
3620 			MIX(sc).type = MIX_UNSIGNED_16;
3621 			MIX(sc).ctl = SOUND_MIXER_NRDEVICES;	/* XXXXX */
3622 			MIX(sc).name = "delay";
3623 			what = DELAY_CONTROL;
3624 			break;
3625 		case (3 << 16):
3626 			MIX(sc).type = MIX_ON_OFF;
3627 			MIX(sc).ctl = SOUND_MIXER_NRDEVICES;	/* XXXXX */
3628 			MIX(sc).name = "boost";
3629 			what = BASS_BOOST_CONTROL;
3630 			break;
3631 		case (3 << 18):
3632 			MIX(sc).type = MIX_ON_OFF;
3633 			MIX(sc).ctl = SOUND_MIXER_LOUD;	/* Is this correct ? */
3634 			MIX(sc).name = "loudness";
3635 			what = LOUDNESS_CONTROL;
3636 			break;
3637 		case (3 << 20):
3638 			MIX(sc).type = MIX_SIGNED_16;
3639 			MIX(sc).ctl = mixernumber;
3640 			MIX(sc).name = "igain";
3641 			what = INPUT_GAIN_CONTROL;
3642 			break;
3643 		case (3 << 22):
3644 			MIX(sc).type = MIX_SIGNED_16;
3645 			MIX(sc).ctl = mixernumber;
3646 			MIX(sc).name = "igainpad";
3647 			what = INPUT_GAIN_PAD_CONTROL;
3648 			break;
3649 		default:
3650 			continue;
3651 		}
3652 
3653 		if ((mmask & ctl) == ctl) {
3654 			MIX(sc).nchan = 1;
3655 			MIX(sc).wValue[0] = MAKE_WORD(what, 0);
3656 		} else if ((cmask & ctl) == ctl) {
3657 			MIX(sc).nchan = nchan - 1;
3658 			for (i = 1; i < nchan; i++) {
3659 				if ((UGETDW(d->bmaControls[i]) & ctl) == ctl)
3660 					MIX(sc).wValue[i - 1] = MAKE_WORD(what, i);
3661 				else
3662 					MIX(sc).wValue[i - 1] = -1;
3663 			}
3664 		} else {
3665 			continue;
3666 		}
3667 
3668 		if (MIX(sc).type != MIX_UNKNOWN)
3669 			uaudio_mixer_add_ctl(sc, &MIX(sc));
3670 	}
3671 }
3672 
3673 static void
3674 uaudio_mixer_add_processing_updown(struct uaudio_softc *sc,
3675     const struct uaudio_terminal_node *iot, int id)
3676 {
3677 	const struct usb_audio_processing_unit_0 *d0 = iot[id].u.pu_v1;
3678 	const struct usb_audio_processing_unit_1 *d1 =
3679 	    (const void *)(d0->baSourceId + d0->bNrInPins);
3680 	const struct usb_audio_processing_unit_updown *ud =
3681 	    (const void *)(d1->bmControls + d1->bControlSize);
3682 	uint8_t i;
3683 
3684 	if (uaudio_mixer_verify_desc(d0, sizeof(*ud)) == NULL) {
3685 		return;
3686 	}
3687 	if (uaudio_mixer_verify_desc(d0, sizeof(*ud) + (2 * ud->bNrModes))
3688 	    == NULL) {
3689 		return;
3690 	}
3691 	DPRINTFN(3, "bUnitId=%d bNrModes=%d\n",
3692 	    d0->bUnitId, ud->bNrModes);
3693 
3694 	if (!(d1->bmControls[0] & UA_PROC_MASK(UD_MODE_SELECT_CONTROL))) {
3695 		DPRINTF("no mode select\n");
3696 		return;
3697 	}
3698 	memset(&MIX(sc), 0, sizeof(MIX(sc)));
3699 
3700 	MIX(sc).wIndex = MAKE_WORD(d0->bUnitId, sc->sc_mixer_iface_no);
3701 	MIX(sc).nchan = 1;
3702 	MIX(sc).wValue[0] = MAKE_WORD(UD_MODE_SELECT_CONTROL, 0);
3703 	uaudio_mixer_determine_class(&iot[id], &MIX(sc));
3704 	MIX(sc).type = MIX_ON_OFF;		/* XXX */
3705 
3706 	for (i = 0; i < ud->bNrModes; i++) {
3707 		DPRINTFN(3, "i=%d bm=0x%x\n", i, UGETW(ud->waModes[i]));
3708 		/* XXX */
3709 	}
3710 
3711 	uaudio_mixer_add_ctl(sc, &MIX(sc));
3712 }
3713 
3714 static void
3715 uaudio_mixer_add_processing(struct uaudio_softc *sc,
3716     const struct uaudio_terminal_node *iot, int id)
3717 {
3718 	const struct usb_audio_processing_unit_0 *d0 = iot[id].u.pu_v1;
3719 	const struct usb_audio_processing_unit_1 *d1 =
3720 	    (const void *)(d0->baSourceId + d0->bNrInPins);
3721 	uint16_t ptype;
3722 
3723 	memset(&MIX(sc), 0, sizeof(MIX(sc)));
3724 
3725 	ptype = UGETW(d0->wProcessType);
3726 
3727 	DPRINTFN(3, "wProcessType=%d bUnitId=%d "
3728 	    "bNrInPins=%d\n", ptype, d0->bUnitId, d0->bNrInPins);
3729 
3730 	if (d1->bControlSize == 0) {
3731 		return;
3732 	}
3733 	if (d1->bmControls[0] & UA_PROC_ENABLE_MASK) {
3734 		MIX(sc).wIndex = MAKE_WORD(d0->bUnitId, sc->sc_mixer_iface_no);
3735 		MIX(sc).nchan = 1;
3736 		MIX(sc).wValue[0] = MAKE_WORD(XX_ENABLE_CONTROL, 0);
3737 		uaudio_mixer_determine_class(&iot[id], &MIX(sc));
3738 		MIX(sc).type = MIX_ON_OFF;
3739 		uaudio_mixer_add_ctl(sc, &MIX(sc));
3740 	}
3741 	switch (ptype) {
3742 	case UPDOWNMIX_PROCESS:
3743 		uaudio_mixer_add_processing_updown(sc, iot, id);
3744 		break;
3745 
3746 	case DOLBY_PROLOGIC_PROCESS:
3747 	case P3D_STEREO_EXTENDER_PROCESS:
3748 	case REVERBATION_PROCESS:
3749 	case CHORUS_PROCESS:
3750 	case DYN_RANGE_COMP_PROCESS:
3751 	default:
3752 		DPRINTF("unit %d, type=%d is not implemented\n",
3753 		    d0->bUnitId, ptype);
3754 		break;
3755 	}
3756 }
3757 
3758 static void
3759 uaudio_mixer_add_extension(struct uaudio_softc *sc,
3760     const struct uaudio_terminal_node *iot, int id)
3761 {
3762 	const struct usb_audio_extension_unit_0 *d0 = iot[id].u.eu_v1;
3763 	const struct usb_audio_extension_unit_1 *d1 =
3764 	    (const void *)(d0->baSourceId + d0->bNrInPins);
3765 
3766 	DPRINTFN(3, "bUnitId=%d bNrInPins=%d\n",
3767 	    d0->bUnitId, d0->bNrInPins);
3768 
3769 	if (sc->sc_uq_au_no_xu) {
3770 		return;
3771 	}
3772 	if (d1->bControlSize == 0) {
3773 		return;
3774 	}
3775 	if (d1->bmControls[0] & UA_EXT_ENABLE_MASK) {
3776 
3777 		memset(&MIX(sc), 0, sizeof(MIX(sc)));
3778 
3779 		MIX(sc).wIndex = MAKE_WORD(d0->bUnitId, sc->sc_mixer_iface_no);
3780 		MIX(sc).nchan = 1;
3781 		MIX(sc).wValue[0] = MAKE_WORD(UA_EXT_ENABLE, 0);
3782 		uaudio_mixer_determine_class(&iot[id], &MIX(sc));
3783 		MIX(sc).type = MIX_ON_OFF;
3784 
3785 		uaudio_mixer_add_ctl(sc, &MIX(sc));
3786 	}
3787 }
3788 
3789 static const void *
3790 uaudio_mixer_verify_desc(const void *arg, uint32_t len)
3791 {
3792 	const struct usb_audio_mixer_unit_1 *d1;
3793 	const struct usb_audio_extension_unit_1 *e1;
3794 	const struct usb_audio_processing_unit_1 *u1;
3795 
3796 	union {
3797 		const struct usb_descriptor *desc;
3798 		const struct usb_audio_input_terminal *it;
3799 		const struct usb_audio_output_terminal *ot;
3800 		const struct usb_audio_mixer_unit_0 *mu;
3801 		const struct usb_audio_selector_unit *su;
3802 		const struct usb_audio_feature_unit *fu;
3803 		const struct usb_audio_processing_unit_0 *pu;
3804 		const struct usb_audio_extension_unit_0 *eu;
3805 	}     u;
3806 
3807 	u.desc = arg;
3808 
3809 	if (u.desc == NULL) {
3810 		goto error;
3811 	}
3812 	if (u.desc->bDescriptorType != UDESC_CS_INTERFACE) {
3813 		goto error;
3814 	}
3815 	switch (u.desc->bDescriptorSubtype) {
3816 	case UDESCSUB_AC_INPUT:
3817 		len += sizeof(*u.it);
3818 		break;
3819 
3820 	case UDESCSUB_AC_OUTPUT:
3821 		len += sizeof(*u.ot);
3822 		break;
3823 
3824 	case UDESCSUB_AC_MIXER:
3825 		len += sizeof(*u.mu);
3826 
3827 		if (u.desc->bLength < len) {
3828 			goto error;
3829 		}
3830 		len += u.mu->bNrInPins;
3831 
3832 		if (u.desc->bLength < len) {
3833 			goto error;
3834 		}
3835 		d1 = (const void *)(u.mu->baSourceId + u.mu->bNrInPins);
3836 
3837 		len += sizeof(*d1);
3838 		break;
3839 
3840 	case UDESCSUB_AC_SELECTOR:
3841 		len += sizeof(*u.su);
3842 
3843 		if (u.desc->bLength < len) {
3844 			goto error;
3845 		}
3846 		len += u.su->bNrInPins + 1;
3847 		break;
3848 
3849 	case UDESCSUB_AC_FEATURE:
3850 		len += sizeof(*u.fu) + 1;
3851 
3852 		if (u.desc->bLength < len)
3853 			goto error;
3854 
3855 		len += u.fu->bControlSize;
3856 		break;
3857 
3858 	case UDESCSUB_AC_PROCESSING:
3859 		len += sizeof(*u.pu);
3860 
3861 		if (u.desc->bLength < len) {
3862 			goto error;
3863 		}
3864 		len += u.pu->bNrInPins;
3865 
3866 		if (u.desc->bLength < len) {
3867 			goto error;
3868 		}
3869 		u1 = (const void *)(u.pu->baSourceId + u.pu->bNrInPins);
3870 
3871 		len += sizeof(*u1);
3872 
3873 		if (u.desc->bLength < len) {
3874 			goto error;
3875 		}
3876 		len += u1->bControlSize;
3877 
3878 		break;
3879 
3880 	case UDESCSUB_AC_EXTENSION:
3881 		len += sizeof(*u.eu);
3882 
3883 		if (u.desc->bLength < len) {
3884 			goto error;
3885 		}
3886 		len += u.eu->bNrInPins;
3887 
3888 		if (u.desc->bLength < len) {
3889 			goto error;
3890 		}
3891 		e1 = (const void *)(u.eu->baSourceId + u.eu->bNrInPins);
3892 
3893 		len += sizeof(*e1);
3894 
3895 		if (u.desc->bLength < len) {
3896 			goto error;
3897 		}
3898 		len += e1->bControlSize;
3899 		break;
3900 
3901 	default:
3902 		goto error;
3903 	}
3904 
3905 	if (u.desc->bLength < len) {
3906 		goto error;
3907 	}
3908 	return (u.desc);
3909 
3910 error:
3911 	if (u.desc) {
3912 		DPRINTF("invalid descriptor, type=%d, "
3913 		    "sub_type=%d, len=%d of %d bytes\n",
3914 		    u.desc->bDescriptorType,
3915 		    u.desc->bDescriptorSubtype,
3916 		    u.desc->bLength, len);
3917 	}
3918 	return (NULL);
3919 }
3920 
3921 static const void *
3922 uaudio20_mixer_verify_desc(const void *arg, uint32_t len)
3923 {
3924 	const struct usb_audio20_mixer_unit_1 *d1;
3925 	const struct usb_audio20_extension_unit_1 *e1;
3926 	const struct usb_audio20_processing_unit_1 *u1;
3927 	const struct usb_audio20_clock_selector_unit_1 *c1;
3928 
3929 	union {
3930 		const struct usb_descriptor *desc;
3931 		const struct usb_audio20_clock_source_unit *csrc;
3932 		const struct usb_audio20_clock_selector_unit_0 *csel;
3933 		const struct usb_audio20_clock_multiplier_unit *cmul;
3934 		const struct usb_audio20_input_terminal *it;
3935 		const struct usb_audio20_output_terminal *ot;
3936 		const struct usb_audio20_mixer_unit_0 *mu;
3937 		const struct usb_audio20_selector_unit *su;
3938 		const struct usb_audio20_feature_unit *fu;
3939 		const struct usb_audio20_sample_rate_unit *ru;
3940 		const struct usb_audio20_processing_unit_0 *pu;
3941 		const struct usb_audio20_extension_unit_0 *eu;
3942 		const struct usb_audio20_effect_unit *ef;
3943 	}     u;
3944 
3945 	u.desc = arg;
3946 
3947 	if (u.desc == NULL)
3948 		goto error;
3949 
3950 	if (u.desc->bDescriptorType != UDESC_CS_INTERFACE)
3951 		goto error;
3952 
3953 	switch (u.desc->bDescriptorSubtype) {
3954 	case UDESCSUB_AC_INPUT:
3955 		len += sizeof(*u.it);
3956 		break;
3957 
3958 	case UDESCSUB_AC_OUTPUT:
3959 		len += sizeof(*u.ot);
3960 		break;
3961 
3962 	case UDESCSUB_AC_MIXER:
3963 		len += sizeof(*u.mu);
3964 
3965 		if (u.desc->bLength < len)
3966 			goto error;
3967 		len += u.mu->bNrInPins;
3968 
3969 		if (u.desc->bLength < len)
3970 			goto error;
3971 
3972 		d1 = (const void *)(u.mu->baSourceId + u.mu->bNrInPins);
3973 
3974 		len += sizeof(*d1) + d1->bNrChannels;
3975 		break;
3976 
3977 	case UDESCSUB_AC_SELECTOR:
3978 		len += sizeof(*u.su);
3979 
3980 		if (u.desc->bLength < len)
3981 			goto error;
3982 
3983 		len += u.su->bNrInPins + 1;
3984 		break;
3985 
3986 	case UDESCSUB_AC_FEATURE:
3987 		len += sizeof(*u.fu) + 1;
3988 		break;
3989 
3990 	case UDESCSUB_AC_EFFECT:
3991 		len += sizeof(*u.ef) + 4;
3992 		break;
3993 
3994 	case UDESCSUB_AC_PROCESSING_V2:
3995 		len += sizeof(*u.pu);
3996 
3997 		if (u.desc->bLength < len)
3998 			goto error;
3999 
4000 		len += u.pu->bNrInPins;
4001 
4002 		if (u.desc->bLength < len)
4003 			goto error;
4004 
4005 		u1 = (const void *)(u.pu->baSourceId + u.pu->bNrInPins);
4006 
4007 		len += sizeof(*u1);
4008 		break;
4009 
4010 	case UDESCSUB_AC_EXTENSION_V2:
4011 		len += sizeof(*u.eu);
4012 
4013 		if (u.desc->bLength < len)
4014 			goto error;
4015 
4016 		len += u.eu->bNrInPins;
4017 
4018 		if (u.desc->bLength < len)
4019 			goto error;
4020 
4021 		e1 = (const void *)(u.eu->baSourceId + u.eu->bNrInPins);
4022 
4023 		len += sizeof(*e1);
4024 		break;
4025 
4026 	case UDESCSUB_AC_CLOCK_SRC:
4027 		len += sizeof(*u.csrc);
4028 		break;
4029 
4030 	case UDESCSUB_AC_CLOCK_SEL:
4031 		len += sizeof(*u.csel);
4032 
4033 		if (u.desc->bLength < len)
4034 			goto error;
4035 
4036 		len += u.csel->bNrInPins;
4037 
4038 		if (u.desc->bLength < len)
4039 			goto error;
4040 
4041 		c1 = (const void *)(u.csel->baCSourceId + u.csel->bNrInPins);
4042 
4043 		len += sizeof(*c1);
4044 		break;
4045 
4046 	case UDESCSUB_AC_CLOCK_MUL:
4047 		len += sizeof(*u.cmul);
4048 		break;
4049 
4050 	case UDESCSUB_AC_SAMPLE_RT:
4051 		len += sizeof(*u.ru);
4052 		break;
4053 
4054 	default:
4055 		goto error;
4056 	}
4057 
4058 	if (u.desc->bLength < len)
4059 		goto error;
4060 
4061 	return (u.desc);
4062 
4063 error:
4064 	if (u.desc) {
4065 		DPRINTF("invalid descriptor, type=%d, "
4066 		    "sub_type=%d, len=%d of %d bytes\n",
4067 		    u.desc->bDescriptorType,
4068 		    u.desc->bDescriptorSubtype,
4069 		    u.desc->bLength, len);
4070 	}
4071 	return (NULL);
4072 }
4073 
4074 static struct usb_audio_cluster
4075 uaudio_mixer_get_cluster(uint8_t id, const struct uaudio_terminal_node *iot)
4076 {
4077 	struct usb_audio_cluster r;
4078 	const struct usb_descriptor *dp;
4079 	uint8_t i;
4080 
4081 	for (i = 0; i < UAUDIO_RECURSE_LIMIT; i++) {	/* avoid infinite loops */
4082 		dp = iot[id].u.desc;
4083 		if (dp == NULL) {
4084 			goto error;
4085 		}
4086 		switch (dp->bDescriptorSubtype) {
4087 		case UDESCSUB_AC_INPUT:
4088 			r.bNrChannels = iot[id].u.it_v1->bNrChannels;
4089 			r.wChannelConfig[0] = iot[id].u.it_v1->wChannelConfig[0];
4090 			r.wChannelConfig[1] = iot[id].u.it_v1->wChannelConfig[1];
4091 			r.iChannelNames = iot[id].u.it_v1->iChannelNames;
4092 			goto done;
4093 
4094 		case UDESCSUB_AC_OUTPUT:
4095 			id = iot[id].u.ot_v1->bSourceId;
4096 			break;
4097 
4098 		case UDESCSUB_AC_MIXER:
4099 			r = *(const struct usb_audio_cluster *)
4100 			    &iot[id].u.mu_v1->baSourceId[
4101 			    iot[id].u.mu_v1->bNrInPins];
4102 			goto done;
4103 
4104 		case UDESCSUB_AC_SELECTOR:
4105 			if (iot[id].u.su_v1->bNrInPins > 0) {
4106 				/* XXX This is not really right */
4107 				id = iot[id].u.su_v1->baSourceId[0];
4108 			}
4109 			break;
4110 
4111 		case UDESCSUB_AC_FEATURE:
4112 			id = iot[id].u.fu_v1->bSourceId;
4113 			break;
4114 
4115 		case UDESCSUB_AC_PROCESSING:
4116 			r = *((const struct usb_audio_cluster *)
4117 			    &iot[id].u.pu_v1->baSourceId[
4118 			    iot[id].u.pu_v1->bNrInPins]);
4119 			goto done;
4120 
4121 		case UDESCSUB_AC_EXTENSION:
4122 			r = *((const struct usb_audio_cluster *)
4123 			    &iot[id].u.eu_v1->baSourceId[
4124 			    iot[id].u.eu_v1->bNrInPins]);
4125 			goto done;
4126 
4127 		default:
4128 			goto error;
4129 		}
4130 	}
4131 error:
4132 	DPRINTF("bad data\n");
4133 	memset(&r, 0, sizeof(r));
4134 done:
4135 	return (r);
4136 }
4137 
4138 static struct usb_audio20_cluster
4139 uaudio20_mixer_get_cluster(uint8_t id, const struct uaudio_terminal_node *iot)
4140 {
4141 	struct usb_audio20_cluster r;
4142 	const struct usb_descriptor *dp;
4143 	uint8_t i;
4144 
4145 	for (i = 0; i < UAUDIO_RECURSE_LIMIT; i++) {	/* avoid infinite loops */
4146 		dp = iot[id].u.desc;
4147 		if (dp == NULL)
4148 			goto error;
4149 
4150 		switch (dp->bDescriptorSubtype) {
4151 		case UDESCSUB_AC_INPUT:
4152 			r.bNrChannels = iot[id].u.it_v2->bNrChannels;
4153 			r.bmChannelConfig[0] = iot[id].u.it_v2->bmChannelConfig[0];
4154 			r.bmChannelConfig[1] = iot[id].u.it_v2->bmChannelConfig[1];
4155 			r.bmChannelConfig[2] = iot[id].u.it_v2->bmChannelConfig[2];
4156 			r.bmChannelConfig[3] = iot[id].u.it_v2->bmChannelConfig[3];
4157 			r.iChannelNames = iot[id].u.it_v2->iTerminal;
4158 			goto done;
4159 
4160 		case UDESCSUB_AC_OUTPUT:
4161 			id = iot[id].u.ot_v2->bSourceId;
4162 			break;
4163 
4164 		case UDESCSUB_AC_MIXER:
4165 			r = *(const struct usb_audio20_cluster *)
4166 			    &iot[id].u.mu_v2->baSourceId[
4167 			    iot[id].u.mu_v2->bNrInPins];
4168 			goto done;
4169 
4170 		case UDESCSUB_AC_SELECTOR:
4171 			if (iot[id].u.su_v2->bNrInPins > 0) {
4172 				/* XXX This is not really right */
4173 				id = iot[id].u.su_v2->baSourceId[0];
4174 			}
4175 			break;
4176 
4177 		case UDESCSUB_AC_SAMPLE_RT:
4178 			id = iot[id].u.ru_v2->bSourceId;
4179 			break;
4180 
4181 		case UDESCSUB_AC_EFFECT:
4182 			id = iot[id].u.ef_v2->bSourceId;
4183 			break;
4184 
4185 		case UDESCSUB_AC_FEATURE:
4186 			id = iot[id].u.fu_v2->bSourceId;
4187 			break;
4188 
4189 		case UDESCSUB_AC_PROCESSING_V2:
4190 			r = *((const struct usb_audio20_cluster *)
4191 			    &iot[id].u.pu_v2->baSourceId[
4192 			    iot[id].u.pu_v2->bNrInPins]);
4193 			goto done;
4194 
4195 		case UDESCSUB_AC_EXTENSION_V2:
4196 			r = *((const struct usb_audio20_cluster *)
4197 			    &iot[id].u.eu_v2->baSourceId[
4198 			    iot[id].u.eu_v2->bNrInPins]);
4199 			goto done;
4200 
4201 		default:
4202 			goto error;
4203 		}
4204 	}
4205 error:
4206 	DPRINTF("Bad data!\n");
4207 	memset(&r, 0, sizeof(r));
4208 done:
4209 	return (r);
4210 }
4211 
4212 static uint16_t
4213 uaudio_mixer_determine_class(const struct uaudio_terminal_node *iot,
4214     struct uaudio_mixer_node *mix)
4215 {
4216 	uint16_t terminal_type = 0x0000;
4217 	const struct uaudio_terminal_node *input[2];
4218 	const struct uaudio_terminal_node *output[2];
4219 
4220 	input[0] = uaudio_mixer_get_input(iot, 0);
4221 	input[1] = uaudio_mixer_get_input(iot, 1);
4222 
4223 	output[0] = uaudio_mixer_get_output(iot, 0);
4224 	output[1] = uaudio_mixer_get_output(iot, 1);
4225 
4226 	/*
4227 	 * check if there is only
4228 	 * one output terminal:
4229 	 */
4230 	if (output[0] && (!output[1])) {
4231 		terminal_type =
4232 		    UGETW(output[0]->u.ot_v1->wTerminalType);
4233 	}
4234 	/*
4235 	 * If the only output terminal is USB,
4236 	 * the class is UAC_RECORD.
4237 	 */
4238 	if ((terminal_type & 0xff00) == (UAT_UNDEFINED & 0xff00)) {
4239 
4240 		mix->class = UAC_RECORD;
4241 		if (input[0] && (!input[1])) {
4242 			terminal_type =
4243 			    UGETW(input[0]->u.it_v1->wTerminalType);
4244 		} else {
4245 			terminal_type = 0;
4246 		}
4247 		goto done;
4248 	}
4249 	/*
4250 	 * if the unit is connected to just
4251 	 * one input terminal, the
4252 	 * class is UAC_INPUT:
4253 	 */
4254 	if (input[0] && (!input[1])) {
4255 		mix->class = UAC_INPUT;
4256 		terminal_type =
4257 		    UGETW(input[0]->u.it_v1->wTerminalType);
4258 		goto done;
4259 	}
4260 	/*
4261 	 * Otherwise, the class is UAC_OUTPUT.
4262 	 */
4263 	mix->class = UAC_OUTPUT;
4264 done:
4265 	return (terminal_type);
4266 }
4267 
4268 static uint16_t
4269 uaudio20_mixer_determine_class(const struct uaudio_terminal_node *iot,
4270     struct uaudio_mixer_node *mix)
4271 {
4272 	uint16_t terminal_type = 0x0000;
4273 	const struct uaudio_terminal_node *input[2];
4274 	const struct uaudio_terminal_node *output[2];
4275 
4276 	input[0] = uaudio_mixer_get_input(iot, 0);
4277 	input[1] = uaudio_mixer_get_input(iot, 1);
4278 
4279 	output[0] = uaudio_mixer_get_output(iot, 0);
4280 	output[1] = uaudio_mixer_get_output(iot, 1);
4281 
4282 	/*
4283 	 * check if there is only
4284 	 * one output terminal:
4285 	 */
4286 	if (output[0] && (!output[1]))
4287 		terminal_type = UGETW(output[0]->u.ot_v2->wTerminalType);
4288 	/*
4289 	 * If the only output terminal is USB,
4290 	 * the class is UAC_RECORD.
4291 	 */
4292 	if ((terminal_type & 0xff00) == (UAT_UNDEFINED & 0xff00)) {
4293 
4294 		mix->class = UAC_RECORD;
4295 		if (input[0] && (!input[1])) {
4296 			terminal_type =
4297 			    UGETW(input[0]->u.it_v2->wTerminalType);
4298 		} else {
4299 			terminal_type = 0;
4300 		}
4301 		goto done;
4302 	}
4303 	/*
4304 	 * if the unit is connected to just
4305 	 * one input terminal, the
4306 	 * class is UAC_INPUT:
4307 	 */
4308 	if (input[0] && (!input[1])) {
4309 		mix->class = UAC_INPUT;
4310 		terminal_type =
4311 		    UGETW(input[0]->u.it_v2->wTerminalType);
4312 		goto done;
4313 	}
4314 	/*
4315 	 * Otherwise, the class is UAC_OUTPUT.
4316 	 */
4317 	mix->class = UAC_OUTPUT;
4318 done:
4319 	return (terminal_type);
4320 }
4321 
4322 struct uaudio_tt_to_feature {
4323 	uint16_t terminal_type;
4324 	uint16_t feature;
4325 };
4326 
4327 static const struct uaudio_tt_to_feature uaudio_tt_to_feature[] = {
4328 
4329 	{UAT_STREAM, SOUND_MIXER_PCM},
4330 
4331 	{UATI_MICROPHONE, SOUND_MIXER_MIC},
4332 	{UATI_DESKMICROPHONE, SOUND_MIXER_MIC},
4333 	{UATI_PERSONALMICROPHONE, SOUND_MIXER_MIC},
4334 	{UATI_OMNIMICROPHONE, SOUND_MIXER_MIC},
4335 	{UATI_MICROPHONEARRAY, SOUND_MIXER_MIC},
4336 	{UATI_PROCMICROPHONEARR, SOUND_MIXER_MIC},
4337 
4338 	{UATO_SPEAKER, SOUND_MIXER_SPEAKER},
4339 	{UATO_DESKTOPSPEAKER, SOUND_MIXER_SPEAKER},
4340 	{UATO_ROOMSPEAKER, SOUND_MIXER_SPEAKER},
4341 	{UATO_COMMSPEAKER, SOUND_MIXER_SPEAKER},
4342 
4343 	{UATE_ANALOGCONN, SOUND_MIXER_LINE},
4344 	{UATE_LINECONN, SOUND_MIXER_LINE},
4345 	{UATE_LEGACYCONN, SOUND_MIXER_LINE},
4346 
4347 	{UATE_DIGITALAUIFC, SOUND_MIXER_ALTPCM},
4348 	{UATE_SPDIF, SOUND_MIXER_ALTPCM},
4349 	{UATE_1394DA, SOUND_MIXER_ALTPCM},
4350 	{UATE_1394DV, SOUND_MIXER_ALTPCM},
4351 
4352 	{UATF_CDPLAYER, SOUND_MIXER_CD},
4353 
4354 	{UATF_SYNTHESIZER, SOUND_MIXER_SYNTH},
4355 
4356 	{UATF_VIDEODISCAUDIO, SOUND_MIXER_VIDEO},
4357 	{UATF_DVDAUDIO, SOUND_MIXER_VIDEO},
4358 	{UATF_TVTUNERAUDIO, SOUND_MIXER_VIDEO},
4359 
4360 	/* telephony terminal types */
4361 	{UATT_UNDEFINED, SOUND_MIXER_PHONEIN},	/* SOUND_MIXER_PHONEOUT */
4362 	{UATT_PHONELINE, SOUND_MIXER_PHONEIN},	/* SOUND_MIXER_PHONEOUT */
4363 	{UATT_TELEPHONE, SOUND_MIXER_PHONEIN},	/* SOUND_MIXER_PHONEOUT */
4364 	{UATT_DOWNLINEPHONE, SOUND_MIXER_PHONEIN},	/* SOUND_MIXER_PHONEOUT */
4365 
4366 	{UATF_RADIORECV, SOUND_MIXER_RADIO},
4367 	{UATF_RADIOXMIT, SOUND_MIXER_RADIO},
4368 
4369 	{UAT_UNDEFINED, SOUND_MIXER_VOLUME},
4370 	{UAT_VENDOR, SOUND_MIXER_VOLUME},
4371 	{UATI_UNDEFINED, SOUND_MIXER_VOLUME},
4372 
4373 	/* output terminal types */
4374 	{UATO_UNDEFINED, SOUND_MIXER_VOLUME},
4375 	{UATO_DISPLAYAUDIO, SOUND_MIXER_VOLUME},
4376 	{UATO_SUBWOOFER, SOUND_MIXER_VOLUME},
4377 	{UATO_HEADPHONES, SOUND_MIXER_VOLUME},
4378 
4379 	/* bidir terminal types */
4380 	{UATB_UNDEFINED, SOUND_MIXER_VOLUME},
4381 	{UATB_HANDSET, SOUND_MIXER_VOLUME},
4382 	{UATB_HEADSET, SOUND_MIXER_VOLUME},
4383 	{UATB_SPEAKERPHONE, SOUND_MIXER_VOLUME},
4384 	{UATB_SPEAKERPHONEESUP, SOUND_MIXER_VOLUME},
4385 	{UATB_SPEAKERPHONEECANC, SOUND_MIXER_VOLUME},
4386 
4387 	/* external terminal types */
4388 	{UATE_UNDEFINED, SOUND_MIXER_VOLUME},
4389 
4390 	/* embedded function terminal types */
4391 	{UATF_UNDEFINED, SOUND_MIXER_VOLUME},
4392 	{UATF_CALIBNOISE, SOUND_MIXER_VOLUME},
4393 	{UATF_EQUNOISE, SOUND_MIXER_VOLUME},
4394 	{UATF_DAT, SOUND_MIXER_VOLUME},
4395 	{UATF_DCC, SOUND_MIXER_VOLUME},
4396 	{UATF_MINIDISK, SOUND_MIXER_VOLUME},
4397 	{UATF_ANALOGTAPE, SOUND_MIXER_VOLUME},
4398 	{UATF_PHONOGRAPH, SOUND_MIXER_VOLUME},
4399 	{UATF_VCRAUDIO, SOUND_MIXER_VOLUME},
4400 	{UATF_SATELLITE, SOUND_MIXER_VOLUME},
4401 	{UATF_CABLETUNER, SOUND_MIXER_VOLUME},
4402 	{UATF_DSS, SOUND_MIXER_VOLUME},
4403 	{UATF_MULTITRACK, SOUND_MIXER_VOLUME},
4404 	{0xffff, SOUND_MIXER_VOLUME},
4405 
4406 	/* default */
4407 	{0x0000, SOUND_MIXER_VOLUME},
4408 };
4409 
4410 static uint16_t
4411 uaudio_mixer_feature_name(const struct uaudio_terminal_node *iot,
4412     struct uaudio_mixer_node *mix)
4413 {
4414 	const struct uaudio_tt_to_feature *uat = uaudio_tt_to_feature;
4415 	uint16_t terminal_type = uaudio_mixer_determine_class(iot, mix);
4416 
4417 	if ((mix->class == UAC_RECORD) && (terminal_type == 0)) {
4418 		return (SOUND_MIXER_IMIX);
4419 	}
4420 	while (uat->terminal_type) {
4421 		if (uat->terminal_type == terminal_type) {
4422 			break;
4423 		}
4424 		uat++;
4425 	}
4426 
4427 	DPRINTF("terminal_type=0x%04x -> %d\n",
4428 	    terminal_type, uat->feature);
4429 
4430 	return (uat->feature);
4431 }
4432 
4433 static uint16_t
4434 uaudio20_mixer_feature_name(const struct uaudio_terminal_node *iot,
4435     struct uaudio_mixer_node *mix)
4436 {
4437 	const struct uaudio_tt_to_feature *uat;
4438 	uint16_t terminal_type = uaudio20_mixer_determine_class(iot, mix);
4439 
4440 	if ((mix->class == UAC_RECORD) && (terminal_type == 0))
4441 		return (SOUND_MIXER_IMIX);
4442 
4443 	for (uat = uaudio_tt_to_feature; uat->terminal_type != 0; uat++) {
4444 		if (uat->terminal_type == terminal_type)
4445 			break;
4446 	}
4447 
4448 	DPRINTF("terminal_type=0x%04x -> %d\n",
4449 	    terminal_type, uat->feature);
4450 
4451 	return (uat->feature);
4452 }
4453 
4454 static const struct uaudio_terminal_node *
4455 uaudio_mixer_get_input(const struct uaudio_terminal_node *iot, uint8_t i)
4456 {
4457 	struct uaudio_terminal_node *root = iot->root;
4458 	uint8_t n;
4459 
4460 	n = iot->usr.id_max;
4461 	do {
4462 		if (iot->usr.bit_input[n / 8] & (1 << (n % 8))) {
4463 			if (!i--)
4464 				return (root + n);
4465 		}
4466 	} while (n--);
4467 
4468 	return (NULL);
4469 }
4470 
4471 static const struct uaudio_terminal_node *
4472 uaudio_mixer_get_output(const struct uaudio_terminal_node *iot, uint8_t i)
4473 {
4474 	struct uaudio_terminal_node *root = iot->root;
4475 	uint8_t n;
4476 
4477 	n = iot->usr.id_max;
4478 	do {
4479 		if (iot->usr.bit_output[n / 8] & (1 << (n % 8))) {
4480 			if (!i--)
4481 				return (root + n);
4482 		}
4483 	} while (n--);
4484 
4485 	return (NULL);
4486 }
4487 
4488 static void
4489 uaudio_mixer_find_inputs_sub(struct uaudio_terminal_node *root,
4490     const uint8_t *p_id, uint8_t n_id,
4491     struct uaudio_search_result *info)
4492 {
4493 	struct uaudio_terminal_node *iot;
4494 	uint8_t n;
4495 	uint8_t i;
4496 	uint8_t is_last;
4497 
4498 top:
4499 	for (n = 0; n < n_id; n++) {
4500 
4501 		i = p_id[n];
4502 
4503 		if (info->recurse_level == UAUDIO_RECURSE_LIMIT) {
4504 			DPRINTF("avoided going into a circle at id=%d!\n", i);
4505 			return;
4506 		}
4507 
4508 		info->recurse_level++;
4509 
4510 		iot = (root + i);
4511 
4512 		if (iot->u.desc == NULL)
4513 			continue;
4514 
4515 		is_last = ((n + 1) == n_id);
4516 
4517 		switch (iot->u.desc->bDescriptorSubtype) {
4518 		case UDESCSUB_AC_INPUT:
4519 			info->bit_input[i / 8] |= (1 << (i % 8));
4520 			break;
4521 
4522 		case UDESCSUB_AC_FEATURE:
4523 			if (is_last) {
4524 				p_id = &iot->u.fu_v1->bSourceId;
4525 				n_id = 1;
4526 				goto top;
4527 			}
4528 			uaudio_mixer_find_inputs_sub(
4529 			    root, &iot->u.fu_v1->bSourceId, 1, info);
4530 			break;
4531 
4532 		case UDESCSUB_AC_OUTPUT:
4533 			if (is_last) {
4534 				p_id = &iot->u.ot_v1->bSourceId;
4535 				n_id = 1;
4536 				goto top;
4537 			}
4538 			uaudio_mixer_find_inputs_sub(
4539 			    root, &iot->u.ot_v1->bSourceId, 1, info);
4540 			break;
4541 
4542 		case UDESCSUB_AC_MIXER:
4543 			if (is_last) {
4544 				p_id = iot->u.mu_v1->baSourceId;
4545 				n_id = iot->u.mu_v1->bNrInPins;
4546 				goto top;
4547 			}
4548 			uaudio_mixer_find_inputs_sub(
4549 			    root, iot->u.mu_v1->baSourceId,
4550 			    iot->u.mu_v1->bNrInPins, info);
4551 			break;
4552 
4553 		case UDESCSUB_AC_SELECTOR:
4554 			if (is_last) {
4555 				p_id = iot->u.su_v1->baSourceId;
4556 				n_id = iot->u.su_v1->bNrInPins;
4557 				goto top;
4558 			}
4559 			uaudio_mixer_find_inputs_sub(
4560 			    root, iot->u.su_v1->baSourceId,
4561 			    iot->u.su_v1->bNrInPins, info);
4562 			break;
4563 
4564 		case UDESCSUB_AC_PROCESSING:
4565 			if (is_last) {
4566 				p_id = iot->u.pu_v1->baSourceId;
4567 				n_id = iot->u.pu_v1->bNrInPins;
4568 				goto top;
4569 			}
4570 			uaudio_mixer_find_inputs_sub(
4571 			    root, iot->u.pu_v1->baSourceId,
4572 			    iot->u.pu_v1->bNrInPins, info);
4573 			break;
4574 
4575 		case UDESCSUB_AC_EXTENSION:
4576 			if (is_last) {
4577 				p_id = iot->u.eu_v1->baSourceId;
4578 				n_id = iot->u.eu_v1->bNrInPins;
4579 				goto top;
4580 			}
4581 			uaudio_mixer_find_inputs_sub(
4582 			    root, iot->u.eu_v1->baSourceId,
4583 			    iot->u.eu_v1->bNrInPins, info);
4584 			break;
4585 
4586 		default:
4587 			break;
4588 		}
4589 	}
4590 }
4591 
4592 static void
4593 uaudio20_mixer_find_inputs_sub(struct uaudio_terminal_node *root,
4594     const uint8_t *p_id, uint8_t n_id,
4595     struct uaudio_search_result *info)
4596 {
4597 	struct uaudio_terminal_node *iot;
4598 	uint8_t n;
4599 	uint8_t i;
4600 	uint8_t is_last;
4601 
4602 top:
4603 	for (n = 0; n < n_id; n++) {
4604 
4605 		i = p_id[n];
4606 
4607 		if (info->recurse_level == UAUDIO_RECURSE_LIMIT) {
4608 			DPRINTF("avoided going into a circle at id=%d!\n", i);
4609 			return;
4610 		}
4611 
4612 		info->recurse_level++;
4613 
4614 		iot = (root + i);
4615 
4616 		if (iot->u.desc == NULL)
4617 			continue;
4618 
4619 		is_last = ((n + 1) == n_id);
4620 
4621 		switch (iot->u.desc->bDescriptorSubtype) {
4622 		case UDESCSUB_AC_INPUT:
4623 			info->bit_input[i / 8] |= (1 << (i % 8));
4624 			break;
4625 
4626 		case UDESCSUB_AC_OUTPUT:
4627 			if (is_last) {
4628 				p_id = &iot->u.ot_v2->bSourceId;
4629 				n_id = 1;
4630 				goto top;
4631 			}
4632 			uaudio20_mixer_find_inputs_sub(
4633 			    root, &iot->u.ot_v2->bSourceId, 1, info);
4634 			break;
4635 
4636 		case UDESCSUB_AC_MIXER:
4637 			if (is_last) {
4638 				p_id = iot->u.mu_v2->baSourceId;
4639 				n_id = iot->u.mu_v2->bNrInPins;
4640 				goto top;
4641 			}
4642 			uaudio20_mixer_find_inputs_sub(
4643 			    root, iot->u.mu_v2->baSourceId,
4644 			    iot->u.mu_v2->bNrInPins, info);
4645 			break;
4646 
4647 		case UDESCSUB_AC_SELECTOR:
4648 			if (is_last) {
4649 				p_id = iot->u.su_v2->baSourceId;
4650 				n_id = iot->u.su_v2->bNrInPins;
4651 				goto top;
4652 			}
4653 			uaudio20_mixer_find_inputs_sub(
4654 			    root, iot->u.su_v2->baSourceId,
4655 			    iot->u.su_v2->bNrInPins, info);
4656 			break;
4657 
4658 		case UDESCSUB_AC_SAMPLE_RT:
4659 			if (is_last) {
4660 				p_id = &iot->u.ru_v2->bSourceId;
4661 				n_id = 1;
4662 				goto top;
4663 			}
4664 			uaudio20_mixer_find_inputs_sub(
4665 			    root, &iot->u.ru_v2->bSourceId,
4666 			    1, info);
4667 			break;
4668 
4669 		case UDESCSUB_AC_EFFECT:
4670 			if (is_last) {
4671 				p_id = &iot->u.ef_v2->bSourceId;
4672 				n_id = 1;
4673 				goto top;
4674 			}
4675 			uaudio20_mixer_find_inputs_sub(
4676 			    root, &iot->u.ef_v2->bSourceId,
4677 			    1, info);
4678 			break;
4679 
4680 		case UDESCSUB_AC_FEATURE:
4681 			if (is_last) {
4682 				p_id = &iot->u.fu_v2->bSourceId;
4683 				n_id = 1;
4684 				goto top;
4685 			}
4686 			uaudio20_mixer_find_inputs_sub(
4687 			    root, &iot->u.fu_v2->bSourceId, 1, info);
4688 			break;
4689 
4690 		case UDESCSUB_AC_PROCESSING_V2:
4691 			if (is_last) {
4692 				p_id = iot->u.pu_v2->baSourceId;
4693 				n_id = iot->u.pu_v2->bNrInPins;
4694 				goto top;
4695 			}
4696 			uaudio20_mixer_find_inputs_sub(
4697 			    root, iot->u.pu_v2->baSourceId,
4698 			    iot->u.pu_v2->bNrInPins, info);
4699 			break;
4700 
4701 		case UDESCSUB_AC_EXTENSION_V2:
4702 			if (is_last) {
4703 				p_id = iot->u.eu_v2->baSourceId;
4704 				n_id = iot->u.eu_v2->bNrInPins;
4705 				goto top;
4706 			}
4707 			uaudio20_mixer_find_inputs_sub(
4708 			    root, iot->u.eu_v2->baSourceId,
4709 			    iot->u.eu_v2->bNrInPins, info);
4710 			break;
4711 		default:
4712 			break;
4713 		}
4714 	}
4715 }
4716 
4717 static void
4718 uaudio20_mixer_find_clocks_sub(struct uaudio_terminal_node *root,
4719     const uint8_t *p_id, uint8_t n_id,
4720     struct uaudio_search_result *info)
4721 {
4722 	struct uaudio_terminal_node *iot;
4723 	uint8_t n;
4724 	uint8_t i;
4725 	uint8_t is_last;
4726 	uint8_t id;
4727 
4728 top:
4729 	for (n = 0; n < n_id; n++) {
4730 
4731 		i = p_id[n];
4732 
4733 		if (info->recurse_level == UAUDIO_RECURSE_LIMIT) {
4734 			DPRINTF("avoided going into a circle at id=%d!\n", i);
4735 			return;
4736 		}
4737 
4738 		info->recurse_level++;
4739 
4740 		iot = (root + i);
4741 
4742 		if (iot->u.desc == NULL)
4743 			continue;
4744 
4745 		is_last = ((n + 1) == n_id);
4746 
4747 		switch (iot->u.desc->bDescriptorSubtype) {
4748 		case UDESCSUB_AC_INPUT:
4749 			info->is_input = 1;
4750 			if (is_last) {
4751 				p_id = &iot->u.it_v2->bCSourceId;
4752 				n_id = 1;
4753 				goto top;
4754 			}
4755 			uaudio20_mixer_find_clocks_sub(root,
4756 			    &iot->u.it_v2->bCSourceId, 1, info);
4757 			break;
4758 
4759 		case UDESCSUB_AC_OUTPUT:
4760 			info->is_input = 0;
4761 			if (is_last) {
4762 				p_id = &iot->u.ot_v2->bCSourceId;
4763 				n_id = 1;
4764 				goto top;
4765 			}
4766 			uaudio20_mixer_find_clocks_sub(root,
4767 			    &iot->u.ot_v2->bCSourceId, 1, info);
4768 			break;
4769 
4770 		case UDESCSUB_AC_CLOCK_SEL:
4771 			if (is_last) {
4772 				p_id = iot->u.csel_v2->baCSourceId;
4773 				n_id = iot->u.csel_v2->bNrInPins;
4774 				goto top;
4775 			}
4776 			uaudio20_mixer_find_clocks_sub(root,
4777 			    iot->u.csel_v2->baCSourceId,
4778 			    iot->u.csel_v2->bNrInPins, info);
4779 			break;
4780 
4781 		case UDESCSUB_AC_CLOCK_MUL:
4782 			if (is_last) {
4783 				p_id = &iot->u.cmul_v2->bCSourceId;
4784 				n_id = 1;
4785 				goto top;
4786 			}
4787 			uaudio20_mixer_find_clocks_sub(root,
4788 			    &iot->u.cmul_v2->bCSourceId,
4789 			    1, info);
4790 			break;
4791 
4792 		case UDESCSUB_AC_CLOCK_SRC:
4793 
4794 			id = iot->u.csrc_v2->bClockId;
4795 
4796 			switch (info->is_input) {
4797 			case 0:
4798 				info->bit_output[id / 8] |= (1 << (id % 8));
4799 				break;
4800 			case 1:
4801 				info->bit_input[id / 8] |= (1 << (id % 8));
4802 				break;
4803 			default:
4804 				break;
4805 			}
4806 			break;
4807 
4808 		default:
4809 			break;
4810 		}
4811 	}
4812 }
4813 
4814 static void
4815 uaudio_mixer_find_outputs_sub(struct uaudio_terminal_node *root, uint8_t id,
4816     uint8_t n_id, struct uaudio_search_result *info)
4817 {
4818 	struct uaudio_terminal_node *iot = (root + id);
4819 	uint8_t j;
4820 
4821 	j = n_id;
4822 	do {
4823 		if ((j != id) && ((root + j)->u.desc) &&
4824 		    ((root + j)->u.desc->bDescriptorSubtype == UDESCSUB_AC_OUTPUT)) {
4825 
4826 			/*
4827 			 * "j" (output) <--- virtual wire <--- "id" (input)
4828 			 *
4829 			 * if "j" has "id" on the input, then "id" have "j" on
4830 			 * the output, because they are connected:
4831 			 */
4832 			if ((root + j)->usr.bit_input[id / 8] & (1 << (id % 8))) {
4833 				iot->usr.bit_output[j / 8] |= (1 << (j % 8));
4834 			}
4835 		}
4836 	} while (j--);
4837 }
4838 
4839 static void
4840 uaudio_mixer_fill_info(struct uaudio_softc *sc,
4841     struct usb_device *udev, void *desc)
4842 {
4843 	const struct usb_audio_control_descriptor *acdp;
4844 	struct usb_config_descriptor *cd = usbd_get_config_descriptor(udev);
4845 	const struct usb_descriptor *dp;
4846 	const struct usb_audio_unit *au;
4847 	struct uaudio_terminal_node *iot = NULL;
4848 	uint16_t wTotalLen;
4849 	uint8_t ID_max = 0;		/* inclusive */
4850 	uint8_t i;
4851 
4852 	desc = usb_desc_foreach(cd, desc);
4853 
4854 	if (desc == NULL) {
4855 		DPRINTF("no Audio Control header\n");
4856 		goto done;
4857 	}
4858 	acdp = desc;
4859 
4860 	if ((acdp->bLength < sizeof(*acdp)) ||
4861 	    (acdp->bDescriptorType != UDESC_CS_INTERFACE) ||
4862 	    (acdp->bDescriptorSubtype != UDESCSUB_AC_HEADER)) {
4863 		DPRINTF("invalid Audio Control header\n");
4864 		goto done;
4865 	}
4866 	/* "wTotalLen" is allowed to be corrupt */
4867 	wTotalLen = UGETW(acdp->wTotalLength) - acdp->bLength;
4868 
4869 	/* get USB audio revision */
4870 	sc->sc_audio_rev = UGETW(acdp->bcdADC);
4871 
4872 	DPRINTFN(3, "found AC header, vers=%03x, len=%d\n",
4873 	    sc->sc_audio_rev, wTotalLen);
4874 
4875 	iot = malloc(sizeof(struct uaudio_terminal_node) * 256, M_TEMP,
4876 	    M_WAITOK | M_ZERO);
4877 
4878 	if (iot == NULL) {
4879 		DPRINTF("no memory!\n");
4880 		goto done;
4881 	}
4882 	while ((desc = usb_desc_foreach(cd, desc))) {
4883 
4884 		dp = desc;
4885 
4886 		if (dp->bLength > wTotalLen) {
4887 			break;
4888 		} else {
4889 			wTotalLen -= dp->bLength;
4890 		}
4891 
4892 		if (sc->sc_audio_rev >= UAUDIO_VERSION_30)
4893 			au = NULL;
4894 		else if (sc->sc_audio_rev >= UAUDIO_VERSION_20)
4895 			au = uaudio20_mixer_verify_desc(dp, 0);
4896 		else
4897 			au = uaudio_mixer_verify_desc(dp, 0);
4898 
4899 		if (au) {
4900 			iot[au->bUnitId].u.desc = (const void *)au;
4901 			if (au->bUnitId > ID_max)
4902 				ID_max = au->bUnitId;
4903 		}
4904 	}
4905 
4906 	DPRINTF("Maximum ID=%d\n", ID_max);
4907 
4908 	/*
4909 	 * determine sourcing inputs for
4910 	 * all nodes in the tree:
4911 	 */
4912 	i = ID_max;
4913 	do {
4914 		if (sc->sc_audio_rev >= UAUDIO_VERSION_30) {
4915 			/* FALLTHROUGH */
4916 		} else if (sc->sc_audio_rev >= UAUDIO_VERSION_20) {
4917 			uaudio20_mixer_find_inputs_sub(iot,
4918 			    &i, 1, &((iot + i)->usr));
4919 
4920 			sc->sc_mixer_clocks.is_input = 255;
4921 			sc->sc_mixer_clocks.recurse_level = 0;
4922 
4923 			uaudio20_mixer_find_clocks_sub(iot,
4924 			    &i, 1, &sc->sc_mixer_clocks);
4925 		} else {
4926 			uaudio_mixer_find_inputs_sub(iot,
4927 			    &i, 1, &((iot + i)->usr));
4928 		}
4929 	} while (i--);
4930 
4931 	/*
4932 	 * determine outputs for
4933 	 * all nodes in the tree:
4934 	 */
4935 	i = ID_max;
4936 	do {
4937 		uaudio_mixer_find_outputs_sub(iot,
4938 		    i, ID_max, &((iot + i)->usr));
4939 	} while (i--);
4940 
4941 	/* set "id_max" and "root" */
4942 
4943 	i = ID_max;
4944 	do {
4945 		(iot + i)->usr.id_max = ID_max;
4946 		(iot + i)->root = iot;
4947 	} while (i--);
4948 
4949 	/*
4950 	 * Scan the config to create a linked list of "mixer" nodes:
4951 	 */
4952 
4953 	i = ID_max;
4954 	do {
4955 		dp = iot[i].u.desc;
4956 
4957 		if (dp == NULL)
4958 			continue;
4959 
4960 		DPRINTFN(11, "id=%d subtype=%d\n",
4961 		    i, dp->bDescriptorSubtype);
4962 
4963 		if (sc->sc_audio_rev >= UAUDIO_VERSION_30) {
4964 			continue;
4965 		} else if (sc->sc_audio_rev >= UAUDIO_VERSION_20) {
4966 
4967 			switch (dp->bDescriptorSubtype) {
4968 			case UDESCSUB_AC_HEADER:
4969 				DPRINTF("unexpected AC header\n");
4970 				break;
4971 
4972 			case UDESCSUB_AC_INPUT:
4973 			case UDESCSUB_AC_OUTPUT:
4974 			case UDESCSUB_AC_PROCESSING_V2:
4975 			case UDESCSUB_AC_EXTENSION_V2:
4976 			case UDESCSUB_AC_EFFECT:
4977 			case UDESCSUB_AC_CLOCK_SRC:
4978 			case UDESCSUB_AC_CLOCK_SEL:
4979 			case UDESCSUB_AC_CLOCK_MUL:
4980 			case UDESCSUB_AC_SAMPLE_RT:
4981 				break;
4982 
4983 			case UDESCSUB_AC_MIXER:
4984 				uaudio20_mixer_add_mixer(sc, iot, i);
4985 				break;
4986 
4987 			case UDESCSUB_AC_SELECTOR:
4988 				uaudio20_mixer_add_selector(sc, iot, i);
4989 				break;
4990 
4991 			case UDESCSUB_AC_FEATURE:
4992 				uaudio20_mixer_add_feature(sc, iot, i);
4993 				break;
4994 
4995 			default:
4996 				DPRINTF("bad AC desc subtype=0x%02x\n",
4997 				    dp->bDescriptorSubtype);
4998 				break;
4999 			}
5000 			continue;
5001 		}
5002 
5003 		switch (dp->bDescriptorSubtype) {
5004 		case UDESCSUB_AC_HEADER:
5005 			DPRINTF("unexpected AC header\n");
5006 			break;
5007 
5008 		case UDESCSUB_AC_INPUT:
5009 		case UDESCSUB_AC_OUTPUT:
5010 			break;
5011 
5012 		case UDESCSUB_AC_MIXER:
5013 			uaudio_mixer_add_mixer(sc, iot, i);
5014 			break;
5015 
5016 		case UDESCSUB_AC_SELECTOR:
5017 			uaudio_mixer_add_selector(sc, iot, i);
5018 			break;
5019 
5020 		case UDESCSUB_AC_FEATURE:
5021 			uaudio_mixer_add_feature(sc, iot, i);
5022 			break;
5023 
5024 		case UDESCSUB_AC_PROCESSING:
5025 			uaudio_mixer_add_processing(sc, iot, i);
5026 			break;
5027 
5028 		case UDESCSUB_AC_EXTENSION:
5029 			uaudio_mixer_add_extension(sc, iot, i);
5030 			break;
5031 
5032 		default:
5033 			DPRINTF("bad AC desc subtype=0x%02x\n",
5034 			    dp->bDescriptorSubtype);
5035 			break;
5036 		}
5037 
5038 	} while (i--);
5039 
5040 done:
5041 	free(iot, M_TEMP);
5042 }
5043 
5044 static int
5045 uaudio_mixer_get(struct usb_device *udev, uint16_t audio_rev,
5046     uint8_t what, struct uaudio_mixer_node *mc)
5047 {
5048 	struct usb_device_request req;
5049 	int val;
5050 	uint8_t data[2 + (2 * 3)];
5051 	usb_error_t err;
5052 
5053 	if (mc->wValue[0] == -1)
5054 		return (0);
5055 
5056 	if (audio_rev >= UAUDIO_VERSION_30)
5057 		return (0);
5058 	else if (audio_rev >= UAUDIO_VERSION_20) {
5059 		if (what == GET_CUR) {
5060 			req.bRequest = UA20_CS_CUR;
5061 			USETW(req.wLength, 2);
5062 		} else {
5063 			req.bRequest = UA20_CS_RANGE;
5064 			USETW(req.wLength, 8);
5065 		}
5066 	} else {
5067 		uint16_t len = MIX_SIZE(mc->type);
5068 
5069 		req.bRequest = what;
5070 		USETW(req.wLength, len);
5071 	}
5072 
5073 	req.bmRequestType = UT_READ_CLASS_INTERFACE;
5074 	USETW(req.wValue, mc->wValue[0]);
5075 	USETW(req.wIndex, mc->wIndex);
5076 
5077 	memset(data, 0, sizeof(data));
5078 
5079 	err = usbd_do_request(udev, NULL, &req, data);
5080 	if (err) {
5081 		DPRINTF("err=%s\n", usbd_errstr(err));
5082 		return (0);
5083 	}
5084 
5085 	if (audio_rev >= UAUDIO_VERSION_30) {
5086 		val = 0;
5087 	} else if (audio_rev >= UAUDIO_VERSION_20) {
5088 		switch (what) {
5089 		case GET_CUR:
5090 			val = (data[0] | (data[1] << 8));
5091 			break;
5092 		case GET_MIN:
5093 			val = (data[2] | (data[3] << 8));
5094 			break;
5095 		case GET_MAX:
5096 			val = (data[4] | (data[5] << 8));
5097 			break;
5098 		case GET_RES:
5099 			val = (data[6] | (data[7] << 8));
5100 			break;
5101 		default:
5102 			val = 0;
5103 			break;
5104 		}
5105 	} else {
5106 		val = (data[0] | (data[1] << 8));
5107 	}
5108 
5109 	if (what == GET_CUR || what == GET_MIN || what == GET_MAX)
5110 		val = uaudio_mixer_signext(mc->type, val);
5111 
5112 	DPRINTFN(3, "val=%d\n", val);
5113 
5114 	return (val);
5115 }
5116 
5117 static void
5118 uaudio_mixer_write_cfg_callback(struct usb_xfer *xfer, usb_error_t error)
5119 {
5120 	struct usb_device_request req;
5121 	struct uaudio_softc *sc = usbd_xfer_softc(xfer);
5122 	struct uaudio_mixer_node *mc = sc->sc_mixer_curr;
5123 	struct usb_page_cache *pc;
5124 	uint16_t len;
5125 	uint8_t repeat = 1;
5126 	uint8_t update;
5127 	uint8_t chan;
5128 	uint8_t buf[2];
5129 
5130 	DPRINTF("\n");
5131 
5132 	switch (USB_GET_STATE(xfer)) {
5133 	case USB_ST_TRANSFERRED:
5134 tr_transferred:
5135 	case USB_ST_SETUP:
5136 tr_setup:
5137 
5138 		if (mc == NULL) {
5139 			mc = sc->sc_mixer_root;
5140 			sc->sc_mixer_curr = mc;
5141 			sc->sc_mixer_chan = 0;
5142 			repeat = 0;
5143 		}
5144 		while (mc) {
5145 			while (sc->sc_mixer_chan < mc->nchan) {
5146 
5147 				chan = sc->sc_mixer_chan;
5148 
5149 				sc->sc_mixer_chan++;
5150 
5151 				update = ((mc->update[chan / 8] & (1 << (chan % 8))) &&
5152 				    (mc->wValue[chan] != -1));
5153 
5154 				mc->update[chan / 8] &= ~(1 << (chan % 8));
5155 
5156 				if (update) {
5157 
5158 					req.bmRequestType = UT_WRITE_CLASS_INTERFACE;
5159 					USETW(req.wValue, mc->wValue[chan]);
5160 					USETW(req.wIndex, mc->wIndex);
5161 
5162 					if (sc->sc_audio_rev >= UAUDIO_VERSION_30) {
5163 						return;
5164 					} else if (sc->sc_audio_rev >= UAUDIO_VERSION_20) {
5165 						len = 2;
5166 						req.bRequest = UA20_CS_CUR;
5167 						USETW(req.wLength, len);
5168 					} else {
5169 						len = MIX_SIZE(mc->type);
5170 						req.bRequest = SET_CUR;
5171 						USETW(req.wLength, len);
5172 					}
5173 
5174 					buf[0] = (mc->wData[chan] & 0xFF);
5175 					buf[1] = (mc->wData[chan] >> 8) & 0xFF;
5176 
5177 					pc = usbd_xfer_get_frame(xfer, 0);
5178 					usbd_copy_in(pc, 0, &req, sizeof(req));
5179 					pc = usbd_xfer_get_frame(xfer, 1);
5180 					usbd_copy_in(pc, 0, buf, len);
5181 
5182 					usbd_xfer_set_frame_len(xfer, 0, sizeof(req));
5183 					usbd_xfer_set_frame_len(xfer, 1, len);
5184 					usbd_xfer_set_frames(xfer, len ? 2 : 1);
5185 					usbd_transfer_submit(xfer);
5186 					return;
5187 				}
5188 			}
5189 
5190 			mc = mc->next;
5191 			sc->sc_mixer_curr = mc;
5192 			sc->sc_mixer_chan = 0;
5193 		}
5194 
5195 		if (repeat) {
5196 			goto tr_setup;
5197 		}
5198 		break;
5199 
5200 	default:			/* Error */
5201 		DPRINTF("error=%s\n", usbd_errstr(error));
5202 		if (error == USB_ERR_CANCELLED) {
5203 			/* do nothing - we are detaching */
5204 			break;
5205 		}
5206 		goto tr_transferred;
5207 	}
5208 }
5209 
5210 static usb_error_t
5211 uaudio_set_speed(struct usb_device *udev, uint8_t endpt, uint32_t speed)
5212 {
5213 	struct usb_device_request req;
5214 	uint8_t data[3];
5215 
5216 	DPRINTFN(6, "endpt=%d speed=%u\n", endpt, speed);
5217 
5218 	req.bmRequestType = UT_WRITE_CLASS_ENDPOINT;
5219 	req.bRequest = SET_CUR;
5220 	USETW2(req.wValue, SAMPLING_FREQ_CONTROL, 0);
5221 	USETW(req.wIndex, endpt);
5222 	USETW(req.wLength, 3);
5223 	data[0] = speed;
5224 	data[1] = speed >> 8;
5225 	data[2] = speed >> 16;
5226 
5227 	return (usbd_do_request(udev, NULL, &req, data));
5228 }
5229 
5230 static usb_error_t
5231 uaudio20_set_speed(struct usb_device *udev, uint8_t iface_no,
5232     uint8_t clockid, uint32_t speed)
5233 {
5234 	struct usb_device_request req;
5235 	uint8_t data[4];
5236 
5237 	DPRINTFN(6, "ifaceno=%d clockid=%d speed=%u\n",
5238 	    iface_no, clockid, speed);
5239 
5240 	req.bmRequestType = UT_WRITE_CLASS_INTERFACE;
5241 	req.bRequest = UA20_CS_CUR;
5242 	USETW2(req.wValue, UA20_CS_SAM_FREQ_CONTROL, 0);
5243 	USETW2(req.wIndex, clockid, iface_no);
5244 	USETW(req.wLength, 4);
5245 	data[0] = speed;
5246 	data[1] = speed >> 8;
5247 	data[2] = speed >> 16;
5248 	data[3] = speed >> 24;
5249 
5250 	return (usbd_do_request(udev, NULL, &req, data));
5251 }
5252 
5253 static int
5254 uaudio_mixer_signext(uint8_t type, int val)
5255 {
5256 	if (!MIX_UNSIGNED(type)) {
5257 		if (MIX_SIZE(type) == 2) {
5258 			val = (int16_t)val;
5259 		} else {
5260 			val = (int8_t)val;
5261 		}
5262 	}
5263 	return (val);
5264 }
5265 
5266 static int
5267 uaudio_mixer_bsd2value(struct uaudio_mixer_node *mc, int32_t val)
5268 {
5269 	if (mc->type == MIX_ON_OFF) {
5270 		val = (val != 0);
5271 	} else if (mc->type == MIX_SELECTOR) {
5272 		if ((val < mc->minval) ||
5273 		    (val > mc->maxval)) {
5274 			val = mc->minval;
5275 		}
5276 	} else {
5277 
5278 		/* compute actual volume */
5279 		val = (val * mc->mul) / 255;
5280 
5281 		/* add lower offset */
5282 		val = val + mc->minval;
5283 
5284 		/* make sure we don't write a value out of range */
5285 		if (val > mc->maxval)
5286 			val = mc->maxval;
5287 		else if (val < mc->minval)
5288 			val = mc->minval;
5289 	}
5290 
5291 	DPRINTFN(6, "type=0x%03x val=%d min=%d max=%d val=%d\n",
5292 	    mc->type, val, mc->minval, mc->maxval, val);
5293 	return (val);
5294 }
5295 
5296 static void
5297 uaudio_mixer_ctl_set(struct uaudio_softc *sc, struct uaudio_mixer_node *mc,
5298     uint8_t chan, int32_t val)
5299 {
5300 	val = uaudio_mixer_bsd2value(mc, val);
5301 
5302 	mc->update[chan / 8] |= (1 << (chan % 8));
5303 	mc->wData[chan] = val;
5304 
5305 	/* start the transfer, if not already started */
5306 
5307 	usbd_transfer_start(sc->sc_mixer_xfer[0]);
5308 }
5309 
5310 static void
5311 uaudio_mixer_init(struct uaudio_softc *sc)
5312 {
5313 	struct uaudio_mixer_node *mc;
5314 	int32_t i;
5315 
5316 	for (mc = sc->sc_mixer_root; mc;
5317 	    mc = mc->next) {
5318 
5319 		if (mc->ctl != SOUND_MIXER_NRDEVICES) {
5320 			/*
5321 			 * Set device mask bits. See
5322 			 * /usr/include/machine/soundcard.h
5323 			 */
5324 			sc->sc_mix_info |= (1 << mc->ctl);
5325 		}
5326 		if ((mc->ctl == SOUND_MIXER_NRDEVICES) &&
5327 		    (mc->type == MIX_SELECTOR)) {
5328 
5329 			for (i = mc->minval; (i > 0) && (i <= mc->maxval); i++) {
5330 				if (mc->slctrtype[i - 1] == SOUND_MIXER_NRDEVICES) {
5331 					continue;
5332 				}
5333 				sc->sc_recsrc_info |= 1 << mc->slctrtype[i - 1];
5334 			}
5335 		}
5336 	}
5337 }
5338 
5339 int
5340 uaudio_mixer_init_sub(struct uaudio_softc *sc, struct snd_mixer *m)
5341 {
5342 	DPRINTF("\n");
5343 
5344 	sc->sc_mixer_lock = mixer_get_lock(m);
5345 	sc->sc_mixer_dev = m;
5346 
5347 	if (usbd_transfer_setup(sc->sc_udev, &sc->sc_mixer_iface_index,
5348 	    sc->sc_mixer_xfer, uaudio_mixer_config, 1, sc,
5349 	    sc->sc_mixer_lock)) {
5350 		DPRINTFN(0, "could not allocate USB "
5351 		    "transfer for audio mixer!\n");
5352 		return (ENOMEM);
5353 	}
5354 	if (!(sc->sc_mix_info & SOUND_MASK_VOLUME)) {
5355 		mix_setparentchild(m, SOUND_MIXER_VOLUME, SOUND_MASK_PCM);
5356 		mix_setrealdev(m, SOUND_MIXER_VOLUME, SOUND_MIXER_NONE);
5357 	}
5358 	mix_setdevs(m, sc->sc_mix_info);
5359 	mix_setrecdevs(m, sc->sc_recsrc_info);
5360 	return (0);
5361 }
5362 
5363 int
5364 uaudio_mixer_uninit_sub(struct uaudio_softc *sc)
5365 {
5366 	DPRINTF("\n");
5367 
5368 	usbd_transfer_unsetup(sc->sc_mixer_xfer, 1);
5369 
5370 	sc->sc_mixer_lock = NULL;
5371 
5372 	return (0);
5373 }
5374 
5375 void
5376 uaudio_mixer_set(struct uaudio_softc *sc, unsigned type,
5377     unsigned left, unsigned right)
5378 {
5379 	struct uaudio_mixer_node *mc;
5380 	int chan;
5381 
5382 	for (mc = sc->sc_mixer_root; mc != NULL; mc = mc->next) {
5383 
5384 		if (mc->ctl == type) {
5385 			for (chan = 0; chan < mc->nchan; chan++) {
5386 				uaudio_mixer_ctl_set(sc, mc, chan,
5387 				    (int)((chan == 0 ? left : right) *
5388 				    255) / 100);
5389 			}
5390 		}
5391 	}
5392 }
5393 
5394 uint32_t
5395 uaudio_mixer_setrecsrc(struct uaudio_softc *sc, uint32_t src)
5396 {
5397 	struct uaudio_mixer_node *mc;
5398 	uint32_t mask;
5399 	uint32_t temp;
5400 	int32_t i;
5401 
5402 	for (mc = sc->sc_mixer_root; mc;
5403 	    mc = mc->next) {
5404 
5405 		if ((mc->ctl == SOUND_MIXER_NRDEVICES) &&
5406 		    (mc->type == MIX_SELECTOR)) {
5407 
5408 			/* compute selector mask */
5409 
5410 			mask = 0;
5411 			for (i = mc->minval; (i > 0) && (i <= mc->maxval); i++) {
5412 				mask |= (1 << mc->slctrtype[i - 1]);
5413 			}
5414 
5415 			temp = mask & src;
5416 			if (temp == 0) {
5417 				continue;
5418 			}
5419 			/* find the first set bit */
5420 			temp = (-temp) & temp;
5421 
5422 			/* update "src" */
5423 			src &= ~mask;
5424 			src |= temp;
5425 
5426 			for (i = mc->minval; (i > 0) && (i <= mc->maxval); i++) {
5427 				if (temp != (1 << mc->slctrtype[i - 1])) {
5428 					continue;
5429 				}
5430 				uaudio_mixer_ctl_set(sc, mc, 0, i);
5431 				break;
5432 			}
5433 		}
5434 	}
5435 	return (src);
5436 }
5437 
5438 /*========================================================================*
5439  * MIDI support routines
5440  *========================================================================*/
5441 
5442 static void
5443 umidi_bulk_read_callback(struct usb_xfer *xfer, usb_error_t error)
5444 {
5445 	struct umidi_chan *chan = usbd_xfer_softc(xfer);
5446 	struct umidi_sub_chan *sub;
5447 	struct usb_page_cache *pc;
5448 	uint8_t buf[4];
5449 	uint8_t cmd_len;
5450 	uint8_t cn;
5451 	uint16_t pos;
5452 	int actlen;
5453 
5454 	usbd_xfer_status(xfer, &actlen, NULL, NULL, NULL);
5455 
5456 	switch (USB_GET_STATE(xfer)) {
5457 	case USB_ST_TRANSFERRED:
5458 
5459 		DPRINTF("actlen=%d bytes\n", actlen);
5460 
5461 		pos = 0;
5462 		pc = usbd_xfer_get_frame(xfer, 0);
5463 
5464 		while (actlen >= 4) {
5465 
5466 			/* copy out the MIDI data */
5467 			usbd_copy_out(pc, pos, buf, 4);
5468 			/* command length */
5469 			cmd_len = umidi_cmd_to_len[buf[0] & 0xF];
5470 			/* cable number */
5471 			cn = buf[0] >> 4;
5472 			/*
5473 			 * Lookup sub-channel. The index is range
5474 			 * checked below.
5475 			 */
5476 			sub = &chan->sub[cn];
5477 
5478 			if ((cmd_len != 0) && (cn < chan->max_emb_jack) &&
5479 			    (sub->read_open != 0)) {
5480 
5481 				/* Send data to the application */
5482 				usb_fifo_put_data_linear(
5483 				    sub->fifo.fp[USB_FIFO_RX],
5484 				    buf + 1, cmd_len, 1);
5485 			}
5486 			actlen -= 4;
5487 			pos += 4;
5488 		}
5489 
5490 	case USB_ST_SETUP:
5491 		DPRINTF("start\n");
5492 tr_setup:
5493 		usbd_xfer_set_frame_len(xfer, 0, usbd_xfer_max_len(xfer));
5494 		usbd_transfer_submit(xfer);
5495 		break;
5496 
5497 	default:
5498 		DPRINTF("error=%s\n", usbd_errstr(error));
5499 
5500 		if (error != USB_ERR_CANCELLED) {
5501 			/* try to clear stall first */
5502 			usbd_xfer_set_stall(xfer);
5503 			goto tr_setup;
5504 		}
5505 		break;
5506 	}
5507 }
5508 
5509 /*
5510  * The following statemachine, that converts MIDI commands to
5511  * USB MIDI packets, derives from Linux's usbmidi.c, which
5512  * was written by "Clemens Ladisch":
5513  *
5514  * Returns:
5515  *    0: No command
5516  * Else: Command is complete
5517  */
5518 static uint8_t
5519 umidi_convert_to_usb(struct umidi_sub_chan *sub, uint8_t cn, uint8_t b)
5520 {
5521 	uint8_t p0 = (cn << 4);
5522 
5523 	if (b >= 0xf8) {
5524 		sub->temp_0[0] = p0 | 0x0f;
5525 		sub->temp_0[1] = b;
5526 		sub->temp_0[2] = 0;
5527 		sub->temp_0[3] = 0;
5528 		sub->temp_cmd = sub->temp_0;
5529 		return (1);
5530 
5531 	} else if (b >= 0xf0) {
5532 		switch (b) {
5533 		case 0xf0:		/* system exclusive begin */
5534 			sub->temp_1[1] = b;
5535 			sub->state = UMIDI_ST_SYSEX_1;
5536 			break;
5537 		case 0xf1:		/* MIDI time code */
5538 		case 0xf3:		/* song select */
5539 			sub->temp_1[1] = b;
5540 			sub->state = UMIDI_ST_1PARAM;
5541 			break;
5542 		case 0xf2:		/* song position pointer */
5543 			sub->temp_1[1] = b;
5544 			sub->state = UMIDI_ST_2PARAM_1;
5545 			break;
5546 		case 0xf4:		/* unknown */
5547 		case 0xf5:		/* unknown */
5548 			sub->state = UMIDI_ST_UNKNOWN;
5549 			break;
5550 		case 0xf6:		/* tune request */
5551 			sub->temp_1[0] = p0 | 0x05;
5552 			sub->temp_1[1] = 0xf6;
5553 			sub->temp_1[2] = 0;
5554 			sub->temp_1[3] = 0;
5555 			sub->temp_cmd = sub->temp_1;
5556 			sub->state = UMIDI_ST_UNKNOWN;
5557 			return (1);
5558 
5559 		case 0xf7:		/* system exclusive end */
5560 			switch (sub->state) {
5561 			case UMIDI_ST_SYSEX_0:
5562 				sub->temp_1[0] = p0 | 0x05;
5563 				sub->temp_1[1] = 0xf7;
5564 				sub->temp_1[2] = 0;
5565 				sub->temp_1[3] = 0;
5566 				sub->temp_cmd = sub->temp_1;
5567 				sub->state = UMIDI_ST_UNKNOWN;
5568 				return (1);
5569 			case UMIDI_ST_SYSEX_1:
5570 				sub->temp_1[0] = p0 | 0x06;
5571 				sub->temp_1[2] = 0xf7;
5572 				sub->temp_1[3] = 0;
5573 				sub->temp_cmd = sub->temp_1;
5574 				sub->state = UMIDI_ST_UNKNOWN;
5575 				return (1);
5576 			case UMIDI_ST_SYSEX_2:
5577 				sub->temp_1[0] = p0 | 0x07;
5578 				sub->temp_1[3] = 0xf7;
5579 				sub->temp_cmd = sub->temp_1;
5580 				sub->state = UMIDI_ST_UNKNOWN;
5581 				return (1);
5582 			}
5583 			sub->state = UMIDI_ST_UNKNOWN;
5584 			break;
5585 		}
5586 	} else if (b >= 0x80) {
5587 		sub->temp_1[1] = b;
5588 		if ((b >= 0xc0) && (b <= 0xdf)) {
5589 			sub->state = UMIDI_ST_1PARAM;
5590 		} else {
5591 			sub->state = UMIDI_ST_2PARAM_1;
5592 		}
5593 	} else {			/* b < 0x80 */
5594 		switch (sub->state) {
5595 		case UMIDI_ST_1PARAM:
5596 			if (sub->temp_1[1] < 0xf0) {
5597 				p0 |= sub->temp_1[1] >> 4;
5598 			} else {
5599 				p0 |= 0x02;
5600 				sub->state = UMIDI_ST_UNKNOWN;
5601 			}
5602 			sub->temp_1[0] = p0;
5603 			sub->temp_1[2] = b;
5604 			sub->temp_1[3] = 0;
5605 			sub->temp_cmd = sub->temp_1;
5606 			return (1);
5607 		case UMIDI_ST_2PARAM_1:
5608 			sub->temp_1[2] = b;
5609 			sub->state = UMIDI_ST_2PARAM_2;
5610 			break;
5611 		case UMIDI_ST_2PARAM_2:
5612 			if (sub->temp_1[1] < 0xf0) {
5613 				p0 |= sub->temp_1[1] >> 4;
5614 				sub->state = UMIDI_ST_2PARAM_1;
5615 			} else {
5616 				p0 |= 0x03;
5617 				sub->state = UMIDI_ST_UNKNOWN;
5618 			}
5619 			sub->temp_1[0] = p0;
5620 			sub->temp_1[3] = b;
5621 			sub->temp_cmd = sub->temp_1;
5622 			return (1);
5623 		case UMIDI_ST_SYSEX_0:
5624 			sub->temp_1[1] = b;
5625 			sub->state = UMIDI_ST_SYSEX_1;
5626 			break;
5627 		case UMIDI_ST_SYSEX_1:
5628 			sub->temp_1[2] = b;
5629 			sub->state = UMIDI_ST_SYSEX_2;
5630 			break;
5631 		case UMIDI_ST_SYSEX_2:
5632 			sub->temp_1[0] = p0 | 0x04;
5633 			sub->temp_1[3] = b;
5634 			sub->temp_cmd = sub->temp_1;
5635 			sub->state = UMIDI_ST_SYSEX_0;
5636 			return (1);
5637 		default:
5638 			break;
5639 		}
5640 	}
5641 	return (0);
5642 }
5643 
5644 static void
5645 umidi_bulk_write_callback(struct usb_xfer *xfer, usb_error_t error)
5646 {
5647 	struct umidi_chan *chan = usbd_xfer_softc(xfer);
5648 	struct umidi_sub_chan *sub;
5649 	struct usb_page_cache *pc;
5650 	uint32_t actlen;
5651 	uint16_t nframes;
5652 	uint8_t buf;
5653 	uint8_t start_cable;
5654 	uint8_t tr_any;
5655 	int len;
5656 
5657 	usbd_xfer_status(xfer, &len, NULL, NULL, NULL);
5658 
5659 	/*
5660 	 * NOTE: Some MIDI devices only accept 4 bytes of data per
5661 	 * short terminated USB transfer.
5662 	 */
5663 	switch (USB_GET_STATE(xfer)) {
5664 	case USB_ST_TRANSFERRED:
5665 		DPRINTF("actlen=%d bytes\n", len);
5666 
5667 	case USB_ST_SETUP:
5668 tr_setup:
5669 		DPRINTF("start\n");
5670 
5671 		nframes = 0;	/* reset */
5672 		start_cable = chan->curr_cable;
5673 		tr_any = 0;
5674 		pc = usbd_xfer_get_frame(xfer, 0);
5675 
5676 		while (1) {
5677 
5678 			/* round robin de-queueing */
5679 
5680 			sub = &chan->sub[chan->curr_cable];
5681 
5682 			if (sub->write_open) {
5683 				usb_fifo_get_data_linear(sub->fifo.fp[USB_FIFO_TX],
5684 				    &buf, 1, &actlen, 0);
5685 			} else {
5686 				actlen = 0;
5687 			}
5688 
5689 			if (actlen) {
5690 
5691 				tr_any = 1;
5692 
5693 				DPRINTF("byte=0x%02x from FIFO %u\n", buf,
5694 				    (unsigned int)chan->curr_cable);
5695 
5696 				if (umidi_convert_to_usb(sub, chan->curr_cable, buf)) {
5697 
5698 					DPRINTF("sub=0x%02x 0x%02x 0x%02x 0x%02x\n",
5699 					    sub->temp_cmd[0], sub->temp_cmd[1],
5700 					    sub->temp_cmd[2], sub->temp_cmd[3]);
5701 
5702 					usbd_copy_in(pc, nframes * 4, sub->temp_cmd, 4);
5703 
5704 					nframes++;
5705 
5706 					if ((nframes >= UMIDI_TX_FRAMES) || (chan->single_command != 0))
5707 						break;
5708 				} else {
5709 					continue;
5710 				}
5711 			}
5712 
5713 			chan->curr_cable++;
5714 			if (chan->curr_cable >= chan->max_emb_jack)
5715 				chan->curr_cable = 0;
5716 
5717 			if (chan->curr_cable == start_cable) {
5718 				if (tr_any == 0)
5719 					break;
5720 				tr_any = 0;
5721 			}
5722 		}
5723 
5724 		if (nframes != 0) {
5725 			DPRINTF("Transferring %d frames\n", (int)nframes);
5726 			usbd_xfer_set_frame_len(xfer, 0, 4 * nframes);
5727 			usbd_transfer_submit(xfer);
5728 		}
5729 		break;
5730 
5731 	default:			/* Error */
5732 
5733 		DPRINTF("error=%s\n", usbd_errstr(error));
5734 
5735 		if (error != USB_ERR_CANCELLED) {
5736 			/* try to clear stall first */
5737 			usbd_xfer_set_stall(xfer);
5738 			goto tr_setup;
5739 		}
5740 		break;
5741 	}
5742 }
5743 
5744 static struct umidi_sub_chan *
5745 umidi_sub_by_fifo(struct usb_fifo *fifo)
5746 {
5747 	struct umidi_chan *chan = usb_fifo_softc(fifo);
5748 	struct umidi_sub_chan *sub;
5749 	uint32_t n;
5750 
5751 	for (n = 0; n < UMIDI_EMB_JACK_MAX; n++) {
5752 		sub = &chan->sub[n];
5753 		if ((sub->fifo.fp[USB_FIFO_RX] == fifo) ||
5754 		    (sub->fifo.fp[USB_FIFO_TX] == fifo)) {
5755 			return (sub);
5756 		}
5757 	}
5758 
5759 	panic("%s:%d cannot find usb_fifo!\n",
5760 	    __FILE__, __LINE__);
5761 
5762 	return (NULL);
5763 }
5764 
5765 static void
5766 umidi_start_read(struct usb_fifo *fifo)
5767 {
5768 	struct umidi_chan *chan = usb_fifo_softc(fifo);
5769 
5770 	usbd_transfer_start(chan->xfer[UMIDI_RX_TRANSFER]);
5771 }
5772 
5773 static void
5774 umidi_stop_read(struct usb_fifo *fifo)
5775 {
5776 	struct umidi_chan *chan = usb_fifo_softc(fifo);
5777 	struct umidi_sub_chan *sub = umidi_sub_by_fifo(fifo);
5778 
5779 	DPRINTF("\n");
5780 
5781 	sub->read_open = 0;
5782 
5783 	if (--(chan->read_open_refcount) == 0) {
5784 		/*
5785 		 * XXX don't stop the read transfer here, hence that causes
5786 		 * problems with some MIDI adapters
5787 		 */
5788 		DPRINTF("(stopping read transfer)\n");
5789 	}
5790 }
5791 
5792 static void
5793 umidi_start_write(struct usb_fifo *fifo)
5794 {
5795 	struct umidi_chan *chan = usb_fifo_softc(fifo);
5796 
5797 	if (chan->xfer[UMIDI_TX_TRANSFER] == NULL) {
5798 		uint8_t buf[1];
5799 		int actlen;
5800 		do {
5801 			/* dump data */
5802 			usb_fifo_get_data_linear(fifo, buf, 1, &actlen, 0);
5803 		} while (actlen > 0);
5804 	} else {
5805 		usbd_transfer_start(chan->xfer[UMIDI_TX_TRANSFER]);
5806 	}
5807 }
5808 
5809 static void
5810 umidi_stop_write(struct usb_fifo *fifo)
5811 {
5812 	struct umidi_chan *chan = usb_fifo_softc(fifo);
5813 	struct umidi_sub_chan *sub = umidi_sub_by_fifo(fifo);
5814 
5815 	DPRINTF("\n");
5816 
5817 	sub->write_open = 0;
5818 
5819 	if (--(chan->write_open_refcount) == 0) {
5820 		DPRINTF("(stopping write transfer)\n");
5821 		usbd_transfer_stop(chan->xfer[UMIDI_TX_TRANSFER]);
5822 	}
5823 }
5824 
5825 static int
5826 umidi_open(struct usb_fifo *fifo, int fflags)
5827 {
5828 	struct umidi_chan *chan = usb_fifo_softc(fifo);
5829 	struct umidi_sub_chan *sub = umidi_sub_by_fifo(fifo);
5830 
5831 	if (fflags & FREAD) {
5832 		if (usb_fifo_alloc_buffer(fifo, 4, (1024 / 4))) {
5833 			return (ENOMEM);
5834 		}
5835 		mtx_lock(&chan->mtx);
5836 		chan->read_open_refcount++;
5837 		sub->read_open = 1;
5838 		mtx_unlock(&chan->mtx);
5839 	}
5840 	if (fflags & FWRITE) {
5841 		if (usb_fifo_alloc_buffer(fifo, 32, (1024 / 32))) {
5842 			return (ENOMEM);
5843 		}
5844 		/* clear stall first */
5845 		mtx_lock(&chan->mtx);
5846 		chan->write_open_refcount++;
5847 		sub->write_open = 1;
5848 
5849 		/* reset */
5850 		sub->state = UMIDI_ST_UNKNOWN;
5851 		mtx_unlock(&chan->mtx);
5852 	}
5853 	return (0);			/* success */
5854 }
5855 
5856 static void
5857 umidi_close(struct usb_fifo *fifo, int fflags)
5858 {
5859 	if (fflags & FREAD) {
5860 		usb_fifo_free_buffer(fifo);
5861 	}
5862 	if (fflags & FWRITE) {
5863 		usb_fifo_free_buffer(fifo);
5864 	}
5865 }
5866 
5867 
5868 static int
5869 umidi_ioctl(struct usb_fifo *fifo, u_long cmd, void *data,
5870     int fflags)
5871 {
5872 	return (ENODEV);
5873 }
5874 
5875 static void
5876 umidi_init(device_t dev)
5877 {
5878 	struct uaudio_softc *sc = device_get_softc(dev);
5879 	struct umidi_chan *chan = &sc->sc_midi_chan;
5880 
5881 	mtx_init(&chan->mtx, "umidi lock", NULL, MTX_DEF | MTX_RECURSE);
5882 }
5883 
5884 static struct usb_fifo_methods umidi_fifo_methods = {
5885 	.f_start_read = &umidi_start_read,
5886 	.f_start_write = &umidi_start_write,
5887 	.f_stop_read = &umidi_stop_read,
5888 	.f_stop_write = &umidi_stop_write,
5889 	.f_open = &umidi_open,
5890 	.f_close = &umidi_close,
5891 	.f_ioctl = &umidi_ioctl,
5892 	.basename[0] = "umidi",
5893 };
5894 
5895 static int
5896 umidi_probe(device_t dev)
5897 {
5898 	struct uaudio_softc *sc = device_get_softc(dev);
5899 	struct usb_attach_arg *uaa = device_get_ivars(dev);
5900 	struct umidi_chan *chan = &sc->sc_midi_chan;
5901 	struct umidi_sub_chan *sub;
5902 	int unit = device_get_unit(dev);
5903 	int error;
5904 	uint32_t n;
5905 
5906 	if (usb_test_quirk(uaa, UQ_SINGLE_CMD_MIDI))
5907 		chan->single_command = 1;
5908 
5909 	if (usbd_set_alt_interface_index(sc->sc_udev, chan->iface_index,
5910 	    chan->iface_alt_index)) {
5911 		DPRINTF("setting of alternate index failed!\n");
5912 		goto detach;
5913 	}
5914 	usbd_set_parent_iface(sc->sc_udev, chan->iface_index,
5915 	    sc->sc_mixer_iface_index);
5916 
5917 	error = usbd_transfer_setup(uaa->device, &chan->iface_index,
5918 	    chan->xfer, umidi_config, UMIDI_N_TRANSFER,
5919 	    chan, &chan->mtx);
5920 	if (error) {
5921 		DPRINTF("error=%s\n", usbd_errstr(error));
5922 		goto detach;
5923 	}
5924 	if (chan->xfer[UMIDI_TX_TRANSFER] == NULL &&
5925 	    chan->xfer[UMIDI_RX_TRANSFER] == NULL) {
5926 		DPRINTF("no BULK or INTERRUPT MIDI endpoint(s) found\n");
5927 		goto detach;
5928 	}
5929 
5930 	/*
5931 	 * Some USB MIDI device makers couldn't resist using
5932 	 * wMaxPacketSize = 4 for RX and TX BULK endpoints, although
5933 	 * that size is an unsupported value for FULL speed BULK
5934 	 * endpoints. The same applies to some HIGH speed MIDI devices
5935 	 * which are using a wMaxPacketSize different from 512 bytes.
5936 	 *
5937 	 * Refer to section 5.8.3 in USB 2.0 PDF: Cite: "All Host
5938 	 * Controllers are required to have support for 8-, 16-, 32-,
5939 	 * and 64-byte maximum packet sizes for full-speed bulk
5940 	 * endpoints and 512 bytes for high-speed bulk endpoints."
5941 	 */
5942 	if (chan->xfer[UMIDI_TX_TRANSFER] != NULL &&
5943 	    usbd_xfer_maxp_was_clamped(chan->xfer[UMIDI_TX_TRANSFER]))
5944 		chan->single_command = 1;
5945 
5946 	if (chan->single_command != 0)
5947 		device_printf(dev, "Single command MIDI quirk enabled\n");
5948 
5949 	if ((chan->max_emb_jack == 0) ||
5950 	    (chan->max_emb_jack > UMIDI_EMB_JACK_MAX)) {
5951 		chan->max_emb_jack = UMIDI_EMB_JACK_MAX;
5952 	}
5953 
5954 	for (n = 0; n < chan->max_emb_jack; n++) {
5955 
5956 		sub = &chan->sub[n];
5957 
5958 		error = usb_fifo_attach(sc->sc_udev, chan, &chan->mtx,
5959 		    &umidi_fifo_methods, &sub->fifo, unit, n,
5960 		    chan->iface_index,
5961 		    UID_ROOT, GID_OPERATOR, 0644);
5962 		if (error) {
5963 			goto detach;
5964 		}
5965 	}
5966 
5967 	mtx_lock(&chan->mtx);
5968 
5969 	/*
5970 	 * NOTE: At least one device will not work properly unless the
5971 	 * BULK IN pipe is open all the time. This might have to do
5972 	 * about that the internal queues of the device overflow if we
5973 	 * don't read them regularly.
5974 	 */
5975 	usbd_transfer_start(chan->xfer[UMIDI_RX_TRANSFER]);
5976 
5977 	mtx_unlock(&chan->mtx);
5978 
5979 	return (0);			/* success */
5980 
5981 detach:
5982 	return (ENXIO);			/* failure */
5983 }
5984 
5985 static int
5986 umidi_detach(device_t dev)
5987 {
5988 	struct uaudio_softc *sc = device_get_softc(dev);
5989 	struct umidi_chan *chan = &sc->sc_midi_chan;
5990 	uint32_t n;
5991 
5992 	for (n = 0; n < UMIDI_EMB_JACK_MAX; n++)
5993 		usb_fifo_detach(&chan->sub[n].fifo);
5994 
5995 	mtx_lock(&chan->mtx);
5996 
5997 	usbd_transfer_stop(chan->xfer[UMIDI_RX_TRANSFER]);
5998 
5999 	mtx_unlock(&chan->mtx);
6000 
6001 	usbd_transfer_unsetup(chan->xfer, UMIDI_N_TRANSFER);
6002 
6003 	mtx_destroy(&chan->mtx);
6004 
6005 	return (0);
6006 }
6007 
6008 static void
6009 uaudio_hid_rx_callback(struct usb_xfer *xfer, usb_error_t error)
6010 {
6011 	struct uaudio_softc *sc = usbd_xfer_softc(xfer);
6012 	const uint8_t *buffer = usbd_xfer_get_frame_buffer(xfer, 0);
6013 	struct snd_mixer *m;
6014 	uint8_t id;
6015 	int actlen;
6016 
6017 	usbd_xfer_status(xfer, &actlen, NULL, NULL, NULL);
6018 
6019 	switch (USB_GET_STATE(xfer)) {
6020 	case USB_ST_TRANSFERRED:
6021 		DPRINTF("actlen=%d\n", actlen);
6022 
6023 		if (actlen != 0 &&
6024 		    (sc->sc_hid.flags & UAUDIO_HID_HAS_ID)) {
6025 			id = *buffer;
6026 			buffer++;
6027 			actlen--;
6028 		} else {
6029 			id = 0;
6030 		}
6031 
6032 		m = sc->sc_mixer_dev;
6033 
6034 		if ((sc->sc_hid.flags & UAUDIO_HID_HAS_MUTE) &&
6035 		    (sc->sc_hid.mute_id == id) &&
6036 		    hid_get_data(buffer, actlen,
6037 		    &sc->sc_hid.mute_loc)) {
6038 
6039 			DPRINTF("Mute toggle\n");
6040 
6041 			mixer_hwvol_mute_locked(m);
6042 		}
6043 
6044 		if ((sc->sc_hid.flags & UAUDIO_HID_HAS_VOLUME_UP) &&
6045 		    (sc->sc_hid.volume_up_id == id) &&
6046 		    hid_get_data(buffer, actlen,
6047 		    &sc->sc_hid.volume_up_loc)) {
6048 
6049 			DPRINTF("Volume Up\n");
6050 
6051 			mixer_hwvol_step_locked(m, 1, 1);
6052 		}
6053 
6054 		if ((sc->sc_hid.flags & UAUDIO_HID_HAS_VOLUME_DOWN) &&
6055 		    (sc->sc_hid.volume_down_id == id) &&
6056 		    hid_get_data(buffer, actlen,
6057 		    &sc->sc_hid.volume_down_loc)) {
6058 
6059 			DPRINTF("Volume Down\n");
6060 
6061 			mixer_hwvol_step_locked(m, -1, -1);
6062 		}
6063 
6064 	case USB_ST_SETUP:
6065 tr_setup:
6066 		/* check if we can put more data into the FIFO */
6067 		usbd_xfer_set_frame_len(xfer, 0, usbd_xfer_max_len(xfer));
6068 		usbd_transfer_submit(xfer);
6069 		break;
6070 
6071 	default:			/* Error */
6072 
6073 		DPRINTF("error=%s\n", usbd_errstr(error));
6074 
6075 		if (error != USB_ERR_CANCELLED) {
6076 			/* try to clear stall first */
6077 			usbd_xfer_set_stall(xfer);
6078 			goto tr_setup;
6079 		}
6080 		break;
6081 	}
6082 }
6083 
6084 static int
6085 uaudio_hid_probe(struct uaudio_softc *sc,
6086     struct usb_attach_arg *uaa)
6087 {
6088 	void *d_ptr;
6089 	uint32_t flags;
6090 	uint16_t d_len;
6091 	uint8_t id;
6092 	int error;
6093 
6094 	if (!(sc->sc_hid.flags & UAUDIO_HID_VALID))
6095 		return (-1);
6096 
6097 	if (sc->sc_mixer_lock == NULL)
6098 		return (-1);
6099 
6100 	/* Get HID descriptor */
6101 	error = usbd_req_get_hid_desc(uaa->device, NULL, &d_ptr,
6102 	    &d_len, M_TEMP, sc->sc_hid.iface_index);
6103 
6104 	if (error) {
6105 		DPRINTF("error reading report description\n");
6106 		return (-1);
6107 	}
6108 
6109 	/* check if there is an ID byte */
6110 	hid_report_size(d_ptr, d_len, hid_input, &id);
6111 
6112 	if (id != 0)
6113 		sc->sc_hid.flags |= UAUDIO_HID_HAS_ID;
6114 
6115 	if (hid_locate(d_ptr, d_len,
6116 	    HID_USAGE2(HUP_CONSUMER, 0xE9 /* Volume Increment */),
6117 	    hid_input, 0, &sc->sc_hid.volume_up_loc, &flags,
6118 	    &sc->sc_hid.volume_up_id)) {
6119 		if (flags & HIO_VARIABLE)
6120 			sc->sc_hid.flags |= UAUDIO_HID_HAS_VOLUME_UP;
6121 		DPRINTFN(1, "Found Volume Up key\n");
6122 	}
6123 
6124 	if (hid_locate(d_ptr, d_len,
6125 	    HID_USAGE2(HUP_CONSUMER, 0xEA /* Volume Decrement */),
6126 	    hid_input, 0, &sc->sc_hid.volume_down_loc, &flags,
6127 	    &sc->sc_hid.volume_down_id)) {
6128 		if (flags & HIO_VARIABLE)
6129 			sc->sc_hid.flags |= UAUDIO_HID_HAS_VOLUME_DOWN;
6130 		DPRINTFN(1, "Found Volume Down key\n");
6131 	}
6132 
6133 	if (hid_locate(d_ptr, d_len,
6134 	    HID_USAGE2(HUP_CONSUMER, 0xE2 /* Mute */),
6135 	    hid_input, 0, &sc->sc_hid.mute_loc, &flags,
6136 	    &sc->sc_hid.mute_id)) {
6137 		if (flags & HIO_VARIABLE)
6138 			sc->sc_hid.flags |= UAUDIO_HID_HAS_MUTE;
6139 		DPRINTFN(1, "Found Mute key\n");
6140 	}
6141 
6142 	free(d_ptr, M_TEMP);
6143 
6144 	if (!(sc->sc_hid.flags & (UAUDIO_HID_HAS_VOLUME_UP |
6145 	    UAUDIO_HID_HAS_VOLUME_DOWN |
6146 	    UAUDIO_HID_HAS_MUTE))) {
6147 		DPRINTFN(1, "Did not find any volume related keys\n");
6148 		return (-1);
6149 	}
6150 
6151 	/* prevent the uhid driver from attaching */
6152 	usbd_set_parent_iface(uaa->device, sc->sc_hid.iface_index,
6153 	    sc->sc_mixer_iface_index);
6154 
6155 	/* allocate USB transfers */
6156 	error = usbd_transfer_setup(uaa->device, &sc->sc_hid.iface_index,
6157 	    sc->sc_hid.xfer, uaudio_hid_config, UAUDIO_HID_N_TRANSFER,
6158 	    sc, sc->sc_mixer_lock);
6159 	if (error) {
6160 		DPRINTF("error=%s\n", usbd_errstr(error));
6161 		return (-1);
6162 	}
6163 	return (0);
6164 }
6165 
6166 static void
6167 uaudio_hid_detach(struct uaudio_softc *sc)
6168 {
6169 	usbd_transfer_unsetup(sc->sc_hid.xfer, UAUDIO_HID_N_TRANSFER);
6170 }
6171 
6172 DRIVER_MODULE_ORDERED(uaudio, uhub, uaudio_driver, uaudio_devclass, NULL, 0, SI_ORDER_ANY);
6173 MODULE_DEPEND(uaudio, usb, 1, 1, 1);
6174 MODULE_DEPEND(uaudio, sound, SOUND_MINVER, SOUND_PREFVER, SOUND_MAXVER);
6175 MODULE_VERSION(uaudio, 1);
6176 USB_PNP_HOST_INFO(uaudio_devs);
6177