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