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