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