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