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