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