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