ALSA: snd-usb: switch over to new endpoint streaming logic
[GitHub/mt8127/android_kernel_alcatel_ttab.git] / sound / usb / endpoint.c
CommitLineData
e5779998
DM
1/*
2 * This program is free software; you can redistribute it and/or modify
3 * it under the terms of the GNU General Public License as published by
4 * the Free Software Foundation; either version 2 of the License, or
5 * (at your option) any later version.
6 *
7 * This program is distributed in the hope that it will be useful,
8 * but WITHOUT ANY WARRANTY; without even the implied warranty of
9 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
10 * GNU General Public License for more details.
11 *
12 * You should have received a copy of the GNU General Public License
13 * along with this program; if not, write to the Free Software
14 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
15 *
16 */
17
c731bc96
DM
18#include <linux/gfp.h>
19#include <linux/init.h>
80c8a2a3 20#include <linux/ratelimit.h>
c731bc96
DM
21#include <linux/usb.h>
22#include <linux/usb/audio.h>
8fdff6a3 23#include <linux/slab.h>
c731bc96
DM
24
25#include <sound/core.h>
26#include <sound/pcm.h>
8fdff6a3 27#include <sound/pcm_params.h>
c731bc96
DM
28
29#include "usbaudio.h"
30#include "helper.h"
31#include "card.h"
32#include "endpoint.h"
33#include "pcm.h"
34
8fdff6a3
DM
35#define EP_FLAG_ACTIVATED 0
36#define EP_FLAG_RUNNING 1
37
c731bc96
DM
38/*
39 * convert a sampling rate into our full speed format (fs/1000 in Q16.16)
40 * this will overflow at approx 524 kHz
41 */
42static inline unsigned get_usb_full_speed_rate(unsigned int rate)
43{
44 return ((rate << 13) + 62) / 125;
45}
46
47/*
48 * convert a sampling rate into USB high speed format (fs/8000 in Q16.16)
49 * this will overflow at approx 4 MHz
50 */
51static inline unsigned get_usb_high_speed_rate(unsigned int rate)
52{
53 return ((rate << 10) + 62) / 125;
54}
55
56/*
57 * unlink active urbs.
58 */
8fdff6a3 59static int deactivate_urbs_old(struct snd_usb_substream *subs, int force, int can_sleep)
c731bc96
DM
60{
61 struct snd_usb_audio *chip = subs->stream->chip;
62 unsigned int i;
63 int async;
64
65 subs->running = 0;
66
67 if (!force && subs->stream->chip->shutdown) /* to be sure... */
68 return -EBADFD;
69
70 async = !can_sleep && chip->async_unlink;
71
72 if (!async && in_interrupt())
73 return 0;
74
75 for (i = 0; i < subs->nurbs; i++) {
76 if (test_bit(i, &subs->active_mask)) {
77 if (!test_and_set_bit(i, &subs->unlink_mask)) {
78 struct urb *u = subs->dataurb[i].urb;
79 if (async)
80 usb_unlink_urb(u);
81 else
82 usb_kill_urb(u);
83 }
84 }
85 }
86 if (subs->syncpipe) {
87 for (i = 0; i < SYNC_URBS; i++) {
88 if (test_bit(i+16, &subs->active_mask)) {
89 if (!test_and_set_bit(i+16, &subs->unlink_mask)) {
90 struct urb *u = subs->syncurb[i].urb;
91 if (async)
92 usb_unlink_urb(u);
93 else
94 usb_kill_urb(u);
95 }
96 }
97 }
98 }
99 return 0;
100}
101
102
103/*
104 * release a urb data
105 */
106static void release_urb_ctx(struct snd_urb_ctx *u)
107{
108 if (u->urb) {
109 if (u->buffer_size)
110 usb_free_coherent(u->subs->dev, u->buffer_size,
111 u->urb->transfer_buffer,
112 u->urb->transfer_dma);
113 usb_free_urb(u->urb);
114 u->urb = NULL;
115 }
116}
117
118/*
119 * wait until all urbs are processed.
120 */
8fdff6a3 121static int wait_clear_urbs_old(struct snd_usb_substream *subs)
c731bc96
DM
122{
123 unsigned long end_time = jiffies + msecs_to_jiffies(1000);
124 unsigned int i;
125 int alive;
126
127 do {
128 alive = 0;
129 for (i = 0; i < subs->nurbs; i++) {
130 if (test_bit(i, &subs->active_mask))
131 alive++;
132 }
133 if (subs->syncpipe) {
134 for (i = 0; i < SYNC_URBS; i++) {
135 if (test_bit(i + 16, &subs->active_mask))
136 alive++;
137 }
138 }
139 if (! alive)
140 break;
141 schedule_timeout_uninterruptible(1);
142 } while (time_before(jiffies, end_time));
143 if (alive)
144 snd_printk(KERN_ERR "timeout: still %d active urbs..\n", alive);
145 return 0;
146}
147
148/*
149 * release a substream
150 */
151void snd_usb_release_substream_urbs(struct snd_usb_substream *subs, int force)
152{
153 int i;
154
155 /* stop urbs (to be sure) */
8fdff6a3
DM
156 deactivate_urbs_old(subs, force, 1);
157 wait_clear_urbs_old(subs);
c731bc96
DM
158
159 for (i = 0; i < MAX_URBS; i++)
160 release_urb_ctx(&subs->dataurb[i]);
161 for (i = 0; i < SYNC_URBS; i++)
162 release_urb_ctx(&subs->syncurb[i]);
163 usb_free_coherent(subs->dev, SYNC_URBS * 4,
164 subs->syncbuf, subs->sync_dma);
165 subs->syncbuf = NULL;
166 subs->nurbs = 0;
167}
168
169/*
170 * complete callback from data urb
171 */
8fdff6a3 172static void snd_complete_urb_old(struct urb *urb)
c731bc96
DM
173{
174 struct snd_urb_ctx *ctx = urb->context;
175 struct snd_usb_substream *subs = ctx->subs;
176 struct snd_pcm_substream *substream = ctx->subs->pcm_substream;
177 int err = 0;
178
179 if ((subs->running && subs->ops.retire(subs, substream->runtime, urb)) ||
180 !subs->running || /* can be stopped during retire callback */
181 (err = subs->ops.prepare(subs, substream->runtime, urb)) < 0 ||
182 (err = usb_submit_urb(urb, GFP_ATOMIC)) < 0) {
183 clear_bit(ctx->index, &subs->active_mask);
184 if (err < 0) {
185 snd_printd(KERN_ERR "cannot submit urb (err = %d)\n", err);
186 snd_pcm_stop(substream, SNDRV_PCM_STATE_XRUN);
187 }
188 }
189}
190
191
192/*
193 * complete callback from sync urb
194 */
195static void snd_complete_sync_urb(struct urb *urb)
196{
197 struct snd_urb_ctx *ctx = urb->context;
198 struct snd_usb_substream *subs = ctx->subs;
199 struct snd_pcm_substream *substream = ctx->subs->pcm_substream;
200 int err = 0;
201
202 if ((subs->running && subs->ops.retire_sync(subs, substream->runtime, urb)) ||
203 !subs->running || /* can be stopped during retire callback */
204 (err = subs->ops.prepare_sync(subs, substream->runtime, urb)) < 0 ||
205 (err = usb_submit_urb(urb, GFP_ATOMIC)) < 0) {
206 clear_bit(ctx->index + 16, &subs->active_mask);
207 if (err < 0) {
208 snd_printd(KERN_ERR "cannot submit sync urb (err = %d)\n", err);
209 snd_pcm_stop(substream, SNDRV_PCM_STATE_XRUN);
210 }
211 }
212}
213
214
215/*
216 * initialize a substream for plaback/capture
217 */
218int snd_usb_init_substream_urbs(struct snd_usb_substream *subs,
219 unsigned int period_bytes,
220 unsigned int rate,
221 unsigned int frame_bits)
222{
223 unsigned int maxsize, i;
224 int is_playback = subs->direction == SNDRV_PCM_STREAM_PLAYBACK;
225 unsigned int urb_packs, total_packs, packs_per_ms;
226 struct snd_usb_audio *chip = subs->stream->chip;
227
228 /* calculate the frequency in 16.16 format */
229 if (snd_usb_get_speed(subs->dev) == USB_SPEED_FULL)
230 subs->freqn = get_usb_full_speed_rate(rate);
231 else
232 subs->freqn = get_usb_high_speed_rate(rate);
233 subs->freqm = subs->freqn;
234 subs->freqshift = INT_MIN;
235 /* calculate max. frequency */
236 if (subs->maxpacksize) {
237 /* whatever fits into a max. size packet */
238 maxsize = subs->maxpacksize;
239 subs->freqmax = (maxsize / (frame_bits >> 3))
240 << (16 - subs->datainterval);
241 } else {
242 /* no max. packet size: just take 25% higher than nominal */
243 subs->freqmax = subs->freqn + (subs->freqn >> 2);
244 maxsize = ((subs->freqmax + 0xffff) * (frame_bits >> 3))
245 >> (16 - subs->datainterval);
246 }
247 subs->phase = 0;
248
249 if (subs->fill_max)
250 subs->curpacksize = subs->maxpacksize;
251 else
252 subs->curpacksize = maxsize;
253
254 if (snd_usb_get_speed(subs->dev) != USB_SPEED_FULL)
255 packs_per_ms = 8 >> subs->datainterval;
256 else
257 packs_per_ms = 1;
258
259 if (is_playback) {
260 urb_packs = max(chip->nrpacks, 1);
261 urb_packs = min(urb_packs, (unsigned int)MAX_PACKS);
262 } else
263 urb_packs = 1;
264 urb_packs *= packs_per_ms;
265 if (subs->syncpipe)
266 urb_packs = min(urb_packs, 1U << subs->syncinterval);
267
268 /* decide how many packets to be used */
269 if (is_playback) {
270 unsigned int minsize, maxpacks;
271 /* determine how small a packet can be */
272 minsize = (subs->freqn >> (16 - subs->datainterval))
273 * (frame_bits >> 3);
274 /* with sync from device, assume it can be 12% lower */
275 if (subs->syncpipe)
276 minsize -= minsize >> 3;
277 minsize = max(minsize, 1u);
278 total_packs = (period_bytes + minsize - 1) / minsize;
279 /* we need at least two URBs for queueing */
280 if (total_packs < 2) {
281 total_packs = 2;
282 } else {
283 /* and we don't want too long a queue either */
284 maxpacks = max(MAX_QUEUE * packs_per_ms, urb_packs * 2);
285 total_packs = min(total_packs, maxpacks);
286 }
287 } else {
288 while (urb_packs > 1 && urb_packs * maxsize >= period_bytes)
289 urb_packs >>= 1;
290 total_packs = MAX_URBS * urb_packs;
291 }
292 subs->nurbs = (total_packs + urb_packs - 1) / urb_packs;
293 if (subs->nurbs > MAX_URBS) {
294 /* too much... */
295 subs->nurbs = MAX_URBS;
296 total_packs = MAX_URBS * urb_packs;
297 } else if (subs->nurbs < 2) {
298 /* too little - we need at least two packets
299 * to ensure contiguous playback/capture
300 */
301 subs->nurbs = 2;
302 }
303
304 /* allocate and initialize data urbs */
305 for (i = 0; i < subs->nurbs; i++) {
306 struct snd_urb_ctx *u = &subs->dataurb[i];
307 u->index = i;
308 u->subs = subs;
309 u->packets = (i + 1) * total_packs / subs->nurbs
310 - i * total_packs / subs->nurbs;
311 u->buffer_size = maxsize * u->packets;
312 if (subs->fmt_type == UAC_FORMAT_TYPE_II)
313 u->packets++; /* for transfer delimiter */
314 u->urb = usb_alloc_urb(u->packets, GFP_KERNEL);
315 if (!u->urb)
316 goto out_of_memory;
317 u->urb->transfer_buffer =
318 usb_alloc_coherent(subs->dev, u->buffer_size,
319 GFP_KERNEL, &u->urb->transfer_dma);
320 if (!u->urb->transfer_buffer)
321 goto out_of_memory;
322 u->urb->pipe = subs->datapipe;
323 u->urb->transfer_flags = URB_ISO_ASAP | URB_NO_TRANSFER_DMA_MAP;
324 u->urb->interval = 1 << subs->datainterval;
325 u->urb->context = u;
8fdff6a3 326 u->urb->complete = snd_complete_urb_old;
c731bc96
DM
327 }
328
329 if (subs->syncpipe) {
330 /* allocate and initialize sync urbs */
331 subs->syncbuf = usb_alloc_coherent(subs->dev, SYNC_URBS * 4,
332 GFP_KERNEL, &subs->sync_dma);
333 if (!subs->syncbuf)
334 goto out_of_memory;
335 for (i = 0; i < SYNC_URBS; i++) {
336 struct snd_urb_ctx *u = &subs->syncurb[i];
337 u->index = i;
338 u->subs = subs;
339 u->packets = 1;
340 u->urb = usb_alloc_urb(1, GFP_KERNEL);
341 if (!u->urb)
342 goto out_of_memory;
343 u->urb->transfer_buffer = subs->syncbuf + i * 4;
344 u->urb->transfer_dma = subs->sync_dma + i * 4;
345 u->urb->transfer_buffer_length = 4;
346 u->urb->pipe = subs->syncpipe;
347 u->urb->transfer_flags = URB_ISO_ASAP |
348 URB_NO_TRANSFER_DMA_MAP;
349 u->urb->number_of_packets = 1;
350 u->urb->interval = 1 << subs->syncinterval;
351 u->urb->context = u;
352 u->urb->complete = snd_complete_sync_urb;
353 }
354 }
355 return 0;
356
357out_of_memory:
358 snd_usb_release_substream_urbs(subs, 0);
359 return -ENOMEM;
360}
361
362/*
363 * prepare urb for full speed capture sync pipe
364 *
365 * fill the length and offset of each urb descriptor.
366 * the fixed 10.14 frequency is passed through the pipe.
367 */
368static int prepare_capture_sync_urb(struct snd_usb_substream *subs,
369 struct snd_pcm_runtime *runtime,
370 struct urb *urb)
371{
372 unsigned char *cp = urb->transfer_buffer;
373 struct snd_urb_ctx *ctx = urb->context;
374
375 urb->dev = ctx->subs->dev; /* we need to set this at each time */
376 urb->iso_frame_desc[0].length = 3;
377 urb->iso_frame_desc[0].offset = 0;
378 cp[0] = subs->freqn >> 2;
379 cp[1] = subs->freqn >> 10;
380 cp[2] = subs->freqn >> 18;
381 return 0;
382}
383
384/*
385 * prepare urb for high speed capture sync pipe
386 *
387 * fill the length and offset of each urb descriptor.
388 * the fixed 12.13 frequency is passed as 16.16 through the pipe.
389 */
390static int prepare_capture_sync_urb_hs(struct snd_usb_substream *subs,
391 struct snd_pcm_runtime *runtime,
392 struct urb *urb)
393{
394 unsigned char *cp = urb->transfer_buffer;
395 struct snd_urb_ctx *ctx = urb->context;
396
397 urb->dev = ctx->subs->dev; /* we need to set this at each time */
398 urb->iso_frame_desc[0].length = 4;
399 urb->iso_frame_desc[0].offset = 0;
400 cp[0] = subs->freqn;
401 cp[1] = subs->freqn >> 8;
402 cp[2] = subs->freqn >> 16;
403 cp[3] = subs->freqn >> 24;
404 return 0;
405}
406
407/*
408 * process after capture sync complete
409 * - nothing to do
410 */
411static int retire_capture_sync_urb(struct snd_usb_substream *subs,
412 struct snd_pcm_runtime *runtime,
413 struct urb *urb)
414{
415 return 0;
416}
417
418/*
419 * prepare urb for capture data pipe
420 *
421 * fill the offset and length of each descriptor.
422 *
423 * we use a temporary buffer to write the captured data.
424 * since the length of written data is determined by host, we cannot
425 * write onto the pcm buffer directly... the data is thus copied
426 * later at complete callback to the global buffer.
427 */
428static int prepare_capture_urb(struct snd_usb_substream *subs,
429 struct snd_pcm_runtime *runtime,
430 struct urb *urb)
431{
432 int i, offs;
433 struct snd_urb_ctx *ctx = urb->context;
434
435 offs = 0;
436 urb->dev = ctx->subs->dev; /* we need to set this at each time */
437 for (i = 0; i < ctx->packets; i++) {
438 urb->iso_frame_desc[i].offset = offs;
439 urb->iso_frame_desc[i].length = subs->curpacksize;
440 offs += subs->curpacksize;
441 }
442 urb->transfer_buffer_length = offs;
443 urb->number_of_packets = ctx->packets;
444 return 0;
445}
446
447/*
448 * process after capture complete
449 *
450 * copy the data from each desctiptor to the pcm buffer, and
451 * update the current position.
452 */
453static int retire_capture_urb(struct snd_usb_substream *subs,
454 struct snd_pcm_runtime *runtime,
455 struct urb *urb)
456{
457 unsigned long flags;
458 unsigned char *cp;
459 int i;
460 unsigned int stride, frames, bytes, oldptr;
461 int period_elapsed = 0;
462
463 stride = runtime->frame_bits >> 3;
464
465 for (i = 0; i < urb->number_of_packets; i++) {
466 cp = (unsigned char *)urb->transfer_buffer + urb->iso_frame_desc[i].offset;
80c8a2a3
TI
467 if (urb->iso_frame_desc[i].status && printk_ratelimit()) {
468 snd_printdd("frame %d active: %d\n", i, urb->iso_frame_desc[i].status);
c731bc96
DM
469 // continue;
470 }
471 bytes = urb->iso_frame_desc[i].actual_length;
472 frames = bytes / stride;
473 if (!subs->txfr_quirk)
474 bytes = frames * stride;
475 if (bytes % (runtime->sample_bits >> 3) != 0) {
476#ifdef CONFIG_SND_DEBUG_VERBOSE
477 int oldbytes = bytes;
478#endif
479 bytes = frames * stride;
480 snd_printdd(KERN_ERR "Corrected urb data len. %d->%d\n",
481 oldbytes, bytes);
482 }
483 /* update the current pointer */
484 spin_lock_irqsave(&subs->lock, flags);
485 oldptr = subs->hwptr_done;
486 subs->hwptr_done += bytes;
487 if (subs->hwptr_done >= runtime->buffer_size * stride)
488 subs->hwptr_done -= runtime->buffer_size * stride;
489 frames = (bytes + (oldptr % stride)) / stride;
490 subs->transfer_done += frames;
491 if (subs->transfer_done >= runtime->period_size) {
492 subs->transfer_done -= runtime->period_size;
493 period_elapsed = 1;
494 }
495 spin_unlock_irqrestore(&subs->lock, flags);
496 /* copy a data chunk */
497 if (oldptr + bytes > runtime->buffer_size * stride) {
498 unsigned int bytes1 =
499 runtime->buffer_size * stride - oldptr;
500 memcpy(runtime->dma_area + oldptr, cp, bytes1);
501 memcpy(runtime->dma_area, cp + bytes1, bytes - bytes1);
502 } else {
503 memcpy(runtime->dma_area + oldptr, cp, bytes);
504 }
505 }
506 if (period_elapsed)
507 snd_pcm_period_elapsed(subs->pcm_substream);
508 return 0;
509}
510
511/*
512 * Process after capture complete when paused. Nothing to do.
513 */
514static int retire_paused_capture_urb(struct snd_usb_substream *subs,
515 struct snd_pcm_runtime *runtime,
516 struct urb *urb)
517{
518 return 0;
519}
520
521
522/*
523 * prepare urb for playback sync pipe
524 *
525 * set up the offset and length to receive the current frequency.
526 */
527static int prepare_playback_sync_urb(struct snd_usb_substream *subs,
528 struct snd_pcm_runtime *runtime,
529 struct urb *urb)
530{
531 struct snd_urb_ctx *ctx = urb->context;
532
533 urb->dev = ctx->subs->dev; /* we need to set this at each time */
534 urb->iso_frame_desc[0].length = min(4u, ctx->subs->syncmaxsize);
535 urb->iso_frame_desc[0].offset = 0;
536 return 0;
537}
538
539/*
540 * process after playback sync complete
541 *
542 * Full speed devices report feedback values in 10.14 format as samples per
543 * frame, high speed devices in 16.16 format as samples per microframe.
544 * Because the Audio Class 1 spec was written before USB 2.0, many high speed
545 * devices use a wrong interpretation, some others use an entirely different
546 * format. Therefore, we cannot predict what format any particular device uses
547 * and must detect it automatically.
548 */
549static int retire_playback_sync_urb(struct snd_usb_substream *subs,
550 struct snd_pcm_runtime *runtime,
551 struct urb *urb)
552{
553 unsigned int f;
554 int shift;
555 unsigned long flags;
556
557 if (urb->iso_frame_desc[0].status != 0 ||
558 urb->iso_frame_desc[0].actual_length < 3)
559 return 0;
560
561 f = le32_to_cpup(urb->transfer_buffer);
562 if (urb->iso_frame_desc[0].actual_length == 3)
563 f &= 0x00ffffff;
564 else
565 f &= 0x0fffffff;
566 if (f == 0)
567 return 0;
568
569 if (unlikely(subs->freqshift == INT_MIN)) {
570 /*
571 * The first time we see a feedback value, determine its format
572 * by shifting it left or right until it matches the nominal
573 * frequency value. This assumes that the feedback does not
574 * differ from the nominal value more than +50% or -25%.
575 */
576 shift = 0;
577 while (f < subs->freqn - subs->freqn / 4) {
578 f <<= 1;
579 shift++;
580 }
581 while (f > subs->freqn + subs->freqn / 2) {
582 f >>= 1;
583 shift--;
584 }
585 subs->freqshift = shift;
586 }
587 else if (subs->freqshift >= 0)
588 f <<= subs->freqshift;
589 else
590 f >>= -subs->freqshift;
591
592 if (likely(f >= subs->freqn - subs->freqn / 8 && f <= subs->freqmax)) {
593 /*
594 * If the frequency looks valid, set it.
595 * This value is referred to in prepare_playback_urb().
596 */
597 spin_lock_irqsave(&subs->lock, flags);
598 subs->freqm = f;
599 spin_unlock_irqrestore(&subs->lock, flags);
600 } else {
601 /*
602 * Out of range; maybe the shift value is wrong.
603 * Reset it so that we autodetect again the next time.
604 */
605 subs->freqshift = INT_MIN;
606 }
607
608 return 0;
609}
610
611/* determine the number of frames in the next packet */
612static int snd_usb_audio_next_packet_size(struct snd_usb_substream *subs)
613{
614 if (subs->fill_max)
615 return subs->maxframesize;
616 else {
617 subs->phase = (subs->phase & 0xffff)
618 + (subs->freqm << subs->datainterval);
619 return min(subs->phase >> 16, subs->maxframesize);
620 }
621}
622
623/*
624 * Prepare urb for streaming before playback starts or when paused.
625 *
626 * We don't have any data, so we send silence.
627 */
628static int prepare_nodata_playback_urb(struct snd_usb_substream *subs,
629 struct snd_pcm_runtime *runtime,
630 struct urb *urb)
631{
632 unsigned int i, offs, counts;
633 struct snd_urb_ctx *ctx = urb->context;
634 int stride = runtime->frame_bits >> 3;
635
636 offs = 0;
637 urb->dev = ctx->subs->dev;
638 for (i = 0; i < ctx->packets; ++i) {
639 counts = snd_usb_audio_next_packet_size(subs);
640 urb->iso_frame_desc[i].offset = offs * stride;
641 urb->iso_frame_desc[i].length = counts * stride;
642 offs += counts;
643 }
644 urb->number_of_packets = ctx->packets;
645 urb->transfer_buffer_length = offs * stride;
646 memset(urb->transfer_buffer,
647 runtime->format == SNDRV_PCM_FORMAT_U8 ? 0x80 : 0,
648 offs * stride);
649 return 0;
650}
651
652/*
653 * prepare urb for playback data pipe
654 *
655 * Since a URB can handle only a single linear buffer, we must use double
656 * buffering when the data to be transferred overflows the buffer boundary.
657 * To avoid inconsistencies when updating hwptr_done, we use double buffering
658 * for all URBs.
659 */
660static int prepare_playback_urb(struct snd_usb_substream *subs,
661 struct snd_pcm_runtime *runtime,
662 struct urb *urb)
663{
664 int i, stride;
665 unsigned int counts, frames, bytes;
666 unsigned long flags;
667 int period_elapsed = 0;
668 struct snd_urb_ctx *ctx = urb->context;
669
670 stride = runtime->frame_bits >> 3;
671
672 frames = 0;
673 urb->dev = ctx->subs->dev; /* we need to set this at each time */
674 urb->number_of_packets = 0;
675 spin_lock_irqsave(&subs->lock, flags);
676 for (i = 0; i < ctx->packets; i++) {
677 counts = snd_usb_audio_next_packet_size(subs);
678 /* set up descriptor */
679 urb->iso_frame_desc[i].offset = frames * stride;
680 urb->iso_frame_desc[i].length = counts * stride;
681 frames += counts;
682 urb->number_of_packets++;
683 subs->transfer_done += counts;
684 if (subs->transfer_done >= runtime->period_size) {
685 subs->transfer_done -= runtime->period_size;
686 period_elapsed = 1;
687 if (subs->fmt_type == UAC_FORMAT_TYPE_II) {
688 if (subs->transfer_done > 0) {
689 /* FIXME: fill-max mode is not
690 * supported yet */
691 frames -= subs->transfer_done;
692 counts -= subs->transfer_done;
693 urb->iso_frame_desc[i].length =
694 counts * stride;
695 subs->transfer_done = 0;
696 }
697 i++;
698 if (i < ctx->packets) {
699 /* add a transfer delimiter */
700 urb->iso_frame_desc[i].offset =
701 frames * stride;
702 urb->iso_frame_desc[i].length = 0;
703 urb->number_of_packets++;
704 }
705 break;
706 }
707 }
708 if (period_elapsed) /* finish at the period boundary */
709 break;
710 }
711 bytes = frames * stride;
712 if (subs->hwptr_done + bytes > runtime->buffer_size * stride) {
713 /* err, the transferred area goes over buffer boundary. */
714 unsigned int bytes1 =
715 runtime->buffer_size * stride - subs->hwptr_done;
716 memcpy(urb->transfer_buffer,
717 runtime->dma_area + subs->hwptr_done, bytes1);
718 memcpy(urb->transfer_buffer + bytes1,
719 runtime->dma_area, bytes - bytes1);
720 } else {
721 memcpy(urb->transfer_buffer,
722 runtime->dma_area + subs->hwptr_done, bytes);
723 }
724 subs->hwptr_done += bytes;
725 if (subs->hwptr_done >= runtime->buffer_size * stride)
726 subs->hwptr_done -= runtime->buffer_size * stride;
727
728 /* update delay with exact number of samples queued */
729 runtime->delay = subs->last_delay;
730 runtime->delay += frames;
731 subs->last_delay = runtime->delay;
732
733 /* realign last_frame_number */
734 subs->last_frame_number = usb_get_current_frame_number(subs->dev);
735 subs->last_frame_number &= 0xFF; /* keep 8 LSBs */
736
737 spin_unlock_irqrestore(&subs->lock, flags);
738 urb->transfer_buffer_length = bytes;
739 if (period_elapsed)
740 snd_pcm_period_elapsed(subs->pcm_substream);
741 return 0;
742}
743
744/*
745 * process after playback data complete
746 * - decrease the delay count again
747 */
748static int retire_playback_urb(struct snd_usb_substream *subs,
749 struct snd_pcm_runtime *runtime,
750 struct urb *urb)
751{
752 unsigned long flags;
753 int stride = runtime->frame_bits >> 3;
754 int processed = urb->transfer_buffer_length / stride;
755 int est_delay;
756
757 spin_lock_irqsave(&subs->lock, flags);
758
759 est_delay = snd_usb_pcm_delay(subs, runtime->rate);
760 /* update delay with exact number of samples played */
761 if (processed > subs->last_delay)
762 subs->last_delay = 0;
763 else
764 subs->last_delay -= processed;
765 runtime->delay = subs->last_delay;
766
767 /*
768 * Report when delay estimate is off by more than 2ms.
769 * The error should be lower than 2ms since the estimate relies
770 * on two reads of a counter updated every ms.
771 */
772 if (abs(est_delay - subs->last_delay) * 1000 > runtime->rate * 2)
773 snd_printk(KERN_DEBUG "delay: estimated %d, actual %d\n",
774 est_delay, subs->last_delay);
775
776 spin_unlock_irqrestore(&subs->lock, flags);
777 return 0;
778}
779
780static const char *usb_error_string(int err)
781{
782 switch (err) {
783 case -ENODEV:
784 return "no device";
785 case -ENOENT:
786 return "endpoint not enabled";
787 case -EPIPE:
788 return "endpoint stalled";
789 case -ENOSPC:
790 return "not enough bandwidth";
791 case -ESHUTDOWN:
792 return "device disabled";
793 case -EHOSTUNREACH:
794 return "device suspended";
795 case -EINVAL:
796 case -EAGAIN:
797 case -EFBIG:
798 case -EMSGSIZE:
799 return "internal error";
800 default:
801 return "unknown error";
802 }
803}
804
805/*
806 * set up and start data/sync urbs
807 */
808static int start_urbs(struct snd_usb_substream *subs, struct snd_pcm_runtime *runtime)
809{
810 unsigned int i;
811 int err;
812
813 if (subs->stream->chip->shutdown)
814 return -EBADFD;
815
816 for (i = 0; i < subs->nurbs; i++) {
817 if (snd_BUG_ON(!subs->dataurb[i].urb))
818 return -EINVAL;
819 if (subs->ops.prepare(subs, runtime, subs->dataurb[i].urb) < 0) {
820 snd_printk(KERN_ERR "cannot prepare datapipe for urb %d\n", i);
821 goto __error;
822 }
823 }
824 if (subs->syncpipe) {
825 for (i = 0; i < SYNC_URBS; i++) {
826 if (snd_BUG_ON(!subs->syncurb[i].urb))
827 return -EINVAL;
828 if (subs->ops.prepare_sync(subs, runtime, subs->syncurb[i].urb) < 0) {
829 snd_printk(KERN_ERR "cannot prepare syncpipe for urb %d\n", i);
830 goto __error;
831 }
832 }
833 }
834
835 subs->active_mask = 0;
836 subs->unlink_mask = 0;
837 subs->running = 1;
838 for (i = 0; i < subs->nurbs; i++) {
839 err = usb_submit_urb(subs->dataurb[i].urb, GFP_ATOMIC);
840 if (err < 0) {
841 snd_printk(KERN_ERR "cannot submit datapipe "
842 "for urb %d, error %d: %s\n",
843 i, err, usb_error_string(err));
844 goto __error;
845 }
846 set_bit(i, &subs->active_mask);
847 }
848 if (subs->syncpipe) {
849 for (i = 0; i < SYNC_URBS; i++) {
850 err = usb_submit_urb(subs->syncurb[i].urb, GFP_ATOMIC);
851 if (err < 0) {
852 snd_printk(KERN_ERR "cannot submit syncpipe "
853 "for urb %d, error %d: %s\n",
854 i, err, usb_error_string(err));
855 goto __error;
856 }
857 set_bit(i + 16, &subs->active_mask);
858 }
859 }
860 return 0;
861
862 __error:
863 // snd_pcm_stop(subs->pcm_substream, SNDRV_PCM_STATE_XRUN);
8fdff6a3 864 deactivate_urbs_old(subs, 0, 0);
c731bc96
DM
865 return -EPIPE;
866}
867
868
869/*
870 */
871static struct snd_urb_ops audio_urb_ops[2] = {
872 {
873 .prepare = prepare_nodata_playback_urb,
874 .retire = retire_playback_urb,
875 .prepare_sync = prepare_playback_sync_urb,
876 .retire_sync = retire_playback_sync_urb,
877 },
878 {
879 .prepare = prepare_capture_urb,
880 .retire = retire_capture_urb,
881 .prepare_sync = prepare_capture_sync_urb,
882 .retire_sync = retire_capture_sync_urb,
883 },
884};
885
886/*
887 * initialize the substream instance.
888 */
889
890void snd_usb_init_substream(struct snd_usb_stream *as,
891 int stream, struct audioformat *fp)
892{
893 struct snd_usb_substream *subs = &as->substream[stream];
894
895 INIT_LIST_HEAD(&subs->fmt_list);
896 spin_lock_init(&subs->lock);
897
898 subs->stream = as;
899 subs->direction = stream;
900 subs->dev = as->chip->dev;
901 subs->txfr_quirk = as->chip->txfr_quirk;
902 subs->ops = audio_urb_ops[stream];
903 if (snd_usb_get_speed(subs->dev) >= USB_SPEED_HIGH)
904 subs->ops.prepare_sync = prepare_capture_sync_urb_hs;
905
906 snd_usb_set_pcm_ops(as->pcm, stream);
907
908 list_add_tail(&fp->list, &subs->fmt_list);
909 subs->formats |= fp->formats;
910 subs->endpoint = fp->endpoint;
911 subs->num_formats++;
912 subs->fmt_type = fp->fmt_type;
913}
914
c731bc96
DM
915int snd_usb_substream_prepare(struct snd_usb_substream *subs,
916 struct snd_pcm_runtime *runtime)
917{
918 /* clear urbs (to be sure) */
8fdff6a3
DM
919 deactivate_urbs_old(subs, 0, 1);
920 wait_clear_urbs_old(subs);
c731bc96
DM
921
922 /* for playback, submit the URBs now; otherwise, the first hwptr_done
923 * updates for all URBs would happen at the same time when starting */
924 if (subs->direction == SNDRV_PCM_STREAM_PLAYBACK) {
925 subs->ops.prepare = prepare_nodata_playback_urb;
926 return start_urbs(subs, runtime);
927 }
928
929 return 0;
930}
931
8fdff6a3
DM
932int snd_usb_endpoint_implict_feedback_sink(struct snd_usb_endpoint *ep)
933{
934 return ep->sync_master &&
935 ep->sync_master->type == SND_USB_ENDPOINT_TYPE_DATA &&
936 ep->type == SND_USB_ENDPOINT_TYPE_DATA &&
937 usb_pipeout(ep->pipe);
938}
939
940/* determine the number of frames in the next packet */
941static int next_packet_size(struct snd_usb_endpoint *ep)
942{
943 unsigned long flags;
944 int ret;
945
946 if (ep->fill_max)
947 return ep->maxframesize;
948
949 spin_lock_irqsave(&ep->lock, flags);
950 ep->phase = (ep->phase & 0xffff)
951 + (ep->freqm << ep->datainterval);
952 ret = min(ep->phase >> 16, ep->maxframesize);
953 spin_unlock_irqrestore(&ep->lock, flags);
954
955 return ret;
956}
957
958static void retire_outbound_urb(struct snd_usb_endpoint *ep,
959 struct snd_urb_ctx *urb_ctx)
960{
961 if (ep->retire_data_urb)
962 ep->retire_data_urb(ep->data_subs, urb_ctx->urb);
963}
964
965static void retire_inbound_urb(struct snd_usb_endpoint *ep,
966 struct snd_urb_ctx *urb_ctx)
967{
968 struct urb *urb = urb_ctx->urb;
969
970 if (ep->sync_slave)
971 snd_usb_handle_sync_urb(ep->sync_slave, ep, urb);
972
973 if (ep->retire_data_urb)
974 ep->retire_data_urb(ep->data_subs, urb);
975}
976
977static void prepare_outbound_urb_sizes(struct snd_usb_endpoint *ep,
978 struct snd_urb_ctx *ctx)
979{
980 int i;
981
982 for (i = 0; i < ctx->packets; ++i)
983 ctx->packet_size[i] = next_packet_size(ep);
984}
985
986/*
987 * Prepare a PLAYBACK urb for submission to the bus.
988 */
989static void prepare_outbound_urb(struct snd_usb_endpoint *ep,
990 struct snd_urb_ctx *ctx)
991{
992 int i;
993 struct urb *urb = ctx->urb;
994 unsigned char *cp = urb->transfer_buffer;
995
996 urb->dev = ep->chip->dev; /* we need to set this at each time */
997
998 switch (ep->type) {
999 case SND_USB_ENDPOINT_TYPE_DATA:
1000 if (ep->prepare_data_urb) {
1001 ep->prepare_data_urb(ep->data_subs, urb);
1002 } else {
1003 /* no data provider, so send silence */
1004 unsigned int offs = 0;
1005 for (i = 0; i < ctx->packets; ++i) {
1006 int counts = ctx->packet_size[i];
1007 urb->iso_frame_desc[i].offset = offs * ep->stride;
1008 urb->iso_frame_desc[i].length = counts * ep->stride;
1009 offs += counts;
1010 }
1011
1012 urb->number_of_packets = ctx->packets;
1013 urb->transfer_buffer_length = offs * ep->stride;
1014 memset(urb->transfer_buffer, ep->silence_value,
1015 offs * ep->stride);
1016 }
1017 break;
1018
1019 case SND_USB_ENDPOINT_TYPE_SYNC:
1020 if (snd_usb_get_speed(ep->chip->dev) >= USB_SPEED_HIGH) {
1021 /*
1022 * fill the length and offset of each urb descriptor.
1023 * the fixed 12.13 frequency is passed as 16.16 through the pipe.
1024 */
1025 urb->iso_frame_desc[0].length = 4;
1026 urb->iso_frame_desc[0].offset = 0;
1027 cp[0] = ep->freqn;
1028 cp[1] = ep->freqn >> 8;
1029 cp[2] = ep->freqn >> 16;
1030 cp[3] = ep->freqn >> 24;
1031 } else {
1032 /*
1033 * fill the length and offset of each urb descriptor.
1034 * the fixed 10.14 frequency is passed through the pipe.
1035 */
1036 urb->iso_frame_desc[0].length = 3;
1037 urb->iso_frame_desc[0].offset = 0;
1038 cp[0] = ep->freqn >> 2;
1039 cp[1] = ep->freqn >> 10;
1040 cp[2] = ep->freqn >> 18;
1041 }
1042
1043 break;
1044 }
1045}
1046
1047/*
1048 * Prepare a CAPTURE or SYNC urb for submission to the bus.
1049 */
1050static inline void prepare_inbound_urb(struct snd_usb_endpoint *ep,
1051 struct snd_urb_ctx *urb_ctx)
1052{
1053 int i, offs;
1054 struct urb *urb = urb_ctx->urb;
1055
1056 urb->dev = ep->chip->dev; /* we need to set this at each time */
1057
1058 switch (ep->type) {
1059 case SND_USB_ENDPOINT_TYPE_DATA:
1060 offs = 0;
1061 for (i = 0; i < urb_ctx->packets; i++) {
1062 urb->iso_frame_desc[i].offset = offs;
1063 urb->iso_frame_desc[i].length = ep->curpacksize;
1064 offs += ep->curpacksize;
1065 }
1066
1067 urb->transfer_buffer_length = offs;
1068 urb->number_of_packets = urb_ctx->packets;
1069 break;
1070
1071 case SND_USB_ENDPOINT_TYPE_SYNC:
1072 urb->iso_frame_desc[0].length = min(4u, ep->syncmaxsize);
1073 urb->iso_frame_desc[0].offset = 0;
1074 break;
1075 }
1076}
1077
1078static void queue_pending_output_urbs(struct snd_usb_endpoint *ep)
1079{
1080 while (test_bit(EP_FLAG_RUNNING, &ep->flags)) {
1081
1082 unsigned long flags;
1083 struct snd_usb_packet_info *packet;
1084 struct snd_urb_ctx *ctx = NULL;
1085 struct urb *urb;
1086 int err, i;
1087
1088 spin_lock_irqsave(&ep->lock, flags);
1089 if (ep->next_packet_read_pos != ep->next_packet_write_pos) {
1090 packet = ep->next_packet + ep->next_packet_read_pos;
1091 ep->next_packet_read_pos++;
1092 ep->next_packet_read_pos %= MAX_URBS;
1093
1094 /* take URB out of FIFO */
1095 if (!list_empty(&ep->ready_playback_urbs))
1096 ctx = list_first_entry(&ep->ready_playback_urbs,
1097 struct snd_urb_ctx, ready_list);
1098 }
1099 spin_unlock_irqrestore(&ep->lock, flags);
1100
1101 if (ctx == NULL)
1102 return;
1103
1104 list_del_init(&ctx->ready_list);
1105 urb = ctx->urb;
1106
1107 /* copy over the length information */
1108 for (i = 0; i < packet->packets; i++)
1109 ctx->packet_size[i] = packet->packet_size[i];
1110
1111 prepare_outbound_urb(ep, ctx);
1112
1113 err = usb_submit_urb(ctx->urb, GFP_ATOMIC);
1114 if (err < 0)
1115 snd_printk(KERN_ERR "Unable to submit urb #%d: %d (urb %p)\n",
1116 ctx->index, err, ctx->urb);
1117 else
1118 set_bit(ctx->index, &ep->active_mask);
1119 }
1120}
1121
1122/*
1123 * complete callback for urbs
1124 */
1125static void snd_complete_urb(struct urb *urb)
1126{
1127 struct snd_urb_ctx *ctx = urb->context;
1128 struct snd_usb_endpoint *ep = ctx->ep;
1129 int err;
1130
1131 if (unlikely(urb->status == -ENOENT || /* unlinked */
1132 urb->status == -ENODEV || /* device removed */
1133 urb->status == -ECONNRESET || /* unlinked */
1134 urb->status == -ESHUTDOWN || /* device disabled */
1135 ep->chip->shutdown)) /* device disconnected */
1136 goto exit_clear;
1137
1138 if (usb_pipeout(ep->pipe)) {
1139 retire_outbound_urb(ep, ctx);
1140 /* can be stopped during retire callback */
1141 if (unlikely(!test_bit(EP_FLAG_RUNNING, &ep->flags)))
1142 goto exit_clear;
1143
1144 if (snd_usb_endpoint_implict_feedback_sink(ep)) {
1145 unsigned long flags;
1146
1147 spin_lock_irqsave(&ep->lock, flags);
1148 list_add_tail(&ctx->ready_list, &ep->ready_playback_urbs);
1149 spin_unlock_irqrestore(&ep->lock, flags);
1150 queue_pending_output_urbs(ep);
1151
1152 goto exit_clear;
1153 }
1154
1155 prepare_outbound_urb_sizes(ep, ctx);
1156 prepare_outbound_urb(ep, ctx);
1157 } else {
1158 retire_inbound_urb(ep, ctx);
1159 /* can be stopped during retire callback */
1160 if (unlikely(!test_bit(EP_FLAG_RUNNING, &ep->flags)))
1161 goto exit_clear;
1162
1163 prepare_inbound_urb(ep, ctx);
1164 }
1165
1166 err = usb_submit_urb(urb, GFP_ATOMIC);
1167 if (err == 0)
1168 return;
1169
1170 snd_printk(KERN_ERR "cannot submit urb (err = %d)\n", err);
1171 //snd_pcm_stop(substream, SNDRV_PCM_STATE_XRUN);
1172
1173exit_clear:
1174 clear_bit(ctx->index, &ep->active_mask);
1175}
1176
1177struct snd_usb_endpoint *snd_usb_add_endpoint(struct snd_usb_audio *chip,
1178 struct usb_host_interface *alts,
1179 int ep_num, int direction, int type)
1180{
1181 struct list_head *p;
1182 struct snd_usb_endpoint *ep;
1183 int ret, is_playback = direction == SNDRV_PCM_STREAM_PLAYBACK;
1184
1185 mutex_lock(&chip->mutex);
1186
1187 list_for_each(p, &chip->ep_list) {
1188 ep = list_entry(p, struct snd_usb_endpoint, list);
1189 if (ep->ep_num == ep_num &&
1190 ep->iface == alts->desc.bInterfaceNumber &&
1191 ep->alt_idx == alts->desc.bAlternateSetting) {
1192 snd_printdd(KERN_DEBUG "Re-using EP %x in iface %d,%d @%p\n",
1193 ep_num, ep->iface, ep->alt_idx, ep);
1194 goto __exit_unlock;
1195 }
1196 }
1197
1198 snd_printdd(KERN_DEBUG "Creating new %s %s endpoint #%x\n",
1199 is_playback ? "playback" : "capture",
1200 type == SND_USB_ENDPOINT_TYPE_DATA ? "data" : "sync",
1201 ep_num);
1202
1203 /* select the alt setting once so the endpoints become valid */
1204 ret = usb_set_interface(chip->dev, alts->desc.bInterfaceNumber,
1205 alts->desc.bAlternateSetting);
1206 if (ret < 0) {
1207 snd_printk(KERN_ERR "%s(): usb_set_interface() failed, ret = %d\n",
1208 __func__, ret);
1209 ep = NULL;
1210 goto __exit_unlock;
1211 }
1212
1213 ep = kzalloc(sizeof(*ep), GFP_KERNEL);
1214 if (!ep)
1215 goto __exit_unlock;
1216
1217 ep->chip = chip;
1218 spin_lock_init(&ep->lock);
1219 ep->type = type;
1220 ep->ep_num = ep_num;
1221 ep->iface = alts->desc.bInterfaceNumber;
1222 ep->alt_idx = alts->desc.bAlternateSetting;
1223 INIT_LIST_HEAD(&ep->ready_playback_urbs);
1224 ep_num &= USB_ENDPOINT_NUMBER_MASK;
1225
1226 if (is_playback)
1227 ep->pipe = usb_sndisocpipe(chip->dev, ep_num);
1228 else
1229 ep->pipe = usb_rcvisocpipe(chip->dev, ep_num);
1230
1231 if (type == SND_USB_ENDPOINT_TYPE_SYNC) {
1232 if (get_endpoint(alts, 1)->bLength >= USB_DT_ENDPOINT_AUDIO_SIZE &&
1233 get_endpoint(alts, 1)->bRefresh >= 1 &&
1234 get_endpoint(alts, 1)->bRefresh <= 9)
1235 ep->syncinterval = get_endpoint(alts, 1)->bRefresh;
1236 else if (snd_usb_get_speed(chip->dev) == USB_SPEED_FULL)
1237 ep->syncinterval = 1;
1238 else if (get_endpoint(alts, 1)->bInterval >= 1 &&
1239 get_endpoint(alts, 1)->bInterval <= 16)
1240 ep->syncinterval = get_endpoint(alts, 1)->bInterval - 1;
1241 else
1242 ep->syncinterval = 3;
1243
1244 ep->syncmaxsize = le16_to_cpu(get_endpoint(alts, 1)->wMaxPacketSize);
1245 }
1246
1247 list_add_tail(&ep->list, &chip->ep_list);
1248
1249__exit_unlock:
1250 mutex_unlock(&chip->mutex);
1251
1252 return ep;
1253}
1254
1255/*
1256 * wait until all urbs are processed.
1257 */
1258static int wait_clear_urbs(struct snd_usb_endpoint *ep)
1259{
1260 unsigned long end_time = jiffies + msecs_to_jiffies(1000);
1261 unsigned int i;
1262 int alive;
1263
1264 do {
1265 alive = 0;
1266 for (i = 0; i < ep->nurbs; i++)
1267 if (test_bit(i, &ep->active_mask))
1268 alive++;
1269
1270 if (!alive)
1271 break;
1272
1273 schedule_timeout_uninterruptible(1);
1274 } while (time_before(jiffies, end_time));
1275
1276 if (alive)
1277 snd_printk(KERN_ERR "timeout: still %d active urbs on EP #%x\n",
1278 alive, ep->ep_num);
1279
1280 return 0;
1281}
1282
1283/*
1284 * unlink active urbs.
1285 */
1286static int deactivate_urbs(struct snd_usb_endpoint *ep, int force, int can_sleep)
1287{
1288 unsigned long flags;
1289 unsigned int i;
1290 int async;
1291
1292 if (!force && ep->chip->shutdown) /* to be sure... */
1293 return -EBADFD;
1294
1295 async = !can_sleep && ep->chip->async_unlink;
1296
1297 clear_bit(EP_FLAG_RUNNING, &ep->flags);
1298
1299 INIT_LIST_HEAD(&ep->ready_playback_urbs);
1300 ep->next_packet_read_pos = 0;
1301 ep->next_packet_write_pos = 0;
1302
1303 if (!async && in_interrupt())
1304 return 0;
1305
1306 for (i = 0; i < ep->nurbs; i++) {
1307 if (test_bit(i, &ep->active_mask)) {
1308 if (!test_and_set_bit(i, &ep->unlink_mask)) {
1309 struct urb *u = ep->urb[i].urb;
1310 if (async)
1311 usb_unlink_urb(u);
1312 else
1313 usb_kill_urb(u);
1314 }
1315 }
1316 }
1317
1318 return 0;
1319}
1320
1321/*
1322 * release an endpoint's urbs
1323 */
1324static void release_urbs(struct snd_usb_endpoint *ep, int force)
1325{
1326 int i;
1327
1328 /* route incoming urbs to nirvana */
1329 ep->retire_data_urb = NULL;
1330 ep->prepare_data_urb = NULL;
1331
1332 /* stop urbs */
1333 deactivate_urbs(ep, force, 1);
1334 wait_clear_urbs(ep);
1335
1336 for (i = 0; i < ep->nurbs; i++)
1337 release_urb_ctx(&ep->urb[i]);
1338
1339 if (ep->syncbuf)
1340 usb_free_coherent(ep->chip->dev, SYNC_URBS * 4,
1341 ep->syncbuf, ep->sync_dma);
1342
1343 ep->syncbuf = NULL;
1344 ep->nurbs = 0;
1345}
1346
1347static int data_ep_set_params(struct snd_usb_endpoint *ep,
1348 struct snd_pcm_hw_params *hw_params,
1349 struct audioformat *fmt,
1350 struct snd_usb_endpoint *sync_ep)
1351{
1352 unsigned int maxsize, i, urb_packs, total_packs, packs_per_ms;
1353 int period_bytes = params_period_bytes(hw_params);
1354 int format = params_format(hw_params);
1355 int is_playback = usb_pipeout(ep->pipe);
1356 int frame_bits = snd_pcm_format_physical_width(params_format(hw_params)) *
1357 params_channels(hw_params);
1358
1359 ep->datainterval = fmt->datainterval;
1360 ep->stride = frame_bits >> 3;
1361 ep->silence_value = format == SNDRV_PCM_FORMAT_U8 ? 0x80 : 0;
1362
1363 /* calculate max. frequency */
1364 if (ep->maxpacksize) {
1365 /* whatever fits into a max. size packet */
1366 maxsize = ep->maxpacksize;
1367 ep->freqmax = (maxsize / (frame_bits >> 3))
1368 << (16 - ep->datainterval);
1369 } else {
1370 /* no max. packet size: just take 25% higher than nominal */
1371 ep->freqmax = ep->freqn + (ep->freqn >> 2);
1372 maxsize = ((ep->freqmax + 0xffff) * (frame_bits >> 3))
1373 >> (16 - ep->datainterval);
1374 }
1375
1376 if (ep->fill_max)
1377 ep->curpacksize = ep->maxpacksize;
1378 else
1379 ep->curpacksize = maxsize;
1380
1381 if (snd_usb_get_speed(ep->chip->dev) != USB_SPEED_FULL)
1382 packs_per_ms = 8 >> ep->datainterval;
1383 else
1384 packs_per_ms = 1;
1385
1386 if (is_playback && !snd_usb_endpoint_implict_feedback_sink(ep)) {
1387 urb_packs = max(ep->chip->nrpacks, 1);
1388 urb_packs = min(urb_packs, (unsigned int) MAX_PACKS);
1389 } else {
1390 urb_packs = 1;
1391 }
1392
1393 urb_packs *= packs_per_ms;
1394
1395 if (sync_ep && !snd_usb_endpoint_implict_feedback_sink(ep))
1396 urb_packs = min(urb_packs, 1U << sync_ep->syncinterval);
1397
1398 /* decide how many packets to be used */
1399 if (is_playback && !snd_usb_endpoint_implict_feedback_sink(ep)) {
1400 unsigned int minsize, maxpacks;
1401 /* determine how small a packet can be */
1402 minsize = (ep->freqn >> (16 - ep->datainterval))
1403 * (frame_bits >> 3);
1404 /* with sync from device, assume it can be 12% lower */
1405 if (sync_ep)
1406 minsize -= minsize >> 3;
1407 minsize = max(minsize, 1u);
1408 total_packs = (period_bytes + minsize - 1) / minsize;
1409 /* we need at least two URBs for queueing */
1410 if (total_packs < 2) {
1411 total_packs = 2;
1412 } else {
1413 /* and we don't want too long a queue either */
1414 maxpacks = max(MAX_QUEUE * packs_per_ms, urb_packs * 2);
1415 total_packs = min(total_packs, maxpacks);
1416 }
1417 } else {
1418 while (urb_packs > 1 && urb_packs * maxsize >= period_bytes)
1419 urb_packs >>= 1;
1420 total_packs = MAX_URBS * urb_packs;
1421 }
1422
1423 ep->nurbs = (total_packs + urb_packs - 1) / urb_packs;
1424 if (ep->nurbs > MAX_URBS) {
1425 /* too much... */
1426 ep->nurbs = MAX_URBS;
1427 total_packs = MAX_URBS * urb_packs;
1428 } else if (ep->nurbs < 2) {
1429 /* too little - we need at least two packets
1430 * to ensure contiguous playback/capture
1431 */
1432 ep->nurbs = 2;
1433 }
1434
1435 /* allocate and initialize data urbs */
1436 for (i = 0; i < ep->nurbs; i++) {
1437 struct snd_urb_ctx *u = &ep->urb[i];
1438 u->index = i;
1439 u->ep = ep;
1440 u->packets = (i + 1) * total_packs / ep->nurbs
1441 - i * total_packs / ep->nurbs;
1442 u->buffer_size = maxsize * u->packets;
1443
1444 if (fmt->fmt_type == UAC_FORMAT_TYPE_II)
1445 u->packets++; /* for transfer delimiter */
1446 u->urb = usb_alloc_urb(u->packets, GFP_KERNEL);
1447 if (!u->urb)
1448 goto out_of_memory;
1449
1450 u->urb->transfer_buffer =
1451 usb_alloc_coherent(ep->chip->dev, u->buffer_size,
1452 GFP_KERNEL, &u->urb->transfer_dma);
1453 if (!u->urb->transfer_buffer)
1454 goto out_of_memory;
1455 u->urb->pipe = ep->pipe;
1456 u->urb->transfer_flags = URB_ISO_ASAP | URB_NO_TRANSFER_DMA_MAP;
1457 u->urb->interval = 1 << ep->datainterval;
1458 u->urb->context = u;
1459 u->urb->complete = snd_complete_urb;
1460 INIT_LIST_HEAD(&u->ready_list);
1461 }
1462
1463 return 0;
1464
1465out_of_memory:
1466 release_urbs(ep, 0);
1467 return -ENOMEM;
1468}
1469
1470static int sync_ep_set_params(struct snd_usb_endpoint *ep,
1471 struct snd_pcm_hw_params *hw_params,
1472 struct audioformat *fmt)
1473{
1474 int i;
1475
1476 ep->syncbuf = usb_alloc_coherent(ep->chip->dev, SYNC_URBS * 4,
1477 GFP_KERNEL, &ep->sync_dma);
1478 if (!ep->syncbuf)
1479 return -ENOMEM;
1480
1481 for (i = 0; i < SYNC_URBS; i++) {
1482 struct snd_urb_ctx *u = &ep->urb[i];
1483 u->index = i;
1484 u->ep = ep;
1485 u->packets = 1;
1486 u->urb = usb_alloc_urb(1, GFP_KERNEL);
1487 if (!u->urb)
1488 goto out_of_memory;
1489 u->urb->transfer_buffer = ep->syncbuf + i * 4;
1490 u->urb->transfer_dma = ep->sync_dma + i * 4;
1491 u->urb->transfer_buffer_length = 4;
1492 u->urb->pipe = ep->pipe;
1493 u->urb->transfer_flags = URB_ISO_ASAP |
1494 URB_NO_TRANSFER_DMA_MAP;
1495 u->urb->number_of_packets = 1;
1496 u->urb->interval = 1 << ep->syncinterval;
1497 u->urb->context = u;
1498 u->urb->complete = snd_complete_urb;
1499 }
1500
1501 ep->nurbs = SYNC_URBS;
1502
1503 return 0;
1504
1505out_of_memory:
1506 release_urbs(ep, 0);
1507 return -ENOMEM;
1508}
1509
1510int snd_usb_endpoint_set_params(struct snd_usb_endpoint *ep,
1511 struct snd_pcm_hw_params *hw_params,
1512 struct audioformat *fmt,
1513 struct snd_usb_endpoint *sync_ep)
1514{
1515 int err;
1516
1517 if (ep->use_count != 0) {
1518 snd_printk(KERN_WARNING "Unable to change format on ep #%x: already in use\n",
1519 ep->ep_num);
1520 return -EBUSY;
1521 }
1522
1523 /* release old buffers, if any */
1524 release_urbs(ep, 0);
1525
1526 ep->datainterval = fmt->datainterval;
1527 ep->maxpacksize = fmt->maxpacksize;
1528 ep->fill_max = fmt->attributes & UAC_EP_CS_ATTR_FILL_MAX;
1529
1530 if (snd_usb_get_speed(ep->chip->dev) == USB_SPEED_FULL)
1531 ep->freqn = get_usb_full_speed_rate(params_rate(hw_params));
1532 else
1533 ep->freqn = get_usb_high_speed_rate(params_rate(hw_params));
1534
1535 /* calculate the frequency in 16.16 format */
1536 ep->freqm = ep->freqn;
1537 ep->freqshift = INT_MIN;
1538
1539 ep->phase = 0;
1540
1541 switch (ep->type) {
1542 case SND_USB_ENDPOINT_TYPE_DATA:
1543 err = data_ep_set_params(ep, hw_params, fmt, sync_ep);
1544 break;
1545 case SND_USB_ENDPOINT_TYPE_SYNC:
1546 err = sync_ep_set_params(ep, hw_params, fmt);
1547 break;
1548 default:
1549 err = -EINVAL;
1550 }
1551
1552 snd_printdd(KERN_DEBUG "Setting params for ep #%x (type %d, %d urbs), ret=%d\n",
1553 ep->ep_num, ep->type, ep->nurbs, err);
1554
1555 return err;
1556}
1557
1558int snd_usb_endpoint_start(struct snd_usb_endpoint *ep)
1559{
1560 int err;
1561 unsigned int i;
1562
1563 if (ep->chip->shutdown)
1564 return -EBADFD;
1565
1566 /* already running? */
1567 if (++ep->use_count != 1)
1568 return 0;
1569
1570 if (snd_BUG_ON(!test_bit(EP_FLAG_ACTIVATED, &ep->flags)))
1571 return -EINVAL;
1572
1573 /* just to be sure */
1574 deactivate_urbs(ep, 0, 1);
1575 wait_clear_urbs(ep);
1576
1577 ep->active_mask = 0;
1578 ep->unlink_mask = 0;
1579 ep->phase = 0;
1580
1581 /*
1582 * If this endpoint has a data endpoint as implicit feedback source,
1583 * don't start the urbs here. Instead, mark them all as available,
1584 * wait for the record urbs to arrive and queue from that context.
1585 */
1586
1587 set_bit(EP_FLAG_RUNNING, &ep->flags);
1588
1589 if (snd_usb_endpoint_implict_feedback_sink(ep)) {
1590 for (i = 0; i < ep->nurbs; i++) {
1591 struct snd_urb_ctx *ctx = ep->urb + i;
1592 list_add_tail(&ctx->ready_list, &ep->ready_playback_urbs);
1593 }
1594
1595 return 0;
1596 }
1597
1598 for (i = 0; i < ep->nurbs; i++) {
1599 struct urb *urb = ep->urb[i].urb;
1600
1601 if (snd_BUG_ON(!urb))
1602 goto __error;
1603
1604 if (usb_pipeout(ep->pipe)) {
1605 prepare_outbound_urb_sizes(ep, urb->context);
1606 prepare_outbound_urb(ep, urb->context);
1607 } else {
1608 prepare_inbound_urb(ep, urb->context);
1609 }
1610
1611 err = usb_submit_urb(urb, GFP_ATOMIC);
1612 if (err < 0) {
1613 snd_printk(KERN_ERR "cannot submit urb %d, error %d: %s\n",
1614 i, err, usb_error_string(err));
1615 goto __error;
1616 }
1617 set_bit(i, &ep->active_mask);
1618 }
1619
1620 return 0;
1621
1622__error:
1623 clear_bit(EP_FLAG_RUNNING, &ep->flags);
1624 ep->use_count--;
1625 deactivate_urbs(ep, 0, 0);
1626 return -EPIPE;
1627}
1628
1629void snd_usb_endpoint_stop(struct snd_usb_endpoint *ep,
1630 int force, int can_sleep, int wait)
1631{
1632 if (!ep)
1633 return;
1634
1635 if (snd_BUG_ON(ep->use_count == 0))
1636 return;
1637
1638 if (snd_BUG_ON(!test_bit(EP_FLAG_ACTIVATED, &ep->flags)))
1639 return;
1640
1641 if (--ep->use_count == 0) {
1642 deactivate_urbs(ep, force, can_sleep);
1643 ep->data_subs = NULL;
1644 ep->sync_slave = NULL;
1645 ep->retire_data_urb = NULL;
1646 ep->prepare_data_urb = NULL;
1647
1648 if (wait)
1649 wait_clear_urbs(ep);
1650 }
1651}
1652
1653int snd_usb_endpoint_activate(struct snd_usb_endpoint *ep)
1654{
1655 if (ep->use_count != 0)
1656 return 0;
1657
1658 if (!ep->chip->shutdown &&
1659 !test_and_set_bit(EP_FLAG_ACTIVATED, &ep->flags)) {
1660 int ret;
1661
1662 ret = usb_set_interface(ep->chip->dev, ep->iface, ep->alt_idx);
1663 if (ret < 0) {
1664 snd_printk(KERN_ERR "%s() usb_set_interface() failed, ret = %d\n",
1665 __func__, ret);
1666 clear_bit(EP_FLAG_ACTIVATED, &ep->flags);
1667 return ret;
1668 }
1669
1670 return 0;
1671 }
1672
1673 return -EBUSY;
1674}
1675
1676int snd_usb_endpoint_deactivate(struct snd_usb_endpoint *ep)
1677{
1678 if (!ep)
1679 return -EINVAL;
1680
1681 if (ep->use_count != 0)
1682 return 0;
1683
1684 if (!ep->chip->shutdown &&
1685 test_and_clear_bit(EP_FLAG_ACTIVATED, &ep->flags)) {
1686 int ret;
1687
1688 ret = usb_set_interface(ep->chip->dev, ep->iface, 0);
1689 if (ret < 0) {
1690 snd_printk(KERN_ERR "%s(): usb_set_interface() failed, ret = %d\n",
1691 __func__, ret);
1692 return ret;
1693 }
1694
1695 return 0;
1696 }
1697
1698 return -EBUSY;
1699}
1700
1701void snd_usb_endpoint_free(struct list_head *head)
1702{
1703 struct snd_usb_endpoint *ep;
1704
1705 ep = list_entry(head, struct snd_usb_endpoint, list);
1706 release_urbs(ep, 1);
1707 kfree(ep);
1708}
1709
1710/*
1711 * process after playback sync complete
1712 *
1713 * Full speed devices report feedback values in 10.14 format as samples per
1714 * frame, high speed devices in 16.16 format as samples per microframe.
1715 * Because the Audio Class 1 spec was written before USB 2.0, many high speed
1716 * devices use a wrong interpretation, some others use an entirely different
1717 * format. Therefore, we cannot predict what format any particular device uses
1718 * and must detect it automatically.
1719 */
1720void snd_usb_handle_sync_urb(struct snd_usb_endpoint *ep,
1721 struct snd_usb_endpoint *sender,
1722 const struct urb *urb)
1723{
1724 int shift;
1725 unsigned int f;
1726 unsigned long flags;
1727
1728 snd_BUG_ON(ep == sender);
1729
1730 if (snd_usb_endpoint_implict_feedback_sink(ep) &&
1731 ep->use_count != 0) {
1732
1733 /* implicit feedback case */
1734 int i, bytes = 0;
1735 struct snd_urb_ctx *in_ctx;
1736 struct snd_usb_packet_info *out_packet;
1737
1738 in_ctx = urb->context;
1739
1740 /* Count overall packet size */
1741 for (i = 0; i < in_ctx->packets; i++)
1742 if (urb->iso_frame_desc[i].status == 0)
1743 bytes += urb->iso_frame_desc[i].actual_length;
1744
1745 /*
1746 * skip empty packets. At least M-Audio's Fast Track Ultra stops
1747 * streaming once it received a 0-byte OUT URB
1748 */
1749 if (bytes == 0)
1750 return;
1751
1752 spin_lock_irqsave(&ep->lock, flags);
1753 out_packet = ep->next_packet + ep->next_packet_write_pos;
1754
1755 /*
1756 * Iterate through the inbound packet and prepare the lengths
1757 * for the output packet. The OUT packet we are about to send
1758 * will have the same amount of payload than the IN packet we
1759 * just received.
1760 */
1761
1762 out_packet->packets = in_ctx->packets;
1763 for (i = 0; i < in_ctx->packets; i++) {
1764 if (urb->iso_frame_desc[i].status == 0)
1765 out_packet->packet_size[i] =
1766 urb->iso_frame_desc[i].actual_length / ep->stride;
1767 else
1768 out_packet->packet_size[i] = 0;
1769 }
1770
1771 ep->next_packet_write_pos++;
1772 ep->next_packet_write_pos %= MAX_URBS;
1773 spin_unlock_irqrestore(&ep->lock, flags);
1774 queue_pending_output_urbs(ep);
1775
1776 return;
1777 }
1778
1779 /* parse sync endpoint packet */
1780
1781 if (urb->iso_frame_desc[0].status != 0 ||
1782 urb->iso_frame_desc[0].actual_length < 3)
1783 return;
1784
1785 f = le32_to_cpup(urb->transfer_buffer);
1786 if (urb->iso_frame_desc[0].actual_length == 3)
1787 f &= 0x00ffffff;
1788 else
1789 f &= 0x0fffffff;
1790
1791 if (f == 0)
1792 return;
1793
1794 if (unlikely(ep->freqshift == INT_MIN)) {
1795 /*
1796 * The first time we see a feedback value, determine its format
1797 * by shifting it left or right until it matches the nominal
1798 * frequency value. This assumes that the feedback does not
1799 * differ from the nominal value more than +50% or -25%.
1800 */
1801 shift = 0;
1802 while (f < ep->freqn - ep->freqn / 4) {
1803 f <<= 1;
1804 shift++;
1805 }
1806 while (f > ep->freqn + ep->freqn / 2) {
1807 f >>= 1;
1808 shift--;
1809 }
1810 ep->freqshift = shift;
1811 } else if (ep->freqshift >= 0)
1812 f <<= ep->freqshift;
1813 else
1814 f >>= -ep->freqshift;
1815
1816 if (likely(f >= ep->freqn - ep->freqn / 8 && f <= ep->freqmax)) {
1817 /*
1818 * If the frequency looks valid, set it.
1819 * This value is referred to in prepare_playback_urb().
1820 */
1821 spin_lock_irqsave(&ep->lock, flags);
1822 ep->freqm = f;
1823 spin_unlock_irqrestore(&ep->lock, flags);
1824 } else {
1825 /*
1826 * Out of range; maybe the shift value is wrong.
1827 * Reset it so that we autodetect again the next time.
1828 */
1829 ep->freqshift = INT_MIN;
1830 }
1831}
1832