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