linux/drivers/media/usb/uvc/uvc_video.c
<<
>>
Prefs
   1/*
   2 *      uvc_video.c  --  USB Video Class driver - Video handling
   3 *
   4 *      Copyright (C) 2005-2010
   5 *          Laurent Pinchart (laurent.pinchart@ideasonboard.com)
   6 *
   7 *      This program is free software; you can redistribute it and/or modify
   8 *      it under the terms of the GNU General Public License as published by
   9 *      the Free Software Foundation; either version 2 of the License, or
  10 *      (at your option) any later version.
  11 *
  12 */
  13
  14#include <linux/kernel.h>
  15#include <linux/list.h>
  16#include <linux/module.h>
  17#include <linux/slab.h>
  18#include <linux/usb.h>
  19#include <linux/videodev2.h>
  20#include <linux/vmalloc.h>
  21#include <linux/wait.h>
  22#include <linux/atomic.h>
  23#include <asm/unaligned.h>
  24
  25#include <media/v4l2-common.h>
  26
  27#include "uvcvideo.h"
  28
  29/* ------------------------------------------------------------------------
  30 * UVC Controls
  31 */
  32
  33static int __uvc_query_ctrl(struct uvc_device *dev, u8 query, u8 unit,
  34                        u8 intfnum, u8 cs, void *data, u16 size,
  35                        int timeout)
  36{
  37        u8 type = USB_TYPE_CLASS | USB_RECIP_INTERFACE;
  38        unsigned int pipe;
  39
  40        pipe = (query & 0x80) ? usb_rcvctrlpipe(dev->udev, 0)
  41                              : usb_sndctrlpipe(dev->udev, 0);
  42        type |= (query & 0x80) ? USB_DIR_IN : USB_DIR_OUT;
  43
  44        return usb_control_msg(dev->udev, pipe, query, type, cs << 8,
  45                        unit << 8 | intfnum, data, size, timeout);
  46}
  47
  48static const char *uvc_query_name(u8 query)
  49{
  50        switch (query) {
  51        case UVC_SET_CUR:
  52                return "SET_CUR";
  53        case UVC_GET_CUR:
  54                return "GET_CUR";
  55        case UVC_GET_MIN:
  56                return "GET_MIN";
  57        case UVC_GET_MAX:
  58                return "GET_MAX";
  59        case UVC_GET_RES:
  60                return "GET_RES";
  61        case UVC_GET_LEN:
  62                return "GET_LEN";
  63        case UVC_GET_INFO:
  64                return "GET_INFO";
  65        case UVC_GET_DEF:
  66                return "GET_DEF";
  67        default:
  68                return "<invalid>";
  69        }
  70}
  71
  72int uvc_query_ctrl(struct uvc_device *dev, u8 query, u8 unit,
  73                        u8 intfnum, u8 cs, void *data, u16 size)
  74{
  75        int ret;
  76        u8 error;
  77        u8 tmp;
  78
  79        ret = __uvc_query_ctrl(dev, query, unit, intfnum, cs, data, size,
  80                                UVC_CTRL_CONTROL_TIMEOUT);
  81        if (likely(ret == size))
  82                return 0;
  83
  84        uvc_printk(KERN_ERR,
  85                   "Failed to query (%s) UVC control %u on unit %u: %d (exp. %u).\n",
  86                   uvc_query_name(query), cs, unit, ret, size);
  87
  88        if (ret != -EPIPE)
  89                return ret;
  90
  91        tmp = *(u8 *)data;
  92
  93        ret = __uvc_query_ctrl(dev, UVC_GET_CUR, 0, intfnum,
  94                               UVC_VC_REQUEST_ERROR_CODE_CONTROL, data, 1,
  95                               UVC_CTRL_CONTROL_TIMEOUT);
  96
  97        error = *(u8 *)data;
  98        *(u8 *)data = tmp;
  99
 100        if (ret != 1)
 101                return ret < 0 ? ret : -EPIPE;
 102
 103        uvc_trace(UVC_TRACE_CONTROL, "Control error %u\n", error);
 104
 105        switch (error) {
 106        case 0:
 107                /* Cannot happen - we received a STALL */
 108                return -EPIPE;
 109        case 1: /* Not ready */
 110                return -EBUSY;
 111        case 2: /* Wrong state */
 112                return -EILSEQ;
 113        case 3: /* Power */
 114                return -EREMOTE;
 115        case 4: /* Out of range */
 116                return -ERANGE;
 117        case 5: /* Invalid unit */
 118        case 6: /* Invalid control */
 119        case 7: /* Invalid Request */
 120        case 8: /* Invalid value within range */
 121                return -EINVAL;
 122        default: /* reserved or unknown */
 123                break;
 124        }
 125
 126        return -EPIPE;
 127}
 128
 129static void uvc_fixup_video_ctrl(struct uvc_streaming *stream,
 130        struct uvc_streaming_control *ctrl)
 131{
 132        struct uvc_format *format = NULL;
 133        struct uvc_frame *frame = NULL;
 134        unsigned int i;
 135
 136        for (i = 0; i < stream->nformats; ++i) {
 137                if (stream->format[i].index == ctrl->bFormatIndex) {
 138                        format = &stream->format[i];
 139                        break;
 140                }
 141        }
 142
 143        if (format == NULL)
 144                return;
 145
 146        for (i = 0; i < format->nframes; ++i) {
 147                if (format->frame[i].bFrameIndex == ctrl->bFrameIndex) {
 148                        frame = &format->frame[i];
 149                        break;
 150                }
 151        }
 152
 153        if (frame == NULL)
 154                return;
 155
 156        if (!(format->flags & UVC_FMT_FLAG_COMPRESSED) ||
 157             (ctrl->dwMaxVideoFrameSize == 0 &&
 158              stream->dev->uvc_version < 0x0110))
 159                ctrl->dwMaxVideoFrameSize =
 160                        frame->dwMaxVideoFrameBufferSize;
 161
 162        /* The "TOSHIBA Web Camera - 5M" Chicony device (04f2:b50b) seems to
 163         * compute the bandwidth on 16 bits and erroneously sign-extend it to
 164         * 32 bits, resulting in a huge bandwidth value. Detect and fix that
 165         * condition by setting the 16 MSBs to 0 when they're all equal to 1.
 166         */
 167        if ((ctrl->dwMaxPayloadTransferSize & 0xffff0000) == 0xffff0000)
 168                ctrl->dwMaxPayloadTransferSize &= ~0xffff0000;
 169
 170        if (!(format->flags & UVC_FMT_FLAG_COMPRESSED) &&
 171            stream->dev->quirks & UVC_QUIRK_FIX_BANDWIDTH &&
 172            stream->intf->num_altsetting > 1) {
 173                u32 interval;
 174                u32 bandwidth;
 175
 176                interval = (ctrl->dwFrameInterval > 100000)
 177                         ? ctrl->dwFrameInterval
 178                         : frame->dwFrameInterval[0];
 179
 180                /* Compute a bandwidth estimation by multiplying the frame
 181                 * size by the number of video frames per second, divide the
 182                 * result by the number of USB frames (or micro-frames for
 183                 * high-speed devices) per second and add the UVC header size
 184                 * (assumed to be 12 bytes long).
 185                 */
 186                bandwidth = frame->wWidth * frame->wHeight / 8 * format->bpp;
 187                bandwidth *= 10000000 / interval + 1;
 188                bandwidth /= 1000;
 189                if (stream->dev->udev->speed == USB_SPEED_HIGH)
 190                        bandwidth /= 8;
 191                bandwidth += 12;
 192
 193                /* The bandwidth estimate is too low for many cameras. Don't use
 194                 * maximum packet sizes lower than 1024 bytes to try and work
 195                 * around the problem. According to measurements done on two
 196                 * different camera models, the value is high enough to get most
 197                 * resolutions working while not preventing two simultaneous
 198                 * VGA streams at 15 fps.
 199                 */
 200                bandwidth = max_t(u32, bandwidth, 1024);
 201
 202                ctrl->dwMaxPayloadTransferSize = bandwidth;
 203        }
 204}
 205
 206static size_t uvc_video_ctrl_size(struct uvc_streaming *stream)
 207{
 208        /*
 209         * Return the size of the video probe and commit controls, which depends
 210         * on the protocol version.
 211         */
 212        if (stream->dev->uvc_version < 0x0110)
 213                return 26;
 214        else if (stream->dev->uvc_version < 0x0150)
 215                return 34;
 216        else
 217                return 48;
 218}
 219
 220static int uvc_get_video_ctrl(struct uvc_streaming *stream,
 221        struct uvc_streaming_control *ctrl, int probe, u8 query)
 222{
 223        u16 size = uvc_video_ctrl_size(stream);
 224        u8 *data;
 225        int ret;
 226
 227        if ((stream->dev->quirks & UVC_QUIRK_PROBE_DEF) &&
 228                        query == UVC_GET_DEF)
 229                return -EIO;
 230
 231        data = kmalloc(size, GFP_KERNEL);
 232        if (data == NULL)
 233                return -ENOMEM;
 234
 235        ret = __uvc_query_ctrl(stream->dev, query, 0, stream->intfnum,
 236                probe ? UVC_VS_PROBE_CONTROL : UVC_VS_COMMIT_CONTROL, data,
 237                size, uvc_timeout_param);
 238
 239        if ((query == UVC_GET_MIN || query == UVC_GET_MAX) && ret == 2) {
 240                /* Some cameras, mostly based on Bison Electronics chipsets,
 241                 * answer a GET_MIN or GET_MAX request with the wCompQuality
 242                 * field only.
 243                 */
 244                uvc_warn_once(stream->dev, UVC_WARN_MINMAX, "UVC non "
 245                        "compliance - GET_MIN/MAX(PROBE) incorrectly "
 246                        "supported. Enabling workaround.\n");
 247                memset(ctrl, 0, sizeof *ctrl);
 248                ctrl->wCompQuality = le16_to_cpup((__le16 *)data);
 249                ret = 0;
 250                goto out;
 251        } else if (query == UVC_GET_DEF && probe == 1 && ret != size) {
 252                /* Many cameras don't support the GET_DEF request on their
 253                 * video probe control. Warn once and return, the caller will
 254                 * fall back to GET_CUR.
 255                 */
 256                uvc_warn_once(stream->dev, UVC_WARN_PROBE_DEF, "UVC non "
 257                        "compliance - GET_DEF(PROBE) not supported. "
 258                        "Enabling workaround.\n");
 259                ret = -EIO;
 260                goto out;
 261        } else if (ret != size) {
 262                uvc_printk(KERN_ERR, "Failed to query (%u) UVC %s control : "
 263                        "%d (exp. %u).\n", query, probe ? "probe" : "commit",
 264                        ret, size);
 265                ret = -EIO;
 266                goto out;
 267        }
 268
 269        ctrl->bmHint = le16_to_cpup((__le16 *)&data[0]);
 270        ctrl->bFormatIndex = data[2];
 271        ctrl->bFrameIndex = data[3];
 272        ctrl->dwFrameInterval = le32_to_cpup((__le32 *)&data[4]);
 273        ctrl->wKeyFrameRate = le16_to_cpup((__le16 *)&data[8]);
 274        ctrl->wPFrameRate = le16_to_cpup((__le16 *)&data[10]);
 275        ctrl->wCompQuality = le16_to_cpup((__le16 *)&data[12]);
 276        ctrl->wCompWindowSize = le16_to_cpup((__le16 *)&data[14]);
 277        ctrl->wDelay = le16_to_cpup((__le16 *)&data[16]);
 278        ctrl->dwMaxVideoFrameSize = get_unaligned_le32(&data[18]);
 279        ctrl->dwMaxPayloadTransferSize = get_unaligned_le32(&data[22]);
 280
 281        if (size >= 34) {
 282                ctrl->dwClockFrequency = get_unaligned_le32(&data[26]);
 283                ctrl->bmFramingInfo = data[30];
 284                ctrl->bPreferedVersion = data[31];
 285                ctrl->bMinVersion = data[32];
 286                ctrl->bMaxVersion = data[33];
 287        } else {
 288                ctrl->dwClockFrequency = stream->dev->clock_frequency;
 289                ctrl->bmFramingInfo = 0;
 290                ctrl->bPreferedVersion = 0;
 291                ctrl->bMinVersion = 0;
 292                ctrl->bMaxVersion = 0;
 293        }
 294
 295        /* Some broken devices return null or wrong dwMaxVideoFrameSize and
 296         * dwMaxPayloadTransferSize fields. Try to get the value from the
 297         * format and frame descriptors.
 298         */
 299        uvc_fixup_video_ctrl(stream, ctrl);
 300        ret = 0;
 301
 302out:
 303        kfree(data);
 304        return ret;
 305}
 306
 307static int uvc_set_video_ctrl(struct uvc_streaming *stream,
 308        struct uvc_streaming_control *ctrl, int probe)
 309{
 310        u16 size = uvc_video_ctrl_size(stream);
 311        u8 *data;
 312        int ret;
 313
 314        data = kzalloc(size, GFP_KERNEL);
 315        if (data == NULL)
 316                return -ENOMEM;
 317
 318        *(__le16 *)&data[0] = cpu_to_le16(ctrl->bmHint);
 319        data[2] = ctrl->bFormatIndex;
 320        data[3] = ctrl->bFrameIndex;
 321        *(__le32 *)&data[4] = cpu_to_le32(ctrl->dwFrameInterval);
 322        *(__le16 *)&data[8] = cpu_to_le16(ctrl->wKeyFrameRate);
 323        *(__le16 *)&data[10] = cpu_to_le16(ctrl->wPFrameRate);
 324        *(__le16 *)&data[12] = cpu_to_le16(ctrl->wCompQuality);
 325        *(__le16 *)&data[14] = cpu_to_le16(ctrl->wCompWindowSize);
 326        *(__le16 *)&data[16] = cpu_to_le16(ctrl->wDelay);
 327        put_unaligned_le32(ctrl->dwMaxVideoFrameSize, &data[18]);
 328        put_unaligned_le32(ctrl->dwMaxPayloadTransferSize, &data[22]);
 329
 330        if (size >= 34) {
 331                put_unaligned_le32(ctrl->dwClockFrequency, &data[26]);
 332                data[30] = ctrl->bmFramingInfo;
 333                data[31] = ctrl->bPreferedVersion;
 334                data[32] = ctrl->bMinVersion;
 335                data[33] = ctrl->bMaxVersion;
 336        }
 337
 338        ret = __uvc_query_ctrl(stream->dev, UVC_SET_CUR, 0, stream->intfnum,
 339                probe ? UVC_VS_PROBE_CONTROL : UVC_VS_COMMIT_CONTROL, data,
 340                size, uvc_timeout_param);
 341        if (ret != size) {
 342                uvc_printk(KERN_ERR, "Failed to set UVC %s control : "
 343                        "%d (exp. %u).\n", probe ? "probe" : "commit",
 344                        ret, size);
 345                ret = -EIO;
 346        }
 347
 348        kfree(data);
 349        return ret;
 350}
 351
 352int uvc_probe_video(struct uvc_streaming *stream,
 353        struct uvc_streaming_control *probe)
 354{
 355        struct uvc_streaming_control probe_min, probe_max;
 356        u16 bandwidth;
 357        unsigned int i;
 358        int ret;
 359
 360        /* Perform probing. The device should adjust the requested values
 361         * according to its capabilities. However, some devices, namely the
 362         * first generation UVC Logitech webcams, don't implement the Video
 363         * Probe control properly, and just return the needed bandwidth. For
 364         * that reason, if the needed bandwidth exceeds the maximum available
 365         * bandwidth, try to lower the quality.
 366         */
 367        ret = uvc_set_video_ctrl(stream, probe, 1);
 368        if (ret < 0)
 369                goto done;
 370
 371        /* Get the minimum and maximum values for compression settings. */
 372        if (!(stream->dev->quirks & UVC_QUIRK_PROBE_MINMAX)) {
 373                ret = uvc_get_video_ctrl(stream, &probe_min, 1, UVC_GET_MIN);
 374                if (ret < 0)
 375                        goto done;
 376                ret = uvc_get_video_ctrl(stream, &probe_max, 1, UVC_GET_MAX);
 377                if (ret < 0)
 378                        goto done;
 379
 380                probe->wCompQuality = probe_max.wCompQuality;
 381        }
 382
 383        for (i = 0; i < 2; ++i) {
 384                ret = uvc_set_video_ctrl(stream, probe, 1);
 385                if (ret < 0)
 386                        goto done;
 387                ret = uvc_get_video_ctrl(stream, probe, 1, UVC_GET_CUR);
 388                if (ret < 0)
 389                        goto done;
 390
 391                if (stream->intf->num_altsetting == 1)
 392                        break;
 393
 394                bandwidth = probe->dwMaxPayloadTransferSize;
 395                if (bandwidth <= stream->maxpsize)
 396                        break;
 397
 398                if (stream->dev->quirks & UVC_QUIRK_PROBE_MINMAX) {
 399                        ret = -ENOSPC;
 400                        goto done;
 401                }
 402
 403                /* TODO: negotiate compression parameters */
 404                probe->wKeyFrameRate = probe_min.wKeyFrameRate;
 405                probe->wPFrameRate = probe_min.wPFrameRate;
 406                probe->wCompQuality = probe_max.wCompQuality;
 407                probe->wCompWindowSize = probe_min.wCompWindowSize;
 408        }
 409
 410done:
 411        return ret;
 412}
 413
 414static int uvc_commit_video(struct uvc_streaming *stream,
 415                            struct uvc_streaming_control *probe)
 416{
 417        return uvc_set_video_ctrl(stream, probe, 0);
 418}
 419
 420/* -----------------------------------------------------------------------------
 421 * Clocks and timestamps
 422 */
 423
 424static inline void uvc_video_get_ts(struct timespec *ts)
 425{
 426        if (uvc_clock_param == CLOCK_MONOTONIC)
 427                ktime_get_ts(ts);
 428        else
 429                ktime_get_real_ts(ts);
 430}
 431
 432static void
 433uvc_video_clock_decode(struct uvc_streaming *stream, struct uvc_buffer *buf,
 434                       const u8 *data, int len)
 435{
 436        struct uvc_clock_sample *sample;
 437        unsigned int header_size;
 438        bool has_pts = false;
 439        bool has_scr = false;
 440        unsigned long flags;
 441        struct timespec ts;
 442        u16 host_sof;
 443        u16 dev_sof;
 444
 445        switch (data[1] & (UVC_STREAM_PTS | UVC_STREAM_SCR)) {
 446        case UVC_STREAM_PTS | UVC_STREAM_SCR:
 447                header_size = 12;
 448                has_pts = true;
 449                has_scr = true;
 450                break;
 451        case UVC_STREAM_PTS:
 452                header_size = 6;
 453                has_pts = true;
 454                break;
 455        case UVC_STREAM_SCR:
 456                header_size = 8;
 457                has_scr = true;
 458                break;
 459        default:
 460                header_size = 2;
 461                break;
 462        }
 463
 464        /* Check for invalid headers. */
 465        if (len < header_size)
 466                return;
 467
 468        /* Extract the timestamps:
 469         *
 470         * - store the frame PTS in the buffer structure
 471         * - if the SCR field is present, retrieve the host SOF counter and
 472         *   kernel timestamps and store them with the SCR STC and SOF fields
 473         *   in the ring buffer
 474         */
 475        if (has_pts && buf != NULL)
 476                buf->pts = get_unaligned_le32(&data[2]);
 477
 478        if (!has_scr)
 479                return;
 480
 481        /* To limit the amount of data, drop SCRs with an SOF identical to the
 482         * previous one.
 483         */
 484        dev_sof = get_unaligned_le16(&data[header_size - 2]);
 485        if (dev_sof == stream->clock.last_sof)
 486                return;
 487
 488        stream->clock.last_sof = dev_sof;
 489
 490        host_sof = usb_get_current_frame_number(stream->dev->udev);
 491        uvc_video_get_ts(&ts);
 492
 493        /* The UVC specification allows device implementations that can't obtain
 494         * the USB frame number to keep their own frame counters as long as they
 495         * match the size and frequency of the frame number associated with USB
 496         * SOF tokens. The SOF values sent by such devices differ from the USB
 497         * SOF tokens by a fixed offset that needs to be estimated and accounted
 498         * for to make timestamp recovery as accurate as possible.
 499         *
 500         * The offset is estimated the first time a device SOF value is received
 501         * as the difference between the host and device SOF values. As the two
 502         * SOF values can differ slightly due to transmission delays, consider
 503         * that the offset is null if the difference is not higher than 10 ms
 504         * (negative differences can not happen and are thus considered as an
 505         * offset). The video commit control wDelay field should be used to
 506         * compute a dynamic threshold instead of using a fixed 10 ms value, but
 507         * devices don't report reliable wDelay values.
 508         *
 509         * See uvc_video_clock_host_sof() for an explanation regarding why only
 510         * the 8 LSBs of the delta are kept.
 511         */
 512        if (stream->clock.sof_offset == (u16)-1) {
 513                u16 delta_sof = (host_sof - dev_sof) & 255;
 514                if (delta_sof >= 10)
 515                        stream->clock.sof_offset = delta_sof;
 516                else
 517                        stream->clock.sof_offset = 0;
 518        }
 519
 520        dev_sof = (dev_sof + stream->clock.sof_offset) & 2047;
 521
 522        spin_lock_irqsave(&stream->clock.lock, flags);
 523
 524        sample = &stream->clock.samples[stream->clock.head];
 525        sample->dev_stc = get_unaligned_le32(&data[header_size - 6]);
 526        sample->dev_sof = dev_sof;
 527        sample->host_sof = host_sof;
 528        sample->host_ts = ts;
 529
 530        /* Update the sliding window head and count. */
 531        stream->clock.head = (stream->clock.head + 1) % stream->clock.size;
 532
 533        if (stream->clock.count < stream->clock.size)
 534                stream->clock.count++;
 535
 536        spin_unlock_irqrestore(&stream->clock.lock, flags);
 537}
 538
 539static void uvc_video_clock_reset(struct uvc_streaming *stream)
 540{
 541        struct uvc_clock *clock = &stream->clock;
 542
 543        clock->head = 0;
 544        clock->count = 0;
 545        clock->last_sof = -1;
 546        clock->sof_offset = -1;
 547}
 548
 549static int uvc_video_clock_init(struct uvc_streaming *stream)
 550{
 551        struct uvc_clock *clock = &stream->clock;
 552
 553        spin_lock_init(&clock->lock);
 554        clock->size = 32;
 555
 556        clock->samples = kmalloc(clock->size * sizeof(*clock->samples),
 557                                 GFP_KERNEL);
 558        if (clock->samples == NULL)
 559                return -ENOMEM;
 560
 561        uvc_video_clock_reset(stream);
 562
 563        return 0;
 564}
 565
 566static void uvc_video_clock_cleanup(struct uvc_streaming *stream)
 567{
 568        kfree(stream->clock.samples);
 569        stream->clock.samples = NULL;
 570}
 571
 572/*
 573 * uvc_video_clock_host_sof - Return the host SOF value for a clock sample
 574 *
 575 * Host SOF counters reported by usb_get_current_frame_number() usually don't
 576 * cover the whole 11-bits SOF range (0-2047) but are limited to the HCI frame
 577 * schedule window. They can be limited to 8, 9 or 10 bits depending on the host
 578 * controller and its configuration.
 579 *
 580 * We thus need to recover the SOF value corresponding to the host frame number.
 581 * As the device and host frame numbers are sampled in a short interval, the
 582 * difference between their values should be equal to a small delta plus an
 583 * integer multiple of 256 caused by the host frame number limited precision.
 584 *
 585 * To obtain the recovered host SOF value, compute the small delta by masking
 586 * the high bits of the host frame counter and device SOF difference and add it
 587 * to the device SOF value.
 588 */
 589static u16 uvc_video_clock_host_sof(const struct uvc_clock_sample *sample)
 590{
 591        /* The delta value can be negative. */
 592        s8 delta_sof;
 593
 594        delta_sof = (sample->host_sof - sample->dev_sof) & 255;
 595
 596        return (sample->dev_sof + delta_sof) & 2047;
 597}
 598
 599/*
 600 * uvc_video_clock_update - Update the buffer timestamp
 601 *
 602 * This function converts the buffer PTS timestamp to the host clock domain by
 603 * going through the USB SOF clock domain and stores the result in the V4L2
 604 * buffer timestamp field.
 605 *
 606 * The relationship between the device clock and the host clock isn't known.
 607 * However, the device and the host share the common USB SOF clock which can be
 608 * used to recover that relationship.
 609 *
 610 * The relationship between the device clock and the USB SOF clock is considered
 611 * to be linear over the clock samples sliding window and is given by
 612 *
 613 * SOF = m * PTS + p
 614 *
 615 * Several methods to compute the slope (m) and intercept (p) can be used. As
 616 * the clock drift should be small compared to the sliding window size, we
 617 * assume that the line that goes through the points at both ends of the window
 618 * is a good approximation. Naming those points P1 and P2, we get
 619 *
 620 * SOF = (SOF2 - SOF1) / (STC2 - STC1) * PTS
 621 *     + (SOF1 * STC2 - SOF2 * STC1) / (STC2 - STC1)
 622 *
 623 * or
 624 *
 625 * SOF = ((SOF2 - SOF1) * PTS + SOF1 * STC2 - SOF2 * STC1) / (STC2 - STC1)   (1)
 626 *
 627 * to avoid loosing precision in the division. Similarly, the host timestamp is
 628 * computed with
 629 *
 630 * TS = ((TS2 - TS1) * PTS + TS1 * SOF2 - TS2 * SOF1) / (SOF2 - SOF1)        (2)
 631 *
 632 * SOF values are coded on 11 bits by USB. We extend their precision with 16
 633 * decimal bits, leading to a 11.16 coding.
 634 *
 635 * TODO: To avoid surprises with device clock values, PTS/STC timestamps should
 636 * be normalized using the nominal device clock frequency reported through the
 637 * UVC descriptors.
 638 *
 639 * Both the PTS/STC and SOF counters roll over, after a fixed but device
 640 * specific amount of time for PTS/STC and after 2048ms for SOF. As long as the
 641 * sliding window size is smaller than the rollover period, differences computed
 642 * on unsigned integers will produce the correct result. However, the p term in
 643 * the linear relations will be miscomputed.
 644 *
 645 * To fix the issue, we subtract a constant from the PTS and STC values to bring
 646 * PTS to half the 32 bit STC range. The sliding window STC values then fit into
 647 * the 32 bit range without any rollover.
 648 *
 649 * Similarly, we add 2048 to the device SOF values to make sure that the SOF
 650 * computed by (1) will never be smaller than 0. This offset is then compensated
 651 * by adding 2048 to the SOF values used in (2). However, this doesn't prevent
 652 * rollovers between (1) and (2): the SOF value computed by (1) can be slightly
 653 * lower than 4096, and the host SOF counters can have rolled over to 2048. This
 654 * case is handled by subtracting 2048 from the SOF value if it exceeds the host
 655 * SOF value at the end of the sliding window.
 656 *
 657 * Finally we subtract a constant from the host timestamps to bring the first
 658 * timestamp of the sliding window to 1s.
 659 */
 660void uvc_video_clock_update(struct uvc_streaming *stream,
 661                            struct v4l2_buffer *v4l2_buf,
 662                            struct uvc_buffer *buf)
 663{
 664        struct uvc_clock *clock = &stream->clock;
 665        struct uvc_clock_sample *first;
 666        struct uvc_clock_sample *last;
 667        unsigned long flags;
 668        struct timespec ts;
 669        u32 delta_stc;
 670        u32 y1, y2;
 671        u32 x1, x2;
 672        u32 mean;
 673        u32 sof;
 674        u32 div;
 675        u32 rem;
 676        u64 y;
 677
 678        if (!uvc_hw_timestamps_param)
 679                return;
 680
 681        spin_lock_irqsave(&clock->lock, flags);
 682
 683        if (clock->count < clock->size)
 684                goto done;
 685
 686        first = &clock->samples[clock->head];
 687        last = &clock->samples[(clock->head - 1) % clock->size];
 688
 689        /* First step, PTS to SOF conversion. */
 690        delta_stc = buf->pts - (1UL << 31);
 691        x1 = first->dev_stc - delta_stc;
 692        x2 = last->dev_stc - delta_stc;
 693        if (x1 == x2)
 694                goto done;
 695
 696        y1 = (first->dev_sof + 2048) << 16;
 697        y2 = (last->dev_sof + 2048) << 16;
 698        if (y2 < y1)
 699                y2 += 2048 << 16;
 700
 701        y = (u64)(y2 - y1) * (1ULL << 31) + (u64)y1 * (u64)x2
 702          - (u64)y2 * (u64)x1;
 703        y = div_u64(y, x2 - x1);
 704
 705        sof = y;
 706
 707        uvc_trace(UVC_TRACE_CLOCK, "%s: PTS %u y %llu.%06llu SOF %u.%06llu "
 708                  "(x1 %u x2 %u y1 %u y2 %u SOF offset %u)\n",
 709                  stream->dev->name, buf->pts,
 710                  y >> 16, div_u64((y & 0xffff) * 1000000, 65536),
 711                  sof >> 16, div_u64(((u64)sof & 0xffff) * 1000000LLU, 65536),
 712                  x1, x2, y1, y2, clock->sof_offset);
 713
 714        /* Second step, SOF to host clock conversion. */
 715        x1 = (uvc_video_clock_host_sof(first) + 2048) << 16;
 716        x2 = (uvc_video_clock_host_sof(last) + 2048) << 16;
 717        if (x2 < x1)
 718                x2 += 2048 << 16;
 719        if (x1 == x2)
 720                goto done;
 721
 722        ts = timespec_sub(last->host_ts, first->host_ts);
 723        y1 = NSEC_PER_SEC;
 724        y2 = (ts.tv_sec + 1) * NSEC_PER_SEC + ts.tv_nsec;
 725
 726        /* Interpolated and host SOF timestamps can wrap around at slightly
 727         * different times. Handle this by adding or removing 2048 to or from
 728         * the computed SOF value to keep it close to the SOF samples mean
 729         * value.
 730         */
 731        mean = (x1 + x2) / 2;
 732        if (mean - (1024 << 16) > sof)
 733                sof += 2048 << 16;
 734        else if (sof > mean + (1024 << 16))
 735                sof -= 2048 << 16;
 736
 737        y = (u64)(y2 - y1) * (u64)sof + (u64)y1 * (u64)x2
 738          - (u64)y2 * (u64)x1;
 739        y = div_u64(y, x2 - x1);
 740
 741        div = div_u64_rem(y, NSEC_PER_SEC, &rem);
 742        ts.tv_sec = first->host_ts.tv_sec - 1 + div;
 743        ts.tv_nsec = first->host_ts.tv_nsec + rem;
 744        if (ts.tv_nsec >= NSEC_PER_SEC) {
 745                ts.tv_sec++;
 746                ts.tv_nsec -= NSEC_PER_SEC;
 747        }
 748
 749        uvc_trace(UVC_TRACE_CLOCK, "%s: SOF %u.%06llu y %llu ts %lu.%06lu "
 750                  "buf ts %lu.%06lu (x1 %u/%u/%u x2 %u/%u/%u y1 %u y2 %u)\n",
 751                  stream->dev->name,
 752                  sof >> 16, div_u64(((u64)sof & 0xffff) * 1000000LLU, 65536),
 753                  y, ts.tv_sec, ts.tv_nsec / NSEC_PER_USEC,
 754                  v4l2_buf->timestamp.tv_sec,
 755                  (unsigned long)v4l2_buf->timestamp.tv_usec,
 756                  x1, first->host_sof, first->dev_sof,
 757                  x2, last->host_sof, last->dev_sof, y1, y2);
 758
 759        /* Update the V4L2 buffer. */
 760        v4l2_buf->timestamp.tv_sec = ts.tv_sec;
 761        v4l2_buf->timestamp.tv_usec = ts.tv_nsec / NSEC_PER_USEC;
 762
 763done:
 764        spin_unlock_irqrestore(&stream->clock.lock, flags);
 765}
 766
 767/* ------------------------------------------------------------------------
 768 * Stream statistics
 769 */
 770
 771static void uvc_video_stats_decode(struct uvc_streaming *stream,
 772                const u8 *data, int len)
 773{
 774        unsigned int header_size;
 775        bool has_pts = false;
 776        bool has_scr = false;
 777        u16 uninitialized_var(scr_sof);
 778        u32 uninitialized_var(scr_stc);
 779        u32 uninitialized_var(pts);
 780
 781        if (stream->stats.stream.nb_frames == 0 &&
 782            stream->stats.frame.nb_packets == 0)
 783                stream->stats.stream.start_ts = ktime_get();
 784
 785        switch (data[1] & (UVC_STREAM_PTS | UVC_STREAM_SCR)) {
 786        case UVC_STREAM_PTS | UVC_STREAM_SCR:
 787                header_size = 12;
 788                has_pts = true;
 789                has_scr = true;
 790                break;
 791        case UVC_STREAM_PTS:
 792                header_size = 6;
 793                has_pts = true;
 794                break;
 795        case UVC_STREAM_SCR:
 796                header_size = 8;
 797                has_scr = true;
 798                break;
 799        default:
 800                header_size = 2;
 801                break;
 802        }
 803
 804        /* Check for invalid headers. */
 805        if (len < header_size || data[0] < header_size) {
 806                stream->stats.frame.nb_invalid++;
 807                return;
 808        }
 809
 810        /* Extract the timestamps. */
 811        if (has_pts)
 812                pts = get_unaligned_le32(&data[2]);
 813
 814        if (has_scr) {
 815                scr_stc = get_unaligned_le32(&data[header_size - 6]);
 816                scr_sof = get_unaligned_le16(&data[header_size - 2]);
 817        }
 818
 819        /* Is PTS constant through the whole frame ? */
 820        if (has_pts && stream->stats.frame.nb_pts) {
 821                if (stream->stats.frame.pts != pts) {
 822                        stream->stats.frame.nb_pts_diffs++;
 823                        stream->stats.frame.last_pts_diff =
 824                                stream->stats.frame.nb_packets;
 825                }
 826        }
 827
 828        if (has_pts) {
 829                stream->stats.frame.nb_pts++;
 830                stream->stats.frame.pts = pts;
 831        }
 832
 833        /* Do all frames have a PTS in their first non-empty packet, or before
 834         * their first empty packet ?
 835         */
 836        if (stream->stats.frame.size == 0) {
 837                if (len > header_size)
 838                        stream->stats.frame.has_initial_pts = has_pts;
 839                if (len == header_size && has_pts)
 840                        stream->stats.frame.has_early_pts = true;
 841        }
 842
 843        /* Do the SCR.STC and SCR.SOF fields vary through the frame ? */
 844        if (has_scr && stream->stats.frame.nb_scr) {
 845                if (stream->stats.frame.scr_stc != scr_stc)
 846                        stream->stats.frame.nb_scr_diffs++;
 847        }
 848
 849        if (has_scr) {
 850                /* Expand the SOF counter to 32 bits and store its value. */
 851                if (stream->stats.stream.nb_frames > 0 ||
 852                    stream->stats.frame.nb_scr > 0)
 853                        stream->stats.stream.scr_sof_count +=
 854                                (scr_sof - stream->stats.stream.scr_sof) % 2048;
 855                stream->stats.stream.scr_sof = scr_sof;
 856
 857                stream->stats.frame.nb_scr++;
 858                stream->stats.frame.scr_stc = scr_stc;
 859                stream->stats.frame.scr_sof = scr_sof;
 860
 861                if (scr_sof < stream->stats.stream.min_sof)
 862                        stream->stats.stream.min_sof = scr_sof;
 863                if (scr_sof > stream->stats.stream.max_sof)
 864                        stream->stats.stream.max_sof = scr_sof;
 865        }
 866
 867        /* Record the first non-empty packet number. */
 868        if (stream->stats.frame.size == 0 && len > header_size)
 869                stream->stats.frame.first_data = stream->stats.frame.nb_packets;
 870
 871        /* Update the frame size. */
 872        stream->stats.frame.size += len - header_size;
 873
 874        /* Update the packets counters. */
 875        stream->stats.frame.nb_packets++;
 876        if (len <= header_size)
 877                stream->stats.frame.nb_empty++;
 878
 879        if (data[1] & UVC_STREAM_ERR)
 880                stream->stats.frame.nb_errors++;
 881}
 882
 883static void uvc_video_stats_update(struct uvc_streaming *stream)
 884{
 885        struct uvc_stats_frame *frame = &stream->stats.frame;
 886
 887        uvc_trace(UVC_TRACE_STATS, "frame %u stats: %u/%u/%u packets, "
 888                  "%u/%u/%u pts (%searly %sinitial), %u/%u scr, "
 889                  "last pts/stc/sof %u/%u/%u\n",
 890                  stream->sequence, frame->first_data,
 891                  frame->nb_packets - frame->nb_empty, frame->nb_packets,
 892                  frame->nb_pts_diffs, frame->last_pts_diff, frame->nb_pts,
 893                  frame->has_early_pts ? "" : "!",
 894                  frame->has_initial_pts ? "" : "!",
 895                  frame->nb_scr_diffs, frame->nb_scr,
 896                  frame->pts, frame->scr_stc, frame->scr_sof);
 897
 898        stream->stats.stream.nb_frames++;
 899        stream->stats.stream.nb_packets += stream->stats.frame.nb_packets;
 900        stream->stats.stream.nb_empty += stream->stats.frame.nb_empty;
 901        stream->stats.stream.nb_errors += stream->stats.frame.nb_errors;
 902        stream->stats.stream.nb_invalid += stream->stats.frame.nb_invalid;
 903
 904        if (frame->has_early_pts)
 905                stream->stats.stream.nb_pts_early++;
 906        if (frame->has_initial_pts)
 907                stream->stats.stream.nb_pts_initial++;
 908        if (frame->last_pts_diff <= frame->first_data)
 909                stream->stats.stream.nb_pts_constant++;
 910        if (frame->nb_scr >= frame->nb_packets - frame->nb_empty)
 911                stream->stats.stream.nb_scr_count_ok++;
 912        if (frame->nb_scr_diffs + 1 == frame->nb_scr)
 913                stream->stats.stream.nb_scr_diffs_ok++;
 914
 915        memset(&stream->stats.frame, 0, sizeof(stream->stats.frame));
 916}
 917
 918size_t uvc_video_stats_dump(struct uvc_streaming *stream, char *buf,
 919                            size_t size)
 920{
 921        unsigned int scr_sof_freq;
 922        unsigned int duration;
 923        size_t count = 0;
 924
 925        /* Compute the SCR.SOF frequency estimate. At the nominal 1kHz SOF
 926         * frequency this will not overflow before more than 1h.
 927         */
 928        duration = ktime_ms_delta(stream->stats.stream.stop_ts,
 929                                  stream->stats.stream.start_ts);
 930        if (duration != 0)
 931                scr_sof_freq = stream->stats.stream.scr_sof_count * 1000
 932                             / duration;
 933        else
 934                scr_sof_freq = 0;
 935
 936        count += scnprintf(buf + count, size - count,
 937                           "frames:  %u\npackets: %u\nempty:   %u\n"
 938                           "errors:  %u\ninvalid: %u\n",
 939                           stream->stats.stream.nb_frames,
 940                           stream->stats.stream.nb_packets,
 941                           stream->stats.stream.nb_empty,
 942                           stream->stats.stream.nb_errors,
 943                           stream->stats.stream.nb_invalid);
 944        count += scnprintf(buf + count, size - count,
 945                           "pts: %u early, %u initial, %u ok\n",
 946                           stream->stats.stream.nb_pts_early,
 947                           stream->stats.stream.nb_pts_initial,
 948                           stream->stats.stream.nb_pts_constant);
 949        count += scnprintf(buf + count, size - count,
 950                           "scr: %u count ok, %u diff ok\n",
 951                           stream->stats.stream.nb_scr_count_ok,
 952                           stream->stats.stream.nb_scr_diffs_ok);
 953        count += scnprintf(buf + count, size - count,
 954                           "sof: %u <= sof <= %u, freq %u.%03u kHz\n",
 955                           stream->stats.stream.min_sof,
 956                           stream->stats.stream.max_sof,
 957                           scr_sof_freq / 1000, scr_sof_freq % 1000);
 958
 959        return count;
 960}
 961
 962static void uvc_video_stats_start(struct uvc_streaming *stream)
 963{
 964        memset(&stream->stats, 0, sizeof(stream->stats));
 965        stream->stats.stream.min_sof = 2048;
 966}
 967
 968static void uvc_video_stats_stop(struct uvc_streaming *stream)
 969{
 970        stream->stats.stream.stop_ts = ktime_get();
 971}
 972
 973/* ------------------------------------------------------------------------
 974 * Video codecs
 975 */
 976
 977/* Video payload decoding is handled by uvc_video_decode_start(),
 978 * uvc_video_decode_data() and uvc_video_decode_end().
 979 *
 980 * uvc_video_decode_start is called with URB data at the start of a bulk or
 981 * isochronous payload. It processes header data and returns the header size
 982 * in bytes if successful. If an error occurs, it returns a negative error
 983 * code. The following error codes have special meanings.
 984 *
 985 * - EAGAIN informs the caller that the current video buffer should be marked
 986 *   as done, and that the function should be called again with the same data
 987 *   and a new video buffer. This is used when end of frame conditions can be
 988 *   reliably detected at the beginning of the next frame only.
 989 *
 990 * If an error other than -EAGAIN is returned, the caller will drop the current
 991 * payload. No call to uvc_video_decode_data and uvc_video_decode_end will be
 992 * made until the next payload. -ENODATA can be used to drop the current
 993 * payload if no other error code is appropriate.
 994 *
 995 * uvc_video_decode_data is called for every URB with URB data. It copies the
 996 * data to the video buffer.
 997 *
 998 * uvc_video_decode_end is called with header data at the end of a bulk or
 999 * isochronous payload. It performs any additional header data processing and
1000 * returns 0 or a negative error code if an error occurred. As header data have
1001 * already been processed by uvc_video_decode_start, this functions isn't
1002 * required to perform sanity checks a second time.
1003 *
1004 * For isochronous transfers where a payload is always transferred in a single
1005 * URB, the three functions will be called in a row.
1006 *
1007 * To let the decoder process header data and update its internal state even
1008 * when no video buffer is available, uvc_video_decode_start must be prepared
1009 * to be called with a NULL buf parameter. uvc_video_decode_data and
1010 * uvc_video_decode_end will never be called with a NULL buffer.
1011 */
1012static int uvc_video_decode_start(struct uvc_streaming *stream,
1013                struct uvc_buffer *buf, const u8 *data, int len)
1014{
1015        u8 fid;
1016
1017        /* Sanity checks:
1018         * - packet must be at least 2 bytes long
1019         * - bHeaderLength value must be at least 2 bytes (see above)
1020         * - bHeaderLength value can't be larger than the packet size.
1021         */
1022        if (len < 2 || data[0] < 2 || data[0] > len) {
1023                stream->stats.frame.nb_invalid++;
1024                return -EINVAL;
1025        }
1026
1027        fid = data[1] & UVC_STREAM_FID;
1028
1029        /* Increase the sequence number regardless of any buffer states, so
1030         * that discontinuous sequence numbers always indicate lost frames.
1031         */
1032        if (stream->last_fid != fid) {
1033                stream->sequence++;
1034                if (stream->sequence)
1035                        uvc_video_stats_update(stream);
1036        }
1037
1038        uvc_video_clock_decode(stream, buf, data, len);
1039        uvc_video_stats_decode(stream, data, len);
1040
1041        /* Store the payload FID bit and return immediately when the buffer is
1042         * NULL.
1043         */
1044        if (buf == NULL) {
1045                stream->last_fid = fid;
1046                return -ENODATA;
1047        }
1048
1049        /* Mark the buffer as bad if the error bit is set. */
1050        if (data[1] & UVC_STREAM_ERR) {
1051                uvc_trace(UVC_TRACE_FRAME, "Marking buffer as bad (error bit "
1052                          "set).\n");
1053                buf->error = 1;
1054        }
1055
1056        /* Synchronize to the input stream by waiting for the FID bit to be
1057         * toggled when the the buffer state is not UVC_BUF_STATE_ACTIVE.
1058         * stream->last_fid is initialized to -1, so the first isochronous
1059         * frame will always be in sync.
1060         *
1061         * If the device doesn't toggle the FID bit, invert stream->last_fid
1062         * when the EOF bit is set to force synchronisation on the next packet.
1063         */
1064        if (buf->state != UVC_BUF_STATE_ACTIVE) {
1065                struct timespec ts;
1066
1067                if (fid == stream->last_fid) {
1068                        uvc_trace(UVC_TRACE_FRAME, "Dropping payload (out of "
1069                                "sync).\n");
1070                        if ((stream->dev->quirks & UVC_QUIRK_STREAM_NO_FID) &&
1071                            (data[1] & UVC_STREAM_EOF))
1072                                stream->last_fid ^= UVC_STREAM_FID;
1073                        return -ENODATA;
1074                }
1075
1076                uvc_video_get_ts(&ts);
1077
1078                buf->buf.v4l2_buf.field = V4L2_FIELD_NONE;
1079                buf->buf.v4l2_buf.sequence = stream->sequence;
1080                buf->buf.v4l2_buf.timestamp.tv_sec = ts.tv_sec;
1081                buf->buf.v4l2_buf.timestamp.tv_usec =
1082                        ts.tv_nsec / NSEC_PER_USEC;
1083
1084                /* TODO: Handle PTS and SCR. */
1085                buf->state = UVC_BUF_STATE_ACTIVE;
1086        }
1087
1088        /* Mark the buffer as done if we're at the beginning of a new frame.
1089         * End of frame detection is better implemented by checking the EOF
1090         * bit (FID bit toggling is delayed by one frame compared to the EOF
1091         * bit), but some devices don't set the bit at end of frame (and the
1092         * last payload can be lost anyway). We thus must check if the FID has
1093         * been toggled.
1094         *
1095         * stream->last_fid is initialized to -1, so the first isochronous
1096         * frame will never trigger an end of frame detection.
1097         *
1098         * Empty buffers (bytesused == 0) don't trigger end of frame detection
1099         * as it doesn't make sense to return an empty buffer. This also
1100         * avoids detecting end of frame conditions at FID toggling if the
1101         * previous payload had the EOF bit set.
1102         */
1103        if (fid != stream->last_fid && buf->bytesused != 0) {
1104                uvc_trace(UVC_TRACE_FRAME, "Frame complete (FID bit "
1105                                "toggled).\n");
1106                buf->state = UVC_BUF_STATE_READY;
1107                return -EAGAIN;
1108        }
1109
1110        stream->last_fid = fid;
1111
1112        return data[0];
1113}
1114
1115static void uvc_video_decode_data(struct uvc_streaming *stream,
1116                struct uvc_buffer *buf, const u8 *data, int len)
1117{
1118        unsigned int maxlen, nbytes;
1119        void *mem;
1120
1121        if (len <= 0)
1122                return;
1123
1124        /* Copy the video data to the buffer. */
1125        maxlen = buf->length - buf->bytesused;
1126        mem = buf->mem + buf->bytesused;
1127        nbytes = min((unsigned int)len, maxlen);
1128        memcpy(mem, data, nbytes);
1129        buf->bytesused += nbytes;
1130
1131        /* Complete the current frame if the buffer size was exceeded. */
1132        if (len > maxlen) {
1133                uvc_trace(UVC_TRACE_FRAME, "Frame complete (overflow).\n");
1134                buf->error = 1;
1135                buf->state = UVC_BUF_STATE_READY;
1136        }
1137}
1138
1139static void uvc_video_decode_end(struct uvc_streaming *stream,
1140                struct uvc_buffer *buf, const u8 *data, int len)
1141{
1142        /* Mark the buffer as done if the EOF marker is set. */
1143        if (data[1] & UVC_STREAM_EOF && buf->bytesused != 0) {
1144                uvc_trace(UVC_TRACE_FRAME, "Frame complete (EOF found).\n");
1145                if (data[0] == len)
1146                        uvc_trace(UVC_TRACE_FRAME, "EOF in empty payload.\n");
1147                buf->state = UVC_BUF_STATE_READY;
1148                if (stream->dev->quirks & UVC_QUIRK_STREAM_NO_FID)
1149                        stream->last_fid ^= UVC_STREAM_FID;
1150        }
1151}
1152
1153/* Video payload encoding is handled by uvc_video_encode_header() and
1154 * uvc_video_encode_data(). Only bulk transfers are currently supported.
1155 *
1156 * uvc_video_encode_header is called at the start of a payload. It adds header
1157 * data to the transfer buffer and returns the header size. As the only known
1158 * UVC output device transfers a whole frame in a single payload, the EOF bit
1159 * is always set in the header.
1160 *
1161 * uvc_video_encode_data is called for every URB and copies the data from the
1162 * video buffer to the transfer buffer.
1163 */
1164static int uvc_video_encode_header(struct uvc_streaming *stream,
1165                struct uvc_buffer *buf, u8 *data, int len)
1166{
1167        data[0] = 2;    /* Header length */
1168        data[1] = UVC_STREAM_EOH | UVC_STREAM_EOF
1169                | (stream->last_fid & UVC_STREAM_FID);
1170        return 2;
1171}
1172
1173static int uvc_video_encode_data(struct uvc_streaming *stream,
1174                struct uvc_buffer *buf, u8 *data, int len)
1175{
1176        struct uvc_video_queue *queue = &stream->queue;
1177        unsigned int nbytes;
1178        void *mem;
1179
1180        /* Copy video data to the URB buffer. */
1181        mem = buf->mem + queue->buf_used;
1182        nbytes = min((unsigned int)len, buf->bytesused - queue->buf_used);
1183        nbytes = min(stream->bulk.max_payload_size - stream->bulk.payload_size,
1184                        nbytes);
1185        memcpy(data, mem, nbytes);
1186
1187        queue->buf_used += nbytes;
1188
1189        return nbytes;
1190}
1191
1192/* ------------------------------------------------------------------------
1193 * URB handling
1194 */
1195
1196/*
1197 * Set error flag for incomplete buffer.
1198 */
1199static void uvc_video_validate_buffer(const struct uvc_streaming *stream,
1200                                      struct uvc_buffer *buf)
1201{
1202        if (stream->ctrl.dwMaxVideoFrameSize != buf->bytesused &&
1203            !(stream->cur_format->flags & UVC_FMT_FLAG_COMPRESSED))
1204                buf->error = 1;
1205}
1206
1207/*
1208 * Completion handler for video URBs.
1209 */
1210static void uvc_video_decode_isoc(struct urb *urb, struct uvc_streaming *stream,
1211        struct uvc_buffer *buf)
1212{
1213        u8 *mem;
1214        int ret, i;
1215
1216        for (i = 0; i < urb->number_of_packets; ++i) {
1217                if (urb->iso_frame_desc[i].status < 0) {
1218                        uvc_trace(UVC_TRACE_FRAME, "USB isochronous frame "
1219                                "lost (%d).\n", urb->iso_frame_desc[i].status);
1220                        /* Mark the buffer as faulty. */
1221                        if (buf != NULL)
1222                                buf->error = 1;
1223                        continue;
1224                }
1225
1226                /* Decode the payload header. */
1227                mem = urb->transfer_buffer + urb->iso_frame_desc[i].offset;
1228                do {
1229                        ret = uvc_video_decode_start(stream, buf, mem,
1230                                urb->iso_frame_desc[i].actual_length);
1231                        if (ret == -EAGAIN) {
1232                                uvc_video_validate_buffer(stream, buf);
1233                                buf = uvc_queue_next_buffer(&stream->queue,
1234                                                            buf);
1235                        }
1236                } while (ret == -EAGAIN);
1237
1238                if (ret < 0)
1239                        continue;
1240
1241                /* Decode the payload data. */
1242                uvc_video_decode_data(stream, buf, mem + ret,
1243                        urb->iso_frame_desc[i].actual_length - ret);
1244
1245                /* Process the header again. */
1246                uvc_video_decode_end(stream, buf, mem,
1247                        urb->iso_frame_desc[i].actual_length);
1248
1249                if (buf->state == UVC_BUF_STATE_READY) {
1250                        uvc_video_validate_buffer(stream, buf);
1251                        buf = uvc_queue_next_buffer(&stream->queue, buf);
1252                }
1253        }
1254}
1255
1256static void uvc_video_decode_bulk(struct urb *urb, struct uvc_streaming *stream,
1257        struct uvc_buffer *buf)
1258{
1259        u8 *mem;
1260        int len, ret;
1261
1262        /*
1263         * Ignore ZLPs if they're not part of a frame, otherwise process them
1264         * to trigger the end of payload detection.
1265         */
1266        if (urb->actual_length == 0 && stream->bulk.header_size == 0)
1267                return;
1268
1269        mem = urb->transfer_buffer;
1270        len = urb->actual_length;
1271        stream->bulk.payload_size += len;
1272
1273        /* If the URB is the first of its payload, decode and save the
1274         * header.
1275         */
1276        if (stream->bulk.header_size == 0 && !stream->bulk.skip_payload) {
1277                do {
1278                        ret = uvc_video_decode_start(stream, buf, mem, len);
1279                        if (ret == -EAGAIN)
1280                                buf = uvc_queue_next_buffer(&stream->queue,
1281                                                            buf);
1282                } while (ret == -EAGAIN);
1283
1284                /* If an error occurred skip the rest of the payload. */
1285                if (ret < 0 || buf == NULL) {
1286                        stream->bulk.skip_payload = 1;
1287                } else {
1288                        memcpy(stream->bulk.header, mem, ret);
1289                        stream->bulk.header_size = ret;
1290
1291                        mem += ret;
1292                        len -= ret;
1293                }
1294        }
1295
1296        /* The buffer queue might have been cancelled while a bulk transfer
1297         * was in progress, so we can reach here with buf equal to NULL. Make
1298         * sure buf is never dereferenced if NULL.
1299         */
1300
1301        /* Process video data. */
1302        if (!stream->bulk.skip_payload && buf != NULL)
1303                uvc_video_decode_data(stream, buf, mem, len);
1304
1305        /* Detect the payload end by a URB smaller than the maximum size (or
1306         * a payload size equal to the maximum) and process the header again.
1307         */
1308        if (urb->actual_length < urb->transfer_buffer_length ||
1309            stream->bulk.payload_size >= stream->bulk.max_payload_size) {
1310                if (!stream->bulk.skip_payload && buf != NULL) {
1311                        uvc_video_decode_end(stream, buf, stream->bulk.header,
1312                                stream->bulk.payload_size);
1313                        if (buf->state == UVC_BUF_STATE_READY)
1314                                uvc_queue_next_buffer(&stream->queue, buf);
1315                }
1316
1317                stream->bulk.header_size = 0;
1318                stream->bulk.skip_payload = 0;
1319                stream->bulk.payload_size = 0;
1320        }
1321}
1322
1323static void uvc_video_encode_bulk(struct urb *urb, struct uvc_streaming *stream,
1324        struct uvc_buffer *buf)
1325{
1326        u8 *mem = urb->transfer_buffer;
1327        int len = stream->urb_size, ret;
1328
1329        if (buf == NULL) {
1330                urb->transfer_buffer_length = 0;
1331                return;
1332        }
1333
1334        /* If the URB is the first of its payload, add the header. */
1335        if (stream->bulk.header_size == 0) {
1336                ret = uvc_video_encode_header(stream, buf, mem, len);
1337                stream->bulk.header_size = ret;
1338                stream->bulk.payload_size += ret;
1339                mem += ret;
1340                len -= ret;
1341        }
1342
1343        /* Process video data. */
1344        ret = uvc_video_encode_data(stream, buf, mem, len);
1345
1346        stream->bulk.payload_size += ret;
1347        len -= ret;
1348
1349        if (buf->bytesused == stream->queue.buf_used ||
1350            stream->bulk.payload_size == stream->bulk.max_payload_size) {
1351                if (buf->bytesused == stream->queue.buf_used) {
1352                        stream->queue.buf_used = 0;
1353                        buf->state = UVC_BUF_STATE_READY;
1354                        buf->buf.v4l2_buf.sequence = ++stream->sequence;
1355                        uvc_queue_next_buffer(&stream->queue, buf);
1356                        stream->last_fid ^= UVC_STREAM_FID;
1357                }
1358
1359                stream->bulk.header_size = 0;
1360                stream->bulk.payload_size = 0;
1361        }
1362
1363        urb->transfer_buffer_length = stream->urb_size - len;
1364}
1365
1366static void uvc_video_complete(struct urb *urb)
1367{
1368        struct uvc_streaming *stream = urb->context;
1369        struct uvc_video_queue *queue = &stream->queue;
1370        struct uvc_buffer *buf = NULL;
1371        unsigned long flags;
1372        int ret;
1373
1374        switch (urb->status) {
1375        case 0:
1376                break;
1377
1378        default:
1379                uvc_printk(KERN_WARNING, "Non-zero status (%d) in video "
1380                        "completion handler.\n", urb->status);
1381                /* fall through */
1382        case -ENOENT:           /* usb_kill_urb() called. */
1383                if (stream->frozen)
1384                        return;
1385                /* fall through */
1386        case -ECONNRESET:       /* usb_unlink_urb() called. */
1387        case -ESHUTDOWN:        /* The endpoint is being disabled. */
1388                uvc_queue_cancel(queue, urb->status == -ESHUTDOWN);
1389                return;
1390        }
1391
1392        spin_lock_irqsave(&queue->irqlock, flags);
1393        if (!list_empty(&queue->irqqueue))
1394                buf = list_first_entry(&queue->irqqueue, struct uvc_buffer,
1395                                       queue);
1396        spin_unlock_irqrestore(&queue->irqlock, flags);
1397
1398        stream->decode(urb, stream, buf);
1399
1400        if ((ret = usb_submit_urb(urb, GFP_ATOMIC)) < 0) {
1401                uvc_printk(KERN_ERR, "Failed to resubmit video URB (%d).\n",
1402                        ret);
1403        }
1404}
1405
1406/*
1407 * Free transfer buffers.
1408 */
1409static void uvc_free_urb_buffers(struct uvc_streaming *stream)
1410{
1411        unsigned int i;
1412
1413        for (i = 0; i < UVC_URBS; ++i) {
1414                if (stream->urb_buffer[i]) {
1415#ifndef CONFIG_DMA_NONCOHERENT
1416                        usb_free_coherent(stream->dev->udev, stream->urb_size,
1417                                stream->urb_buffer[i], stream->urb_dma[i]);
1418#else
1419                        kfree(stream->urb_buffer[i]);
1420#endif
1421                        stream->urb_buffer[i] = NULL;
1422                }
1423        }
1424
1425        stream->urb_size = 0;
1426}
1427
1428/*
1429 * Allocate transfer buffers. This function can be called with buffers
1430 * already allocated when resuming from suspend, in which case it will
1431 * return without touching the buffers.
1432 *
1433 * Limit the buffer size to UVC_MAX_PACKETS bulk/isochronous packets. If the
1434 * system is too low on memory try successively smaller numbers of packets
1435 * until allocation succeeds.
1436 *
1437 * Return the number of allocated packets on success or 0 when out of memory.
1438 */
1439static int uvc_alloc_urb_buffers(struct uvc_streaming *stream,
1440        unsigned int size, unsigned int psize, gfp_t gfp_flags)
1441{
1442        unsigned int npackets;
1443        unsigned int i;
1444
1445        /* Buffers are already allocated, bail out. */
1446        if (stream->urb_size)
1447                return stream->urb_size / psize;
1448
1449        /* Compute the number of packets. Bulk endpoints might transfer UVC
1450         * payloads across multiple URBs.
1451         */
1452        npackets = DIV_ROUND_UP(size, psize);
1453        if (npackets > UVC_MAX_PACKETS)
1454                npackets = UVC_MAX_PACKETS;
1455
1456        /* Retry allocations until one succeed. */
1457        for (; npackets > 1; npackets /= 2) {
1458                for (i = 0; i < UVC_URBS; ++i) {
1459                        stream->urb_size = psize * npackets;
1460#ifndef CONFIG_DMA_NONCOHERENT
1461                        stream->urb_buffer[i] = usb_alloc_coherent(
1462                                stream->dev->udev, stream->urb_size,
1463                                gfp_flags | __GFP_NOWARN, &stream->urb_dma[i]);
1464#else
1465                        stream->urb_buffer[i] =
1466                            kmalloc(stream->urb_size, gfp_flags | __GFP_NOWARN);
1467#endif
1468                        if (!stream->urb_buffer[i]) {
1469                                uvc_free_urb_buffers(stream);
1470                                break;
1471                        }
1472                }
1473
1474                if (i == UVC_URBS) {
1475                        uvc_trace(UVC_TRACE_VIDEO, "Allocated %u URB buffers "
1476                                "of %ux%u bytes each.\n", UVC_URBS, npackets,
1477                                psize);
1478                        return npackets;
1479                }
1480        }
1481
1482        uvc_trace(UVC_TRACE_VIDEO, "Failed to allocate URB buffers (%u bytes "
1483                "per packet).\n", psize);
1484        return 0;
1485}
1486
1487/*
1488 * Uninitialize isochronous/bulk URBs and free transfer buffers.
1489 */
1490static void uvc_uninit_video(struct uvc_streaming *stream, int free_buffers)
1491{
1492        struct urb *urb;
1493        unsigned int i;
1494
1495        uvc_video_stats_stop(stream);
1496
1497        for (i = 0; i < UVC_URBS; ++i) {
1498                urb = stream->urb[i];
1499                if (urb == NULL)
1500                        continue;
1501
1502                usb_kill_urb(urb);
1503                usb_free_urb(urb);
1504                stream->urb[i] = NULL;
1505        }
1506
1507        if (free_buffers)
1508                uvc_free_urb_buffers(stream);
1509}
1510
1511/*
1512 * Compute the maximum number of bytes per interval for an endpoint.
1513 */
1514static unsigned int uvc_endpoint_max_bpi(struct usb_device *dev,
1515                                         struct usb_host_endpoint *ep)
1516{
1517        u16 psize;
1518        u16 mult;
1519
1520        switch (dev->speed) {
1521        case USB_SPEED_SUPER:
1522        case USB_SPEED_SUPER_PLUS:
1523                return le16_to_cpu(ep->ss_ep_comp.wBytesPerInterval);
1524        case USB_SPEED_HIGH:
1525                psize = usb_endpoint_maxp(&ep->desc);
1526                mult = usb_endpoint_maxp_mult(&ep->desc);
1527                return psize * mult;
1528        case USB_SPEED_WIRELESS:
1529                psize = usb_endpoint_maxp(&ep->desc);
1530                return psize;
1531        default:
1532                psize = usb_endpoint_maxp(&ep->desc);
1533                return psize;
1534        }
1535}
1536
1537/*
1538 * Initialize isochronous URBs and allocate transfer buffers. The packet size
1539 * is given by the endpoint.
1540 */
1541static int uvc_init_video_isoc(struct uvc_streaming *stream,
1542        struct usb_host_endpoint *ep, gfp_t gfp_flags)
1543{
1544        struct urb *urb;
1545        unsigned int npackets, i, j;
1546        u16 psize;
1547        u32 size;
1548
1549        psize = uvc_endpoint_max_bpi(stream->dev->udev, ep);
1550        size = stream->ctrl.dwMaxVideoFrameSize;
1551
1552        npackets = uvc_alloc_urb_buffers(stream, size, psize, gfp_flags);
1553        if (npackets == 0)
1554                return -ENOMEM;
1555
1556        size = npackets * psize;
1557
1558        for (i = 0; i < UVC_URBS; ++i) {
1559                urb = usb_alloc_urb(npackets, gfp_flags);
1560                if (urb == NULL) {
1561                        uvc_uninit_video(stream, 1);
1562                        return -ENOMEM;
1563                }
1564
1565                urb->dev = stream->dev->udev;
1566                urb->context = stream;
1567                urb->pipe = usb_rcvisocpipe(stream->dev->udev,
1568                                ep->desc.bEndpointAddress);
1569#ifndef CONFIG_DMA_NONCOHERENT
1570                urb->transfer_flags = URB_ISO_ASAP | URB_NO_TRANSFER_DMA_MAP;
1571                urb->transfer_dma = stream->urb_dma[i];
1572#else
1573                urb->transfer_flags = URB_ISO_ASAP;
1574#endif
1575                urb->interval = ep->desc.bInterval;
1576                urb->transfer_buffer = stream->urb_buffer[i];
1577                urb->complete = uvc_video_complete;
1578                urb->number_of_packets = npackets;
1579                urb->transfer_buffer_length = size;
1580
1581                for (j = 0; j < npackets; ++j) {
1582                        urb->iso_frame_desc[j].offset = j * psize;
1583                        urb->iso_frame_desc[j].length = psize;
1584                }
1585
1586                stream->urb[i] = urb;
1587        }
1588
1589        return 0;
1590}
1591
1592/*
1593 * Initialize bulk URBs and allocate transfer buffers. The packet size is
1594 * given by the endpoint.
1595 */
1596static int uvc_init_video_bulk(struct uvc_streaming *stream,
1597        struct usb_host_endpoint *ep, gfp_t gfp_flags)
1598{
1599        struct urb *urb;
1600        unsigned int npackets, pipe, i;
1601        u16 psize;
1602        u32 size;
1603
1604        psize = usb_endpoint_maxp(&ep->desc);
1605        size = stream->ctrl.dwMaxPayloadTransferSize;
1606        stream->bulk.max_payload_size = size;
1607
1608        npackets = uvc_alloc_urb_buffers(stream, size, psize, gfp_flags);
1609        if (npackets == 0)
1610                return -ENOMEM;
1611
1612        size = npackets * psize;
1613
1614        if (usb_endpoint_dir_in(&ep->desc))
1615                pipe = usb_rcvbulkpipe(stream->dev->udev,
1616                                       ep->desc.bEndpointAddress);
1617        else
1618                pipe = usb_sndbulkpipe(stream->dev->udev,
1619                                       ep->desc.bEndpointAddress);
1620
1621        if (stream->type == V4L2_BUF_TYPE_VIDEO_OUTPUT)
1622                size = 0;
1623
1624        for (i = 0; i < UVC_URBS; ++i) {
1625                urb = usb_alloc_urb(0, gfp_flags);
1626                if (urb == NULL) {
1627                        uvc_uninit_video(stream, 1);
1628                        return -ENOMEM;
1629                }
1630
1631                usb_fill_bulk_urb(urb, stream->dev->udev, pipe,
1632                        stream->urb_buffer[i], size, uvc_video_complete,
1633                        stream);
1634#ifndef CONFIG_DMA_NONCOHERENT
1635                urb->transfer_flags = URB_NO_TRANSFER_DMA_MAP;
1636                urb->transfer_dma = stream->urb_dma[i];
1637#endif
1638
1639                stream->urb[i] = urb;
1640        }
1641
1642        return 0;
1643}
1644
1645/*
1646 * Initialize isochronous/bulk URBs and allocate transfer buffers.
1647 */
1648static int uvc_init_video(struct uvc_streaming *stream, gfp_t gfp_flags)
1649{
1650        struct usb_interface *intf = stream->intf;
1651        struct usb_host_endpoint *ep;
1652        unsigned int i;
1653        int ret;
1654
1655        stream->sequence = -1;
1656        stream->last_fid = -1;
1657        stream->bulk.header_size = 0;
1658        stream->bulk.skip_payload = 0;
1659        stream->bulk.payload_size = 0;
1660
1661        uvc_video_stats_start(stream);
1662
1663        if (intf->num_altsetting > 1) {
1664                struct usb_host_endpoint *best_ep = NULL;
1665                unsigned int best_psize = UINT_MAX;
1666                unsigned int bandwidth;
1667                unsigned int uninitialized_var(altsetting);
1668                int intfnum = stream->intfnum;
1669
1670                /* Isochronous endpoint, select the alternate setting. */
1671                bandwidth = stream->ctrl.dwMaxPayloadTransferSize;
1672
1673                if (bandwidth == 0) {
1674                        uvc_trace(UVC_TRACE_VIDEO, "Device requested null "
1675                                "bandwidth, defaulting to lowest.\n");
1676                        bandwidth = 1;
1677                } else {
1678                        uvc_trace(UVC_TRACE_VIDEO, "Device requested %u "
1679                                "B/frame bandwidth.\n", bandwidth);
1680                }
1681
1682                for (i = 0; i < intf->num_altsetting; ++i) {
1683                        struct usb_host_interface *alts;
1684                        unsigned int psize;
1685
1686                        alts = &intf->altsetting[i];
1687                        ep = uvc_find_endpoint(alts,
1688                                stream->header.bEndpointAddress);
1689                        if (ep == NULL)
1690                                continue;
1691
1692                        /* Check if the bandwidth is high enough. */
1693                        psize = uvc_endpoint_max_bpi(stream->dev->udev, ep);
1694                        if (psize >= bandwidth && psize <= best_psize) {
1695                                altsetting = alts->desc.bAlternateSetting;
1696                                best_psize = psize;
1697                                best_ep = ep;
1698                        }
1699                }
1700
1701                if (best_ep == NULL) {
1702                        uvc_trace(UVC_TRACE_VIDEO, "No fast enough alt setting "
1703                                "for requested bandwidth.\n");
1704                        return -EIO;
1705                }
1706
1707                uvc_trace(UVC_TRACE_VIDEO, "Selecting alternate setting %u "
1708                        "(%u B/frame bandwidth).\n", altsetting, best_psize);
1709
1710                ret = usb_set_interface(stream->dev->udev, intfnum, altsetting);
1711                if (ret < 0)
1712                        return ret;
1713
1714                ret = uvc_init_video_isoc(stream, best_ep, gfp_flags);
1715        } else {
1716                /* Bulk endpoint, proceed to URB initialization. */
1717                ep = uvc_find_endpoint(&intf->altsetting[0],
1718                                stream->header.bEndpointAddress);
1719                if (ep == NULL)
1720                        return -EIO;
1721
1722                ret = uvc_init_video_bulk(stream, ep, gfp_flags);
1723        }
1724
1725        if (ret < 0)
1726                return ret;
1727
1728        /* Submit the URBs. */
1729        for (i = 0; i < UVC_URBS; ++i) {
1730                ret = usb_submit_urb(stream->urb[i], gfp_flags);
1731                if (ret < 0) {
1732                        uvc_printk(KERN_ERR, "Failed to submit URB %u "
1733                                        "(%d).\n", i, ret);
1734                        uvc_uninit_video(stream, 1);
1735                        return ret;
1736                }
1737        }
1738
1739        return 0;
1740}
1741
1742/* --------------------------------------------------------------------------
1743 * Suspend/resume
1744 */
1745
1746/*
1747 * Stop streaming without disabling the video queue.
1748 *
1749 * To let userspace applications resume without trouble, we must not touch the
1750 * video buffers in any way. We mark the device as frozen to make sure the URB
1751 * completion handler won't try to cancel the queue when we kill the URBs.
1752 */
1753int uvc_video_suspend(struct uvc_streaming *stream)
1754{
1755        if (!uvc_queue_streaming(&stream->queue))
1756                return 0;
1757
1758        stream->frozen = 1;
1759        uvc_uninit_video(stream, 0);
1760        usb_set_interface(stream->dev->udev, stream->intfnum, 0);
1761        return 0;
1762}
1763
1764/*
1765 * Reconfigure the video interface and restart streaming if it was enabled
1766 * before suspend.
1767 *
1768 * If an error occurs, disable the video queue. This will wake all pending
1769 * buffers, making sure userspace applications are notified of the problem
1770 * instead of waiting forever.
1771 */
1772int uvc_video_resume(struct uvc_streaming *stream, int reset)
1773{
1774        int ret;
1775
1776        /* If the bus has been reset on resume, set the alternate setting to 0.
1777         * This should be the default value, but some devices crash or otherwise
1778         * misbehave if they don't receive a SET_INTERFACE request before any
1779         * other video control request.
1780         */
1781        if (reset)
1782                usb_set_interface(stream->dev->udev, stream->intfnum, 0);
1783
1784        stream->frozen = 0;
1785
1786        uvc_video_clock_reset(stream);
1787
1788        ret = uvc_commit_video(stream, &stream->ctrl);
1789        if (ret < 0) {
1790                uvc_queue_enable(&stream->queue, 0);
1791                return ret;
1792        }
1793
1794        if (!uvc_queue_streaming(&stream->queue))
1795                return 0;
1796
1797        ret = uvc_init_video(stream, GFP_NOIO);
1798        if (ret < 0)
1799                uvc_queue_enable(&stream->queue, 0);
1800
1801        return ret;
1802}
1803
1804/* ------------------------------------------------------------------------
1805 * Video device
1806 */
1807
1808/*
1809 * Initialize the UVC video device by switching to alternate setting 0 and
1810 * retrieve the default format.
1811 *
1812 * Some cameras (namely the Fuji Finepix) set the format and frame
1813 * indexes to zero. The UVC standard doesn't clearly make this a spec
1814 * violation, so try to silently fix the values if possible.
1815 *
1816 * This function is called before registering the device with V4L.
1817 */
1818int uvc_video_init(struct uvc_streaming *stream)
1819{
1820        struct uvc_streaming_control *probe = &stream->ctrl;
1821        struct uvc_format *format = NULL;
1822        struct uvc_frame *frame = NULL;
1823        unsigned int i;
1824        int ret;
1825
1826        if (stream->nformats == 0) {
1827                uvc_printk(KERN_INFO, "No supported video formats found.\n");
1828                return -EINVAL;
1829        }
1830
1831        atomic_set(&stream->active, 0);
1832
1833        /* Initialize the video buffers queue. */
1834        ret = uvc_queue_init(&stream->queue, stream->type, !uvc_no_drop_param);
1835        if (ret)
1836                return ret;
1837
1838        /* Alternate setting 0 should be the default, yet the XBox Live Vision
1839         * Cam (and possibly other devices) crash or otherwise misbehave if
1840         * they don't receive a SET_INTERFACE request before any other video
1841         * control request.
1842         */
1843        usb_set_interface(stream->dev->udev, stream->intfnum, 0);
1844
1845        /* Set the streaming probe control with default streaming parameters
1846         * retrieved from the device. Webcams that don't suport GET_DEF
1847         * requests on the probe control will just keep their current streaming
1848         * parameters.
1849         */
1850        if (uvc_get_video_ctrl(stream, probe, 1, UVC_GET_DEF) == 0)
1851                uvc_set_video_ctrl(stream, probe, 1);
1852
1853        /* Initialize the streaming parameters with the probe control current
1854         * value. This makes sure SET_CUR requests on the streaming commit
1855         * control will always use values retrieved from a successful GET_CUR
1856         * request on the probe control, as required by the UVC specification.
1857         */
1858        ret = uvc_get_video_ctrl(stream, probe, 1, UVC_GET_CUR);
1859        if (ret < 0)
1860                return ret;
1861
1862        /* Check if the default format descriptor exists. Use the first
1863         * available format otherwise.
1864         */
1865        for (i = stream->nformats; i > 0; --i) {
1866                format = &stream->format[i-1];
1867                if (format->index == probe->bFormatIndex)
1868                        break;
1869        }
1870
1871        if (format->nframes == 0) {
1872                uvc_printk(KERN_INFO, "No frame descriptor found for the "
1873                        "default format.\n");
1874                return -EINVAL;
1875        }
1876
1877        /* Zero bFrameIndex might be correct. Stream-based formats (including
1878         * MPEG-2 TS and DV) do not support frames but have a dummy frame
1879         * descriptor with bFrameIndex set to zero. If the default frame
1880         * descriptor is not found, use the first available frame.
1881         */
1882        for (i = format->nframes; i > 0; --i) {
1883                frame = &format->frame[i-1];
1884                if (frame->bFrameIndex == probe->bFrameIndex)
1885                        break;
1886        }
1887
1888        probe->bFormatIndex = format->index;
1889        probe->bFrameIndex = frame->bFrameIndex;
1890
1891        stream->def_format = format;
1892        stream->cur_format = format;
1893        stream->cur_frame = frame;
1894
1895        /* Select the video decoding function */
1896        if (stream->type == V4L2_BUF_TYPE_VIDEO_CAPTURE) {
1897                if (stream->dev->quirks & UVC_QUIRK_BUILTIN_ISIGHT)
1898                        stream->decode = uvc_video_decode_isight;
1899                else if (stream->intf->num_altsetting > 1)
1900                        stream->decode = uvc_video_decode_isoc;
1901                else
1902                        stream->decode = uvc_video_decode_bulk;
1903        } else {
1904                if (stream->intf->num_altsetting == 1)
1905                        stream->decode = uvc_video_encode_bulk;
1906                else {
1907                        uvc_printk(KERN_INFO, "Isochronous endpoints are not "
1908                                "supported for video output devices.\n");
1909                        return -EINVAL;
1910                }
1911        }
1912
1913        return 0;
1914}
1915
1916/*
1917 * Enable or disable the video stream.
1918 */
1919int uvc_video_enable(struct uvc_streaming *stream, int enable)
1920{
1921        int ret;
1922
1923        if (!enable) {
1924                uvc_uninit_video(stream, 1);
1925                if (stream->intf->num_altsetting > 1) {
1926                        usb_set_interface(stream->dev->udev,
1927                                          stream->intfnum, 0);
1928                } else {
1929                        /* UVC doesn't specify how to inform a bulk-based device
1930                         * when the video stream is stopped. Windows sends a
1931                         * CLEAR_FEATURE(HALT) request to the video streaming
1932                         * bulk endpoint, mimic the same behaviour.
1933                         */
1934                        unsigned int epnum = stream->header.bEndpointAddress
1935                                           & USB_ENDPOINT_NUMBER_MASK;
1936                        unsigned int dir = stream->header.bEndpointAddress
1937                                         & USB_ENDPOINT_DIR_MASK;
1938                        unsigned int pipe;
1939
1940                        pipe = usb_sndbulkpipe(stream->dev->udev, epnum) | dir;
1941                        usb_clear_halt(stream->dev->udev, pipe);
1942                }
1943
1944                uvc_queue_enable(&stream->queue, 0);
1945                uvc_video_clock_cleanup(stream);
1946                return 0;
1947        }
1948
1949        ret = uvc_video_clock_init(stream);
1950        if (ret < 0)
1951                return ret;
1952
1953        ret = uvc_queue_enable(&stream->queue, 1);
1954        if (ret < 0)
1955                goto error_queue;
1956
1957        /* Commit the streaming parameters. */
1958        ret = uvc_commit_video(stream, &stream->ctrl);
1959        if (ret < 0)
1960                goto error_commit;
1961
1962        ret = uvc_init_video(stream, GFP_KERNEL);
1963        if (ret < 0)
1964                goto error_video;
1965
1966        return 0;
1967
1968error_video:
1969        usb_set_interface(stream->dev->udev, stream->intfnum, 0);
1970error_commit:
1971        uvc_queue_enable(&stream->queue, 0);
1972error_queue:
1973        uvc_video_clock_cleanup(stream);
1974
1975        return ret;
1976}
1977