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