1 /*
2  * dvb_ca.c: generic DVB functions for EN50221 CAM interfaces
3  *
4  * Copyright (C) 2004 Andrew de Quincey
5  *
6  * Parts of this file were based on sources as follows:
7  *
8  * Copyright (C) 2003 Ralph Metzler <rjkm@metzlerbros.de>
9  *
10  * based on code:
11  *
12  * Copyright (C) 1999-2002 Ralph  Metzler
13  *                       & Marcus Metzler for convergence integrated media GmbH
14  *
15  * This program is free software; you can redistribute it and/or
16  * modify it under the terms of the GNU General Public License
17  * as published by the Free Software Foundation; either version 2
18  * of the License, or (at your option) any later version.
19  *
20  * This program is distributed in the hope that it will be useful,
21  * but WITHOUT ANY WARRANTY; without even the implied warranty of
22  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
23  * GNU General Public License for more details.
24  * To obtain the license, point your browser to
25  * http://www.gnu.org/copyleft/gpl.html
26  */
27 
28 #define pr_fmt(fmt) "dvb_ca_en50221: " fmt
29 
30 #include <linux/errno.h>
31 #include <linux/slab.h>
32 #include <linux/list.h>
33 #include <linux/module.h>
34 #include <linux/vmalloc.h>
35 #include <linux/delay.h>
36 #include <linux/spinlock.h>
37 #include <linux/sched/signal.h>
38 #include <linux/kthread.h>
39 
40 #include "dvb_ca_en50221.h"
41 #include "dvb_ringbuffer.h"
42 
43 static int dvb_ca_en50221_debug;
44 
45 module_param_named(cam_debug, dvb_ca_en50221_debug, int, 0644);
46 MODULE_PARM_DESC(cam_debug, "enable verbose debug messages");
47 
48 #define dprintk(fmt, arg...) do {					\
49 	if (dvb_ca_en50221_debug)					\
50 		printk(KERN_DEBUG pr_fmt("%s: " fmt), __func__, ##arg);\
51 } while (0)
52 
53 #define INIT_TIMEOUT_SECS 10
54 
55 #define HOST_LINK_BUF_SIZE 0x200
56 
57 #define RX_BUFFER_SIZE 65535
58 
59 #define MAX_RX_PACKETS_PER_ITERATION 10
60 
61 #define CTRLIF_DATA      0
62 #define CTRLIF_COMMAND   1
63 #define CTRLIF_STATUS    1
64 #define CTRLIF_SIZE_LOW  2
65 #define CTRLIF_SIZE_HIGH 3
66 
67 #define CMDREG_HC        1	/* Host control */
68 #define CMDREG_SW        2	/* Size write */
69 #define CMDREG_SR        4	/* Size read */
70 #define CMDREG_RS        8	/* Reset interface */
71 #define CMDREG_FRIE   0x40	/* Enable FR interrupt */
72 #define CMDREG_DAIE   0x80	/* Enable DA interrupt */
73 #define IRQEN (CMDREG_DAIE)
74 
75 #define STATUSREG_RE     1	/* read error */
76 #define STATUSREG_WE     2	/* write error */
77 #define STATUSREG_FR  0x40	/* module free */
78 #define STATUSREG_DA  0x80	/* data available */
79 #define STATUSREG_TXERR (STATUSREG_RE|STATUSREG_WE)	/* general transfer error */
80 
81 
82 #define DVB_CA_SLOTSTATE_NONE           0
83 #define DVB_CA_SLOTSTATE_UNINITIALISED  1
84 #define DVB_CA_SLOTSTATE_RUNNING        2
85 #define DVB_CA_SLOTSTATE_INVALID        3
86 #define DVB_CA_SLOTSTATE_WAITREADY      4
87 #define DVB_CA_SLOTSTATE_VALIDATE       5
88 #define DVB_CA_SLOTSTATE_WAITFR         6
89 #define DVB_CA_SLOTSTATE_LINKINIT       7
90 
91 
92 /* Information on a CA slot */
93 struct dvb_ca_slot {
94 
95 	/* current state of the CAM */
96 	int slot_state;
97 
98 	/* mutex used for serializing access to one CI slot */
99 	struct mutex slot_lock;
100 
101 	/* Number of CAMCHANGES that have occurred since last processing */
102 	atomic_t camchange_count;
103 
104 	/* Type of last CAMCHANGE */
105 	int camchange_type;
106 
107 	/* base address of CAM config */
108 	u32 config_base;
109 
110 	/* value to write into Config Control register */
111 	u8 config_option;
112 
113 	/* if 1, the CAM supports DA IRQs */
114 	u8 da_irq_supported:1;
115 
116 	/* size of the buffer to use when talking to the CAM */
117 	int link_buf_size;
118 
119 	/* buffer for incoming packets */
120 	struct dvb_ringbuffer rx_buffer;
121 
122 	/* timer used during various states of the slot */
123 	unsigned long timeout;
124 };
125 
126 /* Private CA-interface information */
127 struct dvb_ca_private {
128 	struct kref refcount;
129 
130 	/* pointer back to the public data structure */
131 	struct dvb_ca_en50221 *pub;
132 
133 	/* the DVB device */
134 	struct dvb_device *dvbdev;
135 
136 	/* Flags describing the interface (DVB_CA_FLAG_*) */
137 	u32 flags;
138 
139 	/* number of slots supported by this CA interface */
140 	unsigned int slot_count;
141 
142 	/* information on each slot */
143 	struct dvb_ca_slot *slot_info;
144 
145 	/* wait queues for read() and write() operations */
146 	wait_queue_head_t wait_queue;
147 
148 	/* PID of the monitoring thread */
149 	struct task_struct *thread;
150 
151 	/* Flag indicating if the CA device is open */
152 	unsigned int open:1;
153 
154 	/* Flag indicating the thread should wake up now */
155 	unsigned int wakeup:1;
156 
157 	/* Delay the main thread should use */
158 	unsigned long delay;
159 
160 	/* Slot to start looking for data to read from in the next user-space read operation */
161 	int next_read_slot;
162 
163 	/* mutex serializing ioctls */
164 	struct mutex ioctl_mutex;
165 };
166 
167 static void dvb_ca_private_free(struct dvb_ca_private *ca)
168 {
169 	unsigned int i;
170 
171 	dvb_free_device(ca->dvbdev);
172 	for (i = 0; i < ca->slot_count; i++)
173 		vfree(ca->slot_info[i].rx_buffer.data);
174 
175 	kfree(ca->slot_info);
176 	kfree(ca);
177 }
178 
179 static void dvb_ca_private_release(struct kref *ref)
180 {
181 	struct dvb_ca_private *ca = container_of(ref, struct dvb_ca_private, refcount);
182 	dvb_ca_private_free(ca);
183 }
184 
185 static void dvb_ca_private_get(struct dvb_ca_private *ca)
186 {
187 	kref_get(&ca->refcount);
188 }
189 
190 static void dvb_ca_private_put(struct dvb_ca_private *ca)
191 {
192 	kref_put(&ca->refcount, dvb_ca_private_release);
193 }
194 
195 static void dvb_ca_en50221_thread_wakeup(struct dvb_ca_private *ca);
196 static int dvb_ca_en50221_read_data(struct dvb_ca_private *ca, int slot,
197 				    u8 *ebuf, int ecount);
198 static int dvb_ca_en50221_write_data(struct dvb_ca_private *ca, int slot,
199 				     u8 *ebuf, int ecount);
200 
201 
202 /**
203  * Safely find needle in haystack.
204  *
205  * @haystack: Buffer to look in.
206  * @hlen: Number of bytes in haystack.
207  * @needle: Buffer to find.
208  * @nlen: Number of bytes in needle.
209  * @return Pointer into haystack needle was found at, or NULL if not found.
210  */
211 static char *findstr(char *haystack, int hlen, char *needle, int nlen)
212 {
213 	int i;
214 
215 	if (hlen < nlen)
216 		return NULL;
217 
218 	for (i = 0; i <= hlen - nlen; i++) {
219 		if (!strncmp(haystack + i, needle, nlen))
220 			return haystack + i;
221 	}
222 
223 	return NULL;
224 }
225 
226 
227 
228 /* ******************************************************************************** */
229 /* EN50221 physical interface functions */
230 
231 
232 /**
233  * dvb_ca_en50221_check_camstatus - Check CAM status.
234  */
235 static int dvb_ca_en50221_check_camstatus(struct dvb_ca_private *ca, int slot)
236 {
237 	int slot_status;
238 	int cam_present_now;
239 	int cam_changed;
240 
241 	/* IRQ mode */
242 	if (ca->flags & DVB_CA_EN50221_FLAG_IRQ_CAMCHANGE) {
243 		return (atomic_read(&ca->slot_info[slot].camchange_count) != 0);
244 	}
245 
246 	/* poll mode */
247 	slot_status = ca->pub->poll_slot_status(ca->pub, slot, ca->open);
248 
249 	cam_present_now = (slot_status & DVB_CA_EN50221_POLL_CAM_PRESENT) ? 1 : 0;
250 	cam_changed = (slot_status & DVB_CA_EN50221_POLL_CAM_CHANGED) ? 1 : 0;
251 	if (!cam_changed) {
252 		int cam_present_old = (ca->slot_info[slot].slot_state != DVB_CA_SLOTSTATE_NONE);
253 		cam_changed = (cam_present_now != cam_present_old);
254 	}
255 
256 	if (cam_changed) {
257 		if (!cam_present_now) {
258 			ca->slot_info[slot].camchange_type = DVB_CA_EN50221_CAMCHANGE_REMOVED;
259 		} else {
260 			ca->slot_info[slot].camchange_type = DVB_CA_EN50221_CAMCHANGE_INSERTED;
261 		}
262 		atomic_set(&ca->slot_info[slot].camchange_count, 1);
263 	} else {
264 		if ((ca->slot_info[slot].slot_state == DVB_CA_SLOTSTATE_WAITREADY) &&
265 		    (slot_status & DVB_CA_EN50221_POLL_CAM_READY)) {
266 			// move to validate state if reset is completed
267 			ca->slot_info[slot].slot_state = DVB_CA_SLOTSTATE_VALIDATE;
268 		}
269 	}
270 
271 	return cam_changed;
272 }
273 
274 
275 /**
276  * dvb_ca_en50221_wait_if_status - Wait for flags to become set on the STATUS
277  *	 register on a CAM interface, checking for errors and timeout.
278  *
279  * @ca: CA instance.
280  * @slot: Slot on interface.
281  * @waitfor: Flags to wait for.
282  * @timeout_ms: Timeout in milliseconds.
283  *
284  * @return 0 on success, nonzero on error.
285  */
286 static int dvb_ca_en50221_wait_if_status(struct dvb_ca_private *ca, int slot,
287 					 u8 waitfor, int timeout_hz)
288 {
289 	unsigned long timeout;
290 	unsigned long start;
291 
292 	dprintk("%s\n", __func__);
293 
294 	/* loop until timeout elapsed */
295 	start = jiffies;
296 	timeout = jiffies + timeout_hz;
297 	while (1) {
298 		/* read the status and check for error */
299 		int res = ca->pub->read_cam_control(ca->pub, slot, CTRLIF_STATUS);
300 		if (res < 0)
301 			return -EIO;
302 
303 		/* if we got the flags, it was successful! */
304 		if (res & waitfor) {
305 			dprintk("%s succeeded timeout:%lu\n",
306 				__func__, jiffies - start);
307 			return 0;
308 		}
309 
310 		/* check for timeout */
311 		if (time_after(jiffies, timeout)) {
312 			break;
313 		}
314 
315 		/* wait for a bit */
316 		msleep(1);
317 	}
318 
319 	dprintk("%s failed timeout:%lu\n", __func__, jiffies - start);
320 
321 	/* if we get here, we've timed out */
322 	return -ETIMEDOUT;
323 }
324 
325 
326 /**
327  * dvb_ca_en50221_link_init - Initialise the link layer connection to a CAM.
328  *
329  * @ca: CA instance.
330  * @slot: Slot id.
331  *
332  * @return 0 on success, nonzero on failure.
333  */
334 static int dvb_ca_en50221_link_init(struct dvb_ca_private *ca, int slot)
335 {
336 	int ret;
337 	int buf_size;
338 	u8 buf[2];
339 
340 	dprintk("%s\n", __func__);
341 
342 	/* we'll be determining these during this function */
343 	ca->slot_info[slot].da_irq_supported = 0;
344 
345 	/* set the host link buffer size temporarily. it will be overwritten with the
346 	 * real negotiated size later. */
347 	ca->slot_info[slot].link_buf_size = 2;
348 
349 	/* read the buffer size from the CAM */
350 	if ((ret = ca->pub->write_cam_control(ca->pub, slot, CTRLIF_COMMAND, IRQEN | CMDREG_SR)) != 0)
351 		return ret;
352 	ret = dvb_ca_en50221_wait_if_status(ca, slot, STATUSREG_DA, HZ);
353 	if (ret != 0)
354 		return ret;
355 	if ((ret = dvb_ca_en50221_read_data(ca, slot, buf, 2)) != 2)
356 		return -EIO;
357 	if ((ret = ca->pub->write_cam_control(ca->pub, slot, CTRLIF_COMMAND, IRQEN)) != 0)
358 		return ret;
359 
360 	/* store it, and choose the minimum of our buffer and the CAM's buffer size */
361 	buf_size = (buf[0] << 8) | buf[1];
362 	if (buf_size > HOST_LINK_BUF_SIZE)
363 		buf_size = HOST_LINK_BUF_SIZE;
364 	ca->slot_info[slot].link_buf_size = buf_size;
365 	buf[0] = buf_size >> 8;
366 	buf[1] = buf_size & 0xff;
367 	dprintk("Chosen link buffer size of %i\n", buf_size);
368 
369 	/* write the buffer size to the CAM */
370 	if ((ret = ca->pub->write_cam_control(ca->pub, slot, CTRLIF_COMMAND, IRQEN | CMDREG_SW)) != 0)
371 		return ret;
372 	if ((ret = dvb_ca_en50221_wait_if_status(ca, slot, STATUSREG_FR, HZ / 10)) != 0)
373 		return ret;
374 	if ((ret = dvb_ca_en50221_write_data(ca, slot, buf, 2)) != 2)
375 		return -EIO;
376 	if ((ret = ca->pub->write_cam_control(ca->pub, slot, CTRLIF_COMMAND, IRQEN)) != 0)
377 		return ret;
378 
379 	/* success */
380 	return 0;
381 }
382 
383 /**
384  * dvb_ca_en50221_read_tuple - Read a tuple from attribute memory.
385  *
386  * @ca: CA instance.
387  * @slot: Slot id.
388  * @address: Address to read from. Updated.
389  * @tupleType: Tuple id byte. Updated.
390  * @tupleLength: Tuple length. Updated.
391  * @tuple: Dest buffer for tuple (must be 256 bytes). Updated.
392  *
393  * @return 0 on success, nonzero on error.
394  */
395 static int dvb_ca_en50221_read_tuple(struct dvb_ca_private *ca, int slot,
396 				     int *address, int *tupleType,
397 				     int *tupleLength, u8 *tuple)
398 {
399 	int i;
400 	int _tupleType;
401 	int _tupleLength;
402 	int _address = *address;
403 
404 	/* grab the next tuple length and type */
405 	if ((_tupleType = ca->pub->read_attribute_mem(ca->pub, slot, _address)) < 0)
406 		return _tupleType;
407 	if (_tupleType == 0xff) {
408 		dprintk("END OF CHAIN TUPLE type:0x%x\n", _tupleType);
409 		*address += 2;
410 		*tupleType = _tupleType;
411 		*tupleLength = 0;
412 		return 0;
413 	}
414 	if ((_tupleLength = ca->pub->read_attribute_mem(ca->pub, slot, _address + 2)) < 0)
415 		return _tupleLength;
416 	_address += 4;
417 
418 	dprintk("TUPLE type:0x%x length:%i\n", _tupleType, _tupleLength);
419 
420 	/* read in the whole tuple */
421 	for (i = 0; i < _tupleLength; i++) {
422 		tuple[i] = ca->pub->read_attribute_mem(ca->pub, slot, _address + (i * 2));
423 		dprintk("  0x%02x: 0x%02x %c\n",
424 			i, tuple[i] & 0xff,
425 			((tuple[i] > 31) && (tuple[i] < 127)) ? tuple[i] : '.');
426 	}
427 	_address += (_tupleLength * 2);
428 
429 	// success
430 	*tupleType = _tupleType;
431 	*tupleLength = _tupleLength;
432 	*address = _address;
433 	return 0;
434 }
435 
436 
437 /**
438  * dvb_ca_en50221_parse_attributes - Parse attribute memory of a CAM module,
439  *	extracting Config register, and checking it is a DVB CAM module.
440  *
441  * @ca: CA instance.
442  * @slot: Slot id.
443  *
444  * @return 0 on success, <0 on failure.
445  */
446 static int dvb_ca_en50221_parse_attributes(struct dvb_ca_private *ca, int slot)
447 {
448 	int address = 0;
449 	int tupleLength;
450 	int tupleType;
451 	u8 tuple[257];
452 	char *dvb_str;
453 	int rasz;
454 	int status;
455 	int got_cftableentry = 0;
456 	int end_chain = 0;
457 	int i;
458 	u16 manfid = 0;
459 	u16 devid = 0;
460 
461 
462 	// CISTPL_DEVICE_0A
463 	if ((status =
464 	     dvb_ca_en50221_read_tuple(ca, slot, &address, &tupleType, &tupleLength, tuple)) < 0)
465 		return status;
466 	if (tupleType != 0x1D)
467 		return -EINVAL;
468 
469 
470 
471 	// CISTPL_DEVICE_0C
472 	if ((status =
473 	     dvb_ca_en50221_read_tuple(ca, slot, &address, &tupleType, &tupleLength, tuple)) < 0)
474 		return status;
475 	if (tupleType != 0x1C)
476 		return -EINVAL;
477 
478 
479 
480 	// CISTPL_VERS_1
481 	if ((status =
482 	     dvb_ca_en50221_read_tuple(ca, slot, &address, &tupleType, &tupleLength, tuple)) < 0)
483 		return status;
484 	if (tupleType != 0x15)
485 		return -EINVAL;
486 
487 
488 
489 	// CISTPL_MANFID
490 	if ((status = dvb_ca_en50221_read_tuple(ca, slot, &address, &tupleType,
491 						&tupleLength, tuple)) < 0)
492 		return status;
493 	if (tupleType != 0x20)
494 		return -EINVAL;
495 	if (tupleLength != 4)
496 		return -EINVAL;
497 	manfid = (tuple[1] << 8) | tuple[0];
498 	devid = (tuple[3] << 8) | tuple[2];
499 
500 
501 
502 	// CISTPL_CONFIG
503 	if ((status = dvb_ca_en50221_read_tuple(ca, slot, &address, &tupleType,
504 						&tupleLength, tuple)) < 0)
505 		return status;
506 	if (tupleType != 0x1A)
507 		return -EINVAL;
508 	if (tupleLength < 3)
509 		return -EINVAL;
510 
511 	/* extract the configbase */
512 	rasz = tuple[0] & 3;
513 	if (tupleLength < (3 + rasz + 14))
514 		return -EINVAL;
515 	ca->slot_info[slot].config_base = 0;
516 	for (i = 0; i < rasz + 1; i++) {
517 		ca->slot_info[slot].config_base |= (tuple[2 + i] << (8 * i));
518 	}
519 
520 	/* check it contains the correct DVB string */
521 	dvb_str = findstr((char *)tuple, tupleLength, "DVB_CI_V", 8);
522 	if (dvb_str == NULL)
523 		return -EINVAL;
524 	if (tupleLength < ((dvb_str - (char *) tuple) + 12))
525 		return -EINVAL;
526 
527 	/* is it a version we support? */
528 	if (strncmp(dvb_str + 8, "1.00", 4)) {
529 		pr_err("dvb_ca adapter %d: Unsupported DVB CAM module version %c%c%c%c\n",
530 		       ca->dvbdev->adapter->num, dvb_str[8], dvb_str[9],
531 		       dvb_str[10], dvb_str[11]);
532 		return -EINVAL;
533 	}
534 
535 	/* process the CFTABLE_ENTRY tuples, and any after those */
536 	while ((!end_chain) && (address < 0x1000)) {
537 		if ((status = dvb_ca_en50221_read_tuple(ca, slot, &address, &tupleType,
538 							&tupleLength, tuple)) < 0)
539 			return status;
540 		switch (tupleType) {
541 		case 0x1B:	// CISTPL_CFTABLE_ENTRY
542 			if (tupleLength < (2 + 11 + 17))
543 				break;
544 
545 			/* if we've already parsed one, just use it */
546 			if (got_cftableentry)
547 				break;
548 
549 			/* get the config option */
550 			ca->slot_info[slot].config_option = tuple[0] & 0x3f;
551 
552 			/* OK, check it contains the correct strings */
553 			if ((findstr((char *)tuple, tupleLength, "DVB_HOST", 8) == NULL) ||
554 			    (findstr((char *)tuple, tupleLength, "DVB_CI_MODULE", 13) == NULL))
555 				break;
556 
557 			got_cftableentry = 1;
558 			break;
559 
560 		case 0x14:	// CISTPL_NO_LINK
561 			break;
562 
563 		case 0xFF:	// CISTPL_END
564 			end_chain = 1;
565 			break;
566 
567 		default:	/* Unknown tuple type - just skip this tuple and move to the next one */
568 			dprintk("dvb_ca: Skipping unknown tuple type:0x%x length:0x%x\n",
569 				tupleType, tupleLength);
570 			break;
571 		}
572 	}
573 
574 	if ((address > 0x1000) || (!got_cftableentry))
575 		return -EINVAL;
576 
577 	dprintk("Valid DVB CAM detected MANID:%x DEVID:%x CONFIGBASE:0x%x CONFIGOPTION:0x%x\n",
578 		manfid, devid, ca->slot_info[slot].config_base,
579 		ca->slot_info[slot].config_option);
580 
581 	// success!
582 	return 0;
583 }
584 
585 
586 /**
587  * dvb_ca_en50221_set_configoption - Set CAM's configoption correctly.
588  *
589  * @ca: CA instance.
590  * @slot: Slot containing the CAM.
591  */
592 static int dvb_ca_en50221_set_configoption(struct dvb_ca_private *ca, int slot)
593 {
594 	int configoption;
595 
596 	dprintk("%s\n", __func__);
597 
598 	/* set the config option */
599 	ca->pub->write_attribute_mem(ca->pub, slot,
600 				     ca->slot_info[slot].config_base,
601 				     ca->slot_info[slot].config_option);
602 
603 	/* check it */
604 	configoption = ca->pub->read_attribute_mem(ca->pub, slot, ca->slot_info[slot].config_base);
605 	dprintk("Set configoption 0x%x, read configoption 0x%x\n",
606 		ca->slot_info[slot].config_option, configoption & 0x3f);
607 
608 	/* fine! */
609 	return 0;
610 
611 }
612 
613 
614 /**
615  * dvb_ca_en50221_read_data - This function talks to an EN50221 CAM control
616  *	interface. It reads a buffer of data from the CAM. The data can either
617  *	be stored in a supplied buffer, or automatically be added to the slot's
618  *	rx_buffer.
619  *
620  * @ca: CA instance.
621  * @slot: Slot to read from.
622  * @ebuf: If non-NULL, the data will be written to this buffer. If NULL,
623  * the data will be added into the buffering system as a normal fragment.
624  * @ecount: Size of ebuf. Ignored if ebuf is NULL.
625  *
626  * @return Number of bytes read, or < 0 on error
627  */
628 static int dvb_ca_en50221_read_data(struct dvb_ca_private *ca, int slot,
629 				    u8 *ebuf, int ecount)
630 {
631 	int bytes_read;
632 	int status;
633 	u8 buf[HOST_LINK_BUF_SIZE];
634 	int i;
635 
636 	dprintk("%s\n", __func__);
637 
638 	/* check if we have space for a link buf in the rx_buffer */
639 	if (ebuf == NULL) {
640 		int buf_free;
641 
642 		if (ca->slot_info[slot].rx_buffer.data == NULL) {
643 			status = -EIO;
644 			goto exit;
645 		}
646 		buf_free = dvb_ringbuffer_free(&ca->slot_info[slot].rx_buffer);
647 
648 		if (buf_free < (ca->slot_info[slot].link_buf_size +
649 				DVB_RINGBUFFER_PKTHDRSIZE)) {
650 			status = -EAGAIN;
651 			goto exit;
652 		}
653 	}
654 
655 	if (ca->pub->read_data &&
656 	    (ca->slot_info[slot].slot_state != DVB_CA_SLOTSTATE_LINKINIT)) {
657 		if (ebuf == NULL)
658 			status = ca->pub->read_data(ca->pub, slot, buf,
659 						    sizeof(buf));
660 		else
661 			status = ca->pub->read_data(ca->pub, slot, buf, ecount);
662 		if (status < 0)
663 			return status;
664 		bytes_read =  status;
665 		if (status == 0)
666 			goto exit;
667 	} else {
668 
669 		/* check if there is data available */
670 		status = ca->pub->read_cam_control(ca->pub, slot,
671 						   CTRLIF_STATUS);
672 		if (status < 0)
673 			goto exit;
674 		if (!(status & STATUSREG_DA)) {
675 			/* no data */
676 			status = 0;
677 			goto exit;
678 		}
679 
680 		/* read the amount of data */
681 		status = ca->pub->read_cam_control(ca->pub, slot,
682 						   CTRLIF_SIZE_HIGH);
683 		if (status < 0)
684 			goto exit;
685 		bytes_read = status << 8;
686 		status = ca->pub->read_cam_control(ca->pub, slot,
687 						   CTRLIF_SIZE_LOW);
688 		if (status < 0)
689 			goto exit;
690 		bytes_read |= status;
691 
692 		/* check it will fit */
693 		if (ebuf == NULL) {
694 			if (bytes_read > ca->slot_info[slot].link_buf_size) {
695 				pr_err("dvb_ca adapter %d: CAM tried to send a buffer larger than the link buffer size (%i > %i)!\n",
696 				       ca->dvbdev->adapter->num, bytes_read,
697 				       ca->slot_info[slot].link_buf_size);
698 				ca->slot_info[slot].slot_state =
699 						     DVB_CA_SLOTSTATE_LINKINIT;
700 				status = -EIO;
701 				goto exit;
702 			}
703 			if (bytes_read < 2) {
704 				pr_err("dvb_ca adapter %d: CAM sent a buffer that was less than 2 bytes!\n",
705 				       ca->dvbdev->adapter->num);
706 				ca->slot_info[slot].slot_state =
707 						     DVB_CA_SLOTSTATE_LINKINIT;
708 				status = -EIO;
709 				goto exit;
710 			}
711 		} else {
712 			if (bytes_read > ecount) {
713 				pr_err("dvb_ca adapter %d: CAM tried to send a buffer larger than the ecount size!\n",
714 				       ca->dvbdev->adapter->num);
715 				status = -EIO;
716 				goto exit;
717 			}
718 		}
719 
720 		/* fill the buffer */
721 		for (i = 0; i < bytes_read; i++) {
722 			/* read byte and check */
723 			status = ca->pub->read_cam_control(ca->pub, slot,
724 							   CTRLIF_DATA);
725 			if (status < 0)
726 				goto exit;
727 
728 			/* OK, store it in the buffer */
729 			buf[i] = status;
730 		}
731 
732 		/* check for read error (RE should now be 0) */
733 		status = ca->pub->read_cam_control(ca->pub, slot,
734 						   CTRLIF_STATUS);
735 		if (status < 0)
736 			goto exit;
737 		if (status & STATUSREG_RE) {
738 			ca->slot_info[slot].slot_state =
739 						     DVB_CA_SLOTSTATE_LINKINIT;
740 			status = -EIO;
741 			goto exit;
742 		}
743 	}
744 
745 	/* OK, add it to the receive buffer, or copy into external buffer if supplied */
746 	if (ebuf == NULL) {
747 		if (ca->slot_info[slot].rx_buffer.data == NULL) {
748 			status = -EIO;
749 			goto exit;
750 		}
751 		dvb_ringbuffer_pkt_write(&ca->slot_info[slot].rx_buffer, buf, bytes_read);
752 	} else {
753 		memcpy(ebuf, buf, bytes_read);
754 	}
755 
756 	dprintk("Received CA packet for slot %i connection id 0x%x last_frag:%i size:0x%x\n", slot,
757 		buf[0], (buf[1] & 0x80) == 0, bytes_read);
758 
759 	/* wake up readers when a last_fragment is received */
760 	if ((buf[1] & 0x80) == 0x00) {
761 		wake_up_interruptible(&ca->wait_queue);
762 	}
763 	status = bytes_read;
764 
765 exit:
766 	return status;
767 }
768 
769 
770 /**
771  * dvb_ca_en50221_write_data - This function talks to an EN50221 CAM control
772  *				interface. It writes a buffer of data to a CAM.
773  *
774  * @ca: CA instance.
775  * @slot: Slot to write to.
776  * @ebuf: The data in this buffer is treated as a complete link-level packet to
777  * be written.
778  * @count: Size of ebuf.
779  *
780  * @return Number of bytes written, or < 0 on error.
781  */
782 static int dvb_ca_en50221_write_data(struct dvb_ca_private *ca, int slot,
783 				     u8 *buf, int bytes_write)
784 {
785 	int status;
786 	int i;
787 
788 	dprintk("%s\n", __func__);
789 
790 
791 	/* sanity check */
792 	if (bytes_write > ca->slot_info[slot].link_buf_size)
793 		return -EINVAL;
794 
795 	if (ca->pub->write_data &&
796 	    (ca->slot_info[slot].slot_state != DVB_CA_SLOTSTATE_LINKINIT))
797 		return ca->pub->write_data(ca->pub, slot, buf, bytes_write);
798 
799 	/* it is possible we are dealing with a single buffer implementation,
800 	   thus if there is data available for read or if there is even a read
801 	   already in progress, we do nothing but awake the kernel thread to
802 	   process the data if necessary. */
803 	if ((status = ca->pub->read_cam_control(ca->pub, slot, CTRLIF_STATUS)) < 0)
804 		goto exitnowrite;
805 	if (status & (STATUSREG_DA | STATUSREG_RE)) {
806 		if (status & STATUSREG_DA)
807 			dvb_ca_en50221_thread_wakeup(ca);
808 
809 		status = -EAGAIN;
810 		goto exitnowrite;
811 	}
812 
813 	/* OK, set HC bit */
814 	if ((status = ca->pub->write_cam_control(ca->pub, slot, CTRLIF_COMMAND,
815 						 IRQEN | CMDREG_HC)) != 0)
816 		goto exit;
817 
818 	/* check if interface is still free */
819 	if ((status = ca->pub->read_cam_control(ca->pub, slot, CTRLIF_STATUS)) < 0)
820 		goto exit;
821 	if (!(status & STATUSREG_FR)) {
822 		/* it wasn't free => try again later */
823 		status = -EAGAIN;
824 		goto exit;
825 	}
826 
827 	/*
828 	 * It may need some time for the CAM to settle down, or there might
829 	 * be a race condition between the CAM, writing HC and our last
830 	 * check for DA. This happens, if the CAM asserts DA, just after
831 	 * checking DA before we are setting HC. In this case it might be
832 	 * a bug in the CAM to keep the FR bit, the lower layer/HW
833 	 * communication requires a longer timeout or the CAM needs more
834 	 * time internally. But this happens in reality!
835 	 * We need to read the status from the HW again and do the same
836 	 * we did for the previous check for DA
837 	 */
838 	status = ca->pub->read_cam_control(ca->pub, slot, CTRLIF_STATUS);
839 	if (status < 0)
840 		goto exit;
841 
842 	if (status & (STATUSREG_DA | STATUSREG_RE)) {
843 		if (status & STATUSREG_DA)
844 			dvb_ca_en50221_thread_wakeup(ca);
845 
846 		status = -EAGAIN;
847 		goto exit;
848 	}
849 
850 	/* send the amount of data */
851 	if ((status = ca->pub->write_cam_control(ca->pub, slot, CTRLIF_SIZE_HIGH, bytes_write >> 8)) != 0)
852 		goto exit;
853 	if ((status = ca->pub->write_cam_control(ca->pub, slot, CTRLIF_SIZE_LOW,
854 						 bytes_write & 0xff)) != 0)
855 		goto exit;
856 
857 	/* send the buffer */
858 	for (i = 0; i < bytes_write; i++) {
859 		if ((status = ca->pub->write_cam_control(ca->pub, slot, CTRLIF_DATA, buf[i])) != 0)
860 			goto exit;
861 	}
862 
863 	/* check for write error (WE should now be 0) */
864 	if ((status = ca->pub->read_cam_control(ca->pub, slot, CTRLIF_STATUS)) < 0)
865 		goto exit;
866 	if (status & STATUSREG_WE) {
867 		ca->slot_info[slot].slot_state = DVB_CA_SLOTSTATE_LINKINIT;
868 		status = -EIO;
869 		goto exit;
870 	}
871 	status = bytes_write;
872 
873 	dprintk("Wrote CA packet for slot %i, connection id 0x%x last_frag:%i size:0x%x\n", slot,
874 		buf[0], (buf[1] & 0x80) == 0, bytes_write);
875 
876 exit:
877 	ca->pub->write_cam_control(ca->pub, slot, CTRLIF_COMMAND, IRQEN);
878 
879 exitnowrite:
880 	return status;
881 }
882 
883 
884 
885 /* ******************************************************************************** */
886 /* EN50221 higher level functions */
887 
888 
889 /**
890  * dvb_ca_en50221_slot_shutdown - A CAM has been removed => shut it down.
891  *
892  * @ca: CA instance.
893  * @slot: Slot to shut down.
894  */
895 static int dvb_ca_en50221_slot_shutdown(struct dvb_ca_private *ca, int slot)
896 {
897 	dprintk("%s\n", __func__);
898 
899 	ca->pub->slot_shutdown(ca->pub, slot);
900 	ca->slot_info[slot].slot_state = DVB_CA_SLOTSTATE_NONE;
901 
902 	/* need to wake up all processes to check if they're now
903 	   trying to write to a defunct CAM */
904 	wake_up_interruptible(&ca->wait_queue);
905 
906 	dprintk("Slot %i shutdown\n", slot);
907 
908 	/* success */
909 	return 0;
910 }
911 
912 
913 /**
914  * dvb_ca_en50221_camchange_irq - A CAMCHANGE IRQ has occurred.
915  *
916  * @ca: CA instance.
917  * @slot: Slot concerned.
918  * @change_type: One of the DVB_CA_CAMCHANGE_* values.
919  */
920 void dvb_ca_en50221_camchange_irq(struct dvb_ca_en50221 *pubca, int slot, int change_type)
921 {
922 	struct dvb_ca_private *ca = pubca->private;
923 
924 	dprintk("CAMCHANGE IRQ slot:%i change_type:%i\n", slot, change_type);
925 
926 	switch (change_type) {
927 	case DVB_CA_EN50221_CAMCHANGE_REMOVED:
928 	case DVB_CA_EN50221_CAMCHANGE_INSERTED:
929 		break;
930 
931 	default:
932 		return;
933 	}
934 
935 	ca->slot_info[slot].camchange_type = change_type;
936 	atomic_inc(&ca->slot_info[slot].camchange_count);
937 	dvb_ca_en50221_thread_wakeup(ca);
938 }
939 EXPORT_SYMBOL(dvb_ca_en50221_camchange_irq);
940 
941 
942 /**
943  * dvb_ca_en50221_camready_irq - A CAMREADY IRQ has occurred.
944  *
945  * @ca: CA instance.
946  * @slot: Slot concerned.
947  */
948 void dvb_ca_en50221_camready_irq(struct dvb_ca_en50221 *pubca, int slot)
949 {
950 	struct dvb_ca_private *ca = pubca->private;
951 
952 	dprintk("CAMREADY IRQ slot:%i\n", slot);
953 
954 	if (ca->slot_info[slot].slot_state == DVB_CA_SLOTSTATE_WAITREADY) {
955 		ca->slot_info[slot].slot_state = DVB_CA_SLOTSTATE_VALIDATE;
956 		dvb_ca_en50221_thread_wakeup(ca);
957 	}
958 }
959 EXPORT_SYMBOL(dvb_ca_en50221_camready_irq);
960 
961 
962 /**
963  * dvb_ca_en50221_frda_irq - An FR or DA IRQ has occurred.
964  *
965  * @ca: CA instance.
966  * @slot: Slot concerned.
967  */
968 void dvb_ca_en50221_frda_irq(struct dvb_ca_en50221 *pubca, int slot)
969 {
970 	struct dvb_ca_private *ca = pubca->private;
971 	int flags;
972 
973 	dprintk("FR/DA IRQ slot:%i\n", slot);
974 
975 	switch (ca->slot_info[slot].slot_state) {
976 	case DVB_CA_SLOTSTATE_LINKINIT:
977 		flags = ca->pub->read_cam_control(pubca, slot, CTRLIF_STATUS);
978 		if (flags & STATUSREG_DA) {
979 			dprintk("CAM supports DA IRQ\n");
980 			ca->slot_info[slot].da_irq_supported = 1;
981 		}
982 		break;
983 
984 	case DVB_CA_SLOTSTATE_RUNNING:
985 		if (ca->open)
986 			dvb_ca_en50221_thread_wakeup(ca);
987 		break;
988 	}
989 }
990 EXPORT_SYMBOL(dvb_ca_en50221_frda_irq);
991 
992 
993 /* ******************************************************************************** */
994 /* EN50221 thread functions */
995 
996 /**
997  * Wake up the DVB CA thread
998  *
999  * @ca: CA instance.
1000  */
1001 static void dvb_ca_en50221_thread_wakeup(struct dvb_ca_private *ca)
1002 {
1003 
1004 	dprintk("%s\n", __func__);
1005 
1006 	ca->wakeup = 1;
1007 	mb();
1008 	wake_up_process(ca->thread);
1009 }
1010 
1011 /**
1012  * Update the delay used by the thread.
1013  *
1014  * @ca: CA instance.
1015  */
1016 static void dvb_ca_en50221_thread_update_delay(struct dvb_ca_private *ca)
1017 {
1018 	int delay;
1019 	int curdelay = 100000000;
1020 	int slot;
1021 
1022 	/* Beware of too high polling frequency, because one polling
1023 	 * call might take several hundred milliseconds until timeout!
1024 	 */
1025 	for (slot = 0; slot < ca->slot_count; slot++) {
1026 		switch (ca->slot_info[slot].slot_state) {
1027 		default:
1028 		case DVB_CA_SLOTSTATE_NONE:
1029 			delay = HZ * 60;  /* 60s */
1030 			if (!(ca->flags & DVB_CA_EN50221_FLAG_IRQ_CAMCHANGE))
1031 				delay = HZ * 5;  /* 5s */
1032 			break;
1033 		case DVB_CA_SLOTSTATE_INVALID:
1034 			delay = HZ * 60;  /* 60s */
1035 			if (!(ca->flags & DVB_CA_EN50221_FLAG_IRQ_CAMCHANGE))
1036 				delay = HZ / 10;  /* 100ms */
1037 			break;
1038 
1039 		case DVB_CA_SLOTSTATE_UNINITIALISED:
1040 		case DVB_CA_SLOTSTATE_WAITREADY:
1041 		case DVB_CA_SLOTSTATE_VALIDATE:
1042 		case DVB_CA_SLOTSTATE_WAITFR:
1043 		case DVB_CA_SLOTSTATE_LINKINIT:
1044 			delay = HZ / 10;  /* 100ms */
1045 			break;
1046 
1047 		case DVB_CA_SLOTSTATE_RUNNING:
1048 			delay = HZ * 60;  /* 60s */
1049 			if (!(ca->flags & DVB_CA_EN50221_FLAG_IRQ_CAMCHANGE))
1050 				delay = HZ / 10;  /* 100ms */
1051 			if (ca->open) {
1052 				if ((!ca->slot_info[slot].da_irq_supported) ||
1053 				    (!(ca->flags & DVB_CA_EN50221_FLAG_IRQ_DA)))
1054 					delay = HZ / 10;  /* 100ms */
1055 			}
1056 			break;
1057 		}
1058 
1059 		if (delay < curdelay)
1060 			curdelay = delay;
1061 	}
1062 
1063 	ca->delay = curdelay;
1064 }
1065 
1066 
1067 
1068 /**
1069  * Kernel thread which monitors CA slots for CAM changes, and performs data transfers.
1070  */
1071 static int dvb_ca_en50221_thread(void *data)
1072 {
1073 	struct dvb_ca_private *ca = data;
1074 	int slot;
1075 	int flags;
1076 	int status;
1077 	int pktcount;
1078 	void *rxbuf;
1079 
1080 	dprintk("%s\n", __func__);
1081 
1082 	/* choose the correct initial delay */
1083 	dvb_ca_en50221_thread_update_delay(ca);
1084 
1085 	/* main loop */
1086 	while (!kthread_should_stop()) {
1087 		/* sleep for a bit */
1088 		if (!ca->wakeup) {
1089 			set_current_state(TASK_INTERRUPTIBLE);
1090 			schedule_timeout(ca->delay);
1091 			if (kthread_should_stop())
1092 				return 0;
1093 		}
1094 		ca->wakeup = 0;
1095 
1096 		/* go through all the slots processing them */
1097 		for (slot = 0; slot < ca->slot_count; slot++) {
1098 
1099 			mutex_lock(&ca->slot_info[slot].slot_lock);
1100 
1101 			// check the cam status + deal with CAMCHANGEs
1102 			while (dvb_ca_en50221_check_camstatus(ca, slot)) {
1103 				/* clear down an old CI slot if necessary */
1104 				if (ca->slot_info[slot].slot_state != DVB_CA_SLOTSTATE_NONE)
1105 					dvb_ca_en50221_slot_shutdown(ca, slot);
1106 
1107 				/* if a CAM is NOW present, initialise it */
1108 				if (ca->slot_info[slot].camchange_type == DVB_CA_EN50221_CAMCHANGE_INSERTED) {
1109 					ca->slot_info[slot].slot_state = DVB_CA_SLOTSTATE_UNINITIALISED;
1110 				}
1111 
1112 				/* we've handled one CAMCHANGE */
1113 				dvb_ca_en50221_thread_update_delay(ca);
1114 				atomic_dec(&ca->slot_info[slot].camchange_count);
1115 			}
1116 
1117 			// CAM state machine
1118 			switch (ca->slot_info[slot].slot_state) {
1119 			case DVB_CA_SLOTSTATE_NONE:
1120 			case DVB_CA_SLOTSTATE_INVALID:
1121 				// no action needed
1122 				break;
1123 
1124 			case DVB_CA_SLOTSTATE_UNINITIALISED:
1125 				ca->slot_info[slot].slot_state = DVB_CA_SLOTSTATE_WAITREADY;
1126 				ca->pub->slot_reset(ca->pub, slot);
1127 				ca->slot_info[slot].timeout = jiffies + (INIT_TIMEOUT_SECS * HZ);
1128 				break;
1129 
1130 			case DVB_CA_SLOTSTATE_WAITREADY:
1131 				if (time_after(jiffies, ca->slot_info[slot].timeout)) {
1132 					pr_err("dvb_ca adaptor %d: PC card did not respond :(\n",
1133 					       ca->dvbdev->adapter->num);
1134 					ca->slot_info[slot].slot_state = DVB_CA_SLOTSTATE_INVALID;
1135 					dvb_ca_en50221_thread_update_delay(ca);
1136 					break;
1137 				}
1138 				// no other action needed; will automatically change state when ready
1139 				break;
1140 
1141 			case DVB_CA_SLOTSTATE_VALIDATE:
1142 				if (dvb_ca_en50221_parse_attributes(ca, slot) != 0) {
1143 					/* we need this extra check for annoying interfaces like the budget-av */
1144 					if ((!(ca->flags & DVB_CA_EN50221_FLAG_IRQ_CAMCHANGE)) &&
1145 					    (ca->pub->poll_slot_status)) {
1146 						status = ca->pub->poll_slot_status(ca->pub, slot, 0);
1147 						if (!(status & DVB_CA_EN50221_POLL_CAM_PRESENT)) {
1148 							ca->slot_info[slot].slot_state = DVB_CA_SLOTSTATE_NONE;
1149 							dvb_ca_en50221_thread_update_delay(ca);
1150 							break;
1151 						}
1152 					}
1153 
1154 					pr_err("dvb_ca adapter %d: Invalid PC card inserted :(\n",
1155 					       ca->dvbdev->adapter->num);
1156 					ca->slot_info[slot].slot_state = DVB_CA_SLOTSTATE_INVALID;
1157 					dvb_ca_en50221_thread_update_delay(ca);
1158 					break;
1159 				}
1160 				if (dvb_ca_en50221_set_configoption(ca, slot) != 0) {
1161 					pr_err("dvb_ca adapter %d: Unable to initialise CAM :(\n",
1162 					       ca->dvbdev->adapter->num);
1163 					ca->slot_info[slot].slot_state = DVB_CA_SLOTSTATE_INVALID;
1164 					dvb_ca_en50221_thread_update_delay(ca);
1165 					break;
1166 				}
1167 				if (ca->pub->write_cam_control(ca->pub, slot,
1168 							       CTRLIF_COMMAND, CMDREG_RS) != 0) {
1169 					pr_err("dvb_ca adapter %d: Unable to reset CAM IF\n",
1170 					       ca->dvbdev->adapter->num);
1171 					ca->slot_info[slot].slot_state = DVB_CA_SLOTSTATE_INVALID;
1172 					dvb_ca_en50221_thread_update_delay(ca);
1173 					break;
1174 				}
1175 				dprintk("DVB CAM validated successfully\n");
1176 
1177 				ca->slot_info[slot].timeout = jiffies + (INIT_TIMEOUT_SECS * HZ);
1178 				ca->slot_info[slot].slot_state = DVB_CA_SLOTSTATE_WAITFR;
1179 				ca->wakeup = 1;
1180 				break;
1181 
1182 			case DVB_CA_SLOTSTATE_WAITFR:
1183 				if (time_after(jiffies, ca->slot_info[slot].timeout)) {
1184 					pr_err("dvb_ca adapter %d: DVB CAM did not respond :(\n",
1185 					       ca->dvbdev->adapter->num);
1186 					ca->slot_info[slot].slot_state = DVB_CA_SLOTSTATE_INVALID;
1187 					dvb_ca_en50221_thread_update_delay(ca);
1188 					break;
1189 				}
1190 
1191 				flags = ca->pub->read_cam_control(ca->pub, slot, CTRLIF_STATUS);
1192 				if (flags & STATUSREG_FR) {
1193 					ca->slot_info[slot].slot_state = DVB_CA_SLOTSTATE_LINKINIT;
1194 					ca->wakeup = 1;
1195 				}
1196 				break;
1197 
1198 			case DVB_CA_SLOTSTATE_LINKINIT:
1199 				if (dvb_ca_en50221_link_init(ca, slot) != 0) {
1200 					/* we need this extra check for annoying interfaces like the budget-av */
1201 					if ((!(ca->flags & DVB_CA_EN50221_FLAG_IRQ_CAMCHANGE)) &&
1202 					    (ca->pub->poll_slot_status)) {
1203 						status = ca->pub->poll_slot_status(ca->pub, slot, 0);
1204 						if (!(status & DVB_CA_EN50221_POLL_CAM_PRESENT)) {
1205 							ca->slot_info[slot].slot_state = DVB_CA_SLOTSTATE_NONE;
1206 							dvb_ca_en50221_thread_update_delay(ca);
1207 							break;
1208 						}
1209 					}
1210 
1211 					pr_err("dvb_ca adapter %d: DVB CAM link initialisation failed :(\n",
1212 					       ca->dvbdev->adapter->num);
1213 					ca->slot_info[slot].slot_state =
1214 						DVB_CA_SLOTSTATE_UNINITIALISED;
1215 					dvb_ca_en50221_thread_update_delay(ca);
1216 					break;
1217 				}
1218 
1219 				if (ca->slot_info[slot].rx_buffer.data == NULL) {
1220 					rxbuf = vmalloc(RX_BUFFER_SIZE);
1221 					if (rxbuf == NULL) {
1222 						pr_err("dvb_ca adapter %d: Unable to allocate CAM rx buffer :(\n",
1223 						       ca->dvbdev->adapter->num);
1224 						ca->slot_info[slot].slot_state = DVB_CA_SLOTSTATE_INVALID;
1225 						dvb_ca_en50221_thread_update_delay(ca);
1226 						break;
1227 					}
1228 					dvb_ringbuffer_init(&ca->slot_info[slot].rx_buffer, rxbuf, RX_BUFFER_SIZE);
1229 				}
1230 
1231 				ca->pub->slot_ts_enable(ca->pub, slot);
1232 				ca->slot_info[slot].slot_state = DVB_CA_SLOTSTATE_RUNNING;
1233 				dvb_ca_en50221_thread_update_delay(ca);
1234 				pr_err("dvb_ca adapter %d: DVB CAM detected and initialised successfully\n",
1235 				       ca->dvbdev->adapter->num);
1236 				break;
1237 
1238 			case DVB_CA_SLOTSTATE_RUNNING:
1239 				if (!ca->open)
1240 					break;
1241 
1242 				// poll slots for data
1243 				pktcount = 0;
1244 				while ((status = dvb_ca_en50221_read_data(ca, slot, NULL, 0)) > 0) {
1245 					if (!ca->open)
1246 						break;
1247 
1248 					/* if a CAMCHANGE occurred at some point, do not do any more processing of this slot */
1249 					if (dvb_ca_en50221_check_camstatus(ca, slot)) {
1250 						// we dont want to sleep on the next iteration so we can handle the cam change
1251 						ca->wakeup = 1;
1252 						break;
1253 					}
1254 
1255 					/* check if we've hit our limit this time */
1256 					if (++pktcount >= MAX_RX_PACKETS_PER_ITERATION) {
1257 						// dont sleep; there is likely to be more data to read
1258 						ca->wakeup = 1;
1259 						break;
1260 					}
1261 				}
1262 				break;
1263 			}
1264 
1265 			mutex_unlock(&ca->slot_info[slot].slot_lock);
1266 		}
1267 	}
1268 
1269 	return 0;
1270 }
1271 
1272 
1273 
1274 /* ******************************************************************************** */
1275 /* EN50221 IO interface functions */
1276 
1277 /**
1278  * Real ioctl implementation.
1279  * NOTE: CA_SEND_MSG/CA_GET_MSG ioctls have userspace buffers passed to them.
1280  *
1281  * @inode: Inode concerned.
1282  * @file: File concerned.
1283  * @cmd: IOCTL command.
1284  * @arg: Associated argument.
1285  *
1286  * @return 0 on success, <0 on error.
1287  */
1288 static int dvb_ca_en50221_io_do_ioctl(struct file *file,
1289 				      unsigned int cmd, void *parg)
1290 {
1291 	struct dvb_device *dvbdev = file->private_data;
1292 	struct dvb_ca_private *ca = dvbdev->priv;
1293 	int err = 0;
1294 	int slot;
1295 
1296 	dprintk("%s\n", __func__);
1297 
1298 	if (mutex_lock_interruptible(&ca->ioctl_mutex))
1299 		return -ERESTARTSYS;
1300 
1301 	switch (cmd) {
1302 	case CA_RESET:
1303 		for (slot = 0; slot < ca->slot_count; slot++) {
1304 			mutex_lock(&ca->slot_info[slot].slot_lock);
1305 			if (ca->slot_info[slot].slot_state != DVB_CA_SLOTSTATE_NONE) {
1306 				dvb_ca_en50221_slot_shutdown(ca, slot);
1307 				if (ca->flags & DVB_CA_EN50221_FLAG_IRQ_CAMCHANGE)
1308 					dvb_ca_en50221_camchange_irq(ca->pub,
1309 								     slot,
1310 								     DVB_CA_EN50221_CAMCHANGE_INSERTED);
1311 			}
1312 			mutex_unlock(&ca->slot_info[slot].slot_lock);
1313 		}
1314 		ca->next_read_slot = 0;
1315 		dvb_ca_en50221_thread_wakeup(ca);
1316 		break;
1317 
1318 	case CA_GET_CAP: {
1319 		struct ca_caps *caps = parg;
1320 
1321 		caps->slot_num = ca->slot_count;
1322 		caps->slot_type = CA_CI_LINK;
1323 		caps->descr_num = 0;
1324 		caps->descr_type = 0;
1325 		break;
1326 	}
1327 
1328 	case CA_GET_SLOT_INFO: {
1329 		struct ca_slot_info *info = parg;
1330 
1331 		if ((info->num > ca->slot_count) || (info->num < 0)) {
1332 			err = -EINVAL;
1333 			goto out_unlock;
1334 		}
1335 
1336 		info->type = CA_CI_LINK;
1337 		info->flags = 0;
1338 		if ((ca->slot_info[info->num].slot_state != DVB_CA_SLOTSTATE_NONE)
1339 			&& (ca->slot_info[info->num].slot_state != DVB_CA_SLOTSTATE_INVALID)) {
1340 			info->flags = CA_CI_MODULE_PRESENT;
1341 		}
1342 		if (ca->slot_info[info->num].slot_state == DVB_CA_SLOTSTATE_RUNNING) {
1343 			info->flags |= CA_CI_MODULE_READY;
1344 		}
1345 		break;
1346 	}
1347 
1348 	default:
1349 		err = -EINVAL;
1350 		break;
1351 	}
1352 
1353 out_unlock:
1354 	mutex_unlock(&ca->ioctl_mutex);
1355 	return err;
1356 }
1357 
1358 
1359 /**
1360  * Wrapper for ioctl implementation.
1361  *
1362  * @inode: Inode concerned.
1363  * @file: File concerned.
1364  * @cmd: IOCTL command.
1365  * @arg: Associated argument.
1366  *
1367  * @return 0 on success, <0 on error.
1368  */
1369 static long dvb_ca_en50221_io_ioctl(struct file *file,
1370 				    unsigned int cmd, unsigned long arg)
1371 {
1372 	return dvb_usercopy(file, cmd, arg, dvb_ca_en50221_io_do_ioctl);
1373 }
1374 
1375 
1376 /**
1377  * Implementation of write() syscall.
1378  *
1379  * @file: File structure.
1380  * @buf: Source buffer.
1381  * @count: Size of source buffer.
1382  * @ppos: Position in file (ignored).
1383  *
1384  * @return Number of bytes read, or <0 on error.
1385  */
1386 static ssize_t dvb_ca_en50221_io_write(struct file *file,
1387 				       const char __user *buf, size_t count,
1388 				       loff_t *ppos)
1389 {
1390 	struct dvb_device *dvbdev = file->private_data;
1391 	struct dvb_ca_private *ca = dvbdev->priv;
1392 	u8 slot, connection_id;
1393 	int status;
1394 	u8 fragbuf[HOST_LINK_BUF_SIZE];
1395 	int fragpos = 0;
1396 	int fraglen;
1397 	unsigned long timeout;
1398 	int written;
1399 
1400 	dprintk("%s\n", __func__);
1401 
1402 	/* Incoming packet has a 2 byte header. hdr[0] = slot_id, hdr[1] = connection_id */
1403 	if (count < 2)
1404 		return -EINVAL;
1405 
1406 	/* extract slot & connection id */
1407 	if (copy_from_user(&slot, buf, 1))
1408 		return -EFAULT;
1409 	if (copy_from_user(&connection_id, buf + 1, 1))
1410 		return -EFAULT;
1411 	buf += 2;
1412 	count -= 2;
1413 
1414 	/* check if the slot is actually running */
1415 	if (ca->slot_info[slot].slot_state != DVB_CA_SLOTSTATE_RUNNING)
1416 		return -EINVAL;
1417 
1418 	/* fragment the packets & store in the buffer */
1419 	while (fragpos < count) {
1420 		fraglen = ca->slot_info[slot].link_buf_size - 2;
1421 		if (fraglen < 0)
1422 			break;
1423 		if (fraglen > HOST_LINK_BUF_SIZE - 2)
1424 			fraglen = HOST_LINK_BUF_SIZE - 2;
1425 		if ((count - fragpos) < fraglen)
1426 			fraglen = count - fragpos;
1427 
1428 		fragbuf[0] = connection_id;
1429 		fragbuf[1] = ((fragpos + fraglen) < count) ? 0x80 : 0x00;
1430 		status = copy_from_user(fragbuf + 2, buf + fragpos, fraglen);
1431 		if (status) {
1432 			status = -EFAULT;
1433 			goto exit;
1434 		}
1435 
1436 		timeout = jiffies + HZ / 2;
1437 		written = 0;
1438 		while (!time_after(jiffies, timeout)) {
1439 			/* check the CAM hasn't been removed/reset in the meantime */
1440 			if (ca->slot_info[slot].slot_state != DVB_CA_SLOTSTATE_RUNNING) {
1441 				status = -EIO;
1442 				goto exit;
1443 			}
1444 
1445 			mutex_lock(&ca->slot_info[slot].slot_lock);
1446 			status = dvb_ca_en50221_write_data(ca, slot, fragbuf, fraglen + 2);
1447 			mutex_unlock(&ca->slot_info[slot].slot_lock);
1448 			if (status == (fraglen + 2)) {
1449 				written = 1;
1450 				break;
1451 			}
1452 			if (status != -EAGAIN)
1453 				goto exit;
1454 
1455 			msleep(1);
1456 		}
1457 		if (!written) {
1458 			status = -EIO;
1459 			goto exit;
1460 		}
1461 
1462 		fragpos += fraglen;
1463 	}
1464 	status = count + 2;
1465 
1466 exit:
1467 	return status;
1468 }
1469 
1470 
1471 /**
1472  * Condition for waking up in dvb_ca_en50221_io_read_condition
1473  */
1474 static int dvb_ca_en50221_io_read_condition(struct dvb_ca_private *ca,
1475 					    int *result, int *_slot)
1476 {
1477 	int slot;
1478 	int slot_count = 0;
1479 	int idx;
1480 	size_t fraglen;
1481 	int connection_id = -1;
1482 	int found = 0;
1483 	u8 hdr[2];
1484 
1485 	slot = ca->next_read_slot;
1486 	while ((slot_count < ca->slot_count) && (!found)) {
1487 		if (ca->slot_info[slot].slot_state != DVB_CA_SLOTSTATE_RUNNING)
1488 			goto nextslot;
1489 
1490 		if (ca->slot_info[slot].rx_buffer.data == NULL) {
1491 			return 0;
1492 		}
1493 
1494 		idx = dvb_ringbuffer_pkt_next(&ca->slot_info[slot].rx_buffer, -1, &fraglen);
1495 		while (idx != -1) {
1496 			dvb_ringbuffer_pkt_read(&ca->slot_info[slot].rx_buffer, idx, 0, hdr, 2);
1497 			if (connection_id == -1)
1498 				connection_id = hdr[0];
1499 			if ((hdr[0] == connection_id) && ((hdr[1] & 0x80) == 0)) {
1500 				*_slot = slot;
1501 				found = 1;
1502 				break;
1503 			}
1504 
1505 			idx = dvb_ringbuffer_pkt_next(&ca->slot_info[slot].rx_buffer, idx, &fraglen);
1506 		}
1507 
1508 nextslot:
1509 		slot = (slot + 1) % ca->slot_count;
1510 		slot_count++;
1511 	}
1512 
1513 	ca->next_read_slot = slot;
1514 	return found;
1515 }
1516 
1517 
1518 /**
1519  * Implementation of read() syscall.
1520  *
1521  * @file: File structure.
1522  * @buf: Destination buffer.
1523  * @count: Size of destination buffer.
1524  * @ppos: Position in file (ignored).
1525  *
1526  * @return Number of bytes read, or <0 on error.
1527  */
1528 static ssize_t dvb_ca_en50221_io_read(struct file *file, char __user *buf,
1529 				      size_t count, loff_t *ppos)
1530 {
1531 	struct dvb_device *dvbdev = file->private_data;
1532 	struct dvb_ca_private *ca = dvbdev->priv;
1533 	int status;
1534 	int result = 0;
1535 	u8 hdr[2];
1536 	int slot;
1537 	int connection_id = -1;
1538 	size_t idx, idx2;
1539 	int last_fragment = 0;
1540 	size_t fraglen;
1541 	int pktlen;
1542 	int dispose = 0;
1543 
1544 	dprintk("%s\n", __func__);
1545 
1546 	/* Outgoing packet has a 2 byte header. hdr[0] = slot_id, hdr[1] = connection_id */
1547 	if (count < 2)
1548 		return -EINVAL;
1549 
1550 	/* wait for some data */
1551 	if ((status = dvb_ca_en50221_io_read_condition(ca, &result, &slot)) == 0) {
1552 
1553 		/* if we're in nonblocking mode, exit immediately */
1554 		if (file->f_flags & O_NONBLOCK)
1555 			return -EWOULDBLOCK;
1556 
1557 		/* wait for some data */
1558 		status = wait_event_interruptible(ca->wait_queue,
1559 						  dvb_ca_en50221_io_read_condition
1560 						  (ca, &result, &slot));
1561 	}
1562 	if ((status < 0) || (result < 0)) {
1563 		if (result)
1564 			return result;
1565 		return status;
1566 	}
1567 
1568 	idx = dvb_ringbuffer_pkt_next(&ca->slot_info[slot].rx_buffer, -1, &fraglen);
1569 	pktlen = 2;
1570 	do {
1571 		if (idx == -1) {
1572 			pr_err("dvb_ca adapter %d: BUG: read packet ended before last_fragment encountered\n",
1573 			       ca->dvbdev->adapter->num);
1574 			status = -EIO;
1575 			goto exit;
1576 		}
1577 
1578 		dvb_ringbuffer_pkt_read(&ca->slot_info[slot].rx_buffer, idx, 0, hdr, 2);
1579 		if (connection_id == -1)
1580 			connection_id = hdr[0];
1581 		if (hdr[0] == connection_id) {
1582 			if (pktlen < count) {
1583 				if ((pktlen + fraglen - 2) > count) {
1584 					fraglen = count - pktlen;
1585 				} else {
1586 					fraglen -= 2;
1587 				}
1588 
1589 				if ((status = dvb_ringbuffer_pkt_read_user(&ca->slot_info[slot].rx_buffer, idx, 2,
1590 								      buf + pktlen, fraglen)) < 0) {
1591 					goto exit;
1592 				}
1593 				pktlen += fraglen;
1594 			}
1595 
1596 			if ((hdr[1] & 0x80) == 0)
1597 				last_fragment = 1;
1598 			dispose = 1;
1599 		}
1600 
1601 		idx2 = dvb_ringbuffer_pkt_next(&ca->slot_info[slot].rx_buffer, idx, &fraglen);
1602 		if (dispose)
1603 			dvb_ringbuffer_pkt_dispose(&ca->slot_info[slot].rx_buffer, idx);
1604 		idx = idx2;
1605 		dispose = 0;
1606 	} while (!last_fragment);
1607 
1608 	hdr[0] = slot;
1609 	hdr[1] = connection_id;
1610 	status = copy_to_user(buf, hdr, 2);
1611 	if (status) {
1612 		status = -EFAULT;
1613 		goto exit;
1614 	}
1615 	status = pktlen;
1616 
1617 exit:
1618 	return status;
1619 }
1620 
1621 
1622 /**
1623  * Implementation of file open syscall.
1624  *
1625  * @inode: Inode concerned.
1626  * @file: File concerned.
1627  *
1628  * @return 0 on success, <0 on failure.
1629  */
1630 static int dvb_ca_en50221_io_open(struct inode *inode, struct file *file)
1631 {
1632 	struct dvb_device *dvbdev = file->private_data;
1633 	struct dvb_ca_private *ca = dvbdev->priv;
1634 	int err;
1635 	int i;
1636 
1637 	dprintk("%s\n", __func__);
1638 
1639 	if (!try_module_get(ca->pub->owner))
1640 		return -EIO;
1641 
1642 	err = dvb_generic_open(inode, file);
1643 	if (err < 0) {
1644 		module_put(ca->pub->owner);
1645 		return err;
1646 	}
1647 
1648 	for (i = 0; i < ca->slot_count; i++) {
1649 
1650 		if (ca->slot_info[i].slot_state == DVB_CA_SLOTSTATE_RUNNING) {
1651 			if (ca->slot_info[i].rx_buffer.data != NULL) {
1652 				/* it is safe to call this here without locks because
1653 				 * ca->open == 0. Data is not read in this case */
1654 				dvb_ringbuffer_flush(&ca->slot_info[i].rx_buffer);
1655 			}
1656 		}
1657 	}
1658 
1659 	ca->open = 1;
1660 	dvb_ca_en50221_thread_update_delay(ca);
1661 	dvb_ca_en50221_thread_wakeup(ca);
1662 
1663 	dvb_ca_private_get(ca);
1664 
1665 	return 0;
1666 }
1667 
1668 
1669 /**
1670  * Implementation of file close syscall.
1671  *
1672  * @inode: Inode concerned.
1673  * @file: File concerned.
1674  *
1675  * @return 0 on success, <0 on failure.
1676  */
1677 static int dvb_ca_en50221_io_release(struct inode *inode, struct file *file)
1678 {
1679 	struct dvb_device *dvbdev = file->private_data;
1680 	struct dvb_ca_private *ca = dvbdev->priv;
1681 	int err;
1682 
1683 	dprintk("%s\n", __func__);
1684 
1685 	/* mark the CA device as closed */
1686 	ca->open = 0;
1687 	dvb_ca_en50221_thread_update_delay(ca);
1688 
1689 	err = dvb_generic_release(inode, file);
1690 
1691 	module_put(ca->pub->owner);
1692 
1693 	dvb_ca_private_put(ca);
1694 
1695 	return err;
1696 }
1697 
1698 
1699 /**
1700  * Implementation of poll() syscall.
1701  *
1702  * @file: File concerned.
1703  * @wait: poll wait table.
1704  *
1705  * @return Standard poll mask.
1706  */
1707 static unsigned int dvb_ca_en50221_io_poll(struct file *file, poll_table *wait)
1708 {
1709 	struct dvb_device *dvbdev = file->private_data;
1710 	struct dvb_ca_private *ca = dvbdev->priv;
1711 	unsigned int mask = 0;
1712 	int slot;
1713 	int result = 0;
1714 
1715 	dprintk("%s\n", __func__);
1716 
1717 	if (dvb_ca_en50221_io_read_condition(ca, &result, &slot) == 1) {
1718 		mask |= POLLIN;
1719 	}
1720 
1721 	/* if there is something, return now */
1722 	if (mask)
1723 		return mask;
1724 
1725 	/* wait for something to happen */
1726 	poll_wait(file, &ca->wait_queue, wait);
1727 
1728 	if (dvb_ca_en50221_io_read_condition(ca, &result, &slot) == 1) {
1729 		mask |= POLLIN;
1730 	}
1731 
1732 	return mask;
1733 }
1734 EXPORT_SYMBOL(dvb_ca_en50221_init);
1735 
1736 
1737 static const struct file_operations dvb_ca_fops = {
1738 	.owner = THIS_MODULE,
1739 	.read = dvb_ca_en50221_io_read,
1740 	.write = dvb_ca_en50221_io_write,
1741 	.unlocked_ioctl = dvb_ca_en50221_io_ioctl,
1742 	.open = dvb_ca_en50221_io_open,
1743 	.release = dvb_ca_en50221_io_release,
1744 	.poll = dvb_ca_en50221_io_poll,
1745 	.llseek = noop_llseek,
1746 };
1747 
1748 static const struct dvb_device dvbdev_ca = {
1749 	.priv = NULL,
1750 	.users = 1,
1751 	.readers = 1,
1752 	.writers = 1,
1753 #if defined(CONFIG_MEDIA_CONTROLLER_DVB)
1754 	.name = "dvb-ca-en50221",
1755 #endif
1756 	.fops = &dvb_ca_fops,
1757 };
1758 
1759 /* ******************************************************************************** */
1760 /* Initialisation/shutdown functions */
1761 
1762 
1763 /**
1764  * Initialise a new DVB CA EN50221 interface device.
1765  *
1766  * @dvb_adapter: DVB adapter to attach the new CA device to.
1767  * @ca: The dvb_ca instance.
1768  * @flags: Flags describing the CA device (DVB_CA_FLAG_*).
1769  * @slot_count: Number of slots supported.
1770  *
1771  * @return 0 on success, nonzero on failure
1772  */
1773 int dvb_ca_en50221_init(struct dvb_adapter *dvb_adapter,
1774 			struct dvb_ca_en50221 *pubca, int flags, int slot_count)
1775 {
1776 	int ret;
1777 	struct dvb_ca_private *ca = NULL;
1778 	int i;
1779 
1780 	dprintk("%s\n", __func__);
1781 
1782 	if (slot_count < 1)
1783 		return -EINVAL;
1784 
1785 	/* initialise the system data */
1786 	if ((ca = kzalloc(sizeof(struct dvb_ca_private), GFP_KERNEL)) == NULL) {
1787 		ret = -ENOMEM;
1788 		goto exit;
1789 	}
1790 	kref_init(&ca->refcount);
1791 	ca->pub = pubca;
1792 	ca->flags = flags;
1793 	ca->slot_count = slot_count;
1794 	if ((ca->slot_info = kcalloc(slot_count, sizeof(struct dvb_ca_slot), GFP_KERNEL)) == NULL) {
1795 		ret = -ENOMEM;
1796 		goto free_ca;
1797 	}
1798 	init_waitqueue_head(&ca->wait_queue);
1799 	ca->open = 0;
1800 	ca->wakeup = 0;
1801 	ca->next_read_slot = 0;
1802 	pubca->private = ca;
1803 
1804 	/* register the DVB device */
1805 	ret = dvb_register_device(dvb_adapter, &ca->dvbdev, &dvbdev_ca, ca, DVB_DEVICE_CA, 0);
1806 	if (ret)
1807 		goto free_slot_info;
1808 
1809 	/* now initialise each slot */
1810 	for (i = 0; i < slot_count; i++) {
1811 		memset(&ca->slot_info[i], 0, sizeof(struct dvb_ca_slot));
1812 		ca->slot_info[i].slot_state = DVB_CA_SLOTSTATE_NONE;
1813 		atomic_set(&ca->slot_info[i].camchange_count, 0);
1814 		ca->slot_info[i].camchange_type = DVB_CA_EN50221_CAMCHANGE_REMOVED;
1815 		mutex_init(&ca->slot_info[i].slot_lock);
1816 	}
1817 
1818 	mutex_init(&ca->ioctl_mutex);
1819 
1820 	if (signal_pending(current)) {
1821 		ret = -EINTR;
1822 		goto unregister_device;
1823 	}
1824 	mb();
1825 
1826 	/* create a kthread for monitoring this CA device */
1827 	ca->thread = kthread_run(dvb_ca_en50221_thread, ca, "kdvb-ca-%i:%i",
1828 				 ca->dvbdev->adapter->num, ca->dvbdev->id);
1829 	if (IS_ERR(ca->thread)) {
1830 		ret = PTR_ERR(ca->thread);
1831 		pr_err("dvb_ca_init: failed to start kernel_thread (%d)\n",
1832 		       ret);
1833 		goto unregister_device;
1834 	}
1835 	return 0;
1836 
1837 unregister_device:
1838 	dvb_unregister_device(ca->dvbdev);
1839 free_slot_info:
1840 	kfree(ca->slot_info);
1841 free_ca:
1842 	kfree(ca);
1843 exit:
1844 	pubca->private = NULL;
1845 	return ret;
1846 }
1847 EXPORT_SYMBOL(dvb_ca_en50221_release);
1848 
1849 
1850 
1851 /**
1852  * Release a DVB CA EN50221 interface device.
1853  *
1854  * @ca_dev: The dvb_device_t instance for the CA device.
1855  * @ca: The associated dvb_ca instance.
1856  */
1857 void dvb_ca_en50221_release(struct dvb_ca_en50221 *pubca)
1858 {
1859 	struct dvb_ca_private *ca = pubca->private;
1860 	int i;
1861 
1862 	dprintk("%s\n", __func__);
1863 
1864 	/* shutdown the thread if there was one */
1865 	kthread_stop(ca->thread);
1866 
1867 	for (i = 0; i < ca->slot_count; i++) {
1868 		dvb_ca_en50221_slot_shutdown(ca, i);
1869 	}
1870 	dvb_remove_device(ca->dvbdev);
1871 	dvb_ca_private_put(ca);
1872 	pubca->private = NULL;
1873 }
1874