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