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