cff2eea88f98dee58d9816941c07007f109c1e07
[linux-block.git] / drivers / s390 / crypto / zcrypt_api.c
1 // SPDX-License-Identifier: GPL-2.0+
2 /*
3  *  Copyright IBM Corp. 2001, 2018
4  *  Author(s): Robert Burroughs
5  *             Eric Rossman (edrossma@us.ibm.com)
6  *             Cornelia Huck <cornelia.huck@de.ibm.com>
7  *
8  *  Hotplug & misc device support: Jochen Roehrig (roehrig@de.ibm.com)
9  *  Major cleanup & driver split: Martin Schwidefsky <schwidefsky@de.ibm.com>
10  *                                Ralph Wuerthner <rwuerthn@de.ibm.com>
11  *  MSGTYPE restruct:             Holger Dengler <hd@linux.vnet.ibm.com>
12  *  Multiple device nodes: Harald Freudenberger <freude@linux.ibm.com>
13  */
14
15 #include <linux/module.h>
16 #include <linux/init.h>
17 #include <linux/interrupt.h>
18 #include <linux/miscdevice.h>
19 #include <linux/fs.h>
20 #include <linux/compat.h>
21 #include <linux/slab.h>
22 #include <linux/atomic.h>
23 #include <linux/uaccess.h>
24 #include <linux/hw_random.h>
25 #include <linux/debugfs.h>
26 #include <linux/cdev.h>
27 #include <linux/ctype.h>
28 #include <linux/capability.h>
29 #include <asm/debug.h>
30
31 #define CREATE_TRACE_POINTS
32 #include <asm/trace/zcrypt.h>
33
34 #include "zcrypt_api.h"
35 #include "zcrypt_debug.h"
36
37 #include "zcrypt_msgtype6.h"
38 #include "zcrypt_msgtype50.h"
39 #include "zcrypt_ccamisc.h"
40 #include "zcrypt_ep11misc.h"
41
42 /*
43  * Module description.
44  */
45 MODULE_AUTHOR("IBM Corporation");
46 MODULE_DESCRIPTION("Cryptographic Coprocessor interface, " \
47                    "Copyright IBM Corp. 2001, 2012");
48 MODULE_LICENSE("GPL");
49
50 /*
51  * zcrypt tracepoint functions
52  */
53 EXPORT_TRACEPOINT_SYMBOL(s390_zcrypt_req);
54 EXPORT_TRACEPOINT_SYMBOL(s390_zcrypt_rep);
55
56 DEFINE_SPINLOCK(zcrypt_list_lock);
57 LIST_HEAD(zcrypt_card_list);
58
59 static atomic_t zcrypt_open_count = ATOMIC_INIT(0);
60 static atomic_t zcrypt_rescan_count = ATOMIC_INIT(0);
61
62 atomic_t zcrypt_rescan_req = ATOMIC_INIT(0);
63 EXPORT_SYMBOL(zcrypt_rescan_req);
64
65 static LIST_HEAD(zcrypt_ops_list);
66
67 /* Zcrypt related debug feature stuff. */
68 debug_info_t *zcrypt_dbf_info;
69
70 /*
71  * Process a rescan of the transport layer.
72  *
73  * Returns 1, if the rescan has been processed, otherwise 0.
74  */
75 static inline int zcrypt_process_rescan(void)
76 {
77         if (atomic_read(&zcrypt_rescan_req)) {
78                 atomic_set(&zcrypt_rescan_req, 0);
79                 atomic_inc(&zcrypt_rescan_count);
80                 ap_bus_force_rescan();
81                 ZCRYPT_DBF_INFO("%s rescan count=%07d\n", __func__,
82                                 atomic_inc_return(&zcrypt_rescan_count));
83                 return 1;
84         }
85         return 0;
86 }
87
88 void zcrypt_msgtype_register(struct zcrypt_ops *zops)
89 {
90         list_add_tail(&zops->list, &zcrypt_ops_list);
91 }
92
93 void zcrypt_msgtype_unregister(struct zcrypt_ops *zops)
94 {
95         list_del_init(&zops->list);
96 }
97
98 struct zcrypt_ops *zcrypt_msgtype(unsigned char *name, int variant)
99 {
100         struct zcrypt_ops *zops;
101
102         list_for_each_entry(zops, &zcrypt_ops_list, list)
103                 if (zops->variant == variant &&
104                     (!strncmp(zops->name, name, sizeof(zops->name))))
105                         return zops;
106         return NULL;
107 }
108 EXPORT_SYMBOL(zcrypt_msgtype);
109
110 /*
111  * Multi device nodes extension functions.
112  */
113
114 #ifdef CONFIG_ZCRYPT_MULTIDEVNODES
115
116 struct zcdn_device;
117
118 static struct class *zcrypt_class;
119 static dev_t zcrypt_devt;
120 static struct cdev zcrypt_cdev;
121
122 struct zcdn_device {
123         struct device device;
124         struct ap_perms perms;
125 };
126
127 #define to_zcdn_dev(x) container_of((x), struct zcdn_device, device)
128
129 #define ZCDN_MAX_NAME 32
130
131 static int zcdn_create(const char *name);
132 static int zcdn_destroy(const char *name);
133
134 /*
135  * Find zcdn device by name.
136  * Returns reference to the zcdn device which needs to be released
137  * with put_device() after use.
138  */
139 static inline struct zcdn_device *find_zcdndev_by_name(const char *name)
140 {
141         struct device *dev = class_find_device_by_name(zcrypt_class, name);
142
143         return dev ? to_zcdn_dev(dev) : NULL;
144 }
145
146 /*
147  * Find zcdn device by devt value.
148  * Returns reference to the zcdn device which needs to be released
149  * with put_device() after use.
150  */
151 static inline struct zcdn_device *find_zcdndev_by_devt(dev_t devt)
152 {
153         struct device *dev = class_find_device_by_devt(zcrypt_class, devt);
154
155         return dev ? to_zcdn_dev(dev) : NULL;
156 }
157
158 static ssize_t ioctlmask_show(struct device *dev,
159                               struct device_attribute *attr,
160                               char *buf)
161 {
162         int i, rc;
163         struct zcdn_device *zcdndev = to_zcdn_dev(dev);
164
165         if (mutex_lock_interruptible(&ap_perms_mutex))
166                 return -ERESTARTSYS;
167
168         buf[0] = '0';
169         buf[1] = 'x';
170         for (i = 0; i < sizeof(zcdndev->perms.ioctlm) / sizeof(long); i++)
171                 snprintf(buf + 2 + 2 * i * sizeof(long),
172                          PAGE_SIZE - 2 - 2 * i * sizeof(long),
173                          "%016lx", zcdndev->perms.ioctlm[i]);
174         buf[2 + 2 * i * sizeof(long)] = '\n';
175         buf[2 + 2 * i * sizeof(long) + 1] = '\0';
176         rc = 2 + 2 * i * sizeof(long) + 1;
177
178         mutex_unlock(&ap_perms_mutex);
179
180         return rc;
181 }
182
183 static ssize_t ioctlmask_store(struct device *dev,
184                                struct device_attribute *attr,
185                                const char *buf, size_t count)
186 {
187         int rc;
188         struct zcdn_device *zcdndev = to_zcdn_dev(dev);
189
190         rc = ap_parse_mask_str(buf, zcdndev->perms.ioctlm,
191                                AP_IOCTLS, &ap_perms_mutex);
192         if (rc)
193                 return rc;
194
195         return count;
196 }
197
198 static DEVICE_ATTR_RW(ioctlmask);
199
200 static ssize_t apmask_show(struct device *dev,
201                            struct device_attribute *attr,
202                            char *buf)
203 {
204         int i, rc;
205         struct zcdn_device *zcdndev = to_zcdn_dev(dev);
206
207         if (mutex_lock_interruptible(&ap_perms_mutex))
208                 return -ERESTARTSYS;
209
210         buf[0] = '0';
211         buf[1] = 'x';
212         for (i = 0; i < sizeof(zcdndev->perms.apm) / sizeof(long); i++)
213                 snprintf(buf + 2 + 2 * i * sizeof(long),
214                          PAGE_SIZE - 2 - 2 * i * sizeof(long),
215                          "%016lx", zcdndev->perms.apm[i]);
216         buf[2 + 2 * i * sizeof(long)] = '\n';
217         buf[2 + 2 * i * sizeof(long) + 1] = '\0';
218         rc = 2 + 2 * i * sizeof(long) + 1;
219
220         mutex_unlock(&ap_perms_mutex);
221
222         return rc;
223 }
224
225 static ssize_t apmask_store(struct device *dev,
226                             struct device_attribute *attr,
227                             const char *buf, size_t count)
228 {
229         int rc;
230         struct zcdn_device *zcdndev = to_zcdn_dev(dev);
231
232         rc = ap_parse_mask_str(buf, zcdndev->perms.apm,
233                                AP_DEVICES, &ap_perms_mutex);
234         if (rc)
235                 return rc;
236
237         return count;
238 }
239
240 static DEVICE_ATTR_RW(apmask);
241
242 static ssize_t aqmask_show(struct device *dev,
243                            struct device_attribute *attr,
244                            char *buf)
245 {
246         int i, rc;
247         struct zcdn_device *zcdndev = to_zcdn_dev(dev);
248
249         if (mutex_lock_interruptible(&ap_perms_mutex))
250                 return -ERESTARTSYS;
251
252         buf[0] = '0';
253         buf[1] = 'x';
254         for (i = 0; i < sizeof(zcdndev->perms.aqm) / sizeof(long); i++)
255                 snprintf(buf + 2 + 2 * i * sizeof(long),
256                          PAGE_SIZE - 2 - 2 * i * sizeof(long),
257                          "%016lx", zcdndev->perms.aqm[i]);
258         buf[2 + 2 * i * sizeof(long)] = '\n';
259         buf[2 + 2 * i * sizeof(long) + 1] = '\0';
260         rc = 2 + 2 * i * sizeof(long) + 1;
261
262         mutex_unlock(&ap_perms_mutex);
263
264         return rc;
265 }
266
267 static ssize_t aqmask_store(struct device *dev,
268                             struct device_attribute *attr,
269                             const char *buf, size_t count)
270 {
271         int rc;
272         struct zcdn_device *zcdndev = to_zcdn_dev(dev);
273
274         rc = ap_parse_mask_str(buf, zcdndev->perms.aqm,
275                                AP_DOMAINS, &ap_perms_mutex);
276         if (rc)
277                 return rc;
278
279         return count;
280 }
281
282 static DEVICE_ATTR_RW(aqmask);
283
284 static ssize_t admask_show(struct device *dev,
285                            struct device_attribute *attr,
286                            char *buf)
287 {
288         int i, rc;
289         struct zcdn_device *zcdndev = to_zcdn_dev(dev);
290
291         if (mutex_lock_interruptible(&ap_perms_mutex))
292                 return -ERESTARTSYS;
293
294         buf[0] = '0';
295         buf[1] = 'x';
296         for (i = 0; i < sizeof(zcdndev->perms.adm) / sizeof(long); i++)
297                 snprintf(buf + 2 + 2 * i * sizeof(long),
298                          PAGE_SIZE - 2 - 2 * i * sizeof(long),
299                          "%016lx", zcdndev->perms.adm[i]);
300         buf[2 + 2 * i * sizeof(long)] = '\n';
301         buf[2 + 2 * i * sizeof(long) + 1] = '\0';
302         rc = 2 + 2 * i * sizeof(long) + 1;
303
304         mutex_unlock(&ap_perms_mutex);
305
306         return rc;
307 }
308
309 static ssize_t admask_store(struct device *dev,
310                             struct device_attribute *attr,
311                             const char *buf, size_t count)
312 {
313         int rc;
314         struct zcdn_device *zcdndev = to_zcdn_dev(dev);
315
316         rc = ap_parse_mask_str(buf, zcdndev->perms.adm,
317                                AP_DOMAINS, &ap_perms_mutex);
318         if (rc)
319                 return rc;
320
321         return count;
322 }
323
324 static DEVICE_ATTR_RW(admask);
325
326 static struct attribute *zcdn_dev_attrs[] = {
327         &dev_attr_ioctlmask.attr,
328         &dev_attr_apmask.attr,
329         &dev_attr_aqmask.attr,
330         &dev_attr_admask.attr,
331         NULL
332 };
333
334 static struct attribute_group zcdn_dev_attr_group = {
335         .attrs = zcdn_dev_attrs
336 };
337
338 static const struct attribute_group *zcdn_dev_attr_groups[] = {
339         &zcdn_dev_attr_group,
340         NULL
341 };
342
343 static ssize_t zcdn_create_store(const struct class *class,
344                                  const struct class_attribute *attr,
345                                  const char *buf, size_t count)
346 {
347         int rc;
348         char name[ZCDN_MAX_NAME];
349
350         strscpy(name, skip_spaces(buf), sizeof(name));
351
352         rc = zcdn_create(strim(name));
353
354         return rc ? rc : count;
355 }
356
357 static const struct class_attribute class_attr_zcdn_create =
358         __ATTR(create, 0600, NULL, zcdn_create_store);
359
360 static ssize_t zcdn_destroy_store(const struct class *class,
361                                   const struct class_attribute *attr,
362                                   const char *buf, size_t count)
363 {
364         int rc;
365         char name[ZCDN_MAX_NAME];
366
367         strscpy(name, skip_spaces(buf), sizeof(name));
368
369         rc = zcdn_destroy(strim(name));
370
371         return rc ? rc : count;
372 }
373
374 static const struct class_attribute class_attr_zcdn_destroy =
375         __ATTR(destroy, 0600, NULL, zcdn_destroy_store);
376
377 static void zcdn_device_release(struct device *dev)
378 {
379         struct zcdn_device *zcdndev = to_zcdn_dev(dev);
380
381         ZCRYPT_DBF_INFO("%s releasing zcdn device %d:%d\n",
382                         __func__, MAJOR(dev->devt), MINOR(dev->devt));
383
384         kfree(zcdndev);
385 }
386
387 static int zcdn_create(const char *name)
388 {
389         dev_t devt;
390         int i, rc = 0;
391         char nodename[ZCDN_MAX_NAME];
392         struct zcdn_device *zcdndev;
393
394         if (mutex_lock_interruptible(&ap_perms_mutex))
395                 return -ERESTARTSYS;
396
397         /* check if device node with this name already exists */
398         if (name[0]) {
399                 zcdndev = find_zcdndev_by_name(name);
400                 if (zcdndev) {
401                         put_device(&zcdndev->device);
402                         rc = -EEXIST;
403                         goto unlockout;
404                 }
405         }
406
407         /* find an unused minor number */
408         for (i = 0; i < ZCRYPT_MAX_MINOR_NODES; i++) {
409                 devt = MKDEV(MAJOR(zcrypt_devt), MINOR(zcrypt_devt) + i);
410                 zcdndev = find_zcdndev_by_devt(devt);
411                 if (zcdndev)
412                         put_device(&zcdndev->device);
413                 else
414                         break;
415         }
416         if (i == ZCRYPT_MAX_MINOR_NODES) {
417                 rc = -ENOSPC;
418                 goto unlockout;
419         }
420
421         /* alloc and prepare a new zcdn device */
422         zcdndev = kzalloc(sizeof(*zcdndev), GFP_KERNEL);
423         if (!zcdndev) {
424                 rc = -ENOMEM;
425                 goto unlockout;
426         }
427         zcdndev->device.release = zcdn_device_release;
428         zcdndev->device.class = zcrypt_class;
429         zcdndev->device.devt = devt;
430         zcdndev->device.groups = zcdn_dev_attr_groups;
431         if (name[0])
432                 strncpy(nodename, name, sizeof(nodename));
433         else
434                 snprintf(nodename, sizeof(nodename),
435                          ZCRYPT_NAME "_%d", (int)MINOR(devt));
436         nodename[sizeof(nodename) - 1] = '\0';
437         if (dev_set_name(&zcdndev->device, nodename)) {
438                 rc = -EINVAL;
439                 goto unlockout;
440         }
441         rc = device_register(&zcdndev->device);
442         if (rc) {
443                 put_device(&zcdndev->device);
444                 goto unlockout;
445         }
446
447         ZCRYPT_DBF_INFO("%s created zcdn device %d:%d\n",
448                         __func__, MAJOR(devt), MINOR(devt));
449
450 unlockout:
451         mutex_unlock(&ap_perms_mutex);
452         return rc;
453 }
454
455 static int zcdn_destroy(const char *name)
456 {
457         int rc = 0;
458         struct zcdn_device *zcdndev;
459
460         if (mutex_lock_interruptible(&ap_perms_mutex))
461                 return -ERESTARTSYS;
462
463         /* try to find this zcdn device */
464         zcdndev = find_zcdndev_by_name(name);
465         if (!zcdndev) {
466                 rc = -ENOENT;
467                 goto unlockout;
468         }
469
470         /*
471          * The zcdn device is not hard destroyed. It is subject to
472          * reference counting and thus just needs to be unregistered.
473          */
474         put_device(&zcdndev->device);
475         device_unregister(&zcdndev->device);
476
477 unlockout:
478         mutex_unlock(&ap_perms_mutex);
479         return rc;
480 }
481
482 static void zcdn_destroy_all(void)
483 {
484         int i;
485         dev_t devt;
486         struct zcdn_device *zcdndev;
487
488         mutex_lock(&ap_perms_mutex);
489         for (i = 0; i < ZCRYPT_MAX_MINOR_NODES; i++) {
490                 devt = MKDEV(MAJOR(zcrypt_devt), MINOR(zcrypt_devt) + i);
491                 zcdndev = find_zcdndev_by_devt(devt);
492                 if (zcdndev) {
493                         put_device(&zcdndev->device);
494                         device_unregister(&zcdndev->device);
495                 }
496         }
497         mutex_unlock(&ap_perms_mutex);
498 }
499
500 #endif
501
502 /*
503  * zcrypt_read (): Not supported beyond zcrypt 1.3.1.
504  *
505  * This function is not supported beyond zcrypt 1.3.1.
506  */
507 static ssize_t zcrypt_read(struct file *filp, char __user *buf,
508                            size_t count, loff_t *f_pos)
509 {
510         return -EPERM;
511 }
512
513 /*
514  * zcrypt_write(): Not allowed.
515  *
516  * Write is not allowed
517  */
518 static ssize_t zcrypt_write(struct file *filp, const char __user *buf,
519                             size_t count, loff_t *f_pos)
520 {
521         return -EPERM;
522 }
523
524 /*
525  * zcrypt_open(): Count number of users.
526  *
527  * Device open function to count number of users.
528  */
529 static int zcrypt_open(struct inode *inode, struct file *filp)
530 {
531         struct ap_perms *perms = &ap_perms;
532
533 #ifdef CONFIG_ZCRYPT_MULTIDEVNODES
534         if (filp->f_inode->i_cdev == &zcrypt_cdev) {
535                 struct zcdn_device *zcdndev;
536
537                 if (mutex_lock_interruptible(&ap_perms_mutex))
538                         return -ERESTARTSYS;
539                 zcdndev = find_zcdndev_by_devt(filp->f_inode->i_rdev);
540                 /* find returns a reference, no get_device() needed */
541                 mutex_unlock(&ap_perms_mutex);
542                 if (zcdndev)
543                         perms = &zcdndev->perms;
544         }
545 #endif
546         filp->private_data = (void *)perms;
547
548         atomic_inc(&zcrypt_open_count);
549         return stream_open(inode, filp);
550 }
551
552 /*
553  * zcrypt_release(): Count number of users.
554  *
555  * Device close function to count number of users.
556  */
557 static int zcrypt_release(struct inode *inode, struct file *filp)
558 {
559 #ifdef CONFIG_ZCRYPT_MULTIDEVNODES
560         if (filp->f_inode->i_cdev == &zcrypt_cdev) {
561                 struct zcdn_device *zcdndev;
562
563                 mutex_lock(&ap_perms_mutex);
564                 zcdndev = find_zcdndev_by_devt(filp->f_inode->i_rdev);
565                 mutex_unlock(&ap_perms_mutex);
566                 if (zcdndev) {
567                         /* 2 puts here: one for find, one for open */
568                         put_device(&zcdndev->device);
569                         put_device(&zcdndev->device);
570                 }
571         }
572 #endif
573
574         atomic_dec(&zcrypt_open_count);
575         return 0;
576 }
577
578 static inline int zcrypt_check_ioctl(struct ap_perms *perms,
579                                      unsigned int cmd)
580 {
581         int rc = -EPERM;
582         int ioctlnr = (cmd & _IOC_NRMASK) >> _IOC_NRSHIFT;
583
584         if (ioctlnr > 0 && ioctlnr < AP_IOCTLS) {
585                 if (test_bit_inv(ioctlnr, perms->ioctlm))
586                         rc = 0;
587         }
588
589         if (rc)
590                 ZCRYPT_DBF_WARN("%s ioctl check failed: ioctlnr=0x%04x rc=%d\n",
591                                 __func__, ioctlnr, rc);
592
593         return rc;
594 }
595
596 static inline bool zcrypt_check_card(struct ap_perms *perms, int card)
597 {
598         return test_bit_inv(card, perms->apm) ? true : false;
599 }
600
601 static inline bool zcrypt_check_queue(struct ap_perms *perms, int queue)
602 {
603         return test_bit_inv(queue, perms->aqm) ? true : false;
604 }
605
606 static inline struct zcrypt_queue *zcrypt_pick_queue(struct zcrypt_card *zc,
607                                                      struct zcrypt_queue *zq,
608                                                      struct module **pmod,
609                                                      unsigned int weight)
610 {
611         if (!zq || !try_module_get(zq->queue->ap_dev.device.driver->owner))
612                 return NULL;
613         zcrypt_queue_get(zq);
614         get_device(&zq->queue->ap_dev.device);
615         atomic_add(weight, &zc->load);
616         atomic_add(weight, &zq->load);
617         zq->request_count++;
618         *pmod = zq->queue->ap_dev.device.driver->owner;
619         return zq;
620 }
621
622 static inline void zcrypt_drop_queue(struct zcrypt_card *zc,
623                                      struct zcrypt_queue *zq,
624                                      struct module *mod,
625                                      unsigned int weight)
626 {
627         zq->request_count--;
628         atomic_sub(weight, &zc->load);
629         atomic_sub(weight, &zq->load);
630         put_device(&zq->queue->ap_dev.device);
631         zcrypt_queue_put(zq);
632         module_put(mod);
633 }
634
635 static inline bool zcrypt_card_compare(struct zcrypt_card *zc,
636                                        struct zcrypt_card *pref_zc,
637                                        unsigned int weight,
638                                        unsigned int pref_weight)
639 {
640         if (!pref_zc)
641                 return true;
642         weight += atomic_read(&zc->load);
643         pref_weight += atomic_read(&pref_zc->load);
644         if (weight == pref_weight)
645                 return atomic64_read(&zc->card->total_request_count) <
646                         atomic64_read(&pref_zc->card->total_request_count);
647         return weight < pref_weight;
648 }
649
650 static inline bool zcrypt_queue_compare(struct zcrypt_queue *zq,
651                                         struct zcrypt_queue *pref_zq,
652                                         unsigned int weight,
653                                         unsigned int pref_weight)
654 {
655         if (!pref_zq)
656                 return true;
657         weight += atomic_read(&zq->load);
658         pref_weight += atomic_read(&pref_zq->load);
659         if (weight == pref_weight)
660                 return zq->queue->total_request_count <
661                         pref_zq->queue->total_request_count;
662         return weight < pref_weight;
663 }
664
665 /*
666  * zcrypt ioctls.
667  */
668 static long zcrypt_rsa_modexpo(struct ap_perms *perms,
669                                struct zcrypt_track *tr,
670                                struct ica_rsa_modexpo *mex)
671 {
672         struct zcrypt_card *zc, *pref_zc;
673         struct zcrypt_queue *zq, *pref_zq;
674         struct ap_message ap_msg;
675         unsigned int wgt = 0, pref_wgt = 0;
676         unsigned int func_code;
677         int cpen, qpen, qid = 0, rc = -ENODEV;
678         struct module *mod;
679
680         trace_s390_zcrypt_req(mex, TP_ICARSAMODEXPO);
681
682         ap_init_message(&ap_msg);
683
684 #ifdef CONFIG_ZCRYPT_DEBUG
685         if (tr && tr->fi.cmd)
686                 ap_msg.fi.cmd = tr->fi.cmd;
687 #endif
688
689         if (mex->outputdatalength < mex->inputdatalength) {
690                 func_code = 0;
691                 rc = -EINVAL;
692                 goto out;
693         }
694
695         /*
696          * As long as outputdatalength is big enough, we can set the
697          * outputdatalength equal to the inputdatalength, since that is the
698          * number of bytes we will copy in any case
699          */
700         mex->outputdatalength = mex->inputdatalength;
701
702         rc = get_rsa_modex_fc(mex, &func_code);
703         if (rc)
704                 goto out;
705
706         pref_zc = NULL;
707         pref_zq = NULL;
708         spin_lock(&zcrypt_list_lock);
709         for_each_zcrypt_card(zc) {
710                 /* Check for usable accelarator or CCA card */
711                 if (!zc->online || !zc->card->config || zc->card->chkstop ||
712                     !(zc->card->functions & 0x18000000))
713                         continue;
714                 /* Check for size limits */
715                 if (zc->min_mod_size > mex->inputdatalength ||
716                     zc->max_mod_size < mex->inputdatalength)
717                         continue;
718                 /* check if device node has admission for this card */
719                 if (!zcrypt_check_card(perms, zc->card->id))
720                         continue;
721                 /* get weight index of the card device  */
722                 wgt = zc->speed_rating[func_code];
723                 /* penalty if this msg was previously sent via this card */
724                 cpen = (tr && tr->again_counter && tr->last_qid &&
725                         AP_QID_CARD(tr->last_qid) == zc->card->id) ?
726                         TRACK_AGAIN_CARD_WEIGHT_PENALTY : 0;
727                 if (!zcrypt_card_compare(zc, pref_zc, wgt + cpen, pref_wgt))
728                         continue;
729                 for_each_zcrypt_queue(zq, zc) {
730                         /* check if device is usable and eligible */
731                         if (!zq->online || !zq->ops->rsa_modexpo ||
732                             !zq->queue->config || zq->queue->chkstop)
733                                 continue;
734                         /* check if device node has admission for this queue */
735                         if (!zcrypt_check_queue(perms,
736                                                 AP_QID_QUEUE(zq->queue->qid)))
737                                 continue;
738                         /* penalty if the msg was previously sent at this qid */
739                         qpen = (tr && tr->again_counter && tr->last_qid &&
740                                 tr->last_qid == zq->queue->qid) ?
741                                 TRACK_AGAIN_QUEUE_WEIGHT_PENALTY : 0;
742                         if (!zcrypt_queue_compare(zq, pref_zq,
743                                                   wgt + cpen + qpen, pref_wgt))
744                                 continue;
745                         pref_zc = zc;
746                         pref_zq = zq;
747                         pref_wgt = wgt + cpen + qpen;
748                 }
749         }
750         pref_zq = zcrypt_pick_queue(pref_zc, pref_zq, &mod, wgt);
751         spin_unlock(&zcrypt_list_lock);
752
753         if (!pref_zq) {
754                 ZCRYPT_DBF_DBG("%s no matching queue found => ENODEV\n",
755                                __func__);
756                 rc = -ENODEV;
757                 goto out;
758         }
759
760         qid = pref_zq->queue->qid;
761         rc = pref_zq->ops->rsa_modexpo(pref_zq, mex, &ap_msg);
762
763         spin_lock(&zcrypt_list_lock);
764         zcrypt_drop_queue(pref_zc, pref_zq, mod, wgt);
765         spin_unlock(&zcrypt_list_lock);
766
767 out:
768         ap_release_message(&ap_msg);
769         if (tr) {
770                 tr->last_rc = rc;
771                 tr->last_qid = qid;
772         }
773         trace_s390_zcrypt_rep(mex, func_code, rc,
774                               AP_QID_CARD(qid), AP_QID_QUEUE(qid));
775         return rc;
776 }
777
778 static long zcrypt_rsa_crt(struct ap_perms *perms,
779                            struct zcrypt_track *tr,
780                            struct ica_rsa_modexpo_crt *crt)
781 {
782         struct zcrypt_card *zc, *pref_zc;
783         struct zcrypt_queue *zq, *pref_zq;
784         struct ap_message ap_msg;
785         unsigned int wgt = 0, pref_wgt = 0;
786         unsigned int func_code;
787         int cpen, qpen, qid = 0, rc = -ENODEV;
788         struct module *mod;
789
790         trace_s390_zcrypt_req(crt, TP_ICARSACRT);
791
792         ap_init_message(&ap_msg);
793
794 #ifdef CONFIG_ZCRYPT_DEBUG
795         if (tr && tr->fi.cmd)
796                 ap_msg.fi.cmd = tr->fi.cmd;
797 #endif
798
799         if (crt->outputdatalength < crt->inputdatalength) {
800                 func_code = 0;
801                 rc = -EINVAL;
802                 goto out;
803         }
804
805         /*
806          * As long as outputdatalength is big enough, we can set the
807          * outputdatalength equal to the inputdatalength, since that is the
808          * number of bytes we will copy in any case
809          */
810         crt->outputdatalength = crt->inputdatalength;
811
812         rc = get_rsa_crt_fc(crt, &func_code);
813         if (rc)
814                 goto out;
815
816         pref_zc = NULL;
817         pref_zq = NULL;
818         spin_lock(&zcrypt_list_lock);
819         for_each_zcrypt_card(zc) {
820                 /* Check for usable accelarator or CCA card */
821                 if (!zc->online || !zc->card->config || zc->card->chkstop ||
822                     !(zc->card->functions & 0x18000000))
823                         continue;
824                 /* Check for size limits */
825                 if (zc->min_mod_size > crt->inputdatalength ||
826                     zc->max_mod_size < crt->inputdatalength)
827                         continue;
828                 /* check if device node has admission for this card */
829                 if (!zcrypt_check_card(perms, zc->card->id))
830                         continue;
831                 /* get weight index of the card device  */
832                 wgt = zc->speed_rating[func_code];
833                 /* penalty if this msg was previously sent via this card */
834                 cpen = (tr && tr->again_counter && tr->last_qid &&
835                         AP_QID_CARD(tr->last_qid) == zc->card->id) ?
836                         TRACK_AGAIN_CARD_WEIGHT_PENALTY : 0;
837                 if (!zcrypt_card_compare(zc, pref_zc, wgt + cpen, pref_wgt))
838                         continue;
839                 for_each_zcrypt_queue(zq, zc) {
840                         /* check if device is usable and eligible */
841                         if (!zq->online || !zq->ops->rsa_modexpo_crt ||
842                             !zq->queue->config || zq->queue->chkstop)
843                                 continue;
844                         /* check if device node has admission for this queue */
845                         if (!zcrypt_check_queue(perms,
846                                                 AP_QID_QUEUE(zq->queue->qid)))
847                                 continue;
848                         /* penalty if the msg was previously sent at this qid */
849                         qpen = (tr && tr->again_counter && tr->last_qid &&
850                                 tr->last_qid == zq->queue->qid) ?
851                                 TRACK_AGAIN_QUEUE_WEIGHT_PENALTY : 0;
852                         if (!zcrypt_queue_compare(zq, pref_zq,
853                                                   wgt + cpen + qpen, pref_wgt))
854                                 continue;
855                         pref_zc = zc;
856                         pref_zq = zq;
857                         pref_wgt = wgt + cpen + qpen;
858                 }
859         }
860         pref_zq = zcrypt_pick_queue(pref_zc, pref_zq, &mod, wgt);
861         spin_unlock(&zcrypt_list_lock);
862
863         if (!pref_zq) {
864                 ZCRYPT_DBF_DBG("%s no matching queue found => ENODEV\n",
865                                __func__);
866                 rc = -ENODEV;
867                 goto out;
868         }
869
870         qid = pref_zq->queue->qid;
871         rc = pref_zq->ops->rsa_modexpo_crt(pref_zq, crt, &ap_msg);
872
873         spin_lock(&zcrypt_list_lock);
874         zcrypt_drop_queue(pref_zc, pref_zq, mod, wgt);
875         spin_unlock(&zcrypt_list_lock);
876
877 out:
878         ap_release_message(&ap_msg);
879         if (tr) {
880                 tr->last_rc = rc;
881                 tr->last_qid = qid;
882         }
883         trace_s390_zcrypt_rep(crt, func_code, rc,
884                               AP_QID_CARD(qid), AP_QID_QUEUE(qid));
885         return rc;
886 }
887
888 static long _zcrypt_send_cprb(bool userspace, struct ap_perms *perms,
889                               struct zcrypt_track *tr,
890                               struct ica_xcRB *xcrb)
891 {
892         struct zcrypt_card *zc, *pref_zc;
893         struct zcrypt_queue *zq, *pref_zq;
894         struct ap_message ap_msg;
895         unsigned int wgt = 0, pref_wgt = 0;
896         unsigned int func_code;
897         unsigned short *domain, tdom;
898         int cpen, qpen, qid = 0, rc = -ENODEV;
899         struct module *mod;
900
901         trace_s390_zcrypt_req(xcrb, TB_ZSECSENDCPRB);
902
903         xcrb->status = 0;
904         ap_init_message(&ap_msg);
905
906 #ifdef CONFIG_ZCRYPT_DEBUG
907         if (tr && tr->fi.cmd)
908                 ap_msg.fi.cmd = tr->fi.cmd;
909         if (tr && tr->fi.action == AP_FI_ACTION_CCA_AGENT_FF) {
910                 ZCRYPT_DBF_WARN("%s fi cmd 0x%04x: forcing invalid agent_ID 'FF'\n",
911                                 __func__, tr->fi.cmd);
912                 xcrb->agent_ID = 0x4646;
913         }
914 #endif
915
916         rc = prep_cca_ap_msg(userspace, xcrb, &ap_msg, &func_code, &domain);
917         if (rc)
918                 goto out;
919
920         tdom = *domain;
921         if (perms != &ap_perms && tdom < AP_DOMAINS) {
922                 if (ap_msg.flags & AP_MSG_FLAG_ADMIN) {
923                         if (!test_bit_inv(tdom, perms->adm)) {
924                                 rc = -ENODEV;
925                                 goto out;
926                         }
927                 } else if ((ap_msg.flags & AP_MSG_FLAG_USAGE) == 0) {
928                         rc = -EOPNOTSUPP;
929                         goto out;
930                 }
931         }
932         /*
933          * If a valid target domain is set and this domain is NOT a usage
934          * domain but a control only domain, autoselect target domain.
935          */
936         if (tdom < AP_DOMAINS &&
937             !ap_test_config_usage_domain(tdom) &&
938             ap_test_config_ctrl_domain(tdom))
939                 tdom = AUTOSEL_DOM;
940
941         pref_zc = NULL;
942         pref_zq = NULL;
943         spin_lock(&zcrypt_list_lock);
944         for_each_zcrypt_card(zc) {
945                 /* Check for usable CCA card */
946                 if (!zc->online || !zc->card->config || zc->card->chkstop ||
947                     !(zc->card->functions & 0x10000000))
948                         continue;
949                 /* Check for user selected CCA card */
950                 if (xcrb->user_defined != AUTOSELECT &&
951                     xcrb->user_defined != zc->card->id)
952                         continue;
953                 /* check if request size exceeds card max msg size */
954                 if (ap_msg.len > zc->card->maxmsgsize)
955                         continue;
956                 /* check if device node has admission for this card */
957                 if (!zcrypt_check_card(perms, zc->card->id))
958                         continue;
959                 /* get weight index of the card device  */
960                 wgt = speed_idx_cca(func_code) * zc->speed_rating[SECKEY];
961                 /* penalty if this msg was previously sent via this card */
962                 cpen = (tr && tr->again_counter && tr->last_qid &&
963                         AP_QID_CARD(tr->last_qid) == zc->card->id) ?
964                         TRACK_AGAIN_CARD_WEIGHT_PENALTY : 0;
965                 if (!zcrypt_card_compare(zc, pref_zc, wgt + cpen, pref_wgt))
966                         continue;
967                 for_each_zcrypt_queue(zq, zc) {
968                         /* check for device usable and eligible */
969                         if (!zq->online || !zq->ops->send_cprb ||
970                             !zq->queue->config || zq->queue->chkstop ||
971                             (tdom != AUTOSEL_DOM &&
972                              tdom != AP_QID_QUEUE(zq->queue->qid)))
973                                 continue;
974                         /* check if device node has admission for this queue */
975                         if (!zcrypt_check_queue(perms,
976                                                 AP_QID_QUEUE(zq->queue->qid)))
977                                 continue;
978                         /* penalty if the msg was previously sent at this qid */
979                         qpen = (tr && tr->again_counter && tr->last_qid &&
980                                 tr->last_qid == zq->queue->qid) ?
981                                 TRACK_AGAIN_QUEUE_WEIGHT_PENALTY : 0;
982                         if (!zcrypt_queue_compare(zq, pref_zq,
983                                                   wgt + cpen + qpen, pref_wgt))
984                                 continue;
985                         pref_zc = zc;
986                         pref_zq = zq;
987                         pref_wgt = wgt + cpen + qpen;
988                 }
989         }
990         pref_zq = zcrypt_pick_queue(pref_zc, pref_zq, &mod, wgt);
991         spin_unlock(&zcrypt_list_lock);
992
993         if (!pref_zq) {
994                 ZCRYPT_DBF_DBG("%s no match for address %02x.%04x => ENODEV\n",
995                                __func__, xcrb->user_defined, *domain);
996                 rc = -ENODEV;
997                 goto out;
998         }
999
1000         /* in case of auto select, provide the correct domain */
1001         qid = pref_zq->queue->qid;
1002         if (*domain == AUTOSEL_DOM)
1003                 *domain = AP_QID_QUEUE(qid);
1004
1005 #ifdef CONFIG_ZCRYPT_DEBUG
1006         if (tr && tr->fi.action == AP_FI_ACTION_CCA_DOM_INVAL) {
1007                 ZCRYPT_DBF_WARN("%s fi cmd 0x%04x: forcing invalid domain\n",
1008                                 __func__, tr->fi.cmd);
1009                 *domain = 99;
1010         }
1011 #endif
1012
1013         rc = pref_zq->ops->send_cprb(userspace, pref_zq, xcrb, &ap_msg);
1014
1015         spin_lock(&zcrypt_list_lock);
1016         zcrypt_drop_queue(pref_zc, pref_zq, mod, wgt);
1017         spin_unlock(&zcrypt_list_lock);
1018
1019 out:
1020         ap_release_message(&ap_msg);
1021         if (tr) {
1022                 tr->last_rc = rc;
1023                 tr->last_qid = qid;
1024         }
1025         trace_s390_zcrypt_rep(xcrb, func_code, rc,
1026                               AP_QID_CARD(qid), AP_QID_QUEUE(qid));
1027         return rc;
1028 }
1029
1030 long zcrypt_send_cprb(struct ica_xcRB *xcrb)
1031 {
1032         return _zcrypt_send_cprb(false, &ap_perms, NULL, xcrb);
1033 }
1034 EXPORT_SYMBOL(zcrypt_send_cprb);
1035
1036 static bool is_desired_ep11_card(unsigned int dev_id,
1037                                  unsigned short target_num,
1038                                  struct ep11_target_dev *targets)
1039 {
1040         while (target_num-- > 0) {
1041                 if (targets->ap_id == dev_id || targets->ap_id == AUTOSEL_AP)
1042                         return true;
1043                 targets++;
1044         }
1045         return false;
1046 }
1047
1048 static bool is_desired_ep11_queue(unsigned int dev_qid,
1049                                   unsigned short target_num,
1050                                   struct ep11_target_dev *targets)
1051 {
1052         int card = AP_QID_CARD(dev_qid), dom = AP_QID_QUEUE(dev_qid);
1053
1054         while (target_num-- > 0) {
1055                 if ((targets->ap_id == card || targets->ap_id == AUTOSEL_AP) &&
1056                     (targets->dom_id == dom || targets->dom_id == AUTOSEL_DOM))
1057                         return true;
1058                 targets++;
1059         }
1060         return false;
1061 }
1062
1063 static long _zcrypt_send_ep11_cprb(bool userspace, struct ap_perms *perms,
1064                                    struct zcrypt_track *tr,
1065                                    struct ep11_urb *xcrb)
1066 {
1067         struct zcrypt_card *zc, *pref_zc;
1068         struct zcrypt_queue *zq, *pref_zq;
1069         struct ep11_target_dev *targets;
1070         unsigned short target_num;
1071         unsigned int wgt = 0, pref_wgt = 0;
1072         unsigned int func_code, domain;
1073         struct ap_message ap_msg;
1074         int cpen, qpen, qid = 0, rc = -ENODEV;
1075         struct module *mod;
1076
1077         trace_s390_zcrypt_req(xcrb, TP_ZSENDEP11CPRB);
1078
1079         ap_init_message(&ap_msg);
1080
1081 #ifdef CONFIG_ZCRYPT_DEBUG
1082         if (tr && tr->fi.cmd)
1083                 ap_msg.fi.cmd = tr->fi.cmd;
1084 #endif
1085
1086         target_num = (unsigned short)xcrb->targets_num;
1087
1088         /* empty list indicates autoselect (all available targets) */
1089         targets = NULL;
1090         if (target_num != 0) {
1091                 struct ep11_target_dev __user *uptr;
1092
1093                 targets = kcalloc(target_num, sizeof(*targets), GFP_KERNEL);
1094                 if (!targets) {
1095                         func_code = 0;
1096                         rc = -ENOMEM;
1097                         goto out;
1098                 }
1099
1100                 uptr = (struct ep11_target_dev __force __user *)xcrb->targets;
1101                 if (z_copy_from_user(userspace, targets, uptr,
1102                                      target_num * sizeof(*targets))) {
1103                         func_code = 0;
1104                         rc = -EFAULT;
1105                         goto out_free;
1106                 }
1107         }
1108
1109         rc = prep_ep11_ap_msg(userspace, xcrb, &ap_msg, &func_code, &domain);
1110         if (rc)
1111                 goto out_free;
1112
1113         if (perms != &ap_perms && domain < AUTOSEL_DOM) {
1114                 if (ap_msg.flags & AP_MSG_FLAG_ADMIN) {
1115                         if (!test_bit_inv(domain, perms->adm)) {
1116                                 rc = -ENODEV;
1117                                 goto out_free;
1118                         }
1119                 } else if ((ap_msg.flags & AP_MSG_FLAG_USAGE) == 0) {
1120                         rc = -EOPNOTSUPP;
1121                         goto out_free;
1122                 }
1123         }
1124
1125         pref_zc = NULL;
1126         pref_zq = NULL;
1127         spin_lock(&zcrypt_list_lock);
1128         for_each_zcrypt_card(zc) {
1129                 /* Check for usable EP11 card */
1130                 if (!zc->online || !zc->card->config || zc->card->chkstop ||
1131                     !(zc->card->functions & 0x04000000))
1132                         continue;
1133                 /* Check for user selected EP11 card */
1134                 if (targets &&
1135                     !is_desired_ep11_card(zc->card->id, target_num, targets))
1136                         continue;
1137                 /* check if request size exceeds card max msg size */
1138                 if (ap_msg.len > zc->card->maxmsgsize)
1139                         continue;
1140                 /* check if device node has admission for this card */
1141                 if (!zcrypt_check_card(perms, zc->card->id))
1142                         continue;
1143                 /* get weight index of the card device  */
1144                 wgt = speed_idx_ep11(func_code) * zc->speed_rating[SECKEY];
1145                 /* penalty if this msg was previously sent via this card */
1146                 cpen = (tr && tr->again_counter && tr->last_qid &&
1147                         AP_QID_CARD(tr->last_qid) == zc->card->id) ?
1148                         TRACK_AGAIN_CARD_WEIGHT_PENALTY : 0;
1149                 if (!zcrypt_card_compare(zc, pref_zc, wgt + cpen, pref_wgt))
1150                         continue;
1151                 for_each_zcrypt_queue(zq, zc) {
1152                         /* check if device is usable and eligible */
1153                         if (!zq->online || !zq->ops->send_ep11_cprb ||
1154                             !zq->queue->config || zq->queue->chkstop ||
1155                             (targets &&
1156                              !is_desired_ep11_queue(zq->queue->qid,
1157                                                     target_num, targets)))
1158                                 continue;
1159                         /* check if device node has admission for this queue */
1160                         if (!zcrypt_check_queue(perms,
1161                                                 AP_QID_QUEUE(zq->queue->qid)))
1162                                 continue;
1163                         /* penalty if the msg was previously sent at this qid */
1164                         qpen = (tr && tr->again_counter && tr->last_qid &&
1165                                 tr->last_qid == zq->queue->qid) ?
1166                                 TRACK_AGAIN_QUEUE_WEIGHT_PENALTY : 0;
1167                         if (!zcrypt_queue_compare(zq, pref_zq,
1168                                                   wgt + cpen + qpen, pref_wgt))
1169                                 continue;
1170                         pref_zc = zc;
1171                         pref_zq = zq;
1172                         pref_wgt = wgt + cpen + qpen;
1173                 }
1174         }
1175         pref_zq = zcrypt_pick_queue(pref_zc, pref_zq, &mod, wgt);
1176         spin_unlock(&zcrypt_list_lock);
1177
1178         if (!pref_zq) {
1179                 if (targets && target_num == 1) {
1180                         ZCRYPT_DBF_DBG("%s no match for address %02x.%04x => ENODEV\n",
1181                                        __func__, (int)targets->ap_id,
1182                                        (int)targets->dom_id);
1183                 } else if (targets) {
1184                         ZCRYPT_DBF_DBG("%s no match for %d target addrs => ENODEV\n",
1185                                        __func__, (int)target_num);
1186                 } else {
1187                         ZCRYPT_DBF_DBG("%s no match for address ff.ffff => ENODEV\n",
1188                                        __func__);
1189                 }
1190                 rc = -ENODEV;
1191                 goto out_free;
1192         }
1193
1194         qid = pref_zq->queue->qid;
1195         rc = pref_zq->ops->send_ep11_cprb(userspace, pref_zq, xcrb, &ap_msg);
1196
1197         spin_lock(&zcrypt_list_lock);
1198         zcrypt_drop_queue(pref_zc, pref_zq, mod, wgt);
1199         spin_unlock(&zcrypt_list_lock);
1200
1201 out_free:
1202         kfree(targets);
1203 out:
1204         ap_release_message(&ap_msg);
1205         if (tr) {
1206                 tr->last_rc = rc;
1207                 tr->last_qid = qid;
1208         }
1209         trace_s390_zcrypt_rep(xcrb, func_code, rc,
1210                               AP_QID_CARD(qid), AP_QID_QUEUE(qid));
1211         return rc;
1212 }
1213
1214 long zcrypt_send_ep11_cprb(struct ep11_urb *xcrb)
1215 {
1216         return _zcrypt_send_ep11_cprb(false, &ap_perms, NULL, xcrb);
1217 }
1218 EXPORT_SYMBOL(zcrypt_send_ep11_cprb);
1219
1220 static long zcrypt_rng(char *buffer)
1221 {
1222         struct zcrypt_card *zc, *pref_zc;
1223         struct zcrypt_queue *zq, *pref_zq;
1224         unsigned int wgt = 0, pref_wgt = 0;
1225         unsigned int func_code;
1226         struct ap_message ap_msg;
1227         unsigned int domain;
1228         int qid = 0, rc = -ENODEV;
1229         struct module *mod;
1230
1231         trace_s390_zcrypt_req(buffer, TP_HWRNGCPRB);
1232
1233         ap_init_message(&ap_msg);
1234         rc = prep_rng_ap_msg(&ap_msg, &func_code, &domain);
1235         if (rc)
1236                 goto out;
1237
1238         pref_zc = NULL;
1239         pref_zq = NULL;
1240         spin_lock(&zcrypt_list_lock);
1241         for_each_zcrypt_card(zc) {
1242                 /* Check for usable CCA card */
1243                 if (!zc->online || !zc->card->config || zc->card->chkstop ||
1244                     !(zc->card->functions & 0x10000000))
1245                         continue;
1246                 /* get weight index of the card device  */
1247                 wgt = zc->speed_rating[func_code];
1248                 if (!zcrypt_card_compare(zc, pref_zc, wgt, pref_wgt))
1249                         continue;
1250                 for_each_zcrypt_queue(zq, zc) {
1251                         /* check if device is usable and eligible */
1252                         if (!zq->online || !zq->ops->rng ||
1253                             !zq->queue->config || zq->queue->chkstop)
1254                                 continue;
1255                         if (!zcrypt_queue_compare(zq, pref_zq, wgt, pref_wgt))
1256                                 continue;
1257                         pref_zc = zc;
1258                         pref_zq = zq;
1259                         pref_wgt = wgt;
1260                 }
1261         }
1262         pref_zq = zcrypt_pick_queue(pref_zc, pref_zq, &mod, wgt);
1263         spin_unlock(&zcrypt_list_lock);
1264
1265         if (!pref_zq) {
1266                 ZCRYPT_DBF_DBG("%s no matching queue found => ENODEV\n",
1267                                __func__);
1268                 rc = -ENODEV;
1269                 goto out;
1270         }
1271
1272         qid = pref_zq->queue->qid;
1273         rc = pref_zq->ops->rng(pref_zq, buffer, &ap_msg);
1274
1275         spin_lock(&zcrypt_list_lock);
1276         zcrypt_drop_queue(pref_zc, pref_zq, mod, wgt);
1277         spin_unlock(&zcrypt_list_lock);
1278
1279 out:
1280         ap_release_message(&ap_msg);
1281         trace_s390_zcrypt_rep(buffer, func_code, rc,
1282                               AP_QID_CARD(qid), AP_QID_QUEUE(qid));
1283         return rc;
1284 }
1285
1286 static void zcrypt_device_status_mask(struct zcrypt_device_status *devstatus)
1287 {
1288         struct zcrypt_card *zc;
1289         struct zcrypt_queue *zq;
1290         struct zcrypt_device_status *stat;
1291         int card, queue;
1292
1293         memset(devstatus, 0, MAX_ZDEV_ENTRIES
1294                * sizeof(struct zcrypt_device_status));
1295
1296         spin_lock(&zcrypt_list_lock);
1297         for_each_zcrypt_card(zc) {
1298                 for_each_zcrypt_queue(zq, zc) {
1299                         card = AP_QID_CARD(zq->queue->qid);
1300                         if (card >= MAX_ZDEV_CARDIDS)
1301                                 continue;
1302                         queue = AP_QID_QUEUE(zq->queue->qid);
1303                         stat = &devstatus[card * AP_DOMAINS + queue];
1304                         stat->hwtype = zc->card->ap_dev.device_type;
1305                         stat->functions = zc->card->functions >> 26;
1306                         stat->qid = zq->queue->qid;
1307                         stat->online = zq->online ? 0x01 : 0x00;
1308                 }
1309         }
1310         spin_unlock(&zcrypt_list_lock);
1311 }
1312
1313 void zcrypt_device_status_mask_ext(struct zcrypt_device_status_ext *devstatus)
1314 {
1315         struct zcrypt_card *zc;
1316         struct zcrypt_queue *zq;
1317         struct zcrypt_device_status_ext *stat;
1318         int card, queue;
1319
1320         memset(devstatus, 0, MAX_ZDEV_ENTRIES_EXT
1321                * sizeof(struct zcrypt_device_status_ext));
1322
1323         spin_lock(&zcrypt_list_lock);
1324         for_each_zcrypt_card(zc) {
1325                 for_each_zcrypt_queue(zq, zc) {
1326                         card = AP_QID_CARD(zq->queue->qid);
1327                         queue = AP_QID_QUEUE(zq->queue->qid);
1328                         stat = &devstatus[card * AP_DOMAINS + queue];
1329                         stat->hwtype = zc->card->ap_dev.device_type;
1330                         stat->functions = zc->card->functions >> 26;
1331                         stat->qid = zq->queue->qid;
1332                         stat->online = zq->online ? 0x01 : 0x00;
1333                 }
1334         }
1335         spin_unlock(&zcrypt_list_lock);
1336 }
1337 EXPORT_SYMBOL(zcrypt_device_status_mask_ext);
1338
1339 int zcrypt_device_status_ext(int card, int queue,
1340                              struct zcrypt_device_status_ext *devstat)
1341 {
1342         struct zcrypt_card *zc;
1343         struct zcrypt_queue *zq;
1344
1345         memset(devstat, 0, sizeof(*devstat));
1346
1347         spin_lock(&zcrypt_list_lock);
1348         for_each_zcrypt_card(zc) {
1349                 for_each_zcrypt_queue(zq, zc) {
1350                         if (card == AP_QID_CARD(zq->queue->qid) &&
1351                             queue == AP_QID_QUEUE(zq->queue->qid)) {
1352                                 devstat->hwtype = zc->card->ap_dev.device_type;
1353                                 devstat->functions = zc->card->functions >> 26;
1354                                 devstat->qid = zq->queue->qid;
1355                                 devstat->online = zq->online ? 0x01 : 0x00;
1356                                 spin_unlock(&zcrypt_list_lock);
1357                                 return 0;
1358                         }
1359                 }
1360         }
1361         spin_unlock(&zcrypt_list_lock);
1362
1363         return -ENODEV;
1364 }
1365 EXPORT_SYMBOL(zcrypt_device_status_ext);
1366
1367 static void zcrypt_status_mask(char status[], size_t max_adapters)
1368 {
1369         struct zcrypt_card *zc;
1370         struct zcrypt_queue *zq;
1371         int card;
1372
1373         memset(status, 0, max_adapters);
1374         spin_lock(&zcrypt_list_lock);
1375         for_each_zcrypt_card(zc) {
1376                 for_each_zcrypt_queue(zq, zc) {
1377                         card = AP_QID_CARD(zq->queue->qid);
1378                         if (AP_QID_QUEUE(zq->queue->qid) != ap_domain_index ||
1379                             card >= max_adapters)
1380                                 continue;
1381                         status[card] = zc->online ? zc->user_space_type : 0x0d;
1382                 }
1383         }
1384         spin_unlock(&zcrypt_list_lock);
1385 }
1386
1387 static void zcrypt_qdepth_mask(char qdepth[], size_t max_adapters)
1388 {
1389         struct zcrypt_card *zc;
1390         struct zcrypt_queue *zq;
1391         int card;
1392
1393         memset(qdepth, 0, max_adapters);
1394         spin_lock(&zcrypt_list_lock);
1395         local_bh_disable();
1396         for_each_zcrypt_card(zc) {
1397                 for_each_zcrypt_queue(zq, zc) {
1398                         card = AP_QID_CARD(zq->queue->qid);
1399                         if (AP_QID_QUEUE(zq->queue->qid) != ap_domain_index ||
1400                             card >= max_adapters)
1401                                 continue;
1402                         spin_lock(&zq->queue->lock);
1403                         qdepth[card] =
1404                                 zq->queue->pendingq_count +
1405                                 zq->queue->requestq_count;
1406                         spin_unlock(&zq->queue->lock);
1407                 }
1408         }
1409         local_bh_enable();
1410         spin_unlock(&zcrypt_list_lock);
1411 }
1412
1413 static void zcrypt_perdev_reqcnt(u32 reqcnt[], size_t max_adapters)
1414 {
1415         struct zcrypt_card *zc;
1416         struct zcrypt_queue *zq;
1417         int card;
1418         u64 cnt;
1419
1420         memset(reqcnt, 0, sizeof(int) * max_adapters);
1421         spin_lock(&zcrypt_list_lock);
1422         local_bh_disable();
1423         for_each_zcrypt_card(zc) {
1424                 for_each_zcrypt_queue(zq, zc) {
1425                         card = AP_QID_CARD(zq->queue->qid);
1426                         if (AP_QID_QUEUE(zq->queue->qid) != ap_domain_index ||
1427                             card >= max_adapters)
1428                                 continue;
1429                         spin_lock(&zq->queue->lock);
1430                         cnt = zq->queue->total_request_count;
1431                         spin_unlock(&zq->queue->lock);
1432                         reqcnt[card] = (cnt < UINT_MAX) ? (u32)cnt : UINT_MAX;
1433                 }
1434         }
1435         local_bh_enable();
1436         spin_unlock(&zcrypt_list_lock);
1437 }
1438
1439 static int zcrypt_pendingq_count(void)
1440 {
1441         struct zcrypt_card *zc;
1442         struct zcrypt_queue *zq;
1443         int pendingq_count;
1444
1445         pendingq_count = 0;
1446         spin_lock(&zcrypt_list_lock);
1447         local_bh_disable();
1448         for_each_zcrypt_card(zc) {
1449                 for_each_zcrypt_queue(zq, zc) {
1450                         if (AP_QID_QUEUE(zq->queue->qid) != ap_domain_index)
1451                                 continue;
1452                         spin_lock(&zq->queue->lock);
1453                         pendingq_count += zq->queue->pendingq_count;
1454                         spin_unlock(&zq->queue->lock);
1455                 }
1456         }
1457         local_bh_enable();
1458         spin_unlock(&zcrypt_list_lock);
1459         return pendingq_count;
1460 }
1461
1462 static int zcrypt_requestq_count(void)
1463 {
1464         struct zcrypt_card *zc;
1465         struct zcrypt_queue *zq;
1466         int requestq_count;
1467
1468         requestq_count = 0;
1469         spin_lock(&zcrypt_list_lock);
1470         local_bh_disable();
1471         for_each_zcrypt_card(zc) {
1472                 for_each_zcrypt_queue(zq, zc) {
1473                         if (AP_QID_QUEUE(zq->queue->qid) != ap_domain_index)
1474                                 continue;
1475                         spin_lock(&zq->queue->lock);
1476                         requestq_count += zq->queue->requestq_count;
1477                         spin_unlock(&zq->queue->lock);
1478                 }
1479         }
1480         local_bh_enable();
1481         spin_unlock(&zcrypt_list_lock);
1482         return requestq_count;
1483 }
1484
1485 static int icarsamodexpo_ioctl(struct ap_perms *perms, unsigned long arg)
1486 {
1487         int rc;
1488         struct zcrypt_track tr;
1489         struct ica_rsa_modexpo mex;
1490         struct ica_rsa_modexpo __user *umex = (void __user *)arg;
1491
1492         memset(&tr, 0, sizeof(tr));
1493         if (copy_from_user(&mex, umex, sizeof(mex)))
1494                 return -EFAULT;
1495
1496 #ifdef CONFIG_ZCRYPT_DEBUG
1497         if (mex.inputdatalength & (1U << 31)) {
1498                 if (!capable(CAP_SYS_ADMIN))
1499                         return -EPERM;
1500                 tr.fi.cmd = (u16)(mex.inputdatalength >> 16);
1501         }
1502         mex.inputdatalength &= 0x0000FFFF;
1503 #endif
1504
1505         do {
1506                 rc = zcrypt_rsa_modexpo(perms, &tr, &mex);
1507                 if (rc == -EAGAIN)
1508                         tr.again_counter++;
1509 #ifdef CONFIG_ZCRYPT_DEBUG
1510                 if (rc == -EAGAIN && (tr.fi.flags & AP_FI_FLAG_NO_RETRY))
1511                         break;
1512 #endif
1513         } while (rc == -EAGAIN && tr.again_counter < TRACK_AGAIN_MAX);
1514         /* on failure: retry once again after a requested rescan */
1515         if ((rc == -ENODEV) && (zcrypt_process_rescan()))
1516                 do {
1517                         rc = zcrypt_rsa_modexpo(perms, &tr, &mex);
1518                         if (rc == -EAGAIN)
1519                                 tr.again_counter++;
1520                 } while (rc == -EAGAIN && tr.again_counter < TRACK_AGAIN_MAX);
1521         if (rc == -EAGAIN && tr.again_counter >= TRACK_AGAIN_MAX)
1522                 rc = -EIO;
1523         if (rc) {
1524                 ZCRYPT_DBF_DBG("ioctl ICARSAMODEXPO rc=%d\n", rc);
1525                 return rc;
1526         }
1527         return put_user(mex.outputdatalength, &umex->outputdatalength);
1528 }
1529
1530 static int icarsacrt_ioctl(struct ap_perms *perms, unsigned long arg)
1531 {
1532         int rc;
1533         struct zcrypt_track tr;
1534         struct ica_rsa_modexpo_crt crt;
1535         struct ica_rsa_modexpo_crt __user *ucrt = (void __user *)arg;
1536
1537         memset(&tr, 0, sizeof(tr));
1538         if (copy_from_user(&crt, ucrt, sizeof(crt)))
1539                 return -EFAULT;
1540
1541 #ifdef CONFIG_ZCRYPT_DEBUG
1542         if (crt.inputdatalength & (1U << 31)) {
1543                 if (!capable(CAP_SYS_ADMIN))
1544                         return -EPERM;
1545                 tr.fi.cmd = (u16)(crt.inputdatalength >> 16);
1546         }
1547         crt.inputdatalength &= 0x0000FFFF;
1548 #endif
1549
1550         do {
1551                 rc = zcrypt_rsa_crt(perms, &tr, &crt);
1552                 if (rc == -EAGAIN)
1553                         tr.again_counter++;
1554 #ifdef CONFIG_ZCRYPT_DEBUG
1555                 if (rc == -EAGAIN && (tr.fi.flags & AP_FI_FLAG_NO_RETRY))
1556                         break;
1557 #endif
1558         } while (rc == -EAGAIN && tr.again_counter < TRACK_AGAIN_MAX);
1559         /* on failure: retry once again after a requested rescan */
1560         if ((rc == -ENODEV) && (zcrypt_process_rescan()))
1561                 do {
1562                         rc = zcrypt_rsa_crt(perms, &tr, &crt);
1563                         if (rc == -EAGAIN)
1564                                 tr.again_counter++;
1565                 } while (rc == -EAGAIN && tr.again_counter < TRACK_AGAIN_MAX);
1566         if (rc == -EAGAIN && tr.again_counter >= TRACK_AGAIN_MAX)
1567                 rc = -EIO;
1568         if (rc) {
1569                 ZCRYPT_DBF_DBG("ioctl ICARSACRT rc=%d\n", rc);
1570                 return rc;
1571         }
1572         return put_user(crt.outputdatalength, &ucrt->outputdatalength);
1573 }
1574
1575 static int zsecsendcprb_ioctl(struct ap_perms *perms, unsigned long arg)
1576 {
1577         int rc;
1578         struct ica_xcRB xcrb;
1579         struct zcrypt_track tr;
1580         struct ica_xcRB __user *uxcrb = (void __user *)arg;
1581
1582         memset(&tr, 0, sizeof(tr));
1583         if (copy_from_user(&xcrb, uxcrb, sizeof(xcrb)))
1584                 return -EFAULT;
1585
1586 #ifdef CONFIG_ZCRYPT_DEBUG
1587         if ((xcrb.status & 0x8000FFFF) == 0x80004649 /* 'FI' */) {
1588                 if (!capable(CAP_SYS_ADMIN))
1589                         return -EPERM;
1590                 tr.fi.cmd = (u16)(xcrb.status >> 16);
1591         }
1592         xcrb.status = 0;
1593 #endif
1594
1595         do {
1596                 rc = _zcrypt_send_cprb(true, perms, &tr, &xcrb);
1597                 if (rc == -EAGAIN)
1598                         tr.again_counter++;
1599 #ifdef CONFIG_ZCRYPT_DEBUG
1600                 if (rc == -EAGAIN && (tr.fi.flags & AP_FI_FLAG_NO_RETRY))
1601                         break;
1602 #endif
1603         } while (rc == -EAGAIN && tr.again_counter < TRACK_AGAIN_MAX);
1604         /* on failure: retry once again after a requested rescan */
1605         if ((rc == -ENODEV) && (zcrypt_process_rescan()))
1606                 do {
1607                         rc = _zcrypt_send_cprb(true, perms, &tr, &xcrb);
1608                         if (rc == -EAGAIN)
1609                                 tr.again_counter++;
1610                 } while (rc == -EAGAIN && tr.again_counter < TRACK_AGAIN_MAX);
1611         if (rc == -EAGAIN && tr.again_counter >= TRACK_AGAIN_MAX)
1612                 rc = -EIO;
1613         if (rc)
1614                 ZCRYPT_DBF_DBG("ioctl ZSENDCPRB rc=%d status=0x%x\n",
1615                                rc, xcrb.status);
1616         if (copy_to_user(uxcrb, &xcrb, sizeof(xcrb)))
1617                 return -EFAULT;
1618         return rc;
1619 }
1620
1621 static int zsendep11cprb_ioctl(struct ap_perms *perms, unsigned long arg)
1622 {
1623         int rc;
1624         struct ep11_urb xcrb;
1625         struct zcrypt_track tr;
1626         struct ep11_urb __user *uxcrb = (void __user *)arg;
1627
1628         memset(&tr, 0, sizeof(tr));
1629         if (copy_from_user(&xcrb, uxcrb, sizeof(xcrb)))
1630                 return -EFAULT;
1631
1632 #ifdef CONFIG_ZCRYPT_DEBUG
1633         if (xcrb.req_len & (1ULL << 63)) {
1634                 if (!capable(CAP_SYS_ADMIN))
1635                         return -EPERM;
1636                 tr.fi.cmd = (u16)(xcrb.req_len >> 48);
1637         }
1638         xcrb.req_len &= 0x0000FFFFFFFFFFFFULL;
1639 #endif
1640
1641         do {
1642                 rc = _zcrypt_send_ep11_cprb(true, perms, &tr, &xcrb);
1643                 if (rc == -EAGAIN)
1644                         tr.again_counter++;
1645 #ifdef CONFIG_ZCRYPT_DEBUG
1646                 if (rc == -EAGAIN && (tr.fi.flags & AP_FI_FLAG_NO_RETRY))
1647                         break;
1648 #endif
1649         } while (rc == -EAGAIN && tr.again_counter < TRACK_AGAIN_MAX);
1650         /* on failure: retry once again after a requested rescan */
1651         if ((rc == -ENODEV) && (zcrypt_process_rescan()))
1652                 do {
1653                         rc = _zcrypt_send_ep11_cprb(true, perms, &tr, &xcrb);
1654                         if (rc == -EAGAIN)
1655                                 tr.again_counter++;
1656                 } while (rc == -EAGAIN && tr.again_counter < TRACK_AGAIN_MAX);
1657         if (rc == -EAGAIN && tr.again_counter >= TRACK_AGAIN_MAX)
1658                 rc = -EIO;
1659         if (rc)
1660                 ZCRYPT_DBF_DBG("ioctl ZSENDEP11CPRB rc=%d\n", rc);
1661         if (copy_to_user(uxcrb, &xcrb, sizeof(xcrb)))
1662                 return -EFAULT;
1663         return rc;
1664 }
1665
1666 static long zcrypt_unlocked_ioctl(struct file *filp, unsigned int cmd,
1667                                   unsigned long arg)
1668 {
1669         int rc;
1670         struct ap_perms *perms =
1671                 (struct ap_perms *)filp->private_data;
1672
1673         rc = zcrypt_check_ioctl(perms, cmd);
1674         if (rc)
1675                 return rc;
1676
1677         switch (cmd) {
1678         case ICARSAMODEXPO:
1679                 return icarsamodexpo_ioctl(perms, arg);
1680         case ICARSACRT:
1681                 return icarsacrt_ioctl(perms, arg);
1682         case ZSECSENDCPRB:
1683                 return zsecsendcprb_ioctl(perms, arg);
1684         case ZSENDEP11CPRB:
1685                 return zsendep11cprb_ioctl(perms, arg);
1686         case ZCRYPT_DEVICE_STATUS: {
1687                 struct zcrypt_device_status_ext *device_status;
1688                 size_t total_size = MAX_ZDEV_ENTRIES_EXT
1689                         * sizeof(struct zcrypt_device_status_ext);
1690
1691                 device_status = kzalloc(total_size, GFP_KERNEL);
1692                 if (!device_status)
1693                         return -ENOMEM;
1694                 zcrypt_device_status_mask_ext(device_status);
1695                 if (copy_to_user((char __user *)arg, device_status,
1696                                  total_size))
1697                         rc = -EFAULT;
1698                 kfree(device_status);
1699                 return rc;
1700         }
1701         case ZCRYPT_STATUS_MASK: {
1702                 char status[AP_DEVICES];
1703
1704                 zcrypt_status_mask(status, AP_DEVICES);
1705                 if (copy_to_user((char __user *)arg, status, sizeof(status)))
1706                         return -EFAULT;
1707                 return 0;
1708         }
1709         case ZCRYPT_QDEPTH_MASK: {
1710                 char qdepth[AP_DEVICES];
1711
1712                 zcrypt_qdepth_mask(qdepth, AP_DEVICES);
1713                 if (copy_to_user((char __user *)arg, qdepth, sizeof(qdepth)))
1714                         return -EFAULT;
1715                 return 0;
1716         }
1717         case ZCRYPT_PERDEV_REQCNT: {
1718                 u32 *reqcnt;
1719
1720                 reqcnt = kcalloc(AP_DEVICES, sizeof(u32), GFP_KERNEL);
1721                 if (!reqcnt)
1722                         return -ENOMEM;
1723                 zcrypt_perdev_reqcnt(reqcnt, AP_DEVICES);
1724                 if (copy_to_user((int __user *)arg, reqcnt,
1725                                  sizeof(u32) * AP_DEVICES))
1726                         rc = -EFAULT;
1727                 kfree(reqcnt);
1728                 return rc;
1729         }
1730         case Z90STAT_REQUESTQ_COUNT:
1731                 return put_user(zcrypt_requestq_count(), (int __user *)arg);
1732         case Z90STAT_PENDINGQ_COUNT:
1733                 return put_user(zcrypt_pendingq_count(), (int __user *)arg);
1734         case Z90STAT_TOTALOPEN_COUNT:
1735                 return put_user(atomic_read(&zcrypt_open_count),
1736                                 (int __user *)arg);
1737         case Z90STAT_DOMAIN_INDEX:
1738                 return put_user(ap_domain_index, (int __user *)arg);
1739         /*
1740          * Deprecated ioctls
1741          */
1742         case ZDEVICESTATUS: {
1743                 /* the old ioctl supports only 64 adapters */
1744                 struct zcrypt_device_status *device_status;
1745                 size_t total_size = MAX_ZDEV_ENTRIES
1746                         * sizeof(struct zcrypt_device_status);
1747
1748                 device_status = kzalloc(total_size, GFP_KERNEL);
1749                 if (!device_status)
1750                         return -ENOMEM;
1751                 zcrypt_device_status_mask(device_status);
1752                 if (copy_to_user((char __user *)arg, device_status,
1753                                  total_size))
1754                         rc = -EFAULT;
1755                 kfree(device_status);
1756                 return rc;
1757         }
1758         case Z90STAT_STATUS_MASK: {
1759                 /* the old ioctl supports only 64 adapters */
1760                 char status[MAX_ZDEV_CARDIDS];
1761
1762                 zcrypt_status_mask(status, MAX_ZDEV_CARDIDS);
1763                 if (copy_to_user((char __user *)arg, status, sizeof(status)))
1764                         return -EFAULT;
1765                 return 0;
1766         }
1767         case Z90STAT_QDEPTH_MASK: {
1768                 /* the old ioctl supports only 64 adapters */
1769                 char qdepth[MAX_ZDEV_CARDIDS];
1770
1771                 zcrypt_qdepth_mask(qdepth, MAX_ZDEV_CARDIDS);
1772                 if (copy_to_user((char __user *)arg, qdepth, sizeof(qdepth)))
1773                         return -EFAULT;
1774                 return 0;
1775         }
1776         case Z90STAT_PERDEV_REQCNT: {
1777                 /* the old ioctl supports only 64 adapters */
1778                 u32 reqcnt[MAX_ZDEV_CARDIDS];
1779
1780                 zcrypt_perdev_reqcnt(reqcnt, MAX_ZDEV_CARDIDS);
1781                 if (copy_to_user((int __user *)arg, reqcnt, sizeof(reqcnt)))
1782                         return -EFAULT;
1783                 return 0;
1784         }
1785         /* unknown ioctl number */
1786         default:
1787                 ZCRYPT_DBF_DBG("unknown ioctl 0x%08x\n", cmd);
1788                 return -ENOIOCTLCMD;
1789         }
1790 }
1791
1792 #ifdef CONFIG_COMPAT
1793 /*
1794  * ioctl32 conversion routines
1795  */
1796 struct compat_ica_rsa_modexpo {
1797         compat_uptr_t   inputdata;
1798         unsigned int    inputdatalength;
1799         compat_uptr_t   outputdata;
1800         unsigned int    outputdatalength;
1801         compat_uptr_t   b_key;
1802         compat_uptr_t   n_modulus;
1803 };
1804
1805 static long trans_modexpo32(struct ap_perms *perms, struct file *filp,
1806                             unsigned int cmd, unsigned long arg)
1807 {
1808         struct compat_ica_rsa_modexpo __user *umex32 = compat_ptr(arg);
1809         struct compat_ica_rsa_modexpo mex32;
1810         struct ica_rsa_modexpo mex64;
1811         struct zcrypt_track tr;
1812         long rc;
1813
1814         memset(&tr, 0, sizeof(tr));
1815         if (copy_from_user(&mex32, umex32, sizeof(mex32)))
1816                 return -EFAULT;
1817         mex64.inputdata = compat_ptr(mex32.inputdata);
1818         mex64.inputdatalength = mex32.inputdatalength;
1819         mex64.outputdata = compat_ptr(mex32.outputdata);
1820         mex64.outputdatalength = mex32.outputdatalength;
1821         mex64.b_key = compat_ptr(mex32.b_key);
1822         mex64.n_modulus = compat_ptr(mex32.n_modulus);
1823         do {
1824                 rc = zcrypt_rsa_modexpo(perms, &tr, &mex64);
1825                 if (rc == -EAGAIN)
1826                         tr.again_counter++;
1827         } while (rc == -EAGAIN && tr.again_counter < TRACK_AGAIN_MAX);
1828         /* on failure: retry once again after a requested rescan */
1829         if ((rc == -ENODEV) && (zcrypt_process_rescan()))
1830                 do {
1831                         rc = zcrypt_rsa_modexpo(perms, &tr, &mex64);
1832                         if (rc == -EAGAIN)
1833                                 tr.again_counter++;
1834                 } while (rc == -EAGAIN && tr.again_counter < TRACK_AGAIN_MAX);
1835         if (rc == -EAGAIN && tr.again_counter >= TRACK_AGAIN_MAX)
1836                 rc = -EIO;
1837         if (rc)
1838                 return rc;
1839         return put_user(mex64.outputdatalength,
1840                         &umex32->outputdatalength);
1841 }
1842
1843 struct compat_ica_rsa_modexpo_crt {
1844         compat_uptr_t   inputdata;
1845         unsigned int    inputdatalength;
1846         compat_uptr_t   outputdata;
1847         unsigned int    outputdatalength;
1848         compat_uptr_t   bp_key;
1849         compat_uptr_t   bq_key;
1850         compat_uptr_t   np_prime;
1851         compat_uptr_t   nq_prime;
1852         compat_uptr_t   u_mult_inv;
1853 };
1854
1855 static long trans_modexpo_crt32(struct ap_perms *perms, struct file *filp,
1856                                 unsigned int cmd, unsigned long arg)
1857 {
1858         struct compat_ica_rsa_modexpo_crt __user *ucrt32 = compat_ptr(arg);
1859         struct compat_ica_rsa_modexpo_crt crt32;
1860         struct ica_rsa_modexpo_crt crt64;
1861         struct zcrypt_track tr;
1862         long rc;
1863
1864         memset(&tr, 0, sizeof(tr));
1865         if (copy_from_user(&crt32, ucrt32, sizeof(crt32)))
1866                 return -EFAULT;
1867         crt64.inputdata = compat_ptr(crt32.inputdata);
1868         crt64.inputdatalength = crt32.inputdatalength;
1869         crt64.outputdata = compat_ptr(crt32.outputdata);
1870         crt64.outputdatalength = crt32.outputdatalength;
1871         crt64.bp_key = compat_ptr(crt32.bp_key);
1872         crt64.bq_key = compat_ptr(crt32.bq_key);
1873         crt64.np_prime = compat_ptr(crt32.np_prime);
1874         crt64.nq_prime = compat_ptr(crt32.nq_prime);
1875         crt64.u_mult_inv = compat_ptr(crt32.u_mult_inv);
1876         do {
1877                 rc = zcrypt_rsa_crt(perms, &tr, &crt64);
1878                 if (rc == -EAGAIN)
1879                         tr.again_counter++;
1880         } while (rc == -EAGAIN && tr.again_counter < TRACK_AGAIN_MAX);
1881         /* on failure: retry once again after a requested rescan */
1882         if ((rc == -ENODEV) && (zcrypt_process_rescan()))
1883                 do {
1884                         rc = zcrypt_rsa_crt(perms, &tr, &crt64);
1885                         if (rc == -EAGAIN)
1886                                 tr.again_counter++;
1887                 } while (rc == -EAGAIN && tr.again_counter < TRACK_AGAIN_MAX);
1888         if (rc == -EAGAIN && tr.again_counter >= TRACK_AGAIN_MAX)
1889                 rc = -EIO;
1890         if (rc)
1891                 return rc;
1892         return put_user(crt64.outputdatalength,
1893                         &ucrt32->outputdatalength);
1894 }
1895
1896 struct compat_ica_xcrb {
1897         unsigned short  agent_ID;
1898         unsigned int    user_defined;
1899         unsigned short  request_ID;
1900         unsigned int    request_control_blk_length;
1901         unsigned char   padding1[16 - sizeof(compat_uptr_t)];
1902         compat_uptr_t   request_control_blk_addr;
1903         unsigned int    request_data_length;
1904         char            padding2[16 - sizeof(compat_uptr_t)];
1905         compat_uptr_t   request_data_address;
1906         unsigned int    reply_control_blk_length;
1907         char            padding3[16 - sizeof(compat_uptr_t)];
1908         compat_uptr_t   reply_control_blk_addr;
1909         unsigned int    reply_data_length;
1910         char            padding4[16 - sizeof(compat_uptr_t)];
1911         compat_uptr_t   reply_data_addr;
1912         unsigned short  priority_window;
1913         unsigned int    status;
1914 } __packed;
1915
1916 static long trans_xcrb32(struct ap_perms *perms, struct file *filp,
1917                          unsigned int cmd, unsigned long arg)
1918 {
1919         struct compat_ica_xcrb __user *uxcrb32 = compat_ptr(arg);
1920         struct compat_ica_xcrb xcrb32;
1921         struct zcrypt_track tr;
1922         struct ica_xcRB xcrb64;
1923         long rc;
1924
1925         memset(&tr, 0, sizeof(tr));
1926         if (copy_from_user(&xcrb32, uxcrb32, sizeof(xcrb32)))
1927                 return -EFAULT;
1928         xcrb64.agent_ID = xcrb32.agent_ID;
1929         xcrb64.user_defined = xcrb32.user_defined;
1930         xcrb64.request_ID = xcrb32.request_ID;
1931         xcrb64.request_control_blk_length =
1932                 xcrb32.request_control_blk_length;
1933         xcrb64.request_control_blk_addr =
1934                 compat_ptr(xcrb32.request_control_blk_addr);
1935         xcrb64.request_data_length =
1936                 xcrb32.request_data_length;
1937         xcrb64.request_data_address =
1938                 compat_ptr(xcrb32.request_data_address);
1939         xcrb64.reply_control_blk_length =
1940                 xcrb32.reply_control_blk_length;
1941         xcrb64.reply_control_blk_addr =
1942                 compat_ptr(xcrb32.reply_control_blk_addr);
1943         xcrb64.reply_data_length = xcrb32.reply_data_length;
1944         xcrb64.reply_data_addr =
1945                 compat_ptr(xcrb32.reply_data_addr);
1946         xcrb64.priority_window = xcrb32.priority_window;
1947         xcrb64.status = xcrb32.status;
1948         do {
1949                 rc = _zcrypt_send_cprb(true, perms, &tr, &xcrb64);
1950                 if (rc == -EAGAIN)
1951                         tr.again_counter++;
1952         } while (rc == -EAGAIN && tr.again_counter < TRACK_AGAIN_MAX);
1953         /* on failure: retry once again after a requested rescan */
1954         if ((rc == -ENODEV) && (zcrypt_process_rescan()))
1955                 do {
1956                         rc = _zcrypt_send_cprb(true, perms, &tr, &xcrb64);
1957                         if (rc == -EAGAIN)
1958                                 tr.again_counter++;
1959                 } while (rc == -EAGAIN && tr.again_counter < TRACK_AGAIN_MAX);
1960         if (rc == -EAGAIN && tr.again_counter >= TRACK_AGAIN_MAX)
1961                 rc = -EIO;
1962         xcrb32.reply_control_blk_length = xcrb64.reply_control_blk_length;
1963         xcrb32.reply_data_length = xcrb64.reply_data_length;
1964         xcrb32.status = xcrb64.status;
1965         if (copy_to_user(uxcrb32, &xcrb32, sizeof(xcrb32)))
1966                 return -EFAULT;
1967         return rc;
1968 }
1969
1970 static long zcrypt_compat_ioctl(struct file *filp, unsigned int cmd,
1971                                 unsigned long arg)
1972 {
1973         int rc;
1974         struct ap_perms *perms =
1975                 (struct ap_perms *)filp->private_data;
1976
1977         rc = zcrypt_check_ioctl(perms, cmd);
1978         if (rc)
1979                 return rc;
1980
1981         if (cmd == ICARSAMODEXPO)
1982                 return trans_modexpo32(perms, filp, cmd, arg);
1983         if (cmd == ICARSACRT)
1984                 return trans_modexpo_crt32(perms, filp, cmd, arg);
1985         if (cmd == ZSECSENDCPRB)
1986                 return trans_xcrb32(perms, filp, cmd, arg);
1987         return zcrypt_unlocked_ioctl(filp, cmd, arg);
1988 }
1989 #endif
1990
1991 /*
1992  * Misc device file operations.
1993  */
1994 static const struct file_operations zcrypt_fops = {
1995         .owner          = THIS_MODULE,
1996         .read           = zcrypt_read,
1997         .write          = zcrypt_write,
1998         .unlocked_ioctl = zcrypt_unlocked_ioctl,
1999 #ifdef CONFIG_COMPAT
2000         .compat_ioctl   = zcrypt_compat_ioctl,
2001 #endif
2002         .open           = zcrypt_open,
2003         .release        = zcrypt_release,
2004         .llseek         = no_llseek,
2005 };
2006
2007 /*
2008  * Misc device.
2009  */
2010 static struct miscdevice zcrypt_misc_device = {
2011         .minor      = MISC_DYNAMIC_MINOR,
2012         .name       = "z90crypt",
2013         .fops       = &zcrypt_fops,
2014 };
2015
2016 static int zcrypt_rng_device_count;
2017 static u32 *zcrypt_rng_buffer;
2018 static int zcrypt_rng_buffer_index;
2019 static DEFINE_MUTEX(zcrypt_rng_mutex);
2020
2021 static int zcrypt_rng_data_read(struct hwrng *rng, u32 *data)
2022 {
2023         int rc;
2024
2025         /*
2026          * We don't need locking here because the RNG API guarantees serialized
2027          * read method calls.
2028          */
2029         if (zcrypt_rng_buffer_index == 0) {
2030                 rc = zcrypt_rng((char *)zcrypt_rng_buffer);
2031                 /* on failure: retry once again after a requested rescan */
2032                 if ((rc == -ENODEV) && (zcrypt_process_rescan()))
2033                         rc = zcrypt_rng((char *)zcrypt_rng_buffer);
2034                 if (rc < 0)
2035                         return -EIO;
2036                 zcrypt_rng_buffer_index = rc / sizeof(*data);
2037         }
2038         *data = zcrypt_rng_buffer[--zcrypt_rng_buffer_index];
2039         return sizeof(*data);
2040 }
2041
2042 static struct hwrng zcrypt_rng_dev = {
2043         .name           = "zcrypt",
2044         .data_read      = zcrypt_rng_data_read,
2045         .quality        = 990,
2046 };
2047
2048 int zcrypt_rng_device_add(void)
2049 {
2050         int rc = 0;
2051
2052         mutex_lock(&zcrypt_rng_mutex);
2053         if (zcrypt_rng_device_count == 0) {
2054                 zcrypt_rng_buffer = (u32 *)get_zeroed_page(GFP_KERNEL);
2055                 if (!zcrypt_rng_buffer) {
2056                         rc = -ENOMEM;
2057                         goto out;
2058                 }
2059                 zcrypt_rng_buffer_index = 0;
2060                 rc = hwrng_register(&zcrypt_rng_dev);
2061                 if (rc)
2062                         goto out_free;
2063                 zcrypt_rng_device_count = 1;
2064         } else {
2065                 zcrypt_rng_device_count++;
2066         }
2067         mutex_unlock(&zcrypt_rng_mutex);
2068         return 0;
2069
2070 out_free:
2071         free_page((unsigned long)zcrypt_rng_buffer);
2072 out:
2073         mutex_unlock(&zcrypt_rng_mutex);
2074         return rc;
2075 }
2076
2077 void zcrypt_rng_device_remove(void)
2078 {
2079         mutex_lock(&zcrypt_rng_mutex);
2080         zcrypt_rng_device_count--;
2081         if (zcrypt_rng_device_count == 0) {
2082                 hwrng_unregister(&zcrypt_rng_dev);
2083                 free_page((unsigned long)zcrypt_rng_buffer);
2084         }
2085         mutex_unlock(&zcrypt_rng_mutex);
2086 }
2087
2088 /*
2089  * Wait until the zcrypt api is operational.
2090  * The AP bus scan and the binding of ap devices to device drivers is
2091  * an asynchronous job. This function waits until these initial jobs
2092  * are done and so the zcrypt api should be ready to serve crypto
2093  * requests - if there are resources available. The function uses an
2094  * internal timeout of 60s. The very first caller will either wait for
2095  * ap bus bindings complete or the timeout happens. This state will be
2096  * remembered for further callers which will only be blocked until a
2097  * decision is made (timeout or bindings complete).
2098  * On timeout -ETIME is returned, on success the return value is 0.
2099  */
2100 int zcrypt_wait_api_operational(void)
2101 {
2102         static DEFINE_MUTEX(zcrypt_wait_api_lock);
2103         static int zcrypt_wait_api_state;
2104         int rc;
2105
2106         rc = mutex_lock_interruptible(&zcrypt_wait_api_lock);
2107         if (rc)
2108                 return rc;
2109
2110         switch (zcrypt_wait_api_state) {
2111         case 0:
2112                 /* initial state, invoke wait for the ap bus complete */
2113                 rc = ap_wait_init_apqn_bindings_complete(
2114                         msecs_to_jiffies(60 * 1000));
2115                 switch (rc) {
2116                 case 0:
2117                         /* ap bus bindings are complete */
2118                         zcrypt_wait_api_state = 1;
2119                         break;
2120                 case -EINTR:
2121                         /* interrupted, go back to caller */
2122                         break;
2123                 case -ETIME:
2124                         /* timeout */
2125                         ZCRYPT_DBF_WARN("%s ap_wait_init_apqn_bindings_complete()=ETIME\n",
2126                                         __func__);
2127                         zcrypt_wait_api_state = -ETIME;
2128                         break;
2129                 default:
2130                         /* other failure */
2131                         ZCRYPT_DBF_DBG("%s ap_wait_init_apqn_bindings_complete()=%d\n",
2132                                        __func__, rc);
2133                         break;
2134                 }
2135                 break;
2136         case 1:
2137                 /* a previous caller already found ap bus bindings complete */
2138                 rc = 0;
2139                 break;
2140         default:
2141                 /* a previous caller had timeout or other failure */
2142                 rc = zcrypt_wait_api_state;
2143                 break;
2144         }
2145
2146         mutex_unlock(&zcrypt_wait_api_lock);
2147
2148         return rc;
2149 }
2150 EXPORT_SYMBOL(zcrypt_wait_api_operational);
2151
2152 int __init zcrypt_debug_init(void)
2153 {
2154         zcrypt_dbf_info = debug_register("zcrypt", 2, 1,
2155                                          DBF_MAX_SPRINTF_ARGS * sizeof(long));
2156         debug_register_view(zcrypt_dbf_info, &debug_sprintf_view);
2157         debug_set_level(zcrypt_dbf_info, DBF_ERR);
2158
2159         return 0;
2160 }
2161
2162 void zcrypt_debug_exit(void)
2163 {
2164         debug_unregister(zcrypt_dbf_info);
2165 }
2166
2167 #ifdef CONFIG_ZCRYPT_MULTIDEVNODES
2168
2169 static int __init zcdn_init(void)
2170 {
2171         int rc;
2172
2173         /* create a new class 'zcrypt' */
2174         zcrypt_class = class_create(ZCRYPT_NAME);
2175         if (IS_ERR(zcrypt_class)) {
2176                 rc = PTR_ERR(zcrypt_class);
2177                 goto out_class_create_failed;
2178         }
2179         zcrypt_class->dev_release = zcdn_device_release;
2180
2181         /* alloc device minor range */
2182         rc = alloc_chrdev_region(&zcrypt_devt,
2183                                  0, ZCRYPT_MAX_MINOR_NODES,
2184                                  ZCRYPT_NAME);
2185         if (rc)
2186                 goto out_alloc_chrdev_failed;
2187
2188         cdev_init(&zcrypt_cdev, &zcrypt_fops);
2189         zcrypt_cdev.owner = THIS_MODULE;
2190         rc = cdev_add(&zcrypt_cdev, zcrypt_devt, ZCRYPT_MAX_MINOR_NODES);
2191         if (rc)
2192                 goto out_cdev_add_failed;
2193
2194         /* need some class specific sysfs attributes */
2195         rc = class_create_file(zcrypt_class, &class_attr_zcdn_create);
2196         if (rc)
2197                 goto out_class_create_file_1_failed;
2198         rc = class_create_file(zcrypt_class, &class_attr_zcdn_destroy);
2199         if (rc)
2200                 goto out_class_create_file_2_failed;
2201
2202         return 0;
2203
2204 out_class_create_file_2_failed:
2205         class_remove_file(zcrypt_class, &class_attr_zcdn_create);
2206 out_class_create_file_1_failed:
2207         cdev_del(&zcrypt_cdev);
2208 out_cdev_add_failed:
2209         unregister_chrdev_region(zcrypt_devt, ZCRYPT_MAX_MINOR_NODES);
2210 out_alloc_chrdev_failed:
2211         class_destroy(zcrypt_class);
2212 out_class_create_failed:
2213         return rc;
2214 }
2215
2216 static void zcdn_exit(void)
2217 {
2218         class_remove_file(zcrypt_class, &class_attr_zcdn_create);
2219         class_remove_file(zcrypt_class, &class_attr_zcdn_destroy);
2220         zcdn_destroy_all();
2221         cdev_del(&zcrypt_cdev);
2222         unregister_chrdev_region(zcrypt_devt, ZCRYPT_MAX_MINOR_NODES);
2223         class_destroy(zcrypt_class);
2224 }
2225
2226 #endif
2227
2228 /*
2229  * zcrypt_api_init(): Module initialization.
2230  *
2231  * The module initialization code.
2232  */
2233 int __init zcrypt_api_init(void)
2234 {
2235         int rc;
2236
2237         rc = zcrypt_debug_init();
2238         if (rc)
2239                 goto out;
2240
2241 #ifdef CONFIG_ZCRYPT_MULTIDEVNODES
2242         rc = zcdn_init();
2243         if (rc)
2244                 goto out;
2245 #endif
2246
2247         /* Register the request sprayer. */
2248         rc = misc_register(&zcrypt_misc_device);
2249         if (rc < 0)
2250                 goto out_misc_register_failed;
2251
2252         zcrypt_msgtype6_init();
2253         zcrypt_msgtype50_init();
2254
2255         return 0;
2256
2257 out_misc_register_failed:
2258 #ifdef CONFIG_ZCRYPT_MULTIDEVNODES
2259         zcdn_exit();
2260 #endif
2261         zcrypt_debug_exit();
2262 out:
2263         return rc;
2264 }
2265
2266 /*
2267  * zcrypt_api_exit(): Module termination.
2268  *
2269  * The module termination code.
2270  */
2271 void __exit zcrypt_api_exit(void)
2272 {
2273 #ifdef CONFIG_ZCRYPT_MULTIDEVNODES
2274         zcdn_exit();
2275 #endif
2276         misc_deregister(&zcrypt_misc_device);
2277         zcrypt_msgtype6_exit();
2278         zcrypt_msgtype50_exit();
2279         zcrypt_ccamisc_exit();
2280         zcrypt_ep11misc_exit();
2281         zcrypt_debug_exit();
2282 }
2283
2284 module_init(zcrypt_api_init);
2285 module_exit(zcrypt_api_exit);