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