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>
24 #define EP_FLAG_RUNNING 1
25 #define EP_FLAG_STOPPING 2
28 * snd_usb_endpoint is a model that abstracts everything related to an
29 * USB endpoint and its streaming.
31 * There are functions to activate and deactivate the streaming URBs and
32 * optional callbacks to let the pcm logic handle the actual content of the
33 * packets for playback and record. Thus, the bus streaming and the audio
34 * handlers are fully decoupled.
36 * There are two different types of endpoints in audio applications.
38 * SND_USB_ENDPOINT_TYPE_DATA handles full audio data payload for both
39 * inbound and outbound traffic.
41 * SND_USB_ENDPOINT_TYPE_SYNC endpoints are for inbound traffic only and
42 * expect the payload to carry Q10.14 / Q16.16 formatted sync information
45 * Each endpoint has to be configured prior to being used by calling
46 * snd_usb_endpoint_set_params().
48 * The model incorporates a reference counting, so that multiple users
49 * can call snd_usb_endpoint_start() and snd_usb_endpoint_stop(), and
50 * only the first user will effectively start the URBs, and only the last
51 * one to stop it will tear the URBs down again.
55 * convert a sampling rate into our full speed format (fs/1000 in Q16.16)
56 * this will overflow at approx 524 kHz
58 static inline unsigned get_usb_full_speed_rate(unsigned int rate)
60 return ((rate << 13) + 62) / 125;
64 * convert a sampling rate into USB high speed format (fs/8000 in Q16.16)
65 * this will overflow at approx 4 MHz
67 static inline unsigned get_usb_high_speed_rate(unsigned int rate)
69 return ((rate << 10) + 62) / 125;
75 static void release_urb_ctx(struct snd_urb_ctx *u)
78 usb_free_coherent(u->ep->chip->dev, u->buffer_size,
79 u->urb->transfer_buffer,
80 u->urb->transfer_dma);
85 static const char *usb_error_string(int err)
91 return "endpoint not enabled";
93 return "endpoint stalled";
95 return "not enough bandwidth";
97 return "device disabled";
99 return "device suspended";
104 return "internal error";
106 return "unknown error";
111 * snd_usb_endpoint_implicit_feedback_sink: Report endpoint usage type
113 * @ep: The snd_usb_endpoint
115 * Determine whether an endpoint is driven by an implicit feedback
116 * data endpoint source.
118 int snd_usb_endpoint_implicit_feedback_sink(struct snd_usb_endpoint *ep)
120 return ep->implicit_fb_sync && usb_pipeout(ep->pipe);
124 * For streaming based on information derived from sync endpoints,
125 * prepare_outbound_urb_sizes() will call slave_next_packet_size() to
126 * determine the number of samples to be sent in the next packet.
128 * For implicit feedback, slave_next_packet_size() is unused.
130 int snd_usb_endpoint_slave_next_packet_size(struct snd_usb_endpoint *ep)
136 return ep->maxframesize;
138 spin_lock_irqsave(&ep->lock, flags);
139 ep->phase = (ep->phase & 0xffff)
140 + (ep->freqm << ep->datainterval);
141 ret = min(ep->phase >> 16, ep->maxframesize);
142 spin_unlock_irqrestore(&ep->lock, flags);
148 * For adaptive and synchronous endpoints, prepare_outbound_urb_sizes()
149 * will call next_packet_size() to determine the number of samples to be
150 * sent in the next packet.
152 int snd_usb_endpoint_next_packet_size(struct snd_usb_endpoint *ep)
157 return ep->maxframesize;
159 ep->sample_accum += ep->sample_rem;
160 if (ep->sample_accum >= ep->pps) {
161 ep->sample_accum -= ep->pps;
162 ret = ep->packsize[1];
164 ret = ep->packsize[0];
170 static void call_retire_callback(struct snd_usb_endpoint *ep,
173 struct snd_usb_substream *data_subs;
175 data_subs = READ_ONCE(ep->data_subs);
176 if (data_subs && ep->retire_data_urb)
177 ep->retire_data_urb(data_subs, urb);
180 static void retire_outbound_urb(struct snd_usb_endpoint *ep,
181 struct snd_urb_ctx *urb_ctx)
183 call_retire_callback(ep, urb_ctx->urb);
186 static void snd_usb_handle_sync_urb(struct snd_usb_endpoint *ep,
187 struct snd_usb_endpoint *sender,
188 const struct urb *urb);
190 static void retire_inbound_urb(struct snd_usb_endpoint *ep,
191 struct snd_urb_ctx *urb_ctx)
193 struct urb *urb = urb_ctx->urb;
194 struct snd_usb_endpoint *sync_slave;
196 if (unlikely(ep->skip_packets > 0)) {
201 sync_slave = READ_ONCE(ep->sync_slave);
203 snd_usb_handle_sync_urb(sync_slave, ep, urb);
205 call_retire_callback(ep, urb);
208 static void prepare_silent_urb(struct snd_usb_endpoint *ep,
209 struct snd_urb_ctx *ctx)
211 struct urb *urb = ctx->urb;
212 unsigned int offs = 0;
213 unsigned int extra = 0;
214 __le32 packet_length;
217 /* For tx_length_quirk, put packet length at start of packet */
218 if (ep->chip->tx_length_quirk)
219 extra = sizeof(packet_length);
221 for (i = 0; i < ctx->packets; ++i) {
226 if (ctx->packet_size[i])
227 counts = ctx->packet_size[i];
228 else if (ep->sync_master)
229 counts = snd_usb_endpoint_slave_next_packet_size(ep);
231 counts = snd_usb_endpoint_next_packet_size(ep);
233 length = counts * ep->stride; /* number of silent bytes */
234 offset = offs * ep->stride + extra * i;
235 urb->iso_frame_desc[i].offset = offset;
236 urb->iso_frame_desc[i].length = length + extra;
238 packet_length = cpu_to_le32(length);
239 memcpy(urb->transfer_buffer + offset,
240 &packet_length, sizeof(packet_length));
242 memset(urb->transfer_buffer + offset + extra,
243 ep->silence_value, length);
247 urb->number_of_packets = ctx->packets;
248 urb->transfer_buffer_length = offs * ep->stride + ctx->packets * extra;
252 * Prepare a PLAYBACK urb for submission to the bus.
254 static void prepare_outbound_urb(struct snd_usb_endpoint *ep,
255 struct snd_urb_ctx *ctx)
257 struct urb *urb = ctx->urb;
258 unsigned char *cp = urb->transfer_buffer;
259 struct snd_usb_substream *data_subs;
261 urb->dev = ep->chip->dev; /* we need to set this at each time */
264 case SND_USB_ENDPOINT_TYPE_DATA:
265 data_subs = READ_ONCE(ep->data_subs);
266 if (data_subs && ep->prepare_data_urb)
267 ep->prepare_data_urb(data_subs, urb);
268 else /* no data provider, so send silence */
269 prepare_silent_urb(ep, ctx);
272 case SND_USB_ENDPOINT_TYPE_SYNC:
273 if (snd_usb_get_speed(ep->chip->dev) >= USB_SPEED_HIGH) {
275 * fill the length and offset of each urb descriptor.
276 * the fixed 12.13 frequency is passed as 16.16 through the pipe.
278 urb->iso_frame_desc[0].length = 4;
279 urb->iso_frame_desc[0].offset = 0;
281 cp[1] = ep->freqn >> 8;
282 cp[2] = ep->freqn >> 16;
283 cp[3] = ep->freqn >> 24;
286 * fill the length and offset of each urb descriptor.
287 * the fixed 10.14 frequency is passed through the pipe.
289 urb->iso_frame_desc[0].length = 3;
290 urb->iso_frame_desc[0].offset = 0;
291 cp[0] = ep->freqn >> 2;
292 cp[1] = ep->freqn >> 10;
293 cp[2] = ep->freqn >> 18;
301 * Prepare a CAPTURE or SYNC urb for submission to the bus.
303 static inline void prepare_inbound_urb(struct snd_usb_endpoint *ep,
304 struct snd_urb_ctx *urb_ctx)
307 struct urb *urb = urb_ctx->urb;
309 urb->dev = ep->chip->dev; /* we need to set this at each time */
312 case SND_USB_ENDPOINT_TYPE_DATA:
314 for (i = 0; i < urb_ctx->packets; i++) {
315 urb->iso_frame_desc[i].offset = offs;
316 urb->iso_frame_desc[i].length = ep->curpacksize;
317 offs += ep->curpacksize;
320 urb->transfer_buffer_length = offs;
321 urb->number_of_packets = urb_ctx->packets;
324 case SND_USB_ENDPOINT_TYPE_SYNC:
325 urb->iso_frame_desc[0].length = min(4u, ep->syncmaxsize);
326 urb->iso_frame_desc[0].offset = 0;
331 /* notify an error as XRUN to the assigned PCM data substream */
332 static void notify_xrun(struct snd_usb_endpoint *ep)
334 struct snd_usb_substream *data_subs;
336 data_subs = READ_ONCE(ep->data_subs);
337 if (data_subs && data_subs->pcm_substream)
338 snd_pcm_stop_xrun(data_subs->pcm_substream);
341 static struct snd_usb_packet_info *
342 next_packet_fifo_enqueue(struct snd_usb_endpoint *ep)
344 struct snd_usb_packet_info *p;
346 p = ep->next_packet + (ep->next_packet_head + ep->next_packet_queued) %
347 ARRAY_SIZE(ep->next_packet);
348 ep->next_packet_queued++;
352 static struct snd_usb_packet_info *
353 next_packet_fifo_dequeue(struct snd_usb_endpoint *ep)
355 struct snd_usb_packet_info *p;
357 p = ep->next_packet + ep->next_packet_head;
358 ep->next_packet_head++;
359 ep->next_packet_head %= ARRAY_SIZE(ep->next_packet);
360 ep->next_packet_queued--;
365 * Send output urbs that have been prepared previously. URBs are dequeued
366 * from ep->ready_playback_urbs and in case there aren't any available
367 * or there are no packets that have been prepared, this function does
370 * The reason why the functionality of sending and preparing URBs is separated
371 * is that host controllers don't guarantee the order in which they return
372 * inbound and outbound packets to their submitters.
374 * This function is only used for implicit feedback endpoints. For endpoints
375 * driven by dedicated sync endpoints, URBs are immediately re-submitted
376 * from their completion handler.
378 static void queue_pending_output_urbs(struct snd_usb_endpoint *ep)
380 while (test_bit(EP_FLAG_RUNNING, &ep->flags)) {
383 struct snd_usb_packet_info *packet;
384 struct snd_urb_ctx *ctx = NULL;
387 spin_lock_irqsave(&ep->lock, flags);
388 if (ep->next_packet_queued > 0 &&
389 !list_empty(&ep->ready_playback_urbs)) {
390 /* take URB out of FIFO */
391 ctx = list_first_entry(&ep->ready_playback_urbs,
392 struct snd_urb_ctx, ready_list);
393 list_del_init(&ctx->ready_list);
395 packet = next_packet_fifo_dequeue(ep);
397 spin_unlock_irqrestore(&ep->lock, flags);
402 /* copy over the length information */
403 for (i = 0; i < packet->packets; i++)
404 ctx->packet_size[i] = packet->packet_size[i];
406 /* call the data handler to fill in playback data */
407 prepare_outbound_urb(ep, ctx);
409 err = usb_submit_urb(ctx->urb, GFP_ATOMIC);
411 usb_audio_err(ep->chip,
412 "Unable to submit urb #%d: %d at %s\n",
413 ctx->index, err, __func__);
418 set_bit(ctx->index, &ep->active_mask);
423 * complete callback for urbs
425 static void snd_complete_urb(struct urb *urb)
427 struct snd_urb_ctx *ctx = urb->context;
428 struct snd_usb_endpoint *ep = ctx->ep;
432 if (unlikely(urb->status == -ENOENT || /* unlinked */
433 urb->status == -ENODEV || /* device removed */
434 urb->status == -ECONNRESET || /* unlinked */
435 urb->status == -ESHUTDOWN)) /* device disabled */
437 /* device disconnected */
438 if (unlikely(atomic_read(&ep->chip->shutdown)))
441 if (unlikely(!test_bit(EP_FLAG_RUNNING, &ep->flags)))
444 if (usb_pipeout(ep->pipe)) {
445 retire_outbound_urb(ep, ctx);
446 /* can be stopped during retire callback */
447 if (unlikely(!test_bit(EP_FLAG_RUNNING, &ep->flags)))
450 if (snd_usb_endpoint_implicit_feedback_sink(ep)) {
451 spin_lock_irqsave(&ep->lock, flags);
452 list_add_tail(&ctx->ready_list, &ep->ready_playback_urbs);
453 clear_bit(ctx->index, &ep->active_mask);
454 spin_unlock_irqrestore(&ep->lock, flags);
455 queue_pending_output_urbs(ep);
459 prepare_outbound_urb(ep, ctx);
460 /* can be stopped during prepare callback */
461 if (unlikely(!test_bit(EP_FLAG_RUNNING, &ep->flags)))
464 retire_inbound_urb(ep, ctx);
465 /* can be stopped during retire callback */
466 if (unlikely(!test_bit(EP_FLAG_RUNNING, &ep->flags)))
469 prepare_inbound_urb(ep, ctx);
472 err = usb_submit_urb(urb, GFP_ATOMIC);
476 usb_audio_err(ep->chip, "cannot submit urb (err = %d)\n", err);
480 clear_bit(ctx->index, &ep->active_mask);
484 * Get the existing endpoint object corresponding EP
485 * Returns NULL if not present.
487 struct snd_usb_endpoint *
488 snd_usb_get_endpoint(struct snd_usb_audio *chip, int ep_num)
490 struct snd_usb_endpoint *ep;
492 list_for_each_entry(ep, &chip->ep_list, list) {
493 if (ep->ep_num == ep_num)
500 #define ep_type_name(type) \
501 (type == SND_USB_ENDPOINT_TYPE_DATA ? "data" : "sync")
504 * snd_usb_add_endpoint: Add an endpoint to an USB audio chip
507 * @ep_num: The number of the endpoint to use
508 * @type: SND_USB_ENDPOINT_TYPE_DATA or SND_USB_ENDPOINT_TYPE_SYNC
510 * If the requested endpoint has not been added to the given chip before,
511 * a new instance is created.
513 * Returns zero on success or a negative error code.
515 * New endpoints will be added to chip->ep_list and must be freed by
516 * calling snd_usb_endpoint_free().
518 * For SND_USB_ENDPOINT_TYPE_SYNC, the caller needs to guarantee that
519 * bNumEndpoints > 1 beforehand.
521 int snd_usb_add_endpoint(struct snd_usb_audio *chip, int ep_num, int type)
523 struct snd_usb_endpoint *ep;
526 ep = snd_usb_get_endpoint(chip, ep_num);
530 usb_audio_dbg(chip, "Creating new %s endpoint #%x\n",
533 ep = kzalloc(sizeof(*ep), GFP_KERNEL);
538 spin_lock_init(&ep->lock);
541 INIT_LIST_HEAD(&ep->ready_playback_urbs);
543 is_playback = ((ep_num & USB_ENDPOINT_DIR_MASK) == USB_DIR_OUT);
544 ep_num &= USB_ENDPOINT_NUMBER_MASK;
546 ep->pipe = usb_sndisocpipe(chip->dev, ep_num);
548 ep->pipe = usb_rcvisocpipe(chip->dev, ep_num);
550 list_add_tail(&ep->list, &chip->ep_list);
554 /* Set up syncinterval and maxsyncsize for a sync EP */
555 static void endpoint_set_syncinterval(struct snd_usb_audio *chip,
556 struct snd_usb_endpoint *ep)
558 struct usb_host_interface *alts;
559 struct usb_endpoint_descriptor *desc;
561 alts = snd_usb_get_host_interface(chip, ep->iface, ep->altsetting);
565 desc = get_endpoint(alts, ep->ep_idx);
566 if (desc->bLength >= USB_DT_ENDPOINT_AUDIO_SIZE &&
567 desc->bRefresh >= 1 && desc->bRefresh <= 9)
568 ep->syncinterval = desc->bRefresh;
569 else if (snd_usb_get_speed(chip->dev) == USB_SPEED_FULL)
570 ep->syncinterval = 1;
571 else if (desc->bInterval >= 1 && desc->bInterval <= 16)
572 ep->syncinterval = desc->bInterval - 1;
574 ep->syncinterval = 3;
576 ep->syncmaxsize = le16_to_cpu(desc->wMaxPacketSize);
579 static bool endpoint_compatible(struct snd_usb_endpoint *ep,
580 const struct audioformat *fp,
581 const struct snd_pcm_hw_params *params)
585 if (ep->cur_audiofmt != fp)
587 if (ep->cur_rate != params_rate(params) ||
588 ep->cur_format != params_format(params) ||
589 ep->cur_period_frames != params_period_size(params) ||
590 ep->cur_buffer_periods != params_periods(params))
596 * Check whether the given fp and hw params are compatbile with the current
597 * setup of the target EP for implicit feedback sync
599 bool snd_usb_endpoint_compatible(struct snd_usb_audio *chip,
600 struct snd_usb_endpoint *ep,
601 const struct audioformat *fp,
602 const struct snd_pcm_hw_params *params)
606 mutex_lock(&chip->mutex);
607 ret = endpoint_compatible(ep, fp, params);
608 mutex_unlock(&chip->mutex);
613 * snd_usb_endpoint_open: Open the endpoint
615 * Called from hw_params to assign the endpoint to the substream.
616 * It's reference-counted, and only the first opener is allowed to set up
617 * arbitrary parameters. The later opener must be compatible with the
618 * former opened parameters.
619 * The endpoint needs to be closed via snd_usb_endpoint_close() later.
621 * Note that this function doesn't configure the endpoint. The substream
622 * needs to set it up later via snd_usb_endpoint_configure().
624 struct snd_usb_endpoint *
625 snd_usb_endpoint_open(struct snd_usb_audio *chip,
626 const struct audioformat *fp,
627 const struct snd_pcm_hw_params *params,
630 struct snd_usb_endpoint *ep;
631 int ep_num = is_sync_ep ? fp->sync_ep : fp->endpoint;
633 mutex_lock(&chip->mutex);
634 ep = snd_usb_get_endpoint(chip, ep_num);
636 usb_audio_err(chip, "Cannot find EP 0x%x to open\n", ep_num);
642 ep->iface = fp->sync_iface;
643 ep->altsetting = fp->sync_altsetting;
644 ep->ep_idx = fp->sync_ep_idx;
646 ep->iface = fp->iface;
647 ep->altsetting = fp->altsetting;
650 usb_audio_dbg(chip, "Open EP 0x%x, iface=%d:%d, idx=%d\n",
651 ep_num, ep->iface, ep->altsetting, ep->ep_idx);
653 ep->cur_audiofmt = fp;
654 ep->cur_channels = fp->channels;
655 ep->cur_rate = params_rate(params);
656 ep->cur_format = params_format(params);
657 ep->cur_frame_bytes = snd_pcm_format_physical_width(ep->cur_format) *
658 ep->cur_channels / 8;
659 ep->cur_period_frames = params_period_size(params);
660 ep->cur_period_bytes = ep->cur_period_frames * ep->cur_frame_bytes;
661 ep->cur_buffer_periods = params_periods(params);
663 if (ep->type == SND_USB_ENDPOINT_TYPE_SYNC)
664 endpoint_set_syncinterval(chip, ep);
666 ep->implicit_fb_sync = fp->implicit_fb;
667 ep->need_setup = true;
669 usb_audio_dbg(chip, " channels=%d, rate=%d, format=%s, period_bytes=%d, periods=%d, implicit_fb=%d\n",
670 ep->cur_channels, ep->cur_rate,
671 snd_pcm_format_name(ep->cur_format),
672 ep->cur_period_bytes, ep->cur_buffer_periods,
673 ep->implicit_fb_sync);
676 if (!endpoint_compatible(ep, fp, params)) {
677 usb_audio_err(chip, "Incompatible EP setup for 0x%x\n",
683 usb_audio_dbg(chip, "Reopened EP 0x%x (count %d)\n",
690 mutex_unlock(&chip->mutex);
695 * snd_usb_endpoint_set_sync: Link data and sync endpoints
697 * Pass NULL to sync_ep to unlink again
699 void snd_usb_endpoint_set_sync(struct snd_usb_audio *chip,
700 struct snd_usb_endpoint *data_ep,
701 struct snd_usb_endpoint *sync_ep)
703 data_ep->sync_master = sync_ep;
707 * Set data endpoint callbacks and the assigned data stream
709 * Called at PCM trigger and cleanups.
710 * Pass NULL to deactivate each callback.
712 void snd_usb_endpoint_set_callback(struct snd_usb_endpoint *ep,
713 void (*prepare)(struct snd_usb_substream *subs,
715 void (*retire)(struct snd_usb_substream *subs,
717 struct snd_usb_substream *data_subs)
719 ep->prepare_data_urb = prepare;
720 ep->retire_data_urb = retire;
721 WRITE_ONCE(ep->data_subs, data_subs);
724 static int endpoint_set_interface(struct snd_usb_audio *chip,
725 struct snd_usb_endpoint *ep,
728 int altset = set ? ep->altsetting : 0;
731 usb_audio_dbg(chip, "Setting usb interface %d:%d for EP 0x%x\n",
732 ep->iface, altset, ep->ep_num);
733 err = usb_set_interface(chip->dev, ep->iface, altset);
735 usb_audio_err(chip, "%d:%d: usb_set_interface failed (%d)\n",
736 ep->iface, altset, err);
740 snd_usb_set_interface_quirk(chip);
745 * snd_usb_endpoint_close: Close the endpoint
747 * Unreference the already opened endpoint via snd_usb_endpoint_open().
749 void snd_usb_endpoint_close(struct snd_usb_audio *chip,
750 struct snd_usb_endpoint *ep)
752 mutex_lock(&chip->mutex);
753 usb_audio_dbg(chip, "Closing EP 0x%x (count %d)\n",
754 ep->ep_num, ep->opened);
756 endpoint_set_interface(chip, ep, false);
759 ep->cur_audiofmt = NULL;
761 usb_audio_dbg(chip, "EP 0x%x closed\n", ep->ep_num);
763 mutex_unlock(&chip->mutex);
766 /* Prepare for suspening EP, called from the main suspend handler */
767 void snd_usb_endpoint_suspend(struct snd_usb_endpoint *ep)
769 ep->need_setup = true;
773 * wait until all urbs are processed.
775 static int wait_clear_urbs(struct snd_usb_endpoint *ep)
777 unsigned long end_time = jiffies + msecs_to_jiffies(1000);
781 alive = bitmap_weight(&ep->active_mask, ep->nurbs);
785 schedule_timeout_uninterruptible(1);
786 } while (time_before(jiffies, end_time));
789 usb_audio_err(ep->chip,
790 "timeout: still %d active urbs on EP #%x\n",
792 clear_bit(EP_FLAG_STOPPING, &ep->flags);
794 ep->sync_slave = NULL;
795 snd_usb_endpoint_set_callback(ep, NULL, NULL, NULL);
800 /* sync the pending stop operation;
801 * this function itself doesn't trigger the stop operation
803 void snd_usb_endpoint_sync_pending_stop(struct snd_usb_endpoint *ep)
805 if (ep && test_bit(EP_FLAG_STOPPING, &ep->flags))
810 * unlink active urbs.
812 static int deactivate_urbs(struct snd_usb_endpoint *ep, bool force)
816 if (!force && atomic_read(&ep->chip->shutdown)) /* to be sure... */
819 clear_bit(EP_FLAG_RUNNING, &ep->flags);
821 INIT_LIST_HEAD(&ep->ready_playback_urbs);
822 ep->next_packet_head = 0;
823 ep->next_packet_queued = 0;
825 for (i = 0; i < ep->nurbs; i++) {
826 if (test_bit(i, &ep->active_mask)) {
827 if (!test_and_set_bit(i, &ep->unlink_mask)) {
828 struct urb *u = ep->urb[i].urb;
838 * release an endpoint's urbs
840 static void release_urbs(struct snd_usb_endpoint *ep, int force)
844 /* route incoming urbs to nirvana */
845 snd_usb_endpoint_set_callback(ep, NULL, NULL, NULL);
848 deactivate_urbs(ep, force);
851 for (i = 0; i < ep->nurbs; i++)
852 release_urb_ctx(&ep->urb[i]);
854 usb_free_coherent(ep->chip->dev, SYNC_URBS * 4,
855 ep->syncbuf, ep->sync_dma);
862 * configure a data endpoint
864 static int data_ep_set_params(struct snd_usb_endpoint *ep)
866 struct snd_usb_audio *chip = ep->chip;
867 unsigned int maxsize, minsize, packs_per_ms, max_packs_per_urb;
868 unsigned int max_packs_per_period, urbs_per_period, urb_packs;
869 unsigned int max_urbs, i;
870 const struct audioformat *fmt = ep->cur_audiofmt;
871 int frame_bits = ep->cur_frame_bytes * 8;
872 int tx_length_quirk = (chip->tx_length_quirk &&
873 usb_pipeout(ep->pipe));
875 usb_audio_dbg(chip, "Setting params for data EP 0x%x, pipe 0x%x\n",
876 ep->ep_num, ep->pipe);
878 if (ep->cur_format == SNDRV_PCM_FORMAT_DSD_U16_LE && fmt->dsd_dop) {
880 * When operating in DSD DOP mode, the size of a sample frame
881 * in hardware differs from the actual physical format width
882 * because we need to make room for the DOP markers.
884 frame_bits += ep->cur_channels << 3;
887 ep->datainterval = fmt->datainterval;
888 ep->stride = frame_bits >> 3;
890 switch (ep->cur_format) {
891 case SNDRV_PCM_FORMAT_U8:
892 ep->silence_value = 0x80;
894 case SNDRV_PCM_FORMAT_DSD_U8:
895 case SNDRV_PCM_FORMAT_DSD_U16_LE:
896 case SNDRV_PCM_FORMAT_DSD_U32_LE:
897 case SNDRV_PCM_FORMAT_DSD_U16_BE:
898 case SNDRV_PCM_FORMAT_DSD_U32_BE:
899 ep->silence_value = 0x69;
902 ep->silence_value = 0;
905 /* assume max. frequency is 50% higher than nominal */
906 ep->freqmax = ep->freqn + (ep->freqn >> 1);
907 /* Round up freqmax to nearest integer in order to calculate maximum
908 * packet size, which must represent a whole number of frames.
909 * This is accomplished by adding 0x0.ffff before converting the
910 * Q16.16 format into integer.
911 * In order to accurately calculate the maximum packet size when
912 * the data interval is more than 1 (i.e. ep->datainterval > 0),
913 * multiply by the data interval prior to rounding. For instance,
914 * a freqmax of 41 kHz will result in a max packet size of 6 (5.125)
915 * frames with a data interval of 1, but 11 (10.25) frames with a
916 * data interval of 2.
917 * (ep->freqmax << ep->datainterval overflows at 8.192 MHz for the
918 * maximum datainterval value of 3, at USB full speed, higher for
919 * USB high speed, noting that ep->freqmax is in units of
920 * frames per packet in Q16.16 format.)
922 maxsize = (((ep->freqmax << ep->datainterval) + 0xffff) >> 16) *
925 maxsize += sizeof(__le32); /* Space for length descriptor */
926 /* but wMaxPacketSize might reduce this */
927 if (ep->maxpacksize && ep->maxpacksize < maxsize) {
928 /* whatever fits into a max. size packet */
929 unsigned int data_maxsize = maxsize = ep->maxpacksize;
932 /* Need to remove the length descriptor to calc freq */
933 data_maxsize -= sizeof(__le32);
934 ep->freqmax = (data_maxsize / (frame_bits >> 3))
935 << (16 - ep->datainterval);
939 ep->curpacksize = ep->maxpacksize;
941 ep->curpacksize = maxsize;
943 if (snd_usb_get_speed(chip->dev) != USB_SPEED_FULL) {
944 packs_per_ms = 8 >> ep->datainterval;
945 max_packs_per_urb = MAX_PACKS_HS;
948 max_packs_per_urb = MAX_PACKS;
950 if (ep->sync_master && !ep->implicit_fb_sync)
951 max_packs_per_urb = min(max_packs_per_urb,
952 1U << ep->sync_master->syncinterval);
953 max_packs_per_urb = max(1u, max_packs_per_urb >> ep->datainterval);
956 * Capture endpoints need to use small URBs because there's no way
957 * to tell in advance where the next period will end, and we don't
958 * want the next URB to complete much after the period ends.
960 * Playback endpoints with implicit sync much use the same parameters
961 * as their corresponding capture endpoint.
963 if (usb_pipein(ep->pipe) || ep->implicit_fb_sync) {
965 urb_packs = packs_per_ms;
967 * Wireless devices can poll at a max rate of once per 4ms.
968 * For dataintervals less than 5, increase the packet count to
969 * allow the host controller to use bursting to fill in the
972 if (snd_usb_get_speed(chip->dev) == USB_SPEED_WIRELESS) {
973 int interval = ep->datainterval;
974 while (interval < 5) {
979 /* make capture URBs <= 1 ms and smaller than a period */
980 urb_packs = min(max_packs_per_urb, urb_packs);
981 while (urb_packs > 1 && urb_packs * maxsize >= ep->cur_period_bytes)
983 ep->nurbs = MAX_URBS;
986 * Playback endpoints without implicit sync are adjusted so that
987 * a period fits as evenly as possible in the smallest number of
988 * URBs. The total number of URBs is adjusted to the size of the
989 * ALSA buffer, subject to the MAX_URBS and MAX_QUEUE limits.
992 /* determine how small a packet can be */
993 minsize = (ep->freqn >> (16 - ep->datainterval)) *
995 /* with sync from device, assume it can be 12% lower */
997 minsize -= minsize >> 3;
998 minsize = max(minsize, 1u);
1000 /* how many packets will contain an entire ALSA period? */
1001 max_packs_per_period = DIV_ROUND_UP(ep->cur_period_bytes, minsize);
1003 /* how many URBs will contain a period? */
1004 urbs_per_period = DIV_ROUND_UP(max_packs_per_period,
1006 /* how many packets are needed in each URB? */
1007 urb_packs = DIV_ROUND_UP(max_packs_per_period, urbs_per_period);
1009 /* limit the number of frames in a single URB */
1010 ep->max_urb_frames = DIV_ROUND_UP(ep->cur_period_frames,
1013 /* try to use enough URBs to contain an entire ALSA buffer */
1014 max_urbs = min((unsigned) MAX_URBS,
1015 MAX_QUEUE * packs_per_ms / urb_packs);
1016 ep->nurbs = min(max_urbs, urbs_per_period * ep->cur_buffer_periods);
1019 /* allocate and initialize data urbs */
1020 for (i = 0; i < ep->nurbs; i++) {
1021 struct snd_urb_ctx *u = &ep->urb[i];
1024 u->packets = urb_packs;
1025 u->buffer_size = maxsize * u->packets;
1027 if (fmt->fmt_type == UAC_FORMAT_TYPE_II)
1028 u->packets++; /* for transfer delimiter */
1029 u->urb = usb_alloc_urb(u->packets, GFP_KERNEL);
1033 u->urb->transfer_buffer =
1034 usb_alloc_coherent(chip->dev, u->buffer_size,
1035 GFP_KERNEL, &u->urb->transfer_dma);
1036 if (!u->urb->transfer_buffer)
1038 u->urb->pipe = ep->pipe;
1039 u->urb->transfer_flags = URB_NO_TRANSFER_DMA_MAP;
1040 u->urb->interval = 1 << ep->datainterval;
1041 u->urb->context = u;
1042 u->urb->complete = snd_complete_urb;
1043 INIT_LIST_HEAD(&u->ready_list);
1049 release_urbs(ep, 0);
1054 * configure a sync endpoint
1056 static int sync_ep_set_params(struct snd_usb_endpoint *ep)
1058 struct snd_usb_audio *chip = ep->chip;
1061 usb_audio_dbg(chip, "Setting params for sync EP 0x%x, pipe 0x%x\n",
1062 ep->ep_num, ep->pipe);
1064 ep->syncbuf = usb_alloc_coherent(chip->dev, SYNC_URBS * 4,
1065 GFP_KERNEL, &ep->sync_dma);
1069 for (i = 0; i < SYNC_URBS; i++) {
1070 struct snd_urb_ctx *u = &ep->urb[i];
1074 u->urb = usb_alloc_urb(1, GFP_KERNEL);
1077 u->urb->transfer_buffer = ep->syncbuf + i * 4;
1078 u->urb->transfer_dma = ep->sync_dma + i * 4;
1079 u->urb->transfer_buffer_length = 4;
1080 u->urb->pipe = ep->pipe;
1081 u->urb->transfer_flags = URB_NO_TRANSFER_DMA_MAP;
1082 u->urb->number_of_packets = 1;
1083 u->urb->interval = 1 << ep->syncinterval;
1084 u->urb->context = u;
1085 u->urb->complete = snd_complete_urb;
1088 ep->nurbs = SYNC_URBS;
1093 release_urbs(ep, 0);
1098 * snd_usb_endpoint_set_params: configure an snd_usb_endpoint
1100 * Determine the number of URBs to be used on this endpoint.
1101 * An endpoint must be configured before it can be started.
1102 * An endpoint that is already running can not be reconfigured.
1104 static int snd_usb_endpoint_set_params(struct snd_usb_audio *chip,
1105 struct snd_usb_endpoint *ep)
1107 const struct audioformat *fmt = ep->cur_audiofmt;
1110 /* release old buffers, if any */
1111 release_urbs(ep, 0);
1113 ep->datainterval = fmt->datainterval;
1114 ep->maxpacksize = fmt->maxpacksize;
1115 ep->fill_max = !!(fmt->attributes & UAC_EP_CS_ATTR_FILL_MAX);
1117 if (snd_usb_get_speed(chip->dev) == USB_SPEED_FULL) {
1118 ep->freqn = get_usb_full_speed_rate(ep->cur_rate);
1119 ep->pps = 1000 >> ep->datainterval;
1121 ep->freqn = get_usb_high_speed_rate(ep->cur_rate);
1122 ep->pps = 8000 >> ep->datainterval;
1125 ep->sample_rem = ep->cur_rate % ep->pps;
1126 ep->packsize[0] = ep->cur_rate / ep->pps;
1127 ep->packsize[1] = (ep->cur_rate + (ep->pps - 1)) / ep->pps;
1129 /* calculate the frequency in 16.16 format */
1130 ep->freqm = ep->freqn;
1131 ep->freqshift = INT_MIN;
1136 case SND_USB_ENDPOINT_TYPE_DATA:
1137 err = data_ep_set_params(ep);
1139 case SND_USB_ENDPOINT_TYPE_SYNC:
1140 err = sync_ep_set_params(ep);
1146 usb_audio_dbg(chip, "Set up %d URBS, ret=%d\n", ep->nurbs, err);
1151 /* some unit conversions in runtime */
1152 ep->maxframesize = ep->maxpacksize / ep->cur_frame_bytes;
1153 ep->curframesize = ep->curpacksize / ep->cur_frame_bytes;
1159 * snd_usb_endpoint_configure: Configure the endpoint
1161 * This function sets up the EP to be fully usable state.
1162 * It's called either from hw_params or prepare callback.
1163 * The function checks need_setup flag, and perfoms nothing unless needed,
1164 * so it's safe to call this multiple times.
1166 * This returns zero if unchanged, 1 if the configuration has changed,
1167 * or a negative error code.
1169 int snd_usb_endpoint_configure(struct snd_usb_audio *chip,
1170 struct snd_usb_endpoint *ep)
1175 mutex_lock(&chip->mutex);
1176 if (!ep->need_setup)
1179 /* No need to (re-)configure the sync EP belonging to the same altset */
1181 err = snd_usb_endpoint_set_params(chip, ep);
1187 /* Need to deselect altsetting at first */
1188 endpoint_set_interface(chip, ep, false);
1190 /* Some UAC1 devices (e.g. Yamaha THR10) need the host interface
1191 * to be set up before parameter setups
1193 iface_first = ep->cur_audiofmt->protocol == UAC_VERSION_1;
1195 err = endpoint_set_interface(chip, ep, true);
1200 err = snd_usb_init_pitch(chip, ep->cur_audiofmt);
1204 err = snd_usb_init_sample_rate(chip, ep->cur_audiofmt, ep->cur_rate);
1208 err = snd_usb_endpoint_set_params(chip, ep);
1212 err = snd_usb_select_mode_quirk(chip, ep->cur_audiofmt);
1216 /* for UAC2/3, enable the interface altset here at last */
1218 err = endpoint_set_interface(chip, ep, true);
1224 ep->need_setup = false;
1228 mutex_unlock(&chip->mutex);
1233 * snd_usb_endpoint_start: start an snd_usb_endpoint
1235 * @ep: the endpoint to start
1237 * A call to this function will increment the running count of the endpoint.
1238 * In case it is not already running, the URBs for this endpoint will be
1239 * submitted. Otherwise, this function does nothing.
1241 * Must be balanced to calls of snd_usb_endpoint_stop().
1243 * Returns an error if the URB submission failed, 0 in all other cases.
1245 int snd_usb_endpoint_start(struct snd_usb_endpoint *ep)
1250 if (atomic_read(&ep->chip->shutdown))
1253 if (ep->sync_master)
1254 WRITE_ONCE(ep->sync_master->sync_slave, ep);
1256 usb_audio_dbg(ep->chip, "Starting %s EP 0x%x (running %d)\n",
1257 ep_type_name(ep->type), ep->ep_num,
1258 atomic_read(&ep->running));
1260 /* already running? */
1261 if (atomic_inc_return(&ep->running) != 1)
1264 /* just to be sure */
1265 deactivate_urbs(ep, false);
1267 ep->active_mask = 0;
1268 ep->unlink_mask = 0;
1270 ep->sample_accum = 0;
1272 snd_usb_endpoint_start_quirk(ep);
1275 * If this endpoint has a data endpoint as implicit feedback source,
1276 * don't start the urbs here. Instead, mark them all as available,
1277 * wait for the record urbs to return and queue the playback urbs
1278 * from that context.
1281 set_bit(EP_FLAG_RUNNING, &ep->flags);
1283 if (snd_usb_endpoint_implicit_feedback_sink(ep)) {
1284 for (i = 0; i < ep->nurbs; i++) {
1285 struct snd_urb_ctx *ctx = ep->urb + i;
1286 list_add_tail(&ctx->ready_list, &ep->ready_playback_urbs);
1289 usb_audio_dbg(ep->chip, "No URB submission due to implicit fb sync\n");
1293 for (i = 0; i < ep->nurbs; i++) {
1294 struct urb *urb = ep->urb[i].urb;
1296 if (snd_BUG_ON(!urb))
1299 if (usb_pipeout(ep->pipe)) {
1300 prepare_outbound_urb(ep, urb->context);
1302 prepare_inbound_urb(ep, urb->context);
1305 err = usb_submit_urb(urb, GFP_ATOMIC);
1307 usb_audio_err(ep->chip,
1308 "cannot submit urb %d, error %d: %s\n",
1309 i, err, usb_error_string(err));
1312 set_bit(i, &ep->active_mask);
1315 usb_audio_dbg(ep->chip, "%d URBs submitted for EP 0x%x\n",
1316 ep->nurbs, ep->ep_num);
1320 if (ep->sync_master)
1321 WRITE_ONCE(ep->sync_master->sync_slave, NULL);
1322 clear_bit(EP_FLAG_RUNNING, &ep->flags);
1323 atomic_dec(&ep->running);
1324 deactivate_urbs(ep, false);
1329 * snd_usb_endpoint_stop: stop an snd_usb_endpoint
1331 * @ep: the endpoint to stop (may be NULL)
1333 * A call to this function will decrement the running count of the endpoint.
1334 * In case the last user has requested the endpoint stop, the URBs will
1335 * actually be deactivated.
1337 * Must be balanced to calls of snd_usb_endpoint_start().
1339 * The caller needs to synchronize the pending stop operation via
1340 * snd_usb_endpoint_sync_pending_stop().
1342 void snd_usb_endpoint_stop(struct snd_usb_endpoint *ep)
1347 usb_audio_dbg(ep->chip, "Stopping %s EP 0x%x (running %d)\n",
1348 ep_type_name(ep->type), ep->ep_num,
1349 atomic_read(&ep->running));
1351 if (snd_BUG_ON(!atomic_read(&ep->running)))
1354 if (ep->sync_master)
1355 WRITE_ONCE(ep->sync_master->sync_slave, NULL);
1357 if (!atomic_dec_return(&ep->running)) {
1358 deactivate_urbs(ep, false);
1359 set_bit(EP_FLAG_STOPPING, &ep->flags);
1364 * snd_usb_endpoint_release: Tear down an snd_usb_endpoint
1366 * @ep: the endpoint to release
1368 * This function does not care for the endpoint's running count but will tear
1369 * down all the streaming URBs immediately.
1371 void snd_usb_endpoint_release(struct snd_usb_endpoint *ep)
1373 release_urbs(ep, 1);
1377 * snd_usb_endpoint_free: Free the resources of an snd_usb_endpoint
1379 * @ep: the endpoint to free
1381 * This free all resources of the given ep.
1383 void snd_usb_endpoint_free(struct snd_usb_endpoint *ep)
1389 * snd_usb_handle_sync_urb: parse an USB sync packet
1391 * @ep: the endpoint to handle the packet
1392 * @sender: the sending endpoint
1393 * @urb: the received packet
1395 * This function is called from the context of an endpoint that received
1396 * the packet and is used to let another endpoint object handle the payload.
1398 static void snd_usb_handle_sync_urb(struct snd_usb_endpoint *ep,
1399 struct snd_usb_endpoint *sender,
1400 const struct urb *urb)
1404 unsigned long flags;
1406 snd_BUG_ON(ep == sender);
1409 * In case the endpoint is operating in implicit feedback mode, prepare
1410 * a new outbound URB that has the same layout as the received packet
1411 * and add it to the list of pending urbs. queue_pending_output_urbs()
1412 * will take care of them later.
1414 if (snd_usb_endpoint_implicit_feedback_sink(ep) &&
1415 atomic_read(&ep->running)) {
1417 /* implicit feedback case */
1419 struct snd_urb_ctx *in_ctx;
1420 struct snd_usb_packet_info *out_packet;
1422 in_ctx = urb->context;
1424 /* Count overall packet size */
1425 for (i = 0; i < in_ctx->packets; i++)
1426 if (urb->iso_frame_desc[i].status == 0)
1427 bytes += urb->iso_frame_desc[i].actual_length;
1430 * skip empty packets. At least M-Audio's Fast Track Ultra stops
1431 * streaming once it received a 0-byte OUT URB
1436 spin_lock_irqsave(&ep->lock, flags);
1437 if (ep->next_packet_queued >= ARRAY_SIZE(ep->next_packet)) {
1438 spin_unlock_irqrestore(&ep->lock, flags);
1439 usb_audio_err(ep->chip,
1440 "next package FIFO overflow EP 0x%x\n",
1446 out_packet = next_packet_fifo_enqueue(ep);
1449 * Iterate through the inbound packet and prepare the lengths
1450 * for the output packet. The OUT packet we are about to send
1451 * will have the same amount of payload bytes per stride as the
1452 * IN packet we just received. Since the actual size is scaled
1453 * by the stride, use the sender stride to calculate the length
1454 * in case the number of channels differ between the implicitly
1455 * fed-back endpoint and the synchronizing endpoint.
1458 out_packet->packets = in_ctx->packets;
1459 for (i = 0; i < in_ctx->packets; i++) {
1460 if (urb->iso_frame_desc[i].status == 0)
1461 out_packet->packet_size[i] =
1462 urb->iso_frame_desc[i].actual_length / sender->stride;
1464 out_packet->packet_size[i] = 0;
1467 spin_unlock_irqrestore(&ep->lock, flags);
1468 queue_pending_output_urbs(ep);
1474 * process after playback sync complete
1476 * Full speed devices report feedback values in 10.14 format as samples
1477 * per frame, high speed devices in 16.16 format as samples per
1480 * Because the Audio Class 1 spec was written before USB 2.0, many high
1481 * speed devices use a wrong interpretation, some others use an
1482 * entirely different format.
1484 * Therefore, we cannot predict what format any particular device uses
1485 * and must detect it automatically.
1488 if (urb->iso_frame_desc[0].status != 0 ||
1489 urb->iso_frame_desc[0].actual_length < 3)
1492 f = le32_to_cpup(urb->transfer_buffer);
1493 if (urb->iso_frame_desc[0].actual_length == 3)
1501 if (unlikely(sender->tenor_fb_quirk)) {
1503 * Devices based on Tenor 8802 chipsets (TEAC UD-H01
1504 * and others) sometimes change the feedback value
1507 if (f < ep->freqn - 0x8000)
1509 else if (f > ep->freqn + 0x8000)
1511 } else if (unlikely(ep->freqshift == INT_MIN)) {
1513 * The first time we see a feedback value, determine its format
1514 * by shifting it left or right until it matches the nominal
1515 * frequency value. This assumes that the feedback does not
1516 * differ from the nominal value more than +50% or -25%.
1519 while (f < ep->freqn - ep->freqn / 4) {
1523 while (f > ep->freqn + ep->freqn / 2) {
1527 ep->freqshift = shift;
1528 } else if (ep->freqshift >= 0)
1529 f <<= ep->freqshift;
1531 f >>= -ep->freqshift;
1533 if (likely(f >= ep->freqn - ep->freqn / 8 && f <= ep->freqmax)) {
1535 * If the frequency looks valid, set it.
1536 * This value is referred to in prepare_playback_urb().
1538 spin_lock_irqsave(&ep->lock, flags);
1540 spin_unlock_irqrestore(&ep->lock, flags);
1543 * Out of range; maybe the shift value is wrong.
1544 * Reset it so that we autodetect again the next time.
1546 ep->freqshift = INT_MIN;