Merge branch 'drm-intel-fixes' of git://people.freedesktop.org/~danvet/drm-intel...
[platform/adaptation/renesas_rcar/renesas_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         current_frame_number = usb_get_current_frame_number(subs->dev);
50         /*
51          * HCD implementations use different widths, use lower 8 bits.
52          * The delay will be managed up to 256ms, which is more than
53          * enough
54          */
55         frame_diff = (current_frame_number - subs->last_frame_number) & 0xff;
56
57         /* Approximation based on number of samples per USB frame (ms),
58            some truncation for 44.1 but the estimate is good enough */
59         est_delay =  subs->last_delay - (frame_diff * rate / 1000);
60         if (est_delay < 0)
61                 est_delay = 0;
62         return est_delay;
63 }
64
65 /*
66  * return the current pcm pointer.  just based on the hwptr_done value.
67  */
68 static snd_pcm_uframes_t snd_usb_pcm_pointer(struct snd_pcm_substream *substream)
69 {
70         struct snd_usb_substream *subs;
71         unsigned int hwptr_done;
72
73         subs = (struct snd_usb_substream *)substream->runtime->private_data;
74         spin_lock(&subs->lock);
75         hwptr_done = subs->hwptr_done;
76         substream->runtime->delay = snd_usb_pcm_delay(subs,
77                                                 substream->runtime->rate);
78         spin_unlock(&subs->lock);
79         return hwptr_done / (substream->runtime->frame_bits >> 3);
80 }
81
82 /*
83  * find a matching audio format
84  */
85 static struct audioformat *find_format(struct snd_usb_substream *subs, unsigned int format,
86                                        unsigned int rate, unsigned int channels)
87 {
88         struct list_head *p;
89         struct audioformat *found = NULL;
90         int cur_attr = 0, attr;
91
92         list_for_each(p, &subs->fmt_list) {
93                 struct audioformat *fp;
94                 fp = list_entry(p, struct audioformat, list);
95                 if (!(fp->formats & (1uLL << format)))
96                         continue;
97                 if (fp->channels != channels)
98                         continue;
99                 if (rate < fp->rate_min || rate > fp->rate_max)
100                         continue;
101                 if (! (fp->rates & SNDRV_PCM_RATE_CONTINUOUS)) {
102                         unsigned int i;
103                         for (i = 0; i < fp->nr_rates; i++)
104                                 if (fp->rate_table[i] == rate)
105                                         break;
106                         if (i >= fp->nr_rates)
107                                 continue;
108                 }
109                 attr = fp->ep_attr & USB_ENDPOINT_SYNCTYPE;
110                 if (! found) {
111                         found = fp;
112                         cur_attr = attr;
113                         continue;
114                 }
115                 /* avoid async out and adaptive in if the other method
116                  * supports the same format.
117                  * this is a workaround for the case like
118                  * M-audio audiophile USB.
119                  */
120                 if (attr != cur_attr) {
121                         if ((attr == USB_ENDPOINT_SYNC_ASYNC &&
122                              subs->direction == SNDRV_PCM_STREAM_PLAYBACK) ||
123                             (attr == USB_ENDPOINT_SYNC_ADAPTIVE &&
124                              subs->direction == SNDRV_PCM_STREAM_CAPTURE))
125                                 continue;
126                         if ((cur_attr == USB_ENDPOINT_SYNC_ASYNC &&
127                              subs->direction == SNDRV_PCM_STREAM_PLAYBACK) ||
128                             (cur_attr == USB_ENDPOINT_SYNC_ADAPTIVE &&
129                              subs->direction == SNDRV_PCM_STREAM_CAPTURE)) {
130                                 found = fp;
131                                 cur_attr = attr;
132                                 continue;
133                         }
134                 }
135                 /* find the format with the largest max. packet size */
136                 if (fp->maxpacksize > found->maxpacksize) {
137                         found = fp;
138                         cur_attr = attr;
139                 }
140         }
141         return found;
142 }
143
144 static int init_pitch_v1(struct snd_usb_audio *chip, int iface,
145                          struct usb_host_interface *alts,
146                          struct audioformat *fmt)
147 {
148         struct usb_device *dev = chip->dev;
149         unsigned int ep;
150         unsigned char data[1];
151         int err;
152
153         ep = get_endpoint(alts, 0)->bEndpointAddress;
154
155         data[0] = 1;
156         if ((err = snd_usb_ctl_msg(dev, usb_sndctrlpipe(dev, 0), UAC_SET_CUR,
157                                    USB_TYPE_CLASS|USB_RECIP_ENDPOINT|USB_DIR_OUT,
158                                    UAC_EP_CS_ATTR_PITCH_CONTROL << 8, ep,
159                                    data, sizeof(data))) < 0) {
160                 snd_printk(KERN_ERR "%d:%d:%d: cannot set enable PITCH\n",
161                            dev->devnum, iface, ep);
162                 return err;
163         }
164
165         return 0;
166 }
167
168 static int init_pitch_v2(struct snd_usb_audio *chip, int iface,
169                          struct usb_host_interface *alts,
170                          struct audioformat *fmt)
171 {
172         struct usb_device *dev = chip->dev;
173         unsigned char data[1];
174         unsigned int ep;
175         int err;
176
177         ep = get_endpoint(alts, 0)->bEndpointAddress;
178
179         data[0] = 1;
180         if ((err = snd_usb_ctl_msg(dev, usb_sndctrlpipe(dev, 0), UAC2_CS_CUR,
181                                    USB_TYPE_CLASS | USB_RECIP_ENDPOINT | USB_DIR_OUT,
182                                    UAC2_EP_CS_PITCH << 8, 0,
183                                    data, sizeof(data))) < 0) {
184                 snd_printk(KERN_ERR "%d:%d:%d: cannot set enable PITCH (v2)\n",
185                            dev->devnum, iface, fmt->altsetting);
186                 return err;
187         }
188
189         return 0;
190 }
191
192 /*
193  * initialize the pitch control and sample rate
194  */
195 int snd_usb_init_pitch(struct snd_usb_audio *chip, int iface,
196                        struct usb_host_interface *alts,
197                        struct audioformat *fmt)
198 {
199         struct usb_interface_descriptor *altsd = get_iface_desc(alts);
200
201         /* if endpoint doesn't have pitch control, bail out */
202         if (!(fmt->attributes & UAC_EP_CS_ATTR_PITCH_CONTROL))
203                 return 0;
204
205         switch (altsd->bInterfaceProtocol) {
206         case UAC_VERSION_1:
207         default:
208                 return init_pitch_v1(chip, iface, alts, fmt);
209
210         case UAC_VERSION_2:
211                 return init_pitch_v2(chip, iface, alts, fmt);
212         }
213 }
214
215 static int start_endpoints(struct snd_usb_substream *subs)
216 {
217         int err;
218
219         if (!subs->data_endpoint)
220                 return -EINVAL;
221
222         if (!test_and_set_bit(SUBSTREAM_FLAG_DATA_EP_STARTED, &subs->flags)) {
223                 struct snd_usb_endpoint *ep = subs->data_endpoint;
224
225                 snd_printdd(KERN_DEBUG "Starting data EP @%p\n", ep);
226
227                 ep->data_subs = subs;
228                 err = snd_usb_endpoint_start(ep);
229                 if (err < 0) {
230                         clear_bit(SUBSTREAM_FLAG_DATA_EP_STARTED, &subs->flags);
231                         return err;
232                 }
233         }
234
235         if (subs->sync_endpoint &&
236             !test_and_set_bit(SUBSTREAM_FLAG_SYNC_EP_STARTED, &subs->flags)) {
237                 struct snd_usb_endpoint *ep = subs->sync_endpoint;
238
239                 snd_printdd(KERN_DEBUG "Starting sync EP @%p\n", ep);
240
241                 ep->sync_slave = subs->data_endpoint;
242                 err = snd_usb_endpoint_start(ep);
243                 if (err < 0) {
244                         clear_bit(SUBSTREAM_FLAG_SYNC_EP_STARTED, &subs->flags);
245                         return err;
246                 }
247         }
248
249         return 0;
250 }
251
252 static void stop_endpoints(struct snd_usb_substream *subs,
253                            int force, int can_sleep, int wait)
254 {
255         if (test_and_clear_bit(SUBSTREAM_FLAG_SYNC_EP_STARTED, &subs->flags))
256                 snd_usb_endpoint_stop(subs->sync_endpoint,
257                                       force, can_sleep, wait);
258
259         if (test_and_clear_bit(SUBSTREAM_FLAG_DATA_EP_STARTED, &subs->flags))
260                 snd_usb_endpoint_stop(subs->data_endpoint,
261                                       force, can_sleep, wait);
262 }
263
264 static int activate_endpoints(struct snd_usb_substream *subs)
265 {
266         if (subs->sync_endpoint) {
267                 int ret;
268
269                 ret = snd_usb_endpoint_activate(subs->sync_endpoint);
270                 if (ret < 0)
271                         return ret;
272         }
273
274         return snd_usb_endpoint_activate(subs->data_endpoint);
275 }
276
277 static int deactivate_endpoints(struct snd_usb_substream *subs)
278 {
279         int reta, retb;
280
281         reta = snd_usb_endpoint_deactivate(subs->sync_endpoint);
282         retb = snd_usb_endpoint_deactivate(subs->data_endpoint);
283
284         if (reta < 0)
285                 return reta;
286
287         if (retb < 0)
288                 return retb;
289
290         return 0;
291 }
292
293 /*
294  * find a matching format and set up the interface
295  */
296 static int set_format(struct snd_usb_substream *subs, struct audioformat *fmt)
297 {
298         struct usb_device *dev = subs->dev;
299         struct usb_host_interface *alts;
300         struct usb_interface_descriptor *altsd;
301         struct usb_interface *iface;
302         unsigned int ep, attr;
303         int is_playback = subs->direction == SNDRV_PCM_STREAM_PLAYBACK;
304         int err, implicit_fb = 0;
305
306         iface = usb_ifnum_to_if(dev, fmt->iface);
307         if (WARN_ON(!iface))
308                 return -EINVAL;
309         alts = &iface->altsetting[fmt->altset_idx];
310         altsd = get_iface_desc(alts);
311         if (WARN_ON(altsd->bAlternateSetting != fmt->altsetting))
312                 return -EINVAL;
313
314         if (fmt == subs->cur_audiofmt)
315                 return 0;
316
317         subs->data_endpoint = snd_usb_add_endpoint(subs->stream->chip,
318                                                    alts, fmt->endpoint, subs->direction,
319                                                    SND_USB_ENDPOINT_TYPE_DATA);
320         if (!subs->data_endpoint)
321                 return -EINVAL;
322
323         /* we need a sync pipe in async OUT or adaptive IN mode */
324         /* check the number of EP, since some devices have broken
325          * descriptors which fool us.  if it has only one EP,
326          * assume it as adaptive-out or sync-in.
327          */
328         attr = fmt->ep_attr & USB_ENDPOINT_SYNCTYPE;
329
330         switch (subs->stream->chip->usb_id) {
331         case USB_ID(0x0763, 0x2080): /* M-Audio FastTrack Ultra */
332         case USB_ID(0x0763, 0x2081):
333                 if (is_playback) {
334                         implicit_fb = 1;
335                         ep = 0x81;
336                         iface = usb_ifnum_to_if(dev, 2);
337
338                         if (!iface || iface->num_altsetting == 0)
339                                 return -EINVAL;
340
341                         alts = &iface->altsetting[1];
342                         goto add_sync_ep;
343                 }
344         }
345
346         if (((is_playback && attr == USB_ENDPOINT_SYNC_ASYNC) ||
347              (!is_playback && attr == USB_ENDPOINT_SYNC_ADAPTIVE)) &&
348             altsd->bNumEndpoints >= 2) {
349                 /* check sync-pipe endpoint */
350                 /* ... and check descriptor size before accessing bSynchAddress
351                    because there is a version of the SB Audigy 2 NX firmware lacking
352                    the audio fields in the endpoint descriptors */
353                 if ((get_endpoint(alts, 1)->bmAttributes & USB_ENDPOINT_XFERTYPE_MASK) != 0x01 ||
354                     (get_endpoint(alts, 1)->bLength >= USB_DT_ENDPOINT_AUDIO_SIZE &&
355                      get_endpoint(alts, 1)->bSynchAddress != 0 &&
356                      !implicit_fb)) {
357                         snd_printk(KERN_ERR "%d:%d:%d : invalid synch pipe\n",
358                                    dev->devnum, fmt->iface, fmt->altsetting);
359                         return -EINVAL;
360                 }
361                 ep = get_endpoint(alts, 1)->bEndpointAddress;
362                 if (get_endpoint(alts, 0)->bLength >= USB_DT_ENDPOINT_AUDIO_SIZE &&
363                     (( is_playback && ep != (unsigned int)(get_endpoint(alts, 0)->bSynchAddress | USB_DIR_IN)) ||
364                      (!is_playback && ep != (unsigned int)(get_endpoint(alts, 0)->bSynchAddress & ~USB_DIR_IN)) ||
365                      ( is_playback && !implicit_fb))) {
366                         snd_printk(KERN_ERR "%d:%d:%d : invalid synch pipe\n",
367                                    dev->devnum, fmt->iface, fmt->altsetting);
368                         return -EINVAL;
369                 }
370
371                 implicit_fb = (get_endpoint(alts, 1)->bmAttributes & USB_ENDPOINT_USAGE_MASK)
372                                 == USB_ENDPOINT_USAGE_IMPLICIT_FB;
373
374 add_sync_ep:
375                 subs->sync_endpoint = snd_usb_add_endpoint(subs->stream->chip,
376                                                            alts, ep, !subs->direction,
377                                                            implicit_fb ?
378                                                                 SND_USB_ENDPOINT_TYPE_DATA :
379                                                                 SND_USB_ENDPOINT_TYPE_SYNC);
380                 if (!subs->sync_endpoint)
381                         return -EINVAL;
382
383                 subs->data_endpoint->sync_master = subs->sync_endpoint;
384         }
385
386         if ((err = snd_usb_init_pitch(subs->stream->chip, subs->interface, alts, fmt)) < 0)
387                 return err;
388
389         subs->cur_audiofmt = fmt;
390
391         snd_usb_set_format_quirk(subs, fmt);
392
393 #if 0
394         printk(KERN_DEBUG
395                "setting done: format = %d, rate = %d..%d, channels = %d\n",
396                fmt->format, fmt->rate_min, fmt->rate_max, fmt->channels);
397         printk(KERN_DEBUG
398                "  datapipe = 0x%0x, syncpipe = 0x%0x\n",
399                subs->datapipe, subs->syncpipe);
400 #endif
401
402         return 0;
403 }
404
405 /*
406  * hw_params callback
407  *
408  * allocate a buffer and set the given audio format.
409  *
410  * so far we use a physically linear buffer although packetize transfer
411  * doesn't need a continuous area.
412  * if sg buffer is supported on the later version of alsa, we'll follow
413  * that.
414  */
415 static int snd_usb_hw_params(struct snd_pcm_substream *substream,
416                              struct snd_pcm_hw_params *hw_params)
417 {
418         struct snd_usb_substream *subs = substream->runtime->private_data;
419         struct audioformat *fmt;
420         unsigned int channels, rate, format;
421         int ret, changed;
422
423         ret = snd_pcm_lib_alloc_vmalloc_buffer(substream,
424                                                params_buffer_bytes(hw_params));
425         if (ret < 0)
426                 return ret;
427
428         format = params_format(hw_params);
429         rate = params_rate(hw_params);
430         channels = params_channels(hw_params);
431         fmt = find_format(subs, format, rate, channels);
432         if (!fmt) {
433                 snd_printd(KERN_DEBUG "cannot set format: format = %#x, rate = %d, channels = %d\n",
434                            format, rate, channels);
435                 return -EINVAL;
436         }
437
438         changed = subs->cur_audiofmt != fmt ||
439                 subs->period_bytes != params_period_bytes(hw_params) ||
440                 subs->cur_rate != rate;
441         if ((ret = set_format(subs, fmt)) < 0)
442                 return ret;
443
444         if (subs->cur_rate != rate) {
445                 struct usb_host_interface *alts;
446                 struct usb_interface *iface;
447                 iface = usb_ifnum_to_if(subs->dev, fmt->iface);
448                 alts = &iface->altsetting[fmt->altset_idx];
449                 ret = snd_usb_init_sample_rate(subs->stream->chip, subs->interface, alts, fmt, rate);
450                 if (ret < 0)
451                         return ret;
452                 subs->cur_rate = rate;
453         }
454
455         if (changed) {
456                 mutex_lock(&subs->stream->chip->shutdown_mutex);
457                 /* format changed */
458                 stop_endpoints(subs, 0, 0, 0);
459                 deactivate_endpoints(subs);
460
461                 ret = activate_endpoints(subs);
462                 if (ret < 0)
463                         goto unlock;
464
465                 ret = snd_usb_endpoint_set_params(subs->data_endpoint, hw_params, fmt,
466                                                   subs->sync_endpoint);
467                 if (ret < 0)
468                         goto unlock;
469
470                 if (subs->sync_endpoint)
471                         ret = snd_usb_endpoint_set_params(subs->sync_endpoint,
472                                                           hw_params, fmt, NULL);
473 unlock:
474                 mutex_unlock(&subs->stream->chip->shutdown_mutex);
475         }
476
477         if (ret == 0) {
478                 subs->interface = fmt->iface;
479                 subs->altset_idx = fmt->altset_idx;
480         }
481
482         return ret;
483 }
484
485 /*
486  * hw_free callback
487  *
488  * reset the audio format and release the buffer
489  */
490 static int snd_usb_hw_free(struct snd_pcm_substream *substream)
491 {
492         struct snd_usb_substream *subs = substream->runtime->private_data;
493
494         subs->cur_audiofmt = NULL;
495         subs->cur_rate = 0;
496         subs->period_bytes = 0;
497         mutex_lock(&subs->stream->chip->shutdown_mutex);
498         stop_endpoints(subs, 0, 1, 1);
499         mutex_unlock(&subs->stream->chip->shutdown_mutex);
500         return snd_pcm_lib_free_vmalloc_buffer(substream);
501 }
502
503 /*
504  * prepare callback
505  *
506  * only a few subtle things...
507  */
508 static int snd_usb_pcm_prepare(struct snd_pcm_substream *substream)
509 {
510         struct snd_pcm_runtime *runtime = substream->runtime;
511         struct snd_usb_substream *subs = runtime->private_data;
512
513         if (! subs->cur_audiofmt) {
514                 snd_printk(KERN_ERR "usbaudio: no format is specified!\n");
515                 return -ENXIO;
516         }
517
518         if (snd_BUG_ON(!subs->data_endpoint))
519                 return -EIO;
520
521         /* some unit conversions in runtime */
522         subs->data_endpoint->maxframesize =
523                 bytes_to_frames(runtime, subs->data_endpoint->maxpacksize);
524         subs->data_endpoint->curframesize =
525                 bytes_to_frames(runtime, subs->data_endpoint->curpacksize);
526
527         /* reset the pointer */
528         subs->hwptr_done = 0;
529         subs->transfer_done = 0;
530         subs->last_delay = 0;
531         subs->last_frame_number = 0;
532         runtime->delay = 0;
533
534         /* for playback, submit the URBs now; otherwise, the first hwptr_done
535          * updates for all URBs would happen at the same time when starting */
536         if (subs->direction == SNDRV_PCM_STREAM_PLAYBACK)
537                 return start_endpoints(subs);
538
539         return 0;
540 }
541
542 static struct snd_pcm_hardware snd_usb_hardware =
543 {
544         .info =                 SNDRV_PCM_INFO_MMAP |
545                                 SNDRV_PCM_INFO_MMAP_VALID |
546                                 SNDRV_PCM_INFO_BATCH |
547                                 SNDRV_PCM_INFO_INTERLEAVED |
548                                 SNDRV_PCM_INFO_BLOCK_TRANSFER |
549                                 SNDRV_PCM_INFO_PAUSE,
550         .buffer_bytes_max =     1024 * 1024,
551         .period_bytes_min =     64,
552         .period_bytes_max =     512 * 1024,
553         .periods_min =          2,
554         .periods_max =          1024,
555 };
556
557 static int hw_check_valid_format(struct snd_usb_substream *subs,
558                                  struct snd_pcm_hw_params *params,
559                                  struct audioformat *fp)
560 {
561         struct snd_interval *it = hw_param_interval(params, SNDRV_PCM_HW_PARAM_RATE);
562         struct snd_interval *ct = hw_param_interval(params, SNDRV_PCM_HW_PARAM_CHANNELS);
563         struct snd_mask *fmts = hw_param_mask(params, SNDRV_PCM_HW_PARAM_FORMAT);
564         struct snd_interval *pt = hw_param_interval(params, SNDRV_PCM_HW_PARAM_PERIOD_TIME);
565         struct snd_mask check_fmts;
566         unsigned int ptime;
567
568         /* check the format */
569         snd_mask_none(&check_fmts);
570         check_fmts.bits[0] = (u32)fp->formats;
571         check_fmts.bits[1] = (u32)(fp->formats >> 32);
572         snd_mask_intersect(&check_fmts, fmts);
573         if (snd_mask_empty(&check_fmts)) {
574                 hwc_debug("   > check: no supported format %d\n", fp->format);
575                 return 0;
576         }
577         /* check the channels */
578         if (fp->channels < ct->min || fp->channels > ct->max) {
579                 hwc_debug("   > check: no valid channels %d (%d/%d)\n", fp->channels, ct->min, ct->max);
580                 return 0;
581         }
582         /* check the rate is within the range */
583         if (fp->rate_min > it->max || (fp->rate_min == it->max && it->openmax)) {
584                 hwc_debug("   > check: rate_min %d > max %d\n", fp->rate_min, it->max);
585                 return 0;
586         }
587         if (fp->rate_max < it->min || (fp->rate_max == it->min && it->openmin)) {
588                 hwc_debug("   > check: rate_max %d < min %d\n", fp->rate_max, it->min);
589                 return 0;
590         }
591         /* check whether the period time is >= the data packet interval */
592         if (snd_usb_get_speed(subs->dev) != USB_SPEED_FULL) {
593                 ptime = 125 * (1 << fp->datainterval);
594                 if (ptime > pt->max || (ptime == pt->max && pt->openmax)) {
595                         hwc_debug("   > check: ptime %u > max %u\n", ptime, pt->max);
596                         return 0;
597                 }
598         }
599         return 1;
600 }
601
602 static int hw_rule_rate(struct snd_pcm_hw_params *params,
603                         struct snd_pcm_hw_rule *rule)
604 {
605         struct snd_usb_substream *subs = rule->private;
606         struct list_head *p;
607         struct snd_interval *it = hw_param_interval(params, SNDRV_PCM_HW_PARAM_RATE);
608         unsigned int rmin, rmax;
609         int changed;
610
611         hwc_debug("hw_rule_rate: (%d,%d)\n", it->min, it->max);
612         changed = 0;
613         rmin = rmax = 0;
614         list_for_each(p, &subs->fmt_list) {
615                 struct audioformat *fp;
616                 fp = list_entry(p, struct audioformat, list);
617                 if (!hw_check_valid_format(subs, params, fp))
618                         continue;
619                 if (changed++) {
620                         if (rmin > fp->rate_min)
621                                 rmin = fp->rate_min;
622                         if (rmax < fp->rate_max)
623                                 rmax = fp->rate_max;
624                 } else {
625                         rmin = fp->rate_min;
626                         rmax = fp->rate_max;
627                 }
628         }
629
630         if (!changed) {
631                 hwc_debug("  --> get empty\n");
632                 it->empty = 1;
633                 return -EINVAL;
634         }
635
636         changed = 0;
637         if (it->min < rmin) {
638                 it->min = rmin;
639                 it->openmin = 0;
640                 changed = 1;
641         }
642         if (it->max > rmax) {
643                 it->max = rmax;
644                 it->openmax = 0;
645                 changed = 1;
646         }
647         if (snd_interval_checkempty(it)) {
648                 it->empty = 1;
649                 return -EINVAL;
650         }
651         hwc_debug("  --> (%d, %d) (changed = %d)\n", it->min, it->max, changed);
652         return changed;
653 }
654
655
656 static int hw_rule_channels(struct snd_pcm_hw_params *params,
657                             struct snd_pcm_hw_rule *rule)
658 {
659         struct snd_usb_substream *subs = rule->private;
660         struct list_head *p;
661         struct snd_interval *it = hw_param_interval(params, SNDRV_PCM_HW_PARAM_CHANNELS);
662         unsigned int rmin, rmax;
663         int changed;
664
665         hwc_debug("hw_rule_channels: (%d,%d)\n", it->min, it->max);
666         changed = 0;
667         rmin = rmax = 0;
668         list_for_each(p, &subs->fmt_list) {
669                 struct audioformat *fp;
670                 fp = list_entry(p, struct audioformat, list);
671                 if (!hw_check_valid_format(subs, params, fp))
672                         continue;
673                 if (changed++) {
674                         if (rmin > fp->channels)
675                                 rmin = fp->channels;
676                         if (rmax < fp->channels)
677                                 rmax = fp->channels;
678                 } else {
679                         rmin = fp->channels;
680                         rmax = fp->channels;
681                 }
682         }
683
684         if (!changed) {
685                 hwc_debug("  --> get empty\n");
686                 it->empty = 1;
687                 return -EINVAL;
688         }
689
690         changed = 0;
691         if (it->min < rmin) {
692                 it->min = rmin;
693                 it->openmin = 0;
694                 changed = 1;
695         }
696         if (it->max > rmax) {
697                 it->max = rmax;
698                 it->openmax = 0;
699                 changed = 1;
700         }
701         if (snd_interval_checkempty(it)) {
702                 it->empty = 1;
703                 return -EINVAL;
704         }
705         hwc_debug("  --> (%d, %d) (changed = %d)\n", it->min, it->max, changed);
706         return changed;
707 }
708
709 static int hw_rule_format(struct snd_pcm_hw_params *params,
710                           struct snd_pcm_hw_rule *rule)
711 {
712         struct snd_usb_substream *subs = rule->private;
713         struct list_head *p;
714         struct snd_mask *fmt = hw_param_mask(params, SNDRV_PCM_HW_PARAM_FORMAT);
715         u64 fbits;
716         u32 oldbits[2];
717         int changed;
718
719         hwc_debug("hw_rule_format: %x:%x\n", fmt->bits[0], fmt->bits[1]);
720         fbits = 0;
721         list_for_each(p, &subs->fmt_list) {
722                 struct audioformat *fp;
723                 fp = list_entry(p, struct audioformat, list);
724                 if (!hw_check_valid_format(subs, params, fp))
725                         continue;
726                 fbits |= fp->formats;
727         }
728
729         oldbits[0] = fmt->bits[0];
730         oldbits[1] = fmt->bits[1];
731         fmt->bits[0] &= (u32)fbits;
732         fmt->bits[1] &= (u32)(fbits >> 32);
733         if (!fmt->bits[0] && !fmt->bits[1]) {
734                 hwc_debug("  --> get empty\n");
735                 return -EINVAL;
736         }
737         changed = (oldbits[0] != fmt->bits[0] || oldbits[1] != fmt->bits[1]);
738         hwc_debug("  --> %x:%x (changed = %d)\n", fmt->bits[0], fmt->bits[1], changed);
739         return changed;
740 }
741
742 static int hw_rule_period_time(struct snd_pcm_hw_params *params,
743                                struct snd_pcm_hw_rule *rule)
744 {
745         struct snd_usb_substream *subs = rule->private;
746         struct audioformat *fp;
747         struct snd_interval *it;
748         unsigned char min_datainterval;
749         unsigned int pmin;
750         int changed;
751
752         it = hw_param_interval(params, SNDRV_PCM_HW_PARAM_PERIOD_TIME);
753         hwc_debug("hw_rule_period_time: (%u,%u)\n", it->min, it->max);
754         min_datainterval = 0xff;
755         list_for_each_entry(fp, &subs->fmt_list, list) {
756                 if (!hw_check_valid_format(subs, params, fp))
757                         continue;
758                 min_datainterval = min(min_datainterval, fp->datainterval);
759         }
760         if (min_datainterval == 0xff) {
761                 hwc_debug("  --> get empty\n");
762                 it->empty = 1;
763                 return -EINVAL;
764         }
765         pmin = 125 * (1 << min_datainterval);
766         changed = 0;
767         if (it->min < pmin) {
768                 it->min = pmin;
769                 it->openmin = 0;
770                 changed = 1;
771         }
772         if (snd_interval_checkempty(it)) {
773                 it->empty = 1;
774                 return -EINVAL;
775         }
776         hwc_debug("  --> (%u,%u) (changed = %d)\n", it->min, it->max, changed);
777         return changed;
778 }
779
780 /*
781  *  If the device supports unusual bit rates, does the request meet these?
782  */
783 static int snd_usb_pcm_check_knot(struct snd_pcm_runtime *runtime,
784                                   struct snd_usb_substream *subs)
785 {
786         struct audioformat *fp;
787         int *rate_list;
788         int count = 0, needs_knot = 0;
789         int err;
790
791         list_for_each_entry(fp, &subs->fmt_list, list) {
792                 if (fp->rates & SNDRV_PCM_RATE_CONTINUOUS)
793                         return 0;
794                 count += fp->nr_rates;
795                 if (fp->rates & SNDRV_PCM_RATE_KNOT)
796                         needs_knot = 1;
797         }
798         if (!needs_knot)
799                 return 0;
800
801         subs->rate_list.list = rate_list =
802                 kmalloc(sizeof(int) * count, GFP_KERNEL);
803         if (!subs->rate_list.list)
804                 return -ENOMEM;
805         subs->rate_list.count = count;
806         subs->rate_list.mask = 0;
807         count = 0;
808         list_for_each_entry(fp, &subs->fmt_list, list) {
809                 int i;
810                 for (i = 0; i < fp->nr_rates; i++)
811                         rate_list[count++] = fp->rate_table[i];
812         }
813         err = snd_pcm_hw_constraint_list(runtime, 0, SNDRV_PCM_HW_PARAM_RATE,
814                                          &subs->rate_list);
815         if (err < 0)
816                 return err;
817
818         return 0;
819 }
820
821
822 /*
823  * set up the runtime hardware information.
824  */
825
826 static int setup_hw_info(struct snd_pcm_runtime *runtime, struct snd_usb_substream *subs)
827 {
828         struct list_head *p;
829         unsigned int pt, ptmin;
830         int param_period_time_if_needed;
831         int err;
832
833         runtime->hw.formats = subs->formats;
834
835         runtime->hw.rate_min = 0x7fffffff;
836         runtime->hw.rate_max = 0;
837         runtime->hw.channels_min = 256;
838         runtime->hw.channels_max = 0;
839         runtime->hw.rates = 0;
840         ptmin = UINT_MAX;
841         /* check min/max rates and channels */
842         list_for_each(p, &subs->fmt_list) {
843                 struct audioformat *fp;
844                 fp = list_entry(p, struct audioformat, list);
845                 runtime->hw.rates |= fp->rates;
846                 if (runtime->hw.rate_min > fp->rate_min)
847                         runtime->hw.rate_min = fp->rate_min;
848                 if (runtime->hw.rate_max < fp->rate_max)
849                         runtime->hw.rate_max = fp->rate_max;
850                 if (runtime->hw.channels_min > fp->channels)
851                         runtime->hw.channels_min = fp->channels;
852                 if (runtime->hw.channels_max < fp->channels)
853                         runtime->hw.channels_max = fp->channels;
854                 if (fp->fmt_type == UAC_FORMAT_TYPE_II && fp->frame_size > 0) {
855                         /* FIXME: there might be more than one audio formats... */
856                         runtime->hw.period_bytes_min = runtime->hw.period_bytes_max =
857                                 fp->frame_size;
858                 }
859                 pt = 125 * (1 << fp->datainterval);
860                 ptmin = min(ptmin, pt);
861         }
862         err = snd_usb_autoresume(subs->stream->chip);
863         if (err < 0)
864                 return err;
865
866         param_period_time_if_needed = SNDRV_PCM_HW_PARAM_PERIOD_TIME;
867         if (snd_usb_get_speed(subs->dev) == USB_SPEED_FULL)
868                 /* full speed devices have fixed data packet interval */
869                 ptmin = 1000;
870         if (ptmin == 1000)
871                 /* if period time doesn't go below 1 ms, no rules needed */
872                 param_period_time_if_needed = -1;
873         snd_pcm_hw_constraint_minmax(runtime, SNDRV_PCM_HW_PARAM_PERIOD_TIME,
874                                      ptmin, UINT_MAX);
875
876         if ((err = snd_pcm_hw_rule_add(runtime, 0, SNDRV_PCM_HW_PARAM_RATE,
877                                        hw_rule_rate, subs,
878                                        SNDRV_PCM_HW_PARAM_FORMAT,
879                                        SNDRV_PCM_HW_PARAM_CHANNELS,
880                                        param_period_time_if_needed,
881                                        -1)) < 0)
882                 goto rep_err;
883         if ((err = snd_pcm_hw_rule_add(runtime, 0, SNDRV_PCM_HW_PARAM_CHANNELS,
884                                        hw_rule_channels, subs,
885                                        SNDRV_PCM_HW_PARAM_FORMAT,
886                                        SNDRV_PCM_HW_PARAM_RATE,
887                                        param_period_time_if_needed,
888                                        -1)) < 0)
889                 goto rep_err;
890         if ((err = snd_pcm_hw_rule_add(runtime, 0, SNDRV_PCM_HW_PARAM_FORMAT,
891                                        hw_rule_format, subs,
892                                        SNDRV_PCM_HW_PARAM_RATE,
893                                        SNDRV_PCM_HW_PARAM_CHANNELS,
894                                        param_period_time_if_needed,
895                                        -1)) < 0)
896                 goto rep_err;
897         if (param_period_time_if_needed >= 0) {
898                 err = snd_pcm_hw_rule_add(runtime, 0,
899                                           SNDRV_PCM_HW_PARAM_PERIOD_TIME,
900                                           hw_rule_period_time, subs,
901                                           SNDRV_PCM_HW_PARAM_FORMAT,
902                                           SNDRV_PCM_HW_PARAM_CHANNELS,
903                                           SNDRV_PCM_HW_PARAM_RATE,
904                                           -1);
905                 if (err < 0)
906                         goto rep_err;
907         }
908         if ((err = snd_usb_pcm_check_knot(runtime, subs)) < 0)
909                 goto rep_err;
910         return 0;
911
912 rep_err:
913         snd_usb_autosuspend(subs->stream->chip);
914         return err;
915 }
916
917 static int snd_usb_pcm_open(struct snd_pcm_substream *substream, int direction)
918 {
919         struct snd_usb_stream *as = snd_pcm_substream_chip(substream);
920         struct snd_pcm_runtime *runtime = substream->runtime;
921         struct snd_usb_substream *subs = &as->substream[direction];
922
923         subs->interface = -1;
924         subs->altset_idx = 0;
925         runtime->hw = snd_usb_hardware;
926         runtime->private_data = subs;
927         subs->pcm_substream = substream;
928         /* runtime PM is also done there */
929         return setup_hw_info(runtime, subs);
930 }
931
932 static int snd_usb_pcm_close(struct snd_pcm_substream *substream, int direction)
933 {
934         int ret;
935         struct snd_usb_stream *as = snd_pcm_substream_chip(substream);
936         struct snd_usb_substream *subs = &as->substream[direction];
937
938         stop_endpoints(subs, 0, 0, 0);
939         ret = deactivate_endpoints(subs);
940         subs->pcm_substream = NULL;
941         snd_usb_autosuspend(subs->stream->chip);
942
943         return ret;
944 }
945
946 /* Since a URB can handle only a single linear buffer, we must use double
947  * buffering when the data to be transferred overflows the buffer boundary.
948  * To avoid inconsistencies when updating hwptr_done, we use double buffering
949  * for all URBs.
950  */
951 static void retire_capture_urb(struct snd_usb_substream *subs,
952                                struct urb *urb)
953 {
954         struct snd_pcm_runtime *runtime = subs->pcm_substream->runtime;
955         unsigned int stride, frames, bytes, oldptr;
956         int i, period_elapsed = 0;
957         unsigned long flags;
958         unsigned char *cp;
959
960         stride = runtime->frame_bits >> 3;
961
962         for (i = 0; i < urb->number_of_packets; i++) {
963                 cp = (unsigned char *)urb->transfer_buffer + urb->iso_frame_desc[i].offset;
964                 if (urb->iso_frame_desc[i].status && printk_ratelimit()) {
965                         snd_printdd(KERN_ERR "frame %d active: %d\n", i, urb->iso_frame_desc[i].status);
966                         // continue;
967                 }
968                 bytes = urb->iso_frame_desc[i].actual_length;
969                 frames = bytes / stride;
970                 if (!subs->txfr_quirk)
971                         bytes = frames * stride;
972                 if (bytes % (runtime->sample_bits >> 3) != 0) {
973 #ifdef CONFIG_SND_DEBUG_VERBOSE
974                         int oldbytes = bytes;
975 #endif
976                         bytes = frames * stride;
977                         snd_printdd(KERN_ERR "Corrected urb data len. %d->%d\n",
978                                                         oldbytes, bytes);
979                 }
980                 /* update the current pointer */
981                 spin_lock_irqsave(&subs->lock, flags);
982                 oldptr = subs->hwptr_done;
983                 subs->hwptr_done += bytes;
984                 if (subs->hwptr_done >= runtime->buffer_size * stride)
985                         subs->hwptr_done -= runtime->buffer_size * stride;
986                 frames = (bytes + (oldptr % stride)) / stride;
987                 subs->transfer_done += frames;
988                 if (subs->transfer_done >= runtime->period_size) {
989                         subs->transfer_done -= runtime->period_size;
990                         period_elapsed = 1;
991                 }
992                 spin_unlock_irqrestore(&subs->lock, flags);
993                 /* copy a data chunk */
994                 if (oldptr + bytes > runtime->buffer_size * stride) {
995                         unsigned int bytes1 =
996                                         runtime->buffer_size * stride - oldptr;
997                         memcpy(runtime->dma_area + oldptr, cp, bytes1);
998                         memcpy(runtime->dma_area, cp + bytes1, bytes - bytes1);
999                 } else {
1000                         memcpy(runtime->dma_area + oldptr, cp, bytes);
1001                 }
1002         }
1003
1004         if (period_elapsed)
1005                 snd_pcm_period_elapsed(subs->pcm_substream);
1006 }
1007
1008 static void prepare_playback_urb(struct snd_usb_substream *subs,
1009                                  struct urb *urb)
1010 {
1011         struct snd_pcm_runtime *runtime = subs->pcm_substream->runtime;
1012         struct snd_urb_ctx *ctx = urb->context;
1013         unsigned int counts, frames, bytes;
1014         int i, stride, period_elapsed = 0;
1015         unsigned long flags;
1016
1017         stride = runtime->frame_bits >> 3;
1018
1019         frames = 0;
1020         urb->number_of_packets = 0;
1021         spin_lock_irqsave(&subs->lock, flags);
1022         for (i = 0; i < ctx->packets; i++) {
1023                 counts = ctx->packet_size[i];
1024                 /* set up descriptor */
1025                 urb->iso_frame_desc[i].offset = frames * stride;
1026                 urb->iso_frame_desc[i].length = counts * stride;
1027                 frames += counts;
1028                 urb->number_of_packets++;
1029                 subs->transfer_done += counts;
1030                 if (subs->transfer_done >= runtime->period_size) {
1031                         subs->transfer_done -= runtime->period_size;
1032                         period_elapsed = 1;
1033                         if (subs->fmt_type == UAC_FORMAT_TYPE_II) {
1034                                 if (subs->transfer_done > 0) {
1035                                         /* FIXME: fill-max mode is not
1036                                          * supported yet */
1037                                         frames -= subs->transfer_done;
1038                                         counts -= subs->transfer_done;
1039                                         urb->iso_frame_desc[i].length =
1040                                                 counts * stride;
1041                                         subs->transfer_done = 0;
1042                                 }
1043                                 i++;
1044                                 if (i < ctx->packets) {
1045                                         /* add a transfer delimiter */
1046                                         urb->iso_frame_desc[i].offset =
1047                                                 frames * stride;
1048                                         urb->iso_frame_desc[i].length = 0;
1049                                         urb->number_of_packets++;
1050                                 }
1051                                 break;
1052                         }
1053                 }
1054                 if (period_elapsed &&
1055                     !snd_usb_endpoint_implict_feedback_sink(subs->data_endpoint)) /* finish at the period boundary */
1056                         break;
1057         }
1058         bytes = frames * stride;
1059         if (subs->hwptr_done + bytes > runtime->buffer_size * stride) {
1060                 /* err, the transferred area goes over buffer boundary. */
1061                 unsigned int bytes1 =
1062                         runtime->buffer_size * stride - subs->hwptr_done;
1063                 memcpy(urb->transfer_buffer,
1064                        runtime->dma_area + subs->hwptr_done, bytes1);
1065                 memcpy(urb->transfer_buffer + bytes1,
1066                        runtime->dma_area, bytes - bytes1);
1067         } else {
1068                 memcpy(urb->transfer_buffer,
1069                        runtime->dma_area + subs->hwptr_done, bytes);
1070         }
1071         subs->hwptr_done += bytes;
1072         if (subs->hwptr_done >= runtime->buffer_size * stride)
1073                 subs->hwptr_done -= runtime->buffer_size * stride;
1074         runtime->delay += frames;
1075         spin_unlock_irqrestore(&subs->lock, flags);
1076         urb->transfer_buffer_length = bytes;
1077         if (period_elapsed)
1078                 snd_pcm_period_elapsed(subs->pcm_substream);
1079 }
1080
1081 /*
1082  * process after playback data complete
1083  * - decrease the delay count again
1084  */
1085 static void retire_playback_urb(struct snd_usb_substream *subs,
1086                                struct urb *urb)
1087 {
1088         unsigned long flags;
1089         struct snd_pcm_runtime *runtime = subs->pcm_substream->runtime;
1090         int stride = runtime->frame_bits >> 3;
1091         int processed = urb->transfer_buffer_length / stride;
1092
1093         spin_lock_irqsave(&subs->lock, flags);
1094         if (processed > runtime->delay)
1095                 runtime->delay = 0;
1096         else
1097                 runtime->delay -= processed;
1098         spin_unlock_irqrestore(&subs->lock, flags);
1099 }
1100
1101 static int snd_usb_playback_open(struct snd_pcm_substream *substream)
1102 {
1103         return snd_usb_pcm_open(substream, SNDRV_PCM_STREAM_PLAYBACK);
1104 }
1105
1106 static int snd_usb_playback_close(struct snd_pcm_substream *substream)
1107 {
1108         return snd_usb_pcm_close(substream, SNDRV_PCM_STREAM_PLAYBACK);
1109 }
1110
1111 static int snd_usb_capture_open(struct snd_pcm_substream *substream)
1112 {
1113         return snd_usb_pcm_open(substream, SNDRV_PCM_STREAM_CAPTURE);
1114 }
1115
1116 static int snd_usb_capture_close(struct snd_pcm_substream *substream)
1117 {
1118         return snd_usb_pcm_close(substream, SNDRV_PCM_STREAM_CAPTURE);
1119 }
1120
1121 static int snd_usb_substream_playback_trigger(struct snd_pcm_substream *substream,
1122                                               int cmd)
1123 {
1124         struct snd_usb_substream *subs = substream->runtime->private_data;
1125
1126         switch (cmd) {
1127         case SNDRV_PCM_TRIGGER_START:
1128         case SNDRV_PCM_TRIGGER_PAUSE_RELEASE:
1129                 subs->data_endpoint->prepare_data_urb = prepare_playback_urb;
1130                 subs->data_endpoint->retire_data_urb = retire_playback_urb;
1131                 subs->running = 1;
1132                 return 0;
1133         case SNDRV_PCM_TRIGGER_STOP:
1134                 stop_endpoints(subs, 0, 0, 0);
1135                 subs->running = 0;
1136                 return 0;
1137         case SNDRV_PCM_TRIGGER_PAUSE_PUSH:
1138                 subs->data_endpoint->prepare_data_urb = NULL;
1139                 subs->data_endpoint->retire_data_urb = NULL;
1140                 subs->running = 0;
1141                 return 0;
1142         }
1143
1144         return -EINVAL;
1145 }
1146
1147 int snd_usb_substream_capture_trigger(struct snd_pcm_substream *substream, int cmd)
1148 {
1149         int err;
1150         struct snd_usb_substream *subs = substream->runtime->private_data;
1151
1152         switch (cmd) {
1153         case SNDRV_PCM_TRIGGER_START:
1154                 err = start_endpoints(subs);
1155                 if (err < 0)
1156                         return err;
1157
1158                 subs->data_endpoint->retire_data_urb = retire_capture_urb;
1159                 subs->running = 1;
1160                 return 0;
1161         case SNDRV_PCM_TRIGGER_STOP:
1162                 stop_endpoints(subs, 0, 0, 0);
1163                 subs->running = 0;
1164                 return 0;
1165         case SNDRV_PCM_TRIGGER_PAUSE_PUSH:
1166                 subs->data_endpoint->retire_data_urb = NULL;
1167                 subs->running = 0;
1168                 return 0;
1169         case SNDRV_PCM_TRIGGER_PAUSE_RELEASE:
1170                 subs->data_endpoint->retire_data_urb = retire_capture_urb;
1171                 subs->running = 1;
1172                 return 0;
1173         }
1174
1175         return -EINVAL;
1176 }
1177
1178 static struct snd_pcm_ops snd_usb_playback_ops = {
1179         .open =         snd_usb_playback_open,
1180         .close =        snd_usb_playback_close,
1181         .ioctl =        snd_pcm_lib_ioctl,
1182         .hw_params =    snd_usb_hw_params,
1183         .hw_free =      snd_usb_hw_free,
1184         .prepare =      snd_usb_pcm_prepare,
1185         .trigger =      snd_usb_substream_playback_trigger,
1186         .pointer =      snd_usb_pcm_pointer,
1187         .page =         snd_pcm_lib_get_vmalloc_page,
1188         .mmap =         snd_pcm_lib_mmap_vmalloc,
1189 };
1190
1191 static struct snd_pcm_ops snd_usb_capture_ops = {
1192         .open =         snd_usb_capture_open,
1193         .close =        snd_usb_capture_close,
1194         .ioctl =        snd_pcm_lib_ioctl,
1195         .hw_params =    snd_usb_hw_params,
1196         .hw_free =      snd_usb_hw_free,
1197         .prepare =      snd_usb_pcm_prepare,
1198         .trigger =      snd_usb_substream_capture_trigger,
1199         .pointer =      snd_usb_pcm_pointer,
1200         .page =         snd_pcm_lib_get_vmalloc_page,
1201         .mmap =         snd_pcm_lib_mmap_vmalloc,
1202 };
1203
1204 void snd_usb_set_pcm_ops(struct snd_pcm *pcm, int stream)
1205 {
1206         snd_pcm_set_ops(pcm, stream,
1207                         stream == SNDRV_PCM_STREAM_PLAYBACK ?
1208                         &snd_usb_playback_ops : &snd_usb_capture_ops);
1209 }