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