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