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