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