]> git.karo-electronics.de Git - mv-sheeva.git/blob - drivers/staging/tm6000/tm6000-video.c
d8e9f2714969a52d259bd7c2b591ac5ad59606ca
[mv-sheeva.git] / drivers / staging / tm6000 / tm6000-video.c
1 /*
2    tm6000-video.c - driver for TM5600/TM6000 USB video capture devices
3
4    Copyright (C) 2006-2007 Mauro Carvalho Chehab <mchehab@infradead.org>
5
6    Copyright (C) 2007 Michel Ludwig <michel.ludwig@gmail.com>
7         - Fixed module load/unload
8
9    This program is free software; you can redistribute it and/or modify
10    it under the terms of the GNU General Public License as published by
11    the Free Software Foundation version 2
12
13    This program is distributed in the hope that it will be useful,
14    but WITHOUT ANY WARRANTY; without even the implied warranty of
15    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16    GNU General Public License for more details.
17
18    You should have received a copy of the GNU General Public License
19    along with this program; if not, write to the Free Software
20    Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
21  */
22 #include <linux/module.h>
23 #include <linux/delay.h>
24 #include <linux/errno.h>
25 #include <linux/fs.h>
26 #include <linux/kernel.h>
27 #include <linux/slab.h>
28 #include <linux/mm.h>
29 #include <linux/ioport.h>
30 #include <linux/init.h>
31 #include <linux/sched.h>
32 #include <linux/random.h>
33 #include <linux/version.h>
34 #include <linux/usb.h>
35 #include <linux/videodev2.h>
36 #ifdef CONFIG_VIDEO_V4L1_COMPAT
37 #include <linux/videodev.h>
38 #endif
39 #include <linux/interrupt.h>
40 #include <linux/kthread.h>
41 #include <linux/highmem.h>
42 #include <linux/freezer.h>
43
44 #include "tm6000-regs.h"
45 #include "tm6000.h"
46
47 #define BUFFER_TIMEOUT     msecs_to_jiffies(2000)  /* 2 seconds */
48
49 /* Limits minimum and default number of buffers */
50 #define TM6000_MIN_BUF 4
51 #define TM6000_DEF_BUF 8
52
53 /* Declare static vars that will be used as parameters */
54 static unsigned int vid_limit = 16;     /* Video memory limit, in Mb */
55 static int video_nr = -1;               /* /dev/videoN, -1 for autodetect */
56
57 unsigned long tm6000_devused;
58
59 /* Debug level */
60 int tm6000_debug;
61
62 /* supported controls */
63 static struct v4l2_queryctrl tm6000_qctrl[] = {
64         {
65                 .id            = V4L2_CID_BRIGHTNESS,
66                 .type          = V4L2_CTRL_TYPE_INTEGER,
67                 .name          = "Brightness",
68                 .minimum       = 0,
69                 .maximum       = 255,
70                 .step          = 1,
71                 .default_value = 54,
72                 .flags         = 0,
73         }, {
74                 .id            = V4L2_CID_CONTRAST,
75                 .type          = V4L2_CTRL_TYPE_INTEGER,
76                 .name          = "Contrast",
77                 .minimum       = 0,
78                 .maximum       = 255,
79                 .step          = 0x1,
80                 .default_value = 119,
81                 .flags         = 0,
82         }, {
83                 .id            = V4L2_CID_SATURATION,
84                 .type          = V4L2_CTRL_TYPE_INTEGER,
85                 .name          = "Saturation",
86                 .minimum       = 0,
87                 .maximum       = 255,
88                 .step          = 0x1,
89                 .default_value = 112,
90                 .flags         = 0,
91         }, {
92                 .id            = V4L2_CID_HUE,
93                 .type          = V4L2_CTRL_TYPE_INTEGER,
94                 .name          = "Hue",
95                 .minimum       = -128,
96                 .maximum       = 127,
97                 .step          = 0x1,
98                 .default_value = 0,             //4 ?
99                 .flags         = 0,
100         }
101 };
102
103 static int qctl_regs[ARRAY_SIZE(tm6000_qctrl)];
104
105 static struct tm6000_fmt format[] = {
106         {
107                 .name     = "4:2:2, packed, YVY2",
108                 .fourcc   = V4L2_PIX_FMT_YUYV,
109                 .depth    = 16,
110         },{
111                 .name     = "4:2:2, packed, UYVY",
112                 .fourcc   = V4L2_PIX_FMT_UYVY,
113                 .depth    = 16,
114         },{
115                 .name     = "A/V + VBI mux packet",
116                 .fourcc   = V4L2_PIX_FMT_TM6000,
117                 .depth    = 16,
118         }
119 };
120
121 static LIST_HEAD(tm6000_corelist);
122
123 /* ------------------------------------------------------------------
124         DMA and thread functions
125    ------------------------------------------------------------------*/
126
127 #define norm_maxw(a) 720
128 #define norm_maxh(a) 480
129
130 //#define norm_minw(a) norm_maxw(a)
131 #define norm_minw(a) norm_maxw(a)
132 #define norm_minh(a) norm_maxh(a)
133
134 /*
135  * video-buf generic routine to get the next available buffer
136  */
137 static int inline get_next_buf (struct tm6000_dmaqueue *dma_q,
138                                           struct tm6000_buffer    **buf)
139 {
140         struct tm6000_core *dev= container_of(dma_q,struct tm6000_core,vidq);
141
142         if (list_empty(&dma_q->active)) {
143                 dprintk(dev, V4L2_DEBUG_QUEUE,"No active queue to serve\n");
144                 return 0;
145         }
146
147         *buf = list_entry(dma_q->active.next,
148                         struct tm6000_buffer, vb.queue);
149
150         /* Nobody is waiting something to be done, just return */
151         if (!waitqueue_active(&(*buf)->vb.done)) {
152                 mod_timer(&dma_q->timeout, jiffies+BUFFER_TIMEOUT);
153                 return -1;
154         }
155
156         return 1;
157 }
158
159 /*
160  * Announces that a buffer were filled and request the next
161  */
162 static void inline buffer_filled (struct tm6000_core *dev,
163                                   struct tm6000_buffer *buf)
164 {
165         /* Advice that buffer was filled */
166         dprintk(dev, V4L2_DEBUG_QUEUE, "[%p/%d] wakeup\n",buf,buf->vb.i);
167         buf->vb.state = STATE_DONE;
168         buf->vb.field_count++;
169         do_gettimeofday(&buf->vb.ts);
170
171         list_del(&buf->vb.queue);
172         wake_up(&buf->vb.done);
173 }
174
175 /*
176  * Macro to allow copying data into the proper memory type
177  */
178
179 #define bufcpy(buf,out_ptr,in_ptr,size)                                 \
180         {                                                               \
181                 if (__copy_to_user(out_ptr,in_ptr,size)!=0)             \
182                         tm6000_err("copy_to_user failed.\n");           \
183         }
184
185 /*
186  * Identify the tm5600/6000 buffer header type and properly handles
187  */
188 static int copy_streams(u8 *data, u8 *out_p, unsigned long len,
189                         struct urb *urb, struct tm6000_buffer **buf)
190 {
191         struct tm6000_dmaqueue  *dma_q = urb->context;
192         struct tm6000_core *dev= container_of(dma_q,struct tm6000_core,vidq);
193         u8 *ptr=data, *endp=data+len;
194         u8 c;
195         unsigned int cmd, cpysize, pktsize, size, field, block, line, pos=0;
196         unsigned long header;
197         int rc=0;
198
199         /* FIXME: this is the hardcoded window size
200          */
201         unsigned int linesize=720*2;
202
203 //static int last_line=-2;
204
205         for (ptr=data; ptr<endp;) {
206                 if (!dev->isoc_ctl.cmd) {
207                         /* Seek for sync */
208                         for (ptr+=3;ptr<endp;ptr++) {
209                                 if (*ptr==0x47) {
210                                         ptr-=3;
211                                         break;
212                                 }
213                         }
214                         if (ptr>=endp)
215                                 return rc;
216
217                         /* Get message header */
218                         header=*(unsigned long *)ptr;
219                         ptr+=4;
220                         c=(header>>24) & 0xff;
221
222                         /* split the header fields */
223                         size  = (((header & 0x7e)<<1) -1) *4;
224                         block = (header>>7) & 0xf;
225                         field = (header>>11) & 0x1;
226                         line  = (header>>12) & 0x1ff;
227                         cmd   = (header>>21) & 0x7;
228
229                         /* FIXME: Maximum possible line is 511.
230                          * This doesn't seem to be enough for PAL standards
231                          */
232
233                         /* Validates header fields */
234                         if(size>TM6000_URB_MSG_LEN)
235                                 size=TM6000_URB_MSG_LEN;
236                         if(block>=8)
237                                 cmd = TM6000_URB_MSG_ERR;
238
239                         /* FIXME: Mounts the image as field0+field1
240                          * It should, instead, check if the user selected
241                          * entrelaced or non-entrelaced mode
242                          */
243                         pos=((line<<1)+field)*linesize+
244                                                 block*TM6000_URB_MSG_LEN;
245
246
247
248                         /* Don't allow to write out of the buffer */
249                         if (pos+TM6000_URB_MSG_LEN > (*buf)->vb.size)
250                                 cmd = TM6000_URB_MSG_ERR;
251
252                         /* Prints debug info */
253                         dprintk(dev, V4L2_DEBUG_ISOC, "size=%d, num=%d, "
254                                         " line=%d, field=%d\n",
255                                         size, block, line, field);
256
257                         dev->isoc_ctl.cmd  = cmd;
258                         dev->isoc_ctl.size = size;
259                         dev->isoc_ctl.pos  = pos;
260                         dev->isoc_ctl.pktsize = pktsize = TM6000_URB_MSG_LEN;
261                 } else {
262                         cmd = dev->isoc_ctl.cmd;
263                         size= dev->isoc_ctl.size;
264                         pos = dev->isoc_ctl.pos;
265                         pktsize = dev->isoc_ctl.pktsize;
266                 }
267                 cpysize=(endp-ptr>size)?size:endp-ptr;
268
269                 if (cpysize) {
270                         /* handles each different URB message */
271                         switch(cmd) {
272                         case TM6000_URB_MSG_VIDEO:
273                                 /* Fills video buffer */
274                                 bufcpy(*buf,&out_p[pos],ptr,cpysize);
275                         break;
276                         }
277                 }
278                 if (cpysize<size) {
279                         /* End of URB packet, but cmd processing is not
280                          * complete. Preserve the state for a next packet
281                          */
282                         dev->isoc_ctl.pos = pos+cpysize;
283                         dev->isoc_ctl.size= size-cpysize;
284                         dev->isoc_ctl.cmd = cmd;
285                         dev->isoc_ctl.pktsize = pktsize-cpysize;
286                         ptr+=cpysize;
287                 } else {
288                         dev->isoc_ctl.cmd = 0;
289                         ptr+=pktsize;
290                 }
291         }
292
293         return rc;
294 }
295 /*
296  * Identify the tm5600/6000 buffer header type and properly handles
297  */
298 static int copy_multiplexed(u8 *ptr, u8 *out_p, unsigned long len,
299                         struct urb *urb, struct tm6000_buffer **buf)
300 {
301         struct tm6000_dmaqueue  *dma_q = urb->context;
302         struct tm6000_core *dev= container_of(dma_q,struct tm6000_core,vidq);
303         unsigned int pos=dev->isoc_ctl.pos,cpysize;
304         int rc=1;
305
306         while (len>0) {
307                 cpysize=min(len,(*buf)->vb.size-pos);
308 //printk("Copying %d bytes (max=%lu) from %p to %p[%u]\n",cpysize,(*buf)->vb.size,ptr,out_p,pos);
309                 bufcpy(*buf,&out_p[pos],ptr,cpysize);
310                 pos+=cpysize;
311                 ptr+=cpysize;
312                 len-=cpysize;
313                 if (pos >= (*buf)->vb.size) {
314                         pos=0;
315                         /* Announces that a new buffer were filled */
316                         buffer_filled (dev, *buf);
317                         dprintk(dev, V4L2_DEBUG_QUEUE, "new buffer filled\n");
318
319                         rc=get_next_buf (dma_q, buf);
320                         if (rc<=0) {
321                                 *buf=NULL;
322                                 printk(KERN_ERR "tm6000: buffer underrun\n");
323                                 break;
324                         }
325                 }
326         }
327
328         dev->isoc_ctl.pos=pos;
329         return rc;
330 }
331
332 /*
333  * Controls the isoc copy of each urb packet
334  */
335 static inline int tm6000_isoc_copy(struct urb *urb, struct tm6000_buffer **buf)
336 {
337         struct tm6000_dmaqueue  *dma_q = urb->context;
338         struct tm6000_core *dev= container_of(dma_q,struct tm6000_core,vidq);
339         void *outp=videobuf_to_vmalloc (&((*buf)->vb));
340         int i, len=0, rc=1;
341         int size=(*buf)->vb.size;
342         char *p;
343         unsigned long copied;
344
345         copied=0;
346
347
348         for (i = 0; i < urb->number_of_packets; i++) {
349                 int status = urb->iso_frame_desc[i].status;
350                 char *errmsg = "Unknown";
351
352                 switch(status) {
353                 case -ENOENT:
354                         errmsg = "unlinked synchronuously";
355                         break;
356                 case -ECONNRESET:
357                         errmsg = "unlinked asynchronuously";
358                         break;
359                 case -ENOSR:
360                         errmsg = "Buffer error (overrun)";
361                         break;
362                 case -EPIPE:
363                         errmsg = "Stalled (device not responding)";
364                         break;
365                 case -EOVERFLOW:
366                         errmsg = "Babble (bad cable?)";
367                         break;
368                 case -EPROTO:
369                         errmsg = "Bit-stuff error (bad cable?)";
370                         break;
371                 case -EILSEQ:
372                         errmsg = "CRC/Timeout (could be anything)";
373                         break;
374                 case -ETIME:
375                         errmsg = "Device does not respond";
376                         break;
377                 }
378                 dprintk(dev, V4L2_DEBUG_QUEUE, "URB status %d [%s].\n",
379                         status, errmsg);
380
381                 if (status<0)
382                         continue;
383
384                 len=urb->iso_frame_desc[i].actual_length;
385
386                 if (len>=TM6000_URB_MSG_LEN) {
387                         p=urb->transfer_buffer + urb->iso_frame_desc[i].offset;
388                         if (!urb->iso_frame_desc[i].status) {
389                                 if (((*buf)->fmt->fourcc)==V4L2_PIX_FMT_TM6000) {
390                                         rc=copy_multiplexed(p,outp,len,urb,buf);
391                                         if (rc<=0)
392                                                 return rc;
393                                 } else {
394                                         rc=copy_streams(p,outp,len,urb,buf);
395                                 }
396                         }
397                         copied += len;
398                         if (copied>=size)
399                                 break;
400                 }
401         }
402
403         if (((*buf)->fmt->fourcc)!=V4L2_PIX_FMT_TM6000) {
404                 buffer_filled (dev, *buf);
405                 dprintk(dev, V4L2_DEBUG_QUEUE, "new buffer filled\n");
406         }
407
408         return rc;
409 }
410
411 /* ------------------------------------------------------------------
412         URB control
413    ------------------------------------------------------------------*/
414
415 /*
416  * IRQ callback, called by URB callback
417  */
418 static void tm6000_irq_callback(struct urb *urb)
419 {
420         struct tm6000_buffer    *buf;
421         struct tm6000_dmaqueue  *dma_q = urb->context;
422         struct tm6000_core *dev= container_of(dma_q,struct tm6000_core,vidq);
423         int rc,i;
424         unsigned long flags;
425
426         spin_lock_irqsave(&dev->slock,flags);
427
428         rc=get_next_buf (dma_q, &buf);
429         if (rc<=0)
430                 goto ret;
431
432         /* Copy data from URB */
433         rc=tm6000_isoc_copy(urb, &buf);
434
435 ret:
436         /* Reset urb buffers */
437         for (i = 0; i < urb->number_of_packets; i++) {
438                 urb->iso_frame_desc[i].status = 0;
439                 urb->iso_frame_desc[i].actual_length = 0;
440         }
441         urb->status = 0;
442
443         if ((urb->status = usb_submit_urb(urb, GFP_ATOMIC))) {
444                 tm6000_err("urb resubmit failed (error=%i)\n",
445                         urb->status);
446         }
447
448         if (rc>=0) {
449                 if (!rc) {
450                         dprintk(dev, V4L2_DEBUG_QUEUE, "No active queue to serve\n");
451                         del_timer(&dma_q->timeout);
452                 } else {
453                         /* Data filled, reset watchdog */
454                         mod_timer(&dma_q->timeout, jiffies+BUFFER_TIMEOUT);
455                 }
456         }
457         spin_unlock_irqrestore(&dev->slock,flags);
458 }
459
460 /*
461  * Stop and Deallocate URBs
462  */
463 static void tm6000_uninit_isoc(struct tm6000_core *dev)
464 {
465         struct urb *urb;
466         int i;
467
468         for (i = 0; i < dev->isoc_ctl.num_bufs; i++) {
469                 urb=dev->isoc_ctl.urb[i];
470                 if (urb) {
471                         usb_kill_urb(urb);
472                         usb_unlink_urb(urb);
473                         if (dev->isoc_ctl.transfer_buffer[i]) {
474                                 usb_buffer_free(dev->udev,
475                                                 urb->transfer_buffer_length,
476                                                 dev->isoc_ctl.transfer_buffer[i],
477                                                 urb->transfer_dma);
478                         }
479                         usb_free_urb(urb);
480                         dev->isoc_ctl.urb[i] = NULL;
481                 }
482                 dev->isoc_ctl.transfer_buffer[i] = NULL;
483         }
484
485         kfree (dev->isoc_ctl.urb);
486         kfree (dev->isoc_ctl.transfer_buffer);
487         dev->isoc_ctl.urb=NULL;
488         dev->isoc_ctl.transfer_buffer=NULL;
489
490         dev->isoc_ctl.num_bufs=0;
491 }
492
493 /*
494  * Stop video thread - FIXME: Can be easily removed
495  */
496 static void tm6000_stop_thread(struct tm6000_dmaqueue  *dma_q)
497 {
498         struct tm6000_core *dev= container_of(dma_q,struct tm6000_core,vidq);
499
500         tm6000_uninit_isoc(dev);
501 }
502
503
504 /*
505  * Allocate URBs and start IRQ
506  */
507 static int tm6000_prepare_isoc(struct tm6000_core *dev,
508                      int max_packets, int num_bufs)
509 {
510         struct tm6000_dmaqueue *dma_q = &dev->vidq;
511         int i;
512         int sb_size, pipe;
513         struct urb *urb;
514         int j, k;
515
516         /* De-allocates all pending stuff */
517         tm6000_uninit_isoc(dev);
518
519         dev->isoc_ctl.num_bufs=num_bufs;
520
521         dev->isoc_ctl.urb=kmalloc(sizeof(void *)*num_bufs,
522                                    GFP_KERNEL);
523         if (!dev->isoc_ctl.urb) {
524                 tm6000_err("cannot alloc memory for usb buffers\n");
525                 return -ENOMEM;
526         }
527
528         dev->isoc_ctl.transfer_buffer=kmalloc(sizeof(void *)*num_bufs,
529                                    GFP_KERNEL);
530         if (!dev->isoc_ctl.urb) {
531                 tm6000_err("cannot allocate memory for usbtransfer\n");
532                 kfree(dev->isoc_ctl.urb);
533                 return -ENOMEM;
534         }
535
536         dev->isoc_ctl.max_pkt_size=dev->max_isoc_in;
537
538         sb_size = max_packets * dev->isoc_ctl.max_pkt_size;
539
540
541         /* allocate urbs and transfer buffers */
542         for (i = 0; i < dev->isoc_ctl.num_bufs; i++) {
543                 urb = usb_alloc_urb(max_packets, GFP_KERNEL);
544                 if (!urb) {
545                         tm6000_err("cannot alloc isoc_ctl.urb %i\n", i);
546                         tm6000_uninit_isoc(dev);
547                         return -ENOMEM;
548                 }
549                 dev->isoc_ctl.urb[i] = urb;
550
551                 dev->isoc_ctl.transfer_buffer[i] = usb_buffer_alloc(dev->udev,
552                         sb_size, GFP_KERNEL,
553                         &dev->isoc_ctl.urb[i]->transfer_dma);
554                 if (!dev->isoc_ctl.transfer_buffer[i]) {
555                         tm6000_err ("unable to allocate %i bytes for transfer"
556                                         " buffer %i\n", sb_size, i);
557                         tm6000_uninit_isoc(dev);
558                         return -ENOMEM;
559                 }
560                 memset(dev->isoc_ctl.transfer_buffer[i], 0, sb_size);
561
562                 pipe=usb_rcvisocpipe(dev->udev,
563                                         dev->isoc_in->desc.bEndpointAddress &
564                                         USB_ENDPOINT_NUMBER_MASK);
565                 usb_fill_int_urb(urb, dev->udev, pipe,
566                                         dev->isoc_ctl.transfer_buffer[i],sb_size,
567                                         tm6000_irq_callback, dma_q,
568                                         dev->isoc_in->desc.bInterval);
569
570                 urb->number_of_packets = max_packets;
571                 urb->transfer_flags = URB_ISO_ASAP;
572
573                 k = 0;
574                 for (j = 0; j < max_packets; j++) {
575                         urb->iso_frame_desc[j].offset = k;
576                         urb->iso_frame_desc[j].length =
577                                                 dev->isoc_ctl.max_pkt_size;
578                         k += dev->isoc_ctl.max_pkt_size;
579                 }
580         }
581
582         return 0;
583 }
584
585 static int tm6000_start_thread( struct tm6000_dmaqueue  *dma_q,
586                                 struct tm6000_buffer *buf)
587 {
588         struct tm6000_core *dev= container_of(dma_q,struct tm6000_core,vidq);
589         int i,rc;
590
591         dma_q->frame=0;
592         dma_q->ini_jiffies=jiffies;
593
594         init_waitqueue_head(&dma_q->wq);
595
596         /* submit urbs and enables IRQ */
597         for (i = 0; i < dev->isoc_ctl.num_bufs; i++) {
598                 rc = usb_submit_urb(dev->isoc_ctl.urb[i], GFP_ATOMIC);
599                 if (rc) {
600                         tm6000_err("submit of urb %i failed (error=%i)\n", i,
601                                    rc);
602                         tm6000_uninit_isoc(dev);
603                         return rc;
604                 }
605         }
606
607         if (rc<0)
608                 return rc;
609
610         return 0;
611 }
612
613 static int restart_video_queue(struct tm6000_dmaqueue *dma_q)
614 {
615         struct tm6000_core *dev= container_of(dma_q,struct tm6000_core,vidq);
616
617         struct tm6000_buffer *buf, *prev;
618         struct list_head *item;
619
620         dprintk(dev, V4L2_DEBUG_QUEUE, "%s dma_q=0x%08lx\n",
621                                          __FUNCTION__,(unsigned long)dma_q);
622
623         if (!list_empty(&dma_q->active)) {
624                 buf = list_entry(dma_q->active.next, struct tm6000_buffer, vb.queue);
625                 dprintk(dev, V4L2_DEBUG_QUEUE,
626                         "restart_queue [%p/%d]: restart dma\n", buf, buf->vb.i);
627
628                 dprintk(dev, V4L2_DEBUG_QUEUE, "Restarting video dma\n");
629                 tm6000_stop_thread(dma_q);
630                 tm6000_start_thread(dma_q, buf);
631
632                 /* cancel all outstanding capture / vbi requests */
633                 list_for_each(item,&dma_q->active) {
634                         buf = list_entry(item, struct tm6000_buffer, vb.queue);
635
636                         list_del(&buf->vb.queue);
637                         buf->vb.state = STATE_ERROR;
638                         wake_up(&buf->vb.done);
639                 }
640                 mod_timer(&dma_q->timeout, jiffies+BUFFER_TIMEOUT);
641
642                 return 0;
643         }
644
645         prev = NULL;
646         for (;;) {
647                 if (list_empty(&dma_q->queued))
648                         return 0;
649                 buf = list_entry(dma_q->queued.next, struct tm6000_buffer, vb.queue);
650                 if (NULL == prev) {
651                         list_del(&buf->vb.queue);
652                         list_add_tail(&buf->vb.queue,&dma_q->active);
653
654                         dprintk(dev, V4L2_DEBUG_QUEUE, "Restarting video dma\n");
655                         tm6000_stop_thread(dma_q);
656                         tm6000_start_thread(dma_q, buf);
657
658                         buf->vb.state = STATE_ACTIVE;
659                         mod_timer(&dma_q->timeout, jiffies+BUFFER_TIMEOUT);
660                         dprintk(dev, V4L2_DEBUG_QUEUE, "[%p/%d] restart_queue -"
661                                         " first active\n", buf, buf->vb.i);
662
663                 } else if (prev->vb.width  == buf->vb.width  &&
664                            prev->vb.height == buf->vb.height &&
665                            prev->fmt       == buf->fmt) {
666                         list_del(&buf->vb.queue);
667                         list_add_tail(&buf->vb.queue,&dma_q->active);
668                         buf->vb.state = STATE_ACTIVE;
669                         dprintk(dev, V4L2_DEBUG_QUEUE, "[%p/%d] restart_queue -"
670                                         " move to active\n",buf,buf->vb.i);
671                 } else {
672                         return 0;
673                 }
674                 prev = buf;
675         }
676 }
677
678 static void tm6000_vid_timeout(unsigned long data)
679 {
680         struct tm6000_core      *dev  = (struct tm6000_core*)data;
681         struct tm6000_dmaqueue *vidq = &dev->vidq;
682         struct tm6000_buffer   *buf;
683         unsigned long flags;
684
685         spin_lock_irqsave(&dev->slock,flags);
686         while (!list_empty(&vidq->active)) {
687                 buf = list_entry(vidq->active.next, struct tm6000_buffer,
688                                                                  vb.queue);
689                 list_del(&buf->vb.queue);
690                 buf->vb.state = STATE_ERROR;
691                 wake_up(&buf->vb.done);
692                 dprintk(dev, V4L2_DEBUG_QUEUE, "tm6000/0: [%p/%d] timeout\n",
693                                                          buf, buf->vb.i);
694         }
695
696         restart_video_queue(vidq);
697         spin_unlock_irqrestore(&dev->slock,flags);
698 }
699
700 /* ------------------------------------------------------------------
701         Videobuf operations
702    ------------------------------------------------------------------*/
703
704 static int
705 buffer_setup(struct videobuf_queue *vq, unsigned int *count, unsigned int *size)
706 {
707         struct tm6000_fh *fh = vq->priv_data;
708
709         *size = fh->fmt->depth * fh->width * fh->height >> 3;
710         if (0 == *count)
711                 *count = TM6000_DEF_BUF;
712
713         if (*count < TM6000_MIN_BUF) {
714                 *count=TM6000_MIN_BUF;
715         }
716
717 printk("Requesting %d buffers\n",*count);
718
719         while (*size * *count > vid_limit * 1024 * 1024)
720                 (*count)--;
721
722         return 0;
723 }
724
725 static void free_buffer(struct videobuf_queue *vq, struct tm6000_buffer *buf)
726 {
727         if (in_interrupt())
728                 BUG();
729
730         videobuf_waiton(&buf->vb,0,0);
731         videobuf_vmalloc_free(&buf->vb);
732         buf->vb.state = STATE_NEEDS_INIT;
733 }
734
735 static int
736 buffer_prepare(struct videobuf_queue *vq, struct videobuf_buffer *vb,
737                                                 enum v4l2_field field)
738 {
739         struct tm6000_fh     *fh  = vq->priv_data;
740         struct tm6000_buffer *buf = container_of(vb,struct tm6000_buffer,vb);
741         struct tm6000_core   *dev = fh->dev;
742         int rc=0, urbsize, urb_init=0;
743
744         BUG_ON(NULL == fh->fmt);
745
746         if (fh->width  < norm_minw(core) || fh->width  > norm_maxw(core) ||
747             fh->height < norm_minh(core) || fh->height > norm_maxh(core)) {
748                 dprintk(dev, V4L2_DEBUG_QUEUE, "Window size (%dx%d) is out of "
749                                 "supported range\n", fh->width, fh->height);
750                 dprintk(dev, V4L2_DEBUG_QUEUE, "Valid range is from (%dx%d) to "
751                                 "(%dx%d)\n", norm_minw(core), norm_minh(core),
752                                 norm_maxw(core),norm_maxh(core));
753                 return -EINVAL;
754         }
755
756         /* FIXME: It assumes depth=2 */
757         /* The only currently supported format is 16 bits/pixel */
758         buf->vb.size = fh->fmt->depth*fh->width*fh->height >> 3;
759         if (0 != buf->vb.baddr  &&  buf->vb.bsize < buf->vb.size)
760                 return -EINVAL;
761
762         if (buf->fmt       != fh->fmt    ||
763             buf->vb.width  != fh->width  ||
764             buf->vb.height != fh->height ||
765             buf->vb.field  != field) {
766                 buf->fmt       = fh->fmt;
767                 buf->vb.width  = fh->width;
768                 buf->vb.height = fh->height;
769                 buf->vb.field  = field;
770                 buf->vb.state = STATE_NEEDS_INIT;
771         }
772
773         if (STATE_NEEDS_INIT == buf->vb.state) {
774                 if (0 != (rc = videobuf_iolock(vq,&buf->vb,NULL)))
775                         goto fail;
776                 urb_init=1;
777         }
778
779
780         if (!dev->isoc_ctl.num_bufs)
781                 urb_init=1;
782
783         if (urb_init) {
784                 /* Should allocate/request at least h
785                    res x v res x 2 bytes/pixel */
786                 urbsize=(buf->vb.size+dev->max_isoc_in-1)/dev->max_isoc_in;
787
788                  /* Hack to allocate memory for Video + Audio */
789                 /* FIXME: should also consider header ovehead of
790                    4 bytes/180 bytes */
791                 urbsize+=((48000*4+24)/25+dev->max_isoc_in-1)/dev->max_isoc_in;
792
793                 dprintk(dev, V4L2_DEBUG_QUEUE, "Allocating %d packets to handle "
794                                         "%lu size\n", urbsize,buf->vb.size);
795                 rc = tm6000_prepare_isoc(dev, urbsize, 2);
796
797                 if (rc<0)
798                         goto fail;
799         }
800
801         buf->vb.state = STATE_PREPARED;
802         return 0;
803
804 fail:
805         free_buffer(vq,buf);
806         return rc;
807 }
808
809 static void
810 buffer_queue(struct videobuf_queue *vq, struct videobuf_buffer *vb)
811 {
812         struct tm6000_buffer    *buf     = container_of(vb,struct tm6000_buffer,vb);
813         struct tm6000_fh        *fh      = vq->priv_data;
814         struct tm6000_core      *dev     = fh->dev;
815         struct tm6000_dmaqueue  *vidq    = &dev->vidq;
816         struct tm6000_buffer    *prev;
817
818         if (!list_empty(&vidq->queued)) {
819                 list_add_tail(&buf->vb.queue,&vidq->queued);
820                 buf->vb.state = STATE_QUEUED;
821                 dprintk(dev, V4L2_DEBUG_QUEUE, "[%p/%d] buffer_queue - "
822                                         "append to queued\n", buf, buf->vb.i);
823         } else if (list_empty(&vidq->active)) {
824                 list_add_tail(&buf->vb.queue,&vidq->active);
825                 buf->vb.state = STATE_ACTIVE;
826                 mod_timer(&vidq->timeout, jiffies+BUFFER_TIMEOUT);
827                 dprintk(dev, V4L2_DEBUG_QUEUE, "[%p/%d] buffer_queue - "
828                                         "first active\n", buf, buf->vb.i);
829                 tm6000_start_thread(vidq, buf);
830         } else {
831                 prev = list_entry(vidq->active.prev, struct tm6000_buffer, vb.queue);
832                 if (prev->vb.width  == buf->vb.width  &&
833                     prev->vb.height == buf->vb.height &&
834                     prev->fmt       == buf->fmt) {
835                         list_add_tail(&buf->vb.queue,&vidq->active);
836                         buf->vb.state = STATE_ACTIVE;
837                         dprintk(dev, V4L2_DEBUG_QUEUE, "[%p/%d] buffer_queue -"
838                                         " append to active\n", buf, buf->vb.i);
839                 } else {
840                         list_add_tail(&buf->vb.queue,&vidq->queued);
841                         buf->vb.state = STATE_QUEUED;
842                         dprintk(dev, V4L2_DEBUG_QUEUE, "[%p/%d] buffer_queue -"
843                                         " first queued\n", buf, buf->vb.i);
844                 }
845         }
846 }
847
848 static void buffer_release(struct videobuf_queue *vq, struct videobuf_buffer *vb)
849 {
850         struct tm6000_buffer   *buf  = container_of(vb,struct tm6000_buffer,vb);
851         struct tm6000_fh       *fh   = vq->priv_data;
852         struct tm6000_core      *dev  = (struct tm6000_core*)fh->dev;
853         struct tm6000_dmaqueue *vidq = &dev->vidq;
854
855         tm6000_stop_thread(vidq);
856
857         free_buffer(vq,buf);
858 }
859
860 static struct videobuf_queue_ops tm6000_video_qops = {
861         .buf_setup      = buffer_setup,
862         .buf_prepare    = buffer_prepare,
863         .buf_queue      = buffer_queue,
864         .buf_release    = buffer_release,
865 };
866
867 /* ------------------------------------------------------------------
868         IOCTL handling
869    ------------------------------------------------------------------*/
870
871 static int res_get(struct tm6000_core *dev, struct tm6000_fh *fh)
872 {
873         /* is it free? */
874         mutex_lock(&dev->lock);
875         if (dev->resources) {
876                 /* no, someone else uses it */
877                 mutex_unlock(&dev->lock);
878                 return 0;
879         }
880         /* it's free, grab it */
881         dev->resources =1;
882         dprintk(dev, V4L2_DEBUG_RES_LOCK, "res: get\n");
883         mutex_unlock(&dev->lock);
884         return 1;
885 }
886
887 static int res_locked(struct tm6000_core *dev)
888 {
889         return (dev->resources);
890 }
891
892 static void res_free(struct tm6000_core *dev, struct tm6000_fh *fh)
893 {
894         mutex_lock(&dev->lock);
895         dev->resources = 0;
896         dprintk(dev, V4L2_DEBUG_RES_LOCK, "res: put\n");
897         mutex_unlock(&dev->lock);
898 }
899
900 /* ------------------------------------------------------------------
901         IOCTL vidioc handling
902    ------------------------------------------------------------------*/
903 static int vidioc_querycap (struct file *file, void  *priv,
904                                         struct v4l2_capability *cap)
905 {
906         //      struct tm6000_core *dev = ((struct tm6000_fh *)priv)->dev;
907
908         strlcpy(cap->driver, "tm6000", sizeof(cap->driver));
909         strlcpy(cap->card,"Trident TVMaster TM5600/6000", sizeof(cap->card));
910         //      strlcpy(cap->bus_info, dev->udev->dev.bus_id, sizeof(cap->bus_info));
911         cap->version = TM6000_VERSION;
912         cap->capabilities =     V4L2_CAP_VIDEO_CAPTURE |
913                                 V4L2_CAP_STREAMING     |
914                                 V4L2_CAP_TUNER         |
915                                 V4L2_CAP_READWRITE;
916         return 0;
917 }
918
919 static int vidioc_enum_fmt_cap (struct file *file, void  *priv,
920                                         struct v4l2_fmtdesc *f)
921 {
922         if (unlikely(f->index >= ARRAY_SIZE(format)))
923                 return -EINVAL;
924
925         strlcpy(f->description,format[f->index].name,sizeof(f->description));
926         f->pixelformat = format[f->index].fourcc;
927         return 0;
928 }
929
930 static int vidioc_g_fmt_cap (struct file *file, void *priv,
931                                         struct v4l2_format *f)
932 {
933         struct tm6000_fh  *fh=priv;
934
935         f->fmt.pix.width        = fh->width;
936         f->fmt.pix.height       = fh->height;
937         f->fmt.pix.field        = fh->vb_vidq.field;
938         f->fmt.pix.pixelformat  = fh->fmt->fourcc;
939         f->fmt.pix.bytesperline =
940                 (f->fmt.pix.width * fh->fmt->depth) >> 3;
941         f->fmt.pix.sizeimage =
942                 f->fmt.pix.height * f->fmt.pix.bytesperline;
943
944         return (0);
945 }
946
947 static struct tm6000_fmt* format_by_fourcc(unsigned int fourcc)
948 {
949         unsigned int i;
950
951         for (i = 0; i < ARRAY_SIZE(format); i++)
952                 if (format[i].fourcc == fourcc)
953                         return format+i;
954         return NULL;
955 }
956
957 static int vidioc_try_fmt_cap (struct file *file, void *priv,
958                         struct v4l2_format *f)
959 {
960         struct tm6000_core *dev = ((struct tm6000_fh *)priv)->dev;
961         struct tm6000_fmt *fmt;
962         enum v4l2_field field;
963
964         fmt = format_by_fourcc(f->fmt.pix.pixelformat);
965         if (NULL == fmt) {
966                 dprintk(dev, V4L2_DEBUG_IOCTL_ARG, "Fourcc format (0x%08x)"
967                                 " invalid.\n", f->fmt.pix.pixelformat);
968                 return -EINVAL;
969         }
970
971         field = f->fmt.pix.field;
972
973         if (field == V4L2_FIELD_ANY) {
974 //              field=V4L2_FIELD_INTERLACED;
975                 field=V4L2_FIELD_SEQ_TB;
976         } else if (V4L2_FIELD_INTERLACED != field) {
977                 dprintk(dev, V4L2_DEBUG_IOCTL_ARG, "Field type invalid.\n");
978                 return -EINVAL;
979         }
980
981         if (f->fmt.pix.width  < norm_minw(core))
982                 f->fmt.pix.width = norm_minw(core);
983
984         if (f->fmt.pix.width  > norm_maxw(core))
985                 f->fmt.pix.width = norm_maxw(core);
986
987         if (f->fmt.pix.height < norm_minh(core))
988                 f->fmt.pix.height = norm_minh(core);
989
990         if (f->fmt.pix.height > norm_maxh(core))
991                 f->fmt.pix.height = norm_maxh(core);
992
993         f->fmt.pix.width &= ~0x01;
994
995         f->fmt.pix.field = field;
996
997         f->fmt.pix.bytesperline =
998                 (f->fmt.pix.width * fmt->depth) >> 3;
999         f->fmt.pix.sizeimage =
1000                 f->fmt.pix.height * f->fmt.pix.bytesperline;
1001
1002         return 0;
1003 }
1004
1005 /*FIXME: This seems to be generic enough to be at videodev2 */
1006 static int vidioc_s_fmt_cap (struct file *file, void *priv,
1007                                         struct v4l2_format *f)
1008 {
1009         struct tm6000_fh  *fh=priv;
1010         struct tm6000_core *dev = fh->dev;
1011         int ret = vidioc_try_fmt_cap(file,fh,f);
1012         if (ret < 0)
1013                 return (ret);
1014
1015         fh->fmt           = format_by_fourcc(f->fmt.pix.pixelformat);
1016         fh->width         = f->fmt.pix.width;
1017         fh->height        = f->fmt.pix.height;
1018         fh->vb_vidq.field = f->fmt.pix.field;
1019         fh->type          = f->type;
1020
1021         dev->fourcc       = f->fmt.pix.pixelformat;
1022
1023         tm6000_set_fourcc_format(dev);
1024
1025         return (0);
1026 }
1027
1028 static int vidioc_reqbufs (struct file *file, void *priv,
1029                            struct v4l2_requestbuffers *p)
1030 {
1031         struct tm6000_fh  *fh=priv;
1032
1033         return (videobuf_reqbufs(&fh->vb_vidq, p));
1034 }
1035
1036 static int vidioc_querybuf (struct file *file, void *priv,
1037                             struct v4l2_buffer *p)
1038 {
1039         struct tm6000_fh  *fh=priv;
1040
1041         return (videobuf_querybuf(&fh->vb_vidq, p));
1042 }
1043
1044 static int vidioc_qbuf (struct file *file, void *priv, struct v4l2_buffer *p)
1045 {
1046         struct tm6000_fh  *fh=priv;
1047
1048         return (videobuf_qbuf(&fh->vb_vidq, p));
1049 }
1050
1051 static int vidioc_dqbuf (struct file *file, void *priv, struct v4l2_buffer *p)
1052 {
1053         struct tm6000_fh  *fh=priv;
1054
1055         return (videobuf_dqbuf(&fh->vb_vidq, p,
1056                                 file->f_flags & O_NONBLOCK));
1057 }
1058
1059 #ifdef CONFIG_VIDEO_V4L1_COMPAT
1060 static int vidiocgmbuf (struct file *file, void *priv, struct video_mbuf *mbuf)
1061 {
1062         struct tm6000_fh  *fh=priv;
1063
1064         return videobuf_cgmbuf (&fh->vb_vidq, mbuf, 8);
1065 }
1066 #endif
1067
1068 static int vidioc_streamon(struct file *file, void *priv, enum v4l2_buf_type i)
1069 {
1070         struct tm6000_fh  *fh=priv;
1071         struct tm6000_core *dev    = fh->dev;
1072
1073         if (fh->type != V4L2_BUF_TYPE_VIDEO_CAPTURE)
1074                 return -EINVAL;
1075         if (i != fh->type)
1076                 return -EINVAL;
1077
1078         if (!res_get(dev,fh))
1079                 return -EBUSY;
1080         return (videobuf_streamon(&fh->vb_vidq));
1081 }
1082
1083 static int vidioc_streamoff(struct file *file, void *priv, enum v4l2_buf_type i)
1084 {
1085         struct tm6000_fh  *fh=priv;
1086         struct tm6000_core *dev    = fh->dev;
1087
1088         if (fh->type != V4L2_BUF_TYPE_VIDEO_CAPTURE)
1089                 return -EINVAL;
1090         if (i != fh->type)
1091                 return -EINVAL;
1092
1093         videobuf_streamoff(&fh->vb_vidq);
1094         res_free(dev,fh);
1095
1096         return (0);
1097 }
1098
1099 static int vidioc_s_std (struct file *file, void *priv, v4l2_std_id *norm)
1100 {
1101         int rc=0;
1102         struct tm6000_fh   *fh=priv;
1103         struct tm6000_core *dev = fh->dev;
1104
1105         rc=tm6000_set_standard (dev, norm);
1106         if (rc<0)
1107                 return rc;
1108
1109         tm6000_i2c_call_clients(dev, VIDIOC_S_STD, &dev->norm);
1110
1111         return 0;
1112 }
1113
1114 static int vidioc_enum_input (struct file *file, void *priv,
1115                                 struct v4l2_input *inp)
1116 {
1117         switch (inp->index) {
1118         case TM6000_INPUT_TV:
1119                 inp->type = V4L2_INPUT_TYPE_TUNER;
1120                 strcpy(inp->name,"Television");
1121                 break;
1122         case TM6000_INPUT_COMPOSITE:
1123                 inp->type = V4L2_INPUT_TYPE_CAMERA;
1124                 strcpy(inp->name,"Composite");
1125                 break;
1126         case TM6000_INPUT_SVIDEO:
1127                 inp->type = V4L2_INPUT_TYPE_CAMERA;
1128                 strcpy(inp->name,"S-Video");
1129                 break;
1130         default:
1131                 return -EINVAL;
1132         }
1133         inp->std = TM6000_STD;
1134
1135         return 0;
1136 }
1137
1138 static int vidioc_g_input (struct file *file, void *priv, unsigned int *i)
1139 {
1140         struct tm6000_fh   *fh=priv;
1141         struct tm6000_core *dev = fh->dev;
1142
1143         *i=dev->input;
1144
1145         return 0;
1146 }
1147 static int vidioc_s_input (struct file *file, void *priv, unsigned int i)
1148 {
1149         struct tm6000_fh   *fh=priv;
1150         struct tm6000_core *dev = fh->dev;
1151         int rc=0;
1152         char buf[1];
1153
1154         switch (i) {
1155         case TM6000_INPUT_TV:
1156                 dev->input=i;
1157                 *buf=0;
1158                 break;
1159         case TM6000_INPUT_COMPOSITE:
1160         case TM6000_INPUT_SVIDEO:
1161                 dev->input=i;
1162                 *buf=1;
1163                 break;
1164         default:
1165                 return -EINVAL;
1166         }
1167         rc=tm6000_read_write_usb (dev, USB_DIR_OUT | USB_TYPE_VENDOR,
1168                                REQ_03_SET_GET_MCU_PIN, 0x03, 1, buf, 1);
1169
1170         if (!rc) {
1171                 dev->input=i;
1172                 rc=vidioc_s_std (file, priv, &dev->vfd->current_norm);
1173         }
1174
1175         return (rc);
1176 }
1177
1178         /* --- controls ---------------------------------------------- */
1179 static int vidioc_queryctrl (struct file *file, void *priv,
1180                                 struct v4l2_queryctrl *qc)
1181 {
1182         int i;
1183
1184         for (i = 0; i < ARRAY_SIZE(tm6000_qctrl); i++)
1185                 if (qc->id && qc->id == tm6000_qctrl[i].id) {
1186                         memcpy(qc, &(tm6000_qctrl[i]),
1187                                 sizeof(*qc));
1188                         return (0);
1189                 }
1190
1191         return -EINVAL;
1192 }
1193
1194 static int vidioc_g_ctrl (struct file *file, void *priv,
1195                                 struct v4l2_control *ctrl)
1196 {
1197         struct tm6000_fh  *fh=priv;
1198         struct tm6000_core *dev    = fh->dev;
1199         int  val;
1200
1201         /* FIXME: Probably, those won't work! Maybe we need shadow regs */
1202         switch (ctrl->id) {
1203         case V4L2_CID_CONTRAST:
1204                 val=tm6000_get_reg (dev, REQ_07_SET_GET_AVREG, 0x08, 0);
1205                 break;
1206         case V4L2_CID_BRIGHTNESS:
1207                 val=tm6000_get_reg (dev, REQ_07_SET_GET_AVREG, 0x09, 0);
1208                 return 0;
1209         case V4L2_CID_SATURATION:
1210                 val=tm6000_get_reg (dev, REQ_07_SET_GET_AVREG, 0x0a, 0);
1211                 return 0;
1212         case V4L2_CID_HUE:
1213                 val=tm6000_get_reg (dev, REQ_07_SET_GET_AVREG, 0x0b, 0);
1214                 return 0;
1215         default:
1216                 return -EINVAL;
1217         }
1218
1219         if (val<0)
1220                 return val;
1221
1222         ctrl->value=val;
1223
1224         return 0;
1225 }
1226 static int vidioc_s_ctrl (struct file *file, void *priv,
1227                                 struct v4l2_control *ctrl)
1228 {
1229         struct tm6000_fh   *fh  =priv;
1230         struct tm6000_core *dev = fh->dev;
1231         u8  val=ctrl->value;
1232
1233         switch (ctrl->id) {
1234         case V4L2_CID_CONTRAST:
1235   tm6000_set_reg (dev, REQ_07_SET_GET_AVREG, 0x08, val);
1236                 return 0;
1237         case V4L2_CID_BRIGHTNESS:
1238   tm6000_set_reg (dev, REQ_07_SET_GET_AVREG, 0x09, val);
1239                 return 0;
1240         case V4L2_CID_SATURATION:
1241   tm6000_set_reg (dev, REQ_07_SET_GET_AVREG, 0x0a, val);
1242                 return 0;
1243         case V4L2_CID_HUE:
1244   tm6000_set_reg (dev, REQ_07_SET_GET_AVREG, 0x0b, val);
1245                 return 0;
1246         }
1247         return -EINVAL;
1248 }
1249
1250 static int vidioc_g_tuner (struct file *file, void *priv,
1251                                 struct v4l2_tuner *t)
1252 {
1253         struct tm6000_fh   *fh  =priv;
1254         struct tm6000_core *dev = fh->dev;
1255
1256         if (unlikely(UNSET == dev->tuner_type))
1257                 return -EINVAL;
1258         if (0 != t->index)
1259                 return -EINVAL;
1260
1261         strcpy(t->name, "Television");
1262         t->type       = V4L2_TUNER_ANALOG_TV;
1263         t->capability = V4L2_TUNER_CAP_NORM;
1264         t->rangehigh  = 0xffffffffUL;
1265         t->rxsubchans = V4L2_TUNER_SUB_MONO;
1266
1267         return 0;
1268 }
1269
1270 static int vidioc_s_tuner (struct file *file, void *priv,
1271                                 struct v4l2_tuner *t)
1272 {
1273         struct tm6000_fh   *fh  =priv;
1274         struct tm6000_core *dev = fh->dev;
1275
1276         if (UNSET == dev->tuner_type)
1277                 return -EINVAL;
1278         if (0 != t->index)
1279                 return -EINVAL;
1280
1281         return 0;
1282 }
1283
1284 static int vidioc_g_frequency (struct file *file, void *priv,
1285                                 struct v4l2_frequency *f)
1286 {
1287         struct tm6000_fh   *fh  =priv;
1288         struct tm6000_core *dev = fh->dev;
1289
1290         if (unlikely(UNSET == dev->tuner_type))
1291                 return -EINVAL;
1292
1293         f->type = V4L2_TUNER_ANALOG_TV;
1294         f->frequency = dev->freq;
1295
1296         tm6000_i2c_call_clients(dev,VIDIOC_G_FREQUENCY,f);
1297
1298         return 0;
1299 }
1300
1301 static int vidioc_s_frequency (struct file *file, void *priv,
1302                                 struct v4l2_frequency *f)
1303 {
1304         struct tm6000_fh   *fh  =priv;
1305         struct tm6000_core *dev = fh->dev;
1306
1307         if (unlikely(f->type != V4L2_TUNER_ANALOG_TV))
1308                 return -EINVAL;
1309
1310         if (unlikely(UNSET == dev->tuner_type))
1311                 return -EINVAL;
1312         if (unlikely(f->tuner != 0))
1313                 return -EINVAL;
1314
1315 //      mutex_lock(&dev->lock);
1316         dev->freq = f->frequency;
1317         tm6000_i2c_call_clients(dev,VIDIOC_S_FREQUENCY,f);
1318 //      mutex_unlock(&dev->lock);
1319
1320         return 0;
1321 }
1322
1323 /* ------------------------------------------------------------------
1324         File operations for the device
1325    ------------------------------------------------------------------*/
1326
1327 static int tm6000_open(struct inode *inode, struct file *file)
1328 {
1329         int minor = iminor(inode);
1330         struct tm6000_core *h,*dev = NULL;
1331         struct tm6000_fh *fh;
1332         struct list_head *list;
1333         enum v4l2_buf_type type = 0;
1334         int i,rc;
1335
1336         printk(KERN_INFO "tm6000: open called (minor=%d)\n",minor);
1337
1338
1339         dprintk(dev, V4L2_DEBUG_OPEN, "tm6000: open called "
1340                                                 "(minor=%d)\n",minor);
1341
1342         list_for_each(list,&tm6000_corelist) {
1343                 h = list_entry(list, struct tm6000_core, tm6000_corelist);
1344                 if (h->vfd->minor == minor) {
1345                         dev  = h;
1346                         type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
1347                 }
1348         }
1349         if (NULL == dev)
1350                 return -ENODEV;
1351
1352
1353         /* If more than one user, mutex should be added */
1354         dev->users++;
1355
1356         dprintk(dev, V4L2_DEBUG_OPEN, "open minor=%d type=%s users=%d\n",
1357                                 minor,v4l2_type_names[type],dev->users);
1358
1359         /* allocate + initialize per filehandle data */
1360         fh = kzalloc(sizeof(*fh),GFP_KERNEL);
1361         if (NULL == fh) {
1362                 dev->users--;
1363                 return -ENOMEM;
1364         }
1365
1366         file->private_data = fh;
1367         fh->dev      = dev;
1368
1369         fh->type     = V4L2_BUF_TYPE_VIDEO_CAPTURE;
1370         dev->fourcc  = format[0].fourcc;
1371
1372         fh->fmt      = format_by_fourcc(dev->fourcc);
1373         fh->width    = norm_maxw();
1374         fh->height   = norm_maxh();
1375
1376         dprintk(dev, V4L2_DEBUG_OPEN, "Open: fh=0x%08lx, dev=0x%08lx, "
1377                                                 "dev->vidq=0x%08lx\n",
1378                 (unsigned long)fh,(unsigned long)dev,(unsigned long)&dev->vidq);
1379         dprintk(dev, V4L2_DEBUG_OPEN, "Open: list_empty "
1380                                 "queued=%d\n",list_empty(&dev->vidq.queued));
1381         dprintk(dev, V4L2_DEBUG_OPEN, "Open: list_empty "
1382                                 "active=%d\n",list_empty(&dev->vidq.active));
1383
1384         /* initialize hardware on analog mode */
1385         if (dev->mode!=TM6000_MODE_ANALOG) {
1386                 rc=tm6000_init_analog_mode (dev);
1387                 if (rc<0)
1388                         return rc;
1389
1390                 /* Put all controls at a sane state */
1391                 for (i = 0; i < ARRAY_SIZE(tm6000_qctrl); i++)
1392                         qctl_regs[i] =tm6000_qctrl[i].default_value;
1393
1394                 dev->mode=TM6000_MODE_ANALOG;
1395         }
1396
1397         videobuf_queue_vmalloc_init(&fh->vb_vidq, &tm6000_video_qops,
1398                         NULL, &dev->slock,
1399                         fh->type,
1400                         V4L2_FIELD_INTERLACED,
1401                         sizeof(struct tm6000_buffer),fh);
1402
1403         return 0;
1404 }
1405
1406 static ssize_t
1407 tm6000_read(struct file *file, char __user *data, size_t count, loff_t *pos)
1408 {
1409         struct tm6000_fh        *fh = file->private_data;
1410
1411         if (fh->type==V4L2_BUF_TYPE_VIDEO_CAPTURE) {
1412                 if (res_locked(fh->dev))
1413                         return -EBUSY;
1414
1415                 return videobuf_read_stream(&fh->vb_vidq, data, count, pos, 0,
1416                                         file->f_flags & O_NONBLOCK);
1417         }
1418         return 0;
1419 }
1420
1421 static unsigned int
1422 tm6000_poll(struct file *file, struct poll_table_struct *wait)
1423 {
1424         struct tm6000_fh        *fh = file->private_data;
1425         struct tm6000_buffer    *buf;
1426
1427         if (V4L2_BUF_TYPE_VIDEO_CAPTURE != fh->type)
1428                 return POLLERR;
1429
1430         if (res_get(fh->dev,fh)) {
1431                 /* streaming capture */
1432                 if (list_empty(&fh->vb_vidq.stream))
1433                         return POLLERR;
1434                 buf = list_entry(fh->vb_vidq.stream.next,struct tm6000_buffer,vb.stream);
1435         } else {
1436                 /* read() capture */
1437                 buf = (struct tm6000_buffer*)fh->vb_vidq.read_buf;
1438                 if (NULL == buf)
1439                         return POLLERR;
1440         }
1441         poll_wait(file, &buf->vb.done, wait);
1442         if (buf->vb.state == STATE_DONE ||
1443             buf->vb.state == STATE_ERROR)
1444                 return POLLIN|POLLRDNORM;
1445         return 0;
1446 }
1447
1448 static int tm6000_release(struct inode *inode, struct file *file)
1449 {
1450         struct tm6000_fh         *fh = file->private_data;
1451         struct tm6000_core      *dev = fh->dev;
1452         struct tm6000_dmaqueue *vidq = &dev->vidq;
1453         int minor = iminor(inode);
1454
1455         dprintk(dev, V4L2_DEBUG_OPEN, "tm6000: close called (minor=%d, users=%d)\n",minor,dev->users);
1456
1457         dev->users--;
1458
1459         if (!dev->users) {
1460                 tm6000_stop_thread(vidq);
1461                 videobuf_mmap_free(&fh->vb_vidq);
1462         }
1463
1464         kfree (fh);
1465
1466         return 0;
1467 }
1468
1469 static int tm6000_mmap(struct file *file, struct vm_area_struct * vma)
1470 {
1471         struct tm6000_fh        *fh = file->private_data;
1472         int ret;
1473
1474         ret=videobuf_mmap_mapper(&fh->vb_vidq, vma);
1475
1476         return ret;
1477 }
1478
1479 static struct file_operations tm6000_fops = {
1480         .owner          = THIS_MODULE,
1481         .open           = tm6000_open,
1482         .release        = tm6000_release,
1483         .ioctl          = video_ioctl2, /* V4L2 ioctl handler */
1484         .read           = tm6000_read,
1485         .poll           = tm6000_poll,
1486         .mmap           = tm6000_mmap,
1487         .llseek         = no_llseek,
1488 };
1489
1490 static struct video_device tm6000_template = {
1491         .name           = "tm6000",
1492         .type           = VID_TYPE_CAPTURE,
1493         .fops           = &tm6000_fops,
1494         .minor          = -1,
1495         .release        = video_device_release,
1496
1497         .vidioc_querycap      = vidioc_querycap,
1498         .vidioc_enum_fmt_cap  = vidioc_enum_fmt_cap,
1499         .vidioc_g_fmt_cap     = vidioc_g_fmt_cap,
1500         .vidioc_try_fmt_cap   = vidioc_try_fmt_cap,
1501         .vidioc_s_fmt_cap     = vidioc_s_fmt_cap,
1502         .vidioc_s_std         = vidioc_s_std,
1503         .vidioc_enum_input    = vidioc_enum_input,
1504         .vidioc_g_input       = vidioc_g_input,
1505         .vidioc_s_input       = vidioc_s_input,
1506         .vidioc_queryctrl     = vidioc_queryctrl,
1507         .vidioc_g_ctrl        = vidioc_g_ctrl,
1508         .vidioc_s_ctrl        = vidioc_s_ctrl,
1509         .vidioc_g_tuner       = vidioc_g_tuner,
1510         .vidioc_s_tuner       = vidioc_s_tuner,
1511         .vidioc_g_frequency   = vidioc_g_frequency,
1512         .vidioc_s_frequency   = vidioc_s_frequency,
1513         .vidioc_streamon      = vidioc_streamon,
1514         .vidioc_streamoff     = vidioc_streamoff,
1515         .vidioc_reqbufs       = vidioc_reqbufs,
1516         .vidioc_querybuf      = vidioc_querybuf,
1517         .vidioc_qbuf          = vidioc_qbuf,
1518         .vidioc_dqbuf         = vidioc_dqbuf,
1519 #ifdef CONFIG_VIDEO_V4L1_COMPAT
1520         .vidiocgmbuf          = vidiocgmbuf,
1521 #endif
1522         .tvnorms              = TM6000_STD,
1523         .current_norm         = V4L2_STD_NTSC_M,
1524 };
1525 /* -----------------------------------------------------------------
1526         Initialization and module stuff
1527    ------------------------------------------------------------------*/
1528
1529 int tm6000_v4l2_register(struct tm6000_core *dev)
1530 {
1531         int ret = -1;
1532         struct video_device *vfd;
1533
1534         vfd = video_device_alloc();
1535         if(!vfd) {
1536                 return -ENOMEM;
1537         }
1538         dev->vfd = vfd;
1539
1540         list_add_tail(&dev->tm6000_corelist,&tm6000_corelist);
1541
1542         /* init video dma queues */
1543         INIT_LIST_HEAD(&dev->vidq.active);
1544         INIT_LIST_HEAD(&dev->vidq.queued);
1545
1546         dev->vidq.timeout.function = tm6000_vid_timeout;
1547         dev->vidq.timeout.data     = (unsigned long)dev;
1548         init_timer(&dev->vidq.timeout);
1549
1550         memcpy (dev->vfd, &tm6000_template, sizeof(*(dev->vfd)));
1551         dev->vfd->debug=tm6000_debug;
1552
1553         ret = video_register_device(dev->vfd, VFL_TYPE_GRABBER, video_nr);
1554         printk(KERN_INFO "Trident TVMaster TM5600/TM6000 USB2 board (Load status: %d)\n", ret);
1555         return ret;
1556 }
1557
1558 int tm6000_v4l2_unregister(struct tm6000_core *dev)
1559 {
1560         struct tm6000_core *h;
1561         struct list_head *pos, *tmp;
1562
1563         video_unregister_device(dev->vfd);
1564
1565         list_for_each_safe(pos, tmp, &tm6000_corelist) {
1566                 h = list_entry(pos, struct tm6000_core, tm6000_corelist);
1567                 if (h == dev) {
1568                         list_del(pos);
1569                 }
1570         }
1571
1572         return 0;
1573 }
1574
1575 int tm6000_v4l2_exit(void)
1576 {
1577         return 0;
1578 }
1579
1580 module_param(video_nr, int, 0);
1581 MODULE_PARM_DESC(video_nr,"Allow changing video device number");
1582
1583 module_param_named (debug, tm6000_debug, int, 0444);
1584 MODULE_PARM_DESC(debug,"activates debug info");
1585
1586 module_param(vid_limit,int,0644);
1587 MODULE_PARM_DESC(vid_limit,"capture memory limit in megabytes");
1588