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