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