1 /*
2  *
3  * device driver for philips saa7134 based TV cards
4  * video4linux video interface
5  *
6  * (c) 2001-03 Gerd Knorr <kraxel@bytesex.org> [SuSE Labs]
7  *
8  *  This program is free software; you can redistribute it and/or modify
9  *  it under the terms of the GNU General Public License as published by
10  *  the Free Software Foundation; either version 2 of the License, or
11  *  (at your option) any later version.
12  *
13  *  This program is distributed in the hope that it will be useful,
14  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
15  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16  *  GNU General Public License for more details.
17  */
18 
19 #include "saa7134.h"
20 #include "saa7134-reg.h"
21 
22 #include <linux/init.h>
23 #include <linux/list.h>
24 #include <linux/module.h>
25 #include <linux/kernel.h>
26 #include <linux/slab.h>
27 #include <linux/sort.h>
28 
29 #include <media/v4l2-common.h>
30 #include <media/v4l2-event.h>
31 #include <media/i2c/saa6588.h>
32 
33 /* ------------------------------------------------------------------ */
34 
35 unsigned int video_debug;
36 static unsigned int gbuffers      = 8;
37 static unsigned int noninterlaced; /* 0 */
38 static unsigned int gbufsize      = 720*576*4;
39 static unsigned int gbufsize_max  = 720*576*4;
40 static char secam[] = "--";
41 module_param(video_debug, int, 0644);
42 MODULE_PARM_DESC(video_debug,"enable debug messages [video]");
43 module_param(gbuffers, int, 0444);
44 MODULE_PARM_DESC(gbuffers,"number of capture buffers, range 2-32");
45 module_param(noninterlaced, int, 0644);
46 MODULE_PARM_DESC(noninterlaced,"capture non interlaced video");
47 module_param_string(secam, secam, sizeof(secam), 0644);
48 MODULE_PARM_DESC(secam, "force SECAM variant, either DK,L or Lc");
49 
50 
51 #define video_dbg(fmt, arg...) do { \
52 	if (video_debug & 0x04) \
53 		printk(KERN_DEBUG pr_fmt("video: " fmt), ## arg); \
54 	} while (0)
55 
56 /* ------------------------------------------------------------------ */
57 /* Defines for Video Output Port Register at address 0x191            */
58 
59 /* Bit 0: VIP code T bit polarity */
60 
61 #define VP_T_CODE_P_NON_INVERTED	0x00
62 #define VP_T_CODE_P_INVERTED		0x01
63 
64 /* ------------------------------------------------------------------ */
65 /* Defines for Video Output Port Register at address 0x195            */
66 
67 /* Bit 2: Video output clock delay control */
68 
69 #define VP_CLK_CTRL2_NOT_DELAYED	0x00
70 #define VP_CLK_CTRL2_DELAYED		0x04
71 
72 /* Bit 1: Video output clock invert control */
73 
74 #define VP_CLK_CTRL1_NON_INVERTED	0x00
75 #define VP_CLK_CTRL1_INVERTED		0x02
76 
77 /* ------------------------------------------------------------------ */
78 /* Defines for Video Output Port Register at address 0x196            */
79 
80 /* Bits 2 to 0: VSYNC pin video vertical sync type */
81 
82 #define VP_VS_TYPE_MASK			0x07
83 
84 #define VP_VS_TYPE_OFF			0x00
85 #define VP_VS_TYPE_V123			0x01
86 #define VP_VS_TYPE_V_ITU		0x02
87 #define VP_VS_TYPE_VGATE_L		0x03
88 #define VP_VS_TYPE_RESERVED1		0x04
89 #define VP_VS_TYPE_RESERVED2		0x05
90 #define VP_VS_TYPE_F_ITU		0x06
91 #define VP_VS_TYPE_SC_FID		0x07
92 
93 /* ------------------------------------------------------------------ */
94 /* data structs for video                                             */
95 
96 static int video_out[][9] = {
97 	[CCIR656] = { 0x00, 0xb1, 0x00, 0xa1, 0x00, 0x04, 0x06, 0x00, 0x00 },
98 };
99 
100 static struct saa7134_format formats[] = {
101 	{
102 		.name     = "8 bpp gray",
103 		.fourcc   = V4L2_PIX_FMT_GREY,
104 		.depth    = 8,
105 		.pm       = 0x06,
106 	},{
107 		.name     = "15 bpp RGB, le",
108 		.fourcc   = V4L2_PIX_FMT_RGB555,
109 		.depth    = 16,
110 		.pm       = 0x13 | 0x80,
111 	},{
112 		.name     = "15 bpp RGB, be",
113 		.fourcc   = V4L2_PIX_FMT_RGB555X,
114 		.depth    = 16,
115 		.pm       = 0x13 | 0x80,
116 		.bswap    = 1,
117 	},{
118 		.name     = "16 bpp RGB, le",
119 		.fourcc   = V4L2_PIX_FMT_RGB565,
120 		.depth    = 16,
121 		.pm       = 0x10 | 0x80,
122 	},{
123 		.name     = "16 bpp RGB, be",
124 		.fourcc   = V4L2_PIX_FMT_RGB565X,
125 		.depth    = 16,
126 		.pm       = 0x10 | 0x80,
127 		.bswap    = 1,
128 	},{
129 		.name     = "24 bpp RGB, le",
130 		.fourcc   = V4L2_PIX_FMT_BGR24,
131 		.depth    = 24,
132 		.pm       = 0x11,
133 	},{
134 		.name     = "24 bpp RGB, be",
135 		.fourcc   = V4L2_PIX_FMT_RGB24,
136 		.depth    = 24,
137 		.pm       = 0x11,
138 		.bswap    = 1,
139 	},{
140 		.name     = "32 bpp RGB, le",
141 		.fourcc   = V4L2_PIX_FMT_BGR32,
142 		.depth    = 32,
143 		.pm       = 0x12,
144 	},{
145 		.name     = "32 bpp RGB, be",
146 		.fourcc   = V4L2_PIX_FMT_RGB32,
147 		.depth    = 32,
148 		.pm       = 0x12,
149 		.bswap    = 1,
150 		.wswap    = 1,
151 	},{
152 		.name     = "4:2:2 packed, YUYV",
153 		.fourcc   = V4L2_PIX_FMT_YUYV,
154 		.depth    = 16,
155 		.pm       = 0x00,
156 		.bswap    = 1,
157 		.yuv      = 1,
158 	},{
159 		.name     = "4:2:2 packed, UYVY",
160 		.fourcc   = V4L2_PIX_FMT_UYVY,
161 		.depth    = 16,
162 		.pm       = 0x00,
163 		.yuv      = 1,
164 	},{
165 		.name     = "4:2:2 planar, Y-Cb-Cr",
166 		.fourcc   = V4L2_PIX_FMT_YUV422P,
167 		.depth    = 16,
168 		.pm       = 0x09,
169 		.yuv      = 1,
170 		.planar   = 1,
171 		.hshift   = 1,
172 		.vshift   = 0,
173 	},{
174 		.name     = "4:2:0 planar, Y-Cb-Cr",
175 		.fourcc   = V4L2_PIX_FMT_YUV420,
176 		.depth    = 12,
177 		.pm       = 0x0a,
178 		.yuv      = 1,
179 		.planar   = 1,
180 		.hshift   = 1,
181 		.vshift   = 1,
182 	},{
183 		.name     = "4:2:0 planar, Y-Cb-Cr",
184 		.fourcc   = V4L2_PIX_FMT_YVU420,
185 		.depth    = 12,
186 		.pm       = 0x0a,
187 		.yuv      = 1,
188 		.planar   = 1,
189 		.uvswap   = 1,
190 		.hshift   = 1,
191 		.vshift   = 1,
192 	}
193 };
194 #define FORMATS ARRAY_SIZE(formats)
195 
196 #define NORM_625_50			\
197 		.h_start       = 0,	\
198 		.h_stop        = 719,	\
199 		.video_v_start = 24,	\
200 		.video_v_stop  = 311,	\
201 		.vbi_v_start_0 = 7,	\
202 		.vbi_v_stop_0  = 23,	\
203 		.vbi_v_start_1 = 319,   \
204 		.src_timing    = 4
205 
206 #define NORM_525_60			\
207 		.h_start       = 0,	\
208 		.h_stop        = 719,	\
209 		.video_v_start = 23,	\
210 		.video_v_stop  = 262,	\
211 		.vbi_v_start_0 = 10,	\
212 		.vbi_v_stop_0  = 21,	\
213 		.vbi_v_start_1 = 273,	\
214 		.src_timing    = 7
215 
216 static struct saa7134_tvnorm tvnorms[] = {
217 	{
218 		.name          = "PAL", /* autodetect */
219 		.id            = V4L2_STD_PAL,
220 		NORM_625_50,
221 
222 		.sync_control  = 0x18,
223 		.luma_control  = 0x40,
224 		.chroma_ctrl1  = 0x81,
225 		.chroma_gain   = 0x2a,
226 		.chroma_ctrl2  = 0x06,
227 		.vgate_misc    = 0x1c,
228 
229 	},{
230 		.name          = "PAL-BG",
231 		.id            = V4L2_STD_PAL_BG,
232 		NORM_625_50,
233 
234 		.sync_control  = 0x18,
235 		.luma_control  = 0x40,
236 		.chroma_ctrl1  = 0x81,
237 		.chroma_gain   = 0x2a,
238 		.chroma_ctrl2  = 0x06,
239 		.vgate_misc    = 0x1c,
240 
241 	},{
242 		.name          = "PAL-I",
243 		.id            = V4L2_STD_PAL_I,
244 		NORM_625_50,
245 
246 		.sync_control  = 0x18,
247 		.luma_control  = 0x40,
248 		.chroma_ctrl1  = 0x81,
249 		.chroma_gain   = 0x2a,
250 		.chroma_ctrl2  = 0x06,
251 		.vgate_misc    = 0x1c,
252 
253 	},{
254 		.name          = "PAL-DK",
255 		.id            = V4L2_STD_PAL_DK,
256 		NORM_625_50,
257 
258 		.sync_control  = 0x18,
259 		.luma_control  = 0x40,
260 		.chroma_ctrl1  = 0x81,
261 		.chroma_gain   = 0x2a,
262 		.chroma_ctrl2  = 0x06,
263 		.vgate_misc    = 0x1c,
264 
265 	},{
266 		.name          = "NTSC",
267 		.id            = V4L2_STD_NTSC,
268 		NORM_525_60,
269 
270 		.sync_control  = 0x59,
271 		.luma_control  = 0x40,
272 		.chroma_ctrl1  = 0x89,
273 		.chroma_gain   = 0x2a,
274 		.chroma_ctrl2  = 0x0e,
275 		.vgate_misc    = 0x18,
276 
277 	},{
278 		.name          = "SECAM",
279 		.id            = V4L2_STD_SECAM,
280 		NORM_625_50,
281 
282 		.sync_control  = 0x18,
283 		.luma_control  = 0x1b,
284 		.chroma_ctrl1  = 0xd1,
285 		.chroma_gain   = 0x80,
286 		.chroma_ctrl2  = 0x00,
287 		.vgate_misc    = 0x1c,
288 
289 	},{
290 		.name          = "SECAM-DK",
291 		.id            = V4L2_STD_SECAM_DK,
292 		NORM_625_50,
293 
294 		.sync_control  = 0x18,
295 		.luma_control  = 0x1b,
296 		.chroma_ctrl1  = 0xd1,
297 		.chroma_gain   = 0x80,
298 		.chroma_ctrl2  = 0x00,
299 		.vgate_misc    = 0x1c,
300 
301 	},{
302 		.name          = "SECAM-L",
303 		.id            = V4L2_STD_SECAM_L,
304 		NORM_625_50,
305 
306 		.sync_control  = 0x18,
307 		.luma_control  = 0x1b,
308 		.chroma_ctrl1  = 0xd1,
309 		.chroma_gain   = 0x80,
310 		.chroma_ctrl2  = 0x00,
311 		.vgate_misc    = 0x1c,
312 
313 	},{
314 		.name          = "SECAM-Lc",
315 		.id            = V4L2_STD_SECAM_LC,
316 		NORM_625_50,
317 
318 		.sync_control  = 0x18,
319 		.luma_control  = 0x1b,
320 		.chroma_ctrl1  = 0xd1,
321 		.chroma_gain   = 0x80,
322 		.chroma_ctrl2  = 0x00,
323 		.vgate_misc    = 0x1c,
324 
325 	},{
326 		.name          = "PAL-M",
327 		.id            = V4L2_STD_PAL_M,
328 		NORM_525_60,
329 
330 		.sync_control  = 0x59,
331 		.luma_control  = 0x40,
332 		.chroma_ctrl1  = 0xb9,
333 		.chroma_gain   = 0x2a,
334 		.chroma_ctrl2  = 0x0e,
335 		.vgate_misc    = 0x18,
336 
337 	},{
338 		.name          = "PAL-Nc",
339 		.id            = V4L2_STD_PAL_Nc,
340 		NORM_625_50,
341 
342 		.sync_control  = 0x18,
343 		.luma_control  = 0x40,
344 		.chroma_ctrl1  = 0xa1,
345 		.chroma_gain   = 0x2a,
346 		.chroma_ctrl2  = 0x06,
347 		.vgate_misc    = 0x1c,
348 
349 	},{
350 		.name          = "PAL-60",
351 		.id            = V4L2_STD_PAL_60,
352 
353 		.h_start       = 0,
354 		.h_stop        = 719,
355 		.video_v_start = 23,
356 		.video_v_stop  = 262,
357 		.vbi_v_start_0 = 10,
358 		.vbi_v_stop_0  = 21,
359 		.vbi_v_start_1 = 273,
360 		.src_timing    = 7,
361 
362 		.sync_control  = 0x18,
363 		.luma_control  = 0x40,
364 		.chroma_ctrl1  = 0x81,
365 		.chroma_gain   = 0x2a,
366 		.chroma_ctrl2  = 0x06,
367 		.vgate_misc    = 0x1c,
368 	}
369 };
370 #define TVNORMS ARRAY_SIZE(tvnorms)
371 
372 static struct saa7134_format* format_by_fourcc(unsigned int fourcc)
373 {
374 	unsigned int i;
375 
376 	for (i = 0; i < FORMATS; i++)
377 		if (formats[i].fourcc == fourcc)
378 			return formats+i;
379 	return NULL;
380 }
381 
382 /* ------------------------------------------------------------------ */
383 
384 static void set_tvnorm(struct saa7134_dev *dev, struct saa7134_tvnorm *norm)
385 {
386 	video_dbg("set tv norm = %s\n", norm->name);
387 	dev->tvnorm = norm;
388 
389 	/* setup cropping */
390 	dev->crop_bounds.left    = norm->h_start;
391 	dev->crop_defrect.left   = norm->h_start;
392 	dev->crop_bounds.width   = norm->h_stop - norm->h_start +1;
393 	dev->crop_defrect.width  = norm->h_stop - norm->h_start +1;
394 
395 	dev->crop_bounds.top     = (norm->vbi_v_stop_0+1)*2;
396 	dev->crop_defrect.top    = norm->video_v_start*2;
397 	dev->crop_bounds.height  = ((norm->id & V4L2_STD_525_60) ? 524 : 624)
398 		- dev->crop_bounds.top;
399 	dev->crop_defrect.height = (norm->video_v_stop - norm->video_v_start +1)*2;
400 
401 	dev->crop_current = dev->crop_defrect;
402 
403 	saa7134_set_tvnorm_hw(dev);
404 }
405 
406 static void video_mux(struct saa7134_dev *dev, int input)
407 {
408 	video_dbg("video input = %d [%s]\n",
409 		  input, saa7134_input_name[card_in(dev, input).type]);
410 	dev->ctl_input = input;
411 	set_tvnorm(dev, dev->tvnorm);
412 	saa7134_tvaudio_setinput(dev, &card_in(dev, input));
413 }
414 
415 
416 static void saa7134_set_decoder(struct saa7134_dev *dev)
417 {
418 	int luma_control, sync_control, chroma_ctrl1, mux;
419 
420 	struct saa7134_tvnorm *norm = dev->tvnorm;
421 	mux = card_in(dev, dev->ctl_input).vmux;
422 
423 	luma_control = norm->luma_control;
424 	sync_control = norm->sync_control;
425 	chroma_ctrl1 = norm->chroma_ctrl1;
426 
427 	if (mux > 5)
428 		luma_control |= 0x80; /* svideo */
429 	if (noninterlaced || dev->nosignal)
430 		sync_control |= 0x20;
431 
432 	/* switch on auto standard detection */
433 	sync_control |= SAA7134_SYNC_CTRL_AUFD;
434 	chroma_ctrl1 |= SAA7134_CHROMA_CTRL1_AUTO0;
435 	chroma_ctrl1 &= ~SAA7134_CHROMA_CTRL1_FCTC;
436 	luma_control &= ~SAA7134_LUMA_CTRL_LDEL;
437 
438 	/* setup video decoder */
439 	saa_writeb(SAA7134_INCR_DELAY,            0x08);
440 	saa_writeb(SAA7134_ANALOG_IN_CTRL1,       0xc0 | mux);
441 	saa_writeb(SAA7134_ANALOG_IN_CTRL2,       0x00);
442 
443 	saa_writeb(SAA7134_ANALOG_IN_CTRL3,       0x90);
444 	saa_writeb(SAA7134_ANALOG_IN_CTRL4,       0x90);
445 	saa_writeb(SAA7134_HSYNC_START,           0xeb);
446 	saa_writeb(SAA7134_HSYNC_STOP,            0xe0);
447 	saa_writeb(SAA7134_SOURCE_TIMING1,        norm->src_timing);
448 
449 	saa_writeb(SAA7134_SYNC_CTRL,             sync_control);
450 	saa_writeb(SAA7134_LUMA_CTRL,             luma_control);
451 	saa_writeb(SAA7134_DEC_LUMA_BRIGHT,       dev->ctl_bright);
452 
453 	saa_writeb(SAA7134_DEC_LUMA_CONTRAST,
454 		dev->ctl_invert ? -dev->ctl_contrast : dev->ctl_contrast);
455 
456 	saa_writeb(SAA7134_DEC_CHROMA_SATURATION,
457 		dev->ctl_invert ? -dev->ctl_saturation : dev->ctl_saturation);
458 
459 	saa_writeb(SAA7134_DEC_CHROMA_HUE,        dev->ctl_hue);
460 	saa_writeb(SAA7134_CHROMA_CTRL1,          chroma_ctrl1);
461 	saa_writeb(SAA7134_CHROMA_GAIN,           norm->chroma_gain);
462 
463 	saa_writeb(SAA7134_CHROMA_CTRL2,          norm->chroma_ctrl2);
464 	saa_writeb(SAA7134_MODE_DELAY_CTRL,       0x00);
465 
466 	saa_writeb(SAA7134_ANALOG_ADC,            0x01);
467 	saa_writeb(SAA7134_VGATE_START,           0x11);
468 	saa_writeb(SAA7134_VGATE_STOP,            0xfe);
469 	saa_writeb(SAA7134_MISC_VGATE_MSB,        norm->vgate_misc);
470 	saa_writeb(SAA7134_RAW_DATA_GAIN,         0x40);
471 	saa_writeb(SAA7134_RAW_DATA_OFFSET,       0x80);
472 }
473 
474 void saa7134_set_tvnorm_hw(struct saa7134_dev *dev)
475 {
476 	saa7134_set_decoder(dev);
477 
478 	saa_call_all(dev, video, s_std, dev->tvnorm->id);
479 	/* Set the correct norm for the saa6752hs. This function
480 	   does nothing if there is no saa6752hs. */
481 	saa_call_empress(dev, video, s_std, dev->tvnorm->id);
482 }
483 
484 static void set_h_prescale(struct saa7134_dev *dev, int task, int prescale)
485 {
486 	static const struct {
487 		int xpsc;
488 		int xacl;
489 		int xc2_1;
490 		int xdcg;
491 		int vpfy;
492 	} vals[] = {
493 		/* XPSC XACL XC2_1 XDCG VPFY */
494 		{    1,   0,    0,    0,   0 },
495 		{    2,   2,    1,    2,   2 },
496 		{    3,   4,    1,    3,   2 },
497 		{    4,   8,    1,    4,   2 },
498 		{    5,   8,    1,    4,   2 },
499 		{    6,   8,    1,    4,   3 },
500 		{    7,   8,    1,    4,   3 },
501 		{    8,  15,    0,    4,   3 },
502 		{    9,  15,    0,    4,   3 },
503 		{   10,  16,    1,    5,   3 },
504 	};
505 	static const int count = ARRAY_SIZE(vals);
506 	int i;
507 
508 	for (i = 0; i < count; i++)
509 		if (vals[i].xpsc == prescale)
510 			break;
511 	if (i == count)
512 		return;
513 
514 	saa_writeb(SAA7134_H_PRESCALE(task), vals[i].xpsc);
515 	saa_writeb(SAA7134_ACC_LENGTH(task), vals[i].xacl);
516 	saa_writeb(SAA7134_LEVEL_CTRL(task),
517 		   (vals[i].xc2_1 << 3) | (vals[i].xdcg));
518 	saa_andorb(SAA7134_FIR_PREFILTER_CTRL(task), 0x0f,
519 		   (vals[i].vpfy << 2) | vals[i].vpfy);
520 }
521 
522 static void set_v_scale(struct saa7134_dev *dev, int task, int yscale)
523 {
524 	int val,mirror;
525 
526 	saa_writeb(SAA7134_V_SCALE_RATIO1(task), yscale &  0xff);
527 	saa_writeb(SAA7134_V_SCALE_RATIO2(task), yscale >> 8);
528 
529 	mirror = (dev->ctl_mirror) ? 0x02 : 0x00;
530 	if (yscale < 2048) {
531 		/* LPI */
532 		video_dbg("yscale LPI yscale=%d\n", yscale);
533 		saa_writeb(SAA7134_V_FILTER(task), 0x00 | mirror);
534 		saa_writeb(SAA7134_LUMA_CONTRAST(task), 0x40);
535 		saa_writeb(SAA7134_CHROMA_SATURATION(task), 0x40);
536 	} else {
537 		/* ACM */
538 		val = 0x40 * 1024 / yscale;
539 		video_dbg("yscale ACM yscale=%d val=0x%x\n", yscale, val);
540 		saa_writeb(SAA7134_V_FILTER(task), 0x01 | mirror);
541 		saa_writeb(SAA7134_LUMA_CONTRAST(task), val);
542 		saa_writeb(SAA7134_CHROMA_SATURATION(task), val);
543 	}
544 	saa_writeb(SAA7134_LUMA_BRIGHT(task),       0x80);
545 }
546 
547 static void set_size(struct saa7134_dev *dev, int task,
548 		     int width, int height, int interlace)
549 {
550 	int prescale,xscale,yscale,y_even,y_odd;
551 	int h_start, h_stop, v_start, v_stop;
552 	int div = interlace ? 2 : 1;
553 
554 	/* setup video scaler */
555 	h_start = dev->crop_current.left;
556 	v_start = dev->crop_current.top/2;
557 	h_stop  = (dev->crop_current.left + dev->crop_current.width -1);
558 	v_stop  = (dev->crop_current.top + dev->crop_current.height -1)/2;
559 
560 	saa_writeb(SAA7134_VIDEO_H_START1(task), h_start &  0xff);
561 	saa_writeb(SAA7134_VIDEO_H_START2(task), h_start >> 8);
562 	saa_writeb(SAA7134_VIDEO_H_STOP1(task),  h_stop  &  0xff);
563 	saa_writeb(SAA7134_VIDEO_H_STOP2(task),  h_stop  >> 8);
564 	saa_writeb(SAA7134_VIDEO_V_START1(task), v_start &  0xff);
565 	saa_writeb(SAA7134_VIDEO_V_START2(task), v_start >> 8);
566 	saa_writeb(SAA7134_VIDEO_V_STOP1(task),  v_stop  &  0xff);
567 	saa_writeb(SAA7134_VIDEO_V_STOP2(task),  v_stop  >> 8);
568 
569 	prescale = dev->crop_current.width / width;
570 	if (0 == prescale)
571 		prescale = 1;
572 	xscale = 1024 * dev->crop_current.width / prescale / width;
573 	yscale = 512 * div * dev->crop_current.height / height;
574 	video_dbg("prescale=%d xscale=%d yscale=%d\n",
575 		  prescale, xscale, yscale);
576 	set_h_prescale(dev,task,prescale);
577 	saa_writeb(SAA7134_H_SCALE_INC1(task),      xscale &  0xff);
578 	saa_writeb(SAA7134_H_SCALE_INC2(task),      xscale >> 8);
579 	set_v_scale(dev,task,yscale);
580 
581 	saa_writeb(SAA7134_VIDEO_PIXELS1(task),     width  & 0xff);
582 	saa_writeb(SAA7134_VIDEO_PIXELS2(task),     width  >> 8);
583 	saa_writeb(SAA7134_VIDEO_LINES1(task),      height/div & 0xff);
584 	saa_writeb(SAA7134_VIDEO_LINES2(task),      height/div >> 8);
585 
586 	/* deinterlace y offsets */
587 	y_odd  = dev->ctl_y_odd;
588 	y_even = dev->ctl_y_even;
589 	saa_writeb(SAA7134_V_PHASE_OFFSET0(task), y_odd);
590 	saa_writeb(SAA7134_V_PHASE_OFFSET1(task), y_even);
591 	saa_writeb(SAA7134_V_PHASE_OFFSET2(task), y_odd);
592 	saa_writeb(SAA7134_V_PHASE_OFFSET3(task), y_even);
593 }
594 
595 /* ------------------------------------------------------------------ */
596 
597 struct cliplist {
598 	__u16 position;
599 	__u8  enable;
600 	__u8  disable;
601 };
602 
603 static void set_cliplist(struct saa7134_dev *dev, int reg,
604 			struct cliplist *cl, int entries, char *name)
605 {
606 	__u8 winbits = 0;
607 	int i;
608 
609 	for (i = 0; i < entries; i++) {
610 		winbits |= cl[i].enable;
611 		winbits &= ~cl[i].disable;
612 		if (i < 15 && cl[i].position == cl[i+1].position)
613 			continue;
614 		saa_writeb(reg + 0, winbits);
615 		saa_writeb(reg + 2, cl[i].position & 0xff);
616 		saa_writeb(reg + 3, cl[i].position >> 8);
617 		video_dbg("clip: %s winbits=%02x pos=%d\n",
618 			name,winbits,cl[i].position);
619 		reg += 8;
620 	}
621 	for (; reg < 0x400; reg += 8) {
622 		saa_writeb(reg+ 0, 0);
623 		saa_writeb(reg + 1, 0);
624 		saa_writeb(reg + 2, 0);
625 		saa_writeb(reg + 3, 0);
626 	}
627 }
628 
629 static int clip_range(int val)
630 {
631 	if (val < 0)
632 		val = 0;
633 	return val;
634 }
635 
636 /* Sort into smallest position first order */
637 static int cliplist_cmp(const void *a, const void *b)
638 {
639 	const struct cliplist *cla = a;
640 	const struct cliplist *clb = b;
641 	if (cla->position < clb->position)
642 		return -1;
643 	if (cla->position > clb->position)
644 		return 1;
645 	return 0;
646 }
647 
648 static int setup_clipping(struct saa7134_dev *dev, struct v4l2_clip *clips,
649 			  int nclips, int interlace)
650 {
651 	struct cliplist col[16], row[16];
652 	int cols = 0, rows = 0, i;
653 	int div = interlace ? 2 : 1;
654 
655 	memset(col, 0, sizeof(col));
656 	memset(row, 0, sizeof(row));
657 	for (i = 0; i < nclips && i < 8; i++) {
658 		col[cols].position = clip_range(clips[i].c.left);
659 		col[cols].enable   = (1 << i);
660 		cols++;
661 		col[cols].position = clip_range(clips[i].c.left+clips[i].c.width);
662 		col[cols].disable  = (1 << i);
663 		cols++;
664 		row[rows].position = clip_range(clips[i].c.top / div);
665 		row[rows].enable   = (1 << i);
666 		rows++;
667 		row[rows].position = clip_range((clips[i].c.top + clips[i].c.height)
668 						/ div);
669 		row[rows].disable  = (1 << i);
670 		rows++;
671 	}
672 	sort(col, cols, sizeof col[0], cliplist_cmp, NULL);
673 	sort(row, rows, sizeof row[0], cliplist_cmp, NULL);
674 	set_cliplist(dev,0x380,col,cols,"cols");
675 	set_cliplist(dev,0x384,row,rows,"rows");
676 	return 0;
677 }
678 
679 static int verify_preview(struct saa7134_dev *dev, struct v4l2_window *win, bool try)
680 {
681 	enum v4l2_field field;
682 	int maxw, maxh;
683 
684 	if (!try && (dev->ovbuf.base == NULL || dev->ovfmt == NULL))
685 		return -EINVAL;
686 	if (win->w.width < 48)
687 		win->w.width = 48;
688 	if (win->w.height < 32)
689 		win->w.height = 32;
690 	if (win->clipcount > 8)
691 		win->clipcount = 8;
692 
693 	win->chromakey = 0;
694 	win->global_alpha = 0;
695 	field = win->field;
696 	maxw  = dev->crop_current.width;
697 	maxh  = dev->crop_current.height;
698 
699 	if (V4L2_FIELD_ANY == field) {
700 		field = (win->w.height > maxh/2)
701 			? V4L2_FIELD_INTERLACED
702 			: V4L2_FIELD_TOP;
703 	}
704 	switch (field) {
705 	case V4L2_FIELD_TOP:
706 	case V4L2_FIELD_BOTTOM:
707 		maxh = maxh / 2;
708 		break;
709 	default:
710 		field = V4L2_FIELD_INTERLACED;
711 		break;
712 	}
713 
714 	win->field = field;
715 	if (win->w.width > maxw)
716 		win->w.width = maxw;
717 	if (win->w.height > maxh)
718 		win->w.height = maxh;
719 	return 0;
720 }
721 
722 static int start_preview(struct saa7134_dev *dev)
723 {
724 	unsigned long base,control,bpl;
725 	int err;
726 
727 	err = verify_preview(dev, &dev->win, false);
728 	if (0 != err)
729 		return err;
730 
731 	dev->ovfield = dev->win.field;
732 	video_dbg("start_preview %dx%d+%d+%d %s field=%s\n",
733 		dev->win.w.width, dev->win.w.height,
734 		dev->win.w.left, dev->win.w.top,
735 		dev->ovfmt->name, v4l2_field_names[dev->ovfield]);
736 
737 	/* setup window + clipping */
738 	set_size(dev, TASK_B, dev->win.w.width, dev->win.w.height,
739 		 V4L2_FIELD_HAS_BOTH(dev->ovfield));
740 	setup_clipping(dev, dev->clips, dev->nclips,
741 		       V4L2_FIELD_HAS_BOTH(dev->ovfield));
742 	if (dev->ovfmt->yuv)
743 		saa_andorb(SAA7134_DATA_PATH(TASK_B), 0x3f, 0x03);
744 	else
745 		saa_andorb(SAA7134_DATA_PATH(TASK_B), 0x3f, 0x01);
746 	saa_writeb(SAA7134_OFMT_VIDEO_B, dev->ovfmt->pm | 0x20);
747 
748 	/* dma: setup channel 1 (= Video Task B) */
749 	base  = (unsigned long)dev->ovbuf.base;
750 	base += dev->ovbuf.fmt.bytesperline * dev->win.w.top;
751 	base += dev->ovfmt->depth/8         * dev->win.w.left;
752 	bpl   = dev->ovbuf.fmt.bytesperline;
753 	control = SAA7134_RS_CONTROL_BURST_16;
754 	if (dev->ovfmt->bswap)
755 		control |= SAA7134_RS_CONTROL_BSWAP;
756 	if (dev->ovfmt->wswap)
757 		control |= SAA7134_RS_CONTROL_WSWAP;
758 	if (V4L2_FIELD_HAS_BOTH(dev->ovfield)) {
759 		saa_writel(SAA7134_RS_BA1(1),base);
760 		saa_writel(SAA7134_RS_BA2(1),base+bpl);
761 		saa_writel(SAA7134_RS_PITCH(1),bpl*2);
762 		saa_writel(SAA7134_RS_CONTROL(1),control);
763 	} else {
764 		saa_writel(SAA7134_RS_BA1(1),base);
765 		saa_writel(SAA7134_RS_BA2(1),base);
766 		saa_writel(SAA7134_RS_PITCH(1),bpl);
767 		saa_writel(SAA7134_RS_CONTROL(1),control);
768 	}
769 
770 	/* start dma */
771 	dev->ovenable = 1;
772 	saa7134_set_dmabits(dev);
773 
774 	return 0;
775 }
776 
777 static int stop_preview(struct saa7134_dev *dev)
778 {
779 	dev->ovenable = 0;
780 	saa7134_set_dmabits(dev);
781 	return 0;
782 }
783 
784 /*
785  * Media Controller helper functions
786  */
787 
788 static int saa7134_enable_analog_tuner(struct saa7134_dev *dev)
789 {
790 #ifdef CONFIG_MEDIA_CONTROLLER
791 	struct media_device *mdev = dev->media_dev;
792 	struct media_entity *source;
793 	struct media_link *link, *found_link = NULL;
794 	int ret, active_links = 0;
795 
796 	if (!mdev || !dev->decoder)
797 		return 0;
798 
799 	/*
800 	 * This will find the tuner that is connected into the decoder.
801 	 * Technically, this is not 100% correct, as the device may be
802 	 * using an analog input instead of the tuner. However, as we can't
803 	 * do DVB streaming while the DMA engine is being used for V4L2,
804 	 * this should be enough for the actual needs.
805 	 */
806 	list_for_each_entry(link, &dev->decoder->links, list) {
807 		if (link->sink->entity == dev->decoder) {
808 			found_link = link;
809 			if (link->flags & MEDIA_LNK_FL_ENABLED)
810 				active_links++;
811 			break;
812 		}
813 	}
814 
815 	if (active_links == 1 || !found_link)
816 		return 0;
817 
818 	source = found_link->source->entity;
819 	list_for_each_entry(link, &source->links, list) {
820 		struct media_entity *sink;
821 		int flags = 0;
822 
823 		sink = link->sink->entity;
824 
825 		if (sink == dev->decoder)
826 			flags = MEDIA_LNK_FL_ENABLED;
827 
828 		ret = media_entity_setup_link(link, flags);
829 		if (ret) {
830 			pr_err("Couldn't change link %s->%s to %s. Error %d\n",
831 			       source->name, sink->name,
832 			       flags ? "enabled" : "disabled",
833 			       ret);
834 			return ret;
835 		}
836 	}
837 #endif
838 	return 0;
839 }
840 
841 /* ------------------------------------------------------------------ */
842 
843 static int buffer_activate(struct saa7134_dev *dev,
844 			   struct saa7134_buf *buf,
845 			   struct saa7134_buf *next)
846 {
847 	struct saa7134_dmaqueue *dmaq = buf->vb2.vb2_buf.vb2_queue->drv_priv;
848 	unsigned long base,control,bpl;
849 	unsigned long bpl_uv,lines_uv,base2,base3,tmp; /* planar */
850 
851 	video_dbg("buffer_activate buf=%p\n", buf);
852 	buf->top_seen = 0;
853 
854 	set_size(dev, TASK_A, dev->width, dev->height,
855 		 V4L2_FIELD_HAS_BOTH(dev->field));
856 	if (dev->fmt->yuv)
857 		saa_andorb(SAA7134_DATA_PATH(TASK_A), 0x3f, 0x03);
858 	else
859 		saa_andorb(SAA7134_DATA_PATH(TASK_A), 0x3f, 0x01);
860 	saa_writeb(SAA7134_OFMT_VIDEO_A, dev->fmt->pm);
861 
862 	/* DMA: setup channel 0 (= Video Task A0) */
863 	base  = saa7134_buffer_base(buf);
864 	if (dev->fmt->planar)
865 		bpl = dev->width;
866 	else
867 		bpl = (dev->width * dev->fmt->depth) / 8;
868 	control = SAA7134_RS_CONTROL_BURST_16 |
869 		SAA7134_RS_CONTROL_ME |
870 		(dmaq->pt.dma >> 12);
871 	if (dev->fmt->bswap)
872 		control |= SAA7134_RS_CONTROL_BSWAP;
873 	if (dev->fmt->wswap)
874 		control |= SAA7134_RS_CONTROL_WSWAP;
875 	if (V4L2_FIELD_HAS_BOTH(dev->field)) {
876 		/* interlaced */
877 		saa_writel(SAA7134_RS_BA1(0),base);
878 		saa_writel(SAA7134_RS_BA2(0),base+bpl);
879 		saa_writel(SAA7134_RS_PITCH(0),bpl*2);
880 	} else {
881 		/* non-interlaced */
882 		saa_writel(SAA7134_RS_BA1(0),base);
883 		saa_writel(SAA7134_RS_BA2(0),base);
884 		saa_writel(SAA7134_RS_PITCH(0),bpl);
885 	}
886 	saa_writel(SAA7134_RS_CONTROL(0),control);
887 
888 	if (dev->fmt->planar) {
889 		/* DMA: setup channel 4+5 (= planar task A) */
890 		bpl_uv   = bpl >> dev->fmt->hshift;
891 		lines_uv = dev->height >> dev->fmt->vshift;
892 		base2    = base + bpl * dev->height;
893 		base3    = base2 + bpl_uv * lines_uv;
894 		if (dev->fmt->uvswap)
895 			tmp = base2, base2 = base3, base3 = tmp;
896 		video_dbg("uv: bpl=%ld lines=%ld base2/3=%ld/%ld\n",
897 			bpl_uv,lines_uv,base2,base3);
898 		if (V4L2_FIELD_HAS_BOTH(dev->field)) {
899 			/* interlaced */
900 			saa_writel(SAA7134_RS_BA1(4),base2);
901 			saa_writel(SAA7134_RS_BA2(4),base2+bpl_uv);
902 			saa_writel(SAA7134_RS_PITCH(4),bpl_uv*2);
903 			saa_writel(SAA7134_RS_BA1(5),base3);
904 			saa_writel(SAA7134_RS_BA2(5),base3+bpl_uv);
905 			saa_writel(SAA7134_RS_PITCH(5),bpl_uv*2);
906 		} else {
907 			/* non-interlaced */
908 			saa_writel(SAA7134_RS_BA1(4),base2);
909 			saa_writel(SAA7134_RS_BA2(4),base2);
910 			saa_writel(SAA7134_RS_PITCH(4),bpl_uv);
911 			saa_writel(SAA7134_RS_BA1(5),base3);
912 			saa_writel(SAA7134_RS_BA2(5),base3);
913 			saa_writel(SAA7134_RS_PITCH(5),bpl_uv);
914 		}
915 		saa_writel(SAA7134_RS_CONTROL(4),control);
916 		saa_writel(SAA7134_RS_CONTROL(5),control);
917 	}
918 
919 	/* start DMA */
920 	saa7134_set_dmabits(dev);
921 	mod_timer(&dmaq->timeout, jiffies + BUFFER_TIMEOUT);
922 	return 0;
923 }
924 
925 static int buffer_init(struct vb2_buffer *vb2)
926 {
927 	struct saa7134_dmaqueue *dmaq = vb2->vb2_queue->drv_priv;
928 	struct vb2_v4l2_buffer *vbuf = to_vb2_v4l2_buffer(vb2);
929 	struct saa7134_buf *buf = container_of(vbuf, struct saa7134_buf, vb2);
930 
931 	dmaq->curr = NULL;
932 	buf->activate = buffer_activate;
933 	return 0;
934 }
935 
936 static int buffer_prepare(struct vb2_buffer *vb2)
937 {
938 	struct saa7134_dmaqueue *dmaq = vb2->vb2_queue->drv_priv;
939 	struct saa7134_dev *dev = dmaq->dev;
940 	struct vb2_v4l2_buffer *vbuf = to_vb2_v4l2_buffer(vb2);
941 	struct saa7134_buf *buf = container_of(vbuf, struct saa7134_buf, vb2);
942 	struct sg_table *dma = vb2_dma_sg_plane_desc(vb2, 0);
943 	unsigned int size;
944 
945 	if (dma->sgl->offset) {
946 		pr_err("The buffer is not page-aligned\n");
947 		return -EINVAL;
948 	}
949 	size = (dev->width * dev->height * dev->fmt->depth) >> 3;
950 	if (vb2_plane_size(vb2, 0) < size)
951 		return -EINVAL;
952 
953 	vb2_set_plane_payload(vb2, 0, size);
954 	vbuf->field = dev->field;
955 
956 	return saa7134_pgtable_build(dev->pci, &dmaq->pt, dma->sgl, dma->nents,
957 				    saa7134_buffer_startpage(buf));
958 }
959 
960 static int queue_setup(struct vb2_queue *q,
961 			   unsigned int *nbuffers, unsigned int *nplanes,
962 			   unsigned int sizes[], struct device *alloc_devs[])
963 {
964 	struct saa7134_dmaqueue *dmaq = q->drv_priv;
965 	struct saa7134_dev *dev = dmaq->dev;
966 	int size = dev->fmt->depth * dev->width * dev->height >> 3;
967 
968 	if (dev->width    < 48 ||
969 	    dev->height   < 32 ||
970 	    dev->width/4  > dev->crop_current.width  ||
971 	    dev->height/4 > dev->crop_current.height ||
972 	    dev->width    > dev->crop_bounds.width  ||
973 	    dev->height   > dev->crop_bounds.height)
974 		return -EINVAL;
975 
976 	*nbuffers = saa7134_buffer_count(size, *nbuffers);
977 	*nplanes = 1;
978 	sizes[0] = size;
979 
980 	saa7134_enable_analog_tuner(dev);
981 
982 	return 0;
983 }
984 
985 /*
986  * move buffer to hardware queue
987  */
988 void saa7134_vb2_buffer_queue(struct vb2_buffer *vb)
989 {
990 	struct saa7134_dmaqueue *dmaq = vb->vb2_queue->drv_priv;
991 	struct saa7134_dev *dev = dmaq->dev;
992 	struct vb2_v4l2_buffer *vbuf = to_vb2_v4l2_buffer(vb);
993 	struct saa7134_buf *buf = container_of(vbuf, struct saa7134_buf, vb2);
994 
995 	saa7134_buffer_queue(dev, dmaq, buf);
996 }
997 EXPORT_SYMBOL_GPL(saa7134_vb2_buffer_queue);
998 
999 int saa7134_vb2_start_streaming(struct vb2_queue *vq, unsigned int count)
1000 {
1001 	struct saa7134_dmaqueue *dmaq = vq->drv_priv;
1002 	struct saa7134_dev *dev = dmaq->dev;
1003 
1004 	/*
1005 	 * Planar video capture and TS share the same DMA channel,
1006 	 * so only one can be active at a time.
1007 	 */
1008 	if (card_is_empress(dev) && vb2_is_busy(&dev->empress_vbq) &&
1009 	    dmaq == &dev->video_q && dev->fmt->planar) {
1010 		struct saa7134_buf *buf, *tmp;
1011 
1012 		list_for_each_entry_safe(buf, tmp, &dmaq->queue, entry) {
1013 			list_del(&buf->entry);
1014 			vb2_buffer_done(&buf->vb2.vb2_buf,
1015 					VB2_BUF_STATE_QUEUED);
1016 		}
1017 		if (dmaq->curr) {
1018 			vb2_buffer_done(&dmaq->curr->vb2.vb2_buf,
1019 					VB2_BUF_STATE_QUEUED);
1020 			dmaq->curr = NULL;
1021 		}
1022 		return -EBUSY;
1023 	}
1024 
1025 	/* The SAA7134 has a 1K FIFO; the datasheet suggests that when
1026 	 * configured conservatively, there's 22 usec of buffering for video.
1027 	 * We therefore request a DMA latency of 20 usec, giving us 2 usec of
1028 	 * margin in case the FIFO is configured differently to the datasheet.
1029 	 * Unfortunately, I lack register-level documentation to check the
1030 	 * Linux FIFO setup and confirm the perfect value.
1031 	 */
1032 	if ((dmaq == &dev->video_q && !vb2_is_streaming(&dev->vbi_vbq)) ||
1033 	    (dmaq == &dev->vbi_q && !vb2_is_streaming(&dev->video_vbq)))
1034 		pm_qos_add_request(&dev->qos_request,
1035 			PM_QOS_CPU_DMA_LATENCY, 20);
1036 	dmaq->seq_nr = 0;
1037 
1038 	return 0;
1039 }
1040 
1041 void saa7134_vb2_stop_streaming(struct vb2_queue *vq)
1042 {
1043 	struct saa7134_dmaqueue *dmaq = vq->drv_priv;
1044 	struct saa7134_dev *dev = dmaq->dev;
1045 
1046 	saa7134_stop_streaming(dev, dmaq);
1047 
1048 	if ((dmaq == &dev->video_q && !vb2_is_streaming(&dev->vbi_vbq)) ||
1049 	    (dmaq == &dev->vbi_q && !vb2_is_streaming(&dev->video_vbq)))
1050 		pm_qos_remove_request(&dev->qos_request);
1051 }
1052 
1053 static const struct vb2_ops vb2_qops = {
1054 	.queue_setup	= queue_setup,
1055 	.buf_init	= buffer_init,
1056 	.buf_prepare	= buffer_prepare,
1057 	.buf_queue	= saa7134_vb2_buffer_queue,
1058 	.wait_prepare	= vb2_ops_wait_prepare,
1059 	.wait_finish	= vb2_ops_wait_finish,
1060 	.start_streaming = saa7134_vb2_start_streaming,
1061 	.stop_streaming = saa7134_vb2_stop_streaming,
1062 };
1063 
1064 /* ------------------------------------------------------------------ */
1065 
1066 static int saa7134_s_ctrl(struct v4l2_ctrl *ctrl)
1067 {
1068 	struct saa7134_dev *dev = container_of(ctrl->handler, struct saa7134_dev, ctrl_handler);
1069 	unsigned long flags;
1070 	int restart_overlay = 0;
1071 
1072 	switch (ctrl->id) {
1073 	case V4L2_CID_BRIGHTNESS:
1074 		dev->ctl_bright = ctrl->val;
1075 		saa_writeb(SAA7134_DEC_LUMA_BRIGHT, ctrl->val);
1076 		break;
1077 	case V4L2_CID_HUE:
1078 		dev->ctl_hue = ctrl->val;
1079 		saa_writeb(SAA7134_DEC_CHROMA_HUE, ctrl->val);
1080 		break;
1081 	case V4L2_CID_CONTRAST:
1082 		dev->ctl_contrast = ctrl->val;
1083 		saa_writeb(SAA7134_DEC_LUMA_CONTRAST,
1084 			   dev->ctl_invert ? -dev->ctl_contrast : dev->ctl_contrast);
1085 		break;
1086 	case V4L2_CID_SATURATION:
1087 		dev->ctl_saturation = ctrl->val;
1088 		saa_writeb(SAA7134_DEC_CHROMA_SATURATION,
1089 			   dev->ctl_invert ? -dev->ctl_saturation : dev->ctl_saturation);
1090 		break;
1091 	case V4L2_CID_AUDIO_MUTE:
1092 		dev->ctl_mute = ctrl->val;
1093 		saa7134_tvaudio_setmute(dev);
1094 		break;
1095 	case V4L2_CID_AUDIO_VOLUME:
1096 		dev->ctl_volume = ctrl->val;
1097 		saa7134_tvaudio_setvolume(dev,dev->ctl_volume);
1098 		break;
1099 	case V4L2_CID_PRIVATE_INVERT:
1100 		dev->ctl_invert = ctrl->val;
1101 		saa_writeb(SAA7134_DEC_LUMA_CONTRAST,
1102 			   dev->ctl_invert ? -dev->ctl_contrast : dev->ctl_contrast);
1103 		saa_writeb(SAA7134_DEC_CHROMA_SATURATION,
1104 			   dev->ctl_invert ? -dev->ctl_saturation : dev->ctl_saturation);
1105 		break;
1106 	case V4L2_CID_HFLIP:
1107 		dev->ctl_mirror = ctrl->val;
1108 		restart_overlay = 1;
1109 		break;
1110 	case V4L2_CID_PRIVATE_Y_EVEN:
1111 		dev->ctl_y_even = ctrl->val;
1112 		restart_overlay = 1;
1113 		break;
1114 	case V4L2_CID_PRIVATE_Y_ODD:
1115 		dev->ctl_y_odd = ctrl->val;
1116 		restart_overlay = 1;
1117 		break;
1118 	case V4L2_CID_PRIVATE_AUTOMUTE:
1119 	{
1120 		struct v4l2_priv_tun_config tda9887_cfg;
1121 
1122 		tda9887_cfg.tuner = TUNER_TDA9887;
1123 		tda9887_cfg.priv = &dev->tda9887_conf;
1124 
1125 		dev->ctl_automute = ctrl->val;
1126 		if (dev->tda9887_conf) {
1127 			if (dev->ctl_automute)
1128 				dev->tda9887_conf |= TDA9887_AUTOMUTE;
1129 			else
1130 				dev->tda9887_conf &= ~TDA9887_AUTOMUTE;
1131 
1132 			saa_call_all(dev, tuner, s_config, &tda9887_cfg);
1133 		}
1134 		break;
1135 	}
1136 	default:
1137 		return -EINVAL;
1138 	}
1139 	if (restart_overlay && dev->overlay_owner) {
1140 		spin_lock_irqsave(&dev->slock, flags);
1141 		stop_preview(dev);
1142 		start_preview(dev);
1143 		spin_unlock_irqrestore(&dev->slock, flags);
1144 	}
1145 	return 0;
1146 }
1147 
1148 /* ------------------------------------------------------------------ */
1149 
1150 static int video_open(struct file *file)
1151 {
1152 	struct video_device *vdev = video_devdata(file);
1153 	struct saa7134_dev *dev = video_drvdata(file);
1154 	int ret = v4l2_fh_open(file);
1155 
1156 	if (ret < 0)
1157 		return ret;
1158 
1159 	mutex_lock(&dev->lock);
1160 	if (vdev->vfl_type == VFL_TYPE_RADIO) {
1161 		/* switch to radio mode */
1162 		saa7134_tvaudio_setinput(dev, &card(dev).radio);
1163 		saa_call_all(dev, tuner, s_radio);
1164 	} else {
1165 		/* switch to video/vbi mode */
1166 		video_mux(dev, dev->ctl_input);
1167 	}
1168 	mutex_unlock(&dev->lock);
1169 
1170 	return 0;
1171 }
1172 
1173 static int video_release(struct file *file)
1174 {
1175 	struct video_device *vdev = video_devdata(file);
1176 	struct saa7134_dev *dev = video_drvdata(file);
1177 	struct v4l2_fh *fh = file->private_data;
1178 	struct saa6588_command cmd;
1179 	unsigned long flags;
1180 
1181 	mutex_lock(&dev->lock);
1182 	saa7134_tvaudio_close(dev);
1183 
1184 	/* turn off overlay */
1185 	if (fh == dev->overlay_owner) {
1186 		spin_lock_irqsave(&dev->slock,flags);
1187 		stop_preview(dev);
1188 		spin_unlock_irqrestore(&dev->slock,flags);
1189 		dev->overlay_owner = NULL;
1190 	}
1191 
1192 	if (vdev->vfl_type == VFL_TYPE_RADIO)
1193 		v4l2_fh_release(file);
1194 	else
1195 		_vb2_fop_release(file, NULL);
1196 
1197 	/* ts-capture will not work in planar mode, so turn it off Hac: 04.05*/
1198 	saa_andorb(SAA7134_OFMT_VIDEO_A, 0x1f, 0);
1199 	saa_andorb(SAA7134_OFMT_VIDEO_B, 0x1f, 0);
1200 	saa_andorb(SAA7134_OFMT_DATA_A, 0x1f, 0);
1201 	saa_andorb(SAA7134_OFMT_DATA_B, 0x1f, 0);
1202 
1203 	saa_call_all(dev, core, s_power, 0);
1204 	if (vdev->vfl_type == VFL_TYPE_RADIO)
1205 		saa_call_all(dev, core, ioctl, SAA6588_CMD_CLOSE, &cmd);
1206 	mutex_unlock(&dev->lock);
1207 
1208 	return 0;
1209 }
1210 
1211 static ssize_t radio_read(struct file *file, char __user *data,
1212 			 size_t count, loff_t *ppos)
1213 {
1214 	struct saa7134_dev *dev = video_drvdata(file);
1215 	struct saa6588_command cmd;
1216 
1217 	cmd.block_count = count/3;
1218 	cmd.nonblocking = file->f_flags & O_NONBLOCK;
1219 	cmd.buffer = data;
1220 	cmd.instance = file;
1221 	cmd.result = -ENODEV;
1222 
1223 	mutex_lock(&dev->lock);
1224 	saa_call_all(dev, core, ioctl, SAA6588_CMD_READ, &cmd);
1225 	mutex_unlock(&dev->lock);
1226 
1227 	return cmd.result;
1228 }
1229 
1230 static unsigned int radio_poll(struct file *file, poll_table *wait)
1231 {
1232 	struct saa7134_dev *dev = video_drvdata(file);
1233 	struct saa6588_command cmd;
1234 	unsigned int rc = v4l2_ctrl_poll(file, wait);
1235 
1236 	cmd.instance = file;
1237 	cmd.event_list = wait;
1238 	cmd.result = 0;
1239 	mutex_lock(&dev->lock);
1240 	saa_call_all(dev, core, ioctl, SAA6588_CMD_POLL, &cmd);
1241 	mutex_unlock(&dev->lock);
1242 
1243 	return rc | cmd.result;
1244 }
1245 
1246 /* ------------------------------------------------------------------ */
1247 
1248 static int saa7134_try_get_set_fmt_vbi_cap(struct file *file, void *priv,
1249 						struct v4l2_format *f)
1250 {
1251 	struct saa7134_dev *dev = video_drvdata(file);
1252 	struct saa7134_tvnorm *norm = dev->tvnorm;
1253 
1254 	memset(&f->fmt.vbi.reserved, 0, sizeof(f->fmt.vbi.reserved));
1255 	f->fmt.vbi.sampling_rate = 6750000 * 4;
1256 	f->fmt.vbi.samples_per_line = 2048 /* VBI_LINE_LENGTH */;
1257 	f->fmt.vbi.sample_format = V4L2_PIX_FMT_GREY;
1258 	f->fmt.vbi.offset = 64 * 4;
1259 	f->fmt.vbi.start[0] = norm->vbi_v_start_0;
1260 	f->fmt.vbi.count[0] = norm->vbi_v_stop_0 - norm->vbi_v_start_0 +1;
1261 	f->fmt.vbi.start[1] = norm->vbi_v_start_1;
1262 	f->fmt.vbi.count[1] = f->fmt.vbi.count[0];
1263 	f->fmt.vbi.flags = 0; /* VBI_UNSYNC VBI_INTERLACED */
1264 
1265 	return 0;
1266 }
1267 
1268 static int saa7134_g_fmt_vid_cap(struct file *file, void *priv,
1269 				struct v4l2_format *f)
1270 {
1271 	struct saa7134_dev *dev = video_drvdata(file);
1272 
1273 	f->fmt.pix.width        = dev->width;
1274 	f->fmt.pix.height       = dev->height;
1275 	f->fmt.pix.field        = dev->field;
1276 	f->fmt.pix.pixelformat  = dev->fmt->fourcc;
1277 	if (dev->fmt->planar)
1278 		f->fmt.pix.bytesperline = f->fmt.pix.width;
1279 	else
1280 		f->fmt.pix.bytesperline =
1281 			(f->fmt.pix.width * dev->fmt->depth) / 8;
1282 	f->fmt.pix.sizeimage =
1283 		(f->fmt.pix.height * f->fmt.pix.width * dev->fmt->depth) / 8;
1284 	f->fmt.pix.colorspace   = V4L2_COLORSPACE_SMPTE170M;
1285 	return 0;
1286 }
1287 
1288 static int saa7134_g_fmt_vid_overlay(struct file *file, void *priv,
1289 				struct v4l2_format *f)
1290 {
1291 	struct saa7134_dev *dev = video_drvdata(file);
1292 	struct v4l2_clip __user *clips = f->fmt.win.clips;
1293 	u32 clipcount = f->fmt.win.clipcount;
1294 	int err = 0;
1295 	int i;
1296 
1297 	if (saa7134_no_overlay > 0) {
1298 		pr_err("V4L2_BUF_TYPE_VIDEO_OVERLAY: no_overlay\n");
1299 		return -EINVAL;
1300 	}
1301 	f->fmt.win = dev->win;
1302 	f->fmt.win.clips = clips;
1303 	if (clips == NULL)
1304 		clipcount = 0;
1305 	if (dev->nclips < clipcount)
1306 		clipcount = dev->nclips;
1307 	f->fmt.win.clipcount = clipcount;
1308 
1309 	for (i = 0; !err && i < clipcount; i++) {
1310 		if (copy_to_user(&f->fmt.win.clips[i].c, &dev->clips[i].c,
1311 					sizeof(struct v4l2_rect)))
1312 			err = -EFAULT;
1313 	}
1314 
1315 	return err;
1316 }
1317 
1318 static int saa7134_try_fmt_vid_cap(struct file *file, void *priv,
1319 						struct v4l2_format *f)
1320 {
1321 	struct saa7134_dev *dev = video_drvdata(file);
1322 	struct saa7134_format *fmt;
1323 	enum v4l2_field field;
1324 	unsigned int maxw, maxh;
1325 
1326 	fmt = format_by_fourcc(f->fmt.pix.pixelformat);
1327 	if (NULL == fmt)
1328 		return -EINVAL;
1329 
1330 	field = f->fmt.pix.field;
1331 	maxw  = min(dev->crop_current.width*4,  dev->crop_bounds.width);
1332 	maxh  = min(dev->crop_current.height*4, dev->crop_bounds.height);
1333 
1334 	if (V4L2_FIELD_ANY == field) {
1335 		field = (f->fmt.pix.height > maxh/2)
1336 			? V4L2_FIELD_INTERLACED
1337 			: V4L2_FIELD_BOTTOM;
1338 	}
1339 	switch (field) {
1340 	case V4L2_FIELD_TOP:
1341 	case V4L2_FIELD_BOTTOM:
1342 		maxh = maxh / 2;
1343 		break;
1344 	default:
1345 		field = V4L2_FIELD_INTERLACED;
1346 		break;
1347 	}
1348 
1349 	f->fmt.pix.field = field;
1350 	if (f->fmt.pix.width  < 48)
1351 		f->fmt.pix.width  = 48;
1352 	if (f->fmt.pix.height < 32)
1353 		f->fmt.pix.height = 32;
1354 	if (f->fmt.pix.width > maxw)
1355 		f->fmt.pix.width = maxw;
1356 	if (f->fmt.pix.height > maxh)
1357 		f->fmt.pix.height = maxh;
1358 	f->fmt.pix.width &= ~0x03;
1359 	if (fmt->planar)
1360 		f->fmt.pix.bytesperline = f->fmt.pix.width;
1361 	else
1362 		f->fmt.pix.bytesperline =
1363 			(f->fmt.pix.width * fmt->depth) / 8;
1364 	f->fmt.pix.sizeimage =
1365 		(f->fmt.pix.height * f->fmt.pix.width * fmt->depth) / 8;
1366 	f->fmt.pix.colorspace   = V4L2_COLORSPACE_SMPTE170M;
1367 
1368 	return 0;
1369 }
1370 
1371 static int saa7134_try_fmt_vid_overlay(struct file *file, void *priv,
1372 						struct v4l2_format *f)
1373 {
1374 	struct saa7134_dev *dev = video_drvdata(file);
1375 
1376 	if (saa7134_no_overlay > 0) {
1377 		pr_err("V4L2_BUF_TYPE_VIDEO_OVERLAY: no_overlay\n");
1378 		return -EINVAL;
1379 	}
1380 
1381 	if (f->fmt.win.clips == NULL)
1382 		f->fmt.win.clipcount = 0;
1383 	return verify_preview(dev, &f->fmt.win, true);
1384 }
1385 
1386 static int saa7134_s_fmt_vid_cap(struct file *file, void *priv,
1387 					struct v4l2_format *f)
1388 {
1389 	struct saa7134_dev *dev = video_drvdata(file);
1390 	int err;
1391 
1392 	err = saa7134_try_fmt_vid_cap(file, priv, f);
1393 	if (0 != err)
1394 		return err;
1395 
1396 	dev->fmt = format_by_fourcc(f->fmt.pix.pixelformat);
1397 	dev->width = f->fmt.pix.width;
1398 	dev->height = f->fmt.pix.height;
1399 	dev->field = f->fmt.pix.field;
1400 	return 0;
1401 }
1402 
1403 static int saa7134_s_fmt_vid_overlay(struct file *file, void *priv,
1404 					struct v4l2_format *f)
1405 {
1406 	struct saa7134_dev *dev = video_drvdata(file);
1407 	int err;
1408 	unsigned long flags;
1409 
1410 	if (saa7134_no_overlay > 0) {
1411 		pr_err("V4L2_BUF_TYPE_VIDEO_OVERLAY: no_overlay\n");
1412 		return -EINVAL;
1413 	}
1414 	if (f->fmt.win.clips == NULL)
1415 		f->fmt.win.clipcount = 0;
1416 	err = verify_preview(dev, &f->fmt.win, true);
1417 	if (0 != err)
1418 		return err;
1419 
1420 	dev->win    = f->fmt.win;
1421 	dev->nclips = f->fmt.win.clipcount;
1422 
1423 	if (copy_from_user(dev->clips, f->fmt.win.clips,
1424 			   sizeof(struct v4l2_clip) * dev->nclips))
1425 		return -EFAULT;
1426 
1427 	if (priv == dev->overlay_owner) {
1428 		spin_lock_irqsave(&dev->slock, flags);
1429 		stop_preview(dev);
1430 		start_preview(dev);
1431 		spin_unlock_irqrestore(&dev->slock, flags);
1432 	}
1433 
1434 	return 0;
1435 }
1436 
1437 int saa7134_enum_input(struct file *file, void *priv, struct v4l2_input *i)
1438 {
1439 	struct saa7134_dev *dev = video_drvdata(file);
1440 	unsigned int n;
1441 
1442 	n = i->index;
1443 	if (n >= SAA7134_INPUT_MAX)
1444 		return -EINVAL;
1445 	if (card_in(dev, i->index).type == SAA7134_NO_INPUT)
1446 		return -EINVAL;
1447 	i->index = n;
1448 	strcpy(i->name, saa7134_input_name[card_in(dev, n).type]);
1449 	switch (card_in(dev, n).type) {
1450 	case SAA7134_INPUT_TV:
1451 	case SAA7134_INPUT_TV_MONO:
1452 		i->type = V4L2_INPUT_TYPE_TUNER;
1453 		break;
1454 	default:
1455 		i->type  = V4L2_INPUT_TYPE_CAMERA;
1456 		break;
1457 	}
1458 	if (n == dev->ctl_input) {
1459 		int v1 = saa_readb(SAA7134_STATUS_VIDEO1);
1460 		int v2 = saa_readb(SAA7134_STATUS_VIDEO2);
1461 
1462 		if (0 != (v1 & 0x40))
1463 			i->status |= V4L2_IN_ST_NO_H_LOCK;
1464 		if (0 != (v2 & 0x40))
1465 			i->status |= V4L2_IN_ST_NO_SIGNAL;
1466 		if (0 != (v2 & 0x0e))
1467 			i->status |= V4L2_IN_ST_MACROVISION;
1468 	}
1469 	i->std = SAA7134_NORMS;
1470 	return 0;
1471 }
1472 EXPORT_SYMBOL_GPL(saa7134_enum_input);
1473 
1474 int saa7134_g_input(struct file *file, void *priv, unsigned int *i)
1475 {
1476 	struct saa7134_dev *dev = video_drvdata(file);
1477 
1478 	*i = dev->ctl_input;
1479 	return 0;
1480 }
1481 EXPORT_SYMBOL_GPL(saa7134_g_input);
1482 
1483 int saa7134_s_input(struct file *file, void *priv, unsigned int i)
1484 {
1485 	struct saa7134_dev *dev = video_drvdata(file);
1486 
1487 	if (i >= SAA7134_INPUT_MAX)
1488 		return -EINVAL;
1489 	if (card_in(dev, i).type == SAA7134_NO_INPUT)
1490 		return -EINVAL;
1491 	video_mux(dev, i);
1492 	return 0;
1493 }
1494 EXPORT_SYMBOL_GPL(saa7134_s_input);
1495 
1496 int saa7134_querycap(struct file *file, void *priv,
1497 					struct v4l2_capability *cap)
1498 {
1499 	struct saa7134_dev *dev = video_drvdata(file);
1500 	struct video_device *vdev = video_devdata(file);
1501 	u32 radio_caps, video_caps, vbi_caps;
1502 
1503 	unsigned int tuner_type = dev->tuner_type;
1504 
1505 	strcpy(cap->driver, "saa7134");
1506 	strlcpy(cap->card, saa7134_boards[dev->board].name,
1507 		sizeof(cap->card));
1508 	sprintf(cap->bus_info, "PCI:%s", pci_name(dev->pci));
1509 
1510 	cap->device_caps = V4L2_CAP_READWRITE | V4L2_CAP_STREAMING;
1511 	if ((tuner_type != TUNER_ABSENT) && (tuner_type != UNSET))
1512 		cap->device_caps |= V4L2_CAP_TUNER;
1513 
1514 	radio_caps = V4L2_CAP_RADIO;
1515 	if (dev->has_rds)
1516 		radio_caps |= V4L2_CAP_RDS_CAPTURE;
1517 
1518 	video_caps = V4L2_CAP_VIDEO_CAPTURE;
1519 	if (saa7134_no_overlay <= 0 && !is_empress(file))
1520 		video_caps |= V4L2_CAP_VIDEO_OVERLAY;
1521 
1522 	vbi_caps = V4L2_CAP_VBI_CAPTURE;
1523 
1524 	switch (vdev->vfl_type) {
1525 	case VFL_TYPE_RADIO:
1526 		cap->device_caps |= radio_caps;
1527 		break;
1528 	case VFL_TYPE_GRABBER:
1529 		cap->device_caps |= video_caps;
1530 		break;
1531 	case VFL_TYPE_VBI:
1532 		cap->device_caps |= vbi_caps;
1533 		break;
1534 	}
1535 	cap->capabilities = radio_caps | video_caps | vbi_caps |
1536 		cap->device_caps | V4L2_CAP_DEVICE_CAPS;
1537 	if (vdev->vfl_type == VFL_TYPE_RADIO) {
1538 		cap->device_caps &= ~V4L2_CAP_STREAMING;
1539 		if (!dev->has_rds)
1540 			cap->device_caps &= ~V4L2_CAP_READWRITE;
1541 	}
1542 
1543 	return 0;
1544 }
1545 EXPORT_SYMBOL_GPL(saa7134_querycap);
1546 
1547 int saa7134_s_std(struct file *file, void *priv, v4l2_std_id id)
1548 {
1549 	struct saa7134_dev *dev = video_drvdata(file);
1550 	struct v4l2_fh *fh = priv;
1551 	unsigned long flags;
1552 	unsigned int i;
1553 	v4l2_std_id fixup;
1554 
1555 	if (is_empress(file) && dev->overlay_owner) {
1556 		/* Don't change the std from the mpeg device
1557 		   if overlay is active. */
1558 		return -EBUSY;
1559 	}
1560 
1561 	for (i = 0; i < TVNORMS; i++)
1562 		if (id == tvnorms[i].id)
1563 			break;
1564 
1565 	if (i == TVNORMS)
1566 		for (i = 0; i < TVNORMS; i++)
1567 			if (id & tvnorms[i].id)
1568 				break;
1569 	if (i == TVNORMS)
1570 		return -EINVAL;
1571 
1572 	if ((id & V4L2_STD_SECAM) && (secam[0] != '-')) {
1573 		if (secam[0] == 'L' || secam[0] == 'l') {
1574 			if (secam[1] == 'C' || secam[1] == 'c')
1575 				fixup = V4L2_STD_SECAM_LC;
1576 			else
1577 				fixup = V4L2_STD_SECAM_L;
1578 		} else {
1579 			if (secam[0] == 'D' || secam[0] == 'd')
1580 				fixup = V4L2_STD_SECAM_DK;
1581 			else
1582 				fixup = V4L2_STD_SECAM;
1583 		}
1584 		for (i = 0; i < TVNORMS; i++) {
1585 			if (fixup == tvnorms[i].id)
1586 				break;
1587 		}
1588 		if (i == TVNORMS)
1589 			return -EINVAL;
1590 	}
1591 
1592 	id = tvnorms[i].id;
1593 
1594 	if (!is_empress(file) && fh == dev->overlay_owner) {
1595 		spin_lock_irqsave(&dev->slock, flags);
1596 		stop_preview(dev);
1597 		spin_unlock_irqrestore(&dev->slock, flags);
1598 
1599 		set_tvnorm(dev, &tvnorms[i]);
1600 
1601 		spin_lock_irqsave(&dev->slock, flags);
1602 		start_preview(dev);
1603 		spin_unlock_irqrestore(&dev->slock, flags);
1604 	} else
1605 		set_tvnorm(dev, &tvnorms[i]);
1606 
1607 	saa7134_tvaudio_do_scan(dev);
1608 	return 0;
1609 }
1610 EXPORT_SYMBOL_GPL(saa7134_s_std);
1611 
1612 int saa7134_g_std(struct file *file, void *priv, v4l2_std_id *id)
1613 {
1614 	struct saa7134_dev *dev = video_drvdata(file);
1615 
1616 	*id = dev->tvnorm->id;
1617 	return 0;
1618 }
1619 EXPORT_SYMBOL_GPL(saa7134_g_std);
1620 
1621 static v4l2_std_id saa7134_read_std(struct saa7134_dev *dev)
1622 {
1623 	static v4l2_std_id stds[] = {
1624 		V4L2_STD_UNKNOWN,
1625 		V4L2_STD_NTSC,
1626 		V4L2_STD_PAL,
1627 		V4L2_STD_SECAM };
1628 
1629 	v4l2_std_id result = 0;
1630 
1631 	u8 st1 = saa_readb(SAA7134_STATUS_VIDEO1);
1632 	u8 st2 = saa_readb(SAA7134_STATUS_VIDEO2);
1633 
1634 	if (!(st2 & 0x1)) /* RDCAP == 0 */
1635 		result = V4L2_STD_UNKNOWN;
1636 	else
1637 		result = stds[st1 & 0x03];
1638 
1639 	return result;
1640 }
1641 
1642 int saa7134_querystd(struct file *file, void *priv, v4l2_std_id *std)
1643 {
1644 	struct saa7134_dev *dev = video_drvdata(file);
1645 	*std &= saa7134_read_std(dev);
1646 	return 0;
1647 }
1648 EXPORT_SYMBOL_GPL(saa7134_querystd);
1649 
1650 static int saa7134_cropcap(struct file *file, void *priv,
1651 					struct v4l2_cropcap *cap)
1652 {
1653 	struct saa7134_dev *dev = video_drvdata(file);
1654 
1655 	if (cap->type != V4L2_BUF_TYPE_VIDEO_CAPTURE &&
1656 	    cap->type != V4L2_BUF_TYPE_VIDEO_OVERLAY)
1657 		return -EINVAL;
1658 	cap->pixelaspect.numerator   = 1;
1659 	cap->pixelaspect.denominator = 1;
1660 	if (dev->tvnorm->id & V4L2_STD_525_60) {
1661 		cap->pixelaspect.numerator   = 11;
1662 		cap->pixelaspect.denominator = 10;
1663 	}
1664 	if (dev->tvnorm->id & V4L2_STD_625_50) {
1665 		cap->pixelaspect.numerator   = 54;
1666 		cap->pixelaspect.denominator = 59;
1667 	}
1668 	return 0;
1669 }
1670 
1671 static int saa7134_g_selection(struct file *file, void *f, struct v4l2_selection *sel)
1672 {
1673 	struct saa7134_dev *dev = video_drvdata(file);
1674 
1675 	if (sel->type != V4L2_BUF_TYPE_VIDEO_CAPTURE &&
1676 	    sel->type != V4L2_BUF_TYPE_VIDEO_OVERLAY)
1677 		return -EINVAL;
1678 
1679 	switch (sel->target) {
1680 	case V4L2_SEL_TGT_CROP:
1681 		sel->r = dev->crop_current;
1682 		break;
1683 	case V4L2_SEL_TGT_CROP_DEFAULT:
1684 		sel->r = dev->crop_defrect;
1685 		break;
1686 	case V4L2_SEL_TGT_CROP_BOUNDS:
1687 		sel->r  = dev->crop_bounds;
1688 		break;
1689 	default:
1690 		return -EINVAL;
1691 	}
1692 	return 0;
1693 }
1694 
1695 static int saa7134_s_selection(struct file *file, void *f, struct v4l2_selection *sel)
1696 {
1697 	struct saa7134_dev *dev = video_drvdata(file);
1698 	struct v4l2_rect *b = &dev->crop_bounds;
1699 	struct v4l2_rect *c = &dev->crop_current;
1700 
1701 	if (sel->type != V4L2_BUF_TYPE_VIDEO_CAPTURE &&
1702 	    sel->type != V4L2_BUF_TYPE_VIDEO_OVERLAY)
1703 		return -EINVAL;
1704 
1705 	if (sel->target != V4L2_SEL_TGT_CROP)
1706 		return -EINVAL;
1707 
1708 	if (dev->overlay_owner)
1709 		return -EBUSY;
1710 	if (vb2_is_streaming(&dev->video_vbq))
1711 		return -EBUSY;
1712 
1713 	*c = sel->r;
1714 	if (c->top < b->top)
1715 		c->top = b->top;
1716 	if (c->top > b->top + b->height)
1717 		c->top = b->top + b->height;
1718 	if (c->height > b->top - c->top + b->height)
1719 		c->height = b->top - c->top + b->height;
1720 
1721 	if (c->left < b->left)
1722 		c->left = b->left;
1723 	if (c->left > b->left + b->width)
1724 		c->left = b->left + b->width;
1725 	if (c->width > b->left - c->left + b->width)
1726 		c->width = b->left - c->left + b->width;
1727 	sel->r = *c;
1728 	return 0;
1729 }
1730 
1731 int saa7134_g_tuner(struct file *file, void *priv,
1732 					struct v4l2_tuner *t)
1733 {
1734 	struct saa7134_dev *dev = video_drvdata(file);
1735 	int n;
1736 
1737 	if (0 != t->index)
1738 		return -EINVAL;
1739 	memset(t, 0, sizeof(*t));
1740 	for (n = 0; n < SAA7134_INPUT_MAX; n++) {
1741 		if (card_in(dev, n).type == SAA7134_INPUT_TV ||
1742 		    card_in(dev, n).type == SAA7134_INPUT_TV_MONO)
1743 			break;
1744 	}
1745 	if (n == SAA7134_INPUT_MAX)
1746 		return -EINVAL;
1747 	if (card_in(dev, n).type != SAA7134_NO_INPUT) {
1748 		strcpy(t->name, "Television");
1749 		t->type = V4L2_TUNER_ANALOG_TV;
1750 		saa_call_all(dev, tuner, g_tuner, t);
1751 		t->capability = V4L2_TUNER_CAP_NORM |
1752 			V4L2_TUNER_CAP_STEREO |
1753 			V4L2_TUNER_CAP_LANG1 |
1754 			V4L2_TUNER_CAP_LANG2;
1755 		t->rxsubchans = saa7134_tvaudio_getstereo(dev);
1756 		t->audmode = saa7134_tvaudio_rx2mode(t->rxsubchans);
1757 	}
1758 	if (0 != (saa_readb(SAA7134_STATUS_VIDEO1) & 0x03))
1759 		t->signal = 0xffff;
1760 	return 0;
1761 }
1762 EXPORT_SYMBOL_GPL(saa7134_g_tuner);
1763 
1764 int saa7134_s_tuner(struct file *file, void *priv,
1765 					const struct v4l2_tuner *t)
1766 {
1767 	struct saa7134_dev *dev = video_drvdata(file);
1768 	int rx, mode;
1769 
1770 	if (0 != t->index)
1771 		return -EINVAL;
1772 
1773 	mode = dev->thread.mode;
1774 	if (UNSET == mode) {
1775 		rx   = saa7134_tvaudio_getstereo(dev);
1776 		mode = saa7134_tvaudio_rx2mode(rx);
1777 	}
1778 	if (mode != t->audmode)
1779 		dev->thread.mode = t->audmode;
1780 
1781 	return 0;
1782 }
1783 EXPORT_SYMBOL_GPL(saa7134_s_tuner);
1784 
1785 int saa7134_g_frequency(struct file *file, void *priv,
1786 					struct v4l2_frequency *f)
1787 {
1788 	struct saa7134_dev *dev = video_drvdata(file);
1789 
1790 	if (0 != f->tuner)
1791 		return -EINVAL;
1792 
1793 	saa_call_all(dev, tuner, g_frequency, f);
1794 
1795 	return 0;
1796 }
1797 EXPORT_SYMBOL_GPL(saa7134_g_frequency);
1798 
1799 int saa7134_s_frequency(struct file *file, void *priv,
1800 					const struct v4l2_frequency *f)
1801 {
1802 	struct saa7134_dev *dev = video_drvdata(file);
1803 
1804 	if (0 != f->tuner)
1805 		return -EINVAL;
1806 
1807 	saa_call_all(dev, tuner, s_frequency, f);
1808 
1809 	saa7134_tvaudio_do_scan(dev);
1810 	return 0;
1811 }
1812 EXPORT_SYMBOL_GPL(saa7134_s_frequency);
1813 
1814 static int saa7134_enum_fmt_vid_cap(struct file *file, void  *priv,
1815 					struct v4l2_fmtdesc *f)
1816 {
1817 	if (f->index >= FORMATS)
1818 		return -EINVAL;
1819 
1820 	strlcpy(f->description, formats[f->index].name,
1821 		sizeof(f->description));
1822 
1823 	f->pixelformat = formats[f->index].fourcc;
1824 
1825 	return 0;
1826 }
1827 
1828 static int saa7134_enum_fmt_vid_overlay(struct file *file, void  *priv,
1829 					struct v4l2_fmtdesc *f)
1830 {
1831 	if (saa7134_no_overlay > 0) {
1832 		pr_err("V4L2_BUF_TYPE_VIDEO_OVERLAY: no_overlay\n");
1833 		return -EINVAL;
1834 	}
1835 
1836 	if ((f->index >= FORMATS) || formats[f->index].planar)
1837 		return -EINVAL;
1838 
1839 	strlcpy(f->description, formats[f->index].name,
1840 		sizeof(f->description));
1841 
1842 	f->pixelformat = formats[f->index].fourcc;
1843 
1844 	return 0;
1845 }
1846 
1847 static int saa7134_g_fbuf(struct file *file, void *f,
1848 				struct v4l2_framebuffer *fb)
1849 {
1850 	struct saa7134_dev *dev = video_drvdata(file);
1851 
1852 	*fb = dev->ovbuf;
1853 	fb->capability = V4L2_FBUF_CAP_LIST_CLIPPING;
1854 
1855 	return 0;
1856 }
1857 
1858 static int saa7134_s_fbuf(struct file *file, void *f,
1859 					const struct v4l2_framebuffer *fb)
1860 {
1861 	struct saa7134_dev *dev = video_drvdata(file);
1862 	struct saa7134_format *fmt;
1863 
1864 	if (!capable(CAP_SYS_ADMIN) &&
1865 	   !capable(CAP_SYS_RAWIO))
1866 		return -EPERM;
1867 
1868 	/* check args */
1869 	fmt = format_by_fourcc(fb->fmt.pixelformat);
1870 	if (NULL == fmt)
1871 		return -EINVAL;
1872 
1873 	/* ok, accept it */
1874 	dev->ovbuf = *fb;
1875 	dev->ovfmt = fmt;
1876 	if (0 == dev->ovbuf.fmt.bytesperline)
1877 		dev->ovbuf.fmt.bytesperline =
1878 			dev->ovbuf.fmt.width*fmt->depth/8;
1879 	return 0;
1880 }
1881 
1882 static int saa7134_overlay(struct file *file, void *priv, unsigned int on)
1883 {
1884 	struct saa7134_dev *dev = video_drvdata(file);
1885 	unsigned long flags;
1886 
1887 	if (on) {
1888 		if (saa7134_no_overlay > 0) {
1889 			video_dbg("no_overlay\n");
1890 			return -EINVAL;
1891 		}
1892 
1893 		if (dev->overlay_owner && priv != dev->overlay_owner)
1894 			return -EBUSY;
1895 		dev->overlay_owner = priv;
1896 		spin_lock_irqsave(&dev->slock, flags);
1897 		start_preview(dev);
1898 		spin_unlock_irqrestore(&dev->slock, flags);
1899 	}
1900 	if (!on) {
1901 		if (priv != dev->overlay_owner)
1902 			return -EINVAL;
1903 		spin_lock_irqsave(&dev->slock, flags);
1904 		stop_preview(dev);
1905 		spin_unlock_irqrestore(&dev->slock, flags);
1906 		dev->overlay_owner = NULL;
1907 	}
1908 	return 0;
1909 }
1910 
1911 #ifdef CONFIG_VIDEO_ADV_DEBUG
1912 static int vidioc_g_register (struct file *file, void *priv,
1913 			      struct v4l2_dbg_register *reg)
1914 {
1915 	struct saa7134_dev *dev = video_drvdata(file);
1916 
1917 	reg->val = saa_readb(reg->reg & 0xffffff);
1918 	reg->size = 1;
1919 	return 0;
1920 }
1921 
1922 static int vidioc_s_register (struct file *file, void *priv,
1923 				const struct v4l2_dbg_register *reg)
1924 {
1925 	struct saa7134_dev *dev = video_drvdata(file);
1926 
1927 	saa_writeb(reg->reg & 0xffffff, reg->val);
1928 	return 0;
1929 }
1930 #endif
1931 
1932 static int radio_g_tuner(struct file *file, void *priv,
1933 					struct v4l2_tuner *t)
1934 {
1935 	struct saa7134_dev *dev = video_drvdata(file);
1936 
1937 	if (0 != t->index)
1938 		return -EINVAL;
1939 
1940 	strcpy(t->name, "Radio");
1941 
1942 	saa_call_all(dev, tuner, g_tuner, t);
1943 	t->audmode &= V4L2_TUNER_MODE_MONO | V4L2_TUNER_MODE_STEREO;
1944 	if (dev->input->amux == TV) {
1945 		t->signal = 0xf800 - ((saa_readb(0x581) & 0x1f) << 11);
1946 		t->rxsubchans = (saa_readb(0x529) & 0x08) ?
1947 				V4L2_TUNER_SUB_STEREO : V4L2_TUNER_SUB_MONO;
1948 	}
1949 	return 0;
1950 }
1951 static int radio_s_tuner(struct file *file, void *priv,
1952 					const struct v4l2_tuner *t)
1953 {
1954 	struct saa7134_dev *dev = video_drvdata(file);
1955 
1956 	if (0 != t->index)
1957 		return -EINVAL;
1958 
1959 	saa_call_all(dev, tuner, s_tuner, t);
1960 	return 0;
1961 }
1962 
1963 static const struct v4l2_file_operations video_fops =
1964 {
1965 	.owner	  = THIS_MODULE,
1966 	.open	  = video_open,
1967 	.release  = video_release,
1968 	.read	  = vb2_fop_read,
1969 	.poll     = vb2_fop_poll,
1970 	.mmap	  = vb2_fop_mmap,
1971 	.unlocked_ioctl	  = video_ioctl2,
1972 };
1973 
1974 static const struct v4l2_ioctl_ops video_ioctl_ops = {
1975 	.vidioc_querycap		= saa7134_querycap,
1976 	.vidioc_enum_fmt_vid_cap	= saa7134_enum_fmt_vid_cap,
1977 	.vidioc_g_fmt_vid_cap		= saa7134_g_fmt_vid_cap,
1978 	.vidioc_try_fmt_vid_cap		= saa7134_try_fmt_vid_cap,
1979 	.vidioc_s_fmt_vid_cap		= saa7134_s_fmt_vid_cap,
1980 	.vidioc_enum_fmt_vid_overlay	= saa7134_enum_fmt_vid_overlay,
1981 	.vidioc_g_fmt_vid_overlay	= saa7134_g_fmt_vid_overlay,
1982 	.vidioc_try_fmt_vid_overlay	= saa7134_try_fmt_vid_overlay,
1983 	.vidioc_s_fmt_vid_overlay	= saa7134_s_fmt_vid_overlay,
1984 	.vidioc_g_fmt_vbi_cap		= saa7134_try_get_set_fmt_vbi_cap,
1985 	.vidioc_try_fmt_vbi_cap		= saa7134_try_get_set_fmt_vbi_cap,
1986 	.vidioc_s_fmt_vbi_cap		= saa7134_try_get_set_fmt_vbi_cap,
1987 	.vidioc_cropcap			= saa7134_cropcap,
1988 	.vidioc_reqbufs			= vb2_ioctl_reqbufs,
1989 	.vidioc_querybuf		= vb2_ioctl_querybuf,
1990 	.vidioc_qbuf			= vb2_ioctl_qbuf,
1991 	.vidioc_dqbuf			= vb2_ioctl_dqbuf,
1992 	.vidioc_expbuf			= vb2_ioctl_expbuf,
1993 	.vidioc_s_std			= saa7134_s_std,
1994 	.vidioc_g_std			= saa7134_g_std,
1995 	.vidioc_querystd		= saa7134_querystd,
1996 	.vidioc_enum_input		= saa7134_enum_input,
1997 	.vidioc_g_input			= saa7134_g_input,
1998 	.vidioc_s_input			= saa7134_s_input,
1999 	.vidioc_streamon		= vb2_ioctl_streamon,
2000 	.vidioc_streamoff		= vb2_ioctl_streamoff,
2001 	.vidioc_g_tuner			= saa7134_g_tuner,
2002 	.vidioc_s_tuner			= saa7134_s_tuner,
2003 	.vidioc_g_selection		= saa7134_g_selection,
2004 	.vidioc_s_selection		= saa7134_s_selection,
2005 	.vidioc_g_fbuf			= saa7134_g_fbuf,
2006 	.vidioc_s_fbuf			= saa7134_s_fbuf,
2007 	.vidioc_overlay			= saa7134_overlay,
2008 	.vidioc_g_frequency		= saa7134_g_frequency,
2009 	.vidioc_s_frequency		= saa7134_s_frequency,
2010 #ifdef CONFIG_VIDEO_ADV_DEBUG
2011 	.vidioc_g_register              = vidioc_g_register,
2012 	.vidioc_s_register              = vidioc_s_register,
2013 #endif
2014 	.vidioc_log_status		= v4l2_ctrl_log_status,
2015 	.vidioc_subscribe_event		= v4l2_ctrl_subscribe_event,
2016 	.vidioc_unsubscribe_event	= v4l2_event_unsubscribe,
2017 };
2018 
2019 static const struct v4l2_file_operations radio_fops = {
2020 	.owner	  = THIS_MODULE,
2021 	.open	  = video_open,
2022 	.read     = radio_read,
2023 	.release  = video_release,
2024 	.unlocked_ioctl	= video_ioctl2,
2025 	.poll     = radio_poll,
2026 };
2027 
2028 static const struct v4l2_ioctl_ops radio_ioctl_ops = {
2029 	.vidioc_querycap	= saa7134_querycap,
2030 	.vidioc_g_tuner		= radio_g_tuner,
2031 	.vidioc_s_tuner		= radio_s_tuner,
2032 	.vidioc_g_frequency	= saa7134_g_frequency,
2033 	.vidioc_s_frequency	= saa7134_s_frequency,
2034 	.vidioc_subscribe_event	= v4l2_ctrl_subscribe_event,
2035 	.vidioc_unsubscribe_event = v4l2_event_unsubscribe,
2036 };
2037 
2038 /* ----------------------------------------------------------- */
2039 /* exported stuff                                              */
2040 
2041 struct video_device saa7134_video_template = {
2042 	.name				= "saa7134-video",
2043 	.fops				= &video_fops,
2044 	.ioctl_ops 			= &video_ioctl_ops,
2045 	.tvnorms			= SAA7134_NORMS,
2046 };
2047 
2048 struct video_device saa7134_radio_template = {
2049 	.name			= "saa7134-radio",
2050 	.fops			= &radio_fops,
2051 	.ioctl_ops 		= &radio_ioctl_ops,
2052 };
2053 
2054 static const struct v4l2_ctrl_ops saa7134_ctrl_ops = {
2055 	.s_ctrl = saa7134_s_ctrl,
2056 };
2057 
2058 static const struct v4l2_ctrl_config saa7134_ctrl_invert = {
2059 	.ops = &saa7134_ctrl_ops,
2060 	.id = V4L2_CID_PRIVATE_INVERT,
2061 	.name = "Invert",
2062 	.type = V4L2_CTRL_TYPE_BOOLEAN,
2063 	.min = 0,
2064 	.max = 1,
2065 	.step = 1,
2066 };
2067 
2068 static const struct v4l2_ctrl_config saa7134_ctrl_y_odd = {
2069 	.ops = &saa7134_ctrl_ops,
2070 	.id = V4L2_CID_PRIVATE_Y_ODD,
2071 	.name = "Y Offset Odd Field",
2072 	.type = V4L2_CTRL_TYPE_INTEGER,
2073 	.min = 0,
2074 	.max = 128,
2075 	.step = 1,
2076 };
2077 
2078 static const struct v4l2_ctrl_config saa7134_ctrl_y_even = {
2079 	.ops = &saa7134_ctrl_ops,
2080 	.id = V4L2_CID_PRIVATE_Y_EVEN,
2081 	.name = "Y Offset Even Field",
2082 	.type = V4L2_CTRL_TYPE_INTEGER,
2083 	.min = 0,
2084 	.max = 128,
2085 	.step = 1,
2086 };
2087 
2088 static const struct v4l2_ctrl_config saa7134_ctrl_automute = {
2089 	.ops = &saa7134_ctrl_ops,
2090 	.id = V4L2_CID_PRIVATE_AUTOMUTE,
2091 	.name = "Automute",
2092 	.type = V4L2_CTRL_TYPE_BOOLEAN,
2093 	.min = 0,
2094 	.max = 1,
2095 	.step = 1,
2096 	.def = 1,
2097 };
2098 
2099 int saa7134_video_init1(struct saa7134_dev *dev)
2100 {
2101 	struct v4l2_ctrl_handler *hdl = &dev->ctrl_handler;
2102 	struct vb2_queue *q;
2103 	int ret;
2104 
2105 	/* sanitycheck insmod options */
2106 	if (gbuffers < 2 || gbuffers > VIDEO_MAX_FRAME)
2107 		gbuffers = 2;
2108 	if (gbufsize > gbufsize_max)
2109 		gbufsize = gbufsize_max;
2110 	gbufsize = (gbufsize + PAGE_SIZE - 1) & PAGE_MASK;
2111 
2112 	v4l2_ctrl_handler_init(hdl, 11);
2113 	v4l2_ctrl_new_std(hdl, &saa7134_ctrl_ops,
2114 			V4L2_CID_BRIGHTNESS, 0, 255, 1, 128);
2115 	v4l2_ctrl_new_std(hdl, &saa7134_ctrl_ops,
2116 			V4L2_CID_CONTRAST, 0, 127, 1, 68);
2117 	v4l2_ctrl_new_std(hdl, &saa7134_ctrl_ops,
2118 			V4L2_CID_SATURATION, 0, 127, 1, 64);
2119 	v4l2_ctrl_new_std(hdl, &saa7134_ctrl_ops,
2120 			V4L2_CID_HUE, -128, 127, 1, 0);
2121 	v4l2_ctrl_new_std(hdl, &saa7134_ctrl_ops,
2122 			V4L2_CID_HFLIP, 0, 1, 1, 0);
2123 	v4l2_ctrl_new_std(hdl, &saa7134_ctrl_ops,
2124 			V4L2_CID_AUDIO_MUTE, 0, 1, 1, 0);
2125 	v4l2_ctrl_new_std(hdl, &saa7134_ctrl_ops,
2126 			V4L2_CID_AUDIO_VOLUME, -15, 15, 1, 0);
2127 	v4l2_ctrl_new_custom(hdl, &saa7134_ctrl_invert, NULL);
2128 	v4l2_ctrl_new_custom(hdl, &saa7134_ctrl_y_odd, NULL);
2129 	v4l2_ctrl_new_custom(hdl, &saa7134_ctrl_y_even, NULL);
2130 	v4l2_ctrl_new_custom(hdl, &saa7134_ctrl_automute, NULL);
2131 	if (hdl->error)
2132 		return hdl->error;
2133 	if (card_has_radio(dev)) {
2134 		hdl = &dev->radio_ctrl_handler;
2135 		v4l2_ctrl_handler_init(hdl, 2);
2136 		v4l2_ctrl_add_handler(hdl, &dev->ctrl_handler,
2137 				v4l2_ctrl_radio_filter);
2138 		if (hdl->error)
2139 			return hdl->error;
2140 	}
2141 	dev->ctl_mute       = 1;
2142 
2143 	if (dev->tda9887_conf && saa7134_ctrl_automute.def)
2144 		dev->tda9887_conf |= TDA9887_AUTOMUTE;
2145 	dev->automute       = 0;
2146 
2147 	INIT_LIST_HEAD(&dev->video_q.queue);
2148 	setup_timer(&dev->video_q.timeout, saa7134_buffer_timeout,
2149 		    (unsigned long)(&dev->video_q));
2150 	dev->video_q.dev              = dev;
2151 	dev->fmt = format_by_fourcc(V4L2_PIX_FMT_BGR24);
2152 	dev->width    = 720;
2153 	dev->height   = 576;
2154 	dev->field = V4L2_FIELD_INTERLACED;
2155 	dev->win.w.width = dev->width;
2156 	dev->win.w.height = dev->height;
2157 	dev->win.field = V4L2_FIELD_INTERLACED;
2158 	dev->ovbuf.fmt.width = dev->width;
2159 	dev->ovbuf.fmt.height = dev->height;
2160 	dev->ovbuf.fmt.pixelformat = dev->fmt->fourcc;
2161 	dev->ovbuf.fmt.colorspace = V4L2_COLORSPACE_SMPTE170M;
2162 
2163 	if (saa7134_boards[dev->board].video_out)
2164 		saa7134_videoport_init(dev);
2165 
2166 	q = &dev->video_vbq;
2167 	q->type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
2168 	/*
2169 	 * Do not add VB2_USERPTR unless explicitly requested: the saa7134 DMA
2170 	 * engine cannot handle transfers that do not start at the beginning
2171 	 * of a page. A user-provided pointer can start anywhere in a page, so
2172 	 * USERPTR support is a no-go unless the application knows about these
2173 	 * limitations and has special support for this.
2174 	 */
2175 	q->io_modes = VB2_MMAP | VB2_DMABUF | VB2_READ;
2176 	if (saa7134_userptr)
2177 		q->io_modes |= VB2_USERPTR;
2178 	q->drv_priv = &dev->video_q;
2179 	q->ops = &vb2_qops;
2180 	q->gfp_flags = GFP_DMA32;
2181 	q->mem_ops = &vb2_dma_sg_memops;
2182 	q->buf_struct_size = sizeof(struct saa7134_buf);
2183 	q->timestamp_flags = V4L2_BUF_FLAG_TIMESTAMP_MONOTONIC;
2184 	q->lock = &dev->lock;
2185 	q->dev = &dev->pci->dev;
2186 	ret = vb2_queue_init(q);
2187 	if (ret)
2188 		return ret;
2189 	saa7134_pgtable_alloc(dev->pci, &dev->video_q.pt);
2190 
2191 	q = &dev->vbi_vbq;
2192 	q->type = V4L2_BUF_TYPE_VBI_CAPTURE;
2193 	/* Don't add VB2_USERPTR, see comment above */
2194 	q->io_modes = VB2_MMAP | VB2_READ;
2195 	if (saa7134_userptr)
2196 		q->io_modes |= VB2_USERPTR;
2197 	q->drv_priv = &dev->vbi_q;
2198 	q->ops = &saa7134_vbi_qops;
2199 	q->gfp_flags = GFP_DMA32;
2200 	q->mem_ops = &vb2_dma_sg_memops;
2201 	q->buf_struct_size = sizeof(struct saa7134_buf);
2202 	q->timestamp_flags = V4L2_BUF_FLAG_TIMESTAMP_MONOTONIC;
2203 	q->lock = &dev->lock;
2204 	q->dev = &dev->pci->dev;
2205 	ret = vb2_queue_init(q);
2206 	if (ret)
2207 		return ret;
2208 	saa7134_pgtable_alloc(dev->pci, &dev->vbi_q.pt);
2209 
2210 	return 0;
2211 }
2212 
2213 void saa7134_video_fini(struct saa7134_dev *dev)
2214 {
2215 	/* free stuff */
2216 	vb2_queue_release(&dev->video_vbq);
2217 	saa7134_pgtable_free(dev->pci, &dev->video_q.pt);
2218 	vb2_queue_release(&dev->vbi_vbq);
2219 	saa7134_pgtable_free(dev->pci, &dev->vbi_q.pt);
2220 	v4l2_ctrl_handler_free(&dev->ctrl_handler);
2221 	if (card_has_radio(dev))
2222 		v4l2_ctrl_handler_free(&dev->radio_ctrl_handler);
2223 }
2224 
2225 int saa7134_videoport_init(struct saa7134_dev *dev)
2226 {
2227 	/* enable video output */
2228 	int vo = saa7134_boards[dev->board].video_out;
2229 	int video_reg;
2230 	unsigned int vid_port_opts = saa7134_boards[dev->board].vid_port_opts;
2231 
2232 	/* Configure videoport */
2233 	saa_writeb(SAA7134_VIDEO_PORT_CTRL0, video_out[vo][0]);
2234 	video_reg = video_out[vo][1];
2235 	if (vid_port_opts & SET_T_CODE_POLARITY_NON_INVERTED)
2236 		video_reg &= ~VP_T_CODE_P_INVERTED;
2237 	saa_writeb(SAA7134_VIDEO_PORT_CTRL1, video_reg);
2238 	saa_writeb(SAA7134_VIDEO_PORT_CTRL2, video_out[vo][2]);
2239 	saa_writeb(SAA7134_VIDEO_PORT_CTRL4, video_out[vo][4]);
2240 	video_reg = video_out[vo][5];
2241 	if (vid_port_opts & SET_CLOCK_NOT_DELAYED)
2242 		video_reg &= ~VP_CLK_CTRL2_DELAYED;
2243 	if (vid_port_opts & SET_CLOCK_INVERTED)
2244 		video_reg |= VP_CLK_CTRL1_INVERTED;
2245 	saa_writeb(SAA7134_VIDEO_PORT_CTRL5, video_reg);
2246 	video_reg = video_out[vo][6];
2247 	if (vid_port_opts & SET_VSYNC_OFF) {
2248 		video_reg &= ~VP_VS_TYPE_MASK;
2249 		video_reg |= VP_VS_TYPE_OFF;
2250 	}
2251 	saa_writeb(SAA7134_VIDEO_PORT_CTRL6, video_reg);
2252 	saa_writeb(SAA7134_VIDEO_PORT_CTRL7, video_out[vo][7]);
2253 	saa_writeb(SAA7134_VIDEO_PORT_CTRL8, video_out[vo][8]);
2254 
2255 	/* Start videoport */
2256 	saa_writeb(SAA7134_VIDEO_PORT_CTRL3, video_out[vo][3]);
2257 
2258 	return 0;
2259 }
2260 
2261 int saa7134_video_init2(struct saa7134_dev *dev)
2262 {
2263 	/* init video hw */
2264 	set_tvnorm(dev,&tvnorms[0]);
2265 	video_mux(dev,0);
2266 	v4l2_ctrl_handler_setup(&dev->ctrl_handler);
2267 	saa7134_tvaudio_setmute(dev);
2268 	saa7134_tvaudio_setvolume(dev,dev->ctl_volume);
2269 	return 0;
2270 }
2271 
2272 void saa7134_irq_video_signalchange(struct saa7134_dev *dev)
2273 {
2274 	static const char *st[] = {
2275 		"(no signal)", "NTSC", "PAL", "SECAM" };
2276 	u32 st1,st2;
2277 
2278 	st1 = saa_readb(SAA7134_STATUS_VIDEO1);
2279 	st2 = saa_readb(SAA7134_STATUS_VIDEO2);
2280 	video_dbg("DCSDT: pll: %s, sync: %s, norm: %s\n",
2281 		(st1 & 0x40) ? "not locked" : "locked",
2282 		(st2 & 0x40) ? "no"         : "yes",
2283 		st[st1 & 0x03]);
2284 	dev->nosignal = (st1 & 0x40) || (st2 & 0x40)  || !(st2 & 0x1);
2285 
2286 	if (dev->nosignal) {
2287 		/* no video signal -> mute audio */
2288 		if (dev->ctl_automute)
2289 			dev->automute = 1;
2290 		saa7134_tvaudio_setmute(dev);
2291 	} else {
2292 		/* wake up tvaudio audio carrier scan thread */
2293 		saa7134_tvaudio_do_scan(dev);
2294 	}
2295 
2296 	if ((st2 & 0x80) && !noninterlaced && !dev->nosignal)
2297 		saa_clearb(SAA7134_SYNC_CTRL, 0x20);
2298 	else
2299 		saa_setb(SAA7134_SYNC_CTRL, 0x20);
2300 
2301 	if (dev->mops && dev->mops->signal_change)
2302 		dev->mops->signal_change(dev);
2303 }
2304 
2305 
2306 void saa7134_irq_video_done(struct saa7134_dev *dev, unsigned long status)
2307 {
2308 	enum v4l2_field field;
2309 
2310 	spin_lock(&dev->slock);
2311 	if (dev->video_q.curr) {
2312 		field = dev->field;
2313 		if (V4L2_FIELD_HAS_BOTH(field)) {
2314 			/* make sure we have seen both fields */
2315 			if ((status & 0x10) == 0x00) {
2316 				dev->video_q.curr->top_seen = 1;
2317 				goto done;
2318 			}
2319 			if (!dev->video_q.curr->top_seen)
2320 				goto done;
2321 		} else if (field == V4L2_FIELD_TOP) {
2322 			if ((status & 0x10) != 0x10)
2323 				goto done;
2324 		} else if (field == V4L2_FIELD_BOTTOM) {
2325 			if ((status & 0x10) != 0x00)
2326 				goto done;
2327 		}
2328 		saa7134_buffer_finish(dev, &dev->video_q, VB2_BUF_STATE_DONE);
2329 	}
2330 	saa7134_buffer_next(dev, &dev->video_q);
2331 
2332  done:
2333 	spin_unlock(&dev->slock);
2334 }
2335