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