KVM: i8259: initialize isr_ack
[~shefty/rdma-dev.git] / drivers / media / video / 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 #include <linux/init.h>
38 #include <linux/module.h>
39 #include <linux/delay.h>
40 #include <linux/slab.h>
41 #include <linux/errno.h>
42 #include <linux/fs.h>
43 #include <linux/kernel.h>
44 #include <linux/sched.h>
45 #include <linux/interrupt.h>
46 #include <linux/kdev_t.h>
47 #include "bttvp.h"
48 #include <media/v4l2-common.h>
49 #include <media/v4l2-ioctl.h>
50 #include <media/tvaudio.h>
51 #include <media/msp3400.h>
52
53 #include <linux/dma-mapping.h>
54
55 #include <asm/io.h>
56 #include <asm/byteorder.h>
57
58 #include <media/rds.h>
59
60
61 unsigned int bttv_num;                  /* number of Bt848s in use */
62 struct bttv *bttvs[BTTV_MAX];
63
64 unsigned int bttv_debug;
65 unsigned int bttv_verbose = 1;
66 unsigned int bttv_gpio;
67
68 /* config variables */
69 #ifdef __BIG_ENDIAN
70 static unsigned int bigendian=1;
71 #else
72 static unsigned int bigendian;
73 #endif
74 static unsigned int radio[BTTV_MAX];
75 static unsigned int irq_debug;
76 static unsigned int gbuffers = 8;
77 static unsigned int gbufsize = 0x208000;
78 static unsigned int reset_crop = 1;
79
80 static int video_nr[BTTV_MAX] = { [0 ... (BTTV_MAX-1)] = -1 };
81 static int radio_nr[BTTV_MAX] = { [0 ... (BTTV_MAX-1)] = -1 };
82 static int vbi_nr[BTTV_MAX] = { [0 ... (BTTV_MAX-1)] = -1 };
83 static int debug_latency;
84 static int disable_ir;
85
86 static unsigned int fdsr;
87
88 /* options */
89 static unsigned int combfilter;
90 static unsigned int lumafilter;
91 static unsigned int automute    = 1;
92 static unsigned int chroma_agc;
93 static unsigned int adc_crush   = 1;
94 static unsigned int whitecrush_upper = 0xCF;
95 static unsigned int whitecrush_lower = 0x7F;
96 static unsigned int vcr_hack;
97 static unsigned int irq_iswitch;
98 static unsigned int uv_ratio    = 50;
99 static unsigned int full_luma_range;
100 static unsigned int coring;
101
102 /* API features (turn on/off stuff for testing) */
103 static unsigned int v4l2        = 1;
104
105 /* insmod args */
106 module_param(bttv_verbose,      int, 0644);
107 module_param(bttv_gpio,         int, 0644);
108 module_param(bttv_debug,        int, 0644);
109 module_param(irq_debug,         int, 0644);
110 module_param(debug_latency,     int, 0644);
111 module_param(disable_ir,        int, 0444);
112
113 module_param(fdsr,              int, 0444);
114 module_param(gbuffers,          int, 0444);
115 module_param(gbufsize,          int, 0444);
116 module_param(reset_crop,        int, 0444);
117
118 module_param(v4l2,              int, 0644);
119 module_param(bigendian,         int, 0644);
120 module_param(irq_iswitch,       int, 0644);
121 module_param(combfilter,        int, 0444);
122 module_param(lumafilter,        int, 0444);
123 module_param(automute,          int, 0444);
124 module_param(chroma_agc,        int, 0444);
125 module_param(adc_crush,         int, 0444);
126 module_param(whitecrush_upper,  int, 0444);
127 module_param(whitecrush_lower,  int, 0444);
128 module_param(vcr_hack,          int, 0444);
129 module_param(uv_ratio,          int, 0444);
130 module_param(full_luma_range,   int, 0444);
131 module_param(coring,            int, 0444);
132
133 module_param_array(radio,       int, NULL, 0444);
134 module_param_array(video_nr,    int, NULL, 0444);
135 module_param_array(radio_nr,    int, NULL, 0444);
136 module_param_array(vbi_nr,      int, NULL, 0444);
137
138 MODULE_PARM_DESC(radio,"The TV card supports radio, default is 0 (no)");
139 MODULE_PARM_DESC(bigendian,"byte order of the framebuffer, default is native endian");
140 MODULE_PARM_DESC(bttv_verbose,"verbose startup messages, default is 1 (yes)");
141 MODULE_PARM_DESC(bttv_gpio,"log gpio changes, default is 0 (no)");
142 MODULE_PARM_DESC(bttv_debug,"debug messages, default is 0 (no)");
143 MODULE_PARM_DESC(irq_debug,"irq handler debug messages, default is 0 (no)");
144 MODULE_PARM_DESC(disable_ir, "disable infrared remote support");
145 MODULE_PARM_DESC(gbuffers,"number of capture buffers. range 2-32, default 8");
146 MODULE_PARM_DESC(gbufsize,"size of the capture buffers, default is 0x208000");
147 MODULE_PARM_DESC(reset_crop,"reset cropping parameters at open(), default "
148                  "is 1 (yes) for compatibility with older applications");
149 MODULE_PARM_DESC(automute,"mute audio on bad/missing video signal, default is 1 (yes)");
150 MODULE_PARM_DESC(chroma_agc,"enables the AGC of chroma signal, default is 0 (no)");
151 MODULE_PARM_DESC(adc_crush,"enables the luminance ADC crush, default is 1 (yes)");
152 MODULE_PARM_DESC(whitecrush_upper,"sets the white crush upper value, default is 207");
153 MODULE_PARM_DESC(whitecrush_lower,"sets the white crush lower value, default is 127");
154 MODULE_PARM_DESC(vcr_hack,"enables the VCR hack (improves synch on poor VCR tapes), default is 0 (no)");
155 MODULE_PARM_DESC(irq_iswitch,"switch inputs in irq handler");
156 MODULE_PARM_DESC(uv_ratio,"ratio between u and v gains, default is 50");
157 MODULE_PARM_DESC(full_luma_range,"use the full luma range, default is 0 (no)");
158 MODULE_PARM_DESC(coring,"set the luma coring level, default is 0 (no)");
159 MODULE_PARM_DESC(video_nr, "video device numbers");
160 MODULE_PARM_DESC(vbi_nr, "vbi device numbers");
161 MODULE_PARM_DESC(radio_nr, "radio device numbers");
162
163 MODULE_DESCRIPTION("bttv - v4l/v4l2 driver module for bt848/878 based cards");
164 MODULE_AUTHOR("Ralph Metzler & Marcus Metzler & Gerd Knorr");
165 MODULE_LICENSE("GPL");
166
167 /* ----------------------------------------------------------------------- */
168 /* sysfs                                                                   */
169
170 static ssize_t show_card(struct device *cd,
171                          struct device_attribute *attr, char *buf)
172 {
173         struct video_device *vfd = container_of(cd, struct video_device, dev);
174         struct bttv *btv = video_get_drvdata(vfd);
175         return sprintf(buf, "%d\n", btv ? btv->c.type : UNSET);
176 }
177 static DEVICE_ATTR(card, S_IRUGO, show_card, NULL);
178
179 /* ----------------------------------------------------------------------- */
180 /* dvb auto-load setup                                                     */
181 #if defined(CONFIG_MODULES) && defined(MODULE)
182 static void request_module_async(struct work_struct *work)
183 {
184         request_module("dvb-bt8xx");
185 }
186
187 static void request_modules(struct bttv *dev)
188 {
189         INIT_WORK(&dev->request_module_wk, request_module_async);
190         schedule_work(&dev->request_module_wk);
191 }
192 #else
193 #define request_modules(dev)
194 #endif /* CONFIG_MODULES */
195
196
197 /* ----------------------------------------------------------------------- */
198 /* static data                                                             */
199
200 /* special timing tables from conexant... */
201 static u8 SRAM_Table[][60] =
202 {
203         /* PAL digital input over GPIO[7:0] */
204         {
205                 45, // 45 bytes following
206                 0x36,0x11,0x01,0x00,0x90,0x02,0x05,0x10,0x04,0x16,
207                 0x12,0x05,0x11,0x00,0x04,0x12,0xC0,0x00,0x31,0x00,
208                 0x06,0x51,0x08,0x03,0x89,0x08,0x07,0xC0,0x44,0x00,
209                 0x81,0x01,0x01,0xA9,0x0D,0x02,0x02,0x50,0x03,0x37,
210                 0x37,0x00,0xAF,0x21,0x00
211         },
212         /* NTSC digital input over GPIO[7:0] */
213         {
214                 51, // 51 bytes following
215                 0x0C,0xC0,0x00,0x00,0x90,0x02,0x03,0x10,0x03,0x06,
216                 0x10,0x04,0x12,0x12,0x05,0x02,0x13,0x04,0x19,0x00,
217                 0x04,0x39,0x00,0x06,0x59,0x08,0x03,0x83,0x08,0x07,
218                 0x03,0x50,0x00,0xC0,0x40,0x00,0x86,0x01,0x01,0xA6,
219                 0x0D,0x02,0x03,0x11,0x01,0x05,0x37,0x00,0xAC,0x21,
220                 0x00,
221         },
222         // TGB_NTSC392 // quartzsight
223         // This table has been modified to be used for Fusion Rev D
224         {
225                 0x2A, // size of table = 42
226                 0x06, 0x08, 0x04, 0x0a, 0xc0, 0x00, 0x18, 0x08, 0x03, 0x24,
227                 0x08, 0x07, 0x02, 0x90, 0x02, 0x08, 0x10, 0x04, 0x0c, 0x10,
228                 0x05, 0x2c, 0x11, 0x04, 0x55, 0x48, 0x00, 0x05, 0x50, 0x00,
229                 0xbf, 0x0c, 0x02, 0x2f, 0x3d, 0x00, 0x2f, 0x3f, 0x00, 0xc3,
230                 0x20, 0x00
231         }
232 };
233
234 /* minhdelayx1  first video pixel we can capture on a line and
235    hdelayx1     start of active video, both relative to rising edge of
236                 /HRESET pulse (0H) in 1 / fCLKx1.
237    swidth       width of active video and
238    totalwidth   total line width, both in 1 / fCLKx1.
239    sqwidth      total line width in square pixels.
240    vdelay       start of active video in 2 * field lines relative to
241                 trailing edge of /VRESET pulse (VDELAY register).
242    sheight      height of active video in 2 * field lines.
243    videostart0  ITU-R frame line number of the line corresponding
244                 to vdelay in the first field. */
245 #define CROPCAP(minhdelayx1, hdelayx1, swidth, totalwidth, sqwidth,      \
246                 vdelay, sheight, videostart0)                            \
247         .cropcap.bounds.left = minhdelayx1,                              \
248         /* * 2 because vertically we count field lines times two, */     \
249         /* e.g. 23 * 2 to 23 * 2 + 576 in PAL-BGHI defrect. */           \
250         .cropcap.bounds.top = (videostart0) * 2 - (vdelay) + MIN_VDELAY, \
251         /* 4 is a safety margin at the end of the line. */               \
252         .cropcap.bounds.width = (totalwidth) - (minhdelayx1) - 4,        \
253         .cropcap.bounds.height = (sheight) + (vdelay) - MIN_VDELAY,      \
254         .cropcap.defrect.left = hdelayx1,                                \
255         .cropcap.defrect.top = (videostart0) * 2,                        \
256         .cropcap.defrect.width = swidth,                                 \
257         .cropcap.defrect.height = sheight,                               \
258         .cropcap.pixelaspect.numerator = totalwidth,                     \
259         .cropcap.pixelaspect.denominator = sqwidth,
260
261 const struct bttv_tvnorm bttv_tvnorms[] = {
262         /* PAL-BDGHI */
263         /* max. active video is actually 922, but 924 is divisible by 4 and 3! */
264         /* actually, max active PAL with HSCALE=0 is 948, NTSC is 768 - nil */
265         {
266                 .v4l2_id        = V4L2_STD_PAL,
267                 .name           = "PAL",
268                 .Fsc            = 35468950,
269                 .swidth         = 924,
270                 .sheight        = 576,
271                 .totalwidth     = 1135,
272                 .adelay         = 0x7f,
273                 .bdelay         = 0x72,
274                 .iform          = (BT848_IFORM_PAL_BDGHI|BT848_IFORM_XT1),
275                 .scaledtwidth   = 1135,
276                 .hdelayx1       = 186,
277                 .hactivex1      = 924,
278                 .vdelay         = 0x20,
279                 .vbipack        = 255, /* min (2048 / 4, 0x1ff) & 0xff */
280                 .sram           = 0,
281                 /* ITU-R frame line number of the first VBI line
282                    we can capture, of the first and second field.
283                    The last line is determined by cropcap.bounds. */
284                 .vbistart       = { 7, 320 },
285                 CROPCAP(/* minhdelayx1 */ 68,
286                         /* hdelayx1 */ 186,
287                         /* Should be (768 * 1135 + 944 / 2) / 944.
288                            cropcap.defrect is used for image width
289                            checks, so we keep the old value 924. */
290                         /* swidth */ 924,
291                         /* totalwidth */ 1135,
292                         /* sqwidth */ 944,
293                         /* vdelay */ 0x20,
294                         /* sheight */ 576,
295                         /* videostart0 */ 23)
296                 /* bt878 (and bt848?) can capture another
297                    line below active video. */
298                 .cropcap.bounds.height = (576 + 2) + 0x20 - 2,
299         },{
300                 .v4l2_id        = V4L2_STD_NTSC_M | V4L2_STD_NTSC_M_KR,
301                 .name           = "NTSC",
302                 .Fsc            = 28636363,
303                 .swidth         = 768,
304                 .sheight        = 480,
305                 .totalwidth     = 910,
306                 .adelay         = 0x68,
307                 .bdelay         = 0x5d,
308                 .iform          = (BT848_IFORM_NTSC|BT848_IFORM_XT0),
309                 .scaledtwidth   = 910,
310                 .hdelayx1       = 128,
311                 .hactivex1      = 910,
312                 .vdelay         = 0x1a,
313                 .vbipack        = 144, /* min (1600 / 4, 0x1ff) & 0xff */
314                 .sram           = 1,
315                 .vbistart       = { 10, 273 },
316                 CROPCAP(/* minhdelayx1 */ 68,
317                         /* hdelayx1 */ 128,
318                         /* Should be (640 * 910 + 780 / 2) / 780? */
319                         /* swidth */ 768,
320                         /* totalwidth */ 910,
321                         /* sqwidth */ 780,
322                         /* vdelay */ 0x1a,
323                         /* sheight */ 480,
324                         /* videostart0 */ 23)
325         },{
326                 .v4l2_id        = V4L2_STD_SECAM,
327                 .name           = "SECAM",
328                 .Fsc            = 35468950,
329                 .swidth         = 924,
330                 .sheight        = 576,
331                 .totalwidth     = 1135,
332                 .adelay         = 0x7f,
333                 .bdelay         = 0xb0,
334                 .iform          = (BT848_IFORM_SECAM|BT848_IFORM_XT1),
335                 .scaledtwidth   = 1135,
336                 .hdelayx1       = 186,
337                 .hactivex1      = 922,
338                 .vdelay         = 0x20,
339                 .vbipack        = 255,
340                 .sram           = 0, /* like PAL, correct? */
341                 .vbistart       = { 7, 320 },
342                 CROPCAP(/* minhdelayx1 */ 68,
343                         /* hdelayx1 */ 186,
344                         /* swidth */ 924,
345                         /* totalwidth */ 1135,
346                         /* sqwidth */ 944,
347                         /* vdelay */ 0x20,
348                         /* sheight */ 576,
349                         /* videostart0 */ 23)
350         },{
351                 .v4l2_id        = V4L2_STD_PAL_Nc,
352                 .name           = "PAL-Nc",
353                 .Fsc            = 28636363,
354                 .swidth         = 640,
355                 .sheight        = 576,
356                 .totalwidth     = 910,
357                 .adelay         = 0x68,
358                 .bdelay         = 0x5d,
359                 .iform          = (BT848_IFORM_PAL_NC|BT848_IFORM_XT0),
360                 .scaledtwidth   = 780,
361                 .hdelayx1       = 130,
362                 .hactivex1      = 734,
363                 .vdelay         = 0x1a,
364                 .vbipack        = 144,
365                 .sram           = -1,
366                 .vbistart       = { 7, 320 },
367                 CROPCAP(/* minhdelayx1 */ 68,
368                         /* hdelayx1 */ 130,
369                         /* swidth */ (640 * 910 + 780 / 2) / 780,
370                         /* totalwidth */ 910,
371                         /* sqwidth */ 780,
372                         /* vdelay */ 0x1a,
373                         /* sheight */ 576,
374                         /* videostart0 */ 23)
375         },{
376                 .v4l2_id        = V4L2_STD_PAL_M,
377                 .name           = "PAL-M",
378                 .Fsc            = 28636363,
379                 .swidth         = 640,
380                 .sheight        = 480,
381                 .totalwidth     = 910,
382                 .adelay         = 0x68,
383                 .bdelay         = 0x5d,
384                 .iform          = (BT848_IFORM_PAL_M|BT848_IFORM_XT0),
385                 .scaledtwidth   = 780,
386                 .hdelayx1       = 135,
387                 .hactivex1      = 754,
388                 .vdelay         = 0x1a,
389                 .vbipack        = 144,
390                 .sram           = -1,
391                 .vbistart       = { 10, 273 },
392                 CROPCAP(/* minhdelayx1 */ 68,
393                         /* hdelayx1 */ 135,
394                         /* swidth */ (640 * 910 + 780 / 2) / 780,
395                         /* totalwidth */ 910,
396                         /* sqwidth */ 780,
397                         /* vdelay */ 0x1a,
398                         /* sheight */ 480,
399                         /* videostart0 */ 23)
400         },{
401                 .v4l2_id        = V4L2_STD_PAL_N,
402                 .name           = "PAL-N",
403                 .Fsc            = 35468950,
404                 .swidth         = 768,
405                 .sheight        = 576,
406                 .totalwidth     = 1135,
407                 .adelay         = 0x7f,
408                 .bdelay         = 0x72,
409                 .iform          = (BT848_IFORM_PAL_N|BT848_IFORM_XT1),
410                 .scaledtwidth   = 944,
411                 .hdelayx1       = 186,
412                 .hactivex1      = 922,
413                 .vdelay         = 0x20,
414                 .vbipack        = 144,
415                 .sram           = -1,
416                 .vbistart       = { 7, 320 },
417                 CROPCAP(/* minhdelayx1 */ 68,
418                         /* hdelayx1 */ 186,
419                         /* swidth */ (768 * 1135 + 944 / 2) / 944,
420                         /* totalwidth */ 1135,
421                         /* sqwidth */ 944,
422                         /* vdelay */ 0x20,
423                         /* sheight */ 576,
424                         /* videostart0 */ 23)
425         },{
426                 .v4l2_id        = V4L2_STD_NTSC_M_JP,
427                 .name           = "NTSC-JP",
428                 .Fsc            = 28636363,
429                 .swidth         = 640,
430                 .sheight        = 480,
431                 .totalwidth     = 910,
432                 .adelay         = 0x68,
433                 .bdelay         = 0x5d,
434                 .iform          = (BT848_IFORM_NTSC_J|BT848_IFORM_XT0),
435                 .scaledtwidth   = 780,
436                 .hdelayx1       = 135,
437                 .hactivex1      = 754,
438                 .vdelay         = 0x16,
439                 .vbipack        = 144,
440                 .sram           = -1,
441                 .vbistart       = { 10, 273 },
442                 CROPCAP(/* minhdelayx1 */ 68,
443                         /* hdelayx1 */ 135,
444                         /* swidth */ (640 * 910 + 780 / 2) / 780,
445                         /* totalwidth */ 910,
446                         /* sqwidth */ 780,
447                         /* vdelay */ 0x16,
448                         /* sheight */ 480,
449                         /* videostart0 */ 23)
450         },{
451                 /* that one hopefully works with the strange timing
452                  * which video recorders produce when playing a NTSC
453                  * tape on a PAL TV ... */
454                 .v4l2_id        = V4L2_STD_PAL_60,
455                 .name           = "PAL-60",
456                 .Fsc            = 35468950,
457                 .swidth         = 924,
458                 .sheight        = 480,
459                 .totalwidth     = 1135,
460                 .adelay         = 0x7f,
461                 .bdelay         = 0x72,
462                 .iform          = (BT848_IFORM_PAL_BDGHI|BT848_IFORM_XT1),
463                 .scaledtwidth   = 1135,
464                 .hdelayx1       = 186,
465                 .hactivex1      = 924,
466                 .vdelay         = 0x1a,
467                 .vbipack        = 255,
468                 .vtotal         = 524,
469                 .sram           = -1,
470                 .vbistart       = { 10, 273 },
471                 CROPCAP(/* minhdelayx1 */ 68,
472                         /* hdelayx1 */ 186,
473                         /* swidth */ 924,
474                         /* totalwidth */ 1135,
475                         /* sqwidth */ 944,
476                         /* vdelay */ 0x1a,
477                         /* sheight */ 480,
478                         /* videostart0 */ 23)
479         }
480 };
481 static const unsigned int BTTV_TVNORMS = ARRAY_SIZE(bttv_tvnorms);
482
483 /* ----------------------------------------------------------------------- */
484 /* bttv format list
485    packed pixel formats must come first */
486 static const struct bttv_format formats[] = {
487         {
488                 .name     = "8 bpp, gray",
489                 .fourcc   = V4L2_PIX_FMT_GREY,
490                 .btformat = BT848_COLOR_FMT_Y8,
491                 .depth    = 8,
492                 .flags    = FORMAT_FLAGS_PACKED,
493         },{
494                 .name     = "8 bpp, dithered color",
495                 .fourcc   = V4L2_PIX_FMT_HI240,
496                 .btformat = BT848_COLOR_FMT_RGB8,
497                 .depth    = 8,
498                 .flags    = FORMAT_FLAGS_PACKED | FORMAT_FLAGS_DITHER,
499         },{
500                 .name     = "15 bpp RGB, le",
501                 .fourcc   = V4L2_PIX_FMT_RGB555,
502                 .btformat = BT848_COLOR_FMT_RGB15,
503                 .depth    = 16,
504                 .flags    = FORMAT_FLAGS_PACKED,
505         },{
506                 .name     = "15 bpp RGB, be",
507                 .fourcc   = V4L2_PIX_FMT_RGB555X,
508                 .btformat = BT848_COLOR_FMT_RGB15,
509                 .btswap   = 0x03, /* byteswap */
510                 .depth    = 16,
511                 .flags    = FORMAT_FLAGS_PACKED,
512         },{
513                 .name     = "16 bpp RGB, le",
514                 .fourcc   = V4L2_PIX_FMT_RGB565,
515                 .btformat = BT848_COLOR_FMT_RGB16,
516                 .depth    = 16,
517                 .flags    = FORMAT_FLAGS_PACKED,
518         },{
519                 .name     = "16 bpp RGB, be",
520                 .fourcc   = V4L2_PIX_FMT_RGB565X,
521                 .btformat = BT848_COLOR_FMT_RGB16,
522                 .btswap   = 0x03, /* byteswap */
523                 .depth    = 16,
524                 .flags    = FORMAT_FLAGS_PACKED,
525         },{
526                 .name     = "24 bpp RGB, le",
527                 .fourcc   = V4L2_PIX_FMT_BGR24,
528                 .btformat = BT848_COLOR_FMT_RGB24,
529                 .depth    = 24,
530                 .flags    = FORMAT_FLAGS_PACKED,
531         },{
532                 .name     = "32 bpp RGB, le",
533                 .fourcc   = V4L2_PIX_FMT_BGR32,
534                 .btformat = BT848_COLOR_FMT_RGB32,
535                 .depth    = 32,
536                 .flags    = FORMAT_FLAGS_PACKED,
537         },{
538                 .name     = "32 bpp RGB, be",
539                 .fourcc   = V4L2_PIX_FMT_RGB32,
540                 .btformat = BT848_COLOR_FMT_RGB32,
541                 .btswap   = 0x0f, /* byte+word swap */
542                 .depth    = 32,
543                 .flags    = FORMAT_FLAGS_PACKED,
544         },{
545                 .name     = "4:2:2, packed, YUYV",
546                 .fourcc   = V4L2_PIX_FMT_YUYV,
547                 .btformat = BT848_COLOR_FMT_YUY2,
548                 .depth    = 16,
549                 .flags    = FORMAT_FLAGS_PACKED,
550         },{
551                 .name     = "4:2:2, packed, YUYV",
552                 .fourcc   = V4L2_PIX_FMT_YUYV,
553                 .btformat = BT848_COLOR_FMT_YUY2,
554                 .depth    = 16,
555                 .flags    = FORMAT_FLAGS_PACKED,
556         },{
557                 .name     = "4:2:2, packed, UYVY",
558                 .fourcc   = V4L2_PIX_FMT_UYVY,
559                 .btformat = BT848_COLOR_FMT_YUY2,
560                 .btswap   = 0x03, /* byteswap */
561                 .depth    = 16,
562                 .flags    = FORMAT_FLAGS_PACKED,
563         },{
564                 .name     = "4:2:2, planar, Y-Cb-Cr",
565                 .fourcc   = V4L2_PIX_FMT_YUV422P,
566                 .btformat = BT848_COLOR_FMT_YCrCb422,
567                 .depth    = 16,
568                 .flags    = FORMAT_FLAGS_PLANAR,
569                 .hshift   = 1,
570                 .vshift   = 0,
571         },{
572                 .name     = "4:2:0, planar, Y-Cb-Cr",
573                 .fourcc   = V4L2_PIX_FMT_YUV420,
574                 .btformat = BT848_COLOR_FMT_YCrCb422,
575                 .depth    = 12,
576                 .flags    = FORMAT_FLAGS_PLANAR,
577                 .hshift   = 1,
578                 .vshift   = 1,
579         },{
580                 .name     = "4:2:0, planar, Y-Cr-Cb",
581                 .fourcc   = V4L2_PIX_FMT_YVU420,
582                 .btformat = BT848_COLOR_FMT_YCrCb422,
583                 .depth    = 12,
584                 .flags    = FORMAT_FLAGS_PLANAR | FORMAT_FLAGS_CrCb,
585                 .hshift   = 1,
586                 .vshift   = 1,
587         },{
588                 .name     = "4:1:1, planar, Y-Cb-Cr",
589                 .fourcc   = V4L2_PIX_FMT_YUV411P,
590                 .btformat = BT848_COLOR_FMT_YCrCb411,
591                 .depth    = 12,
592                 .flags    = FORMAT_FLAGS_PLANAR,
593                 .hshift   = 2,
594                 .vshift   = 0,
595         },{
596                 .name     = "4:1:0, planar, Y-Cb-Cr",
597                 .fourcc   = V4L2_PIX_FMT_YUV410,
598                 .btformat = BT848_COLOR_FMT_YCrCb411,
599                 .depth    = 9,
600                 .flags    = FORMAT_FLAGS_PLANAR,
601                 .hshift   = 2,
602                 .vshift   = 2,
603         },{
604                 .name     = "4:1:0, planar, Y-Cr-Cb",
605                 .fourcc   = V4L2_PIX_FMT_YVU410,
606                 .btformat = BT848_COLOR_FMT_YCrCb411,
607                 .depth    = 9,
608                 .flags    = FORMAT_FLAGS_PLANAR | FORMAT_FLAGS_CrCb,
609                 .hshift   = 2,
610                 .vshift   = 2,
611         },{
612                 .name     = "raw scanlines",
613                 .fourcc   = -1,
614                 .btformat = BT848_COLOR_FMT_RAW,
615                 .depth    = 8,
616                 .flags    = FORMAT_FLAGS_RAW,
617         }
618 };
619 static const unsigned int FORMATS = ARRAY_SIZE(formats);
620
621 /* ----------------------------------------------------------------------- */
622
623 #define V4L2_CID_PRIVATE_CHROMA_AGC  (V4L2_CID_PRIVATE_BASE + 0)
624 #define V4L2_CID_PRIVATE_COMBFILTER  (V4L2_CID_PRIVATE_BASE + 1)
625 #define V4L2_CID_PRIVATE_AUTOMUTE    (V4L2_CID_PRIVATE_BASE + 2)
626 #define V4L2_CID_PRIVATE_LUMAFILTER  (V4L2_CID_PRIVATE_BASE + 3)
627 #define V4L2_CID_PRIVATE_AGC_CRUSH   (V4L2_CID_PRIVATE_BASE + 4)
628 #define V4L2_CID_PRIVATE_VCR_HACK    (V4L2_CID_PRIVATE_BASE + 5)
629 #define V4L2_CID_PRIVATE_WHITECRUSH_UPPER   (V4L2_CID_PRIVATE_BASE + 6)
630 #define V4L2_CID_PRIVATE_WHITECRUSH_LOWER   (V4L2_CID_PRIVATE_BASE + 7)
631 #define V4L2_CID_PRIVATE_UV_RATIO    (V4L2_CID_PRIVATE_BASE + 8)
632 #define V4L2_CID_PRIVATE_FULL_LUMA_RANGE    (V4L2_CID_PRIVATE_BASE + 9)
633 #define V4L2_CID_PRIVATE_CORING      (V4L2_CID_PRIVATE_BASE + 10)
634 #define V4L2_CID_PRIVATE_LASTP1      (V4L2_CID_PRIVATE_BASE + 11)
635
636 static const struct v4l2_queryctrl no_ctl = {
637         .name  = "42",
638         .flags = V4L2_CTRL_FLAG_DISABLED,
639 };
640 static const struct v4l2_queryctrl bttv_ctls[] = {
641         /* --- video --- */
642         {
643                 .id            = V4L2_CID_BRIGHTNESS,
644                 .name          = "Brightness",
645                 .minimum       = 0,
646                 .maximum       = 65535,
647                 .step          = 256,
648                 .default_value = 32768,
649                 .type          = V4L2_CTRL_TYPE_INTEGER,
650         },{
651                 .id            = V4L2_CID_CONTRAST,
652                 .name          = "Contrast",
653                 .minimum       = 0,
654                 .maximum       = 65535,
655                 .step          = 128,
656                 .default_value = 32768,
657                 .type          = V4L2_CTRL_TYPE_INTEGER,
658         },{
659                 .id            = V4L2_CID_SATURATION,
660                 .name          = "Saturation",
661                 .minimum       = 0,
662                 .maximum       = 65535,
663                 .step          = 128,
664                 .default_value = 32768,
665                 .type          = V4L2_CTRL_TYPE_INTEGER,
666         },{
667                 .id            = V4L2_CID_HUE,
668                 .name          = "Hue",
669                 .minimum       = 0,
670                 .maximum       = 65535,
671                 .step          = 256,
672                 .default_value = 32768,
673                 .type          = V4L2_CTRL_TYPE_INTEGER,
674         },
675         /* --- audio --- */
676         {
677                 .id            = V4L2_CID_AUDIO_MUTE,
678                 .name          = "Mute",
679                 .minimum       = 0,
680                 .maximum       = 1,
681                 .type          = V4L2_CTRL_TYPE_BOOLEAN,
682         },{
683                 .id            = V4L2_CID_AUDIO_VOLUME,
684                 .name          = "Volume",
685                 .minimum       = 0,
686                 .maximum       = 65535,
687                 .step          = 65535/100,
688                 .default_value = 65535,
689                 .type          = V4L2_CTRL_TYPE_INTEGER,
690         },{
691                 .id            = V4L2_CID_AUDIO_BALANCE,
692                 .name          = "Balance",
693                 .minimum       = 0,
694                 .maximum       = 65535,
695                 .step          = 65535/100,
696                 .default_value = 32768,
697                 .type          = V4L2_CTRL_TYPE_INTEGER,
698         },{
699                 .id            = V4L2_CID_AUDIO_BASS,
700                 .name          = "Bass",
701                 .minimum       = 0,
702                 .maximum       = 65535,
703                 .step          = 65535/100,
704                 .default_value = 32768,
705                 .type          = V4L2_CTRL_TYPE_INTEGER,
706         },{
707                 .id            = V4L2_CID_AUDIO_TREBLE,
708                 .name          = "Treble",
709                 .minimum       = 0,
710                 .maximum       = 65535,
711                 .step          = 65535/100,
712                 .default_value = 32768,
713                 .type          = V4L2_CTRL_TYPE_INTEGER,
714         },
715         /* --- private --- */
716         {
717                 .id            = V4L2_CID_PRIVATE_CHROMA_AGC,
718                 .name          = "chroma agc",
719                 .minimum       = 0,
720                 .maximum       = 1,
721                 .type          = V4L2_CTRL_TYPE_BOOLEAN,
722         },{
723                 .id            = V4L2_CID_PRIVATE_COMBFILTER,
724                 .name          = "combfilter",
725                 .minimum       = 0,
726                 .maximum       = 1,
727                 .type          = V4L2_CTRL_TYPE_BOOLEAN,
728         },{
729                 .id            = V4L2_CID_PRIVATE_AUTOMUTE,
730                 .name          = "automute",
731                 .minimum       = 0,
732                 .maximum       = 1,
733                 .type          = V4L2_CTRL_TYPE_BOOLEAN,
734         },{
735                 .id            = V4L2_CID_PRIVATE_LUMAFILTER,
736                 .name          = "luma decimation filter",
737                 .minimum       = 0,
738                 .maximum       = 1,
739                 .type          = V4L2_CTRL_TYPE_BOOLEAN,
740         },{
741                 .id            = V4L2_CID_PRIVATE_AGC_CRUSH,
742                 .name          = "agc crush",
743                 .minimum       = 0,
744                 .maximum       = 1,
745                 .type          = V4L2_CTRL_TYPE_BOOLEAN,
746         },{
747                 .id            = V4L2_CID_PRIVATE_VCR_HACK,
748                 .name          = "vcr hack",
749                 .minimum       = 0,
750                 .maximum       = 1,
751                 .type          = V4L2_CTRL_TYPE_BOOLEAN,
752         },{
753                 .id            = V4L2_CID_PRIVATE_WHITECRUSH_UPPER,
754                 .name          = "whitecrush upper",
755                 .minimum       = 0,
756                 .maximum       = 255,
757                 .step          = 1,
758                 .default_value = 0xCF,
759                 .type          = V4L2_CTRL_TYPE_INTEGER,
760         },{
761                 .id            = V4L2_CID_PRIVATE_WHITECRUSH_LOWER,
762                 .name          = "whitecrush lower",
763                 .minimum       = 0,
764                 .maximum       = 255,
765                 .step          = 1,
766                 .default_value = 0x7F,
767                 .type          = V4L2_CTRL_TYPE_INTEGER,
768         },{
769                 .id            = V4L2_CID_PRIVATE_UV_RATIO,
770                 .name          = "uv ratio",
771                 .minimum       = 0,
772                 .maximum       = 100,
773                 .step          = 1,
774                 .default_value = 50,
775                 .type          = V4L2_CTRL_TYPE_INTEGER,
776         },{
777                 .id            = V4L2_CID_PRIVATE_FULL_LUMA_RANGE,
778                 .name          = "full luma range",
779                 .minimum       = 0,
780                 .maximum       = 1,
781                 .type          = V4L2_CTRL_TYPE_BOOLEAN,
782         },{
783                 .id            = V4L2_CID_PRIVATE_CORING,
784                 .name          = "coring",
785                 .minimum       = 0,
786                 .maximum       = 3,
787                 .step          = 1,
788                 .default_value = 0,
789                 .type          = V4L2_CTRL_TYPE_INTEGER,
790         }
791
792
793
794 };
795
796 static const struct v4l2_queryctrl *ctrl_by_id(int id)
797 {
798         int i;
799
800         for (i = 0; i < ARRAY_SIZE(bttv_ctls); i++)
801                 if (bttv_ctls[i].id == id)
802                         return bttv_ctls+i;
803
804         return NULL;
805 }
806
807 /* ----------------------------------------------------------------------- */
808 /* resource management                                                     */
809
810 /*
811    RESOURCE_    allocated by                freed by
812
813    VIDEO_READ   bttv_read 1)                bttv_read 2)
814
815    VIDEO_STREAM VIDIOC_STREAMON             VIDIOC_STREAMOFF
816                  VIDIOC_QBUF 1)              bttv_release
817                  VIDIOCMCAPTURE 1)
818
819    OVERLAY       VIDIOCCAPTURE on            VIDIOCCAPTURE off
820                  VIDIOC_OVERLAY on           VIDIOC_OVERLAY off
821                  3)                          bttv_release
822
823    VBI           VIDIOC_STREAMON             VIDIOC_STREAMOFF
824                  VIDIOC_QBUF 1)              bttv_release
825                  bttv_read, bttv_poll 1) 4)
826
827    1) The resource must be allocated when we enter buffer prepare functions
828       and remain allocated while buffers are in the DMA queue.
829    2) This is a single frame read.
830    3) VIDIOC_S_FBUF and VIDIOC_S_FMT (OVERLAY) still work when
831       RESOURCE_OVERLAY is allocated.
832    4) This is a continuous read, implies VIDIOC_STREAMON.
833
834    Note this driver permits video input and standard changes regardless if
835    resources are allocated.
836 */
837
838 #define VBI_RESOURCES (RESOURCE_VBI)
839 #define VIDEO_RESOURCES (RESOURCE_VIDEO_READ | \
840                          RESOURCE_VIDEO_STREAM | \
841                          RESOURCE_OVERLAY)
842
843 static
844 int check_alloc_btres_lock(struct bttv *btv, struct bttv_fh *fh, int bit)
845 {
846         int xbits; /* mutual exclusive resources */
847
848         if (fh->resources & bit)
849                 /* have it already allocated */
850                 return 1;
851
852         xbits = bit;
853         if (bit & (RESOURCE_VIDEO_READ | RESOURCE_VIDEO_STREAM))
854                 xbits |= RESOURCE_VIDEO_READ | RESOURCE_VIDEO_STREAM;
855
856         /* is it free? */
857         mutex_lock(&btv->lock);
858         if (btv->resources & xbits) {
859                 /* no, someone else uses it */
860                 goto fail;
861         }
862
863         if ((bit & VIDEO_RESOURCES)
864             && 0 == (btv->resources & VIDEO_RESOURCES)) {
865                 /* Do crop - use current, don't - use default parameters. */
866                 __s32 top = btv->crop[!!fh->do_crop].rect.top;
867
868                 if (btv->vbi_end > top)
869                         goto fail;
870
871                 /* We cannot capture the same line as video and VBI data.
872                    Claim scan lines crop[].rect.top to bottom. */
873                 btv->crop_start = top;
874         } else if (bit & VBI_RESOURCES) {
875                 __s32 end = fh->vbi_fmt.end;
876
877                 if (end > btv->crop_start)
878                         goto fail;
879
880                 /* Claim scan lines above fh->vbi_fmt.end. */
881                 btv->vbi_end = end;
882         }
883
884         /* it's free, grab it */
885         fh->resources  |= bit;
886         btv->resources |= bit;
887         mutex_unlock(&btv->lock);
888         return 1;
889
890  fail:
891         mutex_unlock(&btv->lock);
892         return 0;
893 }
894
895 static
896 int check_btres(struct bttv_fh *fh, int bit)
897 {
898         return (fh->resources & bit);
899 }
900
901 static
902 int locked_btres(struct bttv *btv, int bit)
903 {
904         return (btv->resources & bit);
905 }
906
907 /* Call with btv->lock down. */
908 static void
909 disclaim_vbi_lines(struct bttv *btv)
910 {
911         btv->vbi_end = 0;
912 }
913
914 /* Call with btv->lock down. */
915 static void
916 disclaim_video_lines(struct bttv *btv)
917 {
918         const struct bttv_tvnorm *tvnorm;
919         u8 crop;
920
921         tvnorm = &bttv_tvnorms[btv->tvnorm];
922         btv->crop_start = tvnorm->cropcap.bounds.top
923                 + tvnorm->cropcap.bounds.height;
924
925         /* VBI capturing ends at VDELAY, start of video capturing, no
926            matter how many lines the VBI RISC program expects. When video
927            capturing is off, it shall no longer "preempt" VBI capturing,
928            so we set VDELAY to maximum. */
929         crop = btread(BT848_E_CROP) | 0xc0;
930         btwrite(crop, BT848_E_CROP);
931         btwrite(0xfe, BT848_E_VDELAY_LO);
932         btwrite(crop, BT848_O_CROP);
933         btwrite(0xfe, BT848_O_VDELAY_LO);
934 }
935
936 static
937 void free_btres_lock(struct bttv *btv, struct bttv_fh *fh, int bits)
938 {
939         if ((fh->resources & bits) != bits) {
940                 /* trying to free ressources not allocated by us ... */
941                 printk("bttv: BUG! (btres)\n");
942         }
943         mutex_lock(&btv->lock);
944         fh->resources  &= ~bits;
945         btv->resources &= ~bits;
946
947         bits = btv->resources;
948
949         if (0 == (bits & VIDEO_RESOURCES))
950                 disclaim_video_lines(btv);
951
952         if (0 == (bits & VBI_RESOURCES))
953                 disclaim_vbi_lines(btv);
954
955         mutex_unlock(&btv->lock);
956 }
957
958 /* ----------------------------------------------------------------------- */
959 /* If Bt848a or Bt849, use PLL for PAL/SECAM and crystal for NTSC          */
960
961 /* Frequency = (F_input / PLL_X) * PLL_I.PLL_F/PLL_C
962    PLL_X = Reference pre-divider (0=1, 1=2)
963    PLL_C = Post divider (0=6, 1=4)
964    PLL_I = Integer input
965    PLL_F = Fractional input
966
967    F_input = 28.636363 MHz:
968    PAL (CLKx2 = 35.46895 MHz): PLL_X = 1, PLL_I = 0x0E, PLL_F = 0xDCF9, PLL_C = 0
969 */
970
971 static void set_pll_freq(struct bttv *btv, unsigned int fin, unsigned int fout)
972 {
973         unsigned char fl, fh, fi;
974
975         /* prevent overflows */
976         fin/=4;
977         fout/=4;
978
979         fout*=12;
980         fi=fout/fin;
981
982         fout=(fout%fin)*256;
983         fh=fout/fin;
984
985         fout=(fout%fin)*256;
986         fl=fout/fin;
987
988         btwrite(fl, BT848_PLL_F_LO);
989         btwrite(fh, BT848_PLL_F_HI);
990         btwrite(fi|BT848_PLL_X, BT848_PLL_XCI);
991 }
992
993 static void set_pll(struct bttv *btv)
994 {
995         int i;
996
997         if (!btv->pll.pll_crystal)
998                 return;
999
1000         if (btv->pll.pll_ofreq == btv->pll.pll_current) {
1001                 dprintk("bttv%d: PLL: no change required\n",btv->c.nr);
1002                 return;
1003         }
1004
1005         if (btv->pll.pll_ifreq == btv->pll.pll_ofreq) {
1006                 /* no PLL needed */
1007                 if (btv->pll.pll_current == 0)
1008                         return;
1009                 bttv_printk(KERN_INFO "bttv%d: PLL can sleep, using XTAL (%d).\n",
1010                         btv->c.nr,btv->pll.pll_ifreq);
1011                 btwrite(0x00,BT848_TGCTRL);
1012                 btwrite(0x00,BT848_PLL_XCI);
1013                 btv->pll.pll_current = 0;
1014                 return;
1015         }
1016
1017         bttv_printk(KERN_INFO "bttv%d: PLL: %d => %d ",btv->c.nr,
1018                 btv->pll.pll_ifreq, btv->pll.pll_ofreq);
1019         set_pll_freq(btv, btv->pll.pll_ifreq, btv->pll.pll_ofreq);
1020
1021         for (i=0; i<10; i++) {
1022                 /*  Let other people run while the PLL stabilizes */
1023                 bttv_printk(".");
1024                 msleep(10);
1025
1026                 if (btread(BT848_DSTATUS) & BT848_DSTATUS_PLOCK) {
1027                         btwrite(0,BT848_DSTATUS);
1028                 } else {
1029                         btwrite(0x08,BT848_TGCTRL);
1030                         btv->pll.pll_current = btv->pll.pll_ofreq;
1031                         bttv_printk(" ok\n");
1032                         return;
1033                 }
1034         }
1035         btv->pll.pll_current = -1;
1036         bttv_printk("failed\n");
1037         return;
1038 }
1039
1040 /* used to switch between the bt848's analog/digital video capture modes */
1041 static void bt848A_set_timing(struct bttv *btv)
1042 {
1043         int i, len;
1044         int table_idx = bttv_tvnorms[btv->tvnorm].sram;
1045         int fsc       = bttv_tvnorms[btv->tvnorm].Fsc;
1046
1047         if (btv->input == btv->dig) {
1048                 dprintk("bttv%d: load digital timing table (table_idx=%d)\n",
1049                         btv->c.nr,table_idx);
1050
1051                 /* timing change...reset timing generator address */
1052                 btwrite(0x00, BT848_TGCTRL);
1053                 btwrite(0x02, BT848_TGCTRL);
1054                 btwrite(0x00, BT848_TGCTRL);
1055
1056                 len=SRAM_Table[table_idx][0];
1057                 for(i = 1; i <= len; i++)
1058                         btwrite(SRAM_Table[table_idx][i],BT848_TGLB);
1059                 btv->pll.pll_ofreq = 27000000;
1060
1061                 set_pll(btv);
1062                 btwrite(0x11, BT848_TGCTRL);
1063                 btwrite(0x41, BT848_DVSIF);
1064         } else {
1065                 btv->pll.pll_ofreq = fsc;
1066                 set_pll(btv);
1067                 btwrite(0x0, BT848_DVSIF);
1068         }
1069 }
1070
1071 /* ----------------------------------------------------------------------- */
1072
1073 static void bt848_bright(struct bttv *btv, int bright)
1074 {
1075         int value;
1076
1077         // printk("bttv: set bright: %d\n",bright); // DEBUG
1078         btv->bright = bright;
1079
1080         /* We want -128 to 127 we get 0-65535 */
1081         value = (bright >> 8) - 128;
1082         btwrite(value & 0xff, BT848_BRIGHT);
1083 }
1084
1085 static void bt848_hue(struct bttv *btv, int hue)
1086 {
1087         int value;
1088
1089         btv->hue = hue;
1090
1091         /* -128 to 127 */
1092         value = (hue >> 8) - 128;
1093         btwrite(value & 0xff, BT848_HUE);
1094 }
1095
1096 static void bt848_contrast(struct bttv *btv, int cont)
1097 {
1098         int value,hibit;
1099
1100         btv->contrast = cont;
1101
1102         /* 0-511 */
1103         value = (cont  >> 7);
1104         hibit = (value >> 6) & 4;
1105         btwrite(value & 0xff, BT848_CONTRAST_LO);
1106         btaor(hibit, ~4, BT848_E_CONTROL);
1107         btaor(hibit, ~4, BT848_O_CONTROL);
1108 }
1109
1110 static void bt848_sat(struct bttv *btv, int color)
1111 {
1112         int val_u,val_v,hibits;
1113
1114         btv->saturation = color;
1115
1116         /* 0-511 for the color */
1117         val_u   = ((color * btv->opt_uv_ratio) / 50) >> 7;
1118         val_v   = (((color * (100 - btv->opt_uv_ratio) / 50) >>7)*180L)/254;
1119         hibits  = (val_u >> 7) & 2;
1120         hibits |= (val_v >> 8) & 1;
1121         btwrite(val_u & 0xff, BT848_SAT_U_LO);
1122         btwrite(val_v & 0xff, BT848_SAT_V_LO);
1123         btaor(hibits, ~3, BT848_E_CONTROL);
1124         btaor(hibits, ~3, BT848_O_CONTROL);
1125 }
1126
1127 /* ----------------------------------------------------------------------- */
1128
1129 static int
1130 video_mux(struct bttv *btv, unsigned int input)
1131 {
1132         int mux,mask2;
1133
1134         if (input >= bttv_tvcards[btv->c.type].video_inputs)
1135                 return -EINVAL;
1136
1137         /* needed by RemoteVideo MX */
1138         mask2 = bttv_tvcards[btv->c.type].gpiomask2;
1139         if (mask2)
1140                 gpio_inout(mask2,mask2);
1141
1142         if (input == btv->svhs)  {
1143                 btor(BT848_CONTROL_COMP, BT848_E_CONTROL);
1144                 btor(BT848_CONTROL_COMP, BT848_O_CONTROL);
1145         } else {
1146                 btand(~BT848_CONTROL_COMP, BT848_E_CONTROL);
1147                 btand(~BT848_CONTROL_COMP, BT848_O_CONTROL);
1148         }
1149         mux = bttv_muxsel(btv, input);
1150         btaor(mux<<5, ~(3<<5), BT848_IFORM);
1151         dprintk(KERN_DEBUG "bttv%d: video mux: input=%d mux=%d\n",
1152                 btv->c.nr,input,mux);
1153
1154         /* card specific hook */
1155         if(bttv_tvcards[btv->c.type].muxsel_hook)
1156                 bttv_tvcards[btv->c.type].muxsel_hook (btv, input);
1157         return 0;
1158 }
1159
1160 static char *audio_modes[] = {
1161         "audio: tuner", "audio: radio", "audio: extern",
1162         "audio: intern", "audio: mute"
1163 };
1164
1165 static int
1166 audio_mux(struct bttv *btv, int input, int mute)
1167 {
1168         int gpio_val, signal;
1169         struct v4l2_control ctrl;
1170
1171         gpio_inout(bttv_tvcards[btv->c.type].gpiomask,
1172                    bttv_tvcards[btv->c.type].gpiomask);
1173         signal = btread(BT848_DSTATUS) & BT848_DSTATUS_HLOC;
1174
1175         btv->mute = mute;
1176         btv->audio = input;
1177
1178         /* automute */
1179         mute = mute || (btv->opt_automute && !signal && !btv->radio_user);
1180
1181         if (mute)
1182                 gpio_val = bttv_tvcards[btv->c.type].gpiomute;
1183         else
1184                 gpio_val = bttv_tvcards[btv->c.type].gpiomux[input];
1185
1186         switch (btv->c.type) {
1187         case BTTV_BOARD_VOODOOTV_FM:
1188         case BTTV_BOARD_VOODOOTV_200:
1189                 gpio_val = bttv_tda9880_setnorm(btv, gpio_val);
1190                 break;
1191
1192         default:
1193                 gpio_bits(bttv_tvcards[btv->c.type].gpiomask, gpio_val);
1194         }
1195
1196         if (bttv_gpio)
1197                 bttv_gpio_tracking(btv, audio_modes[mute ? 4 : input]);
1198         if (in_interrupt())
1199                 return 0;
1200
1201         ctrl.id = V4L2_CID_AUDIO_MUTE;
1202         ctrl.value = btv->mute;
1203         bttv_call_all(btv, core, s_ctrl, &ctrl);
1204         if (btv->sd_msp34xx) {
1205                 u32 in;
1206
1207                 /* Note: the inputs tuner/radio/extern/intern are translated
1208                    to msp routings. This assumes common behavior for all msp3400
1209                    based TV cards. When this assumption fails, then the
1210                    specific MSP routing must be added to the card table.
1211                    For now this is sufficient. */
1212                 switch (input) {
1213                 case TVAUDIO_INPUT_RADIO:
1214                         in = MSP_INPUT(MSP_IN_SCART2, MSP_IN_TUNER1,
1215                                     MSP_DSP_IN_SCART, MSP_DSP_IN_SCART);
1216                         break;
1217                 case TVAUDIO_INPUT_EXTERN:
1218                         in = MSP_INPUT(MSP_IN_SCART1, MSP_IN_TUNER1,
1219                                     MSP_DSP_IN_SCART, MSP_DSP_IN_SCART);
1220                         break;
1221                 case TVAUDIO_INPUT_INTERN:
1222                         /* Yes, this is the same input as for RADIO. I doubt
1223                            if this is ever used. The only board with an INTERN
1224                            input is the BTTV_BOARD_AVERMEDIA98. I wonder how
1225                            that was tested. My guess is that the whole INTERN
1226                            input does not work. */
1227                         in = MSP_INPUT(MSP_IN_SCART2, MSP_IN_TUNER1,
1228                                     MSP_DSP_IN_SCART, MSP_DSP_IN_SCART);
1229                         break;
1230                 case TVAUDIO_INPUT_TUNER:
1231                 default:
1232                         /* This is the only card that uses TUNER2, and afaik,
1233                            is the only difference between the VOODOOTV_FM
1234                            and VOODOOTV_200 */
1235                         if (btv->c.type == BTTV_BOARD_VOODOOTV_200)
1236                                 in = MSP_INPUT(MSP_IN_SCART1, MSP_IN_TUNER2, \
1237                                         MSP_DSP_IN_TUNER, MSP_DSP_IN_TUNER);
1238                         else
1239                                 in = MSP_INPUT_DEFAULT;
1240                         break;
1241                 }
1242                 v4l2_subdev_call(btv->sd_msp34xx, audio, s_routing,
1243                                in, MSP_OUTPUT_DEFAULT, 0);
1244         }
1245         if (btv->sd_tvaudio) {
1246                 v4l2_subdev_call(btv->sd_tvaudio, audio, s_routing,
1247                                 input, 0, 0);
1248         }
1249         return 0;
1250 }
1251
1252 static inline int
1253 audio_mute(struct bttv *btv, int mute)
1254 {
1255         return audio_mux(btv, btv->audio, mute);
1256 }
1257
1258 static inline int
1259 audio_input(struct bttv *btv, int input)
1260 {
1261         return audio_mux(btv, input, btv->mute);
1262 }
1263
1264 static void
1265 bttv_crop_calc_limits(struct bttv_crop *c)
1266 {
1267         /* Scale factor min. 1:1, max. 16:1. Min. image size
1268            48 x 32. Scaled width must be a multiple of 4. */
1269
1270         if (1) {
1271                 /* For bug compatibility with VIDIOCGCAP and image
1272                    size checks in earlier driver versions. */
1273                 c->min_scaled_width = 48;
1274                 c->min_scaled_height = 32;
1275         } else {
1276                 c->min_scaled_width =
1277                         (max(48, c->rect.width >> 4) + 3) & ~3;
1278                 c->min_scaled_height =
1279                         max(32, c->rect.height >> 4);
1280         }
1281
1282         c->max_scaled_width  = c->rect.width & ~3;
1283         c->max_scaled_height = c->rect.height;
1284 }
1285
1286 static void
1287 bttv_crop_reset(struct bttv_crop *c, unsigned int norm)
1288 {
1289         c->rect = bttv_tvnorms[norm].cropcap.defrect;
1290         bttv_crop_calc_limits(c);
1291 }
1292
1293 /* Call with btv->lock down. */
1294 static int
1295 set_tvnorm(struct bttv *btv, unsigned int norm)
1296 {
1297         const struct bttv_tvnorm *tvnorm;
1298         v4l2_std_id id;
1299
1300         BUG_ON(norm >= BTTV_TVNORMS);
1301         BUG_ON(btv->tvnorm >= BTTV_TVNORMS);
1302
1303         tvnorm = &bttv_tvnorms[norm];
1304
1305         if (memcmp(&bttv_tvnorms[btv->tvnorm].cropcap, &tvnorm->cropcap,
1306                     sizeof (tvnorm->cropcap))) {
1307                 bttv_crop_reset(&btv->crop[0], norm);
1308                 btv->crop[1] = btv->crop[0]; /* current = default */
1309
1310                 if (0 == (btv->resources & VIDEO_RESOURCES)) {
1311                         btv->crop_start = tvnorm->cropcap.bounds.top
1312                                 + tvnorm->cropcap.bounds.height;
1313                 }
1314         }
1315
1316         btv->tvnorm = norm;
1317
1318         btwrite(tvnorm->adelay, BT848_ADELAY);
1319         btwrite(tvnorm->bdelay, BT848_BDELAY);
1320         btaor(tvnorm->iform,~(BT848_IFORM_NORM|BT848_IFORM_XTBOTH),
1321               BT848_IFORM);
1322         btwrite(tvnorm->vbipack, BT848_VBI_PACK_SIZE);
1323         btwrite(1, BT848_VBI_PACK_DEL);
1324         bt848A_set_timing(btv);
1325
1326         switch (btv->c.type) {
1327         case BTTV_BOARD_VOODOOTV_FM:
1328         case BTTV_BOARD_VOODOOTV_200:
1329                 bttv_tda9880_setnorm(btv, gpio_read());
1330                 break;
1331         }
1332         id = tvnorm->v4l2_id;
1333         bttv_call_all(btv, core, s_std, id);
1334
1335         return 0;
1336 }
1337
1338 /* Call with btv->lock down. */
1339 static void
1340 set_input(struct bttv *btv, unsigned int input, unsigned int norm)
1341 {
1342         unsigned long flags;
1343
1344         btv->input = input;
1345         if (irq_iswitch) {
1346                 spin_lock_irqsave(&btv->s_lock,flags);
1347                 if (btv->curr.frame_irq) {
1348                         /* active capture -> delayed input switch */
1349                         btv->new_input = input;
1350                 } else {
1351                         video_mux(btv,input);
1352                 }
1353                 spin_unlock_irqrestore(&btv->s_lock,flags);
1354         } else {
1355                 video_mux(btv,input);
1356         }
1357         audio_input(btv, (btv->tuner_type != TUNER_ABSENT && input == 0) ?
1358                          TVAUDIO_INPUT_TUNER : TVAUDIO_INPUT_EXTERN);
1359         set_tvnorm(btv, norm);
1360 }
1361
1362 static void init_irqreg(struct bttv *btv)
1363 {
1364         /* clear status */
1365         btwrite(0xfffffUL, BT848_INT_STAT);
1366
1367         if (bttv_tvcards[btv->c.type].no_video) {
1368                 /* i2c only */
1369                 btwrite(BT848_INT_I2CDONE,
1370                         BT848_INT_MASK);
1371         } else {
1372                 /* full video */
1373                 btwrite((btv->triton1)  |
1374                         (btv->gpioirq ? BT848_INT_GPINT : 0) |
1375                         BT848_INT_SCERR |
1376                         (fdsr ? BT848_INT_FDSR : 0) |
1377                         BT848_INT_RISCI | BT848_INT_OCERR |
1378                         BT848_INT_FMTCHG|BT848_INT_HLOCK|
1379                         BT848_INT_I2CDONE,
1380                         BT848_INT_MASK);
1381         }
1382 }
1383
1384 static void init_bt848(struct bttv *btv)
1385 {
1386         int val;
1387
1388         if (bttv_tvcards[btv->c.type].no_video) {
1389                 /* very basic init only */
1390                 init_irqreg(btv);
1391                 return;
1392         }
1393
1394         btwrite(0x00, BT848_CAP_CTL);
1395         btwrite(BT848_COLOR_CTL_GAMMA, BT848_COLOR_CTL);
1396         btwrite(BT848_IFORM_XTAUTO | BT848_IFORM_AUTO, BT848_IFORM);
1397
1398         /* set planar and packed mode trigger points and         */
1399         /* set rising edge of inverted GPINTR pin as irq trigger */
1400         btwrite(BT848_GPIO_DMA_CTL_PKTP_32|
1401                 BT848_GPIO_DMA_CTL_PLTP1_16|
1402                 BT848_GPIO_DMA_CTL_PLTP23_16|
1403                 BT848_GPIO_DMA_CTL_GPINTC|
1404                 BT848_GPIO_DMA_CTL_GPINTI,
1405                 BT848_GPIO_DMA_CTL);
1406
1407         val = btv->opt_chroma_agc ? BT848_SCLOOP_CAGC : 0;
1408         btwrite(val, BT848_E_SCLOOP);
1409         btwrite(val, BT848_O_SCLOOP);
1410
1411         btwrite(0x20, BT848_E_VSCALE_HI);
1412         btwrite(0x20, BT848_O_VSCALE_HI);
1413         btwrite(BT848_ADC_RESERVED | (btv->opt_adc_crush ? BT848_ADC_CRUSH : 0),
1414                 BT848_ADC);
1415
1416         btwrite(whitecrush_upper, BT848_WC_UP);
1417         btwrite(whitecrush_lower, BT848_WC_DOWN);
1418
1419         if (btv->opt_lumafilter) {
1420                 btwrite(0, BT848_E_CONTROL);
1421                 btwrite(0, BT848_O_CONTROL);
1422         } else {
1423                 btwrite(BT848_CONTROL_LDEC, BT848_E_CONTROL);
1424                 btwrite(BT848_CONTROL_LDEC, BT848_O_CONTROL);
1425         }
1426
1427         bt848_bright(btv,   btv->bright);
1428         bt848_hue(btv,      btv->hue);
1429         bt848_contrast(btv, btv->contrast);
1430         bt848_sat(btv,      btv->saturation);
1431
1432         /* interrupt */
1433         init_irqreg(btv);
1434 }
1435
1436 static void bttv_reinit_bt848(struct bttv *btv)
1437 {
1438         unsigned long flags;
1439
1440         if (bttv_verbose)
1441                 printk(KERN_INFO "bttv%d: reset, reinitialize\n",btv->c.nr);
1442         spin_lock_irqsave(&btv->s_lock,flags);
1443         btv->errors=0;
1444         bttv_set_dma(btv,0);
1445         spin_unlock_irqrestore(&btv->s_lock,flags);
1446
1447         init_bt848(btv);
1448         btv->pll.pll_current = -1;
1449         set_input(btv, btv->input, btv->tvnorm);
1450 }
1451
1452 static int bttv_g_ctrl(struct file *file, void *priv,
1453                                         struct v4l2_control *c)
1454 {
1455         struct bttv_fh *fh = priv;
1456         struct bttv *btv = fh->btv;
1457
1458         switch (c->id) {
1459         case V4L2_CID_BRIGHTNESS:
1460                 c->value = btv->bright;
1461                 break;
1462         case V4L2_CID_HUE:
1463                 c->value = btv->hue;
1464                 break;
1465         case V4L2_CID_CONTRAST:
1466                 c->value = btv->contrast;
1467                 break;
1468         case V4L2_CID_SATURATION:
1469                 c->value = btv->saturation;
1470                 break;
1471
1472         case V4L2_CID_AUDIO_MUTE:
1473         case V4L2_CID_AUDIO_VOLUME:
1474         case V4L2_CID_AUDIO_BALANCE:
1475         case V4L2_CID_AUDIO_BASS:
1476         case V4L2_CID_AUDIO_TREBLE:
1477                 bttv_call_all(btv, core, g_ctrl, c);
1478                 break;
1479
1480         case V4L2_CID_PRIVATE_CHROMA_AGC:
1481                 c->value = btv->opt_chroma_agc;
1482                 break;
1483         case V4L2_CID_PRIVATE_COMBFILTER:
1484                 c->value = btv->opt_combfilter;
1485                 break;
1486         case V4L2_CID_PRIVATE_LUMAFILTER:
1487                 c->value = btv->opt_lumafilter;
1488                 break;
1489         case V4L2_CID_PRIVATE_AUTOMUTE:
1490                 c->value = btv->opt_automute;
1491                 break;
1492         case V4L2_CID_PRIVATE_AGC_CRUSH:
1493                 c->value = btv->opt_adc_crush;
1494                 break;
1495         case V4L2_CID_PRIVATE_VCR_HACK:
1496                 c->value = btv->opt_vcr_hack;
1497                 break;
1498         case V4L2_CID_PRIVATE_WHITECRUSH_UPPER:
1499                 c->value = btv->opt_whitecrush_upper;
1500                 break;
1501         case V4L2_CID_PRIVATE_WHITECRUSH_LOWER:
1502                 c->value = btv->opt_whitecrush_lower;
1503                 break;
1504         case V4L2_CID_PRIVATE_UV_RATIO:
1505                 c->value = btv->opt_uv_ratio;
1506                 break;
1507         case V4L2_CID_PRIVATE_FULL_LUMA_RANGE:
1508                 c->value = btv->opt_full_luma_range;
1509                 break;
1510         case V4L2_CID_PRIVATE_CORING:
1511                 c->value = btv->opt_coring;
1512                 break;
1513         default:
1514                 return -EINVAL;
1515         }
1516         return 0;
1517 }
1518
1519 static int bttv_s_ctrl(struct file *file, void *f,
1520                                         struct v4l2_control *c)
1521 {
1522         int err;
1523         int val;
1524         struct bttv_fh *fh = f;
1525         struct bttv *btv = fh->btv;
1526
1527         err = v4l2_prio_check(&btv->prio, fh->prio);
1528         if (0 != err)
1529                 return err;
1530
1531         switch (c->id) {
1532         case V4L2_CID_BRIGHTNESS:
1533                 bt848_bright(btv, c->value);
1534                 break;
1535         case V4L2_CID_HUE:
1536                 bt848_hue(btv, c->value);
1537                 break;
1538         case V4L2_CID_CONTRAST:
1539                 bt848_contrast(btv, c->value);
1540                 break;
1541         case V4L2_CID_SATURATION:
1542                 bt848_sat(btv, c->value);
1543                 break;
1544         case V4L2_CID_AUDIO_MUTE:
1545                 audio_mute(btv, c->value);
1546                 /* fall through */
1547         case V4L2_CID_AUDIO_VOLUME:
1548                 if (btv->volume_gpio)
1549                         btv->volume_gpio(btv, c->value);
1550
1551                 bttv_call_all(btv, core, s_ctrl, c);
1552                 break;
1553         case V4L2_CID_AUDIO_BALANCE:
1554         case V4L2_CID_AUDIO_BASS:
1555         case V4L2_CID_AUDIO_TREBLE:
1556                 bttv_call_all(btv, core, s_ctrl, c);
1557                 break;
1558
1559         case V4L2_CID_PRIVATE_CHROMA_AGC:
1560                 btv->opt_chroma_agc = c->value;
1561                 val = btv->opt_chroma_agc ? BT848_SCLOOP_CAGC : 0;
1562                 btwrite(val, BT848_E_SCLOOP);
1563                 btwrite(val, BT848_O_SCLOOP);
1564                 break;
1565         case V4L2_CID_PRIVATE_COMBFILTER:
1566                 btv->opt_combfilter = c->value;
1567                 break;
1568         case V4L2_CID_PRIVATE_LUMAFILTER:
1569                 btv->opt_lumafilter = c->value;
1570                 if (btv->opt_lumafilter) {
1571                         btand(~BT848_CONTROL_LDEC, BT848_E_CONTROL);
1572                         btand(~BT848_CONTROL_LDEC, BT848_O_CONTROL);
1573                 } else {
1574                         btor(BT848_CONTROL_LDEC, BT848_E_CONTROL);
1575                         btor(BT848_CONTROL_LDEC, BT848_O_CONTROL);
1576                 }
1577                 break;
1578         case V4L2_CID_PRIVATE_AUTOMUTE:
1579                 btv->opt_automute = c->value;
1580                 break;
1581         case V4L2_CID_PRIVATE_AGC_CRUSH:
1582                 btv->opt_adc_crush = c->value;
1583                 btwrite(BT848_ADC_RESERVED |
1584                                 (btv->opt_adc_crush ? BT848_ADC_CRUSH : 0),
1585                                 BT848_ADC);
1586                 break;
1587         case V4L2_CID_PRIVATE_VCR_HACK:
1588                 btv->opt_vcr_hack = c->value;
1589                 break;
1590         case V4L2_CID_PRIVATE_WHITECRUSH_UPPER:
1591                 btv->opt_whitecrush_upper = c->value;
1592                 btwrite(c->value, BT848_WC_UP);
1593                 break;
1594         case V4L2_CID_PRIVATE_WHITECRUSH_LOWER:
1595                 btv->opt_whitecrush_lower = c->value;
1596                 btwrite(c->value, BT848_WC_DOWN);
1597                 break;
1598         case V4L2_CID_PRIVATE_UV_RATIO:
1599                 btv->opt_uv_ratio = c->value;
1600                 bt848_sat(btv, btv->saturation);
1601                 break;
1602         case V4L2_CID_PRIVATE_FULL_LUMA_RANGE:
1603                 btv->opt_full_luma_range = c->value;
1604                 btaor((c->value<<7), ~BT848_OFORM_RANGE, BT848_OFORM);
1605                 break;
1606         case V4L2_CID_PRIVATE_CORING:
1607                 btv->opt_coring = c->value;
1608                 btaor((c->value<<5), ~BT848_OFORM_CORE32, BT848_OFORM);
1609                 break;
1610         default:
1611                 return -EINVAL;
1612         }
1613         return 0;
1614 }
1615
1616 /* ----------------------------------------------------------------------- */
1617
1618 void bttv_gpio_tracking(struct bttv *btv, char *comment)
1619 {
1620         unsigned int outbits, data;
1621         outbits = btread(BT848_GPIO_OUT_EN);
1622         data    = btread(BT848_GPIO_DATA);
1623         printk(KERN_DEBUG "bttv%d: gpio: en=%08x, out=%08x in=%08x [%s]\n",
1624                btv->c.nr,outbits,data & outbits, data & ~outbits, comment);
1625 }
1626
1627 static void bttv_field_count(struct bttv *btv)
1628 {
1629         int need_count = 0;
1630
1631         if (btv->users)
1632                 need_count++;
1633
1634         if (need_count) {
1635                 /* start field counter */
1636                 btor(BT848_INT_VSYNC,BT848_INT_MASK);
1637         } else {
1638                 /* stop field counter */
1639                 btand(~BT848_INT_VSYNC,BT848_INT_MASK);
1640                 btv->field_count = 0;
1641         }
1642 }
1643
1644 static const struct bttv_format*
1645 format_by_fourcc(int fourcc)
1646 {
1647         unsigned int i;
1648
1649         for (i = 0; i < FORMATS; i++) {
1650                 if (-1 == formats[i].fourcc)
1651                         continue;
1652                 if (formats[i].fourcc == fourcc)
1653                         return formats+i;
1654         }
1655         return NULL;
1656 }
1657
1658 /* ----------------------------------------------------------------------- */
1659 /* misc helpers                                                            */
1660
1661 static int
1662 bttv_switch_overlay(struct bttv *btv, struct bttv_fh *fh,
1663                     struct bttv_buffer *new)
1664 {
1665         struct bttv_buffer *old;
1666         unsigned long flags;
1667         int retval = 0;
1668
1669         dprintk("switch_overlay: enter [new=%p]\n",new);
1670         if (new)
1671                 new->vb.state = VIDEOBUF_DONE;
1672         spin_lock_irqsave(&btv->s_lock,flags);
1673         old = btv->screen;
1674         btv->screen = new;
1675         btv->loop_irq |= 1;
1676         bttv_set_dma(btv, 0x03);
1677         spin_unlock_irqrestore(&btv->s_lock,flags);
1678         if (NULL != old) {
1679                 dprintk("switch_overlay: old=%p state is %d\n",old,old->vb.state);
1680                 bttv_dma_free(&fh->cap,btv, old);
1681                 kfree(old);
1682         }
1683         if (NULL == new)
1684                 free_btres_lock(btv,fh,RESOURCE_OVERLAY);
1685         dprintk("switch_overlay: done\n");
1686         return retval;
1687 }
1688
1689 /* ----------------------------------------------------------------------- */
1690 /* video4linux (1) interface                                               */
1691
1692 static int bttv_prepare_buffer(struct videobuf_queue *q,struct bttv *btv,
1693                                struct bttv_buffer *buf,
1694                                const struct bttv_format *fmt,
1695                                unsigned int width, unsigned int height,
1696                                enum v4l2_field field)
1697 {
1698         struct bttv_fh *fh = q->priv_data;
1699         int redo_dma_risc = 0;
1700         struct bttv_crop c;
1701         int norm;
1702         int rc;
1703
1704         /* check settings */
1705         if (NULL == fmt)
1706                 return -EINVAL;
1707         if (fmt->btformat == BT848_COLOR_FMT_RAW) {
1708                 width  = RAW_BPL;
1709                 height = RAW_LINES*2;
1710                 if (width*height > buf->vb.bsize)
1711                         return -EINVAL;
1712                 buf->vb.size = buf->vb.bsize;
1713
1714                 /* Make sure tvnorm and vbi_end remain consistent
1715                    until we're done. */
1716                 mutex_lock(&btv->lock);
1717
1718                 norm = btv->tvnorm;
1719
1720                 /* In this mode capturing always starts at defrect.top
1721                    (default VDELAY), ignoring cropping parameters. */
1722                 if (btv->vbi_end > bttv_tvnorms[norm].cropcap.defrect.top) {
1723                         mutex_unlock(&btv->lock);
1724                         return -EINVAL;
1725                 }
1726
1727                 mutex_unlock(&btv->lock);
1728
1729                 c.rect = bttv_tvnorms[norm].cropcap.defrect;
1730         } else {
1731                 mutex_lock(&btv->lock);
1732
1733                 norm = btv->tvnorm;
1734                 c = btv->crop[!!fh->do_crop];
1735
1736                 mutex_unlock(&btv->lock);
1737
1738                 if (width < c.min_scaled_width ||
1739                     width > c.max_scaled_width ||
1740                     height < c.min_scaled_height)
1741                         return -EINVAL;
1742
1743                 switch (field) {
1744                 case V4L2_FIELD_TOP:
1745                 case V4L2_FIELD_BOTTOM:
1746                 case V4L2_FIELD_ALTERNATE:
1747                         /* btv->crop counts frame lines. Max. scale
1748                            factor is 16:1 for frames, 8:1 for fields. */
1749                         if (height * 2 > c.max_scaled_height)
1750                                 return -EINVAL;
1751                         break;
1752
1753                 default:
1754                         if (height > c.max_scaled_height)
1755                                 return -EINVAL;
1756                         break;
1757                 }
1758
1759                 buf->vb.size = (width * height * fmt->depth) >> 3;
1760                 if (0 != buf->vb.baddr  &&  buf->vb.bsize < buf->vb.size)
1761                         return -EINVAL;
1762         }
1763
1764         /* alloc + fill struct bttv_buffer (if changed) */
1765         if (buf->vb.width != width || buf->vb.height != height ||
1766             buf->vb.field != field ||
1767             buf->tvnorm != norm || buf->fmt != fmt ||
1768             buf->crop.top != c.rect.top ||
1769             buf->crop.left != c.rect.left ||
1770             buf->crop.width != c.rect.width ||
1771             buf->crop.height != c.rect.height) {
1772                 buf->vb.width  = width;
1773                 buf->vb.height = height;
1774                 buf->vb.field  = field;
1775                 buf->tvnorm    = norm;
1776                 buf->fmt       = fmt;
1777                 buf->crop      = c.rect;
1778                 redo_dma_risc = 1;
1779         }
1780
1781         /* alloc risc memory */
1782         if (VIDEOBUF_NEEDS_INIT == buf->vb.state) {
1783                 redo_dma_risc = 1;
1784                 if (0 != (rc = videobuf_iolock(q,&buf->vb,&btv->fbuf)))
1785                         goto fail;
1786         }
1787
1788         if (redo_dma_risc)
1789                 if (0 != (rc = bttv_buffer_risc(btv,buf)))
1790                         goto fail;
1791
1792         buf->vb.state = VIDEOBUF_PREPARED;
1793         return 0;
1794
1795  fail:
1796         bttv_dma_free(q,btv,buf);
1797         return rc;
1798 }
1799
1800 static int
1801 buffer_setup(struct videobuf_queue *q, unsigned int *count, unsigned int *size)
1802 {
1803         struct bttv_fh *fh = q->priv_data;
1804
1805         *size = fh->fmt->depth*fh->width*fh->height >> 3;
1806         if (0 == *count)
1807                 *count = gbuffers;
1808         if (*size * *count > gbuffers * gbufsize)
1809                 *count = (gbuffers * gbufsize) / *size;
1810         return 0;
1811 }
1812
1813 static int
1814 buffer_prepare(struct videobuf_queue *q, struct videobuf_buffer *vb,
1815                enum v4l2_field field)
1816 {
1817         struct bttv_buffer *buf = container_of(vb,struct bttv_buffer,vb);
1818         struct bttv_fh *fh = q->priv_data;
1819
1820         return bttv_prepare_buffer(q,fh->btv, buf, fh->fmt,
1821                                    fh->width, fh->height, field);
1822 }
1823
1824 static void
1825 buffer_queue(struct videobuf_queue *q, struct videobuf_buffer *vb)
1826 {
1827         struct bttv_buffer *buf = container_of(vb,struct bttv_buffer,vb);
1828         struct bttv_fh *fh = q->priv_data;
1829         struct bttv    *btv = fh->btv;
1830
1831         buf->vb.state = VIDEOBUF_QUEUED;
1832         list_add_tail(&buf->vb.queue,&btv->capture);
1833         if (!btv->curr.frame_irq) {
1834                 btv->loop_irq |= 1;
1835                 bttv_set_dma(btv, 0x03);
1836         }
1837 }
1838
1839 static void buffer_release(struct videobuf_queue *q, struct videobuf_buffer *vb)
1840 {
1841         struct bttv_buffer *buf = container_of(vb,struct bttv_buffer,vb);
1842         struct bttv_fh *fh = q->priv_data;
1843
1844         bttv_dma_free(q,fh->btv,buf);
1845 }
1846
1847 static struct videobuf_queue_ops bttv_video_qops = {
1848         .buf_setup    = buffer_setup,
1849         .buf_prepare  = buffer_prepare,
1850         .buf_queue    = buffer_queue,
1851         .buf_release  = buffer_release,
1852 };
1853
1854 static int bttv_s_std(struct file *file, void *priv, v4l2_std_id *id)
1855 {
1856         struct bttv_fh *fh  = priv;
1857         struct bttv *btv = fh->btv;
1858         unsigned int i;
1859         int err;
1860
1861         mutex_lock(&btv->lock);
1862         err = v4l2_prio_check(&btv->prio, fh->prio);
1863         if (err)
1864                 goto err;
1865
1866         for (i = 0; i < BTTV_TVNORMS; i++)
1867                 if (*id & bttv_tvnorms[i].v4l2_id)
1868                         break;
1869         if (i == BTTV_TVNORMS) {
1870                 err = -EINVAL;
1871                 goto err;
1872         }
1873
1874         set_tvnorm(btv, i);
1875
1876 err:
1877         mutex_unlock(&btv->lock);
1878
1879         return err;
1880 }
1881
1882 static int bttv_querystd(struct file *file, void *f, v4l2_std_id *id)
1883 {
1884         struct bttv_fh *fh = f;
1885         struct bttv *btv = fh->btv;
1886
1887         if (btread(BT848_DSTATUS) & BT848_DSTATUS_NUML)
1888                 *id = V4L2_STD_625_50;
1889         else
1890                 *id = V4L2_STD_525_60;
1891         return 0;
1892 }
1893
1894 static int bttv_enum_input(struct file *file, void *priv,
1895                                         struct v4l2_input *i)
1896 {
1897         struct bttv_fh *fh = priv;
1898         struct bttv *btv = fh->btv;
1899         int rc = 0;
1900
1901         mutex_lock(&btv->lock);
1902         if (i->index >= bttv_tvcards[btv->c.type].video_inputs) {
1903                 rc = -EINVAL;
1904                 goto err;
1905         }
1906
1907         i->type     = V4L2_INPUT_TYPE_CAMERA;
1908         i->audioset = 1;
1909
1910         if (btv->tuner_type != TUNER_ABSENT && i->index == 0) {
1911                 sprintf(i->name, "Television");
1912                 i->type  = V4L2_INPUT_TYPE_TUNER;
1913                 i->tuner = 0;
1914         } else if (i->index == btv->svhs) {
1915                 sprintf(i->name, "S-Video");
1916         } else {
1917                 sprintf(i->name, "Composite%d", i->index);
1918         }
1919
1920         if (i->index == btv->input) {
1921                 __u32 dstatus = btread(BT848_DSTATUS);
1922                 if (0 == (dstatus & BT848_DSTATUS_PRES))
1923                         i->status |= V4L2_IN_ST_NO_SIGNAL;
1924                 if (0 == (dstatus & BT848_DSTATUS_HLOC))
1925                         i->status |= V4L2_IN_ST_NO_H_LOCK;
1926         }
1927
1928         i->std = BTTV_NORMS;
1929
1930 err:
1931         mutex_unlock(&btv->lock);
1932
1933         return rc;
1934 }
1935
1936 static int bttv_g_input(struct file *file, void *priv, unsigned int *i)
1937 {
1938         struct bttv_fh *fh = priv;
1939         struct bttv *btv = fh->btv;
1940
1941         mutex_lock(&btv->lock);
1942         *i = btv->input;
1943         mutex_unlock(&btv->lock);
1944
1945         return 0;
1946 }
1947
1948 static int bttv_s_input(struct file *file, void *priv, unsigned int i)
1949 {
1950         struct bttv_fh *fh  = priv;
1951         struct bttv *btv = fh->btv;
1952
1953         int err;
1954
1955         mutex_lock(&btv->lock);
1956         err = v4l2_prio_check(&btv->prio, fh->prio);
1957         if (unlikely(err))
1958                 goto err;
1959
1960         if (i > bttv_tvcards[btv->c.type].video_inputs) {
1961                 err = -EINVAL;
1962                 goto err;
1963         }
1964
1965         set_input(btv, i, btv->tvnorm);
1966
1967 err:
1968         mutex_unlock(&btv->lock);
1969         return 0;
1970 }
1971
1972 static int bttv_s_tuner(struct file *file, void *priv,
1973                                         struct v4l2_tuner *t)
1974 {
1975         struct bttv_fh *fh  = priv;
1976         struct bttv *btv = fh->btv;
1977         int err;
1978
1979         if (unlikely(0 != t->index))
1980                 return -EINVAL;
1981
1982         mutex_lock(&btv->lock);
1983         if (unlikely(btv->tuner_type == TUNER_ABSENT)) {
1984                 err = -EINVAL;
1985                 goto err;
1986         }
1987
1988         err = v4l2_prio_check(&btv->prio, fh->prio);
1989         if (unlikely(err))
1990                 goto err;
1991
1992         bttv_call_all(btv, tuner, s_tuner, t);
1993
1994         if (btv->audio_mode_gpio)
1995                 btv->audio_mode_gpio(btv, t, 1);
1996
1997 err:
1998         mutex_unlock(&btv->lock);
1999
2000         return 0;
2001 }
2002
2003 static int bttv_g_frequency(struct file *file, void *priv,
2004                                         struct v4l2_frequency *f)
2005 {
2006         struct bttv_fh *fh  = priv;
2007         struct bttv *btv = fh->btv;
2008
2009         mutex_lock(&btv->lock);
2010         f->type = btv->radio_user ? V4L2_TUNER_RADIO : V4L2_TUNER_ANALOG_TV;
2011         f->frequency = btv->freq;
2012         mutex_unlock(&btv->lock);
2013
2014         return 0;
2015 }
2016
2017 static int bttv_s_frequency(struct file *file, void *priv,
2018                                         struct v4l2_frequency *f)
2019 {
2020         struct bttv_fh *fh  = priv;
2021         struct bttv *btv = fh->btv;
2022         int err;
2023
2024         if (unlikely(f->tuner != 0))
2025                 return -EINVAL;
2026
2027         mutex_lock(&btv->lock);
2028         err = v4l2_prio_check(&btv->prio, fh->prio);
2029         if (unlikely(err))
2030                 goto err;
2031
2032         if (unlikely(f->type != (btv->radio_user
2033                 ? V4L2_TUNER_RADIO : V4L2_TUNER_ANALOG_TV))) {
2034                 err = -EINVAL;
2035                 goto err;
2036         }
2037         btv->freq = f->frequency;
2038         bttv_call_all(btv, tuner, s_frequency, f);
2039         if (btv->has_matchbox && btv->radio_user)
2040                 tea5757_set_freq(btv, btv->freq);
2041 err:
2042         mutex_unlock(&btv->lock);
2043
2044         return 0;
2045 }
2046
2047 static int bttv_log_status(struct file *file, void *f)
2048 {
2049         struct bttv_fh *fh  = f;
2050         struct bttv *btv = fh->btv;
2051
2052         printk(KERN_INFO "bttv%d: ========  START STATUS CARD #%d  ========\n",
2053                         btv->c.nr, btv->c.nr);
2054         bttv_call_all(btv, core, log_status);
2055         printk(KERN_INFO "bttv%d: ========  END STATUS CARD   #%d  ========\n",
2056                         btv->c.nr, btv->c.nr);
2057         return 0;
2058 }
2059
2060 #ifdef CONFIG_VIDEO_ADV_DEBUG
2061 static int bttv_g_register(struct file *file, void *f,
2062                                         struct v4l2_dbg_register *reg)
2063 {
2064         struct bttv_fh *fh = f;
2065         struct bttv *btv = fh->btv;
2066
2067         if (!capable(CAP_SYS_ADMIN))
2068                 return -EPERM;
2069
2070         if (!v4l2_chip_match_host(&reg->match))
2071                 return -EINVAL;
2072
2073         /* bt848 has a 12-bit register space */
2074         reg->reg &= 0xfff;
2075         reg->val = btread(reg->reg);
2076         reg->size = 1;
2077
2078         return 0;
2079 }
2080
2081 static int bttv_s_register(struct file *file, void *f,
2082                                         struct v4l2_dbg_register *reg)
2083 {
2084         struct bttv_fh *fh = f;
2085         struct bttv *btv = fh->btv;
2086
2087         if (!capable(CAP_SYS_ADMIN))
2088                 return -EPERM;
2089
2090         if (!v4l2_chip_match_host(&reg->match))
2091                 return -EINVAL;
2092
2093         /* bt848 has a 12-bit register space */
2094         reg->reg &= 0xfff;
2095         btwrite(reg->val, reg->reg);
2096
2097         return 0;
2098 }
2099 #endif
2100
2101 /* Given cropping boundaries b and the scaled width and height of a
2102    single field or frame, which must not exceed hardware limits, this
2103    function adjusts the cropping parameters c. */
2104 static void
2105 bttv_crop_adjust        (struct bttv_crop *             c,
2106                          const struct v4l2_rect *       b,
2107                          __s32                          width,
2108                          __s32                          height,
2109                          enum v4l2_field                field)
2110 {
2111         __s32 frame_height = height << !V4L2_FIELD_HAS_BOTH(field);
2112         __s32 max_left;
2113         __s32 max_top;
2114
2115         if (width < c->min_scaled_width) {
2116                 /* Max. hor. scale factor 16:1. */
2117                 c->rect.width = width * 16;
2118         } else if (width > c->max_scaled_width) {
2119                 /* Min. hor. scale factor 1:1. */
2120                 c->rect.width = width;
2121
2122                 max_left = b->left + b->width - width;
2123                 max_left = min(max_left, (__s32) MAX_HDELAY);
2124                 if (c->rect.left > max_left)
2125                         c->rect.left = max_left;
2126         }
2127
2128         if (height < c->min_scaled_height) {
2129                 /* Max. vert. scale factor 16:1, single fields 8:1. */
2130                 c->rect.height = height * 16;
2131         } else if (frame_height > c->max_scaled_height) {
2132                 /* Min. vert. scale factor 1:1.
2133                    Top and height count field lines times two. */
2134                 c->rect.height = (frame_height + 1) & ~1;
2135
2136                 max_top = b->top + b->height - c->rect.height;
2137                 if (c->rect.top > max_top)
2138                         c->rect.top = max_top;
2139         }
2140
2141         bttv_crop_calc_limits(c);
2142 }
2143
2144 /* Returns an error if scaling to a frame or single field with the given
2145    width and height is not possible with the current cropping parameters
2146    and width aligned according to width_mask. If adjust_size is TRUE the
2147    function may adjust the width and/or height instead, rounding width
2148    to (width + width_bias) & width_mask. If adjust_crop is TRUE it may
2149    also adjust the current cropping parameters to get closer to the
2150    desired image size. */
2151 static int
2152 limit_scaled_size_lock       (struct bttv_fh *               fh,
2153                          __s32 *                        width,
2154                          __s32 *                        height,
2155                          enum v4l2_field                field,
2156                          unsigned int                   width_mask,
2157                          unsigned int                   width_bias,
2158                          int                            adjust_size,
2159                          int                            adjust_crop)
2160 {
2161         struct bttv *btv = fh->btv;
2162         const struct v4l2_rect *b;
2163         struct bttv_crop *c;
2164         __s32 min_width;
2165         __s32 min_height;
2166         __s32 max_width;
2167         __s32 max_height;
2168         int rc;
2169
2170         BUG_ON((int) width_mask >= 0 ||
2171                width_bias >= (unsigned int) -width_mask);
2172
2173         /* Make sure tvnorm, vbi_end and the current cropping parameters
2174            remain consistent until we're done. */
2175         mutex_lock(&btv->lock);
2176
2177         b = &bttv_tvnorms[btv->tvnorm].cropcap.bounds;
2178
2179         /* Do crop - use current, don't - use default parameters. */
2180         c = &btv->crop[!!fh->do_crop];
2181
2182         if (fh->do_crop
2183             && adjust_size
2184             && adjust_crop
2185             && !locked_btres(btv, VIDEO_RESOURCES)) {
2186                 min_width = 48;
2187                 min_height = 32;
2188
2189                 /* We cannot scale up. When the scaled image is larger
2190                    than crop.rect we adjust the crop.rect as required
2191                    by the V4L2 spec, hence cropcap.bounds are our limit. */
2192                 max_width = min(b->width, (__s32) MAX_HACTIVE);
2193                 max_height = b->height;
2194
2195                 /* We cannot capture the same line as video and VBI data.
2196                    Note btv->vbi_end is really a minimum, see
2197                    bttv_vbi_try_fmt(). */
2198                 if (btv->vbi_end > b->top) {
2199                         max_height -= btv->vbi_end - b->top;
2200                         rc = -EBUSY;
2201                         if (min_height > max_height)
2202                                 goto fail;
2203                 }
2204         } else {
2205                 rc = -EBUSY;
2206                 if (btv->vbi_end > c->rect.top)
2207                         goto fail;
2208
2209                 min_width  = c->min_scaled_width;
2210                 min_height = c->min_scaled_height;
2211                 max_width  = c->max_scaled_width;
2212                 max_height = c->max_scaled_height;
2213
2214                 adjust_crop = 0;
2215         }
2216
2217         min_width = (min_width - width_mask - 1) & width_mask;
2218         max_width = max_width & width_mask;
2219
2220         /* Max. scale factor is 16:1 for frames, 8:1 for fields. */
2221         min_height = min_height;
2222         /* Min. scale factor is 1:1. */
2223         max_height >>= !V4L2_FIELD_HAS_BOTH(field);
2224
2225         if (adjust_size) {
2226                 *width = clamp(*width, min_width, max_width);
2227                 *height = clamp(*height, min_height, max_height);
2228
2229                 /* Round after clamping to avoid overflow. */
2230                 *width = (*width + width_bias) & width_mask;
2231
2232                 if (adjust_crop) {
2233                         bttv_crop_adjust(c, b, *width, *height, field);
2234
2235                         if (btv->vbi_end > c->rect.top) {
2236                                 /* Move the crop window out of the way. */
2237                                 c->rect.top = btv->vbi_end;
2238                         }
2239                 }
2240         } else {
2241                 rc = -EINVAL;
2242                 if (*width  < min_width ||
2243                     *height < min_height ||
2244                     *width  > max_width ||
2245                     *height > max_height ||
2246                     0 != (*width & ~width_mask))
2247                         goto fail;
2248         }
2249
2250         rc = 0; /* success */
2251
2252  fail:
2253         mutex_unlock(&btv->lock);
2254
2255         return rc;
2256 }
2257
2258 /* Returns an error if the given overlay window dimensions are not
2259    possible with the current cropping parameters. If adjust_size is
2260    TRUE the function may adjust the window width and/or height
2261    instead, however it always rounds the horizontal position and
2262    width as btcx_align() does. If adjust_crop is TRUE the function
2263    may also adjust the current cropping parameters to get closer
2264    to the desired window size. */
2265 static int
2266 verify_window_lock              (struct bttv_fh *               fh,
2267                          struct v4l2_window *           win,
2268                          int                            adjust_size,
2269                          int                            adjust_crop)
2270 {
2271         enum v4l2_field field;
2272         unsigned int width_mask;
2273         int rc;
2274
2275         if (win->w.width  < 48 || win->w.height < 32)
2276                 return -EINVAL;
2277         if (win->clipcount > 2048)
2278                 return -EINVAL;
2279
2280         field = win->field;
2281
2282         if (V4L2_FIELD_ANY == field) {
2283                 __s32 height2;
2284
2285                 mutex_lock(&fh->btv->lock);
2286                 height2 = fh->btv->crop[!!fh->do_crop].rect.height >> 1;
2287                 mutex_unlock(&fh->btv->lock);
2288                 field = (win->w.height > height2)
2289                         ? V4L2_FIELD_INTERLACED
2290                         : V4L2_FIELD_TOP;
2291         }
2292         switch (field) {
2293         case V4L2_FIELD_TOP:
2294         case V4L2_FIELD_BOTTOM:
2295         case V4L2_FIELD_INTERLACED:
2296                 break;
2297         default:
2298                 return -EINVAL;
2299         }
2300
2301         /* 4-byte alignment. */
2302         if (NULL == fh->ovfmt)
2303                 return -EINVAL;
2304         width_mask = ~0;
2305         switch (fh->ovfmt->depth) {
2306         case 8:
2307         case 24:
2308                 width_mask = ~3;
2309                 break;
2310         case 16:
2311                 width_mask = ~1;
2312                 break;
2313         case 32:
2314                 break;
2315         default:
2316                 BUG();
2317         }
2318
2319         win->w.width -= win->w.left & ~width_mask;
2320         win->w.left = (win->w.left - width_mask - 1) & width_mask;
2321
2322         rc = limit_scaled_size_lock(fh, &win->w.width, &win->w.height,
2323                                field, width_mask,
2324                                /* width_bias: round down */ 0,
2325                                adjust_size, adjust_crop);
2326         if (0 != rc)
2327                 return rc;
2328
2329         win->field = field;
2330         return 0;
2331 }
2332
2333 static int setup_window_lock(struct bttv_fh *fh, struct bttv *btv,
2334                         struct v4l2_window *win, int fixup)
2335 {
2336         struct v4l2_clip *clips = NULL;
2337         int n,size,retval = 0;
2338
2339         if (NULL == fh->ovfmt)
2340                 return -EINVAL;
2341         if (!(fh->ovfmt->flags & FORMAT_FLAGS_PACKED))
2342                 return -EINVAL;
2343         retval = verify_window_lock(fh, win,
2344                                /* adjust_size */ fixup,
2345                                /* adjust_crop */ fixup);
2346         if (0 != retval)
2347                 return retval;
2348
2349         /* copy clips  --  luckily v4l1 + v4l2 are binary
2350            compatible here ...*/
2351         n = win->clipcount;
2352         size = sizeof(*clips)*(n+4);
2353         clips = kmalloc(size,GFP_KERNEL);
2354         if (NULL == clips)
2355                 return -ENOMEM;
2356         if (n > 0) {
2357                 if (copy_from_user(clips,win->clips,sizeof(struct v4l2_clip)*n)) {
2358                         kfree(clips);
2359                         return -EFAULT;
2360                 }
2361         }
2362
2363         mutex_lock(&fh->cap.vb_lock);
2364         /* clip against screen */
2365         if (NULL != btv->fbuf.base)
2366                 n = btcx_screen_clips(btv->fbuf.fmt.width, btv->fbuf.fmt.height,
2367                                       &win->w, clips, n);
2368         btcx_sort_clips(clips,n);
2369
2370         /* 4-byte alignments */
2371         switch (fh->ovfmt->depth) {
2372         case 8:
2373         case 24:
2374                 btcx_align(&win->w, clips, n, 3);
2375                 break;
2376         case 16:
2377                 btcx_align(&win->w, clips, n, 1);
2378                 break;
2379         case 32:
2380                 /* no alignment fixups needed */
2381                 break;
2382         default:
2383                 BUG();
2384         }
2385
2386         kfree(fh->ov.clips);
2387         fh->ov.clips    = clips;
2388         fh->ov.nclips   = n;
2389
2390         fh->ov.w        = win->w;
2391         fh->ov.field    = win->field;
2392         fh->ov.setup_ok = 1;
2393
2394         /*
2395          * FIXME: btv is protected by btv->lock mutex, while btv->init
2396          *        is protected by fh->cap.vb_lock. This seems to open the
2397          *        possibility for some race situations. Maybe the better would
2398          *        be to unify those locks or to use another way to store the
2399          *        init values that will be consumed by videobuf callbacks
2400          */
2401         btv->init.ov.w.width   = win->w.width;
2402         btv->init.ov.w.height  = win->w.height;
2403         btv->init.ov.field     = win->field;
2404
2405         /* update overlay if needed */
2406         retval = 0;
2407         if (check_btres(fh, RESOURCE_OVERLAY)) {
2408                 struct bttv_buffer *new;
2409
2410                 new = videobuf_sg_alloc(sizeof(*new));
2411                 new->crop = btv->crop[!!fh->do_crop].rect;
2412                 bttv_overlay_risc(btv, &fh->ov, fh->ovfmt, new);
2413                 retval = bttv_switch_overlay(btv,fh,new);
2414         }
2415         mutex_unlock(&fh->cap.vb_lock);
2416         return retval;
2417 }
2418
2419 /* ----------------------------------------------------------------------- */
2420
2421 static struct videobuf_queue* bttv_queue(struct bttv_fh *fh)
2422 {
2423         struct videobuf_queue* q = NULL;
2424
2425         switch (fh->type) {
2426         case V4L2_BUF_TYPE_VIDEO_CAPTURE:
2427                 q = &fh->cap;
2428                 break;
2429         case V4L2_BUF_TYPE_VBI_CAPTURE:
2430                 q = &fh->vbi;
2431                 break;
2432         default:
2433                 BUG();
2434         }
2435         return q;
2436 }
2437
2438 static int bttv_resource(struct bttv_fh *fh)
2439 {
2440         int res = 0;
2441
2442         switch (fh->type) {
2443         case V4L2_BUF_TYPE_VIDEO_CAPTURE:
2444                 res = RESOURCE_VIDEO_STREAM;
2445                 break;
2446         case V4L2_BUF_TYPE_VBI_CAPTURE:
2447                 res = RESOURCE_VBI;
2448                 break;
2449         default:
2450                 BUG();
2451         }
2452         return res;
2453 }
2454
2455 static int bttv_switch_type(struct bttv_fh *fh, enum v4l2_buf_type type)
2456 {
2457         struct videobuf_queue *q = bttv_queue(fh);
2458         int res = bttv_resource(fh);
2459
2460         if (check_btres(fh,res))
2461                 return -EBUSY;
2462         if (videobuf_queue_is_busy(q))
2463                 return -EBUSY;
2464         fh->type = type;
2465         return 0;
2466 }
2467
2468 static void
2469 pix_format_set_size     (struct v4l2_pix_format *       f,
2470                          const struct bttv_format *     fmt,
2471                          unsigned int                   width,
2472                          unsigned int                   height)
2473 {
2474         f->width = width;
2475         f->height = height;
2476
2477         if (fmt->flags & FORMAT_FLAGS_PLANAR) {
2478                 f->bytesperline = width; /* Y plane */
2479                 f->sizeimage = (width * height * fmt->depth) >> 3;
2480         } else {
2481                 f->bytesperline = (width * fmt->depth) >> 3;
2482                 f->sizeimage = height * f->bytesperline;
2483         }
2484 }
2485
2486 static int bttv_g_fmt_vid_cap(struct file *file, void *priv,
2487                                         struct v4l2_format *f)
2488 {
2489         struct bttv_fh *fh  = priv;
2490
2491         pix_format_set_size(&f->fmt.pix, fh->fmt,
2492                                 fh->width, fh->height);
2493         f->fmt.pix.field        = fh->cap.field;
2494         f->fmt.pix.pixelformat  = fh->fmt->fourcc;
2495
2496         return 0;
2497 }
2498
2499 static int bttv_g_fmt_vid_overlay(struct file *file, void *priv,
2500                                         struct v4l2_format *f)
2501 {
2502         struct bttv_fh *fh  = priv;
2503
2504         f->fmt.win.w     = fh->ov.w;
2505         f->fmt.win.field = fh->ov.field;
2506
2507         return 0;
2508 }
2509
2510 static int bttv_try_fmt_vid_cap(struct file *file, void *priv,
2511                                                 struct v4l2_format *f)
2512 {
2513         const struct bttv_format *fmt;
2514         struct bttv_fh *fh = priv;
2515         struct bttv *btv = fh->btv;
2516         enum v4l2_field field;
2517         __s32 width, height;
2518         int rc;
2519
2520         fmt = format_by_fourcc(f->fmt.pix.pixelformat);
2521         if (NULL == fmt)
2522                 return -EINVAL;
2523
2524         field = f->fmt.pix.field;
2525
2526         if (V4L2_FIELD_ANY == field) {
2527                 __s32 height2;
2528
2529                 mutex_lock(&btv->lock);
2530                 height2 = btv->crop[!!fh->do_crop].rect.height >> 1;
2531                 mutex_unlock(&btv->lock);
2532                 field = (f->fmt.pix.height > height2)
2533                         ? V4L2_FIELD_INTERLACED
2534                         : V4L2_FIELD_BOTTOM;
2535         }
2536
2537         if (V4L2_FIELD_SEQ_BT == field)
2538                 field = V4L2_FIELD_SEQ_TB;
2539
2540         switch (field) {
2541         case V4L2_FIELD_TOP:
2542         case V4L2_FIELD_BOTTOM:
2543         case V4L2_FIELD_ALTERNATE:
2544         case V4L2_FIELD_INTERLACED:
2545                 break;
2546         case V4L2_FIELD_SEQ_TB:
2547                 if (fmt->flags & FORMAT_FLAGS_PLANAR)
2548                         return -EINVAL;
2549                 break;
2550         default:
2551                 return -EINVAL;
2552         }
2553
2554         width = f->fmt.pix.width;
2555         height = f->fmt.pix.height;
2556
2557         rc = limit_scaled_size_lock(fh, &width, &height, field,
2558                                /* width_mask: 4 pixels */ ~3,
2559                                /* width_bias: nearest */ 2,
2560                                /* adjust_size */ 1,
2561                                /* adjust_crop */ 0);
2562         if (0 != rc)
2563                 return rc;
2564
2565         /* update data for the application */
2566         f->fmt.pix.field = field;
2567         pix_format_set_size(&f->fmt.pix, fmt, width, height);
2568
2569         return 0;
2570 }
2571
2572 static int bttv_try_fmt_vid_overlay(struct file *file, void *priv,
2573                                                 struct v4l2_format *f)
2574 {
2575         struct bttv_fh *fh = priv;
2576
2577         return verify_window_lock(fh, &f->fmt.win,
2578                         /* adjust_size */ 1,
2579                         /* adjust_crop */ 0);
2580 }
2581
2582 static int bttv_s_fmt_vid_cap(struct file *file, void *priv,
2583                                 struct v4l2_format *f)
2584 {
2585         int retval;
2586         const struct bttv_format *fmt;
2587         struct bttv_fh *fh = priv;
2588         struct bttv *btv = fh->btv;
2589         __s32 width, height;
2590         enum v4l2_field field;
2591
2592         retval = bttv_switch_type(fh, f->type);
2593         if (0 != retval)
2594                 return retval;
2595
2596         retval = bttv_try_fmt_vid_cap(file, priv, f);
2597         if (0 != retval)
2598                 return retval;
2599
2600         width = f->fmt.pix.width;
2601         height = f->fmt.pix.height;
2602         field = f->fmt.pix.field;
2603
2604         retval = limit_scaled_size_lock(fh, &width, &height, f->fmt.pix.field,
2605                                /* width_mask: 4 pixels */ ~3,
2606                                /* width_bias: nearest */ 2,
2607                                /* adjust_size */ 1,
2608                                /* adjust_crop */ 1);
2609         if (0 != retval)
2610                 return retval;
2611
2612         f->fmt.pix.field = field;
2613
2614         fmt = format_by_fourcc(f->fmt.pix.pixelformat);
2615
2616         /* update our state informations */
2617         mutex_lock(&fh->cap.vb_lock);
2618         fh->fmt              = fmt;
2619         fh->cap.field        = f->fmt.pix.field;
2620         fh->cap.last         = V4L2_FIELD_NONE;
2621         fh->width            = f->fmt.pix.width;
2622         fh->height           = f->fmt.pix.height;
2623         btv->init.fmt        = fmt;
2624         btv->init.width      = f->fmt.pix.width;
2625         btv->init.height     = f->fmt.pix.height;
2626         mutex_unlock(&fh->cap.vb_lock);
2627
2628         return 0;
2629 }
2630
2631 static int bttv_s_fmt_vid_overlay(struct file *file, void *priv,
2632                                 struct v4l2_format *f)
2633 {
2634         struct bttv_fh *fh = priv;
2635         struct bttv *btv = fh->btv;
2636
2637         if (no_overlay > 0) {
2638                 printk(KERN_ERR "V4L2_BUF_TYPE_VIDEO_OVERLAY: no_overlay\n");
2639                 return -EINVAL;
2640         }
2641
2642         return setup_window_lock(fh, btv, &f->fmt.win, 1);
2643 }
2644
2645 #ifdef CONFIG_VIDEO_V4L1_COMPAT
2646 static int vidiocgmbuf(struct file *file, void *priv, struct video_mbuf *mbuf)
2647 {
2648         int retval;
2649         unsigned int i;
2650         struct bttv_fh *fh = priv;
2651
2652         mutex_lock(&fh->cap.vb_lock);
2653         retval = __videobuf_mmap_setup(&fh->cap, gbuffers, gbufsize,
2654                                      V4L2_MEMORY_MMAP);
2655         if (retval < 0) {
2656                 mutex_unlock(&fh->cap.vb_lock);
2657                 return retval;
2658         }
2659
2660         gbuffers = retval;
2661         memset(mbuf, 0, sizeof(*mbuf));
2662         mbuf->frames = gbuffers;
2663         mbuf->size   = gbuffers * gbufsize;
2664
2665         for (i = 0; i < gbuffers; i++)
2666                 mbuf->offsets[i] = i * gbufsize;
2667
2668         mutex_unlock(&fh->cap.vb_lock);
2669         return 0;
2670 }
2671 #endif
2672
2673 static int bttv_querycap(struct file *file, void  *priv,
2674                                 struct v4l2_capability *cap)
2675 {
2676         struct bttv_fh *fh = priv;
2677         struct bttv *btv = fh->btv;
2678
2679         if (0 == v4l2)
2680                 return -EINVAL;
2681
2682         strlcpy(cap->driver, "bttv", sizeof(cap->driver));
2683         strlcpy(cap->card, btv->video_dev->name, sizeof(cap->card));
2684         snprintf(cap->bus_info, sizeof(cap->bus_info),
2685                  "PCI:%s", pci_name(btv->c.pci));
2686         cap->version = BTTV_VERSION_CODE;
2687         cap->capabilities =
2688                 V4L2_CAP_VIDEO_CAPTURE |
2689                 V4L2_CAP_VBI_CAPTURE |
2690                 V4L2_CAP_READWRITE |
2691                 V4L2_CAP_STREAMING;
2692         if (no_overlay <= 0)
2693                 cap->capabilities |= V4L2_CAP_VIDEO_OVERLAY;
2694
2695         /*
2696          * No need to lock here: those vars are initialized during board
2697          * probe and remains untouched during the rest of the driver lifecycle
2698          */
2699         if (btv->has_saa6588)
2700                 cap->capabilities |= V4L2_CAP_RDS_CAPTURE;
2701         if (btv->tuner_type != TUNER_ABSENT)
2702                 cap->capabilities |= V4L2_CAP_TUNER;
2703         return 0;
2704 }
2705
2706 static int bttv_enum_fmt_cap_ovr(struct v4l2_fmtdesc *f)
2707 {
2708         int index = -1, i;
2709
2710         for (i = 0; i < FORMATS; i++) {
2711                 if (formats[i].fourcc != -1)
2712                         index++;
2713                 if ((unsigned int)index == f->index)
2714                         break;
2715         }
2716         if (FORMATS == i)
2717                 return -EINVAL;
2718
2719         f->pixelformat = formats[i].fourcc;
2720         strlcpy(f->description, formats[i].name, sizeof(f->description));
2721
2722         return i;
2723 }
2724
2725 static int bttv_enum_fmt_vid_cap(struct file *file, void  *priv,
2726                                 struct v4l2_fmtdesc *f)
2727 {
2728         int rc = bttv_enum_fmt_cap_ovr(f);
2729
2730         if (rc < 0)
2731                 return rc;
2732
2733         return 0;
2734 }
2735
2736 static int bttv_enum_fmt_vid_overlay(struct file *file, void  *priv,
2737                                         struct v4l2_fmtdesc *f)
2738 {
2739         int rc;
2740
2741         if (no_overlay > 0) {
2742                 printk(KERN_ERR "V4L2_BUF_TYPE_VIDEO_OVERLAY: no_overlay\n");
2743                 return -EINVAL;
2744         }
2745
2746         rc = bttv_enum_fmt_cap_ovr(f);
2747
2748         if (rc < 0)
2749                 return rc;
2750
2751         if (!(formats[rc].flags & FORMAT_FLAGS_PACKED))
2752                 return -EINVAL;
2753
2754         return 0;
2755 }
2756
2757 static int bttv_g_fbuf(struct file *file, void *f,
2758                                 struct v4l2_framebuffer *fb)
2759 {
2760         struct bttv_fh *fh = f;
2761         struct bttv *btv = fh->btv;
2762
2763         *fb = btv->fbuf;
2764         fb->capability = V4L2_FBUF_CAP_LIST_CLIPPING;
2765         if (fh->ovfmt)
2766                 fb->fmt.pixelformat  = fh->ovfmt->fourcc;
2767         return 0;
2768 }
2769
2770 static int bttv_overlay(struct file *file, void *f, unsigned int on)
2771 {
2772         struct bttv_fh *fh = f;
2773         struct bttv *btv = fh->btv;
2774         struct bttv_buffer *new;
2775         int retval = 0;
2776
2777         if (on) {
2778                 mutex_lock(&fh->cap.vb_lock);
2779                 /* verify args */
2780                 if (unlikely(!btv->fbuf.base)) {
2781                         mutex_unlock(&fh->cap.vb_lock);
2782                         return -EINVAL;
2783                 }
2784                 if (unlikely(!fh->ov.setup_ok)) {
2785                         dprintk("bttv%d: overlay: !setup_ok\n", btv->c.nr);
2786                         retval = -EINVAL;
2787                 }
2788                 if (retval)
2789                         return retval;
2790                 mutex_unlock(&fh->cap.vb_lock);
2791         }
2792
2793         if (!check_alloc_btres_lock(btv, fh, RESOURCE_OVERLAY))
2794                 return -EBUSY;
2795
2796         mutex_lock(&fh->cap.vb_lock);
2797         if (on) {
2798                 fh->ov.tvnorm = btv->tvnorm;
2799                 new = videobuf_sg_alloc(sizeof(*new));
2800                 new->crop = btv->crop[!!fh->do_crop].rect;
2801                 bttv_overlay_risc(btv, &fh->ov, fh->ovfmt, new);
2802         } else {
2803                 new = NULL;
2804         }
2805
2806         /* switch over */
2807         retval = bttv_switch_overlay(btv, fh, new);
2808         mutex_unlock(&fh->cap.vb_lock);
2809         return retval;
2810 }
2811
2812 static int bttv_s_fbuf(struct file *file, void *f,
2813                                 struct v4l2_framebuffer *fb)
2814 {
2815         struct bttv_fh *fh = f;
2816         struct bttv *btv = fh->btv;
2817         const struct bttv_format *fmt;
2818         int retval;
2819
2820         if (!capable(CAP_SYS_ADMIN) &&
2821                 !capable(CAP_SYS_RAWIO))
2822                 return -EPERM;
2823
2824         /* check args */
2825         fmt = format_by_fourcc(fb->fmt.pixelformat);
2826         if (NULL == fmt)
2827                 return -EINVAL;
2828         if (0 == (fmt->flags & FORMAT_FLAGS_PACKED))
2829                 return -EINVAL;
2830
2831         retval = -EINVAL;
2832         if (fb->flags & V4L2_FBUF_FLAG_OVERLAY) {
2833                 __s32 width = fb->fmt.width;
2834                 __s32 height = fb->fmt.height;
2835
2836                 retval = limit_scaled_size_lock(fh, &width, &height,
2837                                            V4L2_FIELD_INTERLACED,
2838                                            /* width_mask */ ~3,
2839                                            /* width_bias */ 2,
2840                                            /* adjust_size */ 0,
2841                                            /* adjust_crop */ 0);
2842                 if (0 != retval)
2843                         return retval;
2844         }
2845
2846         /* ok, accept it */
2847         mutex_lock(&fh->cap.vb_lock);
2848         btv->fbuf.base       = fb->base;
2849         btv->fbuf.fmt.width  = fb->fmt.width;
2850         btv->fbuf.fmt.height = fb->fmt.height;
2851         if (0 != fb->fmt.bytesperline)
2852                 btv->fbuf.fmt.bytesperline = fb->fmt.bytesperline;
2853         else
2854                 btv->fbuf.fmt.bytesperline = btv->fbuf.fmt.width*fmt->depth/8;
2855
2856         retval = 0;
2857         fh->ovfmt = fmt;
2858         btv->init.ovfmt = fmt;
2859         if (fb->flags & V4L2_FBUF_FLAG_OVERLAY) {
2860                 fh->ov.w.left   = 0;
2861                 fh->ov.w.top    = 0;
2862                 fh->ov.w.width  = fb->fmt.width;
2863                 fh->ov.w.height = fb->fmt.height;
2864                 btv->init.ov.w.width  = fb->fmt.width;
2865                 btv->init.ov.w.height = fb->fmt.height;
2866                         kfree(fh->ov.clips);
2867                 fh->ov.clips = NULL;
2868                 fh->ov.nclips = 0;
2869
2870                 if (check_btres(fh, RESOURCE_OVERLAY)) {
2871                         struct bttv_buffer *new;
2872
2873                         new = videobuf_sg_alloc(sizeof(*new));
2874                         new->crop = btv->crop[!!fh->do_crop].rect;
2875                         bttv_overlay_risc(btv, &fh->ov, fh->ovfmt, new);
2876                         retval = bttv_switch_overlay(btv, fh, new);
2877                 }
2878         }
2879         mutex_unlock(&fh->cap.vb_lock);
2880         return retval;
2881 }
2882
2883 static int bttv_reqbufs(struct file *file, void *priv,
2884                                 struct v4l2_requestbuffers *p)
2885 {
2886         struct bttv_fh *fh = priv;
2887         return videobuf_reqbufs(bttv_queue(fh), p);
2888 }
2889
2890 static int bttv_querybuf(struct file *file, void *priv,
2891                                 struct v4l2_buffer *b)
2892 {
2893         struct bttv_fh *fh = priv;
2894         return videobuf_querybuf(bttv_queue(fh), b);
2895 }
2896
2897 static int bttv_qbuf(struct file *file, void *priv, struct v4l2_buffer *b)
2898 {
2899         struct bttv_fh *fh = priv;
2900         struct bttv *btv = fh->btv;
2901         int res = bttv_resource(fh);
2902
2903         if (!check_alloc_btres_lock(btv, fh, res))
2904                 return -EBUSY;
2905
2906         return videobuf_qbuf(bttv_queue(fh), b);
2907 }
2908
2909 static int bttv_dqbuf(struct file *file, void *priv, struct v4l2_buffer *b)
2910 {
2911         struct bttv_fh *fh = priv;
2912         return videobuf_dqbuf(bttv_queue(fh), b,
2913                         file->f_flags & O_NONBLOCK);
2914 }
2915
2916 static int bttv_streamon(struct file *file, void *priv,
2917                                         enum v4l2_buf_type type)
2918 {
2919         struct bttv_fh *fh = priv;
2920         struct bttv *btv = fh->btv;
2921         int res = bttv_resource(fh);
2922
2923         if (!check_alloc_btres_lock(btv, fh, res))
2924                 return -EBUSY;
2925         return videobuf_streamon(bttv_queue(fh));
2926 }
2927
2928
2929 static int bttv_streamoff(struct file *file, void *priv,
2930                                         enum v4l2_buf_type type)
2931 {
2932         struct bttv_fh *fh = priv;
2933         struct bttv *btv = fh->btv;
2934         int retval;
2935         int res = bttv_resource(fh);
2936
2937
2938         retval = videobuf_streamoff(bttv_queue(fh));
2939         if (retval < 0)
2940                 return retval;
2941         free_btres_lock(btv, fh, res);
2942         return 0;
2943 }
2944
2945 static int bttv_queryctrl(struct file *file, void *priv,
2946                                         struct v4l2_queryctrl *c)
2947 {
2948         struct bttv_fh *fh = priv;
2949         struct bttv *btv = fh->btv;
2950         const struct v4l2_queryctrl *ctrl;
2951
2952         if ((c->id <  V4L2_CID_BASE ||
2953              c->id >= V4L2_CID_LASTP1) &&
2954             (c->id <  V4L2_CID_PRIVATE_BASE ||
2955              c->id >= V4L2_CID_PRIVATE_LASTP1))
2956                 return -EINVAL;
2957
2958         mutex_lock(&btv->lock);
2959         if (!btv->volume_gpio && (c->id == V4L2_CID_AUDIO_VOLUME))
2960                 *c = no_ctl;
2961         else {
2962                 ctrl = ctrl_by_id(c->id);
2963
2964                 *c = (NULL != ctrl) ? *ctrl : no_ctl;
2965         }
2966         mutex_unlock(&btv->lock);
2967
2968         return 0;
2969 }
2970
2971 static int bttv_g_parm(struct file *file, void *f,
2972                                 struct v4l2_streamparm *parm)
2973 {
2974         struct bttv_fh *fh = f;
2975         struct bttv *btv = fh->btv;
2976
2977         mutex_lock(&btv->lock);
2978         v4l2_video_std_frame_period(bttv_tvnorms[btv->tvnorm].v4l2_id,
2979                                     &parm->parm.capture.timeperframe);
2980         mutex_unlock(&btv->lock);
2981
2982         return 0;
2983 }
2984
2985 static int bttv_g_tuner(struct file *file, void *priv,
2986                                 struct v4l2_tuner *t)
2987 {
2988         struct bttv_fh *fh = priv;
2989         struct bttv *btv = fh->btv;
2990
2991         if (btv->tuner_type == TUNER_ABSENT)
2992                 return -EINVAL;
2993         if (0 != t->index)
2994                 return -EINVAL;
2995
2996         mutex_lock(&btv->lock);
2997         t->rxsubchans = V4L2_TUNER_SUB_MONO;
2998         bttv_call_all(btv, tuner, g_tuner, t);
2999         strcpy(t->name, "Television");
3000         t->capability = V4L2_TUNER_CAP_NORM;
3001         t->type       = V4L2_TUNER_ANALOG_TV;
3002         if (btread(BT848_DSTATUS)&BT848_DSTATUS_HLOC)
3003                 t->signal = 0xffff;
3004
3005         if (btv->audio_mode_gpio)
3006                 btv->audio_mode_gpio(btv, t, 0);
3007
3008         mutex_unlock(&btv->lock);
3009         return 0;
3010 }
3011
3012 static int bttv_g_priority(struct file *file, void *f, enum v4l2_priority *p)
3013 {
3014         struct bttv_fh *fh = f;
3015         struct bttv *btv = fh->btv;
3016
3017         mutex_lock(&btv->lock);
3018         *p = v4l2_prio_max(&btv->prio);
3019         mutex_unlock(&btv->lock);
3020
3021         return 0;
3022 }
3023
3024 static int bttv_s_priority(struct file *file, void *f,
3025                                         enum v4l2_priority prio)
3026 {
3027         struct bttv_fh *fh = f;
3028         struct bttv *btv = fh->btv;
3029         int     rc;
3030
3031         mutex_lock(&btv->lock);
3032         rc = v4l2_prio_change(&btv->prio, &fh->prio, prio);
3033         mutex_unlock(&btv->lock);
3034
3035         return rc;
3036 }
3037
3038 static int bttv_cropcap(struct file *file, void *priv,
3039                                 struct v4l2_cropcap *cap)
3040 {
3041         struct bttv_fh *fh = priv;
3042         struct bttv *btv = fh->btv;
3043
3044         if (cap->type != V4L2_BUF_TYPE_VIDEO_CAPTURE &&
3045             cap->type != V4L2_BUF_TYPE_VIDEO_OVERLAY)
3046                 return -EINVAL;
3047
3048         mutex_lock(&btv->lock);
3049         *cap = bttv_tvnorms[btv->tvnorm].cropcap;
3050         mutex_unlock(&btv->lock);
3051
3052         return 0;
3053 }
3054
3055 static int bttv_g_crop(struct file *file, void *f, struct v4l2_crop *crop)
3056 {
3057         struct bttv_fh *fh = f;
3058         struct bttv *btv = fh->btv;
3059
3060         if (crop->type != V4L2_BUF_TYPE_VIDEO_CAPTURE &&
3061             crop->type != V4L2_BUF_TYPE_VIDEO_OVERLAY)
3062                 return -EINVAL;
3063
3064         /* No fh->do_crop = 1; because btv->crop[1] may be
3065            inconsistent with fh->width or fh->height and apps
3066            do not expect a change here. */
3067
3068         mutex_lock(&btv->lock);
3069         crop->c = btv->crop[!!fh->do_crop].rect;
3070         mutex_unlock(&btv->lock);
3071
3072         return 0;
3073 }
3074
3075 static int bttv_s_crop(struct file *file, void *f, struct v4l2_crop *crop)
3076 {
3077         struct bttv_fh *fh = f;
3078         struct bttv *btv = fh->btv;
3079         const struct v4l2_rect *b;
3080         int retval;
3081         struct bttv_crop c;
3082         __s32 b_left;
3083         __s32 b_top;
3084         __s32 b_right;
3085         __s32 b_bottom;
3086
3087         if (crop->type != V4L2_BUF_TYPE_VIDEO_CAPTURE &&
3088             crop->type != V4L2_BUF_TYPE_VIDEO_OVERLAY)
3089                 return -EINVAL;
3090
3091         /* Make sure tvnorm, vbi_end and the current cropping
3092            parameters remain consistent until we're done. Note
3093            read() may change vbi_end in check_alloc_btres_lock(). */
3094         mutex_lock(&btv->lock);
3095         retval = v4l2_prio_check(&btv->prio, fh->prio);
3096         if (0 != retval) {
3097                 mutex_unlock(&btv->lock);
3098                 return retval;
3099         }
3100
3101         retval = -EBUSY;
3102
3103         if (locked_btres(fh->btv, VIDEO_RESOURCES)) {
3104                 mutex_unlock(&btv->lock);
3105                 return retval;
3106         }
3107
3108         b = &bttv_tvnorms[btv->tvnorm].cropcap.bounds;
3109
3110         b_left = b->left;
3111         b_right = b_left + b->width;
3112         b_bottom = b->top + b->height;
3113
3114         b_top = max(b->top, btv->vbi_end);
3115         if (b_top + 32 >= b_bottom) {
3116                 mutex_unlock(&btv->lock);
3117                 return retval;
3118         }
3119
3120         /* Min. scaled size 48 x 32. */
3121         c.rect.left = clamp(crop->c.left, b_left, b_right - 48);
3122         c.rect.left = min(c.rect.left, (__s32) MAX_HDELAY);
312