ALSA: usb-audio: add support for samplerate setting on v2 devices
[safe/jmp/linux-2.6] / 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/usb.h>
19 #include <linux/usb/audio.h>
20
21 #include <sound/core.h>
22 #include <sound/pcm.h>
23 #include <sound/pcm_params.h>
24
25 #include "usbaudio.h"
26 #include "card.h"
27 #include "quirks.h"
28 #include "debug.h"
29 #include "urb.h"
30 #include "helper.h"
31 #include "pcm.h"
32
33 /*
34  * return the current pcm pointer.  just based on the hwptr_done value.
35  */
36 static snd_pcm_uframes_t snd_usb_pcm_pointer(struct snd_pcm_substream *substream)
37 {
38         struct snd_usb_substream *subs;
39         unsigned int hwptr_done;
40
41         subs = (struct snd_usb_substream *)substream->runtime->private_data;
42         spin_lock(&subs->lock);
43         hwptr_done = subs->hwptr_done;
44         spin_unlock(&subs->lock);
45         return hwptr_done / (substream->runtime->frame_bits >> 3);
46 }
47
48 /*
49  * find a matching audio format
50  */
51 static struct audioformat *find_format(struct snd_usb_substream *subs, unsigned int format,
52                                        unsigned int rate, unsigned int channels)
53 {
54         struct list_head *p;
55         struct audioformat *found = NULL;
56         int cur_attr = 0, attr;
57
58         list_for_each(p, &subs->fmt_list) {
59                 struct audioformat *fp;
60                 fp = list_entry(p, struct audioformat, list);
61                 if (!(fp->formats & (1uLL << format)))
62                         continue;
63                 if (fp->channels != channels)
64                         continue;
65                 if (rate < fp->rate_min || rate > fp->rate_max)
66                         continue;
67                 if (! (fp->rates & SNDRV_PCM_RATE_CONTINUOUS)) {
68                         unsigned int i;
69                         for (i = 0; i < fp->nr_rates; i++)
70                                 if (fp->rate_table[i] == rate)
71                                         break;
72                         if (i >= fp->nr_rates)
73                                 continue;
74                 }
75                 attr = fp->ep_attr & USB_ENDPOINT_SYNCTYPE;
76                 if (! found) {
77                         found = fp;
78                         cur_attr = attr;
79                         continue;
80                 }
81                 /* avoid async out and adaptive in if the other method
82                  * supports the same format.
83                  * this is a workaround for the case like
84                  * M-audio audiophile USB.
85                  */
86                 if (attr != cur_attr) {
87                         if ((attr == USB_ENDPOINT_SYNC_ASYNC &&
88                              subs->direction == SNDRV_PCM_STREAM_PLAYBACK) ||
89                             (attr == USB_ENDPOINT_SYNC_ADAPTIVE &&
90                              subs->direction == SNDRV_PCM_STREAM_CAPTURE))
91                                 continue;
92                         if ((cur_attr == USB_ENDPOINT_SYNC_ASYNC &&
93                              subs->direction == SNDRV_PCM_STREAM_PLAYBACK) ||
94                             (cur_attr == USB_ENDPOINT_SYNC_ADAPTIVE &&
95                              subs->direction == SNDRV_PCM_STREAM_CAPTURE)) {
96                                 found = fp;
97                                 cur_attr = attr;
98                                 continue;
99                         }
100                 }
101                 /* find the format with the largest max. packet size */
102                 if (fp->maxpacksize > found->maxpacksize) {
103                         found = fp;
104                         cur_attr = attr;
105                 }
106         }
107         return found;
108 }
109
110 static int init_pitch_v1(struct snd_usb_audio *chip, int iface,
111                          struct usb_host_interface *alts,
112                          struct audioformat *fmt)
113 {
114         struct usb_device *dev = chip->dev;
115         unsigned int ep;
116         unsigned char data[1];
117         int err;
118
119         ep = get_endpoint(alts, 0)->bEndpointAddress;
120
121         /* if endpoint doesn't have pitch control, bail out */
122         if (!(fmt->attributes & UAC_EP_CS_ATTR_PITCH_CONTROL))
123                 return 0;
124
125         data[0] = 1;
126         if ((err = snd_usb_ctl_msg(dev, usb_sndctrlpipe(dev, 0), UAC_SET_CUR,
127                                    USB_TYPE_CLASS|USB_RECIP_ENDPOINT|USB_DIR_OUT,
128                                    UAC_EP_CS_ATTR_PITCH_CONTROL << 8, ep,
129                                    data, sizeof(data), 1000)) < 0) {
130                 snd_printk(KERN_ERR "%d:%d:%d: cannot set enable PITCH\n",
131                            dev->devnum, iface, ep);
132                 return err;
133         }
134
135         return 0;
136 }
137
138 /*
139  * initialize the picth control and sample rate
140  */
141 int snd_usb_init_pitch(struct snd_usb_audio *chip, int iface,
142                        struct usb_host_interface *alts,
143                        struct audioformat *fmt)
144 {
145         struct usb_interface_descriptor *altsd = get_iface_desc(alts);
146
147         switch (altsd->bInterfaceProtocol) {
148         case UAC_VERSION_1:
149                 return init_pitch_v1(chip, iface, alts, fmt);
150
151         case UAC_VERSION_2:
152                 /* not implemented yet */
153                 return 0;
154         }
155
156         return -EINVAL;
157 }
158
159 static int set_sample_rate_v1(struct snd_usb_audio *chip, int iface,
160                               struct usb_host_interface *alts,
161                               struct audioformat *fmt, int rate)
162 {
163         struct usb_device *dev = chip->dev;
164         unsigned int ep;
165         unsigned char data[3];
166         int err, crate;
167
168         ep = get_endpoint(alts, 0)->bEndpointAddress;
169         /* if endpoint doesn't have sampling rate control, bail out */
170         if (!(fmt->attributes & UAC_EP_CS_ATTR_SAMPLE_RATE)) {
171                 snd_printk(KERN_WARNING "%d:%d:%d: endpoint lacks sample rate attribute bit, cannot set.\n",
172                                    dev->devnum, iface, fmt->altsetting);
173                 return 0;
174         }
175
176         data[0] = rate;
177         data[1] = rate >> 8;
178         data[2] = rate >> 16;
179         if ((err = snd_usb_ctl_msg(dev, usb_sndctrlpipe(dev, 0), UAC_SET_CUR,
180                                    USB_TYPE_CLASS|USB_RECIP_ENDPOINT|USB_DIR_OUT,
181                                    UAC_EP_CS_ATTR_SAMPLE_RATE << 8, ep,
182                                    data, sizeof(data), 1000)) < 0) {
183                 snd_printk(KERN_ERR "%d:%d:%d: cannot set freq %d to ep %#x\n",
184                            dev->devnum, iface, fmt->altsetting, rate, ep);
185                 return err;
186         }
187         if ((err = snd_usb_ctl_msg(dev, usb_rcvctrlpipe(dev, 0), UAC_GET_CUR,
188                                    USB_TYPE_CLASS|USB_RECIP_ENDPOINT|USB_DIR_IN,
189                                    UAC_EP_CS_ATTR_SAMPLE_RATE << 8, ep,
190                                    data, sizeof(data), 1000)) < 0) {
191                 snd_printk(KERN_WARNING "%d:%d:%d: cannot get freq at ep %#x\n",
192                            dev->devnum, iface, fmt->altsetting, ep);
193                 return 0; /* some devices don't support reading */
194         }
195         crate = data[0] | (data[1] << 8) | (data[2] << 16);
196         if (crate != rate) {
197                 snd_printd(KERN_WARNING "current rate %d is different from the runtime rate %d\n", crate, rate);
198                 // runtime->rate = crate;
199         }
200
201         return 0;
202 }
203
204 static int set_sample_rate_v2(struct snd_usb_audio *chip, int iface,
205                               struct usb_host_interface *alts,
206                               struct audioformat *fmt, int rate)
207 {
208         struct usb_device *dev = chip->dev;
209         unsigned char data[4];
210         int err, crate;
211
212         data[0] = rate;
213         data[1] = rate >> 8;
214         data[2] = rate >> 16;
215         data[3] = rate >> 24;
216         if ((err = snd_usb_ctl_msg(dev, usb_sndctrlpipe(dev, 0), UAC2_CS_CUR,
217                                    USB_TYPE_CLASS | USB_RECIP_INTERFACE | USB_DIR_OUT,
218                                    0x0100, chip->clock_id << 8,
219                                    data, sizeof(data), 1000)) < 0) {
220                 snd_printk(KERN_ERR "%d:%d:%d: cannot set freq %d (v2)\n",
221                            dev->devnum, iface, fmt->altsetting, rate);
222                 return err;
223         }
224         if ((err = snd_usb_ctl_msg(dev, usb_rcvctrlpipe(dev, 0), UAC2_CS_CUR,
225                                    USB_TYPE_CLASS | USB_RECIP_INTERFACE | USB_DIR_IN,
226                                    0x0100, chip->clock_id << 8,
227                                    data, sizeof(data), 1000)) < 0) {
228                 snd_printk(KERN_WARNING "%d:%d:%d: cannot get freq (v2)\n",
229                            dev->devnum, iface, fmt->altsetting);
230                 return err;
231         }
232         crate = data[0] | (data[1] << 8) | (data[2] << 16) | (data[3] << 24);
233         if (crate != rate)
234                 snd_printd(KERN_WARNING "current rate %d is different from the runtime rate %d\n", crate, rate);
235
236         return 0;
237 }
238
239 int snd_usb_init_sample_rate(struct snd_usb_audio *chip, int iface,
240                              struct usb_host_interface *alts,
241                              struct audioformat *fmt, int rate)
242 {
243         struct usb_interface_descriptor *altsd = get_iface_desc(alts);
244
245         switch (altsd->bInterfaceProtocol) {
246         case UAC_VERSION_1:
247                 return set_sample_rate_v1(chip, iface, alts, fmt, rate);
248
249         case UAC_VERSION_2:
250                 return set_sample_rate_v2(chip, iface, alts, fmt, rate);
251         }
252
253         return -EINVAL;
254 }
255
256 /*
257  * find a matching format and set up the interface
258  */
259 static int set_format(struct snd_usb_substream *subs, struct audioformat *fmt)
260 {
261         struct usb_device *dev = subs->dev;
262         struct usb_host_interface *alts;
263         struct usb_interface_descriptor *altsd;
264         struct usb_interface *iface;
265         unsigned int ep, attr;
266         int is_playback = subs->direction == SNDRV_PCM_STREAM_PLAYBACK;
267         int err;
268
269         iface = usb_ifnum_to_if(dev, fmt->iface);
270         if (WARN_ON(!iface))
271                 return -EINVAL;
272         alts = &iface->altsetting[fmt->altset_idx];
273         altsd = get_iface_desc(alts);
274         if (WARN_ON(altsd->bAlternateSetting != fmt->altsetting))
275                 return -EINVAL;
276
277         if (fmt == subs->cur_audiofmt)
278                 return 0;
279
280         /* close the old interface */
281         if (subs->interface >= 0 && subs->interface != fmt->iface) {
282                 if (usb_set_interface(subs->dev, subs->interface, 0) < 0) {
283                         snd_printk(KERN_ERR "%d:%d:%d: return to setting 0 failed\n",
284                                 dev->devnum, fmt->iface, fmt->altsetting);
285                         return -EIO;
286                 }
287                 subs->interface = -1;
288                 subs->altset_idx = 0;
289         }
290
291         /* set interface */
292         if (subs->interface != fmt->iface || subs->altset_idx != fmt->altset_idx) {
293                 if (usb_set_interface(dev, fmt->iface, fmt->altsetting) < 0) {
294                         snd_printk(KERN_ERR "%d:%d:%d: usb_set_interface failed\n",
295                                    dev->devnum, fmt->iface, fmt->altsetting);
296                         return -EIO;
297                 }
298                 snd_printdd(KERN_INFO "setting usb interface %d:%d\n", fmt->iface, fmt->altsetting);
299                 subs->interface = fmt->iface;
300                 subs->altset_idx = fmt->altset_idx;
301         }
302
303         /* create a data pipe */
304         ep = fmt->endpoint & USB_ENDPOINT_NUMBER_MASK;
305         if (is_playback)
306                 subs->datapipe = usb_sndisocpipe(dev, ep);
307         else
308                 subs->datapipe = usb_rcvisocpipe(dev, ep);
309         subs->datainterval = fmt->datainterval;
310         subs->syncpipe = subs->syncinterval = 0;
311         subs->maxpacksize = fmt->maxpacksize;
312         subs->fill_max = 0;
313
314         /* we need a sync pipe in async OUT or adaptive IN mode */
315         /* check the number of EP, since some devices have broken
316          * descriptors which fool us.  if it has only one EP,
317          * assume it as adaptive-out or sync-in.
318          */
319         attr = fmt->ep_attr & USB_ENDPOINT_SYNCTYPE;
320         if (((is_playback && attr == USB_ENDPOINT_SYNC_ASYNC) ||
321              (! is_playback && attr == USB_ENDPOINT_SYNC_ADAPTIVE)) &&
322             altsd->bNumEndpoints >= 2) {
323                 /* check sync-pipe endpoint */
324                 /* ... and check descriptor size before accessing bSynchAddress
325                    because there is a version of the SB Audigy 2 NX firmware lacking
326                    the audio fields in the endpoint descriptors */
327                 if ((get_endpoint(alts, 1)->bmAttributes & USB_ENDPOINT_XFERTYPE_MASK) != 0x01 ||
328                     (get_endpoint(alts, 1)->bLength >= USB_DT_ENDPOINT_AUDIO_SIZE &&
329                      get_endpoint(alts, 1)->bSynchAddress != 0)) {
330                         snd_printk(KERN_ERR "%d:%d:%d : invalid synch pipe\n",
331                                    dev->devnum, fmt->iface, fmt->altsetting);
332                         return -EINVAL;
333                 }
334                 ep = get_endpoint(alts, 1)->bEndpointAddress;
335                 if (get_endpoint(alts, 0)->bLength >= USB_DT_ENDPOINT_AUDIO_SIZE &&
336                     (( is_playback && ep != (unsigned int)(get_endpoint(alts, 0)->bSynchAddress | USB_DIR_IN)) ||
337                      (!is_playback && ep != (unsigned int)(get_endpoint(alts, 0)->bSynchAddress & ~USB_DIR_IN)))) {
338                         snd_printk(KERN_ERR "%d:%d:%d : invalid synch pipe\n",
339                                    dev->devnum, fmt->iface, fmt->altsetting);
340                         return -EINVAL;
341                 }
342                 ep &= USB_ENDPOINT_NUMBER_MASK;
343                 if (is_playback)
344                         subs->syncpipe = usb_rcvisocpipe(dev, ep);
345                 else
346                         subs->syncpipe = usb_sndisocpipe(dev, ep);
347                 if (get_endpoint(alts, 1)->bLength >= USB_DT_ENDPOINT_AUDIO_SIZE &&
348                     get_endpoint(alts, 1)->bRefresh >= 1 &&
349                     get_endpoint(alts, 1)->bRefresh <= 9)
350                         subs->syncinterval = get_endpoint(alts, 1)->bRefresh;
351                 else if (snd_usb_get_speed(subs->dev) == USB_SPEED_FULL)
352                         subs->syncinterval = 1;
353                 else if (get_endpoint(alts, 1)->bInterval >= 1 &&
354                          get_endpoint(alts, 1)->bInterval <= 16)
355                         subs->syncinterval = get_endpoint(alts, 1)->bInterval - 1;
356                 else
357                         subs->syncinterval = 3;
358         }
359
360         /* always fill max packet size */
361         if (fmt->attributes & UAC_EP_CS_ATTR_FILL_MAX)
362                 subs->fill_max = 1;
363
364         if ((err = snd_usb_init_pitch(subs->stream->chip, subs->interface, alts, fmt)) < 0)
365                 return err;
366
367         subs->cur_audiofmt = fmt;
368
369         snd_usb_set_format_quirk(subs, fmt);
370
371 #if 0
372         printk(KERN_DEBUG
373                "setting done: format = %d, rate = %d..%d, channels = %d\n",
374                fmt->format, fmt->rate_min, fmt->rate_max, fmt->channels);
375         printk(KERN_DEBUG
376                "  datapipe = 0x%0x, syncpipe = 0x%0x\n",
377                subs->datapipe, subs->syncpipe);
378 #endif
379
380         return 0;
381 }
382
383 /*
384  * hw_params callback
385  *
386  * allocate a buffer and set the given audio format.
387  *
388  * so far we use a physically linear buffer although packetize transfer
389  * doesn't need a continuous area.
390  * if sg buffer is supported on the later version of alsa, we'll follow
391  * that.
392  */
393 static int snd_usb_hw_params(struct snd_pcm_substream *substream,
394                              struct snd_pcm_hw_params *hw_params)
395 {
396         struct snd_usb_substream *subs = substream->runtime->private_data;
397         struct audioformat *fmt;
398         unsigned int channels, rate, format;
399         int ret, changed;
400
401         ret = snd_pcm_lib_alloc_vmalloc_buffer(substream,
402                                                params_buffer_bytes(hw_params));
403         if (ret < 0)
404                 return ret;
405
406         format = params_format(hw_params);
407         rate = params_rate(hw_params);
408         channels = params_channels(hw_params);
409         fmt = find_format(subs, format, rate, channels);
410         if (!fmt) {
411                 snd_printd(KERN_DEBUG "cannot set format: format = %#x, rate = %d, channels = %d\n",
412                            format, rate, channels);
413                 return -EINVAL;
414         }
415
416         changed = subs->cur_audiofmt != fmt ||
417                 subs->period_bytes != params_period_bytes(hw_params) ||
418                 subs->cur_rate != rate;
419         if ((ret = set_format(subs, fmt)) < 0)
420                 return ret;
421
422         if (subs->cur_rate != rate) {
423                 struct usb_host_interface *alts;
424                 struct usb_interface *iface;
425                 iface = usb_ifnum_to_if(subs->dev, fmt->iface);
426                 alts = &iface->altsetting[fmt->altset_idx];
427                 ret = snd_usb_init_sample_rate(subs->stream->chip, subs->interface, alts, fmt, rate);
428                 if (ret < 0)
429                         return ret;
430                 subs->cur_rate = rate;
431         }
432
433         if (changed) {
434                 /* format changed */
435                 snd_usb_release_substream_urbs(subs, 0);
436                 /* influenced: period_bytes, channels, rate, format, */
437                 ret = snd_usb_init_substream_urbs(subs, params_period_bytes(hw_params),
438                                                   params_rate(hw_params),
439                                                   snd_pcm_format_physical_width(params_format(hw_params)) *
440                                                         params_channels(hw_params));
441         }
442
443         return ret;
444 }
445
446 /*
447  * hw_free callback
448  *
449  * reset the audio format and release the buffer
450  */
451 static int snd_usb_hw_free(struct snd_pcm_substream *substream)
452 {
453         struct snd_usb_substream *subs = substream->runtime->private_data;
454
455         subs->cur_audiofmt = NULL;
456         subs->cur_rate = 0;
457         subs->period_bytes = 0;
458         if (!subs->stream->chip->shutdown)
459                 snd_usb_release_substream_urbs(subs, 0);
460         return snd_pcm_lib_free_vmalloc_buffer(substream);
461 }
462
463 /*
464  * prepare callback
465  *
466  * only a few subtle things...
467  */
468 static int snd_usb_pcm_prepare(struct snd_pcm_substream *substream)
469 {
470         struct snd_pcm_runtime *runtime = substream->runtime;
471         struct snd_usb_substream *subs = runtime->private_data;
472
473         if (! subs->cur_audiofmt) {
474                 snd_printk(KERN_ERR "usbaudio: no format is specified!\n");
475                 return -ENXIO;
476         }
477
478         /* some unit conversions in runtime */
479         subs->maxframesize = bytes_to_frames(runtime, subs->maxpacksize);
480         subs->curframesize = bytes_to_frames(runtime, subs->curpacksize);
481
482         /* reset the pointer */
483         subs->hwptr_done = 0;
484         subs->transfer_done = 0;
485         subs->phase = 0;
486         runtime->delay = 0;
487
488         return snd_usb_substream_prepare(subs, runtime);
489 }
490
491 static struct snd_pcm_hardware snd_usb_hardware =
492 {
493         .info =                 SNDRV_PCM_INFO_MMAP |
494                                 SNDRV_PCM_INFO_MMAP_VALID |
495                                 SNDRV_PCM_INFO_BATCH |
496                                 SNDRV_PCM_INFO_INTERLEAVED |
497                                 SNDRV_PCM_INFO_BLOCK_TRANSFER |
498                                 SNDRV_PCM_INFO_PAUSE,
499         .buffer_bytes_max =     1024 * 1024,
500         .period_bytes_min =     64,
501         .period_bytes_max =     512 * 1024,
502         .periods_min =          2,
503         .periods_max =          1024,
504 };
505
506 static int hw_check_valid_format(struct snd_usb_substream *subs,
507                                  struct snd_pcm_hw_params *params,
508                                  struct audioformat *fp)
509 {
510         struct snd_interval *it = hw_param_interval(params, SNDRV_PCM_HW_PARAM_RATE);
511         struct snd_interval *ct = hw_param_interval(params, SNDRV_PCM_HW_PARAM_CHANNELS);
512         struct snd_mask *fmts = hw_param_mask(params, SNDRV_PCM_HW_PARAM_FORMAT);
513         struct snd_interval *pt = hw_param_interval(params, SNDRV_PCM_HW_PARAM_PERIOD_TIME);
514         struct snd_mask check_fmts;
515         unsigned int ptime;
516
517         /* check the format */
518         snd_mask_none(&check_fmts);
519         check_fmts.bits[0] = (u32)fp->formats;
520         check_fmts.bits[1] = (u32)(fp->formats >> 32);
521         snd_mask_intersect(&check_fmts, fmts);
522         if (snd_mask_empty(&check_fmts)) {
523                 hwc_debug("   > check: no supported format %d\n", fp->format);
524                 return 0;
525         }
526         /* check the channels */
527         if (fp->channels < ct->min || fp->channels > ct->max) {
528                 hwc_debug("   > check: no valid channels %d (%d/%d)\n", fp->channels, ct->min, ct->max);
529                 return 0;
530         }
531         /* check the rate is within the range */
532         if (fp->rate_min > it->max || (fp->rate_min == it->max && it->openmax)) {
533                 hwc_debug("   > check: rate_min %d > max %d\n", fp->rate_min, it->max);
534                 return 0;
535         }
536         if (fp->rate_max < it->min || (fp->rate_max == it->min && it->openmin)) {
537                 hwc_debug("   > check: rate_max %d < min %d\n", fp->rate_max, it->min);
538                 return 0;
539         }
540         /* check whether the period time is >= the data packet interval */
541         if (snd_usb_get_speed(subs->dev) == USB_SPEED_HIGH) {
542                 ptime = 125 * (1 << fp->datainterval);
543                 if (ptime > pt->max || (ptime == pt->max && pt->openmax)) {
544                         hwc_debug("   > check: ptime %u > max %u\n", ptime, pt->max);
545                         return 0;
546                 }
547         }
548         return 1;
549 }
550
551 static int hw_rule_rate(struct snd_pcm_hw_params *params,
552                         struct snd_pcm_hw_rule *rule)
553 {
554         struct snd_usb_substream *subs = rule->private;
555         struct list_head *p;
556         struct snd_interval *it = hw_param_interval(params, SNDRV_PCM_HW_PARAM_RATE);
557         unsigned int rmin, rmax;
558         int changed;
559
560         hwc_debug("hw_rule_rate: (%d,%d)\n", it->min, it->max);
561         changed = 0;
562         rmin = rmax = 0;
563         list_for_each(p, &subs->fmt_list) {
564                 struct audioformat *fp;
565                 fp = list_entry(p, struct audioformat, list);
566                 if (!hw_check_valid_format(subs, params, fp))
567                         continue;
568                 if (changed++) {
569                         if (rmin > fp->rate_min)
570                                 rmin = fp->rate_min;
571                         if (rmax < fp->rate_max)
572                                 rmax = fp->rate_max;
573                 } else {
574                         rmin = fp->rate_min;
575                         rmax = fp->rate_max;
576                 }
577         }
578
579         if (!changed) {
580                 hwc_debug("  --> get empty\n");
581                 it->empty = 1;
582                 return -EINVAL;
583         }
584
585         changed = 0;
586         if (it->min < rmin) {
587                 it->min = rmin;
588                 it->openmin = 0;
589                 changed = 1;
590         }
591         if (it->max > rmax) {
592                 it->max = rmax;
593                 it->openmax = 0;
594                 changed = 1;
595         }
596         if (snd_interval_checkempty(it)) {
597                 it->empty = 1;
598                 return -EINVAL;
599         }
600         hwc_debug("  --> (%d, %d) (changed = %d)\n", it->min, it->max, changed);
601         return changed;
602 }
603
604
605 static int hw_rule_channels(struct snd_pcm_hw_params *params,
606                             struct snd_pcm_hw_rule *rule)
607 {
608         struct snd_usb_substream *subs = rule->private;
609         struct list_head *p;
610         struct snd_interval *it = hw_param_interval(params, SNDRV_PCM_HW_PARAM_CHANNELS);
611         unsigned int rmin, rmax;
612         int changed;
613
614         hwc_debug("hw_rule_channels: (%d,%d)\n", it->min, it->max);
615         changed = 0;
616         rmin = rmax = 0;
617         list_for_each(p, &subs->fmt_list) {
618                 struct audioformat *fp;
619                 fp = list_entry(p, struct audioformat, list);
620                 if (!hw_check_valid_format(subs, params, fp))
621                         continue;
622                 if (changed++) {
623                         if (rmin > fp->channels)
624                                 rmin = fp->channels;
625                         if (rmax < fp->channels)
626                                 rmax = fp->channels;
627                 } else {
628                         rmin = fp->channels;
629                         rmax = fp->channels;
630                 }
631         }
632
633         if (!changed) {
634                 hwc_debug("  --> get empty\n");
635                 it->empty = 1;
636                 return -EINVAL;
637         }
638
639         changed = 0;
640         if (it->min < rmin) {
641                 it->min = rmin;
642                 it->openmin = 0;
643                 changed = 1;
644         }
645         if (it->max > rmax) {
646                 it->max = rmax;
647                 it->openmax = 0;
648                 changed = 1;
649         }
650         if (snd_interval_checkempty(it)) {
651                 it->empty = 1;
652                 return -EINVAL;
653         }
654         hwc_debug("  --> (%d, %d) (changed = %d)\n", it->min, it->max, changed);
655         return changed;
656 }
657
658 static int hw_rule_format(struct snd_pcm_hw_params *params,
659                           struct snd_pcm_hw_rule *rule)
660 {
661         struct snd_usb_substream *subs = rule->private;
662         struct list_head *p;
663         struct snd_mask *fmt = hw_param_mask(params, SNDRV_PCM_HW_PARAM_FORMAT);
664         u64 fbits;
665         u32 oldbits[2];
666         int changed;
667
668         hwc_debug("hw_rule_format: %x:%x\n", fmt->bits[0], fmt->bits[1]);
669         fbits = 0;
670         list_for_each(p, &subs->fmt_list) {
671                 struct audioformat *fp;
672                 fp = list_entry(p, struct audioformat, list);
673                 if (!hw_check_valid_format(subs, params, fp))
674                         continue;
675                 fbits |= fp->formats;
676         }
677
678         oldbits[0] = fmt->bits[0];
679         oldbits[1] = fmt->bits[1];
680         fmt->bits[0] &= (u32)fbits;
681         fmt->bits[1] &= (u32)(fbits >> 32);
682         if (!fmt->bits[0] && !fmt->bits[1]) {
683                 hwc_debug("  --> get empty\n");
684                 return -EINVAL;
685         }
686         changed = (oldbits[0] != fmt->bits[0] || oldbits[1] != fmt->bits[1]);
687         hwc_debug("  --> %x:%x (changed = %d)\n", fmt->bits[0], fmt->bits[1], changed);
688         return changed;
689 }
690
691 static int hw_rule_period_time(struct snd_pcm_hw_params *params,
692                                struct snd_pcm_hw_rule *rule)
693 {
694         struct snd_usb_substream *subs = rule->private;
695         struct audioformat *fp;
696         struct snd_interval *it;
697         unsigned char min_datainterval;
698         unsigned int pmin;
699         int changed;
700
701         it = hw_param_interval(params, SNDRV_PCM_HW_PARAM_PERIOD_TIME);
702         hwc_debug("hw_rule_period_time: (%u,%u)\n", it->min, it->max);
703         min_datainterval = 0xff;
704         list_for_each_entry(fp, &subs->fmt_list, list) {
705                 if (!hw_check_valid_format(subs, params, fp))
706                         continue;
707                 min_datainterval = min(min_datainterval, fp->datainterval);
708         }
709         if (min_datainterval == 0xff) {
710                 hwc_debug("  --> get emtpy\n");
711                 it->empty = 1;
712                 return -EINVAL;
713         }
714         pmin = 125 * (1 << min_datainterval);
715         changed = 0;
716         if (it->min < pmin) {
717                 it->min = pmin;
718                 it->openmin = 0;
719                 changed = 1;
720         }
721         if (snd_interval_checkempty(it)) {
722                 it->empty = 1;
723                 return -EINVAL;
724         }
725         hwc_debug("  --> (%u,%u) (changed = %d)\n", it->min, it->max, changed);
726         return changed;
727 }
728
729 /*
730  *  If the device supports unusual bit rates, does the request meet these?
731  */
732 static int snd_usb_pcm_check_knot(struct snd_pcm_runtime *runtime,
733                                   struct snd_usb_substream *subs)
734 {
735         struct audioformat *fp;
736         int count = 0, needs_knot = 0;
737         int err;
738
739         list_for_each_entry(fp, &subs->fmt_list, list) {
740                 if (fp->rates & SNDRV_PCM_RATE_CONTINUOUS)
741                         return 0;
742                 count += fp->nr_rates;
743                 if (fp->rates & SNDRV_PCM_RATE_KNOT)
744                         needs_knot = 1;
745         }
746         if (!needs_knot)
747                 return 0;
748
749         subs->rate_list.count = count;
750         subs->rate_list.list = kmalloc(sizeof(int) * count, GFP_KERNEL);
751         subs->rate_list.mask = 0;
752         count = 0;
753         list_for_each_entry(fp, &subs->fmt_list, list) {
754                 int i;
755                 for (i = 0; i < fp->nr_rates; i++)
756                         subs->rate_list.list[count++] = fp->rate_table[i];
757         }
758         err = snd_pcm_hw_constraint_list(runtime, 0, SNDRV_PCM_HW_PARAM_RATE,
759                                          &subs->rate_list);
760         if (err < 0)
761                 return err;
762
763         return 0;
764 }
765
766
767 /*
768  * set up the runtime hardware information.
769  */
770
771 static int setup_hw_info(struct snd_pcm_runtime *runtime, struct snd_usb_substream *subs)
772 {
773         struct list_head *p;
774         unsigned int pt, ptmin;
775         int param_period_time_if_needed;
776         int err;
777
778         runtime->hw.formats = subs->formats;
779
780         runtime->hw.rate_min = 0x7fffffff;
781         runtime->hw.rate_max = 0;
782         runtime->hw.channels_min = 256;
783         runtime->hw.channels_max = 0;
784         runtime->hw.rates = 0;
785         ptmin = UINT_MAX;
786         /* check min/max rates and channels */
787         list_for_each(p, &subs->fmt_list) {
788                 struct audioformat *fp;
789                 fp = list_entry(p, struct audioformat, list);
790                 runtime->hw.rates |= fp->rates;
791                 if (runtime->hw.rate_min > fp->rate_min)
792                         runtime->hw.rate_min = fp->rate_min;
793                 if (runtime->hw.rate_max < fp->rate_max)
794                         runtime->hw.rate_max = fp->rate_max;
795                 if (runtime->hw.channels_min > fp->channels)
796                         runtime->hw.channels_min = fp->channels;
797                 if (runtime->hw.channels_max < fp->channels)
798                         runtime->hw.channels_max = fp->channels;
799                 if (fp->fmt_type == UAC_FORMAT_TYPE_II && fp->frame_size > 0) {
800                         /* FIXME: there might be more than one audio formats... */
801                         runtime->hw.period_bytes_min = runtime->hw.period_bytes_max =
802                                 fp->frame_size;
803                 }
804                 pt = 125 * (1 << fp->datainterval);
805                 ptmin = min(ptmin, pt);
806         }
807
808         param_period_time_if_needed = SNDRV_PCM_HW_PARAM_PERIOD_TIME;
809         if (snd_usb_get_speed(subs->dev) != USB_SPEED_HIGH)
810                 /* full speed devices have fixed data packet interval */
811                 ptmin = 1000;
812         if (ptmin == 1000)
813                 /* if period time doesn't go below 1 ms, no rules needed */
814                 param_period_time_if_needed = -1;
815         snd_pcm_hw_constraint_minmax(runtime, SNDRV_PCM_HW_PARAM_PERIOD_TIME,
816                                      ptmin, UINT_MAX);
817
818         if ((err = snd_pcm_hw_rule_add(runtime, 0, SNDRV_PCM_HW_PARAM_RATE,
819                                        hw_rule_rate, subs,
820                                        SNDRV_PCM_HW_PARAM_FORMAT,
821                                        SNDRV_PCM_HW_PARAM_CHANNELS,
822                                        param_period_time_if_needed,
823                                        -1)) < 0)
824                 return err;
825         if ((err = snd_pcm_hw_rule_add(runtime, 0, SNDRV_PCM_HW_PARAM_CHANNELS,
826                                        hw_rule_channels, subs,
827                                        SNDRV_PCM_HW_PARAM_FORMAT,
828                                        SNDRV_PCM_HW_PARAM_RATE,
829                                        param_period_time_if_needed,
830                                        -1)) < 0)
831                 return err;
832         if ((err = snd_pcm_hw_rule_add(runtime, 0, SNDRV_PCM_HW_PARAM_FORMAT,
833                                        hw_rule_format, subs,
834                                        SNDRV_PCM_HW_PARAM_RATE,
835                                        SNDRV_PCM_HW_PARAM_CHANNELS,
836                                        param_period_time_if_needed,
837                                        -1)) < 0)
838                 return err;
839         if (param_period_time_if_needed >= 0) {
840                 err = snd_pcm_hw_rule_add(runtime, 0,
841                                           SNDRV_PCM_HW_PARAM_PERIOD_TIME,
842                                           hw_rule_period_time, subs,
843                                           SNDRV_PCM_HW_PARAM_FORMAT,
844                                           SNDRV_PCM_HW_PARAM_CHANNELS,
845                                           SNDRV_PCM_HW_PARAM_RATE,
846                                           -1);
847                 if (err < 0)
848                         return err;
849         }
850         if ((err = snd_usb_pcm_check_knot(runtime, subs)) < 0)
851                 return err;
852         return 0;
853 }
854
855 static int snd_usb_pcm_open(struct snd_pcm_substream *substream, int direction)
856 {
857         struct snd_usb_stream *as = snd_pcm_substream_chip(substream);
858         struct snd_pcm_runtime *runtime = substream->runtime;
859         struct snd_usb_substream *subs = &as->substream[direction];
860
861         subs->interface = -1;
862         subs->altset_idx = 0;
863         runtime->hw = snd_usb_hardware;
864         runtime->private_data = subs;
865         subs->pcm_substream = substream;
866         return setup_hw_info(runtime, subs);
867 }
868
869 static int snd_usb_pcm_close(struct snd_pcm_substream *substream, int direction)
870 {
871         struct snd_usb_stream *as = snd_pcm_substream_chip(substream);
872         struct snd_usb_substream *subs = &as->substream[direction];
873
874         if (!as->chip->shutdown && subs->interface >= 0) {
875                 usb_set_interface(subs->dev, subs->interface, 0);
876                 subs->interface = -1;
877         }
878         subs->pcm_substream = NULL;
879         return 0;
880 }
881
882 static int snd_usb_playback_open(struct snd_pcm_substream *substream)
883 {
884         return snd_usb_pcm_open(substream, SNDRV_PCM_STREAM_PLAYBACK);
885 }
886
887 static int snd_usb_playback_close(struct snd_pcm_substream *substream)
888 {
889         return snd_usb_pcm_close(substream, SNDRV_PCM_STREAM_PLAYBACK);
890 }
891
892 static int snd_usb_capture_open(struct snd_pcm_substream *substream)
893 {
894         return snd_usb_pcm_open(substream, SNDRV_PCM_STREAM_CAPTURE);
895 }
896
897 static int snd_usb_capture_close(struct snd_pcm_substream *substream)
898 {
899         return snd_usb_pcm_close(substream, SNDRV_PCM_STREAM_CAPTURE);
900 }
901
902 static struct snd_pcm_ops snd_usb_playback_ops = {
903         .open =         snd_usb_playback_open,
904         .close =        snd_usb_playback_close,
905         .ioctl =        snd_pcm_lib_ioctl,
906         .hw_params =    snd_usb_hw_params,
907         .hw_free =      snd_usb_hw_free,
908         .prepare =      snd_usb_pcm_prepare,
909         .trigger =      snd_usb_substream_playback_trigger,
910         .pointer =      snd_usb_pcm_pointer,
911         .page =         snd_pcm_lib_get_vmalloc_page,
912         .mmap =         snd_pcm_lib_mmap_vmalloc,
913 };
914
915 static struct snd_pcm_ops snd_usb_capture_ops = {
916         .open =         snd_usb_capture_open,
917         .close =        snd_usb_capture_close,
918         .ioctl =        snd_pcm_lib_ioctl,
919         .hw_params =    snd_usb_hw_params,
920         .hw_free =      snd_usb_hw_free,
921         .prepare =      snd_usb_pcm_prepare,
922         .trigger =      snd_usb_substream_capture_trigger,
923         .pointer =      snd_usb_pcm_pointer,
924         .page =         snd_pcm_lib_get_vmalloc_page,
925         .mmap =         snd_pcm_lib_mmap_vmalloc,
926 };
927
928 void snd_usb_set_pcm_ops(struct snd_pcm *pcm, int stream)
929 {
930         snd_pcm_set_ops(pcm, stream,
931                         stream == SNDRV_PCM_STREAM_PLAYBACK ?
932                         &snd_usb_playback_ops : &snd_usb_capture_ops);
933 }