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