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