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