4d733b2d8287d14419f140f8b7057acdc27deee1
[linux-2.6-microblaze.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 "clock.h"
22 #include "quirks.h"
23
24 #define EP_FLAG_RUNNING         1
25 #define EP_FLAG_STOPPING        2
26
27 /*
28  * snd_usb_endpoint is a model that abstracts everything related to an
29  * USB endpoint and its streaming.
30  *
31  * There are functions to activate and deactivate the streaming URBs and
32  * optional callbacks to let the pcm logic handle the actual content of the
33  * packets for playback and record. Thus, the bus streaming and the audio
34  * handlers are fully decoupled.
35  *
36  * There are two different types of endpoints in audio applications.
37  *
38  * SND_USB_ENDPOINT_TYPE_DATA handles full audio data payload for both
39  * inbound and outbound traffic.
40  *
41  * SND_USB_ENDPOINT_TYPE_SYNC endpoints are for inbound traffic only and
42  * expect the payload to carry Q10.14 / Q16.16 formatted sync information
43  * (3 or 4 bytes).
44  *
45  * Each endpoint has to be configured prior to being used by calling
46  * snd_usb_endpoint_set_params().
47  *
48  * The model incorporates a reference counting, so that multiple users
49  * can call snd_usb_endpoint_start() and snd_usb_endpoint_stop(), and
50  * only the first user will effectively start the URBs, and only the last
51  * one to stop it will tear the URBs down again.
52  */
53
54 /*
55  * convert a sampling rate into our full speed format (fs/1000 in Q16.16)
56  * this will overflow at approx 524 kHz
57  */
58 static inline unsigned get_usb_full_speed_rate(unsigned int rate)
59 {
60         return ((rate << 13) + 62) / 125;
61 }
62
63 /*
64  * convert a sampling rate into USB high speed format (fs/8000 in Q16.16)
65  * this will overflow at approx 4 MHz
66  */
67 static inline unsigned get_usb_high_speed_rate(unsigned int rate)
68 {
69         return ((rate << 10) + 62) / 125;
70 }
71
72 /*
73  * release a urb data
74  */
75 static void release_urb_ctx(struct snd_urb_ctx *u)
76 {
77         if (u->buffer_size)
78                 usb_free_coherent(u->ep->chip->dev, u->buffer_size,
79                                   u->urb->transfer_buffer,
80                                   u->urb->transfer_dma);
81         usb_free_urb(u->urb);
82         u->urb = NULL;
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->implicit_fb_sync && usb_pipeout(ep->pipe);
121 }
122
123 /*
124  * For streaming based on information derived from sync endpoints,
125  * prepare_outbound_urb_sizes() will call slave_next_packet_size() to
126  * determine the number of samples to be sent in the next packet.
127  *
128  * For implicit feedback, slave_next_packet_size() is unused.
129  */
130 int snd_usb_endpoint_slave_next_packet_size(struct snd_usb_endpoint *ep)
131 {
132         unsigned long flags;
133         int ret;
134
135         if (ep->fill_max)
136                 return ep->maxframesize;
137
138         spin_lock_irqsave(&ep->lock, flags);
139         ep->phase = (ep->phase & 0xffff)
140                 + (ep->freqm << ep->datainterval);
141         ret = min(ep->phase >> 16, ep->maxframesize);
142         spin_unlock_irqrestore(&ep->lock, flags);
143
144         return ret;
145 }
146
147 /*
148  * For adaptive and synchronous endpoints, prepare_outbound_urb_sizes()
149  * will call next_packet_size() to determine the number of samples to be
150  * sent in the next packet.
151  */
152 int snd_usb_endpoint_next_packet_size(struct snd_usb_endpoint *ep)
153 {
154         int ret;
155
156         if (ep->fill_max)
157                 return ep->maxframesize;
158
159         ep->sample_accum += ep->sample_rem;
160         if (ep->sample_accum >= ep->pps) {
161                 ep->sample_accum -= ep->pps;
162                 ret = ep->packsize[1];
163         } else {
164                 ret = ep->packsize[0];
165         }
166
167         return ret;
168 }
169
170 static void call_retire_callback(struct snd_usb_endpoint *ep,
171                                  struct urb *urb)
172 {
173         struct snd_usb_substream *data_subs;
174
175         data_subs = READ_ONCE(ep->data_subs);
176         if (data_subs && ep->retire_data_urb)
177                 ep->retire_data_urb(data_subs, urb);
178 }
179
180 static void retire_outbound_urb(struct snd_usb_endpoint *ep,
181                                 struct snd_urb_ctx *urb_ctx)
182 {
183         call_retire_callback(ep, urb_ctx->urb);
184 }
185
186 static void snd_usb_handle_sync_urb(struct snd_usb_endpoint *ep,
187                                     struct snd_usb_endpoint *sender,
188                                     const struct urb *urb);
189
190 static void retire_inbound_urb(struct snd_usb_endpoint *ep,
191                                struct snd_urb_ctx *urb_ctx)
192 {
193         struct urb *urb = urb_ctx->urb;
194         struct snd_usb_endpoint *sync_slave;
195
196         if (unlikely(ep->skip_packets > 0)) {
197                 ep->skip_packets--;
198                 return;
199         }
200
201         sync_slave = READ_ONCE(ep->sync_slave);
202         if (sync_slave)
203                 snd_usb_handle_sync_urb(sync_slave, ep, urb);
204
205         call_retire_callback(ep, urb);
206 }
207
208 static void prepare_silent_urb(struct snd_usb_endpoint *ep,
209                                struct snd_urb_ctx *ctx)
210 {
211         struct urb *urb = ctx->urb;
212         unsigned int offs = 0;
213         unsigned int extra = 0;
214         __le32 packet_length;
215         int i;
216
217         /* For tx_length_quirk, put packet length at start of packet */
218         if (ep->chip->tx_length_quirk)
219                 extra = sizeof(packet_length);
220
221         for (i = 0; i < ctx->packets; ++i) {
222                 unsigned int offset;
223                 unsigned int length;
224                 int counts;
225
226                 if (ctx->packet_size[i])
227                         counts = ctx->packet_size[i];
228                 else if (ep->sync_master)
229                         counts = snd_usb_endpoint_slave_next_packet_size(ep);
230                 else
231                         counts = snd_usb_endpoint_next_packet_size(ep);
232
233                 length = counts * ep->stride; /* number of silent bytes */
234                 offset = offs * ep->stride + extra * i;
235                 urb->iso_frame_desc[i].offset = offset;
236                 urb->iso_frame_desc[i].length = length + extra;
237                 if (extra) {
238                         packet_length = cpu_to_le32(length);
239                         memcpy(urb->transfer_buffer + offset,
240                                &packet_length, sizeof(packet_length));
241                 }
242                 memset(urb->transfer_buffer + offset + extra,
243                        ep->silence_value, length);
244                 offs += counts;
245         }
246
247         urb->number_of_packets = ctx->packets;
248         urb->transfer_buffer_length = offs * ep->stride + ctx->packets * extra;
249 }
250
251 /*
252  * Prepare a PLAYBACK urb for submission to the bus.
253  */
254 static void prepare_outbound_urb(struct snd_usb_endpoint *ep,
255                                  struct snd_urb_ctx *ctx)
256 {
257         struct urb *urb = ctx->urb;
258         unsigned char *cp = urb->transfer_buffer;
259         struct snd_usb_substream *data_subs;
260
261         urb->dev = ep->chip->dev; /* we need to set this at each time */
262
263         switch (ep->type) {
264         case SND_USB_ENDPOINT_TYPE_DATA:
265                 data_subs = READ_ONCE(ep->data_subs);
266                 if (data_subs && ep->prepare_data_urb)
267                         ep->prepare_data_urb(data_subs, urb);
268                 else /* no data provider, so send silence */
269                         prepare_silent_urb(ep, ctx);
270                 break;
271
272         case SND_USB_ENDPOINT_TYPE_SYNC:
273                 if (snd_usb_get_speed(ep->chip->dev) >= USB_SPEED_HIGH) {
274                         /*
275                          * fill the length and offset of each urb descriptor.
276                          * the fixed 12.13 frequency is passed as 16.16 through the pipe.
277                          */
278                         urb->iso_frame_desc[0].length = 4;
279                         urb->iso_frame_desc[0].offset = 0;
280                         cp[0] = ep->freqn;
281                         cp[1] = ep->freqn >> 8;
282                         cp[2] = ep->freqn >> 16;
283                         cp[3] = ep->freqn >> 24;
284                 } else {
285                         /*
286                          * fill the length and offset of each urb descriptor.
287                          * the fixed 10.14 frequency is passed through the pipe.
288                          */
289                         urb->iso_frame_desc[0].length = 3;
290                         urb->iso_frame_desc[0].offset = 0;
291                         cp[0] = ep->freqn >> 2;
292                         cp[1] = ep->freqn >> 10;
293                         cp[2] = ep->freqn >> 18;
294                 }
295
296                 break;
297         }
298 }
299
300 /*
301  * Prepare a CAPTURE or SYNC urb for submission to the bus.
302  */
303 static inline void prepare_inbound_urb(struct snd_usb_endpoint *ep,
304                                        struct snd_urb_ctx *urb_ctx)
305 {
306         int i, offs;
307         struct urb *urb = urb_ctx->urb;
308
309         urb->dev = ep->chip->dev; /* we need to set this at each time */
310
311         switch (ep->type) {
312         case SND_USB_ENDPOINT_TYPE_DATA:
313                 offs = 0;
314                 for (i = 0; i < urb_ctx->packets; i++) {
315                         urb->iso_frame_desc[i].offset = offs;
316                         urb->iso_frame_desc[i].length = ep->curpacksize;
317                         offs += ep->curpacksize;
318                 }
319
320                 urb->transfer_buffer_length = offs;
321                 urb->number_of_packets = urb_ctx->packets;
322                 break;
323
324         case SND_USB_ENDPOINT_TYPE_SYNC:
325                 urb->iso_frame_desc[0].length = min(4u, ep->syncmaxsize);
326                 urb->iso_frame_desc[0].offset = 0;
327                 break;
328         }
329 }
330
331 /* notify an error as XRUN to the assigned PCM data substream */
332 static void notify_xrun(struct snd_usb_endpoint *ep)
333 {
334         struct snd_usb_substream *data_subs;
335
336         data_subs = READ_ONCE(ep->data_subs);
337         if (data_subs && data_subs->pcm_substream)
338                 snd_pcm_stop_xrun(data_subs->pcm_substream);
339 }
340
341 static struct snd_usb_packet_info *
342 next_packet_fifo_enqueue(struct snd_usb_endpoint *ep)
343 {
344         struct snd_usb_packet_info *p;
345
346         p = ep->next_packet + (ep->next_packet_head + ep->next_packet_queued) %
347                 ARRAY_SIZE(ep->next_packet);
348         ep->next_packet_queued++;
349         return p;
350 }
351
352 static struct snd_usb_packet_info *
353 next_packet_fifo_dequeue(struct snd_usb_endpoint *ep)
354 {
355         struct snd_usb_packet_info *p;
356
357         p = ep->next_packet + ep->next_packet_head;
358         ep->next_packet_head++;
359         ep->next_packet_head %= ARRAY_SIZE(ep->next_packet);
360         ep->next_packet_queued--;
361         return p;
362 }
363
364 /*
365  * Send output urbs that have been prepared previously. URBs are dequeued
366  * from ep->ready_playback_urbs and in case there aren't any available
367  * or there are no packets that have been prepared, this function does
368  * nothing.
369  *
370  * The reason why the functionality of sending and preparing URBs is separated
371  * is that host controllers don't guarantee the order in which they return
372  * inbound and outbound packets to their submitters.
373  *
374  * This function is only used for implicit feedback endpoints. For endpoints
375  * driven by dedicated sync endpoints, URBs are immediately re-submitted
376  * from their completion handler.
377  */
378 static void queue_pending_output_urbs(struct snd_usb_endpoint *ep)
379 {
380         while (test_bit(EP_FLAG_RUNNING, &ep->flags)) {
381
382                 unsigned long flags;
383                 struct snd_usb_packet_info *packet;
384                 struct snd_urb_ctx *ctx = NULL;
385                 int err, i;
386
387                 spin_lock_irqsave(&ep->lock, flags);
388                 if (ep->next_packet_queued > 0 &&
389                     !list_empty(&ep->ready_playback_urbs)) {
390                         /* take URB out of FIFO */
391                         ctx = list_first_entry(&ep->ready_playback_urbs,
392                                                struct snd_urb_ctx, ready_list);
393                         list_del_init(&ctx->ready_list);
394
395                         packet = next_packet_fifo_dequeue(ep);
396                 }
397                 spin_unlock_irqrestore(&ep->lock, flags);
398
399                 if (ctx == NULL)
400                         return;
401
402                 /* copy over the length information */
403                 for (i = 0; i < packet->packets; i++)
404                         ctx->packet_size[i] = packet->packet_size[i];
405
406                 /* call the data handler to fill in playback data */
407                 prepare_outbound_urb(ep, ctx);
408
409                 err = usb_submit_urb(ctx->urb, GFP_ATOMIC);
410                 if (err < 0) {
411                         usb_audio_err(ep->chip,
412                                       "Unable to submit urb #%d: %d at %s\n",
413                                       ctx->index, err, __func__);
414                         notify_xrun(ep);
415                         return;
416                 }
417
418                 set_bit(ctx->index, &ep->active_mask);
419         }
420 }
421
422 /*
423  * complete callback for urbs
424  */
425 static void snd_complete_urb(struct urb *urb)
426 {
427         struct snd_urb_ctx *ctx = urb->context;
428         struct snd_usb_endpoint *ep = ctx->ep;
429         unsigned long flags;
430         int err;
431
432         if (unlikely(urb->status == -ENOENT ||          /* unlinked */
433                      urb->status == -ENODEV ||          /* device removed */
434                      urb->status == -ECONNRESET ||      /* unlinked */
435                      urb->status == -ESHUTDOWN))        /* device disabled */
436                 goto exit_clear;
437         /* device disconnected */
438         if (unlikely(atomic_read(&ep->chip->shutdown)))
439                 goto exit_clear;
440
441         if (unlikely(!test_bit(EP_FLAG_RUNNING, &ep->flags)))
442                 goto exit_clear;
443
444         if (usb_pipeout(ep->pipe)) {
445                 retire_outbound_urb(ep, ctx);
446                 /* can be stopped during retire callback */
447                 if (unlikely(!test_bit(EP_FLAG_RUNNING, &ep->flags)))
448                         goto exit_clear;
449
450                 if (snd_usb_endpoint_implicit_feedback_sink(ep)) {
451                         spin_lock_irqsave(&ep->lock, flags);
452                         list_add_tail(&ctx->ready_list, &ep->ready_playback_urbs);
453                         clear_bit(ctx->index, &ep->active_mask);
454                         spin_unlock_irqrestore(&ep->lock, flags);
455                         queue_pending_output_urbs(ep);
456                         return;
457                 }
458
459                 prepare_outbound_urb(ep, ctx);
460                 /* can be stopped during prepare callback */
461                 if (unlikely(!test_bit(EP_FLAG_RUNNING, &ep->flags)))
462                         goto exit_clear;
463         } else {
464                 retire_inbound_urb(ep, ctx);
465                 /* can be stopped during retire callback */
466                 if (unlikely(!test_bit(EP_FLAG_RUNNING, &ep->flags)))
467                         goto exit_clear;
468
469                 prepare_inbound_urb(ep, ctx);
470         }
471
472         err = usb_submit_urb(urb, GFP_ATOMIC);
473         if (err == 0)
474                 return;
475
476         usb_audio_err(ep->chip, "cannot submit urb (err = %d)\n", err);
477         notify_xrun(ep);
478
479 exit_clear:
480         clear_bit(ctx->index, &ep->active_mask);
481 }
482
483 /*
484  * Get the existing endpoint object corresponding EP
485  * Returns NULL if not present.
486  */
487 struct snd_usb_endpoint *
488 snd_usb_get_endpoint(struct snd_usb_audio *chip, int ep_num)
489 {
490         struct snd_usb_endpoint *ep;
491
492         list_for_each_entry(ep, &chip->ep_list, list) {
493                 if (ep->ep_num == ep_num)
494                         return ep;
495         }
496
497         return NULL;
498 }
499
500 #define ep_type_name(type) \
501         (type == SND_USB_ENDPOINT_TYPE_DATA ? "data" : "sync")
502
503 /**
504  * snd_usb_add_endpoint: Add an endpoint to an USB audio chip
505  *
506  * @chip: The chip
507  * @ep_num: The number of the endpoint to use
508  * @type: SND_USB_ENDPOINT_TYPE_DATA or SND_USB_ENDPOINT_TYPE_SYNC
509  *
510  * If the requested endpoint has not been added to the given chip before,
511  * a new instance is created.
512  *
513  * Returns zero on success or a negative error code.
514  *
515  * New endpoints will be added to chip->ep_list and must be freed by
516  * calling snd_usb_endpoint_free().
517  *
518  * For SND_USB_ENDPOINT_TYPE_SYNC, the caller needs to guarantee that
519  * bNumEndpoints > 1 beforehand.
520  */
521 int snd_usb_add_endpoint(struct snd_usb_audio *chip, int ep_num, int type)
522 {
523         struct snd_usb_endpoint *ep;
524         bool is_playback;
525
526         ep = snd_usb_get_endpoint(chip, ep_num);
527         if (ep)
528                 return 0;
529
530         usb_audio_dbg(chip, "Creating new %s endpoint #%x\n",
531                       ep_type_name(type),
532                       ep_num);
533         ep = kzalloc(sizeof(*ep), GFP_KERNEL);
534         if (!ep)
535                 return -ENOMEM;
536
537         ep->chip = chip;
538         spin_lock_init(&ep->lock);
539         ep->type = type;
540         ep->ep_num = ep_num;
541         INIT_LIST_HEAD(&ep->ready_playback_urbs);
542
543         is_playback = ((ep_num & USB_ENDPOINT_DIR_MASK) == USB_DIR_OUT);
544         ep_num &= USB_ENDPOINT_NUMBER_MASK;
545         if (is_playback)
546                 ep->pipe = usb_sndisocpipe(chip->dev, ep_num);
547         else
548                 ep->pipe = usb_rcvisocpipe(chip->dev, ep_num);
549
550         list_add_tail(&ep->list, &chip->ep_list);
551         return 0;
552 }
553
554 /* Set up syncinterval and maxsyncsize for a sync EP */
555 static void endpoint_set_syncinterval(struct snd_usb_audio *chip,
556                                       struct snd_usb_endpoint *ep)
557 {
558         struct usb_host_interface *alts;
559         struct usb_endpoint_descriptor *desc;
560
561         alts = snd_usb_get_host_interface(chip, ep->iface, ep->altsetting);
562         if (!alts)
563                 return;
564
565         desc = get_endpoint(alts, ep->ep_idx);
566         if (desc->bLength >= USB_DT_ENDPOINT_AUDIO_SIZE &&
567             desc->bRefresh >= 1 && desc->bRefresh <= 9)
568                 ep->syncinterval = desc->bRefresh;
569         else if (snd_usb_get_speed(chip->dev) == USB_SPEED_FULL)
570                 ep->syncinterval = 1;
571         else if (desc->bInterval >= 1 && desc->bInterval <= 16)
572                 ep->syncinterval = desc->bInterval - 1;
573         else
574                 ep->syncinterval = 3;
575
576         ep->syncmaxsize = le16_to_cpu(desc->wMaxPacketSize);
577 }
578
579 static bool endpoint_compatible(struct snd_usb_endpoint *ep,
580                                 const struct audioformat *fp,
581                                 const struct snd_pcm_hw_params *params)
582 {
583         if (!ep->opened)
584                 return false;
585         if (ep->cur_audiofmt != fp)
586                 return false;
587         if (ep->cur_rate != params_rate(params) ||
588             ep->cur_format != params_format(params) ||
589             ep->cur_period_frames != params_period_size(params) ||
590             ep->cur_buffer_periods != params_periods(params))
591                 return false;
592         return true;
593 }
594
595 /*
596  * Check whether the given fp and hw params are compatbile with the current
597  * setup of the target EP for implicit feedback sync
598  */
599 bool snd_usb_endpoint_compatible(struct snd_usb_audio *chip,
600                                  struct snd_usb_endpoint *ep,
601                                  const struct audioformat *fp,
602                                  const struct snd_pcm_hw_params *params)
603 {
604         bool ret;
605
606         mutex_lock(&chip->mutex);
607         ret = endpoint_compatible(ep, fp, params);
608         mutex_unlock(&chip->mutex);
609         return ret;
610 }
611
612 /*
613  * snd_usb_endpoint_open: Open the endpoint
614  *
615  * Called from hw_params to assign the endpoint to the substream.
616  * It's reference-counted, and only the first opener is allowed to set up
617  * arbitrary parameters.  The later opener must be compatible with the
618  * former opened parameters.
619  * The endpoint needs to be closed via snd_usb_endpoint_close() later.
620  *
621  * Note that this function doesn't configure the endpoint.  The substream
622  * needs to set it up later via snd_usb_endpoint_configure().
623  */
624 struct snd_usb_endpoint *
625 snd_usb_endpoint_open(struct snd_usb_audio *chip,
626                       const struct audioformat *fp,
627                       const struct snd_pcm_hw_params *params,
628                       bool is_sync_ep)
629 {
630         struct snd_usb_endpoint *ep;
631         int ep_num = is_sync_ep ? fp->sync_ep : fp->endpoint;
632
633         mutex_lock(&chip->mutex);
634         ep = snd_usb_get_endpoint(chip, ep_num);
635         if (!ep) {
636                 usb_audio_err(chip, "Cannot find EP 0x%x to open\n", ep_num);
637                 goto unlock;
638         }
639
640         if (!ep->opened) {
641                 if (is_sync_ep) {
642                         ep->iface = fp->sync_iface;
643                         ep->altsetting = fp->sync_altsetting;
644                         ep->ep_idx = fp->sync_ep_idx;
645                 } else {
646                         ep->iface = fp->iface;
647                         ep->altsetting = fp->altsetting;
648                         ep->ep_idx = 0;
649                 }
650                 usb_audio_dbg(chip, "Open EP 0x%x, iface=%d:%d, idx=%d\n",
651                               ep_num, ep->iface, ep->altsetting, ep->ep_idx);
652
653                 ep->cur_audiofmt = fp;
654                 ep->cur_channels = fp->channels;
655                 ep->cur_rate = params_rate(params);
656                 ep->cur_format = params_format(params);
657                 ep->cur_frame_bytes = snd_pcm_format_physical_width(ep->cur_format) *
658                         ep->cur_channels / 8;
659                 ep->cur_period_frames = params_period_size(params);
660                 ep->cur_period_bytes = ep->cur_period_frames * ep->cur_frame_bytes;
661                 ep->cur_buffer_periods = params_periods(params);
662
663                 if (ep->type == SND_USB_ENDPOINT_TYPE_SYNC)
664                         endpoint_set_syncinterval(chip, ep);
665
666                 ep->implicit_fb_sync = fp->implicit_fb;
667                 ep->need_setup = true;
668
669                 usb_audio_dbg(chip, "  channels=%d, rate=%d, format=%s, period_bytes=%d, periods=%d, implicit_fb=%d\n",
670                               ep->cur_channels, ep->cur_rate,
671                               snd_pcm_format_name(ep->cur_format),
672                               ep->cur_period_bytes, ep->cur_buffer_periods,
673                               ep->implicit_fb_sync);
674
675         } else {
676                 if (!endpoint_compatible(ep, fp, params)) {
677                         usb_audio_err(chip, "Incompatible EP setup for 0x%x\n",
678                                       ep_num);
679                         ep = NULL;
680                         goto unlock;
681                 }
682
683                 usb_audio_dbg(chip, "Reopened EP 0x%x (count %d)\n",
684                               ep_num, ep->opened);
685         }
686
687         ep->opened++;
688
689  unlock:
690         mutex_unlock(&chip->mutex);
691         return ep;
692 }
693
694 /*
695  * snd_usb_endpoint_set_sync: Link data and sync endpoints
696  *
697  * Pass NULL to sync_ep to unlink again
698  */
699 void snd_usb_endpoint_set_sync(struct snd_usb_audio *chip,
700                                struct snd_usb_endpoint *data_ep,
701                                struct snd_usb_endpoint *sync_ep)
702 {
703         data_ep->sync_master = sync_ep;
704 }
705
706 /*
707  * Set data endpoint callbacks and the assigned data stream
708  *
709  * Called at PCM trigger and cleanups.
710  * Pass NULL to deactivate each callback.
711  */
712 void snd_usb_endpoint_set_callback(struct snd_usb_endpoint *ep,
713                                    void (*prepare)(struct snd_usb_substream *subs,
714                                                    struct urb *urb),
715                                    void (*retire)(struct snd_usb_substream *subs,
716                                                   struct urb *urb),
717                                    struct snd_usb_substream *data_subs)
718 {
719         ep->prepare_data_urb = prepare;
720         ep->retire_data_urb = retire;
721         WRITE_ONCE(ep->data_subs, data_subs);
722 }
723
724 static int endpoint_set_interface(struct snd_usb_audio *chip,
725                                   struct snd_usb_endpoint *ep,
726                                   bool set)
727 {
728         int altset = set ? ep->altsetting : 0;
729         int err;
730
731         usb_audio_dbg(chip, "Setting usb interface %d:%d for EP 0x%x\n",
732                       ep->iface, altset, ep->ep_num);
733         err = usb_set_interface(chip->dev, ep->iface, altset);
734         if (err < 0) {
735                 usb_audio_err(chip, "%d:%d: usb_set_interface failed (%d)\n",
736                               ep->iface, altset, err);
737                 return err;
738         }
739
740         snd_usb_set_interface_quirk(chip);
741         return 0;
742 }
743
744 /*
745  * snd_usb_endpoint_close: Close the endpoint
746  *
747  * Unreference the already opened endpoint via snd_usb_endpoint_open().
748  */
749 void snd_usb_endpoint_close(struct snd_usb_audio *chip,
750                             struct snd_usb_endpoint *ep)
751 {
752         mutex_lock(&chip->mutex);
753         usb_audio_dbg(chip, "Closing EP 0x%x (count %d)\n",
754                       ep->ep_num, ep->opened);
755         if (!--ep->opened) {
756                 endpoint_set_interface(chip, ep, false);
757                 ep->iface = -1;
758                 ep->altsetting = 0;
759                 ep->cur_audiofmt = NULL;
760                 ep->cur_rate = 0;
761                 usb_audio_dbg(chip, "EP 0x%x closed\n", ep->ep_num);
762         }
763         mutex_unlock(&chip->mutex);
764 }
765
766 /* Prepare for suspening EP, called from the main suspend handler */
767 void snd_usb_endpoint_suspend(struct snd_usb_endpoint *ep)
768 {
769         ep->need_setup = true;
770 }
771
772 /*
773  *  wait until all urbs are processed.
774  */
775 static int wait_clear_urbs(struct snd_usb_endpoint *ep)
776 {
777         unsigned long end_time = jiffies + msecs_to_jiffies(1000);
778         int alive;
779
780         do {
781                 alive = bitmap_weight(&ep->active_mask, ep->nurbs);
782                 if (!alive)
783                         break;
784
785                 schedule_timeout_uninterruptible(1);
786         } while (time_before(jiffies, end_time));
787
788         if (alive)
789                 usb_audio_err(ep->chip,
790                         "timeout: still %d active urbs on EP #%x\n",
791                         alive, ep->ep_num);
792         clear_bit(EP_FLAG_STOPPING, &ep->flags);
793
794         ep->sync_slave = NULL;
795         snd_usb_endpoint_set_callback(ep, NULL, NULL, NULL);
796
797         return 0;
798 }
799
800 /* sync the pending stop operation;
801  * this function itself doesn't trigger the stop operation
802  */
803 void snd_usb_endpoint_sync_pending_stop(struct snd_usb_endpoint *ep)
804 {
805         if (ep && test_bit(EP_FLAG_STOPPING, &ep->flags))
806                 wait_clear_urbs(ep);
807 }
808
809 /*
810  * unlink active urbs.
811  */
812 static int deactivate_urbs(struct snd_usb_endpoint *ep, bool force)
813 {
814         unsigned int i;
815
816         if (!force && atomic_read(&ep->chip->shutdown)) /* to be sure... */
817                 return -EBADFD;
818
819         clear_bit(EP_FLAG_RUNNING, &ep->flags);
820
821         INIT_LIST_HEAD(&ep->ready_playback_urbs);
822         ep->next_packet_head = 0;
823         ep->next_packet_queued = 0;
824
825         for (i = 0; i < ep->nurbs; i++) {
826                 if (test_bit(i, &ep->active_mask)) {
827                         if (!test_and_set_bit(i, &ep->unlink_mask)) {
828                                 struct urb *u = ep->urb[i].urb;
829                                 usb_unlink_urb(u);
830                         }
831                 }
832         }
833
834         return 0;
835 }
836
837 /*
838  * release an endpoint's urbs
839  */
840 static void release_urbs(struct snd_usb_endpoint *ep, int force)
841 {
842         int i;
843
844         /* route incoming urbs to nirvana */
845         snd_usb_endpoint_set_callback(ep, NULL, NULL, NULL);
846
847         /* stop urbs */
848         deactivate_urbs(ep, force);
849         wait_clear_urbs(ep);
850
851         for (i = 0; i < ep->nurbs; i++)
852                 release_urb_ctx(&ep->urb[i]);
853
854         usb_free_coherent(ep->chip->dev, SYNC_URBS * 4,
855                           ep->syncbuf, ep->sync_dma);
856
857         ep->syncbuf = NULL;
858         ep->nurbs = 0;
859 }
860
861 /*
862  * configure a data endpoint
863  */
864 static int data_ep_set_params(struct snd_usb_endpoint *ep)
865 {
866         struct snd_usb_audio *chip = ep->chip;
867         unsigned int maxsize, minsize, packs_per_ms, max_packs_per_urb;
868         unsigned int max_packs_per_period, urbs_per_period, urb_packs;
869         unsigned int max_urbs, i;
870         const struct audioformat *fmt = ep->cur_audiofmt;
871         int frame_bits = ep->cur_frame_bytes * 8;
872         int tx_length_quirk = (chip->tx_length_quirk &&
873                                usb_pipeout(ep->pipe));
874
875         usb_audio_dbg(chip, "Setting params for data EP 0x%x, pipe 0x%x\n",
876                       ep->ep_num, ep->pipe);
877
878         if (ep->cur_format == SNDRV_PCM_FORMAT_DSD_U16_LE && fmt->dsd_dop) {
879                 /*
880                  * When operating in DSD DOP mode, the size of a sample frame
881                  * in hardware differs from the actual physical format width
882                  * because we need to make room for the DOP markers.
883                  */
884                 frame_bits += ep->cur_channels << 3;
885         }
886
887         ep->datainterval = fmt->datainterval;
888         ep->stride = frame_bits >> 3;
889
890         switch (ep->cur_format) {
891         case SNDRV_PCM_FORMAT_U8:
892                 ep->silence_value = 0x80;
893                 break;
894         case SNDRV_PCM_FORMAT_DSD_U8:
895         case SNDRV_PCM_FORMAT_DSD_U16_LE:
896         case SNDRV_PCM_FORMAT_DSD_U32_LE:
897         case SNDRV_PCM_FORMAT_DSD_U16_BE:
898         case SNDRV_PCM_FORMAT_DSD_U32_BE:
899                 ep->silence_value = 0x69;
900                 break;
901         default:
902                 ep->silence_value = 0;
903         }
904
905         /* assume max. frequency is 50% higher than nominal */
906         ep->freqmax = ep->freqn + (ep->freqn >> 1);
907         /* Round up freqmax to nearest integer in order to calculate maximum
908          * packet size, which must represent a whole number of frames.
909          * This is accomplished by adding 0x0.ffff before converting the
910          * Q16.16 format into integer.
911          * In order to accurately calculate the maximum packet size when
912          * the data interval is more than 1 (i.e. ep->datainterval > 0),
913          * multiply by the data interval prior to rounding. For instance,
914          * a freqmax of 41 kHz will result in a max packet size of 6 (5.125)
915          * frames with a data interval of 1, but 11 (10.25) frames with a
916          * data interval of 2.
917          * (ep->freqmax << ep->datainterval overflows at 8.192 MHz for the
918          * maximum datainterval value of 3, at USB full speed, higher for
919          * USB high speed, noting that ep->freqmax is in units of
920          * frames per packet in Q16.16 format.)
921          */
922         maxsize = (((ep->freqmax << ep->datainterval) + 0xffff) >> 16) *
923                          (frame_bits >> 3);
924         if (tx_length_quirk)
925                 maxsize += sizeof(__le32); /* Space for length descriptor */
926         /* but wMaxPacketSize might reduce this */
927         if (ep->maxpacksize && ep->maxpacksize < maxsize) {
928                 /* whatever fits into a max. size packet */
929                 unsigned int data_maxsize = maxsize = ep->maxpacksize;
930
931                 if (tx_length_quirk)
932                         /* Need to remove the length descriptor to calc freq */
933                         data_maxsize -= sizeof(__le32);
934                 ep->freqmax = (data_maxsize / (frame_bits >> 3))
935                                 << (16 - ep->datainterval);
936         }
937
938         if (ep->fill_max)
939                 ep->curpacksize = ep->maxpacksize;
940         else
941                 ep->curpacksize = maxsize;
942
943         if (snd_usb_get_speed(chip->dev) != USB_SPEED_FULL) {
944                 packs_per_ms = 8 >> ep->datainterval;
945                 max_packs_per_urb = MAX_PACKS_HS;
946         } else {
947                 packs_per_ms = 1;
948                 max_packs_per_urb = MAX_PACKS;
949         }
950         if (ep->sync_master && !ep->implicit_fb_sync)
951                 max_packs_per_urb = min(max_packs_per_urb,
952                                         1U << ep->sync_master->syncinterval);
953         max_packs_per_urb = max(1u, max_packs_per_urb >> ep->datainterval);
954
955         /*
956          * Capture endpoints need to use small URBs because there's no way
957          * to tell in advance where the next period will end, and we don't
958          * want the next URB to complete much after the period ends.
959          *
960          * Playback endpoints with implicit sync much use the same parameters
961          * as their corresponding capture endpoint.
962          */
963         if (usb_pipein(ep->pipe) || ep->implicit_fb_sync) {
964
965                 urb_packs = packs_per_ms;
966                 /*
967                  * Wireless devices can poll at a max rate of once per 4ms.
968                  * For dataintervals less than 5, increase the packet count to
969                  * allow the host controller to use bursting to fill in the
970                  * gaps.
971                  */
972                 if (snd_usb_get_speed(chip->dev) == USB_SPEED_WIRELESS) {
973                         int interval = ep->datainterval;
974                         while (interval < 5) {
975                                 urb_packs <<= 1;
976                                 ++interval;
977                         }
978                 }
979                 /* make capture URBs <= 1 ms and smaller than a period */
980                 urb_packs = min(max_packs_per_urb, urb_packs);
981                 while (urb_packs > 1 && urb_packs * maxsize >= ep->cur_period_bytes)
982                         urb_packs >>= 1;
983                 ep->nurbs = MAX_URBS;
984
985         /*
986          * Playback endpoints without implicit sync are adjusted so that
987          * a period fits as evenly as possible in the smallest number of
988          * URBs.  The total number of URBs is adjusted to the size of the
989          * ALSA buffer, subject to the MAX_URBS and MAX_QUEUE limits.
990          */
991         } else {
992                 /* determine how small a packet can be */
993                 minsize = (ep->freqn >> (16 - ep->datainterval)) *
994                                 (frame_bits >> 3);
995                 /* with sync from device, assume it can be 12% lower */
996                 if (ep->sync_master)
997                         minsize -= minsize >> 3;
998                 minsize = max(minsize, 1u);
999
1000                 /* how many packets will contain an entire ALSA period? */
1001                 max_packs_per_period = DIV_ROUND_UP(ep->cur_period_bytes, minsize);
1002
1003                 /* how many URBs will contain a period? */
1004                 urbs_per_period = DIV_ROUND_UP(max_packs_per_period,
1005                                 max_packs_per_urb);
1006                 /* how many packets are needed in each URB? */
1007                 urb_packs = DIV_ROUND_UP(max_packs_per_period, urbs_per_period);
1008
1009                 /* limit the number of frames in a single URB */
1010                 ep->max_urb_frames = DIV_ROUND_UP(ep->cur_period_frames,
1011                                                   urbs_per_period);
1012
1013                 /* try to use enough URBs to contain an entire ALSA buffer */
1014                 max_urbs = min((unsigned) MAX_URBS,
1015                                 MAX_QUEUE * packs_per_ms / urb_packs);
1016                 ep->nurbs = min(max_urbs, urbs_per_period * ep->cur_buffer_periods);
1017         }
1018
1019         /* allocate and initialize data urbs */
1020         for (i = 0; i < ep->nurbs; i++) {
1021                 struct snd_urb_ctx *u = &ep->urb[i];
1022                 u->index = i;
1023                 u->ep = ep;
1024                 u->packets = urb_packs;
1025                 u->buffer_size = maxsize * u->packets;
1026
1027                 if (fmt->fmt_type == UAC_FORMAT_TYPE_II)
1028                         u->packets++; /* for transfer delimiter */
1029                 u->urb = usb_alloc_urb(u->packets, GFP_KERNEL);
1030                 if (!u->urb)
1031                         goto out_of_memory;
1032
1033                 u->urb->transfer_buffer =
1034                         usb_alloc_coherent(chip->dev, u->buffer_size,
1035                                            GFP_KERNEL, &u->urb->transfer_dma);
1036                 if (!u->urb->transfer_buffer)
1037                         goto out_of_memory;
1038                 u->urb->pipe = ep->pipe;
1039                 u->urb->transfer_flags = URB_NO_TRANSFER_DMA_MAP;
1040                 u->urb->interval = 1 << ep->datainterval;
1041                 u->urb->context = u;
1042                 u->urb->complete = snd_complete_urb;
1043                 INIT_LIST_HEAD(&u->ready_list);
1044         }
1045
1046         return 0;
1047
1048 out_of_memory:
1049         release_urbs(ep, 0);
1050         return -ENOMEM;
1051 }
1052
1053 /*
1054  * configure a sync endpoint
1055  */
1056 static int sync_ep_set_params(struct snd_usb_endpoint *ep)
1057 {
1058         struct snd_usb_audio *chip = ep->chip;
1059         int i;
1060
1061         usb_audio_dbg(chip, "Setting params for sync EP 0x%x, pipe 0x%x\n",
1062                       ep->ep_num, ep->pipe);
1063
1064         ep->syncbuf = usb_alloc_coherent(chip->dev, SYNC_URBS * 4,
1065                                          GFP_KERNEL, &ep->sync_dma);
1066         if (!ep->syncbuf)
1067                 return -ENOMEM;
1068
1069         for (i = 0; i < SYNC_URBS; i++) {
1070                 struct snd_urb_ctx *u = &ep->urb[i];
1071                 u->index = i;
1072                 u->ep = ep;
1073                 u->packets = 1;
1074                 u->urb = usb_alloc_urb(1, GFP_KERNEL);
1075                 if (!u->urb)
1076                         goto out_of_memory;
1077                 u->urb->transfer_buffer = ep->syncbuf + i * 4;
1078                 u->urb->transfer_dma = ep->sync_dma + i * 4;
1079                 u->urb->transfer_buffer_length = 4;
1080                 u->urb->pipe = ep->pipe;
1081                 u->urb->transfer_flags = URB_NO_TRANSFER_DMA_MAP;
1082                 u->urb->number_of_packets = 1;
1083                 u->urb->interval = 1 << ep->syncinterval;
1084                 u->urb->context = u;
1085                 u->urb->complete = snd_complete_urb;
1086         }
1087
1088         ep->nurbs = SYNC_URBS;
1089
1090         return 0;
1091
1092 out_of_memory:
1093         release_urbs(ep, 0);
1094         return -ENOMEM;
1095 }
1096
1097 /*
1098  * snd_usb_endpoint_set_params: configure an snd_usb_endpoint
1099  *
1100  * Determine the number of URBs to be used on this endpoint.
1101  * An endpoint must be configured before it can be started.
1102  * An endpoint that is already running can not be reconfigured.
1103  */
1104 static int snd_usb_endpoint_set_params(struct snd_usb_audio *chip,
1105                                        struct snd_usb_endpoint *ep)
1106 {
1107         const struct audioformat *fmt = ep->cur_audiofmt;
1108         int err;
1109
1110         /* release old buffers, if any */
1111         release_urbs(ep, 0);
1112
1113         ep->datainterval = fmt->datainterval;
1114         ep->maxpacksize = fmt->maxpacksize;
1115         ep->fill_max = !!(fmt->attributes & UAC_EP_CS_ATTR_FILL_MAX);
1116
1117         if (snd_usb_get_speed(chip->dev) == USB_SPEED_FULL) {
1118                 ep->freqn = get_usb_full_speed_rate(ep->cur_rate);
1119                 ep->pps = 1000 >> ep->datainterval;
1120         } else {
1121                 ep->freqn = get_usb_high_speed_rate(ep->cur_rate);
1122                 ep->pps = 8000 >> ep->datainterval;
1123         }
1124
1125         ep->sample_rem = ep->cur_rate % ep->pps;
1126         ep->packsize[0] = ep->cur_rate / ep->pps;
1127         ep->packsize[1] = (ep->cur_rate + (ep->pps - 1)) / ep->pps;
1128
1129         /* calculate the frequency in 16.16 format */
1130         ep->freqm = ep->freqn;
1131         ep->freqshift = INT_MIN;
1132
1133         ep->phase = 0;
1134
1135         switch (ep->type) {
1136         case  SND_USB_ENDPOINT_TYPE_DATA:
1137                 err = data_ep_set_params(ep);
1138                 break;
1139         case  SND_USB_ENDPOINT_TYPE_SYNC:
1140                 err = sync_ep_set_params(ep);
1141                 break;
1142         default:
1143                 err = -EINVAL;
1144         }
1145
1146         usb_audio_dbg(chip, "Set up %d URBS, ret=%d\n", ep->nurbs, err);
1147
1148         if (err < 0)
1149                 return err;
1150
1151         /* some unit conversions in runtime */
1152         ep->maxframesize = ep->maxpacksize / ep->cur_frame_bytes;
1153         ep->curframesize = ep->curpacksize / ep->cur_frame_bytes;
1154
1155         return 0;
1156 }
1157
1158 /*
1159  * snd_usb_endpoint_configure: Configure the endpoint
1160  *
1161  * This function sets up the EP to be fully usable state.
1162  * It's called either from hw_params or prepare callback.
1163  * The function checks need_setup flag, and perfoms nothing unless needed,
1164  * so it's safe to call this multiple times.
1165  *
1166  * This returns zero if unchanged, 1 if the configuration has changed,
1167  * or a negative error code.
1168  */
1169 int snd_usb_endpoint_configure(struct snd_usb_audio *chip,
1170                                struct snd_usb_endpoint *ep)
1171 {
1172         bool iface_first;
1173         int err = 0;
1174
1175         mutex_lock(&chip->mutex);
1176         if (!ep->need_setup)
1177                 goto unlock;
1178
1179         /* No need to (re-)configure the sync EP belonging to the same altset */
1180         if (ep->ep_idx) {
1181                 err = snd_usb_endpoint_set_params(chip, ep);
1182                 if (err < 0)
1183                         goto unlock;
1184                 goto done;
1185         }
1186
1187         /* Need to deselect altsetting at first */
1188         endpoint_set_interface(chip, ep, false);
1189
1190         /* Some UAC1 devices (e.g. Yamaha THR10) need the host interface
1191          * to be set up before parameter setups
1192          */
1193         iface_first = ep->cur_audiofmt->protocol == UAC_VERSION_1;
1194         if (iface_first) {
1195                 err = endpoint_set_interface(chip, ep, true);
1196                 if (err < 0)
1197                         goto unlock;
1198         }
1199
1200         err = snd_usb_init_pitch(chip, ep->cur_audiofmt);
1201         if (err < 0)
1202                 goto unlock;
1203
1204         err = snd_usb_init_sample_rate(chip, ep->cur_audiofmt, ep->cur_rate);
1205         if (err < 0)
1206                 goto unlock;
1207
1208         err = snd_usb_endpoint_set_params(chip, ep);
1209         if (err < 0)
1210                 goto unlock;
1211
1212         err = snd_usb_select_mode_quirk(chip, ep->cur_audiofmt);
1213         if (err < 0)
1214                 goto unlock;
1215
1216         /* for UAC2/3, enable the interface altset here at last */
1217         if (!iface_first) {
1218                 err = endpoint_set_interface(chip, ep, true);
1219                 if (err < 0)
1220                         goto unlock;
1221         }
1222
1223  done:
1224         ep->need_setup = false;
1225         err = 1;
1226
1227 unlock:
1228         mutex_unlock(&chip->mutex);
1229         return err;
1230 }
1231
1232 /**
1233  * snd_usb_endpoint_start: start an snd_usb_endpoint
1234  *
1235  * @ep: the endpoint to start
1236  *
1237  * A call to this function will increment the running count of the endpoint.
1238  * In case it is not already running, the URBs for this endpoint will be
1239  * submitted. Otherwise, this function does nothing.
1240  *
1241  * Must be balanced to calls of snd_usb_endpoint_stop().
1242  *
1243  * Returns an error if the URB submission failed, 0 in all other cases.
1244  */
1245 int snd_usb_endpoint_start(struct snd_usb_endpoint *ep)
1246 {
1247         int err;
1248         unsigned int i;
1249
1250         if (atomic_read(&ep->chip->shutdown))
1251                 return -EBADFD;
1252
1253         if (ep->sync_master)
1254                 WRITE_ONCE(ep->sync_master->sync_slave, ep);
1255
1256         usb_audio_dbg(ep->chip, "Starting %s EP 0x%x (running %d)\n",
1257                       ep_type_name(ep->type), ep->ep_num,
1258                       atomic_read(&ep->running));
1259
1260         /* already running? */
1261         if (atomic_inc_return(&ep->running) != 1)
1262                 return 0;
1263
1264         /* just to be sure */
1265         deactivate_urbs(ep, false);
1266
1267         ep->active_mask = 0;
1268         ep->unlink_mask = 0;
1269         ep->phase = 0;
1270         ep->sample_accum = 0;
1271
1272         snd_usb_endpoint_start_quirk(ep);
1273
1274         /*
1275          * If this endpoint has a data endpoint as implicit feedback source,
1276          * don't start the urbs here. Instead, mark them all as available,
1277          * wait for the record urbs to return and queue the playback urbs
1278          * from that context.
1279          */
1280
1281         set_bit(EP_FLAG_RUNNING, &ep->flags);
1282
1283         if (snd_usb_endpoint_implicit_feedback_sink(ep)) {
1284                 for (i = 0; i < ep->nurbs; i++) {
1285                         struct snd_urb_ctx *ctx = ep->urb + i;
1286                         list_add_tail(&ctx->ready_list, &ep->ready_playback_urbs);
1287                 }
1288
1289                 usb_audio_dbg(ep->chip, "No URB submission due to implicit fb sync\n");
1290                 return 0;
1291         }
1292
1293         for (i = 0; i < ep->nurbs; i++) {
1294                 struct urb *urb = ep->urb[i].urb;
1295
1296                 if (snd_BUG_ON(!urb))
1297                         goto __error;
1298
1299                 if (usb_pipeout(ep->pipe)) {
1300                         prepare_outbound_urb(ep, urb->context);
1301                 } else {
1302                         prepare_inbound_urb(ep, urb->context);
1303                 }
1304
1305                 err = usb_submit_urb(urb, GFP_ATOMIC);
1306                 if (err < 0) {
1307                         usb_audio_err(ep->chip,
1308                                 "cannot submit urb %d, error %d: %s\n",
1309                                 i, err, usb_error_string(err));
1310                         goto __error;
1311                 }
1312                 set_bit(i, &ep->active_mask);
1313         }
1314
1315         usb_audio_dbg(ep->chip, "%d URBs submitted for EP 0x%x\n",
1316                       ep->nurbs, ep->ep_num);
1317         return 0;
1318
1319 __error:
1320         if (ep->sync_master)
1321                 WRITE_ONCE(ep->sync_master->sync_slave, NULL);
1322         clear_bit(EP_FLAG_RUNNING, &ep->flags);
1323         atomic_dec(&ep->running);
1324         deactivate_urbs(ep, false);
1325         return -EPIPE;
1326 }
1327
1328 /**
1329  * snd_usb_endpoint_stop: stop an snd_usb_endpoint
1330  *
1331  * @ep: the endpoint to stop (may be NULL)
1332  *
1333  * A call to this function will decrement the running count of the endpoint.
1334  * In case the last user has requested the endpoint stop, the URBs will
1335  * actually be deactivated.
1336  *
1337  * Must be balanced to calls of snd_usb_endpoint_start().
1338  *
1339  * The caller needs to synchronize the pending stop operation via
1340  * snd_usb_endpoint_sync_pending_stop().
1341  */
1342 void snd_usb_endpoint_stop(struct snd_usb_endpoint *ep)
1343 {
1344         if (!ep)
1345                 return;
1346
1347         usb_audio_dbg(ep->chip, "Stopping %s EP 0x%x (running %d)\n",
1348                       ep_type_name(ep->type), ep->ep_num,
1349                       atomic_read(&ep->running));
1350
1351         if (snd_BUG_ON(!atomic_read(&ep->running)))
1352                 return;
1353
1354         if (ep->sync_master)
1355                 WRITE_ONCE(ep->sync_master->sync_slave, NULL);
1356
1357         if (!atomic_dec_return(&ep->running)) {
1358                 deactivate_urbs(ep, false);
1359                 set_bit(EP_FLAG_STOPPING, &ep->flags);
1360         }
1361 }
1362
1363 /**
1364  * snd_usb_endpoint_release: Tear down an snd_usb_endpoint
1365  *
1366  * @ep: the endpoint to release
1367  *
1368  * This function does not care for the endpoint's running count but will tear
1369  * down all the streaming URBs immediately.
1370  */
1371 void snd_usb_endpoint_release(struct snd_usb_endpoint *ep)
1372 {
1373         release_urbs(ep, 1);
1374 }
1375
1376 /**
1377  * snd_usb_endpoint_free: Free the resources of an snd_usb_endpoint
1378  *
1379  * @ep: the endpoint to free
1380  *
1381  * This free all resources of the given ep.
1382  */
1383 void snd_usb_endpoint_free(struct snd_usb_endpoint *ep)
1384 {
1385         kfree(ep);
1386 }
1387
1388 /*
1389  * snd_usb_handle_sync_urb: parse an USB sync packet
1390  *
1391  * @ep: the endpoint to handle the packet
1392  * @sender: the sending endpoint
1393  * @urb: the received packet
1394  *
1395  * This function is called from the context of an endpoint that received
1396  * the packet and is used to let another endpoint object handle the payload.
1397  */
1398 static void snd_usb_handle_sync_urb(struct snd_usb_endpoint *ep,
1399                                     struct snd_usb_endpoint *sender,
1400                                     const struct urb *urb)
1401 {
1402         int shift;
1403         unsigned int f;
1404         unsigned long flags;
1405
1406         snd_BUG_ON(ep == sender);
1407
1408         /*
1409          * In case the endpoint is operating in implicit feedback mode, prepare
1410          * a new outbound URB that has the same layout as the received packet
1411          * and add it to the list of pending urbs. queue_pending_output_urbs()
1412          * will take care of them later.
1413          */
1414         if (snd_usb_endpoint_implicit_feedback_sink(ep) &&
1415             atomic_read(&ep->running)) {
1416
1417                 /* implicit feedback case */
1418                 int i, bytes = 0;
1419                 struct snd_urb_ctx *in_ctx;
1420                 struct snd_usb_packet_info *out_packet;
1421
1422                 in_ctx = urb->context;
1423
1424                 /* Count overall packet size */
1425                 for (i = 0; i < in_ctx->packets; i++)
1426                         if (urb->iso_frame_desc[i].status == 0)
1427                                 bytes += urb->iso_frame_desc[i].actual_length;
1428
1429                 /*
1430                  * skip empty packets. At least M-Audio's Fast Track Ultra stops
1431                  * streaming once it received a 0-byte OUT URB
1432                  */
1433                 if (bytes == 0)
1434                         return;
1435
1436                 spin_lock_irqsave(&ep->lock, flags);
1437                 if (ep->next_packet_queued >= ARRAY_SIZE(ep->next_packet)) {
1438                         spin_unlock_irqrestore(&ep->lock, flags);
1439                         usb_audio_err(ep->chip,
1440                                       "next package FIFO overflow EP 0x%x\n",
1441                                       ep->ep_num);
1442                         notify_xrun(ep);
1443                         return;
1444                 }
1445
1446                 out_packet = next_packet_fifo_enqueue(ep);
1447
1448                 /*
1449                  * Iterate through the inbound packet and prepare the lengths
1450                  * for the output packet. The OUT packet we are about to send
1451                  * will have the same amount of payload bytes per stride as the
1452                  * IN packet we just received. Since the actual size is scaled
1453                  * by the stride, use the sender stride to calculate the length
1454                  * in case the number of channels differ between the implicitly
1455                  * fed-back endpoint and the synchronizing endpoint.
1456                  */
1457
1458                 out_packet->packets = in_ctx->packets;
1459                 for (i = 0; i < in_ctx->packets; i++) {
1460                         if (urb->iso_frame_desc[i].status == 0)
1461                                 out_packet->packet_size[i] =
1462                                         urb->iso_frame_desc[i].actual_length / sender->stride;
1463                         else
1464                                 out_packet->packet_size[i] = 0;
1465                 }
1466
1467                 spin_unlock_irqrestore(&ep->lock, flags);
1468                 queue_pending_output_urbs(ep);
1469
1470                 return;
1471         }
1472
1473         /*
1474          * process after playback sync complete
1475          *
1476          * Full speed devices report feedback values in 10.14 format as samples
1477          * per frame, high speed devices in 16.16 format as samples per
1478          * microframe.
1479          *
1480          * Because the Audio Class 1 spec was written before USB 2.0, many high
1481          * speed devices use a wrong interpretation, some others use an
1482          * entirely different format.
1483          *
1484          * Therefore, we cannot predict what format any particular device uses
1485          * and must detect it automatically.
1486          */
1487
1488         if (urb->iso_frame_desc[0].status != 0 ||
1489             urb->iso_frame_desc[0].actual_length < 3)
1490                 return;
1491
1492         f = le32_to_cpup(urb->transfer_buffer);
1493         if (urb->iso_frame_desc[0].actual_length == 3)
1494                 f &= 0x00ffffff;
1495         else
1496                 f &= 0x0fffffff;
1497
1498         if (f == 0)
1499                 return;
1500
1501         if (unlikely(sender->tenor_fb_quirk)) {
1502                 /*
1503                  * Devices based on Tenor 8802 chipsets (TEAC UD-H01
1504                  * and others) sometimes change the feedback value
1505                  * by +/- 0x1.0000.
1506                  */
1507                 if (f < ep->freqn - 0x8000)
1508                         f += 0xf000;
1509                 else if (f > ep->freqn + 0x8000)
1510                         f -= 0xf000;
1511         } else if (unlikely(ep->freqshift == INT_MIN)) {
1512                 /*
1513                  * The first time we see a feedback value, determine its format
1514                  * by shifting it left or right until it matches the nominal
1515                  * frequency value.  This assumes that the feedback does not
1516                  * differ from the nominal value more than +50% or -25%.
1517                  */
1518                 shift = 0;
1519                 while (f < ep->freqn - ep->freqn / 4) {
1520                         f <<= 1;
1521                         shift++;
1522                 }
1523                 while (f > ep->freqn + ep->freqn / 2) {
1524                         f >>= 1;
1525                         shift--;
1526                 }
1527                 ep->freqshift = shift;
1528         } else if (ep->freqshift >= 0)
1529                 f <<= ep->freqshift;
1530         else
1531                 f >>= -ep->freqshift;
1532
1533         if (likely(f >= ep->freqn - ep->freqn / 8 && f <= ep->freqmax)) {
1534                 /*
1535                  * If the frequency looks valid, set it.
1536                  * This value is referred to in prepare_playback_urb().
1537                  */
1538                 spin_lock_irqsave(&ep->lock, flags);
1539                 ep->freqm = f;
1540                 spin_unlock_irqrestore(&ep->lock, flags);
1541         } else {
1542                 /*
1543                  * Out of range; maybe the shift value is wrong.
1544                  * Reset it so that we autodetect again the next time.
1545                  */
1546                 ep->freqshift = INT_MIN;
1547         }
1548 }
1549