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