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