1 // SPDX-License-Identifier: GPL-2.0-or-later
5 #include <linux/init.h>
6 #include <linux/slab.h>
7 #include <linux/bitrev.h>
8 #include <linux/ratelimit.h>
10 #include <linux/usb/audio.h>
11 #include <linux/usb/audio-v2.h>
13 #include <sound/core.h>
14 #include <sound/pcm.h>
15 #include <sound/pcm_params.h>
28 #define SUBSTREAM_FLAG_DATA_EP_STARTED 0
29 #define SUBSTREAM_FLAG_SYNC_EP_STARTED 1
31 /* return the estimated delay based on USB frame counters */
32 snd_pcm_uframes_t snd_usb_pcm_delay(struct snd_usb_substream *subs,
35 int current_frame_number;
39 if (!subs->last_delay)
40 return 0; /* short path */
42 current_frame_number = usb_get_current_frame_number(subs->dev);
44 * HCD implementations use different widths, use lower 8 bits.
45 * The delay will be managed up to 256ms, which is more than
48 frame_diff = (current_frame_number - subs->last_frame_number) & 0xff;
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;
56 est_delay = subs->last_delay + est_delay;
64 * return the current pcm pointer. just based on the hwptr_done value.
66 static snd_pcm_uframes_t snd_usb_pcm_pointer(struct snd_pcm_substream *substream)
68 struct snd_usb_substream *subs = substream->runtime->private_data;
69 unsigned int hwptr_done;
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);
82 * find a matching audio format
84 static struct audioformat *find_format(struct snd_usb_substream *subs)
86 struct audioformat *fp;
87 struct audioformat *found = NULL;
88 int cur_attr = 0, attr;
90 list_for_each_entry(fp, &subs->fmt_list, list) {
91 if (!(fp->formats & pcm_format_to_bits(subs->pcm_format)))
93 if (fp->channels != subs->channels)
95 if (subs->cur_rate < fp->rate_min ||
96 subs->cur_rate > fp->rate_max)
98 if (! (fp->rates & SNDRV_PCM_RATE_CONTINUOUS)) {
100 for (i = 0; i < fp->nr_rates; i++)
101 if (fp->rate_table[i] == subs->cur_rate)
103 if (i >= fp->nr_rates)
106 attr = fp->ep_attr & USB_ENDPOINT_SYNCTYPE;
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.
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))
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)) {
132 /* find the format with the largest max. packet size */
133 if (fp->maxpacksize > found->maxpacksize) {
141 static int init_pitch_v1(struct snd_usb_audio *chip, int iface,
142 struct usb_host_interface *alts,
143 struct audioformat *fmt)
145 struct usb_device *dev = chip->dev;
147 unsigned char data[1];
150 if (get_iface_desc(alts)->bNumEndpoints < 1)
152 ep = get_endpoint(alts, 0)->bEndpointAddress;
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,
160 usb_audio_err(chip, "%d:%d: cannot set enable PITCH\n",
168 static int init_pitch_v2(struct snd_usb_audio *chip, int iface,
169 struct usb_host_interface *alts,
170 struct audioformat *fmt)
172 struct usb_device *dev = chip->dev;
173 unsigned char data[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,
182 usb_audio_err(chip, "%d:%d: cannot set enable PITCH (v2)\n",
183 iface, fmt->altsetting);
191 * initialize the pitch control and sample rate
193 int snd_usb_init_pitch(struct snd_usb_audio *chip, int iface,
194 struct usb_host_interface *alts,
195 struct audioformat *fmt)
197 /* if endpoint doesn't have pitch control, bail out */
198 if (!(fmt->attributes & UAC_EP_CS_ATTR_PITCH_CONTROL))
201 switch (fmt->protocol) {
204 return init_pitch_v1(chip, iface, alts, fmt);
207 return init_pitch_v2(chip, iface, alts, fmt);
211 static int start_endpoints(struct snd_usb_substream *subs)
215 if (!subs->data_endpoint)
218 if (!test_and_set_bit(SUBSTREAM_FLAG_DATA_EP_STARTED, &subs->flags)) {
219 struct snd_usb_endpoint *ep = subs->data_endpoint;
221 dev_dbg(&subs->dev->dev, "Starting data EP 0x%x\n", ep->ep_num);
223 ep->data_subs = subs;
224 err = snd_usb_endpoint_start(ep);
226 clear_bit(SUBSTREAM_FLAG_DATA_EP_STARTED, &subs->flags);
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;
235 dev_dbg(&subs->dev->dev, "Starting sync EP 0x%x\n", ep->ep_num);
237 ep->sync_slave = subs->data_endpoint;
238 err = snd_usb_endpoint_start(ep);
240 clear_bit(SUBSTREAM_FLAG_SYNC_EP_STARTED, &subs->flags);
241 ep->sync_slave = NULL;
249 static void sync_pending_stops(struct snd_usb_substream *subs)
251 snd_usb_endpoint_sync_pending_stop(subs->sync_endpoint);
252 snd_usb_endpoint_sync_pending_stop(subs->data_endpoint);
255 static void stop_endpoints(struct snd_usb_substream *subs)
257 if (test_and_clear_bit(SUBSTREAM_FLAG_SYNC_EP_STARTED, &subs->flags)) {
258 dev_dbg(&subs->dev->dev, "Stopping sync EP 0x%x\n",
259 subs->sync_endpoint->ep_num);
260 snd_usb_endpoint_stop(subs->sync_endpoint);
261 subs->sync_endpoint->sync_slave = NULL;
264 if (test_and_clear_bit(SUBSTREAM_FLAG_DATA_EP_STARTED, &subs->flags)) {
265 dev_dbg(&subs->dev->dev, "Stopping data EP 0x%x\n",
266 subs->data_endpoint->ep_num);
267 snd_usb_endpoint_stop(subs->data_endpoint);
271 /* PCM sync_stop callback */
272 static int snd_usb_pcm_sync_stop(struct snd_pcm_substream *substream)
274 struct snd_usb_substream *subs = substream->runtime->private_data;
276 if (!snd_usb_lock_shutdown(subs->stream->chip)) {
277 sync_pending_stops(subs);
278 snd_usb_unlock_shutdown(subs->stream->chip);
283 /* Check whether the given iface:altsetting points to an implicit fb source */
284 static bool search_generic_implicit_fb(struct usb_device *dev, int ifnum,
285 unsigned int altsetting,
286 struct usb_host_interface **altsp,
289 struct usb_interface *iface;
290 struct usb_host_interface *alts;
291 struct usb_interface_descriptor *altsd;
292 struct usb_endpoint_descriptor *epd;
294 iface = usb_ifnum_to_if(dev, ifnum);
297 alts = usb_altnum_to_altsetting(iface, altsetting);
300 altsd = get_iface_desc(alts);
301 if (altsd->bInterfaceClass != USB_CLASS_AUDIO ||
302 altsd->bInterfaceSubClass != USB_SUBCLASS_AUDIOSTREAMING ||
303 altsd->bInterfaceProtocol != UAC_VERSION_2 ||
304 altsd->bNumEndpoints < 1)
306 epd = get_endpoint(alts, 0);
307 if (!usb_endpoint_is_isoc_in(epd) ||
308 (epd->bmAttributes & USB_ENDPOINT_USAGE_MASK) !=
309 USB_ENDPOINT_USAGE_IMPLICIT_FB)
311 *ep = epd->bEndpointAddress;
316 /* Like the function above, but specific to Roland with vendor class and hack */
317 static bool search_roland_implicit_fb(struct usb_device *dev, int ifnum,
318 unsigned int altsetting,
319 struct usb_host_interface **altsp,
322 struct usb_interface *iface;
323 struct usb_host_interface *alts;
324 struct usb_interface_descriptor *altsd;
325 struct usb_endpoint_descriptor *epd;
327 iface = usb_ifnum_to_if(dev, ifnum);
330 alts = usb_altnum_to_altsetting(iface, altsetting);
333 altsd = get_iface_desc(alts);
334 if (altsd->bInterfaceClass != USB_CLASS_VENDOR_SPEC ||
335 (altsd->bInterfaceSubClass != 2 &&
336 altsd->bInterfaceProtocol != 2) ||
337 altsd->bNumEndpoints < 1)
339 epd = get_endpoint(alts, 0);
340 if (!usb_endpoint_is_isoc_in(epd) ||
341 (epd->bmAttributes & USB_ENDPOINT_USAGE_MASK) !=
342 USB_ENDPOINT_USAGE_IMPLICIT_FB)
344 *ep = epd->bEndpointAddress;
349 /* Setup an implicit feedback endpoint from a quirk. Returns 0 if no quirk
350 * applies. Returns 1 if a quirk was found.
352 static int audioformat_implicit_fb_quirk(struct snd_usb_audio *chip,
353 struct audioformat *fmt,
354 struct usb_interface *iface,
355 struct usb_host_interface *alts)
357 struct usb_device *dev = chip->dev;
358 struct usb_interface_descriptor *altsd = get_iface_desc(alts);
359 unsigned int attr = fmt->ep_attr & USB_ENDPOINT_SYNCTYPE;
363 switch (chip->usb_id) {
364 case USB_ID(0x0763, 0x2030): /* M-Audio Fast Track C400 */
365 case USB_ID(0x0763, 0x2031): /* M-Audio Fast Track C600 */
366 case USB_ID(0x22f0, 0x0006): /* Allen&Heath Qu-16 */
369 goto add_sync_ep_from_ifnum;
370 case USB_ID(0x0763, 0x2080): /* M-Audio FastTrack Ultra */
371 case USB_ID(0x0763, 0x2081):
374 goto add_sync_ep_from_ifnum;
375 case USB_ID(0x2466, 0x8003): /* Fractal Audio Axe-Fx II */
376 case USB_ID(0x0499, 0x172a): /* Yamaha MODX */
379 goto add_sync_ep_from_ifnum;
380 case USB_ID(0x2466, 0x8010): /* Fractal Audio Axe-Fx III */
383 goto add_sync_ep_from_ifnum;
384 case USB_ID(0x1686, 0xf029): /* Zoom UAC-2 */
387 goto add_sync_ep_from_ifnum;
388 case USB_ID(0x1397, 0x0001): /* Behringer UFX1604 */
389 case USB_ID(0x1397, 0x0002): /* Behringer UFX1204 */
392 goto add_sync_ep_from_ifnum;
393 case USB_ID(0x07fd, 0x0004): /* MOTU MicroBook II/IIc */
395 if (altsd->bInterfaceClass == USB_CLASS_AUDIO)
401 goto add_sync_ep_from_ifnum;
402 case USB_ID(0x07fd, 0x0008): /* MOTU M Series */
403 case USB_ID(0x31e9, 0x0001): /* Solid State Logic SSL2 */
404 case USB_ID(0x31e9, 0x0002): /* Solid State Logic SSL2+ */
405 case USB_ID(0x0499, 0x172f): /* Steinberg UR22C */
406 case USB_ID(0x0d9a, 0x00df): /* RTX6001 */
409 goto add_sync_ep_from_ifnum;
410 case USB_ID(0x2b73, 0x000a): /* Pioneer DJ DJM-900NXS2 */
411 case USB_ID(0x2b73, 0x0017): /* Pioneer DJ DJM-250MK2 */
414 goto add_sync_ep_from_ifnum;
415 case USB_ID(0x0582, 0x01d8): /* BOSS Katana */
416 /* BOSS Katana amplifiers do not need quirks */
420 /* Generic UAC2 implicit feedback */
421 if (attr == USB_ENDPOINT_SYNC_ASYNC &&
422 altsd->bInterfaceClass == USB_CLASS_AUDIO &&
423 altsd->bInterfaceProtocol == UAC_VERSION_2 &&
424 altsd->bNumEndpoints == 1) {
425 ifnum = altsd->bInterfaceNumber + 1;
426 if (search_generic_implicit_fb(dev, ifnum,
427 altsd->bAlternateSetting,
432 /* Roland/BOSS implicit feedback with vendor spec class */
433 if (attr == USB_ENDPOINT_SYNC_ASYNC &&
434 altsd->bInterfaceClass == USB_CLASS_VENDOR_SPEC &&
435 altsd->bInterfaceProtocol == 2 &&
436 altsd->bNumEndpoints == 1 &&
437 USB_ID_VENDOR(chip->usb_id) == 0x0582 /* Roland */) {
438 ifnum = altsd->bInterfaceNumber + 1;
439 if (search_roland_implicit_fb(dev, ifnum,
440 altsd->bAlternateSetting,
448 add_sync_ep_from_ifnum:
449 iface = usb_ifnum_to_if(dev, ifnum);
451 if (!iface || iface->num_altsetting < 2)
454 alts = &iface->altsetting[1];
458 fmt->sync_iface = ifnum;
459 fmt->sync_altsetting = alts->desc.bAlternateSetting;
460 fmt->implicit_fb = 1;
461 dev_dbg(&dev->dev, "%d:%d: found implicit_fb sync_ep=%x, iface=%d, alt=%d\n",
462 fmt->iface, fmt->altsetting, fmt->sync_ep, fmt->sync_iface,
463 fmt->sync_altsetting);
468 int snd_usb_audioformat_set_sync_ep(struct snd_usb_audio *chip,
469 struct audioformat *fmt)
471 struct usb_device *dev = chip->dev;
472 struct usb_interface *iface;
473 struct usb_host_interface *alts;
474 struct usb_interface_descriptor *altsd;
475 unsigned int ep, attr, sync_attr;
479 iface = usb_ifnum_to_if(dev, fmt->iface);
482 alts = usb_altnum_to_altsetting(iface, fmt->altsetting);
485 altsd = get_iface_desc(alts);
487 is_playback = !(get_endpoint(alts, 0)->bEndpointAddress & USB_DIR_IN);
489 err = audioformat_implicit_fb_quirk(chip, fmt, iface, alts);
494 if (altsd->bNumEndpoints < 2)
497 attr = fmt->ep_attr & USB_ENDPOINT_SYNCTYPE;
498 if ((is_playback && (attr == USB_ENDPOINT_SYNC_SYNC ||
499 attr == USB_ENDPOINT_SYNC_ADAPTIVE)) ||
500 (!is_playback && attr != USB_ENDPOINT_SYNC_ADAPTIVE))
503 sync_attr = get_endpoint(alts, 1)->bmAttributes;
506 * In case of illegal SYNC_NONE for OUT endpoint, we keep going to see
507 * if we don't find a sync endpoint, as on M-Audio Transit. In case of
508 * error fall back to SYNC mode and don't create sync endpoint
511 /* check sync-pipe endpoint */
512 /* ... and check descriptor size before accessing bSynchAddress
513 because there is a version of the SB Audigy 2 NX firmware lacking
514 the audio fields in the endpoint descriptors */
515 if ((sync_attr & USB_ENDPOINT_XFERTYPE_MASK) != USB_ENDPOINT_XFER_ISOC ||
516 (get_endpoint(alts, 1)->bLength >= USB_DT_ENDPOINT_AUDIO_SIZE &&
517 get_endpoint(alts, 1)->bSynchAddress != 0)) {
519 "%d:%d : invalid sync pipe. bmAttributes %02x, bLength %d, bSynchAddress %02x\n",
520 fmt->iface, fmt->altsetting,
521 get_endpoint(alts, 1)->bmAttributes,
522 get_endpoint(alts, 1)->bLength,
523 get_endpoint(alts, 1)->bSynchAddress);
524 if (is_playback && attr == USB_ENDPOINT_SYNC_NONE)
528 ep = get_endpoint(alts, 1)->bEndpointAddress;
529 if (get_endpoint(alts, 0)->bLength >= USB_DT_ENDPOINT_AUDIO_SIZE &&
530 get_endpoint(alts, 0)->bSynchAddress != 0 &&
531 ((is_playback && ep != (unsigned int)(get_endpoint(alts, 0)->bSynchAddress | USB_DIR_IN)) ||
532 (!is_playback && ep != (unsigned int)(get_endpoint(alts, 0)->bSynchAddress & ~USB_DIR_IN)))) {
534 "%d:%d : invalid sync pipe. is_playback %d, ep %02x, bSynchAddress %02x\n",
535 fmt->iface, fmt->altsetting,
536 is_playback, ep, get_endpoint(alts, 0)->bSynchAddress);
537 if (is_playback && attr == USB_ENDPOINT_SYNC_NONE)
543 fmt->sync_iface = altsd->bInterfaceNumber;
544 fmt->sync_altsetting = altsd->bAlternateSetting;
545 if ((sync_attr & USB_ENDPOINT_USAGE_MASK) == USB_ENDPOINT_USAGE_IMPLICIT_FB)
546 fmt->implicit_fb = 1;
548 dev_dbg(&dev->dev, "%d:%d: found sync_ep=0x%x, iface=%d, alt=%d, implicit_fb=%d\n",
549 fmt->iface, fmt->altsetting, fmt->sync_ep, fmt->sync_iface,
550 fmt->sync_altsetting, fmt->implicit_fb);
555 static int set_sync_endpoint(struct snd_usb_substream *subs,
556 struct audioformat *fmt)
558 struct usb_device *dev = subs->dev;
559 struct usb_interface *iface;
560 struct usb_host_interface *alts;
561 int is_playback = subs->direction == SNDRV_PCM_STREAM_PLAYBACK;
565 subs->sync_endpoint = NULL;
566 subs->data_endpoint->sync_master = NULL;
572 iface = usb_ifnum_to_if(dev, fmt->sync_iface);
576 alts = usb_altnum_to_altsetting(iface, fmt->altsetting);
580 subs->sync_endpoint = snd_usb_add_endpoint(subs->stream->chip,
581 alts, ep, !subs->direction,
583 SND_USB_ENDPOINT_TYPE_DATA :
584 SND_USB_ENDPOINT_TYPE_SYNC);
585 if (!subs->sync_endpoint) {
587 (fmt->ep_attr & USB_ENDPOINT_SYNCTYPE) == USB_ENDPOINT_SYNC_NONE)
592 subs->sync_endpoint->is_implicit_feedback = fmt->implicit_fb;
594 subs->data_endpoint->sync_master = subs->sync_endpoint;
596 if (subs->data_endpoint->iface != subs->sync_endpoint->iface ||
597 subs->data_endpoint->altsetting != subs->sync_endpoint->altsetting) {
598 err = usb_set_interface(subs->dev,
599 subs->sync_endpoint->iface,
600 subs->sync_endpoint->altsetting);
603 dev_dbg(&dev->dev, "setting usb interface %d:%d\n",
604 subs->sync_endpoint->iface,
605 subs->sync_endpoint->altsetting);
606 snd_usb_set_interface_quirk(dev);
613 * find a matching format and set up the interface
615 static int set_format(struct snd_usb_substream *subs, struct audioformat *fmt)
617 struct usb_device *dev = subs->dev;
618 struct usb_host_interface *alts;
619 struct usb_interface *iface;
622 iface = usb_ifnum_to_if(dev, fmt->iface);
625 alts = usb_altnum_to_altsetting(iface, fmt->altsetting);
629 if (fmt == subs->cur_audiofmt && !subs->need_setup_fmt)
632 /* close the old interface */
633 if (subs->interface >= 0 && (subs->interface != fmt->iface || subs->need_setup_fmt)) {
634 if (!subs->stream->chip->keep_iface) {
635 err = usb_set_interface(subs->dev, subs->interface, 0);
638 "%d:%d: return to setting 0 failed (%d)\n",
639 fmt->iface, fmt->altsetting, err);
643 subs->interface = -1;
644 subs->altset_idx = 0;
647 if (subs->need_setup_fmt)
648 subs->need_setup_fmt = false;
651 if (iface->cur_altsetting != alts) {
652 err = snd_usb_select_mode_quirk(subs, fmt);
656 err = usb_set_interface(dev, fmt->iface, fmt->altsetting);
659 "%d:%d: usb_set_interface failed (%d)\n",
660 fmt->iface, fmt->altsetting, err);
663 dev_dbg(&dev->dev, "setting usb interface %d:%d\n",
664 fmt->iface, fmt->altsetting);
665 snd_usb_set_interface_quirk(dev);
668 subs->interface = fmt->iface;
669 subs->altset_idx = fmt->altset_idx;
670 subs->data_endpoint = snd_usb_add_endpoint(subs->stream->chip,
671 alts, fmt->endpoint, subs->direction,
672 SND_USB_ENDPOINT_TYPE_DATA);
674 if (!subs->data_endpoint)
677 err = set_sync_endpoint(subs, fmt);
681 err = snd_usb_init_pitch(subs->stream->chip, fmt->iface, alts, fmt);
685 subs->cur_audiofmt = fmt;
687 snd_usb_set_format_quirk(subs, fmt);
693 * Return the score of matching two audioformats.
694 * Veto the audioformat if:
695 * - It has no channels for some reason.
696 * - Requested PCM format is not supported.
697 * - Requested sample rate is not supported.
699 static int match_endpoint_audioformats(struct snd_usb_substream *subs,
700 struct audioformat *fp,
701 struct audioformat *match, int rate,
702 snd_pcm_format_t pcm_format)
707 if (fp->channels < 1) {
708 dev_dbg(&subs->dev->dev,
709 "%s: (fmt @%p) no channels\n", __func__, fp);
713 if (!(fp->formats & pcm_format_to_bits(pcm_format))) {
714 dev_dbg(&subs->dev->dev,
715 "%s: (fmt @%p) no match for format %d\n", __func__,
720 for (i = 0; i < fp->nr_rates; i++) {
721 if (fp->rate_table[i] == rate) {
727 dev_dbg(&subs->dev->dev,
728 "%s: (fmt @%p) no match for rate %d\n", __func__,
733 if (fp->channels == match->channels)
736 dev_dbg(&subs->dev->dev,
737 "%s: (fmt @%p) score %d\n", __func__, fp, score);
743 * Configure the sync ep using the rate and pcm format of the data ep.
745 static int configure_sync_endpoint(struct snd_usb_substream *subs)
748 struct audioformat *fp;
749 struct audioformat *sync_fp = NULL;
751 int sync_period_bytes = subs->period_bytes;
752 struct snd_usb_substream *sync_subs =
753 &subs->stream->substream[subs->direction ^ 1];
755 if (subs->sync_endpoint->type != SND_USB_ENDPOINT_TYPE_DATA ||
757 return snd_usb_endpoint_set_params(subs->sync_endpoint,
766 /* Try to find the best matching audioformat. */
767 list_for_each_entry(fp, &sync_subs->fmt_list, list) {
768 int score = match_endpoint_audioformats(subs,
769 fp, subs->cur_audiofmt,
770 subs->cur_rate, subs->pcm_format);
772 if (score > cur_score) {
778 if (unlikely(sync_fp == NULL)) {
779 dev_err(&subs->dev->dev,
780 "%s: no valid audioformat for sync ep %x found\n",
781 __func__, sync_subs->ep_num);
786 * Recalculate the period bytes if channel number differ between
787 * data and sync ep audioformat.
789 if (sync_fp->channels != subs->channels) {
790 sync_period_bytes = (subs->period_bytes / subs->channels) *
792 dev_dbg(&subs->dev->dev,
793 "%s: adjusted sync ep period bytes (%d -> %d)\n",
794 __func__, subs->period_bytes, sync_period_bytes);
797 ret = snd_usb_endpoint_set_params(subs->sync_endpoint,
810 * configure endpoint params
812 * called during initial setup and upon resume
814 static int configure_endpoint(struct snd_usb_substream *subs)
819 stop_endpoints(subs);
820 sync_pending_stops(subs);
821 ret = snd_usb_endpoint_set_params(subs->data_endpoint,
826 subs->buffer_periods,
829 subs->sync_endpoint);
833 if (subs->sync_endpoint)
834 ret = configure_sync_endpoint(subs);
839 static int snd_usb_pcm_change_state(struct snd_usb_substream *subs, int state)
846 ret = snd_usb_power_domain_set(subs->stream->chip, subs->str_pd, state);
848 dev_err(&subs->dev->dev,
849 "Cannot change Power Domain ID: %d to state: %d. Err: %d\n",
850 subs->str_pd->pd_id, state, ret);
857 int snd_usb_pcm_suspend(struct snd_usb_stream *as)
861 ret = snd_usb_pcm_change_state(&as->substream[0], UAC3_PD_STATE_D2);
865 ret = snd_usb_pcm_change_state(&as->substream[1], UAC3_PD_STATE_D2);
872 int snd_usb_pcm_resume(struct snd_usb_stream *as)
876 ret = snd_usb_pcm_change_state(&as->substream[0], UAC3_PD_STATE_D1);
880 ret = snd_usb_pcm_change_state(&as->substream[1], UAC3_PD_STATE_D1);
890 * allocate a buffer and set the given audio format.
892 * so far we use a physically linear buffer although packetize transfer
893 * doesn't need a continuous area.
894 * if sg buffer is supported on the later version of alsa, we'll follow
897 static int snd_usb_hw_params(struct snd_pcm_substream *substream,
898 struct snd_pcm_hw_params *hw_params)
900 struct snd_usb_substream *subs = substream->runtime->private_data;
901 struct audioformat *fmt;
904 ret = snd_media_start_pipeline(subs);
908 subs->pcm_format = params_format(hw_params);
909 subs->period_bytes = params_period_bytes(hw_params);
910 subs->period_frames = params_period_size(hw_params);
911 subs->buffer_periods = params_periods(hw_params);
912 subs->channels = params_channels(hw_params);
913 subs->cur_rate = params_rate(hw_params);
915 fmt = find_format(subs);
917 dev_dbg(&subs->dev->dev,
918 "cannot set format: format = %#x, rate = %d, channels = %d\n",
919 subs->pcm_format, subs->cur_rate, subs->channels);
924 ret = snd_usb_lock_shutdown(subs->stream->chip);
928 ret = snd_usb_pcm_change_state(subs, UAC3_PD_STATE_D0);
932 ret = set_format(subs, fmt);
936 subs->interface = fmt->iface;
937 subs->altset_idx = fmt->altset_idx;
938 subs->need_setup_ep = true;
941 snd_usb_unlock_shutdown(subs->stream->chip);
947 snd_media_stop_pipeline(subs);
954 * reset the audio format and release the buffer
956 static int snd_usb_hw_free(struct snd_pcm_substream *substream)
958 struct snd_usb_substream *subs = substream->runtime->private_data;
960 snd_media_stop_pipeline(subs);
961 subs->cur_audiofmt = NULL;
963 subs->period_bytes = 0;
964 if (!snd_usb_lock_shutdown(subs->stream->chip)) {
965 stop_endpoints(subs);
966 sync_pending_stops(subs);
967 snd_usb_endpoint_deactivate(subs->sync_endpoint);
968 snd_usb_endpoint_deactivate(subs->data_endpoint);
969 if (subs->data_endpoint) {
970 subs->data_endpoint->sync_master = NULL;
971 subs->data_endpoint = NULL;
973 subs->sync_endpoint = NULL;
974 snd_usb_unlock_shutdown(subs->stream->chip);
983 * only a few subtle things...
985 static int snd_usb_pcm_prepare(struct snd_pcm_substream *substream)
987 struct snd_pcm_runtime *runtime = substream->runtime;
988 struct snd_usb_substream *subs = runtime->private_data;
989 struct usb_host_interface *alts;
990 struct usb_interface *iface;
993 if (! subs->cur_audiofmt) {
994 dev_err(&subs->dev->dev, "no format is specified!\n");
998 ret = snd_usb_lock_shutdown(subs->stream->chip);
1001 if (snd_BUG_ON(!subs->data_endpoint)) {
1006 ret = snd_usb_pcm_change_state(subs, UAC3_PD_STATE_D0);
1010 ret = set_format(subs, subs->cur_audiofmt);
1014 if (subs->need_setup_ep) {
1016 iface = usb_ifnum_to_if(subs->dev, subs->cur_audiofmt->iface);
1017 alts = &iface->altsetting[subs->cur_audiofmt->altset_idx];
1018 ret = snd_usb_init_sample_rate(subs->stream->chip,
1019 subs->cur_audiofmt->iface,
1026 ret = configure_endpoint(subs);
1029 subs->need_setup_ep = false;
1032 /* some unit conversions in runtime */
1033 subs->data_endpoint->maxframesize =
1034 bytes_to_frames(runtime, subs->data_endpoint->maxpacksize);
1035 subs->data_endpoint->curframesize =
1036 bytes_to_frames(runtime, subs->data_endpoint->curpacksize);
1038 /* reset the pointer */
1039 subs->hwptr_done = 0;
1040 subs->transfer_done = 0;
1041 subs->last_delay = 0;
1042 subs->last_frame_number = 0;
1045 /* for playback, submit the URBs now; otherwise, the first hwptr_done
1046 * updates for all URBs would happen at the same time when starting */
1047 if (subs->direction == SNDRV_PCM_STREAM_PLAYBACK)
1048 ret = start_endpoints(subs);
1051 snd_usb_unlock_shutdown(subs->stream->chip);
1055 static const struct snd_pcm_hardware snd_usb_hardware =
1057 .info = SNDRV_PCM_INFO_MMAP |
1058 SNDRV_PCM_INFO_MMAP_VALID |
1059 SNDRV_PCM_INFO_BATCH |
1060 SNDRV_PCM_INFO_INTERLEAVED |
1061 SNDRV_PCM_INFO_BLOCK_TRANSFER |
1062 SNDRV_PCM_INFO_PAUSE,
1063 .buffer_bytes_max = 1024 * 1024,
1064 .period_bytes_min = 64,
1065 .period_bytes_max = 512 * 1024,
1067 .periods_max = 1024,
1070 static int hw_check_valid_format(struct snd_usb_substream *subs,
1071 struct snd_pcm_hw_params *params,
1072 struct audioformat *fp)
1074 struct snd_interval *it = hw_param_interval(params, SNDRV_PCM_HW_PARAM_RATE);
1075 struct snd_interval *ct = hw_param_interval(params, SNDRV_PCM_HW_PARAM_CHANNELS);
1076 struct snd_mask *fmts = hw_param_mask(params, SNDRV_PCM_HW_PARAM_FORMAT);
1077 struct snd_interval *pt = hw_param_interval(params, SNDRV_PCM_HW_PARAM_PERIOD_TIME);
1078 struct snd_mask check_fmts;
1081 /* check the format */
1082 snd_mask_none(&check_fmts);
1083 check_fmts.bits[0] = (u32)fp->formats;
1084 check_fmts.bits[1] = (u32)(fp->formats >> 32);
1085 snd_mask_intersect(&check_fmts, fmts);
1086 if (snd_mask_empty(&check_fmts)) {
1087 hwc_debug(" > check: no supported format %d\n", fp->format);
1090 /* check the channels */
1091 if (fp->channels < ct->min || fp->channels > ct->max) {
1092 hwc_debug(" > check: no valid channels %d (%d/%d)\n", fp->channels, ct->min, ct->max);
1095 /* check the rate is within the range */
1096 if (fp->rate_min > it->max || (fp->rate_min == it->max && it->openmax)) {
1097 hwc_debug(" > check: rate_min %d > max %d\n", fp->rate_min, it->max);
1100 if (fp->rate_max < it->min || (fp->rate_max == it->min && it->openmin)) {
1101 hwc_debug(" > check: rate_max %d < min %d\n", fp->rate_max, it->min);
1104 /* check whether the period time is >= the data packet interval */
1105 if (subs->speed != USB_SPEED_FULL) {
1106 ptime = 125 * (1 << fp->datainterval);
1107 if (ptime > pt->max || (ptime == pt->max && pt->openmax)) {
1108 hwc_debug(" > check: ptime %u > max %u\n", ptime, pt->max);
1115 static int hw_rule_rate(struct snd_pcm_hw_params *params,
1116 struct snd_pcm_hw_rule *rule)
1118 struct snd_usb_substream *subs = rule->private;
1119 struct audioformat *fp;
1120 struct snd_interval *it = hw_param_interval(params, SNDRV_PCM_HW_PARAM_RATE);
1121 unsigned int rmin, rmax, r;
1125 hwc_debug("hw_rule_rate: (%d,%d)\n", it->min, it->max);
1128 list_for_each_entry(fp, &subs->fmt_list, list) {
1129 if (!hw_check_valid_format(subs, params, fp))
1131 if (fp->rate_table && fp->nr_rates) {
1132 for (i = 0; i < fp->nr_rates; i++) {
1133 r = fp->rate_table[i];
1134 if (!snd_interval_test(it, r))
1136 rmin = min(rmin, r);
1137 rmax = max(rmax, r);
1140 rmin = min(rmin, fp->rate_min);
1141 rmax = max(rmax, fp->rate_max);
1146 hwc_debug(" --> get empty\n");
1152 if (it->min < rmin) {
1157 if (it->max > rmax) {
1162 if (snd_interval_checkempty(it)) {
1166 hwc_debug(" --> (%d, %d) (changed = %d)\n", it->min, it->max, changed);
1171 static int hw_rule_channels(struct snd_pcm_hw_params *params,
1172 struct snd_pcm_hw_rule *rule)
1174 struct snd_usb_substream *subs = rule->private;
1175 struct audioformat *fp;
1176 struct snd_interval *it = hw_param_interval(params, SNDRV_PCM_HW_PARAM_CHANNELS);
1177 unsigned int rmin, rmax;
1180 hwc_debug("hw_rule_channels: (%d,%d)\n", it->min, it->max);
1183 list_for_each_entry(fp, &subs->fmt_list, list) {
1184 if (!hw_check_valid_format(subs, params, fp))
1187 if (rmin > fp->channels)
1188 rmin = fp->channels;
1189 if (rmax < fp->channels)
1190 rmax = fp->channels;
1192 rmin = fp->channels;
1193 rmax = fp->channels;
1198 hwc_debug(" --> get empty\n");
1204 if (it->min < rmin) {
1209 if (it->max > rmax) {
1214 if (snd_interval_checkempty(it)) {
1218 hwc_debug(" --> (%d, %d) (changed = %d)\n", it->min, it->max, changed);
1222 static int hw_rule_format(struct snd_pcm_hw_params *params,
1223 struct snd_pcm_hw_rule *rule)
1225 struct snd_usb_substream *subs = rule->private;
1226 struct audioformat *fp;
1227 struct snd_mask *fmt = hw_param_mask(params, SNDRV_PCM_HW_PARAM_FORMAT);
1232 hwc_debug("hw_rule_format: %x:%x\n", fmt->bits[0], fmt->bits[1]);
1234 list_for_each_entry(fp, &subs->fmt_list, list) {
1235 if (!hw_check_valid_format(subs, params, fp))
1237 fbits |= fp->formats;
1240 oldbits[0] = fmt->bits[0];
1241 oldbits[1] = fmt->bits[1];
1242 fmt->bits[0] &= (u32)fbits;
1243 fmt->bits[1] &= (u32)(fbits >> 32);
1244 if (!fmt->bits[0] && !fmt->bits[1]) {
1245 hwc_debug(" --> get empty\n");
1248 changed = (oldbits[0] != fmt->bits[0] || oldbits[1] != fmt->bits[1]);
1249 hwc_debug(" --> %x:%x (changed = %d)\n", fmt->bits[0], fmt->bits[1], changed);
1253 static int hw_rule_period_time(struct snd_pcm_hw_params *params,
1254 struct snd_pcm_hw_rule *rule)
1256 struct snd_usb_substream *subs = rule->private;
1257 struct audioformat *fp;
1258 struct snd_interval *it;
1259 unsigned char min_datainterval;
1263 it = hw_param_interval(params, SNDRV_PCM_HW_PARAM_PERIOD_TIME);
1264 hwc_debug("hw_rule_period_time: (%u,%u)\n", it->min, it->max);
1265 min_datainterval = 0xff;
1266 list_for_each_entry(fp, &subs->fmt_list, list) {
1267 if (!hw_check_valid_format(subs, params, fp))
1269 min_datainterval = min(min_datainterval, fp->datainterval);
1271 if (min_datainterval == 0xff) {
1272 hwc_debug(" --> get empty\n");
1276 pmin = 125 * (1 << min_datainterval);
1278 if (it->min < pmin) {
1283 if (snd_interval_checkempty(it)) {
1287 hwc_debug(" --> (%u,%u) (changed = %d)\n", it->min, it->max, changed);
1293 * set up the runtime hardware information.
1296 static int setup_hw_info(struct snd_pcm_runtime *runtime, struct snd_usb_substream *subs)
1298 struct audioformat *fp;
1299 unsigned int pt, ptmin;
1300 int param_period_time_if_needed;
1303 runtime->hw.formats = subs->formats;
1305 runtime->hw.rate_min = 0x7fffffff;
1306 runtime->hw.rate_max = 0;
1307 runtime->hw.channels_min = 256;
1308 runtime->hw.channels_max = 0;
1309 runtime->hw.rates = 0;
1311 /* check min/max rates and channels */
1312 list_for_each_entry(fp, &subs->fmt_list, list) {
1313 runtime->hw.rates |= fp->rates;
1314 if (runtime->hw.rate_min > fp->rate_min)
1315 runtime->hw.rate_min = fp->rate_min;
1316 if (runtime->hw.rate_max < fp->rate_max)
1317 runtime->hw.rate_max = fp->rate_max;
1318 if (runtime->hw.channels_min > fp->channels)
1319 runtime->hw.channels_min = fp->channels;
1320 if (runtime->hw.channels_max < fp->channels)
1321 runtime->hw.channels_max = fp->channels;
1322 if (fp->fmt_type == UAC_FORMAT_TYPE_II && fp->frame_size > 0) {
1323 /* FIXME: there might be more than one audio formats... */
1324 runtime->hw.period_bytes_min = runtime->hw.period_bytes_max =
1327 pt = 125 * (1 << fp->datainterval);
1328 ptmin = min(ptmin, pt);
1331 param_period_time_if_needed = SNDRV_PCM_HW_PARAM_PERIOD_TIME;
1332 if (subs->speed == USB_SPEED_FULL)
1333 /* full speed devices have fixed data packet interval */
1336 /* if period time doesn't go below 1 ms, no rules needed */
1337 param_period_time_if_needed = -1;
1339 err = snd_pcm_hw_constraint_minmax(runtime,
1340 SNDRV_PCM_HW_PARAM_PERIOD_TIME,
1345 err = snd_pcm_hw_rule_add(runtime, 0, SNDRV_PCM_HW_PARAM_RATE,
1347 SNDRV_PCM_HW_PARAM_FORMAT,
1348 SNDRV_PCM_HW_PARAM_CHANNELS,
1349 param_period_time_if_needed,
1353 err = snd_pcm_hw_rule_add(runtime, 0, SNDRV_PCM_HW_PARAM_CHANNELS,
1354 hw_rule_channels, subs,
1355 SNDRV_PCM_HW_PARAM_FORMAT,
1356 SNDRV_PCM_HW_PARAM_RATE,
1357 param_period_time_if_needed,
1361 err = snd_pcm_hw_rule_add(runtime, 0, SNDRV_PCM_HW_PARAM_FORMAT,
1362 hw_rule_format, subs,
1363 SNDRV_PCM_HW_PARAM_RATE,
1364 SNDRV_PCM_HW_PARAM_CHANNELS,
1365 param_period_time_if_needed,
1369 if (param_period_time_if_needed >= 0) {
1370 err = snd_pcm_hw_rule_add(runtime, 0,
1371 SNDRV_PCM_HW_PARAM_PERIOD_TIME,
1372 hw_rule_period_time, subs,
1373 SNDRV_PCM_HW_PARAM_FORMAT,
1374 SNDRV_PCM_HW_PARAM_CHANNELS,
1375 SNDRV_PCM_HW_PARAM_RATE,
1381 return snd_usb_autoresume(subs->stream->chip);
1384 static int snd_usb_pcm_open(struct snd_pcm_substream *substream)
1386 int direction = substream->stream;
1387 struct snd_usb_stream *as = snd_pcm_substream_chip(substream);
1388 struct snd_pcm_runtime *runtime = substream->runtime;
1389 struct snd_usb_substream *subs = &as->substream[direction];
1392 subs->interface = -1;
1393 subs->altset_idx = 0;
1394 runtime->hw = snd_usb_hardware;
1395 runtime->private_data = subs;
1396 subs->pcm_substream = substream;
1397 /* runtime PM is also done there */
1399 /* initialize DSD/DOP context */
1400 subs->dsd_dop.byte_idx = 0;
1401 subs->dsd_dop.channel = 0;
1402 subs->dsd_dop.marker = 1;
1404 ret = setup_hw_info(runtime, subs);
1406 ret = snd_media_stream_init(subs, as->pcm, direction);
1408 snd_usb_autosuspend(subs->stream->chip);
1413 static int snd_usb_pcm_close(struct snd_pcm_substream *substream)
1415 int direction = substream->stream;
1416 struct snd_usb_stream *as = snd_pcm_substream_chip(substream);
1417 struct snd_usb_substream *subs = &as->substream[direction];
1420 snd_media_stop_pipeline(subs);
1422 if (!as->chip->keep_iface &&
1423 subs->interface >= 0 &&
1424 !snd_usb_lock_shutdown(subs->stream->chip)) {
1425 usb_set_interface(subs->dev, subs->interface, 0);
1426 subs->interface = -1;
1427 ret = snd_usb_pcm_change_state(subs, UAC3_PD_STATE_D1);
1428 snd_usb_unlock_shutdown(subs->stream->chip);
1433 subs->pcm_substream = NULL;
1434 snd_usb_autosuspend(subs->stream->chip);
1439 /* Since a URB can handle only a single linear buffer, we must use double
1440 * buffering when the data to be transferred overflows the buffer boundary.
1441 * To avoid inconsistencies when updating hwptr_done, we use double buffering
1444 static void retire_capture_urb(struct snd_usb_substream *subs,
1447 struct snd_pcm_runtime *runtime = subs->pcm_substream->runtime;
1448 unsigned int stride, frames, bytes, oldptr;
1449 int i, period_elapsed = 0;
1450 unsigned long flags;
1452 int current_frame_number;
1454 /* read frame number here, update pointer in critical section */
1455 current_frame_number = usb_get_current_frame_number(subs->dev);
1457 stride = runtime->frame_bits >> 3;
1459 for (i = 0; i < urb->number_of_packets; i++) {
1460 cp = (unsigned char *)urb->transfer_buffer + urb->iso_frame_desc[i].offset + subs->pkt_offset_adj;
1461 if (urb->iso_frame_desc[i].status && printk_ratelimit()) {
1462 dev_dbg(&subs->dev->dev, "frame %d active: %d\n",
1463 i, urb->iso_frame_desc[i].status);
1466 bytes = urb->iso_frame_desc[i].actual_length;
1467 if (subs->stream_offset_adj > 0) {
1468 unsigned int adj = min(subs->stream_offset_adj, bytes);
1471 subs->stream_offset_adj -= adj;
1473 frames = bytes / stride;
1474 if (!subs->txfr_quirk)
1475 bytes = frames * stride;
1476 if (bytes % (runtime->sample_bits >> 3) != 0) {
1477 int oldbytes = bytes;
1478 bytes = frames * stride;
1479 dev_warn_ratelimited(&subs->dev->dev,
1480 "Corrected urb data len. %d->%d\n",
1483 /* update the current pointer */
1484 spin_lock_irqsave(&subs->lock, flags);
1485 oldptr = subs->hwptr_done;
1486 subs->hwptr_done += bytes;
1487 if (subs->hwptr_done >= runtime->buffer_size * stride)
1488 subs->hwptr_done -= runtime->buffer_size * stride;
1489 frames = (bytes + (oldptr % stride)) / stride;
1490 subs->transfer_done += frames;
1491 if (subs->transfer_done >= runtime->period_size) {
1492 subs->transfer_done -= runtime->period_size;
1495 /* capture delay is by construction limited to one URB,
1498 runtime->delay = subs->last_delay = 0;
1500 /* realign last_frame_number */
1501 subs->last_frame_number = current_frame_number;
1502 subs->last_frame_number &= 0xFF; /* keep 8 LSBs */
1504 spin_unlock_irqrestore(&subs->lock, flags);
1505 /* copy a data chunk */
1506 if (oldptr + bytes > runtime->buffer_size * stride) {
1507 unsigned int bytes1 =
1508 runtime->buffer_size * stride - oldptr;
1509 memcpy(runtime->dma_area + oldptr, cp, bytes1);
1510 memcpy(runtime->dma_area, cp + bytes1, bytes - bytes1);
1512 memcpy(runtime->dma_area + oldptr, cp, bytes);
1517 snd_pcm_period_elapsed(subs->pcm_substream);
1520 static inline void fill_playback_urb_dsd_dop(struct snd_usb_substream *subs,
1521 struct urb *urb, unsigned int bytes)
1523 struct snd_pcm_runtime *runtime = subs->pcm_substream->runtime;
1524 unsigned int stride = runtime->frame_bits >> 3;
1525 unsigned int dst_idx = 0;
1526 unsigned int src_idx = subs->hwptr_done;
1527 unsigned int wrap = runtime->buffer_size * stride;
1528 u8 *dst = urb->transfer_buffer;
1529 u8 *src = runtime->dma_area;
1530 u8 marker[] = { 0x05, 0xfa };
1533 * The DSP DOP format defines a way to transport DSD samples over
1534 * normal PCM data endpoints. It requires stuffing of marker bytes
1535 * (0x05 and 0xfa, alternating per sample frame), and then expects
1536 * 2 additional bytes of actual payload. The whole frame is stored
1539 * Hence, for a stereo transport, the buffer layout looks like this,
1540 * where L refers to left channel samples and R to right.
1542 * L1 L2 0x05 R1 R2 0x05 L3 L4 0xfa R3 R4 0xfa
1543 * L5 L6 0x05 R5 R6 0x05 L7 L8 0xfa R7 R8 0xfa
1549 if (++subs->dsd_dop.byte_idx == 3) {
1550 /* frame boundary? */
1551 dst[dst_idx++] = marker[subs->dsd_dop.marker];
1553 subs->dsd_dop.byte_idx = 0;
1555 if (++subs->dsd_dop.channel % runtime->channels == 0) {
1556 /* alternate the marker */
1557 subs->dsd_dop.marker++;
1558 subs->dsd_dop.marker %= ARRAY_SIZE(marker);
1559 subs->dsd_dop.channel = 0;
1562 /* stuff the DSD payload */
1563 int idx = (src_idx + subs->dsd_dop.byte_idx - 1) % wrap;
1565 if (subs->cur_audiofmt->dsd_bitrev)
1566 dst[dst_idx++] = bitrev8(src[idx]);
1568 dst[dst_idx++] = src[idx];
1573 if (subs->hwptr_done >= runtime->buffer_size * stride)
1574 subs->hwptr_done -= runtime->buffer_size * stride;
1577 static void copy_to_urb(struct snd_usb_substream *subs, struct urb *urb,
1578 int offset, int stride, unsigned int bytes)
1580 struct snd_pcm_runtime *runtime = subs->pcm_substream->runtime;
1582 if (subs->hwptr_done + bytes > runtime->buffer_size * stride) {
1583 /* err, the transferred area goes over buffer boundary. */
1584 unsigned int bytes1 =
1585 runtime->buffer_size * stride - subs->hwptr_done;
1586 memcpy(urb->transfer_buffer + offset,
1587 runtime->dma_area + subs->hwptr_done, bytes1);
1588 memcpy(urb->transfer_buffer + offset + bytes1,
1589 runtime->dma_area, bytes - bytes1);
1591 memcpy(urb->transfer_buffer + offset,
1592 runtime->dma_area + subs->hwptr_done, bytes);
1594 subs->hwptr_done += bytes;
1595 if (subs->hwptr_done >= runtime->buffer_size * stride)
1596 subs->hwptr_done -= runtime->buffer_size * stride;
1599 static unsigned int copy_to_urb_quirk(struct snd_usb_substream *subs,
1600 struct urb *urb, int stride,
1603 __le32 packet_length;
1606 /* Put __le32 length descriptor at start of each packet. */
1607 for (i = 0; i < urb->number_of_packets; i++) {
1608 unsigned int length = urb->iso_frame_desc[i].length;
1609 unsigned int offset = urb->iso_frame_desc[i].offset;
1611 packet_length = cpu_to_le32(length);
1612 offset += i * sizeof(packet_length);
1613 urb->iso_frame_desc[i].offset = offset;
1614 urb->iso_frame_desc[i].length += sizeof(packet_length);
1615 memcpy(urb->transfer_buffer + offset,
1616 &packet_length, sizeof(packet_length));
1617 copy_to_urb(subs, urb, offset + sizeof(packet_length),
1620 /* Adjust transfer size accordingly. */
1621 bytes += urb->number_of_packets * sizeof(packet_length);
1625 static void prepare_playback_urb(struct snd_usb_substream *subs,
1628 struct snd_pcm_runtime *runtime = subs->pcm_substream->runtime;
1629 struct snd_usb_endpoint *ep = subs->data_endpoint;
1630 struct snd_urb_ctx *ctx = urb->context;
1631 unsigned int counts, frames, bytes;
1632 int i, stride, period_elapsed = 0;
1633 unsigned long flags;
1635 stride = runtime->frame_bits >> 3;
1638 urb->number_of_packets = 0;
1639 spin_lock_irqsave(&subs->lock, flags);
1640 subs->frame_limit += ep->max_urb_frames;
1641 for (i = 0; i < ctx->packets; i++) {
1642 if (ctx->packet_size[i])
1643 counts = ctx->packet_size[i];
1644 else if (ep->sync_master)
1645 counts = snd_usb_endpoint_slave_next_packet_size(ep);
1647 counts = snd_usb_endpoint_next_packet_size(ep);
1649 /* set up descriptor */
1650 urb->iso_frame_desc[i].offset = frames * ep->stride;
1651 urb->iso_frame_desc[i].length = counts * ep->stride;
1653 urb->number_of_packets++;
1654 subs->transfer_done += counts;
1655 if (subs->transfer_done >= runtime->period_size) {
1656 subs->transfer_done -= runtime->period_size;
1657 subs->frame_limit = 0;
1659 if (subs->fmt_type == UAC_FORMAT_TYPE_II) {
1660 if (subs->transfer_done > 0) {
1661 /* FIXME: fill-max mode is not
1663 frames -= subs->transfer_done;
1664 counts -= subs->transfer_done;
1665 urb->iso_frame_desc[i].length =
1666 counts * ep->stride;
1667 subs->transfer_done = 0;
1670 if (i < ctx->packets) {
1671 /* add a transfer delimiter */
1672 urb->iso_frame_desc[i].offset =
1673 frames * ep->stride;
1674 urb->iso_frame_desc[i].length = 0;
1675 urb->number_of_packets++;
1680 /* finish at the period boundary or after enough frames */
1681 if ((period_elapsed ||
1682 subs->transfer_done >= subs->frame_limit) &&
1683 !snd_usb_endpoint_implicit_feedback_sink(ep))
1686 bytes = frames * ep->stride;
1688 if (unlikely(subs->pcm_format == SNDRV_PCM_FORMAT_DSD_U16_LE &&
1689 subs->cur_audiofmt->dsd_dop)) {
1690 fill_playback_urb_dsd_dop(subs, urb, bytes);
1691 } else if (unlikely(subs->pcm_format == SNDRV_PCM_FORMAT_DSD_U8 &&
1692 subs->cur_audiofmt->dsd_bitrev)) {
1693 /* bit-reverse the bytes */
1694 u8 *buf = urb->transfer_buffer;
1695 for (i = 0; i < bytes; i++) {
1696 int idx = (subs->hwptr_done + i)
1697 % (runtime->buffer_size * stride);
1698 buf[i] = bitrev8(runtime->dma_area[idx]);
1701 subs->hwptr_done += bytes;
1702 if (subs->hwptr_done >= runtime->buffer_size * stride)
1703 subs->hwptr_done -= runtime->buffer_size * stride;
1706 if (!subs->tx_length_quirk)
1707 copy_to_urb(subs, urb, 0, stride, bytes);
1709 bytes = copy_to_urb_quirk(subs, urb, stride, bytes);
1710 /* bytes is now amount of outgoing data */
1713 /* update delay with exact number of samples queued */
1714 runtime->delay = subs->last_delay;
1715 runtime->delay += frames;
1716 subs->last_delay = runtime->delay;
1718 /* realign last_frame_number */
1719 subs->last_frame_number = usb_get_current_frame_number(subs->dev);
1720 subs->last_frame_number &= 0xFF; /* keep 8 LSBs */
1722 if (subs->trigger_tstamp_pending_update) {
1723 /* this is the first actual URB submitted,
1724 * update trigger timestamp to reflect actual start time
1726 snd_pcm_gettime(runtime, &runtime->trigger_tstamp);
1727 subs->trigger_tstamp_pending_update = false;
1730 spin_unlock_irqrestore(&subs->lock, flags);
1731 urb->transfer_buffer_length = bytes;
1733 snd_pcm_period_elapsed(subs->pcm_substream);
1737 * process after playback data complete
1738 * - decrease the delay count again
1740 static void retire_playback_urb(struct snd_usb_substream *subs,
1743 unsigned long flags;
1744 struct snd_pcm_runtime *runtime = subs->pcm_substream->runtime;
1745 struct snd_usb_endpoint *ep = subs->data_endpoint;
1746 int processed = urb->transfer_buffer_length / ep->stride;
1749 /* ignore the delay accounting when processed=0 is given, i.e.
1750 * silent payloads are processed before handling the actual data
1755 spin_lock_irqsave(&subs->lock, flags);
1756 if (!subs->last_delay)
1757 goto out; /* short path */
1759 est_delay = snd_usb_pcm_delay(subs, runtime->rate);
1760 /* update delay with exact number of samples played */
1761 if (processed > subs->last_delay)
1762 subs->last_delay = 0;
1764 subs->last_delay -= processed;
1765 runtime->delay = subs->last_delay;
1768 * Report when delay estimate is off by more than 2ms.
1769 * The error should be lower than 2ms since the estimate relies
1770 * on two reads of a counter updated every ms.
1772 if (abs(est_delay - subs->last_delay) * 1000 > runtime->rate * 2)
1773 dev_dbg_ratelimited(&subs->dev->dev,
1774 "delay: estimated %d, actual %d\n",
1775 est_delay, subs->last_delay);
1777 if (!subs->running) {
1778 /* update last_frame_number for delay counting here since
1779 * prepare_playback_urb won't be called during pause
1781 subs->last_frame_number =
1782 usb_get_current_frame_number(subs->dev) & 0xff;
1786 spin_unlock_irqrestore(&subs->lock, flags);
1789 static int snd_usb_substream_playback_trigger(struct snd_pcm_substream *substream,
1792 struct snd_usb_substream *subs = substream->runtime->private_data;
1795 case SNDRV_PCM_TRIGGER_START:
1796 subs->trigger_tstamp_pending_update = true;
1798 case SNDRV_PCM_TRIGGER_PAUSE_RELEASE:
1799 subs->data_endpoint->prepare_data_urb = prepare_playback_urb;
1800 subs->data_endpoint->retire_data_urb = retire_playback_urb;
1803 case SNDRV_PCM_TRIGGER_STOP:
1804 stop_endpoints(subs);
1807 case SNDRV_PCM_TRIGGER_PAUSE_PUSH:
1808 subs->data_endpoint->prepare_data_urb = NULL;
1809 /* keep retire_data_urb for delay calculation */
1810 subs->data_endpoint->retire_data_urb = retire_playback_urb;
1813 case SNDRV_PCM_TRIGGER_SUSPEND:
1814 if (subs->stream->chip->setup_fmt_after_resume_quirk) {
1815 stop_endpoints(subs);
1816 subs->need_setup_fmt = true;
1825 static int snd_usb_substream_capture_trigger(struct snd_pcm_substream *substream,
1829 struct snd_usb_substream *subs = substream->runtime->private_data;
1832 case SNDRV_PCM_TRIGGER_START:
1833 err = start_endpoints(subs);
1837 subs->data_endpoint->retire_data_urb = retire_capture_urb;
1840 case SNDRV_PCM_TRIGGER_STOP:
1841 stop_endpoints(subs);
1842 subs->data_endpoint->retire_data_urb = NULL;
1845 case SNDRV_PCM_TRIGGER_PAUSE_PUSH:
1846 subs->data_endpoint->retire_data_urb = NULL;
1849 case SNDRV_PCM_TRIGGER_PAUSE_RELEASE:
1850 subs->data_endpoint->retire_data_urb = retire_capture_urb;
1853 case SNDRV_PCM_TRIGGER_SUSPEND:
1854 if (subs->stream->chip->setup_fmt_after_resume_quirk) {
1855 stop_endpoints(subs);
1856 subs->need_setup_fmt = true;
1865 static const struct snd_pcm_ops snd_usb_playback_ops = {
1866 .open = snd_usb_pcm_open,
1867 .close = snd_usb_pcm_close,
1868 .hw_params = snd_usb_hw_params,
1869 .hw_free = snd_usb_hw_free,
1870 .prepare = snd_usb_pcm_prepare,
1871 .trigger = snd_usb_substream_playback_trigger,
1872 .sync_stop = snd_usb_pcm_sync_stop,
1873 .pointer = snd_usb_pcm_pointer,
1876 static const struct snd_pcm_ops snd_usb_capture_ops = {
1877 .open = snd_usb_pcm_open,
1878 .close = snd_usb_pcm_close,
1879 .hw_params = snd_usb_hw_params,
1880 .hw_free = snd_usb_hw_free,
1881 .prepare = snd_usb_pcm_prepare,
1882 .trigger = snd_usb_substream_capture_trigger,
1883 .sync_stop = snd_usb_pcm_sync_stop,
1884 .pointer = snd_usb_pcm_pointer,
1887 void snd_usb_set_pcm_ops(struct snd_pcm *pcm, int stream)
1889 const struct snd_pcm_ops *ops;
1891 ops = stream == SNDRV_PCM_STREAM_PLAYBACK ?
1892 &snd_usb_playback_ops : &snd_usb_capture_ops;
1893 snd_pcm_set_ops(pcm, stream, ops);
1896 void snd_usb_preallocate_buffer(struct snd_usb_substream *subs)
1898 struct snd_pcm *pcm = subs->stream->pcm;
1899 struct snd_pcm_substream *s = pcm->streams[subs->direction].substream;
1900 struct device *dev = subs->dev->bus->controller;
1902 if (snd_usb_use_vmalloc)
1903 snd_pcm_set_managed_buffer(s, SNDRV_DMA_TYPE_VMALLOC,
1906 snd_pcm_set_managed_buffer(s, SNDRV_DMA_TYPE_DEV_SG,
1907 dev, 64*1024, 512*1024);