Merge tag 'for-linus-2019-08-17' of git://git.kernel.dk/linux-block
[sfrench/cifs-2.6.git] / sound / usb / stream.c
1 // SPDX-License-Identifier: GPL-2.0-or-later
2 /*
3  */
4
5
6 #include <linux/init.h>
7 #include <linux/slab.h>
8 #include <linux/usb.h>
9 #include <linux/usb/audio.h>
10 #include <linux/usb/audio-v2.h>
11 #include <linux/usb/audio-v3.h>
12
13 #include <sound/core.h>
14 #include <sound/pcm.h>
15 #include <sound/control.h>
16 #include <sound/tlv.h>
17
18 #include "usbaudio.h"
19 #include "card.h"
20 #include "proc.h"
21 #include "quirks.h"
22 #include "endpoint.h"
23 #include "pcm.h"
24 #include "helper.h"
25 #include "format.h"
26 #include "clock.h"
27 #include "stream.h"
28 #include "power.h"
29 #include "media.h"
30
31 /*
32  * free a substream
33  */
34 static void free_substream(struct snd_usb_substream *subs)
35 {
36         struct audioformat *fp, *n;
37
38         if (!subs->num_formats)
39                 return; /* not initialized */
40         list_for_each_entry_safe(fp, n, &subs->fmt_list, list) {
41                 kfree(fp->rate_table);
42                 kfree(fp->chmap);
43                 kfree(fp);
44         }
45         kfree(subs->rate_list.list);
46         kfree(subs->str_pd);
47         snd_media_stream_delete(subs);
48 }
49
50
51 /*
52  * free a usb stream instance
53  */
54 static void snd_usb_audio_stream_free(struct snd_usb_stream *stream)
55 {
56         free_substream(&stream->substream[0]);
57         free_substream(&stream->substream[1]);
58         list_del(&stream->list);
59         kfree(stream);
60 }
61
62 static void snd_usb_audio_pcm_free(struct snd_pcm *pcm)
63 {
64         struct snd_usb_stream *stream = pcm->private_data;
65         if (stream) {
66                 stream->pcm = NULL;
67                 snd_usb_audio_stream_free(stream);
68         }
69 }
70
71 /*
72  * initialize the substream instance.
73  */
74
75 static void snd_usb_init_substream(struct snd_usb_stream *as,
76                                    int stream,
77                                    struct audioformat *fp,
78                                    struct snd_usb_power_domain *pd)
79 {
80         struct snd_usb_substream *subs = &as->substream[stream];
81
82         INIT_LIST_HEAD(&subs->fmt_list);
83         spin_lock_init(&subs->lock);
84
85         subs->stream = as;
86         subs->direction = stream;
87         subs->dev = as->chip->dev;
88         subs->txfr_quirk = as->chip->txfr_quirk;
89         subs->tx_length_quirk = as->chip->tx_length_quirk;
90         subs->speed = snd_usb_get_speed(subs->dev);
91         subs->pkt_offset_adj = 0;
92
93         snd_usb_set_pcm_ops(as->pcm, stream);
94
95         list_add_tail(&fp->list, &subs->fmt_list);
96         subs->formats |= fp->formats;
97         subs->num_formats++;
98         subs->fmt_type = fp->fmt_type;
99         subs->ep_num = fp->endpoint;
100         if (fp->channels > subs->channels_max)
101                 subs->channels_max = fp->channels;
102
103         if (pd) {
104                 subs->str_pd = pd;
105                 /* Initialize Power Domain to idle status D1 */
106                 snd_usb_power_domain_set(subs->stream->chip, pd,
107                                          UAC3_PD_STATE_D1);
108         }
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 static int __snd_usb_add_audio_stream(struct snd_usb_audio *chip,
472                                       int stream,
473                                       struct audioformat *fp,
474                                       struct snd_usb_power_domain *pd)
475
476 {
477         struct snd_usb_stream *as;
478         struct snd_usb_substream *subs;
479         struct snd_pcm *pcm;
480         int err;
481
482         list_for_each_entry(as, &chip->pcm_list, list) {
483                 if (as->fmt_type != fp->fmt_type)
484                         continue;
485                 subs = &as->substream[stream];
486                 if (subs->ep_num == fp->endpoint) {
487                         list_add_tail(&fp->list, &subs->fmt_list);
488                         subs->num_formats++;
489                         subs->formats |= fp->formats;
490                         return 0;
491                 }
492         }
493         /* look for an empty stream */
494         list_for_each_entry(as, &chip->pcm_list, list) {
495                 if (as->fmt_type != fp->fmt_type)
496                         continue;
497                 subs = &as->substream[stream];
498                 if (subs->ep_num)
499                         continue;
500                 err = snd_pcm_new_stream(as->pcm, stream, 1);
501                 if (err < 0)
502                         return err;
503                 snd_usb_init_substream(as, stream, fp, pd);
504                 return add_chmap(as->pcm, stream, subs);
505         }
506
507         /* create a new pcm */
508         as = kzalloc(sizeof(*as), GFP_KERNEL);
509         if (!as)
510                 return -ENOMEM;
511         as->pcm_index = chip->pcm_devs;
512         as->chip = chip;
513         as->fmt_type = fp->fmt_type;
514         err = snd_pcm_new(chip->card, "USB Audio", chip->pcm_devs,
515                           stream == SNDRV_PCM_STREAM_PLAYBACK ? 1 : 0,
516                           stream == SNDRV_PCM_STREAM_PLAYBACK ? 0 : 1,
517                           &pcm);
518         if (err < 0) {
519                 kfree(as);
520                 return err;
521         }
522         as->pcm = pcm;
523         pcm->private_data = as;
524         pcm->private_free = snd_usb_audio_pcm_free;
525         pcm->info_flags = 0;
526         if (chip->pcm_devs > 0)
527                 sprintf(pcm->name, "USB Audio #%d", chip->pcm_devs);
528         else
529                 strcpy(pcm->name, "USB Audio");
530
531         snd_usb_init_substream(as, stream, fp, pd);
532
533         /*
534          * Keep using head insertion for M-Audio Audiophile USB (tm) which has a
535          * fix to swap capture stream order in conf/cards/USB-audio.conf
536          */
537         if (chip->usb_id == USB_ID(0x0763, 0x2003))
538                 list_add(&as->list, &chip->pcm_list);
539         else
540                 list_add_tail(&as->list, &chip->pcm_list);
541
542         chip->pcm_devs++;
543
544         snd_usb_proc_pcm_format_add(as);
545
546         return add_chmap(pcm, stream, &as->substream[stream]);
547 }
548
549 int snd_usb_add_audio_stream(struct snd_usb_audio *chip,
550                              int stream,
551                              struct audioformat *fp)
552 {
553         return __snd_usb_add_audio_stream(chip, stream, fp, NULL);
554 }
555
556 static int snd_usb_add_audio_stream_v3(struct snd_usb_audio *chip,
557                                        int stream,
558                                        struct audioformat *fp,
559                                        struct snd_usb_power_domain *pd)
560 {
561         return __snd_usb_add_audio_stream(chip, stream, fp, pd);
562 }
563
564 static int parse_uac_endpoint_attributes(struct snd_usb_audio *chip,
565                                          struct usb_host_interface *alts,
566                                          int protocol, int iface_no)
567 {
568         /* parsed with a v1 header here. that's ok as we only look at the
569          * header first which is the same for both versions */
570         struct uac_iso_endpoint_descriptor *csep;
571         struct usb_interface_descriptor *altsd = get_iface_desc(alts);
572         int attributes = 0;
573
574         csep = snd_usb_find_desc(alts->endpoint[0].extra, alts->endpoint[0].extralen, NULL, USB_DT_CS_ENDPOINT);
575
576         /* Creamware Noah has this descriptor after the 2nd endpoint */
577         if (!csep && altsd->bNumEndpoints >= 2)
578                 csep = snd_usb_find_desc(alts->endpoint[1].extra, alts->endpoint[1].extralen, NULL, USB_DT_CS_ENDPOINT);
579
580         /*
581          * If we can't locate the USB_DT_CS_ENDPOINT descriptor in the extra
582          * bytes after the first endpoint, go search the entire interface.
583          * Some devices have it directly *before* the standard endpoint.
584          */
585         if (!csep)
586                 csep = snd_usb_find_desc(alts->extra, alts->extralen, NULL, USB_DT_CS_ENDPOINT);
587
588         if (!csep || csep->bLength < 7 ||
589             csep->bDescriptorSubtype != UAC_EP_GENERAL)
590                 goto error;
591
592         if (protocol == UAC_VERSION_1) {
593                 attributes = csep->bmAttributes;
594         } else if (protocol == UAC_VERSION_2) {
595                 struct uac2_iso_endpoint_descriptor *csep2 =
596                         (struct uac2_iso_endpoint_descriptor *) csep;
597
598                 if (csep2->bLength < sizeof(*csep2))
599                         goto error;
600                 attributes = csep->bmAttributes & UAC_EP_CS_ATTR_FILL_MAX;
601
602                 /* emulate the endpoint attributes of a v1 device */
603                 if (csep2->bmControls & UAC2_CONTROL_PITCH)
604                         attributes |= UAC_EP_CS_ATTR_PITCH_CONTROL;
605         } else { /* UAC_VERSION_3 */
606                 struct uac3_iso_endpoint_descriptor *csep3 =
607                         (struct uac3_iso_endpoint_descriptor *) csep;
608
609                 if (csep3->bLength < sizeof(*csep3))
610                         goto error;
611                 /* emulate the endpoint attributes of a v1 device */
612                 if (le32_to_cpu(csep3->bmControls) & UAC2_CONTROL_PITCH)
613                         attributes |= UAC_EP_CS_ATTR_PITCH_CONTROL;
614         }
615
616         return attributes;
617
618  error:
619         usb_audio_warn(chip,
620                        "%u:%d : no or invalid class specific endpoint descriptor\n",
621                        iface_no, altsd->bAlternateSetting);
622         return 0;
623 }
624
625 /* find an input terminal descriptor (either UAC1 or UAC2) with the given
626  * terminal id
627  */
628 static void *
629 snd_usb_find_input_terminal_descriptor(struct usb_host_interface *ctrl_iface,
630                                        int terminal_id, bool uac23)
631 {
632         struct uac2_input_terminal_descriptor *term = NULL;
633         size_t minlen = uac23 ? sizeof(struct uac2_input_terminal_descriptor) :
634                 sizeof(struct uac_input_terminal_descriptor);
635
636         while ((term = snd_usb_find_csint_desc(ctrl_iface->extra,
637                                                ctrl_iface->extralen,
638                                                term, UAC_INPUT_TERMINAL))) {
639                 if (term->bLength < minlen)
640                         continue;
641                 if (term->bTerminalID == terminal_id)
642                         return term;
643         }
644
645         return NULL;
646 }
647
648 static void *
649 snd_usb_find_output_terminal_descriptor(struct usb_host_interface *ctrl_iface,
650                                         int terminal_id)
651 {
652         /* OK to use with both UAC2 and UAC3 */
653         struct uac2_output_terminal_descriptor *term = NULL;
654
655         while ((term = snd_usb_find_csint_desc(ctrl_iface->extra,
656                                                ctrl_iface->extralen,
657                                                term, UAC_OUTPUT_TERMINAL))) {
658                 if (term->bLength >= sizeof(*term) &&
659                     term->bTerminalID == terminal_id)
660                         return term;
661         }
662
663         return NULL;
664 }
665
666 static struct audioformat *
667 audio_format_alloc_init(struct snd_usb_audio *chip,
668                        struct usb_host_interface *alts,
669                        int protocol, int iface_no, int altset_idx,
670                        int altno, int num_channels, int clock)
671 {
672         struct audioformat *fp;
673
674         fp = kzalloc(sizeof(*fp), GFP_KERNEL);
675         if (!fp)
676                 return NULL;
677
678         fp->iface = iface_no;
679         fp->altsetting = altno;
680         fp->altset_idx = altset_idx;
681         fp->endpoint = get_endpoint(alts, 0)->bEndpointAddress;
682         fp->ep_attr = get_endpoint(alts, 0)->bmAttributes;
683         fp->datainterval = snd_usb_parse_datainterval(chip, alts);
684         fp->protocol = protocol;
685         fp->maxpacksize = le16_to_cpu(get_endpoint(alts, 0)->wMaxPacketSize);
686         fp->channels = num_channels;
687         if (snd_usb_get_speed(chip->dev) == USB_SPEED_HIGH)
688                 fp->maxpacksize = (((fp->maxpacksize >> 11) & 3) + 1)
689                                 * (fp->maxpacksize & 0x7ff);
690         fp->clock = clock;
691         INIT_LIST_HEAD(&fp->list);
692
693         return fp;
694 }
695
696 static struct audioformat *
697 snd_usb_get_audioformat_uac12(struct snd_usb_audio *chip,
698                               struct usb_host_interface *alts,
699                               int protocol, int iface_no, int altset_idx,
700                               int altno, int stream, int bm_quirk)
701 {
702         struct usb_device *dev = chip->dev;
703         struct uac_format_type_i_continuous_descriptor *fmt;
704         unsigned int num_channels = 0, chconfig = 0;
705         struct audioformat *fp;
706         int clock = 0;
707         u64 format;
708
709         /* get audio formats */
710         if (protocol == UAC_VERSION_1) {
711                 struct uac1_as_header_descriptor *as =
712                         snd_usb_find_csint_desc(alts->extra, alts->extralen,
713                                                 NULL, UAC_AS_GENERAL);
714                 struct uac_input_terminal_descriptor *iterm;
715
716                 if (!as) {
717                         dev_err(&dev->dev,
718                                 "%u:%d : UAC_AS_GENERAL descriptor not found\n",
719                                 iface_no, altno);
720                         return NULL;
721                 }
722
723                 if (as->bLength < sizeof(*as)) {
724                         dev_err(&dev->dev,
725                                 "%u:%d : invalid UAC_AS_GENERAL desc\n",
726                                 iface_no, altno);
727                         return NULL;
728                 }
729
730                 format = le16_to_cpu(as->wFormatTag); /* remember the format value */
731
732                 iterm = snd_usb_find_input_terminal_descriptor(chip->ctrl_intf,
733                                                                as->bTerminalLink,
734                                                                false);
735                 if (iterm) {
736                         num_channels = iterm->bNrChannels;
737                         chconfig = le16_to_cpu(iterm->wChannelConfig);
738                 }
739         } else { /* UAC_VERSION_2 */
740                 struct uac2_input_terminal_descriptor *input_term;
741                 struct uac2_output_terminal_descriptor *output_term;
742                 struct uac2_as_header_descriptor *as =
743                         snd_usb_find_csint_desc(alts->extra, alts->extralen,
744                                                 NULL, UAC_AS_GENERAL);
745
746                 if (!as) {
747                         dev_err(&dev->dev,
748                                 "%u:%d : UAC_AS_GENERAL descriptor not found\n",
749                                 iface_no, altno);
750                         return NULL;
751                 }
752
753                 if (as->bLength < sizeof(*as)) {
754                         dev_err(&dev->dev,
755                                 "%u:%d : invalid UAC_AS_GENERAL desc\n",
756                                 iface_no, altno);
757                         return NULL;
758                 }
759
760                 num_channels = as->bNrChannels;
761                 format = le32_to_cpu(as->bmFormats);
762                 chconfig = le32_to_cpu(as->bmChannelConfig);
763
764                 /*
765                  * lookup the terminal associated to this interface
766                  * to extract the clock
767                  */
768                 input_term = snd_usb_find_input_terminal_descriptor(chip->ctrl_intf,
769                                                                     as->bTerminalLink,
770                                                                     true);
771                 if (input_term) {
772                         clock = input_term->bCSourceID;
773                         if (!chconfig && (num_channels == input_term->bNrChannels))
774                                 chconfig = le32_to_cpu(input_term->bmChannelConfig);
775                         goto found_clock;
776                 }
777
778                 output_term = snd_usb_find_output_terminal_descriptor(chip->ctrl_intf,
779                                                                       as->bTerminalLink);
780                 if (output_term) {
781                         clock = output_term->bCSourceID;
782                         goto found_clock;
783                 }
784
785                 dev_err(&dev->dev,
786                         "%u:%d : bogus bTerminalLink %d\n",
787                         iface_no, altno, as->bTerminalLink);
788                 return NULL;
789         }
790
791 found_clock:
792         /* get format type */
793         fmt = snd_usb_find_csint_desc(alts->extra, alts->extralen,
794                                       NULL, UAC_FORMAT_TYPE);
795         if (!fmt) {
796                 dev_err(&dev->dev,
797                         "%u:%d : no UAC_FORMAT_TYPE desc\n",
798                         iface_no, altno);
799                 return NULL;
800         }
801         if (((protocol == UAC_VERSION_1) && (fmt->bLength < 8))
802                         || ((protocol == UAC_VERSION_2) &&
803                                         (fmt->bLength < 6))) {
804                 dev_err(&dev->dev,
805                         "%u:%d : invalid UAC_FORMAT_TYPE desc\n",
806                         iface_no, altno);
807                 return NULL;
808         }
809
810         /*
811          * Blue Microphones workaround: The last altsetting is
812          * identical with the previous one, except for a larger
813          * packet size, but is actually a mislabeled two-channel
814          * setting; ignore it.
815          *
816          * Part 2: analyze quirk flag and format
817          */
818         if (bm_quirk && fmt->bNrChannels == 1 && fmt->bSubframeSize == 2)
819                 return NULL;
820
821         fp = audio_format_alloc_init(chip, alts, protocol, iface_no,
822                                      altset_idx, altno, num_channels, clock);
823         if (!fp)
824                 return ERR_PTR(-ENOMEM);
825
826         fp->attributes = parse_uac_endpoint_attributes(chip, alts, protocol,
827                                                        iface_no);
828
829         /* some quirks for attributes here */
830         snd_usb_audioformat_attributes_quirk(chip, fp, stream);
831
832         /* ok, let's parse further... */
833         if (snd_usb_parse_audio_format(chip, fp, format,
834                                         fmt, stream) < 0) {
835                 kfree(fp->rate_table);
836                 kfree(fp);
837                 return NULL;
838         }
839
840         /* Create chmap */
841         if (fp->channels != num_channels)
842                 chconfig = 0;
843
844         fp->chmap = convert_chmap(fp->channels, chconfig, protocol);
845
846         return fp;
847 }
848
849 static struct audioformat *
850 snd_usb_get_audioformat_uac3(struct snd_usb_audio *chip,
851                              struct usb_host_interface *alts,
852                              struct snd_usb_power_domain **pd_out,
853                              int iface_no, int altset_idx,
854                              int altno, int stream)
855 {
856         struct usb_device *dev = chip->dev;
857         struct uac3_input_terminal_descriptor *input_term;
858         struct uac3_output_terminal_descriptor *output_term;
859         struct uac3_cluster_header_descriptor *cluster;
860         struct uac3_as_header_descriptor *as = NULL;
861         struct uac3_hc_descriptor_header hc_header;
862         struct snd_pcm_chmap_elem *chmap;
863         struct snd_usb_power_domain *pd;
864         unsigned char badd_profile;
865         u64 badd_formats = 0;
866         unsigned int num_channels;
867         struct audioformat *fp;
868         u16 cluster_id, wLength;
869         int clock = 0;
870         int err;
871
872         badd_profile = chip->badd_profile;
873
874         if (badd_profile >= UAC3_FUNCTION_SUBCLASS_GENERIC_IO) {
875                 unsigned int maxpacksize =
876                         le16_to_cpu(get_endpoint(alts, 0)->wMaxPacketSize);
877
878                 switch (maxpacksize) {
879                 default:
880                         dev_err(&dev->dev,
881                                 "%u:%d : incorrect wMaxPacketSize for BADD profile\n",
882                                 iface_no, altno);
883                         return NULL;
884                 case UAC3_BADD_EP_MAXPSIZE_SYNC_MONO_16:
885                 case UAC3_BADD_EP_MAXPSIZE_ASYNC_MONO_16:
886                         badd_formats = SNDRV_PCM_FMTBIT_S16_LE;
887                         num_channels = 1;
888                         break;
889                 case UAC3_BADD_EP_MAXPSIZE_SYNC_MONO_24:
890                 case UAC3_BADD_EP_MAXPSIZE_ASYNC_MONO_24:
891                         badd_formats = SNDRV_PCM_FMTBIT_S24_3LE;
892                         num_channels = 1;
893                         break;
894                 case UAC3_BADD_EP_MAXPSIZE_SYNC_STEREO_16:
895                 case UAC3_BADD_EP_MAXPSIZE_ASYNC_STEREO_16:
896                         badd_formats = SNDRV_PCM_FMTBIT_S16_LE;
897                         num_channels = 2;
898                         break;
899                 case UAC3_BADD_EP_MAXPSIZE_SYNC_STEREO_24:
900                 case UAC3_BADD_EP_MAXPSIZE_ASYNC_STEREO_24:
901                         badd_formats = SNDRV_PCM_FMTBIT_S24_3LE;
902                         num_channels = 2;
903                         break;
904                 }
905
906                 chmap = kzalloc(sizeof(*chmap), GFP_KERNEL);
907                 if (!chmap)
908                         return ERR_PTR(-ENOMEM);
909
910                 if (num_channels == 1) {
911                         chmap->map[0] = SNDRV_CHMAP_MONO;
912                 } else {
913                         chmap->map[0] = SNDRV_CHMAP_FL;
914                         chmap->map[1] = SNDRV_CHMAP_FR;
915                 }
916
917                 chmap->channels = num_channels;
918                 clock = UAC3_BADD_CS_ID9;
919                 goto found_clock;
920         }
921
922         as = snd_usb_find_csint_desc(alts->extra, alts->extralen,
923                                      NULL, UAC_AS_GENERAL);
924         if (!as) {
925                 dev_err(&dev->dev,
926                         "%u:%d : UAC_AS_GENERAL descriptor not found\n",
927                         iface_no, altno);
928                 return NULL;
929         }
930
931         if (as->bLength < sizeof(*as)) {
932                 dev_err(&dev->dev,
933                         "%u:%d : invalid UAC_AS_GENERAL desc\n",
934                         iface_no, altno);
935                 return NULL;
936         }
937
938         cluster_id = le16_to_cpu(as->wClusterDescrID);
939         if (!cluster_id) {
940                 dev_err(&dev->dev,
941                         "%u:%d : no cluster descriptor\n",
942                         iface_no, altno);
943                 return NULL;
944         }
945
946         /*
947          * Get number of channels and channel map through
948          * High Capability Cluster Descriptor
949          *
950          * First step: get High Capability header and
951          * read size of Cluster Descriptor
952          */
953         err = snd_usb_ctl_msg(chip->dev,
954                         usb_rcvctrlpipe(chip->dev, 0),
955                         UAC3_CS_REQ_HIGH_CAPABILITY_DESCRIPTOR,
956                         USB_RECIP_INTERFACE | USB_TYPE_CLASS | USB_DIR_IN,
957                         cluster_id,
958                         snd_usb_ctrl_intf(chip),
959                         &hc_header, sizeof(hc_header));
960         if (err < 0)
961                 return ERR_PTR(err);
962         else if (err != sizeof(hc_header)) {
963                 dev_err(&dev->dev,
964                         "%u:%d : can't get High Capability descriptor\n",
965                         iface_no, altno);
966                 return ERR_PTR(-EIO);
967         }
968
969         /*
970          * Second step: allocate needed amount of memory
971          * and request Cluster Descriptor
972          */
973         wLength = le16_to_cpu(hc_header.wLength);
974         cluster = kzalloc(wLength, GFP_KERNEL);
975         if (!cluster)
976                 return ERR_PTR(-ENOMEM);
977         err = snd_usb_ctl_msg(chip->dev,
978                         usb_rcvctrlpipe(chip->dev, 0),
979                         UAC3_CS_REQ_HIGH_CAPABILITY_DESCRIPTOR,
980                         USB_RECIP_INTERFACE | USB_TYPE_CLASS | USB_DIR_IN,
981                         cluster_id,
982                         snd_usb_ctrl_intf(chip),
983                         cluster, wLength);
984         if (err < 0) {
985                 kfree(cluster);
986                 return ERR_PTR(err);
987         } else if (err != wLength) {
988                 dev_err(&dev->dev,
989                         "%u:%d : can't get Cluster Descriptor\n",
990                         iface_no, altno);
991                 kfree(cluster);
992                 return ERR_PTR(-EIO);
993         }
994
995         num_channels = cluster->bNrChannels;
996         chmap = convert_chmap_v3(cluster);
997         kfree(cluster);
998
999         /*
1000          * lookup the terminal associated to this interface
1001          * to extract the clock
1002          */
1003         input_term = snd_usb_find_input_terminal_descriptor(chip->ctrl_intf,
1004                                                             as->bTerminalLink,
1005                                                             true);
1006         if (input_term) {
1007                 clock = input_term->bCSourceID;
1008                 goto found_clock;
1009         }
1010
1011         output_term = snd_usb_find_output_terminal_descriptor(chip->ctrl_intf,
1012                                                              as->bTerminalLink);
1013         if (output_term) {
1014                 clock = output_term->bCSourceID;
1015                 goto found_clock;
1016         }
1017
1018         dev_err(&dev->dev, "%u:%d : bogus bTerminalLink %d\n",
1019                         iface_no, altno, as->bTerminalLink);
1020         kfree(chmap);
1021         return NULL;
1022
1023 found_clock:
1024         fp = audio_format_alloc_init(chip, alts, UAC_VERSION_3, iface_no,
1025                                      altset_idx, altno, num_channels, clock);
1026         if (!fp) {
1027                 kfree(chmap);
1028                 return ERR_PTR(-ENOMEM);
1029         }
1030
1031         fp->chmap = chmap;
1032
1033         if (badd_profile >= UAC3_FUNCTION_SUBCLASS_GENERIC_IO) {
1034                 fp->attributes = 0; /* No attributes */
1035
1036                 fp->fmt_type = UAC_FORMAT_TYPE_I;
1037                 fp->formats = badd_formats;
1038
1039                 fp->nr_rates = 0;       /* SNDRV_PCM_RATE_CONTINUOUS */
1040                 fp->rate_min = UAC3_BADD_SAMPLING_RATE;
1041                 fp->rate_max = UAC3_BADD_SAMPLING_RATE;
1042                 fp->rates = SNDRV_PCM_RATE_CONTINUOUS;
1043
1044                 pd = kzalloc(sizeof(*pd), GFP_KERNEL);
1045                 if (!pd) {
1046                         kfree(fp->chmap);
1047                         kfree(fp->rate_table);
1048                         kfree(fp);
1049                         return NULL;
1050                 }
1051                 pd->pd_id = (stream == SNDRV_PCM_STREAM_PLAYBACK) ?
1052                                         UAC3_BADD_PD_ID10 : UAC3_BADD_PD_ID11;
1053                 pd->pd_d1d0_rec = UAC3_BADD_PD_RECOVER_D1D0;
1054                 pd->pd_d2d0_rec = UAC3_BADD_PD_RECOVER_D2D0;
1055
1056         } else {
1057                 fp->attributes = parse_uac_endpoint_attributes(chip, alts,
1058                                                                UAC_VERSION_3,
1059                                                                iface_no);
1060
1061                 pd = snd_usb_find_power_domain(chip->ctrl_intf,
1062                                                as->bTerminalLink);
1063
1064                 /* ok, let's parse further... */
1065                 if (snd_usb_parse_audio_format_v3(chip, fp, as, stream) < 0) {
1066                         kfree(pd);
1067                         kfree(fp->chmap);
1068                         kfree(fp->rate_table);
1069                         kfree(fp);
1070                         return NULL;
1071                 }
1072         }
1073
1074         if (pd)
1075                 *pd_out = pd;
1076
1077         return fp;
1078 }
1079
1080 int snd_usb_parse_audio_interface(struct snd_usb_audio *chip, int iface_no)
1081 {
1082         struct usb_device *dev;
1083         struct usb_interface *iface;
1084         struct usb_host_interface *alts;
1085         struct usb_interface_descriptor *altsd;
1086         int i, altno, err, stream;
1087         struct audioformat *fp = NULL;
1088         struct snd_usb_power_domain *pd = NULL;
1089         int num, protocol;
1090
1091         dev = chip->dev;
1092
1093         /* parse the interface's altsettings */
1094         iface = usb_ifnum_to_if(dev, iface_no);
1095
1096         num = iface->num_altsetting;
1097
1098         /*
1099          * Dallas DS4201 workaround: It presents 5 altsettings, but the last
1100          * one misses syncpipe, and does not produce any sound.
1101          */
1102         if (chip->usb_id == USB_ID(0x04fa, 0x4201))
1103                 num = 4;
1104
1105         for (i = 0; i < num; i++) {
1106                 alts = &iface->altsetting[i];
1107                 altsd = get_iface_desc(alts);
1108                 protocol = altsd->bInterfaceProtocol;
1109                 /* skip invalid one */
1110                 if (((altsd->bInterfaceClass != USB_CLASS_AUDIO ||
1111                       (altsd->bInterfaceSubClass != USB_SUBCLASS_AUDIOSTREAMING &&
1112                        altsd->bInterfaceSubClass != USB_SUBCLASS_VENDOR_SPEC)) &&
1113                      altsd->bInterfaceClass != USB_CLASS_VENDOR_SPEC) ||
1114                     altsd->bNumEndpoints < 1 ||
1115                     le16_to_cpu(get_endpoint(alts, 0)->wMaxPacketSize) == 0)
1116                         continue;
1117                 /* must be isochronous */
1118                 if ((get_endpoint(alts, 0)->bmAttributes & USB_ENDPOINT_XFERTYPE_MASK) !=
1119                     USB_ENDPOINT_XFER_ISOC)
1120                         continue;
1121                 /* check direction */
1122                 stream = (get_endpoint(alts, 0)->bEndpointAddress & USB_DIR_IN) ?
1123                         SNDRV_PCM_STREAM_CAPTURE : SNDRV_PCM_STREAM_PLAYBACK;
1124                 altno = altsd->bAlternateSetting;
1125
1126                 if (snd_usb_apply_interface_quirk(chip, iface_no, altno))
1127                         continue;
1128
1129                 /*
1130                  * Roland audio streaming interfaces are marked with protocols
1131                  * 0/1/2, but are UAC 1 compatible.
1132                  */
1133                 if (USB_ID_VENDOR(chip->usb_id) == 0x0582 &&
1134                     altsd->bInterfaceClass == USB_CLASS_VENDOR_SPEC &&
1135                     protocol <= 2)
1136                         protocol = UAC_VERSION_1;
1137
1138                 switch (protocol) {
1139                 default:
1140                         dev_dbg(&dev->dev, "%u:%d: unknown interface protocol %#02x, assuming v1\n",
1141                                 iface_no, altno, protocol);
1142                         protocol = UAC_VERSION_1;
1143                         /* fall through */
1144                 case UAC_VERSION_1:
1145                         /* fall through */
1146                 case UAC_VERSION_2: {
1147                         int bm_quirk = 0;
1148
1149                         /*
1150                          * Blue Microphones workaround: The last altsetting is
1151                          * identical with the previous one, except for a larger
1152                          * packet size, but is actually a mislabeled two-channel
1153                          * setting; ignore it.
1154                          *
1155                          * Part 1: prepare quirk flag
1156                          */
1157                         if (altno == 2 && num == 3 &&
1158                             fp && fp->altsetting == 1 && fp->channels == 1 &&
1159                             fp->formats == SNDRV_PCM_FMTBIT_S16_LE &&
1160                             protocol == UAC_VERSION_1 &&
1161                             le16_to_cpu(get_endpoint(alts, 0)->wMaxPacketSize) ==
1162                                                         fp->maxpacksize * 2)
1163                                 bm_quirk = 1;
1164
1165                         fp = snd_usb_get_audioformat_uac12(chip, alts, protocol,
1166                                                            iface_no, i, altno,
1167                                                            stream, bm_quirk);
1168                         break;
1169                 }
1170                 case UAC_VERSION_3:
1171                         fp = snd_usb_get_audioformat_uac3(chip, alts, &pd,
1172                                                 iface_no, i, altno, stream);
1173                         break;
1174                 }
1175
1176                 if (!fp)
1177                         continue;
1178                 else if (IS_ERR(fp))
1179                         return PTR_ERR(fp);
1180
1181                 dev_dbg(&dev->dev, "%u:%d: add audio endpoint %#x\n", iface_no, altno, fp->endpoint);
1182                 if (protocol == UAC_VERSION_3)
1183                         err = snd_usb_add_audio_stream_v3(chip, stream, fp, pd);
1184                 else
1185                         err = snd_usb_add_audio_stream(chip, stream, fp);
1186
1187                 if (err < 0) {
1188                         list_del(&fp->list); /* unlink for avoiding double-free */
1189                         kfree(pd);
1190                         kfree(fp->rate_table);
1191                         kfree(fp->chmap);
1192                         kfree(fp);
1193                         return err;
1194                 }
1195                 /* try to set the interface... */
1196                 usb_set_interface(chip->dev, iface_no, altno);
1197                 snd_usb_init_pitch(chip, iface_no, alts, fp);
1198                 snd_usb_init_sample_rate(chip, iface_no, alts, fp, fp->rate_max);
1199         }
1200         return 0;
1201 }
1202