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