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