xref: /freebsd/sys/dev/sound/usb/uaudio.c (revision 10b59a9b4add0320d52c15ce057dd697261e7dfc)
1 /*	$NetBSD: uaudio.c,v 1.91 2004/11/05 17:46:14 kent Exp $	*/
2 /*	$FreeBSD$ */
3 
4 /*-
5  * Copyright (c) 1999 The NetBSD Foundation, Inc.
6  * All rights reserved.
7  *
8  * This code is derived from software contributed to The NetBSD Foundation
9  * by Lennart Augustsson (lennart@augustsson.net) at
10  * Carlstedt Research & Technology.
11  *
12  * Redistribution and use in source and binary forms, with or without
13  * modification, are permitted provided that the following conditions
14  * are met:
15  * 1. Redistributions of source code must retain the above copyright
16  *    notice, this list of conditions and the following disclaimer.
17  * 2. Redistributions in binary form must reproduce the above copyright
18  *    notice, this list of conditions and the following disclaimer in the
19  *    documentation and/or other materials provided with the distribution.
20  *
21  * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
22  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
23  * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
24  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
25  * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
26  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
27  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
28  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
29  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
30  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
31  * POSSIBILITY OF SUCH DAMAGE.
32  */
33 
34 /*
35  * USB audio specs: http://www.usb.org/developers/devclass_docs/audio10.pdf
36  *                  http://www.usb.org/developers/devclass_docs/frmts10.pdf
37  *                  http://www.usb.org/developers/devclass_docs/termt10.pdf
38  */
39 
40 /*
41  * Also merged:
42  *  $NetBSD: uaudio.c,v 1.94 2005/01/15 15:19:53 kent Exp $
43  *  $NetBSD: uaudio.c,v 1.95 2005/01/16 06:02:19 dsainty Exp $
44  *  $NetBSD: uaudio.c,v 1.96 2005/01/16 12:46:00 kent Exp $
45  *  $NetBSD: uaudio.c,v 1.97 2005/02/24 08:19:38 martin Exp $
46  */
47 
48 #include <sys/stdint.h>
49 #include <sys/stddef.h>
50 #include <sys/param.h>
51 #include <sys/queue.h>
52 #include <sys/types.h>
53 #include <sys/systm.h>
54 #include <sys/kernel.h>
55 #include <sys/bus.h>
56 #include <sys/module.h>
57 #include <sys/lock.h>
58 #include <sys/mutex.h>
59 #include <sys/condvar.h>
60 #include <sys/sysctl.h>
61 #include <sys/sx.h>
62 #include <sys/unistd.h>
63 #include <sys/callout.h>
64 #include <sys/malloc.h>
65 #include <sys/priv.h>
66 
67 #include "usbdevs.h"
68 #include <dev/usb/usb.h>
69 #include <dev/usb/usbdi.h>
70 #include <dev/usb/usbdi_util.h>
71 
72 #define	USB_DEBUG_VAR uaudio_debug
73 #include <dev/usb/usb_debug.h>
74 
75 #include <dev/usb/quirk/usb_quirk.h>
76 
77 #include <sys/reboot.h>			/* for bootverbose */
78 
79 #ifdef HAVE_KERNEL_OPTION_HEADERS
80 #include "opt_snd.h"
81 #endif
82 
83 #include <dev/sound/pcm/sound.h>
84 #include <dev/sound/usb/uaudioreg.h>
85 #include <dev/sound/usb/uaudio.h>
86 #include <dev/sound/chip.h>
87 #include "feeder_if.h"
88 
89 static int uaudio_default_rate = 0;		/* use rate list */
90 static int uaudio_default_bits = 32;
91 static int uaudio_default_channels = 0;		/* use default */
92 
93 #ifdef USB_DEBUG
94 static int uaudio_debug = 0;
95 
96 static SYSCTL_NODE(_hw_usb, OID_AUTO, uaudio, CTLFLAG_RW, 0, "USB uaudio");
97 
98 SYSCTL_INT(_hw_usb_uaudio, OID_AUTO, debug, CTLFLAG_RW,
99     &uaudio_debug, 0, "uaudio debug level");
100 
101 TUNABLE_INT("hw.usb.uaudio.default_rate", &uaudio_default_rate);
102 SYSCTL_INT(_hw_usb_uaudio, OID_AUTO, default_rate, CTLFLAG_RW,
103     &uaudio_default_rate, 0, "uaudio default sample rate");
104 
105 TUNABLE_INT("hw.usb.uaudio.default_bits", &uaudio_default_bits);
106 SYSCTL_INT(_hw_usb_uaudio, OID_AUTO, default_bits, CTLFLAG_RW,
107     &uaudio_default_bits, 0, "uaudio default sample bits");
108 
109 TUNABLE_INT("hw.usb.uaudio.default_channels", &uaudio_default_channels);
110 SYSCTL_INT(_hw_usb_uaudio, OID_AUTO, default_channels, CTLFLAG_RW,
111     &uaudio_default_channels, 0, "uaudio default sample channels");
112 #endif
113 
114 #define	UAUDIO_NFRAMES		64	/* must be factor of 8 due HS-USB */
115 #define	UAUDIO_NCHANBUFS        2	/* number of outstanding request */
116 #define	UAUDIO_RECURSE_LIMIT   24	/* rounds */
117 
118 #define	MAKE_WORD(h,l) (((h) << 8) | (l))
119 #define	BIT_TEST(bm,bno) (((bm)[(bno) / 8] >> (7 - ((bno) % 8))) & 1)
120 #define	UAUDIO_MAX_CHAN(x) (x)
121 
122 struct uaudio_mixer_node {
123 	int32_t	minval;
124 	int32_t	maxval;
125 #define	MIX_MAX_CHAN 8
126 	int32_t	wValue[MIX_MAX_CHAN];	/* using nchan */
127 	uint32_t mul;
128 	uint32_t ctl;
129 
130 	uint16_t wData[MIX_MAX_CHAN];	/* using nchan */
131 	uint16_t wIndex;
132 
133 	uint8_t	update[(MIX_MAX_CHAN + 7) / 8];
134 	uint8_t	nchan;
135 	uint8_t	type;
136 #define	MIX_ON_OFF	1
137 #define	MIX_SIGNED_16	2
138 #define	MIX_UNSIGNED_16	3
139 #define	MIX_SIGNED_8	4
140 #define	MIX_SELECTOR	5
141 #define	MIX_UNKNOWN     6
142 #define	MIX_SIZE(n) ((((n) == MIX_SIGNED_16) || \
143 		      ((n) == MIX_UNSIGNED_16)) ? 2 : 1)
144 #define	MIX_UNSIGNED(n) ((n) == MIX_UNSIGNED_16)
145 
146 #define	MAX_SELECTOR_INPUT_PIN 256
147 	uint8_t	slctrtype[MAX_SELECTOR_INPUT_PIN];
148 	uint8_t	class;
149 
150 	struct uaudio_mixer_node *next;
151 };
152 
153 struct uaudio_chan {
154 	struct pcmchan_caps pcm_cap;	/* capabilities */
155 
156 	struct snd_dbuf *pcm_buf;
157 	const struct usb_config *usb_cfg;
158 	struct mtx *pcm_mtx;		/* lock protecting this structure */
159 	struct uaudio_softc *priv_sc;
160 	struct pcm_channel *pcm_ch;
161 	struct usb_xfer *xfer[UAUDIO_NCHANBUFS];
162 	const struct usb_audio_streaming_interface_descriptor *p_asid;
163 	const struct usb_audio_streaming_type1_descriptor *p_asf1d;
164 	const struct usb_audio_streaming_endpoint_descriptor *p_sed;
165 	const usb_endpoint_descriptor_audio_t *p_ed1;
166 	const usb_endpoint_descriptor_audio_t *p_ed2;
167 	const struct uaudio_format *p_fmt;
168 
169 	uint8_t *buf;			/* pointer to buffer */
170 	uint8_t *start;			/* upper layer buffer start */
171 	uint8_t *end;			/* upper layer buffer end */
172 	uint8_t *cur;			/* current position in upper layer
173 					 * buffer */
174 
175 	uint32_t intr_size;		/* in bytes */
176 	uint32_t intr_frames;		/* in units */
177 	uint32_t sample_rate;
178 	uint32_t frames_per_second;
179 	uint32_t sample_rem;
180 	uint32_t sample_curr;
181 
182 	uint32_t format;
183 	uint32_t pcm_format[2];
184 
185 	uint16_t bytes_per_frame[2];
186 
187 	uint16_t sample_size;
188 
189 	uint8_t	valid;
190 	uint8_t	iface_index;
191 	uint8_t	iface_alt_index;
192 };
193 
194 #define	UMIDI_CABLES_MAX   16		/* units */
195 #define	UMIDI_TX_FRAMES	   256		/* units */
196 #define	UMIDI_TX_BUFFER    (UMIDI_TX_FRAMES * 4)	/* bytes */
197 
198 enum {
199 	UMIDI_TX_TRANSFER,
200 	UMIDI_RX_TRANSFER,
201 	UMIDI_N_TRANSFER,
202 };
203 
204 struct umidi_sub_chan {
205 	struct usb_fifo_sc fifo;
206 	uint8_t *temp_cmd;
207 	uint8_t	temp_0[4];
208 	uint8_t	temp_1[4];
209 	uint8_t	state;
210 #define	UMIDI_ST_UNKNOWN   0		/* scan for command */
211 #define	UMIDI_ST_1PARAM    1
212 #define	UMIDI_ST_2PARAM_1  2
213 #define	UMIDI_ST_2PARAM_2  3
214 #define	UMIDI_ST_SYSEX_0   4
215 #define	UMIDI_ST_SYSEX_1   5
216 #define	UMIDI_ST_SYSEX_2   6
217 
218 	uint8_t	read_open:1;
219 	uint8_t	write_open:1;
220 	uint8_t	unused:6;
221 };
222 
223 struct umidi_chan {
224 
225 	struct umidi_sub_chan sub[UMIDI_CABLES_MAX];
226 	struct mtx mtx;
227 
228 	struct usb_xfer *xfer[UMIDI_N_TRANSFER];
229 
230 	uint8_t	iface_index;
231 	uint8_t	iface_alt_index;
232 
233 	uint8_t	read_open_refcount;
234 	uint8_t	write_open_refcount;
235 
236 	uint8_t	curr_cable;
237 	uint8_t	max_cable;
238 	uint8_t	valid;
239 	uint8_t single_command;
240 };
241 
242 struct uaudio_softc {
243 	struct sbuf sc_sndstat;
244 	struct sndcard_func sc_sndcard_func;
245 	struct uaudio_chan sc_rec_chan;
246 	struct uaudio_chan sc_play_chan;
247 	struct umidi_chan sc_midi_chan;
248 
249 	struct usb_device *sc_udev;
250 	struct usb_xfer *sc_mixer_xfer[1];
251 	struct uaudio_mixer_node *sc_mixer_root;
252 	struct uaudio_mixer_node *sc_mixer_curr;
253 
254 	uint32_t sc_mix_info;
255 	uint32_t sc_recsrc_info;
256 
257 	uint16_t sc_audio_rev;
258 	uint16_t sc_mixer_count;
259 
260 	uint8_t	sc_sndstat_valid;
261 	uint8_t	sc_mixer_iface_index;
262 	uint8_t	sc_mixer_iface_no;
263 	uint8_t	sc_mixer_chan;
264 	uint8_t	sc_pcm_registered:1;
265 	uint8_t	sc_mixer_init:1;
266 	uint8_t	sc_uq_audio_swap_lr:1;
267 	uint8_t	sc_uq_au_inp_async:1;
268 	uint8_t	sc_uq_au_no_xu:1;
269 	uint8_t	sc_uq_bad_adc:1;
270 	uint8_t	sc_uq_au_vendor_class:1;
271 };
272 
273 struct uaudio_search_result {
274 	uint8_t	bit_input[(256 + 7) / 8];
275 	uint8_t	bit_output[(256 + 7) / 8];
276 	uint8_t	bit_visited[(256 + 7) / 8];
277 	uint8_t	recurse_level;
278 	uint8_t	id_max;
279 };
280 
281 struct uaudio_terminal_node {
282 	union {
283 		const struct usb_descriptor *desc;
284 		const struct usb_audio_input_terminal *it;
285 		const struct usb_audio_output_terminal *ot;
286 		const struct usb_audio_mixer_unit_0 *mu;
287 		const struct usb_audio_selector_unit *su;
288 		const struct usb_audio_feature_unit *fu;
289 		const struct usb_audio_processing_unit_0 *pu;
290 		const struct usb_audio_extension_unit_0 *eu;
291 	}	u;
292 	struct uaudio_search_result usr;
293 	struct uaudio_terminal_node *root;
294 };
295 
296 struct uaudio_format {
297 	uint16_t wFormat;
298 	uint8_t	bPrecision;
299 	uint32_t freebsd_fmt;
300 	const char *description;
301 };
302 
303 static const struct uaudio_format uaudio_formats[] = {
304 
305 	{UA_FMT_PCM8, 8, AFMT_U8, "8-bit U-LE PCM"},
306 	{UA_FMT_PCM8, 16, AFMT_U16_LE, "16-bit U-LE PCM"},
307 	{UA_FMT_PCM8, 24, AFMT_U24_LE, "24-bit U-LE PCM"},
308 	{UA_FMT_PCM8, 32, AFMT_U32_LE, "32-bit U-LE PCM"},
309 
310 	{UA_FMT_PCM, 8, AFMT_S8, "8-bit S-LE PCM"},
311 	{UA_FMT_PCM, 16, AFMT_S16_LE, "16-bit S-LE PCM"},
312 	{UA_FMT_PCM, 24, AFMT_S24_LE, "24-bit S-LE PCM"},
313 	{UA_FMT_PCM, 32, AFMT_S32_LE, "32-bit S-LE PCM"},
314 
315 	{UA_FMT_ALAW, 8, AFMT_A_LAW, "8-bit A-Law"},
316 	{UA_FMT_MULAW, 8, AFMT_MU_LAW, "8-bit mu-Law"},
317 
318 	{0, 0, 0, NULL}
319 };
320 
321 #define	UAC_OUTPUT	0
322 #define	UAC_INPUT	1
323 #define	UAC_EQUAL	2
324 #define	UAC_RECORD	3
325 #define	UAC_NCLASSES	4
326 
327 #ifdef USB_DEBUG
328 static const char *uac_names[] = {
329 	"outputs", "inputs", "equalization", "record"
330 };
331 
332 #endif
333 
334 /* prototypes */
335 
336 static device_probe_t uaudio_probe;
337 static device_attach_t uaudio_attach;
338 static device_detach_t uaudio_detach;
339 
340 static usb_callback_t uaudio_chan_play_callback;
341 static usb_callback_t uaudio_chan_record_callback;
342 static usb_callback_t uaudio_mixer_write_cfg_callback;
343 static usb_callback_t umidi_bulk_read_callback;
344 static usb_callback_t umidi_bulk_write_callback;
345 
346 static void	uaudio_chan_fill_info_sub(struct uaudio_softc *,
347 		    struct usb_device *, uint32_t, uint8_t, uint8_t);
348 static void	uaudio_chan_fill_info(struct uaudio_softc *,
349 		    struct usb_device *);
350 static void	uaudio_mixer_add_ctl_sub(struct uaudio_softc *,
351 		    struct uaudio_mixer_node *);
352 static void	uaudio_mixer_add_ctl(struct uaudio_softc *,
353 		    struct uaudio_mixer_node *);
354 static void	uaudio_mixer_add_input(struct uaudio_softc *,
355 		    const struct uaudio_terminal_node *, int);
356 static void	uaudio_mixer_add_output(struct uaudio_softc *,
357 		    const struct uaudio_terminal_node *, int);
358 static void	uaudio_mixer_add_mixer(struct uaudio_softc *,
359 		    const struct uaudio_terminal_node *, int);
360 static void	uaudio_mixer_add_selector(struct uaudio_softc *,
361 		    const struct uaudio_terminal_node *, int);
362 static uint32_t	uaudio_mixer_feature_get_bmaControls(
363 		    const struct usb_audio_feature_unit *, uint8_t);
364 static void	uaudio_mixer_add_feature(struct uaudio_softc *,
365 		    const struct uaudio_terminal_node *, int);
366 static void	uaudio_mixer_add_processing_updown(struct uaudio_softc *,
367 		    const struct uaudio_terminal_node *, int);
368 static void	uaudio_mixer_add_processing(struct uaudio_softc *,
369 		    const struct uaudio_terminal_node *, int);
370 static void	uaudio_mixer_add_extension(struct uaudio_softc *,
371 		    const struct uaudio_terminal_node *, int);
372 static struct	usb_audio_cluster uaudio_mixer_get_cluster(uint8_t,
373 		    const struct uaudio_terminal_node *);
374 static uint16_t	uaudio_mixer_determine_class(const struct uaudio_terminal_node *,
375 		    struct uaudio_mixer_node *);
376 static uint16_t	uaudio_mixer_feature_name(const struct uaudio_terminal_node *,
377 		    struct uaudio_mixer_node *);
378 static const struct uaudio_terminal_node *uaudio_mixer_get_input(
379 		    const struct uaudio_terminal_node *, uint8_t);
380 static const struct uaudio_terminal_node *uaudio_mixer_get_output(
381 		    const struct uaudio_terminal_node *, uint8_t);
382 static void	uaudio_mixer_find_inputs_sub(struct uaudio_terminal_node *,
383 		    const uint8_t *, uint8_t, struct uaudio_search_result *);
384 static void	uaudio_mixer_find_outputs_sub(struct uaudio_terminal_node *,
385 		    uint8_t, uint8_t, struct uaudio_search_result *);
386 static void	uaudio_mixer_fill_info(struct uaudio_softc *,
387 		    struct usb_device *, void *);
388 static uint16_t	uaudio_mixer_get(struct usb_device *, uint8_t,
389 		    struct uaudio_mixer_node *);
390 static void	uaudio_mixer_ctl_set(struct uaudio_softc *,
391 		    struct uaudio_mixer_node *, uint8_t, int32_t val);
392 static usb_error_t uaudio_set_speed(struct usb_device *, uint8_t, uint32_t);
393 static int	uaudio_mixer_signext(uint8_t, int);
394 static int	uaudio_mixer_bsd2value(struct uaudio_mixer_node *, int32_t val);
395 static const void *uaudio_mixer_verify_desc(const void *, uint32_t);
396 static void	uaudio_mixer_init(struct uaudio_softc *);
397 static uint8_t	umidi_convert_to_usb(struct umidi_sub_chan *, uint8_t, uint8_t);
398 static struct	umidi_sub_chan *umidi_sub_by_fifo(struct usb_fifo *);
399 static void	umidi_start_read(struct usb_fifo *);
400 static void	umidi_stop_read(struct usb_fifo *);
401 static void	umidi_start_write(struct usb_fifo *);
402 static void	umidi_stop_write(struct usb_fifo *);
403 static int	umidi_open(struct usb_fifo *, int);
404 static int	umidi_ioctl(struct usb_fifo *, u_long cmd, void *, int);
405 static void	umidi_close(struct usb_fifo *, int);
406 static void	umidi_init(device_t dev);
407 static int	umidi_probe(device_t dev);
408 static int	umidi_detach(device_t dev);
409 
410 #ifdef USB_DEBUG
411 static void	uaudio_chan_dump_ep_desc(
412 		    const usb_endpoint_descriptor_audio_t *);
413 static void	uaudio_mixer_dump_cluster(uint8_t,
414 		    const struct uaudio_terminal_node *);
415 static const char *uaudio_mixer_get_terminal_name(uint16_t);
416 #endif
417 
418 static const struct usb_config
419 	uaudio_cfg_record[UAUDIO_NCHANBUFS] = {
420 	[0] = {
421 		.type = UE_ISOCHRONOUS,
422 		.endpoint = UE_ADDR_ANY,
423 		.direction = UE_DIR_IN,
424 		.bufsize = 0,	/* use "wMaxPacketSize * frames" */
425 		.frames = UAUDIO_NFRAMES,
426 		.flags = {.short_xfer_ok = 1,},
427 		.callback = &uaudio_chan_record_callback,
428 	},
429 
430 	[1] = {
431 		.type = UE_ISOCHRONOUS,
432 		.endpoint = UE_ADDR_ANY,
433 		.direction = UE_DIR_IN,
434 		.bufsize = 0,	/* use "wMaxPacketSize * frames" */
435 		.frames = UAUDIO_NFRAMES,
436 		.flags = {.short_xfer_ok = 1,},
437 		.callback = &uaudio_chan_record_callback,
438 	},
439 };
440 
441 static const struct usb_config
442 	uaudio_cfg_play[UAUDIO_NCHANBUFS] = {
443 	[0] = {
444 		.type = UE_ISOCHRONOUS,
445 		.endpoint = UE_ADDR_ANY,
446 		.direction = UE_DIR_OUT,
447 		.bufsize = 0,	/* use "wMaxPacketSize * frames" */
448 		.frames = UAUDIO_NFRAMES,
449 		.flags = {.short_xfer_ok = 1,},
450 		.callback = &uaudio_chan_play_callback,
451 	},
452 
453 	[1] = {
454 		.type = UE_ISOCHRONOUS,
455 		.endpoint = UE_ADDR_ANY,
456 		.direction = UE_DIR_OUT,
457 		.bufsize = 0,	/* use "wMaxPacketSize * frames" */
458 		.frames = UAUDIO_NFRAMES,
459 		.flags = {.short_xfer_ok = 1,},
460 		.callback = &uaudio_chan_play_callback,
461 	},
462 };
463 
464 static const struct usb_config
465 	uaudio_mixer_config[1] = {
466 	[0] = {
467 		.type = UE_CONTROL,
468 		.endpoint = 0x00,	/* Control pipe */
469 		.direction = UE_DIR_ANY,
470 		.bufsize = (sizeof(struct usb_device_request) + 4),
471 		.callback = &uaudio_mixer_write_cfg_callback,
472 		.timeout = 1000,	/* 1 second */
473 	},
474 };
475 
476 static const
477 uint8_t	umidi_cmd_to_len[16] = {
478 	[0x0] = 0,			/* reserved */
479 	[0x1] = 0,			/* reserved */
480 	[0x2] = 2,			/* bytes */
481 	[0x3] = 3,			/* bytes */
482 	[0x4] = 3,			/* bytes */
483 	[0x5] = 1,			/* bytes */
484 	[0x6] = 2,			/* bytes */
485 	[0x7] = 3,			/* bytes */
486 	[0x8] = 3,			/* bytes */
487 	[0x9] = 3,			/* bytes */
488 	[0xA] = 3,			/* bytes */
489 	[0xB] = 3,			/* bytes */
490 	[0xC] = 2,			/* bytes */
491 	[0xD] = 2,			/* bytes */
492 	[0xE] = 3,			/* bytes */
493 	[0xF] = 1,			/* bytes */
494 };
495 
496 static const struct usb_config
497 	umidi_config[UMIDI_N_TRANSFER] = {
498 	[UMIDI_TX_TRANSFER] = {
499 		.type = UE_BULK,
500 		.endpoint = UE_ADDR_ANY,
501 		.direction = UE_DIR_OUT,
502 		.bufsize = UMIDI_TX_BUFFER,
503 		.callback = &umidi_bulk_write_callback,
504 	},
505 
506 	[UMIDI_RX_TRANSFER] = {
507 		.type = UE_BULK,
508 		.endpoint = UE_ADDR_ANY,
509 		.direction = UE_DIR_IN,
510 		.bufsize = 4,	/* bytes */
511 		.flags = {.short_xfer_ok = 1,.proxy_buffer = 1,},
512 		.callback = &umidi_bulk_read_callback,
513 	},
514 };
515 
516 static devclass_t uaudio_devclass;
517 
518 static device_method_t uaudio_methods[] = {
519 	DEVMETHOD(device_probe, uaudio_probe),
520 	DEVMETHOD(device_attach, uaudio_attach),
521 	DEVMETHOD(device_detach, uaudio_detach),
522 	DEVMETHOD(device_suspend, bus_generic_suspend),
523 	DEVMETHOD(device_resume, bus_generic_resume),
524 	DEVMETHOD(device_shutdown, bus_generic_shutdown),
525 	DEVMETHOD(bus_print_child, bus_generic_print_child),
526 	{0, 0}
527 };
528 
529 static driver_t uaudio_driver = {
530 	.name = "uaudio",
531 	.methods = uaudio_methods,
532 	.size = sizeof(struct uaudio_softc),
533 };
534 
535 static const STRUCT_USB_HOST_ID __used uaudio_devs[] = {
536 	/* Generic USB audio class match */
537 	{USB_IFACE_CLASS(UICLASS_AUDIO),
538 	 USB_IFACE_SUBCLASS(UISUBCLASS_AUDIOCONTROL),},
539 	/* Generic USB MIDI class match */
540 	{USB_IFACE_CLASS(UICLASS_AUDIO),
541 	 USB_IFACE_SUBCLASS(UISUBCLASS_MIDISTREAM),},
542 };
543 
544 static int
545 uaudio_probe(device_t dev)
546 {
547 	struct usb_attach_arg *uaa = device_get_ivars(dev);
548 
549 	if (uaa->usb_mode != USB_MODE_HOST)
550 		return (ENXIO);
551 
552 	/* lookup non-standard device */
553 
554 	if (uaa->info.bInterfaceClass != UICLASS_AUDIO) {
555 		if (usb_test_quirk(uaa, UQ_AU_VENDOR_CLASS) == 0)
556 			return (ENXIO);
557 	}
558 
559 	/* check for AUDIO control interface */
560 
561 	if (uaa->info.bInterfaceSubClass == UISUBCLASS_AUDIOCONTROL) {
562 		if (usb_test_quirk(uaa, UQ_BAD_AUDIO))
563 			return (ENXIO);
564 		else
565 			return (BUS_PROBE_GENERIC);
566 	}
567 
568 	/* check for MIDI stream */
569 
570 	if (uaa->info.bInterfaceSubClass == UISUBCLASS_MIDISTREAM) {
571 		if (usb_test_quirk(uaa, UQ_BAD_MIDI))
572 			return (ENXIO);
573 		else
574 			return (BUS_PROBE_GENERIC);
575 	}
576 	return (ENXIO);
577 }
578 
579 static int
580 uaudio_attach(device_t dev)
581 {
582 	struct usb_attach_arg *uaa = device_get_ivars(dev);
583 	struct uaudio_softc *sc = device_get_softc(dev);
584 	struct usb_interface_descriptor *id;
585 	device_t child;
586 
587 	sc->sc_play_chan.priv_sc = sc;
588 	sc->sc_rec_chan.priv_sc = sc;
589 	sc->sc_udev = uaa->device;
590 	sc->sc_mixer_iface_index = uaa->info.bIfaceIndex;
591 	sc->sc_mixer_iface_no = uaa->info.bIfaceNum;
592 
593 	if (usb_test_quirk(uaa, UQ_AUDIO_SWAP_LR))
594 		sc->sc_uq_audio_swap_lr = 1;
595 
596 	if (usb_test_quirk(uaa, UQ_AU_INP_ASYNC))
597 		sc->sc_uq_au_inp_async = 1;
598 
599 	if (usb_test_quirk(uaa, UQ_AU_NO_XU))
600 		sc->sc_uq_au_no_xu = 1;
601 
602 	if (usb_test_quirk(uaa, UQ_BAD_ADC))
603 		sc->sc_uq_bad_adc = 1;
604 
605 	if (usb_test_quirk(uaa, UQ_AU_VENDOR_CLASS))
606 		sc->sc_uq_au_vendor_class = 1;
607 
608 	umidi_init(dev);
609 
610 	device_set_usb_desc(dev);
611 
612 	id = usbd_get_interface_descriptor(uaa->iface);
613 
614 	uaudio_chan_fill_info(sc, uaa->device);
615 
616 	uaudio_mixer_fill_info(sc, uaa->device, id);
617 
618 	DPRINTF("audio rev %d.%02x\n",
619 	    sc->sc_audio_rev >> 8,
620 	    sc->sc_audio_rev & 0xff);
621 
622 	DPRINTF("%d mixer controls\n",
623 	    sc->sc_mixer_count);
624 
625 	if (sc->sc_play_chan.valid) {
626 		device_printf(dev, "Play: %d Hz, %d ch, %s format\n",
627 		    sc->sc_play_chan.sample_rate,
628 		    sc->sc_play_chan.p_asf1d->bNrChannels,
629 		    sc->sc_play_chan.p_fmt->description);
630 	} else {
631 		device_printf(dev, "No playback!\n");
632 	}
633 
634 	if (sc->sc_rec_chan.valid) {
635 		device_printf(dev, "Record: %d Hz, %d ch, %s format\n",
636 		    sc->sc_rec_chan.sample_rate,
637 		    sc->sc_rec_chan.p_asf1d->bNrChannels,
638 		    sc->sc_rec_chan.p_fmt->description);
639 	} else {
640 		device_printf(dev, "No recording!\n");
641 	}
642 
643 	if (sc->sc_midi_chan.valid) {
644 
645 		if (umidi_probe(dev)) {
646 			goto detach;
647 		}
648 		device_printf(dev, "MIDI sequencer\n");
649 	} else {
650 		device_printf(dev, "No midi sequencer\n");
651 	}
652 
653 	DPRINTF("doing child attach\n");
654 
655 	/* attach the children */
656 
657 	sc->sc_sndcard_func.func = SCF_PCM;
658 
659 	child = device_add_child(dev, "pcm", -1);
660 
661 	if (child == NULL) {
662 		DPRINTF("out of memory\n");
663 		goto detach;
664 	}
665 	device_set_ivars(child, &sc->sc_sndcard_func);
666 
667 	if (bus_generic_attach(dev)) {
668 		DPRINTF("child attach failed\n");
669 		goto detach;
670 	}
671 	return (0);			/* success */
672 
673 detach:
674 	uaudio_detach(dev);
675 	return (ENXIO);
676 }
677 
678 static void
679 uaudio_pcm_setflags(device_t dev, uint32_t flags)
680 {
681 	pcm_setflags(dev, pcm_getflags(dev) | flags);
682 }
683 
684 int
685 uaudio_attach_sub(device_t dev, kobj_class_t mixer_class, kobj_class_t chan_class)
686 {
687 	struct uaudio_softc *sc = device_get_softc(device_get_parent(dev));
688 	char status[SND_STATUSLEN];
689 
690 	uaudio_mixer_init(sc);
691 
692 	if (sc->sc_uq_audio_swap_lr) {
693 		DPRINTF("hardware has swapped left and right\n");
694 		/* uaudio_pcm_setflags(dev, SD_F_PSWAPLR); */
695 	}
696 	if (!(sc->sc_mix_info & SOUND_MASK_PCM)) {
697 
698 		DPRINTF("emulating master volume\n");
699 
700 		/*
701 		 * Emulate missing pcm mixer controller
702 		 * through FEEDER_VOLUME
703 		 */
704 		uaudio_pcm_setflags(dev, SD_F_SOFTPCMVOL);
705 	}
706 	if (mixer_init(dev, mixer_class, sc)) {
707 		goto detach;
708 	}
709 	sc->sc_mixer_init = 1;
710 
711 	snprintf(status, sizeof(status), "at ? %s", PCM_KLDSTRING(snd_uaudio));
712 
713 	if (pcm_register(dev, sc,
714 	    sc->sc_play_chan.valid ? 1 : 0,
715 	    sc->sc_rec_chan.valid ? 1 : 0)) {
716 		goto detach;
717 	}
718 
719 	uaudio_pcm_setflags(dev, SD_F_MPSAFE);
720 	sc->sc_pcm_registered = 1;
721 
722 	if (sc->sc_play_chan.valid) {
723 		pcm_addchan(dev, PCMDIR_PLAY, chan_class, sc);
724 	}
725 	if (sc->sc_rec_chan.valid) {
726 		pcm_addchan(dev, PCMDIR_REC, chan_class, sc);
727 	}
728 	pcm_setstatus(dev, status);
729 
730 	return (0);			/* success */
731 
732 detach:
733 	uaudio_detach_sub(dev);
734 	return (ENXIO);
735 }
736 
737 int
738 uaudio_detach_sub(device_t dev)
739 {
740 	struct uaudio_softc *sc = device_get_softc(device_get_parent(dev));
741 	int error = 0;
742 
743 repeat:
744 	if (sc->sc_pcm_registered) {
745 		error = pcm_unregister(dev);
746 	} else {
747 		if (sc->sc_mixer_init) {
748 			error = mixer_uninit(dev);
749 		}
750 	}
751 
752 	if (error) {
753 		device_printf(dev, "Waiting for sound application to exit!\n");
754 		usb_pause_mtx(NULL, 2 * hz);
755 		goto repeat;		/* try again */
756 	}
757 	return (0);			/* success */
758 }
759 
760 static int
761 uaudio_detach(device_t dev)
762 {
763 	struct uaudio_softc *sc = device_get_softc(dev);
764 
765 	if (bus_generic_detach(dev)) {
766 		DPRINTF("detach failed!\n");
767 	}
768 	sbuf_delete(&sc->sc_sndstat);
769 	sc->sc_sndstat_valid = 0;
770 
771 	umidi_detach(dev);
772 
773 	return (0);
774 }
775 
776 /*========================================================================*
777  * AS - Audio Stream - routines
778  *========================================================================*/
779 
780 #ifdef USB_DEBUG
781 static void
782 uaudio_chan_dump_ep_desc(const usb_endpoint_descriptor_audio_t *ed)
783 {
784 	if (ed) {
785 		DPRINTF("endpoint=%p bLength=%d bDescriptorType=%d \n"
786 		    "bEndpointAddress=%d bmAttributes=0x%x \n"
787 		    "wMaxPacketSize=%d bInterval=%d \n"
788 		    "bRefresh=%d bSynchAddress=%d\n",
789 		    ed, ed->bLength, ed->bDescriptorType,
790 		    ed->bEndpointAddress, ed->bmAttributes,
791 		    UGETW(ed->wMaxPacketSize), ed->bInterval,
792 		    UEP_HAS_REFRESH(ed) ? ed->bRefresh : 0,
793 		    UEP_HAS_SYNCADDR(ed) ? ed->bSynchAddress : 0);
794 	}
795 }
796 
797 #endif
798 
799 /*
800  * The following is a workaround for broken no-name USB audio devices
801  * sold by dealextreme called "3D sound". The problem is that the
802  * manufacturer computed wMaxPacketSize is too small to hold the
803  * actual data sent. In other words the device sometimes sends more
804  * data than it actually reports it can send in a single isochronous
805  * packet.
806  */
807 static void
808 uaudio_record_fix_fs(usb_endpoint_descriptor_audio_t *ep,
809     uint32_t xps, uint32_t add)
810 {
811 	uint32_t mps;
812 
813 	mps = UGETW(ep->wMaxPacketSize);
814 
815 	/*
816 	 * If the device indicates it can send more data than what the
817 	 * sample rate indicates, we apply the workaround.
818 	 */
819 	if (mps > xps) {
820 
821 		/* allow additional data */
822 		xps += add;
823 
824 		/* check against the maximum USB 1.x length */
825 		if (xps > 1023)
826 			xps = 1023;
827 
828 		/* check if we should do an update */
829 		if (mps < xps) {
830 			/* simply update the wMaxPacketSize field */
831 			USETW(ep->wMaxPacketSize, xps);
832 			DPRINTF("Workaround: Updated wMaxPacketSize "
833 			    "from %d to %d bytes.\n",
834 			    (int)mps, (int)xps);
835 		}
836 	}
837 }
838 
839 static void
840 uaudio_chan_fill_info_sub(struct uaudio_softc *sc, struct usb_device *udev,
841     uint32_t rate, uint8_t channels, uint8_t bit_resolution)
842 {
843 	struct usb_descriptor *desc = NULL;
844 	const struct usb_audio_streaming_interface_descriptor *asid = NULL;
845 	const struct usb_audio_streaming_type1_descriptor *asf1d = NULL;
846 	const struct usb_audio_streaming_endpoint_descriptor *sed = NULL;
847 	usb_endpoint_descriptor_audio_t *ed1 = NULL;
848 	const usb_endpoint_descriptor_audio_t *ed2 = NULL;
849 	struct usb_config_descriptor *cd = usbd_get_config_descriptor(udev);
850 	struct usb_interface_descriptor *id;
851 	const struct uaudio_format *p_fmt;
852 	struct uaudio_chan *chan;
853 	uint16_t curidx = 0xFFFF;
854 	uint16_t lastidx = 0xFFFF;
855 	uint16_t alt_index = 0;
856 	uint16_t wFormat;
857 	uint8_t ep_dir;
858 	uint8_t bChannels;
859 	uint8_t bBitResolution;
860 	uint8_t x;
861 	uint8_t audio_if = 0;
862 	uint8_t uma_if_class;
863 
864 	while ((desc = usb_desc_foreach(cd, desc))) {
865 
866 		if ((desc->bDescriptorType == UDESC_INTERFACE) &&
867 		    (desc->bLength >= sizeof(*id))) {
868 
869 			id = (void *)desc;
870 
871 			if (id->bInterfaceNumber != lastidx) {
872 				lastidx = id->bInterfaceNumber;
873 				curidx++;
874 				alt_index = 0;
875 
876 			} else {
877 				alt_index++;
878 			}
879 
880 			uma_if_class =
881 			    ((id->bInterfaceClass == UICLASS_AUDIO) ||
882 			    ((id->bInterfaceClass == UICLASS_VENDOR) &&
883 			    (sc->sc_uq_au_vendor_class != 0)));
884 
885 			if ((uma_if_class != 0) && (id->bInterfaceSubClass == UISUBCLASS_AUDIOSTREAM)) {
886 				audio_if = 1;
887 			} else {
888 				audio_if = 0;
889 			}
890 
891 			if ((uma_if_class != 0) &&
892 			    (id->bInterfaceSubClass == UISUBCLASS_MIDISTREAM)) {
893 
894 				/*
895 				 * XXX could allow multiple MIDI interfaces
896 				 */
897 
898 				if ((sc->sc_midi_chan.valid == 0) &&
899 				    usbd_get_iface(udev, curidx)) {
900 					sc->sc_midi_chan.iface_index = curidx;
901 					sc->sc_midi_chan.iface_alt_index = alt_index;
902 					sc->sc_midi_chan.valid = 1;
903 				}
904 			}
905 			asid = NULL;
906 			asf1d = NULL;
907 			ed1 = NULL;
908 			ed2 = NULL;
909 			sed = NULL;
910 		}
911 		if ((desc->bDescriptorType == UDESC_CS_INTERFACE) &&
912 		    (desc->bDescriptorSubtype == AS_GENERAL) &&
913 		    (desc->bLength >= sizeof(*asid))) {
914 			if (asid == NULL) {
915 				asid = (void *)desc;
916 			}
917 		}
918 		if ((desc->bDescriptorType == UDESC_CS_INTERFACE) &&
919 		    (desc->bDescriptorSubtype == FORMAT_TYPE) &&
920 		    (desc->bLength >= sizeof(*asf1d))) {
921 			if (asf1d == NULL) {
922 				asf1d = (void *)desc;
923 				if (asf1d->bFormatType != FORMAT_TYPE_I) {
924 					DPRINTFN(11, "ignored bFormatType = %d\n",
925 					    asf1d->bFormatType);
926 					asf1d = NULL;
927 					continue;
928 				}
929 				if (asf1d->bLength < (sizeof(*asf1d) +
930 				    ((asf1d->bSamFreqType == 0) ? 6 :
931 				    (asf1d->bSamFreqType * 3)))) {
932 					DPRINTFN(11, "'asf1d' descriptor is too short\n");
933 					asf1d = NULL;
934 					continue;
935 				}
936 			}
937 		}
938 		if ((desc->bDescriptorType == UDESC_ENDPOINT) &&
939 		    (desc->bLength >= UEP_MINSIZE)) {
940 			if (ed1 == NULL) {
941 				ed1 = (void *)desc;
942 				if (UE_GET_XFERTYPE(ed1->bmAttributes) != UE_ISOCHRONOUS) {
943 					ed1 = NULL;
944 				}
945 			}
946 		}
947 		if ((desc->bDescriptorType == UDESC_CS_ENDPOINT) &&
948 		    (desc->bDescriptorSubtype == AS_GENERAL) &&
949 		    (desc->bLength >= sizeof(*sed))) {
950 			if (sed == NULL) {
951 				sed = (void *)desc;
952 			}
953 		}
954 		if (audio_if && asid && asf1d && ed1 && sed) {
955 
956 			ep_dir = UE_GET_DIR(ed1->bEndpointAddress);
957 
958 			/* We ignore sync endpoint information until further. */
959 
960 			wFormat = UGETW(asid->wFormatTag);
961 			bChannels = UAUDIO_MAX_CHAN(asf1d->bNrChannels);
962 			bBitResolution = asf1d->bBitResolution;
963 
964 			if (asf1d->bSamFreqType == 0) {
965 				DPRINTFN(16, "Sample rate: %d-%dHz\n",
966 				    UA_SAMP_LO(asf1d), UA_SAMP_HI(asf1d));
967 
968 				if ((rate >= UA_SAMP_LO(asf1d)) &&
969 				    (rate <= UA_SAMP_HI(asf1d))) {
970 					goto found_rate;
971 				}
972 			} else {
973 
974 				for (x = 0; x < asf1d->bSamFreqType; x++) {
975 					DPRINTFN(16, "Sample rate = %dHz\n",
976 					    UA_GETSAMP(asf1d, x));
977 
978 					if (rate == UA_GETSAMP(asf1d, x)) {
979 						goto found_rate;
980 					}
981 				}
982 			}
983 
984 			audio_if = 0;
985 			continue;
986 
987 	found_rate:
988 
989 			for (p_fmt = uaudio_formats;
990 			    p_fmt->wFormat;
991 			    p_fmt++) {
992 				if ((p_fmt->wFormat == wFormat) &&
993 				    (p_fmt->bPrecision == bBitResolution)) {
994 					goto found_format;
995 				}
996 			}
997 
998 			audio_if = 0;
999 			continue;
1000 
1001 	found_format:
1002 
1003 			if ((bChannels == channels) &&
1004 			    (bBitResolution == bit_resolution)) {
1005 
1006 				chan = (ep_dir == UE_DIR_IN) ?
1007 				    &sc->sc_rec_chan :
1008 				    &sc->sc_play_chan;
1009 
1010 				if ((chan->valid == 0) && usbd_get_iface(udev, curidx)) {
1011 
1012 					chan->valid = 1;
1013 #ifdef USB_DEBUG
1014 					uaudio_chan_dump_ep_desc(ed1);
1015 					uaudio_chan_dump_ep_desc(ed2);
1016 
1017 					if (sed->bmAttributes & UA_SED_FREQ_CONTROL) {
1018 						DPRINTFN(2, "FREQ_CONTROL\n");
1019 					}
1020 					if (sed->bmAttributes & UA_SED_PITCH_CONTROL) {
1021 						DPRINTFN(2, "PITCH_CONTROL\n");
1022 					}
1023 #endif
1024 					DPRINTF("Sample rate = %dHz, channels = %d, "
1025 					    "bits = %d, format = %s\n", rate, channels,
1026 					    bit_resolution, p_fmt->description);
1027 
1028 					chan->sample_rate = rate;
1029 					chan->p_asid = asid;
1030 					chan->p_asf1d = asf1d;
1031 					chan->p_ed1 = ed1;
1032 					chan->p_ed2 = ed2;
1033 					chan->p_fmt = p_fmt;
1034 					chan->p_sed = sed;
1035 					chan->iface_index = curidx;
1036 					chan->iface_alt_index = alt_index;
1037 
1038 					if (ep_dir == UE_DIR_IN)
1039 						chan->usb_cfg =
1040 						    uaudio_cfg_record;
1041 					else
1042 						chan->usb_cfg =
1043 						    uaudio_cfg_play;
1044 
1045 					chan->sample_size = ((
1046 					    UAUDIO_MAX_CHAN(chan->p_asf1d->bNrChannels) *
1047 					    chan->p_asf1d->bBitResolution) / 8);
1048 
1049 					if (ep_dir == UE_DIR_IN &&
1050 					    usbd_get_speed(udev) == USB_SPEED_FULL) {
1051 						uaudio_record_fix_fs(ed1,
1052 						    chan->sample_size * (rate / 1000),
1053 						    chan->sample_size * (rate / 4000));
1054 					}
1055 
1056 					if (sc->sc_sndstat_valid) {
1057 						sbuf_printf(&sc->sc_sndstat, "\n\t"
1058 						    "mode %d.%d:(%s) %dch, %d/%dbit, %s, %dHz",
1059 						    curidx, alt_index,
1060 						    (ep_dir == UE_DIR_IN) ? "input" : "output",
1061 						    asf1d->bNrChannels, asf1d->bBitResolution,
1062 						    asf1d->bSubFrameSize * 8,
1063 						    p_fmt->description, rate);
1064 					}
1065 				}
1066 			}
1067 			audio_if = 0;
1068 			continue;
1069 		}
1070 	}
1071 }
1072 
1073 /* This structure defines all the supported rates. */
1074 
1075 static const uint32_t uaudio_rate_list[] = {
1076 	96000,
1077 	88000,
1078 	80000,
1079 	72000,
1080 	64000,
1081 	56000,
1082 	48000,
1083 	44100,
1084 	40000,
1085 	32000,
1086 	24000,
1087 	22050,
1088 	16000,
1089 	11025,
1090 	8000,
1091 	0
1092 };
1093 
1094 static void
1095 uaudio_chan_fill_info(struct uaudio_softc *sc, struct usb_device *udev)
1096 {
1097 	uint32_t rate = uaudio_default_rate;
1098 	uint8_t z;
1099 	uint8_t bits = uaudio_default_bits;
1100 	uint8_t y;
1101 	uint8_t channels = uaudio_default_channels;
1102 	uint8_t x;
1103 
1104 	bits -= (bits % 8);
1105 	if ((bits == 0) || (bits > 32)) {
1106 		/* set a valid value */
1107 		bits = 32;
1108 	}
1109 	if (channels == 0) {
1110 		switch (usbd_get_speed(udev)) {
1111 		case USB_SPEED_LOW:
1112 		case USB_SPEED_FULL:
1113 			/*
1114 			 * Due to high bandwidth usage and problems
1115 			 * with HIGH-speed split transactions we
1116 			 * disable surround setups on FULL-speed USB
1117 			 * by default
1118 			 */
1119 			channels = 2;
1120 			break;
1121 		default:
1122 			channels = 16;
1123 			break;
1124 		}
1125 	} else if (channels > 16) {
1126 		channels = 16;
1127 	}
1128 	if (sbuf_new(&sc->sc_sndstat, NULL, 4096, SBUF_AUTOEXTEND)) {
1129 		sc->sc_sndstat_valid = 1;
1130 	}
1131 	/* try to search for a valid config */
1132 
1133 	for (x = channels; x; x--) {
1134 		for (y = bits; y; y -= 8) {
1135 
1136 			/* try user defined rate, if any */
1137 			if (rate != 0)
1138 				uaudio_chan_fill_info_sub(sc, udev, rate, x, y);
1139 
1140 			/* try find a matching rate, if any */
1141 			for (z = 0; uaudio_rate_list[z]; z++) {
1142 				uaudio_chan_fill_info_sub(sc, udev, uaudio_rate_list[z], x, y);
1143 
1144 				if (sc->sc_rec_chan.valid &&
1145 				    sc->sc_play_chan.valid) {
1146 					goto done;
1147 				}
1148 			}
1149 		}
1150 	}
1151 
1152 done:
1153 	if (sc->sc_sndstat_valid) {
1154 		sbuf_finish(&sc->sc_sndstat);
1155 	}
1156 }
1157 
1158 static void
1159 uaudio_chan_play_callback(struct usb_xfer *xfer, usb_error_t error)
1160 {
1161 	struct uaudio_chan *ch = usbd_xfer_softc(xfer);
1162 	struct usb_page_cache *pc;
1163 	uint32_t total;
1164 	uint32_t blockcount;
1165 	uint32_t n;
1166 	uint32_t offset;
1167 	int actlen;
1168 	int sumlen;
1169 
1170 	usbd_xfer_status(xfer, &actlen, &sumlen, NULL, NULL);
1171 
1172 	if (ch->end == ch->start) {
1173 		DPRINTF("no buffer!\n");
1174 		return;
1175 	}
1176 
1177 	switch (USB_GET_STATE(xfer)) {
1178 	case USB_ST_TRANSFERRED:
1179 tr_transferred:
1180 		if (actlen < sumlen) {
1181 			DPRINTF("short transfer, "
1182 			    "%d of %d bytes\n", actlen, sumlen);
1183 		}
1184 		chn_intr(ch->pcm_ch);
1185 
1186 	case USB_ST_SETUP:
1187 		if (ch->bytes_per_frame[1] > usbd_xfer_max_framelen(xfer)) {
1188 			DPRINTF("bytes per transfer, %d, "
1189 			    "exceeds maximum, %d!\n",
1190 			    ch->bytes_per_frame[1],
1191 			    usbd_xfer_max_framelen(xfer));
1192 			break;
1193 		}
1194 
1195 		blockcount = ch->intr_frames;
1196 
1197 		/* setup number of frames */
1198 		usbd_xfer_set_frames(xfer, blockcount);
1199 
1200 		/* reset total length */
1201 		total = 0;
1202 
1203 		/* setup frame lengths */
1204 		for (n = 0; n != blockcount; n++) {
1205 			ch->sample_curr += ch->sample_rem;
1206 			if (ch->sample_curr >= ch->frames_per_second) {
1207 				ch->sample_curr -= ch->frames_per_second;
1208 				usbd_xfer_set_frame_len(xfer, n, ch->bytes_per_frame[1]);
1209 				total += ch->bytes_per_frame[1];
1210 			} else {
1211 				usbd_xfer_set_frame_len(xfer, n, ch->bytes_per_frame[0]);
1212 				total += ch->bytes_per_frame[0];
1213 			}
1214 		}
1215 
1216 		DPRINTFN(6, "transfer %d bytes\n", total);
1217 
1218 		offset = 0;
1219 
1220 		pc = usbd_xfer_get_frame(xfer, 0);
1221 		while (total > 0) {
1222 
1223 			n = (ch->end - ch->cur);
1224 			if (n > total) {
1225 				n = total;
1226 			}
1227 			usbd_copy_in(pc, offset, ch->cur, n);
1228 
1229 			total -= n;
1230 			ch->cur += n;
1231 			offset += n;
1232 
1233 			if (ch->cur >= ch->end) {
1234 				ch->cur = ch->start;
1235 			}
1236 		}
1237 
1238 		usbd_transfer_submit(xfer);
1239 		break;
1240 
1241 	default:			/* Error */
1242 		if (error == USB_ERR_CANCELLED) {
1243 			break;
1244 		}
1245 		goto tr_transferred;
1246 	}
1247 }
1248 
1249 static void
1250 uaudio_chan_record_callback(struct usb_xfer *xfer, usb_error_t error)
1251 {
1252 	struct uaudio_chan *ch = usbd_xfer_softc(xfer);
1253 	struct usb_page_cache *pc;
1254 	uint32_t n;
1255 	uint32_t m;
1256 	uint32_t blockcount;
1257 	uint32_t offset0;
1258 	uint32_t offset1;
1259 	uint32_t mfl;
1260 	int len;
1261 	int actlen;
1262 	int nframes;
1263 
1264 	usbd_xfer_status(xfer, &actlen, NULL, NULL, &nframes);
1265 	mfl = usbd_xfer_max_framelen(xfer);
1266 
1267 	if (ch->end == ch->start) {
1268 		DPRINTF("no buffer!\n");
1269 		return;
1270 	}
1271 
1272 	switch (USB_GET_STATE(xfer)) {
1273 	case USB_ST_TRANSFERRED:
1274 
1275 		DPRINTFN(6, "transferred %d bytes\n", actlen);
1276 
1277 		offset0 = 0;
1278 		pc = usbd_xfer_get_frame(xfer, 0);
1279 
1280 		for (n = 0; n != nframes; n++) {
1281 
1282 			offset1 = offset0;
1283 			len = usbd_xfer_frame_len(xfer, n);
1284 
1285 			while (len > 0) {
1286 
1287 				m = (ch->end - ch->cur);
1288 
1289 				if (m > len) {
1290 					m = len;
1291 				}
1292 				usbd_copy_out(pc, offset1, ch->cur, m);
1293 
1294 				len -= m;
1295 				offset1 += m;
1296 				ch->cur += m;
1297 
1298 				if (ch->cur >= ch->end) {
1299 					ch->cur = ch->start;
1300 				}
1301 			}
1302 
1303 			offset0 += mfl;
1304 		}
1305 
1306 		chn_intr(ch->pcm_ch);
1307 
1308 	case USB_ST_SETUP:
1309 tr_setup:
1310 		blockcount = ch->intr_frames;
1311 
1312 		usbd_xfer_set_frames(xfer, blockcount);
1313 		for (n = 0; n < blockcount; n++) {
1314 			usbd_xfer_set_frame_len(xfer, n, mfl);
1315 		}
1316 
1317 		usbd_transfer_submit(xfer);
1318 		break;
1319 
1320 	default:			/* Error */
1321 		if (error == USB_ERR_CANCELLED) {
1322 			break;
1323 		}
1324 		goto tr_setup;
1325 	}
1326 }
1327 
1328 void   *
1329 uaudio_chan_init(struct uaudio_softc *sc, struct snd_dbuf *b,
1330     struct pcm_channel *c, int dir)
1331 {
1332 	struct uaudio_chan *ch = ((dir == PCMDIR_PLAY) ?
1333 	    &sc->sc_play_chan : &sc->sc_rec_chan);
1334 	uint32_t buf_size;
1335 	uint32_t frames;
1336 	uint32_t format;
1337 	uint16_t fps;
1338 	uint8_t endpoint;
1339 	uint8_t blocks;
1340 	uint8_t iface_index;
1341 	uint8_t alt_index;
1342 	uint8_t fps_shift;
1343 	usb_error_t err;
1344 
1345 	fps = usbd_get_isoc_fps(sc->sc_udev);
1346 
1347 	if (fps < 8000) {
1348 		/* FULL speed USB */
1349 		frames = 8;
1350 	} else {
1351 		/* HIGH speed USB */
1352 		frames = UAUDIO_NFRAMES;
1353 	}
1354 
1355 	/* setup play/record format */
1356 
1357 	ch->pcm_cap.fmtlist = ch->pcm_format;
1358 
1359 	ch->pcm_format[0] = 0;
1360 	ch->pcm_format[1] = 0;
1361 
1362 	ch->pcm_cap.minspeed = ch->sample_rate;
1363 	ch->pcm_cap.maxspeed = ch->sample_rate;
1364 
1365 	/* setup mutex and PCM channel */
1366 
1367 	ch->pcm_ch = c;
1368 	ch->pcm_mtx = c->lock;
1369 
1370 	format = ch->p_fmt->freebsd_fmt;
1371 
1372 	switch (ch->p_asf1d->bNrChannels) {
1373 	case 2:
1374 		/* stereo */
1375 		format = SND_FORMAT(format, 2, 0);
1376 		break;
1377 	case 1:
1378 		/* mono */
1379 		format = SND_FORMAT(format, 1, 0);
1380 		break;
1381 	default:
1382 		/* surround and more */
1383 		format = feeder_matrix_default_format(
1384 		    SND_FORMAT(format, ch->p_asf1d->bNrChannels, 0));
1385 		break;
1386 	}
1387 
1388 	ch->pcm_cap.fmtlist[0] = format;
1389 	ch->pcm_cap.fmtlist[1] = 0;
1390 
1391 	/* check if format is not supported */
1392 
1393 	if (format == 0) {
1394 		DPRINTF("The selected audio format is not supported\n");
1395 		goto error;
1396 	}
1397 
1398 	/* set alternate interface corresponding to the mode */
1399 
1400 	endpoint = ch->p_ed1->bEndpointAddress;
1401 	iface_index = ch->iface_index;
1402 	alt_index = ch->iface_alt_index;
1403 
1404 	DPRINTF("endpoint=0x%02x, speed=%d, iface=%d alt=%d\n",
1405 	    endpoint, ch->sample_rate, iface_index, alt_index);
1406 
1407 	err = usbd_set_alt_interface_index(sc->sc_udev, iface_index, alt_index);
1408 	if (err) {
1409 		DPRINTF("setting of alternate index failed: %s!\n",
1410 		    usbd_errstr(err));
1411 		goto error;
1412 	}
1413 	usbd_set_parent_iface(sc->sc_udev, iface_index,
1414 	    sc->sc_mixer_iface_index);
1415 
1416 	/*
1417 	 * Only set the sample rate if the channel reports that it
1418 	 * supports the frequency control.
1419 	 */
1420 	if (ch->p_sed->bmAttributes & UA_SED_FREQ_CONTROL) {
1421 		if (uaudio_set_speed(sc->sc_udev, endpoint, ch->sample_rate)) {
1422 			/*
1423 			 * If the endpoint is adaptive setting the speed may
1424 			 * fail.
1425 			 */
1426 			DPRINTF("setting of sample rate failed! (continuing anyway)\n");
1427 		}
1428 	}
1429 	if (usbd_transfer_setup(sc->sc_udev, &iface_index, ch->xfer,
1430 	    ch->usb_cfg, UAUDIO_NCHANBUFS, ch, ch->pcm_mtx)) {
1431 		DPRINTF("could not allocate USB transfers!\n");
1432 		goto error;
1433 	}
1434 
1435 	fps_shift = usbd_xfer_get_fps_shift(ch->xfer[0]);
1436 
1437 	/* down shift number of frames per second, if any */
1438 	fps >>= fps_shift;
1439 	frames >>= fps_shift;
1440 
1441 	/* bytes per frame should not be zero */
1442 	ch->bytes_per_frame[0] = ((ch->sample_rate / fps) * ch->sample_size);
1443 	ch->bytes_per_frame[1] = (((ch->sample_rate + fps - 1) / fps) * ch->sample_size);
1444 
1445 	/* setup data rate dithering, if any */
1446 	ch->frames_per_second = fps;
1447 	ch->sample_rem = ch->sample_rate % fps;
1448 	ch->sample_curr = 0;
1449 	ch->frames_per_second = fps;
1450 
1451 	/* compute required buffer size */
1452 	buf_size = (ch->bytes_per_frame[1] * frames);
1453 
1454 	ch->intr_size = buf_size;
1455 	ch->intr_frames = frames;
1456 
1457 	DPRINTF("fps=%d sample_rem=%d\n", fps, ch->sample_rem);
1458 
1459 	if (ch->intr_frames == 0) {
1460 		DPRINTF("frame shift is too high!\n");
1461 		goto error;
1462 	}
1463 
1464 	/* setup double buffering */
1465 	buf_size *= 2;
1466 	blocks = 2;
1467 
1468 	ch->buf = malloc(buf_size, M_DEVBUF, M_WAITOK | M_ZERO);
1469 	if (ch->buf == NULL)
1470 		goto error;
1471 	if (sndbuf_setup(b, ch->buf, buf_size) != 0)
1472 		goto error;
1473 	if (sndbuf_resize(b, blocks, ch->intr_size))
1474 		goto error;
1475 
1476 	ch->start = ch->buf;
1477 	ch->end = ch->buf + buf_size;
1478 	ch->cur = ch->buf;
1479 	ch->pcm_buf = b;
1480 
1481 	if (ch->pcm_mtx == NULL) {
1482 		DPRINTF("ERROR: PCM channels does not have a mutex!\n");
1483 		goto error;
1484 	}
1485 
1486 	return (ch);
1487 
1488 error:
1489 	uaudio_chan_free(ch);
1490 	return (NULL);
1491 }
1492 
1493 int
1494 uaudio_chan_free(struct uaudio_chan *ch)
1495 {
1496 	if (ch->buf != NULL) {
1497 		free(ch->buf, M_DEVBUF);
1498 		ch->buf = NULL;
1499 	}
1500 	usbd_transfer_unsetup(ch->xfer, UAUDIO_NCHANBUFS);
1501 
1502 	ch->valid = 0;
1503 
1504 	return (0);
1505 }
1506 
1507 int
1508 uaudio_chan_set_param_blocksize(struct uaudio_chan *ch, uint32_t blocksize)
1509 {
1510 	return (ch->intr_size);
1511 }
1512 
1513 int
1514 uaudio_chan_set_param_fragments(struct uaudio_chan *ch, uint32_t blocksize,
1515     uint32_t blockcount)
1516 {
1517 	return (1);
1518 }
1519 
1520 int
1521 uaudio_chan_set_param_speed(struct uaudio_chan *ch, uint32_t speed)
1522 {
1523 	if (speed != ch->sample_rate) {
1524 		DPRINTF("rate conversion required\n");
1525 	}
1526 	return (ch->sample_rate);
1527 }
1528 
1529 int
1530 uaudio_chan_getptr(struct uaudio_chan *ch)
1531 {
1532 	return (ch->cur - ch->start);
1533 }
1534 
1535 struct pcmchan_caps *
1536 uaudio_chan_getcaps(struct uaudio_chan *ch)
1537 {
1538 	return (&ch->pcm_cap);
1539 }
1540 
1541 static struct pcmchan_matrix uaudio_chan_matrix_swap_2_0 = {
1542 	.id = SND_CHN_MATRIX_DRV,
1543 	.channels = 2,
1544 	.ext = 0,
1545 	.map = {
1546 		/* Right */
1547 		[0] = {
1548 			.type = SND_CHN_T_FR,
1549 			.members =
1550 			    SND_CHN_T_MASK_FR | SND_CHN_T_MASK_FC |
1551 			    SND_CHN_T_MASK_LF | SND_CHN_T_MASK_BR |
1552 			    SND_CHN_T_MASK_BC | SND_CHN_T_MASK_SR
1553 		},
1554 		/* Left */
1555 		[1] = {
1556 			.type = SND_CHN_T_FL,
1557 			.members =
1558 			    SND_CHN_T_MASK_FL | SND_CHN_T_MASK_FC |
1559 			    SND_CHN_T_MASK_LF | SND_CHN_T_MASK_BL |
1560 			    SND_CHN_T_MASK_BC | SND_CHN_T_MASK_SL
1561 		},
1562 		[2] = {
1563 			.type = SND_CHN_T_MAX,
1564 			.members = 0
1565 		}
1566 	},
1567 	.mask = SND_CHN_T_MASK_FR | SND_CHN_T_MASK_FL,
1568 	.offset = {  1,  0, -1, -1, -1, -1, -1, -1, -1,
1569 		    -1, -1, -1, -1, -1, -1, -1, -1, -1  }
1570 };
1571 
1572 struct pcmchan_matrix *
1573 uaudio_chan_getmatrix(struct uaudio_chan *ch, uint32_t format)
1574 {
1575 	struct uaudio_softc *sc;
1576 
1577 	sc = ch->priv_sc;
1578 
1579 	if (sc != NULL && sc->sc_uq_audio_swap_lr != 0 &&
1580 	    AFMT_CHANNEL(format) == 2)
1581 		return (&uaudio_chan_matrix_swap_2_0);
1582 
1583 	return (feeder_matrix_format_map(format));
1584 }
1585 
1586 int
1587 uaudio_chan_set_param_format(struct uaudio_chan *ch, uint32_t format)
1588 {
1589 	ch->format = format;
1590 	return (0);
1591 }
1592 
1593 int
1594 uaudio_chan_start(struct uaudio_chan *ch)
1595 {
1596 	ch->cur = ch->start;
1597 
1598 #if (UAUDIO_NCHANBUFS != 2)
1599 #error "please update code"
1600 #endif
1601 	if (ch->xfer[0]) {
1602 		usbd_transfer_start(ch->xfer[0]);
1603 	}
1604 	if (ch->xfer[1]) {
1605 		usbd_transfer_start(ch->xfer[1]);
1606 	}
1607 	return (0);
1608 }
1609 
1610 int
1611 uaudio_chan_stop(struct uaudio_chan *ch)
1612 {
1613 #if (UAUDIO_NCHANBUFS != 2)
1614 #error "please update code"
1615 #endif
1616 	usbd_transfer_stop(ch->xfer[0]);
1617 	usbd_transfer_stop(ch->xfer[1]);
1618 	return (0);
1619 }
1620 
1621 /*========================================================================*
1622  * AC - Audio Controller - routines
1623  *========================================================================*/
1624 
1625 static void
1626 uaudio_mixer_add_ctl_sub(struct uaudio_softc *sc, struct uaudio_mixer_node *mc)
1627 {
1628 	struct uaudio_mixer_node *p_mc_new =
1629 	    malloc(sizeof(*p_mc_new), M_USBDEV, M_WAITOK);
1630 
1631 	if (p_mc_new != NULL) {
1632 		memcpy(p_mc_new, mc, sizeof(*p_mc_new));
1633 		p_mc_new->next = sc->sc_mixer_root;
1634 		sc->sc_mixer_root = p_mc_new;
1635 		sc->sc_mixer_count++;
1636 	} else {
1637 		DPRINTF("out of memory\n");
1638 	}
1639 }
1640 
1641 static void
1642 uaudio_mixer_add_ctl(struct uaudio_softc *sc, struct uaudio_mixer_node *mc)
1643 {
1644 	int32_t res;
1645 
1646 	if (mc->class < UAC_NCLASSES) {
1647 		DPRINTF("adding %s.%d\n",
1648 		    uac_names[mc->class], mc->ctl);
1649 	} else {
1650 		DPRINTF("adding %d\n", mc->ctl);
1651 	}
1652 
1653 	if (mc->type == MIX_ON_OFF) {
1654 		mc->minval = 0;
1655 		mc->maxval = 1;
1656 	} else if (mc->type == MIX_SELECTOR) {
1657 	} else {
1658 
1659 		/* determine min and max values */
1660 
1661 		mc->minval = uaudio_mixer_get(sc->sc_udev, GET_MIN, mc);
1662 
1663 		mc->minval = uaudio_mixer_signext(mc->type, mc->minval);
1664 
1665 		mc->maxval = uaudio_mixer_get(sc->sc_udev, GET_MAX, mc);
1666 
1667 		mc->maxval = uaudio_mixer_signext(mc->type, mc->maxval);
1668 
1669 		/* check if max and min was swapped */
1670 
1671 		if (mc->maxval < mc->minval) {
1672 			res = mc->maxval;
1673 			mc->maxval = mc->minval;
1674 			mc->minval = res;
1675 		}
1676 
1677 		/* compute value range */
1678 		mc->mul = mc->maxval - mc->minval;
1679 		if (mc->mul == 0)
1680 			mc->mul = 1;
1681 
1682 		/* compute value alignment */
1683 		res = uaudio_mixer_get(sc->sc_udev, GET_RES, mc);
1684 
1685 		DPRINTF("Resolution = %d\n", (int)res);
1686 	}
1687 
1688 	uaudio_mixer_add_ctl_sub(sc, mc);
1689 
1690 #ifdef USB_DEBUG
1691 	if (uaudio_debug > 2) {
1692 		uint8_t i;
1693 
1694 		for (i = 0; i < mc->nchan; i++) {
1695 			DPRINTF("[mix] wValue=%04x\n", mc->wValue[0]);
1696 		}
1697 		DPRINTF("[mix] wIndex=%04x type=%d ctl='%d' "
1698 		    "min=%d max=%d\n",
1699 		    mc->wIndex, mc->type, mc->ctl,
1700 		    mc->minval, mc->maxval);
1701 	}
1702 #endif
1703 }
1704 
1705 static void
1706 uaudio_mixer_add_input(struct uaudio_softc *sc,
1707     const struct uaudio_terminal_node *iot, int id)
1708 {
1709 #ifdef USB_DEBUG
1710 	const struct usb_audio_input_terminal *d = iot[id].u.it;
1711 
1712 	DPRINTFN(3, "bTerminalId=%d wTerminalType=0x%04x "
1713 	    "bAssocTerminal=%d bNrChannels=%d wChannelConfig=%d "
1714 	    "iChannelNames=%d\n",
1715 	    d->bTerminalId, UGETW(d->wTerminalType), d->bAssocTerminal,
1716 	    d->bNrChannels, UGETW(d->wChannelConfig),
1717 	    d->iChannelNames);
1718 #endif
1719 }
1720 
1721 static void
1722 uaudio_mixer_add_output(struct uaudio_softc *sc,
1723     const struct uaudio_terminal_node *iot, int id)
1724 {
1725 #ifdef USB_DEBUG
1726 	const struct usb_audio_output_terminal *d = iot[id].u.ot;
1727 
1728 	DPRINTFN(3, "bTerminalId=%d wTerminalType=0x%04x "
1729 	    "bAssocTerminal=%d bSourceId=%d iTerminal=%d\n",
1730 	    d->bTerminalId, UGETW(d->wTerminalType), d->bAssocTerminal,
1731 	    d->bSourceId, d->iTerminal);
1732 #endif
1733 }
1734 
1735 static void
1736 uaudio_mixer_add_mixer(struct uaudio_softc *sc,
1737     const struct uaudio_terminal_node *iot, int id)
1738 {
1739 	struct uaudio_mixer_node mix;
1740 
1741 	const struct usb_audio_mixer_unit_0 *d0 = iot[id].u.mu;
1742 	const struct usb_audio_mixer_unit_1 *d1;
1743 
1744 	uint32_t bno;			/* bit number */
1745 	uint32_t p;			/* bit number accumulator */
1746 	uint32_t mo;			/* matching outputs */
1747 	uint32_t mc;			/* matching channels */
1748 	uint32_t ichs;			/* input channels */
1749 	uint32_t ochs;			/* output channels */
1750 	uint32_t c;
1751 	uint32_t chs;			/* channels */
1752 	uint32_t i;
1753 	uint32_t o;
1754 
1755 	DPRINTFN(3, "bUnitId=%d bNrInPins=%d\n",
1756 	    d0->bUnitId, d0->bNrInPins);
1757 
1758 	/* compute the number of input channels */
1759 
1760 	ichs = 0;
1761 	for (i = 0; i < d0->bNrInPins; i++) {
1762 		ichs += (uaudio_mixer_get_cluster(d0->baSourceId[i], iot)
1763 		    .bNrChannels);
1764 	}
1765 
1766 	d1 = (const void *)(d0->baSourceId + d0->bNrInPins);
1767 
1768 	/* and the number of output channels */
1769 
1770 	ochs = d1->bNrChannels;
1771 
1772 	DPRINTFN(3, "ichs=%d ochs=%d\n", ichs, ochs);
1773 
1774 	memset(&mix, 0, sizeof(mix));
1775 
1776 	mix.wIndex = MAKE_WORD(d0->bUnitId, sc->sc_mixer_iface_no);
1777 	uaudio_mixer_determine_class(&iot[id], &mix);
1778 	mix.type = MIX_SIGNED_16;
1779 
1780 	if (uaudio_mixer_verify_desc(d0, ((ichs * ochs) + 7) / 8) == NULL) {
1781 		return;
1782 	}
1783 	for (p = i = 0; i < d0->bNrInPins; i++) {
1784 		chs = uaudio_mixer_get_cluster(d0->baSourceId[i], iot).bNrChannels;
1785 		mc = 0;
1786 		for (c = 0; c < chs; c++) {
1787 			mo = 0;
1788 			for (o = 0; o < ochs; o++) {
1789 				bno = ((p + c) * ochs) + o;
1790 				if (BIT_TEST(d1->bmControls, bno)) {
1791 					mo++;
1792 				}
1793 			}
1794 			if (mo == 1) {
1795 				mc++;
1796 			}
1797 		}
1798 		if ((mc == chs) && (chs <= MIX_MAX_CHAN)) {
1799 
1800 			/* repeat bit-scan */
1801 
1802 			mc = 0;
1803 			for (c = 0; c < chs; c++) {
1804 				for (o = 0; o < ochs; o++) {
1805 					bno = ((p + c) * ochs) + o;
1806 					if (BIT_TEST(d1->bmControls, bno)) {
1807 						mix.wValue[mc++] = MAKE_WORD(p + c + 1, o + 1);
1808 					}
1809 				}
1810 			}
1811 			mix.nchan = chs;
1812 			uaudio_mixer_add_ctl(sc, &mix);
1813 		} else {
1814 			/* XXX */
1815 		}
1816 		p += chs;
1817 	}
1818 }
1819 
1820 static void
1821 uaudio_mixer_add_selector(struct uaudio_softc *sc,
1822     const struct uaudio_terminal_node *iot, int id)
1823 {
1824 	const struct usb_audio_selector_unit *d = iot[id].u.su;
1825 	struct uaudio_mixer_node mix;
1826 	uint16_t i;
1827 
1828 	DPRINTFN(3, "bUnitId=%d bNrInPins=%d\n",
1829 	    d->bUnitId, d->bNrInPins);
1830 
1831 	if (d->bNrInPins == 0) {
1832 		return;
1833 	}
1834 	memset(&mix, 0, sizeof(mix));
1835 
1836 	mix.wIndex = MAKE_WORD(d->bUnitId, sc->sc_mixer_iface_no);
1837 	mix.wValue[0] = MAKE_WORD(0, 0);
1838 	uaudio_mixer_determine_class(&iot[id], &mix);
1839 	mix.nchan = 1;
1840 	mix.type = MIX_SELECTOR;
1841 
1842 	mix.ctl = SOUND_MIXER_NRDEVICES;
1843 	mix.minval = 1;
1844 	mix.maxval = d->bNrInPins;
1845 
1846 	if (mix.maxval > MAX_SELECTOR_INPUT_PIN) {
1847 		mix.maxval = MAX_SELECTOR_INPUT_PIN;
1848 	}
1849 	mix.mul = (mix.maxval - mix.minval);
1850 	for (i = 0; i < MAX_SELECTOR_INPUT_PIN; i++) {
1851 		mix.slctrtype[i] = SOUND_MIXER_NRDEVICES;
1852 	}
1853 
1854 	for (i = 0; i < mix.maxval; i++) {
1855 		mix.slctrtype[i] = uaudio_mixer_feature_name
1856 		    (&iot[d->baSourceId[i]], &mix);
1857 	}
1858 
1859 	mix.class = 0;			/* not used */
1860 
1861 	uaudio_mixer_add_ctl(sc, &mix);
1862 }
1863 
1864 static uint32_t
1865 uaudio_mixer_feature_get_bmaControls(const struct usb_audio_feature_unit *d,
1866     uint8_t index)
1867 {
1868 	uint32_t temp = 0;
1869 	uint32_t offset = (index * d->bControlSize);
1870 
1871 	if (d->bControlSize > 0) {
1872 		temp |= d->bmaControls[offset];
1873 		if (d->bControlSize > 1) {
1874 			temp |= d->bmaControls[offset + 1] << 8;
1875 			if (d->bControlSize > 2) {
1876 				temp |= d->bmaControls[offset + 2] << 16;
1877 				if (d->bControlSize > 3) {
1878 					temp |= d->bmaControls[offset + 3] << 24;
1879 				}
1880 			}
1881 		}
1882 	}
1883 	return (temp);
1884 }
1885 
1886 static void
1887 uaudio_mixer_add_feature(struct uaudio_softc *sc,
1888     const struct uaudio_terminal_node *iot, int id)
1889 {
1890 	const struct usb_audio_feature_unit *d = iot[id].u.fu;
1891 	struct uaudio_mixer_node mix;
1892 	uint32_t fumask;
1893 	uint32_t mmask;
1894 	uint32_t cmask;
1895 	uint16_t mixernumber;
1896 	uint8_t nchan;
1897 	uint8_t chan;
1898 	uint8_t ctl;
1899 	uint8_t i;
1900 
1901 	if (d->bControlSize == 0) {
1902 		return;
1903 	}
1904 	memset(&mix, 0, sizeof(mix));
1905 
1906 	nchan = (d->bLength - 7) / d->bControlSize;
1907 	mmask = uaudio_mixer_feature_get_bmaControls(d, 0);
1908 	cmask = 0;
1909 
1910 	if (nchan == 0) {
1911 		return;
1912 	}
1913 	/* figure out what we can control */
1914 
1915 	for (chan = 1; chan < nchan; chan++) {
1916 		DPRINTFN(10, "chan=%d mask=%x\n",
1917 		    chan, uaudio_mixer_feature_get_bmaControls(d, chan));
1918 
1919 		cmask |= uaudio_mixer_feature_get_bmaControls(d, chan);
1920 	}
1921 
1922 	if (nchan > MIX_MAX_CHAN) {
1923 		nchan = MIX_MAX_CHAN;
1924 	}
1925 	mix.wIndex = MAKE_WORD(d->bUnitId, sc->sc_mixer_iface_no);
1926 
1927 	for (ctl = 1; ctl <= LOUDNESS_CONTROL; ctl++) {
1928 
1929 		fumask = FU_MASK(ctl);
1930 
1931 		DPRINTFN(5, "ctl=%d fumask=0x%04x\n",
1932 		    ctl, fumask);
1933 
1934 		if (mmask & fumask) {
1935 			mix.nchan = 1;
1936 			mix.wValue[0] = MAKE_WORD(ctl, 0);
1937 		} else if (cmask & fumask) {
1938 			mix.nchan = nchan - 1;
1939 			for (i = 1; i < nchan; i++) {
1940 				if (uaudio_mixer_feature_get_bmaControls(d, i) & fumask)
1941 					mix.wValue[i - 1] = MAKE_WORD(ctl, i);
1942 				else
1943 					mix.wValue[i - 1] = -1;
1944 			}
1945 		} else {
1946 			continue;
1947 		}
1948 
1949 		mixernumber = uaudio_mixer_feature_name(&iot[id], &mix);
1950 
1951 		switch (ctl) {
1952 		case MUTE_CONTROL:
1953 			mix.type = MIX_ON_OFF;
1954 			mix.ctl = SOUND_MIXER_NRDEVICES;
1955 			break;
1956 
1957 		case VOLUME_CONTROL:
1958 			mix.type = MIX_SIGNED_16;
1959 			mix.ctl = mixernumber;
1960 			break;
1961 
1962 		case BASS_CONTROL:
1963 			mix.type = MIX_SIGNED_8;
1964 			mix.ctl = SOUND_MIXER_BASS;
1965 			break;
1966 
1967 		case MID_CONTROL:
1968 			mix.type = MIX_SIGNED_8;
1969 			mix.ctl = SOUND_MIXER_NRDEVICES;	/* XXXXX */
1970 			break;
1971 
1972 		case TREBLE_CONTROL:
1973 			mix.type = MIX_SIGNED_8;
1974 			mix.ctl = SOUND_MIXER_TREBLE;
1975 			break;
1976 
1977 		case GRAPHIC_EQUALIZER_CONTROL:
1978 			continue;	/* XXX don't add anything */
1979 			break;
1980 
1981 		case AGC_CONTROL:
1982 			mix.type = MIX_ON_OFF;
1983 			mix.ctl = SOUND_MIXER_NRDEVICES;	/* XXXXX */
1984 			break;
1985 
1986 		case DELAY_CONTROL:
1987 			mix.type = MIX_UNSIGNED_16;
1988 			mix.ctl = SOUND_MIXER_NRDEVICES;	/* XXXXX */
1989 			break;
1990 
1991 		case BASS_BOOST_CONTROL:
1992 			mix.type = MIX_ON_OFF;
1993 			mix.ctl = SOUND_MIXER_NRDEVICES;	/* XXXXX */
1994 			break;
1995 
1996 		case LOUDNESS_CONTROL:
1997 			mix.type = MIX_ON_OFF;
1998 			mix.ctl = SOUND_MIXER_LOUD;	/* Is this correct ? */
1999 			break;
2000 
2001 		default:
2002 			mix.type = MIX_UNKNOWN;
2003 			break;
2004 		}
2005 
2006 		if (mix.type != MIX_UNKNOWN) {
2007 			uaudio_mixer_add_ctl(sc, &mix);
2008 		}
2009 	}
2010 }
2011 
2012 static void
2013 uaudio_mixer_add_processing_updown(struct uaudio_softc *sc,
2014     const struct uaudio_terminal_node *iot, int id)
2015 {
2016 	const struct usb_audio_processing_unit_0 *d0 = iot[id].u.pu;
2017 	const struct usb_audio_processing_unit_1 *d1 =
2018 	(const void *)(d0->baSourceId + d0->bNrInPins);
2019 	const struct usb_audio_processing_unit_updown *ud =
2020 	(const void *)(d1->bmControls + d1->bControlSize);
2021 	struct uaudio_mixer_node mix;
2022 	uint8_t i;
2023 
2024 	if (uaudio_mixer_verify_desc(d0, sizeof(*ud)) == NULL) {
2025 		return;
2026 	}
2027 	if (uaudio_mixer_verify_desc(d0, sizeof(*ud) + (2 * ud->bNrModes))
2028 	    == NULL) {
2029 		return;
2030 	}
2031 	DPRINTFN(3, "bUnitId=%d bNrModes=%d\n",
2032 	    d0->bUnitId, ud->bNrModes);
2033 
2034 	if (!(d1->bmControls[0] & UA_PROC_MASK(UD_MODE_SELECT_CONTROL))) {
2035 		DPRINTF("no mode select\n");
2036 		return;
2037 	}
2038 	memset(&mix, 0, sizeof(mix));
2039 
2040 	mix.wIndex = MAKE_WORD(d0->bUnitId, sc->sc_mixer_iface_no);
2041 	mix.nchan = 1;
2042 	mix.wValue[0] = MAKE_WORD(UD_MODE_SELECT_CONTROL, 0);
2043 	uaudio_mixer_determine_class(&iot[id], &mix);
2044 	mix.type = MIX_ON_OFF;		/* XXX */
2045 
2046 	for (i = 0; i < ud->bNrModes; i++) {
2047 		DPRINTFN(3, "i=%d bm=0x%x\n", i, UGETW(ud->waModes[i]));
2048 		/* XXX */
2049 	}
2050 
2051 	uaudio_mixer_add_ctl(sc, &mix);
2052 }
2053 
2054 static void
2055 uaudio_mixer_add_processing(struct uaudio_softc *sc,
2056     const struct uaudio_terminal_node *iot, int id)
2057 {
2058 	const struct usb_audio_processing_unit_0 *d0 = iot[id].u.pu;
2059 	const struct usb_audio_processing_unit_1 *d1 =
2060 	(const void *)(d0->baSourceId + d0->bNrInPins);
2061 	struct uaudio_mixer_node mix;
2062 	uint16_t ptype;
2063 
2064 	memset(&mix, 0, sizeof(mix));
2065 
2066 	ptype = UGETW(d0->wProcessType);
2067 
2068 	DPRINTFN(3, "wProcessType=%d bUnitId=%d "
2069 	    "bNrInPins=%d\n", ptype, d0->bUnitId, d0->bNrInPins);
2070 
2071 	if (d1->bControlSize == 0) {
2072 		return;
2073 	}
2074 	if (d1->bmControls[0] & UA_PROC_ENABLE_MASK) {
2075 		mix.wIndex = MAKE_WORD(d0->bUnitId, sc->sc_mixer_iface_no);
2076 		mix.nchan = 1;
2077 		mix.wValue[0] = MAKE_WORD(XX_ENABLE_CONTROL, 0);
2078 		uaudio_mixer_determine_class(&iot[id], &mix);
2079 		mix.type = MIX_ON_OFF;
2080 		uaudio_mixer_add_ctl(sc, &mix);
2081 	}
2082 	switch (ptype) {
2083 	case UPDOWNMIX_PROCESS:
2084 		uaudio_mixer_add_processing_updown(sc, iot, id);
2085 		break;
2086 
2087 	case DOLBY_PROLOGIC_PROCESS:
2088 	case P3D_STEREO_EXTENDER_PROCESS:
2089 	case REVERBATION_PROCESS:
2090 	case CHORUS_PROCESS:
2091 	case DYN_RANGE_COMP_PROCESS:
2092 	default:
2093 		DPRINTF("unit %d, type=%d is not implemented\n",
2094 		    d0->bUnitId, ptype);
2095 		break;
2096 	}
2097 }
2098 
2099 static void
2100 uaudio_mixer_add_extension(struct uaudio_softc *sc,
2101     const struct uaudio_terminal_node *iot, int id)
2102 {
2103 	const struct usb_audio_extension_unit_0 *d0 = iot[id].u.eu;
2104 	const struct usb_audio_extension_unit_1 *d1 =
2105 	(const void *)(d0->baSourceId + d0->bNrInPins);
2106 	struct uaudio_mixer_node mix;
2107 
2108 	DPRINTFN(3, "bUnitId=%d bNrInPins=%d\n",
2109 	    d0->bUnitId, d0->bNrInPins);
2110 
2111 	if (sc->sc_uq_au_no_xu) {
2112 		return;
2113 	}
2114 	if (d1->bControlSize == 0) {
2115 		return;
2116 	}
2117 	if (d1->bmControls[0] & UA_EXT_ENABLE_MASK) {
2118 
2119 		memset(&mix, 0, sizeof(mix));
2120 
2121 		mix.wIndex = MAKE_WORD(d0->bUnitId, sc->sc_mixer_iface_no);
2122 		mix.nchan = 1;
2123 		mix.wValue[0] = MAKE_WORD(UA_EXT_ENABLE, 0);
2124 		uaudio_mixer_determine_class(&iot[id], &mix);
2125 		mix.type = MIX_ON_OFF;
2126 
2127 		uaudio_mixer_add_ctl(sc, &mix);
2128 	}
2129 }
2130 
2131 static const void *
2132 uaudio_mixer_verify_desc(const void *arg, uint32_t len)
2133 {
2134 	const struct usb_audio_mixer_unit_1 *d1;
2135 	const struct usb_audio_extension_unit_1 *e1;
2136 	const struct usb_audio_processing_unit_1 *u1;
2137 
2138 	union {
2139 		const struct usb_descriptor *desc;
2140 		const struct usb_audio_input_terminal *it;
2141 		const struct usb_audio_output_terminal *ot;
2142 		const struct usb_audio_mixer_unit_0 *mu;
2143 		const struct usb_audio_selector_unit *su;
2144 		const struct usb_audio_feature_unit *fu;
2145 		const struct usb_audio_processing_unit_0 *pu;
2146 		const struct usb_audio_extension_unit_0 *eu;
2147 	}     u;
2148 
2149 	u.desc = arg;
2150 
2151 	if (u.desc == NULL) {
2152 		goto error;
2153 	}
2154 	if (u.desc->bDescriptorType != UDESC_CS_INTERFACE) {
2155 		goto error;
2156 	}
2157 	switch (u.desc->bDescriptorSubtype) {
2158 	case UDESCSUB_AC_INPUT:
2159 		len += sizeof(*u.it);
2160 		break;
2161 
2162 	case UDESCSUB_AC_OUTPUT:
2163 		len += sizeof(*u.ot);
2164 		break;
2165 
2166 	case UDESCSUB_AC_MIXER:
2167 		len += sizeof(*u.mu);
2168 
2169 		if (u.desc->bLength < len) {
2170 			goto error;
2171 		}
2172 		len += u.mu->bNrInPins;
2173 
2174 		if (u.desc->bLength < len) {
2175 			goto error;
2176 		}
2177 		d1 = (const void *)(u.mu->baSourceId + u.mu->bNrInPins);
2178 
2179 		len += sizeof(*d1);
2180 		break;
2181 
2182 	case UDESCSUB_AC_SELECTOR:
2183 		len += sizeof(*u.su);
2184 
2185 		if (u.desc->bLength < len) {
2186 			goto error;
2187 		}
2188 		len += u.su->bNrInPins;
2189 		break;
2190 
2191 	case UDESCSUB_AC_FEATURE:
2192 		len += (sizeof(*u.fu) + 1);
2193 		break;
2194 
2195 	case UDESCSUB_AC_PROCESSING:
2196 		len += sizeof(*u.pu);
2197 
2198 		if (u.desc->bLength < len) {
2199 			goto error;
2200 		}
2201 		len += u.pu->bNrInPins;
2202 
2203 		if (u.desc->bLength < len) {
2204 			goto error;
2205 		}
2206 		u1 = (const void *)(u.pu->baSourceId + u.pu->bNrInPins);
2207 
2208 		len += sizeof(*u1);
2209 
2210 		if (u.desc->bLength < len) {
2211 			goto error;
2212 		}
2213 		len += u1->bControlSize;
2214 
2215 		break;
2216 
2217 	case UDESCSUB_AC_EXTENSION:
2218 		len += sizeof(*u.eu);
2219 
2220 		if (u.desc->bLength < len) {
2221 			goto error;
2222 		}
2223 		len += u.eu->bNrInPins;
2224 
2225 		if (u.desc->bLength < len) {
2226 			goto error;
2227 		}
2228 		e1 = (const void *)(u.eu->baSourceId + u.eu->bNrInPins);
2229 
2230 		len += sizeof(*e1);
2231 
2232 		if (u.desc->bLength < len) {
2233 			goto error;
2234 		}
2235 		len += e1->bControlSize;
2236 		break;
2237 
2238 	default:
2239 		goto error;
2240 	}
2241 
2242 	if (u.desc->bLength < len) {
2243 		goto error;
2244 	}
2245 	return (u.desc);
2246 
2247 error:
2248 	if (u.desc) {
2249 		DPRINTF("invalid descriptor, type=%d, "
2250 		    "sub_type=%d, len=%d of %d bytes\n",
2251 		    u.desc->bDescriptorType,
2252 		    u.desc->bDescriptorSubtype,
2253 		    u.desc->bLength, len);
2254 	}
2255 	return (NULL);
2256 }
2257 
2258 #ifdef USB_DEBUG
2259 static void
2260 uaudio_mixer_dump_cluster(uint8_t id, const struct uaudio_terminal_node *iot)
2261 {
2262 	static const char *channel_names[16] = {
2263 		"LEFT", "RIGHT", "CENTER", "LFE",
2264 		"LEFT_SURROUND", "RIGHT_SURROUND", "LEFT_CENTER", "RIGHT_CENTER",
2265 		"SURROUND", "LEFT_SIDE", "RIGHT_SIDE", "TOP",
2266 		"RESERVED12", "RESERVED13", "RESERVED14", "RESERVED15",
2267 	};
2268 	uint16_t cc;
2269 	uint8_t i;
2270 	const struct usb_audio_cluster cl = uaudio_mixer_get_cluster(id, iot);
2271 
2272 	cc = UGETW(cl.wChannelConfig);
2273 
2274 	DPRINTF("cluster: bNrChannels=%u iChannelNames=%u wChannelConfig="
2275 	    "0x%04x:\n", cl.iChannelNames, cl.bNrChannels, cc);
2276 
2277 	for (i = 0; cc; i++) {
2278 		if (cc & 1) {
2279 			DPRINTF(" - %s\n", channel_names[i]);
2280 		}
2281 		cc >>= 1;
2282 	}
2283 }
2284 
2285 #endif
2286 
2287 static struct usb_audio_cluster
2288 uaudio_mixer_get_cluster(uint8_t id, const struct uaudio_terminal_node *iot)
2289 {
2290 	struct usb_audio_cluster r;
2291 	const struct usb_descriptor *dp;
2292 	uint8_t i;
2293 
2294 	for (i = 0; i < UAUDIO_RECURSE_LIMIT; i++) {	/* avoid infinite loops */
2295 		dp = iot[id].u.desc;
2296 		if (dp == NULL) {
2297 			goto error;
2298 		}
2299 		switch (dp->bDescriptorSubtype) {
2300 		case UDESCSUB_AC_INPUT:
2301 			r.bNrChannels = iot[id].u.it->bNrChannels;
2302 			r.wChannelConfig[0] = iot[id].u.it->wChannelConfig[0];
2303 			r.wChannelConfig[1] = iot[id].u.it->wChannelConfig[1];
2304 			r.iChannelNames = iot[id].u.it->iChannelNames;
2305 			goto done;
2306 
2307 		case UDESCSUB_AC_OUTPUT:
2308 			id = iot[id].u.ot->bSourceId;
2309 			break;
2310 
2311 		case UDESCSUB_AC_MIXER:
2312 			r = *(const struct usb_audio_cluster *)
2313 			    &iot[id].u.mu->baSourceId[iot[id].u.mu->
2314 			    bNrInPins];
2315 			goto done;
2316 
2317 		case UDESCSUB_AC_SELECTOR:
2318 			if (iot[id].u.su->bNrInPins > 0) {
2319 				/* XXX This is not really right */
2320 				id = iot[id].u.su->baSourceId[0];
2321 			}
2322 			break;
2323 
2324 		case UDESCSUB_AC_FEATURE:
2325 			id = iot[id].u.fu->bSourceId;
2326 			break;
2327 
2328 		case UDESCSUB_AC_PROCESSING:
2329 			r = *((const struct usb_audio_cluster *)
2330 			    &iot[id].u.pu->baSourceId[iot[id].u.pu->
2331 			    bNrInPins]);
2332 			goto done;
2333 
2334 		case UDESCSUB_AC_EXTENSION:
2335 			r = *((const struct usb_audio_cluster *)
2336 			    &iot[id].u.eu->baSourceId[iot[id].u.eu->
2337 			    bNrInPins]);
2338 			goto done;
2339 
2340 		default:
2341 			goto error;
2342 		}
2343 	}
2344 error:
2345 	DPRINTF("bad data\n");
2346 	memset(&r, 0, sizeof(r));
2347 done:
2348 	return (r);
2349 }
2350 
2351 #ifdef USB_DEBUG
2352 
2353 struct uaudio_tt_to_string {
2354 	uint16_t terminal_type;
2355 	const char *desc;
2356 };
2357 
2358 static const struct uaudio_tt_to_string uaudio_tt_to_string[] = {
2359 
2360 	/* USB terminal types */
2361 	{UAT_UNDEFINED, "UAT_UNDEFINED"},
2362 	{UAT_STREAM, "UAT_STREAM"},
2363 	{UAT_VENDOR, "UAT_VENDOR"},
2364 
2365 	/* input terminal types */
2366 	{UATI_UNDEFINED, "UATI_UNDEFINED"},
2367 	{UATI_MICROPHONE, "UATI_MICROPHONE"},
2368 	{UATI_DESKMICROPHONE, "UATI_DESKMICROPHONE"},
2369 	{UATI_PERSONALMICROPHONE, "UATI_PERSONALMICROPHONE"},
2370 	{UATI_OMNIMICROPHONE, "UATI_OMNIMICROPHONE"},
2371 	{UATI_MICROPHONEARRAY, "UATI_MICROPHONEARRAY"},
2372 	{UATI_PROCMICROPHONEARR, "UATI_PROCMICROPHONEARR"},
2373 
2374 	/* output terminal types */
2375 	{UATO_UNDEFINED, "UATO_UNDEFINED"},
2376 	{UATO_SPEAKER, "UATO_SPEAKER"},
2377 	{UATO_HEADPHONES, "UATO_HEADPHONES"},
2378 	{UATO_DISPLAYAUDIO, "UATO_DISPLAYAUDIO"},
2379 	{UATO_DESKTOPSPEAKER, "UATO_DESKTOPSPEAKER"},
2380 	{UATO_ROOMSPEAKER, "UATO_ROOMSPEAKER"},
2381 	{UATO_COMMSPEAKER, "UATO_COMMSPEAKER"},
2382 	{UATO_SUBWOOFER, "UATO_SUBWOOFER"},
2383 
2384 	/* bidir terminal types */
2385 	{UATB_UNDEFINED, "UATB_UNDEFINED"},
2386 	{UATB_HANDSET, "UATB_HANDSET"},
2387 	{UATB_HEADSET, "UATB_HEADSET"},
2388 	{UATB_SPEAKERPHONE, "UATB_SPEAKERPHONE"},
2389 	{UATB_SPEAKERPHONEESUP, "UATB_SPEAKERPHONEESUP"},
2390 	{UATB_SPEAKERPHONEECANC, "UATB_SPEAKERPHONEECANC"},
2391 
2392 	/* telephony terminal types */
2393 	{UATT_UNDEFINED, "UATT_UNDEFINED"},
2394 	{UATT_PHONELINE, "UATT_PHONELINE"},
2395 	{UATT_TELEPHONE, "UATT_TELEPHONE"},
2396 	{UATT_DOWNLINEPHONE, "UATT_DOWNLINEPHONE"},
2397 
2398 	/* external terminal types */
2399 	{UATE_UNDEFINED, "UATE_UNDEFINED"},
2400 	{UATE_ANALOGCONN, "UATE_ANALOGCONN"},
2401 	{UATE_LINECONN, "UATE_LINECONN"},
2402 	{UATE_LEGACYCONN, "UATE_LEGACYCONN"},
2403 	{UATE_DIGITALAUIFC, "UATE_DIGITALAUIFC"},
2404 	{UATE_SPDIF, "UATE_SPDIF"},
2405 	{UATE_1394DA, "UATE_1394DA"},
2406 	{UATE_1394DV, "UATE_1394DV"},
2407 
2408 	/* embedded function terminal types */
2409 	{UATF_UNDEFINED, "UATF_UNDEFINED"},
2410 	{UATF_CALIBNOISE, "UATF_CALIBNOISE"},
2411 	{UATF_EQUNOISE, "UATF_EQUNOISE"},
2412 	{UATF_CDPLAYER, "UATF_CDPLAYER"},
2413 	{UATF_DAT, "UATF_DAT"},
2414 	{UATF_DCC, "UATF_DCC"},
2415 	{UATF_MINIDISK, "UATF_MINIDISK"},
2416 	{UATF_ANALOGTAPE, "UATF_ANALOGTAPE"},
2417 	{UATF_PHONOGRAPH, "UATF_PHONOGRAPH"},
2418 	{UATF_VCRAUDIO, "UATF_VCRAUDIO"},
2419 	{UATF_VIDEODISCAUDIO, "UATF_VIDEODISCAUDIO"},
2420 	{UATF_DVDAUDIO, "UATF_DVDAUDIO"},
2421 	{UATF_TVTUNERAUDIO, "UATF_TVTUNERAUDIO"},
2422 	{UATF_SATELLITE, "UATF_SATELLITE"},
2423 	{UATF_CABLETUNER, "UATF_CABLETUNER"},
2424 	{UATF_DSS, "UATF_DSS"},
2425 	{UATF_RADIORECV, "UATF_RADIORECV"},
2426 	{UATF_RADIOXMIT, "UATF_RADIOXMIT"},
2427 	{UATF_MULTITRACK, "UATF_MULTITRACK"},
2428 	{UATF_SYNTHESIZER, "UATF_SYNTHESIZER"},
2429 
2430 	/* unknown */
2431 	{0x0000, "UNKNOWN"},
2432 };
2433 
2434 static const char *
2435 uaudio_mixer_get_terminal_name(uint16_t terminal_type)
2436 {
2437 	const struct uaudio_tt_to_string *uat = uaudio_tt_to_string;
2438 
2439 	while (uat->terminal_type) {
2440 		if (uat->terminal_type == terminal_type) {
2441 			break;
2442 		}
2443 		uat++;
2444 	}
2445 	if (uat->terminal_type == 0) {
2446 		DPRINTF("unknown terminal type (0x%04x)", terminal_type);
2447 	}
2448 	return (uat->desc);
2449 }
2450 
2451 #endif
2452 
2453 static uint16_t
2454 uaudio_mixer_determine_class(const struct uaudio_terminal_node *iot,
2455     struct uaudio_mixer_node *mix)
2456 {
2457 	uint16_t terminal_type = 0x0000;
2458 	const struct uaudio_terminal_node *input[2];
2459 	const struct uaudio_terminal_node *output[2];
2460 
2461 	input[0] = uaudio_mixer_get_input(iot, 0);
2462 	input[1] = uaudio_mixer_get_input(iot, 1);
2463 
2464 	output[0] = uaudio_mixer_get_output(iot, 0);
2465 	output[1] = uaudio_mixer_get_output(iot, 1);
2466 
2467 	/*
2468 	 * check if there is only
2469 	 * one output terminal:
2470 	 */
2471 	if (output[0] && (!output[1])) {
2472 		terminal_type = UGETW(output[0]->u.ot->wTerminalType);
2473 	}
2474 	/*
2475 	 * If the only output terminal is USB,
2476 	 * the class is UAC_RECORD.
2477 	 */
2478 	if ((terminal_type & 0xff00) == (UAT_UNDEFINED & 0xff00)) {
2479 
2480 		mix->class = UAC_RECORD;
2481 		if (input[0] && (!input[1])) {
2482 			terminal_type = UGETW(input[0]->u.it->wTerminalType);
2483 		} else {
2484 			terminal_type = 0;
2485 		}
2486 		goto done;
2487 	}
2488 	/*
2489 	 * if the unit is connected to just
2490 	 * one input terminal, the
2491 	 * class is UAC_INPUT:
2492 	 */
2493 	if (input[0] && (!input[1])) {
2494 		mix->class = UAC_INPUT;
2495 		terminal_type = UGETW(input[0]->u.it->wTerminalType);
2496 		goto done;
2497 	}
2498 	/*
2499 	 * Otherwise, the class is UAC_OUTPUT.
2500 	 */
2501 	mix->class = UAC_OUTPUT;
2502 done:
2503 	return (terminal_type);
2504 }
2505 
2506 struct uaudio_tt_to_feature {
2507 	uint16_t terminal_type;
2508 	uint16_t feature;
2509 };
2510 
2511 static const struct uaudio_tt_to_feature uaudio_tt_to_feature[] = {
2512 
2513 	{UAT_STREAM, SOUND_MIXER_PCM},
2514 
2515 	{UATI_MICROPHONE, SOUND_MIXER_MIC},
2516 	{UATI_DESKMICROPHONE, SOUND_MIXER_MIC},
2517 	{UATI_PERSONALMICROPHONE, SOUND_MIXER_MIC},
2518 	{UATI_OMNIMICROPHONE, SOUND_MIXER_MIC},
2519 	{UATI_MICROPHONEARRAY, SOUND_MIXER_MIC},
2520 	{UATI_PROCMICROPHONEARR, SOUND_MIXER_MIC},
2521 
2522 	{UATO_SPEAKER, SOUND_MIXER_SPEAKER},
2523 	{UATO_DESKTOPSPEAKER, SOUND_MIXER_SPEAKER},
2524 	{UATO_ROOMSPEAKER, SOUND_MIXER_SPEAKER},
2525 	{UATO_COMMSPEAKER, SOUND_MIXER_SPEAKER},
2526 
2527 	{UATE_ANALOGCONN, SOUND_MIXER_LINE},
2528 	{UATE_LINECONN, SOUND_MIXER_LINE},
2529 	{UATE_LEGACYCONN, SOUND_MIXER_LINE},
2530 
2531 	{UATE_DIGITALAUIFC, SOUND_MIXER_ALTPCM},
2532 	{UATE_SPDIF, SOUND_MIXER_ALTPCM},
2533 	{UATE_1394DA, SOUND_MIXER_ALTPCM},
2534 	{UATE_1394DV, SOUND_MIXER_ALTPCM},
2535 
2536 	{UATF_CDPLAYER, SOUND_MIXER_CD},
2537 
2538 	{UATF_SYNTHESIZER, SOUND_MIXER_SYNTH},
2539 
2540 	{UATF_VIDEODISCAUDIO, SOUND_MIXER_VIDEO},
2541 	{UATF_DVDAUDIO, SOUND_MIXER_VIDEO},
2542 	{UATF_TVTUNERAUDIO, SOUND_MIXER_VIDEO},
2543 
2544 	/* telephony terminal types */
2545 	{UATT_UNDEFINED, SOUND_MIXER_PHONEIN},	/* SOUND_MIXER_PHONEOUT */
2546 	{UATT_PHONELINE, SOUND_MIXER_PHONEIN},	/* SOUND_MIXER_PHONEOUT */
2547 	{UATT_TELEPHONE, SOUND_MIXER_PHONEIN},	/* SOUND_MIXER_PHONEOUT */
2548 	{UATT_DOWNLINEPHONE, SOUND_MIXER_PHONEIN},	/* SOUND_MIXER_PHONEOUT */
2549 
2550 	{UATF_RADIORECV, SOUND_MIXER_RADIO},
2551 	{UATF_RADIOXMIT, SOUND_MIXER_RADIO},
2552 
2553 	{UAT_UNDEFINED, SOUND_MIXER_VOLUME},
2554 	{UAT_VENDOR, SOUND_MIXER_VOLUME},
2555 	{UATI_UNDEFINED, SOUND_MIXER_VOLUME},
2556 
2557 	/* output terminal types */
2558 	{UATO_UNDEFINED, SOUND_MIXER_VOLUME},
2559 	{UATO_DISPLAYAUDIO, SOUND_MIXER_VOLUME},
2560 	{UATO_SUBWOOFER, SOUND_MIXER_VOLUME},
2561 	{UATO_HEADPHONES, SOUND_MIXER_VOLUME},
2562 
2563 	/* bidir terminal types */
2564 	{UATB_UNDEFINED, SOUND_MIXER_VOLUME},
2565 	{UATB_HANDSET, SOUND_MIXER_VOLUME},
2566 	{UATB_HEADSET, SOUND_MIXER_VOLUME},
2567 	{UATB_SPEAKERPHONE, SOUND_MIXER_VOLUME},
2568 	{UATB_SPEAKERPHONEESUP, SOUND_MIXER_VOLUME},
2569 	{UATB_SPEAKERPHONEECANC, SOUND_MIXER_VOLUME},
2570 
2571 	/* external terminal types */
2572 	{UATE_UNDEFINED, SOUND_MIXER_VOLUME},
2573 
2574 	/* embedded function terminal types */
2575 	{UATF_UNDEFINED, SOUND_MIXER_VOLUME},
2576 	{UATF_CALIBNOISE, SOUND_MIXER_VOLUME},
2577 	{UATF_EQUNOISE, SOUND_MIXER_VOLUME},
2578 	{UATF_DAT, SOUND_MIXER_VOLUME},
2579 	{UATF_DCC, SOUND_MIXER_VOLUME},
2580 	{UATF_MINIDISK, SOUND_MIXER_VOLUME},
2581 	{UATF_ANALOGTAPE, SOUND_MIXER_VOLUME},
2582 	{UATF_PHONOGRAPH, SOUND_MIXER_VOLUME},
2583 	{UATF_VCRAUDIO, SOUND_MIXER_VOLUME},
2584 	{UATF_SATELLITE, SOUND_MIXER_VOLUME},
2585 	{UATF_CABLETUNER, SOUND_MIXER_VOLUME},
2586 	{UATF_DSS, SOUND_MIXER_VOLUME},
2587 	{UATF_MULTITRACK, SOUND_MIXER_VOLUME},
2588 	{0xffff, SOUND_MIXER_VOLUME},
2589 
2590 	/* default */
2591 	{0x0000, SOUND_MIXER_VOLUME},
2592 };
2593 
2594 static uint16_t
2595 uaudio_mixer_feature_name(const struct uaudio_terminal_node *iot,
2596     struct uaudio_mixer_node *mix)
2597 {
2598 	const struct uaudio_tt_to_feature *uat = uaudio_tt_to_feature;
2599 	uint16_t terminal_type = uaudio_mixer_determine_class(iot, mix);
2600 
2601 	if ((mix->class == UAC_RECORD) && (terminal_type == 0)) {
2602 		return (SOUND_MIXER_IMIX);
2603 	}
2604 	while (uat->terminal_type) {
2605 		if (uat->terminal_type == terminal_type) {
2606 			break;
2607 		}
2608 		uat++;
2609 	}
2610 
2611 	DPRINTF("terminal_type=%s (0x%04x) -> %d\n",
2612 	    uaudio_mixer_get_terminal_name(terminal_type),
2613 	    terminal_type, uat->feature);
2614 
2615 	return (uat->feature);
2616 }
2617 
2618 const static struct uaudio_terminal_node *
2619 uaudio_mixer_get_input(const struct uaudio_terminal_node *iot, uint8_t index)
2620 {
2621 	struct uaudio_terminal_node *root = iot->root;
2622 	uint8_t n;
2623 
2624 	n = iot->usr.id_max;
2625 	do {
2626 		if (iot->usr.bit_input[n / 8] & (1 << (n % 8))) {
2627 			if (!index--) {
2628 				return (root + n);
2629 			}
2630 		}
2631 	} while (n--);
2632 
2633 	return (NULL);
2634 }
2635 
2636 const static struct uaudio_terminal_node *
2637 uaudio_mixer_get_output(const struct uaudio_terminal_node *iot, uint8_t index)
2638 {
2639 	struct uaudio_terminal_node *root = iot->root;
2640 	uint8_t n;
2641 
2642 	n = iot->usr.id_max;
2643 	do {
2644 		if (iot->usr.bit_output[n / 8] & (1 << (n % 8))) {
2645 			if (!index--) {
2646 				return (root + n);
2647 			}
2648 		}
2649 	} while (n--);
2650 
2651 	return (NULL);
2652 }
2653 
2654 static void
2655 uaudio_mixer_find_inputs_sub(struct uaudio_terminal_node *root,
2656     const uint8_t *p_id, uint8_t n_id,
2657     struct uaudio_search_result *info)
2658 {
2659 	struct uaudio_terminal_node *iot;
2660 	uint8_t n;
2661 	uint8_t i;
2662 
2663 	if (info->recurse_level >= UAUDIO_RECURSE_LIMIT) {
2664 		return;
2665 	}
2666 	info->recurse_level++;
2667 
2668 	for (n = 0; n < n_id; n++) {
2669 
2670 		i = p_id[n];
2671 
2672 		if (info->bit_visited[i / 8] & (1 << (i % 8))) {
2673 			/* don't go into a circle */
2674 			DPRINTF("avoided going into a circle at id=%d!\n", i);
2675 			continue;
2676 		} else {
2677 			info->bit_visited[i / 8] |= (1 << (i % 8));
2678 		}
2679 
2680 		iot = (root + i);
2681 
2682 		if (iot->u.desc == NULL) {
2683 			continue;
2684 		}
2685 		switch (iot->u.desc->bDescriptorSubtype) {
2686 		case UDESCSUB_AC_INPUT:
2687 			info->bit_input[i / 8] |= (1 << (i % 8));
2688 			break;
2689 
2690 		case UDESCSUB_AC_FEATURE:
2691 			uaudio_mixer_find_inputs_sub
2692 			    (root, &iot->u.fu->bSourceId, 1, info);
2693 			break;
2694 
2695 		case UDESCSUB_AC_OUTPUT:
2696 			uaudio_mixer_find_inputs_sub
2697 			    (root, &iot->u.ot->bSourceId, 1, info);
2698 			break;
2699 
2700 		case UDESCSUB_AC_MIXER:
2701 			uaudio_mixer_find_inputs_sub
2702 			    (root, iot->u.mu->baSourceId,
2703 			    iot->u.mu->bNrInPins, info);
2704 			break;
2705 
2706 		case UDESCSUB_AC_SELECTOR:
2707 			uaudio_mixer_find_inputs_sub
2708 			    (root, iot->u.su->baSourceId,
2709 			    iot->u.su->bNrInPins, info);
2710 			break;
2711 
2712 		case UDESCSUB_AC_PROCESSING:
2713 			uaudio_mixer_find_inputs_sub
2714 			    (root, iot->u.pu->baSourceId,
2715 			    iot->u.pu->bNrInPins, info);
2716 			break;
2717 
2718 		case UDESCSUB_AC_EXTENSION:
2719 			uaudio_mixer_find_inputs_sub
2720 			    (root, iot->u.eu->baSourceId,
2721 			    iot->u.eu->bNrInPins, info);
2722 			break;
2723 
2724 		case UDESCSUB_AC_HEADER:
2725 		default:
2726 			break;
2727 		}
2728 	}
2729 	info->recurse_level--;
2730 }
2731 
2732 static void
2733 uaudio_mixer_find_outputs_sub(struct uaudio_terminal_node *root, uint8_t id,
2734     uint8_t n_id, struct uaudio_search_result *info)
2735 {
2736 	struct uaudio_terminal_node *iot = (root + id);
2737 	uint8_t j;
2738 
2739 	j = n_id;
2740 	do {
2741 		if ((j != id) && ((root + j)->u.desc) &&
2742 		    ((root + j)->u.desc->bDescriptorSubtype == UDESCSUB_AC_OUTPUT)) {
2743 
2744 			/*
2745 			 * "j" (output) <--- virtual wire <--- "id" (input)
2746 			 *
2747 			 * if "j" has "id" on the input, then "id" have "j" on
2748 			 * the output, because they are connected:
2749 			 */
2750 			if ((root + j)->usr.bit_input[id / 8] & (1 << (id % 8))) {
2751 				iot->usr.bit_output[j / 8] |= (1 << (j % 8));
2752 			}
2753 		}
2754 	} while (j--);
2755 }
2756 
2757 static void
2758 uaudio_mixer_fill_info(struct uaudio_softc *sc, struct usb_device *udev,
2759     void *desc)
2760 {
2761 	const struct usb_audio_control_descriptor *acdp;
2762 	struct usb_config_descriptor *cd = usbd_get_config_descriptor(udev);
2763 	const struct usb_descriptor *dp;
2764 	const struct usb_audio_unit *au;
2765 	struct uaudio_terminal_node *iot = NULL;
2766 	uint16_t wTotalLen;
2767 	uint8_t ID_max = 0;		/* inclusive */
2768 	uint8_t i;
2769 
2770 	desc = usb_desc_foreach(cd, desc);
2771 
2772 	if (desc == NULL) {
2773 		DPRINTF("no Audio Control header\n");
2774 		goto done;
2775 	}
2776 	acdp = desc;
2777 
2778 	if ((acdp->bLength < sizeof(*acdp)) ||
2779 	    (acdp->bDescriptorType != UDESC_CS_INTERFACE) ||
2780 	    (acdp->bDescriptorSubtype != UDESCSUB_AC_HEADER)) {
2781 		DPRINTF("invalid Audio Control header\n");
2782 		goto done;
2783 	}
2784 	/* "wTotalLen" is allowed to be corrupt */
2785 	wTotalLen = UGETW(acdp->wTotalLength) - acdp->bLength;
2786 
2787 	/* get USB audio revision */
2788 	sc->sc_audio_rev = UGETW(acdp->bcdADC);
2789 
2790 	DPRINTFN(3, "found AC header, vers=%03x, len=%d\n",
2791 	    sc->sc_audio_rev, wTotalLen);
2792 
2793 	if (sc->sc_audio_rev != UAUDIO_VERSION) {
2794 
2795 		if (sc->sc_uq_bad_adc) {
2796 
2797 		} else {
2798 			DPRINTF("invalid audio version\n");
2799 			goto done;
2800 		}
2801 	}
2802 	iot = malloc(sizeof(struct uaudio_terminal_node) * 256, M_TEMP,
2803 	    M_WAITOK | M_ZERO);
2804 
2805 	if (iot == NULL) {
2806 		DPRINTF("no memory!\n");
2807 		goto done;
2808 	}
2809 	while ((desc = usb_desc_foreach(cd, desc))) {
2810 
2811 		dp = desc;
2812 
2813 		if (dp->bLength > wTotalLen) {
2814 			break;
2815 		} else {
2816 			wTotalLen -= dp->bLength;
2817 		}
2818 
2819 		au = uaudio_mixer_verify_desc(dp, 0);
2820 
2821 		if (au) {
2822 			iot[au->bUnitId].u.desc = (const void *)au;
2823 			if (au->bUnitId > ID_max) {
2824 				ID_max = au->bUnitId;
2825 			}
2826 		}
2827 	}
2828 
2829 	DPRINTF("Maximum ID=%d\n", ID_max);
2830 
2831 	/*
2832 	 * determine sourcing inputs for
2833 	 * all nodes in the tree:
2834 	 */
2835 	i = ID_max;
2836 	do {
2837 		uaudio_mixer_find_inputs_sub(iot, &i, 1, &((iot + i)->usr));
2838 	} while (i--);
2839 
2840 	/*
2841 	 * determine outputs for
2842 	 * all nodes in the tree:
2843 	 */
2844 	i = ID_max;
2845 	do {
2846 		uaudio_mixer_find_outputs_sub(iot, i, ID_max, &((iot + i)->usr));
2847 	} while (i--);
2848 
2849 	/* set "id_max" and "root" */
2850 
2851 	i = ID_max;
2852 	do {
2853 		(iot + i)->usr.id_max = ID_max;
2854 		(iot + i)->root = iot;
2855 	} while (i--);
2856 
2857 #ifdef USB_DEBUG
2858 	i = ID_max;
2859 	do {
2860 		uint8_t j;
2861 
2862 		if (iot[i].u.desc == NULL) {
2863 			continue;
2864 		}
2865 		DPRINTF("id %d:\n", i);
2866 
2867 		switch (iot[i].u.desc->bDescriptorSubtype) {
2868 		case UDESCSUB_AC_INPUT:
2869 			DPRINTF(" - AC_INPUT type=%s\n",
2870 			    uaudio_mixer_get_terminal_name
2871 			    (UGETW(iot[i].u.it->wTerminalType)));
2872 			uaudio_mixer_dump_cluster(i, iot);
2873 			break;
2874 
2875 		case UDESCSUB_AC_OUTPUT:
2876 			DPRINTF(" - AC_OUTPUT type=%s "
2877 			    "src=%d\n", uaudio_mixer_get_terminal_name
2878 			    (UGETW(iot[i].u.ot->wTerminalType)),
2879 			    iot[i].u.ot->bSourceId);
2880 			break;
2881 
2882 		case UDESCSUB_AC_MIXER:
2883 			DPRINTF(" - AC_MIXER src:\n");
2884 			for (j = 0; j < iot[i].u.mu->bNrInPins; j++) {
2885 				DPRINTF("   - %d\n", iot[i].u.mu->baSourceId[j]);
2886 			}
2887 			uaudio_mixer_dump_cluster(i, iot);
2888 			break;
2889 
2890 		case UDESCSUB_AC_SELECTOR:
2891 			DPRINTF(" - AC_SELECTOR src:\n");
2892 			for (j = 0; j < iot[i].u.su->bNrInPins; j++) {
2893 				DPRINTF("   - %d\n", iot[i].u.su->baSourceId[j]);
2894 			}
2895 			break;
2896 
2897 		case UDESCSUB_AC_FEATURE:
2898 			DPRINTF(" - AC_FEATURE src=%d\n", iot[i].u.fu->bSourceId);
2899 			break;
2900 
2901 		case UDESCSUB_AC_PROCESSING:
2902 			DPRINTF(" - AC_PROCESSING src:\n");
2903 			for (j = 0; j < iot[i].u.pu->bNrInPins; j++) {
2904 				DPRINTF("   - %d\n", iot[i].u.pu->baSourceId[j]);
2905 			}
2906 			uaudio_mixer_dump_cluster(i, iot);
2907 			break;
2908 
2909 		case UDESCSUB_AC_EXTENSION:
2910 			DPRINTF(" - AC_EXTENSION src:\n");
2911 			for (j = 0; j < iot[i].u.eu->bNrInPins; j++) {
2912 				DPRINTF("%d ", iot[i].u.eu->baSourceId[j]);
2913 			}
2914 			uaudio_mixer_dump_cluster(i, iot);
2915 			break;
2916 
2917 		default:
2918 			DPRINTF("unknown audio control (subtype=%d)\n",
2919 			    iot[i].u.desc->bDescriptorSubtype);
2920 		}
2921 
2922 		DPRINTF("Inputs to this ID are:\n");
2923 
2924 		j = ID_max;
2925 		do {
2926 			if (iot[i].usr.bit_input[j / 8] & (1 << (j % 8))) {
2927 				DPRINTF("  -- ID=%d\n", j);
2928 			}
2929 		} while (j--);
2930 
2931 		DPRINTF("Outputs from this ID are:\n");
2932 
2933 		j = ID_max;
2934 		do {
2935 			if (iot[i].usr.bit_output[j / 8] & (1 << (j % 8))) {
2936 				DPRINTF("  -- ID=%d\n", j);
2937 			}
2938 		} while (j--);
2939 
2940 	} while (i--);
2941 #endif
2942 
2943 	/*
2944 	 * scan the config to create a linked
2945 	 * list of "mixer" nodes:
2946 	 */
2947 
2948 	i = ID_max;
2949 	do {
2950 		dp = iot[i].u.desc;
2951 
2952 		if (dp == NULL) {
2953 			continue;
2954 		}
2955 		DPRINTFN(11, "id=%d subtype=%d\n",
2956 		    i, dp->bDescriptorSubtype);
2957 
2958 		switch (dp->bDescriptorSubtype) {
2959 		case UDESCSUB_AC_HEADER:
2960 			DPRINTF("unexpected AC header\n");
2961 			break;
2962 
2963 		case UDESCSUB_AC_INPUT:
2964 			uaudio_mixer_add_input(sc, iot, i);
2965 			break;
2966 
2967 		case UDESCSUB_AC_OUTPUT:
2968 			uaudio_mixer_add_output(sc, iot, i);
2969 			break;
2970 
2971 		case UDESCSUB_AC_MIXER:
2972 			uaudio_mixer_add_mixer(sc, iot, i);
2973 			break;
2974 
2975 		case UDESCSUB_AC_SELECTOR:
2976 			uaudio_mixer_add_selector(sc, iot, i);
2977 			break;
2978 
2979 		case UDESCSUB_AC_FEATURE:
2980 			uaudio_mixer_add_feature(sc, iot, i);
2981 			break;
2982 
2983 		case UDESCSUB_AC_PROCESSING:
2984 			uaudio_mixer_add_processing(sc, iot, i);
2985 			break;
2986 
2987 		case UDESCSUB_AC_EXTENSION:
2988 			uaudio_mixer_add_extension(sc, iot, i);
2989 			break;
2990 
2991 		default:
2992 			DPRINTF("bad AC desc subtype=0x%02x\n",
2993 			    dp->bDescriptorSubtype);
2994 			break;
2995 		}
2996 
2997 	} while (i--);
2998 
2999 done:
3000 	if (iot) {
3001 		free(iot, M_TEMP);
3002 	}
3003 }
3004 
3005 static uint16_t
3006 uaudio_mixer_get(struct usb_device *udev, uint8_t what,
3007     struct uaudio_mixer_node *mc)
3008 {
3009 	struct usb_device_request req;
3010 	uint16_t val;
3011 	uint16_t len = MIX_SIZE(mc->type);
3012 	uint8_t data[4];
3013 	usb_error_t err;
3014 
3015 	if (mc->wValue[0] == -1) {
3016 		return (0);
3017 	}
3018 	req.bmRequestType = UT_READ_CLASS_INTERFACE;
3019 	req.bRequest = what;
3020 	USETW(req.wValue, mc->wValue[0]);
3021 	USETW(req.wIndex, mc->wIndex);
3022 	USETW(req.wLength, len);
3023 
3024 	err = usbd_do_request(udev, NULL, &req, data);
3025 	if (err) {
3026 		DPRINTF("err=%s\n", usbd_errstr(err));
3027 		return (0);
3028 	}
3029 	if (len < 1) {
3030 		data[0] = 0;
3031 	}
3032 	if (len < 2) {
3033 		data[1] = 0;
3034 	}
3035 	val = (data[0] | (data[1] << 8));
3036 
3037 	DPRINTFN(3, "val=%d\n", val);
3038 
3039 	return (val);
3040 }
3041 
3042 static void
3043 uaudio_mixer_write_cfg_callback(struct usb_xfer *xfer, usb_error_t error)
3044 {
3045 	struct usb_device_request req;
3046 	struct uaudio_softc *sc = usbd_xfer_softc(xfer);
3047 	struct uaudio_mixer_node *mc = sc->sc_mixer_curr;
3048 	struct usb_page_cache *pc;
3049 	uint16_t len;
3050 	uint8_t repeat = 1;
3051 	uint8_t update;
3052 	uint8_t chan;
3053 	uint8_t buf[2];
3054 
3055 	DPRINTF("\n");
3056 
3057 	switch (USB_GET_STATE(xfer)) {
3058 	case USB_ST_TRANSFERRED:
3059 tr_transferred:
3060 	case USB_ST_SETUP:
3061 tr_setup:
3062 
3063 		if (mc == NULL) {
3064 			mc = sc->sc_mixer_root;
3065 			sc->sc_mixer_curr = mc;
3066 			sc->sc_mixer_chan = 0;
3067 			repeat = 0;
3068 		}
3069 		while (mc) {
3070 			while (sc->sc_mixer_chan < mc->nchan) {
3071 
3072 				len = MIX_SIZE(mc->type);
3073 
3074 				chan = sc->sc_mixer_chan;
3075 
3076 				sc->sc_mixer_chan++;
3077 
3078 				update = ((mc->update[chan / 8] & (1 << (chan % 8))) &&
3079 				    (mc->wValue[chan] != -1));
3080 
3081 				mc->update[chan / 8] &= ~(1 << (chan % 8));
3082 
3083 				if (update) {
3084 
3085 					req.bmRequestType = UT_WRITE_CLASS_INTERFACE;
3086 					req.bRequest = SET_CUR;
3087 					USETW(req.wValue, mc->wValue[chan]);
3088 					USETW(req.wIndex, mc->wIndex);
3089 					USETW(req.wLength, len);
3090 
3091 					if (len > 0) {
3092 						buf[0] = (mc->wData[chan] & 0xFF);
3093 					}
3094 					if (len > 1) {
3095 						buf[1] = (mc->wData[chan] >> 8) & 0xFF;
3096 					}
3097 					pc = usbd_xfer_get_frame(xfer, 0);
3098 					usbd_copy_in(pc, 0, &req, sizeof(req));
3099 					pc = usbd_xfer_get_frame(xfer, 1);
3100 					usbd_copy_in(pc, 0, buf, len);
3101 
3102 					usbd_xfer_set_frame_len(xfer, 0, sizeof(req));
3103 					usbd_xfer_set_frame_len(xfer, 1, len);
3104 					usbd_xfer_set_frames(xfer, len ? 2 : 1);
3105 					usbd_transfer_submit(xfer);
3106 					return;
3107 				}
3108 			}
3109 
3110 			mc = mc->next;
3111 			sc->sc_mixer_curr = mc;
3112 			sc->sc_mixer_chan = 0;
3113 		}
3114 
3115 		if (repeat) {
3116 			goto tr_setup;
3117 		}
3118 		break;
3119 
3120 	default:			/* Error */
3121 		DPRINTF("error=%s\n", usbd_errstr(error));
3122 		if (error == USB_ERR_CANCELLED) {
3123 			/* do nothing - we are detaching */
3124 			break;
3125 		}
3126 		goto tr_transferred;
3127 	}
3128 }
3129 
3130 static usb_error_t
3131 uaudio_set_speed(struct usb_device *udev, uint8_t endpt, uint32_t speed)
3132 {
3133 	struct usb_device_request req;
3134 	uint8_t data[3];
3135 
3136 	DPRINTFN(6, "endpt=%d speed=%u\n", endpt, speed);
3137 
3138 	req.bmRequestType = UT_WRITE_CLASS_ENDPOINT;
3139 	req.bRequest = SET_CUR;
3140 	USETW2(req.wValue, SAMPLING_FREQ_CONTROL, 0);
3141 	USETW(req.wIndex, endpt);
3142 	USETW(req.wLength, 3);
3143 	data[0] = speed;
3144 	data[1] = speed >> 8;
3145 	data[2] = speed >> 16;
3146 
3147 	return (usbd_do_request(udev, NULL, &req, data));
3148 }
3149 
3150 static int
3151 uaudio_mixer_signext(uint8_t type, int val)
3152 {
3153 	if (!MIX_UNSIGNED(type)) {
3154 		if (MIX_SIZE(type) == 2) {
3155 			val = (int16_t)val;
3156 		} else {
3157 			val = (int8_t)val;
3158 		}
3159 	}
3160 	return (val);
3161 }
3162 
3163 static int
3164 uaudio_mixer_bsd2value(struct uaudio_mixer_node *mc, int32_t val)
3165 {
3166 	if (mc->type == MIX_ON_OFF) {
3167 		val = (val != 0);
3168 	} else if (mc->type == MIX_SELECTOR) {
3169 		if ((val < mc->minval) ||
3170 		    (val > mc->maxval)) {
3171 			val = mc->minval;
3172 		}
3173 	} else {
3174 
3175 		/* compute actual volume */
3176 		val = (val * mc->mul) / 255;
3177 
3178 		/* add lower offset */
3179 		val = val + mc->minval;
3180 
3181 		/* make sure we don't write a value out of range */
3182 		if (val > mc->maxval)
3183 			val = mc->maxval;
3184 		else if (val < mc->minval)
3185 			val = mc->minval;
3186 	}
3187 
3188 	DPRINTFN(6, "type=0x%03x val=%d min=%d max=%d val=%d\n",
3189 	    mc->type, val, mc->minval, mc->maxval, val);
3190 	return (val);
3191 }
3192 
3193 static void
3194 uaudio_mixer_ctl_set(struct uaudio_softc *sc, struct uaudio_mixer_node *mc,
3195     uint8_t chan, int32_t val)
3196 {
3197 	val = uaudio_mixer_bsd2value(mc, val);
3198 
3199 	mc->update[chan / 8] |= (1 << (chan % 8));
3200 	mc->wData[chan] = val;
3201 
3202 	/* start the transfer, if not already started */
3203 
3204 	usbd_transfer_start(sc->sc_mixer_xfer[0]);
3205 }
3206 
3207 static void
3208 uaudio_mixer_init(struct uaudio_softc *sc)
3209 {
3210 	struct uaudio_mixer_node *mc;
3211 	int32_t i;
3212 
3213 	for (mc = sc->sc_mixer_root; mc;
3214 	    mc = mc->next) {
3215 
3216 		if (mc->ctl != SOUND_MIXER_NRDEVICES) {
3217 			/*
3218 			 * Set device mask bits. See
3219 			 * /usr/include/machine/soundcard.h
3220 			 */
3221 			sc->sc_mix_info |= (1 << mc->ctl);
3222 		}
3223 		if ((mc->ctl == SOUND_MIXER_NRDEVICES) &&
3224 		    (mc->type == MIX_SELECTOR)) {
3225 
3226 			for (i = mc->minval; (i > 0) && (i <= mc->maxval); i++) {
3227 				if (mc->slctrtype[i - 1] == SOUND_MIXER_NRDEVICES) {
3228 					continue;
3229 				}
3230 				sc->sc_recsrc_info |= 1 << mc->slctrtype[i - 1];
3231 			}
3232 		}
3233 	}
3234 }
3235 
3236 int
3237 uaudio_mixer_init_sub(struct uaudio_softc *sc, struct snd_mixer *m)
3238 {
3239 	DPRINTF("\n");
3240 
3241 	if (usbd_transfer_setup(sc->sc_udev, &sc->sc_mixer_iface_index,
3242 	    sc->sc_mixer_xfer, uaudio_mixer_config, 1, sc,
3243 	    mixer_get_lock(m))) {
3244 		DPRINTFN(0, "could not allocate USB "
3245 		    "transfer for audio mixer!\n");
3246 		return (ENOMEM);
3247 	}
3248 	if (!(sc->sc_mix_info & SOUND_MASK_VOLUME)) {
3249 		mix_setparentchild(m, SOUND_MIXER_VOLUME, SOUND_MASK_PCM);
3250 		mix_setrealdev(m, SOUND_MIXER_VOLUME, SOUND_MIXER_NONE);
3251 	}
3252 	mix_setdevs(m, sc->sc_mix_info);
3253 	mix_setrecdevs(m, sc->sc_recsrc_info);
3254 	return (0);
3255 }
3256 
3257 int
3258 uaudio_mixer_uninit_sub(struct uaudio_softc *sc)
3259 {
3260 	DPRINTF("\n");
3261 
3262 	usbd_transfer_unsetup(sc->sc_mixer_xfer, 1);
3263 
3264 	return (0);
3265 }
3266 
3267 void
3268 uaudio_mixer_set(struct uaudio_softc *sc, unsigned type,
3269     unsigned left, unsigned right)
3270 {
3271 	struct uaudio_mixer_node *mc;
3272 
3273 	for (mc = sc->sc_mixer_root; mc;
3274 	    mc = mc->next) {
3275 
3276 		if (mc->ctl == type) {
3277 			if (mc->nchan == 2) {
3278 				/* set Right */
3279 				uaudio_mixer_ctl_set(sc, mc, 1, (int)(right * 255) / 100);
3280 			}
3281 			/* set Left or Mono */
3282 			uaudio_mixer_ctl_set(sc, mc, 0, (int)(left * 255) / 100);
3283 		}
3284 	}
3285 }
3286 
3287 uint32_t
3288 uaudio_mixer_setrecsrc(struct uaudio_softc *sc, uint32_t src)
3289 {
3290 	struct uaudio_mixer_node *mc;
3291 	uint32_t mask;
3292 	uint32_t temp;
3293 	int32_t i;
3294 
3295 	for (mc = sc->sc_mixer_root; mc;
3296 	    mc = mc->next) {
3297 
3298 		if ((mc->ctl == SOUND_MIXER_NRDEVICES) &&
3299 		    (mc->type == MIX_SELECTOR)) {
3300 
3301 			/* compute selector mask */
3302 
3303 			mask = 0;
3304 			for (i = mc->minval; (i > 0) && (i <= mc->maxval); i++) {
3305 				mask |= (1 << mc->slctrtype[i - 1]);
3306 			}
3307 
3308 			temp = mask & src;
3309 			if (temp == 0) {
3310 				continue;
3311 			}
3312 			/* find the first set bit */
3313 			temp = (-temp) & temp;
3314 
3315 			/* update "src" */
3316 			src &= ~mask;
3317 			src |= temp;
3318 
3319 			for (i = mc->minval; (i > 0) && (i <= mc->maxval); i++) {
3320 				if (temp != (1 << mc->slctrtype[i - 1])) {
3321 					continue;
3322 				}
3323 				uaudio_mixer_ctl_set(sc, mc, 0, i);
3324 				break;
3325 			}
3326 		}
3327 	}
3328 	return (src);
3329 }
3330 
3331 /*========================================================================*
3332  * MIDI support routines
3333  *========================================================================*/
3334 
3335 static void
3336 umidi_bulk_read_callback(struct usb_xfer *xfer, usb_error_t error)
3337 {
3338 	struct umidi_chan *chan = usbd_xfer_softc(xfer);
3339 	struct umidi_sub_chan *sub;
3340 	struct usb_page_cache *pc;
3341 	uint8_t buf[4];
3342 	uint8_t cmd_len;
3343 	uint8_t cn;
3344 	uint16_t pos;
3345 	int actlen;
3346 
3347 	usbd_xfer_status(xfer, &actlen, NULL, NULL, NULL);
3348 
3349 	switch (USB_GET_STATE(xfer)) {
3350 	case USB_ST_TRANSFERRED:
3351 
3352 		DPRINTF("actlen=%d bytes\n", actlen);
3353 
3354 		pos = 0;
3355 		pc = usbd_xfer_get_frame(xfer, 0);
3356 
3357 		while (actlen >= 4) {
3358 
3359 			/* copy out the MIDI data */
3360 			usbd_copy_out(pc, pos, buf, 4);
3361 			/* command length */
3362 			cmd_len = umidi_cmd_to_len[buf[0] & 0xF];
3363 			/* cable number */
3364 			cn = buf[0] >> 4;
3365 			/*
3366 			 * Lookup sub-channel. The index is range
3367 			 * checked below.
3368 			 */
3369 			sub = &chan->sub[cn];
3370 
3371 			if ((cmd_len != 0) &&
3372 			    (cn < chan->max_cable) &&
3373 			    (sub->read_open != 0)) {
3374 
3375 				/* Send data to the application */
3376 				usb_fifo_put_data_linear(
3377 				    sub->fifo.fp[USB_FIFO_RX],
3378 				    buf + 1, cmd_len, 1);
3379 			}
3380 			actlen -= 4;
3381 			pos += 4;
3382 		}
3383 
3384 	case USB_ST_SETUP:
3385 		DPRINTF("start\n");
3386 tr_setup:
3387 		usbd_xfer_set_frame_len(xfer, 0, usbd_xfer_max_len(xfer));
3388 		usbd_transfer_submit(xfer);
3389 		break;
3390 
3391 	default:
3392 		DPRINTF("error=%s\n", usbd_errstr(error));
3393 
3394 		if (error != USB_ERR_CANCELLED) {
3395 			/* try to clear stall first */
3396 			usbd_xfer_set_stall(xfer);
3397 			goto tr_setup;
3398 		}
3399 		break;
3400 	}
3401 }
3402 
3403 /*
3404  * The following statemachine, that converts MIDI commands to
3405  * USB MIDI packets, derives from Linux's usbmidi.c, which
3406  * was written by "Clemens Ladisch":
3407  *
3408  * Returns:
3409  *    0: No command
3410  * Else: Command is complete
3411  */
3412 static uint8_t
3413 umidi_convert_to_usb(struct umidi_sub_chan *sub, uint8_t cn, uint8_t b)
3414 {
3415 	uint8_t p0 = (cn << 4);
3416 
3417 	if (b >= 0xf8) {
3418 		sub->temp_0[0] = p0 | 0x0f;
3419 		sub->temp_0[1] = b;
3420 		sub->temp_0[2] = 0;
3421 		sub->temp_0[3] = 0;
3422 		sub->temp_cmd = sub->temp_0;
3423 		return (1);
3424 
3425 	} else if (b >= 0xf0) {
3426 		switch (b) {
3427 		case 0xf0:		/* system exclusive begin */
3428 			sub->temp_1[1] = b;
3429 			sub->state = UMIDI_ST_SYSEX_1;
3430 			break;
3431 		case 0xf1:		/* MIDI time code */
3432 		case 0xf3:		/* song select */
3433 			sub->temp_1[1] = b;
3434 			sub->state = UMIDI_ST_1PARAM;
3435 			break;
3436 		case 0xf2:		/* song position pointer */
3437 			sub->temp_1[1] = b;
3438 			sub->state = UMIDI_ST_2PARAM_1;
3439 			break;
3440 		case 0xf4:		/* unknown */
3441 		case 0xf5:		/* unknown */
3442 			sub->state = UMIDI_ST_UNKNOWN;
3443 			break;
3444 		case 0xf6:		/* tune request */
3445 			sub->temp_1[0] = p0 | 0x05;
3446 			sub->temp_1[1] = 0xf6;
3447 			sub->temp_1[2] = 0;
3448 			sub->temp_1[3] = 0;
3449 			sub->temp_cmd = sub->temp_1;
3450 			sub->state = UMIDI_ST_UNKNOWN;
3451 			return (1);
3452 
3453 		case 0xf7:		/* system exclusive end */
3454 			switch (sub->state) {
3455 			case UMIDI_ST_SYSEX_0:
3456 				sub->temp_1[0] = p0 | 0x05;
3457 				sub->temp_1[1] = 0xf7;
3458 				sub->temp_1[2] = 0;
3459 				sub->temp_1[3] = 0;
3460 				sub->temp_cmd = sub->temp_1;
3461 				sub->state = UMIDI_ST_UNKNOWN;
3462 				return (1);
3463 			case UMIDI_ST_SYSEX_1:
3464 				sub->temp_1[0] = p0 | 0x06;
3465 				sub->temp_1[2] = 0xf7;
3466 				sub->temp_1[3] = 0;
3467 				sub->temp_cmd = sub->temp_1;
3468 				sub->state = UMIDI_ST_UNKNOWN;
3469 				return (1);
3470 			case UMIDI_ST_SYSEX_2:
3471 				sub->temp_1[0] = p0 | 0x07;
3472 				sub->temp_1[3] = 0xf7;
3473 				sub->temp_cmd = sub->temp_1;
3474 				sub->state = UMIDI_ST_UNKNOWN;
3475 				return (1);
3476 			}
3477 			sub->state = UMIDI_ST_UNKNOWN;
3478 			break;
3479 		}
3480 	} else if (b >= 0x80) {
3481 		sub->temp_1[1] = b;
3482 		if ((b >= 0xc0) && (b <= 0xdf)) {
3483 			sub->state = UMIDI_ST_1PARAM;
3484 		} else {
3485 			sub->state = UMIDI_ST_2PARAM_1;
3486 		}
3487 	} else {			/* b < 0x80 */
3488 		switch (sub->state) {
3489 		case UMIDI_ST_1PARAM:
3490 			if (sub->temp_1[1] < 0xf0) {
3491 				p0 |= sub->temp_1[1] >> 4;
3492 			} else {
3493 				p0 |= 0x02;
3494 				sub->state = UMIDI_ST_UNKNOWN;
3495 			}
3496 			sub->temp_1[0] = p0;
3497 			sub->temp_1[2] = b;
3498 			sub->temp_1[3] = 0;
3499 			sub->temp_cmd = sub->temp_1;
3500 			return (1);
3501 		case UMIDI_ST_2PARAM_1:
3502 			sub->temp_1[2] = b;
3503 			sub->state = UMIDI_ST_2PARAM_2;
3504 			break;
3505 		case UMIDI_ST_2PARAM_2:
3506 			if (sub->temp_1[1] < 0xf0) {
3507 				p0 |= sub->temp_1[1] >> 4;
3508 				sub->state = UMIDI_ST_2PARAM_1;
3509 			} else {
3510 				p0 |= 0x03;
3511 				sub->state = UMIDI_ST_UNKNOWN;
3512 			}
3513 			sub->temp_1[0] = p0;
3514 			sub->temp_1[3] = b;
3515 			sub->temp_cmd = sub->temp_1;
3516 			return (1);
3517 		case UMIDI_ST_SYSEX_0:
3518 			sub->temp_1[1] = b;
3519 			sub->state = UMIDI_ST_SYSEX_1;
3520 			break;
3521 		case UMIDI_ST_SYSEX_1:
3522 			sub->temp_1[2] = b;
3523 			sub->state = UMIDI_ST_SYSEX_2;
3524 			break;
3525 		case UMIDI_ST_SYSEX_2:
3526 			sub->temp_1[0] = p0 | 0x04;
3527 			sub->temp_1[3] = b;
3528 			sub->temp_cmd = sub->temp_1;
3529 			sub->state = UMIDI_ST_SYSEX_0;
3530 			return (1);
3531 		default:
3532 			break;
3533 		}
3534 	}
3535 	return (0);
3536 }
3537 
3538 static void
3539 umidi_bulk_write_callback(struct usb_xfer *xfer, usb_error_t error)
3540 {
3541 	struct umidi_chan *chan = usbd_xfer_softc(xfer);
3542 	struct umidi_sub_chan *sub;
3543 	struct usb_page_cache *pc;
3544 	uint32_t actlen;
3545 	uint16_t nframes;
3546 	uint8_t buf;
3547 	uint8_t start_cable;
3548 	uint8_t tr_any;
3549 	int len;
3550 
3551 	usbd_xfer_status(xfer, &len, NULL, NULL, NULL);
3552 
3553 	/*
3554 	 * NOTE: Some MIDI devices only accept 4 bytes of data per
3555 	 * short terminated USB transfer.
3556 	 */
3557 	switch (USB_GET_STATE(xfer)) {
3558 	case USB_ST_TRANSFERRED:
3559 		DPRINTF("actlen=%d bytes\n", len);
3560 
3561 	case USB_ST_SETUP:
3562 tr_setup:
3563 		DPRINTF("start\n");
3564 
3565 		nframes = 0;	/* reset */
3566 		start_cable = chan->curr_cable;
3567 		tr_any = 0;
3568 		pc = usbd_xfer_get_frame(xfer, 0);
3569 
3570 		while (1) {
3571 
3572 			/* round robin de-queueing */
3573 
3574 			sub = &chan->sub[chan->curr_cable];
3575 
3576 			if (sub->write_open) {
3577 				usb_fifo_get_data_linear(sub->fifo.fp[USB_FIFO_TX],
3578 				    &buf, 1, &actlen, 0);
3579 			} else {
3580 				actlen = 0;
3581 			}
3582 
3583 			if (actlen) {
3584 
3585 				tr_any = 1;
3586 
3587 				DPRINTF("byte=0x%02x from FIFO %u\n", buf,
3588 				    (unsigned int)chan->curr_cable);
3589 
3590 				if (umidi_convert_to_usb(sub, chan->curr_cable, buf)) {
3591 
3592 					DPRINTF("sub=0x%02x 0x%02x 0x%02x 0x%02x\n",
3593 					    sub->temp_cmd[0], sub->temp_cmd[1],
3594 					    sub->temp_cmd[2], sub->temp_cmd[3]);
3595 
3596 					usbd_copy_in(pc, nframes * 4, sub->temp_cmd, 4);
3597 
3598 					nframes++;
3599 
3600 					if ((nframes >= UMIDI_TX_FRAMES) || (chan->single_command != 0))
3601 						break;
3602 				} else {
3603 					continue;
3604 				}
3605 			}
3606 
3607 			chan->curr_cable++;
3608 			if (chan->curr_cable >= chan->max_cable)
3609 				chan->curr_cable = 0;
3610 
3611 			if (chan->curr_cable == start_cable) {
3612 				if (tr_any == 0)
3613 					break;
3614 				tr_any = 0;
3615 			}
3616 		}
3617 
3618 		if (nframes != 0) {
3619 			DPRINTF("Transferring %d frames\n", (int)nframes);
3620 			usbd_xfer_set_frame_len(xfer, 0, 4 * nframes);
3621 			usbd_transfer_submit(xfer);
3622 		}
3623 		break;
3624 
3625 	default:			/* Error */
3626 
3627 		DPRINTF("error=%s\n", usbd_errstr(error));
3628 
3629 		if (error != USB_ERR_CANCELLED) {
3630 			/* try to clear stall first */
3631 			usbd_xfer_set_stall(xfer);
3632 			goto tr_setup;
3633 		}
3634 		break;
3635 	}
3636 }
3637 
3638 static struct umidi_sub_chan *
3639 umidi_sub_by_fifo(struct usb_fifo *fifo)
3640 {
3641 	struct umidi_chan *chan = usb_fifo_softc(fifo);
3642 	struct umidi_sub_chan *sub;
3643 	uint32_t n;
3644 
3645 	for (n = 0; n < UMIDI_CABLES_MAX; n++) {
3646 		sub = &chan->sub[n];
3647 		if ((sub->fifo.fp[USB_FIFO_RX] == fifo) ||
3648 		    (sub->fifo.fp[USB_FIFO_TX] == fifo)) {
3649 			return (sub);
3650 		}
3651 	}
3652 
3653 	panic("%s:%d cannot find usb_fifo!\n",
3654 	    __FILE__, __LINE__);
3655 
3656 	return (NULL);
3657 }
3658 
3659 static void
3660 umidi_start_read(struct usb_fifo *fifo)
3661 {
3662 	struct umidi_chan *chan = usb_fifo_softc(fifo);
3663 
3664 	usbd_transfer_start(chan->xfer[UMIDI_RX_TRANSFER]);
3665 }
3666 
3667 static void
3668 umidi_stop_read(struct usb_fifo *fifo)
3669 {
3670 	struct umidi_chan *chan = usb_fifo_softc(fifo);
3671 	struct umidi_sub_chan *sub = umidi_sub_by_fifo(fifo);
3672 
3673 	DPRINTF("\n");
3674 
3675 	sub->read_open = 0;
3676 
3677 	if (--(chan->read_open_refcount) == 0) {
3678 		/*
3679 		 * XXX don't stop the read transfer here, hence that causes
3680 		 * problems with some MIDI adapters
3681 		 */
3682 		DPRINTF("(stopping read transfer)\n");
3683 	}
3684 }
3685 
3686 static void
3687 umidi_start_write(struct usb_fifo *fifo)
3688 {
3689 	struct umidi_chan *chan = usb_fifo_softc(fifo);
3690 
3691 	usbd_transfer_start(chan->xfer[UMIDI_TX_TRANSFER]);
3692 }
3693 
3694 static void
3695 umidi_stop_write(struct usb_fifo *fifo)
3696 {
3697 	struct umidi_chan *chan = usb_fifo_softc(fifo);
3698 	struct umidi_sub_chan *sub = umidi_sub_by_fifo(fifo);
3699 
3700 	DPRINTF("\n");
3701 
3702 	sub->write_open = 0;
3703 
3704 	if (--(chan->write_open_refcount) == 0) {
3705 		DPRINTF("(stopping write transfer)\n");
3706 		usbd_transfer_stop(chan->xfer[UMIDI_TX_TRANSFER]);
3707 	}
3708 }
3709 
3710 static int
3711 umidi_open(struct usb_fifo *fifo, int fflags)
3712 {
3713 	struct umidi_chan *chan = usb_fifo_softc(fifo);
3714 	struct umidi_sub_chan *sub = umidi_sub_by_fifo(fifo);
3715 
3716 	if (fflags & FREAD) {
3717 		if (usb_fifo_alloc_buffer(fifo, 4, (1024 / 4))) {
3718 			return (ENOMEM);
3719 		}
3720 		mtx_lock(&chan->mtx);
3721 		chan->read_open_refcount++;
3722 		sub->read_open = 1;
3723 		mtx_unlock(&chan->mtx);
3724 	}
3725 	if (fflags & FWRITE) {
3726 		if (usb_fifo_alloc_buffer(fifo, 32, (1024 / 32))) {
3727 			return (ENOMEM);
3728 		}
3729 		/* clear stall first */
3730 		mtx_lock(&chan->mtx);
3731 		usbd_xfer_set_stall(chan->xfer[UMIDI_TX_TRANSFER]);
3732 		chan->write_open_refcount++;
3733 		sub->write_open = 1;
3734 
3735 		/* reset */
3736 		sub->state = UMIDI_ST_UNKNOWN;
3737 		mtx_unlock(&chan->mtx);
3738 	}
3739 	return (0);			/* success */
3740 }
3741 
3742 static void
3743 umidi_close(struct usb_fifo *fifo, int fflags)
3744 {
3745 	if (fflags & FREAD) {
3746 		usb_fifo_free_buffer(fifo);
3747 	}
3748 	if (fflags & FWRITE) {
3749 		usb_fifo_free_buffer(fifo);
3750 	}
3751 }
3752 
3753 
3754 static int
3755 umidi_ioctl(struct usb_fifo *fifo, u_long cmd, void *data,
3756     int fflags)
3757 {
3758 	return (ENODEV);
3759 }
3760 
3761 static void
3762 umidi_init(device_t dev)
3763 {
3764 	struct uaudio_softc *sc = device_get_softc(dev);
3765 	struct umidi_chan *chan = &sc->sc_midi_chan;
3766 
3767 	mtx_init(&chan->mtx, "umidi lock", NULL, MTX_DEF | MTX_RECURSE);
3768 }
3769 
3770 static struct usb_fifo_methods umidi_fifo_methods = {
3771 	.f_start_read = &umidi_start_read,
3772 	.f_start_write = &umidi_start_write,
3773 	.f_stop_read = &umidi_stop_read,
3774 	.f_stop_write = &umidi_stop_write,
3775 	.f_open = &umidi_open,
3776 	.f_close = &umidi_close,
3777 	.f_ioctl = &umidi_ioctl,
3778 	.basename[0] = "umidi",
3779 };
3780 
3781 static int
3782 umidi_probe(device_t dev)
3783 {
3784 	struct uaudio_softc *sc = device_get_softc(dev);
3785 	struct usb_attach_arg *uaa = device_get_ivars(dev);
3786 	struct umidi_chan *chan = &sc->sc_midi_chan;
3787 	struct umidi_sub_chan *sub;
3788 	int unit = device_get_unit(dev);
3789 	int error;
3790 	uint32_t n;
3791 
3792 	if (usb_test_quirk(uaa, UQ_SINGLE_CMD_MIDI))
3793 		chan->single_command = 1;
3794 
3795 	if (usbd_set_alt_interface_index(sc->sc_udev, chan->iface_index,
3796 	    chan->iface_alt_index)) {
3797 		DPRINTF("setting of alternate index failed!\n");
3798 		goto detach;
3799 	}
3800 	usbd_set_parent_iface(sc->sc_udev, chan->iface_index,
3801 	    sc->sc_mixer_iface_index);
3802 
3803 	error = usbd_transfer_setup(uaa->device, &chan->iface_index,
3804 	    chan->xfer, umidi_config, UMIDI_N_TRANSFER,
3805 	    chan, &chan->mtx);
3806 	if (error) {
3807 		DPRINTF("error=%s\n", usbd_errstr(error));
3808 		goto detach;
3809 	}
3810 	if ((chan->max_cable > UMIDI_CABLES_MAX) ||
3811 	    (chan->max_cable == 0)) {
3812 		chan->max_cable = UMIDI_CABLES_MAX;
3813 	}
3814 
3815 	for (n = 0; n < chan->max_cable; n++) {
3816 
3817 		sub = &chan->sub[n];
3818 
3819 		error = usb_fifo_attach(sc->sc_udev, chan, &chan->mtx,
3820 		    &umidi_fifo_methods, &sub->fifo, unit, n,
3821 		    chan->iface_index,
3822 		    UID_ROOT, GID_OPERATOR, 0644);
3823 		if (error) {
3824 			goto detach;
3825 		}
3826 	}
3827 
3828 	mtx_lock(&chan->mtx);
3829 
3830 	/* clear stall first */
3831 	usbd_xfer_set_stall(chan->xfer[UMIDI_RX_TRANSFER]);
3832 
3833 	/*
3834 	 * NOTE: At least one device will not work properly unless the
3835 	 * BULK IN pipe is open all the time. This might have to do
3836 	 * about that the internal queues of the device overflow if we
3837 	 * don't read them regularly.
3838 	 */
3839 	usbd_transfer_start(chan->xfer[UMIDI_RX_TRANSFER]);
3840 
3841 	mtx_unlock(&chan->mtx);
3842 
3843 	return (0);			/* success */
3844 
3845 detach:
3846 	return (ENXIO);			/* failure */
3847 }
3848 
3849 static int
3850 umidi_detach(device_t dev)
3851 {
3852 	struct uaudio_softc *sc = device_get_softc(dev);
3853 	struct umidi_chan *chan = &sc->sc_midi_chan;
3854 	uint32_t n;
3855 
3856 	for (n = 0; n < UMIDI_CABLES_MAX; n++) {
3857 		usb_fifo_detach(&chan->sub[n].fifo);
3858 	}
3859 
3860 	mtx_lock(&chan->mtx);
3861 
3862 	usbd_transfer_stop(chan->xfer[UMIDI_RX_TRANSFER]);
3863 
3864 	mtx_unlock(&chan->mtx);
3865 
3866 	usbd_transfer_unsetup(chan->xfer, UMIDI_N_TRANSFER);
3867 
3868 	mtx_destroy(&chan->mtx);
3869 
3870 	return (0);
3871 }
3872 
3873 DRIVER_MODULE(uaudio, uhub, uaudio_driver, uaudio_devclass, NULL, 0);
3874 MODULE_DEPEND(uaudio, usb, 1, 1, 1);
3875 MODULE_DEPEND(uaudio, sound, SOUND_MINVER, SOUND_PREFVER, SOUND_MAXVER);
3876 MODULE_VERSION(uaudio, 1);
3877