Merge branch 'master' of git://git.kernel.org/pub/scm/linux/kernel/git/linville/wirel...
[firefly-linux-kernel-4.4.55.git] / drivers / media / platform / vivi.c
1 /*
2  * Virtual Video driver - This code emulates a real video device with v4l2 api
3  *
4  * Copyright (c) 2006 by:
5  *      Mauro Carvalho Chehab <mchehab--a.t--infradead.org>
6  *      Ted Walther <ted--a.t--enumera.com>
7  *      John Sokol <sokol--a.t--videotechnology.com>
8  *      http://v4l.videotechnology.com/
9  *
10  *      Conversion to videobuf2 by Pawel Osciak & Marek Szyprowski
11  *      Copyright (c) 2010 Samsung Electronics
12  *
13  * This program is free software; you can redistribute it and/or modify
14  * it under the terms of the BSD Licence, GNU General Public License
15  * as published by the Free Software Foundation; either version 2 of the
16  * License, or (at your option) any later version
17  */
18 #include <linux/module.h>
19 #include <linux/errno.h>
20 #include <linux/kernel.h>
21 #include <linux/init.h>
22 #include <linux/sched.h>
23 #include <linux/slab.h>
24 #include <linux/font.h>
25 #include <linux/mutex.h>
26 #include <linux/videodev2.h>
27 #include <linux/kthread.h>
28 #include <linux/freezer.h>
29 #include <media/videobuf2-vmalloc.h>
30 #include <media/v4l2-device.h>
31 #include <media/v4l2-ioctl.h>
32 #include <media/v4l2-ctrls.h>
33 #include <media/v4l2-fh.h>
34 #include <media/v4l2-event.h>
35 #include <media/v4l2-common.h>
36
37 #define VIVI_MODULE_NAME "vivi"
38
39 /* Wake up at about 30 fps */
40 #define WAKE_NUMERATOR 30
41 #define WAKE_DENOMINATOR 1001
42
43 #define MAX_WIDTH 1920
44 #define MAX_HEIGHT 1200
45
46 #define VIVI_VERSION "0.8.1"
47
48 MODULE_DESCRIPTION("Video Technology Magazine Virtual Video Capture Board");
49 MODULE_AUTHOR("Mauro Carvalho Chehab, Ted Walther and John Sokol");
50 MODULE_LICENSE("Dual BSD/GPL");
51 MODULE_VERSION(VIVI_VERSION);
52
53 static unsigned video_nr = -1;
54 module_param(video_nr, uint, 0644);
55 MODULE_PARM_DESC(video_nr, "videoX start number, -1 is autodetect");
56
57 static unsigned n_devs = 1;
58 module_param(n_devs, uint, 0644);
59 MODULE_PARM_DESC(n_devs, "number of video devices to create");
60
61 static unsigned debug;
62 module_param(debug, uint, 0644);
63 MODULE_PARM_DESC(debug, "activates debug info");
64
65 static unsigned int vid_limit = 16;
66 module_param(vid_limit, uint, 0644);
67 MODULE_PARM_DESC(vid_limit, "capture memory limit in megabytes");
68
69 /* Global font descriptor */
70 static const u8 *font8x16;
71
72 #define dprintk(dev, level, fmt, arg...) \
73         v4l2_dbg(level, debug, &dev->v4l2_dev, fmt, ## arg)
74
75 /* ------------------------------------------------------------------
76         Basic structures
77    ------------------------------------------------------------------*/
78
79 struct vivi_fmt {
80         char  *name;
81         u32   fourcc;          /* v4l2 format id */
82         u8    depth;
83         bool  is_yuv;
84 };
85
86 static struct vivi_fmt formats[] = {
87         {
88                 .name     = "4:2:2, packed, YUYV",
89                 .fourcc   = V4L2_PIX_FMT_YUYV,
90                 .depth    = 16,
91                 .is_yuv   = true,
92         },
93         {
94                 .name     = "4:2:2, packed, UYVY",
95                 .fourcc   = V4L2_PIX_FMT_UYVY,
96                 .depth    = 16,
97                 .is_yuv   = true,
98         },
99         {
100                 .name     = "4:2:2, packed, YVYU",
101                 .fourcc   = V4L2_PIX_FMT_YVYU,
102                 .depth    = 16,
103                 .is_yuv   = true,
104         },
105         {
106                 .name     = "4:2:2, packed, VYUY",
107                 .fourcc   = V4L2_PIX_FMT_VYUY,
108                 .depth    = 16,
109                 .is_yuv   = true,
110         },
111         {
112                 .name     = "RGB565 (LE)",
113                 .fourcc   = V4L2_PIX_FMT_RGB565, /* gggbbbbb rrrrrggg */
114                 .depth    = 16,
115         },
116         {
117                 .name     = "RGB565 (BE)",
118                 .fourcc   = V4L2_PIX_FMT_RGB565X, /* rrrrrggg gggbbbbb */
119                 .depth    = 16,
120         },
121         {
122                 .name     = "RGB555 (LE)",
123                 .fourcc   = V4L2_PIX_FMT_RGB555, /* gggbbbbb arrrrrgg */
124                 .depth    = 16,
125         },
126         {
127                 .name     = "RGB555 (BE)",
128                 .fourcc   = V4L2_PIX_FMT_RGB555X, /* arrrrrgg gggbbbbb */
129                 .depth    = 16,
130         },
131         {
132                 .name     = "RGB24 (LE)",
133                 .fourcc   = V4L2_PIX_FMT_RGB24, /* rgb */
134                 .depth    = 24,
135         },
136         {
137                 .name     = "RGB24 (BE)",
138                 .fourcc   = V4L2_PIX_FMT_BGR24, /* bgr */
139                 .depth    = 24,
140         },
141         {
142                 .name     = "RGB32 (LE)",
143                 .fourcc   = V4L2_PIX_FMT_RGB32, /* argb */
144                 .depth    = 32,
145         },
146         {
147                 .name     = "RGB32 (BE)",
148                 .fourcc   = V4L2_PIX_FMT_BGR32, /* bgra */
149                 .depth    = 32,
150         },
151 };
152
153 static struct vivi_fmt *get_format(struct v4l2_format *f)
154 {
155         struct vivi_fmt *fmt;
156         unsigned int k;
157
158         for (k = 0; k < ARRAY_SIZE(formats); k++) {
159                 fmt = &formats[k];
160                 if (fmt->fourcc == f->fmt.pix.pixelformat)
161                         break;
162         }
163
164         if (k == ARRAY_SIZE(formats))
165                 return NULL;
166
167         return &formats[k];
168 }
169
170 /* buffer for one video frame */
171 struct vivi_buffer {
172         /* common v4l buffer stuff -- must be first */
173         struct vb2_buffer       vb;
174         struct list_head        list;
175         struct vivi_fmt        *fmt;
176 };
177
178 struct vivi_dmaqueue {
179         struct list_head       active;
180
181         /* thread for generating video stream*/
182         struct task_struct         *kthread;
183         wait_queue_head_t          wq;
184         /* Counters to control fps rate */
185         int                        frame;
186         int                        ini_jiffies;
187 };
188
189 static LIST_HEAD(vivi_devlist);
190
191 struct vivi_dev {
192         struct list_head           vivi_devlist;
193         struct v4l2_device         v4l2_dev;
194         struct v4l2_ctrl_handler   ctrl_handler;
195         struct video_device        vdev;
196
197         /* controls */
198         struct v4l2_ctrl           *brightness;
199         struct v4l2_ctrl           *contrast;
200         struct v4l2_ctrl           *saturation;
201         struct v4l2_ctrl           *hue;
202         struct {
203                 /* autogain/gain cluster */
204                 struct v4l2_ctrl           *autogain;
205                 struct v4l2_ctrl           *gain;
206         };
207         struct v4l2_ctrl           *volume;
208         struct v4l2_ctrl           *alpha;
209         struct v4l2_ctrl           *button;
210         struct v4l2_ctrl           *boolean;
211         struct v4l2_ctrl           *int32;
212         struct v4l2_ctrl           *int64;
213         struct v4l2_ctrl           *menu;
214         struct v4l2_ctrl           *string;
215         struct v4l2_ctrl           *bitmask;
216         struct v4l2_ctrl           *int_menu;
217
218         spinlock_t                 slock;
219         struct mutex               mutex;
220
221         struct vivi_dmaqueue       vidq;
222
223         /* Several counters */
224         unsigned                   ms;
225         unsigned long              jiffies;
226         unsigned                   button_pressed;
227
228         int                        mv_count;    /* Controls bars movement */
229
230         /* Input Number */
231         int                        input;
232
233         /* video capture */
234         struct vivi_fmt            *fmt;
235         unsigned int               width, height;
236         struct vb2_queue           vb_vidq;
237         unsigned int               field_count;
238
239         u8                         bars[9][3];
240         u8                         line[MAX_WIDTH * 8];
241         unsigned int               pixelsize;
242         u8                         alpha_component;
243 };
244
245 /* ------------------------------------------------------------------
246         DMA and thread functions
247    ------------------------------------------------------------------*/
248
249 /* Bars and Colors should match positions */
250
251 enum colors {
252         WHITE,
253         AMBER,
254         CYAN,
255         GREEN,
256         MAGENTA,
257         RED,
258         BLUE,
259         BLACK,
260         TEXT_BLACK,
261 };
262
263 /* R   G   B */
264 #define COLOR_WHITE     {204, 204, 204}
265 #define COLOR_AMBER     {208, 208,   0}
266 #define COLOR_CYAN      {  0, 206, 206}
267 #define COLOR_GREEN     {  0, 239,   0}
268 #define COLOR_MAGENTA   {239,   0, 239}
269 #define COLOR_RED       {205,   0,   0}
270 #define COLOR_BLUE      {  0,   0, 255}
271 #define COLOR_BLACK     {  0,   0,   0}
272
273 struct bar_std {
274         u8 bar[9][3];
275 };
276
277 /* Maximum number of bars are 10 - otherwise, the input print code
278    should be modified */
279 static struct bar_std bars[] = {
280         {       /* Standard ITU-R color bar sequence */
281                 { COLOR_WHITE, COLOR_AMBER, COLOR_CYAN, COLOR_GREEN,
282                   COLOR_MAGENTA, COLOR_RED, COLOR_BLUE, COLOR_BLACK, COLOR_BLACK }
283         }, {
284                 { COLOR_WHITE, COLOR_AMBER, COLOR_BLACK, COLOR_WHITE,
285                   COLOR_AMBER, COLOR_BLACK, COLOR_WHITE, COLOR_AMBER, COLOR_BLACK }
286         }, {
287                 { COLOR_WHITE, COLOR_CYAN, COLOR_BLACK, COLOR_WHITE,
288                   COLOR_CYAN, COLOR_BLACK, COLOR_WHITE, COLOR_CYAN, COLOR_BLACK }
289         }, {
290                 { COLOR_WHITE, COLOR_GREEN, COLOR_BLACK, COLOR_WHITE,
291                   COLOR_GREEN, COLOR_BLACK, COLOR_WHITE, COLOR_GREEN, COLOR_BLACK }
292         },
293 };
294
295 #define NUM_INPUTS ARRAY_SIZE(bars)
296
297 #define TO_Y(r, g, b) \
298         (((16829 * r + 33039 * g + 6416 * b  + 32768) >> 16) + 16)
299 /* RGB to  V(Cr) Color transform */
300 #define TO_V(r, g, b) \
301         (((28784 * r - 24103 * g - 4681 * b  + 32768) >> 16) + 128)
302 /* RGB to  U(Cb) Color transform */
303 #define TO_U(r, g, b) \
304         (((-9714 * r - 19070 * g + 28784 * b + 32768) >> 16) + 128)
305
306 /* precalculate color bar values to speed up rendering */
307 static void precalculate_bars(struct vivi_dev *dev)
308 {
309         u8 r, g, b;
310         int k, is_yuv;
311
312         for (k = 0; k < 9; k++) {
313                 r = bars[dev->input].bar[k][0];
314                 g = bars[dev->input].bar[k][1];
315                 b = bars[dev->input].bar[k][2];
316                 is_yuv = dev->fmt->is_yuv;
317
318                 switch (dev->fmt->fourcc) {
319                 case V4L2_PIX_FMT_RGB565:
320                 case V4L2_PIX_FMT_RGB565X:
321                         r >>= 3;
322                         g >>= 2;
323                         b >>= 3;
324                         break;
325                 case V4L2_PIX_FMT_RGB555:
326                 case V4L2_PIX_FMT_RGB555X:
327                         r >>= 3;
328                         g >>= 3;
329                         b >>= 3;
330                         break;
331                 case V4L2_PIX_FMT_YUYV:
332                 case V4L2_PIX_FMT_UYVY:
333                 case V4L2_PIX_FMT_YVYU:
334                 case V4L2_PIX_FMT_VYUY:
335                 case V4L2_PIX_FMT_RGB24:
336                 case V4L2_PIX_FMT_BGR24:
337                 case V4L2_PIX_FMT_RGB32:
338                 case V4L2_PIX_FMT_BGR32:
339                         break;
340                 }
341
342                 if (is_yuv) {
343                         dev->bars[k][0] = TO_Y(r, g, b);        /* Luma */
344                         dev->bars[k][1] = TO_U(r, g, b);        /* Cb */
345                         dev->bars[k][2] = TO_V(r, g, b);        /* Cr */
346                 } else {
347                         dev->bars[k][0] = r;
348                         dev->bars[k][1] = g;
349                         dev->bars[k][2] = b;
350                 }
351         }
352 }
353
354 /* 'odd' is true for pixels 1, 3, 5, etc. and false for pixels 0, 2, 4, etc. */
355 static void gen_twopix(struct vivi_dev *dev, u8 *buf, int colorpos, bool odd)
356 {
357         u8 r_y, g_u, b_v;
358         u8 alpha = dev->alpha_component;
359         int color;
360         u8 *p;
361
362         r_y = dev->bars[colorpos][0]; /* R or precalculated Y */
363         g_u = dev->bars[colorpos][1]; /* G or precalculated U */
364         b_v = dev->bars[colorpos][2]; /* B or precalculated V */
365
366         for (color = 0; color < dev->pixelsize; color++) {
367                 p = buf + color;
368
369                 switch (dev->fmt->fourcc) {
370                 case V4L2_PIX_FMT_YUYV:
371                         switch (color) {
372                         case 0:
373                                 *p = r_y;
374                                 break;
375                         case 1:
376                                 *p = odd ? b_v : g_u;
377                                 break;
378                         }
379                         break;
380                 case V4L2_PIX_FMT_UYVY:
381                         switch (color) {
382                         case 0:
383                                 *p = odd ? b_v : g_u;
384                                 break;
385                         case 1:
386                                 *p = r_y;
387                                 break;
388                         }
389                         break;
390                 case V4L2_PIX_FMT_YVYU:
391                         switch (color) {
392                         case 0:
393                                 *p = r_y;
394                                 break;
395                         case 1:
396                                 *p = odd ? g_u : b_v;
397                                 break;
398                         }
399                         break;
400                 case V4L2_PIX_FMT_VYUY:
401                         switch (color) {
402                         case 0:
403                                 *p = odd ? g_u : b_v;
404                                 break;
405                         case 1:
406                                 *p = r_y;
407                                 break;
408                         }
409                         break;
410                 case V4L2_PIX_FMT_RGB565:
411                         switch (color) {
412                         case 0:
413                                 *p = (g_u << 5) | b_v;
414                                 break;
415                         case 1:
416                                 *p = (r_y << 3) | (g_u >> 3);
417                                 break;
418                         }
419                         break;
420                 case V4L2_PIX_FMT_RGB565X:
421                         switch (color) {
422                         case 0:
423                                 *p = (r_y << 3) | (g_u >> 3);
424                                 break;
425                         case 1:
426                                 *p = (g_u << 5) | b_v;
427                                 break;
428                         }
429                         break;
430                 case V4L2_PIX_FMT_RGB555:
431                         switch (color) {
432                         case 0:
433                                 *p = (g_u << 5) | b_v;
434                                 break;
435                         case 1:
436                                 *p = (alpha & 0x80) | (r_y << 2) | (g_u >> 3);
437                                 break;
438                         }
439                         break;
440                 case V4L2_PIX_FMT_RGB555X:
441                         switch (color) {
442                         case 0:
443                                 *p = (alpha & 0x80) | (r_y << 2) | (g_u >> 3);
444                                 break;
445                         case 1:
446                                 *p = (g_u << 5) | b_v;
447                                 break;
448                         }
449                         break;
450                 case V4L2_PIX_FMT_RGB24:
451                         switch (color) {
452                         case 0:
453                                 *p = r_y;
454                                 break;
455                         case 1:
456                                 *p = g_u;
457                                 break;
458                         case 2:
459                                 *p = b_v;
460                                 break;
461                         }
462                         break;
463                 case V4L2_PIX_FMT_BGR24:
464                         switch (color) {
465                         case 0:
466                                 *p = b_v;
467                                 break;
468                         case 1:
469                                 *p = g_u;
470                                 break;
471                         case 2:
472                                 *p = r_y;
473                                 break;
474                         }
475                         break;
476                 case V4L2_PIX_FMT_RGB32:
477                         switch (color) {
478                         case 0:
479                                 *p = alpha;
480                                 break;
481                         case 1:
482                                 *p = r_y;
483                                 break;
484                         case 2:
485                                 *p = g_u;
486                                 break;
487                         case 3:
488                                 *p = b_v;
489                                 break;
490                         }
491                         break;
492                 case V4L2_PIX_FMT_BGR32:
493                         switch (color) {
494                         case 0:
495                                 *p = b_v;
496                                 break;
497                         case 1:
498                                 *p = g_u;
499                                 break;
500                         case 2:
501                                 *p = r_y;
502                                 break;
503                         case 3:
504                                 *p = alpha;
505                                 break;
506                         }
507                         break;
508                 }
509         }
510 }
511
512 static void precalculate_line(struct vivi_dev *dev)
513 {
514         int w;
515
516         for (w = 0; w < dev->width * 2; w++) {
517                 int colorpos = w / (dev->width / 8) % 8;
518
519                 gen_twopix(dev, dev->line + w * dev->pixelsize, colorpos, w & 1);
520         }
521 }
522
523 static void gen_text(struct vivi_dev *dev, char *basep,
524                                         int y, int x, char *text)
525 {
526         int line;
527
528         /* Checks if it is possible to show string */
529         if (y + 16 >= dev->height || x + strlen(text) * 8 >= dev->width)
530                 return;
531
532         /* Print stream time */
533         for (line = y; line < y + 16; line++) {
534                 int j = 0;
535                 char *pos = basep + line * dev->width * dev->pixelsize + x * dev->pixelsize;
536                 char *s;
537
538                 for (s = text; *s; s++) {
539                         u8 chr = font8x16[*s * 16 + line - y];
540                         int i;
541
542                         for (i = 0; i < 7; i++, j++) {
543                                 /* Draw white font on black background */
544                                 if (chr & (1 << (7 - i)))
545                                         gen_twopix(dev, pos + j * dev->pixelsize, WHITE, (x+y) & 1);
546                                 else
547                                         gen_twopix(dev, pos + j * dev->pixelsize, TEXT_BLACK, (x+y) & 1);
548                         }
549                 }
550         }
551 }
552
553 static void vivi_fillbuff(struct vivi_dev *dev, struct vivi_buffer *buf)
554 {
555         int wmax = dev->width;
556         int hmax = dev->height;
557         struct timeval ts;
558         void *vbuf = vb2_plane_vaddr(&buf->vb, 0);
559         unsigned ms;
560         char str[100];
561         int h, line = 1;
562         s32 gain;
563
564         if (!vbuf)
565                 return;
566
567         for (h = 0; h < hmax; h++)
568                 memcpy(vbuf + h * wmax * dev->pixelsize,
569                        dev->line + (dev->mv_count % wmax) * dev->pixelsize,
570                        wmax * dev->pixelsize);
571
572         /* Updates stream time */
573
574         dev->ms += jiffies_to_msecs(jiffies - dev->jiffies);
575         dev->jiffies = jiffies;
576         ms = dev->ms;
577         snprintf(str, sizeof(str), " %02d:%02d:%02d:%03d ",
578                         (ms / (60 * 60 * 1000)) % 24,
579                         (ms / (60 * 1000)) % 60,
580                         (ms / 1000) % 60,
581                         ms % 1000);
582         gen_text(dev, vbuf, line++ * 16, 16, str);
583         snprintf(str, sizeof(str), " %dx%d, input %d ",
584                         dev->width, dev->height, dev->input);
585         gen_text(dev, vbuf, line++ * 16, 16, str);
586
587         gain = v4l2_ctrl_g_ctrl(dev->gain);
588         mutex_lock(dev->ctrl_handler.lock);
589         snprintf(str, sizeof(str), " brightness %3d, contrast %3d, saturation %3d, hue %d ",
590                         dev->brightness->cur.val,
591                         dev->contrast->cur.val,
592                         dev->saturation->cur.val,
593                         dev->hue->cur.val);
594         gen_text(dev, vbuf, line++ * 16, 16, str);
595         snprintf(str, sizeof(str), " autogain %d, gain %3d, volume %3d, alpha 0x%02x ",
596                         dev->autogain->cur.val, gain, dev->volume->cur.val,
597                         dev->alpha->cur.val);
598         gen_text(dev, vbuf, line++ * 16, 16, str);
599         snprintf(str, sizeof(str), " int32 %d, int64 %lld, bitmask %08x ",
600                         dev->int32->cur.val,
601                         dev->int64->cur.val64,
602                         dev->bitmask->cur.val);
603         gen_text(dev, vbuf, line++ * 16, 16, str);
604         snprintf(str, sizeof(str), " boolean %d, menu %s, string \"%s\" ",
605                         dev->boolean->cur.val,
606                         dev->menu->qmenu[dev->menu->cur.val],
607                         dev->string->cur.string);
608         gen_text(dev, vbuf, line++ * 16, 16, str);
609         snprintf(str, sizeof(str), " integer_menu %lld, value %d ",
610                         dev->int_menu->qmenu_int[dev->int_menu->cur.val],
611                         dev->int_menu->cur.val);
612         gen_text(dev, vbuf, line++ * 16, 16, str);
613         mutex_unlock(dev->ctrl_handler.lock);
614         if (dev->button_pressed) {
615                 dev->button_pressed--;
616                 snprintf(str, sizeof(str), " button pressed!");
617                 gen_text(dev, vbuf, line++ * 16, 16, str);
618         }
619
620         dev->mv_count += 2;
621
622         buf->vb.v4l2_buf.field = V4L2_FIELD_INTERLACED;
623         dev->field_count++;
624         buf->vb.v4l2_buf.sequence = dev->field_count >> 1;
625         do_gettimeofday(&ts);
626         buf->vb.v4l2_buf.timestamp = ts;
627 }
628
629 static void vivi_thread_tick(struct vivi_dev *dev)
630 {
631         struct vivi_dmaqueue *dma_q = &dev->vidq;
632         struct vivi_buffer *buf;
633         unsigned long flags = 0;
634
635         dprintk(dev, 1, "Thread tick\n");
636
637         spin_lock_irqsave(&dev->slock, flags);
638         if (list_empty(&dma_q->active)) {
639                 dprintk(dev, 1, "No active queue to serve\n");
640                 spin_unlock_irqrestore(&dev->slock, flags);
641                 return;
642         }
643
644         buf = list_entry(dma_q->active.next, struct vivi_buffer, list);
645         list_del(&buf->list);
646         spin_unlock_irqrestore(&dev->slock, flags);
647
648         do_gettimeofday(&buf->vb.v4l2_buf.timestamp);
649
650         /* Fill buffer */
651         vivi_fillbuff(dev, buf);
652         dprintk(dev, 1, "filled buffer %p\n", buf);
653
654         vb2_buffer_done(&buf->vb, VB2_BUF_STATE_DONE);
655         dprintk(dev, 2, "[%p/%d] done\n", buf, buf->vb.v4l2_buf.index);
656 }
657
658 #define frames_to_ms(frames)                                    \
659         ((frames * WAKE_NUMERATOR * 1000) / WAKE_DENOMINATOR)
660
661 static void vivi_sleep(struct vivi_dev *dev)
662 {
663         struct vivi_dmaqueue *dma_q = &dev->vidq;
664         int timeout;
665         DECLARE_WAITQUEUE(wait, current);
666
667         dprintk(dev, 1, "%s dma_q=0x%08lx\n", __func__,
668                 (unsigned long)dma_q);
669
670         add_wait_queue(&dma_q->wq, &wait);
671         if (kthread_should_stop())
672                 goto stop_task;
673
674         /* Calculate time to wake up */
675         timeout = msecs_to_jiffies(frames_to_ms(1));
676
677         vivi_thread_tick(dev);
678
679         schedule_timeout_interruptible(timeout);
680
681 stop_task:
682         remove_wait_queue(&dma_q->wq, &wait);
683         try_to_freeze();
684 }
685
686 static int vivi_thread(void *data)
687 {
688         struct vivi_dev *dev = data;
689
690         dprintk(dev, 1, "thread started\n");
691
692         set_freezable();
693
694         for (;;) {
695                 vivi_sleep(dev);
696
697                 if (kthread_should_stop())
698                         break;
699         }
700         dprintk(dev, 1, "thread: exit\n");
701         return 0;
702 }
703
704 static int vivi_start_generating(struct vivi_dev *dev)
705 {
706         struct vivi_dmaqueue *dma_q = &dev->vidq;
707
708         dprintk(dev, 1, "%s\n", __func__);
709
710         /* Resets frame counters */
711         dev->ms = 0;
712         dev->mv_count = 0;
713         dev->jiffies = jiffies;
714
715         dma_q->frame = 0;
716         dma_q->ini_jiffies = jiffies;
717         dma_q->kthread = kthread_run(vivi_thread, dev, dev->v4l2_dev.name);
718
719         if (IS_ERR(dma_q->kthread)) {
720                 v4l2_err(&dev->v4l2_dev, "kernel_thread() failed\n");
721                 return PTR_ERR(dma_q->kthread);
722         }
723         /* Wakes thread */
724         wake_up_interruptible(&dma_q->wq);
725
726         dprintk(dev, 1, "returning from %s\n", __func__);
727         return 0;
728 }
729
730 static void vivi_stop_generating(struct vivi_dev *dev)
731 {
732         struct vivi_dmaqueue *dma_q = &dev->vidq;
733
734         dprintk(dev, 1, "%s\n", __func__);
735
736         /* shutdown control thread */
737         if (dma_q->kthread) {
738                 kthread_stop(dma_q->kthread);
739                 dma_q->kthread = NULL;
740         }
741
742         /*
743          * Typical driver might need to wait here until dma engine stops.
744          * In this case we can abort imiedetly, so it's just a noop.
745          */
746
747         /* Release all active buffers */
748         while (!list_empty(&dma_q->active)) {
749                 struct vivi_buffer *buf;
750                 buf = list_entry(dma_q->active.next, struct vivi_buffer, list);
751                 list_del(&buf->list);
752                 vb2_buffer_done(&buf->vb, VB2_BUF_STATE_ERROR);
753                 dprintk(dev, 2, "[%p/%d] done\n", buf, buf->vb.v4l2_buf.index);
754         }
755 }
756 /* ------------------------------------------------------------------
757         Videobuf operations
758    ------------------------------------------------------------------*/
759 static int queue_setup(struct vb2_queue *vq, const struct v4l2_format *fmt,
760                                 unsigned int *nbuffers, unsigned int *nplanes,
761                                 unsigned int sizes[], void *alloc_ctxs[])
762 {
763         struct vivi_dev *dev = vb2_get_drv_priv(vq);
764         unsigned long size;
765
766         if (fmt)
767                 size = fmt->fmt.pix.sizeimage;
768         else
769                 size = dev->width * dev->height * dev->pixelsize;
770
771         if (size == 0)
772                 return -EINVAL;
773
774         if (0 == *nbuffers)
775                 *nbuffers = 32;
776
777         while (size * *nbuffers > vid_limit * 1024 * 1024)
778                 (*nbuffers)--;
779
780         *nplanes = 1;
781
782         sizes[0] = size;
783
784         /*
785          * videobuf2-vmalloc allocator is context-less so no need to set
786          * alloc_ctxs array.
787          */
788
789         dprintk(dev, 1, "%s, count=%d, size=%ld\n", __func__,
790                 *nbuffers, size);
791
792         return 0;
793 }
794
795 static int buffer_prepare(struct vb2_buffer *vb)
796 {
797         struct vivi_dev *dev = vb2_get_drv_priv(vb->vb2_queue);
798         struct vivi_buffer *buf = container_of(vb, struct vivi_buffer, vb);
799         unsigned long size;
800
801         dprintk(dev, 1, "%s, field=%d\n", __func__, vb->v4l2_buf.field);
802
803         BUG_ON(NULL == dev->fmt);
804
805         /*
806          * Theses properties only change when queue is idle, see s_fmt.
807          * The below checks should not be performed here, on each
808          * buffer_prepare (i.e. on each qbuf). Most of the code in this function
809          * should thus be moved to buffer_init and s_fmt.
810          */
811         if (dev->width  < 48 || dev->width  > MAX_WIDTH ||
812             dev->height < 32 || dev->height > MAX_HEIGHT)
813                 return -EINVAL;
814
815         size = dev->width * dev->height * dev->pixelsize;
816         if (vb2_plane_size(vb, 0) < size) {
817                 dprintk(dev, 1, "%s data will not fit into plane (%lu < %lu)\n",
818                                 __func__, vb2_plane_size(vb, 0), size);
819                 return -EINVAL;
820         }
821
822         vb2_set_plane_payload(&buf->vb, 0, size);
823
824         buf->fmt = dev->fmt;
825
826         precalculate_bars(dev);
827         precalculate_line(dev);
828
829         return 0;
830 }
831
832 static void buffer_queue(struct vb2_buffer *vb)
833 {
834         struct vivi_dev *dev = vb2_get_drv_priv(vb->vb2_queue);
835         struct vivi_buffer *buf = container_of(vb, struct vivi_buffer, vb);
836         struct vivi_dmaqueue *vidq = &dev->vidq;
837         unsigned long flags = 0;
838
839         dprintk(dev, 1, "%s\n", __func__);
840
841         spin_lock_irqsave(&dev->slock, flags);
842         list_add_tail(&buf->list, &vidq->active);
843         spin_unlock_irqrestore(&dev->slock, flags);
844 }
845
846 static int start_streaming(struct vb2_queue *vq, unsigned int count)
847 {
848         struct vivi_dev *dev = vb2_get_drv_priv(vq);
849         dprintk(dev, 1, "%s\n", __func__);
850         return vivi_start_generating(dev);
851 }
852
853 /* abort streaming and wait for last buffer */
854 static int stop_streaming(struct vb2_queue *vq)
855 {
856         struct vivi_dev *dev = vb2_get_drv_priv(vq);
857         dprintk(dev, 1, "%s\n", __func__);
858         vivi_stop_generating(dev);
859         return 0;
860 }
861
862 static void vivi_lock(struct vb2_queue *vq)
863 {
864         struct vivi_dev *dev = vb2_get_drv_priv(vq);
865         mutex_lock(&dev->mutex);
866 }
867
868 static void vivi_unlock(struct vb2_queue *vq)
869 {
870         struct vivi_dev *dev = vb2_get_drv_priv(vq);
871         mutex_unlock(&dev->mutex);
872 }
873
874
875 static struct vb2_ops vivi_video_qops = {
876         .queue_setup            = queue_setup,
877         .buf_prepare            = buffer_prepare,
878         .buf_queue              = buffer_queue,
879         .start_streaming        = start_streaming,
880         .stop_streaming         = stop_streaming,
881         .wait_prepare           = vivi_unlock,
882         .wait_finish            = vivi_lock,
883 };
884
885 /* ------------------------------------------------------------------
886         IOCTL vidioc handling
887    ------------------------------------------------------------------*/
888 static int vidioc_querycap(struct file *file, void  *priv,
889                                         struct v4l2_capability *cap)
890 {
891         struct vivi_dev *dev = video_drvdata(file);
892
893         strcpy(cap->driver, "vivi");
894         strcpy(cap->card, "vivi");
895         snprintf(cap->bus_info, sizeof(cap->bus_info),
896                         "platform:%s", dev->v4l2_dev.name);
897         cap->device_caps = V4L2_CAP_VIDEO_CAPTURE | V4L2_CAP_STREAMING |
898                             V4L2_CAP_READWRITE;
899         cap->capabilities = cap->device_caps | V4L2_CAP_DEVICE_CAPS;
900         return 0;
901 }
902
903 static int vidioc_enum_fmt_vid_cap(struct file *file, void  *priv,
904                                         struct v4l2_fmtdesc *f)
905 {
906         struct vivi_fmt *fmt;
907
908         if (f->index >= ARRAY_SIZE(formats))
909                 return -EINVAL;
910
911         fmt = &formats[f->index];
912
913         strlcpy(f->description, fmt->name, sizeof(f->description));
914         f->pixelformat = fmt->fourcc;
915         return 0;
916 }
917
918 static int vidioc_g_fmt_vid_cap(struct file *file, void *priv,
919                                         struct v4l2_format *f)
920 {
921         struct vivi_dev *dev = video_drvdata(file);
922
923         f->fmt.pix.width        = dev->width;
924         f->fmt.pix.height       = dev->height;
925         f->fmt.pix.field        = V4L2_FIELD_INTERLACED;
926         f->fmt.pix.pixelformat  = dev->fmt->fourcc;
927         f->fmt.pix.bytesperline =
928                 (f->fmt.pix.width * dev->fmt->depth) >> 3;
929         f->fmt.pix.sizeimage =
930                 f->fmt.pix.height * f->fmt.pix.bytesperline;
931         if (dev->fmt->is_yuv)
932                 f->fmt.pix.colorspace = V4L2_COLORSPACE_SMPTE170M;
933         else
934                 f->fmt.pix.colorspace = V4L2_COLORSPACE_SRGB;
935         return 0;
936 }
937
938 static int vidioc_try_fmt_vid_cap(struct file *file, void *priv,
939                         struct v4l2_format *f)
940 {
941         struct vivi_dev *dev = video_drvdata(file);
942         struct vivi_fmt *fmt;
943
944         fmt = get_format(f);
945         if (!fmt) {
946                 dprintk(dev, 1, "Fourcc format (0x%08x) unknown.\n",
947                         f->fmt.pix.pixelformat);
948                 f->fmt.pix.pixelformat = V4L2_PIX_FMT_YUYV;
949                 fmt = get_format(f);
950         }
951
952         f->fmt.pix.field = V4L2_FIELD_INTERLACED;
953         v4l_bound_align_image(&f->fmt.pix.width, 48, MAX_WIDTH, 2,
954                               &f->fmt.pix.height, 32, MAX_HEIGHT, 0, 0);
955         f->fmt.pix.bytesperline =
956                 (f->fmt.pix.width * fmt->depth) >> 3;
957         f->fmt.pix.sizeimage =
958                 f->fmt.pix.height * f->fmt.pix.bytesperline;
959         if (fmt->is_yuv)
960                 f->fmt.pix.colorspace = V4L2_COLORSPACE_SMPTE170M;
961         else
962                 f->fmt.pix.colorspace = V4L2_COLORSPACE_SRGB;
963         f->fmt.pix.priv = 0;
964         return 0;
965 }
966
967 static int vidioc_s_fmt_vid_cap(struct file *file, void *priv,
968                                         struct v4l2_format *f)
969 {
970         struct vivi_dev *dev = video_drvdata(file);
971         struct vb2_queue *q = &dev->vb_vidq;
972
973         int ret = vidioc_try_fmt_vid_cap(file, priv, f);
974         if (ret < 0)
975                 return ret;
976
977         if (vb2_is_busy(q)) {
978                 dprintk(dev, 1, "%s device busy\n", __func__);
979                 return -EBUSY;
980         }
981
982         dev->fmt = get_format(f);
983         dev->pixelsize = dev->fmt->depth / 8;
984         dev->width = f->fmt.pix.width;
985         dev->height = f->fmt.pix.height;
986
987         return 0;
988 }
989
990 static int vidioc_enum_framesizes(struct file *file, void *fh,
991                                          struct v4l2_frmsizeenum *fsize)
992 {
993         static const struct v4l2_frmsize_stepwise sizes = {
994                 48, MAX_WIDTH, 4,
995                 32, MAX_HEIGHT, 1
996         };
997         int i;
998
999         if (fsize->index)
1000                 return -EINVAL;
1001         for (i = 0; i < ARRAY_SIZE(formats); i++)
1002                 if (formats[i].fourcc == fsize->pixel_format)
1003                         break;
1004         if (i == ARRAY_SIZE(formats))
1005                 return -EINVAL;
1006         fsize->type = V4L2_FRMSIZE_TYPE_STEPWISE;
1007         fsize->stepwise = sizes;
1008         return 0;
1009 }
1010
1011 /* only one input in this sample driver */
1012 static int vidioc_enum_input(struct file *file, void *priv,
1013                                 struct v4l2_input *inp)
1014 {
1015         if (inp->index >= NUM_INPUTS)
1016                 return -EINVAL;
1017
1018         inp->type = V4L2_INPUT_TYPE_CAMERA;
1019         sprintf(inp->name, "Camera %u", inp->index);
1020         return 0;
1021 }
1022
1023 static int vidioc_g_input(struct file *file, void *priv, unsigned int *i)
1024 {
1025         struct vivi_dev *dev = video_drvdata(file);
1026
1027         *i = dev->input;
1028         return 0;
1029 }
1030
1031 static int vidioc_s_input(struct file *file, void *priv, unsigned int i)
1032 {
1033         struct vivi_dev *dev = video_drvdata(file);
1034
1035         if (i >= NUM_INPUTS)
1036                 return -EINVAL;
1037
1038         if (i == dev->input)
1039                 return 0;
1040
1041         dev->input = i;
1042         precalculate_bars(dev);
1043         precalculate_line(dev);
1044         return 0;
1045 }
1046
1047 /* --- controls ---------------------------------------------- */
1048
1049 static int vivi_g_volatile_ctrl(struct v4l2_ctrl *ctrl)
1050 {
1051         struct vivi_dev *dev = container_of(ctrl->handler, struct vivi_dev, ctrl_handler);
1052
1053         if (ctrl == dev->autogain)
1054                 dev->gain->val = jiffies & 0xff;
1055         return 0;
1056 }
1057
1058 static int vivi_s_ctrl(struct v4l2_ctrl *ctrl)
1059 {
1060         struct vivi_dev *dev = container_of(ctrl->handler, struct vivi_dev, ctrl_handler);
1061
1062         switch (ctrl->id) {
1063         case V4L2_CID_ALPHA_COMPONENT:
1064                 dev->alpha_component = ctrl->val;
1065                 break;
1066         default:
1067                 if (ctrl == dev->button)
1068                         dev->button_pressed = 30;
1069                 break;
1070         }
1071         return 0;
1072 }
1073
1074 /* ------------------------------------------------------------------
1075         File operations for the device
1076    ------------------------------------------------------------------*/
1077
1078 static const struct v4l2_ctrl_ops vivi_ctrl_ops = {
1079         .g_volatile_ctrl = vivi_g_volatile_ctrl,
1080         .s_ctrl = vivi_s_ctrl,
1081 };
1082
1083 #define VIVI_CID_CUSTOM_BASE    (V4L2_CID_USER_BASE | 0xf000)
1084
1085 static const struct v4l2_ctrl_config vivi_ctrl_button = {
1086         .ops = &vivi_ctrl_ops,
1087         .id = VIVI_CID_CUSTOM_BASE + 0,
1088         .name = "Button",
1089         .type = V4L2_CTRL_TYPE_BUTTON,
1090 };
1091
1092 static const struct v4l2_ctrl_config vivi_ctrl_boolean = {
1093         .ops = &vivi_ctrl_ops,
1094         .id = VIVI_CID_CUSTOM_BASE + 1,
1095         .name = "Boolean",
1096         .type = V4L2_CTRL_TYPE_BOOLEAN,
1097         .min = 0,
1098         .max = 1,
1099         .step = 1,
1100         .def = 1,
1101 };
1102
1103 static const struct v4l2_ctrl_config vivi_ctrl_int32 = {
1104         .ops = &vivi_ctrl_ops,
1105         .id = VIVI_CID_CUSTOM_BASE + 2,
1106         .name = "Integer 32 Bits",
1107         .type = V4L2_CTRL_TYPE_INTEGER,
1108         .min = 0x80000000,
1109         .max = 0x7fffffff,
1110         .step = 1,
1111 };
1112
1113 static const struct v4l2_ctrl_config vivi_ctrl_int64 = {
1114         .ops = &vivi_ctrl_ops,
1115         .id = VIVI_CID_CUSTOM_BASE + 3,
1116         .name = "Integer 64 Bits",
1117         .type = V4L2_CTRL_TYPE_INTEGER64,
1118 };
1119
1120 static const char * const vivi_ctrl_menu_strings[] = {
1121         "Menu Item 0 (Skipped)",
1122         "Menu Item 1",
1123         "Menu Item 2 (Skipped)",
1124         "Menu Item 3",
1125         "Menu Item 4",
1126         "Menu Item 5 (Skipped)",
1127         NULL,
1128 };
1129
1130 static const struct v4l2_ctrl_config vivi_ctrl_menu = {
1131         .ops = &vivi_ctrl_ops,
1132         .id = VIVI_CID_CUSTOM_BASE + 4,
1133         .name = "Menu",
1134         .type = V4L2_CTRL_TYPE_MENU,
1135         .min = 1,
1136         .max = 4,
1137         .def = 3,
1138         .menu_skip_mask = 0x04,
1139         .qmenu = vivi_ctrl_menu_strings,
1140 };
1141
1142 static const struct v4l2_ctrl_config vivi_ctrl_string = {
1143         .ops = &vivi_ctrl_ops,
1144         .id = VIVI_CID_CUSTOM_BASE + 5,
1145         .name = "String",
1146         .type = V4L2_CTRL_TYPE_STRING,
1147         .min = 2,
1148         .max = 4,
1149         .step = 1,
1150 };
1151
1152 static const struct v4l2_ctrl_config vivi_ctrl_bitmask = {
1153         .ops = &vivi_ctrl_ops,
1154         .id = VIVI_CID_CUSTOM_BASE + 6,
1155         .name = "Bitmask",
1156         .type = V4L2_CTRL_TYPE_BITMASK,
1157         .def = 0x80002000,
1158         .min = 0,
1159         .max = 0x80402010,
1160         .step = 0,
1161 };
1162
1163 static const s64 vivi_ctrl_int_menu_values[] = {
1164         1, 1, 2, 3, 5, 8, 13, 21, 42,
1165 };
1166
1167 static const struct v4l2_ctrl_config vivi_ctrl_int_menu = {
1168         .ops = &vivi_ctrl_ops,
1169         .id = VIVI_CID_CUSTOM_BASE + 7,
1170         .name = "Integer menu",
1171         .type = V4L2_CTRL_TYPE_INTEGER_MENU,
1172         .min = 1,
1173         .max = 8,
1174         .def = 4,
1175         .menu_skip_mask = 0x02,
1176         .qmenu_int = vivi_ctrl_int_menu_values,
1177 };
1178
1179 static const struct v4l2_file_operations vivi_fops = {
1180         .owner          = THIS_MODULE,
1181         .open           = v4l2_fh_open,
1182         .release        = vb2_fop_release,
1183         .read           = vb2_fop_read,
1184         .poll           = vb2_fop_poll,
1185         .unlocked_ioctl = video_ioctl2, /* V4L2 ioctl handler */
1186         .mmap           = vb2_fop_mmap,
1187 };
1188
1189 static const struct v4l2_ioctl_ops vivi_ioctl_ops = {
1190         .vidioc_querycap      = vidioc_querycap,
1191         .vidioc_enum_fmt_vid_cap  = vidioc_enum_fmt_vid_cap,
1192         .vidioc_g_fmt_vid_cap     = vidioc_g_fmt_vid_cap,
1193         .vidioc_try_fmt_vid_cap   = vidioc_try_fmt_vid_cap,
1194         .vidioc_s_fmt_vid_cap     = vidioc_s_fmt_vid_cap,
1195         .vidioc_enum_framesizes   = vidioc_enum_framesizes,
1196         .vidioc_reqbufs       = vb2_ioctl_reqbufs,
1197         .vidioc_create_bufs   = vb2_ioctl_create_bufs,
1198         .vidioc_prepare_buf   = vb2_ioctl_prepare_buf,
1199         .vidioc_querybuf      = vb2_ioctl_querybuf,
1200         .vidioc_qbuf          = vb2_ioctl_qbuf,
1201         .vidioc_dqbuf         = vb2_ioctl_dqbuf,
1202         .vidioc_enum_input    = vidioc_enum_input,
1203         .vidioc_g_input       = vidioc_g_input,
1204         .vidioc_s_input       = vidioc_s_input,
1205         .vidioc_streamon      = vb2_ioctl_streamon,
1206         .vidioc_streamoff     = vb2_ioctl_streamoff,
1207         .vidioc_log_status    = v4l2_ctrl_log_status,
1208         .vidioc_subscribe_event = v4l2_ctrl_subscribe_event,
1209         .vidioc_unsubscribe_event = v4l2_event_unsubscribe,
1210 };
1211
1212 static struct video_device vivi_template = {
1213         .name           = "vivi",
1214         .fops           = &vivi_fops,
1215         .ioctl_ops      = &vivi_ioctl_ops,
1216         .release        = video_device_release_empty,
1217 };
1218
1219 /* -----------------------------------------------------------------
1220         Initialization and module stuff
1221    ------------------------------------------------------------------*/
1222
1223 static int vivi_release(void)
1224 {
1225         struct vivi_dev *dev;
1226         struct list_head *list;
1227
1228         while (!list_empty(&vivi_devlist)) {
1229                 list = vivi_devlist.next;
1230                 list_del(list);
1231                 dev = list_entry(list, struct vivi_dev, vivi_devlist);
1232
1233                 v4l2_info(&dev->v4l2_dev, "unregistering %s\n",
1234                         video_device_node_name(&dev->vdev));
1235                 video_unregister_device(&dev->vdev);
1236                 v4l2_device_unregister(&dev->v4l2_dev);
1237                 v4l2_ctrl_handler_free(&dev->ctrl_handler);
1238                 kfree(dev);
1239         }
1240
1241         return 0;
1242 }
1243
1244 static int __init vivi_create_instance(int inst)
1245 {
1246         struct vivi_dev *dev;
1247         struct video_device *vfd;
1248         struct v4l2_ctrl_handler *hdl;
1249         struct vb2_queue *q;
1250         int ret;
1251
1252         dev = kzalloc(sizeof(*dev), GFP_KERNEL);
1253         if (!dev)
1254                 return -ENOMEM;
1255
1256         snprintf(dev->v4l2_dev.name, sizeof(dev->v4l2_dev.name),
1257                         "%s-%03d", VIVI_MODULE_NAME, inst);
1258         ret = v4l2_device_register(NULL, &dev->v4l2_dev);
1259         if (ret)
1260                 goto free_dev;
1261
1262         dev->fmt = &formats[0];
1263         dev->width = 640;
1264         dev->height = 480;
1265         dev->pixelsize = dev->fmt->depth / 8;
1266         hdl = &dev->ctrl_handler;
1267         v4l2_ctrl_handler_init(hdl, 11);
1268         dev->volume = v4l2_ctrl_new_std(hdl, &vivi_ctrl_ops,
1269                         V4L2_CID_AUDIO_VOLUME, 0, 255, 1, 200);
1270         dev->brightness = v4l2_ctrl_new_std(hdl, &vivi_ctrl_ops,
1271                         V4L2_CID_BRIGHTNESS, 0, 255, 1, 127);
1272         dev->contrast = v4l2_ctrl_new_std(hdl, &vivi_ctrl_ops,
1273                         V4L2_CID_CONTRAST, 0, 255, 1, 16);
1274         dev->saturation = v4l2_ctrl_new_std(hdl, &vivi_ctrl_ops,
1275                         V4L2_CID_SATURATION, 0, 255, 1, 127);
1276         dev->hue = v4l2_ctrl_new_std(hdl, &vivi_ctrl_ops,
1277                         V4L2_CID_HUE, -128, 127, 1, 0);
1278         dev->autogain = v4l2_ctrl_new_std(hdl, &vivi_ctrl_ops,
1279                         V4L2_CID_AUTOGAIN, 0, 1, 1, 1);
1280         dev->gain = v4l2_ctrl_new_std(hdl, &vivi_ctrl_ops,
1281                         V4L2_CID_GAIN, 0, 255, 1, 100);
1282         dev->alpha = v4l2_ctrl_new_std(hdl, &vivi_ctrl_ops,
1283                         V4L2_CID_ALPHA_COMPONENT, 0, 255, 1, 0);
1284         dev->button = v4l2_ctrl_new_custom(hdl, &vivi_ctrl_button, NULL);
1285         dev->int32 = v4l2_ctrl_new_custom(hdl, &vivi_ctrl_int32, NULL);
1286         dev->int64 = v4l2_ctrl_new_custom(hdl, &vivi_ctrl_int64, NULL);
1287         dev->boolean = v4l2_ctrl_new_custom(hdl, &vivi_ctrl_boolean, NULL);
1288         dev->menu = v4l2_ctrl_new_custom(hdl, &vivi_ctrl_menu, NULL);
1289         dev->string = v4l2_ctrl_new_custom(hdl, &vivi_ctrl_string, NULL);
1290         dev->bitmask = v4l2_ctrl_new_custom(hdl, &vivi_ctrl_bitmask, NULL);
1291         dev->int_menu = v4l2_ctrl_new_custom(hdl, &vivi_ctrl_int_menu, NULL);
1292         if (hdl->error) {
1293                 ret = hdl->error;
1294                 goto unreg_dev;
1295         }
1296         v4l2_ctrl_auto_cluster(2, &dev->autogain, 0, true);
1297         dev->v4l2_dev.ctrl_handler = hdl;
1298
1299         /* initialize locks */
1300         spin_lock_init(&dev->slock);
1301
1302         /* initialize queue */
1303         q = &dev->vb_vidq;
1304         q->type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
1305         q->io_modes = VB2_MMAP | VB2_USERPTR | VB2_DMABUF | VB2_READ;
1306         q->drv_priv = dev;
1307         q->buf_struct_size = sizeof(struct vivi_buffer);
1308         q->ops = &vivi_video_qops;
1309         q->mem_ops = &vb2_vmalloc_memops;
1310
1311         ret = vb2_queue_init(q);
1312         if (ret)
1313                 goto unreg_dev;
1314
1315         mutex_init(&dev->mutex);
1316
1317         /* init video dma queues */
1318         INIT_LIST_HEAD(&dev->vidq.active);
1319         init_waitqueue_head(&dev->vidq.wq);
1320
1321         vfd = &dev->vdev;
1322         *vfd = vivi_template;
1323         vfd->debug = debug;
1324         vfd->v4l2_dev = &dev->v4l2_dev;
1325         vfd->queue = q;
1326         set_bit(V4L2_FL_USE_FH_PRIO, &vfd->flags);
1327
1328         /*
1329          * Provide a mutex to v4l2 core. It will be used to protect
1330          * all fops and v4l2 ioctls.
1331          */
1332         vfd->lock = &dev->mutex;
1333         video_set_drvdata(vfd, dev);
1334
1335         ret = video_register_device(vfd, VFL_TYPE_GRABBER, video_nr);
1336         if (ret < 0)
1337                 goto unreg_dev;
1338
1339         /* Now that everything is fine, let's add it to device list */
1340         list_add_tail(&dev->vivi_devlist, &vivi_devlist);
1341
1342         v4l2_info(&dev->v4l2_dev, "V4L2 device registered as %s\n",
1343                   video_device_node_name(vfd));
1344         return 0;
1345
1346 unreg_dev:
1347         v4l2_ctrl_handler_free(hdl);
1348         v4l2_device_unregister(&dev->v4l2_dev);
1349 free_dev:
1350         kfree(dev);
1351         return ret;
1352 }
1353
1354 /* This routine allocates from 1 to n_devs virtual drivers.
1355
1356    The real maximum number of virtual drivers will depend on how many drivers
1357    will succeed. This is limited to the maximum number of devices that
1358    videodev supports, which is equal to VIDEO_NUM_DEVICES.
1359  */
1360 static int __init vivi_init(void)
1361 {
1362         const struct font_desc *font = find_font("VGA8x16");
1363         int ret = 0, i;
1364
1365         if (font == NULL) {
1366                 printk(KERN_ERR "vivi: could not find font\n");
1367                 return -ENODEV;
1368         }
1369         font8x16 = font->data;
1370
1371         if (n_devs <= 0)
1372                 n_devs = 1;
1373
1374         for (i = 0; i < n_devs; i++) {
1375                 ret = vivi_create_instance(i);
1376                 if (ret) {
1377                         /* If some instantiations succeeded, keep driver */
1378                         if (i)
1379                                 ret = 0;
1380                         break;
1381                 }
1382         }
1383
1384         if (ret < 0) {
1385                 printk(KERN_ERR "vivi: error %d while loading driver\n", ret);
1386                 return ret;
1387         }
1388
1389         printk(KERN_INFO "Video Technology Magazine Virtual Video "
1390                         "Capture Board ver %s successfully loaded.\n",
1391                         VIVI_VERSION);
1392
1393         /* n_devs will reflect the actual number of allocated devices */
1394         n_devs = i;
1395
1396         return ret;
1397 }
1398
1399 static void __exit vivi_exit(void)
1400 {
1401         vivi_release();
1402 }
1403
1404 module_init(vivi_init);
1405 module_exit(vivi_exit);