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