1 /*
2  *  cx18 ioctl system call
3  *
4  *  Derived from ivtv-ioctl.c
5  *
6  *  Copyright (C) 2007  Hans Verkuil <hverkuil@xs4all.nl>
7  *  Copyright (C) 2008  Andy Walls <awalls@md.metrocast.net>
8  *
9  *  This program is free software; you can redistribute it and/or modify
10  *  it under the terms of the GNU General Public License as published by
11  *  the Free Software Foundation; either version 2 of the License, or
12  *  (at your option) any later version.
13  *
14  *  This program is distributed in the hope that it will be useful,
15  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
16  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17  *  GNU General Public License for more details.
18  *
19  *  You should have received a copy of the GNU General Public License
20  *  along with this program; if not, write to the Free Software
21  *  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
22  *  02111-1307  USA
23  */
24 
25 #include "cx18-driver.h"
26 #include "cx18-io.h"
27 #include "cx18-version.h"
28 #include "cx18-mailbox.h"
29 #include "cx18-i2c.h"
30 #include "cx18-queue.h"
31 #include "cx18-fileops.h"
32 #include "cx18-vbi.h"
33 #include "cx18-audio.h"
34 #include "cx18-video.h"
35 #include "cx18-streams.h"
36 #include "cx18-ioctl.h"
37 #include "cx18-gpio.h"
38 #include "cx18-controls.h"
39 #include "cx18-cards.h"
40 #include "cx18-av-core.h"
41 #include <media/tveeprom.h>
42 #include <media/v4l2-event.h>
43 
44 u16 cx18_service2vbi(int type)
45 {
46 	switch (type) {
47 	case V4L2_SLICED_TELETEXT_B:
48 		return CX18_SLICED_TYPE_TELETEXT_B;
49 	case V4L2_SLICED_CAPTION_525:
50 		return CX18_SLICED_TYPE_CAPTION_525;
51 	case V4L2_SLICED_WSS_625:
52 		return CX18_SLICED_TYPE_WSS_625;
53 	case V4L2_SLICED_VPS:
54 		return CX18_SLICED_TYPE_VPS;
55 	default:
56 		return 0;
57 	}
58 }
59 
60 /* Check if VBI services are allowed on the (field, line) for the video std */
61 static int valid_service_line(int field, int line, int is_pal)
62 {
63 	return (is_pal && line >= 6 &&
64 		((field == 0 && line <= 23) || (field == 1 && line <= 22))) ||
65 	       (!is_pal && line >= 10 && line < 22);
66 }
67 
68 /*
69  * For a (field, line, std) and inbound potential set of services for that line,
70  * return the first valid service of those passed in the incoming set for that
71  * line in priority order:
72  * CC, VPS, or WSS over TELETEXT for well known lines
73  * TELETEXT, before VPS, before CC, before WSS, for other lines
74  */
75 static u16 select_service_from_set(int field, int line, u16 set, int is_pal)
76 {
77 	u16 valid_set = (is_pal ? V4L2_SLICED_VBI_625 : V4L2_SLICED_VBI_525);
78 	int i;
79 
80 	set = set & valid_set;
81 	if (set == 0 || !valid_service_line(field, line, is_pal))
82 		return 0;
83 	if (!is_pal) {
84 		if (line == 21 && (set & V4L2_SLICED_CAPTION_525))
85 			return V4L2_SLICED_CAPTION_525;
86 	} else {
87 		if (line == 16 && field == 0 && (set & V4L2_SLICED_VPS))
88 			return V4L2_SLICED_VPS;
89 		if (line == 23 && field == 0 && (set & V4L2_SLICED_WSS_625))
90 			return V4L2_SLICED_WSS_625;
91 		if (line == 23)
92 			return 0;
93 	}
94 	for (i = 0; i < 32; i++) {
95 		if ((1 << i) & set)
96 			return 1 << i;
97 	}
98 	return 0;
99 }
100 
101 /*
102  * Expand the service_set of *fmt into valid service_lines for the std,
103  * and clear the passed in fmt->service_set
104  */
105 void cx18_expand_service_set(struct v4l2_sliced_vbi_format *fmt, int is_pal)
106 {
107 	u16 set = fmt->service_set;
108 	int f, l;
109 
110 	fmt->service_set = 0;
111 	for (f = 0; f < 2; f++) {
112 		for (l = 0; l < 24; l++)
113 			fmt->service_lines[f][l] = select_service_from_set(f, l, set, is_pal);
114 	}
115 }
116 
117 /*
118  * Sanitize the service_lines in *fmt per the video std, and return 1
119  * if any service_line is left as valid after santization
120  */
121 static int check_service_set(struct v4l2_sliced_vbi_format *fmt, int is_pal)
122 {
123 	int f, l;
124 	u16 set = 0;
125 
126 	for (f = 0; f < 2; f++) {
127 		for (l = 0; l < 24; l++) {
128 			fmt->service_lines[f][l] = select_service_from_set(f, l, fmt->service_lines[f][l], is_pal);
129 			set |= fmt->service_lines[f][l];
130 		}
131 	}
132 	return set != 0;
133 }
134 
135 /* Compute the service_set from the assumed valid service_lines of *fmt */
136 u16 cx18_get_service_set(struct v4l2_sliced_vbi_format *fmt)
137 {
138 	int f, l;
139 	u16 set = 0;
140 
141 	for (f = 0; f < 2; f++) {
142 		for (l = 0; l < 24; l++)
143 			set |= fmt->service_lines[f][l];
144 	}
145 	return set;
146 }
147 
148 static int cx18_g_fmt_vid_cap(struct file *file, void *fh,
149 				struct v4l2_format *fmt)
150 {
151 	struct cx18_open_id *id = fh2id(fh);
152 	struct cx18 *cx = id->cx;
153 	struct cx18_stream *s = &cx->streams[id->type];
154 	struct v4l2_pix_format *pixfmt = &fmt->fmt.pix;
155 
156 	pixfmt->width = cx->cxhdl.width;
157 	pixfmt->height = cx->cxhdl.height;
158 	pixfmt->colorspace = V4L2_COLORSPACE_SMPTE170M;
159 	pixfmt->field = V4L2_FIELD_INTERLACED;
160 	if (id->type == CX18_ENC_STREAM_TYPE_YUV) {
161 		pixfmt->pixelformat = s->pixelformat;
162 		pixfmt->sizeimage = s->vb_bytes_per_frame;
163 		pixfmt->bytesperline = s->vb_bytes_per_line;
164 	} else {
165 		pixfmt->pixelformat = V4L2_PIX_FMT_MPEG;
166 		pixfmt->sizeimage = 128 * 1024;
167 		pixfmt->bytesperline = 0;
168 	}
169 	return 0;
170 }
171 
172 static int cx18_g_fmt_vbi_cap(struct file *file, void *fh,
173 				struct v4l2_format *fmt)
174 {
175 	struct cx18 *cx = fh2id(fh)->cx;
176 	struct v4l2_vbi_format *vbifmt = &fmt->fmt.vbi;
177 
178 	vbifmt->sampling_rate = 27000000;
179 	vbifmt->offset = 248; /* FIXME - slightly wrong for both 50 & 60 Hz */
180 	vbifmt->samples_per_line = vbi_active_samples - 4;
181 	vbifmt->sample_format = V4L2_PIX_FMT_GREY;
182 	vbifmt->start[0] = cx->vbi.start[0];
183 	vbifmt->start[1] = cx->vbi.start[1];
184 	vbifmt->count[0] = vbifmt->count[1] = cx->vbi.count;
185 	vbifmt->flags = 0;
186 	vbifmt->reserved[0] = 0;
187 	vbifmt->reserved[1] = 0;
188 	return 0;
189 }
190 
191 static int cx18_g_fmt_sliced_vbi_cap(struct file *file, void *fh,
192 					struct v4l2_format *fmt)
193 {
194 	struct cx18 *cx = fh2id(fh)->cx;
195 	struct v4l2_sliced_vbi_format *vbifmt = &fmt->fmt.sliced;
196 
197 	/* sane, V4L2 spec compliant, defaults */
198 	vbifmt->reserved[0] = 0;
199 	vbifmt->reserved[1] = 0;
200 	vbifmt->io_size = sizeof(struct v4l2_sliced_vbi_data) * 36;
201 	memset(vbifmt->service_lines, 0, sizeof(vbifmt->service_lines));
202 	vbifmt->service_set = 0;
203 
204 	/*
205 	 * Fetch the configured service_lines and total service_set from the
206 	 * digitizer/slicer.  Note, cx18_av_vbi() wipes the passed in
207 	 * fmt->fmt.sliced under valid calling conditions
208 	 */
209 	if (v4l2_subdev_call(cx->sd_av, vbi, g_sliced_fmt, &fmt->fmt.sliced))
210 		return -EINVAL;
211 
212 	vbifmt->service_set = cx18_get_service_set(vbifmt);
213 	return 0;
214 }
215 
216 static int cx18_try_fmt_vid_cap(struct file *file, void *fh,
217 				struct v4l2_format *fmt)
218 {
219 	struct cx18_open_id *id = fh2id(fh);
220 	struct cx18 *cx = id->cx;
221 	int w = fmt->fmt.pix.width;
222 	int h = fmt->fmt.pix.height;
223 	int min_h = 2;
224 
225 	w = min(w, 720);
226 	w = max(w, 2);
227 	if (id->type == CX18_ENC_STREAM_TYPE_YUV) {
228 		/* YUV height must be a multiple of 32 */
229 		h &= ~0x1f;
230 		min_h = 32;
231 	}
232 	h = min(h, cx->is_50hz ? 576 : 480);
233 	h = max(h, min_h);
234 
235 	fmt->fmt.pix.width = w;
236 	fmt->fmt.pix.height = h;
237 	return 0;
238 }
239 
240 static int cx18_try_fmt_vbi_cap(struct file *file, void *fh,
241 				struct v4l2_format *fmt)
242 {
243 	return cx18_g_fmt_vbi_cap(file, fh, fmt);
244 }
245 
246 static int cx18_try_fmt_sliced_vbi_cap(struct file *file, void *fh,
247 					struct v4l2_format *fmt)
248 {
249 	struct cx18 *cx = fh2id(fh)->cx;
250 	struct v4l2_sliced_vbi_format *vbifmt = &fmt->fmt.sliced;
251 
252 	vbifmt->io_size = sizeof(struct v4l2_sliced_vbi_data) * 36;
253 	vbifmt->reserved[0] = 0;
254 	vbifmt->reserved[1] = 0;
255 
256 	/* If given a service set, expand it validly & clear passed in set */
257 	if (vbifmt->service_set)
258 		cx18_expand_service_set(vbifmt, cx->is_50hz);
259 	/* Sanitize the service_lines, and compute the new set if any valid */
260 	if (check_service_set(vbifmt, cx->is_50hz))
261 		vbifmt->service_set = cx18_get_service_set(vbifmt);
262 	return 0;
263 }
264 
265 static int cx18_s_fmt_vid_cap(struct file *file, void *fh,
266 				struct v4l2_format *fmt)
267 {
268 	struct cx18_open_id *id = fh2id(fh);
269 	struct cx18 *cx = id->cx;
270 	struct v4l2_subdev_format format = {
271 		.which = V4L2_SUBDEV_FORMAT_ACTIVE,
272 	};
273 	struct cx18_stream *s = &cx->streams[id->type];
274 	int ret;
275 	int w, h;
276 
277 	ret = cx18_try_fmt_vid_cap(file, fh, fmt);
278 	if (ret)
279 		return ret;
280 	w = fmt->fmt.pix.width;
281 	h = fmt->fmt.pix.height;
282 
283 	if (cx->cxhdl.width == w && cx->cxhdl.height == h &&
284 	    s->pixelformat == fmt->fmt.pix.pixelformat)
285 		return 0;
286 
287 	if (atomic_read(&cx->ana_capturing) > 0)
288 		return -EBUSY;
289 
290 	s->pixelformat = fmt->fmt.pix.pixelformat;
291 	/* HM12 YUV size is (Y=(h*720) + UV=(h*(720/2)))
292 	   UYUV YUV size is (Y=(h*720) + UV=(h*(720))) */
293 	if (s->pixelformat == V4L2_PIX_FMT_HM12) {
294 		s->vb_bytes_per_frame = h * 720 * 3 / 2;
295 		s->vb_bytes_per_line = 720; /* First plane */
296 	} else {
297 		s->vb_bytes_per_frame = h * 720 * 2;
298 		s->vb_bytes_per_line = 1440; /* Packed */
299 	}
300 
301 	format.format.width = cx->cxhdl.width = w;
302 	format.format.height = cx->cxhdl.height = h;
303 	format.format.code = MEDIA_BUS_FMT_FIXED;
304 	v4l2_subdev_call(cx->sd_av, pad, set_fmt, NULL, &format);
305 	return cx18_g_fmt_vid_cap(file, fh, fmt);
306 }
307 
308 static int cx18_s_fmt_vbi_cap(struct file *file, void *fh,
309 				struct v4l2_format *fmt)
310 {
311 	struct cx18_open_id *id = fh2id(fh);
312 	struct cx18 *cx = id->cx;
313 	int ret;
314 
315 	/*
316 	 * Changing the Encoder's Raw VBI parameters won't have any effect
317 	 * if any analog capture is ongoing
318 	 */
319 	if (!cx18_raw_vbi(cx) && atomic_read(&cx->ana_capturing) > 0)
320 		return -EBUSY;
321 
322 	/*
323 	 * Set the digitizer registers for raw active VBI.
324 	 * Note cx18_av_vbi_wipes out a lot of the passed in fmt under valid
325 	 * calling conditions
326 	 */
327 	ret = v4l2_subdev_call(cx->sd_av, vbi, s_raw_fmt, &fmt->fmt.vbi);
328 	if (ret)
329 		return ret;
330 
331 	/* Store our new v4l2 (non-)sliced VBI state */
332 	cx->vbi.sliced_in->service_set = 0;
333 	cx->vbi.in.type = V4L2_BUF_TYPE_VBI_CAPTURE;
334 
335 	return cx18_g_fmt_vbi_cap(file, fh, fmt);
336 }
337 
338 static int cx18_s_fmt_sliced_vbi_cap(struct file *file, void *fh,
339 					struct v4l2_format *fmt)
340 {
341 	struct cx18_open_id *id = fh2id(fh);
342 	struct cx18 *cx = id->cx;
343 	int ret;
344 	struct v4l2_sliced_vbi_format *vbifmt = &fmt->fmt.sliced;
345 
346 	cx18_try_fmt_sliced_vbi_cap(file, fh, fmt);
347 
348 	/*
349 	 * Changing the Encoder's Raw VBI parameters won't have any effect
350 	 * if any analog capture is ongoing
351 	 */
352 	if (cx18_raw_vbi(cx) && atomic_read(&cx->ana_capturing) > 0)
353 		return -EBUSY;
354 
355 	/*
356 	 * Set the service_lines requested in the digitizer/slicer registers.
357 	 * Note, cx18_av_vbi() wipes some "impossible" service lines in the
358 	 * passed in fmt->fmt.sliced under valid calling conditions
359 	 */
360 	ret = v4l2_subdev_call(cx->sd_av, vbi, s_sliced_fmt, &fmt->fmt.sliced);
361 	if (ret)
362 		return ret;
363 	/* Store our current v4l2 sliced VBI settings */
364 	cx->vbi.in.type =  V4L2_BUF_TYPE_SLICED_VBI_CAPTURE;
365 	memcpy(cx->vbi.sliced_in, vbifmt, sizeof(*cx->vbi.sliced_in));
366 	return 0;
367 }
368 
369 #ifdef CONFIG_VIDEO_ADV_DEBUG
370 static int cx18_g_register(struct file *file, void *fh,
371 				struct v4l2_dbg_register *reg)
372 {
373 	struct cx18 *cx = fh2id(fh)->cx;
374 
375 	if (reg->reg & 0x3)
376 		return -EINVAL;
377 	if (reg->reg >= CX18_MEM_OFFSET + CX18_MEM_SIZE)
378 		return -EINVAL;
379 	reg->size = 4;
380 	reg->val = cx18_read_enc(cx, reg->reg);
381 	return 0;
382 }
383 
384 static int cx18_s_register(struct file *file, void *fh,
385 				const struct v4l2_dbg_register *reg)
386 {
387 	struct cx18 *cx = fh2id(fh)->cx;
388 
389 	if (reg->reg & 0x3)
390 		return -EINVAL;
391 	if (reg->reg >= CX18_MEM_OFFSET + CX18_MEM_SIZE)
392 		return -EINVAL;
393 	cx18_write_enc(cx, reg->val, reg->reg);
394 	return 0;
395 }
396 #endif
397 
398 static int cx18_querycap(struct file *file, void *fh,
399 				struct v4l2_capability *vcap)
400 {
401 	struct cx18_open_id *id = fh2id(fh);
402 	struct cx18_stream *s = video_drvdata(file);
403 	struct cx18 *cx = id->cx;
404 
405 	strlcpy(vcap->driver, CX18_DRIVER_NAME, sizeof(vcap->driver));
406 	strlcpy(vcap->card, cx->card_name, sizeof(vcap->card));
407 	snprintf(vcap->bus_info, sizeof(vcap->bus_info),
408 		 "PCI:%s", pci_name(cx->pci_dev));
409 	vcap->capabilities = cx->v4l2_cap;	/* capabilities */
410 	vcap->device_caps = s->v4l2_dev_caps;	/* device capabilities */
411 	vcap->capabilities |= V4L2_CAP_DEVICE_CAPS;
412 	return 0;
413 }
414 
415 static int cx18_enumaudio(struct file *file, void *fh, struct v4l2_audio *vin)
416 {
417 	struct cx18 *cx = fh2id(fh)->cx;
418 
419 	return cx18_get_audio_input(cx, vin->index, vin);
420 }
421 
422 static int cx18_g_audio(struct file *file, void *fh, struct v4l2_audio *vin)
423 {
424 	struct cx18 *cx = fh2id(fh)->cx;
425 
426 	vin->index = cx->audio_input;
427 	return cx18_get_audio_input(cx, vin->index, vin);
428 }
429 
430 static int cx18_s_audio(struct file *file, void *fh, const struct v4l2_audio *vout)
431 {
432 	struct cx18 *cx = fh2id(fh)->cx;
433 
434 	if (vout->index >= cx->nof_audio_inputs)
435 		return -EINVAL;
436 	cx->audio_input = vout->index;
437 	cx18_audio_set_io(cx);
438 	return 0;
439 }
440 
441 static int cx18_enum_input(struct file *file, void *fh, struct v4l2_input *vin)
442 {
443 	struct cx18 *cx = fh2id(fh)->cx;
444 
445 	/* set it to defaults from our table */
446 	return cx18_get_input(cx, vin->index, vin);
447 }
448 
449 static int cx18_cropcap(struct file *file, void *fh,
450 			struct v4l2_cropcap *cropcap)
451 {
452 	struct cx18 *cx = fh2id(fh)->cx;
453 
454 	if (cropcap->type != V4L2_BUF_TYPE_VIDEO_CAPTURE)
455 		return -EINVAL;
456 	cropcap->pixelaspect.numerator = cx->is_50hz ? 54 : 11;
457 	cropcap->pixelaspect.denominator = cx->is_50hz ? 59 : 10;
458 	return 0;
459 }
460 
461 static int cx18_g_selection(struct file *file, void *fh,
462 			    struct v4l2_selection *sel)
463 {
464 	struct cx18 *cx = fh2id(fh)->cx;
465 
466 	if (sel->type != V4L2_BUF_TYPE_VIDEO_CAPTURE)
467 		return -EINVAL;
468 	switch (sel->target) {
469 	case V4L2_SEL_TGT_CROP_BOUNDS:
470 	case V4L2_SEL_TGT_CROP_DEFAULT:
471 		sel->r.top = sel->r.left = 0;
472 		sel->r.width = 720;
473 		sel->r.height = cx->is_50hz ? 576 : 480;
474 		break;
475 	default:
476 		return -EINVAL;
477 	}
478 	return 0;
479 }
480 
481 static int cx18_enum_fmt_vid_cap(struct file *file, void *fh,
482 					struct v4l2_fmtdesc *fmt)
483 {
484 	static const struct v4l2_fmtdesc formats[] = {
485 		{ 0, V4L2_BUF_TYPE_VIDEO_CAPTURE, 0,
486 		  "HM12 (YUV 4:1:1)", V4L2_PIX_FMT_HM12, { 0, 0, 0, 0 }
487 		},
488 		{ 1, V4L2_BUF_TYPE_VIDEO_CAPTURE, V4L2_FMT_FLAG_COMPRESSED,
489 		  "MPEG", V4L2_PIX_FMT_MPEG, { 0, 0, 0, 0 }
490 		},
491 		{ 2, V4L2_BUF_TYPE_VIDEO_CAPTURE, 0,
492 		  "UYVY 4:2:2", V4L2_PIX_FMT_UYVY, { 0, 0, 0, 0 }
493 		},
494 	};
495 
496 	if (fmt->index > ARRAY_SIZE(formats) - 1)
497 		return -EINVAL;
498 	*fmt = formats[fmt->index];
499 	return 0;
500 }
501 
502 static int cx18_g_input(struct file *file, void *fh, unsigned int *i)
503 {
504 	struct cx18 *cx = fh2id(fh)->cx;
505 
506 	*i = cx->active_input;
507 	return 0;
508 }
509 
510 int cx18_s_input(struct file *file, void *fh, unsigned int inp)
511 {
512 	struct cx18_open_id *id = fh2id(fh);
513 	struct cx18 *cx = id->cx;
514 	v4l2_std_id std = V4L2_STD_ALL;
515 	const struct cx18_card_video_input *card_input =
516 				cx->card->video_inputs + inp;
517 
518 	if (inp >= cx->nof_inputs)
519 		return -EINVAL;
520 
521 	if (inp == cx->active_input) {
522 		CX18_DEBUG_INFO("Input unchanged\n");
523 		return 0;
524 	}
525 
526 	CX18_DEBUG_INFO("Changing input from %d to %d\n",
527 			cx->active_input, inp);
528 
529 	cx->active_input = inp;
530 	/* Set the audio input to whatever is appropriate for the input type. */
531 	cx->audio_input = cx->card->video_inputs[inp].audio_index;
532 	if (card_input->video_type == V4L2_INPUT_TYPE_TUNER)
533 		std = cx->tuner_std;
534 	cx->streams[CX18_ENC_STREAM_TYPE_MPG].video_dev.tvnorms = std;
535 	cx->streams[CX18_ENC_STREAM_TYPE_YUV].video_dev.tvnorms = std;
536 	cx->streams[CX18_ENC_STREAM_TYPE_VBI].video_dev.tvnorms = std;
537 
538 	/* prevent others from messing with the streams until
539 	   we're finished changing inputs. */
540 	cx18_mute(cx);
541 	cx18_video_set_io(cx);
542 	cx18_audio_set_io(cx);
543 	cx18_unmute(cx);
544 	return 0;
545 }
546 
547 static int cx18_g_frequency(struct file *file, void *fh,
548 				struct v4l2_frequency *vf)
549 {
550 	struct cx18 *cx = fh2id(fh)->cx;
551 
552 	if (vf->tuner != 0)
553 		return -EINVAL;
554 
555 	cx18_call_all(cx, tuner, g_frequency, vf);
556 	return 0;
557 }
558 
559 int cx18_s_frequency(struct file *file, void *fh, const struct v4l2_frequency *vf)
560 {
561 	struct cx18_open_id *id = fh2id(fh);
562 	struct cx18 *cx = id->cx;
563 
564 	if (vf->tuner != 0)
565 		return -EINVAL;
566 
567 	cx18_mute(cx);
568 	CX18_DEBUG_INFO("v4l2 ioctl: set frequency %d\n", vf->frequency);
569 	cx18_call_all(cx, tuner, s_frequency, vf);
570 	cx18_unmute(cx);
571 	return 0;
572 }
573 
574 static int cx18_g_std(struct file *file, void *fh, v4l2_std_id *std)
575 {
576 	struct cx18 *cx = fh2id(fh)->cx;
577 
578 	*std = cx->std;
579 	return 0;
580 }
581 
582 int cx18_s_std(struct file *file, void *fh, v4l2_std_id std)
583 {
584 	struct cx18_open_id *id = fh2id(fh);
585 	struct cx18 *cx = id->cx;
586 
587 	if ((std & V4L2_STD_ALL) == 0)
588 		return -EINVAL;
589 
590 	if (std == cx->std)
591 		return 0;
592 
593 	if (test_bit(CX18_F_I_RADIO_USER, &cx->i_flags) ||
594 	    atomic_read(&cx->ana_capturing) > 0) {
595 		/* Switching standard would turn off the radio or mess
596 		   with already running streams, prevent that by
597 		   returning EBUSY. */
598 		return -EBUSY;
599 	}
600 
601 	cx->std = std;
602 	cx->is_60hz = (std & V4L2_STD_525_60) ? 1 : 0;
603 	cx->is_50hz = !cx->is_60hz;
604 	cx2341x_handler_set_50hz(&cx->cxhdl, cx->is_50hz);
605 	cx->cxhdl.width = 720;
606 	cx->cxhdl.height = cx->is_50hz ? 576 : 480;
607 	cx->vbi.count = cx->is_50hz ? 18 : 12;
608 	cx->vbi.start[0] = cx->is_50hz ? 6 : 10;
609 	cx->vbi.start[1] = cx->is_50hz ? 318 : 273;
610 	CX18_DEBUG_INFO("Switching standard to %llx.\n",
611 			(unsigned long long) cx->std);
612 
613 	/* Tuner */
614 	cx18_call_all(cx, video, s_std, cx->std);
615 	return 0;
616 }
617 
618 static int cx18_s_tuner(struct file *file, void *fh, const struct v4l2_tuner *vt)
619 {
620 	struct cx18_open_id *id = fh2id(fh);
621 	struct cx18 *cx = id->cx;
622 
623 	if (vt->index != 0)
624 		return -EINVAL;
625 
626 	cx18_call_all(cx, tuner, s_tuner, vt);
627 	return 0;
628 }
629 
630 static int cx18_g_tuner(struct file *file, void *fh, struct v4l2_tuner *vt)
631 {
632 	struct cx18 *cx = fh2id(fh)->cx;
633 
634 	if (vt->index != 0)
635 		return -EINVAL;
636 
637 	cx18_call_all(cx, tuner, g_tuner, vt);
638 
639 	if (vt->type == V4L2_TUNER_RADIO)
640 		strlcpy(vt->name, "cx18 Radio Tuner", sizeof(vt->name));
641 	else
642 		strlcpy(vt->name, "cx18 TV Tuner", sizeof(vt->name));
643 	return 0;
644 }
645 
646 static int cx18_g_sliced_vbi_cap(struct file *file, void *fh,
647 					struct v4l2_sliced_vbi_cap *cap)
648 {
649 	struct cx18 *cx = fh2id(fh)->cx;
650 	int set = cx->is_50hz ? V4L2_SLICED_VBI_625 : V4L2_SLICED_VBI_525;
651 	int f, l;
652 
653 	if (cap->type != V4L2_BUF_TYPE_SLICED_VBI_CAPTURE)
654 		return -EINVAL;
655 
656 	cap->service_set = 0;
657 	for (f = 0; f < 2; f++) {
658 		for (l = 0; l < 24; l++) {
659 			if (valid_service_line(f, l, cx->is_50hz)) {
660 				/*
661 				 * We can find all v4l2 supported vbi services
662 				 * for the standard, on a valid line for the std
663 				 */
664 				cap->service_lines[f][l] = set;
665 				cap->service_set |= set;
666 			} else
667 				cap->service_lines[f][l] = 0;
668 		}
669 	}
670 	for (f = 0; f < 3; f++)
671 		cap->reserved[f] = 0;
672 	return 0;
673 }
674 
675 static int _cx18_process_idx_data(struct cx18_buffer *buf,
676 				  struct v4l2_enc_idx *idx)
677 {
678 	int consumed, remaining;
679 	struct v4l2_enc_idx_entry *e_idx;
680 	struct cx18_enc_idx_entry *e_buf;
681 
682 	/* Frame type lookup: 1=I, 2=P, 4=B */
683 	const int mapping[8] = {
684 		-1, V4L2_ENC_IDX_FRAME_I, V4L2_ENC_IDX_FRAME_P,
685 		-1, V4L2_ENC_IDX_FRAME_B, -1, -1, -1
686 	};
687 
688 	/*
689 	 * Assumption here is that a buf holds an integral number of
690 	 * struct cx18_enc_idx_entry objects and is properly aligned.
691 	 * This is enforced by the module options on IDX buffer sizes.
692 	 */
693 	remaining = buf->bytesused - buf->readpos;
694 	consumed = 0;
695 	e_idx = &idx->entry[idx->entries];
696 	e_buf = (struct cx18_enc_idx_entry *) &buf->buf[buf->readpos];
697 
698 	while (remaining >= sizeof(struct cx18_enc_idx_entry) &&
699 	       idx->entries < V4L2_ENC_IDX_ENTRIES) {
700 
701 		e_idx->offset = (((u64) le32_to_cpu(e_buf->offset_high)) << 32)
702 				| le32_to_cpu(e_buf->offset_low);
703 
704 		e_idx->pts = (((u64) (le32_to_cpu(e_buf->pts_high) & 1)) << 32)
705 			     | le32_to_cpu(e_buf->pts_low);
706 
707 		e_idx->length = le32_to_cpu(e_buf->length);
708 
709 		e_idx->flags = mapping[le32_to_cpu(e_buf->flags) & 0x7];
710 
711 		e_idx->reserved[0] = 0;
712 		e_idx->reserved[1] = 0;
713 
714 		idx->entries++;
715 		e_idx = &idx->entry[idx->entries];
716 		e_buf++;
717 
718 		remaining -= sizeof(struct cx18_enc_idx_entry);
719 		consumed += sizeof(struct cx18_enc_idx_entry);
720 	}
721 
722 	/* Swallow any partial entries at the end, if there are any */
723 	if (remaining > 0 && remaining < sizeof(struct cx18_enc_idx_entry))
724 		consumed += remaining;
725 
726 	buf->readpos += consumed;
727 	return consumed;
728 }
729 
730 static int cx18_process_idx_data(struct cx18_stream *s, struct cx18_mdl *mdl,
731 				 struct v4l2_enc_idx *idx)
732 {
733 	if (s->type != CX18_ENC_STREAM_TYPE_IDX)
734 		return -EINVAL;
735 
736 	if (mdl->curr_buf == NULL)
737 		mdl->curr_buf = list_first_entry(&mdl->buf_list,
738 						 struct cx18_buffer, list);
739 
740 	if (list_entry_is_past_end(mdl->curr_buf, &mdl->buf_list, list)) {
741 		/*
742 		 * For some reason we've exhausted the buffers, but the MDL
743 		 * object still said some data was unread.
744 		 * Fix that and bail out.
745 		 */
746 		mdl->readpos = mdl->bytesused;
747 		return 0;
748 	}
749 
750 	list_for_each_entry_from(mdl->curr_buf, &mdl->buf_list, list) {
751 
752 		/* Skip any empty buffers in the MDL */
753 		if (mdl->curr_buf->readpos >= mdl->curr_buf->bytesused)
754 			continue;
755 
756 		mdl->readpos += _cx18_process_idx_data(mdl->curr_buf, idx);
757 
758 		/* exit when MDL drained or request satisfied */
759 		if (idx->entries >= V4L2_ENC_IDX_ENTRIES ||
760 		    mdl->curr_buf->readpos < mdl->curr_buf->bytesused ||
761 		    mdl->readpos >= mdl->bytesused)
762 			break;
763 	}
764 	return 0;
765 }
766 
767 static int cx18_g_enc_index(struct file *file, void *fh,
768 				struct v4l2_enc_idx *idx)
769 {
770 	struct cx18 *cx = fh2id(fh)->cx;
771 	struct cx18_stream *s = &cx->streams[CX18_ENC_STREAM_TYPE_IDX];
772 	s32 tmp;
773 	struct cx18_mdl *mdl;
774 
775 	if (!cx18_stream_enabled(s)) /* Module options inhibited IDX stream */
776 		return -EINVAL;
777 
778 	/* Compute the best case number of entries we can buffer */
779 	tmp = s->buffers -
780 			  s->bufs_per_mdl * CX18_ENC_STREAM_TYPE_IDX_FW_MDL_MIN;
781 	if (tmp <= 0)
782 		tmp = 1;
783 	tmp = tmp * s->buf_size / sizeof(struct cx18_enc_idx_entry);
784 
785 	/* Fill out the header of the return structure */
786 	idx->entries = 0;
787 	idx->entries_cap = tmp;
788 	memset(idx->reserved, 0, sizeof(idx->reserved));
789 
790 	/* Pull IDX MDLs and buffers from q_full and populate the entries */
791 	do {
792 		mdl = cx18_dequeue(s, &s->q_full);
793 		if (mdl == NULL) /* No more IDX data right now */
794 			break;
795 
796 		/* Extract the Index entry data from the MDL and buffers */
797 		cx18_process_idx_data(s, mdl, idx);
798 		if (mdl->readpos < mdl->bytesused) {
799 			/* We finished with data remaining, push the MDL back */
800 			cx18_push(s, mdl, &s->q_full);
801 			break;
802 		}
803 
804 		/* We drained this MDL, schedule it to go to the firmware */
805 		cx18_enqueue(s, mdl, &s->q_free);
806 
807 	} while (idx->entries < V4L2_ENC_IDX_ENTRIES);
808 
809 	/* Tell the work handler to send free IDX MDLs to the firmware */
810 	cx18_stream_load_fw_queue(s);
811 	return 0;
812 }
813 
814 static struct videobuf_queue *cx18_vb_queue(struct cx18_open_id *id)
815 {
816 	struct videobuf_queue *q = NULL;
817 	struct cx18 *cx = id->cx;
818 	struct cx18_stream *s = &cx->streams[id->type];
819 
820 	switch (s->vb_type) {
821 	case V4L2_BUF_TYPE_VIDEO_CAPTURE:
822 		q = &s->vbuf_q;
823 		break;
824 	case V4L2_BUF_TYPE_VBI_CAPTURE:
825 		break;
826 	default:
827 		break;
828 	}
829 	return q;
830 }
831 
832 static int cx18_streamon(struct file *file, void *priv,
833 	enum v4l2_buf_type type)
834 {
835 	struct cx18_open_id *id = file->private_data;
836 	struct cx18 *cx = id->cx;
837 	struct cx18_stream *s = &cx->streams[id->type];
838 
839 	/* Start the hardware only if we're the video device */
840 	if ((s->vb_type != V4L2_BUF_TYPE_VIDEO_CAPTURE) &&
841 		(s->vb_type != V4L2_BUF_TYPE_VBI_CAPTURE))
842 		return -EINVAL;
843 
844 	if (id->type != CX18_ENC_STREAM_TYPE_YUV)
845 		return -EINVAL;
846 
847 	/* Establish a buffer timeout */
848 	mod_timer(&s->vb_timeout, msecs_to_jiffies(2000) + jiffies);
849 
850 	return videobuf_streamon(cx18_vb_queue(id));
851 }
852 
853 static int cx18_streamoff(struct file *file, void *priv,
854 	enum v4l2_buf_type type)
855 {
856 	struct cx18_open_id *id = file->private_data;
857 	struct cx18 *cx = id->cx;
858 	struct cx18_stream *s = &cx->streams[id->type];
859 
860 	/* Start the hardware only if we're the video device */
861 	if ((s->vb_type != V4L2_BUF_TYPE_VIDEO_CAPTURE) &&
862 		(s->vb_type != V4L2_BUF_TYPE_VBI_CAPTURE))
863 		return -EINVAL;
864 
865 	if (id->type != CX18_ENC_STREAM_TYPE_YUV)
866 		return -EINVAL;
867 
868 	return videobuf_streamoff(cx18_vb_queue(id));
869 }
870 
871 static int cx18_reqbufs(struct file *file, void *priv,
872 	struct v4l2_requestbuffers *rb)
873 {
874 	struct cx18_open_id *id = file->private_data;
875 	struct cx18 *cx = id->cx;
876 	struct cx18_stream *s = &cx->streams[id->type];
877 
878 	if ((s->vb_type != V4L2_BUF_TYPE_VIDEO_CAPTURE) &&
879 		(s->vb_type != V4L2_BUF_TYPE_VBI_CAPTURE))
880 		return -EINVAL;
881 
882 	return videobuf_reqbufs(cx18_vb_queue(id), rb);
883 }
884 
885 static int cx18_querybuf(struct file *file, void *priv,
886 	struct v4l2_buffer *b)
887 {
888 	struct cx18_open_id *id = file->private_data;
889 	struct cx18 *cx = id->cx;
890 	struct cx18_stream *s = &cx->streams[id->type];
891 
892 	if ((s->vb_type != V4L2_BUF_TYPE_VIDEO_CAPTURE) &&
893 		(s->vb_type != V4L2_BUF_TYPE_VBI_CAPTURE))
894 		return -EINVAL;
895 
896 	return videobuf_querybuf(cx18_vb_queue(id), b);
897 }
898 
899 static int cx18_qbuf(struct file *file, void *priv, struct v4l2_buffer *b)
900 {
901 	struct cx18_open_id *id = file->private_data;
902 	struct cx18 *cx = id->cx;
903 	struct cx18_stream *s = &cx->streams[id->type];
904 
905 	if ((s->vb_type != V4L2_BUF_TYPE_VIDEO_CAPTURE) &&
906 		(s->vb_type != V4L2_BUF_TYPE_VBI_CAPTURE))
907 		return -EINVAL;
908 
909 	return videobuf_qbuf(cx18_vb_queue(id), b);
910 }
911 
912 static int cx18_dqbuf(struct file *file, void *priv, struct v4l2_buffer *b)
913 {
914 	struct cx18_open_id *id = file->private_data;
915 	struct cx18 *cx = id->cx;
916 	struct cx18_stream *s = &cx->streams[id->type];
917 
918 	if ((s->vb_type != V4L2_BUF_TYPE_VIDEO_CAPTURE) &&
919 		(s->vb_type != V4L2_BUF_TYPE_VBI_CAPTURE))
920 		return -EINVAL;
921 
922 	return videobuf_dqbuf(cx18_vb_queue(id), b, file->f_flags & O_NONBLOCK);
923 }
924 
925 static int cx18_encoder_cmd(struct file *file, void *fh,
926 				struct v4l2_encoder_cmd *enc)
927 {
928 	struct cx18_open_id *id = fh2id(fh);
929 	struct cx18 *cx = id->cx;
930 	u32 h;
931 
932 	switch (enc->cmd) {
933 	case V4L2_ENC_CMD_START:
934 		CX18_DEBUG_IOCTL("V4L2_ENC_CMD_START\n");
935 		enc->flags = 0;
936 		return cx18_start_capture(id);
937 
938 	case V4L2_ENC_CMD_STOP:
939 		CX18_DEBUG_IOCTL("V4L2_ENC_CMD_STOP\n");
940 		enc->flags &= V4L2_ENC_CMD_STOP_AT_GOP_END;
941 		cx18_stop_capture(id,
942 				  enc->flags & V4L2_ENC_CMD_STOP_AT_GOP_END);
943 		break;
944 
945 	case V4L2_ENC_CMD_PAUSE:
946 		CX18_DEBUG_IOCTL("V4L2_ENC_CMD_PAUSE\n");
947 		enc->flags = 0;
948 		if (!atomic_read(&cx->ana_capturing))
949 			return -EPERM;
950 		if (test_and_set_bit(CX18_F_I_ENC_PAUSED, &cx->i_flags))
951 			return 0;
952 		h = cx18_find_handle(cx);
953 		if (h == CX18_INVALID_TASK_HANDLE) {
954 			CX18_ERR("Can't find valid task handle for "
955 				 "V4L2_ENC_CMD_PAUSE\n");
956 			return -EBADFD;
957 		}
958 		cx18_mute(cx);
959 		cx18_vapi(cx, CX18_CPU_CAPTURE_PAUSE, 1, h);
960 		break;
961 
962 	case V4L2_ENC_CMD_RESUME:
963 		CX18_DEBUG_IOCTL("V4L2_ENC_CMD_RESUME\n");
964 		enc->flags = 0;
965 		if (!atomic_read(&cx->ana_capturing))
966 			return -EPERM;
967 		if (!test_and_clear_bit(CX18_F_I_ENC_PAUSED, &cx->i_flags))
968 			return 0;
969 		h = cx18_find_handle(cx);
970 		if (h == CX18_INVALID_TASK_HANDLE) {
971 			CX18_ERR("Can't find valid task handle for "
972 				 "V4L2_ENC_CMD_RESUME\n");
973 			return -EBADFD;
974 		}
975 		cx18_vapi(cx, CX18_CPU_CAPTURE_RESUME, 1, h);
976 		cx18_unmute(cx);
977 		break;
978 
979 	default:
980 		CX18_DEBUG_IOCTL("Unknown cmd %d\n", enc->cmd);
981 		return -EINVAL;
982 	}
983 	return 0;
984 }
985 
986 static int cx18_try_encoder_cmd(struct file *file, void *fh,
987 				struct v4l2_encoder_cmd *enc)
988 {
989 	struct cx18 *cx = fh2id(fh)->cx;
990 
991 	switch (enc->cmd) {
992 	case V4L2_ENC_CMD_START:
993 		CX18_DEBUG_IOCTL("V4L2_ENC_CMD_START\n");
994 		enc->flags = 0;
995 		break;
996 
997 	case V4L2_ENC_CMD_STOP:
998 		CX18_DEBUG_IOCTL("V4L2_ENC_CMD_STOP\n");
999 		enc->flags &= V4L2_ENC_CMD_STOP_AT_GOP_END;
1000 		break;
1001 
1002 	case V4L2_ENC_CMD_PAUSE:
1003 		CX18_DEBUG_IOCTL("V4L2_ENC_CMD_PAUSE\n");
1004 		enc->flags = 0;
1005 		break;
1006 
1007 	case V4L2_ENC_CMD_RESUME:
1008 		CX18_DEBUG_IOCTL("V4L2_ENC_CMD_RESUME\n");
1009 		enc->flags = 0;
1010 		break;
1011 
1012 	default:
1013 		CX18_DEBUG_IOCTL("Unknown cmd %d\n", enc->cmd);
1014 		return -EINVAL;
1015 	}
1016 	return 0;
1017 }
1018 
1019 static int cx18_log_status(struct file *file, void *fh)
1020 {
1021 	struct cx18 *cx = fh2id(fh)->cx;
1022 	struct v4l2_input vidin;
1023 	struct v4l2_audio audin;
1024 	int i;
1025 
1026 	CX18_INFO("Version: %s  Card: %s\n", CX18_VERSION, cx->card_name);
1027 	if (cx->hw_flags & CX18_HW_TVEEPROM) {
1028 		struct tveeprom tv;
1029 
1030 		cx18_read_eeprom(cx, &tv);
1031 	}
1032 	cx18_call_all(cx, core, log_status);
1033 	cx18_get_input(cx, cx->active_input, &vidin);
1034 	cx18_get_audio_input(cx, cx->audio_input, &audin);
1035 	CX18_INFO("Video Input: %s\n", vidin.name);
1036 	CX18_INFO("Audio Input: %s\n", audin.name);
1037 	mutex_lock(&cx->gpio_lock);
1038 	CX18_INFO("GPIO:  direction 0x%08x, value 0x%08x\n",
1039 		cx->gpio_dir, cx->gpio_val);
1040 	mutex_unlock(&cx->gpio_lock);
1041 	CX18_INFO("Tuner: %s\n",
1042 		test_bit(CX18_F_I_RADIO_USER, &cx->i_flags) ?  "Radio" : "TV");
1043 	v4l2_ctrl_handler_log_status(&cx->cxhdl.hdl, cx->v4l2_dev.name);
1044 	CX18_INFO("Status flags: 0x%08lx\n", cx->i_flags);
1045 	for (i = 0; i < CX18_MAX_STREAMS; i++) {
1046 		struct cx18_stream *s = &cx->streams[i];
1047 
1048 		if (s->video_dev.v4l2_dev == NULL || s->buffers == 0)
1049 			continue;
1050 		CX18_INFO("Stream %s: status 0x%04lx, %d%% of %d KiB (%d buffers) in use\n",
1051 			  s->name, s->s_flags,
1052 			  atomic_read(&s->q_full.depth) * s->bufs_per_mdl * 100
1053 			   / s->buffers,
1054 			  (s->buffers * s->buf_size) / 1024, s->buffers);
1055 	}
1056 	CX18_INFO("Read MPEG/VBI: %lld/%lld bytes\n",
1057 			(long long)cx->mpg_data_received,
1058 			(long long)cx->vbi_data_inserted);
1059 	return 0;
1060 }
1061 
1062 static long cx18_default(struct file *file, void *fh, bool valid_prio,
1063 			 unsigned int cmd, void *arg)
1064 {
1065 	struct cx18 *cx = fh2id(fh)->cx;
1066 
1067 	switch (cmd) {
1068 	case VIDIOC_INT_RESET: {
1069 		u32 val = *(u32 *)arg;
1070 
1071 		if ((val == 0) || (val & 0x01))
1072 			cx18_call_hw(cx, CX18_HW_GPIO_RESET_CTRL, core, reset,
1073 				     (u32) CX18_GPIO_RESET_Z8F0811);
1074 		break;
1075 	}
1076 
1077 	default:
1078 		return -ENOTTY;
1079 	}
1080 	return 0;
1081 }
1082 
1083 static const struct v4l2_ioctl_ops cx18_ioctl_ops = {
1084 	.vidioc_querycap                = cx18_querycap,
1085 	.vidioc_s_audio                 = cx18_s_audio,
1086 	.vidioc_g_audio                 = cx18_g_audio,
1087 	.vidioc_enumaudio               = cx18_enumaudio,
1088 	.vidioc_enum_input              = cx18_enum_input,
1089 	.vidioc_cropcap                 = cx18_cropcap,
1090 	.vidioc_g_selection             = cx18_g_selection,
1091 	.vidioc_g_input                 = cx18_g_input,
1092 	.vidioc_s_input                 = cx18_s_input,
1093 	.vidioc_g_frequency             = cx18_g_frequency,
1094 	.vidioc_s_frequency             = cx18_s_frequency,
1095 	.vidioc_s_tuner                 = cx18_s_tuner,
1096 	.vidioc_g_tuner                 = cx18_g_tuner,
1097 	.vidioc_g_enc_index             = cx18_g_enc_index,
1098 	.vidioc_g_std                   = cx18_g_std,
1099 	.vidioc_s_std                   = cx18_s_std,
1100 	.vidioc_log_status              = cx18_log_status,
1101 	.vidioc_enum_fmt_vid_cap        = cx18_enum_fmt_vid_cap,
1102 	.vidioc_encoder_cmd             = cx18_encoder_cmd,
1103 	.vidioc_try_encoder_cmd         = cx18_try_encoder_cmd,
1104 	.vidioc_g_fmt_vid_cap           = cx18_g_fmt_vid_cap,
1105 	.vidioc_g_fmt_vbi_cap           = cx18_g_fmt_vbi_cap,
1106 	.vidioc_g_fmt_sliced_vbi_cap    = cx18_g_fmt_sliced_vbi_cap,
1107 	.vidioc_s_fmt_vid_cap           = cx18_s_fmt_vid_cap,
1108 	.vidioc_s_fmt_vbi_cap           = cx18_s_fmt_vbi_cap,
1109 	.vidioc_s_fmt_sliced_vbi_cap    = cx18_s_fmt_sliced_vbi_cap,
1110 	.vidioc_try_fmt_vid_cap         = cx18_try_fmt_vid_cap,
1111 	.vidioc_try_fmt_vbi_cap         = cx18_try_fmt_vbi_cap,
1112 	.vidioc_try_fmt_sliced_vbi_cap  = cx18_try_fmt_sliced_vbi_cap,
1113 	.vidioc_g_sliced_vbi_cap        = cx18_g_sliced_vbi_cap,
1114 #ifdef CONFIG_VIDEO_ADV_DEBUG
1115 	.vidioc_g_register              = cx18_g_register,
1116 	.vidioc_s_register              = cx18_s_register,
1117 #endif
1118 	.vidioc_default                 = cx18_default,
1119 	.vidioc_streamon                = cx18_streamon,
1120 	.vidioc_streamoff               = cx18_streamoff,
1121 	.vidioc_reqbufs                 = cx18_reqbufs,
1122 	.vidioc_querybuf                = cx18_querybuf,
1123 	.vidioc_qbuf                    = cx18_qbuf,
1124 	.vidioc_dqbuf                   = cx18_dqbuf,
1125 	.vidioc_subscribe_event		= v4l2_ctrl_subscribe_event,
1126 	.vidioc_unsubscribe_event	= v4l2_event_unsubscribe,
1127 };
1128 
1129 void cx18_set_funcs(struct video_device *vdev)
1130 {
1131 	vdev->ioctl_ops = &cx18_ioctl_ops;
1132 }
1133