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