Back to home page

OSCL-LXR

 
 

    


0001 // SPDX-License-Identifier: GPL-2.0+
0002 /*
0003  *  Copyright IBM Corp. 2001, 2018
0004  *  Author(s): Robert Burroughs
0005  *         Eric Rossman (edrossma@us.ibm.com)
0006  *         Cornelia Huck <cornelia.huck@de.ibm.com>
0007  *
0008  *  Hotplug & misc device support: Jochen Roehrig (roehrig@de.ibm.com)
0009  *  Major cleanup & driver split: Martin Schwidefsky <schwidefsky@de.ibm.com>
0010  *                Ralph Wuerthner <rwuerthn@de.ibm.com>
0011  *  MSGTYPE restruct:         Holger Dengler <hd@linux.vnet.ibm.com>
0012  *  Multiple device nodes: Harald Freudenberger <freude@linux.ibm.com>
0013  */
0014 
0015 #include <linux/module.h>
0016 #include <linux/init.h>
0017 #include <linux/interrupt.h>
0018 #include <linux/miscdevice.h>
0019 #include <linux/fs.h>
0020 #include <linux/compat.h>
0021 #include <linux/slab.h>
0022 #include <linux/atomic.h>
0023 #include <linux/uaccess.h>
0024 #include <linux/hw_random.h>
0025 #include <linux/debugfs.h>
0026 #include <linux/cdev.h>
0027 #include <linux/ctype.h>
0028 #include <linux/capability.h>
0029 #include <asm/debug.h>
0030 
0031 #define CREATE_TRACE_POINTS
0032 #include <asm/trace/zcrypt.h>
0033 
0034 #include "zcrypt_api.h"
0035 #include "zcrypt_debug.h"
0036 
0037 #include "zcrypt_msgtype6.h"
0038 #include "zcrypt_msgtype50.h"
0039 #include "zcrypt_ccamisc.h"
0040 #include "zcrypt_ep11misc.h"
0041 
0042 /*
0043  * Module description.
0044  */
0045 MODULE_AUTHOR("IBM Corporation");
0046 MODULE_DESCRIPTION("Cryptographic Coprocessor interface, " \
0047            "Copyright IBM Corp. 2001, 2012");
0048 MODULE_LICENSE("GPL");
0049 
0050 /*
0051  * zcrypt tracepoint functions
0052  */
0053 EXPORT_TRACEPOINT_SYMBOL(s390_zcrypt_req);
0054 EXPORT_TRACEPOINT_SYMBOL(s390_zcrypt_rep);
0055 
0056 static int zcrypt_hwrng_seed = 1;
0057 module_param_named(hwrng_seed, zcrypt_hwrng_seed, int, 0440);
0058 MODULE_PARM_DESC(hwrng_seed, "Turn on/off hwrng auto seed, default is 1 (on).");
0059 
0060 DEFINE_SPINLOCK(zcrypt_list_lock);
0061 LIST_HEAD(zcrypt_card_list);
0062 
0063 static atomic_t zcrypt_open_count = ATOMIC_INIT(0);
0064 static atomic_t zcrypt_rescan_count = ATOMIC_INIT(0);
0065 
0066 atomic_t zcrypt_rescan_req = ATOMIC_INIT(0);
0067 EXPORT_SYMBOL(zcrypt_rescan_req);
0068 
0069 static LIST_HEAD(zcrypt_ops_list);
0070 
0071 /* Zcrypt related debug feature stuff. */
0072 debug_info_t *zcrypt_dbf_info;
0073 
0074 /*
0075  * Process a rescan of the transport layer.
0076  *
0077  * Returns 1, if the rescan has been processed, otherwise 0.
0078  */
0079 static inline int zcrypt_process_rescan(void)
0080 {
0081     if (atomic_read(&zcrypt_rescan_req)) {
0082         atomic_set(&zcrypt_rescan_req, 0);
0083         atomic_inc(&zcrypt_rescan_count);
0084         ap_bus_force_rescan();
0085         ZCRYPT_DBF_INFO("%s rescan count=%07d\n", __func__,
0086                 atomic_inc_return(&zcrypt_rescan_count));
0087         return 1;
0088     }
0089     return 0;
0090 }
0091 
0092 void zcrypt_msgtype_register(struct zcrypt_ops *zops)
0093 {
0094     list_add_tail(&zops->list, &zcrypt_ops_list);
0095 }
0096 
0097 void zcrypt_msgtype_unregister(struct zcrypt_ops *zops)
0098 {
0099     list_del_init(&zops->list);
0100 }
0101 
0102 struct zcrypt_ops *zcrypt_msgtype(unsigned char *name, int variant)
0103 {
0104     struct zcrypt_ops *zops;
0105 
0106     list_for_each_entry(zops, &zcrypt_ops_list, list)
0107         if (zops->variant == variant &&
0108             (!strncmp(zops->name, name, sizeof(zops->name))))
0109             return zops;
0110     return NULL;
0111 }
0112 EXPORT_SYMBOL(zcrypt_msgtype);
0113 
0114 /*
0115  * Multi device nodes extension functions.
0116  */
0117 
0118 #ifdef CONFIG_ZCRYPT_MULTIDEVNODES
0119 
0120 struct zcdn_device;
0121 
0122 static struct class *zcrypt_class;
0123 static dev_t zcrypt_devt;
0124 static struct cdev zcrypt_cdev;
0125 
0126 struct zcdn_device {
0127     struct device device;
0128     struct ap_perms perms;
0129 };
0130 
0131 #define to_zcdn_dev(x) container_of((x), struct zcdn_device, device)
0132 
0133 #define ZCDN_MAX_NAME 32
0134 
0135 static int zcdn_create(const char *name);
0136 static int zcdn_destroy(const char *name);
0137 
0138 /*
0139  * Find zcdn device by name.
0140  * Returns reference to the zcdn device which needs to be released
0141  * with put_device() after use.
0142  */
0143 static inline struct zcdn_device *find_zcdndev_by_name(const char *name)
0144 {
0145     struct device *dev = class_find_device_by_name(zcrypt_class, name);
0146 
0147     return dev ? to_zcdn_dev(dev) : NULL;
0148 }
0149 
0150 /*
0151  * Find zcdn device by devt value.
0152  * Returns reference to the zcdn device which needs to be released
0153  * with put_device() after use.
0154  */
0155 static inline struct zcdn_device *find_zcdndev_by_devt(dev_t devt)
0156 {
0157     struct device *dev = class_find_device_by_devt(zcrypt_class, devt);
0158 
0159     return dev ? to_zcdn_dev(dev) : NULL;
0160 }
0161 
0162 static ssize_t ioctlmask_show(struct device *dev,
0163                   struct device_attribute *attr,
0164                   char *buf)
0165 {
0166     int i, rc;
0167     struct zcdn_device *zcdndev = to_zcdn_dev(dev);
0168 
0169     if (mutex_lock_interruptible(&ap_perms_mutex))
0170         return -ERESTARTSYS;
0171 
0172     buf[0] = '0';
0173     buf[1] = 'x';
0174     for (i = 0; i < sizeof(zcdndev->perms.ioctlm) / sizeof(long); i++)
0175         snprintf(buf + 2 + 2 * i * sizeof(long),
0176              PAGE_SIZE - 2 - 2 * i * sizeof(long),
0177              "%016lx", zcdndev->perms.ioctlm[i]);
0178     buf[2 + 2 * i * sizeof(long)] = '\n';
0179     buf[2 + 2 * i * sizeof(long) + 1] = '\0';
0180     rc = 2 + 2 * i * sizeof(long) + 1;
0181 
0182     mutex_unlock(&ap_perms_mutex);
0183 
0184     return rc;
0185 }
0186 
0187 static ssize_t ioctlmask_store(struct device *dev,
0188                    struct device_attribute *attr,
0189                    const char *buf, size_t count)
0190 {
0191     int rc;
0192     struct zcdn_device *zcdndev = to_zcdn_dev(dev);
0193 
0194     rc = ap_parse_mask_str(buf, zcdndev->perms.ioctlm,
0195                    AP_IOCTLS, &ap_perms_mutex);
0196     if (rc)
0197         return rc;
0198 
0199     return count;
0200 }
0201 
0202 static DEVICE_ATTR_RW(ioctlmask);
0203 
0204 static ssize_t apmask_show(struct device *dev,
0205                struct device_attribute *attr,
0206                char *buf)
0207 {
0208     int i, rc;
0209     struct zcdn_device *zcdndev = to_zcdn_dev(dev);
0210 
0211     if (mutex_lock_interruptible(&ap_perms_mutex))
0212         return -ERESTARTSYS;
0213 
0214     buf[0] = '0';
0215     buf[1] = 'x';
0216     for (i = 0; i < sizeof(zcdndev->perms.apm) / sizeof(long); i++)
0217         snprintf(buf + 2 + 2 * i * sizeof(long),
0218              PAGE_SIZE - 2 - 2 * i * sizeof(long),
0219              "%016lx", zcdndev->perms.apm[i]);
0220     buf[2 + 2 * i * sizeof(long)] = '\n';
0221     buf[2 + 2 * i * sizeof(long) + 1] = '\0';
0222     rc = 2 + 2 * i * sizeof(long) + 1;
0223 
0224     mutex_unlock(&ap_perms_mutex);
0225 
0226     return rc;
0227 }
0228 
0229 static ssize_t apmask_store(struct device *dev,
0230                 struct device_attribute *attr,
0231                 const char *buf, size_t count)
0232 {
0233     int rc;
0234     struct zcdn_device *zcdndev = to_zcdn_dev(dev);
0235 
0236     rc = ap_parse_mask_str(buf, zcdndev->perms.apm,
0237                    AP_DEVICES, &ap_perms_mutex);
0238     if (rc)
0239         return rc;
0240 
0241     return count;
0242 }
0243 
0244 static DEVICE_ATTR_RW(apmask);
0245 
0246 static ssize_t aqmask_show(struct device *dev,
0247                struct device_attribute *attr,
0248                char *buf)
0249 {
0250     int i, rc;
0251     struct zcdn_device *zcdndev = to_zcdn_dev(dev);
0252 
0253     if (mutex_lock_interruptible(&ap_perms_mutex))
0254         return -ERESTARTSYS;
0255 
0256     buf[0] = '0';
0257     buf[1] = 'x';
0258     for (i = 0; i < sizeof(zcdndev->perms.aqm) / sizeof(long); i++)
0259         snprintf(buf + 2 + 2 * i * sizeof(long),
0260              PAGE_SIZE - 2 - 2 * i * sizeof(long),
0261              "%016lx", zcdndev->perms.aqm[i]);
0262     buf[2 + 2 * i * sizeof(long)] = '\n';
0263     buf[2 + 2 * i * sizeof(long) + 1] = '\0';
0264     rc = 2 + 2 * i * sizeof(long) + 1;
0265 
0266     mutex_unlock(&ap_perms_mutex);
0267 
0268     return rc;
0269 }
0270 
0271 static ssize_t aqmask_store(struct device *dev,
0272                 struct device_attribute *attr,
0273                 const char *buf, size_t count)
0274 {
0275     int rc;
0276     struct zcdn_device *zcdndev = to_zcdn_dev(dev);
0277 
0278     rc = ap_parse_mask_str(buf, zcdndev->perms.aqm,
0279                    AP_DOMAINS, &ap_perms_mutex);
0280     if (rc)
0281         return rc;
0282 
0283     return count;
0284 }
0285 
0286 static DEVICE_ATTR_RW(aqmask);
0287 
0288 static ssize_t admask_show(struct device *dev,
0289                struct device_attribute *attr,
0290                char *buf)
0291 {
0292     int i, rc;
0293     struct zcdn_device *zcdndev = to_zcdn_dev(dev);
0294 
0295     if (mutex_lock_interruptible(&ap_perms_mutex))
0296         return -ERESTARTSYS;
0297 
0298     buf[0] = '0';
0299     buf[1] = 'x';
0300     for (i = 0; i < sizeof(zcdndev->perms.adm) / sizeof(long); i++)
0301         snprintf(buf + 2 + 2 * i * sizeof(long),
0302              PAGE_SIZE - 2 - 2 * i * sizeof(long),
0303              "%016lx", zcdndev->perms.adm[i]);
0304     buf[2 + 2 * i * sizeof(long)] = '\n';
0305     buf[2 + 2 * i * sizeof(long) + 1] = '\0';
0306     rc = 2 + 2 * i * sizeof(long) + 1;
0307 
0308     mutex_unlock(&ap_perms_mutex);
0309 
0310     return rc;
0311 }
0312 
0313 static ssize_t admask_store(struct device *dev,
0314                 struct device_attribute *attr,
0315                 const char *buf, size_t count)
0316 {
0317     int rc;
0318     struct zcdn_device *zcdndev = to_zcdn_dev(dev);
0319 
0320     rc = ap_parse_mask_str(buf, zcdndev->perms.adm,
0321                    AP_DOMAINS, &ap_perms_mutex);
0322     if (rc)
0323         return rc;
0324 
0325     return count;
0326 }
0327 
0328 static DEVICE_ATTR_RW(admask);
0329 
0330 static struct attribute *zcdn_dev_attrs[] = {
0331     &dev_attr_ioctlmask.attr,
0332     &dev_attr_apmask.attr,
0333     &dev_attr_aqmask.attr,
0334     &dev_attr_admask.attr,
0335     NULL
0336 };
0337 
0338 static struct attribute_group zcdn_dev_attr_group = {
0339     .attrs = zcdn_dev_attrs
0340 };
0341 
0342 static const struct attribute_group *zcdn_dev_attr_groups[] = {
0343     &zcdn_dev_attr_group,
0344     NULL
0345 };
0346 
0347 static ssize_t zcdn_create_store(struct class *class,
0348                  struct class_attribute *attr,
0349                  const char *buf, size_t count)
0350 {
0351     int rc;
0352     char name[ZCDN_MAX_NAME];
0353 
0354     strncpy(name, skip_spaces(buf), sizeof(name));
0355     name[sizeof(name) - 1] = '\0';
0356 
0357     rc = zcdn_create(strim(name));
0358 
0359     return rc ? rc : count;
0360 }
0361 
0362 static const struct class_attribute class_attr_zcdn_create =
0363     __ATTR(create, 0600, NULL, zcdn_create_store);
0364 
0365 static ssize_t zcdn_destroy_store(struct class *class,
0366                   struct class_attribute *attr,
0367                   const char *buf, size_t count)
0368 {
0369     int rc;
0370     char name[ZCDN_MAX_NAME];
0371 
0372     strncpy(name, skip_spaces(buf), sizeof(name));
0373     name[sizeof(name) - 1] = '\0';
0374 
0375     rc = zcdn_destroy(strim(name));
0376 
0377     return rc ? rc : count;
0378 }
0379 
0380 static const struct class_attribute class_attr_zcdn_destroy =
0381     __ATTR(destroy, 0600, NULL, zcdn_destroy_store);
0382 
0383 static void zcdn_device_release(struct device *dev)
0384 {
0385     struct zcdn_device *zcdndev = to_zcdn_dev(dev);
0386 
0387     ZCRYPT_DBF_INFO("%s releasing zcdn device %d:%d\n",
0388             __func__, MAJOR(dev->devt), MINOR(dev->devt));
0389 
0390     kfree(zcdndev);
0391 }
0392 
0393 static int zcdn_create(const char *name)
0394 {
0395     dev_t devt;
0396     int i, rc = 0;
0397     char nodename[ZCDN_MAX_NAME];
0398     struct zcdn_device *zcdndev;
0399 
0400     if (mutex_lock_interruptible(&ap_perms_mutex))
0401         return -ERESTARTSYS;
0402 
0403     /* check if device node with this name already exists */
0404     if (name[0]) {
0405         zcdndev = find_zcdndev_by_name(name);
0406         if (zcdndev) {
0407             put_device(&zcdndev->device);
0408             rc = -EEXIST;
0409             goto unlockout;
0410         }
0411     }
0412 
0413     /* find an unused minor number */
0414     for (i = 0; i < ZCRYPT_MAX_MINOR_NODES; i++) {
0415         devt = MKDEV(MAJOR(zcrypt_devt), MINOR(zcrypt_devt) + i);
0416         zcdndev = find_zcdndev_by_devt(devt);
0417         if (zcdndev)
0418             put_device(&zcdndev->device);
0419         else
0420             break;
0421     }
0422     if (i == ZCRYPT_MAX_MINOR_NODES) {
0423         rc = -ENOSPC;
0424         goto unlockout;
0425     }
0426 
0427     /* alloc and prepare a new zcdn device */
0428     zcdndev = kzalloc(sizeof(*zcdndev), GFP_KERNEL);
0429     if (!zcdndev) {
0430         rc = -ENOMEM;
0431         goto unlockout;
0432     }
0433     zcdndev->device.release = zcdn_device_release;
0434     zcdndev->device.class = zcrypt_class;
0435     zcdndev->device.devt = devt;
0436     zcdndev->device.groups = zcdn_dev_attr_groups;
0437     if (name[0])
0438         strncpy(nodename, name, sizeof(nodename));
0439     else
0440         snprintf(nodename, sizeof(nodename),
0441              ZCRYPT_NAME "_%d", (int)MINOR(devt));
0442     nodename[sizeof(nodename) - 1] = '\0';
0443     if (dev_set_name(&zcdndev->device, nodename)) {
0444         rc = -EINVAL;
0445         goto unlockout;
0446     }
0447     rc = device_register(&zcdndev->device);
0448     if (rc) {
0449         put_device(&zcdndev->device);
0450         goto unlockout;
0451     }
0452 
0453     ZCRYPT_DBF_INFO("%s created zcdn device %d:%d\n",
0454             __func__, MAJOR(devt), MINOR(devt));
0455 
0456 unlockout:
0457     mutex_unlock(&ap_perms_mutex);
0458     return rc;
0459 }
0460 
0461 static int zcdn_destroy(const char *name)
0462 {
0463     int rc = 0;
0464     struct zcdn_device *zcdndev;
0465 
0466     if (mutex_lock_interruptible(&ap_perms_mutex))
0467         return -ERESTARTSYS;
0468 
0469     /* try to find this zcdn device */
0470     zcdndev = find_zcdndev_by_name(name);
0471     if (!zcdndev) {
0472         rc = -ENOENT;
0473         goto unlockout;
0474     }
0475 
0476     /*
0477      * The zcdn device is not hard destroyed. It is subject to
0478      * reference counting and thus just needs to be unregistered.
0479      */
0480     put_device(&zcdndev->device);
0481     device_unregister(&zcdndev->device);
0482 
0483 unlockout:
0484     mutex_unlock(&ap_perms_mutex);
0485     return rc;
0486 }
0487 
0488 static void zcdn_destroy_all(void)
0489 {
0490     int i;
0491     dev_t devt;
0492     struct zcdn_device *zcdndev;
0493 
0494     mutex_lock(&ap_perms_mutex);
0495     for (i = 0; i < ZCRYPT_MAX_MINOR_NODES; i++) {
0496         devt = MKDEV(MAJOR(zcrypt_devt), MINOR(zcrypt_devt) + i);
0497         zcdndev = find_zcdndev_by_devt(devt);
0498         if (zcdndev) {
0499             put_device(&zcdndev->device);
0500             device_unregister(&zcdndev->device);
0501         }
0502     }
0503     mutex_unlock(&ap_perms_mutex);
0504 }
0505 
0506 #endif
0507 
0508 /*
0509  * zcrypt_read (): Not supported beyond zcrypt 1.3.1.
0510  *
0511  * This function is not supported beyond zcrypt 1.3.1.
0512  */
0513 static ssize_t zcrypt_read(struct file *filp, char __user *buf,
0514                size_t count, loff_t *f_pos)
0515 {
0516     return -EPERM;
0517 }
0518 
0519 /*
0520  * zcrypt_write(): Not allowed.
0521  *
0522  * Write is not allowed
0523  */
0524 static ssize_t zcrypt_write(struct file *filp, const char __user *buf,
0525                 size_t count, loff_t *f_pos)
0526 {
0527     return -EPERM;
0528 }
0529 
0530 /*
0531  * zcrypt_open(): Count number of users.
0532  *
0533  * Device open function to count number of users.
0534  */
0535 static int zcrypt_open(struct inode *inode, struct file *filp)
0536 {
0537     struct ap_perms *perms = &ap_perms;
0538 
0539 #ifdef CONFIG_ZCRYPT_MULTIDEVNODES
0540     if (filp->f_inode->i_cdev == &zcrypt_cdev) {
0541         struct zcdn_device *zcdndev;
0542 
0543         if (mutex_lock_interruptible(&ap_perms_mutex))
0544             return -ERESTARTSYS;
0545         zcdndev = find_zcdndev_by_devt(filp->f_inode->i_rdev);
0546         /* find returns a reference, no get_device() needed */
0547         mutex_unlock(&ap_perms_mutex);
0548         if (zcdndev)
0549             perms = &zcdndev->perms;
0550     }
0551 #endif
0552     filp->private_data = (void *)perms;
0553 
0554     atomic_inc(&zcrypt_open_count);
0555     return stream_open(inode, filp);
0556 }
0557 
0558 /*
0559  * zcrypt_release(): Count number of users.
0560  *
0561  * Device close function to count number of users.
0562  */
0563 static int zcrypt_release(struct inode *inode, struct file *filp)
0564 {
0565 #ifdef CONFIG_ZCRYPT_MULTIDEVNODES
0566     if (filp->f_inode->i_cdev == &zcrypt_cdev) {
0567         struct zcdn_device *zcdndev;
0568 
0569         mutex_lock(&ap_perms_mutex);
0570         zcdndev = find_zcdndev_by_devt(filp->f_inode->i_rdev);
0571         mutex_unlock(&ap_perms_mutex);
0572         if (zcdndev) {
0573             /* 2 puts here: one for find, one for open */
0574             put_device(&zcdndev->device);
0575             put_device(&zcdndev->device);
0576         }
0577     }
0578 #endif
0579 
0580     atomic_dec(&zcrypt_open_count);
0581     return 0;
0582 }
0583 
0584 static inline int zcrypt_check_ioctl(struct ap_perms *perms,
0585                      unsigned int cmd)
0586 {
0587     int rc = -EPERM;
0588     int ioctlnr = (cmd & _IOC_NRMASK) >> _IOC_NRSHIFT;
0589 
0590     if (ioctlnr > 0 && ioctlnr < AP_IOCTLS) {
0591         if (test_bit_inv(ioctlnr, perms->ioctlm))
0592             rc = 0;
0593     }
0594 
0595     if (rc)
0596         ZCRYPT_DBF_WARN("%s ioctl check failed: ioctlnr=0x%04x rc=%d\n",
0597                 __func__, ioctlnr, rc);
0598 
0599     return rc;
0600 }
0601 
0602 static inline bool zcrypt_check_card(struct ap_perms *perms, int card)
0603 {
0604     return test_bit_inv(card, perms->apm) ? true : false;
0605 }
0606 
0607 static inline bool zcrypt_check_queue(struct ap_perms *perms, int queue)
0608 {
0609     return test_bit_inv(queue, perms->aqm) ? true : false;
0610 }
0611 
0612 static inline struct zcrypt_queue *zcrypt_pick_queue(struct zcrypt_card *zc,
0613                              struct zcrypt_queue *zq,
0614                              struct module **pmod,
0615                              unsigned int weight)
0616 {
0617     if (!zq || !try_module_get(zq->queue->ap_dev.device.driver->owner))
0618         return NULL;
0619     zcrypt_queue_get(zq);
0620     get_device(&zq->queue->ap_dev.device);
0621     atomic_add(weight, &zc->load);
0622     atomic_add(weight, &zq->load);
0623     zq->request_count++;
0624     *pmod = zq->queue->ap_dev.device.driver->owner;
0625     return zq;
0626 }
0627 
0628 static inline void zcrypt_drop_queue(struct zcrypt_card *zc,
0629                      struct zcrypt_queue *zq,
0630                      struct module *mod,
0631                      unsigned int weight)
0632 {
0633     zq->request_count--;
0634     atomic_sub(weight, &zc->load);
0635     atomic_sub(weight, &zq->load);
0636     put_device(&zq->queue->ap_dev.device);
0637     zcrypt_queue_put(zq);
0638     module_put(mod);
0639 }
0640 
0641 static inline bool zcrypt_card_compare(struct zcrypt_card *zc,
0642                        struct zcrypt_card *pref_zc,
0643                        unsigned int weight,
0644                        unsigned int pref_weight)
0645 {
0646     if (!pref_zc)
0647         return true;
0648     weight += atomic_read(&zc->load);
0649     pref_weight += atomic_read(&pref_zc->load);
0650     if (weight == pref_weight)
0651         return atomic64_read(&zc->card->total_request_count) <
0652             atomic64_read(&pref_zc->card->total_request_count);
0653     return weight < pref_weight;
0654 }
0655 
0656 static inline bool zcrypt_queue_compare(struct zcrypt_queue *zq,
0657                     struct zcrypt_queue *pref_zq,
0658                     unsigned int weight,
0659                     unsigned int pref_weight)
0660 {
0661     if (!pref_zq)
0662         return true;
0663     weight += atomic_read(&zq->load);
0664     pref_weight += atomic_read(&pref_zq->load);
0665     if (weight == pref_weight)
0666         return zq->queue->total_request_count <
0667             pref_zq->queue->total_request_count;
0668     return weight < pref_weight;
0669 }
0670 
0671 /*
0672  * zcrypt ioctls.
0673  */
0674 static long zcrypt_rsa_modexpo(struct ap_perms *perms,
0675                    struct zcrypt_track *tr,
0676                    struct ica_rsa_modexpo *mex)
0677 {
0678     struct zcrypt_card *zc, *pref_zc;
0679     struct zcrypt_queue *zq, *pref_zq;
0680     struct ap_message ap_msg;
0681     unsigned int wgt = 0, pref_wgt = 0;
0682     unsigned int func_code;
0683     int cpen, qpen, qid = 0, rc = -ENODEV;
0684     struct module *mod;
0685 
0686     trace_s390_zcrypt_req(mex, TP_ICARSAMODEXPO);
0687 
0688     ap_init_message(&ap_msg);
0689 
0690 #ifdef CONFIG_ZCRYPT_DEBUG
0691     if (tr && tr->fi.cmd)
0692         ap_msg.fi.cmd = tr->fi.cmd;
0693 #endif
0694 
0695     if (mex->outputdatalength < mex->inputdatalength) {
0696         func_code = 0;
0697         rc = -EINVAL;
0698         goto out;
0699     }
0700 
0701     /*
0702      * As long as outputdatalength is big enough, we can set the
0703      * outputdatalength equal to the inputdatalength, since that is the
0704      * number of bytes we will copy in any case
0705      */
0706     mex->outputdatalength = mex->inputdatalength;
0707 
0708     rc = get_rsa_modex_fc(mex, &func_code);
0709     if (rc)
0710         goto out;
0711 
0712     pref_zc = NULL;
0713     pref_zq = NULL;
0714     spin_lock(&zcrypt_list_lock);
0715     for_each_zcrypt_card(zc) {
0716         /* Check for usable accelarator or CCA card */
0717         if (!zc->online || !zc->card->config || zc->card->chkstop ||
0718             !(zc->card->functions & 0x18000000))
0719             continue;
0720         /* Check for size limits */
0721         if (zc->min_mod_size > mex->inputdatalength ||
0722             zc->max_mod_size < mex->inputdatalength)
0723             continue;
0724         /* check if device node has admission for this card */
0725         if (!zcrypt_check_card(perms, zc->card->id))
0726             continue;
0727         /* get weight index of the card device  */
0728         wgt = zc->speed_rating[func_code];
0729         /* penalty if this msg was previously sent via this card */
0730         cpen = (tr && tr->again_counter && tr->last_qid &&
0731             AP_QID_CARD(tr->last_qid) == zc->card->id) ?
0732             TRACK_AGAIN_CARD_WEIGHT_PENALTY : 0;
0733         if (!zcrypt_card_compare(zc, pref_zc, wgt + cpen, pref_wgt))
0734             continue;
0735         for_each_zcrypt_queue(zq, zc) {
0736             /* check if device is usable and eligible */
0737             if (!zq->online || !zq->ops->rsa_modexpo ||
0738                 !zq->queue->config || zq->queue->chkstop)
0739                 continue;
0740             /* check if device node has admission for this queue */
0741             if (!zcrypt_check_queue(perms,
0742                         AP_QID_QUEUE(zq->queue->qid)))
0743                 continue;
0744             /* penalty if the msg was previously sent at this qid */
0745             qpen = (tr && tr->again_counter && tr->last_qid &&
0746                 tr->last_qid == zq->queue->qid) ?
0747                 TRACK_AGAIN_QUEUE_WEIGHT_PENALTY : 0;
0748             if (!zcrypt_queue_compare(zq, pref_zq,
0749                           wgt + cpen + qpen, pref_wgt))
0750                 continue;
0751             pref_zc = zc;
0752             pref_zq = zq;
0753             pref_wgt = wgt + cpen + qpen;
0754         }
0755     }
0756     pref_zq = zcrypt_pick_queue(pref_zc, pref_zq, &mod, wgt);
0757     spin_unlock(&zcrypt_list_lock);
0758 
0759     if (!pref_zq) {
0760         ZCRYPT_DBF_DBG("%s no matching queue found => ENODEV\n",
0761                    __func__);
0762         rc = -ENODEV;
0763         goto out;
0764     }
0765 
0766     qid = pref_zq->queue->qid;
0767     rc = pref_zq->ops->rsa_modexpo(pref_zq, mex, &ap_msg);
0768 
0769     spin_lock(&zcrypt_list_lock);
0770     zcrypt_drop_queue(pref_zc, pref_zq, mod, wgt);
0771     spin_unlock(&zcrypt_list_lock);
0772 
0773 out:
0774     ap_release_message(&ap_msg);
0775     if (tr) {
0776         tr->last_rc = rc;
0777         tr->last_qid = qid;
0778     }
0779     trace_s390_zcrypt_rep(mex, func_code, rc,
0780                   AP_QID_CARD(qid), AP_QID_QUEUE(qid));
0781     return rc;
0782 }
0783 
0784 static long zcrypt_rsa_crt(struct ap_perms *perms,
0785                struct zcrypt_track *tr,
0786                struct ica_rsa_modexpo_crt *crt)
0787 {
0788     struct zcrypt_card *zc, *pref_zc;
0789     struct zcrypt_queue *zq, *pref_zq;
0790     struct ap_message ap_msg;
0791     unsigned int wgt = 0, pref_wgt = 0;
0792     unsigned int func_code;
0793     int cpen, qpen, qid = 0, rc = -ENODEV;
0794     struct module *mod;
0795 
0796     trace_s390_zcrypt_req(crt, TP_ICARSACRT);
0797 
0798     ap_init_message(&ap_msg);
0799 
0800 #ifdef CONFIG_ZCRYPT_DEBUG
0801     if (tr && tr->fi.cmd)
0802         ap_msg.fi.cmd = tr->fi.cmd;
0803 #endif
0804 
0805     if (crt->outputdatalength < crt->inputdatalength) {
0806         func_code = 0;
0807         rc = -EINVAL;
0808         goto out;
0809     }
0810 
0811     /*
0812      * As long as outputdatalength is big enough, we can set the
0813      * outputdatalength equal to the inputdatalength, since that is the
0814      * number of bytes we will copy in any case
0815      */
0816     crt->outputdatalength = crt->inputdatalength;
0817 
0818     rc = get_rsa_crt_fc(crt, &func_code);
0819     if (rc)
0820         goto out;
0821 
0822     pref_zc = NULL;
0823     pref_zq = NULL;
0824     spin_lock(&zcrypt_list_lock);
0825     for_each_zcrypt_card(zc) {
0826         /* Check for usable accelarator or CCA card */
0827         if (!zc->online || !zc->card->config || zc->card->chkstop ||
0828             !(zc->card->functions & 0x18000000))
0829             continue;
0830         /* Check for size limits */
0831         if (zc->min_mod_size > crt->inputdatalength ||
0832             zc->max_mod_size < crt->inputdatalength)
0833             continue;
0834         /* check if device node has admission for this card */
0835         if (!zcrypt_check_card(perms, zc->card->id))
0836             continue;
0837         /* get weight index of the card device  */
0838         wgt = zc->speed_rating[func_code];
0839         /* penalty if this msg was previously sent via this card */
0840         cpen = (tr && tr->again_counter && tr->last_qid &&
0841             AP_QID_CARD(tr->last_qid) == zc->card->id) ?
0842             TRACK_AGAIN_CARD_WEIGHT_PENALTY : 0;
0843         if (!zcrypt_card_compare(zc, pref_zc, wgt + cpen, pref_wgt))
0844             continue;
0845         for_each_zcrypt_queue(zq, zc) {
0846             /* check if device is usable and eligible */
0847             if (!zq->online || !zq->ops->rsa_modexpo_crt ||
0848                 !zq->queue->config || zq->queue->chkstop)
0849                 continue;
0850             /* check if device node has admission for this queue */
0851             if (!zcrypt_check_queue(perms,
0852                         AP_QID_QUEUE(zq->queue->qid)))
0853                 continue;
0854             /* penalty if the msg was previously sent at this qid */
0855             qpen = (tr && tr->again_counter && tr->last_qid &&
0856                 tr->last_qid == zq->queue->qid) ?
0857                 TRACK_AGAIN_QUEUE_WEIGHT_PENALTY : 0;
0858             if (!zcrypt_queue_compare(zq, pref_zq,
0859                           wgt + cpen + qpen, pref_wgt))
0860                 continue;
0861             pref_zc = zc;
0862             pref_zq = zq;
0863             pref_wgt = wgt + cpen + qpen;
0864         }
0865     }
0866     pref_zq = zcrypt_pick_queue(pref_zc, pref_zq, &mod, wgt);
0867     spin_unlock(&zcrypt_list_lock);
0868 
0869     if (!pref_zq) {
0870         ZCRYPT_DBF_DBG("%s no matching queue found => ENODEV\n",
0871                    __func__);
0872         rc = -ENODEV;
0873         goto out;
0874     }
0875 
0876     qid = pref_zq->queue->qid;
0877     rc = pref_zq->ops->rsa_modexpo_crt(pref_zq, crt, &ap_msg);
0878 
0879     spin_lock(&zcrypt_list_lock);
0880     zcrypt_drop_queue(pref_zc, pref_zq, mod, wgt);
0881     spin_unlock(&zcrypt_list_lock);
0882 
0883 out:
0884     ap_release_message(&ap_msg);
0885     if (tr) {
0886         tr->last_rc = rc;
0887         tr->last_qid = qid;
0888     }
0889     trace_s390_zcrypt_rep(crt, func_code, rc,
0890                   AP_QID_CARD(qid), AP_QID_QUEUE(qid));
0891     return rc;
0892 }
0893 
0894 static long _zcrypt_send_cprb(bool userspace, struct ap_perms *perms,
0895                   struct zcrypt_track *tr,
0896                   struct ica_xcRB *xcrb)
0897 {
0898     struct zcrypt_card *zc, *pref_zc;
0899     struct zcrypt_queue *zq, *pref_zq;
0900     struct ap_message ap_msg;
0901     unsigned int wgt = 0, pref_wgt = 0;
0902     unsigned int func_code;
0903     unsigned short *domain, tdom;
0904     int cpen, qpen, qid = 0, rc = -ENODEV;
0905     struct module *mod;
0906 
0907     trace_s390_zcrypt_req(xcrb, TB_ZSECSENDCPRB);
0908 
0909     xcrb->status = 0;
0910     ap_init_message(&ap_msg);
0911 
0912 #ifdef CONFIG_ZCRYPT_DEBUG
0913     if (tr && tr->fi.cmd)
0914         ap_msg.fi.cmd = tr->fi.cmd;
0915     if (tr && tr->fi.action == AP_FI_ACTION_CCA_AGENT_FF) {
0916         ZCRYPT_DBF_WARN("%s fi cmd 0x%04x: forcing invalid agent_ID 'FF'\n",
0917                 __func__, tr->fi.cmd);
0918         xcrb->agent_ID = 0x4646;
0919     }
0920 #endif
0921 
0922     rc = prep_cca_ap_msg(userspace, xcrb, &ap_msg, &func_code, &domain);
0923     if (rc)
0924         goto out;
0925 
0926     tdom = *domain;
0927     if (perms != &ap_perms && tdom < AP_DOMAINS) {
0928         if (ap_msg.flags & AP_MSG_FLAG_ADMIN) {
0929             if (!test_bit_inv(tdom, perms->adm)) {
0930                 rc = -ENODEV;
0931                 goto out;
0932             }
0933         } else if ((ap_msg.flags & AP_MSG_FLAG_USAGE) == 0) {
0934             rc = -EOPNOTSUPP;
0935             goto out;
0936         }
0937     }
0938     /*
0939      * If a valid target domain is set and this domain is NOT a usage
0940      * domain but a control only domain, autoselect target domain.
0941      */
0942     if (tdom < AP_DOMAINS &&
0943         !ap_test_config_usage_domain(tdom) &&
0944         ap_test_config_ctrl_domain(tdom))
0945         tdom = AUTOSEL_DOM;
0946 
0947     pref_zc = NULL;
0948     pref_zq = NULL;
0949     spin_lock(&zcrypt_list_lock);
0950     for_each_zcrypt_card(zc) {
0951         /* Check for usable CCA card */
0952         if (!zc->online || !zc->card->config || zc->card->chkstop ||
0953             !(zc->card->functions & 0x10000000))
0954             continue;
0955         /* Check for user selected CCA card */
0956         if (xcrb->user_defined != AUTOSELECT &&
0957             xcrb->user_defined != zc->card->id)
0958             continue;
0959         /* check if request size exceeds card max msg size */
0960         if (ap_msg.len > zc->card->maxmsgsize)
0961             continue;
0962         /* check if device node has admission for this card */
0963         if (!zcrypt_check_card(perms, zc->card->id))
0964             continue;
0965         /* get weight index of the card device  */
0966         wgt = speed_idx_cca(func_code) * zc->speed_rating[SECKEY];
0967         /* penalty if this msg was previously sent via this card */
0968         cpen = (tr && tr->again_counter && tr->last_qid &&
0969             AP_QID_CARD(tr->last_qid) == zc->card->id) ?
0970             TRACK_AGAIN_CARD_WEIGHT_PENALTY : 0;
0971         if (!zcrypt_card_compare(zc, pref_zc, wgt + cpen, pref_wgt))
0972             continue;
0973         for_each_zcrypt_queue(zq, zc) {
0974             /* check for device usable and eligible */
0975             if (!zq->online || !zq->ops->send_cprb ||
0976                 !zq->queue->config || zq->queue->chkstop ||
0977                 (tdom != AUTOSEL_DOM &&
0978                  tdom != AP_QID_QUEUE(zq->queue->qid)))
0979                 continue;
0980             /* check if device node has admission for this queue */
0981             if (!zcrypt_check_queue(perms,
0982                         AP_QID_QUEUE(zq->queue->qid)))
0983                 continue;
0984             /* penalty if the msg was previously sent at this qid */
0985             qpen = (tr && tr->again_counter && tr->last_qid &&
0986                 tr->last_qid == zq->queue->qid) ?
0987                 TRACK_AGAIN_QUEUE_WEIGHT_PENALTY : 0;
0988             if (!zcrypt_queue_compare(zq, pref_zq,
0989                           wgt + cpen + qpen, pref_wgt))
0990                 continue;
0991             pref_zc = zc;
0992             pref_zq = zq;
0993             pref_wgt = wgt + cpen + qpen;
0994         }
0995     }
0996     pref_zq = zcrypt_pick_queue(pref_zc, pref_zq, &mod, wgt);
0997     spin_unlock(&zcrypt_list_lock);
0998 
0999     if (!pref_zq) {
1000         ZCRYPT_DBF_DBG("%s no match for address %02x.%04x => ENODEV\n",
1001                    __func__, xcrb->user_defined, *domain);
1002         rc = -ENODEV;
1003         goto out;
1004     }
1005 
1006     /* in case of auto select, provide the correct domain */
1007     qid = pref_zq->queue->qid;
1008     if (*domain == AUTOSEL_DOM)
1009         *domain = AP_QID_QUEUE(qid);
1010 
1011 #ifdef CONFIG_ZCRYPT_DEBUG
1012     if (tr && tr->fi.action == AP_FI_ACTION_CCA_DOM_INVAL) {
1013         ZCRYPT_DBF_WARN("%s fi cmd 0x%04x: forcing invalid domain\n",
1014                 __func__, tr->fi.cmd);
1015         *domain = 99;
1016     }
1017 #endif
1018 
1019     rc = pref_zq->ops->send_cprb(userspace, pref_zq, xcrb, &ap_msg);
1020 
1021     spin_lock(&zcrypt_list_lock);
1022     zcrypt_drop_queue(pref_zc, pref_zq, mod, wgt);
1023     spin_unlock(&zcrypt_list_lock);
1024 
1025 out:
1026     ap_release_message(&ap_msg);
1027     if (tr) {
1028         tr->last_rc = rc;
1029         tr->last_qid = qid;
1030     }
1031     trace_s390_zcrypt_rep(xcrb, func_code, rc,
1032                   AP_QID_CARD(qid), AP_QID_QUEUE(qid));
1033     return rc;
1034 }
1035 
1036 long zcrypt_send_cprb(struct ica_xcRB *xcrb)
1037 {
1038     return _zcrypt_send_cprb(false, &ap_perms, NULL, xcrb);
1039 }
1040 EXPORT_SYMBOL(zcrypt_send_cprb);
1041 
1042 static bool is_desired_ep11_card(unsigned int dev_id,
1043                  unsigned short target_num,
1044                  struct ep11_target_dev *targets)
1045 {
1046     while (target_num-- > 0) {
1047         if (targets->ap_id == dev_id || targets->ap_id == AUTOSEL_AP)
1048             return true;
1049         targets++;
1050     }
1051     return false;
1052 }
1053 
1054 static bool is_desired_ep11_queue(unsigned int dev_qid,
1055                   unsigned short target_num,
1056                   struct ep11_target_dev *targets)
1057 {
1058     int card = AP_QID_CARD(dev_qid), dom = AP_QID_QUEUE(dev_qid);
1059 
1060     while (target_num-- > 0) {
1061         if ((targets->ap_id == card || targets->ap_id == AUTOSEL_AP) &&
1062             (targets->dom_id == dom || targets->dom_id == AUTOSEL_DOM))
1063             return true;
1064         targets++;
1065     }
1066     return false;
1067 }
1068 
1069 static long _zcrypt_send_ep11_cprb(bool userspace, struct ap_perms *perms,
1070                    struct zcrypt_track *tr,
1071                    struct ep11_urb *xcrb)
1072 {
1073     struct zcrypt_card *zc, *pref_zc;
1074     struct zcrypt_queue *zq, *pref_zq;
1075     struct ep11_target_dev *targets;
1076     unsigned short target_num;
1077     unsigned int wgt = 0, pref_wgt = 0;
1078     unsigned int func_code, domain;
1079     struct ap_message ap_msg;
1080     int cpen, qpen, qid = 0, rc = -ENODEV;
1081     struct module *mod;
1082 
1083     trace_s390_zcrypt_req(xcrb, TP_ZSENDEP11CPRB);
1084 
1085     ap_init_message(&ap_msg);
1086 
1087 #ifdef CONFIG_ZCRYPT_DEBUG
1088     if (tr && tr->fi.cmd)
1089         ap_msg.fi.cmd = tr->fi.cmd;
1090 #endif
1091 
1092     target_num = (unsigned short)xcrb->targets_num;
1093 
1094     /* empty list indicates autoselect (all available targets) */
1095     targets = NULL;
1096     if (target_num != 0) {
1097         struct ep11_target_dev __user *uptr;
1098 
1099         targets = kcalloc(target_num, sizeof(*targets), GFP_KERNEL);
1100         if (!targets) {
1101             func_code = 0;
1102             rc = -ENOMEM;
1103             goto out;
1104         }
1105 
1106         uptr = (struct ep11_target_dev __force __user *)xcrb->targets;
1107         if (z_copy_from_user(userspace, targets, uptr,
1108                      target_num * sizeof(*targets))) {
1109             func_code = 0;
1110             rc = -EFAULT;
1111             goto out_free;
1112         }
1113     }
1114 
1115     rc = prep_ep11_ap_msg(userspace, xcrb, &ap_msg, &func_code, &domain);
1116     if (rc)
1117         goto out_free;
1118 
1119     if (perms != &ap_perms && domain < AUTOSEL_DOM) {
1120         if (ap_msg.flags & AP_MSG_FLAG_ADMIN) {
1121             if (!test_bit_inv(domain, perms->adm)) {
1122                 rc = -ENODEV;
1123                 goto out_free;
1124             }
1125         } else if ((ap_msg.flags & AP_MSG_FLAG_USAGE) == 0) {
1126             rc = -EOPNOTSUPP;
1127             goto out_free;
1128         }
1129     }
1130 
1131     pref_zc = NULL;
1132     pref_zq = NULL;
1133     spin_lock(&zcrypt_list_lock);
1134     for_each_zcrypt_card(zc) {
1135         /* Check for usable EP11 card */
1136         if (!zc->online || !zc->card->config || zc->card->chkstop ||
1137             !(zc->card->functions & 0x04000000))
1138             continue;
1139         /* Check for user selected EP11 card */
1140         if (targets &&
1141             !is_desired_ep11_card(zc->card->id, target_num, targets))
1142             continue;
1143         /* check if request size exceeds card max msg size */
1144         if (ap_msg.len > zc->card->maxmsgsize)
1145             continue;
1146         /* check if device node has admission for this card */
1147         if (!zcrypt_check_card(perms, zc->card->id))
1148             continue;
1149         /* get weight index of the card device  */
1150         wgt = speed_idx_ep11(func_code) * zc->speed_rating[SECKEY];
1151         /* penalty if this msg was previously sent via this card */
1152         cpen = (tr && tr->again_counter && tr->last_qid &&
1153             AP_QID_CARD(tr->last_qid) == zc->card->id) ?
1154             TRACK_AGAIN_CARD_WEIGHT_PENALTY : 0;
1155         if (!zcrypt_card_compare(zc, pref_zc, wgt + cpen, pref_wgt))
1156             continue;
1157         for_each_zcrypt_queue(zq, zc) {
1158             /* check if device is usable and eligible */
1159             if (!zq->online || !zq->ops->send_ep11_cprb ||
1160                 !zq->queue->config || zq->queue->chkstop ||
1161                 (targets &&
1162                  !is_desired_ep11_queue(zq->queue->qid,
1163                             target_num, targets)))
1164                 continue;
1165             /* check if device node has admission for this queue */
1166             if (!zcrypt_check_queue(perms,
1167                         AP_QID_QUEUE(zq->queue->qid)))
1168                 continue;
1169             /* penalty if the msg was previously sent at this qid */
1170             qpen = (tr && tr->again_counter && tr->last_qid &&
1171                 tr->last_qid == zq->queue->qid) ?
1172                 TRACK_AGAIN_QUEUE_WEIGHT_PENALTY : 0;
1173             if (!zcrypt_queue_compare(zq, pref_zq,
1174                           wgt + cpen + qpen, pref_wgt))
1175                 continue;
1176             pref_zc = zc;
1177             pref_zq = zq;
1178             pref_wgt = wgt + cpen + qpen;
1179         }
1180     }
1181     pref_zq = zcrypt_pick_queue(pref_zc, pref_zq, &mod, wgt);
1182     spin_unlock(&zcrypt_list_lock);
1183 
1184     if (!pref_zq) {
1185         if (targets && target_num == 1) {
1186             ZCRYPT_DBF_DBG("%s no match for address %02x.%04x => ENODEV\n",
1187                        __func__, (int)targets->ap_id,
1188                        (int)targets->dom_id);
1189         } else if (targets) {
1190             ZCRYPT_DBF_DBG("%s no match for %d target addrs => ENODEV\n",
1191                        __func__, (int)target_num);
1192         } else {
1193             ZCRYPT_DBF_DBG("%s no match for address ff.ffff => ENODEV\n",
1194                        __func__);
1195         }
1196         rc = -ENODEV;
1197         goto out_free;
1198     }
1199 
1200     qid = pref_zq->queue->qid;
1201     rc = pref_zq->ops->send_ep11_cprb(userspace, pref_zq, xcrb, &ap_msg);
1202 
1203     spin_lock(&zcrypt_list_lock);
1204     zcrypt_drop_queue(pref_zc, pref_zq, mod, wgt);
1205     spin_unlock(&zcrypt_list_lock);
1206 
1207 out_free:
1208     kfree(targets);
1209 out:
1210     ap_release_message(&ap_msg);
1211     if (tr) {
1212         tr->last_rc = rc;
1213         tr->last_qid = qid;
1214     }
1215     trace_s390_zcrypt_rep(xcrb, func_code, rc,
1216                   AP_QID_CARD(qid), AP_QID_QUEUE(qid));
1217     return rc;
1218 }
1219 
1220 long zcrypt_send_ep11_cprb(struct ep11_urb *xcrb)
1221 {
1222     return _zcrypt_send_ep11_cprb(false, &ap_perms, NULL, xcrb);
1223 }
1224 EXPORT_SYMBOL(zcrypt_send_ep11_cprb);
1225 
1226 static long zcrypt_rng(char *buffer)
1227 {
1228     struct zcrypt_card *zc, *pref_zc;
1229     struct zcrypt_queue *zq, *pref_zq;
1230     unsigned int wgt = 0, pref_wgt = 0;
1231     unsigned int func_code;
1232     struct ap_message ap_msg;
1233     unsigned int domain;
1234     int qid = 0, rc = -ENODEV;
1235     struct module *mod;
1236 
1237     trace_s390_zcrypt_req(buffer, TP_HWRNGCPRB);
1238 
1239     ap_init_message(&ap_msg);
1240     rc = prep_rng_ap_msg(&ap_msg, &func_code, &domain);
1241     if (rc)
1242         goto out;
1243 
1244     pref_zc = NULL;
1245     pref_zq = NULL;
1246     spin_lock(&zcrypt_list_lock);
1247     for_each_zcrypt_card(zc) {
1248         /* Check for usable CCA card */
1249         if (!zc->online || !zc->card->config || zc->card->chkstop ||
1250             !(zc->card->functions & 0x10000000))
1251             continue;
1252         /* get weight index of the card device  */
1253         wgt = zc->speed_rating[func_code];
1254         if (!zcrypt_card_compare(zc, pref_zc, wgt, pref_wgt))
1255             continue;
1256         for_each_zcrypt_queue(zq, zc) {
1257             /* check if device is usable and eligible */
1258             if (!zq->online || !zq->ops->rng ||
1259                 !zq->queue->config || zq->queue->chkstop)
1260                 continue;
1261             if (!zcrypt_queue_compare(zq, pref_zq, wgt, pref_wgt))
1262                 continue;
1263             pref_zc = zc;
1264             pref_zq = zq;
1265             pref_wgt = wgt;
1266         }
1267     }
1268     pref_zq = zcrypt_pick_queue(pref_zc, pref_zq, &mod, wgt);
1269     spin_unlock(&zcrypt_list_lock);
1270 
1271     if (!pref_zq) {
1272         ZCRYPT_DBF_DBG("%s no matching queue found => ENODEV\n",
1273                    __func__);
1274         rc = -ENODEV;
1275         goto out;
1276     }
1277 
1278     qid = pref_zq->queue->qid;
1279     rc = pref_zq->ops->rng(pref_zq, buffer, &ap_msg);
1280 
1281     spin_lock(&zcrypt_list_lock);
1282     zcrypt_drop_queue(pref_zc, pref_zq, mod, wgt);
1283     spin_unlock(&zcrypt_list_lock);
1284 
1285 out:
1286     ap_release_message(&ap_msg);
1287     trace_s390_zcrypt_rep(buffer, func_code, rc,
1288                   AP_QID_CARD(qid), AP_QID_QUEUE(qid));
1289     return rc;
1290 }
1291 
1292 static void zcrypt_device_status_mask(struct zcrypt_device_status *devstatus)
1293 {
1294     struct zcrypt_card *zc;
1295     struct zcrypt_queue *zq;
1296     struct zcrypt_device_status *stat;
1297     int card, queue;
1298 
1299     memset(devstatus, 0, MAX_ZDEV_ENTRIES
1300            * sizeof(struct zcrypt_device_status));
1301 
1302     spin_lock(&zcrypt_list_lock);
1303     for_each_zcrypt_card(zc) {
1304         for_each_zcrypt_queue(zq, zc) {
1305             card = AP_QID_CARD(zq->queue->qid);
1306             if (card >= MAX_ZDEV_CARDIDS)
1307                 continue;
1308             queue = AP_QID_QUEUE(zq->queue->qid);
1309             stat = &devstatus[card * AP_DOMAINS + queue];
1310             stat->hwtype = zc->card->ap_dev.device_type;
1311             stat->functions = zc->card->functions >> 26;
1312             stat->qid = zq->queue->qid;
1313             stat->online = zq->online ? 0x01 : 0x00;
1314         }
1315     }
1316     spin_unlock(&zcrypt_list_lock);
1317 }
1318 
1319 void zcrypt_device_status_mask_ext(struct zcrypt_device_status_ext *devstatus)
1320 {
1321     struct zcrypt_card *zc;
1322     struct zcrypt_queue *zq;
1323     struct zcrypt_device_status_ext *stat;
1324     int card, queue;
1325 
1326     memset(devstatus, 0, MAX_ZDEV_ENTRIES_EXT
1327            * sizeof(struct zcrypt_device_status_ext));
1328 
1329     spin_lock(&zcrypt_list_lock);
1330     for_each_zcrypt_card(zc) {
1331         for_each_zcrypt_queue(zq, zc) {
1332             card = AP_QID_CARD(zq->queue->qid);
1333             queue = AP_QID_QUEUE(zq->queue->qid);
1334             stat = &devstatus[card * AP_DOMAINS + queue];
1335             stat->hwtype = zc->card->ap_dev.device_type;
1336             stat->functions = zc->card->functions >> 26;
1337             stat->qid = zq->queue->qid;
1338             stat->online = zq->online ? 0x01 : 0x00;
1339         }
1340     }
1341     spin_unlock(&zcrypt_list_lock);
1342 }
1343 EXPORT_SYMBOL(zcrypt_device_status_mask_ext);
1344 
1345 int zcrypt_device_status_ext(int card, int queue,
1346                  struct zcrypt_device_status_ext *devstat)
1347 {
1348     struct zcrypt_card *zc;
1349     struct zcrypt_queue *zq;
1350 
1351     memset(devstat, 0, sizeof(*devstat));
1352 
1353     spin_lock(&zcrypt_list_lock);
1354     for_each_zcrypt_card(zc) {
1355         for_each_zcrypt_queue(zq, zc) {
1356             if (card == AP_QID_CARD(zq->queue->qid) &&
1357                 queue == AP_QID_QUEUE(zq->queue->qid)) {
1358                 devstat->hwtype = zc->card->ap_dev.device_type;
1359                 devstat->functions = zc->card->functions >> 26;
1360                 devstat->qid = zq->queue->qid;
1361                 devstat->online = zq->online ? 0x01 : 0x00;
1362                 spin_unlock(&zcrypt_list_lock);
1363                 return 0;
1364             }
1365         }
1366     }
1367     spin_unlock(&zcrypt_list_lock);
1368 
1369     return -ENODEV;
1370 }
1371 EXPORT_SYMBOL(zcrypt_device_status_ext);
1372 
1373 static void zcrypt_status_mask(char status[], size_t max_adapters)
1374 {
1375     struct zcrypt_card *zc;
1376     struct zcrypt_queue *zq;
1377     int card;
1378 
1379     memset(status, 0, max_adapters);
1380     spin_lock(&zcrypt_list_lock);
1381     for_each_zcrypt_card(zc) {
1382         for_each_zcrypt_queue(zq, zc) {
1383             card = AP_QID_CARD(zq->queue->qid);
1384             if (AP_QID_QUEUE(zq->queue->qid) != ap_domain_index ||
1385                 card >= max_adapters)
1386                 continue;
1387             status[card] = zc->online ? zc->user_space_type : 0x0d;
1388         }
1389     }
1390     spin_unlock(&zcrypt_list_lock);
1391 }
1392 
1393 static void zcrypt_qdepth_mask(char qdepth[], size_t max_adapters)
1394 {
1395     struct zcrypt_card *zc;
1396     struct zcrypt_queue *zq;
1397     int card;
1398 
1399     memset(qdepth, 0, max_adapters);
1400     spin_lock(&zcrypt_list_lock);
1401     local_bh_disable();
1402     for_each_zcrypt_card(zc) {
1403         for_each_zcrypt_queue(zq, zc) {
1404             card = AP_QID_CARD(zq->queue->qid);
1405             if (AP_QID_QUEUE(zq->queue->qid) != ap_domain_index ||
1406                 card >= max_adapters)
1407                 continue;
1408             spin_lock(&zq->queue->lock);
1409             qdepth[card] =
1410                 zq->queue->pendingq_count +
1411                 zq->queue->requestq_count;
1412             spin_unlock(&zq->queue->lock);
1413         }
1414     }
1415     local_bh_enable();
1416     spin_unlock(&zcrypt_list_lock);
1417 }
1418 
1419 static void zcrypt_perdev_reqcnt(u32 reqcnt[], size_t max_adapters)
1420 {
1421     struct zcrypt_card *zc;
1422     struct zcrypt_queue *zq;
1423     int card;
1424     u64 cnt;
1425 
1426     memset(reqcnt, 0, sizeof(int) * max_adapters);
1427     spin_lock(&zcrypt_list_lock);
1428     local_bh_disable();
1429     for_each_zcrypt_card(zc) {
1430         for_each_zcrypt_queue(zq, zc) {
1431             card = AP_QID_CARD(zq->queue->qid);
1432             if (AP_QID_QUEUE(zq->queue->qid) != ap_domain_index ||
1433                 card >= max_adapters)
1434                 continue;
1435             spin_lock(&zq->queue->lock);
1436             cnt = zq->queue->total_request_count;
1437             spin_unlock(&zq->queue->lock);
1438             reqcnt[card] = (cnt < UINT_MAX) ? (u32)cnt : UINT_MAX;
1439         }
1440     }
1441     local_bh_enable();
1442     spin_unlock(&zcrypt_list_lock);
1443 }
1444 
1445 static int zcrypt_pendingq_count(void)
1446 {
1447     struct zcrypt_card *zc;
1448     struct zcrypt_queue *zq;
1449     int pendingq_count;
1450 
1451     pendingq_count = 0;
1452     spin_lock(&zcrypt_list_lock);
1453     local_bh_disable();
1454     for_each_zcrypt_card(zc) {
1455         for_each_zcrypt_queue(zq, zc) {
1456             if (AP_QID_QUEUE(zq->queue->qid) != ap_domain_index)
1457                 continue;
1458             spin_lock(&zq->queue->lock);
1459             pendingq_count += zq->queue->pendingq_count;
1460             spin_unlock(&zq->queue->lock);
1461         }
1462     }
1463     local_bh_enable();
1464     spin_unlock(&zcrypt_list_lock);
1465     return pendingq_count;
1466 }
1467 
1468 static int zcrypt_requestq_count(void)
1469 {
1470     struct zcrypt_card *zc;
1471     struct zcrypt_queue *zq;
1472     int requestq_count;
1473 
1474     requestq_count = 0;
1475     spin_lock(&zcrypt_list_lock);
1476     local_bh_disable();
1477     for_each_zcrypt_card(zc) {
1478         for_each_zcrypt_queue(zq, zc) {
1479             if (AP_QID_QUEUE(zq->queue->qid) != ap_domain_index)
1480                 continue;
1481             spin_lock(&zq->queue->lock);
1482             requestq_count += zq->queue->requestq_count;
1483             spin_unlock(&zq->queue->lock);
1484         }
1485     }
1486     local_bh_enable();
1487     spin_unlock(&zcrypt_list_lock);
1488     return requestq_count;
1489 }
1490 
1491 static int icarsamodexpo_ioctl(struct ap_perms *perms, unsigned long arg)
1492 {
1493     int rc;
1494     struct zcrypt_track tr;
1495     struct ica_rsa_modexpo mex;
1496     struct ica_rsa_modexpo __user *umex = (void __user *)arg;
1497 
1498     memset(&tr, 0, sizeof(tr));
1499     if (copy_from_user(&mex, umex, sizeof(mex)))
1500         return -EFAULT;
1501 
1502 #ifdef CONFIG_ZCRYPT_DEBUG
1503     if (mex.inputdatalength & (1U << 31)) {
1504         if (!capable(CAP_SYS_ADMIN))
1505             return -EPERM;
1506         tr.fi.cmd = (u16)(mex.inputdatalength >> 16);
1507     }
1508     mex.inputdatalength &= 0x0000FFFF;
1509 #endif
1510 
1511     do {
1512         rc = zcrypt_rsa_modexpo(perms, &tr, &mex);
1513         if (rc == -EAGAIN)
1514             tr.again_counter++;
1515 #ifdef CONFIG_ZCRYPT_DEBUG
1516         if (rc == -EAGAIN && (tr.fi.flags & AP_FI_FLAG_NO_RETRY))
1517             break;
1518 #endif
1519     } while (rc == -EAGAIN && tr.again_counter < TRACK_AGAIN_MAX);
1520     /* on failure: retry once again after a requested rescan */
1521     if ((rc == -ENODEV) && (zcrypt_process_rescan()))
1522         do {
1523             rc = zcrypt_rsa_modexpo(perms, &tr, &mex);
1524             if (rc == -EAGAIN)
1525                 tr.again_counter++;
1526         } while (rc == -EAGAIN && tr.again_counter < TRACK_AGAIN_MAX);
1527     if (rc == -EAGAIN && tr.again_counter >= TRACK_AGAIN_MAX)
1528         rc = -EIO;
1529     if (rc) {
1530         ZCRYPT_DBF_DBG("ioctl ICARSAMODEXPO rc=%d\n", rc);
1531         return rc;
1532     }
1533     return put_user(mex.outputdatalength, &umex->outputdatalength);
1534 }
1535 
1536 static int icarsacrt_ioctl(struct ap_perms *perms, unsigned long arg)
1537 {
1538     int rc;
1539     struct zcrypt_track tr;
1540     struct ica_rsa_modexpo_crt crt;
1541     struct ica_rsa_modexpo_crt __user *ucrt = (void __user *)arg;
1542 
1543     memset(&tr, 0, sizeof(tr));
1544     if (copy_from_user(&crt, ucrt, sizeof(crt)))
1545         return -EFAULT;
1546 
1547 #ifdef CONFIG_ZCRYPT_DEBUG
1548     if (crt.inputdatalength & (1U << 31)) {
1549         if (!capable(CAP_SYS_ADMIN))
1550             return -EPERM;
1551         tr.fi.cmd = (u16)(crt.inputdatalength >> 16);
1552     }
1553     crt.inputdatalength &= 0x0000FFFF;
1554 #endif
1555 
1556     do {
1557         rc = zcrypt_rsa_crt(perms, &tr, &crt);
1558         if (rc == -EAGAIN)
1559             tr.again_counter++;
1560 #ifdef CONFIG_ZCRYPT_DEBUG
1561         if (rc == -EAGAIN && (tr.fi.flags & AP_FI_FLAG_NO_RETRY))
1562             break;
1563 #endif
1564     } while (rc == -EAGAIN && tr.again_counter < TRACK_AGAIN_MAX);
1565     /* on failure: retry once again after a requested rescan */
1566     if ((rc == -ENODEV) && (zcrypt_process_rescan()))
1567         do {
1568             rc = zcrypt_rsa_crt(perms, &tr, &crt);
1569             if (rc == -EAGAIN)
1570                 tr.again_counter++;
1571         } while (rc == -EAGAIN && tr.again_counter < TRACK_AGAIN_MAX);
1572     if (rc == -EAGAIN && tr.again_counter >= TRACK_AGAIN_MAX)
1573         rc = -EIO;
1574     if (rc) {
1575         ZCRYPT_DBF_DBG("ioctl ICARSACRT rc=%d\n", rc);
1576         return rc;
1577     }
1578     return put_user(crt.outputdatalength, &ucrt->outputdatalength);
1579 }
1580 
1581 static int zsecsendcprb_ioctl(struct ap_perms *perms, unsigned long arg)
1582 {
1583     int rc;
1584     struct ica_xcRB xcrb;
1585     struct zcrypt_track tr;
1586     struct ica_xcRB __user *uxcrb = (void __user *)arg;
1587 
1588     memset(&tr, 0, sizeof(tr));
1589     if (copy_from_user(&xcrb, uxcrb, sizeof(xcrb)))
1590         return -EFAULT;
1591 
1592 #ifdef CONFIG_ZCRYPT_DEBUG
1593     if ((xcrb.status & 0x8000FFFF) == 0x80004649 /* 'FI' */) {
1594         if (!capable(CAP_SYS_ADMIN))
1595             return -EPERM;
1596         tr.fi.cmd = (u16)(xcrb.status >> 16);
1597     }
1598     xcrb.status = 0;
1599 #endif
1600 
1601     do {
1602         rc = _zcrypt_send_cprb(true, perms, &tr, &xcrb);
1603         if (rc == -EAGAIN)
1604             tr.again_counter++;
1605 #ifdef CONFIG_ZCRYPT_DEBUG
1606         if (rc == -EAGAIN && (tr.fi.flags & AP_FI_FLAG_NO_RETRY))
1607             break;
1608 #endif
1609     } while (rc == -EAGAIN && tr.again_counter < TRACK_AGAIN_MAX);
1610     /* on failure: retry once again after a requested rescan */
1611     if ((rc == -ENODEV) && (zcrypt_process_rescan()))
1612         do {
1613             rc = _zcrypt_send_cprb(true, perms, &tr, &xcrb);
1614             if (rc == -EAGAIN)
1615                 tr.again_counter++;
1616         } while (rc == -EAGAIN && tr.again_counter < TRACK_AGAIN_MAX);
1617     if (rc == -EAGAIN && tr.again_counter >= TRACK_AGAIN_MAX)
1618         rc = -EIO;
1619     if (rc)
1620         ZCRYPT_DBF_DBG("ioctl ZSENDCPRB rc=%d status=0x%x\n",
1621                    rc, xcrb.status);
1622     if (copy_to_user(uxcrb, &xcrb, sizeof(xcrb)))
1623         return -EFAULT;
1624     return rc;
1625 }
1626 
1627 static int zsendep11cprb_ioctl(struct ap_perms *perms, unsigned long arg)
1628 {
1629     int rc;
1630     struct ep11_urb xcrb;
1631     struct zcrypt_track tr;
1632     struct ep11_urb __user *uxcrb = (void __user *)arg;
1633 
1634     memset(&tr, 0, sizeof(tr));
1635     if (copy_from_user(&xcrb, uxcrb, sizeof(xcrb)))
1636         return -EFAULT;
1637 
1638 #ifdef CONFIG_ZCRYPT_DEBUG
1639     if (xcrb.req_len & (1ULL << 63)) {
1640         if (!capable(CAP_SYS_ADMIN))
1641             return -EPERM;
1642         tr.fi.cmd = (u16)(xcrb.req_len >> 48);
1643     }
1644     xcrb.req_len &= 0x0000FFFFFFFFFFFFULL;
1645 #endif
1646 
1647     do {
1648         rc = _zcrypt_send_ep11_cprb(true, perms, &tr, &xcrb);
1649         if (rc == -EAGAIN)
1650             tr.again_counter++;
1651 #ifdef CONFIG_ZCRYPT_DEBUG
1652         if (rc == -EAGAIN && (tr.fi.flags & AP_FI_FLAG_NO_RETRY))
1653             break;
1654 #endif
1655     } while (rc == -EAGAIN && tr.again_counter < TRACK_AGAIN_MAX);
1656     /* on failure: retry once again after a requested rescan */
1657     if ((rc == -ENODEV) && (zcrypt_process_rescan()))
1658         do {
1659             rc = _zcrypt_send_ep11_cprb(true, perms, &tr, &xcrb);
1660             if (rc == -EAGAIN)
1661                 tr.again_counter++;
1662         } while (rc == -EAGAIN && tr.again_counter < TRACK_AGAIN_MAX);
1663     if (rc == -EAGAIN && tr.again_counter >= TRACK_AGAIN_MAX)
1664         rc = -EIO;
1665     if (rc)
1666         ZCRYPT_DBF_DBG("ioctl ZSENDEP11CPRB rc=%d\n", rc);
1667     if (copy_to_user(uxcrb, &xcrb, sizeof(xcrb)))
1668         return -EFAULT;
1669     return rc;
1670 }
1671 
1672 static long zcrypt_unlocked_ioctl(struct file *filp, unsigned int cmd,
1673                   unsigned long arg)
1674 {
1675     int rc;
1676     struct ap_perms *perms =
1677         (struct ap_perms *)filp->private_data;
1678 
1679     rc = zcrypt_check_ioctl(perms, cmd);
1680     if (rc)
1681         return rc;
1682 
1683     switch (cmd) {
1684     case ICARSAMODEXPO:
1685         return icarsamodexpo_ioctl(perms, arg);
1686     case ICARSACRT:
1687         return icarsacrt_ioctl(perms, arg);
1688     case ZSECSENDCPRB:
1689         return zsecsendcprb_ioctl(perms, arg);
1690     case ZSENDEP11CPRB:
1691         return zsendep11cprb_ioctl(perms, arg);
1692     case ZCRYPT_DEVICE_STATUS: {
1693         struct zcrypt_device_status_ext *device_status;
1694         size_t total_size = MAX_ZDEV_ENTRIES_EXT
1695             * sizeof(struct zcrypt_device_status_ext);
1696 
1697         device_status = kzalloc(total_size, GFP_KERNEL);
1698         if (!device_status)
1699             return -ENOMEM;
1700         zcrypt_device_status_mask_ext(device_status);
1701         if (copy_to_user((char __user *)arg, device_status,
1702                  total_size))
1703             rc = -EFAULT;
1704         kfree(device_status);
1705         return rc;
1706     }
1707     case ZCRYPT_STATUS_MASK: {
1708         char status[AP_DEVICES];
1709 
1710         zcrypt_status_mask(status, AP_DEVICES);
1711         if (copy_to_user((char __user *)arg, status, sizeof(status)))
1712             return -EFAULT;
1713         return 0;
1714     }
1715     case ZCRYPT_QDEPTH_MASK: {
1716         char qdepth[AP_DEVICES];
1717 
1718         zcrypt_qdepth_mask(qdepth, AP_DEVICES);
1719         if (copy_to_user((char __user *)arg, qdepth, sizeof(qdepth)))
1720             return -EFAULT;
1721         return 0;
1722     }
1723     case ZCRYPT_PERDEV_REQCNT: {
1724         u32 *reqcnt;
1725 
1726         reqcnt = kcalloc(AP_DEVICES, sizeof(u32), GFP_KERNEL);
1727         if (!reqcnt)
1728             return -ENOMEM;
1729         zcrypt_perdev_reqcnt(reqcnt, AP_DEVICES);
1730         if (copy_to_user((int __user *)arg, reqcnt,
1731                  sizeof(u32) * AP_DEVICES))
1732             rc = -EFAULT;
1733         kfree(reqcnt);
1734         return rc;
1735     }
1736     case Z90STAT_REQUESTQ_COUNT:
1737         return put_user(zcrypt_requestq_count(), (int __user *)arg);
1738     case Z90STAT_PENDINGQ_COUNT:
1739         return put_user(zcrypt_pendingq_count(), (int __user *)arg);
1740     case Z90STAT_TOTALOPEN_COUNT:
1741         return put_user(atomic_read(&zcrypt_open_count),
1742                 (int __user *)arg);
1743     case Z90STAT_DOMAIN_INDEX:
1744         return put_user(ap_domain_index, (int __user *)arg);
1745     /*
1746      * Deprecated ioctls
1747      */
1748     case ZDEVICESTATUS: {
1749         /* the old ioctl supports only 64 adapters */
1750         struct zcrypt_device_status *device_status;
1751         size_t total_size = MAX_ZDEV_ENTRIES
1752             * sizeof(struct zcrypt_device_status);
1753 
1754         device_status = kzalloc(total_size, GFP_KERNEL);
1755         if (!device_status)
1756             return -ENOMEM;
1757         zcrypt_device_status_mask(device_status);
1758         if (copy_to_user((char __user *)arg, device_status,
1759                  total_size))
1760             rc = -EFAULT;
1761         kfree(device_status);
1762         return rc;
1763     }
1764     case Z90STAT_STATUS_MASK: {
1765         /* the old ioctl supports only 64 adapters */
1766         char status[MAX_ZDEV_CARDIDS];
1767 
1768         zcrypt_status_mask(status, MAX_ZDEV_CARDIDS);
1769         if (copy_to_user((char __user *)arg, status, sizeof(status)))
1770             return -EFAULT;
1771         return 0;
1772     }
1773     case Z90STAT_QDEPTH_MASK: {
1774         /* the old ioctl supports only 64 adapters */
1775         char qdepth[MAX_ZDEV_CARDIDS];
1776 
1777         zcrypt_qdepth_mask(qdepth, MAX_ZDEV_CARDIDS);
1778         if (copy_to_user((char __user *)arg, qdepth, sizeof(qdepth)))
1779             return -EFAULT;
1780         return 0;
1781     }
1782     case Z90STAT_PERDEV_REQCNT: {
1783         /* the old ioctl supports only 64 adapters */
1784         u32 reqcnt[MAX_ZDEV_CARDIDS];
1785 
1786         zcrypt_perdev_reqcnt(reqcnt, MAX_ZDEV_CARDIDS);
1787         if (copy_to_user((int __user *)arg, reqcnt, sizeof(reqcnt)))
1788             return -EFAULT;
1789         return 0;
1790     }
1791     /* unknown ioctl number */
1792     default:
1793         ZCRYPT_DBF_DBG("unknown ioctl 0x%08x\n", cmd);
1794         return -ENOIOCTLCMD;
1795     }
1796 }
1797 
1798 #ifdef CONFIG_COMPAT
1799 /*
1800  * ioctl32 conversion routines
1801  */
1802 struct compat_ica_rsa_modexpo {
1803     compat_uptr_t   inputdata;
1804     unsigned int    inputdatalength;
1805     compat_uptr_t   outputdata;
1806     unsigned int    outputdatalength;
1807     compat_uptr_t   b_key;
1808     compat_uptr_t   n_modulus;
1809 };
1810 
1811 static long trans_modexpo32(struct ap_perms *perms, struct file *filp,
1812                 unsigned int cmd, unsigned long arg)
1813 {
1814     struct compat_ica_rsa_modexpo __user *umex32 = compat_ptr(arg);
1815     struct compat_ica_rsa_modexpo mex32;
1816     struct ica_rsa_modexpo mex64;
1817     struct zcrypt_track tr;
1818     long rc;
1819 
1820     memset(&tr, 0, sizeof(tr));
1821     if (copy_from_user(&mex32, umex32, sizeof(mex32)))
1822         return -EFAULT;
1823     mex64.inputdata = compat_ptr(mex32.inputdata);
1824     mex64.inputdatalength = mex32.inputdatalength;
1825     mex64.outputdata = compat_ptr(mex32.outputdata);
1826     mex64.outputdatalength = mex32.outputdatalength;
1827     mex64.b_key = compat_ptr(mex32.b_key);
1828     mex64.n_modulus = compat_ptr(mex32.n_modulus);
1829     do {
1830         rc = zcrypt_rsa_modexpo(perms, &tr, &mex64);
1831         if (rc == -EAGAIN)
1832             tr.again_counter++;
1833     } while (rc == -EAGAIN && tr.again_counter < TRACK_AGAIN_MAX);
1834     /* on failure: retry once again after a requested rescan */
1835     if ((rc == -ENODEV) && (zcrypt_process_rescan()))
1836         do {
1837             rc = zcrypt_rsa_modexpo(perms, &tr, &mex64);
1838             if (rc == -EAGAIN)
1839                 tr.again_counter++;
1840         } while (rc == -EAGAIN && tr.again_counter < TRACK_AGAIN_MAX);
1841     if (rc == -EAGAIN && tr.again_counter >= TRACK_AGAIN_MAX)
1842         rc = -EIO;
1843     if (rc)
1844         return rc;
1845     return put_user(mex64.outputdatalength,
1846             &umex32->outputdatalength);
1847 }
1848 
1849 struct compat_ica_rsa_modexpo_crt {
1850     compat_uptr_t   inputdata;
1851     unsigned int    inputdatalength;
1852     compat_uptr_t   outputdata;
1853     unsigned int    outputdatalength;
1854     compat_uptr_t   bp_key;
1855     compat_uptr_t   bq_key;
1856     compat_uptr_t   np_prime;
1857     compat_uptr_t   nq_prime;
1858     compat_uptr_t   u_mult_inv;
1859 };
1860 
1861 static long trans_modexpo_crt32(struct ap_perms *perms, struct file *filp,
1862                 unsigned int cmd, unsigned long arg)
1863 {
1864     struct compat_ica_rsa_modexpo_crt __user *ucrt32 = compat_ptr(arg);
1865     struct compat_ica_rsa_modexpo_crt crt32;
1866     struct ica_rsa_modexpo_crt crt64;
1867     struct zcrypt_track tr;
1868     long rc;
1869 
1870     memset(&tr, 0, sizeof(tr));
1871     if (copy_from_user(&crt32, ucrt32, sizeof(crt32)))
1872         return -EFAULT;
1873     crt64.inputdata = compat_ptr(crt32.inputdata);
1874     crt64.inputdatalength = crt32.inputdatalength;
1875     crt64.outputdata = compat_ptr(crt32.outputdata);
1876     crt64.outputdatalength = crt32.outputdatalength;
1877     crt64.bp_key = compat_ptr(crt32.bp_key);
1878     crt64.bq_key = compat_ptr(crt32.bq_key);
1879     crt64.np_prime = compat_ptr(crt32.np_prime);
1880     crt64.nq_prime = compat_ptr(crt32.nq_prime);
1881     crt64.u_mult_inv = compat_ptr(crt32.u_mult_inv);
1882     do {
1883         rc = zcrypt_rsa_crt(perms, &tr, &crt64);
1884         if (rc == -EAGAIN)
1885             tr.again_counter++;
1886     } while (rc == -EAGAIN && tr.again_counter < TRACK_AGAIN_MAX);
1887     /* on failure: retry once again after a requested rescan */
1888     if ((rc == -ENODEV) && (zcrypt_process_rescan()))
1889         do {
1890             rc = zcrypt_rsa_crt(perms, &tr, &crt64);
1891             if (rc == -EAGAIN)
1892                 tr.again_counter++;
1893         } while (rc == -EAGAIN && tr.again_counter < TRACK_AGAIN_MAX);
1894     if (rc == -EAGAIN && tr.again_counter >= TRACK_AGAIN_MAX)
1895         rc = -EIO;
1896     if (rc)
1897         return rc;
1898     return put_user(crt64.outputdatalength,
1899             &ucrt32->outputdatalength);
1900 }
1901 
1902 struct compat_ica_xcrb {
1903     unsigned short  agent_ID;
1904     unsigned int    user_defined;
1905     unsigned short  request_ID;
1906     unsigned int    request_control_blk_length;
1907     unsigned char   padding1[16 - sizeof(compat_uptr_t)];
1908     compat_uptr_t   request_control_blk_addr;
1909     unsigned int    request_data_length;
1910     char        padding2[16 - sizeof(compat_uptr_t)];
1911     compat_uptr_t   request_data_address;
1912     unsigned int    reply_control_blk_length;
1913     char        padding3[16 - sizeof(compat_uptr_t)];
1914     compat_uptr_t   reply_control_blk_addr;
1915     unsigned int    reply_data_length;
1916     char        padding4[16 - sizeof(compat_uptr_t)];
1917     compat_uptr_t   reply_data_addr;
1918     unsigned short  priority_window;
1919     unsigned int    status;
1920 } __packed;
1921 
1922 static long trans_xcrb32(struct ap_perms *perms, struct file *filp,
1923              unsigned int cmd, unsigned long arg)
1924 {
1925     struct compat_ica_xcrb __user *uxcrb32 = compat_ptr(arg);
1926     struct compat_ica_xcrb xcrb32;
1927     struct zcrypt_track tr;
1928     struct ica_xcRB xcrb64;
1929     long rc;
1930 
1931     memset(&tr, 0, sizeof(tr));
1932     if (copy_from_user(&xcrb32, uxcrb32, sizeof(xcrb32)))
1933         return -EFAULT;
1934     xcrb64.agent_ID = xcrb32.agent_ID;
1935     xcrb64.user_defined = xcrb32.user_defined;
1936     xcrb64.request_ID = xcrb32.request_ID;
1937     xcrb64.request_control_blk_length =
1938         xcrb32.request_control_blk_length;
1939     xcrb64.request_control_blk_addr =
1940         compat_ptr(xcrb32.request_control_blk_addr);
1941     xcrb64.request_data_length =
1942         xcrb32.request_data_length;
1943     xcrb64.request_data_address =
1944         compat_ptr(xcrb32.request_data_address);
1945     xcrb64.reply_control_blk_length =
1946         xcrb32.reply_control_blk_length;
1947     xcrb64.reply_control_blk_addr =
1948         compat_ptr(xcrb32.reply_control_blk_addr);
1949     xcrb64.reply_data_length = xcrb32.reply_data_length;
1950     xcrb64.reply_data_addr =
1951         compat_ptr(xcrb32.reply_data_addr);
1952     xcrb64.priority_window = xcrb32.priority_window;
1953     xcrb64.status = xcrb32.status;
1954     do {
1955         rc = _zcrypt_send_cprb(true, perms, &tr, &xcrb64);
1956         if (rc == -EAGAIN)
1957             tr.again_counter++;
1958     } while (rc == -EAGAIN && tr.again_counter < TRACK_AGAIN_MAX);
1959     /* on failure: retry once again after a requested rescan */
1960     if ((rc == -ENODEV) && (zcrypt_process_rescan()))
1961         do {
1962             rc = _zcrypt_send_cprb(true, perms, &tr, &xcrb64);
1963             if (rc == -EAGAIN)
1964                 tr.again_counter++;
1965         } while (rc == -EAGAIN && tr.again_counter < TRACK_AGAIN_MAX);
1966     if (rc == -EAGAIN && tr.again_counter >= TRACK_AGAIN_MAX)
1967         rc = -EIO;
1968     xcrb32.reply_control_blk_length = xcrb64.reply_control_blk_length;
1969     xcrb32.reply_data_length = xcrb64.reply_data_length;
1970     xcrb32.status = xcrb64.status;
1971     if (copy_to_user(uxcrb32, &xcrb32, sizeof(xcrb32)))
1972         return -EFAULT;
1973     return rc;
1974 }
1975 
1976 static long zcrypt_compat_ioctl(struct file *filp, unsigned int cmd,
1977                 unsigned long arg)
1978 {
1979     int rc;
1980     struct ap_perms *perms =
1981         (struct ap_perms *)filp->private_data;
1982 
1983     rc = zcrypt_check_ioctl(perms, cmd);
1984     if (rc)
1985         return rc;
1986 
1987     if (cmd == ICARSAMODEXPO)
1988         return trans_modexpo32(perms, filp, cmd, arg);
1989     if (cmd == ICARSACRT)
1990         return trans_modexpo_crt32(perms, filp, cmd, arg);
1991     if (cmd == ZSECSENDCPRB)
1992         return trans_xcrb32(perms, filp, cmd, arg);
1993     return zcrypt_unlocked_ioctl(filp, cmd, arg);
1994 }
1995 #endif
1996 
1997 /*
1998  * Misc device file operations.
1999  */
2000 static const struct file_operations zcrypt_fops = {
2001     .owner      = THIS_MODULE,
2002     .read       = zcrypt_read,
2003     .write      = zcrypt_write,
2004     .unlocked_ioctl = zcrypt_unlocked_ioctl,
2005 #ifdef CONFIG_COMPAT
2006     .compat_ioctl   = zcrypt_compat_ioctl,
2007 #endif
2008     .open       = zcrypt_open,
2009     .release    = zcrypt_release,
2010     .llseek     = no_llseek,
2011 };
2012 
2013 /*
2014  * Misc device.
2015  */
2016 static struct miscdevice zcrypt_misc_device = {
2017     .minor      = MISC_DYNAMIC_MINOR,
2018     .name       = "z90crypt",
2019     .fops       = &zcrypt_fops,
2020 };
2021 
2022 static int zcrypt_rng_device_count;
2023 static u32 *zcrypt_rng_buffer;
2024 static int zcrypt_rng_buffer_index;
2025 static DEFINE_MUTEX(zcrypt_rng_mutex);
2026 
2027 static int zcrypt_rng_data_read(struct hwrng *rng, u32 *data)
2028 {
2029     int rc;
2030 
2031     /*
2032      * We don't need locking here because the RNG API guarantees serialized
2033      * read method calls.
2034      */
2035     if (zcrypt_rng_buffer_index == 0) {
2036         rc = zcrypt_rng((char *)zcrypt_rng_buffer);
2037         /* on failure: retry once again after a requested rescan */
2038         if ((rc == -ENODEV) && (zcrypt_process_rescan()))
2039             rc = zcrypt_rng((char *)zcrypt_rng_buffer);
2040         if (rc < 0)
2041             return -EIO;
2042         zcrypt_rng_buffer_index = rc / sizeof(*data);
2043     }
2044     *data = zcrypt_rng_buffer[--zcrypt_rng_buffer_index];
2045     return sizeof(*data);
2046 }
2047 
2048 static struct hwrng zcrypt_rng_dev = {
2049     .name       = "zcrypt",
2050     .data_read  = zcrypt_rng_data_read,
2051     .quality    = 990,
2052 };
2053 
2054 int zcrypt_rng_device_add(void)
2055 {
2056     int rc = 0;
2057 
2058     mutex_lock(&zcrypt_rng_mutex);
2059     if (zcrypt_rng_device_count == 0) {
2060         zcrypt_rng_buffer = (u32 *)get_zeroed_page(GFP_KERNEL);
2061         if (!zcrypt_rng_buffer) {
2062             rc = -ENOMEM;
2063             goto out;
2064         }
2065         zcrypt_rng_buffer_index = 0;
2066         if (!zcrypt_hwrng_seed)
2067             zcrypt_rng_dev.quality = 0;
2068         rc = hwrng_register(&zcrypt_rng_dev);
2069         if (rc)
2070             goto out_free;
2071         zcrypt_rng_device_count = 1;
2072     } else {
2073         zcrypt_rng_device_count++;
2074     }
2075     mutex_unlock(&zcrypt_rng_mutex);
2076     return 0;
2077 
2078 out_free:
2079     free_page((unsigned long)zcrypt_rng_buffer);
2080 out:
2081     mutex_unlock(&zcrypt_rng_mutex);
2082     return rc;
2083 }
2084 
2085 void zcrypt_rng_device_remove(void)
2086 {
2087     mutex_lock(&zcrypt_rng_mutex);
2088     zcrypt_rng_device_count--;
2089     if (zcrypt_rng_device_count == 0) {
2090         hwrng_unregister(&zcrypt_rng_dev);
2091         free_page((unsigned long)zcrypt_rng_buffer);
2092     }
2093     mutex_unlock(&zcrypt_rng_mutex);
2094 }
2095 
2096 /*
2097  * Wait until the zcrypt api is operational.
2098  * The AP bus scan and the binding of ap devices to device drivers is
2099  * an asynchronous job. This function waits until these initial jobs
2100  * are done and so the zcrypt api should be ready to serve crypto
2101  * requests - if there are resources available. The function uses an
2102  * internal timeout of 60s. The very first caller will either wait for
2103  * ap bus bindings complete or the timeout happens. This state will be
2104  * remembered for further callers which will only be blocked until a
2105  * decision is made (timeout or bindings complete).
2106  * On timeout -ETIME is returned, on success the return value is 0.
2107  */
2108 int zcrypt_wait_api_operational(void)
2109 {
2110     static DEFINE_MUTEX(zcrypt_wait_api_lock);
2111     static int zcrypt_wait_api_state;
2112     int rc;
2113 
2114     rc = mutex_lock_interruptible(&zcrypt_wait_api_lock);
2115     if (rc)
2116         return rc;
2117 
2118     switch (zcrypt_wait_api_state) {
2119     case 0:
2120         /* initial state, invoke wait for the ap bus complete */
2121         rc = ap_wait_init_apqn_bindings_complete(
2122             msecs_to_jiffies(60 * 1000));
2123         switch (rc) {
2124         case 0:
2125             /* ap bus bindings are complete */
2126             zcrypt_wait_api_state = 1;
2127             break;
2128         case -EINTR:
2129             /* interrupted, go back to caller */
2130             break;
2131         case -ETIME:
2132             /* timeout */
2133             ZCRYPT_DBF_WARN("%s ap_wait_init_apqn_bindings_complete()=ETIME\n",
2134                     __func__);
2135             zcrypt_wait_api_state = -ETIME;
2136             break;
2137         default:
2138             /* other failure */
2139             ZCRYPT_DBF_DBG("%s ap_wait_init_apqn_bindings_complete()=%d\n",
2140                        __func__, rc);
2141             break;
2142         }
2143         break;
2144     case 1:
2145         /* a previous caller already found ap bus bindings complete */
2146         rc = 0;
2147         break;
2148     default:
2149         /* a previous caller had timeout or other failure */
2150         rc = zcrypt_wait_api_state;
2151         break;
2152     }
2153 
2154     mutex_unlock(&zcrypt_wait_api_lock);
2155 
2156     return rc;
2157 }
2158 EXPORT_SYMBOL(zcrypt_wait_api_operational);
2159 
2160 int __init zcrypt_debug_init(void)
2161 {
2162     zcrypt_dbf_info = debug_register("zcrypt", 2, 1,
2163                      DBF_MAX_SPRINTF_ARGS * sizeof(long));
2164     debug_register_view(zcrypt_dbf_info, &debug_sprintf_view);
2165     debug_set_level(zcrypt_dbf_info, DBF_ERR);
2166 
2167     return 0;
2168 }
2169 
2170 void zcrypt_debug_exit(void)
2171 {
2172     debug_unregister(zcrypt_dbf_info);
2173 }
2174 
2175 #ifdef CONFIG_ZCRYPT_MULTIDEVNODES
2176 
2177 static int __init zcdn_init(void)
2178 {
2179     int rc;
2180 
2181     /* create a new class 'zcrypt' */
2182     zcrypt_class = class_create(THIS_MODULE, ZCRYPT_NAME);
2183     if (IS_ERR(zcrypt_class)) {
2184         rc = PTR_ERR(zcrypt_class);
2185         goto out_class_create_failed;
2186     }
2187     zcrypt_class->dev_release = zcdn_device_release;
2188 
2189     /* alloc device minor range */
2190     rc = alloc_chrdev_region(&zcrypt_devt,
2191                  0, ZCRYPT_MAX_MINOR_NODES,
2192                  ZCRYPT_NAME);
2193     if (rc)
2194         goto out_alloc_chrdev_failed;
2195 
2196     cdev_init(&zcrypt_cdev, &zcrypt_fops);
2197     zcrypt_cdev.owner = THIS_MODULE;
2198     rc = cdev_add(&zcrypt_cdev, zcrypt_devt, ZCRYPT_MAX_MINOR_NODES);
2199     if (rc)
2200         goto out_cdev_add_failed;
2201 
2202     /* need some class specific sysfs attributes */
2203     rc = class_create_file(zcrypt_class, &class_attr_zcdn_create);
2204     if (rc)
2205         goto out_class_create_file_1_failed;
2206     rc = class_create_file(zcrypt_class, &class_attr_zcdn_destroy);
2207     if (rc)
2208         goto out_class_create_file_2_failed;
2209 
2210     return 0;
2211 
2212 out_class_create_file_2_failed:
2213     class_remove_file(zcrypt_class, &class_attr_zcdn_create);
2214 out_class_create_file_1_failed:
2215     cdev_del(&zcrypt_cdev);
2216 out_cdev_add_failed:
2217     unregister_chrdev_region(zcrypt_devt, ZCRYPT_MAX_MINOR_NODES);
2218 out_alloc_chrdev_failed:
2219     class_destroy(zcrypt_class);
2220 out_class_create_failed:
2221     return rc;
2222 }
2223 
2224 static void zcdn_exit(void)
2225 {
2226     class_remove_file(zcrypt_class, &class_attr_zcdn_create);
2227     class_remove_file(zcrypt_class, &class_attr_zcdn_destroy);
2228     zcdn_destroy_all();
2229     cdev_del(&zcrypt_cdev);
2230     unregister_chrdev_region(zcrypt_devt, ZCRYPT_MAX_MINOR_NODES);
2231     class_destroy(zcrypt_class);
2232 }
2233 
2234 #endif
2235 
2236 /*
2237  * zcrypt_api_init(): Module initialization.
2238  *
2239  * The module initialization code.
2240  */
2241 int __init zcrypt_api_init(void)
2242 {
2243     int rc;
2244 
2245     rc = zcrypt_debug_init();
2246     if (rc)
2247         goto out;
2248 
2249 #ifdef CONFIG_ZCRYPT_MULTIDEVNODES
2250     rc = zcdn_init();
2251     if (rc)
2252         goto out;
2253 #endif
2254 
2255     /* Register the request sprayer. */
2256     rc = misc_register(&zcrypt_misc_device);
2257     if (rc < 0)
2258         goto out_misc_register_failed;
2259 
2260     zcrypt_msgtype6_init();
2261     zcrypt_msgtype50_init();
2262 
2263     return 0;
2264 
2265 out_misc_register_failed:
2266 #ifdef CONFIG_ZCRYPT_MULTIDEVNODES
2267     zcdn_exit();
2268 #endif
2269     zcrypt_debug_exit();
2270 out:
2271     return rc;
2272 }
2273 
2274 /*
2275  * zcrypt_api_exit(): Module termination.
2276  *
2277  * The module termination code.
2278  */
2279 void __exit zcrypt_api_exit(void)
2280 {
2281 #ifdef CONFIG_ZCRYPT_MULTIDEVNODES
2282     zcdn_exit();
2283 #endif
2284     misc_deregister(&zcrypt_misc_device);
2285     zcrypt_msgtype6_exit();
2286     zcrypt_msgtype50_exit();
2287     zcrypt_ccamisc_exit();
2288     zcrypt_ep11misc_exit();
2289     zcrypt_debug_exit();
2290 }
2291 
2292 module_init(zcrypt_api_init);
2293 module_exit(zcrypt_api_exit);