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