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