xref: /linux/sound/usb/mixer.c (revision d158ee133e3af1f11739b9d37dde754fdeb62a9f)
1 // SPDX-License-Identifier: GPL-2.0-or-later
2 /*
3  *   (Tentative) USB Audio Driver for ALSA
4  *
5  *   Mixer control part
6  *
7  *   Copyright (c) 2002 by Takashi Iwai <tiwai@suse.de>
8  *
9  *   Many codes borrowed from audio.c by
10  *	    Alan Cox (alan@lxorguk.ukuu.org.uk)
11  *	    Thomas Sailer (sailer@ife.ee.ethz.ch)
12  */
13 
14 /*
15  * TODOs, for both the mixer and the streaming interfaces:
16  *
17  *  - support for UAC2 effect units
18  *  - support for graphical equalizers
19  *  - RANGE and MEM set commands (UAC2)
20  *  - RANGE and MEM interrupt dispatchers (UAC2)
21  *  - audio channel clustering (UAC2)
22  *  - audio sample rate converter units (UAC2)
23  *  - proper handling of clock multipliers (UAC2)
24  *  - dispatch clock change notifications (UAC2)
25  *  	- stop PCM streams which use a clock that became invalid
26  *  	- stop PCM streams which use a clock selector that has changed
27  *  	- parse available sample rates again when clock sources changed
28  */
29 
30 #include <linux/bitops.h>
31 #include <linux/init.h>
32 #include <linux/list.h>
33 #include <linux/log2.h>
34 #include <linux/slab.h>
35 #include <linux/string.h>
36 #include <linux/usb.h>
37 #include <linux/usb/audio.h>
38 #include <linux/usb/audio-v2.h>
39 #include <linux/usb/audio-v3.h>
40 
41 #include <sound/core.h>
42 #include <sound/control.h>
43 #include <sound/hwdep.h>
44 #include <sound/info.h>
45 #include <sound/tlv.h>
46 
47 #include "usbaudio.h"
48 #include "mixer.h"
49 #include "helper.h"
50 #include "mixer_quirks.h"
51 #include "power.h"
52 
53 #define MAX_ID_ELEMS	256
54 
55 struct usb_audio_term {
56 	int id;
57 	int type;
58 	int channels;
59 	unsigned int chconfig;
60 	int name;
61 };
62 
63 struct usbmix_name_map;
64 
65 struct mixer_build {
66 	struct snd_usb_audio *chip;
67 	struct usb_mixer_interface *mixer;
68 	unsigned char *buffer;
69 	unsigned int buflen;
70 	DECLARE_BITMAP(unitbitmap, MAX_ID_ELEMS);
71 	DECLARE_BITMAP(termbitmap, MAX_ID_ELEMS);
72 	struct usb_audio_term oterm;
73 	const struct usbmix_name_map *map;
74 	const struct usbmix_selector_map *selector_map;
75 };
76 
77 /*E-mu 0202/0404/0204 eXtension Unit(XU) control*/
78 enum {
79 	USB_XU_CLOCK_RATE 		= 0xe301,
80 	USB_XU_CLOCK_SOURCE		= 0xe302,
81 	USB_XU_DIGITAL_IO_STATUS	= 0xe303,
82 	USB_XU_DEVICE_OPTIONS		= 0xe304,
83 	USB_XU_DIRECT_MONITORING	= 0xe305,
84 	USB_XU_METERING			= 0xe306
85 };
86 enum {
87 	USB_XU_CLOCK_SOURCE_SELECTOR = 0x02,	/* clock source*/
88 	USB_XU_CLOCK_RATE_SELECTOR = 0x03,	/* clock rate */
89 	USB_XU_DIGITAL_FORMAT_SELECTOR = 0x01,	/* the spdif format */
90 	USB_XU_SOFT_LIMIT_SELECTOR = 0x03	/* soft limiter */
91 };
92 
93 /*
94  * manual mapping of mixer names
95  * if the mixer topology is too complicated and the parsed names are
96  * ambiguous, add the entries in usbmixer_maps.c.
97  */
98 #include "mixer_maps.c"
99 
100 static const struct usbmix_name_map *
101 find_map(const struct usbmix_name_map *p, int unitid, int control)
102 {
103 	if (!p)
104 		return NULL;
105 
106 	for (; p->id; p++) {
107 		if (p->id == unitid &&
108 		    (!control || !p->control || control == p->control))
109 			return p;
110 	}
111 	return NULL;
112 }
113 
114 /* get the mapped name if the unit matches */
115 static int
116 check_mapped_name(const struct usbmix_name_map *p, char *buf, int buflen)
117 {
118 	int len;
119 
120 	if (!p || !p->name)
121 		return 0;
122 
123 	buflen--;
124 	len = strscpy(buf, p->name, buflen);
125 	return len < 0 ? buflen : len;
126 }
127 
128 /* ignore the error value if ignore_ctl_error flag is set */
129 #define filter_error(cval, err) \
130 	((cval)->head.mixer->ignore_ctl_error ? 0 : (err))
131 
132 /* check whether the control should be ignored */
133 static inline int
134 check_ignored_ctl(const struct usbmix_name_map *p)
135 {
136 	if (!p || p->name || p->dB)
137 		return 0;
138 	return 1;
139 }
140 
141 /* dB mapping */
142 static inline void check_mapped_dB(const struct usbmix_name_map *p,
143 				   struct usb_mixer_elem_info *cval)
144 {
145 	if (p && p->dB) {
146 		cval->dBmin = p->dB->min;
147 		cval->dBmax = p->dB->max;
148 		cval->min_mute = p->dB->min_mute;
149 		cval->initialized = 1;
150 	}
151 }
152 
153 /* get the mapped selector source name */
154 static int check_mapped_selector_name(struct mixer_build *state, int unitid,
155 				      int index, char *buf, int buflen)
156 {
157 	const struct usbmix_selector_map *p;
158 	int len;
159 
160 	if (!state->selector_map)
161 		return 0;
162 	for (p = state->selector_map; p->id; p++) {
163 		if (p->id == unitid && index < p->count) {
164 			len = strscpy(buf, p->names[index], buflen);
165 			return len < 0 ? buflen : len;
166 		}
167 	}
168 	return 0;
169 }
170 
171 /*
172  * find an audio control unit with the given unit id
173  */
174 static void *find_audio_control_unit(struct mixer_build *state,
175 				     unsigned char unit)
176 {
177 	/* we just parse the header */
178 	struct uac_feature_unit_descriptor *hdr = NULL;
179 
180 	while ((hdr = snd_usb_find_desc(state->buffer, state->buflen, hdr,
181 					USB_DT_CS_INTERFACE)) != NULL) {
182 		if (hdr->bLength >= 4 &&
183 		    hdr->bDescriptorSubtype >= UAC_INPUT_TERMINAL &&
184 		    hdr->bDescriptorSubtype <= UAC3_SAMPLE_RATE_CONVERTER &&
185 		    hdr->bUnitID == unit)
186 			return hdr;
187 	}
188 
189 	return NULL;
190 }
191 
192 /*
193  * copy a string with the given id
194  */
195 static int snd_usb_copy_string_desc(struct snd_usb_audio *chip,
196 				    int index, char *buf, int maxlen)
197 {
198 	int len = usb_string(chip->dev, index, buf, maxlen - 1);
199 
200 	if (len < 0)
201 		return 0;
202 
203 	buf[len] = 0;
204 	return len;
205 }
206 
207 /*
208  * convert from the byte/word on usb descriptor to the zero-based integer
209  */
210 static int convert_signed_value(struct usb_mixer_elem_info *cval, int val)
211 {
212 	switch (cval->val_type) {
213 	case USB_MIXER_BOOLEAN:
214 		return !!val;
215 	case USB_MIXER_INV_BOOLEAN:
216 		return !val;
217 	case USB_MIXER_U8:
218 		val &= 0xff;
219 		break;
220 	case USB_MIXER_S8:
221 		val &= 0xff;
222 		if (val >= 0x80)
223 			val -= 0x100;
224 		break;
225 	case USB_MIXER_U16:
226 		val &= 0xffff;
227 		break;
228 	case USB_MIXER_S16:
229 		val &= 0xffff;
230 		if (val >= 0x8000)
231 			val -= 0x10000;
232 		break;
233 	}
234 	return val;
235 }
236 
237 /*
238  * convert from the zero-based int to the byte/word for usb descriptor
239  */
240 static int convert_bytes_value(struct usb_mixer_elem_info *cval, int val)
241 {
242 	switch (cval->val_type) {
243 	case USB_MIXER_BOOLEAN:
244 		return !!val;
245 	case USB_MIXER_INV_BOOLEAN:
246 		return !val;
247 	case USB_MIXER_S8:
248 	case USB_MIXER_U8:
249 		return val & 0xff;
250 	case USB_MIXER_S16:
251 	case USB_MIXER_U16:
252 		return val & 0xffff;
253 	}
254 	return 0; /* not reached */
255 }
256 
257 static int get_relative_value(struct usb_mixer_elem_info *cval, int val)
258 {
259 	if (!cval->res)
260 		cval->res = 1;
261 	if (val < cval->min)
262 		return 0;
263 	else if (val >= cval->max)
264 		return DIV_ROUND_UP(cval->max - cval->min, cval->res);
265 	else
266 		return (val - cval->min) / cval->res;
267 }
268 
269 static int get_abs_value(struct usb_mixer_elem_info *cval, int val)
270 {
271 	if (val < 0)
272 		return cval->min;
273 	if (!cval->res)
274 		cval->res = 1;
275 	val *= cval->res;
276 	val += cval->min;
277 	if (val > cval->max)
278 		return cval->max;
279 	return val;
280 }
281 
282 static int uac2_ctl_value_size(int val_type)
283 {
284 	switch (val_type) {
285 	case USB_MIXER_S32:
286 	case USB_MIXER_U32:
287 		return 4;
288 	case USB_MIXER_S16:
289 	case USB_MIXER_U16:
290 		return 2;
291 	default:
292 		return 1;
293 	}
294 	return 0; /* unreachable */
295 }
296 
297 
298 /*
299  * retrieve a mixer value
300  */
301 
302 static inline int mixer_ctrl_intf(struct usb_mixer_interface *mixer)
303 {
304 	return get_iface_desc(mixer->hostif)->bInterfaceNumber;
305 }
306 
307 /* send a request for UAC1 feature & mixer unit */
308 static int request_get_ctl_v1(struct usb_mixer_elem_info *cval,
309 			      u8 request, int validx, int *value_ret)
310 {
311 	struct snd_usb_audio *chip = cval->head.mixer->chip;
312 	unsigned char buf[2];
313 	int val_len = cval->val_type >= USB_MIXER_S16 ? 2 : 1;
314 	int timeout = 10;
315 	int idx = 0, err;
316 
317 	CLASS(snd_usb_lock, pm)(chip);
318 	if (pm.err < 0)
319 		return -EIO;
320 
321 	validx += cval->idx_off;
322 
323 	while (timeout-- > 0) {
324 		idx = mixer_ctrl_intf(cval->head.mixer) | (cval->head.id << 8);
325 		err = snd_usb_ctl_msg(chip->dev, usb_rcvctrlpipe(chip->dev, 0), request,
326 				      USB_RECIP_INTERFACE | USB_TYPE_CLASS | USB_DIR_IN,
327 				      validx, idx, buf, val_len);
328 		if (err >= val_len) {
329 			*value_ret = convert_signed_value(cval, snd_usb_combine_bytes(buf, val_len));
330 			return 0;
331 		} else if (err == -ETIMEDOUT) {
332 			return err;
333 		}
334 	}
335 	usb_audio_dbg(chip,
336 		"cannot get ctl value: req = %#x, wValue = %#x, wIndex = %#x, type = %d\n",
337 		request, validx, idx, cval->val_type);
338 	return -EINVAL;
339 }
340 
341 /* convert the given UAC1 wValue (ICN|OCN) to UAC2 MCN */
342 static unsigned char to_mcn(const struct usb_mixer_elem_info *cval,
343 			    unsigned int validx)
344 {
345 	unsigned char m = (validx >> 8) & 0xff; /* 1-based input channel */
346 	unsigned char v = validx & 0xff; /* 1-based output channel */
347 
348 	/* num_inputs * num_outputs is guaranteed to be < 256 */
349 	return (m - 1) * cval->num_outputs + (v - 1);
350 }
351 
352 /* send a request for UAC2 feature & mixer unit */
353 static int request_get_ctl_v2(struct usb_mixer_elem_info *cval,
354 			      u8 request, int validx, unsigned char *buf,
355 			      int size)
356 {
357 	struct snd_usb_audio *chip = cval->head.mixer->chip;
358 	int idx, ret;
359 
360 	CLASS(snd_usb_lock, pm)(chip);
361 	if (pm.err)
362 		return -EIO;
363 
364 	validx += cval->idx_off;
365 
366 	/* correct wValue for UAC2 mixer control with MCN */
367 	if (cval->v2_mixer)
368 		validx = (UAC2_MU_MIXER << 8) | to_mcn(cval, validx);
369 
370 	memset(buf, 0, size);
371 	idx = mixer_ctrl_intf(cval->head.mixer) | (cval->head.id << 8);
372 	ret = snd_usb_ctl_msg(chip->dev, usb_rcvctrlpipe(chip->dev, 0),
373 			      request,
374 			      USB_RECIP_INTERFACE | USB_TYPE_CLASS | USB_DIR_IN,
375 			      validx, idx, buf, size);
376 	if (ret < 0)
377 		usb_audio_dbg(chip,
378 			"cannot get ctl value: req = %#x, wValue = %#x, wIndex = %#x, type = %d\n",
379 			request, validx, idx, cval->val_type);
380 
381 	return ret;
382 }
383 
384 /* read the current value for UAC2 */
385 static int get_ctl_value_v2(struct usb_mixer_elem_info *cval,
386 			    int validx, int *value_ret)
387 {
388 	/* enough space for one value */
389 	unsigned char buf[sizeof(__u32)];
390 	int ret, val_size;
391 
392 	val_size = uac2_ctl_value_size(cval->val_type);
393 
394 	ret = request_get_ctl_v2(cval, UAC2_CS_CUR, validx, buf, val_size);
395 	if (ret < 0)
396 		return ret;
397 
398 	*value_ret = convert_signed_value(cval,
399 					  snd_usb_combine_bytes(buf, val_size));
400 	return 0;
401 }
402 
403 /* read the current value */
404 static int get_cur_ctl_value(struct usb_mixer_elem_info *cval,
405 			     int validx, int *value_ret)
406 {
407 	return (cval->head.mixer->protocol == UAC_VERSION_1) ?
408 		request_get_ctl_v1(cval, UAC_GET_CUR, validx, value_ret) :
409 		get_ctl_value_v2(cval, validx, value_ret);
410 }
411 
412 /* channel = 0: master, 1 = first channel */
413 static inline int get_cur_mix_raw(struct usb_mixer_elem_info *cval,
414 				  int channel, int *value)
415 {
416 	return get_cur_ctl_value(cval,
417 				 (cval->control << 8) | channel,
418 				 value);
419 }
420 
421 int snd_usb_get_cur_mix_value(struct usb_mixer_elem_info *cval,
422 			     int channel, int index, int *value)
423 {
424 	int err;
425 
426 	if (test_bit(channel, cval->cached)) {
427 		*value = cval->cache_val[index];
428 		return 0;
429 	}
430 
431 	/* The current value is always provided by the cache after initialization. */
432 	if (cval->get_cur_broken)
433 		return -ENXIO;
434 
435 	err = get_cur_mix_raw(cval, channel, value);
436 	if (err < 0) {
437 		if (!cval->head.mixer->ignore_ctl_error)
438 			usb_audio_dbg(cval->head.mixer->chip,
439 				"cannot get current value for control %d ch %d: err = %d\n",
440 				      cval->control, channel, err);
441 		return err;
442 	}
443 	set_bit(channel, cval->cached);
444 	cval->cache_val[index] = *value;
445 	return 0;
446 }
447 
448 /* extract the mixer min/max/res info from UAC1 feature / mixer unit */
449 static int get_ctl_range_v1(struct usb_mixer_elem_info *cval, int validx)
450 {
451 	int last_valid_res;
452 
453 	if (request_get_ctl_v1(cval, UAC_GET_MAX, validx, &cval->max) < 0 ||
454 	    request_get_ctl_v1(cval, UAC_GET_MIN, validx, &cval->min) < 0) {
455 		usb_audio_err(cval->head.mixer->chip,
456 			      "%d:%d: cannot get min/max values for control %d (id %d)\n",
457 			      cval->head.id, mixer_ctrl_intf(cval->head.mixer),
458 			      cval->control, cval->head.id);
459 		return -EAGAIN; /* handled by the caller later again */
460 	}
461 
462 	if (request_get_ctl_v1(cval, UAC_GET_RES, validx, &cval->res) < 0) {
463 		cval->res = 1;
464 		return 0;
465 	}
466 
467 	last_valid_res = cval->res;
468 	while (cval->res > 1) {
469 		if (snd_usb_mixer_set_ctl_value(cval, UAC_SET_RES,
470 						validx, cval->res / 2) < 0)
471 			break;
472 		cval->res /= 2;
473 	}
474 	if (request_get_ctl_v1(cval, UAC_GET_RES, validx, &cval->res) < 0)
475 		cval->res = last_valid_res;
476 
477 	return 0;
478 }
479 
480 /* extract the mixer min/max/res info from UAC2 feature / mixer unit */
481 static int get_ctl_range_v2(struct usb_mixer_elem_info *cval, int validx)
482 {
483 	/* enough space for one range */
484 	unsigned char buf[sizeof(__u16) + 3 * sizeof(__u32)];
485 	unsigned char *val;
486 	int val_size, size;
487 
488 	val_size = uac2_ctl_value_size(cval->val_type);
489 	size = sizeof(__u16) + 3 * val_size;
490 
491 	if (request_get_ctl_v2(cval, UAC2_CS_RANGE, validx, buf, size) < 0) {
492 		usb_audio_err(cval->head.mixer->chip,
493 			      "%d:%d: cannot get RANGE values for control %d (id %d)\n",
494 			      cval->head.id, mixer_ctrl_intf(cval->head.mixer),
495 			      cval->control, cval->head.id);
496 		return -EAGAIN; /* handled by the caller later again */
497 	}
498 
499 	/* FIXME: how should we handle multiple triplets here? */
500 	val = buf + 2;
501 	cval->min = convert_signed_value(cval, snd_usb_combine_bytes(val, val_size));
502 	val += val_size;
503 	cval->max = convert_signed_value(cval, snd_usb_combine_bytes(val, val_size));
504 	val += val_size;
505 	cval->res = convert_signed_value(cval, snd_usb_combine_bytes(val, val_size));
506 	return 0;
507 }
508 
509 /* extract the mixer min/max/res info */
510 static int get_ctl_range(struct usb_mixer_elem_info *cval, int validx)
511 {
512 	switch (cval->head.mixer->protocol) {
513 	case UAC_VERSION_1:
514 		return get_ctl_range_v1(cval, validx);
515 	case UAC_VERSION_2:
516 	case UAC_VERSION_3:
517 		return get_ctl_range_v2(cval, validx);
518 	default:
519 		return -EINVAL;
520 	}
521 }
522 
523 /*
524  * set a mixer value
525  */
526 
527 int snd_usb_mixer_set_ctl_value(struct usb_mixer_elem_info *cval,
528 				int request, int validx, int value_set)
529 {
530 	struct snd_usb_audio *chip = cval->head.mixer->chip;
531 	unsigned char buf[4];
532 	int idx = 0, val_len, err, timeout = 10;
533 
534 	validx += cval->idx_off;
535 
536 
537 	if (cval->head.mixer->protocol == UAC_VERSION_1) {
538 		val_len = cval->val_type >= USB_MIXER_S16 ? 2 : 1;
539 	} else { /* UAC_VERSION_2/3 */
540 		val_len = uac2_ctl_value_size(cval->val_type);
541 
542 		/* FIXME */
543 		if (request != UAC_SET_CUR) {
544 			usb_audio_dbg(chip, "RANGE setting not yet supported\n");
545 			return -EINVAL;
546 		}
547 
548 		request = UAC2_CS_CUR;
549 
550 		/* correct wValue for UAC2 mixer control with MCN */
551 		if (cval->v2_mixer)
552 			validx = (UAC2_MU_MIXER << 8) | to_mcn(cval, validx);
553 	}
554 
555 	value_set = convert_bytes_value(cval, value_set);
556 	buf[0] = value_set & 0xff;
557 	buf[1] = (value_set >> 8) & 0xff;
558 	buf[2] = (value_set >> 16) & 0xff;
559 	buf[3] = (value_set >> 24) & 0xff;
560 
561 	CLASS(snd_usb_lock, pm)(chip);
562 	if (pm.err < 0)
563 		return -EIO;
564 
565 	while (timeout-- > 0) {
566 		idx = mixer_ctrl_intf(cval->head.mixer) | (cval->head.id << 8);
567 		err = snd_usb_ctl_msg(chip->dev,
568 				      usb_sndctrlpipe(chip->dev, 0), request,
569 				      USB_RECIP_INTERFACE | USB_TYPE_CLASS | USB_DIR_OUT,
570 				      validx, idx, buf, val_len);
571 		if (err >= 0)
572 			return 0;
573 		else if (err == -ETIMEDOUT)
574 			return err;
575 	}
576 	usb_audio_dbg(chip, "cannot set ctl value: req = %#x, wValue = %#x, wIndex = %#x, type = %d, data = %#x/%#x\n",
577 		      request, validx, idx, cval->val_type, buf[0], buf[1]);
578 	return -EINVAL;
579 }
580 
581 static int set_cur_ctl_value(struct usb_mixer_elem_info *cval,
582 			     int validx, int value)
583 {
584 	return snd_usb_mixer_set_ctl_value(cval, UAC_SET_CUR, validx, value);
585 }
586 
587 int snd_usb_set_cur_mix_value(struct usb_mixer_elem_info *cval, int channel,
588 			     int index, int value)
589 {
590 	int err;
591 	unsigned int read_only = (channel == 0) ?
592 		cval->master_readonly :
593 		cval->ch_readonly & BIT(channel - 1);
594 
595 	if (read_only) {
596 		usb_audio_dbg(cval->head.mixer->chip,
597 			      "%s(): channel %d of control %d is read_only\n",
598 			    __func__, channel, cval->control);
599 		return 0;
600 	}
601 
602 	err = snd_usb_mixer_set_ctl_value(cval,
603 					  UAC_SET_CUR, (cval->control << 8) | channel,
604 					  value);
605 	if (err < 0)
606 		return err;
607 	set_bit(channel, cval->cached);
608 	cval->cache_val[index] = value;
609 	return 0;
610 }
611 
612 /*
613  * TLV callback for mixer volume controls
614  */
615 int snd_usb_mixer_vol_tlv(struct snd_kcontrol *kcontrol, int op_flag,
616 			 unsigned int size, unsigned int __user *_tlv)
617 {
618 	struct usb_mixer_elem_info *cval = snd_kcontrol_chip(kcontrol);
619 	DECLARE_TLV_DB_MINMAX(scale, 0, 0);
620 
621 	if (size < sizeof(scale))
622 		return -ENOMEM;
623 	if (cval->min_mute)
624 		scale[0] = SNDRV_CTL_TLVT_DB_MINMAX_MUTE;
625 	scale[2] = cval->dBmin;
626 	scale[3] = cval->dBmax;
627 	if (copy_to_user(_tlv, scale, sizeof(scale)))
628 		return -EFAULT;
629 	return 0;
630 }
631 
632 /*
633  * parser routines begin here...
634  */
635 
636 static int parse_audio_unit(struct mixer_build *state, int unitid);
637 
638 
639 /*
640  * check if the input/output channel routing is enabled on the given bitmap.
641  * used for mixer unit parser
642  */
643 static int check_matrix_bitmap(unsigned char *bmap,
644 			       int ich, int och, int num_outs)
645 {
646 	int idx = ich * num_outs + och;
647 	return bmap[idx >> 3] & (0x80 >> (idx & 7));
648 }
649 
650 /*
651  * add an alsa control element
652  * when @look_for_empty is set, search and increment the index until an empty
653  * slot is found.
654  *
655  * if failed, give up and free the control instance.
656  */
657 
658 int snd_usb_mixer_add_list(struct usb_mixer_elem_list *list,
659 			   struct snd_kcontrol *kctl,
660 			   bool is_std_info,
661 			   bool look_for_empty)
662 {
663 	struct usb_mixer_interface *mixer = list->mixer;
664 	int err;
665 
666 	if (look_for_empty) {
667 		while (snd_ctl_find_id(mixer->chip->card, &kctl->id))
668 			kctl->id.index++;
669 	}
670 
671 	err = snd_ctl_add(mixer->chip->card, kctl);
672 	if (err < 0) {
673 		usb_audio_dbg(mixer->chip, "cannot add control (err = %d)\n",
674 			      err);
675 		return err;
676 	}
677 	list->kctl = kctl;
678 	list->is_std_info = is_std_info;
679 	list->next_id_elem = mixer->id_elems[list->id];
680 	mixer->id_elems[list->id] = list;
681 	return 0;
682 }
683 
684 /*
685  * get a terminal name string
686  */
687 
688 static struct iterm_name_combo {
689 	int type;
690 	char *name;
691 } iterm_names[] = {
692 	{ 0x0300, "Output" },
693 	{ 0x0301, "Speaker" },
694 	{ 0x0302, "Headphone" },
695 	{ 0x0303, "HMD Audio" },
696 	{ 0x0304, "Desktop Speaker" },
697 	{ 0x0305, "Room Speaker" },
698 	{ 0x0306, "Com Speaker" },
699 	{ 0x0307, "LFE" },
700 	{ 0x0600, "External In" },
701 	{ 0x0601, "Analog In" },
702 	{ 0x0602, "Digital In" },
703 	{ 0x0603, "Line" },
704 	{ 0x0604, "Legacy In" },
705 	{ 0x0605, "IEC958 In" },
706 	{ 0x0606, "1394 DA Stream" },
707 	{ 0x0607, "1394 DV Stream" },
708 	{ 0x0700, "Embedded" },
709 	{ 0x0701, "Noise Source" },
710 	{ 0x0702, "Equalization Noise" },
711 	{ 0x0703, "CD" },
712 	{ 0x0704, "DAT" },
713 	{ 0x0705, "DCC" },
714 	{ 0x0706, "MiniDisk" },
715 	{ 0x0707, "Analog Tape" },
716 	{ 0x0708, "Phonograph" },
717 	{ 0x0709, "VCR Audio" },
718 	{ 0x070a, "Video Disk Audio" },
719 	{ 0x070b, "DVD Audio" },
720 	{ 0x070c, "TV Tuner Audio" },
721 	{ 0x070d, "Satellite Rec Audio" },
722 	{ 0x070e, "Cable Tuner Audio" },
723 	{ 0x070f, "DSS Audio" },
724 	{ 0x0710, "Radio Receiver" },
725 	{ 0x0711, "Radio Transmitter" },
726 	{ 0x0712, "Multi-Track Recorder" },
727 	{ 0x0713, "Synthesizer" },
728 	{ 0 },
729 };
730 
731 static int get_term_name(struct snd_usb_audio *chip, struct usb_audio_term *iterm,
732 			 unsigned char *name, int maxlen, int term_only)
733 {
734 	struct iterm_name_combo *names;
735 	int len;
736 
737 	if (iterm->name) {
738 		len = snd_usb_copy_string_desc(chip, iterm->name,
739 						name, maxlen);
740 		if (len)
741 			return len;
742 	}
743 
744 	/* virtual type - not a real terminal */
745 	if (iterm->type >> 16) {
746 		if (term_only)
747 			return 0;
748 		switch (iterm->type >> 16) {
749 		case UAC3_SELECTOR_UNIT:
750 			return strscpy(name, "Selector", maxlen);
751 		case UAC3_PROCESSING_UNIT:
752 			return strscpy(name, "Process Unit", maxlen);
753 		case UAC3_EXTENSION_UNIT:
754 			return strscpy(name, "Ext Unit", maxlen);
755 		case UAC3_MIXER_UNIT:
756 			return strscpy(name, "Mixer", maxlen);
757 		default:
758 			return scnprintf(name, maxlen, "Unit %d", iterm->id);
759 		}
760 	}
761 
762 	switch (iterm->type & 0xff00) {
763 	case 0x0100:
764 		return strscpy(name, "PCM", maxlen);
765 	case 0x0200:
766 		return strscpy(name, "Mic", maxlen);
767 	case 0x0400:
768 		return strscpy(name, "Headset", maxlen);
769 	case 0x0500:
770 		return strscpy(name, "Phone", maxlen);
771 	}
772 
773 	for (names = iterm_names; names->type; names++)
774 		if (names->type == iterm->type)
775 			return strscpy(name, names->name, maxlen);
776 
777 	return 0;
778 }
779 
780 /*
781  * Get logical cluster information for UAC3 devices.
782  */
783 static int get_cluster_channels_v3(struct mixer_build *state, unsigned int cluster_id)
784 {
785 	struct uac3_cluster_header_descriptor c_header;
786 	int err;
787 
788 	err = snd_usb_ctl_msg(state->chip->dev,
789 			usb_rcvctrlpipe(state->chip->dev, 0),
790 			UAC3_CS_REQ_HIGH_CAPABILITY_DESCRIPTOR,
791 			USB_RECIP_INTERFACE | USB_TYPE_CLASS | USB_DIR_IN,
792 			cluster_id,
793 			snd_usb_ctrl_intf(state->mixer->hostif),
794 			&c_header, sizeof(c_header));
795 	if (err < 0)
796 		goto error;
797 	if (err != sizeof(c_header)) {
798 		err = -EIO;
799 		goto error;
800 	}
801 
802 	return c_header.bNrChannels;
803 
804 error:
805 	usb_audio_err(state->chip, "cannot request logical cluster ID: %d (err: %d)\n", cluster_id, err);
806 	return err;
807 }
808 
809 /*
810  * Get number of channels for a Mixer Unit.
811  */
812 static int uac_mixer_unit_get_channels(struct mixer_build *state,
813 				       struct uac_mixer_unit_descriptor *desc)
814 {
815 	int mu_channels;
816 
817 	switch (state->mixer->protocol) {
818 	case UAC_VERSION_1:
819 	case UAC_VERSION_2:
820 	default:
821 		if (desc->bLength < sizeof(*desc) + desc->bNrInPins + 1)
822 			return 0; /* no bmControls -> skip */
823 		mu_channels = uac_mixer_unit_bNrChannels(desc);
824 		break;
825 	case UAC_VERSION_3:
826 		mu_channels = get_cluster_channels_v3(state,
827 				uac3_mixer_unit_wClusterDescrID(desc));
828 		break;
829 	}
830 
831 	return mu_channels;
832 }
833 
834 /*
835  * Parse Input Terminal Unit
836  */
837 static int __check_input_term(struct mixer_build *state, int id,
838 			      struct usb_audio_term *term);
839 
840 static int parse_term_uac1_iterm_unit(struct mixer_build *state,
841 				      struct usb_audio_term *term,
842 				      void *p1, int id)
843 {
844 	struct uac_input_terminal_descriptor *d = p1;
845 
846 	term->type = le16_to_cpu(d->wTerminalType);
847 	term->channels = d->bNrChannels;
848 	term->chconfig = le16_to_cpu(d->wChannelConfig);
849 	term->name = d->iTerminal;
850 	return 0;
851 }
852 
853 static int parse_term_uac2_iterm_unit(struct mixer_build *state,
854 				      struct usb_audio_term *term,
855 				      void *p1, int id)
856 {
857 	struct uac2_input_terminal_descriptor *d = p1;
858 	int err;
859 
860 	/* call recursively to verify the referenced clock entity */
861 	err = __check_input_term(state, d->bCSourceID, term);
862 	if (err < 0)
863 		return err;
864 
865 	/* save input term properties after recursion,
866 	 * to ensure they are not overridden by the recursion calls
867 	 */
868 	term->id = id;
869 	term->type = le16_to_cpu(d->wTerminalType);
870 	term->channels = d->bNrChannels;
871 	term->chconfig = le32_to_cpu(d->bmChannelConfig);
872 	term->name = d->iTerminal;
873 	return 0;
874 }
875 
876 static int parse_term_uac3_iterm_unit(struct mixer_build *state,
877 				      struct usb_audio_term *term,
878 				      void *p1, int id)
879 {
880 	struct uac3_input_terminal_descriptor *d = p1;
881 	int err;
882 
883 	/* call recursively to verify the referenced clock entity */
884 	err = __check_input_term(state, d->bCSourceID, term);
885 	if (err < 0)
886 		return err;
887 
888 	/* save input term properties after recursion,
889 	 * to ensure they are not overridden by the recursion calls
890 	 */
891 	term->id = id;
892 	term->type = le16_to_cpu(d->wTerminalType);
893 
894 	err = get_cluster_channels_v3(state, le16_to_cpu(d->wClusterDescrID));
895 	if (err < 0)
896 		return err;
897 	term->channels = err;
898 
899 	/* REVISIT: UAC3 IT doesn't have channels cfg */
900 	term->chconfig = 0;
901 
902 	term->name = le16_to_cpu(d->wTerminalDescrStr);
903 	return 0;
904 }
905 
906 static int parse_term_mixer_unit(struct mixer_build *state,
907 				 struct usb_audio_term *term,
908 				 void *p1, int id)
909 {
910 	struct uac_mixer_unit_descriptor *d = p1;
911 	int protocol = state->mixer->protocol;
912 	int err;
913 
914 	err = uac_mixer_unit_get_channels(state, d);
915 	if (err <= 0)
916 		return err;
917 
918 	term->type = UAC3_MIXER_UNIT << 16; /* virtual type */
919 	term->channels = err;
920 	if (protocol != UAC_VERSION_3) {
921 		term->chconfig = uac_mixer_unit_wChannelConfig(d, protocol);
922 		term->name = uac_mixer_unit_iMixer(d);
923 	}
924 	return 0;
925 }
926 
927 static int parse_term_selector_unit(struct mixer_build *state,
928 				    struct usb_audio_term *term,
929 				    void *p1, int id)
930 {
931 	struct uac_selector_unit_descriptor *d = p1;
932 	int err;
933 
934 	/* call recursively to retrieve the channel info */
935 	err = __check_input_term(state, d->baSourceID[0], term);
936 	if (err < 0)
937 		return err;
938 	term->type = UAC3_SELECTOR_UNIT << 16; /* virtual type */
939 	term->id = id;
940 	if (state->mixer->protocol != UAC_VERSION_3)
941 		term->name = uac_selector_unit_iSelector(d);
942 	return 0;
943 }
944 
945 static int parse_term_proc_unit(struct mixer_build *state,
946 				struct usb_audio_term *term,
947 				void *p1, int id, int vtype)
948 {
949 	struct uac_processing_unit_descriptor *d = p1;
950 	int protocol = state->mixer->protocol;
951 	int err;
952 
953 	if (d->bNrInPins) {
954 		/* call recursively to retrieve the channel info */
955 		err = __check_input_term(state, d->baSourceID[0], term);
956 		if (err < 0)
957 			return err;
958 	}
959 
960 	term->type = vtype << 16; /* virtual type */
961 	term->id = id;
962 
963 	if (protocol == UAC_VERSION_3)
964 		return 0;
965 
966 	if (!term->channels) {
967 		term->channels = uac_processing_unit_bNrChannels(d);
968 		term->chconfig = uac_processing_unit_wChannelConfig(d, protocol);
969 	}
970 	term->name = uac_processing_unit_iProcessing(d, protocol);
971 	return 0;
972 }
973 
974 static int parse_term_effect_unit(struct mixer_build *state,
975 				  struct usb_audio_term *term,
976 				  void *p1, int id)
977 {
978 	struct uac2_effect_unit_descriptor *d = p1;
979 	int err;
980 
981 	err = __check_input_term(state, d->bSourceID, term);
982 	if (err < 0)
983 		return err;
984 	term->type = UAC3_EFFECT_UNIT << 16; /* virtual type */
985 	term->id = id;
986 	return 0;
987 }
988 
989 static int parse_term_uac2_clock_source(struct mixer_build *state,
990 					struct usb_audio_term *term,
991 					void *p1, int id)
992 {
993 	struct uac_clock_source_descriptor *d = p1;
994 
995 	term->type = UAC2_CLOCK_SOURCE << 16; /* virtual type */
996 	term->id = id;
997 	term->name = d->iClockSource;
998 	return 0;
999 }
1000 
1001 static int parse_term_uac3_clock_source(struct mixer_build *state,
1002 					struct usb_audio_term *term,
1003 					void *p1, int id)
1004 {
1005 	struct uac3_clock_source_descriptor *d = p1;
1006 
1007 	term->type = UAC3_CLOCK_SOURCE << 16; /* virtual type */
1008 	term->id = id;
1009 	term->name = le16_to_cpu(d->wClockSourceStr);
1010 	return 0;
1011 }
1012 
1013 #define PTYPE(a, b)	((a) << 8 | (b))
1014 
1015 /*
1016  * parse the source unit recursively until it reaches to a terminal
1017  * or a branched unit.
1018  */
1019 static int __check_input_term(struct mixer_build *state, int id,
1020 			      struct usb_audio_term *term)
1021 {
1022 	int protocol = state->mixer->protocol;
1023 	void *p1;
1024 	unsigned char *hdr;
1025 
1026 	for (;;) {
1027 		/* a loop in the terminal chain? */
1028 		if (test_and_set_bit(id, state->termbitmap))
1029 			return -EINVAL;
1030 
1031 		p1 = find_audio_control_unit(state, id);
1032 		if (!p1)
1033 			break;
1034 		if (!snd_usb_validate_audio_desc(p1, protocol))
1035 			break; /* bad descriptor */
1036 
1037 		hdr = p1;
1038 		term->id = id;
1039 
1040 		switch (PTYPE(protocol, hdr[2])) {
1041 		case PTYPE(UAC_VERSION_1, UAC_FEATURE_UNIT):
1042 		case PTYPE(UAC_VERSION_2, UAC_FEATURE_UNIT):
1043 		case PTYPE(UAC_VERSION_3, UAC3_FEATURE_UNIT): {
1044 			/* the header is the same for all versions */
1045 			struct uac_feature_unit_descriptor *d = p1;
1046 
1047 			id = d->bSourceID;
1048 			break; /* continue to parse */
1049 		}
1050 		case PTYPE(UAC_VERSION_1, UAC_INPUT_TERMINAL):
1051 			return parse_term_uac1_iterm_unit(state, term, p1, id);
1052 		case PTYPE(UAC_VERSION_2, UAC_INPUT_TERMINAL):
1053 			return parse_term_uac2_iterm_unit(state, term, p1, id);
1054 		case PTYPE(UAC_VERSION_3, UAC_INPUT_TERMINAL):
1055 			return parse_term_uac3_iterm_unit(state, term, p1, id);
1056 		case PTYPE(UAC_VERSION_1, UAC_MIXER_UNIT):
1057 		case PTYPE(UAC_VERSION_2, UAC_MIXER_UNIT):
1058 		case PTYPE(UAC_VERSION_3, UAC3_MIXER_UNIT):
1059 			return parse_term_mixer_unit(state, term, p1, id);
1060 		case PTYPE(UAC_VERSION_1, UAC_SELECTOR_UNIT):
1061 		case PTYPE(UAC_VERSION_2, UAC_SELECTOR_UNIT):
1062 		case PTYPE(UAC_VERSION_2, UAC2_CLOCK_SELECTOR):
1063 		case PTYPE(UAC_VERSION_3, UAC3_SELECTOR_UNIT):
1064 		case PTYPE(UAC_VERSION_3, UAC3_CLOCK_SELECTOR):
1065 			return parse_term_selector_unit(state, term, p1, id);
1066 		case PTYPE(UAC_VERSION_1, UAC1_PROCESSING_UNIT):
1067 		case PTYPE(UAC_VERSION_2, UAC2_PROCESSING_UNIT_V2):
1068 		case PTYPE(UAC_VERSION_3, UAC3_PROCESSING_UNIT):
1069 			return parse_term_proc_unit(state, term, p1, id,
1070 						    UAC3_PROCESSING_UNIT);
1071 		case PTYPE(UAC_VERSION_2, UAC2_EFFECT_UNIT):
1072 		case PTYPE(UAC_VERSION_3, UAC3_EFFECT_UNIT):
1073 			return parse_term_effect_unit(state, term, p1, id);
1074 		case PTYPE(UAC_VERSION_1, UAC1_EXTENSION_UNIT):
1075 		case PTYPE(UAC_VERSION_2, UAC2_EXTENSION_UNIT_V2):
1076 		case PTYPE(UAC_VERSION_3, UAC3_EXTENSION_UNIT):
1077 			return parse_term_proc_unit(state, term, p1, id,
1078 						    UAC3_EXTENSION_UNIT);
1079 		case PTYPE(UAC_VERSION_2, UAC2_CLOCK_SOURCE):
1080 			return parse_term_uac2_clock_source(state, term, p1, id);
1081 		case PTYPE(UAC_VERSION_3, UAC3_CLOCK_SOURCE):
1082 			return parse_term_uac3_clock_source(state, term, p1, id);
1083 		default:
1084 			return -ENODEV;
1085 		}
1086 	}
1087 	return -ENODEV;
1088 }
1089 
1090 
1091 static int check_input_term(struct mixer_build *state, int id,
1092 			    struct usb_audio_term *term)
1093 {
1094 	memset(term, 0, sizeof(*term));
1095 	memset(state->termbitmap, 0, sizeof(state->termbitmap));
1096 	return __check_input_term(state, id, term);
1097 }
1098 
1099 /*
1100  * Feature Unit
1101  */
1102 
1103 /* feature unit control information */
1104 struct usb_feature_control_info {
1105 	int control;
1106 	const char *name;
1107 	int type;	/* data type for uac1 */
1108 	int type_uac2;	/* data type for uac2 if different from uac1, else -1 */
1109 };
1110 
1111 static const struct usb_feature_control_info audio_feature_info[] = {
1112 	{ UAC_FU_MUTE,			"Mute",			USB_MIXER_INV_BOOLEAN, -1 },
1113 	{ UAC_FU_VOLUME,		"Volume",		USB_MIXER_S16, -1 },
1114 	{ UAC_FU_BASS,			"Tone Control - Bass",	USB_MIXER_S8, -1 },
1115 	{ UAC_FU_MID,			"Tone Control - Mid",	USB_MIXER_S8, -1 },
1116 	{ UAC_FU_TREBLE,		"Tone Control - Treble", USB_MIXER_S8, -1 },
1117 	{ UAC_FU_GRAPHIC_EQUALIZER,	"Graphic Equalizer",	USB_MIXER_S8, -1 }, /* FIXME: not implemented yet */
1118 	{ UAC_FU_AUTOMATIC_GAIN,	"Auto Gain Control",	USB_MIXER_BOOLEAN, -1 },
1119 	{ UAC_FU_DELAY,			"Delay Control",	USB_MIXER_U16, USB_MIXER_U32 },
1120 	{ UAC_FU_BASS_BOOST,		"Bass Boost",		USB_MIXER_BOOLEAN, -1 },
1121 	{ UAC_FU_LOUDNESS,		"Loudness",		USB_MIXER_BOOLEAN, -1 },
1122 	/* UAC2 specific */
1123 	{ UAC2_FU_INPUT_GAIN,		"Input Gain Control",	USB_MIXER_S16, -1 },
1124 	{ UAC2_FU_INPUT_GAIN_PAD,	"Input Gain Pad Control", USB_MIXER_S16, -1 },
1125 	{ UAC2_FU_PHASE_INVERTER,	 "Phase Inverter Control", USB_MIXER_BOOLEAN, -1 },
1126 };
1127 
1128 static void usb_mixer_elem_info_free(struct usb_mixer_elem_info *cval)
1129 {
1130 	kfree(cval);
1131 }
1132 
1133 /* private_free callback */
1134 void snd_usb_mixer_elem_free(struct snd_kcontrol *kctl)
1135 {
1136 	usb_mixer_elem_info_free(kctl->private_data);
1137 	kctl->private_data = NULL;
1138 }
1139 
1140 /*
1141  * interface to ALSA control for feature/mixer units
1142  */
1143 
1144 /* volume control quirks */
1145 static void volume_control_quirks(struct usb_mixer_elem_info *cval,
1146 				  struct snd_kcontrol *kctl)
1147 {
1148 	struct snd_usb_audio *chip = cval->head.mixer->chip;
1149 
1150 	if (chip->quirk_flags & QUIRK_FLAG_MIC_RES_384) {
1151 		if (!strcmp(kctl->id.name, "Mic Capture Volume")) {
1152 			usb_audio_info(chip,
1153 				"set resolution quirk: cval->res = 384\n");
1154 			cval->res = 384;
1155 		}
1156 	} else if (chip->quirk_flags & QUIRK_FLAG_MIC_RES_16) {
1157 		if (!strcmp(kctl->id.name, "Mic Capture Volume")) {
1158 			usb_audio_info(chip,
1159 				"set resolution quirk: cval->res = 16\n");
1160 			cval->res = 16;
1161 		}
1162 	}
1163 
1164 	switch (chip->usb_id) {
1165 	case USB_ID(0x0763, 0x2030): /* M-Audio Fast Track C400 */
1166 	case USB_ID(0x0763, 0x2031): /* M-Audio Fast Track C600 */
1167 		if (strcmp(kctl->id.name, "Effect Duration") == 0) {
1168 			cval->min = 0x0000;
1169 			cval->max = 0xffff;
1170 			cval->res = 0x00e6;
1171 			break;
1172 		}
1173 		if (strcmp(kctl->id.name, "Effect Volume") == 0 ||
1174 		    strcmp(kctl->id.name, "Effect Feedback Volume") == 0) {
1175 			cval->min = 0x00;
1176 			cval->max = 0xff;
1177 			break;
1178 		}
1179 		if (strstr(kctl->id.name, "Effect Return") != NULL) {
1180 			cval->min = 0xb706;
1181 			cval->max = 0xff7b;
1182 			cval->res = 0x0073;
1183 			break;
1184 		}
1185 		if ((strstr(kctl->id.name, "Playback Volume") != NULL) ||
1186 			(strstr(kctl->id.name, "Effect Send") != NULL)) {
1187 			cval->min = 0xb5fb; /* -73 dB = 0xb6ff */
1188 			cval->max = 0xfcfe;
1189 			cval->res = 0x0073;
1190 		}
1191 		break;
1192 
1193 	case USB_ID(0x0763, 0x2081): /* M-Audio Fast Track Ultra 8R */
1194 	case USB_ID(0x0763, 0x2080): /* M-Audio Fast Track Ultra */
1195 		if (strcmp(kctl->id.name, "Effect Duration") == 0) {
1196 			usb_audio_info(chip,
1197 				       "set quirk for FTU Effect Duration\n");
1198 			cval->min = 0x0000;
1199 			cval->max = 0x7f00;
1200 			cval->res = 0x0100;
1201 			break;
1202 		}
1203 		if (strcmp(kctl->id.name, "Effect Volume") == 0 ||
1204 		    strcmp(kctl->id.name, "Effect Feedback Volume") == 0) {
1205 			usb_audio_info(chip,
1206 				       "set quirks for FTU Effect Feedback/Volume\n");
1207 			cval->min = 0x00;
1208 			cval->max = 0x7f;
1209 			break;
1210 		}
1211 		break;
1212 
1213 	case USB_ID(0x0d8c, 0x0103):
1214 		if (!strcmp(kctl->id.name, "PCM Playback Volume")) {
1215 			usb_audio_info(chip,
1216 				 "set volume quirk for CM102-A+/102S+\n");
1217 			cval->min = -256;
1218 		}
1219 		break;
1220 
1221 	case USB_ID(0x045e, 0x070f): /* MS LifeChat LX-3000 Headset */
1222 		if (!strcmp(kctl->id.name, "Speaker Playback Volume")) {
1223 			usb_audio_info(chip,
1224 				"set volume quirk for MS LifeChat LX-3000\n");
1225 			cval->res = 192;
1226 		}
1227 		break;
1228 
1229 	case USB_ID(0x0471, 0x0101):
1230 	case USB_ID(0x0471, 0x0104):
1231 	case USB_ID(0x0471, 0x0105):
1232 	case USB_ID(0x0672, 0x1041):
1233 	/* quirk for UDA1321/N101.
1234 	 * note that detection between firmware 2.1.1.7 (N101)
1235 	 * and later 2.1.1.21 is not very clear from datasheets.
1236 	 * I hope that the min value is -15360 for newer firmware --jk
1237 	 */
1238 		if (!strcmp(kctl->id.name, "PCM Playback Volume") &&
1239 		    cval->min == -15616) {
1240 			usb_audio_info(chip,
1241 				 "set volume quirk for UDA1321/N101 chip\n");
1242 			cval->max = -256;
1243 		}
1244 		break;
1245 
1246 	case USB_ID(0x046d, 0x09a4):
1247 		if (!strcmp(kctl->id.name, "Mic Capture Volume")) {
1248 			usb_audio_info(chip,
1249 				"set volume quirk for QuickCam E3500\n");
1250 			cval->min = 6080;
1251 			cval->max = 8768;
1252 			cval->res = 192;
1253 		}
1254 		break;
1255 
1256 	case USB_ID(0x0495, 0x3042): /* ESS Technology Asus USB DAC */
1257 		if ((strstr(kctl->id.name, "Playback Volume") != NULL) ||
1258 			strstr(kctl->id.name, "Capture Volume") != NULL) {
1259 			cval->min >>= 8;
1260 			cval->max = 0;
1261 			cval->res = 1;
1262 		}
1263 		break;
1264 
1265 	case USB_ID(0x0e6f, 0x024a): /* PDP Riffmaster for PS4 */
1266 	case USB_ID(0x0e6f, 0x0249): /* PDP Riffmaster for PS5 */
1267 		if (!strcmp(kctl->id.name, "PCM Playback Volume")) {
1268 			usb_audio_info(chip,
1269 				"set volume quirk for PDP Riffmaster for PS4/PS5\n");
1270 			cval->min = -2560; /* Mute under it */
1271 		}
1272 		break;
1273 
1274 	case USB_ID(0x3302, 0x12db): /* MOONDROP Quark2 */
1275 		if (!strcmp(kctl->id.name, "PCM Playback Volume")) {
1276 			usb_audio_info(chip,
1277 				"set volume quirk for MOONDROP Quark2\n");
1278 			cval->min = -14208; /* Mute under it */
1279 		}
1280 		break;
1281 	case USB_ID(0x12d1, 0x3a07): /* Huawei Technologies Co., Ltd. CM-Q3 */
1282 		if (!strcmp(kctl->id.name, "PCM Playback Volume")) {
1283 			usb_audio_info(chip,
1284 				       "set volume quirk for Huawei Technologies Co., Ltd. CM-Q3\n");
1285 			cval->min = -11264; /* Mute under it */
1286 		}
1287 		break;
1288 	case USB_ID(0x31b2, 0x0111): /* MOONDROP JU Jiu */
1289 		if (!strcmp(kctl->id.name, "PCM Playback Volume")) {
1290 			usb_audio_info(chip,
1291 				       "set volume quirk for MOONDROP JU Jiu\n");
1292 			cval->min = -10880; /* Mute under it */
1293 		}
1294 		break;
1295 	}
1296 }
1297 
1298 /* forcibly initialize the current mixer value; if GET_CUR fails, set to
1299  * the minimum as default
1300  */
1301 static void init_cur_mix_raw(struct usb_mixer_elem_info *cval, int ch, int idx)
1302 {
1303 	int val, err;
1304 
1305 	err = snd_usb_get_cur_mix_value(cval, ch, idx, &val);
1306 	if (!err)
1307 		return;
1308 	if (!cval->head.mixer->ignore_ctl_error && !cval->get_cur_broken)
1309 		usb_audio_warn(cval->head.mixer->chip,
1310 			       "%d:%d: failed to get current value for ch %d (%d)\n",
1311 			       cval->head.id, mixer_ctrl_intf(cval->head.mixer),
1312 			       ch, err);
1313 	snd_usb_set_cur_mix_value(cval, ch, idx, cval->min);
1314 }
1315 
1316 /*
1317  * Additional checks for sticky GET_CUR
1318  *
1319  * Some devices' volume control mixers have sticky GET_CUR, which implies either
1320  * stubbed SET_CUR or broken GET_CUR. For the former case, the mixer accepts
1321  * SET_CUR but do absolutely nothing, so falling back to soft mixer is the only
1322  * way to control the volume. For the latter case, the mixer has effective
1323  * SET_CUR despite GET_CUR being constant, and the mixer is usable as long as we
1324  * always provide mixer value from the ceche.
1325  *
1326  * Check the return values of GET_CUR with different SET_CUR values. Consider
1327  * GET_CUR as sticky if GET_CUR always returns a constant value.
1328  *
1329  * Unfortunately, we can't distinguish between stubbed SET_CUR and broken
1330  * GET_CUR with simple read-back tests. Disabling the mixer regardless and
1331  * forcing userspace to use soft mixer instead can lead to audible distortion at
1332  * low volume on some wireless headphones, probably due to their poorly-
1333  * performed lossy codec.
1334  *
1335  * Instead, mark GET_CUR as broken regardless and only provide mixer value from
1336  * the cache. Users may opt into soft mixer in userspace audio stack if they
1337  * need it.
1338  */
1339 static int check_sticky_volume_control(struct usb_mixer_elem_info *cval,
1340 				       int channel, int saved)
1341 {
1342 	int sticky_test_values[] = { cval->min, cval->max };
1343 	int test, check, i;
1344 
1345 	for (i = 0; i < ARRAY_SIZE(sticky_test_values); i++) {
1346 		test = sticky_test_values[i];
1347 		if (test == saved)
1348 			continue;
1349 
1350 		/* Assume non-sticky on failure. */
1351 		if (snd_usb_set_cur_mix_value(cval, channel, 0, test) ||
1352 		    get_cur_mix_raw(cval, channel, &check) ||
1353 		    check != saved) /* SET_CUR effective, non-sticky. */
1354 			return 0;
1355 	}
1356 
1357 	usb_audio_info(cval->head.mixer->chip,
1358 		       "%d:%d: broken mixer GET_CUR (%d/%d/%d => %d)\n",
1359 		       cval->head.id, mixer_ctrl_intf(cval->head.mixer),
1360 		       cval->min, cval->max, cval->res, saved);
1361 
1362 	cval->get_cur_broken = 1;
1363 	return -ENXIO;
1364 }
1365 
1366 /*
1367  * Additional checks for the proper resolution
1368  *
1369  * Some devices report smaller resolutions than actually reacting.
1370  * They don't return errors but simply clip to the lower aligned value.
1371  */
1372 static void check_volume_control_res(struct usb_mixer_elem_info *cval,
1373 				     int channel, int saved)
1374 {
1375 	int last_valid_res = cval->res;
1376 	int test, check;
1377 
1378 	for (;;) {
1379 		test = saved;
1380 		if (test < cval->max)
1381 			test += cval->res;
1382 		else
1383 			test -= cval->res;
1384 
1385 		if (test < cval->min || test > cval->max ||
1386 		    snd_usb_set_cur_mix_value(cval, channel, 0, test) ||
1387 		    get_cur_mix_raw(cval, channel, &check)) {
1388 			cval->res = last_valid_res;
1389 			break;
1390 		}
1391 		if (test == check)
1392 			break;
1393 
1394 		cval->res *= 2;
1395 	}
1396 }
1397 
1398 /*
1399  * retrieve the minimum and maximum values for the specified control
1400  */
1401 static int get_min_max_with_quirks(struct usb_mixer_elem_info *cval,
1402 				   int default_min, struct snd_kcontrol *kctl)
1403 {
1404 	int i, idx, ret = 0;
1405 
1406 	/* for failsafe */
1407 	cval->min = default_min;
1408 	cval->max = cval->min + 1;
1409 	cval->res = 1;
1410 	cval->dBmin = cval->dBmax = 0;
1411 
1412 	if (cval->val_type == USB_MIXER_BOOLEAN ||
1413 	    cval->val_type == USB_MIXER_INV_BOOLEAN) {
1414 		cval->initialized = 1;
1415 	} else {
1416 		int minchn = 0;
1417 		if (cval->cmask) {
1418 			for (i = 0; i < MAX_CHANNELS; i++)
1419 				if (cval->cmask & BIT(i)) {
1420 					minchn = i + 1;
1421 					break;
1422 				}
1423 		}
1424 
1425 		ret = get_ctl_range(cval, (cval->control << 8) | minchn);
1426 		if (ret < 0)
1427 			return ret;
1428 
1429 		if (cval->res == 0)
1430 			cval->res = 1;
1431 
1432 		if (cval->min < cval->max) {
1433 			int saved;
1434 
1435 			if (get_cur_mix_raw(cval, minchn, &saved) < 0)
1436 				goto no_checks;
1437 
1438 			ret = check_sticky_volume_control(cval, minchn, saved);
1439 			if (ret)
1440 				goto no_checks;
1441 
1442 			if (cval->min + cval->res < cval->max)
1443 				check_volume_control_res(cval, minchn, saved);
1444 
1445 			snd_usb_set_cur_mix_value(cval, minchn, 0, saved);
1446 		}
1447 
1448 no_checks:
1449 		/*
1450 		 * Got a non-fatal failure during sanity checks.
1451 		 *
1452 		 * Do not propagate mixer values written by sanity checks.
1453 		 * Instead, rely on init_cur_mix_raw() to initialize the mixer
1454 		 * properly.
1455 		 */
1456 		if (ret)
1457 			bitmap_zero(cval->cached, MAX_CHANNELS + 1);
1458 
1459 		cval->initialized = 1;
1460 	}
1461 
1462 	if (kctl)
1463 		volume_control_quirks(cval, kctl);
1464 
1465 	/* USB descriptions contain the dB scale in 1/256 dB unit
1466 	 * while ALSA TLV contains in 1/100 dB unit
1467 	 */
1468 	cval->dBmin = (convert_signed_value(cval, cval->min) * 100) / 256;
1469 	cval->dBmax = (convert_signed_value(cval, cval->max) * 100) / 256;
1470 	if (cval->dBmin > cval->dBmax) {
1471 		/* something is wrong; assume it's either from/to 0dB */
1472 		if (cval->dBmin < 0)
1473 			cval->dBmax = 0;
1474 		else if (cval->dBmin > 0)
1475 			cval->dBmin = 0;
1476 		if (cval->dBmin > cval->dBmax) {
1477 			/* totally crap, return an error */
1478 			return -EINVAL;
1479 		}
1480 	} else {
1481 		/* if the max volume is too low, it's likely a bogus range;
1482 		 * here we use -96dB as the threshold
1483 		 */
1484 		if (cval->dBmax <= -9600) {
1485 			usb_audio_info(cval->head.mixer->chip,
1486 				       "%d:%d: bogus dB values (%d/%d), disabling dB reporting\n",
1487 				       cval->head.id, mixer_ctrl_intf(cval->head.mixer),
1488 				       cval->dBmin, cval->dBmax);
1489 			cval->dBmin = cval->dBmax = 0;
1490 		}
1491 	}
1492 
1493 	/* initialize all elements */
1494 	if (!cval->cmask) {
1495 		init_cur_mix_raw(cval, 0, 0);
1496 	} else {
1497 		idx = 0;
1498 		for (i = 0; i < MAX_CHANNELS; i++) {
1499 			if (cval->cmask & BIT(i)) {
1500 				init_cur_mix_raw(cval, i + 1, idx);
1501 				idx++;
1502 			}
1503 		}
1504 	}
1505 
1506 	/*
1507 	 * When GET_CUR is sticky, the saved value is bogus, so mixer values set
1508 	 * by the sanity checks must be discarded through init_cur_mix_raw().
1509 	 * After that, we can clear the flag as per QUIRK_FLAG_MIXER_GET_CUR_OK.
1510 	 */
1511 	if (cval->head.mixer->chip->quirk_flags & QUIRK_FLAG_MIXER_GET_CUR_OK)
1512 		cval->get_cur_broken = 0;
1513 
1514 	return 0;
1515 }
1516 
1517 #define get_min_max(cval, def)	get_min_max_with_quirks(cval, def, NULL)
1518 
1519 /* get the max value advertised via control API */
1520 static int get_max_exposed(struct usb_mixer_elem_info *cval)
1521 {
1522 	if (!cval->max_exposed) {
1523 		if (cval->res)
1524 			cval->max_exposed =
1525 				DIV_ROUND_UP(cval->max - cval->min, cval->res);
1526 		else
1527 			cval->max_exposed = cval->max - cval->min;
1528 	}
1529 	return cval->max_exposed;
1530 }
1531 
1532 /* get a feature/mixer unit info */
1533 static int mixer_ctl_feature_info(struct snd_kcontrol *kcontrol,
1534 				  struct snd_ctl_elem_info *uinfo)
1535 {
1536 	struct usb_mixer_elem_info *cval = snd_kcontrol_chip(kcontrol);
1537 	int ret;
1538 
1539 	guard(mutex)(&cval->head.mixer->lock);
1540 	if (cval->val_type == USB_MIXER_BOOLEAN ||
1541 	    cval->val_type == USB_MIXER_INV_BOOLEAN)
1542 		uinfo->type = SNDRV_CTL_ELEM_TYPE_BOOLEAN;
1543 	else
1544 		uinfo->type = SNDRV_CTL_ELEM_TYPE_INTEGER;
1545 	uinfo->count = cval->channels;
1546 	if (cval->val_type != USB_MIXER_BOOLEAN &&
1547 	    cval->val_type != USB_MIXER_INV_BOOLEAN) {
1548 		if (!cval->initialized) {
1549 			ret = get_min_max_with_quirks(cval, 0, kcontrol);
1550 			if ((ret >= 0 || ret == -EAGAIN) &&
1551 			    cval->initialized && cval->dBmin >= cval->dBmax) {
1552 				kcontrol->vd[0].access &=
1553 					~(SNDRV_CTL_ELEM_ACCESS_TLV_READ |
1554 					  SNDRV_CTL_ELEM_ACCESS_TLV_CALLBACK);
1555 				snd_ctl_notify(cval->head.mixer->chip->card,
1556 					       SNDRV_CTL_EVENT_MASK_INFO,
1557 					       &kcontrol->id);
1558 			}
1559 		}
1560 	}
1561 
1562 	uinfo->value.integer.min = 0;
1563 	uinfo->value.integer.max = get_max_exposed(cval);
1564 	return 0;
1565 }
1566 
1567 /* get the current value from feature/mixer unit */
1568 static int mixer_ctl_feature_get(struct snd_kcontrol *kcontrol,
1569 				 struct snd_ctl_elem_value *ucontrol)
1570 {
1571 	struct usb_mixer_elem_info *cval = snd_kcontrol_chip(kcontrol);
1572 	int c, cnt, val, err;
1573 
1574 	guard(mutex)(&cval->head.mixer->lock);
1575 	ucontrol->value.integer.value[0] = cval->min;
1576 	if (cval->cmask) {
1577 		cnt = 0;
1578 		for (c = 0; c < MAX_CHANNELS; c++) {
1579 			if (!(cval->cmask & BIT(c)))
1580 				continue;
1581 			err = snd_usb_get_cur_mix_value(cval, c + 1, cnt, &val);
1582 			if (err < 0)
1583 				return filter_error(cval, err);
1584 			val = get_relative_value(cval, val);
1585 			ucontrol->value.integer.value[cnt] = val;
1586 			cnt++;
1587 		}
1588 		return 0;
1589 	} else {
1590 		/* master channel */
1591 		err = snd_usb_get_cur_mix_value(cval, 0, 0, &val);
1592 		if (err < 0)
1593 			return filter_error(cval, err);
1594 		val = get_relative_value(cval, val);
1595 		ucontrol->value.integer.value[0] = val;
1596 	}
1597 	return 0;
1598 }
1599 
1600 /* put the current value to feature/mixer unit */
1601 static int mixer_ctl_feature_put(struct snd_kcontrol *kcontrol,
1602 				 struct snd_ctl_elem_value *ucontrol)
1603 {
1604 	struct usb_mixer_elem_info *cval = snd_kcontrol_chip(kcontrol);
1605 	int max_val;
1606 	int c, cnt, val, oval, err;
1607 	int changed = 0;
1608 
1609 	guard(mutex)(&cval->head.mixer->lock);
1610 	max_val = get_max_exposed(cval);
1611 	if (cval->cmask) {
1612 		cnt = 0;
1613 		for (c = 0; c < MAX_CHANNELS; c++) {
1614 			if (!(cval->cmask & BIT(c)))
1615 				continue;
1616 			err = snd_usb_get_cur_mix_value(cval, c + 1, cnt, &oval);
1617 			if (err < 0)
1618 				return filter_error(cval, err);
1619 			val = ucontrol->value.integer.value[cnt];
1620 			if (val < 0 || val > max_val)
1621 				return -EINVAL;
1622 			val = get_abs_value(cval, val);
1623 			if (oval != val) {
1624 				err = snd_usb_set_cur_mix_value(cval, c + 1,
1625 								cnt, val);
1626 				if (err < 0)
1627 					return filter_error(cval, err);
1628 				changed = 1;
1629 			}
1630 			cnt++;
1631 		}
1632 	} else {
1633 		/* master channel */
1634 		err = snd_usb_get_cur_mix_value(cval, 0, 0, &oval);
1635 		if (err < 0)
1636 			return filter_error(cval, err);
1637 		val = ucontrol->value.integer.value[0];
1638 		if (val < 0 || val > max_val)
1639 			return -EINVAL;
1640 		val = get_abs_value(cval, val);
1641 		if (val != oval) {
1642 			err = snd_usb_set_cur_mix_value(cval, 0, 0, val);
1643 			if (err < 0)
1644 				return filter_error(cval, err);
1645 			changed = 1;
1646 		}
1647 	}
1648 	return changed;
1649 }
1650 
1651 /* get the boolean value from the master channel of a UAC control */
1652 static int mixer_ctl_master_bool_get(struct snd_kcontrol *kcontrol,
1653 				     struct snd_ctl_elem_value *ucontrol)
1654 {
1655 	struct usb_mixer_elem_info *cval = snd_kcontrol_chip(kcontrol);
1656 	int val, err;
1657 
1658 	guard(mutex)(&cval->head.mixer->lock);
1659 	err = snd_usb_get_cur_mix_value(cval, 0, 0, &val);
1660 	if (err < 0)
1661 		return filter_error(cval, err);
1662 	val = (val != 0);
1663 	ucontrol->value.integer.value[0] = val;
1664 	return 0;
1665 }
1666 
1667 static int get_connector_value(struct usb_mixer_elem_info *cval,
1668 			       char *name, int *val)
1669 {
1670 	struct snd_usb_audio *chip = cval->head.mixer->chip;
1671 	int idx = 0, validx, ret;
1672 
1673 	validx = cval->control << 8 | 0;
1674 
1675 	CLASS(snd_usb_lock, pm)(chip);
1676 	if (pm.err) {
1677 		ret = -EIO;
1678 		goto error;
1679 	}
1680 
1681 	idx = mixer_ctrl_intf(cval->head.mixer) | (cval->head.id << 8);
1682 	if (cval->head.mixer->protocol == UAC_VERSION_2) {
1683 		struct uac2_connectors_ctl_blk uac2_conn;
1684 
1685 		ret = snd_usb_ctl_msg(chip->dev, usb_rcvctrlpipe(chip->dev, 0), UAC2_CS_CUR,
1686 				      USB_RECIP_INTERFACE | USB_TYPE_CLASS | USB_DIR_IN,
1687 				      validx, idx, &uac2_conn, sizeof(uac2_conn));
1688 		if (val)
1689 			*val = !!uac2_conn.bNrChannels;
1690 	} else { /* UAC_VERSION_3 */
1691 		struct uac3_insertion_ctl_blk uac3_conn;
1692 
1693 		ret = snd_usb_ctl_msg(chip->dev, usb_rcvctrlpipe(chip->dev, 0), UAC2_CS_CUR,
1694 				      USB_RECIP_INTERFACE | USB_TYPE_CLASS | USB_DIR_IN,
1695 				      validx, idx, &uac3_conn, sizeof(uac3_conn));
1696 		if (val)
1697 			*val = !!uac3_conn.bmConInserted;
1698 	}
1699 
1700 	if (ret < 0) {
1701 		if (name && strstr(name, "Speaker")) {
1702 			if (val)
1703 				*val = 1;
1704 			return 0;
1705 		}
1706 error:
1707 		usb_audio_err(chip,
1708 			"cannot get connectors status: req = %#x, wValue = %#x, wIndex = %#x, type = %d\n",
1709 			UAC_GET_CUR, validx, idx, cval->val_type);
1710 
1711 		if (val)
1712 			*val = 0;
1713 
1714 		return filter_error(cval, ret);
1715 	}
1716 
1717 	return ret;
1718 }
1719 
1720 /* get the connectors status and report it as boolean type */
1721 static int mixer_ctl_connector_get(struct snd_kcontrol *kcontrol,
1722 				   struct snd_ctl_elem_value *ucontrol)
1723 {
1724 	struct usb_mixer_elem_info *cval = snd_kcontrol_chip(kcontrol);
1725 	int ret, val;
1726 
1727 	ret = get_connector_value(cval, kcontrol->id.name, &val);
1728 
1729 	if (ret < 0)
1730 		return ret;
1731 
1732 	ucontrol->value.integer.value[0] = val;
1733 	return 0;
1734 }
1735 
1736 static const struct snd_kcontrol_new usb_feature_unit_ctl = {
1737 	.iface = SNDRV_CTL_ELEM_IFACE_MIXER,
1738 	.name = "", /* will be filled later manually */
1739 	.info = mixer_ctl_feature_info,
1740 	.get = mixer_ctl_feature_get,
1741 	.put = mixer_ctl_feature_put,
1742 };
1743 
1744 /* the read-only variant */
1745 static const struct snd_kcontrol_new usb_feature_unit_ctl_ro = {
1746 	.iface = SNDRV_CTL_ELEM_IFACE_MIXER,
1747 	.name = "", /* will be filled later manually */
1748 	.info = mixer_ctl_feature_info,
1749 	.get = mixer_ctl_feature_get,
1750 	.put = NULL,
1751 };
1752 
1753 /*
1754  * A control which shows the boolean value from reading a UAC control on
1755  * the master channel.
1756  */
1757 static const struct snd_kcontrol_new usb_bool_master_control_ctl_ro = {
1758 	.iface = SNDRV_CTL_ELEM_IFACE_CARD,
1759 	.name = "", /* will be filled later manually */
1760 	.access = SNDRV_CTL_ELEM_ACCESS_READ,
1761 	.info = snd_ctl_boolean_mono_info,
1762 	.get = mixer_ctl_master_bool_get,
1763 	.put = NULL,
1764 };
1765 
1766 static const struct snd_kcontrol_new usb_connector_ctl_ro = {
1767 	.iface = SNDRV_CTL_ELEM_IFACE_CARD,
1768 	.name = "", /* will be filled later manually */
1769 	.access = SNDRV_CTL_ELEM_ACCESS_READ,
1770 	.info = snd_ctl_boolean_mono_info,
1771 	.get = mixer_ctl_connector_get,
1772 	.put = NULL,
1773 };
1774 
1775 /*
1776  * This symbol is exported in order to allow the mixer quirks to
1777  * hook up to the standard feature unit control mechanism
1778  */
1779 const struct snd_kcontrol_new *snd_usb_feature_unit_ctl = &usb_feature_unit_ctl;
1780 
1781 /*
1782  * build a feature control
1783  */
1784 static void append_ctl_name(struct snd_kcontrol *kctl, const char *str)
1785 {
1786 	size_t len = strlen(kctl->id.name);
1787 
1788 	strscpy(kctl->id.name + len, str, sizeof(kctl->id.name) - len);
1789 }
1790 
1791 /*
1792  * A lot of headsets/headphones have a "Speaker" mixer. Make sure we
1793  * rename it to "Headphone". We determine if something is a headphone
1794  * similar to how udev determines form factor.
1795  */
1796 static void check_no_speaker_on_headset(struct snd_kcontrol *kctl,
1797 					struct snd_card *card)
1798 {
1799 	static const char * const names_to_check[] = {
1800 		"Headset", "headset", "Headphone", "headphone", NULL};
1801 	const char * const *s;
1802 	bool found = false;
1803 
1804 	if (strcmp("Speaker", kctl->id.name))
1805 		return;
1806 
1807 	for (s = names_to_check; *s; s++)
1808 		if (strstr(card->shortname, *s)) {
1809 			found = true;
1810 			break;
1811 		}
1812 
1813 	if (!found)
1814 		return;
1815 
1816 	snd_ctl_rename(card, kctl, "Headphone");
1817 }
1818 
1819 static const struct usb_feature_control_info *get_feature_control_info(int control)
1820 {
1821 	int i;
1822 
1823 	for (i = 0; i < ARRAY_SIZE(audio_feature_info); ++i) {
1824 		if (audio_feature_info[i].control == control)
1825 			return &audio_feature_info[i];
1826 	}
1827 	return NULL;
1828 }
1829 
1830 static bool check_insane_volume_range(struct usb_mixer_interface *mixer,
1831 				      struct snd_kcontrol *kctl,
1832 				      struct usb_mixer_elem_info *cval)
1833 {
1834 	int range, steps, threshold;
1835 
1836 	/*
1837 	 * If a device quirk has overrode our TLV callback, no warning should
1838 	 * be generated since our checks are only meaningful for dB volume.
1839 	 */
1840 	if (!(kctl->vd[0].access & SNDRV_CTL_ELEM_ACCESS_TLV_CALLBACK) ||
1841 	    kctl->tlv.c != snd_usb_mixer_vol_tlv)
1842 		return false;
1843 
1844 	/*
1845 	 * Meaningless volume control capability (<1dB). This should cover
1846 	 * devices mapping their volume to val = 0/100/1, which are very likely
1847 	 * to be quirky.
1848 	 */
1849 	range = cval->max - cval->min;
1850 	if (range < 256) {
1851 		usb_audio_warn(mixer->chip,
1852 			       "Warning! Unlikely small volume range (=%u), linear volume or custom curve?",
1853 			       range);
1854 		return true;
1855 	}
1856 
1857 	steps = range / cval->res;
1858 
1859 	/*
1860 	 * There are definitely devices with ~20,000 ranges (e.g., HyperX Cloud
1861 	 * III with val = -18944/0/1), so we use some heuristics here:
1862 	 *
1863 	 * min < 0 < max: Attenuator + amplifier? Likely to be sane
1864 	 *
1865 	 * min < 0 = max: DSP? Voltage attenuator with FW conversion to dB?
1866 	 * Likely to be sane
1867 	 *
1868 	 * min < max < 0: Measured values? Neutral
1869 	 *
1870 	 * min = 0 < max: Oversimplified FW conversion? Linear volume? Likely to
1871 	 * be quirky (e.g., MV-SILICON)
1872 	 *
1873 	 * 0 < min < max: Amplifier with fixed gains? Likely to be quirky
1874 	 * (e.g., Logitech webcam)
1875 	 */
1876 	if (cval->min < 0 && 0 <= cval->max)
1877 		threshold = 24576; /* 65535 * (3 / 8) */
1878 	else if (cval->min < cval->max && cval->max < 0)
1879 		threshold = 1024;
1880 	else
1881 		threshold = 384;
1882 
1883 	if (steps > threshold) {
1884 		usb_audio_warn(mixer->chip,
1885 			       "Warning! Unlikely big volume step count (=%u), linear volume or wrong cval->res?",
1886 			       steps);
1887 		return true;
1888 	}
1889 
1890 	return false;
1891 }
1892 
1893 static void __build_feature_ctl(struct usb_mixer_interface *mixer,
1894 				const struct usbmix_name_map *imap,
1895 				u64 ctl_mask, int control,
1896 				struct usb_audio_term *iterm,
1897 				struct usb_audio_term *oterm,
1898 				int unitid, int nameid, int readonly_mask)
1899 {
1900 	const struct usb_feature_control_info *ctl_info;
1901 	unsigned int len = 0;
1902 	int mapped_name = 0;
1903 	struct snd_kcontrol *kctl;
1904 	struct usb_mixer_elem_info *cval;
1905 	const struct usbmix_name_map *map;
1906 	int ret;
1907 
1908 	if (control == UAC_FU_GRAPHIC_EQUALIZER) {
1909 		/* FIXME: not supported yet */
1910 		return;
1911 	}
1912 
1913 	map = find_map(imap, unitid, control);
1914 	if (check_ignored_ctl(map))
1915 		return;
1916 
1917 	cval = kzalloc_obj(*cval);
1918 	if (!cval)
1919 		return;
1920 	snd_usb_mixer_elem_init_std(&cval->head, mixer, unitid);
1921 	cval->control = control;
1922 	cval->cmask = ctl_mask;
1923 
1924 	ctl_info = get_feature_control_info(control);
1925 	if (!ctl_info) {
1926 		usb_mixer_elem_info_free(cval);
1927 		return;
1928 	}
1929 	if (mixer->protocol == UAC_VERSION_1)
1930 		cval->val_type = ctl_info->type;
1931 	else /* UAC_VERSION_2 */
1932 		cval->val_type = ctl_info->type_uac2 >= 0 ?
1933 			ctl_info->type_uac2 : ctl_info->type;
1934 
1935 	if (ctl_mask == 0) {
1936 		cval->channels = 1;	/* master channel */
1937 		cval->master_readonly = readonly_mask;
1938 	} else {
1939 		int i, c = 0;
1940 		for (i = 0; i < MAX_CHANNELS; i++)
1941 			if (ctl_mask & BIT(i))
1942 				c++;
1943 		cval->channels = c;
1944 		cval->ch_readonly = readonly_mask;
1945 	}
1946 
1947 	/*
1948 	 * If all channels in the mask are marked read-only, make the control
1949 	 * read-only. snd_usb_set_cur_mix_value() will check the mask again and won't
1950 	 * issue write commands to read-only channels.
1951 	 */
1952 	if (cval->channels == readonly_mask)
1953 		kctl = snd_ctl_new1(&usb_feature_unit_ctl_ro, cval);
1954 	else
1955 		kctl = snd_ctl_new1(&usb_feature_unit_ctl, cval);
1956 
1957 	if (!kctl) {
1958 		usb_audio_err(mixer->chip, "cannot malloc kcontrol\n");
1959 		usb_mixer_elem_info_free(cval);
1960 		return;
1961 	}
1962 	kctl->private_free = snd_usb_mixer_elem_free;
1963 
1964 	len = check_mapped_name(map, kctl->id.name, sizeof(kctl->id.name));
1965 	mapped_name = len != 0;
1966 	if (!len && nameid)
1967 		len = snd_usb_copy_string_desc(mixer->chip, nameid,
1968 				kctl->id.name, sizeof(kctl->id.name));
1969 
1970 	switch (control) {
1971 	case UAC_FU_MUTE:
1972 	case UAC_FU_VOLUME:
1973 		/*
1974 		 * determine the control name.  the rule is:
1975 		 * - if a name id is given in descriptor, use it.
1976 		 * - if the connected input can be determined, then use the name
1977 		 *   of terminal type.
1978 		 * - if the connected output can be determined, use it.
1979 		 * - otherwise, anonymous name.
1980 		 */
1981 		if (!len) {
1982 			if (iterm)
1983 				len = get_term_name(mixer->chip, iterm,
1984 						    kctl->id.name,
1985 						    sizeof(kctl->id.name), 1);
1986 			if (!len && oterm)
1987 				len = get_term_name(mixer->chip, oterm,
1988 						    kctl->id.name,
1989 						    sizeof(kctl->id.name), 1);
1990 			if (!len)
1991 				snprintf(kctl->id.name, sizeof(kctl->id.name),
1992 					 "Feature %d", unitid);
1993 		}
1994 
1995 		if (!mapped_name)
1996 			check_no_speaker_on_headset(kctl, mixer->chip->card);
1997 
1998 		/*
1999 		 * determine the stream direction:
2000 		 * if the connected output is USB stream, then it's likely a
2001 		 * capture stream.  otherwise it should be playback (hopefully :)
2002 		 */
2003 		if (!mapped_name && oterm && !(oterm->type >> 16)) {
2004 			if ((oterm->type & 0xff00) == 0x0100)
2005 				append_ctl_name(kctl, " Capture");
2006 			else
2007 				append_ctl_name(kctl, " Playback");
2008 		}
2009 		append_ctl_name(kctl, control == UAC_FU_MUTE ?
2010 				" Switch" : " Volume");
2011 		break;
2012 	default:
2013 		if (!len)
2014 			strscpy(kctl->id.name, audio_feature_info[control-1].name,
2015 				sizeof(kctl->id.name));
2016 		break;
2017 	}
2018 
2019 	/* get min/max values */
2020 	ret = get_min_max_with_quirks(cval, 0, kctl);
2021 
2022 	/* skip a bogus volume range */
2023 	if ((ret < 0 && ret != -EAGAIN) || cval->max <= cval->min) {
2024 		usb_audio_dbg(mixer->chip,
2025 			      "[%d] FU [%s] skipped due to invalid volume\n",
2026 			      cval->head.id, kctl->id.name);
2027 		snd_ctl_free_one(kctl);
2028 		return;
2029 	}
2030 
2031 
2032 	if (control == UAC_FU_VOLUME) {
2033 		check_mapped_dB(map, cval);
2034 		if (cval->dBmin < cval->dBmax || !cval->initialized) {
2035 			kctl->tlv.c = snd_usb_mixer_vol_tlv;
2036 			kctl->vd[0].access |=
2037 				SNDRV_CTL_ELEM_ACCESS_TLV_READ |
2038 				SNDRV_CTL_ELEM_ACCESS_TLV_CALLBACK;
2039 		}
2040 	}
2041 
2042 	snd_usb_mixer_fu_apply_quirk(mixer, cval, unitid, kctl);
2043 
2044 	if (check_insane_volume_range(mixer, kctl, cval)) {
2045 		usb_audio_warn(mixer->chip, "[%d] FU [%s] ch = %d, val = %d/%d/%d\n",
2046 			       cval->head.id, kctl->id.name, cval->channels,
2047 			       cval->min, cval->max, cval->res);
2048 	} else {
2049 		usb_audio_dbg(mixer->chip, "[%d] FU [%s] ch = %d, val = %d/%d/%d\n",
2050 			      cval->head.id, kctl->id.name, cval->channels,
2051 			      cval->min, cval->max, cval->res);
2052 	}
2053 
2054 	snd_usb_mixer_add_control(&cval->head, kctl);
2055 }
2056 
2057 static void build_feature_ctl(struct mixer_build *state, void *raw_desc,
2058 			      u64 ctl_mask, int control,
2059 			      struct usb_audio_term *iterm, int unitid,
2060 			      int readonly_mask)
2061 {
2062 	struct uac_feature_unit_descriptor *desc = raw_desc;
2063 	int nameid = uac_feature_unit_iFeature(desc);
2064 
2065 	__build_feature_ctl(state->mixer, state->map, ctl_mask, control,
2066 			iterm, &state->oterm, unitid, nameid, readonly_mask);
2067 }
2068 
2069 static void build_feature_ctl_badd(struct usb_mixer_interface *mixer,
2070 			      u64 ctl_mask, int control, int unitid,
2071 			      const struct usbmix_name_map *badd_map)
2072 {
2073 	__build_feature_ctl(mixer, badd_map, ctl_mask, control,
2074 			NULL, NULL, unitid, 0, 0);
2075 }
2076 
2077 static void get_connector_control_name(struct usb_mixer_interface *mixer,
2078 				       struct usb_audio_term *term,
2079 				       bool is_input, char *name, int name_size)
2080 {
2081 	int name_len = get_term_name(mixer->chip, term, name, name_size, 0);
2082 
2083 	if (name_len == 0)
2084 		name_len = strscpy(name, "Unknown", name_size);
2085 	if (name_len < 0)
2086 		return;
2087 
2088 	/*
2089 	 *  sound/core/ctljack.c has a convention of naming jack controls
2090 	 * by ending in " Jack".  Make it slightly more useful by
2091 	 * indicating Input or Output after the terminal name.
2092 	 */
2093 	if (is_input)
2094 		strscpy(name + name_len, " - Input Jack", name_size - name_len);
2095 	else
2096 		strscpy(name + name_len, " - Output Jack", name_size - name_len);
2097 }
2098 
2099 /* get connector value to "wake up" the USB audio */
2100 static int connector_mixer_resume(struct usb_mixer_elem_list *list)
2101 {
2102 	struct usb_mixer_elem_info *cval = mixer_elem_list_to_info(list);
2103 
2104 	get_connector_value(cval, NULL, NULL);
2105 	return 0;
2106 }
2107 
2108 /* Build a mixer control for a UAC connector control (jack-detect) */
2109 static void build_connector_control(struct usb_mixer_interface *mixer,
2110 				    const struct usbmix_name_map *imap,
2111 				    struct usb_audio_term *term, bool is_input)
2112 {
2113 	struct snd_kcontrol *kctl;
2114 	struct usb_mixer_elem_info *cval;
2115 	const struct usbmix_name_map *map;
2116 
2117 	map = find_map(imap, term->id, 0);
2118 	if (check_ignored_ctl(map))
2119 		return;
2120 
2121 	cval = kzalloc_obj(*cval);
2122 	if (!cval)
2123 		return;
2124 	snd_usb_mixer_elem_init_std(&cval->head, mixer, term->id);
2125 
2126 	/* set up a specific resume callback */
2127 	cval->head.resume = connector_mixer_resume;
2128 
2129 	/*
2130 	 * UAC2: The first byte from reading the UAC2_TE_CONNECTOR control returns the
2131 	 * number of channels connected.
2132 	 *
2133 	 * UAC3: The first byte specifies size of bitmap for the inserted controls. The
2134 	 * following byte(s) specifies which connectors are inserted.
2135 	 *
2136 	 * This boolean ctl will simply report if any channels are connected
2137 	 * or not.
2138 	 */
2139 	if (mixer->protocol == UAC_VERSION_2)
2140 		cval->control = UAC2_TE_CONNECTOR;
2141 	else /* UAC_VERSION_3 */
2142 		cval->control = UAC3_TE_INSERTION;
2143 
2144 	cval->val_type = USB_MIXER_BOOLEAN;
2145 	cval->channels = 1; /* report true if any channel is connected */
2146 	cval->min = 0;
2147 	cval->max = 1;
2148 	kctl = snd_ctl_new1(&usb_connector_ctl_ro, cval);
2149 	if (!kctl) {
2150 		usb_audio_err(mixer->chip, "cannot malloc kcontrol\n");
2151 		usb_mixer_elem_info_free(cval);
2152 		return;
2153 	}
2154 
2155 	if (check_mapped_name(map, kctl->id.name, sizeof(kctl->id.name)))
2156 		append_ctl_name(kctl, " Jack");
2157 	else
2158 		get_connector_control_name(mixer, term, is_input, kctl->id.name,
2159 					   sizeof(kctl->id.name));
2160 	kctl->private_free = snd_usb_mixer_elem_free;
2161 	snd_usb_mixer_add_control(&cval->head, kctl);
2162 }
2163 
2164 static int parse_clock_source_unit(struct mixer_build *state, int unitid,
2165 				   void *_ftr)
2166 {
2167 	struct uac_clock_source_descriptor *hdr = _ftr;
2168 	struct usb_mixer_elem_info *cval;
2169 	struct snd_kcontrol *kctl;
2170 	int ret;
2171 
2172 	if (state->mixer->protocol != UAC_VERSION_2)
2173 		return -EINVAL;
2174 
2175 	/*
2176 	 * The only property of this unit we are interested in is the
2177 	 * clock source validity. If that isn't readable, just bail out.
2178 	 */
2179 	if (!uac_v2v3_control_is_readable(hdr->bmControls,
2180 				      UAC2_CS_CONTROL_CLOCK_VALID))
2181 		return 0;
2182 
2183 	cval = kzalloc_obj(*cval);
2184 	if (!cval)
2185 		return -ENOMEM;
2186 
2187 	snd_usb_mixer_elem_init_std(&cval->head, state->mixer, hdr->bClockID);
2188 
2189 	cval->min = 0;
2190 	cval->max = 1;
2191 	cval->channels = 1;
2192 	cval->val_type = USB_MIXER_BOOLEAN;
2193 	cval->control = UAC2_CS_CONTROL_CLOCK_VALID;
2194 
2195 	cval->master_readonly = 1;
2196 	/* From UAC2 5.2.5.1.2 "Only the get request is supported." */
2197 	kctl = snd_ctl_new1(&usb_bool_master_control_ctl_ro, cval);
2198 
2199 	if (!kctl) {
2200 		usb_mixer_elem_info_free(cval);
2201 		return -ENOMEM;
2202 	}
2203 
2204 	kctl->private_free = snd_usb_mixer_elem_free;
2205 	ret = snd_usb_copy_string_desc(state->chip, hdr->iClockSource,
2206 				       kctl->id.name, sizeof(kctl->id.name));
2207 	if (ret > 0)
2208 		append_ctl_name(kctl, " Validity");
2209 	else
2210 		snprintf(kctl->id.name, sizeof(kctl->id.name),
2211 			 "Clock Source %d Validity", hdr->bClockID);
2212 
2213 	return snd_usb_mixer_add_control(&cval->head, kctl);
2214 }
2215 
2216 /*
2217  * parse a feature unit
2218  *
2219  * most of controls are defined here.
2220  */
2221 static int parse_audio_feature_unit(struct mixer_build *state, int unitid,
2222 				    void *_ftr)
2223 {
2224 	int channels, i, j;
2225 	struct usb_audio_term iterm;
2226 	unsigned int master_bits;
2227 	int err, csize;
2228 	struct uac_feature_unit_descriptor *hdr = _ftr;
2229 	__u8 *bmaControls;
2230 
2231 	if (state->mixer->protocol == UAC_VERSION_1) {
2232 		csize = hdr->bControlSize;
2233 		channels = (hdr->bLength - 7) / csize - 1;
2234 		bmaControls = hdr->bmaControls;
2235 	} else if (state->mixer->protocol == UAC_VERSION_2) {
2236 		struct uac2_feature_unit_descriptor *ftr = _ftr;
2237 		csize = 4;
2238 		channels = (hdr->bLength - 6) / 4 - 1;
2239 		bmaControls = ftr->bmaControls;
2240 	} else { /* UAC_VERSION_3 */
2241 		struct uac3_feature_unit_descriptor *ftr = _ftr;
2242 
2243 		csize = 4;
2244 		channels = (ftr->bLength - 7) / 4 - 1;
2245 		bmaControls = ftr->bmaControls;
2246 	}
2247 
2248 	if (channels > MAX_CHANNELS) {
2249 		usb_audio_info(state->chip,
2250 			       "usbmixer: too many channels (%d) in unit %d\n",
2251 			       channels, unitid);
2252 		return -EINVAL;
2253 	}
2254 
2255 	/* parse the source unit */
2256 	err = parse_audio_unit(state, hdr->bSourceID);
2257 	if (err < 0)
2258 		return err;
2259 
2260 	/* determine the input source type and name */
2261 	err = check_input_term(state, hdr->bSourceID, &iterm);
2262 	if (err < 0)
2263 		return err;
2264 
2265 	master_bits = snd_usb_combine_bytes(bmaControls, csize);
2266 	/* master configuration quirks */
2267 	switch (state->chip->usb_id) {
2268 	case USB_ID(0x08bb, 0x2702):
2269 		usb_audio_info(state->chip,
2270 			       "usbmixer: master volume quirk for PCM2702 chip\n");
2271 		/* disable non-functional volume control */
2272 		master_bits &= ~UAC_CONTROL_BIT(UAC_FU_VOLUME);
2273 		break;
2274 	case USB_ID(0x1130, 0xf211):
2275 		usb_audio_info(state->chip,
2276 			       "usbmixer: volume control quirk for Tenx TP6911 Audio Headset\n");
2277 		/* disable non-functional volume control */
2278 		channels = 0;
2279 		break;
2280 
2281 	}
2282 
2283 	if (state->mixer->protocol == UAC_VERSION_1) {
2284 		/* check all control types */
2285 		for (i = 0; i < 10; i++) {
2286 			u64 ch_bits = 0;
2287 			int control = audio_feature_info[i].control;
2288 
2289 			for (j = 0; j < channels; j++) {
2290 				unsigned int mask;
2291 
2292 				mask = snd_usb_combine_bytes(bmaControls +
2293 							     csize * (j+1), csize);
2294 				if (mask & BIT(i))
2295 					ch_bits |= BIT(j);
2296 			}
2297 			/* audio class v1 controls are never read-only */
2298 
2299 			/*
2300 			 * The first channel must be set
2301 			 * (for ease of programming).
2302 			 */
2303 			if (ch_bits & 1)
2304 				build_feature_ctl(state, _ftr, ch_bits, control,
2305 						  &iterm, unitid, 0);
2306 			if (master_bits & BIT(i))
2307 				build_feature_ctl(state, _ftr, 0, control,
2308 						  &iterm, unitid, 0);
2309 		}
2310 	} else { /* UAC_VERSION_2/3 */
2311 		for (i = 0; i < ARRAY_SIZE(audio_feature_info); i++) {
2312 			u64 ch_bits = 0;
2313 			unsigned int ch_read_only = 0;
2314 			int control = audio_feature_info[i].control;
2315 
2316 			for (j = 0; j < channels; j++) {
2317 				unsigned int mask;
2318 
2319 				mask = snd_usb_combine_bytes(bmaControls +
2320 							     csize * (j+1), csize);
2321 				if (uac_v2v3_control_is_readable(mask, control)) {
2322 					ch_bits |= BIT(j);
2323 					if (!uac_v2v3_control_is_writeable(mask, control))
2324 						ch_read_only |= BIT(j);
2325 				}
2326 			}
2327 
2328 			/*
2329 			 * NOTE: build_feature_ctl() will mark the control
2330 			 * read-only if all channels are marked read-only in
2331 			 * the descriptors. Otherwise, the control will be
2332 			 * reported as writeable, but the driver will not
2333 			 * actually issue a write command for read-only
2334 			 * channels.
2335 			 */
2336 
2337 			/*
2338 			 * The first channel must be set
2339 			 * (for ease of programming).
2340 			 */
2341 			if (ch_bits & 1)
2342 				build_feature_ctl(state, _ftr, ch_bits, control,
2343 						  &iterm, unitid, ch_read_only);
2344 			if (uac_v2v3_control_is_readable(master_bits, control))
2345 				build_feature_ctl(state, _ftr, 0, control,
2346 						  &iterm, unitid,
2347 						  !uac_v2v3_control_is_writeable(master_bits,
2348 										 control));
2349 		}
2350 	}
2351 
2352 	return 0;
2353 }
2354 
2355 /*
2356  * Mixer Unit
2357  */
2358 
2359 /* check whether the given in/out overflows bmMixerControls matrix */
2360 static bool mixer_bitmap_overflow(struct uac_mixer_unit_descriptor *desc,
2361 				  int protocol, int num_ins, int num_outs)
2362 {
2363 	u8 *hdr = (u8 *)desc;
2364 	u8 *c = uac_mixer_unit_bmControls(desc, protocol);
2365 	size_t rest; /* remaining bytes after bmMixerControls */
2366 
2367 	switch (protocol) {
2368 	case UAC_VERSION_1:
2369 	default:
2370 		rest = 1; /* iMixer */
2371 		break;
2372 	case UAC_VERSION_2:
2373 		rest = 2; /* bmControls + iMixer */
2374 		break;
2375 	case UAC_VERSION_3:
2376 		rest = 6; /* bmControls + wMixerDescrStr */
2377 		break;
2378 	}
2379 
2380 	/* overflow? */
2381 	return c + (num_ins * num_outs + 7) / 8 + rest > hdr + hdr[0];
2382 }
2383 
2384 /*
2385  * build a mixer unit control
2386  *
2387  * the callbacks are identical with feature unit.
2388  * input channel number (zero based) is given in control field instead.
2389  */
2390 static void build_mixer_unit_ctl(struct mixer_build *state,
2391 				 struct uac_mixer_unit_descriptor *desc,
2392 				 int in_ch, int num_outs,
2393 				 int unitid, struct usb_audio_term *iterm)
2394 {
2395 	struct usb_mixer_elem_info *cval;
2396 	unsigned int i, len;
2397 	struct snd_kcontrol *kctl;
2398 	const struct usbmix_name_map *map;
2399 	int ret;
2400 
2401 	map = find_map(state->map, unitid, 0);
2402 	if (check_ignored_ctl(map))
2403 		return;
2404 
2405 	cval = kzalloc_obj(*cval);
2406 	if (!cval)
2407 		return;
2408 
2409 	snd_usb_mixer_elem_init_std(&cval->head, state->mixer, unitid);
2410 	cval->control = in_ch + 1; /* based on 1 */
2411 	if (state->mixer->protocol == UAC_VERSION_2 ||
2412 	    state->mixer->protocol == UAC_VERSION_3)
2413 		cval->v2_mixer = true;
2414 	cval->num_outputs = num_outs;
2415 	cval->val_type = USB_MIXER_S16;
2416 	for (i = 0; i < num_outs; i++) {
2417 		__u8 *c = uac_mixer_unit_bmControls(desc, state->mixer->protocol);
2418 
2419 		if (check_matrix_bitmap(c, in_ch, i, num_outs)) {
2420 			cval->cmask |= BIT(i);
2421 			cval->channels++;
2422 		}
2423 	}
2424 
2425 	/* get min/max values */
2426 	ret = get_min_max(cval, 0);
2427 	if (ret < 0 && ret != -EAGAIN) {
2428 		usb_mixer_elem_info_free(cval);
2429 		return;
2430 	}
2431 
2432 	kctl = snd_ctl_new1(&usb_feature_unit_ctl, cval);
2433 	if (!kctl) {
2434 		usb_audio_err(state->chip, "cannot malloc kcontrol\n");
2435 		usb_mixer_elem_info_free(cval);
2436 		return;
2437 	}
2438 	kctl->private_free = snd_usb_mixer_elem_free;
2439 
2440 	len = check_mapped_name(map, kctl->id.name, sizeof(kctl->id.name));
2441 	if (!len)
2442 		len = get_term_name(state->chip, iterm, kctl->id.name,
2443 				    sizeof(kctl->id.name), 0);
2444 	if (!len)
2445 		snprintf(kctl->id.name, sizeof(kctl->id.name), "Mixer Source %d", in_ch + 1);
2446 
2447 	append_ctl_name(kctl, " Volume");
2448 
2449 	usb_audio_dbg(state->chip, "[%d] MU [%s] ch = %d, val = %d/%d\n",
2450 		    cval->head.id, kctl->id.name, cval->channels, cval->min, cval->max);
2451 	snd_usb_mixer_add_control(&cval->head, kctl);
2452 }
2453 
2454 static int parse_audio_input_terminal(struct mixer_build *state, int unitid,
2455 				      void *raw_desc)
2456 {
2457 	struct usb_audio_term iterm;
2458 	unsigned int control, bmctls, term_id;
2459 
2460 	if (state->mixer->protocol == UAC_VERSION_2) {
2461 		struct uac2_input_terminal_descriptor *d_v2 = raw_desc;
2462 		control = UAC2_TE_CONNECTOR;
2463 		term_id = d_v2->bTerminalID;
2464 		bmctls = le16_to_cpu(d_v2->bmControls);
2465 	} else if (state->mixer->protocol == UAC_VERSION_3) {
2466 		struct uac3_input_terminal_descriptor *d_v3 = raw_desc;
2467 		control = UAC3_TE_INSERTION;
2468 		term_id = d_v3->bTerminalID;
2469 		bmctls = le32_to_cpu(d_v3->bmControls);
2470 	} else {
2471 		return 0; /* UAC1. No Insertion control */
2472 	}
2473 
2474 	check_input_term(state, term_id, &iterm);
2475 
2476 	/* Check for jack detection. */
2477 	if ((iterm.type & 0xff00) != 0x0100 &&
2478 	    uac_v2v3_control_is_readable(bmctls, control))
2479 		build_connector_control(state->mixer, state->map, &iterm, true);
2480 
2481 	return 0;
2482 }
2483 
2484 /*
2485  * parse a mixer unit
2486  */
2487 /* UAC1 mixer unit */
2488 static int parse_audio_mixer_unit_v1(struct mixer_build *state, int unitid,
2489 				     int input_pins, int num_outs,
2490 				     struct uac_mixer_unit_descriptor *desc)
2491 {
2492 	struct usb_audio_term iterm;
2493 	int num_ins, pin, ich, och, err;
2494 
2495 	num_ins = 0;
2496 	ich = 0;
2497 	for (pin = 0; pin < input_pins; pin++) {
2498 		err = parse_audio_unit(state, desc->baSourceID[pin]);
2499 		if (err < 0)
2500 			continue;
2501 		/* no bmControls field (e.g. Maya44) -> ignore */
2502 		if (!num_outs)
2503 			continue;
2504 		err = check_input_term(state, desc->baSourceID[pin], &iterm);
2505 		if (err < 0)
2506 			return err;
2507 		num_ins += iterm.channels;
2508 		if (mixer_bitmap_overflow(desc, state->mixer->protocol,
2509 					  num_ins, num_outs))
2510 			break;
2511 		for (; ich < num_ins; ich++) {
2512 			for (och = 0; och < num_outs; och++) {
2513 				__u8 *c = uac_mixer_unit_bmControls(desc,
2514 						state->mixer->protocol);
2515 
2516 				if (check_matrix_bitmap(c, ich, och, num_outs))
2517 					break;
2518 			}
2519 			if (och < num_outs)
2520 				build_mixer_unit_ctl(state, desc, ich, num_outs,
2521 						     unitid, &iterm);
2522 		}
2523 	}
2524 	return 0;
2525 }
2526 
2527 /* UAC2/UAC3 mixer unit */
2528 static int parse_audio_mixer_unit_v2(struct mixer_build *state, int unitid,
2529 				     int input_pins, int num_outs,
2530 				     struct uac_mixer_unit_descriptor *desc)
2531 {
2532 	struct usb_audio_term iterm;
2533 	int pin, och, err;
2534 
2535 	if (input_pins * num_outs > 256 ||
2536 	    mixer_bitmap_overflow(desc, state->mixer->protocol,
2537 				  input_pins, num_outs)) {
2538 		usb_audio_err(state->chip,
2539 			      "invalid channels for MIXER UNIT %d: input=%d, output=%d\n",
2540 			      unitid, input_pins, num_outs);
2541 		return -EINVAL;
2542 	}
2543 
2544 	for (pin = 0; pin < input_pins; pin++) {
2545 		err = parse_audio_unit(state, desc->baSourceID[pin]);
2546 		if (err < 0)
2547 			continue;
2548 		if (!num_outs)
2549 			continue;
2550 		err = check_input_term(state, desc->baSourceID[pin], &iterm);
2551 		if (err < 0)
2552 			return err;
2553 
2554 		for (och = 0; och < num_outs; och++) {
2555 			__u8 *c = uac_mixer_unit_bmControls(desc,
2556 						state->mixer->protocol);
2557 
2558 			if (check_matrix_bitmap(c, pin, och, num_outs))
2559 				break;
2560 		}
2561 		if (och < num_outs)
2562 			build_mixer_unit_ctl(state, desc, pin, num_outs,
2563 					     unitid, &iterm);
2564 	}
2565 	return 0;
2566 }
2567 
2568 static int parse_audio_mixer_unit(struct mixer_build *state, int unitid,
2569 				  void *raw_desc)
2570 {
2571 	struct uac_mixer_unit_descriptor *desc = raw_desc;
2572 	int num_outs;
2573 
2574 	num_outs = uac_mixer_unit_get_channels(state, desc);
2575 	if (num_outs < 0) {
2576 		usb_audio_err(state->chip,
2577 			      "invalid MIXER UNIT descriptor %d\n",
2578 			      unitid);
2579 		return num_outs;
2580 	}
2581 
2582 	switch (state->mixer->protocol) {
2583 	case UAC_VERSION_1:
2584 	default:
2585 		return parse_audio_mixer_unit_v1(state, unitid,
2586 						 desc->bNrInPins, num_outs,
2587 						 desc);
2588 	case UAC_VERSION_2:
2589 	case UAC_VERSION_3:
2590 		return parse_audio_mixer_unit_v2(state, unitid,
2591 						 desc->bNrInPins, num_outs,
2592 						 desc);
2593 	}
2594 }
2595 
2596 /*
2597  * Processing Unit / Extension Unit
2598  */
2599 
2600 /* get callback for processing/extension unit */
2601 static int mixer_ctl_procunit_get(struct snd_kcontrol *kcontrol,
2602 				  struct snd_ctl_elem_value *ucontrol)
2603 {
2604 	struct usb_mixer_elem_info *cval = snd_kcontrol_chip(kcontrol);
2605 	int err, val;
2606 
2607 	guard(mutex)(&cval->head.mixer->lock);
2608 	err = get_cur_ctl_value(cval, cval->control << 8, &val);
2609 	if (err < 0) {
2610 		ucontrol->value.integer.value[0] = cval->min;
2611 		return filter_error(cval, err);
2612 	}
2613 	val = get_relative_value(cval, val);
2614 	ucontrol->value.integer.value[0] = val;
2615 	return 0;
2616 }
2617 
2618 /* put callback for processing/extension unit */
2619 static int mixer_ctl_procunit_put(struct snd_kcontrol *kcontrol,
2620 				  struct snd_ctl_elem_value *ucontrol)
2621 {
2622 	struct usb_mixer_elem_info *cval = snd_kcontrol_chip(kcontrol);
2623 	int val, oval, err;
2624 
2625 	guard(mutex)(&cval->head.mixer->lock);
2626 	err = get_cur_ctl_value(cval, cval->control << 8, &oval);
2627 	if (err < 0)
2628 		return filter_error(cval, err);
2629 	val = ucontrol->value.integer.value[0];
2630 	if (val < 0 || val > get_max_exposed(cval))
2631 		return -EINVAL;
2632 	val = get_abs_value(cval, val);
2633 	if (val != oval) {
2634 		err = set_cur_ctl_value(cval, cval->control << 8, val);
2635 		if (err < 0)
2636 			return filter_error(cval, err);
2637 		return 1;
2638 	}
2639 	return 0;
2640 }
2641 
2642 /* alsa control interface for processing/extension unit */
2643 static const struct snd_kcontrol_new mixer_procunit_ctl = {
2644 	.iface = SNDRV_CTL_ELEM_IFACE_MIXER,
2645 	.name = "", /* will be filled later */
2646 	.info = mixer_ctl_feature_info,
2647 	.get = mixer_ctl_procunit_get,
2648 	.put = mixer_ctl_procunit_put,
2649 };
2650 
2651 /*
2652  * predefined data for processing units
2653  */
2654 struct procunit_value_info {
2655 	int control;
2656 	const char *suffix;
2657 	int val_type;
2658 	int min_value;
2659 };
2660 
2661 struct procunit_info {
2662 	int type;
2663 	char *name;
2664 	const struct procunit_value_info *values;
2665 };
2666 
2667 static const struct procunit_value_info undefined_proc_info[] = {
2668 	{ 0x00, "Control Undefined", 0 },
2669 	{ 0 }
2670 };
2671 
2672 static const struct procunit_value_info updown_proc_info[] = {
2673 	{ UAC_UD_ENABLE, "Switch", USB_MIXER_BOOLEAN },
2674 	{ UAC_UD_MODE_SELECT, "Mode Select", USB_MIXER_U8, 1 },
2675 	{ 0 }
2676 };
2677 static const struct procunit_value_info prologic_proc_info[] = {
2678 	{ UAC_DP_ENABLE, "Switch", USB_MIXER_BOOLEAN },
2679 	{ UAC_DP_MODE_SELECT, "Mode Select", USB_MIXER_U8, 1 },
2680 	{ 0 }
2681 };
2682 static const struct procunit_value_info threed_enh_proc_info[] = {
2683 	{ UAC_3D_ENABLE, "Switch", USB_MIXER_BOOLEAN },
2684 	{ UAC_3D_SPACE, "Spaciousness", USB_MIXER_U8 },
2685 	{ 0 }
2686 };
2687 static const struct procunit_value_info reverb_proc_info[] = {
2688 	{ UAC_REVERB_ENABLE, "Switch", USB_MIXER_BOOLEAN },
2689 	{ UAC_REVERB_LEVEL, "Level", USB_MIXER_U8 },
2690 	{ UAC_REVERB_TIME, "Time", USB_MIXER_U16 },
2691 	{ UAC_REVERB_FEEDBACK, "Feedback", USB_MIXER_U8 },
2692 	{ 0 }
2693 };
2694 static const struct procunit_value_info chorus_proc_info[] = {
2695 	{ UAC_CHORUS_ENABLE, "Switch", USB_MIXER_BOOLEAN },
2696 	{ UAC_CHORUS_LEVEL, "Level", USB_MIXER_U8 },
2697 	{ UAC_CHORUS_RATE, "Rate", USB_MIXER_U16 },
2698 	{ UAC_CHORUS_DEPTH, "Depth", USB_MIXER_U16 },
2699 	{ 0 }
2700 };
2701 static const struct procunit_value_info dcr_proc_info[] = {
2702 	{ UAC_DCR_ENABLE, "Switch", USB_MIXER_BOOLEAN },
2703 	{ UAC_DCR_RATE, "Ratio", USB_MIXER_U16 },
2704 	{ UAC_DCR_MAXAMPL, "Max Amp", USB_MIXER_S16 },
2705 	{ UAC_DCR_THRESHOLD, "Threshold", USB_MIXER_S16 },
2706 	{ UAC_DCR_ATTACK_TIME, "Attack Time", USB_MIXER_U16 },
2707 	{ UAC_DCR_RELEASE_TIME, "Release Time", USB_MIXER_U16 },
2708 	{ 0 }
2709 };
2710 
2711 static const struct procunit_info procunits[] = {
2712 	{ UAC_PROCESS_UP_DOWNMIX, "Up Down", updown_proc_info },
2713 	{ UAC_PROCESS_DOLBY_PROLOGIC, "Dolby Prologic", prologic_proc_info },
2714 	{ UAC_PROCESS_STEREO_EXTENDER, "3D Stereo Extender", threed_enh_proc_info },
2715 	{ UAC_PROCESS_REVERB, "Reverb", reverb_proc_info },
2716 	{ UAC_PROCESS_CHORUS, "Chorus", chorus_proc_info },
2717 	{ UAC_PROCESS_DYN_RANGE_COMP, "DCR", dcr_proc_info },
2718 	{ 0 },
2719 };
2720 
2721 static const struct procunit_value_info uac3_updown_proc_info[] = {
2722 	{ UAC3_UD_MODE_SELECT, "Mode Select", USB_MIXER_U8, 1 },
2723 	{ 0 }
2724 };
2725 static const struct procunit_value_info uac3_stereo_ext_proc_info[] = {
2726 	{ UAC3_EXT_WIDTH_CONTROL, "Width Control", USB_MIXER_U8 },
2727 	{ 0 }
2728 };
2729 
2730 static const struct procunit_info uac3_procunits[] = {
2731 	{ UAC3_PROCESS_UP_DOWNMIX, "Up Down", uac3_updown_proc_info },
2732 	{ UAC3_PROCESS_STEREO_EXTENDER, "3D Stereo Extender", uac3_stereo_ext_proc_info },
2733 	{ UAC3_PROCESS_MULTI_FUNCTION, "Multi-Function", undefined_proc_info },
2734 	{ 0 },
2735 };
2736 
2737 /*
2738  * predefined data for extension units
2739  */
2740 static const struct procunit_value_info clock_rate_xu_info[] = {
2741 	{ USB_XU_CLOCK_RATE_SELECTOR, "Selector", USB_MIXER_U8, 0 },
2742 	{ 0 }
2743 };
2744 static const struct procunit_value_info clock_source_xu_info[] = {
2745 	{ USB_XU_CLOCK_SOURCE_SELECTOR, "External", USB_MIXER_BOOLEAN },
2746 	{ 0 }
2747 };
2748 static const struct procunit_value_info spdif_format_xu_info[] = {
2749 	{ USB_XU_DIGITAL_FORMAT_SELECTOR, "SPDIF/AC3", USB_MIXER_BOOLEAN },
2750 	{ 0 }
2751 };
2752 static const struct procunit_value_info soft_limit_xu_info[] = {
2753 	{ USB_XU_SOFT_LIMIT_SELECTOR, " ", USB_MIXER_BOOLEAN },
2754 	{ 0 }
2755 };
2756 static const struct procunit_info extunits[] = {
2757 	{ USB_XU_CLOCK_RATE, "Clock rate", clock_rate_xu_info },
2758 	{ USB_XU_CLOCK_SOURCE, "DigitalIn CLK source", clock_source_xu_info },
2759 	{ USB_XU_DIGITAL_IO_STATUS, "DigitalOut format:", spdif_format_xu_info },
2760 	{ USB_XU_DEVICE_OPTIONS, "AnalogueIn Soft Limit", soft_limit_xu_info },
2761 	{ 0 }
2762 };
2763 
2764 /*
2765  * build a processing/extension unit
2766  */
2767 static int build_audio_procunit(struct mixer_build *state, int unitid,
2768 				void *raw_desc, const struct procunit_info *list,
2769 				bool extension_unit)
2770 {
2771 	struct uac_processing_unit_descriptor *desc = raw_desc;
2772 	int num_ins;
2773 	struct usb_mixer_elem_info *cval;
2774 	struct snd_kcontrol *kctl;
2775 	int i, err, nameid, type, len, val;
2776 	const struct procunit_info *info;
2777 	const struct procunit_value_info *valinfo;
2778 	const struct usbmix_name_map *map;
2779 	static const struct procunit_value_info default_value_info[] = {
2780 		{ 0x01, "Switch", USB_MIXER_BOOLEAN },
2781 		{ 0 }
2782 	};
2783 	static const struct procunit_info default_info = {
2784 		0, NULL, default_value_info
2785 	};
2786 	const char *name = extension_unit ?
2787 		"Extension Unit" : "Processing Unit";
2788 
2789 	num_ins = desc->bNrInPins;
2790 	for (i = 0; i < num_ins; i++) {
2791 		err = parse_audio_unit(state, desc->baSourceID[i]);
2792 		if (err < 0)
2793 			return err;
2794 	}
2795 
2796 	type = le16_to_cpu(desc->wProcessType);
2797 	for (info = list; info && info->type; info++)
2798 		if (info->type == type)
2799 			break;
2800 	if (!info || !info->type)
2801 		info = &default_info;
2802 
2803 	for (valinfo = info->values; valinfo->control; valinfo++) {
2804 		__u8 *controls = uac_processing_unit_bmControls(desc, state->mixer->protocol);
2805 
2806 		if (state->mixer->protocol == UAC_VERSION_1) {
2807 			if (!(controls[valinfo->control / 8] &
2808 			      BIT((valinfo->control % 8) - 1)))
2809 				continue;
2810 		} else { /* UAC_VERSION_2/3 */
2811 			if (!uac_v2v3_control_is_readable(controls[valinfo->control / 8],
2812 							  valinfo->control))
2813 				continue;
2814 		}
2815 
2816 		map = find_map(state->map, unitid, valinfo->control);
2817 		if (check_ignored_ctl(map))
2818 			continue;
2819 		cval = kzalloc_obj(*cval);
2820 		if (!cval)
2821 			return -ENOMEM;
2822 		snd_usb_mixer_elem_init_std(&cval->head, state->mixer, unitid);
2823 		cval->control = valinfo->control;
2824 		cval->val_type = valinfo->val_type;
2825 		cval->channels = 1;
2826 
2827 		if (state->mixer->protocol > UAC_VERSION_1 &&
2828 		    !uac_v2v3_control_is_writeable(controls[valinfo->control / 8],
2829 						   valinfo->control))
2830 			cval->master_readonly = 1;
2831 
2832 		/* get min/max values */
2833 		switch (type) {
2834 		case USB_XU_CLOCK_RATE:
2835 			/*
2836 			 * E-Mu USB 0404/0202/TrackerPre/0204
2837 			 * samplerate control quirk
2838 			 */
2839 			cval->min = 0;
2840 			cval->max = 5;
2841 			cval->res = 1;
2842 			cval->initialized = 1;
2843 			break;
2844 		case UAC_PROCESS_UP_DOWNMIX: {
2845 			bool mode_sel = false;
2846 
2847 			switch (state->mixer->protocol) {
2848 			case UAC_VERSION_1:
2849 			case UAC_VERSION_2:
2850 			default:
2851 				if (cval->control == UAC_UD_MODE_SELECT)
2852 					mode_sel = true;
2853 				break;
2854 			case UAC_VERSION_3:
2855 				if (cval->control == UAC3_UD_MODE_SELECT)
2856 					mode_sel = true;
2857 				break;
2858 			}
2859 
2860 			if (mode_sel) {
2861 				__u8 *control_spec = uac_processing_unit_specific(desc,
2862 								state->mixer->protocol);
2863 				cval->min = 1;
2864 				cval->max = control_spec[0];
2865 				cval->res = 1;
2866 				cval->initialized = 1;
2867 				break;
2868 			}
2869 
2870 			fallthrough;
2871 		}
2872 		default:
2873 			err = get_min_max(cval, valinfo->min_value);
2874 			if (err < 0 && err != -EAGAIN) {
2875 				usb_mixer_elem_info_free(cval);
2876 				return err;
2877 			}
2878 		}
2879 
2880 		err = get_cur_ctl_value(cval, cval->control << 8, &val);
2881 		if (err < 0) {
2882 			usb_mixer_elem_info_free(cval);
2883 			return -EINVAL;
2884 		}
2885 
2886 		kctl = snd_ctl_new1(&mixer_procunit_ctl, cval);
2887 		if (!kctl) {
2888 			usb_mixer_elem_info_free(cval);
2889 			return -ENOMEM;
2890 		}
2891 		kctl->private_free = snd_usb_mixer_elem_free;
2892 
2893 		if (check_mapped_name(map, kctl->id.name, sizeof(kctl->id.name))) {
2894 			/* nothing */ ;
2895 		} else if (info->name) {
2896 			strscpy(kctl->id.name, info->name, sizeof(kctl->id.name));
2897 		} else {
2898 			if (extension_unit)
2899 				nameid = uac_extension_unit_iExtension(desc, state->mixer->protocol);
2900 			else
2901 				nameid = uac_processing_unit_iProcessing(desc, state->mixer->protocol);
2902 			len = 0;
2903 			if (nameid)
2904 				len = snd_usb_copy_string_desc(state->chip,
2905 							       nameid,
2906 							       kctl->id.name,
2907 							       sizeof(kctl->id.name));
2908 			if (!len)
2909 				strscpy(kctl->id.name, name, sizeof(kctl->id.name));
2910 		}
2911 		append_ctl_name(kctl, " ");
2912 		append_ctl_name(kctl, valinfo->suffix);
2913 
2914 		usb_audio_dbg(state->chip,
2915 			      "[%d] PU [%s] ch = %d, val = %d/%d\n",
2916 			      cval->head.id, kctl->id.name, cval->channels,
2917 			      cval->min, cval->max);
2918 
2919 		err = snd_usb_mixer_add_control(&cval->head, kctl);
2920 		if (err < 0)
2921 			return err;
2922 	}
2923 	return 0;
2924 }
2925 
2926 static int parse_audio_processing_unit(struct mixer_build *state, int unitid,
2927 				       void *raw_desc)
2928 {
2929 	switch (state->mixer->protocol) {
2930 	case UAC_VERSION_1:
2931 	case UAC_VERSION_2:
2932 	default:
2933 		return build_audio_procunit(state, unitid, raw_desc,
2934 					    procunits, false);
2935 	case UAC_VERSION_3:
2936 		return build_audio_procunit(state, unitid, raw_desc,
2937 					    uac3_procunits, false);
2938 	}
2939 }
2940 
2941 static int parse_audio_extension_unit(struct mixer_build *state, int unitid,
2942 				      void *raw_desc)
2943 {
2944 	/*
2945 	 * Note that we parse extension units with processing unit descriptors.
2946 	 * That's ok as the layout is the same.
2947 	 */
2948 	return build_audio_procunit(state, unitid, raw_desc, extunits, true);
2949 }
2950 
2951 /*
2952  * Selector Unit
2953  */
2954 
2955 /*
2956  * info callback for selector unit
2957  * use an enumerator type for routing
2958  */
2959 static int mixer_ctl_selector_info(struct snd_kcontrol *kcontrol,
2960 				   struct snd_ctl_elem_info *uinfo)
2961 {
2962 	struct usb_mixer_elem_info *cval = snd_kcontrol_chip(kcontrol);
2963 	const char **itemlist = (const char **)kcontrol->private_value;
2964 
2965 	if (snd_BUG_ON(!itemlist))
2966 		return -EINVAL;
2967 	return snd_ctl_enum_info(uinfo, 1, cval->max, itemlist);
2968 }
2969 
2970 /* get callback for selector unit */
2971 static int mixer_ctl_selector_get(struct snd_kcontrol *kcontrol,
2972 				  struct snd_ctl_elem_value *ucontrol)
2973 {
2974 	struct usb_mixer_elem_info *cval = snd_kcontrol_chip(kcontrol);
2975 	int val, err;
2976 
2977 	guard(mutex)(&cval->head.mixer->lock);
2978 	err = get_cur_ctl_value(cval, cval->control << 8, &val);
2979 	if (err < 0) {
2980 		ucontrol->value.enumerated.item[0] = 0;
2981 		return filter_error(cval, err);
2982 	}
2983 	val = get_relative_value(cval, val);
2984 	ucontrol->value.enumerated.item[0] = val;
2985 	return 0;
2986 }
2987 
2988 /* put callback for selector unit */
2989 static int mixer_ctl_selector_put(struct snd_kcontrol *kcontrol,
2990 				  struct snd_ctl_elem_value *ucontrol)
2991 {
2992 	struct usb_mixer_elem_info *cval = snd_kcontrol_chip(kcontrol);
2993 	int val, oval, err;
2994 
2995 	guard(mutex)(&cval->head.mixer->lock);
2996 	err = get_cur_ctl_value(cval, cval->control << 8, &oval);
2997 	if (err < 0)
2998 		return filter_error(cval, err);
2999 	val = ucontrol->value.enumerated.item[0];
3000 	if (val < 0 || val >= cval->max) /* here cval->max = # elements */
3001 		return -EINVAL;
3002 	val = get_abs_value(cval, val);
3003 	if (val != oval) {
3004 		err = set_cur_ctl_value(cval, cval->control << 8, val);
3005 		if (err < 0)
3006 			return filter_error(cval, err);
3007 		return 1;
3008 	}
3009 	return 0;
3010 }
3011 
3012 /* alsa control interface for selector unit */
3013 static const struct snd_kcontrol_new mixer_selectunit_ctl = {
3014 	.iface = SNDRV_CTL_ELEM_IFACE_MIXER,
3015 	.name = "", /* will be filled later */
3016 	.info = mixer_ctl_selector_info,
3017 	.get = mixer_ctl_selector_get,
3018 	.put = mixer_ctl_selector_put,
3019 };
3020 
3021 /*
3022  * private free callback.
3023  * free both private_data and private_value
3024  */
3025 static void usb_mixer_selector_elem_free(struct snd_kcontrol *kctl)
3026 {
3027 	int i, num_ins = 0;
3028 
3029 	if (kctl->private_data) {
3030 		struct usb_mixer_elem_info *cval = kctl->private_data;
3031 		num_ins = cval->max;
3032 		usb_mixer_elem_info_free(cval);
3033 		kctl->private_data = NULL;
3034 	}
3035 	if (kctl->private_value) {
3036 		char **itemlist = (char **)kctl->private_value;
3037 		for (i = 0; i < num_ins; i++)
3038 			kfree(itemlist[i]);
3039 		kfree(itemlist);
3040 		kctl->private_value = 0;
3041 	}
3042 }
3043 
3044 /*
3045  * parse a selector unit
3046  */
3047 static int parse_audio_selector_unit(struct mixer_build *state, int unitid,
3048 				     void *raw_desc)
3049 {
3050 	struct uac_selector_unit_descriptor *desc = raw_desc;
3051 	unsigned int i, nameid, len;
3052 	int err;
3053 	struct usb_mixer_elem_info *cval;
3054 	struct snd_kcontrol *kctl;
3055 	const struct usbmix_name_map *map;
3056 	char **namelist;
3057 
3058 	for (i = 0; i < desc->bNrInPins; i++) {
3059 		err = parse_audio_unit(state, desc->baSourceID[i]);
3060 		if (err < 0)
3061 			return err;
3062 	}
3063 
3064 	if (desc->bNrInPins == 1) /* only one ? nonsense! */
3065 		return 0;
3066 
3067 	map = find_map(state->map, unitid, 0);
3068 	if (check_ignored_ctl(map))
3069 		return 0;
3070 
3071 	cval = kzalloc_obj(*cval);
3072 	if (!cval)
3073 		return -ENOMEM;
3074 	snd_usb_mixer_elem_init_std(&cval->head, state->mixer, unitid);
3075 	cval->val_type = USB_MIXER_U8;
3076 	cval->channels = 1;
3077 	cval->min = 1;
3078 	cval->max = desc->bNrInPins;
3079 	cval->res = 1;
3080 	cval->initialized = 1;
3081 
3082 	switch (state->mixer->protocol) {
3083 	case UAC_VERSION_1:
3084 	default:
3085 		cval->control = 0;
3086 		break;
3087 	case UAC_VERSION_2:
3088 	case UAC_VERSION_3:
3089 		if (desc->bDescriptorSubtype == UAC2_CLOCK_SELECTOR ||
3090 		    desc->bDescriptorSubtype == UAC3_CLOCK_SELECTOR)
3091 			cval->control = UAC2_CX_CLOCK_SELECTOR;
3092 		else /* UAC2/3_SELECTOR_UNIT */
3093 			cval->control = UAC2_SU_SELECTOR;
3094 		break;
3095 	}
3096 
3097 	namelist = kcalloc(desc->bNrInPins, sizeof(char *), GFP_KERNEL);
3098 	if (!namelist) {
3099 		err = -ENOMEM;
3100 		goto error_cval;
3101 	}
3102 #define MAX_ITEM_NAME_LEN	64
3103 	for (i = 0; i < desc->bNrInPins; i++) {
3104 		struct usb_audio_term iterm;
3105 		namelist[i] = kmalloc(MAX_ITEM_NAME_LEN, GFP_KERNEL);
3106 		if (!namelist[i]) {
3107 			err = -ENOMEM;
3108 			goto error_name;
3109 		}
3110 		len = check_mapped_selector_name(state, unitid, i, namelist[i],
3111 						 MAX_ITEM_NAME_LEN);
3112 		if (! len && check_input_term(state, desc->baSourceID[i], &iterm) >= 0)
3113 			len = get_term_name(state->chip, &iterm, namelist[i],
3114 					    MAX_ITEM_NAME_LEN, 0);
3115 		if (! len)
3116 			scnprintf(namelist[i], MAX_ITEM_NAME_LEN, "Input %u", i);
3117 	}
3118 
3119 	kctl = snd_ctl_new1(&mixer_selectunit_ctl, cval);
3120 	if (! kctl) {
3121 		usb_audio_err(state->chip, "cannot malloc kcontrol\n");
3122 		err = -ENOMEM;
3123 		goto error_name;
3124 	}
3125 	kctl->private_value = (unsigned long)namelist;
3126 	kctl->private_free = usb_mixer_selector_elem_free;
3127 
3128 	/* check the static mapping table at first */
3129 	len = check_mapped_name(map, kctl->id.name, sizeof(kctl->id.name));
3130 	if (!len) {
3131 		/* no mapping ? */
3132 		switch (state->mixer->protocol) {
3133 		case UAC_VERSION_1:
3134 		case UAC_VERSION_2:
3135 		default:
3136 		/* if iSelector is given, use it */
3137 			nameid = uac_selector_unit_iSelector(desc);
3138 			if (nameid)
3139 				len = snd_usb_copy_string_desc(state->chip,
3140 							nameid, kctl->id.name,
3141 							sizeof(kctl->id.name));
3142 			break;
3143 		case UAC_VERSION_3:
3144 			/* TODO: Class-Specific strings not yet supported */
3145 			break;
3146 		}
3147 
3148 		/* ... or pick up the terminal name at next */
3149 		if (!len)
3150 			len = get_term_name(state->chip, &state->oterm,
3151 				    kctl->id.name, sizeof(kctl->id.name), 0);
3152 		/* ... or use the fixed string "USB" as the last resort */
3153 		if (!len)
3154 			strscpy(kctl->id.name, "USB", sizeof(kctl->id.name));
3155 
3156 		/* and add the proper suffix */
3157 		if (desc->bDescriptorSubtype == UAC2_CLOCK_SELECTOR ||
3158 		    desc->bDescriptorSubtype == UAC3_CLOCK_SELECTOR)
3159 			append_ctl_name(kctl, " Clock Source");
3160 		else if ((state->oterm.type & 0xff00) == 0x0100)
3161 			append_ctl_name(kctl, " Capture Source");
3162 		else
3163 			append_ctl_name(kctl, " Playback Source");
3164 	}
3165 
3166 	usb_audio_dbg(state->chip, "[%d] SU [%s] items = %d\n",
3167 		    cval->head.id, kctl->id.name, desc->bNrInPins);
3168 	return snd_usb_mixer_add_control(&cval->head, kctl);
3169 
3170  error_name:
3171 	for (i = 0; i < desc->bNrInPins; i++)
3172 		kfree(namelist[i]);
3173 	kfree(namelist);
3174  error_cval:
3175 	usb_mixer_elem_info_free(cval);
3176 	return err;
3177 }
3178 
3179 /*
3180  * parse an audio unit recursively
3181  */
3182 
3183 static int parse_audio_unit(struct mixer_build *state, int unitid)
3184 {
3185 	unsigned char *p1;
3186 	int protocol = state->mixer->protocol;
3187 
3188 	if (test_and_set_bit(unitid, state->unitbitmap))
3189 		return 0; /* the unit already visited */
3190 
3191 	p1 = find_audio_control_unit(state, unitid);
3192 	if (!p1) {
3193 		usb_audio_err(state->chip, "unit %d not found!\n", unitid);
3194 		return -EINVAL;
3195 	}
3196 
3197 	if (!snd_usb_validate_audio_desc(p1, protocol)) {
3198 		usb_audio_dbg(state->chip, "invalid unit %d\n", unitid);
3199 		return 0; /* skip invalid unit */
3200 	}
3201 
3202 	switch (PTYPE(protocol, p1[2])) {
3203 	case PTYPE(UAC_VERSION_1, UAC_INPUT_TERMINAL):
3204 	case PTYPE(UAC_VERSION_2, UAC_INPUT_TERMINAL):
3205 	case PTYPE(UAC_VERSION_3, UAC_INPUT_TERMINAL):
3206 		return parse_audio_input_terminal(state, unitid, p1);
3207 	case PTYPE(UAC_VERSION_1, UAC_MIXER_UNIT):
3208 	case PTYPE(UAC_VERSION_2, UAC_MIXER_UNIT):
3209 	case PTYPE(UAC_VERSION_3, UAC3_MIXER_UNIT):
3210 		return parse_audio_mixer_unit(state, unitid, p1);
3211 	case PTYPE(UAC_VERSION_2, UAC2_CLOCK_SOURCE):
3212 	case PTYPE(UAC_VERSION_3, UAC3_CLOCK_SOURCE):
3213 		return parse_clock_source_unit(state, unitid, p1);
3214 	case PTYPE(UAC_VERSION_1, UAC_SELECTOR_UNIT):
3215 	case PTYPE(UAC_VERSION_2, UAC_SELECTOR_UNIT):
3216 	case PTYPE(UAC_VERSION_3, UAC3_SELECTOR_UNIT):
3217 	case PTYPE(UAC_VERSION_2, UAC2_CLOCK_SELECTOR):
3218 	case PTYPE(UAC_VERSION_3, UAC3_CLOCK_SELECTOR):
3219 		return parse_audio_selector_unit(state, unitid, p1);
3220 	case PTYPE(UAC_VERSION_1, UAC_FEATURE_UNIT):
3221 	case PTYPE(UAC_VERSION_2, UAC_FEATURE_UNIT):
3222 	case PTYPE(UAC_VERSION_3, UAC3_FEATURE_UNIT):
3223 		return parse_audio_feature_unit(state, unitid, p1);
3224 	case PTYPE(UAC_VERSION_1, UAC1_PROCESSING_UNIT):
3225 	case PTYPE(UAC_VERSION_2, UAC2_PROCESSING_UNIT_V2):
3226 	case PTYPE(UAC_VERSION_3, UAC3_PROCESSING_UNIT):
3227 		return parse_audio_processing_unit(state, unitid, p1);
3228 	case PTYPE(UAC_VERSION_1, UAC1_EXTENSION_UNIT):
3229 	case PTYPE(UAC_VERSION_2, UAC2_EXTENSION_UNIT_V2):
3230 	case PTYPE(UAC_VERSION_3, UAC3_EXTENSION_UNIT):
3231 		return parse_audio_extension_unit(state, unitid, p1);
3232 	case PTYPE(UAC_VERSION_2, UAC2_EFFECT_UNIT):
3233 	case PTYPE(UAC_VERSION_3, UAC3_EFFECT_UNIT):
3234 		return 0; /* FIXME - effect units not implemented yet */
3235 	default:
3236 		usb_audio_err(state->chip,
3237 			      "unit %u: unexpected type 0x%02x\n",
3238 			      unitid, p1[2]);
3239 		return -EINVAL;
3240 	}
3241 }
3242 
3243 static void snd_usb_mixer_free(struct usb_mixer_interface *mixer)
3244 {
3245 	struct usb_mixer_elem_list *list, *next;
3246 	int id;
3247 
3248 	/* kill pending URBs */
3249 	snd_usb_mixer_disconnect(mixer);
3250 
3251 	/* Unregister controls first, snd_ctl_remove() frees the element */
3252 	if (mixer->id_elems) {
3253 		for (id = 0; id < MAX_ID_ELEMS; id++) {
3254 			for (list = mixer->id_elems[id]; list; list = next) {
3255 				next = list->next_id_elem;
3256 				if (list->kctl)
3257 					snd_ctl_remove(mixer->chip->card, list->kctl);
3258 			}
3259 		}
3260 		kfree(mixer->id_elems);
3261 	}
3262 	if (mixer->urb) {
3263 		kfree(mixer->urb->transfer_buffer);
3264 		usb_free_urb(mixer->urb);
3265 	}
3266 	usb_free_urb(mixer->rc_urb);
3267 	kfree(mixer->rc_setup_packet);
3268 	mutex_destroy(&mixer->lock);
3269 	kfree(mixer);
3270 }
3271 
3272 static int snd_usb_mixer_dev_free(struct snd_device *device)
3273 {
3274 	struct usb_mixer_interface *mixer = device->device_data;
3275 	snd_usb_mixer_free(mixer);
3276 	return 0;
3277 }
3278 
3279 /* UAC3 predefined channels configuration */
3280 struct uac3_badd_profile {
3281 	int subclass;
3282 	const char *name;
3283 	int c_chmask;	/* capture channels mask */
3284 	int p_chmask;	/* playback channels mask */
3285 	int st_chmask;	/* side tone mixing channel mask */
3286 };
3287 
3288 static const struct uac3_badd_profile uac3_badd_profiles[] = {
3289 	{
3290 		/*
3291 		 * BAIF, BAOF or combination of both
3292 		 * IN: Mono or Stereo cfg, Mono alt possible
3293 		 * OUT: Mono or Stereo cfg, Mono alt possible
3294 		 */
3295 		.subclass = UAC3_FUNCTION_SUBCLASS_GENERIC_IO,
3296 		.name = "GENERIC IO",
3297 		.c_chmask = -1,		/* dynamic channels */
3298 		.p_chmask = -1,		/* dynamic channels */
3299 	},
3300 	{
3301 		/* BAOF; Stereo only cfg, Mono alt possible */
3302 		.subclass = UAC3_FUNCTION_SUBCLASS_HEADPHONE,
3303 		.name = "HEADPHONE",
3304 		.p_chmask = 3,
3305 	},
3306 	{
3307 		/* BAOF; Mono or Stereo cfg, Mono alt possible */
3308 		.subclass = UAC3_FUNCTION_SUBCLASS_SPEAKER,
3309 		.name = "SPEAKER",
3310 		.p_chmask = -1,		/* dynamic channels */
3311 	},
3312 	{
3313 		/* BAIF; Mono or Stereo cfg, Mono alt possible */
3314 		.subclass = UAC3_FUNCTION_SUBCLASS_MICROPHONE,
3315 		.name = "MICROPHONE",
3316 		.c_chmask = -1,		/* dynamic channels */
3317 	},
3318 	{
3319 		/*
3320 		 * BAIOF topology
3321 		 * IN: Mono only
3322 		 * OUT: Mono or Stereo cfg, Mono alt possible
3323 		 */
3324 		.subclass = UAC3_FUNCTION_SUBCLASS_HEADSET,
3325 		.name = "HEADSET",
3326 		.c_chmask = 1,
3327 		.p_chmask = -1,		/* dynamic channels */
3328 		.st_chmask = 1,
3329 	},
3330 	{
3331 		/* BAIOF; IN: Mono only; OUT: Stereo only, Mono alt possible */
3332 		.subclass = UAC3_FUNCTION_SUBCLASS_HEADSET_ADAPTER,
3333 		.name = "HEADSET ADAPTER",
3334 		.c_chmask = 1,
3335 		.p_chmask = 3,
3336 		.st_chmask = 1,
3337 	},
3338 	{
3339 		/* BAIF + BAOF; IN: Mono only; OUT: Mono only */
3340 		.subclass = UAC3_FUNCTION_SUBCLASS_SPEAKERPHONE,
3341 		.name = "SPEAKERPHONE",
3342 		.c_chmask = 1,
3343 		.p_chmask = 1,
3344 	},
3345 	{ 0 } /* terminator */
3346 };
3347 
3348 static bool uac3_badd_func_has_valid_channels(struct usb_mixer_interface *mixer,
3349 					      const struct uac3_badd_profile *f,
3350 					      int c_chmask, int p_chmask)
3351 {
3352 	/*
3353 	 * If both playback/capture channels are dynamic, make sure
3354 	 * at least one channel is present
3355 	 */
3356 	if (f->c_chmask < 0 && f->p_chmask < 0) {
3357 		if (!c_chmask && !p_chmask) {
3358 			usb_audio_warn(mixer->chip, "BAAD %s: no channels?",
3359 				       f->name);
3360 			return false;
3361 		}
3362 		return true;
3363 	}
3364 
3365 	if ((f->c_chmask < 0 && !c_chmask) ||
3366 	    (f->c_chmask >= 0 && f->c_chmask != c_chmask)) {
3367 		usb_audio_warn(mixer->chip, "BAAD %s c_chmask mismatch",
3368 			       f->name);
3369 		return false;
3370 	}
3371 	if ((f->p_chmask < 0 && !p_chmask) ||
3372 	    (f->p_chmask >= 0 && f->p_chmask != p_chmask)) {
3373 		usb_audio_warn(mixer->chip, "BAAD %s p_chmask mismatch",
3374 			       f->name);
3375 		return false;
3376 	}
3377 	return true;
3378 }
3379 
3380 /*
3381  * create mixer controls for UAC3 BADD profiles
3382  *
3383  * UAC3 BADD device doesn't contain CS descriptors thus we will guess everything
3384  *
3385  * BADD device may contain Mixer Unit, which doesn't have any controls, skip it
3386  */
3387 static int snd_usb_mixer_controls_badd(struct usb_mixer_interface *mixer,
3388 				       int ctrlif)
3389 {
3390 	struct usb_device *dev = mixer->chip->dev;
3391 	struct usb_interface_assoc_descriptor *assoc;
3392 	int badd_profile = mixer->chip->badd_profile;
3393 	const struct uac3_badd_profile *f;
3394 	const struct usbmix_ctl_map *map;
3395 	int p_chmask = 0, c_chmask = 0, st_chmask = 0;
3396 	int i;
3397 
3398 	assoc = usb_ifnum_to_if(dev, ctrlif)->intf_assoc;
3399 	if (!assoc)
3400 		return -EINVAL;
3401 
3402 	/* Detect BADD capture/playback channels from AS EP descriptors */
3403 	for (i = 0; i < assoc->bInterfaceCount; i++) {
3404 		int intf = assoc->bFirstInterface + i;
3405 
3406 		struct usb_interface *iface;
3407 		struct usb_host_interface *alts;
3408 		struct usb_interface_descriptor *altsd;
3409 		unsigned int maxpacksize;
3410 		char dir_in;
3411 		int chmask, num;
3412 
3413 		if (intf == ctrlif)
3414 			continue;
3415 
3416 		iface = usb_ifnum_to_if(dev, intf);
3417 		if (!iface)
3418 			continue;
3419 
3420 		num = iface->num_altsetting;
3421 
3422 		if (num < 2)
3423 			return -EINVAL;
3424 
3425 		/*
3426 		 * The number of Channels in an AudioStreaming interface
3427 		 * and the audio sample bit resolution (16 bits or 24
3428 		 * bits) can be derived from the wMaxPacketSize field in
3429 		 * the Standard AS Audio Data Endpoint descriptor in
3430 		 * Alternate Setting 1
3431 		 */
3432 		alts = &iface->altsetting[1];
3433 		altsd = get_iface_desc(alts);
3434 
3435 		if (altsd->bNumEndpoints < 1)
3436 			return -EINVAL;
3437 
3438 		/* check direction */
3439 		dir_in = (get_endpoint(alts, 0)->bEndpointAddress & USB_DIR_IN);
3440 		maxpacksize = le16_to_cpu(get_endpoint(alts, 0)->wMaxPacketSize);
3441 
3442 		switch (maxpacksize) {
3443 		default:
3444 			usb_audio_err(mixer->chip,
3445 				"incorrect wMaxPacketSize 0x%x for BADD profile\n",
3446 				maxpacksize);
3447 			return -EINVAL;
3448 		case UAC3_BADD_EP_MAXPSIZE_SYNC_MONO_16:
3449 		case UAC3_BADD_EP_MAXPSIZE_ASYNC_MONO_16:
3450 		case UAC3_BADD_EP_MAXPSIZE_SYNC_MONO_24:
3451 		case UAC3_BADD_EP_MAXPSIZE_ASYNC_MONO_24:
3452 			chmask = 1;
3453 			break;
3454 		case UAC3_BADD_EP_MAXPSIZE_SYNC_STEREO_16:
3455 		case UAC3_BADD_EP_MAXPSIZE_ASYNC_STEREO_16:
3456 		case UAC3_BADD_EP_MAXPSIZE_SYNC_STEREO_24:
3457 		case UAC3_BADD_EP_MAXPSIZE_ASYNC_STEREO_24:
3458 			chmask = 3;
3459 			break;
3460 		}
3461 
3462 		if (dir_in)
3463 			c_chmask = chmask;
3464 		else
3465 			p_chmask = chmask;
3466 	}
3467 
3468 	usb_audio_dbg(mixer->chip,
3469 		"UAC3 BADD profile 0x%x: detected c_chmask=%d p_chmask=%d\n",
3470 		badd_profile, c_chmask, p_chmask);
3471 
3472 	/* check the mapping table */
3473 	for (map = uac3_badd_usbmix_ctl_maps; map->id; map++) {
3474 		if (map->id == badd_profile)
3475 			break;
3476 	}
3477 
3478 	if (!map->id)
3479 		return -EINVAL;
3480 
3481 	for (f = uac3_badd_profiles; f->name; f++) {
3482 		if (badd_profile == f->subclass)
3483 			break;
3484 	}
3485 	if (!f->name)
3486 		return -EINVAL;
3487 	if (!uac3_badd_func_has_valid_channels(mixer, f, c_chmask, p_chmask))
3488 		return -EINVAL;
3489 	st_chmask = f->st_chmask;
3490 
3491 	/* Playback */
3492 	if (p_chmask) {
3493 		/* Master channel, always writable */
3494 		build_feature_ctl_badd(mixer, 0, UAC_FU_MUTE,
3495 				       UAC3_BADD_FU_ID2, map->map);
3496 		/* Mono/Stereo volume channels, always writable */
3497 		build_feature_ctl_badd(mixer, p_chmask, UAC_FU_VOLUME,
3498 				       UAC3_BADD_FU_ID2, map->map);
3499 	}
3500 
3501 	/* Capture */
3502 	if (c_chmask) {
3503 		/* Master channel, always writable */
3504 		build_feature_ctl_badd(mixer, 0, UAC_FU_MUTE,
3505 				       UAC3_BADD_FU_ID5, map->map);
3506 		/* Mono/Stereo volume channels, always writable */
3507 		build_feature_ctl_badd(mixer, c_chmask, UAC_FU_VOLUME,
3508 				       UAC3_BADD_FU_ID5, map->map);
3509 	}
3510 
3511 	/* Side tone-mixing */
3512 	if (st_chmask) {
3513 		/* Master channel, always writable */
3514 		build_feature_ctl_badd(mixer, 0, UAC_FU_MUTE,
3515 				       UAC3_BADD_FU_ID7, map->map);
3516 		/* Mono volume channel, always writable */
3517 		build_feature_ctl_badd(mixer, 1, UAC_FU_VOLUME,
3518 				       UAC3_BADD_FU_ID7, map->map);
3519 	}
3520 
3521 	/* Insertion Control */
3522 	if (f->subclass == UAC3_FUNCTION_SUBCLASS_HEADSET_ADAPTER) {
3523 		struct usb_audio_term iterm, oterm;
3524 
3525 		/* Input Term - Insertion control */
3526 		memset(&iterm, 0, sizeof(iterm));
3527 		iterm.id = UAC3_BADD_IT_ID4;
3528 		iterm.type = UAC_BIDIR_TERMINAL_HEADSET;
3529 		build_connector_control(mixer, map->map, &iterm, true);
3530 
3531 		/* Output Term - Insertion control */
3532 		memset(&oterm, 0, sizeof(oterm));
3533 		oterm.id = UAC3_BADD_OT_ID3;
3534 		oterm.type = UAC_BIDIR_TERMINAL_HEADSET;
3535 		build_connector_control(mixer, map->map, &oterm, false);
3536 	}
3537 
3538 	return 0;
3539 }
3540 
3541 /*
3542  * create mixer controls
3543  *
3544  * walk through all UAC_OUTPUT_TERMINAL descriptors to search for mixers
3545  */
3546 static int snd_usb_mixer_controls(struct usb_mixer_interface *mixer)
3547 {
3548 	struct mixer_build state;
3549 	int err;
3550 	const struct usbmix_ctl_map *map;
3551 	void *p;
3552 
3553 	memset(&state, 0, sizeof(state));
3554 	state.chip = mixer->chip;
3555 	state.mixer = mixer;
3556 	state.buffer = mixer->hostif->extra;
3557 	state.buflen = mixer->hostif->extralen;
3558 
3559 	/* check the mapping table */
3560 	for (map = usbmix_ctl_maps; map->id; map++) {
3561 		if (map->id == state.chip->usb_id) {
3562 			state.map = map->map;
3563 			state.selector_map = map->selector_map;
3564 			mixer->connector_map = map->connector_map;
3565 			break;
3566 		}
3567 	}
3568 
3569 	p = NULL;
3570 	while ((p = snd_usb_find_csint_desc(mixer->hostif->extra,
3571 					    mixer->hostif->extralen,
3572 					    p, UAC_OUTPUT_TERMINAL)) != NULL) {
3573 		if (!snd_usb_validate_audio_desc(p, mixer->protocol))
3574 			continue; /* skip invalid descriptor */
3575 
3576 		if (mixer->protocol == UAC_VERSION_1) {
3577 			struct uac1_output_terminal_descriptor *desc = p;
3578 
3579 			/* mark terminal ID as visited */
3580 			set_bit(desc->bTerminalID, state.unitbitmap);
3581 			state.oterm.id = desc->bTerminalID;
3582 			state.oterm.type = le16_to_cpu(desc->wTerminalType);
3583 			state.oterm.name = desc->iTerminal;
3584 			err = parse_audio_unit(&state, desc->bSourceID);
3585 			if (err < 0 && err != -EINVAL)
3586 				return err;
3587 		} else if (mixer->protocol == UAC_VERSION_2) {
3588 			struct uac2_output_terminal_descriptor *desc = p;
3589 
3590 			/* mark terminal ID as visited */
3591 			set_bit(desc->bTerminalID, state.unitbitmap);
3592 			state.oterm.id = desc->bTerminalID;
3593 			state.oterm.type = le16_to_cpu(desc->wTerminalType);
3594 			state.oterm.name = desc->iTerminal;
3595 			err = parse_audio_unit(&state, desc->bSourceID);
3596 			if (err < 0 && err != -EINVAL)
3597 				return err;
3598 
3599 			/*
3600 			 * For UAC2, use the same approach to also add the
3601 			 * clock selectors
3602 			 */
3603 			err = parse_audio_unit(&state, desc->bCSourceID);
3604 			if (err < 0 && err != -EINVAL)
3605 				return err;
3606 
3607 			if ((state.oterm.type & 0xff00) != 0x0100 &&
3608 			    uac_v2v3_control_is_readable(le16_to_cpu(desc->bmControls),
3609 							 UAC2_TE_CONNECTOR)) {
3610 				build_connector_control(state.mixer, state.map,
3611 							&state.oterm, false);
3612 			}
3613 		} else {  /* UAC_VERSION_3 */
3614 			struct uac3_output_terminal_descriptor *desc = p;
3615 
3616 			/* mark terminal ID as visited */
3617 			set_bit(desc->bTerminalID, state.unitbitmap);
3618 			state.oterm.id = desc->bTerminalID;
3619 			state.oterm.type = le16_to_cpu(desc->wTerminalType);
3620 			state.oterm.name = le16_to_cpu(desc->wTerminalDescrStr);
3621 			err = parse_audio_unit(&state, desc->bSourceID);
3622 			if (err < 0 && err != -EINVAL)
3623 				return err;
3624 
3625 			/*
3626 			 * For UAC3, use the same approach to also add the
3627 			 * clock selectors
3628 			 */
3629 			err = parse_audio_unit(&state, desc->bCSourceID);
3630 			if (err < 0 && err != -EINVAL)
3631 				return err;
3632 
3633 			if ((state.oterm.type & 0xff00) != 0x0100 &&
3634 			    uac_v2v3_control_is_readable(le32_to_cpu(desc->bmControls),
3635 							 UAC3_TE_INSERTION)) {
3636 				build_connector_control(state.mixer, state.map,
3637 							&state.oterm, false);
3638 			}
3639 		}
3640 	}
3641 
3642 	return 0;
3643 }
3644 
3645 static int delegate_notify(struct usb_mixer_interface *mixer, int unitid,
3646 			   u8 *control, u8 *channel)
3647 {
3648 	const struct usbmix_connector_map *map = mixer->connector_map;
3649 
3650 	if (!map)
3651 		return unitid;
3652 
3653 	for (; map->id; map++) {
3654 		if (map->id == unitid) {
3655 			if (control && map->control)
3656 				*control = map->control;
3657 			if (channel && map->channel)
3658 				*channel = map->channel;
3659 			return map->delegated_id;
3660 		}
3661 	}
3662 	return unitid;
3663 }
3664 
3665 void snd_usb_mixer_notify_id(struct usb_mixer_interface *mixer, int unitid)
3666 {
3667 	struct usb_mixer_elem_list *list;
3668 
3669 	unitid = delegate_notify(mixer, unitid, NULL, NULL);
3670 
3671 	for_each_mixer_elem(list, mixer, unitid) {
3672 		struct usb_mixer_elem_info *info;
3673 
3674 		if (!list->is_std_info)
3675 			continue;
3676 		info = mixer_elem_list_to_info(list);
3677 		/* invalidate cache, so the value is read from the device */
3678 		if (!info->get_cur_broken)
3679 			bitmap_zero(info->cached, MAX_CHANNELS + 1);
3680 		snd_ctl_notify(mixer->chip->card, SNDRV_CTL_EVENT_MASK_VALUE,
3681 			       &list->kctl->id);
3682 	}
3683 }
3684 
3685 static void snd_usb_mixer_dump_cval(struct snd_info_buffer *buffer,
3686 				    struct usb_mixer_elem_list *list)
3687 {
3688 	struct usb_mixer_elem_info *cval = mixer_elem_list_to_info(list);
3689 	static const char * const val_types[] = {
3690 		[USB_MIXER_BOOLEAN] = "BOOLEAN",
3691 		[USB_MIXER_INV_BOOLEAN] = "INV_BOOLEAN",
3692 		[USB_MIXER_S8] = "S8",
3693 		[USB_MIXER_U8] = "U8",
3694 		[USB_MIXER_S16] = "S16",
3695 		[USB_MIXER_U16] = "U16",
3696 		[USB_MIXER_S32] = "S32",
3697 		[USB_MIXER_U32] = "U32",
3698 		[USB_MIXER_BESPOKEN] = "BESPOKEN",
3699 	};
3700 	snd_iprintf(buffer, "    Info: id=%i, control=%i, cmask=0x%llx, "
3701 			    "channels=%i, type=\"%s\"\n", cval->head.id,
3702 			    cval->control, cval->cmask, cval->channels,
3703 			    val_types[cval->val_type]);
3704 	snd_iprintf(buffer, "    Volume: min=%i, max=%i, dBmin=%i, dBmax=%i\n",
3705 			    cval->min, cval->max, cval->dBmin, cval->dBmax);
3706 }
3707 
3708 static void snd_usb_mixer_proc_read(struct snd_info_entry *entry,
3709 				    struct snd_info_buffer *buffer)
3710 {
3711 	struct snd_usb_audio *chip = entry->private_data;
3712 	struct usb_mixer_interface *mixer;
3713 	struct usb_mixer_elem_list *list;
3714 	int unitid;
3715 
3716 	list_for_each_entry(mixer, &chip->mixer_list, list) {
3717 		snd_iprintf(buffer,
3718 			"USB Mixer: usb_id=0x%08x, ctrlif=%i, ctlerr=%i\n",
3719 				chip->usb_id, mixer_ctrl_intf(mixer),
3720 				mixer->ignore_ctl_error);
3721 		snd_iprintf(buffer, "Card: %s\n", chip->card->longname);
3722 		for (unitid = 0; unitid < MAX_ID_ELEMS; unitid++) {
3723 			for_each_mixer_elem(list, mixer, unitid) {
3724 				snd_iprintf(buffer, "  Unit: %i\n", list->id);
3725 				if (list->kctl)
3726 					snd_iprintf(buffer,
3727 						    "    Control: name=\"%s\", index=%i\n",
3728 						    list->kctl->id.name,
3729 						    list->kctl->id.index);
3730 				if (list->dump)
3731 					list->dump(buffer, list);
3732 			}
3733 		}
3734 	}
3735 }
3736 
3737 static void snd_usb_mixer_interrupt_v2(struct usb_mixer_interface *mixer,
3738 				       int attribute, int value, int index)
3739 {
3740 	struct usb_mixer_elem_list *list;
3741 	__u8 unitid = (index >> 8) & 0xff;
3742 	__u8 control = (value >> 8) & 0xff;
3743 	__u8 channel = value & 0xff;
3744 	unsigned int count = 0;
3745 
3746 	if (channel > MAX_CHANNELS) {
3747 		usb_audio_dbg(mixer->chip,
3748 			"%s(): bogus channel number %d\n",
3749 			__func__, channel);
3750 		return;
3751 	}
3752 
3753 	unitid = delegate_notify(mixer, unitid, &control, &channel);
3754 
3755 	for_each_mixer_elem(list, mixer, unitid)
3756 		count++;
3757 
3758 	if (count == 0)
3759 		return;
3760 
3761 	for_each_mixer_elem(list, mixer, unitid) {
3762 		struct usb_mixer_elem_info *info;
3763 
3764 		if (!list->kctl)
3765 			continue;
3766 		if (!list->is_std_info)
3767 			continue;
3768 
3769 		info = mixer_elem_list_to_info(list);
3770 		if (count > 1 && info->control != control)
3771 			continue;
3772 
3773 		switch (attribute) {
3774 		case UAC2_CS_CUR:
3775 			/* invalidate cache, so the value is read from the device */
3776 			if (!info->get_cur_broken) {
3777 				if (channel)
3778 					clear_bit(channel, info->cached);
3779 				else /* master channel */
3780 					bitmap_zero(info->cached, MAX_CHANNELS + 1);
3781 			}
3782 
3783 			snd_ctl_notify(mixer->chip->card, SNDRV_CTL_EVENT_MASK_VALUE,
3784 				       &info->head.kctl->id);
3785 			break;
3786 
3787 		case UAC2_CS_RANGE:
3788 			/* TODO */
3789 			break;
3790 
3791 		case UAC2_CS_MEM:
3792 			/* TODO */
3793 			break;
3794 
3795 		default:
3796 			usb_audio_dbg(mixer->chip,
3797 				"unknown attribute %d in interrupt\n",
3798 				attribute);
3799 			break;
3800 		} /* switch */
3801 	}
3802 }
3803 
3804 static void snd_usb_mixer_interrupt(struct urb *urb)
3805 {
3806 	struct usb_mixer_interface *mixer = urb->context;
3807 	int len = urb->actual_length;
3808 	int ustatus = urb->status;
3809 
3810 	if (ustatus != 0)
3811 		goto requeue;
3812 
3813 	if (mixer->protocol == UAC_VERSION_1) {
3814 		struct uac1_status_word *status;
3815 
3816 		for (status = urb->transfer_buffer;
3817 		     len >= sizeof(*status);
3818 		     len -= sizeof(*status), status++) {
3819 			dev_dbg(&urb->dev->dev, "status interrupt: %02x %02x\n",
3820 						status->bStatusType,
3821 						status->bOriginator);
3822 
3823 			/* ignore any notifications not from the control interface */
3824 			if ((status->bStatusType & UAC1_STATUS_TYPE_ORIG_MASK) !=
3825 				UAC1_STATUS_TYPE_ORIG_AUDIO_CONTROL_IF)
3826 				continue;
3827 
3828 			if (status->bStatusType & UAC1_STATUS_TYPE_MEM_CHANGED)
3829 				snd_usb_mixer_rc_memory_change(mixer, status->bOriginator);
3830 			else
3831 				snd_usb_mixer_notify_id(mixer, status->bOriginator);
3832 		}
3833 	} else { /* UAC_VERSION_2 */
3834 		struct uac2_interrupt_data_msg *msg;
3835 
3836 		for (msg = urb->transfer_buffer;
3837 		     len >= sizeof(*msg);
3838 		     len -= sizeof(*msg), msg++) {
3839 			/* drop vendor specific and endpoint requests */
3840 			if ((msg->bInfo & UAC2_INTERRUPT_DATA_MSG_VENDOR) ||
3841 			    (msg->bInfo & UAC2_INTERRUPT_DATA_MSG_EP))
3842 				continue;
3843 
3844 			snd_usb_mixer_interrupt_v2(mixer, msg->bAttribute,
3845 						   le16_to_cpu(msg->wValue),
3846 						   le16_to_cpu(msg->wIndex));
3847 		}
3848 	}
3849 
3850 requeue:
3851 	if (ustatus != -ENOENT &&
3852 	    ustatus != -ECONNRESET &&
3853 	    ustatus != -ESHUTDOWN) {
3854 		urb->dev = mixer->chip->dev;
3855 		usb_submit_urb(urb, GFP_ATOMIC);
3856 	}
3857 }
3858 
3859 /* create the handler for the optional status interrupt endpoint */
3860 static int snd_usb_mixer_status_create(struct usb_mixer_interface *mixer)
3861 {
3862 	struct usb_endpoint_descriptor *ep;
3863 	void *transfer_buffer;
3864 	int buffer_length;
3865 	unsigned int epnum;
3866 
3867 	/* we need one interrupt input endpoint */
3868 	if (get_iface_desc(mixer->hostif)->bNumEndpoints < 1)
3869 		return 0;
3870 	ep = get_endpoint(mixer->hostif, 0);
3871 	if (!usb_endpoint_dir_in(ep) || !usb_endpoint_xfer_int(ep))
3872 		return 0;
3873 
3874 	epnum = usb_endpoint_num(ep);
3875 	buffer_length = le16_to_cpu(ep->wMaxPacketSize);
3876 	transfer_buffer = kmalloc(buffer_length, GFP_KERNEL);
3877 	if (!transfer_buffer)
3878 		return -ENOMEM;
3879 	mixer->urb = usb_alloc_urb(0, GFP_KERNEL);
3880 	if (!mixer->urb) {
3881 		kfree(transfer_buffer);
3882 		return -ENOMEM;
3883 	}
3884 	usb_fill_int_urb(mixer->urb, mixer->chip->dev,
3885 			 usb_rcvintpipe(mixer->chip->dev, epnum),
3886 			 transfer_buffer, buffer_length,
3887 			 snd_usb_mixer_interrupt, mixer, ep->bInterval);
3888 	usb_submit_urb(mixer->urb, GFP_KERNEL);
3889 	return 0;
3890 }
3891 
3892 int snd_usb_create_mixer(struct snd_usb_audio *chip, int ctrlif)
3893 {
3894 	static const struct snd_device_ops dev_ops = {
3895 		.dev_free = snd_usb_mixer_dev_free
3896 	};
3897 	struct usb_mixer_interface *mixer;
3898 	int err;
3899 
3900 	strscpy(chip->card->mixername, "USB Mixer");
3901 
3902 	mixer = kzalloc_obj(*mixer);
3903 	if (!mixer)
3904 		return -ENOMEM;
3905 	mixer->chip = chip;
3906 	mixer->ignore_ctl_error = !!(chip->quirk_flags & QUIRK_FLAG_IGNORE_CTL_ERROR);
3907 	mixer->id_elems = kzalloc_objs(*mixer->id_elems, MAX_ID_ELEMS);
3908 	if (!mixer->id_elems) {
3909 		kfree(mixer);
3910 		return -ENOMEM;
3911 	}
3912 
3913 	mutex_init(&mixer->lock);
3914 
3915 	mixer->hostif = &usb_ifnum_to_if(chip->dev, ctrlif)->altsetting[0];
3916 	switch (get_iface_desc(mixer->hostif)->bInterfaceProtocol) {
3917 	case UAC_VERSION_1:
3918 	default:
3919 		mixer->protocol = UAC_VERSION_1;
3920 		break;
3921 	case UAC_VERSION_2:
3922 		mixer->protocol = UAC_VERSION_2;
3923 		break;
3924 	case UAC_VERSION_3:
3925 		mixer->protocol = UAC_VERSION_3;
3926 		break;
3927 	}
3928 
3929 	if (mixer->protocol == UAC_VERSION_3 &&
3930 			chip->badd_profile >= UAC3_FUNCTION_SUBCLASS_GENERIC_IO) {
3931 		err = snd_usb_mixer_controls_badd(mixer, ctrlif);
3932 		if (err < 0)
3933 			goto _error;
3934 	} else {
3935 		err = snd_usb_mixer_controls(mixer);
3936 		if (err < 0)
3937 			goto _error;
3938 	}
3939 
3940 	err = snd_usb_mixer_status_create(mixer);
3941 	if (err < 0)
3942 		goto _error;
3943 
3944 	err = snd_usb_mixer_apply_create_quirk(mixer);
3945 	if (err < 0)
3946 		goto _error;
3947 
3948 	err = snd_device_new(chip->card, SNDRV_DEV_CODEC, mixer, &dev_ops);
3949 	if (err < 0)
3950 		goto _error;
3951 
3952 	if (list_empty(&chip->mixer_list))
3953 		snd_card_ro_proc_new(chip->card, "usbmixer", chip,
3954 				     snd_usb_mixer_proc_read);
3955 
3956 	list_add(&mixer->list, &chip->mixer_list);
3957 	return 0;
3958 
3959 _error:
3960 	snd_usb_mixer_free(mixer);
3961 	return err;
3962 }
3963 
3964 void snd_usb_mixer_disconnect(struct usb_mixer_interface *mixer)
3965 {
3966 	if (mixer->disconnected)
3967 		return;
3968 	if (mixer->urb)
3969 		usb_kill_urb(mixer->urb);
3970 	if (mixer->rc_urb)
3971 		usb_kill_urb(mixer->rc_urb);
3972 	if (mixer->private_free)
3973 		mixer->private_free(mixer);
3974 	mixer->disconnected = true;
3975 }
3976 
3977 /* stop any bus activity of a mixer */
3978 static void snd_usb_mixer_inactivate(struct usb_mixer_interface *mixer)
3979 {
3980 	usb_kill_urb(mixer->urb);
3981 	usb_kill_urb(mixer->rc_urb);
3982 }
3983 
3984 static int snd_usb_mixer_activate(struct usb_mixer_interface *mixer)
3985 {
3986 	int err;
3987 
3988 	if (mixer->urb) {
3989 		err = usb_submit_urb(mixer->urb, GFP_NOIO);
3990 		if (err < 0)
3991 			return err;
3992 	}
3993 
3994 	return 0;
3995 }
3996 
3997 int snd_usb_mixer_suspend(struct usb_mixer_interface *mixer)
3998 {
3999 	snd_usb_mixer_inactivate(mixer);
4000 	if (mixer->private_suspend)
4001 		mixer->private_suspend(mixer);
4002 	return 0;
4003 }
4004 
4005 static int restore_mixer_value(struct usb_mixer_elem_list *list)
4006 {
4007 	struct usb_mixer_elem_info *cval = mixer_elem_list_to_info(list);
4008 	int c, err, idx;
4009 
4010 	if (cval->val_type == USB_MIXER_BESPOKEN)
4011 		return 0;
4012 
4013 	if (cval->cmask) {
4014 		idx = 0;
4015 		for (c = 0; c < MAX_CHANNELS; c++) {
4016 			if (!(cval->cmask & BIT(c)))
4017 				continue;
4018 			if (test_bit(c + 1, cval->cached)) {
4019 				err = snd_usb_set_cur_mix_value(cval, c + 1, idx,
4020 							cval->cache_val[idx]);
4021 				if (err < 0)
4022 					break;
4023 			}
4024 			idx++;
4025 		}
4026 	} else {
4027 		/* master */
4028 		if (test_bit(0, cval->cached))
4029 			snd_usb_set_cur_mix_value(cval, 0, 0, *cval->cache_val);
4030 	}
4031 
4032 	return 0;
4033 }
4034 
4035 int snd_usb_mixer_resume(struct usb_mixer_interface *mixer)
4036 {
4037 	struct usb_mixer_elem_list *list;
4038 	int id, err;
4039 
4040 	if (mixer->private_resume) {
4041 		err = mixer->private_resume(mixer);
4042 		if (err < 0)
4043 			return err;
4044 	}
4045 
4046 	/* restore cached mixer values */
4047 	for (id = 0; id < MAX_ID_ELEMS; id++) {
4048 		for_each_mixer_elem(list, mixer, id) {
4049 			if (list->resume) {
4050 				err = list->resume(list);
4051 				if (err < 0)
4052 					return err;
4053 			}
4054 		}
4055 	}
4056 
4057 	snd_usb_mixer_resume_quirk(mixer);
4058 
4059 	return snd_usb_mixer_activate(mixer);
4060 }
4061 
4062 void snd_usb_mixer_elem_init_std(struct usb_mixer_elem_list *list,
4063 				 struct usb_mixer_interface *mixer,
4064 				 int unitid)
4065 {
4066 	list->mixer = mixer;
4067 	list->id = unitid;
4068 	list->dump = snd_usb_mixer_dump_cval;
4069 	list->resume = restore_mixer_value;
4070 }
4071