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