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