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

~ [ 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