V4L/DVB (8125): This driver adds support for the Sensoray 2255 devices.
[linux-2.6] / drivers / media / video / zoran_driver.c
1 /*
2  * Zoran zr36057/zr36067 PCI controller driver, for the
3  * Pinnacle/Miro DC10/DC10+/DC30/DC30+, Iomega Buz, Linux
4  * Media Labs LML33/LML33R10.
5  *
6  * Copyright (C) 2000 Serguei Miridonov <mirsev@cicese.mx>
7  *
8  * Changes for BUZ by Wolfgang Scherr <scherr@net4you.net>
9  *
10  * Changes for DC10/DC30 by Laurent Pinchart <laurent.pinchart@skynet.be>
11  *
12  * Changes for LML33R10 by Maxim Yevtyushkin <max@linuxmedialabs.com>
13  *
14  * Changes for videodev2/v4l2 by Ronald Bultje <rbultje@ronald.bitfreak.net>
15  *
16  * Based on
17  *
18  * Miro DC10 driver
19  * Copyright (C) 1999 Wolfgang Scherr <scherr@net4you.net>
20  *
21  * Iomega Buz driver version 1.0
22  * Copyright (C) 1999 Rainer Johanni <Rainer@Johanni.de>
23  *
24  * buz.0.0.3
25  * Copyright (C) 1998 Dave Perks <dperks@ibm.net>
26  *
27  * bttv - Bt848 frame grabber driver
28  * Copyright (C) 1996,97,98 Ralph  Metzler (rjkm@thp.uni-koeln.de)
29  *                        & Marcus Metzler (mocm@thp.uni-koeln.de)
30  *
31  *
32  * This program is free software; you can redistribute it and/or modify
33  * it under the terms of the GNU General Public License as published by
34  * the Free Software Foundation; either version 2 of the License, or
35  * (at your option) any later version.
36  *
37  * This program is distributed in the hope that it will be useful,
38  * but WITHOUT ANY WARRANTY; without even the implied warranty of
39  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
40  * GNU General Public License for more details.
41  *
42  * You should have received a copy of the GNU General Public License
43  * along with this program; if not, write to the Free Software
44  * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
45  */
46
47 #include <linux/version.h>
48 #include <linux/init.h>
49 #include <linux/module.h>
50 #include <linux/delay.h>
51 #include <linux/slab.h>
52 #include <linux/pci.h>
53 #include <linux/vmalloc.h>
54 #include <linux/wait.h>
55
56 #include <linux/interrupt.h>
57 #include <linux/i2c.h>
58 #include <linux/i2c-algo-bit.h>
59
60 #include <linux/spinlock.h>
61 #define     MAP_NR(x)       virt_to_page(x)
62 #define     ZORAN_VID_TYPE  ( \
63                                 VID_TYPE_CAPTURE | \
64                                 VID_TYPE_OVERLAY | \
65                                 VID_TYPE_CLIPPING | \
66                                 VID_TYPE_FRAMERAM | \
67                                 VID_TYPE_SCALES | \
68                                 VID_TYPE_MJPEG_DECODER | \
69                                 VID_TYPE_MJPEG_ENCODER \
70                              )
71
72 #include <linux/videodev.h>
73 #include <media/v4l2-common.h>
74 #include "videocodec.h"
75
76 #include <asm/byteorder.h>
77 #include <asm/io.h>
78 #include <asm/uaccess.h>
79 #include <linux/proc_fs.h>
80
81 #include <linux/video_decoder.h>
82 #include <linux/video_encoder.h>
83 #include <linux/mutex.h>
84 #include "zoran.h"
85 #include "zoran_device.h"
86 #include "zoran_card.h"
87
88         /* we declare some card type definitions here, they mean
89          * the same as the v4l1 ZORAN_VID_TYPE above, except it's v4l2 */
90 #define ZORAN_V4L2_VID_FLAGS ( \
91                                 V4L2_CAP_STREAMING |\
92                                 V4L2_CAP_VIDEO_CAPTURE |\
93                                 V4L2_CAP_VIDEO_OUTPUT |\
94                                 V4L2_CAP_VIDEO_OVERLAY \
95                               )
96
97
98 #if defined(CONFIG_VIDEO_V4L1_COMPAT)
99 #define ZFMT(pal, fcc, cs) \
100         .palette = (pal), .fourcc = (fcc), .colorspace = (cs)
101 #else
102 #define ZFMT(pal, fcc, cs) \
103         .fourcc = (fcc), .colorspace = (cs)
104 #endif
105
106 const struct zoran_format zoran_formats[] = {
107         {
108                 .name = "15-bit RGB LE",
109                 ZFMT(VIDEO_PALETTE_RGB555,
110                      V4L2_PIX_FMT_RGB555, V4L2_COLORSPACE_SRGB),
111                 .depth = 15,
112                 .flags = ZORAN_FORMAT_CAPTURE |
113                          ZORAN_FORMAT_OVERLAY,
114                 .vfespfr = ZR36057_VFESPFR_RGB555|ZR36057_VFESPFR_ErrDif|
115                            ZR36057_VFESPFR_LittleEndian,
116         }, {
117                 .name = "15-bit RGB BE",
118                 ZFMT(-1,
119                      V4L2_PIX_FMT_RGB555X, V4L2_COLORSPACE_SRGB),
120                 .depth = 15,
121                 .flags = ZORAN_FORMAT_CAPTURE |
122                          ZORAN_FORMAT_OVERLAY,
123                 .vfespfr = ZR36057_VFESPFR_RGB555|ZR36057_VFESPFR_ErrDif,
124         }, {
125                 .name = "16-bit RGB LE",
126                 ZFMT(VIDEO_PALETTE_RGB565,
127                      V4L2_PIX_FMT_RGB565, V4L2_COLORSPACE_SRGB),
128                 .depth = 16,
129                 .flags = ZORAN_FORMAT_CAPTURE |
130                          ZORAN_FORMAT_OVERLAY,
131                 .vfespfr = ZR36057_VFESPFR_RGB565|ZR36057_VFESPFR_ErrDif|
132                            ZR36057_VFESPFR_LittleEndian,
133         }, {
134                 .name = "16-bit RGB BE",
135                 ZFMT(-1,
136                      V4L2_PIX_FMT_RGB565, V4L2_COLORSPACE_SRGB),
137                 .depth = 16,
138                 .flags = ZORAN_FORMAT_CAPTURE |
139                          ZORAN_FORMAT_OVERLAY,
140                 .vfespfr = ZR36057_VFESPFR_RGB565|ZR36057_VFESPFR_ErrDif,
141         }, {
142                 .name = "24-bit RGB",
143                 ZFMT(VIDEO_PALETTE_RGB24,
144                      V4L2_PIX_FMT_BGR24, V4L2_COLORSPACE_SRGB),
145                 .depth = 24,
146                 .flags = ZORAN_FORMAT_CAPTURE |
147                          ZORAN_FORMAT_OVERLAY,
148                 .vfespfr = ZR36057_VFESPFR_RGB888|ZR36057_VFESPFR_Pack24,
149         }, {
150                 .name = "32-bit RGB LE",
151                 ZFMT(VIDEO_PALETTE_RGB32,
152                      V4L2_PIX_FMT_BGR32, V4L2_COLORSPACE_SRGB),
153                 .depth = 32,
154                 .flags = ZORAN_FORMAT_CAPTURE |
155                          ZORAN_FORMAT_OVERLAY,
156                 .vfespfr = ZR36057_VFESPFR_RGB888|ZR36057_VFESPFR_LittleEndian,
157         }, {
158                 .name = "32-bit RGB BE",
159                 ZFMT(-1,
160                      V4L2_PIX_FMT_RGB32, V4L2_COLORSPACE_SRGB),
161                 .depth = 32,
162                 .flags = ZORAN_FORMAT_CAPTURE |
163                          ZORAN_FORMAT_OVERLAY,
164                 .vfespfr = ZR36057_VFESPFR_RGB888,
165         }, {
166                 .name = "4:2:2, packed, YUYV",
167                 ZFMT(VIDEO_PALETTE_YUV422,
168                      V4L2_PIX_FMT_YUYV, V4L2_COLORSPACE_SMPTE170M),
169                 .depth = 16,
170                 .flags = ZORAN_FORMAT_CAPTURE |
171                          ZORAN_FORMAT_OVERLAY,
172                 .vfespfr = ZR36057_VFESPFR_YUV422,
173         }, {
174                 .name = "4:2:2, packed, UYVY",
175                 ZFMT(VIDEO_PALETTE_UYVY,
176                      V4L2_PIX_FMT_UYVY, V4L2_COLORSPACE_SMPTE170M),
177                 .depth = 16,
178                 .flags = ZORAN_FORMAT_CAPTURE |
179                          ZORAN_FORMAT_OVERLAY,
180                 .vfespfr = ZR36057_VFESPFR_YUV422|ZR36057_VFESPFR_LittleEndian,
181         }, {
182                 .name = "Hardware-encoded Motion-JPEG",
183                 ZFMT(-1,
184                      V4L2_PIX_FMT_MJPEG, V4L2_COLORSPACE_SMPTE170M),
185                 .depth = 0,
186                 .flags = ZORAN_FORMAT_CAPTURE |
187                          ZORAN_FORMAT_PLAYBACK |
188                          ZORAN_FORMAT_COMPRESSED,
189         }
190 };
191 #define NUM_FORMATS ARRAY_SIZE(zoran_formats)
192
193 // RJ: Test only - want to test BUZ_USE_HIMEM even when CONFIG_BIGPHYS_AREA is defined
194
195
196 extern int v4l_nbufs;
197 extern int v4l_bufsize;
198 extern int jpg_nbufs;
199 extern int jpg_bufsize;
200 extern int pass_through;
201
202 static int lock_norm;   /* 0 = default 1 = Don't change TV standard (norm) */
203 module_param(lock_norm, int, 0644);
204 MODULE_PARM_DESC(lock_norm, "Prevent norm changes (1 = ignore, >1 = fail)");
205
206         /* small helper function for calculating buffersizes for v4l2
207          * we calculate the nearest higher power-of-two, which
208          * will be the recommended buffersize */
209 static __u32
210 zoran_v4l2_calc_bufsize (struct zoran_jpg_settings *settings)
211 {
212         __u8 div = settings->VerDcm * settings->HorDcm * settings->TmpDcm;
213         __u32 num = (1024 * 512) / (div);
214         __u32 result = 2;
215
216         num--;
217         while (num) {
218                 num >>= 1;
219                 result <<= 1;
220         }
221
222         if (result > jpg_bufsize)
223                 return jpg_bufsize;
224         if (result < 8192)
225                 return 8192;
226         return result;
227 }
228
229 /* forward references */
230 static void v4l_fbuffer_free(struct file *file);
231 static void jpg_fbuffer_free(struct file *file);
232
233 /*
234  *   Allocate the V4L grab buffers
235  *
236  *   These have to be pysically contiguous.
237  *   If v4l_bufsize <= MAX_KMALLOC_MEM we use kmalloc
238  *   else we try to allocate them with bigphysarea_alloc_pages
239  *   if the bigphysarea patch is present in the kernel,
240  *   else we try to use high memory (if the user has bootet
241  *   Linux with the necessary memory left over).
242  */
243
244 static unsigned long
245 get_high_mem (unsigned long size)
246 {
247 /*
248  * Check if there is usable memory at the end of Linux memory
249  * of at least size. Return the physical address of this memory,
250  * return 0 on failure.
251  *
252  * The idea is from Alexandro Rubini's book "Linux device drivers".
253  * The driver from him which is downloadable from O'Reilly's
254  * web site misses the "virt_to_phys(high_memory)" part
255  * (and therefore doesn't work at all - at least with 2.2.x kernels).
256  *
257  * It should be unnecessary to mention that THIS IS DANGEROUS,
258  * if more than one driver at a time has the idea to use this memory!!!!
259  */
260
261         volatile unsigned char __iomem *mem;
262         unsigned char c;
263         unsigned long hi_mem_ph;
264         unsigned long i;
265
266         /* Map the high memory to user space */
267
268         hi_mem_ph = virt_to_phys(high_memory);
269
270         mem = ioremap(hi_mem_ph, size);
271         if (!mem) {
272                 dprintk(1,
273                         KERN_ERR "%s: get_high_mem() - ioremap failed\n",
274                         ZORAN_NAME);
275                 return 0;
276         }
277
278         for (i = 0; i < size; i++) {
279                 /* Check if it is memory */
280                 c = i & 0xff;
281                 writeb(c, mem + i);
282                 if (readb(mem + i) != c)
283                         break;
284                 c = 255 - c;
285                 writeb(c, mem + i);
286                 if (readb(mem + i) != c)
287                         break;
288                 writeb(0, mem + i);     /* zero out memory */
289
290                 /* give the kernel air to breath */
291                 if ((i & 0x3ffff) == 0x3ffff)
292                         schedule();
293         }
294
295         iounmap(mem);
296
297         if (i != size) {
298                 dprintk(1,
299                         KERN_ERR
300                         "%s: get_high_mem() - requested %lu, avail %lu\n",
301                         ZORAN_NAME, size, i);
302                 return 0;
303         }
304
305         return hi_mem_ph;
306 }
307
308 static int
309 v4l_fbuffer_alloc (struct file *file)
310 {
311         struct zoran_fh *fh = file->private_data;
312         struct zoran *zr = fh->zr;
313         int i, off;
314         unsigned char *mem;
315         unsigned long pmem = 0;
316
317         /* we might have old buffers lying around... */
318         if (fh->v4l_buffers.ready_to_be_freed) {
319                 v4l_fbuffer_free(file);
320         }
321
322         for (i = 0; i < fh->v4l_buffers.num_buffers; i++) {
323                 if (fh->v4l_buffers.buffer[i].fbuffer)
324                         dprintk(2,
325                                 KERN_WARNING
326                                 "%s: v4l_fbuffer_alloc() - buffer %d allready allocated!?\n",
327                                 ZR_DEVNAME(zr), i);
328
329                 //udelay(20);
330                 if (fh->v4l_buffers.buffer_size <= MAX_KMALLOC_MEM) {
331                         /* Use kmalloc */
332
333                         mem = kmalloc(fh->v4l_buffers.buffer_size, GFP_KERNEL);
334                         if (!mem) {
335                                 dprintk(1,
336                                         KERN_ERR
337                                         "%s: v4l_fbuffer_alloc() - kmalloc for V4L buf %d failed\n",
338                                         ZR_DEVNAME(zr), i);
339                                 v4l_fbuffer_free(file);
340                                 return -ENOBUFS;
341                         }
342                         fh->v4l_buffers.buffer[i].fbuffer = mem;
343                         fh->v4l_buffers.buffer[i].fbuffer_phys =
344                             virt_to_phys(mem);
345                         fh->v4l_buffers.buffer[i].fbuffer_bus =
346                             virt_to_bus(mem);
347                         for (off = 0; off < fh->v4l_buffers.buffer_size;
348                              off += PAGE_SIZE)
349                                 SetPageReserved(MAP_NR(mem + off));
350                         dprintk(4,
351                                 KERN_INFO
352                                 "%s: v4l_fbuffer_alloc() - V4L frame %d mem 0x%lx (bus: 0x%lx)\n",
353                                 ZR_DEVNAME(zr), i, (unsigned long) mem,
354                                 virt_to_bus(mem));
355                 } else {
356
357                         /* Use high memory which has been left at boot time */
358
359                         /* Ok., Ok. this is an evil hack - we make
360                          * the assumption that physical addresses are
361                          * the same as bus addresses (true at least
362                          * for Intel processors). The whole method of
363                          * obtaining and using this memory is not very
364                          * nice - but I hope it saves some poor users
365                          * from kernel hacking, which might have even
366                          * more evil results */
367
368                         if (i == 0) {
369                                 int size =
370                                     fh->v4l_buffers.num_buffers *
371                                     fh->v4l_buffers.buffer_size;
372
373                                 pmem = get_high_mem(size);
374                                 if (pmem == 0) {
375                                         dprintk(1,
376                                                 KERN_ERR
377                                                 "%s: v4l_fbuffer_alloc() - get_high_mem (size = %d KB) for V4L bufs failed\n",
378                                                 ZR_DEVNAME(zr), size >> 10);
379                                         return -ENOBUFS;
380                                 }
381                                 fh->v4l_buffers.buffer[0].fbuffer = NULL;
382                                 fh->v4l_buffers.buffer[0].fbuffer_phys = pmem;
383                                 fh->v4l_buffers.buffer[0].fbuffer_bus = pmem;
384                                 dprintk(4,
385                                         KERN_INFO
386                                         "%s: v4l_fbuffer_alloc() - using %d KB high memory\n",
387                                         ZR_DEVNAME(zr), size >> 10);
388                         } else {
389                                 fh->v4l_buffers.buffer[i].fbuffer = NULL;
390                                 fh->v4l_buffers.buffer[i].fbuffer_phys =
391                                     pmem + i * fh->v4l_buffers.buffer_size;
392                                 fh->v4l_buffers.buffer[i].fbuffer_bus =
393                                     pmem + i * fh->v4l_buffers.buffer_size;
394                         }
395                 }
396         }
397
398         fh->v4l_buffers.allocated = 1;
399
400         return 0;
401 }
402
403 /* free the V4L grab buffers */
404 static void
405 v4l_fbuffer_free (struct file *file)
406 {
407         struct zoran_fh *fh = file->private_data;
408         struct zoran *zr = fh->zr;
409         int i, off;
410         unsigned char *mem;
411
412         dprintk(4, KERN_INFO "%s: v4l_fbuffer_free()\n", ZR_DEVNAME(zr));
413
414         for (i = 0; i < fh->v4l_buffers.num_buffers; i++) {
415                 if (!fh->v4l_buffers.buffer[i].fbuffer)
416                         continue;
417
418                 if (fh->v4l_buffers.buffer_size <= MAX_KMALLOC_MEM) {
419                         mem = fh->v4l_buffers.buffer[i].fbuffer;
420                         for (off = 0; off < fh->v4l_buffers.buffer_size;
421                              off += PAGE_SIZE)
422                                 ClearPageReserved(MAP_NR(mem + off));
423                         kfree((void *) fh->v4l_buffers.buffer[i].fbuffer);
424                 }
425                 fh->v4l_buffers.buffer[i].fbuffer = NULL;
426         }
427
428         fh->v4l_buffers.allocated = 0;
429         fh->v4l_buffers.ready_to_be_freed = 0;
430 }
431
432 /*
433  *   Allocate the MJPEG grab buffers.
434  *
435  *   If the requested buffer size is smaller than MAX_KMALLOC_MEM,
436  *   kmalloc is used to request a physically contiguous area,
437  *   else we allocate the memory in framgents with get_zeroed_page.
438  *
439  *   If a Natoma chipset is present and this is a revision 1 zr36057,
440  *   each MJPEG buffer needs to be physically contiguous.
441  *   (RJ: This statement is from Dave Perks' original driver,
442  *   I could never check it because I have a zr36067)
443  *   The driver cares about this because it reduces the buffer
444  *   size to MAX_KMALLOC_MEM in that case (which forces contiguous allocation).
445  *
446  *   RJ: The contents grab buffers needs never be accessed in the driver.
447  *       Therefore there is no need to allocate them with vmalloc in order
448  *       to get a contiguous virtual memory space.
449  *       I don't understand why many other drivers first allocate them with
450  *       vmalloc (which uses internally also get_zeroed_page, but delivers you
451  *       virtual addresses) and then again have to make a lot of efforts
452  *       to get the physical address.
453  *
454  *   Ben Capper:
455  *       On big-endian architectures (such as ppc) some extra steps
456  *       are needed. When reading and writing to the stat_com array
457  *       and fragment buffers, the device expects to see little-
458  *       endian values. The use of cpu_to_le32() and le32_to_cpu()
459  *       in this function (and one or two others in zoran_device.c)
460  *       ensure that these values are always stored in little-endian
461  *       form, regardless of architecture. The zr36057 does Very Bad
462  *       Things on big endian architectures if the stat_com array
463  *       and fragment buffers are not little-endian.
464  */
465
466 static int
467 jpg_fbuffer_alloc (struct file *file)
468 {
469         struct zoran_fh *fh = file->private_data;
470         struct zoran *zr = fh->zr;
471         int i, j, off;
472         unsigned long mem;
473
474         /* we might have old buffers lying around */
475         if (fh->jpg_buffers.ready_to_be_freed) {
476                 jpg_fbuffer_free(file);
477         }
478
479         for (i = 0; i < fh->jpg_buffers.num_buffers; i++) {
480                 if (fh->jpg_buffers.buffer[i].frag_tab)
481                         dprintk(2,
482                                 KERN_WARNING
483                                 "%s: jpg_fbuffer_alloc() - buffer %d allready allocated!?\n",
484                                 ZR_DEVNAME(zr), i);
485
486                 /* Allocate fragment table for this buffer */
487
488                 mem = get_zeroed_page(GFP_KERNEL);
489                 if (mem == 0) {
490                         dprintk(1,
491                                 KERN_ERR
492                                 "%s: jpg_fbuffer_alloc() - get_zeroed_page (frag_tab) failed for buffer %d\n",
493                                 ZR_DEVNAME(zr), i);
494                         jpg_fbuffer_free(file);
495                         return -ENOBUFS;
496                 }
497                 fh->jpg_buffers.buffer[i].frag_tab = (__le32 *) mem;
498                 fh->jpg_buffers.buffer[i].frag_tab_bus =
499                     virt_to_bus((void *) mem);
500
501                 //if (alloc_contig) {
502                 if (fh->jpg_buffers.need_contiguous) {
503                         mem =
504                             (unsigned long) kmalloc(fh->jpg_buffers.
505                                                     buffer_size,
506                                                     GFP_KERNEL);
507                         if (mem == 0) {
508                                 dprintk(1,
509                                         KERN_ERR
510                                         "%s: jpg_fbuffer_alloc() - kmalloc failed for buffer %d\n",
511                                         ZR_DEVNAME(zr), i);
512                                 jpg_fbuffer_free(file);
513                                 return -ENOBUFS;
514                         }
515                         fh->jpg_buffers.buffer[i].frag_tab[0] =
516                             cpu_to_le32(virt_to_bus((void *) mem));
517                         fh->jpg_buffers.buffer[i].frag_tab[1] =
518                             cpu_to_le32(((fh->jpg_buffers.buffer_size / 4) << 1) | 1);
519                         for (off = 0; off < fh->jpg_buffers.buffer_size;
520                              off += PAGE_SIZE)
521                                 SetPageReserved(MAP_NR(mem + off));
522                 } else {
523                         /* jpg_bufsize is allreay page aligned */
524                         for (j = 0;
525                              j < fh->jpg_buffers.buffer_size / PAGE_SIZE;
526                              j++) {
527                                 mem = get_zeroed_page(GFP_KERNEL);
528                                 if (mem == 0) {
529                                         dprintk(1,
530                                                 KERN_ERR
531                                                 "%s: jpg_fbuffer_alloc() - get_zeroed_page failed for buffer %d\n",
532                                                 ZR_DEVNAME(zr), i);
533                                         jpg_fbuffer_free(file);
534                                         return -ENOBUFS;
535                                 }
536
537                                 fh->jpg_buffers.buffer[i].frag_tab[2 * j] =
538                                     cpu_to_le32(virt_to_bus((void *) mem));
539                                 fh->jpg_buffers.buffer[i].frag_tab[2 * j +
540                                                                    1] =
541                                     cpu_to_le32((PAGE_SIZE / 4) << 1);
542                                 SetPageReserved(MAP_NR(mem));
543                         }
544
545                         fh->jpg_buffers.buffer[i].frag_tab[2 * j - 1] |= cpu_to_le32(1);
546                 }
547         }
548
549         dprintk(4,
550                 KERN_DEBUG "%s: jpg_fbuffer_alloc() - %d KB allocated\n",
551                 ZR_DEVNAME(zr),
552                 (fh->jpg_buffers.num_buffers *
553                  fh->jpg_buffers.buffer_size) >> 10);
554
555         fh->jpg_buffers.allocated = 1;
556
557         return 0;
558 }
559
560 /* free the MJPEG grab buffers */
561 static void
562 jpg_fbuffer_free (struct file *file)
563 {
564         struct zoran_fh *fh = file->private_data;
565         struct zoran *zr = fh->zr;
566         int i, j, off;
567         unsigned char *mem;
568
569         dprintk(4, KERN_DEBUG "%s: jpg_fbuffer_free()\n", ZR_DEVNAME(zr));
570
571         for (i = 0; i < fh->jpg_buffers.num_buffers; i++) {
572                 if (!fh->jpg_buffers.buffer[i].frag_tab)
573                         continue;
574
575                 //if (alloc_contig) {
576                 if (fh->jpg_buffers.need_contiguous) {
577                         if (fh->jpg_buffers.buffer[i].frag_tab[0]) {
578                                 mem = (unsigned char *) bus_to_virt(le32_to_cpu(
579                                         fh->jpg_buffers.buffer[i].frag_tab[0]));
580                                 for (off = 0;
581                                      off < fh->jpg_buffers.buffer_size;
582                                      off += PAGE_SIZE)
583                                         ClearPageReserved(MAP_NR
584                                                           (mem + off));
585                                 kfree(mem);
586                                 fh->jpg_buffers.buffer[i].frag_tab[0] = 0;
587                                 fh->jpg_buffers.buffer[i].frag_tab[1] = 0;
588                         }
589                 } else {
590                         for (j = 0;
591                              j < fh->jpg_buffers.buffer_size / PAGE_SIZE;
592                              j++) {
593                                 if (!fh->jpg_buffers.buffer[i].
594                                     frag_tab[2 * j])
595                                         break;
596                                 ClearPageReserved(MAP_NR
597                                                   (bus_to_virt
598                                                    (le32_to_cpu
599                                                     (fh->jpg_buffers.
600                                                      buffer[i].frag_tab[2 *
601                                                                        j]))));
602                                 free_page((unsigned long)
603                                           bus_to_virt
604                                                   (le32_to_cpu
605                                                    (fh->jpg_buffers.
606                                                       buffer[i].
607                                                       frag_tab[2 * j])));
608                                 fh->jpg_buffers.buffer[i].frag_tab[2 * j] =
609                                     0;
610                                 fh->jpg_buffers.buffer[i].frag_tab[2 * j +
611                                                                    1] = 0;
612                         }
613                 }
614
615                 free_page((unsigned long) fh->jpg_buffers.buffer[i].
616                           frag_tab);
617                 fh->jpg_buffers.buffer[i].frag_tab = NULL;
618         }
619
620         fh->jpg_buffers.allocated = 0;
621         fh->jpg_buffers.ready_to_be_freed = 0;
622 }
623
624 /*
625  *   V4L Buffer grabbing
626  */
627
628 static int
629 zoran_v4l_set_format (struct file               *file,
630                       int                        width,
631                       int                        height,
632                       const struct zoran_format *format)
633 {
634         struct zoran_fh *fh = file->private_data;
635         struct zoran *zr = fh->zr;
636         int bpp;
637
638         /* Check size and format of the grab wanted */
639
640         if (height < BUZ_MIN_HEIGHT || width < BUZ_MIN_WIDTH ||
641             height > BUZ_MAX_HEIGHT || width > BUZ_MAX_WIDTH) {
642                 dprintk(1,
643                         KERN_ERR
644                         "%s: v4l_set_format() - wrong frame size (%dx%d)\n",
645                         ZR_DEVNAME(zr), width, height);
646                 return -EINVAL;
647         }
648
649         bpp = (format->depth + 7) / 8;
650
651         /* Check against available buffer size */
652         if (height * width * bpp > fh->v4l_buffers.buffer_size) {
653                 dprintk(1,
654                         KERN_ERR
655                         "%s: v4l_set_format() - video buffer size (%d kB) is too small\n",
656                         ZR_DEVNAME(zr), fh->v4l_buffers.buffer_size >> 10);
657                 return -EINVAL;
658         }
659
660         /* The video front end needs 4-byte alinged line sizes */
661
662         if ((bpp == 2 && (width & 1)) || (bpp == 3 && (width & 3))) {
663                 dprintk(1,
664                         KERN_ERR
665                         "%s: v4l_set_format() - wrong frame alingment\n",
666                         ZR_DEVNAME(zr));
667                 return -EINVAL;
668         }
669
670         fh->v4l_settings.width = width;
671         fh->v4l_settings.height = height;
672         fh->v4l_settings.format = format;
673         fh->v4l_settings.bytesperline = bpp * fh->v4l_settings.width;
674
675         return 0;
676 }
677
678 static int
679 zoran_v4l_queue_frame (struct file *file,
680                        int          num)
681 {
682         struct zoran_fh *fh = file->private_data;
683         struct zoran *zr = fh->zr;
684         unsigned long flags;
685         int res = 0;
686
687         if (!fh->v4l_buffers.allocated) {
688                 dprintk(1,
689                         KERN_ERR
690                         "%s: v4l_queue_frame() - buffers not yet allocated\n",
691                         ZR_DEVNAME(zr));
692                 res = -ENOMEM;
693         }
694
695         /* No grabbing outside the buffer range! */
696         if (num >= fh->v4l_buffers.num_buffers || num < 0) {
697                 dprintk(1,
698                         KERN_ERR
699                         "%s: v4l_queue_frame() - buffer %d is out of range\n",
700                         ZR_DEVNAME(zr), num);
701                 res = -EINVAL;
702         }
703
704         spin_lock_irqsave(&zr->spinlock, flags);
705
706         if (fh->v4l_buffers.active == ZORAN_FREE) {
707                 if (zr->v4l_buffers.active == ZORAN_FREE) {
708                         zr->v4l_buffers = fh->v4l_buffers;
709                         fh->v4l_buffers.active = ZORAN_ACTIVE;
710                 } else {
711                         dprintk(1,
712                                 KERN_ERR
713                                 "%s: v4l_queue_frame() - another session is already capturing\n",
714                                 ZR_DEVNAME(zr));
715                         res = -EBUSY;
716                 }
717         }
718
719         /* make sure a grab isn't going on currently with this buffer */
720         if (!res) {
721                 switch (zr->v4l_buffers.buffer[num].state) {
722                 default:
723                 case BUZ_STATE_PEND:
724                         if (zr->v4l_buffers.active == ZORAN_FREE) {
725                                 fh->v4l_buffers.active = ZORAN_FREE;
726                                 zr->v4l_buffers.allocated = 0;
727                         }
728                         res = -EBUSY;   /* what are you doing? */
729                         break;
730                 case BUZ_STATE_DONE:
731                         dprintk(2,
732                                 KERN_WARNING
733                                 "%s: v4l_queue_frame() - queueing buffer %d in state DONE!?\n",
734                                 ZR_DEVNAME(zr), num);
735                 case BUZ_STATE_USER:
736                         /* since there is at least one unused buffer there's room for at least
737                          * one more pend[] entry */
738                         zr->v4l_pend[zr->v4l_pend_head++ &
739                                         V4L_MASK_FRAME] = num;
740                         zr->v4l_buffers.buffer[num].state = BUZ_STATE_PEND;
741                         zr->v4l_buffers.buffer[num].bs.length =
742                             fh->v4l_settings.bytesperline *
743                             zr->v4l_settings.height;
744                         fh->v4l_buffers.buffer[num] =
745                             zr->v4l_buffers.buffer[num];
746                         break;
747                 }
748         }
749
750         spin_unlock_irqrestore(&zr->spinlock, flags);
751
752         if (!res && zr->v4l_buffers.active == ZORAN_FREE)
753                 zr->v4l_buffers.active = fh->v4l_buffers.active;
754
755         return res;
756 }
757
758 static int
759 v4l_grab (struct file       *file,
760           struct video_mmap *mp)
761 {
762         struct zoran_fh *fh = file->private_data;
763         struct zoran *zr = fh->zr;
764         int res = 0, i;
765
766         for (i = 0; i < NUM_FORMATS; i++) {
767                 if (zoran_formats[i].palette == mp->format &&
768                     zoran_formats[i].flags & ZORAN_FORMAT_CAPTURE &&
769                     !(zoran_formats[i].flags & ZORAN_FORMAT_COMPRESSED))
770                         break;
771         }
772         if (i == NUM_FORMATS || zoran_formats[i].depth == 0) {
773                 dprintk(1,
774                         KERN_ERR
775                         "%s: v4l_grab() - wrong bytes-per-pixel format\n",
776                         ZR_DEVNAME(zr));
777                 return -EINVAL;
778         }
779
780         /*
781          * To minimize the time spent in the IRQ routine, we avoid setting up
782          * the video front end there.
783          * If this grab has different parameters from a running streaming capture
784          * we stop the streaming capture and start it over again.
785          */
786         if (zr->v4l_memgrab_active &&
787             (zr->v4l_settings.width != mp->width ||
788              zr->v4l_settings.height != mp->height ||
789              zr->v4l_settings.format->palette != mp->format)) {
790                 res = wait_grab_pending(zr);
791                 if (res)
792                         return res;
793         }
794         if ((res = zoran_v4l_set_format(file,
795                                         mp->width,
796                                         mp->height,
797                                         &zoran_formats[i])))
798                 return res;
799         zr->v4l_settings = fh->v4l_settings;
800
801         /* queue the frame in the pending queue */
802         if ((res = zoran_v4l_queue_frame(file, mp->frame))) {
803                 fh->v4l_buffers.active = ZORAN_FREE;
804                 return res;
805         }
806
807         /* put the 36057 into frame grabbing mode */
808         if (!res && !zr->v4l_memgrab_active)
809                 zr36057_set_memgrab(zr, 1);
810
811         //dprintk(4, KERN_INFO "%s: Frame grab 3...\n", ZR_DEVNAME(zr));
812
813         return res;
814 }
815
816 /*
817  * Sync on a V4L buffer
818  */
819
820 static int
821 v4l_sync (struct file *file,
822           int          frame)
823 {
824         struct zoran_fh *fh = file->private_data;
825         struct zoran *zr = fh->zr;
826         unsigned long flags;
827
828         if (fh->v4l_buffers.active == ZORAN_FREE) {
829                 dprintk(1,
830                         KERN_ERR
831                         "%s: v4l_sync() - no grab active for this session\n",
832                         ZR_DEVNAME(zr));
833                 return -EINVAL;
834         }
835
836         /* check passed-in frame number */
837         if (frame >= fh->v4l_buffers.num_buffers || frame < 0) {
838                 dprintk(1,
839                         KERN_ERR "%s: v4l_sync() - frame %d is invalid\n",
840                         ZR_DEVNAME(zr), frame);
841                 return -EINVAL;
842         }
843
844         /* Check if is buffer was queued at all */
845         if (zr->v4l_buffers.buffer[frame].state == BUZ_STATE_USER) {
846                 dprintk(1,
847                         KERN_ERR
848                         "%s: v4l_sync() - attempt to sync on a buffer which was not queued?\n",
849                         ZR_DEVNAME(zr));
850                 return -EPROTO;
851         }
852
853         /* wait on this buffer to get ready */
854         if (!wait_event_interruptible_timeout(zr->v4l_capq,
855                                 (zr->v4l_buffers.buffer[frame].state != BUZ_STATE_PEND),
856                                 10*HZ))
857                 return -ETIME;
858         if (signal_pending(current))
859                 return -ERESTARTSYS;
860
861         /* buffer should now be in BUZ_STATE_DONE */
862         if (zr->v4l_buffers.buffer[frame].state != BUZ_STATE_DONE)
863                 dprintk(2,
864                         KERN_ERR "%s: v4l_sync() - internal state error\n",
865                         ZR_DEVNAME(zr));
866
867         zr->v4l_buffers.buffer[frame].state = BUZ_STATE_USER;
868         fh->v4l_buffers.buffer[frame] = zr->v4l_buffers.buffer[frame];
869
870         spin_lock_irqsave(&zr->spinlock, flags);
871
872         /* Check if streaming capture has finished */
873         if (zr->v4l_pend_tail == zr->v4l_pend_head) {
874                 zr36057_set_memgrab(zr, 0);
875                 if (zr->v4l_buffers.active == ZORAN_ACTIVE) {
876                         fh->v4l_buffers.active = zr->v4l_buffers.active =
877                             ZORAN_FREE;
878                         zr->v4l_buffers.allocated = 0;
879                 }
880         }
881
882         spin_unlock_irqrestore(&zr->spinlock, flags);
883
884         return 0;
885 }
886
887 /*
888  *   Queue a MJPEG buffer for capture/playback
889  */
890
891 static int
892 zoran_jpg_queue_frame (struct file          *file,
893                        int                   num,
894                        enum zoran_codec_mode mode)
895 {
896         struct zoran_fh *fh = file->private_data;
897         struct zoran *zr = fh->zr;
898         unsigned long flags;
899         int res = 0;
900
901         /* Check if buffers are allocated */
902         if (!fh->jpg_buffers.allocated) {
903                 dprintk(1,
904                         KERN_ERR
905                         "%s: jpg_queue_frame() - buffers not yet allocated\n",
906                         ZR_DEVNAME(zr));
907                 return -ENOMEM;
908         }
909
910         /* No grabbing outside the buffer range! */
911         if (num >= fh->jpg_buffers.num_buffers || num < 0) {
912                 dprintk(1,
913                         KERN_ERR
914                         "%s: jpg_queue_frame() - buffer %d out of range\n",
915                         ZR_DEVNAME(zr), num);
916                 return -EINVAL;
917         }
918
919         /* what is the codec mode right now? */
920         if (zr->codec_mode == BUZ_MODE_IDLE) {
921                 zr->jpg_settings = fh->jpg_settings;
922         } else if (zr->codec_mode != mode) {
923                 /* wrong codec mode active - invalid */
924                 dprintk(1,
925                         KERN_ERR
926                         "%s: jpg_queue_frame() - codec in wrong mode\n",
927                         ZR_DEVNAME(zr));
928                 return -EINVAL;
929         }
930
931         if (fh->jpg_buffers.active == ZORAN_FREE) {
932                 if (zr->jpg_buffers.active == ZORAN_FREE) {
933                         zr->jpg_buffers = fh->jpg_buffers;
934                         fh->jpg_buffers.active = ZORAN_ACTIVE;
935                 } else {
936                         dprintk(1,
937                                 KERN_ERR
938                                 "%s: jpg_queue_frame() - another session is already capturing\n",
939                                 ZR_DEVNAME(zr));
940                         res = -EBUSY;
941                 }
942         }
943
944         if (!res && zr->codec_mode == BUZ_MODE_IDLE) {
945                 /* Ok load up the jpeg codec */
946                 zr36057_enable_jpg(zr, mode);
947         }
948
949         spin_lock_irqsave(&zr->spinlock, flags);
950
951         if (!res) {
952                 switch (zr->jpg_buffers.buffer[num].state) {
953                 case BUZ_STATE_DONE:
954                         dprintk(2,
955                                 KERN_WARNING
956                                 "%s: jpg_queue_frame() - queing frame in BUZ_STATE_DONE state!?\n",
957                                 ZR_DEVNAME(zr));
958                 case BUZ_STATE_USER:
959                         /* since there is at least one unused buffer there's room for at
960                          *least one more pend[] entry */
961                         zr->jpg_pend[zr->jpg_que_head++ & BUZ_MASK_FRAME] =
962                             num;
963                         zr->jpg_buffers.buffer[num].state = BUZ_STATE_PEND;
964                         fh->jpg_buffers.buffer[num] =
965                             zr->jpg_buffers.buffer[num];
966                         zoran_feed_stat_com(zr);
967                         break;
968                 default:
969                 case BUZ_STATE_DMA:
970                 case BUZ_STATE_PEND:
971                         if (zr->jpg_buffers.active == ZORAN_FREE) {
972                                 fh->jpg_buffers.active = ZORAN_FREE;
973                                 zr->jpg_buffers.allocated = 0;
974                         }
975                         res = -EBUSY;   /* what are you doing? */
976                         break;
977                 }
978         }
979
980         spin_unlock_irqrestore(&zr->spinlock, flags);
981
982         if (!res && zr->jpg_buffers.active == ZORAN_FREE) {
983                 zr->jpg_buffers.active = fh->jpg_buffers.active;
984         }
985
986         return res;
987 }
988
989 static int
990 jpg_qbuf (struct file          *file,
991           int                   frame,
992           enum zoran_codec_mode mode)
993 {
994         struct zoran_fh *fh = file->private_data;
995         struct zoran *zr = fh->zr;
996         int res = 0;
997
998         /* Does the user want to stop streaming? */
999         if (frame < 0) {
1000                 if (zr->codec_mode == mode) {
1001                         if (fh->jpg_buffers.active == ZORAN_FREE) {
1002                                 dprintk(1,
1003                                         KERN_ERR
1004                                         "%s: jpg_qbuf(-1) - session not active\n",
1005                                         ZR_DEVNAME(zr));
1006                                 return -EINVAL;
1007                         }
1008                         fh->jpg_buffers.active = zr->jpg_buffers.active =
1009                             ZORAN_FREE;
1010                         zr->jpg_buffers.allocated = 0;
1011                         zr36057_enable_jpg(zr, BUZ_MODE_IDLE);
1012                         return 0;
1013                 } else {
1014                         dprintk(1,
1015                                 KERN_ERR
1016                                 "%s: jpg_qbuf() - stop streaming but not in streaming mode\n",
1017                                 ZR_DEVNAME(zr));
1018                         return -EINVAL;
1019                 }
1020         }
1021
1022         if ((res = zoran_jpg_queue_frame(file, frame, mode)))
1023                 return res;
1024
1025         /* Start the jpeg codec when the first frame is queued  */
1026         if (!res && zr->jpg_que_head == 1)
1027                 jpeg_start(zr);
1028
1029         return res;
1030 }
1031
1032 /*
1033  *   Sync on a MJPEG buffer
1034  */
1035
1036 static int
1037 jpg_sync (struct file       *file,
1038           struct zoran_sync *bs)
1039 {
1040         struct zoran_fh *fh = file->private_data;
1041         struct zoran *zr = fh->zr;
1042         unsigned long flags;
1043         int frame;
1044
1045         if (fh->jpg_buffers.active == ZORAN_FREE) {
1046                 dprintk(1,
1047                         KERN_ERR
1048                         "%s: jpg_sync() - capture is not currently active\n",
1049                         ZR_DEVNAME(zr));
1050                 return -EINVAL;
1051         }
1052         if (zr->codec_mode != BUZ_MODE_MOTION_DECOMPRESS &&
1053             zr->codec_mode != BUZ_MODE_MOTION_COMPRESS) {
1054                 dprintk(1,
1055                         KERN_ERR
1056                         "%s: jpg_sync() - codec not in streaming mode\n",
1057                         ZR_DEVNAME(zr));
1058                 return -EINVAL;
1059         }
1060         if (!wait_event_interruptible_timeout(zr->jpg_capq,
1061                         (zr->jpg_que_tail != zr->jpg_dma_tail ||
1062                          zr->jpg_dma_tail == zr->jpg_dma_head),
1063                         10*HZ)) {
1064                 int isr;
1065
1066                 btand(~ZR36057_JMC_Go_en, ZR36057_JMC);
1067                 udelay(1);
1068                 zr->codec->control(zr->codec, CODEC_G_STATUS,
1069                                            sizeof(isr), &isr);
1070                 dprintk(1,
1071                         KERN_ERR
1072                         "%s: jpg_sync() - timeout: codec isr=0x%02x\n",
1073                         ZR_DEVNAME(zr), isr);
1074
1075                 return -ETIME;
1076
1077         }
1078         if (signal_pending(current))
1079                 return -ERESTARTSYS;
1080
1081         spin_lock_irqsave(&zr->spinlock, flags);
1082
1083         if (zr->jpg_dma_tail != zr->jpg_dma_head)
1084                 frame = zr->jpg_pend[zr->jpg_que_tail++ & BUZ_MASK_FRAME];
1085         else
1086                 frame = zr->jpg_pend[zr->jpg_que_tail & BUZ_MASK_FRAME];
1087
1088         /* buffer should now be in BUZ_STATE_DONE */
1089         if (zr->jpg_buffers.buffer[frame].state != BUZ_STATE_DONE)
1090                 dprintk(2,
1091                         KERN_ERR "%s: jpg_sync() - internal state error\n",
1092                         ZR_DEVNAME(zr));
1093
1094         *bs = zr->jpg_buffers.buffer[frame].bs;
1095         bs->frame = frame;
1096         zr->jpg_buffers.buffer[frame].state = BUZ_STATE_USER;
1097         fh->jpg_buffers.buffer[frame] = zr->jpg_buffers.buffer[frame];
1098
1099         spin_unlock_irqrestore(&zr->spinlock, flags);
1100
1101         return 0;
1102 }
1103
1104 static void
1105 zoran_open_init_session (struct file *file)
1106 {
1107         int i;
1108         struct zoran_fh *fh = file->private_data;
1109         struct zoran *zr = fh->zr;
1110
1111         /* Per default, map the V4L Buffers */
1112         fh->map_mode = ZORAN_MAP_MODE_RAW;
1113
1114         /* take over the card's current settings */
1115         fh->overlay_settings = zr->overlay_settings;
1116         fh->overlay_settings.is_set = 0;
1117         fh->overlay_settings.format = zr->overlay_settings.format;
1118         fh->overlay_active = ZORAN_FREE;
1119
1120         /* v4l settings */
1121         fh->v4l_settings = zr->v4l_settings;
1122
1123         /* v4l_buffers */
1124         memset(&fh->v4l_buffers, 0, sizeof(struct zoran_v4l_struct));
1125         for (i = 0; i < VIDEO_MAX_FRAME; i++) {
1126                 fh->v4l_buffers.buffer[i].state = BUZ_STATE_USER;       /* nothing going on */
1127                 fh->v4l_buffers.buffer[i].bs.frame = i;
1128         }
1129         fh->v4l_buffers.allocated = 0;
1130         fh->v4l_buffers.ready_to_be_freed = 0;
1131         fh->v4l_buffers.active = ZORAN_FREE;
1132         fh->v4l_buffers.buffer_size = v4l_bufsize;
1133         fh->v4l_buffers.num_buffers = v4l_nbufs;
1134
1135         /* jpg settings */
1136         fh->jpg_settings = zr->jpg_settings;
1137
1138         /* jpg_buffers */
1139         memset(&fh->jpg_buffers, 0, sizeof(struct zoran_jpg_struct));
1140         for (i = 0; i < BUZ_MAX_FRAME; i++) {
1141                 fh->jpg_buffers.buffer[i].state = BUZ_STATE_USER;       /* nothing going on */
1142                 fh->jpg_buffers.buffer[i].bs.frame = i;
1143         }
1144         fh->jpg_buffers.need_contiguous = zr->jpg_buffers.need_contiguous;
1145         fh->jpg_buffers.allocated = 0;
1146         fh->jpg_buffers.ready_to_be_freed = 0;
1147         fh->jpg_buffers.active = ZORAN_FREE;
1148         fh->jpg_buffers.buffer_size = jpg_bufsize;
1149         fh->jpg_buffers.num_buffers = jpg_nbufs;
1150 }
1151
1152 static void
1153 zoran_close_end_session (struct file *file)
1154 {
1155         struct zoran_fh *fh = file->private_data;
1156         struct zoran *zr = fh->zr;
1157
1158         /* overlay */
1159         if (fh->overlay_active != ZORAN_FREE) {
1160                 fh->overlay_active = zr->overlay_active = ZORAN_FREE;
1161                 zr->v4l_overlay_active = 0;
1162                 if (!zr->v4l_memgrab_active)
1163                         zr36057_overlay(zr, 0);
1164                 zr->overlay_mask = NULL;
1165         }
1166
1167         /* v4l capture */
1168         if (fh->v4l_buffers.active != ZORAN_FREE) {
1169                 unsigned long flags;
1170
1171                 spin_lock_irqsave(&zr->spinlock, flags);
1172                 zr36057_set_memgrab(zr, 0);
1173                 zr->v4l_buffers.allocated = 0;
1174                 zr->v4l_buffers.active = fh->v4l_buffers.active =
1175                     ZORAN_FREE;
1176                 spin_unlock_irqrestore(&zr->spinlock, flags);
1177         }
1178
1179         /* v4l buffers */
1180         if (fh->v4l_buffers.allocated ||
1181             fh->v4l_buffers.ready_to_be_freed) {
1182                 v4l_fbuffer_free(file);
1183         }
1184
1185         /* jpg capture */
1186         if (fh->jpg_buffers.active != ZORAN_FREE) {
1187                 zr36057_enable_jpg(zr, BUZ_MODE_IDLE);
1188                 zr->jpg_buffers.allocated = 0;
1189                 zr->jpg_buffers.active = fh->jpg_buffers.active =
1190                     ZORAN_FREE;
1191         }
1192
1193         /* jpg buffers */
1194         if (fh->jpg_buffers.allocated ||
1195             fh->jpg_buffers.ready_to_be_freed) {
1196                 jpg_fbuffer_free(file);
1197         }
1198 }
1199
1200 /*
1201  *   Open a zoran card. Right now the flags stuff is just playing
1202  */
1203
1204 static int
1205 zoran_open (struct inode *inode,
1206             struct file  *file)
1207 {
1208         unsigned int minor = iminor(inode);
1209         struct zoran *zr = NULL;
1210         struct zoran_fh *fh;
1211         int i, res, first_open = 0, have_module_locks = 0;
1212
1213         /* find the device */
1214         for (i = 0; i < zoran_num; i++) {
1215                 if (zoran[i].video_dev->minor == minor) {
1216                         zr = &zoran[i];
1217                         break;
1218                 }
1219         }
1220
1221         if (!zr) {
1222                 dprintk(1, KERN_ERR "%s: device not found!\n", ZORAN_NAME);
1223                 res = -ENODEV;
1224                 goto open_unlock_and_return;
1225         }
1226
1227         /* see fs/device.c - the kernel already locks during open(),
1228          * so locking ourselves only causes deadlocks */
1229         /*mutex_lock(&zr->resource_lock);*/
1230
1231         if (!zr->decoder) {
1232                 dprintk(1,
1233                         KERN_ERR "%s: no TV decoder loaded for device!\n",
1234                         ZR_DEVNAME(zr));
1235                 res = -EIO;
1236                 goto open_unlock_and_return;
1237         }
1238
1239         /* try to grab a module lock */
1240         if (!try_module_get(THIS_MODULE)) {
1241                 dprintk(1,
1242                         KERN_ERR
1243                         "%s: failed to acquire my own lock! PANIC!\n",
1244                         ZR_DEVNAME(zr));
1245                 res = -ENODEV;
1246                 goto open_unlock_and_return;
1247         }
1248         if (!try_module_get(zr->decoder->driver->driver.owner)) {
1249                 dprintk(1,
1250                         KERN_ERR
1251                         "%s: failed to grab ownership of i2c decoder\n",
1252                         ZR_DEVNAME(zr));
1253                 res = -EIO;
1254                 module_put(THIS_MODULE);
1255                 goto open_unlock_and_return;
1256         }
1257         if (zr->encoder &&
1258             !try_module_get(zr->encoder->driver->driver.owner)) {
1259                 dprintk(1,
1260                         KERN_ERR
1261                         "%s: failed to grab ownership of i2c encoder\n",
1262                         ZR_DEVNAME(zr));
1263                 res = -EIO;
1264                 module_put(zr->decoder->driver->driver.owner);
1265                 module_put(THIS_MODULE);
1266                 goto open_unlock_and_return;
1267         }
1268
1269         have_module_locks = 1;
1270
1271         if (zr->user >= 2048) {
1272                 dprintk(1, KERN_ERR "%s: too many users (%d) on device\n",
1273                         ZR_DEVNAME(zr), zr->user);
1274                 res = -EBUSY;
1275                 goto open_unlock_and_return;
1276         }
1277
1278         dprintk(1, KERN_INFO "%s: zoran_open(%s, pid=[%d]), users(-)=%d\n",
1279                 ZR_DEVNAME(zr), current->comm, task_pid_nr(current), zr->user);
1280
1281         /* now, create the open()-specific file_ops struct */
1282         fh = kzalloc(sizeof(struct zoran_fh), GFP_KERNEL);
1283         if (!fh) {
1284                 dprintk(1,
1285                         KERN_ERR
1286                         "%s: zoran_open() - allocation of zoran_fh failed\n",
1287                         ZR_DEVNAME(zr));
1288                 res = -ENOMEM;
1289                 goto open_unlock_and_return;
1290         }
1291         /* used to be BUZ_MAX_WIDTH/HEIGHT, but that gives overflows
1292          * on norm-change! */
1293         fh->overlay_mask =
1294             kmalloc(((768 + 31) / 32) * 576 * 4, GFP_KERNEL);
1295         if (!fh->overlay_mask) {
1296                 dprintk(1,
1297                         KERN_ERR
1298                         "%s: zoran_open() - allocation of overlay_mask failed\n",
1299                         ZR_DEVNAME(zr));
1300                 kfree(fh);
1301                 res = -ENOMEM;
1302                 goto open_unlock_and_return;
1303         }
1304
1305         if (zr->user++ == 0)
1306                 first_open = 1;
1307
1308         /*mutex_unlock(&zr->resource_lock);*/
1309
1310         /* default setup - TODO: look at flags */
1311         if (first_open) {       /* First device open */
1312                 zr36057_restart(zr);
1313                 zoran_open_init_params(zr);
1314                 zoran_init_hardware(zr);
1315
1316                 btor(ZR36057_ICR_IntPinEn, ZR36057_ICR);
1317         }
1318
1319         /* set file_ops stuff */
1320         file->private_data = fh;
1321         fh->zr = zr;
1322         zoran_open_init_session(file);
1323
1324         return 0;
1325
1326 open_unlock_and_return:
1327         /* if we grabbed locks, release them accordingly */
1328         if (have_module_locks) {
1329                 module_put(zr->decoder->driver->driver.owner);
1330                 if (zr->encoder) {
1331                         module_put(zr->encoder->driver->driver.owner);
1332                 }
1333                 module_put(THIS_MODULE);
1334         }
1335
1336         /* if there's no device found, we didn't obtain the lock either */
1337         if (zr) {
1338                 /*mutex_unlock(&zr->resource_lock);*/
1339         }
1340
1341         return res;
1342 }
1343
1344 static int
1345 zoran_close (struct inode *inode,
1346              struct file  *file)
1347 {
1348         struct zoran_fh *fh = file->private_data;
1349         struct zoran *zr = fh->zr;
1350
1351         dprintk(1, KERN_INFO "%s: zoran_close(%s, pid=[%d]), users(+)=%d\n",
1352                 ZR_DEVNAME(zr), current->comm, task_pid_nr(current), zr->user);
1353
1354         /* kernel locks (fs/device.c), so don't do that ourselves
1355          * (prevents deadlocks) */
1356         /*mutex_lock(&zr->resource_lock);*/
1357
1358         zoran_close_end_session(file);
1359
1360         if (zr->user-- == 1) {  /* Last process */
1361                 /* Clean up JPEG process */
1362                 wake_up_interruptible(&zr->jpg_capq);
1363                 zr36057_enable_jpg(zr, BUZ_MODE_IDLE);
1364                 zr->jpg_buffers.allocated = 0;
1365                 zr->jpg_buffers.active = ZORAN_FREE;
1366
1367                 /* disable interrupts */
1368                 btand(~ZR36057_ICR_IntPinEn, ZR36057_ICR);
1369
1370                 if (zr36067_debug > 1)
1371                         print_interrupts(zr);
1372
1373                 /* Overlay off */
1374                 zr->v4l_overlay_active = 0;
1375                 zr36057_overlay(zr, 0);
1376                 zr->overlay_mask = NULL;
1377
1378                 /* capture off */
1379                 wake_up_interruptible(&zr->v4l_capq);
1380                 zr36057_set_memgrab(zr, 0);
1381                 zr->v4l_buffers.allocated = 0;
1382                 zr->v4l_buffers.active = ZORAN_FREE;
1383                 zoran_set_pci_master(zr, 0);
1384
1385                 if (!pass_through) {    /* Switch to color bar */
1386                         int zero = 0, two = 2;
1387                         decoder_command(zr, DECODER_ENABLE_OUTPUT, &zero);
1388                         encoder_command(zr, ENCODER_SET_INPUT, &two);
1389                 }
1390         }
1391
1392         file->private_data = NULL;
1393         kfree(fh->overlay_mask);
1394         kfree(fh);
1395
1396         /* release locks on the i2c modules */
1397         module_put(zr->decoder->driver->driver.owner);
1398         if (zr->encoder) {
1399                  module_put(zr->encoder->driver->driver.owner);
1400         }
1401         module_put(THIS_MODULE);
1402
1403         /*mutex_unlock(&zr->resource_lock);*/
1404
1405         dprintk(4, KERN_INFO "%s: zoran_close() done\n", ZR_DEVNAME(zr));
1406
1407         return 0;
1408 }
1409
1410
1411 static ssize_t
1412 zoran_read (struct file *file,
1413             char        __user *data,
1414             size_t       count,
1415             loff_t      *ppos)
1416 {
1417         /* we simply don't support read() (yet)... */
1418
1419         return -EINVAL;
1420 }
1421
1422 static ssize_t
1423 zoran_write (struct file *file,
1424              const char  __user *data,
1425              size_t       count,
1426              loff_t      *ppos)
1427 {
1428         /* ...and the same goes for write() */
1429
1430         return -EINVAL;
1431 }
1432
1433 static int
1434 setup_fbuffer (struct file               *file,
1435                void                      *base,
1436                const struct zoran_format *fmt,
1437                int                        width,
1438                int                        height,
1439                int                        bytesperline)
1440 {
1441         struct zoran_fh *fh = file->private_data;
1442         struct zoran *zr = fh->zr;
1443
1444         /* (Ronald) v4l/v4l2 guidelines */
1445         if (!capable(CAP_SYS_ADMIN) && !capable(CAP_SYS_RAWIO))
1446                 return -EPERM;
1447
1448         /* Don't allow frame buffer overlay if PCI or AGP is buggy, or on
1449            ALi Magik (that needs very low latency while the card needs a
1450            higher value always) */
1451
1452         if (pci_pci_problems & (PCIPCI_FAIL | PCIAGP_FAIL | PCIPCI_ALIMAGIK))
1453                 return -ENXIO;
1454
1455         /* we need a bytesperline value, even if not given */
1456         if (!bytesperline)
1457                 bytesperline = width * ((fmt->depth + 7) & ~7) / 8;
1458
1459 #if 0
1460         if (zr->overlay_active) {
1461                 /* dzjee... stupid users... don't even bother to turn off
1462                  * overlay before changing the memory location...
1463                  * normally, we would return errors here. However, one of
1464                  * the tools that does this is... xawtv! and since xawtv
1465                  * is used by +/- 99% of the users, we'd rather be user-
1466                  * friendly and silently do as if nothing went wrong */
1467                 dprintk(3,
1468                         KERN_ERR
1469                         "%s: setup_fbuffer() - forced overlay turnoff because framebuffer changed\n",
1470                         ZR_DEVNAME(zr));
1471                 zr36057_overlay(zr, 0);
1472         }
1473 #endif
1474
1475         if (!(fmt->flags & ZORAN_FORMAT_OVERLAY)) {
1476                 dprintk(1,
1477                         KERN_ERR
1478                         "%s: setup_fbuffer() - no valid overlay format given\n",
1479                         ZR_DEVNAME(zr));
1480                 return -EINVAL;
1481         }
1482         if (height <= 0 || width <= 0 || bytesperline <= 0) {
1483                 dprintk(1,
1484                         KERN_ERR
1485                         "%s: setup_fbuffer() - invalid height/width/bpl value (%d|%d|%d)\n",
1486                         ZR_DEVNAME(zr), width, height, bytesperline);
1487                 return -EINVAL;
1488         }
1489         if (bytesperline & 3) {
1490                 dprintk(1,
1491                         KERN_ERR
1492                         "%s: setup_fbuffer() - bytesperline (%d) must be 4-byte aligned\n",
1493                         ZR_DEVNAME(zr), bytesperline);
1494                 return -EINVAL;
1495         }
1496
1497         zr->buffer.base = (void *) ((unsigned long) base & ~3);
1498         zr->buffer.height = height;
1499         zr->buffer.width = width;
1500         zr->buffer.depth = fmt->depth;
1501         zr->overlay_settings.format = fmt;
1502         zr->buffer.bytesperline = bytesperline;
1503
1504         /* The user should set new window parameters */
1505         zr->overlay_settings.is_set = 0;
1506
1507         return 0;
1508 }
1509
1510
1511 static int
1512 setup_window (struct file       *file,
1513               int                x,
1514               int                y,
1515               int                width,
1516               int                height,
1517               struct video_clip __user *clips,
1518               int                clipcount,
1519               void              __user *bitmap)
1520 {
1521         struct zoran_fh *fh = file->private_data;
1522         struct zoran *zr = fh->zr;
1523         struct video_clip *vcp = NULL;
1524         int on, end;
1525
1526
1527         if (!zr->buffer.base) {
1528                 dprintk(1,
1529                         KERN_ERR
1530                         "%s: setup_window() - frame buffer has to be set first\n",
1531                         ZR_DEVNAME(zr));
1532                 return -EINVAL;
1533         }
1534
1535         if (!fh->overlay_settings.format) {
1536                 dprintk(1,
1537                         KERN_ERR
1538                         "%s: setup_window() - no overlay format set\n",
1539                         ZR_DEVNAME(zr));
1540                 return -EINVAL;
1541         }
1542
1543         /*
1544          * The video front end needs 4-byte alinged line sizes, we correct that
1545          * silently here if necessary
1546          */
1547         if (zr->buffer.depth == 15 || zr->buffer.depth == 16) {
1548                 end = (x + width) & ~1; /* round down */
1549                 x = (x + 1) & ~1;       /* round up */
1550                 width = end - x;
1551         }
1552
1553         if (zr->buffer.depth == 24) {
1554                 end = (x + width) & ~3; /* round down */
1555                 x = (x + 3) & ~3;       /* round up */
1556                 width = end - x;
1557         }
1558
1559         if (width > BUZ_MAX_WIDTH)
1560                 width = BUZ_MAX_WIDTH;
1561         if (height > BUZ_MAX_HEIGHT)
1562                 height = BUZ_MAX_HEIGHT;
1563
1564         /* Check for vaild parameters */
1565         if (width < BUZ_MIN_WIDTH || height < BUZ_MIN_HEIGHT ||
1566             width > BUZ_MAX_WIDTH || height > BUZ_MAX_HEIGHT) {
1567                 dprintk(1,
1568                         KERN_ERR
1569                         "%s: setup_window() - width = %d or height = %d invalid\n",
1570                         ZR_DEVNAME(zr), width, height);
1571                 return -EINVAL;
1572         }
1573
1574         fh->overlay_settings.x = x;
1575         fh->overlay_settings.y = y;
1576         fh->overlay_settings.width = width;
1577         fh->overlay_settings.height = height;
1578         fh->overlay_settings.clipcount = clipcount;
1579
1580         /*
1581          * If an overlay is running, we have to switch it off
1582          * and switch it on again in order to get the new settings in effect.
1583          *
1584          * We also want to avoid that the overlay mask is written
1585          * when an overlay is running.
1586          */
1587
1588         on = zr->v4l_overlay_active && !zr->v4l_memgrab_active &&
1589             zr->overlay_active != ZORAN_FREE &&
1590             fh->overlay_active != ZORAN_FREE;
1591         if (on)
1592                 zr36057_overlay(zr, 0);
1593
1594         /*
1595          *   Write the overlay mask if clips are wanted.
1596          *   We prefer a bitmap.
1597          */
1598         if (bitmap) {
1599                 /* fake value - it just means we want clips */
1600                 fh->overlay_settings.clipcount = 1;
1601
1602                 if (copy_from_user(fh->overlay_mask, bitmap,
1603                                    (width * height + 7) / 8)) {
1604                         return -EFAULT;
1605                 }
1606         } else if (clipcount > 0) {
1607                 /* write our own bitmap from the clips */
1608                 vcp = vmalloc(sizeof(struct video_clip) * (clipcount + 4));
1609                 if (vcp == NULL) {
1610                         dprintk(1,
1611                                 KERN_ERR
1612                                 "%s: setup_window() - Alloc of clip mask failed\n",
1613                                 ZR_DEVNAME(zr));
1614                         return -ENOMEM;
1615                 }
1616                 if (copy_from_user
1617                     (vcp, clips, sizeof(struct video_clip) * clipcount)) {
1618                         vfree(vcp);
1619                         return -EFAULT;
1620                 }
1621                 write_overlay_mask(file, vcp, clipcount);
1622                 vfree(vcp);
1623         }
1624
1625         fh->overlay_settings.is_set = 1;
1626         if (fh->overlay_active != ZORAN_FREE &&
1627             zr->overlay_active != ZORAN_FREE)
1628                 zr->overlay_settings = fh->overlay_settings;
1629
1630         if (on)
1631                 zr36057_overlay(zr, 1);
1632
1633         /* Make sure the changes come into effect */
1634         return wait_grab_pending(zr);
1635 }
1636
1637 static int
1638 setup_overlay (struct file *file,
1639                int          on)
1640 {
1641         struct zoran_fh *fh = file->private_data;
1642         struct zoran *zr = fh->zr;
1643
1644         /* If there is nothing to do, return immediatly */
1645         if ((on && fh->overlay_active != ZORAN_FREE) ||
1646             (!on && fh->overlay_active == ZORAN_FREE))
1647                 return 0;
1648
1649         /* check whether we're touching someone else's overlay */
1650         if (on && zr->overlay_active != ZORAN_FREE &&
1651             fh->overlay_active == ZORAN_FREE) {
1652                 dprintk(1,
1653                         KERN_ERR
1654                         "%s: setup_overlay() - overlay is already active for another session\n",
1655                         ZR_DEVNAME(zr));
1656                 return -EBUSY;
1657         }
1658         if (!on && zr->overlay_active != ZORAN_FREE &&
1659             fh->overlay_active == ZORAN_FREE) {
1660                 dprintk(1,
1661                         KERN_ERR
1662                         "%s: setup_overlay() - you cannot cancel someone else's session\n",
1663                         ZR_DEVNAME(zr));
1664                 return -EPERM;
1665         }
1666
1667         if (on == 0) {
1668                 zr->overlay_active = fh->overlay_active = ZORAN_FREE;
1669                 zr->v4l_overlay_active = 0;
1670                 /* When a grab is running, the video simply
1671                  * won't be switched on any more */
1672                 if (!zr->v4l_memgrab_active)
1673                         zr36057_overlay(zr, 0);
1674                 zr->overlay_mask = NULL;
1675         } else {
1676                 if (!zr->buffer.base || !fh->overlay_settings.is_set) {
1677                         dprintk(1,
1678                                 KERN_ERR
1679                                 "%s: setup_overlay() - buffer or window not set\n",
1680                                 ZR_DEVNAME(zr));
1681                         return -EINVAL;
1682                 }
1683                 if (!fh->overlay_settings.format) {
1684                         dprintk(1,
1685                                 KERN_ERR
1686                                 "%s: setup_overlay() - no overlay format set\n",
1687                                 ZR_DEVNAME(zr));
1688                         return -EINVAL;
1689                 }
1690                 zr->overlay_active = fh->overlay_active = ZORAN_LOCKED;
1691                 zr->v4l_overlay_active = 1;
1692                 zr->overlay_mask = fh->overlay_mask;
1693                 zr->overlay_settings = fh->overlay_settings;
1694                 if (!zr->v4l_memgrab_active)
1695                         zr36057_overlay(zr, 1);
1696                 /* When a grab is running, the video will be
1697                  * switched on when grab is finished */
1698         }
1699
1700         /* Make sure the changes come into effect */
1701         return wait_grab_pending(zr);
1702 }
1703
1704         /* get the status of a buffer in the clients buffer queue */
1705 static int
1706 zoran_v4l2_buffer_status (struct file        *file,
1707                           struct v4l2_buffer *buf,
1708                           int                 num)
1709 {
1710         struct zoran_fh *fh = file->private_data;
1711         struct zoran *zr = fh->zr;
1712
1713         buf->flags = V4L2_BUF_FLAG_MAPPED;
1714
1715         switch (fh->map_mode) {
1716         case ZORAN_MAP_MODE_RAW:
1717
1718                 /* check range */
1719                 if (num < 0 || num >= fh->v4l_buffers.num_buffers ||
1720                     !fh->v4l_buffers.allocated) {
1721                         dprintk(1,
1722                                 KERN_ERR
1723                                 "%s: v4l2_buffer_status() - wrong number or buffers not allocated\n",
1724                                 ZR_DEVNAME(zr));
1725                         return -EINVAL;
1726                 }
1727
1728                 buf->type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
1729                 buf->length = fh->v4l_buffers.buffer_size;
1730
1731                 /* get buffer */
1732                 buf->bytesused = fh->v4l_buffers.buffer[num].bs.length;
1733                 if (fh->v4l_buffers.buffer[num].state == BUZ_STATE_DONE ||
1734                     fh->v4l_buffers.buffer[num].state == BUZ_STATE_USER) {
1735                         buf->sequence = fh->v4l_buffers.buffer[num].bs.seq;
1736                         buf->flags |= V4L2_BUF_FLAG_DONE;
1737                         buf->timestamp =
1738                             fh->v4l_buffers.buffer[num].bs.timestamp;
1739                 } else {
1740                         buf->flags |= V4L2_BUF_FLAG_QUEUED;
1741                 }
1742
1743                 if (fh->v4l_settings.height <= BUZ_MAX_HEIGHT / 2)
1744                         buf->field = V4L2_FIELD_TOP;
1745                 else
1746                         buf->field = V4L2_FIELD_INTERLACED;
1747
1748                 break;
1749
1750         case ZORAN_MAP_MODE_JPG_REC:
1751         case ZORAN_MAP_MODE_JPG_PLAY:
1752
1753                 /* check range */
1754                 if (num < 0 || num >= fh->jpg_buffers.num_buffers ||
1755                     !fh->jpg_buffers.allocated) {
1756                         dprintk(1,
1757                                 KERN_ERR
1758                                 "%s: v4l2_buffer_status() - wrong number or buffers not allocated\n",
1759                                 ZR_DEVNAME(zr));
1760                         return -EINVAL;
1761                 }
1762
1763                 buf->type = (fh->map_mode == ZORAN_MAP_MODE_JPG_REC) ?
1764                               V4L2_BUF_TYPE_VIDEO_CAPTURE :
1765                               V4L2_BUF_TYPE_VIDEO_OUTPUT;
1766                 buf->length = fh->jpg_buffers.buffer_size;
1767
1768                 /* these variables are only written after frame has been captured */
1769                 if (fh->jpg_buffers.buffer[num].state == BUZ_STATE_DONE ||
1770                     fh->jpg_buffers.buffer[num].state == BUZ_STATE_USER) {
1771                         buf->sequence = fh->jpg_buffers.buffer[num].bs.seq;
1772                         buf->timestamp =
1773                             fh->jpg_buffers.buffer[num].bs.timestamp;
1774                         buf->bytesused =
1775                             fh->jpg_buffers.buffer[num].bs.length;
1776                         buf->flags |= V4L2_BUF_FLAG_DONE;
1777                 } else {
1778                         buf->flags |= V4L2_BUF_FLAG_QUEUED;
1779                 }
1780
1781                 /* which fields are these? */
1782                 if (fh->jpg_settings.TmpDcm != 1)
1783                         buf->field =
1784                             fh->jpg_settings.
1785                             odd_even ? V4L2_FIELD_TOP : V4L2_FIELD_BOTTOM;
1786                 else
1787                         buf->field =
1788                             fh->jpg_settings.
1789                             odd_even ? V4L2_FIELD_SEQ_TB :
1790                             V4L2_FIELD_SEQ_BT;
1791
1792                 break;
1793
1794         default:
1795
1796                 dprintk(5,
1797                         KERN_ERR
1798                         "%s: v4l2_buffer_status() - invalid buffer type|map_mode (%d|%d)\n",
1799                         ZR_DEVNAME(zr), buf->type, fh->map_mode);
1800                 return -EINVAL;
1801         }
1802
1803         buf->memory = V4L2_MEMORY_MMAP;
1804         buf->index = num;
1805         buf->m.offset = buf->length * num;
1806
1807         return 0;
1808 }
1809
1810 static int
1811 zoran_set_norm (struct zoran *zr,
1812                 int           norm) /* VIDEO_MODE_* */
1813 {
1814         int norm_encoder, on;
1815
1816         if (zr->v4l_buffers.active != ZORAN_FREE ||
1817             zr->jpg_buffers.active != ZORAN_FREE) {
1818                 dprintk(1,
1819                         KERN_WARNING
1820                         "%s: set_norm() called while in playback/capture mode\n",
1821                         ZR_DEVNAME(zr));
1822                 return -EBUSY;
1823         }
1824
1825         if (lock_norm && norm != zr->norm) {
1826                 if (lock_norm > 1) {
1827                         dprintk(1,
1828                                 KERN_WARNING
1829                                 "%s: set_norm() - TV standard is locked, can not switch norm\n",
1830                                 ZR_DEVNAME(zr));
1831                         return -EPERM;
1832                 } else {
1833                         dprintk(1,
1834                                 KERN_WARNING
1835                                 "%s: set_norm() - TV standard is locked, norm was not changed\n",
1836                                 ZR_DEVNAME(zr));
1837                         norm = zr->norm;
1838                 }
1839         }
1840
1841         if (norm != VIDEO_MODE_AUTO &&
1842             (norm < 0 || norm >= zr->card.norms ||
1843              !zr->card.tvn[norm])) {
1844                 dprintk(1,
1845                         KERN_ERR "%s: set_norm() - unsupported norm %d\n",
1846                         ZR_DEVNAME(zr), norm);
1847                 return -EINVAL;
1848         }
1849
1850         if (norm == VIDEO_MODE_AUTO) {
1851                 int status;
1852
1853                 /* if we have autodetect, ... */
1854                 struct video_decoder_capability caps;
1855                 decoder_command(zr, DECODER_GET_CAPABILITIES, &caps);
1856                 if (!(caps.flags & VIDEO_DECODER_AUTO)) {
1857                         dprintk(1, KERN_ERR "%s: norm=auto unsupported\n",
1858                                 ZR_DEVNAME(zr));
1859                         return -EINVAL;
1860                 }
1861
1862                 decoder_command(zr, DECODER_SET_NORM, &norm);
1863
1864                 /* let changes come into effect */
1865                 ssleep(2);
1866
1867                 decoder_command(zr, DECODER_GET_STATUS, &status);
1868                 if (!(status & DECODER_STATUS_GOOD)) {
1869                         dprintk(1,
1870                                 KERN_ERR
1871                                 "%s: set_norm() - no norm detected\n",
1872                                 ZR_DEVNAME(zr));
1873                         /* reset norm */
1874                         decoder_command(zr, DECODER_SET_NORM, &zr->norm);
1875                         return -EIO;
1876                 }
1877
1878                 if (status & DECODER_STATUS_NTSC)
1879                         norm = VIDEO_MODE_NTSC;
1880                 else if (status & DECODER_STATUS_SECAM)
1881                         norm = VIDEO_MODE_SECAM;
1882                 else
1883                         norm = VIDEO_MODE_PAL;
1884         }
1885         zr->timing = zr->card.tvn[norm];
1886         norm_encoder = norm;
1887
1888         /* We switch overlay off and on since a change in the
1889          * norm needs different VFE settings */
1890         on = zr->overlay_active && !zr->v4l_memgrab_active;
1891         if (on)
1892                 zr36057_overlay(zr, 0);
1893
1894         decoder_command(zr, DECODER_SET_NORM, &norm);
1895         encoder_command(zr, ENCODER_SET_NORM, &norm_encoder);
1896
1897         if (on)
1898                 zr36057_overlay(zr, 1);
1899
1900         /* Make sure the changes come into effect */
1901         zr->norm = norm;
1902
1903         return 0;
1904 }
1905
1906 static int
1907 zoran_set_input (struct zoran *zr,
1908                  int           input)
1909 {
1910         int realinput;
1911
1912         if (input == zr->input) {
1913                 return 0;
1914         }
1915
1916         if (zr->v4l_buffers.active != ZORAN_FREE ||
1917             zr->jpg_buffers.active != ZORAN_FREE) {
1918                 dprintk(1,
1919                         KERN_WARNING
1920                         "%s: set_input() called while in playback/capture mode\n",
1921                         ZR_DEVNAME(zr));
1922                 return -EBUSY;
1923         }
1924
1925         if (input < 0 || input >= zr->card.inputs) {
1926                 dprintk(1,
1927                         KERN_ERR
1928                         "%s: set_input() - unnsupported input %d\n",
1929                         ZR_DEVNAME(zr), input);
1930                 return -EINVAL;
1931         }
1932
1933         realinput = zr->card.input[input].muxsel;
1934         zr->input = input;
1935
1936         decoder_command(zr, DECODER_SET_INPUT, &realinput);
1937
1938         return 0;
1939 }
1940
1941 /*
1942  *   ioctl routine
1943  */
1944
1945 static int
1946 zoran_do_ioctl (struct inode *inode,
1947                 struct file  *file,
1948                 unsigned int  cmd,
1949                 void         *arg)
1950 {
1951         struct zoran_fh *fh = file->private_data;
1952         struct zoran *zr = fh->zr;
1953         /* CAREFUL: used in multiple places here */
1954         struct zoran_jpg_settings settings;
1955
1956         /* we might have older buffers lying around... We don't want
1957          * to wait, but we do want to try cleaning them up ASAP. So
1958          * we try to obtain the lock and free them. If that fails, we
1959          * don't do anything and wait for the next turn. In the end,
1960          * zoran_close() or a new allocation will still free them...
1961          * This is just a 'the sooner the better' extra 'feature'
1962          *
1963          * We don't free the buffers right on munmap() because that
1964          * causes oopses (kfree() inside munmap() oopses for no
1965          * apparent reason - it's also not reproduceable in any way,
1966          * but moving the free code outside the munmap() handler fixes
1967          * all this... If someone knows why, please explain me (Ronald)
1968          */
1969         if (mutex_trylock(&zr->resource_lock)) {
1970                 /* we obtained it! Let's try to free some things */
1971                 if (fh->jpg_buffers.ready_to_be_freed)
1972                         jpg_fbuffer_free(file);
1973                 if (fh->v4l_buffers.ready_to_be_freed)
1974                         v4l_fbuffer_free(file);
1975
1976                 mutex_unlock(&zr->resource_lock);
1977         }
1978
1979         switch (cmd) {
1980
1981         case VIDIOCGCAP:
1982         {
1983                 struct video_capability *vcap = arg;
1984
1985                 dprintk(3, KERN_DEBUG "%s: VIDIOCGCAP\n", ZR_DEVNAME(zr));
1986
1987                 memset(vcap, 0, sizeof(struct video_capability));
1988                 strncpy(vcap->name, ZR_DEVNAME(zr), sizeof(vcap->name)-1);
1989                 vcap->type = ZORAN_VID_TYPE;
1990
1991                 vcap->channels = zr->card.inputs;
1992                 vcap->audios = 0;
1993                 mutex_lock(&zr->resource_lock);
1994                 vcap->maxwidth = BUZ_MAX_WIDTH;
1995                 vcap->maxheight = BUZ_MAX_HEIGHT;
1996                 vcap->minwidth = BUZ_MIN_WIDTH;
1997                 vcap->minheight = BUZ_MIN_HEIGHT;
1998                 mutex_unlock(&zr->resource_lock);
1999
2000                 return 0;
2001         }
2002                 break;
2003
2004         case VIDIOCGCHAN:
2005         {
2006                 struct video_channel *vchan = arg;
2007                 int channel = vchan->channel;
2008
2009                 dprintk(3, KERN_DEBUG "%s: VIDIOCGCHAN - channel=%d\n",
2010                         ZR_DEVNAME(zr), vchan->channel);
2011
2012                 memset(vchan, 0, sizeof(struct video_channel));
2013                 if (channel > zr->card.inputs || channel < 0) {
2014                         dprintk(1,
2015                                 KERN_ERR
2016                                 "%s: VIDIOCGCHAN on not existing channel %d\n",
2017                                 ZR_DEVNAME(zr), channel);
2018                         return -EINVAL;
2019                 }
2020
2021                 strcpy(vchan->name, zr->card.input[channel].name);
2022
2023                 vchan->tuners = 0;
2024                 vchan->flags = 0;
2025                 vchan->type = VIDEO_TYPE_CAMERA;
2026                 mutex_lock(&zr->resource_lock);
2027                 vchan->norm = zr->norm;
2028                 mutex_unlock(&zr->resource_lock);
2029                 vchan->channel = channel;
2030
2031                 return 0;
2032         }
2033                 break;
2034
2035                 /* RJ: the documentation at http://roadrunner.swansea.linux.org.uk/v4lapi.shtml says:
2036                  *
2037                  * * "The VIDIOCSCHAN ioctl takes an integer argument and switches the capture to this input."
2038                  * *                                 ^^^^^^^
2039                  * * The famos BTTV driver has it implemented with a struct video_channel argument
2040                  * * and we follow it for compatibility reasons
2041                  * *
2042                  * * BTW: this is the only way the user can set the norm!
2043                  */
2044
2045         case VIDIOCSCHAN:
2046         {
2047                 struct video_channel *vchan = arg;
2048                 int res;
2049
2050                 dprintk(3,
2051                         KERN_DEBUG
2052                         "%s: VIDIOCSCHAN - channel=%d, norm=%d\n",
2053                         ZR_DEVNAME(zr), vchan->channel, vchan->norm);
2054
2055                 mutex_lock(&zr->resource_lock);
2056                 if ((res = zoran_set_input(zr, vchan->channel)))
2057                         goto schan_unlock_and_return;
2058                 if ((res = zoran_set_norm(zr, vchan->norm)))
2059                         goto schan_unlock_and_return;
2060
2061                 /* Make sure the changes come into effect */
2062                 res = wait_grab_pending(zr);
2063         schan_unlock_and_return:
2064                 mutex_unlock(&zr->resource_lock);
2065                 return res;
2066         }
2067                 break;
2068
2069         case VIDIOCGPICT:
2070         {
2071                 struct video_picture *vpict = arg;
2072
2073                 dprintk(3, KERN_DEBUG "%s: VIDIOCGPICT\n", ZR_DEVNAME(zr));
2074
2075                 memset(vpict, 0, sizeof(struct video_picture));
2076                 mutex_lock(&zr->resource_lock);
2077                 vpict->hue = zr->hue;
2078                 vpict->brightness = zr->brightness;
2079                 vpict->contrast = zr->contrast;
2080                 vpict->colour = zr->saturation;
2081                 if (fh->overlay_settings.format) {
2082                         vpict->depth = fh->overlay_settings.format->depth;
2083                         vpict->palette = fh->overlay_settings.format->palette;
2084                 } else {
2085                         vpict->depth = 0;
2086                 }
2087                 mutex_unlock(&zr->resource_lock);
2088
2089                 return 0;
2090         }
2091                 break;
2092
2093         case VIDIOCSPICT:
2094         {
2095                 struct video_picture *vpict = arg;
2096                 int i;
2097
2098                 dprintk(3,
2099                         KERN_DEBUG
2100                         "%s: VIDIOCSPICT - bri=%d, hue=%d, col=%d, con=%d, dep=%d, pal=%d\n",
2101                         ZR_DEVNAME(zr), vpict->brightness, vpict->hue,
2102                         vpict->colour, vpict->contrast, vpict->depth,
2103                         vpict->palette);
2104
2105                 for (i = 0; i < NUM_FORMATS; i++) {
2106                         const struct zoran_format *fmt = &zoran_formats[i];
2107
2108                         if (fmt->palette != -1 &&
2109                             fmt->flags & ZORAN_FORMAT_OVERLAY &&
2110                             fmt->palette == vpict->palette &&
2111                             fmt->depth == vpict->depth)
2112                                 break;
2113                 }
2114                 if (i == NUM_FORMATS) {
2115                         dprintk(1,
2116                                 KERN_ERR
2117                                 "%s: VIDIOCSPICT - Invalid palette %d\n",
2118                                 ZR_DEVNAME(zr), vpict->palette);
2119                         return -EINVAL;
2120                 }
2121
2122                 mutex_lock(&zr->resource_lock);
2123
2124                 decoder_command(zr, DECODER_SET_PICTURE, vpict);
2125
2126                 zr->hue = vpict->hue;
2127                 zr->contrast = vpict->contrast;
2128                 zr->saturation = vpict->colour;
2129                 zr->brightness = vpict->brightness;
2130
2131                 fh->overlay_settings.format = &zoran_formats[i];
2132
2133                 mutex_unlock(&zr->resource_lock);
2134
2135                 return 0;
2136         }
2137                 break;
2138
2139         case VIDIOCCAPTURE:
2140         {
2141                 int *on = arg, res;
2142
2143                 dprintk(3, KERN_DEBUG "%s: VIDIOCCAPTURE - on=%d\n",
2144                         ZR_DEVNAME(zr), *on);
2145
2146                 mutex_lock(&zr->resource_lock);
2147                 res = setup_overlay(file, *on);
2148                 mutex_unlock(&zr->resource_lock);
2149
2150                 return res;
2151         }
2152                 break;
2153
2154         case VIDIOCGWIN:
2155         {
2156                 struct video_window *vwin = arg;
2157
2158                 dprintk(3, KERN_DEBUG "%s: VIDIOCGWIN\n", ZR_DEVNAME(zr));
2159
2160                 memset(vwin, 0, sizeof(struct video_window));
2161                 mutex_lock(&zr->resource_lock);
2162                 vwin->x = fh->overlay_settings.x;
2163                 vwin->y = fh->overlay_settings.y;
2164                 vwin->width = fh->overlay_settings.width;
2165                 vwin->height = fh->overlay_settings.height;
2166                 mutex_unlock(&zr->resource_lock);
2167                 vwin->clipcount = 0;
2168                 return 0;
2169         }
2170                 break;
2171
2172         case VIDIOCSWIN:
2173         {
2174                 struct video_window *vwin = arg;
2175                 int res;
2176
2177                 dprintk(3,
2178                         KERN_DEBUG
2179                         "%s: VIDIOCSWIN - x=%d, y=%d, w=%d, h=%d, clipcount=%d\n",
2180                         ZR_DEVNAME(zr), vwin->x, vwin->y, vwin->width,
2181                         vwin->height, vwin->clipcount);
2182
2183                 mutex_lock(&zr->resource_lock);
2184                 res =
2185                     setup_window(file, vwin->x, vwin->y, vwin->width,
2186                                  vwin->height, vwin->clips,
2187                                  vwin->clipcount, NULL);
2188                 mutex_unlock(&zr->resource_lock);
2189
2190                 return res;
2191         }
2192                 break;
2193
2194         case VIDIOCGFBUF:
2195         {
2196                 struct video_buffer *vbuf = arg;
2197
2198                 dprintk(3, KERN_DEBUG "%s: VIDIOCGFBUF\n", ZR_DEVNAME(zr));
2199
2200                 mutex_lock(&zr->resource_lock);
2201                 *vbuf = zr->buffer;
2202                 mutex_unlock(&zr->resource_lock);
2203                 return 0;
2204         }
2205                 break;
2206
2207         case VIDIOCSFBUF:
2208         {
2209                 struct video_buffer *vbuf = arg;
2210                 int i, res = 0;
2211
2212                 dprintk(3,
2213                         KERN_DEBUG
2214                         "%s: VIDIOCSFBUF - base=%p, w=%d, h=%d, depth=%d, bpl=%d\n",
2215                         ZR_DEVNAME(zr), vbuf->base, vbuf->width,
2216                         vbuf->height, vbuf->depth, vbuf->bytesperline);
2217
2218                 for (i = 0; i < NUM_FORMATS; i++)
2219                         if (zoran_formats[i].depth == vbuf->depth)
2220                                 break;
2221                 if (i == NUM_FORMATS) {
2222                         dprintk(1,
2223                                 KERN_ERR
2224                                 "%s: VIDIOCSFBUF - invalid fbuf depth %d\n",
2225                                 ZR_DEVNAME(zr), vbuf->depth);
2226                         return -EINVAL;
2227                 }
2228
2229                 mutex_lock(&zr->resource_lock);
2230                 res =
2231                     setup_fbuffer(file, vbuf->base, &zoran_formats[i],
2232                                   vbuf->width, vbuf->height,
2233                                   vbuf->bytesperline);
2234                 mutex_unlock(&zr->resource_lock);
2235
2236                 return res;
2237         }
2238                 break;
2239
2240         case VIDIOCSYNC:
2241         {
2242                 int *frame = arg, res;
2243
2244                 dprintk(3, KERN_DEBUG "%s: VIDIOCSYNC - frame=%d\n",
2245                         ZR_DEVNAME(zr), *frame);
2246
2247                 mutex_lock(&zr->resource_lock);
2248                 res = v4l_sync(file, *frame);
2249                 mutex_unlock(&zr->resource_lock);
2250                 if (!res)
2251                         zr->v4l_sync_tail++;
2252                 return res;
2253         }
2254                 break;
2255
2256         case VIDIOCMCAPTURE:
2257         {
2258                 struct video_mmap *vmap = arg;
2259                 int res;
2260
2261                 dprintk(3,
2262                         KERN_DEBUG
2263                         "%s: VIDIOCMCAPTURE - frame=%d, geom=%dx%d, fmt=%d\n",
2264                         ZR_DEVNAME(zr), vmap->frame, vmap->width, vmap->height,
2265                         vmap->format);
2266
2267                 mutex_lock(&zr->resource_lock);
2268                 res = v4l_grab(file, vmap);
2269                 mutex_unlock(&zr->resource_lock);
2270                 return res;
2271         }
2272                 break;
2273
2274         case VIDIOCGMBUF:
2275         {
2276                 struct video_mbuf *vmbuf = arg;
2277                 int i, res = 0;
2278
2279                 dprintk(3, KERN_DEBUG "%s: VIDIOCGMBUF\n", ZR_DEVNAME(zr));
2280
2281                 vmbuf->size =
2282                     fh->v4l_buffers.num_buffers *
2283                     fh->v4l_buffers.buffer_size;
2284                 vmbuf->frames = fh->v4l_buffers.num_buffers;
2285                 for (i = 0; i < vmbuf->frames; i++) {
2286                         vmbuf->offsets[i] =
2287                             i * fh->v4l_buffers.buffer_size;
2288                 }
2289
2290                 mutex_lock(&zr->resource_lock);
2291
2292                 if (fh->jpg_buffers.allocated || fh->v4l_buffers.allocated) {
2293                         dprintk(1,
2294                                 KERN_ERR
2295                                 "%s: VIDIOCGMBUF - buffers already allocated\n",
2296                                 ZR_DEVNAME(zr));
2297                         res = -EINVAL;
2298                         goto v4l1reqbuf_unlock_and_return;
2299                 }
2300
2301                 if (v4l_fbuffer_alloc(file)) {
2302                         res = -ENOMEM;
2303                         goto v4l1reqbuf_unlock_and_return;
2304                 }
2305
2306                 /* The next mmap will map the V4L buffers */
2307                 fh->map_mode = ZORAN_MAP_MODE_RAW;
2308         v4l1reqbuf_unlock_and_return:
2309                 mutex_unlock(&zr->resource_lock);
2310
2311                 return res;
2312         }
2313                 break;
2314
2315         case VIDIOCGUNIT:
2316         {
2317                 struct video_unit *vunit = arg;
2318
2319                 dprintk(3, KERN_DEBUG "%s: VIDIOCGUNIT\n", ZR_DEVNAME(zr));
2320
2321                 vunit->video = zr->video_dev->minor;
2322                 vunit->vbi = VIDEO_NO_UNIT;
2323                 vunit->radio = VIDEO_NO_UNIT;
2324                 vunit->audio = VIDEO_NO_UNIT;
2325                 vunit->teletext = VIDEO_NO_UNIT;
2326
2327                 return 0;
2328         }
2329                 break;
2330
2331                 /*
2332                  * RJ: In principal we could support subcaptures for V4L grabbing.
2333                  *     Not even the famous BTTV driver has them, however.
2334                  *     If there should be a strong demand, one could consider
2335                  *     to implement them.
2336                  */
2337         case VIDIOCGCAPTURE:
2338         {
2339                 dprintk(3, KERN_ERR "%s: VIDIOCGCAPTURE not supported\n",
2340                         ZR_DEVNAME(zr));
2341                 return -EINVAL;
2342         }
2343                 break;
2344
2345         case VIDIOCSCAPTURE:
2346         {
2347                 dprintk(3, KERN_ERR "%s: VIDIOCSCAPTURE not supported\n",
2348                         ZR_DEVNAME(zr));
2349                 return -EINVAL;
2350         }
2351                 break;
2352
2353         case BUZIOC_G_PARAMS:
2354         {
2355                 struct zoran_params *bparams = arg;
2356
2357                 dprintk(3, KERN_DEBUG "%s: BUZIOC_G_PARAMS\n", ZR_DEVNAME(zr));
2358
2359                 memset(bparams, 0, sizeof(struct zoran_params));
2360                 bparams->major_version = MAJOR_VERSION;
2361                 bparams->minor_version = MINOR_VERSION;
2362
2363                 mutex_lock(&zr->resource_lock);
2364
2365                 bparams->norm = zr->norm;
2366                 bparams->input = zr->input;
2367
2368                 bparams->decimation = fh->jpg_settings.decimation;
2369                 bparams->HorDcm = fh->jpg_settings.HorDcm;
2370                 bparams->VerDcm = fh->jpg_settings.VerDcm;
2371                 bparams->TmpDcm = fh->jpg_settings.TmpDcm;
2372                 bparams->field_per_buff = fh->jpg_settings.field_per_buff;
2373                 bparams->img_x = fh->jpg_settings.img_x;
2374                 bparams->img_y = fh->jpg_settings.img_y;
2375                 bparams->img_width = fh->jpg_settings.img_width;
2376                 bparams->img_height = fh->jpg_settings.img_height;
2377                 bparams->odd_even = fh->jpg_settings.odd_even;
2378
2379                 bparams->quality = fh->jpg_settings.jpg_comp.quality;
2380                 bparams->APPn = fh->jpg_settings.jpg_comp.APPn;
2381                 bparams->APP_len = fh->jpg_settings.jpg_comp.APP_len;
2382                 memcpy(bparams->APP_data,
2383                        fh->jpg_settings.jpg_comp.APP_data,
2384                        sizeof(bparams->APP_data));
2385                 bparams->COM_len = zr->jpg_settings.jpg_comp.COM_len;
2386                 memcpy(bparams->COM_data,
2387                        fh->jpg_settings.jpg_comp.COM_data,
2388                        sizeof(bparams->COM_data));
2389                 bparams->jpeg_markers =
2390                     fh->jpg_settings.jpg_comp.jpeg_markers;
2391
2392                 mutex_unlock(&zr->resource_lock);
2393
2394                 bparams->VFIFO_FB = 0;
2395
2396                 return 0;
2397         }
2398                 break;
2399
2400         case BUZIOC_S_PARAMS:
2401         {
2402                 struct zoran_params *bparams = arg;
2403                 int res = 0;
2404
2405                 dprintk(3, KERN_DEBUG "%s: BUZIOC_S_PARAMS\n", ZR_DEVNAME(zr));
2406
2407                 settings.decimation = bparams->decimation;
2408                 settings.HorDcm = bparams->HorDcm;
2409                 settings.VerDcm = bparams->VerDcm;
2410                 settings.TmpDcm = bparams->TmpDcm;
2411                 settings.field_per_buff = bparams->field_per_buff;
2412                 settings.img_x = bparams->img_x;
2413                 settings.img_y = bparams->img_y;
2414                 settings.img_width = bparams->img_width;
2415                 settings.img_height = bparams->img_height;
2416                 settings.odd_even = bparams->odd_even;
2417
2418                 settings.jpg_comp.quality = bparams->quality;
2419                 settings.jpg_comp.APPn = bparams->APPn;
2420                 settings.jpg_comp.APP_len = bparams->APP_len;
2421                 memcpy(settings.jpg_comp.APP_data, bparams->APP_data,
2422                        sizeof(bparams->APP_data));
2423                 settings.jpg_comp.COM_len = bparams->COM_len;
2424                 memcpy(settings.jpg_comp.COM_data, bparams->COM_data,
2425                        sizeof(bparams->COM_data));
2426                 settings.jpg_comp.jpeg_markers = bparams->jpeg_markers;
2427
2428                 mutex_lock(&zr->resource_lock);
2429
2430                 if (zr->codec_mode != BUZ_MODE_IDLE) {
2431                         dprintk(1,
2432                                 KERN_ERR
2433                                 "%s: BUZIOC_S_PARAMS called, but Buz in capture/playback mode\n",
2434                                 ZR_DEVNAME(zr));
2435                         res = -EINVAL;
2436                         goto sparams_unlock_and_return;
2437                 }
2438
2439                 /* Check the params first before overwriting our
2440                  * nternal values */
2441                 if (zoran_check_jpg_settings(zr, &settings)) {
2442                         res = -EINVAL;
2443                         goto sparams_unlock_and_return;
2444                 }
2445
2446                 fh->jpg_settings = settings;
2447         sparams_unlock_and_return:
2448                 mutex_unlock(&zr->resource_lock);
2449
2450                 return res;
2451         }
2452                 break;
2453
2454         case BUZIOC_REQBUFS:
2455         {
2456                 struct zoran_requestbuffers *breq = arg;
2457                 int res = 0;
2458
2459                 dprintk(3,
2460                         KERN_DEBUG
2461                         "%s: BUZIOC_REQBUFS - count=%lu, size=%lu\n",
2462                         ZR_DEVNAME(zr), breq->count, breq->size);
2463
2464                 /* Enforce reasonable lower and upper limits */
2465                 if (breq->count < 4)
2466                         breq->count = 4;        /* Could be choosen smaller */
2467                 if (breq->count > jpg_nbufs)
2468                         breq->count = jpg_nbufs;
2469                 breq->size = PAGE_ALIGN(breq->size);
2470                 if (breq->size < 8192)
2471                         breq->size = 8192;      /* Arbitrary */
2472                 /* breq->size is limited by 1 page for the stat_com
2473                  * tables to a Maximum of 2 MB */
2474                 if (breq->size > jpg_bufsize)
2475                         breq->size = jpg_bufsize;
2476                 if (fh->jpg_buffers.need_contiguous &&
2477                     breq->size > MAX_KMALLOC_MEM)
2478                         breq->size = MAX_KMALLOC_MEM;
2479
2480                 mutex_lock(&zr->resource_lock);
2481
2482                 if (fh->jpg_buffers.allocated || fh->v4l_buffers.allocated) {
2483                         dprintk(1,
2484                                 KERN_ERR
2485                                 "%s: BUZIOC_REQBUFS - buffers allready allocated\n",
2486                                 ZR_DEVNAME(zr));
2487                         res = -EBUSY;
2488                         goto jpgreqbuf_unlock_and_return;
2489                 }
2490
2491                 fh->jpg_buffers.num_buffers = breq->count;
2492                 fh->jpg_buffers.buffer_size = breq->size;
2493
2494                 if (jpg_fbuffer_alloc(file)) {
2495                         res = -ENOMEM;
2496                         goto jpgreqbuf_unlock_and_return;
2497                 }
2498
2499                 /* The next mmap will map the MJPEG buffers - could
2500                  * also be *_PLAY, but it doesn't matter here */
2501                 fh->map_mode = ZORAN_MAP_MODE_JPG_REC;
2502         jpgreqbuf_unlock_and_return:
2503                 mutex_unlock(&zr->resource_lock);
2504
2505                 return res;
2506         }
2507                 break;
2508
2509         case BUZIOC_QBUF_CAPT:
2510         {
2511                 int *frame = arg, res;
2512
2513                 dprintk(3, KERN_DEBUG "%s: BUZIOC_QBUF_CAPT - frame=%d\n",
2514                         ZR_DEVNAME(zr), *frame);
2515
2516                 mutex_lock(&zr->resource_lock);
2517                 res = jpg_qbuf(file, *frame, BUZ_MODE_MOTION_COMPRESS);
2518                 mutex_unlock(&zr->resource_lock);
2519
2520                 return res;
2521         }
2522                 break;
2523
2524         case BUZIOC_QBUF_PLAY:
2525         {
2526                 int *frame = arg, res;
2527
2528                 dprintk(3, KERN_DEBUG "%s: BUZIOC_QBUF_PLAY - frame=%d\n",
2529                         ZR_DEVNAME(zr), *frame);
2530
2531                 mutex_lock(&zr->resource_lock);
2532                 res = jpg_qbuf(file, *frame, BUZ_MODE_MOTION_DECOMPRESS);
2533                 mutex_unlock(&zr->resource_lock);
2534
2535                 return res;
2536         }
2537                 break;
2538
2539         case BUZIOC_SYNC:
2540         {
2541                 struct zoran_sync *bsync = arg;
2542                 int res;
2543
2544                 dprintk(3, KERN_DEBUG "%s: BUZIOC_SYNC\n", ZR_DEVNAME(zr));
2545
2546                 mutex_lock(&zr->resource_lock);
2547                 res = jpg_sync(file, bsync);
2548                 mutex_unlock(&zr->resource_lock);
2549
2550                 return res;
2551         }
2552                 break;
2553
2554         case BUZIOC_G_STATUS:
2555         {
2556                 struct zoran_status *bstat = arg;
2557                 int norm, input, status, res = 0;
2558
2559                 dprintk(3, KERN_DEBUG "%s: BUZIOC_G_STATUS\n", ZR_DEVNAME(zr));
2560
2561                 if (zr->codec_mode != BUZ_MODE_IDLE) {
2562                         dprintk(1,
2563                                 KERN_ERR
2564                                 "%s: BUZIOC_G_STATUS called but Buz in capture/playback mode\n",
2565                                 ZR_DEVNAME(zr));
2566                         return -EINVAL;
2567                 }
2568
2569                 input = zr->card.input[bstat->input].muxsel;
2570                 norm = VIDEO_MODE_AUTO;
2571
2572                 mutex_lock(&zr->resource_lock);
2573
2574                 if (zr->codec_mode != BUZ_MODE_IDLE) {
2575                         dprintk(1,
2576                                 KERN_ERR
2577                                 "%s: BUZIOC_G_STATUS called, but Buz in capture/playback mode\n",
2578                                 ZR_DEVNAME(zr));
2579                         res = -EINVAL;
2580                         goto gstat_unlock_and_return;
2581                 }
2582
2583                 decoder_command(zr, DECODER_SET_INPUT, &input);
2584                 decoder_command(zr, DECODER_SET_NORM, &norm);
2585
2586                 /* sleep 1 second */
2587                 ssleep(1);
2588
2589                 /* Get status of video decoder */
2590                 decoder_command(zr, DECODER_GET_STATUS, &status);
2591
2592                 /* restore previous input and norm */
2593                 input = zr->card.input[zr->input].muxsel;
2594                 decoder_command(zr, DECODER_SET_INPUT, &input);
2595                 decoder_command(zr, DECODER_SET_NORM, &zr->norm);
2596         gstat_unlock_and_return:
2597                 mutex_unlock(&zr->resource_lock);
2598
2599                 if (!res) {
2600                         bstat->signal =
2601                             (status & DECODER_STATUS_GOOD) ? 1 : 0;
2602                         if (status & DECODER_STATUS_NTSC)
2603                                 bstat->norm = VIDEO_MODE_NTSC;
2604                         else if (status & DECODER_STATUS_SECAM)
2605                                 bstat->norm = VIDEO_MODE_SECAM;
2606                         else
2607                                 bstat->norm = VIDEO_MODE_PAL;
2608
2609                         bstat->color =
2610                             (status & DECODER_STATUS_COLOR) ? 1 : 0;
2611                 }
2612
2613                 return res;
2614         }
2615                 break;
2616
2617                 /* The new video4linux2 capture interface - much nicer than video4linux1, since
2618                  * it allows for integrating the JPEG capturing calls inside standard v4l2
2619                  */
2620
2621         case VIDIOC_QUERYCAP:
2622         {
2623                 struct v4l2_capability *cap = arg;
2624
2625                 dprintk(3, KERN_DEBUG "%s: VIDIOC_QUERYCAP\n", ZR_DEVNAME(zr));
2626
2627                 memset(cap, 0, sizeof(*cap));
2628                 strncpy(cap->card, ZR_DEVNAME(zr), sizeof(cap->card)-1);
2629                 strncpy(cap->driver, "zoran", sizeof(cap->driver)-1);
2630                 snprintf(cap->bus_info, sizeof(cap->bus_info), "PCI:%s",
2631                          pci_name(zr->pci_dev));
2632                 cap->version =
2633                     KERNEL_VERSION(MAJOR_VERSION, MINOR_VERSION,
2634                                    RELEASE_VERSION);
2635                 cap->capabilities = ZORAN_V4L2_VID_FLAGS;
2636
2637                 return 0;
2638         }
2639                 break;
2640
2641         case VIDIOC_ENUM_FMT:
2642         {
2643                 struct v4l2_fmtdesc *fmt = arg;
2644                 int index = fmt->index, num = -1, i, flag = 0, type =
2645                     fmt->type;
2646
2647                 dprintk(3, KERN_DEBUG "%s: VIDIOC_ENUM_FMT - index=%d\n",
2648                         ZR_DEVNAME(zr), fmt->index);
2649
2650                 switch (fmt->type) {
2651                 case V4L2_BUF_TYPE_VIDEO_CAPTURE:
2652                         flag = ZORAN_FORMAT_CAPTURE;
2653                         break;
2654                 case V4L2_BUF_TYPE_VIDEO_OUTPUT:
2655                         flag = ZORAN_FORMAT_PLAYBACK;
2656                         break;
2657                 case V4L2_BUF_TYPE_VIDEO_OVERLAY:
2658                         flag = ZORAN_FORMAT_OVERLAY;
2659                         break;
2660                 default:
2661                         dprintk(1,
2662                                 KERN_ERR
2663                                 "%s: VIDIOC_ENUM_FMT - unknown type %d\n",
2664                                 ZR_DEVNAME(zr), fmt->type);
2665                         return -EINVAL;
2666                 }
2667
2668                 for (i = 0; i < NUM_FORMATS; i++) {
2669                         if (zoran_formats[i].flags & flag)
2670                                 num++;
2671                         if (num == fmt->index)
2672                                 break;
2673                 }
2674                 if (fmt->index < 0 /* late, but not too late */  ||
2675                     i == NUM_FORMATS)
2676                         return -EINVAL;
2677
2678                 memset(fmt, 0, sizeof(*fmt));
2679                 fmt->index = index;
2680                 fmt->type = type;
2681                 strncpy(fmt->description, zoran_formats[i].name, sizeof(fmt->description)-1);
2682                 fmt->pixelformat = zoran_formats[i].fourcc;
2683                 if (zoran_formats[i].flags & ZORAN_FORMAT_COMPRESSED)
2684                         fmt->flags |= V4L2_FMT_FLAG_COMPRESSED;
2685
2686                 return 0;
2687         }
2688                 break;
2689
2690         case VIDIOC_G_FMT:
2691         {
2692                 struct v4l2_format *fmt = arg;
2693                 int type = fmt->type;
2694
2695                 dprintk(5, KERN_DEBUG "%s: VIDIOC_G_FMT\n", ZR_DEVNAME(zr));
2696
2697                 memset(fmt, 0, sizeof(*fmt));
2698                 fmt->type = type;
2699
2700                 switch (fmt->type) {
2701                 case V4L2_BUF_TYPE_VIDEO_OVERLAY:
2702
2703                         mutex_lock(&zr->resource_lock);
2704
2705                         fmt->fmt.win.w.left = fh->overlay_settings.x;
2706                         fmt->fmt.win.w.top = fh->overlay_settings.y;
2707                         fmt->fmt.win.w.width = fh->overlay_settings.width;
2708                         fmt->fmt.win.w.height =
2709                             fh->overlay_settings.height;
2710                         if (fh->overlay_settings.width * 2 >
2711                             BUZ_MAX_HEIGHT)
2712                                 fmt->fmt.win.field = V4L2_FIELD_INTERLACED;
2713                         else
2714                                 fmt->fmt.win.field = V4L2_FIELD_TOP;
2715
2716                         mutex_unlock(&zr->resource_lock);
2717
2718                         break;
2719
2720                 case V4L2_BUF_TYPE_VIDEO_CAPTURE:
2721                 case V4L2_BUF_TYPE_VIDEO_OUTPUT:
2722
2723                         mutex_lock(&zr->resource_lock);
2724
2725                         if (fmt->type == V4L2_BUF_TYPE_VIDEO_CAPTURE &&
2726                             fh->map_mode == ZORAN_MAP_MODE_RAW) {
2727
2728                                 fmt->fmt.pix.width =
2729                                     fh->v4l_settings.width;
2730                                 fmt->fmt.pix.height =
2731                                     fh->v4l_settings.height;
2732                                 fmt->fmt.pix.sizeimage =
2733                                     fh->v4l_settings.bytesperline *
2734                                     fh->v4l_settings.height;
2735                                 fmt->fmt.pix.pixelformat =
2736                                     fh->v4l_settings.format->fourcc;
2737                                 fmt->fmt.pix.colorspace =
2738                                     fh->v4l_settings.format->colorspace;
2739                                 fmt->fmt.pix.bytesperline = 0;
2740                                 if (BUZ_MAX_HEIGHT <
2741                                     (fh->v4l_settings.height * 2))
2742                                         fmt->fmt.pix.field =
2743                                             V4L2_FIELD_INTERLACED;
2744                                 else
2745                                         fmt->fmt.pix.field =
2746                                             V4L2_FIELD_TOP;
2747
2748                         } else {
2749
2750                                 fmt->fmt.pix.width =
2751                                     fh->jpg_settings.img_width /
2752                                     fh->jpg_settings.HorDcm;
2753                                 fmt->fmt.pix.height =
2754                                     fh->jpg_settings.img_height /
2755                                     (fh->jpg_settings.VerDcm *
2756                                      fh->jpg_settings.TmpDcm);
2757                                 fmt->fmt.pix.sizeimage =
2758                                     zoran_v4l2_calc_bufsize(&fh->
2759                                                             jpg_settings);
2760                                 fmt->fmt.pix.pixelformat =
2761                                     V4L2_PIX_FMT_MJPEG;
2762                                 if (fh->jpg_settings.TmpDcm == 1)
2763                                         fmt->fmt.pix.field =
2764                                             (fh->jpg_settings.
2765                                              odd_even ? V4L2_FIELD_SEQ_BT :
2766                                              V4L2_FIELD_SEQ_BT);
2767                                 else
2768                                         fmt->fmt.pix.field =
2769                                             (fh->jpg_settings.
2770                                              odd_even ? V4L2_FIELD_TOP :
2771                                              V4L2_FIELD_BOTTOM);
2772
2773                                 fmt->fmt.pix.bytesperline = 0;
2774                                 fmt->fmt.pix.colorspace =
2775                                     V4L2_COLORSPACE_SMPTE170M;
2776                         }
2777
2778                         mutex_unlock(&zr->resource_lock);
2779
2780                         break;
2781
2782                 default:
2783                         dprintk(1,
2784                                 KERN_ERR
2785                                 "%s: VIDIOC_G_FMT - unsupported type %d\n",
2786                                 ZR_DEVNAME(zr), fmt->type);
2787                         return -EINVAL;
2788                 }
2789                 return 0;
2790         }
2791                 break;
2792
2793         case VIDIOC_S_FMT:
2794         {
2795                 struct v4l2_format *fmt = arg;
2796                 int i, res = 0;
2797                 __u32 printformat;
2798
2799                 dprintk(3, KERN_DEBUG "%s: VIDIOC_S_FMT - type=%d, ",
2800                         ZR_DEVNAME(zr), fmt->type);
2801
2802                 switch (fmt->type) {
2803                 case V4L2_BUF_TYPE_VIDEO_OVERLAY:
2804
2805                         dprintk(3, "x=%d, y=%d, w=%d, h=%d, cnt=%d, map=0x%p\n",
2806                                 fmt->fmt.win.w.left, fmt->fmt.win.w.top,
2807                                 fmt->fmt.win.w.width,
2808                                 fmt->fmt.win.w.height,
2809                                 fmt->fmt.win.clipcount,
2810                                 fmt->fmt.win.bitmap);
2811                         mutex_lock(&zr->resource_lock);
2812                         res =
2813                             setup_window(file, fmt->fmt.win.w.left,
2814                                          fmt->fmt.win.w.top,
2815                                          fmt->fmt.win.w.width,
2816                                          fmt->fmt.win.w.height,
2817                                          (struct video_clip __user *)
2818                                            fmt->fmt.win.clips,
2819                                          fmt->fmt.win.clipcount,
2820                                          fmt->fmt.win.bitmap);
2821                         mutex_unlock(&zr->resource_lock);
2822                         return res;
2823                         break;
2824
2825                 case V4L2_BUF_TYPE_VIDEO_CAPTURE:
2826                 case V4L2_BUF_TYPE_VIDEO_OUTPUT:
2827
2828                         printformat =
2829                             __cpu_to_le32(fmt->fmt.pix.pixelformat);
2830                         dprintk(3, "size=%dx%d, fmt=0x%x (%4.4s)\n",
2831                                 fmt->fmt.pix.width, fmt->fmt.pix.height,
2832                                 fmt->fmt.pix.pixelformat,
2833                                 (char *) &printformat);
2834
2835                         if (fmt->fmt.pix.bytesperline > 0) {
2836                                 dprintk(5,
2837                                         KERN_ERR "%s: bpl not supported\n",
2838                                         ZR_DEVNAME(zr));
2839                                 return -EINVAL;
2840                         }
2841
2842                         /* we can be requested to do JPEG/raw playback/capture */
2843                         if (!
2844                             (fmt->type == V4L2_BUF_TYPE_VIDEO_CAPTURE ||
2845                              (fmt->type == V4L2_BUF_TYPE_VIDEO_OUTPUT &&
2846                               fmt->fmt.pix.pixelformat ==
2847                               V4L2_PIX_FMT_MJPEG))) {
2848                                 dprintk(1,
2849                                         KERN_ERR
2850                                         "%s: VIDIOC_S_FMT - unknown type %d/0x%x(%4.4s) combination\n",
2851                                         ZR_DEVNAME(zr), fmt->type,
2852                                         fmt->fmt.pix.pixelformat,
2853                                         (char *) &printformat);
2854                                 return -EINVAL;
2855                         }
2856
2857                         if (fmt->fmt.pix.pixelformat == V4L2_PIX_FMT_MJPEG) {
2858                                 mutex_lock(&zr->resource_lock);
2859
2860                                 settings = fh->jpg_settings;
2861
2862                                 if (fh->v4l_buffers.allocated ||
2863                                     fh->jpg_buffers.allocated) {
2864                                         dprintk(1,
2865                                                 KERN_ERR
2866                                                 "%s: VIDIOC_S_FMT - cannot change capture mode\n",
2867                                                 ZR_DEVNAME(zr));
2868                                         res = -EBUSY;
2869                                         goto sfmtjpg_unlock_and_return;
2870                                 }
2871
2872                                 /* we actually need to set 'real' parameters now */
2873                                 if ((fmt->fmt.pix.height * 2) >
2874                                     BUZ_MAX_HEIGHT)
2875                                         settings.TmpDcm = 1;
2876                                 else
2877                                         settings.TmpDcm = 2;
2878                                 settings.decimation = 0;
2879                                 if (fmt->fmt.pix.height <=
2880                                     fh->jpg_settings.img_height / 2)
2881                                         settings.VerDcm = 2;
2882                                 else
2883                                         settings.VerDcm = 1;
2884                                 if (fmt->fmt.pix.width <=
2885                                     fh->jpg_settings.img_width / 4)
2886                                         settings.HorDcm = 4;
2887                                 else if (fmt->fmt.pix.width <=
2888                                          fh->jpg_settings.img_width / 2)
2889                                         settings.HorDcm = 2;
2890                                 else
2891                                         settings.HorDcm = 1;
2892                                 if (settings.TmpDcm == 1)
2893                                         settings.field_per_buff = 2;
2894                                 else
2895                                         settings.field_per_buff = 1;
2896
2897                                 /* check */
2898                                 if ((res =
2899                                      zoran_check_jpg_settings(zr,
2900                                                               &settings)))
2901                                         goto sfmtjpg_unlock_and_return;
2902
2903                                 /* it's ok, so set them */
2904                                 fh->jpg_settings = settings;
2905
2906                                 /* tell the user what we actually did */
2907                                 fmt->fmt.pix.width =
2908                                     settings.img_width / settings.HorDcm;
2909                                 fmt->fmt.pix.height =
2910                                     settings.img_height * 2 /
2911                                     (settings.TmpDcm * settings.VerDcm);
2912                                 if (settings.TmpDcm == 1)
2913                                         fmt->fmt.pix.field =
2914                                             (fh->jpg_settings.
2915                                              odd_even ? V4L2_FIELD_SEQ_TB :
2916                                              V4L2_FIELD_SEQ_BT);
2917                                 else
2918                                         fmt->fmt.pix.field =
2919                                             (fh->jpg_settings.
2920                                              odd_even ? V4L2_FIELD_TOP :
2921                                              V4L2_FIELD_BOTTOM);
2922                                 fh->jpg_buffers.buffer_size =
2923                                     zoran_v4l2_calc_bufsize(&fh->
2924                                                             jpg_settings);
2925                                 fmt->fmt.pix.sizeimage =
2926                                     fh->jpg_buffers.buffer_size;
2927
2928                                 /* we hereby abuse this variable to show that
2929                                  * we're gonna do mjpeg capture */
2930                                 fh->map_mode =
2931                                     (fmt->type ==
2932                                      V4L2_BUF_TYPE_VIDEO_CAPTURE) ?
2933                                     ZORAN_MAP_MODE_JPG_REC :
2934                                     ZORAN_MAP_MODE_JPG_PLAY;
2935                         sfmtjpg_unlock_and_return:
2936                                 mutex_unlock(&zr->resource_lock);
2937                         } else {
2938                                 for (i = 0; i < NUM_FORMATS; i++)
2939                                         if (fmt->fmt.pix.pixelformat ==
2940                                             zoran_formats[i].fourcc)
2941                                                 break;
2942                                 if (i == NUM_FORMATS) {
2943                                         dprintk(1,
2944                                                 KERN_ERR
2945                                                 "%s: VIDIOC_S_FMT - unknown/unsupported format 0x%x (%4.4s)\n",
2946                                                 ZR_DEVNAME(zr),
2947                                                 fmt->fmt.pix.pixelformat,
2948                                                 (char *) &printformat);
2949                                         return -EINVAL;
2950                                 }
2951                                 mutex_lock(&zr->resource_lock);
2952                                 if (fh->jpg_buffers.allocated ||
2953                                     (fh->v4l_buffers.allocated &&
2954                                      fh->v4l_buffers.active !=
2955                                      ZORAN_FREE)) {
2956                                         dprintk(1,
2957                                                 KERN_ERR
2958                                                 "%s: VIDIOC_S_FMT - cannot change capture mode\n",
2959                                                 ZR_DEVNAME(zr));
2960                                         res = -EBUSY;
2961                                         goto sfmtv4l_unlock_and_return;
2962                                 }
2963                                 if (fmt->fmt.pix.height > BUZ_MAX_HEIGHT)
2964                                         fmt->fmt.pix.height =
2965                                             BUZ_MAX_HEIGHT;
2966                                 if (fmt->fmt.pix.width > BUZ_MAX_WIDTH)
2967                                         fmt->fmt.pix.width = BUZ_MAX_WIDTH;
2968
2969                                 if ((res =
2970                                      zoran_v4l_set_format(file,
2971                                                           fmt->fmt.pix.
2972                                                           width,
2973                                                           fmt->fmt.pix.
2974                                                           height,
2975                                                           &zoran_formats
2976                                                           [i])))
2977                                         goto sfmtv4l_unlock_and_return;
2978
2979                                 /* tell the user the
2980                                  * results/missing stuff */
2981                                 fmt->fmt.pix.sizeimage =
2982                                         fh->v4l_settings.height *
2983                                         fh->v4l_settings.bytesperline;
2984                                 if (BUZ_MAX_HEIGHT <
2985                                     (fh->v4l_settings.height * 2))
2986                                         fmt->fmt.pix.field =
2987                                             V4L2_FIELD_INTERLACED;
2988                                 else
2989                                         fmt->fmt.pix.field =
2990                                             V4L2_FIELD_TOP;
2991
2992                                 fh->map_mode = ZORAN_MAP_MODE_RAW;
2993                         sfmtv4l_unlock_and_return:
2994                                 mutex_unlock(&zr->resource_lock);
2995                         }
2996
2997                         break;
2998
2999                 default:
3000                         dprintk(3, "unsupported\n");
3001                         dprintk(1,
3002                                 KERN_ERR
3003                                 "%s: VIDIOC_S_FMT - unsupported type %d\n",
3004                                 ZR_DEVNAME(zr), fmt->type);
3005                         return -EINVAL;
3006                 }
3007
3008                 return res;
3009         }
3010                 break;
3011
3012         case VIDIOC_G_FBUF:
3013         {
3014                 struct v4l2_framebuffer *fb = arg;
3015
3016                 dprintk(3, KERN_DEBUG "%s: VIDIOC_G_FBUF\n", ZR_DEVNAME(zr));
3017
3018                 memset(fb, 0, sizeof(*fb));
3019                 mutex_lock(&zr->resource_lock);
3020                 fb->base = zr->buffer.base;
3021                 fb->fmt.width = zr->buffer.width;
3022                 fb->fmt.height = zr->buffer.height;
3023                 if (zr->overlay_settings.format) {
3024                         fb->fmt.pixelformat =
3025                                 fh->overlay_settings.format->fourcc;
3026                 }
3027                 fb->fmt.bytesperline = zr->buffer.bytesperline;
3028                 mutex_unlock(&zr->resource_lock);
3029                 fb->fmt.colorspace = V4L2_COLORSPACE_SRGB;
3030                 fb->fmt.field = V4L2_FIELD_INTERLACED;
3031                 fb->flags = V4L2_FBUF_FLAG_OVERLAY;
3032                 fb->capability = V4L2_FBUF_CAP_LIST_CLIPPING;
3033
3034                 return 0;
3035         }
3036                 break;
3037
3038         case VIDIOC_S_FBUF:
3039         {
3040                 int i, res = 0;
3041                 struct v4l2_framebuffer *fb = arg;
3042                 __u32 printformat = __cpu_to_le32(fb->fmt.pixelformat);
3043
3044                 dprintk(3,
3045                         KERN_DEBUG
3046                         "%s: VIDIOC_S_FBUF - base=0x%p, size=%dx%d, bpl=%d, fmt=0x%x (%4.4s)\n",
3047                         ZR_DEVNAME(zr), fb->base, fb->fmt.width, fb->fmt.height,
3048                         fb->fmt.bytesperline, fb->fmt.pixelformat,
3049                         (char *) &printformat);
3050
3051                 for (i = 0; i < NUM_FORMATS; i++)
3052                         if (zoran_formats[i].fourcc == fb->fmt.pixelformat)
3053                                 break;
3054                 if (i == NUM_FORMATS) {
3055                         dprintk(1,
3056                                 KERN_ERR
3057                                 "%s: VIDIOC_S_FBUF - format=0x%x (%4.4s) not allowed\n",
3058                                 ZR_DEVNAME(zr), fb->fmt.pixelformat,
3059                                 (char *) &printformat);
3060                         return -EINVAL;
3061                 }
3062
3063                 mutex_lock(&zr->resource_lock);
3064                 res =
3065                     setup_fbuffer(file, fb->base, &zoran_formats[i],
3066                                   fb->fmt.width, fb->fmt.height,
3067                                   fb->fmt.bytesperline);
3068                 mutex_unlock(&zr->resource_lock);
3069
3070                 return res;
3071         }
3072                 break;
3073
3074         case VIDIOC_OVERLAY:
3075         {
3076                 int *on = arg, res;
3077
3078                 dprintk(3, KERN_DEBUG "%s: VIDIOC_PREVIEW - on=%d\n",
3079                         ZR_DEVNAME(zr), *on);
3080
3081                 mutex_lock(&zr->resource_lock);
3082                 res = setup_overlay(file, *on);
3083                 mutex_unlock(&zr->resource_lock);
3084
3085                 return res;
3086         }
3087                 break;
3088
3089         case VIDIOC_REQBUFS:
3090         {
3091                 struct v4l2_requestbuffers *req = arg;
3092                 int res = 0;
3093
3094                 dprintk(3, KERN_DEBUG "%s: VIDIOC_REQBUFS - type=%d\n",
3095                         ZR_DEVNAME(zr), req->type);
3096
3097                 if (req->memory != V4L2_MEMORY_MMAP) {
3098                         dprintk(1,
3099                                 KERN_ERR
3100                                 "%s: only MEMORY_MMAP capture is supported, not %d\n",
3101                                 ZR_DEVNAME(zr), req->memory);
3102                         return -EINVAL;
3103                 }
3104
3105                 mutex_lock(&zr->resource_lock);
3106
3107                 if (fh->v4l_buffers.allocated || fh->jpg_buffers.allocated) {
3108                         dprintk(1,
3109                                 KERN_ERR
3110                                 "%s: VIDIOC_REQBUFS - buffers allready allocated\n",
3111                                 ZR_DEVNAME(zr));
3112                         res = -EBUSY;
3113                         goto v4l2reqbuf_unlock_and_return;
3114                 }
3115
3116                 if (fh->map_mode == ZORAN_MAP_MODE_RAW &&
3117                     req->type == V4L2_BUF_TYPE_VIDEO_CAPTURE) {
3118
3119                         /* control user input */
3120                         if (req->count < 2)
3121                                 req->count = 2;
3122                         if (req->count > v4l_nbufs)
3123                                 req->count = v4l_nbufs;
3124                         fh->v4l_buffers.num_buffers = req->count;
3125
3126                         if (v4l_fbuffer_alloc(file)) {
3127                                 res = -ENOMEM;
3128                                 goto v4l2reqbuf_unlock_and_return;
3129                         }
3130
3131                         /* The next mmap will map the V4L buffers */
3132                         fh->map_mode = ZORAN_MAP_MODE_RAW;
3133
3134                 } else if (fh->map_mode == ZORAN_MAP_MODE_JPG_REC ||
3135                            fh->map_mode == ZORAN_MAP_MODE_JPG_PLAY) {
3136
3137                         /* we need to calculate size ourselves now */
3138                         if (req->count < 4)
3139                                 req->count = 4;
3140                         if (req->count > jpg_nbufs)
3141                                 req->count = jpg_nbufs;
3142                         fh->jpg_buffers.num_buffers = req->count;
3143                         fh->jpg_buffers.buffer_size =
3144                             zoran_v4l2_calc_bufsize(&fh->jpg_settings);
3145
3146                         if (jpg_fbuffer_alloc(file)) {
3147                                 res = -ENOMEM;
3148                                 goto v4l2reqbuf_unlock_and_return;
3149                         }
3150
3151                         /* The next mmap will map the MJPEG buffers */
3152                         if (req->type == V4L2_BUF_TYPE_VIDEO_CAPTURE)
3153                                 fh->map_mode = ZORAN_MAP_MODE_JPG_REC;
3154                         else
3155                                 fh->map_mode = ZORAN_MAP_MODE_JPG_PLAY;
3156
3157                 } else {
3158                         dprintk(1,
3159                                 KERN_ERR
3160                                 "%s: VIDIOC_REQBUFS - unknown type %d\n",
3161                                 ZR_DEVNAME(zr), req->type);
3162                         res = -EINVAL;
3163                         goto v4l2reqbuf_unlock_and_return;
3164                 }
3165         v4l2reqbuf_unlock_and_return:
3166                 mutex_unlock(&zr->resource_lock);
3167
3168                 return 0;
3169         }
3170                 break;
3171
3172         case VIDIOC_QUERYBUF:
3173         {
3174                 struct v4l2_buffer *buf = arg;
3175                 __u32 type = buf->type;
3176                 int index = buf->index, res;
3177
3178                 dprintk(3,
3179                         KERN_DEBUG
3180                         "%s: VIDIOC_QUERYBUF - index=%d, type=%d\n",
3181                         ZR_DEVNAME(zr), buf->index, buf->type);
3182
3183                 memset(buf, 0, sizeof(*buf));
3184                 buf->type = type;
3185                 buf->index = index;
3186
3187                 mutex_lock(&zr->resource_lock);
3188                 res = zoran_v4l2_buffer_status(file, buf, buf->index);
3189                 mutex_unlock(&zr->resource_lock);
3190
3191                 return res;
3192         }
3193                 break;
3194
3195         case VIDIOC_QBUF:
3196         {
3197                 struct v4l2_buffer *buf = arg;
3198                 int res = 0, codec_mode, buf_type;
3199
3200                 dprintk(3,
3201                         KERN_DEBUG "%s: VIDIOC_QBUF - type=%d, index=%d\n",
3202                         ZR_DEVNAME(zr), buf->type, buf->index);
3203
3204                 mutex_lock(&zr->resource_lock);
3205
3206                 switch (fh->map_mode) {
3207                 case ZORAN_MAP_MODE_RAW:
3208                         if (buf->type != V4L2_BUF_TYPE_VIDEO_CAPTURE) {
3209                                 dprintk(1,
3210                                         KERN_ERR
3211                                         "%s: VIDIOC_QBUF - invalid buf->type=%d for map_mode=%d\n",
3212                                         ZR_DEVNAME(zr), buf->type, fh->map_mode);
3213                                 res = -EINVAL;
3214                                 goto qbuf_unlock_and_return;
3215                         }
3216
3217                         res = zoran_v4l_queue_frame(file, buf->index);
3218                         if (res)
3219                                 goto qbuf_unlock_and_return;
3220                         if (!zr->v4l_memgrab_active &&
3221                             fh->v4l_buffers.active == ZORAN_LOCKED)
3222                                 zr36057_set_memgrab(zr, 1);
3223                         break;
3224
3225                 case ZORAN_MAP_MODE_JPG_REC:
3226                 case ZORAN_MAP_MODE_JPG_PLAY:
3227                         if (fh->map_mode == ZORAN_MAP_MODE_JPG_PLAY) {
3228                                 buf_type = V4L2_BUF_TYPE_VIDEO_OUTPUT;
3229                                 codec_mode = BUZ_MODE_MOTION_DECOMPRESS;
3230                         } else {
3231                                 buf_type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
3232                                 codec_mode = BUZ_MODE_MOTION_COMPRESS;
3233                         }
3234
3235                         if (buf->type != buf_type) {
3236                                 dprintk(1,
3237                                         KERN_ERR
3238                                         "%s: VIDIOC_QBUF - invalid buf->type=%d for map_mode=%d\n",
3239                                         ZR_DEVNAME(zr), buf->type, fh->map_mode);
3240                                 res = -EINVAL;
3241                                 goto qbuf_unlock_and_return;
3242                         }
3243
3244                         res =
3245                             zoran_jpg_queue_frame(file, buf->index,
3246                                                   codec_mode);
3247                         if (res != 0)
3248                                 goto qbuf_unlock_and_return;
3249                         if (zr->codec_mode == BUZ_MODE_IDLE &&
3250                             fh->jpg_buffers.active == ZORAN_LOCKED) {
3251                                 zr36057_enable_jpg(zr, codec_mode);
3252                         }
3253                         break;
3254
3255                 default:
3256                         dprintk(1,
3257                                 KERN_ERR
3258                                 "%s: VIDIOC_QBUF - unsupported type %d\n",
3259                                 ZR_DEVNAME(zr), buf->type);
3260                         res = -EINVAL;
3261                         goto qbuf_unlock_and_return;
3262                 }
3263         qbuf_unlock_and_return:
3264                 mutex_unlock(&zr->resource_lock);
3265
3266                 return res;
3267         }
3268                 break;
3269
3270         case VIDIOC_DQBUF:
3271         {
3272                 struct v4l2_buffer *buf = arg;
3273                 int res = 0, buf_type, num = -1;        /* compiler borks here (?) */
3274
3275                 dprintk(3, KERN_DEBUG "%s: VIDIOC_DQBUF - type=%d\n",
3276                         ZR_DEVNAME(zr), buf->type);
3277
3278                 mutex_lock(&zr->resource_lock);
3279
3280                 switch (fh->map_mode) {
3281                 case ZORAN_MAP_MODE_RAW:
3282                         if (buf->type != V4L2_BUF_TYPE_VIDEO_CAPTURE) {
3283                                 dprintk(1,
3284                                         KERN_ERR
3285                                         "%s: VIDIOC_QBUF - invalid buf->type=%d for map_mode=%d\n",
3286                                         ZR_DEVNAME(zr), buf->type, fh->map_mode);
3287                                 res = -EINVAL;
3288                                 goto dqbuf_unlock_and_return;
3289                         }
3290
3291                         num = zr->v4l_pend[zr->v4l_sync_tail & V4L_MASK_FRAME];
3292                         if (file->f_flags & O_NONBLOCK &&
3293                             zr->v4l_buffers.buffer[num].state !=
3294                             BUZ_STATE_DONE) {
3295                                 res = -EAGAIN;
3296                                 goto dqbuf_unlock_and_return;
3297                         }
3298                         res = v4l_sync(file, num);
3299                         if (res)
3300                                 goto dqbuf_unlock_and_return;
3301                         else
3302                                 zr->v4l_sync_tail++;
3303                         res = zoran_v4l2_buffer_status(file, buf, num);
3304                         break;
3305
3306                 case ZORAN_MAP_MODE_JPG_REC:
3307                 case ZORAN_MAP_MODE_JPG_PLAY:
3308                 {
3309                         struct zoran_sync bs;
3310
3311                         if (fh->map_mode == ZORAN_MAP_MODE_JPG_PLAY)
3312                                 buf_type = V4L2_BUF_TYPE_VIDEO_OUTPUT;
3313                         else
3314                                 buf_type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
3315
3316                         if (buf->type != buf_type) {
3317                                 dprintk(1,
3318                                         KERN_ERR
3319                                         "%s: VIDIOC_QBUF - invalid buf->type=%d for map_mode=%d\n",
3320                                         ZR_DEVNAME(zr), buf->type, fh->map_mode);
3321                                 res = -EINVAL;
3322                                 goto dqbuf_unlock_and_return;
3323                         }
3324
3325                         num =
3326                             zr->jpg_pend[zr->
3327                                          jpg_que_tail & BUZ_MASK_FRAME];
3328
3329                         if (file->f_flags & O_NONBLOCK &&
3330                             zr->jpg_buffers.buffer[num].state !=
3331                             BUZ_STATE_DONE) {
3332                                 res = -EAGAIN;
3333                                 goto dqbuf_unlock_and_return;
3334                         }
3335                         res = jpg_sync(file, &bs);
3336                         if (res)
3337                                 goto dqbuf_unlock_and_return;
3338                         res =
3339                             zoran_v4l2_buffer_status(file, buf, bs.frame);
3340                         break;
3341                 }
3342
3343                 default:
3344                         dprintk(1,
3345                                 KERN_ERR
3346                                 "%s: VIDIOC_DQBUF - unsupported type %d\n",
3347                                 ZR_DEVNAME(zr), buf->type);
3348                         res = -EINVAL;
3349                         goto dqbuf_unlock_and_return;
3350                 }
3351         dqbuf_unlock_and_return:
3352                 mutex_unlock(&zr->resource_lock);
3353
3354                 return res;
3355         }
3356                 break;
3357
3358         case VIDIOC_STREAMON:
3359         {
3360                 int res = 0;
3361
3362                 dprintk(3, KERN_DEBUG "%s: VIDIOC_STREAMON\n", ZR_DEVNAME(zr));
3363
3364                 mutex_lock(&zr->resource_lock);
3365
3366                 switch (fh->map_mode) {
3367                 case ZORAN_MAP_MODE_RAW:        /* raw capture */
3368                         if (zr->v4l_buffers.active != ZORAN_ACTIVE ||
3369                             fh->v4l_buffers.active != ZORAN_ACTIVE) {
3370                                 res = -EBUSY;
3371                                 goto strmon_unlock_and_return;
3372                         }
3373
3374                         zr->v4l_buffers.active = fh->v4l_buffers.active =
3375                             ZORAN_LOCKED;
3376                         zr->v4l_settings = fh->v4l_settings;
3377
3378                         zr->v4l_sync_tail = zr->v4l_pend_tail;
3379                         if (!zr->v4l_memgrab_active &&
3380                             zr->v4l_pend_head != zr->v4l_pend_tail) {
3381                                 zr36057_set_memgrab(zr, 1);
3382                         }
3383                         break;
3384
3385                 case ZORAN_MAP_MODE_JPG_REC:
3386                 case ZORAN_MAP_MODE_JPG_PLAY:
3387                         /* what is the codec mode right now? */
3388                         if (zr->jpg_buffers.active != ZORAN_ACTIVE ||
3389                             fh->jpg_buffers.active != ZORAN_ACTIVE) {
3390                                 res = -EBUSY;
3391                                 goto strmon_unlock_and_return;
3392                         }
3393
3394                         zr->jpg_buffers.active = fh->jpg_buffers.active =
3395                             ZORAN_LOCKED;
3396
3397                         if (zr->jpg_que_head != zr->jpg_que_tail) {
3398                                 /* Start the jpeg codec when the first frame is queued  */
3399                                 jpeg_start(zr);
3400                         }
3401
3402                         break;
3403                 default:
3404                         dprintk(1,
3405                                 KERN_ERR
3406                                 "%s: VIDIOC_STREAMON - invalid map mode %d\n",
3407                                 ZR_DEVNAME(zr), fh->map_mode);
3408                         res = -EINVAL;
3409                         goto strmon_unlock_and_return;
3410                 }
3411         strmon_unlock_and_return:
3412                 mutex_unlock(&zr->resource_lock);
3413
3414                 return res;
3415         }
3416                 break;
3417
3418         case VIDIOC_STREAMOFF:
3419         {
3420                 int i, res = 0;
3421
3422                 dprintk(3, KERN_DEBUG "%s: VIDIOC_STREAMOFF\n", ZR_DEVNAME(zr));
3423
3424                 mutex_lock(&zr->resource_lock);
3425
3426                 switch (fh->map_mode) {
3427                 case ZORAN_MAP_MODE_RAW:        /* raw capture */
3428                         if (fh->v4l_buffers.active == ZORAN_FREE &&
3429                             zr->v4l_buffers.active != ZORAN_FREE) {
3430                                 res = -EPERM;   /* stay off other's settings! */
3431                                 goto strmoff_unlock_and_return;
3432                         }
3433                         if (zr->v4l_buffers.active == ZORAN_FREE)
3434                                 goto strmoff_unlock_and_return;
3435
3436                         /* unload capture */
3437                         if (zr->v4l_memgrab_active) {
3438                                 unsigned long flags;
3439
3440                                 spin_lock_irqsave(&zr->spinlock, flags);
3441                                 zr36057_set_memgrab(zr, 0);
3442                                 spin_unlock_irqrestore(&zr->spinlock, flags);
3443                         }
3444
3445                         for (i = 0; i < fh->v4l_buffers.num_buffers; i++)
3446                                 zr->v4l_buffers.buffer[i].state =
3447                                     BUZ_STATE_USER;
3448                         fh->v4l_buffers = zr->v4l_buffers;
3449
3450                         zr->v4l_buffers.active = fh->v4l_buffers.active =
3451                             ZORAN_FREE;
3452
3453                         zr->v4l_grab_seq = 0;
3454                         zr->v4l_pend_head = zr->v4l_pend_tail = 0;
3455                         zr->v4l_sync_tail = 0;
3456
3457                         break;
3458
3459                 case ZORAN_MAP_MODE_JPG_REC:
3460                 case ZORAN_MAP_MODE_JPG_PLAY:
3461                         if (fh->jpg_buffers.active == ZORAN_FREE &&
3462                             zr->jpg_buffers.active != ZORAN_FREE) {
3463                                 res = -EPERM;   /* stay off other's settings! */
3464                                 goto strmoff_unlock_and_return;
3465                         }
3466                         if (zr->jpg_buffers.active == ZORAN_FREE)
3467                                 goto strmoff_unlock_and_return;
3468
3469                         res =
3470                             jpg_qbuf(file, -1,
3471                                      (fh->map_mode ==
3472                                       ZORAN_MAP_MODE_JPG_REC) ?
3473                                      BUZ_MODE_MOTION_COMPRESS :
3474                                      BUZ_MODE_MOTION_DECOMPRESS);
3475                         if (res)
3476                                 goto strmoff_unlock_and_return;
3477                         break;
3478                 default:
3479                         dprintk(1,
3480                                 KERN_ERR
3481                                 "%s: VIDIOC_STREAMOFF - invalid map mode %d\n",
3482                                 ZR_DEVNAME(zr), fh->map_mode);
3483                         res = -EINVAL;
3484                         goto strmoff_unlock_and_return;
3485                 }
3486         strmoff_unlock_and_return:
3487                 mutex_unlock(&zr->resource_lock);
3488
3489                 return res;
3490         }
3491                 break;
3492
3493         case VIDIOC_QUERYCTRL:
3494         {
3495                 struct v4l2_queryctrl *ctrl = arg;
3496
3497                 dprintk(3, KERN_DEBUG "%s: VIDIOC_QUERYCTRL - id=%d\n",
3498                         ZR_DEVNAME(zr), ctrl->id);
3499
3500                 /* we only support hue/saturation/contrast/brightness */
3501                 if (ctrl->id < V4L2_CID_BRIGHTNESS ||
3502                     ctrl->id > V4L2_CID_HUE)
3503                         return -EINVAL;
3504                 else {
3505                         int id = ctrl->id;
3506                         memset(ctrl, 0, sizeof(*ctrl));
3507                         ctrl->id = id;
3508                 }
3509
3510                 switch (ctrl->id) {
3511                 case V4L2_CID_BRIGHTNESS:
3512                         strncpy(ctrl->name, "Brightness", sizeof(ctrl->name)-1);
3513                         break;
3514                 case V4L2_CID_CONTRAST:
3515                         strncpy(ctrl->name, "Contrast", sizeof(ctrl->name)-1);
3516                         break;
3517                 case V4L2_CID_SATURATION:
3518                         strncpy(ctrl->name, "Saturation", sizeof(ctrl->name)-1);
3519                         break;
3520                 case V4L2_CID_HUE:
3521                         strncpy(ctrl->name, "Hue", sizeof(ctrl->name)-1);
3522                         break;
3523                 }
3524
3525                 ctrl->minimum = 0;
3526                 ctrl->maximum = 65535;
3527                 ctrl->step = 1;
3528                 ctrl->default_value = 32768;
3529                 ctrl->type = V4L2_CTRL_TYPE_INTEGER;
3530
3531                 return 0;
3532         }
3533                 break;
3534
3535         case VIDIOC_G_CTRL:
3536         {
3537                 struct v4l2_control *ctrl = arg;
3538
3539                 dprintk(3, KERN_DEBUG "%s: VIDIOC_G_CTRL - id=%d\n",
3540                         ZR_DEVNAME(zr), ctrl->id);
3541
3542                 /* we only support hue/saturation/contrast/brightness */
3543                 if (ctrl->id < V4L2_CID_BRIGHTNESS ||
3544                     ctrl->id > V4L2_CID_HUE)
3545                         return -EINVAL;
3546
3547                 mutex_lock(&zr->resource_lock);
3548                 switch (ctrl->id) {
3549                 case V4L2_CID_BRIGHTNESS:
3550                         ctrl->value = zr->brightness;
3551                         break;
3552                 case V4L2_CID_CONTRAST:
3553                         ctrl->value = zr->contrast;
3554                         break;
3555                 case V4L2_CID_SATURATION:
3556                         ctrl->value = zr->saturation;
3557                         break;
3558                 case V4L2_CID_HUE:
3559                         ctrl->value = zr->hue;
3560                         break;
3561                 }
3562                 mutex_unlock(&zr->resource_lock);
3563
3564                 return 0;
3565         }
3566                 break;
3567
3568         case VIDIOC_S_CTRL:
3569         {
3570                 struct v4l2_control *ctrl = arg;
3571                 struct video_picture pict;
3572
3573                 dprintk(3, KERN_DEBUG "%s: VIDIOC_S_CTRL - id=%d\n",
3574                         ZR_DEVNAME(zr), ctrl->id);
3575
3576                 /* we only support hue/saturation/contrast/brightness */
3577                 if (ctrl->id < V4L2_CID_BRIGHTNESS ||
3578                     ctrl->id > V4L2_CID_HUE)
3579                         return -EINVAL;
3580
3581                 if (ctrl->value < 0 || ctrl->value > 65535) {
3582                         dprintk(1,
3583                                 KERN_ERR
3584                                 "%s: VIDIOC_S_CTRL - invalid value %d for id=%d\n",
3585                                 ZR_DEVNAME(zr), ctrl->value, ctrl->id);
3586                         return -EINVAL;
3587                 }
3588
3589                 mutex_lock(&zr->resource_lock);
3590                 switch (ctrl->id) {
3591                 case V4L2_CID_BRIGHTNESS:
3592                         zr->brightness = ctrl->value;
3593                         break;
3594                 case V4L2_CID_CONTRAST:
3595                         zr->contrast = ctrl->value;
3596                         break;
3597                 case V4L2_CID_SATURATION:
3598                         zr->saturation = ctrl->value;
3599                         break;
3600                 case V4L2_CID_HUE:
3601                         zr->hue = ctrl->value;
3602                         break;
3603                 }
3604                 pict.brightness = zr->brightness;
3605                 pict.contrast = zr->contrast;
3606                 pict.colour = zr->saturation;
3607                 pict.hue = zr->hue;
3608
3609                 decoder_command(zr, DECODER_SET_PICTURE, &pict);
3610
3611                 mutex_unlock(&zr->resource_lock);
3612
3613                 return 0;
3614         }
3615                 break;
3616
3617         case VIDIOC_ENUMSTD:
3618         {
3619                 struct v4l2_standard *std = arg;
3620
3621                 dprintk(3, KERN_DEBUG "%s: VIDIOC_ENUMSTD - index=%d\n",
3622                         ZR_DEVNAME(zr), std->index);
3623
3624                 if (std->index < 0 || std->index >= (zr->card.norms + 1))
3625                         return -EINVAL;
3626                 else {
3627                         int id = std->index;
3628                         memset(std, 0, sizeof(*std));
3629                         std->index = id;
3630                 }
3631
3632                 if (std->index == zr->card.norms) {
3633                         /* if we have autodetect, ... */
3634                         struct video_decoder_capability caps;
3635                         decoder_command(zr, DECODER_GET_CAPABILITIES,
3636                                         &caps);
3637                         if (caps.flags & VIDEO_DECODER_AUTO) {
3638                                 std->id = V4L2_STD_ALL;
3639                                 strncpy(std->name, "Autodetect", sizeof(std->name)-1);
3640                                 return 0;
3641                         } else
3642                                 return -EINVAL;
3643                 }
3644                 switch (std->index) {
3645                 case 0:
3646                         std->id = V4L2_STD_PAL;
3647                         strncpy(std->name, "PAL", sizeof(std->name)-1);
3648                         std->frameperiod.numerator = 1;
3649                         std->frameperiod.denominator = 25;
3650                         std->framelines = zr->card.tvn[0]->Ht;
3651                         break;
3652                 case 1:
3653                         std->id = V4L2_STD_NTSC;
3654                         strncpy(std->name, "NTSC", sizeof(std->name)-1);
3655                         std->frameperiod.numerator = 1001;
3656                         std->frameperiod.denominator = 30000;
3657                         std->framelines = zr->card.tvn[1]->Ht;
3658                         break;
3659                 case 2:
3660                         std->id = V4L2_STD_SECAM;
3661                         strncpy(std->name, "SECAM", sizeof(std->name)-1);
3662                         std->frameperiod.numerator = 1;
3663                         std->frameperiod.denominator = 25;
3664                         std->framelines = zr->card.tvn[2]->Ht;
3665                         break;
3666                 }
3667
3668                 return 0;
3669         }
3670                 break;
3671
3672         case VIDIOC_G_STD:
3673         {
3674                 v4l2_std_id *std = arg;
3675                 int norm;
3676
3677                 dprintk(3, KERN_DEBUG "%s: VIDIOC_G_STD\n", ZR_DEVNAME(zr));
3678
3679                 mutex_lock(&zr->resource_lock);
3680                 norm = zr->norm;
3681                 mutex_unlock(&zr->resource_lock);
3682
3683                 switch (norm) {
3684                 case VIDEO_MODE_PAL:
3685                         *std = V4L2_STD_PAL;
3686                         break;
3687                 case VIDEO_MODE_NTSC:
3688                         *std = V4L2_STD_NTSC;
3689                         break;
3690                 case VIDEO_MODE_SECAM:
3691                         *std = V4L2_STD_SECAM;
3692                         break;
3693                 }
3694
3695                 return 0;
3696         }
3697                 break;
3698
3699         case VIDIOC_S_STD:
3700         {
3701                 int norm = -1, res = 0;
3702                 v4l2_std_id *std = arg;
3703
3704                 dprintk(3, KERN_DEBUG "%s: VIDIOC_S_STD - norm=0x%llx\n",
3705                         ZR_DEVNAME(zr), (unsigned long long)*std);
3706
3707                 if ((*std & V4L2_STD_PAL) && !(*std & ~V4L2_STD_PAL))
3708                         norm = VIDEO_MODE_PAL;
3709                 else if ((*std & V4L2_STD_NTSC) && !(*std & ~V4L2_STD_NTSC))
3710                         norm = VIDEO_MODE_NTSC;
3711                 else if ((*std & V4L2_STD_SECAM) && !(*std & ~V4L2_STD_SECAM))
3712                         norm = VIDEO_MODE_SECAM;
3713                 else if (*std == V4L2_STD_ALL)
3714                         norm = VIDEO_MODE_AUTO;
3715                 else {
3716                         dprintk(1,
3717                                 KERN_ERR
3718                                 "%s: VIDIOC_S_STD - invalid norm 0x%llx\n",
3719                                 ZR_DEVNAME(zr), (unsigned long long)*std);
3720                         return -EINVAL;
3721                 }
3722
3723                 mutex_lock(&zr->resource_lock);
3724                 if ((res = zoran_set_norm(zr, norm)))
3725                         goto sstd_unlock_and_return;
3726
3727                 res = wait_grab_pending(zr);
3728         sstd_unlock_and_return:
3729                 mutex_unlock(&zr->resource_lock);
3730                 return res;
3731         }
3732                 break;
3733
3734         case VIDIOC_ENUMINPUT:
3735         {
3736                 struct v4l2_input *inp = arg;
3737                 int status;
3738
3739                 dprintk(3, KERN_DEBUG "%s: VIDIOC_ENUMINPUT - index=%d\n",
3740                         ZR_DEVNAME(zr), inp->index);
3741
3742                 if (inp->index < 0 || inp->index >= zr->card.inputs)
3743                         return -EINVAL;
3744                 else {
3745                         int id = inp->index;
3746                         memset(inp, 0, sizeof(*inp));
3747                         inp->index = id;
3748                 }
3749
3750                 strncpy(inp->name, zr->card.input[inp->index].name,
3751                         sizeof(inp->name) - 1);
3752                 inp->type = V4L2_INPUT_TYPE_CAMERA;
3753                 inp->std = V4L2_STD_ALL;
3754
3755                 /* Get status of video decoder */
3756                 mutex_lock(&zr->resource_lock);
3757                 decoder_command(zr, DECODER_GET_STATUS, &status);
3758                 mutex_unlock(&zr->resource_lock);
3759
3760                 if (!(status & DECODER_STATUS_GOOD)) {
3761                         inp->status |= V4L2_IN_ST_NO_POWER;
3762                         inp->status |= V4L2_IN_ST_NO_SIGNAL;
3763                 }
3764                 if (!(status & DECODER_STATUS_COLOR))
3765                         inp->status |= V4L2_IN_ST_NO_COLOR;
3766
3767                 return 0;
3768         }
3769                 break;
3770
3771         case VIDIOC_G_INPUT:
3772         {
3773                 int *input = arg;
3774
3775                 dprintk(3, KERN_DEBUG "%s: VIDIOC_G_INPUT\n", ZR_DEVNAME(zr));
3776
3777                 mutex_lock(&zr->resource_lock);
3778                 *input = zr->input;
3779                 mutex_unlock(&zr->resource_lock);
3780
3781                 return 0;
3782         }
3783                 break;
3784
3785         case VIDIOC_S_INPUT:
3786         {
3787                 int *input = arg, res = 0;
3788
3789                 dprintk(3, KERN_DEBUG "%s: VIDIOC_S_INPUT - input=%d\n",
3790                         ZR_DEVNAME(zr), *input);
3791
3792                 mutex_lock(&zr->resource_lock);
3793                 if ((res = zoran_set_input(zr, *input)))
3794                         goto sinput_unlock_and_return;
3795
3796                 /* Make sure the changes come into effect */
3797                 res = wait_grab_pending(zr);
3798         sinput_unlock_and_return:
3799                 mutex_unlock(&zr->resource_lock);
3800                 return res;
3801         }
3802                 break;
3803
3804         case VIDIOC_ENUMOUTPUT:
3805         {
3806                 struct v4l2_output *outp = arg;
3807
3808                 dprintk(3, KERN_DEBUG "%s: VIDIOC_ENUMOUTPUT - index=%d\n",
3809                         ZR_DEVNAME(zr), outp->index);
3810
3811                 if (outp->index != 0)
3812                         return -EINVAL;
3813
3814                 memset(outp, 0, sizeof(*outp));
3815                 outp->index = 0;
3816                 outp->type = V4L2_OUTPUT_TYPE_ANALOGVGAOVERLAY;
3817                 strncpy(outp->name, "Autodetect", sizeof(outp->name)-1);
3818
3819                 return 0;
3820         }
3821                 break;
3822
3823         case VIDIOC_G_OUTPUT:
3824         {
3825                 int *output = arg;
3826
3827                 dprintk(3, KERN_DEBUG "%s: VIDIOC_G_OUTPUT\n", ZR_DEVNAME(zr));
3828
3829                 *output = 0;
3830
3831                 return 0;
3832         }
3833                 break;
3834
3835         case VIDIOC_S_OUTPUT:
3836         {
3837                 int *output = arg;
3838
3839                 dprintk(3, KERN_DEBUG "%s: VIDIOC_S_OUTPUT - output=%d\n",
3840                         ZR_DEVNAME(zr), *output);
3841
3842                 if (*output != 0)
3843                         return -EINVAL;
3844
3845                 return 0;
3846         }
3847                 break;
3848
3849                 /* cropping (sub-frame capture) */
3850         case VIDIOC_CROPCAP:
3851         {
3852                 struct v4l2_cropcap *cropcap = arg;
3853                 int type = cropcap->type, res = 0;
3854
3855                 dprintk(3, KERN_ERR "%s: VIDIOC_CROPCAP - type=%d\n",
3856                         ZR_DEVNAME(zr), cropcap->type);
3857
3858                 memset(cropcap, 0, sizeof(*cropcap));
3859                 cropcap->type = type;
3860
3861                 mutex_lock(&zr->resource_lock);
3862
3863                 if (cropcap->type != V4L2_BUF_TYPE_VIDEO_OUTPUT &&
3864                     (cropcap->type != V4L2_BUF_TYPE_VIDEO_CAPTURE ||
3865                      fh->map_mode == ZORAN_MAP_MODE_RAW)) {
3866                         dprintk(1,
3867                                 KERN_ERR
3868                                 "%s: VIDIOC_CROPCAP - subcapture only supported for compressed capture\n",
3869                                 ZR_DEVNAME(zr));
3870                         res = -EINVAL;
3871                         goto cropcap_unlock_and_return;
3872                 }
3873
3874                 cropcap->bounds.top = cropcap->bounds.left = 0;
3875                 cropcap->bounds.width = BUZ_MAX_WIDTH;
3876                 cropcap->bounds.height = BUZ_MAX_HEIGHT;
3877                 cropcap->defrect.top = cropcap->defrect.left = 0;
3878                 cropcap->defrect.width = BUZ_MIN_WIDTH;
3879                 cropcap->defrect.height = BUZ_MIN_HEIGHT;
3880         cropcap_unlock_and_return:
3881                 mutex_unlock(&zr->resource_lock);
3882                 return res;
3883         }
3884                 break;
3885
3886         case VIDIOC_G_CROP:
3887         {
3888                 struct v4l2_crop *crop = arg;
3889                 int type = crop->type, res = 0;
3890
3891                 dprintk(3, KERN_ERR "%s: VIDIOC_G_CROP - type=%d\n",
3892                         ZR_DEVNAME(zr), crop->type);
3893
3894                 memset(crop, 0, sizeof(*crop));
3895                 crop->type = type;
3896
3897                 mutex_lock(&zr->resource_lock);
3898
3899                 if (crop->type != V4L2_BUF_TYPE_VIDEO_OUTPUT &&
3900                     (crop->type != V4L2_BUF_TYPE_VIDEO_CAPTURE ||
3901                      fh->map_mode == ZORAN_MAP_MODE_RAW)) {
3902                         dprintk(1,
3903                                 KERN_ERR
3904                                 "%s: VIDIOC_G_CROP - subcapture only supported for compressed capture\n",
3905                                 ZR_DEVNAME(zr));
3906                         res = -EINVAL;
3907                         goto gcrop_unlock_and_return;
3908                 }
3909
3910                 crop->c.top = fh->jpg_settings.img_y;
3911                 crop->c.left = fh->jpg_settings.img_x;
3912                 crop->c.width = fh->jpg_settings.img_width;
3913                 crop->c.height = fh->jpg_settings.img_height;
3914
3915         gcrop_unlock_and_return:
3916                 mutex_unlock(&zr->resource_lock);
3917
3918                 return res;
3919         }
3920                 break;
3921
3922         case VIDIOC_S_CROP:
3923         {
3924                 struct v4l2_crop *crop = arg;
3925                 int res = 0;
3926
3927                 settings = fh->jpg_settings;
3928
3929                 dprintk(3,
3930                         KERN_ERR
3931                         "%s: VIDIOC_S_CROP - type=%d, x=%d,y=%d,w=%d,h=%d\n",
3932                         ZR_DEVNAME(zr), crop->type, crop->c.left, crop->c.top,
3933                         crop->c.width, crop->c.height);
3934
3935                 mutex_lock(&zr->resource_lock);
3936
3937                 if (fh->jpg_buffers.allocated || fh->v4l_buffers.allocated) {
3938                         dprintk(1,
3939                                 KERN_ERR
3940                                 "%s: VIDIOC_S_CROP - cannot change settings while active\n",
3941                                 ZR_DEVNAME(zr));
3942                         res = -EBUSY;
3943                         goto scrop_unlock_and_return;
3944                 }
3945
3946                 if (crop->type != V4L2_BUF_TYPE_VIDEO_OUTPUT &&
3947                     (crop->type != V4L2_BUF_TYPE_VIDEO_CAPTURE ||
3948                      fh->map_mode == ZORAN_MAP_MODE_RAW)) {
3949                         dprintk(1,
3950                                 KERN_ERR
3951                                 "%s: VIDIOC_G_CROP - subcapture only supported for compressed capture\n",
3952                                 ZR_DEVNAME(zr));
3953                         res = -EINVAL;
3954                         goto scrop_unlock_and_return;
3955                 }
3956
3957                 /* move into a form that we understand */
3958                 settings.img_x = crop->c.left;
3959                 settings.img_y = crop->c.top;
3960                 settings.img_width = crop->c.width;
3961                 settings.img_height = crop->c.height;
3962
3963                 /* check validity */
3964                 if ((res = zoran_check_jpg_settings(zr, &settings)))
3965                         goto scrop_unlock_and_return;
3966
3967                 /* accept */
3968                 fh->jpg_settings = settings;
3969
3970         scrop_unlock_and_return:
3971                 mutex_unlock(&zr->resource_lock);
3972                 return res;
3973         }
3974                 break;
3975
3976         case VIDIOC_G_JPEGCOMP:
3977         {
3978                 struct v4l2_jpegcompression *params = arg;
3979
3980                 dprintk(3, KERN_DEBUG "%s: VIDIOC_G_JPEGCOMP\n",
3981                         ZR_DEVNAME(zr));
3982
3983                 memset(params, 0, sizeof(*params));
3984
3985                 mutex_lock(&zr->resource_lock);
3986
3987                 params->quality = fh->jpg_settings.jpg_comp.quality;
3988                 params->APPn = fh->jpg_settings.jpg_comp.APPn;
3989                 memcpy(params->APP_data,
3990                        fh->jpg_settings.jpg_comp.APP_data,
3991                        fh->jpg_settings.jpg_comp.APP_len);
3992                 params->APP_len = fh->jpg_settings.jpg_comp.APP_len;
3993                 memcpy(params->COM_data,
3994                        fh->jpg_settings.jpg_comp.COM_data,
3995                        fh->jpg_settings.jpg_comp.COM_len);
3996                 params->COM_len = fh->jpg_settings.jpg_comp.COM_len;
3997                 params->jpeg_markers =
3998                     fh->jpg_settings.jpg_comp.jpeg_markers;
3999
4000                 mutex_unlock(&zr->resource_lock);
4001
4002                 return 0;
4003         }
4004                 break;
4005
4006         case VIDIOC_S_JPEGCOMP:
4007         {
4008                 struct v4l2_jpegcompression *params = arg;
4009                 int res = 0;
4010
4011                 settings = fh->jpg_settings;
4012
4013                 dprintk(3,
4014                         KERN_DEBUG
4015                         "%s: VIDIOC_S_JPEGCOMP - quality=%d, APPN=%d, APP_len=%d, COM_len=%d\n",
4016                         ZR_DEVNAME(zr), params->quality, params->APPn,
4017                         params->APP_len, params->COM_len);
4018
4019                 settings.jpg_comp = *params;
4020
4021                 mutex_lock(&zr->resource_lock);
4022
4023                 if (fh->v4l_buffers.active != ZORAN_FREE ||
4024                     fh->jpg_buffers.active != ZORAN_FREE) {
4025                         dprintk(1,
4026                                 KERN_WARNING
4027                                 "%s: VIDIOC_S_JPEGCOMP called while in playback/capture mode\n",
4028                                 ZR_DEVNAME(zr));
4029                         res = -EBUSY;
4030                         goto sjpegc_unlock_and_return;
4031                 }
4032
4033                 if ((res = zoran_check_jpg_settings(zr, &settings)))
4034                         goto sjpegc_unlock_and_return;
4035                 if (!fh->jpg_buffers.allocated)
4036                         fh->jpg_buffers.buffer_size =
4037                             zoran_v4l2_calc_bufsize(&fh->jpg_settings);
4038                 fh->jpg_settings.jpg_comp = *params = settings.jpg_comp;
4039         sjpegc_unlock_and_return:
4040                 mutex_unlock(&zr->resource_lock);
4041
4042                 return 0;
4043         }
4044                 break;
4045
4046         case VIDIOC_QUERYSTD:   /* why is this useful? */
4047         {
4048                 v4l2_std_id *std = arg;
4049
4050                 dprintk(3,
4051                         KERN_DEBUG "%s: VIDIOC_QUERY_STD - std=0x%llx\n",
4052                         ZR_DEVNAME(zr), (unsigned long long)*std);
4053
4054                 if (*std == V4L2_STD_ALL || *std == V4L2_STD_NTSC ||
4055                     *std == V4L2_STD_PAL || (*std == V4L2_STD_SECAM &&
4056                                              zr->card.norms == 3)) {
4057                         return 0;
4058                 }
4059
4060                 return -EINVAL;
4061         }
4062                 break;
4063
4064         case VIDIOC_TRY_FMT:
4065         {
4066                 struct v4l2_format *fmt = arg;
4067                 int res = 0;
4068
4069                 dprintk(3, KERN_DEBUG "%s: VIDIOC_TRY_FMT - type=%d\n",
4070                         ZR_DEVNAME(zr), fmt->type);
4071
4072                 switch (fmt->type) {
4073                 case V4L2_BUF_TYPE_VIDEO_OVERLAY:
4074                         mutex_lock(&zr->resource_lock);
4075
4076                         if (fmt->fmt.win.w.width > BUZ_MAX_WIDTH)
4077                                 fmt->fmt.win.w.width = BUZ_MAX_WIDTH;
4078                         if (fmt->fmt.win.w.width < BUZ_MIN_WIDTH)
4079                                 fmt->fmt.win.w.width = BUZ_MIN_WIDTH;
4080                         if (fmt->fmt.win.w.height > BUZ_MAX_HEIGHT)
4081                                 fmt->fmt.win.w.height = BUZ_MAX_HEIGHT;
4082                         if (fmt->fmt.win.w.height < BUZ_MIN_HEIGHT)
4083                                 fmt->fmt.win.w.height = BUZ_MIN_HEIGHT;
4084
4085                         mutex_unlock(&zr->resource_lock);
4086                         break;
4087
4088                 case V4L2_BUF_TYPE_VIDEO_CAPTURE:
4089                 case V4L2_BUF_TYPE_VIDEO_OUTPUT:
4090                         if (fmt->fmt.pix.bytesperline > 0)
4091                                 return -EINVAL;
4092
4093                         mutex_lock(&zr->resource_lock);
4094
4095                         if (fmt->fmt.pix.pixelformat == V4L2_PIX_FMT_MJPEG) {
4096                                 settings = fh->jpg_settings;
4097
4098                                 /* we actually need to set 'real' parameters now */
4099                                 if ((fmt->fmt.pix.height * 2) >
4100                                     BUZ_MAX_HEIGHT)
4101                                         settings.TmpDcm = 1;
4102                                 else
4103                                         settings.TmpDcm = 2;
4104                                 settings.decimation = 0;
4105                                 if (fmt->fmt.pix.height <=
4106                                     fh->jpg_settings.img_height / 2)
4107                                         settings.VerDcm = 2;
4108                                 else
4109                                         settings.VerDcm = 1;
4110                                 if (fmt->fmt.pix.width <=
4111                                     fh->jpg_settings.img_width / 4)
4112                                         settings.HorDcm = 4;
4113                                 else if (fmt->fmt.pix.width <=
4114                                          fh->jpg_settings.img_width / 2)
4115                                         settings.HorDcm = 2;
4116                                 else
4117                                         settings.HorDcm = 1;
4118                                 if (settings.TmpDcm == 1)
4119                                         settings.field_per_buff = 2;
4120                                 else
4121                                         settings.field_per_buff = 1;
4122
4123                                 /* check */
4124                                 if ((res =
4125                                      zoran_check_jpg_settings(zr,
4126                                                               &settings)))
4127                                         goto tryfmt_unlock_and_return;
4128
4129                                 /* tell the user what we actually did */
4130                                 fmt->fmt.pix.width =
4131                                     settings.img_width / settings.HorDcm;
4132                                 fmt->fmt.pix.height =
4133                                     settings.img_height * 2 /
4134                                     (settings.TmpDcm * settings.VerDcm);
4135                                 if (settings.TmpDcm == 1)
4136                                         fmt->fmt.pix.field =
4137                                             (fh->jpg_settings.
4138                                              odd_even ? V4L2_FIELD_SEQ_TB :
4139                                              V4L2_FIELD_SEQ_BT);
4140                                 else
4141                                         fmt->fmt.pix.field =
4142                                             (fh->jpg_settings.
4143                                              odd_even ? V4L2_FIELD_TOP :
4144                                              V4L2_FIELD_BOTTOM);
4145
4146                                 fmt->fmt.pix.sizeimage =
4147                                     zoran_v4l2_calc_bufsize(&settings);
4148                         } else if (fmt->type ==
4149                                    V4L2_BUF_TYPE_VIDEO_CAPTURE) {
4150                                 int i;
4151
4152                                 for (i = 0; i < NUM_FORMATS; i++)
4153                                         if (zoran_formats[i].fourcc ==
4154                                             fmt->fmt.pix.pixelformat)
4155                                                 break;
4156                                 if (i == NUM_FORMATS) {
4157                                         res = -EINVAL;
4158                                         goto tryfmt_unlock_and_return;
4159                                 }
4160
4161                                 if (fmt->fmt.pix.width > BUZ_MAX_WIDTH)
4162                                         fmt->fmt.pix.width = BUZ_MAX_WIDTH;
4163                                 if (fmt->fmt.pix.width < BUZ_MIN_WIDTH)
4164                                         fmt->fmt.pix.width = BUZ_MIN_WIDTH;
4165                                 if (fmt->fmt.pix.height > BUZ_MAX_HEIGHT)
4166                                         fmt->fmt.pix.height =
4167                                             BUZ_MAX_HEIGHT;
4168                                 if (fmt->fmt.pix.height < BUZ_MIN_HEIGHT)
4169                                         fmt->fmt.pix.height =
4170                                             BUZ_MIN_HEIGHT;
4171                         } else {
4172                                 res = -EINVAL;
4173                                 goto tryfmt_unlock_and_return;
4174                         }
4175                 tryfmt_unlock_and_return:
4176                         mutex_unlock(&zr->resource_lock);
4177
4178                         return res;
4179                         break;
4180
4181                 default:
4182                         return -EINVAL;
4183                 }
4184
4185                 return 0;
4186         }
4187                 break;
4188
4189         default:
4190                 dprintk(1, KERN_DEBUG "%s: UNKNOWN ioctl cmd: 0x%x\n",
4191                         ZR_DEVNAME(zr), cmd);
4192                 return -ENOIOCTLCMD;
4193                 break;
4194
4195         }
4196         return 0;
4197 }
4198
4199
4200 static int
4201 zoran_ioctl (struct inode *inode,
4202              struct file  *file,
4203              unsigned int  cmd,
4204              unsigned long arg)
4205 {
4206         return video_usercopy(inode, file, cmd, arg, zoran_do_ioctl);
4207 }
4208
4209 static unsigned int
4210 zoran_poll (struct file *file,
4211             poll_table  *wait)
4212 {
4213         struct zoran_fh *fh = file->private_data;
4214         struct zoran *zr = fh->zr;
4215         int res = 0, frame;
4216         unsigned long flags;
4217
4218         /* we should check whether buffers are ready to be synced on
4219          * (w/o waits - O_NONBLOCK) here
4220          * if ready for read (sync), return POLLIN|POLLRDNORM,
4221          * if ready for write (sync), return POLLOUT|POLLWRNORM,
4222          * if error, return POLLERR,
4223          * if no buffers queued or so, return POLLNVAL
4224          */
4225
4226         mutex_lock(&zr->resource_lock);
4227
4228         switch (fh->map_mode) {
4229         case ZORAN_MAP_MODE_RAW:
4230                 poll_wait(file, &zr->v4l_capq, wait);
4231                 frame = zr->v4l_pend[zr->v4l_sync_tail & V4L_MASK_FRAME];
4232
4233                 spin_lock_irqsave(&zr->spinlock, flags);
4234                 dprintk(3,
4235                         KERN_DEBUG
4236                         "%s: %s() raw - active=%c, sync_tail=%lu/%c, pend_tail=%lu, pend_head=%lu\n",
4237                         ZR_DEVNAME(zr), __func__,
4238                         "FAL"[fh->v4l_buffers.active], zr->v4l_sync_tail,
4239                         "UPMD"[zr->v4l_buffers.buffer[frame].state],
4240                         zr->v4l_pend_tail, zr->v4l_pend_head);
4241                 /* Process is the one capturing? */
4242                 if (fh->v4l_buffers.active != ZORAN_FREE &&
4243                     /* Buffer ready to DQBUF? */
4244                     zr->v4l_buffers.buffer[frame].state == BUZ_STATE_DONE)
4245                         res = POLLIN | POLLRDNORM;
4246                 spin_unlock_irqrestore(&zr->spinlock, flags);
4247
4248                 break;
4249
4250         case ZORAN_MAP_MODE_JPG_REC:
4251         case ZORAN_MAP_MODE_JPG_PLAY:
4252                 poll_wait(file, &zr->jpg_capq, wait);
4253                 frame = zr->jpg_pend[zr->jpg_que_tail & BUZ_MASK_FRAME];
4254
4255                 spin_lock_irqsave(&zr->spinlock, flags);
4256                 dprintk(3,
4257                         KERN_DEBUG
4258                         "%s: %s() jpg - active=%c, que_tail=%lu/%c, que_head=%lu, dma=%lu/%lu\n",
4259                         ZR_DEVNAME(zr), __func__,
4260                         "FAL"[fh->jpg_buffers.active], zr->jpg_que_tail,
4261                         "UPMD"[zr->jpg_buffers.buffer[frame].state],
4262                         zr->jpg_que_head, zr->jpg_dma_tail, zr->jpg_dma_head);
4263                 if (fh->jpg_buffers.active != ZORAN_FREE &&
4264                     zr->jpg_buffers.buffer[frame].state == BUZ_STATE_DONE) {
4265                         if (fh->map_mode == ZORAN_MAP_MODE_JPG_REC)
4266                                 res = POLLIN | POLLRDNORM;
4267                         else
4268                                 res = POLLOUT | POLLWRNORM;
4269                 }
4270                 spin_unlock_irqrestore(&zr->spinlock, flags);
4271
4272                 break;
4273
4274         default:
4275                 dprintk(1,
4276                         KERN_ERR
4277                         "%s: zoran_poll() - internal error, unknown map_mode=%d\n",
4278                         ZR_DEVNAME(zr), fh->map_mode);
4279                 res = POLLNVAL;
4280         }
4281
4282         mutex_unlock(&zr->resource_lock);
4283
4284         return res;
4285 }
4286
4287
4288 /*
4289  * This maps the buffers to user space.
4290  *
4291  * Depending on the state of fh->map_mode
4292  * the V4L or the MJPEG buffers are mapped
4293  * per buffer or all together
4294  *
4295  * Note that we need to connect to some
4296  * unmap signal event to unmap the de-allocate
4297  * the buffer accordingly (zoran_vm_close())
4298  */
4299
4300 static void
4301 zoran_vm_open (struct vm_area_struct *vma)
4302 {
4303         struct zoran_mapping *map = vma->vm_private_data;
4304
4305         map->count++;
4306 }
4307
4308 static void
4309 zoran_vm_close (struct vm_area_struct *vma)
4310 {
4311         struct zoran_mapping *map = vma->vm_private_data;
4312         struct file *file = map->file;
4313         struct zoran_fh *fh = file->private_data;
4314         struct zoran *zr = fh->zr;
4315         int i;
4316
4317         map->count--;
4318         if (map->count == 0) {
4319                 switch (fh->map_mode) {
4320                 case ZORAN_MAP_MODE_JPG_REC:
4321                 case ZORAN_MAP_MODE_JPG_PLAY:
4322
4323                         dprintk(3, KERN_INFO "%s: munmap(MJPEG)\n",
4324                                 ZR_DEVNAME(zr));
4325
4326                         for (i = 0; i < fh->jpg_buffers.num_buffers; i++) {
4327                                 if (fh->jpg_buffers.buffer[i].map == map) {
4328                                         fh->jpg_buffers.buffer[i].map =
4329                                             NULL;
4330                                 }
4331                         }
4332                         kfree(map);
4333
4334                         for (i = 0; i < fh->jpg_buffers.num_buffers; i++)
4335                                 if (fh->jpg_buffers.buffer[i].map)
4336                                         break;
4337                         if (i == fh->jpg_buffers.num_buffers) {
4338                                 mutex_lock(&zr->resource_lock);
4339
4340                                 if (fh->jpg_buffers.active != ZORAN_FREE) {
4341                                         jpg_qbuf(file, -1, zr->codec_mode);
4342                                         zr->jpg_buffers.allocated = 0;
4343                                         zr->jpg_buffers.active =
4344                                             fh->jpg_buffers.active =
4345                                             ZORAN_FREE;
4346                                 }
4347                                 //jpg_fbuffer_free(file);
4348                                 fh->jpg_buffers.allocated = 0;
4349                                 fh->jpg_buffers.ready_to_be_freed = 1;
4350
4351                                 mutex_unlock(&zr->resource_lock);
4352                         }
4353
4354                         break;
4355
4356                 case ZORAN_MAP_MODE_RAW:
4357
4358                         dprintk(3, KERN_INFO "%s: munmap(V4L)\n",
4359                                 ZR_DEVNAME(zr));
4360
4361                         for (i = 0; i < fh->v4l_buffers.num_buffers; i++) {
4362                                 if (fh->v4l_buffers.buffer[i].map == map) {
4363                                         /* unqueue/unmap */
4364                                         fh->v4l_buffers.buffer[i].map =
4365                                             NULL;
4366                                 }
4367                         }
4368                         kfree(map);
4369
4370                         for (i = 0; i < fh->v4l_buffers.num_buffers; i++)
4371                                 if (fh->v4l_buffers.buffer[i].map)
4372                                         break;
4373                         if (i == fh->v4l_buffers.num_buffers) {
4374                                 mutex_lock(&zr->resource_lock);
4375
4376                                 if (fh->v4l_buffers.active != ZORAN_FREE) {
4377                                         unsigned long flags;
4378
4379                                         spin_lock_irqsave(&zr->spinlock, flags);
4380                                         zr36057_set_memgrab(zr, 0);
4381                                         zr->v4l_buffers.allocated = 0;
4382                                         zr->v4l_buffers.active =
4383                                             fh->v4l_buffers.active =
4384                                             ZORAN_FREE;
4385                                         spin_unlock_irqrestore(&zr->spinlock, flags);
4386                                 }
4387                                 //v4l_fbuffer_free(file);
4388                                 fh->v4l_buffers.allocated = 0;
4389                                 fh->v4l_buffers.ready_to_be_freed = 1;
4390
4391                                 mutex_unlock(&zr->resource_lock);
4392                         }
4393
4394                         break;
4395
4396                 default:
4397                         printk(KERN_ERR
4398                                "%s: munmap() - internal error - unknown map mode %d\n",
4399                                ZR_DEVNAME(zr), fh->map_mode);
4400                         break;
4401
4402                 }
4403         }
4404 }
4405
4406 static struct vm_operations_struct zoran_vm_ops = {
4407         .open = zoran_vm_open,
4408         .close = zoran_vm_close,
4409 };
4410
4411 static int
4412 zoran_mmap (struct file           *file,
4413             struct vm_area_struct *vma)
4414 {
4415         struct zoran_fh *fh = file->private_data;
4416         struct zoran *zr = fh->zr;
4417         unsigned long size = (vma->vm_end - vma->vm_start);
4418         unsigned long offset = vma->vm_pgoff << PAGE_SHIFT;
4419         int i, j;
4420         unsigned long page, start = vma->vm_start, todo, pos, fraglen;
4421         int first, last;
4422         struct zoran_mapping *map;
4423         int res = 0;
4424
4425         dprintk(3,
4426                 KERN_INFO "%s: mmap(%s) of 0x%08lx-0x%08lx (size=%lu)\n",
4427                 ZR_DEVNAME(zr),
4428                 fh->map_mode == ZORAN_MAP_MODE_RAW ? "V4L" : "MJPEG",
4429                 vma->vm_start, vma->vm_end, size);
4430
4431         if (!(vma->vm_flags & VM_SHARED) || !(vma->vm_flags & VM_READ) ||
4432             !(vma->vm_flags & VM_WRITE)) {
4433                 dprintk(1,
4434                         KERN_ERR
4435                         "%s: mmap() - no MAP_SHARED/PROT_{READ,WRITE} given\n",
4436                         ZR_DEVNAME(zr));
4437                 return -EINVAL;
4438         }
4439
4440         switch (fh->map_mode) {
4441
4442         case ZORAN_MAP_MODE_JPG_REC:
4443         case ZORAN_MAP_MODE_JPG_PLAY:
4444
4445                 /* lock */
4446                 mutex_lock(&zr->resource_lock);
4447
4448                 /* Map the MJPEG buffers */
4449                 if (!fh->jpg_buffers.allocated) {
4450                         dprintk(1,
4451                                 KERN_ERR
4452                                 "%s: zoran_mmap(MJPEG) - buffers not yet allocated\n",
4453                                 ZR_DEVNAME(zr));
4454                         res = -ENOMEM;
4455                         goto jpg_mmap_unlock_and_return;
4456                 }
4457
4458                 first = offset / fh->jpg_buffers.buffer_size;
4459                 last = first - 1 + size / fh->jpg_buffers.buffer_size;
4460                 if (offset % fh->jpg_buffers.buffer_size != 0 ||
4461                     size % fh->jpg_buffers.buffer_size != 0 || first < 0 ||
4462                     last < 0 || first >= fh->jpg_buffers.num_buffers ||
4463                     last >= fh->jpg_buffers.num_buffers) {
4464                         dprintk(1,
4465                                 KERN_ERR
4466                                 "%s: mmap(MJPEG) - offset=%lu or size=%lu invalid for bufsize=%d and numbufs=%d\n",
4467                                 ZR_DEVNAME(zr), offset, size,
4468                                 fh->jpg_buffers.buffer_size,
4469                                 fh->jpg_buffers.num_buffers);
4470                         res = -EINVAL;
4471                         goto jpg_mmap_unlock_and_return;
4472                 }
4473                 for (i = first; i <= last; i++) {
4474                         if (fh->jpg_buffers.buffer[i].map) {
4475                                 dprintk(1,
4476                                         KERN_ERR
4477                                         "%s: mmap(MJPEG) - buffer %d already mapped\n",
4478                                         ZR_DEVNAME(zr), i);
4479                                 res = -EBUSY;
4480                                 goto jpg_mmap_unlock_and_return;
4481                         }
4482                 }
4483
4484                 /* map these buffers (v4l_buffers[i]) */
4485                 map = kmalloc(sizeof(struct zoran_mapping), GFP_KERNEL);
4486                 if (!map) {
4487                         res = -ENOMEM;
4488                         goto jpg_mmap_unlock_and_return;
4489                 }
4490                 map->file = file;
4491                 map->count = 1;
4492
4493                 vma->vm_ops = &zoran_vm_ops;
4494                 vma->vm_flags |= VM_DONTEXPAND;
4495                 vma->vm_private_data = map;
4496
4497                 for (i = first; i <= last; i++) {
4498                         for (j = 0;
4499                              j < fh->jpg_buffers.buffer_size / PAGE_SIZE;
4500                              j++) {
4501                                 fraglen =
4502                                     (le32_to_cpu(fh->jpg_buffers.buffer[i].
4503                                      frag_tab[2 * j + 1]) & ~1) << 1;
4504                                 todo = size;
4505                                 if (todo > fraglen)
4506                                         todo = fraglen;
4507                                 pos =
4508                                     le32_to_cpu(fh->jpg_buffers.
4509                                     buffer[i].frag_tab[2 * j]);
4510                                 /* should just be pos on i386 */
4511                                 page = virt_to_phys(bus_to_virt(pos))
4512                                                                 >> PAGE_SHIFT;
4513                                 if (remap_pfn_range(vma, start, page,
4514                                                         todo, PAGE_SHARED)) {
4515                                         dprintk(1,
4516                                                 KERN_ERR
4517                                                 "%s: zoran_mmap(V4L) - remap_pfn_range failed\n",
4518                                                 ZR_DEVNAME(zr));
4519                                         res = -EAGAIN;
4520                                         goto jpg_mmap_unlock_and_return;
4521                                 }
4522                                 size -= todo;
4523                                 start += todo;
4524                                 if (size == 0)
4525                                         break;
4526                                 if (le32_to_cpu(fh->jpg_buffers.buffer[i].
4527                                     frag_tab[2 * j + 1]) & 1)
4528                                         break;  /* was last fragment */
4529                         }
4530                         fh->jpg_buffers.buffer[i].map = map;
4531                         if (size == 0)
4532                                 break;
4533
4534                 }
4535         jpg_mmap_unlock_and_return:
4536                 mutex_unlock(&zr->resource_lock);
4537
4538                 break;
4539
4540         case ZORAN_MAP_MODE_RAW:
4541
4542                 mutex_lock(&zr->resource_lock);
4543
4544                 /* Map the V4L buffers */
4545                 if (!fh->v4l_buffers.allocated) {
4546                         dprintk(1,
4547                                 KERN_ERR
4548                                 "%s: zoran_mmap(V4L) - buffers not yet allocated\n",
4549                                 ZR_DEVNAME(zr));
4550                         res = -ENOMEM;
4551                         goto v4l_mmap_unlock_and_return;
4552                 }
4553
4554                 first = offset / fh->v4l_buffers.buffer_size;
4555                 last = first - 1 + size / fh->v4l_buffers.buffer_size;
4556                 if (offset % fh->v4l_buffers.buffer_size != 0 ||
4557                     size % fh->v4l_buffers.buffer_size != 0 || first < 0 ||
4558                     last < 0 || first >= fh->v4l_buffers.num_buffers ||
4559                     last >= fh->v4l_buffers.buffer_size) {
4560                         dprintk(1,
4561                                 KERN_ERR
4562                                 "%s: mmap(V4L) - offset=%lu or size=%lu invalid for bufsize=%d and numbufs=%d\n",
4563                                 ZR_DEVNAME(zr), offset, size,
4564                                 fh->v4l_buffers.buffer_size,
4565                                 fh->v4l_buffers.num_buffers);
4566                         res = -EINVAL;
4567                         goto v4l_mmap_unlock_and_return;
4568                 }
4569                 for (i = first; i <= last; i++) {
4570                         if (fh->v4l_buffers.buffer[i].map) {
4571                                 dprintk(1,
4572                                         KERN_ERR
4573                                         "%s: mmap(V4L) - buffer %d already mapped\n",
4574                                         ZR_DEVNAME(zr), i);
4575                                 res = -EBUSY;
4576                                 goto v4l_mmap_unlock_and_return;
4577                         }
4578                 }
4579
4580                 /* map these buffers (v4l_buffers[i]) */
4581                 map = kmalloc(sizeof(struct zoran_mapping), GFP_KERNEL);
4582                 if (!map) {
4583                         res = -ENOMEM;
4584                         goto v4l_mmap_unlock_and_return;
4585                 }
4586                 map->file = file;
4587                 map->count = 1;
4588
4589                 vma->vm_ops = &zoran_vm_ops;
4590                 vma->vm_flags |= VM_DONTEXPAND;
4591                 vma->vm_private_data = map;
4592
4593                 for (i = first; i <= last; i++) {
4594                         todo = size;
4595                         if (todo > fh->v4l_buffers.buffer_size)
4596                                 todo = fh->v4l_buffers.buffer_size;
4597                         page = fh->v4l_buffers.buffer[i].fbuffer_phys;
4598                         if (remap_pfn_range(vma, start, page >> PAGE_SHIFT,
4599                                                         todo, PAGE_SHARED)) {
4600                                 dprintk(1,
4601                                         KERN_ERR
4602                                         "%s: zoran_mmap(V4L)i - remap_pfn_range failed\n",
4603                                         ZR_DEVNAME(zr));
4604                                 res = -EAGAIN;
4605                                 goto v4l_mmap_unlock_and_return;
4606                         }
4607                         size -= todo;
4608                         start += todo;
4609                         fh->v4l_buffers.buffer[i].map = map;
4610                         if (size == 0)
4611                                 break;
4612                 }
4613         v4l_mmap_unlock_and_return:
4614                 mutex_unlock(&zr->resource_lock);
4615
4616                 break;
4617
4618         default:
4619                 dprintk(1,
4620                         KERN_ERR
4621                         "%s: zoran_mmap() - internal error - unknown map mode %d\n",
4622                         ZR_DEVNAME(zr), fh->map_mode);
4623                 break;
4624         }
4625
4626         return 0;
4627 }
4628
4629 static const struct file_operations zoran_fops = {
4630         .owner = THIS_MODULE,
4631         .open = zoran_open,
4632         .release = zoran_close,
4633         .ioctl = zoran_ioctl,
4634 #ifdef CONFIG_COMPAT
4635         .compat_ioctl   = v4l_compat_ioctl32,
4636 #endif
4637         .llseek = no_llseek,
4638         .read = zoran_read,
4639         .write = zoran_write,
4640         .mmap = zoran_mmap,
4641         .poll = zoran_poll,
4642 };
4643
4644 struct video_device zoran_template __devinitdata = {
4645         .name = ZORAN_NAME,
4646         .type = ZORAN_VID_TYPE,
4647         .type2 = ZORAN_V4L2_VID_FLAGS,
4648         .fops = &zoran_fops,
4649         .release = &zoran_vdev_release,
4650         .minor = -1
4651 };
4652