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