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