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