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