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