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