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