IB/ipoib: Fix double free of skb in case of multicast traffic in CM mode
[linux/fpc-iii.git] / sound / usb / pcm.c
blob8b91be394407a33094817c6e18d3b729d086ece2
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.
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.
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
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>
25 #include <sound/core.h>
26 #include <sound/pcm.h>
27 #include <sound/pcm_params.h>
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"
39 #define SUBSTREAM_FLAG_DATA_EP_STARTED 0
40 #define SUBSTREAM_FLAG_SYNC_EP_STARTED 1
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)
46 int current_frame_number;
47 int frame_diff;
48 int est_delay;
50 if (!subs->last_delay)
51 return 0; /* short path */
53 current_frame_number = usb_get_current_frame_number(subs->dev);
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
59 frame_diff = (current_frame_number - subs->last_frame_number) & 0xff;
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;
69 if (est_delay < 0)
70 est_delay = 0;
71 return est_delay;
75 * return the current pcm pointer. just based on the hwptr_done value.
77 static snd_pcm_uframes_t snd_usb_pcm_pointer(struct snd_pcm_substream *substream)
79 struct snd_usb_substream *subs = substream->runtime->private_data;
80 unsigned int hwptr_done;
82 if (atomic_read(&subs->stream->chip->shutdown))
83 return SNDRV_PCM_POS_XRUN;
84 spin_lock(&subs->lock);
85 hwptr_done = subs->hwptr_done;
86 substream->runtime->delay = snd_usb_pcm_delay(subs,
87 substream->runtime->rate);
88 spin_unlock(&subs->lock);
89 return hwptr_done / (substream->runtime->frame_bits >> 3);
93 * find a matching audio format
95 static struct audioformat *find_format(struct snd_usb_substream *subs)
97 struct audioformat *fp;
98 struct audioformat *found = NULL;
99 int cur_attr = 0, attr;
101 list_for_each_entry(fp, &subs->fmt_list, list) {
102 if (!(fp->formats & pcm_format_to_bits(subs->pcm_format)))
103 continue;
104 if (fp->channels != subs->channels)
105 continue;
106 if (subs->cur_rate < fp->rate_min ||
107 subs->cur_rate > fp->rate_max)
108 continue;
109 if (! (fp->rates & SNDRV_PCM_RATE_CONTINUOUS)) {
110 unsigned int i;
111 for (i = 0; i < fp->nr_rates; i++)
112 if (fp->rate_table[i] == subs->cur_rate)
113 break;
114 if (i >= fp->nr_rates)
115 continue;
117 attr = fp->ep_attr & USB_ENDPOINT_SYNCTYPE;
118 if (! found) {
119 found = fp;
120 cur_attr = attr;
121 continue;
123 /* avoid async out and adaptive in if the other method
124 * supports the same format.
125 * this is a workaround for the case like
126 * M-audio audiophile USB.
128 if (attr != cur_attr) {
129 if ((attr == USB_ENDPOINT_SYNC_ASYNC &&
130 subs->direction == SNDRV_PCM_STREAM_PLAYBACK) ||
131 (attr == USB_ENDPOINT_SYNC_ADAPTIVE &&
132 subs->direction == SNDRV_PCM_STREAM_CAPTURE))
133 continue;
134 if ((cur_attr == USB_ENDPOINT_SYNC_ASYNC &&
135 subs->direction == SNDRV_PCM_STREAM_PLAYBACK) ||
136 (cur_attr == USB_ENDPOINT_SYNC_ADAPTIVE &&
137 subs->direction == SNDRV_PCM_STREAM_CAPTURE)) {
138 found = fp;
139 cur_attr = attr;
140 continue;
143 /* find the format with the largest max. packet size */
144 if (fp->maxpacksize > found->maxpacksize) {
145 found = fp;
146 cur_attr = attr;
149 return found;
152 static int init_pitch_v1(struct snd_usb_audio *chip, int iface,
153 struct usb_host_interface *alts,
154 struct audioformat *fmt)
156 struct usb_device *dev = chip->dev;
157 unsigned int ep;
158 unsigned char data[1];
159 int err;
161 if (get_iface_desc(alts)->bNumEndpoints < 1)
162 return -EINVAL;
163 ep = get_endpoint(alts, 0)->bEndpointAddress;
165 data[0] = 1;
166 err = snd_usb_ctl_msg(dev, usb_sndctrlpipe(dev, 0), UAC_SET_CUR,
167 USB_TYPE_CLASS|USB_RECIP_ENDPOINT|USB_DIR_OUT,
168 UAC_EP_CS_ATTR_PITCH_CONTROL << 8, ep,
169 data, sizeof(data));
170 if (err < 0) {
171 usb_audio_err(chip, "%d:%d: cannot set enable PITCH\n",
172 iface, ep);
173 return err;
176 return 0;
179 static int init_pitch_v2(struct snd_usb_audio *chip, int iface,
180 struct usb_host_interface *alts,
181 struct audioformat *fmt)
183 struct usb_device *dev = chip->dev;
184 unsigned char data[1];
185 int err;
187 data[0] = 1;
188 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));
192 if (err < 0) {
193 usb_audio_err(chip, "%d:%d: cannot set enable PITCH (v2)\n",
194 iface, fmt->altsetting);
195 return err;
198 return 0;
202 * initialize the pitch control and sample rate
204 int snd_usb_init_pitch(struct snd_usb_audio *chip, int iface,
205 struct usb_host_interface *alts,
206 struct audioformat *fmt)
208 /* if endpoint doesn't have pitch control, bail out */
209 if (!(fmt->attributes & UAC_EP_CS_ATTR_PITCH_CONTROL))
210 return 0;
212 switch (fmt->protocol) {
213 case UAC_VERSION_1:
214 default:
215 return init_pitch_v1(chip, iface, alts, fmt);
217 case UAC_VERSION_2:
218 return init_pitch_v2(chip, iface, alts, fmt);
222 static int start_endpoints(struct snd_usb_substream *subs)
224 int err;
226 if (!subs->data_endpoint)
227 return -EINVAL;
229 if (!test_and_set_bit(SUBSTREAM_FLAG_DATA_EP_STARTED, &subs->flags)) {
230 struct snd_usb_endpoint *ep = subs->data_endpoint;
232 dev_dbg(&subs->dev->dev, "Starting data EP @%p\n", ep);
234 ep->data_subs = subs;
235 err = snd_usb_endpoint_start(ep);
236 if (err < 0) {
237 clear_bit(SUBSTREAM_FLAG_DATA_EP_STARTED, &subs->flags);
238 return err;
242 if (subs->sync_endpoint &&
243 !test_and_set_bit(SUBSTREAM_FLAG_SYNC_EP_STARTED, &subs->flags)) {
244 struct snd_usb_endpoint *ep = subs->sync_endpoint;
246 if (subs->data_endpoint->iface != subs->sync_endpoint->iface ||
247 subs->data_endpoint->altsetting != subs->sync_endpoint->altsetting) {
248 err = usb_set_interface(subs->dev,
249 subs->sync_endpoint->iface,
250 subs->sync_endpoint->altsetting);
251 if (err < 0) {
252 clear_bit(SUBSTREAM_FLAG_SYNC_EP_STARTED, &subs->flags);
253 dev_err(&subs->dev->dev,
254 "%d:%d: cannot set interface (%d)\n",
255 subs->sync_endpoint->iface,
256 subs->sync_endpoint->altsetting, err);
257 return -EIO;
261 dev_dbg(&subs->dev->dev, "Starting sync EP @%p\n", ep);
263 ep->sync_slave = subs->data_endpoint;
264 err = snd_usb_endpoint_start(ep);
265 if (err < 0) {
266 clear_bit(SUBSTREAM_FLAG_SYNC_EP_STARTED, &subs->flags);
267 return err;
271 return 0;
274 static void stop_endpoints(struct snd_usb_substream *subs, bool wait)
276 if (test_and_clear_bit(SUBSTREAM_FLAG_SYNC_EP_STARTED, &subs->flags))
277 snd_usb_endpoint_stop(subs->sync_endpoint);
279 if (test_and_clear_bit(SUBSTREAM_FLAG_DATA_EP_STARTED, &subs->flags))
280 snd_usb_endpoint_stop(subs->data_endpoint);
282 if (wait) {
283 snd_usb_endpoint_sync_pending_stop(subs->sync_endpoint);
284 snd_usb_endpoint_sync_pending_stop(subs->data_endpoint);
288 static int search_roland_implicit_fb(struct usb_device *dev, int ifnum,
289 unsigned int altsetting,
290 struct usb_host_interface **alts,
291 unsigned int *ep)
293 struct usb_interface *iface;
294 struct usb_interface_descriptor *altsd;
295 struct usb_endpoint_descriptor *epd;
297 iface = usb_ifnum_to_if(dev, ifnum);
298 if (!iface || iface->num_altsetting < altsetting + 1)
299 return -ENOENT;
300 *alts = &iface->altsetting[altsetting];
301 altsd = get_iface_desc(*alts);
302 if (altsd->bAlternateSetting != altsetting ||
303 altsd->bInterfaceClass != USB_CLASS_VENDOR_SPEC ||
304 (altsd->bInterfaceSubClass != 2 &&
305 altsd->bInterfaceProtocol != 2 ) ||
306 altsd->bNumEndpoints < 1)
307 return -ENOENT;
308 epd = get_endpoint(*alts, 0);
309 if (!usb_endpoint_is_isoc_in(epd) ||
310 (epd->bmAttributes & USB_ENDPOINT_USAGE_MASK) !=
311 USB_ENDPOINT_USAGE_IMPLICIT_FB)
312 return -ENOENT;
313 *ep = epd->bEndpointAddress;
314 return 0;
317 /* Setup an implicit feedback endpoint from a quirk. Returns 0 if no quirk
318 * applies. Returns 1 if a quirk was found.
320 static int set_sync_ep_implicit_fb_quirk(struct snd_usb_substream *subs,
321 struct usb_device *dev,
322 struct usb_interface_descriptor *altsd,
323 unsigned int attr)
325 struct usb_host_interface *alts;
326 struct usb_interface *iface;
327 unsigned int ep;
328 unsigned int ifnum;
330 /* Implicit feedback sync EPs consumers are always playback EPs */
331 if (subs->direction != SNDRV_PCM_STREAM_PLAYBACK)
332 return 0;
334 switch (subs->stream->chip->usb_id) {
335 case USB_ID(0x0763, 0x2030): /* M-Audio Fast Track C400 */
336 case USB_ID(0x0763, 0x2031): /* M-Audio Fast Track C600 */
337 ep = 0x81;
338 ifnum = 3;
339 goto add_sync_ep_from_ifnum;
340 case USB_ID(0x0763, 0x2080): /* M-Audio FastTrack Ultra */
341 case USB_ID(0x0763, 0x2081):
342 ep = 0x81;
343 ifnum = 2;
344 goto add_sync_ep_from_ifnum;
345 case USB_ID(0x2466, 0x8003): /* Fractal Audio Axe-Fx II */
346 ep = 0x86;
347 ifnum = 2;
348 goto add_sync_ep_from_ifnum;
349 case USB_ID(0x2466, 0x8010): /* Fractal Audio Axe-Fx III */
350 ep = 0x81;
351 ifnum = 2;
352 goto add_sync_ep_from_ifnum;
353 case USB_ID(0x1397, 0x0001): /* Behringer UFX1604 */
354 case USB_ID(0x1397, 0x0002): /* Behringer UFX1204 */
355 ep = 0x81;
356 ifnum = 1;
357 goto add_sync_ep_from_ifnum;
358 case USB_ID(0x0582, 0x01d8): /* BOSS Katana */
359 /* BOSS Katana amplifiers do not need quirks */
360 return 0;
363 if (attr == USB_ENDPOINT_SYNC_ASYNC &&
364 altsd->bInterfaceClass == USB_CLASS_VENDOR_SPEC &&
365 altsd->bInterfaceProtocol == 2 &&
366 altsd->bNumEndpoints == 1 &&
367 USB_ID_VENDOR(subs->stream->chip->usb_id) == 0x0582 /* Roland */ &&
368 search_roland_implicit_fb(dev, altsd->bInterfaceNumber + 1,
369 altsd->bAlternateSetting,
370 &alts, &ep) >= 0) {
371 goto add_sync_ep;
374 /* No quirk */
375 return 0;
377 add_sync_ep_from_ifnum:
378 iface = usb_ifnum_to_if(dev, ifnum);
380 if (!iface || iface->num_altsetting < 2)
381 return -EINVAL;
383 alts = &iface->altsetting[1];
385 add_sync_ep:
386 subs->sync_endpoint = snd_usb_add_endpoint(subs->stream->chip,
387 alts, ep, !subs->direction,
388 SND_USB_ENDPOINT_TYPE_DATA);
389 if (!subs->sync_endpoint)
390 return -EINVAL;
392 subs->data_endpoint->sync_master = subs->sync_endpoint;
394 return 1;
397 static int set_sync_endpoint(struct snd_usb_substream *subs,
398 struct audioformat *fmt,
399 struct usb_device *dev,
400 struct usb_host_interface *alts,
401 struct usb_interface_descriptor *altsd)
403 int is_playback = subs->direction == SNDRV_PCM_STREAM_PLAYBACK;
404 unsigned int ep, attr;
405 bool implicit_fb;
406 int err;
408 /* we need a sync pipe in async OUT or adaptive IN mode */
409 /* check the number of EP, since some devices have broken
410 * descriptors which fool us. if it has only one EP,
411 * assume it as adaptive-out or sync-in.
413 attr = fmt->ep_attr & USB_ENDPOINT_SYNCTYPE;
415 if ((is_playback && (attr != USB_ENDPOINT_SYNC_ASYNC)) ||
416 (!is_playback && (attr != USB_ENDPOINT_SYNC_ADAPTIVE))) {
419 * In these modes the notion of sync_endpoint is irrelevant.
420 * Reset pointers to avoid using stale data from previously
421 * used settings, e.g. when configuration and endpoints were
422 * changed
425 subs->sync_endpoint = NULL;
426 subs->data_endpoint->sync_master = NULL;
429 err = set_sync_ep_implicit_fb_quirk(subs, dev, altsd, attr);
430 if (err < 0)
431 return err;
433 /* endpoint set by quirk */
434 if (err > 0)
435 return 0;
437 if (altsd->bNumEndpoints < 2)
438 return 0;
440 if ((is_playback && (attr == USB_ENDPOINT_SYNC_SYNC ||
441 attr == USB_ENDPOINT_SYNC_ADAPTIVE)) ||
442 (!is_playback && attr != USB_ENDPOINT_SYNC_ADAPTIVE))
443 return 0;
446 * In case of illegal SYNC_NONE for OUT endpoint, we keep going to see
447 * if we don't find a sync endpoint, as on M-Audio Transit. In case of
448 * error fall back to SYNC mode and don't create sync endpoint
451 /* check sync-pipe endpoint */
452 /* ... and check descriptor size before accessing bSynchAddress
453 because there is a version of the SB Audigy 2 NX firmware lacking
454 the audio fields in the endpoint descriptors */
455 if ((get_endpoint(alts, 1)->bmAttributes & USB_ENDPOINT_XFERTYPE_MASK) != USB_ENDPOINT_XFER_ISOC ||
456 (get_endpoint(alts, 1)->bLength >= USB_DT_ENDPOINT_AUDIO_SIZE &&
457 get_endpoint(alts, 1)->bSynchAddress != 0)) {
458 dev_err(&dev->dev,
459 "%d:%d : invalid sync pipe. bmAttributes %02x, bLength %d, bSynchAddress %02x\n",
460 fmt->iface, fmt->altsetting,
461 get_endpoint(alts, 1)->bmAttributes,
462 get_endpoint(alts, 1)->bLength,
463 get_endpoint(alts, 1)->bSynchAddress);
464 if (is_playback && attr == USB_ENDPOINT_SYNC_NONE)
465 return 0;
466 return -EINVAL;
468 ep = get_endpoint(alts, 1)->bEndpointAddress;
469 if (get_endpoint(alts, 0)->bLength >= USB_DT_ENDPOINT_AUDIO_SIZE &&
470 get_endpoint(alts, 0)->bSynchAddress != 0 &&
471 ((is_playback && ep != (unsigned int)(get_endpoint(alts, 0)->bSynchAddress | USB_DIR_IN)) ||
472 (!is_playback && ep != (unsigned int)(get_endpoint(alts, 0)->bSynchAddress & ~USB_DIR_IN)))) {
473 dev_err(&dev->dev,
474 "%d:%d : invalid sync pipe. is_playback %d, ep %02x, bSynchAddress %02x\n",
475 fmt->iface, fmt->altsetting,
476 is_playback, ep, get_endpoint(alts, 0)->bSynchAddress);
477 if (is_playback && attr == USB_ENDPOINT_SYNC_NONE)
478 return 0;
479 return -EINVAL;
482 implicit_fb = (get_endpoint(alts, 1)->bmAttributes & USB_ENDPOINT_USAGE_MASK)
483 == USB_ENDPOINT_USAGE_IMPLICIT_FB;
485 subs->sync_endpoint = snd_usb_add_endpoint(subs->stream->chip,
486 alts, ep, !subs->direction,
487 implicit_fb ?
488 SND_USB_ENDPOINT_TYPE_DATA :
489 SND_USB_ENDPOINT_TYPE_SYNC);
490 if (!subs->sync_endpoint) {
491 if (is_playback && attr == USB_ENDPOINT_SYNC_NONE)
492 return 0;
493 return -EINVAL;
496 subs->data_endpoint->sync_master = subs->sync_endpoint;
498 return 0;
502 * find a matching format and set up the interface
504 static int set_format(struct snd_usb_substream *subs, struct audioformat *fmt)
506 struct usb_device *dev = subs->dev;
507 struct usb_host_interface *alts;
508 struct usb_interface_descriptor *altsd;
509 struct usb_interface *iface;
510 int err;
512 iface = usb_ifnum_to_if(dev, fmt->iface);
513 if (WARN_ON(!iface))
514 return -EINVAL;
515 alts = usb_altnum_to_altsetting(iface, fmt->altsetting);
516 if (WARN_ON(!alts))
517 return -EINVAL;
518 altsd = get_iface_desc(alts);
520 if (fmt == subs->cur_audiofmt && !subs->need_setup_fmt)
521 return 0;
523 /* close the old interface */
524 if (subs->interface >= 0 && (subs->interface != fmt->iface || subs->need_setup_fmt)) {
525 if (!subs->stream->chip->keep_iface) {
526 err = usb_set_interface(subs->dev, subs->interface, 0);
527 if (err < 0) {
528 dev_err(&dev->dev,
529 "%d:%d: return to setting 0 failed (%d)\n",
530 fmt->iface, fmt->altsetting, err);
531 return -EIO;
534 subs->interface = -1;
535 subs->altset_idx = 0;
538 if (subs->need_setup_fmt)
539 subs->need_setup_fmt = false;
541 /* set interface */
542 if (iface->cur_altsetting != alts) {
543 err = snd_usb_select_mode_quirk(subs, fmt);
544 if (err < 0)
545 return -EIO;
547 err = usb_set_interface(dev, fmt->iface, fmt->altsetting);
548 if (err < 0) {
549 dev_err(&dev->dev,
550 "%d:%d: usb_set_interface failed (%d)\n",
551 fmt->iface, fmt->altsetting, err);
552 return -EIO;
554 dev_dbg(&dev->dev, "setting usb interface %d:%d\n",
555 fmt->iface, fmt->altsetting);
556 snd_usb_set_interface_quirk(dev);
559 subs->interface = fmt->iface;
560 subs->altset_idx = fmt->altset_idx;
561 subs->data_endpoint = snd_usb_add_endpoint(subs->stream->chip,
562 alts, fmt->endpoint, subs->direction,
563 SND_USB_ENDPOINT_TYPE_DATA);
565 if (!subs->data_endpoint)
566 return -EINVAL;
568 err = set_sync_endpoint(subs, fmt, dev, alts, altsd);
569 if (err < 0)
570 return err;
572 err = snd_usb_init_pitch(subs->stream->chip, fmt->iface, alts, fmt);
573 if (err < 0)
574 return err;
576 subs->cur_audiofmt = fmt;
578 snd_usb_set_format_quirk(subs, fmt);
580 return 0;
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.
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)
595 int i;
596 int score = 0;
598 if (fp->channels < 1) {
599 dev_dbg(&subs->dev->dev,
600 "%s: (fmt @%p) no channels\n", __func__, fp);
601 return 0;
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;
611 for (i = 0; i < fp->nr_rates; i++) {
612 if (fp->rate_table[i] == rate) {
613 score++;
614 break;
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;
624 if (fp->channels == match->channels)
625 score++;
627 dev_dbg(&subs->dev->dev,
628 "%s: (fmt @%p) score %d\n", __func__, fp, score);
630 return score;
634 * Configure the sync ep using the rate and pcm format of the data ep.
636 static int configure_sync_endpoint(struct snd_usb_substream *subs)
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];
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);
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);
663 if (score > cur_score) {
664 sync_fp = fp;
665 cur_score = score;
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;
677 * Recalculate the period bytes if channel number differ between
678 * data and sync ep audioformat.
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);
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);
697 return ret;
701 * configure endpoint params
703 * called during initial setup and upon resume
705 static int configure_endpoint(struct snd_usb_substream *subs)
707 int ret;
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;
723 if (subs->sync_endpoint)
724 ret = configure_sync_endpoint(subs);
726 return ret;
729 static int snd_usb_pcm_change_state(struct snd_usb_substream *subs, int state)
731 int ret;
733 if (!subs->str_pd)
734 return 0;
736 ret = snd_usb_power_domain_set(subs->stream->chip, subs->str_pd, state);
737 if (ret < 0) {
738 dev_err(&subs->dev->dev,
739 "Cannot change Power Domain ID: %d to state: %d. Err: %d\n",
740 subs->str_pd->pd_id, state, ret);
741 return ret;
744 return 0;
747 int snd_usb_pcm_suspend(struct snd_usb_stream *as)
749 int ret;
751 ret = snd_usb_pcm_change_state(&as->substream[0], UAC3_PD_STATE_D2);
752 if (ret < 0)
753 return ret;
755 ret = snd_usb_pcm_change_state(&as->substream[1], UAC3_PD_STATE_D2);
756 if (ret < 0)
757 return ret;
759 return 0;
762 int snd_usb_pcm_resume(struct snd_usb_stream *as)
764 int ret;
766 ret = snd_usb_pcm_change_state(&as->substream[0], UAC3_PD_STATE_D1);
767 if (ret < 0)
768 return ret;
770 ret = snd_usb_pcm_change_state(&as->substream[1], UAC3_PD_STATE_D1);
771 if (ret < 0)
772 return ret;
774 return 0;
778 * hw_params callback
780 * allocate a buffer and set the given audio format.
782 * so far we use a physically linear buffer although packetize transfer
783 * doesn't need a continuous area.
784 * if sg buffer is supported on the later version of alsa, we'll follow
785 * that.
787 static int snd_usb_hw_params(struct snd_pcm_substream *substream,
788 struct snd_pcm_hw_params *hw_params)
790 struct snd_usb_substream *subs = substream->runtime->private_data;
791 struct audioformat *fmt;
792 int ret;
794 if (snd_usb_use_vmalloc)
795 ret = snd_pcm_lib_alloc_vmalloc_buffer(substream,
796 params_buffer_bytes(hw_params));
797 else
798 ret = snd_pcm_lib_malloc_pages(substream,
799 params_buffer_bytes(hw_params));
800 if (ret < 0)
801 return ret;
803 subs->pcm_format = params_format(hw_params);
804 subs->period_bytes = params_period_bytes(hw_params);
805 subs->period_frames = params_period_size(hw_params);
806 subs->buffer_periods = params_periods(hw_params);
807 subs->channels = params_channels(hw_params);
808 subs->cur_rate = params_rate(hw_params);
810 fmt = find_format(subs);
811 if (!fmt) {
812 dev_dbg(&subs->dev->dev,
813 "cannot set format: format = %#x, rate = %d, channels = %d\n",
814 subs->pcm_format, subs->cur_rate, subs->channels);
815 return -EINVAL;
818 ret = snd_usb_lock_shutdown(subs->stream->chip);
819 if (ret < 0)
820 return ret;
822 ret = snd_usb_pcm_change_state(subs, UAC3_PD_STATE_D0);
823 if (ret < 0)
824 goto unlock;
826 ret = set_format(subs, fmt);
827 if (ret < 0)
828 goto unlock;
830 subs->interface = fmt->iface;
831 subs->altset_idx = fmt->altset_idx;
832 subs->need_setup_ep = true;
834 unlock:
835 snd_usb_unlock_shutdown(subs->stream->chip);
836 return ret;
840 * hw_free callback
842 * reset the audio format and release the buffer
844 static int snd_usb_hw_free(struct snd_pcm_substream *substream)
846 struct snd_usb_substream *subs = substream->runtime->private_data;
848 subs->cur_audiofmt = NULL;
849 subs->cur_rate = 0;
850 subs->period_bytes = 0;
851 if (!snd_usb_lock_shutdown(subs->stream->chip)) {
852 stop_endpoints(subs, true);
853 snd_usb_endpoint_deactivate(subs->sync_endpoint);
854 snd_usb_endpoint_deactivate(subs->data_endpoint);
855 snd_usb_unlock_shutdown(subs->stream->chip);
858 if (snd_usb_use_vmalloc)
859 return snd_pcm_lib_free_vmalloc_buffer(substream);
860 else
861 return snd_pcm_lib_free_pages(substream);
865 * prepare callback
867 * only a few subtle things...
869 static int snd_usb_pcm_prepare(struct snd_pcm_substream *substream)
871 struct snd_pcm_runtime *runtime = substream->runtime;
872 struct snd_usb_substream *subs = runtime->private_data;
873 struct usb_host_interface *alts;
874 struct usb_interface *iface;
875 int ret;
877 if (! subs->cur_audiofmt) {
878 dev_err(&subs->dev->dev, "no format is specified!\n");
879 return -ENXIO;
882 ret = snd_usb_lock_shutdown(subs->stream->chip);
883 if (ret < 0)
884 return ret;
885 if (snd_BUG_ON(!subs->data_endpoint)) {
886 ret = -EIO;
887 goto unlock;
890 snd_usb_endpoint_sync_pending_stop(subs->sync_endpoint);
891 snd_usb_endpoint_sync_pending_stop(subs->data_endpoint);
893 ret = snd_usb_pcm_change_state(subs, UAC3_PD_STATE_D0);
894 if (ret < 0)
895 goto unlock;
897 ret = set_format(subs, subs->cur_audiofmt);
898 if (ret < 0)
899 goto unlock;
901 if (subs->need_setup_ep) {
903 iface = usb_ifnum_to_if(subs->dev, subs->cur_audiofmt->iface);
904 alts = &iface->altsetting[subs->cur_audiofmt->altset_idx];
905 ret = snd_usb_init_sample_rate(subs->stream->chip,
906 subs->cur_audiofmt->iface,
907 alts,
908 subs->cur_audiofmt,
909 subs->cur_rate);
910 if (ret < 0)
911 goto unlock;
913 ret = configure_endpoint(subs);
914 if (ret < 0)
915 goto unlock;
916 subs->need_setup_ep = false;
919 /* some unit conversions in runtime */
920 subs->data_endpoint->maxframesize =
921 bytes_to_frames(runtime, subs->data_endpoint->maxpacksize);
922 subs->data_endpoint->curframesize =
923 bytes_to_frames(runtime, subs->data_endpoint->curpacksize);
925 /* reset the pointer */
926 subs->hwptr_done = 0;
927 subs->transfer_done = 0;
928 subs->last_delay = 0;
929 subs->last_frame_number = 0;
930 runtime->delay = 0;
932 /* for playback, submit the URBs now; otherwise, the first hwptr_done
933 * updates for all URBs would happen at the same time when starting */
934 if (subs->direction == SNDRV_PCM_STREAM_PLAYBACK)
935 ret = start_endpoints(subs);
937 unlock:
938 snd_usb_unlock_shutdown(subs->stream->chip);
939 return ret;
942 static const struct snd_pcm_hardware snd_usb_hardware =
944 .info = SNDRV_PCM_INFO_MMAP |
945 SNDRV_PCM_INFO_MMAP_VALID |
946 SNDRV_PCM_INFO_BATCH |
947 SNDRV_PCM_INFO_INTERLEAVED |
948 SNDRV_PCM_INFO_BLOCK_TRANSFER |
949 SNDRV_PCM_INFO_PAUSE,
950 .buffer_bytes_max = 1024 * 1024,
951 .period_bytes_min = 64,
952 .period_bytes_max = 512 * 1024,
953 .periods_min = 2,
954 .periods_max = 1024,
957 static int hw_check_valid_format(struct snd_usb_substream *subs,
958 struct snd_pcm_hw_params *params,
959 struct audioformat *fp)
961 struct snd_interval *it = hw_param_interval(params, SNDRV_PCM_HW_PARAM_RATE);
962 struct snd_interval *ct = hw_param_interval(params, SNDRV_PCM_HW_PARAM_CHANNELS);
963 struct snd_mask *fmts = hw_param_mask(params, SNDRV_PCM_HW_PARAM_FORMAT);
964 struct snd_interval *pt = hw_param_interval(params, SNDRV_PCM_HW_PARAM_PERIOD_TIME);
965 struct snd_mask check_fmts;
966 unsigned int ptime;
968 /* check the format */
969 snd_mask_none(&check_fmts);
970 check_fmts.bits[0] = (u32)fp->formats;
971 check_fmts.bits[1] = (u32)(fp->formats >> 32);
972 snd_mask_intersect(&check_fmts, fmts);
973 if (snd_mask_empty(&check_fmts)) {
974 hwc_debug(" > check: no supported format %d\n", fp->format);
975 return 0;
977 /* check the channels */
978 if (fp->channels < ct->min || fp->channels > ct->max) {
979 hwc_debug(" > check: no valid channels %d (%d/%d)\n", fp->channels, ct->min, ct->max);
980 return 0;
982 /* check the rate is within the range */
983 if (fp->rate_min > it->max || (fp->rate_min == it->max && it->openmax)) {
984 hwc_debug(" > check: rate_min %d > max %d\n", fp->rate_min, it->max);
985 return 0;
987 if (fp->rate_max < it->min || (fp->rate_max == it->min && it->openmin)) {
988 hwc_debug(" > check: rate_max %d < min %d\n", fp->rate_max, it->min);
989 return 0;
991 /* check whether the period time is >= the data packet interval */
992 if (subs->speed != USB_SPEED_FULL) {
993 ptime = 125 * (1 << fp->datainterval);
994 if (ptime > pt->max || (ptime == pt->max && pt->openmax)) {
995 hwc_debug(" > check: ptime %u > max %u\n", ptime, pt->max);
996 return 0;
999 return 1;
1002 static int hw_rule_rate(struct snd_pcm_hw_params *params,
1003 struct snd_pcm_hw_rule *rule)
1005 struct snd_usb_substream *subs = rule->private;
1006 struct audioformat *fp;
1007 struct snd_interval *it = hw_param_interval(params, SNDRV_PCM_HW_PARAM_RATE);
1008 unsigned int rmin, rmax;
1009 int changed;
1011 hwc_debug("hw_rule_rate: (%d,%d)\n", it->min, it->max);
1012 changed = 0;
1013 rmin = rmax = 0;
1014 list_for_each_entry(fp, &subs->fmt_list, list) {
1015 if (!hw_check_valid_format(subs, params, fp))
1016 continue;
1017 if (changed++) {
1018 if (rmin > fp->rate_min)
1019 rmin = fp->rate_min;
1020 if (rmax < fp->rate_max)
1021 rmax = fp->rate_max;
1022 } else {
1023 rmin = fp->rate_min;
1024 rmax = fp->rate_max;
1028 if (!changed) {
1029 hwc_debug(" --> get empty\n");
1030 it->empty = 1;
1031 return -EINVAL;
1034 changed = 0;
1035 if (it->min < rmin) {
1036 it->min = rmin;
1037 it->openmin = 0;
1038 changed = 1;
1040 if (it->max > rmax) {
1041 it->max = rmax;
1042 it->openmax = 0;
1043 changed = 1;
1045 if (snd_interval_checkempty(it)) {
1046 it->empty = 1;
1047 return -EINVAL;
1049 hwc_debug(" --> (%d, %d) (changed = %d)\n", it->min, it->max, changed);
1050 return changed;
1054 static int hw_rule_channels(struct snd_pcm_hw_params *params,
1055 struct snd_pcm_hw_rule *rule)
1057 struct snd_usb_substream *subs = rule->private;
1058 struct audioformat *fp;
1059 struct snd_interval *it = hw_param_interval(params, SNDRV_PCM_HW_PARAM_CHANNELS);
1060 unsigned int rmin, rmax;
1061 int changed;
1063 hwc_debug("hw_rule_channels: (%d,%d)\n", it->min, it->max);
1064 changed = 0;
1065 rmin = rmax = 0;
1066 list_for_each_entry(fp, &subs->fmt_list, list) {
1067 if (!hw_check_valid_format(subs, params, fp))
1068 continue;
1069 if (changed++) {
1070 if (rmin > fp->channels)
1071 rmin = fp->channels;
1072 if (rmax < fp->channels)
1073 rmax = fp->channels;
1074 } else {
1075 rmin = fp->channels;
1076 rmax = fp->channels;
1080 if (!changed) {
1081 hwc_debug(" --> get empty\n");
1082 it->empty = 1;
1083 return -EINVAL;
1086 changed = 0;
1087 if (it->min < rmin) {
1088 it->min = rmin;
1089 it->openmin = 0;
1090 changed = 1;
1092 if (it->max > rmax) {
1093 it->max = rmax;
1094 it->openmax = 0;
1095 changed = 1;
1097 if (snd_interval_checkempty(it)) {
1098 it->empty = 1;
1099 return -EINVAL;
1101 hwc_debug(" --> (%d, %d) (changed = %d)\n", it->min, it->max, changed);
1102 return changed;
1105 static int hw_rule_format(struct snd_pcm_hw_params *params,
1106 struct snd_pcm_hw_rule *rule)
1108 struct snd_usb_substream *subs = rule->private;
1109 struct audioformat *fp;
1110 struct snd_mask *fmt = hw_param_mask(params, SNDRV_PCM_HW_PARAM_FORMAT);
1111 u64 fbits;
1112 u32 oldbits[2];
1113 int changed;
1115 hwc_debug("hw_rule_format: %x:%x\n", fmt->bits[0], fmt->bits[1]);
1116 fbits = 0;
1117 list_for_each_entry(fp, &subs->fmt_list, list) {
1118 if (!hw_check_valid_format(subs, params, fp))
1119 continue;
1120 fbits |= fp->formats;
1123 oldbits[0] = fmt->bits[0];
1124 oldbits[1] = fmt->bits[1];
1125 fmt->bits[0] &= (u32)fbits;
1126 fmt->bits[1] &= (u32)(fbits >> 32);
1127 if (!fmt->bits[0] && !fmt->bits[1]) {
1128 hwc_debug(" --> get empty\n");
1129 return -EINVAL;
1131 changed = (oldbits[0] != fmt->bits[0] || oldbits[1] != fmt->bits[1]);
1132 hwc_debug(" --> %x:%x (changed = %d)\n", fmt->bits[0], fmt->bits[1], changed);
1133 return changed;
1136 static int hw_rule_period_time(struct snd_pcm_hw_params *params,
1137 struct snd_pcm_hw_rule *rule)
1139 struct snd_usb_substream *subs = rule->private;
1140 struct audioformat *fp;
1141 struct snd_interval *it;
1142 unsigned char min_datainterval;
1143 unsigned int pmin;
1144 int changed;
1146 it = hw_param_interval(params, SNDRV_PCM_HW_PARAM_PERIOD_TIME);
1147 hwc_debug("hw_rule_period_time: (%u,%u)\n", it->min, it->max);
1148 min_datainterval = 0xff;
1149 list_for_each_entry(fp, &subs->fmt_list, list) {
1150 if (!hw_check_valid_format(subs, params, fp))
1151 continue;
1152 min_datainterval = min(min_datainterval, fp->datainterval);
1154 if (min_datainterval == 0xff) {
1155 hwc_debug(" --> get empty\n");
1156 it->empty = 1;
1157 return -EINVAL;
1159 pmin = 125 * (1 << min_datainterval);
1160 changed = 0;
1161 if (it->min < pmin) {
1162 it->min = pmin;
1163 it->openmin = 0;
1164 changed = 1;
1166 if (snd_interval_checkempty(it)) {
1167 it->empty = 1;
1168 return -EINVAL;
1170 hwc_debug(" --> (%u,%u) (changed = %d)\n", it->min, it->max, changed);
1171 return changed;
1175 * If the device supports unusual bit rates, does the request meet these?
1177 static int snd_usb_pcm_check_knot(struct snd_pcm_runtime *runtime,
1178 struct snd_usb_substream *subs)
1180 struct audioformat *fp;
1181 int *rate_list;
1182 int count = 0, needs_knot = 0;
1183 int err;
1185 kfree(subs->rate_list.list);
1186 subs->rate_list.list = NULL;
1188 list_for_each_entry(fp, &subs->fmt_list, list) {
1189 if (fp->rates & SNDRV_PCM_RATE_CONTINUOUS)
1190 return 0;
1191 count += fp->nr_rates;
1192 if (fp->rates & SNDRV_PCM_RATE_KNOT)
1193 needs_knot = 1;
1195 if (!needs_knot)
1196 return 0;
1198 subs->rate_list.list = rate_list =
1199 kmalloc_array(count, sizeof(int), GFP_KERNEL);
1200 if (!subs->rate_list.list)
1201 return -ENOMEM;
1202 subs->rate_list.count = count;
1203 subs->rate_list.mask = 0;
1204 count = 0;
1205 list_for_each_entry(fp, &subs->fmt_list, list) {
1206 int i;
1207 for (i = 0; i < fp->nr_rates; i++)
1208 rate_list[count++] = fp->rate_table[i];
1210 err = snd_pcm_hw_constraint_list(runtime, 0, SNDRV_PCM_HW_PARAM_RATE,
1211 &subs->rate_list);
1212 if (err < 0)
1213 return err;
1215 return 0;
1220 * set up the runtime hardware information.
1223 static int setup_hw_info(struct snd_pcm_runtime *runtime, struct snd_usb_substream *subs)
1225 struct audioformat *fp;
1226 unsigned int pt, ptmin;
1227 int param_period_time_if_needed;
1228 int err;
1230 runtime->hw.formats = subs->formats;
1232 runtime->hw.rate_min = 0x7fffffff;
1233 runtime->hw.rate_max = 0;
1234 runtime->hw.channels_min = 256;
1235 runtime->hw.channels_max = 0;
1236 runtime->hw.rates = 0;
1237 ptmin = UINT_MAX;
1238 /* check min/max rates and channels */
1239 list_for_each_entry(fp, &subs->fmt_list, list) {
1240 runtime->hw.rates |= fp->rates;
1241 if (runtime->hw.rate_min > fp->rate_min)
1242 runtime->hw.rate_min = fp->rate_min;
1243 if (runtime->hw.rate_max < fp->rate_max)
1244 runtime->hw.rate_max = fp->rate_max;
1245 if (runtime->hw.channels_min > fp->channels)
1246 runtime->hw.channels_min = fp->channels;
1247 if (runtime->hw.channels_max < fp->channels)
1248 runtime->hw.channels_max = fp->channels;
1249 if (fp->fmt_type == UAC_FORMAT_TYPE_II && fp->frame_size > 0) {
1250 /* FIXME: there might be more than one audio formats... */
1251 runtime->hw.period_bytes_min = runtime->hw.period_bytes_max =
1252 fp->frame_size;
1254 pt = 125 * (1 << fp->datainterval);
1255 ptmin = min(ptmin, pt);
1258 param_period_time_if_needed = SNDRV_PCM_HW_PARAM_PERIOD_TIME;
1259 if (subs->speed == USB_SPEED_FULL)
1260 /* full speed devices have fixed data packet interval */
1261 ptmin = 1000;
1262 if (ptmin == 1000)
1263 /* if period time doesn't go below 1 ms, no rules needed */
1264 param_period_time_if_needed = -1;
1266 err = snd_pcm_hw_constraint_minmax(runtime,
1267 SNDRV_PCM_HW_PARAM_PERIOD_TIME,
1268 ptmin, UINT_MAX);
1269 if (err < 0)
1270 return err;
1272 err = snd_pcm_hw_rule_add(runtime, 0, SNDRV_PCM_HW_PARAM_RATE,
1273 hw_rule_rate, subs,
1274 SNDRV_PCM_HW_PARAM_FORMAT,
1275 SNDRV_PCM_HW_PARAM_CHANNELS,
1276 param_period_time_if_needed,
1277 -1);
1278 if (err < 0)
1279 return err;
1280 err = snd_pcm_hw_rule_add(runtime, 0, SNDRV_PCM_HW_PARAM_CHANNELS,
1281 hw_rule_channels, subs,
1282 SNDRV_PCM_HW_PARAM_FORMAT,
1283 SNDRV_PCM_HW_PARAM_RATE,
1284 param_period_time_if_needed,
1285 -1);
1286 if (err < 0)
1287 return err;
1288 err = snd_pcm_hw_rule_add(runtime, 0, SNDRV_PCM_HW_PARAM_FORMAT,
1289 hw_rule_format, subs,
1290 SNDRV_PCM_HW_PARAM_RATE,
1291 SNDRV_PCM_HW_PARAM_CHANNELS,
1292 param_period_time_if_needed,
1293 -1);
1294 if (err < 0)
1295 return err;
1296 if (param_period_time_if_needed >= 0) {
1297 err = snd_pcm_hw_rule_add(runtime, 0,
1298 SNDRV_PCM_HW_PARAM_PERIOD_TIME,
1299 hw_rule_period_time, subs,
1300 SNDRV_PCM_HW_PARAM_FORMAT,
1301 SNDRV_PCM_HW_PARAM_CHANNELS,
1302 SNDRV_PCM_HW_PARAM_RATE,
1303 -1);
1304 if (err < 0)
1305 return err;
1307 err = snd_usb_pcm_check_knot(runtime, subs);
1308 if (err < 0)
1309 return err;
1311 return snd_usb_autoresume(subs->stream->chip);
1314 static int snd_usb_pcm_open(struct snd_pcm_substream *substream)
1316 int direction = substream->stream;
1317 struct snd_usb_stream *as = snd_pcm_substream_chip(substream);
1318 struct snd_pcm_runtime *runtime = substream->runtime;
1319 struct snd_usb_substream *subs = &as->substream[direction];
1321 subs->interface = -1;
1322 subs->altset_idx = 0;
1323 runtime->hw = snd_usb_hardware;
1324 runtime->private_data = subs;
1325 subs->pcm_substream = substream;
1326 /* runtime PM is also done there */
1328 /* initialize DSD/DOP context */
1329 subs->dsd_dop.byte_idx = 0;
1330 subs->dsd_dop.channel = 0;
1331 subs->dsd_dop.marker = 1;
1333 return setup_hw_info(runtime, subs);
1336 static int snd_usb_pcm_close(struct snd_pcm_substream *substream)
1338 int direction = substream->stream;
1339 struct snd_usb_stream *as = snd_pcm_substream_chip(substream);
1340 struct snd_usb_substream *subs = &as->substream[direction];
1341 int ret;
1343 stop_endpoints(subs, true);
1345 if (!as->chip->keep_iface &&
1346 subs->interface >= 0 &&
1347 !snd_usb_lock_shutdown(subs->stream->chip)) {
1348 usb_set_interface(subs->dev, subs->interface, 0);
1349 subs->interface = -1;
1350 ret = snd_usb_pcm_change_state(subs, UAC3_PD_STATE_D1);
1351 snd_usb_unlock_shutdown(subs->stream->chip);
1352 if (ret < 0)
1353 return ret;
1356 subs->pcm_substream = NULL;
1357 snd_usb_autosuspend(subs->stream->chip);
1359 return 0;
1362 /* Since a URB can handle only a single linear buffer, we must use double
1363 * buffering when the data to be transferred overflows the buffer boundary.
1364 * To avoid inconsistencies when updating hwptr_done, we use double buffering
1365 * for all URBs.
1367 static void retire_capture_urb(struct snd_usb_substream *subs,
1368 struct urb *urb)
1370 struct snd_pcm_runtime *runtime = subs->pcm_substream->runtime;
1371 unsigned int stride, frames, bytes, oldptr;
1372 int i, period_elapsed = 0;
1373 unsigned long flags;
1374 unsigned char *cp;
1375 int current_frame_number;
1377 /* read frame number here, update pointer in critical section */
1378 current_frame_number = usb_get_current_frame_number(subs->dev);
1380 stride = runtime->frame_bits >> 3;
1382 for (i = 0; i < urb->number_of_packets; i++) {
1383 cp = (unsigned char *)urb->transfer_buffer + urb->iso_frame_desc[i].offset + subs->pkt_offset_adj;
1384 if (urb->iso_frame_desc[i].status && printk_ratelimit()) {
1385 dev_dbg(&subs->dev->dev, "frame %d active: %d\n",
1386 i, urb->iso_frame_desc[i].status);
1387 // continue;
1389 bytes = urb->iso_frame_desc[i].actual_length;
1390 frames = bytes / stride;
1391 if (!subs->txfr_quirk)
1392 bytes = frames * stride;
1393 if (bytes % (runtime->sample_bits >> 3) != 0) {
1394 int oldbytes = bytes;
1395 bytes = frames * stride;
1396 dev_warn_ratelimited(&subs->dev->dev,
1397 "Corrected urb data len. %d->%d\n",
1398 oldbytes, bytes);
1400 /* update the current pointer */
1401 spin_lock_irqsave(&subs->lock, flags);
1402 oldptr = subs->hwptr_done;
1403 subs->hwptr_done += bytes;
1404 if (subs->hwptr_done >= runtime->buffer_size * stride)
1405 subs->hwptr_done -= runtime->buffer_size * stride;
1406 frames = (bytes + (oldptr % stride)) / stride;
1407 subs->transfer_done += frames;
1408 if (subs->transfer_done >= runtime->period_size) {
1409 subs->transfer_done -= runtime->period_size;
1410 period_elapsed = 1;
1412 /* capture delay is by construction limited to one URB,
1413 * reset delays here
1415 runtime->delay = subs->last_delay = 0;
1417 /* realign last_frame_number */
1418 subs->last_frame_number = current_frame_number;
1419 subs->last_frame_number &= 0xFF; /* keep 8 LSBs */
1421 spin_unlock_irqrestore(&subs->lock, flags);
1422 /* copy a data chunk */
1423 if (oldptr + bytes > runtime->buffer_size * stride) {
1424 unsigned int bytes1 =
1425 runtime->buffer_size * stride - oldptr;
1426 memcpy(runtime->dma_area + oldptr, cp, bytes1);
1427 memcpy(runtime->dma_area, cp + bytes1, bytes - bytes1);
1428 } else {
1429 memcpy(runtime->dma_area + oldptr, cp, bytes);
1433 if (period_elapsed)
1434 snd_pcm_period_elapsed(subs->pcm_substream);
1437 static inline void fill_playback_urb_dsd_dop(struct snd_usb_substream *subs,
1438 struct urb *urb, unsigned int bytes)
1440 struct snd_pcm_runtime *runtime = subs->pcm_substream->runtime;
1441 unsigned int stride = runtime->frame_bits >> 3;
1442 unsigned int dst_idx = 0;
1443 unsigned int src_idx = subs->hwptr_done;
1444 unsigned int wrap = runtime->buffer_size * stride;
1445 u8 *dst = urb->transfer_buffer;
1446 u8 *src = runtime->dma_area;
1447 u8 marker[] = { 0x05, 0xfa };
1450 * The DSP DOP format defines a way to transport DSD samples over
1451 * normal PCM data endpoints. It requires stuffing of marker bytes
1452 * (0x05 and 0xfa, alternating per sample frame), and then expects
1453 * 2 additional bytes of actual payload. The whole frame is stored
1454 * LSB.
1456 * Hence, for a stereo transport, the buffer layout looks like this,
1457 * where L refers to left channel samples and R to right.
1459 * L1 L2 0x05 R1 R2 0x05 L3 L4 0xfa R3 R4 0xfa
1460 * L5 L6 0x05 R5 R6 0x05 L7 L8 0xfa R7 R8 0xfa
1461 * .....
1465 while (bytes--) {
1466 if (++subs->dsd_dop.byte_idx == 3) {
1467 /* frame boundary? */
1468 dst[dst_idx++] = marker[subs->dsd_dop.marker];
1469 src_idx += 2;
1470 subs->dsd_dop.byte_idx = 0;
1472 if (++subs->dsd_dop.channel % runtime->channels == 0) {
1473 /* alternate the marker */
1474 subs->dsd_dop.marker++;
1475 subs->dsd_dop.marker %= ARRAY_SIZE(marker);
1476 subs->dsd_dop.channel = 0;
1478 } else {
1479 /* stuff the DSD payload */
1480 int idx = (src_idx + subs->dsd_dop.byte_idx - 1) % wrap;
1482 if (subs->cur_audiofmt->dsd_bitrev)
1483 dst[dst_idx++] = bitrev8(src[idx]);
1484 else
1485 dst[dst_idx++] = src[idx];
1487 subs->hwptr_done++;
1490 if (subs->hwptr_done >= runtime->buffer_size * stride)
1491 subs->hwptr_done -= runtime->buffer_size * stride;
1494 static void copy_to_urb(struct snd_usb_substream *subs, struct urb *urb,
1495 int offset, int stride, unsigned int bytes)
1497 struct snd_pcm_runtime *runtime = subs->pcm_substream->runtime;
1499 if (subs->hwptr_done + bytes > runtime->buffer_size * stride) {
1500 /* err, the transferred area goes over buffer boundary. */
1501 unsigned int bytes1 =
1502 runtime->buffer_size * stride - subs->hwptr_done;
1503 memcpy(urb->transfer_buffer + offset,
1504 runtime->dma_area + subs->hwptr_done, bytes1);
1505 memcpy(urb->transfer_buffer + offset + bytes1,
1506 runtime->dma_area, bytes - bytes1);
1507 } else {
1508 memcpy(urb->transfer_buffer + offset,
1509 runtime->dma_area + subs->hwptr_done, bytes);
1511 subs->hwptr_done += bytes;
1512 if (subs->hwptr_done >= runtime->buffer_size * stride)
1513 subs->hwptr_done -= runtime->buffer_size * stride;
1516 static unsigned int copy_to_urb_quirk(struct snd_usb_substream *subs,
1517 struct urb *urb, int stride,
1518 unsigned int bytes)
1520 __le32 packet_length;
1521 int i;
1523 /* Put __le32 length descriptor at start of each packet. */
1524 for (i = 0; i < urb->number_of_packets; i++) {
1525 unsigned int length = urb->iso_frame_desc[i].length;
1526 unsigned int offset = urb->iso_frame_desc[i].offset;
1528 packet_length = cpu_to_le32(length);
1529 offset += i * sizeof(packet_length);
1530 urb->iso_frame_desc[i].offset = offset;
1531 urb->iso_frame_desc[i].length += sizeof(packet_length);
1532 memcpy(urb->transfer_buffer + offset,
1533 &packet_length, sizeof(packet_length));
1534 copy_to_urb(subs, urb, offset + sizeof(packet_length),
1535 stride, length);
1537 /* Adjust transfer size accordingly. */
1538 bytes += urb->number_of_packets * sizeof(packet_length);
1539 return bytes;
1542 static void prepare_playback_urb(struct snd_usb_substream *subs,
1543 struct urb *urb)
1545 struct snd_pcm_runtime *runtime = subs->pcm_substream->runtime;
1546 struct snd_usb_endpoint *ep = subs->data_endpoint;
1547 struct snd_urb_ctx *ctx = urb->context;
1548 unsigned int counts, frames, bytes;
1549 int i, stride, period_elapsed = 0;
1550 unsigned long flags;
1552 stride = runtime->frame_bits >> 3;
1554 frames = 0;
1555 urb->number_of_packets = 0;
1556 spin_lock_irqsave(&subs->lock, flags);
1557 subs->frame_limit += ep->max_urb_frames;
1558 for (i = 0; i < ctx->packets; i++) {
1559 if (ctx->packet_size[i])
1560 counts = ctx->packet_size[i];
1561 else
1562 counts = snd_usb_endpoint_next_packet_size(ep);
1564 /* set up descriptor */
1565 urb->iso_frame_desc[i].offset = frames * ep->stride;
1566 urb->iso_frame_desc[i].length = counts * ep->stride;
1567 frames += counts;
1568 urb->number_of_packets++;
1569 subs->transfer_done += counts;
1570 if (subs->transfer_done >= runtime->period_size) {
1571 subs->transfer_done -= runtime->period_size;
1572 subs->frame_limit = 0;
1573 period_elapsed = 1;
1574 if (subs->fmt_type == UAC_FORMAT_TYPE_II) {
1575 if (subs->transfer_done > 0) {
1576 /* FIXME: fill-max mode is not
1577 * supported yet */
1578 frames -= subs->transfer_done;
1579 counts -= subs->transfer_done;
1580 urb->iso_frame_desc[i].length =
1581 counts * ep->stride;
1582 subs->transfer_done = 0;
1584 i++;
1585 if (i < ctx->packets) {
1586 /* add a transfer delimiter */
1587 urb->iso_frame_desc[i].offset =
1588 frames * ep->stride;
1589 urb->iso_frame_desc[i].length = 0;
1590 urb->number_of_packets++;
1592 break;
1595 /* finish at the period boundary or after enough frames */
1596 if ((period_elapsed ||
1597 subs->transfer_done >= subs->frame_limit) &&
1598 !snd_usb_endpoint_implicit_feedback_sink(ep))
1599 break;
1601 bytes = frames * ep->stride;
1603 if (unlikely(subs->pcm_format == SNDRV_PCM_FORMAT_DSD_U16_LE &&
1604 subs->cur_audiofmt->dsd_dop)) {
1605 fill_playback_urb_dsd_dop(subs, urb, bytes);
1606 } else if (unlikely(subs->pcm_format == SNDRV_PCM_FORMAT_DSD_U8 &&
1607 subs->cur_audiofmt->dsd_bitrev)) {
1608 /* bit-reverse the bytes */
1609 u8 *buf = urb->transfer_buffer;
1610 for (i = 0; i < bytes; i++) {
1611 int idx = (subs->hwptr_done + i)
1612 % (runtime->buffer_size * stride);
1613 buf[i] = bitrev8(runtime->dma_area[idx]);
1616 subs->hwptr_done += bytes;
1617 if (subs->hwptr_done >= runtime->buffer_size * stride)
1618 subs->hwptr_done -= runtime->buffer_size * stride;
1619 } else {
1620 /* usual PCM */
1621 if (!subs->tx_length_quirk)
1622 copy_to_urb(subs, urb, 0, stride, bytes);
1623 else
1624 bytes = copy_to_urb_quirk(subs, urb, stride, bytes);
1625 /* bytes is now amount of outgoing data */
1628 /* update delay with exact number of samples queued */
1629 runtime->delay = subs->last_delay;
1630 runtime->delay += frames;
1631 subs->last_delay = runtime->delay;
1633 /* realign last_frame_number */
1634 subs->last_frame_number = usb_get_current_frame_number(subs->dev);
1635 subs->last_frame_number &= 0xFF; /* keep 8 LSBs */
1637 if (subs->trigger_tstamp_pending_update) {
1638 /* this is the first actual URB submitted,
1639 * update trigger timestamp to reflect actual start time
1641 snd_pcm_gettime(runtime, &runtime->trigger_tstamp);
1642 subs->trigger_tstamp_pending_update = false;
1645 spin_unlock_irqrestore(&subs->lock, flags);
1646 urb->transfer_buffer_length = bytes;
1647 if (period_elapsed)
1648 snd_pcm_period_elapsed(subs->pcm_substream);
1652 * process after playback data complete
1653 * - decrease the delay count again
1655 static void retire_playback_urb(struct snd_usb_substream *subs,
1656 struct urb *urb)
1658 unsigned long flags;
1659 struct snd_pcm_runtime *runtime = subs->pcm_substream->runtime;
1660 struct snd_usb_endpoint *ep = subs->data_endpoint;
1661 int processed = urb->transfer_buffer_length / ep->stride;
1662 int est_delay;
1664 /* ignore the delay accounting when procssed=0 is given, i.e.
1665 * silent payloads are procssed before handling the actual data
1667 if (!processed)
1668 return;
1670 spin_lock_irqsave(&subs->lock, flags);
1671 if (!subs->last_delay)
1672 goto out; /* short path */
1674 est_delay = snd_usb_pcm_delay(subs, runtime->rate);
1675 /* update delay with exact number of samples played */
1676 if (processed > subs->last_delay)
1677 subs->last_delay = 0;
1678 else
1679 subs->last_delay -= processed;
1680 runtime->delay = subs->last_delay;
1683 * Report when delay estimate is off by more than 2ms.
1684 * The error should be lower than 2ms since the estimate relies
1685 * on two reads of a counter updated every ms.
1687 if (abs(est_delay - subs->last_delay) * 1000 > runtime->rate * 2)
1688 dev_dbg_ratelimited(&subs->dev->dev,
1689 "delay: estimated %d, actual %d\n",
1690 est_delay, subs->last_delay);
1692 if (!subs->running) {
1693 /* update last_frame_number for delay counting here since
1694 * prepare_playback_urb won't be called during pause
1696 subs->last_frame_number =
1697 usb_get_current_frame_number(subs->dev) & 0xff;
1700 out:
1701 spin_unlock_irqrestore(&subs->lock, flags);
1704 static int snd_usb_substream_playback_trigger(struct snd_pcm_substream *substream,
1705 int cmd)
1707 struct snd_usb_substream *subs = substream->runtime->private_data;
1709 switch (cmd) {
1710 case SNDRV_PCM_TRIGGER_START:
1711 subs->trigger_tstamp_pending_update = true;
1712 /* fall through */
1713 case SNDRV_PCM_TRIGGER_PAUSE_RELEASE:
1714 subs->data_endpoint->prepare_data_urb = prepare_playback_urb;
1715 subs->data_endpoint->retire_data_urb = retire_playback_urb;
1716 subs->running = 1;
1717 return 0;
1718 case SNDRV_PCM_TRIGGER_STOP:
1719 stop_endpoints(subs, false);
1720 subs->running = 0;
1721 return 0;
1722 case SNDRV_PCM_TRIGGER_PAUSE_PUSH:
1723 subs->data_endpoint->prepare_data_urb = NULL;
1724 /* keep retire_data_urb for delay calculation */
1725 subs->data_endpoint->retire_data_urb = retire_playback_urb;
1726 subs->running = 0;
1727 return 0;
1728 case SNDRV_PCM_TRIGGER_SUSPEND:
1729 if (subs->stream->chip->setup_fmt_after_resume_quirk) {
1730 stop_endpoints(subs, true);
1731 subs->need_setup_fmt = true;
1732 return 0;
1734 break;
1737 return -EINVAL;
1740 static int snd_usb_substream_capture_trigger(struct snd_pcm_substream *substream,
1741 int cmd)
1743 int err;
1744 struct snd_usb_substream *subs = substream->runtime->private_data;
1746 switch (cmd) {
1747 case SNDRV_PCM_TRIGGER_START:
1748 err = start_endpoints(subs);
1749 if (err < 0)
1750 return err;
1752 subs->data_endpoint->retire_data_urb = retire_capture_urb;
1753 subs->running = 1;
1754 return 0;
1755 case SNDRV_PCM_TRIGGER_STOP:
1756 stop_endpoints(subs, false);
1757 subs->running = 0;
1758 return 0;
1759 case SNDRV_PCM_TRIGGER_PAUSE_PUSH:
1760 subs->data_endpoint->retire_data_urb = NULL;
1761 subs->running = 0;
1762 return 0;
1763 case SNDRV_PCM_TRIGGER_PAUSE_RELEASE:
1764 subs->data_endpoint->retire_data_urb = retire_capture_urb;
1765 subs->running = 1;
1766 return 0;
1767 case SNDRV_PCM_TRIGGER_SUSPEND:
1768 if (subs->stream->chip->setup_fmt_after_resume_quirk) {
1769 stop_endpoints(subs, true);
1770 subs->need_setup_fmt = true;
1771 return 0;
1773 break;
1776 return -EINVAL;
1779 static const struct snd_pcm_ops snd_usb_playback_ops = {
1780 .open = snd_usb_pcm_open,
1781 .close = snd_usb_pcm_close,
1782 .ioctl = snd_pcm_lib_ioctl,
1783 .hw_params = snd_usb_hw_params,
1784 .hw_free = snd_usb_hw_free,
1785 .prepare = snd_usb_pcm_prepare,
1786 .trigger = snd_usb_substream_playback_trigger,
1787 .pointer = snd_usb_pcm_pointer,
1788 .page = snd_pcm_lib_get_vmalloc_page,
1791 static const struct snd_pcm_ops snd_usb_capture_ops = {
1792 .open = snd_usb_pcm_open,
1793 .close = snd_usb_pcm_close,
1794 .ioctl = snd_pcm_lib_ioctl,
1795 .hw_params = snd_usb_hw_params,
1796 .hw_free = snd_usb_hw_free,
1797 .prepare = snd_usb_pcm_prepare,
1798 .trigger = snd_usb_substream_capture_trigger,
1799 .pointer = snd_usb_pcm_pointer,
1800 .page = snd_pcm_lib_get_vmalloc_page,
1803 static const struct snd_pcm_ops snd_usb_playback_dev_ops = {
1804 .open = snd_usb_pcm_open,
1805 .close = snd_usb_pcm_close,
1806 .ioctl = snd_pcm_lib_ioctl,
1807 .hw_params = snd_usb_hw_params,
1808 .hw_free = snd_usb_hw_free,
1809 .prepare = snd_usb_pcm_prepare,
1810 .trigger = snd_usb_substream_playback_trigger,
1811 .pointer = snd_usb_pcm_pointer,
1812 .page = snd_pcm_sgbuf_ops_page,
1815 static const struct snd_pcm_ops snd_usb_capture_dev_ops = {
1816 .open = snd_usb_pcm_open,
1817 .close = snd_usb_pcm_close,
1818 .ioctl = snd_pcm_lib_ioctl,
1819 .hw_params = snd_usb_hw_params,
1820 .hw_free = snd_usb_hw_free,
1821 .prepare = snd_usb_pcm_prepare,
1822 .trigger = snd_usb_substream_capture_trigger,
1823 .pointer = snd_usb_pcm_pointer,
1824 .page = snd_pcm_sgbuf_ops_page,
1827 void snd_usb_set_pcm_ops(struct snd_pcm *pcm, int stream)
1829 const struct snd_pcm_ops *ops;
1831 if (snd_usb_use_vmalloc)
1832 ops = stream == SNDRV_PCM_STREAM_PLAYBACK ?
1833 &snd_usb_playback_ops : &snd_usb_capture_ops;
1834 else
1835 ops = stream == SNDRV_PCM_STREAM_PLAYBACK ?
1836 &snd_usb_playback_dev_ops : &snd_usb_capture_dev_ops;
1837 snd_pcm_set_ops(pcm, stream, ops);
1840 void snd_usb_preallocate_buffer(struct snd_usb_substream *subs)
1842 struct snd_pcm *pcm = subs->stream->pcm;
1843 struct snd_pcm_substream *s = pcm->streams[subs->direction].substream;
1844 struct device *dev = subs->dev->bus->controller;
1846 if (!snd_usb_use_vmalloc)
1847 snd_pcm_lib_preallocate_pages(s, SNDRV_DMA_TYPE_DEV_SG,
1848 dev, 64*1024, 512*1024);