1 // SPDX-License-Identifier: GPL-2.0-or-later
2 /*
3  *  cx18 init/start/stop/exit stream functions
4  *
5  *  Derived from ivtv-streams.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-fileops.h"
14 #include "cx18-mailbox.h"
15 #include "cx18-i2c.h"
16 #include "cx18-queue.h"
17 #include "cx18-ioctl.h"
18 #include "cx18-streams.h"
19 #include "cx18-cards.h"
20 #include "cx18-scb.h"
21 #include "cx18-dvb.h"
22 
23 #define CX18_DSP0_INTERRUPT_MASK	0xd0004C
24 
25 static const struct v4l2_file_operations cx18_v4l2_enc_fops = {
26 	.owner = THIS_MODULE,
27 	.read = cx18_v4l2_read,
28 	.open = cx18_v4l2_open,
29 	.unlocked_ioctl = video_ioctl2,
30 	.release = cx18_v4l2_close,
31 	.poll = cx18_v4l2_enc_poll,
32 };
33 
34 static const struct v4l2_file_operations cx18_v4l2_enc_yuv_fops = {
35 	.owner = THIS_MODULE,
36 	.open = cx18_v4l2_open,
37 	.unlocked_ioctl = video_ioctl2,
38 	.release = cx18_v4l2_close,
39 	.poll = vb2_fop_poll,
40 	.read = vb2_fop_read,
41 	.mmap = vb2_fop_mmap,
42 };
43 
44 /* offset from 0 to register ts v4l2 minors on */
45 #define CX18_V4L2_ENC_TS_OFFSET   16
46 /* offset from 0 to register pcm v4l2 minors on */
47 #define CX18_V4L2_ENC_PCM_OFFSET  24
48 /* offset from 0 to register yuv v4l2 minors on */
49 #define CX18_V4L2_ENC_YUV_OFFSET  32
50 
51 static struct {
52 	const char *name;
53 	int vfl_type;
54 	int num_offset;
55 	int dma;
56 	u32 caps;
57 } cx18_stream_info[] = {
58 	{	/* CX18_ENC_STREAM_TYPE_MPG */
59 		"encoder MPEG",
60 		VFL_TYPE_VIDEO, 0,
61 		DMA_FROM_DEVICE,
62 		V4L2_CAP_VIDEO_CAPTURE | V4L2_CAP_READWRITE |
63 		V4L2_CAP_AUDIO | V4L2_CAP_TUNER
64 	},
65 	{	/* CX18_ENC_STREAM_TYPE_TS */
66 		"TS",
67 		VFL_TYPE_VIDEO, -1,
68 		DMA_FROM_DEVICE,
69 	},
70 	{	/* CX18_ENC_STREAM_TYPE_YUV */
71 		"encoder YUV",
72 		VFL_TYPE_VIDEO, CX18_V4L2_ENC_YUV_OFFSET,
73 		DMA_FROM_DEVICE,
74 		V4L2_CAP_VIDEO_CAPTURE | V4L2_CAP_READWRITE |
75 		V4L2_CAP_STREAMING | V4L2_CAP_AUDIO | V4L2_CAP_TUNER
76 	},
77 	{	/* CX18_ENC_STREAM_TYPE_VBI */
78 		"encoder VBI",
79 		VFL_TYPE_VBI, 0,
80 		DMA_FROM_DEVICE,
81 		V4L2_CAP_VBI_CAPTURE | V4L2_CAP_SLICED_VBI_CAPTURE |
82 		V4L2_CAP_READWRITE | V4L2_CAP_AUDIO | V4L2_CAP_TUNER
83 	},
84 	{	/* CX18_ENC_STREAM_TYPE_PCM */
85 		"encoder PCM audio",
86 		VFL_TYPE_VIDEO, CX18_V4L2_ENC_PCM_OFFSET,
87 		DMA_FROM_DEVICE,
88 		V4L2_CAP_TUNER | V4L2_CAP_AUDIO | V4L2_CAP_READWRITE,
89 	},
90 	{	/* CX18_ENC_STREAM_TYPE_IDX */
91 		"encoder IDX",
92 		VFL_TYPE_VIDEO, -1,
93 		DMA_FROM_DEVICE,
94 	},
95 	{	/* CX18_ENC_STREAM_TYPE_RAD */
96 		"encoder radio",
97 		VFL_TYPE_RADIO, 0,
98 		DMA_NONE,
99 		V4L2_CAP_RADIO | V4L2_CAP_TUNER
100 	},
101 };
102 
103 static int cx18_queue_setup(struct vb2_queue *vq,
104 			    unsigned int *nbuffers, unsigned int *nplanes,
105 			    unsigned int sizes[], struct device *alloc_devs[])
106 {
107 	struct cx18_stream *s = vb2_get_drv_priv(vq);
108 	struct cx18 *cx = s->cx;
109 	unsigned int szimage;
110 
111 	/*
112 	 * HM12 YUV size is (Y=(h*720) + UV=(h*(720/2)))
113 	 * UYUV YUV size is (Y=(h*720) + UV=(h*(720)))
114 	 */
115 	if (s->pixelformat == V4L2_PIX_FMT_NV12_16L16)
116 		szimage = cx->cxhdl.height * 720 * 3 / 2;
117 	else
118 		szimage = cx->cxhdl.height * 720 * 2;
119 
120 	/*
121 	 * Let's request at least three buffers: two for the
122 	 * DMA engine and one for userspace.
123 	 */
124 	if (vq->num_buffers + *nbuffers < 3)
125 		*nbuffers = 3 - vq->num_buffers;
126 
127 	if (*nplanes) {
128 		if (*nplanes != 1 || sizes[0] < szimage)
129 			return -EINVAL;
130 		return 0;
131 	}
132 
133 	sizes[0] = szimage;
134 	*nplanes = 1;
135 	return 0;
136 }
137 
138 static void cx18_buf_queue(struct vb2_buffer *vb)
139 {
140 	struct cx18_stream *s = vb2_get_drv_priv(vb->vb2_queue);
141 	struct vb2_v4l2_buffer *vbuf = to_vb2_v4l2_buffer(vb);
142 	struct cx18_vb2_buffer *buf =
143 		container_of(vbuf, struct cx18_vb2_buffer, vb);
144 	unsigned long flags;
145 
146 	spin_lock_irqsave(&s->vb_lock, flags);
147 	list_add_tail(&buf->list, &s->vb_capture);
148 	spin_unlock_irqrestore(&s->vb_lock, flags);
149 }
150 
151 static int cx18_buf_prepare(struct vb2_buffer *vb)
152 {
153 	struct vb2_v4l2_buffer *vbuf = to_vb2_v4l2_buffer(vb);
154 	struct cx18_stream *s = vb2_get_drv_priv(vb->vb2_queue);
155 	struct cx18 *cx = s->cx;
156 	unsigned int size;
157 
158 	/*
159 	 * HM12 YUV size is (Y=(h*720) + UV=(h*(720/2)))
160 	 * UYUV YUV size is (Y=(h*720) + UV=(h*(720)))
161 	 */
162 	if (s->pixelformat == V4L2_PIX_FMT_NV12_16L16)
163 		size = cx->cxhdl.height * 720 * 3 / 2;
164 	else
165 		size = cx->cxhdl.height * 720 * 2;
166 
167 	if (vb2_plane_size(vb, 0) < size)
168 		return -EINVAL;
169 	vb2_set_plane_payload(vb, 0, size);
170 	vbuf->field = V4L2_FIELD_INTERLACED;
171 	return 0;
172 }
173 
174 void cx18_clear_queue(struct cx18_stream *s, enum vb2_buffer_state state)
175 {
176 	while (!list_empty(&s->vb_capture)) {
177 		struct cx18_vb2_buffer *buf;
178 
179 		buf = list_first_entry(&s->vb_capture,
180 				       struct cx18_vb2_buffer, list);
181 		list_del(&buf->list);
182 		vb2_buffer_done(&buf->vb.vb2_buf, state);
183 	}
184 }
185 
186 static int cx18_start_streaming(struct vb2_queue *vq, unsigned int count)
187 {
188 	struct v4l2_fh *owner = vq->owner;
189 	struct cx18_stream *s = vb2_get_drv_priv(vq);
190 	unsigned long flags;
191 	int rc;
192 
193 	if (WARN_ON(!owner)) {
194 		rc = -EIO;
195 		goto clear_queue;
196 	}
197 
198 	s->sequence = 0;
199 	rc = cx18_start_capture(fh2id(owner));
200 	if (!rc) {
201 		/* Establish a buffer timeout */
202 		mod_timer(&s->vb_timeout, msecs_to_jiffies(2000) + jiffies);
203 		return 0;
204 	}
205 
206 clear_queue:
207 	spin_lock_irqsave(&s->vb_lock, flags);
208 	cx18_clear_queue(s, VB2_BUF_STATE_QUEUED);
209 	spin_unlock_irqrestore(&s->vb_lock, flags);
210 	return rc;
211 }
212 
213 static void cx18_stop_streaming(struct vb2_queue *vq)
214 {
215 	struct cx18_stream *s = vb2_get_drv_priv(vq);
216 	unsigned long flags;
217 
218 	cx18_stop_capture(s, 0);
219 	timer_delete_sync(&s->vb_timeout);
220 	spin_lock_irqsave(&s->vb_lock, flags);
221 	cx18_clear_queue(s, VB2_BUF_STATE_ERROR);
222 	spin_unlock_irqrestore(&s->vb_lock, flags);
223 }
224 
225 static const struct vb2_ops cx18_vb2_qops = {
226 	.queue_setup		= cx18_queue_setup,
227 	.buf_queue		= cx18_buf_queue,
228 	.buf_prepare		= cx18_buf_prepare,
229 	.start_streaming	= cx18_start_streaming,
230 	.stop_streaming		= cx18_stop_streaming,
231 	.wait_prepare		= vb2_ops_wait_prepare,
232 	.wait_finish		= vb2_ops_wait_finish,
233 };
234 
235 static int cx18_stream_init(struct cx18 *cx, int type)
236 {
237 	struct cx18_stream *s = &cx->streams[type];
238 	int err = 0;
239 
240 	memset(s, 0, sizeof(*s));
241 
242 	/* initialize cx18_stream fields */
243 	s->dvb = NULL;
244 	s->cx = cx;
245 	s->type = type;
246 	s->name = cx18_stream_info[type].name;
247 	s->handle = CX18_INVALID_TASK_HANDLE;
248 
249 	s->dma = cx18_stream_info[type].dma;
250 	s->v4l2_dev_caps = cx18_stream_info[type].caps;
251 	s->buffers = cx->stream_buffers[type];
252 	s->buf_size = cx->stream_buf_size[type];
253 	INIT_LIST_HEAD(&s->buf_pool);
254 	s->bufs_per_mdl = 1;
255 	s->mdl_size = s->buf_size * s->bufs_per_mdl;
256 
257 	init_waitqueue_head(&s->waitq);
258 	s->id = -1;
259 	spin_lock_init(&s->q_free.lock);
260 	cx18_queue_init(&s->q_free);
261 	spin_lock_init(&s->q_busy.lock);
262 	cx18_queue_init(&s->q_busy);
263 	spin_lock_init(&s->q_full.lock);
264 	cx18_queue_init(&s->q_full);
265 	spin_lock_init(&s->q_idle.lock);
266 	cx18_queue_init(&s->q_idle);
267 
268 	INIT_WORK(&s->out_work_order, cx18_out_work_handler);
269 
270 	INIT_LIST_HEAD(&s->vb_capture);
271 	timer_setup(&s->vb_timeout, cx18_vb_timeout, 0);
272 	spin_lock_init(&s->vb_lock);
273 
274 	if (type == CX18_ENC_STREAM_TYPE_YUV) {
275 		s->vb_type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
276 
277 		/* Assume the previous pixel default */
278 		s->pixelformat = V4L2_PIX_FMT_NV12_16L16;
279 		s->vb_bytes_per_frame = cx->cxhdl.height * 720 * 3 / 2;
280 		s->vb_bytes_per_line = 720;
281 
282 		s->vidq.io_modes = VB2_READ | VB2_MMAP | VB2_DMABUF;
283 		s->vidq.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
284 		s->vidq.drv_priv = s;
285 		s->vidq.buf_struct_size = sizeof(struct cx18_vb2_buffer);
286 		s->vidq.ops = &cx18_vb2_qops;
287 		s->vidq.mem_ops = &vb2_vmalloc_memops;
288 		s->vidq.timestamp_flags = V4L2_BUF_FLAG_TIMESTAMP_MONOTONIC;
289 		s->vidq.min_buffers_needed = 2;
290 		s->vidq.gfp_flags = GFP_DMA32;
291 		s->vidq.dev = &cx->pci_dev->dev;
292 		s->vidq.lock = &cx->serialize_lock;
293 
294 		err = vb2_queue_init(&s->vidq);
295 		if (err)
296 			v4l2_err(&cx->v4l2_dev, "cannot init vb2 queue\n");
297 		s->video_dev.queue = &s->vidq;
298 	}
299 	return err;
300 }
301 
302 static int cx18_prep_dev(struct cx18 *cx, int type)
303 {
304 	struct cx18_stream *s = &cx->streams[type];
305 	u32 cap = cx->v4l2_cap;
306 	int num_offset = cx18_stream_info[type].num_offset;
307 	int num = cx->instance + cx18_first_minor + num_offset;
308 	int err;
309 
310 	/*
311 	 * These five fields are always initialized.
312 	 * For analog capture related streams, if video_dev.v4l2_dev == NULL then the
313 	 * stream is not in use.
314 	 * For the TS stream, if dvb == NULL then the stream is not in use.
315 	 * In those cases no other fields but these four can be used.
316 	 */
317 	s->video_dev.v4l2_dev = NULL;
318 	s->dvb = NULL;
319 	s->cx = cx;
320 	s->type = type;
321 	s->name = cx18_stream_info[type].name;
322 
323 	/* Check whether the radio is supported */
324 	if (type == CX18_ENC_STREAM_TYPE_RAD && !(cap & V4L2_CAP_RADIO))
325 		return 0;
326 
327 	/* Check whether VBI is supported */
328 	if (type == CX18_ENC_STREAM_TYPE_VBI &&
329 	    !(cap & (V4L2_CAP_VBI_CAPTURE | V4L2_CAP_SLICED_VBI_CAPTURE)))
330 		return 0;
331 
332 	/* User explicitly selected 0 buffers for these streams, so don't
333 	   create them. */
334 	if (cx18_stream_info[type].dma != DMA_NONE &&
335 	    cx->stream_buffers[type] == 0) {
336 		CX18_INFO("Disabled %s device\n", cx18_stream_info[type].name);
337 		return 0;
338 	}
339 
340 	err = cx18_stream_init(cx, type);
341 	if (err)
342 		return err;
343 
344 	/* Allocate the cx18_dvb struct only for the TS on cards with DTV */
345 	if (type == CX18_ENC_STREAM_TYPE_TS) {
346 		if (cx->card->hw_all & CX18_HW_DVB) {
347 			s->dvb = kzalloc(sizeof(struct cx18_dvb), GFP_KERNEL);
348 			if (s->dvb == NULL) {
349 				CX18_ERR("Couldn't allocate cx18_dvb structure for %s\n",
350 					 s->name);
351 				return -ENOMEM;
352 			}
353 		} else {
354 			/* Don't need buffers for the TS, if there is no DVB */
355 			s->buffers = 0;
356 		}
357 	}
358 
359 	if (num_offset == -1)
360 		return 0;
361 
362 	/* initialize the v4l2 video device structure */
363 	snprintf(s->video_dev.name, sizeof(s->video_dev.name), "%s %s",
364 		 cx->v4l2_dev.name, s->name);
365 
366 	s->video_dev.num = num;
367 	s->video_dev.v4l2_dev = &cx->v4l2_dev;
368 	if (type == CX18_ENC_STREAM_TYPE_YUV)
369 		s->video_dev.fops = &cx18_v4l2_enc_yuv_fops;
370 	else
371 		s->video_dev.fops = &cx18_v4l2_enc_fops;
372 	s->video_dev.release = video_device_release_empty;
373 	if (cx->card->video_inputs->video_type == CX18_CARD_INPUT_VID_TUNER)
374 		s->video_dev.tvnorms = cx->tuner_std;
375 	else
376 		s->video_dev.tvnorms = V4L2_STD_ALL;
377 	s->video_dev.lock = &cx->serialize_lock;
378 	cx18_set_funcs(&s->video_dev);
379 	return 0;
380 }
381 
382 /* Initialize v4l2 variables and register v4l2 devices */
383 int cx18_streams_setup(struct cx18 *cx)
384 {
385 	int type, ret;
386 
387 	/* Setup V4L2 Devices */
388 	for (type = 0; type < CX18_MAX_STREAMS; type++) {
389 		/* Prepare device */
390 		ret = cx18_prep_dev(cx, type);
391 		if (ret < 0)
392 			break;
393 
394 		/* Allocate Stream */
395 		ret = cx18_stream_alloc(&cx->streams[type]);
396 		if (ret < 0)
397 			break;
398 	}
399 	if (type == CX18_MAX_STREAMS)
400 		return 0;
401 
402 	/* One or more streams could not be initialized. Clean 'em all up. */
403 	cx18_streams_cleanup(cx, 0);
404 	return ret;
405 }
406 
407 static int cx18_reg_dev(struct cx18 *cx, int type)
408 {
409 	struct cx18_stream *s = &cx->streams[type];
410 	int vfl_type = cx18_stream_info[type].vfl_type;
411 	const char *name;
412 	int num, ret;
413 
414 	if (type == CX18_ENC_STREAM_TYPE_TS && s->dvb != NULL) {
415 		ret = cx18_dvb_register(s);
416 		if (ret < 0) {
417 			CX18_ERR("DVB failed to register\n");
418 			return ret;
419 		}
420 	}
421 
422 	if (s->video_dev.v4l2_dev == NULL)
423 		return 0;
424 
425 	num = s->video_dev.num;
426 	s->video_dev.device_caps = s->v4l2_dev_caps;	/* device capabilities */
427 	/* card number + user defined offset + device offset */
428 	if (type != CX18_ENC_STREAM_TYPE_MPG) {
429 		struct cx18_stream *s_mpg = &cx->streams[CX18_ENC_STREAM_TYPE_MPG];
430 
431 		if (s_mpg->video_dev.v4l2_dev)
432 			num = s_mpg->video_dev.num
433 			    + cx18_stream_info[type].num_offset;
434 	}
435 	video_set_drvdata(&s->video_dev, s);
436 
437 	/* Register device. First try the desired minor, then any free one. */
438 	ret = video_register_device_no_warn(&s->video_dev, vfl_type, num);
439 	if (ret < 0) {
440 		CX18_ERR("Couldn't register v4l2 device for %s (device node number %d)\n",
441 			s->name, num);
442 		s->video_dev.v4l2_dev = NULL;
443 		return ret;
444 	}
445 
446 	name = video_device_node_name(&s->video_dev);
447 
448 	switch (vfl_type) {
449 	case VFL_TYPE_VIDEO:
450 		CX18_INFO("Registered device %s for %s (%d x %d.%02d kB)\n",
451 			  name, s->name, cx->stream_buffers[type],
452 			  cx->stream_buf_size[type] / 1024,
453 			  (cx->stream_buf_size[type] * 100 / 1024) % 100);
454 		break;
455 
456 	case VFL_TYPE_RADIO:
457 		CX18_INFO("Registered device %s for %s\n", name, s->name);
458 		break;
459 
460 	case VFL_TYPE_VBI:
461 		if (cx->stream_buffers[type])
462 			CX18_INFO("Registered device %s for %s (%d x %d bytes)\n",
463 				  name, s->name, cx->stream_buffers[type],
464 				  cx->stream_buf_size[type]);
465 		else
466 			CX18_INFO("Registered device %s for %s\n",
467 				name, s->name);
468 		break;
469 	}
470 
471 	return 0;
472 }
473 
474 /* Register v4l2 devices */
475 int cx18_streams_register(struct cx18 *cx)
476 {
477 	int type;
478 	int err;
479 	int ret = 0;
480 
481 	/* Register V4L2 devices */
482 	for (type = 0; type < CX18_MAX_STREAMS; type++) {
483 		err = cx18_reg_dev(cx, type);
484 		if (err && ret == 0)
485 			ret = err;
486 	}
487 
488 	if (ret == 0)
489 		return 0;
490 
491 	/* One or more streams could not be initialized. Clean 'em all up. */
492 	cx18_streams_cleanup(cx, 1);
493 	return ret;
494 }
495 
496 /* Unregister v4l2 devices */
497 void cx18_streams_cleanup(struct cx18 *cx, int unregister)
498 {
499 	struct video_device *vdev;
500 	int type;
501 
502 	/* Teardown all streams */
503 	for (type = 0; type < CX18_MAX_STREAMS; type++) {
504 
505 		/* The TS has a cx18_dvb structure, not a video_device */
506 		if (type == CX18_ENC_STREAM_TYPE_TS) {
507 			if (cx->streams[type].dvb != NULL) {
508 				if (unregister)
509 					cx18_dvb_unregister(&cx->streams[type]);
510 				kfree(cx->streams[type].dvb);
511 				cx->streams[type].dvb = NULL;
512 				cx18_stream_free(&cx->streams[type]);
513 			}
514 			continue;
515 		}
516 
517 		/* No struct video_device, but can have buffers allocated */
518 		if (type == CX18_ENC_STREAM_TYPE_IDX) {
519 			/* If the module params didn't inhibit IDX ... */
520 			if (cx->stream_buffers[type] != 0) {
521 				cx->stream_buffers[type] = 0;
522 				/*
523 				 * Before calling cx18_stream_free(),
524 				 * check if the IDX stream was actually set up.
525 				 * Needed, since the cx18_probe() error path
526 				 * exits through here as well as normal clean up
527 				 */
528 				if (cx->streams[type].buffers != 0)
529 					cx18_stream_free(&cx->streams[type]);
530 			}
531 			continue;
532 		}
533 
534 		/* If struct video_device exists, can have buffers allocated */
535 		vdev = &cx->streams[type].video_dev;
536 
537 		if (vdev->v4l2_dev == NULL)
538 			continue;
539 
540 		cx18_stream_free(&cx->streams[type]);
541 
542 		if (type == CX18_ENC_STREAM_TYPE_YUV)
543 			vb2_video_unregister_device(vdev);
544 		else
545 			video_unregister_device(vdev);
546 	}
547 }
548 
549 static void cx18_vbi_setup(struct cx18_stream *s)
550 {
551 	struct cx18 *cx = s->cx;
552 	int raw = cx18_raw_vbi(cx);
553 	u32 data[CX2341X_MBOX_MAX_DATA];
554 	int lines;
555 
556 	if (cx->is_60hz) {
557 		cx->vbi.count = 12;
558 		cx->vbi.start[0] = 10;
559 		cx->vbi.start[1] = 273;
560 	} else {        /* PAL/SECAM */
561 		cx->vbi.count = 18;
562 		cx->vbi.start[0] = 6;
563 		cx->vbi.start[1] = 318;
564 	}
565 
566 	/* setup VBI registers */
567 	if (raw)
568 		v4l2_subdev_call(cx->sd_av, vbi, s_raw_fmt, &cx->vbi.in.fmt.vbi);
569 	else
570 		v4l2_subdev_call(cx->sd_av, vbi, s_sliced_fmt, &cx->vbi.in.fmt.sliced);
571 
572 	/*
573 	 * Send the CX18_CPU_SET_RAW_VBI_PARAM API command to setup Encoder Raw
574 	 * VBI when the first analog capture channel starts, as once it starts
575 	 * (e.g. MPEG), we can't effect any change in the Encoder Raw VBI setup
576 	 * (i.e. for the VBI capture channels).  We also send it for each
577 	 * analog capture channel anyway just to make sure we get the proper
578 	 * behavior
579 	 */
580 	if (raw) {
581 		lines = cx->vbi.count * 2;
582 	} else {
583 		/*
584 		 * For 525/60 systems, according to the VIP 2 & BT.656 std:
585 		 * The EAV RP code's Field bit toggles on line 4, a few lines
586 		 * after the Vertcal Blank bit has already toggled.
587 		 * Tell the encoder to capture 21-4+1=18 lines per field,
588 		 * since we want lines 10 through 21.
589 		 *
590 		 * For 625/50 systems, according to the VIP 2 & BT.656 std:
591 		 * The EAV RP code's Field bit toggles on line 1, a few lines
592 		 * after the Vertcal Blank bit has already toggled.
593 		 * (We've actually set the digitizer so that the Field bit
594 		 * toggles on line 2.) Tell the encoder to capture 23-2+1=22
595 		 * lines per field, since we want lines 6 through 23.
596 		 */
597 		lines = cx->is_60hz ? (21 - 4 + 1) * 2 : (23 - 2 + 1) * 2;
598 	}
599 
600 	data[0] = s->handle;
601 	/* Lines per field */
602 	data[1] = (lines / 2) | ((lines / 2) << 16);
603 	/* bytes per line */
604 	data[2] = (raw ? VBI_ACTIVE_SAMPLES
605 		       : (cx->is_60hz ? VBI_HBLANK_SAMPLES_60HZ
606 				      : VBI_HBLANK_SAMPLES_50HZ));
607 	/* Every X number of frames a VBI interrupt arrives
608 	   (frames as in 25 or 30 fps) */
609 	data[3] = 1;
610 	/*
611 	 * Set the SAV/EAV RP codes to look for as start/stop points
612 	 * when in VIP-1.1 mode
613 	 */
614 	if (raw) {
615 		/*
616 		 * Start codes for beginning of "active" line in vertical blank
617 		 * 0x20 (               VerticalBlank                )
618 		 * 0x60 (     EvenField VerticalBlank                )
619 		 */
620 		data[4] = 0x20602060;
621 		/*
622 		 * End codes for end of "active" raw lines and regular lines
623 		 * 0x30 (               VerticalBlank HorizontalBlank)
624 		 * 0x70 (     EvenField VerticalBlank HorizontalBlank)
625 		 * 0x90 (Task                         HorizontalBlank)
626 		 * 0xd0 (Task EvenField               HorizontalBlank)
627 		 */
628 		data[5] = 0x307090d0;
629 	} else {
630 		/*
631 		 * End codes for active video, we want data in the hblank region
632 		 * 0xb0 (Task         0 VerticalBlank HorizontalBlank)
633 		 * 0xf0 (Task EvenField VerticalBlank HorizontalBlank)
634 		 *
635 		 * Since the V bit is only allowed to toggle in the EAV RP code,
636 		 * just before the first active region line, these two
637 		 * are problematic:
638 		 * 0x90 (Task                         HorizontalBlank)
639 		 * 0xd0 (Task EvenField               HorizontalBlank)
640 		 *
641 		 * We have set the digitzer such that we don't have to worry
642 		 * about these problem codes.
643 		 */
644 		data[4] = 0xB0F0B0F0;
645 		/*
646 		 * Start codes for beginning of active line in vertical blank
647 		 * 0xa0 (Task           VerticalBlank                )
648 		 * 0xe0 (Task EvenField VerticalBlank                )
649 		 */
650 		data[5] = 0xA0E0A0E0;
651 	}
652 
653 	CX18_DEBUG_INFO("Setup VBI h: %d lines %x bpl %d fr %d %x %x\n",
654 			data[0], data[1], data[2], data[3], data[4], data[5]);
655 
656 	cx18_api(cx, CX18_CPU_SET_RAW_VBI_PARAM, 6, data);
657 }
658 
659 void cx18_stream_rotate_idx_mdls(struct cx18 *cx)
660 {
661 	struct cx18_stream *s = &cx->streams[CX18_ENC_STREAM_TYPE_IDX];
662 	struct cx18_mdl *mdl;
663 
664 	if (!cx18_stream_enabled(s))
665 		return;
666 
667 	/* Return if the firmware is not running low on MDLs */
668 	if ((atomic_read(&s->q_free.depth) + atomic_read(&s->q_busy.depth)) >=
669 					    CX18_ENC_STREAM_TYPE_IDX_FW_MDL_MIN)
670 		return;
671 
672 	/* Return if there are no MDLs to rotate back to the firmware */
673 	if (atomic_read(&s->q_full.depth) < 2)
674 		return;
675 
676 	/*
677 	 * Take the oldest IDX MDL still holding data, and discard its index
678 	 * entries by scheduling the MDL to go back to the firmware
679 	 */
680 	mdl = cx18_dequeue(s, &s->q_full);
681 	if (mdl != NULL)
682 		cx18_enqueue(s, mdl, &s->q_free);
683 }
684 
685 static
686 struct cx18_queue *_cx18_stream_put_mdl_fw(struct cx18_stream *s,
687 					   struct cx18_mdl *mdl)
688 {
689 	struct cx18 *cx = s->cx;
690 	struct cx18_queue *q;
691 
692 	/* Don't give it to the firmware, if we're not running a capture */
693 	if (s->handle == CX18_INVALID_TASK_HANDLE ||
694 	    test_bit(CX18_F_S_STOPPING, &s->s_flags) ||
695 	    !test_bit(CX18_F_S_STREAMING, &s->s_flags))
696 		return cx18_enqueue(s, mdl, &s->q_free);
697 
698 	q = cx18_enqueue(s, mdl, &s->q_busy);
699 	if (q != &s->q_busy)
700 		return q; /* The firmware has the max MDLs it can handle */
701 
702 	cx18_mdl_sync_for_device(s, mdl);
703 	cx18_vapi(cx, CX18_CPU_DE_SET_MDL, 5, s->handle,
704 		  (void __iomem *) &cx->scb->cpu_mdl[mdl->id] - cx->enc_mem,
705 		  s->bufs_per_mdl, mdl->id, s->mdl_size);
706 	return q;
707 }
708 
709 static
710 void _cx18_stream_load_fw_queue(struct cx18_stream *s)
711 {
712 	struct cx18_queue *q;
713 	struct cx18_mdl *mdl;
714 
715 	if (atomic_read(&s->q_free.depth) == 0 ||
716 	    atomic_read(&s->q_busy.depth) >= CX18_MAX_FW_MDLS_PER_STREAM)
717 		return;
718 
719 	/* Move from q_free to q_busy notifying the firmware, until the limit */
720 	do {
721 		mdl = cx18_dequeue(s, &s->q_free);
722 		if (mdl == NULL)
723 			break;
724 		q = _cx18_stream_put_mdl_fw(s, mdl);
725 	} while (atomic_read(&s->q_busy.depth) < CX18_MAX_FW_MDLS_PER_STREAM
726 		 && q == &s->q_busy);
727 }
728 
729 void cx18_out_work_handler(struct work_struct *work)
730 {
731 	struct cx18_stream *s =
732 			 container_of(work, struct cx18_stream, out_work_order);
733 
734 	_cx18_stream_load_fw_queue(s);
735 }
736 
737 static void cx18_stream_configure_mdls(struct cx18_stream *s)
738 {
739 	cx18_unload_queues(s);
740 
741 	switch (s->type) {
742 	case CX18_ENC_STREAM_TYPE_YUV:
743 		/*
744 		 * Height should be a multiple of 32 lines.
745 		 * Set the MDL size to the exact size needed for one frame.
746 		 * Use enough buffers per MDL to cover the MDL size
747 		 */
748 		if (s->pixelformat == V4L2_PIX_FMT_NV12_16L16)
749 			s->mdl_size = 720 * s->cx->cxhdl.height * 3 / 2;
750 		else
751 			s->mdl_size = 720 * s->cx->cxhdl.height * 2;
752 		s->bufs_per_mdl = s->mdl_size / s->buf_size;
753 		if (s->mdl_size % s->buf_size)
754 			s->bufs_per_mdl++;
755 		break;
756 	case CX18_ENC_STREAM_TYPE_VBI:
757 		s->bufs_per_mdl = 1;
758 		if  (cx18_raw_vbi(s->cx)) {
759 			s->mdl_size = (s->cx->is_60hz ? 12 : 18)
760 						       * 2 * VBI_ACTIVE_SAMPLES;
761 		} else {
762 			/*
763 			 * See comment in cx18_vbi_setup() below about the
764 			 * extra lines we capture in sliced VBI mode due to
765 			 * the lines on which EAV RP codes toggle.
766 			*/
767 			s->mdl_size = s->cx->is_60hz
768 				   ? (21 - 4 + 1) * 2 * VBI_HBLANK_SAMPLES_60HZ
769 				   : (23 - 2 + 1) * 2 * VBI_HBLANK_SAMPLES_50HZ;
770 		}
771 		break;
772 	default:
773 		s->bufs_per_mdl = 1;
774 		s->mdl_size = s->buf_size * s->bufs_per_mdl;
775 		break;
776 	}
777 
778 	cx18_load_queues(s);
779 }
780 
781 int cx18_start_v4l2_encode_stream(struct cx18_stream *s)
782 {
783 	u32 data[MAX_MB_ARGUMENTS];
784 	struct cx18 *cx = s->cx;
785 	int captype = 0;
786 	struct cx18_stream *s_idx;
787 
788 	if (!cx18_stream_enabled(s))
789 		return -EINVAL;
790 
791 	CX18_DEBUG_INFO("Start encoder stream %s\n", s->name);
792 
793 	switch (s->type) {
794 	case CX18_ENC_STREAM_TYPE_MPG:
795 		captype = CAPTURE_CHANNEL_TYPE_MPEG;
796 		cx->mpg_data_received = cx->vbi_data_inserted = 0;
797 		cx->dualwatch_jiffies = jiffies;
798 		cx->dualwatch_stereo_mode = v4l2_ctrl_g_ctrl(cx->cxhdl.audio_mode);
799 		cx->search_pack_header = 0;
800 		break;
801 
802 	case CX18_ENC_STREAM_TYPE_IDX:
803 		captype = CAPTURE_CHANNEL_TYPE_INDEX;
804 		break;
805 	case CX18_ENC_STREAM_TYPE_TS:
806 		captype = CAPTURE_CHANNEL_TYPE_TS;
807 		break;
808 	case CX18_ENC_STREAM_TYPE_YUV:
809 		captype = CAPTURE_CHANNEL_TYPE_YUV;
810 		break;
811 	case CX18_ENC_STREAM_TYPE_PCM:
812 		captype = CAPTURE_CHANNEL_TYPE_PCM;
813 		break;
814 	case CX18_ENC_STREAM_TYPE_VBI:
815 #ifdef CX18_ENCODER_PARSES_SLICED
816 		captype = cx18_raw_vbi(cx) ?
817 		     CAPTURE_CHANNEL_TYPE_VBI : CAPTURE_CHANNEL_TYPE_SLICED_VBI;
818 #else
819 		/*
820 		 * Currently we set things up so that Sliced VBI from the
821 		 * digitizer is handled as Raw VBI by the encoder
822 		 */
823 		captype = CAPTURE_CHANNEL_TYPE_VBI;
824 #endif
825 		cx->vbi.frame = 0;
826 		cx->vbi.inserted_frame = 0;
827 		memset(cx->vbi.sliced_mpeg_size,
828 			0, sizeof(cx->vbi.sliced_mpeg_size));
829 		break;
830 	default:
831 		return -EINVAL;
832 	}
833 
834 	/* Clear Streamoff flags in case left from last capture */
835 	clear_bit(CX18_F_S_STREAMOFF, &s->s_flags);
836 
837 	cx18_vapi_result(cx, data, CX18_CREATE_TASK, 1, CPU_CMD_MASK_CAPTURE);
838 	s->handle = data[0];
839 	cx18_vapi(cx, CX18_CPU_SET_CHANNEL_TYPE, 2, s->handle, captype);
840 
841 	/*
842 	 * For everything but CAPTURE_CHANNEL_TYPE_TS, play it safe and
843 	 * set up all the parameters, as it is not obvious which parameters the
844 	 * firmware shares across capture channel types and which it does not.
845 	 *
846 	 * Some of the cx18_vapi() calls below apply to only certain capture
847 	 * channel types.  We're hoping there's no harm in calling most of them
848 	 * anyway, as long as the values are all consistent.  Setting some
849 	 * shared parameters will have no effect once an analog capture channel
850 	 * has started streaming.
851 	 */
852 	if (captype != CAPTURE_CHANNEL_TYPE_TS) {
853 		cx18_vapi(cx, CX18_CPU_SET_VER_CROP_LINE, 2, s->handle, 0);
854 		cx18_vapi(cx, CX18_CPU_SET_MISC_PARAMETERS, 3, s->handle, 3, 1);
855 		cx18_vapi(cx, CX18_CPU_SET_MISC_PARAMETERS, 3, s->handle, 8, 0);
856 		cx18_vapi(cx, CX18_CPU_SET_MISC_PARAMETERS, 3, s->handle, 4, 1);
857 
858 		/*
859 		 * Audio related reset according to
860 		 * Documentation/driver-api/media/drivers/cx2341x-devel.rst
861 		 */
862 		if (atomic_read(&cx->ana_capturing) == 0)
863 			cx18_vapi(cx, CX18_CPU_SET_MISC_PARAMETERS, 2,
864 				  s->handle, 12);
865 
866 		/*
867 		 * Number of lines for Field 1 & Field 2 according to
868 		 * Documentation/driver-api/media/drivers/cx2341x-devel.rst
869 		 * Field 1 is 312 for 625 line systems in BT.656
870 		 * Field 2 is 313 for 625 line systems in BT.656
871 		 */
872 		cx18_vapi(cx, CX18_CPU_SET_CAPTURE_LINE_NO, 3,
873 			  s->handle, 312, 313);
874 
875 		if (cx->v4l2_cap & V4L2_CAP_VBI_CAPTURE)
876 			cx18_vbi_setup(s);
877 
878 		/*
879 		 * Select to receive I, P, and B frame index entries, if the
880 		 * index stream is enabled.  Otherwise disable index entry
881 		 * generation.
882 		 */
883 		s_idx = &cx->streams[CX18_ENC_STREAM_TYPE_IDX];
884 		cx18_vapi_result(cx, data, CX18_CPU_SET_INDEXTABLE, 2,
885 				 s->handle, cx18_stream_enabled(s_idx) ? 7 : 0);
886 
887 		/* Call out to the common CX2341x API setup for user controls */
888 		cx->cxhdl.priv = s;
889 		cx2341x_handler_setup(&cx->cxhdl);
890 
891 		/*
892 		 * When starting a capture and we're set for radio,
893 		 * ensure the video is muted, despite the user control.
894 		 */
895 		if (!cx->cxhdl.video_mute &&
896 		    test_bit(CX18_F_I_RADIO_USER, &cx->i_flags))
897 			cx18_vapi(cx, CX18_CPU_SET_VIDEO_MUTE, 2, s->handle,
898 			  (v4l2_ctrl_g_ctrl(cx->cxhdl.video_mute_yuv) << 8) | 1);
899 
900 		/* Enable the Video Format Converter for UYVY 4:2:2 support,
901 		 * rather than the default HM12 Macroblovk 4:2:0 support.
902 		 */
903 		if (captype == CAPTURE_CHANNEL_TYPE_YUV) {
904 			if (s->pixelformat == V4L2_PIX_FMT_UYVY)
905 				cx18_vapi(cx, CX18_CPU_SET_VFC_PARAM, 2,
906 					s->handle, 1);
907 			else
908 				/* If in doubt, default to HM12 */
909 				cx18_vapi(cx, CX18_CPU_SET_VFC_PARAM, 2,
910 					s->handle, 0);
911 		}
912 	}
913 
914 	if (atomic_read(&cx->tot_capturing) == 0) {
915 		cx2341x_handler_set_busy(&cx->cxhdl, 1);
916 		clear_bit(CX18_F_I_EOS, &cx->i_flags);
917 		cx18_write_reg(cx, 7, CX18_DSP0_INTERRUPT_MASK);
918 	}
919 
920 	cx18_vapi(cx, CX18_CPU_DE_SET_MDL_ACK, 3, s->handle,
921 		(void __iomem *)&cx->scb->cpu_mdl_ack[s->type][0] - cx->enc_mem,
922 		(void __iomem *)&cx->scb->cpu_mdl_ack[s->type][1] - cx->enc_mem);
923 
924 	/* Init all the cpu_mdls for this stream */
925 	cx18_stream_configure_mdls(s);
926 	_cx18_stream_load_fw_queue(s);
927 
928 	/* begin_capture */
929 	if (cx18_vapi(cx, CX18_CPU_CAPTURE_START, 1, s->handle)) {
930 		CX18_DEBUG_WARN("Error starting capture!\n");
931 		/* Ensure we're really not capturing before releasing MDLs */
932 		set_bit(CX18_F_S_STOPPING, &s->s_flags);
933 		if (s->type == CX18_ENC_STREAM_TYPE_MPG)
934 			cx18_vapi(cx, CX18_CPU_CAPTURE_STOP, 2, s->handle, 1);
935 		else
936 			cx18_vapi(cx, CX18_CPU_CAPTURE_STOP, 1, s->handle);
937 		clear_bit(CX18_F_S_STREAMING, &s->s_flags);
938 		/* FIXME - CX18_F_S_STREAMOFF as well? */
939 		cx18_vapi(cx, CX18_CPU_DE_RELEASE_MDL, 1, s->handle);
940 		cx18_vapi(cx, CX18_DESTROY_TASK, 1, s->handle);
941 		s->handle = CX18_INVALID_TASK_HANDLE;
942 		clear_bit(CX18_F_S_STOPPING, &s->s_flags);
943 		if (atomic_read(&cx->tot_capturing) == 0) {
944 			set_bit(CX18_F_I_EOS, &cx->i_flags);
945 			cx18_write_reg(cx, 5, CX18_DSP0_INTERRUPT_MASK);
946 		}
947 		return -EINVAL;
948 	}
949 
950 	/* you're live! sit back and await interrupts :) */
951 	if (captype != CAPTURE_CHANNEL_TYPE_TS)
952 		atomic_inc(&cx->ana_capturing);
953 	atomic_inc(&cx->tot_capturing);
954 	return 0;
955 }
956 EXPORT_SYMBOL(cx18_start_v4l2_encode_stream);
957 
958 void cx18_stop_all_captures(struct cx18 *cx)
959 {
960 	int i;
961 
962 	for (i = CX18_MAX_STREAMS - 1; i >= 0; i--) {
963 		struct cx18_stream *s = &cx->streams[i];
964 
965 		if (!cx18_stream_enabled(s))
966 			continue;
967 		if (test_bit(CX18_F_S_STREAMING, &s->s_flags))
968 			cx18_stop_v4l2_encode_stream(s, 0);
969 	}
970 }
971 
972 int cx18_stop_v4l2_encode_stream(struct cx18_stream *s, int gop_end)
973 {
974 	struct cx18 *cx = s->cx;
975 
976 	if (!cx18_stream_enabled(s))
977 		return -EINVAL;
978 
979 	/* This function assumes that you are allowed to stop the capture
980 	   and that we are actually capturing */
981 
982 	CX18_DEBUG_INFO("Stop Capture\n");
983 
984 	if (atomic_read(&cx->tot_capturing) == 0)
985 		return 0;
986 
987 	set_bit(CX18_F_S_STOPPING, &s->s_flags);
988 	if (s->type == CX18_ENC_STREAM_TYPE_MPG)
989 		cx18_vapi(cx, CX18_CPU_CAPTURE_STOP, 2, s->handle, !gop_end);
990 	else
991 		cx18_vapi(cx, CX18_CPU_CAPTURE_STOP, 1, s->handle);
992 
993 	if (s->type == CX18_ENC_STREAM_TYPE_MPG && gop_end) {
994 		CX18_INFO("ignoring gop_end: not (yet?) supported by the firmware\n");
995 	}
996 
997 	if (s->type != CX18_ENC_STREAM_TYPE_TS)
998 		atomic_dec(&cx->ana_capturing);
999 	atomic_dec(&cx->tot_capturing);
1000 
1001 	/* Clear capture and no-read bits */
1002 	clear_bit(CX18_F_S_STREAMING, &s->s_flags);
1003 
1004 	/* Tell the CX23418 it can't use our buffers anymore */
1005 	cx18_vapi(cx, CX18_CPU_DE_RELEASE_MDL, 1, s->handle);
1006 
1007 	cx18_vapi(cx, CX18_DESTROY_TASK, 1, s->handle);
1008 	s->handle = CX18_INVALID_TASK_HANDLE;
1009 	clear_bit(CX18_F_S_STOPPING, &s->s_flags);
1010 
1011 	if (atomic_read(&cx->tot_capturing) > 0)
1012 		return 0;
1013 
1014 	cx2341x_handler_set_busy(&cx->cxhdl, 0);
1015 	cx18_write_reg(cx, 5, CX18_DSP0_INTERRUPT_MASK);
1016 	wake_up(&s->waitq);
1017 
1018 	return 0;
1019 }
1020 EXPORT_SYMBOL(cx18_stop_v4l2_encode_stream);
1021 
1022 u32 cx18_find_handle(struct cx18 *cx)
1023 {
1024 	int i;
1025 
1026 	/* find first available handle to be used for global settings */
1027 	for (i = 0; i < CX18_MAX_STREAMS; i++) {
1028 		struct cx18_stream *s = &cx->streams[i];
1029 
1030 		if (s->video_dev.v4l2_dev && (s->handle != CX18_INVALID_TASK_HANDLE))
1031 			return s->handle;
1032 	}
1033 	return CX18_INVALID_TASK_HANDLE;
1034 }
1035 
1036 struct cx18_stream *cx18_handle_to_stream(struct cx18 *cx, u32 handle)
1037 {
1038 	int i;
1039 	struct cx18_stream *s;
1040 
1041 	if (handle == CX18_INVALID_TASK_HANDLE)
1042 		return NULL;
1043 
1044 	for (i = 0; i < CX18_MAX_STREAMS; i++) {
1045 		s = &cx->streams[i];
1046 		if (s->handle != handle)
1047 			continue;
1048 		if (cx18_stream_enabled(s))
1049 			return s;
1050 	}
1051 	return NULL;
1052 }
1053