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