ALSA: usb-audio: Fix races at disconnection
[pandora-kernel.git] / sound / usb / mixer.c
1 /*
2  *   (Tentative) USB Audio Driver for ALSA
3  *
4  *   Mixer control part
5  *
6  *   Copyright (c) 2002 by Takashi Iwai <tiwai@suse.de>
7  *
8  *   Many codes borrowed from audio.c by
9  *          Alan Cox (alan@lxorguk.ukuu.org.uk)
10  *          Thomas Sailer (sailer@ife.ee.ethz.ch)
11  *
12  *
13  *   This program is free software; you can redistribute it and/or modify
14  *   it under the terms of the GNU General Public License as published by
15  *   the Free Software Foundation; either version 2 of the License, or
16  *   (at your option) any later version.
17  *
18  *   This program is distributed in the hope that it will be useful,
19  *   but WITHOUT ANY WARRANTY; without even the implied warranty of
20  *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
21  *   GNU General Public License for more details.
22  *
23  *   You should have received a copy of the GNU General Public License
24  *   along with this program; if not, write to the Free Software
25  *   Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307 USA
26  *
27  */
28
29 /*
30  * TODOs, for both the mixer and the streaming interfaces:
31  *
32  *  - support for UAC2 effect units
33  *  - support for graphical equalizers
34  *  - RANGE and MEM set commands (UAC2)
35  *  - RANGE and MEM interrupt dispatchers (UAC2)
36  *  - audio channel clustering (UAC2)
37  *  - audio sample rate converter units (UAC2)
38  *  - proper handling of clock multipliers (UAC2)
39  *  - dispatch clock change notifications (UAC2)
40  *      - stop PCM streams which use a clock that became invalid
41  *      - stop PCM streams which use a clock selector that has changed
42  *      - parse available sample rates again when clock sources changed
43  */
44
45 #include <linux/bitops.h>
46 #include <linux/init.h>
47 #include <linux/list.h>
48 #include <linux/slab.h>
49 #include <linux/string.h>
50 #include <linux/usb.h>
51 #include <linux/usb/audio.h>
52 #include <linux/usb/audio-v2.h>
53
54 #include <sound/core.h>
55 #include <sound/control.h>
56 #include <sound/hwdep.h>
57 #include <sound/info.h>
58 #include <sound/tlv.h>
59
60 #include "usbaudio.h"
61 #include "mixer.h"
62 #include "helper.h"
63 #include "mixer_quirks.h"
64 #include "power.h"
65
66 #define MAX_ID_ELEMS    256
67
68 struct usb_audio_term {
69         int id;
70         int type;
71         int channels;
72         unsigned int chconfig;
73         int name;
74 };
75
76 struct usbmix_name_map;
77
78 struct mixer_build {
79         struct snd_usb_audio *chip;
80         struct usb_mixer_interface *mixer;
81         unsigned char *buffer;
82         unsigned int buflen;
83         DECLARE_BITMAP(unitbitmap, MAX_ID_ELEMS);
84         struct usb_audio_term oterm;
85         const struct usbmix_name_map *map;
86         const struct usbmix_selector_map *selector_map;
87 };
88
89 /*E-mu 0202/0404/0204 eXtension Unit(XU) control*/
90 enum {
91         USB_XU_CLOCK_RATE               = 0xe301,
92         USB_XU_CLOCK_SOURCE             = 0xe302,
93         USB_XU_DIGITAL_IO_STATUS        = 0xe303,
94         USB_XU_DEVICE_OPTIONS           = 0xe304,
95         USB_XU_DIRECT_MONITORING        = 0xe305,
96         USB_XU_METERING                 = 0xe306
97 };
98 enum {
99         USB_XU_CLOCK_SOURCE_SELECTOR = 0x02,    /* clock source*/
100         USB_XU_CLOCK_RATE_SELECTOR = 0x03,      /* clock rate */
101         USB_XU_DIGITAL_FORMAT_SELECTOR = 0x01,  /* the spdif format */
102         USB_XU_SOFT_LIMIT_SELECTOR = 0x03       /* soft limiter */
103 };
104
105 /*
106  * manual mapping of mixer names
107  * if the mixer topology is too complicated and the parsed names are
108  * ambiguous, add the entries in usbmixer_maps.c.
109  */
110 #include "mixer_maps.c"
111
112 static const struct usbmix_name_map *
113 find_map(struct mixer_build *state, int unitid, int control)
114 {
115         const struct usbmix_name_map *p = state->map;
116
117         if (!p)
118                 return NULL;
119
120         for (p = state->map; p->id; p++) {
121                 if (p->id == unitid &&
122                     (!control || !p->control || control == p->control))
123                         return p;
124         }
125         return NULL;
126 }
127
128 /* get the mapped name if the unit matches */
129 static int
130 check_mapped_name(const struct usbmix_name_map *p, char *buf, int buflen)
131 {
132         if (!p || !p->name)
133                 return 0;
134
135         buflen--;
136         return strlcpy(buf, p->name, buflen);
137 }
138
139 /* check whether the control should be ignored */
140 static inline int
141 check_ignored_ctl(const struct usbmix_name_map *p)
142 {
143         if (!p || p->name || p->dB)
144                 return 0;
145         return 1;
146 }
147
148 /* dB mapping */
149 static inline void check_mapped_dB(const struct usbmix_name_map *p,
150                                    struct usb_mixer_elem_info *cval)
151 {
152         if (p && p->dB) {
153                 cval->dBmin = p->dB->min;
154                 cval->dBmax = p->dB->max;
155                 cval->initialized = 1;
156         }
157 }
158
159 /* get the mapped selector source name */
160 static int check_mapped_selector_name(struct mixer_build *state, int unitid,
161                                       int index, char *buf, int buflen)
162 {
163         const struct usbmix_selector_map *p;
164
165         if (! state->selector_map)
166                 return 0;
167         for (p = state->selector_map; p->id; p++) {
168                 if (p->id == unitid && index < p->count)
169                         return strlcpy(buf, p->names[index], buflen);
170         }
171         return 0;
172 }
173
174 /*
175  * find an audio control unit with the given unit id
176  */
177 static void *find_audio_control_unit(struct mixer_build *state, unsigned char unit)
178 {
179         /* we just parse the header */
180         struct uac_feature_unit_descriptor *hdr = NULL;
181
182         while ((hdr = snd_usb_find_desc(state->buffer, state->buflen, hdr,
183                                         USB_DT_CS_INTERFACE)) != NULL) {
184                 if (hdr->bLength >= 4 &&
185                     hdr->bDescriptorSubtype >= UAC_INPUT_TERMINAL &&
186                     hdr->bDescriptorSubtype <= UAC2_SAMPLE_RATE_CONVERTER &&
187                     hdr->bUnitID == unit)
188                         return hdr;
189         }
190
191         return NULL;
192 }
193
194 /*
195  * copy a string with the given id
196  */
197 static int snd_usb_copy_string_desc(struct mixer_build *state, int index, char *buf, int maxlen)
198 {
199         int len = usb_string(state->chip->dev, index, buf, maxlen - 1);
200         buf[len] = 0;
201         return len;
202 }
203
204 /*
205  * convert from the byte/word on usb descriptor to the zero-based integer
206  */
207 static int convert_signed_value(struct usb_mixer_elem_info *cval, int val)
208 {
209         switch (cval->val_type) {
210         case USB_MIXER_BOOLEAN:
211                 return !!val;
212         case USB_MIXER_INV_BOOLEAN:
213                 return !val;
214         case USB_MIXER_U8:
215                 val &= 0xff;
216                 break;
217         case USB_MIXER_S8:
218                 val &= 0xff;
219                 if (val >= 0x80)
220                         val -= 0x100;
221                 break;
222         case USB_MIXER_U16:
223                 val &= 0xffff;
224                 break;
225         case USB_MIXER_S16:
226                 val &= 0xffff;
227                 if (val >= 0x8000)
228                         val -= 0x10000;
229                 break;
230         }
231         return val;
232 }
233
234 /*
235  * convert from the zero-based int to the byte/word for usb descriptor
236  */
237 static int convert_bytes_value(struct usb_mixer_elem_info *cval, int val)
238 {
239         switch (cval->val_type) {
240         case USB_MIXER_BOOLEAN:
241                 return !!val;
242         case USB_MIXER_INV_BOOLEAN:
243                 return !val;
244         case USB_MIXER_S8:
245         case USB_MIXER_U8:
246                 return val & 0xff;
247         case USB_MIXER_S16:
248         case USB_MIXER_U16:
249                 return val & 0xffff;
250         }
251         return 0; /* not reached */
252 }
253
254 static int get_relative_value(struct usb_mixer_elem_info *cval, int val)
255 {
256         if (! cval->res)
257                 cval->res = 1;
258         if (val < cval->min)
259                 return 0;
260         else if (val >= cval->max)
261                 return (cval->max - cval->min + cval->res - 1) / cval->res;
262         else
263                 return (val - cval->min) / cval->res;
264 }
265
266 static int get_abs_value(struct usb_mixer_elem_info *cval, int val)
267 {
268         if (val < 0)
269                 return cval->min;
270         if (! cval->res)
271                 cval->res = 1;
272         val *= cval->res;
273         val += cval->min;
274         if (val > cval->max)
275                 return cval->max;
276         return val;
277 }
278
279
280 /*
281  * retrieve a mixer value
282  */
283
284 static int get_ctl_value_v1(struct usb_mixer_elem_info *cval, int request, int validx, int *value_ret)
285 {
286         struct snd_usb_audio *chip = cval->mixer->chip;
287         unsigned char buf[2];
288         int val_len = cval->val_type >= USB_MIXER_S16 ? 2 : 1;
289         int timeout = 10;
290         int idx = 0, err;
291
292         err = snd_usb_autoresume(cval->mixer->chip);
293         if (err < 0)
294                 return -EIO;
295         mutex_lock(&chip->shutdown_mutex);
296         while (timeout-- > 0) {
297                 if (chip->shutdown)
298                         break;
299                 idx = snd_usb_ctrl_intf(chip) | (cval->id << 8);
300                 if (snd_usb_ctl_msg(chip->dev, usb_rcvctrlpipe(chip->dev, 0), request,
301                                     USB_RECIP_INTERFACE | USB_TYPE_CLASS | USB_DIR_IN,
302                                     validx, idx, buf, val_len) >= val_len) {
303                         *value_ret = convert_signed_value(cval, snd_usb_combine_bytes(buf, val_len));
304                         err = 0;
305                         goto out;
306                 }
307         }
308         snd_printdd(KERN_ERR "cannot get ctl value: req = %#x, wValue = %#x, wIndex = %#x, type = %d\n",
309                     request, validx, idx, cval->val_type);
310         err = -EINVAL;
311
312  out:
313         mutex_unlock(&chip->shutdown_mutex);
314         snd_usb_autosuspend(cval->mixer->chip);
315         return err;
316 }
317
318 static int get_ctl_value_v2(struct usb_mixer_elem_info *cval, int request, int validx, int *value_ret)
319 {
320         struct snd_usb_audio *chip = cval->mixer->chip;
321         unsigned char buf[2 + 3*sizeof(__u16)]; /* enough space for one range */
322         unsigned char *val;
323         int idx = 0, ret, size;
324         __u8 bRequest;
325
326         if (request == UAC_GET_CUR) {
327                 bRequest = UAC2_CS_CUR;
328                 size = sizeof(__u16);
329         } else {
330                 bRequest = UAC2_CS_RANGE;
331                 size = sizeof(buf);
332         }
333
334         memset(buf, 0, sizeof(buf));
335
336         ret = snd_usb_autoresume(chip) ? -EIO : 0;
337         if (ret)
338                 goto error;
339
340         mutex_lock(&chip->shutdown_mutex);
341         if (chip->shutdown)
342                 ret = -ENODEV;
343         else {
344                 idx = snd_usb_ctrl_intf(chip) | (cval->id << 8);
345                 ret = snd_usb_ctl_msg(chip->dev, usb_rcvctrlpipe(chip->dev, 0), bRequest,
346                               USB_RECIP_INTERFACE | USB_TYPE_CLASS | USB_DIR_IN,
347                               validx, idx, buf, size);
348         }
349         mutex_unlock(&chip->shutdown_mutex);
350         snd_usb_autosuspend(chip);
351
352         if (ret < 0) {
353 error:
354                 snd_printk(KERN_ERR "cannot get ctl value: req = %#x, wValue = %#x, wIndex = %#x, type = %d\n",
355                            request, validx, idx, cval->val_type);
356                 return ret;
357         }
358
359         /* FIXME: how should we handle multiple triplets here? */
360
361         switch (request) {
362         case UAC_GET_CUR:
363                 val = buf;
364                 break;
365         case UAC_GET_MIN:
366                 val = buf + sizeof(__u16);
367                 break;
368         case UAC_GET_MAX:
369                 val = buf + sizeof(__u16) * 2;
370                 break;
371         case UAC_GET_RES:
372                 val = buf + sizeof(__u16) * 3;
373                 break;
374         default:
375                 return -EINVAL;
376         }
377
378         *value_ret = convert_signed_value(cval, snd_usb_combine_bytes(val, sizeof(__u16)));
379
380         return 0;
381 }
382
383 static int get_ctl_value(struct usb_mixer_elem_info *cval, int request, int validx, int *value_ret)
384 {
385         return (cval->mixer->protocol == UAC_VERSION_1) ?
386                 get_ctl_value_v1(cval, request, validx, value_ret) :
387                 get_ctl_value_v2(cval, request, validx, value_ret);
388 }
389
390 static int get_cur_ctl_value(struct usb_mixer_elem_info *cval, int validx, int *value)
391 {
392         return get_ctl_value(cval, UAC_GET_CUR, validx, value);
393 }
394
395 /* channel = 0: master, 1 = first channel */
396 static inline int get_cur_mix_raw(struct usb_mixer_elem_info *cval,
397                                   int channel, int *value)
398 {
399         return get_ctl_value(cval, UAC_GET_CUR, (cval->control << 8) | channel, value);
400 }
401
402 static int get_cur_mix_value(struct usb_mixer_elem_info *cval,
403                              int channel, int index, int *value)
404 {
405         int err;
406
407         if (cval->cached & (1 << channel)) {
408                 *value = cval->cache_val[index];
409                 return 0;
410         }
411         err = get_cur_mix_raw(cval, channel, value);
412         if (err < 0) {
413                 if (!cval->mixer->ignore_ctl_error)
414                         snd_printd(KERN_ERR "cannot get current value for control %d ch %d: err = %d\n",
415                                    cval->control, channel, err);
416                 return err;
417         }
418         cval->cached |= 1 << channel;
419         cval->cache_val[index] = *value;
420         return 0;
421 }
422
423
424 /*
425  * set a mixer value
426  */
427
428 int snd_usb_mixer_set_ctl_value(struct usb_mixer_elem_info *cval,
429                                 int request, int validx, int value_set)
430 {
431         struct snd_usb_audio *chip = cval->mixer->chip;
432         unsigned char buf[2];
433         int idx = 0, val_len, err, timeout = 10;
434
435         if (cval->mixer->protocol == UAC_VERSION_1) {
436                 val_len = cval->val_type >= USB_MIXER_S16 ? 2 : 1;
437         } else { /* UAC_VERSION_2 */
438                 /* audio class v2 controls are always 2 bytes in size */
439                 val_len = sizeof(__u16);
440
441                 /* FIXME */
442                 if (request != UAC_SET_CUR) {
443                         snd_printdd(KERN_WARNING "RANGE setting not yet supported\n");
444                         return -EINVAL;
445                 }
446
447                 request = UAC2_CS_CUR;
448         }
449
450         value_set = convert_bytes_value(cval, value_set);
451         buf[0] = value_set & 0xff;
452         buf[1] = (value_set >> 8) & 0xff;
453         err = snd_usb_autoresume(chip);
454         if (err < 0)
455                 return -EIO;
456         mutex_lock(&chip->shutdown_mutex);
457         while (timeout-- > 0) {
458                 if (chip->shutdown)
459                         break;
460                 idx = snd_usb_ctrl_intf(chip) | (cval->id << 8);
461                 if (snd_usb_ctl_msg(chip->dev,
462                                     usb_sndctrlpipe(chip->dev, 0), request,
463                                     USB_RECIP_INTERFACE | USB_TYPE_CLASS | USB_DIR_OUT,
464                                     validx, idx, buf, val_len) >= 0) {
465                         err = 0;
466                         goto out;
467                 }
468         }
469         snd_printdd(KERN_ERR "cannot set ctl value: req = %#x, wValue = %#x, wIndex = %#x, type = %d, data = %#x/%#x\n",
470                     request, validx, idx, cval->val_type, buf[0], buf[1]);
471         err = -EINVAL;
472
473  out:
474         mutex_unlock(&chip->shutdown_mutex);
475         snd_usb_autosuspend(chip);
476         return err;
477 }
478
479 static int set_cur_ctl_value(struct usb_mixer_elem_info *cval, int validx, int value)
480 {
481         return snd_usb_mixer_set_ctl_value(cval, UAC_SET_CUR, validx, value);
482 }
483
484 static int set_cur_mix_value(struct usb_mixer_elem_info *cval, int channel,
485                              int index, int value)
486 {
487         int err;
488         unsigned int read_only = (channel == 0) ?
489                 cval->master_readonly :
490                 cval->ch_readonly & (1 << (channel - 1));
491
492         if (read_only) {
493                 snd_printdd(KERN_INFO "%s(): channel %d of control %d is read_only\n",
494                             __func__, channel, cval->control);
495                 return 0;
496         }
497
498         err = snd_usb_mixer_set_ctl_value(cval, UAC_SET_CUR, (cval->control << 8) | channel,
499                             value);
500         if (err < 0)
501                 return err;
502         cval->cached |= 1 << channel;
503         cval->cache_val[index] = value;
504         return 0;
505 }
506
507 /*
508  * TLV callback for mixer volume controls
509  */
510 static int mixer_vol_tlv(struct snd_kcontrol *kcontrol, int op_flag,
511                          unsigned int size, unsigned int __user *_tlv)
512 {
513         struct usb_mixer_elem_info *cval = kcontrol->private_data;
514         DECLARE_TLV_DB_MINMAX(scale, 0, 0);
515
516         if (size < sizeof(scale))
517                 return -ENOMEM;
518         scale[2] = cval->dBmin;
519         scale[3] = cval->dBmax;
520         if (copy_to_user(_tlv, scale, sizeof(scale)))
521                 return -EFAULT;
522         return 0;
523 }
524
525 /*
526  * parser routines begin here...
527  */
528
529 static int parse_audio_unit(struct mixer_build *state, int unitid);
530
531
532 /*
533  * check if the input/output channel routing is enabled on the given bitmap.
534  * used for mixer unit parser
535  */
536 static int check_matrix_bitmap(unsigned char *bmap, int ich, int och, int num_outs)
537 {
538         int idx = ich * num_outs + och;
539         return bmap[idx >> 3] & (0x80 >> (idx & 7));
540 }
541
542
543 /*
544  * add an alsa control element
545  * search and increment the index until an empty slot is found.
546  *
547  * if failed, give up and free the control instance.
548  */
549
550 int snd_usb_mixer_add_control(struct usb_mixer_interface *mixer,
551                               struct snd_kcontrol *kctl)
552 {
553         struct usb_mixer_elem_info *cval = kctl->private_data;
554         int err;
555
556         while (snd_ctl_find_id(mixer->chip->card, &kctl->id))
557                 kctl->id.index++;
558         if ((err = snd_ctl_add(mixer->chip->card, kctl)) < 0) {
559                 snd_printd(KERN_ERR "cannot add control (err = %d)\n", err);
560                 return err;
561         }
562         cval->elem_id = &kctl->id;
563         cval->next_id_elem = mixer->id_elems[cval->id];
564         mixer->id_elems[cval->id] = cval;
565         return 0;
566 }
567
568
569 /*
570  * get a terminal name string
571  */
572
573 static struct iterm_name_combo {
574         int type;
575         char *name;
576 } iterm_names[] = {
577         { 0x0300, "Output" },
578         { 0x0301, "Speaker" },
579         { 0x0302, "Headphone" },
580         { 0x0303, "HMD Audio" },
581         { 0x0304, "Desktop Speaker" },
582         { 0x0305, "Room Speaker" },
583         { 0x0306, "Com Speaker" },
584         { 0x0307, "LFE" },
585         { 0x0600, "External In" },
586         { 0x0601, "Analog In" },
587         { 0x0602, "Digital In" },
588         { 0x0603, "Line" },
589         { 0x0604, "Legacy In" },
590         { 0x0605, "IEC958 In" },
591         { 0x0606, "1394 DA Stream" },
592         { 0x0607, "1394 DV Stream" },
593         { 0x0700, "Embedded" },
594         { 0x0701, "Noise Source" },
595         { 0x0702, "Equalization Noise" },
596         { 0x0703, "CD" },
597         { 0x0704, "DAT" },
598         { 0x0705, "DCC" },
599         { 0x0706, "MiniDisk" },
600         { 0x0707, "Analog Tape" },
601         { 0x0708, "Phonograph" },
602         { 0x0709, "VCR Audio" },
603         { 0x070a, "Video Disk Audio" },
604         { 0x070b, "DVD Audio" },
605         { 0x070c, "TV Tuner Audio" },
606         { 0x070d, "Satellite Rec Audio" },
607         { 0x070e, "Cable Tuner Audio" },
608         { 0x070f, "DSS Audio" },
609         { 0x0710, "Radio Receiver" },
610         { 0x0711, "Radio Transmitter" },
611         { 0x0712, "Multi-Track Recorder" },
612         { 0x0713, "Synthesizer" },
613         { 0 },
614 };
615
616 static int get_term_name(struct mixer_build *state, struct usb_audio_term *iterm,
617                          unsigned char *name, int maxlen, int term_only)
618 {
619         struct iterm_name_combo *names;
620
621         if (iterm->name)
622                 return snd_usb_copy_string_desc(state, iterm->name, name, maxlen);
623
624         /* virtual type - not a real terminal */
625         if (iterm->type >> 16) {
626                 if (term_only)
627                         return 0;
628                 switch (iterm->type >> 16) {
629                 case UAC_SELECTOR_UNIT:
630                         strcpy(name, "Selector"); return 8;
631                 case UAC1_PROCESSING_UNIT:
632                         strcpy(name, "Process Unit"); return 12;
633                 case UAC1_EXTENSION_UNIT:
634                         strcpy(name, "Ext Unit"); return 8;
635                 case UAC_MIXER_UNIT:
636                         strcpy(name, "Mixer"); return 5;
637                 default:
638                         return sprintf(name, "Unit %d", iterm->id);
639                 }
640         }
641
642         switch (iterm->type & 0xff00) {
643         case 0x0100:
644                 strcpy(name, "PCM"); return 3;
645         case 0x0200:
646                 strcpy(name, "Mic"); return 3;
647         case 0x0400:
648                 strcpy(name, "Headset"); return 7;
649         case 0x0500:
650                 strcpy(name, "Phone"); return 5;
651         }
652
653         for (names = iterm_names; names->type; names++)
654                 if (names->type == iterm->type) {
655                         strcpy(name, names->name);
656                         return strlen(names->name);
657                 }
658         return 0;
659 }
660
661
662 /*
663  * parse the source unit recursively until it reaches to a terminal
664  * or a branched unit.
665  */
666 static int check_input_term(struct mixer_build *state, int id, struct usb_audio_term *term)
667 {
668         int err;
669         void *p1;
670
671         memset(term, 0, sizeof(*term));
672         while ((p1 = find_audio_control_unit(state, id)) != NULL) {
673                 unsigned char *hdr = p1;
674                 term->id = id;
675                 switch (hdr[2]) {
676                 case UAC_INPUT_TERMINAL:
677                         if (state->mixer->protocol == UAC_VERSION_1) {
678                                 struct uac_input_terminal_descriptor *d = p1;
679                                 term->type = le16_to_cpu(d->wTerminalType);
680                                 term->channels = d->bNrChannels;
681                                 term->chconfig = le16_to_cpu(d->wChannelConfig);
682                                 term->name = d->iTerminal;
683                         } else { /* UAC_VERSION_2 */
684                                 struct uac2_input_terminal_descriptor *d = p1;
685                                 term->type = le16_to_cpu(d->wTerminalType);
686                                 term->channels = d->bNrChannels;
687                                 term->chconfig = le32_to_cpu(d->bmChannelConfig);
688                                 term->name = d->iTerminal;
689
690                                 /* call recursively to get the clock selectors */
691                                 err = check_input_term(state, d->bCSourceID, term);
692                                 if (err < 0)
693                                         return err;
694                         }
695                         return 0;
696                 case UAC_FEATURE_UNIT: {
697                         /* the header is the same for v1 and v2 */
698                         struct uac_feature_unit_descriptor *d = p1;
699                         id = d->bSourceID;
700                         break; /* continue to parse */
701                 }
702                 case UAC_MIXER_UNIT: {
703                         struct uac_mixer_unit_descriptor *d = p1;
704                         term->type = d->bDescriptorSubtype << 16; /* virtual type */
705                         term->channels = uac_mixer_unit_bNrChannels(d);
706                         term->chconfig = uac_mixer_unit_wChannelConfig(d, state->mixer->protocol);
707                         term->name = uac_mixer_unit_iMixer(d);
708                         return 0;
709                 }
710                 case UAC_SELECTOR_UNIT:
711                 case UAC2_CLOCK_SELECTOR: {
712                         struct uac_selector_unit_descriptor *d = p1;
713                         /* call recursively to retrieve the channel info */
714                         if (check_input_term(state, d->baSourceID[0], term) < 0)
715                                 return -ENODEV;
716                         term->type = d->bDescriptorSubtype << 16; /* virtual type */
717                         term->id = id;
718                         term->name = uac_selector_unit_iSelector(d);
719                         return 0;
720                 }
721                 case UAC1_PROCESSING_UNIT:
722                 case UAC1_EXTENSION_UNIT: {
723                         struct uac_processing_unit_descriptor *d = p1;
724                         if (d->bNrInPins) {
725                                 id = d->baSourceID[0];
726                                 break; /* continue to parse */
727                         }
728                         term->type = d->bDescriptorSubtype << 16; /* virtual type */
729                         term->channels = uac_processing_unit_bNrChannels(d);
730                         term->chconfig = uac_processing_unit_wChannelConfig(d, state->mixer->protocol);
731                         term->name = uac_processing_unit_iProcessing(d, state->mixer->protocol);
732                         return 0;
733                 }
734                 case UAC2_CLOCK_SOURCE: {
735                         struct uac_clock_source_descriptor *d = p1;
736                         term->type = d->bDescriptorSubtype << 16; /* virtual type */
737                         term->id = id;
738                         term->name = d->iClockSource;
739                         return 0;
740                 }
741                 default:
742                         return -ENODEV;
743                 }
744         }
745         return -ENODEV;
746 }
747
748
749 /*
750  * Feature Unit
751  */
752
753 /* feature unit control information */
754 struct usb_feature_control_info {
755         const char *name;
756         unsigned int type;      /* control type (mute, volume, etc.) */
757 };
758
759 static struct usb_feature_control_info audio_feature_info[] = {
760         { "Mute",                       USB_MIXER_INV_BOOLEAN },
761         { "Volume",                     USB_MIXER_S16 },
762         { "Tone Control - Bass",        USB_MIXER_S8 },
763         { "Tone Control - Mid",         USB_MIXER_S8 },
764         { "Tone Control - Treble",      USB_MIXER_S8 },
765         { "Graphic Equalizer",          USB_MIXER_S8 }, /* FIXME: not implemeted yet */
766         { "Auto Gain Control",          USB_MIXER_BOOLEAN },
767         { "Delay Control",              USB_MIXER_U16 },
768         { "Bass Boost",                 USB_MIXER_BOOLEAN },
769         { "Loudness",                   USB_MIXER_BOOLEAN },
770         /* UAC2 specific */
771         { "Input Gain Control",         USB_MIXER_U16 },
772         { "Input Gain Pad Control",     USB_MIXER_BOOLEAN },
773         { "Phase Inverter Control",     USB_MIXER_BOOLEAN },
774 };
775
776
777 /* private_free callback */
778 static void usb_mixer_elem_free(struct snd_kcontrol *kctl)
779 {
780         kfree(kctl->private_data);
781         kctl->private_data = NULL;
782 }
783
784
785 /*
786  * interface to ALSA control for feature/mixer units
787  */
788
789 /* volume control quirks */
790 static void volume_control_quirks(struct usb_mixer_elem_info *cval,
791                                   struct snd_kcontrol *kctl)
792 {
793         switch (cval->mixer->chip->usb_id) {
794         case USB_ID(0x0471, 0x0101):
795         case USB_ID(0x0471, 0x0104):
796         case USB_ID(0x0471, 0x0105):
797         case USB_ID(0x0672, 0x1041):
798         /* quirk for UDA1321/N101.
799          * note that detection between firmware 2.1.1.7 (N101)
800          * and later 2.1.1.21 is not very clear from datasheets.
801          * I hope that the min value is -15360 for newer firmware --jk
802          */
803                 if (!strcmp(kctl->id.name, "PCM Playback Volume") &&
804                     cval->min == -15616) {
805                         snd_printk(KERN_INFO
806                                  "set volume quirk for UDA1321/N101 chip\n");
807                         cval->max = -256;
808                 }
809                 break;
810
811         case USB_ID(0x046d, 0x09a4):
812                 if (!strcmp(kctl->id.name, "Mic Capture Volume")) {
813                         snd_printk(KERN_INFO
814                                 "set volume quirk for QuickCam E3500\n");
815                         cval->min = 6080;
816                         cval->max = 8768;
817                         cval->res = 192;
818                 }
819                 break;
820
821         case USB_ID(0x046d, 0x0808):
822         case USB_ID(0x046d, 0x0809):
823         case USB_ID(0x046d, 0x081d): /* HD Webcam c510 */
824         case USB_ID(0x046d, 0x0991):
825         /* Most audio usb devices lie about volume resolution.
826          * Most Logitech webcams have res = 384.
827          * Proboly there is some logitech magic behind this number --fishor
828          */
829                 if (!strcmp(kctl->id.name, "Mic Capture Volume")) {
830                         snd_printk(KERN_INFO
831                                 "set resolution quirk: cval->res = 384\n");
832                         cval->res = 384;
833                 }
834                 break;
835
836         }
837 }
838
839 /*
840  * retrieve the minimum and maximum values for the specified control
841  */
842 static int get_min_max_with_quirks(struct usb_mixer_elem_info *cval,
843                                    int default_min, struct snd_kcontrol *kctl)
844 {
845         /* for failsafe */
846         cval->min = default_min;
847         cval->max = cval->min + 1;
848         cval->res = 1;
849         cval->dBmin = cval->dBmax = 0;
850
851         if (cval->val_type == USB_MIXER_BOOLEAN ||
852             cval->val_type == USB_MIXER_INV_BOOLEAN) {
853                 cval->initialized = 1;
854         } else {
855                 int minchn = 0;
856                 if (cval->cmask) {
857                         int i;
858                         for (i = 0; i < MAX_CHANNELS; i++)
859                                 if (cval->cmask & (1 << i)) {
860                                         minchn = i + 1;
861                                         break;
862                                 }
863                 }
864                 if (get_ctl_value(cval, UAC_GET_MAX, (cval->control << 8) | minchn, &cval->max) < 0 ||
865                     get_ctl_value(cval, UAC_GET_MIN, (cval->control << 8) | minchn, &cval->min) < 0) {
866                         snd_printd(KERN_ERR "%d:%d: cannot get min/max values for control %d (id %d)\n",
867                                    cval->id, snd_usb_ctrl_intf(cval->mixer->chip), cval->control, cval->id);
868                         return -EINVAL;
869                 }
870                 if (get_ctl_value(cval, UAC_GET_RES, (cval->control << 8) | minchn, &cval->res) < 0) {
871                         cval->res = 1;
872                 } else {
873                         int last_valid_res = cval->res;
874
875                         while (cval->res > 1) {
876                                 if (snd_usb_mixer_set_ctl_value(cval, UAC_SET_RES,
877                                                                 (cval->control << 8) | minchn, cval->res / 2) < 0)
878                                         break;
879                                 cval->res /= 2;
880                         }
881                         if (get_ctl_value(cval, UAC_GET_RES, (cval->control << 8) | minchn, &cval->res) < 0)
882                                 cval->res = last_valid_res;
883                 }
884                 if (cval->res == 0)
885                         cval->res = 1;
886
887                 /* Additional checks for the proper resolution
888                  *
889                  * Some devices report smaller resolutions than actually
890                  * reacting.  They don't return errors but simply clip
891                  * to the lower aligned value.
892                  */
893                 if (cval->min + cval->res < cval->max) {
894                         int last_valid_res = cval->res;
895                         int saved, test, check;
896                         get_cur_mix_raw(cval, minchn, &saved);
897                         for (;;) {
898                                 test = saved;
899                                 if (test < cval->max)
900                                         test += cval->res;
901                                 else
902                                         test -= cval->res;
903                                 if (test < cval->min || test > cval->max ||
904                                     set_cur_mix_value(cval, minchn, 0, test) ||
905                                     get_cur_mix_raw(cval, minchn, &check)) {
906                                         cval->res = last_valid_res;
907                                         break;
908                                 }
909                                 if (test == check)
910                                         break;
911                                 cval->res *= 2;
912                         }
913                         set_cur_mix_value(cval, minchn, 0, saved);
914                 }
915
916                 cval->initialized = 1;
917         }
918
919         if (kctl)
920                 volume_control_quirks(cval, kctl);
921
922         /* USB descriptions contain the dB scale in 1/256 dB unit
923          * while ALSA TLV contains in 1/100 dB unit
924          */
925         cval->dBmin = (convert_signed_value(cval, cval->min) * 100) / 256;
926         cval->dBmax = (convert_signed_value(cval, cval->max) * 100) / 256;
927         if (cval->dBmin > cval->dBmax) {
928                 /* something is wrong; assume it's either from/to 0dB */
929                 if (cval->dBmin < 0)
930                         cval->dBmax = 0;
931                 else if (cval->dBmin > 0)
932                         cval->dBmin = 0;
933                 if (cval->dBmin > cval->dBmax) {
934                         /* totally crap, return an error */
935                         return -EINVAL;
936                 }
937         }
938
939         return 0;
940 }
941
942 #define get_min_max(cval, def)  get_min_max_with_quirks(cval, def, NULL)
943
944 /* get a feature/mixer unit info */
945 static int mixer_ctl_feature_info(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_info *uinfo)
946 {
947         struct usb_mixer_elem_info *cval = kcontrol->private_data;
948
949         if (cval->val_type == USB_MIXER_BOOLEAN ||
950             cval->val_type == USB_MIXER_INV_BOOLEAN)
951                 uinfo->type = SNDRV_CTL_ELEM_TYPE_BOOLEAN;
952         else
953                 uinfo->type = SNDRV_CTL_ELEM_TYPE_INTEGER;
954         uinfo->count = cval->channels;
955         if (cval->val_type == USB_MIXER_BOOLEAN ||
956             cval->val_type == USB_MIXER_INV_BOOLEAN) {
957                 uinfo->value.integer.min = 0;
958                 uinfo->value.integer.max = 1;
959         } else {
960                 if (!cval->initialized) {
961                         get_min_max_with_quirks(cval, 0, kcontrol);
962                         if (cval->initialized && cval->dBmin >= cval->dBmax) {
963                                 kcontrol->vd[0].access &= 
964                                         ~(SNDRV_CTL_ELEM_ACCESS_TLV_READ |
965                                           SNDRV_CTL_ELEM_ACCESS_TLV_CALLBACK);
966                                 snd_ctl_notify(cval->mixer->chip->card,
967                                                SNDRV_CTL_EVENT_MASK_INFO,
968                                                &kcontrol->id);
969                         }
970                 }
971                 uinfo->value.integer.min = 0;
972                 uinfo->value.integer.max =
973                         (cval->max - cval->min + cval->res - 1) / cval->res;
974         }
975         return 0;
976 }
977
978 /* get the current value from feature/mixer unit */
979 static int mixer_ctl_feature_get(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_value *ucontrol)
980 {
981         struct usb_mixer_elem_info *cval = kcontrol->private_data;
982         int c, cnt, val, err;
983
984         ucontrol->value.integer.value[0] = cval->min;
985         if (cval->cmask) {
986                 cnt = 0;
987                 for (c = 0; c < MAX_CHANNELS; c++) {
988                         if (!(cval->cmask & (1 << c)))
989                                 continue;
990                         err = get_cur_mix_value(cval, c + 1, cnt, &val);
991                         if (err < 0)
992                                 return cval->mixer->ignore_ctl_error ? 0 : err;
993                         val = get_relative_value(cval, val);
994                         ucontrol->value.integer.value[cnt] = val;
995                         cnt++;
996                 }
997                 return 0;
998         } else {
999                 /* master channel */
1000                 err = get_cur_mix_value(cval, 0, 0, &val);
1001                 if (err < 0)
1002                         return cval->mixer->ignore_ctl_error ? 0 : err;
1003                 val = get_relative_value(cval, val);
1004                 ucontrol->value.integer.value[0] = val;
1005         }
1006         return 0;
1007 }
1008
1009 /* put the current value to feature/mixer unit */
1010 static int mixer_ctl_feature_put(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_value *ucontrol)
1011 {
1012         struct usb_mixer_elem_info *cval = kcontrol->private_data;
1013         int c, cnt, val, oval, err;
1014         int changed = 0;
1015
1016         if (cval->cmask) {
1017                 cnt = 0;
1018                 for (c = 0; c < MAX_CHANNELS; c++) {
1019                         if (!(cval->cmask & (1 << c)))
1020                                 continue;
1021                         err = get_cur_mix_value(cval, c + 1, cnt, &oval);
1022                         if (err < 0)
1023                                 return cval->mixer->ignore_ctl_error ? 0 : err;
1024                         val = ucontrol->value.integer.value[cnt];
1025                         val = get_abs_value(cval, val);
1026                         if (oval != val) {
1027                                 set_cur_mix_value(cval, c + 1, cnt, val);
1028                                 changed = 1;
1029                         }
1030                         cnt++;
1031                 }
1032         } else {
1033                 /* master channel */
1034                 err = get_cur_mix_value(cval, 0, 0, &oval);
1035                 if (err < 0)
1036                         return cval->mixer->ignore_ctl_error ? 0 : err;
1037                 val = ucontrol->value.integer.value[0];
1038                 val = get_abs_value(cval, val);
1039                 if (val != oval) {
1040                         set_cur_mix_value(cval, 0, 0, val);
1041                         changed = 1;
1042                 }
1043         }
1044         return changed;
1045 }
1046
1047 static struct snd_kcontrol_new usb_feature_unit_ctl = {
1048         .iface = SNDRV_CTL_ELEM_IFACE_MIXER,
1049         .name = "", /* will be filled later manually */
1050         .info = mixer_ctl_feature_info,
1051         .get = mixer_ctl_feature_get,
1052         .put = mixer_ctl_feature_put,
1053 };
1054
1055 /* the read-only variant */
1056 static struct snd_kcontrol_new usb_feature_unit_ctl_ro = {
1057         .iface = SNDRV_CTL_ELEM_IFACE_MIXER,
1058         .name = "", /* will be filled later manually */
1059         .info = mixer_ctl_feature_info,
1060         .get = mixer_ctl_feature_get,
1061         .put = NULL,
1062 };
1063
1064 /* This symbol is exported in order to allow the mixer quirks to
1065  * hook up to the standard feature unit control mechanism */
1066 struct snd_kcontrol_new *snd_usb_feature_unit_ctl = &usb_feature_unit_ctl;
1067
1068 /*
1069  * build a feature control
1070  */
1071
1072 static size_t append_ctl_name(struct snd_kcontrol *kctl, const char *str)
1073 {
1074         return strlcat(kctl->id.name, str, sizeof(kctl->id.name));
1075 }
1076
1077 static void build_feature_ctl(struct mixer_build *state, void *raw_desc,
1078                               unsigned int ctl_mask, int control,
1079                               struct usb_audio_term *iterm, int unitid,
1080                               int readonly_mask)
1081 {
1082         struct uac_feature_unit_descriptor *desc = raw_desc;
1083         unsigned int len = 0;
1084         int mapped_name = 0;
1085         int nameid = uac_feature_unit_iFeature(desc);
1086         struct snd_kcontrol *kctl;
1087         struct usb_mixer_elem_info *cval;
1088         const struct usbmix_name_map *map;
1089         unsigned int range;
1090
1091         control++; /* change from zero-based to 1-based value */
1092
1093         if (control == UAC_FU_GRAPHIC_EQUALIZER) {
1094                 /* FIXME: not supported yet */
1095                 return;
1096         }
1097
1098         map = find_map(state, unitid, control);
1099         if (check_ignored_ctl(map))
1100                 return;
1101
1102         cval = kzalloc(sizeof(*cval), GFP_KERNEL);
1103         if (! cval) {
1104                 snd_printk(KERN_ERR "cannot malloc kcontrol\n");
1105                 return;
1106         }
1107         cval->mixer = state->mixer;
1108         cval->id = unitid;
1109         cval->control = control;
1110         cval->cmask = ctl_mask;
1111         cval->val_type = audio_feature_info[control-1].type;
1112         if (ctl_mask == 0) {
1113                 cval->channels = 1;     /* master channel */
1114                 cval->master_readonly = readonly_mask;
1115         } else {
1116                 int i, c = 0;
1117                 for (i = 0; i < 16; i++)
1118                         if (ctl_mask & (1 << i))
1119                                 c++;
1120                 cval->channels = c;
1121                 cval->ch_readonly = readonly_mask;
1122         }
1123
1124         /* if all channels in the mask are marked read-only, make the control
1125          * read-only. set_cur_mix_value() will check the mask again and won't
1126          * issue write commands to read-only channels. */
1127         if (cval->channels == readonly_mask)
1128                 kctl = snd_ctl_new1(&usb_feature_unit_ctl_ro, cval);
1129         else
1130                 kctl = snd_ctl_new1(&usb_feature_unit_ctl, cval);
1131
1132         if (! kctl) {
1133                 snd_printk(KERN_ERR "cannot malloc kcontrol\n");
1134                 kfree(cval);
1135                 return;
1136         }
1137         kctl->private_free = usb_mixer_elem_free;
1138
1139         len = check_mapped_name(map, kctl->id.name, sizeof(kctl->id.name));
1140         mapped_name = len != 0;
1141         if (! len && nameid)
1142                 len = snd_usb_copy_string_desc(state, nameid,
1143                                 kctl->id.name, sizeof(kctl->id.name));
1144
1145         /* get min/max values */
1146         get_min_max_with_quirks(cval, 0, kctl);
1147
1148         switch (control) {
1149         case UAC_FU_MUTE:
1150         case UAC_FU_VOLUME:
1151                 /* determine the control name.  the rule is:
1152                  * - if a name id is given in descriptor, use it.
1153                  * - if the connected input can be determined, then use the name
1154                  *   of terminal type.
1155                  * - if the connected output can be determined, use it.
1156                  * - otherwise, anonymous name.
1157                  */
1158                 if (! len) {
1159                         len = get_term_name(state, iterm, kctl->id.name, sizeof(kctl->id.name), 1);
1160                         if (! len)
1161                                 len = get_term_name(state, &state->oterm, kctl->id.name, sizeof(kctl->id.name), 1);
1162                         if (! len)
1163                                 len = snprintf(kctl->id.name, sizeof(kctl->id.name),
1164                                                "Feature %d", unitid);
1165                 }
1166                 /* determine the stream direction:
1167                  * if the connected output is USB stream, then it's likely a
1168                  * capture stream.  otherwise it should be playback (hopefully :)
1169                  */
1170                 if (! mapped_name && ! (state->oterm.type >> 16)) {
1171                         if ((state->oterm.type & 0xff00) == 0x0100) {
1172                                 len = append_ctl_name(kctl, " Capture");
1173                         } else {
1174                                 len = append_ctl_name(kctl, " Playback");
1175                         }
1176                 }
1177                 append_ctl_name(kctl, control == UAC_FU_MUTE ?
1178                                 " Switch" : " Volume");
1179                 if (control == UAC_FU_VOLUME) {
1180                         check_mapped_dB(map, cval);
1181                         if (cval->dBmin < cval->dBmax || !cval->initialized) {
1182                                 kctl->tlv.c = mixer_vol_tlv;
1183                                 kctl->vd[0].access |= 
1184                                         SNDRV_CTL_ELEM_ACCESS_TLV_READ |
1185                                         SNDRV_CTL_ELEM_ACCESS_TLV_CALLBACK;
1186                         }
1187                 }
1188                 break;
1189
1190         default:
1191                 if (! len)
1192                         strlcpy(kctl->id.name, audio_feature_info[control-1].name,
1193                                 sizeof(kctl->id.name));
1194                 break;
1195         }
1196
1197         range = (cval->max - cval->min) / cval->res;
1198         /* Are there devices with volume range more than 255? I use a bit more
1199          * to be sure. 384 is a resolution magic number found on Logitech
1200          * devices. It will definitively catch all buggy Logitech devices.
1201          */
1202         if (range > 384) {
1203                 snd_printk(KERN_WARNING "usb_audio: Warning! Unlikely big "
1204                            "volume range (=%u), cval->res is probably wrong.",
1205                            range);
1206                 snd_printk(KERN_WARNING "usb_audio: [%d] FU [%s] ch = %d, "
1207                            "val = %d/%d/%d", cval->id,
1208                            kctl->id.name, cval->channels,
1209                            cval->min, cval->max, cval->res);
1210         }
1211
1212         snd_printdd(KERN_INFO "[%d] FU [%s] ch = %d, val = %d/%d/%d\n",
1213                     cval->id, kctl->id.name, cval->channels, cval->min, cval->max, cval->res);
1214         snd_usb_mixer_add_control(state->mixer, kctl);
1215 }
1216
1217
1218
1219 /*
1220  * parse a feature unit
1221  *
1222  * most of controls are defined here.
1223  */
1224 static int parse_audio_feature_unit(struct mixer_build *state, int unitid, void *_ftr)
1225 {
1226         int channels, i, j;
1227         struct usb_audio_term iterm;
1228         unsigned int master_bits, first_ch_bits;
1229         int err, csize;
1230         struct uac_feature_unit_descriptor *hdr = _ftr;
1231         __u8 *bmaControls;
1232
1233         if (state->mixer->protocol == UAC_VERSION_1) {
1234                 csize = hdr->bControlSize;
1235                 if (!csize) {
1236                         snd_printdd(KERN_ERR "usbaudio: unit %u: "
1237                                     "invalid bControlSize == 0\n", unitid);
1238                         return -EINVAL;
1239                 }
1240                 channels = (hdr->bLength - 7) / csize - 1;
1241                 bmaControls = hdr->bmaControls;
1242         } else {
1243                 struct uac2_feature_unit_descriptor *ftr = _ftr;
1244                 csize = 4;
1245                 channels = (hdr->bLength - 6) / 4 - 1;
1246                 bmaControls = ftr->bmaControls;
1247         }
1248
1249         if (hdr->bLength < 7 || !csize || hdr->bLength < 7 + csize) {
1250                 snd_printk(KERN_ERR "usbaudio: unit %u: invalid UAC_FEATURE_UNIT descriptor\n", unitid);
1251                 return -EINVAL;
1252         }
1253
1254         /* parse the source unit */
1255         if ((err = parse_audio_unit(state, hdr->bSourceID)) < 0)
1256                 return err;
1257
1258         /* determine the input source type and name */
1259         if (check_input_term(state, hdr->bSourceID, &iterm) < 0)
1260                 return -EINVAL;
1261
1262         master_bits = snd_usb_combine_bytes(bmaControls, csize);
1263         /* master configuration quirks */
1264         switch (state->chip->usb_id) {
1265         case USB_ID(0x08bb, 0x2702):
1266                 snd_printk(KERN_INFO
1267                            "usbmixer: master volume quirk for PCM2702 chip\n");
1268                 /* disable non-functional volume control */
1269                 master_bits &= ~UAC_CONTROL_BIT(UAC_FU_VOLUME);
1270                 break;
1271         }
1272         if (channels > 0)
1273                 first_ch_bits = snd_usb_combine_bytes(bmaControls + csize, csize);
1274         else
1275                 first_ch_bits = 0;
1276
1277         if (state->mixer->protocol == UAC_VERSION_1) {
1278                 /* check all control types */
1279                 for (i = 0; i < 10; i++) {
1280                         unsigned int ch_bits = 0;
1281                         for (j = 0; j < channels; j++) {
1282                                 unsigned int mask = snd_usb_combine_bytes(bmaControls + csize * (j+1), csize);
1283                                 if (mask & (1 << i))
1284                                         ch_bits |= (1 << j);
1285                         }
1286                         /* audio class v1 controls are never read-only */
1287                         if (ch_bits & 1) /* the first channel must be set (for ease of programming) */
1288                                 build_feature_ctl(state, _ftr, ch_bits, i, &iterm, unitid, 0);
1289                         if (master_bits & (1 << i))
1290                                 build_feature_ctl(state, _ftr, 0, i, &iterm, unitid, 0);
1291                 }
1292         } else { /* UAC_VERSION_2 */
1293                 for (i = 0; i < ARRAY_SIZE(audio_feature_info); i++) {
1294                         unsigned int ch_bits = 0;
1295                         unsigned int ch_read_only = 0;
1296
1297                         for (j = 0; j < channels; j++) {
1298                                 unsigned int mask = snd_usb_combine_bytes(bmaControls + csize * (j+1), csize);
1299                                 if (uac2_control_is_readable(mask, i)) {
1300                                         ch_bits |= (1 << j);
1301                                         if (!uac2_control_is_writeable(mask, i))
1302                                                 ch_read_only |= (1 << j);
1303                                 }
1304                         }
1305
1306                         /* NOTE: build_feature_ctl() will mark the control read-only if all channels
1307                          * are marked read-only in the descriptors. Otherwise, the control will be
1308                          * reported as writeable, but the driver will not actually issue a write
1309                          * command for read-only channels */
1310                         if (ch_bits & 1) /* the first channel must be set (for ease of programming) */
1311                                 build_feature_ctl(state, _ftr, ch_bits, i, &iterm, unitid, ch_read_only);
1312                         if (uac2_control_is_readable(master_bits, i))
1313                                 build_feature_ctl(state, _ftr, 0, i, &iterm, unitid,
1314                                                   !uac2_control_is_writeable(master_bits, i));
1315                 }
1316         }
1317
1318         return 0;
1319 }
1320
1321
1322 /*
1323  * Mixer Unit
1324  */
1325
1326 /*
1327  * build a mixer unit control
1328  *
1329  * the callbacks are identical with feature unit.
1330  * input channel number (zero based) is given in control field instead.
1331  */
1332
1333 static void build_mixer_unit_ctl(struct mixer_build *state,
1334                                  struct uac_mixer_unit_descriptor *desc,
1335                                  int in_pin, int in_ch, int unitid,
1336                                  struct usb_audio_term *iterm)
1337 {
1338         struct usb_mixer_elem_info *cval;
1339         unsigned int num_outs = uac_mixer_unit_bNrChannels(desc);
1340         unsigned int i, len;
1341         struct snd_kcontrol *kctl;
1342         const struct usbmix_name_map *map;
1343
1344         map = find_map(state, unitid, 0);
1345         if (check_ignored_ctl(map))
1346                 return;
1347
1348         cval = kzalloc(sizeof(*cval), GFP_KERNEL);
1349         if (! cval)
1350                 return;
1351
1352         cval->mixer = state->mixer;
1353         cval->id = unitid;
1354         cval->control = in_ch + 1; /* based on 1 */
1355         cval->val_type = USB_MIXER_S16;
1356         for (i = 0; i < num_outs; i++) {
1357                 if (check_matrix_bitmap(uac_mixer_unit_bmControls(desc, state->mixer->protocol), in_ch, i, num_outs)) {
1358                         cval->cmask |= (1 << i);
1359                         cval->channels++;
1360                 }
1361         }
1362
1363         /* get min/max values */
1364         get_min_max(cval, 0);
1365
1366         kctl = snd_ctl_new1(&usb_feature_unit_ctl, cval);
1367         if (! kctl) {
1368                 snd_printk(KERN_ERR "cannot malloc kcontrol\n");
1369                 kfree(cval);
1370                 return;
1371         }
1372         kctl->private_free = usb_mixer_elem_free;
1373
1374         len = check_mapped_name(map, kctl->id.name, sizeof(kctl->id.name));
1375         if (! len)
1376                 len = get_term_name(state, iterm, kctl->id.name, sizeof(kctl->id.name), 0);
1377         if (! len)
1378                 len = sprintf(kctl->id.name, "Mixer Source %d", in_ch + 1);
1379         append_ctl_name(kctl, " Volume");
1380
1381         snd_printdd(KERN_INFO "[%d] MU [%s] ch = %d, val = %d/%d\n",
1382                     cval->id, kctl->id.name, cval->channels, cval->min, cval->max);
1383         snd_usb_mixer_add_control(state->mixer, kctl);
1384 }
1385
1386
1387 /*
1388  * parse a mixer unit
1389  */
1390 static int parse_audio_mixer_unit(struct mixer_build *state, int unitid, void *raw_desc)
1391 {
1392         struct uac_mixer_unit_descriptor *desc = raw_desc;
1393         struct usb_audio_term iterm;
1394         int input_pins, num_ins, num_outs;
1395         int pin, ich, err;
1396
1397         if (desc->bLength < 11 || ! (input_pins = desc->bNrInPins) || ! (num_outs = uac_mixer_unit_bNrChannels(desc))) {
1398                 snd_printk(KERN_ERR "invalid MIXER UNIT descriptor %d\n", unitid);
1399                 return -EINVAL;
1400         }
1401         /* no bmControls field (e.g. Maya44) -> ignore */
1402         if (desc->bLength <= 10 + input_pins) {
1403                 snd_printdd(KERN_INFO "MU %d has no bmControls field\n", unitid);
1404                 return 0;
1405         }
1406
1407         num_ins = 0;
1408         ich = 0;
1409         for (pin = 0; pin < input_pins; pin++) {
1410                 err = parse_audio_unit(state, desc->baSourceID[pin]);
1411                 if (err < 0)
1412                         return err;
1413                 err = check_input_term(state, desc->baSourceID[pin], &iterm);
1414                 if (err < 0)
1415                         return err;
1416                 num_ins += iterm.channels;
1417                 for (; ich < num_ins; ++ich) {
1418                         int och, ich_has_controls = 0;
1419
1420                         for (och = 0; och < num_outs; ++och) {
1421                                 if (check_matrix_bitmap(uac_mixer_unit_bmControls(desc, state->mixer->protocol),
1422                                                         ich, och, num_outs)) {
1423                                         ich_has_controls = 1;
1424                                         break;
1425                                 }
1426                         }
1427                         if (ich_has_controls)
1428                                 build_mixer_unit_ctl(state, desc, pin, ich,
1429                                                      unitid, &iterm);
1430                 }
1431         }
1432         return 0;
1433 }
1434
1435
1436 /*
1437  * Processing Unit / Extension Unit
1438  */
1439
1440 /* get callback for processing/extension unit */
1441 static int mixer_ctl_procunit_get(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_value *ucontrol)
1442 {
1443         struct usb_mixer_elem_info *cval = kcontrol->private_data;
1444         int err, val;
1445
1446         err = get_cur_ctl_value(cval, cval->control << 8, &val);
1447         if (err < 0 && cval->mixer->ignore_ctl_error) {
1448                 ucontrol->value.integer.value[0] = cval->min;
1449                 return 0;
1450         }
1451         if (err < 0)
1452                 return err;
1453         val = get_relative_value(cval, val);
1454         ucontrol->value.integer.value[0] = val;
1455         return 0;
1456 }
1457
1458 /* put callback for processing/extension unit */
1459 static int mixer_ctl_procunit_put(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_value *ucontrol)
1460 {
1461         struct usb_mixer_elem_info *cval = kcontrol->private_data;
1462         int val, oval, err;
1463
1464         err = get_cur_ctl_value(cval, cval->control << 8, &oval);
1465         if (err < 0) {
1466                 if (cval->mixer->ignore_ctl_error)
1467                         return 0;
1468                 return err;
1469         }
1470         val = ucontrol->value.integer.value[0];
1471         val = get_abs_value(cval, val);
1472         if (val != oval) {
1473                 set_cur_ctl_value(cval, cval->control << 8, val);
1474                 return 1;
1475         }
1476         return 0;
1477 }
1478
1479 /* alsa control interface for processing/extension unit */
1480 static struct snd_kcontrol_new mixer_procunit_ctl = {
1481         .iface = SNDRV_CTL_ELEM_IFACE_MIXER,
1482         .name = "", /* will be filled later */
1483         .info = mixer_ctl_feature_info,
1484         .get = mixer_ctl_procunit_get,
1485         .put = mixer_ctl_procunit_put,
1486 };
1487
1488
1489 /*
1490  * predefined data for processing units
1491  */
1492 struct procunit_value_info {
1493         int control;
1494         char *suffix;
1495         int val_type;
1496         int min_value;
1497 };
1498
1499 struct procunit_info {
1500         int type;
1501         char *name;
1502         struct procunit_value_info *values;
1503 };
1504
1505 static struct procunit_value_info updown_proc_info[] = {
1506         { UAC_UD_ENABLE, "Switch", USB_MIXER_BOOLEAN },
1507         { UAC_UD_MODE_SELECT, "Mode Select", USB_MIXER_U8, 1 },
1508         { 0 }
1509 };
1510 static struct procunit_value_info prologic_proc_info[] = {
1511         { UAC_DP_ENABLE, "Switch", USB_MIXER_BOOLEAN },
1512         { UAC_DP_MODE_SELECT, "Mode Select", USB_MIXER_U8, 1 },
1513         { 0 }
1514 };
1515 static struct procunit_value_info threed_enh_proc_info[] = {
1516         { UAC_3D_ENABLE, "Switch", USB_MIXER_BOOLEAN },
1517         { UAC_3D_SPACE, "Spaciousness", USB_MIXER_U8 },
1518         { 0 }
1519 };
1520 static struct procunit_value_info reverb_proc_info[] = {
1521         { UAC_REVERB_ENABLE, "Switch", USB_MIXER_BOOLEAN },
1522         { UAC_REVERB_LEVEL, "Level", USB_MIXER_U8 },
1523         { UAC_REVERB_TIME, "Time", USB_MIXER_U16 },
1524         { UAC_REVERB_FEEDBACK, "Feedback", USB_MIXER_U8 },
1525         { 0 }
1526 };
1527 static struct procunit_value_info chorus_proc_info[] = {
1528         { UAC_CHORUS_ENABLE, "Switch", USB_MIXER_BOOLEAN },
1529         { UAC_CHORUS_LEVEL, "Level", USB_MIXER_U8 },
1530         { UAC_CHORUS_RATE, "Rate", USB_MIXER_U16 },
1531         { UAC_CHORUS_DEPTH, "Depth", USB_MIXER_U16 },
1532         { 0 }
1533 };
1534 static struct procunit_value_info dcr_proc_info[] = {
1535         { UAC_DCR_ENABLE, "Switch", USB_MIXER_BOOLEAN },
1536         { UAC_DCR_RATE, "Ratio", USB_MIXER_U16 },
1537         { UAC_DCR_MAXAMPL, "Max Amp", USB_MIXER_S16 },
1538         { UAC_DCR_THRESHOLD, "Threshold", USB_MIXER_S16 },
1539         { UAC_DCR_ATTACK_TIME, "Attack Time", USB_MIXER_U16 },
1540         { UAC_DCR_RELEASE_TIME, "Release Time", USB_MIXER_U16 },
1541         { 0 }
1542 };
1543
1544 static struct procunit_info procunits[] = {
1545         { UAC_PROCESS_UP_DOWNMIX, "Up Down", updown_proc_info },
1546         { UAC_PROCESS_DOLBY_PROLOGIC, "Dolby Prologic", prologic_proc_info },
1547         { UAC_PROCESS_STEREO_EXTENDER, "3D Stereo Extender", threed_enh_proc_info },
1548         { UAC_PROCESS_REVERB, "Reverb", reverb_proc_info },
1549         { UAC_PROCESS_CHORUS, "Chorus", chorus_proc_info },
1550         { UAC_PROCESS_DYN_RANGE_COMP, "DCR", dcr_proc_info },
1551         { 0 },
1552 };
1553 /*
1554  * predefined data for extension units
1555  */
1556 static struct procunit_value_info clock_rate_xu_info[] = {
1557         { USB_XU_CLOCK_RATE_SELECTOR, "Selector", USB_MIXER_U8, 0 },
1558         { 0 }
1559 };
1560 static struct procunit_value_info clock_source_xu_info[] = {
1561         { USB_XU_CLOCK_SOURCE_SELECTOR, "External", USB_MIXER_BOOLEAN },
1562         { 0 }
1563 };
1564 static struct procunit_value_info spdif_format_xu_info[] = {
1565         { USB_XU_DIGITAL_FORMAT_SELECTOR, "SPDIF/AC3", USB_MIXER_BOOLEAN },
1566         { 0 }
1567 };
1568 static struct procunit_value_info soft_limit_xu_info[] = {
1569         { USB_XU_SOFT_LIMIT_SELECTOR, " ", USB_MIXER_BOOLEAN },
1570         { 0 }
1571 };
1572 static struct procunit_info extunits[] = {
1573         { USB_XU_CLOCK_RATE, "Clock rate", clock_rate_xu_info },
1574         { USB_XU_CLOCK_SOURCE, "DigitalIn CLK source", clock_source_xu_info },
1575         { USB_XU_DIGITAL_IO_STATUS, "DigitalOut format:", spdif_format_xu_info },
1576         { USB_XU_DEVICE_OPTIONS, "AnalogueIn Soft Limit", soft_limit_xu_info },
1577         { 0 }
1578 };
1579 /*
1580  * build a processing/extension unit
1581  */
1582 static int build_audio_procunit(struct mixer_build *state, int unitid, void *raw_desc, struct procunit_info *list, char *name)
1583 {
1584         struct uac_processing_unit_descriptor *desc = raw_desc;
1585         int num_ins = desc->bNrInPins;
1586         struct usb_mixer_elem_info *cval;
1587         struct snd_kcontrol *kctl;
1588         int i, err, nameid, type, len;
1589         struct procunit_info *info;
1590         struct procunit_value_info *valinfo;
1591         const struct usbmix_name_map *map;
1592         static struct procunit_value_info default_value_info[] = {
1593                 { 0x01, "Switch", USB_MIXER_BOOLEAN },
1594                 { 0 }
1595         };
1596         static struct procunit_info default_info = {
1597                 0, NULL, default_value_info
1598         };
1599
1600         if (desc->bLength < 13 || desc->bLength < 13 + num_ins ||
1601             desc->bLength < num_ins + uac_processing_unit_bControlSize(desc, state->mixer->protocol)) {
1602                 snd_printk(KERN_ERR "invalid %s descriptor (id %d)\n", name, unitid);
1603                 return -EINVAL;
1604         }
1605
1606         for (i = 0; i < num_ins; i++) {
1607                 if ((err = parse_audio_unit(state, desc->baSourceID[i])) < 0)
1608                         return err;
1609         }
1610
1611         type = le16_to_cpu(desc->wProcessType);
1612         for (info = list; info && info->type; info++)
1613                 if (info->type == type)
1614                         break;
1615         if (! info || ! info->type)
1616                 info = &default_info;
1617
1618         for (valinfo = info->values; valinfo->control; valinfo++) {
1619                 __u8 *controls = uac_processing_unit_bmControls(desc, state->mixer->protocol);
1620
1621                 if (! (controls[valinfo->control / 8] & (1 << ((valinfo->control % 8) - 1))))
1622                         continue;
1623                 map = find_map(state, unitid, valinfo->control);
1624                 if (check_ignored_ctl(map))
1625                         continue;
1626                 cval = kzalloc(sizeof(*cval), GFP_KERNEL);
1627                 if (! cval) {
1628                         snd_printk(KERN_ERR "cannot malloc kcontrol\n");
1629                         return -ENOMEM;
1630                 }
1631                 cval->mixer = state->mixer;
1632                 cval->id = unitid;
1633                 cval->control = valinfo->control;
1634                 cval->val_type = valinfo->val_type;
1635                 cval->channels = 1;
1636
1637                 /* get min/max values */
1638                 if (type == UAC_PROCESS_UP_DOWNMIX && cval->control == UAC_UD_MODE_SELECT) {
1639                         __u8 *control_spec = uac_processing_unit_specific(desc, state->mixer->protocol);
1640                         /* FIXME: hard-coded */
1641                         cval->min = 1;
1642                         cval->max = control_spec[0];
1643                         cval->res = 1;
1644                         cval->initialized = 1;
1645                 } else {
1646                         if (type == USB_XU_CLOCK_RATE) {
1647                                 /* E-Mu USB 0404/0202/TrackerPre/0204
1648                                  * samplerate control quirk
1649                                  */
1650                                 cval->min = 0;
1651                                 cval->max = 5;
1652                                 cval->res = 1;
1653                                 cval->initialized = 1;
1654                         } else
1655                                 get_min_max(cval, valinfo->min_value);
1656                 }
1657
1658                 kctl = snd_ctl_new1(&mixer_procunit_ctl, cval);
1659                 if (! kctl) {
1660                         snd_printk(KERN_ERR "cannot malloc kcontrol\n");
1661                         kfree(cval);
1662                         return -ENOMEM;
1663                 }
1664                 kctl->private_free = usb_mixer_elem_free;
1665
1666                 if (check_mapped_name(map, kctl->id.name,
1667                                                 sizeof(kctl->id.name)))
1668                         /* nothing */ ;
1669                 else if (info->name)
1670                         strlcpy(kctl->id.name, info->name, sizeof(kctl->id.name));
1671                 else {
1672                         nameid = uac_processing_unit_iProcessing(desc, state->mixer->protocol);
1673                         len = 0;
1674                         if (nameid)
1675                                 len = snd_usb_copy_string_desc(state, nameid, kctl->id.name, sizeof(kctl->id.name));
1676                         if (! len)
1677                                 strlcpy(kctl->id.name, name, sizeof(kctl->id.name));
1678                 }
1679                 append_ctl_name(kctl, " ");
1680                 append_ctl_name(kctl, valinfo->suffix);
1681
1682                 snd_printdd(KERN_INFO "[%d] PU [%s] ch = %d, val = %d/%d\n",
1683                             cval->id, kctl->id.name, cval->channels, cval->min, cval->max);
1684                 if ((err = snd_usb_mixer_add_control(state->mixer, kctl)) < 0)
1685                         return err;
1686         }
1687         return 0;
1688 }
1689
1690
1691 static int parse_audio_processing_unit(struct mixer_build *state, int unitid, void *raw_desc)
1692 {
1693         return build_audio_procunit(state, unitid, raw_desc, procunits, "Processing Unit");
1694 }
1695
1696 static int parse_audio_extension_unit(struct mixer_build *state, int unitid, void *raw_desc)
1697 {
1698         /* Note that we parse extension units with processing unit descriptors.
1699          * That's ok as the layout is the same */
1700         return build_audio_procunit(state, unitid, raw_desc, extunits, "Extension Unit");
1701 }
1702
1703
1704 /*
1705  * Selector Unit
1706  */
1707
1708 /* info callback for selector unit
1709  * use an enumerator type for routing
1710  */
1711 static int mixer_ctl_selector_info(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_info *uinfo)
1712 {
1713         struct usb_mixer_elem_info *cval = kcontrol->private_data;
1714         const char **itemlist = (const char **)kcontrol->private_value;
1715
1716         if (snd_BUG_ON(!itemlist))
1717                 return -EINVAL;
1718         return snd_ctl_enum_info(uinfo, 1, cval->max, itemlist);
1719 }
1720
1721 /* get callback for selector unit */
1722 static int mixer_ctl_selector_get(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_value *ucontrol)
1723 {
1724         struct usb_mixer_elem_info *cval = kcontrol->private_data;
1725         int val, err;
1726
1727         err = get_cur_ctl_value(cval, cval->control << 8, &val);
1728         if (err < 0) {
1729                 if (cval->mixer->ignore_ctl_error) {
1730                         ucontrol->value.enumerated.item[0] = 0;
1731                         return 0;
1732                 }
1733                 return err;
1734         }
1735         val = get_relative_value(cval, val);
1736         ucontrol->value.enumerated.item[0] = val;
1737         return 0;
1738 }
1739
1740 /* put callback for selector unit */
1741 static int mixer_ctl_selector_put(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_value *ucontrol)
1742 {
1743         struct usb_mixer_elem_info *cval = kcontrol->private_data;
1744         int val, oval, err;
1745
1746         err = get_cur_ctl_value(cval, cval->control << 8, &oval);
1747         if (err < 0) {
1748                 if (cval->mixer->ignore_ctl_error)
1749                         return 0;
1750                 return err;
1751         }
1752         val = ucontrol->value.enumerated.item[0];
1753         val = get_abs_value(cval, val);
1754         if (val != oval) {
1755                 set_cur_ctl_value(cval, cval->control << 8, val);
1756                 return 1;
1757         }
1758         return 0;
1759 }
1760
1761 /* alsa control interface for selector unit */
1762 static struct snd_kcontrol_new mixer_selectunit_ctl = {
1763         .iface = SNDRV_CTL_ELEM_IFACE_MIXER,
1764         .name = "", /* will be filled later */
1765         .info = mixer_ctl_selector_info,
1766         .get = mixer_ctl_selector_get,
1767         .put = mixer_ctl_selector_put,
1768 };
1769
1770
1771 /* private free callback.
1772  * free both private_data and private_value
1773  */
1774 static void usb_mixer_selector_elem_free(struct snd_kcontrol *kctl)
1775 {
1776         int i, num_ins = 0;
1777
1778         if (kctl->private_data) {
1779                 struct usb_mixer_elem_info *cval = kctl->private_data;
1780                 num_ins = cval->max;
1781                 kfree(cval);
1782                 kctl->private_data = NULL;
1783         }
1784         if (kctl->private_value) {
1785                 char **itemlist = (char **)kctl->private_value;
1786                 for (i = 0; i < num_ins; i++)
1787                         kfree(itemlist[i]);
1788                 kfree(itemlist);
1789                 kctl->private_value = 0;
1790         }
1791 }
1792
1793 /*
1794  * parse a selector unit
1795  */
1796 static int parse_audio_selector_unit(struct mixer_build *state, int unitid, void *raw_desc)
1797 {
1798         struct uac_selector_unit_descriptor *desc = raw_desc;
1799         unsigned int i, nameid, len;
1800         int err;
1801         struct usb_mixer_elem_info *cval;
1802         struct snd_kcontrol *kctl;
1803         const struct usbmix_name_map *map;
1804         char **namelist;
1805
1806         if (!desc->bNrInPins || desc->bLength < 5 + desc->bNrInPins) {
1807                 snd_printk(KERN_ERR "invalid SELECTOR UNIT descriptor %d\n", unitid);
1808                 return -EINVAL;
1809         }
1810
1811         for (i = 0; i < desc->bNrInPins; i++) {
1812                 if ((err = parse_audio_unit(state, desc->baSourceID[i])) < 0)
1813                         return err;
1814         }
1815
1816         if (desc->bNrInPins == 1) /* only one ? nonsense! */
1817                 return 0;
1818
1819         map = find_map(state, unitid, 0);
1820         if (check_ignored_ctl(map))
1821                 return 0;
1822
1823         cval = kzalloc(sizeof(*cval), GFP_KERNEL);
1824         if (! cval) {
1825                 snd_printk(KERN_ERR "cannot malloc kcontrol\n");
1826                 return -ENOMEM;
1827         }
1828         cval->mixer = state->mixer;
1829         cval->id = unitid;
1830         cval->val_type = USB_MIXER_U8;
1831         cval->channels = 1;
1832         cval->min = 1;
1833         cval->max = desc->bNrInPins;
1834         cval->res = 1;
1835         cval->initialized = 1;
1836
1837         if (desc->bDescriptorSubtype == UAC2_CLOCK_SELECTOR)
1838                 cval->control = UAC2_CX_CLOCK_SELECTOR;
1839         else
1840                 cval->control = 0;
1841
1842         namelist = kmalloc(sizeof(char *) * desc->bNrInPins, GFP_KERNEL);
1843         if (! namelist) {
1844                 snd_printk(KERN_ERR "cannot malloc\n");
1845                 kfree(cval);
1846                 return -ENOMEM;
1847         }
1848 #define MAX_ITEM_NAME_LEN       64
1849         for (i = 0; i < desc->bNrInPins; i++) {
1850                 struct usb_audio_term iterm;
1851                 len = 0;
1852                 namelist[i] = kmalloc(MAX_ITEM_NAME_LEN, GFP_KERNEL);
1853                 if (! namelist[i]) {
1854                         snd_printk(KERN_ERR "cannot malloc\n");
1855                         while (i--)
1856                                 kfree(namelist[i]);
1857                         kfree(namelist);
1858                         kfree(cval);
1859                         return -ENOMEM;
1860                 }
1861                 len = check_mapped_selector_name(state, unitid, i, namelist[i],
1862                                                  MAX_ITEM_NAME_LEN);
1863                 if (! len && check_input_term(state, desc->baSourceID[i], &iterm) >= 0)
1864                         len = get_term_name(state, &iterm, namelist[i], MAX_ITEM_NAME_LEN, 0);
1865                 if (! len)
1866                         sprintf(namelist[i], "Input %d", i);
1867         }
1868
1869         kctl = snd_ctl_new1(&mixer_selectunit_ctl, cval);
1870         if (! kctl) {
1871                 snd_printk(KERN_ERR "cannot malloc kcontrol\n");
1872                 kfree(namelist);
1873                 kfree(cval);
1874                 return -ENOMEM;
1875         }
1876         kctl->private_value = (unsigned long)namelist;
1877         kctl->private_free = usb_mixer_selector_elem_free;
1878
1879         nameid = uac_selector_unit_iSelector(desc);
1880         len = check_mapped_name(map, kctl->id.name, sizeof(kctl->id.name));
1881         if (len)
1882                 ;
1883         else if (nameid)
1884                 snd_usb_copy_string_desc(state, nameid, kctl->id.name, sizeof(kctl->id.name));
1885         else {
1886                 len = get_term_name(state, &state->oterm,
1887                                     kctl->id.name, sizeof(kctl->id.name), 0);
1888                 if (! len)
1889                         strlcpy(kctl->id.name, "USB", sizeof(kctl->id.name));
1890
1891                 if (desc->bDescriptorSubtype == UAC2_CLOCK_SELECTOR)
1892                         append_ctl_name(kctl, " Clock Source");
1893                 else if ((state->oterm.type & 0xff00) == 0x0100)
1894                         append_ctl_name(kctl, " Capture Source");
1895                 else
1896                         append_ctl_name(kctl, " Playback Source");
1897         }
1898
1899         snd_printdd(KERN_INFO "[%d] SU [%s] items = %d\n",
1900                     cval->id, kctl->id.name, desc->bNrInPins);
1901         if ((err = snd_usb_mixer_add_control(state->mixer, kctl)) < 0)
1902                 return err;
1903
1904         return 0;
1905 }
1906
1907
1908 /*
1909  * parse an audio unit recursively
1910  */
1911
1912 static int parse_audio_unit(struct mixer_build *state, int unitid)
1913 {
1914         unsigned char *p1;
1915
1916         if (test_and_set_bit(unitid, state->unitbitmap))
1917                 return 0; /* the unit already visited */
1918
1919         p1 = find_audio_control_unit(state, unitid);
1920         if (!p1) {
1921                 snd_printk(KERN_ERR "usbaudio: unit %d not found!\n", unitid);
1922                 return -EINVAL;
1923         }
1924
1925         switch (p1[2]) {
1926         case UAC_INPUT_TERMINAL:
1927         case UAC2_CLOCK_SOURCE:
1928                 return 0; /* NOP */
1929         case UAC_MIXER_UNIT:
1930                 return parse_audio_mixer_unit(state, unitid, p1);
1931         case UAC_SELECTOR_UNIT:
1932         case UAC2_CLOCK_SELECTOR:
1933                 return parse_audio_selector_unit(state, unitid, p1);
1934         case UAC_FEATURE_UNIT:
1935                 return parse_audio_feature_unit(state, unitid, p1);
1936         case UAC1_PROCESSING_UNIT:
1937         /*   UAC2_EFFECT_UNIT has the same value */
1938                 if (state->mixer->protocol == UAC_VERSION_1)
1939                         return parse_audio_processing_unit(state, unitid, p1);
1940                 else
1941                         return 0; /* FIXME - effect units not implemented yet */
1942         case UAC1_EXTENSION_UNIT:
1943         /*   UAC2_PROCESSING_UNIT_V2 has the same value */
1944                 if (state->mixer->protocol == UAC_VERSION_1)
1945                         return parse_audio_extension_unit(state, unitid, p1);
1946                 else /* UAC_VERSION_2 */
1947                         return parse_audio_processing_unit(state, unitid, p1);
1948         default:
1949                 snd_printk(KERN_ERR "usbaudio: unit %u: unexpected type 0x%02x\n", unitid, p1[2]);
1950                 return -EINVAL;
1951         }
1952 }
1953
1954 static void snd_usb_mixer_free(struct usb_mixer_interface *mixer)
1955 {
1956         kfree(mixer->id_elems);
1957         if (mixer->urb) {
1958                 kfree(mixer->urb->transfer_buffer);
1959                 usb_free_urb(mixer->urb);
1960         }
1961         usb_free_urb(mixer->rc_urb);
1962         kfree(mixer->rc_setup_packet);
1963         kfree(mixer);
1964 }
1965
1966 static int snd_usb_mixer_dev_free(struct snd_device *device)
1967 {
1968         struct usb_mixer_interface *mixer = device->device_data;
1969         snd_usb_mixer_free(mixer);
1970         return 0;
1971 }
1972
1973 /*
1974  * create mixer controls
1975  *
1976  * walk through all UAC_OUTPUT_TERMINAL descriptors to search for mixers
1977  */
1978 static int snd_usb_mixer_controls(struct usb_mixer_interface *mixer)
1979 {
1980         struct mixer_build state;
1981         int err;
1982         const struct usbmix_ctl_map *map;
1983         void *p;
1984
1985         memset(&state, 0, sizeof(state));
1986         state.chip = mixer->chip;
1987         state.mixer = mixer;
1988         state.buffer = mixer->hostif->extra;
1989         state.buflen = mixer->hostif->extralen;
1990
1991         /* check the mapping table */
1992         for (map = usbmix_ctl_maps; map->id; map++) {
1993                 if (map->id == state.chip->usb_id) {
1994                         state.map = map->map;
1995                         state.selector_map = map->selector_map;
1996                         mixer->ignore_ctl_error = map->ignore_ctl_error;
1997                         break;
1998                 }
1999         }
2000
2001         p = NULL;
2002         while ((p = snd_usb_find_csint_desc(mixer->hostif->extra, mixer->hostif->extralen,
2003                                             p, UAC_OUTPUT_TERMINAL)) != NULL) {
2004                 if (mixer->protocol == UAC_VERSION_1) {
2005                         struct uac1_output_terminal_descriptor *desc = p;
2006
2007                         if (desc->bLength < sizeof(*desc))
2008                                 continue; /* invalid descriptor? */
2009                         set_bit(desc->bTerminalID, state.unitbitmap);  /* mark terminal ID as visited */
2010                         state.oterm.id = desc->bTerminalID;
2011                         state.oterm.type = le16_to_cpu(desc->wTerminalType);
2012                         state.oterm.name = desc->iTerminal;
2013                         err = parse_audio_unit(&state, desc->bSourceID);
2014                         if (err < 0)
2015                                 return err;
2016                 } else { /* UAC_VERSION_2 */
2017                         struct uac2_output_terminal_descriptor *desc = p;
2018
2019                         if (desc->bLength < sizeof(*desc))
2020                                 continue; /* invalid descriptor? */
2021                         set_bit(desc->bTerminalID, state.unitbitmap);  /* mark terminal ID as visited */
2022                         state.oterm.id = desc->bTerminalID;
2023                         state.oterm.type = le16_to_cpu(desc->wTerminalType);
2024                         state.oterm.name = desc->iTerminal;
2025                         err = parse_audio_unit(&state, desc->bSourceID);
2026                         if (err < 0)
2027                                 return err;
2028
2029                         /* for UAC2, use the same approach to also add the clock selectors */
2030                         err = parse_audio_unit(&state, desc->bCSourceID);
2031                         if (err < 0)
2032                                 return err;
2033                 }
2034         }
2035
2036         return 0;
2037 }
2038
2039 void snd_usb_mixer_notify_id(struct usb_mixer_interface *mixer, int unitid)
2040 {
2041         struct usb_mixer_elem_info *info;
2042
2043         for (info = mixer->id_elems[unitid]; info; info = info->next_id_elem)
2044                 snd_ctl_notify(mixer->chip->card, SNDRV_CTL_EVENT_MASK_VALUE,
2045                                info->elem_id);
2046 }
2047
2048 static void snd_usb_mixer_dump_cval(struct snd_info_buffer *buffer,
2049                                     int unitid,
2050                                     struct usb_mixer_elem_info *cval)
2051 {
2052         static char *val_types[] = {"BOOLEAN", "INV_BOOLEAN",
2053                                     "S8", "U8", "S16", "U16"};
2054         snd_iprintf(buffer, "  Unit: %i\n", unitid);
2055         if (cval->elem_id)
2056                 snd_iprintf(buffer, "    Control: name=\"%s\", index=%i\n",
2057                                 cval->elem_id->name, cval->elem_id->index);
2058         snd_iprintf(buffer, "    Info: id=%i, control=%i, cmask=0x%x, "
2059                             "channels=%i, type=\"%s\"\n", cval->id,
2060                             cval->control, cval->cmask, cval->channels,
2061                             val_types[cval->val_type]);
2062         snd_iprintf(buffer, "    Volume: min=%i, max=%i, dBmin=%i, dBmax=%i\n",
2063                             cval->min, cval->max, cval->dBmin, cval->dBmax);
2064 }
2065
2066 static void snd_usb_mixer_proc_read(struct snd_info_entry *entry,
2067                                     struct snd_info_buffer *buffer)
2068 {
2069         struct snd_usb_audio *chip = entry->private_data;
2070         struct usb_mixer_interface *mixer;
2071         struct usb_mixer_elem_info *cval;
2072         int unitid;
2073
2074         list_for_each_entry(mixer, &chip->mixer_list, list) {
2075                 snd_iprintf(buffer,
2076                         "USB Mixer: usb_id=0x%08x, ctrlif=%i, ctlerr=%i\n",
2077                                 chip->usb_id, snd_usb_ctrl_intf(chip),
2078                                 mixer->ignore_ctl_error);
2079                 snd_iprintf(buffer, "Card: %s\n", chip->card->longname);
2080                 for (unitid = 0; unitid < MAX_ID_ELEMS; unitid++) {
2081                         for (cval = mixer->id_elems[unitid]; cval;
2082                                                 cval = cval->next_id_elem)
2083                                 snd_usb_mixer_dump_cval(buffer, unitid, cval);
2084                 }
2085         }
2086 }
2087
2088 static void snd_usb_mixer_interrupt_v2(struct usb_mixer_interface *mixer,
2089                                        int attribute, int value, int index)
2090 {
2091         struct usb_mixer_elem_info *info;
2092         __u8 unitid = (index >> 8) & 0xff;
2093         __u8 control = (value >> 8) & 0xff;
2094         __u8 channel = value & 0xff;
2095
2096         if (channel >= MAX_CHANNELS) {
2097                 snd_printk(KERN_DEBUG "%s(): bogus channel number %d\n",
2098                                 __func__, channel);
2099                 return;
2100         }
2101
2102         for (info = mixer->id_elems[unitid]; info; info = info->next_id_elem) {
2103                 if (info->control != control)
2104                         continue;
2105
2106                 switch (attribute) {
2107                 case UAC2_CS_CUR:
2108                         /* invalidate cache, so the value is read from the device */
2109                         if (channel)
2110                                 info->cached &= ~(1 << channel);
2111                         else /* master channel */
2112                                 info->cached = 0;
2113
2114                         snd_ctl_notify(mixer->chip->card, SNDRV_CTL_EVENT_MASK_VALUE,
2115                                         info->elem_id);
2116                         break;
2117
2118                 case UAC2_CS_RANGE:
2119                         /* TODO */
2120                         break;
2121
2122                 case UAC2_CS_MEM:
2123                         /* TODO */
2124                         break;
2125
2126                 default:
2127                         snd_printk(KERN_DEBUG "unknown attribute %d in interrupt\n",
2128                                                 attribute);
2129                         break;
2130                 } /* switch */
2131         }
2132 }
2133
2134 static void snd_usb_mixer_interrupt(struct urb *urb)
2135 {
2136         struct usb_mixer_interface *mixer = urb->context;
2137         int len = urb->actual_length;
2138         int ustatus = urb->status;
2139
2140         if (ustatus != 0)
2141                 goto requeue;
2142
2143         if (mixer->protocol == UAC_VERSION_1) {
2144                 struct uac1_status_word *status;
2145
2146                 for (status = urb->transfer_buffer;
2147                      len >= sizeof(*status);
2148                      len -= sizeof(*status), status++) {
2149                         snd_printd(KERN_DEBUG "status interrupt: %02x %02x\n",
2150                                                 status->bStatusType,
2151                                                 status->bOriginator);
2152
2153                         /* ignore any notifications not from the control interface */
2154                         if ((status->bStatusType & UAC1_STATUS_TYPE_ORIG_MASK) !=
2155                                 UAC1_STATUS_TYPE_ORIG_AUDIO_CONTROL_IF)
2156                                 continue;
2157
2158                         if (status->bStatusType & UAC1_STATUS_TYPE_MEM_CHANGED)
2159                                 snd_usb_mixer_rc_memory_change(mixer, status->bOriginator);
2160                         else
2161                                 snd_usb_mixer_notify_id(mixer, status->bOriginator);
2162                 }
2163         } else { /* UAC_VERSION_2 */
2164                 struct uac2_interrupt_data_msg *msg;
2165
2166                 for (msg = urb->transfer_buffer;
2167                      len >= sizeof(*msg);
2168                      len -= sizeof(*msg), msg++) {
2169                         /* drop vendor specific and endpoint requests */
2170                         if ((msg->bInfo & UAC2_INTERRUPT_DATA_MSG_VENDOR) ||
2171                             (msg->bInfo & UAC2_INTERRUPT_DATA_MSG_EP))
2172                                 continue;
2173
2174                         snd_usb_mixer_interrupt_v2(mixer, msg->bAttribute,
2175                                                    le16_to_cpu(msg->wValue),
2176                                                    le16_to_cpu(msg->wIndex));
2177                 }
2178         }
2179
2180 requeue:
2181         if (ustatus != -ENOENT && ustatus != -ECONNRESET && ustatus != -ESHUTDOWN) {
2182                 urb->dev = mixer->chip->dev;
2183                 usb_submit_urb(urb, GFP_ATOMIC);
2184         }
2185 }
2186
2187 /* stop any bus activity of a mixer */
2188 void snd_usb_mixer_inactivate(struct usb_mixer_interface *mixer)
2189 {
2190         usb_kill_urb(mixer->urb);
2191         usb_kill_urb(mixer->rc_urb);
2192 }
2193
2194 int snd_usb_mixer_activate(struct usb_mixer_interface *mixer)
2195 {
2196         int err;
2197
2198         if (mixer->urb) {
2199                 err = usb_submit_urb(mixer->urb, GFP_NOIO);
2200                 if (err < 0)
2201                         return err;
2202         }
2203
2204         return 0;
2205 }
2206
2207 /* create the handler for the optional status interrupt endpoint */
2208 static int snd_usb_mixer_status_create(struct usb_mixer_interface *mixer)
2209 {
2210         struct usb_endpoint_descriptor *ep;
2211         void *transfer_buffer;
2212         int buffer_length;
2213         unsigned int epnum;
2214
2215         /* we need one interrupt input endpoint */
2216         if (get_iface_desc(mixer->hostif)->bNumEndpoints < 1)
2217                 return 0;
2218         ep = get_endpoint(mixer->hostif, 0);
2219         if (!usb_endpoint_dir_in(ep) || !usb_endpoint_xfer_int(ep))
2220                 return 0;
2221
2222         epnum = usb_endpoint_num(ep);
2223         buffer_length = le16_to_cpu(ep->wMaxPacketSize);
2224         transfer_buffer = kmalloc(buffer_length, GFP_KERNEL);
2225         if (!transfer_buffer)
2226                 return -ENOMEM;
2227         mixer->urb = usb_alloc_urb(0, GFP_KERNEL);
2228         if (!mixer->urb) {
2229                 kfree(transfer_buffer);
2230                 return -ENOMEM;
2231         }
2232         usb_fill_int_urb(mixer->urb, mixer->chip->dev,
2233                          usb_rcvintpipe(mixer->chip->dev, epnum),
2234                          transfer_buffer, buffer_length,
2235                          snd_usb_mixer_interrupt, mixer, ep->bInterval);
2236         usb_submit_urb(mixer->urb, GFP_KERNEL);
2237         return 0;
2238 }
2239
2240 int snd_usb_create_mixer(struct snd_usb_audio *chip, int ctrlif,
2241                          int ignore_error)
2242 {
2243         static struct snd_device_ops dev_ops = {
2244                 .dev_free = snd_usb_mixer_dev_free
2245         };
2246         struct usb_mixer_interface *mixer;
2247         struct snd_info_entry *entry;
2248         int err;
2249
2250         strcpy(chip->card->mixername, "USB Mixer");
2251
2252         mixer = kzalloc(sizeof(*mixer), GFP_KERNEL);
2253         if (!mixer)
2254                 return -ENOMEM;
2255         mixer->chip = chip;
2256         mixer->ignore_ctl_error = ignore_error;
2257         mixer->id_elems = kcalloc(MAX_ID_ELEMS, sizeof(*mixer->id_elems),
2258                                   GFP_KERNEL);
2259         if (!mixer->id_elems) {
2260                 kfree(mixer);
2261                 return -ENOMEM;
2262         }
2263
2264         mixer->hostif = &usb_ifnum_to_if(chip->dev, ctrlif)->altsetting[0];
2265         switch (get_iface_desc(mixer->hostif)->bInterfaceProtocol) {
2266         case UAC_VERSION_1:
2267         default:
2268                 mixer->protocol = UAC_VERSION_1;
2269                 break;
2270         case UAC_VERSION_2:
2271                 mixer->protocol = UAC_VERSION_2;
2272                 break;
2273         }
2274
2275         if ((err = snd_usb_mixer_controls(mixer)) < 0 ||
2276             (err = snd_usb_mixer_status_create(mixer)) < 0)
2277                 goto _error;
2278
2279         snd_usb_mixer_apply_create_quirk(mixer);
2280
2281         err = snd_device_new(chip->card, SNDRV_DEV_LOWLEVEL, mixer, &dev_ops);
2282         if (err < 0)
2283                 goto _error;
2284
2285         if (list_empty(&chip->mixer_list) &&
2286             !snd_card_proc_new(chip->card, "usbmixer", &entry))
2287                 snd_info_set_text_ops(entry, chip, snd_usb_mixer_proc_read);
2288
2289         list_add(&mixer->list, &chip->mixer_list);
2290         return 0;
2291
2292 _error:
2293         snd_usb_mixer_free(mixer);
2294         return err;
2295 }
2296
2297 void snd_usb_mixer_disconnect(struct list_head *p)
2298 {
2299         struct usb_mixer_interface *mixer;
2300
2301         mixer = list_entry(p, struct usb_mixer_interface, list);
2302         usb_kill_urb(mixer->urb);
2303         usb_kill_urb(mixer->rc_urb);
2304 }