]> asedeno.scripts.mit.edu Git - linux.git/blob - drivers/media/usb/cx231xx/cx231xx-video.c
Linux 5.3-rc4
[linux.git] / drivers / media / usb / cx231xx / cx231xx-video.c
1 // SPDX-License-Identifier: GPL-2.0-or-later
2 /*
3    cx231xx-video.c - driver for Conexant Cx23100/101/102
4                      USB video capture devices
5
6    Copyright (C) 2008 <srinivasa.deevi at conexant dot com>
7         Based on em28xx driver
8         Based on cx23885 driver
9         Based on cx88 driver
10
11  */
12
13 #include "cx231xx.h"
14 #include <linux/init.h>
15 #include <linux/list.h>
16 #include <linux/module.h>
17 #include <linux/kernel.h>
18 #include <linux/bitmap.h>
19 #include <linux/i2c.h>
20 #include <linux/mm.h>
21 #include <linux/mutex.h>
22 #include <linux/slab.h>
23
24 #include <media/v4l2-common.h>
25 #include <media/v4l2-ioctl.h>
26 #include <media/v4l2-event.h>
27 #include <media/drv-intf/msp3400.h>
28 #include <media/tuner.h>
29
30 #include <media/dvb_frontend.h>
31
32 #include "cx231xx-vbi.h"
33
34 #define CX231XX_VERSION "0.0.3"
35
36 #define DRIVER_AUTHOR   "Srinivasa Deevi <srinivasa.deevi@conexant.com>"
37 #define DRIVER_DESC     "Conexant cx231xx based USB video device driver"
38
39 #define cx231xx_videodbg(fmt, arg...) do {\
40         if (video_debug) \
41                 printk(KERN_INFO "%s %s :"fmt, \
42                          dev->name, __func__ , ##arg); } while (0)
43
44 static unsigned int isoc_debug;
45 module_param(isoc_debug, int, 0644);
46 MODULE_PARM_DESC(isoc_debug, "enable debug messages [isoc transfers]");
47
48 #define cx231xx_isocdbg(fmt, arg...) \
49 do {\
50         if (isoc_debug) { \
51                 printk(KERN_INFO "%s %s :"fmt, \
52                          dev->name, __func__ , ##arg); \
53         } \
54   } while (0)
55
56 MODULE_AUTHOR(DRIVER_AUTHOR);
57 MODULE_DESCRIPTION(DRIVER_DESC);
58 MODULE_LICENSE("GPL");
59 MODULE_VERSION(CX231XX_VERSION);
60
61 static unsigned int card[]     = {[0 ... (CX231XX_MAXBOARDS - 1)] = UNSET };
62 static unsigned int video_nr[] = {[0 ... (CX231XX_MAXBOARDS - 1)] = UNSET };
63 static unsigned int vbi_nr[]   = {[0 ... (CX231XX_MAXBOARDS - 1)] = UNSET };
64 static unsigned int radio_nr[] = {[0 ... (CX231XX_MAXBOARDS - 1)] = UNSET };
65
66 module_param_array(card, int, NULL, 0444);
67 module_param_array(video_nr, int, NULL, 0444);
68 module_param_array(vbi_nr, int, NULL, 0444);
69 module_param_array(radio_nr, int, NULL, 0444);
70
71 MODULE_PARM_DESC(card, "card type");
72 MODULE_PARM_DESC(video_nr, "video device numbers");
73 MODULE_PARM_DESC(vbi_nr, "vbi device numbers");
74 MODULE_PARM_DESC(radio_nr, "radio device numbers");
75
76 static unsigned int video_debug;
77 module_param(video_debug, int, 0644);
78 MODULE_PARM_DESC(video_debug, "enable debug messages [video]");
79
80 /* supported video standards */
81 static struct cx231xx_fmt format[] = {
82         {
83          .name = "16bpp YUY2, 4:2:2, packed",
84          .fourcc = V4L2_PIX_FMT_YUYV,
85          .depth = 16,
86          .reg = 0,
87          },
88 };
89
90
91 static int cx231xx_enable_analog_tuner(struct cx231xx *dev)
92 {
93 #ifdef CONFIG_MEDIA_CONTROLLER
94         struct media_device *mdev = dev->media_dev;
95         struct media_entity  *entity, *decoder = NULL, *source;
96         struct media_link *link, *found_link = NULL;
97         int ret, active_links = 0;
98
99         if (!mdev)
100                 return 0;
101
102         /*
103          * This will find the tuner that is connected into the decoder.
104          * Technically, this is not 100% correct, as the device may be
105          * using an analog input instead of the tuner. However, as we can't
106          * do DVB streaming while the DMA engine is being used for V4L2,
107          * this should be enough for the actual needs.
108          */
109         media_device_for_each_entity(entity, mdev) {
110                 if (entity->function == MEDIA_ENT_F_ATV_DECODER) {
111                         decoder = entity;
112                         break;
113                 }
114         }
115         if (!decoder)
116                 return 0;
117
118         list_for_each_entry(link, &decoder->links, list) {
119                 if (link->sink->entity == decoder) {
120                         found_link = link;
121                         if (link->flags & MEDIA_LNK_FL_ENABLED)
122                                 active_links++;
123                         break;
124                 }
125         }
126
127         if (active_links == 1 || !found_link)
128                 return 0;
129
130         source = found_link->source->entity;
131         list_for_each_entry(link, &source->links, list) {
132                 struct media_entity *sink;
133                 int flags = 0;
134
135                 sink = link->sink->entity;
136
137                 if (sink == entity)
138                         flags = MEDIA_LNK_FL_ENABLED;
139
140                 ret = media_entity_setup_link(link, flags);
141                 if (ret) {
142                         dev_err(dev->dev,
143                                 "Couldn't change link %s->%s to %s. Error %d\n",
144                                 source->name, sink->name,
145                                 flags ? "enabled" : "disabled",
146                                 ret);
147                         return ret;
148                 } else
149                         dev_dbg(dev->dev,
150                                 "link %s->%s was %s\n",
151                                 source->name, sink->name,
152                                 flags ? "ENABLED" : "disabled");
153         }
154 #endif
155         return 0;
156 }
157
158 /* ------------------------------------------------------------------
159         Video buffer and parser functions
160    ------------------------------------------------------------------*/
161
162 /*
163  * Announces that a buffer were filled and request the next
164  */
165 static inline void buffer_filled(struct cx231xx *dev,
166                                  struct cx231xx_dmaqueue *dma_q,
167                                  struct cx231xx_buffer *buf)
168 {
169         /* Advice that buffer was filled */
170         cx231xx_isocdbg("[%p/%d] wakeup\n", buf, buf->vb.i);
171         buf->vb.state = VIDEOBUF_DONE;
172         buf->vb.field_count++;
173         buf->vb.ts = ktime_get_ns();
174
175         if (dev->USE_ISO)
176                 dev->video_mode.isoc_ctl.buf = NULL;
177         else
178                 dev->video_mode.bulk_ctl.buf = NULL;
179
180         list_del(&buf->vb.queue);
181         wake_up(&buf->vb.done);
182 }
183
184 static inline void print_err_status(struct cx231xx *dev, int packet, int status)
185 {
186         char *errmsg = "Unknown";
187
188         switch (status) {
189         case -ENOENT:
190                 errmsg = "unlinked synchronously";
191                 break;
192         case -ECONNRESET:
193                 errmsg = "unlinked asynchronously";
194                 break;
195         case -ENOSR:
196                 errmsg = "Buffer error (overrun)";
197                 break;
198         case -EPIPE:
199                 errmsg = "Stalled (device not responding)";
200                 break;
201         case -EOVERFLOW:
202                 errmsg = "Babble (bad cable?)";
203                 break;
204         case -EPROTO:
205                 errmsg = "Bit-stuff error (bad cable?)";
206                 break;
207         case -EILSEQ:
208                 errmsg = "CRC/Timeout (could be anything)";
209                 break;
210         case -ETIME:
211                 errmsg = "Device does not respond";
212                 break;
213         }
214         if (packet < 0) {
215                 cx231xx_isocdbg("URB status %d [%s].\n", status, errmsg);
216         } else {
217                 cx231xx_isocdbg("URB packet %d, status %d [%s].\n",
218                                 packet, status, errmsg);
219         }
220 }
221
222 /*
223  * video-buf generic routine to get the next available buffer
224  */
225 static inline void get_next_buf(struct cx231xx_dmaqueue *dma_q,
226                                 struct cx231xx_buffer **buf)
227 {
228         struct cx231xx_video_mode *vmode =
229             container_of(dma_q, struct cx231xx_video_mode, vidq);
230         struct cx231xx *dev = container_of(vmode, struct cx231xx, video_mode);
231
232         char *outp;
233
234         if (list_empty(&dma_q->active)) {
235                 cx231xx_isocdbg("No active queue to serve\n");
236                 if (dev->USE_ISO)
237                         dev->video_mode.isoc_ctl.buf = NULL;
238                 else
239                         dev->video_mode.bulk_ctl.buf = NULL;
240                 *buf = NULL;
241                 return;
242         }
243
244         /* Get the next buffer */
245         *buf = list_entry(dma_q->active.next, struct cx231xx_buffer, vb.queue);
246
247         /* Cleans up buffer - Useful for testing for frame/URB loss */
248         outp = videobuf_to_vmalloc(&(*buf)->vb);
249         memset(outp, 0, (*buf)->vb.size);
250
251         if (dev->USE_ISO)
252                 dev->video_mode.isoc_ctl.buf = *buf;
253         else
254                 dev->video_mode.bulk_ctl.buf = *buf;
255
256         return;
257 }
258
259 /*
260  * Controls the isoc copy of each urb packet
261  */
262 static inline int cx231xx_isoc_copy(struct cx231xx *dev, struct urb *urb)
263 {
264         struct cx231xx_dmaqueue *dma_q = urb->context;
265         int i;
266         unsigned char *p_buffer;
267         u32 bytes_parsed = 0, buffer_size = 0;
268         u8 sav_eav = 0;
269
270         if (!dev)
271                 return 0;
272
273         if (dev->state & DEV_DISCONNECTED)
274                 return 0;
275
276         if (urb->status < 0) {
277                 print_err_status(dev, -1, urb->status);
278                 if (urb->status == -ENOENT)
279                         return 0;
280         }
281
282         for (i = 0; i < urb->number_of_packets; i++) {
283                 int status = urb->iso_frame_desc[i].status;
284
285                 if (status < 0) {
286                         print_err_status(dev, i, status);
287                         if (urb->iso_frame_desc[i].status != -EPROTO)
288                                 continue;
289                 }
290
291                 if (urb->iso_frame_desc[i].actual_length <= 0) {
292                         /* cx231xx_isocdbg("packet %d is empty",i); - spammy */
293                         continue;
294                 }
295                 if (urb->iso_frame_desc[i].actual_length >
296                     dev->video_mode.max_pkt_size) {
297                         cx231xx_isocdbg("packet bigger than packet size");
298                         continue;
299                 }
300
301                 /*  get buffer pointer and length */
302                 p_buffer = urb->transfer_buffer + urb->iso_frame_desc[i].offset;
303                 buffer_size = urb->iso_frame_desc[i].actual_length;
304                 bytes_parsed = 0;
305
306                 if (dma_q->is_partial_line) {
307                         /* Handle the case of a partial line */
308                         sav_eav = dma_q->last_sav;
309                 } else {
310                         /* Check for a SAV/EAV overlapping
311                                 the buffer boundary */
312                         sav_eav =
313                             cx231xx_find_boundary_SAV_EAV(p_buffer,
314                                                           dma_q->partial_buf,
315                                                           &bytes_parsed);
316                 }
317
318                 sav_eav &= 0xF0;
319                 /* Get the first line if we have some portion of an SAV/EAV from
320                    the last buffer or a partial line  */
321                 if (sav_eav) {
322                         bytes_parsed += cx231xx_get_video_line(dev, dma_q,
323                                 sav_eav,        /* SAV/EAV */
324                                 p_buffer + bytes_parsed,        /* p_buffer */
325                                 buffer_size - bytes_parsed);/* buf size */
326                 }
327
328                 /* Now parse data that is completely in this buffer */
329                 /* dma_q->is_partial_line = 0;  */
330
331                 while (bytes_parsed < buffer_size) {
332                         u32 bytes_used = 0;
333
334                         sav_eav = cx231xx_find_next_SAV_EAV(
335                                 p_buffer + bytes_parsed,        /* p_buffer */
336                                 buffer_size - bytes_parsed,     /* buf size */
337                                 &bytes_used);/* bytes used to get SAV/EAV */
338
339                         bytes_parsed += bytes_used;
340
341                         sav_eav &= 0xF0;
342                         if (sav_eav && (bytes_parsed < buffer_size)) {
343                                 bytes_parsed += cx231xx_get_video_line(dev,
344                                         dma_q, sav_eav, /* SAV/EAV */
345                                         p_buffer + bytes_parsed,/* p_buffer */
346                                         buffer_size - bytes_parsed);/*buf size*/
347                         }
348                 }
349
350                 /* Save the last four bytes of the buffer so we can check the
351                    buffer boundary condition next time */
352                 memcpy(dma_q->partial_buf, p_buffer + buffer_size - 4, 4);
353                 bytes_parsed = 0;
354
355         }
356         return 1;
357 }
358
359 static inline int cx231xx_bulk_copy(struct cx231xx *dev, struct urb *urb)
360 {
361         struct cx231xx_dmaqueue *dma_q = urb->context;
362         unsigned char *p_buffer;
363         u32 bytes_parsed = 0, buffer_size = 0;
364         u8 sav_eav = 0;
365
366         if (!dev)
367                 return 0;
368
369         if (dev->state & DEV_DISCONNECTED)
370                 return 0;
371
372         if (urb->status < 0) {
373                 print_err_status(dev, -1, urb->status);
374                 if (urb->status == -ENOENT)
375                         return 0;
376         }
377
378         if (1) {
379
380                 /*  get buffer pointer and length */
381                 p_buffer = urb->transfer_buffer;
382                 buffer_size = urb->actual_length;
383                 bytes_parsed = 0;
384
385                 if (dma_q->is_partial_line) {
386                         /* Handle the case of a partial line */
387                         sav_eav = dma_q->last_sav;
388                 } else {
389                         /* Check for a SAV/EAV overlapping
390                                 the buffer boundary */
391                         sav_eav =
392                             cx231xx_find_boundary_SAV_EAV(p_buffer,
393                                                           dma_q->partial_buf,
394                                                           &bytes_parsed);
395                 }
396
397                 sav_eav &= 0xF0;
398                 /* Get the first line if we have some portion of an SAV/EAV from
399                    the last buffer or a partial line  */
400                 if (sav_eav) {
401                         bytes_parsed += cx231xx_get_video_line(dev, dma_q,
402                                 sav_eav,        /* SAV/EAV */
403                                 p_buffer + bytes_parsed,        /* p_buffer */
404                                 buffer_size - bytes_parsed);/* buf size */
405                 }
406
407                 /* Now parse data that is completely in this buffer */
408                 /* dma_q->is_partial_line = 0;  */
409
410                 while (bytes_parsed < buffer_size) {
411                         u32 bytes_used = 0;
412
413                         sav_eav = cx231xx_find_next_SAV_EAV(
414                                 p_buffer + bytes_parsed,        /* p_buffer */
415                                 buffer_size - bytes_parsed,     /* buf size */
416                                 &bytes_used);/* bytes used to get SAV/EAV */
417
418                         bytes_parsed += bytes_used;
419
420                         sav_eav &= 0xF0;
421                         if (sav_eav && (bytes_parsed < buffer_size)) {
422                                 bytes_parsed += cx231xx_get_video_line(dev,
423                                         dma_q, sav_eav, /* SAV/EAV */
424                                         p_buffer + bytes_parsed,/* p_buffer */
425                                         buffer_size - bytes_parsed);/*buf size*/
426                         }
427                 }
428
429                 /* Save the last four bytes of the buffer so we can check the
430                    buffer boundary condition next time */
431                 memcpy(dma_q->partial_buf, p_buffer + buffer_size - 4, 4);
432                 bytes_parsed = 0;
433
434         }
435         return 1;
436 }
437
438
439 u8 cx231xx_find_boundary_SAV_EAV(u8 *p_buffer, u8 *partial_buf,
440                                  u32 *p_bytes_used)
441 {
442         u32 bytes_used;
443         u8 boundary_bytes[8];
444         u8 sav_eav = 0;
445
446         *p_bytes_used = 0;
447
448         /* Create an array of the last 4 bytes of the last buffer and the first
449            4 bytes of the current buffer. */
450
451         memcpy(boundary_bytes, partial_buf, 4);
452         memcpy(boundary_bytes + 4, p_buffer, 4);
453
454         /* Check for the SAV/EAV in the boundary buffer */
455         sav_eav = cx231xx_find_next_SAV_EAV((u8 *)&boundary_bytes, 8,
456                                             &bytes_used);
457
458         if (sav_eav) {
459                 /* found a boundary SAV/EAV.  Updates the bytes used to reflect
460                    only those used in the new buffer */
461                 *p_bytes_used = bytes_used - 4;
462         }
463
464         return sav_eav;
465 }
466
467 u8 cx231xx_find_next_SAV_EAV(u8 *p_buffer, u32 buffer_size, u32 *p_bytes_used)
468 {
469         u32 i;
470         u8 sav_eav = 0;
471
472         /*
473          * Don't search if the buffer size is less than 4.  It causes a page
474          * fault since buffer_size - 4 evaluates to a large number in that
475          * case.
476          */
477         if (buffer_size < 4) {
478                 *p_bytes_used = buffer_size;
479                 return 0;
480         }
481
482         for (i = 0; i < (buffer_size - 3); i++) {
483
484                 if ((p_buffer[i] == 0xFF) &&
485                     (p_buffer[i + 1] == 0x00) && (p_buffer[i + 2] == 0x00)) {
486
487                         *p_bytes_used = i + 4;
488                         sav_eav = p_buffer[i + 3];
489                         return sav_eav;
490                 }
491         }
492
493         *p_bytes_used = buffer_size;
494         return 0;
495 }
496
497 u32 cx231xx_get_video_line(struct cx231xx *dev,
498                            struct cx231xx_dmaqueue *dma_q, u8 sav_eav,
499                            u8 *p_buffer, u32 buffer_size)
500 {
501         u32 bytes_copied = 0;
502         int current_field = -1;
503
504         switch (sav_eav) {
505         case SAV_ACTIVE_VIDEO_FIELD1:
506                 /* looking for skipped line which occurred in PAL 720x480 mode.
507                    In this case, there will be no active data contained
508                    between the SAV and EAV */
509                 if ((buffer_size > 3) && (p_buffer[0] == 0xFF) &&
510                     (p_buffer[1] == 0x00) && (p_buffer[2] == 0x00) &&
511                     ((p_buffer[3] == EAV_ACTIVE_VIDEO_FIELD1) ||
512                      (p_buffer[3] == EAV_ACTIVE_VIDEO_FIELD2) ||
513                      (p_buffer[3] == EAV_VBLANK_FIELD1) ||
514                      (p_buffer[3] == EAV_VBLANK_FIELD2)))
515                         return bytes_copied;
516                 current_field = 1;
517                 break;
518
519         case SAV_ACTIVE_VIDEO_FIELD2:
520                 /* looking for skipped line which occurred in PAL 720x480 mode.
521                    In this case, there will be no active data contained between
522                    the SAV and EAV */
523                 if ((buffer_size > 3) && (p_buffer[0] == 0xFF) &&
524                     (p_buffer[1] == 0x00) && (p_buffer[2] == 0x00) &&
525                     ((p_buffer[3] == EAV_ACTIVE_VIDEO_FIELD1) ||
526                      (p_buffer[3] == EAV_ACTIVE_VIDEO_FIELD2) ||
527                      (p_buffer[3] == EAV_VBLANK_FIELD1)       ||
528                      (p_buffer[3] == EAV_VBLANK_FIELD2)))
529                         return bytes_copied;
530                 current_field = 2;
531                 break;
532         }
533
534         dma_q->last_sav = sav_eav;
535
536         bytes_copied = cx231xx_copy_video_line(dev, dma_q, p_buffer,
537                                                buffer_size, current_field);
538
539         return bytes_copied;
540 }
541
542 u32 cx231xx_copy_video_line(struct cx231xx *dev,
543                             struct cx231xx_dmaqueue *dma_q, u8 *p_line,
544                             u32 length, int field_number)
545 {
546         u32 bytes_to_copy;
547         struct cx231xx_buffer *buf;
548         u32 _line_size = dev->width * 2;
549
550         if (dma_q->current_field != field_number)
551                 cx231xx_reset_video_buffer(dev, dma_q);
552
553         /* get the buffer pointer */
554         if (dev->USE_ISO)
555                 buf = dev->video_mode.isoc_ctl.buf;
556         else
557                 buf = dev->video_mode.bulk_ctl.buf;
558
559         /* Remember the field number for next time */
560         dma_q->current_field = field_number;
561
562         bytes_to_copy = dma_q->bytes_left_in_line;
563         if (bytes_to_copy > length)
564                 bytes_to_copy = length;
565
566         if (dma_q->lines_completed >= dma_q->lines_per_field) {
567                 dma_q->bytes_left_in_line -= bytes_to_copy;
568                 dma_q->is_partial_line = (dma_q->bytes_left_in_line == 0) ?
569                                           0 : 1;
570                 return 0;
571         }
572
573         dma_q->is_partial_line = 1;
574
575         /* If we don't have a buffer, just return the number of bytes we would
576            have copied if we had a buffer. */
577         if (!buf) {
578                 dma_q->bytes_left_in_line -= bytes_to_copy;
579                 dma_q->is_partial_line = (dma_q->bytes_left_in_line == 0)
580                                          ? 0 : 1;
581                 return bytes_to_copy;
582         }
583
584         /* copy the data to video buffer */
585         cx231xx_do_copy(dev, dma_q, p_line, bytes_to_copy);
586
587         dma_q->pos += bytes_to_copy;
588         dma_q->bytes_left_in_line -= bytes_to_copy;
589
590         if (dma_q->bytes_left_in_line == 0) {
591                 dma_q->bytes_left_in_line = _line_size;
592                 dma_q->lines_completed++;
593                 dma_q->is_partial_line = 0;
594
595                 if (cx231xx_is_buffer_done(dev, dma_q) && buf) {
596                         buffer_filled(dev, dma_q, buf);
597
598                         dma_q->pos = 0;
599                         buf = NULL;
600                         dma_q->lines_completed = 0;
601                 }
602         }
603
604         return bytes_to_copy;
605 }
606
607 void cx231xx_reset_video_buffer(struct cx231xx *dev,
608                                 struct cx231xx_dmaqueue *dma_q)
609 {
610         struct cx231xx_buffer *buf;
611
612         /* handle the switch from field 1 to field 2 */
613         if (dma_q->current_field == 1) {
614                 if (dma_q->lines_completed >= dma_q->lines_per_field)
615                         dma_q->field1_done = 1;
616                 else
617                         dma_q->field1_done = 0;
618         }
619
620         if (dev->USE_ISO)
621                 buf = dev->video_mode.isoc_ctl.buf;
622         else
623                 buf = dev->video_mode.bulk_ctl.buf;
624
625         if (buf == NULL) {
626                 /* first try to get the buffer */
627                 get_next_buf(dma_q, &buf);
628
629                 dma_q->pos = 0;
630                 dma_q->field1_done = 0;
631                 dma_q->current_field = -1;
632         }
633
634         /* reset the counters */
635         dma_q->bytes_left_in_line = dev->width << 1;
636         dma_q->lines_completed = 0;
637 }
638
639 int cx231xx_do_copy(struct cx231xx *dev, struct cx231xx_dmaqueue *dma_q,
640                     u8 *p_buffer, u32 bytes_to_copy)
641 {
642         u8 *p_out_buffer = NULL;
643         u32 current_line_bytes_copied = 0;
644         struct cx231xx_buffer *buf;
645         u32 _line_size = dev->width << 1;
646         void *startwrite;
647         int offset, lencopy;
648
649         if (dev->USE_ISO)
650                 buf = dev->video_mode.isoc_ctl.buf;
651         else
652                 buf = dev->video_mode.bulk_ctl.buf;
653
654         if (buf == NULL)
655                 return -1;
656
657         p_out_buffer = videobuf_to_vmalloc(&buf->vb);
658
659         current_line_bytes_copied = _line_size - dma_q->bytes_left_in_line;
660
661         /* Offset field 2 one line from the top of the buffer */
662         offset = (dma_q->current_field == 1) ? 0 : _line_size;
663
664         /* Offset for field 2 */
665         startwrite = p_out_buffer + offset;
666
667         /* lines already completed in the current field */
668         startwrite += (dma_q->lines_completed * _line_size * 2);
669
670         /* bytes already completed in the current line */
671         startwrite += current_line_bytes_copied;
672
673         lencopy = dma_q->bytes_left_in_line > bytes_to_copy ?
674                   bytes_to_copy : dma_q->bytes_left_in_line;
675
676         if ((u8 *)(startwrite + lencopy) > (u8 *)(p_out_buffer + buf->vb.size))
677                 return 0;
678
679         /* The below copies the UYVY data straight into video buffer */
680         cx231xx_swab((u16 *) p_buffer, (u16 *) startwrite, (u16) lencopy);
681
682         return 0;
683 }
684
685 void cx231xx_swab(u16 *from, u16 *to, u16 len)
686 {
687         u16 i;
688
689         if (len <= 0)
690                 return;
691
692         for (i = 0; i < len / 2; i++)
693                 to[i] = (from[i] << 8) | (from[i] >> 8);
694 }
695
696 u8 cx231xx_is_buffer_done(struct cx231xx *dev, struct cx231xx_dmaqueue *dma_q)
697 {
698         u8 buffer_complete = 0;
699
700         /* Dual field stream */
701         buffer_complete = ((dma_q->current_field == 2) &&
702                            (dma_q->lines_completed >= dma_q->lines_per_field) &&
703                             dma_q->field1_done);
704
705         return buffer_complete;
706 }
707
708 /* ------------------------------------------------------------------
709         Videobuf operations
710    ------------------------------------------------------------------*/
711
712 static int
713 buffer_setup(struct videobuf_queue *vq, unsigned int *count, unsigned int *size)
714 {
715         struct cx231xx_fh *fh = vq->priv_data;
716         struct cx231xx *dev = fh->dev;
717
718         *size = (fh->dev->width * fh->dev->height * dev->format->depth + 7)>>3;
719         if (0 == *count)
720                 *count = CX231XX_DEF_BUF;
721
722         if (*count < CX231XX_MIN_BUF)
723                 *count = CX231XX_MIN_BUF;
724
725
726         cx231xx_enable_analog_tuner(dev);
727
728         return 0;
729 }
730
731 /* This is called *without* dev->slock held; please keep it that way */
732 static void free_buffer(struct videobuf_queue *vq, struct cx231xx_buffer *buf)
733 {
734         struct cx231xx_fh *fh = vq->priv_data;
735         struct cx231xx *dev = fh->dev;
736         unsigned long flags = 0;
737
738         BUG_ON(in_interrupt());
739
740         /* We used to wait for the buffer to finish here, but this didn't work
741            because, as we were keeping the state as VIDEOBUF_QUEUED,
742            videobuf_queue_cancel marked it as finished for us.
743            (Also, it could wedge forever if the hardware was misconfigured.)
744
745            This should be safe; by the time we get here, the buffer isn't
746            queued anymore. If we ever start marking the buffers as
747            VIDEOBUF_ACTIVE, it won't be, though.
748          */
749         spin_lock_irqsave(&dev->video_mode.slock, flags);
750         if (dev->USE_ISO) {
751                 if (dev->video_mode.isoc_ctl.buf == buf)
752                         dev->video_mode.isoc_ctl.buf = NULL;
753         } else {
754                 if (dev->video_mode.bulk_ctl.buf == buf)
755                         dev->video_mode.bulk_ctl.buf = NULL;
756         }
757         spin_unlock_irqrestore(&dev->video_mode.slock, flags);
758
759         videobuf_vmalloc_free(&buf->vb);
760         buf->vb.state = VIDEOBUF_NEEDS_INIT;
761 }
762
763 static int
764 buffer_prepare(struct videobuf_queue *vq, struct videobuf_buffer *vb,
765                enum v4l2_field field)
766 {
767         struct cx231xx_fh *fh = vq->priv_data;
768         struct cx231xx_buffer *buf =
769             container_of(vb, struct cx231xx_buffer, vb);
770         struct cx231xx *dev = fh->dev;
771         int rc = 0, urb_init = 0;
772
773         /* The only currently supported format is 16 bits/pixel */
774         buf->vb.size = (fh->dev->width * fh->dev->height * dev->format->depth
775                         + 7) >> 3;
776         if (0 != buf->vb.baddr && buf->vb.bsize < buf->vb.size)
777                 return -EINVAL;
778
779         buf->vb.width = dev->width;
780         buf->vb.height = dev->height;
781         buf->vb.field = field;
782
783         if (VIDEOBUF_NEEDS_INIT == buf->vb.state) {
784                 rc = videobuf_iolock(vq, &buf->vb, NULL);
785                 if (rc < 0)
786                         goto fail;
787         }
788
789         if (dev->USE_ISO) {
790                 if (!dev->video_mode.isoc_ctl.num_bufs)
791                         urb_init = 1;
792         } else {
793                 if (!dev->video_mode.bulk_ctl.num_bufs)
794                         urb_init = 1;
795         }
796         dev_dbg(dev->dev,
797                 "urb_init=%d dev->video_mode.max_pkt_size=%d\n",
798                 urb_init, dev->video_mode.max_pkt_size);
799         if (urb_init) {
800                 dev->mode_tv = 0;
801                 if (dev->USE_ISO)
802                         rc = cx231xx_init_isoc(dev, CX231XX_NUM_PACKETS,
803                                        CX231XX_NUM_BUFS,
804                                        dev->video_mode.max_pkt_size,
805                                        cx231xx_isoc_copy);
806                 else
807                         rc = cx231xx_init_bulk(dev, CX231XX_NUM_PACKETS,
808                                        CX231XX_NUM_BUFS,
809                                        dev->video_mode.max_pkt_size,
810                                        cx231xx_bulk_copy);
811                 if (rc < 0)
812                         goto fail;
813         }
814
815         buf->vb.state = VIDEOBUF_PREPARED;
816
817         return 0;
818
819 fail:
820         free_buffer(vq, buf);
821         return rc;
822 }
823
824 static void buffer_queue(struct videobuf_queue *vq, struct videobuf_buffer *vb)
825 {
826         struct cx231xx_buffer *buf =
827             container_of(vb, struct cx231xx_buffer, vb);
828         struct cx231xx_fh *fh = vq->priv_data;
829         struct cx231xx *dev = fh->dev;
830         struct cx231xx_dmaqueue *vidq = &dev->video_mode.vidq;
831
832         buf->vb.state = VIDEOBUF_QUEUED;
833         list_add_tail(&buf->vb.queue, &vidq->active);
834
835 }
836
837 static void buffer_release(struct videobuf_queue *vq,
838                            struct videobuf_buffer *vb)
839 {
840         struct cx231xx_buffer *buf =
841             container_of(vb, struct cx231xx_buffer, vb);
842         struct cx231xx_fh *fh = vq->priv_data;
843         struct cx231xx *dev = (struct cx231xx *)fh->dev;
844
845         cx231xx_isocdbg("cx231xx: called buffer_release\n");
846
847         free_buffer(vq, buf);
848 }
849
850 static const struct videobuf_queue_ops cx231xx_video_qops = {
851         .buf_setup = buffer_setup,
852         .buf_prepare = buffer_prepare,
853         .buf_queue = buffer_queue,
854         .buf_release = buffer_release,
855 };
856
857 /*********************  v4l2 interface  **************************************/
858
859 void video_mux(struct cx231xx *dev, int index)
860 {
861         dev->video_input = index;
862         dev->ctl_ainput = INPUT(index)->amux;
863
864         cx231xx_set_video_input_mux(dev, index);
865
866         cx25840_call(dev, video, s_routing, INPUT(index)->vmux, 0, 0);
867
868         cx231xx_set_audio_input(dev, dev->ctl_ainput);
869
870         dev_dbg(dev->dev, "video_mux : %d\n", index);
871
872         /* do mode control overrides if required */
873         cx231xx_do_mode_ctrl_overrides(dev);
874 }
875
876 /* Usage lock check functions */
877 static int res_get(struct cx231xx_fh *fh)
878 {
879         struct cx231xx *dev = fh->dev;
880         int rc = 0;
881
882         /* This instance already has stream_on */
883         if (fh->stream_on)
884                 return rc;
885
886         if (fh->type == V4L2_BUF_TYPE_VIDEO_CAPTURE) {
887                 if (dev->stream_on)
888                         return -EBUSY;
889                 dev->stream_on = 1;
890         } else if (fh->type == V4L2_BUF_TYPE_VBI_CAPTURE) {
891                 if (dev->vbi_stream_on)
892                         return -EBUSY;
893                 dev->vbi_stream_on = 1;
894         } else
895                 return -EINVAL;
896
897         fh->stream_on = 1;
898
899         return rc;
900 }
901
902 static int res_check(struct cx231xx_fh *fh)
903 {
904         return fh->stream_on;
905 }
906
907 static void res_free(struct cx231xx_fh *fh)
908 {
909         struct cx231xx *dev = fh->dev;
910
911         fh->stream_on = 0;
912
913         if (fh->type == V4L2_BUF_TYPE_VIDEO_CAPTURE)
914                 dev->stream_on = 0;
915         if (fh->type == V4L2_BUF_TYPE_VBI_CAPTURE)
916                 dev->vbi_stream_on = 0;
917 }
918
919 static int check_dev(struct cx231xx *dev)
920 {
921         if (dev->state & DEV_DISCONNECTED) {
922                 dev_err(dev->dev, "v4l2 ioctl: device not present\n");
923                 return -ENODEV;
924         }
925         return 0;
926 }
927
928 /* ------------------------------------------------------------------
929         IOCTL vidioc handling
930    ------------------------------------------------------------------*/
931
932 static int vidioc_g_fmt_vid_cap(struct file *file, void *priv,
933                                 struct v4l2_format *f)
934 {
935         struct cx231xx_fh *fh = priv;
936         struct cx231xx *dev = fh->dev;
937
938         f->fmt.pix.width = dev->width;
939         f->fmt.pix.height = dev->height;
940         f->fmt.pix.pixelformat = dev->format->fourcc;
941         f->fmt.pix.bytesperline = (dev->width * dev->format->depth + 7) >> 3;
942         f->fmt.pix.sizeimage = f->fmt.pix.bytesperline * dev->height;
943         f->fmt.pix.colorspace = V4L2_COLORSPACE_SMPTE170M;
944
945         f->fmt.pix.field = V4L2_FIELD_INTERLACED;
946
947         return 0;
948 }
949
950 static struct cx231xx_fmt *format_by_fourcc(unsigned int fourcc)
951 {
952         unsigned int i;
953
954         for (i = 0; i < ARRAY_SIZE(format); i++)
955                 if (format[i].fourcc == fourcc)
956                         return &format[i];
957
958         return NULL;
959 }
960
961 static int vidioc_try_fmt_vid_cap(struct file *file, void *priv,
962                                   struct v4l2_format *f)
963 {
964         struct cx231xx_fh *fh = priv;
965         struct cx231xx *dev = fh->dev;
966         unsigned int width = f->fmt.pix.width;
967         unsigned int height = f->fmt.pix.height;
968         unsigned int maxw = norm_maxw(dev);
969         unsigned int maxh = norm_maxh(dev);
970         struct cx231xx_fmt *fmt;
971
972         fmt = format_by_fourcc(f->fmt.pix.pixelformat);
973         if (!fmt) {
974                 cx231xx_videodbg("Fourcc format (%08x) invalid.\n",
975                                  f->fmt.pix.pixelformat);
976                 return -EINVAL;
977         }
978
979         /* width must even because of the YUYV format
980            height must be even because of interlacing */
981         v4l_bound_align_image(&width, 48, maxw, 1, &height, 32, maxh, 1, 0);
982
983         f->fmt.pix.width = width;
984         f->fmt.pix.height = height;
985         f->fmt.pix.pixelformat = fmt->fourcc;
986         f->fmt.pix.bytesperline = (width * fmt->depth + 7) >> 3;
987         f->fmt.pix.sizeimage = f->fmt.pix.bytesperline * height;
988         f->fmt.pix.colorspace = V4L2_COLORSPACE_SMPTE170M;
989         f->fmt.pix.field = V4L2_FIELD_INTERLACED;
990
991         return 0;
992 }
993
994 static int vidioc_s_fmt_vid_cap(struct file *file, void *priv,
995                                 struct v4l2_format *f)
996 {
997         struct cx231xx_fh *fh = priv;
998         struct cx231xx *dev = fh->dev;
999         int rc;
1000         struct cx231xx_fmt *fmt;
1001         struct v4l2_subdev_format format = {
1002                 .which = V4L2_SUBDEV_FORMAT_ACTIVE,
1003         };
1004
1005         rc = check_dev(dev);
1006         if (rc < 0)
1007                 return rc;
1008
1009         vidioc_try_fmt_vid_cap(file, priv, f);
1010
1011         fmt = format_by_fourcc(f->fmt.pix.pixelformat);
1012         if (!fmt)
1013                 return -EINVAL;
1014
1015         if (videobuf_queue_is_busy(&fh->vb_vidq)) {
1016                 dev_err(dev->dev, "%s: queue busy\n", __func__);
1017                 return -EBUSY;
1018         }
1019
1020         if (dev->stream_on && !fh->stream_on) {
1021                 dev_err(dev->dev,
1022                         "%s: device in use by another fh\n", __func__);
1023                 return -EBUSY;
1024         }
1025
1026         /* set new image size */
1027         dev->width = f->fmt.pix.width;
1028         dev->height = f->fmt.pix.height;
1029         dev->format = fmt;
1030
1031         v4l2_fill_mbus_format(&format.format, &f->fmt.pix, MEDIA_BUS_FMT_FIXED);
1032         call_all(dev, pad, set_fmt, NULL, &format);
1033         v4l2_fill_pix_format(&f->fmt.pix, &format.format);
1034
1035         return rc;
1036 }
1037
1038 static int vidioc_g_std(struct file *file, void *priv, v4l2_std_id *id)
1039 {
1040         struct cx231xx_fh *fh = priv;
1041         struct cx231xx *dev = fh->dev;
1042
1043         *id = dev->norm;
1044         return 0;
1045 }
1046
1047 static int vidioc_s_std(struct file *file, void *priv, v4l2_std_id norm)
1048 {
1049         struct cx231xx_fh *fh = priv;
1050         struct cx231xx *dev = fh->dev;
1051         struct v4l2_subdev_format format = {
1052                 .which = V4L2_SUBDEV_FORMAT_ACTIVE,
1053         };
1054         int rc;
1055
1056         rc = check_dev(dev);
1057         if (rc < 0)
1058                 return rc;
1059
1060         if (dev->norm == norm)
1061                 return 0;
1062
1063         if (videobuf_queue_is_busy(&fh->vb_vidq))
1064                 return -EBUSY;
1065
1066         dev->norm = norm;
1067
1068         /* Adjusts width/height, if needed */
1069         dev->width = 720;
1070         dev->height = (dev->norm & V4L2_STD_625_50) ? 576 : 480;
1071
1072         call_all(dev, video, s_std, dev->norm);
1073
1074         /* We need to reset basic properties in the decoder related to
1075            resolution (since a standard change effects things like the number
1076            of lines in VACT, etc) */
1077         format.format.code = MEDIA_BUS_FMT_FIXED;
1078         format.format.width = dev->width;
1079         format.format.height = dev->height;
1080         call_all(dev, pad, set_fmt, NULL, &format);
1081
1082         /* do mode control overrides */
1083         cx231xx_do_mode_ctrl_overrides(dev);
1084
1085         return 0;
1086 }
1087
1088 static const char *iname[] = {
1089         [CX231XX_VMUX_COMPOSITE1] = "Composite1",
1090         [CX231XX_VMUX_SVIDEO]     = "S-Video",
1091         [CX231XX_VMUX_TELEVISION] = "Television",
1092         [CX231XX_VMUX_CABLE]      = "Cable TV",
1093         [CX231XX_VMUX_DVB]        = "DVB",
1094 };
1095
1096 void cx231xx_v4l2_create_entities(struct cx231xx *dev)
1097 {
1098 #if defined(CONFIG_MEDIA_CONTROLLER)
1099         int ret, i;
1100
1101         /* Create entities for each input connector */
1102         for (i = 0; i < MAX_CX231XX_INPUT; i++) {
1103                 struct media_entity *ent = &dev->input_ent[i];
1104
1105                 if (!INPUT(i)->type)
1106                         break;
1107
1108                 ent->name = iname[INPUT(i)->type];
1109                 ent->flags = MEDIA_ENT_FL_CONNECTOR;
1110                 dev->input_pad[i].flags = MEDIA_PAD_FL_SOURCE;
1111
1112                 switch (INPUT(i)->type) {
1113                 case CX231XX_VMUX_COMPOSITE1:
1114                         ent->function = MEDIA_ENT_F_CONN_COMPOSITE;
1115                         break;
1116                 case CX231XX_VMUX_SVIDEO:
1117                         ent->function = MEDIA_ENT_F_CONN_SVIDEO;
1118                         break;
1119                 case CX231XX_VMUX_TELEVISION:
1120                 case CX231XX_VMUX_CABLE:
1121                 case CX231XX_VMUX_DVB:
1122                         /* The DVB core will handle it */
1123                         if (dev->tuner_type == TUNER_ABSENT)
1124                                 continue;
1125                         /* fall through */
1126                 default: /* just to shut up a gcc warning */
1127                         ent->function = MEDIA_ENT_F_CONN_RF;
1128                         break;
1129                 }
1130
1131                 ret = media_entity_pads_init(ent, 1, &dev->input_pad[i]);
1132                 if (ret < 0)
1133                         pr_err("failed to initialize input pad[%d]!\n", i);
1134
1135                 ret = media_device_register_entity(dev->media_dev, ent);
1136                 if (ret < 0)
1137                         pr_err("failed to register input entity %d!\n", i);
1138         }
1139 #endif
1140 }
1141
1142 int cx231xx_enum_input(struct file *file, void *priv,
1143                              struct v4l2_input *i)
1144 {
1145         struct cx231xx_fh *fh = priv;
1146         struct cx231xx *dev = fh->dev;
1147         u32 gen_stat;
1148         unsigned int n;
1149         int ret;
1150
1151         n = i->index;
1152         if (n >= MAX_CX231XX_INPUT)
1153                 return -EINVAL;
1154         if (0 == INPUT(n)->type)
1155                 return -EINVAL;
1156
1157         i->index = n;
1158         i->type = V4L2_INPUT_TYPE_CAMERA;
1159
1160         strscpy(i->name, iname[INPUT(n)->type], sizeof(i->name));
1161
1162         if ((CX231XX_VMUX_TELEVISION == INPUT(n)->type) ||
1163             (CX231XX_VMUX_CABLE == INPUT(n)->type))
1164                 i->type = V4L2_INPUT_TYPE_TUNER;
1165
1166         i->std = dev->vdev.tvnorms;
1167
1168         /* If they are asking about the active input, read signal status */
1169         if (n == dev->video_input) {
1170                 ret = cx231xx_read_i2c_data(dev, VID_BLK_I2C_ADDRESS,
1171                                             GEN_STAT, 2, &gen_stat, 4);
1172                 if (ret > 0) {
1173                         if ((gen_stat & FLD_VPRES) == 0x00)
1174                                 i->status |= V4L2_IN_ST_NO_SIGNAL;
1175                         if ((gen_stat & FLD_HLOCK) == 0x00)
1176                                 i->status |= V4L2_IN_ST_NO_H_LOCK;
1177                 }
1178         }
1179
1180         return 0;
1181 }
1182
1183 int cx231xx_g_input(struct file *file, void *priv, unsigned int *i)
1184 {
1185         struct cx231xx_fh *fh = priv;
1186         struct cx231xx *dev = fh->dev;
1187
1188         *i = dev->video_input;
1189
1190         return 0;
1191 }
1192
1193 int cx231xx_s_input(struct file *file, void *priv, unsigned int i)
1194 {
1195         struct cx231xx_fh *fh = priv;
1196         struct cx231xx *dev = fh->dev;
1197         int rc;
1198
1199         dev->mode_tv = 0;
1200         rc = check_dev(dev);
1201         if (rc < 0)
1202                 return rc;
1203
1204         if (i >= MAX_CX231XX_INPUT)
1205                 return -EINVAL;
1206         if (0 == INPUT(i)->type)
1207                 return -EINVAL;
1208
1209         video_mux(dev, i);
1210
1211         if (INPUT(i)->type == CX231XX_VMUX_TELEVISION ||
1212             INPUT(i)->type == CX231XX_VMUX_CABLE) {
1213                 /* There's a tuner, so reset the standard and put it on the
1214                    last known frequency (since it was probably powered down
1215                    until now */
1216                 call_all(dev, video, s_std, dev->norm);
1217         }
1218
1219         return 0;
1220 }
1221
1222 int cx231xx_g_tuner(struct file *file, void *priv, struct v4l2_tuner *t)
1223 {
1224         struct cx231xx_fh *fh = priv;
1225         struct cx231xx *dev = fh->dev;
1226         int rc;
1227
1228         rc = check_dev(dev);
1229         if (rc < 0)
1230                 return rc;
1231
1232         if (0 != t->index)
1233                 return -EINVAL;
1234
1235         strscpy(t->name, "Tuner", sizeof(t->name));
1236
1237         t->type = V4L2_TUNER_ANALOG_TV;
1238         t->capability = V4L2_TUNER_CAP_NORM;
1239         t->rangehigh = 0xffffffffUL;
1240         t->signal = 0xffff;     /* LOCKED */
1241         call_all(dev, tuner, g_tuner, t);
1242
1243         return 0;
1244 }
1245
1246 int cx231xx_s_tuner(struct file *file, void *priv, const struct v4l2_tuner *t)
1247 {
1248         struct cx231xx_fh *fh = priv;
1249         struct cx231xx *dev = fh->dev;
1250         int rc;
1251
1252         rc = check_dev(dev);
1253         if (rc < 0)
1254                 return rc;
1255
1256         if (0 != t->index)
1257                 return -EINVAL;
1258 #if 0
1259         call_all(dev, tuner, s_tuner, t);
1260 #endif
1261         return 0;
1262 }
1263
1264 int cx231xx_g_frequency(struct file *file, void *priv,
1265                               struct v4l2_frequency *f)
1266 {
1267         struct cx231xx_fh *fh = priv;
1268         struct cx231xx *dev = fh->dev;
1269
1270         if (f->tuner)
1271                 return -EINVAL;
1272
1273         f->frequency = dev->ctl_freq;
1274
1275         return 0;
1276 }
1277
1278 int cx231xx_s_frequency(struct file *file, void *priv,
1279                               const struct v4l2_frequency *f)
1280 {
1281         struct cx231xx_fh *fh = priv;
1282         struct cx231xx *dev = fh->dev;
1283         struct v4l2_frequency new_freq = *f;
1284         int rc;
1285         u32 if_frequency = 5400000;
1286
1287         dev_dbg(dev->dev,
1288                 "Enter vidioc_s_frequency()f->frequency=%d;f->type=%d\n",
1289                 f->frequency, f->type);
1290
1291         rc = check_dev(dev);
1292         if (rc < 0)
1293                 return rc;
1294
1295         if (0 != f->tuner)
1296                 return -EINVAL;
1297
1298         /* set pre channel change settings in DIF first */
1299         rc = cx231xx_tuner_pre_channel_change(dev);
1300
1301         call_all(dev, tuner, s_frequency, f);
1302         call_all(dev, tuner, g_frequency, &new_freq);
1303         dev->ctl_freq = new_freq.frequency;
1304
1305         /* set post channel change settings in DIF first */
1306         rc = cx231xx_tuner_post_channel_change(dev);
1307
1308         if (dev->tuner_type == TUNER_NXP_TDA18271) {
1309                 if (dev->norm & (V4L2_STD_MN | V4L2_STD_NTSC_443))
1310                         if_frequency = 5400000;  /*5.4MHz       */
1311                 else if (dev->norm & V4L2_STD_B)
1312                         if_frequency = 6000000;  /*6.0MHz       */
1313                 else if (dev->norm & (V4L2_STD_PAL_DK | V4L2_STD_SECAM_DK))
1314                         if_frequency = 6900000;  /*6.9MHz       */
1315                 else if (dev->norm & V4L2_STD_GH)
1316                         if_frequency = 7100000;  /*7.1MHz       */
1317                 else if (dev->norm & V4L2_STD_PAL_I)
1318                         if_frequency = 7250000;  /*7.25MHz      */
1319                 else if (dev->norm & V4L2_STD_SECAM_L)
1320                         if_frequency = 6900000;  /*6.9MHz       */
1321                 else if (dev->norm & V4L2_STD_SECAM_LC)
1322                         if_frequency = 1250000;  /*1.25MHz      */
1323
1324                 dev_dbg(dev->dev,
1325                         "if_frequency is set to %d\n", if_frequency);
1326                 cx231xx_set_Colibri_For_LowIF(dev, if_frequency, 1, 1);
1327
1328                 update_HH_register_after_set_DIF(dev);
1329         }
1330
1331         dev_dbg(dev->dev, "Set New FREQUENCY to %d\n", f->frequency);
1332
1333         return rc;
1334 }
1335
1336 #ifdef CONFIG_VIDEO_ADV_DEBUG
1337
1338 int cx231xx_g_chip_info(struct file *file, void *fh,
1339                         struct v4l2_dbg_chip_info *chip)
1340 {
1341         switch (chip->match.addr) {
1342         case 0: /* Cx231xx - internal registers */
1343                 return 0;
1344         case 1: /* AFE - read byte */
1345                 strscpy(chip->name, "AFE (byte)", sizeof(chip->name));
1346                 return 0;
1347         case 2: /* Video Block - read byte */
1348                 strscpy(chip->name, "Video (byte)", sizeof(chip->name));
1349                 return 0;
1350         case 3: /* I2S block - read byte */
1351                 strscpy(chip->name, "I2S (byte)", sizeof(chip->name));
1352                 return 0;
1353         case 4: /* AFE - read dword */
1354                 strscpy(chip->name, "AFE (dword)", sizeof(chip->name));
1355                 return 0;
1356         case 5: /* Video Block - read dword */
1357                 strscpy(chip->name, "Video (dword)", sizeof(chip->name));
1358                 return 0;
1359         case 6: /* I2S Block - read dword */
1360                 strscpy(chip->name, "I2S (dword)", sizeof(chip->name));
1361                 return 0;
1362         }
1363         return -EINVAL;
1364 }
1365
1366 int cx231xx_g_register(struct file *file, void *priv,
1367                              struct v4l2_dbg_register *reg)
1368 {
1369         struct cx231xx_fh *fh = priv;
1370         struct cx231xx *dev = fh->dev;
1371         int ret;
1372         u8 value[4] = { 0, 0, 0, 0 };
1373         u32 data = 0;
1374
1375         switch (reg->match.addr) {
1376         case 0: /* Cx231xx - internal registers */
1377                 ret = cx231xx_read_ctrl_reg(dev, VRT_GET_REGISTER,
1378                                 (u16)reg->reg, value, 4);
1379                 reg->val = value[0] | value[1] << 8 |
1380                         value[2] << 16 | (u32)value[3] << 24;
1381                 reg->size = 4;
1382                 break;
1383         case 1: /* AFE - read byte */
1384                 ret = cx231xx_read_i2c_data(dev, AFE_DEVICE_ADDRESS,
1385                                 (u16)reg->reg, 2, &data, 1);
1386                 reg->val = data;
1387                 reg->size = 1;
1388                 break;
1389         case 2: /* Video Block - read byte */
1390                 ret = cx231xx_read_i2c_data(dev, VID_BLK_I2C_ADDRESS,
1391                                 (u16)reg->reg, 2, &data, 1);
1392                 reg->val = data;
1393                 reg->size = 1;
1394                 break;
1395         case 3: /* I2S block - read byte */
1396                 ret = cx231xx_read_i2c_data(dev, I2S_BLK_DEVICE_ADDRESS,
1397                                 (u16)reg->reg, 1, &data, 1);
1398                 reg->val = data;
1399                 reg->size = 1;
1400                 break;
1401         case 4: /* AFE - read dword */
1402                 ret = cx231xx_read_i2c_data(dev, AFE_DEVICE_ADDRESS,
1403                                 (u16)reg->reg, 2, &data, 4);
1404                 reg->val = data;
1405                 reg->size = 4;
1406                 break;
1407         case 5: /* Video Block - read dword */
1408                 ret = cx231xx_read_i2c_data(dev, VID_BLK_I2C_ADDRESS,
1409                                 (u16)reg->reg, 2, &data, 4);
1410                 reg->val = data;
1411                 reg->size = 4;
1412                 break;
1413         case 6: /* I2S Block - read dword */
1414                 ret = cx231xx_read_i2c_data(dev, I2S_BLK_DEVICE_ADDRESS,
1415                                 (u16)reg->reg, 1, &data, 4);
1416                 reg->val = data;
1417                 reg->size = 4;
1418                 break;
1419         default:
1420                 return -EINVAL;
1421         }
1422         return ret < 0 ? ret : 0;
1423 }
1424
1425 int cx231xx_s_register(struct file *file, void *priv,
1426                              const struct v4l2_dbg_register *reg)
1427 {
1428         struct cx231xx_fh *fh = priv;
1429         struct cx231xx *dev = fh->dev;
1430         int ret;
1431         u8 data[4] = { 0, 0, 0, 0 };
1432
1433         switch (reg->match.addr) {
1434         case 0: /* cx231xx internal registers */
1435                 data[0] = (u8) reg->val;
1436                 data[1] = (u8) (reg->val >> 8);
1437                 data[2] = (u8) (reg->val >> 16);
1438                 data[3] = (u8) (reg->val >> 24);
1439                 ret = cx231xx_write_ctrl_reg(dev, VRT_SET_REGISTER,
1440                                 (u16)reg->reg, data, 4);
1441                 break;
1442         case 1: /* AFE - write byte */
1443                 ret = cx231xx_write_i2c_data(dev, AFE_DEVICE_ADDRESS,
1444                                 (u16)reg->reg, 2, reg->val, 1);
1445                 break;
1446         case 2: /* Video Block - write byte */
1447                 ret = cx231xx_write_i2c_data(dev, VID_BLK_I2C_ADDRESS,
1448                                 (u16)reg->reg, 2, reg->val, 1);
1449                 break;
1450         case 3: /* I2S block - write byte */
1451                 ret = cx231xx_write_i2c_data(dev, I2S_BLK_DEVICE_ADDRESS,
1452                                 (u16)reg->reg, 1, reg->val, 1);
1453                 break;
1454         case 4: /* AFE - write dword */
1455                 ret = cx231xx_write_i2c_data(dev, AFE_DEVICE_ADDRESS,
1456                                 (u16)reg->reg, 2, reg->val, 4);
1457                 break;
1458         case 5: /* Video Block - write dword */
1459                 ret = cx231xx_write_i2c_data(dev, VID_BLK_I2C_ADDRESS,
1460                                 (u16)reg->reg, 2, reg->val, 4);
1461                 break;
1462         case 6: /* I2S block - write dword */
1463                 ret = cx231xx_write_i2c_data(dev, I2S_BLK_DEVICE_ADDRESS,
1464                                 (u16)reg->reg, 1, reg->val, 4);
1465                 break;
1466         default:
1467                 return -EINVAL;
1468         }
1469         return ret < 0 ? ret : 0;
1470 }
1471 #endif
1472
1473 static int vidioc_g_pixelaspect(struct file *file, void *priv,
1474                                 int type, struct v4l2_fract *f)
1475 {
1476         struct cx231xx_fh *fh = priv;
1477         struct cx231xx *dev = fh->dev;
1478         bool is_50hz = dev->norm & V4L2_STD_625_50;
1479
1480         if (type != V4L2_BUF_TYPE_VIDEO_CAPTURE)
1481                 return -EINVAL;
1482
1483         f->numerator = is_50hz ? 54 : 11;
1484         f->denominator = is_50hz ? 59 : 10;
1485
1486         return 0;
1487 }
1488
1489 static int vidioc_g_selection(struct file *file, void *priv,
1490                               struct v4l2_selection *s)
1491 {
1492         struct cx231xx_fh *fh = priv;
1493         struct cx231xx *dev = fh->dev;
1494
1495         if (s->type != V4L2_BUF_TYPE_VIDEO_CAPTURE)
1496                 return -EINVAL;
1497
1498         switch (s->target) {
1499         case V4L2_SEL_TGT_CROP_BOUNDS:
1500         case V4L2_SEL_TGT_CROP_DEFAULT:
1501                 s->r.left = 0;
1502                 s->r.top = 0;
1503                 s->r.width = dev->width;
1504                 s->r.height = dev->height;
1505                 break;
1506         default:
1507                 return -EINVAL;
1508         }
1509         return 0;
1510 }
1511
1512 static int vidioc_streamon(struct file *file, void *priv,
1513                            enum v4l2_buf_type type)
1514 {
1515         struct cx231xx_fh *fh = priv;
1516         struct cx231xx *dev = fh->dev;
1517         int rc;
1518
1519         rc = check_dev(dev);
1520         if (rc < 0)
1521                 return rc;
1522
1523         rc = res_get(fh);
1524
1525         if (likely(rc >= 0))
1526                 rc = videobuf_streamon(&fh->vb_vidq);
1527
1528         call_all(dev, video, s_stream, 1);
1529
1530         return rc;
1531 }
1532
1533 static int vidioc_streamoff(struct file *file, void *priv,
1534                             enum v4l2_buf_type type)
1535 {
1536         struct cx231xx_fh *fh = priv;
1537         struct cx231xx *dev = fh->dev;
1538         int rc;
1539
1540         rc = check_dev(dev);
1541         if (rc < 0)
1542                 return rc;
1543
1544         if (type != fh->type)
1545                 return -EINVAL;
1546
1547         cx25840_call(dev, video, s_stream, 0);
1548
1549         videobuf_streamoff(&fh->vb_vidq);
1550         res_free(fh);
1551
1552         return 0;
1553 }
1554
1555 int cx231xx_querycap(struct file *file, void *priv,
1556                            struct v4l2_capability *cap)
1557 {
1558         struct cx231xx_fh *fh = priv;
1559         struct cx231xx *dev = fh->dev;
1560
1561         strscpy(cap->driver, "cx231xx", sizeof(cap->driver));
1562         strscpy(cap->card, cx231xx_boards[dev->model].name, sizeof(cap->card));
1563         usb_make_path(dev->udev, cap->bus_info, sizeof(cap->bus_info));
1564         cap->capabilities = V4L2_CAP_READWRITE |
1565                 V4L2_CAP_VBI_CAPTURE | V4L2_CAP_VIDEO_CAPTURE |
1566                 V4L2_CAP_STREAMING | V4L2_CAP_DEVICE_CAPS;
1567         if (video_is_registered(&dev->radio_dev))
1568                 cap->capabilities |= V4L2_CAP_RADIO;
1569         if (dev->tuner_type != TUNER_ABSENT)
1570                 cap->capabilities |= V4L2_CAP_TUNER;
1571
1572         return 0;
1573 }
1574
1575 static int vidioc_enum_fmt_vid_cap(struct file *file, void *priv,
1576                                    struct v4l2_fmtdesc *f)
1577 {
1578         if (unlikely(f->index >= ARRAY_SIZE(format)))
1579                 return -EINVAL;
1580
1581         strscpy(f->description, format[f->index].name, sizeof(f->description));
1582         f->pixelformat = format[f->index].fourcc;
1583
1584         return 0;
1585 }
1586
1587 /* RAW VBI ioctls */
1588
1589 static int vidioc_g_fmt_vbi_cap(struct file *file, void *priv,
1590                                 struct v4l2_format *f)
1591 {
1592         struct cx231xx_fh *fh = priv;
1593         struct cx231xx *dev = fh->dev;
1594
1595         f->fmt.vbi.sampling_rate = 6750000 * 4;
1596         f->fmt.vbi.samples_per_line = VBI_LINE_LENGTH;
1597         f->fmt.vbi.sample_format = V4L2_PIX_FMT_GREY;
1598         f->fmt.vbi.offset = 0;
1599         f->fmt.vbi.start[0] = (dev->norm & V4L2_STD_625_50) ?
1600             PAL_VBI_START_LINE : NTSC_VBI_START_LINE;
1601         f->fmt.vbi.count[0] = (dev->norm & V4L2_STD_625_50) ?
1602             PAL_VBI_LINES : NTSC_VBI_LINES;
1603         f->fmt.vbi.start[1] = (dev->norm & V4L2_STD_625_50) ?
1604             PAL_VBI_START_LINE + 312 : NTSC_VBI_START_LINE + 263;
1605         f->fmt.vbi.count[1] = f->fmt.vbi.count[0];
1606         memset(f->fmt.vbi.reserved, 0, sizeof(f->fmt.vbi.reserved));
1607
1608         return 0;
1609
1610 }
1611
1612 static int vidioc_try_fmt_vbi_cap(struct file *file, void *priv,
1613                                   struct v4l2_format *f)
1614 {
1615         struct cx231xx_fh *fh = priv;
1616         struct cx231xx *dev = fh->dev;
1617
1618         f->fmt.vbi.sampling_rate = 6750000 * 4;
1619         f->fmt.vbi.samples_per_line = VBI_LINE_LENGTH;
1620         f->fmt.vbi.sample_format = V4L2_PIX_FMT_GREY;
1621         f->fmt.vbi.offset = 0;
1622         f->fmt.vbi.flags = 0;
1623         f->fmt.vbi.start[0] = (dev->norm & V4L2_STD_625_50) ?
1624             PAL_VBI_START_LINE : NTSC_VBI_START_LINE;
1625         f->fmt.vbi.count[0] = (dev->norm & V4L2_STD_625_50) ?
1626             PAL_VBI_LINES : NTSC_VBI_LINES;
1627         f->fmt.vbi.start[1] = (dev->norm & V4L2_STD_625_50) ?
1628             PAL_VBI_START_LINE + 312 : NTSC_VBI_START_LINE + 263;
1629         f->fmt.vbi.count[1] = f->fmt.vbi.count[0];
1630         memset(f->fmt.vbi.reserved, 0, sizeof(f->fmt.vbi.reserved));
1631
1632         return 0;
1633
1634 }
1635
1636 static int vidioc_s_fmt_vbi_cap(struct file *file, void *priv,
1637                                   struct v4l2_format *f)
1638 {
1639         struct cx231xx_fh *fh = priv;
1640         struct cx231xx *dev = fh->dev;
1641
1642         if (dev->vbi_stream_on && !fh->stream_on) {
1643                 dev_err(dev->dev,
1644                         "%s device in use by another fh\n", __func__);
1645                 return -EBUSY;
1646         }
1647         return vidioc_try_fmt_vbi_cap(file, priv, f);
1648 }
1649
1650 static int vidioc_reqbufs(struct file *file, void *priv,
1651                           struct v4l2_requestbuffers *rb)
1652 {
1653         struct cx231xx_fh *fh = priv;
1654         struct cx231xx *dev = fh->dev;
1655         int rc;
1656
1657         rc = check_dev(dev);
1658         if (rc < 0)
1659                 return rc;
1660
1661         return videobuf_reqbufs(&fh->vb_vidq, rb);
1662 }
1663
1664 static int vidioc_querybuf(struct file *file, void *priv, struct v4l2_buffer *b)
1665 {
1666         struct cx231xx_fh *fh = priv;
1667         struct cx231xx *dev = fh->dev;
1668         int rc;
1669
1670         rc = check_dev(dev);
1671         if (rc < 0)
1672                 return rc;
1673
1674         return videobuf_querybuf(&fh->vb_vidq, b);
1675 }
1676
1677 static int vidioc_qbuf(struct file *file, void *priv, struct v4l2_buffer *b)
1678 {
1679         struct cx231xx_fh *fh = priv;
1680         struct cx231xx *dev = fh->dev;
1681         int rc;
1682
1683         rc = check_dev(dev);
1684         if (rc < 0)
1685                 return rc;
1686
1687         return videobuf_qbuf(&fh->vb_vidq, b);
1688 }
1689
1690 static int vidioc_dqbuf(struct file *file, void *priv, struct v4l2_buffer *b)
1691 {
1692         struct cx231xx_fh *fh = priv;
1693         struct cx231xx *dev = fh->dev;
1694         int rc;
1695
1696         rc = check_dev(dev);
1697         if (rc < 0)
1698                 return rc;
1699
1700         return videobuf_dqbuf(&fh->vb_vidq, b, file->f_flags & O_NONBLOCK);
1701 }
1702
1703 /* ----------------------------------------------------------- */
1704 /* RADIO ESPECIFIC IOCTLS                                      */
1705 /* ----------------------------------------------------------- */
1706
1707 static int radio_g_tuner(struct file *file, void *priv, struct v4l2_tuner *t)
1708 {
1709         struct cx231xx *dev = ((struct cx231xx_fh *)priv)->dev;
1710
1711         if (t->index)
1712                 return -EINVAL;
1713
1714         strscpy(t->name, "Radio", sizeof(t->name));
1715
1716         call_all(dev, tuner, g_tuner, t);
1717
1718         return 0;
1719 }
1720 static int radio_s_tuner(struct file *file, void *priv, const struct v4l2_tuner *t)
1721 {
1722         struct cx231xx *dev = ((struct cx231xx_fh *)priv)->dev;
1723
1724         if (t->index)
1725                 return -EINVAL;
1726
1727         call_all(dev, tuner, s_tuner, t);
1728
1729         return 0;
1730 }
1731
1732 /*
1733  * cx231xx_v4l2_open()
1734  * inits the device and starts isoc transfer
1735  */
1736 static int cx231xx_v4l2_open(struct file *filp)
1737 {
1738         int radio = 0;
1739         struct video_device *vdev = video_devdata(filp);
1740         struct cx231xx *dev = video_drvdata(filp);
1741         struct cx231xx_fh *fh;
1742         enum v4l2_buf_type fh_type = 0;
1743
1744         switch (vdev->vfl_type) {
1745         case VFL_TYPE_GRABBER:
1746                 fh_type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
1747                 break;
1748         case VFL_TYPE_VBI:
1749                 fh_type = V4L2_BUF_TYPE_VBI_CAPTURE;
1750                 break;
1751         case VFL_TYPE_RADIO:
1752                 radio = 1;
1753                 break;
1754         default:
1755                 return -EINVAL;
1756         }
1757
1758         cx231xx_videodbg("open dev=%s type=%s users=%d\n",
1759                          video_device_node_name(vdev), v4l2_type_names[fh_type],
1760                          dev->users);
1761
1762 #if 0
1763         errCode = cx231xx_set_mode(dev, CX231XX_ANALOG_MODE);
1764         if (errCode < 0) {
1765                 dev_err(dev->dev,
1766                         "Device locked on digital mode. Can't open analog\n");
1767                 return -EBUSY;
1768         }
1769 #endif
1770
1771         fh = kzalloc(sizeof(struct cx231xx_fh), GFP_KERNEL);
1772         if (!fh)
1773                 return -ENOMEM;
1774         if (mutex_lock_interruptible(&dev->lock)) {
1775                 kfree(fh);
1776                 return -ERESTARTSYS;
1777         }
1778         fh->dev = dev;
1779         fh->type = fh_type;
1780         filp->private_data = fh;
1781         v4l2_fh_init(&fh->fh, vdev);
1782
1783         if (fh->type == V4L2_BUF_TYPE_VIDEO_CAPTURE && dev->users == 0) {
1784                 /* Power up in Analog TV mode */
1785                 if (dev->board.external_av)
1786                         cx231xx_set_power_mode(dev,
1787                                  POLARIS_AVMODE_ENXTERNAL_AV);
1788                 else
1789                         cx231xx_set_power_mode(dev, POLARIS_AVMODE_ANALOGT_TV);
1790
1791 #if 0
1792                 cx231xx_set_mode(dev, CX231XX_ANALOG_MODE);
1793 #endif
1794
1795                 /* set video alternate setting */
1796                 cx231xx_set_video_alternate(dev);
1797
1798                 /* Needed, since GPIO might have disabled power of
1799                    some i2c device */
1800                 cx231xx_config_i2c(dev);
1801
1802                 /* device needs to be initialized before isoc transfer */
1803                 dev->video_input = dev->video_input > 2 ? 2 : dev->video_input;
1804
1805         }
1806         if (radio) {
1807                 cx231xx_videodbg("video_open: setting radio device\n");
1808
1809                 /* cx231xx_start_radio(dev); */
1810
1811                 call_all(dev, tuner, s_radio);
1812         }
1813
1814         dev->users++;
1815
1816         if (fh->type == V4L2_BUF_TYPE_VIDEO_CAPTURE)
1817                 videobuf_queue_vmalloc_init(&fh->vb_vidq, &cx231xx_video_qops,
1818                                             NULL, &dev->video_mode.slock,
1819                                             fh->type, V4L2_FIELD_INTERLACED,
1820                                             sizeof(struct cx231xx_buffer),
1821                                             fh, &dev->lock);
1822         if (fh->type == V4L2_BUF_TYPE_VBI_CAPTURE) {
1823                 /* Set the required alternate setting  VBI interface works in
1824                    Bulk mode only */
1825                 cx231xx_set_alt_setting(dev, INDEX_VANC, 0);
1826
1827                 videobuf_queue_vmalloc_init(&fh->vb_vidq, &cx231xx_vbi_qops,
1828                                             NULL, &dev->vbi_mode.slock,
1829                                             fh->type, V4L2_FIELD_SEQ_TB,
1830                                             sizeof(struct cx231xx_buffer),
1831                                             fh, &dev->lock);
1832         }
1833         mutex_unlock(&dev->lock);
1834         v4l2_fh_add(&fh->fh);
1835
1836         return 0;
1837 }
1838
1839 /*
1840  * cx231xx_realease_resources()
1841  * unregisters the v4l2,i2c and usb devices
1842  * called when the device gets disconected or at module unload
1843 */
1844 void cx231xx_release_analog_resources(struct cx231xx *dev)
1845 {
1846
1847         /*FIXME: I2C IR should be disconnected */
1848
1849         if (video_is_registered(&dev->radio_dev))
1850                 video_unregister_device(&dev->radio_dev);
1851         if (video_is_registered(&dev->vbi_dev)) {
1852                 dev_info(dev->dev, "V4L2 device %s deregistered\n",
1853                         video_device_node_name(&dev->vbi_dev));
1854                 video_unregister_device(&dev->vbi_dev);
1855         }
1856         if (video_is_registered(&dev->vdev)) {
1857                 dev_info(dev->dev, "V4L2 device %s deregistered\n",
1858                         video_device_node_name(&dev->vdev));
1859
1860                 if (dev->board.has_417)
1861                         cx231xx_417_unregister(dev);
1862
1863                 video_unregister_device(&dev->vdev);
1864         }
1865         v4l2_ctrl_handler_free(&dev->ctrl_handler);
1866         v4l2_ctrl_handler_free(&dev->radio_ctrl_handler);
1867 }
1868
1869 /*
1870  * cx231xx_close()
1871  * stops streaming and deallocates all resources allocated by the v4l2
1872  * calls and ioctls
1873  */
1874 static int cx231xx_close(struct file *filp)
1875 {
1876         struct cx231xx_fh *fh = filp->private_data;
1877         struct cx231xx *dev = fh->dev;
1878
1879         cx231xx_videodbg("users=%d\n", dev->users);
1880
1881         cx231xx_videodbg("users=%d\n", dev->users);
1882         if (res_check(fh))
1883                 res_free(fh);
1884
1885         /*
1886          * To workaround error number=-71 on EP0 for VideoGrabber,
1887          *       need exclude following.
1888          * FIXME: It is probably safe to remove most of these, as we're
1889          * now avoiding the alternate setting for INDEX_VANC
1890          */
1891         if (!dev->board.no_alt_vanc)
1892                 if (fh->type == V4L2_BUF_TYPE_VBI_CAPTURE) {
1893                         videobuf_stop(&fh->vb_vidq);
1894                         videobuf_mmap_free(&fh->vb_vidq);
1895
1896                         /* the device is already disconnect,
1897                            free the remaining resources */
1898                         if (dev->state & DEV_DISCONNECTED) {
1899                                 if (atomic_read(&dev->devlist_count) > 0) {
1900                                         cx231xx_release_resources(dev);
1901                                         fh->dev = NULL;
1902                                         return 0;
1903                                 }
1904                                 return 0;
1905                         }
1906
1907                         /* do this before setting alternate! */
1908                         cx231xx_uninit_vbi_isoc(dev);
1909
1910                         /* set alternate 0 */
1911                         if (!dev->vbi_or_sliced_cc_mode)
1912                                 cx231xx_set_alt_setting(dev, INDEX_VANC, 0);
1913                         else
1914                                 cx231xx_set_alt_setting(dev, INDEX_HANC, 0);
1915
1916                         v4l2_fh_del(&fh->fh);
1917                         v4l2_fh_exit(&fh->fh);
1918                         kfree(fh);
1919                         dev->users--;
1920                         wake_up_interruptible(&dev->open);
1921                         return 0;
1922                 }
1923
1924         v4l2_fh_del(&fh->fh);
1925         dev->users--;
1926         if (!dev->users) {
1927                 videobuf_stop(&fh->vb_vidq);
1928                 videobuf_mmap_free(&fh->vb_vidq);
1929
1930                 /* the device is already disconnect,
1931                    free the remaining resources */
1932                 if (dev->state & DEV_DISCONNECTED) {
1933                         cx231xx_release_resources(dev);
1934                         fh->dev = NULL;
1935                         return 0;
1936                 }
1937
1938                 /* Save some power by putting tuner to sleep */
1939                 call_all(dev, tuner, standby);
1940
1941                 /* do this before setting alternate! */
1942                 if (dev->USE_ISO)
1943                         cx231xx_uninit_isoc(dev);
1944                 else
1945                         cx231xx_uninit_bulk(dev);
1946                 cx231xx_set_mode(dev, CX231XX_SUSPEND);
1947
1948                 /* set alternate 0 */
1949                 cx231xx_set_alt_setting(dev, INDEX_VIDEO, 0);
1950         }
1951         v4l2_fh_exit(&fh->fh);
1952         kfree(fh);
1953         wake_up_interruptible(&dev->open);
1954         return 0;
1955 }
1956
1957 static int cx231xx_v4l2_close(struct file *filp)
1958 {
1959         struct cx231xx_fh *fh = filp->private_data;
1960         struct cx231xx *dev = fh->dev;
1961         int rc;
1962
1963         mutex_lock(&dev->lock);
1964         rc = cx231xx_close(filp);
1965         mutex_unlock(&dev->lock);
1966         return rc;
1967 }
1968
1969 /*
1970  * cx231xx_v4l2_read()
1971  * will allocate buffers when called for the first time
1972  */
1973 static ssize_t
1974 cx231xx_v4l2_read(struct file *filp, char __user *buf, size_t count,
1975                   loff_t *pos)
1976 {
1977         struct cx231xx_fh *fh = filp->private_data;
1978         struct cx231xx *dev = fh->dev;
1979         int rc;
1980
1981         rc = check_dev(dev);
1982         if (rc < 0)
1983                 return rc;
1984
1985         if ((fh->type == V4L2_BUF_TYPE_VIDEO_CAPTURE) ||
1986             (fh->type == V4L2_BUF_TYPE_VBI_CAPTURE)) {
1987                 rc = res_get(fh);
1988
1989                 if (unlikely(rc < 0))
1990                         return rc;
1991
1992                 if (mutex_lock_interruptible(&dev->lock))
1993                         return -ERESTARTSYS;
1994                 rc = videobuf_read_stream(&fh->vb_vidq, buf, count, pos, 0,
1995                                             filp->f_flags & O_NONBLOCK);
1996                 mutex_unlock(&dev->lock);
1997                 return rc;
1998         }
1999         return 0;
2000 }
2001
2002 /*
2003  * cx231xx_v4l2_poll()
2004  * will allocate buffers when called for the first time
2005  */
2006 static __poll_t cx231xx_v4l2_poll(struct file *filp, poll_table *wait)
2007 {
2008         __poll_t req_events = poll_requested_events(wait);
2009         struct cx231xx_fh *fh = filp->private_data;
2010         struct cx231xx *dev = fh->dev;
2011         __poll_t res = 0;
2012         int rc;
2013
2014         rc = check_dev(dev);
2015         if (rc < 0)
2016                 return EPOLLERR;
2017
2018         rc = res_get(fh);
2019
2020         if (unlikely(rc < 0))
2021                 return EPOLLERR;
2022
2023         if (v4l2_event_pending(&fh->fh))
2024                 res |= EPOLLPRI;
2025         else
2026                 poll_wait(filp, &fh->fh.wait, wait);
2027
2028         if (!(req_events & (EPOLLIN | EPOLLRDNORM)))
2029                 return res;
2030
2031         if ((V4L2_BUF_TYPE_VIDEO_CAPTURE == fh->type) ||
2032             (V4L2_BUF_TYPE_VBI_CAPTURE == fh->type)) {
2033                 mutex_lock(&dev->lock);
2034                 res |= videobuf_poll_stream(filp, &fh->vb_vidq, wait);
2035                 mutex_unlock(&dev->lock);
2036                 return res;
2037         }
2038         return res | EPOLLERR;
2039 }
2040
2041 /*
2042  * cx231xx_v4l2_mmap()
2043  */
2044 static int cx231xx_v4l2_mmap(struct file *filp, struct vm_area_struct *vma)
2045 {
2046         struct cx231xx_fh *fh = filp->private_data;
2047         struct cx231xx *dev = fh->dev;
2048         int rc;
2049
2050         rc = check_dev(dev);
2051         if (rc < 0)
2052                 return rc;
2053
2054         rc = res_get(fh);
2055
2056         if (unlikely(rc < 0))
2057                 return rc;
2058
2059         if (mutex_lock_interruptible(&dev->lock))
2060                 return -ERESTARTSYS;
2061         rc = videobuf_mmap_mapper(&fh->vb_vidq, vma);
2062         mutex_unlock(&dev->lock);
2063
2064         cx231xx_videodbg("vma start=0x%08lx, size=%ld, ret=%d\n",
2065                          (unsigned long)vma->vm_start,
2066                          (unsigned long)vma->vm_end -
2067                          (unsigned long)vma->vm_start, rc);
2068
2069         return rc;
2070 }
2071
2072 static const struct v4l2_file_operations cx231xx_v4l_fops = {
2073         .owner   = THIS_MODULE,
2074         .open    = cx231xx_v4l2_open,
2075         .release = cx231xx_v4l2_close,
2076         .read    = cx231xx_v4l2_read,
2077         .poll    = cx231xx_v4l2_poll,
2078         .mmap    = cx231xx_v4l2_mmap,
2079         .unlocked_ioctl   = video_ioctl2,
2080 };
2081
2082 static const struct v4l2_ioctl_ops video_ioctl_ops = {
2083         .vidioc_querycap               = cx231xx_querycap,
2084         .vidioc_enum_fmt_vid_cap       = vidioc_enum_fmt_vid_cap,
2085         .vidioc_g_fmt_vid_cap          = vidioc_g_fmt_vid_cap,
2086         .vidioc_try_fmt_vid_cap        = vidioc_try_fmt_vid_cap,
2087         .vidioc_s_fmt_vid_cap          = vidioc_s_fmt_vid_cap,
2088         .vidioc_g_fmt_vbi_cap          = vidioc_g_fmt_vbi_cap,
2089         .vidioc_try_fmt_vbi_cap        = vidioc_try_fmt_vbi_cap,
2090         .vidioc_s_fmt_vbi_cap          = vidioc_s_fmt_vbi_cap,
2091         .vidioc_g_pixelaspect          = vidioc_g_pixelaspect,
2092         .vidioc_g_selection            = vidioc_g_selection,
2093         .vidioc_reqbufs                = vidioc_reqbufs,
2094         .vidioc_querybuf               = vidioc_querybuf,
2095         .vidioc_qbuf                   = vidioc_qbuf,
2096         .vidioc_dqbuf                  = vidioc_dqbuf,
2097         .vidioc_s_std                  = vidioc_s_std,
2098         .vidioc_g_std                  = vidioc_g_std,
2099         .vidioc_enum_input             = cx231xx_enum_input,
2100         .vidioc_g_input                = cx231xx_g_input,
2101         .vidioc_s_input                = cx231xx_s_input,
2102         .vidioc_streamon               = vidioc_streamon,
2103         .vidioc_streamoff              = vidioc_streamoff,
2104         .vidioc_g_tuner                = cx231xx_g_tuner,
2105         .vidioc_s_tuner                = cx231xx_s_tuner,
2106         .vidioc_g_frequency            = cx231xx_g_frequency,
2107         .vidioc_s_frequency            = cx231xx_s_frequency,
2108 #ifdef CONFIG_VIDEO_ADV_DEBUG
2109         .vidioc_g_chip_info            = cx231xx_g_chip_info,
2110         .vidioc_g_register             = cx231xx_g_register,
2111         .vidioc_s_register             = cx231xx_s_register,
2112 #endif
2113         .vidioc_subscribe_event = v4l2_ctrl_subscribe_event,
2114         .vidioc_unsubscribe_event = v4l2_event_unsubscribe,
2115 };
2116
2117 static struct video_device cx231xx_vbi_template;
2118
2119 static const struct video_device cx231xx_video_template = {
2120         .fops         = &cx231xx_v4l_fops,
2121         .release      = video_device_release_empty,
2122         .ioctl_ops    = &video_ioctl_ops,
2123         .tvnorms      = V4L2_STD_ALL,
2124 };
2125
2126 static const struct v4l2_file_operations radio_fops = {
2127         .owner   = THIS_MODULE,
2128         .open   = cx231xx_v4l2_open,
2129         .release = cx231xx_v4l2_close,
2130         .poll = v4l2_ctrl_poll,
2131         .unlocked_ioctl = video_ioctl2,
2132 };
2133
2134 static const struct v4l2_ioctl_ops radio_ioctl_ops = {
2135         .vidioc_querycap    = cx231xx_querycap,
2136         .vidioc_g_tuner     = radio_g_tuner,
2137         .vidioc_s_tuner     = radio_s_tuner,
2138         .vidioc_g_frequency = cx231xx_g_frequency,
2139         .vidioc_s_frequency = cx231xx_s_frequency,
2140 #ifdef CONFIG_VIDEO_ADV_DEBUG
2141         .vidioc_g_chip_info = cx231xx_g_chip_info,
2142         .vidioc_g_register  = cx231xx_g_register,
2143         .vidioc_s_register  = cx231xx_s_register,
2144 #endif
2145         .vidioc_subscribe_event = v4l2_ctrl_subscribe_event,
2146         .vidioc_unsubscribe_event = v4l2_event_unsubscribe,
2147 };
2148
2149 static struct video_device cx231xx_radio_template = {
2150         .name      = "cx231xx-radio",
2151         .fops      = &radio_fops,
2152         .ioctl_ops = &radio_ioctl_ops,
2153 };
2154
2155 /******************************** usb interface ******************************/
2156
2157 static void cx231xx_vdev_init(struct cx231xx *dev,
2158                 struct video_device *vfd,
2159                 const struct video_device *template,
2160                 const char *type_name)
2161 {
2162         *vfd = *template;
2163         vfd->v4l2_dev = &dev->v4l2_dev;
2164         vfd->release = video_device_release_empty;
2165         vfd->lock = &dev->lock;
2166
2167         snprintf(vfd->name, sizeof(vfd->name), "%s %s", dev->name, type_name);
2168
2169         video_set_drvdata(vfd, dev);
2170         if (dev->tuner_type == TUNER_ABSENT) {
2171                 v4l2_disable_ioctl(vfd, VIDIOC_G_FREQUENCY);
2172                 v4l2_disable_ioctl(vfd, VIDIOC_S_FREQUENCY);
2173                 v4l2_disable_ioctl(vfd, VIDIOC_G_TUNER);
2174                 v4l2_disable_ioctl(vfd, VIDIOC_S_TUNER);
2175         }
2176 }
2177
2178 int cx231xx_register_analog_devices(struct cx231xx *dev)
2179 {
2180         int ret;
2181
2182         dev_info(dev->dev, "v4l2 driver version %s\n", CX231XX_VERSION);
2183
2184         /* set default norm */
2185         dev->norm = V4L2_STD_PAL;
2186         dev->width = norm_maxw(dev);
2187         dev->height = norm_maxh(dev);
2188         dev->interlaced = 0;
2189
2190         /* Analog specific initialization */
2191         dev->format = &format[0];
2192
2193         /* Set the initial input */
2194         video_mux(dev, dev->video_input);
2195
2196         call_all(dev, video, s_std, dev->norm);
2197
2198         v4l2_ctrl_handler_init(&dev->ctrl_handler, 10);
2199         v4l2_ctrl_handler_init(&dev->radio_ctrl_handler, 5);
2200
2201         if (dev->sd_cx25840) {
2202                 v4l2_ctrl_add_handler(&dev->ctrl_handler,
2203                                 dev->sd_cx25840->ctrl_handler, NULL, true);
2204                 v4l2_ctrl_add_handler(&dev->radio_ctrl_handler,
2205                                 dev->sd_cx25840->ctrl_handler,
2206                                 v4l2_ctrl_radio_filter, true);
2207         }
2208
2209         if (dev->ctrl_handler.error)
2210                 return dev->ctrl_handler.error;
2211         if (dev->radio_ctrl_handler.error)
2212                 return dev->radio_ctrl_handler.error;
2213
2214         /* enable vbi capturing */
2215         /* write code here...  */
2216
2217         /* allocate and fill video video_device struct */
2218         cx231xx_vdev_init(dev, &dev->vdev, &cx231xx_video_template, "video");
2219 #if defined(CONFIG_MEDIA_CONTROLLER)
2220         dev->video_pad.flags = MEDIA_PAD_FL_SINK;
2221         ret = media_entity_pads_init(&dev->vdev.entity, 1, &dev->video_pad);
2222         if (ret < 0)
2223                 dev_err(dev->dev, "failed to initialize video media entity!\n");
2224 #endif
2225         dev->vdev.ctrl_handler = &dev->ctrl_handler;
2226         dev->vdev.device_caps = V4L2_CAP_READWRITE | V4L2_CAP_STREAMING |
2227                                 V4L2_CAP_VIDEO_CAPTURE;
2228         if (dev->tuner_type != TUNER_ABSENT)
2229                 dev->vdev.device_caps |= V4L2_CAP_TUNER;
2230
2231         /* register v4l2 video video_device */
2232         ret = video_register_device(&dev->vdev, VFL_TYPE_GRABBER,
2233                                     video_nr[dev->devno]);
2234         if (ret) {
2235                 dev_err(dev->dev,
2236                         "unable to register video device (error=%i).\n",
2237                         ret);
2238                 return ret;
2239         }
2240
2241         dev_info(dev->dev, "Registered video device %s [v4l2]\n",
2242                 video_device_node_name(&dev->vdev));
2243
2244         /* Initialize VBI template */
2245         cx231xx_vbi_template = cx231xx_video_template;
2246         strscpy(cx231xx_vbi_template.name, "cx231xx-vbi",
2247                 sizeof(cx231xx_vbi_template.name));
2248
2249         /* Allocate and fill vbi video_device struct */
2250         cx231xx_vdev_init(dev, &dev->vbi_dev, &cx231xx_vbi_template, "vbi");
2251
2252 #if defined(CONFIG_MEDIA_CONTROLLER)
2253         dev->vbi_pad.flags = MEDIA_PAD_FL_SINK;
2254         ret = media_entity_pads_init(&dev->vbi_dev.entity, 1, &dev->vbi_pad);
2255         if (ret < 0)
2256                 dev_err(dev->dev, "failed to initialize vbi media entity!\n");
2257 #endif
2258         dev->vbi_dev.ctrl_handler = &dev->ctrl_handler;
2259         dev->vbi_dev.device_caps = V4L2_CAP_READWRITE | V4L2_CAP_STREAMING |
2260                                    V4L2_CAP_VBI_CAPTURE;
2261         if (dev->tuner_type != TUNER_ABSENT)
2262                 dev->vbi_dev.device_caps |= V4L2_CAP_TUNER;
2263
2264         /* register v4l2 vbi video_device */
2265         ret = video_register_device(&dev->vbi_dev, VFL_TYPE_VBI,
2266                                     vbi_nr[dev->devno]);
2267         if (ret < 0) {
2268                 dev_err(dev->dev, "unable to register vbi device\n");
2269                 return ret;
2270         }
2271
2272         dev_info(dev->dev, "Registered VBI device %s\n",
2273                 video_device_node_name(&dev->vbi_dev));
2274
2275         if (cx231xx_boards[dev->model].radio.type == CX231XX_RADIO) {
2276                 cx231xx_vdev_init(dev, &dev->radio_dev,
2277                                 &cx231xx_radio_template, "radio");
2278                 dev->radio_dev.ctrl_handler = &dev->radio_ctrl_handler;
2279                 dev->radio_dev.device_caps = V4L2_CAP_RADIO | V4L2_CAP_TUNER;
2280                 ret = video_register_device(&dev->radio_dev, VFL_TYPE_RADIO,
2281                                             radio_nr[dev->devno]);
2282                 if (ret < 0) {
2283                         dev_err(dev->dev,
2284                                 "can't register radio device\n");
2285                         return ret;
2286                 }
2287                 dev_info(dev->dev, "Registered radio device as %s\n",
2288                         video_device_node_name(&dev->radio_dev));
2289         }
2290
2291         return 0;
2292 }