OSDN Git Service

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