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                frame->v4l2_buf.timestamp = ktime_to_timeval(ktime_get());
 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 = 0;
 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                        pr_err("usb_alloc_urb failed\n");
 800                        return -ENOMEM;
 801                }
 802                gspca_dev->urb[n] = urb;
 803                urb->transfer_buffer = usb_alloc_coherent(gspca_dev->dev,
 804                                                bsize,
 805                                                GFP_KERNEL,
 806                                                &urb->transfer_dma);
 807
 808                if (urb->transfer_buffer == NULL) {
 809                        pr_err("usb_alloc_coherent failed\n");
 810                        return -ENOMEM;
 811                }
 812                urb->dev = gspca_dev->dev;
 813                urb->context = gspca_dev;
 814                urb->transfer_buffer_length = bsize;
 815                if (npkt != 0) {                /* ISOC */
 816                        urb->pipe = usb_rcvisocpipe(gspca_dev->dev,
 817                                                    ep->desc.bEndpointAddress);
 818                        urb->transfer_flags = URB_ISO_ASAP
 819                                        | URB_NO_TRANSFER_DMA_MAP;
 820                        urb->interval = 1 << (ep->desc.bInterval - 1);
 821                        urb->complete = isoc_irq;
 822                        urb->number_of_packets = npkt;
 823                        for (i = 0; i < npkt; i++) {
 824                                urb->iso_frame_desc[i].length = psize;
 825                                urb->iso_frame_desc[i].offset = psize * i;
 826                        }
 827                } else {                /* bulk */
 828                        urb->pipe = usb_rcvbulkpipe(gspca_dev->dev,
 829                                                ep->desc.bEndpointAddress);
 830                        urb->transfer_flags = URB_NO_TRANSFER_DMA_MAP;
 831                        urb->complete = bulk_irq;
 832                }
 833        }
 834        return 0;
 835}
 836
 837/*
 838 * start the USB transfer
 839 */
 840static int gspca_init_transfer(struct gspca_dev *gspca_dev)
 841{
 842        struct usb_interface *intf;
 843        struct usb_host_endpoint *ep;
 844        struct urb *urb;
 845        struct ep_tb_s ep_tb[MAX_ALT];
 846        int n, ret, xfer, alt, alt_idx;
 847
 848        /* reset the streaming variables */
 849        gspca_dev->image = NULL;
 850        gspca_dev->image_len = 0;
 851        gspca_dev->last_packet_type = DISCARD_PACKET;
 852        gspca_dev->sequence = 0;
 853
 854        gspca_dev->usb_err = 0;
 855
 856        /* do the specific subdriver stuff before endpoint selection */
 857        intf = usb_ifnum_to_if(gspca_dev->dev, gspca_dev->iface);
 858        gspca_dev->alt = gspca_dev->cam.bulk ? intf->num_altsetting : 0;
 859        if (gspca_dev->sd_desc->isoc_init) {
 860                ret = gspca_dev->sd_desc->isoc_init(gspca_dev);
 861                if (ret < 0)
 862                        return ret;
 863        }
 864        xfer = gspca_dev->cam.bulk ? USB_ENDPOINT_XFER_BULK
 865                                   : USB_ENDPOINT_XFER_ISOC;
 866
 867        /* if bulk or the subdriver forced an altsetting, get the endpoint */
 868        if (gspca_dev->alt != 0) {
 869                gspca_dev->alt--;       /* (previous version compatibility) */
 870                ep = alt_xfer(&intf->altsetting[gspca_dev->alt], xfer,
 871                              gspca_dev->xfer_ep);
 872                if (ep == NULL) {
 873                        pr_err("bad altsetting %d\n", gspca_dev->alt);
 874                        return -EIO;
 875                }
 876                ep_tb[0].alt = gspca_dev->alt;
 877                alt_idx = 1;
 878        } else {
 879
 880        /* else, compute the minimum bandwidth
 881         * and build the endpoint table */
 882                alt_idx = build_isoc_ep_tb(gspca_dev, intf, ep_tb);
 883                if (alt_idx <= 0) {
 884                        pr_err("no transfer endpoint found\n");
 885                        return -EIO;
 886                }
 887        }
 888
 889        /* set the highest alternate setting and
 890         * loop until urb submit succeeds */
 891        gspca_input_destroy_urb(gspca_dev);
 892
 893        gspca_dev->alt = ep_tb[--alt_idx].alt;
 894        alt = -1;
 895        for (;;) {
 896                if (alt != gspca_dev->alt) {
 897                        alt = gspca_dev->alt;
 898                        if (intf->num_altsetting > 1) {
 899                                ret = usb_set_interface(gspca_dev->dev,
 900                                                        gspca_dev->iface,
 901                                                        alt);
 902                                if (ret < 0) {
 903                                        if (ret == -ENOSPC)
 904                                                goto retry; /*fixme: ugly*/
 905                                        pr_err("set alt %d err %d\n", alt, ret);
 906                                        goto out;
 907                                }
 908                        }
 909                }
 910                if (!gspca_dev->cam.no_urb_create) {
 911                        PDEBUG(D_STREAM, "init transfer alt %d", alt);
 912                        ret = create_urbs(gspca_dev,
 913                                alt_xfer(&intf->altsetting[alt], xfer,
 914                                         gspca_dev->xfer_ep));
 915                        if (ret < 0) {
 916                                destroy_urbs(gspca_dev);
 917                                goto out;
 918                        }
 919                }
 920
 921                /* clear the bulk endpoint */
 922                if (gspca_dev->cam.bulk)
 923                        usb_clear_halt(gspca_dev->dev,
 924                                        gspca_dev->urb[0]->pipe);
 925
 926                /* start the cam */
 927                ret = gspca_dev->sd_desc->start(gspca_dev);
 928                if (ret < 0) {
 929                        destroy_urbs(gspca_dev);
 930                        goto out;
 931                }
 932                gspca_dev->streaming = 1;
 933                v4l2_ctrl_handler_setup(gspca_dev->vdev.ctrl_handler);
 934
 935                /* some bulk transfers are started by the subdriver */
 936                if (gspca_dev->cam.bulk && gspca_dev->cam.bulk_nurbs == 0)
 937                        break;
 938
 939                /* submit the URBs */
 940                for (n = 0; n < MAX_NURBS; n++) {
 941                        urb = gspca_dev->urb[n];
 942                        if (urb == NULL)
 943                                break;
 944                        ret = usb_submit_urb(urb, GFP_KERNEL);
 945                        if (ret < 0)
 946                                break;
 947                }
 948                if (ret >= 0)
 949                        break;                  /* transfer is started */
 950
 951                /* something when wrong
 952                 * stop the webcam and free the transfer resources */
 953                gspca_stream_off(gspca_dev);
 954                if (ret != -ENOSPC) {
 955                        pr_err("usb_submit_urb alt %d err %d\n",
 956                               gspca_dev->alt, ret);
 957                        goto out;
 958                }
 959
 960                /* the bandwidth is not wide enough
 961                 * negotiate or try a lower alternate setting */
 962retry:
 963                PERR("alt %d - bandwidth not wide enough, trying again", alt);
 964                msleep(20);     /* wait for kill complete */
 965                if (gspca_dev->sd_desc->isoc_nego) {
 966                        ret = gspca_dev->sd_desc->isoc_nego(gspca_dev);
 967                        if (ret < 0)
 968                                goto out;
 969                } else {
 970                        if (alt_idx <= 0) {
 971                                pr_err("no transfer endpoint found\n");
 972                                ret = -EIO;
 973                                goto out;
 974                        }
 975                        gspca_dev->alt = ep_tb[--alt_idx].alt;
 976                }
 977        }
 978out:
 979        gspca_input_create_urb(gspca_dev);
 980        return ret;
 981}
 982
 983static void gspca_set_default_mode(struct gspca_dev *gspca_dev)
 984{
 985        int i;
 986
 987        i = gspca_dev->cam.nmodes - 1;  /* take the highest mode */
 988        gspca_dev->curr_mode = i;
 989        gspca_dev->pixfmt = gspca_dev->cam.cam_mode[i];
 990
 991        /* does nothing if ctrl_handler == NULL */
 992        v4l2_ctrl_handler_setup(gspca_dev->vdev.ctrl_handler);
 993}
 994
 995static int wxh_to_mode(struct gspca_dev *gspca_dev,
 996                        int width, int height)
 997{
 998        int i;
 999
1000        for (i = gspca_dev->cam.nmodes; --i > 0; ) {
1001                if (width >= gspca_dev->cam.cam_mode[i].width
1002                    && height >= gspca_dev->cam.cam_mode[i].height)
1003                        break;
1004        }
1005        return i;
1006}
1007
1008/*
1009 * search a mode with the right pixel format
1010 */
1011static int gspca_get_mode(struct gspca_dev *gspca_dev,
1012                        int mode,
1013                        int pixfmt)
1014{
1015        int modeU, modeD;
1016
1017        modeU = modeD = mode;
1018        while ((modeU < gspca_dev->cam.nmodes) || modeD >= 0) {
1019                if (--modeD >= 0) {
1020                        if (gspca_dev->cam.cam_mode[modeD].pixelformat
1021                                                                == pixfmt)
1022                                return modeD;
1023                }
1024                if (++modeU < gspca_dev->cam.nmodes) {
1025                        if (gspca_dev->cam.cam_mode[modeU].pixelformat
1026                                                                == pixfmt)
1027                                return modeU;
1028                }
1029        }
1030        return -EINVAL;
1031}
1032
1033#ifdef CONFIG_VIDEO_ADV_DEBUG
1034static int vidioc_g_chip_info(struct file *file, void *priv,
1035                                struct v4l2_dbg_chip_info *chip)
1036{
1037        struct gspca_dev *gspca_dev = video_drvdata(file);
1038
1039        gspca_dev->usb_err = 0;
1040        if (gspca_dev->sd_desc->get_chip_info)
1041                return gspca_dev->sd_desc->get_chip_info(gspca_dev, chip);
1042        return chip->match.addr ? -EINVAL : 0;
1043}
1044
1045static int vidioc_g_register(struct file *file, void *priv,
1046                struct v4l2_dbg_register *reg)
1047{
1048        struct gspca_dev *gspca_dev = video_drvdata(file);
1049
1050        gspca_dev->usb_err = 0;
1051        return gspca_dev->sd_desc->get_register(gspca_dev, reg);
1052}
1053
1054static int vidioc_s_register(struct file *file, void *priv,
1055                const struct v4l2_dbg_register *reg)
1056{
1057        struct gspca_dev *gspca_dev = video_drvdata(file);
1058
1059        gspca_dev->usb_err = 0;
1060        return gspca_dev->sd_desc->set_register(gspca_dev, reg);
1061}
1062#endif
1063
1064static int vidioc_enum_fmt_vid_cap(struct file *file, void  *priv,
1065                                struct v4l2_fmtdesc *fmtdesc)
1066{
1067        struct gspca_dev *gspca_dev = video_drvdata(file);
1068        int i, j, index;
1069        __u32 fmt_tb[8];
1070
1071        /* give an index to each format */
1072        index = 0;
1073        j = 0;
1074        for (i = gspca_dev->cam.nmodes; --i >= 0; ) {
1075                fmt_tb[index] = gspca_dev->cam.cam_mode[i].pixelformat;
1076                j = 0;
1077                for (;;) {
1078                        if (fmt_tb[j] == fmt_tb[index])
1079                                break;
1080                        j++;
1081                }
1082                if (j == index) {
1083                        if (fmtdesc->index == index)
1084                                break;          /* new format */
1085                        index++;
1086                        if (index >= ARRAY_SIZE(fmt_tb))
1087                                return -EINVAL;
1088                }
1089        }
1090        if (i < 0)
1091                return -EINVAL;         /* no more format */
1092
1093        fmtdesc->pixelformat = fmt_tb[index];
1094        if (gspca_dev->cam.cam_mode[i].sizeimage <
1095                        gspca_dev->cam.cam_mode[i].width *
1096                                gspca_dev->cam.cam_mode[i].height)
1097                fmtdesc->flags = V4L2_FMT_FLAG_COMPRESSED;
1098        fmtdesc->description[0] = fmtdesc->pixelformat & 0xff;
1099        fmtdesc->description[1] = (fmtdesc->pixelformat >> 8) & 0xff;
1100        fmtdesc->description[2] = (fmtdesc->pixelformat >> 16) & 0xff;
1101        fmtdesc->description[3] = fmtdesc->pixelformat >> 24;
1102        fmtdesc->description[4] = '\0';
1103        return 0;
1104}
1105
1106static int vidioc_g_fmt_vid_cap(struct file *file, void *priv,
1107                            struct v4l2_format *fmt)
1108{
1109        struct gspca_dev *gspca_dev = video_drvdata(file);
1110
1111        fmt->fmt.pix = gspca_dev->pixfmt;
1112        /* some drivers use priv internally, zero it before giving it back to
1113           the core */
1114        fmt->fmt.pix.priv = 0;
1115        return 0;
1116}
1117
1118static int try_fmt_vid_cap(struct gspca_dev *gspca_dev,
1119                        struct v4l2_format *fmt)
1120{
1121        int w, h, mode, mode2;
1122
1123        w = fmt->fmt.pix.width;
1124        h = fmt->fmt.pix.height;
1125
1126        PDEBUG_MODE(gspca_dev, D_CONF, "try fmt cap",
1127                    fmt->fmt.pix.pixelformat, w, h);
1128
1129        /* search the closest mode for width and height */
1130        mode = wxh_to_mode(gspca_dev, w, h);
1131
1132        /* OK if right palette */
1133        if (gspca_dev->cam.cam_mode[mode].pixelformat
1134                                                != fmt->fmt.pix.pixelformat) {
1135
1136                /* else, search the closest mode with the same pixel format */
1137                mode2 = gspca_get_mode(gspca_dev, mode,
1138                                        fmt->fmt.pix.pixelformat);
1139                if (mode2 >= 0)
1140                        mode = mode2;
1141        }
1142        fmt->fmt.pix = gspca_dev->cam.cam_mode[mode];
1143        if (gspca_dev->sd_desc->try_fmt) {
1144                /* pass original resolution to subdriver try_fmt */
1145                fmt->fmt.pix.width = w;
1146                fmt->fmt.pix.height = h;
1147                gspca_dev->sd_desc->try_fmt(gspca_dev, fmt);
1148        }
1149        /* some drivers use priv internally, zero it before giving it back to
1150           the core */
1151        fmt->fmt.pix.priv = 0;
1152        return mode;                    /* used when s_fmt */
1153}
1154
1155static int vidioc_try_fmt_vid_cap(struct file *file,
1156                              void *priv,
1157                              struct v4l2_format *fmt)
1158{
1159        struct gspca_dev *gspca_dev = video_drvdata(file);
1160        int ret;
1161
1162        ret = try_fmt_vid_cap(gspca_dev, fmt);
1163        if (ret < 0)
1164                return ret;
1165        return 0;
1166}
1167
1168static int vidioc_s_fmt_vid_cap(struct file *file, void *priv,
1169                            struct v4l2_format *fmt)
1170{
1171        struct gspca_dev *gspca_dev = video_drvdata(file);
1172        int ret;
1173
1174        if (mutex_lock_interruptible(&gspca_dev->queue_lock))
1175                return -ERESTARTSYS;
1176
1177        ret = try_fmt_vid_cap(gspca_dev, fmt);
1178        if (ret < 0)
1179                goto out;
1180
1181        if (gspca_dev->nframes != 0
1182            && fmt->fmt.pix.sizeimage > gspca_dev->frsz) {
1183                ret = -EINVAL;
1184                goto out;
1185        }
1186
1187        if (gspca_dev->streaming) {
1188                ret = -EBUSY;
1189                goto out;
1190        }
1191        gspca_dev->curr_mode = ret;
1192        if (gspca_dev->sd_desc->try_fmt)
1193                /* subdriver try_fmt can modify format parameters */
1194                gspca_dev->pixfmt = fmt->fmt.pix;
1195        else
1196                gspca_dev->pixfmt = gspca_dev->cam.cam_mode[ret];
1197
1198        ret = 0;
1199out:
1200        mutex_unlock(&gspca_dev->queue_lock);
1201        return ret;
1202}
1203
1204static int vidioc_enum_framesizes(struct file *file, void *priv,
1205                                  struct v4l2_frmsizeenum *fsize)
1206{
1207        struct gspca_dev *gspca_dev = video_drvdata(file);
1208        int i;
1209        __u32 index = 0;
1210
1211        if (gspca_dev->sd_desc->enum_framesizes)
1212                return gspca_dev->sd_desc->enum_framesizes(gspca_dev, fsize);
1213
1214        for (i = 0; i < gspca_dev->cam.nmodes; i++) {
1215                if (fsize->pixel_format !=
1216                                gspca_dev->cam.cam_mode[i].pixelformat)
1217                        continue;
1218
1219                if (fsize->index == index) {
1220                        fsize->type = V4L2_FRMSIZE_TYPE_DISCRETE;
1221                        fsize->discrete.width =
1222                                gspca_dev->cam.cam_mode[i].width;
1223                        fsize->discrete.height =
1224                                gspca_dev->cam.cam_mode[i].height;
1225                        return 0;
1226                }
1227                index++;
1228        }
1229
1230        return -EINVAL;
1231}
1232
1233static int vidioc_enum_frameintervals(struct file *filp, void *priv,
1234                                      struct v4l2_frmivalenum *fival)
1235{
1236        struct gspca_dev *gspca_dev = video_drvdata(filp);
1237        int mode = wxh_to_mode(gspca_dev, fival->width, fival->height);
1238        __u32 i;
1239
1240        if (gspca_dev->cam.mode_framerates == NULL ||
1241                        gspca_dev->cam.mode_framerates[mode].nrates == 0)
1242                return -EINVAL;
1243
1244        if (fival->pixel_format !=
1245                        gspca_dev->cam.cam_mode[mode].pixelformat)
1246                return -EINVAL;
1247
1248        for (i = 0; i < gspca_dev->cam.mode_framerates[mode].nrates; i++) {
1249                if (fival->index == i) {
1250                        fival->type = V4L2_FRMSIZE_TYPE_DISCRETE;
1251                        fival->discrete.numerator = 1;
1252                        fival->discrete.denominator =
1253                                gspca_dev->cam.mode_framerates[mode].rates[i];
1254                        return 0;
1255                }
1256        }
1257
1258        return -EINVAL;
1259}
1260
1261static void gspca_release(struct v4l2_device *v4l2_device)
1262{
1263        struct gspca_dev *gspca_dev =
1264                container_of(v4l2_device, struct gspca_dev, v4l2_dev);
1265
1266        v4l2_ctrl_handler_free(gspca_dev->vdev.ctrl_handler);
1267        v4l2_device_unregister(&gspca_dev->v4l2_dev);
1268        kfree(gspca_dev->usb_buf);
1269        kfree(gspca_dev);
1270}
1271
1272static int dev_open(struct file *file)
1273{
1274        struct gspca_dev *gspca_dev = video_drvdata(file);
1275        int ret;
1276
1277        PDEBUG(D_STREAM, "[%s] open", current->comm);
1278
1279        /* protect the subdriver against rmmod */
1280        if (!try_module_get(gspca_dev->module))
1281                return -ENODEV;
1282
1283        ret = v4l2_fh_open(file);
1284        if (ret)
1285                module_put(gspca_dev->module);
1286        return ret;
1287}
1288
1289static int dev_close(struct file *file)
1290{
1291        struct gspca_dev *gspca_dev = video_drvdata(file);
1292
1293        PDEBUG(D_STREAM, "[%s] close", current->comm);
1294
1295        /* Needed for gspca_stream_off, always lock before queue_lock! */
1296        if (mutex_lock_interruptible(&gspca_dev->usb_lock))
1297                return -ERESTARTSYS;
1298
1299        if (mutex_lock_interruptible(&gspca_dev->queue_lock)) {
1300                mutex_unlock(&gspca_dev->usb_lock);
1301                return -ERESTARTSYS;
1302        }
1303
1304        /* if the file did the capture, free the streaming resources */
1305        if (gspca_dev->capt_file == file) {
1306                if (gspca_dev->streaming)
1307                        gspca_stream_off(gspca_dev);
1308                frame_free(gspca_dev);
1309        }
1310        module_put(gspca_dev->module);
1311        mutex_unlock(&gspca_dev->queue_lock);
1312        mutex_unlock(&gspca_dev->usb_lock);
1313
1314        PDEBUG(D_STREAM, "close done");
1315
1316        return v4l2_fh_release(file);
1317}
1318
1319static int vidioc_querycap(struct file *file, void  *priv,
1320                           struct v4l2_capability *cap)
1321{
1322        struct gspca_dev *gspca_dev = video_drvdata(file);
1323
1324        strlcpy((char *) cap->driver, gspca_dev->sd_desc->name,
1325                        sizeof cap->driver);
1326        if (gspca_dev->dev->product != NULL) {
1327                strlcpy((char *) cap->card, gspca_dev->dev->product,
1328                        sizeof cap->card);
1329        } else {
1330                snprintf((char *) cap->card, sizeof cap->card,
1331                        "USB Camera (%04x:%04x)",
1332                        le16_to_cpu(gspca_dev->dev->descriptor.idVendor),
1333                        le16_to_cpu(gspca_dev->dev->descriptor.idProduct));
1334        }
1335        usb_make_path(gspca_dev->dev, (char *) cap->bus_info,
1336                        sizeof(cap->bus_info));
1337        cap->device_caps = V4L2_CAP_VIDEO_CAPTURE
1338                          | V4L2_CAP_STREAMING
1339                          | V4L2_CAP_READWRITE;
1340        cap->capabilities = cap->device_caps | V4L2_CAP_DEVICE_CAPS;
1341        return 0;
1342}
1343
1344static int vidioc_enum_input(struct file *file, void *priv,
1345                                struct v4l2_input *input)
1346{
1347        struct gspca_dev *gspca_dev = video_drvdata(file);
1348
1349        if (input->index != 0)
1350                return -EINVAL;
1351        input->type = V4L2_INPUT_TYPE_CAMERA;
1352        input->status = gspca_dev->cam.input_flags;
1353        strlcpy(input->name, gspca_dev->sd_desc->name,
1354                sizeof input->name);
1355        return 0;
1356}
1357
1358static int vidioc_g_input(struct file *file, void *priv, unsigned int *i)
1359{
1360        *i = 0;
1361        return 0;
1362}
1363
1364static int vidioc_s_input(struct file *file, void *priv, unsigned int i)
1365{
1366        if (i > 0)
1367                return -EINVAL;
1368        return (0);
1369}
1370
1371static int vidioc_reqbufs(struct file *file, void *priv,
1372                          struct v4l2_requestbuffers *rb)
1373{
1374        struct gspca_dev *gspca_dev = video_drvdata(file);
1375        int i, ret = 0, streaming;
1376
1377        i = rb->memory;                 /* (avoid compilation warning) */
1378        switch (i) {
1379        case GSPCA_MEMORY_READ:                 /* (internal call) */
1380        case V4L2_MEMORY_MMAP:
1381        case V4L2_MEMORY_USERPTR:
1382                break;
1383        default:
1384                return -EINVAL;
1385        }
1386        if (mutex_lock_interruptible(&gspca_dev->queue_lock))
1387                return -ERESTARTSYS;
1388
1389        if (gspca_dev->memory != GSPCA_MEMORY_NO
1390            && gspca_dev->memory != GSPCA_MEMORY_READ
1391            && gspca_dev->memory != rb->memory) {
1392                ret = -EBUSY;
1393                goto out;
1394        }
1395
1396        /* only one file may do the capture */
1397        if (gspca_dev->capt_file != NULL
1398            && gspca_dev->capt_file != file) {
1399                ret = -EBUSY;
1400                goto out;
1401        }
1402
1403        /* if allocated, the buffers must not be mapped */
1404        for (i = 0; i < gspca_dev->nframes; i++) {
1405                if (gspca_dev->frame[i].vma_use_count) {
1406                        ret = -EBUSY;
1407                        goto out;
1408                }
1409        }
1410
1411        /* stop streaming */
1412        streaming = gspca_dev->streaming;
1413        if (streaming) {
1414                gspca_stream_off(gspca_dev);
1415
1416                /* Don't restart the stream when switching from read
1417                 * to mmap mode */
1418                if (gspca_dev->memory == GSPCA_MEMORY_READ)
1419                        streaming = 0;
1420        }
1421
1422        /* free the previous allocated buffers, if any */
1423        if (gspca_dev->nframes != 0)
1424                frame_free(gspca_dev);
1425        if (rb->count == 0)                     /* unrequest */
1426                goto out;
1427        ret = frame_alloc(gspca_dev, file, rb->memory, rb->count);
1428        if (ret == 0) {
1429                rb->count = gspca_dev->nframes;
1430                if (streaming)
1431                        ret = gspca_init_transfer(gspca_dev);
1432        }
1433out:
1434        mutex_unlock(&gspca_dev->queue_lock);
1435        PDEBUG(D_STREAM, "reqbufs st:%d c:%d", ret, rb->count);
1436        return ret;
1437}
1438
1439static int vidioc_querybuf(struct file *file, void *priv,
1440                           struct v4l2_buffer *v4l2_buf)
1441{
1442        struct gspca_dev *gspca_dev = video_drvdata(file);
1443        struct gspca_frame *frame;
1444
1445        if (v4l2_buf->index >= gspca_dev->nframes)
1446                return -EINVAL;
1447
1448        frame = &gspca_dev->frame[v4l2_buf->index];
1449        memcpy(v4l2_buf, &frame->v4l2_buf, sizeof *v4l2_buf);
1450        return 0;
1451}
1452
1453static int vidioc_streamon(struct file *file, void *priv,
1454                           enum v4l2_buf_type buf_type)
1455{
1456        struct gspca_dev *gspca_dev = video_drvdata(file);
1457        int ret;
1458
1459        if (buf_type != V4L2_BUF_TYPE_VIDEO_CAPTURE)
1460                return -EINVAL;
1461        if (mutex_lock_interruptible(&gspca_dev->queue_lock))
1462                return -ERESTARTSYS;
1463
1464        /* check the capture file */
1465        if (gspca_dev->capt_file != file) {
1466                ret = -EBUSY;
1467                goto out;
1468        }
1469
1470        if (gspca_dev->nframes == 0
1471            || !(gspca_dev->frame[0].v4l2_buf.flags & V4L2_BUF_FLAG_QUEUED)) {
1472                ret = -EINVAL;
1473                goto out;
1474        }
1475        if (!gspca_dev->streaming) {
1476                ret = gspca_init_transfer(gspca_dev);
1477                if (ret < 0)
1478                        goto out;
1479        }
1480        PDEBUG_MODE(gspca_dev, D_STREAM, "stream on OK",
1481                    gspca_dev->pixfmt.pixelformat,
1482                    gspca_dev->pixfmt.width, gspca_dev->pixfmt.height);
1483        ret = 0;
1484out:
1485        mutex_unlock(&gspca_dev->queue_lock);
1486        return ret;
1487}
1488
1489static int vidioc_streamoff(struct file *file, void *priv,
1490                                enum v4l2_buf_type buf_type)
1491{
1492        struct gspca_dev *gspca_dev = video_drvdata(file);
1493        int i, ret;
1494
1495        if (buf_type != V4L2_BUF_TYPE_VIDEO_CAPTURE)
1496                return -EINVAL;
1497
1498        if (mutex_lock_interruptible(&gspca_dev->queue_lock))
1499                return -ERESTARTSYS;
1500
1501        if (!gspca_dev->streaming) {
1502                ret = 0;
1503                goto out;
1504        }
1505
1506        /* check the capture file */
1507        if (gspca_dev->capt_file != file) {
1508                ret = -EBUSY;
1509                goto out;
1510        }
1511
1512        /* stop streaming */
1513        gspca_stream_off(gspca_dev);
1514        /* In case another thread is waiting in dqbuf */
1515        wake_up_interruptible(&gspca_dev->wq);
1516
1517        /* empty the transfer queues */
1518        for (i = 0; i < gspca_dev->nframes; i++)
1519                gspca_dev->frame[i].v4l2_buf.flags &= ~BUF_ALL_FLAGS;
1520        atomic_set(&gspca_dev->fr_q, 0);
1521        atomic_set(&gspca_dev->fr_i, 0);
1522        gspca_dev->fr_o = 0;
1523        ret = 0;
1524out:
1525        mutex_unlock(&gspca_dev->queue_lock);
1526        return ret;
1527}
1528
1529static int vidioc_g_jpegcomp(struct file *file, void *priv,
1530                        struct v4l2_jpegcompression *jpegcomp)
1531{
1532        struct gspca_dev *gspca_dev = video_drvdata(file);
1533
1534        gspca_dev->usb_err = 0;
1535        return gspca_dev->sd_desc->get_jcomp(gspca_dev, jpegcomp);
1536}
1537
1538static int vidioc_s_jpegcomp(struct file *file, void *priv,
1539                        const struct v4l2_jpegcompression *jpegcomp)
1540{
1541        struct gspca_dev *gspca_dev = video_drvdata(file);
1542
1543        gspca_dev->usb_err = 0;
1544        return gspca_dev->sd_desc->set_jcomp(gspca_dev, jpegcomp);
1545}
1546
1547static int vidioc_g_parm(struct file *filp, void *priv,
1548                        struct v4l2_streamparm *parm)
1549{
1550        struct gspca_dev *gspca_dev = video_drvdata(filp);
1551
1552        parm->parm.capture.readbuffers = gspca_dev->nbufread;
1553
1554        if (gspca_dev->sd_desc->get_streamparm) {
1555                gspca_dev->usb_err = 0;
1556                gspca_dev->sd_desc->get_streamparm(gspca_dev, parm);
1557                return gspca_dev->usb_err;
1558        }
1559        return 0;
1560}
1561
1562static int vidioc_s_parm(struct file *filp, void *priv,
1563                        struct v4l2_streamparm *parm)
1564{
1565        struct gspca_dev *gspca_dev = video_drvdata(filp);
1566        int n;
1567
1568        n = parm->parm.capture.readbuffers;
1569        if (n == 0 || n >= GSPCA_MAX_FRAMES)
1570                parm->parm.capture.readbuffers = gspca_dev->nbufread;
1571        else
1572                gspca_dev->nbufread = n;
1573
1574        if (gspca_dev->sd_desc->set_streamparm) {
1575                gspca_dev->usb_err = 0;
1576                gspca_dev->sd_desc->set_streamparm(gspca_dev, parm);
1577                return gspca_dev->usb_err;
1578        }
1579
1580        return 0;
1581}
1582
1583static int dev_mmap(struct file *file, struct vm_area_struct *vma)
1584{
1585        struct gspca_dev *gspca_dev = video_drvdata(file);
1586        struct gspca_frame *frame;
1587        struct page *page;
1588        unsigned long addr, start, size;
1589        int i, ret;
1590
1591        start = vma->vm_start;
1592        size = vma->vm_end - vma->vm_start;
1593        PDEBUG(D_STREAM, "mmap start:%08x size:%d", (int) start, (int) size);
1594
1595        if (mutex_lock_interruptible(&gspca_dev->queue_lock))
1596                return -ERESTARTSYS;
1597        if (gspca_dev->capt_file != file) {
1598                ret = -EINVAL;
1599                goto out;
1600        }
1601
1602        frame = NULL;
1603        for (i = 0; i < gspca_dev->nframes; ++i) {
1604                if (gspca_dev->frame[i].v4l2_buf.memory != V4L2_MEMORY_MMAP) {
1605                        PDEBUG(D_STREAM, "mmap bad memory type");
1606                        break;
1607                }
1608                if ((gspca_dev->frame[i].v4l2_buf.m.offset >> PAGE_SHIFT)
1609                                                == vma->vm_pgoff) {
1610                        frame = &gspca_dev->frame[i];
1611                        break;
1612                }
1613        }
1614        if (frame == NULL) {
1615                PDEBUG(D_STREAM, "mmap no frame buffer found");
1616                ret = -EINVAL;
1617                goto out;
1618        }
1619        if (size != frame->v4l2_buf.length) {
1620                PDEBUG(D_STREAM, "mmap bad size");
1621                ret = -EINVAL;
1622                goto out;
1623        }
1624
1625        /*
1626         * - VM_IO marks the area as being a mmaped region for I/O to a
1627         *   device. It also prevents the region from being core dumped.
1628         */
1629        vma->vm_flags |= VM_IO;
1630
1631        addr = (unsigned long) frame->data;
1632        while (size > 0) {
1633                page = vmalloc_to_page((void *) addr);
1634                ret = vm_insert_page(vma, start, page);
1635                if (ret < 0)
1636                        goto out;
1637                start += PAGE_SIZE;
1638                addr += PAGE_SIZE;
1639                size -= PAGE_SIZE;
1640        }
1641
1642        vma->vm_ops = &gspca_vm_ops;
1643        vma->vm_private_data = frame;
1644        gspca_vm_open(vma);
1645        ret = 0;
1646out:
1647        mutex_unlock(&gspca_dev->queue_lock);
1648        return ret;
1649}
1650
1651static int frame_ready_nolock(struct gspca_dev *gspca_dev, struct file *file,
1652                                enum v4l2_memory memory)
1653{
1654        if (!gspca_dev->present)
1655                return -ENODEV;
1656        if (gspca_dev->capt_file != file || gspca_dev->memory != memory ||
1657                        !gspca_dev->streaming)
1658                return -EINVAL;
1659
1660        /* check if a frame is ready */
1661        return gspca_dev->fr_o != atomic_read(&gspca_dev->fr_i);
1662}
1663
1664static int frame_ready(struct gspca_dev *gspca_dev, struct file *file,
1665                        enum v4l2_memory memory)
1666{
1667        int ret;
1668
1669        if (mutex_lock_interruptible(&gspca_dev->queue_lock))
1670                return -ERESTARTSYS;
1671        ret = frame_ready_nolock(gspca_dev, file, memory);
1672        mutex_unlock(&gspca_dev->queue_lock);
1673        return ret;
1674}
1675
1676/*
1677 * dequeue a video buffer
1678 *
1679 * If nonblock_ing is false, block until a buffer is available.
1680 */
1681static int vidioc_dqbuf(struct file *file, void *priv,
1682                        struct v4l2_buffer *v4l2_buf)
1683{
1684        struct gspca_dev *gspca_dev = video_drvdata(file);
1685        struct gspca_frame *frame;
1686        int i, j, ret;
1687
1688        PDEBUG(D_FRAM, "dqbuf");
1689
1690        if (mutex_lock_interruptible(&gspca_dev->queue_lock))
1691                return -ERESTARTSYS;
1692
1693        for (;;) {
1694                ret = frame_ready_nolock(gspca_dev, file, v4l2_buf->memory);
1695                if (ret < 0)
1696                        goto out;
1697                if (ret > 0)
1698                        break;
1699
1700                mutex_unlock(&gspca_dev->queue_lock);
1701
1702                if (file->f_flags & O_NONBLOCK)
1703                        return -EAGAIN;
1704
1705                /* wait till a frame is ready */
1706                ret = wait_event_interruptible_timeout(gspca_dev->wq,
1707                        frame_ready(gspca_dev, file, v4l2_buf->memory),
1708                        msecs_to_jiffies(3000));
1709                if (ret < 0)
1710                        return ret;
1711                if (ret == 0)
1712                        return -EIO;
1713
1714                if (mutex_lock_interruptible(&gspca_dev->queue_lock))
1715                        return -ERESTARTSYS;
1716        }
1717
1718        i = gspca_dev->fr_o;
1719        j = gspca_dev->fr_queue[i];
1720        frame = &gspca_dev->frame[j];
1721
1722        gspca_dev->fr_o = (i + 1) % GSPCA_MAX_FRAMES;
1723
1724        frame->v4l2_buf.flags &= ~V4L2_BUF_FLAG_DONE;
1725        memcpy(v4l2_buf, &frame->v4l2_buf, sizeof *v4l2_buf);
1726        PDEBUG(D_FRAM, "dqbuf %d", j);
1727        ret = 0;
1728
1729        if (gspca_dev->memory == V4L2_MEMORY_USERPTR) {
1730                if (copy_to_user((__u8 __user *) frame->v4l2_buf.m.userptr,
1731                                 frame->data,
1732                                 frame->v4l2_buf.bytesused)) {
1733                        PERR("dqbuf cp to user failed");
1734                        ret = -EFAULT;
1735                }
1736        }
1737out:
1738        mutex_unlock(&gspca_dev->queue_lock);
1739
1740        if (ret == 0 && gspca_dev->sd_desc->dq_callback) {
1741                mutex_lock(&gspca_dev->usb_lock);
1742                gspca_dev->usb_err = 0;
1743                if (gspca_dev->present)
1744                        gspca_dev->sd_desc->dq_callback(gspca_dev);
1745                mutex_unlock(&gspca_dev->usb_lock);
1746        }
1747
1748        return ret;
1749}
1750
1751/*
1752 * queue a video buffer
1753 *
1754 * Attempting to queue a buffer that has already been
1755 * queued will return -EINVAL.
1756 */
1757static int vidioc_qbuf(struct file *file, void *priv,
1758                        struct v4l2_buffer *v4l2_buf)
1759{
1760        struct gspca_dev *gspca_dev = video_drvdata(file);
1761        struct gspca_frame *frame;
1762        int i, index, ret;
1763
1764        PDEBUG(D_FRAM, "qbuf %d", v4l2_buf->index);
1765
1766        if (mutex_lock_interruptible(&gspca_dev->queue_lock))
1767                return -ERESTARTSYS;
1768
1769        index = v4l2_buf->index;
1770        if ((unsigned) index >= gspca_dev->nframes) {
1771                PDEBUG(D_FRAM,
1772                        "qbuf idx %d >= %d", index, gspca_dev->nframes);
1773                ret = -EINVAL;
1774                goto out;
1775        }
1776        if (v4l2_buf->memory != gspca_dev->memory) {
1777                PDEBUG(D_FRAM, "qbuf bad memory type");
1778                ret = -EINVAL;
1779                goto out;
1780        }
1781
1782        frame = &gspca_dev->frame[index];
1783        if (frame->v4l2_buf.flags & BUF_ALL_FLAGS) {
1784                PDEBUG(D_FRAM, "qbuf bad state");
1785                ret = -EINVAL;
1786                goto out;
1787        }
1788
1789        frame->v4l2_buf.flags |= V4L2_BUF_FLAG_QUEUED;
1790
1791        if (frame->v4l2_buf.memory == V4L2_MEMORY_USERPTR) {
1792                frame->v4l2_buf.m.userptr = v4l2_buf->m.userptr;
1793                frame->v4l2_buf.length = v4l2_buf->length;
1794        }
1795
1796        /* put the buffer in the 'queued' queue */
1797        i = atomic_read(&gspca_dev->fr_q);
1798        gspca_dev->fr_queue[i] = index;
1799        atomic_set(&gspca_dev->fr_q, (i + 1) % GSPCA_MAX_FRAMES);
1800
1801        v4l2_buf->flags |= V4L2_BUF_FLAG_QUEUED;
1802        v4l2_buf->flags &= ~V4L2_BUF_FLAG_DONE;
1803        ret = 0;
1804out:
1805        mutex_unlock(&gspca_dev->queue_lock);
1806        return ret;
1807}
1808
1809/*
1810 * allocate the resources for read()
1811 */
1812static int read_alloc(struct gspca_dev *gspca_dev,
1813                        struct file *file)
1814{
1815        struct v4l2_buffer v4l2_buf;
1816        int i, ret;
1817
1818        PDEBUG(D_STREAM, "read alloc");
1819
1820        if (mutex_lock_interruptible(&gspca_dev->usb_lock))
1821                return -ERESTARTSYS;
1822
1823        if (gspca_dev->nframes == 0) {
1824                struct v4l2_requestbuffers rb;
1825
1826                memset(&rb, 0, sizeof rb);
1827                rb.count = gspca_dev->nbufread;
1828                rb.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
1829                rb.memory = GSPCA_MEMORY_READ;
1830                ret = vidioc_reqbufs(file, gspca_dev, &rb);
1831                if (ret != 0) {
1832                        PDEBUG(D_STREAM, "read reqbuf err %d", ret);
1833                        goto out;
1834                }
1835                memset(&v4l2_buf, 0, sizeof v4l2_buf);
1836                v4l2_buf.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
1837                v4l2_buf.memory = GSPCA_MEMORY_READ;
1838                for (i = 0; i < gspca_dev->nbufread; i++) {
1839                        v4l2_buf.index = i;
1840                        ret = vidioc_qbuf(file, gspca_dev, &v4l2_buf);
1841                        if (ret != 0) {
1842                                PDEBUG(D_STREAM, "read qbuf err: %d", ret);
1843                                goto out;
1844                        }
1845                }
1846        }
1847
1848        /* start streaming */
1849        ret = vidioc_streamon(file, gspca_dev, V4L2_BUF_TYPE_VIDEO_CAPTURE);
1850        if (ret != 0)
1851                PDEBUG(D_STREAM, "read streamon err %d", ret);
1852out:
1853        mutex_unlock(&gspca_dev->usb_lock);
1854        return ret;
1855}
1856
1857static unsigned int dev_poll(struct file *file, poll_table *wait)
1858{
1859        struct gspca_dev *gspca_dev = video_drvdata(file);
1860        unsigned long req_events = poll_requested_events(wait);
1861        int ret = 0;
1862
1863        PDEBUG(D_FRAM, "poll");
1864
1865        if (req_events & POLLPRI)
1866                ret |= v4l2_ctrl_poll(file, wait);
1867
1868        if (req_events & (POLLIN | POLLRDNORM)) {
1869                /* if reqbufs is not done, the user would use read() */
1870                if (gspca_dev->memory == GSPCA_MEMORY_NO) {
1871                        if (read_alloc(gspca_dev, file) != 0) {
1872                                ret |= POLLERR;
1873                                goto out;
1874                        }
1875                }
1876
1877                poll_wait(file, &gspca_dev->wq, wait);
1878
1879                /* check if an image has been received */
1880                if (mutex_lock_interruptible(&gspca_dev->queue_lock) != 0) {
1881                        ret |= POLLERR;
1882                        goto out;
1883                }
1884                if (gspca_dev->fr_o != atomic_read(&gspca_dev->fr_i))
1885                        ret |= POLLIN | POLLRDNORM;
1886                mutex_unlock(&gspca_dev->queue_lock);
1887        }
1888
1889out:
1890        if (!gspca_dev->present)
1891                ret |= POLLHUP;
1892
1893        return ret;
1894}
1895
1896static ssize_t dev_read(struct file *file, char __user *data,
1897                    size_t count, loff_t *ppos)
1898{
1899        struct gspca_dev *gspca_dev = video_drvdata(file);
1900        struct gspca_frame *frame;
1901        struct v4l2_buffer v4l2_buf;
1902        struct timeval timestamp;
1903        int n, ret, ret2;
1904
1905        PDEBUG(D_FRAM, "read (%zd)", count);
1906        if (gspca_dev->memory == GSPCA_MEMORY_NO) { /* first time ? */
1907                ret = read_alloc(gspca_dev, file);
1908                if (ret != 0)
1909                        return ret;
1910        }
1911
1912        /* get a frame */
1913        timestamp = ktime_to_timeval(ktime_get());
1914        timestamp.tv_sec--;
1915        n = 2;
1916        for (;;) {
1917                memset(&v4l2_buf, 0, sizeof v4l2_buf);
1918                v4l2_buf.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
1919                v4l2_buf.memory = GSPCA_MEMORY_READ;
1920                ret = vidioc_dqbuf(file, gspca_dev, &v4l2_buf);
1921                if (ret != 0) {
1922                        PDEBUG(D_STREAM, "read dqbuf err %d", ret);
1923                        return ret;
1924                }
1925
1926                /* if the process slept for more than 1 second,
1927                 * get a newer frame */
1928                frame = &gspca_dev->frame[v4l2_buf.index];
1929                if (--n < 0)
1930                        break;                  /* avoid infinite loop */
1931                if (frame->v4l2_buf.timestamp.tv_sec >= timestamp.tv_sec)
1932                        break;
1933                ret = vidioc_qbuf(file, gspca_dev, &v4l2_buf);
1934                if (ret != 0) {
1935                        PDEBUG(D_STREAM, "read qbuf err %d", ret);
1936                        return ret;
1937                }
1938        }
1939
1940        /* copy the frame */
1941        if (count > frame->v4l2_buf.bytesused)
1942                count = frame->v4l2_buf.bytesused;
1943        ret = copy_to_user(data, frame->data, count);
1944        if (ret != 0) {
1945                PERR("read cp to user lack %d / %zd", ret, count);
1946                ret = -EFAULT;
1947                goto out;
1948        }
1949        ret = count;
1950out:
1951        /* in each case, requeue the buffer */
1952        ret2 = vidioc_qbuf(file, gspca_dev, &v4l2_buf);
1953        if (ret2 != 0)
1954                return ret2;
1955        return ret;
1956}
1957
1958static struct v4l2_file_operations dev_fops = {
1959        .owner = THIS_MODULE,
1960        .open = dev_open,
1961        .release = dev_close,
1962        .read = dev_read,
1963        .mmap = dev_mmap,
1964        .unlocked_ioctl = video_ioctl2,
1965        .poll   = dev_poll,
1966};
1967
1968static const struct v4l2_ioctl_ops dev_ioctl_ops = {
1969        .vidioc_querycap        = vidioc_querycap,
1970        .vidioc_dqbuf           = vidioc_dqbuf,
1971        .vidioc_qbuf            = vidioc_qbuf,
1972        .vidioc_enum_fmt_vid_cap = vidioc_enum_fmt_vid_cap,
1973        .vidioc_try_fmt_vid_cap = vidioc_try_fmt_vid_cap,
1974        .vidioc_g_fmt_vid_cap   = vidioc_g_fmt_vid_cap,
1975        .vidioc_s_fmt_vid_cap   = vidioc_s_fmt_vid_cap,
1976        .vidioc_streamon        = vidioc_streamon,
1977        .vidioc_enum_input      = vidioc_enum_input,
1978        .vidioc_g_input         = vidioc_g_input,
1979        .vidioc_s_input         = vidioc_s_input,
1980        .vidioc_reqbufs         = vidioc_reqbufs,
1981        .vidioc_querybuf        = vidioc_querybuf,
1982        .vidioc_streamoff       = vidioc_streamoff,
1983        .vidioc_g_jpegcomp      = vidioc_g_jpegcomp,
1984        .vidioc_s_jpegcomp      = vidioc_s_jpegcomp,
1985        .vidioc_g_parm          = vidioc_g_parm,
1986        .vidioc_s_parm          = vidioc_s_parm,
1987        .vidioc_enum_framesizes = vidioc_enum_framesizes,
1988        .vidioc_enum_frameintervals = vidioc_enum_frameintervals,
1989#ifdef CONFIG_VIDEO_ADV_DEBUG
1990        .vidioc_g_chip_info     = vidioc_g_chip_info,
1991        .vidioc_g_register      = vidioc_g_register,
1992        .vidioc_s_register      = vidioc_s_register,
1993#endif
1994        .vidioc_subscribe_event = v4l2_ctrl_subscribe_event,
1995        .vidioc_unsubscribe_event = v4l2_event_unsubscribe,
1996};
1997
1998static const struct video_device gspca_template = {
1999        .name = "gspca main driver",
2000        .fops = &dev_fops,
2001        .ioctl_ops = &dev_ioctl_ops,
2002        .release = video_device_release_empty, /* We use v4l2_dev.release */
2003};
2004
2005/*
2006 * probe and create a new gspca device
2007 *
2008 * This function must be called by the sub-driver when it is
2009 * called for probing a new device.
2010 */
2011int gspca_dev_probe2(struct usb_interface *intf,
2012                const struct usb_device_id *id,
2013                const struct sd_desc *sd_desc,
2014                int dev_size,
2015                struct module *module)
2016{
2017        struct gspca_dev *gspca_dev;
2018        struct usb_device *dev = interface_to_usbdev(intf);
2019        int ret;
2020
2021        pr_info("%s-" GSPCA_VERSION " probing %04x:%04x\n",
2022                sd_desc->name, id->idVendor, id->idProduct);
2023
2024        /* create the device */
2025        if (dev_size < sizeof *gspca_dev)
2026                dev_size = sizeof *gspca_dev;
2027        gspca_dev = kzalloc(dev_size, GFP_KERNEL);
2028        if (!gspca_dev) {
2029                pr_err("couldn't kzalloc gspca struct\n");
2030                return -ENOMEM;
2031        }
2032        gspca_dev->usb_buf = kmalloc(USB_BUF_SZ, GFP_KERNEL);
2033        if (!gspca_dev->usb_buf) {
2034                pr_err("out of memory\n");
2035                ret = -ENOMEM;
2036                goto out;
2037        }
2038        gspca_dev->dev = dev;
2039        gspca_dev->iface = intf->cur_altsetting->desc.bInterfaceNumber;
2040        gspca_dev->xfer_ep = -1;
2041
2042        /* check if any audio device */
2043        if (dev->actconfig->desc.bNumInterfaces != 1) {
2044                int i;
2045                struct usb_interface *intf2;
2046
2047                for (i = 0; i < dev->actconfig->desc.bNumInterfaces; i++) {
2048                        intf2 = dev->actconfig->interface[i];
2049                        if (intf2 != NULL
2050                         && intf2->altsetting != NULL
2051                         && intf2->altsetting->desc.bInterfaceClass ==
2052                                         USB_CLASS_AUDIO) {
2053                                gspca_dev->audio = 1;
2054                                break;
2055                        }
2056                }
2057        }
2058
2059        gspca_dev->v4l2_dev.release = gspca_release;
2060        ret = v4l2_device_register(&intf->dev, &gspca_dev->v4l2_dev);
2061        if (ret)
2062                goto out;
2063        gspca_dev->sd_desc = sd_desc;
2064        gspca_dev->nbufread = 2;
2065        gspca_dev->empty_packet = -1;   /* don't check the empty packets */
2066        gspca_dev->vdev = gspca_template;
2067        gspca_dev->vdev.v4l2_dev = &gspca_dev->v4l2_dev;
2068        video_set_drvdata(&gspca_dev->vdev, gspca_dev);
2069        gspca_dev->module = module;
2070        gspca_dev->present = 1;
2071
2072        mutex_init(&gspca_dev->usb_lock);
2073        gspca_dev->vdev.lock = &gspca_dev->usb_lock;
2074        mutex_init(&gspca_dev->queue_lock);
2075        init_waitqueue_head(&gspca_dev->wq);
2076
2077        /* configure the subdriver and initialize the USB device */
2078        ret = sd_desc->config(gspca_dev, id);
2079        if (ret < 0)
2080                goto out;
2081        ret = sd_desc->init(gspca_dev);
2082        if (ret < 0)
2083                goto out;
2084        if (sd_desc->init_controls)
2085                ret = sd_desc->init_controls(gspca_dev);
2086        if (ret < 0)
2087                goto out;
2088        gspca_set_default_mode(gspca_dev);
2089
2090        ret = gspca_input_connect(gspca_dev);
2091        if (ret)
2092                goto out;
2093
2094        /*
2095         * Don't take usb_lock for these ioctls. This improves latency if
2096         * usb_lock is taken for a long time, e.g. when changing a control
2097         * value, and a new frame is ready to be dequeued.
2098         */
2099        v4l2_disable_ioctl_locking(&gspca_dev->vdev, VIDIOC_DQBUF);
2100        v4l2_disable_ioctl_locking(&gspca_dev->vdev, VIDIOC_QBUF);
2101        v4l2_disable_ioctl_locking(&gspca_dev->vdev, VIDIOC_QUERYBUF);
2102#ifdef CONFIG_VIDEO_ADV_DEBUG
2103        if (!gspca_dev->sd_desc->get_register)
2104                v4l2_disable_ioctl(&gspca_dev->vdev, VIDIOC_DBG_G_REGISTER);
2105        if (!gspca_dev->sd_desc->set_register)
2106                v4l2_disable_ioctl(&gspca_dev->vdev, VIDIOC_DBG_S_REGISTER);
2107#endif
2108        if (!gspca_dev->sd_desc->get_jcomp)
2109                v4l2_disable_ioctl(&gspca_dev->vdev, VIDIOC_G_JPEGCOMP);
2110        if (!gspca_dev->sd_desc->set_jcomp)
2111                v4l2_disable_ioctl(&gspca_dev->vdev, VIDIOC_S_JPEGCOMP);
2112
2113        /* init video stuff */
2114        ret = video_register_device(&gspca_dev->vdev,
2115                                  VFL_TYPE_GRABBER,
2116                                  -1);
2117        if (ret < 0) {
2118                pr_err("video_register_device err %d\n", ret);
2119                goto out;
2120        }
2121
2122        usb_set_intfdata(intf, gspca_dev);
2123        PDEBUG(D_PROBE, "%s created", video_device_node_name(&gspca_dev->vdev));
2124
2125        gspca_input_create_urb(gspca_dev);
2126
2127        return 0;
2128out:
2129#if IS_ENABLED(CONFIG_INPUT)
2130        if (gspca_dev->input_dev)
2131                input_unregister_device(gspca_dev->input_dev);
2132#endif
2133        v4l2_ctrl_handler_free(gspca_dev->vdev.ctrl_handler);
2134        kfree(gspca_dev->usb_buf);
2135        kfree(gspca_dev);
2136        return ret;
2137}
2138EXPORT_SYMBOL(gspca_dev_probe2);
2139
2140/* same function as the previous one, but check the interface */
2141int gspca_dev_probe(struct usb_interface *intf,
2142                const struct usb_device_id *id,
2143                const struct sd_desc *sd_desc,
2144                int dev_size,
2145                struct module *module)
2146{
2147        struct usb_device *dev = interface_to_usbdev(intf);
2148
2149        /* we don't handle multi-config cameras */
2150        if (dev->descriptor.bNumConfigurations != 1) {
2151                pr_err("%04x:%04x too many config\n",
2152                       id->idVendor, id->idProduct);
2153                return -ENODEV;
2154        }
2155
2156        /* the USB video interface must be the first one */
2157        if (dev->actconfig->desc.bNumInterfaces != 1
2158         && intf->cur_altsetting->desc.bInterfaceNumber != 0)
2159                return -ENODEV;
2160
2161        return gspca_dev_probe2(intf, id, sd_desc, dev_size, module);
2162}
2163EXPORT_SYMBOL(gspca_dev_probe);
2164
2165/*
2166 * USB disconnection
2167 *
2168 * This function must be called by the sub-driver
2169 * when the device disconnects, after the specific resources are freed.
2170 */
2171void gspca_disconnect(struct usb_interface *intf)
2172{
2173        struct gspca_dev *gspca_dev = usb_get_intfdata(intf);
2174#if IS_ENABLED(CONFIG_INPUT)
2175        struct input_dev *input_dev;
2176#endif
2177
2178        PDEBUG(D_PROBE, "%s disconnect",
2179                video_device_node_name(&gspca_dev->vdev));
2180
2181        mutex_lock(&gspca_dev->usb_lock);
2182
2183        gspca_dev->present = 0;
2184        destroy_urbs(gspca_dev);
2185
2186#if IS_ENABLED(CONFIG_INPUT)
2187        gspca_input_destroy_urb(gspca_dev);
2188        input_dev = gspca_dev->input_dev;
2189        if (input_dev) {
2190                gspca_dev->input_dev = NULL;
2191                input_unregister_device(input_dev);
2192        }
2193#endif
2194        /* Free subdriver's streaming resources / stop sd workqueue(s) */
2195        if (gspca_dev->sd_desc->stop0 && gspca_dev->streaming)
2196                gspca_dev->sd_desc->stop0(gspca_dev);
2197        gspca_dev->streaming = 0;
2198        gspca_dev->dev = NULL;
2199        wake_up_interruptible(&gspca_dev->wq);
2200
2201        v4l2_device_disconnect(&gspca_dev->v4l2_dev);
2202        video_unregister_device(&gspca_dev->vdev);
2203
2204        mutex_unlock(&gspca_dev->usb_lock);
2205
2206        /* (this will call gspca_release() immediately or on last close) */
2207        v4l2_device_put(&gspca_dev->v4l2_dev);
2208}
2209EXPORT_SYMBOL(gspca_disconnect);
2210
2211#ifdef CONFIG_PM
2212int gspca_suspend(struct usb_interface *intf, pm_message_t message)
2213{
2214        struct gspca_dev *gspca_dev = usb_get_intfdata(intf);
2215
2216        gspca_input_destroy_urb(gspca_dev);
2217
2218        if (!gspca_dev->streaming)
2219                return 0;
2220
2221        mutex_lock(&gspca_dev->usb_lock);
2222        gspca_dev->frozen = 1;          /* avoid urb error messages */
2223        gspca_dev->usb_err = 0;
2224        if (gspca_dev->sd_desc->stopN)
2225                gspca_dev->sd_desc->stopN(gspca_dev);
2226        destroy_urbs(gspca_dev);
2227        gspca_set_alt0(gspca_dev);
2228        if (gspca_dev->sd_desc->stop0)
2229                gspca_dev->sd_desc->stop0(gspca_dev);
2230        mutex_unlock(&gspca_dev->usb_lock);
2231
2232        return 0;
2233}
2234EXPORT_SYMBOL(gspca_suspend);
2235
2236int gspca_resume(struct usb_interface *intf)
2237{
2238        struct gspca_dev *gspca_dev = usb_get_intfdata(intf);
2239        int streaming, ret = 0;
2240
2241        mutex_lock(&gspca_dev->usb_lock);
2242        gspca_dev->frozen = 0;
2243        gspca_dev->usb_err = 0;
2244        gspca_dev->sd_desc->init(gspca_dev);
2245        /*
2246         * Most subdrivers send all ctrl values on sd_start and thus
2247         * only write to the device registers on s_ctrl when streaming ->
2248         * Clear streaming to avoid setting all ctrls twice.
2249         */
2250        streaming = gspca_dev->streaming;
2251        gspca_dev->streaming = 0;
2252        if (streaming)
2253                ret = gspca_init_transfer(gspca_dev);
2254        else
2255                gspca_input_create_urb(gspca_dev);
2256        mutex_unlock(&gspca_dev->usb_lock);
2257
2258        return ret;
2259}
2260EXPORT_SYMBOL(gspca_resume);
2261#endif
2262
2263/* -- module insert / remove -- */
2264static int __init gspca_init(void)
2265{
2266        pr_info("v" GSPCA_VERSION " registered\n");
2267        return 0;
2268}
2269static void __exit gspca_exit(void)
2270{
2271}
2272
2273module_init(gspca_init);
2274module_exit(gspca_exit);
2275
2276module_param_named(debug, gspca_debug, int, 0644);
2277MODULE_PARM_DESC(debug,
2278                "1:probe 2:config 3:stream 4:frame 5:packet 6:usbi 7:usbo");
2279