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