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