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