xref: /openbmc/linux/drivers/s390/crypto/zcrypt_api.c (revision 22a41e9a5044bf3519f05b4a00e99af34bfeb40c)
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_INFO("%s rescan count=%07d\n", __func__,
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_INFO("%s releasing zcdn device %d:%d\n",
345 			__func__, 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_INFO("%s created zcdn device %d:%d\n",
411 			__func__, 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_WARN("%s ioctl check failed: ioctlnr=0x%04x rc=%d\n",
554 				__func__, ioctlnr, rc);
555 
556 	return rc;
557 }
558 
559 static inline bool zcrypt_check_card(struct ap_perms *perms, int card)
560 {
561 	return test_bit_inv(card, perms->apm) ? true : false;
562 }
563 
564 static inline bool zcrypt_check_queue(struct ap_perms *perms, int queue)
565 {
566 	return test_bit_inv(queue, perms->aqm) ? true : false;
567 }
568 
569 static inline struct zcrypt_queue *zcrypt_pick_queue(struct zcrypt_card *zc,
570 						     struct zcrypt_queue *zq,
571 						     struct module **pmod,
572 						     unsigned int weight)
573 {
574 	if (!zq || !try_module_get(zq->queue->ap_dev.device.driver->owner))
575 		return NULL;
576 	zcrypt_queue_get(zq);
577 	get_device(&zq->queue->ap_dev.device);
578 	atomic_add(weight, &zc->load);
579 	atomic_add(weight, &zq->load);
580 	zq->request_count++;
581 	*pmod = zq->queue->ap_dev.device.driver->owner;
582 	return zq;
583 }
584 
585 static inline void zcrypt_drop_queue(struct zcrypt_card *zc,
586 				     struct zcrypt_queue *zq,
587 				     struct module *mod,
588 				     unsigned int weight)
589 {
590 	zq->request_count--;
591 	atomic_sub(weight, &zc->load);
592 	atomic_sub(weight, &zq->load);
593 	put_device(&zq->queue->ap_dev.device);
594 	zcrypt_queue_put(zq);
595 	module_put(mod);
596 }
597 
598 static inline bool zcrypt_card_compare(struct zcrypt_card *zc,
599 				       struct zcrypt_card *pref_zc,
600 				       unsigned int weight,
601 				       unsigned int pref_weight)
602 {
603 	if (!pref_zc)
604 		return true;
605 	weight += atomic_read(&zc->load);
606 	pref_weight += atomic_read(&pref_zc->load);
607 	if (weight == pref_weight)
608 		return atomic64_read(&zc->card->total_request_count) <
609 			atomic64_read(&pref_zc->card->total_request_count);
610 	return weight < pref_weight;
611 }
612 
613 static inline bool zcrypt_queue_compare(struct zcrypt_queue *zq,
614 					struct zcrypt_queue *pref_zq,
615 					unsigned int weight,
616 					unsigned int pref_weight)
617 {
618 	if (!pref_zq)
619 		return true;
620 	weight += atomic_read(&zq->load);
621 	pref_weight += atomic_read(&pref_zq->load);
622 	if (weight == pref_weight)
623 		return zq->queue->total_request_count <
624 			pref_zq->queue->total_request_count;
625 	return weight < pref_weight;
626 }
627 
628 /*
629  * zcrypt ioctls.
630  */
631 static long zcrypt_rsa_modexpo(struct ap_perms *perms,
632 			       struct zcrypt_track *tr,
633 			       struct ica_rsa_modexpo *mex)
634 {
635 	struct zcrypt_card *zc, *pref_zc;
636 	struct zcrypt_queue *zq, *pref_zq;
637 	struct ap_message ap_msg;
638 	unsigned int wgt = 0, pref_wgt = 0;
639 	unsigned int func_code;
640 	int cpen, qpen, qid = 0, rc = -ENODEV;
641 	struct module *mod;
642 
643 	trace_s390_zcrypt_req(mex, TP_ICARSAMODEXPO);
644 
645 	ap_init_message(&ap_msg);
646 
647 #ifdef CONFIG_ZCRYPT_DEBUG
648 	if (tr && tr->fi.cmd)
649 		ap_msg.fi.cmd = tr->fi.cmd;
650 #endif
651 
652 	if (mex->outputdatalength < mex->inputdatalength) {
653 		func_code = 0;
654 		rc = -EINVAL;
655 		goto out;
656 	}
657 
658 	/*
659 	 * As long as outputdatalength is big enough, we can set the
660 	 * outputdatalength equal to the inputdatalength, since that is the
661 	 * number of bytes we will copy in any case
662 	 */
663 	mex->outputdatalength = mex->inputdatalength;
664 
665 	rc = get_rsa_modex_fc(mex, &func_code);
666 	if (rc)
667 		goto out;
668 
669 	pref_zc = NULL;
670 	pref_zq = NULL;
671 	spin_lock(&zcrypt_list_lock);
672 	for_each_zcrypt_card(zc) {
673 		/* Check for useable accelarator or CCA card */
674 		if (!zc->online || !zc->card->config || zc->card->chkstop ||
675 		    !(zc->card->functions & 0x18000000))
676 			continue;
677 		/* Check for size limits */
678 		if (zc->min_mod_size > mex->inputdatalength ||
679 		    zc->max_mod_size < mex->inputdatalength)
680 			continue;
681 		/* check if device node has admission for this card */
682 		if (!zcrypt_check_card(perms, zc->card->id))
683 			continue;
684 		/* get weight index of the card device	*/
685 		wgt = zc->speed_rating[func_code];
686 		/* penalty if this msg was previously sent via this card */
687 		cpen = (tr && tr->again_counter && tr->last_qid &&
688 			AP_QID_CARD(tr->last_qid) == zc->card->id) ?
689 			TRACK_AGAIN_CARD_WEIGHT_PENALTY : 0;
690 		if (!zcrypt_card_compare(zc, pref_zc, wgt + cpen, pref_wgt))
691 			continue;
692 		for_each_zcrypt_queue(zq, zc) {
693 			/* check if device is useable and eligible */
694 			if (!zq->online || !zq->ops->rsa_modexpo ||
695 			    !zq->queue->config || zq->queue->chkstop)
696 				continue;
697 			/* check if device node has admission for this queue */
698 			if (!zcrypt_check_queue(perms,
699 						AP_QID_QUEUE(zq->queue->qid)))
700 				continue;
701 			/* penalty if the msg was previously sent at this qid */
702 			qpen = (tr && tr->again_counter && tr->last_qid &&
703 				tr->last_qid == zq->queue->qid) ?
704 				TRACK_AGAIN_QUEUE_WEIGHT_PENALTY : 0;
705 			if (!zcrypt_queue_compare(zq, pref_zq,
706 						  wgt + cpen + qpen, pref_wgt))
707 				continue;
708 			pref_zc = zc;
709 			pref_zq = zq;
710 			pref_wgt = wgt + cpen + qpen;
711 		}
712 	}
713 	pref_zq = zcrypt_pick_queue(pref_zc, pref_zq, &mod, wgt);
714 	spin_unlock(&zcrypt_list_lock);
715 
716 	if (!pref_zq) {
717 		ZCRYPT_DBF_DBG("%s no matching queue found => ENODEV\n",
718 			       __func__);
719 		rc = -ENODEV;
720 		goto out;
721 	}
722 
723 	qid = pref_zq->queue->qid;
724 	rc = pref_zq->ops->rsa_modexpo(pref_zq, mex, &ap_msg);
725 
726 	spin_lock(&zcrypt_list_lock);
727 	zcrypt_drop_queue(pref_zc, pref_zq, mod, wgt);
728 	spin_unlock(&zcrypt_list_lock);
729 
730 out:
731 	ap_release_message(&ap_msg);
732 	if (tr) {
733 		tr->last_rc = rc;
734 		tr->last_qid = qid;
735 	}
736 	trace_s390_zcrypt_rep(mex, func_code, rc,
737 			      AP_QID_CARD(qid), AP_QID_QUEUE(qid));
738 	return rc;
739 }
740 
741 static long zcrypt_rsa_crt(struct ap_perms *perms,
742 			   struct zcrypt_track *tr,
743 			   struct ica_rsa_modexpo_crt *crt)
744 {
745 	struct zcrypt_card *zc, *pref_zc;
746 	struct zcrypt_queue *zq, *pref_zq;
747 	struct ap_message ap_msg;
748 	unsigned int wgt = 0, pref_wgt = 0;
749 	unsigned int func_code;
750 	int cpen, qpen, qid = 0, rc = -ENODEV;
751 	struct module *mod;
752 
753 	trace_s390_zcrypt_req(crt, TP_ICARSACRT);
754 
755 	ap_init_message(&ap_msg);
756 
757 #ifdef CONFIG_ZCRYPT_DEBUG
758 	if (tr && tr->fi.cmd)
759 		ap_msg.fi.cmd = tr->fi.cmd;
760 #endif
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 useable accelarator 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 useable 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 #ifdef CONFIG_ZCRYPT_DEBUG
870 	if (tr && tr->fi.cmd)
871 		ap_msg.fi.cmd = tr->fi.cmd;
872 	if (tr && tr->fi.action == AP_FI_ACTION_CCA_AGENT_FF) {
873 		ZCRYPT_DBF_WARN("%s fi cmd 0x%04x: forcing invalid agent_ID 'FF'\n",
874 				__func__, tr->fi.cmd);
875 		xcRB->agent_ID = 0x4646;
876 	}
877 #endif
878 
879 	rc = prep_cca_ap_msg(userspace, xcRB, &ap_msg, &func_code, &domain);
880 	if (rc)
881 		goto out;
882 
883 	/*
884 	 * If a valid target domain is set and this domain is NOT a usage
885 	 * domain but a control only domain, autoselect target domain.
886 	 */
887 	tdom = *domain;
888 	if (tdom < AP_DOMAINS &&
889 	    !ap_test_config_usage_domain(tdom) &&
890 	    ap_test_config_ctrl_domain(tdom))
891 		tdom = AUTOSEL_DOM;
892 
893 	pref_zc = NULL;
894 	pref_zq = NULL;
895 	spin_lock(&zcrypt_list_lock);
896 	for_each_zcrypt_card(zc) {
897 		/* Check for useable CCA card */
898 		if (!zc->online || !zc->card->config || zc->card->chkstop ||
899 		    !(zc->card->functions & 0x10000000))
900 			continue;
901 		/* Check for user selected CCA card */
902 		if (xcRB->user_defined != AUTOSELECT &&
903 		    xcRB->user_defined != zc->card->id)
904 			continue;
905 		/* check if request size exceeds card max msg size */
906 		if (ap_msg.len > zc->card->maxmsgsize)
907 			continue;
908 		/* check if device node has admission for this card */
909 		if (!zcrypt_check_card(perms, zc->card->id))
910 			continue;
911 		/* get weight index of the card device	*/
912 		wgt = speed_idx_cca(func_code) * zc->speed_rating[SECKEY];
913 		/* penalty if this msg was previously sent via this card */
914 		cpen = (tr && tr->again_counter && tr->last_qid &&
915 			AP_QID_CARD(tr->last_qid) == zc->card->id) ?
916 			TRACK_AGAIN_CARD_WEIGHT_PENALTY : 0;
917 		if (!zcrypt_card_compare(zc, pref_zc, wgt + cpen, pref_wgt))
918 			continue;
919 		for_each_zcrypt_queue(zq, zc) {
920 			/* check for device useable and eligible */
921 			if (!zq->online || !zq->ops->send_cprb ||
922 			    !zq->queue->config || zq->queue->chkstop ||
923 			    (tdom != AUTOSEL_DOM &&
924 			     tdom != AP_QID_QUEUE(zq->queue->qid)))
925 				continue;
926 			/* check if device node has admission for this queue */
927 			if (!zcrypt_check_queue(perms,
928 						AP_QID_QUEUE(zq->queue->qid)))
929 				continue;
930 			/* penalty if the msg was previously sent at this qid */
931 			qpen = (tr && tr->again_counter && tr->last_qid &&
932 				tr->last_qid == zq->queue->qid) ?
933 				TRACK_AGAIN_QUEUE_WEIGHT_PENALTY : 0;
934 			if (!zcrypt_queue_compare(zq, pref_zq,
935 						  wgt + cpen + qpen, pref_wgt))
936 				continue;
937 			pref_zc = zc;
938 			pref_zq = zq;
939 			pref_wgt = wgt + cpen + qpen;
940 		}
941 	}
942 	pref_zq = zcrypt_pick_queue(pref_zc, pref_zq, &mod, wgt);
943 	spin_unlock(&zcrypt_list_lock);
944 
945 	if (!pref_zq) {
946 		ZCRYPT_DBF_DBG("%s no match for address %02x.%04x => ENODEV\n",
947 			       __func__, xcRB->user_defined, *domain);
948 		rc = -ENODEV;
949 		goto out;
950 	}
951 
952 	/* in case of auto select, provide the correct domain */
953 	qid = pref_zq->queue->qid;
954 	if (*domain == AUTOSEL_DOM)
955 		*domain = AP_QID_QUEUE(qid);
956 
957 #ifdef CONFIG_ZCRYPT_DEBUG
958 	if (tr && tr->fi.action == AP_FI_ACTION_CCA_DOM_INVAL) {
959 		ZCRYPT_DBF_WARN("%s fi cmd 0x%04x: forcing invalid domain\n",
960 				__func__, tr->fi.cmd);
961 		*domain = 99;
962 	}
963 #endif
964 
965 	rc = pref_zq->ops->send_cprb(userspace, pref_zq, xcRB, &ap_msg);
966 
967 	spin_lock(&zcrypt_list_lock);
968 	zcrypt_drop_queue(pref_zc, pref_zq, mod, wgt);
969 	spin_unlock(&zcrypt_list_lock);
970 
971 out:
972 	ap_release_message(&ap_msg);
973 	if (tr) {
974 		tr->last_rc = rc;
975 		tr->last_qid = qid;
976 	}
977 	trace_s390_zcrypt_rep(xcRB, func_code, rc,
978 			      AP_QID_CARD(qid), AP_QID_QUEUE(qid));
979 	return rc;
980 }
981 
982 long zcrypt_send_cprb(struct ica_xcRB *xcRB)
983 {
984 	return _zcrypt_send_cprb(false, &ap_perms, NULL, xcRB);
985 }
986 EXPORT_SYMBOL(zcrypt_send_cprb);
987 
988 static bool is_desired_ep11_card(unsigned int dev_id,
989 				 unsigned short target_num,
990 				 struct ep11_target_dev *targets)
991 {
992 	while (target_num-- > 0) {
993 		if (targets->ap_id == dev_id || targets->ap_id == AUTOSEL_AP)
994 			return true;
995 		targets++;
996 	}
997 	return false;
998 }
999 
1000 static bool is_desired_ep11_queue(unsigned int dev_qid,
1001 				  unsigned short target_num,
1002 				  struct ep11_target_dev *targets)
1003 {
1004 	int card = AP_QID_CARD(dev_qid), dom = AP_QID_QUEUE(dev_qid);
1005 
1006 	while (target_num-- > 0) {
1007 		if ((targets->ap_id == card || targets->ap_id == AUTOSEL_AP) &&
1008 		    (targets->dom_id == dom || targets->dom_id == AUTOSEL_DOM))
1009 			return true;
1010 		targets++;
1011 	}
1012 	return false;
1013 }
1014 
1015 static long _zcrypt_send_ep11_cprb(bool userspace, struct ap_perms *perms,
1016 				   struct zcrypt_track *tr,
1017 				   struct ep11_urb *xcrb)
1018 {
1019 	struct zcrypt_card *zc, *pref_zc;
1020 	struct zcrypt_queue *zq, *pref_zq;
1021 	struct ep11_target_dev *targets;
1022 	unsigned short target_num;
1023 	unsigned int wgt = 0, pref_wgt = 0;
1024 	unsigned int func_code, domain;
1025 	struct ap_message ap_msg;
1026 	int cpen, qpen, qid = 0, rc = -ENODEV;
1027 	struct module *mod;
1028 
1029 	trace_s390_zcrypt_req(xcrb, TP_ZSENDEP11CPRB);
1030 
1031 	ap_init_message(&ap_msg);
1032 
1033 #ifdef CONFIG_ZCRYPT_DEBUG
1034 	if (tr && tr->fi.cmd)
1035 		ap_msg.fi.cmd = tr->fi.cmd;
1036 #endif
1037 
1038 	target_num = (unsigned short) xcrb->targets_num;
1039 
1040 	/* empty list indicates autoselect (all available targets) */
1041 	targets = NULL;
1042 	if (target_num != 0) {
1043 		struct ep11_target_dev __user *uptr;
1044 
1045 		targets = kcalloc(target_num, sizeof(*targets), GFP_KERNEL);
1046 		if (!targets) {
1047 			func_code = 0;
1048 			rc = -ENOMEM;
1049 			goto out;
1050 		}
1051 
1052 		uptr = (struct ep11_target_dev __force __user *) xcrb->targets;
1053 		if (z_copy_from_user(userspace, targets, uptr,
1054 				   target_num * sizeof(*targets))) {
1055 			func_code = 0;
1056 			rc = -EFAULT;
1057 			goto out_free;
1058 		}
1059 	}
1060 
1061 	rc = prep_ep11_ap_msg(userspace, xcrb, &ap_msg, &func_code, &domain);
1062 	if (rc)
1063 		goto out_free;
1064 
1065 	pref_zc = NULL;
1066 	pref_zq = NULL;
1067 	spin_lock(&zcrypt_list_lock);
1068 	for_each_zcrypt_card(zc) {
1069 		/* Check for useable 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 useable 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 useable 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 useable 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 #ifdef CONFIG_ZCRYPT_DEBUG
1437 	if (mex.inputdatalength & (1U << 31)) {
1438 		if (!capable(CAP_SYS_ADMIN))
1439 			return -EPERM;
1440 		tr.fi.cmd = (u16)(mex.inputdatalength >> 16);
1441 	}
1442 	mex.inputdatalength &= 0x0000FFFF;
1443 #endif
1444 
1445 	do {
1446 		rc = zcrypt_rsa_modexpo(perms, &tr, &mex);
1447 		if (rc == -EAGAIN)
1448 			tr.again_counter++;
1449 #ifdef CONFIG_ZCRYPT_DEBUG
1450 		if (rc == -EAGAIN && (tr.fi.flags & AP_FI_FLAG_NO_RETRY))
1451 			break;
1452 #endif
1453 	} while (rc == -EAGAIN && tr.again_counter < TRACK_AGAIN_MAX);
1454 	/* on failure: retry once again after a requested rescan */
1455 	if ((rc == -ENODEV) && (zcrypt_process_rescan()))
1456 		do {
1457 			rc = zcrypt_rsa_modexpo(perms, &tr, &mex);
1458 			if (rc == -EAGAIN)
1459 				tr.again_counter++;
1460 		} while (rc == -EAGAIN && tr.again_counter < TRACK_AGAIN_MAX);
1461 	if (rc == -EAGAIN && tr.again_counter >= TRACK_AGAIN_MAX)
1462 		rc = -EIO;
1463 	if (rc) {
1464 		ZCRYPT_DBF_DBG("ioctl ICARSAMODEXPO rc=%d\n", rc);
1465 		return rc;
1466 	}
1467 	return put_user(mex.outputdatalength, &umex->outputdatalength);
1468 }
1469 
1470 static int icarsacrt_ioctl(struct ap_perms *perms, unsigned long arg)
1471 {
1472 	int rc;
1473 	struct zcrypt_track tr;
1474 	struct ica_rsa_modexpo_crt crt;
1475 	struct ica_rsa_modexpo_crt __user *ucrt = (void __user *) arg;
1476 
1477 	memset(&tr, 0, sizeof(tr));
1478 	if (copy_from_user(&crt, ucrt, sizeof(crt)))
1479 		return -EFAULT;
1480 
1481 #ifdef CONFIG_ZCRYPT_DEBUG
1482 	if (crt.inputdatalength & (1U << 31)) {
1483 		if (!capable(CAP_SYS_ADMIN))
1484 			return -EPERM;
1485 		tr.fi.cmd = (u16)(crt.inputdatalength >> 16);
1486 	}
1487 	crt.inputdatalength &= 0x0000FFFF;
1488 #endif
1489 
1490 	do {
1491 		rc = zcrypt_rsa_crt(perms, &tr, &crt);
1492 		if (rc == -EAGAIN)
1493 			tr.again_counter++;
1494 #ifdef CONFIG_ZCRYPT_DEBUG
1495 		if (rc == -EAGAIN && (tr.fi.flags & AP_FI_FLAG_NO_RETRY))
1496 			break;
1497 #endif
1498 	} while (rc == -EAGAIN && tr.again_counter < TRACK_AGAIN_MAX);
1499 	/* on failure: retry once again after a requested rescan */
1500 	if ((rc == -ENODEV) && (zcrypt_process_rescan()))
1501 		do {
1502 			rc = zcrypt_rsa_crt(perms, &tr, &crt);
1503 			if (rc == -EAGAIN)
1504 				tr.again_counter++;
1505 		} while (rc == -EAGAIN && tr.again_counter < TRACK_AGAIN_MAX);
1506 	if (rc == -EAGAIN && tr.again_counter >= TRACK_AGAIN_MAX)
1507 		rc = -EIO;
1508 	if (rc) {
1509 		ZCRYPT_DBF_DBG("ioctl ICARSACRT rc=%d\n", rc);
1510 		return rc;
1511 	}
1512 	return put_user(crt.outputdatalength, &ucrt->outputdatalength);
1513 }
1514 
1515 static int zsecsendcprb_ioctl(struct ap_perms *perms, unsigned long arg)
1516 {
1517 	int rc;
1518 	struct ica_xcRB xcRB;
1519 	struct zcrypt_track tr;
1520 	struct ica_xcRB __user *uxcRB = (void __user *) arg;
1521 
1522 	memset(&tr, 0, sizeof(tr));
1523 	if (copy_from_user(&xcRB, uxcRB, sizeof(xcRB)))
1524 		return -EFAULT;
1525 
1526 #ifdef CONFIG_ZCRYPT_DEBUG
1527 	if ((xcRB.status & 0x8000FFFF) == 0x80004649 /* 'FI' */) {
1528 		if (!capable(CAP_SYS_ADMIN))
1529 			return -EPERM;
1530 		tr.fi.cmd = (u16)(xcRB.status >> 16);
1531 	}
1532 	xcRB.status = 0;
1533 #endif
1534 
1535 	do {
1536 		rc = _zcrypt_send_cprb(true, perms, &tr, &xcRB);
1537 		if (rc == -EAGAIN)
1538 			tr.again_counter++;
1539 #ifdef CONFIG_ZCRYPT_DEBUG
1540 		if (rc == -EAGAIN && (tr.fi.flags & AP_FI_FLAG_NO_RETRY))
1541 			break;
1542 #endif
1543 	} while (rc == -EAGAIN && tr.again_counter < TRACK_AGAIN_MAX);
1544 	/* on failure: retry once again after a requested rescan */
1545 	if ((rc == -ENODEV) && (zcrypt_process_rescan()))
1546 		do {
1547 			rc = _zcrypt_send_cprb(true, perms, &tr, &xcRB);
1548 			if (rc == -EAGAIN)
1549 				tr.again_counter++;
1550 		} while (rc == -EAGAIN && tr.again_counter < TRACK_AGAIN_MAX);
1551 	if (rc == -EAGAIN && tr.again_counter >= TRACK_AGAIN_MAX)
1552 		rc = -EIO;
1553 	if (rc)
1554 		ZCRYPT_DBF_DBG("ioctl ZSENDCPRB rc=%d status=0x%x\n",
1555 			       rc, xcRB.status);
1556 	if (copy_to_user(uxcRB, &xcRB, sizeof(xcRB)))
1557 		return -EFAULT;
1558 	return rc;
1559 }
1560 
1561 static int zsendep11cprb_ioctl(struct ap_perms *perms, unsigned long arg)
1562 {
1563 	int rc;
1564 	struct ep11_urb xcrb;
1565 	struct zcrypt_track tr;
1566 	struct ep11_urb __user *uxcrb = (void __user *)arg;
1567 
1568 	memset(&tr, 0, sizeof(tr));
1569 	if (copy_from_user(&xcrb, uxcrb, sizeof(xcrb)))
1570 		return -EFAULT;
1571 
1572 #ifdef CONFIG_ZCRYPT_DEBUG
1573 	if (xcrb.req_len & (1ULL << 63)) {
1574 		if (!capable(CAP_SYS_ADMIN))
1575 			return -EPERM;
1576 		tr.fi.cmd = (u16)(xcrb.req_len >> 48);
1577 	}
1578 	xcrb.req_len &= 0x0000FFFFFFFFFFFFULL;
1579 #endif
1580 
1581 	do {
1582 		rc = _zcrypt_send_ep11_cprb(true, perms, &tr, &xcrb);
1583 		if (rc == -EAGAIN)
1584 			tr.again_counter++;
1585 #ifdef CONFIG_ZCRYPT_DEBUG
1586 		if (rc == -EAGAIN && (tr.fi.flags & AP_FI_FLAG_NO_RETRY))
1587 			break;
1588 #endif
1589 	} while (rc == -EAGAIN && tr.again_counter < TRACK_AGAIN_MAX);
1590 	/* on failure: retry once again after a requested rescan */
1591 	if ((rc == -ENODEV) && (zcrypt_process_rescan()))
1592 		do {
1593 			rc = _zcrypt_send_ep11_cprb(true, perms, &tr, &xcrb);
1594 			if (rc == -EAGAIN)
1595 				tr.again_counter++;
1596 		} while (rc == -EAGAIN && tr.again_counter < TRACK_AGAIN_MAX);
1597 	if (rc == -EAGAIN && tr.again_counter >= TRACK_AGAIN_MAX)
1598 		rc = -EIO;
1599 	if (rc)
1600 		ZCRYPT_DBF_DBG("ioctl ZSENDEP11CPRB rc=%d\n", rc);
1601 	if (copy_to_user(uxcrb, &xcrb, sizeof(xcrb)))
1602 		return -EFAULT;
1603 	return rc;
1604 }
1605 
1606 static long zcrypt_unlocked_ioctl(struct file *filp, unsigned int cmd,
1607 				  unsigned long arg)
1608 {
1609 	int rc;
1610 	struct ap_perms *perms =
1611 		(struct ap_perms *) filp->private_data;
1612 
1613 	rc = zcrypt_check_ioctl(perms, cmd);
1614 	if (rc)
1615 		return rc;
1616 
1617 	switch (cmd) {
1618 	case ICARSAMODEXPO:
1619 		return icarsamodexpo_ioctl(perms, arg);
1620 	case ICARSACRT:
1621 		return icarsacrt_ioctl(perms, arg);
1622 	case ZSECSENDCPRB:
1623 		return zsecsendcprb_ioctl(perms, arg);
1624 	case ZSENDEP11CPRB:
1625 		return zsendep11cprb_ioctl(perms, arg);
1626 	case ZCRYPT_DEVICE_STATUS: {
1627 		struct zcrypt_device_status_ext *device_status;
1628 		size_t total_size = MAX_ZDEV_ENTRIES_EXT
1629 			* sizeof(struct zcrypt_device_status_ext);
1630 
1631 		device_status = kzalloc(total_size, GFP_KERNEL);
1632 		if (!device_status)
1633 			return -ENOMEM;
1634 		zcrypt_device_status_mask_ext(device_status);
1635 		if (copy_to_user((char __user *) arg, device_status,
1636 				 total_size))
1637 			rc = -EFAULT;
1638 		kfree(device_status);
1639 		return rc;
1640 	}
1641 	case ZCRYPT_STATUS_MASK: {
1642 		char status[AP_DEVICES];
1643 
1644 		zcrypt_status_mask(status, AP_DEVICES);
1645 		if (copy_to_user((char __user *) arg, status, sizeof(status)))
1646 			return -EFAULT;
1647 		return 0;
1648 	}
1649 	case ZCRYPT_QDEPTH_MASK: {
1650 		char qdepth[AP_DEVICES];
1651 
1652 		zcrypt_qdepth_mask(qdepth, AP_DEVICES);
1653 		if (copy_to_user((char __user *) arg, qdepth, sizeof(qdepth)))
1654 			return -EFAULT;
1655 		return 0;
1656 	}
1657 	case ZCRYPT_PERDEV_REQCNT: {
1658 		u32 *reqcnt;
1659 
1660 		reqcnt = kcalloc(AP_DEVICES, sizeof(u32), GFP_KERNEL);
1661 		if (!reqcnt)
1662 			return -ENOMEM;
1663 		zcrypt_perdev_reqcnt(reqcnt, AP_DEVICES);
1664 		if (copy_to_user((int __user *) arg, reqcnt,
1665 				 sizeof(u32) * AP_DEVICES))
1666 			rc = -EFAULT;
1667 		kfree(reqcnt);
1668 		return rc;
1669 	}
1670 	case Z90STAT_REQUESTQ_COUNT:
1671 		return put_user(zcrypt_requestq_count(), (int __user *) arg);
1672 	case Z90STAT_PENDINGQ_COUNT:
1673 		return put_user(zcrypt_pendingq_count(), (int __user *) arg);
1674 	case Z90STAT_TOTALOPEN_COUNT:
1675 		return put_user(atomic_read(&zcrypt_open_count),
1676 				(int __user *) arg);
1677 	case Z90STAT_DOMAIN_INDEX:
1678 		return put_user(ap_domain_index, (int __user *) arg);
1679 	/*
1680 	 * Deprecated ioctls
1681 	 */
1682 	case ZDEVICESTATUS: {
1683 		/* the old ioctl supports only 64 adapters */
1684 		struct zcrypt_device_status *device_status;
1685 		size_t total_size = MAX_ZDEV_ENTRIES
1686 			* sizeof(struct zcrypt_device_status);
1687 
1688 		device_status = kzalloc(total_size, GFP_KERNEL);
1689 		if (!device_status)
1690 			return -ENOMEM;
1691 		zcrypt_device_status_mask(device_status);
1692 		if (copy_to_user((char __user *) arg, device_status,
1693 				 total_size))
1694 			rc = -EFAULT;
1695 		kfree(device_status);
1696 		return rc;
1697 	}
1698 	case Z90STAT_STATUS_MASK: {
1699 		/* the old ioctl supports only 64 adapters */
1700 		char status[MAX_ZDEV_CARDIDS];
1701 
1702 		zcrypt_status_mask(status, MAX_ZDEV_CARDIDS);
1703 		if (copy_to_user((char __user *) arg, status, sizeof(status)))
1704 			return -EFAULT;
1705 		return 0;
1706 	}
1707 	case Z90STAT_QDEPTH_MASK: {
1708 		/* the old ioctl supports only 64 adapters */
1709 		char qdepth[MAX_ZDEV_CARDIDS];
1710 
1711 		zcrypt_qdepth_mask(qdepth, MAX_ZDEV_CARDIDS);
1712 		if (copy_to_user((char __user *) arg, qdepth, sizeof(qdepth)))
1713 			return -EFAULT;
1714 		return 0;
1715 	}
1716 	case Z90STAT_PERDEV_REQCNT: {
1717 		/* the old ioctl supports only 64 adapters */
1718 		u32 reqcnt[MAX_ZDEV_CARDIDS];
1719 
1720 		zcrypt_perdev_reqcnt(reqcnt, MAX_ZDEV_CARDIDS);
1721 		if (copy_to_user((int __user *) arg, reqcnt, sizeof(reqcnt)))
1722 			return -EFAULT;
1723 		return 0;
1724 	}
1725 	/* unknown ioctl number */
1726 	default:
1727 		ZCRYPT_DBF_DBG("unknown ioctl 0x%08x\n", cmd);
1728 		return -ENOIOCTLCMD;
1729 	}
1730 }
1731 
1732 #ifdef CONFIG_COMPAT
1733 /*
1734  * ioctl32 conversion routines
1735  */
1736 struct compat_ica_rsa_modexpo {
1737 	compat_uptr_t	inputdata;
1738 	unsigned int	inputdatalength;
1739 	compat_uptr_t	outputdata;
1740 	unsigned int	outputdatalength;
1741 	compat_uptr_t	b_key;
1742 	compat_uptr_t	n_modulus;
1743 };
1744 
1745 static long trans_modexpo32(struct ap_perms *perms, struct file *filp,
1746 			    unsigned int cmd, unsigned long arg)
1747 {
1748 	struct compat_ica_rsa_modexpo __user *umex32 = compat_ptr(arg);
1749 	struct compat_ica_rsa_modexpo mex32;
1750 	struct ica_rsa_modexpo mex64;
1751 	struct zcrypt_track tr;
1752 	long rc;
1753 
1754 	memset(&tr, 0, sizeof(tr));
1755 	if (copy_from_user(&mex32, umex32, sizeof(mex32)))
1756 		return -EFAULT;
1757 	mex64.inputdata = compat_ptr(mex32.inputdata);
1758 	mex64.inputdatalength = mex32.inputdatalength;
1759 	mex64.outputdata = compat_ptr(mex32.outputdata);
1760 	mex64.outputdatalength = mex32.outputdatalength;
1761 	mex64.b_key = compat_ptr(mex32.b_key);
1762 	mex64.n_modulus = compat_ptr(mex32.n_modulus);
1763 	do {
1764 		rc = zcrypt_rsa_modexpo(perms, &tr, &mex64);
1765 		if (rc == -EAGAIN)
1766 			tr.again_counter++;
1767 	} while (rc == -EAGAIN && tr.again_counter < TRACK_AGAIN_MAX);
1768 	/* on failure: retry once again after a requested rescan */
1769 	if ((rc == -ENODEV) && (zcrypt_process_rescan()))
1770 		do {
1771 			rc = zcrypt_rsa_modexpo(perms, &tr, &mex64);
1772 			if (rc == -EAGAIN)
1773 				tr.again_counter++;
1774 		} while (rc == -EAGAIN && tr.again_counter < TRACK_AGAIN_MAX);
1775 	if (rc == -EAGAIN && tr.again_counter >= TRACK_AGAIN_MAX)
1776 		rc = -EIO;
1777 	if (rc)
1778 		return rc;
1779 	return put_user(mex64.outputdatalength,
1780 			&umex32->outputdatalength);
1781 }
1782 
1783 struct compat_ica_rsa_modexpo_crt {
1784 	compat_uptr_t	inputdata;
1785 	unsigned int	inputdatalength;
1786 	compat_uptr_t	outputdata;
1787 	unsigned int	outputdatalength;
1788 	compat_uptr_t	bp_key;
1789 	compat_uptr_t	bq_key;
1790 	compat_uptr_t	np_prime;
1791 	compat_uptr_t	nq_prime;
1792 	compat_uptr_t	u_mult_inv;
1793 };
1794 
1795 static long trans_modexpo_crt32(struct ap_perms *perms, struct file *filp,
1796 				unsigned int cmd, unsigned long arg)
1797 {
1798 	struct compat_ica_rsa_modexpo_crt __user *ucrt32 = compat_ptr(arg);
1799 	struct compat_ica_rsa_modexpo_crt crt32;
1800 	struct ica_rsa_modexpo_crt crt64;
1801 	struct zcrypt_track tr;
1802 	long rc;
1803 
1804 	memset(&tr, 0, sizeof(tr));
1805 	if (copy_from_user(&crt32, ucrt32, sizeof(crt32)))
1806 		return -EFAULT;
1807 	crt64.inputdata = compat_ptr(crt32.inputdata);
1808 	crt64.inputdatalength = crt32.inputdatalength;
1809 	crt64.outputdata = compat_ptr(crt32.outputdata);
1810 	crt64.outputdatalength = crt32.outputdatalength;
1811 	crt64.bp_key = compat_ptr(crt32.bp_key);
1812 	crt64.bq_key = compat_ptr(crt32.bq_key);
1813 	crt64.np_prime = compat_ptr(crt32.np_prime);
1814 	crt64.nq_prime = compat_ptr(crt32.nq_prime);
1815 	crt64.u_mult_inv = compat_ptr(crt32.u_mult_inv);
1816 	do {
1817 		rc = zcrypt_rsa_crt(perms, &tr, &crt64);
1818 		if (rc == -EAGAIN)
1819 			tr.again_counter++;
1820 	} while (rc == -EAGAIN && tr.again_counter < TRACK_AGAIN_MAX);
1821 	/* on failure: retry once again after a requested rescan */
1822 	if ((rc == -ENODEV) && (zcrypt_process_rescan()))
1823 		do {
1824 			rc = zcrypt_rsa_crt(perms, &tr, &crt64);
1825 			if (rc == -EAGAIN)
1826 				tr.again_counter++;
1827 		} while (rc == -EAGAIN && tr.again_counter < TRACK_AGAIN_MAX);
1828 	if (rc == -EAGAIN && tr.again_counter >= TRACK_AGAIN_MAX)
1829 		rc = -EIO;
1830 	if (rc)
1831 		return rc;
1832 	return put_user(crt64.outputdatalength,
1833 			&ucrt32->outputdatalength);
1834 }
1835 
1836 struct compat_ica_xcRB {
1837 	unsigned short	agent_ID;
1838 	unsigned int	user_defined;
1839 	unsigned short	request_ID;
1840 	unsigned int	request_control_blk_length;
1841 	unsigned char	padding1[16 - sizeof(compat_uptr_t)];
1842 	compat_uptr_t	request_control_blk_addr;
1843 	unsigned int	request_data_length;
1844 	char		padding2[16 - sizeof(compat_uptr_t)];
1845 	compat_uptr_t	request_data_address;
1846 	unsigned int	reply_control_blk_length;
1847 	char		padding3[16 - sizeof(compat_uptr_t)];
1848 	compat_uptr_t	reply_control_blk_addr;
1849 	unsigned int	reply_data_length;
1850 	char		padding4[16 - sizeof(compat_uptr_t)];
1851 	compat_uptr_t	reply_data_addr;
1852 	unsigned short	priority_window;
1853 	unsigned int	status;
1854 } __packed;
1855 
1856 static long trans_xcRB32(struct ap_perms *perms, struct file *filp,
1857 			 unsigned int cmd, unsigned long arg)
1858 {
1859 	struct compat_ica_xcRB __user *uxcRB32 = compat_ptr(arg);
1860 	struct compat_ica_xcRB xcRB32;
1861 	struct zcrypt_track tr;
1862 	struct ica_xcRB xcRB64;
1863 	long rc;
1864 
1865 	memset(&tr, 0, sizeof(tr));
1866 	if (copy_from_user(&xcRB32, uxcRB32, sizeof(xcRB32)))
1867 		return -EFAULT;
1868 	xcRB64.agent_ID = xcRB32.agent_ID;
1869 	xcRB64.user_defined = xcRB32.user_defined;
1870 	xcRB64.request_ID = xcRB32.request_ID;
1871 	xcRB64.request_control_blk_length =
1872 		xcRB32.request_control_blk_length;
1873 	xcRB64.request_control_blk_addr =
1874 		compat_ptr(xcRB32.request_control_blk_addr);
1875 	xcRB64.request_data_length =
1876 		xcRB32.request_data_length;
1877 	xcRB64.request_data_address =
1878 		compat_ptr(xcRB32.request_data_address);
1879 	xcRB64.reply_control_blk_length =
1880 		xcRB32.reply_control_blk_length;
1881 	xcRB64.reply_control_blk_addr =
1882 		compat_ptr(xcRB32.reply_control_blk_addr);
1883 	xcRB64.reply_data_length = xcRB32.reply_data_length;
1884 	xcRB64.reply_data_addr =
1885 		compat_ptr(xcRB32.reply_data_addr);
1886 	xcRB64.priority_window = xcRB32.priority_window;
1887 	xcRB64.status = xcRB32.status;
1888 	do {
1889 		rc = _zcrypt_send_cprb(true, perms, &tr, &xcRB64);
1890 		if (rc == -EAGAIN)
1891 			tr.again_counter++;
1892 	} while (rc == -EAGAIN && tr.again_counter < TRACK_AGAIN_MAX);
1893 	/* on failure: retry once again after a requested rescan */
1894 	if ((rc == -ENODEV) && (zcrypt_process_rescan()))
1895 		do {
1896 			rc = _zcrypt_send_cprb(true, perms, &tr, &xcRB64);
1897 			if (rc == -EAGAIN)
1898 				tr.again_counter++;
1899 		} while (rc == -EAGAIN && tr.again_counter < TRACK_AGAIN_MAX);
1900 	if (rc == -EAGAIN && tr.again_counter >= TRACK_AGAIN_MAX)
1901 		rc = -EIO;
1902 	xcRB32.reply_control_blk_length = xcRB64.reply_control_blk_length;
1903 	xcRB32.reply_data_length = xcRB64.reply_data_length;
1904 	xcRB32.status = xcRB64.status;
1905 	if (copy_to_user(uxcRB32, &xcRB32, sizeof(xcRB32)))
1906 		return -EFAULT;
1907 	return rc;
1908 }
1909 
1910 static long zcrypt_compat_ioctl(struct file *filp, unsigned int cmd,
1911 			 unsigned long arg)
1912 {
1913 	int rc;
1914 	struct ap_perms *perms =
1915 		(struct ap_perms *) filp->private_data;
1916 
1917 	rc = zcrypt_check_ioctl(perms, cmd);
1918 	if (rc)
1919 		return rc;
1920 
1921 	if (cmd == ICARSAMODEXPO)
1922 		return trans_modexpo32(perms, filp, cmd, arg);
1923 	if (cmd == ICARSACRT)
1924 		return trans_modexpo_crt32(perms, filp, cmd, arg);
1925 	if (cmd == ZSECSENDCPRB)
1926 		return trans_xcRB32(perms, filp, cmd, arg);
1927 	return zcrypt_unlocked_ioctl(filp, cmd, arg);
1928 }
1929 #endif
1930 
1931 /*
1932  * Misc device file operations.
1933  */
1934 static const struct file_operations zcrypt_fops = {
1935 	.owner		= THIS_MODULE,
1936 	.read		= zcrypt_read,
1937 	.write		= zcrypt_write,
1938 	.unlocked_ioctl	= zcrypt_unlocked_ioctl,
1939 #ifdef CONFIG_COMPAT
1940 	.compat_ioctl	= zcrypt_compat_ioctl,
1941 #endif
1942 	.open		= zcrypt_open,
1943 	.release	= zcrypt_release,
1944 	.llseek		= no_llseek,
1945 };
1946 
1947 /*
1948  * Misc device.
1949  */
1950 static struct miscdevice zcrypt_misc_device = {
1951 	.minor	    = MISC_DYNAMIC_MINOR,
1952 	.name	    = "z90crypt",
1953 	.fops	    = &zcrypt_fops,
1954 };
1955 
1956 static int zcrypt_rng_device_count;
1957 static u32 *zcrypt_rng_buffer;
1958 static int zcrypt_rng_buffer_index;
1959 static DEFINE_MUTEX(zcrypt_rng_mutex);
1960 
1961 static int zcrypt_rng_data_read(struct hwrng *rng, u32 *data)
1962 {
1963 	int rc;
1964 
1965 	/*
1966 	 * We don't need locking here because the RNG API guarantees serialized
1967 	 * read method calls.
1968 	 */
1969 	if (zcrypt_rng_buffer_index == 0) {
1970 		rc = zcrypt_rng((char *) zcrypt_rng_buffer);
1971 		/* on failure: retry once again after a requested rescan */
1972 		if ((rc == -ENODEV) && (zcrypt_process_rescan()))
1973 			rc = zcrypt_rng((char *) zcrypt_rng_buffer);
1974 		if (rc < 0)
1975 			return -EIO;
1976 		zcrypt_rng_buffer_index = rc / sizeof(*data);
1977 	}
1978 	*data = zcrypt_rng_buffer[--zcrypt_rng_buffer_index];
1979 	return sizeof(*data);
1980 }
1981 
1982 static struct hwrng zcrypt_rng_dev = {
1983 	.name		= "zcrypt",
1984 	.data_read	= zcrypt_rng_data_read,
1985 	.quality	= 990,
1986 };
1987 
1988 int zcrypt_rng_device_add(void)
1989 {
1990 	int rc = 0;
1991 
1992 	mutex_lock(&zcrypt_rng_mutex);
1993 	if (zcrypt_rng_device_count == 0) {
1994 		zcrypt_rng_buffer = (u32 *) get_zeroed_page(GFP_KERNEL);
1995 		if (!zcrypt_rng_buffer) {
1996 			rc = -ENOMEM;
1997 			goto out;
1998 		}
1999 		zcrypt_rng_buffer_index = 0;
2000 		if (!zcrypt_hwrng_seed)
2001 			zcrypt_rng_dev.quality = 0;
2002 		rc = hwrng_register(&zcrypt_rng_dev);
2003 		if (rc)
2004 			goto out_free;
2005 		zcrypt_rng_device_count = 1;
2006 	} else
2007 		zcrypt_rng_device_count++;
2008 	mutex_unlock(&zcrypt_rng_mutex);
2009 	return 0;
2010 
2011 out_free:
2012 	free_page((unsigned long) zcrypt_rng_buffer);
2013 out:
2014 	mutex_unlock(&zcrypt_rng_mutex);
2015 	return rc;
2016 }
2017 
2018 void zcrypt_rng_device_remove(void)
2019 {
2020 	mutex_lock(&zcrypt_rng_mutex);
2021 	zcrypt_rng_device_count--;
2022 	if (zcrypt_rng_device_count == 0) {
2023 		hwrng_unregister(&zcrypt_rng_dev);
2024 		free_page((unsigned long) zcrypt_rng_buffer);
2025 	}
2026 	mutex_unlock(&zcrypt_rng_mutex);
2027 }
2028 
2029 /*
2030  * Wait until the zcrypt api is operational.
2031  * The AP bus scan and the binding of ap devices to device drivers is
2032  * an asynchronous job. This function waits until these initial jobs
2033  * are done and so the zcrypt api should be ready to serve crypto
2034  * requests - if there are resources available. The function uses an
2035  * internal timeout of 60s. The very first caller will either wait for
2036  * ap bus bindings complete or the timeout happens. This state will be
2037  * remembered for further callers which will only be blocked until a
2038  * decision is made (timeout or bindings complete).
2039  * On timeout -ETIME is returned, on success the return value is 0.
2040  */
2041 int zcrypt_wait_api_operational(void)
2042 {
2043 	static DEFINE_MUTEX(zcrypt_wait_api_lock);
2044 	static int zcrypt_wait_api_state;
2045 	int rc;
2046 
2047 	rc = mutex_lock_interruptible(&zcrypt_wait_api_lock);
2048 	if (rc)
2049 		return rc;
2050 
2051 	switch (zcrypt_wait_api_state) {
2052 	case 0:
2053 		/* initial state, invoke wait for the ap bus complete */
2054 		rc = ap_wait_init_apqn_bindings_complete(
2055 			msecs_to_jiffies(60 * 1000));
2056 		switch (rc) {
2057 		case 0:
2058 			/* ap bus bindings are complete */
2059 			zcrypt_wait_api_state = 1;
2060 			break;
2061 		case -EINTR:
2062 			/* interrupted, go back to caller */
2063 			break;
2064 		case -ETIME:
2065 			/* timeout */
2066 			ZCRYPT_DBF_WARN("%s ap_wait_init_apqn_bindings_complete()=ETIME\n",
2067 					__func__);
2068 			zcrypt_wait_api_state = -ETIME;
2069 			break;
2070 		default:
2071 			/* other failure */
2072 			ZCRYPT_DBF_DBG("%s ap_wait_init_apqn_bindings_complete()=%d\n",
2073 				       __func__, rc);
2074 			break;
2075 		}
2076 		break;
2077 	case 1:
2078 		/* a previous caller already found ap bus bindings complete */
2079 		rc = 0;
2080 		break;
2081 	default:
2082 		/* a previous caller had timeout or other failure */
2083 		rc = zcrypt_wait_api_state;
2084 		break;
2085 	}
2086 
2087 	mutex_unlock(&zcrypt_wait_api_lock);
2088 
2089 	return rc;
2090 }
2091 EXPORT_SYMBOL(zcrypt_wait_api_operational);
2092 
2093 int __init zcrypt_debug_init(void)
2094 {
2095 	zcrypt_dbf_info = debug_register("zcrypt", 2, 1,
2096 					 DBF_MAX_SPRINTF_ARGS * sizeof(long));
2097 	debug_register_view(zcrypt_dbf_info, &debug_sprintf_view);
2098 	debug_set_level(zcrypt_dbf_info, DBF_ERR);
2099 
2100 	return 0;
2101 }
2102 
2103 void zcrypt_debug_exit(void)
2104 {
2105 	debug_unregister(zcrypt_dbf_info);
2106 }
2107 
2108 #ifdef CONFIG_ZCRYPT_MULTIDEVNODES
2109 
2110 static int __init zcdn_init(void)
2111 {
2112 	int rc;
2113 
2114 	/* create a new class 'zcrypt' */
2115 	zcrypt_class = class_create(THIS_MODULE, ZCRYPT_NAME);
2116 	if (IS_ERR(zcrypt_class)) {
2117 		rc = PTR_ERR(zcrypt_class);
2118 		goto out_class_create_failed;
2119 	}
2120 	zcrypt_class->dev_release = zcdn_device_release;
2121 
2122 	/* alloc device minor range */
2123 	rc = alloc_chrdev_region(&zcrypt_devt,
2124 				 0, ZCRYPT_MAX_MINOR_NODES,
2125 				 ZCRYPT_NAME);
2126 	if (rc)
2127 		goto out_alloc_chrdev_failed;
2128 
2129 	cdev_init(&zcrypt_cdev, &zcrypt_fops);
2130 	zcrypt_cdev.owner = THIS_MODULE;
2131 	rc = cdev_add(&zcrypt_cdev, zcrypt_devt, ZCRYPT_MAX_MINOR_NODES);
2132 	if (rc)
2133 		goto out_cdev_add_failed;
2134 
2135 	/* need some class specific sysfs attributes */
2136 	rc = class_create_file(zcrypt_class, &class_attr_zcdn_create);
2137 	if (rc)
2138 		goto out_class_create_file_1_failed;
2139 	rc = class_create_file(zcrypt_class, &class_attr_zcdn_destroy);
2140 	if (rc)
2141 		goto out_class_create_file_2_failed;
2142 
2143 	return 0;
2144 
2145 out_class_create_file_2_failed:
2146 	class_remove_file(zcrypt_class, &class_attr_zcdn_create);
2147 out_class_create_file_1_failed:
2148 	cdev_del(&zcrypt_cdev);
2149 out_cdev_add_failed:
2150 	unregister_chrdev_region(zcrypt_devt, ZCRYPT_MAX_MINOR_NODES);
2151 out_alloc_chrdev_failed:
2152 	class_destroy(zcrypt_class);
2153 out_class_create_failed:
2154 	return rc;
2155 }
2156 
2157 static void zcdn_exit(void)
2158 {
2159 	class_remove_file(zcrypt_class, &class_attr_zcdn_create);
2160 	class_remove_file(zcrypt_class, &class_attr_zcdn_destroy);
2161 	zcdn_destroy_all();
2162 	cdev_del(&zcrypt_cdev);
2163 	unregister_chrdev_region(zcrypt_devt, ZCRYPT_MAX_MINOR_NODES);
2164 	class_destroy(zcrypt_class);
2165 }
2166 
2167 #endif
2168 
2169 /*
2170  * zcrypt_api_init(): Module initialization.
2171  *
2172  * The module initialization code.
2173  */
2174 int __init zcrypt_api_init(void)
2175 {
2176 	int rc;
2177 
2178 	rc = zcrypt_debug_init();
2179 	if (rc)
2180 		goto out;
2181 
2182 #ifdef CONFIG_ZCRYPT_MULTIDEVNODES
2183 	rc = zcdn_init();
2184 	if (rc)
2185 		goto out;
2186 #endif
2187 
2188 	/* Register the request sprayer. */
2189 	rc = misc_register(&zcrypt_misc_device);
2190 	if (rc < 0)
2191 		goto out_misc_register_failed;
2192 
2193 	zcrypt_msgtype6_init();
2194 	zcrypt_msgtype50_init();
2195 
2196 	return 0;
2197 
2198 out_misc_register_failed:
2199 #ifdef CONFIG_ZCRYPT_MULTIDEVNODES
2200 	zcdn_exit();
2201 #endif
2202 	zcrypt_debug_exit();
2203 out:
2204 	return rc;
2205 }
2206 
2207 /*
2208  * zcrypt_api_exit(): Module termination.
2209  *
2210  * The module termination code.
2211  */
2212 void __exit zcrypt_api_exit(void)
2213 {
2214 #ifdef CONFIG_ZCRYPT_MULTIDEVNODES
2215 	zcdn_exit();
2216 #endif
2217 	misc_deregister(&zcrypt_misc_device);
2218 	zcrypt_msgtype6_exit();
2219 	zcrypt_msgtype50_exit();
2220 	zcrypt_ccamisc_exit();
2221 	zcrypt_ep11misc_exit();
2222 	zcrypt_debug_exit();
2223 }
2224 
2225 module_init(zcrypt_api_init);
2226 module_exit(zcrypt_api_exit);
2227