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