Merge branch 'akpm' (Andrew's patch-bomb)
[firefly-linux-kernel-4.4.55.git] / drivers / media / video / cpia2 / cpia2_v4l.c
1 /****************************************************************************
2  *
3  *  Filename: cpia2_v4l.c
4  *
5  *  Copyright 2001, STMicrolectronics, Inc.
6  *      Contact:  steve.miller@st.com
7  *  Copyright 2001,2005, Scott J. Bertin <scottbertin@yahoo.com>
8  *
9  *  Description:
10  *     This is a USB driver for CPia2 based video cameras.
11  *     The infrastructure of this driver is based on the cpia usb driver by
12  *     Jochen Scharrlach and Johannes Erdfeldt.
13  *
14  *  This program is free software; you can redistribute it and/or modify
15  *  it under the terms of the GNU General Public License as published by
16  *  the Free Software Foundation; either version 2 of the License, or
17  *  (at your option) any later version.
18  *
19  *  This program is distributed in the hope that it will be useful,
20  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
21  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
22  *  GNU General Public License for more details.
23  *
24  *  You should have received a copy of the GNU General Public License
25  *  along with this program; if not, write to the Free Software
26  *  Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
27  *
28  *  Stripped of 2.4 stuff ready for main kernel submit by
29  *              Alan Cox <alan@lxorguk.ukuu.org.uk>
30  ****************************************************************************/
31
32 #define CPIA_VERSION "3.0.1"
33
34 #include <linux/module.h>
35 #include <linux/time.h>
36 #include <linux/sched.h>
37 #include <linux/slab.h>
38 #include <linux/init.h>
39 #include <linux/videodev2.h>
40 #include <linux/stringify.h>
41 #include <media/v4l2-ioctl.h>
42 #include <media/v4l2-event.h>
43
44 #include "cpia2.h"
45
46 static int video_nr = -1;
47 module_param(video_nr, int, 0);
48 MODULE_PARM_DESC(video_nr, "video device to register (0=/dev/video0, etc)");
49
50 static int buffer_size = 68 * 1024;
51 module_param(buffer_size, int, 0);
52 MODULE_PARM_DESC(buffer_size, "Size for each frame buffer in bytes (default 68k)");
53
54 static int num_buffers = 3;
55 module_param(num_buffers, int, 0);
56 MODULE_PARM_DESC(num_buffers, "Number of frame buffers (1-"
57                  __stringify(VIDEO_MAX_FRAME) ", default 3)");
58
59 static int alternate = DEFAULT_ALT;
60 module_param(alternate, int, 0);
61 MODULE_PARM_DESC(alternate, "USB Alternate (" __stringify(USBIF_ISO_1) "-"
62                  __stringify(USBIF_ISO_6) ", default "
63                  __stringify(DEFAULT_ALT) ")");
64
65 static int flicker_mode;
66 module_param(flicker_mode, int, 0);
67 MODULE_PARM_DESC(flicker_mode, "Flicker frequency (0 (disabled), " __stringify(50) " or "
68                  __stringify(60) ", default 0)");
69
70 MODULE_AUTHOR("Steve Miller (STMicroelectronics) <steve.miller@st.com>");
71 MODULE_DESCRIPTION("V4L-driver for STMicroelectronics CPiA2 based cameras");
72 MODULE_SUPPORTED_DEVICE("video");
73 MODULE_LICENSE("GPL");
74 MODULE_VERSION(CPIA_VERSION);
75
76 #define ABOUT "V4L-Driver for Vision CPiA2 based cameras"
77 #define CPIA2_CID_USB_ALT (V4L2_CID_USER_BASE | 0xf000)
78
79 /******************************************************************************
80  *
81  *  cpia2_open
82  *
83  *****************************************************************************/
84 static int cpia2_open(struct file *file)
85 {
86         struct camera_data *cam = video_drvdata(file);
87         int retval = v4l2_fh_open(file);
88
89         if (retval)
90                 return retval;
91
92         if (v4l2_fh_is_singular_file(file)) {
93                 if (cpia2_allocate_buffers(cam)) {
94                         v4l2_fh_release(file);
95                         return -ENOMEM;
96                 }
97
98                 /* reset the camera */
99                 if (cpia2_reset_camera(cam) < 0) {
100                         v4l2_fh_release(file);
101                         return -EIO;
102                 }
103
104                 cam->APP_len = 0;
105                 cam->COM_len = 0;
106         }
107
108         cpia2_dbg_dump_registers(cam);
109         return 0;
110 }
111
112 /******************************************************************************
113  *
114  *  cpia2_close
115  *
116  *****************************************************************************/
117 static int cpia2_close(struct file *file)
118 {
119         struct video_device *dev = video_devdata(file);
120         struct camera_data *cam = video_get_drvdata(dev);
121
122         if (video_is_registered(&cam->vdev) && v4l2_fh_is_singular_file(file)) {
123                 cpia2_usb_stream_stop(cam);
124
125                 /* save camera state for later open */
126                 cpia2_save_camera_state(cam);
127
128                 cpia2_set_low_power(cam);
129                 cpia2_free_buffers(cam);
130         }
131
132         if (cam->stream_fh == file->private_data) {
133                 cam->stream_fh = NULL;
134                 cam->mmapped = 0;
135         }
136         return v4l2_fh_release(file);
137 }
138
139 /******************************************************************************
140  *
141  *  cpia2_v4l_read
142  *
143  *****************************************************************************/
144 static ssize_t cpia2_v4l_read(struct file *file, char __user *buf, size_t count,
145                               loff_t *off)
146 {
147         struct camera_data *cam = video_drvdata(file);
148         int noblock = file->f_flags&O_NONBLOCK;
149
150         if(!cam)
151                 return -EINVAL;
152
153         return cpia2_read(cam, buf, count, noblock);
154 }
155
156
157 /******************************************************************************
158  *
159  *  cpia2_v4l_poll
160  *
161  *****************************************************************************/
162 static unsigned int cpia2_v4l_poll(struct file *filp, struct poll_table_struct *wait)
163 {
164         struct camera_data *cam = video_drvdata(filp);
165
166         return cpia2_poll(cam, filp, wait);
167 }
168
169
170 static int sync(struct camera_data *cam, int frame_nr)
171 {
172         struct framebuf *frame = &cam->buffers[frame_nr];
173
174         while (1) {
175                 if (frame->status == FRAME_READY)
176                         return 0;
177
178                 if (!cam->streaming) {
179                         frame->status = FRAME_READY;
180                         frame->length = 0;
181                         return 0;
182                 }
183
184                 mutex_unlock(&cam->v4l2_lock);
185                 wait_event_interruptible(cam->wq_stream,
186                                          !cam->streaming ||
187                                          frame->status == FRAME_READY);
188                 mutex_lock(&cam->v4l2_lock);
189                 if (signal_pending(current))
190                         return -ERESTARTSYS;
191                 if (!video_is_registered(&cam->vdev))
192                         return -ENOTTY;
193         }
194 }
195
196 /******************************************************************************
197  *
198  *  ioctl_querycap
199  *
200  *  V4L2 device capabilities
201  *
202  *****************************************************************************/
203
204 static int cpia2_querycap(struct file *file, void *fh, struct v4l2_capability *vc)
205 {
206         struct camera_data *cam = video_drvdata(file);
207
208         strcpy(vc->driver, "cpia2");
209
210         if (cam->params.pnp_id.product == 0x151)
211                 strcpy(vc->card, "QX5 Microscope");
212         else
213                 strcpy(vc->card, "CPiA2 Camera");
214         switch (cam->params.pnp_id.device_type) {
215         case DEVICE_STV_672:
216                 strcat(vc->card, " (672/");
217                 break;
218         case DEVICE_STV_676:
219                 strcat(vc->card, " (676/");
220                 break;
221         default:
222                 strcat(vc->card, " (XXX/");
223                 break;
224         }
225         switch (cam->params.version.sensor_flags) {
226         case CPIA2_VP_SENSOR_FLAGS_404:
227                 strcat(vc->card, "404)");
228                 break;
229         case CPIA2_VP_SENSOR_FLAGS_407:
230                 strcat(vc->card, "407)");
231                 break;
232         case CPIA2_VP_SENSOR_FLAGS_409:
233                 strcat(vc->card, "409)");
234                 break;
235         case CPIA2_VP_SENSOR_FLAGS_410:
236                 strcat(vc->card, "410)");
237                 break;
238         case CPIA2_VP_SENSOR_FLAGS_500:
239                 strcat(vc->card, "500)");
240                 break;
241         default:
242                 strcat(vc->card, "XXX)");
243                 break;
244         }
245
246         if (usb_make_path(cam->dev, vc->bus_info, sizeof(vc->bus_info)) <0)
247                 memset(vc->bus_info,0, sizeof(vc->bus_info));
248
249         vc->device_caps = V4L2_CAP_VIDEO_CAPTURE |
250                            V4L2_CAP_READWRITE |
251                            V4L2_CAP_STREAMING;
252         vc->capabilities = vc->device_caps |
253                            V4L2_CAP_DEVICE_CAPS;
254
255         return 0;
256 }
257
258 /******************************************************************************
259  *
260  *  ioctl_input
261  *
262  *  V4L2 input get/set/enumerate
263  *
264  *****************************************************************************/
265
266 static int cpia2_enum_input(struct file *file, void *fh, struct v4l2_input *i)
267 {
268         if (i->index)
269                 return -EINVAL;
270         strcpy(i->name, "Camera");
271         i->type = V4L2_INPUT_TYPE_CAMERA;
272         return 0;
273 }
274
275 static int cpia2_g_input(struct file *file, void *fh, unsigned int *i)
276 {
277         *i = 0;
278         return 0;
279 }
280
281 static int cpia2_s_input(struct file *file, void *fh, unsigned int i)
282 {
283         return i ? -EINVAL : 0;
284 }
285
286 /******************************************************************************
287  *
288  *  ioctl_enum_fmt
289  *
290  *  V4L2 format enumerate
291  *
292  *****************************************************************************/
293
294 static int cpia2_enum_fmt_vid_cap(struct file *file, void *fh,
295                                             struct v4l2_fmtdesc *f)
296 {
297         int index = f->index;
298
299         if (index < 0 || index > 1)
300                return -EINVAL;
301
302         memset(f, 0, sizeof(*f));
303         f->index = index;
304         f->type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
305         f->flags = V4L2_FMT_FLAG_COMPRESSED;
306         switch(index) {
307         case 0:
308                 strcpy(f->description, "MJPEG");
309                 f->pixelformat = V4L2_PIX_FMT_MJPEG;
310                 break;
311         case 1:
312                 strcpy(f->description, "JPEG");
313                 f->pixelformat = V4L2_PIX_FMT_JPEG;
314                 break;
315         default:
316                 return -EINVAL;
317         }
318
319         return 0;
320 }
321
322 /******************************************************************************
323  *
324  *  ioctl_try_fmt
325  *
326  *  V4L2 format try
327  *
328  *****************************************************************************/
329
330 static int cpia2_try_fmt_vid_cap(struct file *file, void *fh,
331                                           struct v4l2_format *f)
332 {
333         struct camera_data *cam = video_drvdata(file);
334
335         if (f->fmt.pix.pixelformat != V4L2_PIX_FMT_MJPEG &&
336             f->fmt.pix.pixelformat != V4L2_PIX_FMT_JPEG)
337                return -EINVAL;
338
339         f->fmt.pix.field = V4L2_FIELD_NONE;
340         f->fmt.pix.bytesperline = 0;
341         f->fmt.pix.sizeimage = cam->frame_size;
342         f->fmt.pix.colorspace = V4L2_COLORSPACE_JPEG;
343         f->fmt.pix.priv = 0;
344
345         switch (cpia2_match_video_size(f->fmt.pix.width, f->fmt.pix.height)) {
346         case VIDEOSIZE_VGA:
347                 f->fmt.pix.width = 640;
348                 f->fmt.pix.height = 480;
349                 break;
350         case VIDEOSIZE_CIF:
351                 f->fmt.pix.width = 352;
352                 f->fmt.pix.height = 288;
353                 break;
354         case VIDEOSIZE_QVGA:
355                 f->fmt.pix.width = 320;
356                 f->fmt.pix.height = 240;
357                 break;
358         case VIDEOSIZE_288_216:
359                 f->fmt.pix.width = 288;
360                 f->fmt.pix.height = 216;
361                 break;
362         case VIDEOSIZE_256_192:
363                 f->fmt.pix.width = 256;
364                 f->fmt.pix.height = 192;
365                 break;
366         case VIDEOSIZE_224_168:
367                 f->fmt.pix.width = 224;
368                 f->fmt.pix.height = 168;
369                 break;
370         case VIDEOSIZE_192_144:
371                 f->fmt.pix.width = 192;
372                 f->fmt.pix.height = 144;
373                 break;
374         case VIDEOSIZE_QCIF:
375         default:
376                 f->fmt.pix.width = 176;
377                 f->fmt.pix.height = 144;
378                 break;
379         }
380
381         return 0;
382 }
383
384 /******************************************************************************
385  *
386  *  ioctl_set_fmt
387  *
388  *  V4L2 format set
389  *
390  *****************************************************************************/
391
392 static int cpia2_s_fmt_vid_cap(struct file *file, void *_fh,
393                                         struct v4l2_format *f)
394 {
395         struct camera_data *cam = video_drvdata(file);
396         int err, frame;
397
398         err = cpia2_try_fmt_vid_cap(file, _fh, f);
399         if(err != 0)
400                 return err;
401
402         cam->pixelformat = f->fmt.pix.pixelformat;
403
404         /* NOTE: This should be set to 1 for MJPEG, but some apps don't handle
405          * the missing Huffman table properly. */
406         cam->params.compression.inhibit_htables = 0;
407                 /*f->fmt.pix.pixelformat == V4L2_PIX_FMT_MJPEG;*/
408
409         /* we set the video window to something smaller or equal to what
410          * is requested by the user???
411          */
412         DBG("Requested width = %d, height = %d\n",
413             f->fmt.pix.width, f->fmt.pix.height);
414         if (f->fmt.pix.width != cam->width ||
415             f->fmt.pix.height != cam->height) {
416                 cam->width = f->fmt.pix.width;
417                 cam->height = f->fmt.pix.height;
418                 cam->params.roi.width = f->fmt.pix.width;
419                 cam->params.roi.height = f->fmt.pix.height;
420                 cpia2_set_format(cam);
421         }
422
423         for (frame = 0; frame < cam->num_frames; ++frame) {
424                 if (cam->buffers[frame].status == FRAME_READING)
425                         if ((err = sync(cam, frame)) < 0)
426                                 return err;
427
428                 cam->buffers[frame].status = FRAME_EMPTY;
429         }
430
431         return 0;
432 }
433
434 /******************************************************************************
435  *
436  *  ioctl_get_fmt
437  *
438  *  V4L2 format get
439  *
440  *****************************************************************************/
441
442 static int cpia2_g_fmt_vid_cap(struct file *file, void *fh,
443                                         struct v4l2_format *f)
444 {
445         struct camera_data *cam = video_drvdata(file);
446
447         f->fmt.pix.width = cam->width;
448         f->fmt.pix.height = cam->height;
449         f->fmt.pix.pixelformat = cam->pixelformat;
450         f->fmt.pix.field = V4L2_FIELD_NONE;
451         f->fmt.pix.bytesperline = 0;
452         f->fmt.pix.sizeimage = cam->frame_size;
453         f->fmt.pix.colorspace = V4L2_COLORSPACE_JPEG;
454         f->fmt.pix.priv = 0;
455
456         return 0;
457 }
458
459 /******************************************************************************
460  *
461  *  ioctl_cropcap
462  *
463  *  V4L2 query cropping capabilities
464  *  NOTE: cropping is currently disabled
465  *
466  *****************************************************************************/
467
468 static int cpia2_cropcap(struct file *file, void *fh, struct v4l2_cropcap *c)
469 {
470         struct camera_data *cam = video_drvdata(file);
471
472         if (c->type != V4L2_BUF_TYPE_VIDEO_CAPTURE)
473                return -EINVAL;
474
475         c->bounds.left = 0;
476         c->bounds.top = 0;
477         c->bounds.width = cam->width;
478         c->bounds.height = cam->height;
479         c->defrect.left = 0;
480         c->defrect.top = 0;
481         c->defrect.width = cam->width;
482         c->defrect.height = cam->height;
483         c->pixelaspect.numerator = 1;
484         c->pixelaspect.denominator = 1;
485
486         return 0;
487 }
488
489 struct framerate_info {
490         int value;
491         struct v4l2_fract period;
492 };
493
494 static const struct framerate_info framerate_controls[] = {
495         { CPIA2_VP_FRAMERATE_6_25, { 4, 25 } },
496         { CPIA2_VP_FRAMERATE_7_5,  { 2, 15 } },
497         { CPIA2_VP_FRAMERATE_12_5, { 2, 25 } },
498         { CPIA2_VP_FRAMERATE_15,   { 1, 15 } },
499         { CPIA2_VP_FRAMERATE_25,   { 1, 25 } },
500         { CPIA2_VP_FRAMERATE_30,   { 1, 30 } },
501 };
502
503 static int cpia2_g_parm(struct file *file, void *fh, struct v4l2_streamparm *p)
504 {
505         struct camera_data *cam = video_drvdata(file);
506         struct v4l2_captureparm *cap = &p->parm.capture;
507         int i;
508
509         if (p->type != V4L2_BUF_TYPE_VIDEO_CAPTURE)
510                 return -EINVAL;
511
512         cap->capability = V4L2_CAP_TIMEPERFRAME;
513         cap->readbuffers = cam->num_frames;
514         for (i = 0; i < ARRAY_SIZE(framerate_controls); i++)
515                 if (cam->params.vp_params.frame_rate == framerate_controls[i].value) {
516                         cap->timeperframe = framerate_controls[i].period;
517                         break;
518                 }
519         return 0;
520 }
521
522 static int cpia2_s_parm(struct file *file, void *fh, struct v4l2_streamparm *p)
523 {
524         struct camera_data *cam = video_drvdata(file);
525         struct v4l2_captureparm *cap = &p->parm.capture;
526         struct v4l2_fract tpf = cap->timeperframe;
527         int max = ARRAY_SIZE(framerate_controls) - 1;
528         int ret;
529         int i;
530
531         ret = cpia2_g_parm(file, fh, p);
532         if (ret || !tpf.denominator || !tpf.numerator)
533                 return ret;
534
535         /* Maximum 15 fps for this model */
536         if (cam->params.pnp_id.device_type == DEVICE_STV_672 &&
537             cam->params.version.sensor_flags == CPIA2_VP_SENSOR_FLAGS_500)
538                 max -= 2;
539         for (i = 0; i <= max; i++) {
540                 struct v4l2_fract f1 = tpf;
541                 struct v4l2_fract f2 = framerate_controls[i].period;
542
543                 f1.numerator *= f2.denominator;
544                 f2.numerator *= f1.denominator;
545                 if (f1.numerator >= f2.numerator)
546                         break;
547         }
548         if (i > max)
549                 i = max;
550         cap->timeperframe = framerate_controls[i].period;
551         return cpia2_set_fps(cam, framerate_controls[i].value);
552 }
553
554 static const struct {
555         u32 width;
556         u32 height;
557 } cpia2_framesizes[] = {
558         { 640, 480 },
559         { 352, 288 },
560         { 320, 240 },
561         { 288, 216 },
562         { 256, 192 },
563         { 224, 168 },
564         { 192, 144 },
565         { 176, 144 },
566 };
567
568 static int cpia2_enum_framesizes(struct file *file, void *fh,
569                                          struct v4l2_frmsizeenum *fsize)
570 {
571
572         if (fsize->pixel_format != V4L2_PIX_FMT_MJPEG &&
573             fsize->pixel_format != V4L2_PIX_FMT_JPEG)
574                 return -EINVAL;
575         if (fsize->index >= ARRAY_SIZE(cpia2_framesizes))
576                 return -EINVAL;
577         fsize->type = V4L2_FRMSIZE_TYPE_DISCRETE;
578         fsize->discrete.width = cpia2_framesizes[fsize->index].width;
579         fsize->discrete.height = cpia2_framesizes[fsize->index].height;
580
581         return 0;
582 }
583
584 static int cpia2_enum_frameintervals(struct file *file, void *fh,
585                                            struct v4l2_frmivalenum *fival)
586 {
587         struct camera_data *cam = video_drvdata(file);
588         int max = ARRAY_SIZE(framerate_controls) - 1;
589         int i;
590
591         if (fival->pixel_format != V4L2_PIX_FMT_MJPEG &&
592             fival->pixel_format != V4L2_PIX_FMT_JPEG)
593                 return -EINVAL;
594
595         /* Maximum 15 fps for this model */
596         if (cam->params.pnp_id.device_type == DEVICE_STV_672 &&
597             cam->params.version.sensor_flags == CPIA2_VP_SENSOR_FLAGS_500)
598                 max -= 2;
599         if (fival->index > max)
600                 return -EINVAL;
601         for (i = 0; i < ARRAY_SIZE(cpia2_framesizes); i++)
602                 if (fival->width == cpia2_framesizes[i].width &&
603                     fival->height == cpia2_framesizes[i].height)
604                         break;
605         if (i == ARRAY_SIZE(cpia2_framesizes))
606                 return -EINVAL;
607         fival->type = V4L2_FRMIVAL_TYPE_DISCRETE;
608         fival->discrete = framerate_controls[fival->index].period;
609         return 0;
610 }
611
612 /******************************************************************************
613  *
614  *  ioctl_s_ctrl
615  *
616  *  V4L2 set the value of a control variable
617  *
618  *****************************************************************************/
619
620 static int cpia2_s_ctrl(struct v4l2_ctrl *ctrl)
621 {
622         struct camera_data *cam =
623                 container_of(ctrl->handler, struct camera_data, hdl);
624         static const int flicker_table[] = {
625                 NEVER_FLICKER,
626                 FLICKER_50,
627                 FLICKER_60,
628         };
629
630         DBG("Set control id:%d, value:%d\n", ctrl->id, ctrl->val);
631
632         switch (ctrl->id) {
633         case V4L2_CID_BRIGHTNESS:
634                 cpia2_set_brightness(cam, ctrl->val);
635                 break;
636         case V4L2_CID_CONTRAST:
637                 cpia2_set_contrast(cam, ctrl->val);
638                 break;
639         case V4L2_CID_SATURATION:
640                 cpia2_set_saturation(cam, ctrl->val);
641                 break;
642         case V4L2_CID_HFLIP:
643                 cpia2_set_property_mirror(cam, ctrl->val);
644                 break;
645         case V4L2_CID_VFLIP:
646                 cpia2_set_property_flip(cam, ctrl->val);
647                 break;
648         case V4L2_CID_POWER_LINE_FREQUENCY:
649                 return cpia2_set_flicker_mode(cam, flicker_table[ctrl->val]);
650         case V4L2_CID_ILLUMINATORS_1:
651                 return cpia2_set_gpio(cam, (cam->top_light->val << 6) |
652                                            (cam->bottom_light->val << 7));
653         case V4L2_CID_JPEG_ACTIVE_MARKER:
654                 cam->params.compression.inhibit_htables =
655                         !(ctrl->val & V4L2_JPEG_ACTIVE_MARKER_DHT);
656                 break;
657         case V4L2_CID_JPEG_COMPRESSION_QUALITY:
658                 cam->params.vc_params.quality = ctrl->val;
659                 break;
660         case CPIA2_CID_USB_ALT:
661                 cam->params.camera_state.stream_mode = ctrl->val;
662                 break;
663         default:
664                 return -EINVAL;
665         }
666
667         return 0;
668 }
669
670 /******************************************************************************
671  *
672  *  ioctl_g_jpegcomp
673  *
674  *  V4L2 get the JPEG compression parameters
675  *
676  *****************************************************************************/
677
678 static int cpia2_g_jpegcomp(struct file *file, void *fh, struct v4l2_jpegcompression *parms)
679 {
680         struct camera_data *cam = video_drvdata(file);
681
682         memset(parms, 0, sizeof(*parms));
683
684         parms->quality = 80; // TODO: Can this be made meaningful?
685
686         parms->jpeg_markers = V4L2_JPEG_MARKER_DQT | V4L2_JPEG_MARKER_DRI;
687         if(!cam->params.compression.inhibit_htables) {
688                 parms->jpeg_markers |= V4L2_JPEG_MARKER_DHT;
689         }
690
691         parms->APPn = cam->APPn;
692         parms->APP_len = cam->APP_len;
693         if(cam->APP_len > 0) {
694                 memcpy(parms->APP_data, cam->APP_data, cam->APP_len);
695                 parms->jpeg_markers |= V4L2_JPEG_MARKER_APP;
696         }
697
698         parms->COM_len = cam->COM_len;
699         if(cam->COM_len > 0) {
700                 memcpy(parms->COM_data, cam->COM_data, cam->COM_len);
701                 parms->jpeg_markers |= JPEG_MARKER_COM;
702         }
703
704         DBG("G_JPEGCOMP APP_len:%d COM_len:%d\n",
705             parms->APP_len, parms->COM_len);
706
707         return 0;
708 }
709
710 /******************************************************************************
711  *
712  *  ioctl_s_jpegcomp
713  *
714  *  V4L2 set the JPEG compression parameters
715  *  NOTE: quality and some jpeg_markers are ignored.
716  *
717  *****************************************************************************/
718
719 static int cpia2_s_jpegcomp(struct file *file, void *fh, struct v4l2_jpegcompression *parms)
720 {
721         struct camera_data *cam = video_drvdata(file);
722
723         DBG("S_JPEGCOMP APP_len:%d COM_len:%d\n",
724             parms->APP_len, parms->COM_len);
725
726         cam->params.compression.inhibit_htables =
727                 !(parms->jpeg_markers & V4L2_JPEG_MARKER_DHT);
728         parms->jpeg_markers &= V4L2_JPEG_MARKER_DQT | V4L2_JPEG_MARKER_DRI |
729                                V4L2_JPEG_MARKER_DHT;
730
731         if(parms->APP_len != 0) {
732                 if(parms->APP_len > 0 &&
733                    parms->APP_len <= sizeof(cam->APP_data) &&
734                    parms->APPn >= 0 && parms->APPn <= 15) {
735                         cam->APPn = parms->APPn;
736                         cam->APP_len = parms->APP_len;
737                         memcpy(cam->APP_data, parms->APP_data, parms->APP_len);
738                 } else {
739                         LOG("Bad APPn Params n=%d len=%d\n",
740                             parms->APPn, parms->APP_len);
741                         return -EINVAL;
742                 }
743         } else {
744                 cam->APP_len = 0;
745         }
746
747         if(parms->COM_len != 0) {
748                 if(parms->COM_len > 0 &&
749                    parms->COM_len <= sizeof(cam->COM_data)) {
750                         cam->COM_len = parms->COM_len;
751                         memcpy(cam->COM_data, parms->COM_data, parms->COM_len);
752                 } else {
753                         LOG("Bad COM_len=%d\n", parms->COM_len);
754                         return -EINVAL;
755                 }
756         }
757
758         return 0;
759 }
760
761 /******************************************************************************
762  *
763  *  ioctl_reqbufs
764  *
765  *  V4L2 Initiate memory mapping.
766  *  NOTE: The user's request is ignored. For now the buffers are fixed.
767  *
768  *****************************************************************************/
769
770 static int cpia2_reqbufs(struct file *file, void *fh, struct v4l2_requestbuffers *req)
771 {
772         struct camera_data *cam = video_drvdata(file);
773
774         if(req->type != V4L2_BUF_TYPE_VIDEO_CAPTURE ||
775            req->memory != V4L2_MEMORY_MMAP)
776                 return -EINVAL;
777
778         DBG("REQBUFS requested:%d returning:%d\n", req->count, cam->num_frames);
779         req->count = cam->num_frames;
780         memset(&req->reserved, 0, sizeof(req->reserved));
781
782         return 0;
783 }
784
785 /******************************************************************************
786  *
787  *  ioctl_querybuf
788  *
789  *  V4L2 Query memory buffer status.
790  *
791  *****************************************************************************/
792
793 static int cpia2_querybuf(struct file *file, void *fh, struct v4l2_buffer *buf)
794 {
795         struct camera_data *cam = video_drvdata(file);
796
797         if(buf->type != V4L2_BUF_TYPE_VIDEO_CAPTURE ||
798            buf->index > cam->num_frames)
799                 return -EINVAL;
800
801         buf->m.offset = cam->buffers[buf->index].data - cam->frame_buffer;
802         buf->length = cam->frame_size;
803
804         buf->memory = V4L2_MEMORY_MMAP;
805
806         if(cam->mmapped)
807                 buf->flags = V4L2_BUF_FLAG_MAPPED;
808         else
809                 buf->flags = 0;
810
811         switch (cam->buffers[buf->index].status) {
812         case FRAME_EMPTY:
813         case FRAME_ERROR:
814         case FRAME_READING:
815                 buf->bytesused = 0;
816                 buf->flags = V4L2_BUF_FLAG_QUEUED;
817                 break;
818         case FRAME_READY:
819                 buf->bytesused = cam->buffers[buf->index].length;
820                 buf->timestamp = cam->buffers[buf->index].timestamp;
821                 buf->sequence = cam->buffers[buf->index].seq;
822                 buf->flags = V4L2_BUF_FLAG_DONE;
823                 break;
824         }
825
826         DBG("QUERYBUF index:%d offset:%d flags:%d seq:%d bytesused:%d\n",
827              buf->index, buf->m.offset, buf->flags, buf->sequence,
828              buf->bytesused);
829
830         return 0;
831 }
832
833 /******************************************************************************
834  *
835  *  ioctl_qbuf
836  *
837  *  V4L2 User is freeing buffer
838  *
839  *****************************************************************************/
840
841 static int cpia2_qbuf(struct file *file, void *fh, struct v4l2_buffer *buf)
842 {
843         struct camera_data *cam = video_drvdata(file);
844
845         if(buf->type != V4L2_BUF_TYPE_VIDEO_CAPTURE ||
846            buf->memory != V4L2_MEMORY_MMAP ||
847            buf->index > cam->num_frames)
848                 return -EINVAL;
849
850         DBG("QBUF #%d\n", buf->index);
851
852         if(cam->buffers[buf->index].status == FRAME_READY)
853                 cam->buffers[buf->index].status = FRAME_EMPTY;
854
855         return 0;
856 }
857
858 /******************************************************************************
859  *
860  *  find_earliest_filled_buffer
861  *
862  *  Helper for ioctl_dqbuf. Find the next ready buffer.
863  *
864  *****************************************************************************/
865
866 static int find_earliest_filled_buffer(struct camera_data *cam)
867 {
868         int i;
869         int found = -1;
870         for (i=0; i<cam->num_frames; i++) {
871                 if(cam->buffers[i].status == FRAME_READY) {
872                         if(found < 0) {
873                                 found = i;
874                         } else {
875                                 /* find which buffer is earlier */
876                                 struct timeval *tv1, *tv2;
877                                 tv1 = &cam->buffers[i].timestamp;
878                                 tv2 = &cam->buffers[found].timestamp;
879                                 if(tv1->tv_sec < tv2->tv_sec ||
880                                    (tv1->tv_sec == tv2->tv_sec &&
881                                     tv1->tv_usec < tv2->tv_usec))
882                                         found = i;
883                         }
884                 }
885         }
886         return found;
887 }
888
889 /******************************************************************************
890  *
891  *  ioctl_dqbuf
892  *
893  *  V4L2 User is asking for a filled buffer.
894  *
895  *****************************************************************************/
896
897 static int cpia2_dqbuf(struct file *file, void *fh, struct v4l2_buffer *buf)
898 {
899         struct camera_data *cam = video_drvdata(file);
900         int frame;
901
902         if(buf->type != V4L2_BUF_TYPE_VIDEO_CAPTURE ||
903            buf->memory != V4L2_MEMORY_MMAP)
904                 return -EINVAL;
905
906         frame = find_earliest_filled_buffer(cam);
907
908         if(frame < 0 && file->f_flags&O_NONBLOCK)
909                 return -EAGAIN;
910
911         if(frame < 0) {
912                 /* Wait for a frame to become available */
913                 struct framebuf *cb=cam->curbuff;
914                 mutex_unlock(&cam->v4l2_lock);
915                 wait_event_interruptible(cam->wq_stream,
916                                          !video_is_registered(&cam->vdev) ||
917                                          (cb=cam->curbuff)->status == FRAME_READY);
918                 mutex_lock(&cam->v4l2_lock);
919                 if (signal_pending(current))
920                         return -ERESTARTSYS;
921                 if (!video_is_registered(&cam->vdev))
922                         return -ENOTTY;
923                 frame = cb->num;
924         }
925
926
927         buf->index = frame;
928         buf->bytesused = cam->buffers[buf->index].length;
929         buf->flags = V4L2_BUF_FLAG_MAPPED | V4L2_BUF_FLAG_DONE;
930         buf->field = V4L2_FIELD_NONE;
931         buf->timestamp = cam->buffers[buf->index].timestamp;
932         buf->sequence = cam->buffers[buf->index].seq;
933         buf->m.offset = cam->buffers[buf->index].data - cam->frame_buffer;
934         buf->length = cam->frame_size;
935         buf->input = 0;
936         buf->reserved = 0;
937         memset(&buf->timecode, 0, sizeof(buf->timecode));
938
939         DBG("DQBUF #%d status:%d seq:%d length:%d\n", buf->index,
940             cam->buffers[buf->index].status, buf->sequence, buf->bytesused);
941
942         return 0;
943 }
944
945 static int cpia2_streamon(struct file *file, void *fh, enum v4l2_buf_type type)
946 {
947         struct camera_data *cam = video_drvdata(file);
948         int ret = -EINVAL;
949
950         DBG("VIDIOC_STREAMON, streaming=%d\n", cam->streaming);
951         if (!cam->mmapped || type != V4L2_BUF_TYPE_VIDEO_CAPTURE)
952                 return -EINVAL;
953
954         if (!cam->streaming) {
955                 ret = cpia2_usb_stream_start(cam,
956                                 cam->params.camera_state.stream_mode);
957                 if (!ret)
958                         v4l2_ctrl_grab(cam->usb_alt, true);
959         }
960         return ret;
961 }
962
963 static int cpia2_streamoff(struct file *file, void *fh, enum v4l2_buf_type type)
964 {
965         struct camera_data *cam = video_drvdata(file);
966         int ret = -EINVAL;
967
968         DBG("VIDIOC_STREAMOFF, streaming=%d\n", cam->streaming);
969         if (!cam->mmapped || type != V4L2_BUF_TYPE_VIDEO_CAPTURE)
970                 return -EINVAL;
971
972         if (cam->streaming) {
973                 ret = cpia2_usb_stream_stop(cam);
974                 if (!ret)
975                         v4l2_ctrl_grab(cam->usb_alt, false);
976         }
977         return ret;
978 }
979
980 /******************************************************************************
981  *
982  *  cpia2_mmap
983  *
984  *****************************************************************************/
985 static int cpia2_mmap(struct file *file, struct vm_area_struct *area)
986 {
987         struct camera_data *cam = video_drvdata(file);
988         int retval;
989
990         retval = cpia2_remap_buffer(cam, area);
991
992         if(!retval)
993                 cam->stream_fh = file->private_data;
994         return retval;
995 }
996
997 /******************************************************************************
998  *
999  *  reset_camera_struct_v4l
1000  *
1001  *  Sets all values to the defaults
1002  *****************************************************************************/
1003 static void reset_camera_struct_v4l(struct camera_data *cam)
1004 {
1005         cam->width = cam->params.roi.width;
1006         cam->height = cam->params.roi.height;
1007
1008         cam->frame_size = buffer_size;
1009         cam->num_frames = num_buffers;
1010
1011         /* Flicker modes */
1012         cam->params.flicker_control.flicker_mode_req = flicker_mode;
1013
1014         /* stream modes */
1015         cam->params.camera_state.stream_mode = alternate;
1016
1017         cam->pixelformat = V4L2_PIX_FMT_JPEG;
1018 }
1019
1020 static const struct v4l2_ioctl_ops cpia2_ioctl_ops = {
1021         .vidioc_querycap                    = cpia2_querycap,
1022         .vidioc_enum_input                  = cpia2_enum_input,
1023         .vidioc_g_input                     = cpia2_g_input,
1024         .vidioc_s_input                     = cpia2_s_input,
1025         .vidioc_enum_fmt_vid_cap            = cpia2_enum_fmt_vid_cap,
1026         .vidioc_g_fmt_vid_cap               = cpia2_g_fmt_vid_cap,
1027         .vidioc_s_fmt_vid_cap               = cpia2_s_fmt_vid_cap,
1028         .vidioc_try_fmt_vid_cap             = cpia2_try_fmt_vid_cap,
1029         .vidioc_g_jpegcomp                  = cpia2_g_jpegcomp,
1030         .vidioc_s_jpegcomp                  = cpia2_s_jpegcomp,
1031         .vidioc_cropcap                     = cpia2_cropcap,
1032         .vidioc_reqbufs                     = cpia2_reqbufs,
1033         .vidioc_querybuf                    = cpia2_querybuf,
1034         .vidioc_qbuf                        = cpia2_qbuf,
1035         .vidioc_dqbuf                       = cpia2_dqbuf,
1036         .vidioc_streamon                    = cpia2_streamon,
1037         .vidioc_streamoff                   = cpia2_streamoff,
1038         .vidioc_s_parm                      = cpia2_s_parm,
1039         .vidioc_g_parm                      = cpia2_g_parm,
1040         .vidioc_enum_framesizes             = cpia2_enum_framesizes,
1041         .vidioc_enum_frameintervals         = cpia2_enum_frameintervals,
1042         .vidioc_subscribe_event             = v4l2_ctrl_subscribe_event,
1043         .vidioc_unsubscribe_event           = v4l2_event_unsubscribe,
1044 };
1045
1046 /***
1047  * The v4l video device structure initialized for this device
1048  ***/
1049 static const struct v4l2_file_operations cpia2_fops = {
1050         .owner          = THIS_MODULE,
1051         .open           = cpia2_open,
1052         .release        = cpia2_close,
1053         .read           = cpia2_v4l_read,
1054         .poll           = cpia2_v4l_poll,
1055         .unlocked_ioctl = video_ioctl2,
1056         .mmap           = cpia2_mmap,
1057 };
1058
1059 static struct video_device cpia2_template = {
1060         /* I could not find any place for the old .initialize initializer?? */
1061         .name =         "CPiA2 Camera",
1062         .fops =         &cpia2_fops,
1063         .ioctl_ops =    &cpia2_ioctl_ops,
1064         .release =      video_device_release_empty,
1065 };
1066
1067 void cpia2_camera_release(struct v4l2_device *v4l2_dev)
1068 {
1069         struct camera_data *cam =
1070                 container_of(v4l2_dev, struct camera_data, v4l2_dev);
1071
1072         v4l2_ctrl_handler_free(&cam->hdl);
1073         v4l2_device_unregister(&cam->v4l2_dev);
1074         kfree(cam);
1075 }
1076
1077 static const struct v4l2_ctrl_ops cpia2_ctrl_ops = {
1078         .s_ctrl = cpia2_s_ctrl,
1079 };
1080
1081 /******************************************************************************
1082  *
1083  *  cpia2_register_camera
1084  *
1085  *****************************************************************************/
1086 int cpia2_register_camera(struct camera_data *cam)
1087 {
1088         struct v4l2_ctrl_handler *hdl = &cam->hdl;
1089         struct v4l2_ctrl_config cpia2_usb_alt = {
1090                 .ops = &cpia2_ctrl_ops,
1091                 .id = CPIA2_CID_USB_ALT,
1092                 .name = "USB Alternate",
1093                 .type = V4L2_CTRL_TYPE_INTEGER,
1094                 .min = USBIF_ISO_1,
1095                 .max = USBIF_ISO_6,
1096                 .step = 1,
1097         };
1098         int ret;
1099
1100         v4l2_ctrl_handler_init(hdl, 12);
1101         v4l2_ctrl_new_std(hdl, &cpia2_ctrl_ops,
1102                         V4L2_CID_BRIGHTNESS,
1103                         cam->params.pnp_id.device_type == DEVICE_STV_672 ? 1 : 0,
1104                         255, 1, DEFAULT_BRIGHTNESS);
1105         v4l2_ctrl_new_std(hdl, &cpia2_ctrl_ops,
1106                         V4L2_CID_CONTRAST, 0, 255, 1, DEFAULT_CONTRAST);
1107         v4l2_ctrl_new_std(hdl, &cpia2_ctrl_ops,
1108                         V4L2_CID_SATURATION, 0, 255, 1, DEFAULT_SATURATION);
1109         v4l2_ctrl_new_std(hdl, &cpia2_ctrl_ops,
1110                         V4L2_CID_HFLIP, 0, 1, 1, 0);
1111         v4l2_ctrl_new_std(hdl, &cpia2_ctrl_ops,
1112                         V4L2_CID_JPEG_ACTIVE_MARKER, 0,
1113                         V4L2_JPEG_ACTIVE_MARKER_DHT, 0,
1114                         V4L2_JPEG_ACTIVE_MARKER_DHT);
1115         v4l2_ctrl_new_std(hdl, &cpia2_ctrl_ops,
1116                         V4L2_CID_JPEG_COMPRESSION_QUALITY, 1,
1117                         100, 1, 100);
1118         cpia2_usb_alt.def = alternate;
1119         cam->usb_alt = v4l2_ctrl_new_custom(hdl, &cpia2_usb_alt, NULL);
1120         /* VP5 Only */
1121         if (cam->params.pnp_id.device_type != DEVICE_STV_672)
1122                 v4l2_ctrl_new_std(hdl, &cpia2_ctrl_ops,
1123                         V4L2_CID_VFLIP, 0, 1, 1, 0);
1124         /* Flicker control only valid for 672 */
1125         if (cam->params.pnp_id.device_type == DEVICE_STV_672)
1126                 v4l2_ctrl_new_std_menu(hdl, &cpia2_ctrl_ops,
1127                         V4L2_CID_POWER_LINE_FREQUENCY,
1128                         V4L2_CID_POWER_LINE_FREQUENCY_60HZ, 0, 0);
1129         /* Light control only valid for the QX5 Microscope */
1130         if (cam->params.pnp_id.product == 0x151) {
1131                 cam->top_light = v4l2_ctrl_new_std(hdl, &cpia2_ctrl_ops,
1132                                 V4L2_CID_ILLUMINATORS_1, 0, 1, 1, 0);
1133                 cam->bottom_light = v4l2_ctrl_new_std(hdl, &cpia2_ctrl_ops,
1134                                 V4L2_CID_ILLUMINATORS_2, 0, 1, 1, 0);
1135                 v4l2_ctrl_cluster(2, &cam->top_light);
1136         }
1137
1138         if (hdl->error) {
1139                 ret = hdl->error;
1140                 v4l2_ctrl_handler_free(hdl);
1141                 return ret;
1142         }
1143
1144         cam->vdev = cpia2_template;
1145         video_set_drvdata(&cam->vdev, cam);
1146         cam->vdev.lock = &cam->v4l2_lock;
1147         cam->vdev.ctrl_handler = hdl;
1148         cam->vdev.v4l2_dev = &cam->v4l2_dev;
1149         set_bit(V4L2_FL_USE_FH_PRIO, &cam->vdev.flags);
1150         /* Locking in file operations other than ioctl should be done
1151            by the driver, not the V4L2 core.
1152            This driver needs auditing so that this flag can be removed. */
1153         set_bit(V4L2_FL_LOCK_ALL_FOPS, &cam->vdev.flags);
1154
1155         reset_camera_struct_v4l(cam);
1156
1157         /* register v4l device */
1158         if (video_register_device(&cam->vdev, VFL_TYPE_GRABBER, video_nr) < 0) {
1159                 ERR("video_register_device failed\n");
1160                 return -ENODEV;
1161         }
1162
1163         return 0;
1164 }
1165
1166 /******************************************************************************
1167  *
1168  *  cpia2_unregister_camera
1169  *
1170  *****************************************************************************/
1171 void cpia2_unregister_camera(struct camera_data *cam)
1172 {
1173         video_unregister_device(&cam->vdev);
1174 }
1175
1176 /******************************************************************************
1177  *
1178  *  check_parameters
1179  *
1180  *  Make sure that all user-supplied parameters are sensible
1181  *****************************************************************************/
1182 static void __init check_parameters(void)
1183 {
1184         if(buffer_size < PAGE_SIZE) {
1185                 buffer_size = PAGE_SIZE;
1186                 LOG("buffer_size too small, setting to %d\n", buffer_size);
1187         } else if(buffer_size > 1024*1024) {
1188                 /* arbitrary upper limiit */
1189                 buffer_size = 1024*1024;
1190                 LOG("buffer_size ridiculously large, setting to %d\n",
1191                     buffer_size);
1192         } else {
1193                 buffer_size += PAGE_SIZE-1;
1194                 buffer_size &= ~(PAGE_SIZE-1);
1195         }
1196
1197         if(num_buffers < 1) {
1198                 num_buffers = 1;
1199                 LOG("num_buffers too small, setting to %d\n", num_buffers);
1200         } else if(num_buffers > VIDEO_MAX_FRAME) {
1201                 num_buffers = VIDEO_MAX_FRAME;
1202                 LOG("num_buffers too large, setting to %d\n", num_buffers);
1203         }
1204
1205         if(alternate < USBIF_ISO_1 || alternate > USBIF_ISO_6) {
1206                 alternate = DEFAULT_ALT;
1207                 LOG("alternate specified is invalid, using %d\n", alternate);
1208         }
1209
1210         if (flicker_mode != 0 && flicker_mode != FLICKER_50 && flicker_mode != FLICKER_60) {
1211                 flicker_mode = 0;
1212                 LOG("Flicker mode specified is invalid, using %d\n",
1213                     flicker_mode);
1214         }
1215
1216         DBG("Using %d buffers, each %d bytes, alternate=%d\n",
1217             num_buffers, buffer_size, alternate);
1218 }
1219
1220 /************   Module Stuff ***************/
1221
1222
1223 /******************************************************************************
1224  *
1225  * cpia2_init/module_init
1226  *
1227  *****************************************************************************/
1228 static int __init cpia2_init(void)
1229 {
1230         LOG("%s v%s\n",
1231             ABOUT, CPIA_VERSION);
1232         check_parameters();
1233         cpia2_usb_init();
1234         return 0;
1235 }
1236
1237
1238 /******************************************************************************
1239  *
1240  * cpia2_exit/module_exit
1241  *
1242  *****************************************************************************/
1243 static void __exit cpia2_exit(void)
1244 {
1245         cpia2_usb_cleanup();
1246         schedule_timeout(2 * HZ);
1247 }
1248
1249 module_init(cpia2_init);
1250 module_exit(cpia2_exit);