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  */
findstr(char * haystack,int hlen,char * needle,int nlen)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  */
dvb_ca_en50221_check_camstatus(struct dvb_ca_private * ca,int slot)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  */
dvb_ca_en50221_wait_if_status(struct dvb_ca_private * ca,int slot,u8 waitfor,int timeout_hz)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  */
dvb_ca_en50221_link_init(struct dvb_ca_private * ca,int slot)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  */
dvb_ca_en50221_read_tuple(struct dvb_ca_private * ca,int slot,int * address,int * tupleType,int * tupleLength,u8 * tuple)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  */
dvb_ca_en50221_parse_attributes(struct dvb_ca_private * ca,int slot)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  */
dvb_ca_en50221_set_configoption(struct dvb_ca_private * ca,int slot)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  */
dvb_ca_en50221_read_data(struct dvb_ca_private * ca,int slot,u8 * ebuf,int ecount)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  */
dvb_ca_en50221_write_data(struct dvb_ca_private * ca,int slot,u8 * buf,int bytes_write)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  */
dvb_ca_en50221_slot_shutdown(struct dvb_ca_private * ca,int slot)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  */
dvb_ca_en50221_camchange_irq(struct dvb_ca_en50221 * pubca,int slot,int change_type)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  */
dvb_ca_en50221_camready_irq(struct dvb_ca_en50221 * pubca,int slot)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  */
dvb_ca_en50221_frda_irq(struct dvb_ca_en50221 * pubca,int slot)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  */
dvb_ca_en50221_thread_wakeup(struct dvb_ca_private * ca)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  */
dvb_ca_en50221_thread_update_delay(struct dvb_ca_private * ca)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  */
dvb_ca_en50221_thread(void * data)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  */
dvb_ca_en50221_io_do_ioctl(struct file * file,unsigned int cmd,void * parg)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  */
dvb_ca_en50221_io_ioctl(struct file * file,unsigned int cmd,unsigned long arg)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  */
dvb_ca_en50221_io_write(struct file * file,const char __user * buf,size_t count,loff_t * ppos)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 ((count - fragpos) < fraglen)
1310 			fraglen = count - fragpos;
1311 
1312 		fragbuf[0] = connection_id;
1313 		fragbuf[1] = ((fragpos + fraglen) < count) ? 0x80 : 0x00;
1314 		status = copy_from_user(fragbuf + 2, buf + fragpos, fraglen);
1315 		if (status) {
1316 			status = -EFAULT;
1317 			goto exit;
1318 		}
1319 
1320 		timeout = jiffies + HZ / 2;
1321 		written = 0;
1322 		while (!time_after(jiffies, timeout)) {
1323 			/* check the CAM hasn't been removed/reset in the meantime */
1324 			if (ca->slot_info[slot].slot_state != DVB_CA_SLOTSTATE_RUNNING) {
1325 				status = -EIO;
1326 				goto exit;
1327 			}
1328 
1329 			mutex_lock(&ca->slot_info[slot].slot_lock);
1330 			status = dvb_ca_en50221_write_data(ca, slot, fragbuf, fraglen + 2);
1331 			mutex_unlock(&ca->slot_info[slot].slot_lock);
1332 			if (status == (fraglen + 2)) {
1333 				written = 1;
1334 				break;
1335 			}
1336 			if (status != -EAGAIN)
1337 				goto exit;
1338 
1339 			msleep(1);
1340 		}
1341 		if (!written) {
1342 			status = -EIO;
1343 			goto exit;
1344 		}
1345 
1346 		fragpos += fraglen;
1347 	}
1348 	status = count + 2;
1349 
1350 exit:
1351 	return status;
1352 }
1353 
1354 
1355 /**
1356  * Condition for waking up in dvb_ca_en50221_io_read_condition
1357  */
dvb_ca_en50221_io_read_condition(struct dvb_ca_private * ca,int * result,int * _slot)1358 static int dvb_ca_en50221_io_read_condition(struct dvb_ca_private *ca,
1359 					    int *result, int *_slot)
1360 {
1361 	int slot;
1362 	int slot_count = 0;
1363 	int idx;
1364 	size_t fraglen;
1365 	int connection_id = -1;
1366 	int found = 0;
1367 	u8 hdr[2];
1368 
1369 	slot = ca->next_read_slot;
1370 	while ((slot_count < ca->slot_count) && (!found)) {
1371 		if (ca->slot_info[slot].slot_state != DVB_CA_SLOTSTATE_RUNNING)
1372 			goto nextslot;
1373 
1374 		if (ca->slot_info[slot].rx_buffer.data == NULL) {
1375 			return 0;
1376 		}
1377 
1378 		idx = dvb_ringbuffer_pkt_next(&ca->slot_info[slot].rx_buffer, -1, &fraglen);
1379 		while (idx != -1) {
1380 			dvb_ringbuffer_pkt_read(&ca->slot_info[slot].rx_buffer, idx, 0, hdr, 2);
1381 			if (connection_id == -1)
1382 				connection_id = hdr[0];
1383 			if ((hdr[0] == connection_id) && ((hdr[1] & 0x80) == 0)) {
1384 				*_slot = slot;
1385 				found = 1;
1386 				break;
1387 			}
1388 
1389 			idx = dvb_ringbuffer_pkt_next(&ca->slot_info[slot].rx_buffer, idx, &fraglen);
1390 		}
1391 
1392 nextslot:
1393 		slot = (slot + 1) % ca->slot_count;
1394 		slot_count++;
1395 	}
1396 
1397 	ca->next_read_slot = slot;
1398 	return found;
1399 }
1400 
1401 
1402 /**
1403  * Implementation of read() syscall.
1404  *
1405  * @param file File structure.
1406  * @param buf Destination buffer.
1407  * @param count Size of destination buffer.
1408  * @param ppos Position in file (ignored).
1409  *
1410  * @return Number of bytes read, or <0 on error.
1411  */
dvb_ca_en50221_io_read(struct file * file,char __user * buf,size_t count,loff_t * ppos)1412 static ssize_t dvb_ca_en50221_io_read(struct file *file, char __user * buf,
1413 				      size_t count, loff_t * ppos)
1414 {
1415 	struct dvb_device *dvbdev = file->private_data;
1416 	struct dvb_ca_private *ca = dvbdev->priv;
1417 	int status;
1418 	int result = 0;
1419 	u8 hdr[2];
1420 	int slot;
1421 	int connection_id = -1;
1422 	size_t idx, idx2;
1423 	int last_fragment = 0;
1424 	size_t fraglen;
1425 	int pktlen;
1426 	int dispose = 0;
1427 
1428 	dprintk("%s\n", __func__);
1429 
1430 	/* Outgoing packet has a 2 byte header. hdr[0] = slot_id, hdr[1] = connection_id */
1431 	if (count < 2)
1432 		return -EINVAL;
1433 
1434 	/* wait for some data */
1435 	if ((status = dvb_ca_en50221_io_read_condition(ca, &result, &slot)) == 0) {
1436 
1437 		/* if we're in nonblocking mode, exit immediately */
1438 		if (file->f_flags & O_NONBLOCK)
1439 			return -EWOULDBLOCK;
1440 
1441 		/* wait for some data */
1442 		status = wait_event_interruptible(ca->wait_queue,
1443 						  dvb_ca_en50221_io_read_condition
1444 						  (ca, &result, &slot));
1445 	}
1446 	if ((status < 0) || (result < 0)) {
1447 		if (result)
1448 			return result;
1449 		return status;
1450 	}
1451 
1452 	idx = dvb_ringbuffer_pkt_next(&ca->slot_info[slot].rx_buffer, -1, &fraglen);
1453 	pktlen = 2;
1454 	do {
1455 		if (idx == -1) {
1456 			printk("dvb_ca adapter %d: BUG: read packet ended before last_fragment encountered\n", ca->dvbdev->adapter->num);
1457 			status = -EIO;
1458 			goto exit;
1459 		}
1460 
1461 		dvb_ringbuffer_pkt_read(&ca->slot_info[slot].rx_buffer, idx, 0, hdr, 2);
1462 		if (connection_id == -1)
1463 			connection_id = hdr[0];
1464 		if (hdr[0] == connection_id) {
1465 			if (pktlen < count) {
1466 				if ((pktlen + fraglen - 2) > count) {
1467 					fraglen = count - pktlen;
1468 				} else {
1469 					fraglen -= 2;
1470 				}
1471 
1472 				if ((status = dvb_ringbuffer_pkt_read_user(&ca->slot_info[slot].rx_buffer, idx, 2,
1473 								      buf + pktlen, fraglen)) < 0) {
1474 					goto exit;
1475 				}
1476 				pktlen += fraglen;
1477 			}
1478 
1479 			if ((hdr[1] & 0x80) == 0)
1480 				last_fragment = 1;
1481 			dispose = 1;
1482 		}
1483 
1484 		idx2 = dvb_ringbuffer_pkt_next(&ca->slot_info[slot].rx_buffer, idx, &fraglen);
1485 		if (dispose)
1486 			dvb_ringbuffer_pkt_dispose(&ca->slot_info[slot].rx_buffer, idx);
1487 		idx = idx2;
1488 		dispose = 0;
1489 	} while (!last_fragment);
1490 
1491 	hdr[0] = slot;
1492 	hdr[1] = connection_id;
1493 	status = copy_to_user(buf, hdr, 2);
1494 	if (status) {
1495 		status = -EFAULT;
1496 		goto exit;
1497 	}
1498 	status = pktlen;
1499 
1500 exit:
1501 	return status;
1502 }
1503 
1504 
1505 /**
1506  * Implementation of file open syscall.
1507  *
1508  * @param inode Inode concerned.
1509  * @param file File concerned.
1510  *
1511  * @return 0 on success, <0 on failure.
1512  */
dvb_ca_en50221_io_open(struct inode * inode,struct file * file)1513 static int dvb_ca_en50221_io_open(struct inode *inode, struct file *file)
1514 {
1515 	struct dvb_device *dvbdev = file->private_data;
1516 	struct dvb_ca_private *ca = dvbdev->priv;
1517 	int err;
1518 	int i;
1519 
1520 	dprintk("%s\n", __func__);
1521 
1522 	if (!try_module_get(ca->pub->owner))
1523 		return -EIO;
1524 
1525 	err = dvb_generic_open(inode, file);
1526 	if (err < 0) {
1527 		module_put(ca->pub->owner);
1528 		return err;
1529 	}
1530 
1531 	for (i = 0; i < ca->slot_count; i++) {
1532 
1533 		if (ca->slot_info[i].slot_state == DVB_CA_SLOTSTATE_RUNNING) {
1534 			if (ca->slot_info[i].rx_buffer.data != NULL) {
1535 				/* it is safe to call this here without locks because
1536 				 * ca->open == 0. Data is not read in this case */
1537 				dvb_ringbuffer_flush(&ca->slot_info[i].rx_buffer);
1538 			}
1539 		}
1540 	}
1541 
1542 	ca->open = 1;
1543 	dvb_ca_en50221_thread_update_delay(ca);
1544 	dvb_ca_en50221_thread_wakeup(ca);
1545 
1546 	return 0;
1547 }
1548 
1549 
1550 /**
1551  * Implementation of file close syscall.
1552  *
1553  * @param inode Inode concerned.
1554  * @param file File concerned.
1555  *
1556  * @return 0 on success, <0 on failure.
1557  */
dvb_ca_en50221_io_release(struct inode * inode,struct file * file)1558 static int dvb_ca_en50221_io_release(struct inode *inode, struct file *file)
1559 {
1560 	struct dvb_device *dvbdev = file->private_data;
1561 	struct dvb_ca_private *ca = dvbdev->priv;
1562 	int err;
1563 
1564 	dprintk("%s\n", __func__);
1565 
1566 	/* mark the CA device as closed */
1567 	ca->open = 0;
1568 	dvb_ca_en50221_thread_update_delay(ca);
1569 
1570 	err = dvb_generic_release(inode, file);
1571 
1572 	module_put(ca->pub->owner);
1573 
1574 	return err;
1575 }
1576 
1577 
1578 /**
1579  * Implementation of poll() syscall.
1580  *
1581  * @param file File concerned.
1582  * @param wait poll wait table.
1583  *
1584  * @return Standard poll mask.
1585  */
dvb_ca_en50221_io_poll(struct file * file,poll_table * wait)1586 static unsigned int dvb_ca_en50221_io_poll(struct file *file, poll_table * wait)
1587 {
1588 	struct dvb_device *dvbdev = file->private_data;
1589 	struct dvb_ca_private *ca = dvbdev->priv;
1590 	unsigned int mask = 0;
1591 	int slot;
1592 	int result = 0;
1593 
1594 	dprintk("%s\n", __func__);
1595 
1596 	if (dvb_ca_en50221_io_read_condition(ca, &result, &slot) == 1) {
1597 		mask |= POLLIN;
1598 	}
1599 
1600 	/* if there is something, return now */
1601 	if (mask)
1602 		return mask;
1603 
1604 	/* wait for something to happen */
1605 	poll_wait(file, &ca->wait_queue, wait);
1606 
1607 	if (dvb_ca_en50221_io_read_condition(ca, &result, &slot) == 1) {
1608 		mask |= POLLIN;
1609 	}
1610 
1611 	return mask;
1612 }
1613 EXPORT_SYMBOL(dvb_ca_en50221_init);
1614 
1615 
1616 static const struct file_operations dvb_ca_fops = {
1617 	.owner = THIS_MODULE,
1618 	.read = dvb_ca_en50221_io_read,
1619 	.write = dvb_ca_en50221_io_write,
1620 	.unlocked_ioctl = dvb_ca_en50221_io_ioctl,
1621 	.open = dvb_ca_en50221_io_open,
1622 	.release = dvb_ca_en50221_io_release,
1623 	.poll = dvb_ca_en50221_io_poll,
1624 	.llseek = noop_llseek,
1625 };
1626 
1627 static struct dvb_device dvbdev_ca = {
1628 	.priv = NULL,
1629 	.users = 1,
1630 	.readers = 1,
1631 	.writers = 1,
1632 	.fops = &dvb_ca_fops,
1633 };
1634 
1635 
1636 /* ******************************************************************************** */
1637 /* Initialisation/shutdown functions */
1638 
1639 
1640 /**
1641  * Initialise a new DVB CA EN50221 interface device.
1642  *
1643  * @param dvb_adapter DVB adapter to attach the new CA device to.
1644  * @param ca The dvb_ca instance.
1645  * @param flags Flags describing the CA device (DVB_CA_FLAG_*).
1646  * @param slot_count Number of slots supported.
1647  *
1648  * @return 0 on success, nonzero on failure
1649  */
dvb_ca_en50221_init(struct dvb_adapter * dvb_adapter,struct dvb_ca_en50221 * pubca,int flags,int slot_count)1650 int dvb_ca_en50221_init(struct dvb_adapter *dvb_adapter,
1651 			struct dvb_ca_en50221 *pubca, int flags, int slot_count)
1652 {
1653 	int ret;
1654 	struct dvb_ca_private *ca = NULL;
1655 	int i;
1656 
1657 	dprintk("%s\n", __func__);
1658 
1659 	if (slot_count < 1)
1660 		return -EINVAL;
1661 
1662 	/* initialise the system data */
1663 	if ((ca = kzalloc(sizeof(struct dvb_ca_private), GFP_KERNEL)) == NULL) {
1664 		ret = -ENOMEM;
1665 		goto error;
1666 	}
1667 	ca->pub = pubca;
1668 	ca->flags = flags;
1669 	ca->slot_count = slot_count;
1670 	if ((ca->slot_info = kcalloc(slot_count, sizeof(struct dvb_ca_slot), GFP_KERNEL)) == NULL) {
1671 		ret = -ENOMEM;
1672 		goto error;
1673 	}
1674 	init_waitqueue_head(&ca->wait_queue);
1675 	ca->open = 0;
1676 	ca->wakeup = 0;
1677 	ca->next_read_slot = 0;
1678 	pubca->private = ca;
1679 
1680 	/* register the DVB device */
1681 	ret = dvb_register_device(dvb_adapter, &ca->dvbdev, &dvbdev_ca, ca, DVB_DEVICE_CA);
1682 	if (ret)
1683 		goto error;
1684 
1685 	/* now initialise each slot */
1686 	for (i = 0; i < slot_count; i++) {
1687 		memset(&ca->slot_info[i], 0, sizeof(struct dvb_ca_slot));
1688 		ca->slot_info[i].slot_state = DVB_CA_SLOTSTATE_NONE;
1689 		atomic_set(&ca->slot_info[i].camchange_count, 0);
1690 		ca->slot_info[i].camchange_type = DVB_CA_EN50221_CAMCHANGE_REMOVED;
1691 		mutex_init(&ca->slot_info[i].slot_lock);
1692 	}
1693 
1694 	if (signal_pending(current)) {
1695 		ret = -EINTR;
1696 		goto error;
1697 	}
1698 	mb();
1699 
1700 	/* create a kthread for monitoring this CA device */
1701 	ca->thread = kthread_run(dvb_ca_en50221_thread, ca, "kdvb-ca-%i:%i",
1702 				 ca->dvbdev->adapter->num, ca->dvbdev->id);
1703 	if (IS_ERR(ca->thread)) {
1704 		ret = PTR_ERR(ca->thread);
1705 		printk("dvb_ca_init: failed to start kernel_thread (%d)\n",
1706 			ret);
1707 		goto error;
1708 	}
1709 	return 0;
1710 
1711 error:
1712 	if (ca != NULL) {
1713 		if (ca->dvbdev != NULL)
1714 			dvb_unregister_device(ca->dvbdev);
1715 		kfree(ca->slot_info);
1716 		kfree(ca);
1717 	}
1718 	pubca->private = NULL;
1719 	return ret;
1720 }
1721 EXPORT_SYMBOL(dvb_ca_en50221_release);
1722 
1723 
1724 
1725 /**
1726  * Release a DVB CA EN50221 interface device.
1727  *
1728  * @param ca_dev The dvb_device_t instance for the CA device.
1729  * @param ca The associated dvb_ca instance.
1730  */
dvb_ca_en50221_release(struct dvb_ca_en50221 * pubca)1731 void dvb_ca_en50221_release(struct dvb_ca_en50221 *pubca)
1732 {
1733 	struct dvb_ca_private *ca = pubca->private;
1734 	int i;
1735 
1736 	dprintk("%s\n", __func__);
1737 
1738 	/* shutdown the thread if there was one */
1739 	kthread_stop(ca->thread);
1740 
1741 	for (i = 0; i < ca->slot_count; i++) {
1742 		dvb_ca_en50221_slot_shutdown(ca, i);
1743 		vfree(ca->slot_info[i].rx_buffer.data);
1744 	}
1745 	kfree(ca->slot_info);
1746 	dvb_unregister_device(ca->dvbdev);
1747 	kfree(ca);
1748 	pubca->private = NULL;
1749 }
1750