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