linux/drivers/media/usb/gspca/gspca.c
<<
>>
Prefs
   1/*
   2 * Main USB camera driver
   3 *
   4 * Copyright (C) 2008-2011 Jean-François Moine <http://moinejf.free.fr>
   5 *
   6 * Camera button input handling by Márton Németh
   7 * Copyright (C) 2009-2010 Márton Németh <nm127@freemail.hu>
   8 *
   9 * This program is free software; you can redistribute it and/or modify it
  10 * under the terms of the GNU General Public License as published by the
  11 * Free Software Foundation; either version 2 of the License, or (at your
  12 * option) any later version.
  13 *
  14 * This program is distributed in the hope that it will be useful, but
  15 * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
  16 * or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  17 * for more details.
  18 *
  19 * You should have received a copy of the GNU General Public License
  20 * along with this program; if not, write to the Free Software Foundation,
  21 * Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
  22 */
  23
  24#define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
  25
  26#define GSPCA_VERSION   "2.14.0"
  27
  28#include <linux/init.h>
  29#include <linux/fs.h>
  30#include <linux/vmalloc.h>
  31#include <linux/sched.h>
  32#include <linux/slab.h>
  33#include <linux/mm.h>
  34#include <linux/string.h>
  35#include <linux/pagemap.h>
  36#include <linux/io.h>
  37#include <asm/page.h>
  38#include <linux/uaccess.h>
  39#include <linux/ktime.h>
  40#include <media/v4l2-ioctl.h>
  41#include <media/v4l2-ctrls.h>
  42#include <media/v4l2-fh.h>
  43#include <media/v4l2-event.h>
  44
  45#include "gspca.h"
  46
  47#if IS_ENABLED(CONFIG_INPUT)
  48#include <linux/input.h>
  49#include <linux/usb/input.h>
  50#endif
  51
  52/* global values */
  53#define DEF_NURBS 3             /* default number of URBs */
  54#if DEF_NURBS > MAX_NURBS
  55#error "DEF_NURBS too big"
  56#endif
  57
  58MODULE_AUTHOR("Jean-François Moine <http://moinejf.free.fr>");
  59MODULE_DESCRIPTION("GSPCA USB Camera Driver");
  60MODULE_LICENSE("GPL");
  61MODULE_VERSION(GSPCA_VERSION);
  62
  63int gspca_debug;
  64EXPORT_SYMBOL(gspca_debug);
  65
  66static void PDEBUG_MODE(struct gspca_dev *gspca_dev, int debug, char *txt,
  67                        __u32 pixfmt, int w, int h)
  68{
  69        if ((pixfmt >> 24) >= '0' && (pixfmt >> 24) <= 'z') {
  70                PDEBUG(debug, "%s %c%c%c%c %dx%d",
  71                        txt,
  72                        pixfmt & 0xff,
  73                        (pixfmt >> 8) & 0xff,
  74                        (pixfmt >> 16) & 0xff,
  75                        pixfmt >> 24,
  76                        w, h);
  77        } else {
  78                PDEBUG(debug, "%s 0x%08x %dx%d",
  79                        txt,
  80                        pixfmt,
  81                        w, h);
  82        }
  83}
  84
  85/* specific memory types - !! should be different from V4L2_MEMORY_xxx */
  86#define GSPCA_MEMORY_NO 0       /* V4L2_MEMORY_xxx starts from 1 */
  87#define GSPCA_MEMORY_READ 7
  88
  89#define BUF_ALL_FLAGS (V4L2_BUF_FLAG_QUEUED | V4L2_BUF_FLAG_DONE)
  90
  91/*
  92 * VMA operations.
  93 */
  94static void gspca_vm_open(struct vm_area_struct *vma)
  95{
  96        struct gspca_frame *frame = vma->vm_private_data;
  97
  98        frame->vma_use_count++;
  99        frame->v4l2_buf.flags |= V4L2_BUF_FLAG_MAPPED;
 100}
 101
 102static void gspca_vm_close(struct vm_area_struct *vma)
 103{
 104        struct gspca_frame *frame = vma->vm_private_data;
 105
 106        if (--frame->vma_use_count <= 0)
 107                frame->v4l2_buf.flags &= ~V4L2_BUF_FLAG_MAPPED;
 108}
 109
 110static const struct vm_operations_struct gspca_vm_ops = {
 111        .open           = gspca_vm_open,
 112        .close          = gspca_vm_close,
 113};
 114
 115/*
 116 * Input and interrupt endpoint handling functions
 117 */
 118#if IS_ENABLED(CONFIG_INPUT)
 119static void int_irq(struct urb *urb)
 120{
 121        struct gspca_dev *gspca_dev = (struct gspca_dev *) urb->context;
 122        int ret;
 123
 124        ret = urb->status;
 125        switch (ret) {
 126        case 0:
 127                if (gspca_dev->sd_desc->int_pkt_scan(gspca_dev,
 128                    urb->transfer_buffer, urb->actual_length) < 0) {
 129                        PERR("Unknown packet received");
 130                }
 131                break;
 132
 133        case -ENOENT:
 134        case -ECONNRESET:
 135        case -ENODEV:
 136        case -ESHUTDOWN:
 137                /* Stop is requested either by software or hardware is gone,
 138                 * keep the ret value non-zero and don't resubmit later.
 139                 */
 140                break;
 141
 142        default:
 143                PERR("URB error %i, resubmitting", urb->status);
 144                urb->status = 0;
 145                ret = 0;
 146        }
 147
 148        if (ret == 0) {
 149                ret = usb_submit_urb(urb, GFP_ATOMIC);
 150                if (ret < 0)
 151                        pr_err("Resubmit URB failed with error %i\n", ret);
 152        }
 153}
 154
 155static int gspca_input_connect(struct gspca_dev *dev)
 156{
 157        struct input_dev *input_dev;
 158        int err = 0;
 159
 160        dev->input_dev = NULL;
 161        if (dev->sd_desc->int_pkt_scan || dev->sd_desc->other_input)  {
 162                input_dev = input_allocate_device();
 163                if (!input_dev)
 164                        return -ENOMEM;
 165
 166                usb_make_path(dev->dev, dev->phys, sizeof(dev->phys));
 167                strlcat(dev->phys, "/input0", sizeof(dev->phys));
 168
 169                input_dev->name = dev->sd_desc->name;
 170                input_dev->phys = dev->phys;
 171
 172                usb_to_input_id(dev->dev, &input_dev->id);
 173
 174                input_dev->evbit[0] = BIT_MASK(EV_KEY);
 175                input_dev->keybit[BIT_WORD(KEY_CAMERA)] = BIT_MASK(KEY_CAMERA);
 176                input_dev->dev.parent = &dev->dev->dev;
 177
 178                err = input_register_device(input_dev);
 179                if (err) {
 180                        pr_err("Input device registration failed with error %i\n",
 181                               err);
 182                        input_dev->dev.parent = NULL;
 183                        input_free_device(input_dev);
 184                } else {
 185                        dev->input_dev = input_dev;
 186                }
 187        }
 188
 189        return err;
 190}
 191
 192static int alloc_and_submit_int_urb(struct gspca_dev *gspca_dev,
 193                          struct usb_endpoint_descriptor *ep)
 194{
 195        unsigned int buffer_len;
 196        int interval;
 197        struct urb *urb;
 198        struct usb_device *dev;
 199        void *buffer = NULL;
 200        int ret = -EINVAL;
 201
 202        buffer_len = le16_to_cpu(ep->wMaxPacketSize);
 203        interval = ep->bInterval;
 204        PDEBUG(D_CONF, "found int in endpoint: 0x%x, "
 205                "buffer_len=%u, interval=%u",
 206                ep->bEndpointAddress, buffer_len, interval);
 207
 208        dev = gspca_dev->dev;
 209
 210        urb = usb_alloc_urb(0, GFP_KERNEL);
 211        if (!urb) {
 212                ret = -ENOMEM;
 213                goto error;
 214        }
 215
 216        buffer = usb_alloc_coherent(dev, buffer_len,
 217                                GFP_KERNEL, &urb->transfer_dma);
 218        if (!buffer) {
 219                ret = -ENOMEM;
 220                goto error_buffer;
 221        }
 222        usb_fill_int_urb(urb, dev,
 223                usb_rcvintpipe(dev, ep->bEndpointAddress),
 224                buffer, buffer_len,
 225                int_irq, (void *)gspca_dev, interval);
 226        urb->transfer_flags |= URB_NO_TRANSFER_DMA_MAP;
 227        ret = usb_submit_urb(urb, GFP_KERNEL);
 228        if (ret < 0) {
 229                PERR("submit int URB failed with error %i", ret);
 230                goto error_submit;
 231        }
 232        gspca_dev->int_urb = urb;
 233        return ret;
 234
 235error_submit:
 236        usb_free_coherent(dev,
 237                          urb->transfer_buffer_length,
 238                          urb->transfer_buffer,
 239                          urb->transfer_dma);
 240error_buffer:
 241        usb_free_urb(urb);
 242error:
 243        return ret;
 244}
 245
 246static void gspca_input_create_urb(struct gspca_dev *gspca_dev)
 247{
 248        struct usb_interface *intf;
 249        struct usb_host_interface *intf_desc;
 250        struct usb_endpoint_descriptor *ep;
 251        int i;
 252
 253        if (gspca_dev->sd_desc->int_pkt_scan)  {
 254                intf = usb_ifnum_to_if(gspca_dev->dev, gspca_dev->iface);
 255                intf_desc = intf->cur_altsetting;
 256                for (i = 0; i < intf_desc->desc.bNumEndpoints; i++) {
 257                        ep = &intf_desc->endpoint[i].desc;
 258                        if (usb_endpoint_dir_in(ep) &&
 259                            usb_endpoint_xfer_int(ep)) {
 260
 261                                alloc_and_submit_int_urb(gspca_dev, ep);
 262                                break;
 263                        }
 264                }
 265        }
 266}
 267
 268static void gspca_input_destroy_urb(struct gspca_dev *gspca_dev)
 269{
 270        struct urb *urb;
 271
 272        urb = gspca_dev->int_urb;
 273        if (urb) {
 274                gspca_dev->int_urb = NULL;
 275                usb_kill_urb(urb);
 276                usb_free_coherent(gspca_dev->dev,
 277                                  urb->transfer_buffer_length,
 278                                  urb->transfer_buffer,
 279                                  urb->transfer_dma);
 280                usb_free_urb(urb);
 281        }
 282}
 283#else
 284static inline void gspca_input_destroy_urb(struct gspca_dev *gspca_dev)
 285{
 286}
 287
 288static inline void gspca_input_create_urb(struct gspca_dev *gspca_dev)
 289{
 290}
 291
 292static inline int gspca_input_connect(struct gspca_dev *dev)
 293{
 294        return 0;
 295}
 296#endif
 297
 298/*
 299 * fill a video frame from an URB and resubmit
 300 */
 301static void fill_frame(struct gspca_dev *gspca_dev,
 302                        struct urb *urb)
 303{
 304        u8 *data;               /* address of data in the iso message */
 305        int i, len, st;
 306        cam_pkt_op pkt_scan;
 307
 308        if (urb->status != 0) {
 309                if (urb->status == -ESHUTDOWN)
 310                        return;         /* disconnection */
 311#ifdef CONFIG_PM
 312                if (gspca_dev->frozen)
 313                        return;
 314#endif
 315                PERR("urb status: %d", urb->status);
 316                urb->status = 0;
 317                goto resubmit;
 318        }
 319        pkt_scan = gspca_dev->sd_desc->pkt_scan;
 320        for (i = 0; i < urb->number_of_packets; i++) {
 321                len = urb->iso_frame_desc[i].actual_length;
 322
 323                /* check the packet status and length */
 324                st = urb->iso_frame_desc[i].status;
 325                if (st) {
 326                        pr_err("ISOC data error: [%d] len=%d, status=%d\n",
 327                               i, len, st);
 328                        gspca_dev->last_packet_type = DISCARD_PACKET;
 329                        continue;
 330                }
 331                if (len == 0) {
 332                        if (gspca_dev->empty_packet == 0)
 333                                gspca_dev->empty_packet = 1;
 334                        continue;
 335                }
 336
 337                /* let the packet be analyzed by the subdriver */
 338                PDEBUG(D_PACK, "packet [%d] o:%d l:%d",
 339                        i, urb->iso_frame_desc[i].offset, len);
 340                data = (u8 *) urb->transfer_buffer
 341                                        + urb->iso_frame_desc[i].offset;
 342                pkt_scan(gspca_dev, data, len);
 343        }
 344
 345resubmit:
 346        /* resubmit the URB */
 347        st = usb_submit_urb(urb, GFP_ATOMIC);
 348        if (st < 0)
 349                pr_err("usb_submit_urb() ret %d\n", st);
 350}
 351
 352/*
 353 * ISOC message interrupt from the USB device
 354 *
 355 * Analyse each packet and call the subdriver for copy to the frame buffer.
 356 */
 357static void isoc_irq(struct urb *urb)
 358{
 359        struct gspca_dev *gspca_dev = (struct gspca_dev *) urb->context;
 360
 361        PDEBUG(D_PACK, "isoc irq");
 362        if (!gspca_dev->streaming)
 363                return;
 364        fill_frame(gspca_dev, urb);
 365}
 366
 367/*
 368 * bulk message interrupt from the USB device
 369 */
 370static void bulk_irq(struct urb *urb)
 371{
 372        struct gspca_dev *gspca_dev = (struct gspca_dev *) urb->context;
 373        int st;
 374
 375        PDEBUG(D_PACK, "bulk irq");
 376        if (!gspca_dev->streaming)
 377                return;
 378        switch (urb->status) {
 379        case 0:
 380                break;
 381        case -ESHUTDOWN:
 382                return;         /* disconnection */
 383        default:
 384#ifdef CONFIG_PM
 385                if (gspca_dev->frozen)
 386                        return;
 387#endif
 388                PERR("urb status: %d", urb->status);
 389                urb->status = 0;
 390                goto resubmit;
 391        }
 392
 393        PDEBUG(D_PACK, "packet l:%d", urb->actual_length);
 394        gspca_dev->sd_desc->pkt_scan(gspca_dev,
 395                                urb->transfer_buffer,
 396                                urb->actual_length);
 397
 398resubmit:
 399        /* resubmit the URB */
 400        if (gspca_dev->cam.bulk_nurbs != 0) {
 401                st = usb_submit_urb(urb, GFP_ATOMIC);
 402                if (st < 0)
 403                        pr_err("usb_submit_urb() ret %d\n", st);
 404        }
 405}
 406
 407/*
 408 * add data to the current frame
 409 *
 410 * This function is called by the subdrivers at interrupt level.
 411 *
 412 * To build a frame, these ones must add
 413 *      - one FIRST_PACKET
 414 *      - 0 or many INTER_PACKETs
 415 *      - one LAST_PACKET
 416 * DISCARD_PACKET invalidates the whole frame.
 417 */
 418void gspca_frame_add(struct gspca_dev *gspca_dev,
 419                        enum gspca_packet_type packet_type,
 420                        const u8 *data,
 421                        int len)
 422{
 423        struct gspca_frame *frame;
 424        int i, j;
 425
 426        PDEBUG(D_PACK, "add t:%d l:%d", packet_type, len);
 427
 428        if (packet_type == FIRST_PACKET) {
 429                i = atomic_read(&gspca_dev->fr_i);
 430
 431                /* if there are no queued buffer, discard the whole frame */
 432                if (i == atomic_read(&gspca_dev->fr_q)) {
 433                        gspca_dev->last_packet_type = DISCARD_PACKET;
 434                        gspca_dev->sequence++;
 435                        return;
 436                }
 437                j = gspca_dev->fr_queue[i];
 438                frame = &gspca_dev->frame[j];
 439                v4l2_get_timestamp(&frame->v4l2_buf.timestamp);
 440                frame->v4l2_buf.sequence = gspca_dev->sequence++;
 441                gspca_dev->image = frame->data;
 442                gspca_dev->image_len = 0;
 443        } else {
 444                switch (gspca_dev->last_packet_type) {
 445                case DISCARD_PACKET:
 446                        if (packet_type == LAST_PACKET) {
 447                                gspca_dev->last_packet_type = packet_type;
 448                                gspca_dev->image = NULL;
 449                                gspca_dev->image_len = 0;
 450                        }
 451                        return;
 452                case LAST_PACKET:
 453                        return;
 454                }
 455        }
 456
 457        /* append the packet to the frame buffer */
 458        if (len > 0) {
 459                if (gspca_dev->image_len + len > gspca_dev->frsz) {
 460                        PERR("frame overflow %d > %d",
 461                                gspca_dev->image_len + len,
 462                                gspca_dev->frsz);
 463                        packet_type = DISCARD_PACKET;
 464                } else {
 465/* !! image is NULL only when last pkt is LAST or DISCARD
 466                        if (gspca_dev->image == NULL) {
 467                                pr_err("gspca_frame_add() image == NULL\n");
 468                                return;
 469                        }
 470 */
 471                        memcpy(gspca_dev->image + gspca_dev->image_len,
 472                                data, len);
 473                        gspca_dev->image_len += len;
 474                }
 475        }
 476        gspca_dev->last_packet_type = packet_type;
 477
 478        /* if last packet, invalidate packet concatenation until
 479         * next first packet, wake up the application and advance
 480         * in the queue */
 481        if (packet_type == LAST_PACKET) {
 482                i = atomic_read(&gspca_dev->fr_i);
 483                j = gspca_dev->fr_queue[i];
 484                frame = &gspca_dev->frame[j];
 485                frame->v4l2_buf.bytesused = gspca_dev->image_len;
 486                frame->v4l2_buf.flags = (frame->v4l2_buf.flags
 487                                         | V4L2_BUF_FLAG_DONE)
 488                                        & ~V4L2_BUF_FLAG_QUEUED;
 489                i = (i + 1) % GSPCA_MAX_FRAMES;
 490                atomic_set(&gspca_dev->fr_i, i);
 491                wake_up_interruptible(&gspca_dev->wq);  /* event = new frame */
 492                PDEBUG(D_FRAM, "frame complete len:%d",
 493                        frame->v4l2_buf.bytesused);
 494                gspca_dev->image = NULL;
 495                gspca_dev->image_len = 0;
 496        }
 497}
 498EXPORT_SYMBOL(gspca_frame_add);
 499
 500static int frame_alloc(struct gspca_dev *gspca_dev, struct file *file,
 501                        enum v4l2_memory memory, unsigned int count)
 502{
 503        struct gspca_frame *frame;
 504        unsigned int frsz;
 505        int i;
 506
 507        frsz = gspca_dev->pixfmt.sizeimage;
 508        PDEBUG(D_STREAM, "frame alloc frsz: %d", frsz);
 509        frsz = PAGE_ALIGN(frsz);
 510        if (count >= GSPCA_MAX_FRAMES)
 511                count = GSPCA_MAX_FRAMES - 1;
 512        gspca_dev->frbuf = vmalloc_32(frsz * count);
 513        if (!gspca_dev->frbuf) {
 514                pr_err("frame alloc failed\n");
 515                return -ENOMEM;
 516        }
 517        gspca_dev->capt_file = file;
 518        gspca_dev->memory = memory;
 519        gspca_dev->frsz = frsz;
 520        gspca_dev->nframes = count;
 521        for (i = 0; i < count; i++) {
 522                frame = &gspca_dev->frame[i];
 523                frame->v4l2_buf.index = i;
 524                frame->v4l2_buf.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
 525                frame->v4l2_buf.flags = V4L2_BUF_FLAG_TIMESTAMP_MONOTONIC;
 526                frame->v4l2_buf.field = V4L2_FIELD_NONE;
 527                frame->v4l2_buf.length = frsz;
 528                frame->v4l2_buf.memory = memory;
 529                frame->v4l2_buf.sequence = 0;
 530                frame->data = gspca_dev->frbuf + i * frsz;
 531                frame->v4l2_buf.m.offset = i * frsz;
 532        }
 533        atomic_set(&gspca_dev->fr_q, 0);
 534        atomic_set(&gspca_dev->fr_i, 0);
 535        gspca_dev->fr_o = 0;
 536        return 0;
 537}
 538
 539static void frame_free(struct gspca_dev *gspca_dev)
 540{
 541        int i;
 542
 543        PDEBUG(D_STREAM, "frame free");
 544        if (gspca_dev->frbuf != NULL) {
 545                vfree(gspca_dev->frbuf);
 546                gspca_dev->frbuf = NULL;
 547                for (i = 0; i < gspca_dev->nframes; i++)
 548                        gspca_dev->frame[i].data = NULL;
 549        }
 550        gspca_dev->nframes = 0;
 551        gspca_dev->frsz = 0;
 552        gspca_dev->capt_file = NULL;
 553        gspca_dev->memory = GSPCA_MEMORY_NO;
 554}
 555
 556static void destroy_urbs(struct gspca_dev *gspca_dev)
 557{
 558        struct urb *urb;
 559        unsigned int i;
 560
 561        PDEBUG(D_STREAM, "kill transfer");
 562        for (i = 0; i < MAX_NURBS; i++) {
 563                urb = gspca_dev->urb[i];
 564                if (urb == NULL)
 565                        break;
 566
 567                gspca_dev->urb[i] = NULL;
 568                usb_kill_urb(urb);
 569                usb_free_coherent(gspca_dev->dev,
 570                                  urb->transfer_buffer_length,
 571                                  urb->transfer_buffer,
 572                                  urb->transfer_dma);
 573                usb_free_urb(urb);
 574        }
 575}
 576
 577static int gspca_set_alt0(struct gspca_dev *gspca_dev)
 578{
 579        int ret;
 580
 581        if (gspca_dev->alt == 0)
 582                return 0;
 583        ret = usb_set_interface(gspca_dev->dev, gspca_dev->iface, 0);
 584        if (ret < 0)
 585                pr_err("set alt 0 err %d\n", ret);
 586        return ret;
 587}
 588
 589/* Note: both the queue and the usb locks should be held when calling this */
 590static void gspca_stream_off(struct gspca_dev *gspca_dev)
 591{
 592        gspca_dev->streaming = 0;
 593        gspca_dev->usb_err = 0;
 594        if (gspca_dev->sd_desc->stopN)
 595                gspca_dev->sd_desc->stopN(gspca_dev);
 596        destroy_urbs(gspca_dev);
 597        gspca_input_destroy_urb(gspca_dev);
 598        gspca_set_alt0(gspca_dev);
 599        gspca_input_create_urb(gspca_dev);
 600        if (gspca_dev->sd_desc->stop0)
 601                gspca_dev->sd_desc->stop0(gspca_dev);
 602        PDEBUG(D_STREAM, "stream off OK");
 603}
 604
 605/*
 606 * look for an input transfer endpoint in an alternate setting.
 607 *
 608 * If xfer_ep is invalid, return the first valid ep found, otherwise
 609 * look for exactly the ep with address equal to xfer_ep.
 610 */
 611static struct usb_host_endpoint *alt_xfer(struct usb_host_interface *alt,
 612                                          int xfer, int xfer_ep)
 613{
 614        struct usb_host_endpoint *ep;
 615        int i, attr;
 616
 617        for (i = 0; i < alt->desc.bNumEndpoints; i++) {
 618                ep = &alt->endpoint[i];
 619                attr = ep->desc.bmAttributes & USB_ENDPOINT_XFERTYPE_MASK;
 620                if (attr == xfer
 621                    && ep->desc.wMaxPacketSize != 0
 622                    && usb_endpoint_dir_in(&ep->desc)
 623                    && (xfer_ep < 0 || ep->desc.bEndpointAddress == xfer_ep))
 624                        return ep;
 625        }
 626        return NULL;
 627}
 628
 629/* compute the minimum bandwidth for the current transfer */
 630static u32 which_bandwidth(struct gspca_dev *gspca_dev)
 631{
 632        u32 bandwidth;
 633
 634        /* get the (max) image size */
 635        bandwidth = gspca_dev->pixfmt.sizeimage;
 636
 637        /* if the image is compressed, estimate its mean size */
 638        if (!gspca_dev->cam.needs_full_bandwidth &&
 639            bandwidth < gspca_dev->pixfmt.width *
 640                                gspca_dev->pixfmt.height)
 641                bandwidth = bandwidth * 3 / 8;  /* 0.375 */
 642
 643        /* estimate the frame rate */
 644        if (gspca_dev->sd_desc->get_streamparm) {
 645                struct v4l2_streamparm parm;
 646
 647                gspca_dev->sd_desc->get_streamparm(gspca_dev, &parm);
 648                bandwidth *= parm.parm.capture.timeperframe.denominator;
 649                bandwidth /= parm.parm.capture.timeperframe.numerator;
 650        } else {
 651
 652                /* don't hope more than 15 fps with USB 1.1 and
 653                 * image resolution >= 640x480 */
 654                if (gspca_dev->pixfmt.width >= 640
 655                 && gspca_dev->dev->speed == USB_SPEED_FULL)
 656                        bandwidth *= 15;                /* 15 fps */
 657                else
 658                        bandwidth *= 30;                /* 30 fps */
 659        }
 660
 661        PDEBUG(D_STREAM, "min bandwidth: %d", bandwidth);
 662        return bandwidth;
 663}
 664
 665/* endpoint table */
 666#define MAX_ALT 16
 667struct ep_tb_s {
 668        u32 alt;
 669        u32 bandwidth;
 670};
 671
 672/*
 673 * build the table of the endpoints
 674 * and compute the minimum bandwidth for the image transfer
 675 */
 676static int build_isoc_ep_tb(struct gspca_dev *gspca_dev,
 677                        struct usb_interface *intf,
 678                        struct ep_tb_s *ep_tb)
 679{
 680        struct usb_host_endpoint *ep;
 681        int i, j, nbalt, psize, found;
 682        u32 bandwidth, last_bw;
 683
 684        nbalt = intf->num_altsetting;
 685        if (nbalt > MAX_ALT)
 686                nbalt = MAX_ALT;        /* fixme: should warn */
 687
 688        /* build the endpoint table */
 689        i = 0;
 690        last_bw = 0;
 691        for (;;) {
 692                ep_tb->bandwidth = 2000 * 2000 * 120;
 693                found = 0;
 694                for (j = 0; j < nbalt; j++) {
 695                        ep = alt_xfer(&intf->altsetting[j],
 696                                      USB_ENDPOINT_XFER_ISOC,
 697                                      gspca_dev->xfer_ep);
 698                        if (ep == NULL)
 699                                continue;
 700                        if (ep->desc.bInterval == 0) {
 701                                pr_err("alt %d iso endp with 0 interval\n", j);
 702                                continue;
 703                        }
 704                        psize = le16_to_cpu(ep->desc.wMaxPacketSize);
 705                        psize = (psize & 0x07ff) * (1 + ((psize >> 11) & 3));
 706                        bandwidth = psize * 1000;
 707                        if (gspca_dev->dev->speed == USB_SPEED_HIGH
 708                         || gspca_dev->dev->speed >= USB_SPEED_SUPER)
 709                                bandwidth *= 8;
 710                        bandwidth /= 1 << (ep->desc.bInterval - 1);
 711                        if (bandwidth <= last_bw)
 712                                continue;
 713                        if (bandwidth < ep_tb->bandwidth) {
 714                                ep_tb->bandwidth = bandwidth;
 715                                ep_tb->alt = j;
 716                                found = 1;
 717                        }
 718                }
 719                if (!found)
 720                        break;
 721                PDEBUG(D_STREAM, "alt %d bandwidth %d",
 722                                ep_tb->alt, ep_tb->bandwidth);
 723                last_bw = ep_tb->bandwidth;
 724                i++;
 725                ep_tb++;
 726        }
 727
 728        /*
 729         * If the camera:
 730         * has a usb audio class interface (a built in usb mic); and
 731         * is a usb 1 full speed device; and
 732         * uses the max full speed iso bandwidth; and
 733         * and has more than 1 alt setting
 734         * then skip the highest alt setting to spare bandwidth for the mic
 735         */
 736        if (gspca_dev->audio &&
 737                        gspca_dev->dev->speed == USB_SPEED_FULL &&
 738                        last_bw >= 1000000 &&
 739                        i > 1) {
 740                PDEBUG(D_STREAM, "dev has usb audio, skipping highest alt");
 741                i--;
 742                ep_tb--;
 743        }
 744
 745        /* get the requested bandwidth and start at the highest atlsetting */
 746        bandwidth = which_bandwidth(gspca_dev);
 747        ep_tb--;
 748        while (i > 1) {
 749                ep_tb--;
 750                if (ep_tb->bandwidth < bandwidth)
 751                        break;
 752                i--;
 753        }
 754        return i;
 755}
 756
 757/*
 758 * create the URBs for image transfer
 759 */
 760static int create_urbs(struct gspca_dev *gspca_dev,
 761                        struct usb_host_endpoint *ep)
 762{
 763        struct urb *urb;
 764        int n, nurbs, i, psize, npkt, bsize;
 765
 766        /* calculate the packet size and the number of packets */
 767        psize = le16_to_cpu(ep->desc.wMaxPacketSize);
 768
 769        if (!gspca_dev->cam.bulk) {             /* isoc */
 770
 771                /* See paragraph 5.9 / table 5-11 of the usb 2.0 spec. */
 772                if (gspca_dev->pkt_size == 0)
 773                        psize = (psize & 0x07ff) * (1 + ((psize >> 11) & 3));
 774                else
 775                        psize = gspca_dev->pkt_size;
 776                npkt = gspca_dev->cam.npkt;
 777                if (npkt == 0)
 778                        npkt = 32;              /* default value */
 779                bsize = psize * npkt;
 780                PDEBUG(D_STREAM,
 781                        "isoc %d pkts size %d = bsize:%d",
 782                        npkt, psize, bsize);
 783                nurbs = DEF_NURBS;
 784        } else {                                /* bulk */
 785                npkt = 0;
 786                bsize = gspca_dev->cam.bulk_size;
 787                if (bsize == 0)
 788                        bsize = psize;
 789                PDEBUG(D_STREAM, "bulk bsize:%d", bsize);
 790                if (gspca_dev->cam.bulk_nurbs != 0)
 791                        nurbs = gspca_dev->cam.bulk_nurbs;
 792                else
 793                        nurbs = 1;
 794        }
 795
 796        for (n = 0; n < nurbs; n++) {
 797                urb = usb_alloc_urb(npkt, GFP_KERNEL);
 798                if (!urb)
 799                        return -ENOMEM;
 800                gspca_dev->urb[n] = urb;
 801                urb->transfer_buffer = usb_alloc_coherent(gspca_dev->dev,
 802                                                bsize,
 803                                                GFP_KERNEL,
 804                                                &urb->transfer_dma);
 805
 806                if (urb->transfer_buffer == NULL) {
 807                        pr_err("usb_alloc_coherent failed\n");
 808                        return -ENOMEM;
 809                }
 810                urb->dev = gspca_dev->dev;
 811                urb->context = gspca_dev;
 812                urb->transfer_buffer_length = bsize;
 813                if (npkt != 0) {                /* ISOC */
 814                        urb->pipe = usb_rcvisocpipe(gspca_dev->dev,
 815                                                    ep->desc.bEndpointAddress);
 816                        urb->transfer_flags = URB_ISO_ASAP
 817                                        | URB_NO_TRANSFER_DMA_MAP;
 818                        urb->interval = 1 << (ep->desc.bInterval - 1);
 819                        urb->complete = isoc_irq;
 820                        urb->number_of_packets = npkt;
 821                        for (i = 0; i < npkt; i++) {
 822                                urb->iso_frame_desc[i].length = psize;
 823                                urb->iso_frame_desc[i].offset = psize * i;
 824                        }
 825                } else {                /* bulk */
 826                        urb->pipe = usb_rcvbulkpipe(gspca_dev->dev,
 827                                                ep->desc.bEndpointAddress);
 828                        urb->transfer_flags = URB_NO_TRANSFER_DMA_MAP;
 829                        urb->complete = bulk_irq;
 830                }
 831        }
 832        return 0;
 833}
 834
 835/*
 836 * start the USB transfer
 837 */
 838static int gspca_init_transfer(struct gspca_dev *gspca_dev)
 839{
 840        struct usb_interface *intf;
 841        struct usb_host_endpoint *ep;
 842        struct urb *urb;
 843        struct ep_tb_s ep_tb[MAX_ALT];
 844        int n, ret, xfer, alt, alt_idx;
 845
 846        /* reset the streaming variables */
 847        gspca_dev->image = NULL;
 848        gspca_dev->image_len = 0;
 849        gspca_dev->last_packet_type = DISCARD_PACKET;
 850        gspca_dev->sequence = 0;
 851
 852        gspca_dev->usb_err = 0;
 853
 854        /* do the specific subdriver stuff before endpoint selection */
 855        intf = usb_ifnum_to_if(gspca_dev->dev, gspca_dev->iface);
 856        gspca_dev->alt = gspca_dev->cam.bulk ? intf->num_altsetting : 0;
 857        if (gspca_dev->sd_desc->isoc_init) {
 858                ret = gspca_dev->sd_desc->isoc_init(gspca_dev);
 859                if (ret < 0)
 860                        return ret;
 861        }
 862        xfer = gspca_dev->cam.bulk ? USB_ENDPOINT_XFER_BULK
 863                                   : USB_ENDPOINT_XFER_ISOC;
 864
 865        /* if bulk or the subdriver forced an altsetting, get the endpoint */
 866        if (gspca_dev->alt != 0) {
 867                gspca_dev->alt--;       /* (previous version compatibility) */
 868                ep = alt_xfer(&intf->altsetting[gspca_dev->alt], xfer,
 869                              gspca_dev->xfer_ep);
 870                if (ep == NULL) {
 871                        pr_err("bad altsetting %d\n", gspca_dev->alt);
 872                        return -EIO;
 873                }
 874                ep_tb[0].alt = gspca_dev->alt;
 875                alt_idx = 1;
 876        } else {
 877                /* else, compute the minimum bandwidth
 878                 * and build the endpoint table */
 879                alt_idx = build_isoc_ep_tb(gspca_dev, intf, ep_tb);
 880                if (alt_idx <= 0) {
 881                        pr_err("no transfer endpoint found\n");
 882                        return -EIO;
 883                }
 884        }
 885
 886        /* set the highest alternate setting and
 887         * loop until urb submit succeeds */
 888        gspca_input_destroy_urb(gspca_dev);
 889
 890        gspca_dev->alt = ep_tb[--alt_idx].alt;
 891        alt = -1;
 892        for (;;) {
 893                if (alt != gspca_dev->alt) {
 894                        alt = gspca_dev->alt;
 895                        if (intf->num_altsetting > 1) {
 896                                ret = usb_set_interface(gspca_dev->dev,
 897                                                        gspca_dev->iface,
 898                                                        alt);
 899                                if (ret < 0) {
 900                                        if (ret == -ENOSPC)
 901                                                goto retry; /*fixme: ugly*/
 902                                        pr_err("set alt %d err %d\n", alt, ret);
 903                                        goto out;
 904                                }
 905                        }
 906                }
 907                if (!gspca_dev->cam.no_urb_create) {
 908                        PDEBUG(D_STREAM, "init transfer alt %d", alt);
 909                        ret = create_urbs(gspca_dev,
 910                                alt_xfer(&intf->altsetting[alt], xfer,
 911                                         gspca_dev->xfer_ep));
 912                        if (ret < 0) {
 913                                destroy_urbs(gspca_dev);
 914                                goto out;
 915                        }
 916                }
 917
 918                /* clear the bulk endpoint */
 919                if (gspca_dev->cam.bulk)
 920                        usb_clear_halt(gspca_dev->dev,
 921                                        gspca_dev->urb[0]->pipe);
 922
 923                /* start the cam */
 924                ret = gspca_dev->sd_desc->start(gspca_dev);
 925                if (ret < 0) {
 926                        destroy_urbs(gspca_dev);
 927                        goto out;
 928                }
 929                gspca_dev->streaming = 1;
 930                v4l2_ctrl_handler_setup(gspca_dev->vdev.ctrl_handler);
 931
 932                /* some bulk transfers are started by the subdriver */
 933                if (gspca_dev->cam.bulk && gspca_dev->cam.bulk_nurbs == 0)
 934                        break;
 935
 936                /* submit the URBs */
 937                for (n = 0; n < MAX_NURBS; n++) {
 938                        urb = gspca_dev->urb[n];
 939                        if (urb == NULL)
 940                                break;
 941                        ret = usb_submit_urb(urb, GFP_KERNEL);
 942                        if (ret < 0)
 943                                break;
 944                }
 945                if (ret >= 0)
 946                        break;                  /* transfer is started */
 947
 948                /* something when wrong
 949                 * stop the webcam and free the transfer resources */
 950                gspca_stream_off(gspca_dev);
 951                if (ret != -ENOSPC) {
 952                        pr_err("usb_submit_urb alt %d err %d\n",
 953                               gspca_dev->alt, ret);
 954                        goto out;
 955                }
 956
 957                /* the bandwidth is not wide enough
 958                 * negotiate or try a lower alternate setting */
 959retry:
 960                PERR("alt %d - bandwidth not wide enough, trying again", alt);
 961                msleep(20);     /* wait for kill complete */
 962                if (gspca_dev->sd_desc->isoc_nego) {
 963                        ret = gspca_dev->sd_desc->isoc_nego(gspca_dev);
 964                        if (ret < 0)
 965                                goto out;
 966                } else {
 967                        if (alt_idx <= 0) {
 968                                pr_err("no transfer endpoint found\n");
 969                                ret = -EIO;
 970                                goto out;
 971                        }
 972                        gspca_dev->alt = ep_tb[--alt_idx].alt;
 973                }
 974        }
 975out:
 976        gspca_input_create_urb(gspca_dev);
 977        return ret;
 978}
 979
 980static void gspca_set_default_mode(struct gspca_dev *gspca_dev)
 981{
 982        int i;
 983
 984        i = gspca_dev->cam.nmodes - 1;  /* take the highest mode */
 985        gspca_dev->curr_mode = i;
 986        gspca_dev->pixfmt = gspca_dev->cam.cam_mode[i];
 987
 988        /* does nothing if ctrl_handler == NULL */
 989        v4l2_ctrl_handler_setup(gspca_dev->vdev.ctrl_handler);
 990}
 991
 992static int wxh_to_mode(struct gspca_dev *gspca_dev,
 993                        int width, int height)
 994{
 995        int i;
 996
 997        for (i = 0; i < gspca_dev->cam.nmodes; i++) {
 998                if (width == gspca_dev->cam.cam_mode[i].width
 999                    && height == gspca_dev->cam.cam_mode[i].height)
1000                        return i;
1001        }
1002        return -EINVAL;
1003}
1004
1005static int wxh_to_nearest_mode(struct gspca_dev *gspca_dev,
1006                        int width, int height)
1007{
1008        int i;
1009
1010        for (i = gspca_dev->cam.nmodes; --i > 0; ) {
1011                if (width >= gspca_dev->cam.cam_mode[i].width
1012                    && height >= gspca_dev->cam.cam_mode[i].height)
1013                        break;
1014        }
1015        return i;
1016}
1017
1018/*
1019 * search a mode with the right pixel format
1020 */
1021static int gspca_get_mode(struct gspca_dev *gspca_dev,
1022                        int mode,
1023                        int pixfmt)
1024{
1025        int modeU, modeD;
1026
1027        modeU = modeD = mode;
1028        while ((modeU < gspca_dev->cam.nmodes) || modeD >= 0) {
1029                if (--modeD >= 0) {
1030                        if (gspca_dev->cam.cam_mode[modeD].pixelformat
1031                                                                == pixfmt)
1032                                return modeD;
1033                }
1034                if (++modeU < gspca_dev->cam.nmodes) {
1035                        if (gspca_dev->cam.cam_mode[modeU].pixelformat
1036                                                                == pixfmt)
1037                                return modeU;
1038                }
1039        }
1040        return -EINVAL;
1041}
1042
1043#ifdef CONFIG_VIDEO_ADV_DEBUG
1044static int vidioc_g_chip_info(struct file *file, void *priv,
1045                                struct v4l2_dbg_chip_info *chip)
1046{
1047        struct gspca_dev *gspca_dev = video_drvdata(file);
1048
1049        gspca_dev->usb_err = 0;
1050        if (gspca_dev->sd_desc->get_chip_info)
1051                return gspca_dev->sd_desc->get_chip_info(gspca_dev, chip);
1052        return chip->match.addr ? -EINVAL : 0;
1053}
1054
1055static int vidioc_g_register(struct file *file, void *priv,
1056                struct v4l2_dbg_register *reg)
1057{
1058        struct gspca_dev *gspca_dev = video_drvdata(file);
1059
1060        gspca_dev->usb_err = 0;
1061        return gspca_dev->sd_desc->get_register(gspca_dev, reg);
1062}
1063
1064static int vidioc_s_register(struct file *file, void *priv,
1065                const struct v4l2_dbg_register *reg)
1066{
1067        struct gspca_dev *gspca_dev = video_drvdata(file);
1068
1069        gspca_dev->usb_err = 0;
1070        return gspca_dev->sd_desc->set_register(gspca_dev, reg);
1071}
1072#endif
1073
1074static int vidioc_enum_fmt_vid_cap(struct file *file, void  *priv,
1075                                struct v4l2_fmtdesc *fmtdesc)
1076{
1077        struct gspca_dev *gspca_dev = video_drvdata(file);
1078        int i, j, index;
1079        __u32 fmt_tb[8];
1080
1081        /* give an index to each format */
1082        index = 0;
1083        j = 0;
1084        for (i = gspca_dev->cam.nmodes; --i >= 0; ) {
1085                fmt_tb[index] = gspca_dev->cam.cam_mode[i].pixelformat;
1086                j = 0;
1087                for (;;) {
1088                        if (fmt_tb[j] == fmt_tb[index])
1089                                break;
1090                        j++;
1091                }
1092                if (j == index) {
1093                        if (fmtdesc->index == index)
1094                                break;          /* new format */
1095                        index++;
1096                        if (index >= ARRAY_SIZE(fmt_tb))
1097                                return -EINVAL;
1098                }
1099        }
1100        if (i < 0)
1101                return -EINVAL;         /* no more format */
1102
1103        fmtdesc->pixelformat = fmt_tb[index];
1104        if (gspca_dev->cam.cam_mode[i].sizeimage <
1105                        gspca_dev->cam.cam_mode[i].width *
1106                                gspca_dev->cam.cam_mode[i].height)
1107                fmtdesc->flags = V4L2_FMT_FLAG_COMPRESSED;
1108        fmtdesc->description[0] = fmtdesc->pixelformat & 0xff;
1109        fmtdesc->description[1] = (fmtdesc->pixelformat >> 8) & 0xff;
1110        fmtdesc->description[2] = (fmtdesc->pixelformat >> 16) & 0xff;
1111        fmtdesc->description[3] = fmtdesc->pixelformat >> 24;
1112        fmtdesc->description[4] = '\0';
1113        return 0;
1114}
1115
1116static int vidioc_g_fmt_vid_cap(struct file *file, void *priv,
1117                            struct v4l2_format *fmt)
1118{
1119        struct gspca_dev *gspca_dev = video_drvdata(file);
1120
1121        fmt->fmt.pix = gspca_dev->pixfmt;
1122        /* some drivers use priv internally, zero it before giving it back to
1123           the core */
1124        fmt->fmt.pix.priv = 0;
1125        return 0;
1126}
1127
1128static int try_fmt_vid_cap(struct gspca_dev *gspca_dev,
1129                        struct v4l2_format *fmt)
1130{
1131        int w, h, mode, mode2;
1132
1133        w = fmt->fmt.pix.width;
1134        h = fmt->fmt.pix.height;
1135
1136        PDEBUG_MODE(gspca_dev, D_CONF, "try fmt cap",
1137                    fmt->fmt.pix.pixelformat, w, h);
1138
1139        /* search the nearest mode for width and height */
1140        mode = wxh_to_nearest_mode(gspca_dev, w, h);
1141
1142        /* OK if right palette */
1143        if (gspca_dev->cam.cam_mode[mode].pixelformat
1144                                                != fmt->fmt.pix.pixelformat) {
1145
1146                /* else, search the closest mode with the same pixel format */
1147                mode2 = gspca_get_mode(gspca_dev, mode,
1148                                        fmt->fmt.pix.pixelformat);
1149                if (mode2 >= 0)
1150                        mode = mode2;
1151        }
1152        fmt->fmt.pix = gspca_dev->cam.cam_mode[mode];
1153        if (gspca_dev->sd_desc->try_fmt) {
1154                /* pass original resolution to subdriver try_fmt */
1155                fmt->fmt.pix.width = w;
1156                fmt->fmt.pix.height = h;
1157                gspca_dev->sd_desc->try_fmt(gspca_dev, fmt);
1158        }
1159        /* some drivers use priv internally, zero it before giving it back to
1160           the core */
1161        fmt->fmt.pix.priv = 0;
1162        return mode;                    /* used when s_fmt */
1163}
1164
1165static int vidioc_try_fmt_vid_cap(struct file *file,
1166                              void *priv,
1167                              struct v4l2_format *fmt)
1168{
1169        struct gspca_dev *gspca_dev = video_drvdata(file);
1170        int ret;
1171
1172        ret = try_fmt_vid_cap(gspca_dev, fmt);
1173        if (ret < 0)
1174                return ret;
1175        return 0;
1176}
1177
1178static int vidioc_s_fmt_vid_cap(struct file *file, void *priv,
1179                            struct v4l2_format *fmt)
1180{
1181        struct gspca_dev *gspca_dev = video_drvdata(file);
1182        int ret;
1183
1184        if (mutex_lock_interruptible(&gspca_dev->queue_lock))
1185                return -ERESTARTSYS;
1186
1187        ret = try_fmt_vid_cap(gspca_dev, fmt);
1188        if (ret < 0)
1189                goto out;
1190
1191        if (gspca_dev->nframes != 0
1192            && fmt->fmt.pix.sizeimage > gspca_dev->frsz) {
1193                ret = -EINVAL;
1194                goto out;
1195        }
1196
1197        if (gspca_dev->streaming) {
1198                ret = -EBUSY;
1199                goto out;
1200        }
1201        gspca_dev->curr_mode = ret;
1202        if (gspca_dev->sd_desc->try_fmt)
1203                /* subdriver try_fmt can modify format parameters */
1204                gspca_dev->pixfmt = fmt->fmt.pix;
1205        else
1206                gspca_dev->pixfmt = gspca_dev->cam.cam_mode[ret];
1207
1208        ret = 0;
1209out:
1210        mutex_unlock(&gspca_dev->queue_lock);
1211        return ret;
1212}
1213
1214static int vidioc_enum_framesizes(struct file *file, void *priv,
1215                                  struct v4l2_frmsizeenum *fsize)
1216{
1217        struct gspca_dev *gspca_dev = video_drvdata(file);
1218        int i;
1219        __u32 index = 0;
1220
1221        if (gspca_dev->sd_desc->enum_framesizes)
1222                return gspca_dev->sd_desc->enum_framesizes(gspca_dev, fsize);
1223
1224        for (i = 0; i < gspca_dev->cam.nmodes; i++) {
1225                if (fsize->pixel_format !=
1226                                gspca_dev->cam.cam_mode[i].pixelformat)
1227                        continue;
1228
1229                if (fsize->index == index) {
1230                        fsize->type = V4L2_FRMSIZE_TYPE_DISCRETE;
1231                        fsize->discrete.width =
1232                                gspca_dev->cam.cam_mode[i].width;
1233                        fsize->discrete.height =
1234                                gspca_dev->cam.cam_mode[i].height;
1235                        return 0;
1236                }
1237                index++;
1238        }
1239
1240        return -EINVAL;
1241}
1242
1243static int vidioc_enum_frameintervals(struct file *filp, void *priv,
1244                                      struct v4l2_frmivalenum *fival)
1245{
1246        struct gspca_dev *gspca_dev = video_drvdata(filp);
1247        int mode;
1248        __u32 i;
1249
1250        mode = wxh_to_mode(gspca_dev, fival->width, fival->height);
1251        if (mode < 0)
1252                return -EINVAL;
1253
1254        if (gspca_dev->cam.mode_framerates == NULL ||
1255                        gspca_dev->cam.mode_framerates[mode].nrates == 0)
1256                return -EINVAL;
1257
1258        if (fival->pixel_format !=
1259                        gspca_dev->cam.cam_mode[mode].pixelformat)
1260                return -EINVAL;
1261
1262        for (i = 0; i < gspca_dev->cam.mode_framerates[mode].nrates; i++) {
1263                if (fival->index == i) {
1264                        fival->type = V4L2_FRMIVAL_TYPE_DISCRETE;
1265                        fival->discrete.numerator = 1;
1266                        fival->discrete.denominator =
1267                                gspca_dev->cam.mode_framerates[mode].rates[i];
1268                        return 0;
1269                }
1270        }
1271
1272        return -EINVAL;
1273}
1274
1275static void gspca_release(struct v4l2_device *v4l2_device)
1276{
1277        struct gspca_dev *gspca_dev =
1278                container_of(v4l2_device, struct gspca_dev, v4l2_dev);
1279
1280        v4l2_ctrl_handler_free(gspca_dev->vdev.ctrl_handler);
1281        v4l2_device_unregister(&gspca_dev->v4l2_dev);
1282        kfree(gspca_dev->usb_buf);
1283        kfree(gspca_dev);
1284}
1285
1286static int dev_open(struct file *file)
1287{
1288        struct gspca_dev *gspca_dev = video_drvdata(file);
1289        int ret;
1290
1291        PDEBUG(D_STREAM, "[%s] open", current->comm);
1292
1293        /* protect the subdriver against rmmod */
1294        if (!try_module_get(gspca_dev->module))
1295                return -ENODEV;
1296
1297        ret = v4l2_fh_open(file);
1298        if (ret)
1299                module_put(gspca_dev->module);
1300        return ret;
1301}
1302
1303static int dev_close(struct file *file)
1304{
1305        struct gspca_dev *gspca_dev = video_drvdata(file);
1306
1307        PDEBUG(D_STREAM, "[%s] close", current->comm);
1308
1309        /* Needed for gspca_stream_off, always lock before queue_lock! */
1310        if (mutex_lock_interruptible(&gspca_dev->usb_lock))
1311                return -ERESTARTSYS;
1312
1313        if (mutex_lock_interruptible(&gspca_dev->queue_lock)) {
1314                mutex_unlock(&gspca_dev->usb_lock);
1315                return -ERESTARTSYS;
1316        }
1317
1318        /* if the file did the capture, free the streaming resources */
1319        if (gspca_dev->capt_file == file) {
1320                if (gspca_dev->streaming)
1321                        gspca_stream_off(gspca_dev);
1322                frame_free(gspca_dev);
1323        }
1324        module_put(gspca_dev->module);
1325        mutex_unlock(&gspca_dev->queue_lock);
1326        mutex_unlock(&gspca_dev->usb_lock);
1327
1328        PDEBUG(D_STREAM, "close done");
1329
1330        return v4l2_fh_release(file);
1331}
1332
1333static int vidioc_querycap(struct file *file, void  *priv,
1334                           struct v4l2_capability *cap)
1335{
1336        struct gspca_dev *gspca_dev = video_drvdata(file);
1337
1338        strlcpy((char *) cap->driver, gspca_dev->sd_desc->name,
1339                        sizeof cap->driver);
1340        if (gspca_dev->dev->product != NULL) {
1341                strlcpy((char *) cap->card, gspca_dev->dev->product,
1342                        sizeof cap->card);
1343        } else {
1344                snprintf((char *) cap->card, sizeof cap->card,
1345                        "USB Camera (%04x:%04x)",
1346                        le16_to_cpu(gspca_dev->dev->descriptor.idVendor),
1347                        le16_to_cpu(gspca_dev->dev->descriptor.idProduct));
1348        }
1349        usb_make_path(gspca_dev->dev, (char *) cap->bus_info,
1350                        sizeof(cap->bus_info));
1351        cap->device_caps = V4L2_CAP_VIDEO_CAPTURE
1352                          | V4L2_CAP_STREAMING
1353                          | V4L2_CAP_READWRITE;
1354        cap->capabilities = cap->device_caps | V4L2_CAP_DEVICE_CAPS;
1355        return 0;
1356}
1357
1358static int vidioc_enum_input(struct file *file, void *priv,
1359                                struct v4l2_input *input)
1360{
1361        struct gspca_dev *gspca_dev = video_drvdata(file);
1362
1363        if (input->index != 0)
1364                return -EINVAL;
1365        input->type = V4L2_INPUT_TYPE_CAMERA;
1366        input->status = gspca_dev->cam.input_flags;
1367        strlcpy(input->name, gspca_dev->sd_desc->name,
1368                sizeof input->name);
1369        return 0;
1370}
1371
1372static int vidioc_g_input(struct file *file, void *priv, unsigned int *i)
1373{
1374        *i = 0;
1375        return 0;
1376}
1377
1378static int vidioc_s_input(struct file *file, void *priv, unsigned int i)
1379{
1380        if (i > 0)
1381                return -EINVAL;
1382        return (0);
1383}
1384
1385static int vidioc_reqbufs(struct file *file, void *priv,
1386                          struct v4l2_requestbuffers *rb)
1387{
1388        struct gspca_dev *gspca_dev = video_drvdata(file);
1389        int i, ret = 0, streaming;
1390
1391        i = rb->memory;                 /* (avoid compilation warning) */
1392        switch (i) {
1393        case GSPCA_MEMORY_READ:                 /* (internal call) */
1394        case V4L2_MEMORY_MMAP:
1395        case V4L2_MEMORY_USERPTR:
1396                break;
1397        default:
1398                return -EINVAL;
1399        }
1400        if (mutex_lock_interruptible(&gspca_dev->queue_lock))
1401                return -ERESTARTSYS;
1402
1403        if (gspca_dev->memory != GSPCA_MEMORY_NO
1404            && gspca_dev->memory != GSPCA_MEMORY_READ
1405            && gspca_dev->memory != rb->memory) {
1406                ret = -EBUSY;
1407                goto out;
1408        }
1409
1410        /* only one file may do the capture */
1411        if (gspca_dev->capt_file != NULL
1412            && gspca_dev->capt_file != file) {
1413                ret = -EBUSY;
1414                goto out;
1415        }
1416
1417        /* if allocated, the buffers must not be mapped */
1418        for (i = 0; i < gspca_dev->nframes; i++) {
1419                if (gspca_dev->frame[i].vma_use_count) {
1420                        ret = -EBUSY;
1421                        goto out;
1422                }
1423        }
1424
1425        /* stop streaming */
1426        streaming = gspca_dev->streaming;
1427        if (streaming) {
1428                gspca_stream_off(gspca_dev);
1429
1430                /* Don't restart the stream when switching from read
1431                 * to mmap mode */
1432                if (gspca_dev->memory == GSPCA_MEMORY_READ)
1433                        streaming = 0;
1434        }
1435
1436        /* free the previous allocated buffers, if any */
1437        if (gspca_dev->nframes != 0)
1438                frame_free(gspca_dev);
1439        if (rb->count == 0)                     /* unrequest */
1440                goto out;
1441        ret = frame_alloc(gspca_dev, file, rb->memory, rb->count);
1442        if (ret == 0) {
1443                rb->count = gspca_dev->nframes;
1444                if (streaming)
1445                        ret = gspca_init_transfer(gspca_dev);
1446        }
1447out:
1448        mutex_unlock(&gspca_dev->queue_lock);
1449        PDEBUG(D_STREAM, "reqbufs st:%d c:%d", ret, rb->count);
1450        return ret;
1451}
1452
1453static int vidioc_querybuf(struct file *file, void *priv,
1454                           struct v4l2_buffer *v4l2_buf)
1455{
1456        struct gspca_dev *gspca_dev = video_drvdata(file);
1457        struct gspca_frame *frame;
1458
1459        if (v4l2_buf->index >= gspca_dev->nframes)
1460                return -EINVAL;
1461
1462        frame = &gspca_dev->frame[v4l2_buf->index];
1463        memcpy(v4l2_buf, &frame->v4l2_buf, sizeof *v4l2_buf);
1464        return 0;
1465}
1466
1467static int vidioc_streamon(struct file *file, void *priv,
1468                           enum v4l2_buf_type buf_type)
1469{
1470        struct gspca_dev *gspca_dev = video_drvdata(file);
1471        int ret;
1472
1473        if (buf_type != V4L2_BUF_TYPE_VIDEO_CAPTURE)
1474                return -EINVAL;
1475        if (mutex_lock_interruptible(&gspca_dev->queue_lock))
1476                return -ERESTARTSYS;
1477
1478        /* check the capture file */
1479        if (gspca_dev->capt_file != file) {
1480                ret = -EBUSY;
1481                goto out;
1482        }
1483
1484        if (gspca_dev->nframes == 0
1485            || !(gspca_dev->frame[0].v4l2_buf.flags & V4L2_BUF_FLAG_QUEUED)) {
1486                ret = -EINVAL;
1487                goto out;
1488        }
1489        if (!gspca_dev->streaming) {
1490                ret = gspca_init_transfer(gspca_dev);
1491                if (ret < 0)
1492                        goto out;
1493        }
1494        PDEBUG_MODE(gspca_dev, D_STREAM, "stream on OK",
1495                    gspca_dev->pixfmt.pixelformat,
1496                    gspca_dev->pixfmt.width, gspca_dev->pixfmt.height);
1497        ret = 0;
1498out:
1499        mutex_unlock(&gspca_dev->queue_lock);
1500        return ret;
1501}
1502
1503static int vidioc_streamoff(struct file *file, void *priv,
1504                                enum v4l2_buf_type buf_type)
1505{
1506        struct gspca_dev *gspca_dev = video_drvdata(file);
1507        int i, ret;
1508
1509        if (buf_type != V4L2_BUF_TYPE_VIDEO_CAPTURE)
1510                return -EINVAL;
1511
1512        if (mutex_lock_interruptible(&gspca_dev->queue_lock))
1513                return -ERESTARTSYS;
1514
1515        if (!gspca_dev->streaming) {
1516                ret = 0;
1517                goto out;
1518        }
1519
1520        /* check the capture file */
1521        if (gspca_dev->capt_file != file) {
1522                ret = -EBUSY;
1523                goto out;
1524        }
1525
1526        /* stop streaming */
1527        gspca_stream_off(gspca_dev);
1528        /* In case another thread is waiting in dqbuf */
1529        wake_up_interruptible(&gspca_dev->wq);
1530
1531        /* empty the transfer queues */
1532        for (i = 0; i < gspca_dev->nframes; i++)
1533                gspca_dev->frame[i].v4l2_buf.flags &= ~BUF_ALL_FLAGS;
1534        atomic_set(&gspca_dev->fr_q, 0);
1535        atomic_set(&gspca_dev->fr_i, 0);
1536        gspca_dev->fr_o = 0;
1537        ret = 0;
1538out:
1539        mutex_unlock(&gspca_dev->queue_lock);
1540        return ret;
1541}
1542
1543static int vidioc_g_jpegcomp(struct file *file, void *priv,
1544                        struct v4l2_jpegcompression *jpegcomp)
1545{
1546        struct gspca_dev *gspca_dev = video_drvdata(file);
1547
1548        gspca_dev->usb_err = 0;
1549        return gspca_dev->sd_desc->get_jcomp(gspca_dev, jpegcomp);
1550}
1551
1552static int vidioc_s_jpegcomp(struct file *file, void *priv,
1553                        const struct v4l2_jpegcompression *jpegcomp)
1554{
1555        struct gspca_dev *gspca_dev = video_drvdata(file);
1556
1557        gspca_dev->usb_err = 0;
1558        return gspca_dev->sd_desc->set_jcomp(gspca_dev, jpegcomp);
1559}
1560
1561static int vidioc_g_parm(struct file *filp, void *priv,
1562                        struct v4l2_streamparm *parm)
1563{
1564        struct gspca_dev *gspca_dev = video_drvdata(filp);
1565
1566        parm->parm.capture.readbuffers = gspca_dev->nbufread;
1567
1568        if (gspca_dev->sd_desc->get_streamparm) {
1569                gspca_dev->usb_err = 0;
1570                gspca_dev->sd_desc->get_streamparm(gspca_dev, parm);
1571                return gspca_dev->usb_err;
1572        }
1573        return 0;
1574}
1575
1576static int vidioc_s_parm(struct file *filp, void *priv,
1577                        struct v4l2_streamparm *parm)
1578{
1579        struct gspca_dev *gspca_dev = video_drvdata(filp);
1580        unsigned int n;
1581
1582        n = parm->parm.capture.readbuffers;
1583        if (n == 0 || n >= GSPCA_MAX_FRAMES)
1584                parm->parm.capture.readbuffers = gspca_dev->nbufread;
1585        else
1586                gspca_dev->nbufread = n;
1587
1588        if (gspca_dev->sd_desc->set_streamparm) {
1589                gspca_dev->usb_err = 0;
1590                gspca_dev->sd_desc->set_streamparm(gspca_dev, parm);
1591                return gspca_dev->usb_err;
1592        }
1593
1594        return 0;
1595}
1596
1597static int dev_mmap(struct file *file, struct vm_area_struct *vma)
1598{
1599        struct gspca_dev *gspca_dev = video_drvdata(file);
1600        struct gspca_frame *frame;
1601        struct page *page;
1602        unsigned long addr, start, size;
1603        int i, ret;
1604
1605        start = vma->vm_start;
1606        size = vma->vm_end - vma->vm_start;
1607        PDEBUG(D_STREAM, "mmap start:%08x size:%d", (int) start, (int) size);
1608
1609        if (mutex_lock_interruptible(&gspca_dev->queue_lock))
1610                return -ERESTARTSYS;
1611        if (gspca_dev->capt_file != file) {
1612                ret = -EINVAL;
1613                goto out;
1614        }
1615
1616        frame = NULL;
1617        for (i = 0; i < gspca_dev->nframes; ++i) {
1618                if (gspca_dev->frame[i].v4l2_buf.memory != V4L2_MEMORY_MMAP) {
1619                        PDEBUG(D_STREAM, "mmap bad memory type");
1620                        break;
1621                }
1622                if ((gspca_dev->frame[i].v4l2_buf.m.offset >> PAGE_SHIFT)
1623                                                == vma->vm_pgoff) {
1624                        frame = &gspca_dev->frame[i];
1625                        break;
1626                }
1627        }
1628        if (frame == NULL) {
1629                PDEBUG(D_STREAM, "mmap no frame buffer found");
1630                ret = -EINVAL;
1631                goto out;
1632        }
1633        if (size != frame->v4l2_buf.length) {
1634                PDEBUG(D_STREAM, "mmap bad size");
1635                ret = -EINVAL;
1636                goto out;
1637        }
1638
1639        /*
1640         * - VM_IO marks the area as being a mmaped region for I/O to a
1641         *   device. It also prevents the region from being core dumped.
1642         */
1643        vma->vm_flags |= VM_IO;
1644
1645        addr = (unsigned long) frame->data;
1646        while (size > 0) {
1647                page = vmalloc_to_page((void *) addr);
1648                ret = vm_insert_page(vma, start, page);
1649                if (ret < 0)
1650                        goto out;
1651                start += PAGE_SIZE;
1652                addr += PAGE_SIZE;
1653                size -= PAGE_SIZE;
1654        }
1655
1656        vma->vm_ops = &gspca_vm_ops;
1657        vma->vm_private_data = frame;
1658        gspca_vm_open(vma);
1659        ret = 0;
1660out:
1661        mutex_unlock(&gspca_dev->queue_lock);
1662        return ret;
1663}
1664
1665static int frame_ready_nolock(struct gspca_dev *gspca_dev, struct file *file,
1666                                enum v4l2_memory memory)
1667{
1668        if (!gspca_dev->present)
1669                return -ENODEV;
1670        if (gspca_dev->capt_file != file || gspca_dev->memory != memory ||
1671                        !gspca_dev->streaming)
1672                return -EINVAL;
1673
1674        /* check if a frame is ready */
1675        return gspca_dev->fr_o != atomic_read(&gspca_dev->fr_i);
1676}
1677
1678static int frame_ready(struct gspca_dev *gspca_dev, struct file *file,
1679                        enum v4l2_memory memory)
1680{
1681        int ret;
1682
1683        if (mutex_lock_interruptible(&gspca_dev->queue_lock))
1684                return -ERESTARTSYS;
1685        ret = frame_ready_nolock(gspca_dev, file, memory);
1686        mutex_unlock(&gspca_dev->queue_lock);
1687        return ret;
1688}
1689
1690/*
1691 * dequeue a video buffer
1692 *
1693 * If nonblock_ing is false, block until a buffer is available.
1694 */
1695static int vidioc_dqbuf(struct file *file, void *priv,
1696                        struct v4l2_buffer *v4l2_buf)
1697{
1698        struct gspca_dev *gspca_dev = video_drvdata(file);
1699        struct gspca_frame *frame;
1700        int i, j, ret;
1701
1702        PDEBUG(D_FRAM, "dqbuf");
1703
1704        if (mutex_lock_interruptible(&gspca_dev->queue_lock))
1705                return -ERESTARTSYS;
1706
1707        for (;;) {
1708                ret = frame_ready_nolock(gspca_dev, file, v4l2_buf->memory);
1709                if (ret < 0)
1710                        goto out;
1711                if (ret > 0)
1712                        break;
1713
1714                mutex_unlock(&gspca_dev->queue_lock);
1715
1716                if (file->f_flags & O_NONBLOCK)
1717                        return -EAGAIN;
1718
1719                /* wait till a frame is ready */
1720                ret = wait_event_interruptible_timeout(gspca_dev->wq,
1721                        frame_ready(gspca_dev, file, v4l2_buf->memory),
1722                        msecs_to_jiffies(3000));
1723                if (ret < 0)
1724                        return ret;
1725                if (ret == 0)
1726                        return -EIO;
1727
1728                if (mutex_lock_interruptible(&gspca_dev->queue_lock))
1729                        return -ERESTARTSYS;
1730        }
1731
1732        i = gspca_dev->fr_o;
1733        j = gspca_dev->fr_queue[i];
1734        frame = &gspca_dev->frame[j];
1735
1736        gspca_dev->fr_o = (i + 1) % GSPCA_MAX_FRAMES;
1737
1738        frame->v4l2_buf.flags &= ~V4L2_BUF_FLAG_DONE;
1739        memcpy(v4l2_buf, &frame->v4l2_buf, sizeof *v4l2_buf);
1740        PDEBUG(D_FRAM, "dqbuf %d", j);
1741        ret = 0;
1742
1743        if (gspca_dev->memory == V4L2_MEMORY_USERPTR) {
1744                if (copy_to_user((__u8 __user *) frame->v4l2_buf.m.userptr,
1745                                 frame->data,
1746                                 frame->v4l2_buf.bytesused)) {
1747                        PERR("dqbuf cp to user failed");
1748                        ret = -EFAULT;
1749                }
1750        }
1751out:
1752        mutex_unlock(&gspca_dev->queue_lock);
1753
1754        if (ret == 0 && gspca_dev->sd_desc->dq_callback) {
1755                mutex_lock(&gspca_dev->usb_lock);
1756                gspca_dev->usb_err = 0;
1757                if (gspca_dev->present)
1758                        gspca_dev->sd_desc->dq_callback(gspca_dev);
1759                mutex_unlock(&gspca_dev->usb_lock);
1760        }
1761
1762        return ret;
1763}
1764
1765/*
1766 * queue a video buffer
1767 *
1768 * Attempting to queue a buffer that has already been
1769 * queued will return -EINVAL.
1770 */
1771static int vidioc_qbuf(struct file *file, void *priv,
1772                        struct v4l2_buffer *v4l2_buf)
1773{
1774        struct gspca_dev *gspca_dev = video_drvdata(file);
1775        struct gspca_frame *frame;
1776        int i, index, ret;
1777
1778        PDEBUG(D_FRAM, "qbuf %d", v4l2_buf->index);
1779
1780        if (mutex_lock_interruptible(&gspca_dev->queue_lock))
1781                return -ERESTARTSYS;
1782
1783        index = v4l2_buf->index;
1784        if ((unsigned) index >= gspca_dev->nframes) {
1785                PDEBUG(D_FRAM,
1786                        "qbuf idx %d >= %d", index, gspca_dev->nframes);
1787                ret = -EINVAL;
1788                goto out;
1789        }
1790        if (v4l2_buf->memory != gspca_dev->memory) {
1791                PDEBUG(D_FRAM, "qbuf bad memory type");
1792                ret = -EINVAL;
1793                goto out;
1794        }
1795
1796        frame = &gspca_dev->frame[index];
1797        if (frame->v4l2_buf.flags & BUF_ALL_FLAGS) {
1798                PDEBUG(D_FRAM, "qbuf bad state");
1799                ret = -EINVAL;
1800                goto out;
1801        }
1802
1803        frame->v4l2_buf.flags |= V4L2_BUF_FLAG_QUEUED;
1804
1805        if (frame->v4l2_buf.memory == V4L2_MEMORY_USERPTR) {
1806                frame->v4l2_buf.m.userptr = v4l2_buf->m.userptr;
1807                frame->v4l2_buf.length = v4l2_buf->length;
1808        }
1809
1810        /* put the buffer in the 'queued' queue */
1811        i = atomic_read(&gspca_dev->fr_q);
1812        gspca_dev->fr_queue[i] = index;
1813        atomic_set(&gspca_dev->fr_q, (i + 1) % GSPCA_MAX_FRAMES);
1814
1815        v4l2_buf->flags |= V4L2_BUF_FLAG_QUEUED;
1816        v4l2_buf->flags &= ~V4L2_BUF_FLAG_DONE;
1817        ret = 0;
1818out:
1819        mutex_unlock(&gspca_dev->queue_lock);
1820        return ret;
1821}
1822
1823/*
1824 * allocate the resources for read()
1825 */
1826static int read_alloc(struct gspca_dev *gspca_dev,
1827                        struct file *file)
1828{
1829        struct v4l2_buffer v4l2_buf;
1830        int i, ret;
1831
1832        PDEBUG(D_STREAM, "read alloc");
1833
1834        if (mutex_lock_interruptible(&gspca_dev->usb_lock))
1835                return -ERESTARTSYS;
1836
1837        if (gspca_dev->nframes == 0) {
1838                struct v4l2_requestbuffers rb;
1839
1840                memset(&rb, 0, sizeof rb);
1841                rb.count = gspca_dev->nbufread;
1842                rb.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
1843                rb.memory = GSPCA_MEMORY_READ;
1844                ret = vidioc_reqbufs(file, gspca_dev, &rb);
1845                if (ret != 0) {
1846                        PDEBUG(D_STREAM, "read reqbuf err %d", ret);
1847                        goto out;
1848                }
1849                memset(&v4l2_buf, 0, sizeof v4l2_buf);
1850                v4l2_buf.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
1851                v4l2_buf.memory = GSPCA_MEMORY_READ;
1852                for (i = 0; i < gspca_dev->nbufread; i++) {
1853                        v4l2_buf.index = i;
1854                        ret = vidioc_qbuf(file, gspca_dev, &v4l2_buf);
1855                        if (ret != 0) {
1856                                PDEBUG(D_STREAM, "read qbuf err: %d", ret);
1857                                goto out;
1858                        }
1859                }
1860        }
1861
1862        /* start streaming */
1863        ret = vidioc_streamon(file, gspca_dev, V4L2_BUF_TYPE_VIDEO_CAPTURE);
1864        if (ret != 0)
1865                PDEBUG(D_STREAM, "read streamon err %d", ret);
1866out:
1867        mutex_unlock(&gspca_dev->usb_lock);
1868        return ret;
1869}
1870
1871static unsigned int dev_poll(struct file *file, poll_table *wait)
1872{
1873        struct gspca_dev *gspca_dev = video_drvdata(file);
1874        unsigned long req_events = poll_requested_events(wait);
1875        int ret = 0;
1876
1877        PDEBUG(D_FRAM, "poll");
1878
1879        if (req_events & POLLPRI)
1880                ret |= v4l2_ctrl_poll(file, wait);
1881
1882        if (req_events & (POLLIN | POLLRDNORM)) {
1883                /* if reqbufs is not done, the user would use read() */
1884                if (gspca_dev->memory == GSPCA_MEMORY_NO) {
1885                        if (read_alloc(gspca_dev, file) != 0) {
1886                                ret |= POLLERR;
1887                                goto out;
1888                        }
1889                }
1890
1891                poll_wait(file, &gspca_dev->wq, wait);
1892
1893                /* check if an image has been received */
1894                if (mutex_lock_interruptible(&gspca_dev->queue_lock) != 0) {
1895                        ret |= POLLERR;
1896                        goto out;
1897                }
1898                if (gspca_dev->fr_o != atomic_read(&gspca_dev->fr_i))
1899                        ret |= POLLIN | POLLRDNORM;
1900                mutex_unlock(&gspca_dev->queue_lock);
1901        }
1902
1903out:
1904        if (!gspca_dev->present)
1905                ret |= POLLHUP;
1906
1907        return ret;
1908}
1909
1910static ssize_t dev_read(struct file *file, char __user *data,
1911                    size_t count, loff_t *ppos)
1912{
1913        struct gspca_dev *gspca_dev = video_drvdata(file);
1914        struct gspca_frame *frame;
1915        struct v4l2_buffer v4l2_buf;
1916        struct timeval timestamp;
1917        int n, ret, ret2;
1918
1919        PDEBUG(D_FRAM, "read (%zd)", count);
1920        if (gspca_dev->memory == GSPCA_MEMORY_NO) { /* first time ? */
1921                ret = read_alloc(gspca_dev, file);
1922                if (ret != 0)
1923                        return ret;
1924        }
1925
1926        /* get a frame */
1927        v4l2_get_timestamp(&timestamp);
1928        timestamp.tv_sec--;
1929        n = 2;
1930        for (;;) {
1931                memset(&v4l2_buf, 0, sizeof v4l2_buf);
1932                v4l2_buf.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
1933                v4l2_buf.memory = GSPCA_MEMORY_READ;
1934                ret = vidioc_dqbuf(file, gspca_dev, &v4l2_buf);
1935                if (ret != 0) {
1936                        PDEBUG(D_STREAM, "read dqbuf err %d", ret);
1937                        return ret;
1938                }
1939
1940                /* if the process slept for more than 1 second,
1941                 * get a newer frame */
1942                frame = &gspca_dev->frame[v4l2_buf.index];
1943                if (--n < 0)
1944                        break;                  /* avoid infinite loop */
1945                if (frame->v4l2_buf.timestamp.tv_sec >= timestamp.tv_sec)
1946                        break;
1947                ret = vidioc_qbuf(file, gspca_dev, &v4l2_buf);
1948                if (ret != 0) {
1949                        PDEBUG(D_STREAM, "read qbuf err %d", ret);
1950                        return ret;
1951                }
1952        }
1953
1954        /* copy the frame */
1955        if (count > frame->v4l2_buf.bytesused)
1956                count = frame->v4l2_buf.bytesused;
1957        ret = copy_to_user(data, frame->data, count);
1958        if (ret != 0) {
1959                PERR("read cp to user lack %d / %zd", ret, count);
1960                ret = -EFAULT;
1961                goto out;
1962        }
1963        ret = count;
1964out:
1965        /* in each case, requeue the buffer */
1966        ret2 = vidioc_qbuf(file, gspca_dev, &v4l2_buf);
1967        if (ret2 != 0)
1968                return ret2;
1969        return ret;
1970}
1971
1972static struct v4l2_file_operations dev_fops = {
1973        .owner = THIS_MODULE,
1974        .open = dev_open,
1975        .release = dev_close,
1976        .read = dev_read,
1977        .mmap = dev_mmap,
1978        .unlocked_ioctl = video_ioctl2,
1979        .poll   = dev_poll,
1980};
1981
1982static const struct v4l2_ioctl_ops dev_ioctl_ops = {
1983        .vidioc_querycap        = vidioc_querycap,
1984        .vidioc_dqbuf           = vidioc_dqbuf,
1985        .vidioc_qbuf            = vidioc_qbuf,
1986        .vidioc_enum_fmt_vid_cap = vidioc_enum_fmt_vid_cap,
1987        .vidioc_try_fmt_vid_cap = vidioc_try_fmt_vid_cap,
1988        .vidioc_g_fmt_vid_cap   = vidioc_g_fmt_vid_cap,
1989        .vidioc_s_fmt_vid_cap   = vidioc_s_fmt_vid_cap,
1990        .vidioc_streamon        = vidioc_streamon,
1991        .vidioc_enum_input      = vidioc_enum_input,
1992        .vidioc_g_input         = vidioc_g_input,
1993        .vidioc_s_input         = vidioc_s_input,
1994        .vidioc_reqbufs         = vidioc_reqbufs,
1995        .vidioc_querybuf        = vidioc_querybuf,
1996        .vidioc_streamoff       = vidioc_streamoff,
1997        .vidioc_g_jpegcomp      = vidioc_g_jpegcomp,
1998        .vidioc_s_jpegcomp      = vidioc_s_jpegcomp,
1999        .vidioc_g_parm          = vidioc_g_parm,
2000        .vidioc_s_parm          = vidioc_s_parm,
2001        .vidioc_enum_framesizes = vidioc_enum_framesizes,
2002        .vidioc_enum_frameintervals = vidioc_enum_frameintervals,
2003#ifdef CONFIG_VIDEO_ADV_DEBUG
2004        .vidioc_g_chip_info     = vidioc_g_chip_info,
2005        .vidioc_g_register      = vidioc_g_register,
2006        .vidioc_s_register      = vidioc_s_register,
2007#endif
2008        .vidioc_subscribe_event = v4l2_ctrl_subscribe_event,
2009        .vidioc_unsubscribe_event = v4l2_event_unsubscribe,
2010};
2011
2012static const struct video_device gspca_template = {
2013        .name = "gspca main driver",
2014        .fops = &dev_fops,
2015        .ioctl_ops = &dev_ioctl_ops,
2016        .release = video_device_release_empty, /* We use v4l2_dev.release */
2017};
2018
2019/*
2020 * probe and create a new gspca device
2021 *
2022 * This function must be called by the sub-driver when it is
2023 * called for probing a new device.
2024 */
2025int gspca_dev_probe2(struct usb_interface *intf,
2026                const struct usb_device_id *id,
2027                const struct sd_desc *sd_desc,
2028                int dev_size,
2029                struct module *module)
2030{
2031        struct gspca_dev *gspca_dev;
2032        struct usb_device *dev = interface_to_usbdev(intf);
2033        int ret;
2034
2035        pr_info("%s-" GSPCA_VERSION " probing %04x:%04x\n",
2036                sd_desc->name, id->idVendor, id->idProduct);
2037
2038        /* create the device */
2039        if (dev_size < sizeof *gspca_dev)
2040                dev_size = sizeof *gspca_dev;
2041        gspca_dev = kzalloc(dev_size, GFP_KERNEL);
2042        if (!gspca_dev) {
2043                pr_err("couldn't kzalloc gspca struct\n");
2044                return -ENOMEM;
2045        }
2046        gspca_dev->usb_buf = kmalloc(USB_BUF_SZ, GFP_KERNEL);
2047        if (!gspca_dev->usb_buf) {
2048                pr_err("out of memory\n");
2049                ret = -ENOMEM;
2050                goto out;
2051        }
2052        gspca_dev->dev = dev;
2053        gspca_dev->iface = intf->cur_altsetting->desc.bInterfaceNumber;
2054        gspca_dev->xfer_ep = -1;
2055
2056        /* check if any audio device */
2057        if (dev->actconfig->desc.bNumInterfaces != 1) {
2058                int i;
2059                struct usb_interface *intf2;
2060
2061                for (i = 0; i < dev->actconfig->desc.bNumInterfaces; i++) {
2062                        intf2 = dev->actconfig->interface[i];
2063                        if (intf2 != NULL
2064                         && intf2->altsetting != NULL
2065                         && intf2->altsetting->desc.bInterfaceClass ==
2066                                         USB_CLASS_AUDIO) {
2067                                gspca_dev->audio = 1;
2068                                break;
2069                        }
2070                }
2071        }
2072
2073        gspca_dev->v4l2_dev.release = gspca_release;
2074        ret = v4l2_device_register(&intf->dev, &gspca_dev->v4l2_dev);
2075        if (ret)
2076                goto out;
2077        gspca_dev->sd_desc = sd_desc;
2078        gspca_dev->nbufread = 2;
2079        gspca_dev->empty_packet = -1;   /* don't check the empty packets */
2080        gspca_dev->vdev = gspca_template;
2081        gspca_dev->vdev.v4l2_dev = &gspca_dev->v4l2_dev;
2082        video_set_drvdata(&gspca_dev->vdev, gspca_dev);
2083        gspca_dev->module = module;
2084        gspca_dev->present = 1;
2085
2086        mutex_init(&gspca_dev->usb_lock);
2087        gspca_dev->vdev.lock = &gspca_dev->usb_lock;
2088        mutex_init(&gspca_dev->queue_lock);
2089        init_waitqueue_head(&gspca_dev->wq);
2090
2091        /* configure the subdriver and initialize the USB device */
2092        ret = sd_desc->config(gspca_dev, id);
2093        if (ret < 0)
2094                goto out;
2095        ret = sd_desc->init(gspca_dev);
2096        if (ret < 0)
2097                goto out;
2098        if (sd_desc->init_controls)
2099                ret = sd_desc->init_controls(gspca_dev);
2100        if (ret < 0)
2101                goto out;
2102        gspca_set_default_mode(gspca_dev);
2103
2104        ret = gspca_input_connect(gspca_dev);
2105        if (ret)
2106                goto out;
2107
2108        /*
2109         * Don't take usb_lock for these ioctls. This improves latency if
2110         * usb_lock is taken for a long time, e.g. when changing a control
2111         * value, and a new frame is ready to be dequeued.
2112         */
2113        v4l2_disable_ioctl_locking(&gspca_dev->vdev, VIDIOC_DQBUF);
2114        v4l2_disable_ioctl_locking(&gspca_dev->vdev, VIDIOC_QBUF);
2115        v4l2_disable_ioctl_locking(&gspca_dev->vdev, VIDIOC_QUERYBUF);
2116#ifdef CONFIG_VIDEO_ADV_DEBUG
2117        if (!gspca_dev->sd_desc->get_register)
2118                v4l2_disable_ioctl(&gspca_dev->vdev, VIDIOC_DBG_G_REGISTER);
2119        if (!gspca_dev->sd_desc->set_register)
2120                v4l2_disable_ioctl(&gspca_dev->vdev, VIDIOC_DBG_S_REGISTER);
2121#endif
2122        if (!gspca_dev->sd_desc->get_jcomp)
2123                v4l2_disable_ioctl(&gspca_dev->vdev, VIDIOC_G_JPEGCOMP);
2124        if (!gspca_dev->sd_desc->set_jcomp)
2125                v4l2_disable_ioctl(&gspca_dev->vdev, VIDIOC_S_JPEGCOMP);
2126
2127        /* init video stuff */
2128        ret = video_register_device(&gspca_dev->vdev,
2129                                  VFL_TYPE_GRABBER,
2130                                  -1);
2131        if (ret < 0) {
2132                pr_err("video_register_device err %d\n", ret);
2133                goto out;
2134        }
2135
2136        usb_set_intfdata(intf, gspca_dev);
2137        PDEBUG(D_PROBE, "%s created", video_device_node_name(&gspca_dev->vdev));
2138
2139        gspca_input_create_urb(gspca_dev);
2140
2141        return 0;
2142out:
2143#if IS_ENABLED(CONFIG_INPUT)
2144        if (gspca_dev->input_dev)
2145                input_unregister_device(gspca_dev->input_dev);
2146#endif
2147        v4l2_ctrl_handler_free(gspca_dev->vdev.ctrl_handler);
2148        kfree(gspca_dev->usb_buf);
2149        kfree(gspca_dev);
2150        return ret;
2151}
2152EXPORT_SYMBOL(gspca_dev_probe2);
2153
2154/* same function as the previous one, but check the interface */
2155int gspca_dev_probe(struct usb_interface *intf,
2156                const struct usb_device_id *id,
2157                const struct sd_desc *sd_desc,
2158                int dev_size,
2159                struct module *module)
2160{
2161        struct usb_device *dev = interface_to_usbdev(intf);
2162
2163        /* we don't handle multi-config cameras */
2164        if (dev->descriptor.bNumConfigurations != 1) {
2165                pr_err("%04x:%04x too many config\n",
2166                       id->idVendor, id->idProduct);
2167                return -ENODEV;
2168        }
2169
2170        /* the USB video interface must be the first one */
2171        if (dev->actconfig->desc.bNumInterfaces != 1
2172         && intf->cur_altsetting->desc.bInterfaceNumber != 0)
2173                return -ENODEV;
2174
2175        return gspca_dev_probe2(intf, id, sd_desc, dev_size, module);
2176}
2177EXPORT_SYMBOL(gspca_dev_probe);
2178
2179/*
2180 * USB disconnection
2181 *
2182 * This function must be called by the sub-driver
2183 * when the device disconnects, after the specific resources are freed.
2184 */
2185void gspca_disconnect(struct usb_interface *intf)
2186{
2187        struct gspca_dev *gspca_dev = usb_get_intfdata(intf);
2188#if IS_ENABLED(CONFIG_INPUT)
2189        struct input_dev *input_dev;
2190#endif
2191
2192        PDEBUG(D_PROBE, "%s disconnect",
2193                video_device_node_name(&gspca_dev->vdev));
2194
2195        mutex_lock(&gspca_dev->usb_lock);
2196
2197        gspca_dev->present = 0;
2198        destroy_urbs(gspca_dev);
2199
2200#if IS_ENABLED(CONFIG_INPUT)
2201        gspca_input_destroy_urb(gspca_dev);
2202        input_dev = gspca_dev->input_dev;
2203        if (input_dev) {
2204                gspca_dev->input_dev = NULL;
2205                input_unregister_device(input_dev);
2206        }
2207#endif
2208        /* Free subdriver's streaming resources / stop sd workqueue(s) */
2209        if (gspca_dev->sd_desc->stop0 && gspca_dev->streaming)
2210                gspca_dev->sd_desc->stop0(gspca_dev);
2211        gspca_dev->streaming = 0;
2212        gspca_dev->dev = NULL;
2213        wake_up_interruptible(&gspca_dev->wq);
2214
2215        v4l2_device_disconnect(&gspca_dev->v4l2_dev);
2216        video_unregister_device(&gspca_dev->vdev);
2217
2218        mutex_unlock(&gspca_dev->usb_lock);
2219
2220        /* (this will call gspca_release() immediately or on last close) */
2221        v4l2_device_put(&gspca_dev->v4l2_dev);
2222}
2223EXPORT_SYMBOL(gspca_disconnect);
2224
2225#ifdef CONFIG_PM
2226int gspca_suspend(struct usb_interface *intf, pm_message_t message)
2227{
2228        struct gspca_dev *gspca_dev = usb_get_intfdata(intf);
2229
2230        gspca_input_destroy_urb(gspca_dev);
2231
2232        if (!gspca_dev->streaming)
2233                return 0;
2234
2235        mutex_lock(&gspca_dev->usb_lock);
2236        gspca_dev->frozen = 1;          /* avoid urb error messages */
2237        gspca_dev->usb_err = 0;
2238        if (gspca_dev->sd_desc->stopN)
2239                gspca_dev->sd_desc->stopN(gspca_dev);
2240        destroy_urbs(gspca_dev);
2241        gspca_set_alt0(gspca_dev);
2242        if (gspca_dev->sd_desc->stop0)
2243                gspca_dev->sd_desc->stop0(gspca_dev);
2244        mutex_unlock(&gspca_dev->usb_lock);
2245
2246        return 0;
2247}
2248EXPORT_SYMBOL(gspca_suspend);
2249
2250int gspca_resume(struct usb_interface *intf)
2251{
2252        struct gspca_dev *gspca_dev = usb_get_intfdata(intf);
2253        int streaming, ret = 0;
2254
2255        mutex_lock(&gspca_dev->usb_lock);
2256        gspca_dev->frozen = 0;
2257        gspca_dev->usb_err = 0;
2258        gspca_dev->sd_desc->init(gspca_dev);
2259        /*
2260         * Most subdrivers send all ctrl values on sd_start and thus
2261         * only write to the device registers on s_ctrl when streaming ->
2262         * Clear streaming to avoid setting all ctrls twice.
2263         */
2264        streaming = gspca_dev->streaming;
2265        gspca_dev->streaming = 0;
2266        if (streaming)
2267                ret = gspca_init_transfer(gspca_dev);
2268        else
2269                gspca_input_create_urb(gspca_dev);
2270        mutex_unlock(&gspca_dev->usb_lock);
2271
2272        return ret;
2273}
2274EXPORT_SYMBOL(gspca_resume);
2275#endif
2276
2277/* -- module insert / remove -- */
2278static int __init gspca_init(void)
2279{
2280        pr_info("v" GSPCA_VERSION " registered\n");
2281        return 0;
2282}
2283static void __exit gspca_exit(void)
2284{
2285}
2286
2287module_init(gspca_init);
2288module_exit(gspca_exit);
2289
2290module_param_named(debug, gspca_debug, int, 0644);
2291MODULE_PARM_DESC(debug,
2292                "1:probe 2:config 3:stream 4:frame 5:packet 6:usbi 7:usbo");
2293