pcm.c 53.1 KB
Newer Older
1
// SPDX-License-Identifier: GPL-2.0-or-later
D
Daniel Mack 已提交
2 3 4 5
/*
 */

#include <linux/init.h>
6
#include <linux/slab.h>
7
#include <linux/bitrev.h>
8
#include <linux/ratelimit.h>
D
Daniel Mack 已提交
9 10
#include <linux/usb.h>
#include <linux/usb/audio.h>
D
Daniel Mack 已提交
11
#include <linux/usb/audio-v2.h>
D
Daniel Mack 已提交
12 13 14 15 16 17 18 19

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

#include "usbaudio.h"
#include "card.h"
#include "quirks.h"
20
#include "endpoint.h"
D
Daniel Mack 已提交
21 22
#include "helper.h"
#include "pcm.h"
23
#include "clock.h"
24
#include "power.h"
25
#include "media.h"
D
Daniel Mack 已提交
26

27 28 29
#define SUBSTREAM_FLAG_DATA_EP_STARTED	0
#define SUBSTREAM_FLAG_SYNC_EP_STARTED	1

30 31 32 33 34 35 36 37
/* 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;

38 39 40
	if (!subs->last_delay)
		return 0; /* short path */

41 42 43 44 45 46 47 48 49 50
	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 */
51 52 53 54 55 56
	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;

57 58 59 60 61
	if (est_delay < 0)
		est_delay = 0;
	return est_delay;
}

D
Daniel Mack 已提交
62 63 64 65 66
/*
 * 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)
{
67
	struct snd_usb_substream *subs = substream->runtime->private_data;
D
Daniel Mack 已提交
68 69
	unsigned int hwptr_done;

70
	if (atomic_read(&subs->stream->chip->shutdown))
71
		return SNDRV_PCM_POS_XRUN;
D
Daniel Mack 已提交
72 73
	spin_lock(&subs->lock);
	hwptr_done = subs->hwptr_done;
74
	substream->runtime->delay = snd_usb_pcm_delay(subs,
75
						substream->runtime->rate);
D
Daniel Mack 已提交
76 77 78 79 80 81 82
	spin_unlock(&subs->lock);
	return hwptr_done / (substream->runtime->frame_bits >> 3);
}

/*
 * find a matching audio format
 */
83 84 85 86 87
static struct audioformat *find_format(struct list_head *fmt_list_head,
				       snd_pcm_format_t format,
				       unsigned int rate,
				       unsigned int channels,
				       struct snd_usb_substream *subs)
D
Daniel Mack 已提交
88
{
89
	struct audioformat *fp;
D
Daniel Mack 已提交
90 91 92
	struct audioformat *found = NULL;
	int cur_attr = 0, attr;

93 94
	list_for_each_entry(fp, fmt_list_head, list) {
		if (!(fp->formats & pcm_format_to_bits(format)))
95
			continue;
96
		if (fp->channels != channels)
D
Daniel Mack 已提交
97
			continue;
98
		if (rate < fp->rate_min || rate > fp->rate_max)
D
Daniel Mack 已提交
99
			continue;
100
		if (!(fp->rates & SNDRV_PCM_RATE_CONTINUOUS)) {
D
Daniel Mack 已提交
101 102
			unsigned int i;
			for (i = 0; i < fp->nr_rates; i++)
103
				if (fp->rate_table[i] == rate)
D
Daniel Mack 已提交
104 105 106 107 108
					break;
			if (i >= fp->nr_rates)
				continue;
		}
		attr = fp->ep_attr & USB_ENDPOINT_SYNCTYPE;
109
		if (!found) {
D
Daniel Mack 已提交
110 111 112 113 114 115 116 117 118
			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.
		 */
119
		if (subs && attr != cur_attr) {
D
Daniel Mack 已提交
120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142
			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;
}

143 144 145 146 147 148
static struct audioformat *find_substream_format(struct snd_usb_substream *subs)
{
	return find_format(&subs->fmt_list, subs->pcm_format, subs->cur_rate,
			   subs->channels, subs);
}

149
static int init_pitch_v1(struct snd_usb_audio *chip,
150 151 152 153 154 155 156
			 struct audioformat *fmt)
{
	struct usb_device *dev = chip->dev;
	unsigned int ep;
	unsigned char data[1];
	int err;

157
	ep = fmt->endpoint;
158 159

	data[0] = 1;
160 161 162 163 164
	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,
			      data, sizeof(data));
	if (err < 0) {
165
		usb_audio_err(chip, "%d:%d: cannot set enable PITCH\n",
166
			      fmt->iface, ep);
167 168 169 170 171
		return err;
	}

	return 0;
}
D
Daniel Mack 已提交
172

173
static int init_pitch_v2(struct snd_usb_audio *chip,
174 175 176 177 178 179 180
			 struct audioformat *fmt)
{
	struct usb_device *dev = chip->dev;
	unsigned char data[1];
	int err;

	data[0] = 1;
181 182 183 184 185
	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,
			      data, sizeof(data));
	if (err < 0) {
186
		usb_audio_err(chip, "%d:%d: cannot set enable PITCH (v2)\n",
187
			      fmt->iface, fmt->altsetting);
188 189 190 191 192 193
		return err;
	}

	return 0;
}

D
Daniel Mack 已提交
194
/*
195
 * initialize the pitch control and sample rate
D
Daniel Mack 已提交
196
 */
197
int snd_usb_init_pitch(struct snd_usb_audio *chip,
D
Daniel Mack 已提交
198 199
		       struct audioformat *fmt)
{
200 201 202 203
	/* if endpoint doesn't have pitch control, bail out */
	if (!(fmt->attributes & UAC_EP_CS_ATTR_PITCH_CONTROL))
		return 0;

204
	switch (fmt->protocol) {
205
	case UAC_VERSION_1:
206
	default:
207
		return init_pitch_v1(chip, fmt);
208 209

	case UAC_VERSION_2:
210
		return init_pitch_v2(chip, fmt);
211 212 213
	}
}

214 215 216 217 218 219 220 221 222 223 224
static void stop_endpoints(struct snd_usb_substream *subs)
{
	if (test_and_clear_bit(SUBSTREAM_FLAG_SYNC_EP_STARTED, &subs->flags)) {
		snd_usb_endpoint_stop(subs->sync_endpoint);
		subs->sync_endpoint->sync_slave = NULL;
	}

	if (test_and_clear_bit(SUBSTREAM_FLAG_DATA_EP_STARTED, &subs->flags))
		snd_usb_endpoint_stop(subs->data_endpoint);
}

225
static int start_endpoints(struct snd_usb_substream *subs)
226 227 228 229 230 231 232 233 234 235
{
	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;

		ep->data_subs = subs;
236
		err = snd_usb_endpoint_start(ep);
237 238
		if (err < 0) {
			clear_bit(SUBSTREAM_FLAG_DATA_EP_STARTED, &subs->flags);
239
			goto error;
240 241 242 243 244 245 246 247
		}
	}

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

		ep->sync_slave = subs->data_endpoint;
248
		err = snd_usb_endpoint_start(ep);
249 250
		if (err < 0) {
			clear_bit(SUBSTREAM_FLAG_SYNC_EP_STARTED, &subs->flags);
251
			ep->sync_slave = NULL;
252
			goto error;
253 254 255 256
		}
	}

	return 0;
257 258 259 260

 error:
	stop_endpoints(subs);
	return err;
261 262
}

263 264 265 266 267 268 269 270 271 272 273 274 275 276
static void sync_pending_stops(struct snd_usb_substream *subs)
{
	snd_usb_endpoint_sync_pending_stop(subs->sync_endpoint);
	snd_usb_endpoint_sync_pending_stop(subs->data_endpoint);
}

/* PCM sync_stop callback */
static int snd_usb_pcm_sync_stop(struct snd_pcm_substream *substream)
{
	struct snd_usb_substream *subs = substream->runtime->private_data;

	if (!snd_usb_lock_shutdown(subs->stream->chip)) {
		sync_pending_stops(subs);
		snd_usb_unlock_shutdown(subs->stream->chip);
277
	}
278
	return 0;
279 280
}

281
/* Check whether the given iface:altsetting points to an implicit fb source */
282
static bool search_generic_implicit_fb(struct snd_usb_audio *chip, int ifnum,
283 284 285
				       unsigned int altsetting,
				       struct usb_host_interface **altsp,
				       unsigned int *ep)
286
{
287 288 289 290
	struct usb_host_interface *alts;
	struct usb_interface_descriptor *altsd;
	struct usb_endpoint_descriptor *epd;

291
	alts = snd_usb_get_host_interface(chip, ifnum, altsetting);
292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310
	if (!alts)
		return false;
	altsd = get_iface_desc(alts);
	if (altsd->bInterfaceClass != USB_CLASS_AUDIO ||
	    altsd->bInterfaceSubClass != USB_SUBCLASS_AUDIOSTREAMING ||
	    altsd->bInterfaceProtocol != UAC_VERSION_2 ||
	    altsd->bNumEndpoints < 1)
		return false;
	epd = get_endpoint(alts, 0);
	if (!usb_endpoint_is_isoc_in(epd) ||
	    (epd->bmAttributes & USB_ENDPOINT_USAGE_MASK) !=
					USB_ENDPOINT_USAGE_IMPLICIT_FB)
		return false;
	*ep = epd->bEndpointAddress;
	*altsp = alts;
	return true;
}

/* Like the function above, but specific to Roland with vendor class and hack */
311
static bool search_roland_implicit_fb(struct snd_usb_audio *chip, int ifnum,
312 313 314 315 316
				      unsigned int altsetting,
				      struct usb_host_interface **altsp,
				      unsigned int *ep)
{
	struct usb_host_interface *alts;
317 318 319
	struct usb_interface_descriptor *altsd;
	struct usb_endpoint_descriptor *epd;

320
	alts = snd_usb_get_host_interface(chip, ifnum, altsetting);
321 322 323 324
	if (!alts)
		return false;
	altsd = get_iface_desc(alts);
	if (altsd->bInterfaceClass != USB_CLASS_VENDOR_SPEC ||
325
	    (altsd->bInterfaceSubClass != 2 &&
326
	     altsd->bInterfaceProtocol != 2) ||
327
	    altsd->bNumEndpoints < 1)
328 329
		return false;
	epd = get_endpoint(alts, 0);
330 331 332
	if (!usb_endpoint_is_isoc_in(epd) ||
	    (epd->bmAttributes & USB_ENDPOINT_USAGE_MASK) !=
					USB_ENDPOINT_USAGE_IMPLICIT_FB)
333
		return false;
334
	*ep = epd->bEndpointAddress;
335 336
	*altsp = alts;
	return true;
337 338
}

339 340 341
/* Setup an implicit feedback endpoint from a quirk. Returns 0 if no quirk
 * applies. Returns 1 if a quirk was found.
 */
342 343 344
static int audioformat_implicit_fb_quirk(struct snd_usb_audio *chip,
					 struct audioformat *fmt,
					 struct usb_host_interface *alts)
D
Daniel Mack 已提交
345
{
346 347
	struct usb_device *dev = chip->dev;
	struct usb_interface_descriptor *altsd = get_iface_desc(alts);
348
	struct usb_interface *iface;
349
	unsigned int attr = fmt->ep_attr & USB_ENDPOINT_SYNCTYPE;
350
	unsigned int ep;
351
	unsigned int ifnum;
352

353
	switch (chip->usb_id) {
354
	case USB_ID(0x0763, 0x2030): /* M-Audio Fast Track C400 */
355
	case USB_ID(0x0763, 0x2031): /* M-Audio Fast Track C600 */
356
	case USB_ID(0x22f0, 0x0006): /* Allen&Heath Qu-16 */
357
		ep = 0x81;
358 359
		ifnum = 3;
		goto add_sync_ep_from_ifnum;
360 361
	case USB_ID(0x0763, 0x2080): /* M-Audio FastTrack Ultra */
	case USB_ID(0x0763, 0x2081):
362
		ep = 0x81;
363 364 365
		ifnum = 2;
		goto add_sync_ep_from_ifnum;
	case USB_ID(0x2466, 0x8003): /* Fractal Audio Axe-Fx II */
366
	case USB_ID(0x0499, 0x172a): /* Yamaha MODX */
367
		ep = 0x86;
368 369
		ifnum = 2;
		goto add_sync_ep_from_ifnum;
370 371 372 373
	case USB_ID(0x2466, 0x8010): /* Fractal Audio Axe-Fx III */
		ep = 0x81;
		ifnum = 2;
		goto add_sync_ep_from_ifnum;
374 375 376 377
	case USB_ID(0x1686, 0xf029): /* Zoom UAC-2 */
		ep = 0x82;
		ifnum = 2;
		goto add_sync_ep_from_ifnum;
378
	case USB_ID(0x1397, 0x0001): /* Behringer UFX1604 */
379
	case USB_ID(0x1397, 0x0002): /* Behringer UFX1204 */
380
		ep = 0x81;
381 382
		ifnum = 1;
		goto add_sync_ep_from_ifnum;
383 384 385 386 387 388
	case USB_ID(0x07fd, 0x0004): /* MOTU MicroBook II/IIc */
		/* MicroBook IIc */
		if (altsd->bInterfaceClass == USB_CLASS_AUDIO)
			return 0;

		/* MicroBook II */
389 390 391
		ep = 0x84;
		ifnum = 0;
		goto add_sync_ep_from_ifnum;
392
	case USB_ID(0x07fd, 0x0008): /* MOTU M Series */
393
	case USB_ID(0x31e9, 0x0001): /* Solid State Logic SSL2 */
394
	case USB_ID(0x31e9, 0x0002): /* Solid State Logic SSL2+ */
395
	case USB_ID(0x0499, 0x172f): /* Steinberg UR22C */
396
	case USB_ID(0x0d9a, 0x00df): /* RTX6001 */
397 398 399
		ep = 0x81;
		ifnum = 2;
		goto add_sync_ep_from_ifnum;
400
	case USB_ID(0x2b73, 0x000a): /* Pioneer DJ DJM-900NXS2 */
401
	case USB_ID(0x2b73, 0x0017): /* Pioneer DJ DJM-250MK2 */
402 403 404
		ep = 0x82;
		ifnum = 0;
		goto add_sync_ep_from_ifnum;
405 406 407
	case USB_ID(0x0582, 0x01d8): /* BOSS Katana */
		/* BOSS Katana amplifiers do not need quirks */
		return 0;
408
	}
409

410 411 412 413 414 415
	/* Generic UAC2 implicit feedback */
	if (attr == USB_ENDPOINT_SYNC_ASYNC &&
	    altsd->bInterfaceClass == USB_CLASS_AUDIO &&
	    altsd->bInterfaceProtocol == UAC_VERSION_2 &&
	    altsd->bNumEndpoints == 1) {
		ifnum = altsd->bInterfaceNumber + 1;
416
		if (search_generic_implicit_fb(chip, ifnum,
417 418 419 420 421 422
					       altsd->bAlternateSetting,
					       &alts, &ep))
			goto add_sync_ep;
	}

	/* Roland/BOSS implicit feedback with vendor spec class */
423
	if (attr == USB_ENDPOINT_SYNC_ASYNC &&
424 425 426
	    altsd->bInterfaceClass == USB_CLASS_VENDOR_SPEC &&
	    altsd->bInterfaceProtocol == 2 &&
	    altsd->bNumEndpoints == 1 &&
427 428
	    USB_ID_VENDOR(chip->usb_id) == 0x0582 /* Roland */) {
		ifnum = altsd->bInterfaceNumber + 1;
429
		if (search_roland_implicit_fb(chip, ifnum,
430 431 432 433
					      altsd->bAlternateSetting,
					      &alts, &ep))
			goto add_sync_ep;
	}
434

435 436 437
	/* No quirk */
	return 0;

438 439 440
add_sync_ep_from_ifnum:
	iface = usb_ifnum_to_if(dev, ifnum);

441
	if (!iface || iface->num_altsetting < 2)
442
		return 0;
443 444 445

	alts = &iface->altsetting[1];

446
add_sync_ep:
447 448 449 450 451 452 453
	fmt->sync_ep = ep;
	fmt->sync_iface = ifnum;
	fmt->sync_altsetting = alts->desc.bAlternateSetting;
	fmt->implicit_fb = 1;
	dev_dbg(&dev->dev, "%d:%d: found implicit_fb sync_ep=%x, iface=%d, alt=%d\n",
		fmt->iface, fmt->altsetting, fmt->sync_ep, fmt->sync_iface,
		fmt->sync_altsetting);
454

455
	return 1;
456 457
}

458 459
int snd_usb_audioformat_set_sync_ep(struct snd_usb_audio *chip,
				    struct audioformat *fmt)
460
{
461 462 463 464 465
	struct usb_device *dev = chip->dev;
	struct usb_host_interface *alts;
	struct usb_interface_descriptor *altsd;
	unsigned int ep, attr, sync_attr;
	bool is_playback;
466 467
	int err;

468
	alts = snd_usb_get_host_interface(chip, fmt->iface, fmt->altsetting);
469
	if (!alts)
470
		return 0;
471 472 473 474
	altsd = get_iface_desc(alts);

	is_playback = !(get_endpoint(alts, 0)->bEndpointAddress & USB_DIR_IN);
	if (is_playback) {
475
		err = audioformat_implicit_fb_quirk(chip, fmt, alts);
476 477 478
		if (err > 0)
			return 0;
	}
479

480 481
	if (altsd->bNumEndpoints < 2)
		return 0;
482

483
	attr = fmt->ep_attr & USB_ENDPOINT_SYNCTYPE;
484 485
	if ((is_playback && (attr == USB_ENDPOINT_SYNC_SYNC ||
			     attr == USB_ENDPOINT_SYNC_ADAPTIVE)) ||
486 487
	    (!is_playback && attr != USB_ENDPOINT_SYNC_ADAPTIVE))
		return 0;
488

489 490
	sync_attr = get_endpoint(alts, 1)->bmAttributes;

491 492 493 494 495 496
	/*
	 * In case of illegal SYNC_NONE for OUT endpoint, we keep going to see
	 * if we don't find a sync endpoint, as on M-Audio Transit. In case of
	 * error fall back to SYNC mode and don't create sync endpoint
	 */

497 498 499 500
	/* 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 */
501
	if ((sync_attr & USB_ENDPOINT_XFERTYPE_MASK) != USB_ENDPOINT_XFER_ISOC ||
502
	    (get_endpoint(alts, 1)->bLength >= USB_DT_ENDPOINT_AUDIO_SIZE &&
503
	     get_endpoint(alts, 1)->bSynchAddress != 0)) {
504 505 506
		dev_err(&dev->dev,
			"%d:%d : invalid sync pipe. bmAttributes %02x, bLength %d, bSynchAddress %02x\n",
			   fmt->iface, fmt->altsetting,
507 508 509
			   get_endpoint(alts, 1)->bmAttributes,
			   get_endpoint(alts, 1)->bLength,
			   get_endpoint(alts, 1)->bSynchAddress);
510 511
		if (is_playback && attr == USB_ENDPOINT_SYNC_NONE)
			return 0;
512 513 514
		return -EINVAL;
	}
	ep = get_endpoint(alts, 1)->bEndpointAddress;
515
	if (get_endpoint(alts, 0)->bLength >= USB_DT_ENDPOINT_AUDIO_SIZE &&
516
	    get_endpoint(alts, 0)->bSynchAddress != 0 &&
517 518
	    ((is_playback && ep != (unsigned int)(get_endpoint(alts, 0)->bSynchAddress | USB_DIR_IN)) ||
	     (!is_playback && ep != (unsigned int)(get_endpoint(alts, 0)->bSynchAddress & ~USB_DIR_IN)))) {
519 520 521
		dev_err(&dev->dev,
			"%d:%d : invalid sync pipe. is_playback %d, ep %02x, bSynchAddress %02x\n",
			   fmt->iface, fmt->altsetting,
522
			   is_playback, ep, get_endpoint(alts, 0)->bSynchAddress);
523 524
		if (is_playback && attr == USB_ENDPOINT_SYNC_NONE)
			return 0;
525
		return -EINVAL;
526
	}
D
Daniel Mack 已提交
527

528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545
	fmt->sync_ep = ep;
	fmt->sync_iface = altsd->bInterfaceNumber;
	fmt->sync_altsetting = altsd->bAlternateSetting;
	if ((sync_attr & USB_ENDPOINT_USAGE_MASK) == USB_ENDPOINT_USAGE_IMPLICIT_FB)
		fmt->implicit_fb = 1;

	dev_dbg(&dev->dev, "%d:%d: found sync_ep=0x%x, iface=%d, alt=%d, implicit_fb=%d\n",
		fmt->iface, fmt->altsetting, fmt->sync_ep, fmt->sync_iface,
		fmt->sync_altsetting, fmt->implicit_fb);

	return 0;
}

static int set_sync_endpoint(struct snd_usb_substream *subs,
			     struct audioformat *fmt)
{
	struct usb_device *dev = subs->dev;
	struct usb_host_interface *alts;
546
	struct snd_usb_audio *chip = subs->stream->chip;
547 548 549 550 551 552 553 554 555 556 557
	int is_playback = subs->direction == SNDRV_PCM_STREAM_PLAYBACK;
	unsigned int ep;
	int err;

	subs->sync_endpoint = NULL;
	subs->data_endpoint->sync_master = NULL;

	ep = fmt->sync_ep;
	if (!ep)
		return 0;

558 559
	alts = snd_usb_get_host_interface(subs->stream->chip, fmt->sync_iface,
					  fmt->altsetting);
560 561
	if (!alts)
		return 0;
562

563
	subs->sync_endpoint = snd_usb_get_endpoint(chip, ep);
564
	if (!subs->sync_endpoint) {
565 566
		if (is_playback &&
		    (fmt->ep_attr & USB_ENDPOINT_SYNCTYPE) == USB_ENDPOINT_SYNC_NONE)
567
			return 0;
568
		return -EINVAL;
569
	}
570

571 572
	subs->sync_endpoint->iface = fmt->sync_iface;
	subs->sync_endpoint->altsetting = fmt->sync_altsetting;
573
	subs->sync_endpoint->is_implicit_feedback = fmt->implicit_fb;
574

575 576
	subs->data_endpoint->sync_master = subs->sync_endpoint;

577 578
	snd_usb_endpoint_set_syncinterval(subs->stream->chip, subs->sync_endpoint, alts);

579 580 581
	if (!subs->sync_endpoint->use_count &&
	    (subs->data_endpoint->iface != subs->sync_endpoint->iface ||
	     subs->data_endpoint->altsetting != subs->sync_endpoint->altsetting)) {
582 583 584 585 586 587 588 589
		err = usb_set_interface(subs->dev,
					subs->sync_endpoint->iface,
					subs->sync_endpoint->altsetting);
		if (err < 0)
			return err;
		dev_dbg(&dev->dev, "setting usb interface %d:%d\n",
			subs->sync_endpoint->iface,
			subs->sync_endpoint->altsetting);
590
		snd_usb_set_interface_quirk(chip);
591 592
	}

593 594 595 596 597 598 599 600 601
	return 0;
}

/*
 * 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;
602
	struct snd_usb_audio *chip = subs->stream->chip;
603 604
	struct usb_host_interface *alts;
	struct usb_interface *iface;
605
	struct snd_usb_endpoint *ep;
606 607 608 609 610
	int err;

	iface = usb_ifnum_to_if(dev, fmt->iface);
	if (WARN_ON(!iface))
		return -EINVAL;
611
	alts = usb_altnum_to_altsetting(iface, fmt->altsetting);
612
	if (WARN_ON(!alts))
613 614
		return -EINVAL;

615
	if (fmt == subs->cur_audiofmt && !subs->need_setup_fmt)
616 617
		return 0;

618 619
	/* shared EP with implicit fb */
	if (fmt->implicit_fb && !subs->need_setup_fmt) {
620
		ep = snd_usb_get_endpoint(chip, fmt->endpoint);
621 622 623 624
		if (ep && ep->use_count > 0)
			goto add_data_ep;
	}

625
	/* close the old interface */
626
	if (subs->interface >= 0 && (subs->interface != fmt->iface || subs->need_setup_fmt)) {
627 628 629 630 631 632
		err = usb_set_interface(subs->dev, subs->interface, 0);
		if (err < 0) {
			dev_err(&dev->dev,
				"%d:%d: return to setting 0 failed (%d)\n",
				fmt->iface, fmt->altsetting, err);
			return -EIO;
633 634 635 636 637
		}
		subs->interface = -1;
		subs->altset_idx = 0;
	}

638 639 640
	if (subs->need_setup_fmt)
		subs->need_setup_fmt = false;

641
	/* set interface */
642
	if (iface->cur_altsetting != alts) {
643
		err = snd_usb_select_mode_quirk(chip, fmt);
644 645 646
		if (err < 0)
			return -EIO;

647 648
		err = usb_set_interface(dev, fmt->iface, fmt->altsetting);
		if (err < 0) {
649 650 651
			dev_err(&dev->dev,
				"%d:%d: usb_set_interface failed (%d)\n",
				fmt->iface, fmt->altsetting, err);
652 653
			return -EIO;
		}
654 655
		dev_dbg(&dev->dev, "setting usb interface %d:%d\n",
			fmt->iface, fmt->altsetting);
656
		snd_usb_set_interface_quirk(chip);
657 658
	}

659 660 661
	subs->need_setup_ep = true;

 add_data_ep:
662 663
	subs->interface = fmt->iface;
	subs->altset_idx = fmt->altset_idx;
664
	subs->data_endpoint = snd_usb_get_endpoint(chip, fmt->endpoint);
665 666
	if (!subs->data_endpoint)
		return -EINVAL;
667 668
	subs->data_endpoint->iface = fmt->iface;
	subs->data_endpoint->altsetting = fmt->altsetting;
669

670
	err = set_sync_endpoint(subs, fmt);
671 672 673
	if (err < 0)
		return err;

674
	if (subs->need_setup_ep) {
675
		err = snd_usb_init_pitch(chip, fmt);
676 677 678
		if (err < 0)
			return err;
	}
D
Daniel Mack 已提交
679 680 681 682 683 684 685 686

	subs->cur_audiofmt = fmt;

	snd_usb_set_format_quirk(subs, fmt);

	return 0;
}

687 688 689 690 691 692 693
/*
 * 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.
 */
694 695 696 697
static int match_endpoint_audioformats(struct snd_usb_substream *subs,
				       struct audioformat *fp,
				       struct audioformat *match, int rate,
				       snd_pcm_format_t pcm_format)
698 699 700 701 702
{
	int i;
	int score = 0;

	if (fp->channels < 1) {
703 704
		dev_dbg(&subs->dev->dev,
			"%s: (fmt @%p) no channels\n", __func__, fp);
705 706 707
		return 0;
	}

708
	if (!(fp->formats & pcm_format_to_bits(pcm_format))) {
709 710
		dev_dbg(&subs->dev->dev,
			"%s: (fmt @%p) no match for format %d\n", __func__,
711 712 713 714 715 716 717 718 719 720 721
			fp, pcm_format);
		return 0;
	}

	for (i = 0; i < fp->nr_rates; i++) {
		if (fp->rate_table[i] == rate) {
			score++;
			break;
		}
	}
	if (!score) {
722 723
		dev_dbg(&subs->dev->dev,
			"%s: (fmt @%p) no match for rate %d\n", __func__,
724 725 726 727 728 729 730
			fp, rate);
		return 0;
	}

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

731 732
	dev_dbg(&subs->dev->dev,
		"%s: (fmt @%p) score %d\n", __func__, fp, score);
733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748

	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)
{
	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];

749 750 751 752 753 754 755 756 757 758
	if (subs->fixed_hw ||
	    !subs->sync_endpoint->is_implicit_feedback) {
		sync_fp = subs->cur_audiofmt;
		goto configure;
	}

	sync_fp = find_format(&sync_subs->fmt_list, subs->pcm_format,
			      subs->cur_rate, subs->channels, NULL);
	if (sync_fp)
		goto configure;
759

760 761
	/* Try to find the best matching audioformat. */
	list_for_each_entry(fp, &sync_subs->fmt_list, list) {
762 763
		int score = match_endpoint_audioformats(subs,
							fp, subs->cur_audiofmt,
764 765 766 767 768 769 770 771 772
			subs->cur_rate, subs->pcm_format);

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

	if (unlikely(sync_fp == NULL)) {
773 774
		dev_err(&subs->dev->dev,
			"%s: no valid audioformat for sync ep %x found\n",
775 776 777 778 779 780 781 782 783 784 785
			__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;
786 787
		dev_dbg(&subs->dev->dev,
			"%s: adjusted sync ep period bytes (%d -> %d)\n",
788 789 790
			__func__, subs->period_bytes, sync_period_bytes);
	}

791 792 793 794 795 796 797 798 799 800
 configure:
	return snd_usb_endpoint_set_params(subs->sync_endpoint,
					   subs->pcm_format,
					   sync_fp->channels,
					   sync_period_bytes,
					   subs->period_frames,
					   subs->buffer_periods,
					   subs->cur_rate,
					   sync_fp,
					   NULL);
801 802
}

803 804 805 806 807 808 809 810 811 812
/*
 * configure endpoint params
 *
 * called  during initial setup and upon resume
 */
static int configure_endpoint(struct snd_usb_substream *subs)
{
	int ret;

	/* format changed */
813 814
	stop_endpoints(subs);
	sync_pending_stops(subs);
815 816 817 818
	ret = snd_usb_endpoint_set_params(subs->data_endpoint,
					  subs->pcm_format,
					  subs->channels,
					  subs->period_bytes,
819 820
					  subs->period_frames,
					  subs->buffer_periods,
821 822 823 824
					  subs->cur_rate,
					  subs->cur_audiofmt,
					  subs->sync_endpoint);
	if (ret < 0)
825
		return ret;
826 827

	if (subs->sync_endpoint)
828 829
		ret = configure_sync_endpoint(subs);

830 831 832
	return ret;
}

833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869
static int snd_usb_pcm_change_state(struct snd_usb_substream *subs, int state)
{
	int ret;

	if (!subs->str_pd)
		return 0;

	ret = snd_usb_power_domain_set(subs->stream->chip, subs->str_pd, state);
	if (ret < 0) {
		dev_err(&subs->dev->dev,
			"Cannot change Power Domain ID: %d to state: %d. Err: %d\n",
			subs->str_pd->pd_id, state, ret);
		return ret;
	}

	return 0;
}

int snd_usb_pcm_suspend(struct snd_usb_stream *as)
{
	int ret;

	ret = snd_usb_pcm_change_state(&as->substream[0], UAC3_PD_STATE_D2);
	if (ret < 0)
		return ret;

	ret = snd_usb_pcm_change_state(&as->substream[1], UAC3_PD_STATE_D2);
	if (ret < 0)
		return ret;

	return 0;
}

int snd_usb_pcm_resume(struct snd_usb_stream *as)
{
	int ret;

870
	ret = snd_usb_pcm_change_state(&as->substream[0], UAC3_PD_STATE_D1);
871 872 873
	if (ret < 0)
		return ret;

874
	ret = snd_usb_pcm_change_state(&as->substream[1], UAC3_PD_STATE_D1);
875 876 877 878 879 880
	if (ret < 0)
		return ret;

	return 0;
}

D
Daniel Mack 已提交
881 882 883 884 885 886 887 888 889 890 891 892 893 894 895
/*
 * 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;
896
	int ret;
D
Daniel Mack 已提交
897

898 899 900 901
	ret = snd_media_start_pipeline(subs);
	if (ret)
		return ret;

902 903
	subs->pcm_format = params_format(hw_params);
	subs->period_bytes = params_period_bytes(hw_params);
904 905
	subs->period_frames = params_period_size(hw_params);
	subs->buffer_periods = params_periods(hw_params);
906 907 908
	subs->channels = params_channels(hw_params);
	subs->cur_rate = params_rate(hw_params);

909
	fmt = find_substream_format(subs);
D
Daniel Mack 已提交
910
	if (!fmt) {
911 912
		dev_dbg(&subs->dev->dev,
			"cannot set format: format = %#x, rate = %d, channels = %d\n",
913
			   subs->pcm_format, subs->cur_rate, subs->channels);
914 915
		ret = -EINVAL;
		goto stop_pipeline;
D
Daniel Mack 已提交
916 917
	}

918 919
	ret = snd_usb_lock_shutdown(subs->stream->chip);
	if (ret < 0)
920
		goto stop_pipeline;
921 922 923 924 925

	ret = snd_usb_pcm_change_state(subs, UAC3_PD_STATE_D0);
	if (ret < 0)
		goto unlock;

926
	ret = set_format(subs, fmt);
927
	if (ret < 0)
928
		goto unlock;
D
Daniel Mack 已提交
929

930 931
 unlock:
	snd_usb_unlock_shutdown(subs->stream->chip);
932 933 934 935 936 937
	if (ret < 0)
		goto stop_pipeline;
	return ret;

 stop_pipeline:
	snd_media_stop_pipeline(subs);
938
	return ret;
D
Daniel Mack 已提交
939 940 941 942 943 944 945 946 947 948
}

/*
 * 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;
949
	struct snd_usb_audio *chip = subs->stream->chip;
D
Daniel Mack 已提交
950

951
	snd_media_stop_pipeline(subs);
D
Daniel Mack 已提交
952 953 954
	subs->cur_audiofmt = NULL;
	subs->cur_rate = 0;
	subs->period_bytes = 0;
955
	if (!snd_usb_lock_shutdown(chip)) {
956 957
		stop_endpoints(subs);
		sync_pending_stops(subs);
958 959
		snd_usb_endpoint_deactivate(subs->sync_endpoint);
		snd_usb_endpoint_deactivate(subs->data_endpoint);
960 961 962 963 964
		if (subs->data_endpoint) {
			subs->data_endpoint->sync_master = NULL;
			subs->data_endpoint = NULL;
		}
		subs->sync_endpoint = NULL;
965
		snd_usb_unlock_shutdown(chip);
966
	}
967

968
	return 0;
D
Daniel Mack 已提交
969 970 971 972 973 974 975 976 977 978 979
}

/*
 * 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;
980 981 982
	struct usb_host_interface *alts;
	struct usb_interface *iface;
	int ret;
D
Daniel Mack 已提交
983 984

	if (! subs->cur_audiofmt) {
985
		dev_err(&subs->dev->dev, "no format is specified!\n");
D
Daniel Mack 已提交
986 987 988
		return -ENXIO;
	}

989 990 991
	ret = snd_usb_lock_shutdown(subs->stream->chip);
	if (ret < 0)
		return ret;
992 993 994 995
	if (snd_BUG_ON(!subs->data_endpoint)) {
		ret = -EIO;
		goto unlock;
	}
996

997 998 999 1000
	ret = snd_usb_pcm_change_state(subs, UAC3_PD_STATE_D0);
	if (ret < 0)
		goto unlock;

1001 1002
	ret = set_format(subs, subs->cur_audiofmt);
	if (ret < 0)
1003
		goto unlock;
1004

1005
	if (subs->need_setup_ep) {
1006 1007 1008 1009 1010 1011 1012 1013 1014

		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,
					       subs->cur_rate);
		if (ret < 0)
			goto unlock;

1015 1016
		ret = configure_endpoint(subs);
		if (ret < 0)
1017
			goto unlock;
1018 1019
		subs->need_setup_ep = false;
	}
1020

D
Daniel Mack 已提交
1021
	/* some unit conversions in runtime */
1022 1023 1024 1025
	subs->data_endpoint->maxframesize =
		bytes_to_frames(runtime, subs->data_endpoint->maxpacksize);
	subs->data_endpoint->curframesize =
		bytes_to_frames(runtime, subs->data_endpoint->curpacksize);
D
Daniel Mack 已提交
1026 1027 1028 1029

	/* reset the pointer */
	subs->hwptr_done = 0;
	subs->transfer_done = 0;
1030 1031
	subs->last_delay = 0;
	subs->last_frame_number = 0;
D
Daniel Mack 已提交
1032 1033
	runtime->delay = 0;

1034 1035 1036
	/* 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)
1037
		ret = start_endpoints(subs);
1038

1039
 unlock:
1040
	snd_usb_unlock_shutdown(subs->stream->chip);
1041
	return ret;
D
Daniel Mack 已提交
1042 1043
}

T
Takashi Iwai 已提交
1044 1045 1046 1047 1048 1049 1050 1051 1052 1053
/*
 * h/w constraints
 */

#ifdef HW_CONST_DEBUG
#define hwc_debug(fmt, args...) pr_debug(fmt, ##args)
#else
#define hwc_debug(fmt, args...) do { } while(0)
#endif

1054
static const struct snd_pcm_hardware snd_usb_hardware =
D
Daniel Mack 已提交
1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076
{
	.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);
1077
	struct snd_mask check_fmts;
D
Daniel Mack 已提交
1078 1079 1080
	unsigned int ptime;

	/* check the format */
1081 1082 1083 1084 1085
	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)) {
D
Daniel Mack 已提交
1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103
		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 */
1104
	if (subs->speed != USB_SPEED_FULL) {
D
Daniel Mack 已提交
1105 1106 1107 1108 1109 1110 1111 1112 1113
		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;
}

1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143
static int apply_hw_params_minmax(struct snd_interval *it, unsigned int rmin,
				  unsigned int rmax)
{
	int changed;

	if (rmin > rmax) {
		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;
}

D
Daniel Mack 已提交
1144 1145 1146 1147
static int hw_rule_rate(struct snd_pcm_hw_params *params,
			struct snd_pcm_hw_rule *rule)
{
	struct snd_usb_substream *subs = rule->private;
1148
	struct audioformat *fp;
D
Daniel Mack 已提交
1149
	struct snd_interval *it = hw_param_interval(params, SNDRV_PCM_HW_PARAM_RATE);
1150 1151
	unsigned int rmin, rmax, r;
	int i;
D
Daniel Mack 已提交
1152 1153

	hwc_debug("hw_rule_rate: (%d,%d)\n", it->min, it->max);
1154 1155
	rmin = UINT_MAX;
	rmax = 0;
1156
	list_for_each_entry(fp, &subs->fmt_list, list) {
D
Daniel Mack 已提交
1157 1158
		if (!hw_check_valid_format(subs, params, fp))
			continue;
1159 1160 1161 1162 1163 1164 1165 1166
		if (fp->rate_table && fp->nr_rates) {
			for (i = 0; i < fp->nr_rates; i++) {
				r = fp->rate_table[i];
				if (!snd_interval_test(it, r))
					continue;
				rmin = min(rmin, r);
				rmax = max(rmax, r);
			}
D
Daniel Mack 已提交
1167
		} else {
1168 1169
			rmin = min(rmin, fp->rate_min);
			rmax = max(rmax, fp->rate_max);
D
Daniel Mack 已提交
1170 1171 1172
		}
	}

1173
	return apply_hw_params_minmax(it, rmin, rmax);
D
Daniel Mack 已提交
1174 1175 1176 1177 1178 1179 1180
}


static int hw_rule_channels(struct snd_pcm_hw_params *params,
			    struct snd_pcm_hw_rule *rule)
{
	struct snd_usb_substream *subs = rule->private;
1181
	struct audioformat *fp;
D
Daniel Mack 已提交
1182 1183 1184 1185
	struct snd_interval *it = hw_param_interval(params, SNDRV_PCM_HW_PARAM_CHANNELS);
	unsigned int rmin, rmax;

	hwc_debug("hw_rule_channels: (%d,%d)\n", it->min, it->max);
1186 1187
	rmin = UINT_MAX;
	rmax = 0;
1188
	list_for_each_entry(fp, &subs->fmt_list, list) {
D
Daniel Mack 已提交
1189 1190
		if (!hw_check_valid_format(subs, params, fp))
			continue;
1191 1192
		rmin = min(rmin, fp->channels);
		rmax = max(rmax, fp->channels);
D
Daniel Mack 已提交
1193 1194
	}

1195
	return apply_hw_params_minmax(it, rmin, rmax);
D
Daniel Mack 已提交
1196 1197 1198 1199 1200 1201
}

static int hw_rule_format(struct snd_pcm_hw_params *params,
			  struct snd_pcm_hw_rule *rule)
{
	struct snd_usb_substream *subs = rule->private;
1202
	struct audioformat *fp;
D
Daniel Mack 已提交
1203 1204 1205 1206 1207 1208 1209
	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;
1210
	list_for_each_entry(fp, &subs->fmt_list, list) {
D
Daniel Mack 已提交
1211 1212
		if (!hw_check_valid_format(subs, params, fp))
			continue;
1213
		fbits |= fp->formats;
D
Daniel Mack 已提交
1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246
	}

	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;

	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) {
1247
		hwc_debug("  --> get empty\n");
D
Daniel Mack 已提交
1248 1249 1250 1251
		it->empty = 1;
		return -EINVAL;
	}
	pmin = 125 * (1 << min_datainterval);
1252 1253

	return apply_hw_params_minmax(it, pmin, UINT_MAX);
D
Daniel Mack 已提交
1254 1255
}

1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266
/* apply PCM hw constraints from the concurrent sync EP */
static int apply_hw_constraint_from_sync(struct snd_pcm_runtime *runtime,
					 struct snd_usb_substream *subs)
{
	struct snd_usb_audio *chip = subs->stream->chip;
	struct snd_usb_endpoint *ep;
	struct audioformat *fp;
	int err;

	subs->fixed_hw = 0;
	list_for_each_entry(fp, &subs->fmt_list, list) {
1267
		ep = snd_usb_get_endpoint(chip, fp->endpoint);
1268 1269 1270 1271 1272
		if (ep && ep->cur_rate)
			goto found;
		if (!fp->implicit_fb)
			continue;
		/* for the implicit fb, check the sync ep as well */
1273
		ep = snd_usb_get_endpoint(chip, fp->sync_ep);
1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311
		if (ep && ep->cur_rate)
			goto found;
	}
	return 0;

 found:
	if (!find_format(&subs->fmt_list, ep->cur_format, ep->cur_rate,
			 ep->cur_channels, NULL)) {
		usb_audio_dbg(chip, "EP 0x%x being used, but not applicable\n",
			      ep->ep_num);
		return 0;
	}

	usb_audio_dbg(chip, "EP 0x%x being used, using fixed params:\n",
		      ep->ep_num);
	usb_audio_dbg(chip, "rate=%d, format=%s, channels=%d, period_size=%d, periods=%d\n",
		      ep->cur_rate, snd_pcm_format_name(ep->cur_format),
		      ep->cur_channels, ep->cur_period_frames,
		      ep->cur_buffer_periods);

	runtime->hw.formats = pcm_format_to_bits(ep->cur_format);
	runtime->hw.rate_min = runtime->hw.rate_max = ep->cur_rate;
	runtime->hw.channels_min = runtime->hw.channels_max =
		ep->cur_channels;
	runtime->hw.rates = SNDRV_PCM_RATE_KNOT;
	runtime->hw.periods_min = runtime->hw.periods_max =
		ep->cur_buffer_periods;
	subs->fixed_hw = 1;

	err = snd_pcm_hw_constraint_minmax(runtime,
					   SNDRV_PCM_HW_PARAM_PERIOD_SIZE,
					   ep->cur_period_frames,
					   ep->cur_period_frames);
	if (err < 0)
		return err;

	return 1; /* notify the finding */
}
D
Daniel Mack 已提交
1312 1313 1314 1315 1316 1317 1318

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

static int setup_hw_info(struct snd_pcm_runtime *runtime, struct snd_usb_substream *subs)
{
1319
	struct snd_usb_audio *chip = subs->stream->chip;
1320
	struct audioformat *fp;
D
Daniel Mack 已提交
1321
	unsigned int pt, ptmin;
1322
	int param_period_time_if_needed = -1;
D
Daniel Mack 已提交
1323 1324
	int err;

1325 1326 1327 1328 1329 1330 1331 1332
	mutex_lock(&chip->mutex);
	err = apply_hw_constraint_from_sync(runtime, subs);
	mutex_unlock(&chip->mutex);
	if (err < 0)
		return err;
	if (err > 0) /* found the matching? */
		goto add_extra_rules;

D
Daniel Mack 已提交
1333 1334 1335 1336 1337 1338 1339 1340 1341
	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 */
1342
	list_for_each_entry(fp, &subs->fmt_list, list) {
D
Daniel Mack 已提交
1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361
		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);
	}

	param_period_time_if_needed = SNDRV_PCM_HW_PARAM_PERIOD_TIME;
1362
	if (subs->speed == USB_SPEED_FULL)
D
Daniel Mack 已提交
1363 1364 1365 1366 1367
		/* 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;
1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382

	err = snd_pcm_hw_constraint_minmax(runtime,
					   SNDRV_PCM_HW_PARAM_PERIOD_TIME,
					   ptmin, UINT_MAX);
	if (err < 0)
		return err;

	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);
	if (err < 0)
		return err;
1383 1384

add_extra_rules:
1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400
	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);
	if (err < 0)
		return err;
	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);
	if (err < 0)
		return err;
D
Daniel Mack 已提交
1401 1402 1403 1404 1405 1406 1407 1408 1409
	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)
1410
			return err;
D
Daniel Mack 已提交
1411
	}
1412

1413
	return 0;
D
Daniel Mack 已提交
1414 1415
}

1416
static int snd_usb_pcm_open(struct snd_pcm_substream *substream)
D
Daniel Mack 已提交
1417
{
1418
	int direction = substream->stream;
D
Daniel Mack 已提交
1419 1420 1421
	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];
1422
	int ret;
D
Daniel Mack 已提交
1423 1424

	subs->interface = -1;
1425
	subs->altset_idx = 0;
D
Daniel Mack 已提交
1426 1427 1428
	runtime->hw = snd_usb_hardware;
	runtime->private_data = subs;
	subs->pcm_substream = substream;
1429
	/* runtime PM is also done there */
1430 1431 1432 1433 1434 1435

	/* initialize DSD/DOP context */
	subs->dsd_dop.byte_idx = 0;
	subs->dsd_dop.channel = 0;
	subs->dsd_dop.marker = 1;

1436
	ret = setup_hw_info(runtime, subs);
1437 1438 1439 1440 1441 1442 1443 1444
	if (ret < 0)
		return ret;
	ret = snd_usb_autoresume(subs->stream->chip);
	if (ret < 0)
		return ret;
	ret = snd_media_stream_init(subs, as->pcm, direction);
	if (ret < 0)
		snd_usb_autosuspend(subs->stream->chip);
1445
	return ret;
D
Daniel Mack 已提交
1446 1447
}

1448
static int snd_usb_pcm_close(struct snd_pcm_substream *substream)
D
Daniel Mack 已提交
1449
{
1450
	int direction = substream->stream;
D
Daniel Mack 已提交
1451 1452
	struct snd_usb_stream *as = snd_pcm_substream_chip(substream);
	struct snd_usb_substream *subs = &as->substream[direction];
1453
	int ret;
D
Daniel Mack 已提交
1454

1455
	snd_media_stop_pipeline(subs);
1456

1457
	if (subs->interface >= 0 &&
1458
	    !snd_usb_lock_shutdown(subs->stream->chip)) {
1459 1460
		usb_set_interface(subs->dev, subs->interface, 0);
		subs->interface = -1;
1461
		ret = snd_usb_pcm_change_state(subs, UAC3_PD_STATE_D1);
1462
		snd_usb_unlock_shutdown(subs->stream->chip);
1463 1464
		if (ret < 0)
			return ret;
1465 1466
	}

D
Daniel Mack 已提交
1467
	subs->pcm_substream = NULL;
1468
	snd_usb_autosuspend(subs->stream->chip);
1469

1470
	return 0;
1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485
}

/* 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;
1486 1487 1488 1489
	int current_frame_number;

	/* read frame number here, update pointer in critical section */
	current_frame_number = usb_get_current_frame_number(subs->dev);
1490 1491 1492 1493

	stride = runtime->frame_bits >> 3;

	for (i = 0; i < urb->number_of_packets; i++) {
1494
		cp = (unsigned char *)urb->transfer_buffer + urb->iso_frame_desc[i].offset + subs->pkt_offset_adj;
1495
		if (urb->iso_frame_desc[i].status && printk_ratelimit()) {
1496 1497
			dev_dbg(&subs->dev->dev, "frame %d active: %d\n",
				i, urb->iso_frame_desc[i].status);
1498 1499 1500
			// continue;
		}
		bytes = urb->iso_frame_desc[i].actual_length;
1501 1502 1503 1504 1505 1506
		if (subs->stream_offset_adj > 0) {
			unsigned int adj = min(subs->stream_offset_adj, bytes);
			cp += adj;
			bytes -= adj;
			subs->stream_offset_adj -= adj;
		}
1507 1508 1509 1510 1511 1512
		frames = bytes / stride;
		if (!subs->txfr_quirk)
			bytes = frames * stride;
		if (bytes % (runtime->sample_bits >> 3) != 0) {
			int oldbytes = bytes;
			bytes = frames * stride;
1513
			dev_warn_ratelimited(&subs->dev->dev,
1514
				 "Corrected urb data len. %d->%d\n",
1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528
							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;
		}
1529 1530 1531 1532 1533 1534 1535 1536 1537
		/* 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 */

1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553
		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);
}

1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597
static inline void fill_playback_urb_dsd_dop(struct snd_usb_substream *subs,
					     struct urb *urb, unsigned int bytes)
{
	struct snd_pcm_runtime *runtime = subs->pcm_substream->runtime;
	unsigned int stride = runtime->frame_bits >> 3;
	unsigned int dst_idx = 0;
	unsigned int src_idx = subs->hwptr_done;
	unsigned int wrap = runtime->buffer_size * stride;
	u8 *dst = urb->transfer_buffer;
	u8 *src = runtime->dma_area;
	u8 marker[] = { 0x05, 0xfa };

	/*
	 * The DSP DOP format defines a way to transport DSD samples over
	 * normal PCM data endpoints. It requires stuffing of marker bytes
	 * (0x05 and 0xfa, alternating per sample frame), and then expects
	 * 2 additional bytes of actual payload. The whole frame is stored
	 * LSB.
	 *
	 * Hence, for a stereo transport, the buffer layout looks like this,
	 * where L refers to left channel samples and R to right.
	 *
	 *   L1 L2 0x05   R1 R2 0x05   L3 L4 0xfa  R3 R4 0xfa
	 *   L5 L6 0x05   R5 R6 0x05   L7 L8 0xfa  R7 R8 0xfa
	 *   .....
	 *
	 */

	while (bytes--) {
		if (++subs->dsd_dop.byte_idx == 3) {
			/* frame boundary? */
			dst[dst_idx++] = marker[subs->dsd_dop.marker];
			src_idx += 2;
			subs->dsd_dop.byte_idx = 0;

			if (++subs->dsd_dop.channel % runtime->channels == 0) {
				/* alternate the marker */
				subs->dsd_dop.marker++;
				subs->dsd_dop.marker %= ARRAY_SIZE(marker);
				subs->dsd_dop.channel = 0;
			}
		} else {
			/* stuff the DSD payload */
			int idx = (src_idx + subs->dsd_dop.byte_idx - 1) % wrap;
1598 1599 1600 1601 1602 1603

			if (subs->cur_audiofmt->dsd_bitrev)
				dst[dst_idx++] = bitrev8(src[idx]);
			else
				dst[dst_idx++] = src[idx];

1604 1605 1606
			subs->hwptr_done++;
		}
	}
1607 1608
	if (subs->hwptr_done >= runtime->buffer_size * stride)
		subs->hwptr_done -= runtime->buffer_size * stride;
1609 1610
}

1611 1612
static void copy_to_urb(struct snd_usb_substream *subs, struct urb *urb,
			int offset, int stride, unsigned int bytes)
1613 1614 1615 1616 1617 1618 1619
{
	struct snd_pcm_runtime *runtime = subs->pcm_substream->runtime;

	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;
1620
		memcpy(urb->transfer_buffer + offset,
1621
		       runtime->dma_area + subs->hwptr_done, bytes1);
1622
		memcpy(urb->transfer_buffer + offset + bytes1,
1623 1624
		       runtime->dma_area, bytes - bytes1);
	} else {
1625
		memcpy(urb->transfer_buffer + offset,
1626 1627 1628
		       runtime->dma_area + subs->hwptr_done, bytes);
	}
	subs->hwptr_done += bytes;
1629 1630
	if (subs->hwptr_done >= runtime->buffer_size * stride)
		subs->hwptr_done -= runtime->buffer_size * stride;
1631 1632
}

1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658
static unsigned int copy_to_urb_quirk(struct snd_usb_substream *subs,
				      struct urb *urb, int stride,
				      unsigned int bytes)
{
	__le32 packet_length;
	int i;

	/* Put __le32 length descriptor at start of each packet. */
	for (i = 0; i < urb->number_of_packets; i++) {
		unsigned int length = urb->iso_frame_desc[i].length;
		unsigned int offset = urb->iso_frame_desc[i].offset;

		packet_length = cpu_to_le32(length);
		offset += i * sizeof(packet_length);
		urb->iso_frame_desc[i].offset = offset;
		urb->iso_frame_desc[i].length += sizeof(packet_length);
		memcpy(urb->transfer_buffer + offset,
		       &packet_length, sizeof(packet_length));
		copy_to_urb(subs, urb, offset + sizeof(packet_length),
			    stride, length);
	}
	/* Adjust transfer size accordingly. */
	bytes += urb->number_of_packets * sizeof(packet_length);
	return bytes;
}

1659 1660 1661 1662
static void prepare_playback_urb(struct snd_usb_substream *subs,
				 struct urb *urb)
{
	struct snd_pcm_runtime *runtime = subs->pcm_substream->runtime;
1663
	struct snd_usb_endpoint *ep = subs->data_endpoint;
1664 1665 1666 1667 1668 1669 1670 1671 1672 1673
	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);
1674
	subs->frame_limit += ep->max_urb_frames;
1675
	for (i = 0; i < ctx->packets; i++) {
1676 1677
		if (ctx->packet_size[i])
			counts = ctx->packet_size[i];
1678 1679
		else if (ep->sync_master)
			counts = snd_usb_endpoint_slave_next_packet_size(ep);
1680 1681 1682
		else
			counts = snd_usb_endpoint_next_packet_size(ep);

1683
		/* set up descriptor */
1684 1685
		urb->iso_frame_desc[i].offset = frames * ep->stride;
		urb->iso_frame_desc[i].length = counts * ep->stride;
1686 1687 1688 1689 1690
		frames += counts;
		urb->number_of_packets++;
		subs->transfer_done += counts;
		if (subs->transfer_done >= runtime->period_size) {
			subs->transfer_done -= runtime->period_size;
1691
			subs->frame_limit = 0;
1692 1693 1694 1695 1696 1697 1698 1699
			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 =
1700
						counts * ep->stride;
1701 1702 1703 1704 1705 1706
					subs->transfer_done = 0;
				}
				i++;
				if (i < ctx->packets) {
					/* add a transfer delimiter */
					urb->iso_frame_desc[i].offset =
1707
						frames * ep->stride;
1708 1709 1710 1711 1712 1713
					urb->iso_frame_desc[i].length = 0;
					urb->number_of_packets++;
				}
				break;
			}
		}
1714 1715 1716 1717
		/* finish at the period boundary or after enough frames */
		if ((period_elapsed ||
				subs->transfer_done >= subs->frame_limit) &&
		    !snd_usb_endpoint_implicit_feedback_sink(ep))
1718 1719
			break;
	}
1720
	bytes = frames * ep->stride;
1721 1722 1723 1724

	if (unlikely(subs->pcm_format == SNDRV_PCM_FORMAT_DSD_U16_LE &&
		     subs->cur_audiofmt->dsd_dop)) {
		fill_playback_urb_dsd_dop(subs, urb, bytes);
1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735
	} else if (unlikely(subs->pcm_format == SNDRV_PCM_FORMAT_DSD_U8 &&
			   subs->cur_audiofmt->dsd_bitrev)) {
		/* bit-reverse the bytes */
		u8 *buf = urb->transfer_buffer;
		for (i = 0; i < bytes; i++) {
			int idx = (subs->hwptr_done + i)
				% (runtime->buffer_size * stride);
			buf[i] = bitrev8(runtime->dma_area[idx]);
		}

		subs->hwptr_done += bytes;
1736 1737
		if (subs->hwptr_done >= runtime->buffer_size * stride)
			subs->hwptr_done -= runtime->buffer_size * stride;
1738
	} else {
1739
		/* usual PCM */
1740 1741 1742 1743 1744
		if (!subs->tx_length_quirk)
			copy_to_urb(subs, urb, 0, stride, bytes);
		else
			bytes = copy_to_urb_quirk(subs, urb, stride, bytes);
			/* bytes is now amount of outgoing data */
1745
	}
1746

1747 1748
	/* update delay with exact number of samples queued */
	runtime->delay = subs->last_delay;
1749
	runtime->delay += frames;
1750 1751 1752 1753 1754 1755
	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 */

1756 1757 1758 1759 1760 1761 1762 1763
	if (subs->trigger_tstamp_pending_update) {
		/* this is the first actual URB submitted,
		 * update trigger timestamp to reflect actual start time
		 */
		snd_pcm_gettime(runtime, &runtime->trigger_tstamp);
		subs->trigger_tstamp_pending_update = false;
	}

1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778
	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;
1779 1780
	struct snd_usb_endpoint *ep = subs->data_endpoint;
	int processed = urb->transfer_buffer_length / ep->stride;
1781
	int est_delay;
1782

A
Alexander Tsoy 已提交
1783 1784
	/* ignore the delay accounting when processed=0 is given, i.e.
	 * silent payloads are processed before handling the actual data
1785 1786 1787 1788
	 */
	if (!processed)
		return;

1789
	spin_lock_irqsave(&subs->lock, flags);
1790 1791 1792
	if (!subs->last_delay)
		goto out; /* short path */

1793 1794 1795 1796
	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;
1797
	else
1798 1799 1800 1801 1802 1803 1804 1805
		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.
	 */
1806 1807
	if (abs(est_delay - subs->last_delay) * 1000 > runtime->rate * 2)
		dev_dbg_ratelimited(&subs->dev->dev,
1808
			"delay: estimated %d, actual %d\n",
1809 1810
			est_delay, subs->last_delay);

1811 1812 1813 1814 1815 1816 1817 1818 1819
	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:
1820
	spin_unlock_irqrestore(&subs->lock, flags);
D
Daniel Mack 已提交
1821 1822
}

1823 1824 1825 1826 1827 1828 1829
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:
1830
		subs->trigger_tstamp_pending_update = true;
1831
		fallthrough;
1832 1833 1834
	case SNDRV_PCM_TRIGGER_PAUSE_RELEASE:
		subs->data_endpoint->prepare_data_urb = prepare_playback_urb;
		subs->data_endpoint->retire_data_urb = retire_playback_urb;
1835
		subs->running = 1;
1836 1837
		return 0;
	case SNDRV_PCM_TRIGGER_STOP:
1838
		stop_endpoints(subs);
1839
		subs->running = 0;
1840 1841 1842
		return 0;
	case SNDRV_PCM_TRIGGER_PAUSE_PUSH:
		subs->data_endpoint->prepare_data_urb = NULL;
1843 1844
		/* keep retire_data_urb for delay calculation */
		subs->data_endpoint->retire_data_urb = retire_playback_urb;
1845
		subs->running = 0;
1846
		return 0;
1847 1848
	case SNDRV_PCM_TRIGGER_SUSPEND:
		if (subs->stream->chip->setup_fmt_after_resume_quirk) {
1849
			stop_endpoints(subs);
1850 1851 1852 1853
			subs->need_setup_fmt = true;
			return 0;
		}
		break;
1854 1855 1856 1857 1858
	}

	return -EINVAL;
}

1859 1860
static int snd_usb_substream_capture_trigger(struct snd_pcm_substream *substream,
					     int cmd)
1861 1862 1863 1864 1865 1866
{
	int err;
	struct snd_usb_substream *subs = substream->runtime->private_data;

	switch (cmd) {
	case SNDRV_PCM_TRIGGER_START:
1867
		err = start_endpoints(subs);
1868 1869 1870 1871
		if (err < 0)
			return err;

		subs->data_endpoint->retire_data_urb = retire_capture_urb;
1872
		subs->running = 1;
1873 1874
		return 0;
	case SNDRV_PCM_TRIGGER_STOP:
1875
		stop_endpoints(subs);
1876
		subs->data_endpoint->retire_data_urb = NULL;
1877
		subs->running = 0;
1878 1879 1880
		return 0;
	case SNDRV_PCM_TRIGGER_PAUSE_PUSH:
		subs->data_endpoint->retire_data_urb = NULL;
1881
		subs->running = 0;
1882 1883 1884
		return 0;
	case SNDRV_PCM_TRIGGER_PAUSE_RELEASE:
		subs->data_endpoint->retire_data_urb = retire_capture_urb;
1885
		subs->running = 1;
1886
		return 0;
1887 1888
	case SNDRV_PCM_TRIGGER_SUSPEND:
		if (subs->stream->chip->setup_fmt_after_resume_quirk) {
1889
			stop_endpoints(subs);
1890 1891 1892 1893
			subs->need_setup_fmt = true;
			return 0;
		}
		break;
1894 1895 1896 1897 1898
	}

	return -EINVAL;
}

1899
static const struct snd_pcm_ops snd_usb_playback_ops = {
1900 1901
	.open =		snd_usb_pcm_open,
	.close =	snd_usb_pcm_close,
D
Daniel Mack 已提交
1902 1903 1904 1905
	.hw_params =	snd_usb_hw_params,
	.hw_free =	snd_usb_hw_free,
	.prepare =	snd_usb_pcm_prepare,
	.trigger =	snd_usb_substream_playback_trigger,
1906
	.sync_stop =	snd_usb_pcm_sync_stop,
D
Daniel Mack 已提交
1907 1908 1909
	.pointer =	snd_usb_pcm_pointer,
};

1910
static const struct snd_pcm_ops snd_usb_capture_ops = {
1911 1912
	.open =		snd_usb_pcm_open,
	.close =	snd_usb_pcm_close,
D
Daniel Mack 已提交
1913 1914 1915 1916
	.hw_params =	snd_usb_hw_params,
	.hw_free =	snd_usb_hw_free,
	.prepare =	snd_usb_pcm_prepare,
	.trigger =	snd_usb_substream_capture_trigger,
1917
	.sync_stop =	snd_usb_pcm_sync_stop,
D
Daniel Mack 已提交
1918
	.pointer =	snd_usb_pcm_pointer,
1919 1920
};

D
Daniel Mack 已提交
1921 1922
void snd_usb_set_pcm_ops(struct snd_pcm *pcm, int stream)
{
1923 1924
	const struct snd_pcm_ops *ops;

1925
	ops = stream == SNDRV_PCM_STREAM_PLAYBACK ?
1926 1927 1928 1929 1930 1931 1932 1933 1934 1935
			&snd_usb_playback_ops : &snd_usb_capture_ops;
	snd_pcm_set_ops(pcm, stream, ops);
}

void snd_usb_preallocate_buffer(struct snd_usb_substream *subs)
{
	struct snd_pcm *pcm = subs->stream->pcm;
	struct snd_pcm_substream *s = pcm->streams[subs->direction].substream;
	struct device *dev = subs->dev->bus->controller;

1936
	if (snd_usb_use_vmalloc)
1937 1938
		snd_pcm_set_managed_buffer(s, SNDRV_DMA_TYPE_VMALLOC,
					   NULL, 0, 0);
1939
	else
1940 1941
		snd_pcm_set_managed_buffer(s, SNDRV_DMA_TYPE_DEV_SG,
					   dev, 64*1024, 512*1024);
D
Daniel Mack 已提交
1942
}