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