~ [ source navigation ] ~ [ diff markup ] ~ [ identifier search ] ~

TOMOYO Linux Cross Reference
Linux/sound/usb/pcm.c

Version: ~ [ linux-5.10-rc5 ] ~ [ linux-5.9.10 ] ~ [ linux-5.8.18 ] ~ [ linux-5.7.19 ] ~ [ linux-5.6.19 ] ~ [ linux-5.5.19 ] ~ [ linux-5.4.79 ] ~ [ linux-5.3.18 ] ~ [ linux-5.2.21 ] ~ [ linux-5.1.21 ] ~ [ linux-5.0.21 ] ~ [ linux-4.20.17 ] ~ [ linux-4.19.159 ] ~ [ linux-4.18.20 ] ~ [ linux-4.17.19 ] ~ [ linux-4.16.18 ] ~ [ linux-4.15.18 ] ~ [ linux-4.14.208 ] ~ [ linux-4.13.16 ] ~ [ linux-4.12.14 ] ~ [ linux-4.11.12 ] ~ [ linux-4.10.17 ] ~ [ linux-4.9.245 ] ~ [ linux-4.8.17 ] ~ [ linux-4.7.10 ] ~ [ linux-4.6.7 ] ~ [ linux-4.5.7 ] ~ [ linux-4.4.245 ] ~ [ linux-4.3.6 ] ~ [ linux-4.2.8 ] ~ [ linux-4.1.52 ] ~ [ linux-4.0.9 ] ~ [ linux-3.19.8 ] ~ [ linux-3.18.140 ] ~ [ linux-3.17.8 ] ~ [ linux-3.16.85 ] ~ [ linux-3.15.10 ] ~ [ linux-3.14.79 ] ~ [ linux-3.13.11 ] ~ [ linux-3.12.74 ] ~ [ linux-3.11.10 ] ~ [ linux-3.10.108 ] ~ [ linux-2.6.32.71 ] ~ [ linux-2.6.0 ] ~ [ linux-2.4.37.11 ] ~ [ unix-v6-master ] ~ [ ccs-tools-1.8.5 ] ~ [ policy-sample ] ~
Architecture: ~ [ i386 ] ~ [ alpha ] ~ [ m68k ] ~ [ mips ] ~ [ ppc ] ~ [ sparc ] ~ [ sparc64 ] ~

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

~ [ source navigation ] ~ [ diff markup ] ~ [ identifier search ] ~

kernel.org | git.kernel.org | LWN.net | Project Home | Wiki (Japanese) | Wiki (English) | SVN repository | Mail admin

Linux® is a registered trademark of Linus Torvalds in the United States and other countries.
TOMOYO® is a registered trademark of NTT DATA CORPORATION.

osdn.jp