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