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