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