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