Back to home page

OSCL-LXR

 
 

    


0001 // SPDX-License-Identifier: GPL-2.0-or-later
0002 /*
0003  * dvb_ca.c: generic DVB functions for EN50221 CAM interfaces
0004  *
0005  * Copyright (C) 2004 Andrew de Quincey
0006  *
0007  * Parts of this file were based on sources as follows:
0008  *
0009  * Copyright (C) 2003 Ralph Metzler <rjkm@metzlerbros.de>
0010  *
0011  * based on code:
0012  *
0013  * Copyright (C) 1999-2002 Ralph  Metzler
0014  *                       & Marcus Metzler for convergence integrated media GmbH
0015  */
0016 
0017 #define pr_fmt(fmt) "dvb_ca_en50221: " fmt
0018 
0019 #include <linux/errno.h>
0020 #include <linux/slab.h>
0021 #include <linux/list.h>
0022 #include <linux/module.h>
0023 #include <linux/nospec.h>
0024 #include <linux/vmalloc.h>
0025 #include <linux/delay.h>
0026 #include <linux/spinlock.h>
0027 #include <linux/sched/signal.h>
0028 #include <linux/kthread.h>
0029 
0030 #include <media/dvb_ca_en50221.h>
0031 #include <media/dvb_ringbuffer.h>
0032 
0033 static int dvb_ca_en50221_debug;
0034 
0035 module_param_named(cam_debug, dvb_ca_en50221_debug, int, 0644);
0036 MODULE_PARM_DESC(cam_debug, "enable verbose debug messages");
0037 
0038 #define dprintk(fmt, arg...) do {                   \
0039     if (dvb_ca_en50221_debug)                   \
0040         printk(KERN_DEBUG pr_fmt("%s: " fmt), __func__, ##arg);\
0041 } while (0)
0042 
0043 #define INIT_TIMEOUT_SECS 10
0044 
0045 #define HOST_LINK_BUF_SIZE 0x200
0046 
0047 #define RX_BUFFER_SIZE 65535
0048 
0049 #define MAX_RX_PACKETS_PER_ITERATION 10
0050 
0051 #define CTRLIF_DATA      0
0052 #define CTRLIF_COMMAND   1
0053 #define CTRLIF_STATUS    1
0054 #define CTRLIF_SIZE_LOW  2
0055 #define CTRLIF_SIZE_HIGH 3
0056 
0057 #define CMDREG_HC        1  /* Host control */
0058 #define CMDREG_SW        2  /* Size write */
0059 #define CMDREG_SR        4  /* Size read */
0060 #define CMDREG_RS        8  /* Reset interface */
0061 #define CMDREG_FRIE   0x40  /* Enable FR interrupt */
0062 #define CMDREG_DAIE   0x80  /* Enable DA interrupt */
0063 #define IRQEN (CMDREG_DAIE)
0064 
0065 #define STATUSREG_RE     1  /* read error */
0066 #define STATUSREG_WE     2  /* write error */
0067 #define STATUSREG_FR  0x40  /* module free */
0068 #define STATUSREG_DA  0x80  /* data available */
0069 
0070 #define DVB_CA_SLOTSTATE_NONE           0
0071 #define DVB_CA_SLOTSTATE_UNINITIALISED  1
0072 #define DVB_CA_SLOTSTATE_RUNNING        2
0073 #define DVB_CA_SLOTSTATE_INVALID        3
0074 #define DVB_CA_SLOTSTATE_WAITREADY      4
0075 #define DVB_CA_SLOTSTATE_VALIDATE       5
0076 #define DVB_CA_SLOTSTATE_WAITFR         6
0077 #define DVB_CA_SLOTSTATE_LINKINIT       7
0078 
0079 /* Information on a CA slot */
0080 struct dvb_ca_slot {
0081     /* current state of the CAM */
0082     int slot_state;
0083 
0084     /* mutex used for serializing access to one CI slot */
0085     struct mutex slot_lock;
0086 
0087     /* Number of CAMCHANGES that have occurred since last processing */
0088     atomic_t camchange_count;
0089 
0090     /* Type of last CAMCHANGE */
0091     int camchange_type;
0092 
0093     /* base address of CAM config */
0094     u32 config_base;
0095 
0096     /* value to write into Config Control register */
0097     u8 config_option;
0098 
0099     /* if 1, the CAM supports DA IRQs */
0100     u8 da_irq_supported:1;
0101 
0102     /* size of the buffer to use when talking to the CAM */
0103     int link_buf_size;
0104 
0105     /* buffer for incoming packets */
0106     struct dvb_ringbuffer rx_buffer;
0107 
0108     /* timer used during various states of the slot */
0109     unsigned long timeout;
0110 };
0111 
0112 /* Private CA-interface information */
0113 struct dvb_ca_private {
0114     struct kref refcount;
0115 
0116     /* pointer back to the public data structure */
0117     struct dvb_ca_en50221 *pub;
0118 
0119     /* the DVB device */
0120     struct dvb_device *dvbdev;
0121 
0122     /* Flags describing the interface (DVB_CA_FLAG_*) */
0123     u32 flags;
0124 
0125     /* number of slots supported by this CA interface */
0126     unsigned int slot_count;
0127 
0128     /* information on each slot */
0129     struct dvb_ca_slot *slot_info;
0130 
0131     /* wait queues for read() and write() operations */
0132     wait_queue_head_t wait_queue;
0133 
0134     /* PID of the monitoring thread */
0135     struct task_struct *thread;
0136 
0137     /* Flag indicating if the CA device is open */
0138     unsigned int open:1;
0139 
0140     /* Flag indicating the thread should wake up now */
0141     unsigned int wakeup:1;
0142 
0143     /* Delay the main thread should use */
0144     unsigned long delay;
0145 
0146     /*
0147      * Slot to start looking for data to read from in the next user-space
0148      * read operation
0149      */
0150     int next_read_slot;
0151 
0152     /* mutex serializing ioctls */
0153     struct mutex ioctl_mutex;
0154 };
0155 
0156 static void dvb_ca_private_free(struct dvb_ca_private *ca)
0157 {
0158     unsigned int i;
0159 
0160     dvb_free_device(ca->dvbdev);
0161     for (i = 0; i < ca->slot_count; i++)
0162         vfree(ca->slot_info[i].rx_buffer.data);
0163 
0164     kfree(ca->slot_info);
0165     kfree(ca);
0166 }
0167 
0168 static void dvb_ca_private_release(struct kref *ref)
0169 {
0170     struct dvb_ca_private *ca;
0171 
0172     ca = container_of(ref, struct dvb_ca_private, refcount);
0173     dvb_ca_private_free(ca);
0174 }
0175 
0176 static void dvb_ca_private_get(struct dvb_ca_private *ca)
0177 {
0178     kref_get(&ca->refcount);
0179 }
0180 
0181 static void dvb_ca_private_put(struct dvb_ca_private *ca)
0182 {
0183     kref_put(&ca->refcount, dvb_ca_private_release);
0184 }
0185 
0186 static void dvb_ca_en50221_thread_wakeup(struct dvb_ca_private *ca);
0187 static int dvb_ca_en50221_read_data(struct dvb_ca_private *ca, int slot,
0188                     u8 *ebuf, int ecount);
0189 static int dvb_ca_en50221_write_data(struct dvb_ca_private *ca, int slot,
0190                      u8 *ebuf, int ecount);
0191 
0192 /**
0193  * findstr - Safely find needle in haystack.
0194  *
0195  * @haystack: Buffer to look in.
0196  * @hlen: Number of bytes in haystack.
0197  * @needle: Buffer to find.
0198  * @nlen: Number of bytes in needle.
0199  * return: Pointer into haystack needle was found at, or NULL if not found.
0200  */
0201 static char *findstr(char *haystack, int hlen, char *needle, int nlen)
0202 {
0203     int i;
0204 
0205     if (hlen < nlen)
0206         return NULL;
0207 
0208     for (i = 0; i <= hlen - nlen; i++) {
0209         if (!strncmp(haystack + i, needle, nlen))
0210             return haystack + i;
0211     }
0212 
0213     return NULL;
0214 }
0215 
0216 /* ************************************************************************** */
0217 /* EN50221 physical interface functions */
0218 
0219 /*
0220  * dvb_ca_en50221_check_camstatus - Check CAM status.
0221  */
0222 static int dvb_ca_en50221_check_camstatus(struct dvb_ca_private *ca, int slot)
0223 {
0224     struct dvb_ca_slot *sl = &ca->slot_info[slot];
0225     int slot_status;
0226     int cam_present_now;
0227     int cam_changed;
0228 
0229     /* IRQ mode */
0230     if (ca->flags & DVB_CA_EN50221_FLAG_IRQ_CAMCHANGE)
0231         return (atomic_read(&sl->camchange_count) != 0);
0232 
0233     /* poll mode */
0234     slot_status = ca->pub->poll_slot_status(ca->pub, slot, ca->open);
0235 
0236     cam_present_now = (slot_status & DVB_CA_EN50221_POLL_CAM_PRESENT) ? 1 : 0;
0237     cam_changed = (slot_status & DVB_CA_EN50221_POLL_CAM_CHANGED) ? 1 : 0;
0238     if (!cam_changed) {
0239         int cam_present_old = (sl->slot_state != DVB_CA_SLOTSTATE_NONE);
0240 
0241         cam_changed = (cam_present_now != cam_present_old);
0242     }
0243 
0244     if (cam_changed) {
0245         if (!cam_present_now)
0246             sl->camchange_type = DVB_CA_EN50221_CAMCHANGE_REMOVED;
0247         else
0248             sl->camchange_type = DVB_CA_EN50221_CAMCHANGE_INSERTED;
0249         atomic_set(&sl->camchange_count, 1);
0250     } else {
0251         if ((sl->slot_state == DVB_CA_SLOTSTATE_WAITREADY) &&
0252             (slot_status & DVB_CA_EN50221_POLL_CAM_READY)) {
0253             /* move to validate state if reset is completed */
0254             sl->slot_state = DVB_CA_SLOTSTATE_VALIDATE;
0255         }
0256     }
0257 
0258     return cam_changed;
0259 }
0260 
0261 /**
0262  * dvb_ca_en50221_wait_if_status - Wait for flags to become set on the STATUS
0263  *   register on a CAM interface, checking for errors and timeout.
0264  *
0265  * @ca: CA instance.
0266  * @slot: Slot on interface.
0267  * @waitfor: Flags to wait for.
0268  * @timeout_hz: Timeout in milliseconds.
0269  *
0270  * return: 0 on success, nonzero on error.
0271  */
0272 static int dvb_ca_en50221_wait_if_status(struct dvb_ca_private *ca, int slot,
0273                      u8 waitfor, int timeout_hz)
0274 {
0275     unsigned long timeout;
0276     unsigned long start;
0277 
0278     dprintk("%s\n", __func__);
0279 
0280     /* loop until timeout elapsed */
0281     start = jiffies;
0282     timeout = jiffies + timeout_hz;
0283     while (1) {
0284         int res;
0285 
0286         /* read the status and check for error */
0287         res = ca->pub->read_cam_control(ca->pub, slot, CTRLIF_STATUS);
0288         if (res < 0)
0289             return -EIO;
0290 
0291         /* if we got the flags, it was successful! */
0292         if (res & waitfor) {
0293             dprintk("%s succeeded timeout:%lu\n",
0294                 __func__, jiffies - start);
0295             return 0;
0296         }
0297 
0298         /* check for timeout */
0299         if (time_after(jiffies, timeout))
0300             break;
0301 
0302         /* wait for a bit */
0303         usleep_range(1000, 1100);
0304     }
0305 
0306     dprintk("%s failed timeout:%lu\n", __func__, jiffies - start);
0307 
0308     /* if we get here, we've timed out */
0309     return -ETIMEDOUT;
0310 }
0311 
0312 /**
0313  * dvb_ca_en50221_link_init - Initialise the link layer connection to a CAM.
0314  *
0315  * @ca: CA instance.
0316  * @slot: Slot id.
0317  *
0318  * return: 0 on success, nonzero on failure.
0319  */
0320 static int dvb_ca_en50221_link_init(struct dvb_ca_private *ca, int slot)
0321 {
0322     struct dvb_ca_slot *sl = &ca->slot_info[slot];
0323     int ret;
0324     int buf_size;
0325     u8 buf[2];
0326 
0327     dprintk("%s\n", __func__);
0328 
0329     /* we'll be determining these during this function */
0330     sl->da_irq_supported = 0;
0331 
0332     /*
0333      * set the host link buffer size temporarily. it will be overwritten
0334      * with the real negotiated size later.
0335      */
0336     sl->link_buf_size = 2;
0337 
0338     /* read the buffer size from the CAM */
0339     ret = ca->pub->write_cam_control(ca->pub, slot, CTRLIF_COMMAND,
0340                      IRQEN | CMDREG_SR);
0341     if (ret)
0342         return ret;
0343     ret = dvb_ca_en50221_wait_if_status(ca, slot, STATUSREG_DA, HZ);
0344     if (ret)
0345         return ret;
0346     ret = dvb_ca_en50221_read_data(ca, slot, buf, 2);
0347     if (ret != 2)
0348         return -EIO;
0349     ret = ca->pub->write_cam_control(ca->pub, slot, CTRLIF_COMMAND, IRQEN);
0350     if (ret)
0351         return ret;
0352 
0353     /*
0354      * store it, and choose the minimum of our buffer and the CAM's buffer
0355      * size
0356      */
0357     buf_size = (buf[0] << 8) | buf[1];
0358     if (buf_size > HOST_LINK_BUF_SIZE)
0359         buf_size = HOST_LINK_BUF_SIZE;
0360     sl->link_buf_size = buf_size;
0361     buf[0] = buf_size >> 8;
0362     buf[1] = buf_size & 0xff;
0363     dprintk("Chosen link buffer size of %i\n", buf_size);
0364 
0365     /* write the buffer size to the CAM */
0366     ret = ca->pub->write_cam_control(ca->pub, slot, CTRLIF_COMMAND,
0367                      IRQEN | CMDREG_SW);
0368     if (ret)
0369         return ret;
0370     ret = dvb_ca_en50221_wait_if_status(ca, slot, STATUSREG_FR, HZ / 10);
0371     if (ret)
0372         return ret;
0373     ret = dvb_ca_en50221_write_data(ca, slot, buf, 2);
0374     if (ret != 2)
0375         return -EIO;
0376     ret = ca->pub->write_cam_control(ca->pub, slot, CTRLIF_COMMAND, IRQEN);
0377     if (ret)
0378         return ret;
0379 
0380     /* success */
0381     return 0;
0382 }
0383 
0384 /**
0385  * dvb_ca_en50221_read_tuple - Read a tuple from attribute memory.
0386  *
0387  * @ca: CA instance.
0388  * @slot: Slot id.
0389  * @address: Address to read from. Updated.
0390  * @tuple_type: Tuple id byte. Updated.
0391  * @tuple_length: Tuple length. Updated.
0392  * @tuple: Dest buffer for tuple (must be 256 bytes). Updated.
0393  *
0394  * return: 0 on success, nonzero on error.
0395  */
0396 static int dvb_ca_en50221_read_tuple(struct dvb_ca_private *ca, int slot,
0397                      int *address, int *tuple_type,
0398                      int *tuple_length, u8 *tuple)
0399 {
0400     int i;
0401     int _tuple_type;
0402     int _tuple_length;
0403     int _address = *address;
0404 
0405     /* grab the next tuple length and type */
0406     _tuple_type = ca->pub->read_attribute_mem(ca->pub, slot, _address);
0407     if (_tuple_type < 0)
0408         return _tuple_type;
0409     if (_tuple_type == 0xff) {
0410         dprintk("END OF CHAIN TUPLE type:0x%x\n", _tuple_type);
0411         *address += 2;
0412         *tuple_type = _tuple_type;
0413         *tuple_length = 0;
0414         return 0;
0415     }
0416     _tuple_length = ca->pub->read_attribute_mem(ca->pub, slot,
0417                             _address + 2);
0418     if (_tuple_length < 0)
0419         return _tuple_length;
0420     _address += 4;
0421 
0422     dprintk("TUPLE type:0x%x length:%i\n", _tuple_type, _tuple_length);
0423 
0424     /* read in the whole tuple */
0425     for (i = 0; i < _tuple_length; i++) {
0426         tuple[i] = ca->pub->read_attribute_mem(ca->pub, slot,
0427                                _address + (i * 2));
0428         dprintk("  0x%02x: 0x%02x %c\n",
0429             i, tuple[i] & 0xff,
0430             ((tuple[i] > 31) && (tuple[i] < 127)) ? tuple[i] : '.');
0431     }
0432     _address += (_tuple_length * 2);
0433 
0434     /* success */
0435     *tuple_type = _tuple_type;
0436     *tuple_length = _tuple_length;
0437     *address = _address;
0438     return 0;
0439 }
0440 
0441 /**
0442  * dvb_ca_en50221_parse_attributes - Parse attribute memory of a CAM module,
0443  *  extracting Config register, and checking it is a DVB CAM module.
0444  *
0445  * @ca: CA instance.
0446  * @slot: Slot id.
0447  *
0448  * return: 0 on success, <0 on failure.
0449  */
0450 static int dvb_ca_en50221_parse_attributes(struct dvb_ca_private *ca, int slot)
0451 {
0452     struct dvb_ca_slot *sl;
0453     int address = 0;
0454     int tuple_length;
0455     int tuple_type;
0456     u8 tuple[257];
0457     char *dvb_str;
0458     int rasz;
0459     int status;
0460     int got_cftableentry = 0;
0461     int end_chain = 0;
0462     int i;
0463     u16 manfid = 0;
0464     u16 devid = 0;
0465 
0466     /* CISTPL_DEVICE_0A */
0467     status = dvb_ca_en50221_read_tuple(ca, slot, &address, &tuple_type,
0468                        &tuple_length, tuple);
0469     if (status < 0)
0470         return status;
0471     if (tuple_type != 0x1D)
0472         return -EINVAL;
0473 
0474     /* CISTPL_DEVICE_0C */
0475     status = dvb_ca_en50221_read_tuple(ca, slot, &address, &tuple_type,
0476                        &tuple_length, tuple);
0477     if (status < 0)
0478         return status;
0479     if (tuple_type != 0x1C)
0480         return -EINVAL;
0481 
0482     /* CISTPL_VERS_1 */
0483     status = dvb_ca_en50221_read_tuple(ca, slot, &address, &tuple_type,
0484                        &tuple_length, tuple);
0485     if (status < 0)
0486         return status;
0487     if (tuple_type != 0x15)
0488         return -EINVAL;
0489 
0490     /* CISTPL_MANFID */
0491     status = dvb_ca_en50221_read_tuple(ca, slot, &address, &tuple_type,
0492                        &tuple_length, tuple);
0493     if (status < 0)
0494         return status;
0495     if (tuple_type != 0x20)
0496         return -EINVAL;
0497     if (tuple_length != 4)
0498         return -EINVAL;
0499     manfid = (tuple[1] << 8) | tuple[0];
0500     devid = (tuple[3] << 8) | tuple[2];
0501 
0502     /* CISTPL_CONFIG */
0503     status = dvb_ca_en50221_read_tuple(ca, slot, &address, &tuple_type,
0504                        &tuple_length, tuple);
0505     if (status < 0)
0506         return status;
0507     if (tuple_type != 0x1A)
0508         return -EINVAL;
0509     if (tuple_length < 3)
0510         return -EINVAL;
0511 
0512     /* extract the configbase */
0513     rasz = tuple[0] & 3;
0514     if (tuple_length < (3 + rasz + 14))
0515         return -EINVAL;
0516     sl = &ca->slot_info[slot];
0517     sl->config_base = 0;
0518     for (i = 0; i < rasz + 1; i++)
0519         sl->config_base |= (tuple[2 + i] << (8 * i));
0520 
0521     /* check it contains the correct DVB string */
0522     dvb_str = findstr((char *)tuple, tuple_length, "DVB_CI_V", 8);
0523     if (!dvb_str)
0524         return -EINVAL;
0525     if (tuple_length < ((dvb_str - (char *)tuple) + 12))
0526         return -EINVAL;
0527 
0528     /* is it a version we support? */
0529     if (strncmp(dvb_str + 8, "1.00", 4)) {
0530         pr_err("dvb_ca adapter %d: Unsupported DVB CAM module version %c%c%c%c\n",
0531                ca->dvbdev->adapter->num, dvb_str[8], dvb_str[9],
0532                dvb_str[10], dvb_str[11]);
0533         return -EINVAL;
0534     }
0535 
0536     /* process the CFTABLE_ENTRY tuples, and any after those */
0537     while ((!end_chain) && (address < 0x1000)) {
0538         status = dvb_ca_en50221_read_tuple(ca, slot, &address,
0539                            &tuple_type, &tuple_length,
0540                            tuple);
0541         if (status < 0)
0542             return status;
0543         switch (tuple_type) {
0544         case 0x1B:  /* CISTPL_CFTABLE_ENTRY */
0545             if (tuple_length < (2 + 11 + 17))
0546                 break;
0547 
0548             /* if we've already parsed one, just use it */
0549             if (got_cftableentry)
0550                 break;
0551 
0552             /* get the config option */
0553             sl->config_option = tuple[0] & 0x3f;
0554 
0555             /* OK, check it contains the correct strings */
0556             if (!findstr((char *)tuple, tuple_length,
0557                      "DVB_HOST", 8) ||
0558                 !findstr((char *)tuple, tuple_length,
0559                      "DVB_CI_MODULE", 13))
0560                 break;
0561 
0562             got_cftableentry = 1;
0563             break;
0564 
0565         case 0x14:  /* CISTPL_NO_LINK */
0566             break;
0567 
0568         case 0xFF:  /* CISTPL_END */
0569             end_chain = 1;
0570             break;
0571 
0572         default:    /* Unknown tuple type - just skip this tuple */
0573             dprintk("dvb_ca: Skipping unknown tuple type:0x%x length:0x%x\n",
0574                 tuple_type, tuple_length);
0575             break;
0576         }
0577     }
0578 
0579     if ((address > 0x1000) || (!got_cftableentry))
0580         return -EINVAL;
0581 
0582     dprintk("Valid DVB CAM detected MANID:%x DEVID:%x CONFIGBASE:0x%x CONFIGOPTION:0x%x\n",
0583         manfid, devid, sl->config_base, sl->config_option);
0584 
0585     /* success! */
0586     return 0;
0587 }
0588 
0589 /**
0590  * dvb_ca_en50221_set_configoption - Set CAM's configoption correctly.
0591  *
0592  * @ca: CA instance.
0593  * @slot: Slot containing the CAM.
0594  */
0595 static int dvb_ca_en50221_set_configoption(struct dvb_ca_private *ca, int slot)
0596 {
0597     struct dvb_ca_slot *sl = &ca->slot_info[slot];
0598     int configoption;
0599 
0600     dprintk("%s\n", __func__);
0601 
0602     /* set the config option */
0603     ca->pub->write_attribute_mem(ca->pub, slot, sl->config_base,
0604                      sl->config_option);
0605 
0606     /* check it */
0607     configoption = ca->pub->read_attribute_mem(ca->pub, slot,
0608                            sl->config_base);
0609     dprintk("Set configoption 0x%x, read configoption 0x%x\n",
0610         sl->config_option, configoption & 0x3f);
0611 
0612     /* fine! */
0613     return 0;
0614 }
0615 
0616 /**
0617  * dvb_ca_en50221_read_data - This function talks to an EN50221 CAM control
0618  *  interface. It reads a buffer of data from the CAM. The data can either
0619  *  be stored in a supplied buffer, or automatically be added to the slot's
0620  *  rx_buffer.
0621  *
0622  * @ca: CA instance.
0623  * @slot: Slot to read from.
0624  * @ebuf: If non-NULL, the data will be written to this buffer. If NULL,
0625  *    the data will be added into the buffering system as a normal
0626  *    fragment.
0627  * @ecount: Size of ebuf. Ignored if ebuf is NULL.
0628  *
0629  * return: Number of bytes read, or < 0 on error
0630  */
0631 static int dvb_ca_en50221_read_data(struct dvb_ca_private *ca, int slot,
0632                     u8 *ebuf, int ecount)
0633 {
0634     struct dvb_ca_slot *sl = &ca->slot_info[slot];
0635     int bytes_read;
0636     int status;
0637     u8 buf[HOST_LINK_BUF_SIZE];
0638     int i;
0639 
0640     dprintk("%s\n", __func__);
0641 
0642     /* check if we have space for a link buf in the rx_buffer */
0643     if (!ebuf) {
0644         int buf_free;
0645 
0646         if (!sl->rx_buffer.data) {
0647             status = -EIO;
0648             goto exit;
0649         }
0650         buf_free = dvb_ringbuffer_free(&sl->rx_buffer);
0651 
0652         if (buf_free < (sl->link_buf_size +
0653                 DVB_RINGBUFFER_PKTHDRSIZE)) {
0654             status = -EAGAIN;
0655             goto exit;
0656         }
0657     }
0658 
0659     if (ca->pub->read_data &&
0660         (sl->slot_state != DVB_CA_SLOTSTATE_LINKINIT)) {
0661         if (!ebuf)
0662             status = ca->pub->read_data(ca->pub, slot, buf,
0663                             sizeof(buf));
0664         else
0665             status = ca->pub->read_data(ca->pub, slot, buf, ecount);
0666         if (status < 0)
0667             return status;
0668         bytes_read =  status;
0669         if (status == 0)
0670             goto exit;
0671     } else {
0672         /* check if there is data available */
0673         status = ca->pub->read_cam_control(ca->pub, slot,
0674                            CTRLIF_STATUS);
0675         if (status < 0)
0676             goto exit;
0677         if (!(status & STATUSREG_DA)) {
0678             /* no data */
0679             status = 0;
0680             goto exit;
0681         }
0682 
0683         /* read the amount of data */
0684         status = ca->pub->read_cam_control(ca->pub, slot,
0685                            CTRLIF_SIZE_HIGH);
0686         if (status < 0)
0687             goto exit;
0688         bytes_read = status << 8;
0689         status = ca->pub->read_cam_control(ca->pub, slot,
0690                            CTRLIF_SIZE_LOW);
0691         if (status < 0)
0692             goto exit;
0693         bytes_read |= status;
0694 
0695         /* check it will fit */
0696         if (!ebuf) {
0697             if (bytes_read > sl->link_buf_size) {
0698                 pr_err("dvb_ca adapter %d: CAM tried to send a buffer larger than the link buffer size (%i > %i)!\n",
0699                        ca->dvbdev->adapter->num, bytes_read,
0700                        sl->link_buf_size);
0701                 sl->slot_state = DVB_CA_SLOTSTATE_LINKINIT;
0702                 status = -EIO;
0703                 goto exit;
0704             }
0705             if (bytes_read < 2) {
0706                 pr_err("dvb_ca adapter %d: CAM sent a buffer that was less than 2 bytes!\n",
0707                        ca->dvbdev->adapter->num);
0708                 sl->slot_state = DVB_CA_SLOTSTATE_LINKINIT;
0709                 status = -EIO;
0710                 goto exit;
0711             }
0712         } else {
0713             if (bytes_read > ecount) {
0714                 pr_err("dvb_ca adapter %d: CAM tried to send a buffer larger than the ecount size!\n",
0715                        ca->dvbdev->adapter->num);
0716                 status = -EIO;
0717                 goto exit;
0718             }
0719         }
0720 
0721         /* fill the buffer */
0722         for (i = 0; i < bytes_read; i++) {
0723             /* read byte and check */
0724             status = ca->pub->read_cam_control(ca->pub, slot,
0725                                CTRLIF_DATA);
0726             if (status < 0)
0727                 goto exit;
0728 
0729             /* OK, store it in the buffer */
0730             buf[i] = status;
0731         }
0732 
0733         /* check for read error (RE should now be 0) */
0734         status = ca->pub->read_cam_control(ca->pub, slot,
0735                            CTRLIF_STATUS);
0736         if (status < 0)
0737             goto exit;
0738         if (status & STATUSREG_RE) {
0739             sl->slot_state = DVB_CA_SLOTSTATE_LINKINIT;
0740             status = -EIO;
0741             goto exit;
0742         }
0743     }
0744 
0745     /*
0746      * OK, add it to the receive buffer, or copy into external buffer if
0747      * supplied
0748      */
0749     if (!ebuf) {
0750         if (!sl->rx_buffer.data) {
0751             status = -EIO;
0752             goto exit;
0753         }
0754         dvb_ringbuffer_pkt_write(&sl->rx_buffer, buf, bytes_read);
0755     } else {
0756         memcpy(ebuf, buf, bytes_read);
0757     }
0758 
0759     dprintk("Received CA packet for slot %i connection id 0x%x last_frag:%i size:0x%x\n", slot,
0760         buf[0], (buf[1] & 0x80) == 0, bytes_read);
0761 
0762     /* wake up readers when a last_fragment is received */
0763     if ((buf[1] & 0x80) == 0x00)
0764         wake_up_interruptible(&ca->wait_queue);
0765 
0766     status = bytes_read;
0767 
0768 exit:
0769     return status;
0770 }
0771 
0772 /**
0773  * dvb_ca_en50221_write_data - This function talks to an EN50221 CAM control
0774  *              interface. It writes a buffer of data to a CAM.
0775  *
0776  * @ca: CA instance.
0777  * @slot: Slot to write to.
0778  * @buf: The data in this buffer is treated as a complete link-level packet to
0779  *   be written.
0780  * @bytes_write: Size of ebuf.
0781  *
0782  * return: Number of bytes written, or < 0 on error.
0783  */
0784 static int dvb_ca_en50221_write_data(struct dvb_ca_private *ca, int slot,
0785                      u8 *buf, int bytes_write)
0786 {
0787     struct dvb_ca_slot *sl = &ca->slot_info[slot];
0788     int status;
0789     int i;
0790 
0791     dprintk("%s\n", __func__);
0792 
0793     /* sanity check */
0794     if (bytes_write > sl->link_buf_size)
0795         return -EINVAL;
0796 
0797     if (ca->pub->write_data &&
0798         (sl->slot_state != DVB_CA_SLOTSTATE_LINKINIT))
0799         return ca->pub->write_data(ca->pub, slot, buf, bytes_write);
0800 
0801     /*
0802      * it is possible we are dealing with a single buffer implementation,
0803      * thus if there is data available for read or if there is even a read
0804      * already in progress, we do nothing but awake the kernel thread to
0805      * process the data if necessary.
0806      */
0807     status = ca->pub->read_cam_control(ca->pub, slot, CTRLIF_STATUS);
0808     if (status < 0)
0809         goto exitnowrite;
0810     if (status & (STATUSREG_DA | STATUSREG_RE)) {
0811         if (status & STATUSREG_DA)
0812             dvb_ca_en50221_thread_wakeup(ca);
0813 
0814         status = -EAGAIN;
0815         goto exitnowrite;
0816     }
0817 
0818     /* OK, set HC bit */
0819     status = ca->pub->write_cam_control(ca->pub, slot, CTRLIF_COMMAND,
0820                         IRQEN | CMDREG_HC);
0821     if (status)
0822         goto exit;
0823 
0824     /* check if interface is still free */
0825     status = ca->pub->read_cam_control(ca->pub, slot, CTRLIF_STATUS);
0826     if (status < 0)
0827         goto exit;
0828     if (!(status & STATUSREG_FR)) {
0829         /* it wasn't free => try again later */
0830         status = -EAGAIN;
0831         goto exit;
0832     }
0833 
0834     /*
0835      * It may need some time for the CAM to settle down, or there might
0836      * be a race condition between the CAM, writing HC and our last
0837      * check for DA. This happens, if the CAM asserts DA, just after
0838      * checking DA before we are setting HC. In this case it might be
0839      * a bug in the CAM to keep the FR bit, the lower layer/HW
0840      * communication requires a longer timeout or the CAM needs more
0841      * time internally. But this happens in reality!
0842      * We need to read the status from the HW again and do the same
0843      * we did for the previous check for DA
0844      */
0845     status = ca->pub->read_cam_control(ca->pub, slot, CTRLIF_STATUS);
0846     if (status < 0)
0847         goto exit;
0848 
0849     if (status & (STATUSREG_DA | STATUSREG_RE)) {
0850         if (status & STATUSREG_DA)
0851             dvb_ca_en50221_thread_wakeup(ca);
0852 
0853         status = -EAGAIN;
0854         goto exit;
0855     }
0856 
0857     /* send the amount of data */
0858     status = ca->pub->write_cam_control(ca->pub, slot, CTRLIF_SIZE_HIGH,
0859                         bytes_write >> 8);
0860     if (status)
0861         goto exit;
0862     status = ca->pub->write_cam_control(ca->pub, slot, CTRLIF_SIZE_LOW,
0863                         bytes_write & 0xff);
0864     if (status)
0865         goto exit;
0866 
0867     /* send the buffer */
0868     for (i = 0; i < bytes_write; i++) {
0869         status = ca->pub->write_cam_control(ca->pub, slot, CTRLIF_DATA,
0870                             buf[i]);
0871         if (status)
0872             goto exit;
0873     }
0874 
0875     /* check for write error (WE should now be 0) */
0876     status = ca->pub->read_cam_control(ca->pub, slot, CTRLIF_STATUS);
0877     if (status < 0)
0878         goto exit;
0879     if (status & STATUSREG_WE) {
0880         sl->slot_state = DVB_CA_SLOTSTATE_LINKINIT;
0881         status = -EIO;
0882         goto exit;
0883     }
0884     status = bytes_write;
0885 
0886     dprintk("Wrote CA packet for slot %i, connection id 0x%x last_frag:%i size:0x%x\n", slot,
0887         buf[0], (buf[1] & 0x80) == 0, bytes_write);
0888 
0889 exit:
0890     ca->pub->write_cam_control(ca->pub, slot, CTRLIF_COMMAND, IRQEN);
0891 
0892 exitnowrite:
0893     return status;
0894 }
0895 
0896 /* ************************************************************************** */
0897 /* EN50221 higher level functions */
0898 
0899 /**
0900  * dvb_ca_en50221_slot_shutdown - A CAM has been removed => shut it down.
0901  *
0902  * @ca: CA instance.
0903  * @slot: Slot to shut down.
0904  */
0905 static int dvb_ca_en50221_slot_shutdown(struct dvb_ca_private *ca, int slot)
0906 {
0907     dprintk("%s\n", __func__);
0908 
0909     ca->pub->slot_shutdown(ca->pub, slot);
0910     ca->slot_info[slot].slot_state = DVB_CA_SLOTSTATE_NONE;
0911 
0912     /*
0913      * need to wake up all processes to check if they're now trying to
0914      * write to a defunct CAM
0915      */
0916     wake_up_interruptible(&ca->wait_queue);
0917 
0918     dprintk("Slot %i shutdown\n", slot);
0919 
0920     /* success */
0921     return 0;
0922 }
0923 
0924 /**
0925  * dvb_ca_en50221_camchange_irq - A CAMCHANGE IRQ has occurred.
0926  *
0927  * @pubca: CA instance.
0928  * @slot: Slot concerned.
0929  * @change_type: One of the DVB_CA_CAMCHANGE_* values.
0930  */
0931 void dvb_ca_en50221_camchange_irq(struct dvb_ca_en50221 *pubca, int slot,
0932                   int change_type)
0933 {
0934     struct dvb_ca_private *ca = pubca->private;
0935     struct dvb_ca_slot *sl = &ca->slot_info[slot];
0936 
0937     dprintk("CAMCHANGE IRQ slot:%i change_type:%i\n", slot, change_type);
0938 
0939     switch (change_type) {
0940     case DVB_CA_EN50221_CAMCHANGE_REMOVED:
0941     case DVB_CA_EN50221_CAMCHANGE_INSERTED:
0942         break;
0943 
0944     default:
0945         return;
0946     }
0947 
0948     sl->camchange_type = change_type;
0949     atomic_inc(&sl->camchange_count);
0950     dvb_ca_en50221_thread_wakeup(ca);
0951 }
0952 EXPORT_SYMBOL(dvb_ca_en50221_camchange_irq);
0953 
0954 /**
0955  * dvb_ca_en50221_camready_irq - A CAMREADY IRQ has occurred.
0956  *
0957  * @pubca: CA instance.
0958  * @slot: Slot concerned.
0959  */
0960 void dvb_ca_en50221_camready_irq(struct dvb_ca_en50221 *pubca, int slot)
0961 {
0962     struct dvb_ca_private *ca = pubca->private;
0963     struct dvb_ca_slot *sl = &ca->slot_info[slot];
0964 
0965     dprintk("CAMREADY IRQ slot:%i\n", slot);
0966 
0967     if (sl->slot_state == DVB_CA_SLOTSTATE_WAITREADY) {
0968         sl->slot_state = DVB_CA_SLOTSTATE_VALIDATE;
0969         dvb_ca_en50221_thread_wakeup(ca);
0970     }
0971 }
0972 EXPORT_SYMBOL(dvb_ca_en50221_camready_irq);
0973 
0974 /**
0975  * dvb_ca_en50221_frda_irq - An FR or DA IRQ has occurred.
0976  *
0977  * @pubca: CA instance.
0978  * @slot: Slot concerned.
0979  */
0980 void dvb_ca_en50221_frda_irq(struct dvb_ca_en50221 *pubca, int slot)
0981 {
0982     struct dvb_ca_private *ca = pubca->private;
0983     struct dvb_ca_slot *sl = &ca->slot_info[slot];
0984     int flags;
0985 
0986     dprintk("FR/DA IRQ slot:%i\n", slot);
0987 
0988     switch (sl->slot_state) {
0989     case DVB_CA_SLOTSTATE_LINKINIT:
0990         flags = ca->pub->read_cam_control(pubca, slot, CTRLIF_STATUS);
0991         if (flags & STATUSREG_DA) {
0992             dprintk("CAM supports DA IRQ\n");
0993             sl->da_irq_supported = 1;
0994         }
0995         break;
0996 
0997     case DVB_CA_SLOTSTATE_RUNNING:
0998         if (ca->open)
0999             dvb_ca_en50221_thread_wakeup(ca);
1000         break;
1001     }
1002 }
1003 EXPORT_SYMBOL(dvb_ca_en50221_frda_irq);
1004 
1005 /* ************************************************************************** */
1006 /* EN50221 thread functions */
1007 
1008 /**
1009  * dvb_ca_en50221_thread_wakeup - Wake up the DVB CA thread
1010  *
1011  * @ca: CA instance.
1012  */
1013 static void dvb_ca_en50221_thread_wakeup(struct dvb_ca_private *ca)
1014 {
1015     dprintk("%s\n", __func__);
1016 
1017     ca->wakeup = 1;
1018     mb();
1019     wake_up_process(ca->thread);
1020 }
1021 
1022 /**
1023  * dvb_ca_en50221_thread_update_delay - Update the delay used by the thread.
1024  *
1025  * @ca: CA instance.
1026  */
1027 static void dvb_ca_en50221_thread_update_delay(struct dvb_ca_private *ca)
1028 {
1029     int delay;
1030     int curdelay = 100000000;
1031     int slot;
1032 
1033     /*
1034      * Beware of too high polling frequency, because one polling
1035      * call might take several hundred milliseconds until timeout!
1036      */
1037     for (slot = 0; slot < ca->slot_count; slot++) {
1038         struct dvb_ca_slot *sl = &ca->slot_info[slot];
1039 
1040         switch (sl->slot_state) {
1041         default:
1042         case DVB_CA_SLOTSTATE_NONE:
1043             delay = HZ * 60;  /* 60s */
1044             if (!(ca->flags & DVB_CA_EN50221_FLAG_IRQ_CAMCHANGE))
1045                 delay = HZ * 5;  /* 5s */
1046             break;
1047         case DVB_CA_SLOTSTATE_INVALID:
1048             delay = HZ * 60;  /* 60s */
1049             if (!(ca->flags & DVB_CA_EN50221_FLAG_IRQ_CAMCHANGE))
1050                 delay = HZ / 10;  /* 100ms */
1051             break;
1052 
1053         case DVB_CA_SLOTSTATE_UNINITIALISED:
1054         case DVB_CA_SLOTSTATE_WAITREADY:
1055         case DVB_CA_SLOTSTATE_VALIDATE:
1056         case DVB_CA_SLOTSTATE_WAITFR:
1057         case DVB_CA_SLOTSTATE_LINKINIT:
1058             delay = HZ / 10;  /* 100ms */
1059             break;
1060 
1061         case DVB_CA_SLOTSTATE_RUNNING:
1062             delay = HZ * 60;  /* 60s */
1063             if (!(ca->flags & DVB_CA_EN50221_FLAG_IRQ_CAMCHANGE))
1064                 delay = HZ / 10;  /* 100ms */
1065             if (ca->open) {
1066                 if ((!sl->da_irq_supported) ||
1067                     (!(ca->flags & DVB_CA_EN50221_FLAG_IRQ_DA)))
1068                     delay = HZ / 10;  /* 100ms */
1069             }
1070             break;
1071         }
1072 
1073         if (delay < curdelay)
1074             curdelay = delay;
1075     }
1076 
1077     ca->delay = curdelay;
1078 }
1079 
1080 /**
1081  * dvb_ca_en50221_poll_cam_gone - Poll if the CAM is gone.
1082  *
1083  * @ca: CA instance.
1084  * @slot: Slot to process.
1085  * return:: 0 .. no change
1086  *          1 .. CAM state changed
1087  */
1088 
1089 static int dvb_ca_en50221_poll_cam_gone(struct dvb_ca_private *ca, int slot)
1090 {
1091     int changed = 0;
1092     int status;
1093 
1094     /*
1095      * we need this extra check for annoying interfaces like the
1096      * budget-av
1097      */
1098     if ((!(ca->flags & DVB_CA_EN50221_FLAG_IRQ_CAMCHANGE)) &&
1099         (ca->pub->poll_slot_status)) {
1100         status = ca->pub->poll_slot_status(ca->pub, slot, 0);
1101         if (!(status &
1102             DVB_CA_EN50221_POLL_CAM_PRESENT)) {
1103             ca->slot_info[slot].slot_state = DVB_CA_SLOTSTATE_NONE;
1104             dvb_ca_en50221_thread_update_delay(ca);
1105             changed = 1;
1106         }
1107     }
1108     return changed;
1109 }
1110 
1111 /**
1112  * dvb_ca_en50221_thread_state_machine - Thread state machine for one CA slot
1113  *  to perform the data transfer.
1114  *
1115  * @ca: CA instance.
1116  * @slot: Slot to process.
1117  */
1118 static void dvb_ca_en50221_thread_state_machine(struct dvb_ca_private *ca,
1119                         int slot)
1120 {
1121     struct dvb_ca_slot *sl = &ca->slot_info[slot];
1122     int flags;
1123     int pktcount;
1124     void *rxbuf;
1125 
1126     mutex_lock(&sl->slot_lock);
1127 
1128     /* check the cam status + deal with CAMCHANGEs */
1129     while (dvb_ca_en50221_check_camstatus(ca, slot)) {
1130         /* clear down an old CI slot if necessary */
1131         if (sl->slot_state != DVB_CA_SLOTSTATE_NONE)
1132             dvb_ca_en50221_slot_shutdown(ca, slot);
1133 
1134         /* if a CAM is NOW present, initialise it */
1135         if (sl->camchange_type == DVB_CA_EN50221_CAMCHANGE_INSERTED)
1136             sl->slot_state = DVB_CA_SLOTSTATE_UNINITIALISED;
1137 
1138         /* we've handled one CAMCHANGE */
1139         dvb_ca_en50221_thread_update_delay(ca);
1140         atomic_dec(&sl->camchange_count);
1141     }
1142 
1143     /* CAM state machine */
1144     switch (sl->slot_state) {
1145     case DVB_CA_SLOTSTATE_NONE:
1146     case DVB_CA_SLOTSTATE_INVALID:
1147         /* no action needed */
1148         break;
1149 
1150     case DVB_CA_SLOTSTATE_UNINITIALISED:
1151         sl->slot_state = DVB_CA_SLOTSTATE_WAITREADY;
1152         ca->pub->slot_reset(ca->pub, slot);
1153         sl->timeout = jiffies + (INIT_TIMEOUT_SECS * HZ);
1154         break;
1155 
1156     case DVB_CA_SLOTSTATE_WAITREADY:
1157         if (time_after(jiffies, sl->timeout)) {
1158             pr_err("dvb_ca adaptor %d: PC card did not respond :(\n",
1159                    ca->dvbdev->adapter->num);
1160             sl->slot_state = DVB_CA_SLOTSTATE_INVALID;
1161             dvb_ca_en50221_thread_update_delay(ca);
1162             break;
1163         }
1164         /*
1165          * no other action needed; will automatically change state when
1166          * ready
1167          */
1168         break;
1169 
1170     case DVB_CA_SLOTSTATE_VALIDATE:
1171         if (dvb_ca_en50221_parse_attributes(ca, slot) != 0) {
1172             if (dvb_ca_en50221_poll_cam_gone(ca, slot))
1173                 break;
1174 
1175             pr_err("dvb_ca adapter %d: Invalid PC card inserted :(\n",
1176                    ca->dvbdev->adapter->num);
1177             sl->slot_state = DVB_CA_SLOTSTATE_INVALID;
1178             dvb_ca_en50221_thread_update_delay(ca);
1179             break;
1180         }
1181         if (dvb_ca_en50221_set_configoption(ca, slot) != 0) {
1182             pr_err("dvb_ca adapter %d: Unable to initialise CAM :(\n",
1183                    ca->dvbdev->adapter->num);
1184             sl->slot_state = DVB_CA_SLOTSTATE_INVALID;
1185             dvb_ca_en50221_thread_update_delay(ca);
1186             break;
1187         }
1188         if (ca->pub->write_cam_control(ca->pub, slot,
1189                            CTRLIF_COMMAND,
1190                            CMDREG_RS) != 0) {
1191             pr_err("dvb_ca adapter %d: Unable to reset CAM IF\n",
1192                    ca->dvbdev->adapter->num);
1193             sl->slot_state = DVB_CA_SLOTSTATE_INVALID;
1194             dvb_ca_en50221_thread_update_delay(ca);
1195             break;
1196         }
1197         dprintk("DVB CAM validated successfully\n");
1198 
1199         sl->timeout = jiffies + (INIT_TIMEOUT_SECS * HZ);
1200         sl->slot_state = DVB_CA_SLOTSTATE_WAITFR;
1201         ca->wakeup = 1;
1202         break;
1203 
1204     case DVB_CA_SLOTSTATE_WAITFR:
1205         if (time_after(jiffies, sl->timeout)) {
1206             pr_err("dvb_ca adapter %d: DVB CAM did not respond :(\n",
1207                    ca->dvbdev->adapter->num);
1208             sl->slot_state = DVB_CA_SLOTSTATE_INVALID;
1209             dvb_ca_en50221_thread_update_delay(ca);
1210             break;
1211         }
1212 
1213         flags = ca->pub->read_cam_control(ca->pub, slot, CTRLIF_STATUS);
1214         if (flags & STATUSREG_FR) {
1215             sl->slot_state = DVB_CA_SLOTSTATE_LINKINIT;
1216             ca->wakeup = 1;
1217         }
1218         break;
1219 
1220     case DVB_CA_SLOTSTATE_LINKINIT:
1221         if (dvb_ca_en50221_link_init(ca, slot) != 0) {
1222             if (dvb_ca_en50221_poll_cam_gone(ca, slot))
1223                 break;
1224 
1225             pr_err("dvb_ca adapter %d: DVB CAM link initialisation failed :(\n",
1226                    ca->dvbdev->adapter->num);
1227             sl->slot_state = DVB_CA_SLOTSTATE_UNINITIALISED;
1228             dvb_ca_en50221_thread_update_delay(ca);
1229             break;
1230         }
1231 
1232         if (!sl->rx_buffer.data) {
1233             rxbuf = vmalloc(RX_BUFFER_SIZE);
1234             if (!rxbuf) {
1235                 pr_err("dvb_ca adapter %d: Unable to allocate CAM rx buffer :(\n",
1236                        ca->dvbdev->adapter->num);
1237                 sl->slot_state = DVB_CA_SLOTSTATE_INVALID;
1238                 dvb_ca_en50221_thread_update_delay(ca);
1239                 break;
1240             }
1241             dvb_ringbuffer_init(&sl->rx_buffer, rxbuf,
1242                         RX_BUFFER_SIZE);
1243         }
1244 
1245         ca->pub->slot_ts_enable(ca->pub, slot);
1246         sl->slot_state = DVB_CA_SLOTSTATE_RUNNING;
1247         dvb_ca_en50221_thread_update_delay(ca);
1248         pr_info("dvb_ca adapter %d: DVB CAM detected and initialised successfully\n",
1249             ca->dvbdev->adapter->num);
1250         break;
1251 
1252     case DVB_CA_SLOTSTATE_RUNNING:
1253         if (!ca->open)
1254             break;
1255 
1256         /* poll slots for data */
1257         pktcount = 0;
1258         while (dvb_ca_en50221_read_data(ca, slot, NULL, 0) > 0) {
1259             if (!ca->open)
1260                 break;
1261 
1262             /*
1263              * if a CAMCHANGE occurred at some point, do not do any
1264              * more processing of this slot
1265              */
1266             if (dvb_ca_en50221_check_camstatus(ca, slot)) {
1267                 /*
1268                  * we don't want to sleep on the next iteration
1269                  * so we can handle the cam change
1270                  */
1271                 ca->wakeup = 1;
1272                 break;
1273             }
1274 
1275             /* check if we've hit our limit this time */
1276             if (++pktcount >= MAX_RX_PACKETS_PER_ITERATION) {
1277                 /*
1278                  * don't sleep; there is likely to be more data
1279                  * to read
1280                  */
1281                 ca->wakeup = 1;
1282                 break;
1283             }
1284         }
1285         break;
1286     }
1287 
1288     mutex_unlock(&sl->slot_lock);
1289 }
1290 
1291 /*
1292  * Kernel thread which monitors CA slots for CAM changes, and performs data
1293  * transfers.
1294  */
1295 static int dvb_ca_en50221_thread(void *data)
1296 {
1297     struct dvb_ca_private *ca = data;
1298     int slot;
1299 
1300     dprintk("%s\n", __func__);
1301 
1302     /* choose the correct initial delay */
1303     dvb_ca_en50221_thread_update_delay(ca);
1304 
1305     /* main loop */
1306     while (!kthread_should_stop()) {
1307         /* sleep for a bit */
1308         if (!ca->wakeup) {
1309             set_current_state(TASK_INTERRUPTIBLE);
1310             schedule_timeout(ca->delay);
1311             if (kthread_should_stop())
1312                 return 0;
1313         }
1314         ca->wakeup = 0;
1315 
1316         /* go through all the slots processing them */
1317         for (slot = 0; slot < ca->slot_count; slot++)
1318             dvb_ca_en50221_thread_state_machine(ca, slot);
1319     }
1320 
1321     return 0;
1322 }
1323 
1324 /* ************************************************************************** */
1325 /* EN50221 IO interface functions */
1326 
1327 /**
1328  * dvb_ca_en50221_io_do_ioctl - Real ioctl implementation.
1329  *
1330  * @file: File concerned.
1331  * @cmd: IOCTL command.
1332  * @parg: Associated argument.
1333  *
1334  * NOTE: CA_SEND_MSG/CA_GET_MSG ioctls have userspace buffers passed to them.
1335  *
1336  * return: 0 on success, <0 on error.
1337  */
1338 static int dvb_ca_en50221_io_do_ioctl(struct file *file,
1339                       unsigned int cmd, void *parg)
1340 {
1341     struct dvb_device *dvbdev = file->private_data;
1342     struct dvb_ca_private *ca = dvbdev->priv;
1343     int err = 0;
1344     int slot;
1345 
1346     dprintk("%s\n", __func__);
1347 
1348     if (mutex_lock_interruptible(&ca->ioctl_mutex))
1349         return -ERESTARTSYS;
1350 
1351     switch (cmd) {
1352     case CA_RESET:
1353         for (slot = 0; slot < ca->slot_count; slot++) {
1354             struct dvb_ca_slot *sl = &ca->slot_info[slot];
1355 
1356             mutex_lock(&sl->slot_lock);
1357             if (sl->slot_state != DVB_CA_SLOTSTATE_NONE) {
1358                 dvb_ca_en50221_slot_shutdown(ca, slot);
1359                 if (ca->flags & DVB_CA_EN50221_FLAG_IRQ_CAMCHANGE)
1360                     dvb_ca_en50221_camchange_irq(ca->pub,
1361                                      slot,
1362                                      DVB_CA_EN50221_CAMCHANGE_INSERTED);
1363             }
1364             mutex_unlock(&sl->slot_lock);
1365         }
1366         ca->next_read_slot = 0;
1367         dvb_ca_en50221_thread_wakeup(ca);
1368         break;
1369 
1370     case CA_GET_CAP: {
1371         struct ca_caps *caps = parg;
1372 
1373         caps->slot_num = ca->slot_count;
1374         caps->slot_type = CA_CI_LINK;
1375         caps->descr_num = 0;
1376         caps->descr_type = 0;
1377         break;
1378     }
1379 
1380     case CA_GET_SLOT_INFO: {
1381         struct ca_slot_info *info = parg;
1382         struct dvb_ca_slot *sl;
1383 
1384         slot = info->num;
1385         if ((slot >= ca->slot_count) || (slot < 0)) {
1386             err = -EINVAL;
1387             goto out_unlock;
1388         }
1389         slot = array_index_nospec(slot, ca->slot_count);
1390 
1391         info->type = CA_CI_LINK;
1392         info->flags = 0;
1393         sl = &ca->slot_info[slot];
1394         if ((sl->slot_state != DVB_CA_SLOTSTATE_NONE) &&
1395             (sl->slot_state != DVB_CA_SLOTSTATE_INVALID)) {
1396             info->flags = CA_CI_MODULE_PRESENT;
1397         }
1398         if (sl->slot_state == DVB_CA_SLOTSTATE_RUNNING)
1399             info->flags |= CA_CI_MODULE_READY;
1400         break;
1401     }
1402 
1403     default:
1404         err = -EINVAL;
1405         break;
1406     }
1407 
1408 out_unlock:
1409     mutex_unlock(&ca->ioctl_mutex);
1410     return err;
1411 }
1412 
1413 /**
1414  * dvb_ca_en50221_io_ioctl - Wrapper for ioctl implementation.
1415  *
1416  * @file: File concerned.
1417  * @cmd: IOCTL command.
1418  * @arg: Associated argument.
1419  *
1420  * return: 0 on success, <0 on error.
1421  */
1422 static long dvb_ca_en50221_io_ioctl(struct file *file,
1423                     unsigned int cmd, unsigned long arg)
1424 {
1425     return dvb_usercopy(file, cmd, arg, dvb_ca_en50221_io_do_ioctl);
1426 }
1427 
1428 /**
1429  * dvb_ca_en50221_io_write - Implementation of write() syscall.
1430  *
1431  * @file: File structure.
1432  * @buf: Source buffer.
1433  * @count: Size of source buffer.
1434  * @ppos: Position in file (ignored).
1435  *
1436  * return: Number of bytes read, or <0 on error.
1437  */
1438 static ssize_t dvb_ca_en50221_io_write(struct file *file,
1439                        const char __user *buf, size_t count,
1440                        loff_t *ppos)
1441 {
1442     struct dvb_device *dvbdev = file->private_data;
1443     struct dvb_ca_private *ca = dvbdev->priv;
1444     struct dvb_ca_slot *sl;
1445     u8 slot, connection_id;
1446     int status;
1447     u8 fragbuf[HOST_LINK_BUF_SIZE];
1448     int fragpos = 0;
1449     int fraglen;
1450     unsigned long timeout;
1451     int written;
1452 
1453     dprintk("%s\n", __func__);
1454 
1455     /*
1456      * Incoming packet has a 2 byte header.
1457      * hdr[0] = slot_id, hdr[1] = connection_id
1458      */
1459     if (count < 2)
1460         return -EINVAL;
1461 
1462     /* extract slot & connection id */
1463     if (copy_from_user(&slot, buf, 1))
1464         return -EFAULT;
1465     if (copy_from_user(&connection_id, buf + 1, 1))
1466         return -EFAULT;
1467     buf += 2;
1468     count -= 2;
1469 
1470     if (slot >= ca->slot_count)
1471         return -EINVAL;
1472     slot = array_index_nospec(slot, ca->slot_count);
1473     sl = &ca->slot_info[slot];
1474 
1475     /* check if the slot is actually running */
1476     if (sl->slot_state != DVB_CA_SLOTSTATE_RUNNING)
1477         return -EINVAL;
1478 
1479     /* fragment the packets & store in the buffer */
1480     while (fragpos < count) {
1481         fraglen = sl->link_buf_size - 2;
1482         if (fraglen < 0)
1483             break;
1484         if (fraglen > HOST_LINK_BUF_SIZE - 2)
1485             fraglen = HOST_LINK_BUF_SIZE - 2;
1486         if ((count - fragpos) < fraglen)
1487             fraglen = count - fragpos;
1488 
1489         fragbuf[0] = connection_id;
1490         fragbuf[1] = ((fragpos + fraglen) < count) ? 0x80 : 0x00;
1491         status = copy_from_user(fragbuf + 2, buf + fragpos, fraglen);
1492         if (status) {
1493             status = -EFAULT;
1494             goto exit;
1495         }
1496 
1497         timeout = jiffies + HZ / 2;
1498         written = 0;
1499         while (!time_after(jiffies, timeout)) {
1500             /*
1501              * check the CAM hasn't been removed/reset in the
1502              * meantime
1503              */
1504             if (sl->slot_state != DVB_CA_SLOTSTATE_RUNNING) {
1505                 status = -EIO;
1506                 goto exit;
1507             }
1508 
1509             mutex_lock(&sl->slot_lock);
1510             status = dvb_ca_en50221_write_data(ca, slot, fragbuf,
1511                                fraglen + 2);
1512             mutex_unlock(&sl->slot_lock);
1513             if (status == (fraglen + 2)) {
1514                 written = 1;
1515                 break;
1516             }
1517             if (status != -EAGAIN)
1518                 goto exit;
1519 
1520             usleep_range(1000, 1100);
1521         }
1522         if (!written) {
1523             status = -EIO;
1524             goto exit;
1525         }
1526 
1527         fragpos += fraglen;
1528     }
1529     status = count + 2;
1530 
1531 exit:
1532     return status;
1533 }
1534 
1535 /*
1536  * Condition for waking up in dvb_ca_en50221_io_read_condition
1537  */
1538 static int dvb_ca_en50221_io_read_condition(struct dvb_ca_private *ca,
1539                         int *result, int *_slot)
1540 {
1541     int slot;
1542     int slot_count = 0;
1543     int idx;
1544     size_t fraglen;
1545     int connection_id = -1;
1546     int found = 0;
1547     u8 hdr[2];
1548 
1549     slot = ca->next_read_slot;
1550     while ((slot_count < ca->slot_count) && (!found)) {
1551         struct dvb_ca_slot *sl = &ca->slot_info[slot];
1552 
1553         if (sl->slot_state != DVB_CA_SLOTSTATE_RUNNING)
1554             goto nextslot;
1555 
1556         if (!sl->rx_buffer.data)
1557             return 0;
1558 
1559         idx = dvb_ringbuffer_pkt_next(&sl->rx_buffer, -1, &fraglen);
1560         while (idx != -1) {
1561             dvb_ringbuffer_pkt_read(&sl->rx_buffer, idx, 0, hdr, 2);
1562             if (connection_id == -1)
1563                 connection_id = hdr[0];
1564             if ((hdr[0] == connection_id) &&
1565                 ((hdr[1] & 0x80) == 0)) {
1566                 *_slot = slot;
1567                 found = 1;
1568                 break;
1569             }
1570 
1571             idx = dvb_ringbuffer_pkt_next(&sl->rx_buffer, idx,
1572                               &fraglen);
1573         }
1574 
1575 nextslot:
1576         slot = (slot + 1) % ca->slot_count;
1577         slot_count++;
1578     }
1579 
1580     ca->next_read_slot = slot;
1581     return found;
1582 }
1583 
1584 /**
1585  * dvb_ca_en50221_io_read - Implementation of read() syscall.
1586  *
1587  * @file: File structure.
1588  * @buf: Destination buffer.
1589  * @count: Size of destination buffer.
1590  * @ppos: Position in file (ignored).
1591  *
1592  * return: Number of bytes read, or <0 on error.
1593  */
1594 static ssize_t dvb_ca_en50221_io_read(struct file *file, char __user *buf,
1595                       size_t count, loff_t *ppos)
1596 {
1597     struct dvb_device *dvbdev = file->private_data;
1598     struct dvb_ca_private *ca = dvbdev->priv;
1599     struct dvb_ca_slot *sl;
1600     int status;
1601     int result = 0;
1602     u8 hdr[2];
1603     int slot;
1604     int connection_id = -1;
1605     size_t idx, idx2;
1606     int last_fragment = 0;
1607     size_t fraglen;
1608     int pktlen;
1609     int dispose = 0;
1610 
1611     dprintk("%s\n", __func__);
1612 
1613     /*
1614      * Outgoing packet has a 2 byte header.
1615      * hdr[0] = slot_id, hdr[1] = connection_id
1616      */
1617     if (count < 2)
1618         return -EINVAL;
1619 
1620     /* wait for some data */
1621     status = dvb_ca_en50221_io_read_condition(ca, &result, &slot);
1622     if (status == 0) {
1623         /* if we're in nonblocking mode, exit immediately */
1624         if (file->f_flags & O_NONBLOCK)
1625             return -EWOULDBLOCK;
1626 
1627         /* wait for some data */
1628         status = wait_event_interruptible(ca->wait_queue,
1629                           dvb_ca_en50221_io_read_condition
1630                           (ca, &result, &slot));
1631     }
1632     if ((status < 0) || (result < 0)) {
1633         if (result)
1634             return result;
1635         return status;
1636     }
1637 
1638     sl = &ca->slot_info[slot];
1639     idx = dvb_ringbuffer_pkt_next(&sl->rx_buffer, -1, &fraglen);
1640     pktlen = 2;
1641     do {
1642         if (idx == -1) {
1643             pr_err("dvb_ca adapter %d: BUG: read packet ended before last_fragment encountered\n",
1644                    ca->dvbdev->adapter->num);
1645             status = -EIO;
1646             goto exit;
1647         }
1648 
1649         dvb_ringbuffer_pkt_read(&sl->rx_buffer, idx, 0, hdr, 2);
1650         if (connection_id == -1)
1651             connection_id = hdr[0];
1652         if (hdr[0] == connection_id) {
1653             if (pktlen < count) {
1654                 if ((pktlen + fraglen - 2) > count)
1655                     fraglen = count - pktlen;
1656                 else
1657                     fraglen -= 2;
1658 
1659                 status =
1660                    dvb_ringbuffer_pkt_read_user(&sl->rx_buffer,
1661                                 idx, 2,
1662                                 buf + pktlen,
1663                                 fraglen);
1664                 if (status < 0)
1665                     goto exit;
1666 
1667                 pktlen += fraglen;
1668             }
1669 
1670             if ((hdr[1] & 0x80) == 0)
1671                 last_fragment = 1;
1672             dispose = 1;
1673         }
1674 
1675         idx2 = dvb_ringbuffer_pkt_next(&sl->rx_buffer, idx, &fraglen);
1676         if (dispose)
1677             dvb_ringbuffer_pkt_dispose(&sl->rx_buffer, idx);
1678         idx = idx2;
1679         dispose = 0;
1680     } while (!last_fragment);
1681 
1682     hdr[0] = slot;
1683     hdr[1] = connection_id;
1684     status = copy_to_user(buf, hdr, 2);
1685     if (status) {
1686         status = -EFAULT;
1687         goto exit;
1688     }
1689     status = pktlen;
1690 
1691 exit:
1692     return status;
1693 }
1694 
1695 /**
1696  * dvb_ca_en50221_io_open - Implementation of file open syscall.
1697  *
1698  * @inode: Inode concerned.
1699  * @file: File concerned.
1700  *
1701  * return: 0 on success, <0 on failure.
1702  */
1703 static int dvb_ca_en50221_io_open(struct inode *inode, struct file *file)
1704 {
1705     struct dvb_device *dvbdev = file->private_data;
1706     struct dvb_ca_private *ca = dvbdev->priv;
1707     int err;
1708     int i;
1709 
1710     dprintk("%s\n", __func__);
1711 
1712     if (!try_module_get(ca->pub->owner))
1713         return -EIO;
1714 
1715     err = dvb_generic_open(inode, file);
1716     if (err < 0) {
1717         module_put(ca->pub->owner);
1718         return err;
1719     }
1720 
1721     for (i = 0; i < ca->slot_count; i++) {
1722         struct dvb_ca_slot *sl = &ca->slot_info[i];
1723 
1724         if (sl->slot_state == DVB_CA_SLOTSTATE_RUNNING) {
1725             if (!sl->rx_buffer.data) {
1726                 /*
1727                  * it is safe to call this here without locks
1728                  * because ca->open == 0. Data is not read in
1729                  * this case
1730                  */
1731                 dvb_ringbuffer_flush(&sl->rx_buffer);
1732             }
1733         }
1734     }
1735 
1736     ca->open = 1;
1737     dvb_ca_en50221_thread_update_delay(ca);
1738     dvb_ca_en50221_thread_wakeup(ca);
1739 
1740     dvb_ca_private_get(ca);
1741 
1742     return 0;
1743 }
1744 
1745 /**
1746  * dvb_ca_en50221_io_release - Implementation of file close syscall.
1747  *
1748  * @inode: Inode concerned.
1749  * @file: File concerned.
1750  *
1751  * return: 0 on success, <0 on failure.
1752  */
1753 static int dvb_ca_en50221_io_release(struct inode *inode, struct file *file)
1754 {
1755     struct dvb_device *dvbdev = file->private_data;
1756     struct dvb_ca_private *ca = dvbdev->priv;
1757     int err;
1758 
1759     dprintk("%s\n", __func__);
1760 
1761     /* mark the CA device as closed */
1762     ca->open = 0;
1763     dvb_ca_en50221_thread_update_delay(ca);
1764 
1765     err = dvb_generic_release(inode, file);
1766 
1767     module_put(ca->pub->owner);
1768 
1769     dvb_ca_private_put(ca);
1770 
1771     return err;
1772 }
1773 
1774 /**
1775  * dvb_ca_en50221_io_poll - Implementation of poll() syscall.
1776  *
1777  * @file: File concerned.
1778  * @wait: poll wait table.
1779  *
1780  * return: Standard poll mask.
1781  */
1782 static __poll_t dvb_ca_en50221_io_poll(struct file *file, poll_table *wait)
1783 {
1784     struct dvb_device *dvbdev = file->private_data;
1785     struct dvb_ca_private *ca = dvbdev->priv;
1786     __poll_t mask = 0;
1787     int slot;
1788     int result = 0;
1789 
1790     dprintk("%s\n", __func__);
1791 
1792     poll_wait(file, &ca->wait_queue, wait);
1793 
1794     if (dvb_ca_en50221_io_read_condition(ca, &result, &slot) == 1)
1795         mask |= EPOLLIN;
1796 
1797     /* if there is something, return now */
1798     if (mask)
1799         return mask;
1800 
1801     if (dvb_ca_en50221_io_read_condition(ca, &result, &slot) == 1)
1802         mask |= EPOLLIN;
1803 
1804     return mask;
1805 }
1806 
1807 static const struct file_operations dvb_ca_fops = {
1808     .owner = THIS_MODULE,
1809     .read = dvb_ca_en50221_io_read,
1810     .write = dvb_ca_en50221_io_write,
1811     .unlocked_ioctl = dvb_ca_en50221_io_ioctl,
1812     .open = dvb_ca_en50221_io_open,
1813     .release = dvb_ca_en50221_io_release,
1814     .poll = dvb_ca_en50221_io_poll,
1815     .llseek = noop_llseek,
1816 };
1817 
1818 static const struct dvb_device dvbdev_ca = {
1819     .priv = NULL,
1820     .users = 1,
1821     .readers = 1,
1822     .writers = 1,
1823 #if defined(CONFIG_MEDIA_CONTROLLER_DVB)
1824     .name = "dvb-ca-en50221",
1825 #endif
1826     .fops = &dvb_ca_fops,
1827 };
1828 
1829 /* ************************************************************************** */
1830 /* Initialisation/shutdown functions */
1831 
1832 /**
1833  * dvb_ca_en50221_init - Initialise a new DVB CA EN50221 interface device.
1834  *
1835  * @dvb_adapter: DVB adapter to attach the new CA device to.
1836  * @pubca: The dvb_ca instance.
1837  * @flags: Flags describing the CA device (DVB_CA_FLAG_*).
1838  * @slot_count: Number of slots supported.
1839  *
1840  * return: 0 on success, nonzero on failure
1841  */
1842 int dvb_ca_en50221_init(struct dvb_adapter *dvb_adapter,
1843             struct dvb_ca_en50221 *pubca, int flags, int slot_count)
1844 {
1845     int ret;
1846     struct dvb_ca_private *ca = NULL;
1847     int i;
1848 
1849     dprintk("%s\n", __func__);
1850 
1851     if (slot_count < 1)
1852         return -EINVAL;
1853 
1854     /* initialise the system data */
1855     ca = kzalloc(sizeof(*ca), GFP_KERNEL);
1856     if (!ca) {
1857         ret = -ENOMEM;
1858         goto exit;
1859     }
1860     kref_init(&ca->refcount);
1861     ca->pub = pubca;
1862     ca->flags = flags;
1863     ca->slot_count = slot_count;
1864     ca->slot_info = kcalloc(slot_count, sizeof(struct dvb_ca_slot),
1865                 GFP_KERNEL);
1866     if (!ca->slot_info) {
1867         ret = -ENOMEM;
1868         goto free_ca;
1869     }
1870     init_waitqueue_head(&ca->wait_queue);
1871     ca->open = 0;
1872     ca->wakeup = 0;
1873     ca->next_read_slot = 0;
1874     pubca->private = ca;
1875 
1876     /* register the DVB device */
1877     ret = dvb_register_device(dvb_adapter, &ca->dvbdev, &dvbdev_ca, ca,
1878                   DVB_DEVICE_CA, 0);
1879     if (ret)
1880         goto free_slot_info;
1881 
1882     /* now initialise each slot */
1883     for (i = 0; i < slot_count; i++) {
1884         struct dvb_ca_slot *sl = &ca->slot_info[i];
1885 
1886         memset(sl, 0, sizeof(struct dvb_ca_slot));
1887         sl->slot_state = DVB_CA_SLOTSTATE_NONE;
1888         atomic_set(&sl->camchange_count, 0);
1889         sl->camchange_type = DVB_CA_EN50221_CAMCHANGE_REMOVED;
1890         mutex_init(&sl->slot_lock);
1891     }
1892 
1893     mutex_init(&ca->ioctl_mutex);
1894 
1895     if (signal_pending(current)) {
1896         ret = -EINTR;
1897         goto unregister_device;
1898     }
1899     mb();
1900 
1901     /* create a kthread for monitoring this CA device */
1902     ca->thread = kthread_run(dvb_ca_en50221_thread, ca, "kdvb-ca-%i:%i",
1903                  ca->dvbdev->adapter->num, ca->dvbdev->id);
1904     if (IS_ERR(ca->thread)) {
1905         ret = PTR_ERR(ca->thread);
1906         pr_err("dvb_ca_init: failed to start kernel_thread (%d)\n",
1907                ret);
1908         goto unregister_device;
1909     }
1910     return 0;
1911 
1912 unregister_device:
1913     dvb_unregister_device(ca->dvbdev);
1914 free_slot_info:
1915     kfree(ca->slot_info);
1916 free_ca:
1917     kfree(ca);
1918 exit:
1919     pubca->private = NULL;
1920     return ret;
1921 }
1922 EXPORT_SYMBOL(dvb_ca_en50221_init);
1923 
1924 /**
1925  * dvb_ca_en50221_release - Release a DVB CA EN50221 interface device.
1926  *
1927  * @pubca: The associated dvb_ca instance.
1928  */
1929 void dvb_ca_en50221_release(struct dvb_ca_en50221 *pubca)
1930 {
1931     struct dvb_ca_private *ca = pubca->private;
1932     int i;
1933 
1934     dprintk("%s\n", __func__);
1935 
1936     /* shutdown the thread if there was one */
1937     kthread_stop(ca->thread);
1938 
1939     for (i = 0; i < ca->slot_count; i++)
1940         dvb_ca_en50221_slot_shutdown(ca, i);
1941 
1942     dvb_remove_device(ca->dvbdev);
1943     dvb_ca_private_put(ca);
1944     pubca->private = NULL;
1945 }
1946 EXPORT_SYMBOL(dvb_ca_en50221_release);