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