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