ALSA: usb-audio: Track implicit fb sync endpoint in audioformat list
[linux-2.6-microblaze.git] / sound / usb / pcm.c
1 // SPDX-License-Identifier: GPL-2.0-or-later
2 /*
3  */
4
5 #include <linux/init.h>
6 #include <linux/slab.h>
7 #include <linux/bitrev.h>
8 #include <linux/ratelimit.h>
9 #include <linux/usb.h>
10 #include <linux/usb/audio.h>
11 #include <linux/usb/audio-v2.h>
12
13 #include <sound/core.h>
14 #include <sound/pcm.h>
15 #include <sound/pcm_params.h>
16
17 #include "usbaudio.h"
18 #include "card.h"
19 #include "quirks.h"
20 #include "debug.h"
21 #include "endpoint.h"
22 #include "helper.h"
23 #include "pcm.h"
24 #include "clock.h"
25 #include "power.h"
26 #include "media.h"
27
28 #define SUBSTREAM_FLAG_DATA_EP_STARTED  0
29 #define SUBSTREAM_FLAG_SYNC_EP_STARTED  1
30
31 /* return the estimated delay based on USB frame counters */
32 snd_pcm_uframes_t snd_usb_pcm_delay(struct snd_usb_substream *subs,
33                                     unsigned int rate)
34 {
35         int current_frame_number;
36         int frame_diff;
37         int est_delay;
38
39         if (!subs->last_delay)
40                 return 0; /* short path */
41
42         current_frame_number = usb_get_current_frame_number(subs->dev);
43         /*
44          * HCD implementations use different widths, use lower 8 bits.
45          * The delay will be managed up to 256ms, which is more than
46          * enough
47          */
48         frame_diff = (current_frame_number - subs->last_frame_number) & 0xff;
49
50         /* Approximation based on number of samples per USB frame (ms),
51            some truncation for 44.1 but the estimate is good enough */
52         est_delay =  frame_diff * rate / 1000;
53         if (subs->direction == SNDRV_PCM_STREAM_PLAYBACK)
54                 est_delay = subs->last_delay - est_delay;
55         else
56                 est_delay = subs->last_delay + est_delay;
57
58         if (est_delay < 0)
59                 est_delay = 0;
60         return est_delay;
61 }
62
63 /*
64  * return the current pcm pointer.  just based on the hwptr_done value.
65  */
66 static snd_pcm_uframes_t snd_usb_pcm_pointer(struct snd_pcm_substream *substream)
67 {
68         struct snd_usb_substream *subs = substream->runtime->private_data;
69         unsigned int hwptr_done;
70
71         if (atomic_read(&subs->stream->chip->shutdown))
72                 return SNDRV_PCM_POS_XRUN;
73         spin_lock(&subs->lock);
74         hwptr_done = subs->hwptr_done;
75         substream->runtime->delay = snd_usb_pcm_delay(subs,
76                                                 substream->runtime->rate);
77         spin_unlock(&subs->lock);
78         return hwptr_done / (substream->runtime->frame_bits >> 3);
79 }
80
81 /*
82  * find a matching audio format
83  */
84 static struct audioformat *find_format(struct snd_usb_substream *subs)
85 {
86         struct audioformat *fp;
87         struct audioformat *found = NULL;
88         int cur_attr = 0, attr;
89
90         list_for_each_entry(fp, &subs->fmt_list, list) {
91                 if (!(fp->formats & pcm_format_to_bits(subs->pcm_format)))
92                         continue;
93                 if (fp->channels != subs->channels)
94                         continue;
95                 if (subs->cur_rate < fp->rate_min ||
96                     subs->cur_rate > fp->rate_max)
97                         continue;
98                 if (! (fp->rates & SNDRV_PCM_RATE_CONTINUOUS)) {
99                         unsigned int i;
100                         for (i = 0; i < fp->nr_rates; i++)
101                                 if (fp->rate_table[i] == subs->cur_rate)
102                                         break;
103                         if (i >= fp->nr_rates)
104                                 continue;
105                 }
106                 attr = fp->ep_attr & USB_ENDPOINT_SYNCTYPE;
107                 if (! found) {
108                         found = fp;
109                         cur_attr = attr;
110                         continue;
111                 }
112                 /* avoid async out and adaptive in if the other method
113                  * supports the same format.
114                  * this is a workaround for the case like
115                  * M-audio audiophile USB.
116                  */
117                 if (attr != cur_attr) {
118                         if ((attr == USB_ENDPOINT_SYNC_ASYNC &&
119                              subs->direction == SNDRV_PCM_STREAM_PLAYBACK) ||
120                             (attr == USB_ENDPOINT_SYNC_ADAPTIVE &&
121                              subs->direction == SNDRV_PCM_STREAM_CAPTURE))
122                                 continue;
123                         if ((cur_attr == USB_ENDPOINT_SYNC_ASYNC &&
124                              subs->direction == SNDRV_PCM_STREAM_PLAYBACK) ||
125                             (cur_attr == USB_ENDPOINT_SYNC_ADAPTIVE &&
126                              subs->direction == SNDRV_PCM_STREAM_CAPTURE)) {
127                                 found = fp;
128                                 cur_attr = attr;
129                                 continue;
130                         }
131                 }
132                 /* find the format with the largest max. packet size */
133                 if (fp->maxpacksize > found->maxpacksize) {
134                         found = fp;
135                         cur_attr = attr;
136                 }
137         }
138         return found;
139 }
140
141 static int init_pitch_v1(struct snd_usb_audio *chip, int iface,
142                          struct usb_host_interface *alts,
143                          struct audioformat *fmt)
144 {
145         struct usb_device *dev = chip->dev;
146         unsigned int ep;
147         unsigned char data[1];
148         int err;
149
150         if (get_iface_desc(alts)->bNumEndpoints < 1)
151                 return -EINVAL;
152         ep = get_endpoint(alts, 0)->bEndpointAddress;
153
154         data[0] = 1;
155         err = snd_usb_ctl_msg(dev, usb_sndctrlpipe(dev, 0), UAC_SET_CUR,
156                               USB_TYPE_CLASS|USB_RECIP_ENDPOINT|USB_DIR_OUT,
157                               UAC_EP_CS_ATTR_PITCH_CONTROL << 8, ep,
158                               data, sizeof(data));
159         if (err < 0) {
160                 usb_audio_err(chip, "%d:%d: cannot set enable PITCH\n",
161                               iface, ep);
162                 return err;
163         }
164
165         return 0;
166 }
167
168 static int init_pitch_v2(struct snd_usb_audio *chip, int iface,
169                          struct usb_host_interface *alts,
170                          struct audioformat *fmt)
171 {
172         struct usb_device *dev = chip->dev;
173         unsigned char data[1];
174         int err;
175
176         data[0] = 1;
177         err = snd_usb_ctl_msg(dev, usb_sndctrlpipe(dev, 0), UAC2_CS_CUR,
178                               USB_TYPE_CLASS | USB_RECIP_ENDPOINT | USB_DIR_OUT,
179                               UAC2_EP_CS_PITCH << 8, 0,
180                               data, sizeof(data));
181         if (err < 0) {
182                 usb_audio_err(chip, "%d:%d: cannot set enable PITCH (v2)\n",
183                               iface, fmt->altsetting);
184                 return err;
185         }
186
187         return 0;
188 }
189
190 /*
191  * initialize the pitch control and sample rate
192  */
193 int snd_usb_init_pitch(struct snd_usb_audio *chip, int iface,
194                        struct usb_host_interface *alts,
195                        struct audioformat *fmt)
196 {
197         /* if endpoint doesn't have pitch control, bail out */
198         if (!(fmt->attributes & UAC_EP_CS_ATTR_PITCH_CONTROL))
199                 return 0;
200
201         switch (fmt->protocol) {
202         case UAC_VERSION_1:
203         default:
204                 return init_pitch_v1(chip, iface, alts, fmt);
205
206         case UAC_VERSION_2:
207                 return init_pitch_v2(chip, iface, alts, fmt);
208         }
209 }
210
211 static int start_endpoints(struct snd_usb_substream *subs)
212 {
213         int err;
214
215         if (!subs->data_endpoint)
216                 return -EINVAL;
217
218         if (!test_and_set_bit(SUBSTREAM_FLAG_DATA_EP_STARTED, &subs->flags)) {
219                 struct snd_usb_endpoint *ep = subs->data_endpoint;
220
221                 dev_dbg(&subs->dev->dev, "Starting data EP 0x%x\n", ep->ep_num);
222
223                 ep->data_subs = subs;
224                 err = snd_usb_endpoint_start(ep);
225                 if (err < 0) {
226                         clear_bit(SUBSTREAM_FLAG_DATA_EP_STARTED, &subs->flags);
227                         return err;
228                 }
229         }
230
231         if (subs->sync_endpoint &&
232             !test_and_set_bit(SUBSTREAM_FLAG_SYNC_EP_STARTED, &subs->flags)) {
233                 struct snd_usb_endpoint *ep = subs->sync_endpoint;
234
235                 dev_dbg(&subs->dev->dev, "Starting sync EP 0x%x\n", ep->ep_num);
236
237                 ep->sync_slave = subs->data_endpoint;
238                 err = snd_usb_endpoint_start(ep);
239                 if (err < 0) {
240                         clear_bit(SUBSTREAM_FLAG_SYNC_EP_STARTED, &subs->flags);
241                         ep->sync_slave = NULL;
242                         return err;
243                 }
244         }
245
246         return 0;
247 }
248
249 static void sync_pending_stops(struct snd_usb_substream *subs)
250 {
251         snd_usb_endpoint_sync_pending_stop(subs->sync_endpoint);
252         snd_usb_endpoint_sync_pending_stop(subs->data_endpoint);
253 }
254
255 static void stop_endpoints(struct snd_usb_substream *subs)
256 {
257         if (test_and_clear_bit(SUBSTREAM_FLAG_SYNC_EP_STARTED, &subs->flags)) {
258                 dev_dbg(&subs->dev->dev, "Stopping sync EP 0x%x\n",
259                         subs->sync_endpoint->ep_num);
260                 snd_usb_endpoint_stop(subs->sync_endpoint);
261                 subs->sync_endpoint->sync_slave = NULL;
262         }
263
264         if (test_and_clear_bit(SUBSTREAM_FLAG_DATA_EP_STARTED, &subs->flags)) {
265                 dev_dbg(&subs->dev->dev, "Stopping data EP 0x%x\n",
266                         subs->data_endpoint->ep_num);
267                 snd_usb_endpoint_stop(subs->data_endpoint);
268         }
269 }
270
271 /* PCM sync_stop callback */
272 static int snd_usb_pcm_sync_stop(struct snd_pcm_substream *substream)
273 {
274         struct snd_usb_substream *subs = substream->runtime->private_data;
275
276         if (!snd_usb_lock_shutdown(subs->stream->chip)) {
277                 sync_pending_stops(subs);
278                 snd_usb_unlock_shutdown(subs->stream->chip);
279         }
280         return 0;
281 }
282
283 /* Check whether the given iface:altsetting points to an implicit fb source */
284 static bool search_generic_implicit_fb(struct usb_device *dev, int ifnum,
285                                        unsigned int altsetting,
286                                        struct usb_host_interface **altsp,
287                                        unsigned int *ep)
288 {
289         struct usb_interface *iface;
290         struct usb_host_interface *alts;
291         struct usb_interface_descriptor *altsd;
292         struct usb_endpoint_descriptor *epd;
293
294         iface = usb_ifnum_to_if(dev, ifnum);
295         if (!iface)
296                 return false;
297         alts = usb_altnum_to_altsetting(iface, altsetting);
298         if (!alts)
299                 return false;
300         altsd = get_iface_desc(alts);
301         if (altsd->bInterfaceClass != USB_CLASS_AUDIO ||
302             altsd->bInterfaceSubClass != USB_SUBCLASS_AUDIOSTREAMING ||
303             altsd->bInterfaceProtocol != UAC_VERSION_2 ||
304             altsd->bNumEndpoints < 1)
305                 return false;
306         epd = get_endpoint(alts, 0);
307         if (!usb_endpoint_is_isoc_in(epd) ||
308             (epd->bmAttributes & USB_ENDPOINT_USAGE_MASK) !=
309                                         USB_ENDPOINT_USAGE_IMPLICIT_FB)
310                 return false;
311         *ep = epd->bEndpointAddress;
312         *altsp = alts;
313         return true;
314 }
315
316 /* Like the function above, but specific to Roland with vendor class and hack */
317 static bool search_roland_implicit_fb(struct usb_device *dev, int ifnum,
318                                       unsigned int altsetting,
319                                       struct usb_host_interface **altsp,
320                                       unsigned int *ep)
321 {
322         struct usb_interface *iface;
323         struct usb_host_interface *alts;
324         struct usb_interface_descriptor *altsd;
325         struct usb_endpoint_descriptor *epd;
326
327         iface = usb_ifnum_to_if(dev, ifnum);
328         if (!iface)
329                 return false;
330         alts = usb_altnum_to_altsetting(iface, altsetting);
331         if (!alts)
332                 return false;
333         altsd = get_iface_desc(alts);
334         if (altsd->bInterfaceClass != USB_CLASS_VENDOR_SPEC ||
335             (altsd->bInterfaceSubClass != 2 &&
336              altsd->bInterfaceProtocol != 2) ||
337             altsd->bNumEndpoints < 1)
338                 return false;
339         epd = get_endpoint(alts, 0);
340         if (!usb_endpoint_is_isoc_in(epd) ||
341             (epd->bmAttributes & USB_ENDPOINT_USAGE_MASK) !=
342                                         USB_ENDPOINT_USAGE_IMPLICIT_FB)
343                 return false;
344         *ep = epd->bEndpointAddress;
345         *altsp = alts;
346         return true;
347 }
348
349 /* Setup an implicit feedback endpoint from a quirk. Returns 0 if no quirk
350  * applies. Returns 1 if a quirk was found.
351  */
352 static int audioformat_implicit_fb_quirk(struct snd_usb_audio *chip,
353                                          struct audioformat *fmt,
354                                          struct usb_interface *iface,
355                                          struct usb_host_interface *alts)
356 {
357         struct usb_device *dev = chip->dev;
358         struct usb_interface_descriptor *altsd = get_iface_desc(alts);
359         unsigned int attr = fmt->ep_attr & USB_ENDPOINT_SYNCTYPE;
360         unsigned int ep;
361         unsigned int ifnum;
362
363         switch (chip->usb_id) {
364         case USB_ID(0x0763, 0x2030): /* M-Audio Fast Track C400 */
365         case USB_ID(0x0763, 0x2031): /* M-Audio Fast Track C600 */
366         case USB_ID(0x22f0, 0x0006): /* Allen&Heath Qu-16 */
367                 ep = 0x81;
368                 ifnum = 3;
369                 goto add_sync_ep_from_ifnum;
370         case USB_ID(0x0763, 0x2080): /* M-Audio FastTrack Ultra */
371         case USB_ID(0x0763, 0x2081):
372                 ep = 0x81;
373                 ifnum = 2;
374                 goto add_sync_ep_from_ifnum;
375         case USB_ID(0x2466, 0x8003): /* Fractal Audio Axe-Fx II */
376         case USB_ID(0x0499, 0x172a): /* Yamaha MODX */
377                 ep = 0x86;
378                 ifnum = 2;
379                 goto add_sync_ep_from_ifnum;
380         case USB_ID(0x2466, 0x8010): /* Fractal Audio Axe-Fx III */
381                 ep = 0x81;
382                 ifnum = 2;
383                 goto add_sync_ep_from_ifnum;
384         case USB_ID(0x1686, 0xf029): /* Zoom UAC-2 */
385                 ep = 0x82;
386                 ifnum = 2;
387                 goto add_sync_ep_from_ifnum;
388         case USB_ID(0x1397, 0x0001): /* Behringer UFX1604 */
389         case USB_ID(0x1397, 0x0002): /* Behringer UFX1204 */
390                 ep = 0x81;
391                 ifnum = 1;
392                 goto add_sync_ep_from_ifnum;
393         case USB_ID(0x07fd, 0x0004): /* MOTU MicroBook II/IIc */
394                 /* MicroBook IIc */
395                 if (altsd->bInterfaceClass == USB_CLASS_AUDIO)
396                         return 0;
397
398                 /* MicroBook II */
399                 ep = 0x84;
400                 ifnum = 0;
401                 goto add_sync_ep_from_ifnum;
402         case USB_ID(0x07fd, 0x0008): /* MOTU M Series */
403         case USB_ID(0x31e9, 0x0001): /* Solid State Logic SSL2 */
404         case USB_ID(0x31e9, 0x0002): /* Solid State Logic SSL2+ */
405         case USB_ID(0x0499, 0x172f): /* Steinberg UR22C */
406         case USB_ID(0x0d9a, 0x00df): /* RTX6001 */
407                 ep = 0x81;
408                 ifnum = 2;
409                 goto add_sync_ep_from_ifnum;
410         case USB_ID(0x2b73, 0x000a): /* Pioneer DJ DJM-900NXS2 */
411         case USB_ID(0x2b73, 0x0017): /* Pioneer DJ DJM-250MK2 */
412                 ep = 0x82;
413                 ifnum = 0;
414                 goto add_sync_ep_from_ifnum;
415         case USB_ID(0x0582, 0x01d8): /* BOSS Katana */
416                 /* BOSS Katana amplifiers do not need quirks */
417                 return 0;
418         }
419
420         /* Generic UAC2 implicit feedback */
421         if (attr == USB_ENDPOINT_SYNC_ASYNC &&
422             altsd->bInterfaceClass == USB_CLASS_AUDIO &&
423             altsd->bInterfaceProtocol == UAC_VERSION_2 &&
424             altsd->bNumEndpoints == 1) {
425                 ifnum = altsd->bInterfaceNumber + 1;
426                 if (search_generic_implicit_fb(dev, ifnum,
427                                                altsd->bAlternateSetting,
428                                                &alts, &ep))
429                         goto add_sync_ep;
430         }
431
432         /* Roland/BOSS implicit feedback with vendor spec class */
433         if (attr == USB_ENDPOINT_SYNC_ASYNC &&
434             altsd->bInterfaceClass == USB_CLASS_VENDOR_SPEC &&
435             altsd->bInterfaceProtocol == 2 &&
436             altsd->bNumEndpoints == 1 &&
437             USB_ID_VENDOR(chip->usb_id) == 0x0582 /* Roland */) {
438                 ifnum = altsd->bInterfaceNumber + 1;
439                 if (search_roland_implicit_fb(dev, ifnum,
440                                               altsd->bAlternateSetting,
441                                               &alts, &ep))
442                         goto add_sync_ep;
443         }
444
445         /* No quirk */
446         return 0;
447
448 add_sync_ep_from_ifnum:
449         iface = usb_ifnum_to_if(dev, ifnum);
450
451         if (!iface || iface->num_altsetting < 2)
452                 return 0;
453
454         alts = &iface->altsetting[1];
455
456 add_sync_ep:
457         fmt->sync_ep = ep;
458         fmt->sync_iface = ifnum;
459         fmt->sync_altsetting = alts->desc.bAlternateSetting;
460         fmt->implicit_fb = 1;
461         dev_dbg(&dev->dev, "%d:%d: found implicit_fb sync_ep=%x, iface=%d, alt=%d\n",
462                 fmt->iface, fmt->altsetting, fmt->sync_ep, fmt->sync_iface,
463                 fmt->sync_altsetting);
464
465         return 1;
466 }
467
468 int snd_usb_audioformat_set_sync_ep(struct snd_usb_audio *chip,
469                                     struct audioformat *fmt)
470 {
471         struct usb_device *dev = chip->dev;
472         struct usb_interface *iface;
473         struct usb_host_interface *alts;
474         struct usb_interface_descriptor *altsd;
475         unsigned int ep, attr, sync_attr;
476         bool is_playback;
477         int err;
478
479         iface = usb_ifnum_to_if(dev, fmt->iface);
480         if (!iface)
481                 return 0;
482         alts = usb_altnum_to_altsetting(iface, fmt->altsetting);
483         if (!alts)
484                 return 0;
485         altsd = get_iface_desc(alts);
486
487         is_playback = !(get_endpoint(alts, 0)->bEndpointAddress & USB_DIR_IN);
488         if (is_playback) {
489                 err = audioformat_implicit_fb_quirk(chip, fmt, iface, alts);
490                 if (err > 0)
491                         return 0;
492         }
493
494         if (altsd->bNumEndpoints < 2)
495                 return 0;
496
497         attr = fmt->ep_attr & USB_ENDPOINT_SYNCTYPE;
498         if ((is_playback && (attr == USB_ENDPOINT_SYNC_SYNC ||
499                              attr == USB_ENDPOINT_SYNC_ADAPTIVE)) ||
500             (!is_playback && attr != USB_ENDPOINT_SYNC_ADAPTIVE))
501                 return 0;
502
503         sync_attr = get_endpoint(alts, 1)->bmAttributes;
504
505         /*
506          * In case of illegal SYNC_NONE for OUT endpoint, we keep going to see
507          * if we don't find a sync endpoint, as on M-Audio Transit. In case of
508          * error fall back to SYNC mode and don't create sync endpoint
509          */
510
511         /* check sync-pipe endpoint */
512         /* ... and check descriptor size before accessing bSynchAddress
513            because there is a version of the SB Audigy 2 NX firmware lacking
514            the audio fields in the endpoint descriptors */
515         if ((sync_attr & USB_ENDPOINT_XFERTYPE_MASK) != USB_ENDPOINT_XFER_ISOC ||
516             (get_endpoint(alts, 1)->bLength >= USB_DT_ENDPOINT_AUDIO_SIZE &&
517              get_endpoint(alts, 1)->bSynchAddress != 0)) {
518                 dev_err(&dev->dev,
519                         "%d:%d : invalid sync pipe. bmAttributes %02x, bLength %d, bSynchAddress %02x\n",
520                            fmt->iface, fmt->altsetting,
521                            get_endpoint(alts, 1)->bmAttributes,
522                            get_endpoint(alts, 1)->bLength,
523                            get_endpoint(alts, 1)->bSynchAddress);
524                 if (is_playback && attr == USB_ENDPOINT_SYNC_NONE)
525                         return 0;
526                 return -EINVAL;
527         }
528         ep = get_endpoint(alts, 1)->bEndpointAddress;
529         if (get_endpoint(alts, 0)->bLength >= USB_DT_ENDPOINT_AUDIO_SIZE &&
530             get_endpoint(alts, 0)->bSynchAddress != 0 &&
531             ((is_playback && ep != (unsigned int)(get_endpoint(alts, 0)->bSynchAddress | USB_DIR_IN)) ||
532              (!is_playback && ep != (unsigned int)(get_endpoint(alts, 0)->bSynchAddress & ~USB_DIR_IN)))) {
533                 dev_err(&dev->dev,
534                         "%d:%d : invalid sync pipe. is_playback %d, ep %02x, bSynchAddress %02x\n",
535                            fmt->iface, fmt->altsetting,
536                            is_playback, ep, get_endpoint(alts, 0)->bSynchAddress);
537                 if (is_playback && attr == USB_ENDPOINT_SYNC_NONE)
538                         return 0;
539                 return -EINVAL;
540         }
541
542         fmt->sync_ep = ep;
543         fmt->sync_iface = altsd->bInterfaceNumber;
544         fmt->sync_altsetting = altsd->bAlternateSetting;
545         if ((sync_attr & USB_ENDPOINT_USAGE_MASK) == USB_ENDPOINT_USAGE_IMPLICIT_FB)
546                 fmt->implicit_fb = 1;
547
548         dev_dbg(&dev->dev, "%d:%d: found sync_ep=0x%x, iface=%d, alt=%d, implicit_fb=%d\n",
549                 fmt->iface, fmt->altsetting, fmt->sync_ep, fmt->sync_iface,
550                 fmt->sync_altsetting, fmt->implicit_fb);
551
552         return 0;
553 }
554
555 static int set_sync_endpoint(struct snd_usb_substream *subs,
556                              struct audioformat *fmt)
557 {
558         struct usb_device *dev = subs->dev;
559         struct usb_interface *iface;
560         struct usb_host_interface *alts;
561         int is_playback = subs->direction == SNDRV_PCM_STREAM_PLAYBACK;
562         unsigned int ep;
563         int err;
564
565         subs->sync_endpoint = NULL;
566         subs->data_endpoint->sync_master = NULL;
567
568         ep = fmt->sync_ep;
569         if (!ep)
570                 return 0;
571
572         iface = usb_ifnum_to_if(dev, fmt->sync_iface);
573         if (!iface)
574                 return 0;
575
576         alts = usb_altnum_to_altsetting(iface, fmt->altsetting);
577         if (!alts)
578                 return 0;
579
580         subs->sync_endpoint = snd_usb_add_endpoint(subs->stream->chip,
581                                                    alts, ep, !subs->direction,
582                                                    fmt->implicit_fb ?
583                                                    SND_USB_ENDPOINT_TYPE_DATA :
584                                                    SND_USB_ENDPOINT_TYPE_SYNC);
585         if (!subs->sync_endpoint) {
586                 if (is_playback &&
587                     (fmt->ep_attr & USB_ENDPOINT_SYNCTYPE) == USB_ENDPOINT_SYNC_NONE)
588                         return 0;
589                 return -EINVAL;
590         }
591
592         subs->sync_endpoint->is_implicit_feedback = fmt->implicit_fb;
593
594         subs->data_endpoint->sync_master = subs->sync_endpoint;
595
596         if (subs->data_endpoint->iface != subs->sync_endpoint->iface ||
597             subs->data_endpoint->altsetting != subs->sync_endpoint->altsetting) {
598                 err = usb_set_interface(subs->dev,
599                                         subs->sync_endpoint->iface,
600                                         subs->sync_endpoint->altsetting);
601                 if (err < 0)
602                         return err;
603                 dev_dbg(&dev->dev, "setting usb interface %d:%d\n",
604                         subs->sync_endpoint->iface,
605                         subs->sync_endpoint->altsetting);
606                 snd_usb_set_interface_quirk(dev);
607         }
608
609         return 0;
610 }
611
612 /*
613  * find a matching format and set up the interface
614  */
615 static int set_format(struct snd_usb_substream *subs, struct audioformat *fmt)
616 {
617         struct usb_device *dev = subs->dev;
618         struct usb_host_interface *alts;
619         struct usb_interface *iface;
620         int err;
621
622         iface = usb_ifnum_to_if(dev, fmt->iface);
623         if (WARN_ON(!iface))
624                 return -EINVAL;
625         alts = usb_altnum_to_altsetting(iface, fmt->altsetting);
626         if (WARN_ON(!alts))
627                 return -EINVAL;
628
629         if (fmt == subs->cur_audiofmt && !subs->need_setup_fmt)
630                 return 0;
631
632         /* close the old interface */
633         if (subs->interface >= 0 && (subs->interface != fmt->iface || subs->need_setup_fmt)) {
634                 if (!subs->stream->chip->keep_iface) {
635                         err = usb_set_interface(subs->dev, subs->interface, 0);
636                         if (err < 0) {
637                                 dev_err(&dev->dev,
638                                         "%d:%d: return to setting 0 failed (%d)\n",
639                                         fmt->iface, fmt->altsetting, err);
640                                 return -EIO;
641                         }
642                 }
643                 subs->interface = -1;
644                 subs->altset_idx = 0;
645         }
646
647         if (subs->need_setup_fmt)
648                 subs->need_setup_fmt = false;
649
650         /* set interface */
651         if (iface->cur_altsetting != alts) {
652                 err = snd_usb_select_mode_quirk(subs, fmt);
653                 if (err < 0)
654                         return -EIO;
655
656                 err = usb_set_interface(dev, fmt->iface, fmt->altsetting);
657                 if (err < 0) {
658                         dev_err(&dev->dev,
659                                 "%d:%d: usb_set_interface failed (%d)\n",
660                                 fmt->iface, fmt->altsetting, err);
661                         return -EIO;
662                 }
663                 dev_dbg(&dev->dev, "setting usb interface %d:%d\n",
664                         fmt->iface, fmt->altsetting);
665                 snd_usb_set_interface_quirk(dev);
666         }
667
668         subs->interface = fmt->iface;
669         subs->altset_idx = fmt->altset_idx;
670         subs->data_endpoint = snd_usb_add_endpoint(subs->stream->chip,
671                                                    alts, fmt->endpoint, subs->direction,
672                                                    SND_USB_ENDPOINT_TYPE_DATA);
673
674         if (!subs->data_endpoint)
675                 return -EINVAL;
676
677         err = set_sync_endpoint(subs, fmt);
678         if (err < 0)
679                 return err;
680
681         err = snd_usb_init_pitch(subs->stream->chip, fmt->iface, alts, fmt);
682         if (err < 0)
683                 return err;
684
685         subs->cur_audiofmt = fmt;
686
687         snd_usb_set_format_quirk(subs, fmt);
688
689         return 0;
690 }
691
692 /*
693  * Return the score of matching two audioformats.
694  * Veto the audioformat if:
695  * - It has no channels for some reason.
696  * - Requested PCM format is not supported.
697  * - Requested sample rate is not supported.
698  */
699 static int match_endpoint_audioformats(struct snd_usb_substream *subs,
700                                        struct audioformat *fp,
701                                        struct audioformat *match, int rate,
702                                        snd_pcm_format_t pcm_format)
703 {
704         int i;
705         int score = 0;
706
707         if (fp->channels < 1) {
708                 dev_dbg(&subs->dev->dev,
709                         "%s: (fmt @%p) no channels\n", __func__, fp);
710                 return 0;
711         }
712
713         if (!(fp->formats & pcm_format_to_bits(pcm_format))) {
714                 dev_dbg(&subs->dev->dev,
715                         "%s: (fmt @%p) no match for format %d\n", __func__,
716                         fp, pcm_format);
717                 return 0;
718         }
719
720         for (i = 0; i < fp->nr_rates; i++) {
721                 if (fp->rate_table[i] == rate) {
722                         score++;
723                         break;
724                 }
725         }
726         if (!score) {
727                 dev_dbg(&subs->dev->dev,
728                         "%s: (fmt @%p) no match for rate %d\n", __func__,
729                         fp, rate);
730                 return 0;
731         }
732
733         if (fp->channels == match->channels)
734                 score++;
735
736         dev_dbg(&subs->dev->dev,
737                 "%s: (fmt @%p) score %d\n", __func__, fp, score);
738
739         return score;
740 }
741
742 /*
743  * Configure the sync ep using the rate and pcm format of the data ep.
744  */
745 static int configure_sync_endpoint(struct snd_usb_substream *subs)
746 {
747         int ret;
748         struct audioformat *fp;
749         struct audioformat *sync_fp = NULL;
750         int cur_score = 0;
751         int sync_period_bytes = subs->period_bytes;
752         struct snd_usb_substream *sync_subs =
753                 &subs->stream->substream[subs->direction ^ 1];
754
755         if (subs->sync_endpoint->type != SND_USB_ENDPOINT_TYPE_DATA ||
756             !subs->stream)
757                 return snd_usb_endpoint_set_params(subs->sync_endpoint,
758                                                    subs->pcm_format,
759                                                    subs->channels,
760                                                    subs->period_bytes,
761                                                    0, 0,
762                                                    subs->cur_rate,
763                                                    subs->cur_audiofmt,
764                                                    NULL);
765
766         /* Try to find the best matching audioformat. */
767         list_for_each_entry(fp, &sync_subs->fmt_list, list) {
768                 int score = match_endpoint_audioformats(subs,
769                                                         fp, subs->cur_audiofmt,
770                         subs->cur_rate, subs->pcm_format);
771
772                 if (score > cur_score) {
773                         sync_fp = fp;
774                         cur_score = score;
775                 }
776         }
777
778         if (unlikely(sync_fp == NULL)) {
779                 dev_err(&subs->dev->dev,
780                         "%s: no valid audioformat for sync ep %x found\n",
781                         __func__, sync_subs->ep_num);
782                 return -EINVAL;
783         }
784
785         /*
786          * Recalculate the period bytes if channel number differ between
787          * data and sync ep audioformat.
788          */
789         if (sync_fp->channels != subs->channels) {
790                 sync_period_bytes = (subs->period_bytes / subs->channels) *
791                         sync_fp->channels;
792                 dev_dbg(&subs->dev->dev,
793                         "%s: adjusted sync ep period bytes (%d -> %d)\n",
794                         __func__, subs->period_bytes, sync_period_bytes);
795         }
796
797         ret = snd_usb_endpoint_set_params(subs->sync_endpoint,
798                                           subs->pcm_format,
799                                           sync_fp->channels,
800                                           sync_period_bytes,
801                                           0, 0,
802                                           subs->cur_rate,
803                                           sync_fp,
804                                           NULL);
805
806         return ret;
807 }
808
809 /*
810  * configure endpoint params
811  *
812  * called  during initial setup and upon resume
813  */
814 static int configure_endpoint(struct snd_usb_substream *subs)
815 {
816         int ret;
817
818         /* format changed */
819         stop_endpoints(subs);
820         sync_pending_stops(subs);
821         ret = snd_usb_endpoint_set_params(subs->data_endpoint,
822                                           subs->pcm_format,
823                                           subs->channels,
824                                           subs->period_bytes,
825                                           subs->period_frames,
826                                           subs->buffer_periods,
827                                           subs->cur_rate,
828                                           subs->cur_audiofmt,
829                                           subs->sync_endpoint);
830         if (ret < 0)
831                 return ret;
832
833         if (subs->sync_endpoint)
834                 ret = configure_sync_endpoint(subs);
835
836         return ret;
837 }
838
839 static int snd_usb_pcm_change_state(struct snd_usb_substream *subs, int state)
840 {
841         int ret;
842
843         if (!subs->str_pd)
844                 return 0;
845
846         ret = snd_usb_power_domain_set(subs->stream->chip, subs->str_pd, state);
847         if (ret < 0) {
848                 dev_err(&subs->dev->dev,
849                         "Cannot change Power Domain ID: %d to state: %d. Err: %d\n",
850                         subs->str_pd->pd_id, state, ret);
851                 return ret;
852         }
853
854         return 0;
855 }
856
857 int snd_usb_pcm_suspend(struct snd_usb_stream *as)
858 {
859         int ret;
860
861         ret = snd_usb_pcm_change_state(&as->substream[0], UAC3_PD_STATE_D2);
862         if (ret < 0)
863                 return ret;
864
865         ret = snd_usb_pcm_change_state(&as->substream[1], UAC3_PD_STATE_D2);
866         if (ret < 0)
867                 return ret;
868
869         return 0;
870 }
871
872 int snd_usb_pcm_resume(struct snd_usb_stream *as)
873 {
874         int ret;
875
876         ret = snd_usb_pcm_change_state(&as->substream[0], UAC3_PD_STATE_D1);
877         if (ret < 0)
878                 return ret;
879
880         ret = snd_usb_pcm_change_state(&as->substream[1], UAC3_PD_STATE_D1);
881         if (ret < 0)
882                 return ret;
883
884         return 0;
885 }
886
887 /*
888  * hw_params callback
889  *
890  * allocate a buffer and set the given audio format.
891  *
892  * so far we use a physically linear buffer although packetize transfer
893  * doesn't need a continuous area.
894  * if sg buffer is supported on the later version of alsa, we'll follow
895  * that.
896  */
897 static int snd_usb_hw_params(struct snd_pcm_substream *substream,
898                              struct snd_pcm_hw_params *hw_params)
899 {
900         struct snd_usb_substream *subs = substream->runtime->private_data;
901         struct audioformat *fmt;
902         int ret;
903
904         ret = snd_media_start_pipeline(subs);
905         if (ret)
906                 return ret;
907
908         subs->pcm_format = params_format(hw_params);
909         subs->period_bytes = params_period_bytes(hw_params);
910         subs->period_frames = params_period_size(hw_params);
911         subs->buffer_periods = params_periods(hw_params);
912         subs->channels = params_channels(hw_params);
913         subs->cur_rate = params_rate(hw_params);
914
915         fmt = find_format(subs);
916         if (!fmt) {
917                 dev_dbg(&subs->dev->dev,
918                         "cannot set format: format = %#x, rate = %d, channels = %d\n",
919                            subs->pcm_format, subs->cur_rate, subs->channels);
920                 ret = -EINVAL;
921                 goto stop_pipeline;
922         }
923
924         ret = snd_usb_lock_shutdown(subs->stream->chip);
925         if (ret < 0)
926                 goto stop_pipeline;
927
928         ret = snd_usb_pcm_change_state(subs, UAC3_PD_STATE_D0);
929         if (ret < 0)
930                 goto unlock;
931
932         ret = set_format(subs, fmt);
933         if (ret < 0)
934                 goto unlock;
935
936         subs->interface = fmt->iface;
937         subs->altset_idx = fmt->altset_idx;
938         subs->need_setup_ep = true;
939
940  unlock:
941         snd_usb_unlock_shutdown(subs->stream->chip);
942         if (ret < 0)
943                 goto stop_pipeline;
944         return ret;
945
946  stop_pipeline:
947         snd_media_stop_pipeline(subs);
948         return ret;
949 }
950
951 /*
952  * hw_free callback
953  *
954  * reset the audio format and release the buffer
955  */
956 static int snd_usb_hw_free(struct snd_pcm_substream *substream)
957 {
958         struct snd_usb_substream *subs = substream->runtime->private_data;
959
960         snd_media_stop_pipeline(subs);
961         subs->cur_audiofmt = NULL;
962         subs->cur_rate = 0;
963         subs->period_bytes = 0;
964         if (!snd_usb_lock_shutdown(subs->stream->chip)) {
965                 stop_endpoints(subs);
966                 sync_pending_stops(subs);
967                 snd_usb_endpoint_deactivate(subs->sync_endpoint);
968                 snd_usb_endpoint_deactivate(subs->data_endpoint);
969                 if (subs->data_endpoint) {
970                         subs->data_endpoint->sync_master = NULL;
971                         subs->data_endpoint = NULL;
972                 }
973                 subs->sync_endpoint = NULL;
974                 snd_usb_unlock_shutdown(subs->stream->chip);
975         }
976
977         return 0;
978 }
979
980 /*
981  * prepare callback
982  *
983  * only a few subtle things...
984  */
985 static int snd_usb_pcm_prepare(struct snd_pcm_substream *substream)
986 {
987         struct snd_pcm_runtime *runtime = substream->runtime;
988         struct snd_usb_substream *subs = runtime->private_data;
989         struct usb_host_interface *alts;
990         struct usb_interface *iface;
991         int ret;
992
993         if (! subs->cur_audiofmt) {
994                 dev_err(&subs->dev->dev, "no format is specified!\n");
995                 return -ENXIO;
996         }
997
998         ret = snd_usb_lock_shutdown(subs->stream->chip);
999         if (ret < 0)
1000                 return ret;
1001         if (snd_BUG_ON(!subs->data_endpoint)) {
1002                 ret = -EIO;
1003                 goto unlock;
1004         }
1005
1006         ret = snd_usb_pcm_change_state(subs, UAC3_PD_STATE_D0);
1007         if (ret < 0)
1008                 goto unlock;
1009
1010         ret = set_format(subs, subs->cur_audiofmt);
1011         if (ret < 0)
1012                 goto unlock;
1013
1014         if (subs->need_setup_ep) {
1015
1016                 iface = usb_ifnum_to_if(subs->dev, subs->cur_audiofmt->iface);
1017                 alts = &iface->altsetting[subs->cur_audiofmt->altset_idx];
1018                 ret = snd_usb_init_sample_rate(subs->stream->chip,
1019                                                subs->cur_audiofmt->iface,
1020                                                alts,
1021                                                subs->cur_audiofmt,
1022                                                subs->cur_rate);
1023                 if (ret < 0)
1024                         goto unlock;
1025
1026                 ret = configure_endpoint(subs);
1027                 if (ret < 0)
1028                         goto unlock;
1029                 subs->need_setup_ep = false;
1030         }
1031
1032         /* some unit conversions in runtime */
1033         subs->data_endpoint->maxframesize =
1034                 bytes_to_frames(runtime, subs->data_endpoint->maxpacksize);
1035         subs->data_endpoint->curframesize =
1036                 bytes_to_frames(runtime, subs->data_endpoint->curpacksize);
1037
1038         /* reset the pointer */
1039         subs->hwptr_done = 0;
1040         subs->transfer_done = 0;
1041         subs->last_delay = 0;
1042         subs->last_frame_number = 0;
1043         runtime->delay = 0;
1044
1045         /* for playback, submit the URBs now; otherwise, the first hwptr_done
1046          * updates for all URBs would happen at the same time when starting */
1047         if (subs->direction == SNDRV_PCM_STREAM_PLAYBACK)
1048                 ret = start_endpoints(subs);
1049
1050  unlock:
1051         snd_usb_unlock_shutdown(subs->stream->chip);
1052         return ret;
1053 }
1054
1055 static const struct snd_pcm_hardware snd_usb_hardware =
1056 {
1057         .info =                 SNDRV_PCM_INFO_MMAP |
1058                                 SNDRV_PCM_INFO_MMAP_VALID |
1059                                 SNDRV_PCM_INFO_BATCH |
1060                                 SNDRV_PCM_INFO_INTERLEAVED |
1061                                 SNDRV_PCM_INFO_BLOCK_TRANSFER |
1062                                 SNDRV_PCM_INFO_PAUSE,
1063         .buffer_bytes_max =     1024 * 1024,
1064         .period_bytes_min =     64,
1065         .period_bytes_max =     512 * 1024,
1066         .periods_min =          2,
1067         .periods_max =          1024,
1068 };
1069
1070 static int hw_check_valid_format(struct snd_usb_substream *subs,
1071                                  struct snd_pcm_hw_params *params,
1072                                  struct audioformat *fp)
1073 {
1074         struct snd_interval *it = hw_param_interval(params, SNDRV_PCM_HW_PARAM_RATE);
1075         struct snd_interval *ct = hw_param_interval(params, SNDRV_PCM_HW_PARAM_CHANNELS);
1076         struct snd_mask *fmts = hw_param_mask(params, SNDRV_PCM_HW_PARAM_FORMAT);
1077         struct snd_interval *pt = hw_param_interval(params, SNDRV_PCM_HW_PARAM_PERIOD_TIME);
1078         struct snd_mask check_fmts;
1079         unsigned int ptime;
1080
1081         /* check the format */
1082         snd_mask_none(&check_fmts);
1083         check_fmts.bits[0] = (u32)fp->formats;
1084         check_fmts.bits[1] = (u32)(fp->formats >> 32);
1085         snd_mask_intersect(&check_fmts, fmts);
1086         if (snd_mask_empty(&check_fmts)) {
1087                 hwc_debug("   > check: no supported format %d\n", fp->format);
1088                 return 0;
1089         }
1090         /* check the channels */
1091         if (fp->channels < ct->min || fp->channels > ct->max) {
1092                 hwc_debug("   > check: no valid channels %d (%d/%d)\n", fp->channels, ct->min, ct->max);
1093                 return 0;
1094         }
1095         /* check the rate is within the range */
1096         if (fp->rate_min > it->max || (fp->rate_min == it->max && it->openmax)) {
1097                 hwc_debug("   > check: rate_min %d > max %d\n", fp->rate_min, it->max);
1098                 return 0;
1099         }
1100         if (fp->rate_max < it->min || (fp->rate_max == it->min && it->openmin)) {
1101                 hwc_debug("   > check: rate_max %d < min %d\n", fp->rate_max, it->min);
1102                 return 0;
1103         }
1104         /* check whether the period time is >= the data packet interval */
1105         if (subs->speed != USB_SPEED_FULL) {
1106                 ptime = 125 * (1 << fp->datainterval);
1107                 if (ptime > pt->max || (ptime == pt->max && pt->openmax)) {
1108                         hwc_debug("   > check: ptime %u > max %u\n", ptime, pt->max);
1109                         return 0;
1110                 }
1111         }
1112         return 1;
1113 }
1114
1115 static int hw_rule_rate(struct snd_pcm_hw_params *params,
1116                         struct snd_pcm_hw_rule *rule)
1117 {
1118         struct snd_usb_substream *subs = rule->private;
1119         struct audioformat *fp;
1120         struct snd_interval *it = hw_param_interval(params, SNDRV_PCM_HW_PARAM_RATE);
1121         unsigned int rmin, rmax, r;
1122         int changed;
1123         int i;
1124
1125         hwc_debug("hw_rule_rate: (%d,%d)\n", it->min, it->max);
1126         rmin = UINT_MAX;
1127         rmax = 0;
1128         list_for_each_entry(fp, &subs->fmt_list, list) {
1129                 if (!hw_check_valid_format(subs, params, fp))
1130                         continue;
1131                 if (fp->rate_table && fp->nr_rates) {
1132                         for (i = 0; i < fp->nr_rates; i++) {
1133                                 r = fp->rate_table[i];
1134                                 if (!snd_interval_test(it, r))
1135                                         continue;
1136                                 rmin = min(rmin, r);
1137                                 rmax = max(rmax, r);
1138                         }
1139                 } else {
1140                         rmin = min(rmin, fp->rate_min);
1141                         rmax = max(rmax, fp->rate_max);
1142                 }
1143         }
1144
1145         if (rmin > rmax) {
1146                 hwc_debug("  --> get empty\n");
1147                 it->empty = 1;
1148                 return -EINVAL;
1149         }
1150
1151         changed = 0;
1152         if (it->min < rmin) {
1153                 it->min = rmin;
1154                 it->openmin = 0;
1155                 changed = 1;
1156         }
1157         if (it->max > rmax) {
1158                 it->max = rmax;
1159                 it->openmax = 0;
1160                 changed = 1;
1161         }
1162         if (snd_interval_checkempty(it)) {
1163                 it->empty = 1;
1164                 return -EINVAL;
1165         }
1166         hwc_debug("  --> (%d, %d) (changed = %d)\n", it->min, it->max, changed);
1167         return changed;
1168 }
1169
1170
1171 static int hw_rule_channels(struct snd_pcm_hw_params *params,
1172                             struct snd_pcm_hw_rule *rule)
1173 {
1174         struct snd_usb_substream *subs = rule->private;
1175         struct audioformat *fp;
1176         struct snd_interval *it = hw_param_interval(params, SNDRV_PCM_HW_PARAM_CHANNELS);
1177         unsigned int rmin, rmax;
1178         int changed;
1179
1180         hwc_debug("hw_rule_channels: (%d,%d)\n", it->min, it->max);
1181         changed = 0;
1182         rmin = rmax = 0;
1183         list_for_each_entry(fp, &subs->fmt_list, list) {
1184                 if (!hw_check_valid_format(subs, params, fp))
1185                         continue;
1186                 if (changed++) {
1187                         if (rmin > fp->channels)
1188                                 rmin = fp->channels;
1189                         if (rmax < fp->channels)
1190                                 rmax = fp->channels;
1191                 } else {
1192                         rmin = fp->channels;
1193                         rmax = fp->channels;
1194                 }
1195         }
1196
1197         if (!changed) {
1198                 hwc_debug("  --> get empty\n");
1199                 it->empty = 1;
1200                 return -EINVAL;
1201         }
1202
1203         changed = 0;
1204         if (it->min < rmin) {
1205                 it->min = rmin;
1206                 it->openmin = 0;
1207                 changed = 1;
1208         }
1209         if (it->max > rmax) {
1210                 it->max = rmax;
1211                 it->openmax = 0;
1212                 changed = 1;
1213         }
1214         if (snd_interval_checkempty(it)) {
1215                 it->empty = 1;
1216                 return -EINVAL;
1217         }
1218         hwc_debug("  --> (%d, %d) (changed = %d)\n", it->min, it->max, changed);
1219         return changed;
1220 }
1221
1222 static int hw_rule_format(struct snd_pcm_hw_params *params,
1223                           struct snd_pcm_hw_rule *rule)
1224 {
1225         struct snd_usb_substream *subs = rule->private;
1226         struct audioformat *fp;
1227         struct snd_mask *fmt = hw_param_mask(params, SNDRV_PCM_HW_PARAM_FORMAT);
1228         u64 fbits;
1229         u32 oldbits[2];
1230         int changed;
1231
1232         hwc_debug("hw_rule_format: %x:%x\n", fmt->bits[0], fmt->bits[1]);
1233         fbits = 0;
1234         list_for_each_entry(fp, &subs->fmt_list, list) {
1235                 if (!hw_check_valid_format(subs, params, fp))
1236                         continue;
1237                 fbits |= fp->formats;
1238         }
1239
1240         oldbits[0] = fmt->bits[0];
1241         oldbits[1] = fmt->bits[1];
1242         fmt->bits[0] &= (u32)fbits;
1243         fmt->bits[1] &= (u32)(fbits >> 32);
1244         if (!fmt->bits[0] && !fmt->bits[1]) {
1245                 hwc_debug("  --> get empty\n");
1246                 return -EINVAL;
1247         }
1248         changed = (oldbits[0] != fmt->bits[0] || oldbits[1] != fmt->bits[1]);
1249         hwc_debug("  --> %x:%x (changed = %d)\n", fmt->bits[0], fmt->bits[1], changed);
1250         return changed;
1251 }
1252
1253 static int hw_rule_period_time(struct snd_pcm_hw_params *params,
1254                                struct snd_pcm_hw_rule *rule)
1255 {
1256         struct snd_usb_substream *subs = rule->private;
1257         struct audioformat *fp;
1258         struct snd_interval *it;
1259         unsigned char min_datainterval;
1260         unsigned int pmin;
1261         int changed;
1262
1263         it = hw_param_interval(params, SNDRV_PCM_HW_PARAM_PERIOD_TIME);
1264         hwc_debug("hw_rule_period_time: (%u,%u)\n", it->min, it->max);
1265         min_datainterval = 0xff;
1266         list_for_each_entry(fp, &subs->fmt_list, list) {
1267                 if (!hw_check_valid_format(subs, params, fp))
1268                         continue;
1269                 min_datainterval = min(min_datainterval, fp->datainterval);
1270         }
1271         if (min_datainterval == 0xff) {
1272                 hwc_debug("  --> get empty\n");
1273                 it->empty = 1;
1274                 return -EINVAL;
1275         }
1276         pmin = 125 * (1 << min_datainterval);
1277         changed = 0;
1278         if (it->min < pmin) {
1279                 it->min = pmin;
1280                 it->openmin = 0;
1281                 changed = 1;
1282         }
1283         if (snd_interval_checkempty(it)) {
1284                 it->empty = 1;
1285                 return -EINVAL;
1286         }
1287         hwc_debug("  --> (%u,%u) (changed = %d)\n", it->min, it->max, changed);
1288         return changed;
1289 }
1290
1291
1292 /*
1293  * set up the runtime hardware information.
1294  */
1295
1296 static int setup_hw_info(struct snd_pcm_runtime *runtime, struct snd_usb_substream *subs)
1297 {
1298         struct audioformat *fp;
1299         unsigned int pt, ptmin;
1300         int param_period_time_if_needed;
1301         int err;
1302
1303         runtime->hw.formats = subs->formats;
1304
1305         runtime->hw.rate_min = 0x7fffffff;
1306         runtime->hw.rate_max = 0;
1307         runtime->hw.channels_min = 256;
1308         runtime->hw.channels_max = 0;
1309         runtime->hw.rates = 0;
1310         ptmin = UINT_MAX;
1311         /* check min/max rates and channels */
1312         list_for_each_entry(fp, &subs->fmt_list, list) {
1313                 runtime->hw.rates |= fp->rates;
1314                 if (runtime->hw.rate_min > fp->rate_min)
1315                         runtime->hw.rate_min = fp->rate_min;
1316                 if (runtime->hw.rate_max < fp->rate_max)
1317                         runtime->hw.rate_max = fp->rate_max;
1318                 if (runtime->hw.channels_min > fp->channels)
1319                         runtime->hw.channels_min = fp->channels;
1320                 if (runtime->hw.channels_max < fp->channels)
1321                         runtime->hw.channels_max = fp->channels;
1322                 if (fp->fmt_type == UAC_FORMAT_TYPE_II && fp->frame_size > 0) {
1323                         /* FIXME: there might be more than one audio formats... */
1324                         runtime->hw.period_bytes_min = runtime->hw.period_bytes_max =
1325                                 fp->frame_size;
1326                 }
1327                 pt = 125 * (1 << fp->datainterval);
1328                 ptmin = min(ptmin, pt);
1329         }
1330
1331         param_period_time_if_needed = SNDRV_PCM_HW_PARAM_PERIOD_TIME;
1332         if (subs->speed == USB_SPEED_FULL)
1333                 /* full speed devices have fixed data packet interval */
1334                 ptmin = 1000;
1335         if (ptmin == 1000)
1336                 /* if period time doesn't go below 1 ms, no rules needed */
1337                 param_period_time_if_needed = -1;
1338
1339         err = snd_pcm_hw_constraint_minmax(runtime,
1340                                            SNDRV_PCM_HW_PARAM_PERIOD_TIME,
1341                                            ptmin, UINT_MAX);
1342         if (err < 0)
1343                 return err;
1344
1345         err = snd_pcm_hw_rule_add(runtime, 0, SNDRV_PCM_HW_PARAM_RATE,
1346                                   hw_rule_rate, subs,
1347                                   SNDRV_PCM_HW_PARAM_FORMAT,
1348                                   SNDRV_PCM_HW_PARAM_CHANNELS,
1349                                   param_period_time_if_needed,
1350                                   -1);
1351         if (err < 0)
1352                 return err;
1353         err = snd_pcm_hw_rule_add(runtime, 0, SNDRV_PCM_HW_PARAM_CHANNELS,
1354                                   hw_rule_channels, subs,
1355                                   SNDRV_PCM_HW_PARAM_FORMAT,
1356                                   SNDRV_PCM_HW_PARAM_RATE,
1357                                   param_period_time_if_needed,
1358                                   -1);
1359         if (err < 0)
1360                 return err;
1361         err = snd_pcm_hw_rule_add(runtime, 0, SNDRV_PCM_HW_PARAM_FORMAT,
1362                                   hw_rule_format, subs,
1363                                   SNDRV_PCM_HW_PARAM_RATE,
1364                                   SNDRV_PCM_HW_PARAM_CHANNELS,
1365                                   param_period_time_if_needed,
1366                                   -1);
1367         if (err < 0)
1368                 return err;
1369         if (param_period_time_if_needed >= 0) {
1370                 err = snd_pcm_hw_rule_add(runtime, 0,
1371                                           SNDRV_PCM_HW_PARAM_PERIOD_TIME,
1372                                           hw_rule_period_time, subs,
1373                                           SNDRV_PCM_HW_PARAM_FORMAT,
1374                                           SNDRV_PCM_HW_PARAM_CHANNELS,
1375                                           SNDRV_PCM_HW_PARAM_RATE,
1376                                           -1);
1377                 if (err < 0)
1378                         return err;
1379         }
1380
1381         return snd_usb_autoresume(subs->stream->chip);
1382 }
1383
1384 static int snd_usb_pcm_open(struct snd_pcm_substream *substream)
1385 {
1386         int direction = substream->stream;
1387         struct snd_usb_stream *as = snd_pcm_substream_chip(substream);
1388         struct snd_pcm_runtime *runtime = substream->runtime;
1389         struct snd_usb_substream *subs = &as->substream[direction];
1390         int ret;
1391
1392         subs->interface = -1;
1393         subs->altset_idx = 0;
1394         runtime->hw = snd_usb_hardware;
1395         runtime->private_data = subs;
1396         subs->pcm_substream = substream;
1397         /* runtime PM is also done there */
1398
1399         /* initialize DSD/DOP context */
1400         subs->dsd_dop.byte_idx = 0;
1401         subs->dsd_dop.channel = 0;
1402         subs->dsd_dop.marker = 1;
1403
1404         ret = setup_hw_info(runtime, subs);
1405         if (ret == 0) {
1406                 ret = snd_media_stream_init(subs, as->pcm, direction);
1407                 if (ret)
1408                         snd_usb_autosuspend(subs->stream->chip);
1409         }
1410         return ret;
1411 }
1412
1413 static int snd_usb_pcm_close(struct snd_pcm_substream *substream)
1414 {
1415         int direction = substream->stream;
1416         struct snd_usb_stream *as = snd_pcm_substream_chip(substream);
1417         struct snd_usb_substream *subs = &as->substream[direction];
1418         int ret;
1419
1420         snd_media_stop_pipeline(subs);
1421
1422         if (!as->chip->keep_iface &&
1423             subs->interface >= 0 &&
1424             !snd_usb_lock_shutdown(subs->stream->chip)) {
1425                 usb_set_interface(subs->dev, subs->interface, 0);
1426                 subs->interface = -1;
1427                 ret = snd_usb_pcm_change_state(subs, UAC3_PD_STATE_D1);
1428                 snd_usb_unlock_shutdown(subs->stream->chip);
1429                 if (ret < 0)
1430                         return ret;
1431         }
1432
1433         subs->pcm_substream = NULL;
1434         snd_usb_autosuspend(subs->stream->chip);
1435
1436         return 0;
1437 }
1438
1439 /* Since a URB can handle only a single linear buffer, we must use double
1440  * buffering when the data to be transferred overflows the buffer boundary.
1441  * To avoid inconsistencies when updating hwptr_done, we use double buffering
1442  * for all URBs.
1443  */
1444 static void retire_capture_urb(struct snd_usb_substream *subs,
1445                                struct urb *urb)
1446 {
1447         struct snd_pcm_runtime *runtime = subs->pcm_substream->runtime;
1448         unsigned int stride, frames, bytes, oldptr;
1449         int i, period_elapsed = 0;
1450         unsigned long flags;
1451         unsigned char *cp;
1452         int current_frame_number;
1453
1454         /* read frame number here, update pointer in critical section */
1455         current_frame_number = usb_get_current_frame_number(subs->dev);
1456
1457         stride = runtime->frame_bits >> 3;
1458
1459         for (i = 0; i < urb->number_of_packets; i++) {
1460                 cp = (unsigned char *)urb->transfer_buffer + urb->iso_frame_desc[i].offset + subs->pkt_offset_adj;
1461                 if (urb->iso_frame_desc[i].status && printk_ratelimit()) {
1462                         dev_dbg(&subs->dev->dev, "frame %d active: %d\n",
1463                                 i, urb->iso_frame_desc[i].status);
1464                         // continue;
1465                 }
1466                 bytes = urb->iso_frame_desc[i].actual_length;
1467                 if (subs->stream_offset_adj > 0) {
1468                         unsigned int adj = min(subs->stream_offset_adj, bytes);
1469                         cp += adj;
1470                         bytes -= adj;
1471                         subs->stream_offset_adj -= adj;
1472                 }
1473                 frames = bytes / stride;
1474                 if (!subs->txfr_quirk)
1475                         bytes = frames * stride;
1476                 if (bytes % (runtime->sample_bits >> 3) != 0) {
1477                         int oldbytes = bytes;
1478                         bytes = frames * stride;
1479                         dev_warn_ratelimited(&subs->dev->dev,
1480                                  "Corrected urb data len. %d->%d\n",
1481                                                         oldbytes, bytes);
1482                 }
1483                 /* update the current pointer */
1484                 spin_lock_irqsave(&subs->lock, flags);
1485                 oldptr = subs->hwptr_done;
1486                 subs->hwptr_done += bytes;
1487                 if (subs->hwptr_done >= runtime->buffer_size * stride)
1488                         subs->hwptr_done -= runtime->buffer_size * stride;
1489                 frames = (bytes + (oldptr % stride)) / stride;
1490                 subs->transfer_done += frames;
1491                 if (subs->transfer_done >= runtime->period_size) {
1492                         subs->transfer_done -= runtime->period_size;
1493                         period_elapsed = 1;
1494                 }
1495                 /* capture delay is by construction limited to one URB,
1496                  * reset delays here
1497                  */
1498                 runtime->delay = subs->last_delay = 0;
1499
1500                 /* realign last_frame_number */
1501                 subs->last_frame_number = current_frame_number;
1502                 subs->last_frame_number &= 0xFF; /* keep 8 LSBs */
1503
1504                 spin_unlock_irqrestore(&subs->lock, flags);
1505                 /* copy a data chunk */
1506                 if (oldptr + bytes > runtime->buffer_size * stride) {
1507                         unsigned int bytes1 =
1508                                         runtime->buffer_size * stride - oldptr;
1509                         memcpy(runtime->dma_area + oldptr, cp, bytes1);
1510                         memcpy(runtime->dma_area, cp + bytes1, bytes - bytes1);
1511                 } else {
1512                         memcpy(runtime->dma_area + oldptr, cp, bytes);
1513                 }
1514         }
1515
1516         if (period_elapsed)
1517                 snd_pcm_period_elapsed(subs->pcm_substream);
1518 }
1519
1520 static inline void fill_playback_urb_dsd_dop(struct snd_usb_substream *subs,
1521                                              struct urb *urb, unsigned int bytes)
1522 {
1523         struct snd_pcm_runtime *runtime = subs->pcm_substream->runtime;
1524         unsigned int stride = runtime->frame_bits >> 3;
1525         unsigned int dst_idx = 0;
1526         unsigned int src_idx = subs->hwptr_done;
1527         unsigned int wrap = runtime->buffer_size * stride;
1528         u8 *dst = urb->transfer_buffer;
1529         u8 *src = runtime->dma_area;
1530         u8 marker[] = { 0x05, 0xfa };
1531
1532         /*
1533          * The DSP DOP format defines a way to transport DSD samples over
1534          * normal PCM data endpoints. It requires stuffing of marker bytes
1535          * (0x05 and 0xfa, alternating per sample frame), and then expects
1536          * 2 additional bytes of actual payload. The whole frame is stored
1537          * LSB.
1538          *
1539          * Hence, for a stereo transport, the buffer layout looks like this,
1540          * where L refers to left channel samples and R to right.
1541          *
1542          *   L1 L2 0x05   R1 R2 0x05   L3 L4 0xfa  R3 R4 0xfa
1543          *   L5 L6 0x05   R5 R6 0x05   L7 L8 0xfa  R7 R8 0xfa
1544          *   .....
1545          *
1546          */
1547
1548         while (bytes--) {
1549                 if (++subs->dsd_dop.byte_idx == 3) {
1550                         /* frame boundary? */
1551                         dst[dst_idx++] = marker[subs->dsd_dop.marker];
1552                         src_idx += 2;
1553                         subs->dsd_dop.byte_idx = 0;
1554
1555                         if (++subs->dsd_dop.channel % runtime->channels == 0) {
1556                                 /* alternate the marker */
1557                                 subs->dsd_dop.marker++;
1558                                 subs->dsd_dop.marker %= ARRAY_SIZE(marker);
1559                                 subs->dsd_dop.channel = 0;
1560                         }
1561                 } else {
1562                         /* stuff the DSD payload */
1563                         int idx = (src_idx + subs->dsd_dop.byte_idx - 1) % wrap;
1564
1565                         if (subs->cur_audiofmt->dsd_bitrev)
1566                                 dst[dst_idx++] = bitrev8(src[idx]);
1567                         else
1568                                 dst[dst_idx++] = src[idx];
1569
1570                         subs->hwptr_done++;
1571                 }
1572         }
1573         if (subs->hwptr_done >= runtime->buffer_size * stride)
1574                 subs->hwptr_done -= runtime->buffer_size * stride;
1575 }
1576
1577 static void copy_to_urb(struct snd_usb_substream *subs, struct urb *urb,
1578                         int offset, int stride, unsigned int bytes)
1579 {
1580         struct snd_pcm_runtime *runtime = subs->pcm_substream->runtime;
1581
1582         if (subs->hwptr_done + bytes > runtime->buffer_size * stride) {
1583                 /* err, the transferred area goes over buffer boundary. */
1584                 unsigned int bytes1 =
1585                         runtime->buffer_size * stride - subs->hwptr_done;
1586                 memcpy(urb->transfer_buffer + offset,
1587                        runtime->dma_area + subs->hwptr_done, bytes1);
1588                 memcpy(urb->transfer_buffer + offset + bytes1,
1589                        runtime->dma_area, bytes - bytes1);
1590         } else {
1591                 memcpy(urb->transfer_buffer + offset,
1592                        runtime->dma_area + subs->hwptr_done, bytes);
1593         }
1594         subs->hwptr_done += bytes;
1595         if (subs->hwptr_done >= runtime->buffer_size * stride)
1596                 subs->hwptr_done -= runtime->buffer_size * stride;
1597 }
1598
1599 static unsigned int copy_to_urb_quirk(struct snd_usb_substream *subs,
1600                                       struct urb *urb, int stride,
1601                                       unsigned int bytes)
1602 {
1603         __le32 packet_length;
1604         int i;
1605
1606         /* Put __le32 length descriptor at start of each packet. */
1607         for (i = 0; i < urb->number_of_packets; i++) {
1608                 unsigned int length = urb->iso_frame_desc[i].length;
1609                 unsigned int offset = urb->iso_frame_desc[i].offset;
1610
1611                 packet_length = cpu_to_le32(length);
1612                 offset += i * sizeof(packet_length);
1613                 urb->iso_frame_desc[i].offset = offset;
1614                 urb->iso_frame_desc[i].length += sizeof(packet_length);
1615                 memcpy(urb->transfer_buffer + offset,
1616                        &packet_length, sizeof(packet_length));
1617                 copy_to_urb(subs, urb, offset + sizeof(packet_length),
1618                             stride, length);
1619         }
1620         /* Adjust transfer size accordingly. */
1621         bytes += urb->number_of_packets * sizeof(packet_length);
1622         return bytes;
1623 }
1624
1625 static void prepare_playback_urb(struct snd_usb_substream *subs,
1626                                  struct urb *urb)
1627 {
1628         struct snd_pcm_runtime *runtime = subs->pcm_substream->runtime;
1629         struct snd_usb_endpoint *ep = subs->data_endpoint;
1630         struct snd_urb_ctx *ctx = urb->context;
1631         unsigned int counts, frames, bytes;
1632         int i, stride, period_elapsed = 0;
1633         unsigned long flags;
1634
1635         stride = runtime->frame_bits >> 3;
1636
1637         frames = 0;
1638         urb->number_of_packets = 0;
1639         spin_lock_irqsave(&subs->lock, flags);
1640         subs->frame_limit += ep->max_urb_frames;
1641         for (i = 0; i < ctx->packets; i++) {
1642                 if (ctx->packet_size[i])
1643                         counts = ctx->packet_size[i];
1644                 else if (ep->sync_master)
1645                         counts = snd_usb_endpoint_slave_next_packet_size(ep);
1646                 else
1647                         counts = snd_usb_endpoint_next_packet_size(ep);
1648
1649                 /* set up descriptor */
1650                 urb->iso_frame_desc[i].offset = frames * ep->stride;
1651                 urb->iso_frame_desc[i].length = counts * ep->stride;
1652                 frames += counts;
1653                 urb->number_of_packets++;
1654                 subs->transfer_done += counts;
1655                 if (subs->transfer_done >= runtime->period_size) {
1656                         subs->transfer_done -= runtime->period_size;
1657                         subs->frame_limit = 0;
1658                         period_elapsed = 1;
1659                         if (subs->fmt_type == UAC_FORMAT_TYPE_II) {
1660                                 if (subs->transfer_done > 0) {
1661                                         /* FIXME: fill-max mode is not
1662                                          * supported yet */
1663                                         frames -= subs->transfer_done;
1664                                         counts -= subs->transfer_done;
1665                                         urb->iso_frame_desc[i].length =
1666                                                 counts * ep->stride;
1667                                         subs->transfer_done = 0;
1668                                 }
1669                                 i++;
1670                                 if (i < ctx->packets) {
1671                                         /* add a transfer delimiter */
1672                                         urb->iso_frame_desc[i].offset =
1673                                                 frames * ep->stride;
1674                                         urb->iso_frame_desc[i].length = 0;
1675                                         urb->number_of_packets++;
1676                                 }
1677                                 break;
1678                         }
1679                 }
1680                 /* finish at the period boundary or after enough frames */
1681                 if ((period_elapsed ||
1682                                 subs->transfer_done >= subs->frame_limit) &&
1683                     !snd_usb_endpoint_implicit_feedback_sink(ep))
1684                         break;
1685         }
1686         bytes = frames * ep->stride;
1687
1688         if (unlikely(subs->pcm_format == SNDRV_PCM_FORMAT_DSD_U16_LE &&
1689                      subs->cur_audiofmt->dsd_dop)) {
1690                 fill_playback_urb_dsd_dop(subs, urb, bytes);
1691         } else if (unlikely(subs->pcm_format == SNDRV_PCM_FORMAT_DSD_U8 &&
1692                            subs->cur_audiofmt->dsd_bitrev)) {
1693                 /* bit-reverse the bytes */
1694                 u8 *buf = urb->transfer_buffer;
1695                 for (i = 0; i < bytes; i++) {
1696                         int idx = (subs->hwptr_done + i)
1697                                 % (runtime->buffer_size * stride);
1698                         buf[i] = bitrev8(runtime->dma_area[idx]);
1699                 }
1700
1701                 subs->hwptr_done += bytes;
1702                 if (subs->hwptr_done >= runtime->buffer_size * stride)
1703                         subs->hwptr_done -= runtime->buffer_size * stride;
1704         } else {
1705                 /* usual PCM */
1706                 if (!subs->tx_length_quirk)
1707                         copy_to_urb(subs, urb, 0, stride, bytes);
1708                 else
1709                         bytes = copy_to_urb_quirk(subs, urb, stride, bytes);
1710                         /* bytes is now amount of outgoing data */
1711         }
1712
1713         /* update delay with exact number of samples queued */
1714         runtime->delay = subs->last_delay;
1715         runtime->delay += frames;
1716         subs->last_delay = runtime->delay;
1717
1718         /* realign last_frame_number */
1719         subs->last_frame_number = usb_get_current_frame_number(subs->dev);
1720         subs->last_frame_number &= 0xFF; /* keep 8 LSBs */
1721
1722         if (subs->trigger_tstamp_pending_update) {
1723                 /* this is the first actual URB submitted,
1724                  * update trigger timestamp to reflect actual start time
1725                  */
1726                 snd_pcm_gettime(runtime, &runtime->trigger_tstamp);
1727                 subs->trigger_tstamp_pending_update = false;
1728         }
1729
1730         spin_unlock_irqrestore(&subs->lock, flags);
1731         urb->transfer_buffer_length = bytes;
1732         if (period_elapsed)
1733                 snd_pcm_period_elapsed(subs->pcm_substream);
1734 }
1735
1736 /*
1737  * process after playback data complete
1738  * - decrease the delay count again
1739  */
1740 static void retire_playback_urb(struct snd_usb_substream *subs,
1741                                struct urb *urb)
1742 {
1743         unsigned long flags;
1744         struct snd_pcm_runtime *runtime = subs->pcm_substream->runtime;
1745         struct snd_usb_endpoint *ep = subs->data_endpoint;
1746         int processed = urb->transfer_buffer_length / ep->stride;
1747         int est_delay;
1748
1749         /* ignore the delay accounting when processed=0 is given, i.e.
1750          * silent payloads are processed before handling the actual data
1751          */
1752         if (!processed)
1753                 return;
1754
1755         spin_lock_irqsave(&subs->lock, flags);
1756         if (!subs->last_delay)
1757                 goto out; /* short path */
1758
1759         est_delay = snd_usb_pcm_delay(subs, runtime->rate);
1760         /* update delay with exact number of samples played */
1761         if (processed > subs->last_delay)
1762                 subs->last_delay = 0;
1763         else
1764                 subs->last_delay -= processed;
1765         runtime->delay = subs->last_delay;
1766
1767         /*
1768          * Report when delay estimate is off by more than 2ms.
1769          * The error should be lower than 2ms since the estimate relies
1770          * on two reads of a counter updated every ms.
1771          */
1772         if (abs(est_delay - subs->last_delay) * 1000 > runtime->rate * 2)
1773                 dev_dbg_ratelimited(&subs->dev->dev,
1774                         "delay: estimated %d, actual %d\n",
1775                         est_delay, subs->last_delay);
1776
1777         if (!subs->running) {
1778                 /* update last_frame_number for delay counting here since
1779                  * prepare_playback_urb won't be called during pause
1780                  */
1781                 subs->last_frame_number =
1782                         usb_get_current_frame_number(subs->dev) & 0xff;
1783         }
1784
1785  out:
1786         spin_unlock_irqrestore(&subs->lock, flags);
1787 }
1788
1789 static int snd_usb_substream_playback_trigger(struct snd_pcm_substream *substream,
1790                                               int cmd)
1791 {
1792         struct snd_usb_substream *subs = substream->runtime->private_data;
1793
1794         switch (cmd) {
1795         case SNDRV_PCM_TRIGGER_START:
1796                 subs->trigger_tstamp_pending_update = true;
1797                 fallthrough;
1798         case SNDRV_PCM_TRIGGER_PAUSE_RELEASE:
1799                 subs->data_endpoint->prepare_data_urb = prepare_playback_urb;
1800                 subs->data_endpoint->retire_data_urb = retire_playback_urb;
1801                 subs->running = 1;
1802                 return 0;
1803         case SNDRV_PCM_TRIGGER_STOP:
1804                 stop_endpoints(subs);
1805                 subs->running = 0;
1806                 return 0;
1807         case SNDRV_PCM_TRIGGER_PAUSE_PUSH:
1808                 subs->data_endpoint->prepare_data_urb = NULL;
1809                 /* keep retire_data_urb for delay calculation */
1810                 subs->data_endpoint->retire_data_urb = retire_playback_urb;
1811                 subs->running = 0;
1812                 return 0;
1813         case SNDRV_PCM_TRIGGER_SUSPEND:
1814                 if (subs->stream->chip->setup_fmt_after_resume_quirk) {
1815                         stop_endpoints(subs);
1816                         subs->need_setup_fmt = true;
1817                         return 0;
1818                 }
1819                 break;
1820         }
1821
1822         return -EINVAL;
1823 }
1824
1825 static int snd_usb_substream_capture_trigger(struct snd_pcm_substream *substream,
1826                                              int cmd)
1827 {
1828         int err;
1829         struct snd_usb_substream *subs = substream->runtime->private_data;
1830
1831         switch (cmd) {
1832         case SNDRV_PCM_TRIGGER_START:
1833                 err = start_endpoints(subs);
1834                 if (err < 0)
1835                         return err;
1836
1837                 subs->data_endpoint->retire_data_urb = retire_capture_urb;
1838                 subs->running = 1;
1839                 return 0;
1840         case SNDRV_PCM_TRIGGER_STOP:
1841                 stop_endpoints(subs);
1842                 subs->data_endpoint->retire_data_urb = NULL;
1843                 subs->running = 0;
1844                 return 0;
1845         case SNDRV_PCM_TRIGGER_PAUSE_PUSH:
1846                 subs->data_endpoint->retire_data_urb = NULL;
1847                 subs->running = 0;
1848                 return 0;
1849         case SNDRV_PCM_TRIGGER_PAUSE_RELEASE:
1850                 subs->data_endpoint->retire_data_urb = retire_capture_urb;
1851                 subs->running = 1;
1852                 return 0;
1853         case SNDRV_PCM_TRIGGER_SUSPEND:
1854                 if (subs->stream->chip->setup_fmt_after_resume_quirk) {
1855                         stop_endpoints(subs);
1856                         subs->need_setup_fmt = true;
1857                         return 0;
1858                 }
1859                 break;
1860         }
1861
1862         return -EINVAL;
1863 }
1864
1865 static const struct snd_pcm_ops snd_usb_playback_ops = {
1866         .open =         snd_usb_pcm_open,
1867         .close =        snd_usb_pcm_close,
1868         .hw_params =    snd_usb_hw_params,
1869         .hw_free =      snd_usb_hw_free,
1870         .prepare =      snd_usb_pcm_prepare,
1871         .trigger =      snd_usb_substream_playback_trigger,
1872         .sync_stop =    snd_usb_pcm_sync_stop,
1873         .pointer =      snd_usb_pcm_pointer,
1874 };
1875
1876 static const struct snd_pcm_ops snd_usb_capture_ops = {
1877         .open =         snd_usb_pcm_open,
1878         .close =        snd_usb_pcm_close,
1879         .hw_params =    snd_usb_hw_params,
1880         .hw_free =      snd_usb_hw_free,
1881         .prepare =      snd_usb_pcm_prepare,
1882         .trigger =      snd_usb_substream_capture_trigger,
1883         .sync_stop =    snd_usb_pcm_sync_stop,
1884         .pointer =      snd_usb_pcm_pointer,
1885 };
1886
1887 void snd_usb_set_pcm_ops(struct snd_pcm *pcm, int stream)
1888 {
1889         const struct snd_pcm_ops *ops;
1890
1891         ops = stream == SNDRV_PCM_STREAM_PLAYBACK ?
1892                         &snd_usb_playback_ops : &snd_usb_capture_ops;
1893         snd_pcm_set_ops(pcm, stream, ops);
1894 }
1895
1896 void snd_usb_preallocate_buffer(struct snd_usb_substream *subs)
1897 {
1898         struct snd_pcm *pcm = subs->stream->pcm;
1899         struct snd_pcm_substream *s = pcm->streams[subs->direction].substream;
1900         struct device *dev = subs->dev->bus->controller;
1901
1902         if (snd_usb_use_vmalloc)
1903                 snd_pcm_set_managed_buffer(s, SNDRV_DMA_TYPE_VMALLOC,
1904                                            NULL, 0, 0);
1905         else
1906                 snd_pcm_set_managed_buffer(s, SNDRV_DMA_TYPE_DEV_SG,
1907                                            dev, 64*1024, 512*1024);
1908 }