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