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