]> Git Repo - linux.git/blob - drivers/media/pci/bt8xx/bttv-driver.c
net: bgmac: Fix return value check for fixed_phy_register()
[linux.git] / drivers / media / pci / bt8xx / bttv-driver.c
1 // SPDX-License-Identifier: GPL-2.0-or-later
2 /*
3
4     bttv - Bt848 frame grabber driver
5
6     Copyright (C) 1996,97,98 Ralph  Metzler <[email protected]>
7                            & Marcus Metzler <[email protected]>
8     (c) 1999-2002 Gerd Knorr <[email protected]>
9
10     some v4l2 code lines are taken from Justin's bttv2 driver which is
11     (c) 2000 Justin Schoeman <[email protected]>
12
13     V4L1 removal from:
14     (c) 2005-2006 Nickolay V. Shmyrev <[email protected]>
15
16     Fixes to be fully V4L2 compliant by
17     (c) 2006 Mauro Carvalho Chehab <[email protected]>
18
19     Cropping and overscan support
20     Copyright (C) 2005, 2006 Michael H. Schimek <[email protected]>
21     Sponsored by OPQ Systems AB
22
23 */
24
25 #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
26
27 #include <linux/init.h>
28 #include <linux/module.h>
29 #include <linux/delay.h>
30 #include <linux/slab.h>
31 #include <linux/errno.h>
32 #include <linux/fs.h>
33 #include <linux/kernel.h>
34 #include <linux/sched.h>
35 #include <linux/interrupt.h>
36 #include <linux/kdev_t.h>
37 #include "bttvp.h"
38 #include <media/v4l2-common.h>
39 #include <media/v4l2-ioctl.h>
40 #include <media/v4l2-event.h>
41 #include <media/i2c/tvaudio.h>
42 #include <media/drv-intf/msp3400.h>
43
44 #include <linux/dma-mapping.h>
45
46 #include <asm/io.h>
47 #include <asm/byteorder.h>
48
49 #include <media/i2c/saa6588.h>
50
51 #define BTTV_VERSION "0.9.19"
52
53 unsigned int bttv_num;                  /* number of Bt848s in use */
54 struct bttv *bttvs[BTTV_MAX];
55
56 unsigned int bttv_debug;
57 unsigned int bttv_verbose = 1;
58 unsigned int bttv_gpio;
59
60 /* config variables */
61 #ifdef __BIG_ENDIAN
62 static unsigned int bigendian=1;
63 #else
64 static unsigned int bigendian;
65 #endif
66 static unsigned int radio[BTTV_MAX];
67 static unsigned int irq_debug;
68 static unsigned int gbuffers = 8;
69 static unsigned int gbufsize = 0x208000;
70 static unsigned int reset_crop = 1;
71
72 static int video_nr[BTTV_MAX] = { [0 ... (BTTV_MAX-1)] = -1 };
73 static int radio_nr[BTTV_MAX] = { [0 ... (BTTV_MAX-1)] = -1 };
74 static int vbi_nr[BTTV_MAX] = { [0 ... (BTTV_MAX-1)] = -1 };
75 static int debug_latency;
76 static int disable_ir;
77
78 static unsigned int fdsr;
79
80 /* options */
81 static unsigned int combfilter;
82 static unsigned int lumafilter;
83 static unsigned int automute    = 1;
84 static unsigned int chroma_agc;
85 static unsigned int agc_crush   = 1;
86 static unsigned int whitecrush_upper = 0xCF;
87 static unsigned int whitecrush_lower = 0x7F;
88 static unsigned int vcr_hack;
89 static unsigned int irq_iswitch;
90 static unsigned int uv_ratio    = 50;
91 static unsigned int full_luma_range;
92 static unsigned int coring;
93
94 /* API features (turn on/off stuff for testing) */
95 static unsigned int v4l2        = 1;
96
97 /* insmod args */
98 module_param(bttv_verbose,      int, 0644);
99 module_param(bttv_gpio,         int, 0644);
100 module_param(bttv_debug,        int, 0644);
101 module_param(irq_debug,         int, 0644);
102 module_param(debug_latency,     int, 0644);
103 module_param(disable_ir,        int, 0444);
104
105 module_param(fdsr,              int, 0444);
106 module_param(gbuffers,          int, 0444);
107 module_param(gbufsize,          int, 0444);
108 module_param(reset_crop,        int, 0444);
109
110 module_param(v4l2,              int, 0644);
111 module_param(bigendian,         int, 0644);
112 module_param(irq_iswitch,       int, 0644);
113 module_param(combfilter,        int, 0444);
114 module_param(lumafilter,        int, 0444);
115 module_param(automute,          int, 0444);
116 module_param(chroma_agc,        int, 0444);
117 module_param(agc_crush,         int, 0444);
118 module_param(whitecrush_upper,  int, 0444);
119 module_param(whitecrush_lower,  int, 0444);
120 module_param(vcr_hack,          int, 0444);
121 module_param(uv_ratio,          int, 0444);
122 module_param(full_luma_range,   int, 0444);
123 module_param(coring,            int, 0444);
124
125 module_param_array(radio,       int, NULL, 0444);
126 module_param_array(video_nr,    int, NULL, 0444);
127 module_param_array(radio_nr,    int, NULL, 0444);
128 module_param_array(vbi_nr,      int, NULL, 0444);
129
130 MODULE_PARM_DESC(radio, "The TV card supports radio, default is 0 (no)");
131 MODULE_PARM_DESC(bigendian, "byte order of the framebuffer, default is native endian");
132 MODULE_PARM_DESC(bttv_verbose, "verbose startup messages, default is 1 (yes)");
133 MODULE_PARM_DESC(bttv_gpio, "log gpio changes, default is 0 (no)");
134 MODULE_PARM_DESC(bttv_debug, "debug messages, default is 0 (no)");
135 MODULE_PARM_DESC(irq_debug, "irq handler debug messages, default is 0 (no)");
136 MODULE_PARM_DESC(disable_ir, "disable infrared remote support");
137 MODULE_PARM_DESC(gbuffers, "number of capture buffers. range 2-32, default 8");
138 MODULE_PARM_DESC(gbufsize, "size of the capture buffers, default is 0x208000");
139 MODULE_PARM_DESC(reset_crop, "reset cropping parameters at open(), default is 1 (yes) for compatibility with older applications");
140 MODULE_PARM_DESC(automute, "mute audio on bad/missing video signal, default is 1 (yes)");
141 MODULE_PARM_DESC(chroma_agc, "enables the AGC of chroma signal, default is 0 (no)");
142 MODULE_PARM_DESC(agc_crush, "enables the luminance AGC crush, default is 1 (yes)");
143 MODULE_PARM_DESC(whitecrush_upper, "sets the white crush upper value, default is 207");
144 MODULE_PARM_DESC(whitecrush_lower, "sets the white crush lower value, default is 127");
145 MODULE_PARM_DESC(vcr_hack, "enables the VCR hack (improves synch on poor VCR tapes), default is 0 (no)");
146 MODULE_PARM_DESC(irq_iswitch, "switch inputs in irq handler");
147 MODULE_PARM_DESC(uv_ratio, "ratio between u and v gains, default is 50");
148 MODULE_PARM_DESC(full_luma_range, "use the full luma range, default is 0 (no)");
149 MODULE_PARM_DESC(coring, "set the luma coring level, default is 0 (no)");
150 MODULE_PARM_DESC(video_nr, "video device numbers");
151 MODULE_PARM_DESC(vbi_nr, "vbi device numbers");
152 MODULE_PARM_DESC(radio_nr, "radio device numbers");
153
154 MODULE_DESCRIPTION("bttv - v4l/v4l2 driver module for bt848/878 based cards");
155 MODULE_AUTHOR("Ralph Metzler & Marcus Metzler & Gerd Knorr");
156 MODULE_LICENSE("GPL");
157 MODULE_VERSION(BTTV_VERSION);
158
159 #define V4L2_CID_PRIVATE_COMBFILTER             (V4L2_CID_USER_BTTV_BASE + 0)
160 #define V4L2_CID_PRIVATE_AUTOMUTE               (V4L2_CID_USER_BTTV_BASE + 1)
161 #define V4L2_CID_PRIVATE_LUMAFILTER             (V4L2_CID_USER_BTTV_BASE + 2)
162 #define V4L2_CID_PRIVATE_AGC_CRUSH              (V4L2_CID_USER_BTTV_BASE + 3)
163 #define V4L2_CID_PRIVATE_VCR_HACK               (V4L2_CID_USER_BTTV_BASE + 4)
164 #define V4L2_CID_PRIVATE_WHITECRUSH_LOWER       (V4L2_CID_USER_BTTV_BASE + 5)
165 #define V4L2_CID_PRIVATE_WHITECRUSH_UPPER       (V4L2_CID_USER_BTTV_BASE + 6)
166 #define V4L2_CID_PRIVATE_UV_RATIO               (V4L2_CID_USER_BTTV_BASE + 7)
167 #define V4L2_CID_PRIVATE_FULL_LUMA_RANGE        (V4L2_CID_USER_BTTV_BASE + 8)
168 #define V4L2_CID_PRIVATE_CORING                 (V4L2_CID_USER_BTTV_BASE + 9)
169
170 /* ----------------------------------------------------------------------- */
171 /* sysfs                                                                   */
172
173 static ssize_t card_show(struct device *cd,
174                          struct device_attribute *attr, char *buf)
175 {
176         struct video_device *vfd = to_video_device(cd);
177         struct bttv *btv = video_get_drvdata(vfd);
178         return sprintf(buf, "%d\n", btv ? btv->c.type : UNSET);
179 }
180 static DEVICE_ATTR_RO(card);
181
182 /* ----------------------------------------------------------------------- */
183 /* dvb auto-load setup                                                     */
184 #if defined(CONFIG_MODULES) && defined(MODULE)
185 static void request_module_async(struct work_struct *work)
186 {
187         request_module("dvb-bt8xx");
188 }
189
190 static void request_modules(struct bttv *dev)
191 {
192         INIT_WORK(&dev->request_module_wk, request_module_async);
193         schedule_work(&dev->request_module_wk);
194 }
195
196 static void flush_request_modules(struct bttv *dev)
197 {
198         flush_work(&dev->request_module_wk);
199 }
200 #else
201 #define request_modules(dev)
202 #define flush_request_modules(dev) do {} while(0)
203 #endif /* CONFIG_MODULES */
204
205
206 /* ----------------------------------------------------------------------- */
207 /* static data                                                             */
208
209 /* special timing tables from conexant... */
210 static u8 SRAM_Table[][60] =
211 {
212         /* PAL digital input over GPIO[7:0] */
213         {
214                 45, // 45 bytes following
215                 0x36,0x11,0x01,0x00,0x90,0x02,0x05,0x10,0x04,0x16,
216                 0x12,0x05,0x11,0x00,0x04,0x12,0xC0,0x00,0x31,0x00,
217                 0x06,0x51,0x08,0x03,0x89,0x08,0x07,0xC0,0x44,0x00,
218                 0x81,0x01,0x01,0xA9,0x0D,0x02,0x02,0x50,0x03,0x37,
219                 0x37,0x00,0xAF,0x21,0x00
220         },
221         /* NTSC digital input over GPIO[7:0] */
222         {
223                 51, // 51 bytes following
224                 0x0C,0xC0,0x00,0x00,0x90,0x02,0x03,0x10,0x03,0x06,
225                 0x10,0x04,0x12,0x12,0x05,0x02,0x13,0x04,0x19,0x00,
226                 0x04,0x39,0x00,0x06,0x59,0x08,0x03,0x83,0x08,0x07,
227                 0x03,0x50,0x00,0xC0,0x40,0x00,0x86,0x01,0x01,0xA6,
228                 0x0D,0x02,0x03,0x11,0x01,0x05,0x37,0x00,0xAC,0x21,
229                 0x00,
230         },
231         // TGB_NTSC392 // quartzsight
232         // This table has been modified to be used for Fusion Rev D
233         {
234                 0x2A, // size of table = 42
235                 0x06, 0x08, 0x04, 0x0a, 0xc0, 0x00, 0x18, 0x08, 0x03, 0x24,
236                 0x08, 0x07, 0x02, 0x90, 0x02, 0x08, 0x10, 0x04, 0x0c, 0x10,
237                 0x05, 0x2c, 0x11, 0x04, 0x55, 0x48, 0x00, 0x05, 0x50, 0x00,
238                 0xbf, 0x0c, 0x02, 0x2f, 0x3d, 0x00, 0x2f, 0x3f, 0x00, 0xc3,
239                 0x20, 0x00
240         }
241 };
242
243 /* minhdelayx1  first video pixel we can capture on a line and
244    hdelayx1     start of active video, both relative to rising edge of
245                 /HRESET pulse (0H) in 1 / fCLKx1.
246    swidth       width of active video and
247    totalwidth   total line width, both in 1 / fCLKx1.
248    sqwidth      total line width in square pixels.
249    vdelay       start of active video in 2 * field lines relative to
250                 trailing edge of /VRESET pulse (VDELAY register).
251    sheight      height of active video in 2 * field lines.
252    extraheight  Added to sheight for cropcap.bounds.height only
253    videostart0  ITU-R frame line number of the line corresponding
254                 to vdelay in the first field. */
255 #define CROPCAP(minhdelayx1, hdelayx1, swidth, totalwidth, sqwidth,      \
256                 vdelay, sheight, extraheight, videostart0)               \
257         .cropcap.bounds.left = minhdelayx1,                              \
258         /* * 2 because vertically we count field lines times two, */     \
259         /* e.g. 23 * 2 to 23 * 2 + 576 in PAL-BGHI defrect. */           \
260         .cropcap.bounds.top = (videostart0) * 2 - (vdelay) + MIN_VDELAY, \
261         /* 4 is a safety margin at the end of the line. */               \
262         .cropcap.bounds.width = (totalwidth) - (minhdelayx1) - 4,        \
263         .cropcap.bounds.height = (sheight) + (extraheight) + (vdelay) -  \
264                                  MIN_VDELAY,                             \
265         .cropcap.defrect.left = hdelayx1,                                \
266         .cropcap.defrect.top = (videostart0) * 2,                        \
267         .cropcap.defrect.width = swidth,                                 \
268         .cropcap.defrect.height = sheight,                               \
269         .cropcap.pixelaspect.numerator = totalwidth,                     \
270         .cropcap.pixelaspect.denominator = sqwidth,
271
272 const struct bttv_tvnorm bttv_tvnorms[] = {
273         /* PAL-BDGHI */
274         /* max. active video is actually 922, but 924 is divisible by 4 and 3! */
275         /* actually, max active PAL with HSCALE=0 is 948, NTSC is 768 - nil */
276         {
277                 .v4l2_id        = V4L2_STD_PAL,
278                 .name           = "PAL",
279                 .Fsc            = 35468950,
280                 .swidth         = 924,
281                 .sheight        = 576,
282                 .totalwidth     = 1135,
283                 .adelay         = 0x7f,
284                 .bdelay         = 0x72,
285                 .iform          = (BT848_IFORM_PAL_BDGHI|BT848_IFORM_XT1),
286                 .scaledtwidth   = 1135,
287                 .hdelayx1       = 186,
288                 .hactivex1      = 924,
289                 .vdelay         = 0x20,
290                 .vbipack        = 255, /* min (2048 / 4, 0x1ff) & 0xff */
291                 .sram           = 0,
292                 /* ITU-R frame line number of the first VBI line
293                    we can capture, of the first and second field.
294                    The last line is determined by cropcap.bounds. */
295                 .vbistart       = { 7, 320 },
296                 CROPCAP(/* minhdelayx1 */ 68,
297                         /* hdelayx1 */ 186,
298                         /* Should be (768 * 1135 + 944 / 2) / 944.
299                            cropcap.defrect is used for image width
300                            checks, so we keep the old value 924. */
301                         /* swidth */ 924,
302                         /* totalwidth */ 1135,
303                         /* sqwidth */ 944,
304                         /* vdelay */ 0x20,
305                         /* sheight */ 576,
306                         /* bt878 (and bt848?) can capture another
307                            line below active video. */
308                         /* extraheight */ 2,
309                         /* videostart0 */ 23)
310         },{
311                 .v4l2_id        = V4L2_STD_NTSC_M | V4L2_STD_NTSC_M_KR,
312                 .name           = "NTSC",
313                 .Fsc            = 28636363,
314                 .swidth         = 768,
315                 .sheight        = 480,
316                 .totalwidth     = 910,
317                 .adelay         = 0x68,
318                 .bdelay         = 0x5d,
319                 .iform          = (BT848_IFORM_NTSC|BT848_IFORM_XT0),
320                 .scaledtwidth   = 910,
321                 .hdelayx1       = 128,
322                 .hactivex1      = 910,
323                 .vdelay         = 0x1a,
324                 .vbipack        = 144, /* min (1600 / 4, 0x1ff) & 0xff */
325                 .sram           = 1,
326                 .vbistart       = { 10, 273 },
327                 CROPCAP(/* minhdelayx1 */ 68,
328                         /* hdelayx1 */ 128,
329                         /* Should be (640 * 910 + 780 / 2) / 780? */
330                         /* swidth */ 768,
331                         /* totalwidth */ 910,
332                         /* sqwidth */ 780,
333                         /* vdelay */ 0x1a,
334                         /* sheight */ 480,
335                         /* extraheight */ 0,
336                         /* videostart0 */ 23)
337         },{
338                 .v4l2_id        = V4L2_STD_SECAM,
339                 .name           = "SECAM",
340                 .Fsc            = 35468950,
341                 .swidth         = 924,
342                 .sheight        = 576,
343                 .totalwidth     = 1135,
344                 .adelay         = 0x7f,
345                 .bdelay         = 0xb0,
346                 .iform          = (BT848_IFORM_SECAM|BT848_IFORM_XT1),
347                 .scaledtwidth   = 1135,
348                 .hdelayx1       = 186,
349                 .hactivex1      = 922,
350                 .vdelay         = 0x20,
351                 .vbipack        = 255,
352                 .sram           = 0, /* like PAL, correct? */
353                 .vbistart       = { 7, 320 },
354                 CROPCAP(/* minhdelayx1 */ 68,
355                         /* hdelayx1 */ 186,
356                         /* swidth */ 924,
357                         /* totalwidth */ 1135,
358                         /* sqwidth */ 944,
359                         /* vdelay */ 0x20,
360                         /* sheight */ 576,
361                         /* extraheight */ 0,
362                         /* videostart0 */ 23)
363         },{
364                 .v4l2_id        = V4L2_STD_PAL_Nc,
365                 .name           = "PAL-Nc",
366                 .Fsc            = 28636363,
367                 .swidth         = 640,
368                 .sheight        = 576,
369                 .totalwidth     = 910,
370                 .adelay         = 0x68,
371                 .bdelay         = 0x5d,
372                 .iform          = (BT848_IFORM_PAL_NC|BT848_IFORM_XT0),
373                 .scaledtwidth   = 780,
374                 .hdelayx1       = 130,
375                 .hactivex1      = 734,
376                 .vdelay         = 0x1a,
377                 .vbipack        = 144,
378                 .sram           = -1,
379                 .vbistart       = { 7, 320 },
380                 CROPCAP(/* minhdelayx1 */ 68,
381                         /* hdelayx1 */ 130,
382                         /* swidth */ (640 * 910 + 780 / 2) / 780,
383                         /* totalwidth */ 910,
384                         /* sqwidth */ 780,
385                         /* vdelay */ 0x1a,
386                         /* sheight */ 576,
387                         /* extraheight */ 0,
388                         /* videostart0 */ 23)
389         },{
390                 .v4l2_id        = V4L2_STD_PAL_M,
391                 .name           = "PAL-M",
392                 .Fsc            = 28636363,
393                 .swidth         = 640,
394                 .sheight        = 480,
395                 .totalwidth     = 910,
396                 .adelay         = 0x68,
397                 .bdelay         = 0x5d,
398                 .iform          = (BT848_IFORM_PAL_M|BT848_IFORM_XT0),
399                 .scaledtwidth   = 780,
400                 .hdelayx1       = 135,
401                 .hactivex1      = 754,
402                 .vdelay         = 0x1a,
403                 .vbipack        = 144,
404                 .sram           = -1,
405                 .vbistart       = { 10, 273 },
406                 CROPCAP(/* minhdelayx1 */ 68,
407                         /* hdelayx1 */ 135,
408                         /* swidth */ (640 * 910 + 780 / 2) / 780,
409                         /* totalwidth */ 910,
410                         /* sqwidth */ 780,
411                         /* vdelay */ 0x1a,
412                         /* sheight */ 480,
413                         /* extraheight */ 0,
414                         /* videostart0 */ 23)
415         },{
416                 .v4l2_id        = V4L2_STD_PAL_N,
417                 .name           = "PAL-N",
418                 .Fsc            = 35468950,
419                 .swidth         = 768,
420                 .sheight        = 576,
421                 .totalwidth     = 1135,
422                 .adelay         = 0x7f,
423                 .bdelay         = 0x72,
424                 .iform          = (BT848_IFORM_PAL_N|BT848_IFORM_XT1),
425                 .scaledtwidth   = 944,
426                 .hdelayx1       = 186,
427                 .hactivex1      = 922,
428                 .vdelay         = 0x20,
429                 .vbipack        = 144,
430                 .sram           = -1,
431                 .vbistart       = { 7, 320 },
432                 CROPCAP(/* minhdelayx1 */ 68,
433                         /* hdelayx1 */ 186,
434                         /* swidth */ (768 * 1135 + 944 / 2) / 944,
435                         /* totalwidth */ 1135,
436                         /* sqwidth */ 944,
437                         /* vdelay */ 0x20,
438                         /* sheight */ 576,
439                         /* extraheight */ 0,
440                         /* videostart0 */ 23)
441         },{
442                 .v4l2_id        = V4L2_STD_NTSC_M_JP,
443                 .name           = "NTSC-JP",
444                 .Fsc            = 28636363,
445                 .swidth         = 640,
446                 .sheight        = 480,
447                 .totalwidth     = 910,
448                 .adelay         = 0x68,
449                 .bdelay         = 0x5d,
450                 .iform          = (BT848_IFORM_NTSC_J|BT848_IFORM_XT0),
451                 .scaledtwidth   = 780,
452                 .hdelayx1       = 135,
453                 .hactivex1      = 754,
454                 .vdelay         = 0x16,
455                 .vbipack        = 144,
456                 .sram           = -1,
457                 .vbistart       = { 10, 273 },
458                 CROPCAP(/* minhdelayx1 */ 68,
459                         /* hdelayx1 */ 135,
460                         /* swidth */ (640 * 910 + 780 / 2) / 780,
461                         /* totalwidth */ 910,
462                         /* sqwidth */ 780,
463                         /* vdelay */ 0x16,
464                         /* sheight */ 480,
465                         /* extraheight */ 0,
466                         /* videostart0 */ 23)
467         },{
468                 /* that one hopefully works with the strange timing
469                  * which video recorders produce when playing a NTSC
470                  * tape on a PAL TV ... */
471                 .v4l2_id        = V4L2_STD_PAL_60,
472                 .name           = "PAL-60",
473                 .Fsc            = 35468950,
474                 .swidth         = 924,
475                 .sheight        = 480,
476                 .totalwidth     = 1135,
477                 .adelay         = 0x7f,
478                 .bdelay         = 0x72,
479                 .iform          = (BT848_IFORM_PAL_BDGHI|BT848_IFORM_XT1),
480                 .scaledtwidth   = 1135,
481                 .hdelayx1       = 186,
482                 .hactivex1      = 924,
483                 .vdelay         = 0x1a,
484                 .vbipack        = 255,
485                 .vtotal         = 524,
486                 .sram           = -1,
487                 .vbistart       = { 10, 273 },
488                 CROPCAP(/* minhdelayx1 */ 68,
489                         /* hdelayx1 */ 186,
490                         /* swidth */ 924,
491                         /* totalwidth */ 1135,
492                         /* sqwidth */ 944,
493                         /* vdelay */ 0x1a,
494                         /* sheight */ 480,
495                         /* extraheight */ 0,
496                         /* videostart0 */ 23)
497         }
498 };
499 static const unsigned int BTTV_TVNORMS = ARRAY_SIZE(bttv_tvnorms);
500
501 /* ----------------------------------------------------------------------- */
502 /* bttv format list
503    packed pixel formats must come first */
504 static const struct bttv_format formats[] = {
505         {
506                 .fourcc   = V4L2_PIX_FMT_GREY,
507                 .btformat = BT848_COLOR_FMT_Y8,
508                 .depth    = 8,
509                 .flags    = FORMAT_FLAGS_PACKED,
510         },{
511                 .fourcc   = V4L2_PIX_FMT_HI240,
512                 .btformat = BT848_COLOR_FMT_RGB8,
513                 .depth    = 8,
514                 .flags    = FORMAT_FLAGS_PACKED | FORMAT_FLAGS_DITHER,
515         },{
516                 .fourcc   = V4L2_PIX_FMT_RGB555,
517                 .btformat = BT848_COLOR_FMT_RGB15,
518                 .depth    = 16,
519                 .flags    = FORMAT_FLAGS_PACKED,
520         },{
521                 .fourcc   = V4L2_PIX_FMT_RGB555X,
522                 .btformat = BT848_COLOR_FMT_RGB15,
523                 .btswap   = 0x03, /* byteswap */
524                 .depth    = 16,
525                 .flags    = FORMAT_FLAGS_PACKED,
526         },{
527                 .fourcc   = V4L2_PIX_FMT_RGB565,
528                 .btformat = BT848_COLOR_FMT_RGB16,
529                 .depth    = 16,
530                 .flags    = FORMAT_FLAGS_PACKED,
531         },{
532                 .fourcc   = V4L2_PIX_FMT_RGB565X,
533                 .btformat = BT848_COLOR_FMT_RGB16,
534                 .btswap   = 0x03, /* byteswap */
535                 .depth    = 16,
536                 .flags    = FORMAT_FLAGS_PACKED,
537         },{
538                 .fourcc   = V4L2_PIX_FMT_BGR24,
539                 .btformat = BT848_COLOR_FMT_RGB24,
540                 .depth    = 24,
541                 .flags    = FORMAT_FLAGS_PACKED,
542         },{
543                 .fourcc   = V4L2_PIX_FMT_BGR32,
544                 .btformat = BT848_COLOR_FMT_RGB32,
545                 .depth    = 32,
546                 .flags    = FORMAT_FLAGS_PACKED,
547         },{
548                 .fourcc   = V4L2_PIX_FMT_RGB32,
549                 .btformat = BT848_COLOR_FMT_RGB32,
550                 .btswap   = 0x0f, /* byte+word swap */
551                 .depth    = 32,
552                 .flags    = FORMAT_FLAGS_PACKED,
553         },{
554                 .fourcc   = V4L2_PIX_FMT_YUYV,
555                 .btformat = BT848_COLOR_FMT_YUY2,
556                 .depth    = 16,
557                 .flags    = FORMAT_FLAGS_PACKED,
558         },{
559                 .fourcc   = V4L2_PIX_FMT_UYVY,
560                 .btformat = BT848_COLOR_FMT_YUY2,
561                 .btswap   = 0x03, /* byteswap */
562                 .depth    = 16,
563                 .flags    = FORMAT_FLAGS_PACKED,
564         },{
565                 .fourcc   = V4L2_PIX_FMT_YUV422P,
566                 .btformat = BT848_COLOR_FMT_YCrCb422,
567                 .depth    = 16,
568                 .flags    = FORMAT_FLAGS_PLANAR,
569                 .hshift   = 1,
570                 .vshift   = 0,
571         },{
572                 .fourcc   = V4L2_PIX_FMT_YUV420,
573                 .btformat = BT848_COLOR_FMT_YCrCb422,
574                 .depth    = 12,
575                 .flags    = FORMAT_FLAGS_PLANAR,
576                 .hshift   = 1,
577                 .vshift   = 1,
578         },{
579                 .fourcc   = V4L2_PIX_FMT_YVU420,
580                 .btformat = BT848_COLOR_FMT_YCrCb422,
581                 .depth    = 12,
582                 .flags    = FORMAT_FLAGS_PLANAR | FORMAT_FLAGS_CrCb,
583                 .hshift   = 1,
584                 .vshift   = 1,
585         },{
586                 .fourcc   = V4L2_PIX_FMT_YUV411P,
587                 .btformat = BT848_COLOR_FMT_YCrCb411,
588                 .depth    = 12,
589                 .flags    = FORMAT_FLAGS_PLANAR,
590                 .hshift   = 2,
591                 .vshift   = 0,
592         },{
593                 .fourcc   = V4L2_PIX_FMT_YUV410,
594                 .btformat = BT848_COLOR_FMT_YCrCb411,
595                 .depth    = 9,
596                 .flags    = FORMAT_FLAGS_PLANAR,
597                 .hshift   = 2,
598                 .vshift   = 2,
599         },{
600                 .fourcc   = V4L2_PIX_FMT_YVU410,
601                 .btformat = BT848_COLOR_FMT_YCrCb411,
602                 .depth    = 9,
603                 .flags    = FORMAT_FLAGS_PLANAR | FORMAT_FLAGS_CrCb,
604                 .hshift   = 2,
605                 .vshift   = 2,
606         },{
607                 .fourcc   = -1,
608                 .btformat = BT848_COLOR_FMT_RAW,
609                 .depth    = 8,
610                 .flags    = FORMAT_FLAGS_RAW,
611         }
612 };
613 static const unsigned int FORMATS = ARRAY_SIZE(formats);
614
615 /* ----------------------------------------------------------------------- */
616 /* resource management                                                     */
617
618 /*
619    RESOURCE_    allocated by                freed by
620
621    VIDEO_READ   bttv_read 1)                bttv_read 2)
622
623    VIDEO_STREAM VIDIOC_STREAMON             VIDIOC_STREAMOFF
624                  VIDIOC_QBUF 1)              bttv_release
625                  VIDIOCMCAPTURE 1)
626
627    VBI           VIDIOC_STREAMON             VIDIOC_STREAMOFF
628                  VIDIOC_QBUF 1)              bttv_release
629                  bttv_read, bttv_poll 1) 3)
630
631    1) The resource must be allocated when we enter buffer prepare functions
632       and remain allocated while buffers are in the DMA queue.
633    2) This is a single frame read.
634    3) This is a continuous read, implies VIDIOC_STREAMON.
635
636    Note this driver permits video input and standard changes regardless if
637    resources are allocated.
638 */
639
640 #define VBI_RESOURCES (RESOURCE_VBI)
641 #define VIDEO_RESOURCES (RESOURCE_VIDEO_READ | \
642                          RESOURCE_VIDEO_STREAM)
643
644 static
645 int check_alloc_btres_lock(struct bttv *btv, struct bttv_fh *fh, int bit)
646 {
647         int xbits; /* mutual exclusive resources */
648
649         if (fh->resources & bit)
650                 /* have it already allocated */
651                 return 1;
652
653         xbits = bit;
654         if (bit & (RESOURCE_VIDEO_READ | RESOURCE_VIDEO_STREAM))
655                 xbits |= RESOURCE_VIDEO_READ | RESOURCE_VIDEO_STREAM;
656
657         /* is it free? */
658         if (btv->resources & xbits) {
659                 /* no, someone else uses it */
660                 goto fail;
661         }
662
663         if ((bit & VIDEO_RESOURCES)
664             && 0 == (btv->resources & VIDEO_RESOURCES)) {
665                 /* Do crop - use current, don't - use default parameters. */
666                 __s32 top = btv->crop[!!fh->do_crop].rect.top;
667
668                 if (btv->vbi_end > top)
669                         goto fail;
670
671                 /* We cannot capture the same line as video and VBI data.
672                    Claim scan lines crop[].rect.top to bottom. */
673                 btv->crop_start = top;
674         } else if (bit & VBI_RESOURCES) {
675                 __s32 end = fh->vbi_fmt.end;
676
677                 if (end > btv->crop_start)
678                         goto fail;
679
680                 /* Claim scan lines above fh->vbi_fmt.end. */
681                 btv->vbi_end = end;
682         }
683
684         /* it's free, grab it */
685         fh->resources  |= bit;
686         btv->resources |= bit;
687         return 1;
688
689  fail:
690         return 0;
691 }
692
693 static
694 int check_btres(struct bttv_fh *fh, int bit)
695 {
696         return (fh->resources & bit);
697 }
698
699 static
700 int locked_btres(struct bttv *btv, int bit)
701 {
702         return (btv->resources & bit);
703 }
704
705 /* Call with btv->lock down. */
706 static void
707 disclaim_vbi_lines(struct bttv *btv)
708 {
709         btv->vbi_end = 0;
710 }
711
712 /* Call with btv->lock down. */
713 static void
714 disclaim_video_lines(struct bttv *btv)
715 {
716         const struct bttv_tvnorm *tvnorm;
717         u8 crop;
718
719         tvnorm = &bttv_tvnorms[btv->tvnorm];
720         btv->crop_start = tvnorm->cropcap.bounds.top
721                 + tvnorm->cropcap.bounds.height;
722
723         /* VBI capturing ends at VDELAY, start of video capturing, no
724            matter how many lines the VBI RISC program expects. When video
725            capturing is off, it shall no longer "preempt" VBI capturing,
726            so we set VDELAY to maximum. */
727         crop = btread(BT848_E_CROP) | 0xc0;
728         btwrite(crop, BT848_E_CROP);
729         btwrite(0xfe, BT848_E_VDELAY_LO);
730         btwrite(crop, BT848_O_CROP);
731         btwrite(0xfe, BT848_O_VDELAY_LO);
732 }
733
734 static
735 void free_btres_lock(struct bttv *btv, struct bttv_fh *fh, int bits)
736 {
737         if ((fh->resources & bits) != bits) {
738                 /* trying to free resources not allocated by us ... */
739                 pr_err("BUG! (btres)\n");
740         }
741         fh->resources  &= ~bits;
742         btv->resources &= ~bits;
743
744         bits = btv->resources;
745
746         if (0 == (bits & VIDEO_RESOURCES))
747                 disclaim_video_lines(btv);
748
749         if (0 == (bits & VBI_RESOURCES))
750                 disclaim_vbi_lines(btv);
751 }
752
753 /* ----------------------------------------------------------------------- */
754 /* If Bt848a or Bt849, use PLL for PAL/SECAM and crystal for NTSC          */
755
756 /* Frequency = (F_input / PLL_X) * PLL_I.PLL_F/PLL_C
757    PLL_X = Reference pre-divider (0=1, 1=2)
758    PLL_C = Post divider (0=6, 1=4)
759    PLL_I = Integer input
760    PLL_F = Fractional input
761
762    F_input = 28.636363 MHz:
763    PAL (CLKx2 = 35.46895 MHz): PLL_X = 1, PLL_I = 0x0E, PLL_F = 0xDCF9, PLL_C = 0
764 */
765
766 static void set_pll_freq(struct bttv *btv, unsigned int fin, unsigned int fout)
767 {
768         unsigned char fl, fh, fi;
769
770         /* prevent overflows */
771         fin/=4;
772         fout/=4;
773
774         fout*=12;
775         fi=fout/fin;
776
777         fout=(fout%fin)*256;
778         fh=fout/fin;
779
780         fout=(fout%fin)*256;
781         fl=fout/fin;
782
783         btwrite(fl, BT848_PLL_F_LO);
784         btwrite(fh, BT848_PLL_F_HI);
785         btwrite(fi|BT848_PLL_X, BT848_PLL_XCI);
786 }
787
788 static void set_pll(struct bttv *btv)
789 {
790         int i;
791
792         if (!btv->pll.pll_crystal)
793                 return;
794
795         if (btv->pll.pll_ofreq == btv->pll.pll_current) {
796                 dprintk("%d: PLL: no change required\n", btv->c.nr);
797                 return;
798         }
799
800         if (btv->pll.pll_ifreq == btv->pll.pll_ofreq) {
801                 /* no PLL needed */
802                 if (btv->pll.pll_current == 0)
803                         return;
804                 if (bttv_verbose)
805                         pr_info("%d: PLL can sleep, using XTAL (%d)\n",
806                                 btv->c.nr, btv->pll.pll_ifreq);
807                 btwrite(0x00,BT848_TGCTRL);
808                 btwrite(0x00,BT848_PLL_XCI);
809                 btv->pll.pll_current = 0;
810                 return;
811         }
812
813         if (bttv_verbose)
814                 pr_info("%d: Setting PLL: %d => %d (needs up to 100ms)\n",
815                         btv->c.nr,
816                         btv->pll.pll_ifreq, btv->pll.pll_ofreq);
817         set_pll_freq(btv, btv->pll.pll_ifreq, btv->pll.pll_ofreq);
818
819         for (i=0; i<10; i++) {
820                 /*  Let other people run while the PLL stabilizes */
821                 msleep(10);
822
823                 if (btread(BT848_DSTATUS) & BT848_DSTATUS_PLOCK) {
824                         btwrite(0,BT848_DSTATUS);
825                 } else {
826                         btwrite(0x08,BT848_TGCTRL);
827                         btv->pll.pll_current = btv->pll.pll_ofreq;
828                         if (bttv_verbose)
829                                 pr_info("PLL set ok\n");
830                         return;
831                 }
832         }
833         btv->pll.pll_current = -1;
834         if (bttv_verbose)
835                 pr_info("Setting PLL failed\n");
836         return;
837 }
838
839 /* used to switch between the bt848's analog/digital video capture modes */
840 static void bt848A_set_timing(struct bttv *btv)
841 {
842         int i, len;
843         int table_idx = bttv_tvnorms[btv->tvnorm].sram;
844         int fsc       = bttv_tvnorms[btv->tvnorm].Fsc;
845
846         if (btv->input == btv->dig) {
847                 dprintk("%d: load digital timing table (table_idx=%d)\n",
848                         btv->c.nr,table_idx);
849
850                 /* timing change...reset timing generator address */
851                 btwrite(0x00, BT848_TGCTRL);
852                 btwrite(0x02, BT848_TGCTRL);
853                 btwrite(0x00, BT848_TGCTRL);
854
855                 len=SRAM_Table[table_idx][0];
856                 for(i = 1; i <= len; i++)
857                         btwrite(SRAM_Table[table_idx][i],BT848_TGLB);
858                 btv->pll.pll_ofreq = 27000000;
859
860                 set_pll(btv);
861                 btwrite(0x11, BT848_TGCTRL);
862                 btwrite(0x41, BT848_DVSIF);
863         } else {
864                 btv->pll.pll_ofreq = fsc;
865                 set_pll(btv);
866                 btwrite(0x0, BT848_DVSIF);
867         }
868 }
869
870 /* ----------------------------------------------------------------------- */
871
872 static void bt848_bright(struct bttv *btv, int bright)
873 {
874         int value;
875
876         // printk("set bright: %d\n", bright); // DEBUG
877         btv->bright = bright;
878
879         /* We want -128 to 127 we get 0-65535 */
880         value = (bright >> 8) - 128;
881         btwrite(value & 0xff, BT848_BRIGHT);
882 }
883
884 static void bt848_hue(struct bttv *btv, int hue)
885 {
886         int value;
887
888         btv->hue = hue;
889
890         /* -128 to 127 */
891         value = (hue >> 8) - 128;
892         btwrite(value & 0xff, BT848_HUE);
893 }
894
895 static void bt848_contrast(struct bttv *btv, int cont)
896 {
897         int value,hibit;
898
899         btv->contrast = cont;
900
901         /* 0-511 */
902         value = (cont  >> 7);
903         hibit = (value >> 6) & 4;
904         btwrite(value & 0xff, BT848_CONTRAST_LO);
905         btaor(hibit, ~4, BT848_E_CONTROL);
906         btaor(hibit, ~4, BT848_O_CONTROL);
907 }
908
909 static void bt848_sat(struct bttv *btv, int color)
910 {
911         int val_u,val_v,hibits;
912
913         btv->saturation = color;
914
915         /* 0-511 for the color */
916         val_u   = ((color * btv->opt_uv_ratio) / 50) >> 7;
917         val_v   = (((color * (100 - btv->opt_uv_ratio) / 50) >>7)*180L)/254;
918         hibits  = (val_u >> 7) & 2;
919         hibits |= (val_v >> 8) & 1;
920         btwrite(val_u & 0xff, BT848_SAT_U_LO);
921         btwrite(val_v & 0xff, BT848_SAT_V_LO);
922         btaor(hibits, ~3, BT848_E_CONTROL);
923         btaor(hibits, ~3, BT848_O_CONTROL);
924 }
925
926 /* ----------------------------------------------------------------------- */
927
928 static int
929 video_mux(struct bttv *btv, unsigned int input)
930 {
931         int mux,mask2;
932
933         if (input >= bttv_tvcards[btv->c.type].video_inputs)
934                 return -EINVAL;
935
936         /* needed by RemoteVideo MX */
937         mask2 = bttv_tvcards[btv->c.type].gpiomask2;
938         if (mask2)
939                 gpio_inout(mask2,mask2);
940
941         if (input == btv->svhs)  {
942                 btor(BT848_CONTROL_COMP, BT848_E_CONTROL);
943                 btor(BT848_CONTROL_COMP, BT848_O_CONTROL);
944         } else {
945                 btand(~BT848_CONTROL_COMP, BT848_E_CONTROL);
946                 btand(~BT848_CONTROL_COMP, BT848_O_CONTROL);
947         }
948         mux = bttv_muxsel(btv, input);
949         btaor(mux<<5, ~(3<<5), BT848_IFORM);
950         dprintk("%d: video mux: input=%d mux=%d\n", btv->c.nr, input, mux);
951
952         /* card specific hook */
953         if(bttv_tvcards[btv->c.type].muxsel_hook)
954                 bttv_tvcards[btv->c.type].muxsel_hook (btv, input);
955         return 0;
956 }
957
958 static char *audio_modes[] = {
959         "audio: tuner", "audio: radio", "audio: extern",
960         "audio: intern", "audio: mute"
961 };
962
963 static void
964 audio_mux_gpio(struct bttv *btv, int input, int mute)
965 {
966         int gpio_val, signal, mute_gpio;
967
968         gpio_inout(bttv_tvcards[btv->c.type].gpiomask,
969                    bttv_tvcards[btv->c.type].gpiomask);
970         signal = btread(BT848_DSTATUS) & BT848_DSTATUS_HLOC;
971
972         /* automute */
973         mute_gpio = mute || (btv->opt_automute && (!signal || !btv->users)
974                                 && !btv->has_radio_tuner);
975
976         if (mute_gpio)
977                 gpio_val = bttv_tvcards[btv->c.type].gpiomute;
978         else
979                 gpio_val = bttv_tvcards[btv->c.type].gpiomux[input];
980
981         switch (btv->c.type) {
982         case BTTV_BOARD_VOODOOTV_FM:
983         case BTTV_BOARD_VOODOOTV_200:
984                 gpio_val = bttv_tda9880_setnorm(btv, gpio_val);
985                 break;
986
987         default:
988                 gpio_bits(bttv_tvcards[btv->c.type].gpiomask, gpio_val);
989         }
990
991         if (bttv_gpio)
992                 bttv_gpio_tracking(btv, audio_modes[mute_gpio ? 4 : input]);
993 }
994
995 static int
996 audio_mute(struct bttv *btv, int mute)
997 {
998         struct v4l2_ctrl *ctrl;
999
1000         audio_mux_gpio(btv, btv->audio_input, mute);
1001
1002         if (btv->sd_msp34xx) {
1003                 ctrl = v4l2_ctrl_find(btv->sd_msp34xx->ctrl_handler, V4L2_CID_AUDIO_MUTE);
1004                 if (ctrl)
1005                         v4l2_ctrl_s_ctrl(ctrl, mute);
1006         }
1007         if (btv->sd_tvaudio) {
1008                 ctrl = v4l2_ctrl_find(btv->sd_tvaudio->ctrl_handler, V4L2_CID_AUDIO_MUTE);
1009                 if (ctrl)
1010                         v4l2_ctrl_s_ctrl(ctrl, mute);
1011         }
1012         if (btv->sd_tda7432) {
1013                 ctrl = v4l2_ctrl_find(btv->sd_tda7432->ctrl_handler, V4L2_CID_AUDIO_MUTE);
1014                 if (ctrl)
1015                         v4l2_ctrl_s_ctrl(ctrl, mute);
1016         }
1017         return 0;
1018 }
1019
1020 static int
1021 audio_input(struct bttv *btv, int input)
1022 {
1023         audio_mux_gpio(btv, input, btv->mute);
1024
1025         if (btv->sd_msp34xx) {
1026                 u32 in;
1027
1028                 /* Note: the inputs tuner/radio/extern/intern are translated
1029                    to msp routings. This assumes common behavior for all msp3400
1030                    based TV cards. When this assumption fails, then the
1031                    specific MSP routing must be added to the card table.
1032                    For now this is sufficient. */
1033                 switch (input) {
1034                 case TVAUDIO_INPUT_RADIO:
1035                         /* Some boards need the msp do to the radio demod */
1036                         if (btv->radio_uses_msp_demodulator) {
1037                                 in = MSP_INPUT_DEFAULT;
1038                                 break;
1039                         }
1040                         in = MSP_INPUT(MSP_IN_SCART2, MSP_IN_TUNER1,
1041                                     MSP_DSP_IN_SCART, MSP_DSP_IN_SCART);
1042                         break;
1043                 case TVAUDIO_INPUT_EXTERN:
1044                         in = MSP_INPUT(MSP_IN_SCART1, MSP_IN_TUNER1,
1045                                     MSP_DSP_IN_SCART, MSP_DSP_IN_SCART);
1046                         break;
1047                 case TVAUDIO_INPUT_INTERN:
1048                         /* Yes, this is the same input as for RADIO. I doubt
1049                            if this is ever used. The only board with an INTERN
1050                            input is the BTTV_BOARD_AVERMEDIA98. I wonder how
1051                            that was tested. My guess is that the whole INTERN
1052                            input does not work. */
1053                         in = MSP_INPUT(MSP_IN_SCART2, MSP_IN_TUNER1,
1054                                     MSP_DSP_IN_SCART, MSP_DSP_IN_SCART);
1055                         break;
1056                 case TVAUDIO_INPUT_TUNER:
1057                 default:
1058                         /* This is the only card that uses TUNER2, and afaik,
1059                            is the only difference between the VOODOOTV_FM
1060                            and VOODOOTV_200 */
1061                         if (btv->c.type == BTTV_BOARD_VOODOOTV_200)
1062                                 in = MSP_INPUT(MSP_IN_SCART1, MSP_IN_TUNER2, \
1063                                         MSP_DSP_IN_TUNER, MSP_DSP_IN_TUNER);
1064                         else
1065                                 in = MSP_INPUT_DEFAULT;
1066                         break;
1067                 }
1068                 v4l2_subdev_call(btv->sd_msp34xx, audio, s_routing,
1069                                in, MSP_OUTPUT_DEFAULT, 0);
1070         }
1071         if (btv->sd_tvaudio) {
1072                 v4l2_subdev_call(btv->sd_tvaudio, audio, s_routing,
1073                                  input, 0, 0);
1074         }
1075         return 0;
1076 }
1077
1078 static void
1079 bttv_crop_calc_limits(struct bttv_crop *c)
1080 {
1081         /* Scale factor min. 1:1, max. 16:1. Min. image size
1082            48 x 32. Scaled width must be a multiple of 4. */
1083
1084         if (1) {
1085                 /* For bug compatibility with VIDIOCGCAP and image
1086                    size checks in earlier driver versions. */
1087                 c->min_scaled_width = 48;
1088                 c->min_scaled_height = 32;
1089         } else {
1090                 c->min_scaled_width =
1091                         (max_t(unsigned int, 48, c->rect.width >> 4) + 3) & ~3;
1092                 c->min_scaled_height =
1093                         max_t(unsigned int, 32, c->rect.height >> 4);
1094         }
1095
1096         c->max_scaled_width  = c->rect.width & ~3;
1097         c->max_scaled_height = c->rect.height;
1098 }
1099
1100 static void
1101 bttv_crop_reset(struct bttv_crop *c, unsigned int norm)
1102 {
1103         c->rect = bttv_tvnorms[norm].cropcap.defrect;
1104         bttv_crop_calc_limits(c);
1105 }
1106
1107 /* Call with btv->lock down. */
1108 static int
1109 set_tvnorm(struct bttv *btv, unsigned int norm)
1110 {
1111         const struct bttv_tvnorm *tvnorm;
1112         v4l2_std_id id;
1113
1114         BUG_ON(norm >= BTTV_TVNORMS);
1115         BUG_ON(btv->tvnorm >= BTTV_TVNORMS);
1116
1117         tvnorm = &bttv_tvnorms[norm];
1118
1119         if (memcmp(&bttv_tvnorms[btv->tvnorm].cropcap, &tvnorm->cropcap,
1120                     sizeof (tvnorm->cropcap))) {
1121                 bttv_crop_reset(&btv->crop[0], norm);
1122                 btv->crop[1] = btv->crop[0]; /* current = default */
1123
1124                 if (0 == (btv->resources & VIDEO_RESOURCES)) {
1125                         btv->crop_start = tvnorm->cropcap.bounds.top
1126                                 + tvnorm->cropcap.bounds.height;
1127                 }
1128         }
1129
1130         btv->tvnorm = norm;
1131
1132         btwrite(tvnorm->adelay, BT848_ADELAY);
1133         btwrite(tvnorm->bdelay, BT848_BDELAY);
1134         btaor(tvnorm->iform,~(BT848_IFORM_NORM|BT848_IFORM_XTBOTH),
1135               BT848_IFORM);
1136         btwrite(tvnorm->vbipack, BT848_VBI_PACK_SIZE);
1137         btwrite(1, BT848_VBI_PACK_DEL);
1138         bt848A_set_timing(btv);
1139
1140         switch (btv->c.type) {
1141         case BTTV_BOARD_VOODOOTV_FM:
1142         case BTTV_BOARD_VOODOOTV_200:
1143                 bttv_tda9880_setnorm(btv, gpio_read());
1144                 break;
1145         }
1146         id = tvnorm->v4l2_id;
1147         bttv_call_all(btv, video, s_std, id);
1148
1149         return 0;
1150 }
1151
1152 /* Call with btv->lock down. */
1153 static void
1154 set_input(struct bttv *btv, unsigned int input, unsigned int norm)
1155 {
1156         unsigned long flags;
1157
1158         btv->input = input;
1159         if (irq_iswitch) {
1160                 spin_lock_irqsave(&btv->s_lock,flags);
1161                 if (btv->curr.frame_irq) {
1162                         /* active capture -> delayed input switch */
1163                         btv->new_input = input;
1164                 } else {
1165                         video_mux(btv,input);
1166                 }
1167                 spin_unlock_irqrestore(&btv->s_lock,flags);
1168         } else {
1169                 video_mux(btv,input);
1170         }
1171         btv->audio_input = (btv->tuner_type != TUNER_ABSENT && input == 0) ?
1172                                 TVAUDIO_INPUT_TUNER : TVAUDIO_INPUT_EXTERN;
1173         audio_input(btv, btv->audio_input);
1174         set_tvnorm(btv, norm);
1175 }
1176
1177 static void init_irqreg(struct bttv *btv)
1178 {
1179         /* clear status */
1180         btwrite(0xfffffUL, BT848_INT_STAT);
1181
1182         if (bttv_tvcards[btv->c.type].no_video) {
1183                 /* i2c only */
1184                 btwrite(BT848_INT_I2CDONE,
1185                         BT848_INT_MASK);
1186         } else {
1187                 /* full video */
1188                 btwrite((btv->triton1)  |
1189                         (btv->gpioirq ? BT848_INT_GPINT : 0) |
1190                         BT848_INT_SCERR |
1191                         (fdsr ? BT848_INT_FDSR : 0) |
1192                         BT848_INT_RISCI | BT848_INT_OCERR |
1193                         BT848_INT_FMTCHG|BT848_INT_HLOCK|
1194                         BT848_INT_I2CDONE,
1195                         BT848_INT_MASK);
1196         }
1197 }
1198
1199 static void init_bt848(struct bttv *btv)
1200 {
1201         if (bttv_tvcards[btv->c.type].no_video) {
1202                 /* very basic init only */
1203                 init_irqreg(btv);
1204                 return;
1205         }
1206
1207         btwrite(0x00, BT848_CAP_CTL);
1208         btwrite(BT848_COLOR_CTL_GAMMA, BT848_COLOR_CTL);
1209         btwrite(BT848_IFORM_XTAUTO | BT848_IFORM_AUTO, BT848_IFORM);
1210
1211         /* set planar and packed mode trigger points and         */
1212         /* set rising edge of inverted GPINTR pin as irq trigger */
1213         btwrite(BT848_GPIO_DMA_CTL_PKTP_32|
1214                 BT848_GPIO_DMA_CTL_PLTP1_16|
1215                 BT848_GPIO_DMA_CTL_PLTP23_16|
1216                 BT848_GPIO_DMA_CTL_GPINTC|
1217                 BT848_GPIO_DMA_CTL_GPINTI,
1218                 BT848_GPIO_DMA_CTL);
1219
1220         btwrite(0x20, BT848_E_VSCALE_HI);
1221         btwrite(0x20, BT848_O_VSCALE_HI);
1222
1223         v4l2_ctrl_handler_setup(&btv->ctrl_handler);
1224
1225         /* interrupt */
1226         init_irqreg(btv);
1227 }
1228
1229 static void bttv_reinit_bt848(struct bttv *btv)
1230 {
1231         unsigned long flags;
1232
1233         if (bttv_verbose)
1234                 pr_info("%d: reset, reinitialize\n", btv->c.nr);
1235         spin_lock_irqsave(&btv->s_lock,flags);
1236         btv->errors=0;
1237         bttv_set_dma(btv,0);
1238         spin_unlock_irqrestore(&btv->s_lock,flags);
1239
1240         init_bt848(btv);
1241         btv->pll.pll_current = -1;
1242         set_input(btv, btv->input, btv->tvnorm);
1243 }
1244
1245 static int bttv_s_ctrl(struct v4l2_ctrl *c)
1246 {
1247         struct bttv *btv = container_of(c->handler, struct bttv, ctrl_handler);
1248         int val;
1249
1250         switch (c->id) {
1251         case V4L2_CID_BRIGHTNESS:
1252                 bt848_bright(btv, c->val);
1253                 break;
1254         case V4L2_CID_HUE:
1255                 bt848_hue(btv, c->val);
1256                 break;
1257         case V4L2_CID_CONTRAST:
1258                 bt848_contrast(btv, c->val);
1259                 break;
1260         case V4L2_CID_SATURATION:
1261                 bt848_sat(btv, c->val);
1262                 break;
1263         case V4L2_CID_COLOR_KILLER:
1264                 if (c->val) {
1265                         btor(BT848_SCLOOP_CKILL, BT848_E_SCLOOP);
1266                         btor(BT848_SCLOOP_CKILL, BT848_O_SCLOOP);
1267                 } else {
1268                         btand(~BT848_SCLOOP_CKILL, BT848_E_SCLOOP);
1269                         btand(~BT848_SCLOOP_CKILL, BT848_O_SCLOOP);
1270                 }
1271                 break;
1272         case V4L2_CID_AUDIO_MUTE:
1273                 audio_mute(btv, c->val);
1274                 btv->mute = c->val;
1275                 break;
1276         case V4L2_CID_AUDIO_VOLUME:
1277                 btv->volume_gpio(btv, c->val);
1278                 break;
1279
1280         case V4L2_CID_CHROMA_AGC:
1281                 val = c->val ? BT848_SCLOOP_CAGC : 0;
1282                 btwrite(val, BT848_E_SCLOOP);
1283                 btwrite(val, BT848_O_SCLOOP);
1284                 break;
1285         case V4L2_CID_PRIVATE_COMBFILTER:
1286                 btv->opt_combfilter = c->val;
1287                 break;
1288         case V4L2_CID_PRIVATE_LUMAFILTER:
1289                 if (c->val) {
1290                         btand(~BT848_CONTROL_LDEC, BT848_E_CONTROL);
1291                         btand(~BT848_CONTROL_LDEC, BT848_O_CONTROL);
1292                 } else {
1293                         btor(BT848_CONTROL_LDEC, BT848_E_CONTROL);
1294                         btor(BT848_CONTROL_LDEC, BT848_O_CONTROL);
1295                 }
1296                 break;
1297         case V4L2_CID_PRIVATE_AUTOMUTE:
1298                 btv->opt_automute = c->val;
1299                 break;
1300         case V4L2_CID_PRIVATE_AGC_CRUSH:
1301                 btwrite(BT848_ADC_RESERVED |
1302                                 (c->val ? BT848_ADC_CRUSH : 0),
1303                                 BT848_ADC);
1304                 break;
1305         case V4L2_CID_PRIVATE_VCR_HACK:
1306                 btv->opt_vcr_hack = c->val;
1307                 break;
1308         case V4L2_CID_PRIVATE_WHITECRUSH_UPPER:
1309                 btwrite(c->val, BT848_WC_UP);
1310                 break;
1311         case V4L2_CID_PRIVATE_WHITECRUSH_LOWER:
1312                 btwrite(c->val, BT848_WC_DOWN);
1313                 break;
1314         case V4L2_CID_PRIVATE_UV_RATIO:
1315                 btv->opt_uv_ratio = c->val;
1316                 bt848_sat(btv, btv->saturation);
1317                 break;
1318         case V4L2_CID_PRIVATE_FULL_LUMA_RANGE:
1319                 btaor((c->val << 7), ~BT848_OFORM_RANGE, BT848_OFORM);
1320                 break;
1321         case V4L2_CID_PRIVATE_CORING:
1322                 btaor((c->val << 5), ~BT848_OFORM_CORE32, BT848_OFORM);
1323                 break;
1324         default:
1325                 return -EINVAL;
1326         }
1327         return 0;
1328 }
1329
1330 /* ----------------------------------------------------------------------- */
1331
1332 static const struct v4l2_ctrl_ops bttv_ctrl_ops = {
1333         .s_ctrl = bttv_s_ctrl,
1334 };
1335
1336 static struct v4l2_ctrl_config bttv_ctrl_combfilter = {
1337         .ops = &bttv_ctrl_ops,
1338         .id = V4L2_CID_PRIVATE_COMBFILTER,
1339         .name = "Comb Filter",
1340         .type = V4L2_CTRL_TYPE_BOOLEAN,
1341         .min = 0,
1342         .max = 1,
1343         .step = 1,
1344         .def = 1,
1345 };
1346
1347 static struct v4l2_ctrl_config bttv_ctrl_automute = {
1348         .ops = &bttv_ctrl_ops,
1349         .id = V4L2_CID_PRIVATE_AUTOMUTE,
1350         .name = "Auto Mute",
1351         .type = V4L2_CTRL_TYPE_BOOLEAN,
1352         .min = 0,
1353         .max = 1,
1354         .step = 1,
1355         .def = 1,
1356 };
1357
1358 static struct v4l2_ctrl_config bttv_ctrl_lumafilter = {
1359         .ops = &bttv_ctrl_ops,
1360         .id = V4L2_CID_PRIVATE_LUMAFILTER,
1361         .name = "Luma Decimation Filter",
1362         .type = V4L2_CTRL_TYPE_BOOLEAN,
1363         .min = 0,
1364         .max = 1,
1365         .step = 1,
1366         .def = 1,
1367 };
1368
1369 static struct v4l2_ctrl_config bttv_ctrl_agc_crush = {
1370         .ops = &bttv_ctrl_ops,
1371         .id = V4L2_CID_PRIVATE_AGC_CRUSH,
1372         .name = "AGC Crush",
1373         .type = V4L2_CTRL_TYPE_BOOLEAN,
1374         .min = 0,
1375         .max = 1,
1376         .step = 1,
1377         .def = 1,
1378 };
1379
1380 static struct v4l2_ctrl_config bttv_ctrl_vcr_hack = {
1381         .ops = &bttv_ctrl_ops,
1382         .id = V4L2_CID_PRIVATE_VCR_HACK,
1383         .name = "VCR Hack",
1384         .type = V4L2_CTRL_TYPE_BOOLEAN,
1385         .min = 0,
1386         .max = 1,
1387         .step = 1,
1388         .def = 1,
1389 };
1390
1391 static struct v4l2_ctrl_config bttv_ctrl_whitecrush_lower = {
1392         .ops = &bttv_ctrl_ops,
1393         .id = V4L2_CID_PRIVATE_WHITECRUSH_LOWER,
1394         .name = "Whitecrush Lower",
1395         .type = V4L2_CTRL_TYPE_INTEGER,
1396         .min = 0,
1397         .max = 255,
1398         .step = 1,
1399         .def = 0x7f,
1400 };
1401
1402 static struct v4l2_ctrl_config bttv_ctrl_whitecrush_upper = {
1403         .ops = &bttv_ctrl_ops,
1404         .id = V4L2_CID_PRIVATE_WHITECRUSH_UPPER,
1405         .name = "Whitecrush Upper",
1406         .type = V4L2_CTRL_TYPE_INTEGER,
1407         .min = 0,
1408         .max = 255,
1409         .step = 1,
1410         .def = 0xcf,
1411 };
1412
1413 static struct v4l2_ctrl_config bttv_ctrl_uv_ratio = {
1414         .ops = &bttv_ctrl_ops,
1415         .id = V4L2_CID_PRIVATE_UV_RATIO,
1416         .name = "UV Ratio",
1417         .type = V4L2_CTRL_TYPE_INTEGER,
1418         .min = 0,
1419         .max = 100,
1420         .step = 1,
1421         .def = 50,
1422 };
1423
1424 static struct v4l2_ctrl_config bttv_ctrl_full_luma = {
1425         .ops = &bttv_ctrl_ops,
1426         .id = V4L2_CID_PRIVATE_FULL_LUMA_RANGE,
1427         .name = "Full Luma Range",
1428         .type = V4L2_CTRL_TYPE_BOOLEAN,
1429         .min = 0,
1430         .max = 1,
1431         .step = 1,
1432 };
1433
1434 static struct v4l2_ctrl_config bttv_ctrl_coring = {
1435         .ops = &bttv_ctrl_ops,
1436         .id = V4L2_CID_PRIVATE_CORING,
1437         .name = "Coring",
1438         .type = V4L2_CTRL_TYPE_INTEGER,
1439         .min = 0,
1440         .max = 3,
1441         .step = 1,
1442 };
1443
1444
1445 /* ----------------------------------------------------------------------- */
1446
1447 void bttv_gpio_tracking(struct bttv *btv, char *comment)
1448 {
1449         unsigned int outbits, data;
1450         outbits = btread(BT848_GPIO_OUT_EN);
1451         data    = btread(BT848_GPIO_DATA);
1452         pr_debug("%d: gpio: en=%08x, out=%08x in=%08x [%s]\n",
1453                  btv->c.nr, outbits, data & outbits, data & ~outbits, comment);
1454 }
1455
1456 static void bttv_field_count(struct bttv *btv)
1457 {
1458         int need_count = 0;
1459
1460         if (btv->users)
1461                 need_count++;
1462
1463         if (need_count) {
1464                 /* start field counter */
1465                 btor(BT848_INT_VSYNC,BT848_INT_MASK);
1466         } else {
1467                 /* stop field counter */
1468                 btand(~BT848_INT_VSYNC,BT848_INT_MASK);
1469                 btv->field_count = 0;
1470         }
1471 }
1472
1473 static const struct bttv_format*
1474 format_by_fourcc(int fourcc)
1475 {
1476         unsigned int i;
1477
1478         for (i = 0; i < FORMATS; i++) {
1479                 if (-1 == formats[i].fourcc)
1480                         continue;
1481                 if (formats[i].fourcc == fourcc)
1482                         return formats+i;
1483         }
1484         return NULL;
1485 }
1486
1487 /* ----------------------------------------------------------------------- */
1488 /* video4linux (1) interface                                               */
1489
1490 static int bttv_prepare_buffer(struct videobuf_queue *q,struct bttv *btv,
1491                                struct bttv_buffer *buf,
1492                                const struct bttv_format *fmt,
1493                                unsigned int width, unsigned int height,
1494                                enum v4l2_field field)
1495 {
1496         struct bttv_fh *fh = q->priv_data;
1497         int redo_dma_risc = 0;
1498         struct bttv_crop c;
1499         int norm;
1500         int rc;
1501
1502         /* check settings */
1503         if (NULL == fmt)
1504                 return -EINVAL;
1505         if (fmt->btformat == BT848_COLOR_FMT_RAW) {
1506                 width  = RAW_BPL;
1507                 height = RAW_LINES*2;
1508                 if (width*height > buf->vb.bsize)
1509                         return -EINVAL;
1510                 buf->vb.size = buf->vb.bsize;
1511
1512                 /* Make sure tvnorm and vbi_end remain consistent
1513                    until we're done. */
1514
1515                 norm = btv->tvnorm;
1516
1517                 /* In this mode capturing always starts at defrect.top
1518                    (default VDELAY), ignoring cropping parameters. */
1519                 if (btv->vbi_end > bttv_tvnorms[norm].cropcap.defrect.top) {
1520                         return -EINVAL;
1521                 }
1522
1523                 c.rect = bttv_tvnorms[norm].cropcap.defrect;
1524         } else {
1525                 norm = btv->tvnorm;
1526                 c = btv->crop[!!fh->do_crop];
1527
1528                 if (width < c.min_scaled_width ||
1529                     width > c.max_scaled_width ||
1530                     height < c.min_scaled_height)
1531                         return -EINVAL;
1532
1533                 switch (field) {
1534                 case V4L2_FIELD_TOP:
1535                 case V4L2_FIELD_BOTTOM:
1536                 case V4L2_FIELD_ALTERNATE:
1537                         /* btv->crop counts frame lines. Max. scale
1538                            factor is 16:1 for frames, 8:1 for fields. */
1539                         if (height * 2 > c.max_scaled_height)
1540                                 return -EINVAL;
1541                         break;
1542
1543                 default:
1544                         if (height > c.max_scaled_height)
1545                                 return -EINVAL;
1546                         break;
1547                 }
1548
1549                 buf->vb.size = (width * height * fmt->depth) >> 3;
1550                 if (0 != buf->vb.baddr  &&  buf->vb.bsize < buf->vb.size)
1551                         return -EINVAL;
1552         }
1553
1554         /* alloc + fill struct bttv_buffer (if changed) */
1555         if (buf->vb.width != width || buf->vb.height != height ||
1556             buf->vb.field != field ||
1557             buf->tvnorm != norm || buf->fmt != fmt ||
1558             buf->crop.top != c.rect.top ||
1559             buf->crop.left != c.rect.left ||
1560             buf->crop.width != c.rect.width ||
1561             buf->crop.height != c.rect.height) {
1562                 buf->vb.width  = width;
1563                 buf->vb.height = height;
1564                 buf->vb.field  = field;
1565                 buf->tvnorm    = norm;
1566                 buf->fmt       = fmt;
1567                 buf->crop      = c.rect;
1568                 redo_dma_risc = 1;
1569         }
1570
1571         /* alloc risc memory */
1572         if (VIDEOBUF_NEEDS_INIT == buf->vb.state) {
1573                 redo_dma_risc = 1;
1574                 if (0 != (rc = videobuf_iolock(q,&buf->vb,&btv->fbuf)))
1575                         goto fail;
1576         }
1577
1578         if (redo_dma_risc)
1579                 if (0 != (rc = bttv_buffer_risc(btv,buf)))
1580                         goto fail;
1581
1582         buf->vb.state = VIDEOBUF_PREPARED;
1583         return 0;
1584
1585  fail:
1586         bttv_dma_free(q,btv,buf);
1587         return rc;
1588 }
1589
1590 static int
1591 buffer_setup(struct videobuf_queue *q, unsigned int *count, unsigned int *size)
1592 {
1593         struct bttv_fh *fh = q->priv_data;
1594
1595         *size = fh->fmt->depth*fh->width*fh->height >> 3;
1596         if (0 == *count)
1597                 *count = gbuffers;
1598         if (*size * *count > gbuffers * gbufsize)
1599                 *count = (gbuffers * gbufsize) / *size;
1600         return 0;
1601 }
1602
1603 static int
1604 buffer_prepare(struct videobuf_queue *q, struct videobuf_buffer *vb,
1605                enum v4l2_field field)
1606 {
1607         struct bttv_buffer *buf = container_of(vb,struct bttv_buffer,vb);
1608         struct bttv_fh *fh = q->priv_data;
1609
1610         return bttv_prepare_buffer(q,fh->btv, buf, fh->fmt,
1611                                    fh->width, fh->height, field);
1612 }
1613
1614 static void
1615 buffer_queue(struct videobuf_queue *q, struct videobuf_buffer *vb)
1616 {
1617         struct bttv_buffer *buf = container_of(vb,struct bttv_buffer,vb);
1618         struct bttv_fh *fh = q->priv_data;
1619         struct bttv    *btv = fh->btv;
1620
1621         buf->vb.state = VIDEOBUF_QUEUED;
1622         list_add_tail(&buf->vb.queue,&btv->capture);
1623         if (!btv->curr.frame_irq) {
1624                 btv->loop_irq |= 1;
1625                 bttv_set_dma(btv, 0x03);
1626         }
1627 }
1628
1629 static void buffer_release(struct videobuf_queue *q, struct videobuf_buffer *vb)
1630 {
1631         struct bttv_buffer *buf = container_of(vb,struct bttv_buffer,vb);
1632         struct bttv_fh *fh = q->priv_data;
1633
1634         bttv_dma_free(q,fh->btv,buf);
1635 }
1636
1637 static const struct videobuf_queue_ops bttv_video_qops = {
1638         .buf_setup    = buffer_setup,
1639         .buf_prepare  = buffer_prepare,
1640         .buf_queue    = buffer_queue,
1641         .buf_release  = buffer_release,
1642 };
1643
1644 static void radio_enable(struct bttv *btv)
1645 {
1646         /* Switch to the radio tuner */
1647         if (!btv->has_radio_tuner) {
1648                 btv->has_radio_tuner = 1;
1649                 bttv_call_all(btv, tuner, s_radio);
1650                 btv->audio_input = TVAUDIO_INPUT_RADIO;
1651                 audio_input(btv, btv->audio_input);
1652         }
1653 }
1654
1655 static int bttv_s_std(struct file *file, void *priv, v4l2_std_id id)
1656 {
1657         struct bttv_fh *fh  = priv;
1658         struct bttv *btv = fh->btv;
1659         unsigned int i;
1660
1661         for (i = 0; i < BTTV_TVNORMS; i++)
1662                 if (id & bttv_tvnorms[i].v4l2_id)
1663                         break;
1664         if (i == BTTV_TVNORMS)
1665                 return -EINVAL;
1666         btv->std = id;
1667         set_tvnorm(btv, i);
1668         return 0;
1669 }
1670
1671 static int bttv_g_std(struct file *file, void *priv, v4l2_std_id *id)
1672 {
1673         struct bttv_fh *fh  = priv;
1674         struct bttv *btv = fh->btv;
1675
1676         *id = btv->std;
1677         return 0;
1678 }
1679
1680 static int bttv_querystd(struct file *file, void *f, v4l2_std_id *id)
1681 {
1682         struct bttv_fh *fh = f;
1683         struct bttv *btv = fh->btv;
1684
1685         if (btread(BT848_DSTATUS) & BT848_DSTATUS_NUML)
1686                 *id &= V4L2_STD_625_50;
1687         else
1688                 *id &= V4L2_STD_525_60;
1689         return 0;
1690 }
1691
1692 static int bttv_enum_input(struct file *file, void *priv,
1693                                         struct v4l2_input *i)
1694 {
1695         struct bttv_fh *fh = priv;
1696         struct bttv *btv = fh->btv;
1697
1698         if (i->index >= bttv_tvcards[btv->c.type].video_inputs)
1699                 return -EINVAL;
1700
1701         i->type     = V4L2_INPUT_TYPE_CAMERA;
1702         i->audioset = 0;
1703
1704         if (btv->tuner_type != TUNER_ABSENT && i->index == 0) {
1705                 sprintf(i->name, "Television");
1706                 i->type  = V4L2_INPUT_TYPE_TUNER;
1707                 i->tuner = 0;
1708         } else if (i->index == btv->svhs) {
1709                 sprintf(i->name, "S-Video");
1710         } else {
1711                 sprintf(i->name, "Composite%d", i->index);
1712         }
1713
1714         if (i->index == btv->input) {
1715                 __u32 dstatus = btread(BT848_DSTATUS);
1716                 if (0 == (dstatus & BT848_DSTATUS_PRES))
1717                         i->status |= V4L2_IN_ST_NO_SIGNAL;
1718                 if (0 == (dstatus & BT848_DSTATUS_HLOC))
1719                         i->status |= V4L2_IN_ST_NO_H_LOCK;
1720         }
1721
1722         i->std = BTTV_NORMS;
1723         return 0;
1724 }
1725
1726 static int bttv_g_input(struct file *file, void *priv, unsigned int *i)
1727 {
1728         struct bttv_fh *fh = priv;
1729         struct bttv *btv = fh->btv;
1730
1731         *i = btv->input;
1732
1733         return 0;
1734 }
1735
1736 static int bttv_s_input(struct file *file, void *priv, unsigned int i)
1737 {
1738         struct bttv_fh *fh  = priv;
1739         struct bttv *btv = fh->btv;
1740
1741         if (i >= bttv_tvcards[btv->c.type].video_inputs)
1742                 return -EINVAL;
1743
1744         set_input(btv, i, btv->tvnorm);
1745         return 0;
1746 }
1747
1748 static int bttv_s_tuner(struct file *file, void *priv,
1749                                         const struct v4l2_tuner *t)
1750 {
1751         struct bttv_fh *fh  = priv;
1752         struct bttv *btv = fh->btv;
1753
1754         if (t->index)
1755                 return -EINVAL;
1756
1757         bttv_call_all(btv, tuner, s_tuner, t);
1758
1759         if (btv->audio_mode_gpio) {
1760                 struct v4l2_tuner copy = *t;
1761
1762                 btv->audio_mode_gpio(btv, &copy, 1);
1763         }
1764         return 0;
1765 }
1766
1767 static int bttv_g_frequency(struct file *file, void *priv,
1768                                         struct v4l2_frequency *f)
1769 {
1770         struct bttv_fh *fh  = priv;
1771         struct bttv *btv = fh->btv;
1772
1773         if (f->tuner)
1774                 return -EINVAL;
1775
1776         if (f->type == V4L2_TUNER_RADIO)
1777                 radio_enable(btv);
1778         f->frequency = f->type == V4L2_TUNER_RADIO ?
1779                                 btv->radio_freq : btv->tv_freq;
1780
1781         return 0;
1782 }
1783
1784 static void bttv_set_frequency(struct bttv *btv, const struct v4l2_frequency *f)
1785 {
1786         struct v4l2_frequency new_freq = *f;
1787
1788         bttv_call_all(btv, tuner, s_frequency, f);
1789         /* s_frequency may clamp the frequency, so get the actual
1790            frequency before assigning radio/tv_freq. */
1791         bttv_call_all(btv, tuner, g_frequency, &new_freq);
1792         if (new_freq.type == V4L2_TUNER_RADIO) {
1793                 radio_enable(btv);
1794                 btv->radio_freq = new_freq.frequency;
1795                 if (btv->has_tea575x) {
1796                         btv->tea.freq = btv->radio_freq;
1797                         snd_tea575x_set_freq(&btv->tea);
1798                 }
1799         } else {
1800                 btv->tv_freq = new_freq.frequency;
1801         }
1802 }
1803
1804 static int bttv_s_frequency(struct file *file, void *priv,
1805                                         const struct v4l2_frequency *f)
1806 {
1807         struct bttv_fh *fh  = priv;
1808         struct bttv *btv = fh->btv;
1809
1810         if (f->tuner)
1811                 return -EINVAL;
1812
1813         bttv_set_frequency(btv, f);
1814         return 0;
1815 }
1816
1817 static int bttv_log_status(struct file *file, void *f)
1818 {
1819         struct video_device *vdev = video_devdata(file);
1820         struct bttv_fh *fh  = f;
1821         struct bttv *btv = fh->btv;
1822
1823         v4l2_ctrl_handler_log_status(vdev->ctrl_handler, btv->c.v4l2_dev.name);
1824         bttv_call_all(btv, core, log_status);
1825         return 0;
1826 }
1827
1828 #ifdef CONFIG_VIDEO_ADV_DEBUG
1829 static int bttv_g_register(struct file *file, void *f,
1830                                         struct v4l2_dbg_register *reg)
1831 {
1832         struct bttv_fh *fh = f;
1833         struct bttv *btv = fh->btv;
1834
1835         /* bt848 has a 12-bit register space */
1836         reg->reg &= 0xfff;
1837         reg->val = btread(reg->reg);
1838         reg->size = 1;
1839
1840         return 0;
1841 }
1842
1843 static int bttv_s_register(struct file *file, void *f,
1844                                         const struct v4l2_dbg_register *reg)
1845 {
1846         struct bttv_fh *fh = f;
1847         struct bttv *btv = fh->btv;
1848
1849         /* bt848 has a 12-bit register space */
1850         btwrite(reg->val, reg->reg & 0xfff);
1851
1852         return 0;
1853 }
1854 #endif
1855
1856 /* Given cropping boundaries b and the scaled width and height of a
1857    single field or frame, which must not exceed hardware limits, this
1858    function adjusts the cropping parameters c. */
1859 static void
1860 bttv_crop_adjust        (struct bttv_crop *             c,
1861                          const struct v4l2_rect *       b,
1862                          __s32                          width,
1863                          __s32                          height,
1864                          enum v4l2_field                field)
1865 {
1866         __s32 frame_height = height << !V4L2_FIELD_HAS_BOTH(field);
1867         __s32 max_left;
1868         __s32 max_top;
1869
1870         if (width < c->min_scaled_width) {
1871                 /* Max. hor. scale factor 16:1. */
1872                 c->rect.width = width * 16;
1873         } else if (width > c->max_scaled_width) {
1874                 /* Min. hor. scale factor 1:1. */
1875                 c->rect.width = width;
1876
1877                 max_left = b->left + b->width - width;
1878                 max_left = min(max_left, (__s32) MAX_HDELAY);
1879                 if (c->rect.left > max_left)
1880                         c->rect.left = max_left;
1881         }
1882
1883         if (height < c->min_scaled_height) {
1884                 /* Max. vert. scale factor 16:1, single fields 8:1. */
1885                 c->rect.height = height * 16;
1886         } else if (frame_height > c->max_scaled_height) {
1887                 /* Min. vert. scale factor 1:1.
1888                    Top and height count field lines times two. */
1889                 c->rect.height = (frame_height + 1) & ~1;
1890
1891                 max_top = b->top + b->height - c->rect.height;
1892                 if (c->rect.top > max_top)
1893                         c->rect.top = max_top;
1894         }
1895
1896         bttv_crop_calc_limits(c);
1897 }
1898
1899 /* Returns an error if scaling to a frame or single field with the given
1900    width and height is not possible with the current cropping parameters
1901    and width aligned according to width_mask. If adjust_size is TRUE the
1902    function may adjust the width and/or height instead, rounding width
1903    to (width + width_bias) & width_mask. If adjust_crop is TRUE it may
1904    also adjust the current cropping parameters to get closer to the
1905    desired image size. */
1906 static int
1907 limit_scaled_size_lock       (struct bttv_fh *               fh,
1908                          __s32 *                        width,
1909                          __s32 *                        height,
1910                          enum v4l2_field                field,
1911                          unsigned int                   width_mask,
1912                          unsigned int                   width_bias,
1913                          int                            adjust_size,
1914                          int                            adjust_crop)
1915 {
1916         struct bttv *btv = fh->btv;
1917         const struct v4l2_rect *b;
1918         struct bttv_crop *c;
1919         __s32 min_width;
1920         __s32 min_height;
1921         __s32 max_width;
1922         __s32 max_height;
1923         int rc;
1924
1925         BUG_ON((int) width_mask >= 0 ||
1926                width_bias >= (unsigned int) -width_mask);
1927
1928         /* Make sure tvnorm, vbi_end and the current cropping parameters
1929            remain consistent until we're done. */
1930
1931         b = &bttv_tvnorms[btv->tvnorm].cropcap.bounds;
1932
1933         /* Do crop - use current, don't - use default parameters. */
1934         c = &btv->crop[!!fh->do_crop];
1935
1936         if (fh->do_crop
1937             && adjust_size
1938             && adjust_crop
1939             && !locked_btres(btv, VIDEO_RESOURCES)) {
1940                 min_width = 48;
1941                 min_height = 32;
1942
1943                 /* We cannot scale up. When the scaled image is larger
1944                    than crop.rect we adjust the crop.rect as required
1945                    by the V4L2 spec, hence cropcap.bounds are our limit. */
1946                 max_width = min_t(unsigned int, b->width, MAX_HACTIVE);
1947                 max_height = b->height;
1948
1949                 /* We cannot capture the same line as video and VBI data.
1950                    Note btv->vbi_end is really a minimum, see
1951                    bttv_vbi_try_fmt(). */
1952                 if (btv->vbi_end > b->top) {
1953                         max_height -= btv->vbi_end - b->top;
1954                         rc = -EBUSY;
1955                         if (min_height > max_height)
1956                                 goto fail;
1957                 }
1958         } else {
1959                 rc = -EBUSY;
1960                 if (btv->vbi_end > c->rect.top)
1961                         goto fail;
1962
1963                 min_width  = c->min_scaled_width;
1964                 min_height = c->min_scaled_height;
1965                 max_width  = c->max_scaled_width;
1966                 max_height = c->max_scaled_height;
1967
1968                 adjust_crop = 0;
1969         }
1970
1971         min_width = (min_width - width_mask - 1) & width_mask;
1972         max_width = max_width & width_mask;
1973
1974         /* Max. scale factor is 16:1 for frames, 8:1 for fields. */
1975         /* Min. scale factor is 1:1. */
1976         max_height >>= !V4L2_FIELD_HAS_BOTH(field);
1977
1978         if (adjust_size) {
1979                 *width = clamp(*width, min_width, max_width);
1980                 *height = clamp(*height, min_height, max_height);
1981
1982                 /* Round after clamping to avoid overflow. */
1983                 *width = (*width + width_bias) & width_mask;
1984
1985                 if (adjust_crop) {
1986                         bttv_crop_adjust(c, b, *width, *height, field);
1987
1988                         if (btv->vbi_end > c->rect.top) {
1989                                 /* Move the crop window out of the way. */
1990                                 c->rect.top = btv->vbi_end;
1991                         }
1992                 }
1993         } else {
1994                 rc = -EINVAL;
1995                 if (*width  < min_width ||
1996                     *height < min_height ||
1997                     *width  > max_width ||
1998                     *height > max_height ||
1999                     0 != (*width & ~width_mask))
2000                         goto fail;
2001         }
2002
2003         rc = 0; /* success */
2004
2005  fail:
2006
2007         return rc;
2008 }
2009
2010 /* ----------------------------------------------------------------------- */
2011
2012 static struct videobuf_queue* bttv_queue(struct bttv_fh *fh)
2013 {
2014         struct videobuf_queue* q = NULL;
2015
2016         switch (fh->type) {
2017         case V4L2_BUF_TYPE_VIDEO_CAPTURE:
2018                 q = &fh->cap;
2019                 break;
2020         case V4L2_BUF_TYPE_VBI_CAPTURE:
2021                 q = &fh->vbi;
2022                 break;
2023         default:
2024                 BUG();
2025         }
2026         return q;
2027 }
2028
2029 static int bttv_resource(struct bttv_fh *fh)
2030 {
2031         int res = 0;
2032
2033         switch (fh->type) {
2034         case V4L2_BUF_TYPE_VIDEO_CAPTURE:
2035                 res = RESOURCE_VIDEO_STREAM;
2036                 break;
2037         case V4L2_BUF_TYPE_VBI_CAPTURE:
2038                 res = RESOURCE_VBI;
2039                 break;
2040         default:
2041                 BUG();
2042         }
2043         return res;
2044 }
2045
2046 static int bttv_switch_type(struct bttv_fh *fh, enum v4l2_buf_type type)
2047 {
2048         struct videobuf_queue *q = bttv_queue(fh);
2049         int res = bttv_resource(fh);
2050
2051         if (check_btres(fh,res))
2052                 return -EBUSY;
2053         if (videobuf_queue_is_busy(q))
2054                 return -EBUSY;
2055         fh->type = type;
2056         return 0;
2057 }
2058
2059 static void
2060 pix_format_set_size     (struct v4l2_pix_format *       f,
2061                          const struct bttv_format *     fmt,
2062                          unsigned int                   width,
2063                          unsigned int                   height)
2064 {
2065         f->width = width;
2066         f->height = height;
2067
2068         if (fmt->flags & FORMAT_FLAGS_PLANAR) {
2069                 f->bytesperline = width; /* Y plane */
2070                 f->sizeimage = (width * height * fmt->depth) >> 3;
2071         } else {
2072                 f->bytesperline = (width * fmt->depth) >> 3;
2073                 f->sizeimage = height * f->bytesperline;
2074         }
2075 }
2076
2077 static int bttv_g_fmt_vid_cap(struct file *file, void *priv,
2078                                         struct v4l2_format *f)
2079 {
2080         struct bttv_fh *fh  = priv;
2081
2082         pix_format_set_size(&f->fmt.pix, fh->fmt,
2083                                 fh->width, fh->height);
2084         f->fmt.pix.field        = fh->cap.field;
2085         f->fmt.pix.pixelformat  = fh->fmt->fourcc;
2086         f->fmt.pix.colorspace   = V4L2_COLORSPACE_SMPTE170M;
2087
2088         return 0;
2089 }
2090
2091 static void bttv_get_width_mask_vid_cap(const struct bttv_format *fmt,
2092                                         unsigned int *width_mask,
2093                                         unsigned int *width_bias)
2094 {
2095         if (fmt->flags & FORMAT_FLAGS_PLANAR) {
2096                 *width_mask = ~15; /* width must be a multiple of 16 pixels */
2097                 *width_bias = 8;   /* nearest */
2098         } else {
2099                 *width_mask = ~3; /* width must be a multiple of 4 pixels */
2100                 *width_bias = 2;  /* nearest */
2101         }
2102 }
2103
2104 static int bttv_try_fmt_vid_cap(struct file *file, void *priv,
2105                                                 struct v4l2_format *f)
2106 {
2107         const struct bttv_format *fmt;
2108         struct bttv_fh *fh = priv;
2109         struct bttv *btv = fh->btv;
2110         enum v4l2_field field;
2111         __s32 width, height;
2112         __s32 height2;
2113         unsigned int width_mask, width_bias;
2114         int rc;
2115
2116         fmt = format_by_fourcc(f->fmt.pix.pixelformat);
2117         if (NULL == fmt)
2118                 return -EINVAL;
2119
2120         field = f->fmt.pix.field;
2121
2122         switch (field) {
2123         case V4L2_FIELD_TOP:
2124         case V4L2_FIELD_BOTTOM:
2125         case V4L2_FIELD_ALTERNATE:
2126         case V4L2_FIELD_INTERLACED:
2127                 break;
2128         case V4L2_FIELD_SEQ_BT:
2129         case V4L2_FIELD_SEQ_TB:
2130                 if (!(fmt->flags & FORMAT_FLAGS_PLANAR)) {
2131                         field = V4L2_FIELD_SEQ_TB;
2132                         break;
2133                 }
2134                 fallthrough;
2135         default: /* FIELD_ANY case */
2136                 height2 = btv->crop[!!fh->do_crop].rect.height >> 1;
2137                 field = (f->fmt.pix.height > height2)
2138                         ? V4L2_FIELD_INTERLACED
2139                         : V4L2_FIELD_BOTTOM;
2140                 break;
2141         }
2142
2143         width = f->fmt.pix.width;
2144         height = f->fmt.pix.height;
2145
2146         bttv_get_width_mask_vid_cap(fmt, &width_mask, &width_bias);
2147         rc = limit_scaled_size_lock(fh, &width, &height, field,
2148                                width_mask, width_bias,
2149                                /* adjust_size */ 1,
2150                                /* adjust_crop */ 0);
2151         if (0 != rc)
2152                 return rc;
2153
2154         /* update data for the application */
2155         f->fmt.pix.field = field;
2156         pix_format_set_size(&f->fmt.pix, fmt, width, height);
2157         f->fmt.pix.colorspace = V4L2_COLORSPACE_SMPTE170M;
2158
2159         return 0;
2160 }
2161
2162 static int bttv_s_fmt_vid_cap(struct file *file, void *priv,
2163                                 struct v4l2_format *f)
2164 {
2165         int retval;
2166         const struct bttv_format *fmt;
2167         struct bttv_fh *fh = priv;
2168         struct bttv *btv = fh->btv;
2169         __s32 width, height;
2170         unsigned int width_mask, width_bias;
2171         enum v4l2_field field;
2172
2173         retval = bttv_switch_type(fh, f->type);
2174         if (0 != retval)
2175                 return retval;
2176
2177         retval = bttv_try_fmt_vid_cap(file, priv, f);
2178         if (0 != retval)
2179                 return retval;
2180
2181         width = f->fmt.pix.width;
2182         height = f->fmt.pix.height;
2183         field = f->fmt.pix.field;
2184
2185         fmt = format_by_fourcc(f->fmt.pix.pixelformat);
2186         bttv_get_width_mask_vid_cap(fmt, &width_mask, &width_bias);
2187         retval = limit_scaled_size_lock(fh, &width, &height, f->fmt.pix.field,
2188                                width_mask, width_bias,
2189                                /* adjust_size */ 1,
2190                                /* adjust_crop */ 1);
2191         if (0 != retval)
2192                 return retval;
2193
2194         f->fmt.pix.field = field;
2195
2196         /* update our state information */
2197         fh->fmt              = fmt;
2198         fh->cap.field        = f->fmt.pix.field;
2199         fh->cap.last         = V4L2_FIELD_NONE;
2200         fh->width            = f->fmt.pix.width;
2201         fh->height           = f->fmt.pix.height;
2202         btv->init.fmt        = fmt;
2203         btv->init.width      = f->fmt.pix.width;
2204         btv->init.height     = f->fmt.pix.height;
2205
2206         return 0;
2207 }
2208
2209 static int bttv_querycap(struct file *file, void  *priv,
2210                                 struct v4l2_capability *cap)
2211 {
2212         struct bttv_fh *fh = priv;
2213         struct bttv *btv = fh->btv;
2214
2215         if (0 == v4l2)
2216                 return -EINVAL;
2217
2218         strscpy(cap->driver, "bttv", sizeof(cap->driver));
2219         strscpy(cap->card, btv->video_dev.name, sizeof(cap->card));
2220         cap->capabilities = V4L2_CAP_VIDEO_CAPTURE | V4L2_CAP_READWRITE |
2221                             V4L2_CAP_STREAMING | V4L2_CAP_DEVICE_CAPS;
2222         if (video_is_registered(&btv->vbi_dev))
2223                 cap->capabilities |= V4L2_CAP_VBI_CAPTURE;
2224         if (video_is_registered(&btv->radio_dev)) {
2225                 cap->capabilities |= V4L2_CAP_RADIO;
2226                 if (btv->has_tea575x)
2227                         cap->capabilities |= V4L2_CAP_HW_FREQ_SEEK;
2228         }
2229
2230         /*
2231          * No need to lock here: those vars are initialized during board
2232          * probe and remains untouched during the rest of the driver lifecycle
2233          */
2234         if (btv->has_saa6588)
2235                 cap->capabilities |= V4L2_CAP_RDS_CAPTURE;
2236         if (btv->tuner_type != TUNER_ABSENT)
2237                 cap->capabilities |= V4L2_CAP_TUNER;
2238         return 0;
2239 }
2240
2241 static int bttv_enum_fmt_vid_cap(struct file *file, void  *priv,
2242                                  struct v4l2_fmtdesc *f)
2243 {
2244         int index = -1, i;
2245
2246         for (i = 0; i < FORMATS; i++) {
2247                 if (formats[i].fourcc != -1)
2248                         index++;
2249                 if ((unsigned int)index == f->index)
2250                         break;
2251         }
2252         if (FORMATS == i)
2253                 return -EINVAL;
2254
2255         f->pixelformat = formats[i].fourcc;
2256
2257         return 0;
2258 }
2259
2260 static int bttv_reqbufs(struct file *file, void *priv,
2261                                 struct v4l2_requestbuffers *p)
2262 {
2263         struct bttv_fh *fh = priv;
2264         return videobuf_reqbufs(bttv_queue(fh), p);
2265 }
2266
2267 static int bttv_querybuf(struct file *file, void *priv,
2268                                 struct v4l2_buffer *b)
2269 {
2270         struct bttv_fh *fh = priv;
2271         return videobuf_querybuf(bttv_queue(fh), b);
2272 }
2273
2274 static int bttv_qbuf(struct file *file, void *priv, struct v4l2_buffer *b)
2275 {
2276         struct bttv_fh *fh = priv;
2277         struct bttv *btv = fh->btv;
2278         int res = bttv_resource(fh);
2279
2280         if (!check_alloc_btres_lock(btv, fh, res))
2281                 return -EBUSY;
2282
2283         return videobuf_qbuf(bttv_queue(fh), b);
2284 }
2285
2286 static int bttv_dqbuf(struct file *file, void *priv, struct v4l2_buffer *b)
2287 {
2288         struct bttv_fh *fh = priv;
2289         return videobuf_dqbuf(bttv_queue(fh), b,
2290                         file->f_flags & O_NONBLOCK);
2291 }
2292
2293 static int bttv_streamon(struct file *file, void *priv,
2294                                         enum v4l2_buf_type type)
2295 {
2296         struct bttv_fh *fh = priv;
2297         struct bttv *btv = fh->btv;
2298         int res = bttv_resource(fh);
2299
2300         if (!check_alloc_btres_lock(btv, fh, res))
2301                 return -EBUSY;
2302         return videobuf_streamon(bttv_queue(fh));
2303 }
2304
2305
2306 static int bttv_streamoff(struct file *file, void *priv,
2307                                         enum v4l2_buf_type type)
2308 {
2309         struct bttv_fh *fh = priv;
2310         struct bttv *btv = fh->btv;
2311         int retval;
2312         int res = bttv_resource(fh);
2313
2314
2315         retval = videobuf_streamoff(bttv_queue(fh));
2316         if (retval < 0)
2317                 return retval;
2318         free_btres_lock(btv, fh, res);
2319         return 0;
2320 }
2321
2322 static int bttv_g_parm(struct file *file, void *f,
2323                                 struct v4l2_streamparm *parm)
2324 {
2325         struct bttv_fh *fh = f;
2326         struct bttv *btv = fh->btv;
2327
2328         if (parm->type != V4L2_BUF_TYPE_VIDEO_CAPTURE)
2329                 return -EINVAL;
2330         parm->parm.capture.readbuffers = gbuffers;
2331         v4l2_video_std_frame_period(bttv_tvnorms[btv->tvnorm].v4l2_id,
2332                                     &parm->parm.capture.timeperframe);
2333
2334         return 0;
2335 }
2336
2337 static int bttv_g_tuner(struct file *file, void *priv,
2338                                 struct v4l2_tuner *t)
2339 {
2340         struct bttv_fh *fh = priv;
2341         struct bttv *btv = fh->btv;
2342
2343         if (0 != t->index)
2344                 return -EINVAL;
2345
2346         t->rxsubchans = V4L2_TUNER_SUB_MONO;
2347         t->capability = V4L2_TUNER_CAP_NORM;
2348         bttv_call_all(btv, tuner, g_tuner, t);
2349         strscpy(t->name, "Television", sizeof(t->name));
2350         t->type       = V4L2_TUNER_ANALOG_TV;
2351         if (btread(BT848_DSTATUS)&BT848_DSTATUS_HLOC)
2352                 t->signal = 0xffff;
2353
2354         if (btv->audio_mode_gpio)
2355                 btv->audio_mode_gpio(btv, t, 0);
2356
2357         return 0;
2358 }
2359
2360 static int bttv_g_pixelaspect(struct file *file, void *priv,
2361                               int type, struct v4l2_fract *f)
2362 {
2363         struct bttv_fh *fh = priv;
2364         struct bttv *btv = fh->btv;
2365
2366         if (type != V4L2_BUF_TYPE_VIDEO_CAPTURE)
2367                 return -EINVAL;
2368
2369         /* defrect and bounds are set via g_selection */
2370         *f = bttv_tvnorms[btv->tvnorm].cropcap.pixelaspect;
2371         return 0;
2372 }
2373
2374 static int bttv_g_selection(struct file *file, void *f, struct v4l2_selection *sel)
2375 {
2376         struct bttv_fh *fh = f;
2377         struct bttv *btv = fh->btv;
2378
2379         if (sel->type != V4L2_BUF_TYPE_VIDEO_CAPTURE)
2380                 return -EINVAL;
2381
2382         switch (sel->target) {
2383         case V4L2_SEL_TGT_CROP:
2384                 /*
2385                  * No fh->do_crop = 1; because btv->crop[1] may be
2386                  * inconsistent with fh->width or fh->height and apps
2387                  * do not expect a change here.
2388                  */
2389                 sel->r = btv->crop[!!fh->do_crop].rect;
2390                 break;
2391         case V4L2_SEL_TGT_CROP_DEFAULT:
2392                 sel->r = bttv_tvnorms[btv->tvnorm].cropcap.defrect;
2393                 break;
2394         case V4L2_SEL_TGT_CROP_BOUNDS:
2395                 sel->r = bttv_tvnorms[btv->tvnorm].cropcap.bounds;
2396                 break;
2397         default:
2398                 return -EINVAL;
2399         }
2400
2401         return 0;
2402 }
2403
2404 static int bttv_s_selection(struct file *file, void *f, struct v4l2_selection *sel)
2405 {
2406         struct bttv_fh *fh = f;
2407         struct bttv *btv = fh->btv;
2408         const struct v4l2_rect *b;
2409         int retval;
2410         struct bttv_crop c;
2411         __s32 b_left;
2412         __s32 b_top;
2413         __s32 b_right;
2414         __s32 b_bottom;
2415
2416         if (sel->type != V4L2_BUF_TYPE_VIDEO_CAPTURE)
2417                 return -EINVAL;
2418
2419         if (sel->target != V4L2_SEL_TGT_CROP)
2420                 return -EINVAL;
2421
2422         /* Make sure tvnorm, vbi_end and the current cropping
2423            parameters remain consistent until we're done. Note
2424            read() may change vbi_end in check_alloc_btres_lock(). */
2425         retval = -EBUSY;
2426
2427         if (locked_btres(fh->btv, VIDEO_RESOURCES)) {
2428                 return retval;
2429         }
2430
2431         b = &bttv_tvnorms[btv->tvnorm].cropcap.bounds;
2432
2433         b_left = b->left;
2434         b_right = b_left + b->width;
2435         b_bottom = b->top + b->height;
2436
2437         b_top = max(b->top, btv->vbi_end);
2438         if (b_top + 32 >= b_bottom) {
2439                 return retval;
2440         }
2441
2442         /* Min. scaled size 48 x 32. */
2443         c.rect.left = clamp_t(s32, sel->r.left, b_left, b_right - 48);
2444         c.rect.left = min(c.rect.left, (__s32) MAX_HDELAY);
2445
2446         c.rect.width = clamp_t(s32, sel->r.width,
2447                              48, b_right - c.rect.left);
2448
2449         c.rect.top = clamp_t(s32, sel->r.top, b_top, b_bottom - 32);
2450         /* Top and height must be a multiple of two. */
2451         c.rect.top = (c.rect.top + 1) & ~1;
2452
2453         c.rect.height = clamp_t(s32, sel->r.height,
2454                               32, b_bottom - c.rect.top);
2455         c.rect.height = (c.rect.height + 1) & ~1;
2456
2457         bttv_crop_calc_limits(&c);
2458
2459         sel->r = c.rect;
2460
2461         btv->crop[1] = c;
2462
2463         fh->do_crop = 1;
2464
2465         if (fh->width < c.min_scaled_width) {
2466                 fh->width = c.min_scaled_width;
2467                 btv->init.width = c.min_scaled_width;
2468         } else if (fh->width > c.max_scaled_width) {
2469                 fh->width = c.max_scaled_width;
2470                 btv->init.width = c.max_scaled_width;
2471         }
2472
2473         if (fh->height < c.min_scaled_height) {
2474                 fh->height = c.min_scaled_height;
2475                 btv->init.height = c.min_scaled_height;
2476         } else if (fh->height > c.max_scaled_height) {
2477                 fh->height = c.max_scaled_height;
2478                 btv->init.height = c.max_scaled_height;
2479         }
2480
2481         return 0;
2482 }
2483
2484 static ssize_t bttv_read(struct file *file, char __user *data,
2485                          size_t count, loff_t *ppos)
2486 {
2487         struct bttv_fh *fh = file->private_data;
2488         int retval = 0;
2489
2490         if (fh->btv->errors)
2491                 bttv_reinit_bt848(fh->btv);
2492         dprintk("%d: read count=%d type=%s\n",
2493                 fh->btv->c.nr, (int)count, v4l2_type_names[fh->type]);
2494
2495         switch (fh->type) {
2496         case V4L2_BUF_TYPE_VIDEO_CAPTURE:
2497                 if (!check_alloc_btres_lock(fh->btv, fh, RESOURCE_VIDEO_READ)) {
2498                         /* VIDEO_READ in use by another fh,
2499                            or VIDEO_STREAM by any fh. */
2500                         return -EBUSY;
2501                 }
2502                 retval = videobuf_read_one(&fh->cap, data, count, ppos,
2503                                            file->f_flags & O_NONBLOCK);
2504                 free_btres_lock(fh->btv, fh, RESOURCE_VIDEO_READ);
2505                 break;
2506         case V4L2_BUF_TYPE_VBI_CAPTURE:
2507                 if (!check_alloc_btres_lock(fh->btv,fh,RESOURCE_VBI))
2508                         return -EBUSY;
2509                 retval = videobuf_read_stream(&fh->vbi, data, count, ppos, 1,
2510                                               file->f_flags & O_NONBLOCK);
2511                 break;
2512         default:
2513                 BUG();
2514         }
2515         return retval;
2516 }
2517
2518 static __poll_t bttv_poll(struct file *file, poll_table *wait)
2519 {
2520         struct bttv_fh *fh = file->private_data;
2521         struct bttv_buffer *buf;
2522         enum v4l2_field field;
2523         __poll_t rc = 0;
2524         __poll_t req_events = poll_requested_events(wait);
2525
2526         if (v4l2_event_pending(&fh->fh))
2527                 rc = EPOLLPRI;
2528         else if (req_events & EPOLLPRI)
2529                 poll_wait(file, &fh->fh.wait, wait);
2530
2531         if (!(req_events & (EPOLLIN | EPOLLRDNORM)))
2532                 return rc;
2533
2534         if (V4L2_BUF_TYPE_VBI_CAPTURE == fh->type) {
2535                 if (!check_alloc_btres_lock(fh->btv,fh,RESOURCE_VBI))
2536                         return rc | EPOLLERR;
2537                 return rc | videobuf_poll_stream(file, &fh->vbi, wait);
2538         }
2539
2540         if (check_btres(fh,RESOURCE_VIDEO_STREAM)) {
2541                 /* streaming capture */
2542                 if (list_empty(&fh->cap.stream))
2543                         return rc | EPOLLERR;
2544                 buf = list_entry(fh->cap.stream.next,struct bttv_buffer,vb.stream);
2545         } else {
2546                 /* read() capture */
2547                 if (NULL == fh->cap.read_buf) {
2548                         /* need to capture a new frame */
2549                         if (locked_btres(fh->btv,RESOURCE_VIDEO_STREAM))
2550                                 return rc | EPOLLERR;
2551                         fh->cap.read_buf = videobuf_sg_alloc(fh->cap.msize);
2552                         if (NULL == fh->cap.read_buf)
2553                                 return rc | EPOLLERR;
2554                         fh->cap.read_buf->memory = V4L2_MEMORY_USERPTR;
2555                         field = videobuf_next_field(&fh->cap);
2556                         if (0 != fh->cap.ops->buf_prepare(&fh->cap,fh->cap.read_buf,field)) {
2557                                 kfree (fh->cap.read_buf);
2558                                 fh->cap.read_buf = NULL;
2559                                 return rc | EPOLLERR;
2560                         }
2561                         fh->cap.ops->buf_queue(&fh->cap,fh->cap.read_buf);
2562                         fh->cap.read_off = 0;
2563                 }
2564                 buf = (struct bttv_buffer*)fh->cap.read_buf;
2565         }
2566
2567         poll_wait(file, &buf->vb.done, wait);
2568         if (buf->vb.state == VIDEOBUF_DONE ||
2569             buf->vb.state == VIDEOBUF_ERROR)
2570                 rc = rc | EPOLLIN|EPOLLRDNORM;
2571         return rc;
2572 }
2573
2574 static int bttv_open(struct file *file)
2575 {
2576         struct video_device *vdev = video_devdata(file);
2577         struct bttv *btv = video_drvdata(file);
2578         struct bttv_fh *fh;
2579         enum v4l2_buf_type type = 0;
2580
2581         dprintk("open dev=%s\n", video_device_node_name(vdev));
2582
2583         if (vdev->vfl_type == VFL_TYPE_VIDEO) {
2584                 type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
2585         } else if (vdev->vfl_type == VFL_TYPE_VBI) {
2586                 type = V4L2_BUF_TYPE_VBI_CAPTURE;
2587         } else {
2588                 WARN_ON(1);
2589                 return -ENODEV;
2590         }
2591
2592         dprintk("%d: open called (type=%s)\n",
2593                 btv->c.nr, v4l2_type_names[type]);
2594
2595         /* allocate per filehandle data */
2596         fh = kmalloc(sizeof(*fh), GFP_KERNEL);
2597         if (unlikely(!fh))
2598                 return -ENOMEM;
2599         btv->users++;
2600         file->private_data = fh;
2601
2602         *fh = btv->init;
2603         v4l2_fh_init(&fh->fh, vdev);
2604
2605         fh->type = type;
2606
2607         videobuf_queue_sg_init(&fh->cap, &bttv_video_qops,
2608                             &btv->c.pci->dev, &btv->s_lock,
2609                             V4L2_BUF_TYPE_VIDEO_CAPTURE,
2610                             V4L2_FIELD_INTERLACED,
2611                             sizeof(struct bttv_buffer),
2612                             fh, &btv->lock);
2613         videobuf_queue_sg_init(&fh->vbi, &bttv_vbi_qops,
2614                             &btv->c.pci->dev, &btv->s_lock,
2615                             V4L2_BUF_TYPE_VBI_CAPTURE,
2616                             V4L2_FIELD_SEQ_TB,
2617                             sizeof(struct bttv_buffer),
2618                             fh, &btv->lock);
2619         set_tvnorm(btv,btv->tvnorm);
2620         set_input(btv, btv->input, btv->tvnorm);
2621         audio_mute(btv, btv->mute);
2622
2623         /* The V4L2 spec requires one global set of cropping parameters
2624            which only change on request. These are stored in btv->crop[1].
2625            However for compatibility with V4L apps and cropping unaware
2626            V4L2 apps we now reset the cropping parameters as seen through
2627            this fh, which is to say VIDIOC_G_SELECTION and scaling limit checks
2628            will use btv->crop[0], the default cropping parameters for the
2629            current video standard, and VIDIOC_S_FMT will not implicitly
2630            change the cropping parameters until VIDIOC_S_SELECTION has been
2631            called. */
2632         fh->do_crop = !reset_crop; /* module parameter */
2633
2634         /* Likewise there should be one global set of VBI capture
2635            parameters, but for compatibility with V4L apps and earlier
2636            driver versions each fh has its own parameters. */
2637         bttv_vbi_fmt_reset(&fh->vbi_fmt, btv->tvnorm);
2638
2639         bttv_field_count(btv);
2640         v4l2_fh_add(&fh->fh);
2641         return 0;
2642 }
2643
2644 static int bttv_release(struct file *file)
2645 {
2646         struct bttv_fh *fh = file->private_data;
2647         struct bttv *btv = fh->btv;
2648
2649         /* stop video capture */
2650         if (check_btres(fh, RESOURCE_VIDEO_STREAM)) {
2651                 videobuf_streamoff(&fh->cap);
2652                 free_btres_lock(btv,fh,RESOURCE_VIDEO_STREAM);
2653         }
2654         if (fh->cap.read_buf) {
2655                 buffer_release(&fh->cap,fh->cap.read_buf);
2656                 kfree(fh->cap.read_buf);
2657         }
2658         if (check_btres(fh, RESOURCE_VIDEO_READ)) {
2659                 free_btres_lock(btv, fh, RESOURCE_VIDEO_READ);
2660         }
2661
2662         /* stop vbi capture */
2663         if (check_btres(fh, RESOURCE_VBI)) {
2664                 videobuf_stop(&fh->vbi);
2665                 free_btres_lock(btv,fh,RESOURCE_VBI);
2666         }
2667
2668         /* free stuff */
2669
2670         videobuf_mmap_free(&fh->cap);
2671         videobuf_mmap_free(&fh->vbi);
2672         file->private_data = NULL;
2673
2674         btv->users--;
2675         bttv_field_count(btv);
2676
2677         if (!btv->users)
2678                 audio_mute(btv, btv->mute);
2679
2680         v4l2_fh_del(&fh->fh);
2681         v4l2_fh_exit(&fh->fh);
2682         kfree(fh);
2683         return 0;
2684 }
2685
2686 static int
2687 bttv_mmap(struct file *file, struct vm_area_struct *vma)
2688 {
2689         struct bttv_fh *fh = file->private_data;
2690
2691         dprintk("%d: mmap type=%s 0x%lx+%ld\n",
2692                 fh->btv->c.nr, v4l2_type_names[fh->type],
2693                 vma->vm_start, vma->vm_end - vma->vm_start);
2694         return videobuf_mmap_mapper(bttv_queue(fh),vma);
2695 }
2696
2697 static const struct v4l2_file_operations bttv_fops =
2698 {
2699         .owner            = THIS_MODULE,
2700         .open             = bttv_open,
2701         .release          = bttv_release,
2702         .unlocked_ioctl   = video_ioctl2,
2703         .read             = bttv_read,
2704         .mmap             = bttv_mmap,
2705         .poll             = bttv_poll,
2706 };
2707
2708 static const struct v4l2_ioctl_ops bttv_ioctl_ops = {
2709         .vidioc_querycap                = bttv_querycap,
2710         .vidioc_enum_fmt_vid_cap        = bttv_enum_fmt_vid_cap,
2711         .vidioc_g_fmt_vid_cap           = bttv_g_fmt_vid_cap,
2712         .vidioc_try_fmt_vid_cap         = bttv_try_fmt_vid_cap,
2713         .vidioc_s_fmt_vid_cap           = bttv_s_fmt_vid_cap,
2714         .vidioc_g_fmt_vbi_cap           = bttv_g_fmt_vbi_cap,
2715         .vidioc_try_fmt_vbi_cap         = bttv_try_fmt_vbi_cap,
2716         .vidioc_s_fmt_vbi_cap           = bttv_s_fmt_vbi_cap,
2717         .vidioc_g_pixelaspect           = bttv_g_pixelaspect,
2718         .vidioc_reqbufs                 = bttv_reqbufs,
2719         .vidioc_querybuf                = bttv_querybuf,
2720         .vidioc_qbuf                    = bttv_qbuf,
2721         .vidioc_dqbuf                   = bttv_dqbuf,
2722         .vidioc_s_std                   = bttv_s_std,
2723         .vidioc_g_std                   = bttv_g_std,
2724         .vidioc_enum_input              = bttv_enum_input,
2725         .vidioc_g_input                 = bttv_g_input,
2726         .vidioc_s_input                 = bttv_s_input,
2727         .vidioc_streamon                = bttv_streamon,
2728         .vidioc_streamoff               = bttv_streamoff,
2729         .vidioc_g_tuner                 = bttv_g_tuner,
2730         .vidioc_s_tuner                 = bttv_s_tuner,
2731         .vidioc_g_selection             = bttv_g_selection,
2732         .vidioc_s_selection             = bttv_s_selection,
2733         .vidioc_g_parm                  = bttv_g_parm,
2734         .vidioc_g_frequency             = bttv_g_frequency,
2735         .vidioc_s_frequency             = bttv_s_frequency,
2736         .vidioc_log_status              = bttv_log_status,
2737         .vidioc_querystd                = bttv_querystd,
2738         .vidioc_subscribe_event         = v4l2_ctrl_subscribe_event,
2739         .vidioc_unsubscribe_event       = v4l2_event_unsubscribe,
2740 #ifdef CONFIG_VIDEO_ADV_DEBUG
2741         .vidioc_g_register              = bttv_g_register,
2742         .vidioc_s_register              = bttv_s_register,
2743 #endif
2744 };
2745
2746 static struct video_device bttv_video_template = {
2747         .fops         = &bttv_fops,
2748         .ioctl_ops    = &bttv_ioctl_ops,
2749         .tvnorms      = BTTV_NORMS,
2750 };
2751
2752 /* ----------------------------------------------------------------------- */
2753 /* radio interface                                                         */
2754
2755 static int radio_open(struct file *file)
2756 {
2757         struct video_device *vdev = video_devdata(file);
2758         struct bttv *btv = video_drvdata(file);
2759         struct bttv_fh *fh;
2760
2761         dprintk("open dev=%s\n", video_device_node_name(vdev));
2762
2763         dprintk("%d: open called (radio)\n", btv->c.nr);
2764
2765         /* allocate per filehandle data */
2766         fh = kmalloc(sizeof(*fh), GFP_KERNEL);
2767         if (unlikely(!fh))
2768                 return -ENOMEM;
2769         file->private_data = fh;
2770         *fh = btv->init;
2771         v4l2_fh_init(&fh->fh, vdev);
2772
2773         btv->radio_user++;
2774         audio_mute(btv, btv->mute);
2775
2776         v4l2_fh_add(&fh->fh);
2777
2778         return 0;
2779 }
2780
2781 static int radio_release(struct file *file)
2782 {
2783         struct bttv_fh *fh = file->private_data;
2784         struct bttv *btv = fh->btv;
2785         struct saa6588_command cmd;
2786
2787         file->private_data = NULL;
2788         v4l2_fh_del(&fh->fh);
2789         v4l2_fh_exit(&fh->fh);
2790         kfree(fh);
2791
2792         btv->radio_user--;
2793
2794         bttv_call_all(btv, core, command, SAA6588_CMD_CLOSE, &cmd);
2795
2796         if (btv->radio_user == 0)
2797                 btv->has_radio_tuner = 0;
2798         return 0;
2799 }
2800
2801 static int radio_g_tuner(struct file *file, void *priv, struct v4l2_tuner *t)
2802 {
2803         struct bttv_fh *fh = priv;
2804         struct bttv *btv = fh->btv;
2805
2806         if (0 != t->index)
2807                 return -EINVAL;
2808         strscpy(t->name, "Radio", sizeof(t->name));
2809         t->type = V4L2_TUNER_RADIO;
2810         radio_enable(btv);
2811
2812         bttv_call_all(btv, tuner, g_tuner, t);
2813
2814         if (btv->audio_mode_gpio)
2815                 btv->audio_mode_gpio(btv, t, 0);
2816
2817         if (btv->has_tea575x)
2818                 return snd_tea575x_g_tuner(&btv->tea, t);
2819
2820         return 0;
2821 }
2822
2823 static int radio_s_tuner(struct file *file, void *priv,
2824                                         const struct v4l2_tuner *t)
2825 {
2826         struct bttv_fh *fh = priv;
2827         struct bttv *btv = fh->btv;
2828
2829         if (0 != t->index)
2830                 return -EINVAL;
2831
2832         radio_enable(btv);
2833         bttv_call_all(btv, tuner, s_tuner, t);
2834         return 0;
2835 }
2836
2837 static int radio_s_hw_freq_seek(struct file *file, void *priv,
2838                                         const struct v4l2_hw_freq_seek *a)
2839 {
2840         struct bttv_fh *fh = priv;
2841         struct bttv *btv = fh->btv;
2842
2843         if (btv->has_tea575x)
2844                 return snd_tea575x_s_hw_freq_seek(file, &btv->tea, a);
2845
2846         return -ENOTTY;
2847 }
2848
2849 static int radio_enum_freq_bands(struct file *file, void *priv,
2850                                          struct v4l2_frequency_band *band)
2851 {
2852         struct bttv_fh *fh = priv;
2853         struct bttv *btv = fh->btv;
2854
2855         if (btv->has_tea575x)
2856                 return snd_tea575x_enum_freq_bands(&btv->tea, band);
2857
2858         return -ENOTTY;
2859 }
2860
2861 static ssize_t radio_read(struct file *file, char __user *data,
2862                          size_t count, loff_t *ppos)
2863 {
2864         struct bttv_fh *fh = file->private_data;
2865         struct bttv *btv = fh->btv;
2866         struct saa6588_command cmd;
2867
2868         cmd.block_count = count / 3;
2869         cmd.nonblocking = file->f_flags & O_NONBLOCK;
2870         cmd.buffer = data;
2871         cmd.instance = file;
2872         cmd.result = -ENODEV;
2873         radio_enable(btv);
2874
2875         bttv_call_all(btv, core, command, SAA6588_CMD_READ, &cmd);
2876
2877         return cmd.result;
2878 }
2879
2880 static __poll_t radio_poll(struct file *file, poll_table *wait)
2881 {
2882         struct bttv_fh *fh = file->private_data;
2883         struct bttv *btv = fh->btv;
2884         __poll_t req_events = poll_requested_events(wait);
2885         struct saa6588_command cmd;
2886         __poll_t res = 0;
2887
2888         if (v4l2_event_pending(&fh->fh))
2889                 res = EPOLLPRI;
2890         else if (req_events & EPOLLPRI)
2891                 poll_wait(file, &fh->fh.wait, wait);
2892         radio_enable(btv);
2893         cmd.instance = file;
2894         cmd.event_list = wait;
2895         cmd.poll_mask = res;
2896         bttv_call_all(btv, core, command, SAA6588_CMD_POLL, &cmd);
2897
2898         return cmd.poll_mask;
2899 }
2900
2901 static const struct v4l2_file_operations radio_fops =
2902 {
2903         .owner    = THIS_MODULE,
2904         .open     = radio_open,
2905         .read     = radio_read,
2906         .release  = radio_release,
2907         .unlocked_ioctl = video_ioctl2,
2908         .poll     = radio_poll,
2909 };
2910
2911 static const struct v4l2_ioctl_ops radio_ioctl_ops = {
2912         .vidioc_querycap        = bttv_querycap,
2913         .vidioc_log_status      = bttv_log_status,
2914         .vidioc_g_tuner         = radio_g_tuner,
2915         .vidioc_s_tuner         = radio_s_tuner,
2916         .vidioc_g_frequency     = bttv_g_frequency,
2917         .vidioc_s_frequency     = bttv_s_frequency,
2918         .vidioc_s_hw_freq_seek  = radio_s_hw_freq_seek,
2919         .vidioc_enum_freq_bands = radio_enum_freq_bands,
2920         .vidioc_subscribe_event = v4l2_ctrl_subscribe_event,
2921         .vidioc_unsubscribe_event = v4l2_event_unsubscribe,
2922 };
2923
2924 static struct video_device radio_template = {
2925         .fops      = &radio_fops,
2926         .ioctl_ops = &radio_ioctl_ops,
2927 };
2928
2929 /* ----------------------------------------------------------------------- */
2930 /* some debug code                                                         */
2931
2932 static int bttv_risc_decode(u32 risc)
2933 {
2934         static char *instr[16] = {
2935                 [ BT848_RISC_WRITE     >> 28 ] = "write",
2936                 [ BT848_RISC_SKIP      >> 28 ] = "skip",
2937                 [ BT848_RISC_WRITEC    >> 28 ] = "writec",
2938                 [ BT848_RISC_JUMP      >> 28 ] = "jump",
2939                 [ BT848_RISC_SYNC      >> 28 ] = "sync",
2940                 [ BT848_RISC_WRITE123  >> 28 ] = "write123",
2941                 [ BT848_RISC_SKIP123   >> 28 ] = "skip123",
2942                 [ BT848_RISC_WRITE1S23 >> 28 ] = "write1s23",
2943         };
2944         static int incr[16] = {
2945                 [ BT848_RISC_WRITE     >> 28 ] = 2,
2946                 [ BT848_RISC_JUMP      >> 28 ] = 2,
2947                 [ BT848_RISC_SYNC      >> 28 ] = 2,
2948                 [ BT848_RISC_WRITE123  >> 28 ] = 5,
2949                 [ BT848_RISC_SKIP123   >> 28 ] = 2,
2950                 [ BT848_RISC_WRITE1S23 >> 28 ] = 3,
2951         };
2952         static char *bits[] = {
2953                 "be0",  "be1",  "be2",  "be3/resync",
2954                 "set0", "set1", "set2", "set3",
2955                 "clr0", "clr1", "clr2", "clr3",
2956                 "irq",  "res",  "eol",  "sol",
2957         };
2958         int i;
2959
2960         pr_cont("0x%08x [ %s", risc,
2961                instr[risc >> 28] ? instr[risc >> 28] : "INVALID");
2962         for (i = ARRAY_SIZE(bits)-1; i >= 0; i--)
2963                 if (risc & (1 << (i + 12)))
2964                         pr_cont(" %s", bits[i]);
2965         pr_cont(" count=%d ]\n", risc & 0xfff);
2966         return incr[risc >> 28] ? incr[risc >> 28] : 1;
2967 }
2968
2969 static void bttv_risc_disasm(struct bttv *btv,
2970                              struct btcx_riscmem *risc)
2971 {
2972         unsigned int i,j,n;
2973
2974         pr_info("%s: risc disasm: %p [dma=0x%08lx]\n",
2975                 btv->c.v4l2_dev.name, risc->cpu, (unsigned long)risc->dma);
2976         for (i = 0; i < (risc->size >> 2); i += n) {
2977                 pr_info("%s:   0x%lx: ",
2978                         btv->c.v4l2_dev.name,
2979                         (unsigned long)(risc->dma + (i<<2)));
2980                 n = bttv_risc_decode(le32_to_cpu(risc->cpu[i]));
2981                 for (j = 1; j < n; j++)
2982                         pr_info("%s:   0x%lx: 0x%08x [ arg #%d ]\n",
2983                                 btv->c.v4l2_dev.name,
2984                                 (unsigned long)(risc->dma + ((i+j)<<2)),
2985                                 risc->cpu[i+j], j);
2986                 if (0 == risc->cpu[i])
2987                         break;
2988         }
2989 }
2990
2991 static void bttv_print_riscaddr(struct bttv *btv)
2992 {
2993         pr_info("  main: %08llx\n", (unsigned long long)btv->main.dma);
2994         pr_info("  vbi : o=%08llx e=%08llx\n",
2995                 btv->cvbi ? (unsigned long long)btv->cvbi->top.dma : 0,
2996                 btv->cvbi ? (unsigned long long)btv->cvbi->bottom.dma : 0);
2997         pr_info("  cap : o=%08llx e=%08llx\n",
2998                 btv->curr.top
2999                 ? (unsigned long long)btv->curr.top->top.dma : 0,
3000                 btv->curr.bottom
3001                 ? (unsigned long long)btv->curr.bottom->bottom.dma : 0);
3002         bttv_risc_disasm(btv, &btv->main);
3003 }
3004
3005 /* ----------------------------------------------------------------------- */
3006 /* irq handler                                                             */
3007
3008 static char *irq_name[] = {
3009         "FMTCHG",  // format change detected (525 vs. 625)
3010         "VSYNC",   // vertical sync (new field)
3011         "HSYNC",   // horizontal sync
3012         "OFLOW",   // chroma/luma AGC overflow
3013         "HLOCK",   // horizontal lock changed
3014         "VPRES",   // video presence changed
3015         "6", "7",
3016         "I2CDONE", // hw irc operation finished
3017         "GPINT",   // gpio port triggered irq
3018         "10",
3019         "RISCI",   // risc instruction triggered irq
3020         "FBUS",    // pixel data fifo dropped data (high pci bus latencies)
3021         "FTRGT",   // pixel data fifo overrun
3022         "FDSR",    // fifo data stream resyncronisation
3023         "PPERR",   // parity error (data transfer)
3024         "RIPERR",  // parity error (read risc instructions)
3025         "PABORT",  // pci abort
3026         "OCERR",   // risc instruction error
3027         "SCERR",   // syncronisation error
3028 };
3029
3030 static void bttv_print_irqbits(u32 print, u32 mark)
3031 {
3032         unsigned int i;
3033
3034         pr_cont("bits:");
3035         for (i = 0; i < ARRAY_SIZE(irq_name); i++) {
3036                 if (print & (1 << i))
3037                         pr_cont(" %s", irq_name[i]);
3038                 if (mark & (1 << i))
3039                         pr_cont("*");
3040         }
3041 }
3042
3043 static void bttv_irq_debug_low_latency(struct bttv *btv, u32 rc)
3044 {
3045         pr_warn("%d: irq: skipped frame [main=%lx,o_vbi=%lx,o_field=%lx,rc=%lx]\n",
3046                 btv->c.nr,
3047                 (unsigned long)btv->main.dma,
3048                 (unsigned long)le32_to_cpu(btv->main.cpu[RISC_SLOT_O_VBI+1]),
3049                 (unsigned long)le32_to_cpu(btv->main.cpu[RISC_SLOT_O_FIELD+1]),
3050                 (unsigned long)rc);
3051
3052         if (0 == (btread(BT848_DSTATUS) & BT848_DSTATUS_HLOC)) {
3053                 pr_notice("%d: Oh, there (temporarily?) is no input signal. Ok, then this is harmless, don't worry ;)\n",
3054                           btv->c.nr);
3055                 return;
3056         }
3057         pr_notice("%d: Uhm. Looks like we have unusual high IRQ latencies\n",
3058                   btv->c.nr);
3059         pr_notice("%d: Lets try to catch the culprit red-handed ...\n",
3060                   btv->c.nr);
3061         dump_stack();
3062 }
3063
3064 static int
3065 bttv_irq_next_video(struct bttv *btv, struct bttv_buffer_set *set)
3066 {
3067         struct bttv_buffer *item;
3068
3069         memset(set,0,sizeof(*set));
3070
3071         /* capture request ? */
3072         if (!list_empty(&btv->capture)) {
3073                 set->frame_irq = 1;
3074                 item = list_entry(btv->capture.next, struct bttv_buffer, vb.queue);
3075                 if (V4L2_FIELD_HAS_TOP(item->vb.field))
3076                         set->top    = item;
3077                 if (V4L2_FIELD_HAS_BOTTOM(item->vb.field))
3078                         set->bottom = item;
3079
3080                 /* capture request for other field ? */
3081                 if (!V4L2_FIELD_HAS_BOTH(item->vb.field) &&
3082                     (item->vb.queue.next != &btv->capture)) {
3083                         item = list_entry(item->vb.queue.next, struct bttv_buffer, vb.queue);
3084                         /* Mike Isely <[email protected]> - Only check
3085                          * and set up the bottom field in the logic
3086                          * below.  Don't ever do the top field.  This
3087                          * of course means that if we set up the
3088                          * bottom field in the above code that we'll
3089                          * actually skip a field.  But that's OK.
3090                          * Having processed only a single buffer this
3091                          * time, then the next time around the first
3092                          * available buffer should be for a top field.
3093                          * That will then cause us here to set up a
3094                          * top then a bottom field in the normal way.
3095                          * The alternative to this understanding is
3096                          * that we set up the second available buffer
3097                          * as a top field, but that's out of order
3098                          * since this driver always processes the top
3099                          * field first - the effect will be the two
3100                          * buffers being returned in the wrong order,
3101                          * with the second buffer also being delayed
3102                          * by one field time (owing to the fifo nature
3103                          * of videobuf).  Worse still, we'll be stuck
3104                          * doing fields out of order now every time
3105                          * until something else causes a field to be
3106                          * dropped.  By effectively forcing a field to
3107                          * drop this way then we always get back into
3108                          * sync within a single frame time.  (Out of
3109                          * order fields can screw up deinterlacing
3110                          * algorithms.) */
3111                         if (!V4L2_FIELD_HAS_BOTH(item->vb.field)) {
3112                                 if (NULL == set->bottom &&
3113                                     V4L2_FIELD_BOTTOM == item->vb.field) {
3114                                         set->bottom = item;
3115                                 }
3116                                 if (NULL != set->top  &&  NULL != set->bottom)
3117                                         set->top_irq = 2;
3118                         }
3119                 }
3120         }
3121
3122         dprintk("%d: next set: top=%p bottom=%p [irq=%d,%d]\n",
3123                 btv->c.nr, set->top, set->bottom,
3124                 set->frame_irq, set->top_irq);
3125         return 0;
3126 }
3127
3128 static void
3129 bttv_irq_wakeup_video(struct bttv *btv, struct bttv_buffer_set *wakeup,
3130                       struct bttv_buffer_set *curr, unsigned int state)
3131 {
3132         u64 ts = ktime_get_ns();
3133
3134         if (wakeup->top == wakeup->bottom) {
3135                 if (NULL != wakeup->top && curr->top != wakeup->top) {
3136                         if (irq_debug > 1)
3137                                 pr_debug("%d: wakeup: both=%p\n",
3138                                          btv->c.nr, wakeup->top);
3139                         wakeup->top->vb.ts = ts;
3140                         wakeup->top->vb.field_count = btv->field_count;
3141                         wakeup->top->vb.state = state;
3142                         wake_up(&wakeup->top->vb.done);
3143                 }
3144         } else {
3145                 if (NULL != wakeup->top && curr->top != wakeup->top) {
3146                         if (irq_debug > 1)
3147                                 pr_debug("%d: wakeup: top=%p\n",
3148                                          btv->c.nr, wakeup->top);
3149                         wakeup->top->vb.ts = ts;
3150                         wakeup->top->vb.field_count = btv->field_count;
3151                         wakeup->top->vb.state = state;
3152                         wake_up(&wakeup->top->vb.done);
3153                 }
3154                 if (NULL != wakeup->bottom && curr->bottom != wakeup->bottom) {
3155                         if (irq_debug > 1)
3156                                 pr_debug("%d: wakeup: bottom=%p\n",
3157                                          btv->c.nr, wakeup->bottom);
3158                         wakeup->bottom->vb.ts = ts;
3159                         wakeup->bottom->vb.field_count = btv->field_count;
3160                         wakeup->bottom->vb.state = state;
3161                         wake_up(&wakeup->bottom->vb.done);
3162                 }
3163         }
3164 }
3165
3166 static void
3167 bttv_irq_wakeup_vbi(struct bttv *btv, struct bttv_buffer *wakeup,
3168                     unsigned int state)
3169 {
3170         if (NULL == wakeup)
3171                 return;
3172
3173         wakeup->vb.ts = ktime_get_ns();
3174         wakeup->vb.field_count = btv->field_count;
3175         wakeup->vb.state = state;
3176         wake_up(&wakeup->vb.done);
3177 }
3178
3179 static void bttv_irq_timeout(struct timer_list *t)
3180 {
3181         struct bttv *btv = from_timer(btv, t, timeout);
3182         struct bttv_buffer_set old,new;
3183         struct bttv_buffer *ovbi;
3184         struct bttv_buffer *item;
3185         unsigned long flags;
3186
3187         if (bttv_verbose) {
3188                 pr_info("%d: timeout: drop=%d irq=%d/%d, risc=%08x, ",
3189                         btv->c.nr, btv->framedrop, btv->irq_me, btv->irq_total,
3190                         btread(BT848_RISC_COUNT));
3191                 bttv_print_irqbits(btread(BT848_INT_STAT),0);
3192                 pr_cont("\n");
3193         }
3194
3195         spin_lock_irqsave(&btv->s_lock,flags);
3196
3197         /* deactivate stuff */
3198         memset(&new,0,sizeof(new));
3199         old  = btv->curr;
3200         ovbi = btv->cvbi;
3201         btv->curr = new;
3202         btv->cvbi = NULL;
3203         btv->loop_irq = 0;
3204         bttv_buffer_activate_video(btv, &new);
3205         bttv_buffer_activate_vbi(btv,   NULL);
3206         bttv_set_dma(btv, 0);
3207
3208         /* wake up */
3209         bttv_irq_wakeup_video(btv, &old, &new, VIDEOBUF_ERROR);
3210         bttv_irq_wakeup_vbi(btv, ovbi, VIDEOBUF_ERROR);
3211
3212         /* cancel all outstanding capture / vbi requests */
3213         while (!list_empty(&btv->capture)) {
3214                 item = list_entry(btv->capture.next, struct bttv_buffer, vb.queue);
3215                 list_del(&item->vb.queue);
3216                 item->vb.state = VIDEOBUF_ERROR;
3217                 wake_up(&item->vb.done);
3218         }
3219         while (!list_empty(&btv->vcapture)) {
3220                 item = list_entry(btv->vcapture.next, struct bttv_buffer, vb.queue);
3221                 list_del(&item->vb.queue);
3222                 item->vb.state = VIDEOBUF_ERROR;
3223                 wake_up(&item->vb.done);
3224         }
3225
3226         btv->errors++;
3227         spin_unlock_irqrestore(&btv->s_lock,flags);
3228 }
3229
3230 static void
3231 bttv_irq_wakeup_top(struct bttv *btv)
3232 {
3233         struct bttv_buffer *wakeup = btv->curr.top;
3234
3235         if (NULL == wakeup)
3236                 return;
3237
3238         spin_lock(&btv->s_lock);
3239         btv->curr.top_irq = 0;
3240         btv->curr.top = NULL;
3241         bttv_risc_hook(btv, RISC_SLOT_O_FIELD, NULL, 0);
3242
3243         wakeup->vb.ts = ktime_get_ns();
3244         wakeup->vb.field_count = btv->field_count;
3245         wakeup->vb.state = VIDEOBUF_DONE;
3246         wake_up(&wakeup->vb.done);
3247         spin_unlock(&btv->s_lock);
3248 }
3249
3250 static inline int is_active(struct btcx_riscmem *risc, u32 rc)
3251 {
3252         if (rc < risc->dma)
3253                 return 0;
3254         if (rc > risc->dma + risc->size)
3255                 return 0;
3256         return 1;
3257 }
3258
3259 static void
3260 bttv_irq_switch_video(struct bttv *btv)
3261 {
3262         struct bttv_buffer_set new;
3263         struct bttv_buffer_set old;
3264         dma_addr_t rc;
3265
3266         spin_lock(&btv->s_lock);
3267
3268         /* new buffer set */
3269         bttv_irq_next_video(btv, &new);
3270         rc = btread(BT848_RISC_COUNT);
3271         if ((btv->curr.top    && is_active(&btv->curr.top->top,       rc)) ||
3272             (btv->curr.bottom && is_active(&btv->curr.bottom->bottom, rc))) {
3273                 btv->framedrop++;
3274                 if (debug_latency)
3275                         bttv_irq_debug_low_latency(btv, rc);
3276                 spin_unlock(&btv->s_lock);
3277                 return;
3278         }
3279
3280         /* switch over */
3281         old = btv->curr;
3282         btv->curr = new;
3283         btv->loop_irq &= ~1;
3284         bttv_buffer_activate_video(btv, &new);
3285         bttv_set_dma(btv, 0);
3286
3287         /* switch input */
3288         if (UNSET != btv->new_input) {
3289                 video_mux(btv,btv->new_input);
3290                 btv->new_input = UNSET;
3291         }
3292
3293         /* wake up finished buffers */
3294         bttv_irq_wakeup_video(btv, &old, &new, VIDEOBUF_DONE);
3295         spin_unlock(&btv->s_lock);
3296 }
3297
3298 static void
3299 bttv_irq_switch_vbi(struct bttv *btv)
3300 {
3301         struct bttv_buffer *new = NULL;
3302         struct bttv_buffer *old;
3303         u32 rc;
3304
3305         spin_lock(&btv->s_lock);
3306
3307         if (!list_empty(&btv->vcapture))
3308                 new = list_entry(btv->vcapture.next, struct bttv_buffer, vb.queue);
3309         old = btv->cvbi;
3310
3311         rc = btread(BT848_RISC_COUNT);
3312         if (NULL != old && (is_active(&old->top,    rc) ||
3313                             is_active(&old->bottom, rc))) {
3314                 btv->framedrop++;
3315                 if (debug_latency)
3316                         bttv_irq_debug_low_latency(btv, rc);
3317                 spin_unlock(&btv->s_lock);
3318                 return;
3319         }
3320
3321         /* switch */
3322         btv->cvbi = new;
3323         btv->loop_irq &= ~4;
3324         bttv_buffer_activate_vbi(btv, new);
3325         bttv_set_dma(btv, 0);
3326
3327         bttv_irq_wakeup_vbi(btv, old, VIDEOBUF_DONE);
3328         spin_unlock(&btv->s_lock);
3329 }
3330
3331 static irqreturn_t bttv_irq(int irq, void *dev_id)
3332 {
3333         u32 stat,astat;
3334         u32 dstat;
3335         int count;
3336         struct bttv *btv;
3337         int handled = 0;
3338
3339         btv=(struct bttv *)dev_id;
3340
3341         count=0;
3342         while (1) {
3343                 /* get/clear interrupt status bits */
3344                 stat=btread(BT848_INT_STAT);
3345                 astat=stat&btread(BT848_INT_MASK);
3346                 if (!astat)
3347                         break;
3348                 handled = 1;
3349                 btwrite(stat,BT848_INT_STAT);
3350
3351                 /* get device status bits */
3352                 dstat=btread(BT848_DSTATUS);
3353
3354                 if (irq_debug) {
3355                         pr_debug("%d: irq loop=%d fc=%d riscs=%x, riscc=%08x, ",
3356                                  btv->c.nr, count, btv->field_count,
3357                                  stat>>28, btread(BT848_RISC_COUNT));
3358                         bttv_print_irqbits(stat,astat);
3359                         if (stat & BT848_INT_HLOCK)
3360                                 pr_cont("   HLOC => %s",
3361                                         dstat & BT848_DSTATUS_HLOC
3362                                         ? "yes" : "no");
3363                         if (stat & BT848_INT_VPRES)
3364                                 pr_cont("   PRES => %s",
3365                                         dstat & BT848_DSTATUS_PRES
3366                                         ? "yes" : "no");
3367                         if (stat & BT848_INT_FMTCHG)
3368                                 pr_cont("   NUML => %s",
3369                                         dstat & BT848_DSTATUS_NUML
3370                                         ? "625" : "525");
3371                         pr_cont("\n");
3372                 }
3373
3374                 if (astat&BT848_INT_VSYNC)
3375                         btv->field_count++;
3376
3377                 if ((astat & BT848_INT_GPINT) && btv->remote) {
3378                         bttv_input_irq(btv);
3379                 }
3380
3381                 if (astat & BT848_INT_I2CDONE) {
3382                         btv->i2c_done = stat;
3383                         wake_up(&btv->i2c_queue);
3384                 }
3385
3386                 if ((astat & BT848_INT_RISCI)  &&  (stat & (4<<28)))
3387                         bttv_irq_switch_vbi(btv);
3388
3389                 if ((astat & BT848_INT_RISCI)  &&  (stat & (2<<28)))
3390                         bttv_irq_wakeup_top(btv);
3391
3392                 if ((astat & BT848_INT_RISCI)  &&  (stat & (1<<28)))
3393                         bttv_irq_switch_video(btv);
3394
3395                 if ((astat & BT848_INT_HLOCK)  &&  btv->opt_automute)
3396                         /* trigger automute */
3397                         audio_mux_gpio(btv, btv->audio_input, btv->mute);
3398
3399                 if (astat & (BT848_INT_SCERR|BT848_INT_OCERR)) {
3400                         pr_info("%d: %s%s @ %08x,",
3401                                 btv->c.nr,
3402                                 (astat & BT848_INT_SCERR) ? "SCERR" : "",
3403                                 (astat & BT848_INT_OCERR) ? "OCERR" : "",
3404                                 btread(BT848_RISC_COUNT));
3405                         bttv_print_irqbits(stat,astat);
3406                         pr_cont("\n");
3407                         if (bttv_debug)
3408                                 bttv_print_riscaddr(btv);
3409                 }
3410                 if (fdsr && astat & BT848_INT_FDSR) {
3411                         pr_info("%d: FDSR @ %08x\n",
3412                                 btv->c.nr, btread(BT848_RISC_COUNT));
3413                         if (bttv_debug)
3414                                 bttv_print_riscaddr(btv);
3415                 }
3416
3417                 count++;
3418                 if (count > 4) {
3419
3420                         if (count > 8 || !(astat & BT848_INT_GPINT)) {
3421                                 btwrite(0, BT848_INT_MASK);
3422
3423                                 pr_err("%d: IRQ lockup, cleared int mask [",
3424                                        btv->c.nr);
3425                         } else {
3426                                 pr_err("%d: IRQ lockup, clearing GPINT from int mask [",
3427                                        btv->c.nr);
3428
3429                                 btwrite(btread(BT848_INT_MASK) & (-1 ^ BT848_INT_GPINT),
3430                                                 BT848_INT_MASK);
3431                         }
3432
3433                         bttv_print_irqbits(stat,astat);
3434
3435                         pr_cont("]\n");
3436                 }
3437         }
3438         btv->irq_total++;
3439         if (handled)
3440                 btv->irq_me++;
3441         return IRQ_RETVAL(handled);
3442 }
3443
3444
3445 /* ----------------------------------------------------------------------- */
3446 /* initialization                                                          */
3447
3448 static void vdev_init(struct bttv *btv,
3449                       struct video_device *vfd,
3450                       const struct video_device *template,
3451                       const char *type_name)
3452 {
3453         *vfd = *template;
3454         vfd->v4l2_dev = &btv->c.v4l2_dev;
3455         vfd->release = video_device_release_empty;
3456         video_set_drvdata(vfd, btv);
3457         snprintf(vfd->name, sizeof(vfd->name), "BT%d%s %s (%s)",
3458                  btv->id, (btv->id==848 && btv->revision==0x12) ? "A" : "",
3459                  type_name, bttv_tvcards[btv->c.type].name);
3460         if (btv->tuner_type == TUNER_ABSENT) {
3461                 v4l2_disable_ioctl(vfd, VIDIOC_G_FREQUENCY);
3462                 v4l2_disable_ioctl(vfd, VIDIOC_S_FREQUENCY);
3463                 v4l2_disable_ioctl(vfd, VIDIOC_G_TUNER);
3464                 v4l2_disable_ioctl(vfd, VIDIOC_S_TUNER);
3465         }
3466 }
3467
3468 static void bttv_unregister_video(struct bttv *btv)
3469 {
3470         video_unregister_device(&btv->video_dev);
3471         video_unregister_device(&btv->vbi_dev);
3472         video_unregister_device(&btv->radio_dev);
3473 }
3474
3475 /* register video4linux devices */
3476 static int bttv_register_video(struct bttv *btv)
3477 {
3478         /* video */
3479         vdev_init(btv, &btv->video_dev, &bttv_video_template, "video");
3480         btv->video_dev.device_caps = V4L2_CAP_VIDEO_CAPTURE |
3481                                      V4L2_CAP_READWRITE | V4L2_CAP_STREAMING;
3482         if (btv->tuner_type != TUNER_ABSENT)
3483                 btv->video_dev.device_caps |= V4L2_CAP_TUNER;
3484
3485         if (video_register_device(&btv->video_dev, VFL_TYPE_VIDEO,
3486                                   video_nr[btv->c.nr]) < 0)
3487                 goto err;
3488         pr_info("%d: registered device %s\n",
3489                 btv->c.nr, video_device_node_name(&btv->video_dev));
3490         if (device_create_file(&btv->video_dev.dev,
3491                                      &dev_attr_card)<0) {
3492                 pr_err("%d: device_create_file 'card' failed\n", btv->c.nr);
3493                 goto err;
3494         }
3495
3496         /* vbi */
3497         vdev_init(btv, &btv->vbi_dev, &bttv_video_template, "vbi");
3498         btv->vbi_dev.device_caps = V4L2_CAP_VBI_CAPTURE | V4L2_CAP_READWRITE |
3499                                    V4L2_CAP_STREAMING;
3500         if (btv->tuner_type != TUNER_ABSENT)
3501                 btv->vbi_dev.device_caps |= V4L2_CAP_TUNER;
3502
3503         if (video_register_device(&btv->vbi_dev, VFL_TYPE_VBI,
3504                                   vbi_nr[btv->c.nr]) < 0)
3505                 goto err;
3506         pr_info("%d: registered device %s\n",
3507                 btv->c.nr, video_device_node_name(&btv->vbi_dev));
3508
3509         if (!btv->has_radio)
3510                 return 0;
3511         /* radio */
3512         vdev_init(btv, &btv->radio_dev, &radio_template, "radio");
3513         btv->radio_dev.device_caps = V4L2_CAP_RADIO | V4L2_CAP_TUNER;
3514         if (btv->has_saa6588)
3515                 btv->radio_dev.device_caps |= V4L2_CAP_READWRITE |
3516                                               V4L2_CAP_RDS_CAPTURE;
3517         if (btv->has_tea575x)
3518                 btv->radio_dev.device_caps |= V4L2_CAP_HW_FREQ_SEEK;
3519         btv->radio_dev.ctrl_handler = &btv->radio_ctrl_handler;
3520         if (video_register_device(&btv->radio_dev, VFL_TYPE_RADIO,
3521                                   radio_nr[btv->c.nr]) < 0)
3522                 goto err;
3523         pr_info("%d: registered device %s\n",
3524                 btv->c.nr, video_device_node_name(&btv->radio_dev));
3525
3526         /* all done */
3527         return 0;
3528
3529  err:
3530         bttv_unregister_video(btv);
3531         return -1;
3532 }
3533
3534
3535 /* on OpenFirmware machines (PowerMac at least), PCI memory cycle */
3536 /* response on cards with no firmware is not enabled by OF */
3537 static void pci_set_command(struct pci_dev *dev)
3538 {
3539 #if defined(__powerpc__)
3540         unsigned int cmd;
3541
3542         pci_read_config_dword(dev, PCI_COMMAND, &cmd);
3543         cmd = (cmd | PCI_COMMAND_MEMORY );
3544         pci_write_config_dword(dev, PCI_COMMAND, cmd);
3545 #endif
3546 }
3547
3548 static int bttv_probe(struct pci_dev *dev, const struct pci_device_id *pci_id)
3549 {
3550         struct v4l2_frequency init_freq = {
3551                 .tuner = 0,
3552                 .type = V4L2_TUNER_ANALOG_TV,
3553                 .frequency = 980,
3554         };
3555         int result;
3556         unsigned char lat;
3557         struct bttv *btv;
3558         struct v4l2_ctrl_handler *hdl;
3559
3560         if (bttv_num == BTTV_MAX)
3561                 return -ENOMEM;
3562         pr_info("Bt8xx card found (%d)\n", bttv_num);
3563         bttvs[bttv_num] = btv = kzalloc(sizeof(*btv), GFP_KERNEL);
3564         if (btv == NULL) {
3565                 pr_err("out of memory\n");
3566                 return -ENOMEM;
3567         }
3568         btv->c.nr  = bttv_num;
3569         snprintf(btv->c.v4l2_dev.name, sizeof(btv->c.v4l2_dev.name),
3570                         "bttv%d", btv->c.nr);
3571
3572         /* initialize structs / fill in defaults */
3573         mutex_init(&btv->lock);
3574         spin_lock_init(&btv->s_lock);
3575         spin_lock_init(&btv->gpio_lock);
3576         init_waitqueue_head(&btv->i2c_queue);
3577         INIT_LIST_HEAD(&btv->c.subs);
3578         INIT_LIST_HEAD(&btv->capture);
3579         INIT_LIST_HEAD(&btv->vcapture);
3580
3581         timer_setup(&btv->timeout, bttv_irq_timeout, 0);
3582
3583         btv->i2c_rc = -1;
3584         btv->tuner_type  = UNSET;
3585         btv->new_input   = UNSET;
3586         btv->has_radio=radio[btv->c.nr];
3587
3588         /* pci stuff (init, get irq/mmio, ... */
3589         btv->c.pci = dev;
3590         btv->id  = dev->device;
3591         if (pci_enable_device(dev)) {
3592                 pr_warn("%d: Can't enable device\n", btv->c.nr);
3593                 result = -EIO;
3594                 goto free_mem;
3595         }
3596         if (dma_set_mask(&dev->dev, DMA_BIT_MASK(32))) {
3597                 pr_warn("%d: No suitable DMA available\n", btv->c.nr);
3598                 result = -EIO;
3599                 goto free_mem;
3600         }
3601         if (!request_mem_region(pci_resource_start(dev,0),
3602                                 pci_resource_len(dev,0),
3603                                 btv->c.v4l2_dev.name)) {
3604                 pr_warn("%d: can't request iomem (0x%llx)\n",
3605                         btv->c.nr,
3606                         (unsigned long long)pci_resource_start(dev, 0));
3607                 result = -EBUSY;
3608                 goto free_mem;
3609         }
3610         pci_set_master(dev);
3611         pci_set_command(dev);
3612
3613         result = v4l2_device_register(&dev->dev, &btv->c.v4l2_dev);
3614         if (result < 0) {
3615                 pr_warn("%d: v4l2_device_register() failed\n", btv->c.nr);
3616                 goto fail0;
3617         }
3618         hdl = &btv->ctrl_handler;
3619         v4l2_ctrl_handler_init(hdl, 20);
3620         btv->c.v4l2_dev.ctrl_handler = hdl;
3621         v4l2_ctrl_handler_init(&btv->radio_ctrl_handler, 6);
3622
3623         btv->revision = dev->revision;
3624         pci_read_config_byte(dev, PCI_LATENCY_TIMER, &lat);
3625         pr_info("%d: Bt%d (rev %d) at %s, irq: %d, latency: %d, mmio: 0x%llx\n",
3626                 bttv_num, btv->id, btv->revision, pci_name(dev),
3627                 btv->c.pci->irq, lat,
3628                 (unsigned long long)pci_resource_start(dev, 0));
3629         schedule();
3630
3631         btv->bt848_mmio = ioremap(pci_resource_start(dev, 0), 0x1000);
3632         if (NULL == btv->bt848_mmio) {
3633                 pr_err("%d: ioremap() failed\n", btv->c.nr);
3634                 result = -EIO;
3635                 goto fail1;
3636         }
3637
3638         /* identify card */
3639         bttv_idcard(btv);
3640
3641         /* disable irqs, register irq handler */
3642         btwrite(0, BT848_INT_MASK);
3643         result = request_irq(btv->c.pci->irq, bttv_irq,
3644             IRQF_SHARED, btv->c.v4l2_dev.name, (void *)btv);
3645         if (result < 0) {
3646                 pr_err("%d: can't get IRQ %d\n",
3647                        bttv_num, btv->c.pci->irq);
3648                 goto fail1;
3649         }
3650
3651         if (0 != bttv_handle_chipset(btv)) {
3652                 result = -EIO;
3653                 goto fail2;
3654         }
3655
3656         /* init options from insmod args */
3657         btv->opt_combfilter = combfilter;
3658         bttv_ctrl_combfilter.def = combfilter;
3659         bttv_ctrl_lumafilter.def = lumafilter;
3660         btv->opt_automute   = automute;
3661         bttv_ctrl_automute.def = automute;
3662         bttv_ctrl_agc_crush.def = agc_crush;
3663         btv->opt_vcr_hack   = vcr_hack;
3664         bttv_ctrl_vcr_hack.def = vcr_hack;
3665         bttv_ctrl_whitecrush_upper.def = whitecrush_upper;
3666         bttv_ctrl_whitecrush_lower.def = whitecrush_lower;
3667         btv->opt_uv_ratio   = uv_ratio;
3668         bttv_ctrl_uv_ratio.def = uv_ratio;
3669         bttv_ctrl_full_luma.def = full_luma_range;
3670         bttv_ctrl_coring.def = coring;
3671
3672         /* fill struct bttv with some useful defaults */
3673         btv->init.btv         = btv;
3674         btv->init.fmt         = format_by_fourcc(V4L2_PIX_FMT_BGR24);
3675         btv->init.width       = 320;
3676         btv->init.height      = 240;
3677         btv->input = 0;
3678
3679         v4l2_ctrl_new_std(hdl, &bttv_ctrl_ops,
3680                         V4L2_CID_BRIGHTNESS, 0, 0xff00, 0x100, 32768);
3681         v4l2_ctrl_new_std(hdl, &bttv_ctrl_ops,
3682                         V4L2_CID_CONTRAST, 0, 0xff80, 0x80, 0x6c00);
3683         v4l2_ctrl_new_std(hdl, &bttv_ctrl_ops,
3684                         V4L2_CID_SATURATION, 0, 0xff80, 0x80, 32768);
3685         v4l2_ctrl_new_std(hdl, &bttv_ctrl_ops,
3686                         V4L2_CID_COLOR_KILLER, 0, 1, 1, 0);
3687         v4l2_ctrl_new_std(hdl, &bttv_ctrl_ops,
3688                         V4L2_CID_HUE, 0, 0xff00, 0x100, 32768);
3689         v4l2_ctrl_new_std(hdl, &bttv_ctrl_ops,
3690                         V4L2_CID_CHROMA_AGC, 0, 1, 1, !!chroma_agc);
3691         v4l2_ctrl_new_std(hdl, &bttv_ctrl_ops,
3692                 V4L2_CID_AUDIO_MUTE, 0, 1, 1, 0);
3693         if (btv->volume_gpio)
3694                 v4l2_ctrl_new_std(hdl, &bttv_ctrl_ops,
3695                         V4L2_CID_AUDIO_VOLUME, 0, 0xff00, 0x100, 0xff00);
3696         v4l2_ctrl_new_custom(hdl, &bttv_ctrl_combfilter, NULL);
3697         v4l2_ctrl_new_custom(hdl, &bttv_ctrl_automute, NULL);
3698         v4l2_ctrl_new_custom(hdl, &bttv_ctrl_lumafilter, NULL);
3699         v4l2_ctrl_new_custom(hdl, &bttv_ctrl_agc_crush, NULL);
3700         v4l2_ctrl_new_custom(hdl, &bttv_ctrl_vcr_hack, NULL);
3701         v4l2_ctrl_new_custom(hdl, &bttv_ctrl_whitecrush_lower, NULL);
3702         v4l2_ctrl_new_custom(hdl, &bttv_ctrl_whitecrush_upper, NULL);
3703         v4l2_ctrl_new_custom(hdl, &bttv_ctrl_uv_ratio, NULL);
3704         v4l2_ctrl_new_custom(hdl, &bttv_ctrl_full_luma, NULL);
3705         v4l2_ctrl_new_custom(hdl, &bttv_ctrl_coring, NULL);
3706
3707         /* initialize hardware */
3708         if (bttv_gpio)
3709                 bttv_gpio_tracking(btv,"pre-init");
3710
3711         bttv_risc_init_main(btv);
3712         init_bt848(btv);
3713
3714         /* gpio */
3715         btwrite(0x00, BT848_GPIO_REG_INP);
3716         btwrite(0x00, BT848_GPIO_OUT_EN);
3717         if (bttv_verbose)
3718                 bttv_gpio_tracking(btv,"init");
3719
3720         /* needs to be done before i2c is registered */
3721         bttv_init_card1(btv);
3722
3723         /* register i2c + gpio */
3724         init_bttv_i2c(btv);
3725
3726         /* some card-specific stuff (needs working i2c) */
3727         bttv_init_card2(btv);
3728         bttv_init_tuner(btv);
3729         if (btv->tuner_type != TUNER_ABSENT) {
3730                 bttv_set_frequency(btv, &init_freq);
3731                 btv->radio_freq = 90500 * 16; /* 90.5Mhz default */
3732         }
3733         btv->std = V4L2_STD_PAL;
3734         init_irqreg(btv);
3735         if (!bttv_tvcards[btv->c.type].no_video)
3736                 v4l2_ctrl_handler_setup(hdl);
3737         if (hdl->error) {
3738                 result = hdl->error;
3739                 goto fail2;
3740         }
3741         /* mute device */
3742         audio_mute(btv, 1);
3743
3744         /* register video4linux + input */
3745         if (!bttv_tvcards[btv->c.type].no_video) {
3746                 v4l2_ctrl_add_handler(&btv->radio_ctrl_handler, hdl,
3747                                 v4l2_ctrl_radio_filter, false);
3748                 if (btv->radio_ctrl_handler.error) {
3749                         result = btv->radio_ctrl_handler.error;
3750                         goto fail2;
3751                 }
3752                 set_input(btv, 0, btv->tvnorm);
3753                 bttv_crop_reset(&btv->crop[0], btv->tvnorm);
3754                 btv->crop[1] = btv->crop[0]; /* current = default */
3755                 disclaim_vbi_lines(btv);
3756                 disclaim_video_lines(btv);
3757                 bttv_register_video(btv);
3758         }
3759
3760         /* add subdevices and autoload dvb-bt8xx if needed */
3761         if (bttv_tvcards[btv->c.type].has_dvb) {
3762                 bttv_sub_add_device(&btv->c, "dvb");
3763                 request_modules(btv);
3764         }
3765
3766         if (!disable_ir) {
3767                 init_bttv_i2c_ir(btv);
3768                 bttv_input_init(btv);
3769         }
3770
3771         /* everything is fine */
3772         bttv_num++;
3773         return 0;
3774
3775 fail2:
3776         free_irq(btv->c.pci->irq,btv);
3777
3778 fail1:
3779         v4l2_ctrl_handler_free(&btv->ctrl_handler);
3780         v4l2_ctrl_handler_free(&btv->radio_ctrl_handler);
3781         v4l2_device_unregister(&btv->c.v4l2_dev);
3782
3783 fail0:
3784         if (btv->bt848_mmio)
3785                 iounmap(btv->bt848_mmio);
3786         release_mem_region(pci_resource_start(btv->c.pci,0),
3787                            pci_resource_len(btv->c.pci,0));
3788         pci_disable_device(btv->c.pci);
3789
3790 free_mem:
3791         bttvs[btv->c.nr] = NULL;
3792         kfree(btv);
3793         return result;
3794 }
3795
3796 static void bttv_remove(struct pci_dev *pci_dev)
3797 {
3798         struct v4l2_device *v4l2_dev = pci_get_drvdata(pci_dev);
3799         struct bttv *btv = to_bttv(v4l2_dev);
3800
3801         if (bttv_verbose)
3802                 pr_info("%d: unloading\n", btv->c.nr);
3803
3804         if (bttv_tvcards[btv->c.type].has_dvb)
3805                 flush_request_modules(btv);
3806
3807         /* shutdown everything (DMA+IRQs) */
3808         btand(~15, BT848_GPIO_DMA_CTL);
3809         btwrite(0, BT848_INT_MASK);
3810         btwrite(~0x0, BT848_INT_STAT);
3811         btwrite(0x0, BT848_GPIO_OUT_EN);
3812         if (bttv_gpio)
3813                 bttv_gpio_tracking(btv,"cleanup");
3814
3815         /* tell gpio modules we are leaving ... */
3816         btv->shutdown=1;
3817         bttv_input_fini(btv);
3818         bttv_sub_del_devices(&btv->c);
3819
3820         /* unregister i2c_bus + input */
3821         fini_bttv_i2c(btv);
3822
3823         /* unregister video4linux */
3824         bttv_unregister_video(btv);
3825
3826         /* free allocated memory */
3827         v4l2_ctrl_handler_free(&btv->ctrl_handler);
3828         v4l2_ctrl_handler_free(&btv->radio_ctrl_handler);
3829         btcx_riscmem_free(btv->c.pci,&btv->main);
3830
3831         /* free resources */
3832         free_irq(btv->c.pci->irq,btv);
3833         iounmap(btv->bt848_mmio);
3834         release_mem_region(pci_resource_start(btv->c.pci,0),
3835                            pci_resource_len(btv->c.pci,0));
3836         pci_disable_device(btv->c.pci);
3837
3838         v4l2_device_unregister(&btv->c.v4l2_dev);
3839         bttvs[btv->c.nr] = NULL;
3840         kfree(btv);
3841
3842         return;
3843 }
3844
3845 static int __maybe_unused bttv_suspend(struct device *dev)
3846 {
3847         struct v4l2_device *v4l2_dev = dev_get_drvdata(dev);
3848         struct bttv *btv = to_bttv(v4l2_dev);
3849         struct bttv_buffer_set idle;
3850         unsigned long flags;
3851
3852         dprintk("%d: suspend\n", btv->c.nr);
3853
3854         /* stop dma + irqs */
3855         spin_lock_irqsave(&btv->s_lock,flags);
3856         memset(&idle, 0, sizeof(idle));
3857         btv->state.video = btv->curr;
3858         btv->state.vbi   = btv->cvbi;
3859         btv->state.loop_irq = btv->loop_irq;
3860         btv->curr = idle;
3861         btv->loop_irq = 0;
3862         bttv_buffer_activate_video(btv, &idle);
3863         bttv_buffer_activate_vbi(btv, NULL);
3864         bttv_set_dma(btv, 0);
3865         btwrite(0, BT848_INT_MASK);
3866         spin_unlock_irqrestore(&btv->s_lock,flags);
3867
3868         /* save bt878 state */
3869         btv->state.gpio_enable = btread(BT848_GPIO_OUT_EN);
3870         btv->state.gpio_data   = gpio_read();
3871
3872         btv->state.disabled = 1;
3873         return 0;
3874 }
3875
3876 static int __maybe_unused bttv_resume(struct device *dev)
3877 {
3878         struct v4l2_device *v4l2_dev = dev_get_drvdata(dev);
3879         struct bttv *btv = to_bttv(v4l2_dev);
3880         unsigned long flags;
3881
3882         dprintk("%d: resume\n", btv->c.nr);
3883
3884         btv->state.disabled = 0;
3885
3886         /* restore bt878 state */
3887         bttv_reinit_bt848(btv);
3888         gpio_inout(0xffffff, btv->state.gpio_enable);
3889         gpio_write(btv->state.gpio_data);
3890
3891         /* restart dma */
3892         spin_lock_irqsave(&btv->s_lock,flags);
3893         btv->curr = btv->state.video;
3894         btv->cvbi = btv->state.vbi;
3895         btv->loop_irq = btv->state.loop_irq;
3896         bttv_buffer_activate_video(btv, &btv->curr);
3897         bttv_buffer_activate_vbi(btv, btv->cvbi);
3898         bttv_set_dma(btv, 0);
3899         spin_unlock_irqrestore(&btv->s_lock,flags);
3900         return 0;
3901 }
3902
3903 static const struct pci_device_id bttv_pci_tbl[] = {
3904         {PCI_VDEVICE(BROOKTREE, PCI_DEVICE_ID_BT848), 0},
3905         {PCI_VDEVICE(BROOKTREE, PCI_DEVICE_ID_BT849), 0},
3906         {PCI_VDEVICE(BROOKTREE, PCI_DEVICE_ID_BT878), 0},
3907         {PCI_VDEVICE(BROOKTREE, PCI_DEVICE_ID_BT879), 0},
3908         {PCI_VDEVICE(BROOKTREE, PCI_DEVICE_ID_FUSION879), 0},
3909         {0,}
3910 };
3911
3912 MODULE_DEVICE_TABLE(pci, bttv_pci_tbl);
3913
3914 static SIMPLE_DEV_PM_OPS(bttv_pm_ops,
3915                          bttv_suspend,
3916                          bttv_resume);
3917
3918 static struct pci_driver bttv_pci_driver = {
3919         .name      = "bttv",
3920         .id_table  = bttv_pci_tbl,
3921         .probe     = bttv_probe,
3922         .remove    = bttv_remove,
3923         .driver.pm = &bttv_pm_ops,
3924 };
3925
3926 static int __init bttv_init_module(void)
3927 {
3928         int ret;
3929
3930         bttv_num = 0;
3931
3932         pr_info("driver version %s loaded\n", BTTV_VERSION);
3933         if (gbuffers < 2 || gbuffers > VIDEO_MAX_FRAME)
3934                 gbuffers = 2;
3935         if (gbufsize > BTTV_MAX_FBUF)
3936                 gbufsize = BTTV_MAX_FBUF;
3937         gbufsize = (gbufsize + PAGE_SIZE - 1) & PAGE_MASK;
3938         if (bttv_verbose)
3939                 pr_info("using %d buffers with %dk (%d pages) each for capture\n",
3940                         gbuffers, gbufsize >> 10, gbufsize >> PAGE_SHIFT);
3941
3942         bttv_check_chipset();
3943
3944         ret = bus_register(&bttv_sub_bus_type);
3945         if (ret < 0) {
3946                 pr_warn("bus_register error: %d\n", ret);
3947                 return ret;
3948         }
3949         ret = pci_register_driver(&bttv_pci_driver);
3950         if (ret < 0)
3951                 bus_unregister(&bttv_sub_bus_type);
3952
3953         return ret;
3954 }
3955
3956 static void __exit bttv_cleanup_module(void)
3957 {
3958         pci_unregister_driver(&bttv_pci_driver);
3959         bus_unregister(&bttv_sub_bus_type);
3960 }
3961
3962 module_init(bttv_init_module);
3963 module_exit(bttv_cleanup_module);
This page took 0.258323 seconds and 4 git commands to generate.