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