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