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