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