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