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