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