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