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