xref: /freebsd/sys/dev/sound/usb/uaudio.c (revision 18250ec6c089c0c50cbd9fd87d78e03ff89916df)
1 /*	$NetBSD: uaudio.c,v 1.91 2004/11/05 17:46:14 kent Exp $	*/
2 
3 /*-
4  * SPDX-License-Identifier: BSD-2-Clause
5  *
6  * Copyright (c) 1999 The NetBSD Foundation, Inc.
7  * All rights reserved.
8  *
9  * This code is derived from software contributed to The NetBSD Foundation
10  * by Lennart Augustsson (lennart@augustsson.net) at
11  * Carlstedt Research & Technology.
12  *
13  * Redistribution and use in source and binary forms, with or without
14  * modification, are permitted provided that the following conditions
15  * are met:
16  * 1. Redistributions of source code must retain the above copyright
17  *    notice, this list of conditions and the following disclaimer.
18  * 2. Redistributions in binary form must reproduce the above copyright
19  *    notice, this list of conditions and the following disclaimer in the
20  *    documentation and/or other materials provided with the distribution.
21  *
22  * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
23  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
24  * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
25  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
26  * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
27  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
28  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
29  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
30  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
31  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
32  * POSSIBILITY OF SUCH DAMAGE.
33  */
34 
35 #include <sys/cdefs.h>
36 /*
37  * USB audio specs: http://www.usb.org/developers/devclass_docs/audio10.pdf
38  *                  http://www.usb.org/developers/devclass_docs/frmts10.pdf
39  *                  http://www.usb.org/developers/devclass_docs/termt10.pdf
40  */
41 
42 /*
43  * Also merged:
44  *  $NetBSD: uaudio.c,v 1.94 2005/01/15 15:19:53 kent Exp $
45  *  $NetBSD: uaudio.c,v 1.95 2005/01/16 06:02:19 dsainty Exp $
46  *  $NetBSD: uaudio.c,v 1.96 2005/01/16 12:46:00 kent Exp $
47  *  $NetBSD: uaudio.c,v 1.97 2005/02/24 08:19:38 martin Exp $
48  */
49 
50 #include <sys/stdint.h>
51 #include <sys/stddef.h>
52 #include <sys/param.h>
53 #include <sys/queue.h>
54 #include <sys/types.h>
55 #include <sys/systm.h>
56 #include <sys/kernel.h>
57 #include <sys/bus.h>
58 #include <sys/module.h>
59 #include <sys/lock.h>
60 #include <sys/mutex.h>
61 #include <sys/condvar.h>
62 #include <sys/sysctl.h>
63 #include <sys/sx.h>
64 #include <sys/unistd.h>
65 #include <sys/callout.h>
66 #include <sys/malloc.h>
67 #include <sys/priv.h>
68 
69 #include <dev/hid/hid.h>
70 
71 #include "usbdevs.h"
72 #include <dev/usb/usb.h>
73 #include <dev/usb/usbdi.h>
74 #include <dev/usb/usbdi_util.h>
75 #include <dev/usb/usbhid.h>
76 #include <dev/usb/usb_request.h>
77 #include <dev/usb/usb_process.h>
78 
79 #define	USB_DEBUG_VAR uaudio_debug
80 #include <dev/usb/usb_debug.h>
81 
82 #include <dev/usb/quirk/usb_quirk.h>
83 
84 #include <sys/reboot.h>			/* for bootverbose */
85 
86 #ifdef HAVE_KERNEL_OPTION_HEADERS
87 #include "opt_snd.h"
88 #endif
89 
90 #include <dev/sound/pcm/sound.h>
91 #include <dev/sound/usb/uaudioreg.h>
92 #include <dev/sound/usb/uaudio.h>
93 #include "feeder_if.h"
94 
95 static int uaudio_default_rate = 0;		/* use rate list */
96 static int uaudio_default_bits = 0;		/* use default sample size */
97 static int uaudio_default_channels = 0;		/* use default */
98 static int uaudio_buffer_ms = 4;
99 static bool uaudio_handle_hid = true;
100 
101 static SYSCTL_NODE(_hw_usb, OID_AUTO, uaudio, CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
102     "USB uaudio");
103 SYSCTL_BOOL(_hw_usb_uaudio, OID_AUTO, handle_hid, CTLFLAG_RWTUN,
104     &uaudio_handle_hid, 0, "uaudio handles any HID volume/mute keys, if set");
105 SYSCTL_INT(_hw_usb_uaudio, OID_AUTO, default_rate, CTLFLAG_RWTUN,
106     &uaudio_default_rate, 0, "uaudio default sample rate");
107 SYSCTL_INT(_hw_usb_uaudio, OID_AUTO, default_bits, CTLFLAG_RWTUN,
108     &uaudio_default_bits, 0, "uaudio default sample bits");
109 SYSCTL_INT(_hw_usb_uaudio, OID_AUTO, default_channels, CTLFLAG_RWTUN,
110     &uaudio_default_channels, 0, "uaudio default sample channels");
111 
112 #define	UAUDIO_BUFFER_MS_MIN	1
113 #define	UAUDIO_BUFFER_MS_MAX	8
114 
115 static int
uaudio_buffer_ms_sysctl(SYSCTL_HANDLER_ARGS)116 uaudio_buffer_ms_sysctl(SYSCTL_HANDLER_ARGS)
117 {
118 	int err, val;
119 
120 	val = uaudio_buffer_ms;
121 	err = sysctl_handle_int(oidp, &val, 0, req);
122 
123 	if (err != 0 || req->newptr == NULL || val == uaudio_buffer_ms)
124 		return (err);
125 
126 	if (val > UAUDIO_BUFFER_MS_MAX)
127 		val = UAUDIO_BUFFER_MS_MAX;
128 	else if (val < UAUDIO_BUFFER_MS_MIN)
129 		val = UAUDIO_BUFFER_MS_MIN;
130 
131 	uaudio_buffer_ms = val;
132 
133 	return (0);
134 }
135 SYSCTL_PROC(_hw_usb_uaudio, OID_AUTO, buffer_ms,
136     CTLTYPE_INT | CTLFLAG_RWTUN | CTLFLAG_MPSAFE, 0, sizeof(int),
137     uaudio_buffer_ms_sysctl, "I",
138     "uaudio buffering delay in milliseconds, from 1 to 8");
139 
140 #ifdef USB_DEBUG
141 static int uaudio_debug;
142 
143 SYSCTL_INT(_hw_usb_uaudio, OID_AUTO, debug, CTLFLAG_RWTUN,
144     &uaudio_debug, 0, "uaudio debug level");
145 #else
146 #define	uaudio_debug 0
147 #endif
148 
149 #define	UAUDIO_NFRAMES		64	/* must be factor of 8 due HS-USB */
150 #define	UAUDIO_NCHANBUFS	2	/* number of outstanding request */
151 #define	UAUDIO_RECURSE_LIMIT	255	/* rounds */
152 #define	UAUDIO_BITS_MAX		32	/* maximum sample size in bits */
153 #define	UAUDIO_CHANNELS_MAX	MIN(64, AFMT_CHANNEL_MAX)
154 #define	UAUDIO_MATRIX_MAX	8	/* channels */
155 
156 #define	MAKE_WORD(h,l) (((h) << 8) | (l))
157 #define	BIT_TEST(bm,bno) (((bm)[(bno) / 8] >> (7 - ((bno) % 8))) & 1)
158 #define	UAUDIO_MAX_CHAN(x) (x)
159 #define	MIX(sc) ((sc)->sc_mixer_node)
160 
161 union uaudio_asid {
162 	const struct usb_audio_streaming_interface_descriptor *v1;
163 	const struct usb_audio20_streaming_interface_descriptor *v2;
164 };
165 
166 union uaudio_asf1d {
167 	const struct usb_audio_streaming_type1_descriptor *v1;
168 	const struct usb_audio20_streaming_type1_descriptor *v2;
169 };
170 
171 union uaudio_sed {
172 	const struct usb_audio_streaming_endpoint_descriptor *v1;
173 	const struct usb_audio20_streaming_endpoint_descriptor *v2;
174 };
175 
176 struct uaudio_mixer_node {
177 	const char *name;
178 
179 	int32_t	minval;
180 	int32_t	maxval;
181 #define	MIX_MAX_CHAN 16
182 	int32_t	wValue[MIX_MAX_CHAN];	/* using nchan */
183 	uint32_t mul;
184 	uint32_t ctl;
185 
186 	int wData[MIX_MAX_CHAN];	/* using nchan */
187 	uint16_t wIndex;
188 
189 	uint8_t	update[(MIX_MAX_CHAN + 7) / 8];
190 	uint8_t	nchan;
191 	uint8_t	type;
192 #define	MIX_ON_OFF	1
193 #define	MIX_SIGNED_16	2
194 #define	MIX_UNSIGNED_16	3
195 #define	MIX_SIGNED_8	4
196 #define	MIX_SELECTOR	5
197 #define	MIX_UNKNOWN     6
198 #define	MIX_SIZE(n) ((((n) == MIX_SIGNED_16) || \
199 		      ((n) == MIX_UNSIGNED_16)) ? 2 : 1)
200 #define	MIX_UNSIGNED(n) ((n) == MIX_UNSIGNED_16)
201 
202 #define	MAX_SELECTOR_INPUT_PIN 256
203 	uint8_t	slctrtype[MAX_SELECTOR_INPUT_PIN];
204 	uint8_t val_default;
205 
206 	uint8_t desc[64];
207 
208 	struct uaudio_mixer_node *next;
209 };
210 
211 struct uaudio_configure_msg {
212 	struct usb_proc_msg hdr;
213 	struct uaudio_softc *sc;
214 };
215 
216 #define	CHAN_MAX_ALT 24
217 
218 struct uaudio_chan_alt {
219 	union uaudio_asf1d p_asf1d;
220 	union uaudio_sed p_sed;
221 	const usb_endpoint_descriptor_audio_t *p_ed1;
222 	const struct uaudio_format *p_fmt;
223 	const struct usb_config *usb_cfg;
224 	uint32_t sample_rate;	/* in Hz */
225 	uint16_t sample_size;
226 	uint8_t	iface_index;
227 	uint8_t	iface_alt_index;
228 	uint8_t channels;
229 };
230 
231 struct uaudio_chan {
232 	struct pcmchan_caps pcm_cap;	/* capabilities */
233 	struct uaudio_chan_alt usb_alt[CHAN_MAX_ALT];
234 	struct snd_dbuf *pcm_buf;
235 	struct mtx *pcm_mtx;		/* lock protecting this structure */
236 	struct uaudio_softc *priv_sc;
237 	struct pcm_channel *pcm_ch;
238 	struct usb_xfer *xfer[UAUDIO_NCHANBUFS + 1];
239 
240 	uint8_t *buf;			/* pointer to buffer */
241 	uint8_t *start;			/* upper layer buffer start */
242 	uint8_t *end;			/* upper layer buffer end */
243 	uint8_t *cur;			/* current position in upper layer
244 					 * buffer */
245 
246 	uint32_t intr_frames;		/* in units */
247 	uint32_t frames_per_second;
248 	uint32_t sample_rem;
249 	uint32_t sample_curr;
250 	uint32_t max_buf;
251 	int32_t jitter_rem;
252 	int32_t jitter_curr;
253 
254 	int feedback_rate;
255 
256 	uint32_t pcm_format[2];
257 
258 	uint16_t bytes_per_frame[2];
259 
260 	uint32_t intr_counter;
261 	uint32_t running;
262 	uint32_t num_alt;
263 	uint32_t cur_alt;
264 	uint32_t set_alt;
265 	uint32_t operation;
266 #define	CHAN_OP_NONE 0
267 #define	CHAN_OP_START 1
268 #define	CHAN_OP_STOP 2
269 #define	CHAN_OP_DRAIN 3
270 
271 	uint8_t iface_index;
272 };
273 
274 #define	UMIDI_EMB_JACK_MAX   16		/* units */
275 #define	UMIDI_TX_FRAMES	   256		/* units */
276 #define	UMIDI_TX_BUFFER    (UMIDI_TX_FRAMES * 4)	/* bytes */
277 
278 enum {
279 	UMIDI_TX_TRANSFER,
280 	UMIDI_RX_TRANSFER,
281 	UMIDI_N_TRANSFER,
282 };
283 
284 struct umidi_sub_chan {
285 	struct usb_fifo_sc fifo;
286 	uint8_t *temp_cmd;
287 	uint8_t	temp_0[4];
288 	uint8_t	temp_1[4];
289 	uint8_t	state;
290 #define	UMIDI_ST_UNKNOWN   0		/* scan for command */
291 #define	UMIDI_ST_1PARAM    1
292 #define	UMIDI_ST_2PARAM_1  2
293 #define	UMIDI_ST_2PARAM_2  3
294 #define	UMIDI_ST_SYSEX_0   4
295 #define	UMIDI_ST_SYSEX_1   5
296 #define	UMIDI_ST_SYSEX_2   6
297 
298 	uint8_t	read_open:1;
299 	uint8_t	write_open:1;
300 	uint8_t	unused:6;
301 };
302 
303 struct umidi_chan {
304 	struct umidi_sub_chan sub[UMIDI_EMB_JACK_MAX];
305 	struct mtx mtx;
306 
307 	struct usb_xfer *xfer[UMIDI_N_TRANSFER];
308 
309 	uint8_t	iface_index;
310 	uint8_t	iface_alt_index;
311 
312 	uint8_t	read_open_refcount;
313 	uint8_t	write_open_refcount;
314 
315 	uint8_t	curr_cable;
316 	uint8_t	max_emb_jack;
317 	uint8_t	valid;
318 	uint8_t single_command;
319 };
320 
321 struct uaudio_search_result {
322 	uint8_t	bit_input[(256 + 7) / 8];
323 	uint8_t	bit_output[(256 + 7) / 8];
324 	uint8_t	recurse_level;
325 	uint8_t	id_max;
326 	uint8_t is_input;
327 };
328 
329 enum {
330 	UAUDIO_HID_RX_TRANSFER,
331 	UAUDIO_HID_N_TRANSFER,
332 };
333 
334 struct uaudio_hid {
335 	struct usb_xfer *xfer[UAUDIO_HID_N_TRANSFER];
336 	struct hid_location volume_up_loc;
337 	struct hid_location volume_down_loc;
338 	struct hid_location mute_loc;
339 	uint32_t flags;
340 #define	UAUDIO_HID_VALID		0x0001
341 #define	UAUDIO_HID_HAS_ID		0x0002
342 #define	UAUDIO_HID_HAS_VOLUME_UP	0x0004
343 #define	UAUDIO_HID_HAS_VOLUME_DOWN	0x0008
344 #define	UAUDIO_HID_HAS_MUTE		0x0010
345 	uint8_t iface_index;
346 	uint8_t volume_up_id;
347 	uint8_t volume_down_id;
348 	uint8_t mute_id;
349 };
350 
351 #define	UAUDIO_SPDIF_OUT	0x01	/* Enable S/PDIF output */
352 #define	UAUDIO_SPDIF_OUT_48K	0x02	/* Out sample rate = 48K */
353 #define	UAUDIO_SPDIF_OUT_96K	0x04	/* Out sample rate = 96K */
354 #define	UAUDIO_SPDIF_IN_MIX	0x10	/* Input mix enable */
355 
356 #define	UAUDIO_MAX_CHILD 2
357 
358 struct uaudio_softc_child {
359 	device_t pcm_device;
360 	struct mtx *mixer_lock;
361 	struct snd_mixer *mixer_dev;
362 
363 	uint32_t mix_info;
364 	uint32_t recsrc_info;
365 
366 	uint8_t	pcm_registered:1;
367 	uint8_t	mixer_init:1;
368 };
369 
370 struct uaudio_softc {
371 	struct sndcard_func sc_sndcard_func;
372 	struct uaudio_chan sc_rec_chan[UAUDIO_MAX_CHILD];
373 	struct uaudio_chan sc_play_chan[UAUDIO_MAX_CHILD];
374 	struct umidi_chan sc_midi_chan;
375 	struct uaudio_hid sc_hid;
376 	struct uaudio_search_result sc_mixer_clocks;
377 	struct uaudio_mixer_node sc_mixer_node;
378 	struct uaudio_configure_msg sc_config_msg[2];
379 	struct uaudio_softc_child sc_child[UAUDIO_MAX_CHILD];
380 
381 	struct usb_device *sc_udev;
382 	struct usb_xfer *sc_mixer_xfer[1];
383 	struct uaudio_mixer_node *sc_mixer_root;
384 	struct uaudio_mixer_node *sc_mixer_curr;
385 	int     (*sc_set_spdif_fn) (struct uaudio_softc *, int);
386 
387 	uint16_t sc_audio_rev;
388 	uint16_t sc_mixer_count;
389 
390 	uint8_t	sc_mixer_iface_index;
391 	uint8_t	sc_mixer_iface_no;
392 	uint8_t	sc_mixer_chan;
393 	uint8_t	sc_uq_audio_swap_lr:1;
394 	uint8_t	sc_uq_au_inp_async:1;
395 	uint8_t	sc_uq_au_no_xu:1;
396 	uint8_t	sc_uq_bad_adc:1;
397 	uint8_t	sc_uq_au_vendor_class:1;
398 	uint8_t	sc_pcm_bitperfect:1;
399 };
400 
401 struct uaudio_terminal_node {
402 	union {
403 		const struct usb_descriptor *desc;
404 		const struct usb_audio_input_terminal *it_v1;
405 		const struct usb_audio_output_terminal *ot_v1;
406 		const struct usb_audio_mixer_unit_0 *mu_v1;
407 		const struct usb_audio_selector_unit *su_v1;
408 		const struct usb_audio_feature_unit *fu_v1;
409 		const struct usb_audio_processing_unit_0 *pu_v1;
410 		const struct usb_audio_extension_unit_0 *eu_v1;
411 		const struct usb_audio20_clock_source_unit *csrc_v2;
412 		const struct usb_audio20_clock_selector_unit_0 *csel_v2;
413 		const struct usb_audio20_clock_multiplier_unit *cmul_v2;
414 		const struct usb_audio20_input_terminal *it_v2;
415 		const struct usb_audio20_output_terminal *ot_v2;
416 		const struct usb_audio20_mixer_unit_0 *mu_v2;
417 		const struct usb_audio20_selector_unit *su_v2;
418 		const struct usb_audio20_feature_unit *fu_v2;
419 		const struct usb_audio20_sample_rate_unit *ru_v2;
420 		const struct usb_audio20_processing_unit_0 *pu_v2;
421 		const struct usb_audio20_extension_unit_0 *eu_v2;
422 		const struct usb_audio20_effect_unit *ef_v2;
423 	}	u;
424 	struct uaudio_search_result usr;
425 	struct uaudio_terminal_node *root;
426 };
427 
428 struct uaudio_format {
429 	uint16_t wFormat;
430 	uint8_t	bPrecision;
431 	uint32_t freebsd_fmt;
432 	const char *description;
433 };
434 
435 static const struct uaudio_format uaudio10_formats[] = {
436 	{UA_FMT_PCM8, 8, AFMT_U8, "8-bit U-LE PCM"},
437 	{UA_FMT_PCM8, 16, AFMT_U16_LE, "16-bit U-LE PCM"},
438 	{UA_FMT_PCM8, 24, AFMT_U24_LE, "24-bit U-LE PCM"},
439 	{UA_FMT_PCM8, 32, AFMT_U32_LE, "32-bit U-LE PCM"},
440 
441 	{UA_FMT_PCM, 8, AFMT_S8, "8-bit S-LE PCM"},
442 	{UA_FMT_PCM, 16, AFMT_S16_LE, "16-bit S-LE PCM"},
443 	{UA_FMT_PCM, 24, AFMT_S24_LE, "24-bit S-LE PCM"},
444 	{UA_FMT_PCM, 32, AFMT_S32_LE, "32-bit S-LE PCM"},
445 
446 	{UA_FMT_ALAW, 8, AFMT_A_LAW, "8-bit A-Law"},
447 	{UA_FMT_MULAW, 8, AFMT_MU_LAW, "8-bit mu-Law"},
448 	{0, 0, 0, NULL}
449 };
450 
451 static const struct uaudio_format uaudio20_formats[] = {
452 	{UA20_FMT_PCM, 8, AFMT_S8, "8-bit S-LE PCM"},
453 	{UA20_FMT_PCM, 16, AFMT_S16_LE, "16-bit S-LE PCM"},
454 	{UA20_FMT_PCM, 24, AFMT_S24_LE, "24-bit S-LE PCM"},
455 	{UA20_FMT_PCM, 32, AFMT_S32_LE, "32-bit S-LE PCM"},
456 
457 	{UA20_FMT_PCM8, 8, AFMT_U8, "8-bit U-LE PCM"},
458 	{UA20_FMT_PCM8, 16, AFMT_U16_LE, "16-bit U-LE PCM"},
459 	{UA20_FMT_PCM8, 24, AFMT_U24_LE, "24-bit U-LE PCM"},
460 	{UA20_FMT_PCM8, 32, AFMT_U32_LE, "32-bit U-LE PCM"},
461 
462 	{UA20_FMT_ALAW, 8, AFMT_A_LAW, "8-bit A-Law"},
463 	{UA20_FMT_MULAW, 8, AFMT_MU_LAW, "8-bit mu-Law"},
464 	{0, 0, 0, NULL}
465 };
466 
467 /* prototypes */
468 
469 static device_probe_t uaudio_probe;
470 static device_attach_t uaudio_attach;
471 static device_detach_t uaudio_detach;
472 
473 static usb_callback_t uaudio_chan_play_callback;
474 static usb_callback_t uaudio_chan_play_sync_callback;
475 static usb_callback_t uaudio_chan_record_callback;
476 static usb_callback_t uaudio_chan_record_sync_callback;
477 static usb_callback_t uaudio_mixer_write_cfg_callback;
478 static usb_callback_t umidi_bulk_read_callback;
479 static usb_callback_t umidi_bulk_write_callback;
480 static usb_callback_t uaudio_hid_rx_callback;
481 
482 static usb_proc_callback_t uaudio_configure_msg;
483 
484 /* ==== USB mixer ==== */
485 
486 static int uaudio_mixer_sysctl_handler(SYSCTL_HANDLER_ARGS);
487 static void uaudio_mixer_ctl_free(struct uaudio_softc *);
488 static void uaudio_mixer_register_sysctl(struct uaudio_softc *, device_t, unsigned);
489 static void uaudio_mixer_reload_all(struct uaudio_softc *);
490 static void uaudio_mixer_controls_create_ftu(struct uaudio_softc *);
491 
492 /* ==== USB audio v1.0 ==== */
493 
494 static void	uaudio_mixer_add_mixer(struct uaudio_softc *,
495 		    const struct uaudio_terminal_node *, int);
496 static void	uaudio_mixer_add_selector(struct uaudio_softc *,
497 		    const struct uaudio_terminal_node *, int);
498 static uint32_t	uaudio_mixer_feature_get_bmaControls(
499 		    const struct usb_audio_feature_unit *, uint8_t);
500 static void	uaudio_mixer_add_feature(struct uaudio_softc *,
501 		    const struct uaudio_terminal_node *, int);
502 static void	uaudio_mixer_add_processing_updown(struct uaudio_softc *,
503 		    const struct uaudio_terminal_node *, int);
504 static void	uaudio_mixer_add_processing(struct uaudio_softc *,
505 		    const struct uaudio_terminal_node *, int);
506 static void	uaudio_mixer_add_extension(struct uaudio_softc *,
507 		    const struct uaudio_terminal_node *, int);
508 static struct	usb_audio_cluster uaudio_mixer_get_cluster(uint8_t,
509 		    const struct uaudio_terminal_node *);
510 static uint16_t	uaudio_mixer_determine_class(const struct uaudio_terminal_node *);
511 static void	uaudio_mixer_find_inputs_sub(struct uaudio_terminal_node *,
512 		    const uint8_t *, uint8_t, struct uaudio_search_result *);
513 static const void *uaudio_mixer_verify_desc(const void *, uint32_t);
514 static usb_error_t uaudio_set_speed(struct usb_device *, uint8_t, uint32_t);
515 static int	uaudio_mixer_get(struct usb_device *, uint16_t, uint8_t,
516 		    struct uaudio_mixer_node *);
517 
518 /* ==== USB audio v2.0 ==== */
519 
520 static void	uaudio20_mixer_add_mixer(struct uaudio_softc *,
521 		    const struct uaudio_terminal_node *, int);
522 static void	uaudio20_mixer_add_selector(struct uaudio_softc *,
523 		    const struct uaudio_terminal_node *, int);
524 static void	uaudio20_mixer_add_feature(struct uaudio_softc *,
525 		    const struct uaudio_terminal_node *, int);
526 static struct	usb_audio20_cluster uaudio20_mixer_get_cluster(uint8_t,
527 		    const struct uaudio_terminal_node *);
528 static uint16_t	uaudio20_mixer_determine_class(const struct uaudio_terminal_node *);
529 static void	uaudio20_mixer_find_inputs_sub(struct uaudio_terminal_node *,
530 		    const uint8_t *, uint8_t, struct uaudio_search_result *);
531 static const void *uaudio20_mixer_verify_desc(const void *, uint32_t);
532 static usb_error_t uaudio20_set_speed(struct usb_device *, uint8_t,
533 		    uint8_t, uint32_t);
534 
535 /* USB audio v1.0 and v2.0 */
536 
537 static void	uaudio_chan_fill_info_sub(struct uaudio_softc *,
538 		    struct usb_device *, uint32_t, uint8_t, uint8_t);
539 static void	uaudio_chan_fill_info(struct uaudio_softc *,
540 		    struct usb_device *);
541 static void	uaudio_mixer_add_ctl_sub(struct uaudio_softc *,
542 		    struct uaudio_mixer_node *);
543 static void	uaudio_mixer_add_ctl(struct uaudio_softc *,
544 		    struct uaudio_mixer_node *);
545 static void	uaudio_mixer_fill_info(struct uaudio_softc *,
546 		    struct usb_device *, void *);
547 static int	uaudio_mixer_signext(uint8_t, int);
548 static void	uaudio_mixer_init(struct uaudio_softc *, unsigned);
549 static uint8_t	umidi_convert_to_usb(struct umidi_sub_chan *, uint8_t, uint8_t);
550 static struct	umidi_sub_chan *umidi_sub_by_fifo(struct usb_fifo *);
551 static void	umidi_start_read(struct usb_fifo *);
552 static void	umidi_stop_read(struct usb_fifo *);
553 static void	umidi_start_write(struct usb_fifo *);
554 static void	umidi_stop_write(struct usb_fifo *);
555 static int	umidi_open(struct usb_fifo *, int);
556 static int	umidi_ioctl(struct usb_fifo *, u_long cmd, void *, int);
557 static void	umidi_close(struct usb_fifo *, int);
558 static void	umidi_init(device_t dev);
559 static int	umidi_probe(device_t dev);
560 static int	umidi_detach(device_t dev);
561 static int	uaudio_hid_probe(struct uaudio_softc *sc,
562 		    struct usb_attach_arg *uaa);
563 static void	uaudio_hid_detach(struct uaudio_softc *sc);
564 
565 #ifdef USB_DEBUG
566 static void	uaudio_chan_dump_ep_desc(
567 		    const usb_endpoint_descriptor_audio_t *);
568 #endif
569 
570 static const struct usb_config
571 	uaudio_cfg_record[UAUDIO_NCHANBUFS + 1] = {
572 	[0] = {
573 		.type = UE_ISOCHRONOUS,
574 		.endpoint = UE_ADDR_ANY,
575 		.direction = UE_DIR_IN,
576 		.bufsize = 0,	/* use "wMaxPacketSize * frames" */
577 		.frames = UAUDIO_NFRAMES,
578 		.flags = {.short_xfer_ok = 1,},
579 		.callback = &uaudio_chan_record_callback,
580 	},
581 
582 	[1] = {
583 		.type = UE_ISOCHRONOUS,
584 		.endpoint = UE_ADDR_ANY,
585 		.direction = UE_DIR_IN,
586 		.bufsize = 0,	/* use "wMaxPacketSize * frames" */
587 		.frames = UAUDIO_NFRAMES,
588 		.flags = {.short_xfer_ok = 1,},
589 		.callback = &uaudio_chan_record_callback,
590 	},
591 
592 	[2] = {
593 		.type = UE_ISOCHRONOUS,
594 		.endpoint = UE_ADDR_ANY,
595 		.direction = UE_DIR_OUT,
596 		.bufsize = 0,	/* use "wMaxPacketSize * frames" */
597 		.frames = 1,
598 		.flags = {.no_pipe_ok = 1,.short_xfer_ok = 1,},
599 		.callback = &uaudio_chan_record_sync_callback,
600 	},
601 };
602 
603 static const struct usb_config
604 	uaudio_cfg_play[UAUDIO_NCHANBUFS + 1] = {
605 	[0] = {
606 		.type = UE_ISOCHRONOUS,
607 		.endpoint = UE_ADDR_ANY,
608 		.direction = UE_DIR_OUT,
609 		.bufsize = 0,	/* use "wMaxPacketSize * frames" */
610 		.frames = UAUDIO_NFRAMES,
611 		.flags = {.short_xfer_ok = 1,},
612 		.callback = &uaudio_chan_play_callback,
613 	},
614 
615 	[1] = {
616 		.type = UE_ISOCHRONOUS,
617 		.endpoint = UE_ADDR_ANY,
618 		.direction = UE_DIR_OUT,
619 		.bufsize = 0,	/* use "wMaxPacketSize * frames" */
620 		.frames = UAUDIO_NFRAMES,
621 		.flags = {.short_xfer_ok = 1,},
622 		.callback = &uaudio_chan_play_callback,
623 	},
624 
625 	[2] = {
626 		.type = UE_ISOCHRONOUS,
627 		.endpoint = UE_ADDR_ANY,
628 		.direction = UE_DIR_IN,
629 		.bufsize = 0,	/* use "wMaxPacketSize * frames" */
630 		.frames = 1,
631 		.flags = {.no_pipe_ok = 1,.short_xfer_ok = 1,},
632 		.callback = &uaudio_chan_play_sync_callback,
633 	},
634 };
635 
636 static const struct usb_config
637 	uaudio_mixer_config[1] = {
638 	[0] = {
639 		.type = UE_CONTROL,
640 		.endpoint = 0x00,	/* Control pipe */
641 		.direction = UE_DIR_ANY,
642 		.bufsize = (sizeof(struct usb_device_request) + 4),
643 		.callback = &uaudio_mixer_write_cfg_callback,
644 		.timeout = 1000,	/* 1 second */
645 	},
646 };
647 
648 static const
649 uint8_t	umidi_cmd_to_len[16] = {
650 	[0x0] = 0,			/* reserved */
651 	[0x1] = 0,			/* reserved */
652 	[0x2] = 2,			/* bytes */
653 	[0x3] = 3,			/* bytes */
654 	[0x4] = 3,			/* bytes */
655 	[0x5] = 1,			/* bytes */
656 	[0x6] = 2,			/* bytes */
657 	[0x7] = 3,			/* bytes */
658 	[0x8] = 3,			/* bytes */
659 	[0x9] = 3,			/* bytes */
660 	[0xA] = 3,			/* bytes */
661 	[0xB] = 3,			/* bytes */
662 	[0xC] = 2,			/* bytes */
663 	[0xD] = 2,			/* bytes */
664 	[0xE] = 3,			/* bytes */
665 	[0xF] = 1,			/* bytes */
666 };
667 
668 static const struct usb_config
669 	umidi_config[UMIDI_N_TRANSFER] = {
670 	[UMIDI_TX_TRANSFER] = {
671 		.type = UE_BULK,
672 		.endpoint = UE_ADDR_ANY,
673 		.direction = UE_DIR_OUT,
674 		.bufsize = UMIDI_TX_BUFFER,
675 		.flags = {.no_pipe_ok = 1},
676 		.callback = &umidi_bulk_write_callback,
677 	},
678 
679 	[UMIDI_RX_TRANSFER] = {
680 		.type = UE_BULK,
681 		.endpoint = UE_ADDR_ANY,
682 		.direction = UE_DIR_IN,
683 		.bufsize = 4,	/* bytes */
684 		.flags = {.short_xfer_ok = 1,.proxy_buffer = 1,.no_pipe_ok = 1},
685 		.callback = &umidi_bulk_read_callback,
686 	},
687 };
688 
689 static const struct usb_config
690 	uaudio_hid_config[UAUDIO_HID_N_TRANSFER] = {
691 	[UAUDIO_HID_RX_TRANSFER] = {
692 		.type = UE_INTERRUPT,
693 		.endpoint = UE_ADDR_ANY,
694 		.direction = UE_DIR_IN,
695 		.bufsize = 0,	/* use wMaxPacketSize */
696 		.flags = {.short_xfer_ok = 1,},
697 		.callback = &uaudio_hid_rx_callback,
698 	},
699 };
700 
701 static device_method_t uaudio_methods[] = {
702 	DEVMETHOD(device_probe, uaudio_probe),
703 	DEVMETHOD(device_attach, uaudio_attach),
704 	DEVMETHOD(device_detach, uaudio_detach),
705 	DEVMETHOD(device_suspend, bus_generic_suspend),
706 	DEVMETHOD(device_resume, bus_generic_resume),
707 	DEVMETHOD(device_shutdown, bus_generic_shutdown),
708 
709 	DEVMETHOD_END
710 };
711 
712 static driver_t uaudio_driver = {
713 	.name = "uaudio",
714 	.methods = uaudio_methods,
715 	.size = sizeof(struct uaudio_softc),
716 };
717 
718 /* The following table is derived from Linux's quirks-table.h */
719 static const STRUCT_USB_HOST_ID uaudio_vendor_midi[] = {
720 	{ USB_VPI(USB_VENDOR_YAMAHA, 0x1000, 0) }, /* UX256 */
721 	{ USB_VPI(USB_VENDOR_YAMAHA, 0x1001, 0) }, /* MU1000 */
722 	{ USB_VPI(USB_VENDOR_YAMAHA, 0x1002, 0) }, /* MU2000 */
723 	{ USB_VPI(USB_VENDOR_YAMAHA, 0x1003, 0) }, /* MU500 */
724 	{ USB_VPI(USB_VENDOR_YAMAHA, 0x1004, 3) }, /* UW500 */
725 	{ USB_VPI(USB_VENDOR_YAMAHA, 0x1005, 0) }, /* MOTIF6 */
726 	{ USB_VPI(USB_VENDOR_YAMAHA, 0x1006, 0) }, /* MOTIF7 */
727 	{ USB_VPI(USB_VENDOR_YAMAHA, 0x1007, 0) }, /* MOTIF8 */
728 	{ USB_VPI(USB_VENDOR_YAMAHA, 0x1008, 0) }, /* UX96 */
729 	{ USB_VPI(USB_VENDOR_YAMAHA, 0x1009, 0) }, /* UX16 */
730 	{ USB_VPI(USB_VENDOR_YAMAHA, 0x100a, 3) }, /* EOS BX */
731 	{ USB_VPI(USB_VENDOR_YAMAHA, 0x100c, 0) }, /* UC-MX */
732 	{ USB_VPI(USB_VENDOR_YAMAHA, 0x100d, 0) }, /* UC-KX */
733 	{ USB_VPI(USB_VENDOR_YAMAHA, 0x100e, 0) }, /* S08 */
734 	{ USB_VPI(USB_VENDOR_YAMAHA, 0x100f, 0) }, /* CLP-150 */
735 	{ USB_VPI(USB_VENDOR_YAMAHA, 0x1010, 0) }, /* CLP-170 */
736 	{ USB_VPI(USB_VENDOR_YAMAHA, 0x1011, 0) }, /* P-250 */
737 	{ USB_VPI(USB_VENDOR_YAMAHA, 0x1012, 0) }, /* TYROS */
738 	{ USB_VPI(USB_VENDOR_YAMAHA, 0x1013, 0) }, /* PF-500 */
739 	{ USB_VPI(USB_VENDOR_YAMAHA, 0x1014, 0) }, /* S90 */
740 	{ USB_VPI(USB_VENDOR_YAMAHA, 0x1015, 0) }, /* MOTIF-R */
741 	{ USB_VPI(USB_VENDOR_YAMAHA, 0x1016, 0) }, /* MDP-5 */
742 	{ USB_VPI(USB_VENDOR_YAMAHA, 0x1017, 0) }, /* CVP-204 */
743 	{ USB_VPI(USB_VENDOR_YAMAHA, 0x1018, 0) }, /* CVP-206 */
744 	{ USB_VPI(USB_VENDOR_YAMAHA, 0x1019, 0) }, /* CVP-208 */
745 	{ USB_VPI(USB_VENDOR_YAMAHA, 0x101a, 0) }, /* CVP-210 */
746 	{ USB_VPI(USB_VENDOR_YAMAHA, 0x101b, 0) }, /* PSR-1100 */
747 	{ USB_VPI(USB_VENDOR_YAMAHA, 0x101c, 0) }, /* PSR-2100 */
748 	{ USB_VPI(USB_VENDOR_YAMAHA, 0x101d, 0) }, /* CLP-175 */
749 	{ USB_VPI(USB_VENDOR_YAMAHA, 0x101e, 0) }, /* PSR-K1 */
750 	{ USB_VPI(USB_VENDOR_YAMAHA, 0x101f, 0) }, /* EZ-J24 */
751 	{ USB_VPI(USB_VENDOR_YAMAHA, 0x1020, 0) }, /* EZ-250i */
752 	{ USB_VPI(USB_VENDOR_YAMAHA, 0x1021, 0) }, /* MOTIF ES 6 */
753 	{ USB_VPI(USB_VENDOR_YAMAHA, 0x1022, 0) }, /* MOTIF ES 7 */
754 	{ USB_VPI(USB_VENDOR_YAMAHA, 0x1023, 0) }, /* MOTIF ES 8 */
755 	{ USB_VPI(USB_VENDOR_YAMAHA, 0x1024, 0) }, /* CVP-301 */
756 	{ USB_VPI(USB_VENDOR_YAMAHA, 0x1025, 0) }, /* CVP-303 */
757 	{ USB_VPI(USB_VENDOR_YAMAHA, 0x1026, 0) }, /* CVP-305 */
758 	{ USB_VPI(USB_VENDOR_YAMAHA, 0x1027, 0) }, /* CVP-307 */
759 	{ USB_VPI(USB_VENDOR_YAMAHA, 0x1028, 0) }, /* CVP-309 */
760 	{ USB_VPI(USB_VENDOR_YAMAHA, 0x1029, 0) }, /* CVP-309GP */
761 	{ USB_VPI(USB_VENDOR_YAMAHA, 0x102a, 0) }, /* PSR-1500 */
762 	{ USB_VPI(USB_VENDOR_YAMAHA, 0x102b, 0) }, /* PSR-3000 */
763 	{ USB_VPI(USB_VENDOR_YAMAHA, 0x102e, 0) }, /* ELS-01/01C */
764 	{ USB_VPI(USB_VENDOR_YAMAHA, 0x1030, 0) }, /* PSR-295/293 */
765 	{ USB_VPI(USB_VENDOR_YAMAHA, 0x1031, 0) }, /* DGX-205/203 */
766 	{ USB_VPI(USB_VENDOR_YAMAHA, 0x1032, 0) }, /* DGX-305 */
767 	{ USB_VPI(USB_VENDOR_YAMAHA, 0x1033, 0) }, /* DGX-505 */
768 	{ USB_VPI(USB_VENDOR_YAMAHA, 0x1034, 0) }, /* NULL */
769 	{ USB_VPI(USB_VENDOR_YAMAHA, 0x1035, 0) }, /* NULL */
770 	{ USB_VPI(USB_VENDOR_YAMAHA, 0x1036, 0) }, /* NULL */
771 	{ USB_VPI(USB_VENDOR_YAMAHA, 0x1037, 0) }, /* NULL */
772 	{ USB_VPI(USB_VENDOR_YAMAHA, 0x1038, 0) }, /* NULL */
773 	{ USB_VPI(USB_VENDOR_YAMAHA, 0x1039, 0) }, /* NULL */
774 	{ USB_VPI(USB_VENDOR_YAMAHA, 0x103a, 0) }, /* NULL */
775 	{ USB_VPI(USB_VENDOR_YAMAHA, 0x103b, 0) }, /* NULL */
776 	{ USB_VPI(USB_VENDOR_YAMAHA, 0x103c, 0) }, /* NULL */
777 	{ USB_VPI(USB_VENDOR_YAMAHA, 0x103d, 0) }, /* NULL */
778 	{ USB_VPI(USB_VENDOR_YAMAHA, 0x103e, 0) }, /* NULL */
779 	{ USB_VPI(USB_VENDOR_YAMAHA, 0x103f, 0) }, /* NULL */
780 	{ USB_VPI(USB_VENDOR_YAMAHA, 0x1040, 0) }, /* NULL */
781 	{ USB_VPI(USB_VENDOR_YAMAHA, 0x1041, 0) }, /* NULL */
782 	{ USB_VPI(USB_VENDOR_YAMAHA, 0x1042, 0) }, /* NULL */
783 	{ USB_VPI(USB_VENDOR_YAMAHA, 0x1043, 0) }, /* NULL */
784 	{ USB_VPI(USB_VENDOR_YAMAHA, 0x1044, 0) }, /* NULL */
785 	{ USB_VPI(USB_VENDOR_YAMAHA, 0x1045, 0) }, /* NULL */
786 	{ USB_VPI(USB_VENDOR_YAMAHA, 0x104e, 0) }, /* NULL */
787 	{ USB_VPI(USB_VENDOR_YAMAHA, 0x104f, 0) }, /* NULL */
788 	{ USB_VPI(USB_VENDOR_YAMAHA, 0x1050, 0) }, /* NULL */
789 	{ USB_VPI(USB_VENDOR_YAMAHA, 0x1051, 0) }, /* NULL */
790 	{ USB_VPI(USB_VENDOR_YAMAHA, 0x1052, 0) }, /* NULL */
791 	{ USB_VPI(USB_VENDOR_YAMAHA, 0x1053, 0) }, /* NULL */
792 	{ USB_VPI(USB_VENDOR_YAMAHA, 0x1054, 0) }, /* NULL */
793 	{ USB_VPI(USB_VENDOR_YAMAHA, 0x1055, 0) }, /* NULL */
794 	{ USB_VPI(USB_VENDOR_YAMAHA, 0x1056, 0) }, /* NULL */
795 	{ USB_VPI(USB_VENDOR_YAMAHA, 0x1057, 0) }, /* NULL */
796 	{ USB_VPI(USB_VENDOR_YAMAHA, 0x1058, 0) }, /* NULL */
797 	{ USB_VPI(USB_VENDOR_YAMAHA, 0x1059, 0) }, /* NULL */
798 	{ USB_VPI(USB_VENDOR_YAMAHA, 0x105a, 0) }, /* NULL */
799 	{ USB_VPI(USB_VENDOR_YAMAHA, 0x105b, 0) }, /* NULL */
800 	{ USB_VPI(USB_VENDOR_YAMAHA, 0x105c, 0) }, /* NULL */
801 	{ USB_VPI(USB_VENDOR_YAMAHA, 0x105d, 0) }, /* NULL */
802 	{ USB_VPI(USB_VENDOR_YAMAHA, 0x1503, 3) }, /* MOX6/MOX8 */
803 	{ USB_VPI(USB_VENDOR_YAMAHA, 0x2000, 0) }, /* DGP-7 */
804 	{ USB_VPI(USB_VENDOR_YAMAHA, 0x2001, 0) }, /* DGP-5 */
805 	{ USB_VPI(USB_VENDOR_YAMAHA, 0x2002, 0) }, /* NULL */
806 	{ USB_VPI(USB_VENDOR_YAMAHA, 0x2003, 0) }, /* NULL */
807 	{ USB_VPI(USB_VENDOR_YAMAHA, 0x5000, 0) }, /* CS1D */
808 	{ USB_VPI(USB_VENDOR_YAMAHA, 0x5001, 0) }, /* DSP1D */
809 	{ USB_VPI(USB_VENDOR_YAMAHA, 0x5002, 0) }, /* DME32 */
810 	{ USB_VPI(USB_VENDOR_YAMAHA, 0x5003, 0) }, /* DM2000 */
811 	{ USB_VPI(USB_VENDOR_YAMAHA, 0x5004, 0) }, /* 02R96 */
812 	{ USB_VPI(USB_VENDOR_YAMAHA, 0x5005, 0) }, /* ACU16-C */
813 	{ USB_VPI(USB_VENDOR_YAMAHA, 0x5006, 0) }, /* NHB32-C */
814 	{ USB_VPI(USB_VENDOR_YAMAHA, 0x5007, 0) }, /* DM1000 */
815 	{ USB_VPI(USB_VENDOR_YAMAHA, 0x5008, 0) }, /* 01V96 */
816 	{ USB_VPI(USB_VENDOR_YAMAHA, 0x5009, 0) }, /* SPX2000 */
817 	{ USB_VPI(USB_VENDOR_YAMAHA, 0x500a, 0) }, /* PM5D */
818 	{ USB_VPI(USB_VENDOR_YAMAHA, 0x500b, 0) }, /* DME64N */
819 	{ USB_VPI(USB_VENDOR_YAMAHA, 0x500c, 0) }, /* DME24N */
820 	{ USB_VPI(USB_VENDOR_YAMAHA, 0x500d, 0) }, /* NULL */
821 	{ USB_VPI(USB_VENDOR_YAMAHA, 0x500e, 0) }, /* NULL */
822 	{ USB_VPI(USB_VENDOR_YAMAHA, 0x500f, 0) }, /* NULL */
823 	{ USB_VPI(USB_VENDOR_YAMAHA, 0x7000, 0) }, /* DTX */
824 	{ USB_VPI(USB_VENDOR_YAMAHA, 0x7010, 0) }, /* UB99 */
825 };
826 
827 static const STRUCT_USB_HOST_ID __used uaudio_devs[] = {
828 	/* Generic USB audio class match */
829 	{USB_IFACE_CLASS(UICLASS_AUDIO),
830 	 USB_IFACE_SUBCLASS(UISUBCLASS_AUDIOCONTROL),},
831 	/* Generic USB MIDI class match */
832 	{USB_IFACE_CLASS(UICLASS_AUDIO),
833 	 USB_IFACE_SUBCLASS(UISUBCLASS_MIDISTREAM),},
834 };
835 
836 static unsigned
uaudio_get_child_index_by_dev(struct uaudio_softc * sc,device_t dev)837 uaudio_get_child_index_by_dev(struct uaudio_softc *sc, device_t dev)
838 {
839 	unsigned i;
840 
841 	for (i = 0; i != UAUDIO_MAX_CHILD; i++) {
842 		if (dev == sc->sc_child[i].pcm_device)
843 			return (i);
844 	}
845 	panic("uaudio_get_child_index_dev: Invalid device: %p\n", dev);
846 	return (0);
847 }
848 
849 static unsigned
uaudio_get_child_index_by_chan(struct uaudio_softc * sc,struct uaudio_chan * ch)850 uaudio_get_child_index_by_chan(struct uaudio_softc *sc, struct uaudio_chan *ch)
851 {
852 	unsigned i;
853 
854 	for (i = 0; i != UAUDIO_MAX_CHILD; i++) {
855 		if ((sc->sc_play_chan + i) == ch ||
856 		    (sc->sc_rec_chan + i) == ch)
857 			return (i);
858 	}
859 	panic("uaudio_get_child_index_by_chan: Invalid chan: %p\n", ch);
860 	return (0);
861 }
862 
863 static int
uaudio_probe(device_t dev)864 uaudio_probe(device_t dev)
865 {
866 	struct usb_attach_arg *uaa = device_get_ivars(dev);
867 
868 	if (uaa->usb_mode != USB_MODE_HOST)
869 		return (ENXIO);
870 
871 	/* lookup non-standard device(s) */
872 
873 	if (usbd_lookup_id_by_uaa(uaudio_vendor_midi,
874 	    sizeof(uaudio_vendor_midi), uaa) == 0) {
875 		return (BUS_PROBE_SPECIFIC);
876 	}
877 
878 	if (uaa->info.bInterfaceClass != UICLASS_AUDIO) {
879 		if (uaa->info.bInterfaceClass != UICLASS_VENDOR ||
880 		    usb_test_quirk(uaa, UQ_AU_VENDOR_CLASS) == 0)
881 			return (ENXIO);
882 	}
883 
884 	/* check for AUDIO control interface */
885 
886 	if (uaa->info.bInterfaceSubClass == UISUBCLASS_AUDIOCONTROL) {
887 		if (usb_test_quirk(uaa, UQ_BAD_AUDIO))
888 			return (ENXIO);
889 		else
890 			return (BUS_PROBE_GENERIC);
891 	}
892 
893 	/* check for MIDI stream */
894 
895 	if (uaa->info.bInterfaceSubClass == UISUBCLASS_MIDISTREAM) {
896 		if (usb_test_quirk(uaa, UQ_BAD_MIDI))
897 			return (ENXIO);
898 		else
899 			return (BUS_PROBE_GENERIC);
900 	}
901 	return (ENXIO);
902 }
903 
904 /*
905  * Set Cmedia CM6206 S/PDIF settings
906  * Source: CM6206 Datasheet v2.3.
907  */
908 static int
uaudio_set_spdif_cm6206(struct uaudio_softc * sc,int flags)909 uaudio_set_spdif_cm6206(struct uaudio_softc *sc, int flags)
910 {
911 	uint8_t cmd[2][4] = {
912 		{0x20, 0x20, 0x00, 0},
913 		{0x20, 0x30, 0x02, 1}
914 	};
915 	int i;
916 
917 	if (flags & UAUDIO_SPDIF_OUT)
918 		cmd[1][1] = 0x00;
919 	else
920 		cmd[1][1] = 0x02;
921 
922 	if (flags & UAUDIO_SPDIF_OUT_96K)
923 		cmd[0][1] = 0x60;	/* 96K: 3'b110 */
924 
925 	if (flags & UAUDIO_SPDIF_IN_MIX)
926 		cmd[1][1] = 0x03;	/* SPDIFMIX */
927 
928 	for (i = 0; i < 2; i++) {
929 		if (usbd_req_set_report(sc->sc_udev, NULL,
930 		    cmd[i], sizeof(cmd[0]),
931 		    sc->sc_mixer_iface_index, UHID_OUTPUT_REPORT, 0) != 0) {
932 			return (ENXIO);
933 		}
934 	}
935 	return (0);
936 }
937 
938 static int
uaudio_set_spdif_dummy(struct uaudio_softc * sc,int flags)939 uaudio_set_spdif_dummy(struct uaudio_softc *sc, int flags)
940 {
941 	return (0);
942 }
943 
944 static usb_error_t
uaudio_force_power_save(struct uaudio_softc * sc,uint8_t iface_index)945 uaudio_force_power_save(struct uaudio_softc *sc, uint8_t iface_index)
946 {
947 	struct usb_interface *iface;
948 	usb_error_t err;
949 
950 	iface = usbd_get_iface(sc->sc_udev, iface_index);
951 	if (iface == NULL || iface->idesc == NULL)
952 		return (USB_ERR_INVAL);
953 
954 	/* check if correct alternate setting is already selected */
955 	if (iface->alt_index == 0) {
956 		/* force power save mode by selecting default alternate setting */
957 		err = usbd_req_set_alt_interface_no(sc->sc_udev, NULL, iface_index,
958 		    iface->idesc->bAlternateSetting);
959 	} else {
960 		err = usbd_set_alt_interface_index(sc->sc_udev, iface_index, 0);
961 	}
962 	return (err);
963 }
964 
965 static int
uaudio_attach(device_t dev)966 uaudio_attach(device_t dev)
967 {
968 	struct usb_attach_arg *uaa = device_get_ivars(dev);
969 	struct uaudio_softc *sc = device_get_softc(dev);
970 	struct usb_interface_descriptor *id;
971 	usb_error_t err;
972 	unsigned i;
973 
974 	sc->sc_udev = uaa->device;
975 	sc->sc_mixer_iface_index = uaa->info.bIfaceIndex;
976 	sc->sc_mixer_iface_no = uaa->info.bIfaceNum;
977 	sc->sc_config_msg[0].hdr.pm_callback = &uaudio_configure_msg;
978 	sc->sc_config_msg[0].sc = sc;
979 	sc->sc_config_msg[1].hdr.pm_callback = &uaudio_configure_msg;
980 	sc->sc_config_msg[1].sc = sc;
981 
982 	if (usb_test_quirk(uaa, UQ_AUDIO_SWAP_LR))
983 		sc->sc_uq_audio_swap_lr = 1;
984 
985 	if (usb_test_quirk(uaa, UQ_AU_INP_ASYNC))
986 		sc->sc_uq_au_inp_async = 1;
987 
988 	if (usb_test_quirk(uaa, UQ_AU_NO_XU))
989 		sc->sc_uq_au_no_xu = 1;
990 
991 	if (usb_test_quirk(uaa, UQ_BAD_ADC))
992 		sc->sc_uq_bad_adc = 1;
993 
994 	if (usb_test_quirk(uaa, UQ_AU_VENDOR_CLASS))
995 		sc->sc_uq_au_vendor_class = 1;
996 
997 	/* set S/PDIF function */
998 	if (usb_test_quirk(uaa, UQ_AU_SET_SPDIF_CM6206))
999 		sc->sc_set_spdif_fn = uaudio_set_spdif_cm6206;
1000 	else
1001 		sc->sc_set_spdif_fn = uaudio_set_spdif_dummy;
1002 
1003 	umidi_init(dev);
1004 
1005 	device_set_usb_desc(dev);
1006 
1007 	id = usbd_get_interface_descriptor(uaa->iface);
1008 
1009 	/* must fill mixer info before channel info */
1010 	uaudio_mixer_fill_info(sc, uaa->device, id);
1011 
1012 	/* fill channel info */
1013 	uaudio_chan_fill_info(sc, uaa->device);
1014 
1015 	DPRINTF("audio rev %d.%02x\n",
1016 	    sc->sc_audio_rev >> 8,
1017 	    sc->sc_audio_rev & 0xff);
1018 
1019 	if (sc->sc_mixer_count == 0) {
1020 		if (uaa->info.idVendor == USB_VENDOR_MAUDIO &&
1021 		    (uaa->info.idProduct == USB_PRODUCT_MAUDIO_FASTTRACKULTRA ||
1022 		    uaa->info.idProduct == USB_PRODUCT_MAUDIO_FASTTRACKULTRA8R)) {
1023 			DPRINTF("Generating mixer descriptors\n");
1024 			uaudio_mixer_controls_create_ftu(sc);
1025 		}
1026 	}
1027 
1028 	DPRINTF("%d mixer controls\n",
1029 	    sc->sc_mixer_count);
1030 
1031 	for (i = 0; i != UAUDIO_MAX_CHILD; i++) {
1032 		uint8_t x;
1033 
1034 		if (sc->sc_play_chan[i].num_alt <= 0)
1035 			break;
1036 
1037 		/*
1038 		 * Need to set a default alternate interface, else
1039 		 * some USB audio devices might go into an infinite
1040 		 * re-enumeration loop:
1041 		 */
1042 		err = uaudio_force_power_save(sc,
1043 		    sc->sc_play_chan[i].usb_alt[0].iface_index);
1044 		if (err) {
1045 			DPRINTF("setting of alternate index failed: %s!\n",
1046 			    usbd_errstr(err));
1047 		}
1048 
1049 		for (x = 0; x != sc->sc_play_chan[i].num_alt; x++) {
1050 			device_printf(dev, "Play[%u]: %d Hz, %d ch, %s format, "
1051 			    "2x%dms buffer.%s\n", i,
1052 			    sc->sc_play_chan[i].usb_alt[x].sample_rate,
1053 			    sc->sc_play_chan[i].usb_alt[x].channels,
1054 			    sc->sc_play_chan[i].usb_alt[x].p_fmt->description,
1055 			    uaudio_buffer_ms,
1056 			    (x == 0) ? " (selected)" : "");
1057 		}
1058 	}
1059 	if (i == 0)
1060 		device_printf(dev, "No playback.\n");
1061 
1062 	for (i = 0; i != UAUDIO_MAX_CHILD; i++) {
1063 		uint8_t x;
1064 
1065 		if (sc->sc_rec_chan[i].num_alt <= 0)
1066 			break;
1067 
1068 		/*
1069 		 * Need to set a default alternate interface, else
1070 		 * some USB audio devices might go into an infinite
1071 		 * re-enumeration loop:
1072 		 */
1073 		err = uaudio_force_power_save(sc,
1074 		    sc->sc_rec_chan[i].usb_alt[0].iface_index);
1075 		if (err) {
1076 			DPRINTF("setting of alternate index failed: %s!\n",
1077 			    usbd_errstr(err));
1078 		}
1079 
1080 		for (x = 0; x != sc->sc_rec_chan[i].num_alt; x++) {
1081 			device_printf(dev, "Record[%u]: %d Hz, %d ch, %s format, "
1082 			    "2x%dms buffer.%s\n", i,
1083 			    sc->sc_rec_chan[i].usb_alt[x].sample_rate,
1084 			    sc->sc_rec_chan[i].usb_alt[x].channels,
1085 			    sc->sc_rec_chan[i].usb_alt[x].p_fmt->description,
1086 			    uaudio_buffer_ms,
1087 			    (x == 0) ? " (selected)" : "");
1088 		}
1089 	}
1090 	if (i == 0)
1091 		device_printf(dev, "No recording.\n");
1092 
1093 	if (sc->sc_midi_chan.valid == 0) {
1094 		if (usbd_lookup_id_by_uaa(uaudio_vendor_midi,
1095 		    sizeof(uaudio_vendor_midi), uaa) == 0) {
1096 			sc->sc_midi_chan.iface_index =
1097 			    (uint8_t)uaa->driver_info;
1098 			sc->sc_midi_chan.iface_alt_index = 0;
1099 			sc->sc_midi_chan.valid = 1;
1100 		}
1101 	}
1102 
1103 	if (sc->sc_midi_chan.valid) {
1104 		if (umidi_probe(dev)) {
1105 			goto detach;
1106 		}
1107 		device_printf(dev, "MIDI sequencer.\n");
1108 	} else {
1109 		device_printf(dev, "No MIDI sequencer.\n");
1110 	}
1111 
1112 	DPRINTF("doing child attach\n");
1113 
1114 	/* attach the children */
1115 
1116 	sc->sc_sndcard_func.func = SCF_PCM;
1117 
1118 	/*
1119 	 * Only attach a PCM device if we have a playback, recording
1120 	 * or mixer device present:
1121 	 */
1122 	for (i = 0; i != UAUDIO_MAX_CHILD; i++) {
1123 		if (sc->sc_play_chan[i].num_alt <= 0 &&
1124 		    sc->sc_rec_chan[i].num_alt <= 0 &&
1125 		    sc->sc_child[i].mix_info == 0)
1126 			continue;
1127 		sc->sc_child[i].pcm_device =
1128 		    device_add_child(dev, "pcm", DEVICE_UNIT_ANY);
1129 
1130 		if (sc->sc_child[i].pcm_device == NULL) {
1131 			DPRINTF("out of memory\n");
1132 			goto detach;
1133 		}
1134 		device_set_ivars(sc->sc_child[i].pcm_device,
1135 		    &sc->sc_sndcard_func);
1136 	}
1137 
1138 	bus_attach_children(dev);
1139 
1140 	if (uaudio_handle_hid) {
1141 		if (uaudio_hid_probe(sc, uaa) == 0) {
1142 			device_printf(dev, "HID volume keys found.\n");
1143 		} else {
1144 			device_printf(dev, "No HID volume keys found.\n");
1145 		}
1146 	}
1147 
1148 	/* reload all mixer settings */
1149 	uaudio_mixer_reload_all(sc);
1150 
1151 	/* enable S/PDIF output, if any */
1152 	if (sc->sc_set_spdif_fn(sc,
1153 	    UAUDIO_SPDIF_OUT | UAUDIO_SPDIF_OUT_48K) != 0) {
1154 		device_printf(dev, "Failed to enable S/PDIF at 48K\n");
1155 	}
1156 	return (0);			/* success */
1157 
1158 detach:
1159 	uaudio_detach(dev);
1160 	return (ENXIO);
1161 }
1162 
1163 static void
uaudio_pcm_setflags(device_t dev,uint32_t flags)1164 uaudio_pcm_setflags(device_t dev, uint32_t flags)
1165 {
1166 	pcm_setflags(dev, pcm_getflags(dev) | flags);
1167 }
1168 
1169 int
uaudio_attach_sub(device_t dev,kobj_class_t mixer_class,kobj_class_t chan_class)1170 uaudio_attach_sub(device_t dev, kobj_class_t mixer_class, kobj_class_t chan_class)
1171 {
1172 	struct uaudio_softc *sc = device_get_softc(device_get_parent(dev));
1173 	unsigned i = uaudio_get_child_index_by_dev(sc, dev);
1174 	char status[SND_STATUSLEN];
1175 
1176 	uaudio_mixer_init(sc, i);
1177 
1178 	if (sc->sc_uq_audio_swap_lr) {
1179 		DPRINTF("hardware has swapped left and right\n");
1180 		/* uaudio_pcm_setflags(dev, SD_F_PSWAPLR); */
1181 	}
1182 	if (sc->sc_play_chan[i].num_alt > 0 &&
1183 	    (sc->sc_child[i].mix_info & SOUND_MASK_PCM) == 0) {
1184 		DPRINTF("software controlled main volume\n");
1185 
1186 		/*
1187 		 * Emulate missing pcm mixer controller
1188 		 * through FEEDER_VOLUME
1189 		 */
1190 		uaudio_pcm_setflags(dev, SD_F_SOFTPCMVOL);
1191 	}
1192 	if (sc->sc_pcm_bitperfect) {
1193 		DPRINTF("device needs bitperfect by default\n");
1194 		uaudio_pcm_setflags(dev, SD_F_BITPERFECT);
1195 	}
1196 	if (mixer_init(dev, mixer_class, sc))
1197 		goto detach;
1198 	sc->sc_child[i].mixer_init = 1;
1199 
1200 	mixer_hwvol_init(dev);
1201 
1202 	device_set_descf(dev, "%s %s",
1203 	    usb_get_manufacturer(sc->sc_udev),
1204 	    usb_get_product(sc->sc_udev));
1205 
1206 	snprintf(status, sizeof(status), "on %s",
1207 	    device_get_nameunit(device_get_parent(dev)));
1208 
1209 	pcm_init(dev, sc);
1210 
1211 	uaudio_pcm_setflags(dev, SD_F_MPSAFE);
1212 
1213 	if (sc->sc_play_chan[i].num_alt > 0) {
1214 		sc->sc_play_chan[i].priv_sc = sc;
1215 		pcm_addchan(dev, PCMDIR_PLAY, chan_class,
1216 		    &sc->sc_play_chan[i]);
1217 	}
1218 
1219 	if (sc->sc_rec_chan[i].num_alt > 0) {
1220 		sc->sc_rec_chan[i].priv_sc = sc;
1221 		pcm_addchan(dev, PCMDIR_REC, chan_class,
1222 		    &sc->sc_rec_chan[i]);
1223 	}
1224 	if (pcm_register(dev, status))
1225 		goto detach;
1226 	sc->sc_child[i].pcm_registered = 1;
1227 
1228 	uaudio_mixer_register_sysctl(sc, dev, i);
1229 
1230 	SYSCTL_ADD_INT(device_get_sysctl_ctx(dev),
1231 	    SYSCTL_CHILDREN(device_get_sysctl_tree(dev)), OID_AUTO,
1232 	    "feedback_rate", CTLFLAG_RD, &sc->sc_play_chan[i].feedback_rate,
1233 	    0, "Feedback sample rate in Hz");
1234 
1235 	return (0);			/* success */
1236 
1237 detach:
1238 	uaudio_detach_sub(dev);
1239 	return (ENXIO);
1240 }
1241 
1242 int
uaudio_detach_sub(device_t dev)1243 uaudio_detach_sub(device_t dev)
1244 {
1245 	struct uaudio_softc *sc = device_get_softc(device_get_parent(dev));
1246 	unsigned i = uaudio_get_child_index_by_dev(sc, dev);
1247 	int error = 0;
1248 
1249 	if (sc->sc_child[i].pcm_registered) {
1250 		error = pcm_unregister(dev);
1251 	} else if (sc->sc_child[i].mixer_init) {
1252 		error = mixer_uninit(dev);
1253 	}
1254 
1255 	return (error);
1256 }
1257 
1258 static int
uaudio_detach(device_t dev)1259 uaudio_detach(device_t dev)
1260 {
1261 	struct uaudio_softc *sc = device_get_softc(dev);
1262 	unsigned i;
1263 
1264 	/*
1265 	 * Stop USB transfers early so that any audio applications
1266 	 * will time out and close opened /dev/dspX.Y device(s), if
1267 	 * any.
1268 	 */
1269 	usb_proc_explore_lock(sc->sc_udev);
1270 	for (i = 0; i != UAUDIO_MAX_CHILD; i++) {
1271 		sc->sc_play_chan[i].operation = CHAN_OP_DRAIN;
1272 		sc->sc_rec_chan[i].operation = CHAN_OP_DRAIN;
1273 	}
1274 	usb_proc_explore_mwait(sc->sc_udev,
1275 	    &sc->sc_config_msg[0], &sc->sc_config_msg[1]);
1276 	usb_proc_explore_unlock(sc->sc_udev);
1277 
1278 	for (i = 0; i != UAUDIO_MAX_CHILD; i++) {
1279 		usbd_transfer_unsetup(sc->sc_play_chan[i].xfer, UAUDIO_NCHANBUFS + 1);
1280 		usbd_transfer_unsetup(sc->sc_rec_chan[i].xfer, UAUDIO_NCHANBUFS + 1);
1281 	}
1282 
1283 	uaudio_hid_detach(sc);
1284 
1285 	if (bus_generic_detach(dev) != 0) {
1286 		DPRINTF("detach failed!\n");
1287 	}
1288 
1289 	umidi_detach(dev);
1290 
1291 	/* free mixer data */
1292 
1293 	uaudio_mixer_ctl_free(sc);
1294 
1295 	/* disable S/PDIF output, if any */
1296 	(void) sc->sc_set_spdif_fn(sc, 0);
1297 
1298 	return (0);
1299 }
1300 
1301 static uint32_t
uaudio_get_interval_frames(const usb_endpoint_descriptor_audio_t * ed)1302 uaudio_get_interval_frames(const usb_endpoint_descriptor_audio_t *ed)
1303 {
1304 	uint32_t frames = 1;
1305 	/* Isochronous transfer interval is 2^(bInterval - 1) frames. */
1306 	if (ed->bInterval >= 1 && ed->bInterval <= 16)
1307 		frames = (1 << (ed->bInterval - 1));
1308 	/* Limit transfer interval to maximum number of frames. */
1309 	if (frames > UAUDIO_NFRAMES)
1310 		frames = UAUDIO_NFRAMES;
1311 	return (frames);
1312 }
1313 
1314 static uint32_t
uaudio_get_buffer_ms(struct uaudio_softc * sc,uint32_t int_frames)1315 uaudio_get_buffer_ms(struct uaudio_softc *sc, uint32_t int_frames)
1316 {
1317 	uint32_t ms = 1;
1318 	uint32_t fps = usbd_get_isoc_fps(sc->sc_udev);
1319 	/* Make sure a whole USB transfer interval fits into the buffer. */
1320 	if (fps >= 1000 && int_frames > 0 && int_frames <= UAUDIO_NFRAMES) {
1321 		/* Convert interval frames to milliseconds. */
1322 		ms = ((int_frames * 1000) / fps);
1323 	}
1324 	/* Respect minimum buffer length set through buffer_ms tunable. */
1325 	if (ms < uaudio_buffer_ms)
1326 		ms = uaudio_buffer_ms;
1327 	/* Limit buffer length to 8 milliseconds. */
1328 	if (ms > UAUDIO_BUFFER_MS_MAX)
1329 		ms = UAUDIO_BUFFER_MS_MAX;
1330 	return (ms);
1331 }
1332 
1333 static uint32_t
uaudio_get_buffer_size(struct uaudio_chan * ch,uint8_t alt)1334 uaudio_get_buffer_size(struct uaudio_chan *ch, uint8_t alt)
1335 {
1336 	struct uaudio_chan_alt *chan_alt = &ch->usb_alt[alt];
1337 	uint32_t int_frames, ms, buf_size;
1338 	/* USB transfer interval in frames, from endpoint descriptor. */
1339 	int_frames = uaudio_get_interval_frames(chan_alt->p_ed1);
1340 	/* Buffer length in milliseconds, and in bytes of audio data. */
1341 	ms = uaudio_get_buffer_ms(ch->priv_sc, int_frames);
1342 	buf_size = chan_alt->sample_size *
1343 	    howmany(chan_alt->sample_rate * ms, 1000);
1344 	return (buf_size);
1345 }
1346 
1347 static uint32_t
uaudio_max_buffer_size(struct uaudio_chan * ch,uint8_t alt)1348 uaudio_max_buffer_size(struct uaudio_chan *ch, uint8_t alt)
1349 {
1350 	struct uaudio_chan_alt *chan_alt = &ch->usb_alt[alt];
1351 	uint32_t buf_size;
1352 	/* Maximum buffer length is 8 milliseconds. */
1353 	buf_size = chan_alt->sample_size *
1354 	    howmany(chan_alt->sample_rate * UAUDIO_BUFFER_MS_MAX, 1000);
1355 	return (buf_size);
1356 }
1357 
1358 static void
uaudio_configure_msg_sub(struct uaudio_softc * sc,struct uaudio_chan * chan,int dir)1359 uaudio_configure_msg_sub(struct uaudio_softc *sc,
1360     struct uaudio_chan *chan, int dir)
1361 {
1362 	struct uaudio_chan_alt *chan_alt;
1363 	uint32_t frames;
1364 	uint32_t buf_size;
1365 	uint16_t fps;
1366 	uint8_t next_alt;
1367 	uint8_t fps_shift;
1368 	uint8_t operation;
1369 	usb_error_t err;
1370 
1371 	if (chan->num_alt <= 0)
1372 		return;
1373 
1374 	DPRINTF("\n");
1375 
1376 	usb_proc_explore_lock(sc->sc_udev);
1377 	operation = chan->operation;
1378 	switch (operation) {
1379 	case CHAN_OP_START:
1380 	case CHAN_OP_STOP:
1381 		chan->operation = CHAN_OP_NONE;
1382 		break;
1383 	default:
1384 		break;
1385 	}
1386 	usb_proc_explore_unlock(sc->sc_udev);
1387 
1388 	switch (operation) {
1389 	case CHAN_OP_STOP:
1390 		/* Unsetup prior USB transfers, if any. */
1391 		usbd_transfer_unsetup(chan->xfer, UAUDIO_NCHANBUFS + 1);
1392 
1393 		mtx_lock(chan->pcm_mtx);
1394 		chan->cur_alt = CHAN_MAX_ALT;
1395 		mtx_unlock(chan->pcm_mtx);
1396 
1397 		/*
1398 		 * The first alternate setting is typically used for
1399 		 * power saving mode. Set this alternate setting as
1400 		 * part of entering stop.
1401 		 */
1402 		err = usbd_set_alt_interface_index(sc->sc_udev, chan->iface_index, 0);
1403 		if (err) {
1404 			DPRINTF("setting of default alternate index failed: %s!\n",
1405 			    usbd_errstr(err));
1406 		}
1407 		return;
1408 
1409 	case CHAN_OP_START:
1410 		/* Unsetup prior USB transfers, if any. */
1411 		usbd_transfer_unsetup(chan->xfer, UAUDIO_NCHANBUFS + 1);
1412 		break;
1413 
1414 	default:
1415 		return;
1416 	}
1417 
1418 	mtx_lock(chan->pcm_mtx);
1419 	next_alt = chan->set_alt;
1420 	mtx_unlock(chan->pcm_mtx);
1421 
1422 	chan_alt = chan->usb_alt + next_alt;
1423 
1424 	err = usbd_set_alt_interface_index(sc->sc_udev,
1425 	    chan_alt->iface_index, chan_alt->iface_alt_index);
1426 	if (err) {
1427 		DPRINTF("setting of alternate index failed: %s!\n",
1428 		    usbd_errstr(err));
1429 		goto error;
1430 	}
1431 
1432 	/*
1433 	 * Only set the sample rate if the channel reports that it
1434 	 * supports the frequency control.
1435 	 */
1436 
1437 	if (sc->sc_audio_rev >= UAUDIO_VERSION_30) {
1438 		/* FALLTHROUGH */
1439 	} else if (sc->sc_audio_rev >= UAUDIO_VERSION_20) {
1440 		unsigned int x;
1441 
1442 		for (x = 0; x != 256; x++) {
1443 			if (dir == PCMDIR_PLAY) {
1444 				if (!(sc->sc_mixer_clocks.bit_output[x / 8] &
1445 				    (1 << (x % 8)))) {
1446 					continue;
1447 				}
1448 			} else {
1449 				if (!(sc->sc_mixer_clocks.bit_input[x / 8] &
1450 				    (1 << (x % 8)))) {
1451 					continue;
1452 				}
1453 			}
1454 
1455 			if (uaudio20_set_speed(sc->sc_udev,
1456 			    sc->sc_mixer_iface_no, x, chan_alt->sample_rate)) {
1457 				/*
1458 				 * If the endpoint is adaptive setting
1459 				 * the speed may fail.
1460 				 */
1461 				DPRINTF("setting of sample rate failed! "
1462 				    "(continuing anyway)\n");
1463 			}
1464 		}
1465 	} else if (chan_alt->p_sed.v1->bmAttributes & UA_SED_FREQ_CONTROL) {
1466 		if (uaudio_set_speed(sc->sc_udev,
1467 		    chan_alt->p_ed1->bEndpointAddress, chan_alt->sample_rate)) {
1468 			/*
1469 			 * If the endpoint is adaptive setting the
1470 			 * speed may fail.
1471 			 */
1472 			DPRINTF("setting of sample rate failed! "
1473 			    "(continuing anyway)\n");
1474 		}
1475 	}
1476 	if (usbd_transfer_setup(sc->sc_udev, &chan_alt->iface_index, chan->xfer,
1477 	    chan_alt->usb_cfg, UAUDIO_NCHANBUFS + 1, chan, chan->pcm_mtx)) {
1478 		DPRINTF("could not allocate USB transfers!\n");
1479 		goto error;
1480 	}
1481 
1482 	fps = usbd_get_isoc_fps(sc->sc_udev);
1483 
1484 	if (fps < 8000) {
1485 		/* FULL speed USB */
1486 		frames = uaudio_buffer_ms;
1487 	} else {
1488 		/* HIGH speed USB */
1489 		frames = uaudio_buffer_ms * 8;
1490 	}
1491 
1492 	fps_shift = usbd_xfer_get_fps_shift(chan->xfer[0]);
1493 
1494 	/* down shift number of frames per second, if any */
1495 	fps >>= fps_shift;
1496 	frames >>= fps_shift;
1497 
1498 	/* bytes per frame should not be zero */
1499 	chan->bytes_per_frame[0] =
1500 	    ((chan_alt->sample_rate / fps) * chan_alt->sample_size);
1501 	chan->bytes_per_frame[1] = howmany(chan_alt->sample_rate, fps) *
1502 	    chan_alt->sample_size;
1503 
1504 	/* setup data rate dithering, if any */
1505 	chan->frames_per_second = fps;
1506 	chan->sample_rem = chan_alt->sample_rate % fps;
1507 	chan->sample_curr = 0;
1508 
1509 	/* compute required buffer size */
1510 	buf_size = (chan->bytes_per_frame[1] * frames);
1511 
1512 	if (buf_size > (chan->end - chan->start)) {
1513 		DPRINTF("buffer size is too big\n");
1514 		goto error;
1515 	}
1516 
1517 	chan->intr_frames = frames;
1518 
1519 	DPRINTF("fps=%d sample_rem=%d\n", (int)fps, (int)chan->sample_rem);
1520 
1521 	if (chan->intr_frames == 0) {
1522 		DPRINTF("frame shift is too high!\n");
1523 		goto error;
1524 	}
1525 
1526 #if (UAUDIO_NCHANBUFS != 2)
1527 #error "Please update code below!"
1528 #endif
1529 
1530 	mtx_lock(chan->pcm_mtx);
1531 	chan->cur_alt = next_alt;
1532 	usbd_transfer_start(chan->xfer[0]);
1533 	usbd_transfer_start(chan->xfer[1]);
1534 	mtx_unlock(chan->pcm_mtx);
1535 	return;
1536 error:
1537 	usbd_transfer_unsetup(chan->xfer, UAUDIO_NCHANBUFS + 1);
1538 
1539 	mtx_lock(chan->pcm_mtx);
1540 	chan->cur_alt = CHAN_MAX_ALT;
1541 	mtx_unlock(chan->pcm_mtx);
1542 }
1543 
1544 static void
uaudio_configure_msg(struct usb_proc_msg * pm)1545 uaudio_configure_msg(struct usb_proc_msg *pm)
1546 {
1547 	struct uaudio_softc *sc = ((struct uaudio_configure_msg *)pm)->sc;
1548 	unsigned i;
1549 
1550 	usb_proc_explore_unlock(sc->sc_udev);
1551 	for (i = 0; i != UAUDIO_MAX_CHILD; i++) {
1552 		uaudio_configure_msg_sub(sc, &sc->sc_play_chan[i], PCMDIR_PLAY);
1553 		uaudio_configure_msg_sub(sc, &sc->sc_rec_chan[i], PCMDIR_REC);
1554 	}
1555 	usb_proc_explore_lock(sc->sc_udev);
1556 }
1557 
1558 /*========================================================================*
1559  * AS - Audio Stream - routines
1560  *========================================================================*/
1561 
1562 #ifdef USB_DEBUG
1563 static void
uaudio_chan_dump_ep_desc(const usb_endpoint_descriptor_audio_t * ed)1564 uaudio_chan_dump_ep_desc(const usb_endpoint_descriptor_audio_t *ed)
1565 {
1566 	if (ed) {
1567 		DPRINTF("endpoint=%p bLength=%d bDescriptorType=%d \n"
1568 		    "bEndpointAddress=%d bmAttributes=0x%x \n"
1569 		    "wMaxPacketSize=%d bInterval=%d \n"
1570 		    "bRefresh=%d bSynchAddress=%d\n",
1571 		    ed, ed->bLength, ed->bDescriptorType,
1572 		    ed->bEndpointAddress, ed->bmAttributes,
1573 		    UGETW(ed->wMaxPacketSize), ed->bInterval,
1574 		    UEP_HAS_REFRESH(ed) ? ed->bRefresh : 0,
1575 		    UEP_HAS_SYNCADDR(ed) ? ed->bSynchAddress : 0);
1576 	}
1577 }
1578 
1579 #endif
1580 
1581 /*
1582  * The following is a workaround for broken no-name USB audio devices
1583  * sold by dealextreme called "3D sound". The problem is that the
1584  * manufacturer computed wMaxPacketSize is too small to hold the
1585  * actual data sent. In other words the device sometimes sends more
1586  * data than it actually reports it can send in a single isochronous
1587  * packet.
1588  */
1589 static void
uaudio_record_fix_fs(usb_endpoint_descriptor_audio_t * ep,uint32_t xps,uint32_t add)1590 uaudio_record_fix_fs(usb_endpoint_descriptor_audio_t *ep,
1591     uint32_t xps, uint32_t add)
1592 {
1593 	uint32_t mps;
1594 
1595 	mps = UGETW(ep->wMaxPacketSize);
1596 
1597 	/*
1598 	 * If the device indicates it can send more data than what the
1599 	 * sample rate indicates, we apply the workaround.
1600 	 */
1601 	if (mps > xps) {
1602 		/* allow additional data */
1603 		xps += add;
1604 
1605 		/* check against the maximum USB 1.x length */
1606 		if (xps > 1023)
1607 			xps = 1023;
1608 
1609 		/* check if we should do an update */
1610 		if (mps < xps) {
1611 			/* simply update the wMaxPacketSize field */
1612 			USETW(ep->wMaxPacketSize, xps);
1613 			DPRINTF("Workaround: Updated wMaxPacketSize "
1614 			    "from %d to %d bytes.\n",
1615 			    (int)mps, (int)xps);
1616 		}
1617 	}
1618 }
1619 
1620 static usb_error_t
uaudio20_check_rate(struct usb_device * udev,uint8_t iface_no,uint8_t clockid,uint32_t rate)1621 uaudio20_check_rate(struct usb_device *udev, uint8_t iface_no,
1622     uint8_t clockid, uint32_t rate)
1623 {
1624 	struct usb_device_request req;
1625 	usb_error_t error;
1626 #define	UAUDIO20_MAX_RATES 32	/* we support at maximum 32 rates */
1627 	uint8_t data[2 + UAUDIO20_MAX_RATES * 12];
1628 	uint16_t actlen;
1629 	uint16_t rates;
1630 	uint16_t x;
1631 
1632 	DPRINTFN(6, "ifaceno=%d clockid=%d rate=%u\n",
1633 	    iface_no, clockid, rate);
1634 
1635 	req.bmRequestType = UT_READ_CLASS_INTERFACE;
1636 	req.bRequest = UA20_CS_RANGE;
1637 	USETW2(req.wValue, UA20_CS_SAM_FREQ_CONTROL, 0);
1638 	USETW2(req.wIndex, clockid, iface_no);
1639 	/*
1640 	 * Assume there is at least one rate to begin with, else some
1641 	 * devices might refuse to return the USB descriptor:
1642 	 */
1643 	USETW(req.wLength, (2 + 1 * 12));
1644 
1645 	error = usbd_do_request_flags(udev, NULL, &req, data,
1646 	    USB_SHORT_XFER_OK, &actlen, USB_DEFAULT_TIMEOUT);
1647 
1648 	if (error != 0 || actlen < 2) {
1649 		/*
1650 		 * Likely the descriptor doesn't fit into the supplied
1651 		 * buffer. Try using a larger buffer and see if that
1652 		 * helps:
1653 		 */
1654 		rates = MIN(UAUDIO20_MAX_RATES, (255 - 2) / 12);
1655 		error = USB_ERR_INVAL;
1656 	} else {
1657 		rates = UGETW(data);
1658 
1659 		if (rates > UAUDIO20_MAX_RATES) {
1660 			DPRINTF("Too many rates truncating to %d\n", UAUDIO20_MAX_RATES);
1661 			rates = UAUDIO20_MAX_RATES;
1662 			error = USB_ERR_INVAL;
1663 		} else if (rates > 1) {
1664 			DPRINTF("Need to read full rate descriptor\n");
1665 			error = USB_ERR_INVAL;
1666 		}
1667 	}
1668 
1669 	if (error != 0) {
1670 		/*
1671 		 * Try to read full rate descriptor.
1672 		 */
1673 		actlen = (2 + rates * 12);
1674 
1675 		USETW(req.wLength, actlen);
1676 
1677 	        error = usbd_do_request_flags(udev, NULL, &req, data,
1678 		    USB_SHORT_XFER_OK, &actlen, USB_DEFAULT_TIMEOUT);
1679 
1680 		if (error != 0 || actlen < 2)
1681 			return (USB_ERR_INVAL);
1682 
1683 		rates = UGETW(data);
1684 	}
1685 
1686 	actlen = (actlen - 2) / 12;
1687 
1688 	if (rates > actlen) {
1689 		DPRINTF("Too many rates truncating to %d\n", actlen);
1690 		rates = actlen;
1691 	}
1692 
1693 	for (x = 0; x != rates; x++) {
1694 		uint32_t min = UGETDW(data + 2 + (12 * x));
1695 		uint32_t max = UGETDW(data + 6 + (12 * x));
1696 		uint32_t res = UGETDW(data + 10 + (12 * x));
1697 
1698 		if (res == 0) {
1699 			DPRINTF("Zero residue\n");
1700 			res = 1;
1701 		}
1702 
1703 		if (min > max) {
1704 			DPRINTF("Swapped max and min\n");
1705 			uint32_t temp;
1706 			temp = min;
1707 			min = max;
1708 			max = temp;
1709 		}
1710 
1711 		if (rate >= min && rate <= max &&
1712 		    (((rate - min) % res) == 0)) {
1713 			return (0);
1714 		}
1715 	}
1716 	return (USB_ERR_INVAL);
1717 }
1718 
1719 static struct uaudio_chan *
uaudio_get_chan(struct uaudio_softc * sc,struct uaudio_chan * chan,uint8_t iface_index)1720 uaudio_get_chan(struct uaudio_softc *sc, struct uaudio_chan *chan,
1721     uint8_t iface_index)
1722 {
1723 	unsigned i;
1724 
1725 	for (i = 0; i != UAUDIO_MAX_CHILD; i++, chan++) {
1726 		if (chan->num_alt == 0) {
1727 			chan->iface_index = iface_index;
1728 			return (chan);
1729 		} else if (chan->iface_index == iface_index)
1730 			return (chan);
1731 	}
1732 	return (NULL);
1733 }
1734 
1735 static void
uaudio_chan_fill_info_sub(struct uaudio_softc * sc,struct usb_device * udev,uint32_t rate,uint8_t channels,uint8_t bit_resolution)1736 uaudio_chan_fill_info_sub(struct uaudio_softc *sc, struct usb_device *udev,
1737     uint32_t rate, uint8_t channels, uint8_t bit_resolution)
1738 {
1739 	struct usb_descriptor *desc = NULL;
1740 	union uaudio_asid asid = { NULL };
1741 	union uaudio_asf1d asf1d = { NULL };
1742 	union uaudio_sed sed = { NULL };
1743 	struct usb_midi_streaming_endpoint_descriptor *msid = NULL;
1744 	usb_endpoint_descriptor_audio_t *ed1 = NULL;
1745 	const struct usb_audio_control_descriptor *acdp = NULL;
1746 	struct usb_config_descriptor *cd = usbd_get_config_descriptor(udev);
1747 	struct usb_interface_descriptor *id;
1748 	const struct uaudio_format *p_fmt = NULL;
1749 	struct uaudio_chan *chan;
1750 	struct uaudio_chan_alt *chan_alt;
1751 	uint32_t format;
1752 	uint16_t curidx = 0xFFFF;
1753 	uint16_t lastidx = 0xFFFF;
1754 	uint16_t alt_index = 0;
1755 	uint16_t audio_rev = 0;
1756 	uint16_t x;
1757 	uint8_t ep_dir;
1758 	uint8_t bChannels;
1759 	uint8_t bBitResolution;
1760 	uint8_t audio_if = 0;
1761 	uint8_t midi_if = 0;
1762 	uint8_t uma_if_class;
1763 
1764 	while ((desc = usb_desc_foreach(cd, desc))) {
1765 		if ((desc->bDescriptorType == UDESC_INTERFACE) &&
1766 		    (desc->bLength >= sizeof(*id))) {
1767 			id = (void *)desc;
1768 
1769 			if (id->bInterfaceNumber != lastidx) {
1770 				lastidx = id->bInterfaceNumber;
1771 				curidx++;
1772 				alt_index = 0;
1773 
1774 			} else {
1775 				alt_index++;
1776 			}
1777 
1778 			if ((!(sc->sc_hid.flags & UAUDIO_HID_VALID)) &&
1779 			    (id->bInterfaceClass == UICLASS_HID) &&
1780 			    (id->bInterfaceSubClass == 0) &&
1781 			    (id->bInterfaceProtocol == 0) &&
1782 			    (alt_index == 0) &&
1783 			    usbd_get_iface(udev, curidx) != NULL) {
1784 				DPRINTF("Found HID interface at %d\n",
1785 				    curidx);
1786 				sc->sc_hid.flags |= UAUDIO_HID_VALID;
1787 				sc->sc_hid.iface_index = curidx;
1788 			}
1789 
1790 			uma_if_class =
1791 			    ((id->bInterfaceClass == UICLASS_AUDIO) ||
1792 			    ((id->bInterfaceClass == UICLASS_VENDOR) &&
1793 			    (sc->sc_uq_au_vendor_class != 0)));
1794 
1795 			if ((uma_if_class != 0) &&
1796 			    (id->bInterfaceSubClass == UISUBCLASS_AUDIOSTREAM)) {
1797 				audio_if = 1;
1798 			} else {
1799 				audio_if = 0;
1800 			}
1801 
1802 			if ((uma_if_class != 0) &&
1803 			    (id->bInterfaceSubClass == UISUBCLASS_MIDISTREAM)) {
1804 				/*
1805 				 * XXX could allow multiple MIDI interfaces
1806 				 */
1807 				midi_if = 1;
1808 
1809 				if ((sc->sc_midi_chan.valid == 0) &&
1810 				    (usbd_get_iface(udev, curidx) != NULL)) {
1811 					sc->sc_midi_chan.iface_index = curidx;
1812 					sc->sc_midi_chan.iface_alt_index = alt_index;
1813 					sc->sc_midi_chan.valid = 1;
1814 				}
1815 			} else {
1816 				midi_if = 0;
1817 			}
1818 			asid.v1 = NULL;
1819 			asf1d.v1 = NULL;
1820 			ed1 = NULL;
1821 			sed.v1 = NULL;
1822 
1823 			/*
1824 			 * There can only be one USB audio instance
1825 			 * per USB device. Grab all USB audio
1826 			 * interfaces on this USB device so that we
1827 			 * don't attach USB audio twice:
1828 			 */
1829 			if (alt_index == 0 && curidx != sc->sc_mixer_iface_index &&
1830 			    (id->bInterfaceClass == UICLASS_AUDIO || audio_if != 0 ||
1831 			    midi_if != 0)) {
1832 				usbd_set_parent_iface(sc->sc_udev, curidx,
1833 				    sc->sc_mixer_iface_index);
1834 			}
1835 		}
1836 
1837 		if (audio_if == 0) {
1838 			if (midi_if == 0) {
1839 				if ((acdp == NULL) &&
1840 				    (desc->bDescriptorType == UDESC_CS_INTERFACE) &&
1841 				    (desc->bDescriptorSubtype == UDESCSUB_AC_HEADER) &&
1842 				    (desc->bLength >= sizeof(*acdp))) {
1843 					acdp = (void *)desc;
1844 					audio_rev = UGETW(acdp->bcdADC);
1845 				}
1846 			} else {
1847 				msid = (void *)desc;
1848 
1849 				/* get the maximum number of embedded jacks in use, if any */
1850 				if (msid->bLength >= sizeof(*msid) &&
1851 				    msid->bDescriptorType == UDESC_CS_ENDPOINT &&
1852 				    msid->bDescriptorSubtype == MS_GENERAL &&
1853 				    msid->bNumEmbMIDIJack > sc->sc_midi_chan.max_emb_jack) {
1854 					sc->sc_midi_chan.max_emb_jack = msid->bNumEmbMIDIJack;
1855 				}
1856 			}
1857 			/*
1858 			 * Don't collect any USB audio descriptors if
1859 			 * this is not an USB audio stream interface.
1860 			 */
1861 			continue;
1862 		}
1863 
1864 		if ((acdp != NULL || sc->sc_uq_au_vendor_class != 0) &&
1865 		    (desc->bDescriptorType == UDESC_CS_INTERFACE) &&
1866 		    (desc->bDescriptorSubtype == AS_GENERAL) &&
1867 		    (asid.v1 == NULL)) {
1868 			if (audio_rev >= UAUDIO_VERSION_30) {
1869 				/* FALLTHROUGH */
1870 			} else if (audio_rev >= UAUDIO_VERSION_20) {
1871 				if (desc->bLength >= sizeof(*asid.v2)) {
1872 					asid.v2 = (void *)desc;
1873 				}
1874 			} else {
1875 				if (desc->bLength >= sizeof(*asid.v1)) {
1876 					asid.v1 = (void *)desc;
1877 				}
1878 			}
1879 		}
1880 		if ((acdp != NULL || sc->sc_uq_au_vendor_class != 0) &&
1881 		    (desc->bDescriptorType == UDESC_CS_INTERFACE) &&
1882 		    (desc->bDescriptorSubtype == FORMAT_TYPE) &&
1883 		    (asf1d.v1 == NULL)) {
1884 			if (audio_rev >= UAUDIO_VERSION_30) {
1885 				/* FALLTHROUGH */
1886 			} else if (audio_rev >= UAUDIO_VERSION_20) {
1887 				if (desc->bLength >= sizeof(*asf1d.v2))
1888 					asf1d.v2 = (void *)desc;
1889 			} else {
1890 				if (desc->bLength >= sizeof(*asf1d.v1)) {
1891 					asf1d.v1 = (void *)desc;
1892 
1893 					if (asf1d.v1->bFormatType != FORMAT_TYPE_I) {
1894 						DPRINTFN(11, "ignored bFormatType = %d\n",
1895 						    asf1d.v1->bFormatType);
1896 						asf1d.v1 = NULL;
1897 						continue;
1898 					}
1899 					if (desc->bLength < (sizeof(*asf1d.v1) +
1900 					    ((asf1d.v1->bSamFreqType == 0) ? 6 :
1901 					    (asf1d.v1->bSamFreqType * 3)))) {
1902 						DPRINTFN(11, "invalid descriptor, "
1903 						    "too short\n");
1904 						asf1d.v1 = NULL;
1905 						continue;
1906 					}
1907 				}
1908 			}
1909 		}
1910 		if ((desc->bDescriptorType == UDESC_ENDPOINT) &&
1911 		    (desc->bLength >= UEP_MINSIZE) &&
1912 		    (ed1 == NULL)) {
1913 			ed1 = (void *)desc;
1914 			if (UE_GET_XFERTYPE(ed1->bmAttributes) != UE_ISOCHRONOUS) {
1915 				ed1 = NULL;
1916 				continue;
1917 			}
1918 		}
1919 		if ((acdp != NULL || sc->sc_uq_au_vendor_class != 0) &&
1920 		    (desc->bDescriptorType == UDESC_CS_ENDPOINT) &&
1921 		    (desc->bDescriptorSubtype == AS_GENERAL) &&
1922 		    (sed.v1 == NULL)) {
1923 			if (audio_rev >= UAUDIO_VERSION_30) {
1924 				/* FALLTHROUGH */
1925 			} else if (audio_rev >= UAUDIO_VERSION_20) {
1926 				if (desc->bLength >= sizeof(*sed.v2))
1927 					sed.v2 = (void *)desc;
1928 			} else {
1929 				if (desc->bLength >= sizeof(*sed.v1))
1930 					sed.v1 = (void *)desc;
1931 			}
1932 		}
1933 		if (asid.v1 == NULL || asf1d.v1 == NULL ||
1934 		    ed1 == NULL || sed.v1 == NULL) {
1935 			/* need more descriptors */
1936 			continue;
1937 		}
1938 
1939 		ep_dir = UE_GET_DIR(ed1->bEndpointAddress);
1940 
1941 		/* We ignore sync endpoint information until further. */
1942 
1943 		if (audio_rev >= UAUDIO_VERSION_30) {
1944 			goto next_ep;
1945 		} else if (audio_rev >= UAUDIO_VERSION_20) {
1946 			uint32_t dwFormat;
1947 
1948 			dwFormat = UGETDW(asid.v2->bmFormats);
1949 			bChannels = asid.v2->bNrChannels;
1950 			bBitResolution = asf1d.v2->bSubslotSize * 8;
1951 
1952 			if ((bChannels != channels) ||
1953 			    (bBitResolution != bit_resolution)) {
1954 				DPRINTF("Wrong number of channels\n");
1955 				goto next_ep;
1956 			}
1957 
1958 			for (p_fmt = uaudio20_formats;
1959 			    p_fmt->wFormat != 0; p_fmt++) {
1960 				if ((p_fmt->wFormat & dwFormat) &&
1961 				    (p_fmt->bPrecision == bBitResolution))
1962 					break;
1963 			}
1964 
1965 			if (p_fmt->wFormat == 0) {
1966 				DPRINTF("Unsupported audio format\n");
1967 				goto next_ep;
1968 			}
1969 
1970 			for (x = 0; x != 256; x++) {
1971 				if (ep_dir == UE_DIR_OUT) {
1972 					if (!(sc->sc_mixer_clocks.bit_output[x / 8] &
1973 					    (1 << (x % 8)))) {
1974 						continue;
1975 					}
1976 				} else {
1977 					if (!(sc->sc_mixer_clocks.bit_input[x / 8] &
1978 					    (1 << (x % 8)))) {
1979 						continue;
1980 					}
1981 				}
1982 
1983 				DPRINTF("Checking clock ID=%d\n", x);
1984 
1985 				if (uaudio20_check_rate(udev,
1986 				    sc->sc_mixer_iface_no, x, rate)) {
1987 					DPRINTF("Unsupported sampling "
1988 					    "rate, id=%d\n", x);
1989 					goto next_ep;
1990 				}
1991 			}
1992 		} else {
1993 			uint16_t wFormat;
1994 
1995 			wFormat = UGETW(asid.v1->wFormatTag);
1996 			bChannels = UAUDIO_MAX_CHAN(asf1d.v1->bNrChannels);
1997 			bBitResolution = asf1d.v1->bSubFrameSize * 8;
1998 
1999 			if (asf1d.v1->bSamFreqType == 0) {
2000 				DPRINTFN(16, "Sample rate: %d-%dHz\n",
2001 				    UA_SAMP_LO(asf1d.v1),
2002 				    UA_SAMP_HI(asf1d.v1));
2003 
2004 				if ((rate >= UA_SAMP_LO(asf1d.v1)) &&
2005 				    (rate <= UA_SAMP_HI(asf1d.v1)))
2006 					goto found_rate;
2007 			} else {
2008 				for (x = 0; x < asf1d.v1->bSamFreqType; x++) {
2009 					DPRINTFN(16, "Sample rate = %dHz\n",
2010 					    UA_GETSAMP(asf1d.v1, x));
2011 
2012 					if (rate == UA_GETSAMP(asf1d.v1, x))
2013 						goto found_rate;
2014 				}
2015 			}
2016 			goto next_ep;
2017 
2018 	found_rate:
2019 			for (p_fmt = uaudio10_formats;
2020 			    p_fmt->wFormat != 0; p_fmt++) {
2021 				if ((p_fmt->wFormat == wFormat) &&
2022 				    (p_fmt->bPrecision == bBitResolution))
2023 					break;
2024 			}
2025 			if (p_fmt->wFormat == 0) {
2026 				DPRINTF("Unsupported audio format\n");
2027 				goto next_ep;
2028 			}
2029 
2030 			if ((bChannels != channels) ||
2031 			    (bBitResolution != bit_resolution)) {
2032 				DPRINTF("Wrong number of channels\n");
2033 				goto next_ep;
2034 			}
2035 		}
2036 
2037 		chan = uaudio_get_chan(sc, (ep_dir == UE_DIR_OUT) ? &sc->sc_play_chan[0] :
2038 		    &sc->sc_rec_chan[0], curidx);
2039 		if (chan == NULL) {
2040 			DPRINTF("More than %d sub devices. (skipped)\n", UAUDIO_MAX_CHILD);
2041 			goto next_ep;
2042 		}
2043 
2044 		if (usbd_get_iface(udev, curidx) == NULL) {
2045 			DPRINTF("Interface is not valid\n");
2046 			goto next_ep;
2047 		}
2048 		if (chan->num_alt == CHAN_MAX_ALT) {
2049 			DPRINTF("Too many alternate settings\n");
2050 			goto next_ep;
2051 		}
2052 		chan->set_alt = 0;
2053 		chan->cur_alt = CHAN_MAX_ALT;
2054 
2055 		chan_alt = &chan->usb_alt[chan->num_alt++];
2056 
2057 #ifdef USB_DEBUG
2058 		uaudio_chan_dump_ep_desc(ed1);
2059 #endif
2060 		DPRINTF("Sample rate = %dHz, channels = %d, "
2061 		    "bits = %d, format = %s, ep 0x%02x, chan %p\n", rate, channels,
2062 		    bit_resolution, p_fmt->description, ed1->bEndpointAddress, chan);
2063 
2064 		chan_alt->sample_rate = rate;
2065 		chan_alt->p_asf1d = asf1d;
2066 		chan_alt->p_ed1 = ed1;
2067 		chan_alt->p_fmt = p_fmt;
2068 		chan_alt->p_sed = sed;
2069 		chan_alt->iface_index = curidx;
2070 		chan_alt->iface_alt_index = alt_index;
2071 
2072 		if (ep_dir == UE_DIR_IN)
2073 			chan_alt->usb_cfg = uaudio_cfg_record;
2074 		else
2075 			chan_alt->usb_cfg = uaudio_cfg_play;
2076 
2077 		chan_alt->sample_size = (UAUDIO_MAX_CHAN(channels) *
2078 		    p_fmt->bPrecision) / 8;
2079 		chan_alt->channels = channels;
2080 
2081 		if (ep_dir == UE_DIR_IN &&
2082 		    usbd_get_speed(udev) == USB_SPEED_FULL) {
2083 			uaudio_record_fix_fs(ed1,
2084 			    chan_alt->sample_size * (rate / 1000),
2085 			    chan_alt->sample_size * (rate / 4000));
2086 		}
2087 
2088 		/* setup play/record format */
2089 
2090 		format = chan_alt->p_fmt->freebsd_fmt;
2091 
2092 		/* get default SND_FORMAT() */
2093 		format = SND_FORMAT(format, chan_alt->channels, 0);
2094 
2095 		switch (chan_alt->channels) {
2096 		uint32_t temp_fmt;
2097 		case 1:
2098 		case 2:
2099 			/* mono and stereo */
2100 			break;
2101 		default:
2102 			/* surround and more */
2103 			temp_fmt = feeder_matrix_default_format(format);
2104 			/* if multichannel, then format can be zero */
2105 			if (temp_fmt != 0)
2106 				format = temp_fmt;
2107 			break;
2108 		}
2109 
2110 		/* check if format is not supported */
2111 		if (format == 0) {
2112 			DPRINTF("The selected audio format is not supported\n");
2113 			chan->num_alt--;
2114 			goto next_ep;
2115 		}
2116 		if (chan->num_alt > 1) {
2117 			/* we only accumulate one format at different sample rates */
2118 			if (chan->pcm_format[0] != format) {
2119 				DPRINTF("Multiple formats is not supported\n");
2120 				chan->num_alt--;
2121 				goto next_ep;
2122 			}
2123 			/* ignore if duplicate sample rate entry */
2124 			if (rate == chan->usb_alt[chan->num_alt - 2].sample_rate) {
2125 				DPRINTF("Duplicate sample rate detected\n");
2126 				chan->num_alt--;
2127 				goto next_ep;
2128 			}
2129 		}
2130 		chan->pcm_cap.fmtlist = chan->pcm_format;
2131 		chan->pcm_cap.fmtlist[0] = format;
2132 
2133 		/* check if device needs bitperfect */
2134 		if (chan_alt->channels > UAUDIO_MATRIX_MAX)
2135 			sc->sc_pcm_bitperfect = 1;
2136 
2137 		if (rate < chan->pcm_cap.minspeed || chan->pcm_cap.minspeed == 0)
2138 			chan->pcm_cap.minspeed = rate;
2139 		if (rate > chan->pcm_cap.maxspeed || chan->pcm_cap.maxspeed == 0)
2140 			chan->pcm_cap.maxspeed = rate;
2141 
2142 	next_ep:
2143 		sed.v1 = NULL;
2144 		ed1 = NULL;
2145 	}
2146 }
2147 
2148 /* This structure defines all the supported rates. */
2149 
2150 static const uint32_t uaudio_rate_list[CHAN_MAX_ALT] = {
2151 	384000,
2152 	352800,
2153 	192000,
2154 	176400,
2155 	96000,
2156 	88200,
2157 	88000,
2158 	80000,
2159 	72000,
2160 	64000,
2161 	56000,
2162 	48000,
2163 	44100,
2164 	40000,
2165 	32000,
2166 	24000,
2167 	22050,
2168 	16000,
2169 	11025,
2170 	8000,
2171 	0
2172 };
2173 
2174 static void
uaudio_chan_fill_info(struct uaudio_softc * sc,struct usb_device * udev)2175 uaudio_chan_fill_info(struct uaudio_softc *sc, struct usb_device *udev)
2176 {
2177 	uint32_t rate = uaudio_default_rate;
2178 	uint8_t z;
2179 	uint8_t bits = uaudio_default_bits;
2180 	uint8_t y;
2181 	uint8_t channels = uaudio_default_channels;
2182 	uint8_t channels_max;
2183 	uint8_t x;
2184 
2185 	bits -= (bits % 8);
2186 	if ((bits == 0) || (bits > UAUDIO_BITS_MAX)) {
2187 		/* set a valid value */
2188 		bits = UAUDIO_BITS_MAX;
2189 	}
2190 
2191 	if (channels > UAUDIO_CHANNELS_MAX)
2192 		channels = UAUDIO_CHANNELS_MAX;
2193 	switch (usbd_get_speed(udev)) {
2194 	case USB_SPEED_LOW:
2195 	case USB_SPEED_FULL:
2196 		/*
2197 		 * Due to high bandwidth usage and problems
2198 		 * with HIGH-speed split transactions we
2199 		 * disable surround setups on FULL-speed USB
2200 		 * by default
2201 		 */
2202 		channels_max = 4;
2203 		/* more channels on request */
2204 		if (channels > channels_max)
2205 			channels_max = channels;
2206 		break;
2207 	default:
2208 		channels_max = UAUDIO_CHANNELS_MAX;
2209 		break;
2210 	}
2211 	if (channels == 0)
2212 		channels = channels_max;
2213 
2214 	/* try to search for a valid config */
2215 
2216 	for (x = channels; x; x--) {
2217 		for (y = bits; y; y -= 8) {
2218 			/* try user defined rate, if any */
2219 			if (rate != 0)
2220 				uaudio_chan_fill_info_sub(sc, udev, rate, x, y);
2221 
2222 			/* try find a matching rate, if any */
2223 			for (z = 0; uaudio_rate_list[z]; z++) {
2224 				if (uaudio_rate_list[z] != rate)
2225 					uaudio_chan_fill_info_sub(sc, udev,
2226 					    uaudio_rate_list[z], x, y);
2227 			}
2228 
2229 			/* after default value in first round, proceed with max bits */
2230 			if (y == bits)
2231 				y = UAUDIO_BITS_MAX + 8;
2232 			/* skip default value subsequently */
2233 			if (y == (bits + 8))
2234 				y -= 8;
2235 		}
2236 
2237 		/* after default value in first round, proceed with max channels */
2238 		if (x == channels)
2239 			x = channels_max + 1;
2240 		/* skip default value subsequently */
2241 		if (x == (channels + 1))
2242 			x--;
2243 	}
2244 }
2245 
2246 static void
uaudio_chan_play_sync_callback(struct usb_xfer * xfer,usb_error_t error)2247 uaudio_chan_play_sync_callback(struct usb_xfer *xfer, usb_error_t error)
2248 {
2249 	struct uaudio_chan *ch = usbd_xfer_softc(xfer);
2250 	struct usb_page_cache *pc;
2251 	uint64_t sample_rate;
2252 	uint8_t buf[4];
2253 	uint64_t temp;
2254 	unsigned i;
2255 	int len;
2256 	int actlen;
2257 	int nframes;
2258 
2259 	usbd_xfer_status(xfer, &actlen, NULL, NULL, &nframes);
2260 
2261 	i = uaudio_get_child_index_by_chan(ch->priv_sc, ch);
2262 
2263 	switch (USB_GET_STATE(xfer)) {
2264 	case USB_ST_TRANSFERRED:
2265 
2266 		DPRINTFN(6, "transferred %d bytes\n", actlen);
2267 
2268 		if (nframes == 0)
2269 			break;
2270 		len = usbd_xfer_frame_len(xfer, 0);
2271 		if (len == 0)
2272 			break;
2273 		if (len > sizeof(buf))
2274 			len = sizeof(buf);
2275 
2276 		memset(buf, 0, sizeof(buf));
2277 
2278 		pc = usbd_xfer_get_frame(xfer, 0);
2279 		usbd_copy_out(pc, 0, buf, len);
2280 
2281 		temp = UGETDW(buf);
2282 
2283 		DPRINTF("Value = 0x%08x\n", (int)temp);
2284 
2285 		/* auto-detect SYNC format */
2286 
2287 		if (len == 4)
2288 			temp &= 0x0fffffff;
2289 
2290 		/* check for no data */
2291 
2292 		if (temp == 0)
2293 			break;
2294 
2295 		temp *= 125ULL;
2296 
2297 		sample_rate = ch->usb_alt[ch->cur_alt].sample_rate;
2298 
2299 		/* auto adjust */
2300 		while (temp < (sample_rate - (sample_rate / 4)))
2301 			temp *= 2;
2302 
2303 		while (temp > (sample_rate + (sample_rate / 2)))
2304 			temp /= 2;
2305 
2306 		DPRINTF("Comparing %d Hz :: %d Hz\n",
2307 		    (int)temp, (int)sample_rate);
2308 
2309 		/*
2310 		 * Use feedback value as fallback when there is no
2311 		 * recording channel:
2312 		 */
2313 		if (ch->priv_sc->sc_rec_chan[i].num_alt == 0) {
2314 			int32_t jitter_max = howmany(sample_rate, 16000);
2315 
2316 			/*
2317 			 * Range check the jitter values to avoid
2318 			 * bogus sample rate adjustments. The expected
2319 			 * deviation should not be more than 1Hz per
2320 			 * second. The USB v2.0 specification also
2321 			 * mandates this requirement. Refer to chapter
2322 			 * 5.12.4.2 about feedback.
2323 			 */
2324 			ch->jitter_curr = temp - sample_rate;
2325 			if (ch->jitter_curr > jitter_max)
2326 				ch->jitter_curr = jitter_max;
2327 			else if (ch->jitter_curr < -jitter_max)
2328 				ch->jitter_curr = -jitter_max;
2329 		}
2330 		ch->feedback_rate = temp;
2331 		break;
2332 
2333 	case USB_ST_SETUP:
2334 		/*
2335 		 * Check if the recording stream can be used as a
2336 		 * source of jitter information to save some
2337 		 * isochronous bandwidth:
2338 		 */
2339 		if (ch->priv_sc->sc_rec_chan[i].num_alt != 0 &&
2340 		    uaudio_debug == 0)
2341 			break;
2342 		usbd_xfer_set_frames(xfer, 1);
2343 		usbd_xfer_set_frame_len(xfer, 0, usbd_xfer_max_framelen(xfer));
2344 		usbd_transfer_submit(xfer);
2345 		break;
2346 
2347 	default:			/* Error */
2348 		break;
2349 	}
2350 }
2351 
2352 static int
uaudio_chan_is_async(struct uaudio_chan * ch,uint8_t alt)2353 uaudio_chan_is_async(struct uaudio_chan *ch, uint8_t alt)
2354 {
2355 	uint8_t attr = ch->usb_alt[alt].p_ed1->bmAttributes;
2356 	return (UE_GET_ISO_TYPE(attr) == UE_ISO_ASYNC);
2357 }
2358 
2359 static void
uaudio_chan_play_callback(struct usb_xfer * xfer,usb_error_t error)2360 uaudio_chan_play_callback(struct usb_xfer *xfer, usb_error_t error)
2361 {
2362 	struct uaudio_chan *ch = usbd_xfer_softc(xfer);
2363 	struct uaudio_chan *ch_rec;
2364 	struct usb_page_cache *pc;
2365 	uint32_t mfl;
2366 	uint32_t total;
2367 	uint32_t blockcount;
2368 	uint32_t n;
2369 	uint32_t offset;
2370 	unsigned i;
2371 	int sample_size;
2372 	int actlen;
2373 	int sumlen;
2374 
2375 	if (ch->running == 0 || ch->start == ch->end) {
2376 		DPRINTF("not running or no buffer!\n");
2377 		return;
2378 	}
2379 
2380 	i = uaudio_get_child_index_by_chan(ch->priv_sc, ch);
2381 
2382 	/* check if there is a valid record channel */
2383 	ch_rec = ch->priv_sc->sc_rec_chan + i;
2384 
2385 	if (ch_rec->num_alt == 0)
2386 		ch_rec = NULL;
2387 
2388 	usbd_xfer_status(xfer, &actlen, &sumlen, NULL, NULL);
2389 
2390 	switch (USB_GET_STATE(xfer)) {
2391 	case USB_ST_SETUP:
2392 tr_setup:
2393 		if (ch_rec != NULL) {
2394 			/*
2395 			 * NOTE: The play and record callbacks are
2396 			 * executed from the same USB thread and
2397 			 * locking the record channel mutex here is
2398 			 * not needed. This avoids a LOR situation.
2399 			 */
2400 
2401 			/* reset receive jitter counters */
2402 			ch_rec->jitter_curr = 0;
2403 			ch_rec->jitter_rem = 0;
2404 		}
2405 
2406 		/* reset transmit jitter counters */
2407 		ch->jitter_curr = 0;
2408 		ch->jitter_rem = 0;
2409 
2410 		/* FALLTHROUGH */
2411 	case USB_ST_TRANSFERRED:
2412 		if (actlen < sumlen) {
2413 			DPRINTF("short transfer, "
2414 			    "%d of %d bytes\n", actlen, sumlen);
2415 		}
2416 		chn_intr(ch->pcm_ch);
2417 
2418 		/*
2419 		 * Check for asynchronous playback endpoint and that
2420 		 * the playback endpoint is properly configured:
2421 		 */
2422 		if (ch_rec != NULL &&
2423 		    uaudio_chan_is_async(ch, ch->cur_alt) != 0) {
2424 			uint32_t rec_alt = ch_rec->cur_alt;
2425 			if (rec_alt < ch_rec->num_alt) {
2426 				int64_t tx_jitter;
2427 				int64_t rx_rate;
2428 				/*
2429 				 * NOTE: The play and record callbacks
2430 				 * are executed from the same USB
2431 				 * thread and locking the record
2432 				 * channel mutex here is not needed.
2433 				 * This avoids a LOR situation.
2434 				 */
2435 
2436 				/* translate receive jitter into transmit jitter */
2437 				tx_jitter = ch->usb_alt[ch->cur_alt].sample_rate;
2438 				tx_jitter = (tx_jitter * ch_rec->jitter_curr) +
2439 				    ch->jitter_rem;
2440 
2441 				/* reset receive jitter counters */
2442 				ch_rec->jitter_curr = 0;
2443 				ch_rec->jitter_rem = 0;
2444 
2445 				/* compute exact number of transmit jitter samples */
2446 				rx_rate = ch_rec->usb_alt[rec_alt].sample_rate;
2447 				ch->jitter_curr += tx_jitter / rx_rate;
2448 				ch->jitter_rem = tx_jitter % rx_rate;
2449 			}
2450 		}
2451 
2452 		/* start the SYNC transfer one time per second, if any */
2453 		ch->intr_counter += ch->intr_frames;
2454 		if (ch->intr_counter >= ch->frames_per_second) {
2455 			ch->intr_counter -= ch->frames_per_second;
2456 			usbd_transfer_start(ch->xfer[UAUDIO_NCHANBUFS]);
2457 		}
2458 
2459 		mfl = usbd_xfer_max_framelen(xfer);
2460 
2461 		if (ch->bytes_per_frame[1] > mfl) {
2462 			DPRINTF("bytes per transfer, %d, "
2463 			    "exceeds maximum, %d!\n",
2464 			    ch->bytes_per_frame[1],
2465 			    mfl);
2466 			break;
2467 		}
2468 
2469 		blockcount = ch->intr_frames;
2470 
2471 		/* setup number of frames */
2472 		usbd_xfer_set_frames(xfer, blockcount);
2473 
2474 		/* get sample size */
2475 		sample_size = ch->usb_alt[ch->cur_alt].sample_size;
2476 
2477 		/* reset total length */
2478 		total = 0;
2479 
2480 		/* setup frame lengths */
2481 		for (n = 0; n != blockcount; n++) {
2482 			uint32_t frame_len;
2483 
2484 			ch->sample_curr += ch->sample_rem;
2485 			if (ch->sample_curr >= ch->frames_per_second) {
2486 				ch->sample_curr -= ch->frames_per_second;
2487 				frame_len = ch->bytes_per_frame[1];
2488 			} else {
2489 				frame_len = ch->bytes_per_frame[0];
2490 			}
2491 
2492 			/* handle free running clock case */
2493 			if (ch->jitter_curr > 0 &&
2494 			    (frame_len + sample_size) <= mfl) {
2495 				DPRINTFN(6, "sending one sample more\n");
2496 				ch->jitter_curr--;
2497 				frame_len += sample_size;
2498 			} else if (ch->jitter_curr < 0 &&
2499 			    frame_len >= sample_size) {
2500 				DPRINTFN(6, "sending one sample less\n");
2501 				ch->jitter_curr++;
2502 				frame_len -= sample_size;
2503 			}
2504 			usbd_xfer_set_frame_len(xfer, n, frame_len);
2505 			total += frame_len;
2506 		}
2507 
2508 		DPRINTFN(6, "transferring %d bytes\n", total);
2509 
2510 		offset = 0;
2511 
2512 		pc = usbd_xfer_get_frame(xfer, 0);
2513 		while (total > 0) {
2514 			n = (ch->end - ch->cur);
2515 			if (n > total)
2516 				n = total;
2517 
2518 			usbd_copy_in(pc, offset, ch->cur, n);
2519 
2520 			total -= n;
2521 			ch->cur += n;
2522 			offset += n;
2523 
2524 			if (ch->cur >= ch->end)
2525 				ch->cur = ch->start;
2526 		}
2527 		usbd_transfer_submit(xfer);
2528 		break;
2529 
2530 	default:			/* Error */
2531 		if (error != USB_ERR_CANCELLED)
2532 			goto tr_setup;
2533 		break;
2534 	}
2535 }
2536 
2537 static void
uaudio_chan_record_sync_callback(struct usb_xfer * xfer,usb_error_t error)2538 uaudio_chan_record_sync_callback(struct usb_xfer *xfer, usb_error_t error)
2539 {
2540 	/* TODO */
2541 }
2542 
2543 static void
uaudio_chan_record_callback(struct usb_xfer * xfer,usb_error_t error)2544 uaudio_chan_record_callback(struct usb_xfer *xfer, usb_error_t error)
2545 {
2546 	struct uaudio_chan *ch = usbd_xfer_softc(xfer);
2547 	struct usb_page_cache *pc;
2548 	uint32_t offset0;
2549 	uint32_t mfl;
2550 	int m;
2551 	int n;
2552 	int len;
2553 	int actlen;
2554 	int nframes;
2555 	int expected_bytes;
2556 	int sample_size;
2557 
2558 	if (ch->start == ch->end) {
2559 		DPRINTF("no buffer!\n");
2560 		return;
2561 	}
2562 
2563 	usbd_xfer_status(xfer, &actlen, NULL, NULL, &nframes);
2564 	mfl = usbd_xfer_max_framelen(xfer);
2565 
2566 	switch (USB_GET_STATE(xfer)) {
2567 	case USB_ST_TRANSFERRED:
2568 
2569 		offset0 = 0;
2570 		pc = usbd_xfer_get_frame(xfer, 0);
2571 
2572 		/* try to compute the number of expected bytes */
2573 		ch->sample_curr += (ch->sample_rem * ch->intr_frames);
2574 
2575 		/* compute number of expected bytes */
2576 		expected_bytes = (ch->intr_frames * ch->bytes_per_frame[0]) +
2577 		    ((ch->sample_curr / ch->frames_per_second) *
2578 		    (ch->bytes_per_frame[1] - ch->bytes_per_frame[0]));
2579 
2580 		/* keep remainder */
2581 		ch->sample_curr %= ch->frames_per_second;
2582 
2583 		/* get current sample size */
2584 		sample_size = ch->usb_alt[ch->cur_alt].sample_size;
2585 
2586 		for (n = 0; n != nframes; n++) {
2587 			uint32_t offset1 = offset0;
2588 
2589 			len = usbd_xfer_frame_len(xfer, n);
2590 
2591 			/* make sure we only receive complete samples */
2592 			len = len - (len % sample_size);
2593 
2594 			/* subtract bytes received from expected payload */
2595 			expected_bytes -= len;
2596 
2597 			/* don't receive data when not ready */
2598 			if (ch->running == 0 || ch->cur_alt != ch->set_alt)
2599 				continue;
2600 
2601 			/* fill ring buffer with samples, if any */
2602 			while (len > 0) {
2603 				m = (ch->end - ch->cur);
2604 
2605 				if (m > len)
2606 					m = len;
2607 
2608 				usbd_copy_out(pc, offset1, ch->cur, m);
2609 
2610 				len -= m;
2611 				offset1 += m;
2612 				ch->cur += m;
2613 
2614 				if (ch->cur >= ch->end)
2615 					ch->cur = ch->start;
2616 			}
2617 
2618 			offset0 += mfl;
2619 		}
2620 
2621 		/* update current jitter */
2622 		ch->jitter_curr -= (expected_bytes / sample_size);
2623 
2624 		/* don't allow a huge amount of jitter to accumulate */
2625 		nframes = 2 * ch->intr_frames;
2626 
2627 		/* range check current jitter */
2628 		if (ch->jitter_curr < -nframes)
2629 			ch->jitter_curr = -nframes;
2630 		else if (ch->jitter_curr > nframes)
2631 			ch->jitter_curr = nframes;
2632 
2633 		DPRINTFN(6, "transferred %d bytes, jitter %d samples\n",
2634 		    actlen, ch->jitter_curr);
2635 
2636 		if (ch->running != 0)
2637 			chn_intr(ch->pcm_ch);
2638 
2639 	case USB_ST_SETUP:
2640 tr_setup:
2641 		nframes = ch->intr_frames;
2642 
2643 		usbd_xfer_set_frames(xfer, nframes);
2644 		for (n = 0; n != nframes; n++)
2645 			usbd_xfer_set_frame_len(xfer, n, mfl);
2646 
2647 		usbd_transfer_submit(xfer);
2648 		break;
2649 
2650 	default:			/* Error */
2651 		if (error != USB_ERR_CANCELLED)
2652 			goto tr_setup;
2653 		break;
2654 	}
2655 }
2656 
2657 void   *
uaudio_chan_init(struct uaudio_chan * ch,struct snd_dbuf * b,struct pcm_channel * c,int dir)2658 uaudio_chan_init(struct uaudio_chan *ch, struct snd_dbuf *b,
2659     struct pcm_channel *c, int dir)
2660 {
2661 	uint32_t buf_size;
2662 	uint8_t x;
2663 
2664 	/* store mutex and PCM channel */
2665 
2666 	ch->pcm_ch = c;
2667 	ch->pcm_mtx = c->lock;
2668 
2669 	/* compute worst case buffer */
2670 
2671 	buf_size = 0;
2672 	for (x = 0; x != ch->num_alt; x++) {
2673 		uint32_t temp = uaudio_max_buffer_size(ch, x);
2674 		if (temp > buf_size)
2675 			buf_size = temp;
2676 	}
2677 
2678 	/* allow double buffering */
2679 	buf_size *= 2;
2680 
2681 	DPRINTF("Worst case buffer is %d bytes\n", (int)buf_size);
2682 
2683 	ch->buf = malloc(buf_size, M_DEVBUF, M_WAITOK | M_ZERO);
2684 	if (sndbuf_setup(b, ch->buf, buf_size) != 0)
2685 		goto error;
2686 
2687 	ch->start = ch->buf;
2688 	ch->end = ch->buf + buf_size;
2689 	ch->cur = ch->buf;
2690 	ch->pcm_buf = b;
2691 	ch->max_buf = buf_size;
2692 
2693 	if (ch->pcm_mtx == NULL) {
2694 		DPRINTF("ERROR: PCM channels does not have a mutex!\n");
2695 		goto error;
2696 	}
2697 	return (ch);
2698 
2699 error:
2700 	uaudio_chan_free(ch);
2701 	return (NULL);
2702 }
2703 
2704 int
uaudio_chan_free(struct uaudio_chan * ch)2705 uaudio_chan_free(struct uaudio_chan *ch)
2706 {
2707 	if (ch->buf != NULL) {
2708 		free(ch->buf, M_DEVBUF);
2709 		ch->buf = NULL;
2710 	}
2711 	usbd_transfer_unsetup(ch->xfer, UAUDIO_NCHANBUFS + 1);
2712 
2713 	ch->num_alt = 0;
2714 
2715 	return (0);
2716 }
2717 
2718 int
uaudio_chan_set_param_blocksize(struct uaudio_chan * ch,uint32_t blocksize)2719 uaudio_chan_set_param_blocksize(struct uaudio_chan *ch, uint32_t blocksize)
2720 {
2721 	uint32_t temp = 2 * uaudio_get_buffer_size(ch, ch->set_alt);
2722 	sndbuf_setup(ch->pcm_buf, ch->buf, temp);
2723 	return (temp / 2);
2724 }
2725 
2726 int
uaudio_chan_set_param_fragments(struct uaudio_chan * ch,uint32_t blocksize,uint32_t blockcount)2727 uaudio_chan_set_param_fragments(struct uaudio_chan *ch, uint32_t blocksize,
2728     uint32_t blockcount)
2729 {
2730 	return (1);
2731 }
2732 
2733 int
uaudio_chan_set_param_speed(struct uaudio_chan * ch,uint32_t speed)2734 uaudio_chan_set_param_speed(struct uaudio_chan *ch, uint32_t speed)
2735 {
2736 	struct uaudio_softc *sc;
2737 	uint8_t x, y;
2738 
2739 	sc = ch->priv_sc;
2740 
2741 	for (x = 0, y = 1; y < ch->num_alt; y++) {
2742 		/* prefer sample rate closer to and greater than requested */
2743 		if ((ch->usb_alt[x].sample_rate < speed &&
2744 		    ch->usb_alt[x].sample_rate < ch->usb_alt[y].sample_rate) ||
2745 		    (speed <= ch->usb_alt[y].sample_rate &&
2746 		    ch->usb_alt[y].sample_rate < ch->usb_alt[x].sample_rate))
2747 			x = y;
2748 	}
2749 
2750 	usb_proc_explore_lock(sc->sc_udev);
2751 	ch->set_alt = x;
2752 	usb_proc_explore_unlock(sc->sc_udev);
2753 
2754 	DPRINTF("Selecting alt %d\n", (int)x);
2755 
2756 	return (ch->usb_alt[x].sample_rate);
2757 }
2758 
2759 int
uaudio_chan_getptr(struct uaudio_chan * ch)2760 uaudio_chan_getptr(struct uaudio_chan *ch)
2761 {
2762 	return (ch->cur - ch->start);
2763 }
2764 
2765 struct pcmchan_caps *
uaudio_chan_getcaps(struct uaudio_chan * ch)2766 uaudio_chan_getcaps(struct uaudio_chan *ch)
2767 {
2768 	return (&ch->pcm_cap);
2769 }
2770 
2771 static struct pcmchan_matrix uaudio_chan_matrix_swap_2_0 = {
2772 	.id = SND_CHN_MATRIX_DRV,
2773 	.channels = 2,
2774 	.ext = 0,
2775 	.map = {
2776 		/* Right */
2777 		[0] = {
2778 			.type = SND_CHN_T_FR,
2779 			.members =
2780 			    SND_CHN_T_MASK_FR | SND_CHN_T_MASK_FC |
2781 			    SND_CHN_T_MASK_LF | SND_CHN_T_MASK_BR |
2782 			    SND_CHN_T_MASK_BC | SND_CHN_T_MASK_SR
2783 		},
2784 		/* Left */
2785 		[1] = {
2786 			.type = SND_CHN_T_FL,
2787 			.members =
2788 			    SND_CHN_T_MASK_FL | SND_CHN_T_MASK_FC |
2789 			    SND_CHN_T_MASK_LF | SND_CHN_T_MASK_BL |
2790 			    SND_CHN_T_MASK_BC | SND_CHN_T_MASK_SL
2791 		},
2792 		[2] = {
2793 			.type = SND_CHN_T_MAX,
2794 			.members = 0
2795 		}
2796 	},
2797 	.mask = SND_CHN_T_MASK_FR | SND_CHN_T_MASK_FL,
2798 	.offset = {  1,  0, -1, -1, -1, -1, -1, -1, -1,
2799 		    -1, -1, -1, -1, -1, -1, -1, -1, -1  }
2800 };
2801 
2802 struct pcmchan_matrix *
uaudio_chan_getmatrix(struct uaudio_chan * ch,uint32_t format)2803 uaudio_chan_getmatrix(struct uaudio_chan *ch, uint32_t format)
2804 {
2805 	struct uaudio_softc *sc;
2806 
2807 	sc = ch->priv_sc;
2808 
2809 	if (sc != NULL && sc->sc_uq_audio_swap_lr != 0 &&
2810 	    AFMT_CHANNEL(format) == 2)
2811 		return (&uaudio_chan_matrix_swap_2_0);
2812 
2813 	return (feeder_matrix_format_map(format));
2814 }
2815 
2816 int
uaudio_chan_set_param_format(struct uaudio_chan * ch,uint32_t format)2817 uaudio_chan_set_param_format(struct uaudio_chan *ch, uint32_t format)
2818 {
2819 	DPRINTF("Selecting format 0x%08x\n", (unsigned int)format);
2820 	return (0);
2821 }
2822 
2823 static void
uaudio_chan_reconfigure(struct uaudio_chan * ch,uint8_t operation)2824 uaudio_chan_reconfigure(struct uaudio_chan *ch, uint8_t operation)
2825 {
2826 	struct uaudio_softc *sc = ch->priv_sc;
2827 
2828 	/* Check for shutdown. */
2829 	if (ch->operation == CHAN_OP_DRAIN)
2830 		return;
2831 
2832 	/* Set next operation. */
2833 	ch->operation = operation;
2834 
2835 	/*
2836 	 * Because changing the alternate setting modifies the USB
2837 	 * configuration, this part must be executed from the USB
2838 	 * explore process.
2839 	 */
2840 	(void)usb_proc_explore_msignal(sc->sc_udev,
2841 	    &sc->sc_config_msg[0], &sc->sc_config_msg[1]);
2842 }
2843 
2844 static int
uaudio_chan_need_both(struct uaudio_chan * pchan,struct uaudio_chan * rchan)2845 uaudio_chan_need_both(struct uaudio_chan *pchan, struct uaudio_chan *rchan)
2846 {
2847 	return (pchan->num_alt > 0 &&
2848 	    pchan->running != 0 &&
2849 	    uaudio_chan_is_async(pchan, pchan->set_alt) != 0 &&
2850 	    rchan->num_alt > 0 &&
2851 	    rchan->running == 0);
2852 }
2853 
2854 static int
uaudio_chan_need_none(struct uaudio_chan * pchan,struct uaudio_chan * rchan)2855 uaudio_chan_need_none(struct uaudio_chan *pchan, struct uaudio_chan *rchan)
2856 {
2857 	return (pchan->num_alt > 0 &&
2858 	    pchan->running == 0 &&
2859 	    rchan->num_alt > 0 &&
2860 	    rchan->running == 0);
2861 }
2862 
2863 void
uaudio_chan_start(struct uaudio_chan * ch)2864 uaudio_chan_start(struct uaudio_chan *ch)
2865 {
2866 	struct uaudio_softc *sc = ch->priv_sc;
2867 	unsigned i = uaudio_get_child_index_by_chan(sc, ch);
2868 
2869 	/* make operation atomic */
2870 	usb_proc_explore_lock(sc->sc_udev);
2871 
2872 	/* check if not running */
2873 	if (ch->running == 0) {
2874 		uint32_t temp;
2875 
2876 		/* get current buffer size */
2877 		temp = 2 * uaudio_get_buffer_size(ch, ch->set_alt);
2878 
2879 		/* set running flag */
2880 		ch->running = 1;
2881 
2882 		/* ensure the hardware buffer is reset */
2883 		ch->start = ch->buf;
2884 		ch->end = ch->buf + temp;
2885 		ch->cur = ch->buf;
2886 
2887 		if (uaudio_chan_need_both(
2888 		    &sc->sc_play_chan[i],
2889 		    &sc->sc_rec_chan[i])) {
2890 			/*
2891 			 * Start both endpoints because of need for
2892 			 * jitter information:
2893 			 */
2894 			uaudio_chan_reconfigure(&sc->sc_rec_chan[i], CHAN_OP_START);
2895 			uaudio_chan_reconfigure(&sc->sc_play_chan[i], CHAN_OP_START);
2896 		} else {
2897 			uaudio_chan_reconfigure(ch, CHAN_OP_START);
2898 		}
2899 	}
2900 
2901 	/* exit atomic operation */
2902 	usb_proc_explore_unlock(sc->sc_udev);
2903 }
2904 
2905 void
uaudio_chan_stop(struct uaudio_chan * ch)2906 uaudio_chan_stop(struct uaudio_chan *ch)
2907 {
2908 	struct uaudio_softc *sc = ch->priv_sc;
2909 	unsigned i = uaudio_get_child_index_by_chan(sc, ch);
2910 
2911 	/* make operation atomic */
2912 	usb_proc_explore_lock(sc->sc_udev);
2913 
2914 	/* check if running */
2915 	if (ch->running != 0) {
2916 		/* clear running flag */
2917 		ch->running = 0;
2918 
2919 		if (uaudio_chan_need_both(
2920 		    &sc->sc_play_chan[i],
2921 		    &sc->sc_rec_chan[i])) {
2922 			/*
2923 			 * Leave the endpoints running because we need
2924 			 * information about jitter!
2925 			 */
2926 		} else if (uaudio_chan_need_none(
2927 		    &sc->sc_play_chan[i],
2928 		    &sc->sc_rec_chan[i])) {
2929 			/*
2930 			 * Stop both endpoints in case the one was used for
2931 			 * jitter information:
2932 			 */
2933 			uaudio_chan_reconfigure(&sc->sc_rec_chan[i], CHAN_OP_STOP);
2934 			uaudio_chan_reconfigure(&sc->sc_play_chan[i], CHAN_OP_STOP);
2935 		} else {
2936 			uaudio_chan_reconfigure(ch, CHAN_OP_STOP);
2937 		}
2938 	}
2939 
2940 	/* exit atomic operation */
2941 	usb_proc_explore_unlock(sc->sc_udev);
2942 }
2943 
2944 /*========================================================================*
2945  * AC - Audio Controller - routines
2946  *========================================================================*/
2947 
2948 static int
uaudio_mixer_sysctl_handler(SYSCTL_HANDLER_ARGS)2949 uaudio_mixer_sysctl_handler(SYSCTL_HANDLER_ARGS)
2950 {
2951 	struct uaudio_softc *sc;
2952 	struct uaudio_mixer_node *pmc;
2953 	int hint;
2954 	int error;
2955 	int temp = 0;
2956 	int chan = 0;
2957 
2958 	sc = (struct uaudio_softc *)oidp->oid_arg1;
2959 	hint = oidp->oid_arg2;
2960 
2961 	if (sc->sc_child[0].mixer_lock == NULL)
2962 		return (ENXIO);
2963 
2964 	/* lookup mixer node */
2965 
2966 	mtx_lock(sc->sc_child[0].mixer_lock);
2967 	for (pmc = sc->sc_mixer_root; pmc != NULL; pmc = pmc->next) {
2968 		for (chan = 0; chan != (int)pmc->nchan; chan++) {
2969 			if (pmc->wValue[chan] != -1 &&
2970 			    pmc->wValue[chan] == hint) {
2971 				temp = pmc->wData[chan];
2972 				goto found;
2973 			}
2974 		}
2975 	}
2976 found:
2977 	mtx_unlock(sc->sc_child[0].mixer_lock);
2978 
2979 	error = sysctl_handle_int(oidp, &temp, 0, req);
2980 	if (error != 0 || req->newptr == NULL)
2981 		return (error);
2982 
2983 	/* update mixer value */
2984 
2985 	mtx_lock(sc->sc_child[0].mixer_lock);
2986 	if (pmc != NULL &&
2987 	    temp >= pmc->minval &&
2988 	    temp <= pmc->maxval) {
2989 		pmc->wData[chan] = temp;
2990 		pmc->update[(chan / 8)] |= (1 << (chan % 8));
2991 
2992 		/* start the transfer, if not already started */
2993 		usbd_transfer_start(sc->sc_mixer_xfer[0]);
2994 	}
2995 	mtx_unlock(sc->sc_child[0].mixer_lock);
2996 
2997 	return (0);
2998 }
2999 
3000 static void
uaudio_mixer_ctl_free(struct uaudio_softc * sc)3001 uaudio_mixer_ctl_free(struct uaudio_softc *sc)
3002 {
3003 	struct uaudio_mixer_node *p_mc;
3004 
3005 	while ((p_mc = sc->sc_mixer_root) != NULL) {
3006 		sc->sc_mixer_root = p_mc->next;
3007 		free(p_mc, M_USBDEV);
3008 	}
3009 }
3010 
3011 static void
uaudio_mixer_register_sysctl(struct uaudio_softc * sc,device_t dev,unsigned index)3012 uaudio_mixer_register_sysctl(struct uaudio_softc *sc, device_t dev,
3013     unsigned index)
3014 {
3015 	struct uaudio_mixer_node *pmc;
3016 	struct sysctl_oid *mixer_tree;
3017 	struct sysctl_oid *control_tree;
3018 	char buf[32];
3019 	int chan;
3020 	int n;
3021 
3022 	if (index != 0)
3023 		return;
3024 
3025 	mixer_tree = SYSCTL_ADD_NODE(device_get_sysctl_ctx(dev),
3026 	    SYSCTL_CHILDREN(device_get_sysctl_tree(dev)), OID_AUTO, "mixer",
3027 	    CTLFLAG_RD | CTLFLAG_MPSAFE, NULL, "");
3028 
3029 	if (mixer_tree == NULL)
3030 		return;
3031 
3032 	for (n = 0, pmc = sc->sc_mixer_root; pmc != NULL;
3033 	    pmc = pmc->next, n++) {
3034 		for (chan = 0; chan < pmc->nchan; chan++) {
3035 			if (pmc->nchan > 1) {
3036 				snprintf(buf, sizeof(buf), "%s_%d_%d",
3037 				    pmc->name, n, chan);
3038 			} else {
3039 				snprintf(buf, sizeof(buf), "%s_%d",
3040 				    pmc->name, n);
3041 			}
3042 
3043 			control_tree = SYSCTL_ADD_NODE(device_get_sysctl_ctx(dev),
3044 			    SYSCTL_CHILDREN(mixer_tree), OID_AUTO, buf,
3045 			    CTLFLAG_RD | CTLFLAG_MPSAFE, NULL,
3046 			    "Mixer control nodes");
3047 
3048 			if (control_tree == NULL)
3049 				continue;
3050 
3051 			SYSCTL_ADD_PROC(device_get_sysctl_ctx(dev),
3052 			    SYSCTL_CHILDREN(control_tree),
3053 			    OID_AUTO, "val",
3054 			    CTLTYPE_INT | CTLFLAG_RWTUN | CTLFLAG_MPSAFE,
3055 			    sc, pmc->wValue[chan],
3056 			    uaudio_mixer_sysctl_handler, "I", "Current value");
3057 
3058 			SYSCTL_ADD_INT(device_get_sysctl_ctx(dev),
3059 			    SYSCTL_CHILDREN(control_tree),
3060 			    OID_AUTO, "min", CTLFLAG_RD, 0, pmc->minval,
3061 			    "Minimum value");
3062 
3063 			SYSCTL_ADD_INT(device_get_sysctl_ctx(dev),
3064 			    SYSCTL_CHILDREN(control_tree),
3065 			    OID_AUTO, "max", CTLFLAG_RD, 0, pmc->maxval,
3066 			    "Maximum value");
3067 
3068 			SYSCTL_ADD_STRING(device_get_sysctl_ctx(dev),
3069 			    SYSCTL_CHILDREN(control_tree),
3070 			    OID_AUTO, "desc", CTLFLAG_RD, pmc->desc, 0,
3071 			    "Description");
3072 		}
3073 	}
3074 }
3075 
3076 /* M-Audio FastTrack Ultra Mixer Description */
3077 /* Origin: Linux USB Audio driver */
3078 static void
uaudio_mixer_controls_create_ftu(struct uaudio_softc * sc)3079 uaudio_mixer_controls_create_ftu(struct uaudio_softc *sc)
3080 {
3081 	int chx;
3082 	int chy;
3083 
3084 	memset(&MIX(sc), 0, sizeof(MIX(sc)));
3085 	MIX(sc).wIndex = MAKE_WORD(6, sc->sc_mixer_iface_no);
3086 	MIX(sc).wValue[0] = MAKE_WORD(8, 0);
3087 	MIX(sc).type = MIX_UNSIGNED_16;
3088 	MIX(sc).ctl = SOUND_MIXER_NRDEVICES;
3089 	MIX(sc).name = "effect";
3090 	MIX(sc).minval = 0;
3091 	MIX(sc).maxval = 7;
3092 	MIX(sc).mul = 7;
3093 	MIX(sc).nchan = 1;
3094 	MIX(sc).update[0] = 1;
3095 	strlcpy(MIX(sc).desc, "Room1,2,3,Hall1,2,Plate,Delay,Echo", sizeof(MIX(sc).desc));
3096 	uaudio_mixer_add_ctl_sub(sc, &MIX(sc));
3097 
3098 	memset(&MIX(sc), 0, sizeof(MIX(sc)));
3099 	MIX(sc).wIndex = MAKE_WORD(5, sc->sc_mixer_iface_no);
3100 
3101 	for (chx = 0; chx != 8; chx++) {
3102 		for (chy = 0; chy != 8; chy++) {
3103 			MIX(sc).wValue[0] = MAKE_WORD(chx + 1, chy + 1);
3104 			MIX(sc).type = MIX_SIGNED_16;
3105 			MIX(sc).ctl = SOUND_MIXER_NRDEVICES;
3106 			MIX(sc).name = "mix_rec";
3107 			MIX(sc).nchan = 1;
3108 			MIX(sc).update[0] = 1;
3109 			MIX(sc).val_default = 0;
3110 			snprintf(MIX(sc).desc, sizeof(MIX(sc).desc),
3111 			    "AIn%d - Out%d Record Volume", chy + 1, chx + 1);
3112 
3113 			uaudio_mixer_add_ctl(sc, &MIX(sc));
3114 
3115 			MIX(sc).wValue[0] = MAKE_WORD(chx + 1, chy + 1 + 8);
3116 			MIX(sc).type = MIX_SIGNED_16;
3117 			MIX(sc).ctl = SOUND_MIXER_NRDEVICES;
3118 			MIX(sc).name = "mix_play";
3119 			MIX(sc).nchan = 1;
3120 			MIX(sc).update[0] = 1;
3121 			MIX(sc).val_default = (chx == chy) ? 2 : 0;
3122 			snprintf(MIX(sc).desc, sizeof(MIX(sc).desc),
3123 			    "DIn%d - Out%d Playback Volume", chy + 1, chx + 1);
3124 
3125 			uaudio_mixer_add_ctl(sc, &MIX(sc));
3126 		}
3127 	}
3128 
3129 	memset(&MIX(sc), 0, sizeof(MIX(sc)));
3130 	MIX(sc).wIndex = MAKE_WORD(6, sc->sc_mixer_iface_no);
3131 	MIX(sc).wValue[0] = MAKE_WORD(2, 0);
3132 	MIX(sc).type = MIX_SIGNED_8;
3133 	MIX(sc).ctl = SOUND_MIXER_NRDEVICES;
3134 	MIX(sc).name = "effect_vol";
3135 	MIX(sc).nchan = 1;
3136 	MIX(sc).update[0] = 1;
3137 	MIX(sc).minval = 0;
3138 	MIX(sc).maxval = 0x7f;
3139 	MIX(sc).mul = 0x7f;
3140 	MIX(sc).nchan = 1;
3141 	MIX(sc).update[0] = 1;
3142 	strlcpy(MIX(sc).desc, "Effect Volume", sizeof(MIX(sc).desc));
3143 	uaudio_mixer_add_ctl_sub(sc, &MIX(sc));
3144 
3145 	memset(&MIX(sc), 0, sizeof(MIX(sc)));
3146 	MIX(sc).wIndex = MAKE_WORD(6, sc->sc_mixer_iface_no);
3147 	MIX(sc).wValue[0] = MAKE_WORD(3, 0);
3148 	MIX(sc).type = MIX_SIGNED_16;
3149 	MIX(sc).ctl = SOUND_MIXER_NRDEVICES;
3150 	MIX(sc).name = "effect_dur";
3151 	MIX(sc).nchan = 1;
3152 	MIX(sc).update[0] = 1;
3153 	MIX(sc).minval = 0;
3154 	MIX(sc).maxval = 0x7f00;
3155 	MIX(sc).mul = 0x7f00;
3156 	MIX(sc).nchan = 1;
3157 	MIX(sc).update[0] = 1;
3158 	strlcpy(MIX(sc).desc, "Effect Duration", sizeof(MIX(sc).desc));
3159 	uaudio_mixer_add_ctl_sub(sc, &MIX(sc));
3160 
3161 	memset(&MIX(sc), 0, sizeof(MIX(sc)));
3162 	MIX(sc).wIndex = MAKE_WORD(6, sc->sc_mixer_iface_no);
3163 	MIX(sc).wValue[0] = MAKE_WORD(4, 0);
3164 	MIX(sc).type = MIX_SIGNED_8;
3165 	MIX(sc).ctl = SOUND_MIXER_NRDEVICES;
3166 	MIX(sc).name = "effect_fb";
3167 	MIX(sc).nchan = 1;
3168 	MIX(sc).update[0] = 1;
3169 	MIX(sc).minval = 0;
3170 	MIX(sc).maxval = 0x7f;
3171 	MIX(sc).mul = 0x7f;
3172 	MIX(sc).nchan = 1;
3173 	MIX(sc).update[0] = 1;
3174 	strlcpy(MIX(sc).desc, "Effect Feedback Volume", sizeof(MIX(sc).desc));
3175 	uaudio_mixer_add_ctl_sub(sc, &MIX(sc));
3176 
3177 	memset(&MIX(sc), 0, sizeof(MIX(sc)));
3178 	MIX(sc).wIndex = MAKE_WORD(7, sc->sc_mixer_iface_no);
3179 	for (chy = 0; chy != 4; chy++) {
3180 		MIX(sc).wValue[0] = MAKE_WORD(7, chy + 1);
3181 		MIX(sc).type = MIX_SIGNED_16;
3182 		MIX(sc).ctl = SOUND_MIXER_NRDEVICES;
3183 		MIX(sc).name = "effect_ret";
3184 		MIX(sc).nchan = 1;
3185 		MIX(sc).update[0] = 1;
3186 		snprintf(MIX(sc).desc, sizeof(MIX(sc).desc),
3187 		    "Effect Return %d Volume", chy + 1);
3188 
3189 		uaudio_mixer_add_ctl(sc, &MIX(sc));
3190 	}
3191 
3192 	memset(&MIX(sc), 0, sizeof(MIX(sc)));
3193 	MIX(sc).wIndex = MAKE_WORD(5, sc->sc_mixer_iface_no);
3194 
3195 	for (chy = 0; chy != 8; chy++) {
3196 		MIX(sc).wValue[0] = MAKE_WORD(9, chy + 1);
3197 		MIX(sc).type = MIX_SIGNED_16;
3198 		MIX(sc).ctl = SOUND_MIXER_NRDEVICES;
3199 		MIX(sc).name = "effect_send";
3200 		MIX(sc).nchan = 1;
3201 		MIX(sc).update[0] = 1;
3202 		snprintf(MIX(sc).desc, sizeof(MIX(sc).desc),
3203 		    "Effect Send AIn%d Volume", chy + 1);
3204 
3205 		uaudio_mixer_add_ctl(sc, &MIX(sc));
3206 
3207 		MIX(sc).wValue[0] = MAKE_WORD(9, chy + 1 + 8);
3208 		MIX(sc).type = MIX_SIGNED_16;
3209 		MIX(sc).ctl = SOUND_MIXER_NRDEVICES;
3210 		MIX(sc).name = "effect_send";
3211 		MIX(sc).nchan = 1;
3212 		MIX(sc).update[0] = 1;
3213 		snprintf(MIX(sc).desc, sizeof(MIX(sc).desc),
3214 		    "Effect Send DIn%d Volume", chy + 1);
3215 
3216 		uaudio_mixer_add_ctl(sc, &MIX(sc));
3217 	}
3218 }
3219 
3220 static void
uaudio_mixer_reload_all(struct uaudio_softc * sc)3221 uaudio_mixer_reload_all(struct uaudio_softc *sc)
3222 {
3223 	struct uaudio_mixer_node *pmc;
3224 	int chan;
3225 
3226 	if (sc->sc_child[0].mixer_lock == NULL)
3227 		return;
3228 
3229 	mtx_lock(sc->sc_child[0].mixer_lock);
3230 	for (pmc = sc->sc_mixer_root; pmc != NULL; pmc = pmc->next) {
3231 		/* use reset defaults for non-oss controlled settings */
3232 		if (pmc->ctl == SOUND_MIXER_NRDEVICES)
3233 			continue;
3234 		for (chan = 0; chan < pmc->nchan; chan++)
3235 			pmc->update[chan / 8] |= (1 << (chan % 8));
3236 	}
3237 	usbd_transfer_start(sc->sc_mixer_xfer[0]);
3238 
3239 	/* start HID volume keys, if any */
3240 	usbd_transfer_start(sc->sc_hid.xfer[0]);
3241 	mtx_unlock(sc->sc_child[0].mixer_lock);
3242 }
3243 
3244 static void
uaudio_mixer_add_ctl_sub(struct uaudio_softc * sc,struct uaudio_mixer_node * mc)3245 uaudio_mixer_add_ctl_sub(struct uaudio_softc *sc, struct uaudio_mixer_node *mc)
3246 {
3247 	struct uaudio_mixer_node *p_mc_new =
3248 	    malloc(sizeof(*p_mc_new), M_USBDEV, M_WAITOK);
3249 	int ch;
3250 
3251 	memcpy(p_mc_new, mc, sizeof(*p_mc_new));
3252 	p_mc_new->next = sc->sc_mixer_root;
3253 	sc->sc_mixer_root = p_mc_new;
3254 	sc->sc_mixer_count++;
3255 
3256 	/* set default value for all channels */
3257 	for (ch = 0; ch < p_mc_new->nchan; ch++) {
3258 		switch (p_mc_new->val_default) {
3259 		case 1:
3260 			/* 50% */
3261 			p_mc_new->wData[ch] = (p_mc_new->maxval + p_mc_new->minval) / 2;
3262 			break;
3263 		case 2:
3264 			/* 100% */
3265 			p_mc_new->wData[ch] = p_mc_new->maxval;
3266 			break;
3267 		default:
3268 			/* 0% */
3269 			p_mc_new->wData[ch] = p_mc_new->minval;
3270 			break;
3271 		}
3272 	}
3273 }
3274 
3275 static void
uaudio_mixer_add_ctl(struct uaudio_softc * sc,struct uaudio_mixer_node * mc)3276 uaudio_mixer_add_ctl(struct uaudio_softc *sc, struct uaudio_mixer_node *mc)
3277 {
3278 	int32_t res;
3279 
3280 	DPRINTF("adding %d\n", mc->ctl);
3281 
3282 	if (mc->type == MIX_ON_OFF) {
3283 		mc->minval = 0;
3284 		mc->maxval = 1;
3285 	} else if (mc->type == MIX_SELECTOR) {
3286 	} else {
3287 		/* determine min and max values */
3288 
3289 		mc->minval = uaudio_mixer_get(sc->sc_udev,
3290 		    sc->sc_audio_rev, GET_MIN, mc);
3291 		mc->maxval = uaudio_mixer_get(sc->sc_udev,
3292 		    sc->sc_audio_rev, GET_MAX, mc);
3293 
3294 		/* check if max and min was swapped */
3295 
3296 		if (mc->maxval < mc->minval) {
3297 			res = mc->maxval;
3298 			mc->maxval = mc->minval;
3299 			mc->minval = res;
3300 		}
3301 
3302 		/* compute value range */
3303 		mc->mul = mc->maxval - mc->minval;
3304 		if (mc->mul == 0)
3305 			mc->mul = 1;
3306 
3307 		/* compute value alignment */
3308 		res = uaudio_mixer_get(sc->sc_udev,
3309 		    sc->sc_audio_rev, GET_RES, mc);
3310 
3311 		DPRINTF("Resolution = %d\n", (int)res);
3312 	}
3313 
3314 	uaudio_mixer_add_ctl_sub(sc, mc);
3315 
3316 #ifdef USB_DEBUG
3317 	if (uaudio_debug > 2) {
3318 		uint8_t i;
3319 
3320 		for (i = 0; i < mc->nchan; i++) {
3321 			DPRINTF("[mix] wValue=%04x\n", mc->wValue[0]);
3322 		}
3323 		DPRINTF("[mix] wIndex=%04x type=%d ctl='%d' "
3324 		    "min=%d max=%d\n",
3325 		    mc->wIndex, mc->type, mc->ctl,
3326 		    mc->minval, mc->maxval);
3327 	}
3328 #endif
3329 }
3330 
3331 static void
uaudio_mixer_add_mixer(struct uaudio_softc * sc,const struct uaudio_terminal_node * iot,int id)3332 uaudio_mixer_add_mixer(struct uaudio_softc *sc,
3333     const struct uaudio_terminal_node *iot, int id)
3334 {
3335 	const struct usb_audio_mixer_unit_0 *d0 = iot[id].u.mu_v1;
3336 	const struct usb_audio_mixer_unit_1 *d1;
3337 
3338 	uint32_t bno;			/* bit number */
3339 	uint32_t p;			/* bit number accumulator */
3340 	uint32_t mo;			/* matching outputs */
3341 	uint32_t mc;			/* matching channels */
3342 	uint32_t ichs;			/* input channels */
3343 	uint32_t ochs;			/* output channels */
3344 	uint32_t c;
3345 	uint32_t chs;			/* channels */
3346 	uint32_t i;
3347 	uint32_t o;
3348 
3349 	DPRINTFN(3, "bUnitId=%d bNrInPins=%d\n",
3350 	    d0->bUnitId, d0->bNrInPins);
3351 
3352 	/* compute the number of input channels */
3353 
3354 	ichs = 0;
3355 	for (i = 0; i < d0->bNrInPins; i++) {
3356 		ichs += uaudio_mixer_get_cluster(
3357 		    d0->baSourceId[i], iot).bNrChannels;
3358 	}
3359 
3360 	d1 = (const void *)(d0->baSourceId + d0->bNrInPins);
3361 
3362 	/* and the number of output channels */
3363 
3364 	ochs = d1->bNrChannels;
3365 
3366 	DPRINTFN(3, "ichs=%d ochs=%d\n", ichs, ochs);
3367 
3368 	memset(&MIX(sc), 0, sizeof(MIX(sc)));
3369 
3370 	MIX(sc).wIndex = MAKE_WORD(d0->bUnitId, sc->sc_mixer_iface_no);
3371 	MIX(sc).type = MIX_SIGNED_16;
3372 
3373 	if (uaudio_mixer_verify_desc(d0, ((ichs * ochs) + 7) / 8) == NULL)
3374 		return;
3375 
3376 	for (p = i = 0; i < d0->bNrInPins; i++) {
3377 		chs = uaudio_mixer_get_cluster(
3378 		    d0->baSourceId[i], iot).bNrChannels;
3379 		mc = 0;
3380 		for (c = 0; c < chs; c++) {
3381 			mo = 0;
3382 			for (o = 0; o < ochs; o++) {
3383 				bno = ((p + c) * ochs) + o;
3384 				if (BIT_TEST(d1->bmControls, bno))
3385 					mo++;
3386 			}
3387 			if (mo == 1)
3388 				mc++;
3389 		}
3390 		if ((mc == chs) && (chs <= MIX_MAX_CHAN)) {
3391 			/* repeat bit-scan */
3392 
3393 			mc = 0;
3394 			for (c = 0; c < chs; c++) {
3395 				for (o = 0; o < ochs; o++) {
3396 					bno = ((p + c) * ochs) + o;
3397 					if (BIT_TEST(d1->bmControls, bno))
3398 						MIX(sc).wValue[mc++] = MAKE_WORD(p + c + 1, o + 1);
3399 				}
3400 			}
3401 			MIX(sc).nchan = chs;
3402 			uaudio_mixer_add_ctl(sc, &MIX(sc));
3403 		}
3404 		p += chs;
3405 	}
3406 }
3407 
3408 static void
uaudio20_mixer_add_mixer(struct uaudio_softc * sc,const struct uaudio_terminal_node * iot,int id)3409 uaudio20_mixer_add_mixer(struct uaudio_softc *sc,
3410     const struct uaudio_terminal_node *iot, int id)
3411 {
3412 	const struct usb_audio20_mixer_unit_0 *d0 = iot[id].u.mu_v2;
3413 	const struct usb_audio20_mixer_unit_1 *d1;
3414 
3415 	uint32_t bno;			/* bit number */
3416 	uint32_t p;			/* bit number accumulator */
3417 	uint32_t mo;			/* matching outputs */
3418 	uint32_t mc;			/* matching channels */
3419 	uint32_t ichs;			/* input channels */
3420 	uint32_t ochs;			/* output channels */
3421 	uint32_t c;
3422 	uint32_t chs;			/* channels */
3423 	uint32_t i;
3424 	uint32_t o;
3425 
3426 	DPRINTFN(3, "bUnitId=%d bNrInPins=%d\n",
3427 	    d0->bUnitId, d0->bNrInPins);
3428 
3429 	/* compute the number of input channels */
3430 
3431 	ichs = 0;
3432 	for (i = 0; i < d0->bNrInPins; i++) {
3433 		ichs += uaudio20_mixer_get_cluster(
3434 		    d0->baSourceId[i], iot).bNrChannels;
3435 	}
3436 
3437 	d1 = (const void *)(d0->baSourceId + d0->bNrInPins);
3438 
3439 	/* and the number of output channels */
3440 
3441 	ochs = d1->bNrChannels;
3442 
3443 	DPRINTFN(3, "ichs=%d ochs=%d\n", ichs, ochs);
3444 
3445 	memset(&MIX(sc), 0, sizeof(MIX(sc)));
3446 
3447 	MIX(sc).wIndex = MAKE_WORD(d0->bUnitId, sc->sc_mixer_iface_no);
3448 	MIX(sc).type = MIX_SIGNED_16;
3449 
3450 	if (uaudio20_mixer_verify_desc(d0, ((ichs * ochs) + 7) / 8) == NULL)
3451 		return;
3452 
3453 	for (p = i = 0; i < d0->bNrInPins; i++) {
3454 		chs = uaudio20_mixer_get_cluster(
3455 		    d0->baSourceId[i], iot).bNrChannels;
3456 		mc = 0;
3457 		for (c = 0; c < chs; c++) {
3458 			mo = 0;
3459 			for (o = 0; o < ochs; o++) {
3460 				bno = ((p + c) * ochs) + o;
3461 				if (BIT_TEST(d1->bmControls, bno))
3462 					mo++;
3463 			}
3464 			if (mo == 1)
3465 				mc++;
3466 		}
3467 		if ((mc == chs) && (chs <= MIX_MAX_CHAN)) {
3468 			/* repeat bit-scan */
3469 
3470 			mc = 0;
3471 			for (c = 0; c < chs; c++) {
3472 				for (o = 0; o < ochs; o++) {
3473 					bno = ((p + c) * ochs) + o;
3474 					if (BIT_TEST(d1->bmControls, bno))
3475 						MIX(sc).wValue[mc++] = MAKE_WORD(p + c + 1, o + 1);
3476 				}
3477 			}
3478 			MIX(sc).nchan = chs;
3479 			uaudio_mixer_add_ctl(sc, &MIX(sc));
3480 		}
3481 		p += chs;
3482 	}
3483 }
3484 
3485 static void
uaudio_mixer_check_selectors(struct uaudio_softc * sc)3486 uaudio_mixer_check_selectors(struct uaudio_softc *sc)
3487 {
3488 	uint8_t reserve_feature[] = {
3489 	    SOUND_MIXER_LINE,
3490 	    SOUND_MIXER_LINE1,
3491 	    SOUND_MIXER_LINE2,
3492 	    SOUND_MIXER_LINE3,
3493 	    SOUND_MIXER_DIGITAL1,
3494 	    SOUND_MIXER_DIGITAL2,
3495 	    SOUND_MIXER_DIGITAL3,
3496 	};
3497 	const uint16_t reserve_max =
3498 	    sizeof(reserve_feature) / sizeof(reserve_feature[0]);
3499 	uint16_t i;
3500 	uint16_t j;
3501 	uint16_t k;
3502 
3503 	/* remove existing selector types from the reserve */
3504 	for (i = 0; i < MIX(sc).maxval; i++) {
3505 		if (MIX(sc).slctrtype[i] == SOUND_MIXER_NRDEVICES)
3506 			continue;
3507 		for (j = 0; j != reserve_max; j++) {
3508 			if (reserve_feature[j] == MIX(sc).slctrtype[i])
3509 				reserve_feature[j] = SOUND_MIXER_NRDEVICES;
3510 		}
3511 	}
3512 
3513 	/* make sure selector types are not overlapping */
3514 	for (i = 0; i < MIX(sc).maxval; i++) {
3515 		if (MIX(sc).slctrtype[i] == SOUND_MIXER_NRDEVICES)
3516 			continue;
3517 		for (j = i + 1; j < MIX(sc).maxval; j++) {
3518 			if (MIX(sc).slctrtype[j] == SOUND_MIXER_NRDEVICES)
3519 				continue;
3520 			if (MIX(sc).slctrtype[i] != MIX(sc).slctrtype[j])
3521 				continue;
3522 			for (k = 0; k != reserve_max; k++) {
3523 				if (reserve_feature[k] == SOUND_MIXER_NRDEVICES)
3524 					continue;
3525 				MIX(sc).slctrtype[j] = reserve_feature[k];
3526 				reserve_feature[k] = SOUND_MIXER_NRDEVICES;
3527 				break;
3528 			}
3529 			if (k == reserve_max) {
3530 				DPRINTF("Selector type %d is not selectable!\n", j);
3531 				MIX(sc).slctrtype[j] = SOUND_MIXER_NRDEVICES;
3532 			}
3533 		}
3534 	}
3535 }
3536 
3537 static void
uaudio_mixer_add_selector(struct uaudio_softc * sc,const struct uaudio_terminal_node * iot,int id)3538 uaudio_mixer_add_selector(struct uaudio_softc *sc,
3539     const struct uaudio_terminal_node *iot, int id)
3540 {
3541 	const struct usb_audio_selector_unit *d = iot[id].u.su_v1;
3542 	uint16_t i;
3543 
3544 	DPRINTFN(3, "bUnitId=%d bNrInPins=%d\n",
3545 	    d->bUnitId, d->bNrInPins);
3546 
3547 	if (d->bNrInPins == 0)
3548 		return;
3549 
3550 	memset(&MIX(sc), 0, sizeof(MIX(sc)));
3551 
3552 	MIX(sc).wIndex = MAKE_WORD(d->bUnitId, sc->sc_mixer_iface_no);
3553 	MIX(sc).wValue[0] = MAKE_WORD(0, 0);
3554 	MIX(sc).nchan = 1;
3555 	MIX(sc).type = MIX_SELECTOR;
3556 	MIX(sc).ctl = SOUND_MIXER_NRDEVICES;
3557 	MIX(sc).minval = 1;
3558 	MIX(sc).maxval = d->bNrInPins;
3559 	MIX(sc).name = "selector";
3560 
3561 	i = d->baSourceId[d->bNrInPins];
3562 	if (i == 0 ||
3563 	    usbd_req_get_string_any(sc->sc_udev, NULL,
3564 	    MIX(sc).desc, sizeof(MIX(sc).desc), i) != 0) {
3565 		MIX(sc).desc[0] = 0;
3566 	}
3567 
3568 	if (MIX(sc).maxval > MAX_SELECTOR_INPUT_PIN)
3569 		MIX(sc).maxval = MAX_SELECTOR_INPUT_PIN;
3570 
3571 	MIX(sc).mul = MIX(sc).maxval - MIX(sc).minval;
3572 
3573 	for (i = 0; i < MIX(sc).maxval; i++) {
3574 		MIX(sc).slctrtype[i] =
3575 		    uaudio_mixer_determine_class(&iot[d->baSourceId[i]]);
3576 	}
3577 	for (; i < MAX_SELECTOR_INPUT_PIN; i++)
3578 		MIX(sc).slctrtype[i] = SOUND_MIXER_NRDEVICES;
3579 
3580 	uaudio_mixer_check_selectors(sc);
3581 	uaudio_mixer_add_ctl(sc, &MIX(sc));
3582 }
3583 
3584 static void
uaudio20_mixer_add_selector(struct uaudio_softc * sc,const struct uaudio_terminal_node * iot,int id)3585 uaudio20_mixer_add_selector(struct uaudio_softc *sc,
3586     const struct uaudio_terminal_node *iot, int id)
3587 {
3588 	const struct usb_audio20_selector_unit *d = iot[id].u.su_v2;
3589 	uint16_t i;
3590 
3591 	DPRINTFN(3, "bUnitId=%d bNrInPins=%d\n",
3592 	    d->bUnitId, d->bNrInPins);
3593 
3594 	if (d->bNrInPins == 0)
3595 		return;
3596 
3597 	memset(&MIX(sc), 0, sizeof(MIX(sc)));
3598 
3599 	MIX(sc).wIndex = MAKE_WORD(d->bUnitId, sc->sc_mixer_iface_no);
3600 	MIX(sc).wValue[0] = MAKE_WORD(0, 0);
3601 	MIX(sc).nchan = 1;
3602 	MIX(sc).type = MIX_SELECTOR;
3603 	MIX(sc).ctl = SOUND_MIXER_NRDEVICES;
3604 	MIX(sc).minval = 1;
3605 	MIX(sc).maxval = d->bNrInPins;
3606 	MIX(sc).name = "selector";
3607 
3608 	i = d->baSourceId[d->bNrInPins];
3609 	if (i == 0 ||
3610 	    usbd_req_get_string_any(sc->sc_udev, NULL,
3611 	    MIX(sc).desc, sizeof(MIX(sc).desc), i) != 0) {
3612 		MIX(sc).desc[0] = 0;
3613 	}
3614 
3615 	if (MIX(sc).maxval > MAX_SELECTOR_INPUT_PIN)
3616 		MIX(sc).maxval = MAX_SELECTOR_INPUT_PIN;
3617 
3618 	MIX(sc).mul = MIX(sc).maxval - MIX(sc).minval;
3619 
3620 	for (i = 0; i < MIX(sc).maxval; i++) {
3621 		MIX(sc).slctrtype[i] =
3622 		    uaudio20_mixer_determine_class(&iot[d->baSourceId[i]]);
3623 	}
3624 	for (; i < MAX_SELECTOR_INPUT_PIN; i++)
3625 		MIX(sc).slctrtype[i] = SOUND_MIXER_NRDEVICES;
3626 
3627 	uaudio_mixer_check_selectors(sc);
3628 	uaudio_mixer_add_ctl(sc, &MIX(sc));
3629 }
3630 
3631 static uint32_t
uaudio_mixer_feature_get_bmaControls(const struct usb_audio_feature_unit * d,uint8_t i)3632 uaudio_mixer_feature_get_bmaControls(const struct usb_audio_feature_unit *d,
3633     uint8_t i)
3634 {
3635 	uint32_t temp = 0;
3636 	uint32_t offset = (i * d->bControlSize);
3637 
3638 	if (d->bControlSize > 0) {
3639 		temp |= d->bmaControls[offset];
3640 		if (d->bControlSize > 1) {
3641 			temp |= d->bmaControls[offset + 1] << 8;
3642 			if (d->bControlSize > 2) {
3643 				temp |= d->bmaControls[offset + 2] << 16;
3644 				if (d->bControlSize > 3) {
3645 					temp |= d->bmaControls[offset + 3] << 24;
3646 				}
3647 			}
3648 		}
3649 	}
3650 	return (temp);
3651 }
3652 
3653 static void
uaudio_mixer_add_feature(struct uaudio_softc * sc,const struct uaudio_terminal_node * iot,int id)3654 uaudio_mixer_add_feature(struct uaudio_softc *sc,
3655     const struct uaudio_terminal_node *iot, int id)
3656 {
3657 	const struct usb_audio_feature_unit *d = iot[id].u.fu_v1;
3658 	uint32_t fumask;
3659 	uint32_t mmask;
3660 	uint32_t cmask;
3661 	uint16_t mixernumber;
3662 	uint8_t nchan;
3663 	uint8_t chan;
3664 	uint8_t ctl;
3665 	uint8_t i;
3666 
3667 	if (d->bControlSize == 0)
3668 		return;
3669 
3670 	memset(&MIX(sc), 0, sizeof(MIX(sc)));
3671 
3672 	nchan = (d->bLength - 7) / d->bControlSize;
3673 	mmask = uaudio_mixer_feature_get_bmaControls(d, 0);
3674 	cmask = 0;
3675 
3676 	if (nchan == 0)
3677 		return;
3678 
3679 	/* figure out what we can control */
3680 
3681 	for (chan = 1; chan < nchan; chan++) {
3682 		DPRINTFN(10, "chan=%d mask=%x\n",
3683 		    chan, uaudio_mixer_feature_get_bmaControls(d, chan));
3684 
3685 		cmask |= uaudio_mixer_feature_get_bmaControls(d, chan);
3686 	}
3687 
3688 	MIX(sc).wIndex = MAKE_WORD(d->bUnitId, sc->sc_mixer_iface_no);
3689 
3690 	i = d->bmaControls[nchan * d->bControlSize];
3691 	if (i == 0 ||
3692 	    usbd_req_get_string_any(sc->sc_udev, NULL,
3693 	    MIX(sc).desc, sizeof(MIX(sc).desc), i) != 0) {
3694 		MIX(sc).desc[0] = 0;
3695 	}
3696 
3697 	if (nchan > MIX_MAX_CHAN)
3698 		nchan = MIX_MAX_CHAN;
3699 
3700 	for (ctl = 1; ctl <= LOUDNESS_CONTROL; ctl++) {
3701 		fumask = FU_MASK(ctl);
3702 
3703 		DPRINTFN(5, "ctl=%d fumask=0x%04x\n",
3704 		    ctl, fumask);
3705 
3706 		if (mmask & fumask) {
3707 			MIX(sc).nchan = 1;
3708 			MIX(sc).wValue[0] = MAKE_WORD(ctl, 0);
3709 		} else if (cmask & fumask) {
3710 			MIX(sc).nchan = nchan - 1;
3711 			for (i = 1; i < nchan; i++) {
3712 				if (uaudio_mixer_feature_get_bmaControls(d, i) & fumask)
3713 					MIX(sc).wValue[i - 1] = MAKE_WORD(ctl, i);
3714 				else
3715 					MIX(sc).wValue[i - 1] = -1;
3716 			}
3717 		} else {
3718 			continue;
3719 		}
3720 
3721 		mixernumber = uaudio_mixer_determine_class(&iot[id]);
3722 
3723 		switch (ctl) {
3724 		case MUTE_CONTROL:
3725 			MIX(sc).type = MIX_ON_OFF;
3726 			MIX(sc).ctl = SOUND_MIXER_MUTE;
3727 			MIX(sc).name = "mute";
3728 			break;
3729 
3730 		case VOLUME_CONTROL:
3731 			MIX(sc).type = MIX_SIGNED_16;
3732 			MIX(sc).ctl = mixernumber;
3733 			MIX(sc).name = "vol";
3734 			break;
3735 
3736 		case BASS_CONTROL:
3737 			MIX(sc).type = MIX_SIGNED_8;
3738 			MIX(sc).ctl = SOUND_MIXER_BASS;
3739 			MIX(sc).name = "bass";
3740 			break;
3741 
3742 		case MID_CONTROL:
3743 			MIX(sc).type = MIX_SIGNED_8;
3744 			MIX(sc).ctl = SOUND_MIXER_NRDEVICES;	/* XXXXX */
3745 			MIX(sc).name = "mid";
3746 			break;
3747 
3748 		case TREBLE_CONTROL:
3749 			MIX(sc).type = MIX_SIGNED_8;
3750 			MIX(sc).ctl = SOUND_MIXER_TREBLE;
3751 			MIX(sc).name = "treble";
3752 			break;
3753 
3754 		case GRAPHIC_EQUALIZER_CONTROL:
3755 			continue;	/* XXX don't add anything */
3756 
3757 		case AGC_CONTROL:
3758 			MIX(sc).type = MIX_ON_OFF;
3759 			MIX(sc).ctl = SOUND_MIXER_NRDEVICES;	/* XXXXX */
3760 			MIX(sc).name = "agc";
3761 			break;
3762 
3763 		case DELAY_CONTROL:
3764 			MIX(sc).type = MIX_UNSIGNED_16;
3765 			MIX(sc).ctl = SOUND_MIXER_NRDEVICES;	/* XXXXX */
3766 			MIX(sc).name = "delay";
3767 			break;
3768 
3769 		case BASS_BOOST_CONTROL:
3770 			MIX(sc).type = MIX_ON_OFF;
3771 			MIX(sc).ctl = SOUND_MIXER_NRDEVICES;	/* XXXXX */
3772 			MIX(sc).name = "boost";
3773 			break;
3774 
3775 		case LOUDNESS_CONTROL:
3776 			MIX(sc).type = MIX_ON_OFF;
3777 			MIX(sc).ctl = SOUND_MIXER_LOUD;	/* Is this correct ? */
3778 			MIX(sc).name = "loudness";
3779 			break;
3780 
3781 		default:
3782 			MIX(sc).type = MIX_UNKNOWN;
3783 			break;
3784 		}
3785 
3786 		if (MIX(sc).type != MIX_UNKNOWN)
3787 			uaudio_mixer_add_ctl(sc, &MIX(sc));
3788 	}
3789 }
3790 
3791 static void
uaudio20_mixer_add_feature(struct uaudio_softc * sc,const struct uaudio_terminal_node * iot,int id)3792 uaudio20_mixer_add_feature(struct uaudio_softc *sc,
3793     const struct uaudio_terminal_node *iot, int id)
3794 {
3795 	const struct usb_audio20_feature_unit *d = iot[id].u.fu_v2;
3796 	uint32_t ctl;
3797 	uint32_t mmask;
3798 	uint32_t cmask;
3799 	uint16_t mixernumber;
3800 	uint8_t nchan;
3801 	uint8_t chan;
3802 	uint8_t i;
3803 	uint8_t what;
3804 
3805 	if (UGETDW(d->bmaControls[0]) == 0)
3806 		return;
3807 
3808 	memset(&MIX(sc), 0, sizeof(MIX(sc)));
3809 
3810 	nchan = (d->bLength - 6) / 4;
3811 	mmask = UGETDW(d->bmaControls[0]);
3812 	cmask = 0;
3813 
3814 	if (nchan == 0)
3815 		return;
3816 
3817 	/* figure out what we can control */
3818 
3819 	for (chan = 1; chan < nchan; chan++)
3820 		cmask |= UGETDW(d->bmaControls[chan]);
3821 
3822 	MIX(sc).wIndex = MAKE_WORD(d->bUnitId, sc->sc_mixer_iface_no);
3823 
3824 	i = d->bmaControls[nchan][0];
3825 	if (i == 0 ||
3826 	    usbd_req_get_string_any(sc->sc_udev, NULL,
3827 	    MIX(sc).desc, sizeof(MIX(sc).desc), i) != 0) {
3828 		MIX(sc).desc[0] = 0;
3829 	}
3830 
3831 	if (nchan > MIX_MAX_CHAN)
3832 		nchan = MIX_MAX_CHAN;
3833 
3834 	for (ctl = 3; ctl != 0; ctl <<= 2) {
3835 		mixernumber = uaudio20_mixer_determine_class(&iot[id]);
3836 
3837 		switch (ctl) {
3838 		case (3 << 0):
3839 			MIX(sc).type = MIX_ON_OFF;
3840 			MIX(sc).ctl = SOUND_MIXER_MUTE;
3841 			MIX(sc).name = "mute";
3842 			what = MUTE_CONTROL;
3843 			break;
3844 		case (3 << 2):
3845 			MIX(sc).type = MIX_SIGNED_16;
3846 			MIX(sc).ctl = mixernumber;
3847 			MIX(sc).name = "vol";
3848 			what = VOLUME_CONTROL;
3849 			break;
3850 		case (3 << 4):
3851 			MIX(sc).type = MIX_SIGNED_8;
3852 			MIX(sc).ctl = SOUND_MIXER_BASS;
3853 			MIX(sc).name = "bass";
3854 			what = BASS_CONTROL;
3855 			break;
3856 		case (3 << 6):
3857 			MIX(sc).type = MIX_SIGNED_8;
3858 			MIX(sc).ctl = SOUND_MIXER_NRDEVICES;	/* XXXXX */
3859 			MIX(sc).name = "mid";
3860 			what = MID_CONTROL;
3861 			break;
3862 		case (3 << 8):
3863 			MIX(sc).type = MIX_SIGNED_8;
3864 			MIX(sc).ctl = SOUND_MIXER_TREBLE;
3865 			MIX(sc).name = "treble";
3866 			what = TREBLE_CONTROL;
3867 			break;
3868 		case (3 << 12):
3869 			MIX(sc).type = MIX_ON_OFF;
3870 			MIX(sc).ctl = SOUND_MIXER_NRDEVICES;	/* XXXXX */
3871 			MIX(sc).name = "agc";
3872 			what = AGC_CONTROL;
3873 			break;
3874 		case (3 << 14):
3875 			MIX(sc).type = MIX_UNSIGNED_16;
3876 			MIX(sc).ctl = SOUND_MIXER_NRDEVICES;	/* XXXXX */
3877 			MIX(sc).name = "delay";
3878 			what = DELAY_CONTROL;
3879 			break;
3880 		case (3 << 16):
3881 			MIX(sc).type = MIX_ON_OFF;
3882 			MIX(sc).ctl = SOUND_MIXER_NRDEVICES;	/* XXXXX */
3883 			MIX(sc).name = "boost";
3884 			what = BASS_BOOST_CONTROL;
3885 			break;
3886 		case (3 << 18):
3887 			MIX(sc).type = MIX_ON_OFF;
3888 			MIX(sc).ctl = SOUND_MIXER_LOUD;	/* Is this correct ? */
3889 			MIX(sc).name = "loudness";
3890 			what = LOUDNESS_CONTROL;
3891 			break;
3892 		case (3 << 20):
3893 			MIX(sc).type = MIX_SIGNED_16;
3894 			MIX(sc).ctl = mixernumber;
3895 			MIX(sc).name = "igain";
3896 			what = INPUT_GAIN_CONTROL;
3897 			break;
3898 		case (3 << 22):
3899 			MIX(sc).type = MIX_SIGNED_16;
3900 			MIX(sc).ctl = mixernumber;
3901 			MIX(sc).name = "igainpad";
3902 			what = INPUT_GAIN_PAD_CONTROL;
3903 			break;
3904 		default:
3905 			continue;
3906 		}
3907 
3908 		if ((mmask & ctl) == ctl) {
3909 			MIX(sc).nchan = 1;
3910 			MIX(sc).wValue[0] = MAKE_WORD(what, 0);
3911 		} else if ((cmask & ctl) == ctl) {
3912 			MIX(sc).nchan = nchan - 1;
3913 			for (i = 1; i < nchan; i++) {
3914 				if ((UGETDW(d->bmaControls[i]) & ctl) == ctl)
3915 					MIX(sc).wValue[i - 1] = MAKE_WORD(what, i);
3916 				else
3917 					MIX(sc).wValue[i - 1] = -1;
3918 			}
3919 		} else {
3920 			continue;
3921 		}
3922 
3923 		if (MIX(sc).type != MIX_UNKNOWN)
3924 			uaudio_mixer_add_ctl(sc, &MIX(sc));
3925 	}
3926 }
3927 
3928 static void
uaudio_mixer_add_processing_updown(struct uaudio_softc * sc,const struct uaudio_terminal_node * iot,int id)3929 uaudio_mixer_add_processing_updown(struct uaudio_softc *sc,
3930     const struct uaudio_terminal_node *iot, int id)
3931 {
3932 	const struct usb_audio_processing_unit_0 *d0 = iot[id].u.pu_v1;
3933 	const struct usb_audio_processing_unit_1 *d1 =
3934 	    (const void *)(d0->baSourceId + d0->bNrInPins);
3935 	const struct usb_audio_processing_unit_updown *ud =
3936 	    (const void *)(d1->bmControls + d1->bControlSize);
3937 	uint8_t i;
3938 
3939 	if (uaudio_mixer_verify_desc(d0, sizeof(*ud)) == NULL) {
3940 		return;
3941 	}
3942 	if (uaudio_mixer_verify_desc(d0, sizeof(*ud) + (2 * ud->bNrModes))
3943 	    == NULL) {
3944 		return;
3945 	}
3946 	DPRINTFN(3, "bUnitId=%d bNrModes=%d\n",
3947 	    d0->bUnitId, ud->bNrModes);
3948 
3949 	if (!(d1->bmControls[0] & UA_PROC_MASK(UD_MODE_SELECT_CONTROL))) {
3950 		DPRINTF("no mode select\n");
3951 		return;
3952 	}
3953 	memset(&MIX(sc), 0, sizeof(MIX(sc)));
3954 
3955 	MIX(sc).wIndex = MAKE_WORD(d0->bUnitId, sc->sc_mixer_iface_no);
3956 	MIX(sc).nchan = 1;
3957 	MIX(sc).wValue[0] = MAKE_WORD(UD_MODE_SELECT_CONTROL, 0);
3958 	MIX(sc).type = MIX_ON_OFF;		/* XXX */
3959 
3960 	for (i = 0; i < ud->bNrModes; i++) {
3961 		DPRINTFN(3, "i=%d bm=0x%x\n", i, UGETW(ud->waModes[i]));
3962 		/* XXX */
3963 	}
3964 
3965 	uaudio_mixer_add_ctl(sc, &MIX(sc));
3966 }
3967 
3968 static void
uaudio_mixer_add_processing(struct uaudio_softc * sc,const struct uaudio_terminal_node * iot,int id)3969 uaudio_mixer_add_processing(struct uaudio_softc *sc,
3970     const struct uaudio_terminal_node *iot, int id)
3971 {
3972 	const struct usb_audio_processing_unit_0 *d0 = iot[id].u.pu_v1;
3973 	const struct usb_audio_processing_unit_1 *d1 =
3974 	    (const void *)(d0->baSourceId + d0->bNrInPins);
3975 	uint16_t ptype;
3976 
3977 	memset(&MIX(sc), 0, sizeof(MIX(sc)));
3978 
3979 	ptype = UGETW(d0->wProcessType);
3980 
3981 	DPRINTFN(3, "wProcessType=%d bUnitId=%d "
3982 	    "bNrInPins=%d\n", ptype, d0->bUnitId, d0->bNrInPins);
3983 
3984 	if (d1->bControlSize == 0) {
3985 		return;
3986 	}
3987 	if (d1->bmControls[0] & UA_PROC_ENABLE_MASK) {
3988 		MIX(sc).wIndex = MAKE_WORD(d0->bUnitId, sc->sc_mixer_iface_no);
3989 		MIX(sc).nchan = 1;
3990 		MIX(sc).wValue[0] = MAKE_WORD(XX_ENABLE_CONTROL, 0);
3991 		MIX(sc).type = MIX_ON_OFF;
3992 		uaudio_mixer_add_ctl(sc, &MIX(sc));
3993 	}
3994 	switch (ptype) {
3995 	case UPDOWNMIX_PROCESS:
3996 		uaudio_mixer_add_processing_updown(sc, iot, id);
3997 		break;
3998 
3999 	case DOLBY_PROLOGIC_PROCESS:
4000 	case P3D_STEREO_EXTENDER_PROCESS:
4001 	case REVERBATION_PROCESS:
4002 	case CHORUS_PROCESS:
4003 	case DYN_RANGE_COMP_PROCESS:
4004 	default:
4005 		DPRINTF("unit %d, type=%d is not implemented\n",
4006 		    d0->bUnitId, ptype);
4007 		break;
4008 	}
4009 }
4010 
4011 static void
uaudio_mixer_add_extension(struct uaudio_softc * sc,const struct uaudio_terminal_node * iot,int id)4012 uaudio_mixer_add_extension(struct uaudio_softc *sc,
4013     const struct uaudio_terminal_node *iot, int id)
4014 {
4015 	const struct usb_audio_extension_unit_0 *d0 = iot[id].u.eu_v1;
4016 	const struct usb_audio_extension_unit_1 *d1 =
4017 	    (const void *)(d0->baSourceId + d0->bNrInPins);
4018 
4019 	DPRINTFN(3, "bUnitId=%d bNrInPins=%d\n",
4020 	    d0->bUnitId, d0->bNrInPins);
4021 
4022 	if (sc->sc_uq_au_no_xu) {
4023 		return;
4024 	}
4025 	if (d1->bControlSize == 0) {
4026 		return;
4027 	}
4028 	if (d1->bmControls[0] & UA_EXT_ENABLE_MASK) {
4029 		memset(&MIX(sc), 0, sizeof(MIX(sc)));
4030 
4031 		MIX(sc).wIndex = MAKE_WORD(d0->bUnitId, sc->sc_mixer_iface_no);
4032 		MIX(sc).nchan = 1;
4033 		MIX(sc).wValue[0] = MAKE_WORD(UA_EXT_ENABLE, 0);
4034 		MIX(sc).type = MIX_ON_OFF;
4035 
4036 		uaudio_mixer_add_ctl(sc, &MIX(sc));
4037 	}
4038 }
4039 
4040 static const void *
uaudio_mixer_verify_desc(const void * arg,uint32_t len)4041 uaudio_mixer_verify_desc(const void *arg, uint32_t len)
4042 {
4043 	const struct usb_audio_mixer_unit_1 *d1;
4044 	const struct usb_audio_extension_unit_1 *e1;
4045 	const struct usb_audio_processing_unit_1 *u1;
4046 
4047 	union {
4048 		const struct usb_descriptor *desc;
4049 		const struct usb_audio_input_terminal *it;
4050 		const struct usb_audio_output_terminal *ot;
4051 		const struct usb_audio_mixer_unit_0 *mu;
4052 		const struct usb_audio_selector_unit *su;
4053 		const struct usb_audio_feature_unit *fu;
4054 		const struct usb_audio_processing_unit_0 *pu;
4055 		const struct usb_audio_extension_unit_0 *eu;
4056 	}     u;
4057 
4058 	u.desc = arg;
4059 
4060 	if (u.desc == NULL) {
4061 		goto error;
4062 	}
4063 	if (u.desc->bDescriptorType != UDESC_CS_INTERFACE) {
4064 		goto error;
4065 	}
4066 	switch (u.desc->bDescriptorSubtype) {
4067 	case UDESCSUB_AC_INPUT:
4068 		len += sizeof(*u.it);
4069 		break;
4070 
4071 	case UDESCSUB_AC_OUTPUT:
4072 		len += sizeof(*u.ot);
4073 		break;
4074 
4075 	case UDESCSUB_AC_MIXER:
4076 		len += sizeof(*u.mu);
4077 
4078 		if (u.desc->bLength < len) {
4079 			goto error;
4080 		}
4081 		len += u.mu->bNrInPins;
4082 
4083 		if (u.desc->bLength < len) {
4084 			goto error;
4085 		}
4086 		d1 = (const void *)(u.mu->baSourceId + u.mu->bNrInPins);
4087 
4088 		len += sizeof(*d1);
4089 		break;
4090 
4091 	case UDESCSUB_AC_SELECTOR:
4092 		len += sizeof(*u.su);
4093 
4094 		if (u.desc->bLength < len) {
4095 			goto error;
4096 		}
4097 		len += u.su->bNrInPins + 1;
4098 		break;
4099 
4100 	case UDESCSUB_AC_FEATURE:
4101 		len += sizeof(*u.fu) + 1;
4102 
4103 		if (u.desc->bLength < len)
4104 			goto error;
4105 
4106 		len += u.fu->bControlSize;
4107 		break;
4108 
4109 	case UDESCSUB_AC_PROCESSING:
4110 		len += sizeof(*u.pu);
4111 
4112 		if (u.desc->bLength < len) {
4113 			goto error;
4114 		}
4115 		len += u.pu->bNrInPins;
4116 
4117 		if (u.desc->bLength < len) {
4118 			goto error;
4119 		}
4120 		u1 = (const void *)(u.pu->baSourceId + u.pu->bNrInPins);
4121 
4122 		len += sizeof(*u1);
4123 
4124 		if (u.desc->bLength < len) {
4125 			goto error;
4126 		}
4127 		len += u1->bControlSize;
4128 
4129 		break;
4130 
4131 	case UDESCSUB_AC_EXTENSION:
4132 		len += sizeof(*u.eu);
4133 
4134 		if (u.desc->bLength < len) {
4135 			goto error;
4136 		}
4137 		len += u.eu->bNrInPins;
4138 
4139 		if (u.desc->bLength < len) {
4140 			goto error;
4141 		}
4142 		e1 = (const void *)(u.eu->baSourceId + u.eu->bNrInPins);
4143 
4144 		len += sizeof(*e1);
4145 
4146 		if (u.desc->bLength < len) {
4147 			goto error;
4148 		}
4149 		len += e1->bControlSize;
4150 		break;
4151 
4152 	default:
4153 		goto error;
4154 	}
4155 
4156 	if (u.desc->bLength < len) {
4157 		goto error;
4158 	}
4159 	return (u.desc);
4160 
4161 error:
4162 	if (u.desc) {
4163 		DPRINTF("invalid descriptor, type=%d, "
4164 		    "sub_type=%d, len=%d of %d bytes\n",
4165 		    u.desc->bDescriptorType,
4166 		    u.desc->bDescriptorSubtype,
4167 		    u.desc->bLength, len);
4168 	}
4169 	return (NULL);
4170 }
4171 
4172 static const void *
uaudio20_mixer_verify_desc(const void * arg,uint32_t len)4173 uaudio20_mixer_verify_desc(const void *arg, uint32_t len)
4174 {
4175 	const struct usb_audio20_mixer_unit_1 *d1;
4176 	const struct usb_audio20_extension_unit_1 *e1;
4177 	const struct usb_audio20_processing_unit_1 *u1;
4178 	const struct usb_audio20_clock_selector_unit_1 *c1;
4179 
4180 	union {
4181 		const struct usb_descriptor *desc;
4182 		const struct usb_audio20_clock_source_unit *csrc;
4183 		const struct usb_audio20_clock_selector_unit_0 *csel;
4184 		const struct usb_audio20_clock_multiplier_unit *cmul;
4185 		const struct usb_audio20_input_terminal *it;
4186 		const struct usb_audio20_output_terminal *ot;
4187 		const struct usb_audio20_mixer_unit_0 *mu;
4188 		const struct usb_audio20_selector_unit *su;
4189 		const struct usb_audio20_feature_unit *fu;
4190 		const struct usb_audio20_sample_rate_unit *ru;
4191 		const struct usb_audio20_processing_unit_0 *pu;
4192 		const struct usb_audio20_extension_unit_0 *eu;
4193 		const struct usb_audio20_effect_unit *ef;
4194 	}     u;
4195 
4196 	u.desc = arg;
4197 
4198 	if (u.desc == NULL)
4199 		goto error;
4200 
4201 	if (u.desc->bDescriptorType != UDESC_CS_INTERFACE)
4202 		goto error;
4203 
4204 	switch (u.desc->bDescriptorSubtype) {
4205 	case UDESCSUB_AC_INPUT:
4206 		len += sizeof(*u.it);
4207 		break;
4208 
4209 	case UDESCSUB_AC_OUTPUT:
4210 		len += sizeof(*u.ot);
4211 		break;
4212 
4213 	case UDESCSUB_AC_MIXER:
4214 		len += sizeof(*u.mu);
4215 
4216 		if (u.desc->bLength < len)
4217 			goto error;
4218 		len += u.mu->bNrInPins;
4219 
4220 		if (u.desc->bLength < len)
4221 			goto error;
4222 
4223 		d1 = (const void *)(u.mu->baSourceId + u.mu->bNrInPins);
4224 
4225 		len += sizeof(*d1) + d1->bNrChannels;
4226 		break;
4227 
4228 	case UDESCSUB_AC_SELECTOR:
4229 		len += sizeof(*u.su);
4230 
4231 		if (u.desc->bLength < len)
4232 			goto error;
4233 
4234 		len += u.su->bNrInPins + 1;
4235 		break;
4236 
4237 	case UDESCSUB_AC_FEATURE:
4238 		len += sizeof(*u.fu) + 1;
4239 		break;
4240 
4241 	case UDESCSUB_AC_EFFECT:
4242 		len += sizeof(*u.ef) + 4;
4243 		break;
4244 
4245 	case UDESCSUB_AC_PROCESSING_V2:
4246 		len += sizeof(*u.pu);
4247 
4248 		if (u.desc->bLength < len)
4249 			goto error;
4250 
4251 		len += u.pu->bNrInPins;
4252 
4253 		if (u.desc->bLength < len)
4254 			goto error;
4255 
4256 		u1 = (const void *)(u.pu->baSourceId + u.pu->bNrInPins);
4257 
4258 		len += sizeof(*u1);
4259 		break;
4260 
4261 	case UDESCSUB_AC_EXTENSION_V2:
4262 		len += sizeof(*u.eu);
4263 
4264 		if (u.desc->bLength < len)
4265 			goto error;
4266 
4267 		len += u.eu->bNrInPins;
4268 
4269 		if (u.desc->bLength < len)
4270 			goto error;
4271 
4272 		e1 = (const void *)(u.eu->baSourceId + u.eu->bNrInPins);
4273 
4274 		len += sizeof(*e1);
4275 		break;
4276 
4277 	case UDESCSUB_AC_CLOCK_SRC:
4278 		len += sizeof(*u.csrc);
4279 		break;
4280 
4281 	case UDESCSUB_AC_CLOCK_SEL:
4282 		len += sizeof(*u.csel);
4283 
4284 		if (u.desc->bLength < len)
4285 			goto error;
4286 
4287 		len += u.csel->bNrInPins;
4288 
4289 		if (u.desc->bLength < len)
4290 			goto error;
4291 
4292 		c1 = (const void *)(u.csel->baCSourceId + u.csel->bNrInPins);
4293 
4294 		len += sizeof(*c1);
4295 		break;
4296 
4297 	case UDESCSUB_AC_CLOCK_MUL:
4298 		len += sizeof(*u.cmul);
4299 		break;
4300 
4301 	case UDESCSUB_AC_SAMPLE_RT:
4302 		len += sizeof(*u.ru);
4303 		break;
4304 
4305 	default:
4306 		goto error;
4307 	}
4308 
4309 	if (u.desc->bLength < len)
4310 		goto error;
4311 
4312 	return (u.desc);
4313 
4314 error:
4315 	if (u.desc) {
4316 		DPRINTF("invalid descriptor, type=%d, "
4317 		    "sub_type=%d, len=%d of %d bytes\n",
4318 		    u.desc->bDescriptorType,
4319 		    u.desc->bDescriptorSubtype,
4320 		    u.desc->bLength, len);
4321 	}
4322 	return (NULL);
4323 }
4324 
4325 static struct usb_audio_cluster
uaudio_mixer_get_cluster(uint8_t id,const struct uaudio_terminal_node * iot)4326 uaudio_mixer_get_cluster(uint8_t id, const struct uaudio_terminal_node *iot)
4327 {
4328 	struct usb_audio_cluster r;
4329 	const struct usb_descriptor *dp;
4330 	uint8_t i;
4331 
4332 	for (i = 0; i < UAUDIO_RECURSE_LIMIT; i++) {	/* avoid infinite loops */
4333 		dp = iot[id].u.desc;
4334 		if (dp == NULL) {
4335 			goto error;
4336 		}
4337 		switch (dp->bDescriptorSubtype) {
4338 		case UDESCSUB_AC_INPUT:
4339 			r.bNrChannels = iot[id].u.it_v1->bNrChannels;
4340 			r.wChannelConfig[0] = iot[id].u.it_v1->wChannelConfig[0];
4341 			r.wChannelConfig[1] = iot[id].u.it_v1->wChannelConfig[1];
4342 			r.iChannelNames = iot[id].u.it_v1->iChannelNames;
4343 			goto done;
4344 
4345 		case UDESCSUB_AC_OUTPUT:
4346 			id = iot[id].u.ot_v1->bSourceId;
4347 			break;
4348 
4349 		case UDESCSUB_AC_MIXER:
4350 			r = *(const struct usb_audio_cluster *)
4351 			    &iot[id].u.mu_v1->baSourceId[
4352 			    iot[id].u.mu_v1->bNrInPins];
4353 			goto done;
4354 
4355 		case UDESCSUB_AC_SELECTOR:
4356 			if (iot[id].u.su_v1->bNrInPins > 0) {
4357 				/* XXX This is not really right */
4358 				id = iot[id].u.su_v1->baSourceId[0];
4359 			}
4360 			break;
4361 
4362 		case UDESCSUB_AC_FEATURE:
4363 			id = iot[id].u.fu_v1->bSourceId;
4364 			break;
4365 
4366 		case UDESCSUB_AC_PROCESSING:
4367 			r = *((const struct usb_audio_cluster *)
4368 			    &iot[id].u.pu_v1->baSourceId[
4369 			    iot[id].u.pu_v1->bNrInPins]);
4370 			goto done;
4371 
4372 		case UDESCSUB_AC_EXTENSION:
4373 			r = *((const struct usb_audio_cluster *)
4374 			    &iot[id].u.eu_v1->baSourceId[
4375 			    iot[id].u.eu_v1->bNrInPins]);
4376 			goto done;
4377 
4378 		default:
4379 			goto error;
4380 		}
4381 	}
4382 error:
4383 	DPRINTF("bad data\n");
4384 	memset(&r, 0, sizeof(r));
4385 done:
4386 	return (r);
4387 }
4388 
4389 static struct usb_audio20_cluster
uaudio20_mixer_get_cluster(uint8_t id,const struct uaudio_terminal_node * iot)4390 uaudio20_mixer_get_cluster(uint8_t id, const struct uaudio_terminal_node *iot)
4391 {
4392 	struct usb_audio20_cluster r;
4393 	const struct usb_descriptor *dp;
4394 	uint8_t i;
4395 
4396 	for (i = 0; i < UAUDIO_RECURSE_LIMIT; i++) {	/* avoid infinite loops */
4397 		dp = iot[id].u.desc;
4398 		if (dp == NULL)
4399 			goto error;
4400 
4401 		switch (dp->bDescriptorSubtype) {
4402 		case UDESCSUB_AC_INPUT:
4403 			r.bNrChannels = iot[id].u.it_v2->bNrChannels;
4404 			r.bmChannelConfig[0] = iot[id].u.it_v2->bmChannelConfig[0];
4405 			r.bmChannelConfig[1] = iot[id].u.it_v2->bmChannelConfig[1];
4406 			r.bmChannelConfig[2] = iot[id].u.it_v2->bmChannelConfig[2];
4407 			r.bmChannelConfig[3] = iot[id].u.it_v2->bmChannelConfig[3];
4408 			r.iChannelNames = iot[id].u.it_v2->iTerminal;
4409 			goto done;
4410 
4411 		case UDESCSUB_AC_OUTPUT:
4412 			id = iot[id].u.ot_v2->bSourceId;
4413 			break;
4414 
4415 		case UDESCSUB_AC_MIXER:
4416 			r = *(const struct usb_audio20_cluster *)
4417 			    &iot[id].u.mu_v2->baSourceId[
4418 			    iot[id].u.mu_v2->bNrInPins];
4419 			goto done;
4420 
4421 		case UDESCSUB_AC_SELECTOR:
4422 			if (iot[id].u.su_v2->bNrInPins > 0) {
4423 				/* XXX This is not really right */
4424 				id = iot[id].u.su_v2->baSourceId[0];
4425 			}
4426 			break;
4427 
4428 		case UDESCSUB_AC_SAMPLE_RT:
4429 			id = iot[id].u.ru_v2->bSourceId;
4430 			break;
4431 
4432 		case UDESCSUB_AC_EFFECT:
4433 			id = iot[id].u.ef_v2->bSourceId;
4434 			break;
4435 
4436 		case UDESCSUB_AC_FEATURE:
4437 			id = iot[id].u.fu_v2->bSourceId;
4438 			break;
4439 
4440 		case UDESCSUB_AC_PROCESSING_V2:
4441 			r = *((const struct usb_audio20_cluster *)
4442 			    &iot[id].u.pu_v2->baSourceId[
4443 			    iot[id].u.pu_v2->bNrInPins]);
4444 			goto done;
4445 
4446 		case UDESCSUB_AC_EXTENSION_V2:
4447 			r = *((const struct usb_audio20_cluster *)
4448 			    &iot[id].u.eu_v2->baSourceId[
4449 			    iot[id].u.eu_v2->bNrInPins]);
4450 			goto done;
4451 
4452 		default:
4453 			goto error;
4454 		}
4455 	}
4456 error:
4457 	DPRINTF("Bad data!\n");
4458 	memset(&r, 0, sizeof(r));
4459 done:
4460 	return (r);
4461 }
4462 
4463 static bool
uaudio_mixer_foreach_input(const struct uaudio_terminal_node * iot,uint8_t * pindex)4464 uaudio_mixer_foreach_input(const struct uaudio_terminal_node *iot, uint8_t *pindex)
4465 {
4466 	uint8_t n;
4467 
4468 	n = *pindex;
4469 
4470 	while (1) {
4471 		if (!n--)
4472 			n = iot->usr.id_max;
4473 		if (n == 0)
4474 			return (false);
4475 		if (iot->usr.bit_input[n / 8] & (1 << (n % 8)))
4476 			break;
4477 	}
4478 	*pindex = n;
4479 	return (true);
4480 }
4481 
4482 static bool
uaudio_mixer_foreach_output(const struct uaudio_terminal_node * iot,uint8_t * pindex)4483 uaudio_mixer_foreach_output(const struct uaudio_terminal_node *iot, uint8_t *pindex)
4484 {
4485 	uint8_t n;
4486 
4487 	n = *pindex;
4488 
4489 	while (1) {
4490 		if (!n--)
4491 			n = iot->usr.id_max;
4492 		if (n == 0)
4493 			return (false);
4494 		if (iot->usr.bit_output[n / 8] & (1 << (n % 8)))
4495 			break;
4496 	}
4497 	*pindex = n;
4498 	return (true);
4499 }
4500 
4501 struct uaudio_tt_to_feature {
4502 	uint16_t terminal_type;
4503 	uint16_t feature;
4504 };
4505 
4506 static const struct uaudio_tt_to_feature uaudio_tt_to_feature[] = {
4507 	{UATI_MICROPHONE, SOUND_MIXER_MIC},
4508 	{UATI_DESKMICROPHONE, SOUND_MIXER_MIC},
4509 	{UATI_PERSONALMICROPHONE, SOUND_MIXER_MIC},
4510 	{UATI_OMNIMICROPHONE, SOUND_MIXER_MIC},
4511 	{UATI_MICROPHONEARRAY, SOUND_MIXER_MIC},
4512 	{UATI_PROCMICROPHONEARR, SOUND_MIXER_MIC},
4513 
4514 	{UATE_ANALOGCONN, SOUND_MIXER_LINE},
4515 	{UATE_LINECONN, SOUND_MIXER_LINE},
4516 	{UATE_LEGACYCONN, SOUND_MIXER_LINE},
4517 
4518 	{UATE_DIGITALAUIFC, SOUND_MIXER_ALTPCM},
4519 	{UATE_SPDIF, SOUND_MIXER_ALTPCM},
4520 	{UATE_1394DA, SOUND_MIXER_ALTPCM},
4521 	{UATE_1394DV, SOUND_MIXER_ALTPCM},
4522 
4523 	{UATF_CDPLAYER, SOUND_MIXER_CD},
4524 
4525 	{UATF_SYNTHESIZER, SOUND_MIXER_SYNTH},
4526 
4527 	{UATF_VIDEODISCAUDIO, SOUND_MIXER_VIDEO},
4528 	{UATF_DVDAUDIO, SOUND_MIXER_VIDEO},
4529 	{UATF_TVTUNERAUDIO, SOUND_MIXER_VIDEO},
4530 
4531 	{UATF_RADIORECV, SOUND_MIXER_RADIO},
4532 	{UATF_RADIOXMIT, SOUND_MIXER_RADIO},
4533 
4534 	{}	/* END */
4535 };
4536 
4537 static uint16_t
uaudio_mixer_get_feature_by_tt(uint16_t terminal_type,uint16_t default_type)4538 uaudio_mixer_get_feature_by_tt(uint16_t terminal_type, uint16_t default_type)
4539 {
4540 	const struct uaudio_tt_to_feature *uat = uaudio_tt_to_feature;
4541 	uint16_t retval;
4542 
4543 	if (terminal_type == 0) {
4544 		retval = default_type;
4545 	} else while (1) {
4546 		if (uat->terminal_type == 0) {
4547 			switch (terminal_type >> 8) {
4548 			case UATI_UNDEFINED >> 8:
4549 				retval = SOUND_MIXER_RECLEV;
4550 				goto done;
4551 			case UATO_UNDEFINED >> 8:
4552 				retval = SOUND_MIXER_PCM;
4553 				goto done;
4554 			case UATT_UNDEFINED >> 8:
4555 				retval = SOUND_MIXER_PHONEIN;
4556 				goto done;
4557 			default:
4558 				retval = default_type;
4559 				goto done;
4560 			}
4561 		} else if (uat->terminal_type == terminal_type) {
4562 			retval = uat->feature;
4563 			goto done;
4564 		}
4565 		uat++;
4566 	}
4567 done:
4568 	DPRINTF("terminal_type=0x%04x RET=%d DEF=%d\n",
4569 	    terminal_type, retval, default_type);
4570 	return (retval);
4571 }
4572 
4573 static uint16_t
uaudio_mixer_determine_class(const struct uaudio_terminal_node * iot)4574 uaudio_mixer_determine_class(const struct uaudio_terminal_node *iot)
4575 {
4576 	const struct uaudio_terminal_node *ptr;
4577 	uint16_t terminal_type_input = 0;
4578 	uint16_t terminal_type_output = 0;
4579 	uint16_t temp;
4580 	uint8_t match = 0;
4581 	uint8_t i;
4582 
4583 	for (i = 0; uaudio_mixer_foreach_input(iot, &i); ) {
4584 		ptr = iot->root + i;
4585 		temp = UGETW(ptr->u.it_v1->wTerminalType);
4586 
4587 		if (temp == 0)
4588 			continue;
4589 		else if (temp == UAT_STREAM)
4590 			match |= 1;
4591 		else if ((temp & 0xFF00) != (UAT_UNDEFINED & 0xff00))
4592 			terminal_type_input = temp;
4593 	}
4594 
4595 	for (i = 0; uaudio_mixer_foreach_output(iot, &i); ) {
4596 		ptr = iot->root + i;
4597 		temp = UGETW(ptr->u.ot_v1->wTerminalType);
4598 
4599 		if (temp == 0)
4600 			continue;
4601 		else if (temp == UAT_STREAM)
4602 			match |= 2;
4603 		else if ((temp & 0xFF00) != (UAT_UNDEFINED & 0xff00))
4604 			terminal_type_output = temp;
4605 	}
4606 
4607 	DPRINTF("MATCH=%d IN=0x%04x OUT=0x%04x\n",
4608 	    match, terminal_type_input, terminal_type_output);
4609 
4610 	switch (match) {
4611 	case 0:	/* not connected to USB */
4612 		if (terminal_type_output != 0) {
4613 			return (uaudio_mixer_get_feature_by_tt(
4614 			    terminal_type_output, SOUND_MIXER_MONITOR));
4615 		} else {
4616 			return (uaudio_mixer_get_feature_by_tt(
4617 			    terminal_type_input, SOUND_MIXER_MONITOR));
4618 		}
4619 	case 3:	/* connected to both USB input and USB output */
4620 		return (SOUND_MIXER_IMIX);
4621 	case 2:	/* connected to USB output */
4622 		return (uaudio_mixer_get_feature_by_tt(
4623 		    terminal_type_input, SOUND_MIXER_RECLEV));
4624 	case 1: /* connected to USB input */
4625 		return (uaudio_mixer_get_feature_by_tt(
4626 		    terminal_type_output, SOUND_MIXER_PCM));
4627 	default:
4628 		return (SOUND_MIXER_NRDEVICES);
4629 	}
4630 }
4631 
4632 static uint16_t
uaudio20_mixer_determine_class(const struct uaudio_terminal_node * iot)4633 uaudio20_mixer_determine_class(const struct uaudio_terminal_node *iot)
4634 {
4635 	const struct uaudio_terminal_node *ptr;
4636 	uint16_t terminal_type_input = 0;
4637 	uint16_t terminal_type_output = 0;
4638 	uint16_t temp;
4639 	uint8_t match = 0;
4640 	uint8_t i;
4641 
4642 	for (i = 0; uaudio_mixer_foreach_input(iot, &i); ) {
4643 		ptr = iot->root + i;
4644 		temp = UGETW(ptr->u.it_v2->wTerminalType);
4645 
4646 		if (temp == 0)
4647 			continue;
4648 		else if (temp == UAT_STREAM)
4649 			match |= 1;
4650 		else if ((temp & 0xFF00) != (UAT_UNDEFINED & 0xff00))
4651 			terminal_type_input = temp;
4652 	}
4653 
4654 	for (i = 0; uaudio_mixer_foreach_output(iot, &i); ) {
4655 		ptr = iot->root + i;
4656 		temp = UGETW(ptr->u.ot_v2->wTerminalType);
4657 
4658 		if (temp == 0)
4659 			continue;
4660 		else if (temp == UAT_STREAM)
4661 			match |= 2;
4662 		else if ((temp & 0xFF00) != (UAT_UNDEFINED & 0xff00))
4663 			terminal_type_output = temp;
4664 	}
4665 
4666 	DPRINTF("MATCH=%d IN=0x%04x OUT=0x%04x\n",
4667 	    match, terminal_type_input, terminal_type_output);
4668 
4669 	switch (match) {
4670 	case 0:	/* not connected to USB */
4671 		if (terminal_type_output != 0) {
4672 			return (uaudio_mixer_get_feature_by_tt(
4673 			    terminal_type_output, SOUND_MIXER_MONITOR));
4674 		} else {
4675 			return (uaudio_mixer_get_feature_by_tt(
4676 			    terminal_type_input, SOUND_MIXER_MONITOR));
4677 		}
4678 	case 3:	/* connected to both USB input and USB output */
4679 		return (SOUND_MIXER_IMIX);
4680 	case 2:	/* connected to USB output */
4681 		return (uaudio_mixer_get_feature_by_tt(
4682 		    terminal_type_input, SOUND_MIXER_RECLEV));
4683 	case 1: /* connected to USB input */
4684 		return (uaudio_mixer_get_feature_by_tt(
4685 		    terminal_type_output, SOUND_MIXER_PCM));
4686 	default:
4687 		return (SOUND_MIXER_NRDEVICES);
4688 	}
4689 }
4690 
4691 static void
uaudio_mixer_merge_outputs(struct uaudio_search_result * dst,const struct uaudio_search_result * src)4692 uaudio_mixer_merge_outputs(struct uaudio_search_result *dst,
4693     const struct uaudio_search_result *src)
4694 {
4695 	const uint8_t max = sizeof(src->bit_output) / sizeof(src->bit_output[0]);
4696 	uint8_t x;
4697 
4698 	for (x = 0; x != max; x++)
4699 		dst->bit_output[x] |= src->bit_output[x];
4700 }
4701 
4702 static void
uaudio_mixer_find_inputs_sub(struct uaudio_terminal_node * root,const uint8_t * p_id,uint8_t n_id,struct uaudio_search_result * info)4703 uaudio_mixer_find_inputs_sub(struct uaudio_terminal_node *root,
4704     const uint8_t *p_id, uint8_t n_id,
4705     struct uaudio_search_result *info)
4706 {
4707 	struct uaudio_terminal_node *iot;
4708 	uint8_t n;
4709 	uint8_t i;
4710 
4711 	for (n = 0; n < n_id; n++) {
4712 		i = p_id[n];
4713 
4714 		if (info->recurse_level == UAUDIO_RECURSE_LIMIT) {
4715 			DPRINTF("avoided going into a circle at id=%d!\n", i);
4716 			return;
4717 		}
4718 
4719 		info->recurse_level++;
4720 
4721 		iot = (root + i);
4722 
4723 		if (iot->u.desc == NULL)
4724 			continue;
4725 
4726 		switch (iot->u.desc->bDescriptorSubtype) {
4727 		case UDESCSUB_AC_INPUT:
4728 			uaudio_mixer_merge_outputs(&iot->usr, info);
4729 			info->bit_input[i / 8] |= (1 << (i % 8));
4730 			break;
4731 
4732 		case UDESCSUB_AC_FEATURE:
4733 			uaudio_mixer_merge_outputs(&iot->usr, info);
4734 			uaudio_mixer_find_inputs_sub(
4735 			    root, &iot->u.fu_v1->bSourceId, 1, info);
4736 			break;
4737 
4738 		case UDESCSUB_AC_OUTPUT:
4739 			info->bit_output[i / 8] |= (1 << (i % 8));
4740 			uaudio_mixer_find_inputs_sub(
4741 			    root, &iot->u.ot_v1->bSourceId, 1, info);
4742 			info->bit_output[i / 8] &= ~(1 << (i % 8));
4743 			break;
4744 
4745 		case UDESCSUB_AC_MIXER:
4746 			uaudio_mixer_merge_outputs(&iot->usr, info);
4747 			uaudio_mixer_find_inputs_sub(
4748 			    root, iot->u.mu_v1->baSourceId,
4749 			    iot->u.mu_v1->bNrInPins, info);
4750 			break;
4751 
4752 		case UDESCSUB_AC_SELECTOR:
4753 			uaudio_mixer_merge_outputs(&iot->usr, info);
4754 			uaudio_mixer_find_inputs_sub(
4755 			    root, iot->u.su_v1->baSourceId,
4756 			    iot->u.su_v1->bNrInPins, info);
4757 			break;
4758 
4759 		case UDESCSUB_AC_PROCESSING:
4760 			uaudio_mixer_merge_outputs(&iot->usr, info);
4761 			uaudio_mixer_find_inputs_sub(
4762 			    root, iot->u.pu_v1->baSourceId,
4763 			    iot->u.pu_v1->bNrInPins, info);
4764 			break;
4765 
4766 		case UDESCSUB_AC_EXTENSION:
4767 			uaudio_mixer_merge_outputs(&iot->usr, info);
4768 			uaudio_mixer_find_inputs_sub(
4769 			    root, iot->u.eu_v1->baSourceId,
4770 			    iot->u.eu_v1->bNrInPins, info);
4771 			break;
4772 
4773 		default:
4774 			break;
4775 		}
4776 	}
4777 }
4778 
4779 static void
uaudio20_mixer_find_inputs_sub(struct uaudio_terminal_node * root,const uint8_t * p_id,uint8_t n_id,struct uaudio_search_result * info)4780 uaudio20_mixer_find_inputs_sub(struct uaudio_terminal_node *root,
4781     const uint8_t *p_id, uint8_t n_id,
4782     struct uaudio_search_result *info)
4783 {
4784 	struct uaudio_terminal_node *iot;
4785 	uint8_t n;
4786 	uint8_t i;
4787 
4788 	for (n = 0; n < n_id; n++) {
4789 		i = p_id[n];
4790 
4791 		if (info->recurse_level == UAUDIO_RECURSE_LIMIT) {
4792 			DPRINTF("avoided going into a circle at id=%d!\n", i);
4793 			return;
4794 		}
4795 
4796 		info->recurse_level++;
4797 
4798 		iot = (root + i);
4799 
4800 		if (iot->u.desc == NULL)
4801 			continue;
4802 
4803 		switch (iot->u.desc->bDescriptorSubtype) {
4804 		case UDESCSUB_AC_INPUT:
4805 			uaudio_mixer_merge_outputs(&iot->usr, info);
4806 			info->bit_input[i / 8] |= (1 << (i % 8));
4807 			break;
4808 
4809 		case UDESCSUB_AC_OUTPUT:
4810 			info->bit_output[i / 8] |= (1 << (i % 8));
4811 			uaudio20_mixer_find_inputs_sub(
4812 			    root, &iot->u.ot_v2->bSourceId, 1, info);
4813 			info->bit_output[i / 8] &= ~(1 << (i % 8));
4814 			break;
4815 
4816 		case UDESCSUB_AC_MIXER:
4817 			uaudio_mixer_merge_outputs(&iot->usr, info);
4818 			uaudio20_mixer_find_inputs_sub(
4819 			    root, iot->u.mu_v2->baSourceId,
4820 			    iot->u.mu_v2->bNrInPins, info);
4821 			break;
4822 
4823 		case UDESCSUB_AC_SELECTOR:
4824 			uaudio_mixer_merge_outputs(&iot->usr, info);
4825 			uaudio20_mixer_find_inputs_sub(
4826 			    root, iot->u.su_v2->baSourceId,
4827 			    iot->u.su_v2->bNrInPins, info);
4828 			break;
4829 
4830 		case UDESCSUB_AC_SAMPLE_RT:
4831 			uaudio_mixer_merge_outputs(&iot->usr, info);
4832 			uaudio20_mixer_find_inputs_sub(
4833 			    root, &iot->u.ru_v2->bSourceId,
4834 			    1, info);
4835 			break;
4836 
4837 		case UDESCSUB_AC_EFFECT:
4838 			uaudio_mixer_merge_outputs(&iot->usr, info);
4839 			uaudio20_mixer_find_inputs_sub(
4840 			    root, &iot->u.ef_v2->bSourceId,
4841 			    1, info);
4842 			break;
4843 
4844 		case UDESCSUB_AC_FEATURE:
4845 			uaudio_mixer_merge_outputs(&iot->usr, info);
4846 			uaudio20_mixer_find_inputs_sub(
4847 			    root, &iot->u.fu_v2->bSourceId, 1, info);
4848 			break;
4849 
4850 		case UDESCSUB_AC_PROCESSING_V2:
4851 			uaudio_mixer_merge_outputs(&iot->usr, info);
4852 			uaudio20_mixer_find_inputs_sub(
4853 			    root, iot->u.pu_v2->baSourceId,
4854 			    iot->u.pu_v2->bNrInPins, info);
4855 			break;
4856 
4857 		case UDESCSUB_AC_EXTENSION_V2:
4858 			uaudio_mixer_merge_outputs(&iot->usr, info);
4859 			uaudio20_mixer_find_inputs_sub(
4860 			    root, iot->u.eu_v2->baSourceId,
4861 			    iot->u.eu_v2->bNrInPins, info);
4862 			break;
4863 		default:
4864 			break;
4865 		}
4866 	}
4867 }
4868 
4869 static void
uaudio20_mixer_find_clocks_sub(struct uaudio_terminal_node * root,const uint8_t * p_id,uint8_t n_id,struct uaudio_search_result * info)4870 uaudio20_mixer_find_clocks_sub(struct uaudio_terminal_node *root,
4871     const uint8_t *p_id, uint8_t n_id,
4872     struct uaudio_search_result *info)
4873 {
4874 	struct uaudio_terminal_node *iot;
4875 	uint8_t n;
4876 	uint8_t i;
4877 	uint8_t is_last;
4878 	uint8_t id;
4879 
4880 top:
4881 	for (n = 0; n < n_id; n++) {
4882 		i = p_id[n];
4883 
4884 		if (info->recurse_level == UAUDIO_RECURSE_LIMIT) {
4885 			DPRINTF("avoided going into a circle at id=%d!\n", i);
4886 			return;
4887 		}
4888 
4889 		info->recurse_level++;
4890 
4891 		iot = (root + i);
4892 
4893 		if (iot->u.desc == NULL)
4894 			continue;
4895 
4896 		is_last = ((n + 1) == n_id);
4897 
4898 		switch (iot->u.desc->bDescriptorSubtype) {
4899 		case UDESCSUB_AC_INPUT:
4900 			info->is_input = 1;
4901 			if (is_last) {
4902 				p_id = &iot->u.it_v2->bCSourceId;
4903 				n_id = 1;
4904 				goto top;
4905 			}
4906 			uaudio20_mixer_find_clocks_sub(root,
4907 			    &iot->u.it_v2->bCSourceId, 1, info);
4908 			break;
4909 
4910 		case UDESCSUB_AC_OUTPUT:
4911 			info->is_input = 0;
4912 			if (is_last) {
4913 				p_id = &iot->u.ot_v2->bCSourceId;
4914 				n_id = 1;
4915 				goto top;
4916 			}
4917 			uaudio20_mixer_find_clocks_sub(root,
4918 			    &iot->u.ot_v2->bCSourceId, 1, info);
4919 			break;
4920 
4921 		case UDESCSUB_AC_CLOCK_SEL:
4922 			if (is_last) {
4923 				p_id = iot->u.csel_v2->baCSourceId;
4924 				n_id = iot->u.csel_v2->bNrInPins;
4925 				goto top;
4926 			}
4927 			uaudio20_mixer_find_clocks_sub(root,
4928 			    iot->u.csel_v2->baCSourceId,
4929 			    iot->u.csel_v2->bNrInPins, info);
4930 			break;
4931 
4932 		case UDESCSUB_AC_CLOCK_MUL:
4933 			if (is_last) {
4934 				p_id = &iot->u.cmul_v2->bCSourceId;
4935 				n_id = 1;
4936 				goto top;
4937 			}
4938 			uaudio20_mixer_find_clocks_sub(root,
4939 			    &iot->u.cmul_v2->bCSourceId,
4940 			    1, info);
4941 			break;
4942 
4943 		case UDESCSUB_AC_CLOCK_SRC:
4944 
4945 			id = iot->u.csrc_v2->bClockId;
4946 
4947 			switch (info->is_input) {
4948 			case 0:
4949 				info->bit_output[id / 8] |= (1 << (id % 8));
4950 				break;
4951 			case 1:
4952 				info->bit_input[id / 8] |= (1 << (id % 8));
4953 				break;
4954 			default:
4955 				break;
4956 			}
4957 			break;
4958 
4959 		default:
4960 			break;
4961 		}
4962 	}
4963 }
4964 
4965 static void
uaudio_mixer_fill_info(struct uaudio_softc * sc,struct usb_device * udev,void * desc)4966 uaudio_mixer_fill_info(struct uaudio_softc *sc,
4967     struct usb_device *udev, void *desc)
4968 {
4969 	const struct usb_audio_control_descriptor *acdp;
4970 	struct usb_config_descriptor *cd = usbd_get_config_descriptor(udev);
4971 	const struct usb_descriptor *dp;
4972 	const struct usb_audio_unit *au;
4973 	struct uaudio_terminal_node *iot = NULL;
4974 	uint16_t wTotalLen;
4975 	uint8_t ID_max = 0;		/* inclusive */
4976 	uint8_t i;
4977 
4978 	desc = usb_desc_foreach(cd, desc);
4979 
4980 	if (desc == NULL) {
4981 		DPRINTF("no Audio Control header\n");
4982 		goto done;
4983 	}
4984 	acdp = desc;
4985 
4986 	if ((acdp->bLength < sizeof(*acdp)) ||
4987 	    (acdp->bDescriptorType != UDESC_CS_INTERFACE) ||
4988 	    (acdp->bDescriptorSubtype != UDESCSUB_AC_HEADER)) {
4989 		DPRINTF("invalid Audio Control header\n");
4990 		goto done;
4991 	}
4992 	/* "wTotalLen" is allowed to be corrupt */
4993 	wTotalLen = UGETW(acdp->wTotalLength) - acdp->bLength;
4994 
4995 	/* get USB audio revision */
4996 	sc->sc_audio_rev = UGETW(acdp->bcdADC);
4997 
4998 	DPRINTFN(3, "found AC header, vers=%03x, len=%d\n",
4999 	    sc->sc_audio_rev, wTotalLen);
5000 
5001 	iot = malloc(sizeof(struct uaudio_terminal_node) * 256, M_TEMP,
5002 	    M_WAITOK | M_ZERO);
5003 
5004 	while ((desc = usb_desc_foreach(cd, desc))) {
5005 		dp = desc;
5006 
5007 		if (dp->bLength > wTotalLen) {
5008 			break;
5009 		} else {
5010 			wTotalLen -= dp->bLength;
5011 		}
5012 
5013 		if (sc->sc_audio_rev >= UAUDIO_VERSION_30)
5014 			au = NULL;
5015 		else if (sc->sc_audio_rev >= UAUDIO_VERSION_20)
5016 			au = uaudio20_mixer_verify_desc(dp, 0);
5017 		else
5018 			au = uaudio_mixer_verify_desc(dp, 0);
5019 
5020 		if (au) {
5021 			iot[au->bUnitId].u.desc = (const void *)au;
5022 			if (au->bUnitId > ID_max)
5023 				ID_max = au->bUnitId;
5024 		}
5025 	}
5026 
5027 	DPRINTF("Maximum ID=%d\n", ID_max);
5028 
5029 	/*
5030 	 * determine sourcing inputs for
5031 	 * all nodes in the tree:
5032 	 */
5033 	i = ID_max;
5034 	do {
5035 		if (sc->sc_audio_rev >= UAUDIO_VERSION_30) {
5036 			/* FALLTHROUGH */
5037 		} else if (sc->sc_audio_rev >= UAUDIO_VERSION_20) {
5038 			uaudio20_mixer_find_inputs_sub(iot,
5039 			    &i, 1, &((iot + i)->usr));
5040 
5041 			sc->sc_mixer_clocks.is_input = 255;
5042 			sc->sc_mixer_clocks.recurse_level = 0;
5043 
5044 			uaudio20_mixer_find_clocks_sub(iot,
5045 			    &i, 1, &sc->sc_mixer_clocks);
5046 		} else {
5047 			uaudio_mixer_find_inputs_sub(iot,
5048 			    &i, 1, &((iot + i)->usr));
5049 		}
5050 	} while (i--);
5051 
5052 	/* set "id_max" and "root" */
5053 
5054 	i = ID_max;
5055 	do {
5056 		(iot + i)->usr.id_max = ID_max;
5057 		(iot + i)->root = iot;
5058 	} while (i--);
5059 
5060 	/*
5061 	 * Scan the config to create a linked list of "mixer" nodes:
5062 	 */
5063 
5064 	i = ID_max;
5065 	do {
5066 		dp = iot[i].u.desc;
5067 
5068 		if (dp == NULL)
5069 			continue;
5070 
5071 		DPRINTFN(11, "id=%d subtype=%d\n",
5072 		    i, dp->bDescriptorSubtype);
5073 
5074 		if (sc->sc_audio_rev >= UAUDIO_VERSION_30) {
5075 			continue;
5076 		} else if (sc->sc_audio_rev >= UAUDIO_VERSION_20) {
5077 			switch (dp->bDescriptorSubtype) {
5078 			case UDESCSUB_AC_HEADER:
5079 				DPRINTF("unexpected AC header\n");
5080 				break;
5081 
5082 			case UDESCSUB_AC_INPUT:
5083 			case UDESCSUB_AC_OUTPUT:
5084 			case UDESCSUB_AC_PROCESSING_V2:
5085 			case UDESCSUB_AC_EXTENSION_V2:
5086 			case UDESCSUB_AC_EFFECT:
5087 			case UDESCSUB_AC_CLOCK_SRC:
5088 			case UDESCSUB_AC_CLOCK_SEL:
5089 			case UDESCSUB_AC_CLOCK_MUL:
5090 			case UDESCSUB_AC_SAMPLE_RT:
5091 				break;
5092 
5093 			case UDESCSUB_AC_MIXER:
5094 				uaudio20_mixer_add_mixer(sc, iot, i);
5095 				break;
5096 
5097 			case UDESCSUB_AC_SELECTOR:
5098 				uaudio20_mixer_add_selector(sc, iot, i);
5099 				break;
5100 
5101 			case UDESCSUB_AC_FEATURE:
5102 				uaudio20_mixer_add_feature(sc, iot, i);
5103 				break;
5104 
5105 			default:
5106 				DPRINTF("bad AC desc subtype=0x%02x\n",
5107 				    dp->bDescriptorSubtype);
5108 				break;
5109 			}
5110 			continue;
5111 		}
5112 
5113 		switch (dp->bDescriptorSubtype) {
5114 		case UDESCSUB_AC_HEADER:
5115 			DPRINTF("unexpected AC header\n");
5116 			break;
5117 
5118 		case UDESCSUB_AC_INPUT:
5119 		case UDESCSUB_AC_OUTPUT:
5120 			break;
5121 
5122 		case UDESCSUB_AC_MIXER:
5123 			uaudio_mixer_add_mixer(sc, iot, i);
5124 			break;
5125 
5126 		case UDESCSUB_AC_SELECTOR:
5127 			uaudio_mixer_add_selector(sc, iot, i);
5128 			break;
5129 
5130 		case UDESCSUB_AC_FEATURE:
5131 			uaudio_mixer_add_feature(sc, iot, i);
5132 			break;
5133 
5134 		case UDESCSUB_AC_PROCESSING:
5135 			uaudio_mixer_add_processing(sc, iot, i);
5136 			break;
5137 
5138 		case UDESCSUB_AC_EXTENSION:
5139 			uaudio_mixer_add_extension(sc, iot, i);
5140 			break;
5141 
5142 		default:
5143 			DPRINTF("bad AC desc subtype=0x%02x\n",
5144 			    dp->bDescriptorSubtype);
5145 			break;
5146 		}
5147 
5148 	} while (i--);
5149 
5150 done:
5151 	free(iot, M_TEMP);
5152 }
5153 
5154 static int
uaudio_mixer_get(struct usb_device * udev,uint16_t audio_rev,uint8_t what,struct uaudio_mixer_node * mc)5155 uaudio_mixer_get(struct usb_device *udev, uint16_t audio_rev,
5156     uint8_t what, struct uaudio_mixer_node *mc)
5157 {
5158 	struct usb_device_request req;
5159 	int val;
5160 	uint8_t data[2 + (2 * 3)];
5161 	usb_error_t err;
5162 
5163 	if (mc->wValue[0] == -1)
5164 		return (0);
5165 
5166 	if (audio_rev >= UAUDIO_VERSION_30)
5167 		return (0);
5168 	else if (audio_rev >= UAUDIO_VERSION_20) {
5169 		if (what == GET_CUR) {
5170 			req.bRequest = UA20_CS_CUR;
5171 			USETW(req.wLength, 2);
5172 		} else {
5173 			req.bRequest = UA20_CS_RANGE;
5174 			USETW(req.wLength, 8);
5175 		}
5176 	} else {
5177 		uint16_t len = MIX_SIZE(mc->type);
5178 
5179 		req.bRequest = what;
5180 		USETW(req.wLength, len);
5181 	}
5182 
5183 	req.bmRequestType = UT_READ_CLASS_INTERFACE;
5184 	USETW(req.wValue, mc->wValue[0]);
5185 	USETW(req.wIndex, mc->wIndex);
5186 
5187 	memset(data, 0, sizeof(data));
5188 
5189 	err = usbd_do_request(udev, NULL, &req, data);
5190 	if (err) {
5191 		DPRINTF("err=%s\n", usbd_errstr(err));
5192 		return (0);
5193 	}
5194 
5195 	if (audio_rev >= UAUDIO_VERSION_30) {
5196 		val = 0;
5197 	} else if (audio_rev >= UAUDIO_VERSION_20) {
5198 		switch (what) {
5199 		case GET_CUR:
5200 			val = (data[0] | (data[1] << 8));
5201 			break;
5202 		case GET_MIN:
5203 			val = (data[2] | (data[3] << 8));
5204 			break;
5205 		case GET_MAX:
5206 			val = (data[4] | (data[5] << 8));
5207 			break;
5208 		case GET_RES:
5209 			val = (data[6] | (data[7] << 8));
5210 			break;
5211 		default:
5212 			val = 0;
5213 			break;
5214 		}
5215 	} else {
5216 		val = (data[0] | (data[1] << 8));
5217 	}
5218 
5219 	if (what == GET_CUR || what == GET_MIN || what == GET_MAX)
5220 		val = uaudio_mixer_signext(mc->type, val);
5221 
5222 	DPRINTFN(3, "val=%d\n", val);
5223 
5224 	return (val);
5225 }
5226 
5227 static void
uaudio_mixer_write_cfg_callback(struct usb_xfer * xfer,usb_error_t error)5228 uaudio_mixer_write_cfg_callback(struct usb_xfer *xfer, usb_error_t error)
5229 {
5230 	struct usb_device_request req;
5231 	struct uaudio_softc *sc = usbd_xfer_softc(xfer);
5232 	struct uaudio_mixer_node *mc = sc->sc_mixer_curr;
5233 	struct usb_page_cache *pc;
5234 	uint16_t len;
5235 	uint8_t repeat = 1;
5236 	uint8_t update;
5237 	uint8_t chan;
5238 	uint8_t buf[2];
5239 
5240 	DPRINTF("\n");
5241 
5242 	switch (USB_GET_STATE(xfer)) {
5243 	case USB_ST_TRANSFERRED:
5244 tr_transferred:
5245 	case USB_ST_SETUP:
5246 tr_setup:
5247 
5248 		if (mc == NULL) {
5249 			mc = sc->sc_mixer_root;
5250 			sc->sc_mixer_curr = mc;
5251 			sc->sc_mixer_chan = 0;
5252 			repeat = 0;
5253 		}
5254 		while (mc) {
5255 			while (sc->sc_mixer_chan < mc->nchan) {
5256 				chan = sc->sc_mixer_chan;
5257 
5258 				sc->sc_mixer_chan++;
5259 
5260 				update = ((mc->update[chan / 8] & (1 << (chan % 8))) &&
5261 				    (mc->wValue[chan] != -1));
5262 
5263 				mc->update[chan / 8] &= ~(1 << (chan % 8));
5264 
5265 				if (update) {
5266 					req.bmRequestType = UT_WRITE_CLASS_INTERFACE;
5267 					USETW(req.wValue, mc->wValue[chan]);
5268 					USETW(req.wIndex, mc->wIndex);
5269 
5270 					if (sc->sc_audio_rev >= UAUDIO_VERSION_30) {
5271 						return;
5272 					} else if (sc->sc_audio_rev >= UAUDIO_VERSION_20) {
5273 						len = 2;
5274 						req.bRequest = UA20_CS_CUR;
5275 						USETW(req.wLength, len);
5276 					} else {
5277 						len = MIX_SIZE(mc->type);
5278 						req.bRequest = SET_CUR;
5279 						USETW(req.wLength, len);
5280 					}
5281 
5282 					buf[0] = (mc->wData[chan] & 0xFF);
5283 					buf[1] = (mc->wData[chan] >> 8) & 0xFF;
5284 
5285 					pc = usbd_xfer_get_frame(xfer, 0);
5286 					usbd_copy_in(pc, 0, &req, sizeof(req));
5287 					pc = usbd_xfer_get_frame(xfer, 1);
5288 					usbd_copy_in(pc, 0, buf, len);
5289 
5290 					usbd_xfer_set_frame_len(xfer, 0, sizeof(req));
5291 					usbd_xfer_set_frame_len(xfer, 1, len);
5292 					usbd_xfer_set_frames(xfer, len ? 2 : 1);
5293 					usbd_transfer_submit(xfer);
5294 					return;
5295 				}
5296 			}
5297 
5298 			mc = mc->next;
5299 			sc->sc_mixer_curr = mc;
5300 			sc->sc_mixer_chan = 0;
5301 		}
5302 
5303 		if (repeat) {
5304 			goto tr_setup;
5305 		}
5306 		break;
5307 
5308 	default:			/* Error */
5309 		DPRINTF("error=%s\n", usbd_errstr(error));
5310 		if (error == USB_ERR_CANCELLED) {
5311 			/* do nothing - we are detaching */
5312 			break;
5313 		}
5314 		goto tr_transferred;
5315 	}
5316 }
5317 
5318 static usb_error_t
uaudio_set_speed(struct usb_device * udev,uint8_t endpt,uint32_t speed)5319 uaudio_set_speed(struct usb_device *udev, uint8_t endpt, uint32_t speed)
5320 {
5321 	struct usb_device_request req;
5322 	uint8_t data[3];
5323 
5324 	DPRINTFN(6, "endpt=%d speed=%u\n", endpt, speed);
5325 
5326 	req.bmRequestType = UT_WRITE_CLASS_ENDPOINT;
5327 	req.bRequest = SET_CUR;
5328 	USETW2(req.wValue, SAMPLING_FREQ_CONTROL, 0);
5329 	USETW(req.wIndex, endpt);
5330 	USETW(req.wLength, 3);
5331 	data[0] = speed;
5332 	data[1] = speed >> 8;
5333 	data[2] = speed >> 16;
5334 
5335 	return (usbd_do_request(udev, NULL, &req, data));
5336 }
5337 
5338 static usb_error_t
uaudio20_set_speed(struct usb_device * udev,uint8_t iface_no,uint8_t clockid,uint32_t speed)5339 uaudio20_set_speed(struct usb_device *udev, uint8_t iface_no,
5340     uint8_t clockid, uint32_t speed)
5341 {
5342 	struct usb_device_request req;
5343 	uint8_t data[4];
5344 
5345 	DPRINTFN(6, "ifaceno=%d clockid=%d speed=%u\n",
5346 	    iface_no, clockid, speed);
5347 
5348 	req.bmRequestType = UT_WRITE_CLASS_INTERFACE;
5349 	req.bRequest = UA20_CS_CUR;
5350 	USETW2(req.wValue, UA20_CS_SAM_FREQ_CONTROL, 0);
5351 	USETW2(req.wIndex, clockid, iface_no);
5352 	USETW(req.wLength, 4);
5353 	data[0] = speed;
5354 	data[1] = speed >> 8;
5355 	data[2] = speed >> 16;
5356 	data[3] = speed >> 24;
5357 
5358 	return (usbd_do_request(udev, NULL, &req, data));
5359 }
5360 
5361 static int
uaudio_mixer_signext(uint8_t type,int val)5362 uaudio_mixer_signext(uint8_t type, int val)
5363 {
5364 	if (!MIX_UNSIGNED(type)) {
5365 		if (MIX_SIZE(type) == 2) {
5366 			val = (int16_t)val;
5367 		} else {
5368 			val = (int8_t)val;
5369 		}
5370 	}
5371 	return (val);
5372 }
5373 
5374 static int
uaudio_mixer_bsd2value(struct uaudio_mixer_node * mc,int val)5375 uaudio_mixer_bsd2value(struct uaudio_mixer_node *mc, int val)
5376 {
5377 	if (mc->type == MIX_ON_OFF) {
5378 		val = (val != 0);
5379 	} else if (mc->type != MIX_SELECTOR) {
5380 		/* compute actual volume */
5381 		val = (val * mc->mul) / 100;
5382 
5383 		/* add lower offset */
5384 		val = val + mc->minval;
5385 	}
5386 	/* make sure we don't write a value out of range */
5387 	if (val > mc->maxval)
5388 		val = mc->maxval;
5389 	else if (val < mc->minval)
5390 		val = mc->minval;
5391 
5392 	DPRINTFN(6, "type=0x%03x val=%d min=%d max=%d val=%d\n",
5393 	    mc->type, val, mc->minval, mc->maxval, val);
5394 	return (val);
5395 }
5396 
5397 static void
uaudio_mixer_ctl_set(struct uaudio_softc * sc,struct uaudio_mixer_node * mc,uint8_t chan,int val)5398 uaudio_mixer_ctl_set(struct uaudio_softc *sc, struct uaudio_mixer_node *mc,
5399     uint8_t chan, int val)
5400 {
5401 	val = uaudio_mixer_bsd2value(mc, val);
5402 
5403 	mc->update[chan / 8] |= (1 << (chan % 8));
5404 	mc->wData[chan] = val;
5405 
5406 	/* start the transfer, if not already started */
5407 
5408 	usbd_transfer_start(sc->sc_mixer_xfer[0]);
5409 }
5410 
5411 static void
uaudio_mixer_init(struct uaudio_softc * sc,unsigned index)5412 uaudio_mixer_init(struct uaudio_softc *sc, unsigned index)
5413 {
5414 	struct uaudio_mixer_node *mc;
5415 	int32_t i;
5416 
5417 	if (index != 0)
5418 		return;
5419 	for (mc = sc->sc_mixer_root; mc; mc = mc->next) {
5420 		if (mc->ctl != SOUND_MIXER_NRDEVICES) {
5421 			/*
5422 			 * Set device mask bits. See
5423 			 * /usr/include/machine/soundcard.h
5424 			 */
5425 			sc->sc_child[index].mix_info |= 1U << mc->ctl;
5426 		}
5427 		if ((mc->ctl == SOUND_MIXER_NRDEVICES) &&
5428 		    (mc->type == MIX_SELECTOR)) {
5429 			for (i = mc->minval; (i > 0) && (i <= mc->maxval); i++) {
5430 				if (mc->slctrtype[i - 1] == SOUND_MIXER_NRDEVICES)
5431 					continue;
5432 				sc->sc_child[index].recsrc_info |= 1U << mc->slctrtype[i - 1];
5433 			}
5434 		}
5435 	}
5436 }
5437 
5438 int
uaudio_mixer_init_sub(struct uaudio_softc * sc,struct snd_mixer * m)5439 uaudio_mixer_init_sub(struct uaudio_softc *sc, struct snd_mixer *m)
5440 {
5441 	unsigned i = uaudio_get_child_index_by_dev(sc, mix_get_dev(m));
5442 
5443 	DPRINTF("child=%u\n", i);
5444 
5445 	sc->sc_child[i].mixer_lock = mixer_get_lock(m);
5446 	sc->sc_child[i].mixer_dev = m;
5447 
5448 	if (i == 0 &&
5449 	    usbd_transfer_setup(sc->sc_udev, &sc->sc_mixer_iface_index,
5450 	    sc->sc_mixer_xfer, uaudio_mixer_config, 1, sc,
5451 	    sc->sc_child[i].mixer_lock)) {
5452 		DPRINTFN(0, "could not allocate USB transfer for mixer!\n");
5453 		return (ENOMEM);
5454 	}
5455 
5456 	if (sc->sc_play_chan[i].num_alt > 0 &&
5457 	    (sc->sc_child[i].mix_info & SOUND_MASK_VOLUME) == 0) {
5458 		mix_setparentchild(m, SOUND_MIXER_VOLUME, SOUND_MASK_PCM);
5459 		mix_setrealdev(m, SOUND_MIXER_VOLUME, SOUND_MIXER_NONE);
5460 	}
5461 	mix_setdevs(m, sc->sc_child[i].mix_info);
5462 	mix_setrecdevs(m, sc->sc_child[i].recsrc_info);
5463 	return (0);
5464 }
5465 
5466 int
uaudio_mixer_uninit_sub(struct uaudio_softc * sc,struct snd_mixer * m)5467 uaudio_mixer_uninit_sub(struct uaudio_softc *sc, struct snd_mixer *m)
5468 {
5469   	unsigned index = uaudio_get_child_index_by_dev(sc, mix_get_dev(m));
5470 
5471 	DPRINTF("child=%u\n", index);
5472 
5473 	if (index == 0)
5474 		usbd_transfer_unsetup(sc->sc_mixer_xfer, 1);
5475 
5476 	sc->sc_child[index].mixer_lock = NULL;
5477 
5478 	return (0);
5479 }
5480 
5481 void
uaudio_mixer_set(struct uaudio_softc * sc,struct snd_mixer * m,unsigned type,unsigned left,unsigned right)5482 uaudio_mixer_set(struct uaudio_softc *sc, struct snd_mixer *m,
5483     unsigned type, unsigned left, unsigned right)
5484 {
5485     	unsigned index = uaudio_get_child_index_by_dev(sc, mix_get_dev(m));
5486 	struct uaudio_mixer_node *mc;
5487 	int chan;
5488 
5489 	if (index != 0)
5490 		return;
5491 	for (mc = sc->sc_mixer_root; mc != NULL; mc = mc->next) {
5492 		if (mc->ctl == type) {
5493 			for (chan = 0; chan < mc->nchan; chan++) {
5494 				uaudio_mixer_ctl_set(sc, mc, chan,
5495 				    chan == 0 ? left : right);
5496 			}
5497 		}
5498 	}
5499 }
5500 
5501 uint32_t
uaudio_mixer_setrecsrc(struct uaudio_softc * sc,struct snd_mixer * m,uint32_t src)5502 uaudio_mixer_setrecsrc(struct uaudio_softc *sc, struct snd_mixer *m, uint32_t src)
5503 {
5504       	unsigned index = uaudio_get_child_index_by_dev(sc, mix_get_dev(m));
5505 	struct uaudio_mixer_node *mc;
5506 	uint32_t mask;
5507 	uint32_t temp;
5508 	int32_t i;
5509 
5510 	if (index != 0)
5511 		return (0);
5512 	for (mc = sc->sc_mixer_root; mc; mc = mc->next) {
5513 		if ((mc->ctl == SOUND_MIXER_NRDEVICES) &&
5514 		    (mc->type == MIX_SELECTOR)) {
5515 			/* compute selector mask */
5516 
5517 			mask = 0;
5518 			for (i = mc->minval; (i > 0) && (i <= mc->maxval); i++)
5519 				mask |= 1U << mc->slctrtype[i - 1];
5520 
5521 			temp = mask & src;
5522 			if (temp == 0)
5523 				continue;
5524 
5525 			/* find the first set bit */
5526 			temp = (-temp) & temp;
5527 
5528 			/* update "src" */
5529 			src &= ~mask;
5530 			src |= temp;
5531 
5532 			for (i = mc->minval; (i > 0) && (i <= mc->maxval); i++) {
5533 				if (temp != (1U << mc->slctrtype[i - 1]))
5534 					continue;
5535 				uaudio_mixer_ctl_set(sc, mc, 0, i);
5536 				break;
5537 			}
5538 		}
5539 	}
5540 	return (src);
5541 }
5542 
5543 /*========================================================================*
5544  * MIDI support routines
5545  *========================================================================*/
5546 
5547 static void
umidi_bulk_read_callback(struct usb_xfer * xfer,usb_error_t error)5548 umidi_bulk_read_callback(struct usb_xfer *xfer, usb_error_t error)
5549 {
5550 	struct umidi_chan *chan = usbd_xfer_softc(xfer);
5551 	struct umidi_sub_chan *sub;
5552 	struct usb_page_cache *pc;
5553 	uint8_t buf[4];
5554 	uint8_t cmd_len;
5555 	uint8_t cn;
5556 	uint16_t pos;
5557 	int actlen;
5558 
5559 	usbd_xfer_status(xfer, &actlen, NULL, NULL, NULL);
5560 
5561 	switch (USB_GET_STATE(xfer)) {
5562 	case USB_ST_TRANSFERRED:
5563 
5564 		DPRINTF("actlen=%d bytes\n", actlen);
5565 
5566 		pos = 0;
5567 		pc = usbd_xfer_get_frame(xfer, 0);
5568 
5569 		while (actlen >= 4) {
5570 			/* copy out the MIDI data */
5571 			usbd_copy_out(pc, pos, buf, 4);
5572 			/* command length */
5573 			cmd_len = umidi_cmd_to_len[buf[0] & 0xF];
5574 			/* cable number */
5575 			cn = buf[0] >> 4;
5576 			/*
5577 			 * Lookup sub-channel. The index is range
5578 			 * checked below.
5579 			 */
5580 			sub = &chan->sub[cn];
5581 
5582 			if ((cmd_len != 0) && (cn < chan->max_emb_jack) &&
5583 			    (sub->read_open != 0)) {
5584 				/* Send data to the application */
5585 				usb_fifo_put_data_linear(
5586 				    sub->fifo.fp[USB_FIFO_RX],
5587 				    buf + 1, cmd_len, 1);
5588 			}
5589 			actlen -= 4;
5590 			pos += 4;
5591 		}
5592 
5593 	case USB_ST_SETUP:
5594 		DPRINTF("start\n");
5595 tr_setup:
5596 		usbd_xfer_set_frame_len(xfer, 0, usbd_xfer_max_len(xfer));
5597 		usbd_transfer_submit(xfer);
5598 		break;
5599 
5600 	default:
5601 		DPRINTF("error=%s\n", usbd_errstr(error));
5602 
5603 		if (error != USB_ERR_CANCELLED) {
5604 			/* try to clear stall first */
5605 			usbd_xfer_set_stall(xfer);
5606 			goto tr_setup;
5607 		}
5608 		break;
5609 	}
5610 }
5611 
5612 /*
5613  * The following statemachine, that converts MIDI commands to
5614  * USB MIDI packets, derives from Linux's usbmidi.c, which
5615  * was written by "Clemens Ladisch":
5616  *
5617  * Returns:
5618  *    0: No command
5619  * Else: Command is complete
5620  */
5621 static uint8_t
umidi_convert_to_usb(struct umidi_sub_chan * sub,uint8_t cn,uint8_t b)5622 umidi_convert_to_usb(struct umidi_sub_chan *sub, uint8_t cn, uint8_t b)
5623 {
5624 	uint8_t p0 = (cn << 4);
5625 
5626 	if (b >= 0xf8) {
5627 		sub->temp_0[0] = p0 | 0x0f;
5628 		sub->temp_0[1] = b;
5629 		sub->temp_0[2] = 0;
5630 		sub->temp_0[3] = 0;
5631 		sub->temp_cmd = sub->temp_0;
5632 		return (1);
5633 
5634 	} else if (b >= 0xf0) {
5635 		switch (b) {
5636 		case 0xf0:		/* system exclusive begin */
5637 			sub->temp_1[1] = b;
5638 			sub->state = UMIDI_ST_SYSEX_1;
5639 			break;
5640 		case 0xf1:		/* MIDI time code */
5641 		case 0xf3:		/* song select */
5642 			sub->temp_1[1] = b;
5643 			sub->state = UMIDI_ST_1PARAM;
5644 			break;
5645 		case 0xf2:		/* song position pointer */
5646 			sub->temp_1[1] = b;
5647 			sub->state = UMIDI_ST_2PARAM_1;
5648 			break;
5649 		case 0xf4:		/* unknown */
5650 		case 0xf5:		/* unknown */
5651 			sub->state = UMIDI_ST_UNKNOWN;
5652 			break;
5653 		case 0xf6:		/* tune request */
5654 			sub->temp_1[0] = p0 | 0x05;
5655 			sub->temp_1[1] = 0xf6;
5656 			sub->temp_1[2] = 0;
5657 			sub->temp_1[3] = 0;
5658 			sub->temp_cmd = sub->temp_1;
5659 			sub->state = UMIDI_ST_UNKNOWN;
5660 			return (1);
5661 
5662 		case 0xf7:		/* system exclusive end */
5663 			switch (sub->state) {
5664 			case UMIDI_ST_SYSEX_0:
5665 				sub->temp_1[0] = p0 | 0x05;
5666 				sub->temp_1[1] = 0xf7;
5667 				sub->temp_1[2] = 0;
5668 				sub->temp_1[3] = 0;
5669 				sub->temp_cmd = sub->temp_1;
5670 				sub->state = UMIDI_ST_UNKNOWN;
5671 				return (1);
5672 			case UMIDI_ST_SYSEX_1:
5673 				sub->temp_1[0] = p0 | 0x06;
5674 				sub->temp_1[2] = 0xf7;
5675 				sub->temp_1[3] = 0;
5676 				sub->temp_cmd = sub->temp_1;
5677 				sub->state = UMIDI_ST_UNKNOWN;
5678 				return (1);
5679 			case UMIDI_ST_SYSEX_2:
5680 				sub->temp_1[0] = p0 | 0x07;
5681 				sub->temp_1[3] = 0xf7;
5682 				sub->temp_cmd = sub->temp_1;
5683 				sub->state = UMIDI_ST_UNKNOWN;
5684 				return (1);
5685 			}
5686 			sub->state = UMIDI_ST_UNKNOWN;
5687 			break;
5688 		}
5689 	} else if (b >= 0x80) {
5690 		sub->temp_1[1] = b;
5691 		if ((b >= 0xc0) && (b <= 0xdf)) {
5692 			sub->state = UMIDI_ST_1PARAM;
5693 		} else {
5694 			sub->state = UMIDI_ST_2PARAM_1;
5695 		}
5696 	} else {			/* b < 0x80 */
5697 		switch (sub->state) {
5698 		case UMIDI_ST_1PARAM:
5699 			if (sub->temp_1[1] < 0xf0) {
5700 				p0 |= sub->temp_1[1] >> 4;
5701 			} else {
5702 				p0 |= 0x02;
5703 				sub->state = UMIDI_ST_UNKNOWN;
5704 			}
5705 			sub->temp_1[0] = p0;
5706 			sub->temp_1[2] = b;
5707 			sub->temp_1[3] = 0;
5708 			sub->temp_cmd = sub->temp_1;
5709 			return (1);
5710 		case UMIDI_ST_2PARAM_1:
5711 			sub->temp_1[2] = b;
5712 			sub->state = UMIDI_ST_2PARAM_2;
5713 			break;
5714 		case UMIDI_ST_2PARAM_2:
5715 			if (sub->temp_1[1] < 0xf0) {
5716 				p0 |= sub->temp_1[1] >> 4;
5717 				sub->state = UMIDI_ST_2PARAM_1;
5718 			} else {
5719 				p0 |= 0x03;
5720 				sub->state = UMIDI_ST_UNKNOWN;
5721 			}
5722 			sub->temp_1[0] = p0;
5723 			sub->temp_1[3] = b;
5724 			sub->temp_cmd = sub->temp_1;
5725 			return (1);
5726 		case UMIDI_ST_SYSEX_0:
5727 			sub->temp_1[1] = b;
5728 			sub->state = UMIDI_ST_SYSEX_1;
5729 			break;
5730 		case UMIDI_ST_SYSEX_1:
5731 			sub->temp_1[2] = b;
5732 			sub->state = UMIDI_ST_SYSEX_2;
5733 			break;
5734 		case UMIDI_ST_SYSEX_2:
5735 			sub->temp_1[0] = p0 | 0x04;
5736 			sub->temp_1[3] = b;
5737 			sub->temp_cmd = sub->temp_1;
5738 			sub->state = UMIDI_ST_SYSEX_0;
5739 			return (1);
5740 		default:
5741 			break;
5742 		}
5743 	}
5744 	return (0);
5745 }
5746 
5747 static void
umidi_bulk_write_callback(struct usb_xfer * xfer,usb_error_t error)5748 umidi_bulk_write_callback(struct usb_xfer *xfer, usb_error_t error)
5749 {
5750 	struct umidi_chan *chan = usbd_xfer_softc(xfer);
5751 	struct umidi_sub_chan *sub;
5752 	struct usb_page_cache *pc;
5753 	uint32_t actlen;
5754 	uint16_t nframes;
5755 	uint8_t buf;
5756 	uint8_t start_cable;
5757 	uint8_t tr_any;
5758 	int len;
5759 
5760 	usbd_xfer_status(xfer, &len, NULL, NULL, NULL);
5761 
5762 	/*
5763 	 * NOTE: Some MIDI devices only accept 4 bytes of data per
5764 	 * short terminated USB transfer.
5765 	 */
5766 	switch (USB_GET_STATE(xfer)) {
5767 	case USB_ST_TRANSFERRED:
5768 		DPRINTF("actlen=%d bytes\n", len);
5769 
5770 	case USB_ST_SETUP:
5771 tr_setup:
5772 		DPRINTF("start\n");
5773 
5774 		nframes = 0;	/* reset */
5775 		start_cable = chan->curr_cable;
5776 		tr_any = 0;
5777 		pc = usbd_xfer_get_frame(xfer, 0);
5778 
5779 		while (1) {
5780 			/* round robin de-queueing */
5781 
5782 			sub = &chan->sub[chan->curr_cable];
5783 
5784 			if (sub->write_open) {
5785 				usb_fifo_get_data_linear(sub->fifo.fp[USB_FIFO_TX],
5786 				    &buf, 1, &actlen, 0);
5787 			} else {
5788 				actlen = 0;
5789 			}
5790 
5791 			if (actlen) {
5792 				tr_any = 1;
5793 
5794 				DPRINTF("byte=0x%02x from FIFO %u\n", buf,
5795 				    (unsigned int)chan->curr_cable);
5796 
5797 				if (umidi_convert_to_usb(sub, chan->curr_cable, buf)) {
5798 					DPRINTF("sub=0x%02x 0x%02x 0x%02x 0x%02x\n",
5799 					    sub->temp_cmd[0], sub->temp_cmd[1],
5800 					    sub->temp_cmd[2], sub->temp_cmd[3]);
5801 
5802 					usbd_copy_in(pc, nframes * 4, sub->temp_cmd, 4);
5803 
5804 					nframes++;
5805 
5806 					if ((nframes >= UMIDI_TX_FRAMES) || (chan->single_command != 0))
5807 						break;
5808 				} else {
5809 					continue;
5810 				}
5811 			}
5812 
5813 			chan->curr_cable++;
5814 			if (chan->curr_cable >= chan->max_emb_jack)
5815 				chan->curr_cable = 0;
5816 
5817 			if (chan->curr_cable == start_cable) {
5818 				if (tr_any == 0)
5819 					break;
5820 				tr_any = 0;
5821 			}
5822 		}
5823 
5824 		if (nframes != 0) {
5825 			DPRINTF("Transferring %d frames\n", (int)nframes);
5826 			usbd_xfer_set_frame_len(xfer, 0, 4 * nframes);
5827 			usbd_transfer_submit(xfer);
5828 		}
5829 		break;
5830 
5831 	default:			/* Error */
5832 
5833 		DPRINTF("error=%s\n", usbd_errstr(error));
5834 
5835 		if (error != USB_ERR_CANCELLED) {
5836 			/* try to clear stall first */
5837 			usbd_xfer_set_stall(xfer);
5838 			goto tr_setup;
5839 		}
5840 		break;
5841 	}
5842 }
5843 
5844 static struct umidi_sub_chan *
umidi_sub_by_fifo(struct usb_fifo * fifo)5845 umidi_sub_by_fifo(struct usb_fifo *fifo)
5846 {
5847 	struct umidi_chan *chan = usb_fifo_softc(fifo);
5848 	struct umidi_sub_chan *sub;
5849 	uint32_t n;
5850 
5851 	for (n = 0; n < UMIDI_EMB_JACK_MAX; n++) {
5852 		sub = &chan->sub[n];
5853 		if ((sub->fifo.fp[USB_FIFO_RX] == fifo) ||
5854 		    (sub->fifo.fp[USB_FIFO_TX] == fifo)) {
5855 			return (sub);
5856 		}
5857 	}
5858 
5859 	panic("%s:%d cannot find usb_fifo!\n",
5860 	    __FILE__, __LINE__);
5861 
5862 	return (NULL);
5863 }
5864 
5865 static void
umidi_start_read(struct usb_fifo * fifo)5866 umidi_start_read(struct usb_fifo *fifo)
5867 {
5868 	struct umidi_chan *chan = usb_fifo_softc(fifo);
5869 
5870 	usbd_transfer_start(chan->xfer[UMIDI_RX_TRANSFER]);
5871 }
5872 
5873 static void
umidi_stop_read(struct usb_fifo * fifo)5874 umidi_stop_read(struct usb_fifo *fifo)
5875 {
5876 	struct umidi_chan *chan = usb_fifo_softc(fifo);
5877 	struct umidi_sub_chan *sub = umidi_sub_by_fifo(fifo);
5878 
5879 	DPRINTF("\n");
5880 
5881 	sub->read_open = 0;
5882 
5883 	if (--(chan->read_open_refcount) == 0) {
5884 		/*
5885 		 * XXX don't stop the read transfer here, hence that causes
5886 		 * problems with some MIDI adapters
5887 		 */
5888 		DPRINTF("(stopping read transfer)\n");
5889 	}
5890 }
5891 
5892 static void
umidi_start_write(struct usb_fifo * fifo)5893 umidi_start_write(struct usb_fifo *fifo)
5894 {
5895 	struct umidi_chan *chan = usb_fifo_softc(fifo);
5896 
5897 	if (chan->xfer[UMIDI_TX_TRANSFER] == NULL) {
5898 		uint8_t buf[1];
5899 		int actlen;
5900 		do {
5901 			/* dump data */
5902 			usb_fifo_get_data_linear(fifo, buf, 1, &actlen, 0);
5903 		} while (actlen > 0);
5904 	} else {
5905 		usbd_transfer_start(chan->xfer[UMIDI_TX_TRANSFER]);
5906 	}
5907 }
5908 
5909 static void
umidi_stop_write(struct usb_fifo * fifo)5910 umidi_stop_write(struct usb_fifo *fifo)
5911 {
5912 	struct umidi_chan *chan = usb_fifo_softc(fifo);
5913 	struct umidi_sub_chan *sub = umidi_sub_by_fifo(fifo);
5914 
5915 	DPRINTF("\n");
5916 
5917 	sub->write_open = 0;
5918 
5919 	if (--(chan->write_open_refcount) == 0) {
5920 		DPRINTF("(stopping write transfer)\n");
5921 		usbd_transfer_stop(chan->xfer[UMIDI_TX_TRANSFER]);
5922 	}
5923 }
5924 
5925 static int
umidi_open(struct usb_fifo * fifo,int fflags)5926 umidi_open(struct usb_fifo *fifo, int fflags)
5927 {
5928 	struct umidi_chan *chan = usb_fifo_softc(fifo);
5929 	struct umidi_sub_chan *sub = umidi_sub_by_fifo(fifo);
5930 
5931 	if (fflags & FREAD) {
5932 		if (usb_fifo_alloc_buffer(fifo, 4, (1024 / 4))) {
5933 			return (ENOMEM);
5934 		}
5935 		mtx_lock(&chan->mtx);
5936 		chan->read_open_refcount++;
5937 		sub->read_open = 1;
5938 		mtx_unlock(&chan->mtx);
5939 	}
5940 	if (fflags & FWRITE) {
5941 		if (usb_fifo_alloc_buffer(fifo, 32, (1024 / 32))) {
5942 			return (ENOMEM);
5943 		}
5944 		/* clear stall first */
5945 		mtx_lock(&chan->mtx);
5946 		chan->write_open_refcount++;
5947 		sub->write_open = 1;
5948 
5949 		/* reset */
5950 		sub->state = UMIDI_ST_UNKNOWN;
5951 		mtx_unlock(&chan->mtx);
5952 	}
5953 	return (0);			/* success */
5954 }
5955 
5956 static void
umidi_close(struct usb_fifo * fifo,int fflags)5957 umidi_close(struct usb_fifo *fifo, int fflags)
5958 {
5959 	if (fflags & FREAD) {
5960 		usb_fifo_free_buffer(fifo);
5961 	}
5962 	if (fflags & FWRITE) {
5963 		usb_fifo_free_buffer(fifo);
5964 	}
5965 }
5966 
5967 static int
umidi_ioctl(struct usb_fifo * fifo,u_long cmd,void * data,int fflags)5968 umidi_ioctl(struct usb_fifo *fifo, u_long cmd, void *data,
5969     int fflags)
5970 {
5971 	return (ENODEV);
5972 }
5973 
5974 static void
umidi_init(device_t dev)5975 umidi_init(device_t dev)
5976 {
5977 	struct uaudio_softc *sc = device_get_softc(dev);
5978 	struct umidi_chan *chan = &sc->sc_midi_chan;
5979 
5980 	mtx_init(&chan->mtx, "umidi lock", NULL, MTX_DEF | MTX_RECURSE);
5981 }
5982 
5983 static struct usb_fifo_methods umidi_fifo_methods = {
5984 	.f_start_read = &umidi_start_read,
5985 	.f_start_write = &umidi_start_write,
5986 	.f_stop_read = &umidi_stop_read,
5987 	.f_stop_write = &umidi_stop_write,
5988 	.f_open = &umidi_open,
5989 	.f_close = &umidi_close,
5990 	.f_ioctl = &umidi_ioctl,
5991 	.basename[0] = "umidi",
5992 };
5993 
5994 static int
umidi_probe(device_t dev)5995 umidi_probe(device_t dev)
5996 {
5997 	struct uaudio_softc *sc = device_get_softc(dev);
5998 	struct usb_attach_arg *uaa = device_get_ivars(dev);
5999 	struct umidi_chan *chan = &sc->sc_midi_chan;
6000 	struct umidi_sub_chan *sub;
6001 	int unit = device_get_unit(dev);
6002 	int error;
6003 	uint32_t n;
6004 
6005 	if (usb_test_quirk(uaa, UQ_SINGLE_CMD_MIDI))
6006 		chan->single_command = 1;
6007 
6008 	error = usbd_set_alt_interface_index(sc->sc_udev,
6009 	    chan->iface_index, chan->iface_alt_index);
6010 	if (error) {
6011 		DPRINTF("setting of alternate index failed: %s\n",
6012 		    usbd_errstr(error));
6013 		goto detach;
6014 	}
6015 	usbd_set_parent_iface(sc->sc_udev, chan->iface_index,
6016 	    sc->sc_mixer_iface_index);
6017 
6018 	error = usbd_transfer_setup(uaa->device, &chan->iface_index,
6019 	    chan->xfer, umidi_config, UMIDI_N_TRANSFER,
6020 	    chan, &chan->mtx);
6021 	if (error) {
6022 		DPRINTF("error=%s\n", usbd_errstr(error));
6023 		goto detach;
6024 	}
6025 	if (chan->xfer[UMIDI_TX_TRANSFER] == NULL &&
6026 	    chan->xfer[UMIDI_RX_TRANSFER] == NULL) {
6027 		DPRINTF("no BULK or INTERRUPT MIDI endpoint(s) found\n");
6028 		goto detach;
6029 	}
6030 
6031 	/*
6032 	 * Some USB MIDI device makers couldn't resist using
6033 	 * wMaxPacketSize = 4 for RX and TX BULK endpoints, although
6034 	 * that size is an unsupported value for FULL speed BULK
6035 	 * endpoints. The same applies to some HIGH speed MIDI devices
6036 	 * which are using a wMaxPacketSize different from 512 bytes.
6037 	 *
6038 	 * Refer to section 5.8.3 in USB 2.0 PDF: Cite: "All Host
6039 	 * Controllers are required to have support for 8-, 16-, 32-,
6040 	 * and 64-byte maximum packet sizes for full-speed bulk
6041 	 * endpoints and 512 bytes for high-speed bulk endpoints."
6042 	 */
6043 	if (chan->xfer[UMIDI_TX_TRANSFER] != NULL &&
6044 	    usbd_xfer_maxp_was_clamped(chan->xfer[UMIDI_TX_TRANSFER]))
6045 		chan->single_command = 1;
6046 
6047 	if (chan->single_command != 0)
6048 		device_printf(dev, "Single command MIDI quirk enabled\n");
6049 
6050 	if ((chan->max_emb_jack == 0) ||
6051 	    (chan->max_emb_jack > UMIDI_EMB_JACK_MAX)) {
6052 		chan->max_emb_jack = UMIDI_EMB_JACK_MAX;
6053 	}
6054 
6055 	for (n = 0; n < chan->max_emb_jack; n++) {
6056 		sub = &chan->sub[n];
6057 
6058 		error = usb_fifo_attach(sc->sc_udev, chan, &chan->mtx,
6059 		    &umidi_fifo_methods, &sub->fifo, unit, n,
6060 		    chan->iface_index,
6061 		    UID_ROOT, GID_OPERATOR, 0666);
6062 		if (error) {
6063 			goto detach;
6064 		}
6065 	}
6066 
6067 	mtx_lock(&chan->mtx);
6068 
6069 	/*
6070 	 * NOTE: At least one device will not work properly unless the
6071 	 * BULK IN pipe is open all the time. This might have to do
6072 	 * about that the internal queues of the device overflow if we
6073 	 * don't read them regularly.
6074 	 */
6075 	usbd_transfer_start(chan->xfer[UMIDI_RX_TRANSFER]);
6076 
6077 	mtx_unlock(&chan->mtx);
6078 
6079 	return (0);			/* success */
6080 
6081 detach:
6082 	return (ENXIO);			/* failure */
6083 }
6084 
6085 static int
umidi_detach(device_t dev)6086 umidi_detach(device_t dev)
6087 {
6088 	struct uaudio_softc *sc = device_get_softc(dev);
6089 	struct umidi_chan *chan = &sc->sc_midi_chan;
6090 	uint32_t n;
6091 
6092 	for (n = 0; n < UMIDI_EMB_JACK_MAX; n++)
6093 		usb_fifo_detach(&chan->sub[n].fifo);
6094 
6095 	mtx_lock(&chan->mtx);
6096 
6097 	usbd_transfer_stop(chan->xfer[UMIDI_RX_TRANSFER]);
6098 
6099 	mtx_unlock(&chan->mtx);
6100 
6101 	usbd_transfer_unsetup(chan->xfer, UMIDI_N_TRANSFER);
6102 
6103 	mtx_destroy(&chan->mtx);
6104 
6105 	return (0);
6106 }
6107 
6108 static void
uaudio_hid_rx_callback(struct usb_xfer * xfer,usb_error_t error)6109 uaudio_hid_rx_callback(struct usb_xfer *xfer, usb_error_t error)
6110 {
6111 	struct uaudio_softc *sc = usbd_xfer_softc(xfer);
6112 	const uint8_t *buffer = usbd_xfer_get_frame_buffer(xfer, 0);
6113 	struct snd_mixer *m;
6114 	uint8_t id;
6115 	int actlen;
6116 
6117 	usbd_xfer_status(xfer, &actlen, NULL, NULL, NULL);
6118 
6119 	switch (USB_GET_STATE(xfer)) {
6120 	case USB_ST_TRANSFERRED:
6121 		DPRINTF("actlen=%d\n", actlen);
6122 
6123 		if (actlen != 0 &&
6124 		    (sc->sc_hid.flags & UAUDIO_HID_HAS_ID)) {
6125 			id = *buffer;
6126 			buffer++;
6127 			actlen--;
6128 		} else {
6129 			id = 0;
6130 		}
6131 
6132 		m = sc->sc_child[0].mixer_dev;
6133 
6134 		if ((sc->sc_hid.flags & UAUDIO_HID_HAS_MUTE) &&
6135 		    (sc->sc_hid.mute_id == id) &&
6136 		    hid_get_data(buffer, actlen,
6137 		    &sc->sc_hid.mute_loc)) {
6138 			DPRINTF("Mute toggle\n");
6139 
6140 			mixer_hwvol_mute_locked(m);
6141 		}
6142 
6143 		if ((sc->sc_hid.flags & UAUDIO_HID_HAS_VOLUME_UP) &&
6144 		    (sc->sc_hid.volume_up_id == id) &&
6145 		    hid_get_data(buffer, actlen,
6146 		    &sc->sc_hid.volume_up_loc)) {
6147 			DPRINTF("Volume Up\n");
6148 
6149 			mixer_hwvol_step_locked(m, 1, 1);
6150 		}
6151 
6152 		if ((sc->sc_hid.flags & UAUDIO_HID_HAS_VOLUME_DOWN) &&
6153 		    (sc->sc_hid.volume_down_id == id) &&
6154 		    hid_get_data(buffer, actlen,
6155 		    &sc->sc_hid.volume_down_loc)) {
6156 			DPRINTF("Volume Down\n");
6157 
6158 			mixer_hwvol_step_locked(m, -1, -1);
6159 		}
6160 
6161 	case USB_ST_SETUP:
6162 tr_setup:
6163 		/* check if we can put more data into the FIFO */
6164 		usbd_xfer_set_frame_len(xfer, 0, usbd_xfer_max_len(xfer));
6165 		usbd_transfer_submit(xfer);
6166 		break;
6167 
6168 	default:			/* Error */
6169 
6170 		DPRINTF("error=%s\n", usbd_errstr(error));
6171 
6172 		if (error != USB_ERR_CANCELLED) {
6173 			/* try to clear stall first */
6174 			usbd_xfer_set_stall(xfer);
6175 			goto tr_setup;
6176 		}
6177 		break;
6178 	}
6179 }
6180 
6181 static int
uaudio_hid_probe(struct uaudio_softc * sc,struct usb_attach_arg * uaa)6182 uaudio_hid_probe(struct uaudio_softc *sc,
6183     struct usb_attach_arg *uaa)
6184 {
6185 	void *d_ptr;
6186 	uint32_t flags;
6187 	uint16_t d_len;
6188 	uint8_t id;
6189 	int error;
6190 
6191 	if (!(sc->sc_hid.flags & UAUDIO_HID_VALID))
6192 		return (-1);
6193 
6194 	if (sc->sc_child[0].mixer_lock == NULL)
6195 		return (-1);
6196 
6197 	/* Get HID descriptor */
6198 	error = usbd_req_get_hid_desc(uaa->device, NULL, &d_ptr,
6199 	    &d_len, M_TEMP, sc->sc_hid.iface_index);
6200 
6201 	if (error) {
6202 		DPRINTF("error reading report description\n");
6203 		return (-1);
6204 	}
6205 
6206 	/* check if there is an ID byte */
6207 	hid_report_size_max(d_ptr, d_len, hid_input, &id);
6208 
6209 	if (id != 0)
6210 		sc->sc_hid.flags |= UAUDIO_HID_HAS_ID;
6211 
6212 	if (hid_locate(d_ptr, d_len,
6213 	    HID_USAGE2(HUP_CONSUMER, 0xE9 /* Volume Increment */),
6214 	    hid_input, 0, &sc->sc_hid.volume_up_loc, &flags,
6215 	    &sc->sc_hid.volume_up_id)) {
6216 		if (flags & HIO_VARIABLE)
6217 			sc->sc_hid.flags |= UAUDIO_HID_HAS_VOLUME_UP;
6218 		DPRINTFN(1, "Found Volume Up key\n");
6219 	}
6220 
6221 	if (hid_locate(d_ptr, d_len,
6222 	    HID_USAGE2(HUP_CONSUMER, 0xEA /* Volume Decrement */),
6223 	    hid_input, 0, &sc->sc_hid.volume_down_loc, &flags,
6224 	    &sc->sc_hid.volume_down_id)) {
6225 		if (flags & HIO_VARIABLE)
6226 			sc->sc_hid.flags |= UAUDIO_HID_HAS_VOLUME_DOWN;
6227 		DPRINTFN(1, "Found Volume Down key\n");
6228 	}
6229 
6230 	if (hid_locate(d_ptr, d_len,
6231 	    HID_USAGE2(HUP_CONSUMER, 0xE2 /* Mute */),
6232 	    hid_input, 0, &sc->sc_hid.mute_loc, &flags,
6233 	    &sc->sc_hid.mute_id)) {
6234 		if (flags & HIO_VARIABLE)
6235 			sc->sc_hid.flags |= UAUDIO_HID_HAS_MUTE;
6236 		DPRINTFN(1, "Found Mute key\n");
6237 	}
6238 
6239 	free(d_ptr, M_TEMP);
6240 
6241 	if (!(sc->sc_hid.flags & (UAUDIO_HID_HAS_VOLUME_UP |
6242 	    UAUDIO_HID_HAS_VOLUME_DOWN |
6243 	    UAUDIO_HID_HAS_MUTE))) {
6244 		DPRINTFN(1, "Did not find any volume related keys\n");
6245 		return (-1);
6246 	}
6247 
6248 	/* prevent the uhid driver from attaching */
6249 	usbd_set_parent_iface(uaa->device, sc->sc_hid.iface_index,
6250 	    sc->sc_mixer_iface_index);
6251 
6252 	/* allocate USB transfers */
6253 	error = usbd_transfer_setup(uaa->device, &sc->sc_hid.iface_index,
6254 	    sc->sc_hid.xfer, uaudio_hid_config, UAUDIO_HID_N_TRANSFER,
6255 	    sc, sc->sc_child[0].mixer_lock);
6256 	if (error) {
6257 		DPRINTF("error=%s\n", usbd_errstr(error));
6258 		return (-1);
6259 	}
6260 	return (0);
6261 }
6262 
6263 static void
uaudio_hid_detach(struct uaudio_softc * sc)6264 uaudio_hid_detach(struct uaudio_softc *sc)
6265 {
6266 	usbd_transfer_unsetup(sc->sc_hid.xfer, UAUDIO_HID_N_TRANSFER);
6267 }
6268 
6269 DRIVER_MODULE_ORDERED(snd_uaudio, uhub, uaudio_driver, NULL, NULL, SI_ORDER_ANY);
6270 MODULE_DEPEND(snd_uaudio, usb, 1, 1, 1);
6271 MODULE_DEPEND(snd_uaudio, sound, SOUND_MINVER, SOUND_PREFVER, SOUND_MAXVER);
6272 MODULE_DEPEND(snd_uaudio, hid, 1, 1, 1);
6273 MODULE_VERSION(snd_uaudio, 1);
6274 USB_PNP_HOST_INFO(uaudio_devs);
6275 USB_PNP_HOST_INFO(uaudio_vendor_midi);
6276