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