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