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