1 // SPDX-License-Identifier: GPL-2.0-or-later
2 /*
3  *  Driver for the NXP SAA7164 PCIe bridge
4  *
5  *  Copyright (c) 2010-2015 Steven Toth <stoth@kernellabs.com>
6  */
7 
8 #include "saa7164.h"
9 
10 #define ENCODER_MAX_BITRATE 6500000
11 #define ENCODER_MIN_BITRATE 1000000
12 #define ENCODER_DEF_BITRATE 5000000
13 
14 /*
15  * This is a dummy non-zero value for the sizeimage field of v4l2_pix_format.
16  * It is not actually used for anything since this driver does not support
17  * stream I/O, only read(), and because this driver produces an MPEG stream
18  * and not discrete frames. But the V4L2 spec doesn't allow for this value
19  * to be 0, so set it to 0x10000 instead.
20  *
21  * If we ever change this driver to support stream I/O, then this field
22  * will be the size of the streaming buffers.
23  */
24 #define SAA7164_SIZEIMAGE (0x10000)
25 
26 static struct saa7164_tvnorm saa7164_tvnorms[] = {
27 	{
28 		.name      = "NTSC-M",
29 		.id        = V4L2_STD_NTSC_M,
30 	}, {
31 		.name      = "NTSC-JP",
32 		.id        = V4L2_STD_NTSC_M_JP,
33 	}
34 };
35 
36 /* Take the encoder configuration form the port struct and
37  * flush it to the hardware.
38  */
39 static void saa7164_encoder_configure(struct saa7164_port *port)
40 {
41 	struct saa7164_dev *dev = port->dev;
42 	dprintk(DBGLVL_ENC, "%s()\n", __func__);
43 
44 	port->encoder_params.width = port->width;
45 	port->encoder_params.height = port->height;
46 	port->encoder_params.is_50hz =
47 		(port->encodernorm.id & V4L2_STD_625_50) != 0;
48 
49 	/* Set up the DIF (enable it) for analog mode by default */
50 	saa7164_api_initialize_dif(port);
51 
52 	/* Configure the correct video standard */
53 	saa7164_api_configure_dif(port, port->encodernorm.id);
54 
55 	/* Ensure the audio decoder is correct configured */
56 	saa7164_api_set_audio_std(port);
57 }
58 
59 static int saa7164_encoder_buffers_dealloc(struct saa7164_port *port)
60 {
61 	struct list_head *c, *n, *p, *q, *l, *v;
62 	struct saa7164_dev *dev = port->dev;
63 	struct saa7164_buffer *buf;
64 	struct saa7164_user_buffer *ubuf;
65 
66 	/* Remove any allocated buffers */
67 	mutex_lock(&port->dmaqueue_lock);
68 
69 	dprintk(DBGLVL_ENC, "%s(port=%d) dmaqueue\n", __func__, port->nr);
70 	list_for_each_safe(c, n, &port->dmaqueue.list) {
71 		buf = list_entry(c, struct saa7164_buffer, list);
72 		list_del(c);
73 		saa7164_buffer_dealloc(buf);
74 	}
75 
76 	dprintk(DBGLVL_ENC, "%s(port=%d) used\n", __func__, port->nr);
77 	list_for_each_safe(p, q, &port->list_buf_used.list) {
78 		ubuf = list_entry(p, struct saa7164_user_buffer, list);
79 		list_del(p);
80 		saa7164_buffer_dealloc_user(ubuf);
81 	}
82 
83 	dprintk(DBGLVL_ENC, "%s(port=%d) free\n", __func__, port->nr);
84 	list_for_each_safe(l, v, &port->list_buf_free.list) {
85 		ubuf = list_entry(l, struct saa7164_user_buffer, list);
86 		list_del(l);
87 		saa7164_buffer_dealloc_user(ubuf);
88 	}
89 
90 	mutex_unlock(&port->dmaqueue_lock);
91 	dprintk(DBGLVL_ENC, "%s(port=%d) done\n", __func__, port->nr);
92 
93 	return 0;
94 }
95 
96 /* Dynamic buffer switch at encoder start time */
97 static int saa7164_encoder_buffers_alloc(struct saa7164_port *port)
98 {
99 	struct saa7164_dev *dev = port->dev;
100 	struct saa7164_buffer *buf;
101 	struct saa7164_user_buffer *ubuf;
102 	struct tmHWStreamParameters *params = &port->hw_streamingparams;
103 	int result = -ENODEV, i;
104 	int len = 0;
105 
106 	dprintk(DBGLVL_ENC, "%s()\n", __func__);
107 
108 	if (port->encoder_params.stream_type ==
109 		V4L2_MPEG_STREAM_TYPE_MPEG2_PS) {
110 		dprintk(DBGLVL_ENC,
111 			"%s() type=V4L2_MPEG_STREAM_TYPE_MPEG2_PS\n",
112 			__func__);
113 		params->samplesperline = 128;
114 		params->numberoflines = 256;
115 		params->pitch = 128;
116 		params->numpagetables = 2 +
117 			((SAA7164_PS_NUMBER_OF_LINES * 128) / PAGE_SIZE);
118 	} else
119 	if (port->encoder_params.stream_type ==
120 		V4L2_MPEG_STREAM_TYPE_MPEG2_TS) {
121 		dprintk(DBGLVL_ENC,
122 			"%s() type=V4L2_MPEG_STREAM_TYPE_MPEG2_TS\n",
123 			__func__);
124 		params->samplesperline = 188;
125 		params->numberoflines = 312;
126 		params->pitch = 188;
127 		params->numpagetables = 2 +
128 			((SAA7164_TS_NUMBER_OF_LINES * 188) / PAGE_SIZE);
129 	} else
130 		BUG();
131 
132 	/* Init and establish defaults */
133 	params->bitspersample = 8;
134 	params->linethreshold = 0;
135 	params->pagetablelistvirt = NULL;
136 	params->pagetablelistphys = NULL;
137 	params->numpagetableentries = port->hwcfg.buffercount;
138 
139 	/* Allocate the PCI resources, buffers (hard) */
140 	for (i = 0; i < port->hwcfg.buffercount; i++) {
141 		buf = saa7164_buffer_alloc(port,
142 			params->numberoflines *
143 			params->pitch);
144 
145 		if (!buf) {
146 			printk(KERN_ERR "%s() failed (errno = %d), unable to allocate buffer\n",
147 				__func__, result);
148 			result = -ENOMEM;
149 			goto failed;
150 		} else {
151 
152 			mutex_lock(&port->dmaqueue_lock);
153 			list_add_tail(&buf->list, &port->dmaqueue.list);
154 			mutex_unlock(&port->dmaqueue_lock);
155 
156 		}
157 	}
158 
159 	/* Allocate some kernel buffers for copying
160 	 * to userpsace.
161 	 */
162 	len = params->numberoflines * params->pitch;
163 
164 	if (encoder_buffers < 16)
165 		encoder_buffers = 16;
166 	if (encoder_buffers > 512)
167 		encoder_buffers = 512;
168 
169 	for (i = 0; i < encoder_buffers; i++) {
170 
171 		ubuf = saa7164_buffer_alloc_user(dev, len);
172 		if (ubuf) {
173 			mutex_lock(&port->dmaqueue_lock);
174 			list_add_tail(&ubuf->list, &port->list_buf_free.list);
175 			mutex_unlock(&port->dmaqueue_lock);
176 		}
177 
178 	}
179 
180 	result = 0;
181 
182 failed:
183 	return result;
184 }
185 
186 static int saa7164_encoder_initialize(struct saa7164_port *port)
187 {
188 	saa7164_encoder_configure(port);
189 	return 0;
190 }
191 
192 /* -- V4L2 --------------------------------------------------------- */
193 int saa7164_s_std(struct saa7164_port *port, v4l2_std_id id)
194 {
195 	struct saa7164_dev *dev = port->dev;
196 	unsigned int i;
197 
198 	dprintk(DBGLVL_ENC, "%s(id=0x%x)\n", __func__, (u32)id);
199 
200 	for (i = 0; i < ARRAY_SIZE(saa7164_tvnorms); i++) {
201 		if (id & saa7164_tvnorms[i].id)
202 			break;
203 	}
204 	if (i == ARRAY_SIZE(saa7164_tvnorms))
205 		return -EINVAL;
206 
207 	port->encodernorm = saa7164_tvnorms[i];
208 	port->std = id;
209 
210 	/* Update the audio decoder while is not running in
211 	 * auto detect mode.
212 	 */
213 	saa7164_api_set_audio_std(port);
214 
215 	dprintk(DBGLVL_ENC, "%s(id=0x%x) OK\n", __func__, (u32)id);
216 
217 	return 0;
218 }
219 
220 static int vidioc_s_std(struct file *file, void *priv, v4l2_std_id id)
221 {
222 	struct saa7164_encoder_fh *fh = file->private_data;
223 
224 	return saa7164_s_std(fh->port, id);
225 }
226 
227 int saa7164_g_std(struct saa7164_port *port, v4l2_std_id *id)
228 {
229 	*id = port->std;
230 	return 0;
231 }
232 
233 static int vidioc_g_std(struct file *file, void *priv, v4l2_std_id *id)
234 {
235 	struct saa7164_encoder_fh *fh = file->private_data;
236 
237 	return saa7164_g_std(fh->port, id);
238 }
239 
240 int saa7164_enum_input(struct file *file, void *priv, struct v4l2_input *i)
241 {
242 	static const char * const inputs[] = {
243 		"tuner", "composite", "svideo", "aux",
244 		"composite 2", "svideo 2", "aux 2"
245 	};
246 	int n;
247 
248 	if (i->index >= 7)
249 		return -EINVAL;
250 
251 	strscpy(i->name, inputs[i->index], sizeof(i->name));
252 
253 	if (i->index == 0)
254 		i->type = V4L2_INPUT_TYPE_TUNER;
255 	else
256 		i->type  = V4L2_INPUT_TYPE_CAMERA;
257 
258 	for (n = 0; n < ARRAY_SIZE(saa7164_tvnorms); n++)
259 		i->std |= saa7164_tvnorms[n].id;
260 
261 	return 0;
262 }
263 
264 int saa7164_g_input(struct saa7164_port *port, unsigned int *i)
265 {
266 	struct saa7164_dev *dev = port->dev;
267 
268 	if (saa7164_api_get_videomux(port) != SAA_OK)
269 		return -EIO;
270 
271 	*i = (port->mux_input - 1);
272 
273 	dprintk(DBGLVL_ENC, "%s() input=%d\n", __func__, *i);
274 
275 	return 0;
276 }
277 
278 static int vidioc_g_input(struct file *file, void *priv, unsigned int *i)
279 {
280 	struct saa7164_encoder_fh *fh = file->private_data;
281 
282 	return saa7164_g_input(fh->port, i);
283 }
284 
285 int saa7164_s_input(struct saa7164_port *port, unsigned int i)
286 {
287 	struct saa7164_dev *dev = port->dev;
288 
289 	dprintk(DBGLVL_ENC, "%s() input=%d\n", __func__, i);
290 
291 	if (i >= 7)
292 		return -EINVAL;
293 
294 	port->mux_input = i + 1;
295 
296 	if (saa7164_api_set_videomux(port) != SAA_OK)
297 		return -EIO;
298 
299 	return 0;
300 }
301 
302 static int vidioc_s_input(struct file *file, void *priv, unsigned int i)
303 {
304 	struct saa7164_encoder_fh *fh = file->private_data;
305 
306 	return saa7164_s_input(fh->port, i);
307 }
308 
309 int saa7164_g_tuner(struct file *file, void *priv, struct v4l2_tuner *t)
310 {
311 	struct saa7164_encoder_fh *fh = file->private_data;
312 	struct saa7164_port *port = fh->port;
313 	struct saa7164_dev *dev = port->dev;
314 
315 	if (0 != t->index)
316 		return -EINVAL;
317 
318 	strscpy(t->name, "tuner", sizeof(t->name));
319 	t->capability = V4L2_TUNER_CAP_NORM | V4L2_TUNER_CAP_STEREO;
320 	t->rangelow = SAA7164_TV_MIN_FREQ;
321 	t->rangehigh = SAA7164_TV_MAX_FREQ;
322 
323 	dprintk(DBGLVL_ENC, "VIDIOC_G_TUNER: tuner type %d\n", t->type);
324 
325 	return 0;
326 }
327 
328 int saa7164_s_tuner(struct file *file, void *priv,
329 			   const struct v4l2_tuner *t)
330 {
331 	if (0 != t->index)
332 		return -EINVAL;
333 
334 	/* Update the A/V core */
335 	return 0;
336 }
337 
338 int saa7164_g_frequency(struct saa7164_port *port, struct v4l2_frequency *f)
339 {
340 	if (f->tuner)
341 		return -EINVAL;
342 
343 	f->frequency = port->freq;
344 	return 0;
345 }
346 
347 static int vidioc_g_frequency(struct file *file, void *priv,
348 	struct v4l2_frequency *f)
349 {
350 	struct saa7164_encoder_fh *fh = file->private_data;
351 
352 	return saa7164_g_frequency(fh->port, f);
353 }
354 
355 int saa7164_s_frequency(struct saa7164_port *port,
356 			const struct v4l2_frequency *f)
357 {
358 	struct saa7164_dev *dev = port->dev;
359 	struct saa7164_port *tsport;
360 	struct dvb_frontend *fe;
361 
362 	/* TODO: Pull this for the std */
363 	struct analog_parameters params = {
364 		.mode      = V4L2_TUNER_ANALOG_TV,
365 		.audmode   = V4L2_TUNER_MODE_STEREO,
366 		.std       = port->encodernorm.id,
367 		.frequency = f->frequency
368 	};
369 
370 	/* Stop the encoder */
371 	dprintk(DBGLVL_ENC, "%s() frequency=%d tuner=%d\n", __func__,
372 		f->frequency, f->tuner);
373 
374 	if (f->tuner != 0)
375 		return -EINVAL;
376 
377 	port->freq = clamp(f->frequency,
378 			   SAA7164_TV_MIN_FREQ, SAA7164_TV_MAX_FREQ);
379 
380 	/* Update the hardware */
381 	if (port->nr == SAA7164_PORT_ENC1)
382 		tsport = &dev->ports[SAA7164_PORT_TS1];
383 	else if (port->nr == SAA7164_PORT_ENC2)
384 		tsport = &dev->ports[SAA7164_PORT_TS2];
385 	else
386 		BUG();
387 
388 	fe = tsport->dvb.frontend;
389 
390 	if (fe && fe->ops.tuner_ops.set_analog_params)
391 		fe->ops.tuner_ops.set_analog_params(fe, &params);
392 	else
393 		printk(KERN_ERR "%s() No analog tuner, aborting\n", __func__);
394 
395 	saa7164_encoder_initialize(port);
396 
397 	return 0;
398 }
399 
400 static int vidioc_s_frequency(struct file *file, void *priv,
401 			      const struct v4l2_frequency *f)
402 {
403 	struct saa7164_encoder_fh *fh = file->private_data;
404 
405 	return saa7164_s_frequency(fh->port, f);
406 }
407 
408 static int saa7164_s_ctrl(struct v4l2_ctrl *ctrl)
409 {
410 	struct saa7164_port *port =
411 		container_of(ctrl->handler, struct saa7164_port, ctrl_handler);
412 	struct saa7164_encoder_params *params = &port->encoder_params;
413 	int ret = 0;
414 
415 	switch (ctrl->id) {
416 	case V4L2_CID_BRIGHTNESS:
417 		port->ctl_brightness = ctrl->val;
418 		saa7164_api_set_usercontrol(port, PU_BRIGHTNESS_CONTROL);
419 		break;
420 	case V4L2_CID_CONTRAST:
421 		port->ctl_contrast = ctrl->val;
422 		saa7164_api_set_usercontrol(port, PU_CONTRAST_CONTROL);
423 		break;
424 	case V4L2_CID_SATURATION:
425 		port->ctl_saturation = ctrl->val;
426 		saa7164_api_set_usercontrol(port, PU_SATURATION_CONTROL);
427 		break;
428 	case V4L2_CID_HUE:
429 		port->ctl_hue = ctrl->val;
430 		saa7164_api_set_usercontrol(port, PU_HUE_CONTROL);
431 		break;
432 	case V4L2_CID_SHARPNESS:
433 		port->ctl_sharpness = ctrl->val;
434 		saa7164_api_set_usercontrol(port, PU_SHARPNESS_CONTROL);
435 		break;
436 	case V4L2_CID_AUDIO_VOLUME:
437 		port->ctl_volume = ctrl->val;
438 		saa7164_api_set_audio_volume(port, port->ctl_volume);
439 		break;
440 	case V4L2_CID_MPEG_VIDEO_BITRATE:
441 		params->bitrate = ctrl->val;
442 		break;
443 	case V4L2_CID_MPEG_STREAM_TYPE:
444 		params->stream_type = ctrl->val;
445 		break;
446 	case V4L2_CID_MPEG_AUDIO_MUTE:
447 		params->ctl_mute = ctrl->val;
448 		ret = saa7164_api_audio_mute(port, params->ctl_mute);
449 		if (ret != SAA_OK) {
450 			printk(KERN_ERR "%s() error, ret = 0x%x\n", __func__,
451 				ret);
452 			ret = -EIO;
453 		}
454 		break;
455 	case V4L2_CID_MPEG_VIDEO_ASPECT:
456 		params->ctl_aspect = ctrl->val;
457 		ret = saa7164_api_set_aspect_ratio(port);
458 		if (ret != SAA_OK) {
459 			printk(KERN_ERR "%s() error, ret = 0x%x\n", __func__,
460 				ret);
461 			ret = -EIO;
462 		}
463 		break;
464 	case V4L2_CID_MPEG_VIDEO_BITRATE_MODE:
465 		params->bitrate_mode = ctrl->val;
466 		break;
467 	case V4L2_CID_MPEG_VIDEO_B_FRAMES:
468 		params->refdist = ctrl->val;
469 		break;
470 	case V4L2_CID_MPEG_VIDEO_BITRATE_PEAK:
471 		params->bitrate_peak = ctrl->val;
472 		break;
473 	case V4L2_CID_MPEG_VIDEO_GOP_SIZE:
474 		params->gop_size = ctrl->val;
475 		break;
476 	default:
477 		ret = -EINVAL;
478 	}
479 
480 	return ret;
481 }
482 
483 static int vidioc_querycap(struct file *file, void  *priv,
484 	struct v4l2_capability *cap)
485 {
486 	struct saa7164_encoder_fh *fh = file->private_data;
487 	struct saa7164_port *port = fh->port;
488 	struct saa7164_dev *dev = port->dev;
489 
490 	strscpy(cap->driver, dev->name, sizeof(cap->driver));
491 	strscpy(cap->card, saa7164_boards[dev->board].name,
492 		sizeof(cap->card));
493 	cap->capabilities = V4L2_CAP_VIDEO_CAPTURE | V4L2_CAP_READWRITE |
494 			    V4L2_CAP_TUNER | V4L2_CAP_VBI_CAPTURE |
495 			    V4L2_CAP_DEVICE_CAPS;
496 	return 0;
497 }
498 
499 static int vidioc_enum_fmt_vid_cap(struct file *file, void  *priv,
500 	struct v4l2_fmtdesc *f)
501 {
502 	if (f->index != 0)
503 		return -EINVAL;
504 
505 	f->pixelformat = V4L2_PIX_FMT_MPEG;
506 
507 	return 0;
508 }
509 
510 static int vidioc_fmt_vid_cap(struct file *file, void *priv,
511 				struct v4l2_format *f)
512 {
513 	struct saa7164_encoder_fh *fh = file->private_data;
514 	struct saa7164_port *port = fh->port;
515 
516 	f->fmt.pix.pixelformat  = V4L2_PIX_FMT_MPEG;
517 	f->fmt.pix.bytesperline = 0;
518 	f->fmt.pix.sizeimage    = SAA7164_SIZEIMAGE;
519 	f->fmt.pix.field        = V4L2_FIELD_INTERLACED;
520 	f->fmt.pix.colorspace   = V4L2_COLORSPACE_SMPTE170M;
521 	f->fmt.pix.width        = port->width;
522 	f->fmt.pix.height       = port->height;
523 	return 0;
524 }
525 
526 static int saa7164_encoder_stop_port(struct saa7164_port *port)
527 {
528 	struct saa7164_dev *dev = port->dev;
529 	int ret;
530 
531 	ret = saa7164_api_transition_port(port, SAA_DMASTATE_STOP);
532 	if ((ret != SAA_OK) && (ret != SAA_ERR_ALREADY_STOPPED)) {
533 		printk(KERN_ERR "%s() stop transition failed, ret = 0x%x\n",
534 			__func__, ret);
535 		ret = -EIO;
536 	} else {
537 		dprintk(DBGLVL_ENC, "%s()    Stopped\n", __func__);
538 		ret = 0;
539 	}
540 
541 	return ret;
542 }
543 
544 static int saa7164_encoder_acquire_port(struct saa7164_port *port)
545 {
546 	struct saa7164_dev *dev = port->dev;
547 	int ret;
548 
549 	ret = saa7164_api_transition_port(port, SAA_DMASTATE_ACQUIRE);
550 	if ((ret != SAA_OK) && (ret != SAA_ERR_ALREADY_STOPPED)) {
551 		printk(KERN_ERR "%s() acquire transition failed, ret = 0x%x\n",
552 			__func__, ret);
553 		ret = -EIO;
554 	} else {
555 		dprintk(DBGLVL_ENC, "%s() Acquired\n", __func__);
556 		ret = 0;
557 	}
558 
559 	return ret;
560 }
561 
562 static int saa7164_encoder_pause_port(struct saa7164_port *port)
563 {
564 	struct saa7164_dev *dev = port->dev;
565 	int ret;
566 
567 	ret = saa7164_api_transition_port(port, SAA_DMASTATE_PAUSE);
568 	if ((ret != SAA_OK) && (ret != SAA_ERR_ALREADY_STOPPED)) {
569 		printk(KERN_ERR "%s() pause transition failed, ret = 0x%x\n",
570 			__func__, ret);
571 		ret = -EIO;
572 	} else {
573 		dprintk(DBGLVL_ENC, "%s()   Paused\n", __func__);
574 		ret = 0;
575 	}
576 
577 	return ret;
578 }
579 
580 /* Firmware is very windows centric, meaning you have to transition
581  * the part through AVStream / KS Windows stages, forwards or backwards.
582  * States are: stopped, acquired (h/w), paused, started.
583  * We have to leave here will all of the soft buffers on the free list,
584  * else the cfg_post() func won't have soft buffers to correctly configure.
585  */
586 static int saa7164_encoder_stop_streaming(struct saa7164_port *port)
587 {
588 	struct saa7164_dev *dev = port->dev;
589 	struct saa7164_buffer *buf;
590 	struct saa7164_user_buffer *ubuf;
591 	struct list_head *c, *n;
592 	int ret;
593 
594 	dprintk(DBGLVL_ENC, "%s(port=%d)\n", __func__, port->nr);
595 
596 	ret = saa7164_encoder_pause_port(port);
597 	ret = saa7164_encoder_acquire_port(port);
598 	ret = saa7164_encoder_stop_port(port);
599 
600 	dprintk(DBGLVL_ENC, "%s(port=%d) Hardware stopped\n", __func__,
601 		port->nr);
602 
603 	/* Reset the state of any allocated buffer resources */
604 	mutex_lock(&port->dmaqueue_lock);
605 
606 	/* Reset the hard and soft buffer state */
607 	list_for_each_safe(c, n, &port->dmaqueue.list) {
608 		buf = list_entry(c, struct saa7164_buffer, list);
609 		buf->flags = SAA7164_BUFFER_FREE;
610 		buf->pos = 0;
611 	}
612 
613 	list_for_each_safe(c, n, &port->list_buf_used.list) {
614 		ubuf = list_entry(c, struct saa7164_user_buffer, list);
615 		ubuf->pos = 0;
616 		list_move_tail(&ubuf->list, &port->list_buf_free.list);
617 	}
618 
619 	mutex_unlock(&port->dmaqueue_lock);
620 
621 	/* Free any allocated resources */
622 	saa7164_encoder_buffers_dealloc(port);
623 
624 	dprintk(DBGLVL_ENC, "%s(port=%d) Released\n", __func__, port->nr);
625 
626 	return ret;
627 }
628 
629 static int saa7164_encoder_start_streaming(struct saa7164_port *port)
630 {
631 	struct saa7164_dev *dev = port->dev;
632 	int result, ret = 0;
633 
634 	dprintk(DBGLVL_ENC, "%s(port=%d)\n", __func__, port->nr);
635 
636 	port->done_first_interrupt = 0;
637 
638 	/* allocate all of the PCIe DMA buffer resources on the fly,
639 	 * allowing switching between TS and PS payloads without
640 	 * requiring a complete driver reload.
641 	 */
642 	saa7164_encoder_buffers_alloc(port);
643 
644 	/* Configure the encoder with any cache values */
645 	saa7164_api_set_encoder(port);
646 	saa7164_api_get_encoder(port);
647 
648 	/* Place the empty buffers on the hardware */
649 	saa7164_buffer_cfg_port(port);
650 
651 	/* Acquire the hardware */
652 	result = saa7164_api_transition_port(port, SAA_DMASTATE_ACQUIRE);
653 	if ((result != SAA_OK) && (result != SAA_ERR_ALREADY_STOPPED)) {
654 		printk(KERN_ERR "%s() acquire transition failed, res = 0x%x\n",
655 			__func__, result);
656 
657 		/* Stop the hardware, regardless */
658 		result = saa7164_api_transition_port(port, SAA_DMASTATE_STOP);
659 		if ((result != SAA_OK) && (result != SAA_ERR_ALREADY_STOPPED)) {
660 			printk(KERN_ERR "%s() acquire/forced stop transition failed, res = 0x%x\n",
661 			       __func__, result);
662 		}
663 		ret = -EIO;
664 		goto out;
665 	} else
666 		dprintk(DBGLVL_ENC, "%s()   Acquired\n", __func__);
667 
668 	/* Pause the hardware */
669 	result = saa7164_api_transition_port(port, SAA_DMASTATE_PAUSE);
670 	if ((result != SAA_OK) && (result != SAA_ERR_ALREADY_STOPPED)) {
671 		printk(KERN_ERR "%s() pause transition failed, res = 0x%x\n",
672 				__func__, result);
673 
674 		/* Stop the hardware, regardless */
675 		result = saa7164_api_transition_port(port, SAA_DMASTATE_STOP);
676 		if ((result != SAA_OK) && (result != SAA_ERR_ALREADY_STOPPED)) {
677 			printk(KERN_ERR "%s() pause/forced stop transition failed, res = 0x%x\n",
678 			       __func__, result);
679 		}
680 
681 		ret = -EIO;
682 		goto out;
683 	} else
684 		dprintk(DBGLVL_ENC, "%s()   Paused\n", __func__);
685 
686 	/* Start the hardware */
687 	result = saa7164_api_transition_port(port, SAA_DMASTATE_RUN);
688 	if ((result != SAA_OK) && (result != SAA_ERR_ALREADY_STOPPED)) {
689 		printk(KERN_ERR "%s() run transition failed, result = 0x%x\n",
690 				__func__, result);
691 
692 		/* Stop the hardware, regardless */
693 		result = saa7164_api_transition_port(port, SAA_DMASTATE_STOP);
694 		if ((result != SAA_OK) && (result != SAA_ERR_ALREADY_STOPPED)) {
695 			printk(KERN_ERR "%s() run/forced stop transition failed, res = 0x%x\n",
696 			       __func__, result);
697 		}
698 
699 		ret = -EIO;
700 	} else
701 		dprintk(DBGLVL_ENC, "%s()   Running\n", __func__);
702 
703 out:
704 	return ret;
705 }
706 
707 static int fops_open(struct file *file)
708 {
709 	struct saa7164_dev *dev;
710 	struct saa7164_port *port;
711 	struct saa7164_encoder_fh *fh;
712 
713 	port = (struct saa7164_port *)video_get_drvdata(video_devdata(file));
714 	if (!port)
715 		return -ENODEV;
716 
717 	dev = port->dev;
718 
719 	dprintk(DBGLVL_ENC, "%s()\n", __func__);
720 
721 	/* allocate + initialize per filehandle data */
722 	fh = kzalloc(sizeof(*fh), GFP_KERNEL);
723 	if (NULL == fh)
724 		return -ENOMEM;
725 
726 	fh->port = port;
727 	v4l2_fh_init(&fh->fh, video_devdata(file));
728 	v4l2_fh_add(&fh->fh);
729 	file->private_data = fh;
730 
731 	return 0;
732 }
733 
734 static int fops_release(struct file *file)
735 {
736 	struct saa7164_encoder_fh *fh = file->private_data;
737 	struct saa7164_port *port = fh->port;
738 	struct saa7164_dev *dev = port->dev;
739 
740 	dprintk(DBGLVL_ENC, "%s()\n", __func__);
741 
742 	/* Shut device down on last close */
743 	if (atomic_cmpxchg(&fh->v4l_reading, 1, 0) == 1) {
744 		if (atomic_dec_return(&port->v4l_reader_count) == 0) {
745 			/* stop mpeg capture then cancel buffers */
746 			saa7164_encoder_stop_streaming(port);
747 		}
748 	}
749 
750 	v4l2_fh_del(&fh->fh);
751 	v4l2_fh_exit(&fh->fh);
752 	kfree(fh);
753 
754 	return 0;
755 }
756 
757 static struct
758 saa7164_user_buffer *saa7164_enc_next_buf(struct saa7164_port *port)
759 {
760 	struct saa7164_user_buffer *ubuf = NULL;
761 	struct saa7164_dev *dev = port->dev;
762 	u32 crc;
763 
764 	mutex_lock(&port->dmaqueue_lock);
765 	if (!list_empty(&port->list_buf_used.list)) {
766 		ubuf = list_first_entry(&port->list_buf_used.list,
767 			struct saa7164_user_buffer, list);
768 
769 		if (crc_checking) {
770 			crc = crc32(0, ubuf->data, ubuf->actual_size);
771 			if (crc != ubuf->crc) {
772 				printk(KERN_ERR
773 		"%s() ubuf %p crc became invalid, was 0x%x became 0x%x\n",
774 					__func__,
775 					ubuf, ubuf->crc, crc);
776 			}
777 		}
778 
779 	}
780 	mutex_unlock(&port->dmaqueue_lock);
781 
782 	dprintk(DBGLVL_ENC, "%s() returns %p\n", __func__, ubuf);
783 
784 	return ubuf;
785 }
786 
787 static ssize_t fops_read(struct file *file, char __user *buffer,
788 	size_t count, loff_t *pos)
789 {
790 	struct saa7164_encoder_fh *fh = file->private_data;
791 	struct saa7164_port *port = fh->port;
792 	struct saa7164_user_buffer *ubuf = NULL;
793 	struct saa7164_dev *dev = port->dev;
794 	int ret = 0;
795 	int rem, cnt;
796 	u8 *p;
797 
798 	port->last_read_msecs_diff = port->last_read_msecs;
799 	port->last_read_msecs = jiffies_to_msecs(jiffies);
800 	port->last_read_msecs_diff = port->last_read_msecs -
801 		port->last_read_msecs_diff;
802 
803 	saa7164_histogram_update(&port->read_interval,
804 		port->last_read_msecs_diff);
805 
806 	if (*pos) {
807 		printk(KERN_ERR "%s() ESPIPE\n", __func__);
808 		return -ESPIPE;
809 	}
810 
811 	if (atomic_cmpxchg(&fh->v4l_reading, 0, 1) == 0) {
812 		if (atomic_inc_return(&port->v4l_reader_count) == 1) {
813 
814 			if (saa7164_encoder_initialize(port) < 0) {
815 				printk(KERN_ERR "%s() EINVAL\n", __func__);
816 				return -EINVAL;
817 			}
818 
819 			saa7164_encoder_start_streaming(port);
820 			msleep(200);
821 		}
822 	}
823 
824 	/* blocking wait for buffer */
825 	if ((file->f_flags & O_NONBLOCK) == 0) {
826 		if (wait_event_interruptible(port->wait_read,
827 			saa7164_enc_next_buf(port))) {
828 				printk(KERN_ERR "%s() ERESTARTSYS\n", __func__);
829 				return -ERESTARTSYS;
830 		}
831 	}
832 
833 	/* Pull the first buffer from the used list */
834 	ubuf = saa7164_enc_next_buf(port);
835 
836 	while ((count > 0) && ubuf) {
837 
838 		/* set remaining bytes to copy */
839 		rem = ubuf->actual_size - ubuf->pos;
840 		cnt = rem > count ? count : rem;
841 
842 		p = ubuf->data + ubuf->pos;
843 
844 		dprintk(DBGLVL_ENC,
845 			"%s() count=%d cnt=%d rem=%d buf=%p buf->pos=%d\n",
846 			__func__, (int)count, cnt, rem, ubuf, ubuf->pos);
847 
848 		if (copy_to_user(buffer, p, cnt)) {
849 			printk(KERN_ERR "%s() copy_to_user failed\n", __func__);
850 			if (!ret) {
851 				printk(KERN_ERR "%s() EFAULT\n", __func__);
852 				ret = -EFAULT;
853 			}
854 			goto err;
855 		}
856 
857 		ubuf->pos += cnt;
858 		count -= cnt;
859 		buffer += cnt;
860 		ret += cnt;
861 
862 		if (ubuf->pos > ubuf->actual_size)
863 			printk(KERN_ERR "read() pos > actual, huh?\n");
864 
865 		if (ubuf->pos == ubuf->actual_size) {
866 
867 			/* finished with current buffer, take next buffer */
868 
869 			/* Requeue the buffer on the free list */
870 			ubuf->pos = 0;
871 
872 			mutex_lock(&port->dmaqueue_lock);
873 			list_move_tail(&ubuf->list, &port->list_buf_free.list);
874 			mutex_unlock(&port->dmaqueue_lock);
875 
876 			/* Dequeue next */
877 			if ((file->f_flags & O_NONBLOCK) == 0) {
878 				if (wait_event_interruptible(port->wait_read,
879 					saa7164_enc_next_buf(port))) {
880 						break;
881 				}
882 			}
883 			ubuf = saa7164_enc_next_buf(port);
884 		}
885 	}
886 err:
887 	if (!ret && !ubuf)
888 		ret = -EAGAIN;
889 
890 	return ret;
891 }
892 
893 static __poll_t fops_poll(struct file *file, poll_table *wait)
894 {
895 	__poll_t req_events = poll_requested_events(wait);
896 	struct saa7164_encoder_fh *fh =
897 		(struct saa7164_encoder_fh *)file->private_data;
898 	struct saa7164_port *port = fh->port;
899 	__poll_t mask = v4l2_ctrl_poll(file, wait);
900 
901 	port->last_poll_msecs_diff = port->last_poll_msecs;
902 	port->last_poll_msecs = jiffies_to_msecs(jiffies);
903 	port->last_poll_msecs_diff = port->last_poll_msecs -
904 		port->last_poll_msecs_diff;
905 
906 	saa7164_histogram_update(&port->poll_interval,
907 		port->last_poll_msecs_diff);
908 
909 	if (!(req_events & (EPOLLIN | EPOLLRDNORM)))
910 		return mask;
911 
912 	if (atomic_cmpxchg(&fh->v4l_reading, 0, 1) == 0) {
913 		if (atomic_inc_return(&port->v4l_reader_count) == 1) {
914 			if (saa7164_encoder_initialize(port) < 0)
915 				return mask | EPOLLERR;
916 			saa7164_encoder_start_streaming(port);
917 			msleep(200);
918 		}
919 	}
920 
921 	/* Pull the first buffer from the used list */
922 	if (!list_empty(&port->list_buf_used.list))
923 		mask |= EPOLLIN | EPOLLRDNORM;
924 
925 	return mask;
926 }
927 
928 static const struct v4l2_ctrl_ops saa7164_ctrl_ops = {
929 	.s_ctrl = saa7164_s_ctrl,
930 };
931 
932 static const struct v4l2_file_operations mpeg_fops = {
933 	.owner		= THIS_MODULE,
934 	.open		= fops_open,
935 	.release	= fops_release,
936 	.read		= fops_read,
937 	.poll		= fops_poll,
938 	.unlocked_ioctl	= video_ioctl2,
939 };
940 
941 static const struct v4l2_ioctl_ops mpeg_ioctl_ops = {
942 	.vidioc_s_std		 = vidioc_s_std,
943 	.vidioc_g_std		 = vidioc_g_std,
944 	.vidioc_enum_input	 = saa7164_enum_input,
945 	.vidioc_g_input		 = vidioc_g_input,
946 	.vidioc_s_input		 = vidioc_s_input,
947 	.vidioc_g_tuner		 = saa7164_g_tuner,
948 	.vidioc_s_tuner		 = saa7164_s_tuner,
949 	.vidioc_g_frequency	 = vidioc_g_frequency,
950 	.vidioc_s_frequency	 = vidioc_s_frequency,
951 	.vidioc_querycap	 = vidioc_querycap,
952 	.vidioc_enum_fmt_vid_cap = vidioc_enum_fmt_vid_cap,
953 	.vidioc_g_fmt_vid_cap	 = vidioc_fmt_vid_cap,
954 	.vidioc_try_fmt_vid_cap	 = vidioc_fmt_vid_cap,
955 	.vidioc_s_fmt_vid_cap	 = vidioc_fmt_vid_cap,
956 	.vidioc_log_status	 = v4l2_ctrl_log_status,
957 	.vidioc_subscribe_event  = v4l2_ctrl_subscribe_event,
958 	.vidioc_unsubscribe_event = v4l2_event_unsubscribe,
959 };
960 
961 static struct video_device saa7164_mpeg_template = {
962 	.name          = "saa7164",
963 	.fops          = &mpeg_fops,
964 	.ioctl_ops     = &mpeg_ioctl_ops,
965 	.minor         = -1,
966 	.tvnorms       = SAA7164_NORMS,
967 	.device_caps   = V4L2_CAP_VIDEO_CAPTURE | V4L2_CAP_READWRITE |
968 			 V4L2_CAP_TUNER,
969 };
970 
971 static struct video_device *saa7164_encoder_alloc(
972 	struct saa7164_port *port,
973 	struct pci_dev *pci,
974 	struct video_device *template,
975 	char *type)
976 {
977 	struct video_device *vfd;
978 	struct saa7164_dev *dev = port->dev;
979 
980 	dprintk(DBGLVL_ENC, "%s()\n", __func__);
981 
982 	vfd = video_device_alloc();
983 	if (NULL == vfd)
984 		return NULL;
985 
986 	*vfd = *template;
987 	snprintf(vfd->name, sizeof(vfd->name), "%s %s (%s)", dev->name,
988 		type, saa7164_boards[dev->board].name);
989 
990 	vfd->v4l2_dev  = &dev->v4l2_dev;
991 	vfd->release = video_device_release;
992 	return vfd;
993 }
994 
995 int saa7164_encoder_register(struct saa7164_port *port)
996 {
997 	struct saa7164_dev *dev = port->dev;
998 	struct v4l2_ctrl_handler *hdl = &port->ctrl_handler;
999 	int result = -ENODEV;
1000 
1001 	dprintk(DBGLVL_ENC, "%s()\n", __func__);
1002 
1003 	BUG_ON(port->type != SAA7164_MPEG_ENCODER);
1004 
1005 	/* Sanity check that the PCI configuration space is active */
1006 	if (port->hwcfg.BARLocation == 0) {
1007 		printk(KERN_ERR "%s() failed (errno = %d), NO PCI configuration\n",
1008 			__func__, result);
1009 		result = -ENOMEM;
1010 		goto fail_pci;
1011 	}
1012 
1013 	/* Establish encoder defaults here */
1014 	/* Set default TV standard */
1015 	port->encodernorm = saa7164_tvnorms[0];
1016 	port->width = 720;
1017 	port->mux_input = 1; /* Composite */
1018 	port->video_format = EU_VIDEO_FORMAT_MPEG_2;
1019 	port->audio_format = 0;
1020 	port->video_resolution = 0;
1021 	port->freq = SAA7164_TV_MIN_FREQ;
1022 
1023 	v4l2_ctrl_handler_init(hdl, 14);
1024 	v4l2_ctrl_new_std(hdl, &saa7164_ctrl_ops,
1025 			  V4L2_CID_BRIGHTNESS, 0, 255, 1, 127);
1026 	v4l2_ctrl_new_std(hdl, &saa7164_ctrl_ops,
1027 			  V4L2_CID_CONTRAST, 0, 255, 1, 66);
1028 	v4l2_ctrl_new_std(hdl, &saa7164_ctrl_ops,
1029 			  V4L2_CID_SATURATION, 0, 255, 1, 62);
1030 	v4l2_ctrl_new_std(hdl, &saa7164_ctrl_ops,
1031 			  V4L2_CID_HUE, 0, 255, 1, 128);
1032 	v4l2_ctrl_new_std(hdl, &saa7164_ctrl_ops,
1033 			  V4L2_CID_SHARPNESS, 0x0, 0x0f, 1, 8);
1034 	v4l2_ctrl_new_std(hdl, &saa7164_ctrl_ops,
1035 			  V4L2_CID_MPEG_AUDIO_MUTE, 0x0, 0x01, 1, 0);
1036 	v4l2_ctrl_new_std(hdl, &saa7164_ctrl_ops,
1037 			  V4L2_CID_AUDIO_VOLUME, -83, 24, 1, 20);
1038 	v4l2_ctrl_new_std(hdl, &saa7164_ctrl_ops,
1039 			  V4L2_CID_MPEG_VIDEO_BITRATE,
1040 			  ENCODER_MIN_BITRATE, ENCODER_MAX_BITRATE,
1041 			  100000, ENCODER_DEF_BITRATE);
1042 	v4l2_ctrl_new_std_menu(hdl, &saa7164_ctrl_ops,
1043 			       V4L2_CID_MPEG_STREAM_TYPE,
1044 			       V4L2_MPEG_STREAM_TYPE_MPEG2_TS, 0,
1045 			       V4L2_MPEG_STREAM_TYPE_MPEG2_PS);
1046 	v4l2_ctrl_new_std_menu(hdl, &saa7164_ctrl_ops,
1047 			       V4L2_CID_MPEG_VIDEO_ASPECT,
1048 			       V4L2_MPEG_VIDEO_ASPECT_221x100, 0,
1049 			       V4L2_MPEG_VIDEO_ASPECT_4x3);
1050 	v4l2_ctrl_new_std(hdl, &saa7164_ctrl_ops,
1051 			  V4L2_CID_MPEG_VIDEO_GOP_SIZE, 1, 255, 1, 15);
1052 	v4l2_ctrl_new_std_menu(hdl, &saa7164_ctrl_ops,
1053 			       V4L2_CID_MPEG_VIDEO_BITRATE_MODE,
1054 			       V4L2_MPEG_VIDEO_BITRATE_MODE_CBR, 0,
1055 			       V4L2_MPEG_VIDEO_BITRATE_MODE_VBR);
1056 	v4l2_ctrl_new_std(hdl, &saa7164_ctrl_ops,
1057 			  V4L2_CID_MPEG_VIDEO_B_FRAMES, 1, 3, 1, 1);
1058 	v4l2_ctrl_new_std(hdl, &saa7164_ctrl_ops,
1059 			  V4L2_CID_MPEG_VIDEO_BITRATE_PEAK,
1060 			  ENCODER_MIN_BITRATE, ENCODER_MAX_BITRATE,
1061 			  100000, ENCODER_DEF_BITRATE);
1062 	if (hdl->error) {
1063 		result = hdl->error;
1064 		goto fail_hdl;
1065 	}
1066 
1067 	port->std = V4L2_STD_NTSC_M;
1068 
1069 	if (port->encodernorm.id & V4L2_STD_525_60)
1070 		port->height = 480;
1071 	else
1072 		port->height = 576;
1073 
1074 	/* Allocate and register the video device node */
1075 	port->v4l_device = saa7164_encoder_alloc(port,
1076 		dev->pci, &saa7164_mpeg_template, "mpeg");
1077 
1078 	if (!port->v4l_device) {
1079 		printk(KERN_INFO "%s: can't allocate mpeg device\n",
1080 			dev->name);
1081 		result = -ENOMEM;
1082 		goto fail_hdl;
1083 	}
1084 
1085 	port->v4l_device->ctrl_handler = hdl;
1086 	v4l2_ctrl_handler_setup(hdl);
1087 	video_set_drvdata(port->v4l_device, port);
1088 	result = video_register_device(port->v4l_device,
1089 		VFL_TYPE_VIDEO, -1);
1090 	if (result < 0) {
1091 		printk(KERN_INFO "%s: can't register mpeg device\n",
1092 			dev->name);
1093 		goto fail_reg;
1094 	}
1095 
1096 	printk(KERN_INFO "%s: registered device video%d [mpeg]\n",
1097 		dev->name, port->v4l_device->num);
1098 
1099 	/* Configure the hardware defaults */
1100 	saa7164_api_set_videomux(port);
1101 	saa7164_api_set_usercontrol(port, PU_BRIGHTNESS_CONTROL);
1102 	saa7164_api_set_usercontrol(port, PU_CONTRAST_CONTROL);
1103 	saa7164_api_set_usercontrol(port, PU_HUE_CONTROL);
1104 	saa7164_api_set_usercontrol(port, PU_SATURATION_CONTROL);
1105 	saa7164_api_set_usercontrol(port, PU_SHARPNESS_CONTROL);
1106 	saa7164_api_audio_mute(port, 0);
1107 	saa7164_api_set_audio_volume(port, 20);
1108 	saa7164_api_set_aspect_ratio(port);
1109 
1110 	/* Disable audio standard detection, it's buggy */
1111 	saa7164_api_set_audio_detection(port, 0);
1112 
1113 	saa7164_api_set_encoder(port);
1114 	saa7164_api_get_encoder(port);
1115 	return 0;
1116 
1117 fail_reg:
1118 	video_device_release(port->v4l_device);
1119 	port->v4l_device = NULL;
1120 fail_hdl:
1121 	v4l2_ctrl_handler_free(hdl);
1122 fail_pci:
1123 	return result;
1124 }
1125 
1126 void saa7164_encoder_unregister(struct saa7164_port *port)
1127 {
1128 	struct saa7164_dev *dev = port->dev;
1129 
1130 	dprintk(DBGLVL_ENC, "%s(port=%d)\n", __func__, port->nr);
1131 
1132 	BUG_ON(port->type != SAA7164_MPEG_ENCODER);
1133 
1134 	if (port->v4l_device) {
1135 		if (port->v4l_device->minor != -1)
1136 			video_unregister_device(port->v4l_device);
1137 		else
1138 			video_device_release(port->v4l_device);
1139 
1140 		port->v4l_device = NULL;
1141 	}
1142 	v4l2_ctrl_handler_free(&port->ctrl_handler);
1143 
1144 	dprintk(DBGLVL_ENC, "%s(port=%d) done\n", __func__, port->nr);
1145 }
1146 
1147