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