pcm.c 40.3 KB
Newer Older
Daniel Mack's avatar
Daniel Mack committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
/*
 *   This program is free software; you can redistribute it and/or modify
 *   it under the terms of the GNU General Public License as published by
 *   the Free Software Foundation; either version 2 of the License, or
 *   (at your option) any later version.
 *
 *   This program is distributed in the hope that it will be useful,
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *   GNU General Public License for more details.
 *
 *   You should have received a copy of the GNU General Public License
 *   along with this program; if not, write to the Free Software
 *   Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307 USA
 */

#include <linux/init.h>
18
#include <linux/slab.h>
19
#include <linux/ratelimit.h>
Daniel Mack's avatar
Daniel Mack committed
20 21
#include <linux/usb.h>
#include <linux/usb/audio.h>
Daniel Mack's avatar
Daniel Mack committed
22
#include <linux/usb/audio-v2.h>
Daniel Mack's avatar
Daniel Mack committed
23 24 25 26 27 28 29 30 31

#include <sound/core.h>
#include <sound/pcm.h>
#include <sound/pcm_params.h>

#include "usbaudio.h"
#include "card.h"
#include "quirks.h"
#include "debug.h"
32
#include "endpoint.h"
Daniel Mack's avatar
Daniel Mack committed
33 34
#include "helper.h"
#include "pcm.h"
35
#include "clock.h"
36
#include "power.h"
Daniel Mack's avatar
Daniel Mack committed
37

38 39 40
#define SUBSTREAM_FLAG_DATA_EP_STARTED	0
#define SUBSTREAM_FLAG_SYNC_EP_STARTED	1

41 42 43 44 45 46 47 48
/* return the estimated delay based on USB frame counters */
snd_pcm_uframes_t snd_usb_pcm_delay(struct snd_usb_substream *subs,
				    unsigned int rate)
{
	int current_frame_number;
	int frame_diff;
	int est_delay;

49 50 51
	if (!subs->last_delay)
		return 0; /* short path */

52 53 54 55 56 57 58 59 60 61
	current_frame_number = usb_get_current_frame_number(subs->dev);
	/*
	 * HCD implementations use different widths, use lower 8 bits.
	 * The delay will be managed up to 256ms, which is more than
	 * enough
	 */
	frame_diff = (current_frame_number - subs->last_frame_number) & 0xff;

	/* Approximation based on number of samples per USB frame (ms),
	   some truncation for 44.1 but the estimate is good enough */
62 63 64 65 66 67
	est_delay =  frame_diff * rate / 1000;
	if (subs->direction == SNDRV_PCM_STREAM_PLAYBACK)
		est_delay = subs->last_delay - est_delay;
	else
		est_delay = subs->last_delay + est_delay;

68 69 70 71 72
	if (est_delay < 0)
		est_delay = 0;
	return est_delay;
}

Daniel Mack's avatar
Daniel Mack committed
73 74 75 76 77 78 79 80 81
/*
 * return the current pcm pointer.  just based on the hwptr_done value.
 */
static snd_pcm_uframes_t snd_usb_pcm_pointer(struct snd_pcm_substream *substream)
{
	struct snd_usb_substream *subs;
	unsigned int hwptr_done;

	subs = (struct snd_usb_substream *)substream->runtime->private_data;
82 83
	if (subs->stream->chip->shutdown)
		return SNDRV_PCM_POS_XRUN;
Daniel Mack's avatar
Daniel Mack committed
84 85
	spin_lock(&subs->lock);
	hwptr_done = subs->hwptr_done;
86
	substream->runtime->delay = snd_usb_pcm_delay(subs,
87
						substream->runtime->rate);
Daniel Mack's avatar
Daniel Mack committed
88 89 90 91 92 93 94
	spin_unlock(&subs->lock);
	return hwptr_done / (substream->runtime->frame_bits >> 3);
}

/*
 * find a matching audio format
 */
95
static struct audioformat *find_format(struct snd_usb_substream *subs)
Daniel Mack's avatar
Daniel Mack committed
96
{
97
	struct audioformat *fp;
Daniel Mack's avatar
Daniel Mack committed
98 99 100
	struct audioformat *found = NULL;
	int cur_attr = 0, attr;

101
	list_for_each_entry(fp, &subs->fmt_list, list) {
102
		if (!(fp->formats & (1uLL << subs->pcm_format)))
103
			continue;
104
		if (fp->channels != subs->channels)
Daniel Mack's avatar
Daniel Mack committed
105
			continue;
106 107
		if (subs->cur_rate < fp->rate_min ||
		    subs->cur_rate > fp->rate_max)
Daniel Mack's avatar
Daniel Mack committed
108 109 110 111
			continue;
		if (! (fp->rates & SNDRV_PCM_RATE_CONTINUOUS)) {
			unsigned int i;
			for (i = 0; i < fp->nr_rates; i++)
112
				if (fp->rate_table[i] == subs->cur_rate)
Daniel Mack's avatar
Daniel Mack committed
113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151
					break;
			if (i >= fp->nr_rates)
				continue;
		}
		attr = fp->ep_attr & USB_ENDPOINT_SYNCTYPE;
		if (! found) {
			found = fp;
			cur_attr = attr;
			continue;
		}
		/* avoid async out and adaptive in if the other method
		 * supports the same format.
		 * this is a workaround for the case like
		 * M-audio audiophile USB.
		 */
		if (attr != cur_attr) {
			if ((attr == USB_ENDPOINT_SYNC_ASYNC &&
			     subs->direction == SNDRV_PCM_STREAM_PLAYBACK) ||
			    (attr == USB_ENDPOINT_SYNC_ADAPTIVE &&
			     subs->direction == SNDRV_PCM_STREAM_CAPTURE))
				continue;
			if ((cur_attr == USB_ENDPOINT_SYNC_ASYNC &&
			     subs->direction == SNDRV_PCM_STREAM_PLAYBACK) ||
			    (cur_attr == USB_ENDPOINT_SYNC_ADAPTIVE &&
			     subs->direction == SNDRV_PCM_STREAM_CAPTURE)) {
				found = fp;
				cur_attr = attr;
				continue;
			}
		}
		/* find the format with the largest max. packet size */
		if (fp->maxpacksize > found->maxpacksize) {
			found = fp;
			cur_attr = attr;
		}
	}
	return found;
}

152 153 154 155 156 157 158 159 160 161 162 163 164 165 166
static int init_pitch_v1(struct snd_usb_audio *chip, int iface,
			 struct usb_host_interface *alts,
			 struct audioformat *fmt)
{
	struct usb_device *dev = chip->dev;
	unsigned int ep;
	unsigned char data[1];
	int err;

	ep = get_endpoint(alts, 0)->bEndpointAddress;

	data[0] = 1;
	if ((err = snd_usb_ctl_msg(dev, usb_sndctrlpipe(dev, 0), UAC_SET_CUR,
				   USB_TYPE_CLASS|USB_RECIP_ENDPOINT|USB_DIR_OUT,
				   UAC_EP_CS_ATTR_PITCH_CONTROL << 8, ep,
167
				   data, sizeof(data))) < 0) {
168 169 170 171 172 173 174
		snd_printk(KERN_ERR "%d:%d:%d: cannot set enable PITCH\n",
			   dev->devnum, iface, ep);
		return err;
	}

	return 0;
}
Daniel Mack's avatar
Daniel Mack committed
175

176 177 178 179 180 181 182 183 184 185 186 187
static int init_pitch_v2(struct snd_usb_audio *chip, int iface,
			 struct usb_host_interface *alts,
			 struct audioformat *fmt)
{
	struct usb_device *dev = chip->dev;
	unsigned char data[1];
	int err;

	data[0] = 1;
	if ((err = snd_usb_ctl_msg(dev, usb_sndctrlpipe(dev, 0), UAC2_CS_CUR,
				   USB_TYPE_CLASS | USB_RECIP_ENDPOINT | USB_DIR_OUT,
				   UAC2_EP_CS_PITCH << 8, 0,
188
				   data, sizeof(data))) < 0) {
189 190 191 192 193 194 195 196
		snd_printk(KERN_ERR "%d:%d:%d: cannot set enable PITCH (v2)\n",
			   dev->devnum, iface, fmt->altsetting);
		return err;
	}

	return 0;
}

Daniel Mack's avatar
Daniel Mack committed
197
/*
198
 * initialize the pitch control and sample rate
Daniel Mack's avatar
Daniel Mack committed
199
 */
200
int snd_usb_init_pitch(struct snd_usb_audio *chip, int iface,
Daniel Mack's avatar
Daniel Mack committed
201 202 203
		       struct usb_host_interface *alts,
		       struct audioformat *fmt)
{
204 205
	struct usb_interface_descriptor *altsd = get_iface_desc(alts);

206 207 208 209
	/* if endpoint doesn't have pitch control, bail out */
	if (!(fmt->attributes & UAC_EP_CS_ATTR_PITCH_CONTROL))
		return 0;

210 211
	switch (altsd->bInterfaceProtocol) {
	case UAC_VERSION_1:
212
	default:
213 214 215
		return init_pitch_v1(chip, iface, alts, fmt);

	case UAC_VERSION_2:
216
		return init_pitch_v2(chip, iface, alts, fmt);
217 218 219
	}
}

220
static int start_endpoints(struct snd_usb_substream *subs, bool can_sleep)
221 222 223 224 225 226 227 228 229 230 231 232
{
	int err;

	if (!subs->data_endpoint)
		return -EINVAL;

	if (!test_and_set_bit(SUBSTREAM_FLAG_DATA_EP_STARTED, &subs->flags)) {
		struct snd_usb_endpoint *ep = subs->data_endpoint;

		snd_printdd(KERN_DEBUG "Starting data EP @%p\n", ep);

		ep->data_subs = subs;
233
		err = snd_usb_endpoint_start(ep, can_sleep);
234 235 236 237 238 239 240 241 242 243
		if (err < 0) {
			clear_bit(SUBSTREAM_FLAG_DATA_EP_STARTED, &subs->flags);
			return err;
		}
	}

	if (subs->sync_endpoint &&
	    !test_and_set_bit(SUBSTREAM_FLAG_SYNC_EP_STARTED, &subs->flags)) {
		struct snd_usb_endpoint *ep = subs->sync_endpoint;

244 245 246 247 248 249 250 251 252 253 254 255 256 257 258
		if (subs->data_endpoint->iface != subs->sync_endpoint->iface ||
		    subs->data_endpoint->alt_idx != subs->sync_endpoint->alt_idx) {
			err = usb_set_interface(subs->dev,
						subs->sync_endpoint->iface,
						subs->sync_endpoint->alt_idx);
			if (err < 0) {
				snd_printk(KERN_ERR
					   "%d:%d:%d: cannot set interface (%d)\n",
					   subs->dev->devnum,
					   subs->sync_endpoint->iface,
					   subs->sync_endpoint->alt_idx, err);
				return -EIO;
			}
		}

259 260 261
		snd_printdd(KERN_DEBUG "Starting sync EP @%p\n", ep);

		ep->sync_slave = subs->data_endpoint;
262
		err = snd_usb_endpoint_start(ep, can_sleep);
263 264 265 266 267 268 269 270 271
		if (err < 0) {
			clear_bit(SUBSTREAM_FLAG_SYNC_EP_STARTED, &subs->flags);
			return err;
		}
	}

	return 0;
}

272
static void stop_endpoints(struct snd_usb_substream *subs, bool wait)
273 274
{
	if (test_and_clear_bit(SUBSTREAM_FLAG_SYNC_EP_STARTED, &subs->flags))
275
		snd_usb_endpoint_stop(subs->sync_endpoint);
276 277

	if (test_and_clear_bit(SUBSTREAM_FLAG_DATA_EP_STARTED, &subs->flags))
278 279 280 281 282 283
		snd_usb_endpoint_stop(subs->data_endpoint);

	if (wait) {
		snd_usb_endpoint_sync_pending_stop(subs->sync_endpoint);
		snd_usb_endpoint_sync_pending_stop(subs->data_endpoint);
	}
284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301
}

static int deactivate_endpoints(struct snd_usb_substream *subs)
{
	int reta, retb;

	reta = snd_usb_endpoint_deactivate(subs->sync_endpoint);
	retb = snd_usb_endpoint_deactivate(subs->data_endpoint);

	if (reta < 0)
		return reta;

	if (retb < 0)
		return retb;

	return 0;
}

Daniel Mack's avatar
Daniel Mack committed
302 303 304 305 306 307 308 309 310 311 312
/*
 * find a matching format and set up the interface
 */
static int set_format(struct snd_usb_substream *subs, struct audioformat *fmt)
{
	struct usb_device *dev = subs->dev;
	struct usb_host_interface *alts;
	struct usb_interface_descriptor *altsd;
	struct usb_interface *iface;
	unsigned int ep, attr;
	int is_playback = subs->direction == SNDRV_PCM_STREAM_PLAYBACK;
313
	int err, implicit_fb = 0;
Daniel Mack's avatar
Daniel Mack committed
314 315 316 317 318 319 320 321 322 323 324 325

	iface = usb_ifnum_to_if(dev, fmt->iface);
	if (WARN_ON(!iface))
		return -EINVAL;
	alts = &iface->altsetting[fmt->altset_idx];
	altsd = get_iface_desc(alts);
	if (WARN_ON(altsd->bAlternateSetting != fmt->altsetting))
		return -EINVAL;

	if (fmt == subs->cur_audiofmt)
		return 0;

326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350
	/* close the old interface */
	if (subs->interface >= 0 && subs->interface != fmt->iface) {
		err = usb_set_interface(subs->dev, subs->interface, 0);
		if (err < 0) {
			snd_printk(KERN_ERR "%d:%d:%d: return to setting 0 failed (%d)\n",
				dev->devnum, fmt->iface, fmt->altsetting, err);
			return -EIO;
		}
		subs->interface = -1;
		subs->altset_idx = 0;
	}

	/* set interface */
	if (subs->interface != fmt->iface ||
	    subs->altset_idx != fmt->altset_idx) {
		err = usb_set_interface(dev, fmt->iface, fmt->altsetting);
		if (err < 0) {
			snd_printk(KERN_ERR "%d:%d:%d: usb_set_interface failed (%d)\n",
				   dev->devnum, fmt->iface, fmt->altsetting, err);
			return -EIO;
		}
		snd_printdd(KERN_INFO "setting usb interface %d:%d\n",
				fmt->iface, fmt->altsetting);
		subs->interface = fmt->iface;
		subs->altset_idx = fmt->altset_idx;
351

352
		snd_usb_set_interface_quirk(dev);
353 354
	}

355 356 357 358 359
	subs->data_endpoint = snd_usb_add_endpoint(subs->stream->chip,
						   alts, fmt->endpoint, subs->direction,
						   SND_USB_ENDPOINT_TYPE_DATA);
	if (!subs->data_endpoint)
		return -EINVAL;
Daniel Mack's avatar
Daniel Mack committed
360 361 362 363 364 365 366

	/* we need a sync pipe in async OUT or adaptive IN mode */
	/* check the number of EP, since some devices have broken
	 * descriptors which fool us.  if it has only one EP,
	 * assume it as adaptive-out or sync-in.
	 */
	attr = fmt->ep_attr & USB_ENDPOINT_SYNCTYPE;
367 368

	switch (subs->stream->chip->usb_id) {
369
	case USB_ID(0x0763, 0x2030): /* M-Audio Fast Track C400 */
370
	case USB_ID(0x0763, 0x2031): /* M-Audio Fast Track C600 */
371 372 373 374 375 376 377 378 379 380 381 382
		if (is_playback) {
			implicit_fb = 1;
			ep = 0x81;
			iface = usb_ifnum_to_if(dev, 3);

			if (!iface || iface->num_altsetting == 0)
				return -EINVAL;

			alts = &iface->altsetting[1];
			goto add_sync_ep;
		}
		break;
383 384 385 386
	case USB_ID(0x0763, 0x2080): /* M-Audio FastTrack Ultra */
	case USB_ID(0x0763, 0x2081):
		if (is_playback) {
			implicit_fb = 1;
387 388
			ep = 0x81;
			iface = usb_ifnum_to_if(dev, 2);
389 390 391 392

			if (!iface || iface->num_altsetting == 0)
				return -EINVAL;

393 394 395
			alts = &iface->altsetting[1];
			goto add_sync_ep;
		}
396
	}
397

398 399 400
	if (((is_playback && attr == USB_ENDPOINT_SYNC_ASYNC) ||
	     (!is_playback && attr == USB_ENDPOINT_SYNC_ADAPTIVE)) &&
	    altsd->bNumEndpoints >= 2) {
Daniel Mack's avatar
Daniel Mack committed
401 402 403 404
		/* check sync-pipe endpoint */
		/* ... and check descriptor size before accessing bSynchAddress
		   because there is a version of the SB Audigy 2 NX firmware lacking
		   the audio fields in the endpoint descriptors */
405
		if ((get_endpoint(alts, 1)->bmAttributes & USB_ENDPOINT_XFERTYPE_MASK) != USB_ENDPOINT_XFER_ISOC ||
Daniel Mack's avatar
Daniel Mack committed
406
		    (get_endpoint(alts, 1)->bLength >= USB_DT_ENDPOINT_AUDIO_SIZE &&
407 408
		     get_endpoint(alts, 1)->bSynchAddress != 0 &&
		     !implicit_fb)) {
409 410 411 412 413
			snd_printk(KERN_ERR "%d:%d:%d : invalid sync pipe. bmAttributes %02x, bLength %d, bSynchAddress %02x\n",
				   dev->devnum, fmt->iface, fmt->altsetting,
				   get_endpoint(alts, 1)->bmAttributes,
				   get_endpoint(alts, 1)->bLength,
				   get_endpoint(alts, 1)->bSynchAddress);
Daniel Mack's avatar
Daniel Mack committed
414 415 416
			return -EINVAL;
		}
		ep = get_endpoint(alts, 1)->bEndpointAddress;
417 418
		if (!implicit_fb &&
		    get_endpoint(alts, 0)->bLength >= USB_DT_ENDPOINT_AUDIO_SIZE &&
Daniel Mack's avatar
Daniel Mack committed
419
		    (( is_playback && ep != (unsigned int)(get_endpoint(alts, 0)->bSynchAddress | USB_DIR_IN)) ||
420 421 422 423
		     (!is_playback && ep != (unsigned int)(get_endpoint(alts, 0)->bSynchAddress & ~USB_DIR_IN)))) {
			snd_printk(KERN_ERR "%d:%d:%d : invalid sync pipe. is_playback %d, ep %02x, bSynchAddress %02x\n",
				   dev->devnum, fmt->iface, fmt->altsetting,
				   is_playback, ep, get_endpoint(alts, 0)->bSynchAddress);
Daniel Mack's avatar
Daniel Mack committed
424 425
			return -EINVAL;
		}
426 427 428 429

		implicit_fb = (get_endpoint(alts, 1)->bmAttributes & USB_ENDPOINT_USAGE_MASK)
				== USB_ENDPOINT_USAGE_IMPLICIT_FB;

430 431 432
add_sync_ep:
		subs->sync_endpoint = snd_usb_add_endpoint(subs->stream->chip,
							   alts, ep, !subs->direction,
433 434 435
							   implicit_fb ?
								SND_USB_ENDPOINT_TYPE_DATA :
								SND_USB_ENDPOINT_TYPE_SYNC);
436 437 438 439 440
		if (!subs->sync_endpoint)
			return -EINVAL;

		subs->data_endpoint->sync_master = subs->sync_endpoint;
	}
Daniel Mack's avatar
Daniel Mack committed
441

442
	if ((err = snd_usb_init_pitch(subs->stream->chip, fmt->iface, alts, fmt)) < 0)
Daniel Mack's avatar
Daniel Mack committed
443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460
		return err;

	subs->cur_audiofmt = fmt;

	snd_usb_set_format_quirk(subs, fmt);

#if 0
	printk(KERN_DEBUG
	       "setting done: format = %d, rate = %d..%d, channels = %d\n",
	       fmt->format, fmt->rate_min, fmt->rate_max, fmt->channels);
	printk(KERN_DEBUG
	       "  datapipe = 0x%0x, syncpipe = 0x%0x\n",
	       subs->datapipe, subs->syncpipe);
#endif

	return 0;
}

461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518
/*
 * Return the score of matching two audioformats.
 * Veto the audioformat if:
 * - It has no channels for some reason.
 * - Requested PCM format is not supported.
 * - Requested sample rate is not supported.
 */
static int match_endpoint_audioformats(struct audioformat *fp,
	struct audioformat *match, int rate,
	snd_pcm_format_t pcm_format)
{
	int i;
	int score = 0;

	if (fp->channels < 1) {
		snd_printdd("%s: (fmt @%p) no channels\n", __func__, fp);
		return 0;
	}

	if (!(fp->formats & (1ULL << pcm_format))) {
		snd_printdd("%s: (fmt @%p) no match for format %d\n", __func__,
			fp, pcm_format);
		return 0;
	}

	for (i = 0; i < fp->nr_rates; i++) {
		if (fp->rate_table[i] == rate) {
			score++;
			break;
		}
	}
	if (!score) {
		snd_printdd("%s: (fmt @%p) no match for rate %d\n", __func__,
			fp, rate);
		return 0;
	}

	if (fp->channels == match->channels)
		score++;

	snd_printdd("%s: (fmt @%p) score %d\n", __func__, fp, score);

	return score;
}

/*
 * Configure the sync ep using the rate and pcm format of the data ep.
 */
static int configure_sync_endpoint(struct snd_usb_substream *subs)
{
	int ret;
	struct audioformat *fp;
	struct audioformat *sync_fp = NULL;
	int cur_score = 0;
	int sync_period_bytes = subs->period_bytes;
	struct snd_usb_substream *sync_subs =
		&subs->stream->substream[subs->direction ^ 1];

519 520 521 522 523 524 525 526 527 528
	if (subs->sync_endpoint->type != SND_USB_ENDPOINT_TYPE_DATA ||
	    !subs->stream)
		return snd_usb_endpoint_set_params(subs->sync_endpoint,
						   subs->pcm_format,
						   subs->channels,
						   subs->period_bytes,
						   subs->cur_rate,
						   subs->cur_audiofmt,
						   NULL);

529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567
	/* Try to find the best matching audioformat. */
	list_for_each_entry(fp, &sync_subs->fmt_list, list) {
		int score = match_endpoint_audioformats(fp, subs->cur_audiofmt,
			subs->cur_rate, subs->pcm_format);

		if (score > cur_score) {
			sync_fp = fp;
			cur_score = score;
		}
	}

	if (unlikely(sync_fp == NULL)) {
		snd_printk(KERN_ERR "%s: no valid audioformat for sync ep %x found\n",
			__func__, sync_subs->ep_num);
		return -EINVAL;
	}

	/*
	 * Recalculate the period bytes if channel number differ between
	 * data and sync ep audioformat.
	 */
	if (sync_fp->channels != subs->channels) {
		sync_period_bytes = (subs->period_bytes / subs->channels) *
			sync_fp->channels;
		snd_printdd("%s: adjusted sync ep period bytes (%d -> %d)\n",
			__func__, subs->period_bytes, sync_period_bytes);
	}

	ret = snd_usb_endpoint_set_params(subs->sync_endpoint,
					  subs->pcm_format,
					  sync_fp->channels,
					  sync_period_bytes,
					  subs->cur_rate,
					  sync_fp,
					  NULL);

	return ret;
}

568 569 570 571 572 573 574 575 576 577
/*
 * configure endpoint params
 *
 * called  during initial setup and upon resume
 */
static int configure_endpoint(struct snd_usb_substream *subs)
{
	int ret;

	/* format changed */
578
	stop_endpoints(subs, true);
579 580 581 582 583 584 585 586
	ret = snd_usb_endpoint_set_params(subs->data_endpoint,
					  subs->pcm_format,
					  subs->channels,
					  subs->period_bytes,
					  subs->cur_rate,
					  subs->cur_audiofmt,
					  subs->sync_endpoint);
	if (ret < 0)
587
		return ret;
588 589

	if (subs->sync_endpoint)
590 591
		ret = configure_sync_endpoint(subs);

592 593 594
	return ret;
}

Daniel Mack's avatar
Daniel Mack committed
595 596 597 598 599 600 601 602 603 604 605 606 607 608 609
/*
 * hw_params callback
 *
 * allocate a buffer and set the given audio format.
 *
 * so far we use a physically linear buffer although packetize transfer
 * doesn't need a continuous area.
 * if sg buffer is supported on the later version of alsa, we'll follow
 * that.
 */
static int snd_usb_hw_params(struct snd_pcm_substream *substream,
			     struct snd_pcm_hw_params *hw_params)
{
	struct snd_usb_substream *subs = substream->runtime->private_data;
	struct audioformat *fmt;
610
	int ret;
Daniel Mack's avatar
Daniel Mack committed
611 612 613 614 615 616

	ret = snd_pcm_lib_alloc_vmalloc_buffer(substream,
					       params_buffer_bytes(hw_params));
	if (ret < 0)
		return ret;

617 618 619 620 621 622
	subs->pcm_format = params_format(hw_params);
	subs->period_bytes = params_period_bytes(hw_params);
	subs->channels = params_channels(hw_params);
	subs->cur_rate = params_rate(hw_params);

	fmt = find_format(subs);
Daniel Mack's avatar
Daniel Mack committed
623 624
	if (!fmt) {
		snd_printd(KERN_DEBUG "cannot set format: format = %#x, rate = %d, channels = %d\n",
625
			   subs->pcm_format, subs->cur_rate, subs->channels);
Daniel Mack's avatar
Daniel Mack committed
626 627 628
		return -EINVAL;
	}

629
	down_read(&subs->stream->chip->shutdown_rwsem);
630 631 632 633
	if (subs->stream->chip->shutdown)
		ret = -ENODEV;
	else
		ret = set_format(subs, fmt);
634
	up_read(&subs->stream->chip->shutdown_rwsem);
635
	if (ret < 0)
Daniel Mack's avatar
Daniel Mack committed
636 637
		return ret;

638 639
	subs->interface = fmt->iface;
	subs->altset_idx = fmt->altset_idx;
640
	subs->need_setup_ep = true;
641

642
	return 0;
Daniel Mack's avatar
Daniel Mack committed
643 644 645 646 647 648 649 650 651 652 653 654 655 656
}

/*
 * hw_free callback
 *
 * reset the audio format and release the buffer
 */
static int snd_usb_hw_free(struct snd_pcm_substream *substream)
{
	struct snd_usb_substream *subs = substream->runtime->private_data;

	subs->cur_audiofmt = NULL;
	subs->cur_rate = 0;
	subs->period_bytes = 0;
657
	down_read(&subs->stream->chip->shutdown_rwsem);
658
	if (!subs->stream->chip->shutdown) {
659
		stop_endpoints(subs, true);
660 661
		deactivate_endpoints(subs);
	}
662
	up_read(&subs->stream->chip->shutdown_rwsem);
Daniel Mack's avatar
Daniel Mack committed
663 664 665 666 667 668 669 670 671 672 673 674
	return snd_pcm_lib_free_vmalloc_buffer(substream);
}

/*
 * prepare callback
 *
 * only a few subtle things...
 */
static int snd_usb_pcm_prepare(struct snd_pcm_substream *substream)
{
	struct snd_pcm_runtime *runtime = substream->runtime;
	struct snd_usb_substream *subs = runtime->private_data;
675 676 677
	struct usb_host_interface *alts;
	struct usb_interface *iface;
	int ret;
Daniel Mack's avatar
Daniel Mack committed
678 679 680 681 682 683

	if (! subs->cur_audiofmt) {
		snd_printk(KERN_ERR "usbaudio: no format is specified!\n");
		return -ENXIO;
	}

684
	down_read(&subs->stream->chip->shutdown_rwsem);
685 686 687 688 689 690 691 692
	if (subs->stream->chip->shutdown) {
		ret = -ENODEV;
		goto unlock;
	}
	if (snd_BUG_ON(!subs->data_endpoint)) {
		ret = -EIO;
		goto unlock;
	}
693

694 695 696
	snd_usb_endpoint_sync_pending_stop(subs->sync_endpoint);
	snd_usb_endpoint_sync_pending_stop(subs->data_endpoint);

697 698
	ret = set_format(subs, subs->cur_audiofmt);
	if (ret < 0)
699
		goto unlock;
700 701 702 703 704 705 706 707 708

	iface = usb_ifnum_to_if(subs->dev, subs->cur_audiofmt->iface);
	alts = &iface->altsetting[subs->cur_audiofmt->altset_idx];
	ret = snd_usb_init_sample_rate(subs->stream->chip,
				       subs->cur_audiofmt->iface,
				       alts,
				       subs->cur_audiofmt,
				       subs->cur_rate);
	if (ret < 0)
709
		goto unlock;
710

711 712 713
	if (subs->need_setup_ep) {
		ret = configure_endpoint(subs);
		if (ret < 0)
714
			goto unlock;
715 716
		subs->need_setup_ep = false;
	}
717

Daniel Mack's avatar
Daniel Mack committed
718
	/* some unit conversions in runtime */
719 720 721 722
	subs->data_endpoint->maxframesize =
		bytes_to_frames(runtime, subs->data_endpoint->maxpacksize);
	subs->data_endpoint->curframesize =
		bytes_to_frames(runtime, subs->data_endpoint->curpacksize);
Daniel Mack's avatar
Daniel Mack committed
723 724 725 726

	/* reset the pointer */
	subs->hwptr_done = 0;
	subs->transfer_done = 0;
727 728
	subs->last_delay = 0;
	subs->last_frame_number = 0;
Daniel Mack's avatar
Daniel Mack committed
729 730
	runtime->delay = 0;

731 732 733
	/* for playback, submit the URBs now; otherwise, the first hwptr_done
	 * updates for all URBs would happen at the same time when starting */
	if (subs->direction == SNDRV_PCM_STREAM_PLAYBACK)
734
		ret = start_endpoints(subs, true);
735

736
 unlock:
737
	up_read(&subs->stream->chip->shutdown_rwsem);
738
	return ret;
Daniel Mack's avatar
Daniel Mack committed
739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763
}

static struct snd_pcm_hardware snd_usb_hardware =
{
	.info =			SNDRV_PCM_INFO_MMAP |
				SNDRV_PCM_INFO_MMAP_VALID |
				SNDRV_PCM_INFO_BATCH |
				SNDRV_PCM_INFO_INTERLEAVED |
				SNDRV_PCM_INFO_BLOCK_TRANSFER |
				SNDRV_PCM_INFO_PAUSE,
	.buffer_bytes_max =	1024 * 1024,
	.period_bytes_min =	64,
	.period_bytes_max =	512 * 1024,
	.periods_min =		2,
	.periods_max =		1024,
};

static int hw_check_valid_format(struct snd_usb_substream *subs,
				 struct snd_pcm_hw_params *params,
				 struct audioformat *fp)
{
	struct snd_interval *it = hw_param_interval(params, SNDRV_PCM_HW_PARAM_RATE);
	struct snd_interval *ct = hw_param_interval(params, SNDRV_PCM_HW_PARAM_CHANNELS);
	struct snd_mask *fmts = hw_param_mask(params, SNDRV_PCM_HW_PARAM_FORMAT);
	struct snd_interval *pt = hw_param_interval(params, SNDRV_PCM_HW_PARAM_PERIOD_TIME);
764
	struct snd_mask check_fmts;
Daniel Mack's avatar
Daniel Mack committed
765 766 767
	unsigned int ptime;

	/* check the format */
768 769 770 771 772
	snd_mask_none(&check_fmts);
	check_fmts.bits[0] = (u32)fp->formats;
	check_fmts.bits[1] = (u32)(fp->formats >> 32);
	snd_mask_intersect(&check_fmts, fmts);
	if (snd_mask_empty(&check_fmts)) {
Daniel Mack's avatar
Daniel Mack committed
773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790
		hwc_debug("   > check: no supported format %d\n", fp->format);
		return 0;
	}
	/* check the channels */
	if (fp->channels < ct->min || fp->channels > ct->max) {
		hwc_debug("   > check: no valid channels %d (%d/%d)\n", fp->channels, ct->min, ct->max);
		return 0;
	}
	/* check the rate is within the range */
	if (fp->rate_min > it->max || (fp->rate_min == it->max && it->openmax)) {
		hwc_debug("   > check: rate_min %d > max %d\n", fp->rate_min, it->max);
		return 0;
	}
	if (fp->rate_max < it->min || (fp->rate_max == it->min && it->openmin)) {
		hwc_debug("   > check: rate_max %d < min %d\n", fp->rate_max, it->min);
		return 0;
	}
	/* check whether the period time is >= the data packet interval */
791
	if (subs->speed != USB_SPEED_FULL) {
Daniel Mack's avatar
Daniel Mack committed
792 793 794 795 796 797 798 799 800 801 802 803 804
		ptime = 125 * (1 << fp->datainterval);
		if (ptime > pt->max || (ptime == pt->max && pt->openmax)) {
			hwc_debug("   > check: ptime %u > max %u\n", ptime, pt->max);
			return 0;
		}
	}
	return 1;
}

static int hw_rule_rate(struct snd_pcm_hw_params *params,
			struct snd_pcm_hw_rule *rule)
{
	struct snd_usb_substream *subs = rule->private;
805
	struct audioformat *fp;
Daniel Mack's avatar
Daniel Mack committed
806 807 808 809 810 811 812
	struct snd_interval *it = hw_param_interval(params, SNDRV_PCM_HW_PARAM_RATE);
	unsigned int rmin, rmax;
	int changed;

	hwc_debug("hw_rule_rate: (%d,%d)\n", it->min, it->max);
	changed = 0;
	rmin = rmax = 0;
813
	list_for_each_entry(fp, &subs->fmt_list, list) {
Daniel Mack's avatar
Daniel Mack committed
814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856
		if (!hw_check_valid_format(subs, params, fp))
			continue;
		if (changed++) {
			if (rmin > fp->rate_min)
				rmin = fp->rate_min;
			if (rmax < fp->rate_max)
				rmax = fp->rate_max;
		} else {
			rmin = fp->rate_min;
			rmax = fp->rate_max;
		}
	}

	if (!changed) {
		hwc_debug("  --> get empty\n");
		it->empty = 1;
		return -EINVAL;
	}

	changed = 0;
	if (it->min < rmin) {
		it->min = rmin;
		it->openmin = 0;
		changed = 1;
	}
	if (it->max > rmax) {
		it->max = rmax;
		it->openmax = 0;
		changed = 1;
	}
	if (snd_interval_checkempty(it)) {
		it->empty = 1;
		return -EINVAL;
	}
	hwc_debug("  --> (%d, %d) (changed = %d)\n", it->min, it->max, changed);
	return changed;
}


static int hw_rule_channels(struct snd_pcm_hw_params *params,
			    struct snd_pcm_hw_rule *rule)
{
	struct snd_usb_substream *subs = rule->private;
857
	struct audioformat *fp;
Daniel Mack's avatar
Daniel Mack committed
858 859 860 861 862 863 864
	struct snd_interval *it = hw_param_interval(params, SNDRV_PCM_HW_PARAM_CHANNELS);
	unsigned int rmin, rmax;
	int changed;

	hwc_debug("hw_rule_channels: (%d,%d)\n", it->min, it->max);
	changed = 0;
	rmin = rmax = 0;
865
	list_for_each_entry(fp, &subs->fmt_list, list) {
Daniel Mack's avatar
Daniel Mack committed
866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907
		if (!hw_check_valid_format(subs, params, fp))
			continue;
		if (changed++) {
			if (rmin > fp->channels)
				rmin = fp->channels;
			if (rmax < fp->channels)
				rmax = fp->channels;
		} else {
			rmin = fp->channels;
			rmax = fp->channels;
		}
	}

	if (!changed) {
		hwc_debug("  --> get empty\n");
		it->empty = 1;
		return -EINVAL;
	}

	changed = 0;
	if (it->min < rmin) {
		it->min = rmin;
		it->openmin = 0;
		changed = 1;
	}
	if (it->max > rmax) {
		it->max = rmax;
		it->openmax = 0;
		changed = 1;
	}
	if (snd_interval_checkempty(it)) {
		it->empty = 1;
		return -EINVAL;
	}
	hwc_debug("  --> (%d, %d) (changed = %d)\n", it->min, it->max, changed);
	return changed;
}

static int hw_rule_format(struct snd_pcm_hw_params *params,
			  struct snd_pcm_hw_rule *rule)
{
	struct snd_usb_substream *subs = rule->private;
908
	struct audioformat *fp;
Daniel Mack's avatar
Daniel Mack committed
909 910 911 912 913 914 915
	struct snd_mask *fmt = hw_param_mask(params, SNDRV_PCM_HW_PARAM_FORMAT);
	u64 fbits;
	u32 oldbits[2];
	int changed;

	hwc_debug("hw_rule_format: %x:%x\n", fmt->bits[0], fmt->bits[1]);
	fbits = 0;
916
	list_for_each_entry(fp, &subs->fmt_list, list) {
Daniel Mack's avatar
Daniel Mack committed
917 918
		if (!hw_check_valid_format(subs, params, fp))
			continue;
919
		fbits |= fp->formats;
Daniel Mack's avatar
Daniel Mack committed
920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953
	}

	oldbits[0] = fmt->bits[0];
	oldbits[1] = fmt->bits[1];
	fmt->bits[0] &= (u32)fbits;
	fmt->bits[1] &= (u32)(fbits >> 32);
	if (!fmt->bits[0] && !fmt->bits[1]) {
		hwc_debug("  --> get empty\n");
		return -EINVAL;
	}
	changed = (oldbits[0] != fmt->bits[0] || oldbits[1] != fmt->bits[1]);
	hwc_debug("  --> %x:%x (changed = %d)\n", fmt->bits[0], fmt->bits[1], changed);
	return changed;
}

static int hw_rule_period_time(struct snd_pcm_hw_params *params,
			       struct snd_pcm_hw_rule *rule)
{
	struct snd_usb_substream *subs = rule->private;
	struct audioformat *fp;
	struct snd_interval *it;
	unsigned char min_datainterval;
	unsigned int pmin;
	int changed;

	it = hw_param_interval(params, SNDRV_PCM_HW_PARAM_PERIOD_TIME);
	hwc_debug("hw_rule_period_time: (%u,%u)\n", it->min, it->max);
	min_datainterval = 0xff;
	list_for_each_entry(fp, &subs->fmt_list, list) {
		if (!hw_check_valid_format(subs, params, fp))
			continue;
		min_datainterval = min(min_datainterval, fp->datainterval);
	}
	if (min_datainterval == 0xff) {
954
		hwc_debug("  --> get empty\n");
Daniel Mack's avatar
Daniel Mack committed
955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979
		it->empty = 1;
		return -EINVAL;
	}
	pmin = 125 * (1 << min_datainterval);
	changed = 0;
	if (it->min < pmin) {
		it->min = pmin;
		it->openmin = 0;
		changed = 1;
	}
	if (snd_interval_checkempty(it)) {
		it->empty = 1;
		return -EINVAL;
	}
	hwc_debug("  --> (%u,%u) (changed = %d)\n", it->min, it->max, changed);
	return changed;
}

/*
 *  If the device supports unusual bit rates, does the request meet these?
 */
static int snd_usb_pcm_check_knot(struct snd_pcm_runtime *runtime,
				  struct snd_usb_substream *subs)
{
	struct audioformat *fp;
980
	int *rate_list;
Daniel Mack's avatar
Daniel Mack committed
981 982 983
	int count = 0, needs_knot = 0;
	int err;

984 985 986
	kfree(subs->rate_list.list);
	subs->rate_list.list = NULL;

Daniel Mack's avatar
Daniel Mack committed
987 988 989 990 991 992 993 994 995 996
	list_for_each_entry(fp, &subs->fmt_list, list) {
		if (fp->rates & SNDRV_PCM_RATE_CONTINUOUS)
			return 0;
		count += fp->nr_rates;
		if (fp->rates & SNDRV_PCM_RATE_KNOT)
			needs_knot = 1;
	}
	if (!needs_knot)
		return 0;

997 998
	subs->rate_list.list = rate_list =
		kmalloc(sizeof(int) * count, GFP_KERNEL);
999 1000 1001
	if (!subs->rate_list.list)
		return -ENOMEM;
	subs->rate_list.count = count;
Daniel Mack's avatar
Daniel Mack committed
1002 1003 1004 1005 1006
	subs->rate_list.mask = 0;
	count = 0;
	list_for_each_entry(fp, &subs->fmt_list, list) {
		int i;
		for (i = 0; i < fp->nr_rates; i++)
1007
			rate_list[count++] = fp->rate_table[i];
Daniel Mack's avatar
Daniel Mack committed
1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023
	}
	err = snd_pcm_hw_constraint_list(runtime, 0, SNDRV_PCM_HW_PARAM_RATE,
					 &subs->rate_list);
	if (err < 0)
		return err;

	return 0;
}


/*
 * set up the runtime hardware information.
 */

static int setup_hw_info(struct snd_pcm_runtime *runtime, struct snd_usb_substream *subs)
{
1024
	struct audioformat *fp;
Daniel Mack's avatar
Daniel Mack committed
1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037
	unsigned int pt, ptmin;
	int param_period_time_if_needed;
	int err;

	runtime->hw.formats = subs->formats;

	runtime->hw.rate_min = 0x7fffffff;
	runtime->hw.rate_max = 0;
	runtime->hw.channels_min = 256;
	runtime->hw.channels_max = 0;
	runtime->hw.rates = 0;
	ptmin = UINT_MAX;
	/* check min/max rates and channels */
1038
	list_for_each_entry(fp, &subs->fmt_list, list) {
Daniel Mack's avatar
Daniel Mack committed
1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055
		runtime->hw.rates |= fp->rates;
		if (runtime->hw.rate_min > fp->rate_min)
			runtime->hw.rate_min = fp->rate_min;
		if (runtime->hw.rate_max < fp->rate_max)
			runtime->hw.rate_max = fp->rate_max;
		if (runtime->hw.channels_min > fp->channels)
			runtime->hw.channels_min = fp->channels;
		if (runtime->hw.channels_max < fp->channels)
			runtime->hw.channels_max = fp->channels;
		if (fp->fmt_type == UAC_FORMAT_TYPE_II && fp->frame_size > 0) {
			/* FIXME: there might be more than one audio formats... */
			runtime->hw.period_bytes_min = runtime->hw.period_bytes_max =
				fp->frame_size;
		}
		pt = 125 * (1 << fp->datainterval);
		ptmin = min(ptmin, pt);
	}
1056 1057 1058
	err = snd_usb_autoresume(subs->stream->chip);
	if (err < 0)
		return err;
Daniel Mack's avatar
Daniel Mack committed
1059 1060

	param_period_time_if_needed = SNDRV_PCM_HW_PARAM_PERIOD_TIME;
1061
	if (subs->speed == USB_SPEED_FULL)
Daniel Mack's avatar
Daniel Mack committed
1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075
		/* full speed devices have fixed data packet interval */
		ptmin = 1000;
	if (ptmin == 1000)
		/* if period time doesn't go below 1 ms, no rules needed */
		param_period_time_if_needed = -1;
	snd_pcm_hw_constraint_minmax(runtime, SNDRV_PCM_HW_PARAM_PERIOD_TIME,
				     ptmin, UINT_MAX);

	if ((err = snd_pcm_hw_rule_add(runtime, 0, SNDRV_PCM_HW_PARAM_RATE,
				       hw_rule_rate, subs,
				       SNDRV_PCM_HW_PARAM_FORMAT,
				       SNDRV_PCM_HW_PARAM_CHANNELS,
				       param_period_time_if_needed,
				       -1)) < 0)
1076
		goto rep_err;
Daniel Mack's avatar
Daniel Mack committed
1077 1078 1079 1080 1081 1082
	if ((err = snd_pcm_hw_rule_add(runtime, 0, SNDRV_PCM_HW_PARAM_CHANNELS,
				       hw_rule_channels, subs,
				       SNDRV_PCM_HW_PARAM_FORMAT,
				       SNDRV_PCM_HW_PARAM_RATE,
				       param_period_time_if_needed,
				       -1)) < 0)
1083
		goto rep_err;
Daniel Mack's avatar
Daniel Mack committed
1084 1085 1086 1087 1088 1089
	if ((err = snd_pcm_hw_rule_add(runtime, 0, SNDRV_PCM_HW_PARAM_FORMAT,
				       hw_rule_format, subs,
				       SNDRV_PCM_HW_PARAM_RATE,
				       SNDRV_PCM_HW_PARAM_CHANNELS,
				       param_period_time_if_needed,
				       -1)) < 0)
1090
		goto rep_err;
Daniel Mack's avatar
Daniel Mack committed
1091 1092 1093 1094 1095 1096 1097 1098 1099
	if (param_period_time_if_needed >= 0) {
		err = snd_pcm_hw_rule_add(runtime, 0,
					  SNDRV_PCM_HW_PARAM_PERIOD_TIME,
					  hw_rule_period_time, subs,
					  SNDRV_PCM_HW_PARAM_FORMAT,
					  SNDRV_PCM_HW_PARAM_CHANNELS,
					  SNDRV_PCM_HW_PARAM_RATE,
					  -1);
		if (err < 0)
1100
			goto rep_err;
Daniel Mack's avatar
Daniel Mack committed
1101 1102
	}
	if ((err = snd_usb_pcm_check_knot(runtime, subs)) < 0)
1103
		goto rep_err;
Daniel Mack's avatar
Daniel Mack committed
1104
	return 0;
1105 1106 1107 1108

rep_err:
	snd_usb_autosuspend(subs->stream->chip);
	return err;
Daniel Mack's avatar
Daniel Mack committed
1109 1110 1111 1112 1113 1114 1115 1116 1117
}

static int snd_usb_pcm_open(struct snd_pcm_substream *substream, int direction)
{
	struct snd_usb_stream *as = snd_pcm_substream_chip(substream);
	struct snd_pcm_runtime *runtime = substream->runtime;
	struct snd_usb_substream *subs = &as->substream[direction];

	subs->interface = -1;
1118
	subs->altset_idx = 0;
Daniel Mack's avatar
Daniel Mack committed
1119 1120 1121
	runtime->hw = snd_usb_hardware;
	runtime->private_data = subs;
	subs->pcm_substream = substream;
1122
	/* runtime PM is also done there */
Daniel Mack's avatar
Daniel Mack committed
1123 1124 1125 1126 1127 1128 1129 1130
	return setup_hw_info(runtime, subs);
}

static int snd_usb_pcm_close(struct snd_pcm_substream *substream, int direction)
{
	struct snd_usb_stream *as = snd_pcm_substream_chip(substream);
	struct snd_usb_substream *subs = &as->substream[direction];

1131
	stop_endpoints(subs, true);
1132 1133 1134 1135 1136 1137

	if (!as->chip->shutdown && subs->interface >= 0) {
		usb_set_interface(subs->dev, subs->interface, 0);
		subs->interface = -1;
	}

Daniel Mack's avatar
Daniel Mack committed
1138
	subs->pcm_substream = NULL;
1139
	snd_usb_autosuspend(subs->stream->chip);
1140

1141
	return 0;
1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156
}

/* Since a URB can handle only a single linear buffer, we must use double
 * buffering when the data to be transferred overflows the buffer boundary.
 * To avoid inconsistencies when updating hwptr_done, we use double buffering
 * for all URBs.
 */
static void retire_capture_urb(struct snd_usb_substream *subs,
			       struct urb *urb)
{
	struct snd_pcm_runtime *runtime = subs->pcm_substream->runtime;
	unsigned int stride, frames, bytes, oldptr;
	int i, period_elapsed = 0;
	unsigned long flags;
	unsigned char *cp;
1157 1158 1159 1160
	int current_frame_number;

	/* read frame number here, update pointer in critical section */
	current_frame_number = usb_get_current_frame_number(subs->dev);
1161 1162 1163 1164

	stride = runtime->frame_bits >> 3;

	for (i = 0; i < urb->number_of_packets; i++) {
1165
		cp = (unsigned char *)urb->transfer_buffer + urb->iso_frame_desc[i].offset + subs->pkt_offset_adj;
1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191
		if (urb->iso_frame_desc[i].status && printk_ratelimit()) {
			snd_printdd(KERN_ERR "frame %d active: %d\n", i, urb->iso_frame_desc[i].status);
			// continue;
		}
		bytes = urb->iso_frame_desc[i].actual_length;
		frames = bytes / stride;
		if (!subs->txfr_quirk)
			bytes = frames * stride;
		if (bytes % (runtime->sample_bits >> 3) != 0) {
			int oldbytes = bytes;
			bytes = frames * stride;
			snd_printdd(KERN_ERR "Corrected urb data len. %d->%d\n",
							oldbytes, bytes);
		}
		/* update the current pointer */
		spin_lock_irqsave(&subs->lock, flags);
		oldptr = subs->hwptr_done;
		subs->hwptr_done += bytes;
		if (subs->hwptr_done >= runtime->buffer_size * stride)
			subs->hwptr_done -= runtime->buffer_size * stride;
		frames = (bytes + (oldptr % stride)) / stride;
		subs->transfer_done += frames;
		if (subs->transfer_done >= runtime->period_size) {
			subs->transfer_done -= runtime->period_size;
			period_elapsed = 1;
		}
1192 1193 1194 1195 1196 1197 1198 1199 1200
		/* capture delay is by construction limited to one URB,
		 * reset delays here
		 */
		runtime->delay = subs->last_delay = 0;

		/* realign last_frame_number */
		subs->last_frame_number = current_frame_number;
		subs->last_frame_number &= 0xFF; /* keep 8 LSBs */

1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220
		spin_unlock_irqrestore(&subs->lock, flags);
		/* copy a data chunk */
		if (oldptr + bytes > runtime->buffer_size * stride) {
			unsigned int bytes1 =
					runtime->buffer_size * stride - oldptr;
			memcpy(runtime->dma_area + oldptr, cp, bytes1);
			memcpy(runtime->dma_area, cp + bytes1, bytes - bytes1);
		} else {
			memcpy(runtime->dma_area + oldptr, cp, bytes);
		}
	}

	if (period_elapsed)
		snd_pcm_period_elapsed(subs->pcm_substream);
}

static void prepare_playback_urb(struct snd_usb_substream *subs,
				 struct urb *urb)
{
	struct snd_pcm_runtime *runtime = subs->pcm_substream->runtime;
1221
	struct snd_usb_endpoint *ep = subs->data_endpoint;
1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232
	struct snd_urb_ctx *ctx = urb->context;
	unsigned int counts, frames, bytes;
	int i, stride, period_elapsed = 0;
	unsigned long flags;

	stride = runtime->frame_bits >> 3;

	frames = 0;
	urb->number_of_packets = 0;
	spin_lock_irqsave(&subs->lock, flags);
	for (i = 0; i < ctx->packets; i++) {
1233 1234 1235 1236 1237
		if (ctx->packet_size[i])
			counts = ctx->packet_size[i];
		else
			counts = snd_usb_endpoint_next_packet_size(ep);

1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268
		/* set up descriptor */
		urb->iso_frame_desc[i].offset = frames * stride;
		urb->iso_frame_desc[i].length = counts * stride;
		frames += counts;
		urb->number_of_packets++;
		subs->transfer_done += counts;
		if (subs->transfer_done >= runtime->period_size) {
			subs->transfer_done -= runtime->period_size;
			period_elapsed = 1;
			if (subs->fmt_type == UAC_FORMAT_TYPE_II) {
				if (subs->transfer_done > 0) {
					/* FIXME: fill-max mode is not
					 * supported yet */
					frames -= subs->transfer_done;
					counts -= subs->transfer_done;
					urb->iso_frame_desc[i].length =
						counts * stride;
					subs->transfer_done = 0;
				}
				i++;
				if (i < ctx->packets) {
					/* add a transfer delimiter */
					urb->iso_frame_desc[i].offset =
						frames * stride;
					urb->iso_frame_desc[i].length = 0;
					urb->number_of_packets++;
				}
				break;
			}
		}
		if (period_elapsed &&
1269
		    !snd_usb_endpoint_implicit_feedback_sink(subs->data_endpoint)) /* finish at the period boundary */
1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287
			break;
	}
	bytes = frames * stride;
	if (subs->hwptr_done + bytes > runtime->buffer_size * stride) {
		/* err, the transferred area goes over buffer boundary. */
		unsigned int bytes1 =
			runtime->buffer_size * stride - subs->hwptr_done;
		memcpy(urb->transfer_buffer,
		       runtime->dma_area + subs->hwptr_done, bytes1);
		memcpy(urb->transfer_buffer + bytes1,
		       runtime->dma_area, bytes - bytes1);
	} else {
		memcpy(urb->transfer_buffer,
		       runtime->dma_area + subs->hwptr_done, bytes);
	}
	subs->hwptr_done += bytes;
	if (subs->hwptr_done >= runtime->buffer_size * stride)
		subs->hwptr_done -= runtime->buffer_size * stride;
1288 1289 1290

	/* update delay with exact number of samples queued */
	runtime->delay = subs->last_delay;
1291
	runtime->delay += frames;
1292 1293 1294 1295 1296 1297
	subs->last_delay = runtime->delay;

	/* realign last_frame_number */
	subs->last_frame_number = usb_get_current_frame_number(subs->dev);
	subs->last_frame_number &= 0xFF; /* keep 8 LSBs */

1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314
	spin_unlock_irqrestore(&subs->lock, flags);
	urb->transfer_buffer_length = bytes;
	if (period_elapsed)
		snd_pcm_period_elapsed(subs->pcm_substream);
}

/*
 * process after playback data complete
 * - decrease the delay count again
 */
static void retire_playback_urb(struct snd_usb_substream *subs,
			       struct urb *urb)
{
	unsigned long flags;
	struct snd_pcm_runtime *runtime = subs->pcm_substream->runtime;
	int stride = runtime->frame_bits >> 3;
	int processed = urb->transfer_buffer_length / stride;
1315
	int est_delay;
1316

1317 1318 1319 1320 1321 1322
	/* ignore the delay accounting when procssed=0 is given, i.e.
	 * silent payloads are procssed before handling the actual data
	 */
	if (!processed)
		return;

1323
	spin_lock_irqsave(&subs->lock, flags);
1324 1325 1326
	if (!subs->last_delay)
		goto out; /* short path */

1327 1328 1329 1330
	est_delay = snd_usb_pcm_delay(subs, runtime->rate);
	/* update delay with exact number of samples played */
	if (processed > subs->last_delay)
		subs->last_delay = 0;
1331
	else
1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343
		subs->last_delay -= processed;
	runtime->delay = subs->last_delay;

	/*
	 * Report when delay estimate is off by more than 2ms.
	 * The error should be lower than 2ms since the estimate relies
	 * on two reads of a counter updated every ms.
	 */
	if (abs(est_delay - subs->last_delay) * 1000 > runtime->rate * 2)
		snd_printk(KERN_DEBUG "delay: estimated %d, actual %d\n",
			est_delay, subs->last_delay);

1344 1345 1346 1347 1348 1349 1350 1351 1352
	if (!subs->running) {
		/* update last_frame_number for delay counting here since
		 * prepare_playback_urb won't be called during pause
		 */
		subs->last_frame_number =
			usb_get_current_frame_number(subs->dev) & 0xff;
	}

 out:
1353
	spin_unlock_irqrestore(&subs->lock, flags);
Daniel Mack's avatar
Daniel Mack committed
1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375
}

static int snd_usb_playback_open(struct snd_pcm_substream *substream)
{
	return snd_usb_pcm_open(substream, SNDRV_PCM_STREAM_PLAYBACK);
}

static int snd_usb_playback_close(struct snd_pcm_substream *substream)
{
	return snd_usb_pcm_close(substream, SNDRV_PCM_STREAM_PLAYBACK);
}

static int snd_usb_capture_open(struct snd_pcm_substream *substream)
{
	return snd_usb_pcm_open(substream, SNDRV_PCM_STREAM_CAPTURE);
}

static int snd_usb_capture_close(struct snd_pcm_substream *substream)
{
	return snd_usb_pcm_close(substream, SNDRV_PCM_STREAM_CAPTURE);
}

1376 1377 1378 1379 1380 1381 1382 1383 1384 1385
static int snd_usb_substream_playback_trigger(struct snd_pcm_substream *substream,
					      int cmd)
{
	struct snd_usb_substream *subs = substream->runtime->private_data;

	switch (cmd) {
	case SNDRV_PCM_TRIGGER_START:
	case SNDRV_PCM_TRIGGER_PAUSE_RELEASE:
		subs->data_endpoint->prepare_data_urb = prepare_playback_urb;
		subs->data_endpoint->retire_data_urb = retire_playback_urb;
1386
		subs->running = 1;
1387 1388
		return 0;
	case SNDRV_PCM_TRIGGER_STOP:
1389
		stop_endpoints(subs, false);
1390
		subs->running = 0;
1391 1392 1393
		return 0;
	case SNDRV_PCM_TRIGGER_PAUSE_PUSH:
		subs->data_endpoint->prepare_data_urb = NULL;
1394 1395
		/* keep retire_data_urb for delay calculation */
		subs->data_endpoint->retire_data_urb = retire_playback_urb;
1396
		subs->running = 0;
1397 1398 1399 1400 1401 1402
		return 0;
	}

	return -EINVAL;
}

1403 1404
static int snd_usb_substream_capture_trigger(struct snd_pcm_substream *substream,
					     int cmd)
1405 1406 1407 1408 1409 1410
{
	int err;
	struct snd_usb_substream *subs = substream->runtime->private_data;

	switch (cmd) {
	case SNDRV_PCM_TRIGGER_START:
1411
		err = start_endpoints(subs, false);
1412 1413 1414 1415
		if (err < 0)
			return err;

		subs->data_endpoint->retire_data_urb = retire_capture_urb;
1416
		subs->running = 1;
1417 1418
		return 0;
	case SNDRV_PCM_TRIGGER_STOP:
1419
		stop_endpoints(subs, false);
1420
		subs->running = 0;
1421 1422 1423
		return 0;