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