File Index
Files and directories
Sign in
FILE

pcm.c

File preview with syntax highlighting.

linux-6.19.14/sound/usb/pcm.c C
   1// SPDX-License-Identifier: GPL-2.0-or-later
   2/*
   3 */
   4
   5#include <linux/init.h>
   6#include <linux/slab.h>
   7#include <linux/bitrev.h>
   8#include <linux/ratelimit.h>
   9#include <linux/usb.h>
  10#include <linux/usb/audio.h>
  11#include <linux/usb/audio-v2.h>
  12
  13#include <sound/core.h>
  14#include <sound/pcm.h>
  15#include <sound/pcm_params.h>
  16
  17#include "usbaudio.h"
  18#include "card.h"
  19#include "quirks.h"
  20#include "endpoint.h"
  21#include "helper.h"
  22#include "pcm.h"
  23#include "clock.h"
  24#include "power.h"
  25#include "media.h"
  26#include "implicit.h"
  27
  28#define SUBSTREAM_FLAG_DATA_EP_STARTED	0
  29#define SUBSTREAM_FLAG_SYNC_EP_STARTED	1
  30
  31/* return the estimated delay based on USB frame counters */
  32static snd_pcm_uframes_t snd_usb_pcm_delay(struct snd_usb_substream *subs,
  33					   struct snd_pcm_runtime *runtime)
  34{
  35	unsigned int current_frame_number;
  36	unsigned int frame_diff;
  37	int est_delay;
  38	int queued;
  39
  40	if (subs->direction == SNDRV_PCM_STREAM_PLAYBACK) {
  41		queued = bytes_to_frames(runtime, subs->inflight_bytes);
  42		if (!queued)
  43			return 0;
  44	} else if (!subs->running) {
  45		return 0;
  46	}
  47
  48	current_frame_number = usb_get_current_frame_number(subs->dev);
  49	/*
  50	 * HCD implementations use different widths, use lower 8 bits.
  51	 * The delay will be managed up to 256ms, which is more than
  52	 * enough
  53	 */
  54	frame_diff = (current_frame_number - subs->last_frame_number) & 0xff;
  55
  56	/* Approximation based on number of samples per USB frame (ms),
  57	   some truncation for 44.1 but the estimate is good enough */
  58	est_delay = frame_diff * runtime->rate / 1000;
  59
  60	if (subs->direction == SNDRV_PCM_STREAM_PLAYBACK) {
  61		est_delay = queued - est_delay;
  62		if (est_delay < 0)
  63			est_delay = 0;
  64	}
  65
  66	return est_delay;
  67}
  68
  69/*
  70 * return the current pcm pointer.  just based on the hwptr_done value.
  71 */
  72static snd_pcm_uframes_t snd_usb_pcm_pointer(struct snd_pcm_substream *substream)
  73{
  74	struct snd_pcm_runtime *runtime = substream->runtime;
  75	struct snd_usb_substream *subs = runtime->private_data;
  76	unsigned int hwptr_done;
  77
  78	if (atomic_read(&subs->stream->chip->shutdown))
  79		return SNDRV_PCM_POS_XRUN;
  80	scoped_guard(spinlock, &subs->lock) {
  81		hwptr_done = subs->hwptr_done;
  82		runtime->delay = snd_usb_pcm_delay(subs, runtime);
  83	}
  84	return bytes_to_frames(runtime, hwptr_done);
  85}
  86
  87/*
  88 * find a matching audio format
  89 */
  90static const struct audioformat *
  91find_format(struct list_head *fmt_list_head, snd_pcm_format_t format,
  92	    unsigned int rate, unsigned int channels, bool strict_match,
  93	    struct snd_usb_substream *subs)
  94{
  95	const struct audioformat *fp;
  96	const struct audioformat *found = NULL;
  97	int cur_attr = 0, attr;
  98
  99	list_for_each_entry(fp, fmt_list_head, list) {
 100		if (strict_match) {
 101			if (!(fp->formats & pcm_format_to_bits(format)))
 102				continue;
 103			if (fp->channels != channels)
 104				continue;
 105		}
 106		if (rate < fp->rate_min || rate > fp->rate_max)
 107			continue;
 108		if (!(fp->rates & SNDRV_PCM_RATE_CONTINUOUS)) {
 109			unsigned int i;
 110			for (i = 0; i < fp->nr_rates; i++)
 111				if (fp->rate_table[i] == rate)
 112					break;
 113			if (i >= fp->nr_rates)
 114				continue;
 115		}
 116		attr = fp->ep_attr & USB_ENDPOINT_SYNCTYPE;
 117		if (!found) {
 118			found = fp;
 119			cur_attr = attr;
 120			continue;
 121		}
 122		/* avoid async out and adaptive in if the other method
 123		 * supports the same format.
 124		 * this is a workaround for the case like
 125		 * M-audio audiophile USB.
 126		 */
 127		if (subs && attr != cur_attr) {
 128			if ((attr == USB_ENDPOINT_SYNC_ASYNC &&
 129			     subs->direction == SNDRV_PCM_STREAM_PLAYBACK) ||
 130			    (attr == USB_ENDPOINT_SYNC_ADAPTIVE &&
 131			     subs->direction == SNDRV_PCM_STREAM_CAPTURE))
 132				continue;
 133			if ((cur_attr == USB_ENDPOINT_SYNC_ASYNC &&
 134			     subs->direction == SNDRV_PCM_STREAM_PLAYBACK) ||
 135			    (cur_attr == USB_ENDPOINT_SYNC_ADAPTIVE &&
 136			     subs->direction == SNDRV_PCM_STREAM_CAPTURE)) {
 137				found = fp;
 138				cur_attr = attr;
 139				continue;
 140			}
 141		}
 142		/* find the format with the largest max. packet size */
 143		if (fp->maxpacksize > found->maxpacksize) {
 144			found = fp;
 145			cur_attr = attr;
 146		}
 147	}
 148	return found;
 149}
 150
 151const struct audioformat *
 152snd_usb_find_format(struct list_head *fmt_list_head, snd_pcm_format_t format,
 153		    unsigned int rate, unsigned int channels, bool strict_match,
 154		    struct snd_usb_substream *subs)
 155{
 156	return find_format(fmt_list_head, format, rate, channels, strict_match,
 157			subs);
 158}
 159EXPORT_SYMBOL_GPL(snd_usb_find_format);
 160
 161static const struct audioformat *
 162find_substream_format(struct snd_usb_substream *subs,
 163		      const struct snd_pcm_hw_params *params)
 164{
 165	return find_format(&subs->fmt_list, params_format(params),
 166			   params_rate(params), params_channels(params),
 167			   true, subs);
 168}
 169
 170const struct audioformat *
 171snd_usb_find_substream_format(struct snd_usb_substream *subs,
 172			      const struct snd_pcm_hw_params *params)
 173{
 174	return find_substream_format(subs, params);
 175}
 176EXPORT_SYMBOL_GPL(snd_usb_find_substream_format);
 177
 178bool snd_usb_pcm_has_fixed_rate(struct snd_usb_substream *subs)
 179{
 180	const struct audioformat *fp;
 181	struct snd_usb_audio *chip;
 182	int rate = -1;
 183
 184	if (!subs)
 185		return false;
 186	chip = subs->stream->chip;
 187	if (!(chip->quirk_flags & QUIRK_FLAG_FIXED_RATE))
 188		return false;
 189	list_for_each_entry(fp, &subs->fmt_list, list) {
 190		if (fp->rates & SNDRV_PCM_RATE_CONTINUOUS)
 191			return false;
 192		if (fp->nr_rates < 1)
 193			continue;
 194		if (fp->nr_rates > 1)
 195			return false;
 196		if (rate < 0) {
 197			rate = fp->rate_table[0];
 198			continue;
 199		}
 200		if (rate != fp->rate_table[0])
 201			return false;
 202	}
 203	return true;
 204}
 205
 206static int init_pitch_v1(struct snd_usb_audio *chip, int ep)
 207{
 208	struct usb_device *dev = chip->dev;
 209	unsigned char data[1];
 210	int err;
 211
 212	data[0] = 1;
 213	err = snd_usb_ctl_msg(dev, usb_sndctrlpipe(dev, 0), UAC_SET_CUR,
 214			      USB_TYPE_CLASS|USB_RECIP_ENDPOINT|USB_DIR_OUT,
 215			      UAC_EP_CS_ATTR_PITCH_CONTROL << 8, ep,
 216			      data, sizeof(data));
 217	return err;
 218}
 219
 220static int init_pitch_v2(struct snd_usb_audio *chip, int ep)
 221{
 222	struct usb_device *dev = chip->dev;
 223	unsigned char data[1];
 224	int err;
 225
 226	data[0] = 1;
 227	err = snd_usb_ctl_msg(dev, usb_sndctrlpipe(dev, 0), UAC2_CS_CUR,
 228			      USB_TYPE_CLASS | USB_RECIP_ENDPOINT | USB_DIR_OUT,
 229			      UAC2_EP_CS_PITCH << 8, 0,
 230			      data, sizeof(data));
 231	return err;
 232}
 233
 234/*
 235 * initialize the pitch control and sample rate
 236 */
 237int snd_usb_init_pitch(struct snd_usb_audio *chip,
 238		       const struct audioformat *fmt)
 239{
 240	int err;
 241
 242	/* if endpoint doesn't have pitch control, bail out */
 243	if (!(fmt->attributes & UAC_EP_CS_ATTR_PITCH_CONTROL))
 244		return 0;
 245
 246	usb_audio_dbg(chip, "enable PITCH for EP 0x%x\n", fmt->endpoint);
 247
 248	switch (fmt->protocol) {
 249	case UAC_VERSION_1:
 250		err = init_pitch_v1(chip, fmt->endpoint);
 251		break;
 252	case UAC_VERSION_2:
 253		err = init_pitch_v2(chip, fmt->endpoint);
 254		break;
 255	default:
 256		return 0;
 257	}
 258
 259	if (err < 0) {
 260		usb_audio_err(chip, "failed to enable PITCH for EP 0x%x\n",
 261			      fmt->endpoint);
 262		return err;
 263	}
 264
 265	return 0;
 266}
 267
 268static bool stop_endpoints(struct snd_usb_substream *subs, bool keep_pending)
 269{
 270	bool stopped = 0;
 271
 272	if (test_and_clear_bit(SUBSTREAM_FLAG_SYNC_EP_STARTED, &subs->flags)) {
 273		snd_usb_endpoint_stop(subs->sync_endpoint, keep_pending);
 274		stopped = true;
 275	}
 276	if (test_and_clear_bit(SUBSTREAM_FLAG_DATA_EP_STARTED, &subs->flags)) {
 277		snd_usb_endpoint_stop(subs->data_endpoint, keep_pending);
 278		stopped = true;
 279	}
 280	return stopped;
 281}
 282
 283static int start_endpoints(struct snd_usb_substream *subs)
 284{
 285	int err;
 286
 287	if (!subs->data_endpoint)
 288		return -EINVAL;
 289
 290	if (!test_and_set_bit(SUBSTREAM_FLAG_DATA_EP_STARTED, &subs->flags)) {
 291		err = snd_usb_endpoint_start(subs->data_endpoint);
 292		if (err < 0) {
 293			clear_bit(SUBSTREAM_FLAG_DATA_EP_STARTED, &subs->flags);
 294			goto error;
 295		}
 296	}
 297
 298	if (subs->sync_endpoint &&
 299	    !test_and_set_bit(SUBSTREAM_FLAG_SYNC_EP_STARTED, &subs->flags)) {
 300		err = snd_usb_endpoint_start(subs->sync_endpoint);
 301		if (err < 0) {
 302			clear_bit(SUBSTREAM_FLAG_SYNC_EP_STARTED, &subs->flags);
 303			goto error;
 304		}
 305	}
 306
 307	return 0;
 308
 309 error:
 310	stop_endpoints(subs, false);
 311	return err;
 312}
 313
 314static void sync_pending_stops(struct snd_usb_substream *subs)
 315{
 316	snd_usb_endpoint_sync_pending_stop(subs->sync_endpoint);
 317	snd_usb_endpoint_sync_pending_stop(subs->data_endpoint);
 318}
 319
 320/* PCM sync_stop callback */
 321static int snd_usb_pcm_sync_stop(struct snd_pcm_substream *substream)
 322{
 323	struct snd_usb_substream *subs = substream->runtime->private_data;
 324
 325	sync_pending_stops(subs);
 326	return 0;
 327}
 328
 329/* Set up sync endpoint */
 330int snd_usb_audioformat_set_sync_ep(struct snd_usb_audio *chip,
 331				    struct audioformat *fmt)
 332{
 333	struct usb_device *dev = chip->dev;
 334	struct usb_host_interface *alts;
 335	struct usb_interface_descriptor *altsd;
 336	unsigned int ep, attr, sync_attr;
 337	bool is_playback;
 338	int err;
 339
 340	if (fmt->sync_ep)
 341		return 0; /* already set up */
 342
 343	alts = snd_usb_get_host_interface(chip, fmt->iface, fmt->altsetting);
 344	if (!alts)
 345		return 0;
 346	altsd = get_iface_desc(alts);
 347
 348	err = snd_usb_parse_implicit_fb_quirk(chip, fmt, alts);
 349	if (err > 0)
 350		return 0; /* matched */
 351
 352	/*
 353	 * Generic sync EP handling
 354	 */
 355
 356	if (fmt->ep_idx > 0 || altsd->bNumEndpoints < 2)
 357		return 0;
 358
 359	is_playback = !(get_endpoint(alts, 0)->bEndpointAddress & USB_DIR_IN);
 360	attr = fmt->ep_attr & USB_ENDPOINT_SYNCTYPE;
 361	if ((is_playback && (attr == USB_ENDPOINT_SYNC_SYNC ||
 362			     attr == USB_ENDPOINT_SYNC_ADAPTIVE)) ||
 363	    (!is_playback && attr != USB_ENDPOINT_SYNC_ADAPTIVE))
 364		return 0;
 365
 366	sync_attr = get_endpoint(alts, 1)->bmAttributes;
 367
 368	/*
 369	 * In case of illegal SYNC_NONE for OUT endpoint, we keep going to see
 370	 * if we don't find a sync endpoint, as on M-Audio Transit. In case of
 371	 * error fall back to SYNC mode and don't create sync endpoint
 372	 */
 373
 374	/* check sync-pipe endpoint */
 375	/* ... and check descriptor size before accessing bSynchAddress
 376	   because there is a version of the SB Audigy 2 NX firmware lacking
 377	   the audio fields in the endpoint descriptors */
 378	if ((sync_attr & USB_ENDPOINT_XFERTYPE_MASK) != USB_ENDPOINT_XFER_ISOC ||
 379	    (get_endpoint(alts, 1)->bLength >= USB_DT_ENDPOINT_AUDIO_SIZE &&
 380	     get_endpoint(alts, 1)->bSynchAddress != 0)) {
 381		dev_err(&dev->dev,
 382			"%d:%d : invalid sync pipe. bmAttributes %02x, bLength %d, bSynchAddress %02x\n",
 383			   fmt->iface, fmt->altsetting,
 384			   get_endpoint(alts, 1)->bmAttributes,
 385			   get_endpoint(alts, 1)->bLength,
 386			   get_endpoint(alts, 1)->bSynchAddress);
 387		if (is_playback && attr == USB_ENDPOINT_SYNC_NONE)
 388			return 0;
 389		return -EINVAL;
 390	}
 391	ep = get_endpoint(alts, 1)->bEndpointAddress;
 392	if (get_endpoint(alts, 0)->bLength >= USB_DT_ENDPOINT_AUDIO_SIZE &&
 393	    get_endpoint(alts, 0)->bSynchAddress != 0 &&
 394	    ((is_playback && ep != (unsigned int)(get_endpoint(alts, 0)->bSynchAddress | USB_DIR_IN)) ||
 395	     (!is_playback && ep != (unsigned int)(get_endpoint(alts, 0)->bSynchAddress & ~USB_DIR_IN)))) {
 396		dev_err(&dev->dev,
 397			"%d:%d : invalid sync pipe. is_playback %d, ep %02x, bSynchAddress %02x\n",
 398			   fmt->iface, fmt->altsetting,
 399			   is_playback, ep, get_endpoint(alts, 0)->bSynchAddress);
 400		if (is_playback && attr == USB_ENDPOINT_SYNC_NONE)
 401			return 0;
 402		return -EINVAL;
 403	}
 404
 405	fmt->sync_ep = ep;
 406	fmt->sync_iface = altsd->bInterfaceNumber;
 407	fmt->sync_altsetting = altsd->bAlternateSetting;
 408	fmt->sync_ep_idx = 1;
 409	if ((sync_attr & USB_ENDPOINT_USAGE_MASK) == USB_ENDPOINT_USAGE_IMPLICIT_FB)
 410		fmt->implicit_fb = 1;
 411
 412	dev_dbg(&dev->dev, "%d:%d: found sync_ep=0x%x, iface=%d, alt=%d, implicit_fb=%d\n",
 413		fmt->iface, fmt->altsetting, fmt->sync_ep, fmt->sync_iface,
 414		fmt->sync_altsetting, fmt->implicit_fb);
 415
 416	return 0;
 417}
 418
 419static int snd_usb_pcm_change_state(struct snd_usb_substream *subs, int state)
 420{
 421	int ret;
 422
 423	if (!subs->str_pd)
 424		return 0;
 425
 426	ret = snd_usb_power_domain_set(subs->stream->chip, subs->str_pd, state);
 427	if (ret < 0) {
 428		dev_err(&subs->dev->dev,
 429			"Cannot change Power Domain ID: %d to state: %d. Err: %d\n",
 430			subs->str_pd->pd_id, state, ret);
 431		return ret;
 432	}
 433
 434	return 0;
 435}
 436
 437int snd_usb_pcm_suspend(struct snd_usb_stream *as)
 438{
 439	int ret;
 440
 441	ret = snd_usb_pcm_change_state(&as->substream[0], UAC3_PD_STATE_D2);
 442	if (ret < 0)
 443		return ret;
 444
 445	ret = snd_usb_pcm_change_state(&as->substream[1], UAC3_PD_STATE_D2);
 446	if (ret < 0)
 447		return ret;
 448
 449	return 0;
 450}
 451
 452int snd_usb_pcm_resume(struct snd_usb_stream *as)
 453{
 454	int ret;
 455
 456	ret = snd_usb_pcm_change_state(&as->substream[0], UAC3_PD_STATE_D1);
 457	if (ret < 0)
 458		return ret;
 459
 460	ret = snd_usb_pcm_change_state(&as->substream[1], UAC3_PD_STATE_D1);
 461	if (ret < 0)
 462		return ret;
 463
 464	return 0;
 465}
 466
 467static void close_endpoints(struct snd_usb_audio *chip,
 468			    struct snd_usb_substream *subs)
 469{
 470	if (subs->data_endpoint) {
 471		snd_usb_endpoint_set_sync(chip, subs->data_endpoint, NULL);
 472		snd_usb_endpoint_close(chip, subs->data_endpoint);
 473		subs->data_endpoint = NULL;
 474	}
 475
 476	if (subs->sync_endpoint) {
 477		snd_usb_endpoint_close(chip, subs->sync_endpoint);
 478		subs->sync_endpoint = NULL;
 479	}
 480}
 481
 482int snd_usb_hw_params(struct snd_usb_substream *subs,
 483		      struct snd_pcm_hw_params *hw_params)
 484{
 485	struct snd_usb_audio *chip = subs->stream->chip;
 486	const struct audioformat *fmt;
 487	const struct audioformat *sync_fmt;
 488	bool fixed_rate, sync_fixed_rate;
 489	int ret;
 490
 491	ret = snd_media_start_pipeline(subs);
 492	if (ret)
 493		return ret;
 494
 495	fixed_rate = snd_usb_pcm_has_fixed_rate(subs);
 496	fmt = find_substream_format(subs, hw_params);
 497	if (!fmt) {
 498		usb_audio_dbg(chip,
 499			      "cannot find format: format=%s, rate=%d, channels=%d\n",
 500			      snd_pcm_format_name(params_format(hw_params)),
 501			      params_rate(hw_params), params_channels(hw_params));
 502		ret = -EINVAL;
 503		goto stop_pipeline;
 504	}
 505
 506	if (fmt->implicit_fb) {
 507		sync_fmt = snd_usb_find_implicit_fb_sync_format(chip, fmt,
 508								hw_params,
 509								!subs->direction,
 510								&sync_fixed_rate);
 511		if (!sync_fmt) {
 512			usb_audio_dbg(chip,
 513				      "cannot find sync format: ep=0x%x, iface=%d:%d, format=%s, rate=%d, channels=%d\n",
 514				      fmt->sync_ep, fmt->sync_iface,
 515				      fmt->sync_altsetting,
 516				      snd_pcm_format_name(params_format(hw_params)),
 517				      params_rate(hw_params), params_channels(hw_params));
 518			ret = -EINVAL;
 519			goto stop_pipeline;
 520		}
 521	} else {
 522		sync_fmt = fmt;
 523		sync_fixed_rate = fixed_rate;
 524	}
 525
 526	ret = snd_usb_lock_shutdown(chip);
 527	if (ret < 0)
 528		goto stop_pipeline;
 529
 530	ret = snd_usb_pcm_change_state(subs, UAC3_PD_STATE_D0);
 531	if (ret < 0)
 532		goto unlock;
 533
 534	if (subs->data_endpoint) {
 535		if (snd_usb_endpoint_compatible(chip, subs->data_endpoint,
 536						fmt, hw_params))
 537			goto unlock;
 538		if (stop_endpoints(subs, false))
 539			sync_pending_stops(subs);
 540		close_endpoints(chip, subs);
 541	}
 542
 543	subs->data_endpoint = snd_usb_endpoint_open(chip, fmt, hw_params, false, fixed_rate);
 544	if (!subs->data_endpoint) {
 545		ret = -EINVAL;
 546		goto unlock;
 547	}
 548
 549	if (fmt->sync_ep) {
 550		subs->sync_endpoint = snd_usb_endpoint_open(chip, sync_fmt,
 551							    hw_params,
 552							    fmt == sync_fmt,
 553							    sync_fixed_rate);
 554		if (!subs->sync_endpoint) {
 555			ret = -EINVAL;
 556			goto unlock;
 557		}
 558
 559		snd_usb_endpoint_set_sync(chip, subs->data_endpoint,
 560					  subs->sync_endpoint);
 561	}
 562
 563	scoped_guard(mutex, &chip->mutex) {
 564		subs->cur_audiofmt = fmt;
 565	}
 566
 567	if (!subs->data_endpoint->need_setup)
 568		goto unlock;
 569
 570	if (subs->sync_endpoint) {
 571		ret = snd_usb_endpoint_set_params(chip, subs->sync_endpoint);
 572		if (ret < 0)
 573			goto unlock;
 574	}
 575
 576	ret = snd_usb_endpoint_set_params(chip, subs->data_endpoint);
 577
 578 unlock:
 579	if (ret < 0)
 580		close_endpoints(chip, subs);
 581
 582	snd_usb_unlock_shutdown(chip);
 583 stop_pipeline:
 584	if (ret < 0)
 585		snd_media_stop_pipeline(subs);
 586
 587	return ret;
 588}
 589EXPORT_SYMBOL_GPL(snd_usb_hw_params);
 590
 591/*
 592 * hw_params callback
 593 *
 594 * allocate a buffer and set the given audio format.
 595 *
 596 * so far we use a physically linear buffer although packetize transfer
 597 * doesn't need a continuous area.
 598 * if sg buffer is supported on the later version of alsa, we'll follow
 599 * that.
 600 */
 601static int snd_usb_pcm_hw_params(struct snd_pcm_substream *substream,
 602				 struct snd_pcm_hw_params *hw_params)
 603{
 604	struct snd_usb_substream *subs = substream->runtime->private_data;
 605
 606	return snd_usb_hw_params(subs, hw_params);
 607}
 608
 609int snd_usb_hw_free(struct snd_usb_substream *subs)
 610{
 611	struct snd_usb_audio *chip = subs->stream->chip;
 612
 613	snd_media_stop_pipeline(subs);
 614	scoped_guard(mutex, &chip->mutex) {
 615		subs->cur_audiofmt = NULL;
 616	}
 617	CLASS(snd_usb_lock, pm)(chip);
 618	if (!pm.err) {
 619		if (stop_endpoints(subs, false))
 620			sync_pending_stops(subs);
 621		close_endpoints(chip, subs);
 622	}
 623
 624	return 0;
 625}
 626EXPORT_SYMBOL_GPL(snd_usb_hw_free);
 627
 628/*
 629 * hw_free callback
 630 *
 631 * reset the audio format and release the buffer
 632 */
 633static int snd_usb_pcm_hw_free(struct snd_pcm_substream *substream)
 634{
 635	struct snd_usb_substream *subs = substream->runtime->private_data;
 636
 637	return snd_usb_hw_free(subs);
 638}
 639
 640/* free-wheeling mode? (e.g. dmix) */
 641static int in_free_wheeling_mode(struct snd_pcm_runtime *runtime)
 642{
 643	return runtime->stop_threshold > runtime->buffer_size;
 644}
 645
 646/* check whether early start is needed for playback stream */
 647static int lowlatency_playback_available(struct snd_pcm_runtime *runtime,
 648					 struct snd_usb_substream *subs)
 649{
 650	struct snd_usb_audio *chip = subs->stream->chip;
 651
 652	if (subs->direction == SNDRV_PCM_STREAM_CAPTURE)
 653		return false;
 654	/* disabled via module option? */
 655	if (!chip->lowlatency)
 656		return false;
 657	if (in_free_wheeling_mode(runtime))
 658		return false;
 659	/* implicit feedback mode has own operation mode */
 660	if (snd_usb_endpoint_implicit_feedback_sink(subs->data_endpoint))
 661		return false;
 662	return true;
 663}
 664
 665/*
 666 * prepare callback
 667 *
 668 * only a few subtle things...
 669 */
 670static int snd_usb_pcm_prepare(struct snd_pcm_substream *substream)
 671{
 672	struct snd_pcm_runtime *runtime = substream->runtime;
 673	struct snd_usb_substream *subs = runtime->private_data;
 674	struct snd_usb_audio *chip = subs->stream->chip;
 675	int retry = 0;
 676	int ret;
 677
 678	CLASS(snd_usb_lock, pm)(chip);
 679	if (pm.err < 0)
 680		return pm.err;
 681	if (snd_BUG_ON(!subs->data_endpoint))
 682		return -EIO;
 683
 684	ret = snd_usb_pcm_change_state(subs, UAC3_PD_STATE_D0);
 685	if (ret < 0)
 686		return ret;
 687
 688 again:
 689	if (subs->sync_endpoint) {
 690		ret = snd_usb_endpoint_prepare(chip, subs->sync_endpoint);
 691		if (ret < 0)
 692			return ret;
 693	}
 694
 695	ret = snd_usb_endpoint_prepare(chip, subs->data_endpoint);
 696	if (ret < 0)
 697		return ret;
 698	else if (ret > 0)
 699		snd_usb_set_format_quirk(subs, subs->cur_audiofmt);
 700	ret = 0;
 701
 702	/* reset the pointer */
 703	subs->buffer_bytes = frames_to_bytes(runtime, runtime->buffer_size);
 704	subs->inflight_bytes = 0;
 705	subs->hwptr_done = 0;
 706	subs->transfer_done = 0;
 707	subs->last_frame_number = 0;
 708	subs->period_elapsed_pending = 0;
 709	runtime->delay = 0;
 710
 711	subs->lowlatency_playback = lowlatency_playback_available(runtime, subs);
 712	if (substream->stream == SNDRV_PCM_STREAM_PLAYBACK &&
 713	    !subs->lowlatency_playback) {
 714		ret = start_endpoints(subs);
 715		/* if XRUN happens at starting streams (possibly with implicit
 716		 * fb case), restart again, but only try once.
 717		 */
 718		if (ret == -EPIPE && !retry++) {
 719			sync_pending_stops(subs);
 720			goto again;
 721		}
 722	}
 723
 724	return ret;
 725}
 726
 727/*
 728 * h/w constraints
 729 */
 730
 731#ifdef HW_CONST_DEBUG
 732#define hwc_debug(fmt, args...) pr_debug(fmt, ##args)
 733#else
 734#define hwc_debug(fmt, args...) do { } while(0)
 735#endif
 736
 737static const struct snd_pcm_hardware snd_usb_hardware =
 738{
 739	.info =			SNDRV_PCM_INFO_MMAP |
 740				SNDRV_PCM_INFO_MMAP_VALID |
 741				SNDRV_PCM_INFO_BATCH |
 742				SNDRV_PCM_INFO_INTERLEAVED |
 743				SNDRV_PCM_INFO_BLOCK_TRANSFER |
 744				SNDRV_PCM_INFO_PAUSE,
 745	.channels_min =		1,
 746	.channels_max =		256,
 747	.buffer_bytes_max =	INT_MAX, /* limited by BUFFER_TIME later */
 748	.period_bytes_min =	64,
 749	.period_bytes_max =	INT_MAX, /* limited by PERIOD_TIME later */
 750	.periods_min =		2,
 751	.periods_max =		1024,
 752};
 753
 754static int hw_check_valid_format(struct snd_usb_substream *subs,
 755				 struct snd_pcm_hw_params *params,
 756				 const struct audioformat *fp)
 757{
 758	struct snd_interval *it = hw_param_interval(params, SNDRV_PCM_HW_PARAM_RATE);
 759	struct snd_interval *ct = hw_param_interval(params, SNDRV_PCM_HW_PARAM_CHANNELS);
 760	struct snd_mask *fmts = hw_param_mask(params, SNDRV_PCM_HW_PARAM_FORMAT);
 761	struct snd_interval *pt = hw_param_interval(params, SNDRV_PCM_HW_PARAM_PERIOD_TIME);
 762	struct snd_mask check_fmts;
 763	unsigned int ptime;
 764
 765	/* check the format */
 766	snd_mask_none(&check_fmts);
 767	check_fmts.bits[0] = (u32)fp->formats;
 768	check_fmts.bits[1] = (u32)(fp->formats >> 32);
 769	snd_mask_intersect(&check_fmts, fmts);
 770	if (snd_mask_empty(&check_fmts)) {
 771		hwc_debug("   > check: no supported format 0x%llx\n", fp->formats);
 772		return 0;
 773	}
 774	/* check the channels */
 775	if (fp->channels < ct->min || fp->channels > ct->max) {
 776		hwc_debug("   > check: no valid channels %d (%d/%d)\n", fp->channels, ct->min, ct->max);
 777		return 0;
 778	}
 779	/* check the rate is within the range */
 780	if (fp->rate_min > it->max || (fp->rate_min == it->max && it->openmax)) {
 781		hwc_debug("   > check: rate_min %d > max %d\n", fp->rate_min, it->max);
 782		return 0;
 783	}
 784	if (fp->rate_max < it->min || (fp->rate_max == it->min && it->openmin)) {
 785		hwc_debug("   > check: rate_max %d < min %d\n", fp->rate_max, it->min);
 786		return 0;
 787	}
 788	/* check whether the period time is >= the data packet interval */
 789	if (subs->speed != USB_SPEED_FULL) {
 790		ptime = 125 * (1 << fp->datainterval);
 791		if (ptime > pt->max || (ptime == pt->max && pt->openmax)) {
 792			hwc_debug("   > check: ptime %u > max %u\n", ptime, pt->max);
 793			return 0;
 794		}
 795	}
 796	return 1;
 797}
 798
 799static int apply_hw_params_minmax(struct snd_interval *it, unsigned int rmin,
 800				  unsigned int rmax)
 801{
 802	int changed;
 803
 804	if (rmin > rmax) {
 805		hwc_debug("  --> get empty\n");
 806		it->empty = 1;
 807		return -EINVAL;
 808	}
 809
 810	changed = 0;
 811	if (it->min < rmin) {
 812		it->min = rmin;
 813		it->openmin = 0;
 814		changed = 1;
 815	}
 816	if (it->max > rmax) {
 817		it->max = rmax;
 818		it->openmax = 0;
 819		changed = 1;
 820	}
 821	if (snd_interval_checkempty(it)) {
 822		it->empty = 1;
 823		return -EINVAL;
 824	}
 825	hwc_debug("  --> (%d, %d) (changed = %d)\n", it->min, it->max, changed);
 826	return changed;
 827}
 828
 829/* get the specified endpoint object that is being used by other streams
 830 * (i.e. the parameter is locked)
 831 */
 832static const struct snd_usb_endpoint *
 833get_endpoint_in_use(struct snd_usb_audio *chip, int endpoint,
 834		    const struct snd_usb_endpoint *ref_ep)
 835{
 836	const struct snd_usb_endpoint *ep;
 837
 838	ep = snd_usb_get_endpoint(chip, endpoint);
 839	if (ep && ep->cur_audiofmt && (ep != ref_ep || ep->opened > 1))
 840		return ep;
 841	return NULL;
 842}
 843
 844static int hw_rule_rate(struct snd_pcm_hw_params *params,
 845			struct snd_pcm_hw_rule *rule)
 846{
 847	struct snd_usb_substream *subs = rule->private;
 848	struct snd_usb_audio *chip = subs->stream->chip;
 849	const struct snd_usb_endpoint *ep;
 850	const struct audioformat *fp;
 851	struct snd_interval *it = hw_param_interval(params, SNDRV_PCM_HW_PARAM_RATE);
 852	unsigned int rmin, rmax, r;
 853	int i;
 854
 855	hwc_debug("hw_rule_rate: (%d,%d)\n", it->min, it->max);
 856	rmin = UINT_MAX;
 857	rmax = 0;
 858	list_for_each_entry(fp, &subs->fmt_list, list) {
 859		if (!hw_check_valid_format(subs, params, fp))
 860			continue;
 861
 862		ep = get_endpoint_in_use(chip, fp->endpoint,
 863					 subs->data_endpoint);
 864		if (ep) {
 865			hwc_debug("rate limit %d for ep#%x\n",
 866				  ep->cur_rate, fp->endpoint);
 867			rmin = min(rmin, ep->cur_rate);
 868			rmax = max(rmax, ep->cur_rate);
 869			continue;
 870		}
 871
 872		if (fp->implicit_fb) {
 873			ep = get_endpoint_in_use(chip, fp->sync_ep,
 874						 subs->sync_endpoint);
 875			if (ep) {
 876				hwc_debug("rate limit %d for sync_ep#%x\n",
 877					  ep->cur_rate, fp->sync_ep);
 878				rmin = min(rmin, ep->cur_rate);
 879				rmax = max(rmax, ep->cur_rate);
 880				continue;
 881			}
 882		}
 883
 884		r = snd_usb_endpoint_get_clock_rate(chip, fp->clock);
 885		if (r > 0) {
 886			if (!snd_interval_test(it, r))
 887				continue;
 888			rmin = min(rmin, r);
 889			rmax = max(rmax, r);
 890			continue;
 891		}
 892		if (fp->rate_table && fp->nr_rates) {
 893			for (i = 0; i < fp->nr_rates; i++) {
 894				r = fp->rate_table[i];
 895				if (!snd_interval_test(it, r))
 896					continue;
 897				rmin = min(rmin, r);
 898				rmax = max(rmax, r);
 899			}
 900		} else {
 901			rmin = min(rmin, fp->rate_min);
 902			rmax = max(rmax, fp->rate_max);
 903		}
 904	}
 905
 906	return apply_hw_params_minmax(it, rmin, rmax);
 907}
 908
 909
 910static int hw_rule_channels(struct snd_pcm_hw_params *params,
 911			    struct snd_pcm_hw_rule *rule)
 912{
 913	struct snd_usb_substream *subs = rule->private;
 914	const struct audioformat *fp;
 915	struct snd_interval *it = hw_param_interval(params, SNDRV_PCM_HW_PARAM_CHANNELS);
 916	unsigned int rmin, rmax;
 917
 918	hwc_debug("hw_rule_channels: (%d,%d)\n", it->min, it->max);
 919	rmin = UINT_MAX;
 920	rmax = 0;
 921	list_for_each_entry(fp, &subs->fmt_list, list) {
 922		if (!hw_check_valid_format(subs, params, fp))
 923			continue;
 924		rmin = min(rmin, fp->channels);
 925		rmax = max(rmax, fp->channels);
 926	}
 927
 928	return apply_hw_params_minmax(it, rmin, rmax);
 929}
 930
 931static int apply_hw_params_format_bits(struct snd_mask *fmt, u64 fbits)
 932{
 933	u32 oldbits[2];
 934	int changed;
 935
 936	oldbits[0] = fmt->bits[0];
 937	oldbits[1] = fmt->bits[1];
 938	fmt->bits[0] &= (u32)fbits;
 939	fmt->bits[1] &= (u32)(fbits >> 32);
 940	if (!fmt->bits[0] && !fmt->bits[1]) {
 941		hwc_debug("  --> get empty\n");
 942		return -EINVAL;
 943	}
 944	changed = (oldbits[0] != fmt->bits[0] || oldbits[1] != fmt->bits[1]);
 945	hwc_debug("  --> %x:%x (changed = %d)\n", fmt->bits[0], fmt->bits[1], changed);
 946	return changed;
 947}
 948
 949static int hw_rule_format(struct snd_pcm_hw_params *params,
 950			  struct snd_pcm_hw_rule *rule)
 951{
 952	struct snd_usb_substream *subs = rule->private;
 953	struct snd_usb_audio *chip = subs->stream->chip;
 954	const struct snd_usb_endpoint *ep;
 955	const struct audioformat *fp;
 956	struct snd_mask *fmt = hw_param_mask(params, SNDRV_PCM_HW_PARAM_FORMAT);
 957	u64 fbits;
 958
 959	hwc_debug("hw_rule_format: %x:%x\n", fmt->bits[0], fmt->bits[1]);
 960	fbits = 0;
 961	list_for_each_entry(fp, &subs->fmt_list, list) {
 962		if (!hw_check_valid_format(subs, params, fp))
 963			continue;
 964
 965		ep = get_endpoint_in_use(chip, fp->endpoint,
 966					 subs->data_endpoint);
 967		if (ep) {
 968			hwc_debug("format limit %d for ep#%x\n",
 969				  ep->cur_format, fp->endpoint);
 970			fbits |= pcm_format_to_bits(ep->cur_format);
 971			continue;
 972		}
 973
 974		if (fp->implicit_fb) {
 975			ep = get_endpoint_in_use(chip, fp->sync_ep,
 976						 subs->sync_endpoint);
 977			if (ep) {
 978				hwc_debug("format limit %d for sync_ep#%x\n",
 979					  ep->cur_format, fp->sync_ep);
 980				fbits |= pcm_format_to_bits(ep->cur_format);
 981				continue;
 982			}
 983		}
 984
 985		fbits |= fp->formats;
 986	}
 987	return apply_hw_params_format_bits(fmt, fbits);
 988}
 989
 990static int hw_rule_period_time(struct snd_pcm_hw_params *params,
 991			       struct snd_pcm_hw_rule *rule)
 992{
 993	struct snd_usb_substream *subs = rule->private;
 994	const struct audioformat *fp;
 995	struct snd_interval *it;
 996	unsigned char min_datainterval;
 997	unsigned int pmin;
 998
 999	it = hw_param_interval(params, SNDRV_PCM_HW_PARAM_PERIOD_TIME);
1000	hwc_debug("hw_rule_period_time: (%u,%u)\n", it->min, it->max);
1001	min_datainterval = 0xff;
1002	list_for_each_entry(fp, &subs->fmt_list, list) {
1003		if (!hw_check_valid_format(subs, params, fp))
1004			continue;
1005		min_datainterval = min(min_datainterval, fp->datainterval);
1006	}
1007	if (min_datainterval == 0xff) {
1008		hwc_debug("  --> get empty\n");
1009		it->empty = 1;
1010		return -EINVAL;
1011	}
1012	pmin = 125 * (1 << min_datainterval);
1013
1014	return apply_hw_params_minmax(it, pmin, UINT_MAX);
1015}
1016
1017/* additional hw constraints for implicit feedback mode */
1018static int hw_rule_period_size_implicit_fb(struct snd_pcm_hw_params *params,
1019					   struct snd_pcm_hw_rule *rule)
1020{
1021	struct snd_usb_substream *subs = rule->private;
1022	struct snd_usb_audio *chip = subs->stream->chip;
1023	const struct audioformat *fp;
1024	const struct snd_usb_endpoint *ep;
1025	struct snd_interval *it;
1026	unsigned int rmin, rmax;
1027
1028	it = hw_param_interval(params, SNDRV_PCM_HW_PARAM_PERIOD_SIZE);
1029	hwc_debug("hw_rule_period_size: (%u,%u)\n", it->min, it->max);
1030	rmin = UINT_MAX;
1031	rmax = 0;
1032	list_for_each_entry(fp, &subs->fmt_list, list) {
1033		if (!hw_check_valid_format(subs, params, fp))
1034			continue;
1035		ep = get_endpoint_in_use(chip, fp->endpoint,
1036					 subs->data_endpoint);
1037		if (ep) {
1038			hwc_debug("period size limit %d for ep#%x\n",
1039				  ep->cur_period_frames, fp->endpoint);
1040			rmin = min(rmin, ep->cur_period_frames);
1041			rmax = max(rmax, ep->cur_period_frames);
1042			continue;
1043		}
1044
1045		if (fp->implicit_fb) {
1046			ep = get_endpoint_in_use(chip, fp->sync_ep,
1047						 subs->sync_endpoint);
1048			if (ep) {
1049				hwc_debug("period size limit %d for sync_ep#%x\n",
1050					  ep->cur_period_frames, fp->sync_ep);
1051				rmin = min(rmin, ep->cur_period_frames);
1052				rmax = max(rmax, ep->cur_period_frames);
1053				continue;
1054			}
1055		}
1056	}
1057
1058	if (!rmax)
1059		return 0; /* no limit by implicit fb */
1060	return apply_hw_params_minmax(it, rmin, rmax);
1061}
1062
1063static int hw_rule_periods_implicit_fb(struct snd_pcm_hw_params *params,
1064				       struct snd_pcm_hw_rule *rule)
1065{
1066	struct snd_usb_substream *subs = rule->private;
1067	struct snd_usb_audio *chip = subs->stream->chip;
1068	const struct audioformat *fp;
1069	const struct snd_usb_endpoint *ep;
1070	struct snd_interval *it;
1071	unsigned int rmin, rmax;
1072
1073	it = hw_param_interval(params, SNDRV_PCM_HW_PARAM_PERIODS);
1074	hwc_debug("hw_rule_periods: (%u,%u)\n", it->min, it->max);
1075	rmin = UINT_MAX;
1076	rmax = 0;
1077	list_for_each_entry(fp, &subs->fmt_list, list) {
1078		if (!hw_check_valid_format(subs, params, fp))
1079			continue;
1080		ep = get_endpoint_in_use(chip, fp->endpoint,
1081					 subs->data_endpoint);
1082		if (ep) {
1083			hwc_debug("periods limit %d for ep#%x\n",
1084				  ep->cur_buffer_periods, fp->endpoint);
1085			rmin = min(rmin, ep->cur_buffer_periods);
1086			rmax = max(rmax, ep->cur_buffer_periods);
1087			continue;
1088		}
1089
1090		if (fp->implicit_fb) {
1091			ep = get_endpoint_in_use(chip, fp->sync_ep,
1092						 subs->sync_endpoint);
1093			if (ep) {
1094				hwc_debug("periods limit %d for sync_ep#%x\n",
1095					  ep->cur_buffer_periods, fp->sync_ep);
1096				rmin = min(rmin, ep->cur_buffer_periods);
1097				rmax = max(rmax, ep->cur_buffer_periods);
1098				continue;
1099			}
1100		}
1101	}
1102
1103	if (!rmax)
1104		return 0; /* no limit by implicit fb */
1105	return apply_hw_params_minmax(it, rmin, rmax);
1106}
1107
1108/*
1109 * set up the runtime hardware information.
1110 */
1111
1112static int setup_hw_info(struct snd_pcm_runtime *runtime, struct snd_usb_substream *subs)
1113{
1114	const struct audioformat *fp;
1115	unsigned int pt, ptmin;
1116	int param_period_time_if_needed = -1;
1117	int err;
1118
1119	runtime->hw.formats = subs->formats;
1120
1121	runtime->hw.rate_min = 0x7fffffff;
1122	runtime->hw.rate_max = 0;
1123	runtime->hw.channels_min = 256;
1124	runtime->hw.channels_max = 0;
1125	runtime->hw.rates = 0;
1126	ptmin = UINT_MAX;
1127	/* check min/max rates and channels */
1128	list_for_each_entry(fp, &subs->fmt_list, list) {
1129		runtime->hw.rates |= fp->rates;
1130		if (runtime->hw.rate_min > fp->rate_min)
1131			runtime->hw.rate_min = fp->rate_min;
1132		if (runtime->hw.rate_max < fp->rate_max)
1133			runtime->hw.rate_max = fp->rate_max;
1134		if (runtime->hw.channels_min > fp->channels)
1135			runtime->hw.channels_min = fp->channels;
1136		if (runtime->hw.channels_max < fp->channels)
1137			runtime->hw.channels_max = fp->channels;
1138		if (fp->fmt_type == UAC_FORMAT_TYPE_II && fp->frame_size > 0) {
1139			/* FIXME: there might be more than one audio formats... */
1140			runtime->hw.period_bytes_min = runtime->hw.period_bytes_max =
1141				fp->frame_size;
1142		}
1143		pt = 125 * (1 << fp->datainterval);
1144		ptmin = min(ptmin, pt);
1145	}
1146
1147	param_period_time_if_needed = SNDRV_PCM_HW_PARAM_PERIOD_TIME;
1148	if (subs->speed == USB_SPEED_FULL)
1149		/* full speed devices have fixed data packet interval */
1150		ptmin = 1000;
1151	if (ptmin == 1000)
1152		/* if period time doesn't go below 1 ms, no rules needed */
1153		param_period_time_if_needed = -1;
1154
1155	err = snd_pcm_hw_constraint_minmax(runtime,
1156					   SNDRV_PCM_HW_PARAM_PERIOD_TIME,
1157					   ptmin, UINT_MAX);
1158	if (err < 0)
1159		return err;
1160
1161	err = snd_pcm_hw_rule_add(runtime, 0, SNDRV_PCM_HW_PARAM_RATE,
1162				  hw_rule_rate, subs,
1163				  SNDRV_PCM_HW_PARAM_RATE,
1164				  SNDRV_PCM_HW_PARAM_FORMAT,
1165				  SNDRV_PCM_HW_PARAM_CHANNELS,
1166				  param_period_time_if_needed,
1167				  -1);
1168	if (err < 0)
1169		return err;
1170
1171	err = snd_pcm_hw_rule_add(runtime, 0, SNDRV_PCM_HW_PARAM_CHANNELS,
1172				  hw_rule_channels, subs,
1173				  SNDRV_PCM_HW_PARAM_CHANNELS,
1174				  SNDRV_PCM_HW_PARAM_FORMAT,
1175				  SNDRV_PCM_HW_PARAM_RATE,
1176				  param_period_time_if_needed,
1177				  -1);
1178	if (err < 0)
1179		return err;
1180	err = snd_pcm_hw_rule_add(runtime, 0, SNDRV_PCM_HW_PARAM_FORMAT,
1181				  hw_rule_format, subs,
1182				  SNDRV_PCM_HW_PARAM_FORMAT,
1183				  SNDRV_PCM_HW_PARAM_RATE,
1184				  SNDRV_PCM_HW_PARAM_CHANNELS,
1185				  param_period_time_if_needed,
1186				  -1);
1187	if (err < 0)
1188		return err;
1189	if (param_period_time_if_needed >= 0) {
1190		err = snd_pcm_hw_rule_add(runtime, 0,
1191					  SNDRV_PCM_HW_PARAM_PERIOD_TIME,
1192					  hw_rule_period_time, subs,
1193					  SNDRV_PCM_HW_PARAM_FORMAT,
1194					  SNDRV_PCM_HW_PARAM_CHANNELS,
1195					  SNDRV_PCM_HW_PARAM_RATE,
1196					  -1);
1197		if (err < 0)
1198			return err;
1199	}
1200
1201	/* set max period and buffer sizes for 1 and 2 seconds, respectively */
1202	err = snd_pcm_hw_constraint_minmax(runtime,
1203					   SNDRV_PCM_HW_PARAM_PERIOD_TIME,
1204					   0, 1000000);
1205	if (err < 0)
1206		return err;
1207	err = snd_pcm_hw_constraint_minmax(runtime,
1208					   SNDRV_PCM_HW_PARAM_BUFFER_TIME,
1209					   0, 2000000);
1210	if (err < 0)
1211		return err;
1212
1213	/* additional hw constraints for implicit fb */
1214	err = snd_pcm_hw_rule_add(runtime, 0, SNDRV_PCM_HW_PARAM_PERIOD_SIZE,
1215				  hw_rule_period_size_implicit_fb, subs,
1216				  SNDRV_PCM_HW_PARAM_PERIOD_SIZE, -1);
1217	if (err < 0)
1218		return err;
1219	err = snd_pcm_hw_rule_add(runtime, 0, SNDRV_PCM_HW_PARAM_PERIODS,
1220				  hw_rule_periods_implicit_fb, subs,
1221				  SNDRV_PCM_HW_PARAM_PERIODS, -1);
1222	if (err < 0)
1223		return err;
1224
1225	list_for_each_entry(fp, &subs->fmt_list, list) {
1226		if (fp->implicit_fb) {
1227			runtime->hw.info |= SNDRV_PCM_INFO_JOINT_DUPLEX;
1228			break;
1229		}
1230	}
1231
1232	return 0;
1233}
1234
1235static int snd_usb_pcm_open(struct snd_pcm_substream *substream)
1236{
1237	int direction = substream->stream;
1238	struct snd_usb_stream *as = snd_pcm_substream_chip(substream);
1239	struct snd_pcm_runtime *runtime = substream->runtime;
1240	struct snd_usb_substream *subs = &as->substream[direction];
1241	struct snd_usb_audio *chip = subs->stream->chip;
1242	int ret;
1243
1244	scoped_guard(mutex, &chip->mutex) {
1245		if (subs->opened)
1246			return -EBUSY;
1247		subs->opened = 1;
1248	}
1249
1250	runtime->hw = snd_usb_hardware;
1251	/* need an explicit sync to catch applptr update in low-latency mode */
1252	if (direction == SNDRV_PCM_STREAM_PLAYBACK &&
1253	    as->chip->lowlatency)
1254		runtime->hw.info |= SNDRV_PCM_INFO_SYNC_APPLPTR;
1255	runtime->private_data = subs;
1256	subs->pcm_substream = substream;
1257	/* runtime PM is also done there */
1258
1259	/* initialize DSD/DOP context */
1260	subs->dsd_dop.byte_idx = 0;
1261	subs->dsd_dop.channel = 0;
1262	subs->dsd_dop.marker = 1;
1263
1264	ret = setup_hw_info(runtime, subs);
1265	if (ret < 0)
1266		goto err_open;
1267	ret = snd_usb_autoresume(subs->stream->chip);
1268	if (ret < 0)
1269		goto err_open;
1270	ret = snd_media_stream_init(subs, as->pcm, direction);
1271	if (ret < 0)
1272		goto err_resume;
1273
1274	return 0;
1275
1276err_resume:
1277	snd_usb_autosuspend(subs->stream->chip);
1278err_open:
1279	scoped_guard(mutex, &chip->mutex) {
1280		subs->opened = 0;
1281	}
1282
1283	return ret;
1284}
1285
1286static int snd_usb_pcm_close(struct snd_pcm_substream *substream)
1287{
1288	int direction = substream->stream;
1289	struct snd_usb_stream *as = snd_pcm_substream_chip(substream);
1290	struct snd_usb_substream *subs = &as->substream[direction];
1291	struct snd_usb_audio *chip = subs->stream->chip;
1292	int ret;
1293
1294	snd_media_stop_pipeline(subs);
1295
1296	{
1297		CLASS(snd_usb_lock, pm)(subs->stream->chip);
1298		if (pm.err)
1299			return pm.err;
1300		ret = snd_usb_pcm_change_state(subs, UAC3_PD_STATE_D1);
1301		if (ret < 0)
1302			return ret;
1303	}
1304
1305	subs->pcm_substream = NULL;
1306	snd_usb_autosuspend(subs->stream->chip);
1307	scoped_guard(mutex, &chip->mutex) {
1308		subs->opened = 0;
1309	}
1310
1311	return 0;
1312}
1313
1314/* Since a URB can handle only a single linear buffer, we must use double
1315 * buffering when the data to be transferred overflows the buffer boundary.
1316 * To avoid inconsistencies when updating hwptr_done, we use double buffering
1317 * for all URBs.
1318 */
1319static void retire_capture_urb(struct snd_usb_substream *subs,
1320			       struct urb *urb)
1321{
1322	struct snd_pcm_runtime *runtime = subs->pcm_substream->runtime;
1323	unsigned int stride, frames, bytes, oldptr;
1324	int i, period_elapsed = 0;
1325	unsigned char *cp;
1326	int current_frame_number;
1327
1328	/* read frame number here, update pointer in critical section */
1329	current_frame_number = usb_get_current_frame_number(subs->dev);
1330
1331	stride = runtime->frame_bits >> 3;
1332
1333	for (i = 0; i < urb->number_of_packets; i++) {
1334		cp = (unsigned char *)urb->transfer_buffer + urb->iso_frame_desc[i].offset + subs->pkt_offset_adj;
1335		if (urb->iso_frame_desc[i].status)
1336			dev_dbg_ratelimited(&subs->dev->dev,
1337					    "frame %d active: %d\n", i,
1338					    urb->iso_frame_desc[i].status);
1339		bytes = urb->iso_frame_desc[i].actual_length;
1340		if (subs->stream_offset_adj > 0) {
1341			unsigned int adj = min(subs->stream_offset_adj, bytes);
1342			cp += adj;
1343			bytes -= adj;
1344			subs->stream_offset_adj -= adj;
1345		}
1346		frames = bytes / stride;
1347		if (!subs->txfr_quirk)
1348			bytes = frames * stride;
1349		if (bytes % (runtime->sample_bits >> 3) != 0) {
1350			int oldbytes = bytes;
1351			bytes = frames * stride;
1352			dev_warn_ratelimited(&subs->dev->dev,
1353				 "Corrected urb data len. %d->%d\n",
1354							oldbytes, bytes);
1355		}
1356		/* update the current pointer */
1357		scoped_guard(spinlock_irqsave, &subs->lock) {
1358			oldptr = subs->hwptr_done;
1359			subs->hwptr_done += bytes;
1360			if (subs->hwptr_done >= subs->buffer_bytes)
1361				subs->hwptr_done -= subs->buffer_bytes;
1362			frames = (bytes + (oldptr % stride)) / stride;
1363			subs->transfer_done += frames;
1364			if (subs->transfer_done >= runtime->period_size) {
1365				subs->transfer_done -= runtime->period_size;
1366				period_elapsed = 1;
1367			}
1368
1369			/* realign last_frame_number */
1370			subs->last_frame_number = current_frame_number;
1371		}
1372		/* copy a data chunk */
1373		if (oldptr + bytes > subs->buffer_bytes) {
1374			unsigned int bytes1 = subs->buffer_bytes - oldptr;
1375
1376			memcpy(runtime->dma_area + oldptr, cp, bytes1);
1377			memcpy(runtime->dma_area, cp + bytes1, bytes - bytes1);
1378		} else {
1379			memcpy(runtime->dma_area + oldptr, cp, bytes);
1380		}
1381	}
1382
1383	if (period_elapsed)
1384		snd_pcm_period_elapsed(subs->pcm_substream);
1385}
1386
1387static void urb_ctx_queue_advance(struct snd_usb_substream *subs,
1388				  struct urb *urb, unsigned int bytes)
1389{
1390	struct snd_urb_ctx *ctx = urb->context;
1391
1392	ctx->queued += bytes;
1393	subs->inflight_bytes += bytes;
1394	subs->hwptr_done += bytes;
1395	if (subs->hwptr_done >= subs->buffer_bytes)
1396		subs->hwptr_done -= subs->buffer_bytes;
1397}
1398
1399static inline void fill_playback_urb_dsd_dop(struct snd_usb_substream *subs,
1400					     struct urb *urb, unsigned int bytes)
1401{
1402	struct snd_pcm_runtime *runtime = subs->pcm_substream->runtime;
1403	unsigned int dst_idx = 0;
1404	unsigned int src_idx = subs->hwptr_done;
1405	unsigned int wrap = subs->buffer_bytes;
1406	u8 *dst = urb->transfer_buffer;
1407	u8 *src = runtime->dma_area;
1408	static const u8 marker[] = { 0x05, 0xfa };
1409	unsigned int queued = 0;
1410
1411	/*
1412	 * The DSP DOP format defines a way to transport DSD samples over
1413	 * normal PCM data endpoints. It requires stuffing of marker bytes
1414	 * (0x05 and 0xfa, alternating per sample frame), and then expects
1415	 * 2 additional bytes of actual payload. The whole frame is stored
1416	 * LSB.
1417	 *
1418	 * Hence, for a stereo transport, the buffer layout looks like this,
1419	 * where L refers to left channel samples and R to right.
1420	 *
1421	 *   L1 L2 0x05   R1 R2 0x05   L3 L4 0xfa  R3 R4 0xfa
1422	 *   L5 L6 0x05   R5 R6 0x05   L7 L8 0xfa  R7 R8 0xfa
1423	 *   .....
1424	 *
1425	 */
1426
1427	while (bytes--) {
1428		if (++subs->dsd_dop.byte_idx == 3) {
1429			/* frame boundary? */
1430			dst[dst_idx++] = marker[subs->dsd_dop.marker];
1431			src_idx += 2;
1432			subs->dsd_dop.byte_idx = 0;
1433
1434			if (++subs->dsd_dop.channel % runtime->channels == 0) {
1435				/* alternate the marker */
1436				subs->dsd_dop.marker++;
1437				subs->dsd_dop.marker %= ARRAY_SIZE(marker);
1438				subs->dsd_dop.channel = 0;
1439			}
1440		} else {
1441			/* stuff the DSD payload */
1442			int idx = (src_idx + subs->dsd_dop.byte_idx - 1) % wrap;
1443
1444			if (subs->cur_audiofmt->dsd_bitrev)
1445				dst[dst_idx++] = bitrev8(src[idx]);
1446			else
1447				dst[dst_idx++] = src[idx];
1448			queued++;
1449		}
1450	}
1451
1452	urb_ctx_queue_advance(subs, urb, queued);
1453}
1454
1455/* copy bit-reversed bytes onto transfer buffer */
1456static void fill_playback_urb_dsd_bitrev(struct snd_usb_substream *subs,
1457					 struct urb *urb, unsigned int bytes)
1458{
1459	struct snd_pcm_runtime *runtime = subs->pcm_substream->runtime;
1460	const u8 *src = runtime->dma_area;
1461	u8 *buf = urb->transfer_buffer;
1462	int i, ofs = subs->hwptr_done;
1463
1464	for (i = 0; i < bytes; i++) {
1465		*buf++ = bitrev8(src[ofs]);
1466		if (++ofs >= subs->buffer_bytes)
1467			ofs = 0;
1468	}
1469
1470	urb_ctx_queue_advance(subs, urb, bytes);
1471}
1472
1473static void copy_to_urb(struct snd_usb_substream *subs, struct urb *urb,
1474			int offset, int stride, unsigned int bytes)
1475{
1476	struct snd_pcm_runtime *runtime = subs->pcm_substream->runtime;
1477
1478	if (subs->hwptr_done + bytes > subs->buffer_bytes) {
1479		/* err, the transferred area goes over buffer boundary. */
1480		unsigned int bytes1 = subs->buffer_bytes - subs->hwptr_done;
1481
1482		memcpy(urb->transfer_buffer + offset,
1483		       runtime->dma_area + subs->hwptr_done, bytes1);
1484		memcpy(urb->transfer_buffer + offset + bytes1,
1485		       runtime->dma_area, bytes - bytes1);
1486	} else {
1487		memcpy(urb->transfer_buffer + offset,
1488		       runtime->dma_area + subs->hwptr_done, bytes);
1489	}
1490
1491	urb_ctx_queue_advance(subs, urb, bytes);
1492}
1493
1494static unsigned int copy_to_urb_quirk(struct snd_usb_substream *subs,
1495				      struct urb *urb, int stride,
1496				      unsigned int bytes)
1497{
1498	__le32 packet_length;
1499	int i;
1500
1501	/* Put __le32 length descriptor at start of each packet. */
1502	for (i = 0; i < urb->number_of_packets; i++) {
1503		unsigned int length = urb->iso_frame_desc[i].length;
1504		unsigned int offset = urb->iso_frame_desc[i].offset;
1505
1506		packet_length = cpu_to_le32(length);
1507		offset += i * sizeof(packet_length);
1508		urb->iso_frame_desc[i].offset = offset;
1509		urb->iso_frame_desc[i].length += sizeof(packet_length);
1510		memcpy(urb->transfer_buffer + offset,
1511		       &packet_length, sizeof(packet_length));
1512		copy_to_urb(subs, urb, offset + sizeof(packet_length),
1513			    stride, length);
1514	}
1515	/* Adjust transfer size accordingly. */
1516	bytes += urb->number_of_packets * sizeof(packet_length);
1517	return bytes;
1518}
1519
1520static int prepare_playback_urb(struct snd_usb_substream *subs,
1521				struct urb *urb,
1522				bool in_stream_lock)
1523{
1524	struct snd_pcm_runtime *runtime = subs->pcm_substream->runtime;
1525	struct snd_usb_endpoint *ep = subs->data_endpoint;
1526	struct snd_urb_ctx *ctx = urb->context;
1527	unsigned int frames, bytes;
1528	int counts;
1529	unsigned int transfer_done, frame_limit, avail = 0;
1530	int i, stride, period_elapsed = 0;
1531
1532	stride = ep->stride;
1533
1534	frames = 0;
1535	ctx->queued = 0;
1536	urb->number_of_packets = 0;
1537
1538	scoped_guard(spinlock_irqsave, &subs->lock) {
1539		frame_limit = subs->frame_limit + ep->max_urb_frames;
1540		transfer_done = subs->transfer_done;
1541
1542		if (subs->lowlatency_playback &&
1543		    runtime->state != SNDRV_PCM_STATE_DRAINING) {
1544			unsigned int hwptr = subs->hwptr_done / stride;
1545
1546			/* calculate the byte offset-in-buffer of the appl_ptr */
1547			avail = (runtime->control->appl_ptr - runtime->hw_ptr_base)
1548				% runtime->buffer_size;
1549			if (avail <= hwptr)
1550				avail += runtime->buffer_size;
1551			avail -= hwptr;
1552		}
1553
1554		for (i = 0; i < ctx->packets; i++) {
1555			counts = snd_usb_endpoint_next_packet_size(ep, ctx, i, avail);
1556			if (counts < 0 ||
1557			    (frames + counts) * stride > ctx->buffer_size)
1558				break;
1559			/* set up descriptor */
1560			urb->iso_frame_desc[i].offset = frames * stride;
1561			urb->iso_frame_desc[i].length = counts * stride;
1562			frames += counts;
1563			avail -= counts;
1564			urb->number_of_packets++;
1565			transfer_done += counts;
1566			if (transfer_done >= runtime->period_size) {
1567				transfer_done -= runtime->period_size;
1568				frame_limit = 0;
1569				period_elapsed = 1;
1570				if (subs->fmt_type == UAC_FORMAT_TYPE_II) {
1571					if (transfer_done > 0) {
1572						/* FIXME: fill-max mode is not
1573						 * supported yet */
1574						frames -= transfer_done;
1575						counts -= transfer_done;
1576						urb->iso_frame_desc[i].length =
1577							counts * stride;
1578						transfer_done = 0;
1579					}
1580					i++;
1581					if (i < ctx->packets) {
1582						/* add a transfer delimiter */
1583						urb->iso_frame_desc[i].offset =
1584							frames * stride;
1585						urb->iso_frame_desc[i].length = 0;
1586						urb->number_of_packets++;
1587					}
1588					break;
1589				}
1590			}
1591			/* finish at the period boundary or after enough frames */
1592			if ((period_elapsed || transfer_done >= frame_limit) &&
1593			    !snd_usb_endpoint_implicit_feedback_sink(ep))
1594				break;
1595		}
1596
1597		if (!frames)
1598			return -EAGAIN;
1599
1600		bytes = frames * stride;
1601		subs->transfer_done = transfer_done;
1602		subs->frame_limit = frame_limit;
1603		if (unlikely(ep->cur_format == SNDRV_PCM_FORMAT_DSD_U16_LE &&
1604			     subs->cur_audiofmt->dsd_dop)) {
1605			fill_playback_urb_dsd_dop(subs, urb, bytes);
1606		} else if (unlikely(ep->cur_format == SNDRV_PCM_FORMAT_DSD_U8 &&
1607				    subs->cur_audiofmt->dsd_bitrev)) {
1608			fill_playback_urb_dsd_bitrev(subs, urb, bytes);
1609		} else {
1610			/* usual PCM */
1611			if (!subs->tx_length_quirk)
1612				copy_to_urb(subs, urb, 0, stride, bytes);
1613			else
1614				bytes = copy_to_urb_quirk(subs, urb, stride, bytes);
1615			/* bytes is now amount of outgoing data */
1616		}
1617
1618		subs->last_frame_number = usb_get_current_frame_number(subs->dev);
1619
1620		if (subs->trigger_tstamp_pending_update) {
1621			/* this is the first actual URB submitted,
1622			 * update trigger timestamp to reflect actual start time
1623			 */
1624			snd_pcm_gettime(runtime, &runtime->trigger_tstamp);
1625			subs->trigger_tstamp_pending_update = false;
1626		}
1627
1628		if (period_elapsed && !subs->running && subs->lowlatency_playback) {
1629			subs->period_elapsed_pending = 1;
1630			period_elapsed = 0;
1631		}
1632	}
1633
1634	urb->transfer_buffer_length = bytes;
1635	if (period_elapsed) {
1636		if (in_stream_lock)
1637			snd_pcm_period_elapsed_under_stream_lock(subs->pcm_substream);
1638		else
1639			snd_pcm_period_elapsed(subs->pcm_substream);
1640	}
1641	return 0;
1642}
1643
1644/*
1645 * process after playback data complete
1646 * - decrease the delay count again
1647 */
1648static void retire_playback_urb(struct snd_usb_substream *subs,
1649			       struct urb *urb)
1650{
1651	struct snd_urb_ctx *ctx = urb->context;
1652	bool period_elapsed = false;
1653
1654	scoped_guard(spinlock_irqsave, &subs->lock) {
1655		if (ctx->queued) {
1656			if (subs->inflight_bytes >= ctx->queued)
1657				subs->inflight_bytes -= ctx->queued;
1658			else
1659				subs->inflight_bytes = 0;
1660		}
1661
1662		subs->last_frame_number = usb_get_current_frame_number(subs->dev);
1663		if (subs->running) {
1664			period_elapsed = subs->period_elapsed_pending;
1665			subs->period_elapsed_pending = 0;
1666		}
1667	}
1668	if (period_elapsed)
1669		snd_pcm_period_elapsed(subs->pcm_substream);
1670}
1671
1672/* PCM ack callback for the playback stream;
1673 * this plays a role only when the stream is running in low-latency mode.
1674 */
1675static int snd_usb_pcm_playback_ack(struct snd_pcm_substream *substream)
1676{
1677	struct snd_usb_substream *subs = substream->runtime->private_data;
1678	struct snd_usb_endpoint *ep;
1679
1680	if (!subs->lowlatency_playback || !subs->running)
1681		return 0;
1682	ep = subs->data_endpoint;
1683	if (!ep)
1684		return 0;
1685	/* When no more in-flight URBs available, try to process the pending
1686	 * outputs here
1687	 */
1688	if (!ep->active_mask)
1689		return snd_usb_queue_pending_output_urbs(ep, true);
1690	return 0;
1691}
1692
1693static int snd_usb_substream_playback_trigger(struct snd_pcm_substream *substream,
1694					      int cmd)
1695{
1696	struct snd_usb_substream *subs = substream->runtime->private_data;
1697	int err;
1698
1699	switch (cmd) {
1700	case SNDRV_PCM_TRIGGER_START:
1701		subs->trigger_tstamp_pending_update = true;
1702		fallthrough;
1703	case SNDRV_PCM_TRIGGER_PAUSE_RELEASE:
1704		snd_usb_endpoint_set_callback(subs->data_endpoint,
1705					      prepare_playback_urb,
1706					      retire_playback_urb,
1707					      subs);
1708		if (subs->lowlatency_playback &&
1709		    cmd == SNDRV_PCM_TRIGGER_START) {
1710			if (in_free_wheeling_mode(substream->runtime))
1711				subs->lowlatency_playback = false;
1712			err = start_endpoints(subs);
1713			if (err < 0) {
1714				snd_usb_endpoint_set_callback(subs->data_endpoint,
1715							      NULL, NULL, NULL);
1716				return err;
1717			}
1718		}
1719		subs->running = 1;
1720		dev_dbg(&subs->dev->dev, "%d:%d Start Playback PCM\n",
1721			subs->cur_audiofmt->iface,
1722			subs->cur_audiofmt->altsetting);
1723		return 0;
1724	case SNDRV_PCM_TRIGGER_SUSPEND:
1725	case SNDRV_PCM_TRIGGER_STOP:
1726		stop_endpoints(subs, substream->runtime->state == SNDRV_PCM_STATE_DRAINING);
1727		snd_usb_endpoint_set_callback(subs->data_endpoint,
1728					      NULL, NULL, NULL);
1729		subs->running = 0;
1730		dev_dbg(&subs->dev->dev, "%d:%d Stop Playback PCM\n",
1731			subs->cur_audiofmt->iface,
1732			subs->cur_audiofmt->altsetting);
1733		return 0;
1734	case SNDRV_PCM_TRIGGER_PAUSE_PUSH:
1735		/* keep retire_data_urb for delay calculation */
1736		snd_usb_endpoint_set_callback(subs->data_endpoint,
1737					      NULL,
1738					      retire_playback_urb,
1739					      subs);
1740		subs->running = 0;
1741		dev_dbg(&subs->dev->dev, "%d:%d Pause Playback PCM\n",
1742			subs->cur_audiofmt->iface,
1743			subs->cur_audiofmt->altsetting);
1744		return 0;
1745	}
1746
1747	return -EINVAL;
1748}
1749
1750static int snd_usb_substream_capture_trigger(struct snd_pcm_substream *substream,
1751					     int cmd)
1752{
1753	int err;
1754	struct snd_usb_substream *subs = substream->runtime->private_data;
1755
1756	switch (cmd) {
1757	case SNDRV_PCM_TRIGGER_START:
1758		err = start_endpoints(subs);
1759		if (err < 0)
1760			return err;
1761		fallthrough;
1762	case SNDRV_PCM_TRIGGER_PAUSE_RELEASE:
1763		snd_usb_endpoint_set_callback(subs->data_endpoint,
1764					      NULL, retire_capture_urb,
1765					      subs);
1766		subs->last_frame_number = usb_get_current_frame_number(subs->dev);
1767		subs->running = 1;
1768		dev_dbg(&subs->dev->dev, "%d:%d Start Capture PCM\n",
1769			subs->cur_audiofmt->iface,
1770			subs->cur_audiofmt->altsetting);
1771		return 0;
1772	case SNDRV_PCM_TRIGGER_SUSPEND:
1773	case SNDRV_PCM_TRIGGER_STOP:
1774		stop_endpoints(subs, false);
1775		fallthrough;
1776	case SNDRV_PCM_TRIGGER_PAUSE_PUSH:
1777		snd_usb_endpoint_set_callback(subs->data_endpoint,
1778					      NULL, NULL, NULL);
1779		subs->running = 0;
1780		dev_dbg(&subs->dev->dev, "%d:%d Stop Capture PCM\n",
1781			subs->cur_audiofmt->iface,
1782			subs->cur_audiofmt->altsetting);
1783		return 0;
1784	}
1785
1786	return -EINVAL;
1787}
1788
1789static const struct snd_pcm_ops snd_usb_playback_ops = {
1790	.open =		snd_usb_pcm_open,
1791	.close =	snd_usb_pcm_close,
1792	.hw_params =	snd_usb_pcm_hw_params,
1793	.hw_free =	snd_usb_pcm_hw_free,
1794	.prepare =	snd_usb_pcm_prepare,
1795	.trigger =	snd_usb_substream_playback_trigger,
1796	.sync_stop =	snd_usb_pcm_sync_stop,
1797	.pointer =	snd_usb_pcm_pointer,
1798	.ack =		snd_usb_pcm_playback_ack,
1799};
1800
1801static const struct snd_pcm_ops snd_usb_capture_ops = {
1802	.open =		snd_usb_pcm_open,
1803	.close =	snd_usb_pcm_close,
1804	.hw_params =	snd_usb_pcm_hw_params,
1805	.hw_free =	snd_usb_pcm_hw_free,
1806	.prepare =	snd_usb_pcm_prepare,
1807	.trigger =	snd_usb_substream_capture_trigger,
1808	.sync_stop =	snd_usb_pcm_sync_stop,
1809	.pointer =	snd_usb_pcm_pointer,
1810};
1811
1812void snd_usb_set_pcm_ops(struct snd_pcm *pcm, int stream)
1813{
1814	const struct snd_pcm_ops *ops;
1815
1816	ops = stream == SNDRV_PCM_STREAM_PLAYBACK ?
1817			&snd_usb_playback_ops : &snd_usb_capture_ops;
1818	snd_pcm_set_ops(pcm, stream, ops);
1819}
1820
1821void snd_usb_preallocate_buffer(struct snd_usb_substream *subs)
1822{
1823	struct snd_pcm *pcm = subs->stream->pcm;
1824	struct snd_pcm_substream *s = pcm->streams[subs->direction].substream;
1825	struct device *dev = subs->dev->bus->sysdev;
1826
1827	if (snd_usb_use_vmalloc)
1828		snd_pcm_set_managed_buffer(s, SNDRV_DMA_TYPE_VMALLOC,
1829					   NULL, 0, 0);
1830	else
1831		snd_pcm_set_managed_buffer(s, SNDRV_DMA_TYPE_DEV_SG,
1832					   dev, 64*1024, 512*1024);
1833}
~/ Read-only file preview.