GNU Linux-libre 5.4.257-gnu1
[releases.git] / sound / usb / endpoint.c
1 // SPDX-License-Identifier: GPL-2.0-or-later
2 /*
3  */
4
5 #include <linux/gfp.h>
6 #include <linux/init.h>
7 #include <linux/ratelimit.h>
8 #include <linux/usb.h>
9 #include <linux/usb/audio.h>
10 #include <linux/slab.h>
11
12 #include <sound/core.h>
13 #include <sound/pcm.h>
14 #include <sound/pcm_params.h>
15
16 #include "usbaudio.h"
17 #include "helper.h"
18 #include "card.h"
19 #include "endpoint.h"
20 #include "pcm.h"
21 #include "quirks.h"
22
23 #define EP_FLAG_RUNNING         1
24 #define EP_FLAG_STOPPING        2
25
26 /*
27  * snd_usb_endpoint is a model that abstracts everything related to an
28  * USB endpoint and its streaming.
29  *
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.
34  *
35  * There are two different types of endpoints in audio applications.
36  *
37  * SND_USB_ENDPOINT_TYPE_DATA handles full audio data payload for both
38  * inbound and outbound traffic.
39  *
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
42  * (3 or 4 bytes).
43  *
44  * Each endpoint has to be configured prior to being used by calling
45  * snd_usb_endpoint_set_params().
46  *
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.
51  */
52
53 /*
54  * convert a sampling rate into our full speed format (fs/1000 in Q16.16)
55  * this will overflow at approx 524 kHz
56  */
57 static inline unsigned get_usb_full_speed_rate(unsigned int rate)
58 {
59         return ((rate << 13) + 62) / 125;
60 }
61
62 /*
63  * convert a sampling rate into USB high speed format (fs/8000 in Q16.16)
64  * this will overflow at approx 4 MHz
65  */
66 static inline unsigned get_usb_high_speed_rate(unsigned int rate)
67 {
68         return ((rate << 10) + 62) / 125;
69 }
70
71 /*
72  * release a urb data
73  */
74 static void release_urb_ctx(struct snd_urb_ctx *u)
75 {
76         if (u->urb && u->buffer_size)
77                 usb_free_coherent(u->ep->chip->dev, u->buffer_size,
78                                   u->urb->transfer_buffer,
79                                   u->urb->transfer_dma);
80         usb_free_urb(u->urb);
81         u->urb = NULL;
82         u->buffer_size = 0;
83 }
84
85 static const char *usb_error_string(int err)
86 {
87         switch (err) {
88         case -ENODEV:
89                 return "no device";
90         case -ENOENT:
91                 return "endpoint not enabled";
92         case -EPIPE:
93                 return "endpoint stalled";
94         case -ENOSPC:
95                 return "not enough bandwidth";
96         case -ESHUTDOWN:
97                 return "device disabled";
98         case -EHOSTUNREACH:
99                 return "device suspended";
100         case -EINVAL:
101         case -EAGAIN:
102         case -EFBIG:
103         case -EMSGSIZE:
104                 return "internal error";
105         default:
106                 return "unknown error";
107         }
108 }
109
110 /**
111  * snd_usb_endpoint_implicit_feedback_sink: Report endpoint usage type
112  *
113  * @ep: The snd_usb_endpoint
114  *
115  * Determine whether an endpoint is driven by an implicit feedback
116  * data endpoint source.
117  */
118 int snd_usb_endpoint_implicit_feedback_sink(struct snd_usb_endpoint *ep)
119 {
120         return  ep->sync_master &&
121                 ep->sync_master->type == SND_USB_ENDPOINT_TYPE_DATA &&
122                 ep->type == SND_USB_ENDPOINT_TYPE_DATA &&
123                 usb_pipeout(ep->pipe);
124 }
125
126 /*
127  * For streaming based on information derived from sync endpoints,
128  * prepare_outbound_urb_sizes() will call next_packet_size() to
129  * determine the number of samples to be sent in the next packet.
130  *
131  * For implicit feedback, next_packet_size() is unused.
132  */
133 int snd_usb_endpoint_next_packet_size(struct snd_usb_endpoint *ep)
134 {
135         unsigned long flags;
136         int ret;
137
138         if (ep->fill_max)
139                 return ep->maxframesize;
140
141         spin_lock_irqsave(&ep->lock, flags);
142         ep->phase = (ep->phase & 0xffff)
143                 + (ep->freqm << ep->datainterval);
144         ret = min(ep->phase >> 16, ep->maxframesize);
145         spin_unlock_irqrestore(&ep->lock, flags);
146
147         return ret;
148 }
149
150 static void retire_outbound_urb(struct snd_usb_endpoint *ep,
151                                 struct snd_urb_ctx *urb_ctx)
152 {
153         if (ep->retire_data_urb)
154                 ep->retire_data_urb(ep->data_subs, urb_ctx->urb);
155 }
156
157 static void retire_inbound_urb(struct snd_usb_endpoint *ep,
158                                struct snd_urb_ctx *urb_ctx)
159 {
160         struct urb *urb = urb_ctx->urb;
161
162         if (unlikely(ep->skip_packets > 0)) {
163                 ep->skip_packets--;
164                 return;
165         }
166
167         if (ep->sync_slave)
168                 snd_usb_handle_sync_urb(ep->sync_slave, ep, urb);
169
170         if (ep->retire_data_urb)
171                 ep->retire_data_urb(ep->data_subs, urb);
172 }
173
174 static void prepare_silent_urb(struct snd_usb_endpoint *ep,
175                                struct snd_urb_ctx *ctx)
176 {
177         struct urb *urb = ctx->urb;
178         unsigned int offs = 0;
179         unsigned int extra = 0;
180         __le32 packet_length;
181         int i;
182
183         /* For tx_length_quirk, put packet length at start of packet */
184         if (ep->chip->tx_length_quirk)
185                 extra = sizeof(packet_length);
186
187         for (i = 0; i < ctx->packets; ++i) {
188                 unsigned int offset;
189                 unsigned int length;
190                 int counts;
191
192                 if (ctx->packet_size[i])
193                         counts = ctx->packet_size[i];
194                 else
195                         counts = snd_usb_endpoint_next_packet_size(ep);
196
197                 length = counts * ep->stride; /* number of silent bytes */
198                 offset = offs * ep->stride + extra * i;
199                 urb->iso_frame_desc[i].offset = offset;
200                 urb->iso_frame_desc[i].length = length + extra;
201                 if (extra) {
202                         packet_length = cpu_to_le32(length);
203                         memcpy(urb->transfer_buffer + offset,
204                                &packet_length, sizeof(packet_length));
205                 }
206                 memset(urb->transfer_buffer + offset + extra,
207                        ep->silence_value, length);
208                 offs += counts;
209         }
210
211         urb->number_of_packets = ctx->packets;
212         urb->transfer_buffer_length = offs * ep->stride + ctx->packets * extra;
213 }
214
215 /*
216  * Prepare a PLAYBACK urb for submission to the bus.
217  */
218 static void prepare_outbound_urb(struct snd_usb_endpoint *ep,
219                                  struct snd_urb_ctx *ctx)
220 {
221         struct urb *urb = ctx->urb;
222         unsigned char *cp = urb->transfer_buffer;
223
224         urb->dev = ep->chip->dev; /* we need to set this at each time */
225
226         switch (ep->type) {
227         case SND_USB_ENDPOINT_TYPE_DATA:
228                 if (ep->prepare_data_urb) {
229                         ep->prepare_data_urb(ep->data_subs, urb);
230                 } else {
231                         /* no data provider, so send silence */
232                         prepare_silent_urb(ep, ctx);
233                 }
234                 break;
235
236         case SND_USB_ENDPOINT_TYPE_SYNC:
237                 if (snd_usb_get_speed(ep->chip->dev) >= USB_SPEED_HIGH) {
238                         /*
239                          * fill the length and offset of each urb descriptor.
240                          * the fixed 12.13 frequency is passed as 16.16 through the pipe.
241                          */
242                         urb->iso_frame_desc[0].length = 4;
243                         urb->iso_frame_desc[0].offset = 0;
244                         cp[0] = ep->freqn;
245                         cp[1] = ep->freqn >> 8;
246                         cp[2] = ep->freqn >> 16;
247                         cp[3] = ep->freqn >> 24;
248                 } else {
249                         /*
250                          * fill the length and offset of each urb descriptor.
251                          * the fixed 10.14 frequency is passed through the pipe.
252                          */
253                         urb->iso_frame_desc[0].length = 3;
254                         urb->iso_frame_desc[0].offset = 0;
255                         cp[0] = ep->freqn >> 2;
256                         cp[1] = ep->freqn >> 10;
257                         cp[2] = ep->freqn >> 18;
258                 }
259
260                 break;
261         }
262 }
263
264 /*
265  * Prepare a CAPTURE or SYNC urb for submission to the bus.
266  */
267 static inline void prepare_inbound_urb(struct snd_usb_endpoint *ep,
268                                        struct snd_urb_ctx *urb_ctx)
269 {
270         int i, offs;
271         struct urb *urb = urb_ctx->urb;
272
273         urb->dev = ep->chip->dev; /* we need to set this at each time */
274
275         switch (ep->type) {
276         case SND_USB_ENDPOINT_TYPE_DATA:
277                 offs = 0;
278                 for (i = 0; i < urb_ctx->packets; i++) {
279                         urb->iso_frame_desc[i].offset = offs;
280                         urb->iso_frame_desc[i].length = ep->curpacksize;
281                         offs += ep->curpacksize;
282                 }
283
284                 urb->transfer_buffer_length = offs;
285                 urb->number_of_packets = urb_ctx->packets;
286                 break;
287
288         case SND_USB_ENDPOINT_TYPE_SYNC:
289                 urb->iso_frame_desc[0].length = min(4u, ep->syncmaxsize);
290                 urb->iso_frame_desc[0].offset = 0;
291                 break;
292         }
293 }
294
295 /*
296  * Send output urbs that have been prepared previously. URBs are dequeued
297  * from ep->ready_playback_urbs and in case there there aren't any available
298  * or there are no packets that have been prepared, this function does
299  * nothing.
300  *
301  * The reason why the functionality of sending and preparing URBs is separated
302  * is that host controllers don't guarantee the order in which they return
303  * inbound and outbound packets to their submitters.
304  *
305  * This function is only used for implicit feedback endpoints. For endpoints
306  * driven by dedicated sync endpoints, URBs are immediately re-submitted
307  * from their completion handler.
308  */
309 static void queue_pending_output_urbs(struct snd_usb_endpoint *ep)
310 {
311         while (test_bit(EP_FLAG_RUNNING, &ep->flags)) {
312
313                 unsigned long flags;
314                 struct snd_usb_packet_info *packet;
315                 struct snd_urb_ctx *ctx = NULL;
316                 int err, i;
317
318                 spin_lock_irqsave(&ep->lock, flags);
319                 if (ep->next_packet_read_pos != ep->next_packet_write_pos) {
320                         packet = ep->next_packet + ep->next_packet_read_pos;
321                         ep->next_packet_read_pos++;
322                         ep->next_packet_read_pos %= MAX_URBS;
323
324                         /* take URB out of FIFO */
325                         if (!list_empty(&ep->ready_playback_urbs)) {
326                                 ctx = list_first_entry(&ep->ready_playback_urbs,
327                                                struct snd_urb_ctx, ready_list);
328                                 list_del_init(&ctx->ready_list);
329                         }
330                 }
331                 spin_unlock_irqrestore(&ep->lock, flags);
332
333                 if (ctx == NULL)
334                         return;
335
336                 /* copy over the length information */
337                 for (i = 0; i < packet->packets; i++)
338                         ctx->packet_size[i] = packet->packet_size[i];
339
340                 /* call the data handler to fill in playback data */
341                 prepare_outbound_urb(ep, ctx);
342
343                 err = usb_submit_urb(ctx->urb, GFP_ATOMIC);
344                 if (err < 0)
345                         usb_audio_err(ep->chip,
346                                 "Unable to submit urb #%d: %d (urb %p)\n",
347                                 ctx->index, err, ctx->urb);
348                 else
349                         set_bit(ctx->index, &ep->active_mask);
350         }
351 }
352
353 /*
354  * complete callback for urbs
355  */
356 static void snd_complete_urb(struct urb *urb)
357 {
358         struct snd_urb_ctx *ctx = urb->context;
359         struct snd_usb_endpoint *ep = ctx->ep;
360         struct snd_pcm_substream *substream;
361         unsigned long flags;
362         int err;
363
364         if (unlikely(urb->status == -ENOENT ||          /* unlinked */
365                      urb->status == -ENODEV ||          /* device removed */
366                      urb->status == -ECONNRESET ||      /* unlinked */
367                      urb->status == -ESHUTDOWN))        /* device disabled */
368                 goto exit_clear;
369         /* device disconnected */
370         if (unlikely(atomic_read(&ep->chip->shutdown)))
371                 goto exit_clear;
372
373         if (unlikely(!test_bit(EP_FLAG_RUNNING, &ep->flags)))
374                 goto exit_clear;
375
376         if (usb_pipeout(ep->pipe)) {
377                 retire_outbound_urb(ep, ctx);
378                 /* can be stopped during retire callback */
379                 if (unlikely(!test_bit(EP_FLAG_RUNNING, &ep->flags)))
380                         goto exit_clear;
381
382                 if (snd_usb_endpoint_implicit_feedback_sink(ep)) {
383                         spin_lock_irqsave(&ep->lock, flags);
384                         list_add_tail(&ctx->ready_list, &ep->ready_playback_urbs);
385                         spin_unlock_irqrestore(&ep->lock, flags);
386                         queue_pending_output_urbs(ep);
387
388                         goto exit_clear;
389                 }
390
391                 prepare_outbound_urb(ep, ctx);
392                 /* can be stopped during prepare callback */
393                 if (unlikely(!test_bit(EP_FLAG_RUNNING, &ep->flags)))
394                         goto exit_clear;
395         } else {
396                 retire_inbound_urb(ep, ctx);
397                 /* can be stopped during retire callback */
398                 if (unlikely(!test_bit(EP_FLAG_RUNNING, &ep->flags)))
399                         goto exit_clear;
400
401                 prepare_inbound_urb(ep, ctx);
402         }
403
404         err = usb_submit_urb(urb, GFP_ATOMIC);
405         if (err == 0)
406                 return;
407
408         usb_audio_err(ep->chip, "cannot submit urb (err = %d)\n", err);
409         if (ep->data_subs && ep->data_subs->pcm_substream) {
410                 substream = ep->data_subs->pcm_substream;
411                 snd_pcm_stop_xrun(substream);
412         }
413
414 exit_clear:
415         clear_bit(ctx->index, &ep->active_mask);
416 }
417
418 /**
419  * snd_usb_add_endpoint: Add an endpoint to an USB audio chip
420  *
421  * @chip: The chip
422  * @alts: The USB host interface
423  * @ep_num: The number of the endpoint to use
424  * @direction: SNDRV_PCM_STREAM_PLAYBACK or SNDRV_PCM_STREAM_CAPTURE
425  * @type: SND_USB_ENDPOINT_TYPE_DATA or SND_USB_ENDPOINT_TYPE_SYNC
426  *
427  * If the requested endpoint has not been added to the given chip before,
428  * a new instance is created. Otherwise, a pointer to the previoulsy
429  * created instance is returned. In case of any error, NULL is returned.
430  *
431  * New endpoints will be added to chip->ep_list and must be freed by
432  * calling snd_usb_endpoint_free().
433  *
434  * For SND_USB_ENDPOINT_TYPE_SYNC, the caller needs to guarantee that
435  * bNumEndpoints > 1 beforehand.
436  */
437 struct snd_usb_endpoint *snd_usb_add_endpoint(struct snd_usb_audio *chip,
438                                               struct usb_host_interface *alts,
439                                               int ep_num, int direction, int type)
440 {
441         struct snd_usb_endpoint *ep;
442         int is_playback = direction == SNDRV_PCM_STREAM_PLAYBACK;
443
444         if (WARN_ON(!alts))
445                 return NULL;
446
447         mutex_lock(&chip->mutex);
448
449         list_for_each_entry(ep, &chip->ep_list, list) {
450                 if (ep->ep_num == ep_num &&
451                     ep->iface == alts->desc.bInterfaceNumber &&
452                     ep->altsetting == alts->desc.bAlternateSetting) {
453                         usb_audio_dbg(ep->chip,
454                                       "Re-using EP %x in iface %d,%d @%p\n",
455                                         ep_num, ep->iface, ep->altsetting, ep);
456                         goto __exit_unlock;
457                 }
458         }
459
460         usb_audio_dbg(chip, "Creating new %s %s endpoint #%x\n",
461                     is_playback ? "playback" : "capture",
462                     type == SND_USB_ENDPOINT_TYPE_DATA ? "data" : "sync",
463                     ep_num);
464
465         ep = kzalloc(sizeof(*ep), GFP_KERNEL);
466         if (!ep)
467                 goto __exit_unlock;
468
469         ep->chip = chip;
470         spin_lock_init(&ep->lock);
471         ep->type = type;
472         ep->ep_num = ep_num;
473         ep->iface = alts->desc.bInterfaceNumber;
474         ep->altsetting = alts->desc.bAlternateSetting;
475         INIT_LIST_HEAD(&ep->ready_playback_urbs);
476         ep_num &= USB_ENDPOINT_NUMBER_MASK;
477
478         if (is_playback)
479                 ep->pipe = usb_sndisocpipe(chip->dev, ep_num);
480         else
481                 ep->pipe = usb_rcvisocpipe(chip->dev, ep_num);
482
483         if (type == SND_USB_ENDPOINT_TYPE_SYNC) {
484                 if (get_endpoint(alts, 1)->bLength >= USB_DT_ENDPOINT_AUDIO_SIZE &&
485                     get_endpoint(alts, 1)->bRefresh >= 1 &&
486                     get_endpoint(alts, 1)->bRefresh <= 9)
487                         ep->syncinterval = get_endpoint(alts, 1)->bRefresh;
488                 else if (snd_usb_get_speed(chip->dev) == USB_SPEED_FULL)
489                         ep->syncinterval = 1;
490                 else if (get_endpoint(alts, 1)->bInterval >= 1 &&
491                          get_endpoint(alts, 1)->bInterval <= 16)
492                         ep->syncinterval = get_endpoint(alts, 1)->bInterval - 1;
493                 else
494                         ep->syncinterval = 3;
495
496                 ep->syncmaxsize = le16_to_cpu(get_endpoint(alts, 1)->wMaxPacketSize);
497         }
498
499         list_add_tail(&ep->list, &chip->ep_list);
500
501         ep->is_implicit_feedback = 0;
502
503 __exit_unlock:
504         mutex_unlock(&chip->mutex);
505
506         return ep;
507 }
508
509 /*
510  *  wait until all urbs are processed.
511  */
512 static int wait_clear_urbs(struct snd_usb_endpoint *ep)
513 {
514         unsigned long end_time = jiffies + msecs_to_jiffies(1000);
515         int alive;
516
517         do {
518                 alive = bitmap_weight(&ep->active_mask, ep->nurbs);
519                 if (!alive)
520                         break;
521
522                 schedule_timeout_uninterruptible(1);
523         } while (time_before(jiffies, end_time));
524
525         if (alive)
526                 usb_audio_err(ep->chip,
527                         "timeout: still %d active urbs on EP #%x\n",
528                         alive, ep->ep_num);
529         clear_bit(EP_FLAG_STOPPING, &ep->flags);
530
531         ep->data_subs = NULL;
532         ep->sync_slave = NULL;
533         ep->retire_data_urb = NULL;
534         ep->prepare_data_urb = NULL;
535
536         return 0;
537 }
538
539 /* sync the pending stop operation;
540  * this function itself doesn't trigger the stop operation
541  */
542 void snd_usb_endpoint_sync_pending_stop(struct snd_usb_endpoint *ep)
543 {
544         if (ep && test_bit(EP_FLAG_STOPPING, &ep->flags))
545                 wait_clear_urbs(ep);
546 }
547
548 /*
549  * unlink active urbs.
550  */
551 static int deactivate_urbs(struct snd_usb_endpoint *ep, bool force)
552 {
553         unsigned int i;
554
555         if (!force && atomic_read(&ep->chip->shutdown)) /* to be sure... */
556                 return -EBADFD;
557
558         clear_bit(EP_FLAG_RUNNING, &ep->flags);
559
560         INIT_LIST_HEAD(&ep->ready_playback_urbs);
561         ep->next_packet_read_pos = 0;
562         ep->next_packet_write_pos = 0;
563
564         for (i = 0; i < ep->nurbs; i++) {
565                 if (test_bit(i, &ep->active_mask)) {
566                         if (!test_and_set_bit(i, &ep->unlink_mask)) {
567                                 struct urb *u = ep->urb[i].urb;
568                                 usb_unlink_urb(u);
569                         }
570                 }
571         }
572
573         return 0;
574 }
575
576 /*
577  * release an endpoint's urbs
578  */
579 static void release_urbs(struct snd_usb_endpoint *ep, int force)
580 {
581         int i;
582
583         /* route incoming urbs to nirvana */
584         ep->retire_data_urb = NULL;
585         ep->prepare_data_urb = NULL;
586
587         /* stop urbs */
588         deactivate_urbs(ep, force);
589         wait_clear_urbs(ep);
590
591         for (i = 0; i < ep->nurbs; i++)
592                 release_urb_ctx(&ep->urb[i]);
593
594         if (ep->syncbuf)
595                 usb_free_coherent(ep->chip->dev, SYNC_URBS * 4,
596                                   ep->syncbuf, ep->sync_dma);
597
598         ep->syncbuf = NULL;
599         ep->nurbs = 0;
600 }
601
602 /*
603  * Check data endpoint for format differences
604  */
605 static bool check_ep_params(struct snd_usb_endpoint *ep,
606                               snd_pcm_format_t pcm_format,
607                               unsigned int channels,
608                               unsigned int period_bytes,
609                               unsigned int frames_per_period,
610                               unsigned int periods_per_buffer,
611                               struct audioformat *fmt,
612                               struct snd_usb_endpoint *sync_ep)
613 {
614         unsigned int maxsize, minsize, packs_per_ms, max_packs_per_urb;
615         unsigned int max_packs_per_period, urbs_per_period, urb_packs;
616         unsigned int max_urbs;
617         int frame_bits = snd_pcm_format_physical_width(pcm_format) * channels;
618         int tx_length_quirk = (ep->chip->tx_length_quirk &&
619                                usb_pipeout(ep->pipe));
620         bool ret = 1;
621
622         if (pcm_format == SNDRV_PCM_FORMAT_DSD_U16_LE && fmt->dsd_dop) {
623                 /*
624                  * When operating in DSD DOP mode, the size of a sample frame
625                  * in hardware differs from the actual physical format width
626                  * because we need to make room for the DOP markers.
627                  */
628                 frame_bits += channels << 3;
629         }
630
631         ret = ret && (ep->datainterval == fmt->datainterval);
632         ret = ret && (ep->stride == frame_bits >> 3);
633
634         switch (pcm_format) {
635         case SNDRV_PCM_FORMAT_U8:
636                 ret = ret && (ep->silence_value == 0x80);
637                 break;
638         case SNDRV_PCM_FORMAT_DSD_U8:
639         case SNDRV_PCM_FORMAT_DSD_U16_LE:
640         case SNDRV_PCM_FORMAT_DSD_U32_LE:
641         case SNDRV_PCM_FORMAT_DSD_U16_BE:
642         case SNDRV_PCM_FORMAT_DSD_U32_BE:
643                 ret = ret && (ep->silence_value == 0x69);
644                 break;
645         default:
646                 ret = ret && (ep->silence_value == 0);
647         }
648
649         /* assume max. frequency is 50% higher than nominal */
650         ret = ret && (ep->freqmax == ep->freqn + (ep->freqn >> 1));
651         /* Round up freqmax to nearest integer in order to calculate maximum
652          * packet size, which must represent a whole number of frames.
653          * This is accomplished by adding 0x0.ffff before converting the
654          * Q16.16 format into integer.
655          * In order to accurately calculate the maximum packet size when
656          * the data interval is more than 1 (i.e. ep->datainterval > 0),
657          * multiply by the data interval prior to rounding. For instance,
658          * a freqmax of 41 kHz will result in a max packet size of 6 (5.125)
659          * frames with a data interval of 1, but 11 (10.25) frames with a
660          * data interval of 2.
661          * (ep->freqmax << ep->datainterval overflows at 8.192 MHz for the
662          * maximum datainterval value of 3, at USB full speed, higher for
663          * USB high speed, noting that ep->freqmax is in units of
664          * frames per packet in Q16.16 format.)
665          */
666         maxsize = (((ep->freqmax << ep->datainterval) + 0xffff) >> 16) *
667                          (frame_bits >> 3);
668         if (tx_length_quirk)
669                 maxsize += sizeof(__le32); /* Space for length descriptor */
670         /* but wMaxPacketSize might reduce this */
671         if (ep->maxpacksize && ep->maxpacksize < maxsize) {
672                 /* whatever fits into a max. size packet */
673                 unsigned int data_maxsize = maxsize = ep->maxpacksize;
674
675                 if (tx_length_quirk)
676                         /* Need to remove the length descriptor to calc freq */
677                         data_maxsize -= sizeof(__le32);
678                 ret = ret && (ep->freqmax == (data_maxsize / (frame_bits >> 3))
679                                 << (16 - ep->datainterval));
680         }
681
682         if (ep->fill_max)
683                 ret = ret && (ep->curpacksize == ep->maxpacksize);
684         else
685                 ret = ret && (ep->curpacksize == maxsize);
686
687         if (snd_usb_get_speed(ep->chip->dev) != USB_SPEED_FULL) {
688                 packs_per_ms = 8 >> ep->datainterval;
689                 max_packs_per_urb = MAX_PACKS_HS;
690         } else {
691                 packs_per_ms = 1;
692                 max_packs_per_urb = MAX_PACKS;
693         }
694         if (sync_ep && !snd_usb_endpoint_implicit_feedback_sink(ep))
695                 max_packs_per_urb = min(max_packs_per_urb,
696                                         1U << sync_ep->syncinterval);
697         max_packs_per_urb = max(1u, max_packs_per_urb >> ep->datainterval);
698
699         /*
700          * Capture endpoints need to use small URBs because there's no way
701          * to tell in advance where the next period will end, and we don't
702          * want the next URB to complete much after the period ends.
703          *
704          * Playback endpoints with implicit sync much use the same parameters
705          * as their corresponding capture endpoint.
706          */
707         if (usb_pipein(ep->pipe) ||
708                         snd_usb_endpoint_implicit_feedback_sink(ep)) {
709
710                 urb_packs = packs_per_ms;
711                 /*
712                  * Wireless devices can poll at a max rate of once per 4ms.
713                  * For dataintervals less than 5, increase the packet count to
714                  * allow the host controller to use bursting to fill in the
715                  * gaps.
716                  */
717                 if (snd_usb_get_speed(ep->chip->dev) == USB_SPEED_WIRELESS) {
718                         int interval = ep->datainterval;
719
720                         while (interval < 5) {
721                                 urb_packs <<= 1;
722                                 ++interval;
723                         }
724                 }
725                 /* make capture URBs <= 1 ms and smaller than a period */
726                 urb_packs = min(max_packs_per_urb, urb_packs);
727                 while (urb_packs > 1 && urb_packs * maxsize >= period_bytes)
728                         urb_packs >>= 1;
729                 ret = ret && (ep->nurbs == MAX_URBS);
730
731         /*
732          * Playback endpoints without implicit sync are adjusted so that
733          * a period fits as evenly as possible in the smallest number of
734          * URBs.  The total number of URBs is adjusted to the size of the
735          * ALSA buffer, subject to the MAX_URBS and MAX_QUEUE limits.
736          */
737         } else {
738                 /* determine how small a packet can be */
739                 minsize = (ep->freqn >> (16 - ep->datainterval)) *
740                                 (frame_bits >> 3);
741                 /* with sync from device, assume it can be 12% lower */
742                 if (sync_ep)
743                         minsize -= minsize >> 3;
744                 minsize = max(minsize, 1u);
745
746                 /* how many packets will contain an entire ALSA period? */
747                 max_packs_per_period = DIV_ROUND_UP(period_bytes, minsize);
748
749                 /* how many URBs will contain a period? */
750                 urbs_per_period = DIV_ROUND_UP(max_packs_per_period,
751                                 max_packs_per_urb);
752                 /* how many packets are needed in each URB? */
753                 urb_packs = DIV_ROUND_UP(max_packs_per_period, urbs_per_period);
754
755                 /* limit the number of frames in a single URB */
756                 ret = ret && (ep->max_urb_frames ==
757                         DIV_ROUND_UP(frames_per_period, urbs_per_period));
758
759                 /* try to use enough URBs to contain an entire ALSA buffer */
760                 max_urbs = min((unsigned) MAX_URBS,
761                                 MAX_QUEUE * packs_per_ms / urb_packs);
762                 ret = ret && (ep->nurbs == min(max_urbs,
763                                 urbs_per_period * periods_per_buffer));
764         }
765
766         ret = ret && (ep->datainterval == fmt->datainterval);
767         ret = ret && (ep->maxpacksize == fmt->maxpacksize);
768         ret = ret &&
769                 (ep->fill_max == !!(fmt->attributes & UAC_EP_CS_ATTR_FILL_MAX));
770
771         return ret;
772 }
773
774 /*
775  * configure a data endpoint
776  */
777 static int data_ep_set_params(struct snd_usb_endpoint *ep,
778                               snd_pcm_format_t pcm_format,
779                               unsigned int channels,
780                               unsigned int period_bytes,
781                               unsigned int frames_per_period,
782                               unsigned int periods_per_buffer,
783                               struct audioformat *fmt,
784                               struct snd_usb_endpoint *sync_ep)
785 {
786         unsigned int maxsize, minsize, packs_per_ms, max_packs_per_urb;
787         unsigned int max_packs_per_period, urbs_per_period, urb_packs;
788         unsigned int max_urbs, i;
789         int frame_bits = snd_pcm_format_physical_width(pcm_format) * channels;
790         int tx_length_quirk = (ep->chip->tx_length_quirk &&
791                                usb_pipeout(ep->pipe));
792
793         if (pcm_format == SNDRV_PCM_FORMAT_DSD_U16_LE && fmt->dsd_dop) {
794                 /*
795                  * When operating in DSD DOP mode, the size of a sample frame
796                  * in hardware differs from the actual physical format width
797                  * because we need to make room for the DOP markers.
798                  */
799                 frame_bits += channels << 3;
800         }
801
802         ep->datainterval = fmt->datainterval;
803         ep->stride = frame_bits >> 3;
804
805         switch (pcm_format) {
806         case SNDRV_PCM_FORMAT_U8:
807                 ep->silence_value = 0x80;
808                 break;
809         case SNDRV_PCM_FORMAT_DSD_U8:
810         case SNDRV_PCM_FORMAT_DSD_U16_LE:
811         case SNDRV_PCM_FORMAT_DSD_U32_LE:
812         case SNDRV_PCM_FORMAT_DSD_U16_BE:
813         case SNDRV_PCM_FORMAT_DSD_U32_BE:
814                 ep->silence_value = 0x69;
815                 break;
816         default:
817                 ep->silence_value = 0;
818         }
819
820         /* assume max. frequency is 50% higher than nominal */
821         ep->freqmax = ep->freqn + (ep->freqn >> 1);
822         /* Round up freqmax to nearest integer in order to calculate maximum
823          * packet size, which must represent a whole number of frames.
824          * This is accomplished by adding 0x0.ffff before converting the
825          * Q16.16 format into integer.
826          * In order to accurately calculate the maximum packet size when
827          * the data interval is more than 1 (i.e. ep->datainterval > 0),
828          * multiply by the data interval prior to rounding. For instance,
829          * a freqmax of 41 kHz will result in a max packet size of 6 (5.125)
830          * frames with a data interval of 1, but 11 (10.25) frames with a
831          * data interval of 2.
832          * (ep->freqmax << ep->datainterval overflows at 8.192 MHz for the
833          * maximum datainterval value of 3, at USB full speed, higher for
834          * USB high speed, noting that ep->freqmax is in units of
835          * frames per packet in Q16.16 format.)
836          */
837         maxsize = (((ep->freqmax << ep->datainterval) + 0xffff) >> 16) *
838                          (frame_bits >> 3);
839         if (tx_length_quirk)
840                 maxsize += sizeof(__le32); /* Space for length descriptor */
841         /* but wMaxPacketSize might reduce this */
842         if (ep->maxpacksize && ep->maxpacksize < maxsize) {
843                 /* whatever fits into a max. size packet */
844                 unsigned int data_maxsize = maxsize = ep->maxpacksize;
845
846                 if (tx_length_quirk)
847                         /* Need to remove the length descriptor to calc freq */
848                         data_maxsize -= sizeof(__le32);
849                 ep->freqmax = (data_maxsize / (frame_bits >> 3))
850                                 << (16 - ep->datainterval);
851         }
852
853         if (ep->fill_max)
854                 ep->curpacksize = ep->maxpacksize;
855         else
856                 ep->curpacksize = maxsize;
857
858         if (snd_usb_get_speed(ep->chip->dev) != USB_SPEED_FULL) {
859                 packs_per_ms = 8 >> ep->datainterval;
860                 max_packs_per_urb = MAX_PACKS_HS;
861         } else {
862                 packs_per_ms = 1;
863                 max_packs_per_urb = MAX_PACKS;
864         }
865         if (sync_ep && !snd_usb_endpoint_implicit_feedback_sink(ep))
866                 max_packs_per_urb = min(max_packs_per_urb,
867                                         1U << sync_ep->syncinterval);
868         max_packs_per_urb = max(1u, max_packs_per_urb >> ep->datainterval);
869
870         /*
871          * Capture endpoints need to use small URBs because there's no way
872          * to tell in advance where the next period will end, and we don't
873          * want the next URB to complete much after the period ends.
874          *
875          * Playback endpoints with implicit sync much use the same parameters
876          * as their corresponding capture endpoint.
877          */
878         if (usb_pipein(ep->pipe) ||
879                         snd_usb_endpoint_implicit_feedback_sink(ep)) {
880
881                 urb_packs = packs_per_ms;
882                 /*
883                  * Wireless devices can poll at a max rate of once per 4ms.
884                  * For dataintervals less than 5, increase the packet count to
885                  * allow the host controller to use bursting to fill in the
886                  * gaps.
887                  */
888                 if (snd_usb_get_speed(ep->chip->dev) == USB_SPEED_WIRELESS) {
889                         int interval = ep->datainterval;
890                         while (interval < 5) {
891                                 urb_packs <<= 1;
892                                 ++interval;
893                         }
894                 }
895                 /* make capture URBs <= 1 ms and smaller than a period */
896                 urb_packs = min(max_packs_per_urb, urb_packs);
897                 while (urb_packs > 1 && urb_packs * maxsize >= period_bytes)
898                         urb_packs >>= 1;
899                 ep->nurbs = MAX_URBS;
900
901         /*
902          * Playback endpoints without implicit sync are adjusted so that
903          * a period fits as evenly as possible in the smallest number of
904          * URBs.  The total number of URBs is adjusted to the size of the
905          * ALSA buffer, subject to the MAX_URBS and MAX_QUEUE limits.
906          */
907         } else {
908                 /* determine how small a packet can be */
909                 minsize = (ep->freqn >> (16 - ep->datainterval)) *
910                                 (frame_bits >> 3);
911                 /* with sync from device, assume it can be 12% lower */
912                 if (sync_ep)
913                         minsize -= minsize >> 3;
914                 minsize = max(minsize, 1u);
915
916                 /* how many packets will contain an entire ALSA period? */
917                 max_packs_per_period = DIV_ROUND_UP(period_bytes, minsize);
918
919                 /* how many URBs will contain a period? */
920                 urbs_per_period = DIV_ROUND_UP(max_packs_per_period,
921                                 max_packs_per_urb);
922                 /* how many packets are needed in each URB? */
923                 urb_packs = DIV_ROUND_UP(max_packs_per_period, urbs_per_period);
924
925                 /* limit the number of frames in a single URB */
926                 ep->max_urb_frames = DIV_ROUND_UP(frames_per_period,
927                                         urbs_per_period);
928
929                 /* try to use enough URBs to contain an entire ALSA buffer */
930                 max_urbs = min((unsigned) MAX_URBS,
931                                 MAX_QUEUE * packs_per_ms / urb_packs);
932                 ep->nurbs = min(max_urbs, urbs_per_period * periods_per_buffer);
933         }
934
935         /* allocate and initialize data urbs */
936         for (i = 0; i < ep->nurbs; i++) {
937                 struct snd_urb_ctx *u = &ep->urb[i];
938                 u->index = i;
939                 u->ep = ep;
940                 u->packets = urb_packs;
941                 u->buffer_size = maxsize * u->packets;
942
943                 if (fmt->fmt_type == UAC_FORMAT_TYPE_II)
944                         u->packets++; /* for transfer delimiter */
945                 u->urb = usb_alloc_urb(u->packets, GFP_KERNEL);
946                 if (!u->urb)
947                         goto out_of_memory;
948
949                 u->urb->transfer_buffer =
950                         usb_alloc_coherent(ep->chip->dev, u->buffer_size,
951                                            GFP_KERNEL, &u->urb->transfer_dma);
952                 if (!u->urb->transfer_buffer)
953                         goto out_of_memory;
954                 u->urb->pipe = ep->pipe;
955                 u->urb->transfer_flags = URB_NO_TRANSFER_DMA_MAP;
956                 u->urb->interval = 1 << ep->datainterval;
957                 u->urb->context = u;
958                 u->urb->complete = snd_complete_urb;
959                 INIT_LIST_HEAD(&u->ready_list);
960         }
961
962         return 0;
963
964 out_of_memory:
965         release_urbs(ep, 0);
966         return -ENOMEM;
967 }
968
969 /*
970  * configure a sync endpoint
971  */
972 static int sync_ep_set_params(struct snd_usb_endpoint *ep)
973 {
974         int i;
975
976         ep->syncbuf = usb_alloc_coherent(ep->chip->dev, SYNC_URBS * 4,
977                                          GFP_KERNEL, &ep->sync_dma);
978         if (!ep->syncbuf)
979                 return -ENOMEM;
980
981         ep->nurbs = SYNC_URBS;
982         for (i = 0; i < SYNC_URBS; i++) {
983                 struct snd_urb_ctx *u = &ep->urb[i];
984                 u->index = i;
985                 u->ep = ep;
986                 u->packets = 1;
987                 u->urb = usb_alloc_urb(1, GFP_KERNEL);
988                 if (!u->urb)
989                         goto out_of_memory;
990                 u->urb->transfer_buffer = ep->syncbuf + i * 4;
991                 u->urb->transfer_dma = ep->sync_dma + i * 4;
992                 u->urb->transfer_buffer_length = 4;
993                 u->urb->pipe = ep->pipe;
994                 u->urb->transfer_flags = URB_NO_TRANSFER_DMA_MAP;
995                 u->urb->number_of_packets = 1;
996                 u->urb->interval = 1 << ep->syncinterval;
997                 u->urb->context = u;
998                 u->urb->complete = snd_complete_urb;
999         }
1000
1001         return 0;
1002
1003 out_of_memory:
1004         release_urbs(ep, 0);
1005         return -ENOMEM;
1006 }
1007
1008 /**
1009  * snd_usb_endpoint_set_params: configure an snd_usb_endpoint
1010  *
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
1020  *
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.
1024  */
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,
1031                                 unsigned int rate,
1032                                 struct audioformat *fmt,
1033                                 struct snd_usb_endpoint *sync_ep)
1034 {
1035         int err;
1036
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,
1042                                              fmt, sync_ep);
1043
1044                 if (!check) {
1045                         usb_audio_warn(ep->chip,
1046                                 "Unable to change format on ep #%x: already in use\n",
1047                                 ep->ep_num);
1048                         return -EBUSY;
1049                 }
1050
1051                 usb_audio_dbg(ep->chip,
1052                               "Ep #%x already in use as implicit feedback but format not changed\n",
1053                               ep->ep_num);
1054                 return 0;
1055         }
1056
1057         /* release old buffers, if any */
1058         release_urbs(ep, 0);
1059
1060         ep->datainterval = fmt->datainterval;
1061         ep->maxpacksize = fmt->maxpacksize;
1062         ep->fill_max = !!(fmt->attributes & UAC_EP_CS_ATTR_FILL_MAX);
1063
1064         if (snd_usb_get_speed(ep->chip->dev) == USB_SPEED_FULL)
1065                 ep->freqn = get_usb_full_speed_rate(rate);
1066         else
1067                 ep->freqn = get_usb_high_speed_rate(rate);
1068
1069         /* calculate the frequency in 16.16 format */
1070         ep->freqm = ep->freqn;
1071         ep->freqshift = INT_MIN;
1072
1073         ep->phase = 0;
1074
1075         switch (ep->type) {
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);
1080                 break;
1081         case  SND_USB_ENDPOINT_TYPE_SYNC:
1082                 err = sync_ep_set_params(ep);
1083                 break;
1084         default:
1085                 err = -EINVAL;
1086         }
1087
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);
1091
1092         return err;
1093 }
1094
1095 /**
1096  * snd_usb_endpoint_start: start an snd_usb_endpoint
1097  *
1098  * @ep: the endpoint to start
1099  *
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.
1103  *
1104  * Must be balanced to calls of snd_usb_endpoint_stop().
1105  *
1106  * Returns an error if the URB submission failed, 0 in all other cases.
1107  */
1108 int snd_usb_endpoint_start(struct snd_usb_endpoint *ep)
1109 {
1110         int err;
1111         unsigned int i;
1112
1113         if (atomic_read(&ep->chip->shutdown))
1114                 return -EBADFD;
1115
1116         /* already running? */
1117         if (++ep->use_count != 1)
1118                 return 0;
1119
1120         /* just to be sure */
1121         deactivate_urbs(ep, false);
1122
1123         ep->active_mask = 0;
1124         ep->unlink_mask = 0;
1125         ep->phase = 0;
1126
1127         snd_usb_endpoint_start_quirk(ep);
1128
1129         /*
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.
1134          */
1135
1136         set_bit(EP_FLAG_RUNNING, &ep->flags);
1137
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);
1142                 }
1143
1144                 return 0;
1145         }
1146
1147         for (i = 0; i < ep->nurbs; i++) {
1148                 struct urb *urb = ep->urb[i].urb;
1149
1150                 if (snd_BUG_ON(!urb))
1151                         goto __error;
1152
1153                 if (usb_pipeout(ep->pipe)) {
1154                         prepare_outbound_urb(ep, urb->context);
1155                 } else {
1156                         prepare_inbound_urb(ep, urb->context);
1157                 }
1158
1159                 err = usb_submit_urb(urb, GFP_ATOMIC);
1160                 if (err < 0) {
1161                         usb_audio_err(ep->chip,
1162                                 "cannot submit urb %d, error %d: %s\n",
1163                                 i, err, usb_error_string(err));
1164                         goto __error;
1165                 }
1166                 set_bit(i, &ep->active_mask);
1167         }
1168
1169         return 0;
1170
1171 __error:
1172         clear_bit(EP_FLAG_RUNNING, &ep->flags);
1173         ep->use_count--;
1174         deactivate_urbs(ep, false);
1175         return -EPIPE;
1176 }
1177
1178 /**
1179  * snd_usb_endpoint_stop: stop an snd_usb_endpoint
1180  *
1181  * @ep: the endpoint to stop (may be NULL)
1182  *
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.
1186  *
1187  * Must be balanced to calls of snd_usb_endpoint_start().
1188  *
1189  * The caller needs to synchronize the pending stop operation via
1190  * snd_usb_endpoint_sync_pending_stop().
1191  */
1192 void snd_usb_endpoint_stop(struct snd_usb_endpoint *ep)
1193 {
1194         if (!ep)
1195                 return;
1196
1197         if (snd_BUG_ON(ep->use_count == 0))
1198                 return;
1199
1200         if (--ep->use_count == 0) {
1201                 deactivate_urbs(ep, false);
1202                 set_bit(EP_FLAG_STOPPING, &ep->flags);
1203         }
1204 }
1205
1206 /**
1207  * snd_usb_endpoint_deactivate: deactivate an snd_usb_endpoint
1208  *
1209  * @ep: the endpoint to deactivate
1210  *
1211  * If the endpoint is not currently in use, this functions will
1212  * deactivate its associated URBs.
1213  *
1214  * In case of any active users, this functions does nothing.
1215  */
1216 void snd_usb_endpoint_deactivate(struct snd_usb_endpoint *ep)
1217 {
1218         if (!ep)
1219                 return;
1220
1221         if (ep->use_count != 0)
1222                 return;
1223
1224         deactivate_urbs(ep, true);
1225         wait_clear_urbs(ep);
1226 }
1227
1228 /**
1229  * snd_usb_endpoint_release: Tear down an snd_usb_endpoint
1230  *
1231  * @ep: the endpoint to release
1232  *
1233  * This function does not care for the endpoint's use count but will tear
1234  * down all the streaming URBs immediately.
1235  */
1236 void snd_usb_endpoint_release(struct snd_usb_endpoint *ep)
1237 {
1238         release_urbs(ep, 1);
1239 }
1240
1241 /**
1242  * snd_usb_endpoint_free: Free the resources of an snd_usb_endpoint
1243  *
1244  * @ep: the endpoint to free
1245  *
1246  * This free all resources of the given ep.
1247  */
1248 void snd_usb_endpoint_free(struct snd_usb_endpoint *ep)
1249 {
1250         kfree(ep);
1251 }
1252
1253 /**
1254  * snd_usb_handle_sync_urb: parse an USB sync packet
1255  *
1256  * @ep: the endpoint to handle the packet
1257  * @sender: the sending endpoint
1258  * @urb: the received packet
1259  *
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.
1262  */
1263 void snd_usb_handle_sync_urb(struct snd_usb_endpoint *ep,
1264                              struct snd_usb_endpoint *sender,
1265                              const struct urb *urb)
1266 {
1267         int shift;
1268         unsigned int f;
1269         unsigned long flags;
1270
1271         snd_BUG_ON(ep == sender);
1272
1273         /*
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.
1278          */
1279         if (snd_usb_endpoint_implicit_feedback_sink(ep) &&
1280             ep->use_count != 0) {
1281
1282                 /* implicit feedback case */
1283                 int i, bytes = 0;
1284                 struct snd_urb_ctx *in_ctx;
1285                 struct snd_usb_packet_info *out_packet;
1286
1287                 in_ctx = urb->context;
1288
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;
1293
1294                 /*
1295                  * skip empty packets. At least M-Audio's Fast Track Ultra stops
1296                  * streaming once it received a 0-byte OUT URB
1297                  */
1298                 if (bytes == 0)
1299                         return;
1300
1301                 spin_lock_irqsave(&ep->lock, flags);
1302                 out_packet = ep->next_packet + ep->next_packet_write_pos;
1303
1304                 /*
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.
1312                  */
1313
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;
1319                         else
1320                                 out_packet->packet_size[i] = 0;
1321                 }
1322
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);
1327
1328                 return;
1329         }
1330
1331         /*
1332          * process after playback sync complete
1333          *
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
1336          * microframe.
1337          *
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.
1341          *
1342          * Therefore, we cannot predict what format any particular device uses
1343          * and must detect it automatically.
1344          */
1345
1346         if (urb->iso_frame_desc[0].status != 0 ||
1347             urb->iso_frame_desc[0].actual_length < 3)
1348                 return;
1349
1350         f = le32_to_cpup(urb->transfer_buffer);
1351         if (urb->iso_frame_desc[0].actual_length == 3)
1352                 f &= 0x00ffffff;
1353         else
1354                 f &= 0x0fffffff;
1355
1356         if (f == 0)
1357                 return;
1358
1359         if (unlikely(sender->tenor_fb_quirk)) {
1360                 /*
1361                  * Devices based on Tenor 8802 chipsets (TEAC UD-H01
1362                  * and others) sometimes change the feedback value
1363                  * by +/- 0x1.0000.
1364                  */
1365                 if (f < ep->freqn - 0x8000)
1366                         f += 0xf000;
1367                 else if (f > ep->freqn + 0x8000)
1368                         f -= 0xf000;
1369         } else if (unlikely(ep->freqshift == INT_MIN)) {
1370                 /*
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%.
1375                  */
1376                 shift = 0;
1377                 while (f < ep->freqn - ep->freqn / 4) {
1378                         f <<= 1;
1379                         shift++;
1380                 }
1381                 while (f > ep->freqn + ep->freqn / 2) {
1382                         f >>= 1;
1383                         shift--;
1384                 }
1385                 ep->freqshift = shift;
1386         } else if (ep->freqshift >= 0)
1387                 f <<= ep->freqshift;
1388         else
1389                 f >>= -ep->freqshift;
1390
1391         if (likely(f >= ep->freqn - ep->freqn / 8 && f <= ep->freqmax)) {
1392                 /*
1393                  * If the frequency looks valid, set it.
1394                  * This value is referred to in prepare_playback_urb().
1395                  */
1396                 spin_lock_irqsave(&ep->lock, flags);
1397                 ep->freqm = f;
1398                 spin_unlock_irqrestore(&ep->lock, flags);
1399         } else {
1400                 /*
1401                  * Out of range; maybe the shift value is wrong.
1402                  * Reset it so that we autodetect again the next time.
1403                  */
1404                 ep->freqshift = INT_MIN;
1405         }
1406 }
1407