xref: /openbmc/linux/sound/usb/mixer.c (revision 8bd1369b)
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 UAC_SELECTOR_UNIT:
679 			strcpy(name, "Selector");
680 			return 8;
681 		case UAC1_PROCESSING_UNIT:
682 			strcpy(name, "Process Unit");
683 			return 12;
684 		case UAC1_EXTENSION_UNIT:
685 			strcpy(name, "Ext Unit");
686 			return 8;
687 		case UAC_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 = d->bDescriptorSubtype << 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 = d->bDescriptorSubtype << 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 			case UAC1_EXTENSION_UNIT:
855 			/* UAC2_PROCESSING_UNIT_V2 */
856 			/* UAC2_EFFECT_UNIT */
857 			case UAC2_EXTENSION_UNIT_V2: {
858 				struct uac_processing_unit_descriptor *d = p1;
859 
860 				if (protocol == UAC_VERSION_2 &&
861 					hdr[2] == UAC2_EFFECT_UNIT) {
862 					/* UAC2/UAC1 unit IDs overlap here in an
863 					 * uncompatible way. Ignore this unit for now.
864 					 */
865 					return 0;
866 				}
867 
868 				if (d->bNrInPins) {
869 					id = d->baSourceID[0];
870 					break; /* continue to parse */
871 				}
872 				term->type = d->bDescriptorSubtype << 16; /* virtual type */
873 				term->channels = uac_processing_unit_bNrChannels(d);
874 				term->chconfig = uac_processing_unit_wChannelConfig(d, protocol);
875 				term->name = uac_processing_unit_iProcessing(d, protocol);
876 				return 0;
877 			}
878 			case UAC2_CLOCK_SOURCE: {
879 				struct uac_clock_source_descriptor *d = p1;
880 
881 				term->type = d->bDescriptorSubtype << 16; /* virtual type */
882 				term->id = id;
883 				term->name = d->iClockSource;
884 				return 0;
885 			}
886 			default:
887 				return -ENODEV;
888 			}
889 		} else { /* UAC_VERSION_3 */
890 			switch (hdr[2]) {
891 			case UAC_INPUT_TERMINAL: {
892 				struct uac3_input_terminal_descriptor *d = p1;
893 
894 				/* call recursively to verify that the
895 				 * referenced clock entity is valid */
896 				err = check_input_term(state, d->bCSourceID, term);
897 				if (err < 0)
898 					return err;
899 
900 				/* save input term properties after recursion,
901 				 * to ensure they are not overriden by the
902 				 * recursion calls */
903 				term->id = id;
904 				term->type = le16_to_cpu(d->wTerminalType);
905 
906 				err = get_cluster_channels_v3(state, le16_to_cpu(d->wClusterDescrID));
907 				if (err < 0)
908 					return err;
909 				term->channels = err;
910 
911 				/* REVISIT: UAC3 IT doesn't have channels cfg */
912 				term->chconfig = 0;
913 
914 				term->name = le16_to_cpu(d->wTerminalDescrStr);
915 				return 0;
916 			}
917 			case UAC3_FEATURE_UNIT: {
918 				struct uac3_feature_unit_descriptor *d = p1;
919 
920 				id = d->bSourceID;
921 				break; /* continue to parse */
922 			}
923 			case UAC3_CLOCK_SOURCE: {
924 				struct uac3_clock_source_descriptor *d = p1;
925 
926 				term->type = d->bDescriptorSubtype << 16; /* virtual type */
927 				term->id = id;
928 				term->name = le16_to_cpu(d->wClockSourceStr);
929 				return 0;
930 			}
931 			case UAC3_MIXER_UNIT: {
932 				struct uac_mixer_unit_descriptor *d = p1;
933 
934 				err = uac_mixer_unit_get_channels(state, d);
935 				if (err < 0)
936 					return err;
937 
938 				term->channels = err;
939 				term->type = d->bDescriptorSubtype << 16; /* virtual type */
940 
941 				return 0;
942 			}
943 			default:
944 				return -ENODEV;
945 			}
946 		}
947 	}
948 	return -ENODEV;
949 }
950 
951 /*
952  * Feature Unit
953  */
954 
955 /* feature unit control information */
956 struct usb_feature_control_info {
957 	int control;
958 	const char *name;
959 	int type;	/* data type for uac1 */
960 	int type_uac2;	/* data type for uac2 if different from uac1, else -1 */
961 };
962 
963 static struct usb_feature_control_info audio_feature_info[] = {
964 	{ UAC_FU_MUTE,			"Mute",			USB_MIXER_INV_BOOLEAN, -1 },
965 	{ UAC_FU_VOLUME,		"Volume",		USB_MIXER_S16, -1 },
966 	{ UAC_FU_BASS,			"Tone Control - Bass",	USB_MIXER_S8, -1 },
967 	{ UAC_FU_MID,			"Tone Control - Mid",	USB_MIXER_S8, -1 },
968 	{ UAC_FU_TREBLE,		"Tone Control - Treble", USB_MIXER_S8, -1 },
969 	{ UAC_FU_GRAPHIC_EQUALIZER,	"Graphic Equalizer",	USB_MIXER_S8, -1 }, /* FIXME: not implemented yet */
970 	{ UAC_FU_AUTOMATIC_GAIN,	"Auto Gain Control",	USB_MIXER_BOOLEAN, -1 },
971 	{ UAC_FU_DELAY,			"Delay Control",	USB_MIXER_U16, USB_MIXER_U32 },
972 	{ UAC_FU_BASS_BOOST,		"Bass Boost",		USB_MIXER_BOOLEAN, -1 },
973 	{ UAC_FU_LOUDNESS,		"Loudness",		USB_MIXER_BOOLEAN, -1 },
974 	/* UAC2 specific */
975 	{ UAC2_FU_INPUT_GAIN,		"Input Gain Control",	USB_MIXER_S16, -1 },
976 	{ UAC2_FU_INPUT_GAIN_PAD,	"Input Gain Pad Control", USB_MIXER_S16, -1 },
977 	{ UAC2_FU_PHASE_INVERTER,	 "Phase Inverter Control", USB_MIXER_BOOLEAN, -1 },
978 };
979 
980 /* private_free callback */
981 void snd_usb_mixer_elem_free(struct snd_kcontrol *kctl)
982 {
983 	kfree(kctl->private_data);
984 	kctl->private_data = NULL;
985 }
986 
987 /*
988  * interface to ALSA control for feature/mixer units
989  */
990 
991 /* volume control quirks */
992 static void volume_control_quirks(struct usb_mixer_elem_info *cval,
993 				  struct snd_kcontrol *kctl)
994 {
995 	struct snd_usb_audio *chip = cval->head.mixer->chip;
996 	switch (chip->usb_id) {
997 	case USB_ID(0x0763, 0x2030): /* M-Audio Fast Track C400 */
998 	case USB_ID(0x0763, 0x2031): /* M-Audio Fast Track C600 */
999 		if (strcmp(kctl->id.name, "Effect Duration") == 0) {
1000 			cval->min = 0x0000;
1001 			cval->max = 0xffff;
1002 			cval->res = 0x00e6;
1003 			break;
1004 		}
1005 		if (strcmp(kctl->id.name, "Effect Volume") == 0 ||
1006 		    strcmp(kctl->id.name, "Effect Feedback Volume") == 0) {
1007 			cval->min = 0x00;
1008 			cval->max = 0xff;
1009 			break;
1010 		}
1011 		if (strstr(kctl->id.name, "Effect Return") != NULL) {
1012 			cval->min = 0xb706;
1013 			cval->max = 0xff7b;
1014 			cval->res = 0x0073;
1015 			break;
1016 		}
1017 		if ((strstr(kctl->id.name, "Playback Volume") != NULL) ||
1018 			(strstr(kctl->id.name, "Effect Send") != NULL)) {
1019 			cval->min = 0xb5fb; /* -73 dB = 0xb6ff */
1020 			cval->max = 0xfcfe;
1021 			cval->res = 0x0073;
1022 		}
1023 		break;
1024 
1025 	case USB_ID(0x0763, 0x2081): /* M-Audio Fast Track Ultra 8R */
1026 	case USB_ID(0x0763, 0x2080): /* M-Audio Fast Track Ultra */
1027 		if (strcmp(kctl->id.name, "Effect Duration") == 0) {
1028 			usb_audio_info(chip,
1029 				       "set quirk for FTU Effect Duration\n");
1030 			cval->min = 0x0000;
1031 			cval->max = 0x7f00;
1032 			cval->res = 0x0100;
1033 			break;
1034 		}
1035 		if (strcmp(kctl->id.name, "Effect Volume") == 0 ||
1036 		    strcmp(kctl->id.name, "Effect Feedback Volume") == 0) {
1037 			usb_audio_info(chip,
1038 				       "set quirks for FTU Effect Feedback/Volume\n");
1039 			cval->min = 0x00;
1040 			cval->max = 0x7f;
1041 			break;
1042 		}
1043 		break;
1044 
1045 	case USB_ID(0x0d8c, 0x0103):
1046 		if (!strcmp(kctl->id.name, "PCM Playback Volume")) {
1047 			usb_audio_info(chip,
1048 				 "set volume quirk for CM102-A+/102S+\n");
1049 			cval->min = -256;
1050 		}
1051 		break;
1052 
1053 	case USB_ID(0x0471, 0x0101):
1054 	case USB_ID(0x0471, 0x0104):
1055 	case USB_ID(0x0471, 0x0105):
1056 	case USB_ID(0x0672, 0x1041):
1057 	/* quirk for UDA1321/N101.
1058 	 * note that detection between firmware 2.1.1.7 (N101)
1059 	 * and later 2.1.1.21 is not very clear from datasheets.
1060 	 * I hope that the min value is -15360 for newer firmware --jk
1061 	 */
1062 		if (!strcmp(kctl->id.name, "PCM Playback Volume") &&
1063 		    cval->min == -15616) {
1064 			usb_audio_info(chip,
1065 				 "set volume quirk for UDA1321/N101 chip\n");
1066 			cval->max = -256;
1067 		}
1068 		break;
1069 
1070 	case USB_ID(0x046d, 0x09a4):
1071 		if (!strcmp(kctl->id.name, "Mic Capture Volume")) {
1072 			usb_audio_info(chip,
1073 				"set volume quirk for QuickCam E3500\n");
1074 			cval->min = 6080;
1075 			cval->max = 8768;
1076 			cval->res = 192;
1077 		}
1078 		break;
1079 
1080 	case USB_ID(0x046d, 0x0807): /* Logitech Webcam C500 */
1081 	case USB_ID(0x046d, 0x0808):
1082 	case USB_ID(0x046d, 0x0809):
1083 	case USB_ID(0x046d, 0x0819): /* Logitech Webcam C210 */
1084 	case USB_ID(0x046d, 0x081b): /* HD Webcam c310 */
1085 	case USB_ID(0x046d, 0x081d): /* HD Webcam c510 */
1086 	case USB_ID(0x046d, 0x0825): /* HD Webcam c270 */
1087 	case USB_ID(0x046d, 0x0826): /* HD Webcam c525 */
1088 	case USB_ID(0x046d, 0x08ca): /* Logitech Quickcam Fusion */
1089 	case USB_ID(0x046d, 0x0991):
1090 	case USB_ID(0x046d, 0x09a2): /* QuickCam Communicate Deluxe/S7500 */
1091 	/* Most audio usb devices lie about volume resolution.
1092 	 * Most Logitech webcams have res = 384.
1093 	 * Probably there is some logitech magic behind this number --fishor
1094 	 */
1095 		if (!strcmp(kctl->id.name, "Mic Capture Volume")) {
1096 			usb_audio_info(chip,
1097 				"set resolution quirk: cval->res = 384\n");
1098 			cval->res = 384;
1099 		}
1100 		break;
1101 	}
1102 }
1103 
1104 /*
1105  * retrieve the minimum and maximum values for the specified control
1106  */
1107 static int get_min_max_with_quirks(struct usb_mixer_elem_info *cval,
1108 				   int default_min, struct snd_kcontrol *kctl)
1109 {
1110 	/* for failsafe */
1111 	cval->min = default_min;
1112 	cval->max = cval->min + 1;
1113 	cval->res = 1;
1114 	cval->dBmin = cval->dBmax = 0;
1115 
1116 	if (cval->val_type == USB_MIXER_BOOLEAN ||
1117 	    cval->val_type == USB_MIXER_INV_BOOLEAN) {
1118 		cval->initialized = 1;
1119 	} else {
1120 		int minchn = 0;
1121 		if (cval->cmask) {
1122 			int i;
1123 			for (i = 0; i < MAX_CHANNELS; i++)
1124 				if (cval->cmask & (1 << i)) {
1125 					minchn = i + 1;
1126 					break;
1127 				}
1128 		}
1129 		if (get_ctl_value(cval, UAC_GET_MAX, (cval->control << 8) | minchn, &cval->max) < 0 ||
1130 		    get_ctl_value(cval, UAC_GET_MIN, (cval->control << 8) | minchn, &cval->min) < 0) {
1131 			usb_audio_err(cval->head.mixer->chip,
1132 				      "%d:%d: cannot get min/max values for control %d (id %d)\n",
1133 				   cval->head.id, snd_usb_ctrl_intf(cval->head.mixer->chip),
1134 							       cval->control, cval->head.id);
1135 			return -EINVAL;
1136 		}
1137 		if (get_ctl_value(cval, UAC_GET_RES,
1138 				  (cval->control << 8) | minchn,
1139 				  &cval->res) < 0) {
1140 			cval->res = 1;
1141 		} else {
1142 			int last_valid_res = cval->res;
1143 
1144 			while (cval->res > 1) {
1145 				if (snd_usb_mixer_set_ctl_value(cval, UAC_SET_RES,
1146 								(cval->control << 8) | minchn,
1147 								cval->res / 2) < 0)
1148 					break;
1149 				cval->res /= 2;
1150 			}
1151 			if (get_ctl_value(cval, UAC_GET_RES,
1152 					  (cval->control << 8) | minchn, &cval->res) < 0)
1153 				cval->res = last_valid_res;
1154 		}
1155 		if (cval->res == 0)
1156 			cval->res = 1;
1157 
1158 		/* Additional checks for the proper resolution
1159 		 *
1160 		 * Some devices report smaller resolutions than actually
1161 		 * reacting.  They don't return errors but simply clip
1162 		 * to the lower aligned value.
1163 		 */
1164 		if (cval->min + cval->res < cval->max) {
1165 			int last_valid_res = cval->res;
1166 			int saved, test, check;
1167 			get_cur_mix_raw(cval, minchn, &saved);
1168 			for (;;) {
1169 				test = saved;
1170 				if (test < cval->max)
1171 					test += cval->res;
1172 				else
1173 					test -= cval->res;
1174 				if (test < cval->min || test > cval->max ||
1175 				    snd_usb_set_cur_mix_value(cval, minchn, 0, test) ||
1176 				    get_cur_mix_raw(cval, minchn, &check)) {
1177 					cval->res = last_valid_res;
1178 					break;
1179 				}
1180 				if (test == check)
1181 					break;
1182 				cval->res *= 2;
1183 			}
1184 			snd_usb_set_cur_mix_value(cval, minchn, 0, saved);
1185 		}
1186 
1187 		cval->initialized = 1;
1188 	}
1189 
1190 	if (kctl)
1191 		volume_control_quirks(cval, kctl);
1192 
1193 	/* USB descriptions contain the dB scale in 1/256 dB unit
1194 	 * while ALSA TLV contains in 1/100 dB unit
1195 	 */
1196 	cval->dBmin = (convert_signed_value(cval, cval->min) * 100) / 256;
1197 	cval->dBmax = (convert_signed_value(cval, cval->max) * 100) / 256;
1198 	if (cval->dBmin > cval->dBmax) {
1199 		/* something is wrong; assume it's either from/to 0dB */
1200 		if (cval->dBmin < 0)
1201 			cval->dBmax = 0;
1202 		else if (cval->dBmin > 0)
1203 			cval->dBmin = 0;
1204 		if (cval->dBmin > cval->dBmax) {
1205 			/* totally crap, return an error */
1206 			return -EINVAL;
1207 		}
1208 	}
1209 
1210 	return 0;
1211 }
1212 
1213 #define get_min_max(cval, def)	get_min_max_with_quirks(cval, def, NULL)
1214 
1215 /* get a feature/mixer unit info */
1216 static int mixer_ctl_feature_info(struct snd_kcontrol *kcontrol,
1217 				  struct snd_ctl_elem_info *uinfo)
1218 {
1219 	struct usb_mixer_elem_info *cval = kcontrol->private_data;
1220 
1221 	if (cval->val_type == USB_MIXER_BOOLEAN ||
1222 	    cval->val_type == USB_MIXER_INV_BOOLEAN)
1223 		uinfo->type = SNDRV_CTL_ELEM_TYPE_BOOLEAN;
1224 	else
1225 		uinfo->type = SNDRV_CTL_ELEM_TYPE_INTEGER;
1226 	uinfo->count = cval->channels;
1227 	if (cval->val_type == USB_MIXER_BOOLEAN ||
1228 	    cval->val_type == USB_MIXER_INV_BOOLEAN) {
1229 		uinfo->value.integer.min = 0;
1230 		uinfo->value.integer.max = 1;
1231 	} else {
1232 		if (!cval->initialized) {
1233 			get_min_max_with_quirks(cval, 0, kcontrol);
1234 			if (cval->initialized && cval->dBmin >= cval->dBmax) {
1235 				kcontrol->vd[0].access &=
1236 					~(SNDRV_CTL_ELEM_ACCESS_TLV_READ |
1237 					  SNDRV_CTL_ELEM_ACCESS_TLV_CALLBACK);
1238 				snd_ctl_notify(cval->head.mixer->chip->card,
1239 					       SNDRV_CTL_EVENT_MASK_INFO,
1240 					       &kcontrol->id);
1241 			}
1242 		}
1243 		uinfo->value.integer.min = 0;
1244 		uinfo->value.integer.max =
1245 			(cval->max - cval->min + cval->res - 1) / cval->res;
1246 	}
1247 	return 0;
1248 }
1249 
1250 /* get the current value from feature/mixer unit */
1251 static int mixer_ctl_feature_get(struct snd_kcontrol *kcontrol,
1252 				 struct snd_ctl_elem_value *ucontrol)
1253 {
1254 	struct usb_mixer_elem_info *cval = kcontrol->private_data;
1255 	int c, cnt, val, err;
1256 
1257 	ucontrol->value.integer.value[0] = cval->min;
1258 	if (cval->cmask) {
1259 		cnt = 0;
1260 		for (c = 0; c < MAX_CHANNELS; c++) {
1261 			if (!(cval->cmask & (1 << c)))
1262 				continue;
1263 			err = snd_usb_get_cur_mix_value(cval, c + 1, cnt, &val);
1264 			if (err < 0)
1265 				return filter_error(cval, err);
1266 			val = get_relative_value(cval, val);
1267 			ucontrol->value.integer.value[cnt] = val;
1268 			cnt++;
1269 		}
1270 		return 0;
1271 	} else {
1272 		/* master channel */
1273 		err = snd_usb_get_cur_mix_value(cval, 0, 0, &val);
1274 		if (err < 0)
1275 			return filter_error(cval, err);
1276 		val = get_relative_value(cval, val);
1277 		ucontrol->value.integer.value[0] = val;
1278 	}
1279 	return 0;
1280 }
1281 
1282 /* put the current value to feature/mixer unit */
1283 static int mixer_ctl_feature_put(struct snd_kcontrol *kcontrol,
1284 				 struct snd_ctl_elem_value *ucontrol)
1285 {
1286 	struct usb_mixer_elem_info *cval = kcontrol->private_data;
1287 	int c, cnt, val, oval, err;
1288 	int changed = 0;
1289 
1290 	if (cval->cmask) {
1291 		cnt = 0;
1292 		for (c = 0; c < MAX_CHANNELS; c++) {
1293 			if (!(cval->cmask & (1 << c)))
1294 				continue;
1295 			err = snd_usb_get_cur_mix_value(cval, c + 1, cnt, &oval);
1296 			if (err < 0)
1297 				return filter_error(cval, err);
1298 			val = ucontrol->value.integer.value[cnt];
1299 			val = get_abs_value(cval, val);
1300 			if (oval != val) {
1301 				snd_usb_set_cur_mix_value(cval, c + 1, cnt, val);
1302 				changed = 1;
1303 			}
1304 			cnt++;
1305 		}
1306 	} else {
1307 		/* master channel */
1308 		err = snd_usb_get_cur_mix_value(cval, 0, 0, &oval);
1309 		if (err < 0)
1310 			return filter_error(cval, err);
1311 		val = ucontrol->value.integer.value[0];
1312 		val = get_abs_value(cval, val);
1313 		if (val != oval) {
1314 			snd_usb_set_cur_mix_value(cval, 0, 0, val);
1315 			changed = 1;
1316 		}
1317 	}
1318 	return changed;
1319 }
1320 
1321 /* get the boolean value from the master channel of a UAC control */
1322 static int mixer_ctl_master_bool_get(struct snd_kcontrol *kcontrol,
1323 				     struct snd_ctl_elem_value *ucontrol)
1324 {
1325 	struct usb_mixer_elem_info *cval = kcontrol->private_data;
1326 	int val, err;
1327 
1328 	err = snd_usb_get_cur_mix_value(cval, 0, 0, &val);
1329 	if (err < 0)
1330 		return filter_error(cval, err);
1331 	val = (val != 0);
1332 	ucontrol->value.integer.value[0] = val;
1333 	return 0;
1334 }
1335 
1336 /* get the connectors status and report it as boolean type */
1337 static int mixer_ctl_connector_get(struct snd_kcontrol *kcontrol,
1338 				   struct snd_ctl_elem_value *ucontrol)
1339 {
1340 	struct usb_mixer_elem_info *cval = kcontrol->private_data;
1341 	struct snd_usb_audio *chip = cval->head.mixer->chip;
1342 	int idx = 0, validx, ret, val;
1343 
1344 	validx = cval->control << 8 | 0;
1345 
1346 	ret = snd_usb_lock_shutdown(chip) ? -EIO : 0;
1347 	if (ret)
1348 		goto error;
1349 
1350 	idx = snd_usb_ctrl_intf(chip) | (cval->head.id << 8);
1351 	if (cval->head.mixer->protocol == UAC_VERSION_2) {
1352 		struct uac2_connectors_ctl_blk uac2_conn;
1353 
1354 		ret = snd_usb_ctl_msg(chip->dev, usb_rcvctrlpipe(chip->dev, 0), UAC2_CS_CUR,
1355 				      USB_RECIP_INTERFACE | USB_TYPE_CLASS | USB_DIR_IN,
1356 				      validx, idx, &uac2_conn, sizeof(uac2_conn));
1357 		val = !!uac2_conn.bNrChannels;
1358 	} else { /* UAC_VERSION_3 */
1359 		struct uac3_insertion_ctl_blk uac3_conn;
1360 
1361 		ret = snd_usb_ctl_msg(chip->dev, usb_rcvctrlpipe(chip->dev, 0), UAC2_CS_CUR,
1362 				      USB_RECIP_INTERFACE | USB_TYPE_CLASS | USB_DIR_IN,
1363 				      validx, idx, &uac3_conn, sizeof(uac3_conn));
1364 		val = !!uac3_conn.bmConInserted;
1365 	}
1366 
1367 	snd_usb_unlock_shutdown(chip);
1368 
1369 	if (ret < 0) {
1370 error:
1371 		usb_audio_err(chip,
1372 			"cannot get connectors status: req = %#x, wValue = %#x, wIndex = %#x, type = %d\n",
1373 			UAC_GET_CUR, validx, idx, cval->val_type);
1374 		return ret;
1375 	}
1376 
1377 	ucontrol->value.integer.value[0] = val;
1378 	return 0;
1379 }
1380 
1381 static struct snd_kcontrol_new usb_feature_unit_ctl = {
1382 	.iface = SNDRV_CTL_ELEM_IFACE_MIXER,
1383 	.name = "", /* will be filled later manually */
1384 	.info = mixer_ctl_feature_info,
1385 	.get = mixer_ctl_feature_get,
1386 	.put = mixer_ctl_feature_put,
1387 };
1388 
1389 /* the read-only variant */
1390 static const struct snd_kcontrol_new usb_feature_unit_ctl_ro = {
1391 	.iface = SNDRV_CTL_ELEM_IFACE_MIXER,
1392 	.name = "", /* will be filled later manually */
1393 	.info = mixer_ctl_feature_info,
1394 	.get = mixer_ctl_feature_get,
1395 	.put = NULL,
1396 };
1397 
1398 /*
1399  * A control which shows the boolean value from reading a UAC control on
1400  * the master channel.
1401  */
1402 static struct snd_kcontrol_new usb_bool_master_control_ctl_ro = {
1403 	.iface = SNDRV_CTL_ELEM_IFACE_CARD,
1404 	.name = "", /* will be filled later manually */
1405 	.access = SNDRV_CTL_ELEM_ACCESS_READ,
1406 	.info = snd_ctl_boolean_mono_info,
1407 	.get = mixer_ctl_master_bool_get,
1408 	.put = NULL,
1409 };
1410 
1411 static const struct snd_kcontrol_new usb_connector_ctl_ro = {
1412 	.iface = SNDRV_CTL_ELEM_IFACE_CARD,
1413 	.name = "", /* will be filled later manually */
1414 	.access = SNDRV_CTL_ELEM_ACCESS_READ,
1415 	.info = snd_ctl_boolean_mono_info,
1416 	.get = mixer_ctl_connector_get,
1417 	.put = NULL,
1418 };
1419 
1420 /*
1421  * This symbol is exported in order to allow the mixer quirks to
1422  * hook up to the standard feature unit control mechanism
1423  */
1424 struct snd_kcontrol_new *snd_usb_feature_unit_ctl = &usb_feature_unit_ctl;
1425 
1426 /*
1427  * build a feature control
1428  */
1429 static size_t append_ctl_name(struct snd_kcontrol *kctl, const char *str)
1430 {
1431 	return strlcat(kctl->id.name, str, sizeof(kctl->id.name));
1432 }
1433 
1434 /*
1435  * A lot of headsets/headphones have a "Speaker" mixer. Make sure we
1436  * rename it to "Headphone". We determine if something is a headphone
1437  * similar to how udev determines form factor.
1438  */
1439 static void check_no_speaker_on_headset(struct snd_kcontrol *kctl,
1440 					struct snd_card *card)
1441 {
1442 	const char *names_to_check[] = {
1443 		"Headset", "headset", "Headphone", "headphone", NULL};
1444 	const char **s;
1445 	bool found = false;
1446 
1447 	if (strcmp("Speaker", kctl->id.name))
1448 		return;
1449 
1450 	for (s = names_to_check; *s; s++)
1451 		if (strstr(card->shortname, *s)) {
1452 			found = true;
1453 			break;
1454 		}
1455 
1456 	if (!found)
1457 		return;
1458 
1459 	strlcpy(kctl->id.name, "Headphone", sizeof(kctl->id.name));
1460 }
1461 
1462 static struct usb_feature_control_info *get_feature_control_info(int control)
1463 {
1464 	int i;
1465 
1466 	for (i = 0; i < ARRAY_SIZE(audio_feature_info); ++i) {
1467 		if (audio_feature_info[i].control == control)
1468 			return &audio_feature_info[i];
1469 	}
1470 	return NULL;
1471 }
1472 
1473 static void __build_feature_ctl(struct usb_mixer_interface *mixer,
1474 				const struct usbmix_name_map *imap,
1475 				unsigned int ctl_mask, int control,
1476 				struct usb_audio_term *iterm,
1477 				struct usb_audio_term *oterm,
1478 				int unitid, int nameid, int readonly_mask)
1479 {
1480 	struct usb_feature_control_info *ctl_info;
1481 	unsigned int len = 0;
1482 	int mapped_name = 0;
1483 	struct snd_kcontrol *kctl;
1484 	struct usb_mixer_elem_info *cval;
1485 	const struct usbmix_name_map *map;
1486 	unsigned int range;
1487 
1488 	if (control == UAC_FU_GRAPHIC_EQUALIZER) {
1489 		/* FIXME: not supported yet */
1490 		return;
1491 	}
1492 
1493 	map = find_map(imap, unitid, control);
1494 	if (check_ignored_ctl(map))
1495 		return;
1496 
1497 	cval = kzalloc(sizeof(*cval), GFP_KERNEL);
1498 	if (!cval)
1499 		return;
1500 	snd_usb_mixer_elem_init_std(&cval->head, mixer, unitid);
1501 	cval->control = control;
1502 	cval->cmask = ctl_mask;
1503 
1504 	ctl_info = get_feature_control_info(control);
1505 	if (!ctl_info) {
1506 		kfree(cval);
1507 		return;
1508 	}
1509 	if (mixer->protocol == UAC_VERSION_1)
1510 		cval->val_type = ctl_info->type;
1511 	else /* UAC_VERSION_2 */
1512 		cval->val_type = ctl_info->type_uac2 >= 0 ?
1513 			ctl_info->type_uac2 : ctl_info->type;
1514 
1515 	if (ctl_mask == 0) {
1516 		cval->channels = 1;	/* master channel */
1517 		cval->master_readonly = readonly_mask;
1518 	} else {
1519 		int i, c = 0;
1520 		for (i = 0; i < 16; i++)
1521 			if (ctl_mask & (1 << i))
1522 				c++;
1523 		cval->channels = c;
1524 		cval->ch_readonly = readonly_mask;
1525 	}
1526 
1527 	/*
1528 	 * If all channels in the mask are marked read-only, make the control
1529 	 * read-only. snd_usb_set_cur_mix_value() will check the mask again and won't
1530 	 * issue write commands to read-only channels.
1531 	 */
1532 	if (cval->channels == readonly_mask)
1533 		kctl = snd_ctl_new1(&usb_feature_unit_ctl_ro, cval);
1534 	else
1535 		kctl = snd_ctl_new1(&usb_feature_unit_ctl, cval);
1536 
1537 	if (!kctl) {
1538 		usb_audio_err(mixer->chip, "cannot malloc kcontrol\n");
1539 		kfree(cval);
1540 		return;
1541 	}
1542 	kctl->private_free = snd_usb_mixer_elem_free;
1543 
1544 	len = check_mapped_name(map, kctl->id.name, sizeof(kctl->id.name));
1545 	mapped_name = len != 0;
1546 	if (!len && nameid)
1547 		len = snd_usb_copy_string_desc(mixer->chip, nameid,
1548 				kctl->id.name, sizeof(kctl->id.name));
1549 
1550 	switch (control) {
1551 	case UAC_FU_MUTE:
1552 	case UAC_FU_VOLUME:
1553 		/*
1554 		 * determine the control name.  the rule is:
1555 		 * - if a name id is given in descriptor, use it.
1556 		 * - if the connected input can be determined, then use the name
1557 		 *   of terminal type.
1558 		 * - if the connected output can be determined, use it.
1559 		 * - otherwise, anonymous name.
1560 		 */
1561 		if (!len) {
1562 			if (iterm)
1563 				len = get_term_name(mixer->chip, iterm,
1564 						    kctl->id.name,
1565 						    sizeof(kctl->id.name), 1);
1566 			if (!len && oterm)
1567 				len = get_term_name(mixer->chip, oterm,
1568 						    kctl->id.name,
1569 						    sizeof(kctl->id.name), 1);
1570 			if (!len)
1571 				snprintf(kctl->id.name, sizeof(kctl->id.name),
1572 					 "Feature %d", unitid);
1573 		}
1574 
1575 		if (!mapped_name)
1576 			check_no_speaker_on_headset(kctl, mixer->chip->card);
1577 
1578 		/*
1579 		 * determine the stream direction:
1580 		 * if the connected output is USB stream, then it's likely a
1581 		 * capture stream.  otherwise it should be playback (hopefully :)
1582 		 */
1583 		if (!mapped_name && oterm && !(oterm->type >> 16)) {
1584 			if ((oterm->type & 0xff00) == 0x0100)
1585 				append_ctl_name(kctl, " Capture");
1586 			else
1587 				append_ctl_name(kctl, " Playback");
1588 		}
1589 		append_ctl_name(kctl, control == UAC_FU_MUTE ?
1590 				" Switch" : " Volume");
1591 		break;
1592 	default:
1593 		if (!len)
1594 			strlcpy(kctl->id.name, audio_feature_info[control-1].name,
1595 				sizeof(kctl->id.name));
1596 		break;
1597 	}
1598 
1599 	/* get min/max values */
1600 	get_min_max_with_quirks(cval, 0, kctl);
1601 
1602 	if (control == UAC_FU_VOLUME) {
1603 		check_mapped_dB(map, cval);
1604 		if (cval->dBmin < cval->dBmax || !cval->initialized) {
1605 			kctl->tlv.c = snd_usb_mixer_vol_tlv;
1606 			kctl->vd[0].access |=
1607 				SNDRV_CTL_ELEM_ACCESS_TLV_READ |
1608 				SNDRV_CTL_ELEM_ACCESS_TLV_CALLBACK;
1609 		}
1610 	}
1611 
1612 	snd_usb_mixer_fu_apply_quirk(mixer, cval, unitid, kctl);
1613 
1614 	range = (cval->max - cval->min) / cval->res;
1615 	/*
1616 	 * Are there devices with volume range more than 255? I use a bit more
1617 	 * to be sure. 384 is a resolution magic number found on Logitech
1618 	 * devices. It will definitively catch all buggy Logitech devices.
1619 	 */
1620 	if (range > 384) {
1621 		usb_audio_warn(mixer->chip,
1622 			       "Warning! Unlikely big volume range (=%u), cval->res is probably wrong.",
1623 			       range);
1624 		usb_audio_warn(mixer->chip,
1625 			       "[%d] FU [%s] ch = %d, val = %d/%d/%d",
1626 			       cval->head.id, kctl->id.name, cval->channels,
1627 			       cval->min, cval->max, cval->res);
1628 	}
1629 
1630 	usb_audio_dbg(mixer->chip, "[%d] FU [%s] ch = %d, val = %d/%d/%d\n",
1631 		      cval->head.id, kctl->id.name, cval->channels,
1632 		      cval->min, cval->max, cval->res);
1633 	snd_usb_mixer_add_control(&cval->head, kctl);
1634 }
1635 
1636 static void build_feature_ctl(struct mixer_build *state, void *raw_desc,
1637 			      unsigned int ctl_mask, int control,
1638 			      struct usb_audio_term *iterm, int unitid,
1639 			      int readonly_mask)
1640 {
1641 	struct uac_feature_unit_descriptor *desc = raw_desc;
1642 	int nameid = uac_feature_unit_iFeature(desc);
1643 
1644 	__build_feature_ctl(state->mixer, state->map, ctl_mask, control,
1645 			iterm, &state->oterm, unitid, nameid, readonly_mask);
1646 }
1647 
1648 static void build_feature_ctl_badd(struct usb_mixer_interface *mixer,
1649 			      unsigned int ctl_mask, int control, int unitid,
1650 			      const struct usbmix_name_map *badd_map)
1651 {
1652 	__build_feature_ctl(mixer, badd_map, ctl_mask, control,
1653 			NULL, NULL, unitid, 0, 0);
1654 }
1655 
1656 static void get_connector_control_name(struct usb_mixer_interface *mixer,
1657 				       struct usb_audio_term *term,
1658 				       bool is_input, char *name, int name_size)
1659 {
1660 	int name_len = get_term_name(mixer->chip, term, name, name_size, 0);
1661 
1662 	if (name_len == 0)
1663 		strlcpy(name, "Unknown", name_size);
1664 
1665 	/*
1666 	 *  sound/core/ctljack.c has a convention of naming jack controls
1667 	 * by ending in " Jack".  Make it slightly more useful by
1668 	 * indicating Input or Output after the terminal name.
1669 	 */
1670 	if (is_input)
1671 		strlcat(name, " - Input Jack", name_size);
1672 	else
1673 		strlcat(name, " - Output Jack", name_size);
1674 }
1675 
1676 /* Build a mixer control for a UAC connector control (jack-detect) */
1677 static void build_connector_control(struct usb_mixer_interface *mixer,
1678 				    struct usb_audio_term *term, bool is_input)
1679 {
1680 	struct snd_kcontrol *kctl;
1681 	struct usb_mixer_elem_info *cval;
1682 
1683 	cval = kzalloc(sizeof(*cval), GFP_KERNEL);
1684 	if (!cval)
1685 		return;
1686 	snd_usb_mixer_elem_init_std(&cval->head, mixer, term->id);
1687 	/*
1688 	 * UAC2: The first byte from reading the UAC2_TE_CONNECTOR control returns the
1689 	 * number of channels connected.
1690 	 *
1691 	 * UAC3: The first byte specifies size of bitmap for the inserted controls. The
1692 	 * following byte(s) specifies which connectors are inserted.
1693 	 *
1694 	 * This boolean ctl will simply report if any channels are connected
1695 	 * or not.
1696 	 */
1697 	if (mixer->protocol == UAC_VERSION_2)
1698 		cval->control = UAC2_TE_CONNECTOR;
1699 	else /* UAC_VERSION_3 */
1700 		cval->control = UAC3_TE_INSERTION;
1701 
1702 	cval->val_type = USB_MIXER_BOOLEAN;
1703 	cval->channels = 1; /* report true if any channel is connected */
1704 	cval->min = 0;
1705 	cval->max = 1;
1706 	kctl = snd_ctl_new1(&usb_connector_ctl_ro, cval);
1707 	if (!kctl) {
1708 		usb_audio_err(mixer->chip, "cannot malloc kcontrol\n");
1709 		kfree(cval);
1710 		return;
1711 	}
1712 	get_connector_control_name(mixer, term, is_input, kctl->id.name,
1713 				   sizeof(kctl->id.name));
1714 	kctl->private_free = snd_usb_mixer_elem_free;
1715 	snd_usb_mixer_add_control(&cval->head, kctl);
1716 }
1717 
1718 static int parse_clock_source_unit(struct mixer_build *state, int unitid,
1719 				   void *_ftr)
1720 {
1721 	struct uac_clock_source_descriptor *hdr = _ftr;
1722 	struct usb_mixer_elem_info *cval;
1723 	struct snd_kcontrol *kctl;
1724 	char name[SNDRV_CTL_ELEM_ID_NAME_MAXLEN];
1725 	int ret;
1726 
1727 	if (state->mixer->protocol != UAC_VERSION_2)
1728 		return -EINVAL;
1729 
1730 	if (hdr->bLength != sizeof(*hdr)) {
1731 		usb_audio_dbg(state->chip,
1732 			      "Bogus clock source descriptor length of %d, ignoring.\n",
1733 			      hdr->bLength);
1734 		return 0;
1735 	}
1736 
1737 	/*
1738 	 * The only property of this unit we are interested in is the
1739 	 * clock source validity. If that isn't readable, just bail out.
1740 	 */
1741 	if (!uac_v2v3_control_is_readable(hdr->bmControls,
1742 				      UAC2_CS_CONTROL_CLOCK_VALID))
1743 		return 0;
1744 
1745 	cval = kzalloc(sizeof(*cval), GFP_KERNEL);
1746 	if (!cval)
1747 		return -ENOMEM;
1748 
1749 	snd_usb_mixer_elem_init_std(&cval->head, state->mixer, hdr->bClockID);
1750 
1751 	cval->min = 0;
1752 	cval->max = 1;
1753 	cval->channels = 1;
1754 	cval->val_type = USB_MIXER_BOOLEAN;
1755 	cval->control = UAC2_CS_CONTROL_CLOCK_VALID;
1756 
1757 	cval->master_readonly = 1;
1758 	/* From UAC2 5.2.5.1.2 "Only the get request is supported." */
1759 	kctl = snd_ctl_new1(&usb_bool_master_control_ctl_ro, cval);
1760 
1761 	if (!kctl) {
1762 		kfree(cval);
1763 		return -ENOMEM;
1764 	}
1765 
1766 	kctl->private_free = snd_usb_mixer_elem_free;
1767 	ret = snd_usb_copy_string_desc(state->chip, hdr->iClockSource,
1768 				       name, sizeof(name));
1769 	if (ret > 0)
1770 		snprintf(kctl->id.name, sizeof(kctl->id.name),
1771 			 "%s Validity", name);
1772 	else
1773 		snprintf(kctl->id.name, sizeof(kctl->id.name),
1774 			 "Clock Source %d Validity", hdr->bClockID);
1775 
1776 	return snd_usb_mixer_add_control(&cval->head, kctl);
1777 }
1778 
1779 /*
1780  * parse a feature unit
1781  *
1782  * most of controls are defined here.
1783  */
1784 static int parse_audio_feature_unit(struct mixer_build *state, int unitid,
1785 				    void *_ftr)
1786 {
1787 	int channels, i, j;
1788 	struct usb_audio_term iterm;
1789 	unsigned int master_bits, first_ch_bits;
1790 	int err, csize;
1791 	struct uac_feature_unit_descriptor *hdr = _ftr;
1792 	__u8 *bmaControls;
1793 
1794 	if (state->mixer->protocol == UAC_VERSION_1) {
1795 		if (hdr->bLength < 7) {
1796 			usb_audio_err(state->chip,
1797 				      "unit %u: invalid UAC_FEATURE_UNIT descriptor\n",
1798 				      unitid);
1799 			return -EINVAL;
1800 		}
1801 		csize = hdr->bControlSize;
1802 		if (!csize) {
1803 			usb_audio_dbg(state->chip,
1804 				      "unit %u: invalid bControlSize == 0\n",
1805 				      unitid);
1806 			return -EINVAL;
1807 		}
1808 		channels = (hdr->bLength - 7) / csize - 1;
1809 		bmaControls = hdr->bmaControls;
1810 		if (hdr->bLength < 7 + csize) {
1811 			usb_audio_err(state->chip,
1812 				      "unit %u: invalid UAC_FEATURE_UNIT descriptor\n",
1813 				      unitid);
1814 			return -EINVAL;
1815 		}
1816 	} else if (state->mixer->protocol == UAC_VERSION_2) {
1817 		struct uac2_feature_unit_descriptor *ftr = _ftr;
1818 		if (hdr->bLength < 6) {
1819 			usb_audio_err(state->chip,
1820 				      "unit %u: invalid UAC_FEATURE_UNIT descriptor\n",
1821 				      unitid);
1822 			return -EINVAL;
1823 		}
1824 		csize = 4;
1825 		channels = (hdr->bLength - 6) / 4 - 1;
1826 		bmaControls = ftr->bmaControls;
1827 		if (hdr->bLength < 6 + csize) {
1828 			usb_audio_err(state->chip,
1829 				      "unit %u: invalid UAC_FEATURE_UNIT descriptor\n",
1830 				      unitid);
1831 			return -EINVAL;
1832 		}
1833 	} else { /* UAC_VERSION_3 */
1834 		struct uac3_feature_unit_descriptor *ftr = _ftr;
1835 
1836 		if (hdr->bLength < 7) {
1837 			usb_audio_err(state->chip,
1838 				      "unit %u: invalid UAC3_FEATURE_UNIT descriptor\n",
1839 				      unitid);
1840 			return -EINVAL;
1841 		}
1842 		csize = 4;
1843 		channels = (ftr->bLength - 7) / 4 - 1;
1844 		bmaControls = ftr->bmaControls;
1845 		if (hdr->bLength < 7 + csize) {
1846 			usb_audio_err(state->chip,
1847 				      "unit %u: invalid UAC3_FEATURE_UNIT descriptor\n",
1848 				      unitid);
1849 			return -EINVAL;
1850 		}
1851 	}
1852 
1853 	/* parse the source unit */
1854 	err = parse_audio_unit(state, hdr->bSourceID);
1855 	if (err < 0)
1856 		return err;
1857 
1858 	/* determine the input source type and name */
1859 	err = check_input_term(state, hdr->bSourceID, &iterm);
1860 	if (err < 0)
1861 		return err;
1862 
1863 	master_bits = snd_usb_combine_bytes(bmaControls, csize);
1864 	/* master configuration quirks */
1865 	switch (state->chip->usb_id) {
1866 	case USB_ID(0x08bb, 0x2702):
1867 		usb_audio_info(state->chip,
1868 			       "usbmixer: master volume quirk for PCM2702 chip\n");
1869 		/* disable non-functional volume control */
1870 		master_bits &= ~UAC_CONTROL_BIT(UAC_FU_VOLUME);
1871 		break;
1872 	case USB_ID(0x1130, 0xf211):
1873 		usb_audio_info(state->chip,
1874 			       "usbmixer: volume control quirk for Tenx TP6911 Audio Headset\n");
1875 		/* disable non-functional volume control */
1876 		channels = 0;
1877 		break;
1878 
1879 	}
1880 	if (channels > 0)
1881 		first_ch_bits = snd_usb_combine_bytes(bmaControls + csize, csize);
1882 	else
1883 		first_ch_bits = 0;
1884 
1885 	if (state->mixer->protocol == UAC_VERSION_1) {
1886 		/* check all control types */
1887 		for (i = 0; i < 10; i++) {
1888 			unsigned int ch_bits = 0;
1889 			int control = audio_feature_info[i].control;
1890 
1891 			for (j = 0; j < channels; j++) {
1892 				unsigned int mask;
1893 
1894 				mask = snd_usb_combine_bytes(bmaControls +
1895 							     csize * (j+1), csize);
1896 				if (mask & (1 << i))
1897 					ch_bits |= (1 << j);
1898 			}
1899 			/* audio class v1 controls are never read-only */
1900 
1901 			/*
1902 			 * The first channel must be set
1903 			 * (for ease of programming).
1904 			 */
1905 			if (ch_bits & 1)
1906 				build_feature_ctl(state, _ftr, ch_bits, control,
1907 						  &iterm, unitid, 0);
1908 			if (master_bits & (1 << i))
1909 				build_feature_ctl(state, _ftr, 0, control,
1910 						  &iterm, unitid, 0);
1911 		}
1912 	} else { /* UAC_VERSION_2/3 */
1913 		for (i = 0; i < ARRAY_SIZE(audio_feature_info); i++) {
1914 			unsigned int ch_bits = 0;
1915 			unsigned int ch_read_only = 0;
1916 			int control = audio_feature_info[i].control;
1917 
1918 			for (j = 0; j < channels; j++) {
1919 				unsigned int mask;
1920 
1921 				mask = snd_usb_combine_bytes(bmaControls +
1922 							     csize * (j+1), csize);
1923 				if (uac_v2v3_control_is_readable(mask, control)) {
1924 					ch_bits |= (1 << j);
1925 					if (!uac_v2v3_control_is_writeable(mask, control))
1926 						ch_read_only |= (1 << j);
1927 				}
1928 			}
1929 
1930 			/*
1931 			 * NOTE: build_feature_ctl() will mark the control
1932 			 * read-only if all channels are marked read-only in
1933 			 * the descriptors. Otherwise, the control will be
1934 			 * reported as writeable, but the driver will not
1935 			 * actually issue a write command for read-only
1936 			 * channels.
1937 			 */
1938 
1939 			/*
1940 			 * The first channel must be set
1941 			 * (for ease of programming).
1942 			 */
1943 			if (ch_bits & 1)
1944 				build_feature_ctl(state, _ftr, ch_bits, control,
1945 						  &iterm, unitid, ch_read_only);
1946 			if (uac_v2v3_control_is_readable(master_bits, control))
1947 				build_feature_ctl(state, _ftr, 0, control,
1948 						  &iterm, unitid,
1949 						  !uac_v2v3_control_is_writeable(master_bits,
1950 										 control));
1951 		}
1952 	}
1953 
1954 	return 0;
1955 }
1956 
1957 /*
1958  * Mixer Unit
1959  */
1960 
1961 /*
1962  * build a mixer unit control
1963  *
1964  * the callbacks are identical with feature unit.
1965  * input channel number (zero based) is given in control field instead.
1966  */
1967 static void build_mixer_unit_ctl(struct mixer_build *state,
1968 				 struct uac_mixer_unit_descriptor *desc,
1969 				 int in_pin, int in_ch, int num_outs,
1970 				 int unitid, struct usb_audio_term *iterm)
1971 {
1972 	struct usb_mixer_elem_info *cval;
1973 	unsigned int i, len;
1974 	struct snd_kcontrol *kctl;
1975 	const struct usbmix_name_map *map;
1976 
1977 	map = find_map(state->map, unitid, 0);
1978 	if (check_ignored_ctl(map))
1979 		return;
1980 
1981 	cval = kzalloc(sizeof(*cval), GFP_KERNEL);
1982 	if (!cval)
1983 		return;
1984 
1985 	snd_usb_mixer_elem_init_std(&cval->head, state->mixer, unitid);
1986 	cval->control = in_ch + 1; /* based on 1 */
1987 	cval->val_type = USB_MIXER_S16;
1988 	for (i = 0; i < num_outs; i++) {
1989 		__u8 *c = uac_mixer_unit_bmControls(desc, state->mixer->protocol);
1990 
1991 		if (check_matrix_bitmap(c, in_ch, i, num_outs)) {
1992 			cval->cmask |= (1 << i);
1993 			cval->channels++;
1994 		}
1995 	}
1996 
1997 	/* get min/max values */
1998 	get_min_max(cval, 0);
1999 
2000 	kctl = snd_ctl_new1(&usb_feature_unit_ctl, cval);
2001 	if (!kctl) {
2002 		usb_audio_err(state->chip, "cannot malloc kcontrol\n");
2003 		kfree(cval);
2004 		return;
2005 	}
2006 	kctl->private_free = snd_usb_mixer_elem_free;
2007 
2008 	len = check_mapped_name(map, kctl->id.name, sizeof(kctl->id.name));
2009 	if (!len)
2010 		len = get_term_name(state->chip, iterm, kctl->id.name,
2011 				    sizeof(kctl->id.name), 0);
2012 	if (!len)
2013 		len = sprintf(kctl->id.name, "Mixer Source %d", in_ch + 1);
2014 	append_ctl_name(kctl, " Volume");
2015 
2016 	usb_audio_dbg(state->chip, "[%d] MU [%s] ch = %d, val = %d/%d\n",
2017 		    cval->head.id, kctl->id.name, cval->channels, cval->min, cval->max);
2018 	snd_usb_mixer_add_control(&cval->head, kctl);
2019 }
2020 
2021 static int parse_audio_input_terminal(struct mixer_build *state, int unitid,
2022 				      void *raw_desc)
2023 {
2024 	struct usb_audio_term iterm;
2025 	unsigned int control, bmctls, term_id;
2026 
2027 	if (state->mixer->protocol == UAC_VERSION_2) {
2028 		struct uac2_input_terminal_descriptor *d_v2 = raw_desc;
2029 		control = UAC2_TE_CONNECTOR;
2030 		term_id = d_v2->bTerminalID;
2031 		bmctls = le16_to_cpu(d_v2->bmControls);
2032 	} else if (state->mixer->protocol == UAC_VERSION_3) {
2033 		struct uac3_input_terminal_descriptor *d_v3 = raw_desc;
2034 		control = UAC3_TE_INSERTION;
2035 		term_id = d_v3->bTerminalID;
2036 		bmctls = le32_to_cpu(d_v3->bmControls);
2037 	} else {
2038 		return 0; /* UAC1. No Insertion control */
2039 	}
2040 
2041 	check_input_term(state, term_id, &iterm);
2042 
2043 	/* Check for jack detection. */
2044 	if (uac_v2v3_control_is_readable(bmctls, control))
2045 		build_connector_control(state->mixer, &iterm, true);
2046 
2047 	return 0;
2048 }
2049 
2050 /*
2051  * parse a mixer unit
2052  */
2053 static int parse_audio_mixer_unit(struct mixer_build *state, int unitid,
2054 				  void *raw_desc)
2055 {
2056 	struct uac_mixer_unit_descriptor *desc = raw_desc;
2057 	struct usb_audio_term iterm;
2058 	int input_pins, num_ins, num_outs;
2059 	int pin, ich, err;
2060 
2061 	err = uac_mixer_unit_get_channels(state, desc);
2062 	if (err < 0) {
2063 		usb_audio_err(state->chip,
2064 			      "invalid MIXER UNIT descriptor %d\n",
2065 			      unitid);
2066 		return err;
2067 	}
2068 
2069 	num_outs = err;
2070 	input_pins = desc->bNrInPins;
2071 
2072 	num_ins = 0;
2073 	ich = 0;
2074 	for (pin = 0; pin < input_pins; pin++) {
2075 		err = parse_audio_unit(state, desc->baSourceID[pin]);
2076 		if (err < 0)
2077 			continue;
2078 		/* no bmControls field (e.g. Maya44) -> ignore */
2079 		if (desc->bLength <= 10 + input_pins)
2080 			continue;
2081 		err = check_input_term(state, desc->baSourceID[pin], &iterm);
2082 		if (err < 0)
2083 			return err;
2084 		num_ins += iterm.channels;
2085 		for (; ich < num_ins; ich++) {
2086 			int och, ich_has_controls = 0;
2087 
2088 			for (och = 0; och < num_outs; och++) {
2089 				__u8 *c = uac_mixer_unit_bmControls(desc,
2090 						state->mixer->protocol);
2091 
2092 				if (check_matrix_bitmap(c, ich, och, num_outs)) {
2093 					ich_has_controls = 1;
2094 					break;
2095 				}
2096 			}
2097 			if (ich_has_controls)
2098 				build_mixer_unit_ctl(state, desc, pin, ich, num_outs,
2099 						     unitid, &iterm);
2100 		}
2101 	}
2102 	return 0;
2103 }
2104 
2105 /*
2106  * Processing Unit / Extension Unit
2107  */
2108 
2109 /* get callback for processing/extension unit */
2110 static int mixer_ctl_procunit_get(struct snd_kcontrol *kcontrol,
2111 				  struct snd_ctl_elem_value *ucontrol)
2112 {
2113 	struct usb_mixer_elem_info *cval = kcontrol->private_data;
2114 	int err, val;
2115 
2116 	err = get_cur_ctl_value(cval, cval->control << 8, &val);
2117 	if (err < 0) {
2118 		ucontrol->value.integer.value[0] = cval->min;
2119 		return filter_error(cval, err);
2120 	}
2121 	val = get_relative_value(cval, val);
2122 	ucontrol->value.integer.value[0] = val;
2123 	return 0;
2124 }
2125 
2126 /* put callback for processing/extension unit */
2127 static int mixer_ctl_procunit_put(struct snd_kcontrol *kcontrol,
2128 				  struct snd_ctl_elem_value *ucontrol)
2129 {
2130 	struct usb_mixer_elem_info *cval = kcontrol->private_data;
2131 	int val, oval, err;
2132 
2133 	err = get_cur_ctl_value(cval, cval->control << 8, &oval);
2134 	if (err < 0)
2135 		return filter_error(cval, err);
2136 	val = ucontrol->value.integer.value[0];
2137 	val = get_abs_value(cval, val);
2138 	if (val != oval) {
2139 		set_cur_ctl_value(cval, cval->control << 8, val);
2140 		return 1;
2141 	}
2142 	return 0;
2143 }
2144 
2145 /* alsa control interface for processing/extension unit */
2146 static const struct snd_kcontrol_new mixer_procunit_ctl = {
2147 	.iface = SNDRV_CTL_ELEM_IFACE_MIXER,
2148 	.name = "", /* will be filled later */
2149 	.info = mixer_ctl_feature_info,
2150 	.get = mixer_ctl_procunit_get,
2151 	.put = mixer_ctl_procunit_put,
2152 };
2153 
2154 /*
2155  * predefined data for processing units
2156  */
2157 struct procunit_value_info {
2158 	int control;
2159 	char *suffix;
2160 	int val_type;
2161 	int min_value;
2162 };
2163 
2164 struct procunit_info {
2165 	int type;
2166 	char *name;
2167 	struct procunit_value_info *values;
2168 };
2169 
2170 static struct procunit_value_info updown_proc_info[] = {
2171 	{ UAC_UD_ENABLE, "Switch", USB_MIXER_BOOLEAN },
2172 	{ UAC_UD_MODE_SELECT, "Mode Select", USB_MIXER_U8, 1 },
2173 	{ 0 }
2174 };
2175 static struct procunit_value_info prologic_proc_info[] = {
2176 	{ UAC_DP_ENABLE, "Switch", USB_MIXER_BOOLEAN },
2177 	{ UAC_DP_MODE_SELECT, "Mode Select", USB_MIXER_U8, 1 },
2178 	{ 0 }
2179 };
2180 static struct procunit_value_info threed_enh_proc_info[] = {
2181 	{ UAC_3D_ENABLE, "Switch", USB_MIXER_BOOLEAN },
2182 	{ UAC_3D_SPACE, "Spaciousness", USB_MIXER_U8 },
2183 	{ 0 }
2184 };
2185 static struct procunit_value_info reverb_proc_info[] = {
2186 	{ UAC_REVERB_ENABLE, "Switch", USB_MIXER_BOOLEAN },
2187 	{ UAC_REVERB_LEVEL, "Level", USB_MIXER_U8 },
2188 	{ UAC_REVERB_TIME, "Time", USB_MIXER_U16 },
2189 	{ UAC_REVERB_FEEDBACK, "Feedback", USB_MIXER_U8 },
2190 	{ 0 }
2191 };
2192 static struct procunit_value_info chorus_proc_info[] = {
2193 	{ UAC_CHORUS_ENABLE, "Switch", USB_MIXER_BOOLEAN },
2194 	{ UAC_CHORUS_LEVEL, "Level", USB_MIXER_U8 },
2195 	{ UAC_CHORUS_RATE, "Rate", USB_MIXER_U16 },
2196 	{ UAC_CHORUS_DEPTH, "Depth", USB_MIXER_U16 },
2197 	{ 0 }
2198 };
2199 static struct procunit_value_info dcr_proc_info[] = {
2200 	{ UAC_DCR_ENABLE, "Switch", USB_MIXER_BOOLEAN },
2201 	{ UAC_DCR_RATE, "Ratio", USB_MIXER_U16 },
2202 	{ UAC_DCR_MAXAMPL, "Max Amp", USB_MIXER_S16 },
2203 	{ UAC_DCR_THRESHOLD, "Threshold", USB_MIXER_S16 },
2204 	{ UAC_DCR_ATTACK_TIME, "Attack Time", USB_MIXER_U16 },
2205 	{ UAC_DCR_RELEASE_TIME, "Release Time", USB_MIXER_U16 },
2206 	{ 0 }
2207 };
2208 
2209 static struct procunit_info procunits[] = {
2210 	{ UAC_PROCESS_UP_DOWNMIX, "Up Down", updown_proc_info },
2211 	{ UAC_PROCESS_DOLBY_PROLOGIC, "Dolby Prologic", prologic_proc_info },
2212 	{ UAC_PROCESS_STEREO_EXTENDER, "3D Stereo Extender", threed_enh_proc_info },
2213 	{ UAC_PROCESS_REVERB, "Reverb", reverb_proc_info },
2214 	{ UAC_PROCESS_CHORUS, "Chorus", chorus_proc_info },
2215 	{ UAC_PROCESS_DYN_RANGE_COMP, "DCR", dcr_proc_info },
2216 	{ 0 },
2217 };
2218 /*
2219  * predefined data for extension units
2220  */
2221 static struct procunit_value_info clock_rate_xu_info[] = {
2222 	{ USB_XU_CLOCK_RATE_SELECTOR, "Selector", USB_MIXER_U8, 0 },
2223 	{ 0 }
2224 };
2225 static struct procunit_value_info clock_source_xu_info[] = {
2226 	{ USB_XU_CLOCK_SOURCE_SELECTOR, "External", USB_MIXER_BOOLEAN },
2227 	{ 0 }
2228 };
2229 static struct procunit_value_info spdif_format_xu_info[] = {
2230 	{ USB_XU_DIGITAL_FORMAT_SELECTOR, "SPDIF/AC3", USB_MIXER_BOOLEAN },
2231 	{ 0 }
2232 };
2233 static struct procunit_value_info soft_limit_xu_info[] = {
2234 	{ USB_XU_SOFT_LIMIT_SELECTOR, " ", USB_MIXER_BOOLEAN },
2235 	{ 0 }
2236 };
2237 static struct procunit_info extunits[] = {
2238 	{ USB_XU_CLOCK_RATE, "Clock rate", clock_rate_xu_info },
2239 	{ USB_XU_CLOCK_SOURCE, "DigitalIn CLK source", clock_source_xu_info },
2240 	{ USB_XU_DIGITAL_IO_STATUS, "DigitalOut format:", spdif_format_xu_info },
2241 	{ USB_XU_DEVICE_OPTIONS, "AnalogueIn Soft Limit", soft_limit_xu_info },
2242 	{ 0 }
2243 };
2244 
2245 /*
2246  * build a processing/extension unit
2247  */
2248 static int build_audio_procunit(struct mixer_build *state, int unitid,
2249 				void *raw_desc, struct procunit_info *list,
2250 				char *name)
2251 {
2252 	struct uac_processing_unit_descriptor *desc = raw_desc;
2253 	int num_ins = desc->bNrInPins;
2254 	struct usb_mixer_elem_info *cval;
2255 	struct snd_kcontrol *kctl;
2256 	int i, err, nameid, type, len;
2257 	struct procunit_info *info;
2258 	struct procunit_value_info *valinfo;
2259 	const struct usbmix_name_map *map;
2260 	static struct procunit_value_info default_value_info[] = {
2261 		{ 0x01, "Switch", USB_MIXER_BOOLEAN },
2262 		{ 0 }
2263 	};
2264 	static struct procunit_info default_info = {
2265 		0, NULL, default_value_info
2266 	};
2267 
2268 	if (desc->bLength < 13 || desc->bLength < 13 + num_ins ||
2269 	    desc->bLength < num_ins + uac_processing_unit_bControlSize(desc, state->mixer->protocol)) {
2270 		usb_audio_err(state->chip, "invalid %s descriptor (id %d)\n", name, unitid);
2271 		return -EINVAL;
2272 	}
2273 
2274 	for (i = 0; i < num_ins; i++) {
2275 		err = parse_audio_unit(state, desc->baSourceID[i]);
2276 		if (err < 0)
2277 			return err;
2278 	}
2279 
2280 	type = le16_to_cpu(desc->wProcessType);
2281 	for (info = list; info && info->type; info++)
2282 		if (info->type == type)
2283 			break;
2284 	if (!info || !info->type)
2285 		info = &default_info;
2286 
2287 	for (valinfo = info->values; valinfo->control; valinfo++) {
2288 		__u8 *controls = uac_processing_unit_bmControls(desc, state->mixer->protocol);
2289 
2290 		if (!(controls[valinfo->control / 8] & (1 << ((valinfo->control % 8) - 1))))
2291 			continue;
2292 		map = find_map(state->map, unitid, valinfo->control);
2293 		if (check_ignored_ctl(map))
2294 			continue;
2295 		cval = kzalloc(sizeof(*cval), GFP_KERNEL);
2296 		if (!cval)
2297 			return -ENOMEM;
2298 		snd_usb_mixer_elem_init_std(&cval->head, state->mixer, unitid);
2299 		cval->control = valinfo->control;
2300 		cval->val_type = valinfo->val_type;
2301 		cval->channels = 1;
2302 
2303 		/* get min/max values */
2304 		if (type == UAC_PROCESS_UP_DOWNMIX && cval->control == UAC_UD_MODE_SELECT) {
2305 			__u8 *control_spec = uac_processing_unit_specific(desc, state->mixer->protocol);
2306 			/* FIXME: hard-coded */
2307 			cval->min = 1;
2308 			cval->max = control_spec[0];
2309 			cval->res = 1;
2310 			cval->initialized = 1;
2311 		} else {
2312 			if (type == USB_XU_CLOCK_RATE) {
2313 				/*
2314 				 * E-Mu USB 0404/0202/TrackerPre/0204
2315 				 * samplerate control quirk
2316 				 */
2317 				cval->min = 0;
2318 				cval->max = 5;
2319 				cval->res = 1;
2320 				cval->initialized = 1;
2321 			} else
2322 				get_min_max(cval, valinfo->min_value);
2323 		}
2324 
2325 		kctl = snd_ctl_new1(&mixer_procunit_ctl, cval);
2326 		if (!kctl) {
2327 			kfree(cval);
2328 			return -ENOMEM;
2329 		}
2330 		kctl->private_free = snd_usb_mixer_elem_free;
2331 
2332 		if (check_mapped_name(map, kctl->id.name, sizeof(kctl->id.name))) {
2333 			/* nothing */ ;
2334 		} else if (info->name) {
2335 			strlcpy(kctl->id.name, info->name, sizeof(kctl->id.name));
2336 		} else {
2337 			nameid = uac_processing_unit_iProcessing(desc, state->mixer->protocol);
2338 			len = 0;
2339 			if (nameid)
2340 				len = snd_usb_copy_string_desc(state->chip,
2341 							       nameid,
2342 							       kctl->id.name,
2343 							       sizeof(kctl->id.name));
2344 			if (!len)
2345 				strlcpy(kctl->id.name, name, sizeof(kctl->id.name));
2346 		}
2347 		append_ctl_name(kctl, " ");
2348 		append_ctl_name(kctl, valinfo->suffix);
2349 
2350 		usb_audio_dbg(state->chip,
2351 			      "[%d] PU [%s] ch = %d, val = %d/%d\n",
2352 			      cval->head.id, kctl->id.name, cval->channels,
2353 			      cval->min, cval->max);
2354 
2355 		err = snd_usb_mixer_add_control(&cval->head, kctl);
2356 		if (err < 0)
2357 			return err;
2358 	}
2359 	return 0;
2360 }
2361 
2362 static int parse_audio_processing_unit(struct mixer_build *state, int unitid,
2363 				       void *raw_desc)
2364 {
2365 	return build_audio_procunit(state, unitid, raw_desc,
2366 				    procunits, "Processing Unit");
2367 }
2368 
2369 static int parse_audio_extension_unit(struct mixer_build *state, int unitid,
2370 				      void *raw_desc)
2371 {
2372 	/*
2373 	 * Note that we parse extension units with processing unit descriptors.
2374 	 * That's ok as the layout is the same.
2375 	 */
2376 	return build_audio_procunit(state, unitid, raw_desc,
2377 				    extunits, "Extension Unit");
2378 }
2379 
2380 /*
2381  * Selector Unit
2382  */
2383 
2384 /*
2385  * info callback for selector unit
2386  * use an enumerator type for routing
2387  */
2388 static int mixer_ctl_selector_info(struct snd_kcontrol *kcontrol,
2389 				   struct snd_ctl_elem_info *uinfo)
2390 {
2391 	struct usb_mixer_elem_info *cval = kcontrol->private_data;
2392 	const char **itemlist = (const char **)kcontrol->private_value;
2393 
2394 	if (snd_BUG_ON(!itemlist))
2395 		return -EINVAL;
2396 	return snd_ctl_enum_info(uinfo, 1, cval->max, itemlist);
2397 }
2398 
2399 /* get callback for selector unit */
2400 static int mixer_ctl_selector_get(struct snd_kcontrol *kcontrol,
2401 				  struct snd_ctl_elem_value *ucontrol)
2402 {
2403 	struct usb_mixer_elem_info *cval = kcontrol->private_data;
2404 	int val, err;
2405 
2406 	err = get_cur_ctl_value(cval, cval->control << 8, &val);
2407 	if (err < 0) {
2408 		ucontrol->value.enumerated.item[0] = 0;
2409 		return filter_error(cval, err);
2410 	}
2411 	val = get_relative_value(cval, val);
2412 	ucontrol->value.enumerated.item[0] = val;
2413 	return 0;
2414 }
2415 
2416 /* put callback for selector unit */
2417 static int mixer_ctl_selector_put(struct snd_kcontrol *kcontrol,
2418 				  struct snd_ctl_elem_value *ucontrol)
2419 {
2420 	struct usb_mixer_elem_info *cval = kcontrol->private_data;
2421 	int val, oval, err;
2422 
2423 	err = get_cur_ctl_value(cval, cval->control << 8, &oval);
2424 	if (err < 0)
2425 		return filter_error(cval, err);
2426 	val = ucontrol->value.enumerated.item[0];
2427 	val = get_abs_value(cval, val);
2428 	if (val != oval) {
2429 		set_cur_ctl_value(cval, cval->control << 8, val);
2430 		return 1;
2431 	}
2432 	return 0;
2433 }
2434 
2435 /* alsa control interface for selector unit */
2436 static const struct snd_kcontrol_new mixer_selectunit_ctl = {
2437 	.iface = SNDRV_CTL_ELEM_IFACE_MIXER,
2438 	.name = "", /* will be filled later */
2439 	.info = mixer_ctl_selector_info,
2440 	.get = mixer_ctl_selector_get,
2441 	.put = mixer_ctl_selector_put,
2442 };
2443 
2444 /*
2445  * private free callback.
2446  * free both private_data and private_value
2447  */
2448 static void usb_mixer_selector_elem_free(struct snd_kcontrol *kctl)
2449 {
2450 	int i, num_ins = 0;
2451 
2452 	if (kctl->private_data) {
2453 		struct usb_mixer_elem_info *cval = kctl->private_data;
2454 		num_ins = cval->max;
2455 		kfree(cval);
2456 		kctl->private_data = NULL;
2457 	}
2458 	if (kctl->private_value) {
2459 		char **itemlist = (char **)kctl->private_value;
2460 		for (i = 0; i < num_ins; i++)
2461 			kfree(itemlist[i]);
2462 		kfree(itemlist);
2463 		kctl->private_value = 0;
2464 	}
2465 }
2466 
2467 /*
2468  * parse a selector unit
2469  */
2470 static int parse_audio_selector_unit(struct mixer_build *state, int unitid,
2471 				     void *raw_desc)
2472 {
2473 	struct uac_selector_unit_descriptor *desc = raw_desc;
2474 	unsigned int i, nameid, len;
2475 	int err;
2476 	struct usb_mixer_elem_info *cval;
2477 	struct snd_kcontrol *kctl;
2478 	const struct usbmix_name_map *map;
2479 	char **namelist;
2480 
2481 	if (desc->bLength < 5 || !desc->bNrInPins ||
2482 	    desc->bLength < 5 + desc->bNrInPins) {
2483 		usb_audio_err(state->chip,
2484 			"invalid SELECTOR UNIT descriptor %d\n", unitid);
2485 		return -EINVAL;
2486 	}
2487 
2488 	for (i = 0; i < desc->bNrInPins; i++) {
2489 		err = parse_audio_unit(state, desc->baSourceID[i]);
2490 		if (err < 0)
2491 			return err;
2492 	}
2493 
2494 	if (desc->bNrInPins == 1) /* only one ? nonsense! */
2495 		return 0;
2496 
2497 	map = find_map(state->map, unitid, 0);
2498 	if (check_ignored_ctl(map))
2499 		return 0;
2500 
2501 	cval = kzalloc(sizeof(*cval), GFP_KERNEL);
2502 	if (!cval)
2503 		return -ENOMEM;
2504 	snd_usb_mixer_elem_init_std(&cval->head, state->mixer, unitid);
2505 	cval->val_type = USB_MIXER_U8;
2506 	cval->channels = 1;
2507 	cval->min = 1;
2508 	cval->max = desc->bNrInPins;
2509 	cval->res = 1;
2510 	cval->initialized = 1;
2511 
2512 	if (state->mixer->protocol == UAC_VERSION_1)
2513 		cval->control = 0;
2514 	else /* UAC_VERSION_2 */
2515 		cval->control = (desc->bDescriptorSubtype == UAC2_CLOCK_SELECTOR) ?
2516 			UAC2_CX_CLOCK_SELECTOR : UAC2_SU_SELECTOR;
2517 
2518 	namelist = kmalloc_array(desc->bNrInPins, sizeof(char *), GFP_KERNEL);
2519 	if (!namelist) {
2520 		kfree(cval);
2521 		return -ENOMEM;
2522 	}
2523 #define MAX_ITEM_NAME_LEN	64
2524 	for (i = 0; i < desc->bNrInPins; i++) {
2525 		struct usb_audio_term iterm;
2526 		len = 0;
2527 		namelist[i] = kmalloc(MAX_ITEM_NAME_LEN, GFP_KERNEL);
2528 		if (!namelist[i]) {
2529 			while (i--)
2530 				kfree(namelist[i]);
2531 			kfree(namelist);
2532 			kfree(cval);
2533 			return -ENOMEM;
2534 		}
2535 		len = check_mapped_selector_name(state, unitid, i, namelist[i],
2536 						 MAX_ITEM_NAME_LEN);
2537 		if (! len && check_input_term(state, desc->baSourceID[i], &iterm) >= 0)
2538 			len = get_term_name(state->chip, &iterm, namelist[i],
2539 					    MAX_ITEM_NAME_LEN, 0);
2540 		if (! len)
2541 			sprintf(namelist[i], "Input %u", i);
2542 	}
2543 
2544 	kctl = snd_ctl_new1(&mixer_selectunit_ctl, cval);
2545 	if (! kctl) {
2546 		usb_audio_err(state->chip, "cannot malloc kcontrol\n");
2547 		kfree(namelist);
2548 		kfree(cval);
2549 		return -ENOMEM;
2550 	}
2551 	kctl->private_value = (unsigned long)namelist;
2552 	kctl->private_free = usb_mixer_selector_elem_free;
2553 
2554 	/* check the static mapping table at first */
2555 	len = check_mapped_name(map, kctl->id.name, sizeof(kctl->id.name));
2556 	if (!len) {
2557 		/* no mapping ? */
2558 		/* if iSelector is given, use it */
2559 		nameid = uac_selector_unit_iSelector(desc);
2560 		if (nameid)
2561 			len = snd_usb_copy_string_desc(state->chip, nameid,
2562 						       kctl->id.name,
2563 						       sizeof(kctl->id.name));
2564 		/* ... or pick up the terminal name at next */
2565 		if (!len)
2566 			len = get_term_name(state->chip, &state->oterm,
2567 				    kctl->id.name, sizeof(kctl->id.name), 0);
2568 		/* ... or use the fixed string "USB" as the last resort */
2569 		if (!len)
2570 			strlcpy(kctl->id.name, "USB", sizeof(kctl->id.name));
2571 
2572 		/* and add the proper suffix */
2573 		if (desc->bDescriptorSubtype == UAC2_CLOCK_SELECTOR)
2574 			append_ctl_name(kctl, " Clock Source");
2575 		else if ((state->oterm.type & 0xff00) == 0x0100)
2576 			append_ctl_name(kctl, " Capture Source");
2577 		else
2578 			append_ctl_name(kctl, " Playback Source");
2579 	}
2580 
2581 	usb_audio_dbg(state->chip, "[%d] SU [%s] items = %d\n",
2582 		    cval->head.id, kctl->id.name, desc->bNrInPins);
2583 	return snd_usb_mixer_add_control(&cval->head, kctl);
2584 }
2585 
2586 /*
2587  * parse an audio unit recursively
2588  */
2589 
2590 static int parse_audio_unit(struct mixer_build *state, int unitid)
2591 {
2592 	unsigned char *p1;
2593 	int protocol = state->mixer->protocol;
2594 
2595 	if (test_and_set_bit(unitid, state->unitbitmap))
2596 		return 0; /* the unit already visited */
2597 
2598 	p1 = find_audio_control_unit(state, unitid);
2599 	if (!p1) {
2600 		usb_audio_err(state->chip, "unit %d not found!\n", unitid);
2601 		return -EINVAL;
2602 	}
2603 
2604 	if (protocol == UAC_VERSION_1 || protocol == UAC_VERSION_2) {
2605 		switch (p1[2]) {
2606 		case UAC_INPUT_TERMINAL:
2607 			return parse_audio_input_terminal(state, unitid, p1);
2608 		case UAC_MIXER_UNIT:
2609 			return parse_audio_mixer_unit(state, unitid, p1);
2610 		case UAC2_CLOCK_SOURCE:
2611 			return parse_clock_source_unit(state, unitid, p1);
2612 		case UAC_SELECTOR_UNIT:
2613 		case UAC2_CLOCK_SELECTOR:
2614 			return parse_audio_selector_unit(state, unitid, p1);
2615 		case UAC_FEATURE_UNIT:
2616 			return parse_audio_feature_unit(state, unitid, p1);
2617 		case UAC1_PROCESSING_UNIT:
2618 		/*   UAC2_EFFECT_UNIT has the same value */
2619 			if (protocol == UAC_VERSION_1)
2620 				return parse_audio_processing_unit(state, unitid, p1);
2621 			else
2622 				return 0; /* FIXME - effect units not implemented yet */
2623 		case UAC1_EXTENSION_UNIT:
2624 		/*   UAC2_PROCESSING_UNIT_V2 has the same value */
2625 			if (protocol == UAC_VERSION_1)
2626 				return parse_audio_extension_unit(state, unitid, p1);
2627 			else /* UAC_VERSION_2 */
2628 				return parse_audio_processing_unit(state, unitid, p1);
2629 		case UAC2_EXTENSION_UNIT_V2:
2630 			return parse_audio_extension_unit(state, unitid, p1);
2631 		default:
2632 			usb_audio_err(state->chip,
2633 				"unit %u: unexpected type 0x%02x\n", unitid, p1[2]);
2634 			return -EINVAL;
2635 		}
2636 	} else { /* UAC_VERSION_3 */
2637 		switch (p1[2]) {
2638 		case UAC_INPUT_TERMINAL:
2639 			return parse_audio_input_terminal(state, unitid, p1);
2640 		case UAC3_MIXER_UNIT:
2641 			return parse_audio_mixer_unit(state, unitid, p1);
2642 		case UAC3_CLOCK_SOURCE:
2643 			return parse_clock_source_unit(state, unitid, p1);
2644 		case UAC3_CLOCK_SELECTOR:
2645 			return parse_audio_selector_unit(state, unitid, p1);
2646 		case UAC3_FEATURE_UNIT:
2647 			return parse_audio_feature_unit(state, unitid, p1);
2648 		case UAC3_EFFECT_UNIT:
2649 			return 0; /* FIXME - effect units not implemented yet */
2650 		case UAC3_PROCESSING_UNIT:
2651 			return parse_audio_processing_unit(state, unitid, p1);
2652 		case UAC3_EXTENSION_UNIT:
2653 			return parse_audio_extension_unit(state, unitid, p1);
2654 		default:
2655 			usb_audio_err(state->chip,
2656 				"unit %u: unexpected type 0x%02x\n", unitid, p1[2]);
2657 			return -EINVAL;
2658 		}
2659 	}
2660 }
2661 
2662 static void snd_usb_mixer_free(struct usb_mixer_interface *mixer)
2663 {
2664 	/* kill pending URBs */
2665 	snd_usb_mixer_disconnect(mixer);
2666 
2667 	kfree(mixer->id_elems);
2668 	if (mixer->urb) {
2669 		kfree(mixer->urb->transfer_buffer);
2670 		usb_free_urb(mixer->urb);
2671 	}
2672 	usb_free_urb(mixer->rc_urb);
2673 	kfree(mixer->rc_setup_packet);
2674 	kfree(mixer);
2675 }
2676 
2677 static int snd_usb_mixer_dev_free(struct snd_device *device)
2678 {
2679 	struct usb_mixer_interface *mixer = device->device_data;
2680 	snd_usb_mixer_free(mixer);
2681 	return 0;
2682 }
2683 
2684 /* UAC3 predefined channels configuration */
2685 struct uac3_badd_profile {
2686 	int subclass;
2687 	const char *name;
2688 	int c_chmask;	/* capture channels mask */
2689 	int p_chmask;	/* playback channels mask */
2690 	int st_chmask;	/* side tone mixing channel mask */
2691 };
2692 
2693 static struct uac3_badd_profile uac3_badd_profiles[] = {
2694 	{
2695 		/*
2696 		 * BAIF, BAOF or combination of both
2697 		 * IN: Mono or Stereo cfg, Mono alt possible
2698 		 * OUT: Mono or Stereo cfg, Mono alt possible
2699 		 */
2700 		.subclass = UAC3_FUNCTION_SUBCLASS_GENERIC_IO,
2701 		.name = "GENERIC IO",
2702 		.c_chmask = -1,		/* dynamic channels */
2703 		.p_chmask = -1,		/* dynamic channels */
2704 	},
2705 	{
2706 		/* BAOF; Stereo only cfg, Mono alt possible */
2707 		.subclass = UAC3_FUNCTION_SUBCLASS_HEADPHONE,
2708 		.name = "HEADPHONE",
2709 		.p_chmask = 3,
2710 	},
2711 	{
2712 		/* BAOF; Mono or Stereo cfg, Mono alt possible */
2713 		.subclass = UAC3_FUNCTION_SUBCLASS_SPEAKER,
2714 		.name = "SPEAKER",
2715 		.p_chmask = -1,		/* dynamic channels */
2716 	},
2717 	{
2718 		/* BAIF; Mono or Stereo cfg, Mono alt possible */
2719 		.subclass = UAC3_FUNCTION_SUBCLASS_MICROPHONE,
2720 		.name = "MICROPHONE",
2721 		.c_chmask = -1,		/* dynamic channels */
2722 	},
2723 	{
2724 		/*
2725 		 * BAIOF topology
2726 		 * IN: Mono only
2727 		 * OUT: Mono or Stereo cfg, Mono alt possible
2728 		 */
2729 		.subclass = UAC3_FUNCTION_SUBCLASS_HEADSET,
2730 		.name = "HEADSET",
2731 		.c_chmask = 1,
2732 		.p_chmask = -1,		/* dynamic channels */
2733 		.st_chmask = 1,
2734 	},
2735 	{
2736 		/* BAIOF; IN: Mono only; OUT: Stereo only, Mono alt possible */
2737 		.subclass = UAC3_FUNCTION_SUBCLASS_HEADSET_ADAPTER,
2738 		.name = "HEADSET ADAPTER",
2739 		.c_chmask = 1,
2740 		.p_chmask = 3,
2741 		.st_chmask = 1,
2742 	},
2743 	{
2744 		/* BAIF + BAOF; IN: Mono only; OUT: Mono only */
2745 		.subclass = UAC3_FUNCTION_SUBCLASS_SPEAKERPHONE,
2746 		.name = "SPEAKERPHONE",
2747 		.c_chmask = 1,
2748 		.p_chmask = 1,
2749 	},
2750 	{ 0 } /* terminator */
2751 };
2752 
2753 static bool uac3_badd_func_has_valid_channels(struct usb_mixer_interface *mixer,
2754 					      struct uac3_badd_profile *f,
2755 					      int c_chmask, int p_chmask)
2756 {
2757 	/*
2758 	 * If both playback/capture channels are dynamic, make sure
2759 	 * at least one channel is present
2760 	 */
2761 	if (f->c_chmask < 0 && f->p_chmask < 0) {
2762 		if (!c_chmask && !p_chmask) {
2763 			usb_audio_warn(mixer->chip, "BAAD %s: no channels?",
2764 				       f->name);
2765 			return false;
2766 		}
2767 		return true;
2768 	}
2769 
2770 	if ((f->c_chmask < 0 && !c_chmask) ||
2771 	    (f->c_chmask >= 0 && f->c_chmask != c_chmask)) {
2772 		usb_audio_warn(mixer->chip, "BAAD %s c_chmask mismatch",
2773 			       f->name);
2774 		return false;
2775 	}
2776 	if ((f->p_chmask < 0 && !p_chmask) ||
2777 	    (f->p_chmask >= 0 && f->p_chmask != p_chmask)) {
2778 		usb_audio_warn(mixer->chip, "BAAD %s p_chmask mismatch",
2779 			       f->name);
2780 		return false;
2781 	}
2782 	return true;
2783 }
2784 
2785 /*
2786  * create mixer controls for UAC3 BADD profiles
2787  *
2788  * UAC3 BADD device doesn't contain CS descriptors thus we will guess everything
2789  *
2790  * BADD device may contain Mixer Unit, which doesn't have any controls, skip it
2791  */
2792 static int snd_usb_mixer_controls_badd(struct usb_mixer_interface *mixer,
2793 				       int ctrlif)
2794 {
2795 	struct usb_device *dev = mixer->chip->dev;
2796 	struct usb_interface_assoc_descriptor *assoc;
2797 	int badd_profile = mixer->chip->badd_profile;
2798 	struct uac3_badd_profile *f;
2799 	const struct usbmix_ctl_map *map;
2800 	int p_chmask = 0, c_chmask = 0, st_chmask = 0;
2801 	int i;
2802 
2803 	assoc = usb_ifnum_to_if(dev, ctrlif)->intf_assoc;
2804 
2805 	/* Detect BADD capture/playback channels from AS EP descriptors */
2806 	for (i = 0; i < assoc->bInterfaceCount; i++) {
2807 		int intf = assoc->bFirstInterface + i;
2808 
2809 		struct usb_interface *iface;
2810 		struct usb_host_interface *alts;
2811 		struct usb_interface_descriptor *altsd;
2812 		unsigned int maxpacksize;
2813 		char dir_in;
2814 		int chmask, num;
2815 
2816 		if (intf == ctrlif)
2817 			continue;
2818 
2819 		iface = usb_ifnum_to_if(dev, intf);
2820 		num = iface->num_altsetting;
2821 
2822 		if (num < 2)
2823 			return -EINVAL;
2824 
2825 		/*
2826 		 * The number of Channels in an AudioStreaming interface
2827 		 * and the audio sample bit resolution (16 bits or 24
2828 		 * bits) can be derived from the wMaxPacketSize field in
2829 		 * the Standard AS Audio Data Endpoint descriptor in
2830 		 * Alternate Setting 1
2831 		 */
2832 		alts = &iface->altsetting[1];
2833 		altsd = get_iface_desc(alts);
2834 
2835 		if (altsd->bNumEndpoints < 1)
2836 			return -EINVAL;
2837 
2838 		/* check direction */
2839 		dir_in = (get_endpoint(alts, 0)->bEndpointAddress & USB_DIR_IN);
2840 		maxpacksize = le16_to_cpu(get_endpoint(alts, 0)->wMaxPacketSize);
2841 
2842 		switch (maxpacksize) {
2843 		default:
2844 			usb_audio_err(mixer->chip,
2845 				"incorrect wMaxPacketSize 0x%x for BADD profile\n",
2846 				maxpacksize);
2847 			return -EINVAL;
2848 		case UAC3_BADD_EP_MAXPSIZE_SYNC_MONO_16:
2849 		case UAC3_BADD_EP_MAXPSIZE_ASYNC_MONO_16:
2850 		case UAC3_BADD_EP_MAXPSIZE_SYNC_MONO_24:
2851 		case UAC3_BADD_EP_MAXPSIZE_ASYNC_MONO_24:
2852 			chmask = 1;
2853 			break;
2854 		case UAC3_BADD_EP_MAXPSIZE_SYNC_STEREO_16:
2855 		case UAC3_BADD_EP_MAXPSIZE_ASYNC_STEREO_16:
2856 		case UAC3_BADD_EP_MAXPSIZE_SYNC_STEREO_24:
2857 		case UAC3_BADD_EP_MAXPSIZE_ASYNC_STEREO_24:
2858 			chmask = 3;
2859 			break;
2860 		}
2861 
2862 		if (dir_in)
2863 			c_chmask = chmask;
2864 		else
2865 			p_chmask = chmask;
2866 	}
2867 
2868 	usb_audio_dbg(mixer->chip,
2869 		"UAC3 BADD profile 0x%x: detected c_chmask=%d p_chmask=%d\n",
2870 		badd_profile, c_chmask, p_chmask);
2871 
2872 	/* check the mapping table */
2873 	for (map = uac3_badd_usbmix_ctl_maps; map->id; map++) {
2874 		if (map->id == badd_profile)
2875 			break;
2876 	}
2877 
2878 	if (!map->id)
2879 		return -EINVAL;
2880 
2881 	for (f = uac3_badd_profiles; f->name; f++) {
2882 		if (badd_profile == f->subclass)
2883 			break;
2884 	}
2885 	if (!f->name)
2886 		return -EINVAL;
2887 	if (!uac3_badd_func_has_valid_channels(mixer, f, c_chmask, p_chmask))
2888 		return -EINVAL;
2889 	st_chmask = f->st_chmask;
2890 
2891 	/* Playback */
2892 	if (p_chmask) {
2893 		/* Master channel, always writable */
2894 		build_feature_ctl_badd(mixer, 0, UAC_FU_MUTE,
2895 				       UAC3_BADD_FU_ID2, map->map);
2896 		/* Mono/Stereo volume channels, always writable */
2897 		build_feature_ctl_badd(mixer, p_chmask, UAC_FU_VOLUME,
2898 				       UAC3_BADD_FU_ID2, map->map);
2899 	}
2900 
2901 	/* Capture */
2902 	if (c_chmask) {
2903 		/* Master channel, always writable */
2904 		build_feature_ctl_badd(mixer, 0, UAC_FU_MUTE,
2905 				       UAC3_BADD_FU_ID5, map->map);
2906 		/* Mono/Stereo volume channels, always writable */
2907 		build_feature_ctl_badd(mixer, c_chmask, UAC_FU_VOLUME,
2908 				       UAC3_BADD_FU_ID5, map->map);
2909 	}
2910 
2911 	/* Side tone-mixing */
2912 	if (st_chmask) {
2913 		/* Master channel, always writable */
2914 		build_feature_ctl_badd(mixer, 0, UAC_FU_MUTE,
2915 				       UAC3_BADD_FU_ID7, map->map);
2916 		/* Mono volume channel, always writable */
2917 		build_feature_ctl_badd(mixer, 1, UAC_FU_VOLUME,
2918 				       UAC3_BADD_FU_ID7, map->map);
2919 	}
2920 
2921 	/* Insertion Control */
2922 	if (f->subclass == UAC3_FUNCTION_SUBCLASS_HEADSET_ADAPTER) {
2923 		struct usb_audio_term iterm, oterm;
2924 
2925 		/* Input Term - Insertion control */
2926 		memset(&iterm, 0, sizeof(iterm));
2927 		iterm.id = UAC3_BADD_IT_ID4;
2928 		iterm.type = UAC_BIDIR_TERMINAL_HEADSET;
2929 		build_connector_control(mixer, &iterm, true);
2930 
2931 		/* Output Term - Insertion control */
2932 		memset(&oterm, 0, sizeof(oterm));
2933 		oterm.id = UAC3_BADD_OT_ID3;
2934 		oterm.type = UAC_BIDIR_TERMINAL_HEADSET;
2935 		build_connector_control(mixer, &oterm, false);
2936 	}
2937 
2938 	return 0;
2939 }
2940 
2941 /*
2942  * create mixer controls
2943  *
2944  * walk through all UAC_OUTPUT_TERMINAL descriptors to search for mixers
2945  */
2946 static int snd_usb_mixer_controls(struct usb_mixer_interface *mixer)
2947 {
2948 	struct mixer_build state;
2949 	int err;
2950 	const struct usbmix_ctl_map *map;
2951 	void *p;
2952 
2953 	memset(&state, 0, sizeof(state));
2954 	state.chip = mixer->chip;
2955 	state.mixer = mixer;
2956 	state.buffer = mixer->hostif->extra;
2957 	state.buflen = mixer->hostif->extralen;
2958 
2959 	/* check the mapping table */
2960 	for (map = usbmix_ctl_maps; map->id; map++) {
2961 		if (map->id == state.chip->usb_id) {
2962 			state.map = map->map;
2963 			state.selector_map = map->selector_map;
2964 			mixer->ignore_ctl_error = map->ignore_ctl_error;
2965 			break;
2966 		}
2967 	}
2968 
2969 	p = NULL;
2970 	while ((p = snd_usb_find_csint_desc(mixer->hostif->extra,
2971 					    mixer->hostif->extralen,
2972 					    p, UAC_OUTPUT_TERMINAL)) != NULL) {
2973 		if (mixer->protocol == UAC_VERSION_1) {
2974 			struct uac1_output_terminal_descriptor *desc = p;
2975 
2976 			if (desc->bLength < sizeof(*desc))
2977 				continue; /* invalid descriptor? */
2978 			/* mark terminal ID as visited */
2979 			set_bit(desc->bTerminalID, state.unitbitmap);
2980 			state.oterm.id = desc->bTerminalID;
2981 			state.oterm.type = le16_to_cpu(desc->wTerminalType);
2982 			state.oterm.name = desc->iTerminal;
2983 			err = parse_audio_unit(&state, desc->bSourceID);
2984 			if (err < 0 && err != -EINVAL)
2985 				return err;
2986 		} else if (mixer->protocol == UAC_VERSION_2) {
2987 			struct uac2_output_terminal_descriptor *desc = p;
2988 
2989 			if (desc->bLength < sizeof(*desc))
2990 				continue; /* invalid descriptor? */
2991 			/* mark terminal ID as visited */
2992 			set_bit(desc->bTerminalID, state.unitbitmap);
2993 			state.oterm.id = desc->bTerminalID;
2994 			state.oterm.type = le16_to_cpu(desc->wTerminalType);
2995 			state.oterm.name = desc->iTerminal;
2996 			err = parse_audio_unit(&state, desc->bSourceID);
2997 			if (err < 0 && err != -EINVAL)
2998 				return err;
2999 
3000 			/*
3001 			 * For UAC2, use the same approach to also add the
3002 			 * clock selectors
3003 			 */
3004 			err = parse_audio_unit(&state, desc->bCSourceID);
3005 			if (err < 0 && err != -EINVAL)
3006 				return err;
3007 
3008 			if (uac_v2v3_control_is_readable(le16_to_cpu(desc->bmControls),
3009 							 UAC2_TE_CONNECTOR)) {
3010 				build_connector_control(state.mixer, &state.oterm,
3011 							false);
3012 			}
3013 		} else {  /* UAC_VERSION_3 */
3014 			struct uac3_output_terminal_descriptor *desc = p;
3015 
3016 			if (desc->bLength < sizeof(*desc))
3017 				continue; /* invalid descriptor? */
3018 			/* mark terminal ID as visited */
3019 			set_bit(desc->bTerminalID, state.unitbitmap);
3020 			state.oterm.id = desc->bTerminalID;
3021 			state.oterm.type = le16_to_cpu(desc->wTerminalType);
3022 			state.oterm.name = le16_to_cpu(desc->wTerminalDescrStr);
3023 			err = parse_audio_unit(&state, desc->bSourceID);
3024 			if (err < 0 && err != -EINVAL)
3025 				return err;
3026 
3027 			/*
3028 			 * For UAC3, use the same approach to also add the
3029 			 * clock selectors
3030 			 */
3031 			err = parse_audio_unit(&state, desc->bCSourceID);
3032 			if (err < 0 && err != -EINVAL)
3033 				return err;
3034 
3035 			if (uac_v2v3_control_is_readable(le32_to_cpu(desc->bmControls),
3036 							 UAC3_TE_INSERTION)) {
3037 				build_connector_control(state.mixer, &state.oterm,
3038 							false);
3039 			}
3040 		}
3041 	}
3042 
3043 	return 0;
3044 }
3045 
3046 void snd_usb_mixer_notify_id(struct usb_mixer_interface *mixer, int unitid)
3047 {
3048 	struct usb_mixer_elem_list *list;
3049 
3050 	for_each_mixer_elem(list, mixer, unitid) {
3051 		struct usb_mixer_elem_info *info =
3052 			mixer_elem_list_to_info(list);
3053 		/* invalidate cache, so the value is read from the device */
3054 		info->cached = 0;
3055 		snd_ctl_notify(mixer->chip->card, SNDRV_CTL_EVENT_MASK_VALUE,
3056 			       &list->kctl->id);
3057 	}
3058 }
3059 
3060 static void snd_usb_mixer_dump_cval(struct snd_info_buffer *buffer,
3061 				    struct usb_mixer_elem_list *list)
3062 {
3063 	struct usb_mixer_elem_info *cval = mixer_elem_list_to_info(list);
3064 	static char *val_types[] = {"BOOLEAN", "INV_BOOLEAN",
3065 				    "S8", "U8", "S16", "U16"};
3066 	snd_iprintf(buffer, "    Info: id=%i, control=%i, cmask=0x%x, "
3067 			    "channels=%i, type=\"%s\"\n", cval->head.id,
3068 			    cval->control, cval->cmask, cval->channels,
3069 			    val_types[cval->val_type]);
3070 	snd_iprintf(buffer, "    Volume: min=%i, max=%i, dBmin=%i, dBmax=%i\n",
3071 			    cval->min, cval->max, cval->dBmin, cval->dBmax);
3072 }
3073 
3074 static void snd_usb_mixer_proc_read(struct snd_info_entry *entry,
3075 				    struct snd_info_buffer *buffer)
3076 {
3077 	struct snd_usb_audio *chip = entry->private_data;
3078 	struct usb_mixer_interface *mixer;
3079 	struct usb_mixer_elem_list *list;
3080 	int unitid;
3081 
3082 	list_for_each_entry(mixer, &chip->mixer_list, list) {
3083 		snd_iprintf(buffer,
3084 			"USB Mixer: usb_id=0x%08x, ctrlif=%i, ctlerr=%i\n",
3085 				chip->usb_id, snd_usb_ctrl_intf(chip),
3086 				mixer->ignore_ctl_error);
3087 		snd_iprintf(buffer, "Card: %s\n", chip->card->longname);
3088 		for (unitid = 0; unitid < MAX_ID_ELEMS; unitid++) {
3089 			for_each_mixer_elem(list, mixer, unitid) {
3090 				snd_iprintf(buffer, "  Unit: %i\n", list->id);
3091 				if (list->kctl)
3092 					snd_iprintf(buffer,
3093 						    "    Control: name=\"%s\", index=%i\n",
3094 						    list->kctl->id.name,
3095 						    list->kctl->id.index);
3096 				if (list->dump)
3097 					list->dump(buffer, list);
3098 			}
3099 		}
3100 	}
3101 }
3102 
3103 static void snd_usb_mixer_interrupt_v2(struct usb_mixer_interface *mixer,
3104 				       int attribute, int value, int index)
3105 {
3106 	struct usb_mixer_elem_list *list;
3107 	__u8 unitid = (index >> 8) & 0xff;
3108 	__u8 control = (value >> 8) & 0xff;
3109 	__u8 channel = value & 0xff;
3110 	unsigned int count = 0;
3111 
3112 	if (channel >= MAX_CHANNELS) {
3113 		usb_audio_dbg(mixer->chip,
3114 			"%s(): bogus channel number %d\n",
3115 			__func__, channel);
3116 		return;
3117 	}
3118 
3119 	for_each_mixer_elem(list, mixer, unitid)
3120 		count++;
3121 
3122 	if (count == 0)
3123 		return;
3124 
3125 	for_each_mixer_elem(list, mixer, unitid) {
3126 		struct usb_mixer_elem_info *info;
3127 
3128 		if (!list->kctl)
3129 			continue;
3130 
3131 		info = mixer_elem_list_to_info(list);
3132 		if (count > 1 && info->control != control)
3133 			continue;
3134 
3135 		switch (attribute) {
3136 		case UAC2_CS_CUR:
3137 			/* invalidate cache, so the value is read from the device */
3138 			if (channel)
3139 				info->cached &= ~(1 << channel);
3140 			else /* master channel */
3141 				info->cached = 0;
3142 
3143 			snd_ctl_notify(mixer->chip->card, SNDRV_CTL_EVENT_MASK_VALUE,
3144 				       &info->head.kctl->id);
3145 			break;
3146 
3147 		case UAC2_CS_RANGE:
3148 			/* TODO */
3149 			break;
3150 
3151 		case UAC2_CS_MEM:
3152 			/* TODO */
3153 			break;
3154 
3155 		default:
3156 			usb_audio_dbg(mixer->chip,
3157 				"unknown attribute %d in interrupt\n",
3158 				attribute);
3159 			break;
3160 		} /* switch */
3161 	}
3162 }
3163 
3164 static void snd_usb_mixer_interrupt(struct urb *urb)
3165 {
3166 	struct usb_mixer_interface *mixer = urb->context;
3167 	int len = urb->actual_length;
3168 	int ustatus = urb->status;
3169 
3170 	if (ustatus != 0)
3171 		goto requeue;
3172 
3173 	if (mixer->protocol == UAC_VERSION_1) {
3174 		struct uac1_status_word *status;
3175 
3176 		for (status = urb->transfer_buffer;
3177 		     len >= sizeof(*status);
3178 		     len -= sizeof(*status), status++) {
3179 			dev_dbg(&urb->dev->dev, "status interrupt: %02x %02x\n",
3180 						status->bStatusType,
3181 						status->bOriginator);
3182 
3183 			/* ignore any notifications not from the control interface */
3184 			if ((status->bStatusType & UAC1_STATUS_TYPE_ORIG_MASK) !=
3185 				UAC1_STATUS_TYPE_ORIG_AUDIO_CONTROL_IF)
3186 				continue;
3187 
3188 			if (status->bStatusType & UAC1_STATUS_TYPE_MEM_CHANGED)
3189 				snd_usb_mixer_rc_memory_change(mixer, status->bOriginator);
3190 			else
3191 				snd_usb_mixer_notify_id(mixer, status->bOriginator);
3192 		}
3193 	} else { /* UAC_VERSION_2 */
3194 		struct uac2_interrupt_data_msg *msg;
3195 
3196 		for (msg = urb->transfer_buffer;
3197 		     len >= sizeof(*msg);
3198 		     len -= sizeof(*msg), msg++) {
3199 			/* drop vendor specific and endpoint requests */
3200 			if ((msg->bInfo & UAC2_INTERRUPT_DATA_MSG_VENDOR) ||
3201 			    (msg->bInfo & UAC2_INTERRUPT_DATA_MSG_EP))
3202 				continue;
3203 
3204 			snd_usb_mixer_interrupt_v2(mixer, msg->bAttribute,
3205 						   le16_to_cpu(msg->wValue),
3206 						   le16_to_cpu(msg->wIndex));
3207 		}
3208 	}
3209 
3210 requeue:
3211 	if (ustatus != -ENOENT &&
3212 	    ustatus != -ECONNRESET &&
3213 	    ustatus != -ESHUTDOWN) {
3214 		urb->dev = mixer->chip->dev;
3215 		usb_submit_urb(urb, GFP_ATOMIC);
3216 	}
3217 }
3218 
3219 /* create the handler for the optional status interrupt endpoint */
3220 static int snd_usb_mixer_status_create(struct usb_mixer_interface *mixer)
3221 {
3222 	struct usb_endpoint_descriptor *ep;
3223 	void *transfer_buffer;
3224 	int buffer_length;
3225 	unsigned int epnum;
3226 
3227 	/* we need one interrupt input endpoint */
3228 	if (get_iface_desc(mixer->hostif)->bNumEndpoints < 1)
3229 		return 0;
3230 	ep = get_endpoint(mixer->hostif, 0);
3231 	if (!usb_endpoint_dir_in(ep) || !usb_endpoint_xfer_int(ep))
3232 		return 0;
3233 
3234 	epnum = usb_endpoint_num(ep);
3235 	buffer_length = le16_to_cpu(ep->wMaxPacketSize);
3236 	transfer_buffer = kmalloc(buffer_length, GFP_KERNEL);
3237 	if (!transfer_buffer)
3238 		return -ENOMEM;
3239 	mixer->urb = usb_alloc_urb(0, GFP_KERNEL);
3240 	if (!mixer->urb) {
3241 		kfree(transfer_buffer);
3242 		return -ENOMEM;
3243 	}
3244 	usb_fill_int_urb(mixer->urb, mixer->chip->dev,
3245 			 usb_rcvintpipe(mixer->chip->dev, epnum),
3246 			 transfer_buffer, buffer_length,
3247 			 snd_usb_mixer_interrupt, mixer, ep->bInterval);
3248 	usb_submit_urb(mixer->urb, GFP_KERNEL);
3249 	return 0;
3250 }
3251 
3252 static int keep_iface_ctl_get(struct snd_kcontrol *kcontrol,
3253 			      struct snd_ctl_elem_value *ucontrol)
3254 {
3255 	struct usb_mixer_interface *mixer = snd_kcontrol_chip(kcontrol);
3256 
3257 	ucontrol->value.integer.value[0] = mixer->chip->keep_iface;
3258 	return 0;
3259 }
3260 
3261 static int keep_iface_ctl_put(struct snd_kcontrol *kcontrol,
3262 			      struct snd_ctl_elem_value *ucontrol)
3263 {
3264 	struct usb_mixer_interface *mixer = snd_kcontrol_chip(kcontrol);
3265 	bool keep_iface = !!ucontrol->value.integer.value[0];
3266 
3267 	if (mixer->chip->keep_iface == keep_iface)
3268 		return 0;
3269 	mixer->chip->keep_iface = keep_iface;
3270 	return 1;
3271 }
3272 
3273 static const struct snd_kcontrol_new keep_iface_ctl = {
3274 	.iface = SNDRV_CTL_ELEM_IFACE_CARD,
3275 	.name = "Keep Interface",
3276 	.info = snd_ctl_boolean_mono_info,
3277 	.get = keep_iface_ctl_get,
3278 	.put = keep_iface_ctl_put,
3279 };
3280 
3281 static int create_keep_iface_ctl(struct usb_mixer_interface *mixer)
3282 {
3283 	struct snd_kcontrol *kctl = snd_ctl_new1(&keep_iface_ctl, mixer);
3284 
3285 	/* need only one control per card */
3286 	if (snd_ctl_find_id(mixer->chip->card, &kctl->id)) {
3287 		snd_ctl_free_one(kctl);
3288 		return 0;
3289 	}
3290 
3291 	return snd_ctl_add(mixer->chip->card, kctl);
3292 }
3293 
3294 int snd_usb_create_mixer(struct snd_usb_audio *chip, int ctrlif,
3295 			 int ignore_error)
3296 {
3297 	static struct snd_device_ops dev_ops = {
3298 		.dev_free = snd_usb_mixer_dev_free
3299 	};
3300 	struct usb_mixer_interface *mixer;
3301 	struct snd_info_entry *entry;
3302 	int err;
3303 
3304 	strcpy(chip->card->mixername, "USB Mixer");
3305 
3306 	mixer = kzalloc(sizeof(*mixer), GFP_KERNEL);
3307 	if (!mixer)
3308 		return -ENOMEM;
3309 	mixer->chip = chip;
3310 	mixer->ignore_ctl_error = ignore_error;
3311 	mixer->id_elems = kcalloc(MAX_ID_ELEMS, sizeof(*mixer->id_elems),
3312 				  GFP_KERNEL);
3313 	if (!mixer->id_elems) {
3314 		kfree(mixer);
3315 		return -ENOMEM;
3316 	}
3317 
3318 	mixer->hostif = &usb_ifnum_to_if(chip->dev, ctrlif)->altsetting[0];
3319 	switch (get_iface_desc(mixer->hostif)->bInterfaceProtocol) {
3320 	case UAC_VERSION_1:
3321 	default:
3322 		mixer->protocol = UAC_VERSION_1;
3323 		break;
3324 	case UAC_VERSION_2:
3325 		mixer->protocol = UAC_VERSION_2;
3326 		break;
3327 	case UAC_VERSION_3:
3328 		mixer->protocol = UAC_VERSION_3;
3329 		break;
3330 	}
3331 
3332 	if (mixer->protocol == UAC_VERSION_3 &&
3333 			chip->badd_profile >= UAC3_FUNCTION_SUBCLASS_GENERIC_IO) {
3334 		err = snd_usb_mixer_controls_badd(mixer, ctrlif);
3335 		if (err < 0)
3336 			goto _error;
3337 	} else {
3338 		err = snd_usb_mixer_controls(mixer);
3339 		if (err < 0)
3340 			goto _error;
3341 	}
3342 
3343 	err = snd_usb_mixer_status_create(mixer);
3344 	if (err < 0)
3345 		goto _error;
3346 
3347 	err = create_keep_iface_ctl(mixer);
3348 	if (err < 0)
3349 		goto _error;
3350 
3351 	snd_usb_mixer_apply_create_quirk(mixer);
3352 
3353 	err = snd_device_new(chip->card, SNDRV_DEV_CODEC, mixer, &dev_ops);
3354 	if (err < 0)
3355 		goto _error;
3356 
3357 	if (list_empty(&chip->mixer_list) &&
3358 	    !snd_card_proc_new(chip->card, "usbmixer", &entry))
3359 		snd_info_set_text_ops(entry, chip, snd_usb_mixer_proc_read);
3360 
3361 	list_add(&mixer->list, &chip->mixer_list);
3362 	return 0;
3363 
3364 _error:
3365 	snd_usb_mixer_free(mixer);
3366 	return err;
3367 }
3368 
3369 void snd_usb_mixer_disconnect(struct usb_mixer_interface *mixer)
3370 {
3371 	if (mixer->disconnected)
3372 		return;
3373 	if (mixer->urb)
3374 		usb_kill_urb(mixer->urb);
3375 	if (mixer->rc_urb)
3376 		usb_kill_urb(mixer->rc_urb);
3377 	mixer->disconnected = true;
3378 }
3379 
3380 #ifdef CONFIG_PM
3381 /* stop any bus activity of a mixer */
3382 static void snd_usb_mixer_inactivate(struct usb_mixer_interface *mixer)
3383 {
3384 	usb_kill_urb(mixer->urb);
3385 	usb_kill_urb(mixer->rc_urb);
3386 }
3387 
3388 static int snd_usb_mixer_activate(struct usb_mixer_interface *mixer)
3389 {
3390 	int err;
3391 
3392 	if (mixer->urb) {
3393 		err = usb_submit_urb(mixer->urb, GFP_NOIO);
3394 		if (err < 0)
3395 			return err;
3396 	}
3397 
3398 	return 0;
3399 }
3400 
3401 int snd_usb_mixer_suspend(struct usb_mixer_interface *mixer)
3402 {
3403 	snd_usb_mixer_inactivate(mixer);
3404 	return 0;
3405 }
3406 
3407 static int restore_mixer_value(struct usb_mixer_elem_list *list)
3408 {
3409 	struct usb_mixer_elem_info *cval = mixer_elem_list_to_info(list);
3410 	int c, err, idx;
3411 
3412 	if (cval->cmask) {
3413 		idx = 0;
3414 		for (c = 0; c < MAX_CHANNELS; c++) {
3415 			if (!(cval->cmask & (1 << c)))
3416 				continue;
3417 			if (cval->cached & (1 << (c + 1))) {
3418 				err = snd_usb_set_cur_mix_value(cval, c + 1, idx,
3419 							cval->cache_val[idx]);
3420 				if (err < 0)
3421 					return err;
3422 			}
3423 			idx++;
3424 		}
3425 	} else {
3426 		/* master */
3427 		if (cval->cached) {
3428 			err = snd_usb_set_cur_mix_value(cval, 0, 0, *cval->cache_val);
3429 			if (err < 0)
3430 				return err;
3431 		}
3432 	}
3433 
3434 	return 0;
3435 }
3436 
3437 int snd_usb_mixer_resume(struct usb_mixer_interface *mixer, bool reset_resume)
3438 {
3439 	struct usb_mixer_elem_list *list;
3440 	int id, err;
3441 
3442 	if (reset_resume) {
3443 		/* restore cached mixer values */
3444 		for (id = 0; id < MAX_ID_ELEMS; id++) {
3445 			for_each_mixer_elem(list, mixer, id) {
3446 				if (list->resume) {
3447 					err = list->resume(list);
3448 					if (err < 0)
3449 						return err;
3450 				}
3451 			}
3452 		}
3453 	}
3454 
3455 	snd_usb_mixer_resume_quirk(mixer);
3456 
3457 	return snd_usb_mixer_activate(mixer);
3458 }
3459 #endif
3460 
3461 void snd_usb_mixer_elem_init_std(struct usb_mixer_elem_list *list,
3462 				 struct usb_mixer_interface *mixer,
3463 				 int unitid)
3464 {
3465 	list->mixer = mixer;
3466 	list->id = unitid;
3467 	list->dump = snd_usb_mixer_dump_cval;
3468 #ifdef CONFIG_PM
3469 	list->resume = restore_mixer_value;
3470 #endif
3471 }
3472