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