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