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