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