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