ALSA: Make snd_printd() and snd_printdd() inline
[firefly-linux-kernel-4.4.55.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 list_head *p;
98         struct audioformat *found = NULL;
99         int cur_attr = 0, attr;
100
101         list_for_each(p, &subs->fmt_list) {
102                 struct audioformat *fp;
103                 fp = list_entry(p, struct audioformat, list);
104                 if (!(fp->formats & (1uLL << subs->pcm_format)))
105                         continue;
106                 if (fp->channels != subs->channels)
107                         continue;
108                 if (subs->cur_rate < fp->rate_min ||
109                     subs->cur_rate > fp->rate_max)
110                         continue;
111                 if (! (fp->rates & SNDRV_PCM_RATE_CONTINUOUS)) {
112                         unsigned int i;
113                         for (i = 0; i < fp->nr_rates; i++)
114                                 if (fp->rate_table[i] == subs->cur_rate)
115                                         break;
116                         if (i >= fp->nr_rates)
117                                 continue;
118                 }
119                 attr = fp->ep_attr & USB_ENDPOINT_SYNCTYPE;
120                 if (! found) {
121                         found = fp;
122                         cur_attr = attr;
123                         continue;
124                 }
125                 /* avoid async out and adaptive in if the other method
126                  * supports the same format.
127                  * this is a workaround for the case like
128                  * M-audio audiophile USB.
129                  */
130                 if (attr != cur_attr) {
131                         if ((attr == USB_ENDPOINT_SYNC_ASYNC &&
132                              subs->direction == SNDRV_PCM_STREAM_PLAYBACK) ||
133                             (attr == USB_ENDPOINT_SYNC_ADAPTIVE &&
134                              subs->direction == SNDRV_PCM_STREAM_CAPTURE))
135                                 continue;
136                         if ((cur_attr == USB_ENDPOINT_SYNC_ASYNC &&
137                              subs->direction == SNDRV_PCM_STREAM_PLAYBACK) ||
138                             (cur_attr == USB_ENDPOINT_SYNC_ADAPTIVE &&
139                              subs->direction == SNDRV_PCM_STREAM_CAPTURE)) {
140                                 found = fp;
141                                 cur_attr = attr;
142                                 continue;
143                         }
144                 }
145                 /* find the format with the largest max. packet size */
146                 if (fp->maxpacksize > found->maxpacksize) {
147                         found = fp;
148                         cur_attr = attr;
149                 }
150         }
151         return found;
152 }
153
154 static int init_pitch_v1(struct snd_usb_audio *chip, int iface,
155                          struct usb_host_interface *alts,
156                          struct audioformat *fmt)
157 {
158         struct usb_device *dev = chip->dev;
159         unsigned int ep;
160         unsigned char data[1];
161         int err;
162
163         ep = get_endpoint(alts, 0)->bEndpointAddress;
164
165         data[0] = 1;
166         if ((err = snd_usb_ctl_msg(dev, usb_sndctrlpipe(dev, 0), UAC_SET_CUR,
167                                    USB_TYPE_CLASS|USB_RECIP_ENDPOINT|USB_DIR_OUT,
168                                    UAC_EP_CS_ATTR_PITCH_CONTROL << 8, ep,
169                                    data, sizeof(data))) < 0) {
170                 snd_printk(KERN_ERR "%d:%d:%d: cannot set enable PITCH\n",
171                            dev->devnum, iface, ep);
172                 return err;
173         }
174
175         return 0;
176 }
177
178 static int init_pitch_v2(struct snd_usb_audio *chip, int iface,
179                          struct usb_host_interface *alts,
180                          struct audioformat *fmt)
181 {
182         struct usb_device *dev = chip->dev;
183         unsigned char data[1];
184         int err;
185
186         data[0] = 1;
187         if ((err = snd_usb_ctl_msg(dev, usb_sndctrlpipe(dev, 0), UAC2_CS_CUR,
188                                    USB_TYPE_CLASS | USB_RECIP_ENDPOINT | USB_DIR_OUT,
189                                    UAC2_EP_CS_PITCH << 8, 0,
190                                    data, sizeof(data))) < 0) {
191                 snd_printk(KERN_ERR "%d:%d:%d: cannot set enable PITCH (v2)\n",
192                            dev->devnum, iface, fmt->altsetting);
193                 return err;
194         }
195
196         return 0;
197 }
198
199 /*
200  * initialize the pitch control and sample rate
201  */
202 int snd_usb_init_pitch(struct snd_usb_audio *chip, int iface,
203                        struct usb_host_interface *alts,
204                        struct audioformat *fmt)
205 {
206         struct usb_interface_descriptor *altsd = get_iface_desc(alts);
207
208         /* if endpoint doesn't have pitch control, bail out */
209         if (!(fmt->attributes & UAC_EP_CS_ATTR_PITCH_CONTROL))
210                 return 0;
211
212         switch (altsd->bInterfaceProtocol) {
213         case UAC_VERSION_1:
214         default:
215                 return init_pitch_v1(chip, iface, alts, fmt);
216
217         case UAC_VERSION_2:
218                 return init_pitch_v2(chip, iface, alts, fmt);
219         }
220 }
221
222 static int start_endpoints(struct snd_usb_substream *subs, bool can_sleep)
223 {
224         int err;
225
226         if (!subs->data_endpoint)
227                 return -EINVAL;
228
229         if (!test_and_set_bit(SUBSTREAM_FLAG_DATA_EP_STARTED, &subs->flags)) {
230                 struct snd_usb_endpoint *ep = subs->data_endpoint;
231
232                 snd_printdd(KERN_DEBUG "Starting data EP @%p\n", ep);
233
234                 ep->data_subs = subs;
235                 err = snd_usb_endpoint_start(ep, can_sleep);
236                 if (err < 0) {
237                         clear_bit(SUBSTREAM_FLAG_DATA_EP_STARTED, &subs->flags);
238                         return err;
239                 }
240         }
241
242         if (subs->sync_endpoint &&
243             !test_and_set_bit(SUBSTREAM_FLAG_SYNC_EP_STARTED, &subs->flags)) {
244                 struct snd_usb_endpoint *ep = subs->sync_endpoint;
245
246                 if (subs->data_endpoint->iface != subs->sync_endpoint->iface ||
247                     subs->data_endpoint->alt_idx != subs->sync_endpoint->alt_idx) {
248                         err = usb_set_interface(subs->dev,
249                                                 subs->sync_endpoint->iface,
250                                                 subs->sync_endpoint->alt_idx);
251                         if (err < 0) {
252                                 snd_printk(KERN_ERR
253                                            "%d:%d:%d: cannot set interface (%d)\n",
254                                            subs->dev->devnum,
255                                            subs->sync_endpoint->iface,
256                                            subs->sync_endpoint->alt_idx, err);
257                                 return -EIO;
258                         }
259                 }
260
261                 snd_printdd(KERN_DEBUG "Starting sync EP @%p\n", ep);
262
263                 ep->sync_slave = subs->data_endpoint;
264                 err = snd_usb_endpoint_start(ep, can_sleep);
265                 if (err < 0) {
266                         clear_bit(SUBSTREAM_FLAG_SYNC_EP_STARTED, &subs->flags);
267                         return err;
268                 }
269         }
270
271         return 0;
272 }
273
274 static void stop_endpoints(struct snd_usb_substream *subs, bool wait)
275 {
276         if (test_and_clear_bit(SUBSTREAM_FLAG_SYNC_EP_STARTED, &subs->flags))
277                 snd_usb_endpoint_stop(subs->sync_endpoint);
278
279         if (test_and_clear_bit(SUBSTREAM_FLAG_DATA_EP_STARTED, &subs->flags))
280                 snd_usb_endpoint_stop(subs->data_endpoint);
281
282         if (wait) {
283                 snd_usb_endpoint_sync_pending_stop(subs->sync_endpoint);
284                 snd_usb_endpoint_sync_pending_stop(subs->data_endpoint);
285         }
286 }
287
288 static int deactivate_endpoints(struct snd_usb_substream *subs)
289 {
290         int reta, retb;
291
292         reta = snd_usb_endpoint_deactivate(subs->sync_endpoint);
293         retb = snd_usb_endpoint_deactivate(subs->data_endpoint);
294
295         if (reta < 0)
296                 return reta;
297
298         if (retb < 0)
299                 return retb;
300
301         return 0;
302 }
303
304 /*
305  * find a matching format and set up the interface
306  */
307 static int set_format(struct snd_usb_substream *subs, struct audioformat *fmt)
308 {
309         struct usb_device *dev = subs->dev;
310         struct usb_host_interface *alts;
311         struct usb_interface_descriptor *altsd;
312         struct usb_interface *iface;
313         unsigned int ep, attr;
314         int is_playback = subs->direction == SNDRV_PCM_STREAM_PLAYBACK;
315         int err, implicit_fb = 0;
316
317         iface = usb_ifnum_to_if(dev, fmt->iface);
318         if (WARN_ON(!iface))
319                 return -EINVAL;
320         alts = &iface->altsetting[fmt->altset_idx];
321         altsd = get_iface_desc(alts);
322         if (WARN_ON(altsd->bAlternateSetting != fmt->altsetting))
323                 return -EINVAL;
324
325         if (fmt == subs->cur_audiofmt)
326                 return 0;
327
328         /* close the old interface */
329         if (subs->interface >= 0 && subs->interface != fmt->iface) {
330                 err = usb_set_interface(subs->dev, subs->interface, 0);
331                 if (err < 0) {
332                         snd_printk(KERN_ERR "%d:%d:%d: return to setting 0 failed (%d)\n",
333                                 dev->devnum, fmt->iface, fmt->altsetting, err);
334                         return -EIO;
335                 }
336                 subs->interface = -1;
337                 subs->altset_idx = 0;
338         }
339
340         /* set interface */
341         if (subs->interface != fmt->iface ||
342             subs->altset_idx != fmt->altset_idx) {
343                 err = usb_set_interface(dev, fmt->iface, fmt->altsetting);
344                 if (err < 0) {
345                         snd_printk(KERN_ERR "%d:%d:%d: usb_set_interface failed (%d)\n",
346                                    dev->devnum, fmt->iface, fmt->altsetting, err);
347                         return -EIO;
348                 }
349                 snd_printdd(KERN_INFO "setting usb interface %d:%d\n",
350                                 fmt->iface, fmt->altsetting);
351                 subs->interface = fmt->iface;
352                 subs->altset_idx = fmt->altset_idx;
353         }
354
355         subs->data_endpoint = snd_usb_add_endpoint(subs->stream->chip,
356                                                    alts, fmt->endpoint, subs->direction,
357                                                    SND_USB_ENDPOINT_TYPE_DATA);
358         if (!subs->data_endpoint)
359                 return -EINVAL;
360
361         /* we need a sync pipe in async OUT or adaptive IN mode */
362         /* check the number of EP, since some devices have broken
363          * descriptors which fool us.  if it has only one EP,
364          * assume it as adaptive-out or sync-in.
365          */
366         attr = fmt->ep_attr & USB_ENDPOINT_SYNCTYPE;
367
368         switch (subs->stream->chip->usb_id) {
369         case USB_ID(0x0763, 0x2030): /* M-Audio Fast Track C400 */
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 & (1ULL << 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 list_head *p;
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(p, &subs->fmt_list) {
813                 struct audioformat *fp;
814                 fp = list_entry(p, struct audioformat, list);
815                 if (!hw_check_valid_format(subs, params, fp))
816                         continue;
817                 if (changed++) {
818                         if (rmin > fp->rate_min)
819                                 rmin = fp->rate_min;
820                         if (rmax < fp->rate_max)
821                                 rmax = fp->rate_max;
822                 } else {
823                         rmin = fp->rate_min;
824                         rmax = fp->rate_max;
825                 }
826         }
827
828         if (!changed) {
829                 hwc_debug("  --> get empty\n");
830                 it->empty = 1;
831                 return -EINVAL;
832         }
833
834         changed = 0;
835         if (it->min < rmin) {
836                 it->min = rmin;
837                 it->openmin = 0;
838                 changed = 1;
839         }
840         if (it->max > rmax) {
841                 it->max = rmax;
842                 it->openmax = 0;
843                 changed = 1;
844         }
845         if (snd_interval_checkempty(it)) {
846                 it->empty = 1;
847                 return -EINVAL;
848         }
849         hwc_debug("  --> (%d, %d) (changed = %d)\n", it->min, it->max, changed);
850         return changed;
851 }
852
853
854 static int hw_rule_channels(struct snd_pcm_hw_params *params,
855                             struct snd_pcm_hw_rule *rule)
856 {
857         struct snd_usb_substream *subs = rule->private;
858         struct list_head *p;
859         struct snd_interval *it = hw_param_interval(params, SNDRV_PCM_HW_PARAM_CHANNELS);
860         unsigned int rmin, rmax;
861         int changed;
862
863         hwc_debug("hw_rule_channels: (%d,%d)\n", it->min, it->max);
864         changed = 0;
865         rmin = rmax = 0;
866         list_for_each(p, &subs->fmt_list) {
867                 struct audioformat *fp;
868                 fp = list_entry(p, struct audioformat, list);
869                 if (!hw_check_valid_format(subs, params, fp))
870                         continue;
871                 if (changed++) {
872                         if (rmin > fp->channels)
873                                 rmin = fp->channels;
874                         if (rmax < fp->channels)
875                                 rmax = fp->channels;
876                 } else {
877                         rmin = fp->channels;
878                         rmax = fp->channels;
879                 }
880         }
881
882         if (!changed) {
883                 hwc_debug("  --> get empty\n");
884                 it->empty = 1;
885                 return -EINVAL;
886         }
887
888         changed = 0;
889         if (it->min < rmin) {
890                 it->min = rmin;
891                 it->openmin = 0;
892                 changed = 1;
893         }
894         if (it->max > rmax) {
895                 it->max = rmax;
896                 it->openmax = 0;
897                 changed = 1;
898         }
899         if (snd_interval_checkempty(it)) {
900                 it->empty = 1;
901                 return -EINVAL;
902         }
903         hwc_debug("  --> (%d, %d) (changed = %d)\n", it->min, it->max, changed);
904         return changed;
905 }
906
907 static int hw_rule_format(struct snd_pcm_hw_params *params,
908                           struct snd_pcm_hw_rule *rule)
909 {
910         struct snd_usb_substream *subs = rule->private;
911         struct list_head *p;
912         struct snd_mask *fmt = hw_param_mask(params, SNDRV_PCM_HW_PARAM_FORMAT);
913         u64 fbits;
914         u32 oldbits[2];
915         int changed;
916
917         hwc_debug("hw_rule_format: %x:%x\n", fmt->bits[0], fmt->bits[1]);
918         fbits = 0;
919         list_for_each(p, &subs->fmt_list) {
920                 struct audioformat *fp;
921                 fp = list_entry(p, struct audioformat, 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 list_head *p;
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(p, &subs->fmt_list) {
1044                 struct audioformat *fp;
1045                 fp = list_entry(p, struct audioformat, list);
1046                 runtime->hw.rates |= fp->rates;
1047                 if (runtime->hw.rate_min > fp->rate_min)
1048                         runtime->hw.rate_min = fp->rate_min;
1049                 if (runtime->hw.rate_max < fp->rate_max)
1050                         runtime->hw.rate_max = fp->rate_max;
1051                 if (runtime->hw.channels_min > fp->channels)
1052                         runtime->hw.channels_min = fp->channels;
1053                 if (runtime->hw.channels_max < fp->channels)
1054                         runtime->hw.channels_max = fp->channels;
1055                 if (fp->fmt_type == UAC_FORMAT_TYPE_II && fp->frame_size > 0) {
1056                         /* FIXME: there might be more than one audio formats... */
1057                         runtime->hw.period_bytes_min = runtime->hw.period_bytes_max =
1058                                 fp->frame_size;
1059                 }
1060                 pt = 125 * (1 << fp->datainterval);
1061                 ptmin = min(ptmin, pt);
1062         }
1063         err = snd_usb_autoresume(subs->stream->chip);
1064         if (err < 0)
1065                 return err;
1066
1067         param_period_time_if_needed = SNDRV_PCM_HW_PARAM_PERIOD_TIME;
1068         if (subs->speed == USB_SPEED_FULL)
1069                 /* full speed devices have fixed data packet interval */
1070                 ptmin = 1000;
1071         if (ptmin == 1000)
1072                 /* if period time doesn't go below 1 ms, no rules needed */
1073                 param_period_time_if_needed = -1;
1074         snd_pcm_hw_constraint_minmax(runtime, SNDRV_PCM_HW_PARAM_PERIOD_TIME,
1075                                      ptmin, UINT_MAX);
1076
1077         if ((err = snd_pcm_hw_rule_add(runtime, 0, SNDRV_PCM_HW_PARAM_RATE,
1078                                        hw_rule_rate, subs,
1079                                        SNDRV_PCM_HW_PARAM_FORMAT,
1080                                        SNDRV_PCM_HW_PARAM_CHANNELS,
1081                                        param_period_time_if_needed,
1082                                        -1)) < 0)
1083                 goto rep_err;
1084         if ((err = snd_pcm_hw_rule_add(runtime, 0, SNDRV_PCM_HW_PARAM_CHANNELS,
1085                                        hw_rule_channels, subs,
1086                                        SNDRV_PCM_HW_PARAM_FORMAT,
1087                                        SNDRV_PCM_HW_PARAM_RATE,
1088                                        param_period_time_if_needed,
1089                                        -1)) < 0)
1090                 goto rep_err;
1091         if ((err = snd_pcm_hw_rule_add(runtime, 0, SNDRV_PCM_HW_PARAM_FORMAT,
1092                                        hw_rule_format, subs,
1093                                        SNDRV_PCM_HW_PARAM_RATE,
1094                                        SNDRV_PCM_HW_PARAM_CHANNELS,
1095                                        param_period_time_if_needed,
1096                                        -1)) < 0)
1097                 goto rep_err;
1098         if (param_period_time_if_needed >= 0) {
1099                 err = snd_pcm_hw_rule_add(runtime, 0,
1100                                           SNDRV_PCM_HW_PARAM_PERIOD_TIME,
1101                                           hw_rule_period_time, subs,
1102                                           SNDRV_PCM_HW_PARAM_FORMAT,
1103                                           SNDRV_PCM_HW_PARAM_CHANNELS,
1104                                           SNDRV_PCM_HW_PARAM_RATE,
1105                                           -1);
1106                 if (err < 0)
1107                         goto rep_err;
1108         }
1109         if ((err = snd_usb_pcm_check_knot(runtime, subs)) < 0)
1110                 goto rep_err;
1111         return 0;
1112
1113 rep_err:
1114         snd_usb_autosuspend(subs->stream->chip);
1115         return err;
1116 }
1117
1118 static int snd_usb_pcm_open(struct snd_pcm_substream *substream, int direction)
1119 {
1120         struct snd_usb_stream *as = snd_pcm_substream_chip(substream);
1121         struct snd_pcm_runtime *runtime = substream->runtime;
1122         struct snd_usb_substream *subs = &as->substream[direction];
1123
1124         subs->interface = -1;
1125         subs->altset_idx = 0;
1126         runtime->hw = snd_usb_hardware;
1127         runtime->private_data = subs;
1128         subs->pcm_substream = substream;
1129         /* runtime PM is also done there */
1130         return setup_hw_info(runtime, subs);
1131 }
1132
1133 static int snd_usb_pcm_close(struct snd_pcm_substream *substream, int direction)
1134 {
1135         struct snd_usb_stream *as = snd_pcm_substream_chip(substream);
1136         struct snd_usb_substream *subs = &as->substream[direction];
1137
1138         stop_endpoints(subs, true);
1139
1140         if (!as->chip->shutdown && subs->interface >= 0) {
1141                 usb_set_interface(subs->dev, subs->interface, 0);
1142                 subs->interface = -1;
1143         }
1144
1145         subs->pcm_substream = NULL;
1146         snd_usb_autosuspend(subs->stream->chip);
1147
1148         return 0;
1149 }
1150
1151 /* Since a URB can handle only a single linear buffer, we must use double
1152  * buffering when the data to be transferred overflows the buffer boundary.
1153  * To avoid inconsistencies when updating hwptr_done, we use double buffering
1154  * for all URBs.
1155  */
1156 static void retire_capture_urb(struct snd_usb_substream *subs,
1157                                struct urb *urb)
1158 {
1159         struct snd_pcm_runtime *runtime = subs->pcm_substream->runtime;
1160         unsigned int stride, frames, bytes, oldptr;
1161         int i, period_elapsed = 0;
1162         unsigned long flags;
1163         unsigned char *cp;
1164         int current_frame_number;
1165
1166         /* read frame number here, update pointer in critical section */
1167         current_frame_number = usb_get_current_frame_number(subs->dev);
1168
1169         stride = runtime->frame_bits >> 3;
1170
1171         for (i = 0; i < urb->number_of_packets; i++) {
1172                 cp = (unsigned char *)urb->transfer_buffer + urb->iso_frame_desc[i].offset;
1173                 if (urb->iso_frame_desc[i].status && printk_ratelimit()) {
1174                         snd_printdd(KERN_ERR "frame %d active: %d\n", i, urb->iso_frame_desc[i].status);
1175                         // continue;
1176                 }
1177                 bytes = urb->iso_frame_desc[i].actual_length;
1178                 frames = bytes / stride;
1179                 if (!subs->txfr_quirk)
1180                         bytes = frames * stride;
1181                 if (bytes % (runtime->sample_bits >> 3) != 0) {
1182                         int oldbytes = bytes;
1183                         bytes = frames * stride;
1184                         snd_printdd(KERN_ERR "Corrected urb data len. %d->%d\n",
1185                                                         oldbytes, bytes);
1186                 }
1187                 /* update the current pointer */
1188                 spin_lock_irqsave(&subs->lock, flags);
1189                 oldptr = subs->hwptr_done;
1190                 subs->hwptr_done += bytes;
1191                 if (subs->hwptr_done >= runtime->buffer_size * stride)
1192                         subs->hwptr_done -= runtime->buffer_size * stride;
1193                 frames = (bytes + (oldptr % stride)) / stride;
1194                 subs->transfer_done += frames;
1195                 if (subs->transfer_done >= runtime->period_size) {
1196                         subs->transfer_done -= runtime->period_size;
1197                         period_elapsed = 1;
1198                 }
1199                 /* capture delay is by construction limited to one URB,
1200                  * reset delays here
1201                  */
1202                 runtime->delay = subs->last_delay = 0;
1203
1204                 /* realign last_frame_number */
1205                 subs->last_frame_number = current_frame_number;
1206                 subs->last_frame_number &= 0xFF; /* keep 8 LSBs */
1207
1208                 spin_unlock_irqrestore(&subs->lock, flags);
1209                 /* copy a data chunk */
1210                 if (oldptr + bytes > runtime->buffer_size * stride) {
1211                         unsigned int bytes1 =
1212                                         runtime->buffer_size * stride - oldptr;
1213                         memcpy(runtime->dma_area + oldptr, cp, bytes1);
1214                         memcpy(runtime->dma_area, cp + bytes1, bytes - bytes1);
1215                 } else {
1216                         memcpy(runtime->dma_area + oldptr, cp, bytes);
1217                 }
1218         }
1219
1220         if (period_elapsed)
1221                 snd_pcm_period_elapsed(subs->pcm_substream);
1222 }
1223
1224 static void prepare_playback_urb(struct snd_usb_substream *subs,
1225                                  struct urb *urb)
1226 {
1227         struct snd_pcm_runtime *runtime = subs->pcm_substream->runtime;
1228         struct snd_usb_endpoint *ep = subs->data_endpoint;
1229         struct snd_urb_ctx *ctx = urb->context;
1230         unsigned int counts, frames, bytes;
1231         int i, stride, period_elapsed = 0;
1232         unsigned long flags;
1233
1234         stride = runtime->frame_bits >> 3;
1235
1236         frames = 0;
1237         urb->number_of_packets = 0;
1238         spin_lock_irqsave(&subs->lock, flags);
1239         for (i = 0; i < ctx->packets; i++) {
1240                 if (ctx->packet_size[i])
1241                         counts = ctx->packet_size[i];
1242                 else
1243                         counts = snd_usb_endpoint_next_packet_size(ep);
1244
1245                 /* set up descriptor */
1246                 urb->iso_frame_desc[i].offset = frames * stride;
1247                 urb->iso_frame_desc[i].length = counts * stride;
1248                 frames += counts;
1249                 urb->number_of_packets++;
1250                 subs->transfer_done += counts;
1251                 if (subs->transfer_done >= runtime->period_size) {
1252                         subs->transfer_done -= runtime->period_size;
1253                         period_elapsed = 1;
1254                         if (subs->fmt_type == UAC_FORMAT_TYPE_II) {
1255                                 if (subs->transfer_done > 0) {
1256                                         /* FIXME: fill-max mode is not
1257                                          * supported yet */
1258                                         frames -= subs->transfer_done;
1259                                         counts -= subs->transfer_done;
1260                                         urb->iso_frame_desc[i].length =
1261                                                 counts * stride;
1262                                         subs->transfer_done = 0;
1263                                 }
1264                                 i++;
1265                                 if (i < ctx->packets) {
1266                                         /* add a transfer delimiter */
1267                                         urb->iso_frame_desc[i].offset =
1268                                                 frames * stride;
1269                                         urb->iso_frame_desc[i].length = 0;
1270                                         urb->number_of_packets++;
1271                                 }
1272                                 break;
1273                         }
1274                 }
1275                 if (period_elapsed &&
1276                     !snd_usb_endpoint_implict_feedback_sink(subs->data_endpoint)) /* finish at the period boundary */
1277                         break;
1278         }
1279         bytes = frames * stride;
1280         if (subs->hwptr_done + bytes > runtime->buffer_size * stride) {
1281                 /* err, the transferred area goes over buffer boundary. */
1282                 unsigned int bytes1 =
1283                         runtime->buffer_size * stride - subs->hwptr_done;
1284                 memcpy(urb->transfer_buffer,
1285                        runtime->dma_area + subs->hwptr_done, bytes1);
1286                 memcpy(urb->transfer_buffer + bytes1,
1287                        runtime->dma_area, bytes - bytes1);
1288         } else {
1289                 memcpy(urb->transfer_buffer,
1290                        runtime->dma_area + subs->hwptr_done, bytes);
1291         }
1292         subs->hwptr_done += bytes;
1293         if (subs->hwptr_done >= runtime->buffer_size * stride)
1294                 subs->hwptr_done -= runtime->buffer_size * stride;
1295
1296         /* update delay with exact number of samples queued */
1297         runtime->delay = subs->last_delay;
1298         runtime->delay += frames;
1299         subs->last_delay = runtime->delay;
1300
1301         /* realign last_frame_number */
1302         subs->last_frame_number = usb_get_current_frame_number(subs->dev);
1303         subs->last_frame_number &= 0xFF; /* keep 8 LSBs */
1304
1305         spin_unlock_irqrestore(&subs->lock, flags);
1306         urb->transfer_buffer_length = bytes;
1307         if (period_elapsed)
1308                 snd_pcm_period_elapsed(subs->pcm_substream);
1309 }
1310
1311 /*
1312  * process after playback data complete
1313  * - decrease the delay count again
1314  */
1315 static void retire_playback_urb(struct snd_usb_substream *subs,
1316                                struct urb *urb)
1317 {
1318         unsigned long flags;
1319         struct snd_pcm_runtime *runtime = subs->pcm_substream->runtime;
1320         int stride = runtime->frame_bits >> 3;
1321         int processed = urb->transfer_buffer_length / stride;
1322         int est_delay;
1323
1324         /* ignore the delay accounting when procssed=0 is given, i.e.
1325          * silent payloads are procssed before handling the actual data
1326          */
1327         if (!processed)
1328                 return;
1329
1330         spin_lock_irqsave(&subs->lock, flags);
1331         if (!subs->last_delay)
1332                 goto out; /* short path */
1333
1334         est_delay = snd_usb_pcm_delay(subs, runtime->rate);
1335         /* update delay with exact number of samples played */
1336         if (processed > subs->last_delay)
1337                 subs->last_delay = 0;
1338         else
1339                 subs->last_delay -= processed;
1340         runtime->delay = subs->last_delay;
1341
1342         /*
1343          * Report when delay estimate is off by more than 2ms.
1344          * The error should be lower than 2ms since the estimate relies
1345          * on two reads of a counter updated every ms.
1346          */
1347         if (abs(est_delay - subs->last_delay) * 1000 > runtime->rate * 2)
1348                 snd_printk(KERN_DEBUG "delay: estimated %d, actual %d\n",
1349                         est_delay, subs->last_delay);
1350
1351         if (!subs->running) {
1352                 /* update last_frame_number for delay counting here since
1353                  * prepare_playback_urb won't be called during pause
1354                  */
1355                 subs->last_frame_number =
1356                         usb_get_current_frame_number(subs->dev) & 0xff;
1357         }
1358
1359  out:
1360         spin_unlock_irqrestore(&subs->lock, flags);
1361 }
1362
1363 static int snd_usb_playback_open(struct snd_pcm_substream *substream)
1364 {
1365         return snd_usb_pcm_open(substream, SNDRV_PCM_STREAM_PLAYBACK);
1366 }
1367
1368 static int snd_usb_playback_close(struct snd_pcm_substream *substream)
1369 {
1370         return snd_usb_pcm_close(substream, SNDRV_PCM_STREAM_PLAYBACK);
1371 }
1372
1373 static int snd_usb_capture_open(struct snd_pcm_substream *substream)
1374 {
1375         return snd_usb_pcm_open(substream, SNDRV_PCM_STREAM_CAPTURE);
1376 }
1377
1378 static int snd_usb_capture_close(struct snd_pcm_substream *substream)
1379 {
1380         return snd_usb_pcm_close(substream, SNDRV_PCM_STREAM_CAPTURE);
1381 }
1382
1383 static int snd_usb_substream_playback_trigger(struct snd_pcm_substream *substream,
1384                                               int cmd)
1385 {
1386         struct snd_usb_substream *subs = substream->runtime->private_data;
1387
1388         switch (cmd) {
1389         case SNDRV_PCM_TRIGGER_START:
1390         case SNDRV_PCM_TRIGGER_PAUSE_RELEASE:
1391                 subs->data_endpoint->prepare_data_urb = prepare_playback_urb;
1392                 subs->data_endpoint->retire_data_urb = retire_playback_urb;
1393                 subs->running = 1;
1394                 return 0;
1395         case SNDRV_PCM_TRIGGER_STOP:
1396                 stop_endpoints(subs, false);
1397                 subs->running = 0;
1398                 return 0;
1399         case SNDRV_PCM_TRIGGER_PAUSE_PUSH:
1400                 subs->data_endpoint->prepare_data_urb = NULL;
1401                 /* keep retire_data_urb for delay calculation */
1402                 subs->data_endpoint->retire_data_urb = retire_playback_urb;
1403                 subs->running = 0;
1404                 return 0;
1405         }
1406
1407         return -EINVAL;
1408 }
1409
1410 static int snd_usb_substream_capture_trigger(struct snd_pcm_substream *substream,
1411                                              int cmd)
1412 {
1413         int err;
1414         struct snd_usb_substream *subs = substream->runtime->private_data;
1415
1416         switch (cmd) {
1417         case SNDRV_PCM_TRIGGER_START:
1418                 err = start_endpoints(subs, false);
1419                 if (err < 0)
1420                         return err;
1421
1422                 subs->data_endpoint->retire_data_urb = retire_capture_urb;
1423                 subs->running = 1;
1424                 return 0;
1425         case SNDRV_PCM_TRIGGER_STOP:
1426                 stop_endpoints(subs, false);
1427                 subs->running = 0;
1428                 return 0;
1429         case SNDRV_PCM_TRIGGER_PAUSE_PUSH:
1430                 subs->data_endpoint->retire_data_urb = NULL;
1431                 subs->running = 0;
1432                 return 0;
1433         case SNDRV_PCM_TRIGGER_PAUSE_RELEASE:
1434                 subs->data_endpoint->retire_data_urb = retire_capture_urb;
1435                 subs->running = 1;
1436                 return 0;
1437         }
1438
1439         return -EINVAL;
1440 }
1441
1442 static struct snd_pcm_ops snd_usb_playback_ops = {
1443         .open =         snd_usb_playback_open,
1444         .close =        snd_usb_playback_close,
1445         .ioctl =        snd_pcm_lib_ioctl,
1446         .hw_params =    snd_usb_hw_params,
1447         .hw_free =      snd_usb_hw_free,
1448         .prepare =      snd_usb_pcm_prepare,
1449         .trigger =      snd_usb_substream_playback_trigger,
1450         .pointer =      snd_usb_pcm_pointer,
1451         .page =         snd_pcm_lib_get_vmalloc_page,
1452         .mmap =         snd_pcm_lib_mmap_vmalloc,
1453 };
1454
1455 static struct snd_pcm_ops snd_usb_capture_ops = {
1456         .open =         snd_usb_capture_open,
1457         .close =        snd_usb_capture_close,
1458         .ioctl =        snd_pcm_lib_ioctl,
1459         .hw_params =    snd_usb_hw_params,
1460         .hw_free =      snd_usb_hw_free,
1461         .prepare =      snd_usb_pcm_prepare,
1462         .trigger =      snd_usb_substream_capture_trigger,
1463         .pointer =      snd_usb_pcm_pointer,
1464         .page =         snd_pcm_lib_get_vmalloc_page,
1465         .mmap =         snd_pcm_lib_mmap_vmalloc,
1466 };
1467
1468 void snd_usb_set_pcm_ops(struct snd_pcm *pcm, int stream)
1469 {
1470         snd_pcm_set_ops(pcm, stream,
1471                         stream == SNDRV_PCM_STREAM_PLAYBACK ?
1472                         &snd_usb_playback_ops : &snd_usb_capture_ops);
1473 }