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