1 /*
2  *  Driver for the NXP SAA7164 PCIe bridge
3  *
4  *  Copyright (c) 2010-2015 Steven Toth <stoth@kernellabs.com>
5  *
6  *  This program is free software; you can redistribute it and/or modify
7  *  it under the terms of the GNU General Public License as published by
8  *  the Free Software Foundation; either version 2 of the License, or
9  *  (at your option) any later version.
10  *
11  *  This program is distributed in the hope that it will be useful,
12  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
13  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14  *
15  *  GNU General Public License for more details.
16  */
17 
18 #include <linux/init.h>
19 #include <linux/list.h>
20 #include <linux/module.h>
21 #include <linux/moduleparam.h>
22 #include <linux/kmod.h>
23 #include <linux/kernel.h>
24 #include <linux/slab.h>
25 #include <linux/interrupt.h>
26 #include <linux/delay.h>
27 #include <asm/div64.h>
28 
29 #ifdef CONFIG_PROC_FS
30 #include <linux/proc_fs.h>
31 #endif
32 #include "saa7164.h"
33 
34 MODULE_DESCRIPTION("Driver for NXP SAA7164 based TV cards");
35 MODULE_AUTHOR("Steven Toth <stoth@kernellabs.com>");
36 MODULE_LICENSE("GPL");
37 
38 /*
39  *  1 Basic
40  *  2
41  *  4 i2c
42  *  8 api
43  * 16 cmd
44  * 32 bus
45  */
46 
47 unsigned int saa_debug;
48 module_param_named(debug, saa_debug, int, 0644);
49 MODULE_PARM_DESC(debug, "enable debug messages");
50 
51 static unsigned int fw_debug;
52 module_param(fw_debug, int, 0644);
53 MODULE_PARM_DESC(fw_debug, "Firmware debug level def:2");
54 
55 unsigned int encoder_buffers = SAA7164_MAX_ENCODER_BUFFERS;
56 module_param(encoder_buffers, int, 0644);
57 MODULE_PARM_DESC(encoder_buffers, "Total buffers in read queue 16-512 def:64");
58 
59 unsigned int vbi_buffers = SAA7164_MAX_VBI_BUFFERS;
60 module_param(vbi_buffers, int, 0644);
61 MODULE_PARM_DESC(vbi_buffers, "Total buffers in read queue 16-512 def:64");
62 
63 unsigned int waitsecs = 10;
64 module_param(waitsecs, int, 0644);
65 MODULE_PARM_DESC(waitsecs, "timeout on firmware messages");
66 
67 static unsigned int card[]  = {[0 ... (SAA7164_MAXBOARDS - 1)] = UNSET };
68 module_param_array(card,  int, NULL, 0444);
69 MODULE_PARM_DESC(card, "card type");
70 
71 static unsigned int print_histogram = 64;
72 module_param(print_histogram, int, 0644);
73 MODULE_PARM_DESC(print_histogram, "print histogram values once");
74 
75 unsigned int crc_checking = 1;
76 module_param(crc_checking, int, 0644);
77 MODULE_PARM_DESC(crc_checking, "enable crc sanity checking on buffers");
78 
79 static unsigned int guard_checking = 1;
80 module_param(guard_checking, int, 0644);
81 MODULE_PARM_DESC(guard_checking,
82 	"enable dma sanity checking for buffer overruns");
83 
84 static bool enable_msi = true;
85 module_param(enable_msi, bool, 0444);
86 MODULE_PARM_DESC(enable_msi,
87 		"enable the use of an msi interrupt if available");
88 
89 static unsigned int saa7164_devcount;
90 
91 static DEFINE_MUTEX(devlist);
92 LIST_HEAD(saa7164_devlist);
93 
94 #define INT_SIZE 16
95 
96 static void saa7164_pack_verifier(struct saa7164_buffer *buf)
97 {
98 	u8 *p = (u8 *)buf->cpu;
99 	int i;
100 
101 	for (i = 0; i < buf->actual_size; i += 2048) {
102 
103 		if ((*(p + i + 0) != 0x00) || (*(p + i + 1) != 0x00) ||
104 			(*(p + i + 2) != 0x01) || (*(p + i + 3) != 0xBA)) {
105 			printk(KERN_ERR "No pack at 0x%x\n", i);
106 #if 0
107 			print_hex_dump(KERN_INFO, "", DUMP_PREFIX_OFFSET, 16, 1,
108 				       p + 1, 32, false);
109 #endif
110 		}
111 	}
112 }
113 
114 #define FIXED_VIDEO_PID 0xf1
115 #define FIXED_AUDIO_PID 0xf2
116 
117 static void saa7164_ts_verifier(struct saa7164_buffer *buf)
118 {
119 	struct saa7164_port *port = buf->port;
120 	u32 i;
121 	u8 cc, a;
122 	u16 pid;
123 	u8 *bufcpu = (u8 *)buf->cpu;
124 
125 	port->sync_errors = 0;
126 	port->v_cc_errors = 0;
127 	port->a_cc_errors = 0;
128 
129 	for (i = 0; i < buf->actual_size; i += 188) {
130 		if (*(bufcpu + i) != 0x47)
131 			port->sync_errors++;
132 
133 		/* TODO: Query pid lower 8 bits, ignoring upper bits intensionally */
134 		pid = ((*(bufcpu + i + 1) & 0x1f) << 8) | *(bufcpu + i + 2);
135 		cc = *(bufcpu + i + 3) & 0x0f;
136 
137 		if (pid == FIXED_VIDEO_PID) {
138 			a = ((port->last_v_cc + 1) & 0x0f);
139 			if (a != cc) {
140 				printk(KERN_ERR "video cc last = %x current = %x i = %d\n",
141 					port->last_v_cc, cc, i);
142 				port->v_cc_errors++;
143 			}
144 
145 			port->last_v_cc = cc;
146 		} else
147 		if (pid == FIXED_AUDIO_PID) {
148 			a = ((port->last_a_cc + 1) & 0x0f);
149 			if (a != cc) {
150 				printk(KERN_ERR "audio cc last = %x current = %x i = %d\n",
151 					port->last_a_cc, cc, i);
152 				port->a_cc_errors++;
153 			}
154 
155 			port->last_a_cc = cc;
156 		}
157 
158 	}
159 
160 	/* Only report errors if we've been through this function at least
161 	 * once already and the cached cc values are primed. First time through
162 	 * always generates errors.
163 	 */
164 	if (port->v_cc_errors && (port->done_first_interrupt > 1))
165 		printk(KERN_ERR "video pid cc, %d errors\n", port->v_cc_errors);
166 
167 	if (port->a_cc_errors && (port->done_first_interrupt > 1))
168 		printk(KERN_ERR "audio pid cc, %d errors\n", port->a_cc_errors);
169 
170 	if (port->sync_errors && (port->done_first_interrupt > 1))
171 		printk(KERN_ERR "sync_errors = %d\n", port->sync_errors);
172 
173 	if (port->done_first_interrupt == 1)
174 		port->done_first_interrupt++;
175 }
176 
177 static void saa7164_histogram_reset(struct saa7164_histogram *hg, char *name)
178 {
179 	int i;
180 
181 	memset(hg, 0, sizeof(struct saa7164_histogram));
182 	strscpy(hg->name, name, sizeof(hg->name));
183 
184 	/* First 30ms x 1ms */
185 	for (i = 0; i < 30; i++)
186 		hg->counter1[0 + i].val = i;
187 
188 	/* 30 - 200ms x 10ms  */
189 	for (i = 0; i < 18; i++)
190 		hg->counter1[30 + i].val = 30 + (i * 10);
191 
192 	/* 200 - 2000ms x 100ms  */
193 	for (i = 0; i < 15; i++)
194 		hg->counter1[48 + i].val = 200 + (i * 200);
195 
196 	/* Catch all massive value (2secs) */
197 	hg->counter1[55].val = 2000;
198 
199 	/* Catch all massive value (4secs) */
200 	hg->counter1[56].val = 4000;
201 
202 	/* Catch all massive value (8secs) */
203 	hg->counter1[57].val = 8000;
204 
205 	/* Catch all massive value (15secs) */
206 	hg->counter1[58].val = 15000;
207 
208 	/* Catch all massive value (30secs) */
209 	hg->counter1[59].val = 30000;
210 
211 	/* Catch all massive value (60secs) */
212 	hg->counter1[60].val = 60000;
213 
214 	/* Catch all massive value (5mins) */
215 	hg->counter1[61].val = 300000;
216 
217 	/* Catch all massive value (15mins) */
218 	hg->counter1[62].val = 900000;
219 
220 	/* Catch all massive values (1hr) */
221 	hg->counter1[63].val = 3600000;
222 }
223 
224 void saa7164_histogram_update(struct saa7164_histogram *hg, u32 val)
225 {
226 	int i;
227 	for (i = 0; i < 64; i++) {
228 		if (val <= hg->counter1[i].val) {
229 			hg->counter1[i].count++;
230 			hg->counter1[i].update_time = jiffies;
231 			break;
232 		}
233 	}
234 }
235 
236 static void saa7164_histogram_print(struct saa7164_port *port,
237 	struct saa7164_histogram *hg)
238 {
239 	u32 entries = 0;
240 	int i;
241 
242 	printk(KERN_ERR "Histogram named %s (ms, count, last_update_jiffy)\n", hg->name);
243 	for (i = 0; i < 64; i++) {
244 		if (hg->counter1[i].count == 0)
245 			continue;
246 
247 		printk(KERN_ERR " %4d %12d %Ld\n",
248 			hg->counter1[i].val,
249 			hg->counter1[i].count,
250 			hg->counter1[i].update_time);
251 
252 		entries++;
253 	}
254 	printk(KERN_ERR "Total: %d\n", entries);
255 }
256 
257 static void saa7164_work_enchandler_helper(struct saa7164_port *port, int bufnr)
258 {
259 	struct saa7164_dev *dev = port->dev;
260 	struct saa7164_buffer *buf = NULL;
261 	struct saa7164_user_buffer *ubuf = NULL;
262 	struct list_head *c, *n;
263 	int i = 0;
264 	u8 *p;
265 
266 	mutex_lock(&port->dmaqueue_lock);
267 	list_for_each_safe(c, n, &port->dmaqueue.list) {
268 
269 		buf = list_entry(c, struct saa7164_buffer, list);
270 		if (i++ > port->hwcfg.buffercount) {
271 			printk(KERN_ERR "%s() illegal i count %d\n",
272 				__func__, i);
273 			break;
274 		}
275 
276 		if (buf->idx == bufnr) {
277 
278 			/* Found the buffer, deal with it */
279 			dprintk(DBGLVL_IRQ, "%s() bufnr: %d\n", __func__, bufnr);
280 
281 			if (crc_checking) {
282 				/* Throw a new checksum on the dma buffer */
283 				buf->crc = crc32(0, buf->cpu, buf->actual_size);
284 			}
285 
286 			if (guard_checking) {
287 				p = (u8 *)buf->cpu;
288 				if ((*(p + buf->actual_size + 0) != 0xff) ||
289 					(*(p + buf->actual_size + 1) != 0xff) ||
290 					(*(p + buf->actual_size + 2) != 0xff) ||
291 					(*(p + buf->actual_size + 3) != 0xff) ||
292 					(*(p + buf->actual_size + 0x10) != 0xff) ||
293 					(*(p + buf->actual_size + 0x11) != 0xff) ||
294 					(*(p + buf->actual_size + 0x12) != 0xff) ||
295 					(*(p + buf->actual_size + 0x13) != 0xff)) {
296 						printk(KERN_ERR "%s() buf %p guard buffer breach\n",
297 							__func__, buf);
298 #if 0
299 			print_hex_dump(KERN_INFO, "", DUMP_PREFIX_OFFSET, 16, 1,
300 				       p + buf->actual_size - 32, 64, false);
301 #endif
302 				}
303 			}
304 
305 			if ((port->nr != SAA7164_PORT_VBI1) && (port->nr != SAA7164_PORT_VBI2)) {
306 				/* Validate the incoming buffer content */
307 				if (port->encoder_params.stream_type == V4L2_MPEG_STREAM_TYPE_MPEG2_TS)
308 					saa7164_ts_verifier(buf);
309 				else if (port->encoder_params.stream_type == V4L2_MPEG_STREAM_TYPE_MPEG2_PS)
310 					saa7164_pack_verifier(buf);
311 			}
312 
313 			/* find a free user buffer and clone to it */
314 			if (!list_empty(&port->list_buf_free.list)) {
315 
316 				/* Pull the first buffer from the used list */
317 				ubuf = list_first_entry(&port->list_buf_free.list,
318 					struct saa7164_user_buffer, list);
319 
320 				if (buf->actual_size <= ubuf->actual_size) {
321 
322 					memcpy(ubuf->data, buf->cpu, ubuf->actual_size);
323 
324 					if (crc_checking) {
325 						/* Throw a new checksum on the read buffer */
326 						ubuf->crc = crc32(0, ubuf->data, ubuf->actual_size);
327 					}
328 
329 					/* Requeue the buffer on the free list */
330 					ubuf->pos = 0;
331 
332 					list_move_tail(&ubuf->list,
333 						&port->list_buf_used.list);
334 
335 					/* Flag any userland waiters */
336 					wake_up_interruptible(&port->wait_read);
337 
338 				} else {
339 					printk(KERN_ERR "buf %p bufsize fails match\n", buf);
340 				}
341 
342 			} else
343 				printk(KERN_ERR "encirq no free buffers, increase param encoder_buffers\n");
344 
345 			/* Ensure offset into buffer remains 0, fill buffer
346 			 * with known bad data. We check for this data at a later point
347 			 * in time. */
348 			saa7164_buffer_zero_offsets(port, bufnr);
349 			memset(buf->cpu, 0xff, buf->pci_size);
350 			if (crc_checking) {
351 				/* Throw yet aanother new checksum on the dma buffer */
352 				buf->crc = crc32(0, buf->cpu, buf->actual_size);
353 			}
354 
355 			break;
356 		}
357 	}
358 	mutex_unlock(&port->dmaqueue_lock);
359 }
360 
361 static void saa7164_work_enchandler(struct work_struct *w)
362 {
363 	struct saa7164_port *port =
364 		container_of(w, struct saa7164_port, workenc);
365 	struct saa7164_dev *dev = port->dev;
366 
367 	u32 wp, mcb, rp, cnt = 0;
368 
369 	port->last_svc_msecs_diff = port->last_svc_msecs;
370 	port->last_svc_msecs = jiffies_to_msecs(jiffies);
371 
372 	port->last_svc_msecs_diff = port->last_svc_msecs -
373 		port->last_svc_msecs_diff;
374 
375 	saa7164_histogram_update(&port->svc_interval,
376 		port->last_svc_msecs_diff);
377 
378 	port->last_irq_svc_msecs_diff = port->last_svc_msecs -
379 		port->last_irq_msecs;
380 
381 	saa7164_histogram_update(&port->irq_svc_interval,
382 		port->last_irq_svc_msecs_diff);
383 
384 	dprintk(DBGLVL_IRQ,
385 		"%s() %Ldms elapsed irq->deferred %Ldms wp: %d rp: %d\n",
386 		__func__,
387 		port->last_svc_msecs_diff,
388 		port->last_irq_svc_msecs_diff,
389 		port->last_svc_wp,
390 		port->last_svc_rp
391 		);
392 
393 	/* Current write position */
394 	wp = saa7164_readl(port->bufcounter);
395 	if (wp > (port->hwcfg.buffercount - 1)) {
396 		printk(KERN_ERR "%s() illegal buf count %d\n", __func__, wp);
397 		return;
398 	}
399 
400 	/* Most current complete buffer */
401 	if (wp == 0)
402 		mcb = (port->hwcfg.buffercount - 1);
403 	else
404 		mcb = wp - 1;
405 
406 	while (1) {
407 		if (port->done_first_interrupt == 0) {
408 			port->done_first_interrupt++;
409 			rp = mcb;
410 		} else
411 			rp = (port->last_svc_rp + 1) % 8;
412 
413 		if (rp > (port->hwcfg.buffercount - 1)) {
414 			printk(KERN_ERR "%s() illegal rp count %d\n", __func__, rp);
415 			break;
416 		}
417 
418 		saa7164_work_enchandler_helper(port, rp);
419 		port->last_svc_rp = rp;
420 		cnt++;
421 
422 		if (rp == mcb)
423 			break;
424 	}
425 
426 	/* TODO: Convert this into a /proc/saa7164 style readable file */
427 	if (print_histogram == port->nr) {
428 		saa7164_histogram_print(port, &port->irq_interval);
429 		saa7164_histogram_print(port, &port->svc_interval);
430 		saa7164_histogram_print(port, &port->irq_svc_interval);
431 		saa7164_histogram_print(port, &port->read_interval);
432 		saa7164_histogram_print(port, &port->poll_interval);
433 		/* TODO: fix this to preserve any previous state */
434 		print_histogram = 64 + port->nr;
435 	}
436 }
437 
438 static void saa7164_work_vbihandler(struct work_struct *w)
439 {
440 	struct saa7164_port *port =
441 		container_of(w, struct saa7164_port, workenc);
442 	struct saa7164_dev *dev = port->dev;
443 
444 	u32 wp, mcb, rp, cnt = 0;
445 
446 	port->last_svc_msecs_diff = port->last_svc_msecs;
447 	port->last_svc_msecs = jiffies_to_msecs(jiffies);
448 	port->last_svc_msecs_diff = port->last_svc_msecs -
449 		port->last_svc_msecs_diff;
450 
451 	saa7164_histogram_update(&port->svc_interval,
452 		port->last_svc_msecs_diff);
453 
454 	port->last_irq_svc_msecs_diff = port->last_svc_msecs -
455 		port->last_irq_msecs;
456 
457 	saa7164_histogram_update(&port->irq_svc_interval,
458 		port->last_irq_svc_msecs_diff);
459 
460 	dprintk(DBGLVL_IRQ,
461 		"%s() %Ldms elapsed irq->deferred %Ldms wp: %d rp: %d\n",
462 		__func__,
463 		port->last_svc_msecs_diff,
464 		port->last_irq_svc_msecs_diff,
465 		port->last_svc_wp,
466 		port->last_svc_rp
467 		);
468 
469 	/* Current write position */
470 	wp = saa7164_readl(port->bufcounter);
471 	if (wp > (port->hwcfg.buffercount - 1)) {
472 		printk(KERN_ERR "%s() illegal buf count %d\n", __func__, wp);
473 		return;
474 	}
475 
476 	/* Most current complete buffer */
477 	if (wp == 0)
478 		mcb = (port->hwcfg.buffercount - 1);
479 	else
480 		mcb = wp - 1;
481 
482 	while (1) {
483 		if (port->done_first_interrupt == 0) {
484 			port->done_first_interrupt++;
485 			rp = mcb;
486 		} else
487 			rp = (port->last_svc_rp + 1) % 8;
488 
489 		if (rp > (port->hwcfg.buffercount - 1)) {
490 			printk(KERN_ERR "%s() illegal rp count %d\n", __func__, rp);
491 			break;
492 		}
493 
494 		saa7164_work_enchandler_helper(port, rp);
495 		port->last_svc_rp = rp;
496 		cnt++;
497 
498 		if (rp == mcb)
499 			break;
500 	}
501 
502 	/* TODO: Convert this into a /proc/saa7164 style readable file */
503 	if (print_histogram == port->nr) {
504 		saa7164_histogram_print(port, &port->irq_interval);
505 		saa7164_histogram_print(port, &port->svc_interval);
506 		saa7164_histogram_print(port, &port->irq_svc_interval);
507 		saa7164_histogram_print(port, &port->read_interval);
508 		saa7164_histogram_print(port, &port->poll_interval);
509 		/* TODO: fix this to preserve any previous state */
510 		print_histogram = 64 + port->nr;
511 	}
512 }
513 
514 static void saa7164_work_cmdhandler(struct work_struct *w)
515 {
516 	struct saa7164_dev *dev = container_of(w, struct saa7164_dev, workcmd);
517 
518 	/* Wake up any complete commands */
519 	saa7164_irq_dequeue(dev);
520 }
521 
522 static void saa7164_buffer_deliver(struct saa7164_buffer *buf)
523 {
524 	struct saa7164_port *port = buf->port;
525 
526 	/* Feed the transport payload into the kernel demux */
527 	dvb_dmx_swfilter_packets(&port->dvb.demux, (u8 *)buf->cpu,
528 		SAA7164_TS_NUMBER_OF_LINES);
529 
530 }
531 
532 static irqreturn_t saa7164_irq_vbi(struct saa7164_port *port)
533 {
534 	struct saa7164_dev *dev = port->dev;
535 
536 	/* Store old time */
537 	port->last_irq_msecs_diff = port->last_irq_msecs;
538 
539 	/* Collect new stats */
540 	port->last_irq_msecs = jiffies_to_msecs(jiffies);
541 
542 	/* Calculate stats */
543 	port->last_irq_msecs_diff = port->last_irq_msecs -
544 		port->last_irq_msecs_diff;
545 
546 	saa7164_histogram_update(&port->irq_interval,
547 		port->last_irq_msecs_diff);
548 
549 	dprintk(DBGLVL_IRQ, "%s() %Ldms elapsed\n", __func__,
550 		port->last_irq_msecs_diff);
551 
552 	/* Tis calls the vbi irq handler */
553 	schedule_work(&port->workenc);
554 	return 0;
555 }
556 
557 static irqreturn_t saa7164_irq_encoder(struct saa7164_port *port)
558 {
559 	struct saa7164_dev *dev = port->dev;
560 
561 	/* Store old time */
562 	port->last_irq_msecs_diff = port->last_irq_msecs;
563 
564 	/* Collect new stats */
565 	port->last_irq_msecs = jiffies_to_msecs(jiffies);
566 
567 	/* Calculate stats */
568 	port->last_irq_msecs_diff = port->last_irq_msecs -
569 		port->last_irq_msecs_diff;
570 
571 	saa7164_histogram_update(&port->irq_interval,
572 		port->last_irq_msecs_diff);
573 
574 	dprintk(DBGLVL_IRQ, "%s() %Ldms elapsed\n", __func__,
575 		port->last_irq_msecs_diff);
576 
577 	schedule_work(&port->workenc);
578 	return 0;
579 }
580 
581 static irqreturn_t saa7164_irq_ts(struct saa7164_port *port)
582 {
583 	struct saa7164_dev *dev = port->dev;
584 	struct saa7164_buffer *buf;
585 	struct list_head *c, *n;
586 	int wp, i = 0, rp;
587 
588 	/* Find the current write point from the hardware */
589 	wp = saa7164_readl(port->bufcounter);
590 	if (wp > (port->hwcfg.buffercount - 1))
591 		BUG();
592 
593 	/* Find the previous buffer to the current write point */
594 	if (wp == 0)
595 		rp = (port->hwcfg.buffercount - 1);
596 	else
597 		rp = wp - 1;
598 
599 	/* Lookup the WP in the buffer list */
600 	/* TODO: turn this into a worker thread */
601 	list_for_each_safe(c, n, &port->dmaqueue.list) {
602 		buf = list_entry(c, struct saa7164_buffer, list);
603 		if (i++ > port->hwcfg.buffercount)
604 			BUG();
605 
606 		if (buf->idx == rp) {
607 			/* Found the buffer, deal with it */
608 			dprintk(DBGLVL_IRQ, "%s() wp: %d processing: %d\n",
609 				__func__, wp, rp);
610 			saa7164_buffer_deliver(buf);
611 			break;
612 		}
613 
614 	}
615 	return 0;
616 }
617 
618 /* Primary IRQ handler and dispatch mechanism */
619 static irqreturn_t saa7164_irq(int irq, void *dev_id)
620 {
621 	struct saa7164_dev *dev = dev_id;
622 	struct saa7164_port *porta, *portb, *portc, *portd, *porte, *portf;
623 
624 	u32 intid, intstat[INT_SIZE/4];
625 	int i, handled = 0, bit;
626 
627 	if (dev == NULL) {
628 		printk(KERN_ERR "%s() No device specified\n", __func__);
629 		handled = 0;
630 		goto out;
631 	}
632 
633 	porta = &dev->ports[SAA7164_PORT_TS1];
634 	portb = &dev->ports[SAA7164_PORT_TS2];
635 	portc = &dev->ports[SAA7164_PORT_ENC1];
636 	portd = &dev->ports[SAA7164_PORT_ENC2];
637 	porte = &dev->ports[SAA7164_PORT_VBI1];
638 	portf = &dev->ports[SAA7164_PORT_VBI2];
639 
640 	/* Check that the hardware is accessible. If the status bytes are
641 	 * 0xFF then the device is not accessible, the the IRQ belongs
642 	 * to another driver.
643 	 * 4 x u32 interrupt registers.
644 	 */
645 	for (i = 0; i < INT_SIZE/4; i++) {
646 
647 		/* TODO: Convert into saa7164_readl() */
648 		/* Read the 4 hardware interrupt registers */
649 		intstat[i] = saa7164_readl(dev->int_status + (i * 4));
650 
651 		if (intstat[i])
652 			handled = 1;
653 	}
654 	if (handled == 0)
655 		goto out;
656 
657 	/* For each of the HW interrupt registers */
658 	for (i = 0; i < INT_SIZE/4; i++) {
659 
660 		if (intstat[i]) {
661 			/* Each function of the board has it's own interruptid.
662 			 * Find the function that triggered then call
663 			 * it's handler.
664 			 */
665 			for (bit = 0; bit < 32; bit++) {
666 
667 				if (((intstat[i] >> bit) & 0x00000001) == 0)
668 					continue;
669 
670 				/* Calculate the interrupt id (0x00 to 0x7f) */
671 
672 				intid = (i * 32) + bit;
673 				if (intid == dev->intfdesc.bInterruptId) {
674 					/* A response to an cmd/api call */
675 					schedule_work(&dev->workcmd);
676 				} else if (intid == porta->hwcfg.interruptid) {
677 
678 					/* Transport path 1 */
679 					saa7164_irq_ts(porta);
680 
681 				} else if (intid == portb->hwcfg.interruptid) {
682 
683 					/* Transport path 2 */
684 					saa7164_irq_ts(portb);
685 
686 				} else if (intid == portc->hwcfg.interruptid) {
687 
688 					/* Encoder path 1 */
689 					saa7164_irq_encoder(portc);
690 
691 				} else if (intid == portd->hwcfg.interruptid) {
692 
693 					/* Encoder path 2 */
694 					saa7164_irq_encoder(portd);
695 
696 				} else if (intid == porte->hwcfg.interruptid) {
697 
698 					/* VBI path 1 */
699 					saa7164_irq_vbi(porte);
700 
701 				} else if (intid == portf->hwcfg.interruptid) {
702 
703 					/* VBI path 2 */
704 					saa7164_irq_vbi(portf);
705 
706 				} else {
707 					/* Find the function */
708 					dprintk(DBGLVL_IRQ,
709 						"%s() unhandled interrupt reg 0x%x bit 0x%x intid = 0x%x\n",
710 						__func__, i, bit, intid);
711 				}
712 			}
713 
714 			/* Ack it */
715 			saa7164_writel(dev->int_ack + (i * 4), intstat[i]);
716 
717 		}
718 	}
719 out:
720 	return IRQ_RETVAL(handled);
721 }
722 
723 void saa7164_getfirmwarestatus(struct saa7164_dev *dev)
724 {
725 	struct saa7164_fw_status *s = &dev->fw_status;
726 
727 	dev->fw_status.status = saa7164_readl(SAA_DEVICE_SYSINIT_STATUS);
728 	dev->fw_status.mode = saa7164_readl(SAA_DEVICE_SYSINIT_MODE);
729 	dev->fw_status.spec = saa7164_readl(SAA_DEVICE_SYSINIT_SPEC);
730 	dev->fw_status.inst = saa7164_readl(SAA_DEVICE_SYSINIT_INST);
731 	dev->fw_status.cpuload = saa7164_readl(SAA_DEVICE_SYSINIT_CPULOAD);
732 	dev->fw_status.remainheap =
733 		saa7164_readl(SAA_DEVICE_SYSINIT_REMAINHEAP);
734 
735 	dprintk(1, "Firmware status:\n");
736 	dprintk(1, " .status     = 0x%08x\n", s->status);
737 	dprintk(1, " .mode       = 0x%08x\n", s->mode);
738 	dprintk(1, " .spec       = 0x%08x\n", s->spec);
739 	dprintk(1, " .inst       = 0x%08x\n", s->inst);
740 	dprintk(1, " .cpuload    = 0x%08x\n", s->cpuload);
741 	dprintk(1, " .remainheap = 0x%08x\n", s->remainheap);
742 }
743 
744 u32 saa7164_getcurrentfirmwareversion(struct saa7164_dev *dev)
745 {
746 	u32 reg;
747 
748 	reg = saa7164_readl(SAA_DEVICE_VERSION);
749 	dprintk(1, "Device running firmware version %d.%d.%d.%d (0x%x)\n",
750 		(reg & 0x0000fc00) >> 10,
751 		(reg & 0x000003e0) >> 5,
752 		(reg & 0x0000001f),
753 		(reg & 0xffff0000) >> 16,
754 		reg);
755 
756 	return reg;
757 }
758 
759 /* TODO: Debugging func, remove */
760 void saa7164_dumpregs(struct saa7164_dev *dev, u32 addr)
761 {
762 	int i;
763 
764 	dprintk(1, "--------------------> 00 01 02 03 04 05 06 07 08 09 0a 0b 0c 0d 0e 0f\n");
765 
766 	for (i = 0; i < 0x100; i += 16)
767 		dprintk(1, "region0[0x%08x] = %02x %02x %02x %02x %02x %02x %02x %02x %02x %02x %02x %02x %02x %02x %02x %02x\n",
768 			i,
769 			(u8)saa7164_readb(addr + i + 0),
770 			(u8)saa7164_readb(addr + i + 1),
771 			(u8)saa7164_readb(addr + i + 2),
772 			(u8)saa7164_readb(addr + i + 3),
773 			(u8)saa7164_readb(addr + i + 4),
774 			(u8)saa7164_readb(addr + i + 5),
775 			(u8)saa7164_readb(addr + i + 6),
776 			(u8)saa7164_readb(addr + i + 7),
777 			(u8)saa7164_readb(addr + i + 8),
778 			(u8)saa7164_readb(addr + i + 9),
779 			(u8)saa7164_readb(addr + i + 10),
780 			(u8)saa7164_readb(addr + i + 11),
781 			(u8)saa7164_readb(addr + i + 12),
782 			(u8)saa7164_readb(addr + i + 13),
783 			(u8)saa7164_readb(addr + i + 14),
784 			(u8)saa7164_readb(addr + i + 15)
785 			);
786 }
787 
788 static void saa7164_dump_hwdesc(struct saa7164_dev *dev)
789 {
790 	dprintk(1, "@0x%p hwdesc sizeof(struct tmComResHWDescr) = %d bytes\n",
791 		&dev->hwdesc, (u32)sizeof(struct tmComResHWDescr));
792 
793 	dprintk(1, " .bLength = 0x%x\n", dev->hwdesc.bLength);
794 	dprintk(1, " .bDescriptorType = 0x%x\n", dev->hwdesc.bDescriptorType);
795 	dprintk(1, " .bDescriptorSubtype = 0x%x\n",
796 		dev->hwdesc.bDescriptorSubtype);
797 
798 	dprintk(1, " .bcdSpecVersion = 0x%x\n", dev->hwdesc.bcdSpecVersion);
799 	dprintk(1, " .dwClockFrequency = 0x%x\n", dev->hwdesc.dwClockFrequency);
800 	dprintk(1, " .dwClockUpdateRes = 0x%x\n", dev->hwdesc.dwClockUpdateRes);
801 	dprintk(1, " .bCapabilities = 0x%x\n", dev->hwdesc.bCapabilities);
802 	dprintk(1, " .dwDeviceRegistersLocation = 0x%x\n",
803 		dev->hwdesc.dwDeviceRegistersLocation);
804 
805 	dprintk(1, " .dwHostMemoryRegion = 0x%x\n",
806 		dev->hwdesc.dwHostMemoryRegion);
807 
808 	dprintk(1, " .dwHostMemoryRegionSize = 0x%x\n",
809 		dev->hwdesc.dwHostMemoryRegionSize);
810 
811 	dprintk(1, " .dwHostHibernatMemRegion = 0x%x\n",
812 		dev->hwdesc.dwHostHibernatMemRegion);
813 
814 	dprintk(1, " .dwHostHibernatMemRegionSize = 0x%x\n",
815 		dev->hwdesc.dwHostHibernatMemRegionSize);
816 }
817 
818 static void saa7164_dump_intfdesc(struct saa7164_dev *dev)
819 {
820 	dprintk(1, "@0x%p intfdesc sizeof(struct tmComResInterfaceDescr) = %d bytes\n",
821 		&dev->intfdesc, (u32)sizeof(struct tmComResInterfaceDescr));
822 
823 	dprintk(1, " .bLength = 0x%x\n", dev->intfdesc.bLength);
824 	dprintk(1, " .bDescriptorType = 0x%x\n", dev->intfdesc.bDescriptorType);
825 	dprintk(1, " .bDescriptorSubtype = 0x%x\n",
826 		dev->intfdesc.bDescriptorSubtype);
827 
828 	dprintk(1, " .bFlags = 0x%x\n", dev->intfdesc.bFlags);
829 	dprintk(1, " .bInterfaceType = 0x%x\n", dev->intfdesc.bInterfaceType);
830 	dprintk(1, " .bInterfaceId = 0x%x\n", dev->intfdesc.bInterfaceId);
831 	dprintk(1, " .bBaseInterface = 0x%x\n", dev->intfdesc.bBaseInterface);
832 	dprintk(1, " .bInterruptId = 0x%x\n", dev->intfdesc.bInterruptId);
833 	dprintk(1, " .bDebugInterruptId = 0x%x\n",
834 		dev->intfdesc.bDebugInterruptId);
835 
836 	dprintk(1, " .BARLocation = 0x%x\n", dev->intfdesc.BARLocation);
837 }
838 
839 static void saa7164_dump_busdesc(struct saa7164_dev *dev)
840 {
841 	dprintk(1, "@0x%p busdesc sizeof(struct tmComResBusDescr) = %d bytes\n",
842 		&dev->busdesc, (u32)sizeof(struct tmComResBusDescr));
843 
844 	dprintk(1, " .CommandRing   = 0x%016Lx\n", dev->busdesc.CommandRing);
845 	dprintk(1, " .ResponseRing  = 0x%016Lx\n", dev->busdesc.ResponseRing);
846 	dprintk(1, " .CommandWrite  = 0x%x\n", dev->busdesc.CommandWrite);
847 	dprintk(1, " .CommandRead   = 0x%x\n", dev->busdesc.CommandRead);
848 	dprintk(1, " .ResponseWrite = 0x%x\n", dev->busdesc.ResponseWrite);
849 	dprintk(1, " .ResponseRead  = 0x%x\n", dev->busdesc.ResponseRead);
850 }
851 
852 /* Much of the hardware configuration and PCI registers are configured
853  * dynamically depending on firmware. We have to cache some initial
854  * structures then use these to locate other important structures
855  * from PCI space.
856  */
857 static void saa7164_get_descriptors(struct saa7164_dev *dev)
858 {
859 	memcpy_fromio(&dev->hwdesc, dev->bmmio, sizeof(struct tmComResHWDescr));
860 	memcpy_fromio(&dev->intfdesc, dev->bmmio + sizeof(struct tmComResHWDescr),
861 		sizeof(struct tmComResInterfaceDescr));
862 	memcpy_fromio(&dev->busdesc, dev->bmmio + dev->intfdesc.BARLocation,
863 		sizeof(struct tmComResBusDescr));
864 
865 	if (dev->hwdesc.bLength != sizeof(struct tmComResHWDescr)) {
866 		printk(KERN_ERR "Structure struct tmComResHWDescr is mangled\n");
867 		printk(KERN_ERR "Need %x got %d\n", dev->hwdesc.bLength,
868 			(u32)sizeof(struct tmComResHWDescr));
869 	} else
870 		saa7164_dump_hwdesc(dev);
871 
872 	if (dev->intfdesc.bLength != sizeof(struct tmComResInterfaceDescr)) {
873 		printk(KERN_ERR "struct struct tmComResInterfaceDescr is mangled\n");
874 		printk(KERN_ERR "Need %x got %d\n", dev->intfdesc.bLength,
875 			(u32)sizeof(struct tmComResInterfaceDescr));
876 	} else
877 		saa7164_dump_intfdesc(dev);
878 
879 	saa7164_dump_busdesc(dev);
880 }
881 
882 static int saa7164_pci_quirks(struct saa7164_dev *dev)
883 {
884 	return 0;
885 }
886 
887 static int get_resources(struct saa7164_dev *dev)
888 {
889 	if (request_mem_region(pci_resource_start(dev->pci, 0),
890 		pci_resource_len(dev->pci, 0), dev->name)) {
891 
892 		if (request_mem_region(pci_resource_start(dev->pci, 2),
893 			pci_resource_len(dev->pci, 2), dev->name))
894 			return 0;
895 	}
896 
897 	printk(KERN_ERR "%s: can't get MMIO memory @ 0x%llx or 0x%llx\n",
898 		dev->name,
899 		(u64)pci_resource_start(dev->pci, 0),
900 		(u64)pci_resource_start(dev->pci, 2));
901 
902 	return -EBUSY;
903 }
904 
905 static int saa7164_port_init(struct saa7164_dev *dev, int portnr)
906 {
907 	struct saa7164_port *port = NULL;
908 
909 	if ((portnr < 0) || (portnr >= SAA7164_MAX_PORTS))
910 		BUG();
911 
912 	port = &dev->ports[portnr];
913 
914 	port->dev = dev;
915 	port->nr = portnr;
916 
917 	if ((portnr == SAA7164_PORT_TS1) || (portnr == SAA7164_PORT_TS2))
918 		port->type = SAA7164_MPEG_DVB;
919 	else
920 	if ((portnr == SAA7164_PORT_ENC1) || (portnr == SAA7164_PORT_ENC2)) {
921 		port->type = SAA7164_MPEG_ENCODER;
922 
923 		/* We need a deferred interrupt handler for cmd handling */
924 		INIT_WORK(&port->workenc, saa7164_work_enchandler);
925 	} else if ((portnr == SAA7164_PORT_VBI1) || (portnr == SAA7164_PORT_VBI2)) {
926 		port->type = SAA7164_MPEG_VBI;
927 
928 		/* We need a deferred interrupt handler for cmd handling */
929 		INIT_WORK(&port->workenc, saa7164_work_vbihandler);
930 	} else
931 		BUG();
932 
933 	/* Init all the critical resources */
934 	mutex_init(&port->dvb.lock);
935 	INIT_LIST_HEAD(&port->dmaqueue.list);
936 	mutex_init(&port->dmaqueue_lock);
937 
938 	INIT_LIST_HEAD(&port->list_buf_used.list);
939 	INIT_LIST_HEAD(&port->list_buf_free.list);
940 	init_waitqueue_head(&port->wait_read);
941 
942 
943 	saa7164_histogram_reset(&port->irq_interval, "irq intervals");
944 	saa7164_histogram_reset(&port->svc_interval, "deferred intervals");
945 	saa7164_histogram_reset(&port->irq_svc_interval,
946 		"irq to deferred intervals");
947 	saa7164_histogram_reset(&port->read_interval,
948 		"encoder/vbi read() intervals");
949 	saa7164_histogram_reset(&port->poll_interval,
950 		"encoder/vbi poll() intervals");
951 
952 	return 0;
953 }
954 
955 static int saa7164_dev_setup(struct saa7164_dev *dev)
956 {
957 	int i;
958 
959 	mutex_init(&dev->lock);
960 	atomic_inc(&dev->refcount);
961 	dev->nr = saa7164_devcount++;
962 
963 	snprintf(dev->name, sizeof(dev->name), "saa7164[%d]", dev->nr);
964 
965 	mutex_lock(&devlist);
966 	list_add_tail(&dev->devlist, &saa7164_devlist);
967 	mutex_unlock(&devlist);
968 
969 	/* board config */
970 	dev->board = UNSET;
971 	if (card[dev->nr] < saa7164_bcount)
972 		dev->board = card[dev->nr];
973 
974 	for (i = 0; UNSET == dev->board  &&  i < saa7164_idcount; i++)
975 		if (dev->pci->subsystem_vendor == saa7164_subids[i].subvendor &&
976 			dev->pci->subsystem_device ==
977 				saa7164_subids[i].subdevice)
978 				dev->board = saa7164_subids[i].card;
979 
980 	if (UNSET == dev->board) {
981 		dev->board = SAA7164_BOARD_UNKNOWN;
982 		saa7164_card_list(dev);
983 	}
984 
985 	dev->pci_bus  = dev->pci->bus->number;
986 	dev->pci_slot = PCI_SLOT(dev->pci->devfn);
987 
988 	/* I2C Defaults / setup */
989 	dev->i2c_bus[0].dev = dev;
990 	dev->i2c_bus[0].nr = 0;
991 	dev->i2c_bus[1].dev = dev;
992 	dev->i2c_bus[1].nr = 1;
993 	dev->i2c_bus[2].dev = dev;
994 	dev->i2c_bus[2].nr = 2;
995 
996 	/* Transport + Encoder ports 1, 2, 3, 4 - Defaults / setup */
997 	saa7164_port_init(dev, SAA7164_PORT_TS1);
998 	saa7164_port_init(dev, SAA7164_PORT_TS2);
999 	saa7164_port_init(dev, SAA7164_PORT_ENC1);
1000 	saa7164_port_init(dev, SAA7164_PORT_ENC2);
1001 	saa7164_port_init(dev, SAA7164_PORT_VBI1);
1002 	saa7164_port_init(dev, SAA7164_PORT_VBI2);
1003 
1004 	if (get_resources(dev) < 0) {
1005 		printk(KERN_ERR "CORE %s No more PCIe resources for subsystem: %04x:%04x\n",
1006 		       dev->name, dev->pci->subsystem_vendor,
1007 		       dev->pci->subsystem_device);
1008 
1009 		saa7164_devcount--;
1010 		return -ENODEV;
1011 	}
1012 
1013 	/* PCI/e allocations */
1014 	dev->lmmio = ioremap(pci_resource_start(dev->pci, 0),
1015 			     pci_resource_len(dev->pci, 0));
1016 
1017 	dev->lmmio2 = ioremap(pci_resource_start(dev->pci, 2),
1018 			     pci_resource_len(dev->pci, 2));
1019 
1020 	dev->bmmio = (u8 __iomem *)dev->lmmio;
1021 	dev->bmmio2 = (u8 __iomem *)dev->lmmio2;
1022 
1023 	/* Interrupt and ack register locations offset of bmmio */
1024 	dev->int_status = 0x183000 + 0xf80;
1025 	dev->int_ack = 0x183000 + 0xf90;
1026 
1027 	printk(KERN_INFO
1028 		"CORE %s: subsystem: %04x:%04x, board: %s [card=%d,%s]\n",
1029 	       dev->name, dev->pci->subsystem_vendor,
1030 	       dev->pci->subsystem_device, saa7164_boards[dev->board].name,
1031 	       dev->board, card[dev->nr] == dev->board ?
1032 	       "insmod option" : "autodetected");
1033 
1034 	saa7164_pci_quirks(dev);
1035 
1036 	return 0;
1037 }
1038 
1039 static void saa7164_dev_unregister(struct saa7164_dev *dev)
1040 {
1041 	dprintk(1, "%s()\n", __func__);
1042 
1043 	release_mem_region(pci_resource_start(dev->pci, 0),
1044 		pci_resource_len(dev->pci, 0));
1045 
1046 	release_mem_region(pci_resource_start(dev->pci, 2),
1047 		pci_resource_len(dev->pci, 2));
1048 
1049 	if (!atomic_dec_and_test(&dev->refcount))
1050 		return;
1051 
1052 	iounmap(dev->lmmio);
1053 	iounmap(dev->lmmio2);
1054 
1055 	return;
1056 }
1057 
1058 #ifdef CONFIG_PROC_FS
1059 static int saa7164_proc_show(struct seq_file *m, void *v)
1060 {
1061 	struct saa7164_dev *dev;
1062 	struct tmComResBusInfo *b;
1063 	struct list_head *list;
1064 	int i, c;
1065 
1066 	if (saa7164_devcount == 0)
1067 		return 0;
1068 
1069 	list_for_each(list, &saa7164_devlist) {
1070 		dev = list_entry(list, struct saa7164_dev, devlist);
1071 		seq_printf(m, "%s = %p\n", dev->name, dev);
1072 
1073 		/* Lock the bus from any other access */
1074 		b = &dev->bus;
1075 		mutex_lock(&b->lock);
1076 
1077 		seq_printf(m, " .m_pdwSetWritePos = 0x%x (0x%08x)\n",
1078 			b->m_dwSetReadPos, saa7164_readl(b->m_dwSetReadPos));
1079 
1080 		seq_printf(m, " .m_pdwSetReadPos  = 0x%x (0x%08x)\n",
1081 			b->m_dwSetWritePos, saa7164_readl(b->m_dwSetWritePos));
1082 
1083 		seq_printf(m, " .m_pdwGetWritePos = 0x%x (0x%08x)\n",
1084 			b->m_dwGetReadPos, saa7164_readl(b->m_dwGetReadPos));
1085 
1086 		seq_printf(m, " .m_pdwGetReadPos  = 0x%x (0x%08x)\n",
1087 			b->m_dwGetWritePos, saa7164_readl(b->m_dwGetWritePos));
1088 		c = 0;
1089 		seq_printf(m, "\n  Set Ring:\n");
1090 		seq_printf(m, "\n addr  00 01 02 03 04 05 06 07 08 09 0a 0b 0c 0d 0e 0f\n");
1091 		for (i = 0; i < b->m_dwSizeSetRing; i++) {
1092 			if (c == 0)
1093 				seq_printf(m, " %04x:", i);
1094 
1095 			seq_printf(m, " %02x", readb(b->m_pdwSetRing + i));
1096 
1097 			if (++c == 16) {
1098 				seq_printf(m, "\n");
1099 				c = 0;
1100 			}
1101 		}
1102 
1103 		c = 0;
1104 		seq_printf(m, "\n  Get Ring:\n");
1105 		seq_printf(m, "\n addr  00 01 02 03 04 05 06 07 08 09 0a 0b 0c 0d 0e 0f\n");
1106 		for (i = 0; i < b->m_dwSizeGetRing; i++) {
1107 			if (c == 0)
1108 				seq_printf(m, " %04x:", i);
1109 
1110 			seq_printf(m, " %02x", readb(b->m_pdwGetRing + i));
1111 
1112 			if (++c == 16) {
1113 				seq_printf(m, "\n");
1114 				c = 0;
1115 			}
1116 		}
1117 
1118 		mutex_unlock(&b->lock);
1119 
1120 	}
1121 
1122 	return 0;
1123 }
1124 
1125 static int saa7164_proc_create(void)
1126 {
1127 	struct proc_dir_entry *pe;
1128 
1129 	pe = proc_create_single("saa7164", S_IRUGO, NULL, saa7164_proc_show);
1130 	if (!pe)
1131 		return -ENOMEM;
1132 
1133 	return 0;
1134 }
1135 #endif
1136 
1137 static int saa7164_thread_function(void *data)
1138 {
1139 	struct saa7164_dev *dev = data;
1140 	struct tmFwInfoStruct fwinfo;
1141 	u64 last_poll_time = 0;
1142 
1143 	dprintk(DBGLVL_THR, "thread started\n");
1144 
1145 	set_freezable();
1146 
1147 	while (1) {
1148 		msleep_interruptible(100);
1149 		if (kthread_should_stop())
1150 			break;
1151 		try_to_freeze();
1152 
1153 		dprintk(DBGLVL_THR, "thread running\n");
1154 
1155 		/* Dump the firmware debug message to console */
1156 		/* Polling this costs us 1-2% of the arm CPU */
1157 		/* convert this into a respnde to interrupt 0x7a */
1158 		saa7164_api_collect_debug(dev);
1159 
1160 		/* Monitor CPU load every 1 second */
1161 		if ((last_poll_time + 1000 /* ms */) < jiffies_to_msecs(jiffies)) {
1162 			saa7164_api_get_load_info(dev, &fwinfo);
1163 			last_poll_time = jiffies_to_msecs(jiffies);
1164 		}
1165 
1166 	}
1167 
1168 	dprintk(DBGLVL_THR, "thread exiting\n");
1169 	return 0;
1170 }
1171 
1172 static bool saa7164_enable_msi(struct pci_dev *pci_dev, struct saa7164_dev *dev)
1173 {
1174 	int err;
1175 
1176 	if (!enable_msi) {
1177 		printk(KERN_WARNING "%s() MSI disabled by module parameter 'enable_msi'"
1178 		       , __func__);
1179 		return false;
1180 	}
1181 
1182 	err = pci_enable_msi(pci_dev);
1183 
1184 	if (err) {
1185 		printk(KERN_ERR "%s() Failed to enable MSI interrupt. Falling back to a shared IRQ\n",
1186 		       __func__);
1187 		return false;
1188 	}
1189 
1190 	/* no error - so request an msi interrupt */
1191 	err = request_irq(pci_dev->irq, saa7164_irq, 0,
1192 						dev->name, dev);
1193 
1194 	if (err) {
1195 		/* fall back to legacy interrupt */
1196 		printk(KERN_ERR "%s() Failed to get an MSI interrupt. Falling back to a shared IRQ\n",
1197 		       __func__);
1198 		pci_disable_msi(pci_dev);
1199 		return false;
1200 	}
1201 
1202 	return true;
1203 }
1204 
1205 static int saa7164_initdev(struct pci_dev *pci_dev,
1206 			   const struct pci_device_id *pci_id)
1207 {
1208 	struct saa7164_dev *dev;
1209 	int err, i;
1210 	u32 version;
1211 
1212 	dev = kzalloc(sizeof(*dev), GFP_KERNEL);
1213 	if (NULL == dev)
1214 		return -ENOMEM;
1215 
1216 	err = v4l2_device_register(&pci_dev->dev, &dev->v4l2_dev);
1217 	if (err < 0) {
1218 		dev_err(&pci_dev->dev, "v4l2_device_register failed\n");
1219 		goto fail_free;
1220 	}
1221 
1222 	/* pci init */
1223 	dev->pci = pci_dev;
1224 	if (pci_enable_device(pci_dev)) {
1225 		err = -EIO;
1226 		goto fail_free;
1227 	}
1228 
1229 	if (saa7164_dev_setup(dev) < 0) {
1230 		err = -EINVAL;
1231 		goto fail_free;
1232 	}
1233 
1234 	/* print pci info */
1235 	dev->pci_rev = pci_dev->revision;
1236 	pci_read_config_byte(pci_dev, PCI_LATENCY_TIMER,  &dev->pci_lat);
1237 	printk(KERN_INFO "%s/0: found at %s, rev: %d, irq: %d, latency: %d, mmio: 0x%llx\n",
1238 	       dev->name,
1239 	       pci_name(pci_dev), dev->pci_rev, pci_dev->irq,
1240 	       dev->pci_lat,
1241 		(unsigned long long)pci_resource_start(pci_dev, 0));
1242 
1243 	pci_set_master(pci_dev);
1244 	/* TODO */
1245 	err = pci_set_dma_mask(pci_dev, 0xffffffff);
1246 	if (err) {
1247 		printk("%s/0: Oops: no 32bit PCI DMA ???\n", dev->name);
1248 		goto fail_irq;
1249 	}
1250 
1251 	/* irq bit */
1252 	if (saa7164_enable_msi(pci_dev, dev)) {
1253 		dev->msi = true;
1254 	} else {
1255 		/* if we have an error (i.e. we don't have an interrupt)
1256 			 or msi is not enabled - fallback to shared interrupt */
1257 
1258 		err = request_irq(pci_dev->irq, saa7164_irq,
1259 				IRQF_SHARED, dev->name, dev);
1260 
1261 		if (err < 0) {
1262 			printk(KERN_ERR "%s: can't get IRQ %d\n", dev->name,
1263 			       pci_dev->irq);
1264 			err = -EIO;
1265 			goto fail_irq;
1266 		}
1267 	}
1268 
1269 	pci_set_drvdata(pci_dev, dev);
1270 
1271 	/* Init the internal command list */
1272 	for (i = 0; i < SAA_CMD_MAX_MSG_UNITS; i++) {
1273 		dev->cmds[i].seqno = i;
1274 		dev->cmds[i].inuse = 0;
1275 		mutex_init(&dev->cmds[i].lock);
1276 		init_waitqueue_head(&dev->cmds[i].wait);
1277 	}
1278 
1279 	/* We need a deferred interrupt handler for cmd handling */
1280 	INIT_WORK(&dev->workcmd, saa7164_work_cmdhandler);
1281 
1282 	/* Only load the firmware if we know the board */
1283 	if (dev->board != SAA7164_BOARD_UNKNOWN) {
1284 
1285 		err = saa7164_downloadfirmware(dev);
1286 		if (err < 0) {
1287 			printk(KERN_ERR
1288 				"Failed to boot firmware, no features registered\n");
1289 			goto fail_fw;
1290 		}
1291 
1292 		saa7164_get_descriptors(dev);
1293 		saa7164_dumpregs(dev, 0);
1294 		saa7164_getcurrentfirmwareversion(dev);
1295 		saa7164_getfirmwarestatus(dev);
1296 		err = saa7164_bus_setup(dev);
1297 		if (err < 0)
1298 			printk(KERN_ERR
1299 				"Failed to setup the bus, will continue\n");
1300 		saa7164_bus_dump(dev);
1301 
1302 		/* Ping the running firmware via the command bus and get the
1303 		 * firmware version, this checks the bus is running OK.
1304 		 */
1305 		version = 0;
1306 		if (saa7164_api_get_fw_version(dev, &version) == SAA_OK)
1307 			dprintk(1, "Bus is operating correctly using version %d.%d.%d.%d (0x%x)\n",
1308 				(version & 0x0000fc00) >> 10,
1309 				(version & 0x000003e0) >> 5,
1310 				(version & 0x0000001f),
1311 				(version & 0xffff0000) >> 16,
1312 				version);
1313 		else
1314 			printk(KERN_ERR
1315 				"Failed to communicate with the firmware\n");
1316 
1317 		/* Bring up the I2C buses */
1318 		saa7164_i2c_register(&dev->i2c_bus[0]);
1319 		saa7164_i2c_register(&dev->i2c_bus[1]);
1320 		saa7164_i2c_register(&dev->i2c_bus[2]);
1321 		saa7164_gpio_setup(dev);
1322 		saa7164_card_setup(dev);
1323 
1324 		/* Parse the dynamic device configuration, find various
1325 		 * media endpoints (MPEG, WMV, PS, TS) and cache their
1326 		 * configuration details into the driver, so we can
1327 		 * reference them later during simething_register() func,
1328 		 * interrupt handlers, deferred work handlers etc.
1329 		 */
1330 		saa7164_api_enum_subdevs(dev);
1331 
1332 		/* Begin to create the video sub-systems and register funcs */
1333 		if (saa7164_boards[dev->board].porta == SAA7164_MPEG_DVB) {
1334 			if (saa7164_dvb_register(&dev->ports[SAA7164_PORT_TS1]) < 0) {
1335 				printk(KERN_ERR "%s() Failed to register dvb adapters on porta\n",
1336 					__func__);
1337 			}
1338 		}
1339 
1340 		if (saa7164_boards[dev->board].portb == SAA7164_MPEG_DVB) {
1341 			if (saa7164_dvb_register(&dev->ports[SAA7164_PORT_TS2]) < 0) {
1342 				printk(KERN_ERR"%s() Failed to register dvb adapters on portb\n",
1343 					__func__);
1344 			}
1345 		}
1346 
1347 		if (saa7164_boards[dev->board].portc == SAA7164_MPEG_ENCODER) {
1348 			if (saa7164_encoder_register(&dev->ports[SAA7164_PORT_ENC1]) < 0) {
1349 				printk(KERN_ERR"%s() Failed to register mpeg encoder\n",
1350 				       __func__);
1351 			}
1352 		}
1353 
1354 		if (saa7164_boards[dev->board].portd == SAA7164_MPEG_ENCODER) {
1355 			if (saa7164_encoder_register(&dev->ports[SAA7164_PORT_ENC2]) < 0) {
1356 				printk(KERN_ERR"%s() Failed to register mpeg encoder\n",
1357 				       __func__);
1358 			}
1359 		}
1360 
1361 		if (saa7164_boards[dev->board].porte == SAA7164_MPEG_VBI) {
1362 			if (saa7164_vbi_register(&dev->ports[SAA7164_PORT_VBI1]) < 0) {
1363 				printk(KERN_ERR"%s() Failed to register vbi device\n",
1364 				       __func__);
1365 			}
1366 		}
1367 
1368 		if (saa7164_boards[dev->board].portf == SAA7164_MPEG_VBI) {
1369 			if (saa7164_vbi_register(&dev->ports[SAA7164_PORT_VBI2]) < 0) {
1370 				printk(KERN_ERR"%s() Failed to register vbi device\n",
1371 				       __func__);
1372 			}
1373 		}
1374 		saa7164_api_set_debug(dev, fw_debug);
1375 
1376 		if (fw_debug) {
1377 			dev->kthread = kthread_run(saa7164_thread_function, dev,
1378 				"saa7164 debug");
1379 			if (IS_ERR(dev->kthread)) {
1380 				dev->kthread = NULL;
1381 				printk(KERN_ERR "%s() Failed to create debug kernel thread\n",
1382 				       __func__);
1383 			}
1384 		}
1385 
1386 	} /* != BOARD_UNKNOWN */
1387 	else
1388 		printk(KERN_ERR "%s() Unsupported board detected, registering without firmware\n",
1389 		       __func__);
1390 
1391 	dprintk(1, "%s() parameter debug = %d\n", __func__, saa_debug);
1392 	dprintk(1, "%s() parameter waitsecs = %d\n", __func__, waitsecs);
1393 
1394 fail_fw:
1395 	return 0;
1396 
1397 fail_irq:
1398 	saa7164_dev_unregister(dev);
1399 fail_free:
1400 	v4l2_device_unregister(&dev->v4l2_dev);
1401 	kfree(dev);
1402 	return err;
1403 }
1404 
1405 static void saa7164_shutdown(struct saa7164_dev *dev)
1406 {
1407 	dprintk(1, "%s()\n", __func__);
1408 }
1409 
1410 static void saa7164_finidev(struct pci_dev *pci_dev)
1411 {
1412 	struct saa7164_dev *dev = pci_get_drvdata(pci_dev);
1413 
1414 	if (dev->board != SAA7164_BOARD_UNKNOWN) {
1415 		if (fw_debug && dev->kthread) {
1416 			kthread_stop(dev->kthread);
1417 			dev->kthread = NULL;
1418 		}
1419 		if (dev->firmwareloaded)
1420 			saa7164_api_set_debug(dev, 0x00);
1421 	}
1422 
1423 	saa7164_histogram_print(&dev->ports[SAA7164_PORT_ENC1],
1424 		&dev->ports[SAA7164_PORT_ENC1].irq_interval);
1425 	saa7164_histogram_print(&dev->ports[SAA7164_PORT_ENC1],
1426 		&dev->ports[SAA7164_PORT_ENC1].svc_interval);
1427 	saa7164_histogram_print(&dev->ports[SAA7164_PORT_ENC1],
1428 		&dev->ports[SAA7164_PORT_ENC1].irq_svc_interval);
1429 	saa7164_histogram_print(&dev->ports[SAA7164_PORT_ENC1],
1430 		&dev->ports[SAA7164_PORT_ENC1].read_interval);
1431 	saa7164_histogram_print(&dev->ports[SAA7164_PORT_ENC1],
1432 		&dev->ports[SAA7164_PORT_ENC1].poll_interval);
1433 	saa7164_histogram_print(&dev->ports[SAA7164_PORT_VBI1],
1434 		&dev->ports[SAA7164_PORT_VBI1].read_interval);
1435 	saa7164_histogram_print(&dev->ports[SAA7164_PORT_VBI2],
1436 		&dev->ports[SAA7164_PORT_VBI2].poll_interval);
1437 
1438 	saa7164_shutdown(dev);
1439 
1440 	if (saa7164_boards[dev->board].porta == SAA7164_MPEG_DVB)
1441 		saa7164_dvb_unregister(&dev->ports[SAA7164_PORT_TS1]);
1442 
1443 	if (saa7164_boards[dev->board].portb == SAA7164_MPEG_DVB)
1444 		saa7164_dvb_unregister(&dev->ports[SAA7164_PORT_TS2]);
1445 
1446 	if (saa7164_boards[dev->board].portc == SAA7164_MPEG_ENCODER)
1447 		saa7164_encoder_unregister(&dev->ports[SAA7164_PORT_ENC1]);
1448 
1449 	if (saa7164_boards[dev->board].portd == SAA7164_MPEG_ENCODER)
1450 		saa7164_encoder_unregister(&dev->ports[SAA7164_PORT_ENC2]);
1451 
1452 	if (saa7164_boards[dev->board].porte == SAA7164_MPEG_VBI)
1453 		saa7164_vbi_unregister(&dev->ports[SAA7164_PORT_VBI1]);
1454 
1455 	if (saa7164_boards[dev->board].portf == SAA7164_MPEG_VBI)
1456 		saa7164_vbi_unregister(&dev->ports[SAA7164_PORT_VBI2]);
1457 
1458 	saa7164_i2c_unregister(&dev->i2c_bus[0]);
1459 	saa7164_i2c_unregister(&dev->i2c_bus[1]);
1460 	saa7164_i2c_unregister(&dev->i2c_bus[2]);
1461 
1462 	/* unregister stuff */
1463 	free_irq(pci_dev->irq, dev);
1464 
1465 	if (dev->msi) {
1466 		pci_disable_msi(pci_dev);
1467 		dev->msi = false;
1468 	}
1469 
1470 	pci_disable_device(pci_dev);
1471 
1472 	mutex_lock(&devlist);
1473 	list_del(&dev->devlist);
1474 	mutex_unlock(&devlist);
1475 
1476 	saa7164_dev_unregister(dev);
1477 	v4l2_device_unregister(&dev->v4l2_dev);
1478 	kfree(dev);
1479 }
1480 
1481 static const struct pci_device_id saa7164_pci_tbl[] = {
1482 	{
1483 		/* SAA7164 */
1484 		.vendor       = 0x1131,
1485 		.device       = 0x7164,
1486 		.subvendor    = PCI_ANY_ID,
1487 		.subdevice    = PCI_ANY_ID,
1488 	}, {
1489 		/* --- end of list --- */
1490 	}
1491 };
1492 MODULE_DEVICE_TABLE(pci, saa7164_pci_tbl);
1493 
1494 static struct pci_driver saa7164_pci_driver = {
1495 	.name     = "saa7164",
1496 	.id_table = saa7164_pci_tbl,
1497 	.probe    = saa7164_initdev,
1498 	.remove   = saa7164_finidev,
1499 	/* TODO */
1500 	.suspend  = NULL,
1501 	.resume   = NULL,
1502 };
1503 
1504 static int __init saa7164_init(void)
1505 {
1506 	printk(KERN_INFO "saa7164 driver loaded\n");
1507 
1508 #ifdef CONFIG_PROC_FS
1509 	saa7164_proc_create();
1510 #endif
1511 	return pci_register_driver(&saa7164_pci_driver);
1512 }
1513 
1514 static void __exit saa7164_fini(void)
1515 {
1516 #ifdef CONFIG_PROC_FS
1517 	remove_proc_entry("saa7164", NULL);
1518 #endif
1519 	pci_unregister_driver(&saa7164_pci_driver);
1520 }
1521 
1522 module_init(saa7164_init);
1523 module_exit(saa7164_fini);
1524 
1525