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