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