1 // SPDX-License-Identifier: GPL-2.0-or-later
6 #include <linux/init.h>
7 #include <linux/ratelimit.h>
9 #include <linux/usb/audio.h>
10 #include <linux/slab.h>
12 #include <sound/core.h>
13 #include <sound/pcm.h>
14 #include <sound/pcm_params.h>
23 #define EP_FLAG_RUNNING 1
24 #define EP_FLAG_STOPPING 2
27 * snd_usb_endpoint is a model that abstracts everything related to an
28 * USB endpoint and its streaming.
30 * There are functions to activate and deactivate the streaming URBs and
31 * optional callbacks to let the pcm logic handle the actual content of the
32 * packets for playback and record. Thus, the bus streaming and the audio
33 * handlers are fully decoupled.
35 * There are two different types of endpoints in audio applications.
37 * SND_USB_ENDPOINT_TYPE_DATA handles full audio data payload for both
38 * inbound and outbound traffic.
40 * SND_USB_ENDPOINT_TYPE_SYNC endpoints are for inbound traffic only and
41 * expect the payload to carry Q10.14 / Q16.16 formatted sync information
44 * Each endpoint has to be configured prior to being used by calling
45 * snd_usb_endpoint_set_params().
47 * The model incorporates a reference counting, so that multiple users
48 * can call snd_usb_endpoint_start() and snd_usb_endpoint_stop(), and
49 * only the first user will effectively start the URBs, and only the last
50 * one to stop it will tear the URBs down again.
54 * convert a sampling rate into our full speed format (fs/1000 in Q16.16)
55 * this will overflow at approx 524 kHz
57 static inline unsigned get_usb_full_speed_rate(unsigned int rate)
59 return ((rate << 13) + 62) / 125;
63 * convert a sampling rate into USB high speed format (fs/8000 in Q16.16)
64 * this will overflow at approx 4 MHz
66 static inline unsigned get_usb_high_speed_rate(unsigned int rate)
68 return ((rate << 10) + 62) / 125;
74 static void release_urb_ctx(struct snd_urb_ctx *u)
77 usb_free_coherent(u->ep->chip->dev, u->buffer_size,
78 u->urb->transfer_buffer,
79 u->urb->transfer_dma);
84 static const char *usb_error_string(int err)
90 return "endpoint not enabled";
92 return "endpoint stalled";
94 return "not enough bandwidth";
96 return "device disabled";
98 return "device suspended";
103 return "internal error";
105 return "unknown error";
110 * snd_usb_endpoint_implicit_feedback_sink: Report endpoint usage type
112 * @ep: The snd_usb_endpoint
114 * Determine whether an endpoint is driven by an implicit feedback
115 * data endpoint source.
117 int snd_usb_endpoint_implicit_feedback_sink(struct snd_usb_endpoint *ep)
119 return ep->sync_master &&
120 ep->sync_master->type == SND_USB_ENDPOINT_TYPE_DATA &&
121 ep->type == SND_USB_ENDPOINT_TYPE_DATA &&
122 usb_pipeout(ep->pipe);
126 * For streaming based on information derived from sync endpoints,
127 * prepare_outbound_urb_sizes() will call slave_next_packet_size() to
128 * determine the number of samples to be sent in the next packet.
130 * For implicit feedback, slave_next_packet_size() is unused.
132 int snd_usb_endpoint_slave_next_packet_size(struct snd_usb_endpoint *ep)
138 return ep->maxframesize;
140 spin_lock_irqsave(&ep->lock, flags);
141 ep->phase = (ep->phase & 0xffff)
142 + (ep->freqm << ep->datainterval);
143 ret = min(ep->phase >> 16, ep->maxframesize);
144 spin_unlock_irqrestore(&ep->lock, flags);
150 * For adaptive and synchronous endpoints, prepare_outbound_urb_sizes()
151 * will call next_packet_size() to determine the number of samples to be
152 * sent in the next packet.
154 int snd_usb_endpoint_next_packet_size(struct snd_usb_endpoint *ep)
159 return ep->maxframesize;
161 ep->sample_accum += ep->sample_rem;
162 if (ep->sample_accum >= ep->pps) {
163 ep->sample_accum -= ep->pps;
164 ret = ep->packsize[1];
166 ret = ep->packsize[0];
172 static void retire_outbound_urb(struct snd_usb_endpoint *ep,
173 struct snd_urb_ctx *urb_ctx)
175 if (ep->retire_data_urb)
176 ep->retire_data_urb(ep->data_subs, urb_ctx->urb);
179 static void retire_inbound_urb(struct snd_usb_endpoint *ep,
180 struct snd_urb_ctx *urb_ctx)
182 struct urb *urb = urb_ctx->urb;
184 if (unlikely(ep->skip_packets > 0)) {
190 snd_usb_handle_sync_urb(ep->sync_slave, ep, urb);
192 if (ep->retire_data_urb)
193 ep->retire_data_urb(ep->data_subs, urb);
196 static void prepare_silent_urb(struct snd_usb_endpoint *ep,
197 struct snd_urb_ctx *ctx)
199 struct urb *urb = ctx->urb;
200 unsigned int offs = 0;
201 unsigned int extra = 0;
202 __le32 packet_length;
205 /* For tx_length_quirk, put packet length at start of packet */
206 if (ep->chip->tx_length_quirk)
207 extra = sizeof(packet_length);
209 for (i = 0; i < ctx->packets; ++i) {
214 if (ctx->packet_size[i])
215 counts = ctx->packet_size[i];
216 else if (ep->sync_master)
217 counts = snd_usb_endpoint_slave_next_packet_size(ep);
219 counts = snd_usb_endpoint_next_packet_size(ep);
221 length = counts * ep->stride; /* number of silent bytes */
222 offset = offs * ep->stride + extra * i;
223 urb->iso_frame_desc[i].offset = offset;
224 urb->iso_frame_desc[i].length = length + extra;
226 packet_length = cpu_to_le32(length);
227 memcpy(urb->transfer_buffer + offset,
228 &packet_length, sizeof(packet_length));
230 memset(urb->transfer_buffer + offset + extra,
231 ep->silence_value, length);
235 urb->number_of_packets = ctx->packets;
236 urb->transfer_buffer_length = offs * ep->stride + ctx->packets * extra;
240 * Prepare a PLAYBACK urb for submission to the bus.
242 static void prepare_outbound_urb(struct snd_usb_endpoint *ep,
243 struct snd_urb_ctx *ctx)
245 struct urb *urb = ctx->urb;
246 unsigned char *cp = urb->transfer_buffer;
248 urb->dev = ep->chip->dev; /* we need to set this at each time */
251 case SND_USB_ENDPOINT_TYPE_DATA:
252 if (ep->prepare_data_urb) {
253 ep->prepare_data_urb(ep->data_subs, urb);
255 /* no data provider, so send silence */
256 prepare_silent_urb(ep, ctx);
260 case SND_USB_ENDPOINT_TYPE_SYNC:
261 if (snd_usb_get_speed(ep->chip->dev) >= USB_SPEED_HIGH) {
263 * fill the length and offset of each urb descriptor.
264 * the fixed 12.13 frequency is passed as 16.16 through the pipe.
266 urb->iso_frame_desc[0].length = 4;
267 urb->iso_frame_desc[0].offset = 0;
269 cp[1] = ep->freqn >> 8;
270 cp[2] = ep->freqn >> 16;
271 cp[3] = ep->freqn >> 24;
274 * fill the length and offset of each urb descriptor.
275 * the fixed 10.14 frequency is passed through the pipe.
277 urb->iso_frame_desc[0].length = 3;
278 urb->iso_frame_desc[0].offset = 0;
279 cp[0] = ep->freqn >> 2;
280 cp[1] = ep->freqn >> 10;
281 cp[2] = ep->freqn >> 18;
289 * Prepare a CAPTURE or SYNC urb for submission to the bus.
291 static inline void prepare_inbound_urb(struct snd_usb_endpoint *ep,
292 struct snd_urb_ctx *urb_ctx)
295 struct urb *urb = urb_ctx->urb;
297 urb->dev = ep->chip->dev; /* we need to set this at each time */
300 case SND_USB_ENDPOINT_TYPE_DATA:
302 for (i = 0; i < urb_ctx->packets; i++) {
303 urb->iso_frame_desc[i].offset = offs;
304 urb->iso_frame_desc[i].length = ep->curpacksize;
305 offs += ep->curpacksize;
308 urb->transfer_buffer_length = offs;
309 urb->number_of_packets = urb_ctx->packets;
312 case SND_USB_ENDPOINT_TYPE_SYNC:
313 urb->iso_frame_desc[0].length = min(4u, ep->syncmaxsize);
314 urb->iso_frame_desc[0].offset = 0;
320 * Send output urbs that have been prepared previously. URBs are dequeued
321 * from ep->ready_playback_urbs and in case there aren't any available
322 * or there are no packets that have been prepared, this function does
325 * The reason why the functionality of sending and preparing URBs is separated
326 * is that host controllers don't guarantee the order in which they return
327 * inbound and outbound packets to their submitters.
329 * This function is only used for implicit feedback endpoints. For endpoints
330 * driven by dedicated sync endpoints, URBs are immediately re-submitted
331 * from their completion handler.
333 static void queue_pending_output_urbs(struct snd_usb_endpoint *ep)
335 while (test_bit(EP_FLAG_RUNNING, &ep->flags)) {
338 struct snd_usb_packet_info *packet;
339 struct snd_urb_ctx *ctx = NULL;
342 spin_lock_irqsave(&ep->lock, flags);
343 if (ep->next_packet_read_pos != ep->next_packet_write_pos) {
344 packet = ep->next_packet + ep->next_packet_read_pos;
345 ep->next_packet_read_pos++;
346 ep->next_packet_read_pos %= MAX_URBS;
348 /* take URB out of FIFO */
349 if (!list_empty(&ep->ready_playback_urbs)) {
350 ctx = list_first_entry(&ep->ready_playback_urbs,
351 struct snd_urb_ctx, ready_list);
352 list_del_init(&ctx->ready_list);
355 spin_unlock_irqrestore(&ep->lock, flags);
360 /* copy over the length information */
361 for (i = 0; i < packet->packets; i++)
362 ctx->packet_size[i] = packet->packet_size[i];
364 /* call the data handler to fill in playback data */
365 prepare_outbound_urb(ep, ctx);
367 err = usb_submit_urb(ctx->urb, GFP_ATOMIC);
369 usb_audio_err(ep->chip,
370 "Unable to submit urb #%d: %d at %s\n",
371 ctx->index, err, __func__);
373 set_bit(ctx->index, &ep->active_mask);
378 * complete callback for urbs
380 static void snd_complete_urb(struct urb *urb)
382 struct snd_urb_ctx *ctx = urb->context;
383 struct snd_usb_endpoint *ep = ctx->ep;
384 struct snd_pcm_substream *substream;
388 if (unlikely(urb->status == -ENOENT || /* unlinked */
389 urb->status == -ENODEV || /* device removed */
390 urb->status == -ECONNRESET || /* unlinked */
391 urb->status == -ESHUTDOWN)) /* device disabled */
393 /* device disconnected */
394 if (unlikely(atomic_read(&ep->chip->shutdown)))
397 if (unlikely(!test_bit(EP_FLAG_RUNNING, &ep->flags)))
400 if (usb_pipeout(ep->pipe)) {
401 retire_outbound_urb(ep, ctx);
402 /* can be stopped during retire callback */
403 if (unlikely(!test_bit(EP_FLAG_RUNNING, &ep->flags)))
406 if (snd_usb_endpoint_implicit_feedback_sink(ep)) {
407 spin_lock_irqsave(&ep->lock, flags);
408 list_add_tail(&ctx->ready_list, &ep->ready_playback_urbs);
409 spin_unlock_irqrestore(&ep->lock, flags);
410 queue_pending_output_urbs(ep);
415 prepare_outbound_urb(ep, ctx);
416 /* can be stopped during prepare callback */
417 if (unlikely(!test_bit(EP_FLAG_RUNNING, &ep->flags)))
420 retire_inbound_urb(ep, ctx);
421 /* can be stopped during retire callback */
422 if (unlikely(!test_bit(EP_FLAG_RUNNING, &ep->flags)))
425 prepare_inbound_urb(ep, ctx);
428 err = usb_submit_urb(urb, GFP_ATOMIC);
432 usb_audio_err(ep->chip, "cannot submit urb (err = %d)\n", err);
433 if (ep->data_subs && ep->data_subs->pcm_substream) {
434 substream = ep->data_subs->pcm_substream;
435 snd_pcm_stop_xrun(substream);
439 clear_bit(ctx->index, &ep->active_mask);
443 * Get the existing endpoint object corresponding EP
444 * Returns NULL if not present.
446 struct snd_usb_endpoint *
447 snd_usb_get_endpoint(struct snd_usb_audio *chip, int ep_num)
449 struct snd_usb_endpoint *ep;
451 list_for_each_entry(ep, &chip->ep_list, list) {
452 if (ep->ep_num == ep_num)
459 #define ep_type_name(type) \
460 (type == SND_USB_ENDPOINT_TYPE_DATA ? "data" : "sync")
463 * snd_usb_add_endpoint: Add an endpoint to an USB audio chip
466 * @ep_num: The number of the endpoint to use
467 * @type: SND_USB_ENDPOINT_TYPE_DATA or SND_USB_ENDPOINT_TYPE_SYNC
469 * If the requested endpoint has not been added to the given chip before,
470 * a new instance is created.
472 * Returns zero on success or a negative error code.
474 * New endpoints will be added to chip->ep_list and must be freed by
475 * calling snd_usb_endpoint_free().
477 * For SND_USB_ENDPOINT_TYPE_SYNC, the caller needs to guarantee that
478 * bNumEndpoints > 1 beforehand.
480 int snd_usb_add_endpoint(struct snd_usb_audio *chip, int ep_num, int type)
482 struct snd_usb_endpoint *ep;
485 ep = snd_usb_get_endpoint(chip, ep_num);
489 usb_audio_dbg(chip, "Creating new %s endpoint #%x\n",
492 ep = kzalloc(sizeof(*ep), GFP_KERNEL);
497 spin_lock_init(&ep->lock);
500 INIT_LIST_HEAD(&ep->ready_playback_urbs);
502 is_playback = ((ep_num & USB_ENDPOINT_DIR_MASK) == USB_DIR_OUT);
503 ep_num &= USB_ENDPOINT_NUMBER_MASK;
505 ep->pipe = usb_sndisocpipe(chip->dev, ep_num);
507 ep->pipe = usb_rcvisocpipe(chip->dev, ep_num);
509 list_add_tail(&ep->list, &chip->ep_list);
513 /* Set up syncinterval and maxsyncsize for a sync EP */
514 void snd_usb_endpoint_set_syncinterval(struct snd_usb_audio *chip,
515 struct snd_usb_endpoint *ep,
516 struct usb_host_interface *alts)
518 struct usb_endpoint_descriptor *desc = get_endpoint(alts, 1);
520 if (ep->type == SND_USB_ENDPOINT_TYPE_SYNC) {
521 if (desc->bLength >= USB_DT_ENDPOINT_AUDIO_SIZE &&
522 desc->bRefresh >= 1 && desc->bRefresh <= 9)
523 ep->syncinterval = desc->bRefresh;
524 else if (snd_usb_get_speed(chip->dev) == USB_SPEED_FULL)
525 ep->syncinterval = 1;
526 else if (desc->bInterval >= 1 && desc->bInterval <= 16)
527 ep->syncinterval = desc->bInterval - 1;
529 ep->syncinterval = 3;
531 ep->syncmaxsize = le16_to_cpu(desc->wMaxPacketSize);
536 * wait until all urbs are processed.
538 static int wait_clear_urbs(struct snd_usb_endpoint *ep)
540 unsigned long end_time = jiffies + msecs_to_jiffies(1000);
544 alive = bitmap_weight(&ep->active_mask, ep->nurbs);
548 schedule_timeout_uninterruptible(1);
549 } while (time_before(jiffies, end_time));
552 usb_audio_err(ep->chip,
553 "timeout: still %d active urbs on EP #%x\n",
555 clear_bit(EP_FLAG_STOPPING, &ep->flags);
557 ep->data_subs = NULL;
558 ep->sync_slave = NULL;
559 ep->retire_data_urb = NULL;
560 ep->prepare_data_urb = NULL;
565 /* sync the pending stop operation;
566 * this function itself doesn't trigger the stop operation
568 void snd_usb_endpoint_sync_pending_stop(struct snd_usb_endpoint *ep)
570 if (ep && test_bit(EP_FLAG_STOPPING, &ep->flags))
575 * unlink active urbs.
577 static int deactivate_urbs(struct snd_usb_endpoint *ep, bool force)
581 if (!force && atomic_read(&ep->chip->shutdown)) /* to be sure... */
584 clear_bit(EP_FLAG_RUNNING, &ep->flags);
586 INIT_LIST_HEAD(&ep->ready_playback_urbs);
587 ep->next_packet_read_pos = 0;
588 ep->next_packet_write_pos = 0;
590 for (i = 0; i < ep->nurbs; i++) {
591 if (test_bit(i, &ep->active_mask)) {
592 if (!test_and_set_bit(i, &ep->unlink_mask)) {
593 struct urb *u = ep->urb[i].urb;
603 * release an endpoint's urbs
605 static void release_urbs(struct snd_usb_endpoint *ep, int force)
609 /* route incoming urbs to nirvana */
610 ep->retire_data_urb = NULL;
611 ep->prepare_data_urb = NULL;
614 deactivate_urbs(ep, force);
617 for (i = 0; i < ep->nurbs; i++)
618 release_urb_ctx(&ep->urb[i]);
620 usb_free_coherent(ep->chip->dev, SYNC_URBS * 4,
621 ep->syncbuf, ep->sync_dma);
628 * Check data endpoint for format differences
630 static bool check_ep_params(struct snd_usb_endpoint *ep,
631 snd_pcm_format_t pcm_format,
632 unsigned int channels,
633 unsigned int period_bytes,
634 unsigned int frames_per_period,
635 unsigned int periods_per_buffer,
637 struct audioformat *fmt,
638 struct snd_usb_endpoint *sync_ep)
640 unsigned int maxsize, minsize, packs_per_ms, max_packs_per_urb;
641 unsigned int max_packs_per_period, urbs_per_period, urb_packs;
642 unsigned int max_urbs;
643 int frame_bits = snd_pcm_format_physical_width(pcm_format) * channels;
644 int tx_length_quirk = (ep->chip->tx_length_quirk &&
645 usb_pipeout(ep->pipe));
648 /* matching with the saved parameters? */
649 if (ep->cur_rate == rate &&
650 ep->cur_format == pcm_format &&
651 ep->cur_channels == channels &&
652 ep->cur_period_frames == frames_per_period &&
653 ep->cur_buffer_periods == periods_per_buffer)
656 if (pcm_format == SNDRV_PCM_FORMAT_DSD_U16_LE && fmt->dsd_dop) {
658 * When operating in DSD DOP mode, the size of a sample frame
659 * in hardware differs from the actual physical format width
660 * because we need to make room for the DOP markers.
662 frame_bits += channels << 3;
665 ret = ret && (ep->datainterval == fmt->datainterval);
666 ret = ret && (ep->stride == frame_bits >> 3);
668 switch (pcm_format) {
669 case SNDRV_PCM_FORMAT_U8:
670 ret = ret && (ep->silence_value == 0x80);
672 case SNDRV_PCM_FORMAT_DSD_U8:
673 case SNDRV_PCM_FORMAT_DSD_U16_LE:
674 case SNDRV_PCM_FORMAT_DSD_U32_LE:
675 case SNDRV_PCM_FORMAT_DSD_U16_BE:
676 case SNDRV_PCM_FORMAT_DSD_U32_BE:
677 ret = ret && (ep->silence_value == 0x69);
680 ret = ret && (ep->silence_value == 0);
683 /* assume max. frequency is 50% higher than nominal */
684 ret = ret && (ep->freqmax == ep->freqn + (ep->freqn >> 1));
685 /* Round up freqmax to nearest integer in order to calculate maximum
686 * packet size, which must represent a whole number of frames.
687 * This is accomplished by adding 0x0.ffff before converting the
688 * Q16.16 format into integer.
689 * In order to accurately calculate the maximum packet size when
690 * the data interval is more than 1 (i.e. ep->datainterval > 0),
691 * multiply by the data interval prior to rounding. For instance,
692 * a freqmax of 41 kHz will result in a max packet size of 6 (5.125)
693 * frames with a data interval of 1, but 11 (10.25) frames with a
694 * data interval of 2.
695 * (ep->freqmax << ep->datainterval overflows at 8.192 MHz for the
696 * maximum datainterval value of 3, at USB full speed, higher for
697 * USB high speed, noting that ep->freqmax is in units of
698 * frames per packet in Q16.16 format.)
700 maxsize = (((ep->freqmax << ep->datainterval) + 0xffff) >> 16) *
703 maxsize += sizeof(__le32); /* Space for length descriptor */
704 /* but wMaxPacketSize might reduce this */
705 if (ep->maxpacksize && ep->maxpacksize < maxsize) {
706 /* whatever fits into a max. size packet */
707 unsigned int data_maxsize = maxsize = ep->maxpacksize;
710 /* Need to remove the length descriptor to calc freq */
711 data_maxsize -= sizeof(__le32);
712 ret = ret && (ep->freqmax == (data_maxsize / (frame_bits >> 3))
713 << (16 - ep->datainterval));
717 ret = ret && (ep->curpacksize == ep->maxpacksize);
719 ret = ret && (ep->curpacksize == maxsize);
721 if (snd_usb_get_speed(ep->chip->dev) != USB_SPEED_FULL) {
722 packs_per_ms = 8 >> ep->datainterval;
723 max_packs_per_urb = MAX_PACKS_HS;
726 max_packs_per_urb = MAX_PACKS;
728 if (sync_ep && !snd_usb_endpoint_implicit_feedback_sink(ep))
729 max_packs_per_urb = min(max_packs_per_urb,
730 1U << sync_ep->syncinterval);
731 max_packs_per_urb = max(1u, max_packs_per_urb >> ep->datainterval);
734 * Capture endpoints need to use small URBs because there's no way
735 * to tell in advance where the next period will end, and we don't
736 * want the next URB to complete much after the period ends.
738 * Playback endpoints with implicit sync much use the same parameters
739 * as their corresponding capture endpoint.
741 if (usb_pipein(ep->pipe) ||
742 snd_usb_endpoint_implicit_feedback_sink(ep)) {
744 urb_packs = packs_per_ms;
746 * Wireless devices can poll at a max rate of once per 4ms.
747 * For dataintervals less than 5, increase the packet count to
748 * allow the host controller to use bursting to fill in the
751 if (snd_usb_get_speed(ep->chip->dev) == USB_SPEED_WIRELESS) {
752 int interval = ep->datainterval;
754 while (interval < 5) {
759 /* make capture URBs <= 1 ms and smaller than a period */
760 urb_packs = min(max_packs_per_urb, urb_packs);
761 while (urb_packs > 1 && urb_packs * maxsize >= period_bytes)
763 ret = ret && (ep->nurbs == MAX_URBS);
766 * Playback endpoints without implicit sync are adjusted so that
767 * a period fits as evenly as possible in the smallest number of
768 * URBs. The total number of URBs is adjusted to the size of the
769 * ALSA buffer, subject to the MAX_URBS and MAX_QUEUE limits.
772 /* determine how small a packet can be */
773 minsize = (ep->freqn >> (16 - ep->datainterval)) *
775 /* with sync from device, assume it can be 12% lower */
777 minsize -= minsize >> 3;
778 minsize = max(minsize, 1u);
780 /* how many packets will contain an entire ALSA period? */
781 max_packs_per_period = DIV_ROUND_UP(period_bytes, minsize);
783 /* how many URBs will contain a period? */
784 urbs_per_period = DIV_ROUND_UP(max_packs_per_period,
786 /* how many packets are needed in each URB? */
787 urb_packs = DIV_ROUND_UP(max_packs_per_period, urbs_per_period);
789 /* limit the number of frames in a single URB */
790 ret = ret && (ep->max_urb_frames ==
791 DIV_ROUND_UP(frames_per_period, urbs_per_period));
793 /* try to use enough URBs to contain an entire ALSA buffer */
794 max_urbs = min((unsigned) MAX_URBS,
795 MAX_QUEUE * packs_per_ms / urb_packs);
796 ret = ret && (ep->nurbs == min(max_urbs,
797 urbs_per_period * periods_per_buffer));
800 ret = ret && (ep->datainterval == fmt->datainterval);
801 ret = ret && (ep->maxpacksize == fmt->maxpacksize);
803 (ep->fill_max == !!(fmt->attributes & UAC_EP_CS_ATTR_FILL_MAX));
809 * configure a data endpoint
811 static int data_ep_set_params(struct snd_usb_endpoint *ep,
812 snd_pcm_format_t pcm_format,
813 unsigned int channels,
814 unsigned int period_bytes,
815 unsigned int frames_per_period,
816 unsigned int periods_per_buffer,
817 struct audioformat *fmt,
818 struct snd_usb_endpoint *sync_ep)
820 unsigned int maxsize, minsize, packs_per_ms, max_packs_per_urb;
821 unsigned int max_packs_per_period, urbs_per_period, urb_packs;
822 unsigned int max_urbs, i;
823 int frame_bits = snd_pcm_format_physical_width(pcm_format) * channels;
824 int tx_length_quirk = (ep->chip->tx_length_quirk &&
825 usb_pipeout(ep->pipe));
827 if (pcm_format == SNDRV_PCM_FORMAT_DSD_U16_LE && fmt->dsd_dop) {
829 * When operating in DSD DOP mode, the size of a sample frame
830 * in hardware differs from the actual physical format width
831 * because we need to make room for the DOP markers.
833 frame_bits += channels << 3;
836 ep->datainterval = fmt->datainterval;
837 ep->stride = frame_bits >> 3;
839 switch (pcm_format) {
840 case SNDRV_PCM_FORMAT_U8:
841 ep->silence_value = 0x80;
843 case SNDRV_PCM_FORMAT_DSD_U8:
844 case SNDRV_PCM_FORMAT_DSD_U16_LE:
845 case SNDRV_PCM_FORMAT_DSD_U32_LE:
846 case SNDRV_PCM_FORMAT_DSD_U16_BE:
847 case SNDRV_PCM_FORMAT_DSD_U32_BE:
848 ep->silence_value = 0x69;
851 ep->silence_value = 0;
854 /* assume max. frequency is 50% higher than nominal */
855 ep->freqmax = ep->freqn + (ep->freqn >> 1);
856 /* Round up freqmax to nearest integer in order to calculate maximum
857 * packet size, which must represent a whole number of frames.
858 * This is accomplished by adding 0x0.ffff before converting the
859 * Q16.16 format into integer.
860 * In order to accurately calculate the maximum packet size when
861 * the data interval is more than 1 (i.e. ep->datainterval > 0),
862 * multiply by the data interval prior to rounding. For instance,
863 * a freqmax of 41 kHz will result in a max packet size of 6 (5.125)
864 * frames with a data interval of 1, but 11 (10.25) frames with a
865 * data interval of 2.
866 * (ep->freqmax << ep->datainterval overflows at 8.192 MHz for the
867 * maximum datainterval value of 3, at USB full speed, higher for
868 * USB high speed, noting that ep->freqmax is in units of
869 * frames per packet in Q16.16 format.)
871 maxsize = (((ep->freqmax << ep->datainterval) + 0xffff) >> 16) *
874 maxsize += sizeof(__le32); /* Space for length descriptor */
875 /* but wMaxPacketSize might reduce this */
876 if (ep->maxpacksize && ep->maxpacksize < maxsize) {
877 /* whatever fits into a max. size packet */
878 unsigned int data_maxsize = maxsize = ep->maxpacksize;
881 /* Need to remove the length descriptor to calc freq */
882 data_maxsize -= sizeof(__le32);
883 ep->freqmax = (data_maxsize / (frame_bits >> 3))
884 << (16 - ep->datainterval);
888 ep->curpacksize = ep->maxpacksize;
890 ep->curpacksize = maxsize;
892 if (snd_usb_get_speed(ep->chip->dev) != USB_SPEED_FULL) {
893 packs_per_ms = 8 >> ep->datainterval;
894 max_packs_per_urb = MAX_PACKS_HS;
897 max_packs_per_urb = MAX_PACKS;
899 if (sync_ep && !snd_usb_endpoint_implicit_feedback_sink(ep))
900 max_packs_per_urb = min(max_packs_per_urb,
901 1U << sync_ep->syncinterval);
902 max_packs_per_urb = max(1u, max_packs_per_urb >> ep->datainterval);
905 * Capture endpoints need to use small URBs because there's no way
906 * to tell in advance where the next period will end, and we don't
907 * want the next URB to complete much after the period ends.
909 * Playback endpoints with implicit sync much use the same parameters
910 * as their corresponding capture endpoint.
912 if (usb_pipein(ep->pipe) ||
913 ep->is_implicit_feedback ||
914 snd_usb_endpoint_implicit_feedback_sink(ep)) {
916 urb_packs = packs_per_ms;
918 * Wireless devices can poll at a max rate of once per 4ms.
919 * For dataintervals less than 5, increase the packet count to
920 * allow the host controller to use bursting to fill in the
923 if (snd_usb_get_speed(ep->chip->dev) == USB_SPEED_WIRELESS) {
924 int interval = ep->datainterval;
925 while (interval < 5) {
930 /* make capture URBs <= 1 ms and smaller than a period */
931 urb_packs = min(max_packs_per_urb, urb_packs);
932 while (urb_packs > 1 && urb_packs * maxsize >= period_bytes)
934 ep->nurbs = MAX_URBS;
937 * Playback endpoints without implicit sync are adjusted so that
938 * a period fits as evenly as possible in the smallest number of
939 * URBs. The total number of URBs is adjusted to the size of the
940 * ALSA buffer, subject to the MAX_URBS and MAX_QUEUE limits.
943 /* determine how small a packet can be */
944 minsize = (ep->freqn >> (16 - ep->datainterval)) *
946 /* with sync from device, assume it can be 12% lower */
948 minsize -= minsize >> 3;
949 minsize = max(minsize, 1u);
951 /* how many packets will contain an entire ALSA period? */
952 max_packs_per_period = DIV_ROUND_UP(period_bytes, minsize);
954 /* how many URBs will contain a period? */
955 urbs_per_period = DIV_ROUND_UP(max_packs_per_period,
957 /* how many packets are needed in each URB? */
958 urb_packs = DIV_ROUND_UP(max_packs_per_period, urbs_per_period);
960 /* limit the number of frames in a single URB */
961 ep->max_urb_frames = DIV_ROUND_UP(frames_per_period,
964 /* try to use enough URBs to contain an entire ALSA buffer */
965 max_urbs = min((unsigned) MAX_URBS,
966 MAX_QUEUE * packs_per_ms / urb_packs);
967 ep->nurbs = min(max_urbs, urbs_per_period * periods_per_buffer);
970 /* allocate and initialize data urbs */
971 for (i = 0; i < ep->nurbs; i++) {
972 struct snd_urb_ctx *u = &ep->urb[i];
975 u->packets = urb_packs;
976 u->buffer_size = maxsize * u->packets;
978 if (fmt->fmt_type == UAC_FORMAT_TYPE_II)
979 u->packets++; /* for transfer delimiter */
980 u->urb = usb_alloc_urb(u->packets, GFP_KERNEL);
984 u->urb->transfer_buffer =
985 usb_alloc_coherent(ep->chip->dev, u->buffer_size,
986 GFP_KERNEL, &u->urb->transfer_dma);
987 if (!u->urb->transfer_buffer)
989 u->urb->pipe = ep->pipe;
990 u->urb->transfer_flags = URB_NO_TRANSFER_DMA_MAP;
991 u->urb->interval = 1 << ep->datainterval;
993 u->urb->complete = snd_complete_urb;
994 INIT_LIST_HEAD(&u->ready_list);
1000 release_urbs(ep, 0);
1005 * configure a sync endpoint
1007 static int sync_ep_set_params(struct snd_usb_endpoint *ep)
1011 ep->syncbuf = usb_alloc_coherent(ep->chip->dev, SYNC_URBS * 4,
1012 GFP_KERNEL, &ep->sync_dma);
1016 for (i = 0; i < SYNC_URBS; i++) {
1017 struct snd_urb_ctx *u = &ep->urb[i];
1021 u->urb = usb_alloc_urb(1, GFP_KERNEL);
1024 u->urb->transfer_buffer = ep->syncbuf + i * 4;
1025 u->urb->transfer_dma = ep->sync_dma + i * 4;
1026 u->urb->transfer_buffer_length = 4;
1027 u->urb->pipe = ep->pipe;
1028 u->urb->transfer_flags = URB_NO_TRANSFER_DMA_MAP;
1029 u->urb->number_of_packets = 1;
1030 u->urb->interval = 1 << ep->syncinterval;
1031 u->urb->context = u;
1032 u->urb->complete = snd_complete_urb;
1035 ep->nurbs = SYNC_URBS;
1040 release_urbs(ep, 0);
1045 * snd_usb_endpoint_set_params: configure an snd_usb_endpoint
1047 * @ep: the snd_usb_endpoint to configure
1048 * @pcm_format: the audio fomat.
1049 * @channels: the number of audio channels.
1050 * @period_bytes: the number of bytes in one alsa period.
1051 * @period_frames: the number of frames in one alsa period.
1052 * @buffer_periods: the number of periods in one alsa buffer.
1053 * @rate: the frame rate.
1054 * @fmt: the USB audio format information
1055 * @sync_ep: the sync endpoint to use, if any
1057 * Determine the number of URBs to be used on this endpoint.
1058 * An endpoint must be configured before it can be started.
1059 * An endpoint that is already running can not be reconfigured.
1061 int snd_usb_endpoint_set_params(struct snd_usb_endpoint *ep,
1062 snd_pcm_format_t pcm_format,
1063 unsigned int channels,
1064 unsigned int period_bytes,
1065 unsigned int period_frames,
1066 unsigned int buffer_periods,
1068 struct audioformat *fmt,
1069 struct snd_usb_endpoint *sync_ep)
1073 usb_audio_dbg(ep->chip,
1074 "Setting params for ep %x (type %s, count %d), rate=%d, format=%s, channels=%d, period_bytes=%d, periods=%d\n",
1075 ep->ep_num, ep_type_name(ep->type), ep->use_count,
1076 rate, snd_pcm_format_name(pcm_format), channels,
1077 period_bytes, buffer_periods);
1079 if (ep->use_count != 0) {
1080 bool check = ep->is_implicit_feedback &&
1081 check_ep_params(ep, pcm_format, channels, period_bytes,
1082 period_frames, buffer_periods, rate,
1086 usb_audio_warn(ep->chip,
1087 "Unable to change format on ep #%x: already in use\n",
1092 usb_audio_dbg(ep->chip,
1093 "Ep #%x already in use as implicit feedback but format not changed\n",
1098 /* release old buffers, if any */
1099 release_urbs(ep, 0);
1101 ep->datainterval = fmt->datainterval;
1102 ep->maxpacksize = fmt->maxpacksize;
1103 ep->fill_max = !!(fmt->attributes & UAC_EP_CS_ATTR_FILL_MAX);
1105 if (snd_usb_get_speed(ep->chip->dev) == USB_SPEED_FULL) {
1106 ep->freqn = get_usb_full_speed_rate(rate);
1107 ep->pps = 1000 >> ep->datainterval;
1109 ep->freqn = get_usb_high_speed_rate(rate);
1110 ep->pps = 8000 >> ep->datainterval;
1113 ep->sample_rem = rate % ep->pps;
1114 ep->packsize[0] = rate / ep->pps;
1115 ep->packsize[1] = (rate + (ep->pps - 1)) / ep->pps;
1117 /* calculate the frequency in 16.16 format */
1118 ep->freqm = ep->freqn;
1119 ep->freqshift = INT_MIN;
1124 case SND_USB_ENDPOINT_TYPE_DATA:
1125 err = data_ep_set_params(ep, pcm_format, channels,
1126 period_bytes, period_frames,
1127 buffer_periods, fmt, sync_ep);
1129 case SND_USB_ENDPOINT_TYPE_SYNC:
1130 err = sync_ep_set_params(ep);
1136 usb_audio_dbg(ep->chip, "Set up %d URBS, ret=%d\n", ep->nurbs, err);
1141 /* record the current set up in the endpoint (for implicit fb) */
1142 spin_lock_irq(&ep->lock);
1143 ep->cur_rate = rate;
1144 ep->cur_channels = channels;
1145 ep->cur_format = pcm_format;
1146 ep->cur_period_frames = period_frames;
1147 ep->cur_period_bytes = period_bytes;
1148 ep->cur_buffer_periods = buffer_periods;
1149 spin_unlock_irq(&ep->lock);
1155 * snd_usb_endpoint_start: start an snd_usb_endpoint
1157 * @ep: the endpoint to start
1159 * A call to this function will increment the use count of the endpoint.
1160 * In case it is not already running, the URBs for this endpoint will be
1161 * submitted. Otherwise, this function does nothing.
1163 * Must be balanced to calls of snd_usb_endpoint_stop().
1165 * Returns an error if the URB submission failed, 0 in all other cases.
1167 int snd_usb_endpoint_start(struct snd_usb_endpoint *ep)
1172 if (atomic_read(&ep->chip->shutdown))
1175 /* already running? */
1176 if (++ep->use_count != 1)
1179 /* just to be sure */
1180 deactivate_urbs(ep, false);
1182 ep->active_mask = 0;
1183 ep->unlink_mask = 0;
1185 ep->sample_accum = 0;
1187 snd_usb_endpoint_start_quirk(ep);
1190 * If this endpoint has a data endpoint as implicit feedback source,
1191 * don't start the urbs here. Instead, mark them all as available,
1192 * wait for the record urbs to return and queue the playback urbs
1193 * from that context.
1196 set_bit(EP_FLAG_RUNNING, &ep->flags);
1198 if (snd_usb_endpoint_implicit_feedback_sink(ep)) {
1199 for (i = 0; i < ep->nurbs; i++) {
1200 struct snd_urb_ctx *ctx = ep->urb + i;
1201 list_add_tail(&ctx->ready_list, &ep->ready_playback_urbs);
1207 for (i = 0; i < ep->nurbs; i++) {
1208 struct urb *urb = ep->urb[i].urb;
1210 if (snd_BUG_ON(!urb))
1213 if (usb_pipeout(ep->pipe)) {
1214 prepare_outbound_urb(ep, urb->context);
1216 prepare_inbound_urb(ep, urb->context);
1219 err = usb_submit_urb(urb, GFP_ATOMIC);
1221 usb_audio_err(ep->chip,
1222 "cannot submit urb %d, error %d: %s\n",
1223 i, err, usb_error_string(err));
1226 set_bit(i, &ep->active_mask);
1232 clear_bit(EP_FLAG_RUNNING, &ep->flags);
1234 deactivate_urbs(ep, false);
1239 * snd_usb_endpoint_stop: stop an snd_usb_endpoint
1241 * @ep: the endpoint to stop (may be NULL)
1243 * A call to this function will decrement the use count of the endpoint.
1244 * In case the last user has requested the endpoint stop, the URBs will
1245 * actually be deactivated.
1247 * Must be balanced to calls of snd_usb_endpoint_start().
1249 * The caller needs to synchronize the pending stop operation via
1250 * snd_usb_endpoint_sync_pending_stop().
1252 void snd_usb_endpoint_stop(struct snd_usb_endpoint *ep)
1257 if (snd_BUG_ON(ep->use_count == 0))
1260 if (--ep->use_count == 0) {
1261 deactivate_urbs(ep, false);
1262 set_bit(EP_FLAG_STOPPING, &ep->flags);
1267 * snd_usb_endpoint_deactivate: deactivate an snd_usb_endpoint
1269 * @ep: the endpoint to deactivate
1271 * If the endpoint is not currently in use, this functions will
1272 * deactivate its associated URBs.
1274 * In case of any active users, this functions does nothing.
1276 void snd_usb_endpoint_deactivate(struct snd_usb_endpoint *ep)
1281 if (ep->use_count != 0)
1284 deactivate_urbs(ep, true);
1285 wait_clear_urbs(ep);
1287 /* clear the saved hw params */
1288 spin_lock_irq(&ep->lock);
1290 spin_unlock_irq(&ep->lock);
1294 * snd_usb_endpoint_release: Tear down an snd_usb_endpoint
1296 * @ep: the endpoint to release
1298 * This function does not care for the endpoint's use count but will tear
1299 * down all the streaming URBs immediately.
1301 void snd_usb_endpoint_release(struct snd_usb_endpoint *ep)
1303 release_urbs(ep, 1);
1307 * snd_usb_endpoint_free: Free the resources of an snd_usb_endpoint
1309 * @ep: the endpoint to free
1311 * This free all resources of the given ep.
1313 void snd_usb_endpoint_free(struct snd_usb_endpoint *ep)
1319 * snd_usb_handle_sync_urb: parse an USB sync packet
1321 * @ep: the endpoint to handle the packet
1322 * @sender: the sending endpoint
1323 * @urb: the received packet
1325 * This function is called from the context of an endpoint that received
1326 * the packet and is used to let another endpoint object handle the payload.
1328 void snd_usb_handle_sync_urb(struct snd_usb_endpoint *ep,
1329 struct snd_usb_endpoint *sender,
1330 const struct urb *urb)
1334 unsigned long flags;
1336 snd_BUG_ON(ep == sender);
1339 * In case the endpoint is operating in implicit feedback mode, prepare
1340 * a new outbound URB that has the same layout as the received packet
1341 * and add it to the list of pending urbs. queue_pending_output_urbs()
1342 * will take care of them later.
1344 if (snd_usb_endpoint_implicit_feedback_sink(ep) &&
1345 ep->use_count != 0) {
1347 /* implicit feedback case */
1349 struct snd_urb_ctx *in_ctx;
1350 struct snd_usb_packet_info *out_packet;
1352 in_ctx = urb->context;
1354 /* Count overall packet size */
1355 for (i = 0; i < in_ctx->packets; i++)
1356 if (urb->iso_frame_desc[i].status == 0)
1357 bytes += urb->iso_frame_desc[i].actual_length;
1360 * skip empty packets. At least M-Audio's Fast Track Ultra stops
1361 * streaming once it received a 0-byte OUT URB
1366 spin_lock_irqsave(&ep->lock, flags);
1367 out_packet = ep->next_packet + ep->next_packet_write_pos;
1370 * Iterate through the inbound packet and prepare the lengths
1371 * for the output packet. The OUT packet we are about to send
1372 * will have the same amount of payload bytes per stride as the
1373 * IN packet we just received. Since the actual size is scaled
1374 * by the stride, use the sender stride to calculate the length
1375 * in case the number of channels differ between the implicitly
1376 * fed-back endpoint and the synchronizing endpoint.
1379 out_packet->packets = in_ctx->packets;
1380 for (i = 0; i < in_ctx->packets; i++) {
1381 if (urb->iso_frame_desc[i].status == 0)
1382 out_packet->packet_size[i] =
1383 urb->iso_frame_desc[i].actual_length / sender->stride;
1385 out_packet->packet_size[i] = 0;
1388 ep->next_packet_write_pos++;
1389 ep->next_packet_write_pos %= MAX_URBS;
1390 spin_unlock_irqrestore(&ep->lock, flags);
1391 queue_pending_output_urbs(ep);
1397 * process after playback sync complete
1399 * Full speed devices report feedback values in 10.14 format as samples
1400 * per frame, high speed devices in 16.16 format as samples per
1403 * Because the Audio Class 1 spec was written before USB 2.0, many high
1404 * speed devices use a wrong interpretation, some others use an
1405 * entirely different format.
1407 * Therefore, we cannot predict what format any particular device uses
1408 * and must detect it automatically.
1411 if (urb->iso_frame_desc[0].status != 0 ||
1412 urb->iso_frame_desc[0].actual_length < 3)
1415 f = le32_to_cpup(urb->transfer_buffer);
1416 if (urb->iso_frame_desc[0].actual_length == 3)
1424 if (unlikely(sender->tenor_fb_quirk)) {
1426 * Devices based on Tenor 8802 chipsets (TEAC UD-H01
1427 * and others) sometimes change the feedback value
1430 if (f < ep->freqn - 0x8000)
1432 else if (f > ep->freqn + 0x8000)
1434 } else if (unlikely(ep->freqshift == INT_MIN)) {
1436 * The first time we see a feedback value, determine its format
1437 * by shifting it left or right until it matches the nominal
1438 * frequency value. This assumes that the feedback does not
1439 * differ from the nominal value more than +50% or -25%.
1442 while (f < ep->freqn - ep->freqn / 4) {
1446 while (f > ep->freqn + ep->freqn / 2) {
1450 ep->freqshift = shift;
1451 } else if (ep->freqshift >= 0)
1452 f <<= ep->freqshift;
1454 f >>= -ep->freqshift;
1456 if (likely(f >= ep->freqn - ep->freqn / 8 && f <= ep->freqmax)) {
1458 * If the frequency looks valid, set it.
1459 * This value is referred to in prepare_playback_urb().
1461 spin_lock_irqsave(&ep->lock, flags);
1463 spin_unlock_irqrestore(&ep->lock, flags);
1466 * Out of range; maybe the shift value is wrong.
1467 * Reset it so that we autodetect again the next time.
1469 ep->freqshift = INT_MIN;