xref: /freebsd/sys/dev/sound/usb/uaudio.c (revision eccd366b0a8ba7d902fcf0b1bec447926a75c36c)
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 lock;		/* 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->lock);
1394 		chan->cur_alt = CHAN_MAX_ALT;
1395 		mtx_unlock(&chan->lock);
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->lock);
1419 	next_alt = chan->set_alt;
1420 	mtx_unlock(&chan->lock);
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->lock)) {
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->lock);
1531 	chan->cur_alt = next_alt;
1532 	usbd_transfer_start(chan->xfer[0]);
1533 	usbd_transfer_start(chan->xfer[1]);
1534 	mtx_unlock(&chan->lock);
1535 	return;
1536 error:
1537 	usbd_transfer_unsetup(chan->xfer, UAUDIO_NCHANBUFS + 1);
1538 
1539 	mtx_lock(&chan->lock);
1540 	chan->cur_alt = CHAN_MAX_ALT;
1541 	mtx_unlock(&chan->lock);
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 	mtx_init(&ch->lock, "uaudio_chan lock", NULL, MTX_DEF);
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 	return (ch);
2694 
2695 error:
2696 	uaudio_chan_free(ch);
2697 	return (NULL);
2698 }
2699 
2700 int
uaudio_chan_free(struct uaudio_chan * ch)2701 uaudio_chan_free(struct uaudio_chan *ch)
2702 {
2703 	free(ch->buf, M_DEVBUF);
2704 	ch->buf = NULL;
2705 	usbd_transfer_unsetup(ch->xfer, UAUDIO_NCHANBUFS + 1);
2706 	mtx_destroy(&ch->lock);
2707 
2708 	ch->num_alt = 0;
2709 
2710 	return (0);
2711 }
2712 
2713 int
uaudio_chan_set_param_blocksize(struct uaudio_chan * ch,uint32_t blocksize)2714 uaudio_chan_set_param_blocksize(struct uaudio_chan *ch, uint32_t blocksize)
2715 {
2716 	uint32_t temp = 2 * uaudio_get_buffer_size(ch, ch->set_alt);
2717 	sndbuf_setup(ch->pcm_buf, ch->buf, temp);
2718 	return (temp / 2);
2719 }
2720 
2721 int
uaudio_chan_set_param_fragments(struct uaudio_chan * ch,uint32_t blocksize,uint32_t blockcount)2722 uaudio_chan_set_param_fragments(struct uaudio_chan *ch, uint32_t blocksize,
2723     uint32_t blockcount)
2724 {
2725 	return (1);
2726 }
2727 
2728 int
uaudio_chan_set_param_speed(struct uaudio_chan * ch,uint32_t speed)2729 uaudio_chan_set_param_speed(struct uaudio_chan *ch, uint32_t speed)
2730 {
2731 	struct uaudio_softc *sc;
2732 	uint8_t x, y;
2733 
2734 	sc = ch->priv_sc;
2735 
2736 	for (x = 0, y = 1; y < ch->num_alt; y++) {
2737 		/* prefer sample rate closer to and greater than requested */
2738 		if ((ch->usb_alt[x].sample_rate < speed &&
2739 		    ch->usb_alt[x].sample_rate < ch->usb_alt[y].sample_rate) ||
2740 		    (speed <= ch->usb_alt[y].sample_rate &&
2741 		    ch->usb_alt[y].sample_rate < ch->usb_alt[x].sample_rate))
2742 			x = y;
2743 	}
2744 
2745 	usb_proc_explore_lock(sc->sc_udev);
2746 	ch->set_alt = x;
2747 	usb_proc_explore_unlock(sc->sc_udev);
2748 
2749 	DPRINTF("Selecting alt %d\n", (int)x);
2750 
2751 	return (ch->usb_alt[x].sample_rate);
2752 }
2753 
2754 int
uaudio_chan_getptr(struct uaudio_chan * ch)2755 uaudio_chan_getptr(struct uaudio_chan *ch)
2756 {
2757 	return (ch->cur - ch->start);
2758 }
2759 
2760 struct pcmchan_caps *
uaudio_chan_getcaps(struct uaudio_chan * ch)2761 uaudio_chan_getcaps(struct uaudio_chan *ch)
2762 {
2763 	return (&ch->pcm_cap);
2764 }
2765 
2766 static struct pcmchan_matrix uaudio_chan_matrix_swap_2_0 = {
2767 	.id = SND_CHN_MATRIX_DRV,
2768 	.channels = 2,
2769 	.ext = 0,
2770 	.map = {
2771 		/* Right */
2772 		[0] = {
2773 			.type = SND_CHN_T_FR,
2774 			.members =
2775 			    SND_CHN_T_MASK_FR | SND_CHN_T_MASK_FC |
2776 			    SND_CHN_T_MASK_LF | SND_CHN_T_MASK_BR |
2777 			    SND_CHN_T_MASK_BC | SND_CHN_T_MASK_SR
2778 		},
2779 		/* Left */
2780 		[1] = {
2781 			.type = SND_CHN_T_FL,
2782 			.members =
2783 			    SND_CHN_T_MASK_FL | SND_CHN_T_MASK_FC |
2784 			    SND_CHN_T_MASK_LF | SND_CHN_T_MASK_BL |
2785 			    SND_CHN_T_MASK_BC | SND_CHN_T_MASK_SL
2786 		},
2787 		[2] = {
2788 			.type = SND_CHN_T_MAX,
2789 			.members = 0
2790 		}
2791 	},
2792 	.mask = SND_CHN_T_MASK_FR | SND_CHN_T_MASK_FL,
2793 	.offset = {  1,  0, -1, -1, -1, -1, -1, -1, -1,
2794 		    -1, -1, -1, -1, -1, -1, -1, -1, -1  }
2795 };
2796 
2797 struct pcmchan_matrix *
uaudio_chan_getmatrix(struct uaudio_chan * ch,uint32_t format)2798 uaudio_chan_getmatrix(struct uaudio_chan *ch, uint32_t format)
2799 {
2800 	struct uaudio_softc *sc;
2801 
2802 	sc = ch->priv_sc;
2803 
2804 	if (sc != NULL && sc->sc_uq_audio_swap_lr != 0 &&
2805 	    AFMT_CHANNEL(format) == 2)
2806 		return (&uaudio_chan_matrix_swap_2_0);
2807 
2808 	return (feeder_matrix_format_map(format));
2809 }
2810 
2811 int
uaudio_chan_set_param_format(struct uaudio_chan * ch,uint32_t format)2812 uaudio_chan_set_param_format(struct uaudio_chan *ch, uint32_t format)
2813 {
2814 	DPRINTF("Selecting format 0x%08x\n", (unsigned int)format);
2815 	return (0);
2816 }
2817 
2818 static void
uaudio_chan_reconfigure(struct uaudio_chan * ch,uint8_t operation)2819 uaudio_chan_reconfigure(struct uaudio_chan *ch, uint8_t operation)
2820 {
2821 	struct uaudio_softc *sc = ch->priv_sc;
2822 
2823 	/* Check for shutdown. */
2824 	if (ch->operation == CHAN_OP_DRAIN)
2825 		return;
2826 
2827 	/* Set next operation. */
2828 	ch->operation = operation;
2829 
2830 	/*
2831 	 * Because changing the alternate setting modifies the USB
2832 	 * configuration, this part must be executed from the USB
2833 	 * explore process.
2834 	 */
2835 	(void)usb_proc_explore_msignal(sc->sc_udev,
2836 	    &sc->sc_config_msg[0], &sc->sc_config_msg[1]);
2837 }
2838 
2839 static int
uaudio_chan_need_both(struct uaudio_chan * pchan,struct uaudio_chan * rchan)2840 uaudio_chan_need_both(struct uaudio_chan *pchan, struct uaudio_chan *rchan)
2841 {
2842 	return (pchan->num_alt > 0 &&
2843 	    pchan->running != 0 &&
2844 	    uaudio_chan_is_async(pchan, pchan->set_alt) != 0 &&
2845 	    rchan->num_alt > 0 &&
2846 	    rchan->running == 0);
2847 }
2848 
2849 static int
uaudio_chan_need_none(struct uaudio_chan * pchan,struct uaudio_chan * rchan)2850 uaudio_chan_need_none(struct uaudio_chan *pchan, struct uaudio_chan *rchan)
2851 {
2852 	return (pchan->num_alt > 0 &&
2853 	    pchan->running == 0 &&
2854 	    rchan->num_alt > 0 &&
2855 	    rchan->running == 0);
2856 }
2857 
2858 void
uaudio_chan_start(struct uaudio_chan * ch)2859 uaudio_chan_start(struct uaudio_chan *ch)
2860 {
2861 	struct uaudio_softc *sc = ch->priv_sc;
2862 	unsigned i = uaudio_get_child_index_by_chan(sc, ch);
2863 
2864 	/* make operation atomic */
2865 	usb_proc_explore_lock(sc->sc_udev);
2866 
2867 	/* check if not running */
2868 	if (ch->running == 0) {
2869 		uint32_t temp;
2870 
2871 		/* get current buffer size */
2872 		temp = 2 * uaudio_get_buffer_size(ch, ch->set_alt);
2873 
2874 		/* set running flag */
2875 		ch->running = 1;
2876 
2877 		/* ensure the hardware buffer is reset */
2878 		ch->start = ch->buf;
2879 		ch->end = ch->buf + temp;
2880 		ch->cur = ch->buf;
2881 
2882 		if (uaudio_chan_need_both(
2883 		    &sc->sc_play_chan[i],
2884 		    &sc->sc_rec_chan[i])) {
2885 			/*
2886 			 * Start both endpoints because of need for
2887 			 * jitter information:
2888 			 */
2889 			uaudio_chan_reconfigure(&sc->sc_rec_chan[i], CHAN_OP_START);
2890 			uaudio_chan_reconfigure(&sc->sc_play_chan[i], CHAN_OP_START);
2891 		} else {
2892 			uaudio_chan_reconfigure(ch, CHAN_OP_START);
2893 		}
2894 	}
2895 
2896 	/* exit atomic operation */
2897 	usb_proc_explore_unlock(sc->sc_udev);
2898 }
2899 
2900 void
uaudio_chan_stop(struct uaudio_chan * ch)2901 uaudio_chan_stop(struct uaudio_chan *ch)
2902 {
2903 	struct uaudio_softc *sc = ch->priv_sc;
2904 	unsigned i = uaudio_get_child_index_by_chan(sc, ch);
2905 
2906 	/* make operation atomic */
2907 	usb_proc_explore_lock(sc->sc_udev);
2908 
2909 	/* check if running */
2910 	if (ch->running != 0) {
2911 		/* clear running flag */
2912 		ch->running = 0;
2913 
2914 		if (uaudio_chan_need_both(
2915 		    &sc->sc_play_chan[i],
2916 		    &sc->sc_rec_chan[i])) {
2917 			/*
2918 			 * Leave the endpoints running because we need
2919 			 * information about jitter!
2920 			 */
2921 		} else if (uaudio_chan_need_none(
2922 		    &sc->sc_play_chan[i],
2923 		    &sc->sc_rec_chan[i])) {
2924 			/*
2925 			 * Stop both endpoints in case the one was used for
2926 			 * jitter information:
2927 			 */
2928 			uaudio_chan_reconfigure(&sc->sc_rec_chan[i], CHAN_OP_STOP);
2929 			uaudio_chan_reconfigure(&sc->sc_play_chan[i], CHAN_OP_STOP);
2930 		} else {
2931 			uaudio_chan_reconfigure(ch, CHAN_OP_STOP);
2932 		}
2933 	}
2934 
2935 	/* exit atomic operation */
2936 	usb_proc_explore_unlock(sc->sc_udev);
2937 }
2938 
2939 /*========================================================================*
2940  * AC - Audio Controller - routines
2941  *========================================================================*/
2942 
2943 static int
uaudio_mixer_sysctl_handler(SYSCTL_HANDLER_ARGS)2944 uaudio_mixer_sysctl_handler(SYSCTL_HANDLER_ARGS)
2945 {
2946 	struct uaudio_softc *sc;
2947 	struct uaudio_mixer_node *pmc;
2948 	int hint;
2949 	int error;
2950 	int temp = 0;
2951 	int chan = 0;
2952 
2953 	sc = (struct uaudio_softc *)oidp->oid_arg1;
2954 	hint = oidp->oid_arg2;
2955 
2956 	if (sc->sc_child[0].mixer_lock == NULL)
2957 		return (ENXIO);
2958 
2959 	/* lookup mixer node */
2960 
2961 	mtx_lock(sc->sc_child[0].mixer_lock);
2962 	for (pmc = sc->sc_mixer_root; pmc != NULL; pmc = pmc->next) {
2963 		for (chan = 0; chan != (int)pmc->nchan; chan++) {
2964 			if (pmc->wValue[chan] != -1 &&
2965 			    pmc->wValue[chan] == hint) {
2966 				temp = pmc->wData[chan];
2967 				goto found;
2968 			}
2969 		}
2970 	}
2971 found:
2972 	mtx_unlock(sc->sc_child[0].mixer_lock);
2973 
2974 	error = sysctl_handle_int(oidp, &temp, 0, req);
2975 	if (error != 0 || req->newptr == NULL)
2976 		return (error);
2977 
2978 	/* update mixer value */
2979 
2980 	mtx_lock(sc->sc_child[0].mixer_lock);
2981 	if (pmc != NULL &&
2982 	    temp >= pmc->minval &&
2983 	    temp <= pmc->maxval) {
2984 		pmc->wData[chan] = temp;
2985 		pmc->update[(chan / 8)] |= (1 << (chan % 8));
2986 
2987 		/* start the transfer, if not already started */
2988 		usbd_transfer_start(sc->sc_mixer_xfer[0]);
2989 	}
2990 	mtx_unlock(sc->sc_child[0].mixer_lock);
2991 
2992 	return (0);
2993 }
2994 
2995 static void
uaudio_mixer_ctl_free(struct uaudio_softc * sc)2996 uaudio_mixer_ctl_free(struct uaudio_softc *sc)
2997 {
2998 	struct uaudio_mixer_node *p_mc;
2999 
3000 	while ((p_mc = sc->sc_mixer_root) != NULL) {
3001 		sc->sc_mixer_root = p_mc->next;
3002 		free(p_mc, M_USBDEV);
3003 	}
3004 }
3005 
3006 static void
uaudio_mixer_register_sysctl(struct uaudio_softc * sc,device_t dev,unsigned index)3007 uaudio_mixer_register_sysctl(struct uaudio_softc *sc, device_t dev,
3008     unsigned index)
3009 {
3010 	struct uaudio_mixer_node *pmc;
3011 	struct sysctl_oid *mixer_tree;
3012 	struct sysctl_oid *control_tree;
3013 	char buf[32];
3014 	int chan;
3015 	int n;
3016 
3017 	if (index != 0)
3018 		return;
3019 
3020 	mixer_tree = SYSCTL_ADD_NODE(device_get_sysctl_ctx(dev),
3021 	    SYSCTL_CHILDREN(device_get_sysctl_tree(dev)), OID_AUTO, "mixer",
3022 	    CTLFLAG_RD | CTLFLAG_MPSAFE, NULL, "");
3023 
3024 	if (mixer_tree == NULL)
3025 		return;
3026 
3027 	for (n = 0, pmc = sc->sc_mixer_root; pmc != NULL;
3028 	    pmc = pmc->next, n++) {
3029 		for (chan = 0; chan < pmc->nchan; chan++) {
3030 			if (pmc->nchan > 1) {
3031 				snprintf(buf, sizeof(buf), "%s_%d_%d",
3032 				    pmc->name, n, chan);
3033 			} else {
3034 				snprintf(buf, sizeof(buf), "%s_%d",
3035 				    pmc->name, n);
3036 			}
3037 
3038 			control_tree = SYSCTL_ADD_NODE(device_get_sysctl_ctx(dev),
3039 			    SYSCTL_CHILDREN(mixer_tree), OID_AUTO, buf,
3040 			    CTLFLAG_RD | CTLFLAG_MPSAFE, NULL,
3041 			    "Mixer control nodes");
3042 
3043 			if (control_tree == NULL)
3044 				continue;
3045 
3046 			SYSCTL_ADD_PROC(device_get_sysctl_ctx(dev),
3047 			    SYSCTL_CHILDREN(control_tree),
3048 			    OID_AUTO, "val",
3049 			    CTLTYPE_INT | CTLFLAG_RWTUN | CTLFLAG_MPSAFE,
3050 			    sc, pmc->wValue[chan],
3051 			    uaudio_mixer_sysctl_handler, "I", "Current value");
3052 
3053 			SYSCTL_ADD_INT(device_get_sysctl_ctx(dev),
3054 			    SYSCTL_CHILDREN(control_tree),
3055 			    OID_AUTO, "min", CTLFLAG_RD, 0, pmc->minval,
3056 			    "Minimum value");
3057 
3058 			SYSCTL_ADD_INT(device_get_sysctl_ctx(dev),
3059 			    SYSCTL_CHILDREN(control_tree),
3060 			    OID_AUTO, "max", CTLFLAG_RD, 0, pmc->maxval,
3061 			    "Maximum value");
3062 
3063 			SYSCTL_ADD_STRING(device_get_sysctl_ctx(dev),
3064 			    SYSCTL_CHILDREN(control_tree),
3065 			    OID_AUTO, "desc", CTLFLAG_RD, pmc->desc, 0,
3066 			    "Description");
3067 		}
3068 	}
3069 }
3070 
3071 /* M-Audio FastTrack Ultra Mixer Description */
3072 /* Origin: Linux USB Audio driver */
3073 static void
uaudio_mixer_controls_create_ftu(struct uaudio_softc * sc)3074 uaudio_mixer_controls_create_ftu(struct uaudio_softc *sc)
3075 {
3076 	int chx;
3077 	int chy;
3078 
3079 	memset(&MIX(sc), 0, sizeof(MIX(sc)));
3080 	MIX(sc).wIndex = MAKE_WORD(6, sc->sc_mixer_iface_no);
3081 	MIX(sc).wValue[0] = MAKE_WORD(8, 0);
3082 	MIX(sc).type = MIX_UNSIGNED_16;
3083 	MIX(sc).ctl = SOUND_MIXER_NRDEVICES;
3084 	MIX(sc).name = "effect";
3085 	MIX(sc).minval = 0;
3086 	MIX(sc).maxval = 7;
3087 	MIX(sc).mul = 7;
3088 	MIX(sc).nchan = 1;
3089 	MIX(sc).update[0] = 1;
3090 	strlcpy(MIX(sc).desc, "Room1,2,3,Hall1,2,Plate,Delay,Echo", sizeof(MIX(sc).desc));
3091 	uaudio_mixer_add_ctl_sub(sc, &MIX(sc));
3092 
3093 	memset(&MIX(sc), 0, sizeof(MIX(sc)));
3094 	MIX(sc).wIndex = MAKE_WORD(5, sc->sc_mixer_iface_no);
3095 
3096 	for (chx = 0; chx != 8; chx++) {
3097 		for (chy = 0; chy != 8; chy++) {
3098 			MIX(sc).wValue[0] = MAKE_WORD(chx + 1, chy + 1);
3099 			MIX(sc).type = MIX_SIGNED_16;
3100 			MIX(sc).ctl = SOUND_MIXER_NRDEVICES;
3101 			MIX(sc).name = "mix_rec";
3102 			MIX(sc).nchan = 1;
3103 			MIX(sc).update[0] = 1;
3104 			MIX(sc).val_default = 0;
3105 			snprintf(MIX(sc).desc, sizeof(MIX(sc).desc),
3106 			    "AIn%d - Out%d Record Volume", chy + 1, chx + 1);
3107 
3108 			uaudio_mixer_add_ctl(sc, &MIX(sc));
3109 
3110 			MIX(sc).wValue[0] = MAKE_WORD(chx + 1, chy + 1 + 8);
3111 			MIX(sc).type = MIX_SIGNED_16;
3112 			MIX(sc).ctl = SOUND_MIXER_NRDEVICES;
3113 			MIX(sc).name = "mix_play";
3114 			MIX(sc).nchan = 1;
3115 			MIX(sc).update[0] = 1;
3116 			MIX(sc).val_default = (chx == chy) ? 2 : 0;
3117 			snprintf(MIX(sc).desc, sizeof(MIX(sc).desc),
3118 			    "DIn%d - Out%d Playback Volume", chy + 1, chx + 1);
3119 
3120 			uaudio_mixer_add_ctl(sc, &MIX(sc));
3121 		}
3122 	}
3123 
3124 	memset(&MIX(sc), 0, sizeof(MIX(sc)));
3125 	MIX(sc).wIndex = MAKE_WORD(6, sc->sc_mixer_iface_no);
3126 	MIX(sc).wValue[0] = MAKE_WORD(2, 0);
3127 	MIX(sc).type = MIX_SIGNED_8;
3128 	MIX(sc).ctl = SOUND_MIXER_NRDEVICES;
3129 	MIX(sc).name = "effect_vol";
3130 	MIX(sc).nchan = 1;
3131 	MIX(sc).update[0] = 1;
3132 	MIX(sc).minval = 0;
3133 	MIX(sc).maxval = 0x7f;
3134 	MIX(sc).mul = 0x7f;
3135 	MIX(sc).nchan = 1;
3136 	MIX(sc).update[0] = 1;
3137 	strlcpy(MIX(sc).desc, "Effect Volume", sizeof(MIX(sc).desc));
3138 	uaudio_mixer_add_ctl_sub(sc, &MIX(sc));
3139 
3140 	memset(&MIX(sc), 0, sizeof(MIX(sc)));
3141 	MIX(sc).wIndex = MAKE_WORD(6, sc->sc_mixer_iface_no);
3142 	MIX(sc).wValue[0] = MAKE_WORD(3, 0);
3143 	MIX(sc).type = MIX_SIGNED_16;
3144 	MIX(sc).ctl = SOUND_MIXER_NRDEVICES;
3145 	MIX(sc).name = "effect_dur";
3146 	MIX(sc).nchan = 1;
3147 	MIX(sc).update[0] = 1;
3148 	MIX(sc).minval = 0;
3149 	MIX(sc).maxval = 0x7f00;
3150 	MIX(sc).mul = 0x7f00;
3151 	MIX(sc).nchan = 1;
3152 	MIX(sc).update[0] = 1;
3153 	strlcpy(MIX(sc).desc, "Effect Duration", sizeof(MIX(sc).desc));
3154 	uaudio_mixer_add_ctl_sub(sc, &MIX(sc));
3155 
3156 	memset(&MIX(sc), 0, sizeof(MIX(sc)));
3157 	MIX(sc).wIndex = MAKE_WORD(6, sc->sc_mixer_iface_no);
3158 	MIX(sc).wValue[0] = MAKE_WORD(4, 0);
3159 	MIX(sc).type = MIX_SIGNED_8;
3160 	MIX(sc).ctl = SOUND_MIXER_NRDEVICES;
3161 	MIX(sc).name = "effect_fb";
3162 	MIX(sc).nchan = 1;
3163 	MIX(sc).update[0] = 1;
3164 	MIX(sc).minval = 0;
3165 	MIX(sc).maxval = 0x7f;
3166 	MIX(sc).mul = 0x7f;
3167 	MIX(sc).nchan = 1;
3168 	MIX(sc).update[0] = 1;
3169 	strlcpy(MIX(sc).desc, "Effect Feedback Volume", sizeof(MIX(sc).desc));
3170 	uaudio_mixer_add_ctl_sub(sc, &MIX(sc));
3171 
3172 	memset(&MIX(sc), 0, sizeof(MIX(sc)));
3173 	MIX(sc).wIndex = MAKE_WORD(7, sc->sc_mixer_iface_no);
3174 	for (chy = 0; chy != 4; chy++) {
3175 		MIX(sc).wValue[0] = MAKE_WORD(7, chy + 1);
3176 		MIX(sc).type = MIX_SIGNED_16;
3177 		MIX(sc).ctl = SOUND_MIXER_NRDEVICES;
3178 		MIX(sc).name = "effect_ret";
3179 		MIX(sc).nchan = 1;
3180 		MIX(sc).update[0] = 1;
3181 		snprintf(MIX(sc).desc, sizeof(MIX(sc).desc),
3182 		    "Effect Return %d Volume", chy + 1);
3183 
3184 		uaudio_mixer_add_ctl(sc, &MIX(sc));
3185 	}
3186 
3187 	memset(&MIX(sc), 0, sizeof(MIX(sc)));
3188 	MIX(sc).wIndex = MAKE_WORD(5, sc->sc_mixer_iface_no);
3189 
3190 	for (chy = 0; chy != 8; chy++) {
3191 		MIX(sc).wValue[0] = MAKE_WORD(9, chy + 1);
3192 		MIX(sc).type = MIX_SIGNED_16;
3193 		MIX(sc).ctl = SOUND_MIXER_NRDEVICES;
3194 		MIX(sc).name = "effect_send";
3195 		MIX(sc).nchan = 1;
3196 		MIX(sc).update[0] = 1;
3197 		snprintf(MIX(sc).desc, sizeof(MIX(sc).desc),
3198 		    "Effect Send AIn%d Volume", chy + 1);
3199 
3200 		uaudio_mixer_add_ctl(sc, &MIX(sc));
3201 
3202 		MIX(sc).wValue[0] = MAKE_WORD(9, chy + 1 + 8);
3203 		MIX(sc).type = MIX_SIGNED_16;
3204 		MIX(sc).ctl = SOUND_MIXER_NRDEVICES;
3205 		MIX(sc).name = "effect_send";
3206 		MIX(sc).nchan = 1;
3207 		MIX(sc).update[0] = 1;
3208 		snprintf(MIX(sc).desc, sizeof(MIX(sc).desc),
3209 		    "Effect Send DIn%d Volume", chy + 1);
3210 
3211 		uaudio_mixer_add_ctl(sc, &MIX(sc));
3212 	}
3213 }
3214 
3215 static void
uaudio_mixer_reload_all(struct uaudio_softc * sc)3216 uaudio_mixer_reload_all(struct uaudio_softc *sc)
3217 {
3218 	struct uaudio_mixer_node *pmc;
3219 	int chan;
3220 
3221 	if (sc->sc_child[0].mixer_lock == NULL)
3222 		return;
3223 
3224 	mtx_lock(sc->sc_child[0].mixer_lock);
3225 	for (pmc = sc->sc_mixer_root; pmc != NULL; pmc = pmc->next) {
3226 		/* use reset defaults for non-oss controlled settings */
3227 		if (pmc->ctl == SOUND_MIXER_NRDEVICES)
3228 			continue;
3229 		for (chan = 0; chan < pmc->nchan; chan++)
3230 			pmc->update[chan / 8] |= (1 << (chan % 8));
3231 	}
3232 	usbd_transfer_start(sc->sc_mixer_xfer[0]);
3233 
3234 	/* start HID volume keys, if any */
3235 	usbd_transfer_start(sc->sc_hid.xfer[0]);
3236 	mtx_unlock(sc->sc_child[0].mixer_lock);
3237 }
3238 
3239 static void
uaudio_mixer_add_ctl_sub(struct uaudio_softc * sc,struct uaudio_mixer_node * mc)3240 uaudio_mixer_add_ctl_sub(struct uaudio_softc *sc, struct uaudio_mixer_node *mc)
3241 {
3242 	struct uaudio_mixer_node *p_mc_new =
3243 	    malloc(sizeof(*p_mc_new), M_USBDEV, M_WAITOK);
3244 	int ch;
3245 
3246 	memcpy(p_mc_new, mc, sizeof(*p_mc_new));
3247 	p_mc_new->next = sc->sc_mixer_root;
3248 	sc->sc_mixer_root = p_mc_new;
3249 	sc->sc_mixer_count++;
3250 
3251 	/* set default value for all channels */
3252 	for (ch = 0; ch < p_mc_new->nchan; ch++) {
3253 		switch (p_mc_new->val_default) {
3254 		case 1:
3255 			/* 50% */
3256 			p_mc_new->wData[ch] = (p_mc_new->maxval + p_mc_new->minval) / 2;
3257 			break;
3258 		case 2:
3259 			/* 100% */
3260 			p_mc_new->wData[ch] = p_mc_new->maxval;
3261 			break;
3262 		default:
3263 			/* 0% */
3264 			p_mc_new->wData[ch] = p_mc_new->minval;
3265 			break;
3266 		}
3267 	}
3268 }
3269 
3270 static void
uaudio_mixer_add_ctl(struct uaudio_softc * sc,struct uaudio_mixer_node * mc)3271 uaudio_mixer_add_ctl(struct uaudio_softc *sc, struct uaudio_mixer_node *mc)
3272 {
3273 	int32_t res;
3274 
3275 	DPRINTF("adding %d\n", mc->ctl);
3276 
3277 	if (mc->type == MIX_ON_OFF) {
3278 		mc->minval = 0;
3279 		mc->maxval = 1;
3280 	} else if (mc->type == MIX_SELECTOR) {
3281 	} else {
3282 		/* determine min and max values */
3283 
3284 		mc->minval = uaudio_mixer_get(sc->sc_udev,
3285 		    sc->sc_audio_rev, GET_MIN, mc);
3286 		mc->maxval = uaudio_mixer_get(sc->sc_udev,
3287 		    sc->sc_audio_rev, GET_MAX, mc);
3288 
3289 		/* check if max and min was swapped */
3290 
3291 		if (mc->maxval < mc->minval) {
3292 			res = mc->maxval;
3293 			mc->maxval = mc->minval;
3294 			mc->minval = res;
3295 		}
3296 
3297 		/* compute value range */
3298 		mc->mul = mc->maxval - mc->minval;
3299 		if (mc->mul == 0)
3300 			mc->mul = 1;
3301 
3302 		/* compute value alignment */
3303 		res = uaudio_mixer_get(sc->sc_udev,
3304 		    sc->sc_audio_rev, GET_RES, mc);
3305 
3306 		DPRINTF("Resolution = %d\n", (int)res);
3307 	}
3308 
3309 	uaudio_mixer_add_ctl_sub(sc, mc);
3310 
3311 #ifdef USB_DEBUG
3312 	if (uaudio_debug > 2) {
3313 		uint8_t i;
3314 
3315 		for (i = 0; i < mc->nchan; i++) {
3316 			DPRINTF("[mix] wValue=%04x\n", mc->wValue[0]);
3317 		}
3318 		DPRINTF("[mix] wIndex=%04x type=%d ctl='%d' "
3319 		    "min=%d max=%d\n",
3320 		    mc->wIndex, mc->type, mc->ctl,
3321 		    mc->minval, mc->maxval);
3322 	}
3323 #endif
3324 }
3325 
3326 static void
uaudio_mixer_add_mixer(struct uaudio_softc * sc,const struct uaudio_terminal_node * iot,int id)3327 uaudio_mixer_add_mixer(struct uaudio_softc *sc,
3328     const struct uaudio_terminal_node *iot, int id)
3329 {
3330 	const struct usb_audio_mixer_unit_0 *d0 = iot[id].u.mu_v1;
3331 	const struct usb_audio_mixer_unit_1 *d1;
3332 
3333 	uint32_t bno;			/* bit number */
3334 	uint32_t p;			/* bit number accumulator */
3335 	uint32_t mo;			/* matching outputs */
3336 	uint32_t mc;			/* matching channels */
3337 	uint32_t ichs;			/* input channels */
3338 	uint32_t ochs;			/* output channels */
3339 	uint32_t c;
3340 	uint32_t chs;			/* channels */
3341 	uint32_t i;
3342 	uint32_t o;
3343 
3344 	DPRINTFN(3, "bUnitId=%d bNrInPins=%d\n",
3345 	    d0->bUnitId, d0->bNrInPins);
3346 
3347 	/* compute the number of input channels */
3348 
3349 	ichs = 0;
3350 	for (i = 0; i < d0->bNrInPins; i++) {
3351 		ichs += uaudio_mixer_get_cluster(
3352 		    d0->baSourceId[i], iot).bNrChannels;
3353 	}
3354 
3355 	d1 = (const void *)(d0->baSourceId + d0->bNrInPins);
3356 
3357 	/* and the number of output channels */
3358 
3359 	ochs = d1->bNrChannels;
3360 
3361 	DPRINTFN(3, "ichs=%d ochs=%d\n", ichs, ochs);
3362 
3363 	memset(&MIX(sc), 0, sizeof(MIX(sc)));
3364 
3365 	MIX(sc).wIndex = MAKE_WORD(d0->bUnitId, sc->sc_mixer_iface_no);
3366 	MIX(sc).type = MIX_SIGNED_16;
3367 
3368 	if (uaudio_mixer_verify_desc(d0, ((ichs * ochs) + 7) / 8) == NULL)
3369 		return;
3370 
3371 	for (p = i = 0; i < d0->bNrInPins; i++) {
3372 		chs = uaudio_mixer_get_cluster(
3373 		    d0->baSourceId[i], iot).bNrChannels;
3374 		mc = 0;
3375 		for (c = 0; c < chs; c++) {
3376 			mo = 0;
3377 			for (o = 0; o < ochs; o++) {
3378 				bno = ((p + c) * ochs) + o;
3379 				if (BIT_TEST(d1->bmControls, bno))
3380 					mo++;
3381 			}
3382 			if (mo == 1)
3383 				mc++;
3384 		}
3385 		if ((mc == chs) && (chs <= MIX_MAX_CHAN)) {
3386 			/* repeat bit-scan */
3387 
3388 			mc = 0;
3389 			for (c = 0; c < chs; c++) {
3390 				for (o = 0; o < ochs; o++) {
3391 					bno = ((p + c) * ochs) + o;
3392 					if (BIT_TEST(d1->bmControls, bno))
3393 						MIX(sc).wValue[mc++] = MAKE_WORD(p + c + 1, o + 1);
3394 				}
3395 			}
3396 			MIX(sc).nchan = chs;
3397 			uaudio_mixer_add_ctl(sc, &MIX(sc));
3398 		}
3399 		p += chs;
3400 	}
3401 }
3402 
3403 static void
uaudio20_mixer_add_mixer(struct uaudio_softc * sc,const struct uaudio_terminal_node * iot,int id)3404 uaudio20_mixer_add_mixer(struct uaudio_softc *sc,
3405     const struct uaudio_terminal_node *iot, int id)
3406 {
3407 	const struct usb_audio20_mixer_unit_0 *d0 = iot[id].u.mu_v2;
3408 	const struct usb_audio20_mixer_unit_1 *d1;
3409 
3410 	uint32_t bno;			/* bit number */
3411 	uint32_t p;			/* bit number accumulator */
3412 	uint32_t mo;			/* matching outputs */
3413 	uint32_t mc;			/* matching channels */
3414 	uint32_t ichs;			/* input channels */
3415 	uint32_t ochs;			/* output channels */
3416 	uint32_t c;
3417 	uint32_t chs;			/* channels */
3418 	uint32_t i;
3419 	uint32_t o;
3420 
3421 	DPRINTFN(3, "bUnitId=%d bNrInPins=%d\n",
3422 	    d0->bUnitId, d0->bNrInPins);
3423 
3424 	/* compute the number of input channels */
3425 
3426 	ichs = 0;
3427 	for (i = 0; i < d0->bNrInPins; i++) {
3428 		ichs += uaudio20_mixer_get_cluster(
3429 		    d0->baSourceId[i], iot).bNrChannels;
3430 	}
3431 
3432 	d1 = (const void *)(d0->baSourceId + d0->bNrInPins);
3433 
3434 	/* and the number of output channels */
3435 
3436 	ochs = d1->bNrChannels;
3437 
3438 	DPRINTFN(3, "ichs=%d ochs=%d\n", ichs, ochs);
3439 
3440 	memset(&MIX(sc), 0, sizeof(MIX(sc)));
3441 
3442 	MIX(sc).wIndex = MAKE_WORD(d0->bUnitId, sc->sc_mixer_iface_no);
3443 	MIX(sc).type = MIX_SIGNED_16;
3444 
3445 	if (uaudio20_mixer_verify_desc(d0, ((ichs * ochs) + 7) / 8) == NULL)
3446 		return;
3447 
3448 	for (p = i = 0; i < d0->bNrInPins; i++) {
3449 		chs = uaudio20_mixer_get_cluster(
3450 		    d0->baSourceId[i], iot).bNrChannels;
3451 		mc = 0;
3452 		for (c = 0; c < chs; c++) {
3453 			mo = 0;
3454 			for (o = 0; o < ochs; o++) {
3455 				bno = ((p + c) * ochs) + o;
3456 				if (BIT_TEST(d1->bmControls, bno))
3457 					mo++;
3458 			}
3459 			if (mo == 1)
3460 				mc++;
3461 		}
3462 		if ((mc == chs) && (chs <= MIX_MAX_CHAN)) {
3463 			/* repeat bit-scan */
3464 
3465 			mc = 0;
3466 			for (c = 0; c < chs; c++) {
3467 				for (o = 0; o < ochs; o++) {
3468 					bno = ((p + c) * ochs) + o;
3469 					if (BIT_TEST(d1->bmControls, bno))
3470 						MIX(sc).wValue[mc++] = MAKE_WORD(p + c + 1, o + 1);
3471 				}
3472 			}
3473 			MIX(sc).nchan = chs;
3474 			uaudio_mixer_add_ctl(sc, &MIX(sc));
3475 		}
3476 		p += chs;
3477 	}
3478 }
3479 
3480 static void
uaudio_mixer_check_selectors(struct uaudio_softc * sc)3481 uaudio_mixer_check_selectors(struct uaudio_softc *sc)
3482 {
3483 	uint8_t reserve_feature[] = {
3484 	    SOUND_MIXER_LINE,
3485 	    SOUND_MIXER_LINE1,
3486 	    SOUND_MIXER_LINE2,
3487 	    SOUND_MIXER_LINE3,
3488 	    SOUND_MIXER_DIGITAL1,
3489 	    SOUND_MIXER_DIGITAL2,
3490 	    SOUND_MIXER_DIGITAL3,
3491 	};
3492 	const uint16_t reserve_max =
3493 	    sizeof(reserve_feature) / sizeof(reserve_feature[0]);
3494 	uint16_t i;
3495 	uint16_t j;
3496 	uint16_t k;
3497 
3498 	/* remove existing selector types from the reserve */
3499 	for (i = 0; i < MIX(sc).maxval; i++) {
3500 		if (MIX(sc).slctrtype[i] == SOUND_MIXER_NRDEVICES)
3501 			continue;
3502 		for (j = 0; j != reserve_max; j++) {
3503 			if (reserve_feature[j] == MIX(sc).slctrtype[i])
3504 				reserve_feature[j] = SOUND_MIXER_NRDEVICES;
3505 		}
3506 	}
3507 
3508 	/* make sure selector types are not overlapping */
3509 	for (i = 0; i < MIX(sc).maxval; i++) {
3510 		if (MIX(sc).slctrtype[i] == SOUND_MIXER_NRDEVICES)
3511 			continue;
3512 		for (j = i + 1; j < MIX(sc).maxval; j++) {
3513 			if (MIX(sc).slctrtype[j] == SOUND_MIXER_NRDEVICES)
3514 				continue;
3515 			if (MIX(sc).slctrtype[i] != MIX(sc).slctrtype[j])
3516 				continue;
3517 			for (k = 0; k != reserve_max; k++) {
3518 				if (reserve_feature[k] == SOUND_MIXER_NRDEVICES)
3519 					continue;
3520 				MIX(sc).slctrtype[j] = reserve_feature[k];
3521 				reserve_feature[k] = SOUND_MIXER_NRDEVICES;
3522 				break;
3523 			}
3524 			if (k == reserve_max) {
3525 				DPRINTF("Selector type %d is not selectable!\n", j);
3526 				MIX(sc).slctrtype[j] = SOUND_MIXER_NRDEVICES;
3527 			}
3528 		}
3529 	}
3530 }
3531 
3532 static void
uaudio_mixer_add_selector(struct uaudio_softc * sc,const struct uaudio_terminal_node * iot,int id)3533 uaudio_mixer_add_selector(struct uaudio_softc *sc,
3534     const struct uaudio_terminal_node *iot, int id)
3535 {
3536 	const struct usb_audio_selector_unit *d = iot[id].u.su_v1;
3537 	uint16_t i;
3538 
3539 	DPRINTFN(3, "bUnitId=%d bNrInPins=%d\n",
3540 	    d->bUnitId, d->bNrInPins);
3541 
3542 	if (d->bNrInPins == 0)
3543 		return;
3544 
3545 	memset(&MIX(sc), 0, sizeof(MIX(sc)));
3546 
3547 	MIX(sc).wIndex = MAKE_WORD(d->bUnitId, sc->sc_mixer_iface_no);
3548 	MIX(sc).wValue[0] = MAKE_WORD(0, 0);
3549 	MIX(sc).nchan = 1;
3550 	MIX(sc).type = MIX_SELECTOR;
3551 	MIX(sc).ctl = SOUND_MIXER_NRDEVICES;
3552 	MIX(sc).minval = 1;
3553 	MIX(sc).maxval = d->bNrInPins;
3554 	MIX(sc).name = "selector";
3555 
3556 	i = d->baSourceId[d->bNrInPins];
3557 	if (i == 0 ||
3558 	    usbd_req_get_string_any(sc->sc_udev, NULL,
3559 	    MIX(sc).desc, sizeof(MIX(sc).desc), i) != 0) {
3560 		MIX(sc).desc[0] = 0;
3561 	}
3562 
3563 	if (MIX(sc).maxval > MAX_SELECTOR_INPUT_PIN)
3564 		MIX(sc).maxval = MAX_SELECTOR_INPUT_PIN;
3565 
3566 	MIX(sc).mul = MIX(sc).maxval - MIX(sc).minval;
3567 
3568 	for (i = 0; i < MIX(sc).maxval; i++) {
3569 		MIX(sc).slctrtype[i] =
3570 		    uaudio_mixer_determine_class(&iot[d->baSourceId[i]]);
3571 	}
3572 	for (; i < MAX_SELECTOR_INPUT_PIN; i++)
3573 		MIX(sc).slctrtype[i] = SOUND_MIXER_NRDEVICES;
3574 
3575 	uaudio_mixer_check_selectors(sc);
3576 	uaudio_mixer_add_ctl(sc, &MIX(sc));
3577 }
3578 
3579 static void
uaudio20_mixer_add_selector(struct uaudio_softc * sc,const struct uaudio_terminal_node * iot,int id)3580 uaudio20_mixer_add_selector(struct uaudio_softc *sc,
3581     const struct uaudio_terminal_node *iot, int id)
3582 {
3583 	const struct usb_audio20_selector_unit *d = iot[id].u.su_v2;
3584 	uint16_t i;
3585 
3586 	DPRINTFN(3, "bUnitId=%d bNrInPins=%d\n",
3587 	    d->bUnitId, d->bNrInPins);
3588 
3589 	if (d->bNrInPins == 0)
3590 		return;
3591 
3592 	memset(&MIX(sc), 0, sizeof(MIX(sc)));
3593 
3594 	MIX(sc).wIndex = MAKE_WORD(d->bUnitId, sc->sc_mixer_iface_no);
3595 	MIX(sc).wValue[0] = MAKE_WORD(0, 0);
3596 	MIX(sc).nchan = 1;
3597 	MIX(sc).type = MIX_SELECTOR;
3598 	MIX(sc).ctl = SOUND_MIXER_NRDEVICES;
3599 	MIX(sc).minval = 1;
3600 	MIX(sc).maxval = d->bNrInPins;
3601 	MIX(sc).name = "selector";
3602 
3603 	i = d->baSourceId[d->bNrInPins];
3604 	if (i == 0 ||
3605 	    usbd_req_get_string_any(sc->sc_udev, NULL,
3606 	    MIX(sc).desc, sizeof(MIX(sc).desc), i) != 0) {
3607 		MIX(sc).desc[0] = 0;
3608 	}
3609 
3610 	if (MIX(sc).maxval > MAX_SELECTOR_INPUT_PIN)
3611 		MIX(sc).maxval = MAX_SELECTOR_INPUT_PIN;
3612 
3613 	MIX(sc).mul = MIX(sc).maxval - MIX(sc).minval;
3614 
3615 	for (i = 0; i < MIX(sc).maxval; i++) {
3616 		MIX(sc).slctrtype[i] =
3617 		    uaudio20_mixer_determine_class(&iot[d->baSourceId[i]]);
3618 	}
3619 	for (; i < MAX_SELECTOR_INPUT_PIN; i++)
3620 		MIX(sc).slctrtype[i] = SOUND_MIXER_NRDEVICES;
3621 
3622 	uaudio_mixer_check_selectors(sc);
3623 	uaudio_mixer_add_ctl(sc, &MIX(sc));
3624 }
3625 
3626 static uint32_t
uaudio_mixer_feature_get_bmaControls(const struct usb_audio_feature_unit * d,uint8_t i)3627 uaudio_mixer_feature_get_bmaControls(const struct usb_audio_feature_unit *d,
3628     uint8_t i)
3629 {
3630 	uint32_t temp = 0;
3631 	uint32_t offset = (i * d->bControlSize);
3632 
3633 	if (d->bControlSize > 0) {
3634 		temp |= d->bmaControls[offset];
3635 		if (d->bControlSize > 1) {
3636 			temp |= d->bmaControls[offset + 1] << 8;
3637 			if (d->bControlSize > 2) {
3638 				temp |= d->bmaControls[offset + 2] << 16;
3639 				if (d->bControlSize > 3) {
3640 					temp |= d->bmaControls[offset + 3] << 24;
3641 				}
3642 			}
3643 		}
3644 	}
3645 	return (temp);
3646 }
3647 
3648 static void
uaudio_mixer_add_feature(struct uaudio_softc * sc,const struct uaudio_terminal_node * iot,int id)3649 uaudio_mixer_add_feature(struct uaudio_softc *sc,
3650     const struct uaudio_terminal_node *iot, int id)
3651 {
3652 	const struct usb_audio_feature_unit *d = iot[id].u.fu_v1;
3653 	uint32_t fumask;
3654 	uint32_t mmask;
3655 	uint32_t cmask;
3656 	uint16_t mixernumber;
3657 	uint8_t nchan;
3658 	uint8_t chan;
3659 	uint8_t ctl;
3660 	uint8_t i;
3661 
3662 	if (d->bControlSize == 0)
3663 		return;
3664 
3665 	memset(&MIX(sc), 0, sizeof(MIX(sc)));
3666 
3667 	nchan = (d->bLength - 7) / d->bControlSize;
3668 	mmask = uaudio_mixer_feature_get_bmaControls(d, 0);
3669 	cmask = 0;
3670 
3671 	if (nchan == 0)
3672 		return;
3673 
3674 	/* figure out what we can control */
3675 
3676 	for (chan = 1; chan < nchan; chan++) {
3677 		DPRINTFN(10, "chan=%d mask=%x\n",
3678 		    chan, uaudio_mixer_feature_get_bmaControls(d, chan));
3679 
3680 		cmask |= uaudio_mixer_feature_get_bmaControls(d, chan);
3681 	}
3682 
3683 	MIX(sc).wIndex = MAKE_WORD(d->bUnitId, sc->sc_mixer_iface_no);
3684 
3685 	i = d->bmaControls[nchan * d->bControlSize];
3686 	if (i == 0 ||
3687 	    usbd_req_get_string_any(sc->sc_udev, NULL,
3688 	    MIX(sc).desc, sizeof(MIX(sc).desc), i) != 0) {
3689 		MIX(sc).desc[0] = 0;
3690 	}
3691 
3692 	if (nchan > MIX_MAX_CHAN)
3693 		nchan = MIX_MAX_CHAN;
3694 
3695 	for (ctl = 1; ctl <= LOUDNESS_CONTROL; ctl++) {
3696 		fumask = FU_MASK(ctl);
3697 
3698 		DPRINTFN(5, "ctl=%d fumask=0x%04x\n",
3699 		    ctl, fumask);
3700 
3701 		if (mmask & fumask) {
3702 			MIX(sc).nchan = 1;
3703 			MIX(sc).wValue[0] = MAKE_WORD(ctl, 0);
3704 		} else if (cmask & fumask) {
3705 			MIX(sc).nchan = nchan - 1;
3706 			for (i = 1; i < nchan; i++) {
3707 				if (uaudio_mixer_feature_get_bmaControls(d, i) & fumask)
3708 					MIX(sc).wValue[i - 1] = MAKE_WORD(ctl, i);
3709 				else
3710 					MIX(sc).wValue[i - 1] = -1;
3711 			}
3712 		} else {
3713 			continue;
3714 		}
3715 
3716 		mixernumber = uaudio_mixer_determine_class(&iot[id]);
3717 
3718 		switch (ctl) {
3719 		case MUTE_CONTROL:
3720 			MIX(sc).type = MIX_ON_OFF;
3721 			MIX(sc).ctl = SOUND_MIXER_MUTE;
3722 			MIX(sc).name = "mute";
3723 			break;
3724 
3725 		case VOLUME_CONTROL:
3726 			MIX(sc).type = MIX_SIGNED_16;
3727 			MIX(sc).ctl = mixernumber;
3728 			MIX(sc).name = "vol";
3729 			break;
3730 
3731 		case BASS_CONTROL:
3732 			MIX(sc).type = MIX_SIGNED_8;
3733 			MIX(sc).ctl = SOUND_MIXER_BASS;
3734 			MIX(sc).name = "bass";
3735 			break;
3736 
3737 		case MID_CONTROL:
3738 			MIX(sc).type = MIX_SIGNED_8;
3739 			MIX(sc).ctl = SOUND_MIXER_NRDEVICES;	/* XXXXX */
3740 			MIX(sc).name = "mid";
3741 			break;
3742 
3743 		case TREBLE_CONTROL:
3744 			MIX(sc).type = MIX_SIGNED_8;
3745 			MIX(sc).ctl = SOUND_MIXER_TREBLE;
3746 			MIX(sc).name = "treble";
3747 			break;
3748 
3749 		case GRAPHIC_EQUALIZER_CONTROL:
3750 			continue;	/* XXX don't add anything */
3751 
3752 		case AGC_CONTROL:
3753 			MIX(sc).type = MIX_ON_OFF;
3754 			MIX(sc).ctl = SOUND_MIXER_NRDEVICES;	/* XXXXX */
3755 			MIX(sc).name = "agc";
3756 			break;
3757 
3758 		case DELAY_CONTROL:
3759 			MIX(sc).type = MIX_UNSIGNED_16;
3760 			MIX(sc).ctl = SOUND_MIXER_NRDEVICES;	/* XXXXX */
3761 			MIX(sc).name = "delay";
3762 			break;
3763 
3764 		case BASS_BOOST_CONTROL:
3765 			MIX(sc).type = MIX_ON_OFF;
3766 			MIX(sc).ctl = SOUND_MIXER_NRDEVICES;	/* XXXXX */
3767 			MIX(sc).name = "boost";
3768 			break;
3769 
3770 		case LOUDNESS_CONTROL:
3771 			MIX(sc).type = MIX_ON_OFF;
3772 			MIX(sc).ctl = SOUND_MIXER_LOUD;	/* Is this correct ? */
3773 			MIX(sc).name = "loudness";
3774 			break;
3775 
3776 		default:
3777 			MIX(sc).type = MIX_UNKNOWN;
3778 			break;
3779 		}
3780 
3781 		if (MIX(sc).type != MIX_UNKNOWN)
3782 			uaudio_mixer_add_ctl(sc, &MIX(sc));
3783 	}
3784 }
3785 
3786 static void
uaudio20_mixer_add_feature(struct uaudio_softc * sc,const struct uaudio_terminal_node * iot,int id)3787 uaudio20_mixer_add_feature(struct uaudio_softc *sc,
3788     const struct uaudio_terminal_node *iot, int id)
3789 {
3790 	const struct usb_audio20_feature_unit *d = iot[id].u.fu_v2;
3791 	uint32_t ctl;
3792 	uint32_t mmask;
3793 	uint32_t cmask;
3794 	uint16_t mixernumber;
3795 	uint8_t nchan;
3796 	uint8_t chan;
3797 	uint8_t i;
3798 	uint8_t what;
3799 
3800 	if (UGETDW(d->bmaControls[0]) == 0)
3801 		return;
3802 
3803 	memset(&MIX(sc), 0, sizeof(MIX(sc)));
3804 
3805 	nchan = (d->bLength - 6) / 4;
3806 	mmask = UGETDW(d->bmaControls[0]);
3807 	cmask = 0;
3808 
3809 	if (nchan == 0)
3810 		return;
3811 
3812 	/* figure out what we can control */
3813 
3814 	for (chan = 1; chan < nchan; chan++)
3815 		cmask |= UGETDW(d->bmaControls[chan]);
3816 
3817 	MIX(sc).wIndex = MAKE_WORD(d->bUnitId, sc->sc_mixer_iface_no);
3818 
3819 	i = d->bmaControls[nchan][0];
3820 	if (i == 0 ||
3821 	    usbd_req_get_string_any(sc->sc_udev, NULL,
3822 	    MIX(sc).desc, sizeof(MIX(sc).desc), i) != 0) {
3823 		MIX(sc).desc[0] = 0;
3824 	}
3825 
3826 	if (nchan > MIX_MAX_CHAN)
3827 		nchan = MIX_MAX_CHAN;
3828 
3829 	for (ctl = 3; ctl != 0; ctl <<= 2) {
3830 		mixernumber = uaudio20_mixer_determine_class(&iot[id]);
3831 
3832 		switch (ctl) {
3833 		case (3 << 0):
3834 			MIX(sc).type = MIX_ON_OFF;
3835 			MIX(sc).ctl = SOUND_MIXER_MUTE;
3836 			MIX(sc).name = "mute";
3837 			what = MUTE_CONTROL;
3838 			break;
3839 		case (3 << 2):
3840 			MIX(sc).type = MIX_SIGNED_16;
3841 			MIX(sc).ctl = mixernumber;
3842 			MIX(sc).name = "vol";
3843 			what = VOLUME_CONTROL;
3844 			break;
3845 		case (3 << 4):
3846 			MIX(sc).type = MIX_SIGNED_8;
3847 			MIX(sc).ctl = SOUND_MIXER_BASS;
3848 			MIX(sc).name = "bass";
3849 			what = BASS_CONTROL;
3850 			break;
3851 		case (3 << 6):
3852 			MIX(sc).type = MIX_SIGNED_8;
3853 			MIX(sc).ctl = SOUND_MIXER_NRDEVICES;	/* XXXXX */
3854 			MIX(sc).name = "mid";
3855 			what = MID_CONTROL;
3856 			break;
3857 		case (3 << 8):
3858 			MIX(sc).type = MIX_SIGNED_8;
3859 			MIX(sc).ctl = SOUND_MIXER_TREBLE;
3860 			MIX(sc).name = "treble";
3861 			what = TREBLE_CONTROL;
3862 			break;
3863 		case (3 << 12):
3864 			MIX(sc).type = MIX_ON_OFF;
3865 			MIX(sc).ctl = SOUND_MIXER_NRDEVICES;	/* XXXXX */
3866 			MIX(sc).name = "agc";
3867 			what = AGC_CONTROL;
3868 			break;
3869 		case (3 << 14):
3870 			MIX(sc).type = MIX_UNSIGNED_16;
3871 			MIX(sc).ctl = SOUND_MIXER_NRDEVICES;	/* XXXXX */
3872 			MIX(sc).name = "delay";
3873 			what = DELAY_CONTROL;
3874 			break;
3875 		case (3 << 16):
3876 			MIX(sc).type = MIX_ON_OFF;
3877 			MIX(sc).ctl = SOUND_MIXER_NRDEVICES;	/* XXXXX */
3878 			MIX(sc).name = "boost";
3879 			what = BASS_BOOST_CONTROL;
3880 			break;
3881 		case (3 << 18):
3882 			MIX(sc).type = MIX_ON_OFF;
3883 			MIX(sc).ctl = SOUND_MIXER_LOUD;	/* Is this correct ? */
3884 			MIX(sc).name = "loudness";
3885 			what = LOUDNESS_CONTROL;
3886 			break;
3887 		case (3 << 20):
3888 			MIX(sc).type = MIX_SIGNED_16;
3889 			MIX(sc).ctl = mixernumber;
3890 			MIX(sc).name = "igain";
3891 			what = INPUT_GAIN_CONTROL;
3892 			break;
3893 		case (3 << 22):
3894 			MIX(sc).type = MIX_SIGNED_16;
3895 			MIX(sc).ctl = mixernumber;
3896 			MIX(sc).name = "igainpad";
3897 			what = INPUT_GAIN_PAD_CONTROL;
3898 			break;
3899 		default:
3900 			continue;
3901 		}
3902 
3903 		if ((mmask & ctl) == ctl) {
3904 			MIX(sc).nchan = 1;
3905 			MIX(sc).wValue[0] = MAKE_WORD(what, 0);
3906 		} else if ((cmask & ctl) == ctl) {
3907 			MIX(sc).nchan = nchan - 1;
3908 			for (i = 1; i < nchan; i++) {
3909 				if ((UGETDW(d->bmaControls[i]) & ctl) == ctl)
3910 					MIX(sc).wValue[i - 1] = MAKE_WORD(what, i);
3911 				else
3912 					MIX(sc).wValue[i - 1] = -1;
3913 			}
3914 		} else {
3915 			continue;
3916 		}
3917 
3918 		if (MIX(sc).type != MIX_UNKNOWN)
3919 			uaudio_mixer_add_ctl(sc, &MIX(sc));
3920 	}
3921 }
3922 
3923 static void
uaudio_mixer_add_processing_updown(struct uaudio_softc * sc,const struct uaudio_terminal_node * iot,int id)3924 uaudio_mixer_add_processing_updown(struct uaudio_softc *sc,
3925     const struct uaudio_terminal_node *iot, int id)
3926 {
3927 	const struct usb_audio_processing_unit_0 *d0 = iot[id].u.pu_v1;
3928 	const struct usb_audio_processing_unit_1 *d1 =
3929 	    (const void *)(d0->baSourceId + d0->bNrInPins);
3930 	const struct usb_audio_processing_unit_updown *ud =
3931 	    (const void *)(d1->bmControls + d1->bControlSize);
3932 	uint8_t i;
3933 
3934 	if (uaudio_mixer_verify_desc(d0, sizeof(*ud)) == NULL) {
3935 		return;
3936 	}
3937 	if (uaudio_mixer_verify_desc(d0, sizeof(*ud) + (2 * ud->bNrModes))
3938 	    == NULL) {
3939 		return;
3940 	}
3941 	DPRINTFN(3, "bUnitId=%d bNrModes=%d\n",
3942 	    d0->bUnitId, ud->bNrModes);
3943 
3944 	if (!(d1->bmControls[0] & UA_PROC_MASK(UD_MODE_SELECT_CONTROL))) {
3945 		DPRINTF("no mode select\n");
3946 		return;
3947 	}
3948 	memset(&MIX(sc), 0, sizeof(MIX(sc)));
3949 
3950 	MIX(sc).wIndex = MAKE_WORD(d0->bUnitId, sc->sc_mixer_iface_no);
3951 	MIX(sc).nchan = 1;
3952 	MIX(sc).wValue[0] = MAKE_WORD(UD_MODE_SELECT_CONTROL, 0);
3953 	MIX(sc).type = MIX_ON_OFF;		/* XXX */
3954 
3955 	for (i = 0; i < ud->bNrModes; i++) {
3956 		DPRINTFN(3, "i=%d bm=0x%x\n", i, UGETW(ud->waModes[i]));
3957 		/* XXX */
3958 	}
3959 
3960 	uaudio_mixer_add_ctl(sc, &MIX(sc));
3961 }
3962 
3963 static void
uaudio_mixer_add_processing(struct uaudio_softc * sc,const struct uaudio_terminal_node * iot,int id)3964 uaudio_mixer_add_processing(struct uaudio_softc *sc,
3965     const struct uaudio_terminal_node *iot, int id)
3966 {
3967 	const struct usb_audio_processing_unit_0 *d0 = iot[id].u.pu_v1;
3968 	const struct usb_audio_processing_unit_1 *d1 =
3969 	    (const void *)(d0->baSourceId + d0->bNrInPins);
3970 	uint16_t ptype;
3971 
3972 	memset(&MIX(sc), 0, sizeof(MIX(sc)));
3973 
3974 	ptype = UGETW(d0->wProcessType);
3975 
3976 	DPRINTFN(3, "wProcessType=%d bUnitId=%d "
3977 	    "bNrInPins=%d\n", ptype, d0->bUnitId, d0->bNrInPins);
3978 
3979 	if (d1->bControlSize == 0) {
3980 		return;
3981 	}
3982 	if (d1->bmControls[0] & UA_PROC_ENABLE_MASK) {
3983 		MIX(sc).wIndex = MAKE_WORD(d0->bUnitId, sc->sc_mixer_iface_no);
3984 		MIX(sc).nchan = 1;
3985 		MIX(sc).wValue[0] = MAKE_WORD(XX_ENABLE_CONTROL, 0);
3986 		MIX(sc).type = MIX_ON_OFF;
3987 		uaudio_mixer_add_ctl(sc, &MIX(sc));
3988 	}
3989 	switch (ptype) {
3990 	case UPDOWNMIX_PROCESS:
3991 		uaudio_mixer_add_processing_updown(sc, iot, id);
3992 		break;
3993 
3994 	case DOLBY_PROLOGIC_PROCESS:
3995 	case P3D_STEREO_EXTENDER_PROCESS:
3996 	case REVERBATION_PROCESS:
3997 	case CHORUS_PROCESS:
3998 	case DYN_RANGE_COMP_PROCESS:
3999 	default:
4000 		DPRINTF("unit %d, type=%d is not implemented\n",
4001 		    d0->bUnitId, ptype);
4002 		break;
4003 	}
4004 }
4005 
4006 static void
uaudio_mixer_add_extension(struct uaudio_softc * sc,const struct uaudio_terminal_node * iot,int id)4007 uaudio_mixer_add_extension(struct uaudio_softc *sc,
4008     const struct uaudio_terminal_node *iot, int id)
4009 {
4010 	const struct usb_audio_extension_unit_0 *d0 = iot[id].u.eu_v1;
4011 	const struct usb_audio_extension_unit_1 *d1 =
4012 	    (const void *)(d0->baSourceId + d0->bNrInPins);
4013 
4014 	DPRINTFN(3, "bUnitId=%d bNrInPins=%d\n",
4015 	    d0->bUnitId, d0->bNrInPins);
4016 
4017 	if (sc->sc_uq_au_no_xu) {
4018 		return;
4019 	}
4020 	if (d1->bControlSize == 0) {
4021 		return;
4022 	}
4023 	if (d1->bmControls[0] & UA_EXT_ENABLE_MASK) {
4024 		memset(&MIX(sc), 0, sizeof(MIX(sc)));
4025 
4026 		MIX(sc).wIndex = MAKE_WORD(d0->bUnitId, sc->sc_mixer_iface_no);
4027 		MIX(sc).nchan = 1;
4028 		MIX(sc).wValue[0] = MAKE_WORD(UA_EXT_ENABLE, 0);
4029 		MIX(sc).type = MIX_ON_OFF;
4030 
4031 		uaudio_mixer_add_ctl(sc, &MIX(sc));
4032 	}
4033 }
4034 
4035 static const void *
uaudio_mixer_verify_desc(const void * arg,uint32_t len)4036 uaudio_mixer_verify_desc(const void *arg, uint32_t len)
4037 {
4038 	const struct usb_audio_mixer_unit_1 *d1;
4039 	const struct usb_audio_extension_unit_1 *e1;
4040 	const struct usb_audio_processing_unit_1 *u1;
4041 
4042 	union {
4043 		const struct usb_descriptor *desc;
4044 		const struct usb_audio_input_terminal *it;
4045 		const struct usb_audio_output_terminal *ot;
4046 		const struct usb_audio_mixer_unit_0 *mu;
4047 		const struct usb_audio_selector_unit *su;
4048 		const struct usb_audio_feature_unit *fu;
4049 		const struct usb_audio_processing_unit_0 *pu;
4050 		const struct usb_audio_extension_unit_0 *eu;
4051 	}     u;
4052 
4053 	u.desc = arg;
4054 
4055 	if (u.desc == NULL) {
4056 		goto error;
4057 	}
4058 	if (u.desc->bDescriptorType != UDESC_CS_INTERFACE) {
4059 		goto error;
4060 	}
4061 	switch (u.desc->bDescriptorSubtype) {
4062 	case UDESCSUB_AC_INPUT:
4063 		len += sizeof(*u.it);
4064 		break;
4065 
4066 	case UDESCSUB_AC_OUTPUT:
4067 		len += sizeof(*u.ot);
4068 		break;
4069 
4070 	case UDESCSUB_AC_MIXER:
4071 		len += sizeof(*u.mu);
4072 
4073 		if (u.desc->bLength < len) {
4074 			goto error;
4075 		}
4076 		len += u.mu->bNrInPins;
4077 
4078 		if (u.desc->bLength < len) {
4079 			goto error;
4080 		}
4081 		d1 = (const void *)(u.mu->baSourceId + u.mu->bNrInPins);
4082 
4083 		len += sizeof(*d1);
4084 		break;
4085 
4086 	case UDESCSUB_AC_SELECTOR:
4087 		len += sizeof(*u.su);
4088 
4089 		if (u.desc->bLength < len) {
4090 			goto error;
4091 		}
4092 		len += u.su->bNrInPins + 1;
4093 		break;
4094 
4095 	case UDESCSUB_AC_FEATURE:
4096 		len += sizeof(*u.fu) + 1;
4097 
4098 		if (u.desc->bLength < len)
4099 			goto error;
4100 
4101 		len += u.fu->bControlSize;
4102 		break;
4103 
4104 	case UDESCSUB_AC_PROCESSING:
4105 		len += sizeof(*u.pu);
4106 
4107 		if (u.desc->bLength < len) {
4108 			goto error;
4109 		}
4110 		len += u.pu->bNrInPins;
4111 
4112 		if (u.desc->bLength < len) {
4113 			goto error;
4114 		}
4115 		u1 = (const void *)(u.pu->baSourceId + u.pu->bNrInPins);
4116 
4117 		len += sizeof(*u1);
4118 
4119 		if (u.desc->bLength < len) {
4120 			goto error;
4121 		}
4122 		len += u1->bControlSize;
4123 
4124 		break;
4125 
4126 	case UDESCSUB_AC_EXTENSION:
4127 		len += sizeof(*u.eu);
4128 
4129 		if (u.desc->bLength < len) {
4130 			goto error;
4131 		}
4132 		len += u.eu->bNrInPins;
4133 
4134 		if (u.desc->bLength < len) {
4135 			goto error;
4136 		}
4137 		e1 = (const void *)(u.eu->baSourceId + u.eu->bNrInPins);
4138 
4139 		len += sizeof(*e1);
4140 
4141 		if (u.desc->bLength < len) {
4142 			goto error;
4143 		}
4144 		len += e1->bControlSize;
4145 		break;
4146 
4147 	default:
4148 		goto error;
4149 	}
4150 
4151 	if (u.desc->bLength < len) {
4152 		goto error;
4153 	}
4154 	return (u.desc);
4155 
4156 error:
4157 	if (u.desc) {
4158 		DPRINTF("invalid descriptor, type=%d, "
4159 		    "sub_type=%d, len=%d of %d bytes\n",
4160 		    u.desc->bDescriptorType,
4161 		    u.desc->bDescriptorSubtype,
4162 		    u.desc->bLength, len);
4163 	}
4164 	return (NULL);
4165 }
4166 
4167 static const void *
uaudio20_mixer_verify_desc(const void * arg,uint32_t len)4168 uaudio20_mixer_verify_desc(const void *arg, uint32_t len)
4169 {
4170 	const struct usb_audio20_mixer_unit_1 *d1;
4171 	const struct usb_audio20_extension_unit_1 *e1;
4172 	const struct usb_audio20_processing_unit_1 *u1;
4173 	const struct usb_audio20_clock_selector_unit_1 *c1;
4174 
4175 	union {
4176 		const struct usb_descriptor *desc;
4177 		const struct usb_audio20_clock_source_unit *csrc;
4178 		const struct usb_audio20_clock_selector_unit_0 *csel;
4179 		const struct usb_audio20_clock_multiplier_unit *cmul;
4180 		const struct usb_audio20_input_terminal *it;
4181 		const struct usb_audio20_output_terminal *ot;
4182 		const struct usb_audio20_mixer_unit_0 *mu;
4183 		const struct usb_audio20_selector_unit *su;
4184 		const struct usb_audio20_feature_unit *fu;
4185 		const struct usb_audio20_sample_rate_unit *ru;
4186 		const struct usb_audio20_processing_unit_0 *pu;
4187 		const struct usb_audio20_extension_unit_0 *eu;
4188 		const struct usb_audio20_effect_unit *ef;
4189 	}     u;
4190 
4191 	u.desc = arg;
4192 
4193 	if (u.desc == NULL)
4194 		goto error;
4195 
4196 	if (u.desc->bDescriptorType != UDESC_CS_INTERFACE)
4197 		goto error;
4198 
4199 	switch (u.desc->bDescriptorSubtype) {
4200 	case UDESCSUB_AC_INPUT:
4201 		len += sizeof(*u.it);
4202 		break;
4203 
4204 	case UDESCSUB_AC_OUTPUT:
4205 		len += sizeof(*u.ot);
4206 		break;
4207 
4208 	case UDESCSUB_AC_MIXER:
4209 		len += sizeof(*u.mu);
4210 
4211 		if (u.desc->bLength < len)
4212 			goto error;
4213 		len += u.mu->bNrInPins;
4214 
4215 		if (u.desc->bLength < len)
4216 			goto error;
4217 
4218 		d1 = (const void *)(u.mu->baSourceId + u.mu->bNrInPins);
4219 
4220 		len += sizeof(*d1) + d1->bNrChannels;
4221 		break;
4222 
4223 	case UDESCSUB_AC_SELECTOR:
4224 		len += sizeof(*u.su);
4225 
4226 		if (u.desc->bLength < len)
4227 			goto error;
4228 
4229 		len += u.su->bNrInPins + 1;
4230 		break;
4231 
4232 	case UDESCSUB_AC_FEATURE:
4233 		len += sizeof(*u.fu) + 1;
4234 		break;
4235 
4236 	case UDESCSUB_AC_EFFECT:
4237 		len += sizeof(*u.ef) + 4;
4238 		break;
4239 
4240 	case UDESCSUB_AC_PROCESSING_V2:
4241 		len += sizeof(*u.pu);
4242 
4243 		if (u.desc->bLength < len)
4244 			goto error;
4245 
4246 		len += u.pu->bNrInPins;
4247 
4248 		if (u.desc->bLength < len)
4249 			goto error;
4250 
4251 		u1 = (const void *)(u.pu->baSourceId + u.pu->bNrInPins);
4252 
4253 		len += sizeof(*u1);
4254 		break;
4255 
4256 	case UDESCSUB_AC_EXTENSION_V2:
4257 		len += sizeof(*u.eu);
4258 
4259 		if (u.desc->bLength < len)
4260 			goto error;
4261 
4262 		len += u.eu->bNrInPins;
4263 
4264 		if (u.desc->bLength < len)
4265 			goto error;
4266 
4267 		e1 = (const void *)(u.eu->baSourceId + u.eu->bNrInPins);
4268 
4269 		len += sizeof(*e1);
4270 		break;
4271 
4272 	case UDESCSUB_AC_CLOCK_SRC:
4273 		len += sizeof(*u.csrc);
4274 		break;
4275 
4276 	case UDESCSUB_AC_CLOCK_SEL:
4277 		len += sizeof(*u.csel);
4278 
4279 		if (u.desc->bLength < len)
4280 			goto error;
4281 
4282 		len += u.csel->bNrInPins;
4283 
4284 		if (u.desc->bLength < len)
4285 			goto error;
4286 
4287 		c1 = (const void *)(u.csel->baCSourceId + u.csel->bNrInPins);
4288 
4289 		len += sizeof(*c1);
4290 		break;
4291 
4292 	case UDESCSUB_AC_CLOCK_MUL:
4293 		len += sizeof(*u.cmul);
4294 		break;
4295 
4296 	case UDESCSUB_AC_SAMPLE_RT:
4297 		len += sizeof(*u.ru);
4298 		break;
4299 
4300 	default:
4301 		goto error;
4302 	}
4303 
4304 	if (u.desc->bLength < len)
4305 		goto error;
4306 
4307 	return (u.desc);
4308 
4309 error:
4310 	if (u.desc) {
4311 		DPRINTF("invalid descriptor, type=%d, "
4312 		    "sub_type=%d, len=%d of %d bytes\n",
4313 		    u.desc->bDescriptorType,
4314 		    u.desc->bDescriptorSubtype,
4315 		    u.desc->bLength, len);
4316 	}
4317 	return (NULL);
4318 }
4319 
4320 static struct usb_audio_cluster
uaudio_mixer_get_cluster(uint8_t id,const struct uaudio_terminal_node * iot)4321 uaudio_mixer_get_cluster(uint8_t id, const struct uaudio_terminal_node *iot)
4322 {
4323 	struct usb_audio_cluster r;
4324 	const struct usb_descriptor *dp;
4325 	uint8_t i;
4326 
4327 	for (i = 0; i < UAUDIO_RECURSE_LIMIT; i++) {	/* avoid infinite loops */
4328 		dp = iot[id].u.desc;
4329 		if (dp == NULL) {
4330 			goto error;
4331 		}
4332 		switch (dp->bDescriptorSubtype) {
4333 		case UDESCSUB_AC_INPUT:
4334 			r.bNrChannels = iot[id].u.it_v1->bNrChannels;
4335 			r.wChannelConfig[0] = iot[id].u.it_v1->wChannelConfig[0];
4336 			r.wChannelConfig[1] = iot[id].u.it_v1->wChannelConfig[1];
4337 			r.iChannelNames = iot[id].u.it_v1->iChannelNames;
4338 			goto done;
4339 
4340 		case UDESCSUB_AC_OUTPUT:
4341 			id = iot[id].u.ot_v1->bSourceId;
4342 			break;
4343 
4344 		case UDESCSUB_AC_MIXER:
4345 			r = *(const struct usb_audio_cluster *)
4346 			    &iot[id].u.mu_v1->baSourceId[
4347 			    iot[id].u.mu_v1->bNrInPins];
4348 			goto done;
4349 
4350 		case UDESCSUB_AC_SELECTOR:
4351 			if (iot[id].u.su_v1->bNrInPins > 0) {
4352 				/* XXX This is not really right */
4353 				id = iot[id].u.su_v1->baSourceId[0];
4354 			}
4355 			break;
4356 
4357 		case UDESCSUB_AC_FEATURE:
4358 			id = iot[id].u.fu_v1->bSourceId;
4359 			break;
4360 
4361 		case UDESCSUB_AC_PROCESSING:
4362 			r = *((const struct usb_audio_cluster *)
4363 			    &iot[id].u.pu_v1->baSourceId[
4364 			    iot[id].u.pu_v1->bNrInPins]);
4365 			goto done;
4366 
4367 		case UDESCSUB_AC_EXTENSION:
4368 			r = *((const struct usb_audio_cluster *)
4369 			    &iot[id].u.eu_v1->baSourceId[
4370 			    iot[id].u.eu_v1->bNrInPins]);
4371 			goto done;
4372 
4373 		default:
4374 			goto error;
4375 		}
4376 	}
4377 error:
4378 	DPRINTF("bad data\n");
4379 	memset(&r, 0, sizeof(r));
4380 done:
4381 	return (r);
4382 }
4383 
4384 static struct usb_audio20_cluster
uaudio20_mixer_get_cluster(uint8_t id,const struct uaudio_terminal_node * iot)4385 uaudio20_mixer_get_cluster(uint8_t id, const struct uaudio_terminal_node *iot)
4386 {
4387 	struct usb_audio20_cluster r;
4388 	const struct usb_descriptor *dp;
4389 	uint8_t i;
4390 
4391 	for (i = 0; i < UAUDIO_RECURSE_LIMIT; i++) {	/* avoid infinite loops */
4392 		dp = iot[id].u.desc;
4393 		if (dp == NULL)
4394 			goto error;
4395 
4396 		switch (dp->bDescriptorSubtype) {
4397 		case UDESCSUB_AC_INPUT:
4398 			r.bNrChannels = iot[id].u.it_v2->bNrChannels;
4399 			r.bmChannelConfig[0] = iot[id].u.it_v2->bmChannelConfig[0];
4400 			r.bmChannelConfig[1] = iot[id].u.it_v2->bmChannelConfig[1];
4401 			r.bmChannelConfig[2] = iot[id].u.it_v2->bmChannelConfig[2];
4402 			r.bmChannelConfig[3] = iot[id].u.it_v2->bmChannelConfig[3];
4403 			r.iChannelNames = iot[id].u.it_v2->iTerminal;
4404 			goto done;
4405 
4406 		case UDESCSUB_AC_OUTPUT:
4407 			id = iot[id].u.ot_v2->bSourceId;
4408 			break;
4409 
4410 		case UDESCSUB_AC_MIXER:
4411 			r = *(const struct usb_audio20_cluster *)
4412 			    &iot[id].u.mu_v2->baSourceId[
4413 			    iot[id].u.mu_v2->bNrInPins];
4414 			goto done;
4415 
4416 		case UDESCSUB_AC_SELECTOR:
4417 			if (iot[id].u.su_v2->bNrInPins > 0) {
4418 				/* XXX This is not really right */
4419 				id = iot[id].u.su_v2->baSourceId[0];
4420 			}
4421 			break;
4422 
4423 		case UDESCSUB_AC_SAMPLE_RT:
4424 			id = iot[id].u.ru_v2->bSourceId;
4425 			break;
4426 
4427 		case UDESCSUB_AC_EFFECT:
4428 			id = iot[id].u.ef_v2->bSourceId;
4429 			break;
4430 
4431 		case UDESCSUB_AC_FEATURE:
4432 			id = iot[id].u.fu_v2->bSourceId;
4433 			break;
4434 
4435 		case UDESCSUB_AC_PROCESSING_V2:
4436 			r = *((const struct usb_audio20_cluster *)
4437 			    &iot[id].u.pu_v2->baSourceId[
4438 			    iot[id].u.pu_v2->bNrInPins]);
4439 			goto done;
4440 
4441 		case UDESCSUB_AC_EXTENSION_V2:
4442 			r = *((const struct usb_audio20_cluster *)
4443 			    &iot[id].u.eu_v2->baSourceId[
4444 			    iot[id].u.eu_v2->bNrInPins]);
4445 			goto done;
4446 
4447 		default:
4448 			goto error;
4449 		}
4450 	}
4451 error:
4452 	DPRINTF("Bad data!\n");
4453 	memset(&r, 0, sizeof(r));
4454 done:
4455 	return (r);
4456 }
4457 
4458 static bool
uaudio_mixer_foreach_input(const struct uaudio_terminal_node * iot,uint8_t * pindex)4459 uaudio_mixer_foreach_input(const struct uaudio_terminal_node *iot, uint8_t *pindex)
4460 {
4461 	uint8_t n;
4462 
4463 	n = *pindex;
4464 
4465 	while (1) {
4466 		if (!n--)
4467 			n = iot->usr.id_max;
4468 		if (n == 0)
4469 			return (false);
4470 		if (iot->usr.bit_input[n / 8] & (1 << (n % 8)))
4471 			break;
4472 	}
4473 	*pindex = n;
4474 	return (true);
4475 }
4476 
4477 static bool
uaudio_mixer_foreach_output(const struct uaudio_terminal_node * iot,uint8_t * pindex)4478 uaudio_mixer_foreach_output(const struct uaudio_terminal_node *iot, uint8_t *pindex)
4479 {
4480 	uint8_t n;
4481 
4482 	n = *pindex;
4483 
4484 	while (1) {
4485 		if (!n--)
4486 			n = iot->usr.id_max;
4487 		if (n == 0)
4488 			return (false);
4489 		if (iot->usr.bit_output[n / 8] & (1 << (n % 8)))
4490 			break;
4491 	}
4492 	*pindex = n;
4493 	return (true);
4494 }
4495 
4496 struct uaudio_tt_to_feature {
4497 	uint16_t terminal_type;
4498 	uint16_t feature;
4499 };
4500 
4501 static const struct uaudio_tt_to_feature uaudio_tt_to_feature[] = {
4502 	{UATI_MICROPHONE, SOUND_MIXER_MIC},
4503 	{UATI_DESKMICROPHONE, SOUND_MIXER_MIC},
4504 	{UATI_PERSONALMICROPHONE, SOUND_MIXER_MIC},
4505 	{UATI_OMNIMICROPHONE, SOUND_MIXER_MIC},
4506 	{UATI_MICROPHONEARRAY, SOUND_MIXER_MIC},
4507 	{UATI_PROCMICROPHONEARR, SOUND_MIXER_MIC},
4508 
4509 	{UATE_ANALOGCONN, SOUND_MIXER_LINE},
4510 	{UATE_LINECONN, SOUND_MIXER_LINE},
4511 	{UATE_LEGACYCONN, SOUND_MIXER_LINE},
4512 
4513 	{UATE_DIGITALAUIFC, SOUND_MIXER_ALTPCM},
4514 	{UATE_SPDIF, SOUND_MIXER_ALTPCM},
4515 	{UATE_1394DA, SOUND_MIXER_ALTPCM},
4516 	{UATE_1394DV, SOUND_MIXER_ALTPCM},
4517 
4518 	{UATF_CDPLAYER, SOUND_MIXER_CD},
4519 
4520 	{UATF_SYNTHESIZER, SOUND_MIXER_SYNTH},
4521 
4522 	{UATF_VIDEODISCAUDIO, SOUND_MIXER_VIDEO},
4523 	{UATF_DVDAUDIO, SOUND_MIXER_VIDEO},
4524 	{UATF_TVTUNERAUDIO, SOUND_MIXER_VIDEO},
4525 
4526 	{UATF_RADIORECV, SOUND_MIXER_RADIO},
4527 	{UATF_RADIOXMIT, SOUND_MIXER_RADIO},
4528 
4529 	{}	/* END */
4530 };
4531 
4532 static uint16_t
uaudio_mixer_get_feature_by_tt(uint16_t terminal_type,uint16_t default_type)4533 uaudio_mixer_get_feature_by_tt(uint16_t terminal_type, uint16_t default_type)
4534 {
4535 	const struct uaudio_tt_to_feature *uat = uaudio_tt_to_feature;
4536 	uint16_t retval;
4537 
4538 	if (terminal_type == 0) {
4539 		retval = default_type;
4540 	} else while (1) {
4541 		if (uat->terminal_type == 0) {
4542 			switch (terminal_type >> 8) {
4543 			case UATI_UNDEFINED >> 8:
4544 				retval = SOUND_MIXER_RECLEV;
4545 				goto done;
4546 			case UATO_UNDEFINED >> 8:
4547 				retval = SOUND_MIXER_PCM;
4548 				goto done;
4549 			case UATT_UNDEFINED >> 8:
4550 				retval = SOUND_MIXER_PHONEIN;
4551 				goto done;
4552 			default:
4553 				retval = default_type;
4554 				goto done;
4555 			}
4556 		} else if (uat->terminal_type == terminal_type) {
4557 			retval = uat->feature;
4558 			goto done;
4559 		}
4560 		uat++;
4561 	}
4562 done:
4563 	DPRINTF("terminal_type=0x%04x RET=%d DEF=%d\n",
4564 	    terminal_type, retval, default_type);
4565 	return (retval);
4566 }
4567 
4568 static uint16_t
uaudio_mixer_determine_class(const struct uaudio_terminal_node * iot)4569 uaudio_mixer_determine_class(const struct uaudio_terminal_node *iot)
4570 {
4571 	const struct uaudio_terminal_node *ptr;
4572 	uint16_t terminal_type_input = 0;
4573 	uint16_t terminal_type_output = 0;
4574 	uint16_t temp;
4575 	uint8_t match = 0;
4576 	uint8_t i;
4577 
4578 	for (i = 0; uaudio_mixer_foreach_input(iot, &i); ) {
4579 		ptr = iot->root + i;
4580 		temp = UGETW(ptr->u.it_v1->wTerminalType);
4581 
4582 		if (temp == 0)
4583 			continue;
4584 		else if (temp == UAT_STREAM)
4585 			match |= 1;
4586 		else if ((temp & 0xFF00) != (UAT_UNDEFINED & 0xff00))
4587 			terminal_type_input = temp;
4588 	}
4589 
4590 	for (i = 0; uaudio_mixer_foreach_output(iot, &i); ) {
4591 		ptr = iot->root + i;
4592 		temp = UGETW(ptr->u.ot_v1->wTerminalType);
4593 
4594 		if (temp == 0)
4595 			continue;
4596 		else if (temp == UAT_STREAM)
4597 			match |= 2;
4598 		else if ((temp & 0xFF00) != (UAT_UNDEFINED & 0xff00))
4599 			terminal_type_output = temp;
4600 	}
4601 
4602 	DPRINTF("MATCH=%d IN=0x%04x OUT=0x%04x\n",
4603 	    match, terminal_type_input, terminal_type_output);
4604 
4605 	switch (match) {
4606 	case 0:	/* not connected to USB */
4607 		if (terminal_type_output != 0) {
4608 			return (uaudio_mixer_get_feature_by_tt(
4609 			    terminal_type_output, SOUND_MIXER_MONITOR));
4610 		} else {
4611 			return (uaudio_mixer_get_feature_by_tt(
4612 			    terminal_type_input, SOUND_MIXER_MONITOR));
4613 		}
4614 	case 3:	/* connected to both USB input and USB output */
4615 		return (SOUND_MIXER_IMIX);
4616 	case 2:	/* connected to USB output */
4617 		return (uaudio_mixer_get_feature_by_tt(
4618 		    terminal_type_input, SOUND_MIXER_RECLEV));
4619 	case 1: /* connected to USB input */
4620 		return (uaudio_mixer_get_feature_by_tt(
4621 		    terminal_type_output, SOUND_MIXER_PCM));
4622 	default:
4623 		return (SOUND_MIXER_NRDEVICES);
4624 	}
4625 }
4626 
4627 static uint16_t
uaudio20_mixer_determine_class(const struct uaudio_terminal_node * iot)4628 uaudio20_mixer_determine_class(const struct uaudio_terminal_node *iot)
4629 {
4630 	const struct uaudio_terminal_node *ptr;
4631 	uint16_t terminal_type_input = 0;
4632 	uint16_t terminal_type_output = 0;
4633 	uint16_t temp;
4634 	uint8_t match = 0;
4635 	uint8_t i;
4636 
4637 	for (i = 0; uaudio_mixer_foreach_input(iot, &i); ) {
4638 		ptr = iot->root + i;
4639 		temp = UGETW(ptr->u.it_v2->wTerminalType);
4640 
4641 		if (temp == 0)
4642 			continue;
4643 		else if (temp == UAT_STREAM)
4644 			match |= 1;
4645 		else if ((temp & 0xFF00) != (UAT_UNDEFINED & 0xff00))
4646 			terminal_type_input = temp;
4647 	}
4648 
4649 	for (i = 0; uaudio_mixer_foreach_output(iot, &i); ) {
4650 		ptr = iot->root + i;
4651 		temp = UGETW(ptr->u.ot_v2->wTerminalType);
4652 
4653 		if (temp == 0)
4654 			continue;
4655 		else if (temp == UAT_STREAM)
4656 			match |= 2;
4657 		else if ((temp & 0xFF00) != (UAT_UNDEFINED & 0xff00))
4658 			terminal_type_output = temp;
4659 	}
4660 
4661 	DPRINTF("MATCH=%d IN=0x%04x OUT=0x%04x\n",
4662 	    match, terminal_type_input, terminal_type_output);
4663 
4664 	switch (match) {
4665 	case 0:	/* not connected to USB */
4666 		if (terminal_type_output != 0) {
4667 			return (uaudio_mixer_get_feature_by_tt(
4668 			    terminal_type_output, SOUND_MIXER_MONITOR));
4669 		} else {
4670 			return (uaudio_mixer_get_feature_by_tt(
4671 			    terminal_type_input, SOUND_MIXER_MONITOR));
4672 		}
4673 	case 3:	/* connected to both USB input and USB output */
4674 		return (SOUND_MIXER_IMIX);
4675 	case 2:	/* connected to USB output */
4676 		return (uaudio_mixer_get_feature_by_tt(
4677 		    terminal_type_input, SOUND_MIXER_RECLEV));
4678 	case 1: /* connected to USB input */
4679 		return (uaudio_mixer_get_feature_by_tt(
4680 		    terminal_type_output, SOUND_MIXER_PCM));
4681 	default:
4682 		return (SOUND_MIXER_NRDEVICES);
4683 	}
4684 }
4685 
4686 static void
uaudio_mixer_merge_outputs(struct uaudio_search_result * dst,const struct uaudio_search_result * src)4687 uaudio_mixer_merge_outputs(struct uaudio_search_result *dst,
4688     const struct uaudio_search_result *src)
4689 {
4690 	const uint8_t max = sizeof(src->bit_output) / sizeof(src->bit_output[0]);
4691 	uint8_t x;
4692 
4693 	for (x = 0; x != max; x++)
4694 		dst->bit_output[x] |= src->bit_output[x];
4695 }
4696 
4697 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)4698 uaudio_mixer_find_inputs_sub(struct uaudio_terminal_node *root,
4699     const uint8_t *p_id, uint8_t n_id,
4700     struct uaudio_search_result *info)
4701 {
4702 	struct uaudio_terminal_node *iot;
4703 	uint8_t n;
4704 	uint8_t i;
4705 
4706 	for (n = 0; n < n_id; n++) {
4707 		i = p_id[n];
4708 
4709 		if (info->recurse_level == UAUDIO_RECURSE_LIMIT) {
4710 			DPRINTF("avoided going into a circle at id=%d!\n", i);
4711 			return;
4712 		}
4713 
4714 		info->recurse_level++;
4715 
4716 		iot = (root + i);
4717 
4718 		if (iot->u.desc == NULL)
4719 			continue;
4720 
4721 		switch (iot->u.desc->bDescriptorSubtype) {
4722 		case UDESCSUB_AC_INPUT:
4723 			uaudio_mixer_merge_outputs(&iot->usr, info);
4724 			info->bit_input[i / 8] |= (1 << (i % 8));
4725 			break;
4726 
4727 		case UDESCSUB_AC_FEATURE:
4728 			uaudio_mixer_merge_outputs(&iot->usr, info);
4729 			uaudio_mixer_find_inputs_sub(
4730 			    root, &iot->u.fu_v1->bSourceId, 1, info);
4731 			break;
4732 
4733 		case UDESCSUB_AC_OUTPUT:
4734 			info->bit_output[i / 8] |= (1 << (i % 8));
4735 			uaudio_mixer_find_inputs_sub(
4736 			    root, &iot->u.ot_v1->bSourceId, 1, info);
4737 			info->bit_output[i / 8] &= ~(1 << (i % 8));
4738 			break;
4739 
4740 		case UDESCSUB_AC_MIXER:
4741 			uaudio_mixer_merge_outputs(&iot->usr, info);
4742 			uaudio_mixer_find_inputs_sub(
4743 			    root, iot->u.mu_v1->baSourceId,
4744 			    iot->u.mu_v1->bNrInPins, info);
4745 			break;
4746 
4747 		case UDESCSUB_AC_SELECTOR:
4748 			uaudio_mixer_merge_outputs(&iot->usr, info);
4749 			uaudio_mixer_find_inputs_sub(
4750 			    root, iot->u.su_v1->baSourceId,
4751 			    iot->u.su_v1->bNrInPins, info);
4752 			break;
4753 
4754 		case UDESCSUB_AC_PROCESSING:
4755 			uaudio_mixer_merge_outputs(&iot->usr, info);
4756 			uaudio_mixer_find_inputs_sub(
4757 			    root, iot->u.pu_v1->baSourceId,
4758 			    iot->u.pu_v1->bNrInPins, info);
4759 			break;
4760 
4761 		case UDESCSUB_AC_EXTENSION:
4762 			uaudio_mixer_merge_outputs(&iot->usr, info);
4763 			uaudio_mixer_find_inputs_sub(
4764 			    root, iot->u.eu_v1->baSourceId,
4765 			    iot->u.eu_v1->bNrInPins, info);
4766 			break;
4767 
4768 		default:
4769 			break;
4770 		}
4771 	}
4772 }
4773 
4774 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)4775 uaudio20_mixer_find_inputs_sub(struct uaudio_terminal_node *root,
4776     const uint8_t *p_id, uint8_t n_id,
4777     struct uaudio_search_result *info)
4778 {
4779 	struct uaudio_terminal_node *iot;
4780 	uint8_t n;
4781 	uint8_t i;
4782 
4783 	for (n = 0; n < n_id; n++) {
4784 		i = p_id[n];
4785 
4786 		if (info->recurse_level == UAUDIO_RECURSE_LIMIT) {
4787 			DPRINTF("avoided going into a circle at id=%d!\n", i);
4788 			return;
4789 		}
4790 
4791 		info->recurse_level++;
4792 
4793 		iot = (root + i);
4794 
4795 		if (iot->u.desc == NULL)
4796 			continue;
4797 
4798 		switch (iot->u.desc->bDescriptorSubtype) {
4799 		case UDESCSUB_AC_INPUT:
4800 			uaudio_mixer_merge_outputs(&iot->usr, info);
4801 			info->bit_input[i / 8] |= (1 << (i % 8));
4802 			break;
4803 
4804 		case UDESCSUB_AC_OUTPUT:
4805 			info->bit_output[i / 8] |= (1 << (i % 8));
4806 			uaudio20_mixer_find_inputs_sub(
4807 			    root, &iot->u.ot_v2->bSourceId, 1, info);
4808 			info->bit_output[i / 8] &= ~(1 << (i % 8));
4809 			break;
4810 
4811 		case UDESCSUB_AC_MIXER:
4812 			uaudio_mixer_merge_outputs(&iot->usr, info);
4813 			uaudio20_mixer_find_inputs_sub(
4814 			    root, iot->u.mu_v2->baSourceId,
4815 			    iot->u.mu_v2->bNrInPins, info);
4816 			break;
4817 
4818 		case UDESCSUB_AC_SELECTOR:
4819 			uaudio_mixer_merge_outputs(&iot->usr, info);
4820 			uaudio20_mixer_find_inputs_sub(
4821 			    root, iot->u.su_v2->baSourceId,
4822 			    iot->u.su_v2->bNrInPins, info);
4823 			break;
4824 
4825 		case UDESCSUB_AC_SAMPLE_RT:
4826 			uaudio_mixer_merge_outputs(&iot->usr, info);
4827 			uaudio20_mixer_find_inputs_sub(
4828 			    root, &iot->u.ru_v2->bSourceId,
4829 			    1, info);
4830 			break;
4831 
4832 		case UDESCSUB_AC_EFFECT:
4833 			uaudio_mixer_merge_outputs(&iot->usr, info);
4834 			uaudio20_mixer_find_inputs_sub(
4835 			    root, &iot->u.ef_v2->bSourceId,
4836 			    1, info);
4837 			break;
4838 
4839 		case UDESCSUB_AC_FEATURE:
4840 			uaudio_mixer_merge_outputs(&iot->usr, info);
4841 			uaudio20_mixer_find_inputs_sub(
4842 			    root, &iot->u.fu_v2->bSourceId, 1, info);
4843 			break;
4844 
4845 		case UDESCSUB_AC_PROCESSING_V2:
4846 			uaudio_mixer_merge_outputs(&iot->usr, info);
4847 			uaudio20_mixer_find_inputs_sub(
4848 			    root, iot->u.pu_v2->baSourceId,
4849 			    iot->u.pu_v2->bNrInPins, info);
4850 			break;
4851 
4852 		case UDESCSUB_AC_EXTENSION_V2:
4853 			uaudio_mixer_merge_outputs(&iot->usr, info);
4854 			uaudio20_mixer_find_inputs_sub(
4855 			    root, iot->u.eu_v2->baSourceId,
4856 			    iot->u.eu_v2->bNrInPins, info);
4857 			break;
4858 		default:
4859 			break;
4860 		}
4861 	}
4862 }
4863 
4864 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)4865 uaudio20_mixer_find_clocks_sub(struct uaudio_terminal_node *root,
4866     const uint8_t *p_id, uint8_t n_id,
4867     struct uaudio_search_result *info)
4868 {
4869 	struct uaudio_terminal_node *iot;
4870 	uint8_t n;
4871 	uint8_t i;
4872 	uint8_t is_last;
4873 	uint8_t id;
4874 
4875 top:
4876 	for (n = 0; n < n_id; n++) {
4877 		i = p_id[n];
4878 
4879 		if (info->recurse_level == UAUDIO_RECURSE_LIMIT) {
4880 			DPRINTF("avoided going into a circle at id=%d!\n", i);
4881 			return;
4882 		}
4883 
4884 		info->recurse_level++;
4885 
4886 		iot = (root + i);
4887 
4888 		if (iot->u.desc == NULL)
4889 			continue;
4890 
4891 		is_last = ((n + 1) == n_id);
4892 
4893 		switch (iot->u.desc->bDescriptorSubtype) {
4894 		case UDESCSUB_AC_INPUT:
4895 			info->is_input = 1;
4896 			if (is_last) {
4897 				p_id = &iot->u.it_v2->bCSourceId;
4898 				n_id = 1;
4899 				goto top;
4900 			}
4901 			uaudio20_mixer_find_clocks_sub(root,
4902 			    &iot->u.it_v2->bCSourceId, 1, info);
4903 			break;
4904 
4905 		case UDESCSUB_AC_OUTPUT:
4906 			info->is_input = 0;
4907 			if (is_last) {
4908 				p_id = &iot->u.ot_v2->bCSourceId;
4909 				n_id = 1;
4910 				goto top;
4911 			}
4912 			uaudio20_mixer_find_clocks_sub(root,
4913 			    &iot->u.ot_v2->bCSourceId, 1, info);
4914 			break;
4915 
4916 		case UDESCSUB_AC_CLOCK_SEL:
4917 			if (is_last) {
4918 				p_id = iot->u.csel_v2->baCSourceId;
4919 				n_id = iot->u.csel_v2->bNrInPins;
4920 				goto top;
4921 			}
4922 			uaudio20_mixer_find_clocks_sub(root,
4923 			    iot->u.csel_v2->baCSourceId,
4924 			    iot->u.csel_v2->bNrInPins, info);
4925 			break;
4926 
4927 		case UDESCSUB_AC_CLOCK_MUL:
4928 			if (is_last) {
4929 				p_id = &iot->u.cmul_v2->bCSourceId;
4930 				n_id = 1;
4931 				goto top;
4932 			}
4933 			uaudio20_mixer_find_clocks_sub(root,
4934 			    &iot->u.cmul_v2->bCSourceId,
4935 			    1, info);
4936 			break;
4937 
4938 		case UDESCSUB_AC_CLOCK_SRC:
4939 
4940 			id = iot->u.csrc_v2->bClockId;
4941 
4942 			switch (info->is_input) {
4943 			case 0:
4944 				info->bit_output[id / 8] |= (1 << (id % 8));
4945 				break;
4946 			case 1:
4947 				info->bit_input[id / 8] |= (1 << (id % 8));
4948 				break;
4949 			default:
4950 				break;
4951 			}
4952 			break;
4953 
4954 		default:
4955 			break;
4956 		}
4957 	}
4958 }
4959 
4960 static void
uaudio_mixer_fill_info(struct uaudio_softc * sc,struct usb_device * udev,void * desc)4961 uaudio_mixer_fill_info(struct uaudio_softc *sc,
4962     struct usb_device *udev, void *desc)
4963 {
4964 	const struct usb_audio_control_descriptor *acdp;
4965 	struct usb_config_descriptor *cd = usbd_get_config_descriptor(udev);
4966 	const struct usb_descriptor *dp;
4967 	const struct usb_audio_unit *au;
4968 	struct uaudio_terminal_node *iot = NULL;
4969 	uint16_t wTotalLen;
4970 	uint8_t ID_max = 0;		/* inclusive */
4971 	uint8_t i;
4972 
4973 	desc = usb_desc_foreach(cd, desc);
4974 
4975 	if (desc == NULL) {
4976 		DPRINTF("no Audio Control header\n");
4977 		goto done;
4978 	}
4979 	acdp = desc;
4980 
4981 	if ((acdp->bLength < sizeof(*acdp)) ||
4982 	    (acdp->bDescriptorType != UDESC_CS_INTERFACE) ||
4983 	    (acdp->bDescriptorSubtype != UDESCSUB_AC_HEADER)) {
4984 		DPRINTF("invalid Audio Control header\n");
4985 		goto done;
4986 	}
4987 	/* "wTotalLen" is allowed to be corrupt */
4988 	wTotalLen = UGETW(acdp->wTotalLength) - acdp->bLength;
4989 
4990 	/* get USB audio revision */
4991 	sc->sc_audio_rev = UGETW(acdp->bcdADC);
4992 
4993 	DPRINTFN(3, "found AC header, vers=%03x, len=%d\n",
4994 	    sc->sc_audio_rev, wTotalLen);
4995 
4996 	iot = malloc(sizeof(struct uaudio_terminal_node) * 256, M_TEMP,
4997 	    M_WAITOK | M_ZERO);
4998 
4999 	while ((desc = usb_desc_foreach(cd, desc))) {
5000 		dp = desc;
5001 
5002 		if (dp->bLength > wTotalLen) {
5003 			break;
5004 		} else {
5005 			wTotalLen -= dp->bLength;
5006 		}
5007 
5008 		if (sc->sc_audio_rev >= UAUDIO_VERSION_30)
5009 			au = NULL;
5010 		else if (sc->sc_audio_rev >= UAUDIO_VERSION_20)
5011 			au = uaudio20_mixer_verify_desc(dp, 0);
5012 		else
5013 			au = uaudio_mixer_verify_desc(dp, 0);
5014 
5015 		if (au) {
5016 			iot[au->bUnitId].u.desc = (const void *)au;
5017 			if (au->bUnitId > ID_max)
5018 				ID_max = au->bUnitId;
5019 		}
5020 	}
5021 
5022 	DPRINTF("Maximum ID=%d\n", ID_max);
5023 
5024 	/*
5025 	 * determine sourcing inputs for
5026 	 * all nodes in the tree:
5027 	 */
5028 	i = ID_max;
5029 	do {
5030 		if (sc->sc_audio_rev >= UAUDIO_VERSION_30) {
5031 			/* FALLTHROUGH */
5032 		} else if (sc->sc_audio_rev >= UAUDIO_VERSION_20) {
5033 			uaudio20_mixer_find_inputs_sub(iot,
5034 			    &i, 1, &((iot + i)->usr));
5035 
5036 			sc->sc_mixer_clocks.is_input = 255;
5037 			sc->sc_mixer_clocks.recurse_level = 0;
5038 
5039 			uaudio20_mixer_find_clocks_sub(iot,
5040 			    &i, 1, &sc->sc_mixer_clocks);
5041 		} else {
5042 			uaudio_mixer_find_inputs_sub(iot,
5043 			    &i, 1, &((iot + i)->usr));
5044 		}
5045 	} while (i--);
5046 
5047 	/* set "id_max" and "root" */
5048 
5049 	i = ID_max;
5050 	do {
5051 		(iot + i)->usr.id_max = ID_max;
5052 		(iot + i)->root = iot;
5053 	} while (i--);
5054 
5055 	/*
5056 	 * Scan the config to create a linked list of "mixer" nodes:
5057 	 */
5058 
5059 	i = ID_max;
5060 	do {
5061 		dp = iot[i].u.desc;
5062 
5063 		if (dp == NULL)
5064 			continue;
5065 
5066 		DPRINTFN(11, "id=%d subtype=%d\n",
5067 		    i, dp->bDescriptorSubtype);
5068 
5069 		if (sc->sc_audio_rev >= UAUDIO_VERSION_30) {
5070 			continue;
5071 		} else if (sc->sc_audio_rev >= UAUDIO_VERSION_20) {
5072 			switch (dp->bDescriptorSubtype) {
5073 			case UDESCSUB_AC_HEADER:
5074 				DPRINTF("unexpected AC header\n");
5075 				break;
5076 
5077 			case UDESCSUB_AC_INPUT:
5078 			case UDESCSUB_AC_OUTPUT:
5079 			case UDESCSUB_AC_PROCESSING_V2:
5080 			case UDESCSUB_AC_EXTENSION_V2:
5081 			case UDESCSUB_AC_EFFECT:
5082 			case UDESCSUB_AC_CLOCK_SRC:
5083 			case UDESCSUB_AC_CLOCK_SEL:
5084 			case UDESCSUB_AC_CLOCK_MUL:
5085 			case UDESCSUB_AC_SAMPLE_RT:
5086 				break;
5087 
5088 			case UDESCSUB_AC_MIXER:
5089 				uaudio20_mixer_add_mixer(sc, iot, i);
5090 				break;
5091 
5092 			case UDESCSUB_AC_SELECTOR:
5093 				uaudio20_mixer_add_selector(sc, iot, i);
5094 				break;
5095 
5096 			case UDESCSUB_AC_FEATURE:
5097 				uaudio20_mixer_add_feature(sc, iot, i);
5098 				break;
5099 
5100 			default:
5101 				DPRINTF("bad AC desc subtype=0x%02x\n",
5102 				    dp->bDescriptorSubtype);
5103 				break;
5104 			}
5105 			continue;
5106 		}
5107 
5108 		switch (dp->bDescriptorSubtype) {
5109 		case UDESCSUB_AC_HEADER:
5110 			DPRINTF("unexpected AC header\n");
5111 			break;
5112 
5113 		case UDESCSUB_AC_INPUT:
5114 		case UDESCSUB_AC_OUTPUT:
5115 			break;
5116 
5117 		case UDESCSUB_AC_MIXER:
5118 			uaudio_mixer_add_mixer(sc, iot, i);
5119 			break;
5120 
5121 		case UDESCSUB_AC_SELECTOR:
5122 			uaudio_mixer_add_selector(sc, iot, i);
5123 			break;
5124 
5125 		case UDESCSUB_AC_FEATURE:
5126 			uaudio_mixer_add_feature(sc, iot, i);
5127 			break;
5128 
5129 		case UDESCSUB_AC_PROCESSING:
5130 			uaudio_mixer_add_processing(sc, iot, i);
5131 			break;
5132 
5133 		case UDESCSUB_AC_EXTENSION:
5134 			uaudio_mixer_add_extension(sc, iot, i);
5135 			break;
5136 
5137 		default:
5138 			DPRINTF("bad AC desc subtype=0x%02x\n",
5139 			    dp->bDescriptorSubtype);
5140 			break;
5141 		}
5142 
5143 	} while (i--);
5144 
5145 done:
5146 	free(iot, M_TEMP);
5147 }
5148 
5149 static int
uaudio_mixer_get(struct usb_device * udev,uint16_t audio_rev,uint8_t what,struct uaudio_mixer_node * mc)5150 uaudio_mixer_get(struct usb_device *udev, uint16_t audio_rev,
5151     uint8_t what, struct uaudio_mixer_node *mc)
5152 {
5153 	struct usb_device_request req;
5154 	int val;
5155 	uint8_t data[2 + (2 * 3)];
5156 	usb_error_t err;
5157 
5158 	if (mc->wValue[0] == -1)
5159 		return (0);
5160 
5161 	if (audio_rev >= UAUDIO_VERSION_30)
5162 		return (0);
5163 	else if (audio_rev >= UAUDIO_VERSION_20) {
5164 		if (what == GET_CUR) {
5165 			req.bRequest = UA20_CS_CUR;
5166 			USETW(req.wLength, 2);
5167 		} else {
5168 			req.bRequest = UA20_CS_RANGE;
5169 			USETW(req.wLength, 8);
5170 		}
5171 	} else {
5172 		uint16_t len = MIX_SIZE(mc->type);
5173 
5174 		req.bRequest = what;
5175 		USETW(req.wLength, len);
5176 	}
5177 
5178 	req.bmRequestType = UT_READ_CLASS_INTERFACE;
5179 	USETW(req.wValue, mc->wValue[0]);
5180 	USETW(req.wIndex, mc->wIndex);
5181 
5182 	memset(data, 0, sizeof(data));
5183 
5184 	err = usbd_do_request(udev, NULL, &req, data);
5185 	if (err) {
5186 		DPRINTF("err=%s\n", usbd_errstr(err));
5187 		return (0);
5188 	}
5189 
5190 	if (audio_rev >= UAUDIO_VERSION_30) {
5191 		val = 0;
5192 	} else if (audio_rev >= UAUDIO_VERSION_20) {
5193 		switch (what) {
5194 		case GET_CUR:
5195 			val = (data[0] | (data[1] << 8));
5196 			break;
5197 		case GET_MIN:
5198 			val = (data[2] | (data[3] << 8));
5199 			break;
5200 		case GET_MAX:
5201 			val = (data[4] | (data[5] << 8));
5202 			break;
5203 		case GET_RES:
5204 			val = (data[6] | (data[7] << 8));
5205 			break;
5206 		default:
5207 			val = 0;
5208 			break;
5209 		}
5210 	} else {
5211 		val = (data[0] | (data[1] << 8));
5212 	}
5213 
5214 	if (what == GET_CUR || what == GET_MIN || what == GET_MAX)
5215 		val = uaudio_mixer_signext(mc->type, val);
5216 
5217 	DPRINTFN(3, "val=%d\n", val);
5218 
5219 	return (val);
5220 }
5221 
5222 static void
uaudio_mixer_write_cfg_callback(struct usb_xfer * xfer,usb_error_t error)5223 uaudio_mixer_write_cfg_callback(struct usb_xfer *xfer, usb_error_t error)
5224 {
5225 	struct usb_device_request req;
5226 	struct uaudio_softc *sc = usbd_xfer_softc(xfer);
5227 	struct uaudio_mixer_node *mc = sc->sc_mixer_curr;
5228 	struct usb_page_cache *pc;
5229 	uint16_t len;
5230 	uint8_t repeat = 1;
5231 	uint8_t update;
5232 	uint8_t chan;
5233 	uint8_t buf[2];
5234 
5235 	DPRINTF("\n");
5236 
5237 	switch (USB_GET_STATE(xfer)) {
5238 	case USB_ST_TRANSFERRED:
5239 tr_transferred:
5240 	case USB_ST_SETUP:
5241 tr_setup:
5242 
5243 		if (mc == NULL) {
5244 			mc = sc->sc_mixer_root;
5245 			sc->sc_mixer_curr = mc;
5246 			sc->sc_mixer_chan = 0;
5247 			repeat = 0;
5248 		}
5249 		while (mc) {
5250 			while (sc->sc_mixer_chan < mc->nchan) {
5251 				chan = sc->sc_mixer_chan;
5252 
5253 				sc->sc_mixer_chan++;
5254 
5255 				update = ((mc->update[chan / 8] & (1 << (chan % 8))) &&
5256 				    (mc->wValue[chan] != -1));
5257 
5258 				mc->update[chan / 8] &= ~(1 << (chan % 8));
5259 
5260 				if (update) {
5261 					req.bmRequestType = UT_WRITE_CLASS_INTERFACE;
5262 					USETW(req.wValue, mc->wValue[chan]);
5263 					USETW(req.wIndex, mc->wIndex);
5264 
5265 					if (sc->sc_audio_rev >= UAUDIO_VERSION_30) {
5266 						return;
5267 					} else if (sc->sc_audio_rev >= UAUDIO_VERSION_20) {
5268 						len = 2;
5269 						req.bRequest = UA20_CS_CUR;
5270 						USETW(req.wLength, len);
5271 					} else {
5272 						len = MIX_SIZE(mc->type);
5273 						req.bRequest = SET_CUR;
5274 						USETW(req.wLength, len);
5275 					}
5276 
5277 					buf[0] = (mc->wData[chan] & 0xFF);
5278 					buf[1] = (mc->wData[chan] >> 8) & 0xFF;
5279 
5280 					pc = usbd_xfer_get_frame(xfer, 0);
5281 					usbd_copy_in(pc, 0, &req, sizeof(req));
5282 					pc = usbd_xfer_get_frame(xfer, 1);
5283 					usbd_copy_in(pc, 0, buf, len);
5284 
5285 					usbd_xfer_set_frame_len(xfer, 0, sizeof(req));
5286 					usbd_xfer_set_frame_len(xfer, 1, len);
5287 					usbd_xfer_set_frames(xfer, len ? 2 : 1);
5288 					usbd_transfer_submit(xfer);
5289 					return;
5290 				}
5291 			}
5292 
5293 			mc = mc->next;
5294 			sc->sc_mixer_curr = mc;
5295 			sc->sc_mixer_chan = 0;
5296 		}
5297 
5298 		if (repeat) {
5299 			goto tr_setup;
5300 		}
5301 		break;
5302 
5303 	default:			/* Error */
5304 		DPRINTF("error=%s\n", usbd_errstr(error));
5305 		if (error == USB_ERR_CANCELLED) {
5306 			/* do nothing - we are detaching */
5307 			break;
5308 		}
5309 		goto tr_transferred;
5310 	}
5311 }
5312 
5313 static usb_error_t
uaudio_set_speed(struct usb_device * udev,uint8_t endpt,uint32_t speed)5314 uaudio_set_speed(struct usb_device *udev, uint8_t endpt, uint32_t speed)
5315 {
5316 	struct usb_device_request req;
5317 	uint8_t data[3];
5318 
5319 	DPRINTFN(6, "endpt=%d speed=%u\n", endpt, speed);
5320 
5321 	req.bmRequestType = UT_WRITE_CLASS_ENDPOINT;
5322 	req.bRequest = SET_CUR;
5323 	USETW2(req.wValue, SAMPLING_FREQ_CONTROL, 0);
5324 	USETW(req.wIndex, endpt);
5325 	USETW(req.wLength, 3);
5326 	data[0] = speed;
5327 	data[1] = speed >> 8;
5328 	data[2] = speed >> 16;
5329 
5330 	return (usbd_do_request(udev, NULL, &req, data));
5331 }
5332 
5333 static usb_error_t
uaudio20_set_speed(struct usb_device * udev,uint8_t iface_no,uint8_t clockid,uint32_t speed)5334 uaudio20_set_speed(struct usb_device *udev, uint8_t iface_no,
5335     uint8_t clockid, uint32_t speed)
5336 {
5337 	struct usb_device_request req;
5338 	uint8_t data[4];
5339 
5340 	DPRINTFN(6, "ifaceno=%d clockid=%d speed=%u\n",
5341 	    iface_no, clockid, speed);
5342 
5343 	req.bmRequestType = UT_WRITE_CLASS_INTERFACE;
5344 	req.bRequest = UA20_CS_CUR;
5345 	USETW2(req.wValue, UA20_CS_SAM_FREQ_CONTROL, 0);
5346 	USETW2(req.wIndex, clockid, iface_no);
5347 	USETW(req.wLength, 4);
5348 	data[0] = speed;
5349 	data[1] = speed >> 8;
5350 	data[2] = speed >> 16;
5351 	data[3] = speed >> 24;
5352 
5353 	return (usbd_do_request(udev, NULL, &req, data));
5354 }
5355 
5356 static int
uaudio_mixer_signext(uint8_t type,int val)5357 uaudio_mixer_signext(uint8_t type, int val)
5358 {
5359 	if (!MIX_UNSIGNED(type)) {
5360 		if (MIX_SIZE(type) == 2) {
5361 			val = (int16_t)val;
5362 		} else {
5363 			val = (int8_t)val;
5364 		}
5365 	}
5366 	return (val);
5367 }
5368 
5369 static int
uaudio_mixer_bsd2value(struct uaudio_mixer_node * mc,int val)5370 uaudio_mixer_bsd2value(struct uaudio_mixer_node *mc, int val)
5371 {
5372 	if (mc->type == MIX_ON_OFF) {
5373 		val = (val != 0);
5374 	} else if (mc->type != MIX_SELECTOR) {
5375 		/* compute actual volume */
5376 		val = (val * mc->mul) / 100;
5377 
5378 		/* add lower offset */
5379 		val = val + mc->minval;
5380 	}
5381 	/* make sure we don't write a value out of range */
5382 	if (val > mc->maxval)
5383 		val = mc->maxval;
5384 	else if (val < mc->minval)
5385 		val = mc->minval;
5386 
5387 	DPRINTFN(6, "type=0x%03x val=%d min=%d max=%d val=%d\n",
5388 	    mc->type, val, mc->minval, mc->maxval, val);
5389 	return (val);
5390 }
5391 
5392 static void
uaudio_mixer_ctl_set(struct uaudio_softc * sc,struct uaudio_mixer_node * mc,uint8_t chan,int val)5393 uaudio_mixer_ctl_set(struct uaudio_softc *sc, struct uaudio_mixer_node *mc,
5394     uint8_t chan, int val)
5395 {
5396 	val = uaudio_mixer_bsd2value(mc, val);
5397 
5398 	mc->update[chan / 8] |= (1 << (chan % 8));
5399 	mc->wData[chan] = val;
5400 
5401 	/* start the transfer, if not already started */
5402 
5403 	usbd_transfer_start(sc->sc_mixer_xfer[0]);
5404 }
5405 
5406 static void
uaudio_mixer_init(struct uaudio_softc * sc,unsigned index)5407 uaudio_mixer_init(struct uaudio_softc *sc, unsigned index)
5408 {
5409 	struct uaudio_mixer_node *mc;
5410 	int32_t i;
5411 
5412 	if (index != 0)
5413 		return;
5414 	for (mc = sc->sc_mixer_root; mc; mc = mc->next) {
5415 		if (mc->ctl != SOUND_MIXER_NRDEVICES) {
5416 			/*
5417 			 * Set device mask bits. See
5418 			 * /usr/include/machine/soundcard.h
5419 			 */
5420 			sc->sc_child[index].mix_info |= 1U << mc->ctl;
5421 		}
5422 		if ((mc->ctl == SOUND_MIXER_NRDEVICES) &&
5423 		    (mc->type == MIX_SELECTOR)) {
5424 			for (i = mc->minval; (i > 0) && (i <= mc->maxval); i++) {
5425 				if (mc->slctrtype[i - 1] == SOUND_MIXER_NRDEVICES)
5426 					continue;
5427 				sc->sc_child[index].recsrc_info |= 1U << mc->slctrtype[i - 1];
5428 			}
5429 		}
5430 	}
5431 }
5432 
5433 int
uaudio_mixer_init_sub(struct uaudio_softc * sc,struct snd_mixer * m)5434 uaudio_mixer_init_sub(struct uaudio_softc *sc, struct snd_mixer *m)
5435 {
5436 	unsigned i = uaudio_get_child_index_by_dev(sc, mix_get_dev(m));
5437 
5438 	DPRINTF("child=%u\n", i);
5439 
5440 	sc->sc_child[i].mixer_lock = mixer_get_lock(m);
5441 	sc->sc_child[i].mixer_dev = m;
5442 
5443 	if (i == 0 &&
5444 	    usbd_transfer_setup(sc->sc_udev, &sc->sc_mixer_iface_index,
5445 	    sc->sc_mixer_xfer, uaudio_mixer_config, 1, sc,
5446 	    sc->sc_child[i].mixer_lock)) {
5447 		DPRINTFN(0, "could not allocate USB transfer for mixer!\n");
5448 		return (ENOMEM);
5449 	}
5450 
5451 	if (sc->sc_play_chan[i].num_alt > 0 &&
5452 	    (sc->sc_child[i].mix_info & SOUND_MASK_VOLUME) == 0) {
5453 		mix_setparentchild(m, SOUND_MIXER_VOLUME, SOUND_MASK_PCM);
5454 		mix_setrealdev(m, SOUND_MIXER_VOLUME, SOUND_MIXER_NONE);
5455 	}
5456 	mix_setdevs(m, sc->sc_child[i].mix_info);
5457 	mix_setrecdevs(m, sc->sc_child[i].recsrc_info);
5458 	return (0);
5459 }
5460 
5461 int
uaudio_mixer_uninit_sub(struct uaudio_softc * sc,struct snd_mixer * m)5462 uaudio_mixer_uninit_sub(struct uaudio_softc *sc, struct snd_mixer *m)
5463 {
5464   	unsigned index = uaudio_get_child_index_by_dev(sc, mix_get_dev(m));
5465 
5466 	DPRINTF("child=%u\n", index);
5467 
5468 	if (index == 0)
5469 		usbd_transfer_unsetup(sc->sc_mixer_xfer, 1);
5470 
5471 	sc->sc_child[index].mixer_lock = NULL;
5472 
5473 	return (0);
5474 }
5475 
5476 void
uaudio_mixer_set(struct uaudio_softc * sc,struct snd_mixer * m,unsigned type,unsigned left,unsigned right)5477 uaudio_mixer_set(struct uaudio_softc *sc, struct snd_mixer *m,
5478     unsigned type, unsigned left, unsigned right)
5479 {
5480     	unsigned index = uaudio_get_child_index_by_dev(sc, mix_get_dev(m));
5481 	struct uaudio_mixer_node *mc;
5482 	int chan;
5483 
5484 	if (index != 0)
5485 		return;
5486 	for (mc = sc->sc_mixer_root; mc != NULL; mc = mc->next) {
5487 		if (mc->ctl == type) {
5488 			for (chan = 0; chan < mc->nchan; chan++) {
5489 				uaudio_mixer_ctl_set(sc, mc, chan,
5490 				    chan == 0 ? left : right);
5491 			}
5492 		}
5493 	}
5494 }
5495 
5496 uint32_t
uaudio_mixer_setrecsrc(struct uaudio_softc * sc,struct snd_mixer * m,uint32_t src)5497 uaudio_mixer_setrecsrc(struct uaudio_softc *sc, struct snd_mixer *m, uint32_t src)
5498 {
5499       	unsigned index = uaudio_get_child_index_by_dev(sc, mix_get_dev(m));
5500 	struct uaudio_mixer_node *mc;
5501 	uint32_t mask;
5502 	uint32_t temp;
5503 	int32_t i;
5504 
5505 	if (index != 0)
5506 		return (0);
5507 	for (mc = sc->sc_mixer_root; mc; mc = mc->next) {
5508 		if ((mc->ctl == SOUND_MIXER_NRDEVICES) &&
5509 		    (mc->type == MIX_SELECTOR)) {
5510 			/* compute selector mask */
5511 
5512 			mask = 0;
5513 			for (i = mc->minval; (i > 0) && (i <= mc->maxval); i++)
5514 				mask |= 1U << mc->slctrtype[i - 1];
5515 
5516 			temp = mask & src;
5517 			if (temp == 0)
5518 				continue;
5519 
5520 			/* find the first set bit */
5521 			temp = (-temp) & temp;
5522 
5523 			/* update "src" */
5524 			src &= ~mask;
5525 			src |= temp;
5526 
5527 			for (i = mc->minval; (i > 0) && (i <= mc->maxval); i++) {
5528 				if (temp != (1U << mc->slctrtype[i - 1]))
5529 					continue;
5530 				uaudio_mixer_ctl_set(sc, mc, 0, i);
5531 				break;
5532 			}
5533 		}
5534 	}
5535 	return (src);
5536 }
5537 
5538 /*========================================================================*
5539  * MIDI support routines
5540  *========================================================================*/
5541 
5542 static void
umidi_bulk_read_callback(struct usb_xfer * xfer,usb_error_t error)5543 umidi_bulk_read_callback(struct usb_xfer *xfer, usb_error_t error)
5544 {
5545 	struct umidi_chan *chan = usbd_xfer_softc(xfer);
5546 	struct umidi_sub_chan *sub;
5547 	struct usb_page_cache *pc;
5548 	uint8_t buf[4];
5549 	uint8_t cmd_len;
5550 	uint8_t cn;
5551 	uint16_t pos;
5552 	int actlen;
5553 
5554 	usbd_xfer_status(xfer, &actlen, NULL, NULL, NULL);
5555 
5556 	switch (USB_GET_STATE(xfer)) {
5557 	case USB_ST_TRANSFERRED:
5558 
5559 		DPRINTF("actlen=%d bytes\n", actlen);
5560 
5561 		pos = 0;
5562 		pc = usbd_xfer_get_frame(xfer, 0);
5563 
5564 		while (actlen >= 4) {
5565 			/* copy out the MIDI data */
5566 			usbd_copy_out(pc, pos, buf, 4);
5567 			/* command length */
5568 			cmd_len = umidi_cmd_to_len[buf[0] & 0xF];
5569 			/* cable number */
5570 			cn = buf[0] >> 4;
5571 			/*
5572 			 * Lookup sub-channel. The index is range
5573 			 * checked below.
5574 			 */
5575 			sub = &chan->sub[cn];
5576 
5577 			if ((cmd_len != 0) && (cn < chan->max_emb_jack) &&
5578 			    (sub->read_open != 0)) {
5579 				/* Send data to the application */
5580 				usb_fifo_put_data_linear(
5581 				    sub->fifo.fp[USB_FIFO_RX],
5582 				    buf + 1, cmd_len, 1);
5583 			}
5584 			actlen -= 4;
5585 			pos += 4;
5586 		}
5587 
5588 	case USB_ST_SETUP:
5589 		DPRINTF("start\n");
5590 tr_setup:
5591 		usbd_xfer_set_frame_len(xfer, 0, usbd_xfer_max_len(xfer));
5592 		usbd_transfer_submit(xfer);
5593 		break;
5594 
5595 	default:
5596 		DPRINTF("error=%s\n", usbd_errstr(error));
5597 
5598 		if (error != USB_ERR_CANCELLED) {
5599 			/* try to clear stall first */
5600 			usbd_xfer_set_stall(xfer);
5601 			goto tr_setup;
5602 		}
5603 		break;
5604 	}
5605 }
5606 
5607 /*
5608  * The following statemachine, that converts MIDI commands to
5609  * USB MIDI packets, derives from Linux's usbmidi.c, which
5610  * was written by "Clemens Ladisch":
5611  *
5612  * Returns:
5613  *    0: No command
5614  * Else: Command is complete
5615  */
5616 static uint8_t
umidi_convert_to_usb(struct umidi_sub_chan * sub,uint8_t cn,uint8_t b)5617 umidi_convert_to_usb(struct umidi_sub_chan *sub, uint8_t cn, uint8_t b)
5618 {
5619 	uint8_t p0 = (cn << 4);
5620 
5621 	if (b >= 0xf8) {
5622 		sub->temp_0[0] = p0 | 0x0f;
5623 		sub->temp_0[1] = b;
5624 		sub->temp_0[2] = 0;
5625 		sub->temp_0[3] = 0;
5626 		sub->temp_cmd = sub->temp_0;
5627 		return (1);
5628 
5629 	} else if (b >= 0xf0) {
5630 		switch (b) {
5631 		case 0xf0:		/* system exclusive begin */
5632 			sub->temp_1[1] = b;
5633 			sub->state = UMIDI_ST_SYSEX_1;
5634 			break;
5635 		case 0xf1:		/* MIDI time code */
5636 		case 0xf3:		/* song select */
5637 			sub->temp_1[1] = b;
5638 			sub->state = UMIDI_ST_1PARAM;
5639 			break;
5640 		case 0xf2:		/* song position pointer */
5641 			sub->temp_1[1] = b;
5642 			sub->state = UMIDI_ST_2PARAM_1;
5643 			break;
5644 		case 0xf4:		/* unknown */
5645 		case 0xf5:		/* unknown */
5646 			sub->state = UMIDI_ST_UNKNOWN;
5647 			break;
5648 		case 0xf6:		/* tune request */
5649 			sub->temp_1[0] = p0 | 0x05;
5650 			sub->temp_1[1] = 0xf6;
5651 			sub->temp_1[2] = 0;
5652 			sub->temp_1[3] = 0;
5653 			sub->temp_cmd = sub->temp_1;
5654 			sub->state = UMIDI_ST_UNKNOWN;
5655 			return (1);
5656 
5657 		case 0xf7:		/* system exclusive end */
5658 			switch (sub->state) {
5659 			case UMIDI_ST_SYSEX_0:
5660 				sub->temp_1[0] = p0 | 0x05;
5661 				sub->temp_1[1] = 0xf7;
5662 				sub->temp_1[2] = 0;
5663 				sub->temp_1[3] = 0;
5664 				sub->temp_cmd = sub->temp_1;
5665 				sub->state = UMIDI_ST_UNKNOWN;
5666 				return (1);
5667 			case UMIDI_ST_SYSEX_1:
5668 				sub->temp_1[0] = p0 | 0x06;
5669 				sub->temp_1[2] = 0xf7;
5670 				sub->temp_1[3] = 0;
5671 				sub->temp_cmd = sub->temp_1;
5672 				sub->state = UMIDI_ST_UNKNOWN;
5673 				return (1);
5674 			case UMIDI_ST_SYSEX_2:
5675 				sub->temp_1[0] = p0 | 0x07;
5676 				sub->temp_1[3] = 0xf7;
5677 				sub->temp_cmd = sub->temp_1;
5678 				sub->state = UMIDI_ST_UNKNOWN;
5679 				return (1);
5680 			}
5681 			sub->state = UMIDI_ST_UNKNOWN;
5682 			break;
5683 		}
5684 	} else if (b >= 0x80) {
5685 		sub->temp_1[1] = b;
5686 		if ((b >= 0xc0) && (b <= 0xdf)) {
5687 			sub->state = UMIDI_ST_1PARAM;
5688 		} else {
5689 			sub->state = UMIDI_ST_2PARAM_1;
5690 		}
5691 	} else {			/* b < 0x80 */
5692 		switch (sub->state) {
5693 		case UMIDI_ST_1PARAM:
5694 			if (sub->temp_1[1] < 0xf0) {
5695 				p0 |= sub->temp_1[1] >> 4;
5696 			} else {
5697 				p0 |= 0x02;
5698 				sub->state = UMIDI_ST_UNKNOWN;
5699 			}
5700 			sub->temp_1[0] = p0;
5701 			sub->temp_1[2] = b;
5702 			sub->temp_1[3] = 0;
5703 			sub->temp_cmd = sub->temp_1;
5704 			return (1);
5705 		case UMIDI_ST_2PARAM_1:
5706 			sub->temp_1[2] = b;
5707 			sub->state = UMIDI_ST_2PARAM_2;
5708 			break;
5709 		case UMIDI_ST_2PARAM_2:
5710 			if (sub->temp_1[1] < 0xf0) {
5711 				p0 |= sub->temp_1[1] >> 4;
5712 				sub->state = UMIDI_ST_2PARAM_1;
5713 			} else {
5714 				p0 |= 0x03;
5715 				sub->state = UMIDI_ST_UNKNOWN;
5716 			}
5717 			sub->temp_1[0] = p0;
5718 			sub->temp_1[3] = b;
5719 			sub->temp_cmd = sub->temp_1;
5720 			return (1);
5721 		case UMIDI_ST_SYSEX_0:
5722 			sub->temp_1[1] = b;
5723 			sub->state = UMIDI_ST_SYSEX_1;
5724 			break;
5725 		case UMIDI_ST_SYSEX_1:
5726 			sub->temp_1[2] = b;
5727 			sub->state = UMIDI_ST_SYSEX_2;
5728 			break;
5729 		case UMIDI_ST_SYSEX_2:
5730 			sub->temp_1[0] = p0 | 0x04;
5731 			sub->temp_1[3] = b;
5732 			sub->temp_cmd = sub->temp_1;
5733 			sub->state = UMIDI_ST_SYSEX_0;
5734 			return (1);
5735 		default:
5736 			break;
5737 		}
5738 	}
5739 	return (0);
5740 }
5741 
5742 static void
umidi_bulk_write_callback(struct usb_xfer * xfer,usb_error_t error)5743 umidi_bulk_write_callback(struct usb_xfer *xfer, usb_error_t error)
5744 {
5745 	struct umidi_chan *chan = usbd_xfer_softc(xfer);
5746 	struct umidi_sub_chan *sub;
5747 	struct usb_page_cache *pc;
5748 	uint32_t actlen;
5749 	uint16_t nframes;
5750 	uint8_t buf;
5751 	uint8_t start_cable;
5752 	uint8_t tr_any;
5753 	int len;
5754 
5755 	usbd_xfer_status(xfer, &len, NULL, NULL, NULL);
5756 
5757 	/*
5758 	 * NOTE: Some MIDI devices only accept 4 bytes of data per
5759 	 * short terminated USB transfer.
5760 	 */
5761 	switch (USB_GET_STATE(xfer)) {
5762 	case USB_ST_TRANSFERRED:
5763 		DPRINTF("actlen=%d bytes\n", len);
5764 
5765 	case USB_ST_SETUP:
5766 tr_setup:
5767 		DPRINTF("start\n");
5768 
5769 		nframes = 0;	/* reset */
5770 		start_cable = chan->curr_cable;
5771 		tr_any = 0;
5772 		pc = usbd_xfer_get_frame(xfer, 0);
5773 
5774 		while (1) {
5775 			/* round robin de-queueing */
5776 
5777 			sub = &chan->sub[chan->curr_cable];
5778 
5779 			if (sub->write_open) {
5780 				usb_fifo_get_data_linear(sub->fifo.fp[USB_FIFO_TX],
5781 				    &buf, 1, &actlen, 0);
5782 			} else {
5783 				actlen = 0;
5784 			}
5785 
5786 			if (actlen) {
5787 				tr_any = 1;
5788 
5789 				DPRINTF("byte=0x%02x from FIFO %u\n", buf,
5790 				    (unsigned int)chan->curr_cable);
5791 
5792 				if (umidi_convert_to_usb(sub, chan->curr_cable, buf)) {
5793 					DPRINTF("sub=0x%02x 0x%02x 0x%02x 0x%02x\n",
5794 					    sub->temp_cmd[0], sub->temp_cmd[1],
5795 					    sub->temp_cmd[2], sub->temp_cmd[3]);
5796 
5797 					usbd_copy_in(pc, nframes * 4, sub->temp_cmd, 4);
5798 
5799 					nframes++;
5800 
5801 					if ((nframes >= UMIDI_TX_FRAMES) || (chan->single_command != 0))
5802 						break;
5803 				} else {
5804 					continue;
5805 				}
5806 			}
5807 
5808 			chan->curr_cable++;
5809 			if (chan->curr_cable >= chan->max_emb_jack)
5810 				chan->curr_cable = 0;
5811 
5812 			if (chan->curr_cable == start_cable) {
5813 				if (tr_any == 0)
5814 					break;
5815 				tr_any = 0;
5816 			}
5817 		}
5818 
5819 		if (nframes != 0) {
5820 			DPRINTF("Transferring %d frames\n", (int)nframes);
5821 			usbd_xfer_set_frame_len(xfer, 0, 4 * nframes);
5822 			usbd_transfer_submit(xfer);
5823 		}
5824 		break;
5825 
5826 	default:			/* Error */
5827 
5828 		DPRINTF("error=%s\n", usbd_errstr(error));
5829 
5830 		if (error != USB_ERR_CANCELLED) {
5831 			/* try to clear stall first */
5832 			usbd_xfer_set_stall(xfer);
5833 			goto tr_setup;
5834 		}
5835 		break;
5836 	}
5837 }
5838 
5839 static struct umidi_sub_chan *
umidi_sub_by_fifo(struct usb_fifo * fifo)5840 umidi_sub_by_fifo(struct usb_fifo *fifo)
5841 {
5842 	struct umidi_chan *chan = usb_fifo_softc(fifo);
5843 	struct umidi_sub_chan *sub;
5844 	uint32_t n;
5845 
5846 	for (n = 0; n < UMIDI_EMB_JACK_MAX; n++) {
5847 		sub = &chan->sub[n];
5848 		if ((sub->fifo.fp[USB_FIFO_RX] == fifo) ||
5849 		    (sub->fifo.fp[USB_FIFO_TX] == fifo)) {
5850 			return (sub);
5851 		}
5852 	}
5853 
5854 	panic("%s:%d cannot find usb_fifo!\n",
5855 	    __FILE__, __LINE__);
5856 
5857 	return (NULL);
5858 }
5859 
5860 static void
umidi_start_read(struct usb_fifo * fifo)5861 umidi_start_read(struct usb_fifo *fifo)
5862 {
5863 	struct umidi_chan *chan = usb_fifo_softc(fifo);
5864 
5865 	usbd_transfer_start(chan->xfer[UMIDI_RX_TRANSFER]);
5866 }
5867 
5868 static void
umidi_stop_read(struct usb_fifo * fifo)5869 umidi_stop_read(struct usb_fifo *fifo)
5870 {
5871 	struct umidi_chan *chan = usb_fifo_softc(fifo);
5872 	struct umidi_sub_chan *sub = umidi_sub_by_fifo(fifo);
5873 
5874 	DPRINTF("\n");
5875 
5876 	sub->read_open = 0;
5877 
5878 	if (--(chan->read_open_refcount) == 0) {
5879 		/*
5880 		 * XXX don't stop the read transfer here, hence that causes
5881 		 * problems with some MIDI adapters
5882 		 */
5883 		DPRINTF("(stopping read transfer)\n");
5884 	}
5885 }
5886 
5887 static void
umidi_start_write(struct usb_fifo * fifo)5888 umidi_start_write(struct usb_fifo *fifo)
5889 {
5890 	struct umidi_chan *chan = usb_fifo_softc(fifo);
5891 
5892 	if (chan->xfer[UMIDI_TX_TRANSFER] == NULL) {
5893 		uint8_t buf[1];
5894 		int actlen;
5895 		do {
5896 			/* dump data */
5897 			usb_fifo_get_data_linear(fifo, buf, 1, &actlen, 0);
5898 		} while (actlen > 0);
5899 	} else {
5900 		usbd_transfer_start(chan->xfer[UMIDI_TX_TRANSFER]);
5901 	}
5902 }
5903 
5904 static void
umidi_stop_write(struct usb_fifo * fifo)5905 umidi_stop_write(struct usb_fifo *fifo)
5906 {
5907 	struct umidi_chan *chan = usb_fifo_softc(fifo);
5908 	struct umidi_sub_chan *sub = umidi_sub_by_fifo(fifo);
5909 
5910 	DPRINTF("\n");
5911 
5912 	sub->write_open = 0;
5913 
5914 	if (--(chan->write_open_refcount) == 0) {
5915 		DPRINTF("(stopping write transfer)\n");
5916 		usbd_transfer_stop(chan->xfer[UMIDI_TX_TRANSFER]);
5917 	}
5918 }
5919 
5920 static int
umidi_open(struct usb_fifo * fifo,int fflags)5921 umidi_open(struct usb_fifo *fifo, int fflags)
5922 {
5923 	struct umidi_chan *chan = usb_fifo_softc(fifo);
5924 	struct umidi_sub_chan *sub = umidi_sub_by_fifo(fifo);
5925 
5926 	if (fflags & FREAD) {
5927 		if (usb_fifo_alloc_buffer(fifo, 4, (1024 / 4))) {
5928 			return (ENOMEM);
5929 		}
5930 		mtx_lock(&chan->mtx);
5931 		chan->read_open_refcount++;
5932 		sub->read_open = 1;
5933 		mtx_unlock(&chan->mtx);
5934 	}
5935 	if (fflags & FWRITE) {
5936 		if (usb_fifo_alloc_buffer(fifo, 32, (1024 / 32))) {
5937 			return (ENOMEM);
5938 		}
5939 		/* clear stall first */
5940 		mtx_lock(&chan->mtx);
5941 		chan->write_open_refcount++;
5942 		sub->write_open = 1;
5943 
5944 		/* reset */
5945 		sub->state = UMIDI_ST_UNKNOWN;
5946 		mtx_unlock(&chan->mtx);
5947 	}
5948 	return (0);			/* success */
5949 }
5950 
5951 static void
umidi_close(struct usb_fifo * fifo,int fflags)5952 umidi_close(struct usb_fifo *fifo, int fflags)
5953 {
5954 	if (fflags & FREAD) {
5955 		usb_fifo_free_buffer(fifo);
5956 	}
5957 	if (fflags & FWRITE) {
5958 		usb_fifo_free_buffer(fifo);
5959 	}
5960 }
5961 
5962 static int
umidi_ioctl(struct usb_fifo * fifo,u_long cmd,void * data,int fflags)5963 umidi_ioctl(struct usb_fifo *fifo, u_long cmd, void *data,
5964     int fflags)
5965 {
5966 	return (ENODEV);
5967 }
5968 
5969 static void
umidi_init(device_t dev)5970 umidi_init(device_t dev)
5971 {
5972 	struct uaudio_softc *sc = device_get_softc(dev);
5973 	struct umidi_chan *chan = &sc->sc_midi_chan;
5974 
5975 	mtx_init(&chan->mtx, "umidi lock", NULL, MTX_DEF | MTX_RECURSE);
5976 }
5977 
5978 static struct usb_fifo_methods umidi_fifo_methods = {
5979 	.f_start_read = &umidi_start_read,
5980 	.f_start_write = &umidi_start_write,
5981 	.f_stop_read = &umidi_stop_read,
5982 	.f_stop_write = &umidi_stop_write,
5983 	.f_open = &umidi_open,
5984 	.f_close = &umidi_close,
5985 	.f_ioctl = &umidi_ioctl,
5986 	.basename[0] = "umidi",
5987 };
5988 
5989 static int
umidi_probe(device_t dev)5990 umidi_probe(device_t dev)
5991 {
5992 	struct uaudio_softc *sc = device_get_softc(dev);
5993 	struct usb_attach_arg *uaa = device_get_ivars(dev);
5994 	struct umidi_chan *chan = &sc->sc_midi_chan;
5995 	struct umidi_sub_chan *sub;
5996 	int unit = device_get_unit(dev);
5997 	int error;
5998 	uint32_t n;
5999 
6000 	if (usb_test_quirk(uaa, UQ_SINGLE_CMD_MIDI))
6001 		chan->single_command = 1;
6002 
6003 	error = usbd_set_alt_interface_index(sc->sc_udev,
6004 	    chan->iface_index, chan->iface_alt_index);
6005 	if (error) {
6006 		DPRINTF("setting of alternate index failed: %s\n",
6007 		    usbd_errstr(error));
6008 		goto detach;
6009 	}
6010 	usbd_set_parent_iface(sc->sc_udev, chan->iface_index,
6011 	    sc->sc_mixer_iface_index);
6012 
6013 	error = usbd_transfer_setup(uaa->device, &chan->iface_index,
6014 	    chan->xfer, umidi_config, UMIDI_N_TRANSFER,
6015 	    chan, &chan->mtx);
6016 	if (error) {
6017 		DPRINTF("error=%s\n", usbd_errstr(error));
6018 		goto detach;
6019 	}
6020 	if (chan->xfer[UMIDI_TX_TRANSFER] == NULL &&
6021 	    chan->xfer[UMIDI_RX_TRANSFER] == NULL) {
6022 		DPRINTF("no BULK or INTERRUPT MIDI endpoint(s) found\n");
6023 		goto detach;
6024 	}
6025 
6026 	/*
6027 	 * Some USB MIDI device makers couldn't resist using
6028 	 * wMaxPacketSize = 4 for RX and TX BULK endpoints, although
6029 	 * that size is an unsupported value for FULL speed BULK
6030 	 * endpoints. The same applies to some HIGH speed MIDI devices
6031 	 * which are using a wMaxPacketSize different from 512 bytes.
6032 	 *
6033 	 * Refer to section 5.8.3 in USB 2.0 PDF: Cite: "All Host
6034 	 * Controllers are required to have support for 8-, 16-, 32-,
6035 	 * and 64-byte maximum packet sizes for full-speed bulk
6036 	 * endpoints and 512 bytes for high-speed bulk endpoints."
6037 	 */
6038 	if (chan->xfer[UMIDI_TX_TRANSFER] != NULL &&
6039 	    usbd_xfer_maxp_was_clamped(chan->xfer[UMIDI_TX_TRANSFER]))
6040 		chan->single_command = 1;
6041 
6042 	if (chan->single_command != 0)
6043 		device_printf(dev, "Single command MIDI quirk enabled\n");
6044 
6045 	if ((chan->max_emb_jack == 0) ||
6046 	    (chan->max_emb_jack > UMIDI_EMB_JACK_MAX)) {
6047 		chan->max_emb_jack = UMIDI_EMB_JACK_MAX;
6048 	}
6049 
6050 	for (n = 0; n < chan->max_emb_jack; n++) {
6051 		sub = &chan->sub[n];
6052 
6053 		error = usb_fifo_attach(sc->sc_udev, chan, &chan->mtx,
6054 		    &umidi_fifo_methods, &sub->fifo, unit, n,
6055 		    chan->iface_index,
6056 		    UID_ROOT, GID_OPERATOR, 0666);
6057 		if (error) {
6058 			goto detach;
6059 		}
6060 	}
6061 
6062 	mtx_lock(&chan->mtx);
6063 
6064 	/*
6065 	 * NOTE: At least one device will not work properly unless the
6066 	 * BULK IN pipe is open all the time. This might have to do
6067 	 * about that the internal queues of the device overflow if we
6068 	 * don't read them regularly.
6069 	 */
6070 	usbd_transfer_start(chan->xfer[UMIDI_RX_TRANSFER]);
6071 
6072 	mtx_unlock(&chan->mtx);
6073 
6074 	return (0);			/* success */
6075 
6076 detach:
6077 	return (ENXIO);			/* failure */
6078 }
6079 
6080 static int
umidi_detach(device_t dev)6081 umidi_detach(device_t dev)
6082 {
6083 	struct uaudio_softc *sc = device_get_softc(dev);
6084 	struct umidi_chan *chan = &sc->sc_midi_chan;
6085 	uint32_t n;
6086 
6087 	for (n = 0; n < UMIDI_EMB_JACK_MAX; n++)
6088 		usb_fifo_detach(&chan->sub[n].fifo);
6089 
6090 	mtx_lock(&chan->mtx);
6091 
6092 	usbd_transfer_stop(chan->xfer[UMIDI_RX_TRANSFER]);
6093 
6094 	mtx_unlock(&chan->mtx);
6095 
6096 	usbd_transfer_unsetup(chan->xfer, UMIDI_N_TRANSFER);
6097 
6098 	mtx_destroy(&chan->mtx);
6099 
6100 	return (0);
6101 }
6102 
6103 static void
uaudio_hid_rx_callback(struct usb_xfer * xfer,usb_error_t error)6104 uaudio_hid_rx_callback(struct usb_xfer *xfer, usb_error_t error)
6105 {
6106 	struct uaudio_softc *sc = usbd_xfer_softc(xfer);
6107 	const uint8_t *buffer = usbd_xfer_get_frame_buffer(xfer, 0);
6108 	struct snd_mixer *m;
6109 	uint8_t id;
6110 	int actlen;
6111 
6112 	usbd_xfer_status(xfer, &actlen, NULL, NULL, NULL);
6113 
6114 	switch (USB_GET_STATE(xfer)) {
6115 	case USB_ST_TRANSFERRED:
6116 		DPRINTF("actlen=%d\n", actlen);
6117 
6118 		if (actlen != 0 &&
6119 		    (sc->sc_hid.flags & UAUDIO_HID_HAS_ID)) {
6120 			id = *buffer;
6121 			buffer++;
6122 			actlen--;
6123 		} else {
6124 			id = 0;
6125 		}
6126 
6127 		m = sc->sc_child[0].mixer_dev;
6128 
6129 		if ((sc->sc_hid.flags & UAUDIO_HID_HAS_MUTE) &&
6130 		    (sc->sc_hid.mute_id == id) &&
6131 		    hid_get_data(buffer, actlen,
6132 		    &sc->sc_hid.mute_loc)) {
6133 			DPRINTF("Mute toggle\n");
6134 
6135 			mixer_hwvol_mute_locked(m);
6136 		}
6137 
6138 		if ((sc->sc_hid.flags & UAUDIO_HID_HAS_VOLUME_UP) &&
6139 		    (sc->sc_hid.volume_up_id == id) &&
6140 		    hid_get_data(buffer, actlen,
6141 		    &sc->sc_hid.volume_up_loc)) {
6142 			DPRINTF("Volume Up\n");
6143 
6144 			mixer_hwvol_step_locked(m, 1, 1);
6145 		}
6146 
6147 		if ((sc->sc_hid.flags & UAUDIO_HID_HAS_VOLUME_DOWN) &&
6148 		    (sc->sc_hid.volume_down_id == id) &&
6149 		    hid_get_data(buffer, actlen,
6150 		    &sc->sc_hid.volume_down_loc)) {
6151 			DPRINTF("Volume Down\n");
6152 
6153 			mixer_hwvol_step_locked(m, -1, -1);
6154 		}
6155 
6156 	case USB_ST_SETUP:
6157 tr_setup:
6158 		/* check if we can put more data into the FIFO */
6159 		usbd_xfer_set_frame_len(xfer, 0, usbd_xfer_max_len(xfer));
6160 		usbd_transfer_submit(xfer);
6161 		break;
6162 
6163 	default:			/* Error */
6164 
6165 		DPRINTF("error=%s\n", usbd_errstr(error));
6166 
6167 		if (error != USB_ERR_CANCELLED) {
6168 			/* try to clear stall first */
6169 			usbd_xfer_set_stall(xfer);
6170 			goto tr_setup;
6171 		}
6172 		break;
6173 	}
6174 }
6175 
6176 static int
uaudio_hid_probe(struct uaudio_softc * sc,struct usb_attach_arg * uaa)6177 uaudio_hid_probe(struct uaudio_softc *sc,
6178     struct usb_attach_arg *uaa)
6179 {
6180 	void *d_ptr;
6181 	uint32_t flags;
6182 	uint16_t d_len;
6183 	uint8_t id;
6184 	int error;
6185 
6186 	if (!(sc->sc_hid.flags & UAUDIO_HID_VALID))
6187 		return (-1);
6188 
6189 	if (sc->sc_child[0].mixer_lock == NULL)
6190 		return (-1);
6191 
6192 	/* Get HID descriptor */
6193 	error = usbd_req_get_hid_desc(uaa->device, NULL, &d_ptr,
6194 	    &d_len, M_TEMP, sc->sc_hid.iface_index);
6195 
6196 	if (error) {
6197 		DPRINTF("error reading report description\n");
6198 		return (-1);
6199 	}
6200 
6201 	/* check if there is an ID byte */
6202 	hid_report_size_max(d_ptr, d_len, hid_input, &id);
6203 
6204 	if (id != 0)
6205 		sc->sc_hid.flags |= UAUDIO_HID_HAS_ID;
6206 
6207 	if (hid_locate(d_ptr, d_len,
6208 	    HID_USAGE2(HUP_CONSUMER, 0xE9 /* Volume Increment */),
6209 	    hid_input, 0, &sc->sc_hid.volume_up_loc, &flags,
6210 	    &sc->sc_hid.volume_up_id)) {
6211 		if (flags & HIO_VARIABLE)
6212 			sc->sc_hid.flags |= UAUDIO_HID_HAS_VOLUME_UP;
6213 		DPRINTFN(1, "Found Volume Up key\n");
6214 	}
6215 
6216 	if (hid_locate(d_ptr, d_len,
6217 	    HID_USAGE2(HUP_CONSUMER, 0xEA /* Volume Decrement */),
6218 	    hid_input, 0, &sc->sc_hid.volume_down_loc, &flags,
6219 	    &sc->sc_hid.volume_down_id)) {
6220 		if (flags & HIO_VARIABLE)
6221 			sc->sc_hid.flags |= UAUDIO_HID_HAS_VOLUME_DOWN;
6222 		DPRINTFN(1, "Found Volume Down key\n");
6223 	}
6224 
6225 	if (hid_locate(d_ptr, d_len,
6226 	    HID_USAGE2(HUP_CONSUMER, 0xE2 /* Mute */),
6227 	    hid_input, 0, &sc->sc_hid.mute_loc, &flags,
6228 	    &sc->sc_hid.mute_id)) {
6229 		if (flags & HIO_VARIABLE)
6230 			sc->sc_hid.flags |= UAUDIO_HID_HAS_MUTE;
6231 		DPRINTFN(1, "Found Mute key\n");
6232 	}
6233 
6234 	free(d_ptr, M_TEMP);
6235 
6236 	if (!(sc->sc_hid.flags & (UAUDIO_HID_HAS_VOLUME_UP |
6237 	    UAUDIO_HID_HAS_VOLUME_DOWN |
6238 	    UAUDIO_HID_HAS_MUTE))) {
6239 		DPRINTFN(1, "Did not find any volume related keys\n");
6240 		return (-1);
6241 	}
6242 
6243 	/* prevent the uhid driver from attaching */
6244 	usbd_set_parent_iface(uaa->device, sc->sc_hid.iface_index,
6245 	    sc->sc_mixer_iface_index);
6246 
6247 	/* allocate USB transfers */
6248 	error = usbd_transfer_setup(uaa->device, &sc->sc_hid.iface_index,
6249 	    sc->sc_hid.xfer, uaudio_hid_config, UAUDIO_HID_N_TRANSFER,
6250 	    sc, sc->sc_child[0].mixer_lock);
6251 	if (error) {
6252 		DPRINTF("error=%s\n", usbd_errstr(error));
6253 		return (-1);
6254 	}
6255 	return (0);
6256 }
6257 
6258 static void
uaudio_hid_detach(struct uaudio_softc * sc)6259 uaudio_hid_detach(struct uaudio_softc *sc)
6260 {
6261 	usbd_transfer_unsetup(sc->sc_hid.xfer, UAUDIO_HID_N_TRANSFER);
6262 }
6263 
6264 DRIVER_MODULE_ORDERED(snd_uaudio, uhub, uaudio_driver, NULL, NULL, SI_ORDER_ANY);
6265 MODULE_DEPEND(snd_uaudio, usb, 1, 1, 1);
6266 MODULE_DEPEND(snd_uaudio, sound, SOUND_MINVER, SOUND_PREFVER, SOUND_MAXVER);
6267 MODULE_DEPEND(snd_uaudio, hid, 1, 1, 1);
6268 MODULE_VERSION(snd_uaudio, 1);
6269 USB_PNP_HOST_INFO(uaudio_devs);
6270 USB_PNP_HOST_INFO(uaudio_vendor_midi);
6271