linux/drivers/media/usb/sn9c102/sn9c102_core.c
<<
>>
Prefs
   1/***************************************************************************
   2 * V4L2 driver for SN9C1xx PC Camera Controllers                           *
   3 *                                                                         *
   4 * Copyright (C) 2004-2007 by Luca Risolia <luca.risolia@studio.unibo.it>  *
   5 *                                                                         *
   6 * This program is free software; you can redistribute it and/or modify    *
   7 * it under the terms of the GNU General Public License as published by    *
   8 * the Free Software Foundation; either version 2 of the License, or       *
   9 * (at your option) any later version.                                     *
  10 *                                                                         *
  11 * This program is distributed in the hope that it will be useful,         *
  12 * but WITHOUT ANY WARRANTY; without even the implied warranty of          *
  13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the           *
  14 * GNU General Public License for more details.                            *
  15 *                                                                         *
  16 * You should have received a copy of the GNU General Public License       *
  17 * along with this program; if not, write to the Free Software             *
  18 * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.               *
  19 ***************************************************************************/
  20
  21#include <linux/module.h>
  22#include <linux/init.h>
  23#include <linux/kernel.h>
  24#include <linux/param.h>
  25#include <linux/errno.h>
  26#include <linux/slab.h>
  27#include <linux/device.h>
  28#include <linux/fs.h>
  29#include <linux/delay.h>
  30#include <linux/compiler.h>
  31#include <linux/ioctl.h>
  32#include <linux/poll.h>
  33#include <linux/stat.h>
  34#include <linux/mm.h>
  35#include <linux/vmalloc.h>
  36#include <linux/version.h>
  37#include <linux/page-flags.h>
  38#include <asm/byteorder.h>
  39#include <asm/page.h>
  40#include <asm/uaccess.h>
  41
  42#include "sn9c102.h"
  43
  44/*****************************************************************************/
  45
  46#define SN9C102_MODULE_NAME     "V4L2 driver for SN9C1xx PC Camera Controllers"
  47#define SN9C102_MODULE_ALIAS    "sn9c1xx"
  48#define SN9C102_MODULE_AUTHOR   "(C) 2004-2007 Luca Risolia"
  49#define SN9C102_AUTHOR_EMAIL    "<luca.risolia@studio.unibo.it>"
  50#define SN9C102_MODULE_LICENSE  "GPL"
  51#define SN9C102_MODULE_VERSION  "1:1.48"
  52
  53/*****************************************************************************/
  54
  55MODULE_DEVICE_TABLE(usb, sn9c102_id_table);
  56
  57MODULE_AUTHOR(SN9C102_MODULE_AUTHOR " " SN9C102_AUTHOR_EMAIL);
  58MODULE_DESCRIPTION(SN9C102_MODULE_NAME);
  59MODULE_ALIAS(SN9C102_MODULE_ALIAS);
  60MODULE_VERSION(SN9C102_MODULE_VERSION);
  61MODULE_LICENSE(SN9C102_MODULE_LICENSE);
  62
  63static short video_nr[] = {[0 ... SN9C102_MAX_DEVICES-1] = -1};
  64module_param_array(video_nr, short, NULL, 0444);
  65MODULE_PARM_DESC(video_nr,
  66                 " <-1|n[,...]>"
  67                 "\nSpecify V4L2 minor mode number."
  68                 "\n-1 = use next available (default)"
  69                 "\n n = use minor number n (integer >= 0)"
  70                 "\nYou can specify up to "__MODULE_STRING(SN9C102_MAX_DEVICES)
  71                 " cameras this way."
  72                 "\nFor example:"
  73                 "\nvideo_nr=-1,2,-1 would assign minor number 2 to"
  74                 "\nthe second camera and use auto for the first"
  75                 "\none and for every other camera."
  76                 "\n");
  77
  78static bool force_munmap[] = {[0 ... SN9C102_MAX_DEVICES-1] =
  79                              SN9C102_FORCE_MUNMAP};
  80module_param_array(force_munmap, bool, NULL, 0444);
  81MODULE_PARM_DESC(force_munmap,
  82                 " <0|1[,...]>"
  83                 "\nForce the application to unmap previously"
  84                 "\nmapped buffer memory before calling any VIDIOC_S_CROP or"
  85                 "\nVIDIOC_S_FMT ioctl's. Not all the applications support"
  86                 "\nthis feature. This parameter is specific for each"
  87                 "\ndetected camera."
  88                 "\n0 = do not force memory unmapping"
  89                 "\n1 = force memory unmapping (save memory)"
  90                 "\nDefault value is "__MODULE_STRING(SN9C102_FORCE_MUNMAP)"."
  91                 "\n");
  92
  93static unsigned int frame_timeout[] = {[0 ... SN9C102_MAX_DEVICES-1] =
  94                                       SN9C102_FRAME_TIMEOUT};
  95module_param_array(frame_timeout, uint, NULL, 0644);
  96MODULE_PARM_DESC(frame_timeout,
  97                 " <0|n[,...]>"
  98                 "\nTimeout for a video frame in seconds before"
  99                 "\nreturning an I/O error; 0 for infinity."
 100                 "\nThis parameter is specific for each detected camera."
 101                 "\nDefault value is "__MODULE_STRING(SN9C102_FRAME_TIMEOUT)"."
 102                 "\n");
 103
 104#ifdef SN9C102_DEBUG
 105static unsigned short debug = SN9C102_DEBUG_LEVEL;
 106module_param(debug, ushort, 0644);
 107MODULE_PARM_DESC(debug,
 108                 " <n>"
 109                 "\nDebugging information level, from 0 to 3:"
 110                 "\n0 = none (use carefully)"
 111                 "\n1 = critical errors"
 112                 "\n2 = significant informations"
 113                 "\n3 = more verbose messages"
 114                 "\nLevel 3 is useful for testing only."
 115                 "\nDefault value is "__MODULE_STRING(SN9C102_DEBUG_LEVEL)"."
 116                 "\n");
 117#endif
 118
 119/*
 120   Add the probe entries to this table. Be sure to add the entry in the right
 121   place, since, on failure, the next probing routine is called according to
 122   the order of the list below, from top to bottom.
 123*/
 124static int (*sn9c102_sensor_table[])(struct sn9c102_device *) = {
 125        &sn9c102_probe_hv7131d, /* strong detection based on SENSOR ids */
 126        &sn9c102_probe_hv7131r, /* strong detection based on SENSOR ids */
 127        &sn9c102_probe_mi0343, /* strong detection based on SENSOR ids */
 128        &sn9c102_probe_mi0360, /* strong detection based on SENSOR ids */
 129        &sn9c102_probe_mt9v111, /* strong detection based on SENSOR ids */
 130        &sn9c102_probe_pas106b, /* strong detection based on SENSOR ids */
 131        &sn9c102_probe_pas202bcb, /* strong detection based on SENSOR ids */
 132        &sn9c102_probe_ov7630, /* strong detection based on SENSOR ids */
 133        &sn9c102_probe_ov7660, /* strong detection based on SENSOR ids */
 134        &sn9c102_probe_tas5110c1b, /* detection based on USB pid/vid */
 135        &sn9c102_probe_tas5110d, /* detection based on USB pid/vid */
 136        &sn9c102_probe_tas5130d1b, /* detection based on USB pid/vid */
 137};
 138
 139/*****************************************************************************/
 140
 141static u32
 142sn9c102_request_buffers(struct sn9c102_device* cam, u32 count,
 143                        enum sn9c102_io_method io)
 144{
 145        struct v4l2_pix_format* p = &(cam->sensor.pix_format);
 146        struct v4l2_rect* r = &(cam->sensor.cropcap.bounds);
 147        size_t imagesize = cam->module_param.force_munmap || io == IO_READ ?
 148                           (p->width * p->height * p->priv) / 8 :
 149                           (r->width * r->height * p->priv) / 8;
 150        void* buff = NULL;
 151        u32 i;
 152
 153        if (count > SN9C102_MAX_FRAMES)
 154                count = SN9C102_MAX_FRAMES;
 155
 156        if (cam->bridge == BRIDGE_SN9C105 || cam->bridge == BRIDGE_SN9C120)
 157                imagesize += 589 + 2; /* length of JPEG header + EOI marker */
 158
 159        cam->nbuffers = count;
 160        while (cam->nbuffers > 0) {
 161                if ((buff = vmalloc_32_user(cam->nbuffers *
 162                                            PAGE_ALIGN(imagesize))))
 163                        break;
 164                cam->nbuffers--;
 165        }
 166
 167        for (i = 0; i < cam->nbuffers; i++) {
 168                cam->frame[i].bufmem = buff + i*PAGE_ALIGN(imagesize);
 169                cam->frame[i].buf.index = i;
 170                cam->frame[i].buf.m.offset = i*PAGE_ALIGN(imagesize);
 171                cam->frame[i].buf.length = imagesize;
 172                cam->frame[i].buf.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
 173                cam->frame[i].buf.sequence = 0;
 174                cam->frame[i].buf.field = V4L2_FIELD_NONE;
 175                cam->frame[i].buf.memory = V4L2_MEMORY_MMAP;
 176                cam->frame[i].buf.flags = V4L2_BUF_FLAG_TIMESTAMP_MONOTONIC;
 177        }
 178
 179        return cam->nbuffers;
 180}
 181
 182
 183static void sn9c102_release_buffers(struct sn9c102_device* cam)
 184{
 185        if (cam->nbuffers) {
 186                vfree(cam->frame[0].bufmem);
 187                cam->nbuffers = 0;
 188        }
 189        cam->frame_current = NULL;
 190}
 191
 192
 193static void sn9c102_empty_framequeues(struct sn9c102_device* cam)
 194{
 195        u32 i;
 196
 197        INIT_LIST_HEAD(&cam->inqueue);
 198        INIT_LIST_HEAD(&cam->outqueue);
 199
 200        for (i = 0; i < SN9C102_MAX_FRAMES; i++) {
 201                cam->frame[i].state = F_UNUSED;
 202                cam->frame[i].buf.bytesused = 0;
 203        }
 204}
 205
 206
 207static void sn9c102_requeue_outqueue(struct sn9c102_device* cam)
 208{
 209        struct sn9c102_frame_t *i;
 210
 211        list_for_each_entry(i, &cam->outqueue, frame) {
 212                i->state = F_QUEUED;
 213                list_add(&i->frame, &cam->inqueue);
 214        }
 215
 216        INIT_LIST_HEAD(&cam->outqueue);
 217}
 218
 219
 220static void sn9c102_queue_unusedframes(struct sn9c102_device* cam)
 221{
 222        unsigned long lock_flags;
 223        u32 i;
 224
 225        for (i = 0; i < cam->nbuffers; i++)
 226                if (cam->frame[i].state == F_UNUSED) {
 227                        cam->frame[i].state = F_QUEUED;
 228                        spin_lock_irqsave(&cam->queue_lock, lock_flags);
 229                        list_add_tail(&cam->frame[i].frame, &cam->inqueue);
 230                        spin_unlock_irqrestore(&cam->queue_lock, lock_flags);
 231                }
 232}
 233
 234/*****************************************************************************/
 235
 236/*
 237   Write a sequence of count value/register pairs. Returns -1 after the first
 238   failed write, or 0 for no errors.
 239*/
 240int sn9c102_write_regs(struct sn9c102_device* cam, const u8 valreg[][2],
 241                       int count)
 242{
 243        struct usb_device* udev = cam->usbdev;
 244        u8* buff = cam->control_buffer;
 245        int i, res;
 246
 247        for (i = 0; i < count; i++) {
 248                u8 index = valreg[i][1];
 249
 250                /*
 251                   index is a u8, so it must be <256 and can't be out of range.
 252                   If we put in a check anyway, gcc annoys us with a warning
 253                   hat our check is useless. People get all uppity when they
 254                   see warnings in the kernel compile.
 255                */
 256
 257                *buff = valreg[i][0];
 258
 259                res = usb_control_msg(udev, usb_sndctrlpipe(udev, 0), 0x08,
 260                                      0x41, index, 0, buff, 1,
 261                                      SN9C102_CTRL_TIMEOUT);
 262
 263                if (res < 0) {
 264                        DBG(3, "Failed to write a register (value 0x%02X, "
 265                               "index 0x%02X, error %d)", *buff, index, res);
 266                        return -1;
 267                }
 268
 269                cam->reg[index] = *buff;
 270        }
 271
 272        return 0;
 273}
 274
 275
 276int sn9c102_write_reg(struct sn9c102_device* cam, u8 value, u16 index)
 277{
 278        struct usb_device* udev = cam->usbdev;
 279        u8* buff = cam->control_buffer;
 280        int res;
 281
 282        if (index >= ARRAY_SIZE(cam->reg))
 283                return -1;
 284
 285        *buff = value;
 286
 287        res = usb_control_msg(udev, usb_sndctrlpipe(udev, 0), 0x08, 0x41,
 288                              index, 0, buff, 1, SN9C102_CTRL_TIMEOUT);
 289        if (res < 0) {
 290                DBG(3, "Failed to write a register (value 0x%02X, index "
 291                       "0x%02X, error %d)", value, index, res);
 292                return -1;
 293        }
 294
 295        cam->reg[index] = value;
 296
 297        return 0;
 298}
 299
 300
 301/* NOTE: with the SN9C10[123] reading some registers always returns 0 */
 302int sn9c102_read_reg(struct sn9c102_device* cam, u16 index)
 303{
 304        struct usb_device* udev = cam->usbdev;
 305        u8* buff = cam->control_buffer;
 306        int res;
 307
 308        res = usb_control_msg(udev, usb_rcvctrlpipe(udev, 0), 0x00, 0xc1,
 309                              index, 0, buff, 1, SN9C102_CTRL_TIMEOUT);
 310        if (res < 0)
 311                DBG(3, "Failed to read a register (index 0x%02X, error %d)",
 312                    index, res);
 313
 314        return (res >= 0) ? (int)(*buff) : -1;
 315}
 316
 317
 318int sn9c102_pread_reg(struct sn9c102_device* cam, u16 index)
 319{
 320        if (index >= ARRAY_SIZE(cam->reg))
 321                return -1;
 322
 323        return cam->reg[index];
 324}
 325
 326
 327static int
 328sn9c102_i2c_wait(struct sn9c102_device* cam,
 329                 const struct sn9c102_sensor* sensor)
 330{
 331        int i, r;
 332
 333        for (i = 1; i <= 5; i++) {
 334                r = sn9c102_read_reg(cam, 0x08);
 335                if (r < 0)
 336                        return -EIO;
 337                if (r & 0x04)
 338                        return 0;
 339                if (sensor->frequency & SN9C102_I2C_400KHZ)
 340                        udelay(5*16);
 341                else
 342                        udelay(16*16);
 343        }
 344        return -EBUSY;
 345}
 346
 347
 348static int
 349sn9c102_i2c_detect_read_error(struct sn9c102_device* cam,
 350                              const struct sn9c102_sensor* sensor)
 351{
 352        int r , err = 0;
 353
 354        r = sn9c102_read_reg(cam, 0x08);
 355        if (r < 0)
 356                err += r;
 357
 358        if (cam->bridge == BRIDGE_SN9C101 || cam->bridge == BRIDGE_SN9C102) {
 359                if (!(r & 0x08))
 360                        err += -1;
 361        } else {
 362                if (r & 0x08)
 363                        err += -1;
 364        }
 365
 366        return err ? -EIO : 0;
 367}
 368
 369
 370static int
 371sn9c102_i2c_detect_write_error(struct sn9c102_device* cam,
 372                               const struct sn9c102_sensor* sensor)
 373{
 374        int r;
 375        r = sn9c102_read_reg(cam, 0x08);
 376        return (r < 0 || (r >= 0 && (r & 0x08))) ? -EIO : 0;
 377}
 378
 379
 380int
 381sn9c102_i2c_try_raw_read(struct sn9c102_device* cam,
 382                         const struct sn9c102_sensor* sensor, u8 data0,
 383                         u8 data1, u8 n, u8 buffer[])
 384{
 385        struct usb_device* udev = cam->usbdev;
 386        u8* data = cam->control_buffer;
 387        int i = 0, err = 0, res;
 388
 389        /* Write cycle */
 390        data[0] = ((sensor->interface == SN9C102_I2C_2WIRES) ? 0x80 : 0) |
 391                  ((sensor->frequency & SN9C102_I2C_400KHZ) ? 0x01 : 0) | 0x10;
 392        data[1] = data0; /* I2C slave id */
 393        data[2] = data1; /* address */
 394        data[7] = 0x10;
 395        res = usb_control_msg(udev, usb_sndctrlpipe(udev, 0), 0x08, 0x41,
 396                              0x08, 0, data, 8, SN9C102_CTRL_TIMEOUT);
 397        if (res < 0)
 398                err += res;
 399
 400        err += sn9c102_i2c_wait(cam, sensor);
 401
 402        /* Read cycle - n bytes */
 403        data[0] = ((sensor->interface == SN9C102_I2C_2WIRES) ? 0x80 : 0) |
 404                  ((sensor->frequency & SN9C102_I2C_400KHZ) ? 0x01 : 0) |
 405                  (n << 4) | 0x02;
 406        data[1] = data0;
 407        data[7] = 0x10;
 408        res = usb_control_msg(udev, usb_sndctrlpipe(udev, 0), 0x08, 0x41,
 409                              0x08, 0, data, 8, SN9C102_CTRL_TIMEOUT);
 410        if (res < 0)
 411                err += res;
 412
 413        err += sn9c102_i2c_wait(cam, sensor);
 414
 415        /* The first read byte will be placed in data[4] */
 416        res = usb_control_msg(udev, usb_rcvctrlpipe(udev, 0), 0x00, 0xc1,
 417                              0x0a, 0, data, 5, SN9C102_CTRL_TIMEOUT);
 418        if (res < 0)
 419                err += res;
 420
 421        err += sn9c102_i2c_detect_read_error(cam, sensor);
 422
 423        PDBGG("I2C read: address 0x%02X, first read byte: 0x%02X", data1,
 424              data[4]);
 425
 426        if (err) {
 427                DBG(3, "I2C read failed for %s image sensor", sensor->name);
 428                return -1;
 429        }
 430
 431        if (buffer)
 432                for (i = 0; i < n && i < 5; i++)
 433                        buffer[n-i-1] = data[4-i];
 434
 435        return (int)data[4];
 436}
 437
 438
 439int
 440sn9c102_i2c_try_raw_write(struct sn9c102_device* cam,
 441                          const struct sn9c102_sensor* sensor, u8 n, u8 data0,
 442                          u8 data1, u8 data2, u8 data3, u8 data4, u8 data5)
 443{
 444        struct usb_device* udev = cam->usbdev;
 445        u8* data = cam->control_buffer;
 446        int err = 0, res;
 447
 448        /* Write cycle. It usually is address + value */
 449        data[0] = ((sensor->interface == SN9C102_I2C_2WIRES) ? 0x80 : 0) |
 450                  ((sensor->frequency & SN9C102_I2C_400KHZ) ? 0x01 : 0)
 451                  | ((n - 1) << 4);
 452        data[1] = data0;
 453        data[2] = data1;
 454        data[3] = data2;
 455        data[4] = data3;
 456        data[5] = data4;
 457        data[6] = data5;
 458        data[7] = 0x17;
 459        res = usb_control_msg(udev, usb_sndctrlpipe(udev, 0), 0x08, 0x41,
 460                              0x08, 0, data, 8, SN9C102_CTRL_TIMEOUT);
 461        if (res < 0)
 462                err += res;
 463
 464        err += sn9c102_i2c_wait(cam, sensor);
 465        err += sn9c102_i2c_detect_write_error(cam, sensor);
 466
 467        if (err)
 468                DBG(3, "I2C write failed for %s image sensor", sensor->name);
 469
 470        PDBGG("I2C raw write: %u bytes, data0 = 0x%02X, data1 = 0x%02X, "
 471              "data2 = 0x%02X, data3 = 0x%02X, data4 = 0x%02X, data5 = 0x%02X",
 472              n, data0, data1, data2, data3, data4, data5);
 473
 474        return err ? -1 : 0;
 475}
 476
 477
 478int
 479sn9c102_i2c_try_read(struct sn9c102_device* cam,
 480                     const struct sn9c102_sensor* sensor, u8 address)
 481{
 482        return sn9c102_i2c_try_raw_read(cam, sensor, sensor->i2c_slave_id,
 483                                        address, 1, NULL);
 484}
 485
 486
 487static int sn9c102_i2c_try_write(struct sn9c102_device* cam,
 488                                 const struct sn9c102_sensor* sensor,
 489                                 u8 address, u8 value)
 490{
 491        return sn9c102_i2c_try_raw_write(cam, sensor, 3,
 492                                         sensor->i2c_slave_id, address,
 493                                         value, 0, 0, 0);
 494}
 495
 496
 497int sn9c102_i2c_read(struct sn9c102_device* cam, u8 address)
 498{
 499        return sn9c102_i2c_try_read(cam, &cam->sensor, address);
 500}
 501
 502
 503int sn9c102_i2c_write(struct sn9c102_device* cam, u8 address, u8 value)
 504{
 505        return sn9c102_i2c_try_write(cam, &cam->sensor, address, value);
 506}
 507
 508/*****************************************************************************/
 509
 510static size_t sn9c102_sof_length(struct sn9c102_device* cam)
 511{
 512        switch (cam->bridge) {
 513        case BRIDGE_SN9C101:
 514        case BRIDGE_SN9C102:
 515                return 12;
 516        case BRIDGE_SN9C103:
 517                return 18;
 518        case BRIDGE_SN9C105:
 519        case BRIDGE_SN9C120:
 520                return 62;
 521        }
 522
 523        return 0;
 524}
 525
 526
 527static void*
 528sn9c102_find_sof_header(struct sn9c102_device* cam, void* mem, size_t len)
 529{
 530        static const char marker[6] = {0xff, 0xff, 0x00, 0xc4, 0xc4, 0x96};
 531        const char *m = mem;
 532        size_t soflen = 0, i, j;
 533
 534        soflen = sn9c102_sof_length(cam);
 535
 536        for (i = 0; i < len; i++) {
 537                size_t b;
 538
 539                /* Read the variable part of the header */
 540                if (unlikely(cam->sof.bytesread >= sizeof(marker))) {
 541                        cam->sof.header[cam->sof.bytesread] = *(m+i);
 542                        if (++cam->sof.bytesread == soflen) {
 543                                cam->sof.bytesread = 0;
 544                                return mem + i;
 545                        }
 546                        continue;
 547                }
 548
 549                /* Search for the SOF marker (fixed part) in the header */
 550                for (j = 0, b=cam->sof.bytesread; j+b < sizeof(marker); j++) {
 551                        if (unlikely(i+j == len))
 552                                return NULL;
 553                        if (*(m+i+j) == marker[cam->sof.bytesread]) {
 554                                cam->sof.header[cam->sof.bytesread] = *(m+i+j);
 555                                if (++cam->sof.bytesread == sizeof(marker)) {
 556                                        PDBGG("Bytes to analyze: %zd. SOF "
 557                                              "starts at byte #%zd", len, i);
 558                                        i += j+1;
 559                                        break;
 560                                }
 561                        } else {
 562                                cam->sof.bytesread = 0;
 563                                break;
 564                        }
 565                }
 566        }
 567
 568        return NULL;
 569}
 570
 571
 572static void*
 573sn9c102_find_eof_header(struct sn9c102_device* cam, void* mem, size_t len)
 574{
 575        static const u8 eof_header[4][4] = {
 576                {0x00, 0x00, 0x00, 0x00},
 577                {0x40, 0x00, 0x00, 0x00},
 578                {0x80, 0x00, 0x00, 0x00},
 579                {0xc0, 0x00, 0x00, 0x00},
 580        };
 581        size_t i, j;
 582
 583        /* The EOF header does not exist in compressed data */
 584        if (cam->sensor.pix_format.pixelformat == V4L2_PIX_FMT_SN9C10X ||
 585            cam->sensor.pix_format.pixelformat == V4L2_PIX_FMT_JPEG)
 586                return NULL;
 587
 588        /*
 589           The EOF header might cross the packet boundary, but this is not a
 590           problem, since the end of a frame is determined by checking its size
 591           in the first place.
 592        */
 593        for (i = 0; (len >= 4) && (i <= len - 4); i++)
 594                for (j = 0; j < ARRAY_SIZE(eof_header); j++)
 595                        if (!memcmp(mem + i, eof_header[j], 4))
 596                                return mem + i;
 597
 598        return NULL;
 599}
 600
 601
 602static void
 603sn9c102_write_jpegheader(struct sn9c102_device* cam, struct sn9c102_frame_t* f)
 604{
 605        static const u8 jpeg_header[589] = {
 606                0xff, 0xd8, 0xff, 0xdb, 0x00, 0x84, 0x00, 0x06, 0x04, 0x05,
 607                0x06, 0x05, 0x04, 0x06, 0x06, 0x05, 0x06, 0x07, 0x07, 0x06,
 608                0x08, 0x0a, 0x10, 0x0a, 0x0a, 0x09, 0x09, 0x0a, 0x14, 0x0e,
 609                0x0f, 0x0c, 0x10, 0x17, 0x14, 0x18, 0x18, 0x17, 0x14, 0x16,
 610                0x16, 0x1a, 0x1d, 0x25, 0x1f, 0x1a, 0x1b, 0x23, 0x1c, 0x16,
 611                0x16, 0x20, 0x2c, 0x20, 0x23, 0x26, 0x27, 0x29, 0x2a, 0x29,
 612                0x19, 0x1f, 0x2d, 0x30, 0x2d, 0x28, 0x30, 0x25, 0x28, 0x29,
 613                0x28, 0x01, 0x07, 0x07, 0x07, 0x0a, 0x08, 0x0a, 0x13, 0x0a,
 614                0x0a, 0x13, 0x28, 0x1a, 0x16, 0x1a, 0x28, 0x28, 0x28, 0x28,
 615                0x28, 0x28, 0x28, 0x28, 0x28, 0x28, 0x28, 0x28, 0x28, 0x28,
 616                0x28, 0x28, 0x28, 0x28, 0x28, 0x28, 0x28, 0x28, 0x28, 0x28,
 617                0x28, 0x28, 0x28, 0x28, 0x28, 0x28, 0x28, 0x28, 0x28, 0x28,
 618                0x28, 0x28, 0x28, 0x28, 0x28, 0x28, 0x28, 0x28, 0x28, 0x28,
 619                0x28, 0x28, 0x28, 0x28, 0x28, 0x28, 0xff, 0xc4, 0x01, 0xa2,
 620                0x00, 0x00, 0x01, 0x05, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01,
 621                0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x02,
 622                0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x01,
 623                0x00, 0x03, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01,
 624                0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x02, 0x03,
 625                0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x10, 0x00,
 626                0x02, 0x01, 0x03, 0x03, 0x02, 0x04, 0x03, 0x05, 0x05, 0x04,
 627                0x04, 0x00, 0x00, 0x01, 0x7d, 0x01, 0x02, 0x03, 0x00, 0x04,
 628                0x11, 0x05, 0x12, 0x21, 0x31, 0x41, 0x06, 0x13, 0x51, 0x61,
 629                0x07, 0x22, 0x71, 0x14, 0x32, 0x81, 0x91, 0xa1, 0x08, 0x23,
 630                0x42, 0xb1, 0xc1, 0x15, 0x52, 0xd1, 0xf0, 0x24, 0x33, 0x62,
 631                0x72, 0x82, 0x09, 0x0a, 0x16, 0x17, 0x18, 0x19, 0x1a, 0x25,
 632                0x26, 0x27, 0x28, 0x29, 0x2a, 0x34, 0x35, 0x36, 0x37, 0x38,
 633                0x39, 0x3a, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48, 0x49, 0x4a,
 634                0x53, 0x54, 0x55, 0x56, 0x57, 0x58, 0x59, 0x5a, 0x63, 0x64,
 635                0x65, 0x66, 0x67, 0x68, 0x69, 0x6a, 0x73, 0x74, 0x75, 0x76,
 636                0x77, 0x78, 0x79, 0x7a, 0x83, 0x84, 0x85, 0x86, 0x87, 0x88,
 637                0x89, 0x8a, 0x92, 0x93, 0x94, 0x95, 0x96, 0x97, 0x98, 0x99,
 638                0x9a, 0xa2, 0xa3, 0xa4, 0xa5, 0xa6, 0xa7, 0xa8, 0xa9, 0xaa,
 639                0xb2, 0xb3, 0xb4, 0xb5, 0xb6, 0xb7, 0xb8, 0xb9, 0xba, 0xc2,
 640                0xc3, 0xc4, 0xc5, 0xc6, 0xc7, 0xc8, 0xc9, 0xca, 0xd2, 0xd3,
 641                0xd4, 0xd5, 0xd6, 0xd7, 0xd8, 0xd9, 0xda, 0xe1, 0xe2, 0xe3,
 642                0xe4, 0xe5, 0xe6, 0xe7, 0xe8, 0xe9, 0xea, 0xf1, 0xf2, 0xf3,
 643                0xf4, 0xf5, 0xf6, 0xf7, 0xf8, 0xf9, 0xfa, 0x11, 0x00, 0x02,
 644                0x01, 0x02, 0x04, 0x04, 0x03, 0x04, 0x07, 0x05, 0x04, 0x04,
 645                0x00, 0x01, 0x02, 0x77, 0x00, 0x01, 0x02, 0x03, 0x11, 0x04,
 646                0x05, 0x21, 0x31, 0x06, 0x12, 0x41, 0x51, 0x07, 0x61, 0x71,
 647                0x13, 0x22, 0x32, 0x81, 0x08, 0x14, 0x42, 0x91, 0xa1, 0xb1,
 648                0xc1, 0x09, 0x23, 0x33, 0x52, 0xf0, 0x15, 0x62, 0x72, 0xd1,
 649                0x0a, 0x16, 0x24, 0x34, 0xe1, 0x25, 0xf1, 0x17, 0x18, 0x19,
 650                0x1a, 0x26, 0x27, 0x28, 0x29, 0x2a, 0x35, 0x36, 0x37, 0x38,
 651                0x39, 0x3a, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48, 0x49, 0x4a,
 652                0x53, 0x54, 0x55, 0x56, 0x57, 0x58, 0x59, 0x5a, 0x63, 0x64,
 653                0x65, 0x66, 0x67, 0x68, 0x69, 0x6a, 0x73, 0x74, 0x75, 0x76,
 654                0x77, 0x78, 0x79, 0x7a, 0x82, 0x83, 0x84, 0x85, 0x86, 0x87,
 655                0x88, 0x89, 0x8a, 0x92, 0x93, 0x94, 0x95, 0x96, 0x97, 0x98,
 656                0x99, 0x9a, 0xa2, 0xa3, 0xa4, 0xa5, 0xa6, 0xa7, 0xa8, 0xa9,
 657                0xaa, 0xb2, 0xb3, 0xb4, 0xb5, 0xb6, 0xb7, 0xb8, 0xb9, 0xba,
 658                0xc2, 0xc3, 0xc4, 0xc5, 0xc6, 0xc7, 0xc8, 0xc9, 0xca, 0xd2,
 659                0xd3, 0xd4, 0xd5, 0xd6, 0xd7, 0xd8, 0xd9, 0xda, 0xe2, 0xe3,
 660                0xe4, 0xe5, 0xe6, 0xe7, 0xe8, 0xe9, 0xea, 0xf2, 0xf3, 0xf4,
 661                0xf5, 0xf6, 0xf7, 0xf8, 0xf9, 0xfa, 0xff, 0xc0, 0x00, 0x11,
 662                0x08, 0x01, 0xe0, 0x02, 0x80, 0x03, 0x01, 0x21, 0x00, 0x02,
 663                0x11, 0x01, 0x03, 0x11, 0x01, 0xff, 0xda, 0x00, 0x0c, 0x03,
 664                0x01, 0x00, 0x02, 0x11, 0x03, 0x11, 0x00, 0x3f, 0x00
 665        };
 666        u8 *pos = f->bufmem;
 667
 668        memcpy(pos, jpeg_header, sizeof(jpeg_header));
 669        *(pos + 6) = 0x00;
 670        *(pos + 7 + 64) = 0x01;
 671        if (cam->compression.quality == 0) {
 672                memcpy(pos + 7, SN9C102_Y_QTABLE0, 64);
 673                memcpy(pos + 8 + 64, SN9C102_UV_QTABLE0, 64);
 674        } else if (cam->compression.quality == 1) {
 675                memcpy(pos + 7, SN9C102_Y_QTABLE1, 64);
 676                memcpy(pos + 8 + 64, SN9C102_UV_QTABLE1, 64);
 677        }
 678        *(pos + 564) = cam->sensor.pix_format.width & 0xFF;
 679        *(pos + 563) = (cam->sensor.pix_format.width >> 8) & 0xFF;
 680        *(pos + 562) = cam->sensor.pix_format.height & 0xFF;
 681        *(pos + 561) = (cam->sensor.pix_format.height >> 8) & 0xFF;
 682        *(pos + 567) = 0x21;
 683
 684        f->buf.bytesused += sizeof(jpeg_header);
 685}
 686
 687
 688static void sn9c102_urb_complete(struct urb *urb)
 689{
 690        struct sn9c102_device* cam = urb->context;
 691        struct sn9c102_frame_t** f;
 692        size_t imagesize, soflen;
 693        u8 i;
 694        int err = 0;
 695
 696        if (urb->status == -ENOENT)
 697                return;
 698
 699        f = &cam->frame_current;
 700
 701        if (cam->stream == STREAM_INTERRUPT) {
 702                cam->stream = STREAM_OFF;
 703                if ((*f))
 704                        (*f)->state = F_QUEUED;
 705                cam->sof.bytesread = 0;
 706                DBG(3, "Stream interrupted by application");
 707                wake_up(&cam->wait_stream);
 708        }
 709
 710        if (cam->state & DEV_DISCONNECTED)
 711                return;
 712
 713        if (cam->state & DEV_MISCONFIGURED) {
 714                wake_up_interruptible(&cam->wait_frame);
 715                return;
 716        }
 717
 718        if (cam->stream == STREAM_OFF || list_empty(&cam->inqueue))
 719                goto resubmit_urb;
 720
 721        if (!(*f))
 722                (*f) = list_entry(cam->inqueue.next, struct sn9c102_frame_t,
 723                                  frame);
 724
 725        imagesize = (cam->sensor.pix_format.width *
 726                     cam->sensor.pix_format.height *
 727                     cam->sensor.pix_format.priv) / 8;
 728        if (cam->sensor.pix_format.pixelformat == V4L2_PIX_FMT_JPEG)
 729                imagesize += 589; /* length of jpeg header */
 730        soflen = sn9c102_sof_length(cam);
 731
 732        for (i = 0; i < urb->number_of_packets; i++) {
 733                unsigned int img, len, status;
 734                void *pos, *sof, *eof;
 735
 736                len = urb->iso_frame_desc[i].actual_length;
 737                status = urb->iso_frame_desc[i].status;
 738                pos = urb->iso_frame_desc[i].offset + urb->transfer_buffer;
 739
 740                if (status) {
 741                        DBG(3, "Error in isochronous frame");
 742                        (*f)->state = F_ERROR;
 743                        cam->sof.bytesread = 0;
 744                        continue;
 745                }
 746
 747                PDBGG("Isochrnous frame: length %u, #%u i", len, i);
 748
 749redo:
 750                sof = sn9c102_find_sof_header(cam, pos, len);
 751                if (likely(!sof)) {
 752                        eof = sn9c102_find_eof_header(cam, pos, len);
 753                        if ((*f)->state == F_GRABBING) {
 754end_of_frame:
 755                                img = len;
 756
 757                                if (eof)
 758                                        img = (eof > pos) ? eof - pos - 1 : 0;
 759
 760                                if ((*f)->buf.bytesused + img > imagesize) {
 761                                        u32 b;
 762                                        b = (*f)->buf.bytesused + img -
 763                                            imagesize;
 764                                        img = imagesize - (*f)->buf.bytesused;
 765                                        PDBGG("Expected EOF not found: video "
 766                                              "frame cut");
 767                                        if (eof)
 768                                                DBG(3, "Exceeded limit: +%u "
 769                                                       "bytes", (unsigned)(b));
 770                                }
 771
 772                                memcpy((*f)->bufmem + (*f)->buf.bytesused, pos,
 773                                       img);
 774
 775                                if ((*f)->buf.bytesused == 0)
 776                                        v4l2_get_timestamp(
 777                                                &(*f)->buf.timestamp);
 778
 779                                (*f)->buf.bytesused += img;
 780
 781                                if ((*f)->buf.bytesused == imagesize ||
 782                                    ((cam->sensor.pix_format.pixelformat ==
 783                                      V4L2_PIX_FMT_SN9C10X ||
 784                                      cam->sensor.pix_format.pixelformat ==
 785                                      V4L2_PIX_FMT_JPEG) && eof)) {
 786                                        u32 b;
 787
 788                                        b = (*f)->buf.bytesused;
 789                                        (*f)->state = F_DONE;
 790                                        (*f)->buf.sequence= ++cam->frame_count;
 791
 792                                        spin_lock(&cam->queue_lock);
 793                                        list_move_tail(&(*f)->frame,
 794                                                       &cam->outqueue);
 795                                        if (!list_empty(&cam->inqueue))
 796                                                (*f) = list_entry(
 797                                                        cam->inqueue.next,
 798                                                        struct sn9c102_frame_t,
 799                                                        frame );
 800                                        else
 801                                                (*f) = NULL;
 802                                        spin_unlock(&cam->queue_lock);
 803
 804                                        memcpy(cam->sysfs.frame_header,
 805                                               cam->sof.header, soflen);
 806
 807                                        DBG(3, "Video frame captured: %lu "
 808                                               "bytes", (unsigned long)(b));
 809
 810                                        if (!(*f))
 811                                                goto resubmit_urb;
 812
 813                                } else if (eof) {
 814                                        (*f)->state = F_ERROR;
 815                                        DBG(3, "Not expected EOF after %lu "
 816                                               "bytes of image data",
 817                                            (unsigned long)
 818                                            ((*f)->buf.bytesused));
 819                                }
 820
 821                                if (sof) /* (1) */
 822                                        goto start_of_frame;
 823
 824                        } else if (eof) {
 825                                DBG(3, "EOF without SOF");
 826                                continue;
 827
 828                        } else {
 829                                PDBGG("Ignoring pointless isochronous frame");
 830                                continue;
 831                        }
 832
 833                } else if ((*f)->state == F_QUEUED || (*f)->state == F_ERROR) {
 834start_of_frame:
 835                        (*f)->state = F_GRABBING;
 836                        (*f)->buf.bytesused = 0;
 837                        len -= (sof - pos);
 838                        pos = sof;
 839                        if (cam->sensor.pix_format.pixelformat ==
 840                            V4L2_PIX_FMT_JPEG)
 841                                sn9c102_write_jpegheader(cam, (*f));
 842                        DBG(3, "SOF detected: new video frame");
 843                        if (len)
 844                                goto redo;
 845
 846                } else if ((*f)->state == F_GRABBING) {
 847                        eof = sn9c102_find_eof_header(cam, pos, len);
 848                        if (eof && eof < sof)
 849                                goto end_of_frame; /* (1) */
 850                        else {
 851                                if (cam->sensor.pix_format.pixelformat ==
 852                                    V4L2_PIX_FMT_SN9C10X ||
 853                                    cam->sensor.pix_format.pixelformat ==
 854                                    V4L2_PIX_FMT_JPEG) {
 855                                        if (sof - pos >= soflen) {
 856                                                eof = sof - soflen;
 857                                        } else { /* remove header */
 858                                                eof = pos;
 859                                                (*f)->buf.bytesused -=
 860                                                        (soflen - (sof - pos));
 861                                        }
 862                                        goto end_of_frame;
 863                                } else {
 864                                        DBG(3, "SOF before expected EOF after "
 865                                               "%lu bytes of image data",
 866                                            (unsigned long)
 867                                            ((*f)->buf.bytesused));
 868                                        goto start_of_frame;
 869                                }
 870                        }
 871                }
 872        }
 873
 874resubmit_urb:
 875        urb->dev = cam->usbdev;
 876        err = usb_submit_urb(urb, GFP_ATOMIC);
 877        if (err < 0 && err != -EPERM) {
 878                cam->state |= DEV_MISCONFIGURED;
 879                DBG(1, "usb_submit_urb() failed");
 880        }
 881
 882        wake_up_interruptible(&cam->wait_frame);
 883}
 884
 885
 886static int sn9c102_start_transfer(struct sn9c102_device* cam)
 887{
 888        struct usb_device *udev = cam->usbdev;
 889        struct urb* urb;
 890        struct usb_host_interface* altsetting = usb_altnum_to_altsetting(
 891                                                    usb_ifnum_to_if(udev, 0),
 892                                                    SN9C102_ALTERNATE_SETTING);
 893        const unsigned int psz = le16_to_cpu(altsetting->
 894                                             endpoint[0].desc.wMaxPacketSize);
 895        s8 i, j;
 896        int err = 0;
 897
 898        for (i = 0; i < SN9C102_URBS; i++) {
 899                cam->transfer_buffer[i] = kzalloc(SN9C102_ISO_PACKETS * psz,
 900                                                  GFP_KERNEL);
 901                if (!cam->transfer_buffer[i]) {
 902                        err = -ENOMEM;
 903                        DBG(1, "Not enough memory");
 904                        goto free_buffers;
 905                }
 906        }
 907
 908        for (i = 0; i < SN9C102_URBS; i++) {
 909                urb = usb_alloc_urb(SN9C102_ISO_PACKETS, GFP_KERNEL);
 910                cam->urb[i] = urb;
 911                if (!urb) {
 912                        err = -ENOMEM;
 913                        DBG(1, "usb_alloc_urb() failed");
 914                        goto free_urbs;
 915                }
 916                urb->dev = udev;
 917                urb->context = cam;
 918                urb->pipe = usb_rcvisocpipe(udev, 1);
 919                urb->transfer_flags = URB_ISO_ASAP;
 920                urb->number_of_packets = SN9C102_ISO_PACKETS;
 921                urb->complete = sn9c102_urb_complete;
 922                urb->transfer_buffer = cam->transfer_buffer[i];
 923                urb->transfer_buffer_length = psz * SN9C102_ISO_PACKETS;
 924                urb->interval = 1;
 925                for (j = 0; j < SN9C102_ISO_PACKETS; j++) {
 926                        urb->iso_frame_desc[j].offset = psz * j;
 927                        urb->iso_frame_desc[j].length = psz;
 928                }
 929        }
 930
 931        /* Enable video */
 932        if (!(cam->reg[0x01] & 0x04)) {
 933                err = sn9c102_write_reg(cam, cam->reg[0x01] | 0x04, 0x01);
 934                if (err) {
 935                        err = -EIO;
 936                        DBG(1, "I/O hardware error");
 937                        goto free_urbs;
 938                }
 939        }
 940
 941        err = usb_set_interface(udev, 0, SN9C102_ALTERNATE_SETTING);
 942        if (err) {
 943                DBG(1, "usb_set_interface() failed");
 944                goto free_urbs;
 945        }
 946
 947        cam->frame_current = NULL;
 948        cam->sof.bytesread = 0;
 949
 950        for (i = 0; i < SN9C102_URBS; i++) {
 951                err = usb_submit_urb(cam->urb[i], GFP_KERNEL);
 952                if (err) {
 953                        for (j = i-1; j >= 0; j--)
 954                                usb_kill_urb(cam->urb[j]);
 955                        DBG(1, "usb_submit_urb() failed, error %d", err);
 956                        goto free_urbs;
 957                }
 958        }
 959
 960        return 0;
 961
 962free_urbs:
 963        for (i = 0; (i < SN9C102_URBS) && cam->urb[i]; i++)
 964                usb_free_urb(cam->urb[i]);
 965
 966free_buffers:
 967        for (i = 0; (i < SN9C102_URBS) && cam->transfer_buffer[i]; i++)
 968                kfree(cam->transfer_buffer[i]);
 969
 970        return err;
 971}
 972
 973
 974static int sn9c102_stop_transfer(struct sn9c102_device* cam)
 975{
 976        struct usb_device *udev = cam->usbdev;
 977        s8 i;
 978        int err = 0;
 979
 980        if (cam->state & DEV_DISCONNECTED)
 981                return 0;
 982
 983        for (i = SN9C102_URBS-1; i >= 0; i--) {
 984                usb_kill_urb(cam->urb[i]);
 985                usb_free_urb(cam->urb[i]);
 986                kfree(cam->transfer_buffer[i]);
 987        }
 988
 989        err = usb_set_interface(udev, 0, 0); /* 0 Mb/s */
 990        if (err)
 991                DBG(3, "usb_set_interface() failed");
 992
 993        return err;
 994}
 995
 996
 997static int sn9c102_stream_interrupt(struct sn9c102_device* cam)
 998{
 999        cam->stream = STREAM_INTERRUPT;
1000        wait_event_timeout(cam->wait_stream,
1001                                     (cam->stream == STREAM_OFF) ||
1002                                     (cam->state & DEV_DISCONNECTED),
1003                                     SN9C102_URB_TIMEOUT);
1004        if (cam->state & DEV_DISCONNECTED)
1005                return -ENODEV;
1006        else if (cam->stream != STREAM_OFF) {
1007                cam->state |= DEV_MISCONFIGURED;
1008                DBG(1, "URB timeout reached. The camera is misconfigured. "
1009                       "To use it, close and open %s again.",
1010                    video_device_node_name(cam->v4ldev));
1011                return -EIO;
1012        }
1013
1014        return 0;
1015}
1016
1017/*****************************************************************************/
1018
1019#ifdef CONFIG_VIDEO_ADV_DEBUG
1020static u16 sn9c102_strtou16(const char* buff, size_t len, ssize_t* count)
1021{
1022        char str[7];
1023        char* endp;
1024        unsigned long val;
1025
1026        if (len < 6) {
1027                strncpy(str, buff, len);
1028                str[len] = '\0';
1029        } else {
1030                strncpy(str, buff, 6);
1031                str[6] = '\0';
1032        }
1033
1034        val = simple_strtoul(str, &endp, 0);
1035
1036        *count = 0;
1037        if (val <= 0xffff)
1038                *count = (ssize_t)(endp - str);
1039        if ((*count) && (len == *count+1) && (buff[*count] == '\n'))
1040                *count += 1;
1041
1042        return (u16)val;
1043}
1044
1045/*
1046   NOTE 1: being inside one of the following methods implies that the v4l
1047           device exists for sure (see kobjects and reference counters)
1048   NOTE 2: buffers are PAGE_SIZE long
1049*/
1050
1051static ssize_t sn9c102_show_reg(struct device* cd,
1052                                struct device_attribute *attr, char* buf)
1053{
1054        struct sn9c102_device* cam;
1055        ssize_t count;
1056
1057        if (mutex_lock_interruptible(&sn9c102_sysfs_lock))
1058                return -ERESTARTSYS;
1059
1060        cam = video_get_drvdata(container_of(cd, struct video_device, dev));
1061        if (!cam) {
1062                mutex_unlock(&sn9c102_sysfs_lock);
1063                return -ENODEV;
1064        }
1065
1066        count = sprintf(buf, "%u\n", cam->sysfs.reg);
1067
1068        mutex_unlock(&sn9c102_sysfs_lock);
1069
1070        return count;
1071}
1072
1073
1074static ssize_t
1075sn9c102_store_reg(struct device* cd, struct device_attribute *attr,
1076                  const char* buf, size_t len)
1077{
1078        struct sn9c102_device* cam;
1079        u16 index;
1080        ssize_t count;
1081
1082        if (mutex_lock_interruptible(&sn9c102_sysfs_lock))
1083                return -ERESTARTSYS;
1084
1085        cam = video_get_drvdata(container_of(cd, struct video_device, dev));
1086        if (!cam) {
1087                mutex_unlock(&sn9c102_sysfs_lock);
1088                return -ENODEV;
1089        }
1090
1091        index = sn9c102_strtou16(buf, len, &count);
1092        if (index >= ARRAY_SIZE(cam->reg) || !count) {
1093                mutex_unlock(&sn9c102_sysfs_lock);
1094                return -EINVAL;
1095        }
1096
1097        cam->sysfs.reg = index;
1098
1099        DBG(2, "Moved SN9C1XX register index to 0x%02X", cam->sysfs.reg);
1100        DBG(3, "Written bytes: %zd", count);
1101
1102        mutex_unlock(&sn9c102_sysfs_lock);
1103
1104        return count;
1105}
1106
1107
1108static ssize_t sn9c102_show_val(struct device* cd,
1109                                struct device_attribute *attr, char* buf)
1110{
1111        struct sn9c102_device* cam;
1112        ssize_t count;
1113        int val;
1114
1115        if (mutex_lock_interruptible(&sn9c102_sysfs_lock))
1116                return -ERESTARTSYS;
1117
1118        cam = video_get_drvdata(container_of(cd, struct video_device, dev));
1119        if (!cam) {
1120                mutex_unlock(&sn9c102_sysfs_lock);
1121                return -ENODEV;
1122        }
1123
1124        if ((val = sn9c102_read_reg(cam, cam->sysfs.reg)) < 0) {
1125                mutex_unlock(&sn9c102_sysfs_lock);
1126                return -EIO;
1127        }
1128
1129        count = sprintf(buf, "%d\n", val);
1130
1131        DBG(3, "Read bytes: %zd, value: %d", count, val);
1132
1133        mutex_unlock(&sn9c102_sysfs_lock);
1134
1135        return count;
1136}
1137
1138
1139static ssize_t
1140sn9c102_store_val(struct device* cd, struct device_attribute *attr,
1141                  const char* buf, size_t len)
1142{
1143        struct sn9c102_device* cam;
1144        u16 value;
1145        ssize_t count;
1146        int err;
1147
1148        if (mutex_lock_interruptible(&sn9c102_sysfs_lock))
1149                return -ERESTARTSYS;
1150
1151        cam = video_get_drvdata(container_of(cd, struct video_device, dev));
1152        if (!cam) {
1153                mutex_unlock(&sn9c102_sysfs_lock);
1154                return -ENODEV;
1155        }
1156
1157        value = sn9c102_strtou16(buf, len, &count);
1158        if (!count) {
1159                mutex_unlock(&sn9c102_sysfs_lock);
1160                return -EINVAL;
1161        }
1162
1163        err = sn9c102_write_reg(cam, value, cam->sysfs.reg);
1164        if (err) {
1165                mutex_unlock(&sn9c102_sysfs_lock);
1166                return -EIO;
1167        }
1168
1169        DBG(2, "Written SN9C1XX reg. 0x%02X, val. 0x%02X",
1170            cam->sysfs.reg, value);
1171        DBG(3, "Written bytes: %zd", count);
1172
1173        mutex_unlock(&sn9c102_sysfs_lock);
1174
1175        return count;
1176}
1177
1178
1179static ssize_t sn9c102_show_i2c_reg(struct device* cd,
1180                                    struct device_attribute *attr, char* buf)
1181{
1182        struct sn9c102_device* cam;
1183        ssize_t count;
1184
1185        if (mutex_lock_interruptible(&sn9c102_sysfs_lock))
1186                return -ERESTARTSYS;
1187
1188        cam = video_get_drvdata(container_of(cd, struct video_device, dev));
1189        if (!cam) {
1190                mutex_unlock(&sn9c102_sysfs_lock);
1191                return -ENODEV;
1192        }
1193
1194        count = sprintf(buf, "%u\n", cam->sysfs.i2c_reg);
1195
1196        DBG(3, "Read bytes: %zd", count);
1197
1198        mutex_unlock(&sn9c102_sysfs_lock);
1199
1200        return count;
1201}
1202
1203
1204static ssize_t
1205sn9c102_store_i2c_reg(struct device* cd, struct device_attribute *attr,
1206                      const char* buf, size_t len)
1207{
1208        struct sn9c102_device* cam;
1209        u16 index;
1210        ssize_t count;
1211
1212        if (mutex_lock_interruptible(&sn9c102_sysfs_lock))
1213                return -ERESTARTSYS;
1214
1215        cam = video_get_drvdata(container_of(cd, struct video_device, dev));
1216        if (!cam) {
1217                mutex_unlock(&sn9c102_sysfs_lock);
1218                return -ENODEV;
1219        }
1220
1221        index = sn9c102_strtou16(buf, len, &count);
1222        if (!count) {
1223                mutex_unlock(&sn9c102_sysfs_lock);
1224                return -EINVAL;
1225        }
1226
1227        cam->sysfs.i2c_reg = index;
1228
1229        DBG(2, "Moved sensor register index to 0x%02X", cam->sysfs.i2c_reg);
1230        DBG(3, "Written bytes: %zd", count);
1231
1232        mutex_unlock(&sn9c102_sysfs_lock);
1233
1234        return count;
1235}
1236
1237
1238static ssize_t sn9c102_show_i2c_val(struct device* cd,
1239                                    struct device_attribute *attr, char* buf)
1240{
1241        struct sn9c102_device* cam;
1242        ssize_t count;
1243        int val;
1244
1245        if (mutex_lock_interruptible(&sn9c102_sysfs_lock))
1246                return -ERESTARTSYS;
1247
1248        cam = video_get_drvdata(container_of(cd, struct video_device, dev));
1249        if (!cam) {
1250                mutex_unlock(&sn9c102_sysfs_lock);
1251                return -ENODEV;
1252        }
1253
1254        if (!(cam->sensor.sysfs_ops & SN9C102_I2C_READ)) {
1255                mutex_unlock(&sn9c102_sysfs_lock);
1256                return -ENOSYS;
1257        }
1258
1259        if ((val = sn9c102_i2c_read(cam, cam->sysfs.i2c_reg)) < 0) {
1260                mutex_unlock(&sn9c102_sysfs_lock);
1261                return -EIO;
1262        }
1263
1264        count = sprintf(buf, "%d\n", val);
1265
1266        DBG(3, "Read bytes: %zd, value: %d", count, val);
1267
1268        mutex_unlock(&sn9c102_sysfs_lock);
1269
1270        return count;
1271}
1272
1273
1274static ssize_t
1275sn9c102_store_i2c_val(struct device* cd, struct device_attribute *attr,
1276                      const char* buf, size_t len)
1277{
1278        struct sn9c102_device* cam;
1279        u16 value;
1280        ssize_t count;
1281        int err;
1282
1283        if (mutex_lock_interruptible(&sn9c102_sysfs_lock))
1284                return -ERESTARTSYS;
1285
1286        cam = video_get_drvdata(container_of(cd, struct video_device, dev));
1287        if (!cam) {
1288                mutex_unlock(&sn9c102_sysfs_lock);
1289                return -ENODEV;
1290        }
1291
1292        if (!(cam->sensor.sysfs_ops & SN9C102_I2C_WRITE)) {
1293                mutex_unlock(&sn9c102_sysfs_lock);
1294                return -ENOSYS;
1295        }
1296
1297        value = sn9c102_strtou16(buf, len, &count);
1298        if (!count) {
1299                mutex_unlock(&sn9c102_sysfs_lock);
1300                return -EINVAL;
1301        }
1302
1303        err = sn9c102_i2c_write(cam, cam->sysfs.i2c_reg, value);
1304        if (err) {
1305                mutex_unlock(&sn9c102_sysfs_lock);
1306                return -EIO;
1307        }
1308
1309        DBG(2, "Written sensor reg. 0x%02X, val. 0x%02X",
1310            cam->sysfs.i2c_reg, value);
1311        DBG(3, "Written bytes: %zd", count);
1312
1313        mutex_unlock(&sn9c102_sysfs_lock);
1314
1315        return count;
1316}
1317
1318
1319static ssize_t
1320sn9c102_store_green(struct device* cd, struct device_attribute *attr,
1321                    const char* buf, size_t len)
1322{
1323        struct sn9c102_device* cam;
1324        enum sn9c102_bridge bridge;
1325        ssize_t res = 0;
1326        u16 value;
1327        ssize_t count;
1328
1329        if (mutex_lock_interruptible(&sn9c102_sysfs_lock))
1330                return -ERESTARTSYS;
1331
1332        cam = video_get_drvdata(container_of(cd, struct video_device, dev));
1333        if (!cam) {
1334                mutex_unlock(&sn9c102_sysfs_lock);
1335                return -ENODEV;
1336        }
1337
1338        bridge = cam->bridge;
1339
1340        mutex_unlock(&sn9c102_sysfs_lock);
1341
1342        value = sn9c102_strtou16(buf, len, &count);
1343        if (!count)
1344                return -EINVAL;
1345
1346        switch (bridge) {
1347        case BRIDGE_SN9C101:
1348        case BRIDGE_SN9C102:
1349                if (value > 0x0f)
1350                        return -EINVAL;
1351                if ((res = sn9c102_store_reg(cd, attr, "0x11", 4)) >= 0)
1352                        res = sn9c102_store_val(cd, attr, buf, len);
1353                break;
1354        case BRIDGE_SN9C103:
1355        case BRIDGE_SN9C105:
1356        case BRIDGE_SN9C120:
1357                if (value > 0x7f)
1358                        return -EINVAL;
1359                if ((res = sn9c102_store_reg(cd, attr, "0x07", 4)) >= 0)
1360                        res = sn9c102_store_val(cd, attr, buf, len);
1361                break;
1362        }
1363
1364        return res;
1365}
1366
1367
1368static ssize_t
1369sn9c102_store_blue(struct device* cd, struct device_attribute *attr,
1370                   const char* buf, size_t len)
1371{
1372        ssize_t res = 0;
1373        u16 value;
1374        ssize_t count;
1375
1376        value = sn9c102_strtou16(buf, len, &count);
1377        if (!count || value > 0x7f)
1378                return -EINVAL;
1379
1380        if ((res = sn9c102_store_reg(cd, attr, "0x06", 4)) >= 0)
1381                res = sn9c102_store_val(cd, attr, buf, len);
1382
1383        return res;
1384}
1385
1386
1387static ssize_t
1388sn9c102_store_red(struct device* cd, struct device_attribute *attr,
1389                  const char* buf, size_t len)
1390{
1391        ssize_t res = 0;
1392        u16 value;
1393        ssize_t count;
1394
1395        value = sn9c102_strtou16(buf, len, &count);
1396        if (!count || value > 0x7f)
1397                return -EINVAL;
1398
1399        if ((res = sn9c102_store_reg(cd, attr, "0x05", 4)) >= 0)
1400                res = sn9c102_store_val(cd, attr, buf, len);
1401
1402        return res;
1403}
1404
1405
1406static ssize_t sn9c102_show_frame_header(struct device* cd,
1407                                         struct device_attribute *attr,
1408                                         char* buf)
1409{
1410        struct sn9c102_device* cam;
1411        ssize_t count;
1412
1413        cam = video_get_drvdata(container_of(cd, struct video_device, dev));
1414        if (!cam)
1415                return -ENODEV;
1416
1417        count = sizeof(cam->sysfs.frame_header);
1418        memcpy(buf, cam->sysfs.frame_header, count);
1419
1420        DBG(3, "Frame header, read bytes: %zd", count);
1421
1422        return count;
1423}
1424
1425
1426static DEVICE_ATTR(reg, S_IRUGO | S_IWUSR, sn9c102_show_reg, sn9c102_store_reg);
1427static DEVICE_ATTR(val, S_IRUGO | S_IWUSR, sn9c102_show_val, sn9c102_store_val);
1428static DEVICE_ATTR(i2c_reg, S_IRUGO | S_IWUSR,
1429                   sn9c102_show_i2c_reg, sn9c102_store_i2c_reg);
1430static DEVICE_ATTR(i2c_val, S_IRUGO | S_IWUSR,
1431                   sn9c102_show_i2c_val, sn9c102_store_i2c_val);
1432static DEVICE_ATTR(green, S_IWUSR, NULL, sn9c102_store_green);
1433static DEVICE_ATTR(blue, S_IWUSR, NULL, sn9c102_store_blue);
1434static DEVICE_ATTR(red, S_IWUSR, NULL, sn9c102_store_red);
1435static DEVICE_ATTR(frame_header, S_IRUGO, sn9c102_show_frame_header, NULL);
1436
1437
1438static int sn9c102_create_sysfs(struct sn9c102_device* cam)
1439{
1440        struct device *dev = &(cam->v4ldev->dev);
1441        int err = 0;
1442
1443        if ((err = device_create_file(dev, &dev_attr_reg)))
1444                goto err_out;
1445        if ((err = device_create_file(dev, &dev_attr_val)))
1446                goto err_reg;
1447        if ((err = device_create_file(dev, &dev_attr_frame_header)))
1448                goto err_val;
1449
1450        if (cam->sensor.sysfs_ops) {
1451                if ((err = device_create_file(dev, &dev_attr_i2c_reg)))
1452                        goto err_frame_header;
1453                if ((err = device_create_file(dev, &dev_attr_i2c_val)))
1454                        goto err_i2c_reg;
1455        }
1456
1457        if (cam->bridge == BRIDGE_SN9C101 || cam->bridge == BRIDGE_SN9C102) {
1458                if ((err = device_create_file(dev, &dev_attr_green)))
1459                        goto err_i2c_val;
1460        } else {
1461                if ((err = device_create_file(dev, &dev_attr_blue)))
1462                        goto err_i2c_val;
1463                if ((err = device_create_file(dev, &dev_attr_red)))
1464                        goto err_blue;
1465        }
1466
1467        return 0;
1468
1469err_blue:
1470        device_remove_file(dev, &dev_attr_blue);
1471err_i2c_val:
1472        if (cam->sensor.sysfs_ops)
1473                device_remove_file(dev, &dev_attr_i2c_val);
1474err_i2c_reg:
1475        if (cam->sensor.sysfs_ops)
1476                device_remove_file(dev, &dev_attr_i2c_reg);
1477err_frame_header:
1478        device_remove_file(dev, &dev_attr_frame_header);
1479err_val:
1480        device_remove_file(dev, &dev_attr_val);
1481err_reg:
1482        device_remove_file(dev, &dev_attr_reg);
1483err_out:
1484        return err;
1485}
1486#endif /* CONFIG_VIDEO_ADV_DEBUG */
1487
1488/*****************************************************************************/
1489
1490static int
1491sn9c102_set_pix_format(struct sn9c102_device* cam, struct v4l2_pix_format* pix)
1492{
1493        int err = 0;
1494
1495        if (pix->pixelformat == V4L2_PIX_FMT_SN9C10X ||
1496            pix->pixelformat == V4L2_PIX_FMT_JPEG) {
1497                switch (cam->bridge) {
1498                case BRIDGE_SN9C101:
1499                case BRIDGE_SN9C102:
1500                case BRIDGE_SN9C103:
1501                        err += sn9c102_write_reg(cam, cam->reg[0x18] | 0x80,
1502                                                 0x18);
1503                        break;
1504                case BRIDGE_SN9C105:
1505                case BRIDGE_SN9C120:
1506                        err += sn9c102_write_reg(cam, cam->reg[0x18] & 0x7f,
1507                                                 0x18);
1508                        break;
1509                }
1510        } else {
1511                switch (cam->bridge) {
1512                case BRIDGE_SN9C101:
1513                case BRIDGE_SN9C102:
1514                case BRIDGE_SN9C103:
1515                        err += sn9c102_write_reg(cam, cam->reg[0x18] & 0x7f,
1516                                                 0x18);
1517                        break;
1518                case BRIDGE_SN9C105:
1519                case BRIDGE_SN9C120:
1520                        err += sn9c102_write_reg(cam, cam->reg[0x18] | 0x80,
1521                                                 0x18);
1522                        break;
1523                }
1524        }
1525
1526        return err ? -EIO : 0;
1527}
1528
1529
1530static int
1531sn9c102_set_compression(struct sn9c102_device* cam,
1532                        struct v4l2_jpegcompression* compression)
1533{
1534        int i, err = 0;
1535
1536        switch (cam->bridge) {
1537        case BRIDGE_SN9C101:
1538        case BRIDGE_SN9C102:
1539        case BRIDGE_SN9C103:
1540                if (compression->quality == 0)
1541                        err += sn9c102_write_reg(cam, cam->reg[0x17] | 0x01,
1542                                                 0x17);
1543                else if (compression->quality == 1)
1544                        err += sn9c102_write_reg(cam, cam->reg[0x17] & 0xfe,
1545                                                 0x17);
1546                break;
1547        case BRIDGE_SN9C105:
1548        case BRIDGE_SN9C120:
1549                if (compression->quality == 0) {
1550                        for (i = 0; i <= 63; i++) {
1551                                err += sn9c102_write_reg(cam,
1552                                                         SN9C102_Y_QTABLE1[i],
1553                                                         0x100 + i);
1554                                err += sn9c102_write_reg(cam,
1555                                                         SN9C102_UV_QTABLE1[i],
1556                                                         0x140 + i);
1557                        }
1558                        err += sn9c102_write_reg(cam, cam->reg[0x18] & 0xbf,
1559                                                 0x18);
1560                } else if (compression->quality == 1) {
1561                        for (i = 0; i <= 63; i++) {
1562                                err += sn9c102_write_reg(cam,
1563                                                         SN9C102_Y_QTABLE1[i],
1564                                                         0x100 + i);
1565                                err += sn9c102_write_reg(cam,
1566                                                         SN9C102_UV_QTABLE1[i],
1567                                                         0x140 + i);
1568                        }
1569                        err += sn9c102_write_reg(cam, cam->reg[0x18] | 0x40,
1570                                                 0x18);
1571                }
1572                break;
1573        }
1574
1575        return err ? -EIO : 0;
1576}
1577
1578
1579static int sn9c102_set_scale(struct sn9c102_device* cam, u8 scale)
1580{
1581        u8 r = 0;
1582        int err = 0;
1583
1584        if (scale == 1)
1585                r = cam->reg[0x18] & 0xcf;
1586        else if (scale == 2) {
1587                r = cam->reg[0x18] & 0xcf;
1588                r |= 0x10;
1589        } else if (scale == 4)
1590                r = cam->reg[0x18] | 0x20;
1591
1592        err += sn9c102_write_reg(cam, r, 0x18);
1593        if (err)
1594                return -EIO;
1595
1596        PDBGG("Scaling factor: %u", scale);
1597
1598        return 0;
1599}
1600
1601
1602static int sn9c102_set_crop(struct sn9c102_device* cam, struct v4l2_rect* rect)
1603{
1604        struct sn9c102_sensor* s = &cam->sensor;
1605        u8 h_start = (u8)(rect->left - s->cropcap.bounds.left),
1606           v_start = (u8)(rect->top - s->cropcap.bounds.top),
1607           h_size = (u8)(rect->width / 16),
1608           v_size = (u8)(rect->height / 16);
1609        int err = 0;
1610
1611        err += sn9c102_write_reg(cam, h_start, 0x12);
1612        err += sn9c102_write_reg(cam, v_start, 0x13);
1613        err += sn9c102_write_reg(cam, h_size, 0x15);
1614        err += sn9c102_write_reg(cam, v_size, 0x16);
1615        if (err)
1616                return -EIO;
1617
1618        PDBGG("h_start, v_start, h_size, v_size, ho_size, vo_size "
1619              "%u %u %u %u", h_start, v_start, h_size, v_size);
1620
1621        return 0;
1622}
1623
1624
1625static int sn9c102_init(struct sn9c102_device* cam)
1626{
1627        struct sn9c102_sensor* s = &cam->sensor;
1628        struct v4l2_control ctrl;
1629        struct v4l2_queryctrl *qctrl;
1630        struct v4l2_rect* rect;
1631        u8 i = 0;
1632        int err = 0;
1633
1634        if (!(cam->state & DEV_INITIALIZED)) {
1635                mutex_init(&cam->open_mutex);
1636                init_waitqueue_head(&cam->wait_open);
1637                qctrl = s->qctrl;
1638                rect = &(s->cropcap.defrect);
1639        } else { /* use current values */
1640                qctrl = s->_qctrl;
1641                rect = &(s->_rect);
1642        }
1643
1644        err += sn9c102_set_scale(cam, rect->width / s->pix_format.width);
1645        err += sn9c102_set_crop(cam, rect);
1646        if (err)
1647                return err;
1648
1649        if (s->init) {
1650                err = s->init(cam);
1651                if (err) {
1652                        DBG(3, "Sensor initialization failed");
1653                        return err;
1654                }
1655        }
1656
1657        if (!(cam->state & DEV_INITIALIZED))
1658                if (cam->bridge == BRIDGE_SN9C101 ||
1659                    cam->bridge == BRIDGE_SN9C102 ||
1660                    cam->bridge == BRIDGE_SN9C103) {
1661                        if (s->pix_format.pixelformat == V4L2_PIX_FMT_JPEG)
1662                                s->pix_format.pixelformat= V4L2_PIX_FMT_SBGGR8;
1663                        cam->compression.quality =  cam->reg[0x17] & 0x01 ?
1664                                                    0 : 1;
1665                } else {
1666                        if (s->pix_format.pixelformat == V4L2_PIX_FMT_SN9C10X)
1667                                s->pix_format.pixelformat = V4L2_PIX_FMT_JPEG;
1668                        cam->compression.quality =  cam->reg[0x18] & 0x40 ?
1669                                                    0 : 1;
1670                        err += sn9c102_set_compression(cam, &cam->compression);
1671                }
1672        else
1673                err += sn9c102_set_compression(cam, &cam->compression);
1674        err += sn9c102_set_pix_format(cam, &s->pix_format);
1675        if (s->set_pix_format)
1676                err += s->set_pix_format(cam, &s->pix_format);
1677        if (err)
1678                return err;
1679
1680        if (s->pix_format.pixelformat == V4L2_PIX_FMT_SN9C10X ||
1681            s->pix_format.pixelformat == V4L2_PIX_FMT_JPEG)
1682                DBG(3, "Compressed video format is active, quality %d",
1683                    cam->compression.quality);
1684        else
1685                DBG(3, "Uncompressed video format is active");
1686
1687        if (s->set_crop)
1688                if ((err = s->set_crop(cam, rect))) {
1689                        DBG(3, "set_crop() failed");
1690                        return err;
1691                }
1692
1693        if (s->set_ctrl) {
1694                for (i = 0; i < ARRAY_SIZE(s->qctrl); i++)
1695                        if (s->qctrl[i].id != 0 &&
1696                            !(s->qctrl[i].flags & V4L2_CTRL_FLAG_DISABLED)) {
1697                                ctrl.id = s->qctrl[i].id;
1698                                ctrl.value = qctrl[i].default_value;
1699                                err = s->set_ctrl(cam, &ctrl);
1700                                if (err) {
1701                                        DBG(3, "Set %s control failed",
1702                                            s->qctrl[i].name);
1703                                        return err;
1704                                }
1705                                DBG(3, "Image sensor supports '%s' control",
1706                                    s->qctrl[i].name);
1707                        }
1708        }
1709
1710        if (!(cam->state & DEV_INITIALIZED)) {
1711                mutex_init(&cam->fileop_mutex);
1712                spin_lock_init(&cam->queue_lock);
1713                init_waitqueue_head(&cam->wait_frame);
1714                init_waitqueue_head(&cam->wait_stream);
1715                cam->nreadbuffers = 2;
1716                memcpy(s->_qctrl, s->qctrl, sizeof(s->qctrl));
1717                memcpy(&(s->_rect), &(s->cropcap.defrect),
1718                       sizeof(struct v4l2_rect));
1719                cam->state |= DEV_INITIALIZED;
1720        }
1721
1722        DBG(2, "Initialization succeeded");
1723        return 0;
1724}
1725
1726/*****************************************************************************/
1727
1728static void sn9c102_release_resources(struct kref *kref)
1729{
1730        struct sn9c102_device *cam;
1731
1732        mutex_lock(&sn9c102_sysfs_lock);
1733
1734        cam = container_of(kref, struct sn9c102_device, kref);
1735
1736        DBG(2, "V4L2 device %s deregistered",
1737            video_device_node_name(cam->v4ldev));
1738        video_set_drvdata(cam->v4ldev, NULL);
1739        video_unregister_device(cam->v4ldev);
1740        usb_put_dev(cam->usbdev);
1741        kfree(cam->control_buffer);
1742        kfree(cam);
1743
1744        mutex_unlock(&sn9c102_sysfs_lock);
1745
1746}
1747
1748
1749static int sn9c102_open(struct file *filp)
1750{
1751        struct sn9c102_device* cam;
1752        int err = 0;
1753
1754        /*
1755           A read_trylock() in open() is the only safe way to prevent race
1756           conditions with disconnect(), one close() and multiple (not
1757           necessarily simultaneous) attempts to open(). For example, it
1758           prevents from waiting for a second access, while the device
1759           structure is being deallocated, after a possible disconnect() and
1760           during a following close() holding the write lock: given that, after
1761           this deallocation, no access will be possible anymore, using the
1762           non-trylock version would have let open() gain the access to the
1763           device structure improperly.
1764           For this reason the lock must also not be per-device.
1765        */
1766        if (!down_read_trylock(&sn9c102_dev_lock))
1767                return -ERESTARTSYS;
1768
1769        cam = video_drvdata(filp);
1770
1771        if (wait_for_completion_interruptible(&cam->probe)) {
1772                up_read(&sn9c102_dev_lock);
1773                return -ERESTARTSYS;
1774        }
1775
1776        kref_get(&cam->kref);
1777
1778        /*
1779            Make sure to isolate all the simultaneous opens.
1780        */
1781        if (mutex_lock_interruptible(&cam->open_mutex)) {
1782                kref_put(&cam->kref, sn9c102_release_resources);
1783                up_read(&sn9c102_dev_lock);
1784                return -ERESTARTSYS;
1785        }
1786
1787        if (cam->state & DEV_DISCONNECTED) {
1788                DBG(1, "Device not present");
1789                err = -ENODEV;
1790                goto out;
1791        }
1792
1793        if (cam->users) {
1794                DBG(2, "Device %s is already in use",
1795                    video_device_node_name(cam->v4ldev));
1796                DBG(3, "Simultaneous opens are not supported");
1797                /*
1798                   open() must follow the open flags and should block
1799                   eventually while the device is in use.
1800                */
1801                if ((filp->f_flags & O_NONBLOCK) ||
1802                    (filp->f_flags & O_NDELAY)) {
1803                        err = -EWOULDBLOCK;
1804                        goto out;
1805                }
1806                DBG(2, "A blocking open() has been requested. Wait for the "
1807                       "device to be released...");
1808                up_read(&sn9c102_dev_lock);
1809                /*
1810                   We will not release the "open_mutex" lock, so that only one
1811                   process can be in the wait queue below. This way the process
1812                   will be sleeping while holding the lock, without losing its
1813                   priority after any wake_up().
1814                */
1815                err = wait_event_interruptible_exclusive(cam->wait_open,
1816                                                (cam->state & DEV_DISCONNECTED)
1817                                                         || !cam->users);
1818                down_read(&sn9c102_dev_lock);
1819                if (err)
1820                        goto out;
1821                if (cam->state & DEV_DISCONNECTED) {
1822                        err = -ENODEV;
1823                        goto out;
1824                }
1825        }
1826
1827        if (cam->state & DEV_MISCONFIGURED) {
1828                err = sn9c102_init(cam);
1829                if (err) {
1830                        DBG(1, "Initialization failed again. "
1831                               "I will retry on next open().");
1832                        goto out;
1833                }
1834                cam->state &= ~DEV_MISCONFIGURED;
1835        }
1836
1837        if ((err = sn9c102_start_transfer(cam)))
1838                goto out;
1839
1840        filp->private_data = cam;
1841        cam->users++;
1842        cam->io = IO_NONE;
1843        cam->stream = STREAM_OFF;
1844        cam->nbuffers = 0;
1845        cam->frame_count = 0;
1846        sn9c102_empty_framequeues(cam);
1847
1848        DBG(3, "Video device %s is open", video_device_node_name(cam->v4ldev));
1849
1850out:
1851        mutex_unlock(&cam->open_mutex);
1852        if (err)
1853                kref_put(&cam->kref, sn9c102_release_resources);
1854
1855        up_read(&sn9c102_dev_lock);
1856        return err;
1857}
1858
1859
1860static int sn9c102_release(struct file *filp)
1861{
1862        struct sn9c102_device* cam;
1863
1864        down_write(&sn9c102_dev_lock);
1865
1866        cam = video_drvdata(filp);
1867
1868        sn9c102_stop_transfer(cam);
1869        sn9c102_release_buffers(cam);
1870        cam->users--;
1871        wake_up_interruptible_nr(&cam->wait_open, 1);
1872
1873        DBG(3, "Video device %s closed", video_device_node_name(cam->v4ldev));
1874
1875        kref_put(&cam->kref, sn9c102_release_resources);
1876
1877        up_write(&sn9c102_dev_lock);
1878
1879        return 0;
1880}
1881
1882
1883static ssize_t
1884sn9c102_read(struct file* filp, char __user * buf, size_t count, loff_t* f_pos)
1885{
1886        struct sn9c102_device *cam = video_drvdata(filp);
1887        struct sn9c102_frame_t* f, * i;
1888        unsigned long lock_flags;
1889        long timeout;
1890        int err = 0;
1891
1892        if (mutex_lock_interruptible(&cam->fileop_mutex))
1893                return -ERESTARTSYS;
1894
1895        if (cam->state & DEV_DISCONNECTED) {
1896                DBG(1, "Device not present");
1897                mutex_unlock(&cam->fileop_mutex);
1898                return -ENODEV;
1899        }
1900
1901        if (cam->state & DEV_MISCONFIGURED) {
1902                DBG(1, "The camera is misconfigured. Close and open it "
1903                       "again.");
1904                mutex_unlock(&cam->fileop_mutex);
1905                return -EIO;
1906        }
1907
1908        if (cam->io == IO_MMAP) {
1909                DBG(3, "Close and open the device again to choose "
1910                       "the read method");
1911                mutex_unlock(&cam->fileop_mutex);
1912                return -EBUSY;
1913        }
1914
1915        if (cam->io == IO_NONE) {
1916                if (!sn9c102_request_buffers(cam,cam->nreadbuffers, IO_READ)) {
1917                        DBG(1, "read() failed, not enough memory");
1918                        mutex_unlock(&cam->fileop_mutex);
1919                        return -ENOMEM;
1920                }
1921                cam->io = IO_READ;
1922                cam->stream = STREAM_ON;
1923        }
1924
1925        if (list_empty(&cam->inqueue)) {
1926                if (!list_empty(&cam->outqueue))
1927                        sn9c102_empty_framequeues(cam);
1928                sn9c102_queue_unusedframes(cam);
1929        }
1930
1931        if (!count) {
1932                mutex_unlock(&cam->fileop_mutex);
1933                return 0;
1934        }
1935
1936        if (list_empty(&cam->outqueue)) {
1937                if (filp->f_flags & O_NONBLOCK) {
1938                        mutex_unlock(&cam->fileop_mutex);
1939                        return -EAGAIN;
1940                }
1941                if (!cam->module_param.frame_timeout) {
1942                        err = wait_event_interruptible
1943                              ( cam->wait_frame,
1944                                (!list_empty(&cam->outqueue)) ||
1945                                (cam->state & DEV_DISCONNECTED) ||
1946                                (cam->state & DEV_MISCONFIGURED) );
1947                        if (err) {
1948                                mutex_unlock(&cam->fileop_mutex);
1949                                return err;
1950                        }
1951                } else {
1952                        timeout = wait_event_interruptible_timeout
1953                                  ( cam->wait_frame,
1954                                    (!list_empty(&cam->outqueue)) ||
1955                                    (cam->state & DEV_DISCONNECTED) ||
1956                                    (cam->state & DEV_MISCONFIGURED),
1957                                    msecs_to_jiffies(
1958                                        cam->module_param.frame_timeout * 1000
1959                                    )
1960                                  );
1961                        if (timeout < 0) {
1962                                mutex_unlock(&cam->fileop_mutex);
1963                                return timeout;
1964                        } else if (timeout == 0 &&
1965                                   !(cam->state & DEV_DISCONNECTED)) {
1966                                DBG(1, "Video frame timeout elapsed");
1967                                mutex_unlock(&cam->fileop_mutex);
1968                                return -EIO;
1969                        }
1970                }
1971                if (cam->state & DEV_DISCONNECTED) {
1972                        mutex_unlock(&cam->fileop_mutex);
1973                        return -ENODEV;
1974                }
1975                if (cam->state & DEV_MISCONFIGURED) {
1976                        mutex_unlock(&cam->fileop_mutex);
1977                        return -EIO;
1978                }
1979        }
1980
1981        f = list_entry(cam->outqueue.prev, struct sn9c102_frame_t, frame);
1982
1983        if (count > f->buf.bytesused)
1984                count = f->buf.bytesused;
1985
1986        if (copy_to_user(buf, f->bufmem, count)) {
1987                err = -EFAULT;
1988                goto exit;
1989        }
1990        *f_pos += count;
1991
1992exit:
1993        spin_lock_irqsave(&cam->queue_lock, lock_flags);
1994        list_for_each_entry(i, &cam->outqueue, frame)
1995                i->state = F_UNUSED;
1996        INIT_LIST_HEAD(&cam->outqueue);
1997        spin_unlock_irqrestore(&cam->queue_lock, lock_flags);
1998
1999        sn9c102_queue_unusedframes(cam);
2000
2001        PDBGG("Frame #%lu, bytes read: %zu",
2002              (unsigned long)f->buf.index, count);
2003
2004        mutex_unlock(&cam->fileop_mutex);
2005
2006        return count;
2007}
2008
2009
2010static unsigned int sn9c102_poll(struct file *filp, poll_table *wait)
2011{
2012        struct sn9c102_device *cam = video_drvdata(filp);
2013        struct sn9c102_frame_t* f;
2014        unsigned long lock_flags;
2015        unsigned int mask = 0;
2016
2017        if (mutex_lock_interruptible(&cam->fileop_mutex))
2018                return POLLERR;
2019
2020        if (cam->state & DEV_DISCONNECTED) {
2021                DBG(1, "Device not present");
2022                goto error;
2023        }
2024
2025        if (cam->state & DEV_MISCONFIGURED) {
2026                DBG(1, "The camera is misconfigured. Close and open it "
2027                       "again.");
2028                goto error;
2029        }
2030
2031        if (cam->io == IO_NONE) {
2032                if (!sn9c102_request_buffers(cam, cam->nreadbuffers,
2033                                             IO_READ)) {
2034                        DBG(1, "poll() failed, not enough memory");
2035                        goto error;
2036                }
2037                cam->io = IO_READ;
2038                cam->stream = STREAM_ON;
2039        }
2040
2041        if (cam->io == IO_READ) {
2042                spin_lock_irqsave(&cam->queue_lock, lock_flags);
2043                list_for_each_entry(f, &cam->outqueue, frame)
2044                        f->state = F_UNUSED;
2045                INIT_LIST_HEAD(&cam->outqueue);
2046                spin_unlock_irqrestore(&cam->queue_lock, lock_flags);
2047                sn9c102_queue_unusedframes(cam);
2048        }
2049
2050        poll_wait(filp, &cam->wait_frame, wait);
2051
2052        if (!list_empty(&cam->outqueue))
2053                mask |= POLLIN | POLLRDNORM;
2054
2055        mutex_unlock(&cam->fileop_mutex);
2056
2057        return mask;
2058
2059error:
2060        mutex_unlock(&cam->fileop_mutex);
2061        return POLLERR;
2062}
2063
2064
2065static void sn9c102_vm_open(struct vm_area_struct* vma)
2066{
2067        struct sn9c102_frame_t* f = vma->vm_private_data;
2068        f->vma_use_count++;
2069}
2070
2071
2072static void sn9c102_vm_close(struct vm_area_struct* vma)
2073{
2074        /* NOTE: buffers are not freed here */
2075        struct sn9c102_frame_t* f = vma->vm_private_data;
2076        f->vma_use_count--;
2077}
2078
2079
2080static const struct vm_operations_struct sn9c102_vm_ops = {
2081        .open = sn9c102_vm_open,
2082        .close = sn9c102_vm_close,
2083};
2084
2085
2086static int sn9c102_mmap(struct file* filp, struct vm_area_struct *vma)
2087{
2088        struct sn9c102_device *cam = video_drvdata(filp);
2089        unsigned long size = vma->vm_end - vma->vm_start,
2090                      start = vma->vm_start;
2091        void *pos;
2092        u32 i;
2093
2094        if (mutex_lock_interruptible(&cam->fileop_mutex))
2095                return -ERESTARTSYS;
2096
2097        if (cam->state & DEV_DISCONNECTED) {
2098                DBG(1, "Device not present");
2099                mutex_unlock(&cam->fileop_mutex);
2100                return -ENODEV;
2101        }
2102
2103        if (cam->state & DEV_MISCONFIGURED) {
2104                DBG(1, "The camera is misconfigured. Close and open it "
2105                       "again.");
2106                mutex_unlock(&cam->fileop_mutex);
2107                return -EIO;
2108        }
2109
2110        if (!(vma->vm_flags & (VM_WRITE | VM_READ))) {
2111                mutex_unlock(&cam->fileop_mutex);
2112                return -EACCES;
2113        }
2114
2115        if (cam->io != IO_MMAP ||
2116            size != PAGE_ALIGN(cam->frame[0].buf.length)) {
2117                mutex_unlock(&cam->fileop_mutex);
2118                return -EINVAL;
2119        }
2120
2121        for (i = 0; i < cam->nbuffers; i++) {
2122                if ((cam->frame[i].buf.m.offset>>PAGE_SHIFT) == vma->vm_pgoff)
2123                        break;
2124        }
2125        if (i == cam->nbuffers) {
2126                mutex_unlock(&cam->fileop_mutex);
2127                return -EINVAL;
2128        }
2129
2130        vma->vm_flags |= VM_IO | VM_DONTEXPAND | VM_DONTDUMP;
2131
2132        pos = cam->frame[i].bufmem;
2133        while (size > 0) { /* size is page-aligned */
2134                if (vm_insert_page(vma, start, vmalloc_to_page(pos))) {
2135                        mutex_unlock(&cam->fileop_mutex);
2136                        return -EAGAIN;
2137                }
2138                start += PAGE_SIZE;
2139                pos += PAGE_SIZE;
2140                size -= PAGE_SIZE;
2141        }
2142
2143        vma->vm_ops = &sn9c102_vm_ops;
2144        vma->vm_private_data = &cam->frame[i];
2145        sn9c102_vm_open(vma);
2146
2147        mutex_unlock(&cam->fileop_mutex);
2148
2149        return 0;
2150}
2151
2152/*****************************************************************************/
2153
2154static int
2155sn9c102_vidioc_querycap(struct sn9c102_device* cam, void __user * arg)
2156{
2157        struct v4l2_capability cap = {
2158                .driver = "sn9c102",
2159                .version = LINUX_VERSION_CODE,
2160                .capabilities = V4L2_CAP_VIDEO_CAPTURE | V4L2_CAP_READWRITE |
2161                                V4L2_CAP_STREAMING,
2162        };
2163
2164        strlcpy(cap.card, cam->v4ldev->name, sizeof(cap.card));
2165        if (usb_make_path(cam->usbdev, cap.bus_info, sizeof(cap.bus_info)) < 0)
2166                strlcpy(cap.bus_info, dev_name(&cam->usbdev->dev),
2167                        sizeof(cap.bus_info));
2168
2169        if (copy_to_user(arg, &cap, sizeof(cap)))
2170                return -EFAULT;
2171
2172        return 0;
2173}
2174
2175
2176static int
2177sn9c102_vidioc_enuminput(struct sn9c102_device* cam, void __user * arg)
2178{
2179        struct v4l2_input i;
2180
2181        if (copy_from_user(&i, arg, sizeof(i)))
2182                return -EFAULT;
2183
2184        if (i.index)
2185                return -EINVAL;
2186
2187        memset(&i, 0, sizeof(i));
2188        strcpy(i.name, "Camera");
2189        i.type = V4L2_INPUT_TYPE_CAMERA;
2190        i.capabilities = V4L2_IN_CAP_STD;
2191
2192        if (copy_to_user(arg, &i, sizeof(i)))
2193                return -EFAULT;
2194
2195        return 0;
2196}
2197
2198
2199static int
2200sn9c102_vidioc_g_input(struct sn9c102_device* cam, void __user * arg)
2201{
2202        int index = 0;
2203
2204        if (copy_to_user(arg, &index, sizeof(index)))
2205                return -EFAULT;
2206
2207        return 0;
2208}
2209
2210
2211static int
2212sn9c102_vidioc_s_input(struct sn9c102_device* cam, void __user * arg)
2213{
2214        int index;
2215
2216        if (copy_from_user(&index, arg, sizeof(index)))
2217                return -EFAULT;
2218
2219        if (index != 0)
2220                return -EINVAL;
2221
2222        return 0;
2223}
2224
2225
2226static int
2227sn9c102_vidioc_query_ctrl(struct sn9c102_device* cam, void __user * arg)
2228{
2229        struct sn9c102_sensor* s = &cam->sensor;
2230        struct v4l2_queryctrl qc;
2231        u8 i;
2232
2233        if (copy_from_user(&qc, arg, sizeof(qc)))
2234                return -EFAULT;
2235
2236        for (i = 0; i < ARRAY_SIZE(s->qctrl); i++)
2237                if (qc.id && qc.id == s->qctrl[i].id) {
2238                        memcpy(&qc, &(s->qctrl[i]), sizeof(qc));
2239                        if (copy_to_user(arg, &qc, sizeof(qc)))
2240                                return -EFAULT;
2241                        return 0;
2242                }
2243
2244        return -EINVAL;
2245}
2246
2247
2248static int
2249sn9c102_vidioc_g_ctrl(struct sn9c102_device* cam, void __user * arg)
2250{
2251        struct sn9c102_sensor* s = &cam->sensor;
2252        struct v4l2_control ctrl;
2253        int err = 0;
2254        u8 i;
2255
2256        if (!s->get_ctrl && !s->set_ctrl)
2257                return -EINVAL;
2258
2259        if (copy_from_user(&ctrl, arg, sizeof(ctrl)))
2260                return -EFAULT;
2261
2262        if (!s->get_ctrl) {
2263                for (i = 0; i < ARRAY_SIZE(s->qctrl); i++)
2264                        if (ctrl.id && ctrl.id == s->qctrl[i].id) {
2265                                ctrl.value = s->_qctrl[i].default_value;
2266                                goto exit;
2267                        }
2268                return -EINVAL;
2269        } else
2270                err = s->get_ctrl(cam, &ctrl);
2271
2272exit:
2273        if (copy_to_user(arg, &ctrl, sizeof(ctrl)))
2274                return -EFAULT;
2275
2276        PDBGG("VIDIOC_G_CTRL: id %lu, value %lu",
2277              (unsigned long)ctrl.id, (unsigned long)ctrl.value);
2278
2279        return err;
2280}
2281
2282
2283static int
2284sn9c102_vidioc_s_ctrl(struct sn9c102_device* cam, void __user * arg)
2285{
2286        struct sn9c102_sensor* s = &cam->sensor;
2287        struct v4l2_control ctrl;
2288        u8 i;
2289        int err = 0;
2290
2291        if (!s->set_ctrl)
2292                return -EINVAL;
2293
2294        if (copy_from_user(&ctrl, arg, sizeof(ctrl)))
2295                return -EFAULT;
2296
2297        for (i = 0; i < ARRAY_SIZE(s->qctrl); i++) {
2298                if (ctrl.id == s->qctrl[i].id) {
2299                        if (s->qctrl[i].flags & V4L2_CTRL_FLAG_DISABLED)
2300                                return -EINVAL;
2301                        if (ctrl.value < s->qctrl[i].minimum ||
2302                            ctrl.value > s->qctrl[i].maximum)
2303                                return -ERANGE;
2304                        ctrl.value -= ctrl.value % s->qctrl[i].step;
2305                        break;
2306                }
2307        }
2308        if (i == ARRAY_SIZE(s->qctrl))
2309                return -EINVAL;
2310        if ((err = s->set_ctrl(cam, &ctrl)))
2311                return err;
2312
2313        s->_qctrl[i].default_value = ctrl.value;
2314
2315        PDBGG("VIDIOC_S_CTRL: id %lu, value %lu",
2316              (unsigned long)ctrl.id, (unsigned long)ctrl.value);
2317
2318        return 0;
2319}
2320
2321
2322static int
2323sn9c102_vidioc_cropcap(struct sn9c102_device* cam, void __user * arg)
2324{
2325        struct v4l2_cropcap* cc = &(cam->sensor.cropcap);
2326
2327        cc->type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
2328        cc->pixelaspect.numerator = 1;
2329        cc->pixelaspect.denominator = 1;
2330
2331        if (copy_to_user(arg, cc, sizeof(*cc)))
2332                return -EFAULT;
2333
2334        return 0;
2335}
2336
2337
2338static int
2339sn9c102_vidioc_g_crop(struct sn9c102_device* cam, void __user * arg)
2340{
2341        struct sn9c102_sensor* s = &cam->sensor;
2342        struct v4l2_crop crop = {
2343                .type = V4L2_BUF_TYPE_VIDEO_CAPTURE,
2344        };
2345
2346        memcpy(&(crop.c), &(s->_rect), sizeof(struct v4l2_rect));
2347
2348        if (copy_to_user(arg, &crop, sizeof(crop)))
2349                return -EFAULT;
2350
2351        return 0;
2352}
2353
2354
2355static int
2356sn9c102_vidioc_s_crop(struct sn9c102_device* cam, void __user * arg)
2357{
2358        struct sn9c102_sensor* s = &cam->sensor;
2359        struct v4l2_crop crop;
2360        struct v4l2_rect* rect;
2361        struct v4l2_rect* bounds = &(s->cropcap.bounds);
2362        struct v4l2_pix_format* pix_format = &(s->pix_format);
2363        u8 scale;
2364        const enum sn9c102_stream_state stream = cam->stream;
2365        const u32 nbuffers = cam->nbuffers;
2366        u32 i;
2367        int err = 0;
2368
2369        if (copy_from_user(&crop, arg, sizeof(crop)))
2370                return -EFAULT;
2371
2372        rect = &(crop.c);
2373
2374        if (crop.type != V4L2_BUF_TYPE_VIDEO_CAPTURE)
2375                return -EINVAL;
2376
2377        if (cam->module_param.force_munmap)
2378                for (i = 0; i < cam->nbuffers; i++)
2379                        if (cam->frame[i].vma_use_count) {
2380                                DBG(3, "VIDIOC_S_CROP failed. "
2381                                       "Unmap the buffers first.");
2382                                return -EBUSY;
2383                        }
2384
2385        /* Preserve R,G or B origin */
2386        rect->left = (s->_rect.left & 1L) ? rect->left | 1L : rect->left & ~1L;
2387        rect->top = (s->_rect.top & 1L) ? rect->top | 1L : rect->top & ~1L;
2388
2389        if (rect->width < 16)
2390                rect->width = 16;
2391        if (rect->height < 16)
2392                rect->height = 16;
2393        if (rect->width > bounds->width)
2394                rect->width = bounds->width;
2395        if (rect->height > bounds->height)
2396                rect->height = bounds->height;
2397        if (rect->left < bounds->left)
2398                rect->left = bounds->left;
2399        if (rect->top < bounds->top)
2400                rect->top = bounds->top;
2401        if (rect->left + rect->width > bounds->left + bounds->width)
2402                rect->left = bounds->left+bounds->width - rect->width;
2403        if (rect->top + rect->height > bounds->top + bounds->height)
2404                rect->top = bounds->top+bounds->height - rect->height;
2405
2406        rect->width &= ~15L;
2407        rect->height &= ~15L;
2408
2409        if (SN9C102_PRESERVE_IMGSCALE) {
2410                /* Calculate the actual scaling factor */
2411                u32 a, b;
2412                a = rect->width * rect->height;
2413                b = pix_format->width * pix_format->height;
2414                scale = b ? (u8)((a / b) < 4 ? 1 : ((a / b) < 16 ? 2 : 4)) : 1;
2415        } else
2416                scale = 1;
2417
2418        if (cam->stream == STREAM_ON)
2419                if ((err = sn9c102_stream_interrupt(cam)))
2420                        return err;
2421
2422        if (copy_to_user(arg, &crop, sizeof(crop))) {
2423                cam->stream = stream;
2424                return -EFAULT;
2425        }
2426
2427        if (cam->module_param.force_munmap || cam->io == IO_READ)
2428                sn9c102_release_buffers(cam);
2429
2430        err = sn9c102_set_crop(cam, rect);
2431        if (s->set_crop)
2432                err += s->set_crop(cam, rect);
2433        err += sn9c102_set_scale(cam, scale);
2434
2435        if (err) { /* atomic, no rollback in ioctl() */
2436                cam->state |= DEV_MISCONFIGURED;
2437                DBG(1, "VIDIOC_S_CROP failed because of hardware problems. To "
2438                       "use the camera, close and open %s again.",
2439                    video_device_node_name(cam->v4ldev));
2440                return -EIO;
2441        }
2442
2443        s->pix_format.width = rect->width/scale;
2444        s->pix_format.height = rect->height/scale;
2445        memcpy(&(s->_rect), rect, sizeof(*rect));
2446
2447        if ((cam->module_param.force_munmap || cam->io == IO_READ) &&
2448            nbuffers != sn9c102_request_buffers(cam, nbuffers, cam->io)) {
2449                cam->state |= DEV_MISCONFIGURED;
2450                DBG(1, "VIDIOC_S_CROP failed because of not enough memory. To "
2451                       "use the camera, close and open %s again.",
2452                    video_device_node_name(cam->v4ldev));
2453                return -ENOMEM;
2454        }
2455
2456        if (cam->io == IO_READ)
2457                sn9c102_empty_framequeues(cam);
2458        else if (cam->module_param.force_munmap)
2459                sn9c102_requeue_outqueue(cam);
2460
2461        cam->stream = stream;
2462
2463        return 0;
2464}
2465
2466
2467static int
2468sn9c102_vidioc_enum_framesizes(struct sn9c102_device* cam, void __user * arg)
2469{
2470        struct v4l2_frmsizeenum frmsize;
2471
2472        if (copy_from_user(&frmsize, arg, sizeof(frmsize)))
2473                return -EFAULT;
2474
2475        if (frmsize.index != 0)
2476                return -EINVAL;
2477
2478        switch (cam->bridge) {
2479        case BRIDGE_SN9C101:
2480        case BRIDGE_SN9C102:
2481        case BRIDGE_SN9C103:
2482                if (frmsize.pixel_format != V4L2_PIX_FMT_SN9C10X &&
2483                    frmsize.pixel_format != V4L2_PIX_FMT_SBGGR8)
2484                        return -EINVAL;
2485                break;
2486        case BRIDGE_SN9C105:
2487        case BRIDGE_SN9C120:
2488                if (frmsize.pixel_format != V4L2_PIX_FMT_JPEG &&
2489                    frmsize.pixel_format != V4L2_PIX_FMT_SBGGR8)
2490                        return -EINVAL;
2491                break;
2492        }
2493
2494        frmsize.type = V4L2_FRMSIZE_TYPE_STEPWISE;
2495        frmsize.stepwise.min_width = frmsize.stepwise.step_width = 16;
2496        frmsize.stepwise.min_height = frmsize.stepwise.step_height = 16;
2497        frmsize.stepwise.max_width = cam->sensor.cropcap.bounds.width;
2498        frmsize.stepwise.max_height = cam->sensor.cropcap.bounds.height;
2499        memset(&frmsize.reserved, 0, sizeof(frmsize.reserved));
2500
2501        if (copy_to_user(arg, &frmsize, sizeof(frmsize)))
2502                return -EFAULT;
2503
2504        return 0;
2505}
2506
2507
2508static int
2509sn9c102_vidioc_enum_fmt(struct sn9c102_device* cam, void __user * arg)
2510{
2511        struct v4l2_fmtdesc fmtd;
2512
2513        if (copy_from_user(&fmtd, arg, sizeof(fmtd)))
2514                return -EFAULT;
2515
2516        if (fmtd.type != V4L2_BUF_TYPE_VIDEO_CAPTURE)
2517                return -EINVAL;
2518
2519        if (fmtd.index == 0) {
2520                strcpy(fmtd.description, "bayer rgb");
2521                fmtd.pixelformat = V4L2_PIX_FMT_SBGGR8;
2522        } else if (fmtd.index == 1) {
2523                switch (cam->bridge) {
2524                case BRIDGE_SN9C101:
2525                case BRIDGE_SN9C102:
2526                case BRIDGE_SN9C103:
2527                        strcpy(fmtd.description, "compressed");
2528                        fmtd.pixelformat = V4L2_PIX_FMT_SN9C10X;
2529                        break;
2530                case BRIDGE_SN9C105:
2531                case BRIDGE_SN9C120:
2532                        strcpy(fmtd.description, "JPEG");
2533                        fmtd.pixelformat = V4L2_PIX_FMT_JPEG;
2534                        break;
2535                }
2536                fmtd.flags = V4L2_FMT_FLAG_COMPRESSED;
2537        } else
2538                return -EINVAL;
2539
2540        fmtd.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
2541        memset(&fmtd.reserved, 0, sizeof(fmtd.reserved));
2542
2543        if (copy_to_user(arg, &fmtd, sizeof(fmtd)))
2544                return -EFAULT;
2545
2546        return 0;
2547}
2548
2549
2550static int
2551sn9c102_vidioc_g_fmt(struct sn9c102_device* cam, void __user * arg)
2552{
2553        struct v4l2_format format;
2554        struct v4l2_pix_format* pfmt = &(cam->sensor.pix_format);
2555
2556        if (copy_from_user(&format, arg, sizeof(format)))
2557                return -EFAULT;
2558
2559        if (format.type != V4L2_BUF_TYPE_VIDEO_CAPTURE)
2560                return -EINVAL;
2561
2562        pfmt->colorspace = (pfmt->pixelformat == V4L2_PIX_FMT_JPEG) ?
2563                           V4L2_COLORSPACE_JPEG : V4L2_COLORSPACE_SRGB;
2564        pfmt->bytesperline = (pfmt->pixelformat == V4L2_PIX_FMT_SN9C10X ||
2565                              pfmt->pixelformat == V4L2_PIX_FMT_JPEG)
2566                             ? 0 : (pfmt->width * pfmt->priv) / 8;
2567        pfmt->sizeimage = pfmt->height * ((pfmt->width*pfmt->priv)/8);
2568        pfmt->field = V4L2_FIELD_NONE;
2569        memcpy(&(format.fmt.pix), pfmt, sizeof(*pfmt));
2570
2571        if (copy_to_user(arg, &format, sizeof(format)))
2572                return -EFAULT;
2573
2574        return 0;
2575}
2576
2577
2578static int
2579sn9c102_vidioc_try_s_fmt(struct sn9c102_device* cam, unsigned int cmd,
2580                         void __user * arg)
2581{
2582        struct sn9c102_sensor* s = &cam->sensor;
2583        struct v4l2_format format;
2584        struct v4l2_pix_format* pix;
2585        struct v4l2_pix_format* pfmt = &(s->pix_format);
2586        struct v4l2_rect* bounds = &(s->cropcap.bounds);
2587        struct v4l2_rect rect;
2588        u8 scale;
2589        const enum sn9c102_stream_state stream = cam->stream;
2590        const u32 nbuffers = cam->nbuffers;
2591        u32 i;
2592        int err = 0;
2593
2594        if (copy_from_user(&format, arg, sizeof(format)))
2595                return -EFAULT;
2596
2597        pix = &(format.fmt.pix);
2598
2599        if (format.type != V4L2_BUF_TYPE_VIDEO_CAPTURE)
2600                return -EINVAL;
2601
2602        memcpy(&rect, &(s->_rect), sizeof(rect));
2603
2604        { /* calculate the actual scaling factor */
2605                u32 a, b;
2606                a = rect.width * rect.height;
2607                b = pix->width * pix->height;
2608                scale = b ? (u8)((a / b) < 4 ? 1 : ((a / b) < 16 ? 2 : 4)) : 1;
2609        }
2610
2611        rect.width = scale * pix->width;
2612        rect.height = scale * pix->height;
2613
2614        if (rect.width < 16)
2615                rect.width = 16;
2616        if (rect.height < 16)
2617                rect.height = 16;
2618        if (rect.width > bounds->left + bounds->width - rect.left)
2619                rect.width = bounds->left + bounds->width - rect.left;
2620        if (rect.height > bounds->top + bounds->height - rect.top)
2621                rect.height = bounds->top + bounds->height - rect.top;
2622
2623        rect.width &= ~15L;
2624        rect.height &= ~15L;
2625
2626        { /* adjust the scaling factor */
2627                u32 a, b;
2628                a = rect.width * rect.height;
2629                b = pix->width * pix->height;
2630                scale = b ? (u8)((a / b) < 4 ? 1 : ((a / b) < 16 ? 2 : 4)) : 1;
2631        }
2632
2633        pix->width = rect.width / scale;
2634        pix->height = rect.height / scale;
2635
2636        switch (cam->bridge) {
2637        case BRIDGE_SN9C101:
2638        case BRIDGE_SN9C102:
2639        case BRIDGE_SN9C103:
2640                if (pix->pixelformat != V4L2_PIX_FMT_SN9C10X &&
2641                    pix->pixelformat != V4L2_PIX_FMT_SBGGR8)
2642                        pix->pixelformat = pfmt->pixelformat;
2643                break;
2644        case BRIDGE_SN9C105:
2645        case BRIDGE_SN9C120:
2646                if (pix->pixelformat != V4L2_PIX_FMT_JPEG &&
2647                    pix->pixelformat != V4L2_PIX_FMT_SBGGR8)
2648                        pix->pixelformat = pfmt->pixelformat;
2649                break;
2650        }
2651        pix->priv = pfmt->priv; /* bpp */
2652        pix->colorspace = (pix->pixelformat == V4L2_PIX_FMT_JPEG) ?
2653                          V4L2_COLORSPACE_JPEG : V4L2_COLORSPACE_SRGB;
2654        pix->bytesperline = (pix->pixelformat == V4L2_PIX_FMT_SN9C10X ||
2655                             pix->pixelformat == V4L2_PIX_FMT_JPEG)
2656                            ? 0 : (pix->width * pix->priv) / 8;
2657        pix->sizeimage = pix->height * ((pix->width * pix->priv) / 8);
2658        pix->field = V4L2_FIELD_NONE;
2659
2660        if (cmd == VIDIOC_TRY_FMT) {
2661                if (copy_to_user(arg, &format, sizeof(format)))
2662                        return -EFAULT;
2663                return 0;
2664        }
2665
2666        if (cam->module_param.force_munmap)
2667                for (i = 0; i < cam->nbuffers; i++)
2668                        if (cam->frame[i].vma_use_count) {
2669                                DBG(3, "VIDIOC_S_FMT failed. Unmap the "
2670                                       "buffers first.");
2671                                return -EBUSY;
2672                        }
2673
2674        if (cam->stream == STREAM_ON)
2675                if ((err = sn9c102_stream_interrupt(cam)))
2676                        return err;
2677
2678        if (copy_to_user(arg, &format, sizeof(format))) {
2679                cam->stream = stream;
2680                return -EFAULT;
2681        }
2682
2683        if (cam->module_param.force_munmap  || cam->io == IO_READ)
2684                sn9c102_release_buffers(cam);
2685
2686        err += sn9c102_set_pix_format(cam, pix);
2687        err += sn9c102_set_crop(cam, &rect);
2688        if (s->set_pix_format)
2689                err += s->set_pix_format(cam, pix);
2690        if (s->set_crop)
2691                err += s->set_crop(cam, &rect);
2692        err += sn9c102_set_scale(cam, scale);
2693
2694        if (err) { /* atomic, no rollback in ioctl() */
2695                cam->state |= DEV_MISCONFIGURED;
2696                DBG(1, "VIDIOC_S_FMT failed because of hardware problems. To "
2697                       "use the camera, close and open %s again.",
2698                    video_device_node_name(cam->v4ldev));
2699                return -EIO;
2700        }
2701
2702        memcpy(pfmt, pix, sizeof(*pix));
2703        memcpy(&(s->_rect), &rect, sizeof(rect));
2704
2705        if ((cam->module_param.force_munmap  || cam->io == IO_READ) &&
2706            nbuffers != sn9c102_request_buffers(cam, nbuffers, cam->io)) {
2707                cam->state |= DEV_MISCONFIGURED;
2708                DBG(1, "VIDIOC_S_FMT failed because of not enough memory. To "
2709                       "use the camera, close and open %s again.",
2710                    video_device_node_name(cam->v4ldev));
2711                return -ENOMEM;
2712        }
2713
2714        if (cam->io == IO_READ)
2715                sn9c102_empty_framequeues(cam);
2716        else if (cam->module_param.force_munmap)
2717                sn9c102_requeue_outqueue(cam);
2718
2719        cam->stream = stream;
2720
2721        return 0;
2722}
2723
2724
2725static int
2726sn9c102_vidioc_g_jpegcomp(struct sn9c102_device* cam, void __user * arg)
2727{
2728        if (copy_to_user(arg, &cam->compression, sizeof(cam->compression)))
2729                return -EFAULT;
2730
2731        return 0;
2732}
2733
2734
2735static int
2736sn9c102_vidioc_s_jpegcomp(struct sn9c102_device* cam, void __user * arg)
2737{
2738        struct v4l2_jpegcompression jc;
2739        const enum sn9c102_stream_state stream = cam->stream;
2740        int err = 0;
2741
2742        if (copy_from_user(&jc, arg, sizeof(jc)))
2743                return -EFAULT;
2744
2745        if (jc.quality != 0 && jc.quality != 1)
2746                return -EINVAL;
2747
2748        if (cam->stream == STREAM_ON)
2749                if ((err = sn9c102_stream_interrupt(cam)))
2750                        return err;
2751
2752        err += sn9c102_set_compression(cam, &jc);
2753        if (err) { /* atomic, no rollback in ioctl() */
2754                cam->state |= DEV_MISCONFIGURED;
2755                DBG(1, "VIDIOC_S_JPEGCOMP failed because of hardware problems. "
2756                       "To use the camera, close and open %s again.",
2757                    video_device_node_name(cam->v4ldev));
2758                return -EIO;
2759        }
2760
2761        cam->compression.quality = jc.quality;
2762
2763        cam->stream = stream;
2764
2765        return 0;
2766}
2767
2768
2769static int
2770sn9c102_vidioc_reqbufs(struct sn9c102_device* cam, void __user * arg)
2771{
2772        struct v4l2_requestbuffers rb;
2773        u32 i;
2774        int err;
2775
2776        if (copy_from_user(&rb, arg, sizeof(rb)))
2777                return -EFAULT;
2778
2779        if (rb.type != V4L2_BUF_TYPE_VIDEO_CAPTURE ||
2780            rb.memory != V4L2_MEMORY_MMAP)
2781                return -EINVAL;
2782
2783        if (cam->io == IO_READ) {
2784                DBG(3, "Close and open the device again to choose the mmap "
2785                       "I/O method");
2786                return -EBUSY;
2787        }
2788
2789        for (i = 0; i < cam->nbuffers; i++)
2790                if (cam->frame[i].vma_use_count) {
2791                        DBG(3, "VIDIOC_REQBUFS failed. Previous buffers are "
2792                               "still mapped.");
2793                        return -EBUSY;
2794                }
2795
2796        if (cam->stream == STREAM_ON)
2797                if ((err = sn9c102_stream_interrupt(cam)))
2798                        return err;
2799
2800        sn9c102_empty_framequeues(cam);
2801
2802        sn9c102_release_buffers(cam);
2803        if (rb.count)
2804                rb.count = sn9c102_request_buffers(cam, rb.count, IO_MMAP);
2805
2806        if (copy_to_user(arg, &rb, sizeof(rb))) {
2807                sn9c102_release_buffers(cam);
2808                cam->io = IO_NONE;
2809                return -EFAULT;
2810        }
2811
2812        cam->io = rb.count ? IO_MMAP : IO_NONE;
2813
2814        return 0;
2815}
2816
2817
2818static int
2819sn9c102_vidioc_querybuf(struct sn9c102_device* cam, void __user * arg)
2820{
2821        struct v4l2_buffer b;
2822
2823        if (copy_from_user(&b, arg, sizeof(b)))
2824                return -EFAULT;
2825
2826        if (b.type != V4L2_BUF_TYPE_VIDEO_CAPTURE ||
2827            b.index >= cam->nbuffers || cam->io != IO_MMAP)
2828                return -EINVAL;
2829
2830        b = cam->frame[b.index].buf;
2831
2832        if (cam->frame[b.index].vma_use_count)
2833                b.flags |= V4L2_BUF_FLAG_MAPPED;
2834
2835        if (cam->frame[b.index].state == F_DONE)
2836                b.flags |= V4L2_BUF_FLAG_DONE;
2837        else if (cam->frame[b.index].state != F_UNUSED)
2838                b.flags |= V4L2_BUF_FLAG_QUEUED;
2839
2840        if (copy_to_user(arg, &b, sizeof(b)))
2841                return -EFAULT;
2842
2843        return 0;
2844}
2845
2846
2847static int
2848sn9c102_vidioc_qbuf(struct sn9c102_device* cam, void __user * arg)
2849{
2850        struct v4l2_buffer b;
2851        unsigned long lock_flags;
2852
2853        if (copy_from_user(&b, arg, sizeof(b)))
2854                return -EFAULT;
2855
2856        if (b.type != V4L2_BUF_TYPE_VIDEO_CAPTURE ||
2857            b.index >= cam->nbuffers || cam->io != IO_MMAP)
2858                return -EINVAL;
2859
2860        if (cam->frame[b.index].state != F_UNUSED)
2861                return -EINVAL;
2862
2863        cam->frame[b.index].state = F_QUEUED;
2864
2865        spin_lock_irqsave(&cam->queue_lock, lock_flags);
2866        list_add_tail(&cam->frame[b.index].frame, &cam->inqueue);
2867        spin_unlock_irqrestore(&cam->queue_lock, lock_flags);
2868
2869        PDBGG("Frame #%lu queued", (unsigned long)b.index);
2870
2871        return 0;
2872}
2873
2874
2875static int
2876sn9c102_vidioc_dqbuf(struct sn9c102_device* cam, struct file* filp,
2877                     void __user * arg)
2878{
2879        struct v4l2_buffer b;
2880        struct sn9c102_frame_t *f;
2881        unsigned long lock_flags;
2882        long timeout;
2883        int err = 0;
2884
2885        if (copy_from_user(&b, arg, sizeof(b)))
2886                return -EFAULT;
2887
2888        if (b.type != V4L2_BUF_TYPE_VIDEO_CAPTURE || cam->io != IO_MMAP)
2889                return -EINVAL;
2890
2891        if (list_empty(&cam->outqueue)) {
2892                if (cam->stream == STREAM_OFF)
2893                        return -EINVAL;
2894                if (filp->f_flags & O_NONBLOCK)
2895                        return -EAGAIN;
2896                if (!cam->module_param.frame_timeout) {
2897                        err = wait_event_interruptible
2898                              ( cam->wait_frame,
2899                                (!list_empty(&cam->outqueue)) ||
2900                                (cam->state & DEV_DISCONNECTED) ||
2901                                (cam->state & DEV_MISCONFIGURED) );
2902                        if (err)
2903                                return err;
2904                } else {
2905                        timeout = wait_event_interruptible_timeout
2906                                  ( cam->wait_frame,
2907                                    (!list_empty(&cam->outqueue)) ||
2908                                    (cam->state & DEV_DISCONNECTED) ||
2909                                    (cam->state & DEV_MISCONFIGURED),
2910                                    cam->module_param.frame_timeout *
2911                                    1000 * msecs_to_jiffies(1) );
2912                        if (timeout < 0)
2913                                return timeout;
2914                        else if (timeout == 0 &&
2915                                 !(cam->state & DEV_DISCONNECTED)) {
2916                                DBG(1, "Video frame timeout elapsed");
2917                                return -EIO;
2918                        }
2919                }
2920                if (cam->state & DEV_DISCONNECTED)
2921                        return -ENODEV;
2922                if (cam->state & DEV_MISCONFIGURED)
2923                        return -EIO;
2924        }
2925
2926        spin_lock_irqsave(&cam->queue_lock, lock_flags);
2927        f = list_entry(cam->outqueue.next, struct sn9c102_frame_t, frame);
2928        list_del(cam->outqueue.next);
2929        spin_unlock_irqrestore(&cam->queue_lock, lock_flags);
2930
2931        f->state = F_UNUSED;
2932
2933        b = f->buf;
2934        if (f->vma_use_count)
2935                b.flags |= V4L2_BUF_FLAG_MAPPED;
2936
2937        if (copy_to_user(arg, &b, sizeof(b)))
2938                return -EFAULT;
2939
2940        PDBGG("Frame #%lu dequeued", (unsigned long)f->buf.index);
2941
2942        return 0;
2943}
2944
2945
2946static int
2947sn9c102_vidioc_streamon(struct sn9c102_device* cam, void __user * arg)
2948{
2949        int type;
2950
2951        if (copy_from_user(&type, arg, sizeof(type)))
2952                return -EFAULT;
2953
2954        if (type != V4L2_BUF_TYPE_VIDEO_CAPTURE || cam->io != IO_MMAP)
2955                return -EINVAL;
2956
2957        cam->stream = STREAM_ON;
2958
2959        DBG(3, "Stream on");
2960
2961        return 0;
2962}
2963
2964
2965static int
2966sn9c102_vidioc_streamoff(struct sn9c102_device* cam, void __user * arg)
2967{
2968        int type, err;
2969
2970        if (copy_from_user(&type, arg, sizeof(type)))
2971                return -EFAULT;
2972
2973        if (type != V4L2_BUF_TYPE_VIDEO_CAPTURE || cam->io != IO_MMAP)
2974                return -EINVAL;
2975
2976        if (cam->stream == STREAM_ON)
2977                if ((err = sn9c102_stream_interrupt(cam)))
2978                        return err;
2979
2980        sn9c102_empty_framequeues(cam);
2981
2982        DBG(3, "Stream off");
2983
2984        return 0;
2985}
2986
2987
2988static int
2989sn9c102_vidioc_g_parm(struct sn9c102_device* cam, void __user * arg)
2990{
2991        struct v4l2_streamparm sp;
2992
2993        if (copy_from_user(&sp, arg, sizeof(sp)))
2994                return -EFAULT;
2995
2996        if (sp.type != V4L2_BUF_TYPE_VIDEO_CAPTURE)
2997                return -EINVAL;
2998
2999        sp.parm.capture.extendedmode = 0;
3000        sp.parm.capture.readbuffers = cam->nreadbuffers;
3001
3002        if (copy_to_user(arg, &sp, sizeof(sp)))
3003                return -EFAULT;
3004
3005        return 0;
3006}
3007
3008
3009static int
3010sn9c102_vidioc_s_parm(struct sn9c102_device* cam, void __user * arg)
3011{
3012        struct v4l2_streamparm sp;
3013
3014        if (copy_from_user(&sp, arg, sizeof(sp)))
3015                return -EFAULT;
3016
3017        if (sp.type != V4L2_BUF_TYPE_VIDEO_CAPTURE)
3018                return -EINVAL;
3019
3020        sp.parm.capture.extendedmode = 0;
3021
3022        if (sp.parm.capture.readbuffers == 0)
3023                sp.parm.capture.readbuffers = cam->nreadbuffers;
3024
3025        if (sp.parm.capture.readbuffers > SN9C102_MAX_FRAMES)
3026                sp.parm.capture.readbuffers = SN9C102_MAX_FRAMES;
3027
3028        if (copy_to_user(arg, &sp, sizeof(sp)))
3029                return -EFAULT;
3030
3031        cam->nreadbuffers = sp.parm.capture.readbuffers;
3032
3033        return 0;
3034}
3035
3036
3037static int
3038sn9c102_vidioc_enumaudio(struct sn9c102_device* cam, void __user * arg)
3039{
3040        struct v4l2_audio audio;
3041
3042        if (cam->bridge == BRIDGE_SN9C101 || cam->bridge == BRIDGE_SN9C102)
3043                return -EINVAL;
3044
3045        if (copy_from_user(&audio, arg, sizeof(audio)))
3046                return -EFAULT;
3047
3048        if (audio.index != 0)
3049                return -EINVAL;
3050
3051        strcpy(audio.name, "Microphone");
3052        audio.capability = 0;
3053        audio.mode = 0;
3054
3055        if (copy_to_user(arg, &audio, sizeof(audio)))
3056                return -EFAULT;
3057
3058        return 0;
3059}
3060
3061
3062static int
3063sn9c102_vidioc_g_audio(struct sn9c102_device* cam, void __user * arg)
3064{
3065        struct v4l2_audio audio;
3066
3067        if (cam->bridge == BRIDGE_SN9C101 || cam->bridge == BRIDGE_SN9C102)
3068                return -EINVAL;
3069
3070        if (copy_from_user(&audio, arg, sizeof(audio)))
3071                return -EFAULT;
3072
3073        memset(&audio, 0, sizeof(audio));
3074        strcpy(audio.name, "Microphone");
3075
3076        if (copy_to_user(arg, &audio, sizeof(audio)))
3077                return -EFAULT;
3078
3079        return 0;
3080}
3081
3082
3083static int
3084sn9c102_vidioc_s_audio(struct sn9c102_device* cam, void __user * arg)
3085{
3086        struct v4l2_audio audio;
3087
3088        if (cam->bridge == BRIDGE_SN9C101 || cam->bridge == BRIDGE_SN9C102)
3089                return -EINVAL;
3090
3091        if (copy_from_user(&audio, arg, sizeof(audio)))
3092                return -EFAULT;
3093
3094        if (audio.index != 0)
3095                return -EINVAL;
3096
3097        return 0;
3098}
3099
3100
3101static long sn9c102_ioctl_v4l2(struct file *filp,
3102                              unsigned int cmd, void __user *arg)
3103{
3104        struct sn9c102_device *cam = video_drvdata(filp);
3105
3106        switch (cmd) {
3107
3108        case VIDIOC_QUERYCAP:
3109                return sn9c102_vidioc_querycap(cam, arg);
3110
3111        case VIDIOC_ENUMINPUT:
3112                return sn9c102_vidioc_enuminput(cam, arg);
3113
3114        case VIDIOC_G_INPUT:
3115                return sn9c102_vidioc_g_input(cam, arg);
3116
3117        case VIDIOC_S_INPUT:
3118                return sn9c102_vidioc_s_input(cam, arg);
3119
3120        case VIDIOC_QUERYCTRL:
3121                return sn9c102_vidioc_query_ctrl(cam, arg);
3122
3123        case VIDIOC_G_CTRL:
3124                return sn9c102_vidioc_g_ctrl(cam, arg);
3125
3126        case VIDIOC_S_CTRL:
3127                return sn9c102_vidioc_s_ctrl(cam, arg);
3128
3129        case VIDIOC_CROPCAP:
3130                return sn9c102_vidioc_cropcap(cam, arg);
3131
3132        case VIDIOC_G_CROP:
3133                return sn9c102_vidioc_g_crop(cam, arg);
3134
3135        case VIDIOC_S_CROP:
3136                return sn9c102_vidioc_s_crop(cam, arg);
3137
3138        case VIDIOC_ENUM_FRAMESIZES:
3139                return sn9c102_vidioc_enum_framesizes(cam, arg);
3140
3141        case VIDIOC_ENUM_FMT:
3142                return sn9c102_vidioc_enum_fmt(cam, arg);
3143
3144        case VIDIOC_G_FMT:
3145                return sn9c102_vidioc_g_fmt(cam, arg);
3146
3147        case VIDIOC_TRY_FMT:
3148        case VIDIOC_S_FMT:
3149                return sn9c102_vidioc_try_s_fmt(cam, cmd, arg);
3150
3151        case VIDIOC_G_JPEGCOMP:
3152                return sn9c102_vidioc_g_jpegcomp(cam, arg);
3153
3154        case VIDIOC_S_JPEGCOMP:
3155                return sn9c102_vidioc_s_jpegcomp(cam, arg);
3156
3157        case VIDIOC_REQBUFS:
3158                return sn9c102_vidioc_reqbufs(cam, arg);
3159
3160        case VIDIOC_QUERYBUF:
3161                return sn9c102_vidioc_querybuf(cam, arg);
3162
3163        case VIDIOC_QBUF:
3164                return sn9c102_vidioc_qbuf(cam, arg);
3165
3166        case VIDIOC_DQBUF:
3167                return sn9c102_vidioc_dqbuf(cam, filp, arg);
3168
3169        case VIDIOC_STREAMON:
3170                return sn9c102_vidioc_streamon(cam, arg);
3171
3172        case VIDIOC_STREAMOFF:
3173                return sn9c102_vidioc_streamoff(cam, arg);
3174
3175        case VIDIOC_G_PARM:
3176                return sn9c102_vidioc_g_parm(cam, arg);
3177
3178        case VIDIOC_S_PARM:
3179                return sn9c102_vidioc_s_parm(cam, arg);
3180
3181        case VIDIOC_ENUMAUDIO:
3182                return sn9c102_vidioc_enumaudio(cam, arg);
3183
3184        case VIDIOC_G_AUDIO:
3185                return sn9c102_vidioc_g_audio(cam, arg);
3186
3187        case VIDIOC_S_AUDIO:
3188                return sn9c102_vidioc_s_audio(cam, arg);
3189
3190        default:
3191                return -ENOTTY;
3192
3193        }
3194}
3195
3196
3197static long sn9c102_ioctl(struct file *filp,
3198                         unsigned int cmd, unsigned long arg)
3199{
3200        struct sn9c102_device *cam = video_drvdata(filp);
3201        int err = 0;
3202
3203        if (mutex_lock_interruptible(&cam->fileop_mutex))
3204                return -ERESTARTSYS;
3205
3206        if (cam->state & DEV_DISCONNECTED) {
3207                DBG(1, "Device not present");
3208                mutex_unlock(&cam->fileop_mutex);
3209                return -ENODEV;
3210        }
3211
3212        if (cam->state & DEV_MISCONFIGURED) {
3213                DBG(1, "The camera is misconfigured. Close and open it "
3214                       "again.");
3215                mutex_unlock(&cam->fileop_mutex);
3216                return -EIO;
3217        }
3218
3219        V4LDBG(3, "sn9c102", cmd);
3220
3221        err = sn9c102_ioctl_v4l2(filp, cmd, (void __user *)arg);
3222
3223        mutex_unlock(&cam->fileop_mutex);
3224
3225        return err;
3226}
3227
3228/*****************************************************************************/
3229
3230static const struct v4l2_file_operations sn9c102_fops = {
3231        .owner = THIS_MODULE,
3232        .open = sn9c102_open,
3233        .release = sn9c102_release,
3234        .unlocked_ioctl = sn9c102_ioctl,
3235        .read = sn9c102_read,
3236        .poll = sn9c102_poll,
3237        .mmap = sn9c102_mmap,
3238};
3239
3240/*****************************************************************************/
3241
3242/* It exists a single interface only. We do not need to validate anything. */
3243static int
3244sn9c102_usb_probe(struct usb_interface* intf, const struct usb_device_id* id)
3245{
3246        struct usb_device *udev = interface_to_usbdev(intf);
3247        struct sn9c102_device* cam;
3248        static unsigned int dev_nr;
3249        unsigned int i;
3250        int err = 0, r;
3251
3252        if (!(cam = kzalloc(sizeof(struct sn9c102_device), GFP_KERNEL)))
3253                return -ENOMEM;
3254
3255        cam->usbdev = udev;
3256
3257        if (!(cam->control_buffer = kzalloc(8, GFP_KERNEL))) {
3258                DBG(1, "kzalloc() failed");
3259                err = -ENOMEM;
3260                goto fail;
3261        }
3262
3263        if (!(cam->v4ldev = video_device_alloc())) {
3264                DBG(1, "video_device_alloc() failed");
3265                err = -ENOMEM;
3266                goto fail;
3267        }
3268
3269        r = sn9c102_read_reg(cam, 0x00);
3270        if (r < 0 || (r != 0x10 && r != 0x11 && r != 0x12)) {
3271                DBG(1, "Sorry, this is not a SN9C1xx-based camera "
3272                       "(vid:pid 0x%04X:0x%04X)", id->idVendor, id->idProduct);
3273                err = -ENODEV;
3274                goto fail;
3275        }
3276
3277        cam->bridge = id->driver_info;
3278        switch (cam->bridge) {
3279        case BRIDGE_SN9C101:
3280        case BRIDGE_SN9C102:
3281                DBG(2, "SN9C10[12] PC Camera Controller detected "
3282                       "(vid:pid 0x%04X:0x%04X)", id->idVendor, id->idProduct);
3283                break;
3284        case BRIDGE_SN9C103:
3285                DBG(2, "SN9C103 PC Camera Controller detected "
3286                       "(vid:pid 0x%04X:0x%04X)", id->idVendor, id->idProduct);
3287                break;
3288        case BRIDGE_SN9C105:
3289                DBG(2, "SN9C105 PC Camera Controller detected "
3290                       "(vid:pid 0x%04X:0x%04X)", id->idVendor, id->idProduct);
3291                break;
3292        case BRIDGE_SN9C120:
3293                DBG(2, "SN9C120 PC Camera Controller detected "
3294                       "(vid:pid 0x%04X:0x%04X)", id->idVendor, id->idProduct);
3295                break;
3296        }
3297
3298        for  (i = 0; i < ARRAY_SIZE(sn9c102_sensor_table); i++) {
3299                err = sn9c102_sensor_table[i](cam);
3300                if (!err)
3301                        break;
3302        }
3303
3304        if (!err) {
3305                DBG(2, "%s image sensor detected", cam->sensor.name);
3306                DBG(3, "Support for %s maintained by %s",
3307                    cam->sensor.name, cam->sensor.maintainer);
3308        } else {
3309                DBG(1, "No supported image sensor detected for this bridge");
3310                err = -ENODEV;
3311                goto fail;
3312        }
3313
3314        if (!(cam->bridge & cam->sensor.supported_bridge)) {
3315                DBG(1, "Bridge not supported");
3316                err = -ENODEV;
3317                goto fail;
3318        }
3319
3320        if (sn9c102_init(cam)) {
3321                DBG(1, "Initialization failed. I will retry on open().");
3322                cam->state |= DEV_MISCONFIGURED;
3323        }
3324
3325        strcpy(cam->v4ldev->name, "SN9C1xx PC Camera");
3326        cam->v4ldev->fops = &sn9c102_fops;
3327        cam->v4ldev->release = video_device_release;
3328        cam->v4ldev->parent = &udev->dev;
3329
3330        init_completion(&cam->probe);
3331
3332        err = video_register_device(cam->v4ldev, VFL_TYPE_GRABBER,
3333                                    video_nr[dev_nr]);
3334        if (err) {
3335                DBG(1, "V4L2 device registration failed");
3336                if (err == -ENFILE && video_nr[dev_nr] == -1)
3337                        DBG(1, "Free /dev/videoX node not found");
3338                video_nr[dev_nr] = -1;
3339                dev_nr = (dev_nr < SN9C102_MAX_DEVICES-1) ? dev_nr+1 : 0;
3340                complete_all(&cam->probe);
3341                goto fail;
3342        }
3343
3344        DBG(2, "V4L2 device registered as %s",
3345            video_device_node_name(cam->v4ldev));
3346
3347        video_set_drvdata(cam->v4ldev, cam);
3348        cam->module_param.force_munmap = force_munmap[dev_nr];
3349        cam->module_param.frame_timeout = frame_timeout[dev_nr];
3350
3351        dev_nr = (dev_nr < SN9C102_MAX_DEVICES-1) ? dev_nr+1 : 0;
3352
3353#ifdef CONFIG_VIDEO_ADV_DEBUG
3354        err = sn9c102_create_sysfs(cam);
3355        if (!err)
3356                DBG(2, "Optional device control through 'sysfs' "
3357                       "interface ready");
3358        else
3359                DBG(2, "Failed to create optional 'sysfs' interface for "
3360                       "device controlling. Error #%d", err);
3361#else
3362        DBG(2, "Optional device control through 'sysfs' interface disabled");
3363        DBG(3, "Compile the kernel with the 'CONFIG_VIDEO_ADV_DEBUG' "
3364               "configuration option to enable it.");
3365#endif
3366
3367        usb_set_intfdata(intf, cam);
3368        kref_init(&cam->kref);
3369        usb_get_dev(cam->usbdev);
3370
3371        complete_all(&cam->probe);
3372
3373        return 0;
3374
3375fail:
3376        if (cam) {
3377                kfree(cam->control_buffer);
3378                if (cam->v4ldev)
3379                        video_device_release(cam->v4ldev);
3380                kfree(cam);
3381        }
3382        return err;
3383}
3384
3385
3386static void sn9c102_usb_disconnect(struct usb_interface* intf)
3387{
3388        struct sn9c102_device* cam;
3389
3390        down_write(&sn9c102_dev_lock);
3391
3392        cam = usb_get_intfdata(intf);
3393
3394        DBG(2, "Disconnecting %s...", cam->v4ldev->name);
3395
3396        if (cam->users) {
3397                DBG(2, "Device %s is open! Deregistration and memory "
3398                       "deallocation are deferred.",
3399                    video_device_node_name(cam->v4ldev));
3400                cam->state |= DEV_MISCONFIGURED;
3401                sn9c102_stop_transfer(cam);
3402                cam->state |= DEV_DISCONNECTED;
3403                wake_up_interruptible(&cam->wait_frame);
3404                wake_up(&cam->wait_stream);
3405        } else
3406                cam->state |= DEV_DISCONNECTED;
3407
3408        wake_up_interruptible_all(&cam->wait_open);
3409
3410        kref_put(&cam->kref, sn9c102_release_resources);
3411
3412        up_write(&sn9c102_dev_lock);
3413}
3414
3415
3416static struct usb_driver sn9c102_usb_driver = {
3417        .name =       "sn9c102",
3418        .id_table =   sn9c102_id_table,
3419        .probe =      sn9c102_usb_probe,
3420        .disconnect = sn9c102_usb_disconnect,
3421};
3422
3423module_usb_driver(sn9c102_usb_driver);
3424