V4L/DVB (6252): Adapt drivers to use the newer videobuf modules
[linux-2.6] / drivers / media / video / vivi.c
1 /*
2  * Virtual Video driver - This code emulates a real video device with v4l2 api
3  *
4  * Copyright (c) 2006 by:
5  *      Mauro Carvalho Chehab <mchehab--a.t--infradead.org>
6  *      Ted Walther <ted--a.t--enumera.com>
7  *      John Sokol <sokol--a.t--videotechnology.com>
8  *      http://v4l.videotechnology.com/
9  *
10  * This program is free software; you can redistribute it and/or modify
11  * it under the terms of the BSD Licence, GNU General Public License
12  * as published by the Free Software Foundation; either version 2 of the
13  * License, or (at your option) any later version
14  */
15 #include <linux/module.h>
16 #include <linux/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/video-buf.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
331         if (buf->vb.dma.varea) {
332                 tmpbuf=kmalloc (wmax*2, GFP_KERNEL);
333         } else {
334                 tmpbuf=buf->vb.dma.vmalloc;
335         }
336
337
338         for (h=0;h<hmax;h++) {
339                 if (buf->vb.dma.varea) {
340                         gen_line(tmpbuf,0,wmax,hmax,h,dev->timestr);
341                         /* FIXME: replacing to __copy_to_user */
342                         if (copy_to_user(buf->vb.dma.varea+pos,tmpbuf,wmax*2)!=0)
343                                 dprintk(2,"vivifill copy_to_user failed.\n");
344                 } else {
345                         gen_line(tmpbuf,pos,wmax,hmax,h,dev->timestr);
346                 }
347                 pos += wmax*2;
348         }
349
350         /* Updates stream time */
351
352         dev->us+=jiffies_to_usecs(jiffies-dev->jiffies);
353         dev->jiffies=jiffies;
354         if (dev->us>=1000000) {
355                 dev->us-=1000000;
356                 dev->s++;
357                 if (dev->s>=60) {
358                         dev->s-=60;
359                         dev->m++;
360                         if (dev->m>60) {
361                                 dev->m-=60;
362                                 dev->h++;
363                                 if (dev->h>24)
364                                         dev->h-=24;
365                         }
366                 }
367         }
368         sprintf(dev->timestr,"%02d:%02d:%02d:%03d",
369                         dev->h,dev->m,dev->s,(dev->us+500)/1000);
370
371         dprintk(2,"vivifill at %s: Buffer 0x%08lx size= %d\n",dev->timestr,
372                         (unsigned long)buf->vb.dma.varea,pos);
373
374         /* Advice that buffer was filled */
375         buf->vb.state = STATE_DONE;
376         buf->vb.field_count++;
377         do_gettimeofday(&ts);
378         buf->vb.ts = ts;
379
380         list_del(&buf->vb.queue);
381         wake_up(&buf->vb.done);
382 }
383
384 static int restart_video_queue(struct vivi_dmaqueue *dma_q);
385
386 static void vivi_thread_tick(struct vivi_dmaqueue  *dma_q)
387 {
388         struct vivi_buffer    *buf;
389         struct vivi_dev *dev= container_of(dma_q,struct vivi_dev,vidq);
390
391         int bc;
392
393         /* Announces videobuf that all went ok */
394         for (bc = 0;; bc++) {
395                 if (list_empty(&dma_q->active)) {
396                         dprintk(1,"No active queue to serve\n");
397                         break;
398                 }
399
400                 buf = list_entry(dma_q->active.next,
401                                  struct vivi_buffer, vb.queue);
402
403                 /* Nobody is waiting something to be done, just return */
404                 if (!waitqueue_active(&buf->vb.done)) {
405                         mod_timer(&dma_q->timeout, jiffies+BUFFER_TIMEOUT);
406                         return;
407                 }
408
409                 do_gettimeofday(&buf->vb.ts);
410                 dprintk(2,"[%p/%d] wakeup\n",buf,buf->vb.i);
411
412                 /* Fill buffer */
413                 vivi_fillbuff(dev,buf);
414
415                 if (list_empty(&dma_q->active)) {
416                         del_timer(&dma_q->timeout);
417                 } else {
418                         mod_timer(&dma_q->timeout, jiffies+BUFFER_TIMEOUT);
419                 }
420         }
421         if (bc != 1)
422                 dprintk(1,"%s: %d buffers handled (should be 1)\n",__FUNCTION__,bc);
423 }
424
425 static void vivi_sleep(struct vivi_dmaqueue  *dma_q)
426 {
427         int timeout;
428         DECLARE_WAITQUEUE(wait, current);
429
430         dprintk(1,"%s dma_q=0x%08lx\n",__FUNCTION__,(unsigned long)dma_q);
431
432         add_wait_queue(&dma_q->wq, &wait);
433         if (!kthread_should_stop()) {
434                 dma_q->frame++;
435
436                 /* Calculate time to wake up */
437                 timeout=dma_q->ini_jiffies+msecs_to_jiffies((dma_q->frame*WAKE_NUMERATOR*1000)/WAKE_DENOMINATOR)-jiffies;
438
439                 if (timeout <= 0) {
440                         int old=dma_q->frame;
441                         dma_q->frame=(jiffies_to_msecs(jiffies-dma_q->ini_jiffies)*WAKE_DENOMINATOR)/(WAKE_NUMERATOR*1000)+1;
442
443                         timeout=dma_q->ini_jiffies+msecs_to_jiffies((dma_q->frame*WAKE_NUMERATOR*1000)/WAKE_DENOMINATOR)-jiffies;
444
445                         dprintk(1,"underrun, losed %d frames. "
446                                   "Now, frame is %d. Waking on %d jiffies\n",
447                                         dma_q->frame-old,dma_q->frame,timeout);
448                 } else
449                         dprintk(1,"will sleep for %i jiffies\n",timeout);
450
451                 vivi_thread_tick(dma_q);
452
453                 schedule_timeout_interruptible (timeout);
454         }
455
456         remove_wait_queue(&dma_q->wq, &wait);
457         try_to_freeze();
458 }
459
460 static int vivi_thread(void *data)
461 {
462         struct vivi_dmaqueue  *dma_q=data;
463
464         dprintk(1,"thread started\n");
465
466         mod_timer(&dma_q->timeout, jiffies+BUFFER_TIMEOUT);
467         set_freezable();
468
469         for (;;) {
470                 vivi_sleep(dma_q);
471
472                 if (kthread_should_stop())
473                         break;
474         }
475         dprintk(1, "thread: exit\n");
476         return 0;
477 }
478
479 static int vivi_start_thread(struct vivi_dmaqueue  *dma_q)
480 {
481         dma_q->frame=0;
482         dma_q->ini_jiffies=jiffies;
483
484         dprintk(1,"%s\n",__FUNCTION__);
485
486         dma_q->kthread = kthread_run(vivi_thread, dma_q, "vivi");
487
488         if (IS_ERR(dma_q->kthread)) {
489                 printk(KERN_ERR "vivi: kernel_thread() failed\n");
490                 return PTR_ERR(dma_q->kthread);
491         }
492         /* Wakes thread */
493         wake_up_interruptible(&dma_q->wq);
494
495         dprintk(1,"returning from %s\n",__FUNCTION__);
496         return 0;
497 }
498
499 static void vivi_stop_thread(struct vivi_dmaqueue  *dma_q)
500 {
501         dprintk(1,"%s\n",__FUNCTION__);
502         /* shutdown control thread */
503         if (dma_q->kthread) {
504                 kthread_stop(dma_q->kthread);
505                 dma_q->kthread=NULL;
506         }
507 }
508
509 static int restart_video_queue(struct vivi_dmaqueue *dma_q)
510 {
511         struct vivi_buffer *buf, *prev;
512         struct list_head *item;
513
514         dprintk(1,"%s dma_q=0x%08lx\n",__FUNCTION__,(unsigned long)dma_q);
515
516         if (!list_empty(&dma_q->active)) {
517                 buf = list_entry(dma_q->active.next, struct vivi_buffer, vb.queue);
518                 dprintk(2,"restart_queue [%p/%d]: restart dma\n",
519                         buf, buf->vb.i);
520
521                 dprintk(1,"Restarting video dma\n");
522                 vivi_stop_thread(dma_q);
523 //              vivi_start_thread(dma_q);
524
525                 /* cancel all outstanding capture / vbi requests */
526                 list_for_each(item,&dma_q->active) {
527                         buf = list_entry(item, struct vivi_buffer, vb.queue);
528
529                         list_del(&buf->vb.queue);
530                         buf->vb.state = STATE_ERROR;
531                         wake_up(&buf->vb.done);
532                 }
533                 mod_timer(&dma_q->timeout, jiffies+BUFFER_TIMEOUT);
534
535                 return 0;
536         }
537
538         prev = NULL;
539         for (;;) {
540                 if (list_empty(&dma_q->queued))
541                         return 0;
542                 buf = list_entry(dma_q->queued.next, struct vivi_buffer, vb.queue);
543                 if (NULL == prev) {
544                         list_del(&buf->vb.queue);
545                         list_add_tail(&buf->vb.queue,&dma_q->active);
546
547                         dprintk(1,"Restarting video dma\n");
548                         vivi_stop_thread(dma_q);
549                         vivi_start_thread(dma_q);
550
551                         buf->vb.state = STATE_ACTIVE;
552                         mod_timer(&dma_q->timeout, jiffies+BUFFER_TIMEOUT);
553                         dprintk(2,"[%p/%d] restart_queue - first active\n",
554                                 buf,buf->vb.i);
555
556                 } else if (prev->vb.width  == buf->vb.width  &&
557                            prev->vb.height == buf->vb.height &&
558                            prev->fmt       == buf->fmt) {
559                         list_del(&buf->vb.queue);
560                         list_add_tail(&buf->vb.queue,&dma_q->active);
561                         buf->vb.state = STATE_ACTIVE;
562                         dprintk(2,"[%p/%d] restart_queue - move to active\n",
563                                 buf,buf->vb.i);
564                 } else {
565                         return 0;
566                 }
567                 prev = buf;
568         }
569 }
570
571 static void vivi_vid_timeout(unsigned long data)
572 {
573         struct vivi_dev      *dev  = (struct vivi_dev*)data;
574         struct vivi_dmaqueue *vidq = &dev->vidq;
575         struct vivi_buffer   *buf;
576
577         while (!list_empty(&vidq->active)) {
578                 buf = list_entry(vidq->active.next, struct vivi_buffer, vb.queue);
579                 list_del(&buf->vb.queue);
580                 buf->vb.state = STATE_ERROR;
581                 wake_up(&buf->vb.done);
582                 printk("vivi/0: [%p/%d] timeout\n", buf, buf->vb.i);
583         }
584
585         restart_video_queue(vidq);
586 }
587
588 /* ------------------------------------------------------------------
589         Videobuf operations
590    ------------------------------------------------------------------*/
591 static int
592 buffer_setup(struct videobuf_queue *vq, unsigned int *count, unsigned int *size)
593 {
594         struct vivi_fh *fh = vq->priv_data;
595
596         *size = fh->width*fh->height*2;
597
598         if (0 == *count)
599                 *count = 32;
600         while (*size * *count > vid_limit * 1024 * 1024)
601                 (*count)--;
602         return 0;
603 }
604
605 static void free_buffer(struct videobuf_queue *vq, struct vivi_buffer *buf)
606 {
607         dprintk(1,"%s\n",__FUNCTION__);
608
609         if (in_interrupt())
610                 BUG();
611
612
613         videobuf_waiton(&buf->vb,0,0);
614         videobuf_dma_unmap(vq, &buf->vb.dma);
615         videobuf_dma_free(&buf->vb.dma);
616         buf->vb.state = STATE_NEEDS_INIT;
617 }
618
619 #define norm_maxw() 1024
620 #define norm_maxh() 768
621 static int
622 buffer_prepare(struct videobuf_queue *vq, struct videobuf_buffer *vb,
623                                                 enum v4l2_field field)
624 {
625         struct vivi_fh     *fh  = vq->priv_data;
626         struct vivi_buffer *buf = container_of(vb,struct vivi_buffer,vb);
627         int rc, init_buffer = 0;
628
629 //      dprintk(1,"%s, field=%d\n",__FUNCTION__,field);
630
631         BUG_ON(NULL == fh->fmt);
632         if (fh->width  < 48 || fh->width  > norm_maxw() ||
633             fh->height < 32 || fh->height > norm_maxh())
634                 return -EINVAL;
635         buf->vb.size = fh->width*fh->height*2;
636         if (0 != buf->vb.baddr  &&  buf->vb.bsize < buf->vb.size)
637                 return -EINVAL;
638
639         if (buf->fmt       != fh->fmt    ||
640             buf->vb.width  != fh->width  ||
641             buf->vb.height != fh->height ||
642         buf->vb.field  != field) {
643                 buf->fmt       = fh->fmt;
644                 buf->vb.width  = fh->width;
645                 buf->vb.height = fh->height;
646                 buf->vb.field  = field;
647                 init_buffer = 1;
648         }
649
650         if (STATE_NEEDS_INIT == buf->vb.state) {
651                 if (0 != (rc = videobuf_iolock(vq,&buf->vb,NULL)))
652                         goto fail;
653         }
654
655         buf->vb.state = STATE_PREPARED;
656
657         return 0;
658
659 fail:
660         free_buffer(vq,buf);
661         return rc;
662 }
663
664 static void
665 buffer_queue(struct videobuf_queue *vq, struct videobuf_buffer *vb)
666 {
667         struct vivi_buffer    *buf     = container_of(vb,struct vivi_buffer,vb);
668         struct vivi_fh        *fh      = vq->priv_data;
669         struct vivi_dev       *dev     = fh->dev;
670         struct vivi_dmaqueue  *vidq    = &dev->vidq;
671         struct vivi_buffer    *prev;
672
673         if (!list_empty(&vidq->queued)) {
674                 dprintk(1,"adding vb queue=0x%08lx\n",(unsigned long)&buf->vb.queue);
675                 list_add_tail(&buf->vb.queue,&vidq->queued);
676                 buf->vb.state = STATE_QUEUED;
677                 dprintk(2,"[%p/%d] buffer_queue - append to queued\n",
678                         buf, buf->vb.i);
679         } else if (list_empty(&vidq->active)) {
680                 list_add_tail(&buf->vb.queue,&vidq->active);
681
682                 buf->vb.state = STATE_ACTIVE;
683                 mod_timer(&vidq->timeout, jiffies+BUFFER_TIMEOUT);
684                 dprintk(2,"[%p/%d] buffer_queue - first active\n",
685                         buf, buf->vb.i);
686
687                 vivi_start_thread(vidq);
688         } else {
689                 prev = list_entry(vidq->active.prev, struct vivi_buffer, vb.queue);
690                 if (prev->vb.width  == buf->vb.width  &&
691                     prev->vb.height == buf->vb.height &&
692                     prev->fmt       == buf->fmt) {
693                         list_add_tail(&buf->vb.queue,&vidq->active);
694                         buf->vb.state = STATE_ACTIVE;
695                         dprintk(2,"[%p/%d] buffer_queue - append to active\n",
696                                 buf, buf->vb.i);
697
698                 } else {
699                         list_add_tail(&buf->vb.queue,&vidq->queued);
700                         buf->vb.state = STATE_QUEUED;
701                         dprintk(2,"[%p/%d] buffer_queue - first queued\n",
702                                 buf, buf->vb.i);
703                 }
704         }
705 }
706
707 static void buffer_release(struct videobuf_queue *vq, struct videobuf_buffer *vb)
708 {
709         struct vivi_buffer   *buf  = container_of(vb,struct vivi_buffer,vb);
710         struct vivi_fh       *fh   = vq->priv_data;
711         struct vivi_dev      *dev  = (struct vivi_dev*)fh->dev;
712         struct vivi_dmaqueue *vidq = &dev->vidq;
713
714         dprintk(1,"%s\n",__FUNCTION__);
715
716         vivi_stop_thread(vidq);
717
718         free_buffer(vq,buf);
719 }
720
721
722 static struct videobuf_queue_ops vivi_video_qops = {
723         .buf_setup      = buffer_setup,
724         .buf_prepare    = buffer_prepare,
725         .buf_queue      = buffer_queue,
726         .buf_release    = buffer_release,
727
728         /* Non-pci handling routines */
729 //      .vb_map_sg      = vivi_map_sg,
730 //      .vb_dma_sync_sg = vivi_dma_sync_sg,
731 //      .vb_unmap_sg    = vivi_unmap_sg,
732 };
733
734 /* ------------------------------------------------------------------
735         IOCTL handling
736    ------------------------------------------------------------------*/
737
738
739 static int res_get(struct vivi_dev *dev, struct vivi_fh *fh)
740 {
741         /* is it free? */
742         mutex_lock(&dev->lock);
743         if (dev->resources) {
744                 /* no, someone else uses it */
745                 mutex_unlock(&dev->lock);
746                 return 0;
747         }
748         /* it's free, grab it */
749         dev->resources =1;
750         dprintk(1,"res: get\n");
751         mutex_unlock(&dev->lock);
752         return 1;
753 }
754
755 static int res_locked(struct vivi_dev *dev)
756 {
757         return (dev->resources);
758 }
759
760 static void res_free(struct vivi_dev *dev, struct vivi_fh *fh)
761 {
762         mutex_lock(&dev->lock);
763         dev->resources = 0;
764         dprintk(1,"res: put\n");
765         mutex_lock(&dev->lock);
766 }
767
768 /* ------------------------------------------------------------------
769         IOCTL vidioc handling
770    ------------------------------------------------------------------*/
771 static int vidioc_querycap (struct file *file, void  *priv,
772                                         struct v4l2_capability *cap)
773 {
774         strcpy(cap->driver, "vivi");
775         strcpy(cap->card, "vivi");
776         cap->version = VIVI_VERSION;
777         cap->capabilities =     V4L2_CAP_VIDEO_CAPTURE |
778                                 V4L2_CAP_STREAMING     |
779                                 V4L2_CAP_READWRITE;
780         return 0;
781 }
782
783 static int vidioc_enum_fmt_cap (struct file *file, void  *priv,
784                                         struct v4l2_fmtdesc *f)
785 {
786         if (f->index > 0)
787                 return -EINVAL;
788
789         strlcpy(f->description,format.name,sizeof(f->description));
790         f->pixelformat = format.fourcc;
791         return 0;
792 }
793
794 static int vidioc_g_fmt_cap (struct file *file, void *priv,
795                                         struct v4l2_format *f)
796 {
797         struct vivi_fh  *fh=priv;
798
799         f->fmt.pix.width        = fh->width;
800         f->fmt.pix.height       = fh->height;
801         f->fmt.pix.field        = fh->vb_vidq.field;
802         f->fmt.pix.pixelformat  = fh->fmt->fourcc;
803         f->fmt.pix.bytesperline =
804                 (f->fmt.pix.width * fh->fmt->depth) >> 3;
805         f->fmt.pix.sizeimage =
806                 f->fmt.pix.height * f->fmt.pix.bytesperline;
807
808         return (0);
809 }
810
811 static int vidioc_try_fmt_cap (struct file *file, void *priv,
812                         struct v4l2_format *f)
813 {
814         struct vivi_fmt *fmt;
815         enum v4l2_field field;
816         unsigned int maxw, maxh;
817
818         if (format.fourcc != f->fmt.pix.pixelformat) {
819                 dprintk(1,"Fourcc format (0x%08x) invalid. Driver accepts "
820                         "only 0x%08x\n",f->fmt.pix.pixelformat,format.fourcc);
821                 return -EINVAL;
822         }
823         fmt=&format;
824
825         field = f->fmt.pix.field;
826
827         if (field == V4L2_FIELD_ANY) {
828 //              field=V4L2_FIELD_INTERLACED;
829                 field=V4L2_FIELD_SEQ_TB;
830         } else if (V4L2_FIELD_INTERLACED != field) {
831                 dprintk(1,"Field type invalid.\n");
832                 return -EINVAL;
833         }
834
835         maxw  = norm_maxw();
836         maxh  = norm_maxh();
837
838         f->fmt.pix.field = field;
839         if (f->fmt.pix.height < 32)
840                 f->fmt.pix.height = 32;
841         if (f->fmt.pix.height > maxh)
842                 f->fmt.pix.height = maxh;
843         if (f->fmt.pix.width < 48)
844                 f->fmt.pix.width = 48;
845         if (f->fmt.pix.width > maxw)
846                 f->fmt.pix.width = maxw;
847         f->fmt.pix.width &= ~0x03;
848         f->fmt.pix.bytesperline =
849                 (f->fmt.pix.width * fmt->depth) >> 3;
850         f->fmt.pix.sizeimage =
851                 f->fmt.pix.height * f->fmt.pix.bytesperline;
852
853         return 0;
854 }
855
856 /*FIXME: This seems to be generic enough to be at videodev2 */
857 static int vidioc_s_fmt_cap (struct file *file, void *priv,
858                                         struct v4l2_format *f)
859 {
860         struct vivi_fh  *fh=priv;
861         int ret = vidioc_try_fmt_cap(file,fh,f);
862         if (ret < 0)
863                 return (ret);
864
865         fh->fmt           = &format;
866         fh->width         = f->fmt.pix.width;
867         fh->height        = f->fmt.pix.height;
868         fh->vb_vidq.field = f->fmt.pix.field;
869         fh->type          = f->type;
870
871         return (0);
872 }
873
874 static int vidioc_reqbufs (struct file *file, void *priv, struct v4l2_requestbuffers *p)
875 {
876         struct vivi_fh  *fh=priv;
877
878         return (videobuf_reqbufs(&fh->vb_vidq, p));
879 }
880
881 static int vidioc_querybuf (struct file *file, void *priv, struct v4l2_buffer *p)
882 {
883         struct vivi_fh  *fh=priv;
884
885         return (videobuf_querybuf(&fh->vb_vidq, p));
886 }
887
888 static int vidioc_qbuf (struct file *file, void *priv, struct v4l2_buffer *p)
889 {
890         struct vivi_fh  *fh=priv;
891
892         return (videobuf_qbuf(&fh->vb_vidq, p));
893 }
894
895 static int vidioc_dqbuf (struct file *file, void *priv, struct v4l2_buffer *p)
896 {
897         struct vivi_fh  *fh=priv;
898
899         return (videobuf_dqbuf(&fh->vb_vidq, p,
900                                 file->f_flags & O_NONBLOCK));
901 }
902
903 #ifdef CONFIG_VIDEO_V4L1_COMPAT
904 static int vidiocgmbuf (struct file *file, void *priv, struct video_mbuf *mbuf)
905 {
906         struct vivi_fh  *fh=priv;
907         struct videobuf_queue *q=&fh->vb_vidq;
908         struct v4l2_requestbuffers req;
909         unsigned int i;
910         int ret;
911
912         req.type   = q->type;
913         req.count  = 8;
914         req.memory = V4L2_MEMORY_MMAP;
915         ret = videobuf_reqbufs(q,&req);
916         if (ret < 0)
917                 return (ret);
918
919         mbuf->frames = req.count;
920         mbuf->size   = 0;
921         for (i = 0; i < mbuf->frames; i++) {
922                 mbuf->offsets[i]  = q->bufs[i]->boff;
923                 mbuf->size       += q->bufs[i]->bsize;
924         }
925         return (0);
926 }
927 #endif
928
929 static int vidioc_streamon(struct file *file, void *priv, enum v4l2_buf_type i)
930 {
931         struct vivi_fh  *fh=priv;
932         struct vivi_dev *dev    = fh->dev;
933
934         if (fh->type != V4L2_BUF_TYPE_VIDEO_CAPTURE)
935                 return -EINVAL;
936         if (i != fh->type)
937                 return -EINVAL;
938
939         if (!res_get(dev,fh))
940                 return -EBUSY;
941         return (videobuf_streamon(&fh->vb_vidq));
942 }
943
944 static int vidioc_streamoff(struct file *file, void *priv, enum v4l2_buf_type i)
945 {
946         struct vivi_fh  *fh=priv;
947         struct vivi_dev *dev    = fh->dev;
948
949         if (fh->type != V4L2_BUF_TYPE_VIDEO_CAPTURE)
950                 return -EINVAL;
951         if (i != fh->type)
952                 return -EINVAL;
953
954         videobuf_streamoff(&fh->vb_vidq);
955         res_free(dev,fh);
956
957         return (0);
958 }
959
960 static int vidioc_s_std (struct file *file, void *priv, v4l2_std_id *i)
961 {
962         return 0;
963 }
964
965 /* only one input in this sample driver */
966 static int vidioc_enum_input (struct file *file, void *priv,
967                                 struct v4l2_input *inp)
968 {
969         if (inp->index != 0)
970                 return -EINVAL;
971
972         inp->type = V4L2_INPUT_TYPE_CAMERA;
973         inp->std = V4L2_STD_NTSC_M;
974         strcpy(inp->name,"Camera");
975
976         return (0);
977 }
978
979 static int vidioc_g_input (struct file *file, void *priv, unsigned int *i)
980 {
981         *i = 0;
982
983         return (0);
984 }
985 static int vidioc_s_input (struct file *file, void *priv, unsigned int i)
986 {
987         if (i > 0)
988                 return -EINVAL;
989
990         return (0);
991 }
992
993         /* --- controls ---------------------------------------------- */
994 static int vidioc_queryctrl (struct file *file, void *priv,
995                                 struct v4l2_queryctrl *qc)
996 {
997         int i;
998
999         for (i = 0; i < ARRAY_SIZE(vivi_qctrl); i++)
1000                 if (qc->id && qc->id == vivi_qctrl[i].id) {
1001                         memcpy(qc, &(vivi_qctrl[i]),
1002                                 sizeof(*qc));
1003                         return (0);
1004                 }
1005
1006         return -EINVAL;
1007 }
1008
1009 static int vidioc_g_ctrl (struct file *file, void *priv,
1010                                 struct v4l2_control *ctrl)
1011 {
1012         int i;
1013
1014         for (i = 0; i < ARRAY_SIZE(vivi_qctrl); i++)
1015                 if (ctrl->id == vivi_qctrl[i].id) {
1016                         ctrl->value=qctl_regs[i];
1017                         return (0);
1018                 }
1019
1020         return -EINVAL;
1021 }
1022 static int vidioc_s_ctrl (struct file *file, void *priv,
1023                                 struct v4l2_control *ctrl)
1024 {
1025         int i;
1026
1027         for (i = 0; i < ARRAY_SIZE(vivi_qctrl); i++)
1028                 if (ctrl->id == vivi_qctrl[i].id) {
1029                         if (ctrl->value <
1030                                 vivi_qctrl[i].minimum
1031                                 || ctrl->value >
1032                                 vivi_qctrl[i].maximum) {
1033                                         return (-ERANGE);
1034                                 }
1035                         qctl_regs[i]=ctrl->value;
1036                         return (0);
1037                 }
1038         return -EINVAL;
1039 }
1040
1041 /* ------------------------------------------------------------------
1042         File operations for the device
1043    ------------------------------------------------------------------*/
1044
1045 #define line_buf_size(norm) (norm_maxw(norm)*(format.depth+7)/8)
1046
1047 static int vivi_open(struct inode *inode, struct file *file)
1048 {
1049         int minor = iminor(inode);
1050         struct vivi_dev *h,*dev = NULL;
1051         struct vivi_fh *fh;
1052         struct list_head *list;
1053         enum v4l2_buf_type type = 0;
1054         int i;
1055
1056         printk(KERN_DEBUG "vivi: open called (minor=%d)\n",minor);
1057
1058         list_for_each(list,&vivi_devlist) {
1059                 h = list_entry(list, struct vivi_dev, vivi_devlist);
1060                 if (h->vfd.minor == minor) {
1061                         dev  = h;
1062                         type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
1063                 }
1064         }
1065         if (NULL == dev)
1066                 return -ENODEV;
1067
1068
1069
1070         /* If more than one user, mutex should be added */
1071         dev->users++;
1072
1073         dprintk(1,"open minor=%d type=%s users=%d\n",
1074                                 minor,v4l2_type_names[type],dev->users);
1075
1076         /* allocate + initialize per filehandle data */
1077         fh = kzalloc(sizeof(*fh),GFP_KERNEL);
1078         if (NULL == fh) {
1079                 dev->users--;
1080                 return -ENOMEM;
1081         }
1082
1083         file->private_data = fh;
1084         fh->dev      = dev;
1085
1086         fh->type     = V4L2_BUF_TYPE_VIDEO_CAPTURE;
1087         fh->fmt      = &format;
1088         fh->width    = 640;
1089         fh->height   = 480;
1090
1091         /* Put all controls at a sane state */
1092         for (i = 0; i < ARRAY_SIZE(vivi_qctrl); i++)
1093                 qctl_regs[i] =vivi_qctrl[i].default_value;
1094
1095         dprintk(1,"Open: fh=0x%08lx, dev=0x%08lx, dev->vidq=0x%08lx\n",
1096                 (unsigned long)fh,(unsigned long)dev,(unsigned long)&dev->vidq);
1097         dprintk(1,"Open: list_empty queued=%d\n",list_empty(&dev->vidq.queued));
1098         dprintk(1,"Open: list_empty active=%d\n",list_empty(&dev->vidq.active));
1099
1100         /* Resets frame counters */
1101         dev->h=0;
1102         dev->m=0;
1103         dev->s=0;
1104         dev->us=0;
1105         dev->jiffies=jiffies;
1106         sprintf(dev->timestr,"%02d:%02d:%02d:%03d",
1107                         dev->h,dev->m,dev->s,(dev->us+500)/1000);
1108
1109         videobuf_queue_init(&fh->vb_vidq, &vivi_video_qops,
1110                         NULL, NULL,
1111                         fh->type,
1112                         V4L2_FIELD_INTERLACED,
1113                         sizeof(struct vivi_buffer),fh);
1114
1115         return 0;
1116 }
1117
1118 static ssize_t
1119 vivi_read(struct file *file, char __user *data, size_t count, loff_t *ppos)
1120 {
1121         struct vivi_fh        *fh = file->private_data;
1122
1123         if (fh->type==V4L2_BUF_TYPE_VIDEO_CAPTURE) {
1124                 if (res_locked(fh->dev))
1125                         return -EBUSY;
1126                 return videobuf_read_stream(&fh->vb_vidq, data, count, ppos, 0,
1127                                         file->f_flags & O_NONBLOCK);
1128         }
1129         return 0;
1130 }
1131
1132 static unsigned int
1133 vivi_poll(struct file *file, struct poll_table_struct *wait)
1134 {
1135         struct vivi_fh        *fh = file->private_data;
1136         struct vivi_buffer    *buf;
1137
1138         dprintk(1,"%s\n",__FUNCTION__);
1139
1140         if (V4L2_BUF_TYPE_VIDEO_CAPTURE != fh->type)
1141                 return POLLERR;
1142
1143         if (res_get(fh->dev,fh)) {
1144                 dprintk(1,"poll: mmap interface\n");
1145                 /* streaming capture */
1146                 if (list_empty(&fh->vb_vidq.stream))
1147                         return POLLERR;
1148                 buf = list_entry(fh->vb_vidq.stream.next,struct vivi_buffer,vb.stream);
1149         } else {
1150                 dprintk(1,"poll: read() interface\n");
1151                 /* read() capture */
1152                 buf = (struct vivi_buffer*)fh->vb_vidq.read_buf;
1153                 if (NULL == buf)
1154                         return POLLERR;
1155         }
1156         poll_wait(file, &buf->vb.done, wait);
1157         if (buf->vb.state == STATE_DONE ||
1158             buf->vb.state == STATE_ERROR)
1159                 return POLLIN|POLLRDNORM;
1160         return 0;
1161 }
1162
1163 static int vivi_release(struct inode *inode, struct file *file)
1164 {
1165         struct vivi_fh         *fh = file->private_data;
1166         struct vivi_dev *dev       = fh->dev;
1167         struct vivi_dmaqueue *vidq = &dev->vidq;
1168
1169         int minor = iminor(inode);
1170
1171         vivi_stop_thread(vidq);
1172         videobuf_mmap_free(&fh->vb_vidq);
1173
1174         kfree (fh);
1175
1176         dev->users--;
1177
1178         printk(KERN_DEBUG "vivi: close called (minor=%d, users=%d)\n",minor,dev->users);
1179
1180         return 0;
1181 }
1182
1183 static int
1184 vivi_mmap(struct file *file, struct vm_area_struct * vma)
1185 {
1186         struct vivi_fh        *fh = file->private_data;
1187         int ret;
1188
1189         dprintk (1,"mmap called, vma=0x%08lx\n",(unsigned long)vma);
1190
1191         ret=videobuf_mmap_mapper(&fh->vb_vidq, vma);
1192
1193         dprintk (1,"vma start=0x%08lx, size=%ld, ret=%d\n",
1194                 (unsigned long)vma->vm_start,
1195                 (unsigned long)vma->vm_end-(unsigned long)vma->vm_start,
1196                 ret);
1197
1198         return ret;
1199 }
1200
1201 static const struct file_operations vivi_fops = {
1202         .owner          = THIS_MODULE,
1203         .open           = vivi_open,
1204         .release        = vivi_release,
1205         .read           = vivi_read,
1206         .poll           = vivi_poll,
1207         .ioctl          = video_ioctl2, /* V4L2 ioctl handler */
1208         .mmap           = vivi_mmap,
1209         .llseek         = no_llseek,
1210 };
1211
1212 static struct video_device vivi = {
1213         .name           = "vivi",
1214         .type           = VID_TYPE_CAPTURE,
1215         .hardware       = 0,
1216         .fops           = &vivi_fops,
1217         .minor          = -1,
1218 //      .release        = video_device_release,
1219
1220         .vidioc_querycap      = vidioc_querycap,
1221         .vidioc_enum_fmt_cap  = vidioc_enum_fmt_cap,
1222         .vidioc_g_fmt_cap     = vidioc_g_fmt_cap,
1223         .vidioc_try_fmt_cap   = vidioc_try_fmt_cap,
1224         .vidioc_s_fmt_cap     = vidioc_s_fmt_cap,
1225         .vidioc_reqbufs       = vidioc_reqbufs,
1226         .vidioc_querybuf      = vidioc_querybuf,
1227         .vidioc_qbuf          = vidioc_qbuf,
1228         .vidioc_dqbuf         = vidioc_dqbuf,
1229         .vidioc_s_std         = vidioc_s_std,
1230         .vidioc_enum_input    = vidioc_enum_input,
1231         .vidioc_g_input       = vidioc_g_input,
1232         .vidioc_s_input       = vidioc_s_input,
1233         .vidioc_queryctrl     = vidioc_queryctrl,
1234         .vidioc_g_ctrl        = vidioc_g_ctrl,
1235         .vidioc_s_ctrl        = vidioc_s_ctrl,
1236         .vidioc_streamon      = vidioc_streamon,
1237         .vidioc_streamoff     = vidioc_streamoff,
1238 #ifdef CONFIG_VIDEO_V4L1_COMPAT
1239         .vidiocgmbuf          = vidiocgmbuf,
1240 #endif
1241         .tvnorms              = V4L2_STD_NTSC_M,
1242         .current_norm         = V4L2_STD_NTSC_M,
1243 };
1244 /* -----------------------------------------------------------------
1245         Initialization and module stuff
1246    ------------------------------------------------------------------*/
1247
1248 static int __init vivi_init(void)
1249 {
1250         int ret;
1251         struct vivi_dev *dev;
1252
1253         dev = kzalloc(sizeof(*dev),GFP_KERNEL);
1254         if (NULL == dev)
1255                 return -ENOMEM;
1256         list_add_tail(&dev->vivi_devlist,&vivi_devlist);
1257
1258         /* init video dma queues */
1259         INIT_LIST_HEAD(&dev->vidq.active);
1260         INIT_LIST_HEAD(&dev->vidq.queued);
1261         init_waitqueue_head(&dev->vidq.wq);
1262
1263         /* initialize locks */
1264         mutex_init(&dev->lock);
1265
1266         dev->vidq.timeout.function = vivi_vid_timeout;
1267         dev->vidq.timeout.data     = (unsigned long)dev;
1268         init_timer(&dev->vidq.timeout);
1269
1270         ret = video_register_device(&vivi, VFL_TYPE_GRABBER, video_nr);
1271         printk(KERN_INFO "Video Technology Magazine Virtual Video Capture Board (Load status: %d)\n", ret);
1272         return ret;
1273 }
1274
1275 static void __exit vivi_exit(void)
1276 {
1277         struct vivi_dev *h;
1278         struct list_head *list;
1279
1280         while (!list_empty(&vivi_devlist)) {
1281                 list = vivi_devlist.next;
1282                 list_del(list);
1283                 h = list_entry(list, struct vivi_dev, vivi_devlist);
1284                 kfree (h);
1285         }
1286         video_unregister_device(&vivi);
1287 }
1288
1289 module_init(vivi_init);
1290 module_exit(vivi_exit);
1291
1292 MODULE_DESCRIPTION("Video Technology Magazine Virtual Video Capture Board");
1293 MODULE_AUTHOR("Mauro Carvalho Chehab, Ted Walther and John Sokol");
1294 MODULE_LICENSE("Dual BSD/GPL");
1295
1296 module_param(video_nr, int, 0);
1297
1298 module_param_named(debug,vivi.debug, int, 0644);
1299 MODULE_PARM_DESC(debug,"activates debug info");
1300
1301 module_param(vid_limit,int,0644);
1302 MODULE_PARM_DESC(vid_limit,"capture memory limit in megabytes");
1303