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