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