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 next_packet_size() to
128 * determine the number of samples to be sent in the next packet.
130 * For implicit feedback, next_packet_size() is unused.
132 int snd_usb_endpoint_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
);
149 static void retire_outbound_urb(struct snd_usb_endpoint
*ep
,
150 struct snd_urb_ctx
*urb_ctx
)
152 if (ep
->retire_data_urb
)
153 ep
->retire_data_urb(ep
->data_subs
, urb_ctx
->urb
);
156 static void retire_inbound_urb(struct snd_usb_endpoint
*ep
,
157 struct snd_urb_ctx
*urb_ctx
)
159 struct urb
*urb
= urb_ctx
->urb
;
161 if (unlikely(ep
->skip_packets
> 0)) {
167 snd_usb_handle_sync_urb(ep
->sync_slave
, ep
, urb
);
169 if (ep
->retire_data_urb
)
170 ep
->retire_data_urb(ep
->data_subs
, urb
);
173 static void prepare_silent_urb(struct snd_usb_endpoint
*ep
,
174 struct snd_urb_ctx
*ctx
)
176 struct urb
*urb
= ctx
->urb
;
177 unsigned int offs
= 0;
178 unsigned int extra
= 0;
179 __le32 packet_length
;
182 /* For tx_length_quirk, put packet length at start of packet */
183 if (ep
->chip
->tx_length_quirk
)
184 extra
= sizeof(packet_length
);
186 for (i
= 0; i
< ctx
->packets
; ++i
) {
191 if (ctx
->packet_size
[i
])
192 counts
= ctx
->packet_size
[i
];
194 counts
= snd_usb_endpoint_next_packet_size(ep
);
196 length
= counts
* ep
->stride
; /* number of silent bytes */
197 offset
= offs
* ep
->stride
+ extra
* i
;
198 urb
->iso_frame_desc
[i
].offset
= offset
;
199 urb
->iso_frame_desc
[i
].length
= length
+ extra
;
201 packet_length
= cpu_to_le32(length
);
202 memcpy(urb
->transfer_buffer
+ offset
,
203 &packet_length
, sizeof(packet_length
));
205 memset(urb
->transfer_buffer
+ offset
+ extra
,
206 ep
->silence_value
, length
);
210 urb
->number_of_packets
= ctx
->packets
;
211 urb
->transfer_buffer_length
= offs
* ep
->stride
+ ctx
->packets
* extra
;
215 * Prepare a PLAYBACK urb for submission to the bus.
217 static void prepare_outbound_urb(struct snd_usb_endpoint
*ep
,
218 struct snd_urb_ctx
*ctx
)
220 struct urb
*urb
= ctx
->urb
;
221 unsigned char *cp
= urb
->transfer_buffer
;
223 urb
->dev
= ep
->chip
->dev
; /* we need to set this at each time */
226 case SND_USB_ENDPOINT_TYPE_DATA
:
227 if (ep
->prepare_data_urb
) {
228 ep
->prepare_data_urb(ep
->data_subs
, urb
);
230 /* no data provider, so send silence */
231 prepare_silent_urb(ep
, ctx
);
235 case SND_USB_ENDPOINT_TYPE_SYNC
:
236 if (snd_usb_get_speed(ep
->chip
->dev
) >= USB_SPEED_HIGH
) {
238 * fill the length and offset of each urb descriptor.
239 * the fixed 12.13 frequency is passed as 16.16 through the pipe.
241 urb
->iso_frame_desc
[0].length
= 4;
242 urb
->iso_frame_desc
[0].offset
= 0;
244 cp
[1] = ep
->freqn
>> 8;
245 cp
[2] = ep
->freqn
>> 16;
246 cp
[3] = ep
->freqn
>> 24;
249 * fill the length and offset of each urb descriptor.
250 * the fixed 10.14 frequency is passed through the pipe.
252 urb
->iso_frame_desc
[0].length
= 3;
253 urb
->iso_frame_desc
[0].offset
= 0;
254 cp
[0] = ep
->freqn
>> 2;
255 cp
[1] = ep
->freqn
>> 10;
256 cp
[2] = ep
->freqn
>> 18;
264 * Prepare a CAPTURE or SYNC urb for submission to the bus.
266 static inline void prepare_inbound_urb(struct snd_usb_endpoint
*ep
,
267 struct snd_urb_ctx
*urb_ctx
)
270 struct urb
*urb
= urb_ctx
->urb
;
272 urb
->dev
= ep
->chip
->dev
; /* we need to set this at each time */
275 case SND_USB_ENDPOINT_TYPE_DATA
:
277 for (i
= 0; i
< urb_ctx
->packets
; i
++) {
278 urb
->iso_frame_desc
[i
].offset
= offs
;
279 urb
->iso_frame_desc
[i
].length
= ep
->curpacksize
;
280 offs
+= ep
->curpacksize
;
283 urb
->transfer_buffer_length
= offs
;
284 urb
->number_of_packets
= urb_ctx
->packets
;
287 case SND_USB_ENDPOINT_TYPE_SYNC
:
288 urb
->iso_frame_desc
[0].length
= min(4u, ep
->syncmaxsize
);
289 urb
->iso_frame_desc
[0].offset
= 0;
295 * Send output urbs that have been prepared previously. URBs are dequeued
296 * from ep->ready_playback_urbs and in case there there aren't any available
297 * or there are no packets that have been prepared, this function does
300 * The reason why the functionality of sending and preparing URBs is separated
301 * is that host controllers don't guarantee the order in which they return
302 * inbound and outbound packets to their submitters.
304 * This function is only used for implicit feedback endpoints. For endpoints
305 * driven by dedicated sync endpoints, URBs are immediately re-submitted
306 * from their completion handler.
308 static void queue_pending_output_urbs(struct snd_usb_endpoint
*ep
)
310 while (test_bit(EP_FLAG_RUNNING
, &ep
->flags
)) {
313 struct snd_usb_packet_info
*uninitialized_var(packet
);
314 struct snd_urb_ctx
*ctx
= NULL
;
317 spin_lock_irqsave(&ep
->lock
, flags
);
318 if (ep
->next_packet_read_pos
!= ep
->next_packet_write_pos
) {
319 packet
= ep
->next_packet
+ ep
->next_packet_read_pos
;
320 ep
->next_packet_read_pos
++;
321 ep
->next_packet_read_pos
%= MAX_URBS
;
323 /* take URB out of FIFO */
324 if (!list_empty(&ep
->ready_playback_urbs
)) {
325 ctx
= list_first_entry(&ep
->ready_playback_urbs
,
326 struct snd_urb_ctx
, ready_list
);
327 list_del_init(&ctx
->ready_list
);
330 spin_unlock_irqrestore(&ep
->lock
, flags
);
335 /* copy over the length information */
336 for (i
= 0; i
< packet
->packets
; i
++)
337 ctx
->packet_size
[i
] = packet
->packet_size
[i
];
339 /* call the data handler to fill in playback data */
340 prepare_outbound_urb(ep
, ctx
);
342 err
= usb_submit_urb(ctx
->urb
, GFP_ATOMIC
);
344 usb_audio_err(ep
->chip
,
345 "Unable to submit urb #%d: %d (urb %p)\n",
346 ctx
->index
, err
, ctx
->urb
);
348 set_bit(ctx
->index
, &ep
->active_mask
);
353 * complete callback for urbs
355 static void snd_complete_urb(struct urb
*urb
)
357 struct snd_urb_ctx
*ctx
= urb
->context
;
358 struct snd_usb_endpoint
*ep
= ctx
->ep
;
359 struct snd_pcm_substream
*substream
;
363 if (unlikely(urb
->status
== -ENOENT
|| /* unlinked */
364 urb
->status
== -ENODEV
|| /* device removed */
365 urb
->status
== -ECONNRESET
|| /* unlinked */
366 urb
->status
== -ESHUTDOWN
)) /* device disabled */
368 /* device disconnected */
369 if (unlikely(atomic_read(&ep
->chip
->shutdown
)))
372 if (unlikely(!test_bit(EP_FLAG_RUNNING
, &ep
->flags
)))
375 if (usb_pipeout(ep
->pipe
)) {
376 retire_outbound_urb(ep
, ctx
);
377 /* can be stopped during retire callback */
378 if (unlikely(!test_bit(EP_FLAG_RUNNING
, &ep
->flags
)))
381 if (snd_usb_endpoint_implicit_feedback_sink(ep
)) {
382 spin_lock_irqsave(&ep
->lock
, flags
);
383 list_add_tail(&ctx
->ready_list
, &ep
->ready_playback_urbs
);
384 spin_unlock_irqrestore(&ep
->lock
, flags
);
385 queue_pending_output_urbs(ep
);
390 prepare_outbound_urb(ep
, ctx
);
391 /* can be stopped during prepare callback */
392 if (unlikely(!test_bit(EP_FLAG_RUNNING
, &ep
->flags
)))
395 retire_inbound_urb(ep
, ctx
);
396 /* can be stopped during retire callback */
397 if (unlikely(!test_bit(EP_FLAG_RUNNING
, &ep
->flags
)))
400 prepare_inbound_urb(ep
, ctx
);
403 err
= usb_submit_urb(urb
, GFP_ATOMIC
);
407 usb_audio_err(ep
->chip
, "cannot submit urb (err = %d)\n", err
);
408 if (ep
->data_subs
&& ep
->data_subs
->pcm_substream
) {
409 substream
= ep
->data_subs
->pcm_substream
;
410 snd_pcm_stop_xrun(substream
);
414 clear_bit(ctx
->index
, &ep
->active_mask
);
418 * snd_usb_add_endpoint: Add an endpoint to an USB audio chip
421 * @alts: The USB host interface
422 * @ep_num: The number of the endpoint to use
423 * @direction: SNDRV_PCM_STREAM_PLAYBACK or SNDRV_PCM_STREAM_CAPTURE
424 * @type: SND_USB_ENDPOINT_TYPE_DATA or SND_USB_ENDPOINT_TYPE_SYNC
426 * If the requested endpoint has not been added to the given chip before,
427 * a new instance is created. Otherwise, a pointer to the previoulsy
428 * created instance is returned. In case of any error, NULL is returned.
430 * New endpoints will be added to chip->ep_list and must be freed by
431 * calling snd_usb_endpoint_free().
433 * For SND_USB_ENDPOINT_TYPE_SYNC, the caller needs to guarantee that
434 * bNumEndpoints > 1 beforehand.
436 struct snd_usb_endpoint
*snd_usb_add_endpoint(struct snd_usb_audio
*chip
,
437 struct usb_host_interface
*alts
,
438 int ep_num
, int direction
, int type
)
440 struct snd_usb_endpoint
*ep
;
441 int is_playback
= direction
== SNDRV_PCM_STREAM_PLAYBACK
;
446 mutex_lock(&chip
->mutex
);
448 list_for_each_entry(ep
, &chip
->ep_list
, list
) {
449 if (ep
->ep_num
== ep_num
&&
450 ep
->iface
== alts
->desc
.bInterfaceNumber
&&
451 ep
->altsetting
== alts
->desc
.bAlternateSetting
) {
452 usb_audio_dbg(ep
->chip
,
453 "Re-using EP %x in iface %d,%d @%p\n",
454 ep_num
, ep
->iface
, ep
->altsetting
, ep
);
459 usb_audio_dbg(chip
, "Creating new %s %s endpoint #%x\n",
460 is_playback
? "playback" : "capture",
461 type
== SND_USB_ENDPOINT_TYPE_DATA
? "data" : "sync",
464 ep
= kzalloc(sizeof(*ep
), GFP_KERNEL
);
469 spin_lock_init(&ep
->lock
);
472 ep
->iface
= alts
->desc
.bInterfaceNumber
;
473 ep
->altsetting
= alts
->desc
.bAlternateSetting
;
474 INIT_LIST_HEAD(&ep
->ready_playback_urbs
);
475 ep_num
&= USB_ENDPOINT_NUMBER_MASK
;
478 ep
->pipe
= usb_sndisocpipe(chip
->dev
, ep_num
);
480 ep
->pipe
= usb_rcvisocpipe(chip
->dev
, ep_num
);
482 if (type
== SND_USB_ENDPOINT_TYPE_SYNC
) {
483 if (get_endpoint(alts
, 1)->bLength
>= USB_DT_ENDPOINT_AUDIO_SIZE
&&
484 get_endpoint(alts
, 1)->bRefresh
>= 1 &&
485 get_endpoint(alts
, 1)->bRefresh
<= 9)
486 ep
->syncinterval
= get_endpoint(alts
, 1)->bRefresh
;
487 else if (snd_usb_get_speed(chip
->dev
) == USB_SPEED_FULL
)
488 ep
->syncinterval
= 1;
489 else if (get_endpoint(alts
, 1)->bInterval
>= 1 &&
490 get_endpoint(alts
, 1)->bInterval
<= 16)
491 ep
->syncinterval
= get_endpoint(alts
, 1)->bInterval
- 1;
493 ep
->syncinterval
= 3;
495 ep
->syncmaxsize
= le16_to_cpu(get_endpoint(alts
, 1)->wMaxPacketSize
);
498 list_add_tail(&ep
->list
, &chip
->ep_list
);
500 ep
->is_implicit_feedback
= 0;
503 mutex_unlock(&chip
->mutex
);
509 * wait until all urbs are processed.
511 static int wait_clear_urbs(struct snd_usb_endpoint
*ep
)
513 unsigned long end_time
= jiffies
+ msecs_to_jiffies(1000);
517 alive
= bitmap_weight(&ep
->active_mask
, ep
->nurbs
);
521 schedule_timeout_uninterruptible(1);
522 } while (time_before(jiffies
, end_time
));
525 usb_audio_err(ep
->chip
,
526 "timeout: still %d active urbs on EP #%x\n",
528 clear_bit(EP_FLAG_STOPPING
, &ep
->flags
);
530 ep
->data_subs
= NULL
;
531 ep
->sync_slave
= NULL
;
532 ep
->retire_data_urb
= NULL
;
533 ep
->prepare_data_urb
= NULL
;
538 /* sync the pending stop operation;
539 * this function itself doesn't trigger the stop operation
541 void snd_usb_endpoint_sync_pending_stop(struct snd_usb_endpoint
*ep
)
543 if (ep
&& test_bit(EP_FLAG_STOPPING
, &ep
->flags
))
548 * unlink active urbs.
550 static int deactivate_urbs(struct snd_usb_endpoint
*ep
, bool force
)
554 if (!force
&& atomic_read(&ep
->chip
->shutdown
)) /* to be sure... */
557 clear_bit(EP_FLAG_RUNNING
, &ep
->flags
);
559 INIT_LIST_HEAD(&ep
->ready_playback_urbs
);
560 ep
->next_packet_read_pos
= 0;
561 ep
->next_packet_write_pos
= 0;
563 for (i
= 0; i
< ep
->nurbs
; i
++) {
564 if (test_bit(i
, &ep
->active_mask
)) {
565 if (!test_and_set_bit(i
, &ep
->unlink_mask
)) {
566 struct urb
*u
= ep
->urb
[i
].urb
;
576 * release an endpoint's urbs
578 static void release_urbs(struct snd_usb_endpoint
*ep
, int force
)
582 /* route incoming urbs to nirvana */
583 ep
->retire_data_urb
= NULL
;
584 ep
->prepare_data_urb
= NULL
;
587 deactivate_urbs(ep
, force
);
590 for (i
= 0; i
< ep
->nurbs
; i
++)
591 release_urb_ctx(&ep
->urb
[i
]);
594 usb_free_coherent(ep
->chip
->dev
, SYNC_URBS
* 4,
595 ep
->syncbuf
, ep
->sync_dma
);
602 * Check data endpoint for format differences
604 static bool check_ep_params(struct snd_usb_endpoint
*ep
,
605 snd_pcm_format_t pcm_format
,
606 unsigned int channels
,
607 unsigned int period_bytes
,
608 unsigned int frames_per_period
,
609 unsigned int periods_per_buffer
,
610 struct audioformat
*fmt
,
611 struct snd_usb_endpoint
*sync_ep
)
613 unsigned int maxsize
, minsize
, packs_per_ms
, max_packs_per_urb
;
614 unsigned int max_packs_per_period
, urbs_per_period
, urb_packs
;
615 unsigned int max_urbs
;
616 int frame_bits
= snd_pcm_format_physical_width(pcm_format
) * channels
;
617 int tx_length_quirk
= (ep
->chip
->tx_length_quirk
&&
618 usb_pipeout(ep
->pipe
));
621 if (pcm_format
== SNDRV_PCM_FORMAT_DSD_U16_LE
&& fmt
->dsd_dop
) {
623 * When operating in DSD DOP mode, the size of a sample frame
624 * in hardware differs from the actual physical format width
625 * because we need to make room for the DOP markers.
627 frame_bits
+= channels
<< 3;
630 ret
= ret
&& (ep
->datainterval
== fmt
->datainterval
);
631 ret
= ret
&& (ep
->stride
== frame_bits
>> 3);
633 switch (pcm_format
) {
634 case SNDRV_PCM_FORMAT_U8
:
635 ret
= ret
&& (ep
->silence_value
== 0x80);
637 case SNDRV_PCM_FORMAT_DSD_U8
:
638 case SNDRV_PCM_FORMAT_DSD_U16_LE
:
639 case SNDRV_PCM_FORMAT_DSD_U32_LE
:
640 case SNDRV_PCM_FORMAT_DSD_U16_BE
:
641 case SNDRV_PCM_FORMAT_DSD_U32_BE
:
642 ret
= ret
&& (ep
->silence_value
== 0x69);
645 ret
= ret
&& (ep
->silence_value
== 0);
648 /* assume max. frequency is 50% higher than nominal */
649 ret
= ret
&& (ep
->freqmax
== ep
->freqn
+ (ep
->freqn
>> 1));
650 /* Round up freqmax to nearest integer in order to calculate maximum
651 * packet size, which must represent a whole number of frames.
652 * This is accomplished by adding 0x0.ffff before converting the
653 * Q16.16 format into integer.
654 * In order to accurately calculate the maximum packet size when
655 * the data interval is more than 1 (i.e. ep->datainterval > 0),
656 * multiply by the data interval prior to rounding. For instance,
657 * a freqmax of 41 kHz will result in a max packet size of 6 (5.125)
658 * frames with a data interval of 1, but 11 (10.25) frames with a
659 * data interval of 2.
660 * (ep->freqmax << ep->datainterval overflows at 8.192 MHz for the
661 * maximum datainterval value of 3, at USB full speed, higher for
662 * USB high speed, noting that ep->freqmax is in units of
663 * frames per packet in Q16.16 format.)
665 maxsize
= (((ep
->freqmax
<< ep
->datainterval
) + 0xffff) >> 16) *
668 maxsize
+= sizeof(__le32
); /* Space for length descriptor */
669 /* but wMaxPacketSize might reduce this */
670 if (ep
->maxpacksize
&& ep
->maxpacksize
< maxsize
) {
671 /* whatever fits into a max. size packet */
672 unsigned int data_maxsize
= maxsize
= ep
->maxpacksize
;
675 /* Need to remove the length descriptor to calc freq */
676 data_maxsize
-= sizeof(__le32
);
677 ret
= ret
&& (ep
->freqmax
== (data_maxsize
/ (frame_bits
>> 3))
678 << (16 - ep
->datainterval
));
682 ret
= ret
&& (ep
->curpacksize
== ep
->maxpacksize
);
684 ret
= ret
&& (ep
->curpacksize
== maxsize
);
686 if (snd_usb_get_speed(ep
->chip
->dev
) != USB_SPEED_FULL
) {
687 packs_per_ms
= 8 >> ep
->datainterval
;
688 max_packs_per_urb
= MAX_PACKS_HS
;
691 max_packs_per_urb
= MAX_PACKS
;
693 if (sync_ep
&& !snd_usb_endpoint_implicit_feedback_sink(ep
))
694 max_packs_per_urb
= min(max_packs_per_urb
,
695 1U << sync_ep
->syncinterval
);
696 max_packs_per_urb
= max(1u, max_packs_per_urb
>> ep
->datainterval
);
699 * Capture endpoints need to use small URBs because there's no way
700 * to tell in advance where the next period will end, and we don't
701 * want the next URB to complete much after the period ends.
703 * Playback endpoints with implicit sync much use the same parameters
704 * as their corresponding capture endpoint.
706 if (usb_pipein(ep
->pipe
) ||
707 snd_usb_endpoint_implicit_feedback_sink(ep
)) {
709 urb_packs
= packs_per_ms
;
711 * Wireless devices can poll at a max rate of once per 4ms.
712 * For dataintervals less than 5, increase the packet count to
713 * allow the host controller to use bursting to fill in the
716 if (snd_usb_get_speed(ep
->chip
->dev
) == USB_SPEED_WIRELESS
) {
717 int interval
= ep
->datainterval
;
719 while (interval
< 5) {
724 /* make capture URBs <= 1 ms and smaller than a period */
725 urb_packs
= min(max_packs_per_urb
, urb_packs
);
726 while (urb_packs
> 1 && urb_packs
* maxsize
>= period_bytes
)
728 ret
= ret
&& (ep
->nurbs
== MAX_URBS
);
731 * Playback endpoints without implicit sync are adjusted so that
732 * a period fits as evenly as possible in the smallest number of
733 * URBs. The total number of URBs is adjusted to the size of the
734 * ALSA buffer, subject to the MAX_URBS and MAX_QUEUE limits.
737 /* determine how small a packet can be */
738 minsize
= (ep
->freqn
>> (16 - ep
->datainterval
)) *
740 /* with sync from device, assume it can be 12% lower */
742 minsize
-= minsize
>> 3;
743 minsize
= max(minsize
, 1u);
745 /* how many packets will contain an entire ALSA period? */
746 max_packs_per_period
= DIV_ROUND_UP(period_bytes
, minsize
);
748 /* how many URBs will contain a period? */
749 urbs_per_period
= DIV_ROUND_UP(max_packs_per_period
,
751 /* how many packets are needed in each URB? */
752 urb_packs
= DIV_ROUND_UP(max_packs_per_period
, urbs_per_period
);
754 /* limit the number of frames in a single URB */
755 ret
= ret
&& (ep
->max_urb_frames
==
756 DIV_ROUND_UP(frames_per_period
, urbs_per_period
));
758 /* try to use enough URBs to contain an entire ALSA buffer */
759 max_urbs
= min((unsigned) MAX_URBS
,
760 MAX_QUEUE
* packs_per_ms
/ urb_packs
);
761 ret
= ret
&& (ep
->nurbs
== min(max_urbs
,
762 urbs_per_period
* periods_per_buffer
));
765 ret
= ret
&& (ep
->datainterval
== fmt
->datainterval
);
766 ret
= ret
&& (ep
->maxpacksize
== fmt
->maxpacksize
);
768 (ep
->fill_max
== !!(fmt
->attributes
& UAC_EP_CS_ATTR_FILL_MAX
));
774 * configure a data endpoint
776 static int data_ep_set_params(struct snd_usb_endpoint
*ep
,
777 snd_pcm_format_t pcm_format
,
778 unsigned int channels
,
779 unsigned int period_bytes
,
780 unsigned int frames_per_period
,
781 unsigned int periods_per_buffer
,
782 struct audioformat
*fmt
,
783 struct snd_usb_endpoint
*sync_ep
)
785 unsigned int maxsize
, minsize
, packs_per_ms
, max_packs_per_urb
;
786 unsigned int max_packs_per_period
, urbs_per_period
, urb_packs
;
787 unsigned int max_urbs
, i
;
788 int frame_bits
= snd_pcm_format_physical_width(pcm_format
) * channels
;
789 int tx_length_quirk
= (ep
->chip
->tx_length_quirk
&&
790 usb_pipeout(ep
->pipe
));
792 if (pcm_format
== SNDRV_PCM_FORMAT_DSD_U16_LE
&& fmt
->dsd_dop
) {
794 * When operating in DSD DOP mode, the size of a sample frame
795 * in hardware differs from the actual physical format width
796 * because we need to make room for the DOP markers.
798 frame_bits
+= channels
<< 3;
801 ep
->datainterval
= fmt
->datainterval
;
802 ep
->stride
= frame_bits
>> 3;
804 switch (pcm_format
) {
805 case SNDRV_PCM_FORMAT_U8
:
806 ep
->silence_value
= 0x80;
808 case SNDRV_PCM_FORMAT_DSD_U8
:
809 case SNDRV_PCM_FORMAT_DSD_U16_LE
:
810 case SNDRV_PCM_FORMAT_DSD_U32_LE
:
811 case SNDRV_PCM_FORMAT_DSD_U16_BE
:
812 case SNDRV_PCM_FORMAT_DSD_U32_BE
:
813 ep
->silence_value
= 0x69;
816 ep
->silence_value
= 0;
819 /* assume max. frequency is 50% higher than nominal */
820 ep
->freqmax
= ep
->freqn
+ (ep
->freqn
>> 1);
821 /* Round up freqmax to nearest integer in order to calculate maximum
822 * packet size, which must represent a whole number of frames.
823 * This is accomplished by adding 0x0.ffff before converting the
824 * Q16.16 format into integer.
825 * In order to accurately calculate the maximum packet size when
826 * the data interval is more than 1 (i.e. ep->datainterval > 0),
827 * multiply by the data interval prior to rounding. For instance,
828 * a freqmax of 41 kHz will result in a max packet size of 6 (5.125)
829 * frames with a data interval of 1, but 11 (10.25) frames with a
830 * data interval of 2.
831 * (ep->freqmax << ep->datainterval overflows at 8.192 MHz for the
832 * maximum datainterval value of 3, at USB full speed, higher for
833 * USB high speed, noting that ep->freqmax is in units of
834 * frames per packet in Q16.16 format.)
836 maxsize
= (((ep
->freqmax
<< ep
->datainterval
) + 0xffff) >> 16) *
839 maxsize
+= sizeof(__le32
); /* Space for length descriptor */
840 /* but wMaxPacketSize might reduce this */
841 if (ep
->maxpacksize
&& ep
->maxpacksize
< maxsize
) {
842 /* whatever fits into a max. size packet */
843 unsigned int data_maxsize
= maxsize
= ep
->maxpacksize
;
846 /* Need to remove the length descriptor to calc freq */
847 data_maxsize
-= sizeof(__le32
);
848 ep
->freqmax
= (data_maxsize
/ (frame_bits
>> 3))
849 << (16 - ep
->datainterval
);
853 ep
->curpacksize
= ep
->maxpacksize
;
855 ep
->curpacksize
= maxsize
;
857 if (snd_usb_get_speed(ep
->chip
->dev
) != USB_SPEED_FULL
) {
858 packs_per_ms
= 8 >> ep
->datainterval
;
859 max_packs_per_urb
= MAX_PACKS_HS
;
862 max_packs_per_urb
= MAX_PACKS
;
864 if (sync_ep
&& !snd_usb_endpoint_implicit_feedback_sink(ep
))
865 max_packs_per_urb
= min(max_packs_per_urb
,
866 1U << sync_ep
->syncinterval
);
867 max_packs_per_urb
= max(1u, max_packs_per_urb
>> ep
->datainterval
);
870 * Capture endpoints need to use small URBs because there's no way
871 * to tell in advance where the next period will end, and we don't
872 * want the next URB to complete much after the period ends.
874 * Playback endpoints with implicit sync much use the same parameters
875 * as their corresponding capture endpoint.
877 if (usb_pipein(ep
->pipe
) ||
878 snd_usb_endpoint_implicit_feedback_sink(ep
)) {
880 urb_packs
= packs_per_ms
;
882 * Wireless devices can poll at a max rate of once per 4ms.
883 * For dataintervals less than 5, increase the packet count to
884 * allow the host controller to use bursting to fill in the
887 if (snd_usb_get_speed(ep
->chip
->dev
) == USB_SPEED_WIRELESS
) {
888 int interval
= ep
->datainterval
;
889 while (interval
< 5) {
894 /* make capture URBs <= 1 ms and smaller than a period */
895 urb_packs
= min(max_packs_per_urb
, urb_packs
);
896 while (urb_packs
> 1 && urb_packs
* maxsize
>= period_bytes
)
898 ep
->nurbs
= MAX_URBS
;
901 * Playback endpoints without implicit sync are adjusted so that
902 * a period fits as evenly as possible in the smallest number of
903 * URBs. The total number of URBs is adjusted to the size of the
904 * ALSA buffer, subject to the MAX_URBS and MAX_QUEUE limits.
907 /* determine how small a packet can be */
908 minsize
= (ep
->freqn
>> (16 - ep
->datainterval
)) *
910 /* with sync from device, assume it can be 12% lower */
912 minsize
-= minsize
>> 3;
913 minsize
= max(minsize
, 1u);
915 /* how many packets will contain an entire ALSA period? */
916 max_packs_per_period
= DIV_ROUND_UP(period_bytes
, minsize
);
918 /* how many URBs will contain a period? */
919 urbs_per_period
= DIV_ROUND_UP(max_packs_per_period
,
921 /* how many packets are needed in each URB? */
922 urb_packs
= DIV_ROUND_UP(max_packs_per_period
, urbs_per_period
);
924 /* limit the number of frames in a single URB */
925 ep
->max_urb_frames
= DIV_ROUND_UP(frames_per_period
,
928 /* try to use enough URBs to contain an entire ALSA buffer */
929 max_urbs
= min((unsigned) MAX_URBS
,
930 MAX_QUEUE
* packs_per_ms
/ urb_packs
);
931 ep
->nurbs
= min(max_urbs
, urbs_per_period
* periods_per_buffer
);
934 /* allocate and initialize data urbs */
935 for (i
= 0; i
< ep
->nurbs
; i
++) {
936 struct snd_urb_ctx
*u
= &ep
->urb
[i
];
939 u
->packets
= urb_packs
;
940 u
->buffer_size
= maxsize
* u
->packets
;
942 if (fmt
->fmt_type
== UAC_FORMAT_TYPE_II
)
943 u
->packets
++; /* for transfer delimiter */
944 u
->urb
= usb_alloc_urb(u
->packets
, GFP_KERNEL
);
948 u
->urb
->transfer_buffer
=
949 usb_alloc_coherent(ep
->chip
->dev
, u
->buffer_size
,
950 GFP_KERNEL
, &u
->urb
->transfer_dma
);
951 if (!u
->urb
->transfer_buffer
)
953 u
->urb
->pipe
= ep
->pipe
;
954 u
->urb
->transfer_flags
= URB_NO_TRANSFER_DMA_MAP
;
955 u
->urb
->interval
= 1 << ep
->datainterval
;
957 u
->urb
->complete
= snd_complete_urb
;
958 INIT_LIST_HEAD(&u
->ready_list
);
969 * configure a sync endpoint
971 static int sync_ep_set_params(struct snd_usb_endpoint
*ep
)
975 ep
->syncbuf
= usb_alloc_coherent(ep
->chip
->dev
, SYNC_URBS
* 4,
976 GFP_KERNEL
, &ep
->sync_dma
);
980 for (i
= 0; i
< SYNC_URBS
; i
++) {
981 struct snd_urb_ctx
*u
= &ep
->urb
[i
];
985 u
->urb
= usb_alloc_urb(1, GFP_KERNEL
);
988 u
->urb
->transfer_buffer
= ep
->syncbuf
+ i
* 4;
989 u
->urb
->transfer_dma
= ep
->sync_dma
+ i
* 4;
990 u
->urb
->transfer_buffer_length
= 4;
991 u
->urb
->pipe
= ep
->pipe
;
992 u
->urb
->transfer_flags
= URB_NO_TRANSFER_DMA_MAP
;
993 u
->urb
->number_of_packets
= 1;
994 u
->urb
->interval
= 1 << ep
->syncinterval
;
996 u
->urb
->complete
= snd_complete_urb
;
999 ep
->nurbs
= SYNC_URBS
;
1004 release_urbs(ep
, 0);
1009 * snd_usb_endpoint_set_params: configure an snd_usb_endpoint
1011 * @ep: the snd_usb_endpoint to configure
1012 * @pcm_format: the audio fomat.
1013 * @channels: the number of audio channels.
1014 * @period_bytes: the number of bytes in one alsa period.
1015 * @period_frames: the number of frames in one alsa period.
1016 * @buffer_periods: the number of periods in one alsa buffer.
1017 * @rate: the frame rate.
1018 * @fmt: the USB audio format information
1019 * @sync_ep: the sync endpoint to use, if any
1021 * Determine the number of URBs to be used on this endpoint.
1022 * An endpoint must be configured before it can be started.
1023 * An endpoint that is already running can not be reconfigured.
1025 int snd_usb_endpoint_set_params(struct snd_usb_endpoint
*ep
,
1026 snd_pcm_format_t pcm_format
,
1027 unsigned int channels
,
1028 unsigned int period_bytes
,
1029 unsigned int period_frames
,
1030 unsigned int buffer_periods
,
1032 struct audioformat
*fmt
,
1033 struct snd_usb_endpoint
*sync_ep
)
1037 if (ep
->use_count
!= 0) {
1038 bool check
= ep
->is_implicit_feedback
&&
1039 check_ep_params(ep
, pcm_format
,
1040 channels
, period_bytes
,
1041 period_frames
, buffer_periods
,
1045 usb_audio_warn(ep
->chip
,
1046 "Unable to change format on ep #%x: already in use\n",
1051 usb_audio_dbg(ep
->chip
,
1052 "Ep #%x already in use as implicit feedback but format not changed\n",
1057 /* release old buffers, if any */
1058 release_urbs(ep
, 0);
1060 ep
->datainterval
= fmt
->datainterval
;
1061 ep
->maxpacksize
= fmt
->maxpacksize
;
1062 ep
->fill_max
= !!(fmt
->attributes
& UAC_EP_CS_ATTR_FILL_MAX
);
1064 if (snd_usb_get_speed(ep
->chip
->dev
) == USB_SPEED_FULL
)
1065 ep
->freqn
= get_usb_full_speed_rate(rate
);
1067 ep
->freqn
= get_usb_high_speed_rate(rate
);
1069 /* calculate the frequency in 16.16 format */
1070 ep
->freqm
= ep
->freqn
;
1071 ep
->freqshift
= INT_MIN
;
1076 case SND_USB_ENDPOINT_TYPE_DATA
:
1077 err
= data_ep_set_params(ep
, pcm_format
, channels
,
1078 period_bytes
, period_frames
,
1079 buffer_periods
, fmt
, sync_ep
);
1081 case SND_USB_ENDPOINT_TYPE_SYNC
:
1082 err
= sync_ep_set_params(ep
);
1088 usb_audio_dbg(ep
->chip
,
1089 "Setting params for ep #%x (type %d, %d urbs), ret=%d\n",
1090 ep
->ep_num
, ep
->type
, ep
->nurbs
, err
);
1096 * snd_usb_endpoint_start: start an snd_usb_endpoint
1098 * @ep: the endpoint to start
1100 * A call to this function will increment the use count of the endpoint.
1101 * In case it is not already running, the URBs for this endpoint will be
1102 * submitted. Otherwise, this function does nothing.
1104 * Must be balanced to calls of snd_usb_endpoint_stop().
1106 * Returns an error if the URB submission failed, 0 in all other cases.
1108 int snd_usb_endpoint_start(struct snd_usb_endpoint
*ep
)
1113 if (atomic_read(&ep
->chip
->shutdown
))
1116 /* already running? */
1117 if (++ep
->use_count
!= 1)
1120 /* just to be sure */
1121 deactivate_urbs(ep
, false);
1123 ep
->active_mask
= 0;
1124 ep
->unlink_mask
= 0;
1127 snd_usb_endpoint_start_quirk(ep
);
1130 * If this endpoint has a data endpoint as implicit feedback source,
1131 * don't start the urbs here. Instead, mark them all as available,
1132 * wait for the record urbs to return and queue the playback urbs
1133 * from that context.
1136 set_bit(EP_FLAG_RUNNING
, &ep
->flags
);
1138 if (snd_usb_endpoint_implicit_feedback_sink(ep
)) {
1139 for (i
= 0; i
< ep
->nurbs
; i
++) {
1140 struct snd_urb_ctx
*ctx
= ep
->urb
+ i
;
1141 list_add_tail(&ctx
->ready_list
, &ep
->ready_playback_urbs
);
1147 for (i
= 0; i
< ep
->nurbs
; i
++) {
1148 struct urb
*urb
= ep
->urb
[i
].urb
;
1150 if (snd_BUG_ON(!urb
))
1153 if (usb_pipeout(ep
->pipe
)) {
1154 prepare_outbound_urb(ep
, urb
->context
);
1156 prepare_inbound_urb(ep
, urb
->context
);
1159 err
= usb_submit_urb(urb
, GFP_ATOMIC
);
1161 usb_audio_err(ep
->chip
,
1162 "cannot submit urb %d, error %d: %s\n",
1163 i
, err
, usb_error_string(err
));
1166 set_bit(i
, &ep
->active_mask
);
1172 clear_bit(EP_FLAG_RUNNING
, &ep
->flags
);
1174 deactivate_urbs(ep
, false);
1179 * snd_usb_endpoint_stop: stop an snd_usb_endpoint
1181 * @ep: the endpoint to stop (may be NULL)
1183 * A call to this function will decrement the use count of the endpoint.
1184 * In case the last user has requested the endpoint stop, the URBs will
1185 * actually be deactivated.
1187 * Must be balanced to calls of snd_usb_endpoint_start().
1189 * The caller needs to synchronize the pending stop operation via
1190 * snd_usb_endpoint_sync_pending_stop().
1192 void snd_usb_endpoint_stop(struct snd_usb_endpoint
*ep
)
1197 if (snd_BUG_ON(ep
->use_count
== 0))
1200 if (--ep
->use_count
== 0) {
1201 deactivate_urbs(ep
, false);
1202 set_bit(EP_FLAG_STOPPING
, &ep
->flags
);
1207 * snd_usb_endpoint_deactivate: deactivate an snd_usb_endpoint
1209 * @ep: the endpoint to deactivate
1211 * If the endpoint is not currently in use, this functions will
1212 * deactivate its associated URBs.
1214 * In case of any active users, this functions does nothing.
1216 void snd_usb_endpoint_deactivate(struct snd_usb_endpoint
*ep
)
1221 if (ep
->use_count
!= 0)
1224 deactivate_urbs(ep
, true);
1225 wait_clear_urbs(ep
);
1229 * snd_usb_endpoint_release: Tear down an snd_usb_endpoint
1231 * @ep: the endpoint to release
1233 * This function does not care for the endpoint's use count but will tear
1234 * down all the streaming URBs immediately.
1236 void snd_usb_endpoint_release(struct snd_usb_endpoint
*ep
)
1238 release_urbs(ep
, 1);
1242 * snd_usb_endpoint_free: Free the resources of an snd_usb_endpoint
1244 * @ep: the endpoint to free
1246 * This free all resources of the given ep.
1248 void snd_usb_endpoint_free(struct snd_usb_endpoint
*ep
)
1254 * snd_usb_handle_sync_urb: parse an USB sync packet
1256 * @ep: the endpoint to handle the packet
1257 * @sender: the sending endpoint
1258 * @urb: the received packet
1260 * This function is called from the context of an endpoint that received
1261 * the packet and is used to let another endpoint object handle the payload.
1263 void snd_usb_handle_sync_urb(struct snd_usb_endpoint
*ep
,
1264 struct snd_usb_endpoint
*sender
,
1265 const struct urb
*urb
)
1269 unsigned long flags
;
1271 snd_BUG_ON(ep
== sender
);
1274 * In case the endpoint is operating in implicit feedback mode, prepare
1275 * a new outbound URB that has the same layout as the received packet
1276 * and add it to the list of pending urbs. queue_pending_output_urbs()
1277 * will take care of them later.
1279 if (snd_usb_endpoint_implicit_feedback_sink(ep
) &&
1280 ep
->use_count
!= 0) {
1282 /* implicit feedback case */
1284 struct snd_urb_ctx
*in_ctx
;
1285 struct snd_usb_packet_info
*out_packet
;
1287 in_ctx
= urb
->context
;
1289 /* Count overall packet size */
1290 for (i
= 0; i
< in_ctx
->packets
; i
++)
1291 if (urb
->iso_frame_desc
[i
].status
== 0)
1292 bytes
+= urb
->iso_frame_desc
[i
].actual_length
;
1295 * skip empty packets. At least M-Audio's Fast Track Ultra stops
1296 * streaming once it received a 0-byte OUT URB
1301 spin_lock_irqsave(&ep
->lock
, flags
);
1302 out_packet
= ep
->next_packet
+ ep
->next_packet_write_pos
;
1305 * Iterate through the inbound packet and prepare the lengths
1306 * for the output packet. The OUT packet we are about to send
1307 * will have the same amount of payload bytes per stride as the
1308 * IN packet we just received. Since the actual size is scaled
1309 * by the stride, use the sender stride to calculate the length
1310 * in case the number of channels differ between the implicitly
1311 * fed-back endpoint and the synchronizing endpoint.
1314 out_packet
->packets
= in_ctx
->packets
;
1315 for (i
= 0; i
< in_ctx
->packets
; i
++) {
1316 if (urb
->iso_frame_desc
[i
].status
== 0)
1317 out_packet
->packet_size
[i
] =
1318 urb
->iso_frame_desc
[i
].actual_length
/ sender
->stride
;
1320 out_packet
->packet_size
[i
] = 0;
1323 ep
->next_packet_write_pos
++;
1324 ep
->next_packet_write_pos
%= MAX_URBS
;
1325 spin_unlock_irqrestore(&ep
->lock
, flags
);
1326 queue_pending_output_urbs(ep
);
1332 * process after playback sync complete
1334 * Full speed devices report feedback values in 10.14 format as samples
1335 * per frame, high speed devices in 16.16 format as samples per
1338 * Because the Audio Class 1 spec was written before USB 2.0, many high
1339 * speed devices use a wrong interpretation, some others use an
1340 * entirely different format.
1342 * Therefore, we cannot predict what format any particular device uses
1343 * and must detect it automatically.
1346 if (urb
->iso_frame_desc
[0].status
!= 0 ||
1347 urb
->iso_frame_desc
[0].actual_length
< 3)
1350 f
= le32_to_cpup(urb
->transfer_buffer
);
1351 if (urb
->iso_frame_desc
[0].actual_length
== 3)
1359 if (unlikely(sender
->tenor_fb_quirk
)) {
1361 * Devices based on Tenor 8802 chipsets (TEAC UD-H01
1362 * and others) sometimes change the feedback value
1365 if (f
< ep
->freqn
- 0x8000)
1367 else if (f
> ep
->freqn
+ 0x8000)
1369 } else if (unlikely(ep
->freqshift
== INT_MIN
)) {
1371 * The first time we see a feedback value, determine its format
1372 * by shifting it left or right until it matches the nominal
1373 * frequency value. This assumes that the feedback does not
1374 * differ from the nominal value more than +50% or -25%.
1377 while (f
< ep
->freqn
- ep
->freqn
/ 4) {
1381 while (f
> ep
->freqn
+ ep
->freqn
/ 2) {
1385 ep
->freqshift
= shift
;
1386 } else if (ep
->freqshift
>= 0)
1387 f
<<= ep
->freqshift
;
1389 f
>>= -ep
->freqshift
;
1391 if (likely(f
>= ep
->freqn
- ep
->freqn
/ 8 && f
<= ep
->freqmax
)) {
1393 * If the frequency looks valid, set it.
1394 * This value is referred to in prepare_playback_urb().
1396 spin_lock_irqsave(&ep
->lock
, flags
);
1398 spin_unlock_irqrestore(&ep
->lock
, flags
);
1401 * Out of range; maybe the shift value is wrong.
1402 * Reset it so that we autodetect again the next time.
1404 ep
->freqshift
= INT_MIN
;