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