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