treewide: Replace GPLv2 boilerplate/reference with SPDX - rule 61
[linux-block.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 video_device *vdev = video_devdata(file);
1559         struct cx231xx_fh *fh = priv;
1560         struct cx231xx *dev = fh->dev;
1561
1562         strscpy(cap->driver, "cx231xx", sizeof(cap->driver));
1563         strscpy(cap->card, cx231xx_boards[dev->model].name, sizeof(cap->card));
1564         usb_make_path(dev->udev, cap->bus_info, sizeof(cap->bus_info));
1565
1566         if (vdev->vfl_type == VFL_TYPE_RADIO)
1567                 cap->device_caps = V4L2_CAP_RADIO;
1568         else {
1569                 cap->device_caps = V4L2_CAP_READWRITE | V4L2_CAP_STREAMING;
1570                 if (vdev->vfl_type == VFL_TYPE_VBI)
1571                         cap->device_caps |= V4L2_CAP_VBI_CAPTURE;
1572                 else
1573                         cap->device_caps |= V4L2_CAP_VIDEO_CAPTURE;
1574         }
1575         if (dev->tuner_type != TUNER_ABSENT)
1576                 cap->device_caps |= V4L2_CAP_TUNER;
1577         cap->capabilities = cap->device_caps | V4L2_CAP_READWRITE |
1578                 V4L2_CAP_VBI_CAPTURE | V4L2_CAP_VIDEO_CAPTURE |
1579                 V4L2_CAP_STREAMING | V4L2_CAP_DEVICE_CAPS;
1580         if (video_is_registered(&dev->radio_dev))
1581                 cap->capabilities |= V4L2_CAP_RADIO;
1582
1583         return 0;
1584 }
1585
1586 static int vidioc_enum_fmt_vid_cap(struct file *file, void *priv,
1587                                    struct v4l2_fmtdesc *f)
1588 {
1589         if (unlikely(f->index >= ARRAY_SIZE(format)))
1590                 return -EINVAL;
1591
1592         strscpy(f->description, format[f->index].name, sizeof(f->description));
1593         f->pixelformat = format[f->index].fourcc;
1594
1595         return 0;
1596 }
1597
1598 /* RAW VBI ioctls */
1599
1600 static int vidioc_g_fmt_vbi_cap(struct file *file, void *priv,
1601                                 struct v4l2_format *f)
1602 {
1603         struct cx231xx_fh *fh = priv;
1604         struct cx231xx *dev = fh->dev;
1605
1606         f->fmt.vbi.sampling_rate = 6750000 * 4;
1607         f->fmt.vbi.samples_per_line = VBI_LINE_LENGTH;
1608         f->fmt.vbi.sample_format = V4L2_PIX_FMT_GREY;
1609         f->fmt.vbi.offset = 0;
1610         f->fmt.vbi.start[0] = (dev->norm & V4L2_STD_625_50) ?
1611             PAL_VBI_START_LINE : NTSC_VBI_START_LINE;
1612         f->fmt.vbi.count[0] = (dev->norm & V4L2_STD_625_50) ?
1613             PAL_VBI_LINES : NTSC_VBI_LINES;
1614         f->fmt.vbi.start[1] = (dev->norm & V4L2_STD_625_50) ?
1615             PAL_VBI_START_LINE + 312 : NTSC_VBI_START_LINE + 263;
1616         f->fmt.vbi.count[1] = f->fmt.vbi.count[0];
1617         memset(f->fmt.vbi.reserved, 0, sizeof(f->fmt.vbi.reserved));
1618
1619         return 0;
1620
1621 }
1622
1623 static int vidioc_try_fmt_vbi_cap(struct file *file, void *priv,
1624                                   struct v4l2_format *f)
1625 {
1626         struct cx231xx_fh *fh = priv;
1627         struct cx231xx *dev = fh->dev;
1628
1629         f->fmt.vbi.sampling_rate = 6750000 * 4;
1630         f->fmt.vbi.samples_per_line = VBI_LINE_LENGTH;
1631         f->fmt.vbi.sample_format = V4L2_PIX_FMT_GREY;
1632         f->fmt.vbi.offset = 0;
1633         f->fmt.vbi.flags = 0;
1634         f->fmt.vbi.start[0] = (dev->norm & V4L2_STD_625_50) ?
1635             PAL_VBI_START_LINE : NTSC_VBI_START_LINE;
1636         f->fmt.vbi.count[0] = (dev->norm & V4L2_STD_625_50) ?
1637             PAL_VBI_LINES : NTSC_VBI_LINES;
1638         f->fmt.vbi.start[1] = (dev->norm & V4L2_STD_625_50) ?
1639             PAL_VBI_START_LINE + 312 : NTSC_VBI_START_LINE + 263;
1640         f->fmt.vbi.count[1] = f->fmt.vbi.count[0];
1641         memset(f->fmt.vbi.reserved, 0, sizeof(f->fmt.vbi.reserved));
1642
1643         return 0;
1644
1645 }
1646
1647 static int vidioc_s_fmt_vbi_cap(struct file *file, void *priv,
1648                                   struct v4l2_format *f)
1649 {
1650         struct cx231xx_fh *fh = priv;
1651         struct cx231xx *dev = fh->dev;
1652
1653         if (dev->vbi_stream_on && !fh->stream_on) {
1654                 dev_err(dev->dev,
1655                         "%s device in use by another fh\n", __func__);
1656                 return -EBUSY;
1657         }
1658         return vidioc_try_fmt_vbi_cap(file, priv, f);
1659 }
1660
1661 static int vidioc_reqbufs(struct file *file, void *priv,
1662                           struct v4l2_requestbuffers *rb)
1663 {
1664         struct cx231xx_fh *fh = priv;
1665         struct cx231xx *dev = fh->dev;
1666         int rc;
1667
1668         rc = check_dev(dev);
1669         if (rc < 0)
1670                 return rc;
1671
1672         return videobuf_reqbufs(&fh->vb_vidq, rb);
1673 }
1674
1675 static int vidioc_querybuf(struct file *file, void *priv, struct v4l2_buffer *b)
1676 {
1677         struct cx231xx_fh *fh = priv;
1678         struct cx231xx *dev = fh->dev;
1679         int rc;
1680
1681         rc = check_dev(dev);
1682         if (rc < 0)
1683                 return rc;
1684
1685         return videobuf_querybuf(&fh->vb_vidq, b);
1686 }
1687
1688 static int vidioc_qbuf(struct file *file, void *priv, struct v4l2_buffer *b)
1689 {
1690         struct cx231xx_fh *fh = priv;
1691         struct cx231xx *dev = fh->dev;
1692         int rc;
1693
1694         rc = check_dev(dev);
1695         if (rc < 0)
1696                 return rc;
1697
1698         return videobuf_qbuf(&fh->vb_vidq, b);
1699 }
1700
1701 static int vidioc_dqbuf(struct file *file, void *priv, struct v4l2_buffer *b)
1702 {
1703         struct cx231xx_fh *fh = priv;
1704         struct cx231xx *dev = fh->dev;
1705         int rc;
1706
1707         rc = check_dev(dev);
1708         if (rc < 0)
1709                 return rc;
1710
1711         return videobuf_dqbuf(&fh->vb_vidq, b, file->f_flags & O_NONBLOCK);
1712 }
1713
1714 /* ----------------------------------------------------------- */
1715 /* RADIO ESPECIFIC IOCTLS                                      */
1716 /* ----------------------------------------------------------- */
1717
1718 static int radio_g_tuner(struct file *file, void *priv, struct v4l2_tuner *t)
1719 {
1720         struct cx231xx *dev = ((struct cx231xx_fh *)priv)->dev;
1721
1722         if (t->index)
1723                 return -EINVAL;
1724
1725         strscpy(t->name, "Radio", sizeof(t->name));
1726
1727         call_all(dev, tuner, g_tuner, t);
1728
1729         return 0;
1730 }
1731 static int radio_s_tuner(struct file *file, void *priv, const struct v4l2_tuner *t)
1732 {
1733         struct cx231xx *dev = ((struct cx231xx_fh *)priv)->dev;
1734
1735         if (t->index)
1736                 return -EINVAL;
1737
1738         call_all(dev, tuner, s_tuner, t);
1739
1740         return 0;
1741 }
1742
1743 /*
1744  * cx231xx_v4l2_open()
1745  * inits the device and starts isoc transfer
1746  */
1747 static int cx231xx_v4l2_open(struct file *filp)
1748 {
1749         int radio = 0;
1750         struct video_device *vdev = video_devdata(filp);
1751         struct cx231xx *dev = video_drvdata(filp);
1752         struct cx231xx_fh *fh;
1753         enum v4l2_buf_type fh_type = 0;
1754
1755         switch (vdev->vfl_type) {
1756         case VFL_TYPE_GRABBER:
1757                 fh_type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
1758                 break;
1759         case VFL_TYPE_VBI:
1760                 fh_type = V4L2_BUF_TYPE_VBI_CAPTURE;
1761                 break;
1762         case VFL_TYPE_RADIO:
1763                 radio = 1;
1764                 break;
1765         default:
1766                 return -EINVAL;
1767         }
1768
1769         cx231xx_videodbg("open dev=%s type=%s users=%d\n",
1770                          video_device_node_name(vdev), v4l2_type_names[fh_type],
1771                          dev->users);
1772
1773 #if 0
1774         errCode = cx231xx_set_mode(dev, CX231XX_ANALOG_MODE);
1775         if (errCode < 0) {
1776                 dev_err(dev->dev,
1777                         "Device locked on digital mode. Can't open analog\n");
1778                 return -EBUSY;
1779         }
1780 #endif
1781
1782         fh = kzalloc(sizeof(struct cx231xx_fh), GFP_KERNEL);
1783         if (!fh)
1784                 return -ENOMEM;
1785         if (mutex_lock_interruptible(&dev->lock)) {
1786                 kfree(fh);
1787                 return -ERESTARTSYS;
1788         }
1789         fh->dev = dev;
1790         fh->type = fh_type;
1791         filp->private_data = fh;
1792         v4l2_fh_init(&fh->fh, vdev);
1793
1794         if (fh->type == V4L2_BUF_TYPE_VIDEO_CAPTURE && dev->users == 0) {
1795                 /* Power up in Analog TV mode */
1796                 if (dev->board.external_av)
1797                         cx231xx_set_power_mode(dev,
1798                                  POLARIS_AVMODE_ENXTERNAL_AV);
1799                 else
1800                         cx231xx_set_power_mode(dev, POLARIS_AVMODE_ANALOGT_TV);
1801
1802 #if 0
1803                 cx231xx_set_mode(dev, CX231XX_ANALOG_MODE);
1804 #endif
1805
1806                 /* set video alternate setting */
1807                 cx231xx_set_video_alternate(dev);
1808
1809                 /* Needed, since GPIO might have disabled power of
1810                    some i2c device */
1811                 cx231xx_config_i2c(dev);
1812
1813                 /* device needs to be initialized before isoc transfer */
1814                 dev->video_input = dev->video_input > 2 ? 2 : dev->video_input;
1815
1816         }
1817         if (radio) {
1818                 cx231xx_videodbg("video_open: setting radio device\n");
1819
1820                 /* cx231xx_start_radio(dev); */
1821
1822                 call_all(dev, tuner, s_radio);
1823         }
1824
1825         dev->users++;
1826
1827         if (fh->type == V4L2_BUF_TYPE_VIDEO_CAPTURE)
1828                 videobuf_queue_vmalloc_init(&fh->vb_vidq, &cx231xx_video_qops,
1829                                             NULL, &dev->video_mode.slock,
1830                                             fh->type, V4L2_FIELD_INTERLACED,
1831                                             sizeof(struct cx231xx_buffer),
1832                                             fh, &dev->lock);
1833         if (fh->type == V4L2_BUF_TYPE_VBI_CAPTURE) {
1834                 /* Set the required alternate setting  VBI interface works in
1835                    Bulk mode only */
1836                 cx231xx_set_alt_setting(dev, INDEX_VANC, 0);
1837
1838                 videobuf_queue_vmalloc_init(&fh->vb_vidq, &cx231xx_vbi_qops,
1839                                             NULL, &dev->vbi_mode.slock,
1840                                             fh->type, V4L2_FIELD_SEQ_TB,
1841                                             sizeof(struct cx231xx_buffer),
1842                                             fh, &dev->lock);
1843         }
1844         mutex_unlock(&dev->lock);
1845         v4l2_fh_add(&fh->fh);
1846
1847         return 0;
1848 }
1849
1850 /*
1851  * cx231xx_realease_resources()
1852  * unregisters the v4l2,i2c and usb devices
1853  * called when the device gets disconected or at module unload
1854 */
1855 void cx231xx_release_analog_resources(struct cx231xx *dev)
1856 {
1857
1858         /*FIXME: I2C IR should be disconnected */
1859
1860         if (video_is_registered(&dev->radio_dev))
1861                 video_unregister_device(&dev->radio_dev);
1862         if (video_is_registered(&dev->vbi_dev)) {
1863                 dev_info(dev->dev, "V4L2 device %s deregistered\n",
1864                         video_device_node_name(&dev->vbi_dev));
1865                 video_unregister_device(&dev->vbi_dev);
1866         }
1867         if (video_is_registered(&dev->vdev)) {
1868                 dev_info(dev->dev, "V4L2 device %s deregistered\n",
1869                         video_device_node_name(&dev->vdev));
1870
1871                 if (dev->board.has_417)
1872                         cx231xx_417_unregister(dev);
1873
1874                 video_unregister_device(&dev->vdev);
1875         }
1876         v4l2_ctrl_handler_free(&dev->ctrl_handler);
1877         v4l2_ctrl_handler_free(&dev->radio_ctrl_handler);
1878 }
1879
1880 /*
1881  * cx231xx_close()
1882  * stops streaming and deallocates all resources allocated by the v4l2
1883  * calls and ioctls
1884  */
1885 static int cx231xx_close(struct file *filp)
1886 {
1887         struct cx231xx_fh *fh = filp->private_data;
1888         struct cx231xx *dev = fh->dev;
1889
1890         cx231xx_videodbg("users=%d\n", dev->users);
1891
1892         cx231xx_videodbg("users=%d\n", dev->users);
1893         if (res_check(fh))
1894                 res_free(fh);
1895
1896         /*
1897          * To workaround error number=-71 on EP0 for VideoGrabber,
1898          *       need exclude following.
1899          * FIXME: It is probably safe to remove most of these, as we're
1900          * now avoiding the alternate setting for INDEX_VANC
1901          */
1902         if (!dev->board.no_alt_vanc)
1903                 if (fh->type == V4L2_BUF_TYPE_VBI_CAPTURE) {
1904                         videobuf_stop(&fh->vb_vidq);
1905                         videobuf_mmap_free(&fh->vb_vidq);
1906
1907                         /* the device is already disconnect,
1908                            free the remaining resources */
1909                         if (dev->state & DEV_DISCONNECTED) {
1910                                 if (atomic_read(&dev->devlist_count) > 0) {
1911                                         cx231xx_release_resources(dev);
1912                                         fh->dev = NULL;
1913                                         return 0;
1914                                 }
1915                                 return 0;
1916                         }
1917
1918                         /* do this before setting alternate! */
1919                         cx231xx_uninit_vbi_isoc(dev);
1920
1921                         /* set alternate 0 */
1922                         if (!dev->vbi_or_sliced_cc_mode)
1923                                 cx231xx_set_alt_setting(dev, INDEX_VANC, 0);
1924                         else
1925                                 cx231xx_set_alt_setting(dev, INDEX_HANC, 0);
1926
1927                         v4l2_fh_del(&fh->fh);
1928                         v4l2_fh_exit(&fh->fh);
1929                         kfree(fh);
1930                         dev->users--;
1931                         wake_up_interruptible(&dev->open);
1932                         return 0;
1933                 }
1934
1935         v4l2_fh_del(&fh->fh);
1936         dev->users--;
1937         if (!dev->users) {
1938                 videobuf_stop(&fh->vb_vidq);
1939                 videobuf_mmap_free(&fh->vb_vidq);
1940
1941                 /* the device is already disconnect,
1942                    free the remaining resources */
1943                 if (dev->state & DEV_DISCONNECTED) {
1944                         cx231xx_release_resources(dev);
1945                         fh->dev = NULL;
1946                         return 0;
1947                 }
1948
1949                 /* Save some power by putting tuner to sleep */
1950                 call_all(dev, tuner, standby);
1951
1952                 /* do this before setting alternate! */
1953                 if (dev->USE_ISO)
1954                         cx231xx_uninit_isoc(dev);
1955                 else
1956                         cx231xx_uninit_bulk(dev);
1957                 cx231xx_set_mode(dev, CX231XX_SUSPEND);
1958
1959                 /* set alternate 0 */
1960                 cx231xx_set_alt_setting(dev, INDEX_VIDEO, 0);
1961         }
1962         v4l2_fh_exit(&fh->fh);
1963         kfree(fh);
1964         wake_up_interruptible(&dev->open);
1965         return 0;
1966 }
1967
1968 static int cx231xx_v4l2_close(struct file *filp)
1969 {
1970         struct cx231xx_fh *fh = filp->private_data;
1971         struct cx231xx *dev = fh->dev;
1972         int rc;
1973
1974         mutex_lock(&dev->lock);
1975         rc = cx231xx_close(filp);
1976         mutex_unlock(&dev->lock);
1977         return rc;
1978 }
1979
1980 /*
1981  * cx231xx_v4l2_read()
1982  * will allocate buffers when called for the first time
1983  */
1984 static ssize_t
1985 cx231xx_v4l2_read(struct file *filp, char __user *buf, size_t count,
1986                   loff_t *pos)
1987 {
1988         struct cx231xx_fh *fh = filp->private_data;
1989         struct cx231xx *dev = fh->dev;
1990         int rc;
1991
1992         rc = check_dev(dev);
1993         if (rc < 0)
1994                 return rc;
1995
1996         if ((fh->type == V4L2_BUF_TYPE_VIDEO_CAPTURE) ||
1997             (fh->type == V4L2_BUF_TYPE_VBI_CAPTURE)) {
1998                 rc = res_get(fh);
1999
2000                 if (unlikely(rc < 0))
2001                         return rc;
2002
2003                 if (mutex_lock_interruptible(&dev->lock))
2004                         return -ERESTARTSYS;
2005                 rc = videobuf_read_stream(&fh->vb_vidq, buf, count, pos, 0,
2006                                             filp->f_flags & O_NONBLOCK);
2007                 mutex_unlock(&dev->lock);
2008                 return rc;
2009         }
2010         return 0;
2011 }
2012
2013 /*
2014  * cx231xx_v4l2_poll()
2015  * will allocate buffers when called for the first time
2016  */
2017 static __poll_t cx231xx_v4l2_poll(struct file *filp, poll_table *wait)
2018 {
2019         __poll_t req_events = poll_requested_events(wait);
2020         struct cx231xx_fh *fh = filp->private_data;
2021         struct cx231xx *dev = fh->dev;
2022         __poll_t res = 0;
2023         int rc;
2024
2025         rc = check_dev(dev);
2026         if (rc < 0)
2027                 return EPOLLERR;
2028
2029         rc = res_get(fh);
2030
2031         if (unlikely(rc < 0))
2032                 return EPOLLERR;
2033
2034         if (v4l2_event_pending(&fh->fh))
2035                 res |= EPOLLPRI;
2036         else
2037                 poll_wait(filp, &fh->fh.wait, wait);
2038
2039         if (!(req_events & (EPOLLIN | EPOLLRDNORM)))
2040                 return res;
2041
2042         if ((V4L2_BUF_TYPE_VIDEO_CAPTURE == fh->type) ||
2043             (V4L2_BUF_TYPE_VBI_CAPTURE == fh->type)) {
2044                 mutex_lock(&dev->lock);
2045                 res |= videobuf_poll_stream(filp, &fh->vb_vidq, wait);
2046                 mutex_unlock(&dev->lock);
2047                 return res;
2048         }
2049         return res | EPOLLERR;
2050 }
2051
2052 /*
2053  * cx231xx_v4l2_mmap()
2054  */
2055 static int cx231xx_v4l2_mmap(struct file *filp, struct vm_area_struct *vma)
2056 {
2057         struct cx231xx_fh *fh = filp->private_data;
2058         struct cx231xx *dev = fh->dev;
2059         int rc;
2060
2061         rc = check_dev(dev);
2062         if (rc < 0)
2063                 return rc;
2064
2065         rc = res_get(fh);
2066
2067         if (unlikely(rc < 0))
2068                 return rc;
2069
2070         if (mutex_lock_interruptible(&dev->lock))
2071                 return -ERESTARTSYS;
2072         rc = videobuf_mmap_mapper(&fh->vb_vidq, vma);
2073         mutex_unlock(&dev->lock);
2074
2075         cx231xx_videodbg("vma start=0x%08lx, size=%ld, ret=%d\n",
2076                          (unsigned long)vma->vm_start,
2077                          (unsigned long)vma->vm_end -
2078                          (unsigned long)vma->vm_start, rc);
2079
2080         return rc;
2081 }
2082
2083 static const struct v4l2_file_operations cx231xx_v4l_fops = {
2084         .owner   = THIS_MODULE,
2085         .open    = cx231xx_v4l2_open,
2086         .release = cx231xx_v4l2_close,
2087         .read    = cx231xx_v4l2_read,
2088         .poll    = cx231xx_v4l2_poll,
2089         .mmap    = cx231xx_v4l2_mmap,
2090         .unlocked_ioctl   = video_ioctl2,
2091 };
2092
2093 static const struct v4l2_ioctl_ops video_ioctl_ops = {
2094         .vidioc_querycap               = cx231xx_querycap,
2095         .vidioc_enum_fmt_vid_cap       = vidioc_enum_fmt_vid_cap,
2096         .vidioc_g_fmt_vid_cap          = vidioc_g_fmt_vid_cap,
2097         .vidioc_try_fmt_vid_cap        = vidioc_try_fmt_vid_cap,
2098         .vidioc_s_fmt_vid_cap          = vidioc_s_fmt_vid_cap,
2099         .vidioc_g_fmt_vbi_cap          = vidioc_g_fmt_vbi_cap,
2100         .vidioc_try_fmt_vbi_cap        = vidioc_try_fmt_vbi_cap,
2101         .vidioc_s_fmt_vbi_cap          = vidioc_s_fmt_vbi_cap,
2102         .vidioc_g_pixelaspect          = vidioc_g_pixelaspect,
2103         .vidioc_g_selection            = vidioc_g_selection,
2104         .vidioc_reqbufs                = vidioc_reqbufs,
2105         .vidioc_querybuf               = vidioc_querybuf,
2106         .vidioc_qbuf                   = vidioc_qbuf,
2107         .vidioc_dqbuf                  = vidioc_dqbuf,
2108         .vidioc_s_std                  = vidioc_s_std,
2109         .vidioc_g_std                  = vidioc_g_std,
2110         .vidioc_enum_input             = cx231xx_enum_input,
2111         .vidioc_g_input                = cx231xx_g_input,
2112         .vidioc_s_input                = cx231xx_s_input,
2113         .vidioc_streamon               = vidioc_streamon,
2114         .vidioc_streamoff              = vidioc_streamoff,
2115         .vidioc_g_tuner                = cx231xx_g_tuner,
2116         .vidioc_s_tuner                = cx231xx_s_tuner,
2117         .vidioc_g_frequency            = cx231xx_g_frequency,
2118         .vidioc_s_frequency            = cx231xx_s_frequency,
2119 #ifdef CONFIG_VIDEO_ADV_DEBUG
2120         .vidioc_g_chip_info            = cx231xx_g_chip_info,
2121         .vidioc_g_register             = cx231xx_g_register,
2122         .vidioc_s_register             = cx231xx_s_register,
2123 #endif
2124         .vidioc_subscribe_event = v4l2_ctrl_subscribe_event,
2125         .vidioc_unsubscribe_event = v4l2_event_unsubscribe,
2126 };
2127
2128 static struct video_device cx231xx_vbi_template;
2129
2130 static const struct video_device cx231xx_video_template = {
2131         .fops         = &cx231xx_v4l_fops,
2132         .release      = video_device_release_empty,
2133         .ioctl_ops    = &video_ioctl_ops,
2134         .tvnorms      = V4L2_STD_ALL,
2135 };
2136
2137 static const struct v4l2_file_operations radio_fops = {
2138         .owner   = THIS_MODULE,
2139         .open   = cx231xx_v4l2_open,
2140         .release = cx231xx_v4l2_close,
2141         .poll = v4l2_ctrl_poll,
2142         .unlocked_ioctl = video_ioctl2,
2143 };
2144
2145 static const struct v4l2_ioctl_ops radio_ioctl_ops = {
2146         .vidioc_querycap    = cx231xx_querycap,
2147         .vidioc_g_tuner     = radio_g_tuner,
2148         .vidioc_s_tuner     = radio_s_tuner,
2149         .vidioc_g_frequency = cx231xx_g_frequency,
2150         .vidioc_s_frequency = cx231xx_s_frequency,
2151 #ifdef CONFIG_VIDEO_ADV_DEBUG
2152         .vidioc_g_chip_info = cx231xx_g_chip_info,
2153         .vidioc_g_register  = cx231xx_g_register,
2154         .vidioc_s_register  = cx231xx_s_register,
2155 #endif
2156         .vidioc_subscribe_event = v4l2_ctrl_subscribe_event,
2157         .vidioc_unsubscribe_event = v4l2_event_unsubscribe,
2158 };
2159
2160 static struct video_device cx231xx_radio_template = {
2161         .name      = "cx231xx-radio",
2162         .fops      = &radio_fops,
2163         .ioctl_ops = &radio_ioctl_ops,
2164 };
2165
2166 /******************************** usb interface ******************************/
2167
2168 static void cx231xx_vdev_init(struct cx231xx *dev,
2169                 struct video_device *vfd,
2170                 const struct video_device *template,
2171                 const char *type_name)
2172 {
2173         *vfd = *template;
2174         vfd->v4l2_dev = &dev->v4l2_dev;
2175         vfd->release = video_device_release_empty;
2176         vfd->lock = &dev->lock;
2177
2178         snprintf(vfd->name, sizeof(vfd->name), "%s %s", dev->name, type_name);
2179
2180         video_set_drvdata(vfd, dev);
2181         if (dev->tuner_type == TUNER_ABSENT) {
2182                 v4l2_disable_ioctl(vfd, VIDIOC_G_FREQUENCY);
2183                 v4l2_disable_ioctl(vfd, VIDIOC_S_FREQUENCY);
2184                 v4l2_disable_ioctl(vfd, VIDIOC_G_TUNER);
2185                 v4l2_disable_ioctl(vfd, VIDIOC_S_TUNER);
2186         }
2187 }
2188
2189 int cx231xx_register_analog_devices(struct cx231xx *dev)
2190 {
2191         int ret;
2192
2193         dev_info(dev->dev, "v4l2 driver version %s\n", CX231XX_VERSION);
2194
2195         /* set default norm */
2196         dev->norm = V4L2_STD_PAL;
2197         dev->width = norm_maxw(dev);
2198         dev->height = norm_maxh(dev);
2199         dev->interlaced = 0;
2200
2201         /* Analog specific initialization */
2202         dev->format = &format[0];
2203
2204         /* Set the initial input */
2205         video_mux(dev, dev->video_input);
2206
2207         call_all(dev, video, s_std, dev->norm);
2208
2209         v4l2_ctrl_handler_init(&dev->ctrl_handler, 10);
2210         v4l2_ctrl_handler_init(&dev->radio_ctrl_handler, 5);
2211
2212         if (dev->sd_cx25840) {
2213                 v4l2_ctrl_add_handler(&dev->ctrl_handler,
2214                                 dev->sd_cx25840->ctrl_handler, NULL, true);
2215                 v4l2_ctrl_add_handler(&dev->radio_ctrl_handler,
2216                                 dev->sd_cx25840->ctrl_handler,
2217                                 v4l2_ctrl_radio_filter, true);
2218         }
2219
2220         if (dev->ctrl_handler.error)
2221                 return dev->ctrl_handler.error;
2222         if (dev->radio_ctrl_handler.error)
2223                 return dev->radio_ctrl_handler.error;
2224
2225         /* enable vbi capturing */
2226         /* write code here...  */
2227
2228         /* allocate and fill video video_device struct */
2229         cx231xx_vdev_init(dev, &dev->vdev, &cx231xx_video_template, "video");
2230 #if defined(CONFIG_MEDIA_CONTROLLER)
2231         dev->video_pad.flags = MEDIA_PAD_FL_SINK;
2232         ret = media_entity_pads_init(&dev->vdev.entity, 1, &dev->video_pad);
2233         if (ret < 0)
2234                 dev_err(dev->dev, "failed to initialize video media entity!\n");
2235 #endif
2236         dev->vdev.ctrl_handler = &dev->ctrl_handler;
2237         /* register v4l2 video video_device */
2238         ret = video_register_device(&dev->vdev, VFL_TYPE_GRABBER,
2239                                     video_nr[dev->devno]);
2240         if (ret) {
2241                 dev_err(dev->dev,
2242                         "unable to register video device (error=%i).\n",
2243                         ret);
2244                 return ret;
2245         }
2246
2247         dev_info(dev->dev, "Registered video device %s [v4l2]\n",
2248                 video_device_node_name(&dev->vdev));
2249
2250         /* Initialize VBI template */
2251         cx231xx_vbi_template = cx231xx_video_template;
2252         strscpy(cx231xx_vbi_template.name, "cx231xx-vbi",
2253                 sizeof(cx231xx_vbi_template.name));
2254
2255         /* Allocate and fill vbi video_device struct */
2256         cx231xx_vdev_init(dev, &dev->vbi_dev, &cx231xx_vbi_template, "vbi");
2257
2258 #if defined(CONFIG_MEDIA_CONTROLLER)
2259         dev->vbi_pad.flags = MEDIA_PAD_FL_SINK;
2260         ret = media_entity_pads_init(&dev->vbi_dev.entity, 1, &dev->vbi_pad);
2261         if (ret < 0)
2262                 dev_err(dev->dev, "failed to initialize vbi media entity!\n");
2263 #endif
2264         dev->vbi_dev.ctrl_handler = &dev->ctrl_handler;
2265         /* register v4l2 vbi video_device */
2266         ret = video_register_device(&dev->vbi_dev, VFL_TYPE_VBI,
2267                                     vbi_nr[dev->devno]);
2268         if (ret < 0) {
2269                 dev_err(dev->dev, "unable to register vbi device\n");
2270                 return ret;
2271         }
2272
2273         dev_info(dev->dev, "Registered VBI device %s\n",
2274                 video_device_node_name(&dev->vbi_dev));
2275
2276         if (cx231xx_boards[dev->model].radio.type == CX231XX_RADIO) {
2277                 cx231xx_vdev_init(dev, &dev->radio_dev,
2278                                 &cx231xx_radio_template, "radio");
2279                 dev->radio_dev.ctrl_handler = &dev->radio_ctrl_handler;
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 }