OSDN Git Service

Merge android-4.4-p.203 (40ef73d) into msm-4.4
[sagit-ice-cold/kernel_xiaomi_msm8998.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/slab.h>
49 #include <linux/string.h>
50 #include <linux/usb.h>
51 #include <linux/usb/audio.h>
52 #include <linux/usb/audio-v2.h>
53 #include <linux/usb/audio-v3.h>
54
55 #include <sound/core.h>
56 #include <sound/control.h>
57 #include <sound/hwdep.h>
58 #include <sound/info.h>
59 #include <sound/tlv.h>
60
61 #include "usbaudio.h"
62 #include "mixer.h"
63 #include "helper.h"
64 #include "mixer_quirks.h"
65 #include "power.h"
66
67 #define MAX_ID_ELEMS    256
68
69 struct usb_audio_term {
70         int id;
71         int type;
72         int channels;
73         unsigned int chconfig;
74         int name;
75 };
76
77 struct usbmix_name_map;
78
79 struct mixer_build {
80         struct snd_usb_audio *chip;
81         struct usb_mixer_interface *mixer;
82         unsigned char *buffer;
83         unsigned int buflen;
84         DECLARE_BITMAP(unitbitmap, MAX_ID_ELEMS);
85         DECLARE_BITMAP(termbitmap, MAX_ID_ELEMS);
86         struct usb_audio_term oterm;
87         const struct usbmix_name_map *map;
88         const struct usbmix_selector_map *selector_map;
89 };
90
91 /*E-mu 0202/0404/0204 eXtension Unit(XU) control*/
92 enum {
93         USB_XU_CLOCK_RATE               = 0xe301,
94         USB_XU_CLOCK_SOURCE             = 0xe302,
95         USB_XU_DIGITAL_IO_STATUS        = 0xe303,
96         USB_XU_DEVICE_OPTIONS           = 0xe304,
97         USB_XU_DIRECT_MONITORING        = 0xe305,
98         USB_XU_METERING                 = 0xe306
99 };
100 enum {
101         USB_XU_CLOCK_SOURCE_SELECTOR = 0x02,    /* clock source*/
102         USB_XU_CLOCK_RATE_SELECTOR = 0x03,      /* clock rate */
103         USB_XU_DIGITAL_FORMAT_SELECTOR = 0x01,  /* the spdif format */
104         USB_XU_SOFT_LIMIT_SELECTOR = 0x03       /* soft limiter */
105 };
106
107 /*
108  * manual mapping of mixer names
109  * if the mixer topology is too complicated and the parsed names are
110  * ambiguous, add the entries in usbmixer_maps.c.
111  */
112 #include "mixer_maps.c"
113
114 static const struct usbmix_name_map *
115 find_map(struct mixer_build *state, int unitid, int control)
116 {
117         const struct usbmix_name_map *p = state->map;
118
119         if (!p)
120                 return NULL;
121
122         for (p = state->map; p->id; p++) {
123                 if (p->id == unitid &&
124                     (!control || !p->control || control == p->control))
125                         return p;
126         }
127         return NULL;
128 }
129
130 /* get the mapped name if the unit matches */
131 static int
132 check_mapped_name(const struct usbmix_name_map *p, char *buf, int buflen)
133 {
134         if (!p || !p->name)
135                 return 0;
136
137         buflen--;
138         return strlcpy(buf, p->name, buflen);
139 }
140
141 /* ignore the error value if ignore_ctl_error flag is set */
142 #define filter_error(cval, err) \
143         ((cval)->head.mixer->ignore_ctl_error ? 0 : (err))
144
145 /* check whether the control should be ignored */
146 static inline int
147 check_ignored_ctl(const struct usbmix_name_map *p)
148 {
149         if (!p || p->name || p->dB)
150                 return 0;
151         return 1;
152 }
153
154 /* dB mapping */
155 static inline void check_mapped_dB(const struct usbmix_name_map *p,
156                                    struct usb_mixer_elem_info *cval)
157 {
158         if (p && p->dB) {
159                 cval->dBmin = p->dB->min;
160                 cval->dBmax = p->dB->max;
161                 cval->initialized = 1;
162         }
163 }
164
165 /* get the mapped selector source name */
166 static int check_mapped_selector_name(struct mixer_build *state, int unitid,
167                                       int index, char *buf, int buflen)
168 {
169         const struct usbmix_selector_map *p;
170
171         if (!state->selector_map)
172                 return 0;
173         for (p = state->selector_map; p->id; p++) {
174                 if (p->id == unitid && index < p->count)
175                         return strlcpy(buf, p->names[index], buflen);
176         }
177         return 0;
178 }
179
180 /*
181  * find an audio control unit with the given unit id
182  */
183 static void *find_audio_control_unit(struct mixer_build *state,
184                                      unsigned char unit)
185 {
186         /* we just parse the header */
187         struct uac_feature_unit_descriptor *hdr = NULL;
188
189         if (state->mixer->protocol == UAC_VERSION_3) {
190                 int i;
191
192                 for (i = 0; i < NUM_BADD_DESCS; i++) {
193                         hdr = (void *)badd_desc_list[i];
194                         if (hdr->bUnitID == unit)
195                                 return hdr;
196                 }
197
198                 return NULL;
199         }
200         while ((hdr = snd_usb_find_desc(state->buffer, state->buflen, hdr,
201                                         USB_DT_CS_INTERFACE)) != NULL) {
202                 if (hdr->bLength >= 4 &&
203                     hdr->bDescriptorSubtype >= UAC_INPUT_TERMINAL &&
204                     hdr->bDescriptorSubtype <= UAC2_SAMPLE_RATE_CONVERTER &&
205                     hdr->bUnitID == unit)
206                         return hdr;
207         }
208
209         return NULL;
210 }
211
212 /*
213  * copy a string with the given id
214  */
215 static int snd_usb_copy_string_desc(struct mixer_build *state,
216                                     int index, char *buf, int maxlen)
217 {
218         int len = usb_string(state->chip->dev, index, buf, maxlen - 1);
219
220         if (len < 0)
221                 return 0;
222
223         buf[len] = 0;
224         return len;
225 }
226
227 /*
228  * convert from the byte/word on usb descriptor to the zero-based integer
229  */
230 static int convert_signed_value(struct usb_mixer_elem_info *cval, int val)
231 {
232         switch (cval->val_type) {
233         case USB_MIXER_BOOLEAN:
234                 return !!val;
235         case USB_MIXER_INV_BOOLEAN:
236                 return !val;
237         case USB_MIXER_U8:
238                 val &= 0xff;
239                 break;
240         case USB_MIXER_S8:
241                 val &= 0xff;
242                 if (val >= 0x80)
243                         val -= 0x100;
244                 break;
245         case USB_MIXER_U16:
246                 val &= 0xffff;
247                 break;
248         case USB_MIXER_S16:
249                 val &= 0xffff;
250                 if (val >= 0x8000)
251                         val -= 0x10000;
252                 break;
253         }
254         return val;
255 }
256
257 /*
258  * convert from the zero-based int to the byte/word for usb descriptor
259  */
260 static int convert_bytes_value(struct usb_mixer_elem_info *cval, int val)
261 {
262         switch (cval->val_type) {
263         case USB_MIXER_BOOLEAN:
264                 return !!val;
265         case USB_MIXER_INV_BOOLEAN:
266                 return !val;
267         case USB_MIXER_S8:
268         case USB_MIXER_U8:
269                 return val & 0xff;
270         case USB_MIXER_S16:
271         case USB_MIXER_U16:
272                 return val & 0xffff;
273         }
274         return 0; /* not reached */
275 }
276
277 static int get_relative_value(struct usb_mixer_elem_info *cval, int val)
278 {
279         if (!cval->res)
280                 cval->res = 1;
281         if (val < cval->min)
282                 return 0;
283         else if (val >= cval->max)
284                 return (cval->max - cval->min + cval->res - 1) / cval->res;
285         else
286                 return (val - cval->min) / cval->res;
287 }
288
289 static int get_abs_value(struct usb_mixer_elem_info *cval, int val)
290 {
291         if (val < 0)
292                 return cval->min;
293         if (!cval->res)
294                 cval->res = 1;
295         val *= cval->res;
296         val += cval->min;
297         if (val > cval->max)
298                 return cval->max;
299         return val;
300 }
301
302 static int uac2_ctl_value_size(int val_type)
303 {
304         switch (val_type) {
305         case USB_MIXER_S32:
306         case USB_MIXER_U32:
307                 return 4;
308         case USB_MIXER_S16:
309         case USB_MIXER_U16:
310                 return 2;
311         default:
312                 return 1;
313         }
314         return 0; /* unreachable */
315 }
316
317
318 /*
319  * retrieve a mixer value
320  */
321
322 static int get_ctl_value_v1(struct usb_mixer_elem_info *cval, int request,
323                             int validx, int *value_ret)
324 {
325         struct snd_usb_audio *chip = cval->head.mixer->chip;
326         unsigned char buf[2];
327         int val_len = cval->val_type >= USB_MIXER_S16 ? 2 : 1;
328         int timeout = 10;
329         int idx = 0, err;
330
331         err = snd_usb_lock_shutdown(chip);
332         if (err < 0)
333                 return -EIO;
334
335         while (timeout-- > 0) {
336                 idx = snd_usb_ctrl_intf(chip) | (cval->head.id << 8);
337                 if (snd_usb_ctl_msg(chip->dev, usb_rcvctrlpipe(chip->dev, 0), request,
338                                     USB_RECIP_INTERFACE | USB_TYPE_CLASS | USB_DIR_IN,
339                                     validx, idx, buf, val_len) >= val_len) {
340                         *value_ret = convert_signed_value(cval, snd_usb_combine_bytes(buf, val_len));
341                         err = 0;
342                         goto out;
343                 }
344         }
345         usb_audio_dbg(chip,
346                 "cannot get ctl value: req = %#x, wValue = %#x, wIndex = %#x, type = %d\n",
347                 request, validx, idx, cval->val_type);
348         err = -EINVAL;
349
350  out:
351         snd_usb_unlock_shutdown(chip);
352         return err;
353 }
354
355 static int get_ctl_value_v2(struct usb_mixer_elem_info *cval, int request,
356                             int validx, int *value_ret)
357 {
358         struct snd_usb_audio *chip = cval->head.mixer->chip;
359         /* enough space for one range */
360         unsigned char buf[sizeof(__u16) + 3 * sizeof(__u32)];
361         unsigned char *val;
362         int idx = 0, ret, val_size, size;
363         __u8 bRequest;
364
365         val_size = uac2_ctl_value_size(cval->val_type);
366
367         if (request == UAC_GET_CUR) {
368                 bRequest = UAC2_CS_CUR;
369                 size = val_size;
370         } else {
371                 bRequest = UAC2_CS_RANGE;
372                 size = sizeof(__u16) + 3 * val_size;
373         }
374
375         memset(buf, 0, sizeof(buf));
376
377         ret = snd_usb_lock_shutdown(chip) ? -EIO : 0;
378         if (ret)
379                 goto error;
380
381         idx = snd_usb_ctrl_intf(chip) | (cval->head.id << 8);
382         ret = snd_usb_ctl_msg(chip->dev, usb_rcvctrlpipe(chip->dev, 0), bRequest,
383                               USB_RECIP_INTERFACE | USB_TYPE_CLASS | USB_DIR_IN,
384                               validx, idx, buf, size);
385         snd_usb_unlock_shutdown(chip);
386
387         if (ret < 0) {
388 error:
389                 usb_audio_err(chip,
390                         "cannot get ctl value: req = %#x, wValue = %#x, wIndex = %#x, type = %d\n",
391                         request, validx, idx, cval->val_type);
392                 return ret;
393         }
394
395         /* FIXME: how should we handle multiple triplets here? */
396
397         switch (request) {
398         case UAC_GET_CUR:
399                 val = buf;
400                 break;
401         case UAC_GET_MIN:
402                 val = buf + sizeof(__u16);
403                 break;
404         case UAC_GET_MAX:
405                 val = buf + sizeof(__u16) + val_size;
406                 break;
407         case UAC_GET_RES:
408                 val = buf + sizeof(__u16) + val_size * 2;
409                 break;
410         default:
411                 return -EINVAL;
412         }
413
414         *value_ret = convert_signed_value(cval,
415                                           snd_usb_combine_bytes(val, val_size));
416
417         return 0;
418 }
419
420 static int get_ctl_value(struct usb_mixer_elem_info *cval, int request,
421                          int validx, int *value_ret)
422 {
423         validx += cval->idx_off;
424
425         return (cval->head.mixer->protocol == UAC_VERSION_1) ?
426                 get_ctl_value_v1(cval, request, validx, value_ret) :
427                 get_ctl_value_v2(cval, request, validx, value_ret);
428 }
429
430 static int get_cur_ctl_value(struct usb_mixer_elem_info *cval,
431                              int validx, int *value)
432 {
433         return get_ctl_value(cval, UAC_GET_CUR, validx, value);
434 }
435
436 /* channel = 0: master, 1 = first channel */
437 static inline int get_cur_mix_raw(struct usb_mixer_elem_info *cval,
438                                   int channel, int *value)
439 {
440         return get_ctl_value(cval, UAC_GET_CUR,
441                              (cval->control << 8) | channel,
442                              value);
443 }
444
445 int snd_usb_get_cur_mix_value(struct usb_mixer_elem_info *cval,
446                              int channel, int index, int *value)
447 {
448         int err;
449
450         if (cval->cached & (1 << channel)) {
451                 *value = cval->cache_val[index];
452                 return 0;
453         }
454         err = get_cur_mix_raw(cval, channel, value);
455         if (err < 0) {
456                 if (!cval->head.mixer->ignore_ctl_error)
457                         usb_audio_dbg(cval->head.mixer->chip,
458                                 "cannot get current value for control %d ch %d: err = %d\n",
459                                       cval->control, channel, err);
460                 return err;
461         }
462         cval->cached |= 1 << channel;
463         cval->cache_val[index] = *value;
464         return 0;
465 }
466
467 /*
468  * set a mixer value
469  */
470
471 int snd_usb_mixer_set_ctl_value(struct usb_mixer_elem_info *cval,
472                                 int request, int validx, int value_set)
473 {
474         struct snd_usb_audio *chip = cval->head.mixer->chip;
475         unsigned char buf[4];
476         int idx = 0, val_len, err, timeout = 10;
477
478         validx += cval->idx_off;
479
480         if (cval->head.mixer->protocol == UAC_VERSION_1) {
481                 val_len = cval->val_type >= USB_MIXER_S16 ? 2 : 1;
482         } else { /* UAC_VERSION_2 */
483                 val_len = uac2_ctl_value_size(cval->val_type);
484
485                 /* FIXME */
486                 if (request != UAC_SET_CUR) {
487                         usb_audio_dbg(chip, "RANGE setting not yet supported\n");
488                         return -EINVAL;
489                 }
490
491                 request = UAC2_CS_CUR;
492         }
493
494         value_set = convert_bytes_value(cval, value_set);
495         buf[0] = value_set & 0xff;
496         buf[1] = (value_set >> 8) & 0xff;
497         buf[2] = (value_set >> 16) & 0xff;
498         buf[3] = (value_set >> 24) & 0xff;
499
500         err = snd_usb_lock_shutdown(chip);
501         if (err < 0)
502                 return -EIO;
503
504         while (timeout-- > 0) {
505                 idx = snd_usb_ctrl_intf(chip) | (cval->head.id << 8);
506                 if (snd_usb_ctl_msg(chip->dev,
507                                     usb_sndctrlpipe(chip->dev, 0), request,
508                                     USB_RECIP_INTERFACE | USB_TYPE_CLASS | USB_DIR_OUT,
509                                     validx, idx, buf, val_len) >= 0) {
510                         err = 0;
511                         goto out;
512                 }
513         }
514         usb_audio_dbg(chip, "cannot set ctl value: req = %#x, wValue = %#x, wIndex = %#x, type = %d, data = %#x/%#x\n",
515                       request, validx, idx, cval->val_type, buf[0], buf[1]);
516         err = -EINVAL;
517
518  out:
519         snd_usb_unlock_shutdown(chip);
520         return err;
521 }
522
523 static int set_cur_ctl_value(struct usb_mixer_elem_info *cval,
524                              int validx, int value)
525 {
526         return snd_usb_mixer_set_ctl_value(cval, UAC_SET_CUR, validx, value);
527 }
528
529 int snd_usb_set_cur_mix_value(struct usb_mixer_elem_info *cval, int channel,
530                              int index, int value)
531 {
532         int err;
533         unsigned int read_only = (channel == 0) ?
534                 cval->master_readonly :
535                 cval->ch_readonly & (1 << (channel - 1));
536
537         if (read_only) {
538                 usb_audio_dbg(cval->head.mixer->chip,
539                               "%s(): channel %d of control %d is read_only\n",
540                             __func__, channel, cval->control);
541                 return 0;
542         }
543
544         err = snd_usb_mixer_set_ctl_value(cval,
545                                           UAC_SET_CUR, (cval->control << 8) | channel,
546                                           value);
547         if (err < 0)
548                 return err;
549         cval->cached |= 1 << channel;
550         cval->cache_val[index] = value;
551         return 0;
552 }
553
554 /*
555  * TLV callback for mixer volume controls
556  */
557 int snd_usb_mixer_vol_tlv(struct snd_kcontrol *kcontrol, int op_flag,
558                          unsigned int size, unsigned int __user *_tlv)
559 {
560         struct usb_mixer_elem_info *cval = kcontrol->private_data;
561         DECLARE_TLV_DB_MINMAX(scale, 0, 0);
562
563         if (size < sizeof(scale))
564                 return -ENOMEM;
565         if (cval->min_mute)
566                 scale[0] = SNDRV_CTL_TLVT_DB_MINMAX_MUTE;
567         scale[2] = cval->dBmin;
568         scale[3] = cval->dBmax;
569         if (copy_to_user(_tlv, scale, sizeof(scale)))
570                 return -EFAULT;
571         return 0;
572 }
573
574 /*
575  * parser routines begin here...
576  */
577
578 static int parse_audio_unit(struct mixer_build *state, int unitid);
579
580
581 /*
582  * check if the input/output channel routing is enabled on the given bitmap.
583  * used for mixer unit parser
584  */
585 static int check_matrix_bitmap(unsigned char *bmap,
586                                int ich, int och, int num_outs)
587 {
588         int idx = ich * num_outs + och;
589         return bmap[idx >> 3] & (0x80 >> (idx & 7));
590 }
591
592 /*
593  * add an alsa control element
594  * search and increment the index until an empty slot is found.
595  *
596  * if failed, give up and free the control instance.
597  */
598
599 int snd_usb_mixer_add_control(struct usb_mixer_elem_list *list,
600                               struct snd_kcontrol *kctl)
601 {
602         struct usb_mixer_interface *mixer = list->mixer;
603         int err;
604
605         while (snd_ctl_find_id(mixer->chip->card, &kctl->id))
606                 kctl->id.index++;
607         if ((err = snd_ctl_add(mixer->chip->card, kctl)) < 0) {
608                 usb_audio_dbg(mixer->chip, "cannot add control (err = %d)\n",
609                               err);
610                 return err;
611         }
612         list->kctl = kctl;
613         list->next_id_elem = mixer->id_elems[list->id];
614         mixer->id_elems[list->id] = list;
615         return 0;
616 }
617
618 /*
619  * get a terminal name string
620  */
621
622 static struct iterm_name_combo {
623         int type;
624         char *name;
625 } iterm_names[] = {
626         { 0x0300, "Output" },
627         { 0x0301, "Speaker" },
628         { 0x0302, "Headphone" },
629         { 0x0303, "HMD Audio" },
630         { 0x0304, "Desktop Speaker" },
631         { 0x0305, "Room Speaker" },
632         { 0x0306, "Com Speaker" },
633         { 0x0307, "LFE" },
634         { 0x0600, "External In" },
635         { 0x0601, "Analog In" },
636         { 0x0602, "Digital In" },
637         { 0x0603, "Line" },
638         { 0x0604, "Legacy In" },
639         { 0x0605, "IEC958 In" },
640         { 0x0606, "1394 DA Stream" },
641         { 0x0607, "1394 DV Stream" },
642         { 0x0700, "Embedded" },
643         { 0x0701, "Noise Source" },
644         { 0x0702, "Equalization Noise" },
645         { 0x0703, "CD" },
646         { 0x0704, "DAT" },
647         { 0x0705, "DCC" },
648         { 0x0706, "MiniDisk" },
649         { 0x0707, "Analog Tape" },
650         { 0x0708, "Phonograph" },
651         { 0x0709, "VCR Audio" },
652         { 0x070a, "Video Disk Audio" },
653         { 0x070b, "DVD Audio" },
654         { 0x070c, "TV Tuner Audio" },
655         { 0x070d, "Satellite Rec Audio" },
656         { 0x070e, "Cable Tuner Audio" },
657         { 0x070f, "DSS Audio" },
658         { 0x0710, "Radio Receiver" },
659         { 0x0711, "Radio Transmitter" },
660         { 0x0712, "Multi-Track Recorder" },
661         { 0x0713, "Synthesizer" },
662         { 0 },
663 };
664
665 static int get_term_name(struct mixer_build *state, struct usb_audio_term *iterm,
666                          unsigned char *name, int maxlen, int term_only)
667 {
668         struct iterm_name_combo *names;
669
670         if (iterm->name)
671                 return snd_usb_copy_string_desc(state, iterm->name,
672                                                 name, maxlen);
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 UAC_SELECTOR_UNIT:
680                         strcpy(name, "Selector");
681                         return 8;
682                 case UAC1_PROCESSING_UNIT:
683                         strcpy(name, "Process Unit");
684                         return 12;
685                 case UAC1_EXTENSION_UNIT:
686                         strcpy(name, "Ext Unit");
687                         return 8;
688                 case UAC_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  * parse the source unit recursively until it reaches to a terminal
723  * or a branched unit.
724  */
725 static int __check_input_term(struct mixer_build *state, int id,
726                             struct usb_audio_term *term)
727 {
728         int err;
729         void *p1;
730         unsigned char *hdr;
731
732         memset(term, 0, sizeof(*term));
733         for (;;) {
734                 /* a loop in the terminal chain? */
735                 if (test_and_set_bit(id, state->termbitmap))
736                         return -EINVAL;
737
738                 p1 = find_audio_control_unit(state, id);
739                 if (!p1)
740                         break;
741
742                 hdr = p1;
743                 term->id = id;
744                 switch (hdr[2]) {
745                 case UAC_INPUT_TERMINAL:
746                         if (state->mixer->protocol == UAC_VERSION_1) {
747                                 struct uac_input_terminal_descriptor *d = p1;
748                                 term->type = le16_to_cpu(d->wTerminalType);
749                                 term->channels = d->bNrChannels;
750                                 term->chconfig = le16_to_cpu(d->wChannelConfig);
751                                 term->name = d->iTerminal;
752                         } else if (state->mixer->protocol == UAC_VERSION_2) {
753                                 struct uac2_input_terminal_descriptor *d = p1;
754
755                                 /* call recursively to verify that the
756                                  * referenced clock entity is valid */
757                                 err = __check_input_term(state, d->bCSourceID, term);
758                                 if (err < 0)
759                                         return err;
760
761                                 /* save input term properties after recursion,
762                                  * to ensure they are not overriden by the
763                                  * recursion calls */
764                                 term->id = id;
765                                 term->type = le16_to_cpu(d->wTerminalType);
766                                 term->channels = d->bNrChannels;
767                                 term->chconfig = le32_to_cpu(d->bmChannelConfig);
768                                 term->name = d->iTerminal;
769                         } else { /* UAC_VERSION_3 */
770                                 struct uac3_input_terminal_descriptor *d = p1;
771
772                                 err = __check_input_term(state,
773                                                          d->bCSourceID, term);
774                                 if (err < 0)
775                                         return err;
776
777                                 term->id = id;
778                                 term->type = d->wTerminalType;
779                                 if (d->wClusterDescrID == CLUSTER_ID_MONO) {
780                                         term->channels = NUM_CHANNELS_MONO;
781                                         term->chconfig = BADD_CH_CONFIG_MONO;
782                                 } else {
783                                         term->channels = NUM_CHANNELS_STEREO;
784                                         term->chconfig = BADD_CH_CONFIG_STEREO;
785                                 }
786                                 term->name = d->wTerminalDescrStr;
787                         }
788                         return 0;
789                 case UAC_FEATURE_UNIT: {
790                         /* the header is the same for v1 and v2 */
791                         struct uac_feature_unit_descriptor *d = p1;
792                         id = d->bSourceID;
793                         break; /* continue to parse */
794                 }
795                 case UAC_MIXER_UNIT: {
796                         struct uac_mixer_unit_descriptor *d = p1;
797                         term->type = d->bDescriptorSubtype << 16; /* virtual type */
798                         term->channels = uac_mixer_unit_bNrChannels(d);
799                         term->chconfig = uac_mixer_unit_wChannelConfig(d, state->mixer->protocol);
800                         term->name = uac_mixer_unit_iMixer(d);
801                         return 0;
802                 }
803                 case UAC_SELECTOR_UNIT:
804                 /* UAC3_MIXER_UNIT_V3 */
805                 case UAC2_CLOCK_SELECTOR:
806                 /* UAC3_CLOCK_SOURCE */ {
807                         if (state->mixer->protocol == UAC_VERSION_3
808                                 && hdr[2] == UAC3_CLOCK_SOURCE) {
809                                 struct uac3_clock_source_descriptor *d = p1;
810
811                                 term->type = d->bDescriptorSubtype << 16;
812                                 term->id = id;
813                                 term->name = d->wClockSourceStr;
814                         } else if (state->mixer->protocol == UAC_VERSION_3
815                                         && hdr[2] == UAC3_MIXER_UNIT_V3) {
816                                 struct uac3_mixer_unit_descriptor *d = p1;
817
818                                 term->type = d->bDescriptorSubtype << 16;
819                                 if (d->wClusterDescrID == CLUSTER_ID_MONO) {
820                                         term->channels = NUM_CHANNELS_MONO;
821                                         term->chconfig = BADD_CH_CONFIG_MONO;
822                                 } else {
823                                         term->channels = NUM_CHANNELS_STEREO;
824                                         term->chconfig = BADD_CH_CONFIG_STEREO;
825                                 }
826                                 term->name = d->wMixerDescrStr;
827                         } else {
828                                 struct uac_selector_unit_descriptor *d = p1;
829                                 /* call recursively to retrieve channel info */
830                                 err = __check_input_term(state,
831                                                          d->baSourceID[0], term);
832                                 if (err < 0)
833                                         return err;
834                                 /* virtual type */
835                                 term->type = d->bDescriptorSubtype << 16;
836                                 term->id = id;
837                                 term->name = uac_selector_unit_iSelector(d);
838                         }
839                         return 0;
840                 }
841                 case UAC1_PROCESSING_UNIT:
842                 case UAC1_EXTENSION_UNIT:
843                 /* UAC2_PROCESSING_UNIT_V2 */
844                 /* UAC2_EFFECT_UNIT */
845                 /* UAC3_FEATURE_UNIT_V3 */
846                 case UAC2_EXTENSION_UNIT_V2: {
847                         if (state->mixer->protocol == UAC_VERSION_3) {
848                                 struct uac_feature_unit_descriptor *d = p1;
849
850                                 id = d->bSourceID;
851                         } else {
852                                 struct uac_processing_unit_descriptor *d = p1;
853
854                                 if (state->mixer->protocol == UAC_VERSION_2 &&
855                                         hdr[2] == UAC2_EFFECT_UNIT) {
856                                         /* UAC2/UAC1 unit IDs overlap here in an
857                                          * uncompatible way. Ignore this unit
858                                          * for now.
859                                          */
860                                         return 0;
861                                 }
862
863                                 if (d->bNrInPins) {
864                                         id = d->baSourceID[0];
865                                         break; /* continue to parse */
866                                 }
867                                 /* virtual type */
868                                 term->type = d->bDescriptorSubtype << 16;
869                                 term->channels =
870                                         uac_processing_unit_bNrChannels(d);
871                                 term->chconfig =
872                                         uac_processing_unit_wChannelConfig(
873                                                 d, state->mixer->protocol);
874                                 term->name = uac_processing_unit_iProcessing(
875                                                 d, state->mixer->protocol);
876                                 return 0;
877                         }
878                         break;
879                 }
880                 case UAC2_CLOCK_SOURCE: {
881                         struct uac_clock_source_descriptor *d = p1;
882                         term->type = d->bDescriptorSubtype << 16; /* virtual type */
883                         term->id = id;
884                         term->name = d->iClockSource;
885                         return 0;
886                 }
887                 default:
888                         return -ENODEV;
889                 }
890         }
891         return -ENODEV;
892 }
893
894
895 static int check_input_term(struct mixer_build *state, int id,
896                             struct usb_audio_term *term)
897 {
898         memset(term, 0, sizeof(*term));
899         memset(state->termbitmap, 0, sizeof(state->termbitmap));
900         return __check_input_term(state, id, term);
901 }
902
903 /*
904  * Feature Unit
905  */
906
907 /* feature unit control information */
908 struct usb_feature_control_info {
909         const char *name;
910         int type;       /* data type for uac1 */
911         int type_uac2;  /* data type for uac2 if different from uac1, else -1 */
912 };
913
914 static struct usb_feature_control_info audio_feature_info[] = {
915         { "Mute",                       USB_MIXER_INV_BOOLEAN, -1 },
916         { "Volume",                     USB_MIXER_S16, -1 },
917         { "Tone Control - Bass",        USB_MIXER_S8, -1 },
918         { "Tone Control - Mid",         USB_MIXER_S8, -1 },
919         { "Tone Control - Treble",      USB_MIXER_S8, -1 },
920         { "Graphic Equalizer",          USB_MIXER_S8, -1 }, /* FIXME: not implemeted yet */
921         { "Auto Gain Control",          USB_MIXER_BOOLEAN, -1 },
922         { "Delay Control",              USB_MIXER_U16, USB_MIXER_U32 },
923         { "Bass Boost",                 USB_MIXER_BOOLEAN, -1 },
924         { "Loudness",                   USB_MIXER_BOOLEAN, -1 },
925         /* UAC2 specific */
926         { "Input Gain Control",         USB_MIXER_S16, -1 },
927         { "Input Gain Pad Control",     USB_MIXER_S16, -1 },
928         { "Phase Inverter Control",     USB_MIXER_BOOLEAN, -1 },
929 };
930
931 /* private_free callback */
932 void snd_usb_mixer_elem_free(struct snd_kcontrol *kctl)
933 {
934         kfree(kctl->private_data);
935         kctl->private_data = NULL;
936 }
937
938 /*
939  * interface to ALSA control for feature/mixer units
940  */
941
942 /* volume control quirks */
943 static void volume_control_quirks(struct usb_mixer_elem_info *cval,
944                                   struct snd_kcontrol *kctl)
945 {
946         struct snd_usb_audio *chip = cval->head.mixer->chip;
947         switch (chip->usb_id) {
948         case USB_ID(0x0763, 0x2030): /* M-Audio Fast Track C400 */
949         case USB_ID(0x0763, 0x2031): /* M-Audio Fast Track C600 */
950                 if (strcmp(kctl->id.name, "Effect Duration") == 0) {
951                         cval->min = 0x0000;
952                         cval->max = 0xffff;
953                         cval->res = 0x00e6;
954                         break;
955                 }
956                 if (strcmp(kctl->id.name, "Effect Volume") == 0 ||
957                     strcmp(kctl->id.name, "Effect Feedback Volume") == 0) {
958                         cval->min = 0x00;
959                         cval->max = 0xff;
960                         break;
961                 }
962                 if (strstr(kctl->id.name, "Effect Return") != NULL) {
963                         cval->min = 0xb706;
964                         cval->max = 0xff7b;
965                         cval->res = 0x0073;
966                         break;
967                 }
968                 if ((strstr(kctl->id.name, "Playback Volume") != NULL) ||
969                         (strstr(kctl->id.name, "Effect Send") != NULL)) {
970                         cval->min = 0xb5fb; /* -73 dB = 0xb6ff */
971                         cval->max = 0xfcfe;
972                         cval->res = 0x0073;
973                 }
974                 break;
975
976         case USB_ID(0x0763, 0x2081): /* M-Audio Fast Track Ultra 8R */
977         case USB_ID(0x0763, 0x2080): /* M-Audio Fast Track Ultra */
978                 if (strcmp(kctl->id.name, "Effect Duration") == 0) {
979                         usb_audio_info(chip,
980                                        "set quirk for FTU Effect Duration\n");
981                         cval->min = 0x0000;
982                         cval->max = 0x7f00;
983                         cval->res = 0x0100;
984                         break;
985                 }
986                 if (strcmp(kctl->id.name, "Effect Volume") == 0 ||
987                     strcmp(kctl->id.name, "Effect Feedback Volume") == 0) {
988                         usb_audio_info(chip,
989                                        "set quirks for FTU Effect Feedback/Volume\n");
990                         cval->min = 0x00;
991                         cval->max = 0x7f;
992                         break;
993                 }
994                 break;
995
996         case USB_ID(0x0d8c, 0x0103):
997                 if (!strcmp(kctl->id.name, "PCM Playback Volume")) {
998                         usb_audio_info(chip,
999                                  "set volume quirk for CM102-A+/102S+\n");
1000                         cval->min = -256;
1001                 }
1002                 break;
1003
1004         case USB_ID(0x0471, 0x0101):
1005         case USB_ID(0x0471, 0x0104):
1006         case USB_ID(0x0471, 0x0105):
1007         case USB_ID(0x0672, 0x1041):
1008         /* quirk for UDA1321/N101.
1009          * note that detection between firmware 2.1.1.7 (N101)
1010          * and later 2.1.1.21 is not very clear from datasheets.
1011          * I hope that the min value is -15360 for newer firmware --jk
1012          */
1013                 if (!strcmp(kctl->id.name, "PCM Playback Volume") &&
1014                     cval->min == -15616) {
1015                         usb_audio_info(chip,
1016                                  "set volume quirk for UDA1321/N101 chip\n");
1017                         cval->max = -256;
1018                 }
1019                 break;
1020
1021         case USB_ID(0x046d, 0x09a4):
1022                 if (!strcmp(kctl->id.name, "Mic Capture Volume")) {
1023                         usb_audio_info(chip,
1024                                 "set volume quirk for QuickCam E3500\n");
1025                         cval->min = 6080;
1026                         cval->max = 8768;
1027                         cval->res = 192;
1028                 }
1029                 break;
1030
1031         case USB_ID(0x046d, 0x0807): /* Logitech Webcam C500 */
1032         case USB_ID(0x046d, 0x0808):
1033         case USB_ID(0x046d, 0x0809):
1034         case USB_ID(0x046d, 0x0819): /* Logitech Webcam C210 */
1035         case USB_ID(0x046d, 0x081b): /* HD Webcam c310 */
1036         case USB_ID(0x046d, 0x081d): /* HD Webcam c510 */
1037         case USB_ID(0x046d, 0x0825): /* HD Webcam c270 */
1038         case USB_ID(0x046d, 0x0826): /* HD Webcam c525 */
1039         case USB_ID(0x046d, 0x08ca): /* Logitech Quickcam Fusion */
1040         case USB_ID(0x046d, 0x0991):
1041         case USB_ID(0x046d, 0x09a2): /* QuickCam Communicate Deluxe/S7500 */
1042         /* Most audio usb devices lie about volume resolution.
1043          * Most Logitech webcams have res = 384.
1044          * Probably there is some logitech magic behind this number --fishor
1045          */
1046                 if (!strcmp(kctl->id.name, "Mic Capture Volume")) {
1047                         usb_audio_info(chip,
1048                                 "set resolution quirk: cval->res = 384\n");
1049                         cval->res = 384;
1050                 }
1051                 break;
1052
1053         case USB_ID(0x1130, 0x1620): /* Logitech Speakers S150 */
1054         /* This audio device has 2 channels and it explicitly requires the
1055          * host to send SET_CUR command on the volume control of both the
1056          * channels. 7936 = 0x1F00 is the default value.
1057          */
1058                 if (cval->channels == 2)
1059                         snd_usb_mixer_set_ctl_value(cval, UAC_SET_CUR,
1060                                                 (cval->control << 8) | 2, 7936);
1061                 break;
1062
1063         }
1064 }
1065
1066 /*
1067  * retrieve the minimum and maximum values for the specified control
1068  */
1069 static int get_min_max_with_quirks(struct usb_mixer_elem_info *cval,
1070                                    int default_min, struct snd_kcontrol *kctl)
1071 {
1072         /* for failsafe */
1073         cval->min = default_min;
1074         cval->max = cval->min + 1;
1075         cval->res = 1;
1076         cval->dBmin = cval->dBmax = 0;
1077
1078         if (cval->val_type == USB_MIXER_BOOLEAN ||
1079             cval->val_type == USB_MIXER_INV_BOOLEAN) {
1080                 cval->initialized = 1;
1081         } else {
1082                 int minchn = 0;
1083                 if (cval->cmask) {
1084                         int i;
1085                         for (i = 0; i < MAX_CHANNELS; i++)
1086                                 if (cval->cmask & (1 << i)) {
1087                                         minchn = i + 1;
1088                                         break;
1089                                 }
1090                 }
1091                 if (get_ctl_value(cval, UAC_GET_MAX, (cval->control << 8) | minchn, &cval->max) < 0 ||
1092                     get_ctl_value(cval, UAC_GET_MIN, (cval->control << 8) | minchn, &cval->min) < 0) {
1093                         usb_audio_err(cval->head.mixer->chip,
1094                                       "%d:%d: cannot get min/max values for control %d (id %d)\n",
1095                                    cval->head.id, snd_usb_ctrl_intf(cval->head.mixer->chip),
1096                                                                cval->control, cval->head.id);
1097                         return -EINVAL;
1098                 }
1099                 if (get_ctl_value(cval, UAC_GET_RES,
1100                                   (cval->control << 8) | minchn,
1101                                   &cval->res) < 0) {
1102                         cval->res = 1;
1103                 } else {
1104                         int last_valid_res = cval->res;
1105
1106                         while (cval->res > 1) {
1107                                 if (snd_usb_mixer_set_ctl_value(cval, UAC_SET_RES,
1108                                                                 (cval->control << 8) | minchn,
1109                                                                 cval->res / 2) < 0)
1110                                         break;
1111                                 cval->res /= 2;
1112                         }
1113                         if (get_ctl_value(cval, UAC_GET_RES,
1114                                           (cval->control << 8) | minchn, &cval->res) < 0)
1115                                 cval->res = last_valid_res;
1116                 }
1117                 if (cval->res == 0)
1118                         cval->res = 1;
1119
1120                 /* Additional checks for the proper resolution
1121                  *
1122                  * Some devices report smaller resolutions than actually
1123                  * reacting.  They don't return errors but simply clip
1124                  * to the lower aligned value.
1125                  */
1126                 if (cval->min + cval->res < cval->max) {
1127                         int last_valid_res = cval->res;
1128                         int saved, test, check;
1129                         if (get_cur_mix_raw(cval, minchn, &saved) < 0)
1130                                 goto no_res_check;
1131                         for (;;) {
1132                                 test = saved;
1133                                 if (test < cval->max)
1134                                         test += cval->res;
1135                                 else
1136                                         test -= cval->res;
1137                                 if (test < cval->min || test > cval->max ||
1138                                     snd_usb_set_cur_mix_value(cval, minchn, 0, test) ||
1139                                     get_cur_mix_raw(cval, minchn, &check)) {
1140                                         cval->res = last_valid_res;
1141                                         break;
1142                                 }
1143                                 if (test == check)
1144                                         break;
1145                                 cval->res *= 2;
1146                         }
1147                         snd_usb_set_cur_mix_value(cval, minchn, 0, saved);
1148                 }
1149
1150 no_res_check:
1151                 cval->initialized = 1;
1152         }
1153
1154         if (kctl)
1155                 volume_control_quirks(cval, kctl);
1156
1157         /* USB descriptions contain the dB scale in 1/256 dB unit
1158          * while ALSA TLV contains in 1/100 dB unit
1159          */
1160         cval->dBmin =
1161                 (convert_signed_value(cval, cval->min) * 100) / (cval->res);
1162         cval->dBmax =
1163                 (convert_signed_value(cval, cval->max) * 100) / (cval->res);
1164         if (cval->dBmin > cval->dBmax) {
1165                 /* something is wrong; assume it's either from/to 0dB */
1166                 if (cval->dBmin < 0)
1167                         cval->dBmax = 0;
1168                 else if (cval->dBmin > 0)
1169                         cval->dBmin = 0;
1170                 if (cval->dBmin > cval->dBmax) {
1171                         /* totally crap, return an error */
1172                         return -EINVAL;
1173                 }
1174         }
1175
1176         return 0;
1177 }
1178
1179 #define get_min_max(cval, def)  get_min_max_with_quirks(cval, def, NULL)
1180
1181 /* get a feature/mixer unit info */
1182 static int mixer_ctl_feature_info(struct snd_kcontrol *kcontrol,
1183                                   struct snd_ctl_elem_info *uinfo)
1184 {
1185         struct usb_mixer_elem_info *cval = kcontrol->private_data;
1186
1187         if (cval->val_type == USB_MIXER_BOOLEAN ||
1188             cval->val_type == USB_MIXER_INV_BOOLEAN)
1189                 uinfo->type = SNDRV_CTL_ELEM_TYPE_BOOLEAN;
1190         else
1191                 uinfo->type = SNDRV_CTL_ELEM_TYPE_INTEGER;
1192         uinfo->count = cval->channels;
1193         if (cval->val_type == USB_MIXER_BOOLEAN ||
1194             cval->val_type == USB_MIXER_INV_BOOLEAN) {
1195                 uinfo->value.integer.min = 0;
1196                 uinfo->value.integer.max = 1;
1197         } else {
1198                 if (!cval->initialized) {
1199                         get_min_max_with_quirks(cval, 0, kcontrol);
1200                         if (cval->initialized && cval->dBmin >= cval->dBmax) {
1201                                 kcontrol->vd[0].access &= 
1202                                         ~(SNDRV_CTL_ELEM_ACCESS_TLV_READ |
1203                                           SNDRV_CTL_ELEM_ACCESS_TLV_CALLBACK);
1204                                 snd_ctl_notify(cval->head.mixer->chip->card,
1205                                                SNDRV_CTL_EVENT_MASK_INFO,
1206                                                &kcontrol->id);
1207                         }
1208                 }
1209                 uinfo->value.integer.min = 0;
1210                 uinfo->value.integer.max =
1211                         (cval->max - cval->min + cval->res - 1) / cval->res;
1212         }
1213         return 0;
1214 }
1215
1216 /* get the current value from feature/mixer unit */
1217 static int mixer_ctl_feature_get(struct snd_kcontrol *kcontrol,
1218                                  struct snd_ctl_elem_value *ucontrol)
1219 {
1220         struct usb_mixer_elem_info *cval = kcontrol->private_data;
1221         int c, cnt, val, err;
1222
1223         ucontrol->value.integer.value[0] = cval->min;
1224         if (cval->cmask) {
1225                 cnt = 0;
1226                 for (c = 0; c < MAX_CHANNELS; c++) {
1227                         if (!(cval->cmask & (1 << c)))
1228                                 continue;
1229                         err = snd_usb_get_cur_mix_value(cval, c + 1, cnt, &val);
1230                         if (err < 0)
1231                                 return filter_error(cval, err);
1232                         val = get_relative_value(cval, val);
1233                         ucontrol->value.integer.value[cnt] = val;
1234                         cnt++;
1235                 }
1236                 return 0;
1237         } else {
1238                 /* master channel */
1239                 err = snd_usb_get_cur_mix_value(cval, 0, 0, &val);
1240                 if (err < 0)
1241                         return filter_error(cval, err);
1242                 val = get_relative_value(cval, val);
1243                 ucontrol->value.integer.value[0] = val;
1244         }
1245         return 0;
1246 }
1247
1248 /* put the current value to feature/mixer unit */
1249 static int mixer_ctl_feature_put(struct snd_kcontrol *kcontrol,
1250                                  struct snd_ctl_elem_value *ucontrol)
1251 {
1252         struct usb_mixer_elem_info *cval = kcontrol->private_data;
1253         int c, cnt, val, oval, err;
1254         int changed = 0;
1255
1256         if (cval->cmask) {
1257                 cnt = 0;
1258                 for (c = 0; c < MAX_CHANNELS; c++) {
1259                         if (!(cval->cmask & (1 << c)))
1260                                 continue;
1261                         err = snd_usb_get_cur_mix_value(cval, c + 1, cnt, &oval);
1262                         if (err < 0)
1263                                 return filter_error(cval, err);
1264                         val = ucontrol->value.integer.value[cnt];
1265                         val = get_abs_value(cval, val);
1266                         if (oval != val) {
1267                                 snd_usb_set_cur_mix_value(cval, c + 1, cnt, val);
1268                                 changed = 1;
1269                         }
1270                         cnt++;
1271                 }
1272         } else {
1273                 /* master channel */
1274                 err = snd_usb_get_cur_mix_value(cval, 0, 0, &oval);
1275                 if (err < 0)
1276                         return filter_error(cval, err);
1277                 val = ucontrol->value.integer.value[0];
1278                 val = get_abs_value(cval, val);
1279                 if (val != oval) {
1280                         snd_usb_set_cur_mix_value(cval, 0, 0, val);
1281                         changed = 1;
1282                 }
1283         }
1284         return changed;
1285 }
1286
1287 static struct snd_kcontrol_new usb_feature_unit_ctl = {
1288         .iface = SNDRV_CTL_ELEM_IFACE_MIXER,
1289         .name = "", /* will be filled later manually */
1290         .info = mixer_ctl_feature_info,
1291         .get = mixer_ctl_feature_get,
1292         .put = mixer_ctl_feature_put,
1293 };
1294
1295 /* the read-only variant */
1296 static struct snd_kcontrol_new usb_feature_unit_ctl_ro = {
1297         .iface = SNDRV_CTL_ELEM_IFACE_MIXER,
1298         .name = "", /* will be filled later manually */
1299         .info = mixer_ctl_feature_info,
1300         .get = mixer_ctl_feature_get,
1301         .put = NULL,
1302 };
1303
1304 /*
1305  * This symbol is exported in order to allow the mixer quirks to
1306  * hook up to the standard feature unit control mechanism
1307  */
1308 struct snd_kcontrol_new *snd_usb_feature_unit_ctl = &usb_feature_unit_ctl;
1309
1310 /*
1311  * build a feature control
1312  */
1313 static size_t append_ctl_name(struct snd_kcontrol *kctl, const char *str)
1314 {
1315         return strlcat(kctl->id.name, str, sizeof(kctl->id.name));
1316 }
1317
1318 /*
1319  * A lot of headsets/headphones have a "Speaker" mixer. Make sure we
1320  * rename it to "Headphone". We determine if something is a headphone
1321  * similar to how udev determines form factor.
1322  */
1323 static void check_no_speaker_on_headset(struct snd_kcontrol *kctl,
1324                                         struct snd_card *card)
1325 {
1326         const char *names_to_check[] = {
1327                 "Headset", "headset", "Headphone", "headphone", NULL};
1328         const char **s;
1329         bool found = false;
1330
1331         if (strcmp("Speaker", kctl->id.name))
1332                 return;
1333
1334         for (s = names_to_check; *s; s++)
1335                 if (strstr(card->shortname, *s)) {
1336                         found = true;
1337                         break;
1338                 }
1339
1340         if (!found)
1341                 return;
1342
1343         strlcpy(kctl->id.name, "Headphone", sizeof(kctl->id.name));
1344 }
1345
1346 static void build_feature_ctl(struct mixer_build *state, void *raw_desc,
1347                               unsigned int ctl_mask, int control,
1348                               struct usb_audio_term *iterm, int unitid,
1349                               int readonly_mask)
1350 {
1351         struct uac_feature_unit_descriptor *desc = raw_desc;
1352         struct usb_feature_control_info *ctl_info;
1353         unsigned int len = 0;
1354         int mapped_name = 0;
1355         int nameid;
1356         struct snd_kcontrol *kctl;
1357         struct usb_mixer_elem_info *cval;
1358         const struct usbmix_name_map *map;
1359         unsigned int range;
1360
1361         if (state->mixer->protocol == UAC_VERSION_3)
1362                 nameid = ((struct uac3_feature_unit_descriptor *)
1363                                 raw_desc)->wFeatureDescrStr;
1364         else
1365                 nameid = uac_feature_unit_iFeature(desc);
1366
1367         control++; /* change from zero-based to 1-based value */
1368
1369         if (control == UAC_FU_GRAPHIC_EQUALIZER) {
1370                 /* FIXME: not supported yet */
1371                 return;
1372         }
1373
1374         map = find_map(state, unitid, control);
1375         if (check_ignored_ctl(map))
1376                 return;
1377
1378         cval = kzalloc(sizeof(*cval), GFP_KERNEL);
1379         if (!cval)
1380                 return;
1381         snd_usb_mixer_elem_init_std(&cval->head, state->mixer, unitid);
1382         cval->control = control;
1383         cval->cmask = ctl_mask;
1384         ctl_info = &audio_feature_info[control-1];
1385         if (state->mixer->protocol == UAC_VERSION_1)
1386                 cval->val_type = ctl_info->type;
1387         else /* UAC_VERSION_2 or UAC_VERSION_3*/
1388                 cval->val_type = ctl_info->type_uac2 >= 0 ?
1389                         ctl_info->type_uac2 : ctl_info->type;
1390
1391         if (ctl_mask == 0) {
1392                 cval->channels = 1;     /* master channel */
1393                 cval->master_readonly = readonly_mask;
1394         } else {
1395                 int i, c = 0;
1396                 for (i = 0; i < 16; i++)
1397                         if (ctl_mask & (1 << i))
1398                                 c++;
1399                 cval->channels = c;
1400                 cval->ch_readonly = readonly_mask;
1401         }
1402
1403         /*
1404          * If all channels in the mask are marked read-only, make the control
1405          * read-only. snd_usb_set_cur_mix_value() will check the mask again and won't
1406          * issue write commands to read-only channels.
1407          */
1408         if (cval->channels == readonly_mask)
1409                 kctl = snd_ctl_new1(&usb_feature_unit_ctl_ro, cval);
1410         else
1411                 kctl = snd_ctl_new1(&usb_feature_unit_ctl, cval);
1412
1413         if (!kctl) {
1414                 usb_audio_err(state->chip, "cannot malloc kcontrol\n");
1415                 kfree(cval);
1416                 return;
1417         }
1418         kctl->private_free = snd_usb_mixer_elem_free;
1419
1420         len = check_mapped_name(map, kctl->id.name, sizeof(kctl->id.name));
1421         mapped_name = len != 0;
1422         if (!len && nameid)
1423                 len = snd_usb_copy_string_desc(state, nameid,
1424                                 kctl->id.name, sizeof(kctl->id.name));
1425
1426         switch (control) {
1427         case UAC_FU_MUTE:
1428         case UAC_FU_VOLUME:
1429                 /*
1430                  * determine the control name.  the rule is:
1431                  * - if a name id is given in descriptor, use it.
1432                  * - if the connected input can be determined, then use the name
1433                  *   of terminal type.
1434                  * - if the connected output can be determined, use it.
1435                  * - otherwise, anonymous name.
1436                  */
1437                 if (!len) {
1438                         len = get_term_name(state, iterm, kctl->id.name,
1439                                             sizeof(kctl->id.name), 1);
1440                         if (!len)
1441                                 len = get_term_name(state, &state->oterm,
1442                                                     kctl->id.name,
1443                                                     sizeof(kctl->id.name), 1);
1444                         if (!len)
1445                                 snprintf(kctl->id.name, sizeof(kctl->id.name),
1446                                          "Feature %d", unitid);
1447                 }
1448
1449                 if (!mapped_name)
1450                         check_no_speaker_on_headset(kctl, state->mixer->chip->card);
1451
1452                 /*
1453                  * determine the stream direction:
1454                  * if the connected output is USB stream, then it's likely a
1455                  * capture stream.  otherwise it should be playback (hopefully :)
1456                  */
1457                 if (!mapped_name && !(state->oterm.type >> 16)) {
1458                         if ((state->oterm.type & 0xff00) == 0x0100)
1459                                 append_ctl_name(kctl, " Capture");
1460                         else
1461                                 append_ctl_name(kctl, " Playback");
1462                 }
1463                 append_ctl_name(kctl, control == UAC_FU_MUTE ?
1464                                 " Switch" : " Volume");
1465                 break;
1466         default:
1467                 if (!len)
1468                         strlcpy(kctl->id.name, audio_feature_info[control-1].name,
1469                                 sizeof(kctl->id.name));
1470                 break;
1471         }
1472
1473         /* get min/max values */
1474         get_min_max_with_quirks(cval, 0, kctl);
1475
1476         if (control == UAC_FU_VOLUME) {
1477                 check_mapped_dB(map, cval);
1478                 if (cval->dBmin < cval->dBmax || !cval->initialized) {
1479                         kctl->tlv.c = snd_usb_mixer_vol_tlv;
1480                         kctl->vd[0].access |=
1481                                 SNDRV_CTL_ELEM_ACCESS_TLV_READ |
1482                                 SNDRV_CTL_ELEM_ACCESS_TLV_CALLBACK;
1483                 }
1484         }
1485
1486         snd_usb_mixer_fu_apply_quirk(state->mixer, cval, unitid, kctl);
1487
1488         range = (cval->max - cval->min) / cval->res;
1489         /*
1490          * Are there devices with volume range more than 255? I use a bit more
1491          * to be sure. 384 is a resolution magic number found on Logitech
1492          * devices. It will definitively catch all buggy Logitech devices.
1493          */
1494         if (range > 384) {
1495                 usb_audio_warn(state->chip,
1496                                "Warning! Unlikely big volume range (=%u), cval->res is probably wrong.",
1497                                range);
1498                 usb_audio_warn(state->chip,
1499                                "[%d] FU [%s] ch = %d, val = %d/%d/%d",
1500                                cval->head.id, kctl->id.name, cval->channels,
1501                                cval->min, cval->max, cval->res);
1502         }
1503
1504         usb_audio_dbg(state->chip, "[%d] FU [%s] ch = %d, val = %d/%d/%d\n",
1505                       cval->head.id, kctl->id.name, cval->channels,
1506                       cval->min, cval->max, cval->res);
1507         snd_usb_mixer_add_control(&cval->head, kctl);
1508 }
1509
1510 static int find_num_channels(struct mixer_build *state, int dir)
1511 {
1512         int num_ch = -EINVAL, num, i, j, wMaxPacketSize;
1513         int ctrlif = get_iface_desc(state->mixer->hostif)->bInterfaceNumber;
1514         struct usb_interface *usb_iface =
1515                         usb_ifnum_to_if(state->mixer->chip->dev, ctrlif);
1516         struct usb_interface_assoc_descriptor *assoc = usb_iface->intf_assoc;
1517         struct usb_host_interface *alts;
1518
1519         for (i = 0; i < assoc->bInterfaceCount; i++) {
1520                 int intf = assoc->bFirstInterface + i;
1521
1522                 if (intf != ctrlif) {
1523                         struct usb_interface *iface =
1524                                 usb_ifnum_to_if(state->mixer->chip->dev, intf);
1525
1526                         alts = &iface->altsetting[1];
1527                         if (dir == USB_DIR_OUT &&
1528                                 get_endpoint(alts, 0)->bEndpointAddress &
1529                                 USB_DIR_IN)
1530                                 continue;
1531                         if (dir == USB_DIR_IN &&
1532                                 !(get_endpoint(alts, 0)->bEndpointAddress &
1533                                 USB_DIR_IN))
1534                                 continue;
1535                         num = iface->num_altsetting;
1536                         for (j = 1; j < num; j++) {
1537                                 num_ch = NUM_CHANNELS_MONO;
1538                                 alts = &iface->altsetting[j];
1539                                 wMaxPacketSize = le16_to_cpu(
1540                                                         get_endpoint(alts, 0)->
1541                                                         wMaxPacketSize);
1542                                 switch (wMaxPacketSize) {
1543                                 case BADD_MAXPSIZE_SYNC_MONO_16:
1544                                 case BADD_MAXPSIZE_SYNC_MONO_24:
1545                                 case BADD_MAXPSIZE_ASYNC_MONO_16:
1546                                 case BADD_MAXPSIZE_ASYNC_MONO_24:
1547                                         break;
1548                                 case BADD_MAXPSIZE_SYNC_STEREO_16:
1549                                 case BADD_MAXPSIZE_SYNC_STEREO_24:
1550                                 case BADD_MAXPSIZE_ASYNC_STEREO_16:
1551                                 case BADD_MAXPSIZE_ASYNC_STEREO_24:
1552                                         num_ch = NUM_CHANNELS_STEREO;
1553                                         break;
1554                                 }
1555                                 if (num_ch == NUM_CHANNELS_MONO)
1556                                         continue;
1557                                 else
1558                                         break;
1559                         }
1560                 }
1561         }
1562
1563         return num_ch;
1564 }
1565
1566 /*
1567  * parse a feature unit
1568  *
1569  * most of controls are defined here.
1570  */
1571 static int parse_audio_feature_unit(struct mixer_build *state, int unitid,
1572                                     void *_ftr)
1573 {
1574         int channels, i, j;
1575         struct usb_audio_term iterm;
1576         unsigned int master_bits, first_ch_bits;
1577         int err, csize;
1578         struct uac_feature_unit_descriptor *hdr = _ftr;
1579         __u8 *bmaControls;
1580
1581         if (state->mixer->protocol == UAC_VERSION_1) {
1582                 if (hdr->bLength < 7) {
1583                         usb_audio_err(state->chip,
1584                                       "unit %u: invalid UAC_FEATURE_UNIT descriptor\n",
1585                                       unitid);
1586                         return -EINVAL;
1587                 }
1588                 csize = hdr->bControlSize;
1589                 if (!csize) {
1590                         usb_audio_dbg(state->chip,
1591                                       "unit %u: invalid bControlSize == 0\n",
1592                                       unitid);
1593                         return -EINVAL;
1594                 }
1595                 channels = (hdr->bLength - 7) / csize - 1;
1596                 bmaControls = hdr->bmaControls;
1597                 if (hdr->bLength < 7 + csize) {
1598                         usb_audio_err(state->chip,
1599                                       "unit %u: invalid UAC_FEATURE_UNIT descriptor\n",
1600                                       unitid);
1601                         return -EINVAL;
1602                 }
1603         } else if (state->mixer->protocol == UAC_VERSION_2) {
1604                 struct uac2_feature_unit_descriptor *ftr = _ftr;
1605                 if (hdr->bLength < 6) {
1606                         usb_audio_err(state->chip,
1607                                       "unit %u: invalid UAC_FEATURE_UNIT descriptor\n",
1608                                       unitid);
1609                         return -EINVAL;
1610                 }
1611                 csize = 4;
1612                 channels = (hdr->bLength - 6) / 4 - 1;
1613                 bmaControls = ftr->bmaControls;
1614                 if (hdr->bLength < 6 + csize) {
1615                         usb_audio_err(state->chip,
1616                                       "unit %u: invalid UAC_FEATURE_UNIT descriptor\n",
1617                                       unitid);
1618                         return -EINVAL;
1619                 }
1620         } else {
1621                 struct usb_interface *usb_iface =
1622                         usb_ifnum_to_if(state->mixer->chip->dev,
1623                         get_iface_desc(state->mixer->hostif)->bInterfaceNumber);
1624                 struct usb_interface_assoc_descriptor *assoc =
1625                                                         usb_iface->intf_assoc;
1626
1627                 csize = 4;
1628                 switch (unitid) {
1629                 case BADD_FU_ID_BAIOF:
1630                         channels = NUM_CHANNELS_MONO;
1631                         bmaControls = monoControls;
1632                         badd_baif_in_term_desc.wClusterDescrID =
1633                                                 CLUSTER_ID_MONO;
1634                         break;
1635
1636                 case BADD_FU_ID_BAOF:
1637                         switch (assoc->bFunctionSubClass) {
1638                         case PROF_HEADPHONE:
1639                         case PROF_HEADSET_ADAPTER:
1640                                 channels = NUM_CHANNELS_STEREO;
1641                                 bmaControls = stereoControls;
1642                                 badd_baiof_mu_desc.wClusterDescrID =
1643                                         CLUSTER_ID_MONO;
1644                                 break;
1645                         case PROF_SPEAKERPHONE:
1646                                 channels = NUM_CHANNELS_MONO;
1647                                 bmaControls = monoControls;
1648                                 badd_baof_in_term_desc.wClusterDescrID =
1649                                         CLUSTER_ID_MONO;
1650                                 break;
1651                         default:
1652                                 channels = find_num_channels(state,
1653                                                                 USB_DIR_OUT);
1654                                 if (channels < 0) {
1655                                         usb_audio_err(state->chip,
1656                                                       "unit %u: Cant find num of channels\n",
1657                                                       unitid);
1658                                         return channels;
1659                                 }
1660
1661                                 bmaControls = (channels == NUM_CHANNELS_MONO) ?
1662                                                 monoControls : stereoControls;
1663                                 badd_baof_in_term_desc.wClusterDescrID =
1664                                         (channels == NUM_CHANNELS_MONO) ?
1665                                         CLUSTER_ID_MONO : CLUSTER_ID_STEREO;
1666                                 break;
1667                         }
1668                         break;
1669
1670                 case BADD_FU_ID_BAIF:
1671                         switch (assoc->bFunctionSubClass) {
1672                         case PROF_HEADSET:
1673                         case PROF_HEADSET_ADAPTER:
1674                         case PROF_SPEAKERPHONE:
1675                                 channels = NUM_CHANNELS_MONO;
1676                                 bmaControls = monoControls;
1677                                 badd_baif_in_term_desc.wClusterDescrID =
1678                                         CLUSTER_ID_MONO;
1679                                 break;
1680                         default:
1681                                 channels = find_num_channels(state, USB_DIR_IN);
1682                                 if (channels < 0) {
1683                                         usb_audio_err(state->chip,
1684                                                       "unit %u: Cant find num of channels\n",
1685                                                       unitid);
1686                                         return channels;
1687                                 }
1688
1689                                 bmaControls = (channels == NUM_CHANNELS_MONO) ?
1690                                                  monoControls : stereoControls;
1691                                 badd_baif_in_term_desc.wClusterDescrID =
1692                                         (channels == NUM_CHANNELS_MONO) ?
1693                                         CLUSTER_ID_MONO : CLUSTER_ID_STEREO;
1694                                 break;
1695                         }
1696                         break;
1697
1698                 default:
1699                         usb_audio_err(state->chip, "Invalid unit %u\n", unitid);
1700                         return -EINVAL;
1701                 }
1702         }
1703
1704         /* parse the source unit */
1705         if (state->mixer->protocol != UAC_VERSION_3) {
1706                 err = parse_audio_unit(state, hdr->bSourceID);
1707                 if (err < 0)
1708                         return err;
1709         } else {
1710                 struct usb_interface *usb_iface =
1711                         usb_ifnum_to_if(state->mixer->chip->dev,
1712                         get_iface_desc(state->mixer->hostif)->bInterfaceNumber);
1713                 struct usb_interface_assoc_descriptor *assoc =
1714                         usb_iface->intf_assoc;
1715
1716                 switch (unitid) {
1717                 case BADD_FU_ID_BAOF:
1718                         switch (assoc->bFunctionSubClass) {
1719                         case PROF_HEADSET:
1720                         case PROF_HEADSET_ADAPTER:
1721                                 hdr->bSourceID = BADD_MU_ID_BAIOF;
1722                                 break;
1723                         default:
1724                                 hdr->bSourceID = BADD_IN_TERM_ID_BAOF;
1725                                 break;
1726                         }
1727                 }
1728                 err = parse_audio_unit(state, hdr->bSourceID);
1729                 if (err < 0)
1730                         return err;
1731         }
1732
1733         /* determine the input source type and name */
1734         err = check_input_term(state, hdr->bSourceID, &iterm);
1735         if (err < 0)
1736                 return err;
1737
1738         master_bits = snd_usb_combine_bytes(bmaControls, csize);
1739         /* master configuration quirks */
1740         switch (state->chip->usb_id) {
1741         case USB_ID(0x08bb, 0x2702):
1742                 usb_audio_info(state->chip,
1743                                "usbmixer: master volume quirk for PCM2702 chip\n");
1744                 /* disable non-functional volume control */
1745                 master_bits &= ~UAC_CONTROL_BIT(UAC_FU_VOLUME);
1746                 break;
1747         case USB_ID(0x1130, 0xf211):
1748                 usb_audio_info(state->chip,
1749                                "usbmixer: volume control quirk for Tenx TP6911 Audio Headset\n");
1750                 /* disable non-functional volume control */
1751                 channels = 0;
1752                 break;
1753
1754         }
1755         if (channels > 0)
1756                 first_ch_bits = snd_usb_combine_bytes(bmaControls + csize, csize);
1757         else
1758                 first_ch_bits = 0;
1759
1760         if (state->mixer->protocol == UAC_VERSION_1) {
1761                 /* check all control types */
1762                 for (i = 0; i < 10; i++) {
1763                         unsigned int ch_bits = 0;
1764                         for (j = 0; j < channels; j++) {
1765                                 unsigned int mask;
1766
1767                                 mask = snd_usb_combine_bytes(bmaControls +
1768                                                              csize * (j+1), csize);
1769                                 if (mask & (1 << i))
1770                                         ch_bits |= (1 << j);
1771                         }
1772                         /* audio class v1 controls are never read-only */
1773
1774                         /*
1775                          * The first channel must be set
1776                          * (for ease of programming).
1777                          */
1778                         if (ch_bits & 1)
1779                                 build_feature_ctl(state, _ftr, ch_bits, i,
1780                                                   &iterm, unitid, 0);
1781                         if (master_bits & (1 << i))
1782                                 build_feature_ctl(state, _ftr, 0, i, &iterm,
1783                                                   unitid, 0);
1784                 }
1785         } else { /* UAC_VERSION_2 or UAC_VERSION_3*/
1786                 for (i = 0; i < ARRAY_SIZE(audio_feature_info); i++) {
1787                         unsigned int ch_bits = 0;
1788                         unsigned int ch_read_only = 0;
1789
1790                         for (j = 0; j < channels; j++) {
1791                                 unsigned int mask;
1792
1793                                 mask = snd_usb_combine_bytes(bmaControls +
1794                                                              csize * (j+1), csize);
1795                                 if (uac2_control_is_readable(mask, i)) {
1796                                         ch_bits |= (1 << j);
1797                                         if (!uac2_control_is_writeable(mask, i))
1798                                                 ch_read_only |= (1 << j);
1799                                 }
1800                         }
1801
1802                         /*
1803                          * NOTE: build_feature_ctl() will mark the control
1804                          * read-only if all channels are marked read-only in
1805                          * the descriptors. Otherwise, the control will be
1806                          * reported as writeable, but the driver will not
1807                          * actually issue a write command for read-only
1808                          * channels.
1809                          */
1810
1811                         /*
1812                          * The first channel must be set
1813                          * (for ease of programming).
1814                          */
1815                         if (ch_bits & 1)
1816                                 build_feature_ctl(state, _ftr, ch_bits, i,
1817                                                   &iterm, unitid, ch_read_only);
1818                         if (uac2_control_is_readable(master_bits, i))
1819                                 build_feature_ctl(state, _ftr, 0, i, &iterm, unitid,
1820                                                   !uac2_control_is_writeable(master_bits, i));
1821                 }
1822         }
1823
1824         return 0;
1825 }
1826
1827 /*
1828  * Mixer Unit
1829  */
1830
1831 /*
1832  * build a mixer unit control
1833  *
1834  * the callbacks are identical with feature unit.
1835  * input channel number (zero based) is given in control field instead.
1836  */
1837 static void build_mixer_unit_ctl(struct mixer_build *state,
1838                                  struct uac_mixer_unit_descriptor *desc,
1839                                  int in_pin, int in_ch, int unitid,
1840                                  struct usb_audio_term *iterm)
1841 {
1842         struct usb_mixer_elem_info *cval;
1843         unsigned int num_outs = uac_mixer_unit_bNrChannels(desc);
1844         unsigned int i, len;
1845         struct snd_kcontrol *kctl;
1846         const struct usbmix_name_map *map;
1847
1848         map = find_map(state, unitid, 0);
1849         if (check_ignored_ctl(map))
1850                 return;
1851
1852         cval = kzalloc(sizeof(*cval), GFP_KERNEL);
1853         if (!cval)
1854                 return;
1855
1856         snd_usb_mixer_elem_init_std(&cval->head, state->mixer, unitid);
1857         cval->control = in_ch + 1; /* based on 1 */
1858         cval->val_type = USB_MIXER_S16;
1859         for (i = 0; i < num_outs; i++) {
1860                 __u8 *c = uac_mixer_unit_bmControls(desc, state->mixer->protocol);
1861
1862                 if (check_matrix_bitmap(c, in_ch, i, num_outs)) {
1863                         cval->cmask |= (1 << i);
1864                         cval->channels++;
1865                 }
1866         }
1867
1868         /* get min/max values */
1869         get_min_max(cval, 0);
1870
1871         kctl = snd_ctl_new1(&usb_feature_unit_ctl, cval);
1872         if (!kctl) {
1873                 usb_audio_err(state->chip, "cannot malloc kcontrol\n");
1874                 kfree(cval);
1875                 return;
1876         }
1877         kctl->private_free = snd_usb_mixer_elem_free;
1878
1879         len = check_mapped_name(map, kctl->id.name, sizeof(kctl->id.name));
1880         if (!len)
1881                 len = get_term_name(state, iterm, kctl->id.name,
1882                                     sizeof(kctl->id.name), 0);
1883         if (!len)
1884                 len = sprintf(kctl->id.name, "Mixer Source %d", in_ch + 1);
1885         append_ctl_name(kctl, " Volume");
1886
1887         usb_audio_dbg(state->chip, "[%d] MU [%s] ch = %d, val = %d/%d\n",
1888                     cval->head.id, kctl->id.name, cval->channels, cval->min, cval->max);
1889         snd_usb_mixer_add_control(&cval->head, kctl);
1890 }
1891
1892 /*
1893  * parse a mixer unit
1894  */
1895 static int parse_audio_mixer_unit(struct mixer_build *state, int unitid,
1896                                   void *raw_desc)
1897 {
1898         struct uac_mixer_unit_descriptor *desc = raw_desc;
1899         struct usb_audio_term iterm;
1900         int input_pins, num_ins, num_outs;
1901         int pin, ich, err;
1902
1903         if (state->mixer->protocol == UAC_VERSION_3) {
1904                 input_pins = badd_baiof_mu_desc.bNrInPins;
1905                 num_outs =
1906                    (badd_baiof_mu_desc.wClusterDescrID == CLUSTER_ID_MONO) ?
1907                     NUM_CHANNELS_MONO : NUM_CHANNELS_STEREO;
1908         } else {
1909                 if (desc->bLength < 11 || !(input_pins = desc->bNrInPins) ||
1910                     desc->bLength < sizeof(*desc) + desc->bNrInPins ||
1911                     !(num_outs = uac_mixer_unit_bNrChannels(desc))) {
1912                         usb_audio_err(state->chip,
1913                                       "invalid MIXER UNIT descriptor %d\n",
1914                                       unitid);
1915                         return -EINVAL;
1916                 }
1917         }
1918
1919         num_ins = 0;
1920         ich = 0;
1921         for (pin = 0; pin < input_pins; pin++) {
1922                 err = parse_audio_unit(state, desc->baSourceID[pin]);
1923                 if (err < 0)
1924                         continue;
1925                 /* no bmControls field (e.g. Maya44) -> ignore */
1926                 if (desc->bLength <= 10 + input_pins)
1927                         continue;
1928                 err = check_input_term(state, desc->baSourceID[pin], &iterm);
1929                 if (err < 0)
1930                         return err;
1931                 num_ins += iterm.channels;
1932                 for (; ich < num_ins; ich++) {
1933                         int och, ich_has_controls = 0;
1934
1935                         for (och = 0; och < num_outs; och++) {
1936                                 __u8 *c = NULL;
1937
1938                                 if (state->mixer->protocol == UAC_VERSION_3)
1939                                         c =
1940                                           &(badd_baiof_mu_desc.bmMixerControls);
1941                                 else
1942                                         c = uac_mixer_unit_bmControls(desc,
1943                                                         state->mixer->protocol);
1944                                 if (check_matrix_bitmap(c, ich, och, num_outs)) {
1945                                         ich_has_controls = 1;
1946                                         break;
1947                                 }
1948                         }
1949                         if (ich_has_controls)
1950                                 build_mixer_unit_ctl(state, desc, pin, ich,
1951                                                      unitid, &iterm);
1952                 }
1953         }
1954         return 0;
1955 }
1956
1957 /*
1958  * Processing Unit / Extension Unit
1959  */
1960
1961 /* get callback for processing/extension unit */
1962 static int mixer_ctl_procunit_get(struct snd_kcontrol *kcontrol,
1963                                   struct snd_ctl_elem_value *ucontrol)
1964 {
1965         struct usb_mixer_elem_info *cval = kcontrol->private_data;
1966         int err, val;
1967
1968         err = get_cur_ctl_value(cval, cval->control << 8, &val);
1969         if (err < 0) {
1970                 ucontrol->value.integer.value[0] = cval->min;
1971                 return filter_error(cval, err);
1972         }
1973         val = get_relative_value(cval, val);
1974         ucontrol->value.integer.value[0] = val;
1975         return 0;
1976 }
1977
1978 /* put callback for processing/extension unit */
1979 static int mixer_ctl_procunit_put(struct snd_kcontrol *kcontrol,
1980                                   struct snd_ctl_elem_value *ucontrol)
1981 {
1982         struct usb_mixer_elem_info *cval = kcontrol->private_data;
1983         int val, oval, err;
1984
1985         err = get_cur_ctl_value(cval, cval->control << 8, &oval);
1986         if (err < 0)
1987                 return filter_error(cval, err);
1988         val = ucontrol->value.integer.value[0];
1989         val = get_abs_value(cval, val);
1990         if (val != oval) {
1991                 set_cur_ctl_value(cval, cval->control << 8, val);
1992                 return 1;
1993         }
1994         return 0;
1995 }
1996
1997 /* alsa control interface for processing/extension unit */
1998 static struct snd_kcontrol_new mixer_procunit_ctl = {
1999         .iface = SNDRV_CTL_ELEM_IFACE_MIXER,
2000         .name = "", /* will be filled later */
2001         .info = mixer_ctl_feature_info,
2002         .get = mixer_ctl_procunit_get,
2003         .put = mixer_ctl_procunit_put,
2004 };
2005
2006 /*
2007  * predefined data for processing units
2008  */
2009 struct procunit_value_info {
2010         int control;
2011         char *suffix;
2012         int val_type;
2013         int min_value;
2014 };
2015
2016 struct procunit_info {
2017         int type;
2018         char *name;
2019         struct procunit_value_info *values;
2020 };
2021
2022 static struct procunit_value_info updown_proc_info[] = {
2023         { UAC_UD_ENABLE, "Switch", USB_MIXER_BOOLEAN },
2024         { UAC_UD_MODE_SELECT, "Mode Select", USB_MIXER_U8, 1 },
2025         { 0 }
2026 };
2027 static struct procunit_value_info prologic_proc_info[] = {
2028         { UAC_DP_ENABLE, "Switch", USB_MIXER_BOOLEAN },
2029         { UAC_DP_MODE_SELECT, "Mode Select", USB_MIXER_U8, 1 },
2030         { 0 }
2031 };
2032 static struct procunit_value_info threed_enh_proc_info[] = {
2033         { UAC_3D_ENABLE, "Switch", USB_MIXER_BOOLEAN },
2034         { UAC_3D_SPACE, "Spaciousness", USB_MIXER_U8 },
2035         { 0 }
2036 };
2037 static struct procunit_value_info reverb_proc_info[] = {
2038         { UAC_REVERB_ENABLE, "Switch", USB_MIXER_BOOLEAN },
2039         { UAC_REVERB_LEVEL, "Level", USB_MIXER_U8 },
2040         { UAC_REVERB_TIME, "Time", USB_MIXER_U16 },
2041         { UAC_REVERB_FEEDBACK, "Feedback", USB_MIXER_U8 },
2042         { 0 }
2043 };
2044 static struct procunit_value_info chorus_proc_info[] = {
2045         { UAC_CHORUS_ENABLE, "Switch", USB_MIXER_BOOLEAN },
2046         { UAC_CHORUS_LEVEL, "Level", USB_MIXER_U8 },
2047         { UAC_CHORUS_RATE, "Rate", USB_MIXER_U16 },
2048         { UAC_CHORUS_DEPTH, "Depth", USB_MIXER_U16 },
2049         { 0 }
2050 };
2051 static struct procunit_value_info dcr_proc_info[] = {
2052         { UAC_DCR_ENABLE, "Switch", USB_MIXER_BOOLEAN },
2053         { UAC_DCR_RATE, "Ratio", USB_MIXER_U16 },
2054         { UAC_DCR_MAXAMPL, "Max Amp", USB_MIXER_S16 },
2055         { UAC_DCR_THRESHOLD, "Threshold", USB_MIXER_S16 },
2056         { UAC_DCR_ATTACK_TIME, "Attack Time", USB_MIXER_U16 },
2057         { UAC_DCR_RELEASE_TIME, "Release Time", USB_MIXER_U16 },
2058         { 0 }
2059 };
2060
2061 static struct procunit_info procunits[] = {
2062         { UAC_PROCESS_UP_DOWNMIX, "Up Down", updown_proc_info },
2063         { UAC_PROCESS_DOLBY_PROLOGIC, "Dolby Prologic", prologic_proc_info },
2064         { UAC_PROCESS_STEREO_EXTENDER, "3D Stereo Extender", threed_enh_proc_info },
2065         { UAC_PROCESS_REVERB, "Reverb", reverb_proc_info },
2066         { UAC_PROCESS_CHORUS, "Chorus", chorus_proc_info },
2067         { UAC_PROCESS_DYN_RANGE_COMP, "DCR", dcr_proc_info },
2068         { 0 },
2069 };
2070 /*
2071  * predefined data for extension units
2072  */
2073 static struct procunit_value_info clock_rate_xu_info[] = {
2074         { USB_XU_CLOCK_RATE_SELECTOR, "Selector", USB_MIXER_U8, 0 },
2075         { 0 }
2076 };
2077 static struct procunit_value_info clock_source_xu_info[] = {
2078         { USB_XU_CLOCK_SOURCE_SELECTOR, "External", USB_MIXER_BOOLEAN },
2079         { 0 }
2080 };
2081 static struct procunit_value_info spdif_format_xu_info[] = {
2082         { USB_XU_DIGITAL_FORMAT_SELECTOR, "SPDIF/AC3", USB_MIXER_BOOLEAN },
2083         { 0 }
2084 };
2085 static struct procunit_value_info soft_limit_xu_info[] = {
2086         { USB_XU_SOFT_LIMIT_SELECTOR, " ", USB_MIXER_BOOLEAN },
2087         { 0 }
2088 };
2089 static struct procunit_info extunits[] = {
2090         { USB_XU_CLOCK_RATE, "Clock rate", clock_rate_xu_info },
2091         { USB_XU_CLOCK_SOURCE, "DigitalIn CLK source", clock_source_xu_info },
2092         { USB_XU_DIGITAL_IO_STATUS, "DigitalOut format:", spdif_format_xu_info },
2093         { USB_XU_DEVICE_OPTIONS, "AnalogueIn Soft Limit", soft_limit_xu_info },
2094         { 0 }
2095 };
2096
2097 /*
2098  * build a processing/extension unit
2099  */
2100 static int build_audio_procunit(struct mixer_build *state, int unitid,
2101                                 void *raw_desc, struct procunit_info *list,
2102                                 char *name)
2103 {
2104         struct uac_processing_unit_descriptor *desc = raw_desc;
2105         int num_ins;
2106         struct usb_mixer_elem_info *cval;
2107         struct snd_kcontrol *kctl;
2108         int i, err, nameid, type, len;
2109         struct procunit_info *info;
2110         struct procunit_value_info *valinfo;
2111         const struct usbmix_name_map *map;
2112         static struct procunit_value_info default_value_info[] = {
2113                 { 0x01, "Switch", USB_MIXER_BOOLEAN },
2114                 { 0 }
2115         };
2116         static struct procunit_info default_info = {
2117                 0, NULL, default_value_info
2118         };
2119
2120         if (desc->bLength < 13) {
2121                 usb_audio_err(state->chip, "invalid %s descriptor (id %d)\n", name, unitid);
2122                 return -EINVAL;
2123         }
2124
2125         num_ins = desc->bNrInPins;
2126         if (desc->bLength < 13 + num_ins ||
2127             desc->bLength < num_ins + uac_processing_unit_bControlSize(desc, state->mixer->protocol)) {
2128                 usb_audio_err(state->chip, "invalid %s descriptor (id %d)\n", name, unitid);
2129                 return -EINVAL;
2130         }
2131
2132         for (i = 0; i < num_ins; i++) {
2133                 if ((err = parse_audio_unit(state, desc->baSourceID[i])) < 0)
2134                         return err;
2135         }
2136
2137         type = le16_to_cpu(desc->wProcessType);
2138         for (info = list; info && info->type; info++)
2139                 if (info->type == type)
2140                         break;
2141         if (!info || !info->type)
2142                 info = &default_info;
2143
2144         for (valinfo = info->values; valinfo->control; valinfo++) {
2145                 __u8 *controls = uac_processing_unit_bmControls(desc, state->mixer->protocol);
2146
2147                 if (!(controls[valinfo->control / 8] & (1 << ((valinfo->control % 8) - 1))))
2148                         continue;
2149                 map = find_map(state, unitid, valinfo->control);
2150                 if (check_ignored_ctl(map))
2151                         continue;
2152                 cval = kzalloc(sizeof(*cval), GFP_KERNEL);
2153                 if (!cval)
2154                         return -ENOMEM;
2155                 snd_usb_mixer_elem_init_std(&cval->head, state->mixer, unitid);
2156                 cval->control = valinfo->control;
2157                 cval->val_type = valinfo->val_type;
2158                 cval->channels = 1;
2159
2160                 /* get min/max values */
2161                 if (type == UAC_PROCESS_UP_DOWNMIX && cval->control == UAC_UD_MODE_SELECT) {
2162                         __u8 *control_spec = uac_processing_unit_specific(desc, state->mixer->protocol);
2163                         /* FIXME: hard-coded */
2164                         cval->min = 1;
2165                         cval->max = control_spec[0];
2166                         cval->res = 1;
2167                         cval->initialized = 1;
2168                 } else {
2169                         if (type == USB_XU_CLOCK_RATE) {
2170                                 /*
2171                                  * E-Mu USB 0404/0202/TrackerPre/0204
2172                                  * samplerate control quirk
2173                                  */
2174                                 cval->min = 0;
2175                                 cval->max = 5;
2176                                 cval->res = 1;
2177                                 cval->initialized = 1;
2178                         } else
2179                                 get_min_max(cval, valinfo->min_value);
2180                 }
2181
2182                 kctl = snd_ctl_new1(&mixer_procunit_ctl, cval);
2183                 if (!kctl) {
2184                         kfree(cval);
2185                         return -ENOMEM;
2186                 }
2187                 kctl->private_free = snd_usb_mixer_elem_free;
2188
2189                 if (check_mapped_name(map, kctl->id.name, sizeof(kctl->id.name))) {
2190                         /* nothing */ ;
2191                 } else if (info->name) {
2192                         strlcpy(kctl->id.name, info->name, sizeof(kctl->id.name));
2193                 } else {
2194                         nameid = uac_processing_unit_iProcessing(desc, state->mixer->protocol);
2195                         len = 0;
2196                         if (nameid)
2197                                 len = snd_usb_copy_string_desc(state, nameid,
2198                                                                kctl->id.name,
2199                                                                sizeof(kctl->id.name));
2200                         if (!len)
2201                                 strlcpy(kctl->id.name, name, sizeof(kctl->id.name));
2202                 }
2203                 append_ctl_name(kctl, " ");
2204                 append_ctl_name(kctl, valinfo->suffix);
2205
2206                 usb_audio_dbg(state->chip,
2207                               "[%d] PU [%s] ch = %d, val = %d/%d\n",
2208                               cval->head.id, kctl->id.name, cval->channels,
2209                               cval->min, cval->max);
2210
2211                 err = snd_usb_mixer_add_control(&cval->head, kctl);
2212                 if (err < 0)
2213                         return err;
2214         }
2215         return 0;
2216 }
2217
2218 static int parse_audio_processing_unit(struct mixer_build *state, int unitid,
2219                                        void *raw_desc)
2220 {
2221         return build_audio_procunit(state, unitid, raw_desc,
2222                                     procunits, "Processing Unit");
2223 }
2224
2225 static int parse_audio_extension_unit(struct mixer_build *state, int unitid,
2226                                       void *raw_desc)
2227 {
2228         /*
2229          * Note that we parse extension units with processing unit descriptors.
2230          * That's ok as the layout is the same.
2231          */
2232         return build_audio_procunit(state, unitid, raw_desc,
2233                                     extunits, "Extension Unit");
2234 }
2235
2236 /*
2237  * Selector Unit
2238  */
2239
2240 /*
2241  * info callback for selector unit
2242  * use an enumerator type for routing
2243  */
2244 static int mixer_ctl_selector_info(struct snd_kcontrol *kcontrol,
2245                                    struct snd_ctl_elem_info *uinfo)
2246 {
2247         struct usb_mixer_elem_info *cval = kcontrol->private_data;
2248         const char **itemlist = (const char **)kcontrol->private_value;
2249
2250         if (snd_BUG_ON(!itemlist))
2251                 return -EINVAL;
2252         return snd_ctl_enum_info(uinfo, 1, cval->max, itemlist);
2253 }
2254
2255 /* get callback for selector unit */
2256 static int mixer_ctl_selector_get(struct snd_kcontrol *kcontrol,
2257                                   struct snd_ctl_elem_value *ucontrol)
2258 {
2259         struct usb_mixer_elem_info *cval = kcontrol->private_data;
2260         int val, err;
2261
2262         err = get_cur_ctl_value(cval, cval->control << 8, &val);
2263         if (err < 0) {
2264                 ucontrol->value.enumerated.item[0] = 0;
2265                 return filter_error(cval, err);
2266         }
2267         val = get_relative_value(cval, val);
2268         ucontrol->value.enumerated.item[0] = val;
2269         return 0;
2270 }
2271
2272 /* put callback for selector unit */
2273 static int mixer_ctl_selector_put(struct snd_kcontrol *kcontrol,
2274                                   struct snd_ctl_elem_value *ucontrol)
2275 {
2276         struct usb_mixer_elem_info *cval = kcontrol->private_data;
2277         int val, oval, err;
2278
2279         err = get_cur_ctl_value(cval, cval->control << 8, &oval);
2280         if (err < 0)
2281                 return filter_error(cval, err);
2282         val = ucontrol->value.enumerated.item[0];
2283         val = get_abs_value(cval, val);
2284         if (val != oval) {
2285                 set_cur_ctl_value(cval, cval->control << 8, val);
2286                 return 1;
2287         }
2288         return 0;
2289 }
2290
2291 /* alsa control interface for selector unit */
2292 static struct snd_kcontrol_new mixer_selectunit_ctl = {
2293         .iface = SNDRV_CTL_ELEM_IFACE_MIXER,
2294         .name = "", /* will be filled later */
2295         .info = mixer_ctl_selector_info,
2296         .get = mixer_ctl_selector_get,
2297         .put = mixer_ctl_selector_put,
2298 };
2299
2300 /*
2301  * private free callback.
2302  * free both private_data and private_value
2303  */
2304 static void usb_mixer_selector_elem_free(struct snd_kcontrol *kctl)
2305 {
2306         int i, num_ins = 0;
2307
2308         if (kctl->private_data) {
2309                 struct usb_mixer_elem_info *cval = kctl->private_data;
2310                 num_ins = cval->max;
2311                 kfree(cval);
2312                 kctl->private_data = NULL;
2313         }
2314         if (kctl->private_value) {
2315                 char **itemlist = (char **)kctl->private_value;
2316                 for (i = 0; i < num_ins; i++)
2317                         kfree(itemlist[i]);
2318                 kfree(itemlist);
2319                 kctl->private_value = 0;
2320         }
2321 }
2322
2323 /*
2324  * parse a selector unit
2325  */
2326 static int parse_audio_selector_unit(struct mixer_build *state, int unitid,
2327                                      void *raw_desc)
2328 {
2329         struct uac_selector_unit_descriptor *desc = raw_desc;
2330         unsigned int i, nameid, len;
2331         int err;
2332         struct usb_mixer_elem_info *cval;
2333         struct snd_kcontrol *kctl;
2334         const struct usbmix_name_map *map;
2335         char **namelist;
2336
2337         if (desc->bLength < 5 || !desc->bNrInPins ||
2338             desc->bLength < 5 + desc->bNrInPins) {
2339                 usb_audio_err(state->chip,
2340                         "invalid SELECTOR UNIT descriptor %d\n", unitid);
2341                 return -EINVAL;
2342         }
2343
2344         for (i = 0; i < desc->bNrInPins; i++) {
2345                 if ((err = parse_audio_unit(state, desc->baSourceID[i])) < 0)
2346                         return err;
2347         }
2348
2349         if (desc->bNrInPins == 1) /* only one ? nonsense! */
2350                 return 0;
2351
2352         map = find_map(state, unitid, 0);
2353         if (check_ignored_ctl(map))
2354                 return 0;
2355
2356         cval = kzalloc(sizeof(*cval), GFP_KERNEL);
2357         if (!cval)
2358                 return -ENOMEM;
2359         snd_usb_mixer_elem_init_std(&cval->head, state->mixer, unitid);
2360         cval->val_type = USB_MIXER_U8;
2361         cval->channels = 1;
2362         cval->min = 1;
2363         cval->max = desc->bNrInPins;
2364         cval->res = 1;
2365         cval->initialized = 1;
2366
2367         if (state->mixer->protocol == UAC_VERSION_1)
2368                 cval->control = 0;
2369         else /* UAC_VERSION_2 */
2370                 cval->control = (desc->bDescriptorSubtype == UAC2_CLOCK_SELECTOR) ?
2371                         UAC2_CX_CLOCK_SELECTOR : UAC2_SU_SELECTOR;
2372
2373         namelist = kmalloc(sizeof(char *) * desc->bNrInPins, GFP_KERNEL);
2374         if (!namelist) {
2375                 kfree(cval);
2376                 return -ENOMEM;
2377         }
2378 #define MAX_ITEM_NAME_LEN       64
2379         for (i = 0; i < desc->bNrInPins; i++) {
2380                 struct usb_audio_term iterm;
2381                 len = 0;
2382                 namelist[i] = kmalloc(MAX_ITEM_NAME_LEN, GFP_KERNEL);
2383                 if (!namelist[i]) {
2384                         while (i--)
2385                                 kfree(namelist[i]);
2386                         kfree(namelist);
2387                         kfree(cval);
2388                         return -ENOMEM;
2389                 }
2390                 len = check_mapped_selector_name(state, unitid, i, namelist[i],
2391                                                  MAX_ITEM_NAME_LEN);
2392                 if (! len && check_input_term(state, desc->baSourceID[i], &iterm) >= 0)
2393                         len = get_term_name(state, &iterm, namelist[i], MAX_ITEM_NAME_LEN, 0);
2394                 if (! len)
2395                         sprintf(namelist[i], "Input %u", i);
2396         }
2397
2398         kctl = snd_ctl_new1(&mixer_selectunit_ctl, cval);
2399         if (! kctl) {
2400                 usb_audio_err(state->chip, "cannot malloc kcontrol\n");
2401                 for (i = 0; i < desc->bNrInPins; i++)
2402                         kfree(namelist[i]);
2403                 kfree(namelist);
2404                 kfree(cval);
2405                 return -ENOMEM;
2406         }
2407         kctl->private_value = (unsigned long)namelist;
2408         kctl->private_free = usb_mixer_selector_elem_free;
2409
2410         /* check the static mapping table at first */
2411         len = check_mapped_name(map, kctl->id.name, sizeof(kctl->id.name));
2412         if (!len) {
2413                 /* no mapping ? */
2414                 /* if iSelector is given, use it */
2415                 nameid = uac_selector_unit_iSelector(desc);
2416                 if (nameid)
2417                         len = snd_usb_copy_string_desc(state, nameid,
2418                                                        kctl->id.name,
2419                                                        sizeof(kctl->id.name));
2420                 /* ... or pick up the terminal name at next */
2421                 if (!len)
2422                         len = get_term_name(state, &state->oterm,
2423                                     kctl->id.name, sizeof(kctl->id.name), 0);
2424                 /* ... or use the fixed string "USB" as the last resort */
2425                 if (!len)
2426                         strlcpy(kctl->id.name, "USB", sizeof(kctl->id.name));
2427
2428                 /* and add the proper suffix */
2429                 if (desc->bDescriptorSubtype == UAC2_CLOCK_SELECTOR)
2430                         append_ctl_name(kctl, " Clock Source");
2431                 else if ((state->oterm.type & 0xff00) == 0x0100)
2432                         append_ctl_name(kctl, " Capture Source");
2433                 else
2434                         append_ctl_name(kctl, " Playback Source");
2435         }
2436
2437         usb_audio_dbg(state->chip, "[%d] SU [%s] items = %d\n",
2438                     cval->head.id, kctl->id.name, desc->bNrInPins);
2439         return snd_usb_mixer_add_control(&cval->head, kctl);
2440 }
2441
2442 /*
2443  * parse an audio unit recursively
2444  */
2445
2446 static int parse_audio_unit(struct mixer_build *state, int unitid)
2447 {
2448         unsigned char *p1;
2449
2450         if (test_and_set_bit(unitid, state->unitbitmap))
2451                 return 0; /* the unit already visited */
2452
2453         p1 = find_audio_control_unit(state, unitid);
2454         if (!p1) {
2455                 usb_audio_err(state->chip, "unit %d not found!\n", unitid);
2456                 return -EINVAL;
2457         }
2458
2459         switch (p1[2]) {
2460         case UAC_INPUT_TERMINAL:
2461         case UAC2_CLOCK_SOURCE:
2462                 return 0; /* NOP */
2463         case UAC_MIXER_UNIT:
2464                 return parse_audio_mixer_unit(state, unitid, p1);
2465         case UAC_SELECTOR_UNIT:
2466         /*   UAC3_MIXER_UNIT_V3 has the same value */
2467         case UAC2_CLOCK_SELECTOR:
2468         /*   UAC3_CLOCK_SOURCE has the same value */
2469                 if (state->mixer->protocol == UAC_VERSION_3 &&
2470                         p1[2] == UAC3_CLOCK_SOURCE)
2471                         return 0; /* NOP */
2472                 else if (state->mixer->protocol == UAC_VERSION_3
2473                         && p1[2] == UAC3_MIXER_UNIT_V3)
2474                         return parse_audio_mixer_unit(state, unitid, p1);
2475                 else
2476                         return parse_audio_selector_unit(state, unitid, p1);
2477         case UAC_FEATURE_UNIT:
2478                 return parse_audio_feature_unit(state, unitid, p1);
2479         case UAC1_PROCESSING_UNIT:
2480         /*   UAC2_EFFECT_UNIT has the same value */
2481         /*   UAC3_FEATURE_UNIT_V3 has the same value */
2482                 if (state->mixer->protocol == UAC_VERSION_1)
2483                         return parse_audio_processing_unit(state, unitid, p1);
2484                 else if (state->mixer->protocol == UAC_VERSION_2)
2485                         return 0; /* FIXME - effect units not implemented yet */
2486                 else
2487                         return parse_audio_feature_unit(state, unitid, p1);
2488         case UAC1_EXTENSION_UNIT:
2489         /*   UAC2_PROCESSING_UNIT_V2 has the same value */
2490                 if (state->mixer->protocol == UAC_VERSION_1)
2491                         return parse_audio_extension_unit(state, unitid, p1);
2492                 else /* UAC_VERSION_2 */
2493                         return parse_audio_processing_unit(state, unitid, p1);
2494         case UAC2_EXTENSION_UNIT_V2:
2495                 return parse_audio_extension_unit(state, unitid, p1);
2496         default:
2497                 usb_audio_err(state->chip,
2498                         "unit %u: unexpected type 0x%02x\n", unitid, p1[2]);
2499                 return -EINVAL;
2500         }
2501 }
2502
2503 static void snd_usb_mixer_free(struct usb_mixer_interface *mixer)
2504 {
2505         /* kill pending URBs */
2506         snd_usb_mixer_disconnect(mixer);
2507
2508         kfree(mixer->id_elems);
2509         if (mixer->urb) {
2510                 kfree(mixer->urb->transfer_buffer);
2511                 usb_free_urb(mixer->urb);
2512         }
2513         usb_free_urb(mixer->rc_urb);
2514         kfree(mixer->rc_setup_packet);
2515         kfree(mixer);
2516 }
2517
2518 static int snd_usb_mixer_dev_free(struct snd_device *device)
2519 {
2520         struct usb_mixer_interface *mixer = device->device_data;
2521         snd_usb_mixer_free(mixer);
2522         return 0;
2523 }
2524
2525 static int make_out_term(struct mixer_build state, int wTerminalType)
2526 {
2527         struct uac3_output_terminal_descriptor *desc = NULL;
2528
2529         if (wTerminalType == UAC_TERMINAL_STREAMING)
2530                 desc = &badd_baif_out_term_desc;
2531         else {
2532                 desc = &badd_baof_out_term_desc;
2533                 desc->wTerminalType = wTerminalType;
2534         }
2535         set_bit(desc->bTerminalID, state.unitbitmap);
2536         state.oterm.id = desc->bTerminalID;
2537         state.oterm.type = desc->wTerminalType;
2538         state.oterm.name = desc->wTerminalDescrStr;
2539         return parse_audio_unit(&state, desc->bSourceID);
2540 }
2541
2542 /*
2543  * create mixer controls
2544  *
2545  * walk through all UAC_OUTPUT_TERMINAL descriptors to search for mixers
2546  */
2547 static int snd_usb_mixer_controls(struct usb_mixer_interface *mixer)
2548 {
2549         struct mixer_build state;
2550         int err = -EINVAL;
2551         const struct usbmix_ctl_map *map;
2552
2553         memset(&state, 0, sizeof(state));
2554         state.chip = mixer->chip;
2555         state.mixer = mixer;
2556         state.buffer = mixer->hostif->extra;
2557         state.buflen = mixer->hostif->extralen;
2558
2559         /* check the mapping table */
2560         for (map = usbmix_ctl_maps; map->id; map++) {
2561                 if (map->id == state.chip->usb_id) {
2562                         state.map = map->map;
2563                         state.selector_map = map->selector_map;
2564                         mixer->ignore_ctl_error = map->ignore_ctl_error;
2565                         break;
2566                 }
2567         }
2568
2569         if (mixer->protocol == UAC_VERSION_3) {
2570                 struct usb_interface *usb_iface =
2571                         usb_ifnum_to_if(mixer->chip->dev,
2572                         get_iface_desc(mixer->hostif)->bInterfaceNumber);
2573                 struct usb_interface_assoc_descriptor *assoc =
2574                         usb_iface->intf_assoc;
2575
2576                 switch (assoc->bFunctionSubClass) {
2577                 case PROF_GENERIC_IO: {
2578                         if (assoc->bInterfaceCount == 0x02) {
2579                                 if (get_endpoint(mixer->hostif,
2580                                         0)->bEndpointAddress | USB_DIR_IN)
2581                                         err = make_out_term(state,
2582                                                         UAC_TERMINAL_STREAMING);
2583                                 else
2584                                         err = make_out_term(state,
2585                                                 UAC_OUTPUT_TERMINAL_UNDEFINED);
2586                         } else {
2587                                 err = make_out_term(state,
2588                                                 UAC_OUTPUT_TERMINAL_UNDEFINED);
2589                                 if (err < 0 && err != -EINVAL)
2590                                         return err;
2591                                 err = make_out_term(state,
2592                                                 UAC_TERMINAL_STREAMING);
2593                         }
2594                         break;
2595                 }
2596
2597                 case PROF_HEADPHONE:
2598                         err = make_out_term(state,
2599                                         UAC_OUTPUT_TERMINAL_HEADPHONES);
2600                         break;
2601                 case PROF_SPEAKER:
2602                         err = make_out_term(state, UAC_OUTPUT_TERMINAL_SPEAKER);
2603                         break;
2604                 case PROF_MICROPHONE:
2605                         err = make_out_term(state, UAC_TERMINAL_STREAMING);
2606                         break;
2607                 case PROF_HEADSET:
2608                 case PROF_HEADSET_ADAPTER:
2609                         err = make_out_term(state, UAC_BIDIR_TERMINAL_HEADSET);
2610                         if (err < 0 && err != -EINVAL)
2611                                 return err;
2612                         err = make_out_term(state, UAC_TERMINAL_STREAMING);
2613                         break;
2614                 case PROF_SPEAKERPHONE:
2615                         err = make_out_term(state,
2616                                         UAC_BIDIR_TERMINAL_SPEAKERPHONE);
2617                         if (err < 0 && err != -EINVAL)
2618                                 return err;
2619                         err = make_out_term(state, UAC_TERMINAL_STREAMING);
2620                         break;
2621                 }
2622                 if (err < 0 && err != -EINVAL)
2623                         return err;
2624         } else {
2625                 void *p;
2626
2627                 p = NULL;
2628                 while ((p = snd_usb_find_csint_desc(mixer->hostif->extra,
2629                                                 mixer->hostif->extralen, p,
2630                                                 UAC_OUTPUT_TERMINAL)) != NULL) {
2631                         if (mixer->protocol == UAC_VERSION_1) {
2632                                 struct uac1_output_terminal_descriptor *desc =
2633                                                                               p;
2634
2635                                 if (desc->bLength < sizeof(*desc))
2636                                         continue; /* invalid descriptor? */
2637                                 /* mark terminal ID as visited */
2638                                 set_bit(desc->bTerminalID, state.unitbitmap);
2639                                 state.oterm.id = desc->bTerminalID;
2640                                 state.oterm.type =
2641                                         le16_to_cpu(desc->wTerminalType);
2642                                 state.oterm.name = desc->iTerminal;
2643                                 err = parse_audio_unit(&state, desc->bSourceID);
2644                                 if (err < 0 && err != -EINVAL)
2645                                         return err;
2646                         } else { /* UAC_VERSION_2 */
2647                                 struct uac2_output_terminal_descriptor *desc =
2648                                                                               p;
2649
2650                                 if (desc->bLength < sizeof(*desc))
2651                                         continue; /* invalid descriptor? */
2652                                 /* mark terminal ID as visited */
2653                                 set_bit(desc->bTerminalID, state.unitbitmap);
2654                                 state.oterm.id = desc->bTerminalID;
2655                                 state.oterm.type =
2656                                         le16_to_cpu(desc->wTerminalType);
2657                                 state.oterm.name = desc->iTerminal;
2658                                 err = parse_audio_unit(&state, desc->bSourceID);
2659                                 if (err < 0 && err != -EINVAL)
2660                                         return err;
2661
2662                                 /*
2663                                  * For UAC2, use the same approach to also add
2664                                  * the clock selectors
2665                                  */
2666                                 err = parse_audio_unit(&state,
2667                                                         desc->bCSourceID);
2668                                 if (err < 0 && err != -EINVAL)
2669                                         return err;
2670                         }
2671                 }
2672         }
2673
2674         return 0;
2675 }
2676
2677 void snd_usb_mixer_notify_id(struct usb_mixer_interface *mixer, int unitid)
2678 {
2679         struct usb_mixer_elem_list *list;
2680
2681         for (list = mixer->id_elems[unitid]; list; list = list->next_id_elem)
2682                 snd_ctl_notify(mixer->chip->card, SNDRV_CTL_EVENT_MASK_VALUE,
2683                                &list->kctl->id);
2684 }
2685
2686 static void snd_usb_mixer_dump_cval(struct snd_info_buffer *buffer,
2687                                     struct usb_mixer_elem_list *list)
2688 {
2689         struct usb_mixer_elem_info *cval = (struct usb_mixer_elem_info *)list;
2690         static char *val_types[] = {"BOOLEAN", "INV_BOOLEAN",
2691                                     "S8", "U8", "S16", "U16"};
2692         snd_iprintf(buffer, "    Info: id=%i, control=%i, cmask=0x%x, "
2693                             "channels=%i, type=\"%s\"\n", cval->head.id,
2694                             cval->control, cval->cmask, cval->channels,
2695                             val_types[cval->val_type]);
2696         snd_iprintf(buffer, "    Volume: min=%i, max=%i, dBmin=%i, dBmax=%i\n",
2697                             cval->min, cval->max, cval->dBmin, cval->dBmax);
2698 }
2699
2700 static void snd_usb_mixer_proc_read(struct snd_info_entry *entry,
2701                                     struct snd_info_buffer *buffer)
2702 {
2703         struct snd_usb_audio *chip = entry->private_data;
2704         struct usb_mixer_interface *mixer;
2705         struct usb_mixer_elem_list *list;
2706         int unitid;
2707
2708         list_for_each_entry(mixer, &chip->mixer_list, list) {
2709                 snd_iprintf(buffer,
2710                         "USB Mixer: usb_id=0x%08x, ctrlif=%i, ctlerr=%i\n",
2711                                 chip->usb_id, snd_usb_ctrl_intf(chip),
2712                                 mixer->ignore_ctl_error);
2713                 snd_iprintf(buffer, "Card: %s\n", chip->card->longname);
2714                 for (unitid = 0; unitid < MAX_ID_ELEMS; unitid++) {
2715                         for (list = mixer->id_elems[unitid]; list;
2716                              list = list->next_id_elem) {
2717                                 snd_iprintf(buffer, "  Unit: %i\n", list->id);
2718                                 if (list->kctl)
2719                                         snd_iprintf(buffer,
2720                                                     "    Control: name=\"%s\", index=%i\n",
2721                                                     list->kctl->id.name,
2722                                                     list->kctl->id.index);
2723                                 if (list->dump)
2724                                         list->dump(buffer, list);
2725                         }
2726                 }
2727         }
2728 }
2729
2730 static void snd_usb_mixer_interrupt_v2(struct usb_mixer_interface *mixer,
2731                                        int attribute, int value, int index)
2732 {
2733         struct usb_mixer_elem_list *list;
2734         __u8 unitid = (index >> 8) & 0xff;
2735         __u8 control = (value >> 8) & 0xff;
2736         __u8 channel = value & 0xff;
2737
2738         if (channel >= MAX_CHANNELS) {
2739                 usb_audio_dbg(mixer->chip,
2740                         "%s(): bogus channel number %d\n",
2741                         __func__, channel);
2742                 return;
2743         }
2744
2745         for (list = mixer->id_elems[unitid]; list; list = list->next_id_elem) {
2746                 struct usb_mixer_elem_info *info;
2747
2748                 if (!list->kctl)
2749                         continue;
2750
2751                 info = (struct usb_mixer_elem_info *)list;
2752                 if (info->control != control)
2753                         continue;
2754
2755                 switch (attribute) {
2756                 case UAC2_CS_CUR:
2757                         /* invalidate cache, so the value is read from the device */
2758                         if (channel)
2759                                 info->cached &= ~(1 << channel);
2760                         else /* master channel */
2761                                 info->cached = 0;
2762
2763                         snd_ctl_notify(mixer->chip->card, SNDRV_CTL_EVENT_MASK_VALUE,
2764                                        &info->head.kctl->id);
2765                         break;
2766
2767                 case UAC2_CS_RANGE:
2768                         /* TODO */
2769                         break;
2770
2771                 case UAC2_CS_MEM:
2772                         /* TODO */
2773                         break;
2774
2775                 default:
2776                         usb_audio_dbg(mixer->chip,
2777                                 "unknown attribute %d in interrupt\n",
2778                                 attribute);
2779                         break;
2780                 } /* switch */
2781         }
2782 }
2783
2784 static void snd_usb_mixer_interrupt(struct urb *urb)
2785 {
2786         struct usb_mixer_interface *mixer = urb->context;
2787         int len = urb->actual_length;
2788         int ustatus = urb->status;
2789
2790         if (ustatus != 0)
2791                 goto requeue;
2792
2793         if (mixer->protocol == UAC_VERSION_1) {
2794                 struct uac1_status_word *status;
2795
2796                 for (status = urb->transfer_buffer;
2797                      len >= sizeof(*status);
2798                      len -= sizeof(*status), status++) {
2799                         dev_dbg(&urb->dev->dev, "status interrupt: %02x %02x\n",
2800                                                 status->bStatusType,
2801                                                 status->bOriginator);
2802
2803                         /* ignore any notifications not from the control interface */
2804                         if ((status->bStatusType & UAC1_STATUS_TYPE_ORIG_MASK) !=
2805                                 UAC1_STATUS_TYPE_ORIG_AUDIO_CONTROL_IF)
2806                                 continue;
2807
2808                         if (status->bStatusType & UAC1_STATUS_TYPE_MEM_CHANGED)
2809                                 snd_usb_mixer_rc_memory_change(mixer, status->bOriginator);
2810                         else
2811                                 snd_usb_mixer_notify_id(mixer, status->bOriginator);
2812                 }
2813         } else { /* UAC_VERSION_2 */
2814                 struct uac2_interrupt_data_msg *msg;
2815
2816                 for (msg = urb->transfer_buffer;
2817                      len >= sizeof(*msg);
2818                      len -= sizeof(*msg), msg++) {
2819                         /* drop vendor specific and endpoint requests */
2820                         if ((msg->bInfo & UAC2_INTERRUPT_DATA_MSG_VENDOR) ||
2821                             (msg->bInfo & UAC2_INTERRUPT_DATA_MSG_EP))
2822                                 continue;
2823
2824                         snd_usb_mixer_interrupt_v2(mixer, msg->bAttribute,
2825                                                    le16_to_cpu(msg->wValue),
2826                                                    le16_to_cpu(msg->wIndex));
2827                 }
2828         }
2829
2830 requeue:
2831         if (ustatus != -ENOENT &&
2832             ustatus != -ECONNRESET &&
2833             ustatus != -ESHUTDOWN) {
2834                 urb->dev = mixer->chip->dev;
2835                 usb_submit_urb(urb, GFP_ATOMIC);
2836         }
2837 }
2838
2839 /* create the handler for the optional status interrupt endpoint */
2840 static int snd_usb_mixer_status_create(struct usb_mixer_interface *mixer)
2841 {
2842         struct usb_endpoint_descriptor *ep;
2843         void *transfer_buffer;
2844         int buffer_length;
2845         unsigned int epnum;
2846
2847         /* we need one interrupt input endpoint */
2848         if (get_iface_desc(mixer->hostif)->bNumEndpoints < 1)
2849                 return 0;
2850         ep = get_endpoint(mixer->hostif, 0);
2851         if (!usb_endpoint_dir_in(ep) || !usb_endpoint_xfer_int(ep))
2852                 return 0;
2853
2854         epnum = usb_endpoint_num(ep);
2855         buffer_length = le16_to_cpu(ep->wMaxPacketSize);
2856         transfer_buffer = kmalloc(buffer_length, GFP_KERNEL);
2857         if (!transfer_buffer)
2858                 return -ENOMEM;
2859         mixer->urb = usb_alloc_urb(0, GFP_KERNEL);
2860         if (!mixer->urb) {
2861                 kfree(transfer_buffer);
2862                 return -ENOMEM;
2863         }
2864         usb_fill_int_urb(mixer->urb, mixer->chip->dev,
2865                          usb_rcvintpipe(mixer->chip->dev, epnum),
2866                          transfer_buffer, buffer_length,
2867                          snd_usb_mixer_interrupt, mixer, ep->bInterval);
2868         usb_submit_urb(mixer->urb, GFP_KERNEL);
2869         return 0;
2870 }
2871
2872 int snd_usb_create_mixer(struct snd_usb_audio *chip, int ctrlif,
2873                          int ignore_error)
2874 {
2875         static struct snd_device_ops dev_ops = {
2876                 .dev_free = snd_usb_mixer_dev_free
2877         };
2878         struct usb_mixer_interface *mixer;
2879         struct snd_info_entry *entry;
2880         int err;
2881
2882         strcpy(chip->card->mixername, "USB Mixer");
2883
2884         mixer = kzalloc(sizeof(*mixer), GFP_KERNEL);
2885         if (!mixer)
2886                 return -ENOMEM;
2887         mixer->chip = chip;
2888         mixer->ignore_ctl_error = ignore_error;
2889         mixer->id_elems = kcalloc(MAX_ID_ELEMS, sizeof(*mixer->id_elems),
2890                                   GFP_KERNEL);
2891         if (!mixer->id_elems) {
2892                 kfree(mixer);
2893                 return -ENOMEM;
2894         }
2895
2896         mixer->hostif = &usb_ifnum_to_if(chip->dev, ctrlif)->altsetting[0];
2897         switch (get_iface_desc(mixer->hostif)->bInterfaceProtocol) {
2898         case UAC_VERSION_1:
2899         default:
2900                 mixer->protocol = UAC_VERSION_1;
2901                 break;
2902         case UAC_VERSION_2:
2903                 mixer->protocol = UAC_VERSION_2;
2904                 break;
2905         case UAC_VERSION_3:
2906                 mixer->protocol = UAC_VERSION_3;
2907                 break;
2908         }
2909
2910         if ((err = snd_usb_mixer_controls(mixer)) < 0 ||
2911             (err = snd_usb_mixer_status_create(mixer)) < 0)
2912                 goto _error;
2913
2914         snd_usb_mixer_apply_create_quirk(mixer);
2915
2916         err = snd_device_new(chip->card, SNDRV_DEV_CODEC, mixer, &dev_ops);
2917         if (err < 0)
2918                 goto _error;
2919
2920         if (list_empty(&chip->mixer_list) &&
2921             !snd_card_proc_new(chip->card, "usbmixer", &entry))
2922                 snd_info_set_text_ops(entry, chip, snd_usb_mixer_proc_read);
2923
2924         list_add(&mixer->list, &chip->mixer_list);
2925         return 0;
2926
2927 _error:
2928         snd_usb_mixer_free(mixer);
2929         return err;
2930 }
2931
2932 void snd_usb_mixer_disconnect(struct usb_mixer_interface *mixer)
2933 {
2934         if (mixer->disconnected)
2935                 return;
2936         if (mixer->urb)
2937                 usb_kill_urb(mixer->urb);
2938         if (mixer->rc_urb)
2939                 usb_kill_urb(mixer->rc_urb);
2940         mixer->disconnected = true;
2941 }
2942
2943 #ifdef CONFIG_PM
2944 /* stop any bus activity of a mixer */
2945 static void snd_usb_mixer_inactivate(struct usb_mixer_interface *mixer)
2946 {
2947         usb_kill_urb(mixer->urb);
2948         usb_kill_urb(mixer->rc_urb);
2949 }
2950
2951 static int snd_usb_mixer_activate(struct usb_mixer_interface *mixer)
2952 {
2953         int err;
2954
2955         if (mixer->urb) {
2956                 err = usb_submit_urb(mixer->urb, GFP_NOIO);
2957                 if (err < 0)
2958                         return err;
2959         }
2960
2961         return 0;
2962 }
2963
2964 int snd_usb_mixer_suspend(struct usb_mixer_interface *mixer)
2965 {
2966         snd_usb_mixer_inactivate(mixer);
2967         return 0;
2968 }
2969
2970 static int restore_mixer_value(struct usb_mixer_elem_list *list)
2971 {
2972         struct usb_mixer_elem_info *cval = (struct usb_mixer_elem_info *)list;
2973         int c, err, idx;
2974
2975         if (cval->cmask) {
2976                 idx = 0;
2977                 for (c = 0; c < MAX_CHANNELS; c++) {
2978                         if (!(cval->cmask & (1 << c)))
2979                                 continue;
2980                         if (cval->cached & (1 << (c + 1))) {
2981                                 err = snd_usb_set_cur_mix_value(cval, c + 1, idx,
2982                                                         cval->cache_val[idx]);
2983                                 if (err < 0)
2984                                         return err;
2985                         }
2986                         idx++;
2987                 }
2988         } else {
2989                 /* master */
2990                 if (cval->cached) {
2991                         err = snd_usb_set_cur_mix_value(cval, 0, 0, *cval->cache_val);
2992                         if (err < 0)
2993                                 return err;
2994                 }
2995         }
2996
2997         return 0;
2998 }
2999
3000 int snd_usb_mixer_resume(struct usb_mixer_interface *mixer, bool reset_resume)
3001 {
3002         struct usb_mixer_elem_list *list;
3003         int id, err;
3004
3005         if (reset_resume) {
3006                 /* restore cached mixer values */
3007                 for (id = 0; id < MAX_ID_ELEMS; id++) {
3008                         for (list = mixer->id_elems[id]; list;
3009                              list = list->next_id_elem) {
3010                                 if (list->resume) {
3011                                         err = list->resume(list);
3012                                         if (err < 0)
3013                                                 return err;
3014                                 }
3015                         }
3016                 }
3017         }
3018
3019         return snd_usb_mixer_activate(mixer);
3020 }
3021 #endif
3022
3023 void snd_usb_mixer_elem_init_std(struct usb_mixer_elem_list *list,
3024                                  struct usb_mixer_interface *mixer,
3025                                  int unitid)
3026 {
3027         list->mixer = mixer;
3028         list->id = unitid;
3029         list->dump = snd_usb_mixer_dump_cval;
3030 #ifdef CONFIG_PM
3031         list->resume = restore_mixer_value;
3032 #endif
3033 }