xref: /freebsd/sys/dev/sound/usb/uaudio.c (revision 9a41df2a0e6408e9b329bbd8b9e37c2b44461a1b)
1 /*	$NetBSD: uaudio.c,v 1.91 2004/11/05 17:46:14 kent Exp $	*/
2 /*	$FreeBSD$ */
3 
4 /*-
5  * Copyright (c) 1999 The NetBSD Foundation, Inc.
6  * All rights reserved.
7  *
8  * This code is derived from software contributed to The NetBSD Foundation
9  * by Lennart Augustsson (lennart@augustsson.net) at
10  * Carlstedt Research & Technology.
11  *
12  * Redistribution and use in source and binary forms, with or without
13  * modification, are permitted provided that the following conditions
14  * are met:
15  * 1. Redistributions of source code must retain the above copyright
16  *    notice, this list of conditions and the following disclaimer.
17  * 2. Redistributions in binary form must reproduce the above copyright
18  *    notice, this list of conditions and the following disclaimer in the
19  *    documentation and/or other materials provided with the distribution.
20  *
21  * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
22  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
23  * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
24  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
25  * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
26  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
27  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
28  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
29  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
30  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
31  * POSSIBILITY OF SUCH DAMAGE.
32  */
33 
34 #include <sys/cdefs.h>
35 __FBSDID("$FreeBSD$");
36 
37 /*
38  * USB audio specs: http://www.usb.org/developers/devclass_docs/audio10.pdf
39  *                  http://www.usb.org/developers/devclass_docs/frmts10.pdf
40  *                  http://www.usb.org/developers/devclass_docs/termt10.pdf
41  */
42 
43 /*
44  * Also merged:
45  *  $NetBSD: uaudio.c,v 1.94 2005/01/15 15:19:53 kent Exp $
46  *  $NetBSD: uaudio.c,v 1.95 2005/01/16 06:02:19 dsainty Exp $
47  *  $NetBSD: uaudio.c,v 1.96 2005/01/16 12:46:00 kent Exp $
48  *  $NetBSD: uaudio.c,v 1.97 2005/02/24 08:19:38 martin Exp $
49  */
50 
51 #include <sys/stdint.h>
52 #include <sys/stddef.h>
53 #include <sys/param.h>
54 #include <sys/queue.h>
55 #include <sys/types.h>
56 #include <sys/systm.h>
57 #include <sys/kernel.h>
58 #include <sys/bus.h>
59 #include <sys/module.h>
60 #include <sys/lock.h>
61 #include <sys/mutex.h>
62 #include <sys/condvar.h>
63 #include <sys/sysctl.h>
64 #include <sys/sx.h>
65 #include <sys/unistd.h>
66 #include <sys/callout.h>
67 #include <sys/malloc.h>
68 #include <sys/priv.h>
69 
70 #include "usbdevs.h"
71 #include <dev/usb/usb.h>
72 #include <dev/usb/usbdi.h>
73 #include <dev/usb/usbdi_util.h>
74 
75 #define	USB_DEBUG_VAR uaudio_debug
76 #include <dev/usb/usb_debug.h>
77 
78 #include <dev/usb/quirk/usb_quirk.h>
79 
80 #include <sys/reboot.h>			/* for bootverbose */
81 
82 #ifdef HAVE_KERNEL_OPTION_HEADERS
83 #include "opt_snd.h"
84 #endif
85 
86 #include <dev/sound/pcm/sound.h>
87 #include <dev/sound/usb/uaudioreg.h>
88 #include <dev/sound/usb/uaudio.h>
89 #include <dev/sound/chip.h>
90 #include "feeder_if.h"
91 
92 static int uaudio_default_rate = 0;		/* use rate list */
93 static int uaudio_default_bits = 32;
94 static int uaudio_default_channels = 0;		/* use default */
95 
96 #ifdef USB_DEBUG
97 static int uaudio_debug = 0;
98 
99 static SYSCTL_NODE(_hw_usb, OID_AUTO, uaudio, CTLFLAG_RW, 0, "USB uaudio");
100 
101 SYSCTL_INT(_hw_usb_uaudio, OID_AUTO, debug, CTLFLAG_RW,
102     &uaudio_debug, 0, "uaudio debug level");
103 
104 TUNABLE_INT("hw.usb.uaudio.default_rate", &uaudio_default_rate);
105 SYSCTL_INT(_hw_usb_uaudio, OID_AUTO, default_rate, CTLFLAG_RW,
106     &uaudio_default_rate, 0, "uaudio default sample rate");
107 
108 TUNABLE_INT("hw.usb.uaudio.default_bits", &uaudio_default_bits);
109 SYSCTL_INT(_hw_usb_uaudio, OID_AUTO, default_bits, CTLFLAG_RW,
110     &uaudio_default_bits, 0, "uaudio default sample bits");
111 
112 TUNABLE_INT("hw.usb.uaudio.default_channels", &uaudio_default_channels);
113 SYSCTL_INT(_hw_usb_uaudio, OID_AUTO, default_channels, CTLFLAG_RW,
114     &uaudio_default_channels, 0, "uaudio default sample channels");
115 #endif
116 
117 #define	UAUDIO_NFRAMES		64	/* must be factor of 8 due HS-USB */
118 #define	UAUDIO_NCHANBUFS	2	/* number of outstanding request */
119 #define	UAUDIO_RECURSE_LIMIT	255	/* rounds */
120 
121 #define	MAKE_WORD(h,l) (((h) << 8) | (l))
122 #define	BIT_TEST(bm,bno) (((bm)[(bno) / 8] >> (7 - ((bno) % 8))) & 1)
123 #define	UAUDIO_MAX_CHAN(x) (x)
124 
125 union uaudio_asid {
126 	const struct usb_audio_streaming_interface_descriptor *v1;
127 	const struct usb_audio20_streaming_interface_descriptor *v2;
128 };
129 
130 union uaudio_asf1d {
131 	const struct usb_audio_streaming_type1_descriptor *v1;
132 	const struct usb_audio20_streaming_type1_descriptor *v2;
133 };
134 
135 union uaudio_sed {
136 	const struct usb_audio_streaming_endpoint_descriptor *v1;
137 	const struct usb_audio20_streaming_endpoint_descriptor *v2;
138 };
139 
140 struct uaudio_mixer_node {
141 	int32_t	minval;
142 	int32_t	maxval;
143 #define	MIX_MAX_CHAN 8
144 	int32_t	wValue[MIX_MAX_CHAN];	/* using nchan */
145 	uint32_t mul;
146 	uint32_t ctl;
147 
148 	uint16_t wData[MIX_MAX_CHAN];	/* using nchan */
149 	uint16_t wIndex;
150 
151 	uint8_t	update[(MIX_MAX_CHAN + 7) / 8];
152 	uint8_t	nchan;
153 	uint8_t	type;
154 #define	MIX_ON_OFF	1
155 #define	MIX_SIGNED_16	2
156 #define	MIX_UNSIGNED_16	3
157 #define	MIX_SIGNED_8	4
158 #define	MIX_SELECTOR	5
159 #define	MIX_UNKNOWN     6
160 #define	MIX_SIZE(n) ((((n) == MIX_SIGNED_16) || \
161 		      ((n) == MIX_UNSIGNED_16)) ? 2 : 1)
162 #define	MIX_UNSIGNED(n) ((n) == MIX_UNSIGNED_16)
163 
164 #define	MAX_SELECTOR_INPUT_PIN 256
165 	uint8_t	slctrtype[MAX_SELECTOR_INPUT_PIN];
166 	uint8_t	class;
167 
168 	struct uaudio_mixer_node *next;
169 };
170 
171 struct uaudio_chan {
172 	struct pcmchan_caps pcm_cap;	/* capabilities */
173 
174 	struct snd_dbuf *pcm_buf;
175 	const struct usb_config *usb_cfg;
176 	struct mtx *pcm_mtx;		/* lock protecting this structure */
177 	struct uaudio_softc *priv_sc;
178 	struct pcm_channel *pcm_ch;
179 	struct usb_xfer *xfer[UAUDIO_NCHANBUFS];
180 	union uaudio_asf1d p_asf1d;
181 	union uaudio_sed p_sed;
182 	const usb_endpoint_descriptor_audio_t *p_ed1;
183 	const struct uaudio_format *p_fmt;
184 
185 	uint8_t *buf;			/* pointer to buffer */
186 	uint8_t *start;			/* upper layer buffer start */
187 	uint8_t *end;			/* upper layer buffer end */
188 	uint8_t *cur;			/* current position in upper layer
189 					 * buffer */
190 
191 	uint32_t intr_size;		/* in bytes */
192 	uint32_t intr_frames;		/* in units */
193 	uint32_t sample_rate;
194 	uint32_t frames_per_second;
195 	uint32_t sample_rem;
196 	uint32_t sample_curr;
197 
198 	uint32_t format;
199 	uint32_t pcm_format[2];
200 
201 	uint16_t bytes_per_frame[2];
202 
203 	uint16_t sample_size;
204 
205 	uint8_t	valid;
206 	uint8_t	iface_index;
207 	uint8_t	iface_alt_index;
208 	uint8_t channels;
209 };
210 
211 #define	UMIDI_CABLES_MAX   16		/* units */
212 #define	UMIDI_TX_FRAMES	   256		/* units */
213 #define	UMIDI_TX_BUFFER    (UMIDI_TX_FRAMES * 4)	/* bytes */
214 
215 enum {
216 	UMIDI_TX_TRANSFER,
217 	UMIDI_RX_TRANSFER,
218 	UMIDI_N_TRANSFER,
219 };
220 
221 struct umidi_sub_chan {
222 	struct usb_fifo_sc fifo;
223 	uint8_t *temp_cmd;
224 	uint8_t	temp_0[4];
225 	uint8_t	temp_1[4];
226 	uint8_t	state;
227 #define	UMIDI_ST_UNKNOWN   0		/* scan for command */
228 #define	UMIDI_ST_1PARAM    1
229 #define	UMIDI_ST_2PARAM_1  2
230 #define	UMIDI_ST_2PARAM_2  3
231 #define	UMIDI_ST_SYSEX_0   4
232 #define	UMIDI_ST_SYSEX_1   5
233 #define	UMIDI_ST_SYSEX_2   6
234 
235 	uint8_t	read_open:1;
236 	uint8_t	write_open:1;
237 	uint8_t	unused:6;
238 };
239 
240 struct umidi_chan {
241 
242 	struct umidi_sub_chan sub[UMIDI_CABLES_MAX];
243 	struct mtx mtx;
244 
245 	struct usb_xfer *xfer[UMIDI_N_TRANSFER];
246 
247 	uint8_t	iface_index;
248 	uint8_t	iface_alt_index;
249 
250 	uint8_t	read_open_refcount;
251 	uint8_t	write_open_refcount;
252 
253 	uint8_t	curr_cable;
254 	uint8_t	max_cable;
255 	uint8_t	valid;
256 	uint8_t single_command;
257 };
258 
259 struct uaudio_search_result {
260 	uint8_t	bit_input[(256 + 7) / 8];
261 	uint8_t	bit_output[(256 + 7) / 8];
262 	uint8_t	recurse_level;
263 	uint8_t	id_max;
264 	uint8_t is_input;
265 };
266 
267 struct uaudio_softc {
268 	struct sbuf sc_sndstat;
269 	struct sndcard_func sc_sndcard_func;
270 	struct uaudio_chan sc_rec_chan;
271 	struct uaudio_chan sc_play_chan;
272 	struct umidi_chan sc_midi_chan;
273 	struct uaudio_search_result sc_mixer_clocks;
274 
275 	struct usb_device *sc_udev;
276 	struct usb_xfer *sc_mixer_xfer[1];
277 	struct uaudio_mixer_node *sc_mixer_root;
278 	struct uaudio_mixer_node *sc_mixer_curr;
279 
280 	uint32_t sc_mix_info;
281 	uint32_t sc_recsrc_info;
282 
283 	uint16_t sc_audio_rev;
284 	uint16_t sc_mixer_count;
285 
286 	uint8_t	sc_sndstat_valid;
287 	uint8_t	sc_mixer_iface_index;
288 	uint8_t	sc_mixer_iface_no;
289 	uint8_t	sc_mixer_chan;
290 	uint8_t	sc_pcm_registered:1;
291 	uint8_t	sc_mixer_init:1;
292 	uint8_t	sc_uq_audio_swap_lr:1;
293 	uint8_t	sc_uq_au_inp_async:1;
294 	uint8_t	sc_uq_au_no_xu:1;
295 	uint8_t	sc_uq_bad_adc:1;
296 	uint8_t	sc_uq_au_vendor_class:1;
297 };
298 
299 struct uaudio_terminal_node {
300 	union {
301 		const struct usb_descriptor *desc;
302 		const struct usb_audio_input_terminal *it_v1;
303 		const struct usb_audio_output_terminal *ot_v1;
304 		const struct usb_audio_mixer_unit_0 *mu_v1;
305 		const struct usb_audio_selector_unit *su_v1;
306 		const struct usb_audio_feature_unit *fu_v1;
307 		const struct usb_audio_processing_unit_0 *pu_v1;
308 		const struct usb_audio_extension_unit_0 *eu_v1;
309 		const struct usb_audio20_clock_source_unit *csrc_v2;
310 		const struct usb_audio20_clock_selector_unit_0 *csel_v2;
311 		const struct usb_audio20_clock_multiplier_unit *cmul_v2;
312 		const struct usb_audio20_input_terminal *it_v2;
313 		const struct usb_audio20_output_terminal *ot_v2;
314 		const struct usb_audio20_mixer_unit_0 *mu_v2;
315 		const struct usb_audio20_selector_unit *su_v2;
316 		const struct usb_audio20_feature_unit *fu_v2;
317 		const struct usb_audio20_sample_rate_unit *ru_v2;
318 		const struct usb_audio20_processing_unit_0 *pu_v2;
319 		const struct usb_audio20_extension_unit_0 *eu_v2;
320 		const struct usb_audio20_effect_unit *ef_v2;
321 	}	u;
322 	struct uaudio_search_result usr;
323 	struct uaudio_terminal_node *root;
324 };
325 
326 struct uaudio_format {
327 	uint16_t wFormat;
328 	uint8_t	bPrecision;
329 	uint32_t freebsd_fmt;
330 	const char *description;
331 };
332 
333 static const struct uaudio_format uaudio10_formats[] = {
334 
335 	{UA_FMT_PCM8, 8, AFMT_U8, "8-bit U-LE PCM"},
336 	{UA_FMT_PCM8, 16, AFMT_U16_LE, "16-bit U-LE PCM"},
337 	{UA_FMT_PCM8, 24, AFMT_U24_LE, "24-bit U-LE PCM"},
338 	{UA_FMT_PCM8, 32, AFMT_U32_LE, "32-bit U-LE PCM"},
339 
340 	{UA_FMT_PCM, 8, AFMT_S8, "8-bit S-LE PCM"},
341 	{UA_FMT_PCM, 16, AFMT_S16_LE, "16-bit S-LE PCM"},
342 	{UA_FMT_PCM, 24, AFMT_S24_LE, "24-bit S-LE PCM"},
343 	{UA_FMT_PCM, 32, AFMT_S32_LE, "32-bit S-LE PCM"},
344 
345 	{UA_FMT_ALAW, 8, AFMT_A_LAW, "8-bit A-Law"},
346 	{UA_FMT_MULAW, 8, AFMT_MU_LAW, "8-bit mu-Law"},
347 
348 	{0, 0, 0, NULL}
349 };
350 
351 static const struct uaudio_format uaudio20_formats[] = {
352 
353 	{UA20_FMT_PCM, 8, AFMT_S8, "8-bit S-LE PCM"},
354 	{UA20_FMT_PCM, 16, AFMT_S16_LE, "16-bit S-LE PCM"},
355 	{UA20_FMT_PCM, 24, AFMT_S24_LE, "24-bit S-LE PCM"},
356 	{UA20_FMT_PCM, 32, AFMT_S32_LE, "32-bit S-LE PCM"},
357 
358 	{UA20_FMT_PCM8, 8, AFMT_U8, "8-bit U-LE PCM"},
359 	{UA20_FMT_PCM8, 16, AFMT_U16_LE, "16-bit U-LE PCM"},
360 	{UA20_FMT_PCM8, 24, AFMT_U24_LE, "24-bit U-LE PCM"},
361 	{UA20_FMT_PCM8, 32, AFMT_U32_LE, "32-bit U-LE PCM"},
362 
363 	{UA20_FMT_ALAW, 8, AFMT_A_LAW, "8-bit A-Law"},
364 	{UA20_FMT_MULAW, 8, AFMT_MU_LAW, "8-bit mu-Law"},
365 
366 	{0, 0, 0, NULL}
367 };
368 
369 #define	UAC_OUTPUT	0
370 #define	UAC_INPUT	1
371 #define	UAC_EQUAL	2
372 #define	UAC_RECORD	3
373 #define	UAC_NCLASSES	4
374 
375 #ifdef USB_DEBUG
376 static const char *uac_names[] = {
377 	"outputs", "inputs", "equalization", "record"
378 };
379 
380 #endif
381 
382 /* prototypes */
383 
384 static device_probe_t uaudio_probe;
385 static device_attach_t uaudio_attach;
386 static device_detach_t uaudio_detach;
387 
388 static usb_callback_t uaudio_chan_play_callback;
389 static usb_callback_t uaudio_chan_record_callback;
390 static usb_callback_t uaudio_mixer_write_cfg_callback;
391 static usb_callback_t umidi_bulk_read_callback;
392 static usb_callback_t umidi_bulk_write_callback;
393 
394 /* ==== USB audio v1.0 ==== */
395 
396 static void	uaudio_mixer_add_mixer(struct uaudio_softc *,
397 		    const struct uaudio_terminal_node *, int);
398 static void	uaudio_mixer_add_selector(struct uaudio_softc *,
399 		    const struct uaudio_terminal_node *, int);
400 static uint32_t	uaudio_mixer_feature_get_bmaControls(
401 		    const struct usb_audio_feature_unit *, uint8_t);
402 static void	uaudio_mixer_add_feature(struct uaudio_softc *,
403 		    const struct uaudio_terminal_node *, int);
404 static void	uaudio_mixer_add_processing_updown(struct uaudio_softc *,
405 		    const struct uaudio_terminal_node *, int);
406 static void	uaudio_mixer_add_processing(struct uaudio_softc *,
407 		    const struct uaudio_terminal_node *, int);
408 static void	uaudio_mixer_add_extension(struct uaudio_softc *,
409 		    const struct uaudio_terminal_node *, int);
410 static struct	usb_audio_cluster uaudio_mixer_get_cluster(uint8_t,
411 		    const struct uaudio_terminal_node *);
412 static uint16_t	uaudio_mixer_determine_class(const struct uaudio_terminal_node *,
413 		    struct uaudio_mixer_node *);
414 static uint16_t	uaudio_mixer_feature_name(const struct uaudio_terminal_node *,
415 		    struct uaudio_mixer_node *);
416 static void	uaudio_mixer_find_inputs_sub(struct uaudio_terminal_node *,
417 		    const uint8_t *, uint8_t, struct uaudio_search_result *);
418 static const void *uaudio_mixer_verify_desc(const void *, uint32_t);
419 static usb_error_t uaudio_set_speed(struct usb_device *, uint8_t, uint32_t);
420 static int	uaudio_mixer_get(struct usb_device *, uint16_t, uint8_t,
421 		    struct uaudio_mixer_node *);
422 
423 /* ==== USB audio v2.0 ==== */
424 
425 static void	uaudio20_mixer_add_mixer(struct uaudio_softc *,
426 		    const struct uaudio_terminal_node *, int);
427 static void	uaudio20_mixer_add_selector(struct uaudio_softc *,
428 		    const struct uaudio_terminal_node *, int);
429 static void	uaudio20_mixer_add_feature(struct uaudio_softc *,
430 		    const struct uaudio_terminal_node *, int);
431 static struct	usb_audio20_cluster uaudio20_mixer_get_cluster(uint8_t,
432 		    const struct uaudio_terminal_node *);
433 static uint16_t	uaudio20_mixer_determine_class(const struct uaudio_terminal_node *,
434 		    struct uaudio_mixer_node *);
435 static uint16_t	uaudio20_mixer_feature_name(const struct uaudio_terminal_node *,
436 		    struct uaudio_mixer_node *);
437 static void	uaudio20_mixer_find_inputs_sub(struct uaudio_terminal_node *,
438 		    const uint8_t *, uint8_t, struct uaudio_search_result *);
439 static const void *uaudio20_mixer_verify_desc(const void *, uint32_t);
440 static usb_error_t uaudio20_set_speed(struct usb_device *, uint8_t,
441 		    uint8_t, uint32_t);
442 
443 /* USB audio v1.0 and v2.0 */
444 
445 static void	uaudio_chan_fill_info_sub(struct uaudio_softc *,
446 		    struct usb_device *, uint32_t, uint8_t, uint8_t);
447 static void	uaudio_chan_fill_info(struct uaudio_softc *,
448 		    struct usb_device *);
449 static void	uaudio_mixer_add_ctl_sub(struct uaudio_softc *,
450 		    struct uaudio_mixer_node *);
451 static void	uaudio_mixer_add_ctl(struct uaudio_softc *,
452 		    struct uaudio_mixer_node *);
453 static void	uaudio_mixer_fill_info(struct uaudio_softc *,
454 		    struct usb_device *, void *);
455 static void	uaudio_mixer_ctl_set(struct uaudio_softc *,
456 		    struct uaudio_mixer_node *, uint8_t, int32_t val);
457 static int	uaudio_mixer_signext(uint8_t, int);
458 static int	uaudio_mixer_bsd2value(struct uaudio_mixer_node *, int32_t val);
459 static void	uaudio_mixer_init(struct uaudio_softc *);
460 static const struct uaudio_terminal_node *uaudio_mixer_get_input(
461 		    const struct uaudio_terminal_node *, uint8_t);
462 static const struct uaudio_terminal_node *uaudio_mixer_get_output(
463 		    const struct uaudio_terminal_node *, uint8_t);
464 static void	uaudio_mixer_find_outputs_sub(struct uaudio_terminal_node *,
465 		    uint8_t, uint8_t, struct uaudio_search_result *);
466 static uint8_t	umidi_convert_to_usb(struct umidi_sub_chan *, uint8_t, uint8_t);
467 static struct	umidi_sub_chan *umidi_sub_by_fifo(struct usb_fifo *);
468 static void	umidi_start_read(struct usb_fifo *);
469 static void	umidi_stop_read(struct usb_fifo *);
470 static void	umidi_start_write(struct usb_fifo *);
471 static void	umidi_stop_write(struct usb_fifo *);
472 static int	umidi_open(struct usb_fifo *, int);
473 static int	umidi_ioctl(struct usb_fifo *, u_long cmd, void *, int);
474 static void	umidi_close(struct usb_fifo *, int);
475 static void	umidi_init(device_t dev);
476 static int	umidi_probe(device_t dev);
477 static int	umidi_detach(device_t dev);
478 
479 #ifdef USB_DEBUG
480 static void	uaudio_chan_dump_ep_desc(
481 		    const usb_endpoint_descriptor_audio_t *);
482 #endif
483 
484 static const struct usb_config
485 	uaudio_cfg_record[UAUDIO_NCHANBUFS] = {
486 	[0] = {
487 		.type = UE_ISOCHRONOUS,
488 		.endpoint = UE_ADDR_ANY,
489 		.direction = UE_DIR_IN,
490 		.bufsize = 0,	/* use "wMaxPacketSize * frames" */
491 		.frames = UAUDIO_NFRAMES,
492 		.flags = {.short_xfer_ok = 1,},
493 		.callback = &uaudio_chan_record_callback,
494 	},
495 
496 	[1] = {
497 		.type = UE_ISOCHRONOUS,
498 		.endpoint = UE_ADDR_ANY,
499 		.direction = UE_DIR_IN,
500 		.bufsize = 0,	/* use "wMaxPacketSize * frames" */
501 		.frames = UAUDIO_NFRAMES,
502 		.flags = {.short_xfer_ok = 1,},
503 		.callback = &uaudio_chan_record_callback,
504 	},
505 };
506 
507 static const struct usb_config
508 	uaudio_cfg_play[UAUDIO_NCHANBUFS] = {
509 	[0] = {
510 		.type = UE_ISOCHRONOUS,
511 		.endpoint = UE_ADDR_ANY,
512 		.direction = UE_DIR_OUT,
513 		.bufsize = 0,	/* use "wMaxPacketSize * frames" */
514 		.frames = UAUDIO_NFRAMES,
515 		.flags = {.short_xfer_ok = 1,},
516 		.callback = &uaudio_chan_play_callback,
517 	},
518 
519 	[1] = {
520 		.type = UE_ISOCHRONOUS,
521 		.endpoint = UE_ADDR_ANY,
522 		.direction = UE_DIR_OUT,
523 		.bufsize = 0,	/* use "wMaxPacketSize * frames" */
524 		.frames = UAUDIO_NFRAMES,
525 		.flags = {.short_xfer_ok = 1,},
526 		.callback = &uaudio_chan_play_callback,
527 	},
528 };
529 
530 static const struct usb_config
531 	uaudio_mixer_config[1] = {
532 	[0] = {
533 		.type = UE_CONTROL,
534 		.endpoint = 0x00,	/* Control pipe */
535 		.direction = UE_DIR_ANY,
536 		.bufsize = (sizeof(struct usb_device_request) + 4),
537 		.callback = &uaudio_mixer_write_cfg_callback,
538 		.timeout = 1000,	/* 1 second */
539 	},
540 };
541 
542 static const
543 uint8_t	umidi_cmd_to_len[16] = {
544 	[0x0] = 0,			/* reserved */
545 	[0x1] = 0,			/* reserved */
546 	[0x2] = 2,			/* bytes */
547 	[0x3] = 3,			/* bytes */
548 	[0x4] = 3,			/* bytes */
549 	[0x5] = 1,			/* bytes */
550 	[0x6] = 2,			/* bytes */
551 	[0x7] = 3,			/* bytes */
552 	[0x8] = 3,			/* bytes */
553 	[0x9] = 3,			/* bytes */
554 	[0xA] = 3,			/* bytes */
555 	[0xB] = 3,			/* bytes */
556 	[0xC] = 2,			/* bytes */
557 	[0xD] = 2,			/* bytes */
558 	[0xE] = 3,			/* bytes */
559 	[0xF] = 1,			/* bytes */
560 };
561 
562 static const struct usb_config
563 	umidi_config[UMIDI_N_TRANSFER] = {
564 	[UMIDI_TX_TRANSFER] = {
565 		.type = UE_BULK,
566 		.endpoint = UE_ADDR_ANY,
567 		.direction = UE_DIR_OUT,
568 		.bufsize = UMIDI_TX_BUFFER,
569 		.callback = &umidi_bulk_write_callback,
570 	},
571 
572 	[UMIDI_RX_TRANSFER] = {
573 		.type = UE_BULK,
574 		.endpoint = UE_ADDR_ANY,
575 		.direction = UE_DIR_IN,
576 		.bufsize = 4,	/* bytes */
577 		.flags = {.short_xfer_ok = 1,.proxy_buffer = 1,},
578 		.callback = &umidi_bulk_read_callback,
579 	},
580 };
581 
582 static devclass_t uaudio_devclass;
583 
584 static device_method_t uaudio_methods[] = {
585 	DEVMETHOD(device_probe, uaudio_probe),
586 	DEVMETHOD(device_attach, uaudio_attach),
587 	DEVMETHOD(device_detach, uaudio_detach),
588 	DEVMETHOD(device_suspend, bus_generic_suspend),
589 	DEVMETHOD(device_resume, bus_generic_resume),
590 	DEVMETHOD(device_shutdown, bus_generic_shutdown),
591 
592 	DEVMETHOD_END
593 };
594 
595 static driver_t uaudio_driver = {
596 	.name = "uaudio",
597 	.methods = uaudio_methods,
598 	.size = sizeof(struct uaudio_softc),
599 };
600 
601 static const STRUCT_USB_HOST_ID __used uaudio_devs[] = {
602 	/* Generic USB audio class match */
603 	{USB_IFACE_CLASS(UICLASS_AUDIO),
604 	 USB_IFACE_SUBCLASS(UISUBCLASS_AUDIOCONTROL),},
605 	/* Generic USB MIDI class match */
606 	{USB_IFACE_CLASS(UICLASS_AUDIO),
607 	 USB_IFACE_SUBCLASS(UISUBCLASS_MIDISTREAM),},
608 };
609 
610 static int
611 uaudio_probe(device_t dev)
612 {
613 	struct usb_attach_arg *uaa = device_get_ivars(dev);
614 
615 	if (uaa->usb_mode != USB_MODE_HOST)
616 		return (ENXIO);
617 
618 	/* lookup non-standard device */
619 
620 	if (uaa->info.bInterfaceClass != UICLASS_AUDIO) {
621 		if (usb_test_quirk(uaa, UQ_AU_VENDOR_CLASS) == 0)
622 			return (ENXIO);
623 	}
624 
625 	/* check for AUDIO control interface */
626 
627 	if (uaa->info.bInterfaceSubClass == UISUBCLASS_AUDIOCONTROL) {
628 		if (usb_test_quirk(uaa, UQ_BAD_AUDIO))
629 			return (ENXIO);
630 		else
631 			return (BUS_PROBE_GENERIC);
632 	}
633 
634 	/* check for MIDI stream */
635 
636 	if (uaa->info.bInterfaceSubClass == UISUBCLASS_MIDISTREAM) {
637 		if (usb_test_quirk(uaa, UQ_BAD_MIDI))
638 			return (ENXIO);
639 		else
640 			return (BUS_PROBE_GENERIC);
641 	}
642 	return (ENXIO);
643 }
644 
645 static int
646 uaudio_attach(device_t dev)
647 {
648 	struct usb_attach_arg *uaa = device_get_ivars(dev);
649 	struct uaudio_softc *sc = device_get_softc(dev);
650 	struct usb_interface_descriptor *id;
651 	device_t child;
652 
653 	sc->sc_play_chan.priv_sc = sc;
654 	sc->sc_rec_chan.priv_sc = sc;
655 	sc->sc_udev = uaa->device;
656 	sc->sc_mixer_iface_index = uaa->info.bIfaceIndex;
657 	sc->sc_mixer_iface_no = uaa->info.bIfaceNum;
658 
659 	if (usb_test_quirk(uaa, UQ_AUDIO_SWAP_LR))
660 		sc->sc_uq_audio_swap_lr = 1;
661 
662 	if (usb_test_quirk(uaa, UQ_AU_INP_ASYNC))
663 		sc->sc_uq_au_inp_async = 1;
664 
665 	if (usb_test_quirk(uaa, UQ_AU_NO_XU))
666 		sc->sc_uq_au_no_xu = 1;
667 
668 	if (usb_test_quirk(uaa, UQ_BAD_ADC))
669 		sc->sc_uq_bad_adc = 1;
670 
671 	if (usb_test_quirk(uaa, UQ_AU_VENDOR_CLASS))
672 		sc->sc_uq_au_vendor_class = 1;
673 
674 	umidi_init(dev);
675 
676 	device_set_usb_desc(dev);
677 
678 	id = usbd_get_interface_descriptor(uaa->iface);
679 
680 	/* must fill mixer info before channel info */
681 	uaudio_mixer_fill_info(sc, uaa->device, id);
682 
683 	/* fill channel info */
684 	uaudio_chan_fill_info(sc, uaa->device);
685 
686 	DPRINTF("audio rev %d.%02x\n",
687 	    sc->sc_audio_rev >> 8,
688 	    sc->sc_audio_rev & 0xff);
689 
690 	DPRINTF("%d mixer controls\n",
691 	    sc->sc_mixer_count);
692 
693 	if (sc->sc_play_chan.valid) {
694 		device_printf(dev, "Play: %d Hz, %d ch, %s format.\n",
695 		    sc->sc_play_chan.sample_rate,
696 		    sc->sc_play_chan.channels,
697 		    sc->sc_play_chan.p_fmt->description);
698 	} else {
699 		device_printf(dev, "No playback.\n");
700 	}
701 
702 	if (sc->sc_rec_chan.valid) {
703 		device_printf(dev, "Record: %d Hz, %d ch, %s format.\n",
704 		    sc->sc_rec_chan.sample_rate,
705 		    sc->sc_play_chan.channels,
706 		    sc->sc_rec_chan.p_fmt->description);
707 	} else {
708 		device_printf(dev, "No recording.\n");
709 	}
710 
711 	if (sc->sc_midi_chan.valid) {
712 
713 		if (umidi_probe(dev)) {
714 			goto detach;
715 		}
716 		device_printf(dev, "MIDI sequencer.\n");
717 	} else {
718 		device_printf(dev, "No midi sequencer.\n");
719 	}
720 
721 	DPRINTF("doing child attach\n");
722 
723 	/* attach the children */
724 
725 	sc->sc_sndcard_func.func = SCF_PCM;
726 
727 	/*
728 	 * Only attach a PCM device if we have a playback, recording
729 	 * or mixer device present:
730 	 */
731 	if (sc->sc_play_chan.valid ||
732 	    sc->sc_rec_chan.valid ||
733 	    sc->sc_mix_info) {
734 		child = device_add_child(dev, "pcm", -1);
735 
736 		if (child == NULL) {
737 			DPRINTF("out of memory\n");
738 			goto detach;
739 		}
740 		device_set_ivars(child, &sc->sc_sndcard_func);
741 	}
742 
743 	if (bus_generic_attach(dev)) {
744 		DPRINTF("child attach failed\n");
745 		goto detach;
746 	}
747 	return (0);			/* success */
748 
749 detach:
750 	uaudio_detach(dev);
751 	return (ENXIO);
752 }
753 
754 static void
755 uaudio_pcm_setflags(device_t dev, uint32_t flags)
756 {
757 	pcm_setflags(dev, pcm_getflags(dev) | flags);
758 }
759 
760 int
761 uaudio_attach_sub(device_t dev, kobj_class_t mixer_class, kobj_class_t chan_class)
762 {
763 	struct uaudio_softc *sc = device_get_softc(device_get_parent(dev));
764 	char status[SND_STATUSLEN];
765 
766 	uaudio_mixer_init(sc);
767 
768 	if (sc->sc_uq_audio_swap_lr) {
769 		DPRINTF("hardware has swapped left and right\n");
770 		/* uaudio_pcm_setflags(dev, SD_F_PSWAPLR); */
771 	}
772 	if (!(sc->sc_mix_info & SOUND_MASK_PCM)) {
773 
774 		DPRINTF("emulating master volume\n");
775 
776 		/*
777 		 * Emulate missing pcm mixer controller
778 		 * through FEEDER_VOLUME
779 		 */
780 		uaudio_pcm_setflags(dev, SD_F_SOFTPCMVOL);
781 	}
782 	if (mixer_init(dev, mixer_class, sc)) {
783 		goto detach;
784 	}
785 	sc->sc_mixer_init = 1;
786 
787 	snprintf(status, sizeof(status), "at ? %s", PCM_KLDSTRING(snd_uaudio));
788 
789 	if (pcm_register(dev, sc,
790 	    sc->sc_play_chan.valid ? 1 : 0,
791 	    sc->sc_rec_chan.valid ? 1 : 0)) {
792 		goto detach;
793 	}
794 
795 	uaudio_pcm_setflags(dev, SD_F_MPSAFE);
796 	sc->sc_pcm_registered = 1;
797 
798 	if (sc->sc_play_chan.valid) {
799 		pcm_addchan(dev, PCMDIR_PLAY, chan_class, sc);
800 	}
801 	if (sc->sc_rec_chan.valid) {
802 		pcm_addchan(dev, PCMDIR_REC, chan_class, sc);
803 	}
804 	pcm_setstatus(dev, status);
805 
806 	return (0);			/* success */
807 
808 detach:
809 	uaudio_detach_sub(dev);
810 	return (ENXIO);
811 }
812 
813 int
814 uaudio_detach_sub(device_t dev)
815 {
816 	struct uaudio_softc *sc = device_get_softc(device_get_parent(dev));
817 	int error = 0;
818 
819 repeat:
820 	if (sc->sc_pcm_registered) {
821 		error = pcm_unregister(dev);
822 	} else {
823 		if (sc->sc_mixer_init) {
824 			error = mixer_uninit(dev);
825 		}
826 	}
827 
828 	if (error) {
829 		device_printf(dev, "Waiting for sound application to exit!\n");
830 		usb_pause_mtx(NULL, 2 * hz);
831 		goto repeat;		/* try again */
832 	}
833 	return (0);			/* success */
834 }
835 
836 static int
837 uaudio_detach(device_t dev)
838 {
839 	struct uaudio_softc *sc = device_get_softc(dev);
840 
841 	/*
842 	 * Stop USB transfers early so that any audio applications
843 	 * will time out and close opened /dev/dspX.Y device(s), if
844 	 * any.
845 	 */
846 	if (sc->sc_play_chan.valid)
847 		usbd_transfer_unsetup(sc->sc_play_chan.xfer, UAUDIO_NCHANBUFS);
848 	if (sc->sc_rec_chan.valid)
849 		usbd_transfer_unsetup(sc->sc_rec_chan.xfer, UAUDIO_NCHANBUFS);
850 
851 	if (bus_generic_detach(dev) != 0) {
852 		DPRINTF("detach failed!\n");
853 	}
854 	sbuf_delete(&sc->sc_sndstat);
855 	sc->sc_sndstat_valid = 0;
856 
857 	umidi_detach(dev);
858 
859 	return (0);
860 }
861 
862 /*========================================================================*
863  * AS - Audio Stream - routines
864  *========================================================================*/
865 
866 #ifdef USB_DEBUG
867 static void
868 uaudio_chan_dump_ep_desc(const usb_endpoint_descriptor_audio_t *ed)
869 {
870 	if (ed) {
871 		DPRINTF("endpoint=%p bLength=%d bDescriptorType=%d \n"
872 		    "bEndpointAddress=%d bmAttributes=0x%x \n"
873 		    "wMaxPacketSize=%d bInterval=%d \n"
874 		    "bRefresh=%d bSynchAddress=%d\n",
875 		    ed, ed->bLength, ed->bDescriptorType,
876 		    ed->bEndpointAddress, ed->bmAttributes,
877 		    UGETW(ed->wMaxPacketSize), ed->bInterval,
878 		    UEP_HAS_REFRESH(ed) ? ed->bRefresh : 0,
879 		    UEP_HAS_SYNCADDR(ed) ? ed->bSynchAddress : 0);
880 	}
881 }
882 
883 #endif
884 
885 /*
886  * The following is a workaround for broken no-name USB audio devices
887  * sold by dealextreme called "3D sound". The problem is that the
888  * manufacturer computed wMaxPacketSize is too small to hold the
889  * actual data sent. In other words the device sometimes sends more
890  * data than it actually reports it can send in a single isochronous
891  * packet.
892  */
893 static void
894 uaudio_record_fix_fs(usb_endpoint_descriptor_audio_t *ep,
895     uint32_t xps, uint32_t add)
896 {
897 	uint32_t mps;
898 
899 	mps = UGETW(ep->wMaxPacketSize);
900 
901 	/*
902 	 * If the device indicates it can send more data than what the
903 	 * sample rate indicates, we apply the workaround.
904 	 */
905 	if (mps > xps) {
906 
907 		/* allow additional data */
908 		xps += add;
909 
910 		/* check against the maximum USB 1.x length */
911 		if (xps > 1023)
912 			xps = 1023;
913 
914 		/* check if we should do an update */
915 		if (mps < xps) {
916 			/* simply update the wMaxPacketSize field */
917 			USETW(ep->wMaxPacketSize, xps);
918 			DPRINTF("Workaround: Updated wMaxPacketSize "
919 			    "from %d to %d bytes.\n",
920 			    (int)mps, (int)xps);
921 		}
922 	}
923 }
924 
925 static usb_error_t
926 uaudio20_check_rate(struct usb_device *udev, uint8_t iface_no,
927     uint8_t clockid, uint32_t rate)
928 {
929 	struct usb_device_request req;
930 	usb_error_t error;
931 	uint8_t data[255];
932 	uint16_t actlen;
933 	uint16_t rates;
934 	uint16_t x;
935 
936 	DPRINTFN(6, "ifaceno=%d clockid=%d rate=%u\n",
937 	    iface_no, clockid, rate);
938 
939 	req.bmRequestType = UT_READ_CLASS_INTERFACE;
940 	req.bRequest = UA20_CS_RANGE;
941 	USETW2(req.wValue, UA20_CS_SAM_FREQ_CONTROL, 0);
942 	USETW2(req.wIndex, clockid, iface_no);
943 	USETW(req.wLength, 255);
944 
945         error = usbd_do_request_flags(udev, NULL, &req, data,
946 	    USB_SHORT_XFER_OK, &actlen, USB_DEFAULT_TIMEOUT);
947 
948 	if (error != 0 || actlen < 2)
949 		return (USB_ERR_INVAL);
950 
951 	rates = data[0] | (data[1] << 8);
952 	actlen = (actlen - 2) / 12;
953 
954 	if (rates > actlen) {
955 		DPRINTF("Too many rates\n");
956 		rates = actlen;
957 	}
958 
959 	for (x = 0; x != rates; x++) {
960 		uint32_t min = UGETDW(data + 2 + (12 * x));
961 		uint32_t max = UGETDW(data + 6 + (12 * x));
962 		uint32_t res = UGETDW(data + 10 + (12 * x));
963 
964 		if (res == 0) {
965 			DPRINTF("Zero residue\n");
966 			res = 1;
967 		}
968 
969 		if (min > max) {
970 			DPRINTF("Swapped max and min\n");
971 			uint32_t temp;
972 			temp = min;
973 			min = max;
974 			max = temp;
975 		}
976 
977 		if (rate >= min && rate <= max &&
978 		    (((rate - min) % res) == 0)) {
979 			return (0);
980 		}
981 	}
982 	return (USB_ERR_INVAL);
983 }
984 
985 static void
986 uaudio_chan_fill_info_sub(struct uaudio_softc *sc, struct usb_device *udev,
987     uint32_t rate, uint8_t channels, uint8_t bit_resolution)
988 {
989 	struct usb_descriptor *desc = NULL;
990 	union uaudio_asid asid = { NULL };
991 	union uaudio_asf1d asf1d = { NULL };
992 	union uaudio_sed sed = { NULL };
993 	usb_endpoint_descriptor_audio_t *ed1 = NULL;
994 	const struct usb_audio_control_descriptor *acdp = NULL;
995 	struct usb_config_descriptor *cd = usbd_get_config_descriptor(udev);
996 	struct usb_interface_descriptor *id;
997 	const struct uaudio_format *p_fmt = NULL;
998 	struct uaudio_chan *chan;
999 	uint16_t curidx = 0xFFFF;
1000 	uint16_t lastidx = 0xFFFF;
1001 	uint16_t alt_index = 0;
1002 	uint16_t audio_rev = 0;
1003 	uint16_t x;
1004 	uint8_t ep_dir;
1005 	uint8_t bChannels;
1006 	uint8_t bBitResolution;
1007 	uint8_t audio_if = 0;
1008 	uint8_t uma_if_class;
1009 
1010 	while ((desc = usb_desc_foreach(cd, desc))) {
1011 
1012 		if ((desc->bDescriptorType == UDESC_INTERFACE) &&
1013 		    (desc->bLength >= sizeof(*id))) {
1014 
1015 			id = (void *)desc;
1016 
1017 			if (id->bInterfaceNumber != lastidx) {
1018 				lastidx = id->bInterfaceNumber;
1019 				curidx++;
1020 				alt_index = 0;
1021 
1022 			} else {
1023 				alt_index++;
1024 			}
1025 
1026 			uma_if_class =
1027 			    ((id->bInterfaceClass == UICLASS_AUDIO) ||
1028 			    ((id->bInterfaceClass == UICLASS_VENDOR) &&
1029 			    (sc->sc_uq_au_vendor_class != 0)));
1030 
1031 			if ((uma_if_class != 0) && (id->bInterfaceSubClass == UISUBCLASS_AUDIOSTREAM)) {
1032 				audio_if = 1;
1033 			} else {
1034 				audio_if = 0;
1035 			}
1036 
1037 			if ((uma_if_class != 0) &&
1038 			    (id->bInterfaceSubClass == UISUBCLASS_MIDISTREAM)) {
1039 
1040 				/*
1041 				 * XXX could allow multiple MIDI interfaces
1042 				 */
1043 
1044 				if ((sc->sc_midi_chan.valid == 0) &&
1045 				    usbd_get_iface(udev, curidx)) {
1046 					sc->sc_midi_chan.iface_index = curidx;
1047 					sc->sc_midi_chan.iface_alt_index = alt_index;
1048 					sc->sc_midi_chan.valid = 1;
1049 				}
1050 			}
1051 			asid.v1 = NULL;
1052 			asf1d.v1 = NULL;
1053 			ed1 = NULL;
1054 			sed.v1 = NULL;
1055 		}
1056 
1057 		if ((acdp == NULL) &&
1058 		    (desc->bDescriptorType == UDESC_CS_INTERFACE) &&
1059 		    (desc->bDescriptorSubtype == AS_GENERAL) &&
1060 		    (desc->bDescriptorSubtype == UDESCSUB_AC_HEADER) &&
1061 		    (desc->bLength >= sizeof(*acdp))) {
1062 			acdp = (void *)desc;
1063 			audio_rev = UGETW(acdp->bcdADC);
1064 		}
1065 
1066 		if ((acdp != NULL) &&
1067 		    (desc->bDescriptorType == UDESC_CS_INTERFACE) &&
1068 		    (desc->bDescriptorSubtype == AS_GENERAL) &&
1069 		    (asid.v1 == NULL)) {
1070 			if (audio_rev >= UAUDIO_VERSION_30) {
1071 				/* FALLTHROUGH */
1072 			} else if (audio_rev >= UAUDIO_VERSION_20) {
1073 				if (desc->bLength >= sizeof(*asid.v2)) {
1074 					asid.v2 = (void *)desc;
1075 				}
1076 			} else {
1077 				if (desc->bLength >= sizeof(*asid.v1)) {
1078 					asid.v1 = (void *)desc;
1079 				}
1080 			}
1081 		}
1082 		if ((acdp != NULL) &&
1083 		    (desc->bDescriptorType == UDESC_CS_INTERFACE) &&
1084 		    (desc->bDescriptorSubtype == FORMAT_TYPE) &&
1085 		    (asf1d.v1 == NULL)) {
1086 			if (audio_rev >= UAUDIO_VERSION_30) {
1087 				/* FALLTHROUGH */
1088 			} else if (audio_rev >= UAUDIO_VERSION_20) {
1089 				if (desc->bLength >= sizeof(*asf1d.v2))
1090 					asf1d.v2 = (void *)desc;
1091 			} else {
1092 				if (desc->bLength >= sizeof(*asf1d.v1)) {
1093 					asf1d.v1 = (void *)desc;
1094 
1095 					if (asf1d.v1->bFormatType != FORMAT_TYPE_I) {
1096 						DPRINTFN(11, "ignored bFormatType = %d\n",
1097 						    asf1d.v1->bFormatType);
1098 						asf1d.v1 = NULL;
1099 						continue;
1100 					}
1101 					if (desc->bLength < (sizeof(*asf1d.v1) +
1102 					    ((asf1d.v1->bSamFreqType == 0) ? 6 :
1103 					    (asf1d.v1->bSamFreqType * 3)))) {
1104 						DPRINTFN(11, "invalid descriptor, "
1105 						    "too short\n");
1106 						asf1d.v1 = NULL;
1107 						continue;
1108 					}
1109 				}
1110 			}
1111 		}
1112 		if ((desc->bDescriptorType == UDESC_ENDPOINT) &&
1113 		    (desc->bLength >= UEP_MINSIZE) &&
1114 		    (ed1 == NULL)) {
1115 			ed1 = (void *)desc;
1116 			if (UE_GET_XFERTYPE(ed1->bmAttributes) != UE_ISOCHRONOUS) {
1117 				ed1 = NULL;
1118 				continue;
1119 			}
1120 		}
1121 		if ((acdp != NULL) &&
1122 		    (desc->bDescriptorType == UDESC_CS_ENDPOINT) &&
1123 		    (desc->bDescriptorSubtype == AS_GENERAL) &&
1124 		    (sed.v1 == NULL)) {
1125 			if (audio_rev >= UAUDIO_VERSION_30) {
1126 				/* FALLTHROUGH */
1127 			} else if (audio_rev >= UAUDIO_VERSION_20) {
1128 				if (desc->bLength >= sizeof(*sed.v2))
1129 					sed.v2 = (void *)desc;
1130 			} else {
1131 				if (desc->bLength >= sizeof(*sed.v1))
1132 					sed.v1 = (void *)desc;
1133 			}
1134 		}
1135 		if (audio_if == 0 || asid.v1 == NULL ||
1136 		    asf1d.v1 == NULL || ed1 == NULL ||
1137 		    sed.v1 == NULL) {
1138 			/* need more descriptors */
1139 			continue;
1140 		}
1141 
1142 		ep_dir = UE_GET_DIR(ed1->bEndpointAddress);
1143 
1144 		/* We ignore sync endpoint information until further. */
1145 
1146 		if (audio_rev >= UAUDIO_VERSION_30) {
1147 			goto next_ep;
1148 		} else if (audio_rev >= UAUDIO_VERSION_20) {
1149 
1150 			uint32_t dwFormat;
1151 			uint8_t bSubslotSize;
1152 
1153 			dwFormat = UGETDW(asid.v2->bmFormats);
1154 			bChannels = asid.v2->bNrChannels;
1155 			bBitResolution = asf1d.v2->bBitResolution;
1156 			bSubslotSize = asf1d.v2->bSubslotSize;
1157 
1158 			if (bBitResolution != (bSubslotSize * 8)) {
1159 				DPRINTF("Invalid bSubslotSize\n");
1160 				goto next_ep;
1161 			}
1162 
1163 			if ((bChannels != channels) ||
1164 			    (bBitResolution != bit_resolution)) {
1165 				DPRINTF("Wrong number of channels\n");
1166 				goto next_ep;
1167 			}
1168 
1169 			for (p_fmt = uaudio20_formats;
1170 			    p_fmt->wFormat != 0; p_fmt++) {
1171 				if ((p_fmt->wFormat & dwFormat) &&
1172 				    (p_fmt->bPrecision == bBitResolution))
1173 					break;
1174 			}
1175 
1176 			if (p_fmt->wFormat == 0) {
1177 				DPRINTF("Unsupported audio format\n");
1178 				goto next_ep;
1179 			}
1180 
1181 			for (x = 0; x != 256; x++) {
1182 				if (ep_dir == UE_DIR_OUT) {
1183 					if (!(sc->sc_mixer_clocks.bit_output[x / 8] &
1184 					    (1 << (x % 8)))) {
1185 						continue;
1186 					}
1187 				} else {
1188 					if (!(sc->sc_mixer_clocks.bit_input[x / 8] &
1189 					    (1 << (x % 8)))) {
1190 						continue;
1191 					}
1192 				}
1193 
1194 				DPRINTF("Checking clock ID=%d\n", x);
1195 
1196 				if (uaudio20_check_rate(udev,
1197 				    sc->sc_mixer_iface_no, x, rate)) {
1198 					DPRINTF("Unsupported sampling "
1199 					    "rate, id=%d\n", x);
1200 					goto next_ep;
1201 				}
1202 			}
1203 		} else {
1204 			uint16_t wFormat;
1205 
1206 			wFormat = UGETW(asid.v1->wFormatTag);
1207 			bChannels = UAUDIO_MAX_CHAN(asf1d.v1->bNrChannels);
1208 			bBitResolution = asf1d.v1->bBitResolution;
1209 
1210 			if (asf1d.v1->bSamFreqType == 0) {
1211 				DPRINTFN(16, "Sample rate: %d-%dHz\n",
1212 				    UA_SAMP_LO(asf1d.v1),
1213 				    UA_SAMP_HI(asf1d.v1));
1214 
1215 				if ((rate >= UA_SAMP_LO(asf1d.v1)) &&
1216 				    (rate <= UA_SAMP_HI(asf1d.v1)))
1217 					goto found_rate;
1218 			} else {
1219 
1220 				for (x = 0; x < asf1d.v1->bSamFreqType; x++) {
1221 					DPRINTFN(16, "Sample rate = %dHz\n",
1222 					    UA_GETSAMP(asf1d.v1, x));
1223 
1224 					if (rate == UA_GETSAMP(asf1d.v1, x))
1225 						goto found_rate;
1226 				}
1227 			}
1228 			goto next_ep;
1229 
1230 	found_rate:
1231 			for (p_fmt = uaudio10_formats;
1232 			    p_fmt->wFormat != 0; p_fmt++) {
1233 				if ((p_fmt->wFormat == wFormat) &&
1234 				    (p_fmt->bPrecision == bBitResolution))
1235 					break;
1236 			}
1237 			if (p_fmt->wFormat == 0) {
1238 				DPRINTF("Unsupported audio format\n");
1239 				goto next_ep;
1240 			}
1241 
1242 			if ((bChannels != channels) ||
1243 			    (bBitResolution != bit_resolution)) {
1244 				DPRINTF("Wrong number of channels\n");
1245 				goto next_ep;
1246 			}
1247 		}
1248 
1249 		chan = (ep_dir == UE_DIR_IN) ?
1250 		    &sc->sc_rec_chan : &sc->sc_play_chan;
1251 
1252 		if (chan->valid != 0 ||
1253 		    usbd_get_iface(udev, curidx) == NULL) {
1254 			DPRINTF("Channel already exists or "
1255 			    "interface is not valid\n");
1256 			goto next_ep;
1257 		}
1258 
1259 		chan->valid = 1;
1260 #ifdef USB_DEBUG
1261 		uaudio_chan_dump_ep_desc(ed1);
1262 #endif
1263 		DPRINTF("Sample rate = %dHz, channels = %d, "
1264 		    "bits = %d, format = %s\n", rate, channels,
1265 		    bit_resolution, p_fmt->description);
1266 
1267 		chan->sample_rate = rate;
1268 		chan->p_asf1d = asf1d;
1269 		chan->p_ed1 = ed1;
1270 		chan->p_fmt = p_fmt;
1271 		chan->p_sed = sed;
1272 		chan->iface_index = curidx;
1273 		chan->iface_alt_index = alt_index;
1274 
1275 		if (ep_dir == UE_DIR_IN)
1276 			chan->usb_cfg = uaudio_cfg_record;
1277 		else
1278 			chan->usb_cfg = uaudio_cfg_play;
1279 
1280 		chan->sample_size = (UAUDIO_MAX_CHAN(channels) *
1281 		    p_fmt->bPrecision) / 8;
1282 		chan->channels = channels;
1283 
1284 		if (ep_dir == UE_DIR_IN &&
1285 		    usbd_get_speed(udev) == USB_SPEED_FULL) {
1286 			uaudio_record_fix_fs(ed1,
1287 			    chan->sample_size * (rate / 1000),
1288 			    chan->sample_size * (rate / 4000));
1289 		}
1290 
1291 		if (sc->sc_sndstat_valid != 0) {
1292 			sbuf_printf(&sc->sc_sndstat, "\n\t"
1293 			    "mode %d.%d:(%s) %dch, %dbit, %s, %dHz",
1294 			    curidx, alt_index,
1295 			    (ep_dir == UE_DIR_IN) ? "input" : "output",
1296 				    channels, p_fmt->bPrecision,
1297 				    p_fmt->description, rate);
1298 		}
1299 
1300 	next_ep:
1301 		sed.v1 = NULL;
1302 		ed1 = NULL;
1303 	}
1304 }
1305 
1306 /* This structure defines all the supported rates. */
1307 
1308 static const uint32_t uaudio_rate_list[] = {
1309 	96000,
1310 	88000,
1311 	80000,
1312 	72000,
1313 	64000,
1314 	56000,
1315 	48000,
1316 	44100,
1317 	40000,
1318 	32000,
1319 	24000,
1320 	22050,
1321 	16000,
1322 	11025,
1323 	8000,
1324 	0
1325 };
1326 
1327 static void
1328 uaudio_chan_fill_info(struct uaudio_softc *sc, struct usb_device *udev)
1329 {
1330 	uint32_t rate = uaudio_default_rate;
1331 	uint8_t z;
1332 	uint8_t bits = uaudio_default_bits;
1333 	uint8_t y;
1334 	uint8_t channels = uaudio_default_channels;
1335 	uint8_t x;
1336 
1337 	bits -= (bits % 8);
1338 	if ((bits == 0) || (bits > 32)) {
1339 		/* set a valid value */
1340 		bits = 32;
1341 	}
1342 	if (channels == 0) {
1343 		switch (usbd_get_speed(udev)) {
1344 		case USB_SPEED_LOW:
1345 		case USB_SPEED_FULL:
1346 			/*
1347 			 * Due to high bandwidth usage and problems
1348 			 * with HIGH-speed split transactions we
1349 			 * disable surround setups on FULL-speed USB
1350 			 * by default
1351 			 */
1352 			channels = 2;
1353 			break;
1354 		default:
1355 			channels = 16;
1356 			break;
1357 		}
1358 	} else if (channels > 16) {
1359 		channels = 16;
1360 	}
1361 	if (sbuf_new(&sc->sc_sndstat, NULL, 4096, SBUF_AUTOEXTEND)) {
1362 		sc->sc_sndstat_valid = 1;
1363 	}
1364 	/* try to search for a valid config */
1365 
1366 	for (x = channels; x; x--) {
1367 		for (y = bits; y; y -= 8) {
1368 
1369 			/* try user defined rate, if any */
1370 			if (rate != 0)
1371 				uaudio_chan_fill_info_sub(sc, udev, rate, x, y);
1372 
1373 			/* try find a matching rate, if any */
1374 			for (z = 0; uaudio_rate_list[z]; z++) {
1375 				uaudio_chan_fill_info_sub(sc, udev, uaudio_rate_list[z], x, y);
1376 
1377 				if (sc->sc_rec_chan.valid &&
1378 				    sc->sc_play_chan.valid) {
1379 					goto done;
1380 				}
1381 			}
1382 		}
1383 	}
1384 
1385 done:
1386 	if (sc->sc_sndstat_valid) {
1387 		sbuf_finish(&sc->sc_sndstat);
1388 	}
1389 }
1390 
1391 static void
1392 uaudio_chan_play_callback(struct usb_xfer *xfer, usb_error_t error)
1393 {
1394 	struct uaudio_chan *ch = usbd_xfer_softc(xfer);
1395 	struct usb_page_cache *pc;
1396 	uint32_t total;
1397 	uint32_t blockcount;
1398 	uint32_t n;
1399 	uint32_t offset;
1400 	int actlen;
1401 	int sumlen;
1402 
1403 	usbd_xfer_status(xfer, &actlen, &sumlen, NULL, NULL);
1404 
1405 	if (ch->end == ch->start) {
1406 		DPRINTF("no buffer!\n");
1407 		return;
1408 	}
1409 
1410 	switch (USB_GET_STATE(xfer)) {
1411 	case USB_ST_TRANSFERRED:
1412 tr_transferred:
1413 		if (actlen < sumlen) {
1414 			DPRINTF("short transfer, "
1415 			    "%d of %d bytes\n", actlen, sumlen);
1416 		}
1417 		chn_intr(ch->pcm_ch);
1418 
1419 	case USB_ST_SETUP:
1420 		if (ch->bytes_per_frame[1] > usbd_xfer_max_framelen(xfer)) {
1421 			DPRINTF("bytes per transfer, %d, "
1422 			    "exceeds maximum, %d!\n",
1423 			    ch->bytes_per_frame[1],
1424 			    usbd_xfer_max_framelen(xfer));
1425 			break;
1426 		}
1427 
1428 		blockcount = ch->intr_frames;
1429 
1430 		/* setup number of frames */
1431 		usbd_xfer_set_frames(xfer, blockcount);
1432 
1433 		/* reset total length */
1434 		total = 0;
1435 
1436 		/* setup frame lengths */
1437 		for (n = 0; n != blockcount; n++) {
1438 			ch->sample_curr += ch->sample_rem;
1439 			if (ch->sample_curr >= ch->frames_per_second) {
1440 				ch->sample_curr -= ch->frames_per_second;
1441 				usbd_xfer_set_frame_len(xfer, n, ch->bytes_per_frame[1]);
1442 				total += ch->bytes_per_frame[1];
1443 			} else {
1444 				usbd_xfer_set_frame_len(xfer, n, ch->bytes_per_frame[0]);
1445 				total += ch->bytes_per_frame[0];
1446 			}
1447 		}
1448 
1449 		DPRINTFN(6, "transfer %d bytes\n", total);
1450 
1451 		offset = 0;
1452 
1453 		pc = usbd_xfer_get_frame(xfer, 0);
1454 		while (total > 0) {
1455 
1456 			n = (ch->end - ch->cur);
1457 			if (n > total) {
1458 				n = total;
1459 			}
1460 			usbd_copy_in(pc, offset, ch->cur, n);
1461 
1462 			total -= n;
1463 			ch->cur += n;
1464 			offset += n;
1465 
1466 			if (ch->cur >= ch->end) {
1467 				ch->cur = ch->start;
1468 			}
1469 		}
1470 
1471 		usbd_transfer_submit(xfer);
1472 		break;
1473 
1474 	default:			/* Error */
1475 		if (error == USB_ERR_CANCELLED) {
1476 			break;
1477 		}
1478 		goto tr_transferred;
1479 	}
1480 }
1481 
1482 static void
1483 uaudio_chan_record_callback(struct usb_xfer *xfer, usb_error_t error)
1484 {
1485 	struct uaudio_chan *ch = usbd_xfer_softc(xfer);
1486 	struct usb_page_cache *pc;
1487 	uint32_t offset0;
1488 	uint32_t offset1;
1489 	uint32_t mfl;
1490 	int m;
1491 	int n;
1492 	int len;
1493 	int actlen;
1494 	int nframes;
1495 	int blockcount;
1496 
1497 	usbd_xfer_status(xfer, &actlen, NULL, NULL, &nframes);
1498 	mfl = usbd_xfer_max_framelen(xfer);
1499 
1500 	if (ch->end == ch->start) {
1501 		DPRINTF("no buffer!\n");
1502 		return;
1503 	}
1504 
1505 	switch (USB_GET_STATE(xfer)) {
1506 	case USB_ST_TRANSFERRED:
1507 
1508 		DPRINTFN(6, "transferred %d bytes\n", actlen);
1509 
1510 		offset0 = 0;
1511 		pc = usbd_xfer_get_frame(xfer, 0);
1512 
1513 		for (n = 0; n != nframes; n++) {
1514 
1515 			offset1 = offset0;
1516 			len = usbd_xfer_frame_len(xfer, n);
1517 
1518 			while (len > 0) {
1519 
1520 				m = (ch->end - ch->cur);
1521 
1522 				if (m > len)
1523 					m = len;
1524 
1525 				usbd_copy_out(pc, offset1, ch->cur, m);
1526 
1527 				len -= m;
1528 				offset1 += m;
1529 				ch->cur += m;
1530 
1531 				if (ch->cur >= ch->end) {
1532 					ch->cur = ch->start;
1533 				}
1534 			}
1535 
1536 			offset0 += mfl;
1537 		}
1538 
1539 		chn_intr(ch->pcm_ch);
1540 
1541 	case USB_ST_SETUP:
1542 tr_setup:
1543 		blockcount = ch->intr_frames;
1544 
1545 		usbd_xfer_set_frames(xfer, blockcount);
1546 		for (n = 0; n < blockcount; n++) {
1547 			usbd_xfer_set_frame_len(xfer, n, mfl);
1548 		}
1549 
1550 		usbd_transfer_submit(xfer);
1551 		break;
1552 
1553 	default:			/* Error */
1554 		if (error == USB_ERR_CANCELLED) {
1555 			break;
1556 		}
1557 		goto tr_setup;
1558 	}
1559 }
1560 
1561 void   *
1562 uaudio_chan_init(struct uaudio_softc *sc, struct snd_dbuf *b,
1563     struct pcm_channel *c, int dir)
1564 {
1565 	struct uaudio_chan *ch = ((dir == PCMDIR_PLAY) ?
1566 	    &sc->sc_play_chan : &sc->sc_rec_chan);
1567 	uint32_t buf_size;
1568 	uint32_t frames;
1569 	uint32_t format;
1570 	uint16_t fps;
1571 	uint8_t endpoint;
1572 	uint8_t blocks;
1573 	uint8_t iface_index;
1574 	uint8_t alt_index;
1575 	uint8_t fps_shift;
1576 	usb_error_t err;
1577 
1578 	fps = usbd_get_isoc_fps(sc->sc_udev);
1579 
1580 	if (fps < 8000) {
1581 		/* FULL speed USB */
1582 		frames = 8;
1583 	} else {
1584 		/* HIGH speed USB */
1585 		frames = UAUDIO_NFRAMES;
1586 	}
1587 
1588 	/* setup play/record format */
1589 
1590 	ch->pcm_cap.fmtlist = ch->pcm_format;
1591 
1592 	ch->pcm_format[0] = 0;
1593 	ch->pcm_format[1] = 0;
1594 
1595 	ch->pcm_cap.minspeed = ch->sample_rate;
1596 	ch->pcm_cap.maxspeed = ch->sample_rate;
1597 
1598 	/* setup mutex and PCM channel */
1599 
1600 	ch->pcm_ch = c;
1601 	ch->pcm_mtx = c->lock;
1602 
1603 	format = ch->p_fmt->freebsd_fmt;
1604 
1605 	switch (ch->channels) {
1606 	case 2:
1607 		/* stereo */
1608 		format = SND_FORMAT(format, 2, 0);
1609 		break;
1610 	case 1:
1611 		/* mono */
1612 		format = SND_FORMAT(format, 1, 0);
1613 		break;
1614 	default:
1615 		/* surround and more */
1616 		format = feeder_matrix_default_format(
1617 		    SND_FORMAT(format, ch->channels, 0));
1618 		break;
1619 	}
1620 
1621 	ch->pcm_cap.fmtlist[0] = format;
1622 	ch->pcm_cap.fmtlist[1] = 0;
1623 
1624 	/* check if format is not supported */
1625 
1626 	if (format == 0) {
1627 		DPRINTF("The selected audio format is not supported\n");
1628 		goto error;
1629 	}
1630 
1631 	/* set alternate interface corresponding to the mode */
1632 
1633 	endpoint = ch->p_ed1->bEndpointAddress;
1634 	iface_index = ch->iface_index;
1635 	alt_index = ch->iface_alt_index;
1636 
1637 	DPRINTF("endpoint=0x%02x, speed=%d, iface=%d alt=%d\n",
1638 	    endpoint, ch->sample_rate, iface_index, alt_index);
1639 
1640 	err = usbd_set_alt_interface_index(sc->sc_udev, iface_index, alt_index);
1641 	if (err) {
1642 		DPRINTF("setting of alternate index failed: %s!\n",
1643 		    usbd_errstr(err));
1644 		goto error;
1645 	}
1646 	usbd_set_parent_iface(sc->sc_udev, iface_index,
1647 	    sc->sc_mixer_iface_index);
1648 
1649 	/*
1650 	 * Only set the sample rate if the channel reports that it
1651 	 * supports the frequency control.
1652 	 */
1653 
1654 	if (sc->sc_audio_rev >= UAUDIO_VERSION_30) {
1655 		/* FALLTHROUGH */
1656 	} else if (sc->sc_audio_rev >= UAUDIO_VERSION_20) {
1657 		unsigned int x;
1658 
1659 		for (x = 0; x != 256; x++) {
1660 			if (dir == PCMDIR_PLAY) {
1661 				if (!(sc->sc_mixer_clocks.bit_output[x / 8] &
1662 				    (1 << (x % 8)))) {
1663 					continue;
1664 				}
1665 			} else {
1666 				if (!(sc->sc_mixer_clocks.bit_input[x / 8] &
1667 				    (1 << (x % 8)))) {
1668 					continue;
1669 				}
1670 			}
1671 
1672 			if (uaudio20_set_speed(sc->sc_udev,
1673 			    sc->sc_mixer_iface_no, x, ch->sample_rate)) {
1674 				/*
1675 				 * If the endpoint is adaptive setting
1676 				 * the speed may fail.
1677 				 */
1678 				DPRINTF("setting of sample rate failed! "
1679 				    "(continuing anyway)\n");
1680 			}
1681 		}
1682 	} else if (ch->p_sed.v1->bmAttributes & UA_SED_FREQ_CONTROL) {
1683 		if (uaudio_set_speed(sc->sc_udev, endpoint, ch->sample_rate)) {
1684 			/*
1685 			 * If the endpoint is adaptive setting the
1686 			 * speed may fail.
1687 			 */
1688 			DPRINTF("setting of sample rate failed! "
1689 			    "(continuing anyway)\n");
1690 		}
1691 	}
1692 	if (usbd_transfer_setup(sc->sc_udev, &iface_index, ch->xfer,
1693 	    ch->usb_cfg, UAUDIO_NCHANBUFS, ch, ch->pcm_mtx)) {
1694 		DPRINTF("could not allocate USB transfers!\n");
1695 		goto error;
1696 	}
1697 
1698 	fps_shift = usbd_xfer_get_fps_shift(ch->xfer[0]);
1699 
1700 	/* down shift number of frames per second, if any */
1701 	fps >>= fps_shift;
1702 	frames >>= fps_shift;
1703 
1704 	/* bytes per frame should not be zero */
1705 	ch->bytes_per_frame[0] = ((ch->sample_rate / fps) * ch->sample_size);
1706 	ch->bytes_per_frame[1] = (((ch->sample_rate + fps - 1) / fps) * ch->sample_size);
1707 
1708 	/* setup data rate dithering, if any */
1709 	ch->frames_per_second = fps;
1710 	ch->sample_rem = ch->sample_rate % fps;
1711 	ch->sample_curr = 0;
1712 	ch->frames_per_second = fps;
1713 
1714 	/* compute required buffer size */
1715 	buf_size = (ch->bytes_per_frame[1] * frames);
1716 
1717 	ch->intr_size = buf_size;
1718 	ch->intr_frames = frames;
1719 
1720 	DPRINTF("fps=%d sample_rem=%d\n", fps, ch->sample_rem);
1721 
1722 	if (ch->intr_frames == 0) {
1723 		DPRINTF("frame shift is too high!\n");
1724 		goto error;
1725 	}
1726 
1727 	/* setup double buffering */
1728 	buf_size *= 2;
1729 	blocks = 2;
1730 
1731 	ch->buf = malloc(buf_size, M_DEVBUF, M_WAITOK | M_ZERO);
1732 	if (ch->buf == NULL)
1733 		goto error;
1734 	if (sndbuf_setup(b, ch->buf, buf_size) != 0)
1735 		goto error;
1736 	if (sndbuf_resize(b, blocks, ch->intr_size))
1737 		goto error;
1738 
1739 	ch->start = ch->buf;
1740 	ch->end = ch->buf + buf_size;
1741 	ch->cur = ch->buf;
1742 	ch->pcm_buf = b;
1743 
1744 	if (ch->pcm_mtx == NULL) {
1745 		DPRINTF("ERROR: PCM channels does not have a mutex!\n");
1746 		goto error;
1747 	}
1748 
1749 	return (ch);
1750 
1751 error:
1752 	uaudio_chan_free(ch);
1753 	return (NULL);
1754 }
1755 
1756 int
1757 uaudio_chan_free(struct uaudio_chan *ch)
1758 {
1759 	if (ch->buf != NULL) {
1760 		free(ch->buf, M_DEVBUF);
1761 		ch->buf = NULL;
1762 	}
1763 	usbd_transfer_unsetup(ch->xfer, UAUDIO_NCHANBUFS);
1764 
1765 	ch->valid = 0;
1766 
1767 	return (0);
1768 }
1769 
1770 int
1771 uaudio_chan_set_param_blocksize(struct uaudio_chan *ch, uint32_t blocksize)
1772 {
1773 	return (ch->intr_size);
1774 }
1775 
1776 int
1777 uaudio_chan_set_param_fragments(struct uaudio_chan *ch, uint32_t blocksize,
1778     uint32_t blockcount)
1779 {
1780 	return (1);
1781 }
1782 
1783 int
1784 uaudio_chan_set_param_speed(struct uaudio_chan *ch, uint32_t speed)
1785 {
1786 	if (speed != ch->sample_rate) {
1787 		DPRINTF("rate conversion required\n");
1788 	}
1789 	return (ch->sample_rate);
1790 }
1791 
1792 int
1793 uaudio_chan_getptr(struct uaudio_chan *ch)
1794 {
1795 	return (ch->cur - ch->start);
1796 }
1797 
1798 struct pcmchan_caps *
1799 uaudio_chan_getcaps(struct uaudio_chan *ch)
1800 {
1801 	return (&ch->pcm_cap);
1802 }
1803 
1804 static struct pcmchan_matrix uaudio_chan_matrix_swap_2_0 = {
1805 	.id = SND_CHN_MATRIX_DRV,
1806 	.channels = 2,
1807 	.ext = 0,
1808 	.map = {
1809 		/* Right */
1810 		[0] = {
1811 			.type = SND_CHN_T_FR,
1812 			.members =
1813 			    SND_CHN_T_MASK_FR | SND_CHN_T_MASK_FC |
1814 			    SND_CHN_T_MASK_LF | SND_CHN_T_MASK_BR |
1815 			    SND_CHN_T_MASK_BC | SND_CHN_T_MASK_SR
1816 		},
1817 		/* Left */
1818 		[1] = {
1819 			.type = SND_CHN_T_FL,
1820 			.members =
1821 			    SND_CHN_T_MASK_FL | SND_CHN_T_MASK_FC |
1822 			    SND_CHN_T_MASK_LF | SND_CHN_T_MASK_BL |
1823 			    SND_CHN_T_MASK_BC | SND_CHN_T_MASK_SL
1824 		},
1825 		[2] = {
1826 			.type = SND_CHN_T_MAX,
1827 			.members = 0
1828 		}
1829 	},
1830 	.mask = SND_CHN_T_MASK_FR | SND_CHN_T_MASK_FL,
1831 	.offset = {  1,  0, -1, -1, -1, -1, -1, -1, -1,
1832 		    -1, -1, -1, -1, -1, -1, -1, -1, -1  }
1833 };
1834 
1835 struct pcmchan_matrix *
1836 uaudio_chan_getmatrix(struct uaudio_chan *ch, uint32_t format)
1837 {
1838 	struct uaudio_softc *sc;
1839 
1840 	sc = ch->priv_sc;
1841 
1842 	if (sc != NULL && sc->sc_uq_audio_swap_lr != 0 &&
1843 	    AFMT_CHANNEL(format) == 2)
1844 		return (&uaudio_chan_matrix_swap_2_0);
1845 
1846 	return (feeder_matrix_format_map(format));
1847 }
1848 
1849 int
1850 uaudio_chan_set_param_format(struct uaudio_chan *ch, uint32_t format)
1851 {
1852 	ch->format = format;
1853 	return (0);
1854 }
1855 
1856 int
1857 uaudio_chan_start(struct uaudio_chan *ch)
1858 {
1859 	ch->cur = ch->start;
1860 
1861 #if (UAUDIO_NCHANBUFS != 2)
1862 #error "please update code"
1863 #endif
1864 	if (ch->xfer[0]) {
1865 		usbd_transfer_start(ch->xfer[0]);
1866 	}
1867 	if (ch->xfer[1]) {
1868 		usbd_transfer_start(ch->xfer[1]);
1869 	}
1870 	return (0);
1871 }
1872 
1873 int
1874 uaudio_chan_stop(struct uaudio_chan *ch)
1875 {
1876 #if (UAUDIO_NCHANBUFS != 2)
1877 #error "please update code"
1878 #endif
1879 	usbd_transfer_stop(ch->xfer[0]);
1880 	usbd_transfer_stop(ch->xfer[1]);
1881 	return (0);
1882 }
1883 
1884 /*========================================================================*
1885  * AC - Audio Controller - routines
1886  *========================================================================*/
1887 
1888 static void
1889 uaudio_mixer_add_ctl_sub(struct uaudio_softc *sc, struct uaudio_mixer_node *mc)
1890 {
1891 	struct uaudio_mixer_node *p_mc_new =
1892 	    malloc(sizeof(*p_mc_new), M_USBDEV, M_WAITOK);
1893 
1894 	if (p_mc_new != NULL) {
1895 		memcpy(p_mc_new, mc, sizeof(*p_mc_new));
1896 		p_mc_new->next = sc->sc_mixer_root;
1897 		sc->sc_mixer_root = p_mc_new;
1898 		sc->sc_mixer_count++;
1899 	} else {
1900 		DPRINTF("out of memory\n");
1901 	}
1902 }
1903 
1904 static void
1905 uaudio_mixer_add_ctl(struct uaudio_softc *sc, struct uaudio_mixer_node *mc)
1906 {
1907 	int32_t res;
1908 
1909 	if (mc->class < UAC_NCLASSES) {
1910 		DPRINTF("adding %s.%d\n",
1911 		    uac_names[mc->class], mc->ctl);
1912 	} else {
1913 		DPRINTF("adding %d\n", mc->ctl);
1914 	}
1915 
1916 	if (mc->type == MIX_ON_OFF) {
1917 		mc->minval = 0;
1918 		mc->maxval = 1;
1919 	} else if (mc->type == MIX_SELECTOR) {
1920 	} else {
1921 
1922 		/* determine min and max values */
1923 
1924 		mc->minval = uaudio_mixer_get(sc->sc_udev,
1925 		    sc->sc_audio_rev, GET_MIN, mc);
1926 		mc->maxval = uaudio_mixer_get(sc->sc_udev,
1927 		    sc->sc_audio_rev, GET_MAX, mc);
1928 
1929 		/* check if max and min was swapped */
1930 
1931 		if (mc->maxval < mc->minval) {
1932 			res = mc->maxval;
1933 			mc->maxval = mc->minval;
1934 			mc->minval = res;
1935 		}
1936 
1937 		/* compute value range */
1938 		mc->mul = mc->maxval - mc->minval;
1939 		if (mc->mul == 0)
1940 			mc->mul = 1;
1941 
1942 		/* compute value alignment */
1943 		res = uaudio_mixer_get(sc->sc_udev,
1944 		    sc->sc_audio_rev, GET_RES, mc);
1945 
1946 		DPRINTF("Resolution = %d\n", (int)res);
1947 	}
1948 
1949 	uaudio_mixer_add_ctl_sub(sc, mc);
1950 
1951 #ifdef USB_DEBUG
1952 	if (uaudio_debug > 2) {
1953 		uint8_t i;
1954 
1955 		for (i = 0; i < mc->nchan; i++) {
1956 			DPRINTF("[mix] wValue=%04x\n", mc->wValue[0]);
1957 		}
1958 		DPRINTF("[mix] wIndex=%04x type=%d ctl='%d' "
1959 		    "min=%d max=%d\n",
1960 		    mc->wIndex, mc->type, mc->ctl,
1961 		    mc->minval, mc->maxval);
1962 	}
1963 #endif
1964 }
1965 
1966 static void
1967 uaudio_mixer_add_mixer(struct uaudio_softc *sc,
1968     const struct uaudio_terminal_node *iot, int id)
1969 {
1970 	struct uaudio_mixer_node mix;
1971 
1972 	const struct usb_audio_mixer_unit_0 *d0 = iot[id].u.mu_v1;
1973 	const struct usb_audio_mixer_unit_1 *d1;
1974 
1975 	uint32_t bno;			/* bit number */
1976 	uint32_t p;			/* bit number accumulator */
1977 	uint32_t mo;			/* matching outputs */
1978 	uint32_t mc;			/* matching channels */
1979 	uint32_t ichs;			/* input channels */
1980 	uint32_t ochs;			/* output channels */
1981 	uint32_t c;
1982 	uint32_t chs;			/* channels */
1983 	uint32_t i;
1984 	uint32_t o;
1985 
1986 	DPRINTFN(3, "bUnitId=%d bNrInPins=%d\n",
1987 	    d0->bUnitId, d0->bNrInPins);
1988 
1989 	/* compute the number of input channels */
1990 
1991 	ichs = 0;
1992 	for (i = 0; i < d0->bNrInPins; i++) {
1993 		ichs += uaudio_mixer_get_cluster(
1994 		    d0->baSourceId[i], iot).bNrChannels;
1995 	}
1996 
1997 	d1 = (const void *)(d0->baSourceId + d0->bNrInPins);
1998 
1999 	/* and the number of output channels */
2000 
2001 	ochs = d1->bNrChannels;
2002 
2003 	DPRINTFN(3, "ichs=%d ochs=%d\n", ichs, ochs);
2004 
2005 	memset(&mix, 0, sizeof(mix));
2006 
2007 	mix.wIndex = MAKE_WORD(d0->bUnitId, sc->sc_mixer_iface_no);
2008 	uaudio_mixer_determine_class(&iot[id], &mix);
2009 	mix.type = MIX_SIGNED_16;
2010 
2011 	if (uaudio_mixer_verify_desc(d0, ((ichs * ochs) + 7) / 8) == NULL)
2012 		return;
2013 
2014 	for (p = i = 0; i < d0->bNrInPins; i++) {
2015 		chs = uaudio_mixer_get_cluster(
2016 		    d0->baSourceId[i], iot).bNrChannels;
2017 		mc = 0;
2018 		for (c = 0; c < chs; c++) {
2019 			mo = 0;
2020 			for (o = 0; o < ochs; o++) {
2021 				bno = ((p + c) * ochs) + o;
2022 				if (BIT_TEST(d1->bmControls, bno))
2023 					mo++;
2024 			}
2025 			if (mo == 1)
2026 				mc++;
2027 		}
2028 		if ((mc == chs) && (chs <= MIX_MAX_CHAN)) {
2029 
2030 			/* repeat bit-scan */
2031 
2032 			mc = 0;
2033 			for (c = 0; c < chs; c++) {
2034 				for (o = 0; o < ochs; o++) {
2035 					bno = ((p + c) * ochs) + o;
2036 					if (BIT_TEST(d1->bmControls, bno))
2037 						mix.wValue[mc++] = MAKE_WORD(p + c + 1, o + 1);
2038 				}
2039 			}
2040 			mix.nchan = chs;
2041 			uaudio_mixer_add_ctl(sc, &mix);
2042 		}
2043 		p += chs;
2044 	}
2045 }
2046 
2047 static void
2048 uaudio20_mixer_add_mixer(struct uaudio_softc *sc,
2049     const struct uaudio_terminal_node *iot, int id)
2050 {
2051 	struct uaudio_mixer_node mix;
2052 
2053 	const struct usb_audio20_mixer_unit_0 *d0 = iot[id].u.mu_v2;
2054 	const struct usb_audio20_mixer_unit_1 *d1;
2055 
2056 	uint32_t bno;			/* bit number */
2057 	uint32_t p;			/* bit number accumulator */
2058 	uint32_t mo;			/* matching outputs */
2059 	uint32_t mc;			/* matching channels */
2060 	uint32_t ichs;			/* input channels */
2061 	uint32_t ochs;			/* output channels */
2062 	uint32_t c;
2063 	uint32_t chs;			/* channels */
2064 	uint32_t i;
2065 	uint32_t o;
2066 
2067 	DPRINTFN(3, "bUnitId=%d bNrInPins=%d\n",
2068 	    d0->bUnitId, d0->bNrInPins);
2069 
2070 	/* compute the number of input channels */
2071 
2072 	ichs = 0;
2073 	for (i = 0; i < d0->bNrInPins; i++) {
2074 		ichs += uaudio20_mixer_get_cluster(
2075 		    d0->baSourceId[i], iot).bNrChannels;
2076 	}
2077 
2078 	d1 = (const void *)(d0->baSourceId + d0->bNrInPins);
2079 
2080 	/* and the number of output channels */
2081 
2082 	ochs = d1->bNrChannels;
2083 
2084 	DPRINTFN(3, "ichs=%d ochs=%d\n", ichs, ochs);
2085 
2086 	memset(&mix, 0, sizeof(mix));
2087 
2088 	mix.wIndex = MAKE_WORD(d0->bUnitId, sc->sc_mixer_iface_no);
2089 	uaudio20_mixer_determine_class(&iot[id], &mix);
2090 	mix.type = MIX_SIGNED_16;
2091 
2092 	if (uaudio20_mixer_verify_desc(d0, ((ichs * ochs) + 7) / 8) == NULL)
2093 		return;
2094 
2095 	for (p = i = 0; i < d0->bNrInPins; i++) {
2096 		chs = uaudio20_mixer_get_cluster(
2097 		    d0->baSourceId[i], iot).bNrChannels;
2098 		mc = 0;
2099 		for (c = 0; c < chs; c++) {
2100 			mo = 0;
2101 			for (o = 0; o < ochs; o++) {
2102 				bno = ((p + c) * ochs) + o;
2103 				if (BIT_TEST(d1->bmControls, bno))
2104 					mo++;
2105 			}
2106 			if (mo == 1)
2107 				mc++;
2108 		}
2109 		if ((mc == chs) && (chs <= MIX_MAX_CHAN)) {
2110 
2111 			/* repeat bit-scan */
2112 
2113 			mc = 0;
2114 			for (c = 0; c < chs; c++) {
2115 				for (o = 0; o < ochs; o++) {
2116 					bno = ((p + c) * ochs) + o;
2117 					if (BIT_TEST(d1->bmControls, bno))
2118 						mix.wValue[mc++] = MAKE_WORD(p + c + 1, o + 1);
2119 				}
2120 			}
2121 			mix.nchan = chs;
2122 			uaudio_mixer_add_ctl(sc, &mix);
2123 		}
2124 		p += chs;
2125 	}
2126 }
2127 
2128 static void
2129 uaudio_mixer_add_selector(struct uaudio_softc *sc,
2130     const struct uaudio_terminal_node *iot, int id)
2131 {
2132 	const struct usb_audio_selector_unit *d = iot[id].u.su_v1;
2133 	struct uaudio_mixer_node mix;
2134 	uint16_t i;
2135 
2136 	DPRINTFN(3, "bUnitId=%d bNrInPins=%d\n",
2137 	    d->bUnitId, d->bNrInPins);
2138 
2139 	if (d->bNrInPins == 0) {
2140 		return;
2141 	}
2142 	memset(&mix, 0, sizeof(mix));
2143 
2144 	mix.wIndex = MAKE_WORD(d->bUnitId, sc->sc_mixer_iface_no);
2145 	mix.wValue[0] = MAKE_WORD(0, 0);
2146 	uaudio_mixer_determine_class(&iot[id], &mix);
2147 	mix.nchan = 1;
2148 	mix.type = MIX_SELECTOR;
2149 
2150 	mix.ctl = SOUND_MIXER_NRDEVICES;
2151 	mix.minval = 1;
2152 	mix.maxval = d->bNrInPins;
2153 
2154 	if (mix.maxval > MAX_SELECTOR_INPUT_PIN) {
2155 		mix.maxval = MAX_SELECTOR_INPUT_PIN;
2156 	}
2157 	mix.mul = (mix.maxval - mix.minval);
2158 	for (i = 0; i < MAX_SELECTOR_INPUT_PIN; i++) {
2159 		mix.slctrtype[i] = SOUND_MIXER_NRDEVICES;
2160 	}
2161 
2162 	for (i = 0; i < mix.maxval; i++) {
2163 		mix.slctrtype[i] = uaudio_mixer_feature_name(
2164 		    &iot[d->baSourceId[i]], &mix);
2165 	}
2166 
2167 	mix.class = 0;			/* not used */
2168 
2169 	uaudio_mixer_add_ctl(sc, &mix);
2170 }
2171 
2172 static void
2173 uaudio20_mixer_add_selector(struct uaudio_softc *sc,
2174     const struct uaudio_terminal_node *iot, int id)
2175 {
2176 	const struct usb_audio20_selector_unit *d = iot[id].u.su_v2;
2177 	struct uaudio_mixer_node mix;
2178 	uint16_t i;
2179 
2180 	DPRINTFN(3, "bUnitId=%d bNrInPins=%d\n",
2181 	    d->bUnitId, d->bNrInPins);
2182 
2183 	if (d->bNrInPins == 0)
2184 		return;
2185 
2186 	memset(&mix, 0, sizeof(mix));
2187 
2188 	mix.wIndex = MAKE_WORD(d->bUnitId, sc->sc_mixer_iface_no);
2189 	mix.wValue[0] = MAKE_WORD(0, 0);
2190 	uaudio20_mixer_determine_class(&iot[id], &mix);
2191 	mix.nchan = 1;
2192 	mix.type = MIX_SELECTOR;
2193 
2194 	mix.ctl = SOUND_MIXER_NRDEVICES;
2195 	mix.minval = 1;
2196 	mix.maxval = d->bNrInPins;
2197 
2198 	if (mix.maxval > MAX_SELECTOR_INPUT_PIN)
2199 		mix.maxval = MAX_SELECTOR_INPUT_PIN;
2200 
2201 	mix.mul = (mix.maxval - mix.minval);
2202 	for (i = 0; i < MAX_SELECTOR_INPUT_PIN; i++)
2203 		mix.slctrtype[i] = SOUND_MIXER_NRDEVICES;
2204 
2205 	for (i = 0; i < mix.maxval; i++) {
2206 		mix.slctrtype[i] = uaudio20_mixer_feature_name(
2207 		    &iot[d->baSourceId[i]], &mix);
2208 	}
2209 
2210 	mix.class = 0;			/* not used */
2211 
2212 	uaudio_mixer_add_ctl(sc, &mix);
2213 }
2214 
2215 static uint32_t
2216 uaudio_mixer_feature_get_bmaControls(const struct usb_audio_feature_unit *d,
2217     uint8_t i)
2218 {
2219 	uint32_t temp = 0;
2220 	uint32_t offset = (i * d->bControlSize);
2221 
2222 	if (d->bControlSize > 0) {
2223 		temp |= d->bmaControls[offset];
2224 		if (d->bControlSize > 1) {
2225 			temp |= d->bmaControls[offset + 1] << 8;
2226 			if (d->bControlSize > 2) {
2227 				temp |= d->bmaControls[offset + 2] << 16;
2228 				if (d->bControlSize > 3) {
2229 					temp |= d->bmaControls[offset + 3] << 24;
2230 				}
2231 			}
2232 		}
2233 	}
2234 	return (temp);
2235 }
2236 
2237 static void
2238 uaudio_mixer_add_feature(struct uaudio_softc *sc,
2239     const struct uaudio_terminal_node *iot, int id)
2240 {
2241 	const struct usb_audio_feature_unit *d = iot[id].u.fu_v1;
2242 	struct uaudio_mixer_node mix;
2243 	uint32_t fumask;
2244 	uint32_t mmask;
2245 	uint32_t cmask;
2246 	uint16_t mixernumber;
2247 	uint8_t nchan;
2248 	uint8_t chan;
2249 	uint8_t ctl;
2250 	uint8_t i;
2251 
2252 	if (d->bControlSize == 0) {
2253 		return;
2254 	}
2255 	memset(&mix, 0, sizeof(mix));
2256 
2257 	nchan = (d->bLength - 7) / d->bControlSize;
2258 	mmask = uaudio_mixer_feature_get_bmaControls(d, 0);
2259 	cmask = 0;
2260 
2261 	if (nchan == 0) {
2262 		return;
2263 	}
2264 	/* figure out what we can control */
2265 
2266 	for (chan = 1; chan < nchan; chan++) {
2267 		DPRINTFN(10, "chan=%d mask=%x\n",
2268 		    chan, uaudio_mixer_feature_get_bmaControls(d, chan));
2269 
2270 		cmask |= uaudio_mixer_feature_get_bmaControls(d, chan);
2271 	}
2272 
2273 	if (nchan > MIX_MAX_CHAN) {
2274 		nchan = MIX_MAX_CHAN;
2275 	}
2276 	mix.wIndex = MAKE_WORD(d->bUnitId, sc->sc_mixer_iface_no);
2277 
2278 	for (ctl = 1; ctl <= LOUDNESS_CONTROL; ctl++) {
2279 
2280 		fumask = FU_MASK(ctl);
2281 
2282 		DPRINTFN(5, "ctl=%d fumask=0x%04x\n",
2283 		    ctl, fumask);
2284 
2285 		if (mmask & fumask) {
2286 			mix.nchan = 1;
2287 			mix.wValue[0] = MAKE_WORD(ctl, 0);
2288 		} else if (cmask & fumask) {
2289 			mix.nchan = nchan - 1;
2290 			for (i = 1; i < nchan; i++) {
2291 				if (uaudio_mixer_feature_get_bmaControls(d, i) & fumask)
2292 					mix.wValue[i - 1] = MAKE_WORD(ctl, i);
2293 				else
2294 					mix.wValue[i - 1] = -1;
2295 			}
2296 		} else {
2297 			continue;
2298 		}
2299 
2300 		mixernumber = uaudio_mixer_feature_name(&iot[id], &mix);
2301 
2302 		switch (ctl) {
2303 		case MUTE_CONTROL:
2304 			mix.type = MIX_ON_OFF;
2305 			mix.ctl = SOUND_MIXER_NRDEVICES;
2306 			break;
2307 
2308 		case VOLUME_CONTROL:
2309 			mix.type = MIX_SIGNED_16;
2310 			mix.ctl = mixernumber;
2311 			break;
2312 
2313 		case BASS_CONTROL:
2314 			mix.type = MIX_SIGNED_8;
2315 			mix.ctl = SOUND_MIXER_BASS;
2316 			break;
2317 
2318 		case MID_CONTROL:
2319 			mix.type = MIX_SIGNED_8;
2320 			mix.ctl = SOUND_MIXER_NRDEVICES;	/* XXXXX */
2321 			break;
2322 
2323 		case TREBLE_CONTROL:
2324 			mix.type = MIX_SIGNED_8;
2325 			mix.ctl = SOUND_MIXER_TREBLE;
2326 			break;
2327 
2328 		case GRAPHIC_EQUALIZER_CONTROL:
2329 			continue;	/* XXX don't add anything */
2330 			break;
2331 
2332 		case AGC_CONTROL:
2333 			mix.type = MIX_ON_OFF;
2334 			mix.ctl = SOUND_MIXER_NRDEVICES;	/* XXXXX */
2335 			break;
2336 
2337 		case DELAY_CONTROL:
2338 			mix.type = MIX_UNSIGNED_16;
2339 			mix.ctl = SOUND_MIXER_NRDEVICES;	/* XXXXX */
2340 			break;
2341 
2342 		case BASS_BOOST_CONTROL:
2343 			mix.type = MIX_ON_OFF;
2344 			mix.ctl = SOUND_MIXER_NRDEVICES;	/* XXXXX */
2345 			break;
2346 
2347 		case LOUDNESS_CONTROL:
2348 			mix.type = MIX_ON_OFF;
2349 			mix.ctl = SOUND_MIXER_LOUD;	/* Is this correct ? */
2350 			break;
2351 
2352 		default:
2353 			mix.type = MIX_UNKNOWN;
2354 			break;
2355 		}
2356 
2357 		if (mix.type != MIX_UNKNOWN)
2358 			uaudio_mixer_add_ctl(sc, &mix);
2359 	}
2360 }
2361 
2362 static void
2363 uaudio20_mixer_add_feature(struct uaudio_softc *sc,
2364     const struct uaudio_terminal_node *iot, int id)
2365 {
2366 	const struct usb_audio20_feature_unit *d = iot[id].u.fu_v2;
2367 	struct uaudio_mixer_node mix;
2368 	uint32_t ctl;
2369 	uint32_t mmask;
2370 	uint32_t cmask;
2371 	uint16_t mixernumber;
2372 	uint8_t nchan;
2373 	uint8_t chan;
2374 	uint8_t i;
2375 	uint8_t what;
2376 
2377 	if (UGETDW(d->bmaControls[0]) == 0)
2378 		return;
2379 
2380 	memset(&mix, 0, sizeof(mix));
2381 
2382 	nchan = (d->bLength - 6) / 4;
2383 	mmask = UGETDW(d->bmaControls[0]);
2384 	cmask = 0;
2385 
2386 	if (nchan == 0)
2387 		return;
2388 
2389 	/* figure out what we can control */
2390 
2391 	for (chan = 1; chan < nchan; chan++)
2392 		cmask |= UGETDW(d->bmaControls[chan]);
2393 
2394 	if (nchan > MIX_MAX_CHAN)
2395 		nchan = MIX_MAX_CHAN;
2396 
2397 	mix.wIndex = MAKE_WORD(d->bUnitId, sc->sc_mixer_iface_no);
2398 
2399 	for (ctl = 3; ctl != 0; ctl <<= 2) {
2400 
2401 		mixernumber = uaudio20_mixer_feature_name(&iot[id], &mix);
2402 
2403 		switch (ctl) {
2404 		case (3 << 0):
2405 			mix.type = MIX_ON_OFF;
2406 			mix.ctl = SOUND_MIXER_NRDEVICES;
2407 			what = MUTE_CONTROL;
2408 			break;
2409 		case (3 << 2):
2410 			mix.type = MIX_SIGNED_16;
2411 			mix.ctl = mixernumber;
2412 			what = VOLUME_CONTROL;
2413 			break;
2414 		case (3 << 4):
2415 			mix.type = MIX_SIGNED_8;
2416 			mix.ctl = SOUND_MIXER_BASS;
2417 			what = BASS_CONTROL;
2418 			break;
2419 		case (3 << 6):
2420 			mix.type = MIX_SIGNED_8;
2421 			mix.ctl = SOUND_MIXER_NRDEVICES;	/* XXXXX */
2422 			what = MID_CONTROL;
2423 			break;
2424 		case (3 << 8):
2425 			mix.type = MIX_SIGNED_8;
2426 			mix.ctl = SOUND_MIXER_TREBLE;
2427 			what = TREBLE_CONTROL;
2428 			break;
2429 		case (3 << 12):
2430 			mix.type = MIX_ON_OFF;
2431 			mix.ctl = SOUND_MIXER_NRDEVICES;	/* XXXXX */
2432 			what = AGC_CONTROL;
2433 			break;
2434 		case (3 << 14):
2435 			mix.type = MIX_UNSIGNED_16;
2436 			mix.ctl = SOUND_MIXER_NRDEVICES;	/* XXXXX */
2437 			what = DELAY_CONTROL;
2438 			break;
2439 		case (3 << 16):
2440 			mix.type = MIX_ON_OFF;
2441 			mix.ctl = SOUND_MIXER_NRDEVICES;	/* XXXXX */
2442 			what = BASS_BOOST_CONTROL;
2443 			break;
2444 		case (3 << 18):
2445 			mix.type = MIX_ON_OFF;
2446 			mix.ctl = SOUND_MIXER_LOUD;	/* Is this correct ? */
2447 			what = LOUDNESS_CONTROL;
2448 			break;
2449 		case (3 << 20):
2450 			mix.type = MIX_SIGNED_16;
2451 			mix.ctl = mixernumber;
2452 			what = INPUT_GAIN_CONTROL;
2453 			break;
2454 		case (3 << 22):
2455 			mix.type = MIX_SIGNED_16;
2456 			mix.ctl = mixernumber;
2457 			what = INPUT_GAIN_PAD_CONTROL;
2458 			break;
2459 		default:
2460 			continue;
2461 		}
2462 
2463 		if ((mmask & ctl) == ctl) {
2464 			mix.nchan = 1;
2465 			mix.wValue[0] = MAKE_WORD(what, 0);
2466 		} else if ((cmask & ctl) == ctl) {
2467 			mix.nchan = nchan - 1;
2468 			for (i = 1; i < nchan; i++) {
2469 				if ((UGETDW(d->bmaControls[i]) & ctl) == ctl)
2470 					mix.wValue[i - 1] = MAKE_WORD(what, i);
2471 				else
2472 					mix.wValue[i - 1] = -1;
2473 			}
2474 		} else {
2475 			continue;
2476 		}
2477 
2478 		if (mix.type != MIX_UNKNOWN)
2479 			uaudio_mixer_add_ctl(sc, &mix);
2480 	}
2481 }
2482 
2483 static void
2484 uaudio_mixer_add_processing_updown(struct uaudio_softc *sc,
2485     const struct uaudio_terminal_node *iot, int id)
2486 {
2487 	const struct usb_audio_processing_unit_0 *d0 = iot[id].u.pu_v1;
2488 	const struct usb_audio_processing_unit_1 *d1 =
2489 	(const void *)(d0->baSourceId + d0->bNrInPins);
2490 	const struct usb_audio_processing_unit_updown *ud =
2491 	(const void *)(d1->bmControls + d1->bControlSize);
2492 	struct uaudio_mixer_node mix;
2493 	uint8_t i;
2494 
2495 	if (uaudio_mixer_verify_desc(d0, sizeof(*ud)) == NULL) {
2496 		return;
2497 	}
2498 	if (uaudio_mixer_verify_desc(d0, sizeof(*ud) + (2 * ud->bNrModes))
2499 	    == NULL) {
2500 		return;
2501 	}
2502 	DPRINTFN(3, "bUnitId=%d bNrModes=%d\n",
2503 	    d0->bUnitId, ud->bNrModes);
2504 
2505 	if (!(d1->bmControls[0] & UA_PROC_MASK(UD_MODE_SELECT_CONTROL))) {
2506 		DPRINTF("no mode select\n");
2507 		return;
2508 	}
2509 	memset(&mix, 0, sizeof(mix));
2510 
2511 	mix.wIndex = MAKE_WORD(d0->bUnitId, sc->sc_mixer_iface_no);
2512 	mix.nchan = 1;
2513 	mix.wValue[0] = MAKE_WORD(UD_MODE_SELECT_CONTROL, 0);
2514 	uaudio_mixer_determine_class(&iot[id], &mix);
2515 	mix.type = MIX_ON_OFF;		/* XXX */
2516 
2517 	for (i = 0; i < ud->bNrModes; i++) {
2518 		DPRINTFN(3, "i=%d bm=0x%x\n", i, UGETW(ud->waModes[i]));
2519 		/* XXX */
2520 	}
2521 
2522 	uaudio_mixer_add_ctl(sc, &mix);
2523 }
2524 
2525 static void
2526 uaudio_mixer_add_processing(struct uaudio_softc *sc,
2527     const struct uaudio_terminal_node *iot, int id)
2528 {
2529 	const struct usb_audio_processing_unit_0 *d0 = iot[id].u.pu_v1;
2530 	const struct usb_audio_processing_unit_1 *d1 =
2531 	(const void *)(d0->baSourceId + d0->bNrInPins);
2532 	struct uaudio_mixer_node mix;
2533 	uint16_t ptype;
2534 
2535 	memset(&mix, 0, sizeof(mix));
2536 
2537 	ptype = UGETW(d0->wProcessType);
2538 
2539 	DPRINTFN(3, "wProcessType=%d bUnitId=%d "
2540 	    "bNrInPins=%d\n", ptype, d0->bUnitId, d0->bNrInPins);
2541 
2542 	if (d1->bControlSize == 0) {
2543 		return;
2544 	}
2545 	if (d1->bmControls[0] & UA_PROC_ENABLE_MASK) {
2546 		mix.wIndex = MAKE_WORD(d0->bUnitId, sc->sc_mixer_iface_no);
2547 		mix.nchan = 1;
2548 		mix.wValue[0] = MAKE_WORD(XX_ENABLE_CONTROL, 0);
2549 		uaudio_mixer_determine_class(&iot[id], &mix);
2550 		mix.type = MIX_ON_OFF;
2551 		uaudio_mixer_add_ctl(sc, &mix);
2552 	}
2553 	switch (ptype) {
2554 	case UPDOWNMIX_PROCESS:
2555 		uaudio_mixer_add_processing_updown(sc, iot, id);
2556 		break;
2557 
2558 	case DOLBY_PROLOGIC_PROCESS:
2559 	case P3D_STEREO_EXTENDER_PROCESS:
2560 	case REVERBATION_PROCESS:
2561 	case CHORUS_PROCESS:
2562 	case DYN_RANGE_COMP_PROCESS:
2563 	default:
2564 		DPRINTF("unit %d, type=%d is not implemented\n",
2565 		    d0->bUnitId, ptype);
2566 		break;
2567 	}
2568 }
2569 
2570 static void
2571 uaudio_mixer_add_extension(struct uaudio_softc *sc,
2572     const struct uaudio_terminal_node *iot, int id)
2573 {
2574 	const struct usb_audio_extension_unit_0 *d0 = iot[id].u.eu_v1;
2575 	const struct usb_audio_extension_unit_1 *d1 =
2576 	(const void *)(d0->baSourceId + d0->bNrInPins);
2577 	struct uaudio_mixer_node mix;
2578 
2579 	DPRINTFN(3, "bUnitId=%d bNrInPins=%d\n",
2580 	    d0->bUnitId, d0->bNrInPins);
2581 
2582 	if (sc->sc_uq_au_no_xu) {
2583 		return;
2584 	}
2585 	if (d1->bControlSize == 0) {
2586 		return;
2587 	}
2588 	if (d1->bmControls[0] & UA_EXT_ENABLE_MASK) {
2589 
2590 		memset(&mix, 0, sizeof(mix));
2591 
2592 		mix.wIndex = MAKE_WORD(d0->bUnitId, sc->sc_mixer_iface_no);
2593 		mix.nchan = 1;
2594 		mix.wValue[0] = MAKE_WORD(UA_EXT_ENABLE, 0);
2595 		uaudio_mixer_determine_class(&iot[id], &mix);
2596 		mix.type = MIX_ON_OFF;
2597 
2598 		uaudio_mixer_add_ctl(sc, &mix);
2599 	}
2600 }
2601 
2602 static const void *
2603 uaudio_mixer_verify_desc(const void *arg, uint32_t len)
2604 {
2605 	const struct usb_audio_mixer_unit_1 *d1;
2606 	const struct usb_audio_extension_unit_1 *e1;
2607 	const struct usb_audio_processing_unit_1 *u1;
2608 
2609 	union {
2610 		const struct usb_descriptor *desc;
2611 		const struct usb_audio_input_terminal *it;
2612 		const struct usb_audio_output_terminal *ot;
2613 		const struct usb_audio_mixer_unit_0 *mu;
2614 		const struct usb_audio_selector_unit *su;
2615 		const struct usb_audio_feature_unit *fu;
2616 		const struct usb_audio_processing_unit_0 *pu;
2617 		const struct usb_audio_extension_unit_0 *eu;
2618 	}     u;
2619 
2620 	u.desc = arg;
2621 
2622 	if (u.desc == NULL) {
2623 		goto error;
2624 	}
2625 	if (u.desc->bDescriptorType != UDESC_CS_INTERFACE) {
2626 		goto error;
2627 	}
2628 	switch (u.desc->bDescriptorSubtype) {
2629 	case UDESCSUB_AC_INPUT:
2630 		len += sizeof(*u.it);
2631 		break;
2632 
2633 	case UDESCSUB_AC_OUTPUT:
2634 		len += sizeof(*u.ot);
2635 		break;
2636 
2637 	case UDESCSUB_AC_MIXER:
2638 		len += sizeof(*u.mu);
2639 
2640 		if (u.desc->bLength < len) {
2641 			goto error;
2642 		}
2643 		len += u.mu->bNrInPins;
2644 
2645 		if (u.desc->bLength < len) {
2646 			goto error;
2647 		}
2648 		d1 = (const void *)(u.mu->baSourceId + u.mu->bNrInPins);
2649 
2650 		len += sizeof(*d1);
2651 		break;
2652 
2653 	case UDESCSUB_AC_SELECTOR:
2654 		len += sizeof(*u.su);
2655 
2656 		if (u.desc->bLength < len) {
2657 			goto error;
2658 		}
2659 		len += u.su->bNrInPins;
2660 		break;
2661 
2662 	case UDESCSUB_AC_FEATURE:
2663 		len += (sizeof(*u.fu) + 1);
2664 		break;
2665 
2666 	case UDESCSUB_AC_PROCESSING:
2667 		len += sizeof(*u.pu);
2668 
2669 		if (u.desc->bLength < len) {
2670 			goto error;
2671 		}
2672 		len += u.pu->bNrInPins;
2673 
2674 		if (u.desc->bLength < len) {
2675 			goto error;
2676 		}
2677 		u1 = (const void *)(u.pu->baSourceId + u.pu->bNrInPins);
2678 
2679 		len += sizeof(*u1);
2680 
2681 		if (u.desc->bLength < len) {
2682 			goto error;
2683 		}
2684 		len += u1->bControlSize;
2685 
2686 		break;
2687 
2688 	case UDESCSUB_AC_EXTENSION:
2689 		len += sizeof(*u.eu);
2690 
2691 		if (u.desc->bLength < len) {
2692 			goto error;
2693 		}
2694 		len += u.eu->bNrInPins;
2695 
2696 		if (u.desc->bLength < len) {
2697 			goto error;
2698 		}
2699 		e1 = (const void *)(u.eu->baSourceId + u.eu->bNrInPins);
2700 
2701 		len += sizeof(*e1);
2702 
2703 		if (u.desc->bLength < len) {
2704 			goto error;
2705 		}
2706 		len += e1->bControlSize;
2707 		break;
2708 
2709 	default:
2710 		goto error;
2711 	}
2712 
2713 	if (u.desc->bLength < len) {
2714 		goto error;
2715 	}
2716 	return (u.desc);
2717 
2718 error:
2719 	if (u.desc) {
2720 		DPRINTF("invalid descriptor, type=%d, "
2721 		    "sub_type=%d, len=%d of %d bytes\n",
2722 		    u.desc->bDescriptorType,
2723 		    u.desc->bDescriptorSubtype,
2724 		    u.desc->bLength, len);
2725 	}
2726 	return (NULL);
2727 }
2728 
2729 static const void *
2730 uaudio20_mixer_verify_desc(const void *arg, uint32_t len)
2731 {
2732 	const struct usb_audio20_mixer_unit_1 *d1;
2733 	const struct usb_audio20_extension_unit_1 *e1;
2734 	const struct usb_audio20_processing_unit_1 *u1;
2735 	const struct usb_audio20_clock_selector_unit_1 *c1;
2736 
2737 	union {
2738 		const struct usb_descriptor *desc;
2739 		const struct usb_audio20_clock_source_unit *csrc;
2740 		const struct usb_audio20_clock_selector_unit_0 *csel;
2741 		const struct usb_audio20_clock_multiplier_unit *cmul;
2742 		const struct usb_audio20_input_terminal *it;
2743 		const struct usb_audio20_output_terminal *ot;
2744 		const struct usb_audio20_mixer_unit_0 *mu;
2745 		const struct usb_audio20_selector_unit *su;
2746 		const struct usb_audio20_feature_unit *fu;
2747 		const struct usb_audio20_sample_rate_unit *ru;
2748 		const struct usb_audio20_processing_unit_0 *pu;
2749 		const struct usb_audio20_extension_unit_0 *eu;
2750 		const struct usb_audio20_effect_unit *ef;
2751 	}     u;
2752 
2753 	u.desc = arg;
2754 
2755 	if (u.desc == NULL)
2756 		goto error;
2757 
2758 	if (u.desc->bDescriptorType != UDESC_CS_INTERFACE)
2759 		goto error;
2760 
2761 	switch (u.desc->bDescriptorSubtype) {
2762 	case UDESCSUB_AC_INPUT:
2763 		len += sizeof(*u.it);
2764 		break;
2765 
2766 	case UDESCSUB_AC_OUTPUT:
2767 		len += sizeof(*u.ot);
2768 		break;
2769 
2770 	case UDESCSUB_AC_MIXER:
2771 		len += sizeof(*u.mu);
2772 
2773 		if (u.desc->bLength < len)
2774 			goto error;
2775 		len += u.mu->bNrInPins;
2776 
2777 		if (u.desc->bLength < len)
2778 			goto error;
2779 
2780 		d1 = (const void *)(u.mu->baSourceId + u.mu->bNrInPins);
2781 
2782 		len += sizeof(*d1) + d1->bNrChannels;
2783 		break;
2784 
2785 	case UDESCSUB_AC_SELECTOR:
2786 		len += sizeof(*u.su);
2787 
2788 		if (u.desc->bLength < len)
2789 			goto error;
2790 
2791 		len += u.su->bNrInPins;
2792 		break;
2793 
2794 	case UDESCSUB_AC_FEATURE:
2795 		len += sizeof(*u.fu) + 1;
2796 
2797 		if (u.desc->bLength < len)
2798 			goto error;
2799 		break;
2800 
2801 	case UDESCSUB_AC_EFFECT:
2802 		len += sizeof(*u.ef) + 4;
2803 		break;
2804 
2805 	case UDESCSUB_AC_PROCESSING_V2:
2806 		len += sizeof(*u.pu);
2807 
2808 		if (u.desc->bLength < len)
2809 			goto error;
2810 
2811 		len += u.pu->bNrInPins;
2812 
2813 		if (u.desc->bLength < len)
2814 			goto error;
2815 
2816 		u1 = (const void *)(u.pu->baSourceId + u.pu->bNrInPins);
2817 
2818 		len += sizeof(*u1);
2819 		break;
2820 
2821 	case UDESCSUB_AC_EXTENSION_V2:
2822 		len += sizeof(*u.eu);
2823 
2824 		if (u.desc->bLength < len)
2825 			goto error;
2826 
2827 		len += u.eu->bNrInPins;
2828 
2829 		if (u.desc->bLength < len)
2830 			goto error;
2831 
2832 		e1 = (const void *)(u.eu->baSourceId + u.eu->bNrInPins);
2833 
2834 		len += sizeof(*e1);
2835 		break;
2836 
2837 	case UDESCSUB_AC_CLOCK_SRC:
2838 		len += sizeof(*u.csrc);
2839 		break;
2840 
2841 	case UDESCSUB_AC_CLOCK_SEL:
2842 		len += sizeof(*u.csel);
2843 
2844 		if (u.desc->bLength < len)
2845 			goto error;
2846 
2847 		len += u.csel->bNrInPins;
2848 
2849 		if (u.desc->bLength < len)
2850 			goto error;
2851 
2852 		c1 = (const void *)(u.csel->baCSourceId + u.csel->bNrInPins);
2853 
2854 		len += sizeof(*c1);
2855 		break;
2856 
2857 	case UDESCSUB_AC_CLOCK_MUL:
2858 		len += sizeof(*u.cmul);
2859 		break;
2860 
2861 	case UDESCSUB_AC_SAMPLE_RT:
2862 		len += sizeof(*u.ru);
2863 		break;
2864 
2865 	default:
2866 		goto error;
2867 	}
2868 
2869 	if (u.desc->bLength < len)
2870 		goto error;
2871 
2872 	return (u.desc);
2873 
2874 error:
2875 	if (u.desc) {
2876 		DPRINTF("invalid descriptor, type=%d, "
2877 		    "sub_type=%d, len=%d of %d bytes\n",
2878 		    u.desc->bDescriptorType,
2879 		    u.desc->bDescriptorSubtype,
2880 		    u.desc->bLength, len);
2881 	}
2882 	return (NULL);
2883 }
2884 
2885 static struct usb_audio_cluster
2886 uaudio_mixer_get_cluster(uint8_t id, const struct uaudio_terminal_node *iot)
2887 {
2888 	struct usb_audio_cluster r;
2889 	const struct usb_descriptor *dp;
2890 	uint8_t i;
2891 
2892 	for (i = 0; i < UAUDIO_RECURSE_LIMIT; i++) {	/* avoid infinite loops */
2893 		dp = iot[id].u.desc;
2894 		if (dp == NULL) {
2895 			goto error;
2896 		}
2897 		switch (dp->bDescriptorSubtype) {
2898 		case UDESCSUB_AC_INPUT:
2899 			r.bNrChannels = iot[id].u.it_v1->bNrChannels;
2900 			r.wChannelConfig[0] = iot[id].u.it_v1->wChannelConfig[0];
2901 			r.wChannelConfig[1] = iot[id].u.it_v1->wChannelConfig[1];
2902 			r.iChannelNames = iot[id].u.it_v1->iChannelNames;
2903 			goto done;
2904 
2905 		case UDESCSUB_AC_OUTPUT:
2906 			id = iot[id].u.ot_v1->bSourceId;
2907 			break;
2908 
2909 		case UDESCSUB_AC_MIXER:
2910 			r = *(const struct usb_audio_cluster *)
2911 			    &iot[id].u.mu_v1->baSourceId[
2912 			    iot[id].u.mu_v1->bNrInPins];
2913 			goto done;
2914 
2915 		case UDESCSUB_AC_SELECTOR:
2916 			if (iot[id].u.su_v1->bNrInPins > 0) {
2917 				/* XXX This is not really right */
2918 				id = iot[id].u.su_v1->baSourceId[0];
2919 			}
2920 			break;
2921 
2922 		case UDESCSUB_AC_FEATURE:
2923 			id = iot[id].u.fu_v1->bSourceId;
2924 			break;
2925 
2926 		case UDESCSUB_AC_PROCESSING:
2927 			r = *((const struct usb_audio_cluster *)
2928 			    &iot[id].u.pu_v1->baSourceId[
2929 			    iot[id].u.pu_v1->bNrInPins]);
2930 			goto done;
2931 
2932 		case UDESCSUB_AC_EXTENSION:
2933 			r = *((const struct usb_audio_cluster *)
2934 			    &iot[id].u.eu_v1->baSourceId[
2935 			    iot[id].u.eu_v1->bNrInPins]);
2936 			goto done;
2937 
2938 		default:
2939 			goto error;
2940 		}
2941 	}
2942 error:
2943 	DPRINTF("bad data\n");
2944 	memset(&r, 0, sizeof(r));
2945 done:
2946 	return (r);
2947 }
2948 
2949 static struct usb_audio20_cluster
2950 uaudio20_mixer_get_cluster(uint8_t id, const struct uaudio_terminal_node *iot)
2951 {
2952 	struct usb_audio20_cluster r;
2953 	const struct usb_descriptor *dp;
2954 	uint8_t i;
2955 
2956 	for (i = 0; i < UAUDIO_RECURSE_LIMIT; i++) {	/* avoid infinite loops */
2957 		dp = iot[id].u.desc;
2958 		if (dp == NULL)
2959 			goto error;
2960 
2961 		switch (dp->bDescriptorSubtype) {
2962 		case UDESCSUB_AC_INPUT:
2963 			r.bNrChannels = iot[id].u.it_v2->bNrChannels;
2964 			r.bmChannelConfig[0] = iot[id].u.it_v2->bmChannelConfig[0];
2965 			r.bmChannelConfig[1] = iot[id].u.it_v2->bmChannelConfig[1];
2966 			r.bmChannelConfig[2] = iot[id].u.it_v2->bmChannelConfig[2];
2967 			r.bmChannelConfig[3] = iot[id].u.it_v2->bmChannelConfig[3];
2968 			r.iChannelNames = iot[id].u.it_v2->iTerminal;
2969 			goto done;
2970 
2971 		case UDESCSUB_AC_OUTPUT:
2972 			id = iot[id].u.ot_v2->bSourceId;
2973 			break;
2974 
2975 		case UDESCSUB_AC_MIXER:
2976 			r = *(const struct usb_audio20_cluster *)
2977 			    &iot[id].u.mu_v2->baSourceId[
2978 			    iot[id].u.mu_v2->bNrInPins];
2979 			goto done;
2980 
2981 		case UDESCSUB_AC_SELECTOR:
2982 			if (iot[id].u.su_v2->bNrInPins > 0) {
2983 				/* XXX This is not really right */
2984 				id = iot[id].u.su_v2->baSourceId[0];
2985 			}
2986 			break;
2987 
2988 		case UDESCSUB_AC_SAMPLE_RT:
2989 			id = iot[id].u.ru_v2->bSourceId;
2990 			break;
2991 
2992 		case UDESCSUB_AC_EFFECT:
2993 			id = iot[id].u.ef_v2->bSourceId;
2994 			break;
2995 
2996 		case UDESCSUB_AC_FEATURE:
2997 			id = iot[id].u.fu_v2->bSourceId;
2998 			break;
2999 
3000 		case UDESCSUB_AC_PROCESSING_V2:
3001 			r = *((const struct usb_audio20_cluster *)
3002 			    &iot[id].u.pu_v2->baSourceId[
3003 			    iot[id].u.pu_v2->bNrInPins]);
3004 			goto done;
3005 
3006 		case UDESCSUB_AC_EXTENSION_V2:
3007 			r = *((const struct usb_audio20_cluster *)
3008 			    &iot[id].u.eu_v2->baSourceId[
3009 			    iot[id].u.eu_v2->bNrInPins]);
3010 			goto done;
3011 
3012 		default:
3013 			goto error;
3014 		}
3015 	}
3016 error:
3017 	DPRINTF("Bad data!\n");
3018 	memset(&r, 0, sizeof(r));
3019 done:
3020 	return (r);
3021 }
3022 
3023 static uint16_t
3024 uaudio_mixer_determine_class(const struct uaudio_terminal_node *iot,
3025     struct uaudio_mixer_node *mix)
3026 {
3027 	uint16_t terminal_type = 0x0000;
3028 	const struct uaudio_terminal_node *input[2];
3029 	const struct uaudio_terminal_node *output[2];
3030 
3031 	input[0] = uaudio_mixer_get_input(iot, 0);
3032 	input[1] = uaudio_mixer_get_input(iot, 1);
3033 
3034 	output[0] = uaudio_mixer_get_output(iot, 0);
3035 	output[1] = uaudio_mixer_get_output(iot, 1);
3036 
3037 	/*
3038 	 * check if there is only
3039 	 * one output terminal:
3040 	 */
3041 	if (output[0] && (!output[1])) {
3042 		terminal_type =
3043 		    UGETW(output[0]->u.ot_v1->wTerminalType);
3044 	}
3045 	/*
3046 	 * If the only output terminal is USB,
3047 	 * the class is UAC_RECORD.
3048 	 */
3049 	if ((terminal_type & 0xff00) == (UAT_UNDEFINED & 0xff00)) {
3050 
3051 		mix->class = UAC_RECORD;
3052 		if (input[0] && (!input[1])) {
3053 			terminal_type =
3054 			    UGETW(input[0]->u.it_v1->wTerminalType);
3055 		} else {
3056 			terminal_type = 0;
3057 		}
3058 		goto done;
3059 	}
3060 	/*
3061 	 * if the unit is connected to just
3062 	 * one input terminal, the
3063 	 * class is UAC_INPUT:
3064 	 */
3065 	if (input[0] && (!input[1])) {
3066 		mix->class = UAC_INPUT;
3067 		terminal_type =
3068 		    UGETW(input[0]->u.it_v1->wTerminalType);
3069 		goto done;
3070 	}
3071 	/*
3072 	 * Otherwise, the class is UAC_OUTPUT.
3073 	 */
3074 	mix->class = UAC_OUTPUT;
3075 done:
3076 	return (terminal_type);
3077 }
3078 
3079 static uint16_t
3080 uaudio20_mixer_determine_class(const struct uaudio_terminal_node *iot,
3081     struct uaudio_mixer_node *mix)
3082 {
3083 	uint16_t terminal_type = 0x0000;
3084 	const struct uaudio_terminal_node *input[2];
3085 	const struct uaudio_terminal_node *output[2];
3086 
3087 	input[0] = uaudio_mixer_get_input(iot, 0);
3088 	input[1] = uaudio_mixer_get_input(iot, 1);
3089 
3090 	output[0] = uaudio_mixer_get_output(iot, 0);
3091 	output[1] = uaudio_mixer_get_output(iot, 1);
3092 
3093 	/*
3094 	 * check if there is only
3095 	 * one output terminal:
3096 	 */
3097 	if (output[0] && (!output[1]))
3098 		terminal_type = UGETW(output[0]->u.ot_v2->wTerminalType);
3099 	/*
3100 	 * If the only output terminal is USB,
3101 	 * the class is UAC_RECORD.
3102 	 */
3103 	if ((terminal_type & 0xff00) == (UAT_UNDEFINED & 0xff00)) {
3104 
3105 		mix->class = UAC_RECORD;
3106 		if (input[0] && (!input[1])) {
3107 			terminal_type =
3108 			    UGETW(input[0]->u.it_v2->wTerminalType);
3109 		} else {
3110 			terminal_type = 0;
3111 		}
3112 		goto done;
3113 	}
3114 	/*
3115 	 * if the unit is connected to just
3116 	 * one input terminal, the
3117 	 * class is UAC_INPUT:
3118 	 */
3119 	if (input[0] && (!input[1])) {
3120 		mix->class = UAC_INPUT;
3121 		terminal_type =
3122 		    UGETW(input[0]->u.it_v2->wTerminalType);
3123 		goto done;
3124 	}
3125 	/*
3126 	 * Otherwise, the class is UAC_OUTPUT.
3127 	 */
3128 	mix->class = UAC_OUTPUT;
3129 done:
3130 	return (terminal_type);
3131 }
3132 
3133 struct uaudio_tt_to_feature {
3134 	uint16_t terminal_type;
3135 	uint16_t feature;
3136 };
3137 
3138 static const struct uaudio_tt_to_feature uaudio_tt_to_feature[] = {
3139 
3140 	{UAT_STREAM, SOUND_MIXER_PCM},
3141 
3142 	{UATI_MICROPHONE, SOUND_MIXER_MIC},
3143 	{UATI_DESKMICROPHONE, SOUND_MIXER_MIC},
3144 	{UATI_PERSONALMICROPHONE, SOUND_MIXER_MIC},
3145 	{UATI_OMNIMICROPHONE, SOUND_MIXER_MIC},
3146 	{UATI_MICROPHONEARRAY, SOUND_MIXER_MIC},
3147 	{UATI_PROCMICROPHONEARR, SOUND_MIXER_MIC},
3148 
3149 	{UATO_SPEAKER, SOUND_MIXER_SPEAKER},
3150 	{UATO_DESKTOPSPEAKER, SOUND_MIXER_SPEAKER},
3151 	{UATO_ROOMSPEAKER, SOUND_MIXER_SPEAKER},
3152 	{UATO_COMMSPEAKER, SOUND_MIXER_SPEAKER},
3153 
3154 	{UATE_ANALOGCONN, SOUND_MIXER_LINE},
3155 	{UATE_LINECONN, SOUND_MIXER_LINE},
3156 	{UATE_LEGACYCONN, SOUND_MIXER_LINE},
3157 
3158 	{UATE_DIGITALAUIFC, SOUND_MIXER_ALTPCM},
3159 	{UATE_SPDIF, SOUND_MIXER_ALTPCM},
3160 	{UATE_1394DA, SOUND_MIXER_ALTPCM},
3161 	{UATE_1394DV, SOUND_MIXER_ALTPCM},
3162 
3163 	{UATF_CDPLAYER, SOUND_MIXER_CD},
3164 
3165 	{UATF_SYNTHESIZER, SOUND_MIXER_SYNTH},
3166 
3167 	{UATF_VIDEODISCAUDIO, SOUND_MIXER_VIDEO},
3168 	{UATF_DVDAUDIO, SOUND_MIXER_VIDEO},
3169 	{UATF_TVTUNERAUDIO, SOUND_MIXER_VIDEO},
3170 
3171 	/* telephony terminal types */
3172 	{UATT_UNDEFINED, SOUND_MIXER_PHONEIN},	/* SOUND_MIXER_PHONEOUT */
3173 	{UATT_PHONELINE, SOUND_MIXER_PHONEIN},	/* SOUND_MIXER_PHONEOUT */
3174 	{UATT_TELEPHONE, SOUND_MIXER_PHONEIN},	/* SOUND_MIXER_PHONEOUT */
3175 	{UATT_DOWNLINEPHONE, SOUND_MIXER_PHONEIN},	/* SOUND_MIXER_PHONEOUT */
3176 
3177 	{UATF_RADIORECV, SOUND_MIXER_RADIO},
3178 	{UATF_RADIOXMIT, SOUND_MIXER_RADIO},
3179 
3180 	{UAT_UNDEFINED, SOUND_MIXER_VOLUME},
3181 	{UAT_VENDOR, SOUND_MIXER_VOLUME},
3182 	{UATI_UNDEFINED, SOUND_MIXER_VOLUME},
3183 
3184 	/* output terminal types */
3185 	{UATO_UNDEFINED, SOUND_MIXER_VOLUME},
3186 	{UATO_DISPLAYAUDIO, SOUND_MIXER_VOLUME},
3187 	{UATO_SUBWOOFER, SOUND_MIXER_VOLUME},
3188 	{UATO_HEADPHONES, SOUND_MIXER_VOLUME},
3189 
3190 	/* bidir terminal types */
3191 	{UATB_UNDEFINED, SOUND_MIXER_VOLUME},
3192 	{UATB_HANDSET, SOUND_MIXER_VOLUME},
3193 	{UATB_HEADSET, SOUND_MIXER_VOLUME},
3194 	{UATB_SPEAKERPHONE, SOUND_MIXER_VOLUME},
3195 	{UATB_SPEAKERPHONEESUP, SOUND_MIXER_VOLUME},
3196 	{UATB_SPEAKERPHONEECANC, SOUND_MIXER_VOLUME},
3197 
3198 	/* external terminal types */
3199 	{UATE_UNDEFINED, SOUND_MIXER_VOLUME},
3200 
3201 	/* embedded function terminal types */
3202 	{UATF_UNDEFINED, SOUND_MIXER_VOLUME},
3203 	{UATF_CALIBNOISE, SOUND_MIXER_VOLUME},
3204 	{UATF_EQUNOISE, SOUND_MIXER_VOLUME},
3205 	{UATF_DAT, SOUND_MIXER_VOLUME},
3206 	{UATF_DCC, SOUND_MIXER_VOLUME},
3207 	{UATF_MINIDISK, SOUND_MIXER_VOLUME},
3208 	{UATF_ANALOGTAPE, SOUND_MIXER_VOLUME},
3209 	{UATF_PHONOGRAPH, SOUND_MIXER_VOLUME},
3210 	{UATF_VCRAUDIO, SOUND_MIXER_VOLUME},
3211 	{UATF_SATELLITE, SOUND_MIXER_VOLUME},
3212 	{UATF_CABLETUNER, SOUND_MIXER_VOLUME},
3213 	{UATF_DSS, SOUND_MIXER_VOLUME},
3214 	{UATF_MULTITRACK, SOUND_MIXER_VOLUME},
3215 	{0xffff, SOUND_MIXER_VOLUME},
3216 
3217 	/* default */
3218 	{0x0000, SOUND_MIXER_VOLUME},
3219 };
3220 
3221 static uint16_t
3222 uaudio_mixer_feature_name(const struct uaudio_terminal_node *iot,
3223     struct uaudio_mixer_node *mix)
3224 {
3225 	const struct uaudio_tt_to_feature *uat = uaudio_tt_to_feature;
3226 	uint16_t terminal_type = uaudio_mixer_determine_class(iot, mix);
3227 
3228 	if ((mix->class == UAC_RECORD) && (terminal_type == 0)) {
3229 		return (SOUND_MIXER_IMIX);
3230 	}
3231 	while (uat->terminal_type) {
3232 		if (uat->terminal_type == terminal_type) {
3233 			break;
3234 		}
3235 		uat++;
3236 	}
3237 
3238 	DPRINTF("terminal_type=0x%04x -> %d\n",
3239 	    terminal_type, uat->feature);
3240 
3241 	return (uat->feature);
3242 }
3243 
3244 static uint16_t
3245 uaudio20_mixer_feature_name(const struct uaudio_terminal_node *iot,
3246     struct uaudio_mixer_node *mix)
3247 {
3248 	const struct uaudio_tt_to_feature *uat;
3249 	uint16_t terminal_type = uaudio20_mixer_determine_class(iot, mix);
3250 
3251 	if ((mix->class == UAC_RECORD) && (terminal_type == 0))
3252 		return (SOUND_MIXER_IMIX);
3253 
3254 	for (uat = uaudio_tt_to_feature; uat->terminal_type != 0; uat++) {
3255 		if (uat->terminal_type == terminal_type)
3256 			break;
3257 	}
3258 
3259 	DPRINTF("terminal_type=0x%04x -> %d\n",
3260 	    terminal_type, uat->feature);
3261 
3262 	return (uat->feature);
3263 }
3264 
3265 static const struct uaudio_terminal_node *
3266 uaudio_mixer_get_input(const struct uaudio_terminal_node *iot, uint8_t i)
3267 {
3268 	struct uaudio_terminal_node *root = iot->root;
3269 	uint8_t n;
3270 
3271 	n = iot->usr.id_max;
3272 	do {
3273 		if (iot->usr.bit_input[n / 8] & (1 << (n % 8))) {
3274 			if (!i--)
3275 				return (root + n);
3276 		}
3277 	} while (n--);
3278 
3279 	return (NULL);
3280 }
3281 
3282 static const struct uaudio_terminal_node *
3283 uaudio_mixer_get_output(const struct uaudio_terminal_node *iot, uint8_t i)
3284 {
3285 	struct uaudio_terminal_node *root = iot->root;
3286 	uint8_t n;
3287 
3288 	n = iot->usr.id_max;
3289 	do {
3290 		if (iot->usr.bit_output[n / 8] & (1 << (n % 8))) {
3291 			if (!i--)
3292 				return (root + n);
3293 		}
3294 	} while (n--);
3295 
3296 	return (NULL);
3297 }
3298 
3299 static void
3300 uaudio_mixer_find_inputs_sub(struct uaudio_terminal_node *root,
3301     const uint8_t *p_id, uint8_t n_id,
3302     struct uaudio_search_result *info)
3303 {
3304 	struct uaudio_terminal_node *iot;
3305 	uint8_t n;
3306 	uint8_t i;
3307 	uint8_t is_last;
3308 
3309 top:
3310 	for (n = 0; n < n_id; n++) {
3311 
3312 		i = p_id[n];
3313 
3314 		if (info->recurse_level == UAUDIO_RECURSE_LIMIT) {
3315 			DPRINTF("avoided going into a circle at id=%d!\n", i);
3316 			return;
3317 		}
3318 
3319 		info->recurse_level++;
3320 
3321 		iot = (root + i);
3322 
3323 		if (iot->u.desc == NULL)
3324 			continue;
3325 
3326 		is_last = ((n + 1) == n_id);
3327 
3328 		switch (iot->u.desc->bDescriptorSubtype) {
3329 		case UDESCSUB_AC_INPUT:
3330 			info->bit_input[i / 8] |= (1 << (i % 8));
3331 			break;
3332 
3333 		case UDESCSUB_AC_FEATURE:
3334 			if (is_last) {
3335 				p_id = &iot->u.fu_v1->bSourceId;
3336 				n_id = 1;
3337 				goto top;
3338 			}
3339 			uaudio_mixer_find_inputs_sub(
3340 			    root, &iot->u.fu_v1->bSourceId, 1, info);
3341 			break;
3342 
3343 		case UDESCSUB_AC_OUTPUT:
3344 			if (is_last) {
3345 				p_id = &iot->u.ot_v1->bSourceId;
3346 				n_id = 1;
3347 				goto top;
3348 			}
3349 			uaudio_mixer_find_inputs_sub(
3350 			    root, &iot->u.ot_v1->bSourceId, 1, info);
3351 			break;
3352 
3353 		case UDESCSUB_AC_MIXER:
3354 			if (is_last) {
3355 				p_id = iot->u.mu_v1->baSourceId;
3356 				n_id = iot->u.mu_v1->bNrInPins;
3357 				goto top;
3358 			}
3359 			uaudio_mixer_find_inputs_sub(
3360 			    root, iot->u.mu_v1->baSourceId,
3361 			    iot->u.mu_v1->bNrInPins, info);
3362 			break;
3363 
3364 		case UDESCSUB_AC_SELECTOR:
3365 			if (is_last) {
3366 				p_id = iot->u.su_v1->baSourceId;
3367 				n_id = iot->u.su_v1->bNrInPins;
3368 				goto top;
3369 			}
3370 			uaudio_mixer_find_inputs_sub(
3371 			    root, iot->u.su_v1->baSourceId,
3372 			    iot->u.su_v1->bNrInPins, info);
3373 			break;
3374 
3375 		case UDESCSUB_AC_PROCESSING:
3376 			if (is_last) {
3377 				p_id = iot->u.pu_v1->baSourceId;
3378 				n_id = iot->u.pu_v1->bNrInPins;
3379 				goto top;
3380 			}
3381 			uaudio_mixer_find_inputs_sub(
3382 			    root, iot->u.pu_v1->baSourceId,
3383 			    iot->u.pu_v1->bNrInPins, info);
3384 			break;
3385 
3386 		case UDESCSUB_AC_EXTENSION:
3387 			if (is_last) {
3388 				p_id = iot->u.eu_v1->baSourceId;
3389 				n_id = iot->u.eu_v1->bNrInPins;
3390 				goto top;
3391 			}
3392 			uaudio_mixer_find_inputs_sub(
3393 			    root, iot->u.eu_v1->baSourceId,
3394 			    iot->u.eu_v1->bNrInPins, info);
3395 			break;
3396 
3397 		default:
3398 			break;
3399 		}
3400 	}
3401 }
3402 
3403 static void
3404 uaudio20_mixer_find_inputs_sub(struct uaudio_terminal_node *root,
3405     const uint8_t *p_id, uint8_t n_id,
3406     struct uaudio_search_result *info)
3407 {
3408 	struct uaudio_terminal_node *iot;
3409 	uint8_t n;
3410 	uint8_t i;
3411 	uint8_t is_last;
3412 
3413 top:
3414 	for (n = 0; n < n_id; n++) {
3415 
3416 		i = p_id[n];
3417 
3418 		if (info->recurse_level == UAUDIO_RECURSE_LIMIT) {
3419 			DPRINTF("avoided going into a circle at id=%d!\n", i);
3420 			return;
3421 		}
3422 
3423 		info->recurse_level++;
3424 
3425 		iot = (root + i);
3426 
3427 		if (iot->u.desc == NULL)
3428 			continue;
3429 
3430 		is_last = ((n + 1) == n_id);
3431 
3432 		switch (iot->u.desc->bDescriptorSubtype) {
3433 		case UDESCSUB_AC_INPUT:
3434 			info->bit_input[i / 8] |= (1 << (i % 8));
3435 			break;
3436 
3437 		case UDESCSUB_AC_OUTPUT:
3438 			if (is_last) {
3439 				p_id = &iot->u.ot_v2->bSourceId;
3440 				n_id = 1;
3441 				goto top;
3442 			}
3443 			uaudio20_mixer_find_inputs_sub(
3444 			    root, &iot->u.ot_v2->bSourceId, 1, info);
3445 			break;
3446 
3447 		case UDESCSUB_AC_MIXER:
3448 			if (is_last) {
3449 				p_id = iot->u.mu_v2->baSourceId;
3450 				n_id = iot->u.mu_v2->bNrInPins;
3451 				goto top;
3452 			}
3453 			uaudio20_mixer_find_inputs_sub(
3454 			    root, iot->u.mu_v2->baSourceId,
3455 			    iot->u.mu_v2->bNrInPins, info);
3456 			break;
3457 
3458 		case UDESCSUB_AC_SELECTOR:
3459 			if (is_last) {
3460 				p_id = iot->u.su_v2->baSourceId;
3461 				n_id = iot->u.su_v2->bNrInPins;
3462 				goto top;
3463 			}
3464 			uaudio20_mixer_find_inputs_sub(
3465 			    root, iot->u.su_v2->baSourceId,
3466 			    iot->u.su_v2->bNrInPins, info);
3467 			break;
3468 
3469 		case UDESCSUB_AC_SAMPLE_RT:
3470 			if (is_last) {
3471 				p_id = &iot->u.ru_v2->bSourceId;
3472 				n_id = 1;
3473 				goto top;
3474 			}
3475 			uaudio20_mixer_find_inputs_sub(
3476 			    root, &iot->u.ru_v2->bSourceId,
3477 			    1, info);
3478 			break;
3479 
3480 		case UDESCSUB_AC_EFFECT:
3481 			if (is_last) {
3482 				p_id = &iot->u.ef_v2->bSourceId;
3483 				n_id = 1;
3484 				goto top;
3485 			}
3486 			uaudio20_mixer_find_inputs_sub(
3487 			    root, &iot->u.ef_v2->bSourceId,
3488 			    1, info);
3489 			break;
3490 
3491 		case UDESCSUB_AC_FEATURE:
3492 			if (is_last) {
3493 				p_id = &iot->u.fu_v2->bSourceId;
3494 				n_id = 1;
3495 				goto top;
3496 			}
3497 			uaudio20_mixer_find_inputs_sub(
3498 			    root, &iot->u.fu_v2->bSourceId, 1, info);
3499 			break;
3500 
3501 		case UDESCSUB_AC_PROCESSING_V2:
3502 			if (is_last) {
3503 				p_id = iot->u.pu_v2->baSourceId;
3504 				n_id = iot->u.pu_v2->bNrInPins;
3505 				goto top;
3506 			}
3507 			uaudio20_mixer_find_inputs_sub(
3508 			    root, iot->u.pu_v2->baSourceId,
3509 			    iot->u.pu_v2->bNrInPins, info);
3510 			break;
3511 
3512 		case UDESCSUB_AC_EXTENSION_V2:
3513 			if (is_last) {
3514 				p_id = iot->u.eu_v2->baSourceId;
3515 				n_id = iot->u.eu_v2->bNrInPins;
3516 				goto top;
3517 			}
3518 			uaudio20_mixer_find_inputs_sub(
3519 			    root, iot->u.eu_v2->baSourceId,
3520 			    iot->u.eu_v2->bNrInPins, info);
3521 			break;
3522 		default:
3523 			break;
3524 		}
3525 	}
3526 }
3527 
3528 static void
3529 uaudio20_mixer_find_clocks_sub(struct uaudio_terminal_node *root,
3530     const uint8_t *p_id, uint8_t n_id,
3531     struct uaudio_search_result *info)
3532 {
3533 	struct uaudio_terminal_node *iot;
3534 	uint8_t n;
3535 	uint8_t i;
3536 	uint8_t is_last;
3537 	uint8_t id;
3538 
3539 top:
3540 	for (n = 0; n < n_id; n++) {
3541 
3542 		i = p_id[n];
3543 
3544 		if (info->recurse_level == UAUDIO_RECURSE_LIMIT) {
3545 			DPRINTF("avoided going into a circle at id=%d!\n", i);
3546 			return;
3547 		}
3548 
3549 		info->recurse_level++;
3550 
3551 		iot = (root + i);
3552 
3553 		if (iot->u.desc == NULL)
3554 			continue;
3555 
3556 		is_last = ((n + 1) == n_id);
3557 
3558 		switch (iot->u.desc->bDescriptorSubtype) {
3559 		case UDESCSUB_AC_INPUT:
3560 			info->is_input = 1;
3561 			if (is_last) {
3562 				p_id = &iot->u.it_v2->bCSourceId;
3563 				n_id = 1;
3564 				goto top;
3565 			}
3566 			uaudio20_mixer_find_clocks_sub(root,
3567 			    &iot->u.it_v2->bCSourceId, 1, info);
3568 			break;
3569 
3570 		case UDESCSUB_AC_OUTPUT:
3571 			info->is_input = 0;
3572 			if (is_last) {
3573 				p_id = &iot->u.ot_v2->bCSourceId;
3574 				n_id = 1;
3575 				goto top;
3576 			}
3577 			uaudio20_mixer_find_clocks_sub(root,
3578 			    &iot->u.ot_v2->bCSourceId, 1, info);
3579 			break;
3580 
3581 		case UDESCSUB_AC_CLOCK_SEL:
3582 			if (is_last) {
3583 				p_id = iot->u.csel_v2->baCSourceId;
3584 				n_id = iot->u.csel_v2->bNrInPins;
3585 				goto top;
3586 			}
3587 			uaudio20_mixer_find_clocks_sub(root,
3588 			    iot->u.csel_v2->baCSourceId,
3589 			    iot->u.csel_v2->bNrInPins, info);
3590 			break;
3591 
3592 		case UDESCSUB_AC_CLOCK_MUL:
3593 			if (is_last) {
3594 				p_id = &iot->u.cmul_v2->bCSourceId;
3595 				n_id = 1;
3596 				goto top;
3597 			}
3598 			uaudio20_mixer_find_clocks_sub(root,
3599 			    &iot->u.cmul_v2->bCSourceId,
3600 			    1, info);
3601 			break;
3602 
3603 		case UDESCSUB_AC_CLOCK_SRC:
3604 
3605 			id = iot->u.csrc_v2->bClockId;
3606 
3607 			switch (info->is_input) {
3608 			case 0:
3609 				info->bit_output[id / 8] |= (1 << (id % 8));
3610 				break;
3611 			case 1:
3612 				info->bit_input[id / 8] |= (1 << (id % 8));
3613 				break;
3614 			default:
3615 				break;
3616 			}
3617 			break;
3618 
3619 		default:
3620 			break;
3621 		}
3622 	}
3623 }
3624 
3625 static void
3626 uaudio_mixer_find_outputs_sub(struct uaudio_terminal_node *root, uint8_t id,
3627     uint8_t n_id, struct uaudio_search_result *info)
3628 {
3629 	struct uaudio_terminal_node *iot = (root + id);
3630 	uint8_t j;
3631 
3632 	j = n_id;
3633 	do {
3634 		if ((j != id) && ((root + j)->u.desc) &&
3635 		    ((root + j)->u.desc->bDescriptorSubtype == UDESCSUB_AC_OUTPUT)) {
3636 
3637 			/*
3638 			 * "j" (output) <--- virtual wire <--- "id" (input)
3639 			 *
3640 			 * if "j" has "id" on the input, then "id" have "j" on
3641 			 * the output, because they are connected:
3642 			 */
3643 			if ((root + j)->usr.bit_input[id / 8] & (1 << (id % 8))) {
3644 				iot->usr.bit_output[j / 8] |= (1 << (j % 8));
3645 			}
3646 		}
3647 	} while (j--);
3648 }
3649 
3650 static void
3651 uaudio_mixer_fill_info(struct uaudio_softc *sc,
3652     struct usb_device *udev, void *desc)
3653 {
3654 	const struct usb_audio_control_descriptor *acdp;
3655 	struct usb_config_descriptor *cd = usbd_get_config_descriptor(udev);
3656 	const struct usb_descriptor *dp;
3657 	const struct usb_audio_unit *au;
3658 	struct uaudio_terminal_node *iot = NULL;
3659 	uint16_t wTotalLen;
3660 	uint8_t ID_max = 0;		/* inclusive */
3661 	uint8_t i;
3662 
3663 	desc = usb_desc_foreach(cd, desc);
3664 
3665 	if (desc == NULL) {
3666 		DPRINTF("no Audio Control header\n");
3667 		goto done;
3668 	}
3669 	acdp = desc;
3670 
3671 	if ((acdp->bLength < sizeof(*acdp)) ||
3672 	    (acdp->bDescriptorType != UDESC_CS_INTERFACE) ||
3673 	    (acdp->bDescriptorSubtype != UDESCSUB_AC_HEADER)) {
3674 		DPRINTF("invalid Audio Control header\n");
3675 		goto done;
3676 	}
3677 	/* "wTotalLen" is allowed to be corrupt */
3678 	wTotalLen = UGETW(acdp->wTotalLength) - acdp->bLength;
3679 
3680 	/* get USB audio revision */
3681 	sc->sc_audio_rev = UGETW(acdp->bcdADC);
3682 
3683 	DPRINTFN(3, "found AC header, vers=%03x, len=%d\n",
3684 	    sc->sc_audio_rev, wTotalLen);
3685 
3686 	iot = malloc(sizeof(struct uaudio_terminal_node) * 256, M_TEMP,
3687 	    M_WAITOK | M_ZERO);
3688 
3689 	if (iot == NULL) {
3690 		DPRINTF("no memory!\n");
3691 		goto done;
3692 	}
3693 	while ((desc = usb_desc_foreach(cd, desc))) {
3694 
3695 		dp = desc;
3696 
3697 		if (dp->bLength > wTotalLen) {
3698 			break;
3699 		} else {
3700 			wTotalLen -= dp->bLength;
3701 		}
3702 
3703 		if (sc->sc_audio_rev >= UAUDIO_VERSION_30)
3704 			au = NULL;
3705 		else if (sc->sc_audio_rev >= UAUDIO_VERSION_20)
3706 			au = uaudio20_mixer_verify_desc(dp, 0);
3707 		else
3708 			au = uaudio_mixer_verify_desc(dp, 0);
3709 
3710 		if (au) {
3711 			iot[au->bUnitId].u.desc = (const void *)au;
3712 			if (au->bUnitId > ID_max)
3713 				ID_max = au->bUnitId;
3714 		}
3715 	}
3716 
3717 	DPRINTF("Maximum ID=%d\n", ID_max);
3718 
3719 	/*
3720 	 * determine sourcing inputs for
3721 	 * all nodes in the tree:
3722 	 */
3723 	i = ID_max;
3724 	do {
3725 		if (sc->sc_audio_rev >= UAUDIO_VERSION_30) {
3726 			/* FALLTHROUGH */
3727 		} else if (sc->sc_audio_rev >= UAUDIO_VERSION_20) {
3728 			uaudio20_mixer_find_inputs_sub(iot,
3729 			    &i, 1, &((iot + i)->usr));
3730 
3731 			sc->sc_mixer_clocks.is_input = 255;
3732 			sc->sc_mixer_clocks.recurse_level = 0;
3733 
3734 			uaudio20_mixer_find_clocks_sub(iot,
3735 			    &i, 1, &sc->sc_mixer_clocks);
3736 		} else {
3737 			uaudio_mixer_find_inputs_sub(iot,
3738 			    &i, 1, &((iot + i)->usr));
3739 		}
3740 	} while (i--);
3741 
3742 	/*
3743 	 * determine outputs for
3744 	 * all nodes in the tree:
3745 	 */
3746 	i = ID_max;
3747 	do {
3748 		uaudio_mixer_find_outputs_sub(iot,
3749 		    i, ID_max, &((iot + i)->usr));
3750 	} while (i--);
3751 
3752 	/* set "id_max" and "root" */
3753 
3754 	i = ID_max;
3755 	do {
3756 		(iot + i)->usr.id_max = ID_max;
3757 		(iot + i)->root = iot;
3758 	} while (i--);
3759 
3760 	/*
3761 	 * Scan the config to create a linked list of "mixer" nodes:
3762 	 */
3763 
3764 	i = ID_max;
3765 	do {
3766 		dp = iot[i].u.desc;
3767 
3768 		if (dp == NULL)
3769 			continue;
3770 
3771 		DPRINTFN(11, "id=%d subtype=%d\n",
3772 		    i, dp->bDescriptorSubtype);
3773 
3774 		if (sc->sc_audio_rev >= UAUDIO_VERSION_30) {
3775 			continue;
3776 		} else if (sc->sc_audio_rev >= UAUDIO_VERSION_20) {
3777 
3778 			switch (dp->bDescriptorSubtype) {
3779 			case UDESCSUB_AC_HEADER:
3780 				DPRINTF("unexpected AC header\n");
3781 				break;
3782 
3783 			case UDESCSUB_AC_INPUT:
3784 			case UDESCSUB_AC_OUTPUT:
3785 			case UDESCSUB_AC_PROCESSING_V2:
3786 			case UDESCSUB_AC_EXTENSION_V2:
3787 			case UDESCSUB_AC_EFFECT:
3788 			case UDESCSUB_AC_CLOCK_SRC:
3789 			case UDESCSUB_AC_CLOCK_SEL:
3790 			case UDESCSUB_AC_CLOCK_MUL:
3791 			case UDESCSUB_AC_SAMPLE_RT:
3792 				break;
3793 
3794 			case UDESCSUB_AC_MIXER:
3795 				uaudio20_mixer_add_mixer(sc, iot, i);
3796 				break;
3797 
3798 			case UDESCSUB_AC_SELECTOR:
3799 				uaudio20_mixer_add_selector(sc, iot, i);
3800 				break;
3801 
3802 			case UDESCSUB_AC_FEATURE:
3803 				uaudio20_mixer_add_feature(sc, iot, i);
3804 				break;
3805 
3806 			default:
3807 				DPRINTF("bad AC desc subtype=0x%02x\n",
3808 				    dp->bDescriptorSubtype);
3809 				break;
3810 			}
3811 			continue;
3812 		}
3813 
3814 		switch (dp->bDescriptorSubtype) {
3815 		case UDESCSUB_AC_HEADER:
3816 			DPRINTF("unexpected AC header\n");
3817 			break;
3818 
3819 		case UDESCSUB_AC_INPUT:
3820 		case UDESCSUB_AC_OUTPUT:
3821 			break;
3822 
3823 		case UDESCSUB_AC_MIXER:
3824 			uaudio_mixer_add_mixer(sc, iot, i);
3825 			break;
3826 
3827 		case UDESCSUB_AC_SELECTOR:
3828 			uaudio_mixer_add_selector(sc, iot, i);
3829 			break;
3830 
3831 		case UDESCSUB_AC_FEATURE:
3832 			uaudio_mixer_add_feature(sc, iot, i);
3833 			break;
3834 
3835 		case UDESCSUB_AC_PROCESSING:
3836 			uaudio_mixer_add_processing(sc, iot, i);
3837 			break;
3838 
3839 		case UDESCSUB_AC_EXTENSION:
3840 			uaudio_mixer_add_extension(sc, iot, i);
3841 			break;
3842 
3843 		default:
3844 			DPRINTF("bad AC desc subtype=0x%02x\n",
3845 			    dp->bDescriptorSubtype);
3846 			break;
3847 		}
3848 
3849 	} while (i--);
3850 
3851 done:
3852 	free(iot, M_TEMP);
3853 }
3854 
3855 static int
3856 uaudio_mixer_get(struct usb_device *udev, uint16_t audio_rev,
3857     uint8_t what, struct uaudio_mixer_node *mc)
3858 {
3859 	struct usb_device_request req;
3860 	int val;
3861 	uint8_t data[2 + (2 * 3)];
3862 	usb_error_t err;
3863 
3864 	if (mc->wValue[0] == -1)
3865 		return (0);
3866 
3867 	if (audio_rev >= UAUDIO_VERSION_30)
3868 		return (0);
3869 	else if (audio_rev >= UAUDIO_VERSION_20) {
3870 		if (what == GET_CUR) {
3871 			req.bRequest = UA20_CS_CUR;
3872 			USETW(req.wLength, 2);
3873 		} else {
3874 			req.bRequest = UA20_CS_RANGE;
3875 			USETW(req.wLength, 8);
3876 		}
3877 	} else {
3878 		uint16_t len = MIX_SIZE(mc->type);
3879 
3880 		req.bRequest = what;
3881 		USETW(req.wLength, len);
3882 	}
3883 
3884 	req.bmRequestType = UT_READ_CLASS_INTERFACE;
3885 	USETW(req.wValue, mc->wValue[0]);
3886 	USETW(req.wIndex, mc->wIndex);
3887 
3888 	memset(data, 0, sizeof(data));
3889 
3890 	err = usbd_do_request(udev, NULL, &req, data);
3891 	if (err) {
3892 		DPRINTF("err=%s\n", usbd_errstr(err));
3893 		return (0);
3894 	}
3895 
3896 	if (audio_rev >= UAUDIO_VERSION_30) {
3897 		val = 0;
3898 	} else if (audio_rev >= UAUDIO_VERSION_20) {
3899 		switch (what) {
3900 		case GET_CUR:
3901 			val = (data[0] | (data[1] << 8));
3902 			break;
3903 		case GET_MIN:
3904 			val = (data[2] | (data[3] << 8));
3905 			break;
3906 		case GET_MAX:
3907 			val = (data[4] | (data[5] << 8));
3908 			break;
3909 		case GET_RES:
3910 			val = (data[6] | (data[7] << 8));
3911 			break;
3912 		default:
3913 			val = 0;
3914 			break;
3915 		}
3916 	} else {
3917 		val = (data[0] | (data[1] << 8));
3918 	}
3919 
3920 	if (what == GET_CUR || what == GET_MIN || what == GET_MAX)
3921 		val = uaudio_mixer_signext(mc->type, val);
3922 
3923 	DPRINTFN(3, "val=%d\n", val);
3924 
3925 	return (val);
3926 }
3927 
3928 static void
3929 uaudio_mixer_write_cfg_callback(struct usb_xfer *xfer, usb_error_t error)
3930 {
3931 	struct usb_device_request req;
3932 	struct uaudio_softc *sc = usbd_xfer_softc(xfer);
3933 	struct uaudio_mixer_node *mc = sc->sc_mixer_curr;
3934 	struct usb_page_cache *pc;
3935 	uint16_t len;
3936 	uint8_t repeat = 1;
3937 	uint8_t update;
3938 	uint8_t chan;
3939 	uint8_t buf[2];
3940 
3941 	DPRINTF("\n");
3942 
3943 	switch (USB_GET_STATE(xfer)) {
3944 	case USB_ST_TRANSFERRED:
3945 tr_transferred:
3946 	case USB_ST_SETUP:
3947 tr_setup:
3948 
3949 		if (mc == NULL) {
3950 			mc = sc->sc_mixer_root;
3951 			sc->sc_mixer_curr = mc;
3952 			sc->sc_mixer_chan = 0;
3953 			repeat = 0;
3954 		}
3955 		while (mc) {
3956 			while (sc->sc_mixer_chan < mc->nchan) {
3957 
3958 				chan = sc->sc_mixer_chan;
3959 
3960 				sc->sc_mixer_chan++;
3961 
3962 				update = ((mc->update[chan / 8] & (1 << (chan % 8))) &&
3963 				    (mc->wValue[chan] != -1));
3964 
3965 				mc->update[chan / 8] &= ~(1 << (chan % 8));
3966 
3967 				if (update) {
3968 
3969 					req.bmRequestType = UT_WRITE_CLASS_INTERFACE;
3970 					USETW(req.wValue, mc->wValue[chan]);
3971 					USETW(req.wIndex, mc->wIndex);
3972 
3973 					if (sc->sc_audio_rev >= UAUDIO_VERSION_30) {
3974 						return;
3975 					} else if (sc->sc_audio_rev >= UAUDIO_VERSION_20) {
3976 						len = 2;
3977 						req.bRequest = UA20_CS_CUR;
3978 						USETW(req.wLength, len);
3979 					} else {
3980 						len = MIX_SIZE(mc->type);
3981 						req.bRequest = SET_CUR;
3982 						USETW(req.wLength, len);
3983 					}
3984 
3985 					buf[0] = (mc->wData[chan] & 0xFF);
3986 					buf[1] = (mc->wData[chan] >> 8) & 0xFF;
3987 
3988 					pc = usbd_xfer_get_frame(xfer, 0);
3989 					usbd_copy_in(pc, 0, &req, sizeof(req));
3990 					pc = usbd_xfer_get_frame(xfer, 1);
3991 					usbd_copy_in(pc, 0, buf, len);
3992 
3993 					usbd_xfer_set_frame_len(xfer, 0, sizeof(req));
3994 					usbd_xfer_set_frame_len(xfer, 1, len);
3995 					usbd_xfer_set_frames(xfer, len ? 2 : 1);
3996 					usbd_transfer_submit(xfer);
3997 					return;
3998 				}
3999 			}
4000 
4001 			mc = mc->next;
4002 			sc->sc_mixer_curr = mc;
4003 			sc->sc_mixer_chan = 0;
4004 		}
4005 
4006 		if (repeat) {
4007 			goto tr_setup;
4008 		}
4009 		break;
4010 
4011 	default:			/* Error */
4012 		DPRINTF("error=%s\n", usbd_errstr(error));
4013 		if (error == USB_ERR_CANCELLED) {
4014 			/* do nothing - we are detaching */
4015 			break;
4016 		}
4017 		goto tr_transferred;
4018 	}
4019 }
4020 
4021 static usb_error_t
4022 uaudio_set_speed(struct usb_device *udev, uint8_t endpt, uint32_t speed)
4023 {
4024 	struct usb_device_request req;
4025 	uint8_t data[3];
4026 
4027 	DPRINTFN(6, "endpt=%d speed=%u\n", endpt, speed);
4028 
4029 	req.bmRequestType = UT_WRITE_CLASS_ENDPOINT;
4030 	req.bRequest = SET_CUR;
4031 	USETW2(req.wValue, SAMPLING_FREQ_CONTROL, 0);
4032 	USETW(req.wIndex, endpt);
4033 	USETW(req.wLength, 3);
4034 	data[0] = speed;
4035 	data[1] = speed >> 8;
4036 	data[2] = speed >> 16;
4037 
4038 	return (usbd_do_request(udev, NULL, &req, data));
4039 }
4040 
4041 static usb_error_t
4042 uaudio20_set_speed(struct usb_device *udev, uint8_t iface_no,
4043     uint8_t clockid, uint32_t speed)
4044 {
4045 	struct usb_device_request req;
4046 	uint8_t data[4];
4047 
4048 	DPRINTFN(6, "ifaceno=%d clockid=%d speed=%u\n",
4049 	    iface_no, clockid, speed);
4050 
4051 	req.bmRequestType = UT_WRITE_CLASS_INTERFACE;
4052 	req.bRequest = UA20_CS_CUR;
4053 	USETW2(req.wValue, UA20_CS_SAM_FREQ_CONTROL, 0);
4054 	USETW2(req.wIndex, clockid, iface_no);
4055 	USETW(req.wLength, 4);
4056 	data[0] = speed;
4057 	data[1] = speed >> 8;
4058 	data[2] = speed >> 16;
4059 	data[3] = speed >> 24;
4060 
4061 	return (usbd_do_request(udev, NULL, &req, data));
4062 }
4063 
4064 static int
4065 uaudio_mixer_signext(uint8_t type, int val)
4066 {
4067 	if (!MIX_UNSIGNED(type)) {
4068 		if (MIX_SIZE(type) == 2) {
4069 			val = (int16_t)val;
4070 		} else {
4071 			val = (int8_t)val;
4072 		}
4073 	}
4074 	return (val);
4075 }
4076 
4077 static int
4078 uaudio_mixer_bsd2value(struct uaudio_mixer_node *mc, int32_t val)
4079 {
4080 	if (mc->type == MIX_ON_OFF) {
4081 		val = (val != 0);
4082 	} else if (mc->type == MIX_SELECTOR) {
4083 		if ((val < mc->minval) ||
4084 		    (val > mc->maxval)) {
4085 			val = mc->minval;
4086 		}
4087 	} else {
4088 
4089 		/* compute actual volume */
4090 		val = (val * mc->mul) / 255;
4091 
4092 		/* add lower offset */
4093 		val = val + mc->minval;
4094 
4095 		/* make sure we don't write a value out of range */
4096 		if (val > mc->maxval)
4097 			val = mc->maxval;
4098 		else if (val < mc->minval)
4099 			val = mc->minval;
4100 	}
4101 
4102 	DPRINTFN(6, "type=0x%03x val=%d min=%d max=%d val=%d\n",
4103 	    mc->type, val, mc->minval, mc->maxval, val);
4104 	return (val);
4105 }
4106 
4107 static void
4108 uaudio_mixer_ctl_set(struct uaudio_softc *sc, struct uaudio_mixer_node *mc,
4109     uint8_t chan, int32_t val)
4110 {
4111 	val = uaudio_mixer_bsd2value(mc, val);
4112 
4113 	mc->update[chan / 8] |= (1 << (chan % 8));
4114 	mc->wData[chan] = val;
4115 
4116 	/* start the transfer, if not already started */
4117 
4118 	usbd_transfer_start(sc->sc_mixer_xfer[0]);
4119 }
4120 
4121 static void
4122 uaudio_mixer_init(struct uaudio_softc *sc)
4123 {
4124 	struct uaudio_mixer_node *mc;
4125 	int32_t i;
4126 
4127 	for (mc = sc->sc_mixer_root; mc;
4128 	    mc = mc->next) {
4129 
4130 		if (mc->ctl != SOUND_MIXER_NRDEVICES) {
4131 			/*
4132 			 * Set device mask bits. See
4133 			 * /usr/include/machine/soundcard.h
4134 			 */
4135 			sc->sc_mix_info |= (1 << mc->ctl);
4136 		}
4137 		if ((mc->ctl == SOUND_MIXER_NRDEVICES) &&
4138 		    (mc->type == MIX_SELECTOR)) {
4139 
4140 			for (i = mc->minval; (i > 0) && (i <= mc->maxval); i++) {
4141 				if (mc->slctrtype[i - 1] == SOUND_MIXER_NRDEVICES) {
4142 					continue;
4143 				}
4144 				sc->sc_recsrc_info |= 1 << mc->slctrtype[i - 1];
4145 			}
4146 		}
4147 	}
4148 }
4149 
4150 int
4151 uaudio_mixer_init_sub(struct uaudio_softc *sc, struct snd_mixer *m)
4152 {
4153 	DPRINTF("\n");
4154 
4155 	if (usbd_transfer_setup(sc->sc_udev, &sc->sc_mixer_iface_index,
4156 	    sc->sc_mixer_xfer, uaudio_mixer_config, 1, sc,
4157 	    mixer_get_lock(m))) {
4158 		DPRINTFN(0, "could not allocate USB "
4159 		    "transfer for audio mixer!\n");
4160 		return (ENOMEM);
4161 	}
4162 	if (!(sc->sc_mix_info & SOUND_MASK_VOLUME)) {
4163 		mix_setparentchild(m, SOUND_MIXER_VOLUME, SOUND_MASK_PCM);
4164 		mix_setrealdev(m, SOUND_MIXER_VOLUME, SOUND_MIXER_NONE);
4165 	}
4166 	mix_setdevs(m, sc->sc_mix_info);
4167 	mix_setrecdevs(m, sc->sc_recsrc_info);
4168 	return (0);
4169 }
4170 
4171 int
4172 uaudio_mixer_uninit_sub(struct uaudio_softc *sc)
4173 {
4174 	DPRINTF("\n");
4175 
4176 	usbd_transfer_unsetup(sc->sc_mixer_xfer, 1);
4177 
4178 	return (0);
4179 }
4180 
4181 void
4182 uaudio_mixer_set(struct uaudio_softc *sc, unsigned type,
4183     unsigned left, unsigned right)
4184 {
4185 	struct uaudio_mixer_node *mc;
4186 
4187 	for (mc = sc->sc_mixer_root; mc;
4188 	    mc = mc->next) {
4189 
4190 		if (mc->ctl == type) {
4191 			if (mc->nchan == 2) {
4192 				/* set Right */
4193 				uaudio_mixer_ctl_set(sc, mc, 1, (int)(right * 255) / 100);
4194 			}
4195 			/* set Left or Mono */
4196 			uaudio_mixer_ctl_set(sc, mc, 0, (int)(left * 255) / 100);
4197 		}
4198 	}
4199 }
4200 
4201 uint32_t
4202 uaudio_mixer_setrecsrc(struct uaudio_softc *sc, uint32_t src)
4203 {
4204 	struct uaudio_mixer_node *mc;
4205 	uint32_t mask;
4206 	uint32_t temp;
4207 	int32_t i;
4208 
4209 	for (mc = sc->sc_mixer_root; mc;
4210 	    mc = mc->next) {
4211 
4212 		if ((mc->ctl == SOUND_MIXER_NRDEVICES) &&
4213 		    (mc->type == MIX_SELECTOR)) {
4214 
4215 			/* compute selector mask */
4216 
4217 			mask = 0;
4218 			for (i = mc->minval; (i > 0) && (i <= mc->maxval); i++) {
4219 				mask |= (1 << mc->slctrtype[i - 1]);
4220 			}
4221 
4222 			temp = mask & src;
4223 			if (temp == 0) {
4224 				continue;
4225 			}
4226 			/* find the first set bit */
4227 			temp = (-temp) & temp;
4228 
4229 			/* update "src" */
4230 			src &= ~mask;
4231 			src |= temp;
4232 
4233 			for (i = mc->minval; (i > 0) && (i <= mc->maxval); i++) {
4234 				if (temp != (1 << mc->slctrtype[i - 1])) {
4235 					continue;
4236 				}
4237 				uaudio_mixer_ctl_set(sc, mc, 0, i);
4238 				break;
4239 			}
4240 		}
4241 	}
4242 	return (src);
4243 }
4244 
4245 /*========================================================================*
4246  * MIDI support routines
4247  *========================================================================*/
4248 
4249 static void
4250 umidi_bulk_read_callback(struct usb_xfer *xfer, usb_error_t error)
4251 {
4252 	struct umidi_chan *chan = usbd_xfer_softc(xfer);
4253 	struct umidi_sub_chan *sub;
4254 	struct usb_page_cache *pc;
4255 	uint8_t buf[4];
4256 	uint8_t cmd_len;
4257 	uint8_t cn;
4258 	uint16_t pos;
4259 	int actlen;
4260 
4261 	usbd_xfer_status(xfer, &actlen, NULL, NULL, NULL);
4262 
4263 	switch (USB_GET_STATE(xfer)) {
4264 	case USB_ST_TRANSFERRED:
4265 
4266 		DPRINTF("actlen=%d bytes\n", actlen);
4267 
4268 		pos = 0;
4269 		pc = usbd_xfer_get_frame(xfer, 0);
4270 
4271 		while (actlen >= 4) {
4272 
4273 			/* copy out the MIDI data */
4274 			usbd_copy_out(pc, pos, buf, 4);
4275 			/* command length */
4276 			cmd_len = umidi_cmd_to_len[buf[0] & 0xF];
4277 			/* cable number */
4278 			cn = buf[0] >> 4;
4279 			/*
4280 			 * Lookup sub-channel. The index is range
4281 			 * checked below.
4282 			 */
4283 			sub = &chan->sub[cn];
4284 
4285 			if ((cmd_len != 0) &&
4286 			    (cn < chan->max_cable) &&
4287 			    (sub->read_open != 0)) {
4288 
4289 				/* Send data to the application */
4290 				usb_fifo_put_data_linear(
4291 				    sub->fifo.fp[USB_FIFO_RX],
4292 				    buf + 1, cmd_len, 1);
4293 			}
4294 			actlen -= 4;
4295 			pos += 4;
4296 		}
4297 
4298 	case USB_ST_SETUP:
4299 		DPRINTF("start\n");
4300 tr_setup:
4301 		usbd_xfer_set_frame_len(xfer, 0, usbd_xfer_max_len(xfer));
4302 		usbd_transfer_submit(xfer);
4303 		break;
4304 
4305 	default:
4306 		DPRINTF("error=%s\n", usbd_errstr(error));
4307 
4308 		if (error != USB_ERR_CANCELLED) {
4309 			/* try to clear stall first */
4310 			usbd_xfer_set_stall(xfer);
4311 			goto tr_setup;
4312 		}
4313 		break;
4314 	}
4315 }
4316 
4317 /*
4318  * The following statemachine, that converts MIDI commands to
4319  * USB MIDI packets, derives from Linux's usbmidi.c, which
4320  * was written by "Clemens Ladisch":
4321  *
4322  * Returns:
4323  *    0: No command
4324  * Else: Command is complete
4325  */
4326 static uint8_t
4327 umidi_convert_to_usb(struct umidi_sub_chan *sub, uint8_t cn, uint8_t b)
4328 {
4329 	uint8_t p0 = (cn << 4);
4330 
4331 	if (b >= 0xf8) {
4332 		sub->temp_0[0] = p0 | 0x0f;
4333 		sub->temp_0[1] = b;
4334 		sub->temp_0[2] = 0;
4335 		sub->temp_0[3] = 0;
4336 		sub->temp_cmd = sub->temp_0;
4337 		return (1);
4338 
4339 	} else if (b >= 0xf0) {
4340 		switch (b) {
4341 		case 0xf0:		/* system exclusive begin */
4342 			sub->temp_1[1] = b;
4343 			sub->state = UMIDI_ST_SYSEX_1;
4344 			break;
4345 		case 0xf1:		/* MIDI time code */
4346 		case 0xf3:		/* song select */
4347 			sub->temp_1[1] = b;
4348 			sub->state = UMIDI_ST_1PARAM;
4349 			break;
4350 		case 0xf2:		/* song position pointer */
4351 			sub->temp_1[1] = b;
4352 			sub->state = UMIDI_ST_2PARAM_1;
4353 			break;
4354 		case 0xf4:		/* unknown */
4355 		case 0xf5:		/* unknown */
4356 			sub->state = UMIDI_ST_UNKNOWN;
4357 			break;
4358 		case 0xf6:		/* tune request */
4359 			sub->temp_1[0] = p0 | 0x05;
4360 			sub->temp_1[1] = 0xf6;
4361 			sub->temp_1[2] = 0;
4362 			sub->temp_1[3] = 0;
4363 			sub->temp_cmd = sub->temp_1;
4364 			sub->state = UMIDI_ST_UNKNOWN;
4365 			return (1);
4366 
4367 		case 0xf7:		/* system exclusive end */
4368 			switch (sub->state) {
4369 			case UMIDI_ST_SYSEX_0:
4370 				sub->temp_1[0] = p0 | 0x05;
4371 				sub->temp_1[1] = 0xf7;
4372 				sub->temp_1[2] = 0;
4373 				sub->temp_1[3] = 0;
4374 				sub->temp_cmd = sub->temp_1;
4375 				sub->state = UMIDI_ST_UNKNOWN;
4376 				return (1);
4377 			case UMIDI_ST_SYSEX_1:
4378 				sub->temp_1[0] = p0 | 0x06;
4379 				sub->temp_1[2] = 0xf7;
4380 				sub->temp_1[3] = 0;
4381 				sub->temp_cmd = sub->temp_1;
4382 				sub->state = UMIDI_ST_UNKNOWN;
4383 				return (1);
4384 			case UMIDI_ST_SYSEX_2:
4385 				sub->temp_1[0] = p0 | 0x07;
4386 				sub->temp_1[3] = 0xf7;
4387 				sub->temp_cmd = sub->temp_1;
4388 				sub->state = UMIDI_ST_UNKNOWN;
4389 				return (1);
4390 			}
4391 			sub->state = UMIDI_ST_UNKNOWN;
4392 			break;
4393 		}
4394 	} else if (b >= 0x80) {
4395 		sub->temp_1[1] = b;
4396 		if ((b >= 0xc0) && (b <= 0xdf)) {
4397 			sub->state = UMIDI_ST_1PARAM;
4398 		} else {
4399 			sub->state = UMIDI_ST_2PARAM_1;
4400 		}
4401 	} else {			/* b < 0x80 */
4402 		switch (sub->state) {
4403 		case UMIDI_ST_1PARAM:
4404 			if (sub->temp_1[1] < 0xf0) {
4405 				p0 |= sub->temp_1[1] >> 4;
4406 			} else {
4407 				p0 |= 0x02;
4408 				sub->state = UMIDI_ST_UNKNOWN;
4409 			}
4410 			sub->temp_1[0] = p0;
4411 			sub->temp_1[2] = b;
4412 			sub->temp_1[3] = 0;
4413 			sub->temp_cmd = sub->temp_1;
4414 			return (1);
4415 		case UMIDI_ST_2PARAM_1:
4416 			sub->temp_1[2] = b;
4417 			sub->state = UMIDI_ST_2PARAM_2;
4418 			break;
4419 		case UMIDI_ST_2PARAM_2:
4420 			if (sub->temp_1[1] < 0xf0) {
4421 				p0 |= sub->temp_1[1] >> 4;
4422 				sub->state = UMIDI_ST_2PARAM_1;
4423 			} else {
4424 				p0 |= 0x03;
4425 				sub->state = UMIDI_ST_UNKNOWN;
4426 			}
4427 			sub->temp_1[0] = p0;
4428 			sub->temp_1[3] = b;
4429 			sub->temp_cmd = sub->temp_1;
4430 			return (1);
4431 		case UMIDI_ST_SYSEX_0:
4432 			sub->temp_1[1] = b;
4433 			sub->state = UMIDI_ST_SYSEX_1;
4434 			break;
4435 		case UMIDI_ST_SYSEX_1:
4436 			sub->temp_1[2] = b;
4437 			sub->state = UMIDI_ST_SYSEX_2;
4438 			break;
4439 		case UMIDI_ST_SYSEX_2:
4440 			sub->temp_1[0] = p0 | 0x04;
4441 			sub->temp_1[3] = b;
4442 			sub->temp_cmd = sub->temp_1;
4443 			sub->state = UMIDI_ST_SYSEX_0;
4444 			return (1);
4445 		default:
4446 			break;
4447 		}
4448 	}
4449 	return (0);
4450 }
4451 
4452 static void
4453 umidi_bulk_write_callback(struct usb_xfer *xfer, usb_error_t error)
4454 {
4455 	struct umidi_chan *chan = usbd_xfer_softc(xfer);
4456 	struct umidi_sub_chan *sub;
4457 	struct usb_page_cache *pc;
4458 	uint32_t actlen;
4459 	uint16_t nframes;
4460 	uint8_t buf;
4461 	uint8_t start_cable;
4462 	uint8_t tr_any;
4463 	int len;
4464 
4465 	usbd_xfer_status(xfer, &len, NULL, NULL, NULL);
4466 
4467 	/*
4468 	 * NOTE: Some MIDI devices only accept 4 bytes of data per
4469 	 * short terminated USB transfer.
4470 	 */
4471 	switch (USB_GET_STATE(xfer)) {
4472 	case USB_ST_TRANSFERRED:
4473 		DPRINTF("actlen=%d bytes\n", len);
4474 
4475 	case USB_ST_SETUP:
4476 tr_setup:
4477 		DPRINTF("start\n");
4478 
4479 		nframes = 0;	/* reset */
4480 		start_cable = chan->curr_cable;
4481 		tr_any = 0;
4482 		pc = usbd_xfer_get_frame(xfer, 0);
4483 
4484 		while (1) {
4485 
4486 			/* round robin de-queueing */
4487 
4488 			sub = &chan->sub[chan->curr_cable];
4489 
4490 			if (sub->write_open) {
4491 				usb_fifo_get_data_linear(sub->fifo.fp[USB_FIFO_TX],
4492 				    &buf, 1, &actlen, 0);
4493 			} else {
4494 				actlen = 0;
4495 			}
4496 
4497 			if (actlen) {
4498 
4499 				tr_any = 1;
4500 
4501 				DPRINTF("byte=0x%02x from FIFO %u\n", buf,
4502 				    (unsigned int)chan->curr_cable);
4503 
4504 				if (umidi_convert_to_usb(sub, chan->curr_cable, buf)) {
4505 
4506 					DPRINTF("sub=0x%02x 0x%02x 0x%02x 0x%02x\n",
4507 					    sub->temp_cmd[0], sub->temp_cmd[1],
4508 					    sub->temp_cmd[2], sub->temp_cmd[3]);
4509 
4510 					usbd_copy_in(pc, nframes * 4, sub->temp_cmd, 4);
4511 
4512 					nframes++;
4513 
4514 					if ((nframes >= UMIDI_TX_FRAMES) || (chan->single_command != 0))
4515 						break;
4516 				} else {
4517 					continue;
4518 				}
4519 			}
4520 
4521 			chan->curr_cable++;
4522 			if (chan->curr_cable >= chan->max_cable)
4523 				chan->curr_cable = 0;
4524 
4525 			if (chan->curr_cable == start_cable) {
4526 				if (tr_any == 0)
4527 					break;
4528 				tr_any = 0;
4529 			}
4530 		}
4531 
4532 		if (nframes != 0) {
4533 			DPRINTF("Transferring %d frames\n", (int)nframes);
4534 			usbd_xfer_set_frame_len(xfer, 0, 4 * nframes);
4535 			usbd_transfer_submit(xfer);
4536 		}
4537 		break;
4538 
4539 	default:			/* Error */
4540 
4541 		DPRINTF("error=%s\n", usbd_errstr(error));
4542 
4543 		if (error != USB_ERR_CANCELLED) {
4544 			/* try to clear stall first */
4545 			usbd_xfer_set_stall(xfer);
4546 			goto tr_setup;
4547 		}
4548 		break;
4549 	}
4550 }
4551 
4552 static struct umidi_sub_chan *
4553 umidi_sub_by_fifo(struct usb_fifo *fifo)
4554 {
4555 	struct umidi_chan *chan = usb_fifo_softc(fifo);
4556 	struct umidi_sub_chan *sub;
4557 	uint32_t n;
4558 
4559 	for (n = 0; n < UMIDI_CABLES_MAX; n++) {
4560 		sub = &chan->sub[n];
4561 		if ((sub->fifo.fp[USB_FIFO_RX] == fifo) ||
4562 		    (sub->fifo.fp[USB_FIFO_TX] == fifo)) {
4563 			return (sub);
4564 		}
4565 	}
4566 
4567 	panic("%s:%d cannot find usb_fifo!\n",
4568 	    __FILE__, __LINE__);
4569 
4570 	return (NULL);
4571 }
4572 
4573 static void
4574 umidi_start_read(struct usb_fifo *fifo)
4575 {
4576 	struct umidi_chan *chan = usb_fifo_softc(fifo);
4577 
4578 	usbd_transfer_start(chan->xfer[UMIDI_RX_TRANSFER]);
4579 }
4580 
4581 static void
4582 umidi_stop_read(struct usb_fifo *fifo)
4583 {
4584 	struct umidi_chan *chan = usb_fifo_softc(fifo);
4585 	struct umidi_sub_chan *sub = umidi_sub_by_fifo(fifo);
4586 
4587 	DPRINTF("\n");
4588 
4589 	sub->read_open = 0;
4590 
4591 	if (--(chan->read_open_refcount) == 0) {
4592 		/*
4593 		 * XXX don't stop the read transfer here, hence that causes
4594 		 * problems with some MIDI adapters
4595 		 */
4596 		DPRINTF("(stopping read transfer)\n");
4597 	}
4598 }
4599 
4600 static void
4601 umidi_start_write(struct usb_fifo *fifo)
4602 {
4603 	struct umidi_chan *chan = usb_fifo_softc(fifo);
4604 
4605 	usbd_transfer_start(chan->xfer[UMIDI_TX_TRANSFER]);
4606 }
4607 
4608 static void
4609 umidi_stop_write(struct usb_fifo *fifo)
4610 {
4611 	struct umidi_chan *chan = usb_fifo_softc(fifo);
4612 	struct umidi_sub_chan *sub = umidi_sub_by_fifo(fifo);
4613 
4614 	DPRINTF("\n");
4615 
4616 	sub->write_open = 0;
4617 
4618 	if (--(chan->write_open_refcount) == 0) {
4619 		DPRINTF("(stopping write transfer)\n");
4620 		usbd_transfer_stop(chan->xfer[UMIDI_TX_TRANSFER]);
4621 	}
4622 }
4623 
4624 static int
4625 umidi_open(struct usb_fifo *fifo, int fflags)
4626 {
4627 	struct umidi_chan *chan = usb_fifo_softc(fifo);
4628 	struct umidi_sub_chan *sub = umidi_sub_by_fifo(fifo);
4629 
4630 	if (fflags & FREAD) {
4631 		if (usb_fifo_alloc_buffer(fifo, 4, (1024 / 4))) {
4632 			return (ENOMEM);
4633 		}
4634 		mtx_lock(&chan->mtx);
4635 		chan->read_open_refcount++;
4636 		sub->read_open = 1;
4637 		mtx_unlock(&chan->mtx);
4638 	}
4639 	if (fflags & FWRITE) {
4640 		if (usb_fifo_alloc_buffer(fifo, 32, (1024 / 32))) {
4641 			return (ENOMEM);
4642 		}
4643 		/* clear stall first */
4644 		mtx_lock(&chan->mtx);
4645 		usbd_xfer_set_stall(chan->xfer[UMIDI_TX_TRANSFER]);
4646 		chan->write_open_refcount++;
4647 		sub->write_open = 1;
4648 
4649 		/* reset */
4650 		sub->state = UMIDI_ST_UNKNOWN;
4651 		mtx_unlock(&chan->mtx);
4652 	}
4653 	return (0);			/* success */
4654 }
4655 
4656 static void
4657 umidi_close(struct usb_fifo *fifo, int fflags)
4658 {
4659 	if (fflags & FREAD) {
4660 		usb_fifo_free_buffer(fifo);
4661 	}
4662 	if (fflags & FWRITE) {
4663 		usb_fifo_free_buffer(fifo);
4664 	}
4665 }
4666 
4667 
4668 static int
4669 umidi_ioctl(struct usb_fifo *fifo, u_long cmd, void *data,
4670     int fflags)
4671 {
4672 	return (ENODEV);
4673 }
4674 
4675 static void
4676 umidi_init(device_t dev)
4677 {
4678 	struct uaudio_softc *sc = device_get_softc(dev);
4679 	struct umidi_chan *chan = &sc->sc_midi_chan;
4680 
4681 	mtx_init(&chan->mtx, "umidi lock", NULL, MTX_DEF | MTX_RECURSE);
4682 }
4683 
4684 static struct usb_fifo_methods umidi_fifo_methods = {
4685 	.f_start_read = &umidi_start_read,
4686 	.f_start_write = &umidi_start_write,
4687 	.f_stop_read = &umidi_stop_read,
4688 	.f_stop_write = &umidi_stop_write,
4689 	.f_open = &umidi_open,
4690 	.f_close = &umidi_close,
4691 	.f_ioctl = &umidi_ioctl,
4692 	.basename[0] = "umidi",
4693 };
4694 
4695 static int
4696 umidi_probe(device_t dev)
4697 {
4698 	struct uaudio_softc *sc = device_get_softc(dev);
4699 	struct usb_attach_arg *uaa = device_get_ivars(dev);
4700 	struct umidi_chan *chan = &sc->sc_midi_chan;
4701 	struct umidi_sub_chan *sub;
4702 	int unit = device_get_unit(dev);
4703 	int error;
4704 	uint32_t n;
4705 
4706 	if (usb_test_quirk(uaa, UQ_SINGLE_CMD_MIDI))
4707 		chan->single_command = 1;
4708 
4709 	if (usbd_set_alt_interface_index(sc->sc_udev, chan->iface_index,
4710 	    chan->iface_alt_index)) {
4711 		DPRINTF("setting of alternate index failed!\n");
4712 		goto detach;
4713 	}
4714 	usbd_set_parent_iface(sc->sc_udev, chan->iface_index,
4715 	    sc->sc_mixer_iface_index);
4716 
4717 	error = usbd_transfer_setup(uaa->device, &chan->iface_index,
4718 	    chan->xfer, umidi_config, UMIDI_N_TRANSFER,
4719 	    chan, &chan->mtx);
4720 	if (error) {
4721 		DPRINTF("error=%s\n", usbd_errstr(error));
4722 		goto detach;
4723 	}
4724 	if ((chan->max_cable > UMIDI_CABLES_MAX) ||
4725 	    (chan->max_cable == 0)) {
4726 		chan->max_cable = UMIDI_CABLES_MAX;
4727 	}
4728 
4729 	for (n = 0; n < chan->max_cable; n++) {
4730 
4731 		sub = &chan->sub[n];
4732 
4733 		error = usb_fifo_attach(sc->sc_udev, chan, &chan->mtx,
4734 		    &umidi_fifo_methods, &sub->fifo, unit, n,
4735 		    chan->iface_index,
4736 		    UID_ROOT, GID_OPERATOR, 0644);
4737 		if (error) {
4738 			goto detach;
4739 		}
4740 	}
4741 
4742 	mtx_lock(&chan->mtx);
4743 
4744 	/* clear stall first */
4745 	usbd_xfer_set_stall(chan->xfer[UMIDI_RX_TRANSFER]);
4746 
4747 	/*
4748 	 * NOTE: At least one device will not work properly unless the
4749 	 * BULK IN pipe is open all the time. This might have to do
4750 	 * about that the internal queues of the device overflow if we
4751 	 * don't read them regularly.
4752 	 */
4753 	usbd_transfer_start(chan->xfer[UMIDI_RX_TRANSFER]);
4754 
4755 	mtx_unlock(&chan->mtx);
4756 
4757 	return (0);			/* success */
4758 
4759 detach:
4760 	return (ENXIO);			/* failure */
4761 }
4762 
4763 static int
4764 umidi_detach(device_t dev)
4765 {
4766 	struct uaudio_softc *sc = device_get_softc(dev);
4767 	struct umidi_chan *chan = &sc->sc_midi_chan;
4768 	uint32_t n;
4769 
4770 	for (n = 0; n < UMIDI_CABLES_MAX; n++) {
4771 		usb_fifo_detach(&chan->sub[n].fifo);
4772 	}
4773 
4774 	mtx_lock(&chan->mtx);
4775 
4776 	usbd_transfer_stop(chan->xfer[UMIDI_RX_TRANSFER]);
4777 
4778 	mtx_unlock(&chan->mtx);
4779 
4780 	usbd_transfer_unsetup(chan->xfer, UMIDI_N_TRANSFER);
4781 
4782 	mtx_destroy(&chan->mtx);
4783 
4784 	return (0);
4785 }
4786 
4787 DRIVER_MODULE(uaudio, uhub, uaudio_driver, uaudio_devclass, NULL, 0);
4788 MODULE_DEPEND(uaudio, usb, 1, 1, 1);
4789 MODULE_DEPEND(uaudio, sound, SOUND_MINVER, SOUND_PREFVER, SOUND_MAXVER);
4790 MODULE_VERSION(uaudio, 1);
4791