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