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