Merge branch 'for-linus' of git://git.kernel.org/pub/scm/linux/kernel/git/gerg/m68knommu
[pandora-kernel.git] / drivers / media / video / s2255drv.c
1 /*
2  *  s2255drv.c - a driver for the Sensoray 2255 USB video capture device
3  *
4  *   Copyright (C) 2007-2010 by Sensoray Company Inc.
5  *                              Dean Anderson
6  *
7  * Some video buffer code based on vivi driver:
8  *
9  * Sensoray 2255 device supports 4 simultaneous channels.
10  * The channels are not "crossbar" inputs, they are physically
11  * attached to separate video decoders.
12  *
13  * Because of USB2.0 bandwidth limitations. There is only a
14  * certain amount of data which may be transferred at one time.
15  *
16  * Example maximum bandwidth utilization:
17  *
18  * -full size, color mode YUYV or YUV422P: 2 channels at once
19  *
20  * -full or half size Grey scale: all 4 channels at once
21  *
22  * -half size, color mode YUYV or YUV422P: all 4 channels at once
23  *
24  * -full size, color mode YUYV or YUV422P 1/2 frame rate: all 4 channels
25  *  at once.
26  *  (TODO: Incorporate videodev2 frame rate(FR) enumeration,
27  *  which is currently experimental.)
28  *
29  * This program is free software; you can redistribute it and/or modify
30  * it under the terms of the GNU General Public License as published by
31  * the Free Software Foundation; either version 2 of the License, or
32  * (at your option) any later version.
33  *
34  * This program is distributed in the hope that it will be useful,
35  * but WITHOUT ANY WARRANTY; without even the implied warranty of
36  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
37  * GNU General Public License for more details.
38  *
39  * You should have received a copy of the GNU General Public License
40  * along with this program; if not, write to the Free Software
41  * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
42  */
43
44 #include <linux/module.h>
45 #include <linux/firmware.h>
46 #include <linux/kernel.h>
47 #include <linux/mutex.h>
48 #include <linux/slab.h>
49 #include <linux/videodev2.h>
50 #include <linux/version.h>
51 #include <linux/mm.h>
52 #include <media/videobuf-vmalloc.h>
53 #include <media/v4l2-common.h>
54 #include <media/v4l2-device.h>
55 #include <media/v4l2-ioctl.h>
56 #include <linux/vmalloc.h>
57 #include <linux/usb.h>
58
59 #define S2255_MAJOR_VERSION     1
60 #define S2255_MINOR_VERSION     21
61 #define S2255_RELEASE           0
62 #define S2255_VERSION           KERNEL_VERSION(S2255_MAJOR_VERSION, \
63                                                S2255_MINOR_VERSION, \
64                                                S2255_RELEASE)
65 #define FIRMWARE_FILE_NAME "f2255usb.bin"
66
67 /* default JPEG quality */
68 #define S2255_DEF_JPEG_QUAL     50
69 /* vendor request in */
70 #define S2255_VR_IN             0
71 /* vendor request out */
72 #define S2255_VR_OUT            1
73 /* firmware query */
74 #define S2255_VR_FW             0x30
75 /* USB endpoint number for configuring the device */
76 #define S2255_CONFIG_EP         2
77 /* maximum time for DSP to start responding after last FW word loaded(ms) */
78 #define S2255_DSP_BOOTTIME      800
79 /* maximum time to wait for firmware to load (ms) */
80 #define S2255_LOAD_TIMEOUT      (5000 + S2255_DSP_BOOTTIME)
81 #define S2255_DEF_BUFS          16
82 #define S2255_SETMODE_TIMEOUT   500
83 #define S2255_VIDSTATUS_TIMEOUT 350
84 #define S2255_MARKER_FRAME      cpu_to_le32(0x2255DA4AL)
85 #define S2255_MARKER_RESPONSE   cpu_to_le32(0x2255ACACL)
86 #define S2255_RESPONSE_SETMODE  cpu_to_le32(0x01)
87 #define S2255_RESPONSE_FW       cpu_to_le32(0x10)
88 #define S2255_RESPONSE_STATUS   cpu_to_le32(0x20)
89 #define S2255_USB_XFER_SIZE     (16 * 1024)
90 #define MAX_CHANNELS            4
91 #define SYS_FRAMES              4
92 /* maximum size is PAL full size plus room for the marker header(s) */
93 #define SYS_FRAMES_MAXSIZE      (720*288*2*2 + 4096)
94 #define DEF_USB_BLOCK           S2255_USB_XFER_SIZE
95 #define LINE_SZ_4CIFS_NTSC      640
96 #define LINE_SZ_2CIFS_NTSC      640
97 #define LINE_SZ_1CIFS_NTSC      320
98 #define LINE_SZ_4CIFS_PAL       704
99 #define LINE_SZ_2CIFS_PAL       704
100 #define LINE_SZ_1CIFS_PAL       352
101 #define NUM_LINES_4CIFS_NTSC    240
102 #define NUM_LINES_2CIFS_NTSC    240
103 #define NUM_LINES_1CIFS_NTSC    240
104 #define NUM_LINES_4CIFS_PAL     288
105 #define NUM_LINES_2CIFS_PAL     288
106 #define NUM_LINES_1CIFS_PAL     288
107 #define LINE_SZ_DEF             640
108 #define NUM_LINES_DEF           240
109
110
111 /* predefined settings */
112 #define FORMAT_NTSC     1
113 #define FORMAT_PAL      2
114
115 #define SCALE_4CIFS     1       /* 640x480(NTSC) or 704x576(PAL) */
116 #define SCALE_2CIFS     2       /* 640x240(NTSC) or 704x288(PAL) */
117 #define SCALE_1CIFS     3       /* 320x240(NTSC) or 352x288(PAL) */
118 /* SCALE_4CIFSI is the 2 fields interpolated into one */
119 #define SCALE_4CIFSI    4       /* 640x480(NTSC) or 704x576(PAL) high quality */
120
121 #define COLOR_YUVPL     1       /* YUV planar */
122 #define COLOR_YUVPK     2       /* YUV packed */
123 #define COLOR_Y8        4       /* monochrome */
124 #define COLOR_JPG       5       /* JPEG */
125
126 #define MASK_COLOR       0x000000ff
127 #define MASK_JPG_QUALITY 0x0000ff00
128 #define MASK_INPUT_TYPE  0x000f0000
129 /* frame decimation. Not implemented by V4L yet(experimental in V4L) */
130 #define FDEC_1          1       /* capture every frame. default */
131 #define FDEC_2          2       /* capture every 2nd frame */
132 #define FDEC_3          3       /* capture every 3rd frame */
133 #define FDEC_5          5       /* capture every 5th frame */
134
135 /*-------------------------------------------------------
136  * Default mode parameters.
137  *-------------------------------------------------------*/
138 #define DEF_SCALE       SCALE_4CIFS
139 #define DEF_COLOR       COLOR_YUVPL
140 #define DEF_FDEC        FDEC_1
141 #define DEF_BRIGHT      0
142 #define DEF_CONTRAST    0x5c
143 #define DEF_SATURATION  0x80
144 #define DEF_HUE         0
145
146 /* usb config commands */
147 #define IN_DATA_TOKEN   cpu_to_le32(0x2255c0de)
148 #define CMD_2255        cpu_to_le32(0xc2255000)
149 #define CMD_SET_MODE    cpu_to_le32((CMD_2255 | 0x10))
150 #define CMD_START       cpu_to_le32((CMD_2255 | 0x20))
151 #define CMD_STOP        cpu_to_le32((CMD_2255 | 0x30))
152 #define CMD_STATUS      cpu_to_le32((CMD_2255 | 0x40))
153
154 struct s2255_mode {
155         u32 format;     /* input video format (NTSC, PAL) */
156         u32 scale;      /* output video scale */
157         u32 color;      /* output video color format */
158         u32 fdec;       /* frame decimation */
159         u32 bright;     /* brightness */
160         u32 contrast;   /* contrast */
161         u32 saturation; /* saturation */
162         u32 hue;        /* hue (NTSC only)*/
163         u32 single;     /* capture 1 frame at a time (!=0), continuously (==0)*/
164         u32 usb_block;  /* block size. should be 4096 of DEF_USB_BLOCK */
165         u32 restart;    /* if DSP requires restart */
166 };
167
168
169 #define S2255_READ_IDLE         0
170 #define S2255_READ_FRAME        1
171
172 /* frame structure */
173 struct s2255_framei {
174         unsigned long size;
175         unsigned long ulState;  /* ulState:S2255_READ_IDLE, S2255_READ_FRAME*/
176         void *lpvbits;          /* image data */
177         unsigned long cur_size; /* current data copied to it */
178 };
179
180 /* image buffer structure */
181 struct s2255_bufferi {
182         unsigned long dwFrames;                 /* number of frames in buffer */
183         struct s2255_framei frame[SYS_FRAMES];  /* array of FRAME structures */
184 };
185
186 #define DEF_MODEI_NTSC_CONT     {FORMAT_NTSC, DEF_SCALE, DEF_COLOR,     \
187                         DEF_FDEC, DEF_BRIGHT, DEF_CONTRAST, DEF_SATURATION, \
188                         DEF_HUE, 0, DEF_USB_BLOCK, 0}
189
190 struct s2255_dmaqueue {
191         struct list_head        active;
192         struct s2255_dev        *dev;
193 };
194
195 /* for firmware loading, fw_state */
196 #define S2255_FW_NOTLOADED      0
197 #define S2255_FW_LOADED_DSPWAIT 1
198 #define S2255_FW_SUCCESS        2
199 #define S2255_FW_FAILED         3
200 #define S2255_FW_DISCONNECTING  4
201 #define S2255_FW_MARKER         cpu_to_le32(0x22552f2f)
202 /* 2255 read states */
203 #define S2255_READ_IDLE         0
204 #define S2255_READ_FRAME        1
205 struct s2255_fw {
206         int                   fw_loaded;
207         int                   fw_size;
208         struct urb            *fw_urb;
209         atomic_t              fw_state;
210         void                  *pfw_data;
211         wait_queue_head_t     wait_fw;
212         const struct firmware *fw;
213 };
214
215 struct s2255_pipeinfo {
216         u32 max_transfer_size;
217         u32 cur_transfer_size;
218         u8 *transfer_buffer;
219         u32 state;
220         void *stream_urb;
221         void *dev;      /* back pointer to s2255_dev struct*/
222         u32 err_count;
223         u32 idx;
224 };
225
226 struct s2255_fmt; /*forward declaration */
227 struct s2255_dev;
228
229 struct s2255_channel {
230         struct video_device     vdev;
231         int                     resources;
232         struct s2255_dmaqueue   vidq;
233         struct s2255_bufferi    buffer;
234         struct s2255_mode       mode;
235         /* jpeg compression */
236         struct v4l2_jpegcompression jc;
237         /* capture parameters (for high quality mode full size) */
238         struct v4l2_captureparm cap_parm;
239         int                     cur_frame;
240         int                     last_frame;
241
242         int                     b_acquire;
243         /* allocated image size */
244         unsigned long           req_image_size;
245         /* received packet size */
246         unsigned long           pkt_size;
247         int                     bad_payload;
248         unsigned long           frame_count;
249         /* if JPEG image */
250         int                     jpg_size;
251         /* if channel configured to default state */
252         int                     configured;
253         wait_queue_head_t       wait_setmode;
254         int                     setmode_ready;
255         /* video status items */
256         int                     vidstatus;
257         wait_queue_head_t       wait_vidstatus;
258         int                     vidstatus_ready;
259         unsigned int            width;
260         unsigned int            height;
261         const struct s2255_fmt  *fmt;
262         int idx; /* channel number on device, 0-3 */
263 };
264
265
266 struct s2255_dev {
267         struct s2255_channel    channel[MAX_CHANNELS];
268         struct v4l2_device      v4l2_dev;
269         atomic_t                num_channels;
270         int                     frames;
271         struct mutex            lock;   /* channels[].vdev.lock */
272         struct mutex            open_lock;
273         struct usb_device       *udev;
274         struct usb_interface    *interface;
275         u8                      read_endpoint;
276         struct timer_list       timer;
277         struct s2255_fw *fw_data;
278         struct s2255_pipeinfo   pipe;
279         u32                     cc;     /* current channel */
280         int                     frame_ready;
281         int                     chn_ready;
282         spinlock_t              slock;
283         /* dsp firmware version (f2255usb.bin) */
284         int                     dsp_fw_ver;
285         u16                     pid; /* product id */
286 };
287
288 static inline struct s2255_dev *to_s2255_dev(struct v4l2_device *v4l2_dev)
289 {
290         return container_of(v4l2_dev, struct s2255_dev, v4l2_dev);
291 }
292
293 struct s2255_fmt {
294         char *name;
295         u32 fourcc;
296         int depth;
297 };
298
299 /* buffer for one video frame */
300 struct s2255_buffer {
301         /* common v4l buffer stuff -- must be first */
302         struct videobuf_buffer vb;
303         const struct s2255_fmt *fmt;
304 };
305
306 struct s2255_fh {
307         struct s2255_dev        *dev;
308         struct videobuf_queue   vb_vidq;
309         enum v4l2_buf_type      type;
310         struct s2255_channel    *channel;
311         int                     resources;
312 };
313
314 /* current cypress EEPROM firmware version */
315 #define S2255_CUR_USB_FWVER     ((3 << 8) | 11)
316 /* current DSP FW version */
317 #define S2255_CUR_DSP_FWVER     10102
318 /* Need DSP version 5+ for video status feature */
319 #define S2255_MIN_DSP_STATUS      5
320 #define S2255_MIN_DSP_COLORFILTER 8
321 #define S2255_NORMS             (V4L2_STD_PAL | V4L2_STD_NTSC)
322
323 /* private V4L2 controls */
324
325 /*
326  * The following chart displays how COLORFILTER should be set
327  *  =========================================================
328  *  =     fourcc              =     COLORFILTER             =
329  *  =                         ===============================
330  *  =                         =   0             =    1      =
331  *  =========================================================
332  *  =  V4L2_PIX_FMT_GREY(Y8)  = monochrome from = monochrome=
333  *  =                         = s-video or      = composite =
334  *  =                         = B/W camera      = input     =
335  *  =========================================================
336  *  =    other                = color, svideo   = color,    =
337  *  =                         =                 = composite =
338  *  =========================================================
339  *
340  * Notes:
341  *   channels 0-3 on 2255 are composite
342  *   channels 0-1 on 2257 are composite, 2-3 are s-video
343  * If COLORFILTER is 0 with a composite color camera connected,
344  * the output will appear monochrome but hatching
345  * will occur.
346  * COLORFILTER is different from "color killer" and "color effects"
347  * for reasons above.
348  */
349 #define S2255_V4L2_YC_ON  1
350 #define S2255_V4L2_YC_OFF 0
351 #define V4L2_CID_PRIVATE_COLORFILTER (V4L2_CID_PRIVATE_BASE + 0)
352
353 /* frame prefix size (sent once every frame) */
354 #define PREFIX_SIZE             512
355
356 /* Channels on box are in reverse order */
357 static unsigned long G_chnmap[MAX_CHANNELS] = {3, 2, 1, 0};
358
359 static int debug;
360 static int *s2255_debug = &debug;
361
362 static int s2255_start_readpipe(struct s2255_dev *dev);
363 static void s2255_stop_readpipe(struct s2255_dev *dev);
364 static int s2255_start_acquire(struct s2255_channel *channel);
365 static int s2255_stop_acquire(struct s2255_channel *channel);
366 static void s2255_fillbuff(struct s2255_channel *chn, struct s2255_buffer *buf,
367                            int jpgsize);
368 static int s2255_set_mode(struct s2255_channel *chan, struct s2255_mode *mode);
369 static int s2255_board_shutdown(struct s2255_dev *dev);
370 static void s2255_fwload_start(struct s2255_dev *dev, int reset);
371 static void s2255_destroy(struct s2255_dev *dev);
372 static long s2255_vendor_req(struct s2255_dev *dev, unsigned char req,
373                              u16 index, u16 value, void *buf,
374                              s32 buf_len, int bOut);
375
376 /* dev_err macro with driver name */
377 #define S2255_DRIVER_NAME "s2255"
378 #define s2255_dev_err(dev, fmt, arg...)                                 \
379                 dev_err(dev, S2255_DRIVER_NAME " - " fmt, ##arg)
380
381 #define dprintk(level, fmt, arg...)                                     \
382         do {                                                            \
383                 if (*s2255_debug >= (level)) {                          \
384                         printk(KERN_DEBUG S2255_DRIVER_NAME             \
385                                 ": " fmt, ##arg);                       \
386                 }                                                       \
387         } while (0)
388
389 static struct usb_driver s2255_driver;
390
391 /* Declare static vars that will be used as parameters */
392 static unsigned int vid_limit = 16;     /* Video memory limit, in Mb */
393
394 /* start video number */
395 static int video_nr = -1;       /* /dev/videoN, -1 for autodetect */
396
397 /* Enable jpeg capture. */
398 static int jpeg_enable = 1;
399
400 module_param(debug, int, 0644);
401 MODULE_PARM_DESC(debug, "Debug level(0-100) default 0");
402 module_param(vid_limit, int, 0644);
403 MODULE_PARM_DESC(vid_limit, "video memory limit(Mb)");
404 module_param(video_nr, int, 0644);
405 MODULE_PARM_DESC(video_nr, "start video minor(-1 default autodetect)");
406 module_param(jpeg_enable, int, 0644);
407 MODULE_PARM_DESC(jpeg_enable, "Jpeg enable(1-on 0-off) default 1");
408
409 /* USB device table */
410 #define USB_SENSORAY_VID        0x1943
411 static struct usb_device_id s2255_table[] = {
412         {USB_DEVICE(USB_SENSORAY_VID, 0x2255)},
413         {USB_DEVICE(USB_SENSORAY_VID, 0x2257)}, /*same family as 2255*/
414         { }                     /* Terminating entry */
415 };
416 MODULE_DEVICE_TABLE(usb, s2255_table);
417
418 #define BUFFER_TIMEOUT msecs_to_jiffies(400)
419
420 /* image formats.  */
421 /* JPEG formats must be defined last to support jpeg_enable parameter */
422 static const struct s2255_fmt formats[] = {
423         {
424                 .name = "4:2:2, planar, YUV422P",
425                 .fourcc = V4L2_PIX_FMT_YUV422P,
426                 .depth = 16
427
428         }, {
429                 .name = "4:2:2, packed, YUYV",
430                 .fourcc = V4L2_PIX_FMT_YUYV,
431                 .depth = 16
432
433         }, {
434                 .name = "4:2:2, packed, UYVY",
435                 .fourcc = V4L2_PIX_FMT_UYVY,
436                 .depth = 16
437         }, {
438                 .name = "8bpp GREY",
439                 .fourcc = V4L2_PIX_FMT_GREY,
440                 .depth = 8
441         }, {
442                 .name = "JPG",
443                 .fourcc = V4L2_PIX_FMT_JPEG,
444                 .depth = 24
445         }, {
446                 .name = "MJPG",
447                 .fourcc = V4L2_PIX_FMT_MJPEG,
448                 .depth = 24
449         }
450 };
451
452 static int norm_maxw(struct video_device *vdev)
453 {
454         return (vdev->current_norm & V4L2_STD_NTSC) ?
455             LINE_SZ_4CIFS_NTSC : LINE_SZ_4CIFS_PAL;
456 }
457
458 static int norm_maxh(struct video_device *vdev)
459 {
460         return (vdev->current_norm & V4L2_STD_NTSC) ?
461             (NUM_LINES_1CIFS_NTSC * 2) : (NUM_LINES_1CIFS_PAL * 2);
462 }
463
464 static int norm_minw(struct video_device *vdev)
465 {
466         return (vdev->current_norm & V4L2_STD_NTSC) ?
467             LINE_SZ_1CIFS_NTSC : LINE_SZ_1CIFS_PAL;
468 }
469
470 static int norm_minh(struct video_device *vdev)
471 {
472         return (vdev->current_norm & V4L2_STD_NTSC) ?
473             (NUM_LINES_1CIFS_NTSC) : (NUM_LINES_1CIFS_PAL);
474 }
475
476
477 /*
478  * TODO: fixme: move YUV reordering to hardware
479  * converts 2255 planar format to yuyv or uyvy
480  */
481 static void planar422p_to_yuv_packed(const unsigned char *in,
482                                      unsigned char *out,
483                                      int width, int height,
484                                      int fmt)
485 {
486         unsigned char *pY;
487         unsigned char *pCb;
488         unsigned char *pCr;
489         unsigned long size = height * width;
490         unsigned int i;
491         pY = (unsigned char *)in;
492         pCr = (unsigned char *)in + height * width;
493         pCb = (unsigned char *)in + height * width + (height * width / 2);
494         for (i = 0; i < size * 2; i += 4) {
495                 out[i] = (fmt == V4L2_PIX_FMT_YUYV) ? *pY++ : *pCr++;
496                 out[i + 1] = (fmt == V4L2_PIX_FMT_YUYV) ? *pCr++ : *pY++;
497                 out[i + 2] = (fmt == V4L2_PIX_FMT_YUYV) ? *pY++ : *pCb++;
498                 out[i + 3] = (fmt == V4L2_PIX_FMT_YUYV) ? *pCb++ : *pY++;
499         }
500         return;
501 }
502
503 static void s2255_reset_dsppower(struct s2255_dev *dev)
504 {
505         s2255_vendor_req(dev, 0x40, 0x0b0b, 0x0b01, NULL, 0, 1);
506         msleep(10);
507         s2255_vendor_req(dev, 0x50, 0x0000, 0x0000, NULL, 0, 1);
508         msleep(600);
509         s2255_vendor_req(dev, 0x10, 0x0000, 0x0000, NULL, 0, 1);
510         return;
511 }
512
513 /* kickstarts the firmware loading. from probe
514  */
515 static void s2255_timer(unsigned long user_data)
516 {
517         struct s2255_fw *data = (struct s2255_fw *)user_data;
518         dprintk(100, "%s\n", __func__);
519         if (usb_submit_urb(data->fw_urb, GFP_ATOMIC) < 0) {
520                 printk(KERN_ERR "s2255: can't submit urb\n");
521                 atomic_set(&data->fw_state, S2255_FW_FAILED);
522                 /* wake up anything waiting for the firmware */
523                 wake_up(&data->wait_fw);
524                 return;
525         }
526 }
527
528
529 /* this loads the firmware asynchronously.
530    Originally this was done synchroously in probe.
531    But it is better to load it asynchronously here than block
532    inside the probe function. Blocking inside probe affects boot time.
533    FW loading is triggered by the timer in the probe function
534 */
535 static void s2255_fwchunk_complete(struct urb *urb)
536 {
537         struct s2255_fw *data = urb->context;
538         struct usb_device *udev = urb->dev;
539         int len;
540         dprintk(100, "%s: udev %p urb %p", __func__, udev, urb);
541         if (urb->status) {
542                 dev_err(&udev->dev, "URB failed with status %d\n", urb->status);
543                 atomic_set(&data->fw_state, S2255_FW_FAILED);
544                 /* wake up anything waiting for the firmware */
545                 wake_up(&data->wait_fw);
546                 return;
547         }
548         if (data->fw_urb == NULL) {
549                 s2255_dev_err(&udev->dev, "disconnected\n");
550                 atomic_set(&data->fw_state, S2255_FW_FAILED);
551                 /* wake up anything waiting for the firmware */
552                 wake_up(&data->wait_fw);
553                 return;
554         }
555 #define CHUNK_SIZE 512
556         /* all USB transfers must be done with continuous kernel memory.
557            can't allocate more than 128k in current linux kernel, so
558            upload the firmware in chunks
559          */
560         if (data->fw_loaded < data->fw_size) {
561                 len = (data->fw_loaded + CHUNK_SIZE) > data->fw_size ?
562                     data->fw_size % CHUNK_SIZE : CHUNK_SIZE;
563
564                 if (len < CHUNK_SIZE)
565                         memset(data->pfw_data, 0, CHUNK_SIZE);
566
567                 dprintk(100, "completed len %d, loaded %d \n", len,
568                         data->fw_loaded);
569
570                 memcpy(data->pfw_data,
571                        (char *) data->fw->data + data->fw_loaded, len);
572
573                 usb_fill_bulk_urb(data->fw_urb, udev, usb_sndbulkpipe(udev, 2),
574                                   data->pfw_data, CHUNK_SIZE,
575                                   s2255_fwchunk_complete, data);
576                 if (usb_submit_urb(data->fw_urb, GFP_ATOMIC) < 0) {
577                         dev_err(&udev->dev, "failed submit URB\n");
578                         atomic_set(&data->fw_state, S2255_FW_FAILED);
579                         /* wake up anything waiting for the firmware */
580                         wake_up(&data->wait_fw);
581                         return;
582                 }
583                 data->fw_loaded += len;
584         } else {
585                 atomic_set(&data->fw_state, S2255_FW_LOADED_DSPWAIT);
586                 dprintk(100, "%s: firmware upload complete\n", __func__);
587         }
588         return;
589
590 }
591
592 static int s2255_got_frame(struct s2255_channel *channel, int jpgsize)
593 {
594         struct s2255_dmaqueue *dma_q = &channel->vidq;
595         struct s2255_buffer *buf;
596         struct s2255_dev *dev = to_s2255_dev(channel->vdev.v4l2_dev);
597         unsigned long flags = 0;
598         int rc = 0;
599         spin_lock_irqsave(&dev->slock, flags);
600         if (list_empty(&dma_q->active)) {
601                 dprintk(1, "No active queue to serve\n");
602                 rc = -1;
603                 goto unlock;
604         }
605         buf = list_entry(dma_q->active.next,
606                          struct s2255_buffer, vb.queue);
607         list_del(&buf->vb.queue);
608         do_gettimeofday(&buf->vb.ts);
609         s2255_fillbuff(channel, buf, jpgsize);
610         wake_up(&buf->vb.done);
611         dprintk(2, "%s: [buf/i] [%p/%d]\n", __func__, buf, buf->vb.i);
612 unlock:
613         spin_unlock_irqrestore(&dev->slock, flags);
614         return rc;
615 }
616
617 static const struct s2255_fmt *format_by_fourcc(int fourcc)
618 {
619         unsigned int i;
620         for (i = 0; i < ARRAY_SIZE(formats); i++) {
621                 if (-1 == formats[i].fourcc)
622                         continue;
623         if (!jpeg_enable && ((formats[i].fourcc == V4L2_PIX_FMT_JPEG) ||
624                              (formats[i].fourcc == V4L2_PIX_FMT_MJPEG)))
625             continue;
626                 if (formats[i].fourcc == fourcc)
627                         return formats + i;
628         }
629         return NULL;
630 }
631
632 /* video buffer vmalloc implementation based partly on VIVI driver which is
633  *          Copyright (c) 2006 by
634  *                  Mauro Carvalho Chehab <mchehab--a.t--infradead.org>
635  *                  Ted Walther <ted--a.t--enumera.com>
636  *                  John Sokol <sokol--a.t--videotechnology.com>
637  *                  http://v4l.videotechnology.com/
638  *
639  */
640 static void s2255_fillbuff(struct s2255_channel *channel,
641                            struct s2255_buffer *buf, int jpgsize)
642 {
643         int pos = 0;
644         struct timeval ts;
645         const char *tmpbuf;
646         char *vbuf = videobuf_to_vmalloc(&buf->vb);
647         unsigned long last_frame;
648         struct s2255_framei *frm;
649
650         if (!vbuf)
651                 return;
652         last_frame = channel->last_frame;
653         if (last_frame != -1) {
654                 frm = &channel->buffer.frame[last_frame];
655                 tmpbuf =
656                     (const char *)channel->buffer.frame[last_frame].lpvbits;
657                 switch (buf->fmt->fourcc) {
658                 case V4L2_PIX_FMT_YUYV:
659                 case V4L2_PIX_FMT_UYVY:
660                         planar422p_to_yuv_packed((const unsigned char *)tmpbuf,
661                                                  vbuf, buf->vb.width,
662                                                  buf->vb.height,
663                                                  buf->fmt->fourcc);
664                         break;
665                 case V4L2_PIX_FMT_GREY:
666                         memcpy(vbuf, tmpbuf, buf->vb.width * buf->vb.height);
667                         break;
668                 case V4L2_PIX_FMT_JPEG:
669                 case V4L2_PIX_FMT_MJPEG:
670                         buf->vb.size = jpgsize;
671                         memcpy(vbuf, tmpbuf, buf->vb.size);
672                         break;
673                 case V4L2_PIX_FMT_YUV422P:
674                         memcpy(vbuf, tmpbuf,
675                                buf->vb.width * buf->vb.height * 2);
676                         break;
677                 default:
678                         printk(KERN_DEBUG "s2255: unknown format?\n");
679                 }
680                 channel->last_frame = -1;
681         } else {
682                 printk(KERN_ERR "s2255: =======no frame\n");
683                 return;
684
685         }
686         dprintk(2, "s2255fill at : Buffer 0x%08lx size= %d\n",
687                 (unsigned long)vbuf, pos);
688         /* tell v4l buffer was filled */
689
690         buf->vb.field_count = channel->frame_count * 2;
691         do_gettimeofday(&ts);
692         buf->vb.ts = ts;
693         buf->vb.state = VIDEOBUF_DONE;
694 }
695
696
697 /* ------------------------------------------------------------------
698    Videobuf operations
699    ------------------------------------------------------------------*/
700
701 static int buffer_setup(struct videobuf_queue *vq, unsigned int *count,
702                         unsigned int *size)
703 {
704         struct s2255_fh *fh = vq->priv_data;
705         struct s2255_channel *channel = fh->channel;
706         *size = channel->width * channel->height * (channel->fmt->depth >> 3);
707
708         if (0 == *count)
709                 *count = S2255_DEF_BUFS;
710
711         if (*size * *count > vid_limit * 1024 * 1024)
712                 *count = (vid_limit * 1024 * 1024) / *size;
713
714         return 0;
715 }
716
717 static void free_buffer(struct videobuf_queue *vq, struct s2255_buffer *buf)
718 {
719         dprintk(4, "%s\n", __func__);
720
721         videobuf_vmalloc_free(&buf->vb);
722         buf->vb.state = VIDEOBUF_NEEDS_INIT;
723 }
724
725 static int buffer_prepare(struct videobuf_queue *vq, struct videobuf_buffer *vb,
726                           enum v4l2_field field)
727 {
728         struct s2255_fh *fh = vq->priv_data;
729         struct s2255_channel *channel = fh->channel;
730         struct s2255_buffer *buf = container_of(vb, struct s2255_buffer, vb);
731         int rc;
732         int w = channel->width;
733         int h = channel->height;
734         dprintk(4, "%s, field=%d\n", __func__, field);
735         if (channel->fmt == NULL)
736                 return -EINVAL;
737
738         if ((w < norm_minw(&channel->vdev)) ||
739             (w > norm_maxw(&channel->vdev)) ||
740             (h < norm_minh(&channel->vdev)) ||
741             (h > norm_maxh(&channel->vdev))) {
742                 dprintk(4, "invalid buffer prepare\n");
743                 return -EINVAL;
744         }
745         buf->vb.size = w * h * (channel->fmt->depth >> 3);
746         if (0 != buf->vb.baddr && buf->vb.bsize < buf->vb.size) {
747                 dprintk(4, "invalid buffer prepare\n");
748                 return -EINVAL;
749         }
750
751         buf->fmt = channel->fmt;
752         buf->vb.width = w;
753         buf->vb.height = h;
754         buf->vb.field = field;
755
756         if (VIDEOBUF_NEEDS_INIT == buf->vb.state) {
757                 rc = videobuf_iolock(vq, &buf->vb, NULL);
758                 if (rc < 0)
759                         goto fail;
760         }
761
762         buf->vb.state = VIDEOBUF_PREPARED;
763         return 0;
764 fail:
765         free_buffer(vq, buf);
766         return rc;
767 }
768
769 static void buffer_queue(struct videobuf_queue *vq, struct videobuf_buffer *vb)
770 {
771         struct s2255_buffer *buf = container_of(vb, struct s2255_buffer, vb);
772         struct s2255_fh *fh = vq->priv_data;
773         struct s2255_channel *channel = fh->channel;
774         struct s2255_dmaqueue *vidq = &channel->vidq;
775         dprintk(1, "%s\n", __func__);
776         buf->vb.state = VIDEOBUF_QUEUED;
777         list_add_tail(&buf->vb.queue, &vidq->active);
778 }
779
780 static void buffer_release(struct videobuf_queue *vq,
781                            struct videobuf_buffer *vb)
782 {
783         struct s2255_buffer *buf = container_of(vb, struct s2255_buffer, vb);
784         struct s2255_fh *fh = vq->priv_data;
785         dprintk(4, "%s %d\n", __func__, fh->channel->idx);
786         free_buffer(vq, buf);
787 }
788
789 static struct videobuf_queue_ops s2255_video_qops = {
790         .buf_setup = buffer_setup,
791         .buf_prepare = buffer_prepare,
792         .buf_queue = buffer_queue,
793         .buf_release = buffer_release,
794 };
795
796
797 static int res_get(struct s2255_fh *fh)
798 {
799         struct s2255_channel *channel = fh->channel;
800         /* is it free? */
801         if (channel->resources)
802                 return 0; /* no, someone else uses it */
803         /* it's free, grab it */
804         channel->resources = 1;
805         fh->resources = 1;
806         dprintk(1, "s2255: res: get\n");
807         return 1;
808 }
809
810 static int res_locked(struct s2255_fh *fh)
811 {
812         return fh->channel->resources;
813 }
814
815 static int res_check(struct s2255_fh *fh)
816 {
817         return fh->resources;
818 }
819
820
821 static void res_free(struct s2255_fh *fh)
822 {
823         struct s2255_channel *channel = fh->channel;
824         channel->resources = 0;
825         fh->resources = 0;
826         dprintk(1, "res: put\n");
827 }
828
829 static int vidioc_querymenu(struct file *file, void *priv,
830                             struct v4l2_querymenu *qmenu)
831 {
832         static const char *colorfilter[] = {
833                 "Off",
834                 "On",
835                 NULL
836         };
837         if (qmenu->id == V4L2_CID_PRIVATE_COLORFILTER) {
838                 int i;
839                 const char **menu_items = colorfilter;
840                 for (i = 0; i < qmenu->index && menu_items[i]; i++)
841                         ; /* do nothing (from v4l2-common.c) */
842                 if (menu_items[i] == NULL || menu_items[i][0] == '\0')
843                         return -EINVAL;
844                 strlcpy(qmenu->name, menu_items[qmenu->index],
845                         sizeof(qmenu->name));
846                 return 0;
847         }
848         return v4l2_ctrl_query_menu(qmenu, NULL, NULL);
849 }
850
851 static int vidioc_querycap(struct file *file, void *priv,
852                            struct v4l2_capability *cap)
853 {
854         struct s2255_fh *fh = file->private_data;
855         struct s2255_dev *dev = fh->dev;
856         strlcpy(cap->driver, "s2255", sizeof(cap->driver));
857         strlcpy(cap->card, "s2255", sizeof(cap->card));
858         usb_make_path(dev->udev, cap->bus_info, sizeof(cap->bus_info));
859         cap->version = S2255_VERSION;
860         cap->capabilities = V4L2_CAP_VIDEO_CAPTURE | V4L2_CAP_STREAMING;
861         return 0;
862 }
863
864 static int vidioc_enum_fmt_vid_cap(struct file *file, void *priv,
865                                struct v4l2_fmtdesc *f)
866 {
867         int index = 0;
868         if (f)
869                 index = f->index;
870
871         if (index >= ARRAY_SIZE(formats))
872                 return -EINVAL;
873     if (!jpeg_enable && ((formats[index].fourcc == V4L2_PIX_FMT_JPEG) ||
874                          (formats[index].fourcc == V4L2_PIX_FMT_MJPEG)))
875         return -EINVAL;
876         dprintk(4, "name %s\n", formats[index].name);
877         strlcpy(f->description, formats[index].name, sizeof(f->description));
878         f->pixelformat = formats[index].fourcc;
879         return 0;
880 }
881
882 static int vidioc_g_fmt_vid_cap(struct file *file, void *priv,
883                             struct v4l2_format *f)
884 {
885         struct s2255_fh *fh = priv;
886         struct s2255_channel *channel = fh->channel;
887
888         f->fmt.pix.width = channel->width;
889         f->fmt.pix.height = channel->height;
890         f->fmt.pix.field = fh->vb_vidq.field;
891         f->fmt.pix.pixelformat = channel->fmt->fourcc;
892         f->fmt.pix.bytesperline = f->fmt.pix.width * (channel->fmt->depth >> 3);
893         f->fmt.pix.sizeimage = f->fmt.pix.height * f->fmt.pix.bytesperline;
894         return 0;
895 }
896
897 static int vidioc_try_fmt_vid_cap(struct file *file, void *priv,
898                               struct v4l2_format *f)
899 {
900         const struct s2255_fmt *fmt;
901         enum v4l2_field field;
902         int  b_any_field = 0;
903         struct s2255_fh *fh = priv;
904         struct s2255_channel *channel = fh->channel;
905         int is_ntsc;
906         is_ntsc =
907                 (channel->vdev.current_norm & V4L2_STD_NTSC) ? 1 : 0;
908
909         fmt = format_by_fourcc(f->fmt.pix.pixelformat);
910
911         if (fmt == NULL)
912                 return -EINVAL;
913
914         field = f->fmt.pix.field;
915         if (field == V4L2_FIELD_ANY)
916                 b_any_field = 1;
917
918         dprintk(50, "%s NTSC: %d suggested width: %d, height: %d\n",
919                 __func__, is_ntsc, f->fmt.pix.width, f->fmt.pix.height);
920         if (is_ntsc) {
921                 /* NTSC */
922                 if (f->fmt.pix.height >= NUM_LINES_1CIFS_NTSC * 2) {
923                         f->fmt.pix.height = NUM_LINES_1CIFS_NTSC * 2;
924                         if (b_any_field) {
925                                 field = V4L2_FIELD_SEQ_TB;
926                         } else if (!((field == V4L2_FIELD_INTERLACED) ||
927                                       (field == V4L2_FIELD_SEQ_TB) ||
928                                       (field == V4L2_FIELD_INTERLACED_TB))) {
929                                 dprintk(1, "unsupported field setting\n");
930                                 return -EINVAL;
931                         }
932                 } else {
933                         f->fmt.pix.height = NUM_LINES_1CIFS_NTSC;
934                         if (b_any_field) {
935                                 field = V4L2_FIELD_TOP;
936                         } else if (!((field == V4L2_FIELD_TOP) ||
937                                       (field == V4L2_FIELD_BOTTOM))) {
938                                 dprintk(1, "unsupported field setting\n");
939                                 return -EINVAL;
940                         }
941
942                 }
943                 if (f->fmt.pix.width >= LINE_SZ_4CIFS_NTSC)
944                         f->fmt.pix.width = LINE_SZ_4CIFS_NTSC;
945                 else if (f->fmt.pix.width >= LINE_SZ_2CIFS_NTSC)
946                         f->fmt.pix.width = LINE_SZ_2CIFS_NTSC;
947                 else if (f->fmt.pix.width >= LINE_SZ_1CIFS_NTSC)
948                         f->fmt.pix.width = LINE_SZ_1CIFS_NTSC;
949                 else
950                         f->fmt.pix.width = LINE_SZ_1CIFS_NTSC;
951         } else {
952                 /* PAL */
953                 if (f->fmt.pix.height >= NUM_LINES_1CIFS_PAL * 2) {
954                         f->fmt.pix.height = NUM_LINES_1CIFS_PAL * 2;
955                         if (b_any_field) {
956                                 field = V4L2_FIELD_SEQ_TB;
957                         } else if (!((field == V4L2_FIELD_INTERLACED) ||
958                                       (field == V4L2_FIELD_SEQ_TB) ||
959                                       (field == V4L2_FIELD_INTERLACED_TB))) {
960                                 dprintk(1, "unsupported field setting\n");
961                                 return -EINVAL;
962                         }
963                 } else {
964                         f->fmt.pix.height = NUM_LINES_1CIFS_PAL;
965                         if (b_any_field) {
966                                 field = V4L2_FIELD_TOP;
967                         } else if (!((field == V4L2_FIELD_TOP) ||
968                                      (field == V4L2_FIELD_BOTTOM))) {
969                                 dprintk(1, "unsupported field setting\n");
970                                 return -EINVAL;
971                         }
972                 }
973                 if (f->fmt.pix.width >= LINE_SZ_4CIFS_PAL) {
974                         f->fmt.pix.width = LINE_SZ_4CIFS_PAL;
975                         field = V4L2_FIELD_SEQ_TB;
976                 } else if (f->fmt.pix.width >= LINE_SZ_2CIFS_PAL) {
977                         f->fmt.pix.width = LINE_SZ_2CIFS_PAL;
978                         field = V4L2_FIELD_TOP;
979                 } else if (f->fmt.pix.width >= LINE_SZ_1CIFS_PAL) {
980                         f->fmt.pix.width = LINE_SZ_1CIFS_PAL;
981                         field = V4L2_FIELD_TOP;
982                 } else {
983                         f->fmt.pix.width = LINE_SZ_1CIFS_PAL;
984                         field = V4L2_FIELD_TOP;
985                 }
986         }
987         f->fmt.pix.field = field;
988         f->fmt.pix.bytesperline = (f->fmt.pix.width * fmt->depth) >> 3;
989         f->fmt.pix.sizeimage = f->fmt.pix.height * f->fmt.pix.bytesperline;
990         dprintk(50, "%s: set width %d height %d field %d\n", __func__,
991                 f->fmt.pix.width, f->fmt.pix.height, f->fmt.pix.field);
992         return 0;
993 }
994
995 static int vidioc_s_fmt_vid_cap(struct file *file, void *priv,
996                             struct v4l2_format *f)
997 {
998         struct s2255_fh *fh = priv;
999         struct s2255_channel *channel = fh->channel;
1000         const struct s2255_fmt *fmt;
1001         struct videobuf_queue *q = &fh->vb_vidq;
1002         struct s2255_mode mode;
1003         int ret;
1004         int norm;
1005
1006         ret = vidioc_try_fmt_vid_cap(file, fh, f);
1007
1008         if (ret < 0)
1009                 return ret;
1010
1011         fmt = format_by_fourcc(f->fmt.pix.pixelformat);
1012
1013         if (fmt == NULL)
1014                 return -EINVAL;
1015
1016         mutex_lock(&q->vb_lock);
1017
1018         if (videobuf_queue_is_busy(&fh->vb_vidq)) {
1019                 dprintk(1, "queue busy\n");
1020                 ret = -EBUSY;
1021                 goto out_s_fmt;
1022         }
1023
1024         if (res_locked(fh)) {
1025                 dprintk(1, "%s: channel busy\n", __func__);
1026                 ret = -EBUSY;
1027                 goto out_s_fmt;
1028         }
1029         mode = channel->mode;
1030         channel->fmt = fmt;
1031         channel->width = f->fmt.pix.width;
1032         channel->height = f->fmt.pix.height;
1033         fh->vb_vidq.field = f->fmt.pix.field;
1034         fh->type = f->type;
1035         norm = norm_minw(&channel->vdev);
1036         if (channel->width > norm_minw(&channel->vdev)) {
1037                 if (channel->height > norm_minh(&channel->vdev)) {
1038                         if (channel->cap_parm.capturemode &
1039                             V4L2_MODE_HIGHQUALITY)
1040                                 mode.scale = SCALE_4CIFSI;
1041                         else
1042                                 mode.scale = SCALE_4CIFS;
1043                 } else
1044                         mode.scale = SCALE_2CIFS;
1045
1046         } else {
1047                 mode.scale = SCALE_1CIFS;
1048         }
1049         /* color mode */
1050         switch (channel->fmt->fourcc) {
1051         case V4L2_PIX_FMT_GREY:
1052                 mode.color &= ~MASK_COLOR;
1053                 mode.color |= COLOR_Y8;
1054                 break;
1055         case V4L2_PIX_FMT_JPEG:
1056         case V4L2_PIX_FMT_MJPEG:
1057                 mode.color &= ~MASK_COLOR;
1058                 mode.color |= COLOR_JPG;
1059                 mode.color |= (channel->jc.quality << 8);
1060                 break;
1061         case V4L2_PIX_FMT_YUV422P:
1062                 mode.color &= ~MASK_COLOR;
1063                 mode.color |= COLOR_YUVPL;
1064                 break;
1065         case V4L2_PIX_FMT_YUYV:
1066         case V4L2_PIX_FMT_UYVY:
1067         default:
1068                 mode.color &= ~MASK_COLOR;
1069                 mode.color |= COLOR_YUVPK;
1070                 break;
1071         }
1072         if ((mode.color & MASK_COLOR) != (channel->mode.color & MASK_COLOR))
1073                 mode.restart = 1;
1074         else if (mode.scale != channel->mode.scale)
1075                 mode.restart = 1;
1076         else if (mode.format != channel->mode.format)
1077                 mode.restart = 1;
1078         channel->mode = mode;
1079         (void) s2255_set_mode(channel, &mode);
1080         ret = 0;
1081 out_s_fmt:
1082         mutex_unlock(&q->vb_lock);
1083         return ret;
1084 }
1085
1086 static int vidioc_reqbufs(struct file *file, void *priv,
1087                           struct v4l2_requestbuffers *p)
1088 {
1089         int rc;
1090         struct s2255_fh *fh = priv;
1091         rc = videobuf_reqbufs(&fh->vb_vidq, p);
1092         return rc;
1093 }
1094
1095 static int vidioc_querybuf(struct file *file, void *priv, struct v4l2_buffer *p)
1096 {
1097         int rc;
1098         struct s2255_fh *fh = priv;
1099         rc = videobuf_querybuf(&fh->vb_vidq, p);
1100         return rc;
1101 }
1102
1103 static int vidioc_qbuf(struct file *file, void *priv, struct v4l2_buffer *p)
1104 {
1105         int rc;
1106         struct s2255_fh *fh = priv;
1107         rc = videobuf_qbuf(&fh->vb_vidq, p);
1108         return rc;
1109 }
1110
1111 static int vidioc_dqbuf(struct file *file, void *priv, struct v4l2_buffer *p)
1112 {
1113         int rc;
1114         struct s2255_fh *fh = priv;
1115         rc = videobuf_dqbuf(&fh->vb_vidq, p, file->f_flags & O_NONBLOCK);
1116         return rc;
1117 }
1118
1119 /* write to the configuration pipe, synchronously */
1120 static int s2255_write_config(struct usb_device *udev, unsigned char *pbuf,
1121                               int size)
1122 {
1123         int pipe;
1124         int done;
1125         long retval = -1;
1126         if (udev) {
1127                 pipe = usb_sndbulkpipe(udev, S2255_CONFIG_EP);
1128                 retval = usb_bulk_msg(udev, pipe, pbuf, size, &done, 500);
1129         }
1130         return retval;
1131 }
1132
1133 static u32 get_transfer_size(struct s2255_mode *mode)
1134 {
1135         int linesPerFrame = LINE_SZ_DEF;
1136         int pixelsPerLine = NUM_LINES_DEF;
1137         u32 outImageSize;
1138         u32 usbInSize;
1139         unsigned int mask_mult;
1140
1141         if (mode == NULL)
1142                 return 0;
1143
1144         if (mode->format == FORMAT_NTSC) {
1145                 switch (mode->scale) {
1146                 case SCALE_4CIFS:
1147                 case SCALE_4CIFSI:
1148                         linesPerFrame = NUM_LINES_4CIFS_NTSC * 2;
1149                         pixelsPerLine = LINE_SZ_4CIFS_NTSC;
1150                         break;
1151                 case SCALE_2CIFS:
1152                         linesPerFrame = NUM_LINES_2CIFS_NTSC;
1153                         pixelsPerLine = LINE_SZ_2CIFS_NTSC;
1154                         break;
1155                 case SCALE_1CIFS:
1156                         linesPerFrame = NUM_LINES_1CIFS_NTSC;
1157                         pixelsPerLine = LINE_SZ_1CIFS_NTSC;
1158                         break;
1159                 default:
1160                         break;
1161                 }
1162         } else if (mode->format == FORMAT_PAL) {
1163                 switch (mode->scale) {
1164                 case SCALE_4CIFS:
1165                 case SCALE_4CIFSI:
1166                         linesPerFrame = NUM_LINES_4CIFS_PAL * 2;
1167                         pixelsPerLine = LINE_SZ_4CIFS_PAL;
1168                         break;
1169                 case SCALE_2CIFS:
1170                         linesPerFrame = NUM_LINES_2CIFS_PAL;
1171                         pixelsPerLine = LINE_SZ_2CIFS_PAL;
1172                         break;
1173                 case SCALE_1CIFS:
1174                         linesPerFrame = NUM_LINES_1CIFS_PAL;
1175                         pixelsPerLine = LINE_SZ_1CIFS_PAL;
1176                         break;
1177                 default:
1178                         break;
1179                 }
1180         }
1181         outImageSize = linesPerFrame * pixelsPerLine;
1182         if ((mode->color & MASK_COLOR) != COLOR_Y8) {
1183                 /* 2 bytes/pixel if not monochrome */
1184                 outImageSize *= 2;
1185         }
1186
1187         /* total bytes to send including prefix and 4K padding;
1188            must be a multiple of USB_READ_SIZE */
1189         usbInSize = outImageSize + PREFIX_SIZE; /* always send prefix */
1190         mask_mult = 0xffffffffUL - DEF_USB_BLOCK + 1;
1191         /* if size not a multiple of USB_READ_SIZE */
1192         if (usbInSize & ~mask_mult)
1193                 usbInSize = (usbInSize & mask_mult) + (DEF_USB_BLOCK);
1194         return usbInSize;
1195 }
1196
1197 static void s2255_print_cfg(struct s2255_dev *sdev, struct s2255_mode *mode)
1198 {
1199         struct device *dev = &sdev->udev->dev;
1200         dev_info(dev, "------------------------------------------------\n");
1201         dev_info(dev, "format: %d\nscale %d\n", mode->format, mode->scale);
1202         dev_info(dev, "fdec: %d\ncolor %d\n", mode->fdec, mode->color);
1203         dev_info(dev, "bright: 0x%x\n", mode->bright);
1204         dev_info(dev, "------------------------------------------------\n");
1205 }
1206
1207 /*
1208  * set mode is the function which controls the DSP.
1209  * the restart parameter in struct s2255_mode should be set whenever
1210  * the image size could change via color format, video system or image
1211  * size.
1212  * When the restart parameter is set, we sleep for ONE frame to allow the
1213  * DSP time to get the new frame
1214  */
1215 static int s2255_set_mode(struct s2255_channel *channel,
1216                           struct s2255_mode *mode)
1217 {
1218         int res;
1219         __le32 *buffer;
1220         unsigned long chn_rev;
1221         struct s2255_dev *dev = to_s2255_dev(channel->vdev.v4l2_dev);
1222         chn_rev = G_chnmap[channel->idx];
1223         dprintk(3, "%s channel: %d\n", __func__, channel->idx);
1224         /* if JPEG, set the quality */
1225         if ((mode->color & MASK_COLOR) == COLOR_JPG) {
1226                 mode->color &= ~MASK_COLOR;
1227                 mode->color |= COLOR_JPG;
1228                 mode->color &= ~MASK_JPG_QUALITY;
1229                 mode->color |= (channel->jc.quality << 8);
1230         }
1231         /* save the mode */
1232         channel->mode = *mode;
1233         channel->req_image_size = get_transfer_size(mode);
1234         dprintk(1, "%s: reqsize %ld\n", __func__, channel->req_image_size);
1235         buffer = kzalloc(512, GFP_KERNEL);
1236         if (buffer == NULL) {
1237                 dev_err(&dev->udev->dev, "out of mem\n");
1238                 return -ENOMEM;
1239         }
1240         /* set the mode */
1241         buffer[0] = IN_DATA_TOKEN;
1242         buffer[1] = (__le32) cpu_to_le32(chn_rev);
1243         buffer[2] = CMD_SET_MODE;
1244         memcpy(&buffer[3], &channel->mode, sizeof(struct s2255_mode));
1245         channel->setmode_ready = 0;
1246         res = s2255_write_config(dev->udev, (unsigned char *)buffer, 512);
1247         if (debug)
1248                 s2255_print_cfg(dev, mode);
1249         kfree(buffer);
1250         /* wait at least 3 frames before continuing */
1251         if (mode->restart) {
1252                 wait_event_timeout(channel->wait_setmode,
1253                                    (channel->setmode_ready != 0),
1254                                    msecs_to_jiffies(S2255_SETMODE_TIMEOUT));
1255                 if (channel->setmode_ready != 1) {
1256                         printk(KERN_DEBUG "s2255: no set mode response\n");
1257                         res = -EFAULT;
1258                 }
1259         }
1260         /* clear the restart flag */
1261         channel->mode.restart = 0;
1262         dprintk(1, "%s chn %d, result: %d\n", __func__, channel->idx, res);
1263         return res;
1264 }
1265
1266 static int s2255_cmd_status(struct s2255_channel *channel, u32 *pstatus)
1267 {
1268         int res;
1269         __le32 *buffer;
1270         u32 chn_rev;
1271         struct s2255_dev *dev = to_s2255_dev(channel->vdev.v4l2_dev);
1272         chn_rev = G_chnmap[channel->idx];
1273         dprintk(4, "%s chan %d\n", __func__, channel->idx);
1274         buffer = kzalloc(512, GFP_KERNEL);
1275         if (buffer == NULL) {
1276                 dev_err(&dev->udev->dev, "out of mem\n");
1277                 return -ENOMEM;
1278         }
1279         /* form the get vid status command */
1280         buffer[0] = IN_DATA_TOKEN;
1281         buffer[1] = (__le32) cpu_to_le32(chn_rev);
1282         buffer[2] = CMD_STATUS;
1283         *pstatus = 0;
1284         channel->vidstatus_ready = 0;
1285         res = s2255_write_config(dev->udev, (unsigned char *)buffer, 512);
1286         kfree(buffer);
1287         wait_event_timeout(channel->wait_vidstatus,
1288                            (channel->vidstatus_ready != 0),
1289                            msecs_to_jiffies(S2255_VIDSTATUS_TIMEOUT));
1290         if (channel->vidstatus_ready != 1) {
1291                 printk(KERN_DEBUG "s2255: no vidstatus response\n");
1292                 res = -EFAULT;
1293         }
1294         *pstatus = channel->vidstatus;
1295         dprintk(4, "%s, vid status %d\n", __func__, *pstatus);
1296         return res;
1297 }
1298
1299 static int vidioc_streamon(struct file *file, void *priv, enum v4l2_buf_type i)
1300 {
1301         int res;
1302         struct s2255_fh *fh = priv;
1303         struct s2255_dev *dev = fh->dev;
1304         struct s2255_channel *channel = fh->channel;
1305         int j;
1306         dprintk(4, "%s\n", __func__);
1307         if (fh->type != V4L2_BUF_TYPE_VIDEO_CAPTURE) {
1308                 dev_err(&dev->udev->dev, "invalid fh type0\n");
1309                 return -EINVAL;
1310         }
1311         if (i != fh->type) {
1312                 dev_err(&dev->udev->dev, "invalid fh type1\n");
1313                 return -EINVAL;
1314         }
1315
1316         if (!res_get(fh)) {
1317                 s2255_dev_err(&dev->udev->dev, "stream busy\n");
1318                 return -EBUSY;
1319         }
1320         channel->last_frame = -1;
1321         channel->bad_payload = 0;
1322         channel->cur_frame = 0;
1323         channel->frame_count = 0;
1324         for (j = 0; j < SYS_FRAMES; j++) {
1325                 channel->buffer.frame[j].ulState = S2255_READ_IDLE;
1326                 channel->buffer.frame[j].cur_size = 0;
1327         }
1328         res = videobuf_streamon(&fh->vb_vidq);
1329         if (res == 0) {
1330                 s2255_start_acquire(channel);
1331                 channel->b_acquire = 1;
1332         } else
1333                 res_free(fh);
1334
1335         return res;
1336 }
1337
1338 static int vidioc_streamoff(struct file *file, void *priv, enum v4l2_buf_type i)
1339 {
1340         struct s2255_fh *fh = priv;
1341         dprintk(4, "%s\n, channel: %d", __func__, fh->channel->idx);
1342         if (fh->type != V4L2_BUF_TYPE_VIDEO_CAPTURE) {
1343                 printk(KERN_ERR "invalid fh type0\n");
1344                 return -EINVAL;
1345         }
1346         if (i != fh->type) {
1347                 printk(KERN_ERR "invalid type i\n");
1348                 return -EINVAL;
1349         }
1350         s2255_stop_acquire(fh->channel);
1351         videobuf_streamoff(&fh->vb_vidq);
1352         res_free(fh);
1353         return 0;
1354 }
1355
1356 static int vidioc_s_std(struct file *file, void *priv, v4l2_std_id *i)
1357 {
1358         struct s2255_fh *fh = priv;
1359         struct s2255_mode mode;
1360         struct videobuf_queue *q = &fh->vb_vidq;
1361         int ret = 0;
1362         mutex_lock(&q->vb_lock);
1363         if (videobuf_queue_is_busy(q)) {
1364                 dprintk(1, "queue busy\n");
1365                 ret = -EBUSY;
1366                 goto out_s_std;
1367         }
1368         if (res_locked(fh)) {
1369                 dprintk(1, "can't change standard after started\n");
1370                 ret = -EBUSY;
1371                 goto out_s_std;
1372         }
1373         mode = fh->channel->mode;
1374         if (*i & V4L2_STD_NTSC) {
1375                 dprintk(4, "%s NTSC\n", __func__);
1376                 /* if changing format, reset frame decimation/intervals */
1377                 if (mode.format != FORMAT_NTSC) {
1378                         mode.restart = 1;
1379                         mode.format = FORMAT_NTSC;
1380                         mode.fdec = FDEC_1;
1381                 }
1382         } else if (*i & V4L2_STD_PAL) {
1383                 dprintk(4, "%s PAL\n", __func__);
1384                 if (mode.format != FORMAT_PAL) {
1385                         mode.restart = 1;
1386                         mode.format = FORMAT_PAL;
1387                         mode.fdec = FDEC_1;
1388                 }
1389         } else {
1390                 ret = -EINVAL;
1391         }
1392         if (mode.restart)
1393                 s2255_set_mode(fh->channel, &mode);
1394 out_s_std:
1395         mutex_unlock(&q->vb_lock);
1396         return ret;
1397 }
1398
1399 /* Sensoray 2255 is a multiple channel capture device.
1400    It does not have a "crossbar" of inputs.
1401    We use one V4L device per channel. The user must
1402    be aware that certain combinations are not allowed.
1403    For instance, you cannot do full FPS on more than 2 channels(2 videodevs)
1404    at once in color(you can do full fps on 4 channels with greyscale.
1405 */
1406 static int vidioc_enum_input(struct file *file, void *priv,
1407                              struct v4l2_input *inp)
1408 {
1409         struct s2255_fh *fh = priv;
1410         struct s2255_dev *dev = fh->dev;
1411         struct s2255_channel *channel = fh->channel;
1412         u32 status = 0;
1413         if (inp->index != 0)
1414                 return -EINVAL;
1415         inp->type = V4L2_INPUT_TYPE_CAMERA;
1416         inp->std = S2255_NORMS;
1417         inp->status = 0;
1418         if (dev->dsp_fw_ver >= S2255_MIN_DSP_STATUS) {
1419                 int rc;
1420                 rc = s2255_cmd_status(fh->channel, &status);
1421                 dprintk(4, "s2255_cmd_status rc: %d status %x\n", rc, status);
1422                 if (rc == 0)
1423                         inp->status =  (status & 0x01) ? 0
1424                                 : V4L2_IN_ST_NO_SIGNAL;
1425         }
1426         switch (dev->pid) {
1427         case 0x2255:
1428         default:
1429                 strlcpy(inp->name, "Composite", sizeof(inp->name));
1430                 break;
1431         case 0x2257:
1432                 strlcpy(inp->name, (channel->idx < 2) ? "Composite" : "S-Video",
1433                         sizeof(inp->name));
1434                 break;
1435         }
1436         return 0;
1437 }
1438
1439 static int vidioc_g_input(struct file *file, void *priv, unsigned int *i)
1440 {
1441         *i = 0;
1442         return 0;
1443 }
1444 static int vidioc_s_input(struct file *file, void *priv, unsigned int i)
1445 {
1446         if (i > 0)
1447                 return -EINVAL;
1448         return 0;
1449 }
1450
1451 /* --- controls ---------------------------------------------- */
1452 static int vidioc_queryctrl(struct file *file, void *priv,
1453                             struct v4l2_queryctrl *qc)
1454 {
1455         struct s2255_fh *fh = priv;
1456         struct s2255_channel *channel = fh->channel;
1457         struct s2255_dev *dev = fh->dev;
1458         switch (qc->id) {
1459         case V4L2_CID_BRIGHTNESS:
1460                 v4l2_ctrl_query_fill(qc, -127, 127, 1, DEF_BRIGHT);
1461                 break;
1462         case V4L2_CID_CONTRAST:
1463                 v4l2_ctrl_query_fill(qc, 0, 255, 1, DEF_CONTRAST);
1464                 break;
1465         case V4L2_CID_SATURATION:
1466                 v4l2_ctrl_query_fill(qc, 0, 255, 1, DEF_SATURATION);
1467                 break;
1468         case V4L2_CID_HUE:
1469                 v4l2_ctrl_query_fill(qc, 0, 255, 1, DEF_HUE);
1470                 break;
1471         case V4L2_CID_PRIVATE_COLORFILTER:
1472                 if (dev->dsp_fw_ver < S2255_MIN_DSP_COLORFILTER)
1473                         return -EINVAL;
1474                 if ((dev->pid == 0x2257) && (channel->idx > 1))
1475                         return -EINVAL;
1476                 strlcpy(qc->name, "Color Filter", sizeof(qc->name));
1477                 qc->type = V4L2_CTRL_TYPE_MENU;
1478                 qc->minimum = 0;
1479                 qc->maximum = 1;
1480                 qc->step = 1;
1481                 qc->default_value = 1;
1482                 qc->flags = 0;
1483                 break;
1484         default:
1485                 return -EINVAL;
1486         }
1487         dprintk(4, "%s, id %d\n", __func__, qc->id);
1488         return 0;
1489 }
1490
1491 static int vidioc_g_ctrl(struct file *file, void *priv,
1492                          struct v4l2_control *ctrl)
1493 {
1494         struct s2255_fh *fh = priv;
1495         struct s2255_dev *dev = fh->dev;
1496         struct s2255_channel *channel = fh->channel;
1497         switch (ctrl->id) {
1498         case V4L2_CID_BRIGHTNESS:
1499                 ctrl->value = channel->mode.bright;
1500                 break;
1501         case V4L2_CID_CONTRAST:
1502                 ctrl->value = channel->mode.contrast;
1503                 break;
1504         case V4L2_CID_SATURATION:
1505                 ctrl->value = channel->mode.saturation;
1506                 break;
1507         case V4L2_CID_HUE:
1508                 ctrl->value = channel->mode.hue;
1509                 break;
1510         case V4L2_CID_PRIVATE_COLORFILTER:
1511                 if (dev->dsp_fw_ver < S2255_MIN_DSP_COLORFILTER)
1512                         return -EINVAL;
1513                 if ((dev->pid == 0x2257) && (channel->idx > 1))
1514                         return -EINVAL;
1515                 ctrl->value = !((channel->mode.color & MASK_INPUT_TYPE) >> 16);
1516                 break;
1517         default:
1518                 return -EINVAL;
1519         }
1520         dprintk(4, "%s, id %d val %d\n", __func__, ctrl->id, ctrl->value);
1521         return 0;
1522 }
1523
1524 static int vidioc_s_ctrl(struct file *file, void *priv,
1525                          struct v4l2_control *ctrl)
1526 {
1527         struct s2255_fh *fh = priv;
1528         struct s2255_channel *channel = fh->channel;
1529         struct s2255_dev *dev = to_s2255_dev(channel->vdev.v4l2_dev);
1530         struct s2255_mode mode;
1531         mode = channel->mode;
1532         dprintk(4, "%s\n", __func__);
1533         /* update the mode to the corresponding value */
1534         switch (ctrl->id) {
1535         case V4L2_CID_BRIGHTNESS:
1536                 mode.bright = ctrl->value;
1537                 break;
1538         case V4L2_CID_CONTRAST:
1539                 mode.contrast = ctrl->value;
1540                 break;
1541         case V4L2_CID_HUE:
1542                 mode.hue = ctrl->value;
1543                 break;
1544         case V4L2_CID_SATURATION:
1545                 mode.saturation = ctrl->value;
1546                 break;
1547         case V4L2_CID_PRIVATE_COLORFILTER:
1548                 if (dev->dsp_fw_ver < S2255_MIN_DSP_COLORFILTER)
1549                         return -EINVAL;
1550                 if ((dev->pid == 0x2257) && (channel->idx > 1))
1551                         return -EINVAL;
1552                 mode.color &= ~MASK_INPUT_TYPE;
1553                 mode.color |= ((ctrl->value ? 0 : 1) << 16);
1554                 break;
1555         default:
1556                 return -EINVAL;
1557         }
1558         mode.restart = 0;
1559         /* set mode here.  Note: stream does not need restarted.
1560            some V4L programs restart stream unnecessarily
1561            after a s_crtl.
1562         */
1563         s2255_set_mode(fh->channel, &mode);
1564         return 0;
1565 }
1566
1567 static int vidioc_g_jpegcomp(struct file *file, void *priv,
1568                          struct v4l2_jpegcompression *jc)
1569 {
1570         struct s2255_fh *fh = priv;
1571         struct s2255_channel *channel = fh->channel;
1572         *jc = channel->jc;
1573         dprintk(2, "%s: quality %d\n", __func__, jc->quality);
1574         return 0;
1575 }
1576
1577 static int vidioc_s_jpegcomp(struct file *file, void *priv,
1578                          struct v4l2_jpegcompression *jc)
1579 {
1580         struct s2255_fh *fh = priv;
1581         struct s2255_channel *channel = fh->channel;
1582         if (jc->quality < 0 || jc->quality > 100)
1583                 return -EINVAL;
1584         channel->jc.quality = jc->quality;
1585         dprintk(2, "%s: quality %d\n", __func__, jc->quality);
1586         return 0;
1587 }
1588
1589 static int vidioc_g_parm(struct file *file, void *priv,
1590                          struct v4l2_streamparm *sp)
1591 {
1592         struct s2255_fh *fh = priv;
1593         __u32 def_num, def_dem;
1594         struct s2255_channel *channel = fh->channel;
1595         if (sp->type != V4L2_BUF_TYPE_VIDEO_CAPTURE)
1596                 return -EINVAL;
1597         memset(sp, 0, sizeof(struct v4l2_streamparm));
1598         sp->parm.capture.capability = V4L2_CAP_TIMEPERFRAME;
1599         sp->parm.capture.capturemode = channel->cap_parm.capturemode;
1600         def_num = (channel->mode.format == FORMAT_NTSC) ? 1001 : 1000;
1601         def_dem = (channel->mode.format == FORMAT_NTSC) ? 30000 : 25000;
1602         sp->parm.capture.timeperframe.denominator = def_dem;
1603         switch (channel->mode.fdec) {
1604         default:
1605         case FDEC_1:
1606                 sp->parm.capture.timeperframe.numerator = def_num;
1607                 break;
1608         case FDEC_2:
1609                 sp->parm.capture.timeperframe.numerator = def_num * 2;
1610                 break;
1611         case FDEC_3:
1612                 sp->parm.capture.timeperframe.numerator = def_num * 3;
1613                 break;
1614         case FDEC_5:
1615                 sp->parm.capture.timeperframe.numerator = def_num * 5;
1616                 break;
1617         }
1618         dprintk(4, "%s capture mode, %d timeperframe %d/%d\n", __func__,
1619                 sp->parm.capture.capturemode,
1620                 sp->parm.capture.timeperframe.numerator,
1621                 sp->parm.capture.timeperframe.denominator);
1622         return 0;
1623 }
1624
1625 static int vidioc_s_parm(struct file *file, void *priv,
1626                          struct v4l2_streamparm *sp)
1627 {
1628         struct s2255_fh *fh = priv;
1629         struct s2255_channel *channel = fh->channel;
1630         struct s2255_mode mode;
1631         int fdec = FDEC_1;
1632         __u32 def_num, def_dem;
1633         if (sp->type != V4L2_BUF_TYPE_VIDEO_CAPTURE)
1634                 return -EINVAL;
1635         mode = channel->mode;
1636         /* high quality capture mode requires a stream restart */
1637         if (channel->cap_parm.capturemode
1638             != sp->parm.capture.capturemode && res_locked(fh))
1639                 return -EBUSY;
1640         def_num = (mode.format == FORMAT_NTSC) ? 1001 : 1000;
1641         def_dem = (mode.format == FORMAT_NTSC) ? 30000 : 25000;
1642         if (def_dem != sp->parm.capture.timeperframe.denominator)
1643                 sp->parm.capture.timeperframe.numerator = def_num;
1644         else if (sp->parm.capture.timeperframe.numerator <= def_num)
1645                 sp->parm.capture.timeperframe.numerator = def_num;
1646         else if (sp->parm.capture.timeperframe.numerator <= (def_num * 2)) {
1647                 sp->parm.capture.timeperframe.numerator = def_num * 2;
1648                 fdec = FDEC_2;
1649         } else if (sp->parm.capture.timeperframe.numerator <= (def_num * 3)) {
1650                 sp->parm.capture.timeperframe.numerator = def_num * 3;
1651                 fdec = FDEC_3;
1652         } else {
1653                 sp->parm.capture.timeperframe.numerator = def_num * 5;
1654                 fdec = FDEC_5;
1655         }
1656         mode.fdec = fdec;
1657         sp->parm.capture.timeperframe.denominator = def_dem;
1658         s2255_set_mode(channel, &mode);
1659         dprintk(4, "%s capture mode, %d timeperframe %d/%d, fdec %d\n",
1660                 __func__,
1661                 sp->parm.capture.capturemode,
1662                 sp->parm.capture.timeperframe.numerator,
1663                 sp->parm.capture.timeperframe.denominator, fdec);
1664         return 0;
1665 }
1666
1667 static int vidioc_enum_frameintervals(struct file *file, void *priv,
1668                             struct v4l2_frmivalenum *fe)
1669 {
1670         int is_ntsc = 0;
1671 #define NUM_FRAME_ENUMS 4
1672         int frm_dec[NUM_FRAME_ENUMS] = {1, 2, 3, 5};
1673         if (fe->index < 0 || fe->index >= NUM_FRAME_ENUMS)
1674                 return -EINVAL;
1675         switch (fe->width) {
1676         case 640:
1677                 if (fe->height != 240 && fe->height != 480)
1678                         return -EINVAL;
1679                 is_ntsc = 1;
1680                 break;
1681         case 320:
1682                 if (fe->height != 240)
1683                         return -EINVAL;
1684                 is_ntsc = 1;
1685                 break;
1686         case 704:
1687                 if (fe->height != 288 && fe->height != 576)
1688                         return -EINVAL;
1689                 break;
1690         case 352:
1691                 if (fe->height != 288)
1692                         return -EINVAL;
1693                 break;
1694         default:
1695                 return -EINVAL;
1696         }
1697         fe->type = V4L2_FRMIVAL_TYPE_DISCRETE;
1698         fe->discrete.denominator = is_ntsc ? 30000 : 25000;
1699         fe->discrete.numerator = (is_ntsc ? 1001 : 1000) * frm_dec[fe->index];
1700         dprintk(4, "%s discrete %d/%d\n", __func__, fe->discrete.numerator,
1701                 fe->discrete.denominator);
1702         return 0;
1703 }
1704
1705 static int s2255_open(struct file *file)
1706 {
1707         struct video_device *vdev = video_devdata(file);
1708         struct s2255_channel *channel = video_drvdata(file);
1709         struct s2255_dev *dev = to_s2255_dev(vdev->v4l2_dev);
1710         struct s2255_fh *fh;
1711         enum v4l2_buf_type type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
1712         int state;
1713         dprintk(1, "s2255: open called (dev=%s)\n",
1714                 video_device_node_name(vdev));
1715         /*
1716          * open lock necessary to prevent multiple instances
1717          * of v4l-conf (or other programs) from simultaneously
1718          * reloading firmware.
1719          */
1720         mutex_lock(&dev->open_lock);
1721         state = atomic_read(&dev->fw_data->fw_state);
1722         switch (state) {
1723         case S2255_FW_DISCONNECTING:
1724                 mutex_unlock(&dev->open_lock);
1725                 return -ENODEV;
1726         case S2255_FW_FAILED:
1727                 s2255_dev_err(&dev->udev->dev,
1728                         "firmware load failed. retrying.\n");
1729                 s2255_fwload_start(dev, 1);
1730                 wait_event_timeout(dev->fw_data->wait_fw,
1731                                    ((atomic_read(&dev->fw_data->fw_state)
1732                                      == S2255_FW_SUCCESS) ||
1733                                     (atomic_read(&dev->fw_data->fw_state)
1734                                      == S2255_FW_DISCONNECTING)),
1735                                    msecs_to_jiffies(S2255_LOAD_TIMEOUT));
1736                 /* state may have changed, re-read */
1737                 state = atomic_read(&dev->fw_data->fw_state);
1738                 break;
1739         case S2255_FW_NOTLOADED:
1740         case S2255_FW_LOADED_DSPWAIT:
1741                 /* give S2255_LOAD_TIMEOUT time for firmware to load in case
1742                    driver loaded and then device immediately opened */
1743                 printk(KERN_INFO "%s waiting for firmware load\n", __func__);
1744                 wait_event_timeout(dev->fw_data->wait_fw,
1745                                    ((atomic_read(&dev->fw_data->fw_state)
1746                                      == S2255_FW_SUCCESS) ||
1747                                     (atomic_read(&dev->fw_data->fw_state)
1748                                      == S2255_FW_DISCONNECTING)),
1749                                    msecs_to_jiffies(S2255_LOAD_TIMEOUT));
1750                 /* state may have changed, re-read */
1751                 state = atomic_read(&dev->fw_data->fw_state);
1752                 break;
1753         case S2255_FW_SUCCESS:
1754         default:
1755                 break;
1756         }
1757         /* state may have changed in above switch statement */
1758         switch (state) {
1759         case S2255_FW_SUCCESS:
1760                 break;
1761         case S2255_FW_FAILED:
1762                 printk(KERN_INFO "2255 firmware load failed.\n");
1763                 mutex_unlock(&dev->open_lock);
1764                 return -ENODEV;
1765         case S2255_FW_DISCONNECTING:
1766                 printk(KERN_INFO "%s: disconnecting\n", __func__);
1767                 mutex_unlock(&dev->open_lock);
1768                 return -ENODEV;
1769         case S2255_FW_LOADED_DSPWAIT:
1770         case S2255_FW_NOTLOADED:
1771                 printk(KERN_INFO "%s: firmware not loaded yet"
1772                        "please try again later\n",
1773                        __func__);
1774                 /*
1775                  * Timeout on firmware load means device unusable.
1776                  * Set firmware failure state.
1777                  * On next s2255_open the firmware will be reloaded.
1778                  */
1779                 atomic_set(&dev->fw_data->fw_state,
1780                            S2255_FW_FAILED);
1781                 mutex_unlock(&dev->open_lock);
1782                 return -EAGAIN;
1783         default:
1784                 printk(KERN_INFO "%s: unknown state\n", __func__);
1785                 mutex_unlock(&dev->open_lock);
1786                 return -EFAULT;
1787         }
1788         mutex_unlock(&dev->open_lock);
1789         /* allocate + initialize per filehandle data */
1790         fh = kzalloc(sizeof(*fh), GFP_KERNEL);
1791         if (NULL == fh)
1792                 return -ENOMEM;
1793         file->private_data = fh;
1794         fh->dev = dev;
1795         fh->type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
1796         fh->channel = channel;
1797         if (!channel->configured) {
1798                 /* configure channel to default state */
1799                 channel->fmt = &formats[0];
1800                 s2255_set_mode(channel, &channel->mode);
1801                 channel->configured = 1;
1802         }
1803         dprintk(1, "%s: dev=%s type=%s\n", __func__,
1804                 video_device_node_name(vdev), v4l2_type_names[type]);
1805         dprintk(2, "%s: fh=0x%08lx, dev=0x%08lx, vidq=0x%08lx\n", __func__,
1806                 (unsigned long)fh, (unsigned long)dev,
1807                 (unsigned long)&channel->vidq);
1808         dprintk(4, "%s: list_empty active=%d\n", __func__,
1809                 list_empty(&channel->vidq.active));
1810         videobuf_queue_vmalloc_init(&fh->vb_vidq, &s2255_video_qops,
1811                                     NULL, &dev->slock,
1812                                     fh->type,
1813                                     V4L2_FIELD_INTERLACED,
1814                                     sizeof(struct s2255_buffer),
1815                                     fh, vdev->lock);
1816         return 0;
1817 }
1818
1819
1820 static unsigned int s2255_poll(struct file *file,
1821                                struct poll_table_struct *wait)
1822 {
1823         struct s2255_fh *fh = file->private_data;
1824         int rc;
1825         dprintk(100, "%s\n", __func__);
1826         if (V4L2_BUF_TYPE_VIDEO_CAPTURE != fh->type)
1827                 return POLLERR;
1828         rc = videobuf_poll_stream(file, &fh->vb_vidq, wait);
1829         return rc;
1830 }
1831
1832 static void s2255_destroy(struct s2255_dev *dev)
1833 {
1834         /* board shutdown stops the read pipe if it is running */
1835         s2255_board_shutdown(dev);
1836         /* make sure firmware still not trying to load */
1837         del_timer(&dev->timer);  /* only started in .probe and .open */
1838         if (dev->fw_data->fw_urb) {
1839                 usb_kill_urb(dev->fw_data->fw_urb);
1840                 usb_free_urb(dev->fw_data->fw_urb);
1841                 dev->fw_data->fw_urb = NULL;
1842         }
1843         if (dev->fw_data->fw)
1844                 release_firmware(dev->fw_data->fw);
1845         kfree(dev->fw_data->pfw_data);
1846         kfree(dev->fw_data);
1847         /* reset the DSP so firmware can be reloaded next time */
1848         s2255_reset_dsppower(dev);
1849         mutex_destroy(&dev->open_lock);
1850         mutex_destroy(&dev->lock);
1851         usb_put_dev(dev->udev);
1852         v4l2_device_unregister(&dev->v4l2_dev);
1853         dprintk(1, "%s", __func__);
1854         kfree(dev);
1855 }
1856
1857 static int s2255_release(struct file *file)
1858 {
1859         struct s2255_fh *fh = file->private_data;
1860         struct s2255_dev *dev = fh->dev;
1861         struct video_device *vdev = video_devdata(file);
1862         struct s2255_channel *channel = fh->channel;
1863         if (!dev)
1864                 return -ENODEV;
1865         /* turn off stream */
1866         if (res_check(fh)) {
1867                 if (channel->b_acquire)
1868                         s2255_stop_acquire(fh->channel);
1869                 videobuf_streamoff(&fh->vb_vidq);
1870                 res_free(fh);
1871         }
1872         videobuf_mmap_free(&fh->vb_vidq);
1873         dprintk(1, "%s (dev=%s)\n", __func__, video_device_node_name(vdev));
1874         kfree(fh);
1875         return 0;
1876 }
1877
1878 static int s2255_mmap_v4l(struct file *file, struct vm_area_struct *vma)
1879 {
1880         struct s2255_fh *fh = file->private_data;
1881         int ret;
1882
1883         if (!fh)
1884                 return -ENODEV;
1885         dprintk(4, "%s, vma=0x%08lx\n", __func__, (unsigned long)vma);
1886         ret = videobuf_mmap_mapper(&fh->vb_vidq, vma);
1887         dprintk(4, "%s vma start=0x%08lx, size=%ld, ret=%d\n", __func__,
1888                 (unsigned long)vma->vm_start,
1889                 (unsigned long)vma->vm_end - (unsigned long)vma->vm_start, ret);
1890         return ret;
1891 }
1892
1893 static const struct v4l2_file_operations s2255_fops_v4l = {
1894         .owner = THIS_MODULE,
1895         .open = s2255_open,
1896         .release = s2255_release,
1897         .poll = s2255_poll,
1898         .unlocked_ioctl = video_ioctl2, /* V4L2 ioctl handler */
1899         .mmap = s2255_mmap_v4l,
1900 };
1901
1902 static const struct v4l2_ioctl_ops s2255_ioctl_ops = {
1903         .vidioc_querymenu = vidioc_querymenu,
1904         .vidioc_querycap = vidioc_querycap,
1905         .vidioc_enum_fmt_vid_cap = vidioc_enum_fmt_vid_cap,
1906         .vidioc_g_fmt_vid_cap = vidioc_g_fmt_vid_cap,
1907         .vidioc_try_fmt_vid_cap = vidioc_try_fmt_vid_cap,
1908         .vidioc_s_fmt_vid_cap = vidioc_s_fmt_vid_cap,
1909         .vidioc_reqbufs = vidioc_reqbufs,
1910         .vidioc_querybuf = vidioc_querybuf,
1911         .vidioc_qbuf = vidioc_qbuf,
1912         .vidioc_dqbuf = vidioc_dqbuf,
1913         .vidioc_s_std = vidioc_s_std,
1914         .vidioc_enum_input = vidioc_enum_input,
1915         .vidioc_g_input = vidioc_g_input,
1916         .vidioc_s_input = vidioc_s_input,
1917         .vidioc_queryctrl = vidioc_queryctrl,
1918         .vidioc_g_ctrl = vidioc_g_ctrl,
1919         .vidioc_s_ctrl = vidioc_s_ctrl,
1920         .vidioc_streamon = vidioc_streamon,
1921         .vidioc_streamoff = vidioc_streamoff,
1922         .vidioc_s_jpegcomp = vidioc_s_jpegcomp,
1923         .vidioc_g_jpegcomp = vidioc_g_jpegcomp,
1924         .vidioc_s_parm = vidioc_s_parm,
1925         .vidioc_g_parm = vidioc_g_parm,
1926         .vidioc_enum_frameintervals = vidioc_enum_frameintervals,
1927 };
1928
1929 static void s2255_video_device_release(struct video_device *vdev)
1930 {
1931         struct s2255_dev *dev = to_s2255_dev(vdev->v4l2_dev);
1932         dprintk(4, "%s, chnls: %d \n", __func__,
1933                 atomic_read(&dev->num_channels));
1934         if (atomic_dec_and_test(&dev->num_channels))
1935                 s2255_destroy(dev);
1936         return;
1937 }
1938
1939 static struct video_device template = {
1940         .name = "s2255v",
1941         .fops = &s2255_fops_v4l,
1942         .ioctl_ops = &s2255_ioctl_ops,
1943         .release = s2255_video_device_release,
1944         .tvnorms = S2255_NORMS,
1945         .current_norm = V4L2_STD_NTSC_M,
1946 };
1947
1948 static int s2255_probe_v4l(struct s2255_dev *dev)
1949 {
1950         int ret;
1951         int i;
1952         int cur_nr = video_nr;
1953         struct s2255_channel *channel;
1954         ret = v4l2_device_register(&dev->interface->dev, &dev->v4l2_dev);
1955         if (ret)
1956                 return ret;
1957         /* initialize all video 4 linux */
1958         /* register 4 video devices */
1959         for (i = 0; i < MAX_CHANNELS; i++) {
1960                 channel = &dev->channel[i];
1961                 INIT_LIST_HEAD(&channel->vidq.active);
1962                 channel->vidq.dev = dev;
1963                 /* register 4 video devices */
1964                 channel->vdev = template;
1965                 channel->vdev.lock = &dev->lock;
1966                 channel->vdev.v4l2_dev = &dev->v4l2_dev;
1967                 video_set_drvdata(&channel->vdev, channel);
1968                 if (video_nr == -1)
1969                         ret = video_register_device(&channel->vdev,
1970                                                     VFL_TYPE_GRABBER,
1971                                                     video_nr);
1972                 else
1973                         ret = video_register_device(&channel->vdev,
1974                                                     VFL_TYPE_GRABBER,
1975                                                     cur_nr + i);
1976
1977                 if (ret) {
1978                         dev_err(&dev->udev->dev,
1979                                 "failed to register video device!\n");
1980                         break;
1981                 }
1982                 atomic_inc(&dev->num_channels);
1983                 v4l2_info(&dev->v4l2_dev, "V4L2 device registered as %s\n",
1984                           video_device_node_name(&channel->vdev));
1985
1986         }
1987         printk(KERN_INFO "Sensoray 2255 V4L driver Revision: %d.%d\n",
1988                S2255_MAJOR_VERSION,
1989                S2255_MINOR_VERSION);
1990         /* if no channels registered, return error and probe will fail*/
1991         if (atomic_read(&dev->num_channels) == 0) {
1992                 v4l2_device_unregister(&dev->v4l2_dev);
1993                 return ret;
1994         }
1995         if (atomic_read(&dev->num_channels) != MAX_CHANNELS)
1996                 printk(KERN_WARNING "s2255: Not all channels available.\n");
1997         return 0;
1998 }
1999
2000 /* this function moves the usb stream read pipe data
2001  * into the system buffers.
2002  * returns 0 on success, EAGAIN if more data to process( call this
2003  * function again).
2004  *
2005  * Received frame structure:
2006  * bytes 0-3:  marker : 0x2255DA4AL (S2255_MARKER_FRAME)
2007  * bytes 4-7:  channel: 0-3
2008  * bytes 8-11: payload size:  size of the frame
2009  * bytes 12-payloadsize+12:  frame data
2010  */
2011 static int save_frame(struct s2255_dev *dev, struct s2255_pipeinfo *pipe_info)
2012 {
2013         char *pdest;
2014         u32 offset = 0;
2015         int bframe = 0;
2016         char *psrc;
2017         unsigned long copy_size;
2018         unsigned long size;
2019         s32 idx = -1;
2020         struct s2255_framei *frm;
2021         unsigned char *pdata;
2022         struct s2255_channel *channel;
2023         dprintk(100, "buffer to user\n");
2024         channel = &dev->channel[dev->cc];
2025         idx = channel->cur_frame;
2026         frm = &channel->buffer.frame[idx];
2027         if (frm->ulState == S2255_READ_IDLE) {
2028                 int jj;
2029                 unsigned int cc;
2030                 __le32 *pdword; /*data from dsp is little endian */
2031                 int payload;
2032                 /* search for marker codes */
2033                 pdata = (unsigned char *)pipe_info->transfer_buffer;
2034                 pdword = (__le32 *)pdata;
2035                 for (jj = 0; jj < (pipe_info->cur_transfer_size - 12); jj++) {
2036                         switch (*pdword) {
2037                         case S2255_MARKER_FRAME:
2038                                 dprintk(4, "found frame marker at offset:"
2039                                         " %d [%x %x]\n", jj, pdata[0],
2040                                         pdata[1]);
2041                                 offset = jj + PREFIX_SIZE;
2042                                 bframe = 1;
2043                                 cc = pdword[1];
2044                                 if (cc >= MAX_CHANNELS) {
2045                                         printk(KERN_ERR
2046                                                "bad channel\n");
2047                                         return -EINVAL;
2048                                 }
2049                                 /* reverse it */
2050                                 dev->cc = G_chnmap[cc];
2051                                 channel = &dev->channel[dev->cc];
2052                                 payload =  pdword[3];
2053                                 if (payload > channel->req_image_size) {
2054                                         channel->bad_payload++;
2055                                         /* discard the bad frame */
2056                                         return -EINVAL;
2057                                 }
2058                                 channel->pkt_size = payload;
2059                                 channel->jpg_size = pdword[4];
2060                                 break;
2061                         case S2255_MARKER_RESPONSE:
2062
2063                                 pdata += DEF_USB_BLOCK;
2064                                 jj += DEF_USB_BLOCK;
2065                                 if (pdword[1] >= MAX_CHANNELS)
2066                                         break;
2067                                 cc = G_chnmap[pdword[1]];
2068                                 if (cc >= MAX_CHANNELS)
2069                                         break;
2070                                 channel = &dev->channel[cc];
2071                                 switch (pdword[2]) {
2072                                 case S2255_RESPONSE_SETMODE:
2073                                         /* check if channel valid */
2074                                         /* set mode ready */
2075                                         channel->setmode_ready = 1;
2076                                         wake_up(&channel->wait_setmode);
2077                                         dprintk(5, "setmode ready %d\n", cc);
2078                                         break;
2079                                 case S2255_RESPONSE_FW:
2080                                         dev->chn_ready |= (1 << cc);
2081                                         if ((dev->chn_ready & 0x0f) != 0x0f)
2082                                                 break;
2083                                         /* all channels ready */
2084                                         printk(KERN_INFO "s2255: fw loaded\n");
2085                                         atomic_set(&dev->fw_data->fw_state,
2086                                                    S2255_FW_SUCCESS);
2087                                         wake_up(&dev->fw_data->wait_fw);
2088                                         break;
2089                                 case S2255_RESPONSE_STATUS:
2090                                         channel->vidstatus = pdword[3];
2091                                         channel->vidstatus_ready = 1;
2092                                         wake_up(&channel->wait_vidstatus);
2093                                         dprintk(5, "got vidstatus %x chan %d\n",
2094                                                 pdword[3], cc);
2095                                         break;
2096                                 default:
2097                                         printk(KERN_INFO "s2255 unknown resp\n");
2098                                 }
2099                         default:
2100                                 pdata++;
2101                                 break;
2102                         }
2103                         if (bframe)
2104                                 break;
2105                 } /* for */
2106                 if (!bframe)
2107                         return -EINVAL;
2108         }
2109         channel = &dev->channel[dev->cc];
2110         idx = channel->cur_frame;
2111         frm = &channel->buffer.frame[idx];
2112         /* search done.  now find out if should be acquiring on this channel */
2113         if (!channel->b_acquire) {
2114                 /* we found a frame, but this channel is turned off */
2115                 frm->ulState = S2255_READ_IDLE;
2116                 return -EINVAL;
2117         }
2118
2119         if (frm->ulState == S2255_READ_IDLE) {
2120                 frm->ulState = S2255_READ_FRAME;
2121                 frm->cur_size = 0;
2122         }
2123
2124         /* skip the marker 512 bytes (and offset if out of sync) */
2125         psrc = (u8 *)pipe_info->transfer_buffer + offset;
2126
2127
2128         if (frm->lpvbits == NULL) {
2129                 dprintk(1, "s2255 frame buffer == NULL.%p %p %d %d",
2130                         frm, dev, dev->cc, idx);
2131                 return -ENOMEM;
2132         }
2133
2134         pdest = frm->lpvbits + frm->cur_size;
2135
2136         copy_size = (pipe_info->cur_transfer_size - offset);
2137
2138         size = channel->pkt_size - PREFIX_SIZE;
2139
2140         /* sanity check on pdest */
2141         if ((copy_size + frm->cur_size) < channel->req_image_size)
2142                 memcpy(pdest, psrc, copy_size);
2143
2144         frm->cur_size += copy_size;
2145         dprintk(4, "cur_size size %lu size %lu \n", frm->cur_size, size);
2146
2147         if (frm->cur_size >= size) {
2148                 dprintk(2, "****************[%d]Buffer[%d]full*************\n",
2149                         dev->cc, idx);
2150                 channel->last_frame = channel->cur_frame;
2151                 channel->cur_frame++;
2152                 /* end of system frame ring buffer, start at zero */
2153                 if ((channel->cur_frame == SYS_FRAMES) ||
2154                     (channel->cur_frame == channel->buffer.dwFrames))
2155                         channel->cur_frame = 0;
2156                 /* frame ready */
2157                 if (channel->b_acquire)
2158                         s2255_got_frame(channel, channel->jpg_size);
2159                 channel->frame_count++;
2160                 frm->ulState = S2255_READ_IDLE;
2161                 frm->cur_size = 0;
2162
2163         }
2164         /* done successfully */
2165         return 0;
2166 }
2167
2168 static void s2255_read_video_callback(struct s2255_dev *dev,
2169                                       struct s2255_pipeinfo *pipe_info)
2170 {
2171         int res;
2172         dprintk(50, "callback read video \n");
2173
2174         if (dev->cc >= MAX_CHANNELS) {
2175                 dev->cc = 0;
2176                 dev_err(&dev->udev->dev, "invalid channel\n");
2177                 return;
2178         }
2179         /* otherwise copy to the system buffers */
2180         res = save_frame(dev, pipe_info);
2181         if (res != 0)
2182                 dprintk(4, "s2255: read callback failed\n");
2183
2184         dprintk(50, "callback read video done\n");
2185         return;
2186 }
2187
2188 static long s2255_vendor_req(struct s2255_dev *dev, unsigned char Request,
2189                              u16 Index, u16 Value, void *TransferBuffer,
2190                              s32 TransferBufferLength, int bOut)
2191 {
2192         int r;
2193         if (!bOut) {
2194                 r = usb_control_msg(dev->udev, usb_rcvctrlpipe(dev->udev, 0),
2195                                     Request,
2196                                     USB_TYPE_VENDOR | USB_RECIP_DEVICE |
2197                                     USB_DIR_IN,
2198                                     Value, Index, TransferBuffer,
2199                                     TransferBufferLength, HZ * 5);
2200         } else {
2201                 r = usb_control_msg(dev->udev, usb_sndctrlpipe(dev->udev, 0),
2202                                     Request, USB_TYPE_VENDOR | USB_RECIP_DEVICE,
2203                                     Value, Index, TransferBuffer,
2204                                     TransferBufferLength, HZ * 5);
2205         }
2206         return r;
2207 }
2208
2209 /*
2210  * retrieve FX2 firmware version. future use.
2211  * @param dev pointer to device extension
2212  * @return -1 for fail, else returns firmware version as an int(16 bits)
2213  */
2214 static int s2255_get_fx2fw(struct s2255_dev *dev)
2215 {
2216         int fw;
2217         int ret;
2218         unsigned char transBuffer[64];
2219         ret = s2255_vendor_req(dev, S2255_VR_FW, 0, 0, transBuffer, 2,
2220                                S2255_VR_IN);
2221         if (ret < 0)
2222                 dprintk(2, "get fw error: %x\n", ret);
2223         fw = transBuffer[0] + (transBuffer[1] << 8);
2224         dprintk(2, "Get FW %x %x\n", transBuffer[0], transBuffer[1]);
2225         return fw;
2226 }
2227
2228 /*
2229  * Create the system ring buffer to copy frames into from the
2230  * usb read pipe.
2231  */
2232 static int s2255_create_sys_buffers(struct s2255_channel *channel)
2233 {
2234         unsigned long i;
2235         unsigned long reqsize;
2236         dprintk(1, "create sys buffers\n");
2237         channel->buffer.dwFrames = SYS_FRAMES;
2238         /* always allocate maximum size(PAL) for system buffers */
2239         reqsize = SYS_FRAMES_MAXSIZE;
2240
2241         if (reqsize > SYS_FRAMES_MAXSIZE)
2242                 reqsize = SYS_FRAMES_MAXSIZE;
2243
2244         for (i = 0; i < SYS_FRAMES; i++) {
2245                 /* allocate the frames */
2246                 channel->buffer.frame[i].lpvbits = vmalloc(reqsize);
2247                 dprintk(1, "valloc %p chan %d, idx %lu, pdata %p\n",
2248                         &channel->buffer.frame[i], channel->idx, i,
2249                         channel->buffer.frame[i].lpvbits);
2250                 channel->buffer.frame[i].size = reqsize;
2251                 if (channel->buffer.frame[i].lpvbits == NULL) {
2252                         printk(KERN_INFO "out of memory.  using less frames\n");
2253                         channel->buffer.dwFrames = i;
2254                         break;
2255                 }
2256         }
2257
2258         /* make sure internal states are set */
2259         for (i = 0; i < SYS_FRAMES; i++) {
2260                 channel->buffer.frame[i].ulState = 0;
2261                 channel->buffer.frame[i].cur_size = 0;
2262         }
2263
2264         channel->cur_frame = 0;
2265         channel->last_frame = -1;
2266         return 0;
2267 }
2268
2269 static int s2255_release_sys_buffers(struct s2255_channel *channel)
2270 {
2271         unsigned long i;
2272         dprintk(1, "release sys buffers\n");
2273         for (i = 0; i < SYS_FRAMES; i++) {
2274                 if (channel->buffer.frame[i].lpvbits) {
2275                         dprintk(1, "vfree %p\n",
2276                                 channel->buffer.frame[i].lpvbits);
2277                         vfree(channel->buffer.frame[i].lpvbits);
2278                 }
2279                 channel->buffer.frame[i].lpvbits = NULL;
2280         }
2281         return 0;
2282 }
2283
2284 static int s2255_board_init(struct s2255_dev *dev)
2285 {
2286         struct s2255_mode mode_def = DEF_MODEI_NTSC_CONT;
2287         int fw_ver;
2288         int j;
2289         struct s2255_pipeinfo *pipe = &dev->pipe;
2290         dprintk(4, "board init: %p", dev);
2291         memset(pipe, 0, sizeof(*pipe));
2292         pipe->dev = dev;
2293         pipe->cur_transfer_size = S2255_USB_XFER_SIZE;
2294         pipe->max_transfer_size = S2255_USB_XFER_SIZE;
2295
2296         pipe->transfer_buffer = kzalloc(pipe->max_transfer_size,
2297                                         GFP_KERNEL);
2298         if (pipe->transfer_buffer == NULL) {
2299                 dprintk(1, "out of memory!\n");
2300                 return -ENOMEM;
2301         }
2302         /* query the firmware */
2303         fw_ver = s2255_get_fx2fw(dev);
2304
2305         printk(KERN_INFO "2255 usb firmware version %d.%d\n",
2306                (fw_ver >> 8) & 0xff,
2307                fw_ver & 0xff);
2308
2309         if (fw_ver < S2255_CUR_USB_FWVER)
2310                 dev_err(&dev->udev->dev,
2311                         "usb firmware not up to date %d.%d\n",
2312                         (fw_ver >> 8) & 0xff,
2313                         fw_ver & 0xff);
2314
2315         for (j = 0; j < MAX_CHANNELS; j++) {
2316                 struct s2255_channel *channel = &dev->channel[j];
2317                 channel->b_acquire = 0;
2318                 channel->mode = mode_def;
2319                 if (dev->pid == 0x2257 && j > 1)
2320                         channel->mode.color |= (1 << 16);
2321                 channel->jc.quality = S2255_DEF_JPEG_QUAL;
2322                 channel->width = LINE_SZ_4CIFS_NTSC;
2323                 channel->height = NUM_LINES_4CIFS_NTSC * 2;
2324                 channel->fmt = &formats[0];
2325                 channel->mode.restart = 1;
2326                 channel->req_image_size = get_transfer_size(&mode_def);
2327                 channel->frame_count = 0;
2328                 /* create the system buffers */
2329                 s2255_create_sys_buffers(channel);
2330         }
2331         /* start read pipe */
2332         s2255_start_readpipe(dev);
2333         dprintk(1, "%s: success\n", __func__);
2334         return 0;
2335 }
2336
2337 static int s2255_board_shutdown(struct s2255_dev *dev)
2338 {
2339         u32 i;
2340         dprintk(1, "%s: dev: %p", __func__,  dev);
2341
2342         for (i = 0; i < MAX_CHANNELS; i++) {
2343                 if (dev->channel[i].b_acquire)
2344                         s2255_stop_acquire(&dev->channel[i]);
2345         }
2346         s2255_stop_readpipe(dev);
2347         for (i = 0; i < MAX_CHANNELS; i++)
2348                 s2255_release_sys_buffers(&dev->channel[i]);
2349         /* release transfer buffer */
2350         kfree(dev->pipe.transfer_buffer);
2351         return 0;
2352 }
2353
2354 static void read_pipe_completion(struct urb *purb)
2355 {
2356         struct s2255_pipeinfo *pipe_info;
2357         struct s2255_dev *dev;
2358         int status;
2359         int pipe;
2360         pipe_info = purb->context;
2361         dprintk(100, "%s: urb:%p, status %d\n", __func__, purb,
2362                 purb->status);
2363         if (pipe_info == NULL) {
2364                 dev_err(&purb->dev->dev, "no context!\n");
2365                 return;
2366         }
2367
2368         dev = pipe_info->dev;
2369         if (dev == NULL) {
2370                 dev_err(&purb->dev->dev, "no context!\n");
2371                 return;
2372         }
2373         status = purb->status;
2374         /* if shutting down, do not resubmit, exit immediately */
2375         if (status == -ESHUTDOWN) {
2376                 dprintk(2, "%s: err shutdown\n", __func__);
2377                 pipe_info->err_count++;
2378                 return;
2379         }
2380
2381         if (pipe_info->state == 0) {
2382                 dprintk(2, "%s: exiting USB pipe", __func__);
2383                 return;
2384         }
2385
2386         if (status == 0)
2387                 s2255_read_video_callback(dev, pipe_info);
2388         else {
2389                 pipe_info->err_count++;
2390                 dprintk(1, "%s: failed URB %d\n", __func__, status);
2391         }
2392
2393         pipe = usb_rcvbulkpipe(dev->udev, dev->read_endpoint);
2394         /* reuse urb */
2395         usb_fill_bulk_urb(pipe_info->stream_urb, dev->udev,
2396                           pipe,
2397                           pipe_info->transfer_buffer,
2398                           pipe_info->cur_transfer_size,
2399                           read_pipe_completion, pipe_info);
2400
2401         if (pipe_info->state != 0) {
2402                 if (usb_submit_urb(pipe_info->stream_urb, GFP_ATOMIC)) {
2403                         dev_err(&dev->udev->dev, "error submitting urb\n");
2404                 }
2405         } else {
2406                 dprintk(2, "%s :complete state 0\n", __func__);
2407         }
2408         return;
2409 }
2410
2411 static int s2255_start_readpipe(struct s2255_dev *dev)
2412 {
2413         int pipe;
2414         int retval;
2415         struct s2255_pipeinfo *pipe_info = &dev->pipe;
2416         pipe = usb_rcvbulkpipe(dev->udev, dev->read_endpoint);
2417         dprintk(2, "%s: IN %d\n", __func__, dev->read_endpoint);
2418         pipe_info->state = 1;
2419         pipe_info->err_count = 0;
2420         pipe_info->stream_urb = usb_alloc_urb(0, GFP_KERNEL);
2421         if (!pipe_info->stream_urb) {
2422                 dev_err(&dev->udev->dev,
2423                         "ReadStream: Unable to alloc URB\n");
2424                 return -ENOMEM;
2425         }
2426         /* transfer buffer allocated in board_init */
2427         usb_fill_bulk_urb(pipe_info->stream_urb, dev->udev,
2428                           pipe,
2429                           pipe_info->transfer_buffer,
2430                           pipe_info->cur_transfer_size,
2431                           read_pipe_completion, pipe_info);
2432         retval = usb_submit_urb(pipe_info->stream_urb, GFP_KERNEL);
2433         if (retval) {
2434                 printk(KERN_ERR "s2255: start read pipe failed\n");
2435                 return retval;
2436         }
2437         return 0;
2438 }
2439
2440 /* starts acquisition process */
2441 static int s2255_start_acquire(struct s2255_channel *channel)
2442 {
2443         unsigned char *buffer;
2444         int res;
2445         unsigned long chn_rev;
2446         int j;
2447         struct s2255_dev *dev = to_s2255_dev(channel->vdev.v4l2_dev);
2448         chn_rev = G_chnmap[channel->idx];
2449         buffer = kzalloc(512, GFP_KERNEL);
2450         if (buffer == NULL) {
2451                 dev_err(&dev->udev->dev, "out of mem\n");
2452                 return -ENOMEM;
2453         }
2454
2455         channel->last_frame = -1;
2456         channel->bad_payload = 0;
2457         channel->cur_frame = 0;
2458         for (j = 0; j < SYS_FRAMES; j++) {
2459                 channel->buffer.frame[j].ulState = 0;
2460                 channel->buffer.frame[j].cur_size = 0;
2461         }
2462
2463         /* send the start command */
2464         *(__le32 *) buffer = IN_DATA_TOKEN;
2465         *((__le32 *) buffer + 1) = (__le32) cpu_to_le32(chn_rev);
2466         *((__le32 *) buffer + 2) = CMD_START;
2467         res = s2255_write_config(dev->udev, (unsigned char *)buffer, 512);
2468         if (res != 0)
2469                 dev_err(&dev->udev->dev, "CMD_START error\n");
2470
2471         dprintk(2, "start acquire exit[%d] %d \n", channel->idx, res);
2472         kfree(buffer);
2473         return 0;
2474 }
2475
2476 static int s2255_stop_acquire(struct s2255_channel *channel)
2477 {
2478         unsigned char *buffer;
2479         int res;
2480         unsigned long chn_rev;
2481         struct s2255_dev *dev = to_s2255_dev(channel->vdev.v4l2_dev);
2482         chn_rev = G_chnmap[channel->idx];
2483         buffer = kzalloc(512, GFP_KERNEL);
2484         if (buffer == NULL) {
2485                 dev_err(&dev->udev->dev, "out of mem\n");
2486                 return -ENOMEM;
2487         }
2488         /* send the stop command */
2489         *(__le32 *) buffer = IN_DATA_TOKEN;
2490         *((__le32 *) buffer + 1) = (__le32) cpu_to_le32(chn_rev);
2491         *((__le32 *) buffer + 2) = CMD_STOP;
2492         res = s2255_write_config(dev->udev, (unsigned char *)buffer, 512);
2493         if (res != 0)
2494                 dev_err(&dev->udev->dev, "CMD_STOP error\n");
2495         kfree(buffer);
2496         channel->b_acquire = 0;
2497         dprintk(4, "%s: chn %d, res %d\n", __func__, channel->idx, res);
2498         return res;
2499 }
2500
2501 static void s2255_stop_readpipe(struct s2255_dev *dev)
2502 {
2503         struct s2255_pipeinfo *pipe = &dev->pipe;
2504
2505         pipe->state = 0;
2506         if (pipe->stream_urb) {
2507                 /* cancel urb */
2508                 usb_kill_urb(pipe->stream_urb);
2509                 usb_free_urb(pipe->stream_urb);
2510                 pipe->stream_urb = NULL;
2511         }
2512         dprintk(4, "%s", __func__);
2513         return;
2514 }
2515
2516 static void s2255_fwload_start(struct s2255_dev *dev, int reset)
2517 {
2518         if (reset)
2519                 s2255_reset_dsppower(dev);
2520         dev->fw_data->fw_size = dev->fw_data->fw->size;
2521         atomic_set(&dev->fw_data->fw_state, S2255_FW_NOTLOADED);
2522         memcpy(dev->fw_data->pfw_data,
2523                dev->fw_data->fw->data, CHUNK_SIZE);
2524         dev->fw_data->fw_loaded = CHUNK_SIZE;
2525         usb_fill_bulk_urb(dev->fw_data->fw_urb, dev->udev,
2526                           usb_sndbulkpipe(dev->udev, 2),
2527                           dev->fw_data->pfw_data,
2528                           CHUNK_SIZE, s2255_fwchunk_complete,
2529                           dev->fw_data);
2530         mod_timer(&dev->timer, jiffies + HZ);
2531 }
2532
2533 /* standard usb probe function */
2534 static int s2255_probe(struct usb_interface *interface,
2535                        const struct usb_device_id *id)
2536 {
2537         struct s2255_dev *dev = NULL;
2538         struct usb_host_interface *iface_desc;
2539         struct usb_endpoint_descriptor *endpoint;
2540         int i;
2541         int retval = -ENOMEM;
2542         __le32 *pdata;
2543         int fw_size;
2544         dprintk(2, "%s\n", __func__);
2545         /* allocate memory for our device state and initialize it to zero */
2546         dev = kzalloc(sizeof(struct s2255_dev), GFP_KERNEL);
2547         if (dev == NULL) {
2548                 s2255_dev_err(&interface->dev, "out of memory\n");
2549                 return -ENOMEM;
2550         }
2551         atomic_set(&dev->num_channels, 0);
2552         dev->pid = id->idProduct;
2553         dev->fw_data = kzalloc(sizeof(struct s2255_fw), GFP_KERNEL);
2554         if (!dev->fw_data)
2555                 goto errorFWDATA1;
2556         mutex_init(&dev->lock);
2557         mutex_init(&dev->open_lock);
2558         /* grab usb_device and save it */
2559         dev->udev = usb_get_dev(interface_to_usbdev(interface));
2560         if (dev->udev == NULL) {
2561                 dev_err(&interface->dev, "null usb device\n");
2562                 retval = -ENODEV;
2563                 goto errorUDEV;
2564         }
2565         dprintk(1, "dev: %p, udev %p interface %p\n", dev,
2566                 dev->udev, interface);
2567         dev->interface = interface;
2568         /* set up the endpoint information  */
2569         iface_desc = interface->cur_altsetting;
2570         dprintk(1, "num endpoints %d\n", iface_desc->desc.bNumEndpoints);
2571         for (i = 0; i < iface_desc->desc.bNumEndpoints; ++i) {
2572                 endpoint = &iface_desc->endpoint[i].desc;
2573                 if (!dev->read_endpoint && usb_endpoint_is_bulk_in(endpoint)) {
2574                         /* we found the bulk in endpoint */
2575                         dev->read_endpoint = endpoint->bEndpointAddress;
2576                 }
2577         }
2578
2579         if (!dev->read_endpoint) {
2580                 dev_err(&interface->dev, "Could not find bulk-in endpoint\n");
2581                 goto errorEP;
2582         }
2583         init_timer(&dev->timer);
2584         dev->timer.function = s2255_timer;
2585         dev->timer.data = (unsigned long)dev->fw_data;
2586         init_waitqueue_head(&dev->fw_data->wait_fw);
2587         for (i = 0; i < MAX_CHANNELS; i++) {
2588                 struct s2255_channel *channel = &dev->channel[i];
2589                 dev->channel[i].idx = i;
2590                 init_waitqueue_head(&channel->wait_setmode);
2591                 init_waitqueue_head(&channel->wait_vidstatus);
2592         }
2593
2594         dev->fw_data->fw_urb = usb_alloc_urb(0, GFP_KERNEL);
2595         if (!dev->fw_data->fw_urb) {
2596                 dev_err(&interface->dev, "out of memory!\n");
2597                 goto errorFWURB;
2598         }
2599
2600         dev->fw_data->pfw_data = kzalloc(CHUNK_SIZE, GFP_KERNEL);
2601         if (!dev->fw_data->pfw_data) {
2602                 dev_err(&interface->dev, "out of memory!\n");
2603                 goto errorFWDATA2;
2604         }
2605         /* load the first chunk */
2606         if (request_firmware(&dev->fw_data->fw,
2607                              FIRMWARE_FILE_NAME, &dev->udev->dev)) {
2608                 printk(KERN_ERR "sensoray 2255 failed to get firmware\n");
2609                 goto errorREQFW;
2610         }
2611         /* check the firmware is valid */
2612         fw_size = dev->fw_data->fw->size;
2613         pdata = (__le32 *) &dev->fw_data->fw->data[fw_size - 8];
2614
2615         if (*pdata != S2255_FW_MARKER) {
2616                 printk(KERN_INFO "Firmware invalid.\n");
2617                 retval = -ENODEV;
2618                 goto errorFWMARKER;
2619         } else {
2620                 /* make sure firmware is the latest */
2621                 __le32 *pRel;
2622                 pRel = (__le32 *) &dev->fw_data->fw->data[fw_size - 4];
2623                 printk(KERN_INFO "s2255 dsp fw version %x\n", *pRel);
2624                 dev->dsp_fw_ver = *pRel;
2625                 if (*pRel < S2255_CUR_DSP_FWVER)
2626                         printk(KERN_INFO "s2255: f2255usb.bin out of date.\n");
2627                 if (dev->pid == 0x2257 && *pRel < S2255_MIN_DSP_COLORFILTER)
2628                         printk(KERN_WARNING "s2255: 2257 requires firmware %d"
2629                                " or above.\n", S2255_MIN_DSP_COLORFILTER);
2630         }
2631         usb_reset_device(dev->udev);
2632         /* load 2255 board specific */
2633         retval = s2255_board_init(dev);
2634         if (retval)
2635                 goto errorBOARDINIT;
2636         spin_lock_init(&dev->slock);
2637         s2255_fwload_start(dev, 0);
2638         /* loads v4l specific */
2639         retval = s2255_probe_v4l(dev);
2640         if (retval)
2641                 goto errorBOARDINIT;
2642         dev_info(&interface->dev, "Sensoray 2255 detected\n");
2643         return 0;
2644 errorBOARDINIT:
2645         s2255_board_shutdown(dev);
2646 errorFWMARKER:
2647         release_firmware(dev->fw_data->fw);
2648 errorREQFW:
2649         kfree(dev->fw_data->pfw_data);
2650 errorFWDATA2:
2651         usb_free_urb(dev->fw_data->fw_urb);
2652 errorFWURB:
2653         del_timer(&dev->timer);
2654 errorEP:
2655         usb_put_dev(dev->udev);
2656 errorUDEV:
2657         kfree(dev->fw_data);
2658         mutex_destroy(&dev->open_lock);
2659         mutex_destroy(&dev->lock);
2660 errorFWDATA1:
2661         kfree(dev);
2662         printk(KERN_WARNING "Sensoray 2255 driver load failed: 0x%x\n", retval);
2663         return retval;
2664 }
2665
2666 /* disconnect routine. when board is removed physically or with rmmod */
2667 static void s2255_disconnect(struct usb_interface *interface)
2668 {
2669         struct s2255_dev *dev = to_s2255_dev(usb_get_intfdata(interface));
2670         int i;
2671         int channels = atomic_read(&dev->num_channels);
2672         mutex_lock(&dev->lock);
2673         v4l2_device_disconnect(&dev->v4l2_dev);
2674         mutex_unlock(&dev->lock);
2675         /*see comments in the uvc_driver.c usb disconnect function */
2676         atomic_inc(&dev->num_channels);
2677         /* unregister each video device. */
2678         for (i = 0; i < channels; i++)
2679                 video_unregister_device(&dev->channel[i].vdev);
2680         /* wake up any of our timers */
2681         atomic_set(&dev->fw_data->fw_state, S2255_FW_DISCONNECTING);
2682         wake_up(&dev->fw_data->wait_fw);
2683         for (i = 0; i < MAX_CHANNELS; i++) {
2684                 dev->channel[i].setmode_ready = 1;
2685                 wake_up(&dev->channel[i].wait_setmode);
2686                 dev->channel[i].vidstatus_ready = 1;
2687                 wake_up(&dev->channel[i].wait_vidstatus);
2688         }
2689         if (atomic_dec_and_test(&dev->num_channels))
2690                 s2255_destroy(dev);
2691         dev_info(&interface->dev, "%s\n", __func__);
2692 }
2693
2694 static struct usb_driver s2255_driver = {
2695         .name = S2255_DRIVER_NAME,
2696         .probe = s2255_probe,
2697         .disconnect = s2255_disconnect,
2698         .id_table = s2255_table,
2699 };
2700
2701 static int __init usb_s2255_init(void)
2702 {
2703         int result;
2704         /* register this driver with the USB subsystem */
2705         result = usb_register(&s2255_driver);
2706         if (result)
2707                 pr_err(KBUILD_MODNAME
2708                        ": usb_register failed. Error number %d\n", result);
2709         dprintk(2, "%s\n", __func__);
2710         return result;
2711 }
2712
2713 static void __exit usb_s2255_exit(void)
2714 {
2715         usb_deregister(&s2255_driver);
2716 }
2717
2718 module_init(usb_s2255_init);
2719 module_exit(usb_s2255_exit);
2720
2721 MODULE_DESCRIPTION("Sensoray 2255 Video for Linux driver");
2722 MODULE_AUTHOR("Dean Anderson (Sensoray Company Inc.)");
2723 MODULE_LICENSE("GPL");