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_configure().
744 */
745 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)746 snd_usb_endpoint_open(struct snd_usb_audio *chip,
747 const struct audioformat *fp,
748 const struct snd_pcm_hw_params *params,
749 bool is_sync_ep)
750 {
751 struct snd_usb_endpoint *ep;
752 int ep_num = is_sync_ep ? fp->sync_ep : fp->endpoint;
753
754 mutex_lock(&chip->mutex);
755 ep = snd_usb_get_endpoint(chip, ep_num);
756 if (!ep) {
757 usb_audio_err(chip, "Cannot find EP 0x%x to open\n", ep_num);
758 goto unlock;
759 }
760
761 if (!ep->opened) {
762 if (is_sync_ep) {
763 ep->iface = fp->sync_iface;
764 ep->altsetting = fp->sync_altsetting;
765 ep->ep_idx = fp->sync_ep_idx;
766 } else {
767 ep->iface = fp->iface;
768 ep->altsetting = fp->altsetting;
769 ep->ep_idx = fp->ep_idx;
770 }
771 usb_audio_dbg(chip, "Open EP 0x%x, iface=%d:%d, idx=%d\n",
772 ep_num, ep->iface, ep->altsetting, ep->ep_idx);
773
774 ep->iface_ref = iface_ref_find(chip, ep->iface);
775 if (!ep->iface_ref) {
776 ep = NULL;
777 goto unlock;
778 }
779
780 ep->cur_audiofmt = fp;
781 ep->cur_channels = fp->channels;
782 ep->cur_rate = params_rate(params);
783 ep->cur_format = params_format(params);
784 ep->cur_frame_bytes = snd_pcm_format_physical_width(ep->cur_format) *
785 ep->cur_channels / 8;
786 ep->cur_period_frames = params_period_size(params);
787 ep->cur_period_bytes = ep->cur_period_frames * ep->cur_frame_bytes;
788 ep->cur_buffer_periods = params_periods(params);
789 ep->cur_clock = fp->clock;
790
791 if (ep->type == SND_USB_ENDPOINT_TYPE_SYNC)
792 endpoint_set_syncinterval(chip, ep);
793
794 ep->implicit_fb_sync = fp->implicit_fb;
795 ep->need_setup = true;
796
797 usb_audio_dbg(chip, " channels=%d, rate=%d, format=%s, period_bytes=%d, periods=%d, implicit_fb=%d\n",
798 ep->cur_channels, ep->cur_rate,
799 snd_pcm_format_name(ep->cur_format),
800 ep->cur_period_bytes, ep->cur_buffer_periods,
801 ep->implicit_fb_sync);
802
803 } else {
804 if (WARN_ON(!ep->iface_ref)) {
805 ep = NULL;
806 goto unlock;
807 }
808
809 if (!endpoint_compatible(ep, fp, params)) {
810 usb_audio_err(chip, "Incompatible EP setup for 0x%x\n",
811 ep_num);
812 ep = NULL;
813 goto unlock;
814 }
815
816 usb_audio_dbg(chip, "Reopened EP 0x%x (count %d)\n",
817 ep_num, ep->opened);
818 }
819
820 if (!ep->iface_ref->opened++)
821 ep->iface_ref->need_setup = true;
822
823 ep->opened++;
824
825 unlock:
826 mutex_unlock(&chip->mutex);
827 return ep;
828 }
829 EXPORT_SYMBOL_GPL(snd_usb_endpoint_open);
830
831 /*
832 * snd_usb_endpoint_set_sync: Link data and sync endpoints
833 *
834 * Pass NULL to sync_ep to unlink again
835 */
snd_usb_endpoint_set_sync(struct snd_usb_audio * chip,struct snd_usb_endpoint * data_ep,struct snd_usb_endpoint * sync_ep)836 void snd_usb_endpoint_set_sync(struct snd_usb_audio *chip,
837 struct snd_usb_endpoint *data_ep,
838 struct snd_usb_endpoint *sync_ep)
839 {
840 data_ep->sync_source = sync_ep;
841 }
842
843 /*
844 * Set data endpoint callbacks and the assigned data stream
845 *
846 * Called at PCM trigger and cleanups.
847 * Pass NULL to deactivate each callback.
848 */
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)849 void snd_usb_endpoint_set_callback(struct snd_usb_endpoint *ep,
850 int (*prepare)(struct snd_usb_substream *subs,
851 struct urb *urb,
852 bool in_stream_lock),
853 void (*retire)(struct snd_usb_substream *subs,
854 struct urb *urb),
855 struct snd_usb_substream *data_subs)
856 {
857 ep->prepare_data_urb = prepare;
858 ep->retire_data_urb = retire;
859 if (data_subs)
860 ep->lowlatency_playback = data_subs->lowlatency_playback;
861 else
862 ep->lowlatency_playback = false;
863 WRITE_ONCE(ep->data_subs, data_subs);
864 }
865
endpoint_set_interface(struct snd_usb_audio * chip,struct snd_usb_endpoint * ep,bool set)866 static int endpoint_set_interface(struct snd_usb_audio *chip,
867 struct snd_usb_endpoint *ep,
868 bool set)
869 {
870 int altset = set ? ep->altsetting : 0;
871 int err;
872
873 usb_audio_dbg(chip, "Setting usb interface %d:%d for EP 0x%x\n",
874 ep->iface, altset, ep->ep_num);
875 err = usb_set_interface(chip->dev, ep->iface, altset);
876 if (err < 0) {
877 usb_audio_err(chip, "%d:%d: usb_set_interface failed (%d)\n",
878 ep->iface, altset, err);
879 return err;
880 }
881
882 if (chip->quirk_flags & QUIRK_FLAG_IFACE_DELAY)
883 msleep(50);
884 return 0;
885 }
886
887 /*
888 * snd_usb_endpoint_close: Close the endpoint
889 *
890 * Unreference the already opened endpoint via snd_usb_endpoint_open().
891 */
snd_usb_endpoint_close(struct snd_usb_audio * chip,struct snd_usb_endpoint * ep)892 void snd_usb_endpoint_close(struct snd_usb_audio *chip,
893 struct snd_usb_endpoint *ep)
894 {
895 mutex_lock(&chip->mutex);
896 usb_audio_dbg(chip, "Closing EP 0x%x (count %d)\n",
897 ep->ep_num, ep->opened);
898
899 if (!--ep->iface_ref->opened &&
900 !(chip->quirk_flags & QUIRK_FLAG_IFACE_SKIP_CLOSE))
901 endpoint_set_interface(chip, ep, false);
902
903 if (!--ep->opened) {
904 ep->iface = 0;
905 ep->altsetting = 0;
906 ep->cur_audiofmt = NULL;
907 ep->cur_rate = 0;
908 ep->cur_clock = 0;
909 ep->iface_ref = NULL;
910 usb_audio_dbg(chip, "EP 0x%x closed\n", ep->ep_num);
911 }
912 mutex_unlock(&chip->mutex);
913 }
914 EXPORT_SYMBOL_GPL(snd_usb_endpoint_close);
915
916 /* Prepare for suspening EP, called from the main suspend handler */
snd_usb_endpoint_suspend(struct snd_usb_endpoint * ep)917 void snd_usb_endpoint_suspend(struct snd_usb_endpoint *ep)
918 {
919 ep->need_setup = true;
920 if (ep->iface_ref)
921 ep->iface_ref->need_setup = true;
922 }
923
924 /*
925 * wait until all urbs are processed.
926 */
wait_clear_urbs(struct snd_usb_endpoint * ep)927 static int wait_clear_urbs(struct snd_usb_endpoint *ep)
928 {
929 unsigned long end_time = jiffies + msecs_to_jiffies(1000);
930 int alive;
931
932 if (atomic_read(&ep->state) != EP_STATE_STOPPING)
933 return 0;
934
935 do {
936 alive = atomic_read(&ep->submitted_urbs);
937 if (!alive)
938 break;
939
940 schedule_timeout_uninterruptible(1);
941 } while (time_before(jiffies, end_time));
942
943 if (alive)
944 usb_audio_err(ep->chip,
945 "timeout: still %d active urbs on EP #%x\n",
946 alive, ep->ep_num);
947
948 if (ep_state_update(ep, EP_STATE_STOPPING, EP_STATE_STOPPED)) {
949 ep->sync_sink = NULL;
950 snd_usb_endpoint_set_callback(ep, NULL, NULL, NULL);
951 }
952
953 return 0;
954 }
955
956 /* sync the pending stop operation;
957 * this function itself doesn't trigger the stop operation
958 */
snd_usb_endpoint_sync_pending_stop(struct snd_usb_endpoint * ep)959 void snd_usb_endpoint_sync_pending_stop(struct snd_usb_endpoint *ep)
960 {
961 if (ep)
962 wait_clear_urbs(ep);
963 }
964
965 /*
966 * Stop active urbs
967 *
968 * This function moves the EP to STOPPING state if it's being RUNNING.
969 */
stop_urbs(struct snd_usb_endpoint * ep,bool force,bool keep_pending)970 static int stop_urbs(struct snd_usb_endpoint *ep, bool force, bool keep_pending)
971 {
972 unsigned int i;
973 unsigned long flags;
974
975 if (!force && atomic_read(&ep->running))
976 return -EBUSY;
977
978 if (!ep_state_update(ep, EP_STATE_RUNNING, EP_STATE_STOPPING))
979 return 0;
980
981 spin_lock_irqsave(&ep->lock, flags);
982 INIT_LIST_HEAD(&ep->ready_playback_urbs);
983 ep->next_packet_head = 0;
984 ep->next_packet_queued = 0;
985 spin_unlock_irqrestore(&ep->lock, flags);
986
987 if (keep_pending)
988 return 0;
989
990 for (i = 0; i < ep->nurbs; i++) {
991 if (test_bit(i, &ep->active_mask)) {
992 if (!test_and_set_bit(i, &ep->unlink_mask)) {
993 struct urb *u = ep->urb[i].urb;
994 usb_unlink_urb(u);
995 }
996 }
997 }
998
999 return 0;
1000 }
1001
1002 /*
1003 * release an endpoint's urbs
1004 */
release_urbs(struct snd_usb_endpoint * ep,bool force)1005 static int release_urbs(struct snd_usb_endpoint *ep, bool force)
1006 {
1007 int i, err;
1008
1009 /* route incoming urbs to nirvana */
1010 snd_usb_endpoint_set_callback(ep, NULL, NULL, NULL);
1011
1012 /* stop and unlink urbs */
1013 err = stop_urbs(ep, force, false);
1014 if (err)
1015 return err;
1016
1017 wait_clear_urbs(ep);
1018
1019 for (i = 0; i < ep->nurbs; i++)
1020 release_urb_ctx(&ep->urb[i]);
1021
1022 usb_free_coherent(ep->chip->dev, SYNC_URBS * 4,
1023 ep->syncbuf, ep->sync_dma);
1024
1025 ep->syncbuf = NULL;
1026 ep->nurbs = 0;
1027 return 0;
1028 }
1029
1030 /*
1031 * configure a data endpoint
1032 */
data_ep_set_params(struct snd_usb_endpoint * ep)1033 static int data_ep_set_params(struct snd_usb_endpoint *ep)
1034 {
1035 struct snd_usb_audio *chip = ep->chip;
1036 unsigned int maxsize, minsize, packs_per_ms, max_packs_per_urb;
1037 unsigned int max_packs_per_period, urbs_per_period, urb_packs;
1038 unsigned int max_urbs, i;
1039 const struct audioformat *fmt = ep->cur_audiofmt;
1040 int frame_bits = ep->cur_frame_bytes * 8;
1041 int tx_length_quirk = (has_tx_length_quirk(chip) &&
1042 usb_pipeout(ep->pipe));
1043
1044 usb_audio_dbg(chip, "Setting params for data EP 0x%x, pipe 0x%x\n",
1045 ep->ep_num, ep->pipe);
1046
1047 if (ep->cur_format == SNDRV_PCM_FORMAT_DSD_U16_LE && fmt->dsd_dop) {
1048 /*
1049 * When operating in DSD DOP mode, the size of a sample frame
1050 * in hardware differs from the actual physical format width
1051 * because we need to make room for the DOP markers.
1052 */
1053 frame_bits += ep->cur_channels << 3;
1054 }
1055
1056 ep->datainterval = fmt->datainterval;
1057 ep->stride = frame_bits >> 3;
1058
1059 switch (ep->cur_format) {
1060 case SNDRV_PCM_FORMAT_U8:
1061 ep->silence_value = 0x80;
1062 break;
1063 case SNDRV_PCM_FORMAT_DSD_U8:
1064 case SNDRV_PCM_FORMAT_DSD_U16_LE:
1065 case SNDRV_PCM_FORMAT_DSD_U32_LE:
1066 case SNDRV_PCM_FORMAT_DSD_U16_BE:
1067 case SNDRV_PCM_FORMAT_DSD_U32_BE:
1068 ep->silence_value = 0x69;
1069 break;
1070 default:
1071 ep->silence_value = 0;
1072 }
1073
1074 /* assume max. frequency is 50% higher than nominal */
1075 ep->freqmax = ep->freqn + (ep->freqn >> 1);
1076 /* Round up freqmax to nearest integer in order to calculate maximum
1077 * packet size, which must represent a whole number of frames.
1078 * This is accomplished by adding 0x0.ffff before converting the
1079 * Q16.16 format into integer.
1080 * In order to accurately calculate the maximum packet size when
1081 * the data interval is more than 1 (i.e. ep->datainterval > 0),
1082 * multiply by the data interval prior to rounding. For instance,
1083 * a freqmax of 41 kHz will result in a max packet size of 6 (5.125)
1084 * frames with a data interval of 1, but 11 (10.25) frames with a
1085 * data interval of 2.
1086 * (ep->freqmax << ep->datainterval overflows at 8.192 MHz for the
1087 * maximum datainterval value of 3, at USB full speed, higher for
1088 * USB high speed, noting that ep->freqmax is in units of
1089 * frames per packet in Q16.16 format.)
1090 */
1091 maxsize = (((ep->freqmax << ep->datainterval) + 0xffff) >> 16) *
1092 (frame_bits >> 3);
1093 if (tx_length_quirk)
1094 maxsize += sizeof(__le32); /* Space for length descriptor */
1095 /* but wMaxPacketSize might reduce this */
1096 if (ep->maxpacksize && ep->maxpacksize < maxsize) {
1097 /* whatever fits into a max. size packet */
1098 unsigned int data_maxsize = maxsize = ep->maxpacksize;
1099
1100 if (tx_length_quirk)
1101 /* Need to remove the length descriptor to calc freq */
1102 data_maxsize -= sizeof(__le32);
1103 ep->freqmax = (data_maxsize / (frame_bits >> 3))
1104 << (16 - ep->datainterval);
1105 }
1106
1107 if (ep->fill_max)
1108 ep->curpacksize = ep->maxpacksize;
1109 else
1110 ep->curpacksize = maxsize;
1111
1112 if (snd_usb_get_speed(chip->dev) != USB_SPEED_FULL) {
1113 packs_per_ms = 8 >> ep->datainterval;
1114 max_packs_per_urb = MAX_PACKS_HS;
1115 } else {
1116 packs_per_ms = 1;
1117 max_packs_per_urb = MAX_PACKS;
1118 }
1119 if (ep->sync_source && !ep->implicit_fb_sync)
1120 max_packs_per_urb = min(max_packs_per_urb,
1121 1U << ep->sync_source->syncinterval);
1122 max_packs_per_urb = max(1u, max_packs_per_urb >> ep->datainterval);
1123
1124 /*
1125 * Capture endpoints need to use small URBs because there's no way
1126 * to tell in advance where the next period will end, and we don't
1127 * want the next URB to complete much after the period ends.
1128 *
1129 * Playback endpoints with implicit sync much use the same parameters
1130 * as their corresponding capture endpoint.
1131 */
1132 if (usb_pipein(ep->pipe) || ep->implicit_fb_sync) {
1133
1134 urb_packs = packs_per_ms;
1135 /*
1136 * Wireless devices can poll at a max rate of once per 4ms.
1137 * For dataintervals less than 5, increase the packet count to
1138 * allow the host controller to use bursting to fill in the
1139 * gaps.
1140 */
1141 if (snd_usb_get_speed(chip->dev) == USB_SPEED_WIRELESS) {
1142 int interval = ep->datainterval;
1143 while (interval < 5) {
1144 urb_packs <<= 1;
1145 ++interval;
1146 }
1147 }
1148 /* make capture URBs <= 1 ms and smaller than a period */
1149 urb_packs = min(max_packs_per_urb, urb_packs);
1150 while (urb_packs > 1 && urb_packs * maxsize >= ep->cur_period_bytes)
1151 urb_packs >>= 1;
1152 ep->nurbs = MAX_URBS;
1153
1154 /*
1155 * Playback endpoints without implicit sync are adjusted so that
1156 * a period fits as evenly as possible in the smallest number of
1157 * URBs. The total number of URBs is adjusted to the size of the
1158 * ALSA buffer, subject to the MAX_URBS and MAX_QUEUE limits.
1159 */
1160 } else {
1161 /* determine how small a packet can be */
1162 minsize = (ep->freqn >> (16 - ep->datainterval)) *
1163 (frame_bits >> 3);
1164 /* with sync from device, assume it can be 12% lower */
1165 if (ep->sync_source)
1166 minsize -= minsize >> 3;
1167 minsize = max(minsize, 1u);
1168
1169 /* how many packets will contain an entire ALSA period? */
1170 max_packs_per_period = DIV_ROUND_UP(ep->cur_period_bytes, minsize);
1171
1172 /* how many URBs will contain a period? */
1173 urbs_per_period = DIV_ROUND_UP(max_packs_per_period,
1174 max_packs_per_urb);
1175 /* how many packets are needed in each URB? */
1176 urb_packs = DIV_ROUND_UP(max_packs_per_period, urbs_per_period);
1177
1178 /* limit the number of frames in a single URB */
1179 ep->max_urb_frames = DIV_ROUND_UP(ep->cur_period_frames,
1180 urbs_per_period);
1181
1182 /* try to use enough URBs to contain an entire ALSA buffer */
1183 max_urbs = min((unsigned) MAX_URBS,
1184 MAX_QUEUE * packs_per_ms / urb_packs);
1185 ep->nurbs = min(max_urbs, urbs_per_period * ep->cur_buffer_periods);
1186 }
1187
1188 /* allocate and initialize data urbs */
1189 for (i = 0; i < ep->nurbs; i++) {
1190 struct snd_urb_ctx *u = &ep->urb[i];
1191 u->index = i;
1192 u->ep = ep;
1193 u->packets = urb_packs;
1194 u->buffer_size = maxsize * u->packets;
1195
1196 if (fmt->fmt_type == UAC_FORMAT_TYPE_II)
1197 u->packets++; /* for transfer delimiter */
1198 u->urb = usb_alloc_urb(u->packets, GFP_KERNEL);
1199 if (!u->urb)
1200 goto out_of_memory;
1201
1202 u->urb->transfer_buffer =
1203 usb_alloc_coherent(chip->dev, u->buffer_size,
1204 GFP_KERNEL, &u->urb->transfer_dma);
1205 if (!u->urb->transfer_buffer)
1206 goto out_of_memory;
1207 u->urb->pipe = ep->pipe;
1208 u->urb->transfer_flags = URB_NO_TRANSFER_DMA_MAP;
1209 u->urb->interval = 1 << ep->datainterval;
1210 u->urb->context = u;
1211 u->urb->complete = snd_complete_urb;
1212 INIT_LIST_HEAD(&u->ready_list);
1213 }
1214
1215 return 0;
1216
1217 out_of_memory:
1218 release_urbs(ep, false);
1219 return -ENOMEM;
1220 }
1221
1222 /*
1223 * configure a sync endpoint
1224 */
sync_ep_set_params(struct snd_usb_endpoint * ep)1225 static int sync_ep_set_params(struct snd_usb_endpoint *ep)
1226 {
1227 struct snd_usb_audio *chip = ep->chip;
1228 int i;
1229
1230 usb_audio_dbg(chip, "Setting params for sync EP 0x%x, pipe 0x%x\n",
1231 ep->ep_num, ep->pipe);
1232
1233 ep->syncbuf = usb_alloc_coherent(chip->dev, SYNC_URBS * 4,
1234 GFP_KERNEL, &ep->sync_dma);
1235 if (!ep->syncbuf)
1236 return -ENOMEM;
1237
1238 ep->nurbs = SYNC_URBS;
1239 for (i = 0; i < SYNC_URBS; i++) {
1240 struct snd_urb_ctx *u = &ep->urb[i];
1241 u->index = i;
1242 u->ep = ep;
1243 u->packets = 1;
1244 u->urb = usb_alloc_urb(1, GFP_KERNEL);
1245 if (!u->urb)
1246 goto out_of_memory;
1247 u->urb->transfer_buffer = ep->syncbuf + i * 4;
1248 u->urb->transfer_dma = ep->sync_dma + i * 4;
1249 u->urb->transfer_buffer_length = 4;
1250 u->urb->pipe = ep->pipe;
1251 u->urb->transfer_flags = URB_NO_TRANSFER_DMA_MAP;
1252 u->urb->number_of_packets = 1;
1253 u->urb->interval = 1 << ep->syncinterval;
1254 u->urb->context = u;
1255 u->urb->complete = snd_complete_urb;
1256 }
1257
1258 return 0;
1259
1260 out_of_memory:
1261 release_urbs(ep, false);
1262 return -ENOMEM;
1263 }
1264
1265 /*
1266 * snd_usb_endpoint_set_params: configure an snd_usb_endpoint
1267 *
1268 * Determine the number of URBs to be used on this endpoint.
1269 * An endpoint must be configured before it can be started.
1270 * An endpoint that is already running can not be reconfigured.
1271 */
snd_usb_endpoint_set_params(struct snd_usb_audio * chip,struct snd_usb_endpoint * ep)1272 static int snd_usb_endpoint_set_params(struct snd_usb_audio *chip,
1273 struct snd_usb_endpoint *ep)
1274 {
1275 const struct audioformat *fmt = ep->cur_audiofmt;
1276 int err;
1277
1278 /* release old buffers, if any */
1279 err = release_urbs(ep, false);
1280 if (err < 0)
1281 return err;
1282
1283 ep->datainterval = fmt->datainterval;
1284 ep->maxpacksize = fmt->maxpacksize;
1285 ep->fill_max = !!(fmt->attributes & UAC_EP_CS_ATTR_FILL_MAX);
1286
1287 if (snd_usb_get_speed(chip->dev) == USB_SPEED_FULL) {
1288 ep->freqn = get_usb_full_speed_rate(ep->cur_rate);
1289 ep->pps = 1000 >> ep->datainterval;
1290 } else {
1291 ep->freqn = get_usb_high_speed_rate(ep->cur_rate);
1292 ep->pps = 8000 >> ep->datainterval;
1293 }
1294
1295 ep->sample_rem = ep->cur_rate % ep->pps;
1296 ep->packsize[0] = ep->cur_rate / ep->pps;
1297 ep->packsize[1] = (ep->cur_rate + (ep->pps - 1)) / ep->pps;
1298
1299 /* calculate the frequency in 16.16 format */
1300 ep->freqm = ep->freqn;
1301 ep->freqshift = INT_MIN;
1302
1303 ep->phase = 0;
1304
1305 switch (ep->type) {
1306 case SND_USB_ENDPOINT_TYPE_DATA:
1307 err = data_ep_set_params(ep);
1308 break;
1309 case SND_USB_ENDPOINT_TYPE_SYNC:
1310 err = sync_ep_set_params(ep);
1311 break;
1312 default:
1313 err = -EINVAL;
1314 }
1315
1316 usb_audio_dbg(chip, "Set up %d URBS, ret=%d\n", ep->nurbs, err);
1317
1318 if (err < 0)
1319 return err;
1320
1321 /* some unit conversions in runtime */
1322 ep->maxframesize = ep->maxpacksize / ep->cur_frame_bytes;
1323 ep->curframesize = ep->curpacksize / ep->cur_frame_bytes;
1324
1325 return 0;
1326 }
1327
1328 /*
1329 * snd_usb_endpoint_configure: Configure the endpoint
1330 *
1331 * This function sets up the EP to be fully usable state.
1332 * It's called either from hw_params or prepare callback.
1333 * The function checks need_setup flag, and performs nothing unless needed,
1334 * so it's safe to call this multiple times.
1335 *
1336 * This returns zero if unchanged, 1 if the configuration has changed,
1337 * or a negative error code.
1338 */
snd_usb_endpoint_configure(struct snd_usb_audio * chip,struct snd_usb_endpoint * ep)1339 int snd_usb_endpoint_configure(struct snd_usb_audio *chip,
1340 struct snd_usb_endpoint *ep)
1341 {
1342 bool iface_first;
1343 int err = 0;
1344
1345 mutex_lock(&chip->mutex);
1346 if (WARN_ON(!ep->iface_ref))
1347 goto unlock;
1348 if (!ep->need_setup)
1349 goto unlock;
1350
1351 /* If the interface has been already set up, just set EP parameters */
1352 if (!ep->iface_ref->need_setup) {
1353 /* sample rate setup of UAC1 is per endpoint, and we need
1354 * to update at each EP configuration
1355 */
1356 if (ep->cur_audiofmt->protocol == UAC_VERSION_1) {
1357 err = snd_usb_init_sample_rate(chip, ep->cur_audiofmt,
1358 ep->cur_rate);
1359 if (err < 0)
1360 goto unlock;
1361 }
1362 err = snd_usb_endpoint_set_params(chip, ep);
1363 if (err < 0)
1364 goto unlock;
1365 goto done;
1366 }
1367
1368 /* Need to deselect altsetting at first */
1369 endpoint_set_interface(chip, ep, false);
1370
1371 /* Some UAC1 devices (e.g. Yamaha THR10) need the host interface
1372 * to be set up before parameter setups
1373 */
1374 iface_first = ep->cur_audiofmt->protocol == UAC_VERSION_1;
1375 /* Workaround for devices that require the interface setup at first like UAC1 */
1376 if (chip->quirk_flags & QUIRK_FLAG_SET_IFACE_FIRST)
1377 iface_first = true;
1378 if (iface_first) {
1379 err = endpoint_set_interface(chip, ep, true);
1380 if (err < 0)
1381 goto unlock;
1382 }
1383
1384 err = snd_usb_init_pitch(chip, ep->cur_audiofmt);
1385 if (err < 0)
1386 goto unlock;
1387
1388 err = snd_usb_init_sample_rate(chip, ep->cur_audiofmt, ep->cur_rate);
1389 if (err < 0)
1390 goto unlock;
1391
1392 err = snd_usb_endpoint_set_params(chip, ep);
1393 if (err < 0)
1394 goto unlock;
1395
1396 err = snd_usb_select_mode_quirk(chip, ep->cur_audiofmt);
1397 if (err < 0)
1398 goto unlock;
1399
1400 /* for UAC2/3, enable the interface altset here at last */
1401 if (!iface_first) {
1402 err = endpoint_set_interface(chip, ep, true);
1403 if (err < 0)
1404 goto unlock;
1405 }
1406
1407 ep->iface_ref->need_setup = false;
1408
1409 done:
1410 ep->need_setup = false;
1411 err = 1;
1412
1413 unlock:
1414 mutex_unlock(&chip->mutex);
1415 return err;
1416 }
1417 EXPORT_SYMBOL_GPL(snd_usb_endpoint_configure);
1418
1419 /* 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)1420 int snd_usb_endpoint_get_clock_rate(struct snd_usb_audio *chip, int clock)
1421 {
1422 struct snd_usb_endpoint *ep;
1423 int rate = 0;
1424
1425 if (!clock)
1426 return 0;
1427 mutex_lock(&chip->mutex);
1428 list_for_each_entry(ep, &chip->ep_list, list) {
1429 if (ep->cur_clock == clock && ep->cur_rate) {
1430 rate = ep->cur_rate;
1431 break;
1432 }
1433 }
1434 mutex_unlock(&chip->mutex);
1435 return rate;
1436 }
1437
1438 /**
1439 * snd_usb_endpoint_start: start an snd_usb_endpoint
1440 *
1441 * @ep: the endpoint to start
1442 *
1443 * A call to this function will increment the running count of the endpoint.
1444 * In case it is not already running, the URBs for this endpoint will be
1445 * submitted. Otherwise, this function does nothing.
1446 *
1447 * Must be balanced to calls of snd_usb_endpoint_stop().
1448 *
1449 * Returns an error if the URB submission failed, 0 in all other cases.
1450 */
snd_usb_endpoint_start(struct snd_usb_endpoint * ep)1451 int snd_usb_endpoint_start(struct snd_usb_endpoint *ep)
1452 {
1453 bool is_playback = usb_pipeout(ep->pipe);
1454 int err;
1455 unsigned int i;
1456
1457 if (atomic_read(&ep->chip->shutdown))
1458 return -EBADFD;
1459
1460 if (ep->sync_source)
1461 WRITE_ONCE(ep->sync_source->sync_sink, ep);
1462
1463 usb_audio_dbg(ep->chip, "Starting %s EP 0x%x (running %d)\n",
1464 ep_type_name(ep->type), ep->ep_num,
1465 atomic_read(&ep->running));
1466
1467 /* already running? */
1468 if (atomic_inc_return(&ep->running) != 1)
1469 return 0;
1470
1471 ep->active_mask = 0;
1472 ep->unlink_mask = 0;
1473 ep->phase = 0;
1474 ep->sample_accum = 0;
1475
1476 snd_usb_endpoint_start_quirk(ep);
1477
1478 /*
1479 * If this endpoint has a data endpoint as implicit feedback source,
1480 * don't start the urbs here. Instead, mark them all as available,
1481 * wait for the record urbs to return and queue the playback urbs
1482 * from that context.
1483 */
1484
1485 if (!ep_state_update(ep, EP_STATE_STOPPED, EP_STATE_RUNNING))
1486 goto __error;
1487
1488 if (snd_usb_endpoint_implicit_feedback_sink(ep) &&
1489 !(ep->chip->quirk_flags & QUIRK_FLAG_PLAYBACK_FIRST)) {
1490 usb_audio_dbg(ep->chip, "No URB submission due to implicit fb sync\n");
1491 i = 0;
1492 goto fill_rest;
1493 }
1494
1495 trace_android_vh_audio_usb_offload_ep_action(ep, true);
1496
1497 for (i = 0; i < ep->nurbs; i++) {
1498 struct urb *urb = ep->urb[i].urb;
1499
1500 if (snd_BUG_ON(!urb))
1501 goto __error;
1502
1503 if (is_playback)
1504 err = prepare_outbound_urb(ep, urb->context, true);
1505 else
1506 err = prepare_inbound_urb(ep, urb->context);
1507 if (err < 0) {
1508 /* stop filling at applptr */
1509 if (err == -EAGAIN)
1510 break;
1511 usb_audio_dbg(ep->chip,
1512 "EP 0x%x: failed to prepare urb: %d\n",
1513 ep->ep_num, err);
1514 goto __error;
1515 }
1516
1517 err = usb_submit_urb(urb, GFP_ATOMIC);
1518 if (err < 0) {
1519 usb_audio_err(ep->chip,
1520 "cannot submit urb %d, error %d: %s\n",
1521 i, err, usb_error_string(err));
1522 goto __error;
1523 }
1524 set_bit(i, &ep->active_mask);
1525 atomic_inc(&ep->submitted_urbs);
1526 }
1527
1528 if (!i) {
1529 usb_audio_dbg(ep->chip, "XRUN at starting EP 0x%x\n",
1530 ep->ep_num);
1531 goto __error;
1532 }
1533
1534 usb_audio_dbg(ep->chip, "%d URBs submitted for EP 0x%x\n",
1535 i, ep->ep_num);
1536
1537 fill_rest:
1538 /* put the remaining URBs to ready list */
1539 if (is_playback) {
1540 for (; i < ep->nurbs; i++)
1541 push_back_to_ready_list(ep, ep->urb + i);
1542 }
1543
1544 return 0;
1545
1546 __error:
1547 snd_usb_endpoint_stop(ep, false);
1548 return -EPIPE;
1549 }
1550
1551 /**
1552 * snd_usb_endpoint_stop: stop an snd_usb_endpoint
1553 *
1554 * @ep: the endpoint to stop (may be NULL)
1555 * @keep_pending: keep in-flight URBs
1556 *
1557 * A call to this function will decrement the running count of the endpoint.
1558 * In case the last user has requested the endpoint stop, the URBs will
1559 * actually be deactivated.
1560 *
1561 * Must be balanced to calls of snd_usb_endpoint_start().
1562 *
1563 * The caller needs to synchronize the pending stop operation via
1564 * snd_usb_endpoint_sync_pending_stop().
1565 */
snd_usb_endpoint_stop(struct snd_usb_endpoint * ep,bool keep_pending)1566 void snd_usb_endpoint_stop(struct snd_usb_endpoint *ep, bool keep_pending)
1567 {
1568 if (!ep)
1569 return;
1570
1571 usb_audio_dbg(ep->chip, "Stopping %s EP 0x%x (running %d)\n",
1572 ep_type_name(ep->type), ep->ep_num,
1573 atomic_read(&ep->running));
1574
1575 if (snd_BUG_ON(!atomic_read(&ep->running)))
1576 return;
1577
1578 if (!atomic_dec_return(&ep->running)) {
1579 if (ep->sync_source)
1580 WRITE_ONCE(ep->sync_source->sync_sink, NULL);
1581 stop_urbs(ep, false, keep_pending);
1582 trace_android_vh_audio_usb_offload_ep_action(ep, false);
1583 }
1584 }
1585
1586 /**
1587 * snd_usb_endpoint_release: Tear down an snd_usb_endpoint
1588 *
1589 * @ep: the endpoint to release
1590 *
1591 * This function does not care for the endpoint's running count but will tear
1592 * down all the streaming URBs immediately.
1593 */
snd_usb_endpoint_release(struct snd_usb_endpoint * ep)1594 void snd_usb_endpoint_release(struct snd_usb_endpoint *ep)
1595 {
1596 release_urbs(ep, true);
1597 }
1598
1599 /**
1600 * snd_usb_endpoint_free_all: Free the resources of an snd_usb_endpoint
1601 * @chip: The chip
1602 *
1603 * This free all endpoints and those resources
1604 */
snd_usb_endpoint_free_all(struct snd_usb_audio * chip)1605 void snd_usb_endpoint_free_all(struct snd_usb_audio *chip)
1606 {
1607 struct snd_usb_endpoint *ep, *en;
1608 struct snd_usb_iface_ref *ip, *in;
1609
1610 list_for_each_entry_safe(ep, en, &chip->ep_list, list)
1611 kfree(ep);
1612
1613 list_for_each_entry_safe(ip, in, &chip->iface_ref_list, list)
1614 kfree(ip);
1615 }
1616
1617 /*
1618 * snd_usb_handle_sync_urb: parse an USB sync packet
1619 *
1620 * @ep: the endpoint to handle the packet
1621 * @sender: the sending endpoint
1622 * @urb: the received packet
1623 *
1624 * This function is called from the context of an endpoint that received
1625 * the packet and is used to let another endpoint object handle the payload.
1626 */
snd_usb_handle_sync_urb(struct snd_usb_endpoint * ep,struct snd_usb_endpoint * sender,const struct urb * urb)1627 static void snd_usb_handle_sync_urb(struct snd_usb_endpoint *ep,
1628 struct snd_usb_endpoint *sender,
1629 const struct urb *urb)
1630 {
1631 int shift;
1632 unsigned int f;
1633 unsigned long flags;
1634
1635 snd_BUG_ON(ep == sender);
1636
1637 /*
1638 * In case the endpoint is operating in implicit feedback mode, prepare
1639 * a new outbound URB that has the same layout as the received packet
1640 * and add it to the list of pending urbs. queue_pending_output_urbs()
1641 * will take care of them later.
1642 */
1643 if (snd_usb_endpoint_implicit_feedback_sink(ep) &&
1644 atomic_read(&ep->running)) {
1645
1646 /* implicit feedback case */
1647 int i, bytes = 0;
1648 struct snd_urb_ctx *in_ctx;
1649 struct snd_usb_packet_info *out_packet;
1650
1651 in_ctx = urb->context;
1652
1653 /* Count overall packet size */
1654 for (i = 0; i < in_ctx->packets; i++)
1655 if (urb->iso_frame_desc[i].status == 0)
1656 bytes += urb->iso_frame_desc[i].actual_length;
1657
1658 /*
1659 * skip empty packets. At least M-Audio's Fast Track Ultra stops
1660 * streaming once it received a 0-byte OUT URB
1661 */
1662 if (bytes == 0)
1663 return;
1664
1665 spin_lock_irqsave(&ep->lock, flags);
1666 if (ep->next_packet_queued >= ARRAY_SIZE(ep->next_packet)) {
1667 spin_unlock_irqrestore(&ep->lock, flags);
1668 usb_audio_err(ep->chip,
1669 "next package FIFO overflow EP 0x%x\n",
1670 ep->ep_num);
1671 notify_xrun(ep);
1672 return;
1673 }
1674
1675 out_packet = next_packet_fifo_enqueue(ep);
1676
1677 /*
1678 * Iterate through the inbound packet and prepare the lengths
1679 * for the output packet. The OUT packet we are about to send
1680 * will have the same amount of payload bytes per stride as the
1681 * IN packet we just received. Since the actual size is scaled
1682 * by the stride, use the sender stride to calculate the length
1683 * in case the number of channels differ between the implicitly
1684 * fed-back endpoint and the synchronizing endpoint.
1685 */
1686
1687 out_packet->packets = in_ctx->packets;
1688 for (i = 0; i < in_ctx->packets; i++) {
1689 if (urb->iso_frame_desc[i].status == 0)
1690 out_packet->packet_size[i] =
1691 urb->iso_frame_desc[i].actual_length / sender->stride;
1692 else
1693 out_packet->packet_size[i] = 0;
1694 }
1695
1696 spin_unlock_irqrestore(&ep->lock, flags);
1697 snd_usb_queue_pending_output_urbs(ep, false);
1698
1699 return;
1700 }
1701
1702 /*
1703 * process after playback sync complete
1704 *
1705 * Full speed devices report feedback values in 10.14 format as samples
1706 * per frame, high speed devices in 16.16 format as samples per
1707 * microframe.
1708 *
1709 * Because the Audio Class 1 spec was written before USB 2.0, many high
1710 * speed devices use a wrong interpretation, some others use an
1711 * entirely different format.
1712 *
1713 * Therefore, we cannot predict what format any particular device uses
1714 * and must detect it automatically.
1715 */
1716
1717 if (urb->iso_frame_desc[0].status != 0 ||
1718 urb->iso_frame_desc[0].actual_length < 3)
1719 return;
1720
1721 f = le32_to_cpup(urb->transfer_buffer);
1722 if (urb->iso_frame_desc[0].actual_length == 3)
1723 f &= 0x00ffffff;
1724 else
1725 f &= 0x0fffffff;
1726
1727 if (f == 0)
1728 return;
1729
1730 if (unlikely(sender->tenor_fb_quirk)) {
1731 /*
1732 * Devices based on Tenor 8802 chipsets (TEAC UD-H01
1733 * and others) sometimes change the feedback value
1734 * by +/- 0x1.0000.
1735 */
1736 if (f < ep->freqn - 0x8000)
1737 f += 0xf000;
1738 else if (f > ep->freqn + 0x8000)
1739 f -= 0xf000;
1740 } else if (unlikely(ep->freqshift == INT_MIN)) {
1741 /*
1742 * The first time we see a feedback value, determine its format
1743 * by shifting it left or right until it matches the nominal
1744 * frequency value. This assumes that the feedback does not
1745 * differ from the nominal value more than +50% or -25%.
1746 */
1747 shift = 0;
1748 while (f < ep->freqn - ep->freqn / 4) {
1749 f <<= 1;
1750 shift++;
1751 }
1752 while (f > ep->freqn + ep->freqn / 2) {
1753 f >>= 1;
1754 shift--;
1755 }
1756 ep->freqshift = shift;
1757 } else if (ep->freqshift >= 0)
1758 f <<= ep->freqshift;
1759 else
1760 f >>= -ep->freqshift;
1761
1762 if (likely(f >= ep->freqn - ep->freqn / 8 && f <= ep->freqmax)) {
1763 /*
1764 * If the frequency looks valid, set it.
1765 * This value is referred to in prepare_playback_urb().
1766 */
1767 spin_lock_irqsave(&ep->lock, flags);
1768 ep->freqm = f;
1769 spin_unlock_irqrestore(&ep->lock, flags);
1770 } else {
1771 /*
1772 * Out of range; maybe the shift value is wrong.
1773 * Reset it so that we autodetect again the next time.
1774 */
1775 ep->freqshift = INT_MIN;
1776 }
1777 }
1778
1779