V4L/DVB: ngene: Speed-up tuning
[linux-2.6.git] / drivers / media / dvb / ngene / ngene-core.c
1 /*
2  * ngene.c: nGene PCIe bridge driver
3  *
4  * Copyright (C) 2005-2007 Micronas
5  *
6  * Copyright (C) 2008-2009 Ralph Metzler <rjkm@metzlerbros.de>
7  *                         Modifications for new nGene firmware,
8  *                         support for EEPROM-copying,
9  *                         support for new dual DVB-S2 card prototype
10  *
11  *
12  * This program is free software; you can redistribute it and/or
13  * modify it under the terms of the GNU General Public License
14  * version 2 only, as published by the Free Software Foundation.
15  *
16  *
17  * This program is distributed in the hope that it will be useful,
18  * but WITHOUT ANY WARRANTY; without even the implied warranty of
19  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
20  * GNU General Public License for more details.
21  *
22  *
23  * You should have received a copy of the GNU General Public License
24  * along with this program; if not, write to the Free Software
25  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
26  * 02110-1301, USA
27  * Or, point your browser to http://www.gnu.org/copyleft/gpl.html
28  */
29
30 #include <linux/module.h>
31 #include <linux/init.h>
32 #include <linux/delay.h>
33 #include <linux/slab.h>
34 #include <linux/poll.h>
35 #include <asm/io.h>
36 #include <asm/div64.h>
37 #include <linux/pci.h>
38 #include <linux/pci_ids.h>
39 #include <linux/smp_lock.h>
40 #include <linux/timer.h>
41 #include <linux/version.h>
42 #include <linux/byteorder/generic.h>
43 #include <linux/firmware.h>
44
45 #include "ngene.h"
46
47 #include "stv6110x.h"
48 #include "stv090x.h"
49 #include "lnbh24.h"
50
51 #ifdef NGENE_COMMAND_API
52 #include "ngene-ioctls.h"
53 #endif
54
55 static int copy_eeprom;
56 module_param(copy_eeprom, int, 0444);
57 MODULE_PARM_DESC(copy_eeprom, "Copy eeprom.");
58
59 static int debug;
60 module_param(debug, int, 0444);
61 MODULE_PARM_DESC(debug, "Print debugging information.");
62
63 DVB_DEFINE_MOD_OPT_ADAPTER_NR(adapter_nr);
64
65 #define dprintk if (debug) printk
66
67 #define DEVICE_NAME "ngene"
68
69 #define ngwriteb(dat, adr)         writeb((dat), (char *)(dev->iomem + (adr)))
70 #define ngwritel(dat, adr)         writel((dat), (char *)(dev->iomem + (adr)))
71 #define ngwriteb(dat, adr)         writeb((dat), (char *)(dev->iomem + (adr)))
72 #define ngreadl(adr)               readl(dev->iomem + (adr))
73 #define ngreadb(adr)               readb(dev->iomem + (adr))
74 #define ngcpyto(adr, src, count)   memcpy_toio((char *) \
75                                    (dev->iomem + (adr)), (src), (count))
76 #define ngcpyfrom(dst, adr, count) memcpy_fromio((dst), (char *) \
77                                    (dev->iomem + (adr)), (count))
78
79 /****************************************************************************/
80 /* Functions with missing kernel exports ************************************/
81 /****************************************************************************/
82
83 /* yeah, let's throw out all exports which are not used in kernel ... */
84
85 void my_dvb_ringbuffer_flush(struct dvb_ringbuffer *rbuf)
86 {
87         rbuf->pread = rbuf->pwrite;
88         rbuf->error = 0;
89 }
90
91 /****************************************************************************/
92 /* nGene interrupt handler **************************************************/
93 /****************************************************************************/
94
95 static void event_tasklet(unsigned long data)
96 {
97         struct ngene *dev = (struct ngene *)data;
98
99         while (dev->EventQueueReadIndex != dev->EventQueueWriteIndex) {
100                 struct EVENT_BUFFER Event =
101                         dev->EventQueue[dev->EventQueueReadIndex];
102                 dev->EventQueueReadIndex =
103                         (dev->EventQueueReadIndex + 1) & (EVENT_QUEUE_SIZE - 1);
104
105                 if ((Event.UARTStatus & 0x01) && (dev->TxEventNotify))
106                         dev->TxEventNotify(dev, Event.TimeStamp);
107                 if ((Event.UARTStatus & 0x02) && (dev->RxEventNotify))
108                         dev->RxEventNotify(dev, Event.TimeStamp,
109                                            Event.RXCharacter);
110         }
111 }
112
113 static void demux_tasklet(unsigned long data)
114 {
115         struct ngene_channel *chan = (struct ngene_channel *)data;
116         struct SBufferHeader *Cur = chan->nextBuffer;
117
118         spin_lock_irq(&chan->state_lock);
119
120         while (Cur->ngeneBuffer.SR.Flags & 0x80) {
121                 if (chan->mode & NGENE_IO_TSOUT) {
122                         u32 Flags = chan->DataFormatFlags;
123                         if (Cur->ngeneBuffer.SR.Flags & 0x20)
124                                 Flags |= BEF_OVERFLOW;
125                         if (chan->pBufferExchange) {
126                                 if (!chan->pBufferExchange(chan,
127                                                            Cur->Buffer1,
128                                                            chan->Capture1Length,
129                                                            Cur->ngeneBuffer.SR.
130                                                            Clock, Flags)) {
131                                         /*
132                                            We didn't get data
133                                            Clear in service flag to make sure we
134                                            get called on next interrupt again.
135                                            leave fill/empty (0x80) flag alone
136                                            to avoid hardware running out of
137                                            buffers during startup, we hold only
138                                            in run state ( the source may be late
139                                            delivering data )
140                                         */
141
142                                         if (chan->HWState == HWSTATE_RUN) {
143                                                 Cur->ngeneBuffer.SR.Flags &=
144                                                         ~0x40;
145                                                 break;
146                                                 /* Stop proccessing stream */
147                                         }
148                                 } else {
149                                         /* We got a valid buffer,
150                                            so switch to run state */
151                                         chan->HWState = HWSTATE_RUN;
152                                 }
153                         } else {
154                                 printk(KERN_ERR DEVICE_NAME ": OOPS\n");
155                                 if (chan->HWState == HWSTATE_RUN) {
156                                         Cur->ngeneBuffer.SR.Flags &= ~0x40;
157                                         break;  /* Stop proccessing stream */
158                                 }
159                         }
160                         if (chan->AudioDTOUpdated) {
161                                 printk(KERN_INFO DEVICE_NAME
162                                        ": Update AudioDTO = %d\n",
163                                        chan->AudioDTOValue);
164                                 Cur->ngeneBuffer.SR.DTOUpdate =
165                                         chan->AudioDTOValue;
166                                 chan->AudioDTOUpdated = 0;
167                         }
168                 } else {
169                         if (chan->HWState == HWSTATE_RUN) {
170                                 u32 Flags = 0;
171                                 if (Cur->ngeneBuffer.SR.Flags & 0x01)
172                                         Flags |= BEF_EVEN_FIELD;
173                                 if (Cur->ngeneBuffer.SR.Flags & 0x20)
174                                         Flags |= BEF_OVERFLOW;
175                                 if (chan->pBufferExchange)
176                                         chan->pBufferExchange(chan,
177                                                               Cur->Buffer1,
178                                                               chan->
179                                                               Capture1Length,
180                                                               Cur->ngeneBuffer.
181                                                               SR.Clock, Flags);
182                                 if (chan->pBufferExchange2)
183                                         chan->pBufferExchange2(chan,
184                                                                Cur->Buffer2,
185                                                                chan->
186                                                                Capture2Length,
187                                                                Cur->ngeneBuffer.
188                                                                SR.Clock, Flags);
189                         } else if (chan->HWState != HWSTATE_STOP)
190                                 chan->HWState = HWSTATE_RUN;
191                 }
192                 Cur->ngeneBuffer.SR.Flags = 0x00;
193                 Cur = Cur->Next;
194         }
195         chan->nextBuffer = Cur;
196
197         spin_unlock_irq(&chan->state_lock);
198 }
199
200 static irqreturn_t irq_handler(int irq, void *dev_id)
201 {
202         struct ngene *dev = (struct ngene *)dev_id;
203         u32 icounts = 0;
204         irqreturn_t rc = IRQ_NONE;
205         u32 i = MAX_STREAM;
206         u8 *tmpCmdDoneByte;
207
208         if (dev->BootFirmware) {
209                 icounts = ngreadl(NGENE_INT_COUNTS);
210                 if (icounts != dev->icounts) {
211                         ngwritel(0, FORCE_NMI);
212                         dev->cmd_done = 1;
213                         wake_up(&dev->cmd_wq);
214                         dev->icounts = icounts;
215                         rc = IRQ_HANDLED;
216                 }
217                 return rc;
218         }
219
220         ngwritel(0, FORCE_NMI);
221
222         spin_lock(&dev->cmd_lock);
223         tmpCmdDoneByte = dev->CmdDoneByte;
224         if (tmpCmdDoneByte &&
225             (*tmpCmdDoneByte ||
226             (dev->ngenetohost[0] == 1 && dev->ngenetohost[1] != 0))) {
227                 dev->CmdDoneByte = NULL;
228                 dev->cmd_done = 1;
229                 wake_up(&dev->cmd_wq);
230                 rc = IRQ_HANDLED;
231         }
232         spin_unlock(&dev->cmd_lock);
233
234         if (dev->EventBuffer->EventStatus & 0x80) {
235                 u8 nextWriteIndex =
236                         (dev->EventQueueWriteIndex + 1) &
237                         (EVENT_QUEUE_SIZE - 1);
238                 if (nextWriteIndex != dev->EventQueueReadIndex) {
239                         dev->EventQueue[dev->EventQueueWriteIndex] =
240                                 *(dev->EventBuffer);
241                         dev->EventQueueWriteIndex = nextWriteIndex;
242                 } else {
243                         printk(KERN_ERR DEVICE_NAME ": event overflow\n");
244                         dev->EventQueueOverflowCount += 1;
245                         dev->EventQueueOverflowFlag = 1;
246                 }
247                 dev->EventBuffer->EventStatus &= ~0x80;
248                 tasklet_schedule(&dev->event_tasklet);
249                 rc = IRQ_HANDLED;
250         }
251
252         while (i > 0) {
253                 i--;
254                 spin_lock(&dev->channel[i].state_lock);
255                 /* if (dev->channel[i].State>=KSSTATE_RUN) { */
256                 if (dev->channel[i].nextBuffer) {
257                         if ((dev->channel[i].nextBuffer->
258                              ngeneBuffer.SR.Flags & 0xC0) == 0x80) {
259                                 dev->channel[i].nextBuffer->
260                                         ngeneBuffer.SR.Flags |= 0x40;
261                                 tasklet_schedule(
262                                         &dev->channel[i].demux_tasklet);
263                                 rc = IRQ_HANDLED;
264                         }
265                 }
266                 spin_unlock(&dev->channel[i].state_lock);
267         }
268
269         return rc;
270 }
271
272 /****************************************************************************/
273 /* nGene command interface **************************************************/
274 /****************************************************************************/
275
276 static int ngene_command_mutex(struct ngene *dev, struct ngene_command *com)
277 {
278         int ret;
279         u8 *tmpCmdDoneByte;
280
281         dev->cmd_done = 0;
282
283         if (com->cmd.hdr.Opcode == CMD_FWLOAD_PREPARE) {
284                 dev->BootFirmware = 1;
285                 dev->icounts = ngreadl(NGENE_INT_COUNTS);
286                 ngwritel(0, NGENE_COMMAND);
287                 ngwritel(0, NGENE_COMMAND_HI);
288                 ngwritel(0, NGENE_STATUS);
289                 ngwritel(0, NGENE_STATUS_HI);
290                 ngwritel(0, NGENE_EVENT);
291                 ngwritel(0, NGENE_EVENT_HI);
292         } else if (com->cmd.hdr.Opcode == CMD_FWLOAD_FINISH) {
293                 u64 fwio = dev->PAFWInterfaceBuffer;
294
295                 ngwritel(fwio & 0xffffffff, NGENE_COMMAND);
296                 ngwritel(fwio >> 32, NGENE_COMMAND_HI);
297                 ngwritel((fwio + 256) & 0xffffffff, NGENE_STATUS);
298                 ngwritel((fwio + 256) >> 32, NGENE_STATUS_HI);
299                 ngwritel((fwio + 512) & 0xffffffff, NGENE_EVENT);
300                 ngwritel((fwio + 512) >> 32, NGENE_EVENT_HI);
301         }
302
303         memcpy(dev->FWInterfaceBuffer, com->cmd.raw8, com->in_len + 2);
304
305         if (dev->BootFirmware)
306                 ngcpyto(HOST_TO_NGENE, com->cmd.raw8, com->in_len + 2);
307
308         spin_lock_irq(&dev->cmd_lock);
309         tmpCmdDoneByte = dev->ngenetohost + com->out_len;
310         if (!com->out_len)
311                 tmpCmdDoneByte++;
312         *tmpCmdDoneByte = 0;
313         dev->ngenetohost[0] = 0;
314         dev->ngenetohost[1] = 0;
315         dev->CmdDoneByte = tmpCmdDoneByte;
316         spin_unlock_irq(&dev->cmd_lock);
317
318         /* Notify 8051. */
319         ngwritel(1, FORCE_INT);
320
321         ret = wait_event_timeout(dev->cmd_wq, dev->cmd_done == 1, 2 * HZ);
322         if (!ret) {
323                 /*ngwritel(0, FORCE_NMI);*/
324
325                 printk(KERN_ERR DEVICE_NAME
326                        ": Command timeout cmd=%02x prev=%02x\n",
327                        com->cmd.hdr.Opcode, dev->prev_cmd);
328                 return -1;
329         }
330         if (com->cmd.hdr.Opcode == CMD_FWLOAD_FINISH)
331                 dev->BootFirmware = 0;
332
333         dev->prev_cmd = com->cmd.hdr.Opcode;
334
335         if (!com->out_len)
336                 return 0;
337
338         memcpy(com->cmd.raw8, dev->ngenetohost, com->out_len);
339
340         return 0;
341 }
342
343 static int ngene_command(struct ngene *dev, struct ngene_command *com)
344 {
345         int result;
346
347         down(&dev->cmd_mutex);
348         result = ngene_command_mutex(dev, com);
349         up(&dev->cmd_mutex);
350         return result;
351 }
352
353 int ngene_command_nop(struct ngene *dev)
354 {
355         struct ngene_command com;
356
357         com.cmd.hdr.Opcode = CMD_NOP;
358         com.cmd.hdr.Length = 0;
359         com.in_len = 0;
360         com.out_len = 0;
361
362         return ngene_command(dev, &com);
363 }
364
365 int ngene_command_i2c_read(struct ngene *dev, u8 adr,
366                            u8 *out, u8 outlen, u8 *in, u8 inlen, int flag)
367 {
368         struct ngene_command com;
369
370         com.cmd.hdr.Opcode = CMD_I2C_READ;
371         com.cmd.hdr.Length = outlen + 3;
372         com.cmd.I2CRead.Device = adr << 1;
373         memcpy(com.cmd.I2CRead.Data, out, outlen);
374         com.cmd.I2CRead.Data[outlen] = inlen;
375         com.cmd.I2CRead.Data[outlen + 1] = 0;
376         com.in_len = outlen + 3;
377         com.out_len = inlen + 1;
378
379         if (ngene_command(dev, &com) < 0)
380                 return -EIO;
381
382         if ((com.cmd.raw8[0] >> 1) != adr)
383                 return -EIO;
384
385         if (flag)
386                 memcpy(in, com.cmd.raw8, inlen + 1);
387         else
388                 memcpy(in, com.cmd.raw8 + 1, inlen);
389         return 0;
390 }
391
392 int ngene_command_i2c_write(struct ngene *dev, u8 adr, u8 *out, u8 outlen)
393 {
394         struct ngene_command com;
395
396
397         com.cmd.hdr.Opcode = CMD_I2C_WRITE;
398         com.cmd.hdr.Length = outlen + 1;
399         com.cmd.I2CRead.Device = adr << 1;
400         memcpy(com.cmd.I2CRead.Data, out, outlen);
401         com.in_len = outlen + 1;
402         com.out_len = 1;
403
404         if (ngene_command(dev, &com) < 0)
405                 return -EIO;
406
407         if (com.cmd.raw8[0] == 1)
408                 return -EIO;
409
410         return 0;
411 }
412
413 static int ngene_command_load_firmware(struct ngene *dev,
414                                        u8 *ngene_fw, u32 size)
415 {
416 #define FIRSTCHUNK (1024)
417         u32 cleft;
418         struct ngene_command com;
419
420         com.cmd.hdr.Opcode = CMD_FWLOAD_PREPARE;
421         com.cmd.hdr.Length = 0;
422         com.in_len = 0;
423         com.out_len = 0;
424
425         ngene_command(dev, &com);
426
427         cleft = (size + 3) & ~3;
428         if (cleft > FIRSTCHUNK) {
429                 ngcpyto(PROGRAM_SRAM + FIRSTCHUNK, ngene_fw + FIRSTCHUNK,
430                         cleft - FIRSTCHUNK);
431                 cleft = FIRSTCHUNK;
432         }
433         ngcpyto(DATA_FIFO_AREA, ngene_fw, cleft);
434
435         memset(&com, 0, sizeof(struct ngene_command));
436         com.cmd.hdr.Opcode = CMD_FWLOAD_FINISH;
437         com.cmd.hdr.Length = 4;
438         com.cmd.FWLoadFinish.Address = DATA_FIFO_AREA;
439         com.cmd.FWLoadFinish.Length = (unsigned short)cleft;
440         com.in_len = 4;
441         com.out_len = 0;
442
443         return ngene_command(dev, &com);
444 }
445
446 int ngene_command_imem_read(struct ngene *dev, u8 adr, u8 *data, int type)
447 {
448         struct ngene_command com;
449
450         com.cmd.hdr.Opcode = type ? CMD_SFR_READ : CMD_IRAM_READ;
451         com.cmd.hdr.Length = 1;
452         com.cmd.SfrIramRead.address = adr;
453         com.in_len = 1;
454         com.out_len = 2;
455
456         if (ngene_command(dev, &com) < 0)
457                 return -EIO;
458
459         *data = com.cmd.raw8[1];
460         return 0;
461 }
462
463 int ngene_command_imem_write(struct ngene *dev, u8 adr, u8 data, int type)
464 {
465         struct ngene_command com;
466
467         com.cmd.hdr.Opcode = type ? CMD_SFR_WRITE : CMD_IRAM_WRITE;
468         com.cmd.hdr.Length = 2;
469         com.cmd.SfrIramWrite.address = adr;
470         com.cmd.SfrIramWrite.data = data;
471         com.in_len = 2;
472         com.out_len = 1;
473
474         if (ngene_command(dev, &com) < 0)
475                 return -EIO;
476
477         return 0;
478 }
479
480 static int ngene_command_config_uart(struct ngene *dev, u8 config,
481                                      tx_cb_t *tx_cb, rx_cb_t *rx_cb)
482 {
483         struct ngene_command com;
484
485         com.cmd.hdr.Opcode = CMD_CONFIGURE_UART;
486         com.cmd.hdr.Length = sizeof(struct FW_CONFIGURE_UART) - 2;
487         com.cmd.ConfigureUart.UartControl = config;
488         com.in_len = sizeof(struct FW_CONFIGURE_UART);
489         com.out_len = 0;
490
491         if (ngene_command(dev, &com) < 0)
492                 return -EIO;
493
494         dev->TxEventNotify = tx_cb;
495         dev->RxEventNotify = rx_cb;
496
497         dprintk(KERN_DEBUG DEVICE_NAME ": Set UART config %02x.\n", config);
498
499         return 0;
500 }
501
502 static void tx_cb(struct ngene *dev, u32 ts)
503 {
504         dev->tx_busy = 0;
505         wake_up_interruptible(&dev->tx_wq);
506 }
507
508 static void rx_cb(struct ngene *dev, u32 ts, u8 c)
509 {
510         int rp = dev->uart_rp;
511         int nwp, wp = dev->uart_wp;
512
513         /* dprintk(KERN_DEBUG DEVICE_NAME ": %c\n", c); */
514         nwp = (wp + 1) % (UART_RBUF_LEN);
515         if (nwp == rp)
516                 return;
517         dev->uart_rbuf[wp] = c;
518         dev->uart_wp = nwp;
519         wake_up_interruptible(&dev->rx_wq);
520 }
521
522 static int ngene_command_config_buf(struct ngene *dev, u8 config)
523 {
524         struct ngene_command com;
525
526         com.cmd.hdr.Opcode = CMD_CONFIGURE_BUFFER;
527         com.cmd.hdr.Length = 1;
528         com.cmd.ConfigureBuffers.config = config;
529         com.in_len = 1;
530         com.out_len = 0;
531
532         if (ngene_command(dev, &com) < 0)
533                 return -EIO;
534         return 0;
535 }
536
537 static int ngene_command_config_free_buf(struct ngene *dev, u8 *config)
538 {
539         struct ngene_command com;
540
541         com.cmd.hdr.Opcode = CMD_CONFIGURE_FREE_BUFFER;
542         com.cmd.hdr.Length = 6;
543         memcpy(&com.cmd.ConfigureBuffers.config, config, 6);
544         com.in_len = 6;
545         com.out_len = 0;
546
547         if (ngene_command(dev, &com) < 0)
548                 return -EIO;
549
550         return 0;
551 }
552
553 static int ngene_command_gpio_set(struct ngene *dev, u8 select, u8 level)
554 {
555         struct ngene_command com;
556
557         com.cmd.hdr.Opcode = CMD_SET_GPIO_PIN;
558         com.cmd.hdr.Length = 1;
559         com.cmd.SetGpioPin.select = select | (level << 7);
560         com.in_len = 1;
561         com.out_len = 0;
562
563         return ngene_command(dev, &com);
564 }
565
566 /* The reset is only wired to GPIO4 on MicRacer Revision 1.10 !
567    Also better set bootdelay to 1 in nvram or less. */
568 static void ngene_reset_decypher(struct ngene *dev)
569 {
570         printk(KERN_INFO DEVICE_NAME ": Resetting Decypher.\n");
571         ngene_command_gpio_set(dev, 4, 0);
572         msleep(1);
573         ngene_command_gpio_set(dev, 4, 1);
574         msleep(2000);
575 }
576
577 /*
578  02000640 is sample on rising edge.
579  02000740 is sample on falling edge.
580  02000040 is ignore "valid" signal
581
582  0: FD_CTL1 Bit 7,6 must be 0,1
583     7   disable(fw controlled)
584     6   0-AUX,1-TS
585     5   0-par,1-ser
586     4   0-lsb/1-msb
587     3,2 reserved
588     1,0 0-no sync, 1-use ext. start, 2-use 0x47, 3-both
589  1: FD_CTL2 has 3-valid must be hi, 2-use valid, 1-edge
590  2: FD_STA is read-only. 0-sync
591  3: FD_INSYNC is number of 47s to trigger "in sync".
592  4: FD_OUTSYNC is number of 47s to trigger "out of sync".
593  5: FD_MAXBYTE1 is low-order of bytes per packet.
594  6: FD_MAXBYTE2 is high-order of bytes per packet.
595  7: Top byte is unused.
596 */
597
598 /****************************************************************************/
599
600 static u8 TSFeatureDecoderSetup[8 * 4] = {
601         0x42, 0x00, 0x00, 0x02, 0x02, 0xbc, 0x00, 0x00,
602         0x40, 0x06, 0x00, 0x02, 0x02, 0xbc, 0x00, 0x00, /* DRXH */
603         0x71, 0x07, 0x00, 0x02, 0x02, 0xbc, 0x00, 0x00, /* DRXHser */
604         0x72, 0x06, 0x00, 0x02, 0x02, 0xbc, 0x00, 0x00, /* S2ser */
605 };
606
607 /* Set NGENE I2S Config to 16 bit packed */
608 static u8 I2SConfiguration[] = {
609         0x00, 0x10, 0x00, 0x00,
610         0x80, 0x10, 0x00, 0x00,
611 };
612
613 static u8 SPDIFConfiguration[10] = {
614         0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00
615 };
616
617 /* Set NGENE I2S Config to transport stream compatible mode */
618
619 static u8 TS_I2SConfiguration[4] = { 0x3E, 0x1A, 0x00, 0x00 }; /*3e 18 00 00 ?*/
620
621 static u8 TS_I2SOutConfiguration[4] = { 0x80, 0x20, 0x00, 0x00 };
622
623 static u8 ITUDecoderSetup[4][16] = {
624         {0x1c, 0x13, 0x01, 0x68, 0x3d, 0x90, 0x14, 0x20,  /* SDTV */
625          0x00, 0x00, 0x01, 0xb0, 0x9c, 0x00, 0x00, 0x00},
626         {0x9c, 0x03, 0x23, 0xC0, 0x60, 0x0E, 0x13, 0x00,
627          0x00, 0x00, 0x00, 0x01, 0xB0, 0x00, 0x00, 0x00},
628         {0x9f, 0x00, 0x23, 0xC0, 0x60, 0x0F, 0x13, 0x00,  /* HDTV 1080i50 */
629          0x00, 0x00, 0x00, 0x01, 0xB0, 0x00, 0x00, 0x00},
630         {0x9c, 0x01, 0x23, 0xC0, 0x60, 0x0E, 0x13, 0x00,  /* HDTV 1080i60 */
631          0x00, 0x00, 0x00, 0x01, 0xB0, 0x00, 0x00, 0x00},
632 };
633
634 /*
635  * 50 48 60 gleich
636  * 27p50 9f 00 22 80 42 69 18 ...
637  * 27p60 93 00 22 80 82 69 1c ...
638  */
639
640 /* Maxbyte to 1144 (for raw data) */
641 static u8 ITUFeatureDecoderSetup[8] = {
642         0x00, 0x00, 0x00, 0x00, 0x00, 0x78, 0x04, 0x00
643 };
644
645 static void FillTSBuffer(void *Buffer, int Length, u32 Flags)
646 {
647         u32 *ptr = Buffer;
648
649         memset(Buffer, Length, 0xff);
650         while (Length > 0) {
651                 if (Flags & DF_SWAP32)
652                         *ptr = 0x471FFF10;
653                 else
654                         *ptr = 0x10FF1F47;
655                 ptr += (188 / 4);
656                 Length -= 188;
657         }
658 }
659
660
661 static void flush_buffers(struct ngene_channel *chan)
662 {
663         u8 val;
664
665         do {
666                 msleep(1);
667                 spin_lock_irq(&chan->state_lock);
668                 val = chan->nextBuffer->ngeneBuffer.SR.Flags & 0x80;
669                 spin_unlock_irq(&chan->state_lock);
670         } while (val);
671 }
672
673 static void clear_buffers(struct ngene_channel *chan)
674 {
675         struct SBufferHeader *Cur = chan->nextBuffer;
676
677         do {
678                 memset(&Cur->ngeneBuffer.SR, 0, sizeof(Cur->ngeneBuffer.SR));
679                 if (chan->mode & NGENE_IO_TSOUT)
680                         FillTSBuffer(Cur->Buffer1,
681                                      chan->Capture1Length,
682                                      chan->DataFormatFlags);
683                 Cur = Cur->Next;
684         } while (Cur != chan->nextBuffer);
685
686         if (chan->mode & NGENE_IO_TSOUT) {
687                 chan->nextBuffer->ngeneBuffer.SR.DTOUpdate =
688                         chan->AudioDTOValue;
689                 chan->AudioDTOUpdated = 0;
690
691                 Cur = chan->TSIdleBuffer.Head;
692
693                 do {
694                         memset(&Cur->ngeneBuffer.SR, 0,
695                                sizeof(Cur->ngeneBuffer.SR));
696                         FillTSBuffer(Cur->Buffer1,
697                                      chan->Capture1Length,
698                                      chan->DataFormatFlags);
699                         Cur = Cur->Next;
700                 } while (Cur != chan->TSIdleBuffer.Head);
701         }
702 }
703
704 int ngene_command_stream_control(struct ngene *dev, u8 stream, u8 control,
705                                  u8 mode, u8 flags)
706 {
707         struct ngene_channel *chan = &dev->channel[stream];
708         struct ngene_command com;
709         u16 BsUVI = ((stream & 1) ? 0x9400 : 0x9300);
710         u16 BsSDI = ((stream & 1) ? 0x9600 : 0x9500);
711         u16 BsSPI = ((stream & 1) ? 0x9800 : 0x9700);
712         u16 BsSDO = 0x9B00;
713
714         /* down(&dev->stream_mutex); */
715         while (down_trylock(&dev->stream_mutex)) {
716                 printk(KERN_INFO DEVICE_NAME ": SC locked\n");
717                 msleep(1);
718         }
719         memset(&com, 0, sizeof(com));
720         com.cmd.hdr.Opcode = CMD_CONTROL;
721         com.cmd.hdr.Length = sizeof(struct FW_STREAM_CONTROL) - 2;
722         com.cmd.StreamControl.Stream = stream | (control ? 8 : 0);
723         if (chan->mode & NGENE_IO_TSOUT)
724                 com.cmd.StreamControl.Stream |= 0x07;
725         com.cmd.StreamControl.Control = control |
726                 (flags & SFLAG_ORDER_LUMA_CHROMA);
727         com.cmd.StreamControl.Mode = mode;
728         com.in_len = sizeof(struct FW_STREAM_CONTROL);
729         com.out_len = 0;
730
731         printk(KERN_INFO DEVICE_NAME ": Stream=%02x, Control=%02x, Mode=%02x\n",
732                com.cmd.StreamControl.Stream, com.cmd.StreamControl.Control,
733                com.cmd.StreamControl.Mode);
734         chan->Mode = mode;
735
736         if (!(control & 0x80)) {
737                 spin_lock_irq(&chan->state_lock);
738                 if (chan->State == KSSTATE_RUN) {
739                         chan->State = KSSTATE_ACQUIRE;
740                         chan->HWState = HWSTATE_STOP;
741                         spin_unlock_irq(&chan->state_lock);
742                         if (ngene_command(dev, &com) < 0) {
743                                 up(&dev->stream_mutex);
744                                 return -1;
745                         }
746                         /* clear_buffers(chan); */
747                         flush_buffers(chan);
748                         up(&dev->stream_mutex);
749                         return 0;
750                 }
751                 spin_unlock_irq(&chan->state_lock);
752                 up(&dev->stream_mutex);
753                 return 0;
754         }
755
756         if (mode & SMODE_AUDIO_CAPTURE) {
757                 com.cmd.StreamControl.CaptureBlockCount =
758                         chan->Capture1Length / AUDIO_BLOCK_SIZE;
759                 com.cmd.StreamControl.Buffer_Address = chan->RingBuffer.PAHead;
760         } else if (mode & SMODE_TRANSPORT_STREAM) {
761                 com.cmd.StreamControl.CaptureBlockCount =
762                         chan->Capture1Length / TS_BLOCK_SIZE;
763                 com.cmd.StreamControl.MaxLinesPerField =
764                         chan->Capture1Length / TS_BLOCK_SIZE;
765                 com.cmd.StreamControl.Buffer_Address =
766                         chan->TSRingBuffer.PAHead;
767                 if (chan->mode & NGENE_IO_TSOUT) {
768                         com.cmd.StreamControl.BytesPerVBILine =
769                                 chan->Capture1Length / TS_BLOCK_SIZE;
770                         com.cmd.StreamControl.Stream |= 0x07;
771                 }
772         } else {
773                 com.cmd.StreamControl.BytesPerVideoLine = chan->nBytesPerLine;
774                 com.cmd.StreamControl.MaxLinesPerField = chan->nLines;
775                 com.cmd.StreamControl.MinLinesPerField = 100;
776                 com.cmd.StreamControl.Buffer_Address = chan->RingBuffer.PAHead;
777
778                 if (mode & SMODE_VBI_CAPTURE) {
779                         com.cmd.StreamControl.MaxVBILinesPerField =
780                                 chan->nVBILines;
781                         com.cmd.StreamControl.MinVBILinesPerField = 0;
782                         com.cmd.StreamControl.BytesPerVBILine =
783                                 chan->nBytesPerVBILine;
784                 }
785                 if (flags & SFLAG_COLORBAR)
786                         com.cmd.StreamControl.Stream |= 0x04;
787         }
788
789         spin_lock_irq(&chan->state_lock);
790         if (mode & SMODE_AUDIO_CAPTURE) {
791                 chan->nextBuffer = chan->RingBuffer.Head;
792                 if (mode & SMODE_AUDIO_SPDIF) {
793                         com.cmd.StreamControl.SetupDataLen =
794                                 sizeof(SPDIFConfiguration);
795                         com.cmd.StreamControl.SetupDataAddr = BsSPI;
796                         memcpy(com.cmd.StreamControl.SetupData,
797                                SPDIFConfiguration, sizeof(SPDIFConfiguration));
798                 } else {
799                         com.cmd.StreamControl.SetupDataLen = 4;
800                         com.cmd.StreamControl.SetupDataAddr = BsSDI;
801                         memcpy(com.cmd.StreamControl.SetupData,
802                                I2SConfiguration +
803                                4 * dev->card_info->i2s[stream], 4);
804                 }
805         } else if (mode & SMODE_TRANSPORT_STREAM) {
806                 chan->nextBuffer = chan->TSRingBuffer.Head;
807                 if (stream >= STREAM_AUDIOIN1) {
808                         if (chan->mode & NGENE_IO_TSOUT) {
809                                 com.cmd.StreamControl.SetupDataLen =
810                                         sizeof(TS_I2SOutConfiguration);
811                                 com.cmd.StreamControl.SetupDataAddr = BsSDO;
812                                 memcpy(com.cmd.StreamControl.SetupData,
813                                        TS_I2SOutConfiguration,
814                                        sizeof(TS_I2SOutConfiguration));
815                         } else {
816                                 com.cmd.StreamControl.SetupDataLen =
817                                         sizeof(TS_I2SConfiguration);
818                                 com.cmd.StreamControl.SetupDataAddr = BsSDI;
819                                 memcpy(com.cmd.StreamControl.SetupData,
820                                        TS_I2SConfiguration,
821                                        sizeof(TS_I2SConfiguration));
822                         }
823                 } else {
824                         com.cmd.StreamControl.SetupDataLen = 8;
825                         com.cmd.StreamControl.SetupDataAddr = BsUVI + 0x10;
826                         memcpy(com.cmd.StreamControl.SetupData,
827                                TSFeatureDecoderSetup +
828                                8 * dev->card_info->tsf[stream], 8);
829                 }
830         } else {
831                 chan->nextBuffer = chan->RingBuffer.Head;
832                 com.cmd.StreamControl.SetupDataLen =
833                         16 + sizeof(ITUFeatureDecoderSetup);
834                 com.cmd.StreamControl.SetupDataAddr = BsUVI;
835                 memcpy(com.cmd.StreamControl.SetupData,
836                        ITUDecoderSetup[chan->itumode], 16);
837                 memcpy(com.cmd.StreamControl.SetupData + 16,
838                        ITUFeatureDecoderSetup, sizeof(ITUFeatureDecoderSetup));
839         }
840         clear_buffers(chan);
841         chan->State = KSSTATE_RUN;
842         if (mode & SMODE_TRANSPORT_STREAM)
843                 chan->HWState = HWSTATE_RUN;
844         else
845                 chan->HWState = HWSTATE_STARTUP;
846         spin_unlock_irq(&chan->state_lock);
847
848         if (ngene_command(dev, &com) < 0) {
849                 up(&dev->stream_mutex);
850                 return -1;
851         }
852         up(&dev->stream_mutex);
853         return 0;
854 }
855
856 int ngene_stream_control(struct ngene *dev, u8 stream, u8 control, u8 mode,
857                          u16 lines, u16 bpl, u16 vblines, u16 vbibpl)
858 {
859         if (!(mode & SMODE_TRANSPORT_STREAM))
860                 return -EINVAL;
861
862         if (lines * bpl > MAX_VIDEO_BUFFER_SIZE)
863                 return -EINVAL;
864
865         if ((mode & SMODE_TRANSPORT_STREAM) && (((bpl * lines) & 0xff) != 0))
866                 return -EINVAL;
867
868         if ((mode & SMODE_VIDEO_CAPTURE) && (bpl & 7) != 0)
869                 return -EINVAL;
870
871         return ngene_command_stream_control(dev, stream, control, mode, 0);
872 }
873
874 /****************************************************************************/
875 /* I2C **********************************************************************/
876 /****************************************************************************/
877
878 static void ngene_i2c_set_bus(struct ngene *dev, int bus)
879 {
880         if (!(dev->card_info->i2c_access & 2))
881                 return;
882         if (dev->i2c_current_bus == bus)
883                 return;
884
885         switch (bus) {
886         case 0:
887                 ngene_command_gpio_set(dev, 3, 0);
888                 ngene_command_gpio_set(dev, 2, 1);
889                 break;
890
891         case 1:
892                 ngene_command_gpio_set(dev, 2, 0);
893                 ngene_command_gpio_set(dev, 3, 1);
894                 break;
895         }
896         dev->i2c_current_bus = bus;
897 }
898
899 static int ngene_i2c_master_xfer(struct i2c_adapter *adapter,
900                                  struct i2c_msg msg[], int num)
901 {
902         struct ngene_channel *chan =
903                 (struct ngene_channel *)i2c_get_adapdata(adapter);
904         struct ngene *dev = chan->dev;
905
906         down(&dev->i2c_switch_mutex);
907         ngene_i2c_set_bus(dev, chan->number);
908
909         if (num == 2 && msg[1].flags & I2C_M_RD && !(msg[0].flags & I2C_M_RD))
910                 if (!ngene_command_i2c_read(dev, msg[0].addr,
911                                             msg[0].buf, msg[0].len,
912                                             msg[1].buf, msg[1].len, 0))
913                         goto done;
914
915         if (num == 1 && !(msg[0].flags & I2C_M_RD))
916                 if (!ngene_command_i2c_write(dev, msg[0].addr,
917                                              msg[0].buf, msg[0].len))
918                         goto done;
919         if (num == 1 && (msg[0].flags & I2C_M_RD))
920                 if (!ngene_command_i2c_read(dev, msg[0].addr, 0, 0,
921                                             msg[0].buf, msg[0].len, 0))
922                         goto done;
923
924         up(&dev->i2c_switch_mutex);
925         return -EIO;
926
927 done:
928         up(&dev->i2c_switch_mutex);
929         return num;
930 }
931
932
933
934 static u32 ngene_i2c_functionality(struct i2c_adapter *adap)
935 {
936         return I2C_FUNC_SMBUS_EMUL;
937 }
938
939 struct i2c_algorithm ngene_i2c_algo = {
940         .master_xfer = ngene_i2c_master_xfer,
941         .functionality = ngene_i2c_functionality,
942 };
943
944 static int ngene_i2c_init(struct ngene *dev, int dev_nr)
945 {
946         struct i2c_adapter *adap = &(dev->channel[dev_nr].i2c_adapter);
947
948         i2c_set_adapdata(adap, &(dev->channel[dev_nr]));
949 #ifdef I2C_ADAP_CLASS_TV_DIGITAL
950         adap->class = I2C_ADAP_CLASS_TV_DIGITAL | I2C_CLASS_TV_ANALOG;
951 #else
952         adap->class = I2C_CLASS_TV_ANALOG;
953 #endif
954
955         strcpy(adap->name, "nGene");
956
957         adap->id = I2C_HW_SAA7146;
958         adap->algo = &ngene_i2c_algo;
959         adap->algo_data = (void *)&(dev->channel[dev_nr]);
960
961         mutex_init(&adap->bus_lock);
962         return i2c_add_adapter(adap);
963 }
964
965 int i2c_write(struct i2c_adapter *adapter, u8 adr, u8 data)
966 {
967         u8 m[1] = {data};
968         struct i2c_msg msg = {.addr = adr, .flags = 0, .buf = m, .len = 1};
969
970         if (i2c_transfer(adapter, &msg, 1) != 1) {
971                 printk(KERN_ERR DEVICE_NAME
972                        ": Failed to write to I2C adr %02x!\n", adr);
973                 return -1;
974         }
975         return 0;
976 }
977
978
979 static int i2c_write_read(struct i2c_adapter *adapter,
980                           u8 adr, u8 *w, u8 wlen, u8 *r, u8 rlen)
981 {
982         struct i2c_msg msgs[2] = {{.addr = adr, .flags = 0,
983                                    .buf = w, .len = wlen},
984                                   {.addr = adr, .flags = I2C_M_RD,
985                                    .buf = r, .len = rlen} };
986
987         if (i2c_transfer(adapter, msgs, 2) != 2) {
988                 printk(KERN_ERR DEVICE_NAME ": error in i2c_write_read\n");
989                 return -1;
990         }
991         return 0;
992 }
993
994 static int test_dec_i2c(struct i2c_adapter *adapter, int reg)
995 {
996         u8 data[256] = { reg, 0x00, 0x93, 0x78, 0x43, 0x45 };
997         u8 data2[256];
998         int i;
999
1000         memset(data2, 0, 256);
1001         i2c_write_read(adapter, 0x66, data, 2, data2, 4);
1002         for (i = 0; i < 4; i++)
1003                 printk("%02x ", data2[i]);
1004         printk("\n");
1005
1006         return 0;
1007 }
1008
1009
1010 /****************************************************************************/
1011 /* EEPROM TAGS **************************************************************/
1012 /****************************************************************************/
1013
1014 #define MICNG_EE_START      0x0100
1015 #define MICNG_EE_END        0x0FF0
1016
1017 #define MICNG_EETAG_END0    0x0000
1018 #define MICNG_EETAG_END1    0xFFFF
1019
1020 /* 0x0001 - 0x000F reserved for housekeeping */
1021 /* 0xFFFF - 0xFFFE reserved for housekeeping */
1022
1023 /* Micronas assigned tags
1024    EEProm tags for hardware support */
1025
1026 #define MICNG_EETAG_DRXD1_OSCDEVIATION  0x1000  /* 2 Bytes data */
1027 #define MICNG_EETAG_DRXD2_OSCDEVIATION  0x1001  /* 2 Bytes data */
1028
1029 #define MICNG_EETAG_MT2060_1_1STIF      0x1100  /* 2 Bytes data */
1030 #define MICNG_EETAG_MT2060_2_1STIF      0x1101  /* 2 Bytes data */
1031
1032 /* Tag range for OEMs */
1033
1034 #define MICNG_EETAG_OEM_FIRST  0xC000
1035 #define MICNG_EETAG_OEM_LAST   0xFFEF
1036
1037 static int i2c_write_eeprom(struct i2c_adapter *adapter,
1038                             u8 adr, u16 reg, u8 data)
1039 {
1040         u8 m[3] = {(reg >> 8), (reg & 0xff), data};
1041         struct i2c_msg msg = {.addr = adr, .flags = 0, .buf = m,
1042                               .len = sizeof(m)};
1043
1044         if (i2c_transfer(adapter, &msg, 1) != 1) {
1045                 dprintk(KERN_DEBUG DEVICE_NAME ": Error writing EEPROM!\n");
1046                 return -EIO;
1047         }
1048         return 0;
1049 }
1050
1051 static int i2c_read_eeprom(struct i2c_adapter *adapter,
1052                            u8 adr, u16 reg, u8 *data, int len)
1053 {
1054         u8 msg[2] = {(reg >> 8), (reg & 0xff)};
1055         struct i2c_msg msgs[2] = {{.addr = adr, .flags = 0,
1056                                    .buf = msg, .len = 2 },
1057                                   {.addr = adr, .flags = I2C_M_RD,
1058                                    .buf = data, .len = len} };
1059
1060         if (i2c_transfer(adapter, msgs, 2) != 2) {
1061                 dprintk(KERN_DEBUG DEVICE_NAME ": Error reading EEPROM\n");
1062                 return -EIO;
1063         }
1064         return 0;
1065 }
1066
1067
1068 static int i2c_dump_eeprom(struct i2c_adapter *adapter, u8 adr)
1069 {
1070         u8 buf[64];
1071         int i;
1072
1073         if (i2c_read_eeprom(adapter, adr, 0x0000, buf, sizeof(buf))) {
1074                 printk(KERN_ERR DEVICE_NAME ": No EEPROM?\n");
1075                 return -1;
1076         }
1077         for (i = 0; i < sizeof(buf); i++) {
1078                 if (!(i & 15))
1079                         printk("\n");
1080                 printk("%02x ", buf[i]);
1081         }
1082         printk("\n");
1083
1084         return 0;
1085 }
1086
1087 static int i2c_copy_eeprom(struct i2c_adapter *adapter, u8 adr, u8 adr2)
1088 {
1089         u8 buf[64];
1090         int i;
1091
1092         if (i2c_read_eeprom(adapter, adr, 0x0000, buf, sizeof(buf))) {
1093                 printk(KERN_ERR DEVICE_NAME ": No EEPROM?\n");
1094                 return -1;
1095         }
1096         buf[36] = 0xc3;
1097         buf[39] = 0xab;
1098         for (i = 0; i < sizeof(buf); i++) {
1099                 i2c_write_eeprom(adapter, adr2, i, buf[i]);
1100                 msleep(10);
1101         }
1102         return 0;
1103 }
1104
1105
1106 /****************************************************************************/
1107 /* COMMAND API interface ****************************************************/
1108 /****************************************************************************/
1109
1110 #ifdef NGENE_COMMAND_API
1111
1112 static int command_do_ioctl(struct inode *inode, struct file *file,
1113                             unsigned int cmd, void *parg)
1114 {
1115         struct dvb_device *dvbdev = file->private_data;
1116         struct ngene_channel *chan = dvbdev->priv;
1117         struct ngene *dev = chan->dev;
1118         int err = 0;
1119
1120         switch (cmd) {
1121         case IOCTL_MIC_NO_OP:
1122                 err = ngene_command_nop(dev);
1123                 break;
1124
1125         case IOCTL_MIC_DOWNLOAD_FIRMWARE:
1126                 break;
1127
1128         case IOCTL_MIC_I2C_READ:
1129         {
1130                 MIC_I2C_READ *msg = parg;
1131
1132                 err = ngene_command_i2c_read(dev, msg->I2CAddress >> 1,
1133                                              msg->OutData, msg->OutLength,
1134                                              msg->OutData, msg->InLength, 1);
1135                 break;
1136         }
1137
1138         case IOCTL_MIC_I2C_WRITE:
1139         {
1140                 MIC_I2C_WRITE *msg = parg;
1141
1142                 err = ngene_command_i2c_write(dev, msg->I2CAddress >> 1,
1143                                               msg->Data, msg->Length);
1144                 break;
1145         }
1146
1147         case IOCTL_MIC_TEST_GETMEM:
1148         {
1149                 MIC_MEM *m = parg;
1150
1151                 if (m->Length > 64 * 1024 || m->Start + m->Length > 64 * 1024)
1152                         return -EINVAL;
1153
1154                 /* WARNING, only use this on x86,
1155                    other archs may not swallow this  */
1156                 err = copy_to_user(m->Data, dev->iomem + m->Start, m->Length);
1157                 break;
1158         }
1159
1160         case IOCTL_MIC_TEST_SETMEM:
1161         {
1162                 MIC_MEM *m = parg;
1163
1164                 if (m->Length > 64 * 1024 || m->Start + m->Length > 64 * 1024)
1165                         return -EINVAL;
1166
1167                 err = copy_from_user(dev->iomem + m->Start, m->Data, m->Length);
1168                 break;
1169         }
1170
1171         case IOCTL_MIC_SFR_READ:
1172         {
1173                 MIC_IMEM *m = parg;
1174
1175                 err = ngene_command_imem_read(dev, m->Address, &m->Data, 1);
1176                 break;
1177         }
1178
1179         case IOCTL_MIC_SFR_WRITE:
1180         {
1181                 MIC_IMEM *m = parg;
1182
1183                 err = ngene_command_imem_write(dev, m->Address, m->Data, 1);
1184                 break;
1185         }
1186
1187         case IOCTL_MIC_IRAM_READ:
1188         {
1189                 MIC_IMEM *m = parg;
1190
1191                 err = ngene_command_imem_read(dev, m->Address, &m->Data, 0);
1192                 break;
1193         }
1194
1195         case IOCTL_MIC_IRAM_WRITE:
1196         {
1197                 MIC_IMEM *m = parg;
1198
1199                 err = ngene_command_imem_write(dev, m->Address, m->Data, 0);
1200                 break;
1201         }
1202
1203         case IOCTL_MIC_STREAM_CONTROL:
1204         {
1205                 MIC_STREAM_CONTROL *m = parg;
1206
1207                 err = ngene_stream_control(dev, m->Stream, m->Control, m->Mode,
1208                                            m->nLines, m->nBytesPerLine,
1209                                            m->nVBILines, m->nBytesPerVBILine);
1210                 break;
1211         }
1212
1213         default:
1214                 err = -EINVAL;
1215                 break;
1216         }
1217         return err;
1218 }
1219
1220 static int command_ioctl(struct inode *inode, struct file *file,
1221                          unsigned int cmd, unsigned long arg)
1222 {
1223         void *parg = (void *)arg, *pbuf = NULL;
1224         char  buf[64];
1225         int   res = -EFAULT;
1226
1227         if (_IOC_DIR(cmd) & _IOC_WRITE) {
1228                 parg = buf;
1229                 if (_IOC_SIZE(cmd) > sizeof(buf)) {
1230                         pbuf = kmalloc(_IOC_SIZE(cmd), GFP_KERNEL);
1231                         if (!pbuf)
1232                                 return -ENOMEM;
1233                         parg = pbuf;
1234                 }
1235                 if (copy_from_user(parg, (void __user *)arg, _IOC_SIZE(cmd)))
1236                         goto error;
1237         }
1238         res = command_do_ioctl(inode, file, cmd, parg);
1239         if (res < 0)
1240                 goto error;
1241         if (_IOC_DIR(cmd) & _IOC_READ)
1242                 if (copy_to_user((void __user *)arg, parg, _IOC_SIZE(cmd)))
1243                         res = -EFAULT;
1244 error:
1245         kfree(pbuf);
1246         return res;
1247 }
1248
1249 struct page *ngene_nopage(struct vm_area_struct *vma,
1250                           unsigned long address, int *type)
1251 {
1252         return 0;
1253 }
1254
1255 static int ngene_mmap(struct file *file, struct vm_area_struct *vma)
1256 {
1257         struct dvb_device *dvbdev = file->private_data;
1258         struct ngene_channel *chan = dvbdev->priv;
1259         struct ngene *dev = chan->dev;
1260
1261         unsigned long size = vma->vm_end - vma->vm_start;
1262         unsigned long off = vma->vm_pgoff << PAGE_SHIFT;
1263         unsigned long padr = pci_resource_start(dev->pci_dev, 0) + off;
1264         unsigned long psize = pci_resource_len(dev->pci_dev, 0) - off;
1265
1266         if (size > psize)
1267                 return -EINVAL;
1268
1269         if (io_remap_pfn_range(vma, vma->vm_start, padr >> PAGE_SHIFT, size,
1270                                vma->vm_page_prot))
1271                 return -EAGAIN;
1272         return 0;
1273 }
1274
1275 static int write_uart(struct ngene *dev, u8 *data, int len)
1276 {
1277         struct ngene_command com;
1278
1279         com.cmd.hdr.Opcode = CMD_WRITE_UART;
1280         com.cmd.hdr.Length = len;
1281         memcpy(com.cmd.WriteUart.Data, data, len);
1282         com.cmd.WriteUart.Data[len] = 0;
1283         com.cmd.WriteUart.Data[len + 1] = 0;
1284         com.in_len = len;
1285         com.out_len = 0;
1286
1287         if (ngene_command(dev, &com) < 0)
1288                 return -EIO;
1289
1290         return 0;
1291 }
1292
1293 static int send_cli(struct ngene *dev, char *cmd)
1294 {
1295         /* printk(KERN_INFO DEVICE_NAME ": %s", cmd); */
1296         return write_uart(dev, cmd, strlen(cmd));
1297 }
1298
1299 static int send_cli_val(struct ngene *dev, char *cmd, u32 val)
1300 {
1301         char s[32];
1302
1303         snprintf(s, 32, "%s %d\n", cmd, val);
1304         /* printk(KERN_INFO DEVICE_NAME ": %s", s); */
1305         return write_uart(dev, s, strlen(s));
1306 }
1307
1308 static int ngene_command_write_uart_user(struct ngene *dev,
1309                                          const u8 *data, int len)
1310 {
1311         struct ngene_command com;
1312
1313         dev->tx_busy = 1;
1314         com.cmd.hdr.Opcode = CMD_WRITE_UART;
1315         com.cmd.hdr.Length = len;
1316
1317         if (copy_from_user(com.cmd.WriteUart.Data, data, len))
1318                 return -EFAULT;
1319         com.in_len = len;
1320         com.out_len = 0;
1321
1322         if (ngene_command(dev, &com) < 0)
1323                 return -EIO;
1324
1325         return 0;
1326 }
1327
1328 static ssize_t uart_write(struct file *file, const char *buf,
1329                           size_t count, loff_t *ppos)
1330 {
1331         struct dvb_device *dvbdev = file->private_data;
1332         struct ngene_channel *chan = dvbdev->priv;
1333         struct ngene *dev = chan->dev;
1334         int len, ret = 0;
1335         size_t left = count;
1336
1337         while (left) {
1338                 len = left;
1339                 if (len > 250)
1340                         len = 250;
1341                 ret = wait_event_interruptible(dev->tx_wq, dev->tx_busy == 0);
1342                 if (ret < 0)
1343                         return ret;
1344                 ngene_command_write_uart_user(dev, buf, len);
1345                 left -= len;
1346                 buf += len;
1347         }
1348         return count;
1349 }
1350
1351 static ssize_t ts_write(struct file *file, const char *buf,
1352                         size_t count, loff_t *ppos)
1353 {
1354         struct dvb_device *dvbdev = file->private_data;
1355         struct ngene_channel *chan = dvbdev->priv;
1356         struct ngene *dev = chan->dev;
1357
1358         if (wait_event_interruptible(dev->tsout_rbuf.queue,
1359                                      dvb_ringbuffer_free
1360                                      (&dev->tsout_rbuf) >= count) < 0)
1361                 return 0;
1362
1363         dvb_ringbuffer_write(&dev->tsout_rbuf, buf, count);
1364
1365         return count;
1366 }
1367
1368 static ssize_t uart_read(struct file *file, char *buf,
1369                          size_t count, loff_t *ppos)
1370 {
1371         struct dvb_device *dvbdev = file->private_data;
1372         struct ngene_channel *chan = dvbdev->priv;
1373         struct ngene *dev = chan->dev;
1374         int left;
1375         int wp, rp, avail, len;
1376
1377         if (!dev->uart_rbuf)
1378                 return -EINVAL;
1379         if (count > 128)
1380                 count = 128;
1381         left = count;
1382         while (left) {
1383                 if (wait_event_interruptible(dev->rx_wq,
1384                                              dev->uart_wp != dev->uart_rp) < 0)
1385                         return -EAGAIN;
1386                 wp = dev->uart_wp;
1387                 rp = dev->uart_rp;
1388                 avail = (wp - rp);
1389
1390                 if (avail < 0)
1391                         avail += UART_RBUF_LEN;
1392                 if (avail > left)
1393                         avail = left;
1394                 if (wp < rp) {
1395                         len = UART_RBUF_LEN - rp;
1396                         if (len > avail)
1397                                 len = avail;
1398                         if (copy_to_user(buf, dev->uart_rbuf + rp, len))
1399                                 return -EFAULT;
1400                         if (len < avail)
1401                                 if (copy_to_user(buf + len, dev->uart_rbuf,
1402                                                  avail - len))
1403                                         return -EFAULT;
1404                 } else {
1405                         if (copy_to_user(buf, dev->uart_rbuf + rp, avail))
1406                                 return -EFAULT;
1407                 }
1408                 dev->uart_rp = (rp + avail) % UART_RBUF_LEN;
1409                 left -= avail;
1410                 buf += avail;
1411         }
1412         return count;
1413 }
1414
1415 static const struct file_operations command_fops = {
1416         .owner   = THIS_MODULE,
1417         .read    = uart_read,
1418         .write   = ts_write,
1419         .ioctl   = command_ioctl,
1420         .open    = dvb_generic_open,
1421         .release = dvb_generic_release,
1422         .poll    = 0,
1423         .mmap    = ngene_mmap,
1424 };
1425
1426 static struct dvb_device dvbdev_command = {
1427         .priv    = 0,
1428         .readers = -1,
1429         .writers = -1,
1430         .users   = -1,
1431         .fops    = &command_fops,
1432 };
1433
1434 #endif
1435
1436 /****************************************************************************/
1437 /* DVB functions and API interface ******************************************/
1438 /****************************************************************************/
1439
1440 static void swap_buffer(u32 *p, u32 len)
1441 {
1442         while (len) {
1443                 *p = swab32(*p);
1444                 p++;
1445                 len -= 4;
1446         }
1447 }
1448
1449
1450 static void *tsin_exchange(void *priv, void *buf, u32 len, u32 clock, u32 flags)
1451 {
1452         struct ngene_channel *chan = priv;
1453
1454
1455         dvb_dmx_swfilter(&chan->demux, buf, len);
1456         return 0;
1457 }
1458
1459 u8 fill_ts[188] = { 0x47, 0x1f, 0xff, 0x10 };
1460
1461 static void *tsout_exchange(void *priv, void *buf, u32 len,
1462                             u32 clock, u32 flags)
1463 {
1464         struct ngene_channel *chan = priv;
1465         struct ngene *dev = chan->dev;
1466         u32 alen;
1467
1468         alen = dvb_ringbuffer_avail(&dev->tsout_rbuf);
1469         alen -= alen % 188;
1470
1471         if (alen < len)
1472                 FillTSBuffer(buf + alen, len - alen, flags);
1473         else
1474                 alen = len;
1475         dvb_ringbuffer_read(&dev->tsout_rbuf, buf, alen);
1476         if (flags & DF_SWAP32)
1477                 swap_buffer((u32 *)buf, alen);
1478         wake_up_interruptible(&dev->tsout_rbuf.queue);
1479         return buf;
1480 }
1481
1482
1483 static void set_transfer(struct ngene_channel *chan, int state)
1484 {
1485         u8 control = 0, mode = 0, flags = 0;
1486         struct ngene *dev = chan->dev;
1487         int ret;
1488
1489         /*
1490         if (chan->running)
1491                 return;
1492         */
1493
1494         /*
1495         printk(KERN_INFO DEVICE_NAME ": st %d\n", state);
1496         msleep(100);
1497         */
1498
1499         if (state) {
1500                 if (chan->running) {
1501                         printk(KERN_INFO DEVICE_NAME ": already running\n");
1502                         return;
1503                 }
1504         } else {
1505                 if (!chan->running) {
1506                         printk(KERN_INFO DEVICE_NAME ": already stopped\n");
1507                         return;
1508                 }
1509         }
1510
1511         if (dev->card_info->switch_ctrl)
1512                 dev->card_info->switch_ctrl(chan, 1, state ^ 1);
1513
1514         if (state) {
1515                 spin_lock_irq(&chan->state_lock);
1516
1517                 /* printk(KERN_INFO DEVICE_NAME ": lock=%08x\n",
1518                           ngreadl(0x9310)); */
1519                 my_dvb_ringbuffer_flush(&dev->tsout_rbuf);
1520                 control = 0x80;
1521                 if (chan->mode & (NGENE_IO_TSIN | NGENE_IO_TSOUT)) {
1522                         chan->Capture1Length = 512 * 188;
1523                         mode = SMODE_TRANSPORT_STREAM;
1524                 }
1525                 if (chan->mode & NGENE_IO_TSOUT) {
1526                         chan->pBufferExchange = tsout_exchange;
1527                         /* 0x66666666 = 50MHz *2^33 /250MHz */
1528                         chan->AudioDTOValue = 0x66666666;
1529                         /* set_dto(chan, 38810700+1000); */
1530                         /* set_dto(chan, 19392658); */
1531                 }
1532                 if (chan->mode & NGENE_IO_TSIN)
1533                         chan->pBufferExchange = tsin_exchange;
1534                 /* ngwritel(0, 0x9310); */
1535                 spin_unlock_irq(&chan->state_lock);
1536         } else
1537                 ;/* printk(KERN_INFO DEVICE_NAME ": lock=%08x\n",
1538                            ngreadl(0x9310)); */
1539
1540         ret = ngene_command_stream_control(dev, chan->number,
1541                                            control, mode, flags);
1542         if (!ret)
1543                 chan->running = state;
1544         else
1545                 printk(KERN_ERR DEVICE_NAME ": set_transfer %d failed\n",
1546                        state);
1547         if (!state) {
1548                 spin_lock_irq(&chan->state_lock);
1549                 chan->pBufferExchange = 0;
1550                 my_dvb_ringbuffer_flush(&dev->tsout_rbuf);
1551                 spin_unlock_irq(&chan->state_lock);
1552         }
1553 }
1554
1555 static int ngene_start_feed(struct dvb_demux_feed *dvbdmxfeed)
1556 {
1557         struct dvb_demux *dvbdmx = dvbdmxfeed->demux;
1558         struct ngene_channel *chan = dvbdmx->priv;
1559 #ifdef NGENE_COMMAND_API
1560         struct ngene *dev = chan->dev;
1561
1562         if (dev->card_info->io_type[chan->number] & NGENE_IO_TSOUT) {
1563                 switch (dvbdmxfeed->pes_type) {
1564                 case DMX_TS_PES_VIDEO:
1565                         send_cli_val(dev, "vpid", dvbdmxfeed->pid);
1566                         send_cli(dev, "res 1080i50\n");
1567                         /* send_cli(dev, "vdec mpeg2\n"); */
1568                         break;
1569
1570                 case DMX_TS_PES_AUDIO:
1571                         send_cli_val(dev, "apid", dvbdmxfeed->pid);
1572                         send_cli(dev, "start\n");
1573                         break;
1574
1575                 case DMX_TS_PES_PCR:
1576                         send_cli_val(dev, "pcrpid", dvbdmxfeed->pid);
1577                         break;
1578
1579                 default:
1580                         break;
1581                 }
1582
1583         }
1584 #endif
1585
1586         if (chan->users == 0) {
1587                 set_transfer(chan, 1);
1588                 /* msleep(10); */
1589         }
1590
1591         return ++chan->users;
1592 }
1593
1594 static int ngene_stop_feed(struct dvb_demux_feed *dvbdmxfeed)
1595 {
1596         struct dvb_demux *dvbdmx = dvbdmxfeed->demux;
1597         struct ngene_channel *chan = dvbdmx->priv;
1598 #ifdef NGENE_COMMAND_API
1599         struct ngene *dev = chan->dev;
1600
1601         if (dev->card_info->io_type[chan->number] & NGENE_IO_TSOUT) {
1602                 switch (dvbdmxfeed->pes_type) {
1603                 case DMX_TS_PES_VIDEO:
1604                         send_cli(dev, "stop\n");
1605                         break;
1606
1607                 case DMX_TS_PES_AUDIO:
1608                         break;
1609
1610                 case DMX_TS_PES_PCR:
1611                         break;
1612
1613                 default:
1614                         break;
1615                 }
1616
1617         }
1618 #endif
1619
1620         if (--chan->users)
1621                 return chan->users;
1622
1623         set_transfer(chan, 0);
1624
1625         return 0;
1626 }
1627
1628
1629
1630 static int write_to_decoder(struct dvb_demux_feed *feed,
1631                             const u8 *buf, size_t len)
1632 {
1633         struct dvb_demux *dvbdmx = feed->demux;
1634         struct ngene_channel *chan = dvbdmx->priv;
1635         struct ngene *dev = chan->dev;
1636
1637         if (wait_event_interruptible(dev->tsout_rbuf.queue,
1638                                      dvb_ringbuffer_free
1639                                      (&dev->tsout_rbuf) >= len) < 0)
1640                 return 0;
1641
1642         dvb_ringbuffer_write(&dev->tsout_rbuf, buf, len);
1643
1644         return len;
1645 }
1646
1647 static int my_dvb_dmx_ts_card_init(struct dvb_demux *dvbdemux, char *id,
1648                                    int (*start_feed)(struct dvb_demux_feed *),
1649                                    int (*stop_feed)(struct dvb_demux_feed *),
1650                                    void *priv)
1651 {
1652         dvbdemux->priv = priv;
1653
1654         dvbdemux->filternum = 256;
1655         dvbdemux->feednum = 256;
1656         dvbdemux->start_feed = start_feed;
1657         dvbdemux->stop_feed = stop_feed;
1658         dvbdemux->write_to_decoder = 0;
1659         dvbdemux->dmx.capabilities = (DMX_TS_FILTERING |
1660                                       DMX_SECTION_FILTERING |
1661                                       DMX_MEMORY_BASED_FILTERING);
1662         return dvb_dmx_init(dvbdemux);
1663 }
1664
1665 static int my_dvb_dmxdev_ts_card_init(struct dmxdev *dmxdev,
1666                                       struct dvb_demux *dvbdemux,
1667                                       struct dmx_frontend *hw_frontend,
1668                                       struct dmx_frontend *mem_frontend,
1669                                       struct dvb_adapter *dvb_adapter)
1670 {
1671         int ret;
1672
1673         dmxdev->filternum = 256;
1674         dmxdev->demux = &dvbdemux->dmx;
1675         dmxdev->capabilities = 0;
1676         ret = dvb_dmxdev_init(dmxdev, dvb_adapter);
1677         if (ret < 0)
1678                 return ret;
1679
1680         hw_frontend->source = DMX_FRONTEND_0;
1681         dvbdemux->dmx.add_frontend(&dvbdemux->dmx, hw_frontend);
1682         mem_frontend->source = DMX_MEMORY_FE;
1683         dvbdemux->dmx.add_frontend(&dvbdemux->dmx, mem_frontend);
1684         return dvbdemux->dmx.connect_frontend(&dvbdemux->dmx, hw_frontend);
1685 }
1686
1687 /****************************************************************************/
1688 /* Decypher firmware loading ************************************************/
1689 /****************************************************************************/
1690
1691 #define DECYPHER_FW "decypher.fw"
1692
1693 static int dec_ts_send(struct ngene *dev, u8 *buf, u32 len)
1694 {
1695         while (dvb_ringbuffer_free(&dev->tsout_rbuf) < len)
1696                 msleep(1);
1697
1698
1699         dvb_ringbuffer_write(&dev->tsout_rbuf, buf, len);
1700
1701         return len;
1702 }
1703
1704 u8 dec_fw_fill_ts[188] = { 0x47, 0x09, 0x0e, 0x10, 0xff, 0xff, 0x00, 0x00 };
1705
1706 int dec_fw_send(struct ngene *dev, u8 *fw, u32 size)
1707 {
1708         struct ngene_channel *chan = &dev->channel[4];
1709         u32 len = 180, cc = 0;
1710         u8 buf[8] = { 0x47, 0x09, 0x0e, 0x10, 0x00, 0x00, 0x00, 0x00 };
1711
1712         set_transfer(chan, 1);
1713         msleep(100);
1714         while (size) {
1715                 len = 180;
1716                 if (len > size)
1717                         len = size;
1718                 buf[3] = 0x10 | (cc & 0x0f);
1719                 buf[4] = (cc >> 8);
1720                 buf[5] = cc & 0xff;
1721                 buf[6] = len;
1722
1723                 dec_ts_send(dev, buf, 8);
1724                 dec_ts_send(dev, fw, len);
1725                 if (len < 180)
1726                         dec_ts_send(dev, dec_fw_fill_ts + len + 8, 180 - len);
1727                 cc++;
1728                 size -= len;
1729                 fw += len;
1730         }
1731         for (len = 0; len < 512; len++)
1732                 dec_ts_send(dev, dec_fw_fill_ts, 188);
1733         while (dvb_ringbuffer_avail(&dev->tsout_rbuf))
1734                 msleep(10);
1735         msleep(100);
1736         set_transfer(chan, 0);
1737         return 0;
1738 }
1739
1740 int dec_fw_boot(struct ngene *dev)
1741 {
1742         u32 size;
1743         const struct firmware *fw = NULL;
1744         u8 *dec_fw;
1745
1746         if (request_firmware(&fw, DECYPHER_FW, &dev->pci_dev->dev) < 0) {
1747                 printk(KERN_ERR DEVICE_NAME
1748                        ": %s not found. Check hotplug directory.\n",
1749                        DECYPHER_FW);
1750                 return -1;
1751         }
1752         printk(KERN_INFO DEVICE_NAME ": Booting decypher firmware file %s\n",
1753                DECYPHER_FW);
1754
1755         size = fw->size;
1756         dec_fw = (u8 *)fw->data;
1757         dec_fw_send(dev, dec_fw, size);
1758         release_firmware(fw);
1759         return 0;
1760 }
1761
1762 /****************************************************************************/
1763 /* nGene hardware init and release functions ********************************/
1764 /****************************************************************************/
1765
1766 void free_ringbuffer(struct ngene *dev, struct SRingBufferDescriptor *rb)
1767 {
1768         struct SBufferHeader *Cur = rb->Head;
1769         u32 j;
1770
1771         if (!Cur)
1772                 return;
1773
1774         for (j = 0; j < rb->NumBuffers; j++, Cur = Cur->Next) {
1775                 if (Cur->Buffer1)
1776                         pci_free_consistent(dev->pci_dev,
1777                                             rb->Buffer1Length,
1778                                             Cur->Buffer1,
1779                                             Cur->scList1->Address);
1780
1781                 if (Cur->Buffer2)
1782                         pci_free_consistent(dev->pci_dev,
1783                                             rb->Buffer2Length,
1784                                             Cur->Buffer2,
1785                                             Cur->scList2->Address);
1786         }
1787
1788         if (rb->SCListMem)
1789                 pci_free_consistent(dev->pci_dev, rb->SCListMemSize,
1790                                     rb->SCListMem, rb->PASCListMem);
1791
1792         pci_free_consistent(dev->pci_dev, rb->MemSize, rb->Head, rb->PAHead);
1793 }
1794
1795 void free_idlebuffer(struct ngene *dev,
1796                      struct SRingBufferDescriptor *rb,
1797                      struct SRingBufferDescriptor *tb)
1798 {
1799         int j;
1800         struct SBufferHeader *Cur = tb->Head;
1801
1802         if (!rb->Head)
1803                 return;
1804         free_ringbuffer(dev, rb);
1805         for (j = 0; j < tb->NumBuffers; j++, Cur = Cur->Next) {
1806                 Cur->Buffer2 = 0;
1807                 Cur->scList2 = 0;
1808                 Cur->ngeneBuffer.Address_of_first_entry_2 = 0;
1809                 Cur->ngeneBuffer.Number_of_entries_2 = 0;
1810         }
1811 }
1812
1813 void free_common_buffers(struct ngene *dev)
1814 {
1815         u32 i;
1816         struct ngene_channel *chan;
1817
1818         for (i = STREAM_VIDEOIN1; i < MAX_STREAM; i++) {
1819                 chan = &dev->channel[i];
1820                 free_idlebuffer(dev, &chan->TSIdleBuffer, &chan->TSRingBuffer);
1821                 free_ringbuffer(dev, &chan->RingBuffer);
1822                 free_ringbuffer(dev, &chan->TSRingBuffer);
1823         }
1824
1825         if (dev->OverflowBuffer)
1826                 pci_free_consistent(dev->pci_dev,
1827                                     OVERFLOW_BUFFER_SIZE,
1828                                     dev->OverflowBuffer, dev->PAOverflowBuffer);
1829
1830         if (dev->FWInterfaceBuffer)
1831                 pci_free_consistent(dev->pci_dev,
1832                                     4096,
1833                                     dev->FWInterfaceBuffer,
1834                                     dev->PAFWInterfaceBuffer);
1835 }
1836
1837 /****************************************************************************/
1838 /* Ring buffer handling *****************************************************/
1839 /****************************************************************************/
1840
1841 int create_ring_buffer(struct pci_dev *pci_dev,
1842                        struct SRingBufferDescriptor *descr, u32 NumBuffers)
1843 {
1844         dma_addr_t tmp;
1845         struct SBufferHeader *Head;
1846         u32 i;
1847         u32 MemSize = SIZEOF_SBufferHeader * NumBuffers;
1848         u64 PARingBufferHead;
1849         u64 PARingBufferCur;
1850         u64 PARingBufferNext;
1851         struct SBufferHeader *Cur, *Next;
1852
1853         descr->Head = 0;
1854         descr->MemSize = 0;
1855         descr->PAHead = 0;
1856         descr->NumBuffers = 0;
1857
1858         if (MemSize < 4096)
1859                 MemSize = 4096;
1860
1861         Head = pci_alloc_consistent(pci_dev, MemSize, &tmp);
1862         PARingBufferHead = tmp;
1863
1864         if (!Head)
1865                 return -ENOMEM;
1866
1867         memset(Head, 0, MemSize);
1868
1869         PARingBufferCur = PARingBufferHead;
1870         Cur = Head;
1871
1872         for (i = 0; i < NumBuffers - 1; i++) {
1873                 Next = (struct SBufferHeader *)
1874                         (((u8 *) Cur) + SIZEOF_SBufferHeader);
1875                 PARingBufferNext = PARingBufferCur + SIZEOF_SBufferHeader;
1876                 Cur->Next = Next;
1877                 Cur->ngeneBuffer.Next = PARingBufferNext;
1878                 Cur = Next;
1879                 PARingBufferCur = PARingBufferNext;
1880         }
1881         /* Last Buffer points back to first one */
1882         Cur->Next = Head;
1883         Cur->ngeneBuffer.Next = PARingBufferHead;
1884
1885         descr->Head       = Head;
1886         descr->MemSize    = MemSize;
1887         descr->PAHead     = PARingBufferHead;
1888         descr->NumBuffers = NumBuffers;
1889
1890         return 0;
1891 }
1892
1893 static int AllocateRingBuffers(struct pci_dev *pci_dev,
1894                                dma_addr_t of,
1895                                struct SRingBufferDescriptor *pRingBuffer,
1896                                u32 Buffer1Length, u32 Buffer2Length)
1897 {
1898         dma_addr_t tmp;
1899         u32 i, j;
1900         int status = 0;
1901         u32 SCListMemSize = pRingBuffer->NumBuffers
1902                 * ((Buffer2Length != 0) ? (NUM_SCATTER_GATHER_ENTRIES * 2) :
1903                     NUM_SCATTER_GATHER_ENTRIES)
1904                 * sizeof(struct HW_SCATTER_GATHER_ELEMENT);
1905
1906         u64 PASCListMem;
1907         PHW_SCATTER_GATHER_ELEMENT SCListEntry;
1908         u64 PASCListEntry;
1909         struct SBufferHeader *Cur;
1910         void *SCListMem;
1911
1912         if (SCListMemSize < 4096)
1913                 SCListMemSize = 4096;
1914
1915         SCListMem = pci_alloc_consistent(pci_dev, SCListMemSize, &tmp);
1916
1917         PASCListMem = tmp;
1918         if (SCListMem == NULL)
1919                 return -ENOMEM;
1920
1921         memset(SCListMem, 0, SCListMemSize);
1922
1923         pRingBuffer->SCListMem = SCListMem;
1924         pRingBuffer->PASCListMem = PASCListMem;
1925         pRingBuffer->SCListMemSize = SCListMemSize;
1926         pRingBuffer->Buffer1Length = Buffer1Length;
1927         pRingBuffer->Buffer2Length = Buffer2Length;
1928
1929         SCListEntry = (PHW_SCATTER_GATHER_ELEMENT) SCListMem;
1930         PASCListEntry = PASCListMem;
1931         Cur = pRingBuffer->Head;
1932
1933         for (i = 0; i < pRingBuffer->NumBuffers; i += 1, Cur = Cur->Next) {
1934                 u64 PABuffer;
1935
1936                 void *Buffer = pci_alloc_consistent(pci_dev, Buffer1Length,
1937                                                     &tmp);
1938                 PABuffer = tmp;
1939
1940                 if (Buffer == NULL)
1941                         return -ENOMEM;
1942
1943                 Cur->Buffer1 = Buffer;
1944
1945                 SCListEntry->Address = PABuffer;
1946                 SCListEntry->Length  = Buffer1Length;
1947
1948                 Cur->scList1 = SCListEntry;
1949                 Cur->ngeneBuffer.Address_of_first_entry_1 = PASCListEntry;
1950                 Cur->ngeneBuffer.Number_of_entries_1 =
1951                         NUM_SCATTER_GATHER_ENTRIES;
1952
1953                 SCListEntry += 1;
1954                 PASCListEntry += sizeof(struct HW_SCATTER_GATHER_ELEMENT);
1955
1956 #if NUM_SCATTER_GATHER_ENTRIES > 1
1957                 for (j = 0; j < NUM_SCATTER_GATHER_ENTRIES - 1; j += 1) {
1958                         SCListEntry->Address = of;
1959                         SCListEntry->Length = OVERFLOW_BUFFER_SIZE;
1960                         SCListEntry += 1;
1961                         PASCListEntry +=
1962                                 sizeof(struct HW_SCATTER_GATHER_ELEMENT);
1963                 }
1964 #endif
1965
1966                 if (!Buffer2Length)
1967                         continue;
1968
1969                 Buffer = pci_alloc_consistent(pci_dev, Buffer2Length, &tmp);
1970                 PABuffer = tmp;
1971
1972                 if (Buffer == NULL)
1973                         return -ENOMEM;
1974
1975                 Cur->Buffer2 = Buffer;
1976
1977                 SCListEntry->Address = PABuffer;
1978                 SCListEntry->Length  = Buffer2Length;
1979
1980                 Cur->scList2 = SCListEntry;
1981                 Cur->ngeneBuffer.Address_of_first_entry_2 = PASCListEntry;
1982                 Cur->ngeneBuffer.Number_of_entries_2 =
1983                         NUM_SCATTER_GATHER_ENTRIES;
1984
1985                 SCListEntry   += 1;
1986                 PASCListEntry += sizeof(struct HW_SCATTER_GATHER_ELEMENT);
1987
1988 #if NUM_SCATTER_GATHER_ENTRIES > 1
1989                 for (j = 0; j < NUM_SCATTER_GATHER_ENTRIES - 1; j++) {
1990                         SCListEntry->Address = of;
1991                         SCListEntry->Length = OVERFLOW_BUFFER_SIZE;
1992                         SCListEntry += 1;
1993                         PASCListEntry +=
1994                                 sizeof(struct HW_SCATTER_GATHER_ELEMENT);
1995                 }
1996 #endif
1997
1998         }
1999
2000         return status;
2001 }
2002
2003 static int FillTSIdleBuffer(struct SRingBufferDescriptor *pIdleBuffer,
2004                             struct SRingBufferDescriptor *pRingBuffer)
2005 {
2006         int status = 0;
2007
2008         /* Copy pointer to scatter gather list in TSRingbuffer
2009            structure for buffer 2
2010            Load number of buffer
2011         */
2012         u32 n = pRingBuffer->NumBuffers;
2013
2014         /* Point to first buffer entry */
2015         struct SBufferHeader *Cur = pRingBuffer->Head;
2016         int i;
2017         /* Loop thru all buffer and set Buffer 2 pointers to TSIdlebuffer */
2018         for (i = 0; i < n; i++) {
2019                 Cur->Buffer2 = pIdleBuffer->Head->Buffer1;
2020                 Cur->scList2 = pIdleBuffer->Head->scList1;
2021                 Cur->ngeneBuffer.Address_of_first_entry_2 =
2022                         pIdleBuffer->Head->ngeneBuffer.
2023                         Address_of_first_entry_1;
2024                 Cur->ngeneBuffer.Number_of_entries_2 =
2025                         pIdleBuffer->Head->ngeneBuffer.Number_of_entries_1;
2026                 Cur = Cur->Next;
2027         }
2028         return status;
2029 }
2030
2031 static u32 RingBufferSizes[MAX_STREAM] = {
2032         RING_SIZE_VIDEO,
2033         RING_SIZE_VIDEO,
2034         RING_SIZE_AUDIO,
2035         RING_SIZE_AUDIO,
2036         RING_SIZE_AUDIO,
2037 };
2038
2039 static u32 Buffer1Sizes[MAX_STREAM] = {
2040         MAX_VIDEO_BUFFER_SIZE,
2041         MAX_VIDEO_BUFFER_SIZE,
2042         MAX_AUDIO_BUFFER_SIZE,
2043         MAX_AUDIO_BUFFER_SIZE,
2044         MAX_AUDIO_BUFFER_SIZE
2045 };
2046
2047 static u32 Buffer2Sizes[MAX_STREAM] = {
2048         MAX_VBI_BUFFER_SIZE,
2049         MAX_VBI_BUFFER_SIZE,
2050         0,
2051         0,
2052         0
2053 };
2054
2055
2056 static int AllocCommonBuffers(struct ngene *dev)
2057 {
2058         int status = 0, i;
2059
2060         dev->FWInterfaceBuffer = pci_alloc_consistent(dev->pci_dev, 4096,
2061                                                      &dev->PAFWInterfaceBuffer);
2062         if (!dev->FWInterfaceBuffer)
2063                 return -ENOMEM;
2064         dev->hosttongene = dev->FWInterfaceBuffer;
2065         dev->ngenetohost = dev->FWInterfaceBuffer + 256;
2066         dev->EventBuffer = dev->FWInterfaceBuffer + 512;
2067
2068         dev->OverflowBuffer = pci_alloc_consistent(dev->pci_dev,
2069                                                    OVERFLOW_BUFFER_SIZE,
2070                                                    &dev->PAOverflowBuffer);
2071         if (!dev->OverflowBuffer)
2072                 return -ENOMEM;
2073         memset(dev->OverflowBuffer, 0, OVERFLOW_BUFFER_SIZE);
2074
2075         for (i = STREAM_VIDEOIN1; i < MAX_STREAM; i++) {
2076                 int type = dev->card_info->io_type[i];
2077
2078                 dev->channel[i].State = KSSTATE_STOP;
2079
2080                 if (type & (NGENE_IO_TV | NGENE_IO_HDTV | NGENE_IO_AIN)) {
2081                         status = create_ring_buffer(dev->pci_dev,
2082                                                     &dev->channel[i].RingBuffer,
2083                                                     RingBufferSizes[i]);
2084                         if (status < 0)
2085                                 break;
2086
2087                         if (type & (NGENE_IO_TV | NGENE_IO_AIN)) {
2088                                 status = AllocateRingBuffers(dev->pci_dev,
2089                                                              dev->
2090                                                              PAOverflowBuffer,
2091                                                              &dev->channel[i].
2092                                                              RingBuffer,
2093                                                              Buffer1Sizes[i],
2094                                                              Buffer2Sizes[i]);
2095                                 if (status < 0)
2096                                         break;
2097                         } else if (type & NGENE_IO_HDTV) {
2098                                 status = AllocateRingBuffers(dev->pci_dev,
2099                                                              dev->
2100                                                              PAOverflowBuffer,
2101                                                              &dev->channel[i].
2102                                                              RingBuffer,
2103                                                            MAX_HDTV_BUFFER_SIZE,
2104                                                              0);
2105                                 if (status < 0)
2106                                         break;
2107                         }
2108                 }
2109
2110                 if (type & (NGENE_IO_TSIN | NGENE_IO_TSOUT)) {
2111
2112                         status = create_ring_buffer(dev->pci_dev,
2113                                                     &dev->channel[i].
2114                                                     TSRingBuffer, RING_SIZE_TS);
2115                         if (status < 0)
2116                                 break;
2117
2118                         status = AllocateRingBuffers(dev->pci_dev,
2119                                                      dev->PAOverflowBuffer,
2120                                                      &dev->channel[i].
2121                                                      TSRingBuffer,
2122                                                      MAX_TS_BUFFER_SIZE, 0);
2123                         if (status)
2124                                 break;
2125                 }
2126
2127                 if (type & NGENE_IO_TSOUT) {
2128                         status = create_ring_buffer(dev->pci_dev,
2129                                                     &dev->channel[i].
2130                                                     TSIdleBuffer, 1);
2131                         if (status < 0)
2132                                 break;
2133                         status = AllocateRingBuffers(dev->pci_dev,
2134                                                      dev->PAOverflowBuffer,
2135                                                      &dev->channel[i].
2136                                                      TSIdleBuffer,
2137                                                      MAX_TS_BUFFER_SIZE, 0);
2138                         if (status)
2139                                 break;
2140                         FillTSIdleBuffer(&dev->channel[i].TSIdleBuffer,
2141                                          &dev->channel[i].TSRingBuffer);
2142                 }
2143         }
2144         return status;
2145 }
2146
2147 static void ngene_release_buffers(struct ngene *dev)
2148 {
2149         if (dev->iomem)
2150                 iounmap(dev->iomem);
2151         free_common_buffers(dev);
2152         vfree(dev->tsout_buf);
2153         vfree(dev->ain_buf);
2154         vfree(dev->vin_buf);
2155         vfree(dev);
2156 }
2157
2158 static int ngene_get_buffers(struct ngene *dev)
2159 {
2160         if (AllocCommonBuffers(dev))
2161                 return -ENOMEM;
2162         if (dev->card_info->io_type[4] & NGENE_IO_TSOUT) {
2163                 dev->tsout_buf = vmalloc(TSOUT_BUF_SIZE);
2164                 if (!dev->tsout_buf)
2165                         return -ENOMEM;
2166                 dvb_ringbuffer_init(&dev->tsout_rbuf,
2167                                     dev->tsout_buf, TSOUT_BUF_SIZE);
2168         }
2169         if (dev->card_info->io_type[2] & NGENE_IO_AIN) {
2170                 dev->ain_buf = vmalloc(AIN_BUF_SIZE);
2171                 if (!dev->ain_buf)
2172                         return -ENOMEM;
2173                 dvb_ringbuffer_init(&dev->ain_rbuf, dev->ain_buf, AIN_BUF_SIZE);
2174         }
2175         if (dev->card_info->io_type[0] & NGENE_IO_HDTV) {
2176                 dev->vin_buf = vmalloc(VIN_BUF_SIZE);
2177                 if (!dev->vin_buf)
2178                         return -ENOMEM;
2179                 dvb_ringbuffer_init(&dev->vin_rbuf, dev->vin_buf, VIN_BUF_SIZE);
2180         }
2181         dev->iomem = ioremap(pci_resource_start(dev->pci_dev, 0),
2182                              pci_resource_len(dev->pci_dev, 0));
2183         if (!dev->iomem)
2184                 return -ENOMEM;
2185
2186         return 0;
2187 }
2188
2189 static void ngene_init(struct ngene *dev)
2190 {
2191         int i;
2192
2193         tasklet_init(&dev->event_tasklet, event_tasklet, (unsigned long)dev);
2194
2195         memset_io(dev->iomem + 0xc000, 0x00, 0x220);
2196         memset_io(dev->iomem + 0xc400, 0x00, 0x100);
2197
2198         for (i = 0; i < MAX_STREAM; i++) {
2199                 dev->channel[i].dev = dev;
2200                 dev->channel[i].number = i;
2201         }
2202
2203         dev->fw_interface_version = 0;
2204
2205         ngwritel(0, NGENE_INT_ENABLE);
2206
2207         dev->icounts = ngreadl(NGENE_INT_COUNTS);
2208
2209         dev->device_version = ngreadl(DEV_VER) & 0x0f;
2210         printk(KERN_INFO DEVICE_NAME ": Device version %d\n",
2211                dev->device_version);
2212 }
2213
2214 static int ngene_load_firm(struct ngene *dev)
2215 {
2216         u32 size;
2217         const struct firmware *fw = NULL;
2218         u8 *ngene_fw;
2219         char *fw_name;
2220         int err, version;
2221
2222         version = dev->card_info->fw_version;
2223
2224         switch (version) {
2225         default:
2226         case 15:
2227                 version = 15;
2228                 size = 23466;
2229                 fw_name = "ngene_15.fw";
2230                 break;
2231         case 16:
2232                 size = 23498;
2233                 fw_name = "ngene_16.fw";
2234                 break;
2235         case 17:
2236                 size = 24446;
2237                 fw_name = "ngene_17.fw";
2238                 break;
2239         }
2240
2241         if (request_firmware(&fw, fw_name, &dev->pci_dev->dev) < 0) {
2242                 printk(KERN_ERR DEVICE_NAME
2243                         ": Could not load firmware file %s.\n", fw_name);
2244                 printk(KERN_INFO DEVICE_NAME
2245                         ": Copy %s to your hotplug directory!\n", fw_name);
2246                 return -1;
2247         }
2248         if (size != fw->size) {
2249                 printk(KERN_ERR DEVICE_NAME
2250                         ": Firmware %s has invalid size!", fw_name);
2251                 err = -1;
2252         } else {
2253                 printk(KERN_INFO DEVICE_NAME
2254                         ": Loading firmware file %s.\n", fw_name);
2255                 ngene_fw = (u8 *) fw->data;
2256                 err = ngene_command_load_firmware(dev, ngene_fw, size);
2257         }
2258
2259         release_firmware(fw);
2260
2261         return err;
2262 }
2263
2264 static void ngene_stop(struct ngene *dev)
2265 {
2266         down(&dev->cmd_mutex);
2267         i2c_del_adapter(&(dev->channel[0].i2c_adapter));
2268         i2c_del_adapter(&(dev->channel[1].i2c_adapter));
2269         ngwritel(0, NGENE_INT_ENABLE);
2270         ngwritel(0, NGENE_COMMAND);
2271         ngwritel(0, NGENE_COMMAND_HI);
2272         ngwritel(0, NGENE_STATUS);
2273         ngwritel(0, NGENE_STATUS_HI);
2274         ngwritel(0, NGENE_EVENT);
2275         ngwritel(0, NGENE_EVENT_HI);
2276         free_irq(dev->pci_dev->irq, dev);
2277 }
2278
2279 static int ngene_start(struct ngene *dev)
2280 {
2281         int stat;
2282         int i;
2283
2284         pci_set_master(dev->pci_dev);
2285         ngene_init(dev);
2286
2287         stat = request_irq(dev->pci_dev->irq, irq_handler,
2288                            IRQF_SHARED, "nGene",
2289                            (void *)dev);
2290         if (stat < 0)
2291                 return stat;
2292
2293         init_waitqueue_head(&dev->cmd_wq);
2294         init_waitqueue_head(&dev->tx_wq);
2295         init_waitqueue_head(&dev->rx_wq);
2296         sema_init(&dev->cmd_mutex, 1);
2297         sema_init(&dev->stream_mutex, 1);
2298         sema_init(&dev->pll_mutex, 1);
2299         sema_init(&dev->i2c_switch_mutex, 1);
2300         spin_lock_init(&dev->cmd_lock);
2301         for (i = 0; i < MAX_STREAM; i++)
2302                 spin_lock_init(&dev->channel[i].state_lock);
2303         ngwritel(1, TIMESTAMPS);
2304
2305         ngwritel(1, NGENE_INT_ENABLE);
2306
2307         stat = ngene_load_firm(dev);
2308         if (stat < 0)
2309                 goto fail;
2310
2311         stat = ngene_i2c_init(dev, 0);
2312         if (stat < 0)
2313                 goto fail;
2314
2315         stat = ngene_i2c_init(dev, 1);
2316         if (stat < 0)
2317                 goto fail;
2318
2319         if (dev->card_info->fw_version == 17) {
2320                 u8 hdtv_config[6] =
2321                         {6144 / 64, 0, 0, 2048 / 64, 2048 / 64, 2048 / 64};
2322                 u8 tsin4_config[6] =
2323                         {3072 / 64, 3072 / 64, 0, 3072 / 64, 3072 / 64, 0};
2324                 u8 default_config[6] =
2325                         {4096 / 64, 4096 / 64, 0, 2048 / 64, 2048 / 64, 0};
2326                 u8 *bconf = default_config;
2327
2328                 if (dev->card_info->io_type[3] == NGENE_IO_TSIN)
2329                         bconf = tsin4_config;
2330                 if (dev->card_info->io_type[0] == NGENE_IO_HDTV) {
2331                         bconf = hdtv_config;
2332                         ngene_reset_decypher(dev);
2333                 }
2334                 printk(KERN_INFO DEVICE_NAME ": FW 17 buffer config\n");
2335                 stat = ngene_command_config_free_buf(dev, bconf);
2336         } else {
2337                 int bconf = BUFFER_CONFIG_4422;
2338
2339                 if (dev->card_info->io_type[0] == NGENE_IO_HDTV) {
2340                         bconf = BUFFER_CONFIG_8022;
2341                         ngene_reset_decypher(dev);
2342                 }
2343                 if (dev->card_info->io_type[3] == NGENE_IO_TSIN)
2344                         bconf = BUFFER_CONFIG_3333;
2345                 stat = ngene_command_config_buf(dev, bconf);
2346         }
2347
2348         if (dev->card_info->io_type[0] == NGENE_IO_HDTV) {
2349                 ngene_command_config_uart(dev, 0xc1, tx_cb, rx_cb);
2350                 test_dec_i2c(&dev->channel[0].i2c_adapter, 0);
2351                 test_dec_i2c(&dev->channel[0].i2c_adapter, 1);
2352         }
2353
2354         return stat;
2355 fail:
2356         ngwritel(0, NGENE_INT_ENABLE);
2357         free_irq(dev->pci_dev->irq, dev);
2358         return stat;
2359 }
2360
2361
2362
2363 /****************************************************************************/
2364 /* Switch control (I2C gates, etc.) *****************************************/
2365 /****************************************************************************/
2366
2367
2368 /****************************************************************************/
2369 /* Demod/tuner attachment ***************************************************/
2370 /****************************************************************************/
2371
2372 static int tuner_attach_stv6110(struct ngene_channel *chan)
2373 {
2374         struct stv090x_config *feconf = (struct stv090x_config *)
2375                 chan->dev->card_info->fe_config[chan->number];
2376         struct stv6110x_config *tunerconf = (struct stv6110x_config *)
2377                 chan->dev->card_info->tuner_config[chan->number];
2378         struct stv6110x_devctl *ctl;
2379
2380         ctl = dvb_attach(stv6110x_attach, chan->fe, tunerconf,
2381                          &chan->i2c_adapter);
2382         if (ctl == NULL) {
2383                 printk(KERN_ERR DEVICE_NAME ": No STV6110X found!\n");
2384                 return -ENODEV;
2385         }
2386
2387         feconf->tuner_init          = ctl->tuner_init;
2388         feconf->tuner_set_mode      = ctl->tuner_set_mode;
2389         feconf->tuner_set_frequency = ctl->tuner_set_frequency;
2390         feconf->tuner_get_frequency = ctl->tuner_get_frequency;
2391         feconf->tuner_set_bandwidth = ctl->tuner_set_bandwidth;
2392         feconf->tuner_get_bandwidth = ctl->tuner_get_bandwidth;
2393         feconf->tuner_set_bbgain    = ctl->tuner_set_bbgain;
2394         feconf->tuner_get_bbgain    = ctl->tuner_get_bbgain;
2395         feconf->tuner_set_refclk    = ctl->tuner_set_refclk;
2396         feconf->tuner_get_status    = ctl->tuner_get_status;
2397
2398         return 0;
2399 }
2400
2401
2402 static int demod_attach_stv0900(struct ngene_channel *chan)
2403 {
2404         struct stv090x_config *feconf = (struct stv090x_config *)
2405                 chan->dev->card_info->fe_config[chan->number];
2406
2407         chan->fe = dvb_attach(stv090x_attach,
2408                         feconf,
2409                         &chan->i2c_adapter,
2410                         chan->number == 0 ? STV090x_DEMODULATOR_0 :
2411                                             STV090x_DEMODULATOR_1);
2412         if (chan->fe == NULL) {
2413                 printk(KERN_ERR DEVICE_NAME ": No STV0900 found!\n");
2414                 return -ENODEV;
2415         }
2416
2417         if (!dvb_attach(lnbh24_attach, chan->fe, &chan->i2c_adapter, 0,
2418                         0, chan->dev->card_info->lnb[chan->number])) {
2419                 printk(KERN_ERR DEVICE_NAME ": No LNBH24 found!\n");
2420                 dvb_frontend_detach(chan->fe);
2421                 return -ENODEV;
2422         }
2423
2424         return 0;
2425 }
2426
2427 /****************************************************************************/
2428 /****************************************************************************/
2429 /****************************************************************************/
2430
2431 static void release_channel(struct ngene_channel *chan)
2432 {
2433         struct dvb_demux *dvbdemux = &chan->demux;
2434         struct ngene *dev = chan->dev;
2435         struct ngene_info *ni = dev->card_info;
2436         int io = ni->io_type[chan->number];
2437
2438         tasklet_kill(&chan->demux_tasklet);
2439
2440         if (io & (NGENE_IO_TSIN | NGENE_IO_TSOUT)) {
2441 #ifdef NGENE_COMMAND_API
2442                 if (chan->command_dev)
2443                         dvb_unregister_device(chan->command_dev);
2444 #endif
2445                 if (chan->fe) {
2446                         dvb_unregister_frontend(chan->fe);
2447                         dvb_frontend_detach(chan->fe);
2448                         chan->fe = 0;
2449                 }
2450                 dvbdemux->dmx.close(&dvbdemux->dmx);
2451                 dvbdemux->dmx.remove_frontend(&dvbdemux->dmx,
2452                                               &chan->hw_frontend);
2453                 dvbdemux->dmx.remove_frontend(&dvbdemux->dmx,
2454                                               &chan->mem_frontend);
2455                 dvb_dmxdev_release(&chan->dmxdev);
2456                 dvb_dmx_release(&chan->demux);
2457 #ifndef ONE_ADAPTER
2458                 dvb_unregister_adapter(&chan->dvb_adapter);
2459 #endif
2460         }
2461
2462 }
2463
2464 static int init_channel(struct ngene_channel *chan)
2465 {
2466         int ret = 0, nr = chan->number;
2467         struct dvb_adapter *adapter = 0;
2468         struct dvb_demux *dvbdemux = &chan->demux;
2469         struct ngene *dev = chan->dev;
2470         struct ngene_info *ni = dev->card_info;
2471         int io = ni->io_type[nr];
2472
2473         tasklet_init(&chan->demux_tasklet, demux_tasklet, (unsigned long)chan);
2474         chan->users = 0;
2475         chan->type = io;
2476         chan->mode = chan->type;        /* for now only one mode */
2477
2478         if (io & (NGENE_IO_TSIN | NGENE_IO_TSOUT)) {
2479                 if (nr >= STREAM_AUDIOIN1)
2480                         chan->DataFormatFlags = DF_SWAP32;
2481
2482                 if (io & NGENE_IO_TSOUT)
2483                         dec_fw_boot(dev);
2484
2485 #ifdef ONE_ADAPTER
2486                 adapter = &chan->dev->dvb_adapter;
2487 #else
2488                 ret = dvb_register_adapter(&chan->dvb_adapter, "nGene",
2489                                            THIS_MODULE,
2490                                            &chan->dev->pci_dev->dev,
2491                                            adapter_nr);
2492                 if (ret < 0)
2493                         return ret;
2494                 adapter = &chan->dvb_adapter;
2495 #endif
2496                 ret = my_dvb_dmx_ts_card_init(dvbdemux, "SW demux",
2497                                               ngene_start_feed,
2498                                               ngene_stop_feed, chan);
2499                 ret = my_dvb_dmxdev_ts_card_init(&chan->dmxdev, &chan->demux,
2500                                                  &chan->hw_frontend,
2501                                                  &chan->mem_frontend, adapter);
2502                 if (io & NGENE_IO_TSOUT) {
2503                         dvbdemux->write_to_decoder = write_to_decoder;
2504                 }
2505 #ifdef NGENE_COMMAND_API
2506                 dvb_register_device(adapter, &chan->command_dev,
2507                                     &dvbdev_command, (void *)chan,
2508                                     DVB_DEVICE_SEC);
2509 #endif
2510         }
2511
2512         if (io & NGENE_IO_TSIN) {
2513                 chan->fe = NULL;
2514                 if (ni->demod_attach[nr])
2515                         ni->demod_attach[nr](chan);
2516                 if (chan->fe) {
2517                         if (dvb_register_frontend(adapter, chan->fe) < 0) {
2518                                 if (chan->fe->ops.release)
2519                                         chan->fe->ops.release(chan->fe);
2520                                 chan->fe = NULL;
2521                         }
2522                 }
2523                 if (chan->fe && ni->tuner_attach[nr])
2524                         if (ni->tuner_attach[nr] (chan) < 0) {
2525                                 printk(KERN_ERR DEVICE_NAME
2526                                        ": Tuner attach failed on channel %d!\n",
2527                                        nr);
2528                         }
2529         }
2530
2531         return ret;
2532 }
2533
2534 static int init_channels(struct ngene *dev)
2535 {
2536         int i, j;
2537
2538         for (i = 0; i < MAX_STREAM; i++) {
2539                 if (init_channel(&dev->channel[i]) < 0) {
2540                         for (j = 0; j < i; j++)
2541                                 release_channel(&dev->channel[j]);
2542                         return -1;
2543                 }
2544         }
2545         return 0;
2546 }
2547
2548 /****************************************************************************/
2549 /* device probe/remove calls ************************************************/
2550 /****************************************************************************/
2551
2552 static void __devexit ngene_remove(struct pci_dev *pdev)
2553 {
2554         struct ngene *dev = (struct ngene *)pci_get_drvdata(pdev);
2555         int i;
2556
2557         tasklet_kill(&dev->event_tasklet);
2558         for (i = 0; i < MAX_STREAM; i++)
2559                 release_channel(&dev->channel[i]);
2560 #ifdef ONE_ADAPTER
2561         dvb_unregister_adapter(&dev->dvb_adapter);
2562 #endif
2563         ngene_stop(dev);
2564         ngene_release_buffers(dev);
2565         pci_set_drvdata(pdev, 0);
2566         pci_disable_device(pdev);
2567 }
2568
2569 static int __devinit ngene_probe(struct pci_dev *pci_dev,
2570                                  const struct pci_device_id *id)
2571 {
2572         struct ngene *dev;
2573         int stat = 0;
2574
2575         if (pci_enable_device(pci_dev) < 0)
2576                 return -ENODEV;
2577
2578         dev = vmalloc(sizeof(struct ngene));
2579         if (dev == NULL) {
2580                 stat = -ENOMEM;
2581                 goto fail0;
2582         }
2583         memset(dev, 0, sizeof(struct ngene));
2584
2585         dev->pci_dev = pci_dev;
2586         dev->card_info = (struct ngene_info *)id->driver_data;
2587         printk(KERN_INFO DEVICE_NAME ": Found %s\n", dev->card_info->name);
2588
2589         pci_set_drvdata(pci_dev, dev);
2590
2591         /* Alloc buffers and start nGene */
2592         stat = ngene_get_buffers(dev);
2593         if (stat < 0)
2594                 goto fail1;
2595         stat = ngene_start(dev);
2596         if (stat < 0)
2597                 goto fail1;
2598
2599         dev->i2c_current_bus = -1;
2600         /* Disable analog TV decoder chips if present */
2601         if (copy_eeprom) {
2602                 i2c_copy_eeprom(&dev->channel[0].i2c_adapter, 0x50, 0x52);
2603                 i2c_dump_eeprom(&dev->channel[0].i2c_adapter, 0x52);
2604         }
2605         /*i2c_check_eeprom(&dev->i2c_adapter);*/
2606
2607         /* Register DVB adapters and devices for both channels */
2608 #ifdef ONE_ADAPTER
2609         if (dvb_register_adapter(&dev->dvb_adapter, "nGene", THIS_MODULE,
2610                                  &dev->pci_dev->dev, adapter_nr) < 0)
2611                 goto fail2;
2612 #endif
2613         if (init_channels(dev) < 0)
2614                 goto fail2;
2615
2616         return 0;
2617
2618 fail2:
2619         ngene_stop(dev);
2620 fail1:
2621         ngene_release_buffers(dev);
2622 fail0:
2623         pci_disable_device(pci_dev);
2624         pci_set_drvdata(pci_dev, 0);
2625         return stat;
2626 }
2627
2628 /****************************************************************************/
2629 /* Card configs *************************************************************/
2630 /****************************************************************************/
2631
2632 static struct stv090x_config fe_mps2 = {
2633         .device         = STV0900,
2634         .demod_mode     = STV090x_DUAL,
2635         .clk_mode       = STV090x_CLK_EXT,
2636
2637         .xtal           = 27000000,
2638         .address        = 0x68,
2639 //      .ref_clk        = 27000000,
2640
2641         .ts1_mode       = STV090x_TSMODE_SERIAL_PUNCTURED,
2642         .ts2_mode       = STV090x_TSMODE_SERIAL_PUNCTURED,
2643
2644         .repeater_level = STV090x_RPTLEVEL_16,
2645
2646         .diseqc_envelope_mode = true,
2647
2648         .tuner_init           = NULL,
2649         .tuner_set_mode       = NULL,
2650         .tuner_set_frequency  = NULL,
2651         .tuner_get_frequency  = NULL,
2652         .tuner_set_bandwidth  = NULL,
2653         .tuner_get_bandwidth  = NULL,
2654         .tuner_set_bbgain     = NULL,
2655         .tuner_get_bbgain     = NULL,
2656         .tuner_set_refclk     = NULL,
2657         .tuner_get_status     = NULL,
2658 };
2659
2660 static struct stv6110x_config tuner_mps2_0 = {
2661         .addr   = 0x60,
2662         .refclk = 27000000,
2663 };
2664
2665 static struct stv6110x_config tuner_mps2_1 = {
2666         .addr   = 0x63,
2667         .refclk = 27000000,
2668 };
2669
2670 static struct ngene_info ngene_info_mps2 = {
2671         .type           = NGENE_SIDEWINDER,
2672         .name           = "Media-Pointer MP-S2/CineS2 DVB-S2 Twin Tuner",
2673         .io_type        = {NGENE_IO_TSIN, NGENE_IO_TSIN},
2674         .demod_attach   = {demod_attach_stv0900, demod_attach_stv0900},
2675         .tuner_attach   = {tuner_attach_stv6110, tuner_attach_stv6110},
2676         .fe_config      = {&fe_mps2, &fe_mps2},
2677         .tuner_config   = {&tuner_mps2_0, &tuner_mps2_1},
2678         .lnb            = {0x0b, 0x08},
2679         .tsf            = {3, 3},
2680         .fw_version     = 17,
2681 };
2682
2683 /****************************************************************************/
2684
2685
2686
2687 /****************************************************************************/
2688 /****************************************************************************/
2689 /****************************************************************************/
2690
2691 #define NGENE_ID(_subvend, _subdev, _driverdata) { \
2692         .vendor = NGENE_VID, .device = NGENE_PID, \
2693         .subvendor = _subvend, .subdevice = _subdev, \
2694         .driver_data = (unsigned long) &_driverdata }
2695
2696 /****************************************************************************/
2697
2698 static const struct pci_device_id ngene_id_tbl[] __devinitdata = {
2699         NGENE_ID(0x18c3, 0xabc3, ngene_info_mps2),
2700         NGENE_ID(0x18c3, 0xabc4, ngene_info_mps2),
2701         NGENE_ID(0x18c3, 0xdb01, ngene_info_mps2),
2702         {0}
2703 };
2704 MODULE_DEVICE_TABLE(pci, ngene_id_tbl);
2705
2706 /****************************************************************************/
2707 /* Init/Exit ****************************************************************/
2708 /****************************************************************************/
2709
2710 static pci_ers_result_t ngene_error_detected(struct pci_dev *dev,
2711                                              enum pci_channel_state state)
2712 {
2713         printk(KERN_ERR DEVICE_NAME ": PCI error\n");
2714         if (state == pci_channel_io_perm_failure)
2715                 return PCI_ERS_RESULT_DISCONNECT;
2716         if (state == pci_channel_io_frozen)
2717                 return PCI_ERS_RESULT_NEED_RESET;
2718         return PCI_ERS_RESULT_CAN_RECOVER;
2719 }
2720
2721 static pci_ers_result_t ngene_link_reset(struct pci_dev *dev)
2722 {
2723         printk(KERN_INFO DEVICE_NAME ": link reset\n");
2724         return 0;
2725 }
2726
2727 static pci_ers_result_t ngene_slot_reset(struct pci_dev *dev)
2728 {
2729         printk(KERN_INFO DEVICE_NAME ": slot reset\n");
2730         return 0;
2731 }
2732
2733 static void ngene_resume(struct pci_dev *dev)
2734 {
2735         printk(KERN_INFO DEVICE_NAME ": resume\n");
2736 }
2737
2738 static struct pci_error_handlers ngene_errors = {
2739         .error_detected = ngene_error_detected,
2740         .link_reset = ngene_link_reset,
2741         .slot_reset = ngene_slot_reset,
2742         .resume = ngene_resume,
2743 };
2744
2745 static struct pci_driver ngene_pci_driver = {
2746         .name        = "ngene",
2747         .id_table    = ngene_id_tbl,
2748         .probe       = ngene_probe,
2749         .remove      = __devexit_p(ngene_remove),
2750         .err_handler = &ngene_errors,
2751 };
2752
2753 static __init int module_init_ngene(void)
2754 {
2755         printk(KERN_INFO
2756                "nGene PCIE bridge driver, Copyright (C) 2005-2007 Micronas\n");
2757         return pci_register_driver(&ngene_pci_driver);
2758 }
2759
2760 static __exit void module_exit_ngene(void)
2761 {
2762         pci_unregister_driver(&ngene_pci_driver);
2763 }
2764
2765 module_init(module_init_ngene);
2766 module_exit(module_exit_ngene);
2767
2768 MODULE_DESCRIPTION("nGene");
2769 MODULE_AUTHOR("Micronas, Ralph Metzler, Manfred Voelkel");
2770 MODULE_LICENSE("GPL");