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