V4L/DVB: vivi and mem2mem_testdev need slab.h to build
[safe/jmp/linux-2.6] / drivers / media / video / 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  * This program is free software; you can redistribute it and/or modify
11  * it under the terms of the BSD Licence, GNU General Public License
12  * as published by the Free Software Foundation; either version 2 of the
13  * License, or (at your option) any later version
14  */
15 #include <linux/module.h>
16 #include <linux/errno.h>
17 #include <linux/kernel.h>
18 #include <linux/init.h>
19 #include <linux/sched.h>
20 #include <linux/slab.h>
21 #include <linux/font.h>
22 #include <linux/version.h>
23 #include <linux/mutex.h>
24 #include <linux/videodev2.h>
25 #include <linux/kthread.h>
26 #if LINUX_VERSION_CODE >= KERNEL_VERSION(2, 6, 20)
27 #include <linux/freezer.h>
28 #endif
29 #include <media/videobuf-vmalloc.h>
30 #include <media/v4l2-device.h>
31 #include <media/v4l2-ioctl.h>
32 #include <media/v4l2-common.h>
33
34 #define VIVI_MODULE_NAME "vivi"
35
36 /* Wake up at about 30 fps */
37 #define WAKE_NUMERATOR 30
38 #define WAKE_DENOMINATOR 1001
39 #define BUFFER_TIMEOUT     msecs_to_jiffies(500)  /* 0.5 seconds */
40
41 #define MAX_WIDTH 1920
42 #define MAX_HEIGHT 1200
43
44 #define VIVI_MAJOR_VERSION 0
45 #define VIVI_MINOR_VERSION 7
46 #define VIVI_RELEASE 0
47 #define VIVI_VERSION \
48         KERNEL_VERSION(VIVI_MAJOR_VERSION, VIVI_MINOR_VERSION, VIVI_RELEASE)
49
50 MODULE_DESCRIPTION("Video Technology Magazine Virtual Video Capture Board");
51 MODULE_AUTHOR("Mauro Carvalho Chehab, Ted Walther and John Sokol");
52 MODULE_LICENSE("Dual BSD/GPL");
53
54 static unsigned video_nr = -1;
55 module_param(video_nr, uint, 0644);
56 MODULE_PARM_DESC(video_nr, "videoX start number, -1 is autodetect");
57
58 static unsigned n_devs = 1;
59 module_param(n_devs, uint, 0644);
60 MODULE_PARM_DESC(n_devs, "number of video devices to create");
61
62 static unsigned debug;
63 module_param(debug, uint, 0644);
64 MODULE_PARM_DESC(debug, "activates debug info");
65
66 static unsigned int vid_limit = 16;
67 module_param(vid_limit, uint, 0644);
68 MODULE_PARM_DESC(vid_limit, "capture memory limit in megabytes");
69
70 /* Global font descriptor */
71 static const u8 *font8x16;
72
73 #define dprintk(dev, level, fmt, arg...) \
74         v4l2_dbg(level, debug, &dev->v4l2_dev, fmt, ## arg)
75
76 /* ------------------------------------------------------------------
77         Basic structures
78    ------------------------------------------------------------------*/
79
80 struct vivi_fmt {
81         char  *name;
82         u32   fourcc;          /* v4l2 format id */
83         int   depth;
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         },
92         {
93                 .name     = "4:2:2, packed, UYVY",
94                 .fourcc   = V4L2_PIX_FMT_UYVY,
95                 .depth    = 16,
96         },
97         {
98                 .name     = "RGB565 (LE)",
99                 .fourcc   = V4L2_PIX_FMT_RGB565, /* gggbbbbb rrrrrggg */
100                 .depth    = 16,
101         },
102         {
103                 .name     = "RGB565 (BE)",
104                 .fourcc   = V4L2_PIX_FMT_RGB565X, /* rrrrrggg gggbbbbb */
105                 .depth    = 16,
106         },
107         {
108                 .name     = "RGB555 (LE)",
109                 .fourcc   = V4L2_PIX_FMT_RGB555, /* gggbbbbb arrrrrgg */
110                 .depth    = 16,
111         },
112         {
113                 .name     = "RGB555 (BE)",
114                 .fourcc   = V4L2_PIX_FMT_RGB555X, /* arrrrrgg gggbbbbb */
115                 .depth    = 16,
116         },
117 };
118
119 static struct vivi_fmt *get_format(struct v4l2_format *f)
120 {
121         struct vivi_fmt *fmt;
122         unsigned int k;
123
124         for (k = 0; k < ARRAY_SIZE(formats); k++) {
125                 fmt = &formats[k];
126                 if (fmt->fourcc == f->fmt.pix.pixelformat)
127                         break;
128         }
129
130         if (k == ARRAY_SIZE(formats))
131                 return NULL;
132
133         return &formats[k];
134 }
135
136 struct sg_to_addr {
137         int pos;
138         struct scatterlist *sg;
139 };
140
141 /* buffer for one video frame */
142 struct vivi_buffer {
143         /* common v4l buffer stuff -- must be first */
144         struct videobuf_buffer vb;
145
146         struct vivi_fmt        *fmt;
147 };
148
149 struct vivi_dmaqueue {
150         struct list_head       active;
151
152         /* thread for generating video stream*/
153         struct task_struct         *kthread;
154         wait_queue_head_t          wq;
155         /* Counters to control fps rate */
156         int                        frame;
157         int                        ini_jiffies;
158 };
159
160 static LIST_HEAD(vivi_devlist);
161
162 struct vivi_dev {
163         struct list_head           vivi_devlist;
164         struct v4l2_device         v4l2_dev;
165
166         /* controls */
167         int                        brightness;
168         int                        contrast;
169         int                        saturation;
170         int                        hue;
171         int                        volume;
172
173         spinlock_t                 slock;
174         struct mutex               mutex;
175
176         /* various device info */
177         struct video_device        *vfd;
178
179         struct vivi_dmaqueue       vidq;
180
181         /* Several counters */
182         unsigned                   ms;
183         unsigned long              jiffies;
184
185         int                        mv_count;    /* Controls bars movement */
186
187         /* Input Number */
188         int                        input;
189
190         /* video capture */
191         struct vivi_fmt            *fmt;
192         unsigned int               width, height;
193         struct videobuf_queue      vb_vidq;
194
195         unsigned long              generating;
196         u8                         bars[9][3];
197         u8                         line[MAX_WIDTH * 4];
198 };
199
200 /* ------------------------------------------------------------------
201         DMA and thread functions
202    ------------------------------------------------------------------*/
203
204 /* Bars and Colors should match positions */
205
206 enum colors {
207         WHITE,
208         AMBER,
209         CYAN,
210         GREEN,
211         MAGENTA,
212         RED,
213         BLUE,
214         BLACK,
215         TEXT_BLACK,
216 };
217
218 /* R   G   B */
219 #define COLOR_WHITE     {204, 204, 204}
220 #define COLOR_AMBER     {208, 208,   0}
221 #define COLOR_CYAN      {  0, 206, 206}
222 #define COLOR_GREEN     {  0, 239,   0}
223 #define COLOR_MAGENTA   {239,   0, 239}
224 #define COLOR_RED       {205,   0,   0}
225 #define COLOR_BLUE      {  0,   0, 255}
226 #define COLOR_BLACK     {  0,   0,   0}
227
228 struct bar_std {
229         u8 bar[9][3];
230 };
231
232 /* Maximum number of bars are 10 - otherwise, the input print code
233    should be modified */
234 static struct bar_std bars[] = {
235         {       /* Standard ITU-R color bar sequence */
236                 { COLOR_WHITE, COLOR_AMBER, COLOR_CYAN, COLOR_GREEN,
237                   COLOR_MAGENTA, COLOR_RED, COLOR_BLUE, COLOR_BLACK, COLOR_BLACK }
238         }, {
239                 { COLOR_WHITE, COLOR_AMBER, COLOR_BLACK, COLOR_WHITE,
240                   COLOR_AMBER, COLOR_BLACK, COLOR_WHITE, COLOR_AMBER, COLOR_BLACK }
241         }, {
242                 { COLOR_WHITE, COLOR_CYAN, COLOR_BLACK, COLOR_WHITE,
243                   COLOR_CYAN, COLOR_BLACK, COLOR_WHITE, COLOR_CYAN, COLOR_BLACK }
244         }, {
245                 { COLOR_WHITE, COLOR_GREEN, COLOR_BLACK, COLOR_WHITE,
246                   COLOR_GREEN, COLOR_BLACK, COLOR_WHITE, COLOR_GREEN, COLOR_BLACK }
247         },
248 };
249
250 #define NUM_INPUTS ARRAY_SIZE(bars)
251
252 #define TO_Y(r, g, b) \
253         (((16829 * r + 33039 * g + 6416 * b  + 32768) >> 16) + 16)
254 /* RGB to  V(Cr) Color transform */
255 #define TO_V(r, g, b) \
256         (((28784 * r - 24103 * g - 4681 * b  + 32768) >> 16) + 128)
257 /* RGB to  U(Cb) Color transform */
258 #define TO_U(r, g, b) \
259         (((-9714 * r - 19070 * g + 28784 * b + 32768) >> 16) + 128)
260
261 /* precalculate color bar values to speed up rendering */
262 static void precalculate_bars(struct vivi_dev *dev)
263 {
264         u8 r, g, b;
265         int k, is_yuv;
266
267         for (k = 0; k < 9; k++) {
268                 r = bars[dev->input].bar[k][0];
269                 g = bars[dev->input].bar[k][1];
270                 b = bars[dev->input].bar[k][2];
271                 is_yuv = 0;
272
273                 switch (dev->fmt->fourcc) {
274                 case V4L2_PIX_FMT_YUYV:
275                 case V4L2_PIX_FMT_UYVY:
276                         is_yuv = 1;
277                         break;
278                 case V4L2_PIX_FMT_RGB565:
279                 case V4L2_PIX_FMT_RGB565X:
280                         r >>= 3;
281                         g >>= 2;
282                         b >>= 3;
283                         break;
284                 case V4L2_PIX_FMT_RGB555:
285                 case V4L2_PIX_FMT_RGB555X:
286                         r >>= 3;
287                         g >>= 3;
288                         b >>= 3;
289                         break;
290                 }
291
292                 if (is_yuv) {
293                         dev->bars[k][0] = TO_Y(r, g, b);        /* Luma */
294                         dev->bars[k][1] = TO_U(r, g, b);        /* Cb */
295                         dev->bars[k][2] = TO_V(r, g, b);        /* Cr */
296                 } else {
297                         dev->bars[k][0] = r;
298                         dev->bars[k][1] = g;
299                         dev->bars[k][2] = b;
300                 }
301         }
302 }
303
304 #define TSTAMP_MIN_Y    24
305 #define TSTAMP_MAX_Y    (TSTAMP_MIN_Y + 15)
306 #define TSTAMP_INPUT_X  10
307 #define TSTAMP_MIN_X    (54 + TSTAMP_INPUT_X)
308
309 static void gen_twopix(struct vivi_dev *dev, u8 *buf, int colorpos)
310 {
311         u8 r_y, g_u, b_v;
312         int color;
313         u8 *p;
314
315         r_y = dev->bars[colorpos][0]; /* R or precalculated Y */
316         g_u = dev->bars[colorpos][1]; /* G or precalculated U */
317         b_v = dev->bars[colorpos][2]; /* B or precalculated V */
318
319         for (color = 0; color < 4; color++) {
320                 p = buf + color;
321
322                 switch (dev->fmt->fourcc) {
323                 case V4L2_PIX_FMT_YUYV:
324                         switch (color) {
325                         case 0:
326                         case 2:
327                                 *p = r_y;
328                                 break;
329                         case 1:
330                                 *p = g_u;
331                                 break;
332                         case 3:
333                                 *p = b_v;
334                                 break;
335                         }
336                         break;
337                 case V4L2_PIX_FMT_UYVY:
338                         switch (color) {
339                         case 1:
340                         case 3:
341                                 *p = r_y;
342                                 break;
343                         case 0:
344                                 *p = g_u;
345                                 break;
346                         case 2:
347                                 *p = b_v;
348                                 break;
349                         }
350                         break;
351                 case V4L2_PIX_FMT_RGB565:
352                         switch (color) {
353                         case 0:
354                         case 2:
355                                 *p = (g_u << 5) | b_v;
356                                 break;
357                         case 1:
358                         case 3:
359                                 *p = (r_y << 3) | (g_u >> 3);
360                                 break;
361                         }
362                         break;
363                 case V4L2_PIX_FMT_RGB565X:
364                         switch (color) {
365                         case 0:
366                         case 2:
367                                 *p = (r_y << 3) | (g_u >> 3);
368                                 break;
369                         case 1:
370                         case 3:
371                                 *p = (g_u << 5) | b_v;
372                                 break;
373                         }
374                         break;
375                 case V4L2_PIX_FMT_RGB555:
376                         switch (color) {
377                         case 0:
378                         case 2:
379                                 *p = (g_u << 5) | b_v;
380                                 break;
381                         case 1:
382                         case 3:
383                                 *p = (r_y << 2) | (g_u >> 3);
384                                 break;
385                         }
386                         break;
387                 case V4L2_PIX_FMT_RGB555X:
388                         switch (color) {
389                         case 0:
390                         case 2:
391                                 *p = (r_y << 2) | (g_u >> 3);
392                                 break;
393                         case 1:
394                         case 3:
395                                 *p = (g_u << 5) | b_v;
396                                 break;
397                         }
398                         break;
399                 }
400         }
401 }
402
403 static void precalculate_line(struct vivi_dev *dev)
404 {
405         int w;
406
407         for (w = 0; w < dev->width * 2; w += 2) {
408                 int colorpos = (w / (dev->width / 8) % 8);
409
410                 gen_twopix(dev, dev->line + w * 2, colorpos);
411         }
412 }
413
414 static void gen_text(struct vivi_dev *dev, char *basep,
415                                         int y, int x, char *text)
416 {
417         int line;
418
419         /* Checks if it is possible to show string */
420         if (y + 16 >= dev->height || x + strlen(text) * 8 >= dev->width)
421                 return;
422
423         /* Print stream time */
424         for (line = y; line < y + 16; line++) {
425                 int j = 0;
426                 char *pos = basep + line * dev->width * 2 + x * 2;
427                 char *s;
428
429                 for (s = text; *s; s++) {
430                         u8 chr = font8x16[*s * 16 + line - y];
431                         int i;
432
433                         for (i = 0; i < 7; i++, j++) {
434                                 /* Draw white font on black background */
435                                 if (chr & (1 << (7 - i)))
436                                         gen_twopix(dev, pos + j * 2, WHITE);
437                                 else
438                                         gen_twopix(dev, pos + j * 2, TEXT_BLACK);
439                         }
440                 }
441         }
442 }
443
444 static void vivi_fillbuff(struct vivi_dev *dev, struct vivi_buffer *buf)
445 {
446         int hmax = buf->vb.height;
447         int wmax = buf->vb.width;
448         struct timeval ts;
449         void *vbuf = videobuf_to_vmalloc(&buf->vb);
450         unsigned ms;
451         char str[100];
452         int h, line = 1;
453
454         if (!vbuf)
455                 return;
456
457         for (h = 0; h < hmax; h++)
458                 memcpy(vbuf + h * wmax * 2, dev->line + (dev->mv_count % wmax) * 2, wmax * 2);
459
460         /* Updates stream time */
461
462         dev->ms += jiffies_to_msecs(jiffies - dev->jiffies);
463         dev->jiffies = jiffies;
464         ms = dev->ms;
465         snprintf(str, sizeof(str), " %02d:%02d:%02d:%03d ",
466                         (ms / (60 * 60 * 1000)) % 24,
467                         (ms / (60 * 1000)) % 60,
468                         (ms / 1000) % 60,
469                         ms % 1000);
470         gen_text(dev, vbuf, line++ * 16, 16, str);
471         snprintf(str, sizeof(str), " %dx%d, input %d ",
472                         dev->width, dev->height, dev->input);
473         gen_text(dev, vbuf, line++ * 16, 16, str);
474
475         snprintf(str, sizeof(str), " brightness %3d, contrast %3d, saturation %3d, hue %d ",
476                         dev->brightness,
477                         dev->contrast,
478                         dev->saturation,
479                         dev->hue);
480         gen_text(dev, vbuf, line++ * 16, 16, str);
481         snprintf(str, sizeof(str), " volume %3d ", dev->volume);
482         gen_text(dev, vbuf, line++ * 16, 16, str);
483
484         dev->mv_count += 2;
485
486         /* Advice that buffer was filled */
487         buf->vb.field_count++;
488         do_gettimeofday(&ts);
489         buf->vb.ts = ts;
490         buf->vb.state = VIDEOBUF_DONE;
491 }
492
493 static void vivi_thread_tick(struct vivi_dev *dev)
494 {
495         struct vivi_dmaqueue *dma_q = &dev->vidq;
496         struct vivi_buffer *buf;
497         unsigned long flags = 0;
498
499         dprintk(dev, 1, "Thread tick\n");
500
501         spin_lock_irqsave(&dev->slock, flags);
502         if (list_empty(&dma_q->active)) {
503                 dprintk(dev, 1, "No active queue to serve\n");
504                 goto unlock;
505         }
506
507         buf = list_entry(dma_q->active.next,
508                          struct vivi_buffer, vb.queue);
509
510         /* Nobody is waiting on this buffer, return */
511         if (!waitqueue_active(&buf->vb.done))
512                 goto unlock;
513
514         list_del(&buf->vb.queue);
515
516         do_gettimeofday(&buf->vb.ts);
517
518         /* Fill buffer */
519         vivi_fillbuff(dev, buf);
520         dprintk(dev, 1, "filled buffer %p\n", buf);
521
522         wake_up(&buf->vb.done);
523         dprintk(dev, 2, "[%p/%d] wakeup\n", buf, buf->vb. i);
524 unlock:
525         spin_unlock_irqrestore(&dev->slock, flags);
526 }
527
528 #define frames_to_ms(frames)                                    \
529         ((frames * WAKE_NUMERATOR * 1000) / WAKE_DENOMINATOR)
530
531 static void vivi_sleep(struct vivi_dev *dev)
532 {
533         struct vivi_dmaqueue *dma_q = &dev->vidq;
534         int timeout;
535         DECLARE_WAITQUEUE(wait, current);
536
537         dprintk(dev, 1, "%s dma_q=0x%08lx\n", __func__,
538                 (unsigned long)dma_q);
539
540         add_wait_queue(&dma_q->wq, &wait);
541         if (kthread_should_stop())
542                 goto stop_task;
543
544         /* Calculate time to wake up */
545         timeout = msecs_to_jiffies(frames_to_ms(1));
546
547         vivi_thread_tick(dev);
548
549         schedule_timeout_interruptible(timeout);
550
551 stop_task:
552         remove_wait_queue(&dma_q->wq, &wait);
553         try_to_freeze();
554 }
555
556 static int vivi_thread(void *data)
557 {
558         struct vivi_dev *dev = data;
559
560         dprintk(dev, 1, "thread started\n");
561
562         set_freezable();
563
564         for (;;) {
565                 vivi_sleep(dev);
566
567                 if (kthread_should_stop())
568                         break;
569         }
570         dprintk(dev, 1, "thread: exit\n");
571         return 0;
572 }
573
574 static void vivi_start_generating(struct file *file)
575 {
576         struct vivi_dev *dev = video_drvdata(file);
577         struct vivi_dmaqueue *dma_q = &dev->vidq;
578
579         dprintk(dev, 1, "%s\n", __func__);
580
581         if (test_and_set_bit(0, &dev->generating))
582                 return;
583         file->private_data = dev;
584
585         /* Resets frame counters */
586         dev->ms = 0;
587         dev->mv_count = 0;
588         dev->jiffies = jiffies;
589
590         dma_q->frame = 0;
591         dma_q->ini_jiffies = jiffies;
592         dma_q->kthread = kthread_run(vivi_thread, dev, dev->v4l2_dev.name);
593
594         if (IS_ERR(dma_q->kthread)) {
595                 v4l2_err(&dev->v4l2_dev, "kernel_thread() failed\n");
596                 clear_bit(0, &dev->generating);
597                 return;
598         }
599         /* Wakes thread */
600         wake_up_interruptible(&dma_q->wq);
601
602         dprintk(dev, 1, "returning from %s\n", __func__);
603 }
604
605 static void vivi_stop_generating(struct file *file)
606 {
607         struct vivi_dev *dev = video_drvdata(file);
608         struct vivi_dmaqueue *dma_q = &dev->vidq;
609
610         dprintk(dev, 1, "%s\n", __func__);
611
612         if (!file->private_data)
613                 return;
614         if (!test_and_clear_bit(0, &dev->generating))
615                 return;
616
617         /* shutdown control thread */
618         if (dma_q->kthread) {
619                 kthread_stop(dma_q->kthread);
620                 dma_q->kthread = NULL;
621         }
622         videobuf_stop(&dev->vb_vidq);
623         videobuf_mmap_free(&dev->vb_vidq);
624 }
625
626 static int vivi_is_generating(struct vivi_dev *dev)
627 {
628         return test_bit(0, &dev->generating);
629 }
630
631 /* ------------------------------------------------------------------
632         Videobuf operations
633    ------------------------------------------------------------------*/
634 static int
635 buffer_setup(struct videobuf_queue *vq, unsigned int *count, unsigned int *size)
636 {
637         struct vivi_dev *dev = vq->priv_data;
638
639         *size = dev->width * dev->height * 2;
640
641         if (0 == *count)
642                 *count = 32;
643
644         while (*size * *count > vid_limit * 1024 * 1024)
645                 (*count)--;
646
647         dprintk(dev, 1, "%s, count=%d, size=%d\n", __func__,
648                 *count, *size);
649
650         return 0;
651 }
652
653 static void free_buffer(struct videobuf_queue *vq, struct vivi_buffer *buf)
654 {
655         struct vivi_dev *dev = vq->priv_data;
656
657         dprintk(dev, 1, "%s, state: %i\n", __func__, buf->vb.state);
658
659         videobuf_vmalloc_free(&buf->vb);
660         dprintk(dev, 1, "free_buffer: freed\n");
661         buf->vb.state = VIDEOBUF_NEEDS_INIT;
662 }
663
664 static int
665 buffer_prepare(struct videobuf_queue *vq, struct videobuf_buffer *vb,
666                                                 enum v4l2_field field)
667 {
668         struct vivi_dev *dev = vq->priv_data;
669         struct vivi_buffer *buf = container_of(vb, struct vivi_buffer, vb);
670         int rc;
671
672         dprintk(dev, 1, "%s, field=%d\n", __func__, field);
673
674         BUG_ON(NULL == dev->fmt);
675
676         if (dev->width  < 48 || dev->width  > MAX_WIDTH ||
677             dev->height < 32 || dev->height > MAX_HEIGHT)
678                 return -EINVAL;
679
680         buf->vb.size = dev->width * dev->height * 2;
681         if (0 != buf->vb.baddr && buf->vb.bsize < buf->vb.size)
682                 return -EINVAL;
683
684         /* These properties only change when queue is idle, see s_fmt */
685         buf->fmt       = dev->fmt;
686         buf->vb.width  = dev->width;
687         buf->vb.height = dev->height;
688         buf->vb.field  = field;
689
690         precalculate_bars(dev);
691         precalculate_line(dev);
692
693         if (VIDEOBUF_NEEDS_INIT == buf->vb.state) {
694                 rc = videobuf_iolock(vq, &buf->vb, NULL);
695                 if (rc < 0)
696                         goto fail;
697         }
698
699         buf->vb.state = VIDEOBUF_PREPARED;
700         return 0;
701
702 fail:
703         free_buffer(vq, buf);
704         return rc;
705 }
706
707 static void
708 buffer_queue(struct videobuf_queue *vq, struct videobuf_buffer *vb)
709 {
710         struct vivi_dev *dev = vq->priv_data;
711         struct vivi_buffer *buf = container_of(vb, struct vivi_buffer, vb);
712         struct vivi_dmaqueue *vidq = &dev->vidq;
713
714         dprintk(dev, 1, "%s\n", __func__);
715
716         buf->vb.state = VIDEOBUF_QUEUED;
717         list_add_tail(&buf->vb.queue, &vidq->active);
718 }
719
720 static void buffer_release(struct videobuf_queue *vq,
721                            struct videobuf_buffer *vb)
722 {
723         struct vivi_dev *dev = vq->priv_data;
724         struct vivi_buffer *buf  = container_of(vb, struct vivi_buffer, vb);
725
726         dprintk(dev, 1, "%s\n", __func__);
727
728         free_buffer(vq, buf);
729 }
730
731 static struct videobuf_queue_ops vivi_video_qops = {
732         .buf_setup      = buffer_setup,
733         .buf_prepare    = buffer_prepare,
734         .buf_queue      = buffer_queue,
735         .buf_release    = buffer_release,
736 };
737
738 /* ------------------------------------------------------------------
739         IOCTL vidioc handling
740    ------------------------------------------------------------------*/
741 static int vidioc_querycap(struct file *file, void  *priv,
742                                         struct v4l2_capability *cap)
743 {
744         struct vivi_dev *dev = video_drvdata(file);
745
746         strcpy(cap->driver, "vivi");
747         strcpy(cap->card, "vivi");
748         strlcpy(cap->bus_info, dev->v4l2_dev.name, sizeof(cap->bus_info));
749         cap->version = VIVI_VERSION;
750         cap->capabilities = V4L2_CAP_VIDEO_CAPTURE | V4L2_CAP_STREAMING | \
751                             V4L2_CAP_READWRITE;
752         return 0;
753 }
754
755 static int vidioc_enum_fmt_vid_cap(struct file *file, void  *priv,
756                                         struct v4l2_fmtdesc *f)
757 {
758         struct vivi_fmt *fmt;
759
760         if (f->index >= ARRAY_SIZE(formats))
761                 return -EINVAL;
762
763         fmt = &formats[f->index];
764
765         strlcpy(f->description, fmt->name, sizeof(f->description));
766         f->pixelformat = fmt->fourcc;
767         return 0;
768 }
769
770 static int vidioc_g_fmt_vid_cap(struct file *file, void *priv,
771                                         struct v4l2_format *f)
772 {
773         struct vivi_dev *dev = video_drvdata(file);
774
775         f->fmt.pix.width        = dev->width;
776         f->fmt.pix.height       = dev->height;
777         f->fmt.pix.field        = dev->vb_vidq.field;
778         f->fmt.pix.pixelformat  = dev->fmt->fourcc;
779         f->fmt.pix.bytesperline =
780                 (f->fmt.pix.width * dev->fmt->depth) >> 3;
781         f->fmt.pix.sizeimage =
782                 f->fmt.pix.height * f->fmt.pix.bytesperline;
783         return 0;
784 }
785
786 static int vidioc_try_fmt_vid_cap(struct file *file, void *priv,
787                         struct v4l2_format *f)
788 {
789         struct vivi_dev *dev = video_drvdata(file);
790         struct vivi_fmt *fmt;
791         enum v4l2_field field;
792
793         fmt = get_format(f);
794         if (!fmt) {
795                 dprintk(dev, 1, "Fourcc format (0x%08x) invalid.\n",
796                         f->fmt.pix.pixelformat);
797                 return -EINVAL;
798         }
799
800         field = f->fmt.pix.field;
801
802         if (field == V4L2_FIELD_ANY) {
803                 field = V4L2_FIELD_INTERLACED;
804         } else if (V4L2_FIELD_INTERLACED != field) {
805                 dprintk(dev, 1, "Field type invalid.\n");
806                 return -EINVAL;
807         }
808
809         f->fmt.pix.field = field;
810         v4l_bound_align_image(&f->fmt.pix.width, 48, MAX_WIDTH, 2,
811                               &f->fmt.pix.height, 32, MAX_HEIGHT, 0, 0);
812         f->fmt.pix.bytesperline =
813                 (f->fmt.pix.width * fmt->depth) >> 3;
814         f->fmt.pix.sizeimage =
815                 f->fmt.pix.height * f->fmt.pix.bytesperline;
816         return 0;
817 }
818
819 static int vidioc_s_fmt_vid_cap(struct file *file, void *priv,
820                                         struct v4l2_format *f)
821 {
822         struct vivi_dev *dev = video_drvdata(file);
823         struct videobuf_queue *q = &dev->vb_vidq;
824
825         int ret = vidioc_try_fmt_vid_cap(file, priv, f);
826         if (ret < 0)
827                 return ret;
828
829         mutex_lock(&q->vb_lock);
830
831         if (vivi_is_generating(dev)) {
832                 dprintk(dev, 1, "%s device busy\n", __func__);
833                 ret = -EBUSY;
834                 goto out;
835         }
836
837         dev->fmt = get_format(f);
838         dev->width = f->fmt.pix.width;
839         dev->height = f->fmt.pix.height;
840         dev->vb_vidq.field = f->fmt.pix.field;
841         ret = 0;
842 out:
843         mutex_unlock(&q->vb_lock);
844         return ret;
845 }
846
847 static int vidioc_reqbufs(struct file *file, void *priv,
848                           struct v4l2_requestbuffers *p)
849 {
850         struct vivi_dev *dev = video_drvdata(file);
851
852         return videobuf_reqbufs(&dev->vb_vidq, p);
853 }
854
855 static int vidioc_querybuf(struct file *file, void *priv, struct v4l2_buffer *p)
856 {
857         struct vivi_dev *dev = video_drvdata(file);
858
859         return videobuf_querybuf(&dev->vb_vidq, p);
860 }
861
862 static int vidioc_qbuf(struct file *file, void *priv, struct v4l2_buffer *p)
863 {
864         struct vivi_dev *dev = video_drvdata(file);
865
866         return videobuf_qbuf(&dev->vb_vidq, p);
867 }
868
869 static int vidioc_dqbuf(struct file *file, void *priv, struct v4l2_buffer *p)
870 {
871         struct vivi_dev *dev = video_drvdata(file);
872
873         return videobuf_dqbuf(&dev->vb_vidq, p,
874                                 file->f_flags & O_NONBLOCK);
875 }
876
877 #ifdef CONFIG_VIDEO_V4L1_COMPAT
878 static int vidiocgmbuf(struct file *file, void *priv, struct video_mbuf *mbuf)
879 {
880         struct vivi_dev *dev = video_drvdata(file);
881
882         return videobuf_cgmbuf(&dev->vb_vidq, mbuf, 8);
883 }
884 #endif
885
886 static int vidioc_streamon(struct file *file, void *priv, enum v4l2_buf_type i)
887 {
888         struct vivi_dev *dev = video_drvdata(file);
889         int ret;
890
891         if (i != V4L2_BUF_TYPE_VIDEO_CAPTURE)
892                 return -EINVAL;
893         ret = videobuf_streamon(&dev->vb_vidq);
894         if (ret)
895                 return ret;
896
897         vivi_start_generating(file);
898         return 0;
899 }
900
901 static int vidioc_streamoff(struct file *file, void *priv, enum v4l2_buf_type i)
902 {
903         struct vivi_dev *dev = video_drvdata(file);
904         int ret;
905
906         if (i != V4L2_BUF_TYPE_VIDEO_CAPTURE)
907                 return -EINVAL;
908         ret = videobuf_streamoff(&dev->vb_vidq);
909         if (!ret)
910                 vivi_stop_generating(file);
911         return ret;
912 }
913
914 static int vidioc_s_std(struct file *file, void *priv, v4l2_std_id *i)
915 {
916         return 0;
917 }
918
919 /* only one input in this sample driver */
920 static int vidioc_enum_input(struct file *file, void *priv,
921                                 struct v4l2_input *inp)
922 {
923         if (inp->index >= NUM_INPUTS)
924                 return -EINVAL;
925
926         inp->type = V4L2_INPUT_TYPE_CAMERA;
927         inp->std = V4L2_STD_525_60;
928         sprintf(inp->name, "Camera %u", inp->index);
929         return 0;
930 }
931
932 static int vidioc_g_input(struct file *file, void *priv, unsigned int *i)
933 {
934         struct vivi_dev *dev = video_drvdata(file);
935
936         *i = dev->input;
937         return 0;
938 }
939
940 static int vidioc_s_input(struct file *file, void *priv, unsigned int i)
941 {
942         struct vivi_dev *dev = video_drvdata(file);
943
944         if (i >= NUM_INPUTS)
945                 return -EINVAL;
946
947         dev->input = i;
948         precalculate_bars(dev);
949         precalculate_line(dev);
950         return 0;
951 }
952
953 /* --- controls ---------------------------------------------- */
954 static int vidioc_queryctrl(struct file *file, void *priv,
955                             struct v4l2_queryctrl *qc)
956 {
957         switch (qc->id) {
958         case V4L2_CID_AUDIO_VOLUME:
959                 return v4l2_ctrl_query_fill(qc, 0, 255, 1, 200);
960         case V4L2_CID_BRIGHTNESS:
961                 return v4l2_ctrl_query_fill(qc, 0, 255, 1, 127);
962         case V4L2_CID_CONTRAST:
963                 return v4l2_ctrl_query_fill(qc, 0, 255, 1, 16);
964         case V4L2_CID_SATURATION:
965                 return v4l2_ctrl_query_fill(qc, 0, 255, 1, 127);
966         case V4L2_CID_HUE:
967                 return v4l2_ctrl_query_fill(qc, -128, 127, 1, 0);
968         }
969         return -EINVAL;
970 }
971
972 static int vidioc_g_ctrl(struct file *file, void *priv,
973                          struct v4l2_control *ctrl)
974 {
975         struct vivi_dev *dev = video_drvdata(file);
976
977         switch (ctrl->id) {
978         case V4L2_CID_AUDIO_VOLUME:
979                 ctrl->value = dev->volume;
980                 return 0;
981         case V4L2_CID_BRIGHTNESS:
982                 ctrl->value = dev->brightness;
983                 return 0;
984         case V4L2_CID_CONTRAST:
985                 ctrl->value = dev->contrast;
986                 return 0;
987         case V4L2_CID_SATURATION:
988                 ctrl->value = dev->saturation;
989                 return 0;
990         case V4L2_CID_HUE:
991                 ctrl->value = dev->hue;
992                 return 0;
993         }
994         return -EINVAL;
995 }
996
997 static int vidioc_s_ctrl(struct file *file, void *priv,
998                                 struct v4l2_control *ctrl)
999 {
1000         struct vivi_dev *dev = video_drvdata(file);
1001         struct v4l2_queryctrl qc;
1002         int err;
1003
1004         qc.id = ctrl->id;
1005         err = vidioc_queryctrl(file, priv, &qc);
1006         if (err < 0)
1007                 return err;
1008         if (ctrl->value < qc.minimum || ctrl->value > qc.maximum)
1009                 return -ERANGE;
1010         switch (ctrl->id) {
1011         case V4L2_CID_AUDIO_VOLUME:
1012                 dev->volume = ctrl->value;
1013                 return 0;
1014         case V4L2_CID_BRIGHTNESS:
1015                 dev->brightness = ctrl->value;
1016                 return 0;
1017         case V4L2_CID_CONTRAST:
1018                 dev->contrast = ctrl->value;
1019                 return 0;
1020         case V4L2_CID_SATURATION:
1021                 dev->saturation = ctrl->value;
1022                 return 0;
1023         case V4L2_CID_HUE:
1024                 dev->hue = ctrl->value;
1025                 return 0;
1026         }
1027         return -EINVAL;
1028 }
1029
1030 /* ------------------------------------------------------------------
1031         File operations for the device
1032    ------------------------------------------------------------------*/
1033
1034 static ssize_t
1035 vivi_read(struct file *file, char __user *data, size_t count, loff_t *ppos)
1036 {
1037         struct vivi_dev *dev = video_drvdata(file);
1038
1039         vivi_start_generating(file);
1040         return videobuf_read_stream(&dev->vb_vidq, data, count, ppos, 0,
1041                                         file->f_flags & O_NONBLOCK);
1042 }
1043
1044 static unsigned int
1045 vivi_poll(struct file *file, struct poll_table_struct *wait)
1046 {
1047         struct vivi_dev *dev = video_drvdata(file);
1048         struct videobuf_queue *q = &dev->vb_vidq;
1049
1050         dprintk(dev, 1, "%s\n", __func__);
1051
1052         vivi_start_generating(file);
1053         return videobuf_poll_stream(file, q, wait);
1054 }
1055
1056 static int vivi_close(struct file *file)
1057 {
1058         struct video_device  *vdev = video_devdata(file);
1059         struct vivi_dev *dev = video_drvdata(file);
1060
1061         vivi_stop_generating(file);
1062
1063         dprintk(dev, 1, "close called (dev=%s)\n",
1064                 video_device_node_name(vdev));
1065         return 0;
1066 }
1067
1068 static int vivi_mmap(struct file *file, struct vm_area_struct *vma)
1069 {
1070         struct vivi_dev *dev = video_drvdata(file);
1071         int ret;
1072
1073         dprintk(dev, 1, "mmap called, vma=0x%08lx\n", (unsigned long)vma);
1074
1075         ret = videobuf_mmap_mapper(&dev->vb_vidq, vma);
1076
1077         dprintk(dev, 1, "vma start=0x%08lx, size=%ld, ret=%d\n",
1078                 (unsigned long)vma->vm_start,
1079                 (unsigned long)vma->vm_end - (unsigned long)vma->vm_start,
1080                 ret);
1081         return ret;
1082 }
1083
1084 static const struct v4l2_file_operations vivi_fops = {
1085         .owner          = THIS_MODULE,
1086         .release        = vivi_close,
1087         .read           = vivi_read,
1088         .poll           = vivi_poll,
1089         .ioctl          = video_ioctl2, /* V4L2 ioctl handler */
1090         .mmap           = vivi_mmap,
1091 };
1092
1093 static const struct v4l2_ioctl_ops vivi_ioctl_ops = {
1094         .vidioc_querycap      = vidioc_querycap,
1095         .vidioc_enum_fmt_vid_cap  = vidioc_enum_fmt_vid_cap,
1096         .vidioc_g_fmt_vid_cap     = vidioc_g_fmt_vid_cap,
1097         .vidioc_try_fmt_vid_cap   = vidioc_try_fmt_vid_cap,
1098         .vidioc_s_fmt_vid_cap     = vidioc_s_fmt_vid_cap,
1099         .vidioc_reqbufs       = vidioc_reqbufs,
1100         .vidioc_querybuf      = vidioc_querybuf,
1101         .vidioc_qbuf          = vidioc_qbuf,
1102         .vidioc_dqbuf         = vidioc_dqbuf,
1103         .vidioc_s_std         = vidioc_s_std,
1104         .vidioc_enum_input    = vidioc_enum_input,
1105         .vidioc_g_input       = vidioc_g_input,
1106         .vidioc_s_input       = vidioc_s_input,
1107         .vidioc_streamon      = vidioc_streamon,
1108         .vidioc_streamoff     = vidioc_streamoff,
1109         .vidioc_queryctrl     = vidioc_queryctrl,
1110         .vidioc_g_ctrl        = vidioc_g_ctrl,
1111         .vidioc_s_ctrl        = vidioc_s_ctrl,
1112 #ifdef CONFIG_VIDEO_V4L1_COMPAT
1113         .vidiocgmbuf          = vidiocgmbuf,
1114 #endif
1115 };
1116
1117 static struct video_device vivi_template = {
1118         .name           = "vivi",
1119         .fops           = &vivi_fops,
1120         .ioctl_ops      = &vivi_ioctl_ops,
1121         .release        = video_device_release,
1122
1123         .tvnorms              = V4L2_STD_525_60,
1124         .current_norm         = V4L2_STD_NTSC_M,
1125 };
1126
1127 /* -----------------------------------------------------------------
1128         Initialization and module stuff
1129    ------------------------------------------------------------------*/
1130
1131 static int vivi_release(void)
1132 {
1133         struct vivi_dev *dev;
1134         struct list_head *list;
1135
1136         while (!list_empty(&vivi_devlist)) {
1137                 list = vivi_devlist.next;
1138                 list_del(list);
1139                 dev = list_entry(list, struct vivi_dev, vivi_devlist);
1140
1141                 v4l2_info(&dev->v4l2_dev, "unregistering %s\n",
1142                         video_device_node_name(dev->vfd));
1143                 video_unregister_device(dev->vfd);
1144                 v4l2_device_unregister(&dev->v4l2_dev);
1145                 kfree(dev);
1146         }
1147
1148         return 0;
1149 }
1150
1151 static int __init vivi_create_instance(int inst)
1152 {
1153         struct vivi_dev *dev;
1154         struct video_device *vfd;
1155         int ret;
1156
1157         dev = kzalloc(sizeof(*dev), GFP_KERNEL);
1158         if (!dev)
1159                 return -ENOMEM;
1160
1161         snprintf(dev->v4l2_dev.name, sizeof(dev->v4l2_dev.name),
1162                         "%s-%03d", VIVI_MODULE_NAME, inst);
1163         ret = v4l2_device_register(NULL, &dev->v4l2_dev);
1164         if (ret)
1165                 goto free_dev;
1166
1167         dev->fmt = &formats[0];
1168         dev->width = 640;
1169         dev->height = 480;
1170         dev->volume = 200;
1171         dev->brightness = 127;
1172         dev->contrast = 16;
1173         dev->saturation = 127;
1174         dev->hue = 0;
1175
1176         videobuf_queue_vmalloc_init(&dev->vb_vidq, &vivi_video_qops,
1177                         NULL, &dev->slock, V4L2_BUF_TYPE_VIDEO_CAPTURE,
1178                         V4L2_FIELD_INTERLACED,
1179                         sizeof(struct vivi_buffer), dev);
1180
1181         /* init video dma queues */
1182         INIT_LIST_HEAD(&dev->vidq.active);
1183         init_waitqueue_head(&dev->vidq.wq);
1184
1185         /* initialize locks */
1186         spin_lock_init(&dev->slock);
1187         mutex_init(&dev->mutex);
1188
1189         ret = -ENOMEM;
1190         vfd = video_device_alloc();
1191         if (!vfd)
1192                 goto unreg_dev;
1193
1194         *vfd = vivi_template;
1195         vfd->debug = debug;
1196         vfd->v4l2_dev = &dev->v4l2_dev;
1197
1198         ret = video_register_device(vfd, VFL_TYPE_GRABBER, video_nr);
1199         if (ret < 0)
1200                 goto rel_vdev;
1201
1202         video_set_drvdata(vfd, dev);
1203
1204         /* Now that everything is fine, let's add it to device list */
1205         list_add_tail(&dev->vivi_devlist, &vivi_devlist);
1206
1207         if (video_nr != -1)
1208                 video_nr++;
1209
1210         dev->vfd = vfd;
1211         v4l2_info(&dev->v4l2_dev, "V4L2 device registered as %s\n",
1212                   video_device_node_name(vfd));
1213         return 0;
1214
1215 rel_vdev:
1216         video_device_release(vfd);
1217 unreg_dev:
1218         v4l2_device_unregister(&dev->v4l2_dev);
1219 free_dev:
1220         kfree(dev);
1221         return ret;
1222 }
1223
1224 /* This routine allocates from 1 to n_devs virtual drivers.
1225
1226    The real maximum number of virtual drivers will depend on how many drivers
1227    will succeed. This is limited to the maximum number of devices that
1228    videodev supports, which is equal to VIDEO_NUM_DEVICES.
1229  */
1230 static int __init vivi_init(void)
1231 {
1232         const struct font_desc *font = find_font("VGA8x16");
1233         int ret = 0, i;
1234
1235         if (font == NULL) {
1236                 printk(KERN_ERR "vivi: could not find font\n");
1237                 return -ENODEV;
1238         }
1239         font8x16 = font->data;
1240
1241         if (n_devs <= 0)
1242                 n_devs = 1;
1243
1244         for (i = 0; i < n_devs; i++) {
1245                 ret = vivi_create_instance(i);
1246                 if (ret) {
1247                         /* If some instantiations succeeded, keep driver */
1248                         if (i)
1249                                 ret = 0;
1250                         break;
1251                 }
1252         }
1253
1254         if (ret < 0) {
1255                 printk(KERN_ERR "vivi: error %d while loading driver\n", ret);
1256                 return ret;
1257         }
1258
1259         printk(KERN_INFO "Video Technology Magazine Virtual Video "
1260                         "Capture Board ver %u.%u.%u successfully loaded.\n",
1261                         (VIVI_VERSION >> 16) & 0xFF, (VIVI_VERSION >> 8) & 0xFF,
1262                         VIVI_VERSION & 0xFF);
1263
1264         /* n_devs will reflect the actual number of allocated devices */
1265         n_devs = i;
1266
1267         return ret;
1268 }
1269
1270 static void __exit vivi_exit(void)
1271 {
1272         vivi_release();
1273 }
1274
1275 module_init(vivi_init);
1276 module_exit(vivi_exit);