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