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  * To obtain the license, point your browser to
23  * http://www.gnu.org/copyleft/gpl.html
24  */
25 
26 #include <linux/module.h>
27 #include <linux/init.h>
28 #include <linux/delay.h>
29 #include <linux/poll.h>
30 #include <linux/io.h>
31 #include <asm/div64.h>
32 #include <linux/pci.h>
33 #include <linux/timer.h>
34 #include <linux/byteorder/generic.h>
35 #include <linux/firmware.h>
36 #include <linux/vmalloc.h>
37 
38 #include "ngene.h"
39 
40 static int one_adapter;
41 module_param(one_adapter, int, 0444);
42 MODULE_PARM_DESC(one_adapter, "Use only one adapter.");
43 
44 static int shutdown_workaround;
45 module_param(shutdown_workaround, int, 0644);
46 MODULE_PARM_DESC(shutdown_workaround, "Activate workaround for shutdown problem with some chipsets.");
47 
48 static int debug;
49 module_param(debug, int, 0444);
50 MODULE_PARM_DESC(debug, "Print debugging information.");
51 
52 DVB_DEFINE_MOD_OPT_ADAPTER_NR(adapter_nr);
53 
54 #define dprintk	if (debug) printk
55 
56 #define ngwriteb(dat, adr)         writeb((dat), dev->iomem + (adr))
57 #define ngwritel(dat, adr)         writel((dat), dev->iomem + (adr))
58 #define ngwriteb(dat, adr)         writeb((dat), dev->iomem + (adr))
59 #define ngreadl(adr)               readl(dev->iomem + (adr))
60 #define ngreadb(adr)               readb(dev->iomem + (adr))
61 #define ngcpyto(adr, src, count)   memcpy_toio(dev->iomem + (adr), (src), (count))
62 #define ngcpyfrom(dst, adr, count) memcpy_fromio((dst), dev->iomem + (adr), (count))
63 
64 /****************************************************************************/
65 /* nGene interrupt handler **************************************************/
66 /****************************************************************************/
67 
68 static void event_tasklet(unsigned long data)
69 {
70 	struct ngene *dev = (struct ngene *)data;
71 
72 	while (dev->EventQueueReadIndex != dev->EventQueueWriteIndex) {
73 		struct EVENT_BUFFER Event =
74 			dev->EventQueue[dev->EventQueueReadIndex];
75 		dev->EventQueueReadIndex =
76 			(dev->EventQueueReadIndex + 1) & (EVENT_QUEUE_SIZE - 1);
77 
78 		if ((Event.UARTStatus & 0x01) && (dev->TxEventNotify))
79 			dev->TxEventNotify(dev, Event.TimeStamp);
80 		if ((Event.UARTStatus & 0x02) && (dev->RxEventNotify))
81 			dev->RxEventNotify(dev, Event.TimeStamp,
82 					   Event.RXCharacter);
83 	}
84 }
85 
86 static void demux_tasklet(unsigned long data)
87 {
88 	struct ngene_channel *chan = (struct ngene_channel *)data;
89 	struct SBufferHeader *Cur = chan->nextBuffer;
90 
91 	spin_lock_irq(&chan->state_lock);
92 
93 	while (Cur->ngeneBuffer.SR.Flags & 0x80) {
94 		if (chan->mode & NGENE_IO_TSOUT) {
95 			u32 Flags = chan->DataFormatFlags;
96 			if (Cur->ngeneBuffer.SR.Flags & 0x20)
97 				Flags |= BEF_OVERFLOW;
98 			if (chan->pBufferExchange) {
99 				if (!chan->pBufferExchange(chan,
100 							   Cur->Buffer1,
101 							   chan->Capture1Length,
102 							   Cur->ngeneBuffer.SR.
103 							   Clock, Flags)) {
104 					/*
105 					   We didn't get data
106 					   Clear in service flag to make sure we
107 					   get called on next interrupt again.
108 					   leave fill/empty (0x80) flag alone
109 					   to avoid hardware running out of
110 					   buffers during startup, we hold only
111 					   in run state ( the source may be late
112 					   delivering data )
113 					*/
114 
115 					if (chan->HWState == HWSTATE_RUN) {
116 						Cur->ngeneBuffer.SR.Flags &=
117 							~0x40;
118 						break;
119 						/* Stop processing stream */
120 					}
121 				} else {
122 					/* We got a valid buffer,
123 					   so switch to run state */
124 					chan->HWState = HWSTATE_RUN;
125 				}
126 			} else {
127 				printk(KERN_ERR DEVICE_NAME ": OOPS\n");
128 				if (chan->HWState == HWSTATE_RUN) {
129 					Cur->ngeneBuffer.SR.Flags &= ~0x40;
130 					break;	/* Stop processing stream */
131 				}
132 			}
133 			if (chan->AudioDTOUpdated) {
134 				printk(KERN_INFO DEVICE_NAME
135 				       ": Update AudioDTO = %d\n",
136 				       chan->AudioDTOValue);
137 				Cur->ngeneBuffer.SR.DTOUpdate =
138 					chan->AudioDTOValue;
139 				chan->AudioDTOUpdated = 0;
140 			}
141 		} else {
142 			if (chan->HWState == HWSTATE_RUN) {
143 				u32 Flags = chan->DataFormatFlags;
144 				IBufferExchange *exch1 = chan->pBufferExchange;
145 				IBufferExchange *exch2 = chan->pBufferExchange2;
146 				if (Cur->ngeneBuffer.SR.Flags & 0x01)
147 					Flags |= BEF_EVEN_FIELD;
148 				if (Cur->ngeneBuffer.SR.Flags & 0x20)
149 					Flags |= BEF_OVERFLOW;
150 				spin_unlock_irq(&chan->state_lock);
151 				if (exch1)
152 					exch1(chan, Cur->Buffer1,
153 						chan->Capture1Length,
154 						Cur->ngeneBuffer.SR.Clock,
155 						Flags);
156 				if (exch2)
157 					exch2(chan, Cur->Buffer2,
158 						chan->Capture2Length,
159 						Cur->ngeneBuffer.SR.Clock,
160 						Flags);
161 				spin_lock_irq(&chan->state_lock);
162 			} else if (chan->HWState != HWSTATE_STOP)
163 				chan->HWState = HWSTATE_RUN;
164 		}
165 		Cur->ngeneBuffer.SR.Flags = 0x00;
166 		Cur = Cur->Next;
167 	}
168 	chan->nextBuffer = Cur;
169 
170 	spin_unlock_irq(&chan->state_lock);
171 }
172 
173 static irqreturn_t irq_handler(int irq, void *dev_id)
174 {
175 	struct ngene *dev = (struct ngene *)dev_id;
176 	u32 icounts = 0;
177 	irqreturn_t rc = IRQ_NONE;
178 	u32 i = MAX_STREAM;
179 	u8 *tmpCmdDoneByte;
180 
181 	if (dev->BootFirmware) {
182 		icounts = ngreadl(NGENE_INT_COUNTS);
183 		if (icounts != dev->icounts) {
184 			ngwritel(0, FORCE_NMI);
185 			dev->cmd_done = 1;
186 			wake_up(&dev->cmd_wq);
187 			dev->icounts = icounts;
188 			rc = IRQ_HANDLED;
189 		}
190 		return rc;
191 	}
192 
193 	ngwritel(0, FORCE_NMI);
194 
195 	spin_lock(&dev->cmd_lock);
196 	tmpCmdDoneByte = dev->CmdDoneByte;
197 	if (tmpCmdDoneByte &&
198 	    (*tmpCmdDoneByte ||
199 	    (dev->ngenetohost[0] == 1 && dev->ngenetohost[1] != 0))) {
200 		dev->CmdDoneByte = NULL;
201 		dev->cmd_done = 1;
202 		wake_up(&dev->cmd_wq);
203 		rc = IRQ_HANDLED;
204 	}
205 	spin_unlock(&dev->cmd_lock);
206 
207 	if (dev->EventBuffer->EventStatus & 0x80) {
208 		u8 nextWriteIndex =
209 			(dev->EventQueueWriteIndex + 1) &
210 			(EVENT_QUEUE_SIZE - 1);
211 		if (nextWriteIndex != dev->EventQueueReadIndex) {
212 			dev->EventQueue[dev->EventQueueWriteIndex] =
213 				*(dev->EventBuffer);
214 			dev->EventQueueWriteIndex = nextWriteIndex;
215 		} else {
216 			printk(KERN_ERR DEVICE_NAME ": event overflow\n");
217 			dev->EventQueueOverflowCount += 1;
218 			dev->EventQueueOverflowFlag = 1;
219 		}
220 		dev->EventBuffer->EventStatus &= ~0x80;
221 		tasklet_schedule(&dev->event_tasklet);
222 		rc = IRQ_HANDLED;
223 	}
224 
225 	while (i > 0) {
226 		i--;
227 		spin_lock(&dev->channel[i].state_lock);
228 		/* if (dev->channel[i].State>=KSSTATE_RUN) { */
229 		if (dev->channel[i].nextBuffer) {
230 			if ((dev->channel[i].nextBuffer->
231 			     ngeneBuffer.SR.Flags & 0xC0) == 0x80) {
232 				dev->channel[i].nextBuffer->
233 					ngeneBuffer.SR.Flags |= 0x40;
234 				tasklet_schedule(
235 					&dev->channel[i].demux_tasklet);
236 				rc = IRQ_HANDLED;
237 			}
238 		}
239 		spin_unlock(&dev->channel[i].state_lock);
240 	}
241 
242 	/* Request might have been processed by a previous call. */
243 	return IRQ_HANDLED;
244 }
245 
246 /****************************************************************************/
247 /* nGene command interface **************************************************/
248 /****************************************************************************/
249 
250 static void dump_command_io(struct ngene *dev)
251 {
252 	u8 buf[8], *b;
253 
254 	ngcpyfrom(buf, HOST_TO_NGENE, 8);
255 	printk(KERN_ERR "host_to_ngene (%04x): %*ph\n", HOST_TO_NGENE, 8, buf);
256 
257 	ngcpyfrom(buf, NGENE_TO_HOST, 8);
258 	printk(KERN_ERR "ngene_to_host (%04x): %*ph\n", NGENE_TO_HOST, 8, buf);
259 
260 	b = dev->hosttongene;
261 	printk(KERN_ERR "dev->hosttongene (%p): %*ph\n", b, 8, b);
262 
263 	b = dev->ngenetohost;
264 	printk(KERN_ERR "dev->ngenetohost (%p): %*ph\n", b, 8, b);
265 }
266 
267 static int ngene_command_mutex(struct ngene *dev, struct ngene_command *com)
268 {
269 	int ret;
270 	u8 *tmpCmdDoneByte;
271 
272 	dev->cmd_done = 0;
273 
274 	if (com->cmd.hdr.Opcode == CMD_FWLOAD_PREPARE) {
275 		dev->BootFirmware = 1;
276 		dev->icounts = ngreadl(NGENE_INT_COUNTS);
277 		ngwritel(0, NGENE_COMMAND);
278 		ngwritel(0, NGENE_COMMAND_HI);
279 		ngwritel(0, NGENE_STATUS);
280 		ngwritel(0, NGENE_STATUS_HI);
281 		ngwritel(0, NGENE_EVENT);
282 		ngwritel(0, NGENE_EVENT_HI);
283 	} else if (com->cmd.hdr.Opcode == CMD_FWLOAD_FINISH) {
284 		u64 fwio = dev->PAFWInterfaceBuffer;
285 
286 		ngwritel(fwio & 0xffffffff, NGENE_COMMAND);
287 		ngwritel(fwio >> 32, NGENE_COMMAND_HI);
288 		ngwritel((fwio + 256) & 0xffffffff, NGENE_STATUS);
289 		ngwritel((fwio + 256) >> 32, NGENE_STATUS_HI);
290 		ngwritel((fwio + 512) & 0xffffffff, NGENE_EVENT);
291 		ngwritel((fwio + 512) >> 32, NGENE_EVENT_HI);
292 	}
293 
294 	memcpy(dev->FWInterfaceBuffer, com->cmd.raw8, com->in_len + 2);
295 
296 	if (dev->BootFirmware)
297 		ngcpyto(HOST_TO_NGENE, com->cmd.raw8, com->in_len + 2);
298 
299 	spin_lock_irq(&dev->cmd_lock);
300 	tmpCmdDoneByte = dev->ngenetohost + com->out_len;
301 	if (!com->out_len)
302 		tmpCmdDoneByte++;
303 	*tmpCmdDoneByte = 0;
304 	dev->ngenetohost[0] = 0;
305 	dev->ngenetohost[1] = 0;
306 	dev->CmdDoneByte = tmpCmdDoneByte;
307 	spin_unlock_irq(&dev->cmd_lock);
308 
309 	/* Notify 8051. */
310 	ngwritel(1, FORCE_INT);
311 
312 	ret = wait_event_timeout(dev->cmd_wq, dev->cmd_done == 1, 2 * HZ);
313 	if (!ret) {
314 		/*ngwritel(0, FORCE_NMI);*/
315 
316 		printk(KERN_ERR DEVICE_NAME
317 		       ": Command timeout cmd=%02x prev=%02x\n",
318 		       com->cmd.hdr.Opcode, dev->prev_cmd);
319 		dump_command_io(dev);
320 		return -1;
321 	}
322 	if (com->cmd.hdr.Opcode == CMD_FWLOAD_FINISH)
323 		dev->BootFirmware = 0;
324 
325 	dev->prev_cmd = com->cmd.hdr.Opcode;
326 
327 	if (!com->out_len)
328 		return 0;
329 
330 	memcpy(com->cmd.raw8, dev->ngenetohost, com->out_len);
331 
332 	return 0;
333 }
334 
335 int ngene_command(struct ngene *dev, struct ngene_command *com)
336 {
337 	int result;
338 
339 	down(&dev->cmd_mutex);
340 	result = ngene_command_mutex(dev, com);
341 	up(&dev->cmd_mutex);
342 	return result;
343 }
344 
345 
346 static int ngene_command_load_firmware(struct ngene *dev,
347 				       u8 *ngene_fw, u32 size)
348 {
349 #define FIRSTCHUNK (1024)
350 	u32 cleft;
351 	struct ngene_command com;
352 
353 	com.cmd.hdr.Opcode = CMD_FWLOAD_PREPARE;
354 	com.cmd.hdr.Length = 0;
355 	com.in_len = 0;
356 	com.out_len = 0;
357 
358 	ngene_command(dev, &com);
359 
360 	cleft = (size + 3) & ~3;
361 	if (cleft > FIRSTCHUNK) {
362 		ngcpyto(PROGRAM_SRAM + FIRSTCHUNK, ngene_fw + FIRSTCHUNK,
363 			cleft - FIRSTCHUNK);
364 		cleft = FIRSTCHUNK;
365 	}
366 	ngcpyto(DATA_FIFO_AREA, ngene_fw, cleft);
367 
368 	memset(&com, 0, sizeof(struct ngene_command));
369 	com.cmd.hdr.Opcode = CMD_FWLOAD_FINISH;
370 	com.cmd.hdr.Length = 4;
371 	com.cmd.FWLoadFinish.Address = DATA_FIFO_AREA;
372 	com.cmd.FWLoadFinish.Length = (unsigned short)cleft;
373 	com.in_len = 4;
374 	com.out_len = 0;
375 
376 	return ngene_command(dev, &com);
377 }
378 
379 
380 static int ngene_command_config_buf(struct ngene *dev, u8 config)
381 {
382 	struct ngene_command com;
383 
384 	com.cmd.hdr.Opcode = CMD_CONFIGURE_BUFFER;
385 	com.cmd.hdr.Length = 1;
386 	com.cmd.ConfigureBuffers.config = config;
387 	com.in_len = 1;
388 	com.out_len = 0;
389 
390 	if (ngene_command(dev, &com) < 0)
391 		return -EIO;
392 	return 0;
393 }
394 
395 static int ngene_command_config_free_buf(struct ngene *dev, u8 *config)
396 {
397 	struct ngene_command com;
398 
399 	com.cmd.hdr.Opcode = CMD_CONFIGURE_FREE_BUFFER;
400 	com.cmd.hdr.Length = 6;
401 	memcpy(&com.cmd.ConfigureBuffers.config, config, 6);
402 	com.in_len = 6;
403 	com.out_len = 0;
404 
405 	if (ngene_command(dev, &com) < 0)
406 		return -EIO;
407 
408 	return 0;
409 }
410 
411 int ngene_command_gpio_set(struct ngene *dev, u8 select, u8 level)
412 {
413 	struct ngene_command com;
414 
415 	com.cmd.hdr.Opcode = CMD_SET_GPIO_PIN;
416 	com.cmd.hdr.Length = 1;
417 	com.cmd.SetGpioPin.select = select | (level << 7);
418 	com.in_len = 1;
419 	com.out_len = 0;
420 
421 	return ngene_command(dev, &com);
422 }
423 
424 
425 /*
426  02000640 is sample on rising edge.
427  02000740 is sample on falling edge.
428  02000040 is ignore "valid" signal
429 
430  0: FD_CTL1 Bit 7,6 must be 0,1
431     7   disable(fw controlled)
432     6   0-AUX,1-TS
433     5   0-par,1-ser
434     4   0-lsb/1-msb
435     3,2 reserved
436     1,0 0-no sync, 1-use ext. start, 2-use 0x47, 3-both
437  1: FD_CTL2 has 3-valid must be hi, 2-use valid, 1-edge
438  2: FD_STA is read-only. 0-sync
439  3: FD_INSYNC is number of 47s to trigger "in sync".
440  4: FD_OUTSYNC is number of 47s to trigger "out of sync".
441  5: FD_MAXBYTE1 is low-order of bytes per packet.
442  6: FD_MAXBYTE2 is high-order of bytes per packet.
443  7: Top byte is unused.
444 */
445 
446 /****************************************************************************/
447 
448 static u8 TSFeatureDecoderSetup[8 * 5] = {
449 	0x42, 0x00, 0x00, 0x02, 0x02, 0xbc, 0x00, 0x00,
450 	0x40, 0x06, 0x00, 0x02, 0x02, 0xbc, 0x00, 0x00,	/* DRXH */
451 	0x71, 0x07, 0x00, 0x02, 0x02, 0xbc, 0x00, 0x00,	/* DRXHser */
452 	0x72, 0x00, 0x00, 0x02, 0x02, 0xbc, 0x00, 0x00,	/* S2ser */
453 	0x40, 0x07, 0x00, 0x02, 0x02, 0xbc, 0x00, 0x00, /* LGDT3303 */
454 };
455 
456 /* Set NGENE I2S Config to 16 bit packed */
457 static u8 I2SConfiguration[] = {
458 	0x00, 0x10, 0x00, 0x00,
459 	0x80, 0x10, 0x00, 0x00,
460 };
461 
462 static u8 SPDIFConfiguration[10] = {
463 	0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00
464 };
465 
466 /* Set NGENE I2S Config to transport stream compatible mode */
467 
468 static u8 TS_I2SConfiguration[4] = { 0x3E, 0x18, 0x00, 0x00 };
469 
470 static u8 TS_I2SOutConfiguration[4] = { 0x80, 0x04, 0x00, 0x00 };
471 
472 static u8 ITUDecoderSetup[4][16] = {
473 	{0x1c, 0x13, 0x01, 0x68, 0x3d, 0x90, 0x14, 0x20,  /* SDTV */
474 	 0x00, 0x00, 0x01, 0xb0, 0x9c, 0x00, 0x00, 0x00},
475 	{0x9c, 0x03, 0x23, 0xC0, 0x60, 0x0E, 0x13, 0x00,
476 	 0x00, 0x00, 0x00, 0x01, 0xB0, 0x00, 0x00, 0x00},
477 	{0x9f, 0x00, 0x23, 0xC0, 0x60, 0x0F, 0x13, 0x00,  /* HDTV 1080i50 */
478 	 0x00, 0x00, 0x00, 0x01, 0xB0, 0x00, 0x00, 0x00},
479 	{0x9c, 0x01, 0x23, 0xC0, 0x60, 0x0E, 0x13, 0x00,  /* HDTV 1080i60 */
480 	 0x00, 0x00, 0x00, 0x01, 0xB0, 0x00, 0x00, 0x00},
481 };
482 
483 /*
484  * 50 48 60 gleich
485  * 27p50 9f 00 22 80 42 69 18 ...
486  * 27p60 93 00 22 80 82 69 1c ...
487  */
488 
489 /* Maxbyte to 1144 (for raw data) */
490 static u8 ITUFeatureDecoderSetup[8] = {
491 	0x00, 0x00, 0x00, 0x00, 0x00, 0x78, 0x04, 0x00
492 };
493 
494 void FillTSBuffer(void *Buffer, int Length, u32 Flags)
495 {
496 	u32 *ptr = Buffer;
497 
498 	memset(Buffer, TS_FILLER, Length);
499 	while (Length > 0) {
500 		if (Flags & DF_SWAP32)
501 			*ptr = 0x471FFF10;
502 		else
503 			*ptr = 0x10FF1F47;
504 		ptr += (188 / 4);
505 		Length -= 188;
506 	}
507 }
508 
509 
510 static void flush_buffers(struct ngene_channel *chan)
511 {
512 	u8 val;
513 
514 	do {
515 		msleep(1);
516 		spin_lock_irq(&chan->state_lock);
517 		val = chan->nextBuffer->ngeneBuffer.SR.Flags & 0x80;
518 		spin_unlock_irq(&chan->state_lock);
519 	} while (val);
520 }
521 
522 static void clear_buffers(struct ngene_channel *chan)
523 {
524 	struct SBufferHeader *Cur = chan->nextBuffer;
525 
526 	do {
527 		memset(&Cur->ngeneBuffer.SR, 0, sizeof(Cur->ngeneBuffer.SR));
528 		if (chan->mode & NGENE_IO_TSOUT)
529 			FillTSBuffer(Cur->Buffer1,
530 				     chan->Capture1Length,
531 				     chan->DataFormatFlags);
532 		Cur = Cur->Next;
533 	} while (Cur != chan->nextBuffer);
534 
535 	if (chan->mode & NGENE_IO_TSOUT) {
536 		chan->nextBuffer->ngeneBuffer.SR.DTOUpdate =
537 			chan->AudioDTOValue;
538 		chan->AudioDTOUpdated = 0;
539 
540 		Cur = chan->TSIdleBuffer.Head;
541 
542 		do {
543 			memset(&Cur->ngeneBuffer.SR, 0,
544 			       sizeof(Cur->ngeneBuffer.SR));
545 			FillTSBuffer(Cur->Buffer1,
546 				     chan->Capture1Length,
547 				     chan->DataFormatFlags);
548 			Cur = Cur->Next;
549 		} while (Cur != chan->TSIdleBuffer.Head);
550 	}
551 }
552 
553 static int ngene_command_stream_control(struct ngene *dev, u8 stream,
554 					u8 control, u8 mode, u8 flags)
555 {
556 	struct ngene_channel *chan = &dev->channel[stream];
557 	struct ngene_command com;
558 	u16 BsUVI = ((stream & 1) ? 0x9400 : 0x9300);
559 	u16 BsSDI = ((stream & 1) ? 0x9600 : 0x9500);
560 	u16 BsSPI = ((stream & 1) ? 0x9800 : 0x9700);
561 	u16 BsSDO = 0x9B00;
562 
563 	down(&dev->stream_mutex);
564 	memset(&com, 0, sizeof(com));
565 	com.cmd.hdr.Opcode = CMD_CONTROL;
566 	com.cmd.hdr.Length = sizeof(struct FW_STREAM_CONTROL) - 2;
567 	com.cmd.StreamControl.Stream = stream | (control ? 8 : 0);
568 	if (chan->mode & NGENE_IO_TSOUT)
569 		com.cmd.StreamControl.Stream |= 0x07;
570 	com.cmd.StreamControl.Control = control |
571 		(flags & SFLAG_ORDER_LUMA_CHROMA);
572 	com.cmd.StreamControl.Mode = mode;
573 	com.in_len = sizeof(struct FW_STREAM_CONTROL);
574 	com.out_len = 0;
575 
576 	dprintk(KERN_INFO DEVICE_NAME
577 		": Stream=%02x, Control=%02x, Mode=%02x\n",
578 		com.cmd.StreamControl.Stream, com.cmd.StreamControl.Control,
579 		com.cmd.StreamControl.Mode);
580 
581 	chan->Mode = mode;
582 
583 	if (!(control & 0x80)) {
584 		spin_lock_irq(&chan->state_lock);
585 		if (chan->State == KSSTATE_RUN) {
586 			chan->State = KSSTATE_ACQUIRE;
587 			chan->HWState = HWSTATE_STOP;
588 			spin_unlock_irq(&chan->state_lock);
589 			if (ngene_command(dev, &com) < 0) {
590 				up(&dev->stream_mutex);
591 				return -1;
592 			}
593 			/* clear_buffers(chan); */
594 			flush_buffers(chan);
595 			up(&dev->stream_mutex);
596 			return 0;
597 		}
598 		spin_unlock_irq(&chan->state_lock);
599 		up(&dev->stream_mutex);
600 		return 0;
601 	}
602 
603 	if (mode & SMODE_AUDIO_CAPTURE) {
604 		com.cmd.StreamControl.CaptureBlockCount =
605 			chan->Capture1Length / AUDIO_BLOCK_SIZE;
606 		com.cmd.StreamControl.Buffer_Address = chan->RingBuffer.PAHead;
607 	} else if (mode & SMODE_TRANSPORT_STREAM) {
608 		com.cmd.StreamControl.CaptureBlockCount =
609 			chan->Capture1Length / TS_BLOCK_SIZE;
610 		com.cmd.StreamControl.MaxLinesPerField =
611 			chan->Capture1Length / TS_BLOCK_SIZE;
612 		com.cmd.StreamControl.Buffer_Address =
613 			chan->TSRingBuffer.PAHead;
614 		if (chan->mode & NGENE_IO_TSOUT) {
615 			com.cmd.StreamControl.BytesPerVBILine =
616 				chan->Capture1Length / TS_BLOCK_SIZE;
617 			com.cmd.StreamControl.Stream |= 0x07;
618 		}
619 	} else {
620 		com.cmd.StreamControl.BytesPerVideoLine = chan->nBytesPerLine;
621 		com.cmd.StreamControl.MaxLinesPerField = chan->nLines;
622 		com.cmd.StreamControl.MinLinesPerField = 100;
623 		com.cmd.StreamControl.Buffer_Address = chan->RingBuffer.PAHead;
624 
625 		if (mode & SMODE_VBI_CAPTURE) {
626 			com.cmd.StreamControl.MaxVBILinesPerField =
627 				chan->nVBILines;
628 			com.cmd.StreamControl.MinVBILinesPerField = 0;
629 			com.cmd.StreamControl.BytesPerVBILine =
630 				chan->nBytesPerVBILine;
631 		}
632 		if (flags & SFLAG_COLORBAR)
633 			com.cmd.StreamControl.Stream |= 0x04;
634 	}
635 
636 	spin_lock_irq(&chan->state_lock);
637 	if (mode & SMODE_AUDIO_CAPTURE) {
638 		chan->nextBuffer = chan->RingBuffer.Head;
639 		if (mode & SMODE_AUDIO_SPDIF) {
640 			com.cmd.StreamControl.SetupDataLen =
641 				sizeof(SPDIFConfiguration);
642 			com.cmd.StreamControl.SetupDataAddr = BsSPI;
643 			memcpy(com.cmd.StreamControl.SetupData,
644 			       SPDIFConfiguration, sizeof(SPDIFConfiguration));
645 		} else {
646 			com.cmd.StreamControl.SetupDataLen = 4;
647 			com.cmd.StreamControl.SetupDataAddr = BsSDI;
648 			memcpy(com.cmd.StreamControl.SetupData,
649 			       I2SConfiguration +
650 			       4 * dev->card_info->i2s[stream], 4);
651 		}
652 	} else if (mode & SMODE_TRANSPORT_STREAM) {
653 		chan->nextBuffer = chan->TSRingBuffer.Head;
654 		if (stream >= STREAM_AUDIOIN1) {
655 			if (chan->mode & NGENE_IO_TSOUT) {
656 				com.cmd.StreamControl.SetupDataLen =
657 					sizeof(TS_I2SOutConfiguration);
658 				com.cmd.StreamControl.SetupDataAddr = BsSDO;
659 				memcpy(com.cmd.StreamControl.SetupData,
660 				       TS_I2SOutConfiguration,
661 				       sizeof(TS_I2SOutConfiguration));
662 			} else {
663 				com.cmd.StreamControl.SetupDataLen =
664 					sizeof(TS_I2SConfiguration);
665 				com.cmd.StreamControl.SetupDataAddr = BsSDI;
666 				memcpy(com.cmd.StreamControl.SetupData,
667 				       TS_I2SConfiguration,
668 				       sizeof(TS_I2SConfiguration));
669 			}
670 		} else {
671 			com.cmd.StreamControl.SetupDataLen = 8;
672 			com.cmd.StreamControl.SetupDataAddr = BsUVI + 0x10;
673 			memcpy(com.cmd.StreamControl.SetupData,
674 			       TSFeatureDecoderSetup +
675 			       8 * dev->card_info->tsf[stream], 8);
676 		}
677 	} else {
678 		chan->nextBuffer = chan->RingBuffer.Head;
679 		com.cmd.StreamControl.SetupDataLen =
680 			16 + sizeof(ITUFeatureDecoderSetup);
681 		com.cmd.StreamControl.SetupDataAddr = BsUVI;
682 		memcpy(com.cmd.StreamControl.SetupData,
683 		       ITUDecoderSetup[chan->itumode], 16);
684 		memcpy(com.cmd.StreamControl.SetupData + 16,
685 		       ITUFeatureDecoderSetup, sizeof(ITUFeatureDecoderSetup));
686 	}
687 	clear_buffers(chan);
688 	chan->State = KSSTATE_RUN;
689 	if (mode & SMODE_TRANSPORT_STREAM)
690 		chan->HWState = HWSTATE_RUN;
691 	else
692 		chan->HWState = HWSTATE_STARTUP;
693 	spin_unlock_irq(&chan->state_lock);
694 
695 	if (ngene_command(dev, &com) < 0) {
696 		up(&dev->stream_mutex);
697 		return -1;
698 	}
699 	up(&dev->stream_mutex);
700 	return 0;
701 }
702 
703 void set_transfer(struct ngene_channel *chan, int state)
704 {
705 	u8 control = 0, mode = 0, flags = 0;
706 	struct ngene *dev = chan->dev;
707 	int ret;
708 
709 	/*
710 	printk(KERN_INFO DEVICE_NAME ": st %d\n", state);
711 	msleep(100);
712 	*/
713 
714 	if (state) {
715 		if (chan->running) {
716 			printk(KERN_INFO DEVICE_NAME ": already running\n");
717 			return;
718 		}
719 	} else {
720 		if (!chan->running) {
721 			printk(KERN_INFO DEVICE_NAME ": already stopped\n");
722 			return;
723 		}
724 	}
725 
726 	if (dev->card_info->switch_ctrl)
727 		dev->card_info->switch_ctrl(chan, 1, state ^ 1);
728 
729 	if (state) {
730 		spin_lock_irq(&chan->state_lock);
731 
732 		/* printk(KERN_INFO DEVICE_NAME ": lock=%08x\n",
733 			  ngreadl(0x9310)); */
734 		dvb_ringbuffer_flush(&dev->tsout_rbuf);
735 		control = 0x80;
736 		if (chan->mode & (NGENE_IO_TSIN | NGENE_IO_TSOUT)) {
737 			chan->Capture1Length = 512 * 188;
738 			mode = SMODE_TRANSPORT_STREAM;
739 		}
740 		if (chan->mode & NGENE_IO_TSOUT) {
741 			chan->pBufferExchange = tsout_exchange;
742 			/* 0x66666666 = 50MHz *2^33 /250MHz */
743 			chan->AudioDTOValue = 0x80000000;
744 			chan->AudioDTOUpdated = 1;
745 		}
746 		if (chan->mode & NGENE_IO_TSIN)
747 			chan->pBufferExchange = tsin_exchange;
748 		spin_unlock_irq(&chan->state_lock);
749 	}
750 		/* else printk(KERN_INFO DEVICE_NAME ": lock=%08x\n",
751 			   ngreadl(0x9310)); */
752 
753 	ret = ngene_command_stream_control(dev, chan->number,
754 					   control, mode, flags);
755 	if (!ret)
756 		chan->running = state;
757 	else
758 		printk(KERN_ERR DEVICE_NAME ": set_transfer %d failed\n",
759 		       state);
760 	if (!state) {
761 		spin_lock_irq(&chan->state_lock);
762 		chan->pBufferExchange = NULL;
763 		dvb_ringbuffer_flush(&dev->tsout_rbuf);
764 		spin_unlock_irq(&chan->state_lock);
765 	}
766 }
767 
768 
769 /****************************************************************************/
770 /* nGene hardware init and release functions ********************************/
771 /****************************************************************************/
772 
773 static void free_ringbuffer(struct ngene *dev, struct SRingBufferDescriptor *rb)
774 {
775 	struct SBufferHeader *Cur = rb->Head;
776 	u32 j;
777 
778 	if (!Cur)
779 		return;
780 
781 	for (j = 0; j < rb->NumBuffers; j++, Cur = Cur->Next) {
782 		if (Cur->Buffer1)
783 			pci_free_consistent(dev->pci_dev,
784 					    rb->Buffer1Length,
785 					    Cur->Buffer1,
786 					    Cur->scList1->Address);
787 
788 		if (Cur->Buffer2)
789 			pci_free_consistent(dev->pci_dev,
790 					    rb->Buffer2Length,
791 					    Cur->Buffer2,
792 					    Cur->scList2->Address);
793 	}
794 
795 	if (rb->SCListMem)
796 		pci_free_consistent(dev->pci_dev, rb->SCListMemSize,
797 				    rb->SCListMem, rb->PASCListMem);
798 
799 	pci_free_consistent(dev->pci_dev, rb->MemSize, rb->Head, rb->PAHead);
800 }
801 
802 static void free_idlebuffer(struct ngene *dev,
803 		     struct SRingBufferDescriptor *rb,
804 		     struct SRingBufferDescriptor *tb)
805 {
806 	int j;
807 	struct SBufferHeader *Cur = tb->Head;
808 
809 	if (!rb->Head)
810 		return;
811 	free_ringbuffer(dev, rb);
812 	for (j = 0; j < tb->NumBuffers; j++, Cur = Cur->Next) {
813 		Cur->Buffer2 = NULL;
814 		Cur->scList2 = NULL;
815 		Cur->ngeneBuffer.Address_of_first_entry_2 = 0;
816 		Cur->ngeneBuffer.Number_of_entries_2 = 0;
817 	}
818 }
819 
820 static void free_common_buffers(struct ngene *dev)
821 {
822 	u32 i;
823 	struct ngene_channel *chan;
824 
825 	for (i = STREAM_VIDEOIN1; i < MAX_STREAM; i++) {
826 		chan = &dev->channel[i];
827 		free_idlebuffer(dev, &chan->TSIdleBuffer, &chan->TSRingBuffer);
828 		free_ringbuffer(dev, &chan->RingBuffer);
829 		free_ringbuffer(dev, &chan->TSRingBuffer);
830 	}
831 
832 	if (dev->OverflowBuffer)
833 		pci_free_consistent(dev->pci_dev,
834 				    OVERFLOW_BUFFER_SIZE,
835 				    dev->OverflowBuffer, dev->PAOverflowBuffer);
836 
837 	if (dev->FWInterfaceBuffer)
838 		pci_free_consistent(dev->pci_dev,
839 				    4096,
840 				    dev->FWInterfaceBuffer,
841 				    dev->PAFWInterfaceBuffer);
842 }
843 
844 /****************************************************************************/
845 /* Ring buffer handling *****************************************************/
846 /****************************************************************************/
847 
848 static int create_ring_buffer(struct pci_dev *pci_dev,
849 		       struct SRingBufferDescriptor *descr, u32 NumBuffers)
850 {
851 	dma_addr_t tmp;
852 	struct SBufferHeader *Head;
853 	u32 i;
854 	u32 MemSize = SIZEOF_SBufferHeader * NumBuffers;
855 	u64 PARingBufferHead;
856 	u64 PARingBufferCur;
857 	u64 PARingBufferNext;
858 	struct SBufferHeader *Cur, *Next;
859 
860 	descr->Head = NULL;
861 	descr->MemSize = 0;
862 	descr->PAHead = 0;
863 	descr->NumBuffers = 0;
864 
865 	if (MemSize < 4096)
866 		MemSize = 4096;
867 
868 	Head = pci_alloc_consistent(pci_dev, MemSize, &tmp);
869 	PARingBufferHead = tmp;
870 
871 	if (!Head)
872 		return -ENOMEM;
873 
874 	memset(Head, 0, MemSize);
875 
876 	PARingBufferCur = PARingBufferHead;
877 	Cur = Head;
878 
879 	for (i = 0; i < NumBuffers - 1; i++) {
880 		Next = (struct SBufferHeader *)
881 			(((u8 *) Cur) + SIZEOF_SBufferHeader);
882 		PARingBufferNext = PARingBufferCur + SIZEOF_SBufferHeader;
883 		Cur->Next = Next;
884 		Cur->ngeneBuffer.Next = PARingBufferNext;
885 		Cur = Next;
886 		PARingBufferCur = PARingBufferNext;
887 	}
888 	/* Last Buffer points back to first one */
889 	Cur->Next = Head;
890 	Cur->ngeneBuffer.Next = PARingBufferHead;
891 
892 	descr->Head       = Head;
893 	descr->MemSize    = MemSize;
894 	descr->PAHead     = PARingBufferHead;
895 	descr->NumBuffers = NumBuffers;
896 
897 	return 0;
898 }
899 
900 static int AllocateRingBuffers(struct pci_dev *pci_dev,
901 			       dma_addr_t of,
902 			       struct SRingBufferDescriptor *pRingBuffer,
903 			       u32 Buffer1Length, u32 Buffer2Length)
904 {
905 	dma_addr_t tmp;
906 	u32 i, j;
907 	u32 SCListMemSize = pRingBuffer->NumBuffers
908 		* ((Buffer2Length != 0) ? (NUM_SCATTER_GATHER_ENTRIES * 2) :
909 		    NUM_SCATTER_GATHER_ENTRIES)
910 		* sizeof(struct HW_SCATTER_GATHER_ELEMENT);
911 
912 	u64 PASCListMem;
913 	struct HW_SCATTER_GATHER_ELEMENT *SCListEntry;
914 	u64 PASCListEntry;
915 	struct SBufferHeader *Cur;
916 	void *SCListMem;
917 
918 	if (SCListMemSize < 4096)
919 		SCListMemSize = 4096;
920 
921 	SCListMem = pci_alloc_consistent(pci_dev, SCListMemSize, &tmp);
922 
923 	PASCListMem = tmp;
924 	if (SCListMem == NULL)
925 		return -ENOMEM;
926 
927 	memset(SCListMem, 0, SCListMemSize);
928 
929 	pRingBuffer->SCListMem = SCListMem;
930 	pRingBuffer->PASCListMem = PASCListMem;
931 	pRingBuffer->SCListMemSize = SCListMemSize;
932 	pRingBuffer->Buffer1Length = Buffer1Length;
933 	pRingBuffer->Buffer2Length = Buffer2Length;
934 
935 	SCListEntry = SCListMem;
936 	PASCListEntry = PASCListMem;
937 	Cur = pRingBuffer->Head;
938 
939 	for (i = 0; i < pRingBuffer->NumBuffers; i += 1, Cur = Cur->Next) {
940 		u64 PABuffer;
941 
942 		void *Buffer = pci_alloc_consistent(pci_dev, Buffer1Length,
943 						    &tmp);
944 		PABuffer = tmp;
945 
946 		if (Buffer == NULL)
947 			return -ENOMEM;
948 
949 		Cur->Buffer1 = Buffer;
950 
951 		SCListEntry->Address = PABuffer;
952 		SCListEntry->Length  = Buffer1Length;
953 
954 		Cur->scList1 = SCListEntry;
955 		Cur->ngeneBuffer.Address_of_first_entry_1 = PASCListEntry;
956 		Cur->ngeneBuffer.Number_of_entries_1 =
957 			NUM_SCATTER_GATHER_ENTRIES;
958 
959 		SCListEntry += 1;
960 		PASCListEntry += sizeof(struct HW_SCATTER_GATHER_ELEMENT);
961 
962 #if NUM_SCATTER_GATHER_ENTRIES > 1
963 		for (j = 0; j < NUM_SCATTER_GATHER_ENTRIES - 1; j += 1) {
964 			SCListEntry->Address = of;
965 			SCListEntry->Length = OVERFLOW_BUFFER_SIZE;
966 			SCListEntry += 1;
967 			PASCListEntry +=
968 				sizeof(struct HW_SCATTER_GATHER_ELEMENT);
969 		}
970 #endif
971 
972 		if (!Buffer2Length)
973 			continue;
974 
975 		Buffer = pci_alloc_consistent(pci_dev, Buffer2Length, &tmp);
976 		PABuffer = tmp;
977 
978 		if (Buffer == NULL)
979 			return -ENOMEM;
980 
981 		Cur->Buffer2 = Buffer;
982 
983 		SCListEntry->Address = PABuffer;
984 		SCListEntry->Length  = Buffer2Length;
985 
986 		Cur->scList2 = SCListEntry;
987 		Cur->ngeneBuffer.Address_of_first_entry_2 = PASCListEntry;
988 		Cur->ngeneBuffer.Number_of_entries_2 =
989 			NUM_SCATTER_GATHER_ENTRIES;
990 
991 		SCListEntry   += 1;
992 		PASCListEntry += sizeof(struct HW_SCATTER_GATHER_ELEMENT);
993 
994 #if NUM_SCATTER_GATHER_ENTRIES > 1
995 		for (j = 0; j < NUM_SCATTER_GATHER_ENTRIES - 1; j++) {
996 			SCListEntry->Address = of;
997 			SCListEntry->Length = OVERFLOW_BUFFER_SIZE;
998 			SCListEntry += 1;
999 			PASCListEntry +=
1000 				sizeof(struct HW_SCATTER_GATHER_ELEMENT);
1001 		}
1002 #endif
1003 
1004 	}
1005 
1006 	return 0;
1007 }
1008 
1009 static int FillTSIdleBuffer(struct SRingBufferDescriptor *pIdleBuffer,
1010 			    struct SRingBufferDescriptor *pRingBuffer)
1011 {
1012 	/* Copy pointer to scatter gather list in TSRingbuffer
1013 	   structure for buffer 2
1014 	   Load number of buffer
1015 	*/
1016 	u32 n = pRingBuffer->NumBuffers;
1017 
1018 	/* Point to first buffer entry */
1019 	struct SBufferHeader *Cur = pRingBuffer->Head;
1020 	int i;
1021 	/* Loop thru all buffer and set Buffer 2 pointers to TSIdlebuffer */
1022 	for (i = 0; i < n; i++) {
1023 		Cur->Buffer2 = pIdleBuffer->Head->Buffer1;
1024 		Cur->scList2 = pIdleBuffer->Head->scList1;
1025 		Cur->ngeneBuffer.Address_of_first_entry_2 =
1026 			pIdleBuffer->Head->ngeneBuffer.
1027 			Address_of_first_entry_1;
1028 		Cur->ngeneBuffer.Number_of_entries_2 =
1029 			pIdleBuffer->Head->ngeneBuffer.Number_of_entries_1;
1030 		Cur = Cur->Next;
1031 	}
1032 	return 0;
1033 }
1034 
1035 static u32 RingBufferSizes[MAX_STREAM] = {
1036 	RING_SIZE_VIDEO,
1037 	RING_SIZE_VIDEO,
1038 	RING_SIZE_AUDIO,
1039 	RING_SIZE_AUDIO,
1040 	RING_SIZE_AUDIO,
1041 };
1042 
1043 static u32 Buffer1Sizes[MAX_STREAM] = {
1044 	MAX_VIDEO_BUFFER_SIZE,
1045 	MAX_VIDEO_BUFFER_SIZE,
1046 	MAX_AUDIO_BUFFER_SIZE,
1047 	MAX_AUDIO_BUFFER_SIZE,
1048 	MAX_AUDIO_BUFFER_SIZE
1049 };
1050 
1051 static u32 Buffer2Sizes[MAX_STREAM] = {
1052 	MAX_VBI_BUFFER_SIZE,
1053 	MAX_VBI_BUFFER_SIZE,
1054 	0,
1055 	0,
1056 	0
1057 };
1058 
1059 
1060 static int AllocCommonBuffers(struct ngene *dev)
1061 {
1062 	int status = 0, i;
1063 
1064 	dev->FWInterfaceBuffer = pci_alloc_consistent(dev->pci_dev, 4096,
1065 						     &dev->PAFWInterfaceBuffer);
1066 	if (!dev->FWInterfaceBuffer)
1067 		return -ENOMEM;
1068 	dev->hosttongene = dev->FWInterfaceBuffer;
1069 	dev->ngenetohost = dev->FWInterfaceBuffer + 256;
1070 	dev->EventBuffer = dev->FWInterfaceBuffer + 512;
1071 
1072 	dev->OverflowBuffer = pci_zalloc_consistent(dev->pci_dev,
1073 						    OVERFLOW_BUFFER_SIZE,
1074 						    &dev->PAOverflowBuffer);
1075 	if (!dev->OverflowBuffer)
1076 		return -ENOMEM;
1077 
1078 	for (i = STREAM_VIDEOIN1; i < MAX_STREAM; i++) {
1079 		int type = dev->card_info->io_type[i];
1080 
1081 		dev->channel[i].State = KSSTATE_STOP;
1082 
1083 		if (type & (NGENE_IO_TV | NGENE_IO_HDTV | NGENE_IO_AIN)) {
1084 			status = create_ring_buffer(dev->pci_dev,
1085 						    &dev->channel[i].RingBuffer,
1086 						    RingBufferSizes[i]);
1087 			if (status < 0)
1088 				break;
1089 
1090 			if (type & (NGENE_IO_TV | NGENE_IO_AIN)) {
1091 				status = AllocateRingBuffers(dev->pci_dev,
1092 							     dev->
1093 							     PAOverflowBuffer,
1094 							     &dev->channel[i].
1095 							     RingBuffer,
1096 							     Buffer1Sizes[i],
1097 							     Buffer2Sizes[i]);
1098 				if (status < 0)
1099 					break;
1100 			} else if (type & NGENE_IO_HDTV) {
1101 				status = AllocateRingBuffers(dev->pci_dev,
1102 							     dev->
1103 							     PAOverflowBuffer,
1104 							     &dev->channel[i].
1105 							     RingBuffer,
1106 							   MAX_HDTV_BUFFER_SIZE,
1107 							     0);
1108 				if (status < 0)
1109 					break;
1110 			}
1111 		}
1112 
1113 		if (type & (NGENE_IO_TSIN | NGENE_IO_TSOUT)) {
1114 
1115 			status = create_ring_buffer(dev->pci_dev,
1116 						    &dev->channel[i].
1117 						    TSRingBuffer, RING_SIZE_TS);
1118 			if (status < 0)
1119 				break;
1120 
1121 			status = AllocateRingBuffers(dev->pci_dev,
1122 						     dev->PAOverflowBuffer,
1123 						     &dev->channel[i].
1124 						     TSRingBuffer,
1125 						     MAX_TS_BUFFER_SIZE, 0);
1126 			if (status)
1127 				break;
1128 		}
1129 
1130 		if (type & NGENE_IO_TSOUT) {
1131 			status = create_ring_buffer(dev->pci_dev,
1132 						    &dev->channel[i].
1133 						    TSIdleBuffer, 1);
1134 			if (status < 0)
1135 				break;
1136 			status = AllocateRingBuffers(dev->pci_dev,
1137 						     dev->PAOverflowBuffer,
1138 						     &dev->channel[i].
1139 						     TSIdleBuffer,
1140 						     MAX_TS_BUFFER_SIZE, 0);
1141 			if (status)
1142 				break;
1143 			FillTSIdleBuffer(&dev->channel[i].TSIdleBuffer,
1144 					 &dev->channel[i].TSRingBuffer);
1145 		}
1146 	}
1147 	return status;
1148 }
1149 
1150 static void ngene_release_buffers(struct ngene *dev)
1151 {
1152 	if (dev->iomem)
1153 		iounmap(dev->iomem);
1154 	free_common_buffers(dev);
1155 	vfree(dev->tsout_buf);
1156 	vfree(dev->tsin_buf);
1157 	vfree(dev->ain_buf);
1158 	vfree(dev->vin_buf);
1159 	vfree(dev);
1160 }
1161 
1162 static int ngene_get_buffers(struct ngene *dev)
1163 {
1164 	if (AllocCommonBuffers(dev))
1165 		return -ENOMEM;
1166 	if (dev->card_info->io_type[4] & NGENE_IO_TSOUT) {
1167 		dev->tsout_buf = vmalloc(TSOUT_BUF_SIZE);
1168 		if (!dev->tsout_buf)
1169 			return -ENOMEM;
1170 		dvb_ringbuffer_init(&dev->tsout_rbuf,
1171 				    dev->tsout_buf, TSOUT_BUF_SIZE);
1172 	}
1173 	if (dev->card_info->io_type[2]&NGENE_IO_TSIN) {
1174 		dev->tsin_buf = vmalloc(TSIN_BUF_SIZE);
1175 		if (!dev->tsin_buf)
1176 			return -ENOMEM;
1177 		dvb_ringbuffer_init(&dev->tsin_rbuf,
1178 				    dev->tsin_buf, TSIN_BUF_SIZE);
1179 	}
1180 	if (dev->card_info->io_type[2] & NGENE_IO_AIN) {
1181 		dev->ain_buf = vmalloc(AIN_BUF_SIZE);
1182 		if (!dev->ain_buf)
1183 			return -ENOMEM;
1184 		dvb_ringbuffer_init(&dev->ain_rbuf, dev->ain_buf, AIN_BUF_SIZE);
1185 	}
1186 	if (dev->card_info->io_type[0] & NGENE_IO_HDTV) {
1187 		dev->vin_buf = vmalloc(VIN_BUF_SIZE);
1188 		if (!dev->vin_buf)
1189 			return -ENOMEM;
1190 		dvb_ringbuffer_init(&dev->vin_rbuf, dev->vin_buf, VIN_BUF_SIZE);
1191 	}
1192 	dev->iomem = ioremap(pci_resource_start(dev->pci_dev, 0),
1193 			     pci_resource_len(dev->pci_dev, 0));
1194 	if (!dev->iomem)
1195 		return -ENOMEM;
1196 
1197 	return 0;
1198 }
1199 
1200 static void ngene_init(struct ngene *dev)
1201 {
1202 	int i;
1203 
1204 	tasklet_init(&dev->event_tasklet, event_tasklet, (unsigned long)dev);
1205 
1206 	memset_io(dev->iomem + 0xc000, 0x00, 0x220);
1207 	memset_io(dev->iomem + 0xc400, 0x00, 0x100);
1208 
1209 	for (i = 0; i < MAX_STREAM; i++) {
1210 		dev->channel[i].dev = dev;
1211 		dev->channel[i].number = i;
1212 	}
1213 
1214 	dev->fw_interface_version = 0;
1215 
1216 	ngwritel(0, NGENE_INT_ENABLE);
1217 
1218 	dev->icounts = ngreadl(NGENE_INT_COUNTS);
1219 
1220 	dev->device_version = ngreadl(DEV_VER) & 0x0f;
1221 	printk(KERN_INFO DEVICE_NAME ": Device version %d\n",
1222 	       dev->device_version);
1223 }
1224 
1225 static int ngene_load_firm(struct ngene *dev)
1226 {
1227 	u32 size;
1228 	const struct firmware *fw = NULL;
1229 	u8 *ngene_fw;
1230 	char *fw_name;
1231 	int err, version;
1232 
1233 	version = dev->card_info->fw_version;
1234 
1235 	switch (version) {
1236 	default:
1237 	case 15:
1238 		version = 15;
1239 		size = 23466;
1240 		fw_name = "ngene_15.fw";
1241 		dev->cmd_timeout_workaround = true;
1242 		break;
1243 	case 16:
1244 		size = 23498;
1245 		fw_name = "ngene_16.fw";
1246 		dev->cmd_timeout_workaround = true;
1247 		break;
1248 	case 17:
1249 		size = 24446;
1250 		fw_name = "ngene_17.fw";
1251 		dev->cmd_timeout_workaround = true;
1252 		break;
1253 	case 18:
1254 		size = 0;
1255 		fw_name = "ngene_18.fw";
1256 		break;
1257 	}
1258 
1259 	if (request_firmware(&fw, fw_name, &dev->pci_dev->dev) < 0) {
1260 		printk(KERN_ERR DEVICE_NAME
1261 			": Could not load firmware file %s.\n", fw_name);
1262 		printk(KERN_INFO DEVICE_NAME
1263 			": Copy %s to your hotplug directory!\n", fw_name);
1264 		return -1;
1265 	}
1266 	if (size == 0)
1267 		size = fw->size;
1268 	if (size != fw->size) {
1269 		printk(KERN_ERR DEVICE_NAME
1270 			": Firmware %s has invalid size!", fw_name);
1271 		err = -1;
1272 	} else {
1273 		printk(KERN_INFO DEVICE_NAME
1274 			": Loading firmware file %s.\n", fw_name);
1275 		ngene_fw = (u8 *) fw->data;
1276 		err = ngene_command_load_firmware(dev, ngene_fw, size);
1277 	}
1278 
1279 	release_firmware(fw);
1280 
1281 	return err;
1282 }
1283 
1284 static void ngene_stop(struct ngene *dev)
1285 {
1286 	down(&dev->cmd_mutex);
1287 	i2c_del_adapter(&(dev->channel[0].i2c_adapter));
1288 	i2c_del_adapter(&(dev->channel[1].i2c_adapter));
1289 	ngwritel(0, NGENE_INT_ENABLE);
1290 	ngwritel(0, NGENE_COMMAND);
1291 	ngwritel(0, NGENE_COMMAND_HI);
1292 	ngwritel(0, NGENE_STATUS);
1293 	ngwritel(0, NGENE_STATUS_HI);
1294 	ngwritel(0, NGENE_EVENT);
1295 	ngwritel(0, NGENE_EVENT_HI);
1296 	free_irq(dev->pci_dev->irq, dev);
1297 #ifdef CONFIG_PCI_MSI
1298 	if (dev->msi_enabled)
1299 		pci_disable_msi(dev->pci_dev);
1300 #endif
1301 }
1302 
1303 static int ngene_buffer_config(struct ngene *dev)
1304 {
1305 	int stat;
1306 
1307 	if (dev->card_info->fw_version >= 17) {
1308 		u8 tsin12_config[6]   = { 0x60, 0x60, 0x00, 0x00, 0x00, 0x00 };
1309 		u8 tsin1234_config[6] = { 0x30, 0x30, 0x00, 0x30, 0x30, 0x00 };
1310 		u8 tsio1235_config[6] = { 0x30, 0x30, 0x00, 0x28, 0x00, 0x38 };
1311 		u8 *bconf = tsin12_config;
1312 
1313 		if (dev->card_info->io_type[2]&NGENE_IO_TSIN &&
1314 		    dev->card_info->io_type[3]&NGENE_IO_TSIN) {
1315 			bconf = tsin1234_config;
1316 			if (dev->card_info->io_type[4]&NGENE_IO_TSOUT &&
1317 			    dev->ci.en)
1318 				bconf = tsio1235_config;
1319 		}
1320 		stat = ngene_command_config_free_buf(dev, bconf);
1321 	} else {
1322 		int bconf = BUFFER_CONFIG_4422;
1323 
1324 		if (dev->card_info->io_type[3] == NGENE_IO_TSIN)
1325 			bconf = BUFFER_CONFIG_3333;
1326 		stat = ngene_command_config_buf(dev, bconf);
1327 	}
1328 	return stat;
1329 }
1330 
1331 
1332 static int ngene_start(struct ngene *dev)
1333 {
1334 	int stat;
1335 	int i;
1336 
1337 	pci_set_master(dev->pci_dev);
1338 	ngene_init(dev);
1339 
1340 	stat = request_irq(dev->pci_dev->irq, irq_handler,
1341 			   IRQF_SHARED, "nGene",
1342 			   (void *)dev);
1343 	if (stat < 0)
1344 		return stat;
1345 
1346 	init_waitqueue_head(&dev->cmd_wq);
1347 	init_waitqueue_head(&dev->tx_wq);
1348 	init_waitqueue_head(&dev->rx_wq);
1349 	sema_init(&dev->cmd_mutex, 1);
1350 	sema_init(&dev->stream_mutex, 1);
1351 	sema_init(&dev->pll_mutex, 1);
1352 	sema_init(&dev->i2c_switch_mutex, 1);
1353 	spin_lock_init(&dev->cmd_lock);
1354 	for (i = 0; i < MAX_STREAM; i++)
1355 		spin_lock_init(&dev->channel[i].state_lock);
1356 	ngwritel(1, TIMESTAMPS);
1357 
1358 	ngwritel(1, NGENE_INT_ENABLE);
1359 
1360 	stat = ngene_load_firm(dev);
1361 	if (stat < 0)
1362 		goto fail;
1363 
1364 #ifdef CONFIG_PCI_MSI
1365 	/* enable MSI if kernel and card support it */
1366 	if (pci_msi_enabled() && dev->card_info->msi_supported) {
1367 		unsigned long flags;
1368 
1369 		ngwritel(0, NGENE_INT_ENABLE);
1370 		free_irq(dev->pci_dev->irq, dev);
1371 		stat = pci_enable_msi(dev->pci_dev);
1372 		if (stat) {
1373 			printk(KERN_INFO DEVICE_NAME
1374 				": MSI not available\n");
1375 			flags = IRQF_SHARED;
1376 		} else {
1377 			flags = 0;
1378 			dev->msi_enabled = true;
1379 		}
1380 		stat = request_irq(dev->pci_dev->irq, irq_handler,
1381 					flags, "nGene", dev);
1382 		if (stat < 0)
1383 			goto fail2;
1384 		ngwritel(1, NGENE_INT_ENABLE);
1385 	}
1386 #endif
1387 
1388 	stat = ngene_i2c_init(dev, 0);
1389 	if (stat < 0)
1390 		goto fail;
1391 
1392 	stat = ngene_i2c_init(dev, 1);
1393 	if (stat < 0)
1394 		goto fail;
1395 
1396 	return 0;
1397 
1398 fail:
1399 	ngwritel(0, NGENE_INT_ENABLE);
1400 	free_irq(dev->pci_dev->irq, dev);
1401 #ifdef CONFIG_PCI_MSI
1402 fail2:
1403 	if (dev->msi_enabled)
1404 		pci_disable_msi(dev->pci_dev);
1405 #endif
1406 	return stat;
1407 }
1408 
1409 /****************************************************************************/
1410 /****************************************************************************/
1411 /****************************************************************************/
1412 
1413 static void release_channel(struct ngene_channel *chan)
1414 {
1415 	struct dvb_demux *dvbdemux = &chan->demux;
1416 	struct ngene *dev = chan->dev;
1417 
1418 	if (chan->running)
1419 		set_transfer(chan, 0);
1420 
1421 	tasklet_kill(&chan->demux_tasklet);
1422 
1423 	if (chan->ci_dev) {
1424 		dvb_unregister_device(chan->ci_dev);
1425 		chan->ci_dev = NULL;
1426 	}
1427 
1428 	if (chan->fe2)
1429 		dvb_unregister_frontend(chan->fe2);
1430 
1431 	if (chan->fe) {
1432 		dvb_unregister_frontend(chan->fe);
1433 		dvb_frontend_detach(chan->fe);
1434 		chan->fe = NULL;
1435 	}
1436 
1437 	if (chan->has_demux) {
1438 		dvb_net_release(&chan->dvbnet);
1439 		dvbdemux->dmx.close(&dvbdemux->dmx);
1440 		dvbdemux->dmx.remove_frontend(&dvbdemux->dmx,
1441 					      &chan->hw_frontend);
1442 		dvbdemux->dmx.remove_frontend(&dvbdemux->dmx,
1443 					      &chan->mem_frontend);
1444 		dvb_dmxdev_release(&chan->dmxdev);
1445 		dvb_dmx_release(&chan->demux);
1446 		chan->has_demux = false;
1447 	}
1448 
1449 	if (chan->has_adapter) {
1450 		dvb_unregister_adapter(&dev->adapter[chan->number]);
1451 		chan->has_adapter = false;
1452 	}
1453 }
1454 
1455 static int init_channel(struct ngene_channel *chan)
1456 {
1457 	int ret = 0, nr = chan->number;
1458 	struct dvb_adapter *adapter = NULL;
1459 	struct dvb_demux *dvbdemux = &chan->demux;
1460 	struct ngene *dev = chan->dev;
1461 	struct ngene_info *ni = dev->card_info;
1462 	int io = ni->io_type[nr];
1463 
1464 	tasklet_init(&chan->demux_tasklet, demux_tasklet, (unsigned long)chan);
1465 	chan->users = 0;
1466 	chan->type = io;
1467 	chan->mode = chan->type;	/* for now only one mode */
1468 
1469 	if (io & NGENE_IO_TSIN) {
1470 		chan->fe = NULL;
1471 		if (ni->demod_attach[nr]) {
1472 			ret = ni->demod_attach[nr](chan);
1473 			if (ret < 0)
1474 				goto err;
1475 		}
1476 		if (chan->fe && ni->tuner_attach[nr]) {
1477 			ret = ni->tuner_attach[nr](chan);
1478 			if (ret < 0)
1479 				goto err;
1480 		}
1481 	}
1482 
1483 	if (!dev->ci.en && (io & NGENE_IO_TSOUT))
1484 		return 0;
1485 
1486 	if (io & (NGENE_IO_TSIN | NGENE_IO_TSOUT)) {
1487 		if (nr >= STREAM_AUDIOIN1)
1488 			chan->DataFormatFlags = DF_SWAP32;
1489 
1490 		if (nr == 0 || !one_adapter || dev->first_adapter == NULL) {
1491 			adapter = &dev->adapter[nr];
1492 			ret = dvb_register_adapter(adapter, "nGene",
1493 						   THIS_MODULE,
1494 						   &chan->dev->pci_dev->dev,
1495 						   adapter_nr);
1496 			if (ret < 0)
1497 				goto err;
1498 			if (dev->first_adapter == NULL)
1499 				dev->first_adapter = adapter;
1500 			chan->has_adapter = true;
1501 		} else
1502 			adapter = dev->first_adapter;
1503 	}
1504 
1505 	if (dev->ci.en && (io & NGENE_IO_TSOUT)) {
1506 		dvb_ca_en50221_init(adapter, dev->ci.en, 0, 1);
1507 		set_transfer(chan, 1);
1508 		chan->dev->channel[2].DataFormatFlags = DF_SWAP32;
1509 		set_transfer(&chan->dev->channel[2], 1);
1510 		dvb_register_device(adapter, &chan->ci_dev,
1511 				    &ngene_dvbdev_ci, (void *) chan,
1512 				    DVB_DEVICE_SEC, 0);
1513 		if (!chan->ci_dev)
1514 			goto err;
1515 	}
1516 
1517 	if (chan->fe) {
1518 		if (dvb_register_frontend(adapter, chan->fe) < 0)
1519 			goto err;
1520 		chan->has_demux = true;
1521 	}
1522 	if (chan->fe2) {
1523 		if (dvb_register_frontend(adapter, chan->fe2) < 0)
1524 			goto err;
1525 		if (chan->fe) {
1526 			chan->fe2->tuner_priv = chan->fe->tuner_priv;
1527 			memcpy(&chan->fe2->ops.tuner_ops,
1528 			       &chan->fe->ops.tuner_ops,
1529 			       sizeof(struct dvb_tuner_ops));
1530 		}
1531 	}
1532 
1533 	if (chan->has_demux) {
1534 		ret = my_dvb_dmx_ts_card_init(dvbdemux, "SW demux",
1535 					      ngene_start_feed,
1536 					      ngene_stop_feed, chan);
1537 		ret = my_dvb_dmxdev_ts_card_init(&chan->dmxdev, &chan->demux,
1538 						 &chan->hw_frontend,
1539 						 &chan->mem_frontend, adapter);
1540 		ret = dvb_net_init(adapter, &chan->dvbnet, &chan->demux.dmx);
1541 	}
1542 
1543 	return ret;
1544 
1545 err:
1546 	if (chan->fe) {
1547 		dvb_frontend_detach(chan->fe);
1548 		chan->fe = NULL;
1549 	}
1550 	release_channel(chan);
1551 	return 0;
1552 }
1553 
1554 static int init_channels(struct ngene *dev)
1555 {
1556 	int i, j;
1557 
1558 	for (i = 0; i < MAX_STREAM; i++) {
1559 		dev->channel[i].number = i;
1560 		if (init_channel(&dev->channel[i]) < 0) {
1561 			for (j = i - 1; j >= 0; j--)
1562 				release_channel(&dev->channel[j]);
1563 			return -1;
1564 		}
1565 	}
1566 	return 0;
1567 }
1568 
1569 static struct cxd2099_cfg cxd_cfg = {
1570 	.bitrate = 62000,
1571 	.adr = 0x40,
1572 	.polarity = 0,
1573 	.clock_mode = 0,
1574 };
1575 
1576 static void cxd_attach(struct ngene *dev)
1577 {
1578 	struct ngene_ci *ci = &dev->ci;
1579 
1580 	ci->en = cxd2099_attach(&cxd_cfg, dev, &dev->channel[0].i2c_adapter);
1581 	ci->dev = dev;
1582 	return;
1583 }
1584 
1585 static void cxd_detach(struct ngene *dev)
1586 {
1587 	struct ngene_ci *ci = &dev->ci;
1588 
1589 	dvb_ca_en50221_release(ci->en);
1590 	kfree(ci->en);
1591 	ci->en = NULL;
1592 }
1593 
1594 /***********************************/
1595 /* workaround for shutdown failure */
1596 /***********************************/
1597 
1598 static void ngene_unlink(struct ngene *dev)
1599 {
1600 	struct ngene_command com;
1601 
1602 	com.cmd.hdr.Opcode = CMD_MEM_WRITE;
1603 	com.cmd.hdr.Length = 3;
1604 	com.cmd.MemoryWrite.address = 0x910c;
1605 	com.cmd.MemoryWrite.data = 0xff;
1606 	com.in_len = 3;
1607 	com.out_len = 1;
1608 
1609 	down(&dev->cmd_mutex);
1610 	ngwritel(0, NGENE_INT_ENABLE);
1611 	ngene_command_mutex(dev, &com);
1612 	up(&dev->cmd_mutex);
1613 }
1614 
1615 void ngene_shutdown(struct pci_dev *pdev)
1616 {
1617 	struct ngene *dev = pci_get_drvdata(pdev);
1618 
1619 	if (!dev || !shutdown_workaround)
1620 		return;
1621 
1622 	printk(KERN_INFO DEVICE_NAME ": shutdown workaround...\n");
1623 	ngene_unlink(dev);
1624 	pci_disable_device(pdev);
1625 }
1626 
1627 /****************************************************************************/
1628 /* device probe/remove calls ************************************************/
1629 /****************************************************************************/
1630 
1631 void ngene_remove(struct pci_dev *pdev)
1632 {
1633 	struct ngene *dev = pci_get_drvdata(pdev);
1634 	int i;
1635 
1636 	tasklet_kill(&dev->event_tasklet);
1637 	for (i = MAX_STREAM - 1; i >= 0; i--)
1638 		release_channel(&dev->channel[i]);
1639 	if (dev->ci.en)
1640 		cxd_detach(dev);
1641 	ngene_stop(dev);
1642 	ngene_release_buffers(dev);
1643 	pci_disable_device(pdev);
1644 }
1645 
1646 int ngene_probe(struct pci_dev *pci_dev, const struct pci_device_id *id)
1647 {
1648 	struct ngene *dev;
1649 	int stat = 0;
1650 
1651 	if (pci_enable_device(pci_dev) < 0)
1652 		return -ENODEV;
1653 
1654 	dev = vzalloc(sizeof(struct ngene));
1655 	if (dev == NULL) {
1656 		stat = -ENOMEM;
1657 		goto fail0;
1658 	}
1659 
1660 	dev->pci_dev = pci_dev;
1661 	dev->card_info = (struct ngene_info *)id->driver_data;
1662 	printk(KERN_INFO DEVICE_NAME ": Found %s\n", dev->card_info->name);
1663 
1664 	pci_set_drvdata(pci_dev, dev);
1665 
1666 	/* Alloc buffers and start nGene */
1667 	stat = ngene_get_buffers(dev);
1668 	if (stat < 0)
1669 		goto fail1;
1670 	stat = ngene_start(dev);
1671 	if (stat < 0)
1672 		goto fail1;
1673 
1674 	cxd_attach(dev);
1675 
1676 	stat = ngene_buffer_config(dev);
1677 	if (stat < 0)
1678 		goto fail1;
1679 
1680 
1681 	dev->i2c_current_bus = -1;
1682 
1683 	/* Register DVB adapters and devices for both channels */
1684 	stat = init_channels(dev);
1685 	if (stat < 0)
1686 		goto fail2;
1687 
1688 	return 0;
1689 
1690 fail2:
1691 	ngene_stop(dev);
1692 fail1:
1693 	ngene_release_buffers(dev);
1694 fail0:
1695 	pci_disable_device(pci_dev);
1696 	return stat;
1697 }
1698