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