GNU Linux-libre 4.9.292-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         iface = usb_ifnum_to_if(subs->dev, subs->cur_audiofmt->iface);
826         alts = &iface->altsetting[subs->cur_audiofmt->altset_idx];
827         ret = snd_usb_init_sample_rate(subs->stream->chip,
828                                        subs->cur_audiofmt->iface,
829                                        alts,
830                                        subs->cur_audiofmt,
831                                        subs->cur_rate);
832         if (ret < 0)
833                 goto unlock;
834
835         if (subs->need_setup_ep) {
836                 ret = configure_endpoint(subs);
837                 if (ret < 0)
838                         goto unlock;
839                 subs->need_setup_ep = false;
840         }
841
842         /* some unit conversions in runtime */
843         subs->data_endpoint->maxframesize =
844                 bytes_to_frames(runtime, subs->data_endpoint->maxpacksize);
845         subs->data_endpoint->curframesize =
846                 bytes_to_frames(runtime, subs->data_endpoint->curpacksize);
847
848         /* reset the pointer */
849         subs->hwptr_done = 0;
850         subs->transfer_done = 0;
851         subs->last_delay = 0;
852         subs->last_frame_number = 0;
853         runtime->delay = 0;
854
855         /* for playback, submit the URBs now; otherwise, the first hwptr_done
856          * updates for all URBs would happen at the same time when starting */
857         if (subs->direction == SNDRV_PCM_STREAM_PLAYBACK)
858                 ret = start_endpoints(subs);
859
860  unlock:
861         snd_usb_unlock_shutdown(subs->stream->chip);
862         return ret;
863 }
864
865 static struct snd_pcm_hardware snd_usb_hardware =
866 {
867         .info =                 SNDRV_PCM_INFO_MMAP |
868                                 SNDRV_PCM_INFO_MMAP_VALID |
869                                 SNDRV_PCM_INFO_BATCH |
870                                 SNDRV_PCM_INFO_INTERLEAVED |
871                                 SNDRV_PCM_INFO_BLOCK_TRANSFER |
872                                 SNDRV_PCM_INFO_PAUSE,
873         .buffer_bytes_max =     1024 * 1024,
874         .period_bytes_min =     64,
875         .period_bytes_max =     512 * 1024,
876         .periods_min =          2,
877         .periods_max =          1024,
878 };
879
880 static int hw_check_valid_format(struct snd_usb_substream *subs,
881                                  struct snd_pcm_hw_params *params,
882                                  struct audioformat *fp)
883 {
884         struct snd_interval *it = hw_param_interval(params, SNDRV_PCM_HW_PARAM_RATE);
885         struct snd_interval *ct = hw_param_interval(params, SNDRV_PCM_HW_PARAM_CHANNELS);
886         struct snd_mask *fmts = hw_param_mask(params, SNDRV_PCM_HW_PARAM_FORMAT);
887         struct snd_interval *pt = hw_param_interval(params, SNDRV_PCM_HW_PARAM_PERIOD_TIME);
888         struct snd_mask check_fmts;
889         unsigned int ptime;
890
891         /* check the format */
892         snd_mask_none(&check_fmts);
893         check_fmts.bits[0] = (u32)fp->formats;
894         check_fmts.bits[1] = (u32)(fp->formats >> 32);
895         snd_mask_intersect(&check_fmts, fmts);
896         if (snd_mask_empty(&check_fmts)) {
897                 hwc_debug("   > check: no supported format %d\n", fp->format);
898                 return 0;
899         }
900         /* check the channels */
901         if (fp->channels < ct->min || fp->channels > ct->max) {
902                 hwc_debug("   > check: no valid channels %d (%d/%d)\n", fp->channels, ct->min, ct->max);
903                 return 0;
904         }
905         /* check the rate is within the range */
906         if (fp->rate_min > it->max || (fp->rate_min == it->max && it->openmax)) {
907                 hwc_debug("   > check: rate_min %d > max %d\n", fp->rate_min, it->max);
908                 return 0;
909         }
910         if (fp->rate_max < it->min || (fp->rate_max == it->min && it->openmin)) {
911                 hwc_debug("   > check: rate_max %d < min %d\n", fp->rate_max, it->min);
912                 return 0;
913         }
914         /* check whether the period time is >= the data packet interval */
915         if (subs->speed != USB_SPEED_FULL) {
916                 ptime = 125 * (1 << fp->datainterval);
917                 if (ptime > pt->max || (ptime == pt->max && pt->openmax)) {
918                         hwc_debug("   > check: ptime %u > max %u\n", ptime, pt->max);
919                         return 0;
920                 }
921         }
922         return 1;
923 }
924
925 static int hw_rule_rate(struct snd_pcm_hw_params *params,
926                         struct snd_pcm_hw_rule *rule)
927 {
928         struct snd_usb_substream *subs = rule->private;
929         struct audioformat *fp;
930         struct snd_interval *it = hw_param_interval(params, SNDRV_PCM_HW_PARAM_RATE);
931         unsigned int rmin, rmax;
932         int changed;
933
934         hwc_debug("hw_rule_rate: (%d,%d)\n", it->min, it->max);
935         changed = 0;
936         rmin = rmax = 0;
937         list_for_each_entry(fp, &subs->fmt_list, list) {
938                 if (!hw_check_valid_format(subs, params, fp))
939                         continue;
940                 if (changed++) {
941                         if (rmin > fp->rate_min)
942                                 rmin = fp->rate_min;
943                         if (rmax < fp->rate_max)
944                                 rmax = fp->rate_max;
945                 } else {
946                         rmin = fp->rate_min;
947                         rmax = fp->rate_max;
948                 }
949         }
950
951         if (!changed) {
952                 hwc_debug("  --> get empty\n");
953                 it->empty = 1;
954                 return -EINVAL;
955         }
956
957         changed = 0;
958         if (it->min < rmin) {
959                 it->min = rmin;
960                 it->openmin = 0;
961                 changed = 1;
962         }
963         if (it->max > rmax) {
964                 it->max = rmax;
965                 it->openmax = 0;
966                 changed = 1;
967         }
968         if (snd_interval_checkempty(it)) {
969                 it->empty = 1;
970                 return -EINVAL;
971         }
972         hwc_debug("  --> (%d, %d) (changed = %d)\n", it->min, it->max, changed);
973         return changed;
974 }
975
976
977 static int hw_rule_channels(struct snd_pcm_hw_params *params,
978                             struct snd_pcm_hw_rule *rule)
979 {
980         struct snd_usb_substream *subs = rule->private;
981         struct audioformat *fp;
982         struct snd_interval *it = hw_param_interval(params, SNDRV_PCM_HW_PARAM_CHANNELS);
983         unsigned int rmin, rmax;
984         int changed;
985
986         hwc_debug("hw_rule_channels: (%d,%d)\n", it->min, it->max);
987         changed = 0;
988         rmin = rmax = 0;
989         list_for_each_entry(fp, &subs->fmt_list, list) {
990                 if (!hw_check_valid_format(subs, params, fp))
991                         continue;
992                 if (changed++) {
993                         if (rmin > fp->channels)
994                                 rmin = fp->channels;
995                         if (rmax < fp->channels)
996                                 rmax = fp->channels;
997                 } else {
998                         rmin = fp->channels;
999                         rmax = fp->channels;
1000                 }
1001         }
1002
1003         if (!changed) {
1004                 hwc_debug("  --> get empty\n");
1005                 it->empty = 1;
1006                 return -EINVAL;
1007         }
1008
1009         changed = 0;
1010         if (it->min < rmin) {
1011                 it->min = rmin;
1012                 it->openmin = 0;
1013                 changed = 1;
1014         }
1015         if (it->max > rmax) {
1016                 it->max = rmax;
1017                 it->openmax = 0;
1018                 changed = 1;
1019         }
1020         if (snd_interval_checkempty(it)) {
1021                 it->empty = 1;
1022                 return -EINVAL;
1023         }
1024         hwc_debug("  --> (%d, %d) (changed = %d)\n", it->min, it->max, changed);
1025         return changed;
1026 }
1027
1028 static int hw_rule_format(struct snd_pcm_hw_params *params,
1029                           struct snd_pcm_hw_rule *rule)
1030 {
1031         struct snd_usb_substream *subs = rule->private;
1032         struct audioformat *fp;
1033         struct snd_mask *fmt = hw_param_mask(params, SNDRV_PCM_HW_PARAM_FORMAT);
1034         u64 fbits;
1035         u32 oldbits[2];
1036         int changed;
1037
1038         hwc_debug("hw_rule_format: %x:%x\n", fmt->bits[0], fmt->bits[1]);
1039         fbits = 0;
1040         list_for_each_entry(fp, &subs->fmt_list, list) {
1041                 if (!hw_check_valid_format(subs, params, fp))
1042                         continue;
1043                 fbits |= fp->formats;
1044         }
1045
1046         oldbits[0] = fmt->bits[0];
1047         oldbits[1] = fmt->bits[1];
1048         fmt->bits[0] &= (u32)fbits;
1049         fmt->bits[1] &= (u32)(fbits >> 32);
1050         if (!fmt->bits[0] && !fmt->bits[1]) {
1051                 hwc_debug("  --> get empty\n");
1052                 return -EINVAL;
1053         }
1054         changed = (oldbits[0] != fmt->bits[0] || oldbits[1] != fmt->bits[1]);
1055         hwc_debug("  --> %x:%x (changed = %d)\n", fmt->bits[0], fmt->bits[1], changed);
1056         return changed;
1057 }
1058
1059 static int hw_rule_period_time(struct snd_pcm_hw_params *params,
1060                                struct snd_pcm_hw_rule *rule)
1061 {
1062         struct snd_usb_substream *subs = rule->private;
1063         struct audioformat *fp;
1064         struct snd_interval *it;
1065         unsigned char min_datainterval;
1066         unsigned int pmin;
1067         int changed;
1068
1069         it = hw_param_interval(params, SNDRV_PCM_HW_PARAM_PERIOD_TIME);
1070         hwc_debug("hw_rule_period_time: (%u,%u)\n", it->min, it->max);
1071         min_datainterval = 0xff;
1072         list_for_each_entry(fp, &subs->fmt_list, list) {
1073                 if (!hw_check_valid_format(subs, params, fp))
1074                         continue;
1075                 min_datainterval = min(min_datainterval, fp->datainterval);
1076         }
1077         if (min_datainterval == 0xff) {
1078                 hwc_debug("  --> get empty\n");
1079                 it->empty = 1;
1080                 return -EINVAL;
1081         }
1082         pmin = 125 * (1 << min_datainterval);
1083         changed = 0;
1084         if (it->min < pmin) {
1085                 it->min = pmin;
1086                 it->openmin = 0;
1087                 changed = 1;
1088         }
1089         if (snd_interval_checkempty(it)) {
1090                 it->empty = 1;
1091                 return -EINVAL;
1092         }
1093         hwc_debug("  --> (%u,%u) (changed = %d)\n", it->min, it->max, changed);
1094         return changed;
1095 }
1096
1097 /*
1098  *  If the device supports unusual bit rates, does the request meet these?
1099  */
1100 static int snd_usb_pcm_check_knot(struct snd_pcm_runtime *runtime,
1101                                   struct snd_usb_substream *subs)
1102 {
1103         struct audioformat *fp;
1104         int *rate_list;
1105         int count = 0, needs_knot = 0;
1106         int err;
1107
1108         kfree(subs->rate_list.list);
1109         subs->rate_list.list = NULL;
1110
1111         list_for_each_entry(fp, &subs->fmt_list, list) {
1112                 if (fp->rates & SNDRV_PCM_RATE_CONTINUOUS)
1113                         return 0;
1114                 count += fp->nr_rates;
1115                 if (fp->rates & SNDRV_PCM_RATE_KNOT)
1116                         needs_knot = 1;
1117         }
1118         if (!needs_knot)
1119                 return 0;
1120
1121         subs->rate_list.list = rate_list =
1122                 kmalloc(sizeof(int) * count, GFP_KERNEL);
1123         if (!subs->rate_list.list)
1124                 return -ENOMEM;
1125         subs->rate_list.count = count;
1126         subs->rate_list.mask = 0;
1127         count = 0;
1128         list_for_each_entry(fp, &subs->fmt_list, list) {
1129                 int i;
1130                 for (i = 0; i < fp->nr_rates; i++)
1131                         rate_list[count++] = fp->rate_table[i];
1132         }
1133         err = snd_pcm_hw_constraint_list(runtime, 0, SNDRV_PCM_HW_PARAM_RATE,
1134                                          &subs->rate_list);
1135         if (err < 0)
1136                 return err;
1137
1138         return 0;
1139 }
1140
1141
1142 /*
1143  * set up the runtime hardware information.
1144  */
1145
1146 static int setup_hw_info(struct snd_pcm_runtime *runtime, struct snd_usb_substream *subs)
1147 {
1148         struct audioformat *fp;
1149         unsigned int pt, ptmin;
1150         int param_period_time_if_needed;
1151         int err;
1152
1153         runtime->hw.formats = subs->formats;
1154
1155         runtime->hw.rate_min = 0x7fffffff;
1156         runtime->hw.rate_max = 0;
1157         runtime->hw.channels_min = 256;
1158         runtime->hw.channels_max = 0;
1159         runtime->hw.rates = 0;
1160         ptmin = UINT_MAX;
1161         /* check min/max rates and channels */
1162         list_for_each_entry(fp, &subs->fmt_list, list) {
1163                 runtime->hw.rates |= fp->rates;
1164                 if (runtime->hw.rate_min > fp->rate_min)
1165                         runtime->hw.rate_min = fp->rate_min;
1166                 if (runtime->hw.rate_max < fp->rate_max)
1167                         runtime->hw.rate_max = fp->rate_max;
1168                 if (runtime->hw.channels_min > fp->channels)
1169                         runtime->hw.channels_min = fp->channels;
1170                 if (runtime->hw.channels_max < fp->channels)
1171                         runtime->hw.channels_max = fp->channels;
1172                 if (fp->fmt_type == UAC_FORMAT_TYPE_II && fp->frame_size > 0) {
1173                         /* FIXME: there might be more than one audio formats... */
1174                         runtime->hw.period_bytes_min = runtime->hw.period_bytes_max =
1175                                 fp->frame_size;
1176                 }
1177                 pt = 125 * (1 << fp->datainterval);
1178                 ptmin = min(ptmin, pt);
1179         }
1180         err = snd_usb_autoresume(subs->stream->chip);
1181         if (err < 0)
1182                 return err;
1183
1184         param_period_time_if_needed = SNDRV_PCM_HW_PARAM_PERIOD_TIME;
1185         if (subs->speed == USB_SPEED_FULL)
1186                 /* full speed devices have fixed data packet interval */
1187                 ptmin = 1000;
1188         if (ptmin == 1000)
1189                 /* if period time doesn't go below 1 ms, no rules needed */
1190                 param_period_time_if_needed = -1;
1191         snd_pcm_hw_constraint_minmax(runtime, SNDRV_PCM_HW_PARAM_PERIOD_TIME,
1192                                      ptmin, UINT_MAX);
1193
1194         if ((err = snd_pcm_hw_rule_add(runtime, 0, SNDRV_PCM_HW_PARAM_RATE,
1195                                        hw_rule_rate, subs,
1196                                        SNDRV_PCM_HW_PARAM_FORMAT,
1197                                        SNDRV_PCM_HW_PARAM_CHANNELS,
1198                                        param_period_time_if_needed,
1199                                        -1)) < 0)
1200                 goto rep_err;
1201         if ((err = snd_pcm_hw_rule_add(runtime, 0, SNDRV_PCM_HW_PARAM_CHANNELS,
1202                                        hw_rule_channels, subs,
1203                                        SNDRV_PCM_HW_PARAM_FORMAT,
1204                                        SNDRV_PCM_HW_PARAM_RATE,
1205                                        param_period_time_if_needed,
1206                                        -1)) < 0)
1207                 goto rep_err;
1208         if ((err = snd_pcm_hw_rule_add(runtime, 0, SNDRV_PCM_HW_PARAM_FORMAT,
1209                                        hw_rule_format, subs,
1210                                        SNDRV_PCM_HW_PARAM_RATE,
1211                                        SNDRV_PCM_HW_PARAM_CHANNELS,
1212                                        param_period_time_if_needed,
1213                                        -1)) < 0)
1214                 goto rep_err;
1215         if (param_period_time_if_needed >= 0) {
1216                 err = snd_pcm_hw_rule_add(runtime, 0,
1217                                           SNDRV_PCM_HW_PARAM_PERIOD_TIME,
1218                                           hw_rule_period_time, subs,
1219                                           SNDRV_PCM_HW_PARAM_FORMAT,
1220                                           SNDRV_PCM_HW_PARAM_CHANNELS,
1221                                           SNDRV_PCM_HW_PARAM_RATE,
1222                                           -1);
1223                 if (err < 0)
1224                         goto rep_err;
1225         }
1226         if ((err = snd_usb_pcm_check_knot(runtime, subs)) < 0)
1227                 goto rep_err;
1228         return 0;
1229
1230 rep_err:
1231         snd_usb_autosuspend(subs->stream->chip);
1232         return err;
1233 }
1234
1235 static int snd_usb_pcm_open(struct snd_pcm_substream *substream, int direction)
1236 {
1237         struct snd_usb_stream *as = snd_pcm_substream_chip(substream);
1238         struct snd_pcm_runtime *runtime = substream->runtime;
1239         struct snd_usb_substream *subs = &as->substream[direction];
1240
1241         subs->interface = -1;
1242         subs->altset_idx = 0;
1243         runtime->hw = snd_usb_hardware;
1244         runtime->private_data = subs;
1245         subs->pcm_substream = substream;
1246         /* runtime PM is also done there */
1247
1248         /* initialize DSD/DOP context */
1249         subs->dsd_dop.byte_idx = 0;
1250         subs->dsd_dop.channel = 0;
1251         subs->dsd_dop.marker = 1;
1252
1253         return setup_hw_info(runtime, subs);
1254 }
1255
1256 static int snd_usb_pcm_close(struct snd_pcm_substream *substream, int direction)
1257 {
1258         struct snd_usb_stream *as = snd_pcm_substream_chip(substream);
1259         struct snd_usb_substream *subs = &as->substream[direction];
1260
1261         stop_endpoints(subs, true);
1262
1263         if (subs->interface >= 0 &&
1264             !snd_usb_lock_shutdown(subs->stream->chip)) {
1265                 usb_set_interface(subs->dev, subs->interface, 0);
1266                 subs->interface = -1;
1267                 snd_usb_unlock_shutdown(subs->stream->chip);
1268         }
1269
1270         subs->pcm_substream = NULL;
1271         snd_usb_autosuspend(subs->stream->chip);
1272
1273         return 0;
1274 }
1275
1276 /* Since a URB can handle only a single linear buffer, we must use double
1277  * buffering when the data to be transferred overflows the buffer boundary.
1278  * To avoid inconsistencies when updating hwptr_done, we use double buffering
1279  * for all URBs.
1280  */
1281 static void retire_capture_urb(struct snd_usb_substream *subs,
1282                                struct urb *urb)
1283 {
1284         struct snd_pcm_runtime *runtime = subs->pcm_substream->runtime;
1285         unsigned int stride, frames, bytes, oldptr;
1286         int i, period_elapsed = 0;
1287         unsigned long flags;
1288         unsigned char *cp;
1289         int current_frame_number;
1290
1291         /* read frame number here, update pointer in critical section */
1292         current_frame_number = usb_get_current_frame_number(subs->dev);
1293
1294         stride = runtime->frame_bits >> 3;
1295
1296         for (i = 0; i < urb->number_of_packets; i++) {
1297                 cp = (unsigned char *)urb->transfer_buffer + urb->iso_frame_desc[i].offset + subs->pkt_offset_adj;
1298                 if (urb->iso_frame_desc[i].status && printk_ratelimit()) {
1299                         dev_dbg(&subs->dev->dev, "frame %d active: %d\n",
1300                                 i, urb->iso_frame_desc[i].status);
1301                         // continue;
1302                 }
1303                 bytes = urb->iso_frame_desc[i].actual_length;
1304                 if (subs->stream_offset_adj > 0) {
1305                         unsigned int adj = min(subs->stream_offset_adj, bytes);
1306                         cp += adj;
1307                         bytes -= adj;
1308                         subs->stream_offset_adj -= adj;
1309                 }
1310                 frames = bytes / stride;
1311                 if (!subs->txfr_quirk)
1312                         bytes = frames * stride;
1313                 if (bytes % (runtime->sample_bits >> 3) != 0) {
1314                         int oldbytes = bytes;
1315                         bytes = frames * stride;
1316                         dev_warn_ratelimited(&subs->dev->dev,
1317                                  "Corrected urb data len. %d->%d\n",
1318                                                         oldbytes, bytes);
1319                 }
1320                 /* update the current pointer */
1321                 spin_lock_irqsave(&subs->lock, flags);
1322                 oldptr = subs->hwptr_done;
1323                 subs->hwptr_done += bytes;
1324                 if (subs->hwptr_done >= runtime->buffer_size * stride)
1325                         subs->hwptr_done -= runtime->buffer_size * stride;
1326                 frames = (bytes + (oldptr % stride)) / stride;
1327                 subs->transfer_done += frames;
1328                 if (subs->transfer_done >= runtime->period_size) {
1329                         subs->transfer_done -= runtime->period_size;
1330                         period_elapsed = 1;
1331                 }
1332                 /* capture delay is by construction limited to one URB,
1333                  * reset delays here
1334                  */
1335                 runtime->delay = subs->last_delay = 0;
1336
1337                 /* realign last_frame_number */
1338                 subs->last_frame_number = current_frame_number;
1339                 subs->last_frame_number &= 0xFF; /* keep 8 LSBs */
1340
1341                 spin_unlock_irqrestore(&subs->lock, flags);
1342                 /* copy a data chunk */
1343                 if (oldptr + bytes > runtime->buffer_size * stride) {
1344                         unsigned int bytes1 =
1345                                         runtime->buffer_size * stride - oldptr;
1346                         memcpy(runtime->dma_area + oldptr, cp, bytes1);
1347                         memcpy(runtime->dma_area, cp + bytes1, bytes - bytes1);
1348                 } else {
1349                         memcpy(runtime->dma_area + oldptr, cp, bytes);
1350                 }
1351         }
1352
1353         if (period_elapsed)
1354                 snd_pcm_period_elapsed(subs->pcm_substream);
1355 }
1356
1357 static inline void fill_playback_urb_dsd_dop(struct snd_usb_substream *subs,
1358                                              struct urb *urb, unsigned int bytes)
1359 {
1360         struct snd_pcm_runtime *runtime = subs->pcm_substream->runtime;
1361         unsigned int stride = runtime->frame_bits >> 3;
1362         unsigned int dst_idx = 0;
1363         unsigned int src_idx = subs->hwptr_done;
1364         unsigned int wrap = runtime->buffer_size * stride;
1365         u8 *dst = urb->transfer_buffer;
1366         u8 *src = runtime->dma_area;
1367         u8 marker[] = { 0x05, 0xfa };
1368
1369         /*
1370          * The DSP DOP format defines a way to transport DSD samples over
1371          * normal PCM data endpoints. It requires stuffing of marker bytes
1372          * (0x05 and 0xfa, alternating per sample frame), and then expects
1373          * 2 additional bytes of actual payload. The whole frame is stored
1374          * LSB.
1375          *
1376          * Hence, for a stereo transport, the buffer layout looks like this,
1377          * where L refers to left channel samples and R to right.
1378          *
1379          *   L1 L2 0x05   R1 R2 0x05   L3 L4 0xfa  R3 R4 0xfa
1380          *   L5 L6 0x05   R5 R6 0x05   L7 L8 0xfa  R7 R8 0xfa
1381          *   .....
1382          *
1383          */
1384
1385         while (bytes--) {
1386                 if (++subs->dsd_dop.byte_idx == 3) {
1387                         /* frame boundary? */
1388                         dst[dst_idx++] = marker[subs->dsd_dop.marker];
1389                         src_idx += 2;
1390                         subs->dsd_dop.byte_idx = 0;
1391
1392                         if (++subs->dsd_dop.channel % runtime->channels == 0) {
1393                                 /* alternate the marker */
1394                                 subs->dsd_dop.marker++;
1395                                 subs->dsd_dop.marker %= ARRAY_SIZE(marker);
1396                                 subs->dsd_dop.channel = 0;
1397                         }
1398                 } else {
1399                         /* stuff the DSD payload */
1400                         int idx = (src_idx + subs->dsd_dop.byte_idx - 1) % wrap;
1401
1402                         if (subs->cur_audiofmt->dsd_bitrev)
1403                                 dst[dst_idx++] = bitrev8(src[idx]);
1404                         else
1405                                 dst[dst_idx++] = src[idx];
1406
1407                         subs->hwptr_done++;
1408                 }
1409         }
1410         if (subs->hwptr_done >= runtime->buffer_size * stride)
1411                 subs->hwptr_done -= runtime->buffer_size * stride;
1412 }
1413
1414 static void copy_to_urb(struct snd_usb_substream *subs, struct urb *urb,
1415                         int offset, int stride, unsigned int bytes)
1416 {
1417         struct snd_pcm_runtime *runtime = subs->pcm_substream->runtime;
1418
1419         if (subs->hwptr_done + bytes > runtime->buffer_size * stride) {
1420                 /* err, the transferred area goes over buffer boundary. */
1421                 unsigned int bytes1 =
1422                         runtime->buffer_size * stride - subs->hwptr_done;
1423                 memcpy(urb->transfer_buffer + offset,
1424                        runtime->dma_area + subs->hwptr_done, bytes1);
1425                 memcpy(urb->transfer_buffer + offset + bytes1,
1426                        runtime->dma_area, bytes - bytes1);
1427         } else {
1428                 memcpy(urb->transfer_buffer + offset,
1429                        runtime->dma_area + subs->hwptr_done, bytes);
1430         }
1431         subs->hwptr_done += bytes;
1432         if (subs->hwptr_done >= runtime->buffer_size * stride)
1433                 subs->hwptr_done -= runtime->buffer_size * stride;
1434 }
1435
1436 static unsigned int copy_to_urb_quirk(struct snd_usb_substream *subs,
1437                                       struct urb *urb, int stride,
1438                                       unsigned int bytes)
1439 {
1440         __le32 packet_length;
1441         int i;
1442
1443         /* Put __le32 length descriptor at start of each packet. */
1444         for (i = 0; i < urb->number_of_packets; i++) {
1445                 unsigned int length = urb->iso_frame_desc[i].length;
1446                 unsigned int offset = urb->iso_frame_desc[i].offset;
1447
1448                 packet_length = cpu_to_le32(length);
1449                 offset += i * sizeof(packet_length);
1450                 urb->iso_frame_desc[i].offset = offset;
1451                 urb->iso_frame_desc[i].length += sizeof(packet_length);
1452                 memcpy(urb->transfer_buffer + offset,
1453                        &packet_length, sizeof(packet_length));
1454                 copy_to_urb(subs, urb, offset + sizeof(packet_length),
1455                             stride, length);
1456         }
1457         /* Adjust transfer size accordingly. */
1458         bytes += urb->number_of_packets * sizeof(packet_length);
1459         return bytes;
1460 }
1461
1462 static void prepare_playback_urb(struct snd_usb_substream *subs,
1463                                  struct urb *urb)
1464 {
1465         struct snd_pcm_runtime *runtime = subs->pcm_substream->runtime;
1466         struct snd_usb_endpoint *ep = subs->data_endpoint;
1467         struct snd_urb_ctx *ctx = urb->context;
1468         unsigned int counts, frames, bytes;
1469         int i, stride, period_elapsed = 0;
1470         unsigned long flags;
1471
1472         stride = runtime->frame_bits >> 3;
1473
1474         frames = 0;
1475         urb->number_of_packets = 0;
1476         spin_lock_irqsave(&subs->lock, flags);
1477         subs->frame_limit += ep->max_urb_frames;
1478         for (i = 0; i < ctx->packets; i++) {
1479                 if (ctx->packet_size[i])
1480                         counts = ctx->packet_size[i];
1481                 else
1482                         counts = snd_usb_endpoint_next_packet_size(ep);
1483
1484                 /* set up descriptor */
1485                 urb->iso_frame_desc[i].offset = frames * ep->stride;
1486                 urb->iso_frame_desc[i].length = counts * ep->stride;
1487                 frames += counts;
1488                 urb->number_of_packets++;
1489                 subs->transfer_done += counts;
1490                 if (subs->transfer_done >= runtime->period_size) {
1491                         subs->transfer_done -= runtime->period_size;
1492                         subs->frame_limit = 0;
1493                         period_elapsed = 1;
1494                         if (subs->fmt_type == UAC_FORMAT_TYPE_II) {
1495                                 if (subs->transfer_done > 0) {
1496                                         /* FIXME: fill-max mode is not
1497                                          * supported yet */
1498                                         frames -= subs->transfer_done;
1499                                         counts -= subs->transfer_done;
1500                                         urb->iso_frame_desc[i].length =
1501                                                 counts * ep->stride;
1502                                         subs->transfer_done = 0;
1503                                 }
1504                                 i++;
1505                                 if (i < ctx->packets) {
1506                                         /* add a transfer delimiter */
1507                                         urb->iso_frame_desc[i].offset =
1508                                                 frames * ep->stride;
1509                                         urb->iso_frame_desc[i].length = 0;
1510                                         urb->number_of_packets++;
1511                                 }
1512                                 break;
1513                         }
1514                 }
1515                 /* finish at the period boundary or after enough frames */
1516                 if ((period_elapsed ||
1517                                 subs->transfer_done >= subs->frame_limit) &&
1518                     !snd_usb_endpoint_implicit_feedback_sink(ep))
1519                         break;
1520         }
1521         bytes = frames * ep->stride;
1522
1523         if (unlikely(subs->pcm_format == SNDRV_PCM_FORMAT_DSD_U16_LE &&
1524                      subs->cur_audiofmt->dsd_dop)) {
1525                 fill_playback_urb_dsd_dop(subs, urb, bytes);
1526         } else if (unlikely(subs->pcm_format == SNDRV_PCM_FORMAT_DSD_U8 &&
1527                            subs->cur_audiofmt->dsd_bitrev)) {
1528                 /* bit-reverse the bytes */
1529                 u8 *buf = urb->transfer_buffer;
1530                 for (i = 0; i < bytes; i++) {
1531                         int idx = (subs->hwptr_done + i)
1532                                 % (runtime->buffer_size * stride);
1533                         buf[i] = bitrev8(runtime->dma_area[idx]);
1534                 }
1535
1536                 subs->hwptr_done += bytes;
1537                 if (subs->hwptr_done >= runtime->buffer_size * stride)
1538                         subs->hwptr_done -= runtime->buffer_size * stride;
1539         } else {
1540                 /* usual PCM */
1541                 if (!subs->tx_length_quirk)
1542                         copy_to_urb(subs, urb, 0, stride, bytes);
1543                 else
1544                         bytes = copy_to_urb_quirk(subs, urb, stride, bytes);
1545                         /* bytes is now amount of outgoing data */
1546         }
1547
1548         /* update delay with exact number of samples queued */
1549         runtime->delay = subs->last_delay;
1550         runtime->delay += frames;
1551         subs->last_delay = runtime->delay;
1552
1553         /* realign last_frame_number */
1554         subs->last_frame_number = usb_get_current_frame_number(subs->dev);
1555         subs->last_frame_number &= 0xFF; /* keep 8 LSBs */
1556
1557         if (subs->trigger_tstamp_pending_update) {
1558                 /* this is the first actual URB submitted,
1559                  * update trigger timestamp to reflect actual start time
1560                  */
1561                 snd_pcm_gettime(runtime, &runtime->trigger_tstamp);
1562                 subs->trigger_tstamp_pending_update = false;
1563         }
1564
1565         spin_unlock_irqrestore(&subs->lock, flags);
1566         urb->transfer_buffer_length = bytes;
1567         if (period_elapsed)
1568                 snd_pcm_period_elapsed(subs->pcm_substream);
1569 }
1570
1571 /*
1572  * process after playback data complete
1573  * - decrease the delay count again
1574  */
1575 static void retire_playback_urb(struct snd_usb_substream *subs,
1576                                struct urb *urb)
1577 {
1578         unsigned long flags;
1579         struct snd_pcm_runtime *runtime = subs->pcm_substream->runtime;
1580         struct snd_usb_endpoint *ep = subs->data_endpoint;
1581         int processed = urb->transfer_buffer_length / ep->stride;
1582         int est_delay;
1583
1584         /* ignore the delay accounting when procssed=0 is given, i.e.
1585          * silent payloads are procssed before handling the actual data
1586          */
1587         if (!processed)
1588                 return;
1589
1590         spin_lock_irqsave(&subs->lock, flags);
1591         if (!subs->last_delay)
1592                 goto out; /* short path */
1593
1594         est_delay = snd_usb_pcm_delay(subs, runtime->rate);
1595         /* update delay with exact number of samples played */
1596         if (processed > subs->last_delay)
1597                 subs->last_delay = 0;
1598         else
1599                 subs->last_delay -= processed;
1600         runtime->delay = subs->last_delay;
1601
1602         /*
1603          * Report when delay estimate is off by more than 2ms.
1604          * The error should be lower than 2ms since the estimate relies
1605          * on two reads of a counter updated every ms.
1606          */
1607         if (abs(est_delay - subs->last_delay) * 1000 > runtime->rate * 2)
1608                 dev_dbg_ratelimited(&subs->dev->dev,
1609                         "delay: estimated %d, actual %d\n",
1610                         est_delay, subs->last_delay);
1611
1612         if (!subs->running) {
1613                 /* update last_frame_number for delay counting here since
1614                  * prepare_playback_urb won't be called during pause
1615                  */
1616                 subs->last_frame_number =
1617                         usb_get_current_frame_number(subs->dev) & 0xff;
1618         }
1619
1620  out:
1621         spin_unlock_irqrestore(&subs->lock, flags);
1622 }
1623
1624 static int snd_usb_playback_open(struct snd_pcm_substream *substream)
1625 {
1626         return snd_usb_pcm_open(substream, SNDRV_PCM_STREAM_PLAYBACK);
1627 }
1628
1629 static int snd_usb_playback_close(struct snd_pcm_substream *substream)
1630 {
1631         return snd_usb_pcm_close(substream, SNDRV_PCM_STREAM_PLAYBACK);
1632 }
1633
1634 static int snd_usb_capture_open(struct snd_pcm_substream *substream)
1635 {
1636         return snd_usb_pcm_open(substream, SNDRV_PCM_STREAM_CAPTURE);
1637 }
1638
1639 static int snd_usb_capture_close(struct snd_pcm_substream *substream)
1640 {
1641         return snd_usb_pcm_close(substream, SNDRV_PCM_STREAM_CAPTURE);
1642 }
1643
1644 static int snd_usb_substream_playback_trigger(struct snd_pcm_substream *substream,
1645                                               int cmd)
1646 {
1647         struct snd_usb_substream *subs = substream->runtime->private_data;
1648
1649         switch (cmd) {
1650         case SNDRV_PCM_TRIGGER_START:
1651                 subs->trigger_tstamp_pending_update = true;
1652         case SNDRV_PCM_TRIGGER_PAUSE_RELEASE:
1653                 subs->data_endpoint->prepare_data_urb = prepare_playback_urb;
1654                 subs->data_endpoint->retire_data_urb = retire_playback_urb;
1655                 subs->running = 1;
1656                 return 0;
1657         case SNDRV_PCM_TRIGGER_STOP:
1658                 stop_endpoints(subs, false);
1659                 subs->running = 0;
1660                 return 0;
1661         case SNDRV_PCM_TRIGGER_PAUSE_PUSH:
1662                 subs->data_endpoint->prepare_data_urb = NULL;
1663                 /* keep retire_data_urb for delay calculation */
1664                 subs->data_endpoint->retire_data_urb = retire_playback_urb;
1665                 subs->running = 0;
1666                 return 0;
1667         }
1668
1669         return -EINVAL;
1670 }
1671
1672 static int snd_usb_substream_capture_trigger(struct snd_pcm_substream *substream,
1673                                              int cmd)
1674 {
1675         int err;
1676         struct snd_usb_substream *subs = substream->runtime->private_data;
1677
1678         switch (cmd) {
1679         case SNDRV_PCM_TRIGGER_START:
1680                 err = start_endpoints(subs);
1681                 if (err < 0)
1682                         return err;
1683
1684                 subs->data_endpoint->retire_data_urb = retire_capture_urb;
1685                 subs->running = 1;
1686                 return 0;
1687         case SNDRV_PCM_TRIGGER_STOP:
1688                 stop_endpoints(subs, false);
1689                 subs->running = 0;
1690                 return 0;
1691         case SNDRV_PCM_TRIGGER_PAUSE_PUSH:
1692                 subs->data_endpoint->retire_data_urb = NULL;
1693                 subs->running = 0;
1694                 return 0;
1695         case SNDRV_PCM_TRIGGER_PAUSE_RELEASE:
1696                 subs->data_endpoint->retire_data_urb = retire_capture_urb;
1697                 subs->running = 1;
1698                 return 0;
1699         }
1700
1701         return -EINVAL;
1702 }
1703
1704 static struct snd_pcm_ops snd_usb_playback_ops = {
1705         .open =         snd_usb_playback_open,
1706         .close =        snd_usb_playback_close,
1707         .ioctl =        snd_pcm_lib_ioctl,
1708         .hw_params =    snd_usb_hw_params,
1709         .hw_free =      snd_usb_hw_free,
1710         .prepare =      snd_usb_pcm_prepare,
1711         .trigger =      snd_usb_substream_playback_trigger,
1712         .pointer =      snd_usb_pcm_pointer,
1713         .page =         snd_pcm_lib_get_vmalloc_page,
1714         .mmap =         snd_pcm_lib_mmap_vmalloc,
1715 };
1716
1717 static struct snd_pcm_ops snd_usb_capture_ops = {
1718         .open =         snd_usb_capture_open,
1719         .close =        snd_usb_capture_close,
1720         .ioctl =        snd_pcm_lib_ioctl,
1721         .hw_params =    snd_usb_hw_params,
1722         .hw_free =      snd_usb_hw_free,
1723         .prepare =      snd_usb_pcm_prepare,
1724         .trigger =      snd_usb_substream_capture_trigger,
1725         .pointer =      snd_usb_pcm_pointer,
1726         .page =         snd_pcm_lib_get_vmalloc_page,
1727         .mmap =         snd_pcm_lib_mmap_vmalloc,
1728 };
1729
1730 void snd_usb_set_pcm_ops(struct snd_pcm *pcm, int stream)
1731 {
1732         snd_pcm_set_ops(pcm, stream,
1733                         stream == SNDRV_PCM_STREAM_PLAYBACK ?
1734                         &snd_usb_playback_ops : &snd_usb_capture_ops);
1735 }