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