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