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