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