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