usb:Restore linked_func list in none-secure mode
[GitHub/MotorolaMobilityLLC/kernel-slsi.git] / sound / usb / pcm.c
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 #include <linux/init.h>
18 #include <linux/slab.h>
19 #include <linux/bitrev.h>
20 #include <linux/ratelimit.h>
21 #include <linux/usb.h>
22 #include <linux/usb/audio.h>
23 #include <linux/usb/audio-v2.h>
24
25 #include <sound/core.h>
26 #include <sound/pcm.h>
27 #include <sound/pcm_params.h>
28
29 #include "usbaudio.h"
30 #include "card.h"
31 #include "quirks.h"
32 #include "debug.h"
33 #include "endpoint.h"
34 #include "helper.h"
35 #include "pcm.h"
36 #include "clock.h"
37 #include "power.h"
38
39 #define SUBSTREAM_FLAG_DATA_EP_STARTED 0
40 #define SUBSTREAM_FLAG_SYNC_EP_STARTED 1
41
42 /* return the estimated delay based on USB frame counters */
43 snd_pcm_uframes_t snd_usb_pcm_delay(struct snd_usb_substream *subs,
44 unsigned int rate)
45 {
46 int current_frame_number;
47 int frame_diff;
48 int est_delay;
49
50 if (!subs->last_delay)
51 return 0; /* short path */
52
53 current_frame_number = usb_get_current_frame_number(subs->dev);
54 /*
55 * HCD implementations use different widths, use lower 8 bits.
56 * The delay will be managed up to 256ms, which is more than
57 * enough
58 */
59 frame_diff = (current_frame_number - subs->last_frame_number) & 0xff;
60
61 /* Approximation based on number of samples per USB frame (ms),
62 some truncation for 44.1 but the estimate is good enough */
63 est_delay = frame_diff * rate / 1000;
64 if (subs->direction == SNDRV_PCM_STREAM_PLAYBACK)
65 est_delay = subs->last_delay - est_delay;
66 else
67 est_delay = subs->last_delay + est_delay;
68
69 if (est_delay < 0)
70 est_delay = 0;
71 return est_delay;
72 }
73
74 /*
75 * return the current pcm pointer. just based on the hwptr_done value.
76 */
77 static snd_pcm_uframes_t snd_usb_pcm_pointer(struct snd_pcm_substream *substream)
78 {
79 struct snd_usb_substream *subs;
80 unsigned int hwptr_done;
81
82 subs = (struct snd_usb_substream *)substream->runtime->private_data;
83 if (atomic_read(&subs->stream->chip->shutdown))
84 return SNDRV_PCM_POS_XRUN;
85 spin_lock(&subs->lock);
86 hwptr_done = subs->hwptr_done;
87 substream->runtime->delay = snd_usb_pcm_delay(subs,
88 substream->runtime->rate);
89 spin_unlock(&subs->lock);
90 return hwptr_done / (substream->runtime->frame_bits >> 3);
91 }
92
93 /*
94 * find a matching audio format
95 */
96 static struct audioformat *find_format(struct snd_usb_substream *subs)
97 {
98 struct audioformat *fp;
99 struct audioformat *found = NULL;
100 int cur_attr = 0, attr;
101
102 list_for_each_entry(fp, &subs->fmt_list, list) {
103 if (!(fp->formats & pcm_format_to_bits(subs->pcm_format)))
104 continue;
105 if (fp->channels != subs->channels)
106 continue;
107 if (subs->cur_rate < fp->rate_min ||
108 subs->cur_rate > fp->rate_max)
109 continue;
110 if (! (fp->rates & SNDRV_PCM_RATE_CONTINUOUS)) {
111 unsigned int i;
112 for (i = 0; i < fp->nr_rates; i++)
113 if (fp->rate_table[i] == subs->cur_rate)
114 break;
115 if (i >= fp->nr_rates)
116 continue;
117 }
118 attr = fp->ep_attr & USB_ENDPOINT_SYNCTYPE;
119 if (! found) {
120 found = fp;
121 cur_attr = attr;
122 continue;
123 }
124 /* avoid async out and adaptive in if the other method
125 * supports the same format.
126 * this is a workaround for the case like
127 * M-audio audiophile USB.
128 */
129 if (attr != cur_attr) {
130 if ((attr == USB_ENDPOINT_SYNC_ASYNC &&
131 subs->direction == SNDRV_PCM_STREAM_PLAYBACK) ||
132 (attr == USB_ENDPOINT_SYNC_ADAPTIVE &&
133 subs->direction == SNDRV_PCM_STREAM_CAPTURE))
134 continue;
135 if ((cur_attr == USB_ENDPOINT_SYNC_ASYNC &&
136 subs->direction == SNDRV_PCM_STREAM_PLAYBACK) ||
137 (cur_attr == USB_ENDPOINT_SYNC_ADAPTIVE &&
138 subs->direction == SNDRV_PCM_STREAM_CAPTURE)) {
139 found = fp;
140 cur_attr = attr;
141 continue;
142 }
143 }
144 /* find the format with the largest max. packet size */
145 if (fp->maxpacksize > found->maxpacksize) {
146 found = fp;
147 cur_attr = attr;
148 }
149 }
150 return found;
151 }
152
153 static int init_pitch_v1(struct snd_usb_audio *chip, int iface,
154 struct usb_host_interface *alts,
155 struct audioformat *fmt)
156 {
157 struct usb_device *dev = chip->dev;
158 unsigned int ep;
159 unsigned char data[1];
160 int err;
161
162 if (get_iface_desc(alts)->bNumEndpoints < 1)
163 return -EINVAL;
164 ep = get_endpoint(alts, 0)->bEndpointAddress;
165
166 data[0] = 1;
167 if ((err = snd_usb_ctl_msg(dev, usb_sndctrlpipe(dev, 0), UAC_SET_CUR,
168 USB_TYPE_CLASS|USB_RECIP_ENDPOINT|USB_DIR_OUT,
169 UAC_EP_CS_ATTR_PITCH_CONTROL << 8, ep,
170 data, sizeof(data))) < 0) {
171 usb_audio_err(chip, "%d:%d: cannot set enable PITCH\n",
172 iface, ep);
173 return err;
174 }
175
176 return 0;
177 }
178
179 static int init_pitch_v2(struct snd_usb_audio *chip, int iface,
180 struct usb_host_interface *alts,
181 struct audioformat *fmt)
182 {
183 struct usb_device *dev = chip->dev;
184 unsigned char data[1];
185 int err;
186
187 data[0] = 1;
188 if ((err = snd_usb_ctl_msg(dev, usb_sndctrlpipe(dev, 0), UAC2_CS_CUR,
189 USB_TYPE_CLASS | USB_RECIP_ENDPOINT | USB_DIR_OUT,
190 UAC2_EP_CS_PITCH << 8, 0,
191 data, sizeof(data))) < 0) {
192 usb_audio_err(chip, "%d:%d: cannot set enable PITCH (v2)\n",
193 iface, fmt->altsetting);
194 return err;
195 }
196
197 return 0;
198 }
199
200 /*
201 * initialize the pitch control and sample rate
202 */
203 int snd_usb_init_pitch(struct snd_usb_audio *chip, int iface,
204 struct usb_host_interface *alts,
205 struct audioformat *fmt)
206 {
207 /* if endpoint doesn't have pitch control, bail out */
208 if (!(fmt->attributes & UAC_EP_CS_ATTR_PITCH_CONTROL))
209 return 0;
210
211 switch (fmt->protocol) {
212 case UAC_VERSION_1:
213 default:
214 return init_pitch_v1(chip, iface, alts, fmt);
215
216 case UAC_VERSION_2:
217 return init_pitch_v2(chip, iface, alts, fmt);
218 }
219 }
220
221 static int start_endpoints(struct snd_usb_substream *subs)
222 {
223 int err;
224
225 if (!subs->data_endpoint)
226 return -EINVAL;
227
228 if (!test_and_set_bit(SUBSTREAM_FLAG_DATA_EP_STARTED, &subs->flags)) {
229 struct snd_usb_endpoint *ep = subs->data_endpoint;
230
231 dev_dbg(&subs->dev->dev, "Starting data EP @%p\n", ep);
232
233 ep->data_subs = subs;
234 err = snd_usb_endpoint_start(ep);
235 if (err < 0) {
236 clear_bit(SUBSTREAM_FLAG_DATA_EP_STARTED, &subs->flags);
237 return err;
238 }
239 }
240
241 if (subs->sync_endpoint &&
242 !test_and_set_bit(SUBSTREAM_FLAG_SYNC_EP_STARTED, &subs->flags)) {
243 struct snd_usb_endpoint *ep = subs->sync_endpoint;
244
245 if (subs->data_endpoint->iface != subs->sync_endpoint->iface ||
246 subs->data_endpoint->altsetting != subs->sync_endpoint->altsetting) {
247 err = usb_set_interface(subs->dev,
248 subs->sync_endpoint->iface,
249 subs->sync_endpoint->altsetting);
250 if (err < 0) {
251 clear_bit(SUBSTREAM_FLAG_SYNC_EP_STARTED, &subs->flags);
252 dev_err(&subs->dev->dev,
253 "%d:%d: cannot set interface (%d)\n",
254 subs->sync_endpoint->iface,
255 subs->sync_endpoint->altsetting, err);
256 return -EIO;
257 }
258 }
259
260 dev_dbg(&subs->dev->dev, "Starting sync EP @%p\n", ep);
261
262 ep->sync_slave = subs->data_endpoint;
263 err = snd_usb_endpoint_start(ep);
264 if (err < 0) {
265 clear_bit(SUBSTREAM_FLAG_SYNC_EP_STARTED, &subs->flags);
266 return err;
267 }
268 }
269
270 return 0;
271 }
272
273 static void stop_endpoints(struct snd_usb_substream *subs, bool wait)
274 {
275 if (test_and_clear_bit(SUBSTREAM_FLAG_SYNC_EP_STARTED, &subs->flags))
276 snd_usb_endpoint_stop(subs->sync_endpoint);
277
278 if (test_and_clear_bit(SUBSTREAM_FLAG_DATA_EP_STARTED, &subs->flags))
279 snd_usb_endpoint_stop(subs->data_endpoint);
280
281 if (wait) {
282 snd_usb_endpoint_sync_pending_stop(subs->sync_endpoint);
283 snd_usb_endpoint_sync_pending_stop(subs->data_endpoint);
284 }
285 }
286
287 static int search_roland_implicit_fb(struct usb_device *dev, int ifnum,
288 unsigned int altsetting,
289 struct usb_host_interface **alts,
290 unsigned int *ep)
291 {
292 struct usb_interface *iface;
293 struct usb_interface_descriptor *altsd;
294 struct usb_endpoint_descriptor *epd;
295
296 iface = usb_ifnum_to_if(dev, ifnum);
297 if (!iface || iface->num_altsetting < altsetting + 1)
298 return -ENOENT;
299 *alts = &iface->altsetting[altsetting];
300 altsd = get_iface_desc(*alts);
301 if (altsd->bAlternateSetting != altsetting ||
302 altsd->bInterfaceClass != USB_CLASS_VENDOR_SPEC ||
303 (altsd->bInterfaceSubClass != 2 &&
304 altsd->bInterfaceProtocol != 2 ) ||
305 altsd->bNumEndpoints < 1)
306 return -ENOENT;
307 epd = get_endpoint(*alts, 0);
308 if (!usb_endpoint_is_isoc_in(epd) ||
309 (epd->bmAttributes & USB_ENDPOINT_USAGE_MASK) !=
310 USB_ENDPOINT_USAGE_IMPLICIT_FB)
311 return -ENOENT;
312 *ep = epd->bEndpointAddress;
313 return 0;
314 }
315
316 /* Setup an implicit feedback endpoint from a quirk. Returns 0 if no quirk
317 * applies. Returns 1 if a quirk was found.
318 */
319 static int set_sync_ep_implicit_fb_quirk(struct snd_usb_substream *subs,
320 struct usb_device *dev,
321 struct usb_interface_descriptor *altsd,
322 unsigned int attr)
323 {
324 struct usb_host_interface *alts;
325 struct usb_interface *iface;
326 unsigned int ep;
327
328 /* Implicit feedback sync EPs consumers are always playback EPs */
329 if (subs->direction != SNDRV_PCM_STREAM_PLAYBACK)
330 return 0;
331
332 switch (subs->stream->chip->usb_id) {
333 case USB_ID(0x0763, 0x2030): /* M-Audio Fast Track C400 */
334 case USB_ID(0x0763, 0x2031): /* M-Audio Fast Track C600 */
335 ep = 0x81;
336 iface = usb_ifnum_to_if(dev, 3);
337
338 if (!iface || iface->num_altsetting == 0)
339 return -EINVAL;
340
341 alts = &iface->altsetting[1];
342 goto add_sync_ep;
343 break;
344 case USB_ID(0x0763, 0x2080): /* M-Audio FastTrack Ultra */
345 case USB_ID(0x0763, 0x2081):
346 ep = 0x81;
347 iface = usb_ifnum_to_if(dev, 2);
348
349 if (!iface || iface->num_altsetting == 0)
350 return -EINVAL;
351
352 alts = &iface->altsetting[1];
353 goto add_sync_ep;
354 case USB_ID(0x2466, 0x8003):
355 ep = 0x86;
356 iface = usb_ifnum_to_if(dev, 2);
357
358 if (!iface || iface->num_altsetting == 0)
359 return -EINVAL;
360
361 alts = &iface->altsetting[1];
362 goto add_sync_ep;
363 case USB_ID(0x1397, 0x0002):
364 ep = 0x81;
365 iface = usb_ifnum_to_if(dev, 1);
366
367 if (!iface || iface->num_altsetting == 0)
368 return -EINVAL;
369
370 alts = &iface->altsetting[1];
371 goto add_sync_ep;
372
373 }
374 if (attr == USB_ENDPOINT_SYNC_ASYNC &&
375 altsd->bInterfaceClass == USB_CLASS_VENDOR_SPEC &&
376 altsd->bInterfaceProtocol == 2 &&
377 altsd->bNumEndpoints == 1 &&
378 USB_ID_VENDOR(subs->stream->chip->usb_id) == 0x0582 /* Roland */ &&
379 search_roland_implicit_fb(dev, altsd->bInterfaceNumber + 1,
380 altsd->bAlternateSetting,
381 &alts, &ep) >= 0) {
382 goto add_sync_ep;
383 }
384
385 /* No quirk */
386 return 0;
387
388 add_sync_ep:
389 subs->sync_endpoint = snd_usb_add_endpoint(subs->stream->chip,
390 alts, ep, !subs->direction,
391 SND_USB_ENDPOINT_TYPE_DATA);
392 if (!subs->sync_endpoint)
393 return -EINVAL;
394
395 subs->data_endpoint->sync_master = subs->sync_endpoint;
396
397 return 1;
398 }
399
400 static int set_sync_endpoint(struct snd_usb_substream *subs,
401 struct audioformat *fmt,
402 struct usb_device *dev,
403 struct usb_host_interface *alts,
404 struct usb_interface_descriptor *altsd)
405 {
406 int is_playback = subs->direction == SNDRV_PCM_STREAM_PLAYBACK;
407 unsigned int ep, attr;
408 bool implicit_fb;
409 int err;
410
411 /* we need a sync pipe in async OUT or adaptive IN mode */
412 /* check the number of EP, since some devices have broken
413 * descriptors which fool us. if it has only one EP,
414 * assume it as adaptive-out or sync-in.
415 */
416 attr = fmt->ep_attr & USB_ENDPOINT_SYNCTYPE;
417
418 if ((is_playback && (attr != USB_ENDPOINT_SYNC_ASYNC)) ||
419 (!is_playback && (attr != USB_ENDPOINT_SYNC_ADAPTIVE))) {
420
421 /*
422 * In these modes the notion of sync_endpoint is irrelevant.
423 * Reset pointers to avoid using stale data from previously
424 * used settings, e.g. when configuration and endpoints were
425 * changed
426 */
427
428 subs->sync_endpoint = NULL;
429 subs->data_endpoint->sync_master = NULL;
430 }
431
432 err = set_sync_ep_implicit_fb_quirk(subs, dev, altsd, attr);
433 if (err < 0)
434 return err;
435
436 /* endpoint set by quirk */
437 if (err > 0)
438 return 0;
439
440 if (altsd->bNumEndpoints < 2)
441 return 0;
442
443 if ((is_playback && (attr == USB_ENDPOINT_SYNC_SYNC ||
444 attr == USB_ENDPOINT_SYNC_ADAPTIVE)) ||
445 (!is_playback && attr != USB_ENDPOINT_SYNC_ADAPTIVE))
446 return 0;
447
448 /*
449 * In case of illegal SYNC_NONE for OUT endpoint, we keep going to see
450 * if we don't find a sync endpoint, as on M-Audio Transit. In case of
451 * error fall back to SYNC mode and don't create sync endpoint
452 */
453
454 /* check sync-pipe endpoint */
455 /* ... and check descriptor size before accessing bSynchAddress
456 because there is a version of the SB Audigy 2 NX firmware lacking
457 the audio fields in the endpoint descriptors */
458 if ((get_endpoint(alts, 1)->bmAttributes & USB_ENDPOINT_XFERTYPE_MASK) != USB_ENDPOINT_XFER_ISOC ||
459 (get_endpoint(alts, 1)->bLength >= USB_DT_ENDPOINT_AUDIO_SIZE &&
460 get_endpoint(alts, 1)->bSynchAddress != 0)) {
461 dev_err(&dev->dev,
462 "%d:%d : invalid sync pipe. bmAttributes %02x, bLength %d, bSynchAddress %02x\n",
463 fmt->iface, fmt->altsetting,
464 get_endpoint(alts, 1)->bmAttributes,
465 get_endpoint(alts, 1)->bLength,
466 get_endpoint(alts, 1)->bSynchAddress);
467 if (is_playback && attr == USB_ENDPOINT_SYNC_NONE)
468 return 0;
469 return -EINVAL;
470 }
471 ep = get_endpoint(alts, 1)->bEndpointAddress;
472 if (get_endpoint(alts, 0)->bLength >= USB_DT_ENDPOINT_AUDIO_SIZE &&
473 ((is_playback && ep != (unsigned int)(get_endpoint(alts, 0)->bSynchAddress | USB_DIR_IN)) ||
474 (!is_playback && ep != (unsigned int)(get_endpoint(alts, 0)->bSynchAddress & ~USB_DIR_IN)))) {
475 dev_err(&dev->dev,
476 "%d:%d : invalid sync pipe. is_playback %d, ep %02x, bSynchAddress %02x\n",
477 fmt->iface, fmt->altsetting,
478 is_playback, ep, get_endpoint(alts, 0)->bSynchAddress);
479 if (is_playback && attr == USB_ENDPOINT_SYNC_NONE)
480 return 0;
481 return -EINVAL;
482 }
483
484 implicit_fb = (get_endpoint(alts, 1)->bmAttributes & USB_ENDPOINT_USAGE_MASK)
485 == USB_ENDPOINT_USAGE_IMPLICIT_FB;
486
487 subs->sync_endpoint = snd_usb_add_endpoint(subs->stream->chip,
488 alts, ep, !subs->direction,
489 implicit_fb ?
490 SND_USB_ENDPOINT_TYPE_DATA :
491 SND_USB_ENDPOINT_TYPE_SYNC);
492 if (!subs->sync_endpoint) {
493 if (is_playback && attr == USB_ENDPOINT_SYNC_NONE)
494 return 0;
495 return -EINVAL;
496 }
497
498 subs->data_endpoint->sync_master = subs->sync_endpoint;
499
500 return 0;
501 }
502
503 /*
504 * find a matching format and set up the interface
505 */
506 static int set_format(struct snd_usb_substream *subs, struct audioformat *fmt)
507 {
508 struct usb_device *dev = subs->dev;
509 struct usb_host_interface *alts;
510 struct usb_interface_descriptor *altsd;
511 struct usb_interface *iface;
512 int err;
513
514 iface = usb_ifnum_to_if(dev, fmt->iface);
515 if (WARN_ON(!iface))
516 return -EINVAL;
517 alts = &iface->altsetting[fmt->altset_idx];
518 altsd = get_iface_desc(alts);
519 if (WARN_ON(altsd->bAlternateSetting != fmt->altsetting))
520 return -EINVAL;
521
522 if (fmt == subs->cur_audiofmt)
523 return 0;
524
525 /* close the old interface */
526 if (subs->interface >= 0 && subs->interface != fmt->iface) {
527 err = usb_set_interface(subs->dev, subs->interface, 0);
528 if (err < 0) {
529 dev_err(&dev->dev,
530 "%d:%d: return to setting 0 failed (%d)\n",
531 fmt->iface, fmt->altsetting, err);
532 return -EIO;
533 }
534 subs->interface = -1;
535 subs->altset_idx = 0;
536 }
537
538 /* set interface */
539 if (subs->interface != fmt->iface ||
540 subs->altset_idx != fmt->altset_idx) {
541
542 err = snd_usb_select_mode_quirk(subs, fmt);
543 if (err < 0)
544 return -EIO;
545
546 err = usb_set_interface(dev, fmt->iface, fmt->altsetting);
547 if (err < 0) {
548 dev_err(&dev->dev,
549 "%d:%d: usb_set_interface failed (%d)\n",
550 fmt->iface, fmt->altsetting, err);
551 return -EIO;
552 }
553 dev_dbg(&dev->dev, "setting usb interface %d:%d\n",
554 fmt->iface, fmt->altsetting);
555 subs->interface = fmt->iface;
556 subs->altset_idx = fmt->altset_idx;
557
558 snd_usb_set_interface_quirk(dev);
559 }
560
561 subs->data_endpoint = snd_usb_add_endpoint(subs->stream->chip,
562 alts, fmt->endpoint, subs->direction,
563 SND_USB_ENDPOINT_TYPE_DATA);
564
565 if (!subs->data_endpoint)
566 return -EINVAL;
567
568 err = set_sync_endpoint(subs, fmt, dev, alts, altsd);
569 if (err < 0)
570 return err;
571
572 err = snd_usb_init_pitch(subs->stream->chip, fmt->iface, alts, fmt);
573 if (err < 0)
574 return err;
575
576 subs->cur_audiofmt = fmt;
577
578 snd_usb_set_format_quirk(subs, fmt);
579
580 return 0;
581 }
582
583 /*
584 * Return the score of matching two audioformats.
585 * Veto the audioformat if:
586 * - It has no channels for some reason.
587 * - Requested PCM format is not supported.
588 * - Requested sample rate is not supported.
589 */
590 static int match_endpoint_audioformats(struct snd_usb_substream *subs,
591 struct audioformat *fp,
592 struct audioformat *match, int rate,
593 snd_pcm_format_t pcm_format)
594 {
595 int i;
596 int score = 0;
597
598 if (fp->channels < 1) {
599 dev_dbg(&subs->dev->dev,
600 "%s: (fmt @%p) no channels\n", __func__, fp);
601 return 0;
602 }
603
604 if (!(fp->formats & pcm_format_to_bits(pcm_format))) {
605 dev_dbg(&subs->dev->dev,
606 "%s: (fmt @%p) no match for format %d\n", __func__,
607 fp, pcm_format);
608 return 0;
609 }
610
611 for (i = 0; i < fp->nr_rates; i++) {
612 if (fp->rate_table[i] == rate) {
613 score++;
614 break;
615 }
616 }
617 if (!score) {
618 dev_dbg(&subs->dev->dev,
619 "%s: (fmt @%p) no match for rate %d\n", __func__,
620 fp, rate);
621 return 0;
622 }
623
624 if (fp->channels == match->channels)
625 score++;
626
627 dev_dbg(&subs->dev->dev,
628 "%s: (fmt @%p) score %d\n", __func__, fp, score);
629
630 return score;
631 }
632
633 /*
634 * Configure the sync ep using the rate and pcm format of the data ep.
635 */
636 static int configure_sync_endpoint(struct snd_usb_substream *subs)
637 {
638 int ret;
639 struct audioformat *fp;
640 struct audioformat *sync_fp = NULL;
641 int cur_score = 0;
642 int sync_period_bytes = subs->period_bytes;
643 struct snd_usb_substream *sync_subs =
644 &subs->stream->substream[subs->direction ^ 1];
645
646 if (subs->sync_endpoint->type != SND_USB_ENDPOINT_TYPE_DATA ||
647 !subs->stream)
648 return snd_usb_endpoint_set_params(subs->sync_endpoint,
649 subs->pcm_format,
650 subs->channels,
651 subs->period_bytes,
652 0, 0,
653 subs->cur_rate,
654 subs->cur_audiofmt,
655 NULL);
656
657 /* Try to find the best matching audioformat. */
658 list_for_each_entry(fp, &sync_subs->fmt_list, list) {
659 int score = match_endpoint_audioformats(subs,
660 fp, subs->cur_audiofmt,
661 subs->cur_rate, subs->pcm_format);
662
663 if (score > cur_score) {
664 sync_fp = fp;
665 cur_score = score;
666 }
667 }
668
669 if (unlikely(sync_fp == NULL)) {
670 dev_err(&subs->dev->dev,
671 "%s: no valid audioformat for sync ep %x found\n",
672 __func__, sync_subs->ep_num);
673 return -EINVAL;
674 }
675
676 /*
677 * Recalculate the period bytes if channel number differ between
678 * data and sync ep audioformat.
679 */
680 if (sync_fp->channels != subs->channels) {
681 sync_period_bytes = (subs->period_bytes / subs->channels) *
682 sync_fp->channels;
683 dev_dbg(&subs->dev->dev,
684 "%s: adjusted sync ep period bytes (%d -> %d)\n",
685 __func__, subs->period_bytes, sync_period_bytes);
686 }
687
688 ret = snd_usb_endpoint_set_params(subs->sync_endpoint,
689 subs->pcm_format,
690 sync_fp->channels,
691 sync_period_bytes,
692 0, 0,
693 subs->cur_rate,
694 sync_fp,
695 NULL);
696
697 return ret;
698 }
699
700 /*
701 * configure endpoint params
702 *
703 * called during initial setup and upon resume
704 */
705 static int configure_endpoint(struct snd_usb_substream *subs)
706 {
707 int ret;
708
709 /* format changed */
710 stop_endpoints(subs, true);
711 ret = snd_usb_endpoint_set_params(subs->data_endpoint,
712 subs->pcm_format,
713 subs->channels,
714 subs->period_bytes,
715 subs->period_frames,
716 subs->buffer_periods,
717 subs->cur_rate,
718 subs->cur_audiofmt,
719 subs->sync_endpoint);
720 if (ret < 0)
721 return ret;
722
723 if (subs->sync_endpoint)
724 ret = configure_sync_endpoint(subs);
725
726 return ret;
727 }
728
729 /*
730 * hw_params callback
731 *
732 * allocate a buffer and set the given audio format.
733 *
734 * so far we use a physically linear buffer although packetize transfer
735 * doesn't need a continuous area.
736 * if sg buffer is supported on the later version of alsa, we'll follow
737 * that.
738 */
739 static int snd_usb_hw_params(struct snd_pcm_substream *substream,
740 struct snd_pcm_hw_params *hw_params)
741 {
742 struct snd_usb_substream *subs = substream->runtime->private_data;
743 struct audioformat *fmt;
744 int ret;
745
746 ret = snd_pcm_lib_alloc_vmalloc_buffer(substream,
747 params_buffer_bytes(hw_params));
748 if (ret < 0)
749 return ret;
750
751 subs->pcm_format = params_format(hw_params);
752 subs->period_bytes = params_period_bytes(hw_params);
753 subs->period_frames = params_period_size(hw_params);
754 subs->buffer_periods = params_periods(hw_params);
755 subs->channels = params_channels(hw_params);
756 subs->cur_rate = params_rate(hw_params);
757
758 fmt = find_format(subs);
759 if (!fmt) {
760 dev_dbg(&subs->dev->dev,
761 "cannot set format: format = %#x, rate = %d, channels = %d\n",
762 subs->pcm_format, subs->cur_rate, subs->channels);
763 return -EINVAL;
764 }
765
766 ret = snd_usb_lock_shutdown(subs->stream->chip);
767 if (ret < 0)
768 return ret;
769 ret = set_format(subs, fmt);
770 snd_usb_unlock_shutdown(subs->stream->chip);
771 if (ret < 0)
772 return ret;
773
774 subs->interface = fmt->iface;
775 subs->altset_idx = fmt->altset_idx;
776 subs->need_setup_ep = true;
777
778 return 0;
779 }
780
781 /*
782 * hw_free callback
783 *
784 * reset the audio format and release the buffer
785 */
786 static int snd_usb_hw_free(struct snd_pcm_substream *substream)
787 {
788 struct snd_usb_substream *subs = substream->runtime->private_data;
789
790 subs->cur_audiofmt = NULL;
791 subs->cur_rate = 0;
792 subs->period_bytes = 0;
793 if (!snd_usb_lock_shutdown(subs->stream->chip)) {
794 stop_endpoints(subs, true);
795 snd_usb_endpoint_deactivate(subs->sync_endpoint);
796 snd_usb_endpoint_deactivate(subs->data_endpoint);
797 snd_usb_unlock_shutdown(subs->stream->chip);
798 }
799 return snd_pcm_lib_free_vmalloc_buffer(substream);
800 }
801
802 /*
803 * prepare callback
804 *
805 * only a few subtle things...
806 */
807 static int snd_usb_pcm_prepare(struct snd_pcm_substream *substream)
808 {
809 struct snd_pcm_runtime *runtime = substream->runtime;
810 struct snd_usb_substream *subs = runtime->private_data;
811 struct usb_host_interface *alts;
812 struct usb_interface *iface;
813 int ret;
814
815 if (! subs->cur_audiofmt) {
816 dev_err(&subs->dev->dev, "no format is specified!\n");
817 return -ENXIO;
818 }
819
820 ret = snd_usb_lock_shutdown(subs->stream->chip);
821 if (ret < 0)
822 return ret;
823 if (snd_BUG_ON(!subs->data_endpoint)) {
824 ret = -EIO;
825 goto unlock;
826 }
827
828 snd_usb_endpoint_sync_pending_stop(subs->sync_endpoint);
829 snd_usb_endpoint_sync_pending_stop(subs->data_endpoint);
830
831 ret = set_format(subs, subs->cur_audiofmt);
832 if (ret < 0)
833 goto unlock;
834
835 if (subs->need_setup_ep) {
836
837 iface = usb_ifnum_to_if(subs->dev, subs->cur_audiofmt->iface);
838 alts = &iface->altsetting[subs->cur_audiofmt->altset_idx];
839 ret = snd_usb_init_sample_rate(subs->stream->chip,
840 subs->cur_audiofmt->iface,
841 alts,
842 subs->cur_audiofmt,
843 subs->cur_rate);
844 if (ret < 0)
845 goto unlock;
846
847 ret = configure_endpoint(subs);
848 if (ret < 0)
849 goto unlock;
850 subs->need_setup_ep = false;
851 }
852
853 /* some unit conversions in runtime */
854 subs->data_endpoint->maxframesize =
855 bytes_to_frames(runtime, subs->data_endpoint->maxpacksize);
856 subs->data_endpoint->curframesize =
857 bytes_to_frames(runtime, subs->data_endpoint->curpacksize);
858
859 /* reset the pointer */
860 subs->hwptr_done = 0;
861 subs->transfer_done = 0;
862 subs->last_delay = 0;
863 subs->last_frame_number = 0;
864 runtime->delay = 0;
865
866 /* for playback, submit the URBs now; otherwise, the first hwptr_done
867 * updates for all URBs would happen at the same time when starting */
868 if (subs->direction == SNDRV_PCM_STREAM_PLAYBACK)
869 ret = start_endpoints(subs);
870
871 unlock:
872 snd_usb_unlock_shutdown(subs->stream->chip);
873 return ret;
874 }
875
876 static const struct snd_pcm_hardware snd_usb_hardware =
877 {
878 .info = SNDRV_PCM_INFO_MMAP |
879 SNDRV_PCM_INFO_MMAP_VALID |
880 SNDRV_PCM_INFO_BATCH |
881 SNDRV_PCM_INFO_INTERLEAVED |
882 SNDRV_PCM_INFO_BLOCK_TRANSFER |
883 SNDRV_PCM_INFO_PAUSE,
884 .buffer_bytes_max = 1024 * 1024,
885 .period_bytes_min = 64,
886 .period_bytes_max = 512 * 1024,
887 .periods_min = 2,
888 .periods_max = 1024,
889 };
890
891 static int hw_check_valid_format(struct snd_usb_substream *subs,
892 struct snd_pcm_hw_params *params,
893 struct audioformat *fp)
894 {
895 struct snd_interval *it = hw_param_interval(params, SNDRV_PCM_HW_PARAM_RATE);
896 struct snd_interval *ct = hw_param_interval(params, SNDRV_PCM_HW_PARAM_CHANNELS);
897 struct snd_mask *fmts = hw_param_mask(params, SNDRV_PCM_HW_PARAM_FORMAT);
898 struct snd_interval *pt = hw_param_interval(params, SNDRV_PCM_HW_PARAM_PERIOD_TIME);
899 struct snd_mask check_fmts;
900 unsigned int ptime;
901
902 /* check the format */
903 snd_mask_none(&check_fmts);
904 check_fmts.bits[0] = (u32)fp->formats;
905 check_fmts.bits[1] = (u32)(fp->formats >> 32);
906 snd_mask_intersect(&check_fmts, fmts);
907 if (snd_mask_empty(&check_fmts)) {
908 hwc_debug(" > check: no supported format %d\n", fp->format);
909 return 0;
910 }
911 /* check the channels */
912 if (fp->channels < ct->min || fp->channels > ct->max) {
913 hwc_debug(" > check: no valid channels %d (%d/%d)\n", fp->channels, ct->min, ct->max);
914 return 0;
915 }
916 /* check the rate is within the range */
917 if (fp->rate_min > it->max || (fp->rate_min == it->max && it->openmax)) {
918 hwc_debug(" > check: rate_min %d > max %d\n", fp->rate_min, it->max);
919 return 0;
920 }
921 if (fp->rate_max < it->min || (fp->rate_max == it->min && it->openmin)) {
922 hwc_debug(" > check: rate_max %d < min %d\n", fp->rate_max, it->min);
923 return 0;
924 }
925 /* check whether the period time is >= the data packet interval */
926 if (subs->speed != USB_SPEED_FULL) {
927 ptime = 125 * (1 << fp->datainterval);
928 if (ptime > pt->max || (ptime == pt->max && pt->openmax)) {
929 hwc_debug(" > check: ptime %u > max %u\n", ptime, pt->max);
930 return 0;
931 }
932 }
933 return 1;
934 }
935
936 static int hw_rule_rate(struct snd_pcm_hw_params *params,
937 struct snd_pcm_hw_rule *rule)
938 {
939 struct snd_usb_substream *subs = rule->private;
940 struct audioformat *fp;
941 struct snd_interval *it = hw_param_interval(params, SNDRV_PCM_HW_PARAM_RATE);
942 unsigned int rmin, rmax;
943 int changed;
944
945 hwc_debug("hw_rule_rate: (%d,%d)\n", it->min, it->max);
946 changed = 0;
947 rmin = rmax = 0;
948 list_for_each_entry(fp, &subs->fmt_list, list) {
949 if (!hw_check_valid_format(subs, params, fp))
950 continue;
951 if (changed++) {
952 if (rmin > fp->rate_min)
953 rmin = fp->rate_min;
954 if (rmax < fp->rate_max)
955 rmax = fp->rate_max;
956 } else {
957 rmin = fp->rate_min;
958 rmax = fp->rate_max;
959 }
960 }
961
962 if (!changed) {
963 hwc_debug(" --> get empty\n");
964 it->empty = 1;
965 return -EINVAL;
966 }
967
968 changed = 0;
969 if (it->min < rmin) {
970 it->min = rmin;
971 it->openmin = 0;
972 changed = 1;
973 }
974 if (it->max > rmax) {
975 it->max = rmax;
976 it->openmax = 0;
977 changed = 1;
978 }
979 if (snd_interval_checkempty(it)) {
980 it->empty = 1;
981 return -EINVAL;
982 }
983 hwc_debug(" --> (%d, %d) (changed = %d)\n", it->min, it->max, changed);
984 return changed;
985 }
986
987
988 static int hw_rule_channels(struct snd_pcm_hw_params *params,
989 struct snd_pcm_hw_rule *rule)
990 {
991 struct snd_usb_substream *subs = rule->private;
992 struct audioformat *fp;
993 struct snd_interval *it = hw_param_interval(params, SNDRV_PCM_HW_PARAM_CHANNELS);
994 unsigned int rmin, rmax;
995 int changed;
996
997 hwc_debug("hw_rule_channels: (%d,%d)\n", it->min, it->max);
998 changed = 0;
999 rmin = rmax = 0;
1000 list_for_each_entry(fp, &subs->fmt_list, list) {
1001 if (!hw_check_valid_format(subs, params, fp))
1002 continue;
1003 if (changed++) {
1004 if (rmin > fp->channels)
1005 rmin = fp->channels;
1006 if (rmax < fp->channels)
1007 rmax = fp->channels;
1008 } else {
1009 rmin = fp->channels;
1010 rmax = fp->channels;
1011 }
1012 }
1013
1014 if (!changed) {
1015 hwc_debug(" --> get empty\n");
1016 it->empty = 1;
1017 return -EINVAL;
1018 }
1019
1020 changed = 0;
1021 if (it->min < rmin) {
1022 it->min = rmin;
1023 it->openmin = 0;
1024 changed = 1;
1025 }
1026 if (it->max > rmax) {
1027 it->max = rmax;
1028 it->openmax = 0;
1029 changed = 1;
1030 }
1031 if (snd_interval_checkempty(it)) {
1032 it->empty = 1;
1033 return -EINVAL;
1034 }
1035 hwc_debug(" --> (%d, %d) (changed = %d)\n", it->min, it->max, changed);
1036 return changed;
1037 }
1038
1039 static int hw_rule_format(struct snd_pcm_hw_params *params,
1040 struct snd_pcm_hw_rule *rule)
1041 {
1042 struct snd_usb_substream *subs = rule->private;
1043 struct audioformat *fp;
1044 struct snd_mask *fmt = hw_param_mask(params, SNDRV_PCM_HW_PARAM_FORMAT);
1045 u64 fbits;
1046 u32 oldbits[2];
1047 int changed;
1048
1049 hwc_debug("hw_rule_format: %x:%x\n", fmt->bits[0], fmt->bits[1]);
1050 fbits = 0;
1051 list_for_each_entry(fp, &subs->fmt_list, list) {
1052 if (!hw_check_valid_format(subs, params, fp))
1053 continue;
1054 fbits |= fp->formats;
1055 }
1056
1057 oldbits[0] = fmt->bits[0];
1058 oldbits[1] = fmt->bits[1];
1059 fmt->bits[0] &= (u32)fbits;
1060 fmt->bits[1] &= (u32)(fbits >> 32);
1061 if (!fmt->bits[0] && !fmt->bits[1]) {
1062 hwc_debug(" --> get empty\n");
1063 return -EINVAL;
1064 }
1065 changed = (oldbits[0] != fmt->bits[0] || oldbits[1] != fmt->bits[1]);
1066 hwc_debug(" --> %x:%x (changed = %d)\n", fmt->bits[0], fmt->bits[1], changed);
1067 return changed;
1068 }
1069
1070 static int hw_rule_period_time(struct snd_pcm_hw_params *params,
1071 struct snd_pcm_hw_rule *rule)
1072 {
1073 struct snd_usb_substream *subs = rule->private;
1074 struct audioformat *fp;
1075 struct snd_interval *it;
1076 unsigned char min_datainterval;
1077 unsigned int pmin;
1078 int changed;
1079
1080 it = hw_param_interval(params, SNDRV_PCM_HW_PARAM_PERIOD_TIME);
1081 hwc_debug("hw_rule_period_time: (%u,%u)\n", it->min, it->max);
1082 min_datainterval = 0xff;
1083 list_for_each_entry(fp, &subs->fmt_list, list) {
1084 if (!hw_check_valid_format(subs, params, fp))
1085 continue;
1086 min_datainterval = min(min_datainterval, fp->datainterval);
1087 }
1088 if (min_datainterval == 0xff) {
1089 hwc_debug(" --> get empty\n");
1090 it->empty = 1;
1091 return -EINVAL;
1092 }
1093 pmin = 125 * (1 << min_datainterval);
1094 changed = 0;
1095 if (it->min < pmin) {
1096 it->min = pmin;
1097 it->openmin = 0;
1098 changed = 1;
1099 }
1100 if (snd_interval_checkempty(it)) {
1101 it->empty = 1;
1102 return -EINVAL;
1103 }
1104 hwc_debug(" --> (%u,%u) (changed = %d)\n", it->min, it->max, changed);
1105 return changed;
1106 }
1107
1108 /*
1109 * If the device supports unusual bit rates, does the request meet these?
1110 */
1111 static int snd_usb_pcm_check_knot(struct snd_pcm_runtime *runtime,
1112 struct snd_usb_substream *subs)
1113 {
1114 struct audioformat *fp;
1115 int *rate_list;
1116 int count = 0, needs_knot = 0;
1117 int err;
1118
1119 kfree(subs->rate_list.list);
1120 subs->rate_list.list = NULL;
1121
1122 list_for_each_entry(fp, &subs->fmt_list, list) {
1123 if (fp->rates & SNDRV_PCM_RATE_CONTINUOUS)
1124 return 0;
1125 count += fp->nr_rates;
1126 if (fp->rates & SNDRV_PCM_RATE_KNOT)
1127 needs_knot = 1;
1128 }
1129 if (!needs_knot)
1130 return 0;
1131
1132 subs->rate_list.list = rate_list =
1133 kmalloc(sizeof(int) * count, GFP_KERNEL);
1134 if (!subs->rate_list.list)
1135 return -ENOMEM;
1136 subs->rate_list.count = count;
1137 subs->rate_list.mask = 0;
1138 count = 0;
1139 list_for_each_entry(fp, &subs->fmt_list, list) {
1140 int i;
1141 for (i = 0; i < fp->nr_rates; i++)
1142 rate_list[count++] = fp->rate_table[i];
1143 }
1144 err = snd_pcm_hw_constraint_list(runtime, 0, SNDRV_PCM_HW_PARAM_RATE,
1145 &subs->rate_list);
1146 if (err < 0)
1147 return err;
1148
1149 return 0;
1150 }
1151
1152
1153 /*
1154 * set up the runtime hardware information.
1155 */
1156
1157 static int setup_hw_info(struct snd_pcm_runtime *runtime, struct snd_usb_substream *subs)
1158 {
1159 struct audioformat *fp;
1160 unsigned int pt, ptmin;
1161 int param_period_time_if_needed;
1162 int err;
1163
1164 runtime->hw.formats = subs->formats;
1165
1166 runtime->hw.rate_min = 0x7fffffff;
1167 runtime->hw.rate_max = 0;
1168 runtime->hw.channels_min = 256;
1169 runtime->hw.channels_max = 0;
1170 runtime->hw.rates = 0;
1171 ptmin = UINT_MAX;
1172 /* check min/max rates and channels */
1173 list_for_each_entry(fp, &subs->fmt_list, list) {
1174 runtime->hw.rates |= fp->rates;
1175 if (runtime->hw.rate_min > fp->rate_min)
1176 runtime->hw.rate_min = fp->rate_min;
1177 if (runtime->hw.rate_max < fp->rate_max)
1178 runtime->hw.rate_max = fp->rate_max;
1179 if (runtime->hw.channels_min > fp->channels)
1180 runtime->hw.channels_min = fp->channels;
1181 if (runtime->hw.channels_max < fp->channels)
1182 runtime->hw.channels_max = fp->channels;
1183 if (fp->fmt_type == UAC_FORMAT_TYPE_II && fp->frame_size > 0) {
1184 /* FIXME: there might be more than one audio formats... */
1185 runtime->hw.period_bytes_min = runtime->hw.period_bytes_max =
1186 fp->frame_size;
1187 }
1188 pt = 125 * (1 << fp->datainterval);
1189 ptmin = min(ptmin, pt);
1190 }
1191 err = snd_usb_autoresume(subs->stream->chip);
1192 if (err < 0)
1193 return err;
1194
1195 param_period_time_if_needed = SNDRV_PCM_HW_PARAM_PERIOD_TIME;
1196 if (subs->speed == USB_SPEED_FULL)
1197 /* full speed devices have fixed data packet interval */
1198 ptmin = 1000;
1199 if (ptmin == 1000)
1200 /* if period time doesn't go below 1 ms, no rules needed */
1201 param_period_time_if_needed = -1;
1202 snd_pcm_hw_constraint_minmax(runtime, SNDRV_PCM_HW_PARAM_PERIOD_TIME,
1203 ptmin, UINT_MAX);
1204
1205 if ((err = snd_pcm_hw_rule_add(runtime, 0, SNDRV_PCM_HW_PARAM_RATE,
1206 hw_rule_rate, subs,
1207 SNDRV_PCM_HW_PARAM_FORMAT,
1208 SNDRV_PCM_HW_PARAM_CHANNELS,
1209 param_period_time_if_needed,
1210 -1)) < 0)
1211 goto rep_err;
1212 if ((err = snd_pcm_hw_rule_add(runtime, 0, SNDRV_PCM_HW_PARAM_CHANNELS,
1213 hw_rule_channels, subs,
1214 SNDRV_PCM_HW_PARAM_FORMAT,
1215 SNDRV_PCM_HW_PARAM_RATE,
1216 param_period_time_if_needed,
1217 -1)) < 0)
1218 goto rep_err;
1219 if ((err = snd_pcm_hw_rule_add(runtime, 0, SNDRV_PCM_HW_PARAM_FORMAT,
1220 hw_rule_format, subs,
1221 SNDRV_PCM_HW_PARAM_RATE,
1222 SNDRV_PCM_HW_PARAM_CHANNELS,
1223 param_period_time_if_needed,
1224 -1)) < 0)
1225 goto rep_err;
1226 if (param_period_time_if_needed >= 0) {
1227 err = snd_pcm_hw_rule_add(runtime, 0,
1228 SNDRV_PCM_HW_PARAM_PERIOD_TIME,
1229 hw_rule_period_time, subs,
1230 SNDRV_PCM_HW_PARAM_FORMAT,
1231 SNDRV_PCM_HW_PARAM_CHANNELS,
1232 SNDRV_PCM_HW_PARAM_RATE,
1233 -1);
1234 if (err < 0)
1235 goto rep_err;
1236 }
1237 if ((err = snd_usb_pcm_check_knot(runtime, subs)) < 0)
1238 goto rep_err;
1239 return 0;
1240
1241 rep_err:
1242 snd_usb_autosuspend(subs->stream->chip);
1243 return err;
1244 }
1245
1246 static int snd_usb_pcm_open(struct snd_pcm_substream *substream, int direction)
1247 {
1248 struct snd_usb_stream *as = snd_pcm_substream_chip(substream);
1249 struct snd_pcm_runtime *runtime = substream->runtime;
1250 struct snd_usb_substream *subs = &as->substream[direction];
1251
1252 subs->interface = -1;
1253 subs->altset_idx = 0;
1254 runtime->hw = snd_usb_hardware;
1255 runtime->private_data = subs;
1256 subs->pcm_substream = substream;
1257 /* runtime PM is also done there */
1258
1259 /* initialize DSD/DOP context */
1260 subs->dsd_dop.byte_idx = 0;
1261 subs->dsd_dop.channel = 0;
1262 subs->dsd_dop.marker = 1;
1263
1264 return setup_hw_info(runtime, subs);
1265 }
1266
1267 static int snd_usb_pcm_close(struct snd_pcm_substream *substream, int direction)
1268 {
1269 struct snd_usb_stream *as = snd_pcm_substream_chip(substream);
1270 struct snd_usb_substream *subs = &as->substream[direction];
1271
1272 stop_endpoints(subs, true);
1273
1274 if (subs->interface >= 0 &&
1275 !snd_usb_lock_shutdown(subs->stream->chip)) {
1276 usb_set_interface(subs->dev, subs->interface, 0);
1277 subs->interface = -1;
1278 snd_usb_unlock_shutdown(subs->stream->chip);
1279 }
1280
1281 subs->pcm_substream = NULL;
1282 snd_usb_autosuspend(subs->stream->chip);
1283
1284 return 0;
1285 }
1286
1287 /* Since a URB can handle only a single linear buffer, we must use double
1288 * buffering when the data to be transferred overflows the buffer boundary.
1289 * To avoid inconsistencies when updating hwptr_done, we use double buffering
1290 * for all URBs.
1291 */
1292 static void retire_capture_urb(struct snd_usb_substream *subs,
1293 struct urb *urb)
1294 {
1295 struct snd_pcm_runtime *runtime = subs->pcm_substream->runtime;
1296 unsigned int stride, frames, bytes, oldptr;
1297 int i, period_elapsed = 0;
1298 unsigned long flags;
1299 unsigned char *cp;
1300 int current_frame_number;
1301
1302 /* read frame number here, update pointer in critical section */
1303 current_frame_number = usb_get_current_frame_number(subs->dev);
1304
1305 stride = runtime->frame_bits >> 3;
1306
1307 for (i = 0; i < urb->number_of_packets; i++) {
1308 cp = (unsigned char *)urb->transfer_buffer + urb->iso_frame_desc[i].offset + subs->pkt_offset_adj;
1309 if (urb->iso_frame_desc[i].status && printk_ratelimit()) {
1310 dev_dbg(&subs->dev->dev, "frame %d active: %d\n",
1311 i, urb->iso_frame_desc[i].status);
1312 // continue;
1313 }
1314 bytes = urb->iso_frame_desc[i].actual_length;
1315 frames = bytes / stride;
1316 if (!subs->txfr_quirk)
1317 bytes = frames * stride;
1318 if (bytes % (runtime->sample_bits >> 3) != 0) {
1319 int oldbytes = bytes;
1320 bytes = frames * stride;
1321 dev_warn_ratelimited(&subs->dev->dev,
1322 "Corrected urb data len. %d->%d\n",
1323 oldbytes, bytes);
1324 }
1325 /* update the current pointer */
1326 spin_lock_irqsave(&subs->lock, flags);
1327 oldptr = subs->hwptr_done;
1328 subs->hwptr_done += bytes;
1329 if (subs->hwptr_done >= runtime->buffer_size * stride)
1330 subs->hwptr_done -= runtime->buffer_size * stride;
1331 frames = (bytes + (oldptr % stride)) / stride;
1332 subs->transfer_done += frames;
1333 if (subs->transfer_done >= runtime->period_size) {
1334 subs->transfer_done -= runtime->period_size;
1335 period_elapsed = 1;
1336 }
1337 /* capture delay is by construction limited to one URB,
1338 * reset delays here
1339 */
1340 runtime->delay = subs->last_delay = 0;
1341
1342 /* realign last_frame_number */
1343 subs->last_frame_number = current_frame_number;
1344 subs->last_frame_number &= 0xFF; /* keep 8 LSBs */
1345
1346 spin_unlock_irqrestore(&subs->lock, flags);
1347 /* copy a data chunk */
1348 if (oldptr + bytes > runtime->buffer_size * stride) {
1349 unsigned int bytes1 =
1350 runtime->buffer_size * stride - oldptr;
1351 memcpy(runtime->dma_area + oldptr, cp, bytes1);
1352 memcpy(runtime->dma_area, cp + bytes1, bytes - bytes1);
1353 } else {
1354 memcpy(runtime->dma_area + oldptr, cp, bytes);
1355 }
1356 }
1357
1358 if (period_elapsed)
1359 snd_pcm_period_elapsed(subs->pcm_substream);
1360 }
1361
1362 static inline void fill_playback_urb_dsd_dop(struct snd_usb_substream *subs,
1363 struct urb *urb, unsigned int bytes)
1364 {
1365 struct snd_pcm_runtime *runtime = subs->pcm_substream->runtime;
1366 unsigned int stride = runtime->frame_bits >> 3;
1367 unsigned int dst_idx = 0;
1368 unsigned int src_idx = subs->hwptr_done;
1369 unsigned int wrap = runtime->buffer_size * stride;
1370 u8 *dst = urb->transfer_buffer;
1371 u8 *src = runtime->dma_area;
1372 u8 marker[] = { 0x05, 0xfa };
1373
1374 /*
1375 * The DSP DOP format defines a way to transport DSD samples over
1376 * normal PCM data endpoints. It requires stuffing of marker bytes
1377 * (0x05 and 0xfa, alternating per sample frame), and then expects
1378 * 2 additional bytes of actual payload. The whole frame is stored
1379 * LSB.
1380 *
1381 * Hence, for a stereo transport, the buffer layout looks like this,
1382 * where L refers to left channel samples and R to right.
1383 *
1384 * L1 L2 0x05 R1 R2 0x05 L3 L4 0xfa R3 R4 0xfa
1385 * L5 L6 0x05 R5 R6 0x05 L7 L8 0xfa R7 R8 0xfa
1386 * .....
1387 *
1388 */
1389
1390 while (bytes--) {
1391 if (++subs->dsd_dop.byte_idx == 3) {
1392 /* frame boundary? */
1393 dst[dst_idx++] = marker[subs->dsd_dop.marker];
1394 src_idx += 2;
1395 subs->dsd_dop.byte_idx = 0;
1396
1397 if (++subs->dsd_dop.channel % runtime->channels == 0) {
1398 /* alternate the marker */
1399 subs->dsd_dop.marker++;
1400 subs->dsd_dop.marker %= ARRAY_SIZE(marker);
1401 subs->dsd_dop.channel = 0;
1402 }
1403 } else {
1404 /* stuff the DSD payload */
1405 int idx = (src_idx + subs->dsd_dop.byte_idx - 1) % wrap;
1406
1407 if (subs->cur_audiofmt->dsd_bitrev)
1408 dst[dst_idx++] = bitrev8(src[idx]);
1409 else
1410 dst[dst_idx++] = src[idx];
1411
1412 subs->hwptr_done++;
1413 }
1414 }
1415 if (subs->hwptr_done >= runtime->buffer_size * stride)
1416 subs->hwptr_done -= runtime->buffer_size * stride;
1417 }
1418
1419 static void copy_to_urb(struct snd_usb_substream *subs, struct urb *urb,
1420 int offset, int stride, unsigned int bytes)
1421 {
1422 struct snd_pcm_runtime *runtime = subs->pcm_substream->runtime;
1423
1424 if (subs->hwptr_done + bytes > runtime->buffer_size * stride) {
1425 /* err, the transferred area goes over buffer boundary. */
1426 unsigned int bytes1 =
1427 runtime->buffer_size * stride - subs->hwptr_done;
1428 memcpy(urb->transfer_buffer + offset,
1429 runtime->dma_area + subs->hwptr_done, bytes1);
1430 memcpy(urb->transfer_buffer + offset + bytes1,
1431 runtime->dma_area, bytes - bytes1);
1432 } else {
1433 memcpy(urb->transfer_buffer + offset,
1434 runtime->dma_area + subs->hwptr_done, bytes);
1435 }
1436 subs->hwptr_done += bytes;
1437 if (subs->hwptr_done >= runtime->buffer_size * stride)
1438 subs->hwptr_done -= runtime->buffer_size * stride;
1439 }
1440
1441 static unsigned int copy_to_urb_quirk(struct snd_usb_substream *subs,
1442 struct urb *urb, int stride,
1443 unsigned int bytes)
1444 {
1445 __le32 packet_length;
1446 int i;
1447
1448 /* Put __le32 length descriptor at start of each packet. */
1449 for (i = 0; i < urb->number_of_packets; i++) {
1450 unsigned int length = urb->iso_frame_desc[i].length;
1451 unsigned int offset = urb->iso_frame_desc[i].offset;
1452
1453 packet_length = cpu_to_le32(length);
1454 offset += i * sizeof(packet_length);
1455 urb->iso_frame_desc[i].offset = offset;
1456 urb->iso_frame_desc[i].length += sizeof(packet_length);
1457 memcpy(urb->transfer_buffer + offset,
1458 &packet_length, sizeof(packet_length));
1459 copy_to_urb(subs, urb, offset + sizeof(packet_length),
1460 stride, length);
1461 }
1462 /* Adjust transfer size accordingly. */
1463 bytes += urb->number_of_packets * sizeof(packet_length);
1464 return bytes;
1465 }
1466
1467 static void prepare_playback_urb(struct snd_usb_substream *subs,
1468 struct urb *urb)
1469 {
1470 struct snd_pcm_runtime *runtime = subs->pcm_substream->runtime;
1471 struct snd_usb_endpoint *ep = subs->data_endpoint;
1472 struct snd_urb_ctx *ctx = urb->context;
1473 unsigned int counts, frames, bytes;
1474 int i, stride, period_elapsed = 0;
1475 unsigned long flags;
1476
1477 stride = runtime->frame_bits >> 3;
1478
1479 frames = 0;
1480 urb->number_of_packets = 0;
1481 spin_lock_irqsave(&subs->lock, flags);
1482 subs->frame_limit += ep->max_urb_frames;
1483 for (i = 0; i < ctx->packets; i++) {
1484 if (ctx->packet_size[i])
1485 counts = ctx->packet_size[i];
1486 else
1487 counts = snd_usb_endpoint_next_packet_size(ep);
1488
1489 /* set up descriptor */
1490 urb->iso_frame_desc[i].offset = frames * ep->stride;
1491 urb->iso_frame_desc[i].length = counts * ep->stride;
1492 frames += counts;
1493 urb->number_of_packets++;
1494 subs->transfer_done += counts;
1495 if (subs->transfer_done >= runtime->period_size) {
1496 subs->transfer_done -= runtime->period_size;
1497 subs->frame_limit = 0;
1498 period_elapsed = 1;
1499 if (subs->fmt_type == UAC_FORMAT_TYPE_II) {
1500 if (subs->transfer_done > 0) {
1501 /* FIXME: fill-max mode is not
1502 * supported yet */
1503 frames -= subs->transfer_done;
1504 counts -= subs->transfer_done;
1505 urb->iso_frame_desc[i].length =
1506 counts * ep->stride;
1507 subs->transfer_done = 0;
1508 }
1509 i++;
1510 if (i < ctx->packets) {
1511 /* add a transfer delimiter */
1512 urb->iso_frame_desc[i].offset =
1513 frames * ep->stride;
1514 urb->iso_frame_desc[i].length = 0;
1515 urb->number_of_packets++;
1516 }
1517 break;
1518 }
1519 }
1520 /* finish at the period boundary or after enough frames */
1521 if ((period_elapsed ||
1522 subs->transfer_done >= subs->frame_limit) &&
1523 !snd_usb_endpoint_implicit_feedback_sink(ep))
1524 break;
1525 }
1526 bytes = frames * ep->stride;
1527
1528 if (unlikely(subs->pcm_format == SNDRV_PCM_FORMAT_DSD_U16_LE &&
1529 subs->cur_audiofmt->dsd_dop)) {
1530 fill_playback_urb_dsd_dop(subs, urb, bytes);
1531 } else if (unlikely(subs->pcm_format == SNDRV_PCM_FORMAT_DSD_U8 &&
1532 subs->cur_audiofmt->dsd_bitrev)) {
1533 /* bit-reverse the bytes */
1534 u8 *buf = urb->transfer_buffer;
1535 for (i = 0; i < bytes; i++) {
1536 int idx = (subs->hwptr_done + i)
1537 % (runtime->buffer_size * stride);
1538 buf[i] = bitrev8(runtime->dma_area[idx]);
1539 }
1540
1541 subs->hwptr_done += bytes;
1542 if (subs->hwptr_done >= runtime->buffer_size * stride)
1543 subs->hwptr_done -= runtime->buffer_size * stride;
1544 } else {
1545 /* usual PCM */
1546 if (!subs->tx_length_quirk)
1547 copy_to_urb(subs, urb, 0, stride, bytes);
1548 else
1549 bytes = copy_to_urb_quirk(subs, urb, stride, bytes);
1550 /* bytes is now amount of outgoing data */
1551 }
1552
1553 /* update delay with exact number of samples queued */
1554 runtime->delay = subs->last_delay;
1555 runtime->delay += frames;
1556 subs->last_delay = runtime->delay;
1557
1558 /* realign last_frame_number */
1559 subs->last_frame_number = usb_get_current_frame_number(subs->dev);
1560 subs->last_frame_number &= 0xFF; /* keep 8 LSBs */
1561
1562 if (subs->trigger_tstamp_pending_update) {
1563 /* this is the first actual URB submitted,
1564 * update trigger timestamp to reflect actual start time
1565 */
1566 snd_pcm_gettime(runtime, &runtime->trigger_tstamp);
1567 subs->trigger_tstamp_pending_update = false;
1568 }
1569
1570 spin_unlock_irqrestore(&subs->lock, flags);
1571 urb->transfer_buffer_length = bytes;
1572 if (period_elapsed)
1573 snd_pcm_period_elapsed(subs->pcm_substream);
1574 }
1575
1576 /*
1577 * process after playback data complete
1578 * - decrease the delay count again
1579 */
1580 static void retire_playback_urb(struct snd_usb_substream *subs,
1581 struct urb *urb)
1582 {
1583 unsigned long flags;
1584 struct snd_pcm_runtime *runtime = subs->pcm_substream->runtime;
1585 struct snd_usb_endpoint *ep = subs->data_endpoint;
1586 int processed = urb->transfer_buffer_length / ep->stride;
1587 int est_delay;
1588
1589 /* ignore the delay accounting when procssed=0 is given, i.e.
1590 * silent payloads are procssed before handling the actual data
1591 */
1592 if (!processed)
1593 return;
1594
1595 spin_lock_irqsave(&subs->lock, flags);
1596 if (!subs->last_delay)
1597 goto out; /* short path */
1598
1599 est_delay = snd_usb_pcm_delay(subs, runtime->rate);
1600 /* update delay with exact number of samples played */
1601 if (processed > subs->last_delay)
1602 subs->last_delay = 0;
1603 else
1604 subs->last_delay -= processed;
1605 runtime->delay = subs->last_delay;
1606
1607 /*
1608 * Report when delay estimate is off by more than 2ms.
1609 * The error should be lower than 2ms since the estimate relies
1610 * on two reads of a counter updated every ms.
1611 */
1612 if (abs(est_delay - subs->last_delay) * 1000 > runtime->rate * 2)
1613 dev_dbg_ratelimited(&subs->dev->dev,
1614 "delay: estimated %d, actual %d\n",
1615 est_delay, subs->last_delay);
1616
1617 if (!subs->running) {
1618 /* update last_frame_number for delay counting here since
1619 * prepare_playback_urb won't be called during pause
1620 */
1621 subs->last_frame_number =
1622 usb_get_current_frame_number(subs->dev) & 0xff;
1623 }
1624
1625 out:
1626 spin_unlock_irqrestore(&subs->lock, flags);
1627 }
1628
1629 static int snd_usb_playback_open(struct snd_pcm_substream *substream)
1630 {
1631 return snd_usb_pcm_open(substream, SNDRV_PCM_STREAM_PLAYBACK);
1632 }
1633
1634 static int snd_usb_playback_close(struct snd_pcm_substream *substream)
1635 {
1636 return snd_usb_pcm_close(substream, SNDRV_PCM_STREAM_PLAYBACK);
1637 }
1638
1639 static int snd_usb_capture_open(struct snd_pcm_substream *substream)
1640 {
1641 return snd_usb_pcm_open(substream, SNDRV_PCM_STREAM_CAPTURE);
1642 }
1643
1644 static int snd_usb_capture_close(struct snd_pcm_substream *substream)
1645 {
1646 return snd_usb_pcm_close(substream, SNDRV_PCM_STREAM_CAPTURE);
1647 }
1648
1649 static int snd_usb_substream_playback_trigger(struct snd_pcm_substream *substream,
1650 int cmd)
1651 {
1652 struct snd_usb_substream *subs = substream->runtime->private_data;
1653
1654 switch (cmd) {
1655 case SNDRV_PCM_TRIGGER_START:
1656 subs->trigger_tstamp_pending_update = true;
1657 case SNDRV_PCM_TRIGGER_PAUSE_RELEASE:
1658 subs->data_endpoint->prepare_data_urb = prepare_playback_urb;
1659 subs->data_endpoint->retire_data_urb = retire_playback_urb;
1660 subs->running = 1;
1661 return 0;
1662 case SNDRV_PCM_TRIGGER_STOP:
1663 stop_endpoints(subs, false);
1664 subs->running = 0;
1665 return 0;
1666 case SNDRV_PCM_TRIGGER_PAUSE_PUSH:
1667 subs->data_endpoint->prepare_data_urb = NULL;
1668 /* keep retire_data_urb for delay calculation */
1669 subs->data_endpoint->retire_data_urb = retire_playback_urb;
1670 subs->running = 0;
1671 return 0;
1672 }
1673
1674 return -EINVAL;
1675 }
1676
1677 static int snd_usb_substream_capture_trigger(struct snd_pcm_substream *substream,
1678 int cmd)
1679 {
1680 int err;
1681 struct snd_usb_substream *subs = substream->runtime->private_data;
1682
1683 switch (cmd) {
1684 case SNDRV_PCM_TRIGGER_START:
1685 err = start_endpoints(subs);
1686 if (err < 0)
1687 return err;
1688
1689 subs->data_endpoint->retire_data_urb = retire_capture_urb;
1690 subs->running = 1;
1691 return 0;
1692 case SNDRV_PCM_TRIGGER_STOP:
1693 stop_endpoints(subs, false);
1694 subs->running = 0;
1695 return 0;
1696 case SNDRV_PCM_TRIGGER_PAUSE_PUSH:
1697 subs->data_endpoint->retire_data_urb = NULL;
1698 subs->running = 0;
1699 return 0;
1700 case SNDRV_PCM_TRIGGER_PAUSE_RELEASE:
1701 subs->data_endpoint->retire_data_urb = retire_capture_urb;
1702 subs->running = 1;
1703 return 0;
1704 }
1705
1706 return -EINVAL;
1707 }
1708
1709 static const struct snd_pcm_ops snd_usb_playback_ops = {
1710 .open = snd_usb_playback_open,
1711 .close = snd_usb_playback_close,
1712 .ioctl = snd_pcm_lib_ioctl,
1713 .hw_params = snd_usb_hw_params,
1714 .hw_free = snd_usb_hw_free,
1715 .prepare = snd_usb_pcm_prepare,
1716 .trigger = snd_usb_substream_playback_trigger,
1717 .pointer = snd_usb_pcm_pointer,
1718 .page = snd_pcm_lib_get_vmalloc_page,
1719 .mmap = snd_pcm_lib_mmap_vmalloc,
1720 };
1721
1722 static const struct snd_pcm_ops snd_usb_capture_ops = {
1723 .open = snd_usb_capture_open,
1724 .close = snd_usb_capture_close,
1725 .ioctl = snd_pcm_lib_ioctl,
1726 .hw_params = snd_usb_hw_params,
1727 .hw_free = snd_usb_hw_free,
1728 .prepare = snd_usb_pcm_prepare,
1729 .trigger = snd_usb_substream_capture_trigger,
1730 .pointer = snd_usb_pcm_pointer,
1731 .page = snd_pcm_lib_get_vmalloc_page,
1732 .mmap = snd_pcm_lib_mmap_vmalloc,
1733 };
1734
1735 void snd_usb_set_pcm_ops(struct snd_pcm *pcm, int stream)
1736 {
1737 snd_pcm_set_ops(pcm, stream,
1738 stream == SNDRV_PCM_STREAM_PLAYBACK ?
1739 &snd_usb_playback_ops : &snd_usb_capture_ops);
1740 }