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