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