4bc486e51d7d53597b0dbc1f65eabd3146389880
[linux-flexiantxendom0-3.2.10.git] / drivers / media / video / zr36120.c
1 /*
2     zr36120.c - Zoran 36120/36125 based framegrabbers
3
4     Copyright (C) 1998-1999 Pauline Middelink <middelin@polyware.nl>
5
6     This program is free software; you can redistribute it and/or modify
7     it under the terms of the GNU General Public License as published by
8     the Free Software Foundation; either version 2 of the License, or
9     (at your option) any later version.
10
11     This program is distributed in the hope that it will be useful,
12     but WITHOUT ANY WARRANTY; without even the implied warranty of
13     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14     GNU General Public License for more details.
15
16     You should have received a copy of the GNU General Public License
17     along with this program; if not, write to the Free Software
18     Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
19 */
20
21 #include <linux/module.h>
22 #include <linux/delay.h>
23 #include <linux/init.h>
24 #include <linux/errno.h>
25 #include <linux/fs.h>
26 #include <linux/kernel.h>
27 #include <linux/major.h>
28 #include <linux/slab.h>
29 #include <linux/vmalloc.h>
30 #include <linux/mm.h>
31 #include <linux/pci.h>
32 #include <linux/signal.h>
33 #include <asm/io.h>
34 #include <asm/pgtable.h>
35 #include <asm/page.h>
36 #include <linux/sched.h>
37 #include <linux/video_decoder.h>
38
39 #include <linux/version.h>
40 #include <asm/uaccess.h>
41
42 #include "tuner.h"
43 #include "zr36120.h"
44 #include "zr36120_mem.h"
45
46 /* mark an required function argument unused - lintism */
47 #define UNUSED(x)       (void)(x)
48
49 /* sensible default */
50 #ifndef CARDTYPE
51 #define CARDTYPE 0
52 #endif
53
54 /* Anybody who uses more than four? */
55 #define ZORAN_MAX 4
56
57 static unsigned int triton1=0;                  /* triton1 chipset? */
58 static unsigned int cardtype[ZORAN_MAX]={ [ 0 ... ZORAN_MAX-1 ] = CARDTYPE };
59 static int video_nr = -1;
60 static int vbi_nr = -1;
61
62 static struct pci_device_id zr36120_pci_tbl[] = {
63         { PCI_VENDOR_ID_ZORAN,PCI_DEVICE_ID_ZORAN_36120,
64           PCI_ANY_ID, PCI_ANY_ID, 0, 0, 0 },
65         { 0 }
66 };
67 MODULE_DEVICE_TABLE(pci, zr36120_pci_tbl);
68
69 MODULE_AUTHOR("Pauline Middelink <middelin@polyware.nl>");
70 MODULE_DESCRIPTION("Zoran ZR36120 based framegrabber");
71 MODULE_LICENSE("GPL");
72
73 MODULE_PARM(triton1,"i");
74 MODULE_PARM(cardtype,"1-" __MODULE_STRING(ZORAN_MAX) "i");
75 MODULE_PARM(video_nr,"i");
76 MODULE_PARM(vbi_nr,"i");
77
78 static int zoran_cards;
79 static struct zoran zorans[ZORAN_MAX];
80
81 /*
82  * the meaning of each element can be found in zr36120.h
83  * Determining the value of gpdir/gpval can be tricky. The
84  * best way is to run the card under the original software
85  * and read the values from the general purpose registers
86  * 0x28 and 0x2C. How you do that is left as an exercise
87  * to the impatient reader :)
88  */
89 #define T 1     /* to separate the bools from the ints */
90 #define F 0
91 static struct tvcard tvcards[] = {
92         /* reported working by <middelin@polyware.nl> */
93 /*0*/   { "Trust Victor II",
94           2, 0, T, T, T, T, 0x7F, 0x80, { 1, SVHS(6) }, { 0 } },
95         /* reported working by <Michael.Paxton@aihw.gov.au>  */
96 /*1*/   { "Aitech WaveWatcher TV-PCI",
97           3, 0, T, F, T, T, 0x7F, 0x80, { 1, TUNER(3), SVHS(6) }, { 0 } },
98         /* reported working by ? */
99 /*2*/   { "Genius Video Wonder PCI Video Capture Card",
100           2, 0, T, T, T, T, 0x7F, 0x80, { 1, SVHS(6) }, { 0 } },
101         /* reported working by <Pascal.Gabriel@wanadoo.fr> */
102 /*3*/   { "Guillemot Maxi-TV PCI",
103           2, 0, T, T, T, T, 0x7F, 0x80, { 1, SVHS(6) }, { 0 } },
104         /* reported working by "Craig Whitmore <lennon@igrin.co.nz> */
105 /*4*/   { "Quadrant Buster",
106           3, 3, T, F, T, T, 0x7F, 0x80, { SVHS(1), TUNER(2), 3 }, { 1, 2, 3 } },
107         /* a debug entry which has all inputs mapped */
108 /*5*/   { "ZR36120 based framegrabber (all inputs enabled)",
109           6, 0, T, T, T, T, 0x7F, 0x80, { 1, 2, 3, 4, 5, 6 }, { 0 } }
110 };
111 #undef T
112 #undef F
113 #define NRTVCARDS (sizeof(tvcards)/sizeof(tvcards[0]))
114
115 #ifdef __sparc__
116 #define ENDIANESS       0
117 #else
118 #define ENDIANESS       ZORAN_VFEC_LE
119 #endif
120
121 static struct { const char name[8]; uint mode; uint bpp; } palette2fmt[] = {
122 /* n/a     */   { "n/a",     0, 0 },
123 /* GREY    */   { "GRAY",    0, 0 },
124 /* HI240   */   { "HI240",   0, 0 },
125 /* RGB565  */   { "RGB565",  ZORAN_VFEC_RGB_RGB565|ENDIANESS, 2 },
126 /* RGB24   */   { "RGB24",   ZORAN_VFEC_RGB_RGB888|ENDIANESS|ZORAN_VFEC_PACK24, 3 },
127 /* RGB32   */   { "RGB32",   ZORAN_VFEC_RGB_RGB888|ENDIANESS, 4 },
128 /* RGB555  */   { "RGB555",  ZORAN_VFEC_RGB_RGB555|ENDIANESS, 2 },
129 /* YUV422  */   { "YUV422",  ZORAN_VFEC_RGB_YUV422|ENDIANESS, 2 },
130 /* YUYV    */   { "YUYV",    0, 0 },
131 /* UYVY    */   { "UYVY",    0, 0 },
132 /* YUV420  */   { "YUV420",  0, 0 },
133 /* YUV411  */   { "YUV411",  0, 0 },
134 /* RAW     */   { "RAW",     0, 0 },
135 /* YUV422P */   { "YUV422P", 0, 0 },
136 /* YUV411P */   { "YUV411P", 0, 0 }};
137 #define NRPALETTES (sizeof(palette2fmt)/sizeof(palette2fmt[0]))
138 #undef ENDIANESS
139
140 /* ----------------------------------------------------------------------- */
141 /* ZORAN chipset detector                                                 */
142 /* shamelessly stolen from bttv.c                                         */
143 /* Reason for beeing here: we need to detect if we are running on a        */
144 /* Triton based chipset, and if so, enable a certain bit                   */
145 /* ----------------------------------------------------------------------- */
146 static
147 void __init handle_chipset(void)
148 {
149         struct pci_dev *dev = NULL;
150
151         /* Just in case some nut set this to something dangerous */
152         if (triton1)
153                 triton1 = ZORAN_VDC_TRICOM;
154
155         while ((dev = pci_find_device(PCI_VENDOR_ID_INTEL, PCI_DEVICE_ID_INTEL_82437, dev)))
156         {
157                 printk(KERN_INFO "zoran: Host bridge 82437FX Triton PIIX\n");
158                 triton1 = ZORAN_VDC_TRICOM;
159         }
160 }
161
162 /* ----------------------------------------------------------------------- */
163 /* ZORAN functions                                                         */
164 /* ----------------------------------------------------------------------- */
165
166 static void zoran_set_geo(struct zoran* ztv, struct vidinfo* i);
167
168 #if 0 /* unused */
169 static
170 void zoran_dump(struct zoran *ztv)
171 {
172         char    str[256];
173         char    *p=str; /* shut up, gcc! */
174         int     i;
175
176         for (i=0; i<0x60; i+=4) {
177                 if ((i % 16) == 0) {
178                         if (i) printk("%s\n",str);
179                         p = str;
180                         p+= sprintf(str, KERN_DEBUG "       %04x: ",i);
181                 }
182                 p += sprintf(p, "%08x ",zrread(i));
183         }
184 }
185 #endif /* unused */
186
187 static
188 void reap_states(struct zoran* ztv)
189 {
190         /* count frames */
191         ztv->fieldnr++;
192
193         /*
194          * Are we busy at all?
195          * This depends on if there is a workqueue AND the
196          * videotransfer is enabled on the chip...
197          */
198         if (ztv->workqueue && (zrread(ZORAN_VDC) & ZORAN_VDC_VIDEN))
199         {
200                 struct vidinfo* newitem;
201
202                 /* did we get a complete frame? */
203                 if (zrread(ZORAN_VSTR) & ZORAN_VSTR_GRAB)
204                         return;
205
206 DEBUG(printk(CARD_DEBUG "completed %s at %p\n",CARD,ztv->workqueue->kindof==FBUFFER_GRAB?"grab":"read",ztv->workqueue));
207
208                 /* we are done with this buffer, tell everyone */
209                 ztv->workqueue->status = FBUFFER_DONE;
210                 ztv->workqueue->fieldnr = ztv->fieldnr;
211                 /* not good, here for BTTV_FIELDNR reasons */
212                 ztv->lastfieldnr = ztv->fieldnr;
213
214                 switch (ztv->workqueue->kindof) {
215                  case FBUFFER_GRAB:
216                         wake_up_interruptible(&ztv->grabq);
217                         break;
218                  case FBUFFER_VBI:
219                         wake_up_interruptible(&ztv->vbiq);
220                         break;
221                  default:
222                         printk(CARD_INFO "somebody killed the workqueue (kindof=%d)!\n",CARD,ztv->workqueue->kindof);
223                 }
224
225                 /* item completed, skip to next item in queue */
226                 write_lock(&ztv->lock);
227                 newitem = ztv->workqueue->next;
228                 ztv->workqueue->next = 0;       /* mark completed */
229                 ztv->workqueue = newitem;
230                 write_unlock(&ztv->lock);
231         }
232
233         /*
234          * ok, so it seems we have nothing in progress right now.
235          * Lets see if we can find some work.
236          */
237         if (ztv->workqueue)
238         {
239                 struct vidinfo* newitem;
240 again:
241
242 DEBUG(printk(CARD_DEBUG "starting %s at %p\n",CARD,ztv->workqueue->kindof==FBUFFER_GRAB?"grab":"read",ztv->workqueue));
243
244                 /* loadup the frame settings */
245                 read_lock(&ztv->lock);
246                 zoran_set_geo(ztv,ztv->workqueue);
247                 read_unlock(&ztv->lock);
248
249                 switch (ztv->workqueue->kindof) {
250                  case FBUFFER_GRAB:
251                  case FBUFFER_VBI:
252                         zrand(~ZORAN_OCR_OVLEN, ZORAN_OCR);
253                         zror(ZORAN_VSTR_SNAPSHOT,ZORAN_VSTR);
254                         zror(ZORAN_VDC_VIDEN,ZORAN_VDC);
255
256                         /* start single-shot grab */
257                         zror(ZORAN_VSTR_GRAB, ZORAN_VSTR);
258                         break;
259                  default:
260                         printk(CARD_INFO "what is this doing on the queue? (kindof=%d)\n",CARD,ztv->workqueue->kindof);
261                         write_lock(&ztv->lock);
262                         newitem = ztv->workqueue->next;
263                         ztv->workqueue->next = 0;
264                         ztv->workqueue = newitem;
265                         write_unlock(&ztv->lock);
266                         if (newitem)
267                                 goto again;     /* yeah, sure.. */
268                 }
269                 /* bye for now */
270                 return;
271         }
272 DEBUG(printk(CARD_DEBUG "nothing in queue\n",CARD));
273
274         /*
275          * What? Even the workqueue is empty? Am i really here
276          * for nothing? Did i come all that way to... do nothing?
277          */
278
279         /* do we need to overlay? */
280         if (test_bit(STATE_OVERLAY, &ztv->state))
281         {
282                 /* are we already overlaying? */
283                 if (!(zrread(ZORAN_OCR) & ZORAN_OCR_OVLEN) ||
284                     !(zrread(ZORAN_VDC) & ZORAN_VDC_VIDEN))
285                 {
286 DEBUG(printk(CARD_DEBUG "starting overlay\n",CARD));
287
288                         read_lock(&ztv->lock);
289                         zoran_set_geo(ztv,&ztv->overinfo);
290                         read_unlock(&ztv->lock);
291
292                         zror(ZORAN_OCR_OVLEN, ZORAN_OCR);
293                         zrand(~ZORAN_VSTR_SNAPSHOT,ZORAN_VSTR);
294                         zror(ZORAN_VDC_VIDEN,ZORAN_VDC);
295                 }
296
297                 /*
298                  * leave overlaying on, but turn interrupts off.
299                  */
300                 zrand(~ZORAN_ICR_EN,ZORAN_ICR);
301                 return;
302         }
303
304         /* do we have any VBI idle time processing? */
305         if (test_bit(STATE_VBI, &ztv->state))
306         {
307                 struct vidinfo* item;
308                 struct vidinfo* lastitem;
309
310                 /* protect the workqueue */
311                 write_lock(&ztv->lock);
312                 lastitem = ztv->workqueue;
313                 if (lastitem)
314                         while (lastitem->next) lastitem = lastitem->next;
315                 for (item=ztv->readinfo; item!=ztv->readinfo+ZORAN_VBI_BUFFERS; item++)
316                         if (item->next == 0 && item->status == FBUFFER_FREE)
317                         {
318 DEBUG(printk(CARD_DEBUG "%p added to queue\n",CARD,item));
319                                 item->status = FBUFFER_BUSY;
320                                 if (!lastitem)
321                                         ztv->workqueue = item;
322                                 else 
323                                         lastitem->next = item;
324                                 lastitem = item;
325                         }
326                 write_unlock(&ztv->lock);
327                 if (ztv->workqueue)
328                         goto again;     /* hey, _i_ graduated :) */
329         }
330
331         /*
332          * Then we must be realy IDLE
333          */
334 DEBUG(printk(CARD_DEBUG "turning off\n",CARD));
335         /* nothing further to do, disable DMA and further IRQs */
336         zrand(~ZORAN_VDC_VIDEN,ZORAN_VDC);
337         zrand(~ZORAN_ICR_EN,ZORAN_ICR);
338 }
339
340 static
341 void zoran_irq(int irq, void *dev_id, struct pt_regs * regs)
342 {
343         u32 stat,estat;
344         int count = 0;
345         struct zoran *ztv = (struct zoran *)dev_id;
346
347         UNUSED(irq); UNUSED(regs);
348         for (;;) {
349                 /* get/clear interrupt status bits */
350                 stat=zrread(ZORAN_ISR);
351                 estat=stat & zrread(ZORAN_ICR);
352                 if (!estat)
353                         return;
354                 zrwrite(estat,ZORAN_ISR);
355                 IDEBUG(printk(CARD_DEBUG "estat %08x\n",CARD,estat));
356                 IDEBUG(printk(CARD_DEBUG " stat %08x\n",CARD,stat));
357
358                 if (estat & ZORAN_ISR_CODE)
359                 {
360                         IDEBUG(printk(CARD_DEBUG "CodReplIRQ\n",CARD));
361                 }
362                 if (estat & ZORAN_ISR_GIRQ0)
363                 {
364                         IDEBUG(printk(CARD_DEBUG "GIRQ0\n",CARD));
365                         if (!ztv->card->usegirq1)
366                                 reap_states(ztv);
367                 }
368                 if (estat & ZORAN_ISR_GIRQ1)
369                 {
370                         IDEBUG(printk(CARD_DEBUG "GIRQ1\n",CARD));
371                         if (ztv->card->usegirq1)
372                                 reap_states(ztv);
373                 }
374
375                 count++;
376                 if (count > 10)
377                         printk(CARD_ERR "irq loop %d (%x)\n",CARD,count,estat);
378                 if (count > 20)
379                 {
380                         zrwrite(0, ZORAN_ICR);
381                         printk(CARD_ERR "IRQ lockup, cleared int mask\n",CARD);
382                 }
383         }
384 }
385
386 static
387 int zoran_muxsel(struct zoran* ztv, int channel, int norm)
388 {
389         int     rv;
390
391         /* set the new video norm */
392         rv = i2c_control_device(&(ztv->i2c), I2C_DRIVERID_VIDEODECODER, DECODER_SET_NORM, &norm);
393         if (rv)
394                 return rv;
395         ztv->norm = norm;
396
397         /* map the given channel to the cards decoder's channel */
398         channel = ztv->card->video_mux[channel] & CHANNEL_MASK;
399
400         /* set the new channel */
401         rv = i2c_control_device(&(ztv->i2c), I2C_DRIVERID_VIDEODECODER, DECODER_SET_INPUT, &channel);
402         return rv;
403 }
404
405 /* Tell the interrupt handler what to to.  */
406 static
407 void zoran_cap(struct zoran* ztv, int on)
408 {
409 DEBUG(printk(CARD_DEBUG "zoran_cap(%d) state=%x\n",CARD,on,ztv->state));
410
411         if (on) {
412                 ztv->running = 1;
413
414                 /*
415                  * turn interrupts (back) on. The DMA will be enabled
416                  * inside the irq handler when it detects a restart.
417                  */
418                 zror(ZORAN_ICR_EN,ZORAN_ICR);
419         }
420         else {
421                 /*
422                  * turn both interrupts and DMA off
423                  */
424                 zrand(~ZORAN_VDC_VIDEN,ZORAN_VDC);
425                 zrand(~ZORAN_ICR_EN,ZORAN_ICR);
426
427                 ztv->running = 0;
428         }
429 }
430
431 static ulong dmask[] = {
432         0xFFFFFFFF, 0xFFFFFFFE, 0xFFFFFFFC, 0xFFFFFFF8,
433         0xFFFFFFF0, 0xFFFFFFE0, 0xFFFFFFC0, 0xFFFFFF80,
434         0xFFFFFF00, 0xFFFFFE00, 0xFFFFFC00, 0xFFFFF800,
435         0xFFFFF000, 0xFFFFE000, 0xFFFFC000, 0xFFFF8000,
436         0xFFFF0000, 0xFFFE0000, 0xFFFC0000, 0xFFF80000,
437         0xFFF00000, 0xFFE00000, 0xFFC00000, 0xFF800000,
438         0xFF000000, 0xFE000000, 0xFC000000, 0xF8000000,
439         0xF0000000, 0xE0000000, 0xC0000000, 0x80000000
440 };
441
442 static
443 void zoran_built_overlay(struct zoran* ztv, int count, struct video_clip *vcp)
444 {
445         ulong*  mtop;
446         int     ystep = (ztv->vidXshift + ztv->vidWidth+31)/32; /* next DWORD */
447         int     i;
448
449 DEBUG(printk(KERN_DEBUG "       overlay at %p, ystep=%d, clips=%d\n",ztv->overinfo.overlay,ystep,count));
450
451         for (i=0; i<count; i++) {
452                 struct video_clip *vp = vcp+i;
453                 UNUSED(vp);
454 DEBUG(printk(KERN_DEBUG "       %d: clip(%d,%d,%d,%d)\n", i,vp->x,vp->y,vp->width,vp->height));
455         }
456
457         /*
458          * activate the visible portion of the screen
459          * Note we take some shortcuts here, because we
460          * know the width can never be < 32. (I.e. a DWORD)
461          * We also assume the overlay starts somewhere in
462          * the FIRST dword.
463          */
464         {
465                 int start = ztv->vidXshift;
466                 ulong firstd = dmask[start];
467                 ulong lastd = ~dmask[(start + ztv->overinfo.w) & 31];
468                 mtop = ztv->overinfo.overlay;
469                 for (i=0; i<ztv->overinfo.h; i++) {
470                         int w = ztv->vidWidth;
471                         ulong* line = mtop;
472                         if (start & 31) {
473                                 *line++ = firstd;
474                                 w -= 32-(start&31);
475                         }
476                         memset(line, ~0, w/8);
477                         if (w & 31)
478                                 line[w/32] = lastd;
479                         mtop += ystep;
480                 }
481         }
482
483         /* process clipping regions */
484         for (i=0; i<count; i++) {
485                 int h;
486                 if (vcp->x < 0 || (uint)vcp->x > ztv->overinfo.w ||
487                     vcp->y < 0 || vcp->y > ztv->overinfo.h ||
488                     vcp->width < 0 || (uint)(vcp->x+vcp->width) > ztv->overinfo.w ||
489                     vcp->height < 0 || (vcp->y+vcp->height) > ztv->overinfo.h)
490                 {
491                         DEBUG(printk(CARD_DEBUG "illegal clipzone (%d,%d,%d,%d) not in (0,0,%d,%d), adapting\n",CARD,vcp->x,vcp->y,vcp->width,vcp->height,ztv->overinfo.w,ztv->overinfo.h));
492                         if (vcp->x < 0) vcp->x = 0;
493                         if ((uint)vcp->x > ztv->overinfo.w) vcp->x = ztv->overinfo.w;
494                         if (vcp->y < 0) vcp->y = 0;
495                         if (vcp->y > ztv->overinfo.h) vcp->y = ztv->overinfo.h;
496                         if (vcp->width < 0) vcp->width = 0;
497                         if ((uint)(vcp->x+vcp->width) > ztv->overinfo.w) vcp->width = ztv->overinfo.w - vcp->x;
498                         if (vcp->height < 0) vcp->height = 0;
499                         if (vcp->y+vcp->height > ztv->overinfo.h) vcp->height = ztv->overinfo.h - vcp->y;
500 //                      continue;
501                 }
502
503                 mtop = &ztv->overinfo.overlay[vcp->y*ystep];
504                 for (h=0; h<=vcp->height; h++) {
505                         int w;
506                         int x = ztv->vidXshift + vcp->x;
507                         for (w=0; w<=vcp->width; w++) {
508                                 clear_bit(x&31, &mtop[x/32]);
509                                 x++;
510                         }
511                         mtop += ystep;
512                 }
513                 ++vcp;
514         }
515
516         mtop = ztv->overinfo.overlay;
517         zrwrite(virt_to_bus(mtop), ZORAN_MTOP);
518         zrwrite(virt_to_bus(mtop+ystep), ZORAN_MBOT);
519         zraor((ztv->vidInterlace*ystep)<<0,~ZORAN_OCR_MASKSTRIDE,ZORAN_OCR);
520 }
521
522 struct tvnorm 
523 {
524         u16 Wt, Wa, Ht, Ha, HStart, VStart;
525 };
526
527 static struct tvnorm tvnorms[] = {
528         /* PAL-BDGHI */
529 /*      { 864, 720, 625, 576, 131, 21 },*/
530 /*00*/  { 864, 768, 625, 576, 81, 17 },
531         /* NTSC */
532 /*01*/  { 858, 720, 525, 480, 121, 10 },
533         /* SECAM */
534 /*02*/  { 864, 720, 625, 576, 131, 21 },
535         /* BW50 */
536 /*03*/  { 864, 720, 625, 576, 131, 21 },
537         /* BW60 */
538 /*04*/  { 858, 720, 525, 480, 121, 10 }
539 };
540 #define TVNORMS (sizeof(tvnorms)/sizeof(tvnorm))
541
542 /*
543  * Program the chip for a setup as described in the vidinfo struct.
544  *
545  * Side-effects: calculates vidXshift, vidInterlace,
546  * vidHeight, vidWidth which are used in a later stage
547  * to calculate the overlay mask
548  *
549  * This is an internal function, as such it does not check the
550  * validity of the struct members... Spectaculair crashes will
551  * follow /very/ quick when you're wrong and the chip right :)
552  */
553 static
554 void zoran_set_geo(struct zoran* ztv, struct vidinfo* i)
555 {
556         ulong   top, bot;
557         int     stride;
558         int     winWidth, winHeight;
559         int     maxWidth, maxHeight, maxXOffset, maxYOffset;
560         long    vfec;
561
562 DEBUG(printk(CARD_DEBUG "set_geo(rect=(%d,%d,%d,%d), norm=%d, format=%d, bpp=%d, bpl=%d, busadr=%lx, overlay=%p)\n",CARD,i->x,i->y,i->w,i->h,ztv->norm,i->format,i->bpp,i->bpl,i->busadr,i->overlay));
563
564         /*
565          * make sure the DMA transfers are inhibited during our
566          * reprogramming of the chip
567          */
568         zrand(~ZORAN_VDC_VIDEN,ZORAN_VDC);
569
570         maxWidth = tvnorms[ztv->norm].Wa;
571         maxHeight = tvnorms[ztv->norm].Ha/2;
572         maxXOffset = tvnorms[ztv->norm].HStart;
573         maxYOffset = tvnorms[ztv->norm].VStart;
574
575         /* setup vfec register (keep ExtFl,TopField and VCLKPol settings) */
576         vfec = (zrread(ZORAN_VFEC) & (ZORAN_VFEC_EXTFL|ZORAN_VFEC_TOPFIELD|ZORAN_VFEC_VCLKPOL)) |
577                (palette2fmt[i->format].mode & (ZORAN_VFEC_RGB|ZORAN_VFEC_ERRDIF|ZORAN_VFEC_LE|ZORAN_VFEC_PACK24));
578
579         /*
580          * Set top, bottom ptrs. Since these must be DWORD aligned,
581          * possible adjust the x and the width of the window.
582          * so the endposition stay the same. The vidXshift will make
583          * sure we are not writing pixels before the requested x.
584          */
585         ztv->vidXshift = 0;
586         winWidth = i->w;
587         if (winWidth < 0)
588                 winWidth = -winWidth;
589         top = i->busadr + i->x*i->bpp + i->y*i->bpl;
590         if (top & 3) {
591                 ztv->vidXshift = (top & 3) / i->bpp;
592                 winWidth += ztv->vidXshift;
593                 DEBUG(printk(KERN_DEBUG "       window-x shifted %d pixels left\n",ztv->vidXshift));
594                 top &= ~3;
595         }
596
597         /*
598          * bottom points to next frame but in interleaved mode we want
599          * to 'mix' the 2 frames to one capture, so 'bot' points to one
600          * (physical) line below the top line.
601          */
602         bot = top + i->bpl;
603         zrwrite(top,ZORAN_VTOP);
604         zrwrite(bot,ZORAN_VBOT);
605
606         /*
607          * Make sure the winWidth is DWORD aligned too,
608          * thereby automaticly making sure the stride to the
609          * next line is DWORD aligned too (as required by spec).
610          */
611         if ((winWidth*i->bpp) & 3) {
612 DEBUG(printk(KERN_DEBUG "       window-width enlarged by %d pixels\n",(winWidth*i->bpp) & 3));
613                 winWidth += (winWidth*i->bpp) & 3;
614         }
615
616         /* determine the DispMode and stride */
617         if (i->h >= 0 && i->h <= maxHeight) {
618                 /* single frame grab suffices for this height. */
619                 vfec |= ZORAN_VFEC_DISPMOD;
620                 ztv->vidInterlace = 0;
621                 stride = i->bpl - (winWidth*i->bpp);
622                 winHeight = i->h;
623         }
624         else {
625                 /* interleaving needed for this height */
626                 ztv->vidInterlace = 1;
627                 stride = i->bpl*2 - (winWidth*i->bpp);
628                 winHeight = i->h/2;
629         }
630         if (winHeight < 0)      /* can happen for VBI! */
631                 winHeight = -winHeight;
632
633         /* safety net, sometimes bpl is too short??? */
634         if (stride<0) {
635 DEBUG(printk(CARD_DEBUG "WARNING stride = %d\n",CARD,stride));
636                 stride = 0;
637         }
638
639         zraor((winHeight<<12)|(winWidth<<0),~(ZORAN_VDC_VIDWINHT|ZORAN_VDC_VIDWINWID), ZORAN_VDC);
640         zraor(stride<<16,~ZORAN_VSTR_DISPSTRIDE,ZORAN_VSTR);
641
642         /* remember vidWidth, vidHeight for overlay calculations */
643         ztv->vidWidth = winWidth;
644         ztv->vidHeight = winHeight;
645 DEBUG(printk(KERN_DEBUG "       top=%08lx, bottom=%08lx\n",top,bot));
646 DEBUG(printk(KERN_DEBUG "       winWidth=%d, winHeight=%d\n",winWidth,winHeight));
647 DEBUG(printk(KERN_DEBUG "       maxWidth=%d, maxHeight=%d\n",maxWidth,maxHeight));
648 DEBUG(printk(KERN_DEBUG "       stride=%d\n",stride));
649
650         /*
651          * determine horizontal scales and crops
652          */
653         if (i->w < 0) {
654                 int Hstart = 1;
655                 int Hend = Hstart + winWidth;
656 DEBUG(printk(KERN_DEBUG "       Y: scale=0, start=%d, end=%d\n", Hstart, Hend));
657                 zraor((Hstart<<10)|(Hend<<0),~(ZORAN_VFEH_HSTART|ZORAN_VFEH_HEND),ZORAN_VFEH);
658         }
659         else {
660                 int Wa = maxWidth;
661                 int X = (winWidth*64+Wa-1)/Wa;
662                 int We = winWidth*64/X;
663                 int HorDcm = 64-X;
664                 int hcrop1 = 2*(Wa-We)/4;
665                 /*
666                  * BUGFIX: Juha Nurmela <junki@qn-lpr2-165.quicknet.inet.fi> 
667                  * found the solution to the color phase shift.
668                  * See ChangeLog for the full explanation)
669                  */
670                 int Hstart = (maxXOffset + hcrop1) | 1;
671                 int Hend = Hstart + We - 1;
672
673 DEBUG(printk(KERN_DEBUG "       X: scale=%d, start=%d, end=%d\n", HorDcm, Hstart, Hend));
674
675                 zraor((Hstart<<10)|(Hend<<0),~(ZORAN_VFEH_HSTART|ZORAN_VFEH_HEND),ZORAN_VFEH);
676                 vfec |= HorDcm<<14;
677
678                 if (HorDcm<16)
679                         vfec |= ZORAN_VFEC_HFILTER_1; /* no filter */
680                 else if (HorDcm<32)
681                         vfec |= ZORAN_VFEC_HFILTER_3; /* 3 tap filter */
682                 else if (HorDcm<48)
683                         vfec |= ZORAN_VFEC_HFILTER_4; /* 4 tap filter */
684                 else    vfec |= ZORAN_VFEC_HFILTER_5; /* 5 tap filter */
685         }
686
687         /*
688          * Determine vertical scales and crops
689          *
690          * when height is negative, we want to read starting at line 0
691          * One day someone might need access to these lines...
692          */
693         if (i->h < 0) {
694                 int Vstart = 0;
695                 int Vend = Vstart + winHeight;
696 DEBUG(printk(KERN_DEBUG "       Y: scale=0, start=%d, end=%d\n", Vstart, Vend));
697                 zraor((Vstart<<10)|(Vend<<0),~(ZORAN_VFEV_VSTART|ZORAN_VFEV_VEND),ZORAN_VFEV);
698         }
699         else {
700                 int Ha = maxHeight;
701                 int Y = (winHeight*64+Ha-1)/Ha;
702                 int He = winHeight*64/Y;
703                 int VerDcm = 64-Y;
704                 int vcrop1 = 2*(Ha-He)/4;
705                 int Vstart = maxYOffset + vcrop1;
706                 int Vend = Vstart + He - 1;
707
708 DEBUG(printk(KERN_DEBUG "       Y: scale=%d, start=%d, end=%d\n", VerDcm, Vstart, Vend));
709                 zraor((Vstart<<10)|(Vend<<0),~(ZORAN_VFEV_VSTART|ZORAN_VFEV_VEND),ZORAN_VFEV);
710                 vfec |= VerDcm<<8;
711         }
712
713 DEBUG(printk(KERN_DEBUG "       F: format=%d(=%s)\n",i->format,palette2fmt[i->format].name));
714
715         /* setup the requested format */
716         zrwrite(vfec, ZORAN_VFEC);
717 }
718
719 static
720 void zoran_common_open(struct zoran* ztv, int flags)
721 {
722         UNUSED(flags);
723
724         /* already opened? */
725         if (ztv->users++ != 0)
726                 return;
727
728         /* unmute audio */
729         /* /what/ audio? */
730
731         ztv->state = 0;
732
733         /* setup the encoder to the initial values */
734         ztv->picture.colour=254<<7;
735         ztv->picture.brightness=128<<8;
736         ztv->picture.hue=128<<8;
737         ztv->picture.contrast=216<<7;
738         i2c_control_device(&ztv->i2c, I2C_DRIVERID_VIDEODECODER, DECODER_SET_PICTURE, &ztv->picture);
739
740         /* default to the composite input since my camera is there */
741         zoran_muxsel(ztv, 0, VIDEO_MODE_PAL);
742 }
743
744 static
745 void zoran_common_close(struct zoran* ztv)
746 {
747         if (--ztv->users != 0)
748                 return;
749
750         /* mute audio */
751         /* /what/ audio? */
752
753         /* stop the chip */
754         zoran_cap(ztv, 0);
755 }
756
757 /*
758  * Open a zoran card. Right now the flags are just a hack
759  */
760 static int zoran_open(struct video_device *dev, int flags)
761 {
762         struct zoran *ztv = (struct zoran*)dev;
763         struct vidinfo* item;
764         char* pos;
765
766         DEBUG(printk(CARD_DEBUG "open(dev,%d)\n",CARD,flags));
767
768         /*********************************************
769          * We really should be doing lazy allocing...
770          *********************************************/
771         /* allocate a frame buffer */
772         if (!ztv->fbuffer)
773                 ztv->fbuffer = bmalloc(ZORAN_MAX_FBUFSIZE);
774         if (!ztv->fbuffer) {
775                 /* could not get a buffer, bail out */
776                 return -ENOBUFS;
777         }
778         /* at this time we _always_ have a framebuffer */
779         memset(ztv->fbuffer,0,ZORAN_MAX_FBUFSIZE);
780
781         if (!ztv->overinfo.overlay)
782                 ztv->overinfo.overlay = (void*)kmalloc(1024*1024/8, GFP_KERNEL);
783         if (!ztv->overinfo.overlay) {
784                 /* could not get an overlay buffer, bail out */
785                 bfree(ztv->fbuffer, ZORAN_MAX_FBUFSIZE);
786                 return -ENOBUFS;
787         }
788         /* at this time we _always_ have a overlay */
789
790         /* clear buffer status, and give them a DMAable address */
791         pos = ztv->fbuffer;
792         for (item=ztv->grabinfo; item!=ztv->grabinfo+ZORAN_MAX_FBUFFERS; item++)
793         {
794                 item->status = FBUFFER_FREE;
795                 item->memadr = pos;
796                 item->busadr = virt_to_bus(pos);
797                 pos += ZORAN_MAX_FBUFFER;
798         }
799
800         /* do the common part of all open's */
801         zoran_common_open(ztv, flags);
802
803         return 0;
804 }
805
806 static
807 void zoran_close(struct video_device* dev)
808 {
809         struct zoran *ztv = (struct zoran*)dev;
810
811         DEBUG(printk(CARD_DEBUG "close(dev)\n",CARD));
812
813         /* driver specific closure */
814         clear_bit(STATE_OVERLAY, &ztv->state);
815
816         zoran_common_close(ztv);
817
818         /*
819          *      This is sucky but right now I can't find a good way to
820          *      be sure its safe to free the buffer. We wait 5-6 fields
821          *      which is more than sufficient to be sure.
822          */
823         current->state = TASK_UNINTERRUPTIBLE;
824         schedule_timeout(HZ/10);        /* Wait 1/10th of a second */
825
826         /* free the allocated framebuffer */
827         if (ztv->fbuffer)
828                 bfree( ztv->fbuffer, ZORAN_MAX_FBUFSIZE );
829         ztv->fbuffer = 0;
830         if (ztv->overinfo.overlay)
831                 kfree( ztv->overinfo.overlay );
832         ztv->overinfo.overlay = 0;
833
834 }
835
836 /*
837  * This read function could be used reentrant in a SMP situation.
838  *
839  * This is made possible by the spinlock which is kept till we
840  * found and marked a buffer for our own use. The lock must
841  * be released as soon as possible to prevent lock contention.
842  */
843 static
844 long zoran_read(struct video_device* dev, char* buf, unsigned long count, int nonblock)
845 {
846         struct zoran *ztv = (struct zoran*)dev;
847         unsigned long max;
848         struct vidinfo* unused = 0;
849         struct vidinfo* done = 0;
850
851         DEBUG(printk(CARD_DEBUG "zoran_read(%p,%ld,%d)\n",CARD,buf,count,nonblock));
852
853         /* find ourself a free or completed buffer */
854         for (;;) {
855                 struct vidinfo* item;
856
857                 write_lock_irq(&ztv->lock);
858                 for (item=ztv->grabinfo; item!=ztv->grabinfo+ZORAN_MAX_FBUFFERS; item++)
859                 {
860                         if (!unused && item->status == FBUFFER_FREE)
861                                 unused = item;
862                         if (!done && item->status == FBUFFER_DONE)
863                                 done = item;
864                 }
865                 if (done || unused)
866                         break;
867
868                 /* no more free buffers, wait for them. */
869                 write_unlock_irq(&ztv->lock);
870                 if (nonblock)
871                         return -EWOULDBLOCK;
872                 interruptible_sleep_on(&ztv->grabq);
873                 if (signal_pending(current))
874                         return -EINTR;
875         }
876
877         /* Do we have 'ready' data? */
878         if (!done) {
879                 /* no? than this will take a while... */
880                 if (nonblock) {
881                         write_unlock_irq(&ztv->lock);
882                         return -EWOULDBLOCK;
883                 }
884
885                 /* mark the unused buffer as wanted */
886                 unused->status = FBUFFER_BUSY;
887                 unused->w = 320;
888                 unused->h = 240;
889                 unused->format = VIDEO_PALETTE_RGB24;
890                 unused->bpp = palette2fmt[unused->format].bpp;
891                 unused->bpl = unused->w * unused->bpp;
892                 unused->next = 0;
893                 { /* add to tail of queue */
894                   struct vidinfo* oldframe = ztv->workqueue;
895                   if (!oldframe) ztv->workqueue = unused;
896                   else {
897                     while (oldframe->next) oldframe = oldframe->next;
898                     oldframe->next = unused;
899                   }
900                 }
901                 write_unlock_irq(&ztv->lock);
902
903                 /* tell the state machine we want it filled /NOW/ */
904                 zoran_cap(ztv, 1);
905
906                 /* wait till this buffer gets grabbed */
907                 while (unused->status == FBUFFER_BUSY) {
908                         interruptible_sleep_on(&ztv->grabq);
909                         /* see if a signal did it */
910                         if (signal_pending(current))
911                                 return -EINTR;
912                 }
913                 done = unused;
914         }
915         else
916                 write_unlock_irq(&ztv->lock);
917
918         /* Yes! we got data! */
919         max = done->bpl * done->h;
920         if (count > max)
921                 count = max;
922         if (copy_to_user((void*)buf, done->memadr, count))
923                 count = -EFAULT;
924
925         /* keep the engine running */
926         done->status = FBUFFER_FREE;
927 //      zoran_cap(ztv,1);
928
929         /* tell listeners this buffer became free */
930         wake_up_interruptible(&ztv->grabq);
931
932         /* goodbye */
933         DEBUG(printk(CARD_DEBUG "zoran_read() returns %lu\n",CARD,count));
934         return count;
935 }
936
937 static
938 long zoran_write(struct video_device* dev, const char* buf, unsigned long count, int nonblock)
939 {
940         struct zoran *ztv = (struct zoran *)dev;
941         UNUSED(ztv); UNUSED(dev); UNUSED(buf); UNUSED(count); UNUSED(nonblock);
942         DEBUG(printk(CARD_DEBUG "zoran_write\n",CARD));
943         return -EINVAL;
944 }
945
946 static
947 unsigned int zoran_poll(struct video_device *dev, struct file *file, poll_table *wait)
948 {
949         struct zoran *ztv = (struct zoran *)dev;
950         struct vidinfo* item;
951         unsigned int mask = 0;
952
953         poll_wait(file, &ztv->grabq, wait);
954
955         for (item=ztv->grabinfo; item!=ztv->grabinfo+ZORAN_MAX_FBUFFERS; item++)
956                 if (item->status == FBUFFER_DONE)
957                 {
958                         mask |= (POLLIN | POLLRDNORM);
959                         break;
960                 }
961
962         DEBUG(printk(CARD_DEBUG "zoran_poll()=%x\n",CARD,mask));
963
964         return mask;
965 }
966
967 /* append a new clipregion to the vector of video_clips */
968 static
969 void new_clip(struct video_window* vw, struct video_clip* vcp, int x, int y, int w, int h)
970 {
971         vcp[vw->clipcount].x = x;
972         vcp[vw->clipcount].y = y;
973         vcp[vw->clipcount].width = w;
974         vcp[vw->clipcount].height = h;
975         vw->clipcount++;
976 }
977
978 static
979 int zoran_ioctl(struct video_device* dev, unsigned int cmd, void *arg)
980 {
981         struct zoran* ztv = (struct zoran*)dev;
982
983         switch (cmd) {
984          case VIDIOCGCAP:
985          {
986                 struct video_capability c;
987                 DEBUG(printk(CARD_DEBUG "VIDIOCGCAP\n",CARD));
988
989                 strcpy(c.name,ztv->video_dev.name);
990                 c.type = VID_TYPE_CAPTURE|
991                          VID_TYPE_OVERLAY|
992                          VID_TYPE_CLIPPING|
993                          VID_TYPE_FRAMERAM|
994                          VID_TYPE_SCALES;
995                 if (ztv->have_tuner)
996                         c.type |= VID_TYPE_TUNER;
997                 if (ztv->have_decoder) {
998                         c.channels = ztv->card->video_inputs;
999                         c.audios = ztv->card->audio_inputs;
1000                 } else
1001                         /* no decoder -> no channels */
1002                         c.channels = c.audios = 0;
1003                 c.maxwidth = 768;
1004                 c.maxheight = 576;
1005                 c.minwidth = 32;
1006                 c.minheight = 32;
1007                 if (copy_to_user(arg,&c,sizeof(c)))
1008                         return -EFAULT;
1009                 break;
1010          }
1011
1012          case VIDIOCGCHAN:
1013          {
1014                 struct video_channel v;
1015                 int mux;
1016                 if (copy_from_user(&v, arg,sizeof(v)))
1017                         return -EFAULT;
1018                 DEBUG(printk(CARD_DEBUG "VIDIOCGCHAN(%d)\n",CARD,v.channel));
1019                 v.flags=VIDEO_VC_AUDIO
1020 #ifdef VIDEO_VC_NORM
1021                         |VIDEO_VC_NORM
1022 #endif
1023                         ;
1024                 v.tuners=0;
1025                 v.type=VIDEO_TYPE_CAMERA;
1026 #ifdef I_EXPECT_POSSIBLE_NORMS_IN_THE_API
1027                 v.norm=VIDEO_MODE_PAL|
1028                        VIDEO_MODE_NTSC|
1029                        VIDEO_MODE_SECAM;
1030 #else
1031                 v.norm=VIDEO_MODE_PAL;
1032 #endif
1033                 /* too many inputs? no decoder -> no channels */
1034                 if (!ztv->have_decoder || v.channel < 0 ||  v.channel >= ztv->card->video_inputs)
1035                         return -EINVAL;
1036
1037                 /* now determine the name of the channel */
1038                 mux = ztv->card->video_mux[v.channel];
1039                 if (mux & IS_TUNER) {
1040                         /* lets assume only one tuner, yes? */
1041                         strcpy(v.name,"Television");
1042                         v.type = VIDEO_TYPE_TV;
1043                         if (ztv->have_tuner) {
1044                                 v.flags |= VIDEO_VC_TUNER;
1045                                 v.tuners = 1;
1046                         }
1047                 }
1048                 else if (mux & IS_SVHS)
1049                         sprintf(v.name,"S-Video-%d",v.channel);
1050                 else
1051                         sprintf(v.name,"CVBS-%d",v.channel);
1052
1053                 if (copy_to_user(arg,&v,sizeof(v)))
1054                         return -EFAULT;
1055                 break;
1056          }
1057          case VIDIOCSCHAN:
1058          {      /* set video channel */
1059                 struct video_channel v;
1060                 if (copy_from_user(&v, arg,sizeof(v)))
1061                         return -EFAULT;
1062                 DEBUG(printk(CARD_DEBUG "VIDIOCSCHAN(%d,%d)\n",CARD,v.channel,v.norm));
1063
1064                 /* too many inputs? no decoder -> no channels */
1065                 if (!ztv->have_decoder || v.channel >= ztv->card->video_inputs || v.channel < 0)
1066                         return -EINVAL;
1067
1068                 if (v.norm != VIDEO_MODE_PAL &&
1069                     v.norm != VIDEO_MODE_NTSC &&
1070                     v.norm != VIDEO_MODE_SECAM &&
1071                     v.norm != VIDEO_MODE_AUTO)
1072                         return -EOPNOTSUPP;
1073
1074                 /* make it happen, nr1! */
1075                 return zoran_muxsel(ztv,v.channel,v.norm);
1076          }
1077
1078          case VIDIOCGTUNER:
1079          {
1080                 struct video_tuner v;
1081                 if (copy_from_user(&v, arg,sizeof(v)))
1082                         return -EFAULT;
1083                 DEBUG(printk(CARD_DEBUG "VIDIOCGTUNER(%d)\n",CARD,v.tuner));
1084
1085                 /* Only no or one tuner for now */
1086                 if (!ztv->have_tuner || v.tuner)
1087                         return -EINVAL;
1088
1089                 strcpy(v.name,"Television");
1090                 v.rangelow  = 0;
1091                 v.rangehigh = ~0;
1092                 v.flags     = VIDEO_TUNER_PAL|VIDEO_TUNER_NTSC|VIDEO_TUNER_SECAM;
1093                 v.mode      = ztv->norm;
1094                 v.signal    = 0xFFFF; /* unknown */
1095
1096                 if (copy_to_user(arg,&v,sizeof(v)))
1097                         return -EFAULT;
1098                 break;
1099          }
1100          case VIDIOCSTUNER:
1101          {
1102                 struct video_tuner v;
1103                 if (copy_from_user(&v, arg, sizeof(v)))
1104                         return -EFAULT;
1105                 DEBUG(printk(CARD_DEBUG "VIDIOCSTUNER(%d,%d)\n",CARD,v.tuner,v.mode));
1106
1107                 /* Only no or one tuner for now */
1108                 if (!ztv->have_tuner || v.tuner)
1109                         return -EINVAL;
1110
1111                 /* and it only has certain valid modes */
1112                 if( v.mode != VIDEO_MODE_PAL &&
1113                     v.mode != VIDEO_MODE_NTSC &&
1114                     v.mode != VIDEO_MODE_SECAM)
1115                         return -EOPNOTSUPP;
1116
1117                 /* engage! */
1118                 return zoran_muxsel(ztv,v.tuner,v.mode);
1119          }
1120
1121          case VIDIOCGPICT:
1122          {
1123                 struct video_picture p = ztv->picture;
1124                 DEBUG(printk(CARD_DEBUG "VIDIOCGPICT\n",CARD));
1125                 p.depth = ztv->depth;
1126                 switch (p.depth) {
1127                  case  8: p.palette=VIDEO_PALETTE_YUV422;
1128                           break;
1129                  case 15: p.palette=VIDEO_PALETTE_RGB555;
1130                           break;
1131                  case 16: p.palette=VIDEO_PALETTE_RGB565;
1132                           break;
1133                  case 24: p.palette=VIDEO_PALETTE_RGB24;
1134                           break;
1135                  case 32: p.palette=VIDEO_PALETTE_RGB32;
1136                           break;
1137                 }
1138                 if (copy_to_user(arg, &p, sizeof(p)))
1139                         return -EFAULT;
1140                 break;
1141          }
1142          case VIDIOCSPICT:
1143          {
1144                 struct video_picture p;
1145                 if (copy_from_user(&p, arg,sizeof(p)))
1146                         return -EFAULT;
1147                 DEBUG(printk(CARD_DEBUG "VIDIOCSPICT(%d,%d,%d,%d,%d,%d,%d)\n",CARD,p.brightness,p.hue,p.colour,p.contrast,p.whiteness,p.depth,p.palette));
1148
1149                 /* depth must match with framebuffer */
1150                 if (p.depth != ztv->depth)
1151                         return -EINVAL;
1152
1153                 /* check if palette matches this bpp */
1154                 if (p.palette>NRPALETTES ||
1155                     palette2fmt[p.palette].bpp != ztv->overinfo.bpp)
1156                         return -EINVAL;
1157
1158                 write_lock_irq(&ztv->lock);
1159                 ztv->overinfo.format = p.palette;
1160                 ztv->picture = p;
1161                 write_unlock_irq(&ztv->lock);
1162
1163                 /* tell the decoder */
1164                 i2c_control_device(&ztv->i2c, I2C_DRIVERID_VIDEODECODER, DECODER_SET_PICTURE, &p);
1165                 break;
1166          }
1167
1168          case VIDIOCGWIN:
1169          {
1170                 struct video_window vw;
1171                 DEBUG(printk(CARD_DEBUG "VIDIOCGWIN\n",CARD));
1172                 read_lock(&ztv->lock);
1173                 vw.x      = ztv->overinfo.x;
1174                 vw.y      = ztv->overinfo.y;
1175                 vw.width  = ztv->overinfo.w;
1176                 vw.height = ztv->overinfo.h;
1177                 vw.chromakey= 0;
1178                 vw.flags  = 0;
1179                 if (ztv->vidInterlace)
1180                         vw.flags|=VIDEO_WINDOW_INTERLACE;
1181                 read_unlock(&ztv->lock);
1182                 if (copy_to_user(arg,&vw,sizeof(vw)))
1183                         return -EFAULT;
1184                 break;
1185          }
1186          case VIDIOCSWIN:
1187          {
1188                 struct video_window vw;
1189                 struct video_clip *vcp;
1190                 int on;
1191                 if (copy_from_user(&vw,arg,sizeof(vw)))
1192                         return -EFAULT;
1193                 DEBUG(printk(CARD_DEBUG "VIDIOCSWIN(%d,%d,%d,%d,%x,%d)\n",CARD,vw.x,vw.y,vw.width,vw.height,vw.flags,vw.clipcount));
1194
1195                 if (vw.flags)
1196                         return -EINVAL;
1197
1198                 if (vw.clipcount <0 || vw.clipcount>256)
1199                         return -EDOM;   /* Too many! */
1200
1201                 /*
1202                  *      Do any clips.
1203                  */
1204                 vcp = vmalloc(sizeof(struct video_clip)*(vw.clipcount+4));
1205                 if (vcp==NULL)
1206                         return -ENOMEM;
1207                 if (vw.clipcount && copy_from_user(vcp,vw.clips,sizeof(struct video_clip)*vw.clipcount)) {
1208                         vfree(vcp);
1209                         return -EFAULT;
1210                 }
1211
1212                 on = ztv->running;
1213                 if (on)
1214                         zoran_cap(ztv, 0);
1215
1216                 /*
1217                  * strange, it seems xawtv sometimes calls us with 0
1218                  * width and/or height. Ignore these values
1219                  */
1220                 if (vw.x == 0)
1221                         vw.x = ztv->overinfo.x;
1222                 if (vw.y == 0)
1223                         vw.y = ztv->overinfo.y;
1224
1225                 /* by now we are committed to the new data... */
1226                 write_lock_irq(&ztv->lock);
1227                 ztv->overinfo.x = vw.x;
1228                 ztv->overinfo.y = vw.y;
1229                 ztv->overinfo.w = vw.width;
1230                 ztv->overinfo.h = vw.height;
1231                 write_unlock_irq(&ztv->lock);
1232
1233                 /*
1234                  *      Impose display clips
1235                  */
1236                 if (vw.x+vw.width > ztv->swidth)
1237                         new_clip(&vw, vcp, ztv->swidth-vw.x, 0, vw.width-1, vw.height-1);
1238                 if (vw.y+vw.height > ztv->sheight)
1239                         new_clip(&vw, vcp, 0, ztv->sheight-vw.y, vw.width-1, vw.height-1);
1240
1241                 /* built the requested clipping zones */
1242                 zoran_set_geo(ztv, &ztv->overinfo);
1243                 zoran_built_overlay(ztv, vw.clipcount, vcp);
1244                 vfree(vcp);
1245
1246                 /* if we were on, restart the video engine */
1247                 if (on)
1248                         zoran_cap(ztv, 1);
1249                 break;
1250          }
1251
1252          case VIDIOCCAPTURE:
1253          {
1254                 int v;
1255                 if (get_user(v, (int *)arg))
1256                         return -EFAULT;
1257                 DEBUG(printk(CARD_DEBUG "VIDIOCCAPTURE(%d)\n",CARD,v));
1258
1259                 if (v==0) {
1260                         clear_bit(STATE_OVERLAY, &ztv->state);
1261                         zoran_cap(ztv, 1);
1262                 }
1263                 else {
1264                         /* is VIDIOCSFBUF, VIDIOCSWIN done? */
1265                         if (ztv->overinfo.busadr==0 || ztv->overinfo.w==0 || ztv->overinfo.h==0)
1266                                 return -EINVAL;
1267
1268                         set_bit(STATE_OVERLAY, &ztv->state);
1269                         zoran_cap(ztv, 1);
1270                 }
1271                 break;
1272          }
1273
1274          case VIDIOCGFBUF:
1275          {
1276                 struct video_buffer v;
1277                 DEBUG(printk(CARD_DEBUG "VIDIOCGFBUF\n",CARD));
1278                 read_lock(&ztv->lock);
1279                 v.base   = (void *)ztv->overinfo.busadr;
1280                 v.height = ztv->sheight;
1281                 v.width  = ztv->swidth;
1282                 v.depth  = ztv->depth;
1283                 v.bytesperline = ztv->overinfo.bpl;
1284                 read_unlock(&ztv->lock);
1285                 if(copy_to_user(arg, &v,sizeof(v)))
1286                         return -EFAULT;
1287                 break;
1288          }
1289          case VIDIOCSFBUF:
1290          {
1291                 struct video_buffer v;
1292                 if(!capable(CAP_SYS_ADMIN))
1293                         return -EPERM;
1294                 if (copy_from_user(&v, arg,sizeof(v)))
1295                         return -EFAULT;
1296                 DEBUG(printk(CARD_DEBUG "VIDIOCSFBUF(%p,%d,%d,%d,%d)\n",CARD,v.base, v.width,v.height,v.depth,v.bytesperline));
1297
1298                 if (v.depth!=15 && v.depth!=16 && v.depth!=24 && v.depth!=32)
1299                         return -EINVAL;
1300                 if (v.bytesperline<1)
1301                         return -EINVAL;
1302                 if (ztv->running)
1303                         return -EBUSY;
1304                 write_lock_irq(&ztv->lock);
1305                 ztv->overinfo.busadr  = (ulong)v.base;
1306                 ztv->sheight      = v.height;
1307                 ztv->swidth       = v.width;
1308                 ztv->depth        = v.depth;            /* bits per pixel */
1309                 ztv->overinfo.bpp = ((v.depth+1)&0x38)/8;/* bytes per pixel */
1310                 ztv->overinfo.bpl = v.bytesperline;     /* bytes per line */
1311                 write_unlock_irq(&ztv->lock);
1312                 break;
1313          }
1314
1315          case VIDIOCKEY:
1316          {
1317                 /* Will be handled higher up .. */
1318                 break;
1319          }
1320
1321          case VIDIOCSYNC:
1322          {
1323                 int i;
1324                 if (get_user(i, (int *) arg))
1325                         return -EFAULT;
1326                 DEBUG(printk(CARD_DEBUG "VIDEOCSYNC(%d)\n",CARD,i));
1327                 if (i<0 || i>ZORAN_MAX_FBUFFERS)
1328                         return -EINVAL;
1329                 switch (ztv->grabinfo[i].status) {
1330                  case FBUFFER_FREE:
1331                         return -EINVAL;
1332                  case FBUFFER_BUSY:
1333                         /* wait till this buffer gets grabbed */
1334                         while (ztv->grabinfo[i].status == FBUFFER_BUSY) {
1335                                 interruptible_sleep_on(&ztv->grabq);
1336                                 /* see if a signal did it */
1337                                 if (signal_pending(current))
1338                                         return -EINTR;
1339                         }
1340                         /* don't fall through; a DONE buffer is not UNUSED */
1341                         break;
1342                  case FBUFFER_DONE:
1343                         ztv->grabinfo[i].status = FBUFFER_FREE;
1344                         /* tell ppl we have a spare buffer */
1345                         wake_up_interruptible(&ztv->grabq);
1346                         break;
1347                 }
1348                 DEBUG(printk(CARD_DEBUG "VIDEOCSYNC(%d) returns\n",CARD,i));
1349                 break;
1350          }
1351
1352          case VIDIOCMCAPTURE:
1353          {
1354                 struct video_mmap vm;
1355                 struct vidinfo* frame;
1356                 if (copy_from_user(&vm,arg,sizeof(vm)))
1357                         return -EFAULT;
1358                 DEBUG(printk(CARD_DEBUG "VIDIOCMCAPTURE(%d,(%d,%d),%d)\n",CARD,vm.frame,vm.width,vm.height,vm.format));
1359                 if (vm.frame<0 || vm.frame>ZORAN_MAX_FBUFFERS ||
1360                     vm.width<32 || vm.width>768 ||
1361                     vm.height<32 || vm.height>576 ||
1362                     vm.format>NRPALETTES ||
1363                     palette2fmt[vm.format].mode == 0)
1364                         return -EINVAL;
1365
1366                 /* we are allowed to take over UNUSED and DONE buffers */
1367                 frame = &ztv->grabinfo[vm.frame];
1368                 if (frame->status == FBUFFER_BUSY)
1369                         return -EBUSY;
1370
1371                 /* setup the other parameters if they are given */
1372                 write_lock_irq(&ztv->lock);
1373                 frame->w = vm.width;
1374                 frame->h = vm.height;
1375                 frame->format = vm.format;
1376                 frame->bpp = palette2fmt[frame->format].bpp;
1377                 frame->bpl = frame->w*frame->bpp;
1378                 frame->status = FBUFFER_BUSY;
1379                 frame->next = 0;
1380                 { /* add to tail of queue */
1381                   struct vidinfo* oldframe = ztv->workqueue;
1382                   if (!oldframe) ztv->workqueue = frame;
1383                   else {
1384                     while (oldframe->next) oldframe = oldframe->next;
1385                     oldframe->next = frame;
1386                   }
1387                 }
1388                 write_unlock_irq(&ztv->lock);
1389                 zoran_cap(ztv, 1);
1390                 break;
1391          }
1392
1393          case VIDIOCGMBUF:
1394          {
1395                 struct video_mbuf mb;
1396                 int i;
1397                 DEBUG(printk(CARD_DEBUG "VIDIOCGMBUF\n",CARD));
1398                 mb.size = ZORAN_MAX_FBUFSIZE;
1399                 mb.frames = ZORAN_MAX_FBUFFERS;
1400                 for (i=0; i<ZORAN_MAX_FBUFFERS; i++)
1401                         mb.offsets[i] = i*ZORAN_MAX_FBUFFER;
1402                 if(copy_to_user(arg, &mb,sizeof(mb)))
1403                         return -EFAULT;
1404                 break;
1405          }
1406
1407          case VIDIOCGUNIT:
1408          {
1409                 struct video_unit vu;
1410                 DEBUG(printk(CARD_DEBUG "VIDIOCGUNIT\n",CARD));
1411                 vu.video = ztv->video_dev.minor;
1412                 vu.vbi = ztv->vbi_dev.minor;
1413                 vu.radio = VIDEO_NO_UNIT;
1414                 vu.audio = VIDEO_NO_UNIT;
1415                 vu.teletext = VIDEO_NO_UNIT;
1416                 if(copy_to_user(arg, &vu,sizeof(vu)))
1417                         return -EFAULT;
1418                 break;
1419          }
1420
1421          case VIDIOCGFREQ:
1422          {
1423                 unsigned long v = ztv->tuner_freq;
1424                 if (copy_to_user(arg,&v,sizeof(v)))
1425                         return -EFAULT;
1426                 DEBUG(printk(CARD_DEBUG "VIDIOCGFREQ\n",CARD));
1427                 break;
1428          }
1429          case VIDIOCSFREQ:
1430          {
1431                 unsigned long v;
1432                 if (copy_from_user(&v, arg, sizeof(v)))
1433                         return -EFAULT;
1434                 DEBUG(printk(CARD_DEBUG "VIDIOCSFREQ\n",CARD));
1435
1436                 if (ztv->have_tuner) {
1437                         int fixme = v;
1438                         if (i2c_control_device(&(ztv->i2c), I2C_DRIVERID_TUNER, TUNER_SET_TVFREQ, &fixme) < 0)
1439                                 return -EAGAIN;
1440                 }
1441                 ztv->tuner_freq = v;
1442                 break;
1443          }
1444
1445          /* Why isn't this in the API?
1446           * And why doesn't it take a buffer number?
1447          case BTTV_FIELDNR: 
1448          {
1449                 unsigned long v = ztv->lastfieldnr;
1450                 if (copy_to_user(arg,&v,sizeof(v)))
1451                         return -EFAULT;
1452                 DEBUG(printk(CARD_DEBUG "BTTV_FIELDNR\n",CARD));
1453                 break;
1454          }
1455          */
1456
1457          default:
1458                 return -ENOIOCTLCMD;
1459         }
1460         return 0;
1461 }
1462
1463 static
1464 int zoran_mmap(struct vm_area_struct *vma, struct video_device* dev, const char* adr, unsigned long size)
1465 {
1466         struct zoran* ztv = (struct zoran*)dev;
1467         unsigned long start = (unsigned long)adr;
1468         unsigned long pos;
1469
1470         DEBUG(printk(CARD_DEBUG "zoran_mmap(0x%p,%ld)\n",CARD,adr,size));
1471
1472         /* sanity checks */
1473         if (size > ZORAN_MAX_FBUFSIZE || !ztv->fbuffer)
1474                 return -EINVAL;
1475
1476         /* start mapping the whole shabang to user memory */
1477         pos = (unsigned long)ztv->fbuffer;
1478         while (size>0) {
1479                 unsigned long page = virt_to_phys((void*)pos);
1480                 if (remap_page_range(vma, start, page, PAGE_SIZE, PAGE_SHARED))
1481                         return -EAGAIN;
1482                 start += PAGE_SIZE;
1483                 pos += PAGE_SIZE;
1484                 size -= PAGE_SIZE;
1485         }
1486         return 0;
1487 }
1488
1489 static struct video_device zr36120_template=
1490 {
1491         .owner          = THIS_MODULE,
1492         .name           = "UNSET",
1493         .type           = VID_TYPE_TUNER|VID_TYPE_CAPTURE|VID_TYPE_OVERLAY,
1494         .hardware       = VID_HARDWARE_ZR36120,
1495         .open           = zoran_open,
1496         .close          = zoran_close,
1497         .read           = zoran_read,
1498         .write          = zoran_write,
1499         .poll           = zoran_poll,
1500         .ioctl          = zoran_ioctl,
1501         .mmap           = zoran_mmap,
1502         .minor          = -1,
1503 };
1504
1505 static
1506 int vbi_open(struct video_device *dev, int flags)
1507 {
1508         struct zoran *ztv = (struct zoran*)dev->priv;
1509         struct vidinfo* item;
1510
1511         DEBUG(printk(CARD_DEBUG "vbi_open(dev,%d)\n",CARD,flags));
1512
1513         /*
1514          * During VBI device open, we continiously grab VBI-like
1515          * data in the vbi buffer when we have nothing to do.
1516          * Only when there is an explicit request for VBI data
1517          * (read call) we /force/ a read.
1518          */
1519
1520         /* allocate buffers */
1521         for (item=ztv->readinfo; item!=ztv->readinfo+ZORAN_VBI_BUFFERS; item++)
1522         {
1523                 item->status = FBUFFER_FREE;
1524
1525                 /* alloc */
1526                 if (!item->memadr) {
1527                         item->memadr = bmalloc(ZORAN_VBI_BUFSIZE);
1528                         if (!item->memadr) {
1529                                 /* could not get a buffer, bail out */
1530                                 while (item != ztv->readinfo) {
1531                                         item--;
1532                                         bfree(item->memadr, ZORAN_VBI_BUFSIZE);
1533                                         item->memadr = 0;
1534                                         item->busadr = 0;
1535                                 }
1536                                 return -ENOBUFS;
1537                         }
1538                 }
1539
1540                 /* determine the DMAable address */
1541                 item->busadr = virt_to_bus(item->memadr);
1542         }
1543
1544         /* do the common part of all open's */
1545         zoran_common_open(ztv, flags);
1546
1547         set_bit(STATE_VBI, &ztv->state);
1548         /* start read-ahead */
1549         zoran_cap(ztv, 1);
1550
1551         return 0;
1552 }
1553
1554 static
1555 void vbi_close(struct video_device *dev)
1556 {
1557         struct zoran *ztv = (struct zoran*)dev->priv;
1558         struct vidinfo* item;
1559
1560         DEBUG(printk(CARD_DEBUG "vbi_close(dev)\n",CARD));
1561
1562         /* driver specific closure */
1563         clear_bit(STATE_VBI, &ztv->state);
1564
1565         zoran_common_close(ztv);
1566
1567         /*
1568          *      This is sucky but right now I can't find a good way to
1569          *      be sure its safe to free the buffer. We wait 5-6 fields
1570          *      which is more than sufficient to be sure.
1571          */
1572         current->state = TASK_UNINTERRUPTIBLE;
1573         schedule_timeout(HZ/10);        /* Wait 1/10th of a second */
1574
1575         for (item=ztv->readinfo; item!=ztv->readinfo+ZORAN_VBI_BUFFERS; item++)
1576         {
1577                 if (item->memadr)
1578                         bfree(item->memadr, ZORAN_VBI_BUFSIZE);
1579                 item->memadr = 0;
1580         }
1581
1582 }
1583
1584 /*
1585  * This read function could be used reentrant in a SMP situation.
1586  *
1587  * This is made possible by the spinlock which is kept till we
1588  * found and marked a buffer for our own use. The lock must
1589  * be released as soon as possible to prevent lock contention.
1590  */
1591 static
1592 long vbi_read(struct video_device* dev, char* buf, unsigned long count, int nonblock)
1593 {
1594         struct zoran *ztv = (struct zoran*)dev->priv;
1595         unsigned long max;
1596         struct vidinfo* unused = 0;
1597         struct vidinfo* done = 0;
1598
1599         DEBUG(printk(CARD_DEBUG "vbi_read(0x%p,%ld,%d)\n",CARD,buf,count,nonblock));
1600
1601         /* find ourself a free or completed buffer */
1602         for (;;) {
1603                 struct vidinfo* item;
1604
1605                 write_lock_irq(&ztv->lock);
1606                 for (item=ztv->readinfo; item!=ztv->readinfo+ZORAN_VBI_BUFFERS; item++) {
1607                         if (!unused && item->status == FBUFFER_FREE)
1608                                 unused = item;
1609                         if (!done && item->status == FBUFFER_DONE)
1610                                 done = item;
1611                 }
1612                 if (done || unused)
1613                         break;
1614
1615                 /* no more free buffers, wait for them. */
1616                 write_unlock_irq(&ztv->lock);
1617                 if (nonblock)
1618                         return -EWOULDBLOCK;
1619                 interruptible_sleep_on(&ztv->vbiq);
1620                 if (signal_pending(current))
1621                         return -EINTR;
1622         }
1623
1624         /* Do we have 'ready' data? */
1625         if (!done) {
1626                 /* no? than this will take a while... */
1627                 if (nonblock) {
1628                         write_unlock_irq(&ztv->lock);
1629                         return -EWOULDBLOCK;
1630                 }
1631                 
1632                 /* mark the unused buffer as wanted */
1633                 unused->status = FBUFFER_BUSY;
1634                 unused->next = 0;
1635                 { /* add to tail of queue */
1636                   struct vidinfo* oldframe = ztv->workqueue;
1637                   if (!oldframe) ztv->workqueue = unused;
1638                   else {
1639                     while (oldframe->next) oldframe = oldframe->next;
1640                     oldframe->next = unused;
1641                   }
1642                 }
1643                 write_unlock_irq(&ztv->lock);
1644
1645                 /* tell the state machine we want it filled /NOW/ */
1646                 zoran_cap(ztv, 1);
1647
1648                 /* wait till this buffer gets grabbed */
1649                 while (unused->status == FBUFFER_BUSY) {
1650                         interruptible_sleep_on(&ztv->vbiq);
1651                         /* see if a signal did it */
1652                         if (signal_pending(current))
1653                                 return -EINTR;
1654                 }
1655                 done = unused;
1656         }
1657         else
1658                 write_unlock_irq(&ztv->lock);
1659
1660         /* Yes! we got data! */
1661         max = done->bpl * -done->h;
1662         if (count > max)
1663                 count = max;
1664
1665         /* check if the user gave us enough room to write the data */
1666         if (!access_ok(VERIFY_WRITE, buf, count)) {
1667                 count = -EFAULT;
1668                 goto out;
1669         }
1670
1671         /*
1672          * Now transform/strip the data from YUV to Y-only
1673          * NB. Assume the Y is in the LSB of the YUV data.
1674          */
1675         {
1676         unsigned char* optr = buf;
1677         unsigned char* eptr = buf+count;
1678
1679         /* are we beeing accessed from an old driver? */
1680         if (count == 2*19*2048) {
1681                 /*
1682                  * Extreme HACK, old VBI programs expect 2048 points
1683                  * of data, and we only got 864 orso. Double each 
1684                  * datapoint and clear the rest of the line.
1685                  * This way we have appear to have a
1686                  * sample_frequency of 29.5 Mc.
1687                  */
1688                 int x,y;
1689                 unsigned char* iptr = done->memadr+1;
1690                 for (y=done->h; optr<eptr && y<0; y++)
1691                 {
1692                         /* copy to doubled data to userland */
1693                         for (x=0; optr+1<eptr && x<-done->w; x++)
1694                         {
1695                                 unsigned char a = iptr[x*2];
1696                                 __put_user(a, optr++);
1697                                 __put_user(a, optr++);
1698                         }
1699                         /* and clear the rest of the line */
1700                         for (x*=2; optr<eptr && x<done->bpl; x++)
1701                                 __put_user(0, optr++);
1702                         /* next line */
1703                         iptr += done->bpl;
1704                 }
1705         }
1706         else {
1707                 /*
1708                  * Other (probably newer) programs asked
1709                  * us what geometry we are using, and are
1710                  * reading the correct size.
1711                  */
1712                 int x,y;
1713                 unsigned char* iptr = done->memadr+1;
1714                 for (y=done->h; optr<eptr && y<0; y++)
1715                 {
1716                         /* copy to doubled data to userland */
1717                         for (x=0; optr<eptr && x<-done->w; x++)
1718                                 __put_user(iptr[x*2], optr++);
1719                         /* and clear the rest of the line */
1720                         for (;optr<eptr && x<done->bpl; x++)
1721                                 __put_user(0, optr++);
1722                         /* next line */
1723                         iptr += done->bpl;
1724                 }
1725         }
1726
1727         /* API compliance:
1728          * place the framenumber (half fieldnr) in the last long
1729          */
1730         __put_user(done->fieldnr/2, ((ulong*)eptr)[-1]);
1731         }
1732
1733         /* keep the engine running */
1734         done->status = FBUFFER_FREE;
1735         zoran_cap(ztv, 1);
1736
1737         /* tell listeners this buffer just became free */
1738         wake_up_interruptible(&ztv->vbiq);
1739
1740         /* goodbye */
1741 out:
1742         DEBUG(printk(CARD_DEBUG "vbi_read() returns %lu\n",CARD,count));
1743         return count;
1744 }
1745
1746 static
1747 unsigned int vbi_poll(struct video_device *dev, struct file *file, poll_table *wait)
1748 {
1749         struct zoran *ztv = (struct zoran*)dev->priv;
1750         struct vidinfo* item;
1751         unsigned int mask = 0;
1752
1753         poll_wait(file, &ztv->vbiq, wait);
1754
1755         for (item=ztv->readinfo; item!=ztv->readinfo+ZORAN_VBI_BUFFERS; item++)
1756                 if (item->status == FBUFFER_DONE)
1757                 {
1758                         mask |= (POLLIN | POLLRDNORM);
1759                         break;
1760                 }
1761
1762         DEBUG(printk(CARD_DEBUG "vbi_poll()=%x\n",CARD,mask));
1763
1764         return mask;
1765 }
1766
1767 static
1768 int vbi_ioctl(struct video_device *dev, unsigned int cmd, void *arg)
1769 {
1770         struct zoran* ztv = (struct zoran*)dev->priv;
1771
1772         switch (cmd) {
1773          case VIDIOCGVBIFMT:
1774          {
1775                 struct vbi_format f;
1776                 DEBUG(printk(CARD_DEBUG "VIDIOCGVBIINFO\n",CARD));
1777                 f.sampling_rate = 14750000UL;
1778                 f.samples_per_line = -ztv->readinfo[0].w;
1779                 f.sample_format = VIDEO_PALETTE_RAW;
1780                 f.start[0] = f.start[1] = ztv->readinfo[0].y;
1781                 f.start[1] += 312;
1782                 f.count[0] = f.count[1] = -ztv->readinfo[0].h;
1783                 f.flags = VBI_INTERLACED;
1784                 if (copy_to_user(arg,&f,sizeof(f)))
1785                         return -EFAULT;
1786                 break;
1787          }
1788          case VIDIOCSVBIFMT:
1789          {
1790                 struct vbi_format f;
1791                 int i;
1792                 if (copy_from_user(&f, arg,sizeof(f)))
1793                         return -EFAULT;
1794                 DEBUG(printk(CARD_DEBUG "VIDIOCSVBIINFO(%d,%d,%d,%d,%d,%d,%d,%x)\n",CARD,f.sampling_rate,f.samples_per_line,f.sample_format,f.start[0],f.start[1],f.count[0],f.count[1],f.flags));
1795
1796                 /* lots of parameters are fixed... (PAL) */
1797                 if (f.sampling_rate != 14750000UL ||
1798                     f.samples_per_line > 864 ||
1799                     f.sample_format != VIDEO_PALETTE_RAW ||
1800                     f.start[0] < 0 ||
1801                     f.start[0] != f.start[1]-312 ||
1802                     f.count[0] != f.count[1] ||
1803                     f.start[0]+f.count[0] >= 288 ||
1804                     f.flags != VBI_INTERLACED)
1805                         return -EINVAL;
1806
1807                 write_lock_irq(&ztv->lock);
1808                 ztv->readinfo[0].y = f.start[0];
1809                 ztv->readinfo[0].w = -f.samples_per_line;
1810                 ztv->readinfo[0].h = -f.count[0];
1811                 ztv->readinfo[0].bpl = f.samples_per_line*ztv->readinfo[0].bpp;
1812                 for (i=1; i<ZORAN_VBI_BUFFERS; i++)
1813                         ztv->readinfo[i] = ztv->readinfo[i];
1814                 write_unlock_irq(&ztv->lock);
1815                 break;
1816          }
1817          default:
1818                 return -ENOIOCTLCMD;
1819         }
1820         return 0;
1821 }
1822
1823 static struct video_device vbi_template=
1824 {
1825         .owner          = THIS_MODULE,
1826         .name           = "UNSET",
1827         .type           = VID_TYPE_CAPTURE|VID_TYPE_TELETEXT,
1828         .hardware       = VID_HARDWARE_ZR36120,
1829         .open           = vbi_open,
1830         .close          = vbi_close,
1831         .read           = vbi_read,
1832         .write          = zoran_write,
1833         .poll           = vbi_poll,
1834         .ioctl          = vbi_ioctl,
1835         .minor          = -1,
1836 };
1837
1838 /*
1839  *      Scan for a Zoran chip, request the irq and map the io memory
1840  */
1841 static
1842 int __init find_zoran(void)
1843 {
1844         int result;
1845         struct zoran *ztv;
1846         struct pci_dev *dev = NULL;
1847         unsigned char revision;
1848         int zoran_num=0;
1849
1850         while ((dev = pci_find_device(PCI_VENDOR_ID_ZORAN,PCI_DEVICE_ID_ZORAN_36120, dev)))
1851         {
1852                 /* Ok, a ZR36120/ZR36125 found! */
1853                 ztv = &zorans[zoran_num];
1854                 ztv->dev = dev;
1855
1856                 if (pci_enable_device(dev))
1857                         return -EIO;
1858
1859                 pci_read_config_byte(dev, PCI_CLASS_REVISION, &revision);
1860                 printk(KERN_INFO "zoran: Zoran %x (rev %d) ",
1861                         dev->device, revision);
1862                 printk("bus: %d, devfn: %d, irq: %d, ",
1863                         dev->bus->number, dev->devfn, dev->irq);
1864                 printk("memory: 0x%08lx.\n", ztv->zoran_adr);
1865
1866                 ztv->zoran_mem = ioremap(ztv->zoran_adr, 0x1000);
1867                 DEBUG(printk(KERN_DEBUG "zoran: mapped-memory at 0x%p\n",ztv->zoran_mem));
1868
1869                 result = request_irq(dev->irq, zoran_irq,
1870                         SA_SHIRQ|SA_INTERRUPT,"zoran",(void *)ztv);
1871                 if (result==-EINVAL)
1872                 {
1873                         iounmap(ztv->zoran_mem);
1874                         printk(KERN_ERR "zoran: Bad irq number or handler\n");
1875                         return -EINVAL;
1876                 }
1877                 if (result==-EBUSY)
1878                         printk(KERN_ERR "zoran: IRQ %d busy, change your PnP config in BIOS\n",dev->irq);
1879                 if (result < 0) {
1880                         iounmap(ztv->zoran_mem);
1881                         return result;
1882                 }
1883                 /* Enable bus-mastering */
1884                 pci_set_master(dev);
1885
1886                 zoran_num++;
1887         }
1888         if(zoran_num)
1889                 printk(KERN_INFO "zoran: %d Zoran card(s) found.\n",zoran_num);
1890         return zoran_num;
1891 }
1892
1893 static
1894 int __init init_zoran(int card)
1895 {
1896         struct zoran *ztv = &zorans[card];
1897         int     i;
1898
1899         /* if the given cardtype valid? */
1900         if (cardtype[card]>=NRTVCARDS) {
1901                 printk(KERN_INFO "invalid cardtype(%d) detected\n",cardtype[card]);
1902                 return -1;
1903         }
1904
1905         /* reset the zoran */
1906         zrand(~ZORAN_PCI_SOFTRESET,ZORAN_PCI);
1907         udelay(10);
1908         zror(ZORAN_PCI_SOFTRESET,ZORAN_PCI);
1909         udelay(10);
1910
1911         /* zoran chip specific details */
1912         ztv->card = tvcards+cardtype[card];     /* point to the selected card */
1913         ztv->norm = 0;                          /* PAL */
1914         ztv->tuner_freq = 0;
1915
1916         /* videocard details */
1917         ztv->swidth = 800;
1918         ztv->sheight = 600;
1919         ztv->depth = 16;
1920
1921         /* State details */
1922         ztv->fbuffer = 0;
1923         ztv->overinfo.kindof = FBUFFER_OVERLAY;
1924         ztv->overinfo.status = FBUFFER_FREE;
1925         ztv->overinfo.x = 0;
1926         ztv->overinfo.y = 0;
1927         ztv->overinfo.w = 768; /* 640 */
1928         ztv->overinfo.h = 576; /* 480 */
1929         ztv->overinfo.format = VIDEO_PALETTE_RGB565;
1930         ztv->overinfo.bpp = palette2fmt[ztv->overinfo.format].bpp;
1931         ztv->overinfo.bpl = ztv->overinfo.bpp*ztv->swidth;
1932         ztv->overinfo.busadr = 0;
1933         ztv->overinfo.memadr = 0;
1934         ztv->overinfo.overlay = 0;
1935         for (i=0; i<ZORAN_MAX_FBUFFERS; i++) {
1936                 ztv->grabinfo[i] = ztv->overinfo;
1937                 ztv->grabinfo[i].kindof = FBUFFER_GRAB;
1938         }
1939         init_waitqueue_head(&ztv->grabq);
1940
1941         /* VBI details */
1942         ztv->readinfo[0] = ztv->overinfo;
1943         ztv->readinfo[0].kindof = FBUFFER_VBI;
1944         ztv->readinfo[0].w = -864;
1945         ztv->readinfo[0].h = -38;
1946         ztv->readinfo[0].format = VIDEO_PALETTE_YUV422;
1947         ztv->readinfo[0].bpp = palette2fmt[ztv->readinfo[0].format].bpp;
1948         ztv->readinfo[0].bpl = 1024*ztv->readinfo[0].bpp;
1949         for (i=1; i<ZORAN_VBI_BUFFERS; i++)
1950                 ztv->readinfo[i] = ztv->readinfo[0];
1951         init_waitqueue_head(&ztv->vbiq);
1952
1953         /* maintenance data */
1954         ztv->have_decoder = 0;
1955         ztv->have_tuner = 0;
1956         ztv->tuner_type = 0;
1957         ztv->running = 0;
1958         ztv->users = 0;
1959         ztv->lock = RW_LOCK_UNLOCKED;
1960         ztv->workqueue = 0;
1961         ztv->fieldnr = 0;
1962         ztv->lastfieldnr = 0;
1963
1964         if (triton1)
1965                 zrand(~ZORAN_VDC_TRICOM, ZORAN_VDC);
1966
1967         /* external FL determines TOP frame */
1968         zror(ZORAN_VFEC_EXTFL, ZORAN_VFEC); 
1969
1970         /* set HSpol */
1971         if (ztv->card->hsync_pos)
1972                 zrwrite(ZORAN_VFEH_HSPOL, ZORAN_VFEH);
1973         /* set VSpol */
1974         if (ztv->card->vsync_pos)
1975                 zrwrite(ZORAN_VFEV_VSPOL, ZORAN_VFEV);
1976
1977         /* Set the proper General Purpuse register bits */
1978         /* implicit: no softreset, 0 waitstates */
1979         zrwrite(ZORAN_PCI_SOFTRESET|(ztv->card->gpdir<<0),ZORAN_PCI);
1980         /* implicit: 3 duration and recovery PCI clocks on guest 0-3 */
1981         zrwrite(ztv->card->gpval<<24,ZORAN_GUEST);
1982
1983         /* clear interrupt status */
1984         zrwrite(~0, ZORAN_ISR);
1985
1986         /*
1987          * i2c template
1988          */
1989         ztv->i2c = zoran_i2c_bus_template;
1990         sprintf(ztv->i2c.name,"zoran-%d",card);
1991         ztv->i2c.data = ztv;
1992
1993         /*
1994          * Now add the template and register the device unit
1995          */
1996         ztv->video_dev = zr36120_template;
1997         strcpy(ztv->video_dev.name, ztv->i2c.name);
1998         ztv->video_dev.priv = ztv;
1999         if (video_register_device(&ztv->video_dev, VFL_TYPE_GRABBER, video_nr) < 0)
2000                 return -1;
2001
2002         ztv->vbi_dev = vbi_template;
2003         strcpy(ztv->vbi_dev.name, ztv->i2c.name);
2004         ztv->vbi_dev.priv = ztv;
2005         if (video_register_device(&ztv->vbi_dev, VFL_TYPE_VBI, vbi_nr) < 0) {
2006                 video_unregister_device(&ztv->video_dev);
2007                 return -1;
2008         }
2009         i2c_register_bus(&ztv->i2c);
2010
2011         /* set interrupt mask - the PIN enable will be set later */
2012         zrwrite(ZORAN_ICR_GIRQ0|ZORAN_ICR_GIRQ1|ZORAN_ICR_CODE, ZORAN_ICR);
2013
2014         printk(KERN_INFO "%s: installed %s\n",ztv->i2c.name,ztv->card->name);
2015         return 0;
2016 }
2017
2018 static
2019 void release_zoran(int max)
2020 {
2021         struct zoran *ztv;
2022         int i;
2023
2024         for (i=0;i<max; i++) 
2025         {
2026                 ztv = &zorans[i];
2027
2028                 /* turn off all capturing, DMA and IRQs */
2029                 /* reset the zoran */
2030                 zrand(~ZORAN_PCI_SOFTRESET,ZORAN_PCI);
2031                 udelay(10);
2032                 zror(ZORAN_PCI_SOFTRESET,ZORAN_PCI);
2033                 udelay(10);
2034
2035                 /* first disable interrupts before unmapping the memory! */
2036                 zrwrite(0, ZORAN_ICR);
2037                 zrwrite(0xffffffffUL,ZORAN_ISR);
2038
2039                 /* free it */
2040                 free_irq(ztv->dev->irq,ztv);
2041  
2042                 /* unregister i2c_bus */
2043                 i2c_unregister_bus((&ztv->i2c));
2044
2045                 /* unmap and free memory */
2046                 if (ztv->zoran_mem)
2047                         iounmap(ztv->zoran_mem);
2048
2049                 video_unregister_device(&ztv->video_dev);
2050                 video_unregister_device(&ztv->vbi_dev);
2051         }
2052 }
2053
2054 void __exit zr36120_exit(void)
2055 {
2056         release_zoran(zoran_cards);
2057 }
2058
2059 int __init zr36120_init(void)
2060 {
2061         int     card;
2062  
2063         handle_chipset();
2064         zoran_cards = find_zoran();
2065         if (zoran_cards<0)
2066                 /* no cards found, no need for a driver */
2067                 return -EIO;
2068
2069         /* initialize Zorans */
2070         for (card=0; card<zoran_cards; card++) {
2071                 if (init_zoran(card)<0) {
2072                         /* only release the zorans we have registered */
2073                         release_zoran(card);
2074                         return -EIO;
2075                 } 
2076         }
2077         return 0;
2078 }
2079
2080 module_init(zr36120_init);
2081 module_exit(zr36120_exit);