]> asedeno.scripts.mit.edu Git - linux.git/blob - sound/usb/stream.c
Merge branch 'x86-pti-for-linus' of git://git.kernel.org/pub/scm/linux/kernel/git/tip/tip
[linux.git] / sound / usb / stream.c
1 /*
2  *   This program is free software; you can redistribute it and/or modify
3  *   it under the terms of the GNU General Public License as published by
4  *   the Free Software Foundation; either version 2 of the License, or
5  *   (at your option) any later version.
6  *
7  *   This program is distributed in the hope that it will be useful,
8  *   but WITHOUT ANY WARRANTY; without even the implied warranty of
9  *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
10  *   GNU General Public License for more details.
11  *
12  *   You should have received a copy of the GNU General Public License
13  *   along with this program; if not, write to the Free Software
14  *   Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307 USA
15  */
16
17
18 #include <linux/init.h>
19 #include <linux/slab.h>
20 #include <linux/usb.h>
21 #include <linux/usb/audio.h>
22 #include <linux/usb/audio-v2.h>
23 #include <linux/usb/audio-v3.h>
24
25 #include <sound/core.h>
26 #include <sound/pcm.h>
27 #include <sound/control.h>
28 #include <sound/tlv.h>
29
30 #include "usbaudio.h"
31 #include "card.h"
32 #include "proc.h"
33 #include "quirks.h"
34 #include "endpoint.h"
35 #include "pcm.h"
36 #include "helper.h"
37 #include "format.h"
38 #include "clock.h"
39 #include "stream.h"
40
41 /*
42  * free a substream
43  */
44 static void free_substream(struct snd_usb_substream *subs)
45 {
46         struct audioformat *fp, *n;
47
48         if (!subs->num_formats)
49                 return; /* not initialized */
50         list_for_each_entry_safe(fp, n, &subs->fmt_list, list) {
51                 kfree(fp->rate_table);
52                 kfree(fp->chmap);
53                 kfree(fp);
54         }
55         kfree(subs->rate_list.list);
56 }
57
58
59 /*
60  * free a usb stream instance
61  */
62 static void snd_usb_audio_stream_free(struct snd_usb_stream *stream)
63 {
64         free_substream(&stream->substream[0]);
65         free_substream(&stream->substream[1]);
66         list_del(&stream->list);
67         kfree(stream);
68 }
69
70 static void snd_usb_audio_pcm_free(struct snd_pcm *pcm)
71 {
72         struct snd_usb_stream *stream = pcm->private_data;
73         if (stream) {
74                 stream->pcm = NULL;
75                 snd_usb_audio_stream_free(stream);
76         }
77 }
78
79 /*
80  * initialize the substream instance.
81  */
82
83 static void snd_usb_init_substream(struct snd_usb_stream *as,
84                                    int stream,
85                                    struct audioformat *fp)
86 {
87         struct snd_usb_substream *subs = &as->substream[stream];
88
89         INIT_LIST_HEAD(&subs->fmt_list);
90         spin_lock_init(&subs->lock);
91
92         subs->stream = as;
93         subs->direction = stream;
94         subs->dev = as->chip->dev;
95         subs->txfr_quirk = as->chip->txfr_quirk;
96         subs->tx_length_quirk = as->chip->tx_length_quirk;
97         subs->speed = snd_usb_get_speed(subs->dev);
98         subs->pkt_offset_adj = 0;
99
100         snd_usb_set_pcm_ops(as->pcm, stream);
101
102         list_add_tail(&fp->list, &subs->fmt_list);
103         subs->formats |= fp->formats;
104         subs->num_formats++;
105         subs->fmt_type = fp->fmt_type;
106         subs->ep_num = fp->endpoint;
107         if (fp->channels > subs->channels_max)
108                 subs->channels_max = fp->channels;
109
110         snd_usb_preallocate_buffer(subs);
111 }
112
113 /* kctl callbacks for usb-audio channel maps */
114 static int usb_chmap_ctl_info(struct snd_kcontrol *kcontrol,
115                               struct snd_ctl_elem_info *uinfo)
116 {
117         struct snd_pcm_chmap *info = snd_kcontrol_chip(kcontrol);
118         struct snd_usb_substream *subs = info->private_data;
119
120         uinfo->type = SNDRV_CTL_ELEM_TYPE_INTEGER;
121         uinfo->count = subs->channels_max;
122         uinfo->value.integer.min = 0;
123         uinfo->value.integer.max = SNDRV_CHMAP_LAST;
124         return 0;
125 }
126
127 /* check whether a duplicated entry exists in the audiofmt list */
128 static bool have_dup_chmap(struct snd_usb_substream *subs,
129                            struct audioformat *fp)
130 {
131         struct audioformat *prev = fp;
132
133         list_for_each_entry_continue_reverse(prev, &subs->fmt_list, list) {
134                 if (prev->chmap &&
135                     !memcmp(prev->chmap, fp->chmap, sizeof(*fp->chmap)))
136                         return true;
137         }
138         return false;
139 }
140
141 static int usb_chmap_ctl_tlv(struct snd_kcontrol *kcontrol, int op_flag,
142                              unsigned int size, unsigned int __user *tlv)
143 {
144         struct snd_pcm_chmap *info = snd_kcontrol_chip(kcontrol);
145         struct snd_usb_substream *subs = info->private_data;
146         struct audioformat *fp;
147         unsigned int __user *dst;
148         int count = 0;
149
150         if (size < 8)
151                 return -ENOMEM;
152         if (put_user(SNDRV_CTL_TLVT_CONTAINER, tlv))
153                 return -EFAULT;
154         size -= 8;
155         dst = tlv + 2;
156         list_for_each_entry(fp, &subs->fmt_list, list) {
157                 int i, ch_bytes;
158
159                 if (!fp->chmap)
160                         continue;
161                 if (have_dup_chmap(subs, fp))
162                         continue;
163                 /* copy the entry */
164                 ch_bytes = fp->chmap->channels * 4;
165                 if (size < 8 + ch_bytes)
166                         return -ENOMEM;
167                 if (put_user(SNDRV_CTL_TLVT_CHMAP_FIXED, dst) ||
168                     put_user(ch_bytes, dst + 1))
169                         return -EFAULT;
170                 dst += 2;
171                 for (i = 0; i < fp->chmap->channels; i++, dst++) {
172                         if (put_user(fp->chmap->map[i], dst))
173                                 return -EFAULT;
174                 }
175
176                 count += 8 + ch_bytes;
177                 size -= 8 + ch_bytes;
178         }
179         if (put_user(count, tlv + 1))
180                 return -EFAULT;
181         return 0;
182 }
183
184 static int usb_chmap_ctl_get(struct snd_kcontrol *kcontrol,
185                              struct snd_ctl_elem_value *ucontrol)
186 {
187         struct snd_pcm_chmap *info = snd_kcontrol_chip(kcontrol);
188         struct snd_usb_substream *subs = info->private_data;
189         struct snd_pcm_chmap_elem *chmap = NULL;
190         int i;
191
192         memset(ucontrol->value.integer.value, 0,
193                sizeof(ucontrol->value.integer.value));
194         if (subs->cur_audiofmt)
195                 chmap = subs->cur_audiofmt->chmap;
196         if (chmap) {
197                 for (i = 0; i < chmap->channels; i++)
198                         ucontrol->value.integer.value[i] = chmap->map[i];
199         }
200         return 0;
201 }
202
203 /* create a chmap kctl assigned to the given USB substream */
204 static int add_chmap(struct snd_pcm *pcm, int stream,
205                      struct snd_usb_substream *subs)
206 {
207         struct audioformat *fp;
208         struct snd_pcm_chmap *chmap;
209         struct snd_kcontrol *kctl;
210         int err;
211
212         list_for_each_entry(fp, &subs->fmt_list, list)
213                 if (fp->chmap)
214                         goto ok;
215         /* no chmap is found */
216         return 0;
217
218  ok:
219         err = snd_pcm_add_chmap_ctls(pcm, stream, NULL, 0, 0, &chmap);
220         if (err < 0)
221                 return err;
222
223         /* override handlers */
224         chmap->private_data = subs;
225         kctl = chmap->kctl;
226         kctl->info = usb_chmap_ctl_info;
227         kctl->get = usb_chmap_ctl_get;
228         kctl->tlv.c = usb_chmap_ctl_tlv;
229
230         return 0;
231 }
232
233 /* convert from USB ChannelConfig bits to ALSA chmap element */
234 static struct snd_pcm_chmap_elem *convert_chmap(int channels, unsigned int bits,
235                                                 int protocol)
236 {
237         static unsigned int uac1_maps[] = {
238                 SNDRV_CHMAP_FL,         /* left front */
239                 SNDRV_CHMAP_FR,         /* right front */
240                 SNDRV_CHMAP_FC,         /* center front */
241                 SNDRV_CHMAP_LFE,        /* LFE */
242                 SNDRV_CHMAP_SL,         /* left surround */
243                 SNDRV_CHMAP_SR,         /* right surround */
244                 SNDRV_CHMAP_FLC,        /* left of center */
245                 SNDRV_CHMAP_FRC,        /* right of center */
246                 SNDRV_CHMAP_RC,         /* surround */
247                 SNDRV_CHMAP_SL,         /* side left */
248                 SNDRV_CHMAP_SR,         /* side right */
249                 SNDRV_CHMAP_TC,         /* top */
250                 0 /* terminator */
251         };
252         static unsigned int uac2_maps[] = {
253                 SNDRV_CHMAP_FL,         /* front left */
254                 SNDRV_CHMAP_FR,         /* front right */
255                 SNDRV_CHMAP_FC,         /* front center */
256                 SNDRV_CHMAP_LFE,        /* LFE */
257                 SNDRV_CHMAP_RL,         /* back left */
258                 SNDRV_CHMAP_RR,         /* back right */
259                 SNDRV_CHMAP_FLC,        /* front left of center */
260                 SNDRV_CHMAP_FRC,        /* front right of center */
261                 SNDRV_CHMAP_RC,         /* back center */
262                 SNDRV_CHMAP_SL,         /* side left */
263                 SNDRV_CHMAP_SR,         /* side right */
264                 SNDRV_CHMAP_TC,         /* top center */
265                 SNDRV_CHMAP_TFL,        /* top front left */
266                 SNDRV_CHMAP_TFC,        /* top front center */
267                 SNDRV_CHMAP_TFR,        /* top front right */
268                 SNDRV_CHMAP_TRL,        /* top back left */
269                 SNDRV_CHMAP_TRC,        /* top back center */
270                 SNDRV_CHMAP_TRR,        /* top back right */
271                 SNDRV_CHMAP_TFLC,       /* top front left of center */
272                 SNDRV_CHMAP_TFRC,       /* top front right of center */
273                 SNDRV_CHMAP_LLFE,       /* left LFE */
274                 SNDRV_CHMAP_RLFE,       /* right LFE */
275                 SNDRV_CHMAP_TSL,        /* top side left */
276                 SNDRV_CHMAP_TSR,        /* top side right */
277                 SNDRV_CHMAP_BC,         /* bottom center */
278                 SNDRV_CHMAP_RLC,        /* back left of center */
279                 SNDRV_CHMAP_RRC,        /* back right of center */
280                 0 /* terminator */
281         };
282         struct snd_pcm_chmap_elem *chmap;
283         const unsigned int *maps;
284         int c;
285
286         if (channels > ARRAY_SIZE(chmap->map))
287                 return NULL;
288
289         chmap = kzalloc(sizeof(*chmap), GFP_KERNEL);
290         if (!chmap)
291                 return NULL;
292
293         maps = protocol == UAC_VERSION_2 ? uac2_maps : uac1_maps;
294         chmap->channels = channels;
295         c = 0;
296
297         if (bits) {
298                 for (; bits && *maps; maps++, bits >>= 1)
299                         if (bits & 1)
300                                 chmap->map[c++] = *maps;
301         } else {
302                 /* If we're missing wChannelConfig, then guess something
303                     to make sure the channel map is not skipped entirely */
304                 if (channels == 1)
305                         chmap->map[c++] = SNDRV_CHMAP_MONO;
306                 else
307                         for (; c < channels && *maps; maps++)
308                                 chmap->map[c++] = *maps;
309         }
310
311         for (; c < channels; c++)
312                 chmap->map[c] = SNDRV_CHMAP_UNKNOWN;
313
314         return chmap;
315 }
316
317 /* UAC3 device stores channels information in Cluster Descriptors */
318 static struct
319 snd_pcm_chmap_elem *convert_chmap_v3(struct uac3_cluster_header_descriptor
320                                                                 *cluster)
321 {
322         unsigned int channels = cluster->bNrChannels;
323         struct snd_pcm_chmap_elem *chmap;
324         void *p = cluster;
325         int len, c;
326
327         if (channels > ARRAY_SIZE(chmap->map))
328                 return NULL;
329
330         chmap = kzalloc(sizeof(*chmap), GFP_KERNEL);
331         if (!chmap)
332                 return NULL;
333
334         len = le16_to_cpu(cluster->wLength);
335         c = 0;
336         p += sizeof(struct uac3_cluster_header_descriptor);
337
338         while (((p - (void *)cluster) < len) && (c < channels)) {
339                 struct uac3_cluster_segment_descriptor *cs_desc = p;
340                 u16 cs_len;
341                 u8 cs_type;
342
343                 cs_len = le16_to_cpu(cs_desc->wLength);
344                 cs_type = cs_desc->bSegmentType;
345
346                 if (cs_type == UAC3_CHANNEL_INFORMATION) {
347                         struct uac3_cluster_information_segment_descriptor *is = p;
348                         unsigned char map;
349
350                         /*
351                          * TODO: this conversion is not complete, update it
352                          * after adding UAC3 values to asound.h
353                          */
354                         switch (is->bChRelationship) {
355                         case UAC3_CH_MONO:
356                                 map = SNDRV_CHMAP_MONO;
357                                 break;
358                         case UAC3_CH_LEFT:
359                         case UAC3_CH_FRONT_LEFT:
360                         case UAC3_CH_HEADPHONE_LEFT:
361                                 map = SNDRV_CHMAP_FL;
362                                 break;
363                         case UAC3_CH_RIGHT:
364                         case UAC3_CH_FRONT_RIGHT:
365                         case UAC3_CH_HEADPHONE_RIGHT:
366                                 map = SNDRV_CHMAP_FR;
367                                 break;
368                         case UAC3_CH_FRONT_CENTER:
369                                 map = SNDRV_CHMAP_FC;
370                                 break;
371                         case UAC3_CH_FRONT_LEFT_OF_CENTER:
372                                 map = SNDRV_CHMAP_FLC;
373                                 break;
374                         case UAC3_CH_FRONT_RIGHT_OF_CENTER:
375                                 map = SNDRV_CHMAP_FRC;
376                                 break;
377                         case UAC3_CH_SIDE_LEFT:
378                                 map = SNDRV_CHMAP_SL;
379                                 break;
380                         case UAC3_CH_SIDE_RIGHT:
381                                 map = SNDRV_CHMAP_SR;
382                                 break;
383                         case UAC3_CH_BACK_LEFT:
384                                 map = SNDRV_CHMAP_RL;
385                                 break;
386                         case UAC3_CH_BACK_RIGHT:
387                                 map = SNDRV_CHMAP_RR;
388                                 break;
389                         case UAC3_CH_BACK_CENTER:
390                                 map = SNDRV_CHMAP_RC;
391                                 break;
392                         case UAC3_CH_BACK_LEFT_OF_CENTER:
393                                 map = SNDRV_CHMAP_RLC;
394                                 break;
395                         case UAC3_CH_BACK_RIGHT_OF_CENTER:
396                                 map = SNDRV_CHMAP_RRC;
397                                 break;
398                         case UAC3_CH_TOP_CENTER:
399                                 map = SNDRV_CHMAP_TC;
400                                 break;
401                         case UAC3_CH_TOP_FRONT_LEFT:
402                                 map = SNDRV_CHMAP_TFL;
403                                 break;
404                         case UAC3_CH_TOP_FRONT_RIGHT:
405                                 map = SNDRV_CHMAP_TFR;
406                                 break;
407                         case UAC3_CH_TOP_FRONT_CENTER:
408                                 map = SNDRV_CHMAP_TFC;
409                                 break;
410                         case UAC3_CH_TOP_FRONT_LOC:
411                                 map = SNDRV_CHMAP_TFLC;
412                                 break;
413                         case UAC3_CH_TOP_FRONT_ROC:
414                                 map = SNDRV_CHMAP_TFRC;
415                                 break;
416                         case UAC3_CH_TOP_SIDE_LEFT:
417                                 map = SNDRV_CHMAP_TSL;
418                                 break;
419                         case UAC3_CH_TOP_SIDE_RIGHT:
420                                 map = SNDRV_CHMAP_TSR;
421                                 break;
422                         case UAC3_CH_TOP_BACK_LEFT:
423                                 map = SNDRV_CHMAP_TRL;
424                                 break;
425                         case UAC3_CH_TOP_BACK_RIGHT:
426                                 map = SNDRV_CHMAP_TRR;
427                                 break;
428                         case UAC3_CH_TOP_BACK_CENTER:
429                                 map = SNDRV_CHMAP_TRC;
430                                 break;
431                         case UAC3_CH_BOTTOM_CENTER:
432                                 map = SNDRV_CHMAP_BC;
433                                 break;
434                         case UAC3_CH_LOW_FREQUENCY_EFFECTS:
435                                 map = SNDRV_CHMAP_LFE;
436                                 break;
437                         case UAC3_CH_LFE_LEFT:
438                                 map = SNDRV_CHMAP_LLFE;
439                                 break;
440                         case UAC3_CH_LFE_RIGHT:
441                                 map = SNDRV_CHMAP_RLFE;
442                                 break;
443                         case UAC3_CH_RELATIONSHIP_UNDEFINED:
444                         default:
445                                 map = SNDRV_CHMAP_UNKNOWN;
446                                 break;
447                         }
448                         chmap->map[c++] = map;
449                 }
450                 p += cs_len;
451         }
452
453         if (channels < c)
454                 pr_err("%s: channel number mismatch\n", __func__);
455
456         chmap->channels = channels;
457
458         for (; c < channels; c++)
459                 chmap->map[c] = SNDRV_CHMAP_UNKNOWN;
460
461         return chmap;
462 }
463
464 /*
465  * add this endpoint to the chip instance.
466  * if a stream with the same endpoint already exists, append to it.
467  * if not, create a new pcm stream. note, fp is added to the substream
468  * fmt_list and will be freed on the chip instance release. do not free
469  * fp or do remove it from the substream fmt_list to avoid double-free.
470  */
471 int snd_usb_add_audio_stream(struct snd_usb_audio *chip,
472                              int stream,
473                              struct audioformat *fp)
474 {
475         struct snd_usb_stream *as;
476         struct snd_usb_substream *subs;
477         struct snd_pcm *pcm;
478         int err;
479
480         list_for_each_entry(as, &chip->pcm_list, list) {
481                 if (as->fmt_type != fp->fmt_type)
482                         continue;
483                 subs = &as->substream[stream];
484                 if (subs->ep_num == fp->endpoint) {
485                         list_add_tail(&fp->list, &subs->fmt_list);
486                         subs->num_formats++;
487                         subs->formats |= fp->formats;
488                         return 0;
489                 }
490         }
491         /* look for an empty stream */
492         list_for_each_entry(as, &chip->pcm_list, list) {
493                 if (as->fmt_type != fp->fmt_type)
494                         continue;
495                 subs = &as->substream[stream];
496                 if (subs->ep_num)
497                         continue;
498                 err = snd_pcm_new_stream(as->pcm, stream, 1);
499                 if (err < 0)
500                         return err;
501                 snd_usb_init_substream(as, stream, fp);
502                 return add_chmap(as->pcm, stream, subs);
503         }
504
505         /* create a new pcm */
506         as = kzalloc(sizeof(*as), GFP_KERNEL);
507         if (!as)
508                 return -ENOMEM;
509         as->pcm_index = chip->pcm_devs;
510         as->chip = chip;
511         as->fmt_type = fp->fmt_type;
512         err = snd_pcm_new(chip->card, "USB Audio", chip->pcm_devs,
513                           stream == SNDRV_PCM_STREAM_PLAYBACK ? 1 : 0,
514                           stream == SNDRV_PCM_STREAM_PLAYBACK ? 0 : 1,
515                           &pcm);
516         if (err < 0) {
517                 kfree(as);
518                 return err;
519         }
520         as->pcm = pcm;
521         pcm->private_data = as;
522         pcm->private_free = snd_usb_audio_pcm_free;
523         pcm->info_flags = 0;
524         if (chip->pcm_devs > 0)
525                 sprintf(pcm->name, "USB Audio #%d", chip->pcm_devs);
526         else
527                 strcpy(pcm->name, "USB Audio");
528
529         snd_usb_init_substream(as, stream, fp);
530
531         /*
532          * Keep using head insertion for M-Audio Audiophile USB (tm) which has a
533          * fix to swap capture stream order in conf/cards/USB-audio.conf
534          */
535         if (chip->usb_id == USB_ID(0x0763, 0x2003))
536                 list_add(&as->list, &chip->pcm_list);
537         else
538                 list_add_tail(&as->list, &chip->pcm_list);
539
540         chip->pcm_devs++;
541
542         snd_usb_proc_pcm_format_add(as);
543
544         return add_chmap(pcm, stream, &as->substream[stream]);
545 }
546
547 static int parse_uac_endpoint_attributes(struct snd_usb_audio *chip,
548                                          struct usb_host_interface *alts,
549                                          int protocol, int iface_no)
550 {
551         /* parsed with a v1 header here. that's ok as we only look at the
552          * header first which is the same for both versions */
553         struct uac_iso_endpoint_descriptor *csep;
554         struct usb_interface_descriptor *altsd = get_iface_desc(alts);
555         int attributes = 0;
556
557         csep = snd_usb_find_desc(alts->endpoint[0].extra, alts->endpoint[0].extralen, NULL, USB_DT_CS_ENDPOINT);
558
559         /* Creamware Noah has this descriptor after the 2nd endpoint */
560         if (!csep && altsd->bNumEndpoints >= 2)
561                 csep = snd_usb_find_desc(alts->endpoint[1].extra, alts->endpoint[1].extralen, NULL, USB_DT_CS_ENDPOINT);
562
563         /*
564          * If we can't locate the USB_DT_CS_ENDPOINT descriptor in the extra
565          * bytes after the first endpoint, go search the entire interface.
566          * Some devices have it directly *before* the standard endpoint.
567          */
568         if (!csep)
569                 csep = snd_usb_find_desc(alts->extra, alts->extralen, NULL, USB_DT_CS_ENDPOINT);
570
571         if (!csep || csep->bLength < 7 ||
572             csep->bDescriptorSubtype != UAC_EP_GENERAL) {
573                 usb_audio_warn(chip,
574                                "%u:%d : no or invalid class specific endpoint descriptor\n",
575                                iface_no, altsd->bAlternateSetting);
576                 return 0;
577         }
578
579         if (protocol == UAC_VERSION_1) {
580                 attributes = csep->bmAttributes;
581         } else if (protocol == UAC_VERSION_2) {
582                 struct uac2_iso_endpoint_descriptor *csep2 =
583                         (struct uac2_iso_endpoint_descriptor *) csep;
584
585                 attributes = csep->bmAttributes & UAC_EP_CS_ATTR_FILL_MAX;
586
587                 /* emulate the endpoint attributes of a v1 device */
588                 if (csep2->bmControls & UAC2_CONTROL_PITCH)
589                         attributes |= UAC_EP_CS_ATTR_PITCH_CONTROL;
590         } else { /* UAC_VERSION_3 */
591                 struct uac3_iso_endpoint_descriptor *csep3 =
592                         (struct uac3_iso_endpoint_descriptor *) csep;
593
594                 /* emulate the endpoint attributes of a v1 device */
595                 if (le32_to_cpu(csep3->bmControls) & UAC2_CONTROL_PITCH)
596                         attributes |= UAC_EP_CS_ATTR_PITCH_CONTROL;
597         }
598
599         return attributes;
600 }
601
602 /* find an input terminal descriptor (either UAC1 or UAC2) with the given
603  * terminal id
604  */
605 static void *
606 snd_usb_find_input_terminal_descriptor(struct usb_host_interface *ctrl_iface,
607                                                int terminal_id)
608 {
609         struct uac2_input_terminal_descriptor *term = NULL;
610
611         while ((term = snd_usb_find_csint_desc(ctrl_iface->extra,
612                                                ctrl_iface->extralen,
613                                                term, UAC_INPUT_TERMINAL))) {
614                 if (term->bTerminalID == terminal_id)
615                         return term;
616         }
617
618         return NULL;
619 }
620
621 static void *
622 snd_usb_find_output_terminal_descriptor(struct usb_host_interface *ctrl_iface,
623                                         int terminal_id)
624 {
625         /* OK to use with both UAC2 and UAC3 */
626         struct uac2_output_terminal_descriptor *term = NULL;
627
628         while ((term = snd_usb_find_csint_desc(ctrl_iface->extra,
629                                                ctrl_iface->extralen,
630                                                term, UAC_OUTPUT_TERMINAL))) {
631                 if (term->bTerminalID == terminal_id)
632                         return term;
633         }
634
635         return NULL;
636 }
637
638 static struct audioformat *
639 audio_format_alloc_init(struct snd_usb_audio *chip,
640                        struct usb_host_interface *alts,
641                        int protocol, int iface_no, int altset_idx,
642                        int altno, int num_channels, int clock)
643 {
644         struct audioformat *fp;
645
646         fp = kzalloc(sizeof(*fp), GFP_KERNEL);
647         if (!fp)
648                 return NULL;
649
650         fp->iface = iface_no;
651         fp->altsetting = altno;
652         fp->altset_idx = altset_idx;
653         fp->endpoint = get_endpoint(alts, 0)->bEndpointAddress;
654         fp->ep_attr = get_endpoint(alts, 0)->bmAttributes;
655         fp->datainterval = snd_usb_parse_datainterval(chip, alts);
656         fp->protocol = protocol;
657         fp->maxpacksize = le16_to_cpu(get_endpoint(alts, 0)->wMaxPacketSize);
658         fp->channels = num_channels;
659         if (snd_usb_get_speed(chip->dev) == USB_SPEED_HIGH)
660                 fp->maxpacksize = (((fp->maxpacksize >> 11) & 3) + 1)
661                                 * (fp->maxpacksize & 0x7ff);
662         fp->clock = clock;
663         INIT_LIST_HEAD(&fp->list);
664
665         return fp;
666 }
667
668 static struct audioformat *
669 snd_usb_get_audioformat_uac12(struct snd_usb_audio *chip,
670                               struct usb_host_interface *alts,
671                               int protocol, int iface_no, int altset_idx,
672                               int altno, int stream, int bm_quirk)
673 {
674         struct usb_device *dev = chip->dev;
675         struct uac_format_type_i_continuous_descriptor *fmt;
676         unsigned int num_channels = 0, chconfig = 0;
677         struct audioformat *fp;
678         int clock = 0;
679         u64 format;
680
681         /* get audio formats */
682         if (protocol == UAC_VERSION_1) {
683                 struct uac1_as_header_descriptor *as =
684                         snd_usb_find_csint_desc(alts->extra, alts->extralen,
685                                                 NULL, UAC_AS_GENERAL);
686                 struct uac_input_terminal_descriptor *iterm;
687
688                 if (!as) {
689                         dev_err(&dev->dev,
690                                 "%u:%d : UAC_AS_GENERAL descriptor not found\n",
691                                 iface_no, altno);
692                         return NULL;
693                 }
694
695                 if (as->bLength < sizeof(*as)) {
696                         dev_err(&dev->dev,
697                                 "%u:%d : invalid UAC_AS_GENERAL desc\n",
698                                 iface_no, altno);
699                         return NULL;
700                 }
701
702                 format = le16_to_cpu(as->wFormatTag); /* remember the format value */
703
704                 iterm = snd_usb_find_input_terminal_descriptor(chip->ctrl_intf,
705                                                              as->bTerminalLink);
706                 if (iterm) {
707                         num_channels = iterm->bNrChannels;
708                         chconfig = le16_to_cpu(iterm->wChannelConfig);
709                 }
710         } else { /* UAC_VERSION_2 */
711                 struct uac2_input_terminal_descriptor *input_term;
712                 struct uac2_output_terminal_descriptor *output_term;
713                 struct uac2_as_header_descriptor *as =
714                         snd_usb_find_csint_desc(alts->extra, alts->extralen,
715                                                 NULL, UAC_AS_GENERAL);
716
717                 if (!as) {
718                         dev_err(&dev->dev,
719                                 "%u:%d : UAC_AS_GENERAL descriptor not found\n",
720                                 iface_no, altno);
721                         return NULL;
722                 }
723
724                 if (as->bLength < sizeof(*as)) {
725                         dev_err(&dev->dev,
726                                 "%u:%d : invalid UAC_AS_GENERAL desc\n",
727                                 iface_no, altno);
728                         return NULL;
729                 }
730
731                 num_channels = as->bNrChannels;
732                 format = le32_to_cpu(as->bmFormats);
733                 chconfig = le32_to_cpu(as->bmChannelConfig);
734
735                 /*
736                  * lookup the terminal associated to this interface
737                  * to extract the clock
738                  */
739                 input_term = snd_usb_find_input_terminal_descriptor(chip->ctrl_intf,
740                                                                     as->bTerminalLink);
741                 if (input_term) {
742                         clock = input_term->bCSourceID;
743                         if (!chconfig && (num_channels == input_term->bNrChannels))
744                                 chconfig = le32_to_cpu(input_term->bmChannelConfig);
745                         goto found_clock;
746                 }
747
748                 output_term = snd_usb_find_output_terminal_descriptor(chip->ctrl_intf,
749                                                                       as->bTerminalLink);
750                 if (output_term) {
751                         clock = output_term->bCSourceID;
752                         goto found_clock;
753                 }
754
755                 dev_err(&dev->dev,
756                         "%u:%d : bogus bTerminalLink %d\n",
757                         iface_no, altno, as->bTerminalLink);
758                 return NULL;
759         }
760
761 found_clock:
762         /* get format type */
763         fmt = snd_usb_find_csint_desc(alts->extra, alts->extralen,
764                                       NULL, UAC_FORMAT_TYPE);
765         if (!fmt) {
766                 dev_err(&dev->dev,
767                         "%u:%d : no UAC_FORMAT_TYPE desc\n",
768                         iface_no, altno);
769                 return NULL;
770         }
771         if (((protocol == UAC_VERSION_1) && (fmt->bLength < 8))
772                         || ((protocol == UAC_VERSION_2) &&
773                                         (fmt->bLength < 6))) {
774                 dev_err(&dev->dev,
775                         "%u:%d : invalid UAC_FORMAT_TYPE desc\n",
776                         iface_no, altno);
777                 return NULL;
778         }
779
780         /*
781          * Blue Microphones workaround: The last altsetting is
782          * identical with the previous one, except for a larger
783          * packet size, but is actually a mislabeled two-channel
784          * setting; ignore it.
785          *
786          * Part 2: analyze quirk flag and format
787          */
788         if (bm_quirk && fmt->bNrChannels == 1 && fmt->bSubframeSize == 2)
789                 return NULL;
790
791         fp = audio_format_alloc_init(chip, alts, protocol, iface_no,
792                                      altset_idx, altno, num_channels, clock);
793         if (!fp)
794                 return ERR_PTR(-ENOMEM);
795
796         fp->attributes = parse_uac_endpoint_attributes(chip, alts, protocol,
797                                                        iface_no);
798
799         /* some quirks for attributes here */
800         snd_usb_audioformat_attributes_quirk(chip, fp, stream);
801
802         /* ok, let's parse further... */
803         if (snd_usb_parse_audio_format(chip, fp, format,
804                                         fmt, stream) < 0) {
805                 kfree(fp->rate_table);
806                 kfree(fp);
807                 return NULL;
808         }
809
810         /* Create chmap */
811         if (fp->channels != num_channels)
812                 chconfig = 0;
813
814         fp->chmap = convert_chmap(fp->channels, chconfig, protocol);
815
816         return fp;
817 }
818
819 static struct audioformat *
820 snd_usb_get_audioformat_uac3(struct snd_usb_audio *chip,
821                              struct usb_host_interface *alts,
822                              int iface_no, int altset_idx,
823                              int altno, int stream)
824 {
825         struct usb_device *dev = chip->dev;
826         struct uac3_input_terminal_descriptor *input_term;
827         struct uac3_output_terminal_descriptor *output_term;
828         struct uac3_cluster_header_descriptor *cluster;
829         struct uac3_as_header_descriptor *as = NULL;
830         struct uac3_hc_descriptor_header hc_header;
831         struct snd_pcm_chmap_elem *chmap;
832         unsigned char badd_profile;
833         u64 badd_formats = 0;
834         unsigned int num_channels;
835         struct audioformat *fp;
836         u16 cluster_id, wLength;
837         int clock = 0;
838         int err;
839
840         badd_profile = chip->badd_profile;
841
842         if (badd_profile >= UAC3_FUNCTION_SUBCLASS_GENERIC_IO) {
843                 unsigned int maxpacksize =
844                         le16_to_cpu(get_endpoint(alts, 0)->wMaxPacketSize);
845
846                 switch (maxpacksize) {
847                 default:
848                         dev_err(&dev->dev,
849                                 "%u:%d : incorrect wMaxPacketSize for BADD profile\n",
850                                 iface_no, altno);
851                         return NULL;
852                 case UAC3_BADD_EP_MAXPSIZE_SYNC_MONO_16:
853                 case UAC3_BADD_EP_MAXPSIZE_ASYNC_MONO_16:
854                         badd_formats = SNDRV_PCM_FMTBIT_S16_LE;
855                         num_channels = 1;
856                         break;
857                 case UAC3_BADD_EP_MAXPSIZE_SYNC_MONO_24:
858                 case UAC3_BADD_EP_MAXPSIZE_ASYNC_MONO_24:
859                         badd_formats = SNDRV_PCM_FMTBIT_S24_3LE;
860                         num_channels = 1;
861                         break;
862                 case UAC3_BADD_EP_MAXPSIZE_SYNC_STEREO_16:
863                 case UAC3_BADD_EP_MAXPSIZE_ASYNC_STEREO_16:
864                         badd_formats = SNDRV_PCM_FMTBIT_S16_LE;
865                         num_channels = 2;
866                         break;
867                 case UAC3_BADD_EP_MAXPSIZE_SYNC_STEREO_24:
868                 case UAC3_BADD_EP_MAXPSIZE_ASYNC_STEREO_24:
869                         badd_formats = SNDRV_PCM_FMTBIT_S24_3LE;
870                         num_channels = 2;
871                         break;
872                 }
873
874                 chmap = kzalloc(sizeof(*chmap), GFP_KERNEL);
875                 if (!chmap)
876                         return ERR_PTR(-ENOMEM);
877
878                 if (num_channels == 1) {
879                         chmap->map[0] = SNDRV_CHMAP_MONO;
880                 } else {
881                         chmap->map[0] = SNDRV_CHMAP_FL;
882                         chmap->map[1] = SNDRV_CHMAP_FR;
883                 }
884
885                 chmap->channels = num_channels;
886                 clock = UAC3_BADD_CS_ID9;
887                 goto found_clock;
888         }
889
890         as = snd_usb_find_csint_desc(alts->extra, alts->extralen,
891                                      NULL, UAC_AS_GENERAL);
892         if (!as) {
893                 dev_err(&dev->dev,
894                         "%u:%d : UAC_AS_GENERAL descriptor not found\n",
895                         iface_no, altno);
896                 return NULL;
897         }
898
899         if (as->bLength < sizeof(*as)) {
900                 dev_err(&dev->dev,
901                         "%u:%d : invalid UAC_AS_GENERAL desc\n",
902                         iface_no, altno);
903                 return NULL;
904         }
905
906         cluster_id = le16_to_cpu(as->wClusterDescrID);
907         if (!cluster_id) {
908                 dev_err(&dev->dev,
909                         "%u:%d : no cluster descriptor\n",
910                         iface_no, altno);
911                 return NULL;
912         }
913
914         /*
915          * Get number of channels and channel map through
916          * High Capability Cluster Descriptor
917          *
918          * First step: get High Capability header and
919          * read size of Cluster Descriptor
920          */
921         err = snd_usb_ctl_msg(chip->dev,
922                         usb_rcvctrlpipe(chip->dev, 0),
923                         UAC3_CS_REQ_HIGH_CAPABILITY_DESCRIPTOR,
924                         USB_RECIP_INTERFACE | USB_TYPE_CLASS | USB_DIR_IN,
925                         cluster_id,
926                         snd_usb_ctrl_intf(chip),
927                         &hc_header, sizeof(hc_header));
928         if (err < 0)
929                 return ERR_PTR(err);
930         else if (err != sizeof(hc_header)) {
931                 dev_err(&dev->dev,
932                         "%u:%d : can't get High Capability descriptor\n",
933                         iface_no, altno);
934                 return ERR_PTR(-EIO);
935         }
936
937         /*
938          * Second step: allocate needed amount of memory
939          * and request Cluster Descriptor
940          */
941         wLength = le16_to_cpu(hc_header.wLength);
942         cluster = kzalloc(wLength, GFP_KERNEL);
943         if (!cluster)
944                 return ERR_PTR(-ENOMEM);
945         err = snd_usb_ctl_msg(chip->dev,
946                         usb_rcvctrlpipe(chip->dev, 0),
947                         UAC3_CS_REQ_HIGH_CAPABILITY_DESCRIPTOR,
948                         USB_RECIP_INTERFACE | USB_TYPE_CLASS | USB_DIR_IN,
949                         cluster_id,
950                         snd_usb_ctrl_intf(chip),
951                         cluster, wLength);
952         if (err < 0) {
953                 kfree(cluster);
954                 return ERR_PTR(err);
955         } else if (err != wLength) {
956                 dev_err(&dev->dev,
957                         "%u:%d : can't get Cluster Descriptor\n",
958                         iface_no, altno);
959                 kfree(cluster);
960                 return ERR_PTR(-EIO);
961         }
962
963         num_channels = cluster->bNrChannels;
964         chmap = convert_chmap_v3(cluster);
965         kfree(cluster);
966
967         /*
968          * lookup the terminal associated to this interface
969          * to extract the clock
970          */
971         input_term = snd_usb_find_input_terminal_descriptor(chip->ctrl_intf,
972                                                             as->bTerminalLink);
973         if (input_term) {
974                 clock = input_term->bCSourceID;
975                 goto found_clock;
976         }
977
978         output_term = snd_usb_find_output_terminal_descriptor(chip->ctrl_intf,
979                                                              as->bTerminalLink);
980         if (output_term) {
981                 clock = output_term->bCSourceID;
982                 goto found_clock;
983         }
984
985         dev_err(&dev->dev, "%u:%d : bogus bTerminalLink %d\n",
986                         iface_no, altno, as->bTerminalLink);
987         kfree(chmap);
988         return NULL;
989
990 found_clock:
991         fp = audio_format_alloc_init(chip, alts, UAC_VERSION_3, iface_no,
992                                      altset_idx, altno, num_channels, clock);
993         if (!fp) {
994                 kfree(chmap);
995                 return ERR_PTR(-ENOMEM);
996         }
997
998         fp->chmap = chmap;
999
1000         if (badd_profile >= UAC3_FUNCTION_SUBCLASS_GENERIC_IO) {
1001                 fp->attributes = 0; /* No attributes */
1002
1003                 fp->fmt_type = UAC_FORMAT_TYPE_I;
1004                 fp->formats = badd_formats;
1005
1006                 fp->nr_rates = 0;       /* SNDRV_PCM_RATE_CONTINUOUS */
1007                 fp->rate_min = UAC3_BADD_SAMPLING_RATE;
1008                 fp->rate_max = UAC3_BADD_SAMPLING_RATE;
1009                 fp->rates = SNDRV_PCM_RATE_CONTINUOUS;
1010
1011         } else {
1012                 fp->attributes = parse_uac_endpoint_attributes(chip, alts,
1013                                                                UAC_VERSION_3,
1014                                                                iface_no);
1015                 /* ok, let's parse further... */
1016                 if (snd_usb_parse_audio_format_v3(chip, fp, as, stream) < 0) {
1017                         kfree(fp->chmap);
1018                         kfree(fp->rate_table);
1019                         kfree(fp);
1020                         return NULL;
1021                 }
1022         }
1023
1024         return fp;
1025 }
1026
1027 int snd_usb_parse_audio_interface(struct snd_usb_audio *chip, int iface_no)
1028 {
1029         struct usb_device *dev;
1030         struct usb_interface *iface;
1031         struct usb_host_interface *alts;
1032         struct usb_interface_descriptor *altsd;
1033         int i, altno, err, stream;
1034         struct audioformat *fp = NULL;
1035         int num, protocol;
1036
1037         dev = chip->dev;
1038
1039         /* parse the interface's altsettings */
1040         iface = usb_ifnum_to_if(dev, iface_no);
1041
1042         num = iface->num_altsetting;
1043
1044         /*
1045          * Dallas DS4201 workaround: It presents 5 altsettings, but the last
1046          * one misses syncpipe, and does not produce any sound.
1047          */
1048         if (chip->usb_id == USB_ID(0x04fa, 0x4201))
1049                 num = 4;
1050
1051         for (i = 0; i < num; i++) {
1052                 alts = &iface->altsetting[i];
1053                 altsd = get_iface_desc(alts);
1054                 protocol = altsd->bInterfaceProtocol;
1055                 /* skip invalid one */
1056                 if (((altsd->bInterfaceClass != USB_CLASS_AUDIO ||
1057                       (altsd->bInterfaceSubClass != USB_SUBCLASS_AUDIOSTREAMING &&
1058                        altsd->bInterfaceSubClass != USB_SUBCLASS_VENDOR_SPEC)) &&
1059                      altsd->bInterfaceClass != USB_CLASS_VENDOR_SPEC) ||
1060                     altsd->bNumEndpoints < 1 ||
1061                     le16_to_cpu(get_endpoint(alts, 0)->wMaxPacketSize) == 0)
1062                         continue;
1063                 /* must be isochronous */
1064                 if ((get_endpoint(alts, 0)->bmAttributes & USB_ENDPOINT_XFERTYPE_MASK) !=
1065                     USB_ENDPOINT_XFER_ISOC)
1066                         continue;
1067                 /* check direction */
1068                 stream = (get_endpoint(alts, 0)->bEndpointAddress & USB_DIR_IN) ?
1069                         SNDRV_PCM_STREAM_CAPTURE : SNDRV_PCM_STREAM_PLAYBACK;
1070                 altno = altsd->bAlternateSetting;
1071
1072                 if (snd_usb_apply_interface_quirk(chip, iface_no, altno))
1073                         continue;
1074
1075                 /*
1076                  * Roland audio streaming interfaces are marked with protocols
1077                  * 0/1/2, but are UAC 1 compatible.
1078                  */
1079                 if (USB_ID_VENDOR(chip->usb_id) == 0x0582 &&
1080                     altsd->bInterfaceClass == USB_CLASS_VENDOR_SPEC &&
1081                     protocol <= 2)
1082                         protocol = UAC_VERSION_1;
1083
1084                 switch (protocol) {
1085                 default:
1086                         dev_dbg(&dev->dev, "%u:%d: unknown interface protocol %#02x, assuming v1\n",
1087                                 iface_no, altno, protocol);
1088                         protocol = UAC_VERSION_1;
1089                         /* fall through */
1090                 case UAC_VERSION_1:
1091                         /* fall through */
1092                 case UAC_VERSION_2: {
1093                         int bm_quirk = 0;
1094
1095                         /*
1096                          * Blue Microphones workaround: The last altsetting is
1097                          * identical with the previous one, except for a larger
1098                          * packet size, but is actually a mislabeled two-channel
1099                          * setting; ignore it.
1100                          *
1101                          * Part 1: prepare quirk flag
1102                          */
1103                         if (altno == 2 && num == 3 &&
1104                             fp && fp->altsetting == 1 && fp->channels == 1 &&
1105                             fp->formats == SNDRV_PCM_FMTBIT_S16_LE &&
1106                             protocol == UAC_VERSION_1 &&
1107                             le16_to_cpu(get_endpoint(alts, 0)->wMaxPacketSize) ==
1108                                                         fp->maxpacksize * 2)
1109                                 bm_quirk = 1;
1110
1111                         fp = snd_usb_get_audioformat_uac12(chip, alts, protocol,
1112                                                            iface_no, i, altno,
1113                                                            stream, bm_quirk);
1114                         break;
1115                 }
1116                 case UAC_VERSION_3:
1117                         fp = snd_usb_get_audioformat_uac3(chip, alts,
1118                                                 iface_no, i, altno, stream);
1119                         break;
1120                 }
1121
1122                 if (!fp)
1123                         continue;
1124                 else if (IS_ERR(fp))
1125                         return PTR_ERR(fp);
1126
1127                 dev_dbg(&dev->dev, "%u:%d: add audio endpoint %#x\n", iface_no, altno, fp->endpoint);
1128                 err = snd_usb_add_audio_stream(chip, stream, fp);
1129                 if (err < 0) {
1130                         list_del(&fp->list); /* unlink for avoiding double-free */
1131                         kfree(fp->rate_table);
1132                         kfree(fp->chmap);
1133                         kfree(fp);
1134                         return err;
1135                 }
1136                 /* try to set the interface... */
1137                 usb_set_interface(chip->dev, iface_no, altno);
1138                 snd_usb_init_pitch(chip, iface_no, alts, fp);
1139                 snd_usb_init_sample_rate(chip, iface_no, alts, fp, fp->rate_max);
1140         }
1141         return 0;
1142 }
1143