OSDN Git Service

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