xref: /linux/sound/usb/endpoint.c (revision 23cb0767f0544858169c02cec445d066d4e02e2b)
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->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 }
105 
106 static const char *usb_error_string(int err)
107 {
108 	switch (err) {
109 	case -ENODEV:
110 		return "no device";
111 	case -ENOENT:
112 		return "endpoint not enabled";
113 	case -EPIPE:
114 		return "endpoint stalled";
115 	case -ENOSPC:
116 		return "not enough bandwidth";
117 	case -ESHUTDOWN:
118 		return "device disabled";
119 	case -EHOSTUNREACH:
120 		return "device suspended";
121 	case -EINVAL:
122 	case -EAGAIN:
123 	case -EFBIG:
124 	case -EMSGSIZE:
125 		return "internal error";
126 	default:
127 		return "unknown error";
128 	}
129 }
130 
131 static inline bool ep_state_running(struct snd_usb_endpoint *ep)
132 {
133 	return atomic_read(&ep->state) == EP_STATE_RUNNING;
134 }
135 
136 static inline bool ep_state_update(struct snd_usb_endpoint *ep, int old, int new)
137 {
138 	return atomic_try_cmpxchg(&ep->state, &old, new);
139 }
140 
141 /**
142  * snd_usb_endpoint_implicit_feedback_sink: Report endpoint usage type
143  *
144  * @ep: The snd_usb_endpoint
145  *
146  * Determine whether an endpoint is driven by an implicit feedback
147  * data endpoint source.
148  */
149 int snd_usb_endpoint_implicit_feedback_sink(struct snd_usb_endpoint *ep)
150 {
151 	return  ep->implicit_fb_sync && usb_pipeout(ep->pipe);
152 }
153 
154 /*
155  * Return the number of samples to be sent in the next packet
156  * for streaming based on information derived from sync endpoints
157  *
158  * This won't be used for implicit feedback which takes the packet size
159  * returned from the sync source
160  */
161 static int slave_next_packet_size(struct snd_usb_endpoint *ep,
162 				  unsigned int avail)
163 {
164 	unsigned long flags;
165 	unsigned int phase;
166 	int ret;
167 
168 	if (ep->fill_max)
169 		return ep->maxframesize;
170 
171 	spin_lock_irqsave(&ep->lock, flags);
172 	phase = (ep->phase & 0xffff) + (ep->freqm << ep->datainterval);
173 	ret = min(phase >> 16, ep->maxframesize);
174 	if (avail && ret >= avail)
175 		ret = -EAGAIN;
176 	else
177 		ep->phase = phase;
178 	spin_unlock_irqrestore(&ep->lock, flags);
179 
180 	return ret;
181 }
182 
183 /*
184  * Return the number of samples to be sent in the next packet
185  * for adaptive and synchronous endpoints
186  */
187 static int next_packet_size(struct snd_usb_endpoint *ep, unsigned int avail)
188 {
189 	unsigned int sample_accum;
190 	int ret;
191 
192 	if (ep->fill_max)
193 		return ep->maxframesize;
194 
195 	sample_accum = ep->sample_accum + ep->sample_rem;
196 	if (sample_accum >= ep->pps) {
197 		sample_accum -= ep->pps;
198 		ret = ep->packsize[1];
199 	} else {
200 		ret = ep->packsize[0];
201 	}
202 	if (avail && ret >= avail)
203 		ret = -EAGAIN;
204 	else
205 		ep->sample_accum = sample_accum;
206 
207 	return ret;
208 }
209 
210 /*
211  * snd_usb_endpoint_next_packet_size: Return the number of samples to be sent
212  * in the next packet
213  *
214  * If the size is equal or exceeds @avail, don't proceed but return -EAGAIN
215  * Exception: @avail = 0 for skipping the check.
216  */
217 int snd_usb_endpoint_next_packet_size(struct snd_usb_endpoint *ep,
218 				      struct snd_urb_ctx *ctx, int idx,
219 				      unsigned int avail)
220 {
221 	unsigned int packet;
222 
223 	packet = ctx->packet_size[idx];
224 	if (packet) {
225 		if (avail && packet >= avail)
226 			return -EAGAIN;
227 		return packet;
228 	}
229 
230 	if (ep->sync_source)
231 		return slave_next_packet_size(ep, avail);
232 	else
233 		return next_packet_size(ep, avail);
234 }
235 
236 static void call_retire_callback(struct snd_usb_endpoint *ep,
237 				 struct urb *urb)
238 {
239 	struct snd_usb_substream *data_subs;
240 
241 	data_subs = READ_ONCE(ep->data_subs);
242 	if (data_subs && ep->retire_data_urb)
243 		ep->retire_data_urb(data_subs, urb);
244 }
245 
246 static void retire_outbound_urb(struct snd_usb_endpoint *ep,
247 				struct snd_urb_ctx *urb_ctx)
248 {
249 	call_retire_callback(ep, urb_ctx->urb);
250 }
251 
252 static void snd_usb_handle_sync_urb(struct snd_usb_endpoint *ep,
253 				    struct snd_usb_endpoint *sender,
254 				    const struct urb *urb);
255 
256 static void retire_inbound_urb(struct snd_usb_endpoint *ep,
257 			       struct snd_urb_ctx *urb_ctx)
258 {
259 	struct urb *urb = urb_ctx->urb;
260 	struct snd_usb_endpoint *sync_sink;
261 
262 	if (unlikely(ep->skip_packets > 0)) {
263 		ep->skip_packets--;
264 		return;
265 	}
266 
267 	sync_sink = READ_ONCE(ep->sync_sink);
268 	if (sync_sink)
269 		snd_usb_handle_sync_urb(sync_sink, ep, urb);
270 
271 	call_retire_callback(ep, urb);
272 }
273 
274 static inline bool has_tx_length_quirk(struct snd_usb_audio *chip)
275 {
276 	return chip->quirk_flags & QUIRK_FLAG_TX_LENGTH;
277 }
278 
279 static void prepare_silent_urb(struct snd_usb_endpoint *ep,
280 			       struct snd_urb_ctx *ctx)
281 {
282 	struct urb *urb = ctx->urb;
283 	unsigned int offs = 0;
284 	unsigned int extra = 0;
285 	__le32 packet_length;
286 	int i;
287 
288 	/* For tx_length_quirk, put packet length at start of packet */
289 	if (has_tx_length_quirk(ep->chip))
290 		extra = sizeof(packet_length);
291 
292 	for (i = 0; i < ctx->packets; ++i) {
293 		unsigned int offset;
294 		unsigned int length;
295 		int counts;
296 
297 		counts = snd_usb_endpoint_next_packet_size(ep, ctx, i, 0);
298 		length = counts * ep->stride; /* number of silent bytes */
299 		offset = offs * ep->stride + extra * i;
300 		urb->iso_frame_desc[i].offset = offset;
301 		urb->iso_frame_desc[i].length = length + extra;
302 		if (extra) {
303 			packet_length = cpu_to_le32(length);
304 			memcpy(urb->transfer_buffer + offset,
305 			       &packet_length, sizeof(packet_length));
306 		}
307 		memset(urb->transfer_buffer + offset + extra,
308 		       ep->silence_value, length);
309 		offs += counts;
310 	}
311 
312 	urb->number_of_packets = ctx->packets;
313 	urb->transfer_buffer_length = offs * ep->stride + ctx->packets * extra;
314 	ctx->queued = 0;
315 }
316 
317 /*
318  * Prepare a PLAYBACK urb for submission to the bus.
319  */
320 static int prepare_outbound_urb(struct snd_usb_endpoint *ep,
321 				struct snd_urb_ctx *ctx,
322 				bool in_stream_lock)
323 {
324 	struct urb *urb = ctx->urb;
325 	unsigned char *cp = urb->transfer_buffer;
326 	struct snd_usb_substream *data_subs;
327 
328 	urb->dev = ep->chip->dev; /* we need to set this at each time */
329 
330 	switch (ep->type) {
331 	case SND_USB_ENDPOINT_TYPE_DATA:
332 		data_subs = READ_ONCE(ep->data_subs);
333 		if (data_subs && ep->prepare_data_urb)
334 			return ep->prepare_data_urb(data_subs, urb, in_stream_lock);
335 		/* no data provider, so send silence */
336 		prepare_silent_urb(ep, ctx);
337 		break;
338 
339 	case SND_USB_ENDPOINT_TYPE_SYNC:
340 		if (snd_usb_get_speed(ep->chip->dev) >= USB_SPEED_HIGH) {
341 			/*
342 			 * fill the length and offset of each urb descriptor.
343 			 * the fixed 12.13 frequency is passed as 16.16 through the pipe.
344 			 */
345 			urb->iso_frame_desc[0].length = 4;
346 			urb->iso_frame_desc[0].offset = 0;
347 			cp[0] = ep->freqn;
348 			cp[1] = ep->freqn >> 8;
349 			cp[2] = ep->freqn >> 16;
350 			cp[3] = ep->freqn >> 24;
351 		} else {
352 			/*
353 			 * fill the length and offset of each urb descriptor.
354 			 * the fixed 10.14 frequency is passed through the pipe.
355 			 */
356 			urb->iso_frame_desc[0].length = 3;
357 			urb->iso_frame_desc[0].offset = 0;
358 			cp[0] = ep->freqn >> 2;
359 			cp[1] = ep->freqn >> 10;
360 			cp[2] = ep->freqn >> 18;
361 		}
362 
363 		break;
364 	}
365 	return 0;
366 }
367 
368 /*
369  * Prepare a CAPTURE or SYNC urb for submission to the bus.
370  */
371 static int prepare_inbound_urb(struct snd_usb_endpoint *ep,
372 			       struct snd_urb_ctx *urb_ctx)
373 {
374 	int i, offs;
375 	struct urb *urb = urb_ctx->urb;
376 
377 	urb->dev = ep->chip->dev; /* we need to set this at each time */
378 
379 	switch (ep->type) {
380 	case SND_USB_ENDPOINT_TYPE_DATA:
381 		offs = 0;
382 		for (i = 0; i < urb_ctx->packets; i++) {
383 			urb->iso_frame_desc[i].offset = offs;
384 			urb->iso_frame_desc[i].length = ep->curpacksize;
385 			offs += ep->curpacksize;
386 		}
387 
388 		urb->transfer_buffer_length = offs;
389 		urb->number_of_packets = urb_ctx->packets;
390 		break;
391 
392 	case SND_USB_ENDPOINT_TYPE_SYNC:
393 		urb->iso_frame_desc[0].length = min(4u, ep->syncmaxsize);
394 		urb->iso_frame_desc[0].offset = 0;
395 		break;
396 	}
397 	return 0;
398 }
399 
400 /* notify an error as XRUN to the assigned PCM data substream */
401 static void notify_xrun(struct snd_usb_endpoint *ep)
402 {
403 	struct snd_usb_substream *data_subs;
404 
405 	data_subs = READ_ONCE(ep->data_subs);
406 	if (data_subs && data_subs->pcm_substream)
407 		snd_pcm_stop_xrun(data_subs->pcm_substream);
408 }
409 
410 static struct snd_usb_packet_info *
411 next_packet_fifo_enqueue(struct snd_usb_endpoint *ep)
412 {
413 	struct snd_usb_packet_info *p;
414 
415 	p = ep->next_packet + (ep->next_packet_head + ep->next_packet_queued) %
416 		ARRAY_SIZE(ep->next_packet);
417 	ep->next_packet_queued++;
418 	return p;
419 }
420 
421 static struct snd_usb_packet_info *
422 next_packet_fifo_dequeue(struct snd_usb_endpoint *ep)
423 {
424 	struct snd_usb_packet_info *p;
425 
426 	p = ep->next_packet + ep->next_packet_head;
427 	ep->next_packet_head++;
428 	ep->next_packet_head %= ARRAY_SIZE(ep->next_packet);
429 	ep->next_packet_queued--;
430 	return p;
431 }
432 
433 static void push_back_to_ready_list(struct snd_usb_endpoint *ep,
434 				    struct snd_urb_ctx *ctx)
435 {
436 	unsigned long flags;
437 
438 	spin_lock_irqsave(&ep->lock, flags);
439 	list_add_tail(&ctx->ready_list, &ep->ready_playback_urbs);
440 	spin_unlock_irqrestore(&ep->lock, flags);
441 }
442 
443 /*
444  * Send output urbs that have been prepared previously. URBs are dequeued
445  * from ep->ready_playback_urbs and in case there aren't any available
446  * or there are no packets that have been prepared, this function does
447  * nothing.
448  *
449  * The reason why the functionality of sending and preparing URBs is separated
450  * is that host controllers don't guarantee the order in which they return
451  * inbound and outbound packets to their submitters.
452  *
453  * This function is used both for implicit feedback endpoints and in low-
454  * latency playback mode.
455  */
456 void snd_usb_queue_pending_output_urbs(struct snd_usb_endpoint *ep,
457 				       bool in_stream_lock)
458 {
459 	bool implicit_fb = snd_usb_endpoint_implicit_feedback_sink(ep);
460 
461 	while (ep_state_running(ep)) {
462 
463 		unsigned long flags;
464 		struct snd_usb_packet_info *packet;
465 		struct snd_urb_ctx *ctx = NULL;
466 		int err, i;
467 
468 		spin_lock_irqsave(&ep->lock, flags);
469 		if ((!implicit_fb || ep->next_packet_queued > 0) &&
470 		    !list_empty(&ep->ready_playback_urbs)) {
471 			/* take URB out of FIFO */
472 			ctx = list_first_entry(&ep->ready_playback_urbs,
473 					       struct snd_urb_ctx, ready_list);
474 			list_del_init(&ctx->ready_list);
475 			if (implicit_fb)
476 				packet = next_packet_fifo_dequeue(ep);
477 		}
478 		spin_unlock_irqrestore(&ep->lock, flags);
479 
480 		if (ctx == NULL)
481 			return;
482 
483 		/* copy over the length information */
484 		if (implicit_fb) {
485 			for (i = 0; i < packet->packets; i++)
486 				ctx->packet_size[i] = packet->packet_size[i];
487 		}
488 
489 		/* call the data handler to fill in playback data */
490 		err = prepare_outbound_urb(ep, ctx, in_stream_lock);
491 		/* can be stopped during prepare callback */
492 		if (unlikely(!ep_state_running(ep)))
493 			break;
494 		if (err < 0) {
495 			/* push back to ready list again for -EAGAIN */
496 			if (err == -EAGAIN)
497 				push_back_to_ready_list(ep, ctx);
498 			else
499 				notify_xrun(ep);
500 			return;
501 		}
502 
503 		err = usb_submit_urb(ctx->urb, GFP_ATOMIC);
504 		if (err < 0) {
505 			usb_audio_err(ep->chip,
506 				      "Unable to submit urb #%d: %d at %s\n",
507 				      ctx->index, err, __func__);
508 			notify_xrun(ep);
509 			return;
510 		}
511 
512 		set_bit(ctx->index, &ep->active_mask);
513 		atomic_inc(&ep->submitted_urbs);
514 	}
515 }
516 
517 /*
518  * complete callback for urbs
519  */
520 static void snd_complete_urb(struct urb *urb)
521 {
522 	struct snd_urb_ctx *ctx = urb->context;
523 	struct snd_usb_endpoint *ep = ctx->ep;
524 	int err;
525 
526 	if (unlikely(urb->status == -ENOENT ||		/* unlinked */
527 		     urb->status == -ENODEV ||		/* device removed */
528 		     urb->status == -ECONNRESET ||	/* unlinked */
529 		     urb->status == -ESHUTDOWN))	/* device disabled */
530 		goto exit_clear;
531 	/* device disconnected */
532 	if (unlikely(atomic_read(&ep->chip->shutdown)))
533 		goto exit_clear;
534 
535 	if (unlikely(!ep_state_running(ep)))
536 		goto exit_clear;
537 
538 	if (usb_pipeout(ep->pipe)) {
539 		retire_outbound_urb(ep, ctx);
540 		/* can be stopped during retire callback */
541 		if (unlikely(!ep_state_running(ep)))
542 			goto exit_clear;
543 
544 		/* in low-latency and implicit-feedback modes, push back the
545 		 * URB to ready list at first, then process as much as possible
546 		 */
547 		if (ep->lowlatency_playback ||
548 		     snd_usb_endpoint_implicit_feedback_sink(ep)) {
549 			push_back_to_ready_list(ep, ctx);
550 			clear_bit(ctx->index, &ep->active_mask);
551 			snd_usb_queue_pending_output_urbs(ep, false);
552 			atomic_dec(&ep->submitted_urbs); /* decrement at last */
553 			return;
554 		}
555 
556 		/* in non-lowlatency mode, no error handling for prepare */
557 		prepare_outbound_urb(ep, ctx, false);
558 		/* can be stopped during prepare callback */
559 		if (unlikely(!ep_state_running(ep)))
560 			goto exit_clear;
561 	} else {
562 		retire_inbound_urb(ep, ctx);
563 		/* can be stopped during retire callback */
564 		if (unlikely(!ep_state_running(ep)))
565 			goto exit_clear;
566 
567 		prepare_inbound_urb(ep, ctx);
568 	}
569 
570 	err = usb_submit_urb(urb, GFP_ATOMIC);
571 	if (err == 0)
572 		return;
573 
574 	usb_audio_err(ep->chip, "cannot submit urb (err = %d)\n", err);
575 	notify_xrun(ep);
576 
577 exit_clear:
578 	clear_bit(ctx->index, &ep->active_mask);
579 	atomic_dec(&ep->submitted_urbs);
580 }
581 
582 /*
583  * Find or create a refcount object for the given interface
584  *
585  * The objects are released altogether in snd_usb_endpoint_free_all()
586  */
587 static struct snd_usb_iface_ref *
588 iface_ref_find(struct snd_usb_audio *chip, int iface)
589 {
590 	struct snd_usb_iface_ref *ip;
591 
592 	list_for_each_entry(ip, &chip->iface_ref_list, list)
593 		if (ip->iface == iface)
594 			return ip;
595 
596 	ip = kzalloc(sizeof(*ip), GFP_KERNEL);
597 	if (!ip)
598 		return NULL;
599 	ip->iface = iface;
600 	list_add_tail(&ip->list, &chip->iface_ref_list);
601 	return ip;
602 }
603 
604 /* Similarly, a refcount object for clock */
605 static struct snd_usb_clock_ref *
606 clock_ref_find(struct snd_usb_audio *chip, int clock)
607 {
608 	struct snd_usb_clock_ref *ref;
609 
610 	list_for_each_entry(ref, &chip->clock_ref_list, list)
611 		if (ref->clock == clock)
612 			return ref;
613 
614 	ref = kzalloc(sizeof(*ref), GFP_KERNEL);
615 	if (!ref)
616 		return NULL;
617 	ref->clock = clock;
618 	atomic_set(&ref->locked, 0);
619 	list_add_tail(&ref->list, &chip->clock_ref_list);
620 	return ref;
621 }
622 
623 /*
624  * Get the existing endpoint object corresponding EP
625  * Returns NULL if not present.
626  */
627 struct snd_usb_endpoint *
628 snd_usb_get_endpoint(struct snd_usb_audio *chip, int ep_num)
629 {
630 	struct snd_usb_endpoint *ep;
631 
632 	list_for_each_entry(ep, &chip->ep_list, list) {
633 		if (ep->ep_num == ep_num)
634 			return ep;
635 	}
636 
637 	return NULL;
638 }
639 
640 #define ep_type_name(type) \
641 	(type == SND_USB_ENDPOINT_TYPE_DATA ? "data" : "sync")
642 
643 /**
644  * snd_usb_add_endpoint: Add an endpoint to an USB audio chip
645  *
646  * @chip: The chip
647  * @ep_num: The number of the endpoint to use
648  * @type: SND_USB_ENDPOINT_TYPE_DATA or SND_USB_ENDPOINT_TYPE_SYNC
649  *
650  * If the requested endpoint has not been added to the given chip before,
651  * a new instance is created.
652  *
653  * Returns zero on success or a negative error code.
654  *
655  * New endpoints will be added to chip->ep_list and freed by
656  * calling snd_usb_endpoint_free_all().
657  *
658  * For SND_USB_ENDPOINT_TYPE_SYNC, the caller needs to guarantee that
659  * bNumEndpoints > 1 beforehand.
660  */
661 int snd_usb_add_endpoint(struct snd_usb_audio *chip, int ep_num, int type)
662 {
663 	struct snd_usb_endpoint *ep;
664 	bool is_playback;
665 
666 	ep = snd_usb_get_endpoint(chip, ep_num);
667 	if (ep)
668 		return 0;
669 
670 	usb_audio_dbg(chip, "Creating new %s endpoint #%x\n",
671 		      ep_type_name(type),
672 		      ep_num);
673 	ep = kzalloc(sizeof(*ep), GFP_KERNEL);
674 	if (!ep)
675 		return -ENOMEM;
676 
677 	ep->chip = chip;
678 	spin_lock_init(&ep->lock);
679 	ep->type = type;
680 	ep->ep_num = ep_num;
681 	INIT_LIST_HEAD(&ep->ready_playback_urbs);
682 	atomic_set(&ep->submitted_urbs, 0);
683 
684 	is_playback = ((ep_num & USB_ENDPOINT_DIR_MASK) == USB_DIR_OUT);
685 	ep_num &= USB_ENDPOINT_NUMBER_MASK;
686 	if (is_playback)
687 		ep->pipe = usb_sndisocpipe(chip->dev, ep_num);
688 	else
689 		ep->pipe = usb_rcvisocpipe(chip->dev, ep_num);
690 
691 	list_add_tail(&ep->list, &chip->ep_list);
692 	return 0;
693 }
694 
695 /* Set up syncinterval and maxsyncsize for a sync EP */
696 static void endpoint_set_syncinterval(struct snd_usb_audio *chip,
697 				      struct snd_usb_endpoint *ep)
698 {
699 	struct usb_host_interface *alts;
700 	struct usb_endpoint_descriptor *desc;
701 
702 	alts = snd_usb_get_host_interface(chip, ep->iface, ep->altsetting);
703 	if (!alts)
704 		return;
705 
706 	desc = get_endpoint(alts, ep->ep_idx);
707 	if (desc->bLength >= USB_DT_ENDPOINT_AUDIO_SIZE &&
708 	    desc->bRefresh >= 1 && desc->bRefresh <= 9)
709 		ep->syncinterval = desc->bRefresh;
710 	else if (snd_usb_get_speed(chip->dev) == USB_SPEED_FULL)
711 		ep->syncinterval = 1;
712 	else if (desc->bInterval >= 1 && desc->bInterval <= 16)
713 		ep->syncinterval = desc->bInterval - 1;
714 	else
715 		ep->syncinterval = 3;
716 
717 	ep->syncmaxsize = le16_to_cpu(desc->wMaxPacketSize);
718 }
719 
720 static bool endpoint_compatible(struct snd_usb_endpoint *ep,
721 				const struct audioformat *fp,
722 				const struct snd_pcm_hw_params *params)
723 {
724 	if (!ep->opened)
725 		return false;
726 	if (ep->cur_audiofmt != fp)
727 		return false;
728 	if (ep->cur_rate != params_rate(params) ||
729 	    ep->cur_format != params_format(params) ||
730 	    ep->cur_period_frames != params_period_size(params) ||
731 	    ep->cur_buffer_periods != params_periods(params))
732 		return false;
733 	return true;
734 }
735 
736 /*
737  * Check whether the given fp and hw params are compatible with the current
738  * setup of the target EP for implicit feedback sync
739  */
740 bool snd_usb_endpoint_compatible(struct snd_usb_audio *chip,
741 				 struct snd_usb_endpoint *ep,
742 				 const struct audioformat *fp,
743 				 const struct snd_pcm_hw_params *params)
744 {
745 	bool ret;
746 
747 	mutex_lock(&chip->mutex);
748 	ret = endpoint_compatible(ep, fp, params);
749 	mutex_unlock(&chip->mutex);
750 	return ret;
751 }
752 
753 /*
754  * snd_usb_endpoint_open: Open the endpoint
755  *
756  * Called from hw_params to assign the endpoint to the substream.
757  * It's reference-counted, and only the first opener is allowed to set up
758  * arbitrary parameters.  The later opener must be compatible with the
759  * former opened parameters.
760  * The endpoint needs to be closed via snd_usb_endpoint_close() later.
761  *
762  * Note that this function doesn't configure the endpoint.  The substream
763  * needs to set it up later via snd_usb_endpoint_set_params() and
764  * snd_usb_endpoint_prepare().
765  */
766 struct snd_usb_endpoint *
767 snd_usb_endpoint_open(struct snd_usb_audio *chip,
768 		      const struct audioformat *fp,
769 		      const struct snd_pcm_hw_params *params,
770 		      bool is_sync_ep)
771 {
772 	struct snd_usb_endpoint *ep;
773 	int ep_num = is_sync_ep ? fp->sync_ep : fp->endpoint;
774 
775 	mutex_lock(&chip->mutex);
776 	ep = snd_usb_get_endpoint(chip, ep_num);
777 	if (!ep) {
778 		usb_audio_err(chip, "Cannot find EP 0x%x to open\n", ep_num);
779 		goto unlock;
780 	}
781 
782 	if (!ep->opened) {
783 		if (is_sync_ep) {
784 			ep->iface = fp->sync_iface;
785 			ep->altsetting = fp->sync_altsetting;
786 			ep->ep_idx = fp->sync_ep_idx;
787 		} else {
788 			ep->iface = fp->iface;
789 			ep->altsetting = fp->altsetting;
790 			ep->ep_idx = fp->ep_idx;
791 		}
792 		usb_audio_dbg(chip, "Open EP 0x%x, iface=%d:%d, idx=%d\n",
793 			      ep_num, ep->iface, ep->altsetting, ep->ep_idx);
794 
795 		ep->iface_ref = iface_ref_find(chip, ep->iface);
796 		if (!ep->iface_ref) {
797 			ep = NULL;
798 			goto unlock;
799 		}
800 
801 		if (fp->protocol != UAC_VERSION_1) {
802 			ep->clock_ref = clock_ref_find(chip, fp->clock);
803 			if (!ep->clock_ref) {
804 				ep = NULL;
805 				goto unlock;
806 			}
807 			ep->clock_ref->opened++;
808 		}
809 
810 		ep->cur_audiofmt = fp;
811 		ep->cur_channels = fp->channels;
812 		ep->cur_rate = params_rate(params);
813 		ep->cur_format = params_format(params);
814 		ep->cur_frame_bytes = snd_pcm_format_physical_width(ep->cur_format) *
815 			ep->cur_channels / 8;
816 		ep->cur_period_frames = params_period_size(params);
817 		ep->cur_period_bytes = ep->cur_period_frames * ep->cur_frame_bytes;
818 		ep->cur_buffer_periods = params_periods(params);
819 
820 		if (ep->type == SND_USB_ENDPOINT_TYPE_SYNC)
821 			endpoint_set_syncinterval(chip, ep);
822 
823 		ep->implicit_fb_sync = fp->implicit_fb;
824 		ep->need_setup = true;
825 
826 		usb_audio_dbg(chip, "  channels=%d, rate=%d, format=%s, period_bytes=%d, periods=%d, implicit_fb=%d\n",
827 			      ep->cur_channels, ep->cur_rate,
828 			      snd_pcm_format_name(ep->cur_format),
829 			      ep->cur_period_bytes, ep->cur_buffer_periods,
830 			      ep->implicit_fb_sync);
831 
832 	} else {
833 		if (WARN_ON(!ep->iface_ref)) {
834 			ep = NULL;
835 			goto unlock;
836 		}
837 
838 		if (!endpoint_compatible(ep, fp, params)) {
839 			usb_audio_err(chip, "Incompatible EP setup for 0x%x\n",
840 				      ep_num);
841 			ep = NULL;
842 			goto unlock;
843 		}
844 
845 		usb_audio_dbg(chip, "Reopened EP 0x%x (count %d)\n",
846 			      ep_num, ep->opened);
847 	}
848 
849 	if (!ep->iface_ref->opened++)
850 		ep->iface_ref->need_setup = true;
851 
852 	ep->opened++;
853 
854  unlock:
855 	mutex_unlock(&chip->mutex);
856 	return ep;
857 }
858 
859 /*
860  * snd_usb_endpoint_set_sync: Link data and sync endpoints
861  *
862  * Pass NULL to sync_ep to unlink again
863  */
864 void snd_usb_endpoint_set_sync(struct snd_usb_audio *chip,
865 			       struct snd_usb_endpoint *data_ep,
866 			       struct snd_usb_endpoint *sync_ep)
867 {
868 	data_ep->sync_source = sync_ep;
869 }
870 
871 /*
872  * Set data endpoint callbacks and the assigned data stream
873  *
874  * Called at PCM trigger and cleanups.
875  * Pass NULL to deactivate each callback.
876  */
877 void snd_usb_endpoint_set_callback(struct snd_usb_endpoint *ep,
878 				   int (*prepare)(struct snd_usb_substream *subs,
879 						  struct urb *urb,
880 						  bool in_stream_lock),
881 				   void (*retire)(struct snd_usb_substream *subs,
882 						  struct urb *urb),
883 				   struct snd_usb_substream *data_subs)
884 {
885 	ep->prepare_data_urb = prepare;
886 	ep->retire_data_urb = retire;
887 	if (data_subs)
888 		ep->lowlatency_playback = data_subs->lowlatency_playback;
889 	else
890 		ep->lowlatency_playback = false;
891 	WRITE_ONCE(ep->data_subs, data_subs);
892 }
893 
894 static int endpoint_set_interface(struct snd_usb_audio *chip,
895 				  struct snd_usb_endpoint *ep,
896 				  bool set)
897 {
898 	int altset = set ? ep->altsetting : 0;
899 	int err;
900 
901 	usb_audio_dbg(chip, "Setting usb interface %d:%d for EP 0x%x\n",
902 		      ep->iface, altset, ep->ep_num);
903 	err = usb_set_interface(chip->dev, ep->iface, altset);
904 	if (err < 0) {
905 		usb_audio_err(chip, "%d:%d: usb_set_interface failed (%d)\n",
906 			      ep->iface, altset, err);
907 		return err;
908 	}
909 
910 	if (chip->quirk_flags & QUIRK_FLAG_IFACE_DELAY)
911 		msleep(50);
912 	return 0;
913 }
914 
915 /*
916  * snd_usb_endpoint_close: Close the endpoint
917  *
918  * Unreference the already opened endpoint via snd_usb_endpoint_open().
919  */
920 void snd_usb_endpoint_close(struct snd_usb_audio *chip,
921 			    struct snd_usb_endpoint *ep)
922 {
923 	mutex_lock(&chip->mutex);
924 	usb_audio_dbg(chip, "Closing EP 0x%x (count %d)\n",
925 		      ep->ep_num, ep->opened);
926 
927 	if (!--ep->iface_ref->opened)
928 		endpoint_set_interface(chip, ep, false);
929 
930 	if (!--ep->opened) {
931 		if (ep->clock_ref) {
932 			if (!--ep->clock_ref->opened)
933 				ep->clock_ref->rate = 0;
934 		}
935 		ep->iface = 0;
936 		ep->altsetting = 0;
937 		ep->cur_audiofmt = NULL;
938 		ep->cur_rate = 0;
939 		ep->iface_ref = NULL;
940 		ep->clock_ref = NULL;
941 		usb_audio_dbg(chip, "EP 0x%x closed\n", ep->ep_num);
942 	}
943 	mutex_unlock(&chip->mutex);
944 }
945 
946 /* Prepare for suspening EP, called from the main suspend handler */
947 void snd_usb_endpoint_suspend(struct snd_usb_endpoint *ep)
948 {
949 	ep->need_setup = true;
950 	if (ep->iface_ref)
951 		ep->iface_ref->need_setup = true;
952 	if (ep->clock_ref)
953 		ep->clock_ref->rate = 0;
954 }
955 
956 /*
957  *  wait until all urbs are processed.
958  */
959 static int wait_clear_urbs(struct snd_usb_endpoint *ep)
960 {
961 	unsigned long end_time = jiffies + msecs_to_jiffies(1000);
962 	int alive;
963 
964 	if (atomic_read(&ep->state) != EP_STATE_STOPPING)
965 		return 0;
966 
967 	do {
968 		alive = atomic_read(&ep->submitted_urbs);
969 		if (!alive)
970 			break;
971 
972 		schedule_timeout_uninterruptible(1);
973 	} while (time_before(jiffies, end_time));
974 
975 	if (alive)
976 		usb_audio_err(ep->chip,
977 			"timeout: still %d active urbs on EP #%x\n",
978 			alive, ep->ep_num);
979 
980 	if (ep_state_update(ep, EP_STATE_STOPPING, EP_STATE_STOPPED)) {
981 		ep->sync_sink = NULL;
982 		snd_usb_endpoint_set_callback(ep, NULL, NULL, NULL);
983 	}
984 
985 	return 0;
986 }
987 
988 /* sync the pending stop operation;
989  * this function itself doesn't trigger the stop operation
990  */
991 void snd_usb_endpoint_sync_pending_stop(struct snd_usb_endpoint *ep)
992 {
993 	if (ep)
994 		wait_clear_urbs(ep);
995 }
996 
997 /*
998  * Stop active urbs
999  *
1000  * This function moves the EP to STOPPING state if it's being RUNNING.
1001  */
1002 static int stop_urbs(struct snd_usb_endpoint *ep, bool force, bool keep_pending)
1003 {
1004 	unsigned int i;
1005 	unsigned long flags;
1006 
1007 	if (!force && atomic_read(&ep->running))
1008 		return -EBUSY;
1009 
1010 	if (!ep_state_update(ep, EP_STATE_RUNNING, EP_STATE_STOPPING))
1011 		return 0;
1012 
1013 	spin_lock_irqsave(&ep->lock, flags);
1014 	INIT_LIST_HEAD(&ep->ready_playback_urbs);
1015 	ep->next_packet_head = 0;
1016 	ep->next_packet_queued = 0;
1017 	spin_unlock_irqrestore(&ep->lock, flags);
1018 
1019 	if (keep_pending)
1020 		return 0;
1021 
1022 	for (i = 0; i < ep->nurbs; i++) {
1023 		if (test_bit(i, &ep->active_mask)) {
1024 			if (!test_and_set_bit(i, &ep->unlink_mask)) {
1025 				struct urb *u = ep->urb[i].urb;
1026 				usb_unlink_urb(u);
1027 			}
1028 		}
1029 	}
1030 
1031 	return 0;
1032 }
1033 
1034 /*
1035  * release an endpoint's urbs
1036  */
1037 static int release_urbs(struct snd_usb_endpoint *ep, bool force)
1038 {
1039 	int i, err;
1040 
1041 	/* route incoming urbs to nirvana */
1042 	snd_usb_endpoint_set_callback(ep, NULL, NULL, NULL);
1043 
1044 	/* stop and unlink urbs */
1045 	err = stop_urbs(ep, force, false);
1046 	if (err)
1047 		return err;
1048 
1049 	wait_clear_urbs(ep);
1050 
1051 	for (i = 0; i < ep->nurbs; i++)
1052 		release_urb_ctx(&ep->urb[i]);
1053 
1054 	usb_free_coherent(ep->chip->dev, SYNC_URBS * 4,
1055 			  ep->syncbuf, ep->sync_dma);
1056 
1057 	ep->syncbuf = NULL;
1058 	ep->nurbs = 0;
1059 	return 0;
1060 }
1061 
1062 /*
1063  * configure a data endpoint
1064  */
1065 static int data_ep_set_params(struct snd_usb_endpoint *ep)
1066 {
1067 	struct snd_usb_audio *chip = ep->chip;
1068 	unsigned int maxsize, minsize, packs_per_ms, max_packs_per_urb;
1069 	unsigned int max_packs_per_period, urbs_per_period, urb_packs;
1070 	unsigned int max_urbs, i;
1071 	const struct audioformat *fmt = ep->cur_audiofmt;
1072 	int frame_bits = ep->cur_frame_bytes * 8;
1073 	int tx_length_quirk = (has_tx_length_quirk(chip) &&
1074 			       usb_pipeout(ep->pipe));
1075 
1076 	usb_audio_dbg(chip, "Setting params for data EP 0x%x, pipe 0x%x\n",
1077 		      ep->ep_num, ep->pipe);
1078 
1079 	if (ep->cur_format == SNDRV_PCM_FORMAT_DSD_U16_LE && fmt->dsd_dop) {
1080 		/*
1081 		 * When operating in DSD DOP mode, the size of a sample frame
1082 		 * in hardware differs from the actual physical format width
1083 		 * because we need to make room for the DOP markers.
1084 		 */
1085 		frame_bits += ep->cur_channels << 3;
1086 	}
1087 
1088 	ep->datainterval = fmt->datainterval;
1089 	ep->stride = frame_bits >> 3;
1090 
1091 	switch (ep->cur_format) {
1092 	case SNDRV_PCM_FORMAT_U8:
1093 		ep->silence_value = 0x80;
1094 		break;
1095 	case SNDRV_PCM_FORMAT_DSD_U8:
1096 	case SNDRV_PCM_FORMAT_DSD_U16_LE:
1097 	case SNDRV_PCM_FORMAT_DSD_U32_LE:
1098 	case SNDRV_PCM_FORMAT_DSD_U16_BE:
1099 	case SNDRV_PCM_FORMAT_DSD_U32_BE:
1100 		ep->silence_value = 0x69;
1101 		break;
1102 	default:
1103 		ep->silence_value = 0;
1104 	}
1105 
1106 	/* assume max. frequency is 50% higher than nominal */
1107 	ep->freqmax = ep->freqn + (ep->freqn >> 1);
1108 	/* Round up freqmax to nearest integer in order to calculate maximum
1109 	 * packet size, which must represent a whole number of frames.
1110 	 * This is accomplished by adding 0x0.ffff before converting the
1111 	 * Q16.16 format into integer.
1112 	 * In order to accurately calculate the maximum packet size when
1113 	 * the data interval is more than 1 (i.e. ep->datainterval > 0),
1114 	 * multiply by the data interval prior to rounding. For instance,
1115 	 * a freqmax of 41 kHz will result in a max packet size of 6 (5.125)
1116 	 * frames with a data interval of 1, but 11 (10.25) frames with a
1117 	 * data interval of 2.
1118 	 * (ep->freqmax << ep->datainterval overflows at 8.192 MHz for the
1119 	 * maximum datainterval value of 3, at USB full speed, higher for
1120 	 * USB high speed, noting that ep->freqmax is in units of
1121 	 * frames per packet in Q16.16 format.)
1122 	 */
1123 	maxsize = (((ep->freqmax << ep->datainterval) + 0xffff) >> 16) *
1124 			 (frame_bits >> 3);
1125 	if (tx_length_quirk)
1126 		maxsize += sizeof(__le32); /* Space for length descriptor */
1127 	/* but wMaxPacketSize might reduce this */
1128 	if (ep->maxpacksize && ep->maxpacksize < maxsize) {
1129 		/* whatever fits into a max. size packet */
1130 		unsigned int data_maxsize = maxsize = ep->maxpacksize;
1131 
1132 		if (tx_length_quirk)
1133 			/* Need to remove the length descriptor to calc freq */
1134 			data_maxsize -= sizeof(__le32);
1135 		ep->freqmax = (data_maxsize / (frame_bits >> 3))
1136 				<< (16 - ep->datainterval);
1137 	}
1138 
1139 	if (ep->fill_max)
1140 		ep->curpacksize = ep->maxpacksize;
1141 	else
1142 		ep->curpacksize = maxsize;
1143 
1144 	if (snd_usb_get_speed(chip->dev) != USB_SPEED_FULL) {
1145 		packs_per_ms = 8 >> ep->datainterval;
1146 		max_packs_per_urb = MAX_PACKS_HS;
1147 	} else {
1148 		packs_per_ms = 1;
1149 		max_packs_per_urb = MAX_PACKS;
1150 	}
1151 	if (ep->sync_source && !ep->implicit_fb_sync)
1152 		max_packs_per_urb = min(max_packs_per_urb,
1153 					1U << ep->sync_source->syncinterval);
1154 	max_packs_per_urb = max(1u, max_packs_per_urb >> ep->datainterval);
1155 
1156 	/*
1157 	 * Capture endpoints need to use small URBs because there's no way
1158 	 * to tell in advance where the next period will end, and we don't
1159 	 * want the next URB to complete much after the period ends.
1160 	 *
1161 	 * Playback endpoints with implicit sync much use the same parameters
1162 	 * as their corresponding capture endpoint.
1163 	 */
1164 	if (usb_pipein(ep->pipe) || ep->implicit_fb_sync) {
1165 
1166 		urb_packs = packs_per_ms;
1167 		/*
1168 		 * Wireless devices can poll at a max rate of once per 4ms.
1169 		 * For dataintervals less than 5, increase the packet count to
1170 		 * allow the host controller to use bursting to fill in the
1171 		 * gaps.
1172 		 */
1173 		if (snd_usb_get_speed(chip->dev) == USB_SPEED_WIRELESS) {
1174 			int interval = ep->datainterval;
1175 			while (interval < 5) {
1176 				urb_packs <<= 1;
1177 				++interval;
1178 			}
1179 		}
1180 		/* make capture URBs <= 1 ms and smaller than a period */
1181 		urb_packs = min(max_packs_per_urb, urb_packs);
1182 		while (urb_packs > 1 && urb_packs * maxsize >= ep->cur_period_bytes)
1183 			urb_packs >>= 1;
1184 		ep->nurbs = MAX_URBS;
1185 
1186 	/*
1187 	 * Playback endpoints without implicit sync are adjusted so that
1188 	 * a period fits as evenly as possible in the smallest number of
1189 	 * URBs.  The total number of URBs is adjusted to the size of the
1190 	 * ALSA buffer, subject to the MAX_URBS and MAX_QUEUE limits.
1191 	 */
1192 	} else {
1193 		/* determine how small a packet can be */
1194 		minsize = (ep->freqn >> (16 - ep->datainterval)) *
1195 				(frame_bits >> 3);
1196 		/* with sync from device, assume it can be 12% lower */
1197 		if (ep->sync_source)
1198 			minsize -= minsize >> 3;
1199 		minsize = max(minsize, 1u);
1200 
1201 		/* how many packets will contain an entire ALSA period? */
1202 		max_packs_per_period = DIV_ROUND_UP(ep->cur_period_bytes, minsize);
1203 
1204 		/* how many URBs will contain a period? */
1205 		urbs_per_period = DIV_ROUND_UP(max_packs_per_period,
1206 				max_packs_per_urb);
1207 		/* how many packets are needed in each URB? */
1208 		urb_packs = DIV_ROUND_UP(max_packs_per_period, urbs_per_period);
1209 
1210 		/* limit the number of frames in a single URB */
1211 		ep->max_urb_frames = DIV_ROUND_UP(ep->cur_period_frames,
1212 						  urbs_per_period);
1213 
1214 		/* try to use enough URBs to contain an entire ALSA buffer */
1215 		max_urbs = min((unsigned) MAX_URBS,
1216 				MAX_QUEUE * packs_per_ms / urb_packs);
1217 		ep->nurbs = min(max_urbs, urbs_per_period * ep->cur_buffer_periods);
1218 	}
1219 
1220 	/* allocate and initialize data urbs */
1221 	for (i = 0; i < ep->nurbs; i++) {
1222 		struct snd_urb_ctx *u = &ep->urb[i];
1223 		u->index = i;
1224 		u->ep = ep;
1225 		u->packets = urb_packs;
1226 		u->buffer_size = maxsize * u->packets;
1227 
1228 		if (fmt->fmt_type == UAC_FORMAT_TYPE_II)
1229 			u->packets++; /* for transfer delimiter */
1230 		u->urb = usb_alloc_urb(u->packets, GFP_KERNEL);
1231 		if (!u->urb)
1232 			goto out_of_memory;
1233 
1234 		u->urb->transfer_buffer =
1235 			usb_alloc_coherent(chip->dev, u->buffer_size,
1236 					   GFP_KERNEL, &u->urb->transfer_dma);
1237 		if (!u->urb->transfer_buffer)
1238 			goto out_of_memory;
1239 		u->urb->pipe = ep->pipe;
1240 		u->urb->transfer_flags = URB_NO_TRANSFER_DMA_MAP;
1241 		u->urb->interval = 1 << ep->datainterval;
1242 		u->urb->context = u;
1243 		u->urb->complete = snd_complete_urb;
1244 		INIT_LIST_HEAD(&u->ready_list);
1245 	}
1246 
1247 	return 0;
1248 
1249 out_of_memory:
1250 	release_urbs(ep, false);
1251 	return -ENOMEM;
1252 }
1253 
1254 /*
1255  * configure a sync endpoint
1256  */
1257 static int sync_ep_set_params(struct snd_usb_endpoint *ep)
1258 {
1259 	struct snd_usb_audio *chip = ep->chip;
1260 	int i;
1261 
1262 	usb_audio_dbg(chip, "Setting params for sync EP 0x%x, pipe 0x%x\n",
1263 		      ep->ep_num, ep->pipe);
1264 
1265 	ep->syncbuf = usb_alloc_coherent(chip->dev, SYNC_URBS * 4,
1266 					 GFP_KERNEL, &ep->sync_dma);
1267 	if (!ep->syncbuf)
1268 		return -ENOMEM;
1269 
1270 	for (i = 0; i < SYNC_URBS; i++) {
1271 		struct snd_urb_ctx *u = &ep->urb[i];
1272 		u->index = i;
1273 		u->ep = ep;
1274 		u->packets = 1;
1275 		u->urb = usb_alloc_urb(1, GFP_KERNEL);
1276 		if (!u->urb)
1277 			goto out_of_memory;
1278 		u->urb->transfer_buffer = ep->syncbuf + i * 4;
1279 		u->urb->transfer_dma = ep->sync_dma + i * 4;
1280 		u->urb->transfer_buffer_length = 4;
1281 		u->urb->pipe = ep->pipe;
1282 		u->urb->transfer_flags = URB_NO_TRANSFER_DMA_MAP;
1283 		u->urb->number_of_packets = 1;
1284 		u->urb->interval = 1 << ep->syncinterval;
1285 		u->urb->context = u;
1286 		u->urb->complete = snd_complete_urb;
1287 	}
1288 
1289 	ep->nurbs = SYNC_URBS;
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