xref: /openbmc/linux/drivers/s390/crypto/pkey_api.c (revision be709d48)
1 // SPDX-License-Identifier: GPL-2.0
2 /*
3  *  pkey device driver
4  *
5  *  Copyright IBM Corp. 2017
6  *  Author(s): Harald Freudenberger
7  */
8 
9 #define KMSG_COMPONENT "pkey"
10 #define pr_fmt(fmt) KMSG_COMPONENT ": " fmt
11 
12 #include <linux/fs.h>
13 #include <linux/init.h>
14 #include <linux/miscdevice.h>
15 #include <linux/module.h>
16 #include <linux/slab.h>
17 #include <linux/kallsyms.h>
18 #include <linux/debugfs.h>
19 #include <linux/random.h>
20 #include <linux/cpufeature.h>
21 #include <asm/zcrypt.h>
22 #include <asm/cpacf.h>
23 #include <asm/pkey.h>
24 #include <crypto/aes.h>
25 
26 #include "zcrypt_api.h"
27 
28 MODULE_LICENSE("GPL");
29 MODULE_AUTHOR("IBM Corporation");
30 MODULE_DESCRIPTION("s390 protected key interface");
31 
32 /* Size of parameter block used for all cca requests/replies */
33 #define PARMBSIZE 512
34 
35 /* Size of vardata block used for some of the cca requests/replies */
36 #define VARDATASIZE 4096
37 
38 /* mask of available pckmo subfunctions, fetched once at module init */
39 static cpacf_mask_t pckmo_functions;
40 
41 /*
42  * debug feature data and functions
43  */
44 
45 static debug_info_t *debug_info;
46 
47 #define DEBUG_DBG(...)	debug_sprintf_event(debug_info, 6, ##__VA_ARGS__)
48 #define DEBUG_INFO(...) debug_sprintf_event(debug_info, 5, ##__VA_ARGS__)
49 #define DEBUG_WARN(...) debug_sprintf_event(debug_info, 4, ##__VA_ARGS__)
50 #define DEBUG_ERR(...)	debug_sprintf_event(debug_info, 3, ##__VA_ARGS__)
51 
52 static void __init pkey_debug_init(void)
53 {
54 	debug_info = debug_register("pkey", 1, 1, 4 * sizeof(long));
55 	debug_register_view(debug_info, &debug_sprintf_view);
56 	debug_set_level(debug_info, 3);
57 }
58 
59 static void __exit pkey_debug_exit(void)
60 {
61 	debug_unregister(debug_info);
62 }
63 
64 /* Key token types */
65 #define TOKTYPE_NON_CCA		0x00 /* Non-CCA key token */
66 #define TOKTYPE_CCA_INTERNAL	0x01 /* CCA internal key token */
67 
68 /* For TOKTYPE_NON_CCA: */
69 #define TOKVER_PROTECTED_KEY	0x01 /* Protected key token */
70 
71 /* For TOKTYPE_CCA_INTERNAL: */
72 #define TOKVER_CCA_AES		0x04 /* CCA AES key token */
73 
74 /* header part of a key token */
75 struct keytoken_header {
76 	u8  type;     /* one of the TOKTYPE values */
77 	u8  res0[3];
78 	u8  version;  /* one of the TOKVER values */
79 	u8  res1[3];
80 } __packed;
81 
82 /* inside view of a secure key token (only type 0x01 version 0x04) */
83 struct secaeskeytoken {
84 	u8  type;     /* 0x01 for internal key token */
85 	u8  res0[3];
86 	u8  version;  /* should be 0x04 */
87 	u8  res1[1];
88 	u8  flag;     /* key flags */
89 	u8  res2[1];
90 	u64 mkvp;     /* master key verification pattern */
91 	u8  key[32];  /* key value (encrypted) */
92 	u8  cv[8];    /* control vector */
93 	u16 bitsize;  /* key bit size */
94 	u16 keysize;  /* key byte size */
95 	u8  tvv[4];   /* token validation value */
96 } __packed;
97 
98 /* inside view of a protected key token (only type 0x00 version 0x01) */
99 struct protaeskeytoken {
100 	u8  type;     /* 0x00 for PAES specific key tokens */
101 	u8  res0[3];
102 	u8  version;  /* should be 0x01 for protected AES key token */
103 	u8  res1[3];
104 	u32 keytype;  /* key type, one of the PKEY_KEYTYPE values */
105 	u32 len;      /* bytes actually stored in protkey[] */
106 	u8  protkey[MAXPROTKEYSIZE]; /* the protected key blob */
107 } __packed;
108 
109 /*
110  * Simple check if the token is a valid CCA secure AES key
111  * token. If keybitsize is given, the bitsize of the key is
112  * also checked. Returns 0 on success or errno value on failure.
113  */
114 static int check_secaeskeytoken(const u8 *token, int keybitsize)
115 {
116 	struct secaeskeytoken *t = (struct secaeskeytoken *) token;
117 
118 	if (t->type != TOKTYPE_CCA_INTERNAL) {
119 		DEBUG_ERR(
120 			"%s secure token check failed, type mismatch 0x%02x != 0x%02x\n",
121 			__func__, (int) t->type, TOKTYPE_CCA_INTERNAL);
122 		return -EINVAL;
123 	}
124 	if (t->version != TOKVER_CCA_AES) {
125 		DEBUG_ERR(
126 			"%s secure token check failed, version mismatch 0x%02x != 0x%02x\n",
127 			__func__, (int) t->version, TOKVER_CCA_AES);
128 		return -EINVAL;
129 	}
130 	if (keybitsize > 0 && t->bitsize != keybitsize) {
131 		DEBUG_ERR(
132 			"%s secure token check failed, bitsize mismatch %d != %d\n",
133 			__func__, (int) t->bitsize, keybitsize);
134 		return -EINVAL;
135 	}
136 
137 	return 0;
138 }
139 
140 /*
141  * Allocate consecutive memory for request CPRB, request param
142  * block, reply CPRB and reply param block and fill in values
143  * for the common fields. Returns 0 on success or errno value
144  * on failure.
145  */
146 static int alloc_and_prep_cprbmem(size_t paramblen,
147 				  u8 **pcprbmem,
148 				  struct CPRBX **preqCPRB,
149 				  struct CPRBX **prepCPRB)
150 {
151 	u8 *cprbmem;
152 	size_t cprbplusparamblen = sizeof(struct CPRBX) + paramblen;
153 	struct CPRBX *preqcblk, *prepcblk;
154 
155 	/*
156 	 * allocate consecutive memory for request CPRB, request param
157 	 * block, reply CPRB and reply param block
158 	 */
159 	cprbmem = kcalloc(2, cprbplusparamblen, GFP_KERNEL);
160 	if (!cprbmem)
161 		return -ENOMEM;
162 
163 	preqcblk = (struct CPRBX *) cprbmem;
164 	prepcblk = (struct CPRBX *) (cprbmem + cprbplusparamblen);
165 
166 	/* fill request cprb struct */
167 	preqcblk->cprb_len = sizeof(struct CPRBX);
168 	preqcblk->cprb_ver_id = 0x02;
169 	memcpy(preqcblk->func_id, "T2", 2);
170 	preqcblk->rpl_msgbl = cprbplusparamblen;
171 	if (paramblen) {
172 		preqcblk->req_parmb =
173 			((u8 *) preqcblk) + sizeof(struct CPRBX);
174 		preqcblk->rpl_parmb =
175 			((u8 *) prepcblk) + sizeof(struct CPRBX);
176 	}
177 
178 	*pcprbmem = cprbmem;
179 	*preqCPRB = preqcblk;
180 	*prepCPRB = prepcblk;
181 
182 	return 0;
183 }
184 
185 /*
186  * Free the cprb memory allocated with the function above.
187  * If the scrub value is not zero, the memory is filled
188  * with zeros before freeing (useful if there was some
189  * clear key material in there).
190  */
191 static void free_cprbmem(void *mem, size_t paramblen, int scrub)
192 {
193 	if (scrub)
194 		memzero_explicit(mem, 2 * (sizeof(struct CPRBX) + paramblen));
195 	kfree(mem);
196 }
197 
198 /*
199  * Helper function to prepare the xcrb struct
200  */
201 static inline void prep_xcrb(struct ica_xcRB *pxcrb,
202 			     u16 cardnr,
203 			     struct CPRBX *preqcblk,
204 			     struct CPRBX *prepcblk)
205 {
206 	memset(pxcrb, 0, sizeof(*pxcrb));
207 	pxcrb->agent_ID = 0x4341; /* 'CA' */
208 	pxcrb->user_defined = (cardnr == 0xFFFF ? AUTOSELECT : cardnr);
209 	pxcrb->request_control_blk_length =
210 		preqcblk->cprb_len + preqcblk->req_parml;
211 	pxcrb->request_control_blk_addr = (void __user *) preqcblk;
212 	pxcrb->reply_control_blk_length = preqcblk->rpl_msgbl;
213 	pxcrb->reply_control_blk_addr = (void __user *) prepcblk;
214 }
215 
216 /*
217  * Helper function which calls zcrypt_send_cprb with
218  * memory management segment adjusted to kernel space
219  * so that the copy_from_user called within this
220  * function do in fact copy from kernel space.
221  */
222 static inline int _zcrypt_send_cprb(struct ica_xcRB *xcrb)
223 {
224 	int rc;
225 	mm_segment_t old_fs = get_fs();
226 
227 	set_fs(KERNEL_DS);
228 	rc = zcrypt_send_cprb(xcrb);
229 	set_fs(old_fs);
230 
231 	return rc;
232 }
233 
234 /*
235  * Generate (random) AES secure key.
236  */
237 int pkey_genseckey(u16 cardnr, u16 domain,
238 		   u32 keytype, struct pkey_seckey *seckey)
239 {
240 	int i, rc, keysize;
241 	int seckeysize;
242 	u8 *mem;
243 	struct CPRBX *preqcblk, *prepcblk;
244 	struct ica_xcRB xcrb;
245 	struct kgreqparm {
246 		u8  subfunc_code[2];
247 		u16 rule_array_len;
248 		struct lv1 {
249 			u16 len;
250 			char  key_form[8];
251 			char  key_length[8];
252 			char  key_type1[8];
253 			char  key_type2[8];
254 		} lv1;
255 		struct lv2 {
256 			u16 len;
257 			struct keyid {
258 				u16 len;
259 				u16 attr;
260 				u8  data[SECKEYBLOBSIZE];
261 			} keyid[6];
262 		} lv2;
263 	} *preqparm;
264 	struct kgrepparm {
265 		u8  subfunc_code[2];
266 		u16 rule_array_len;
267 		struct lv3 {
268 			u16 len;
269 			u16 keyblocklen;
270 			struct {
271 				u16 toklen;
272 				u16 tokattr;
273 				u8  tok[0];
274 				/* ... some more data ... */
275 			} keyblock;
276 		} lv3;
277 	} *prepparm;
278 
279 	/* get already prepared memory for 2 cprbs with param block each */
280 	rc = alloc_and_prep_cprbmem(PARMBSIZE, &mem, &preqcblk, &prepcblk);
281 	if (rc)
282 		return rc;
283 
284 	/* fill request cprb struct */
285 	preqcblk->domain = domain;
286 
287 	/* fill request cprb param block with KG request */
288 	preqparm = (struct kgreqparm *) preqcblk->req_parmb;
289 	memcpy(preqparm->subfunc_code, "KG", 2);
290 	preqparm->rule_array_len = sizeof(preqparm->rule_array_len);
291 	preqparm->lv1.len = sizeof(struct lv1);
292 	memcpy(preqparm->lv1.key_form,	 "OP      ", 8);
293 	switch (keytype) {
294 	case PKEY_KEYTYPE_AES_128:
295 		keysize = 16;
296 		memcpy(preqparm->lv1.key_length, "KEYLN16 ", 8);
297 		break;
298 	case PKEY_KEYTYPE_AES_192:
299 		keysize = 24;
300 		memcpy(preqparm->lv1.key_length, "KEYLN24 ", 8);
301 		break;
302 	case PKEY_KEYTYPE_AES_256:
303 		keysize = 32;
304 		memcpy(preqparm->lv1.key_length, "KEYLN32 ", 8);
305 		break;
306 	default:
307 		DEBUG_ERR(
308 			"%s unknown/unsupported keytype %d\n",
309 			__func__, keytype);
310 		rc = -EINVAL;
311 		goto out;
312 	}
313 	memcpy(preqparm->lv1.key_type1,  "AESDATA ", 8);
314 	preqparm->lv2.len = sizeof(struct lv2);
315 	for (i = 0; i < 6; i++) {
316 		preqparm->lv2.keyid[i].len = sizeof(struct keyid);
317 		preqparm->lv2.keyid[i].attr = (i == 2 ? 0x30 : 0x10);
318 	}
319 	preqcblk->req_parml = sizeof(struct kgreqparm);
320 
321 	/* fill xcrb struct */
322 	prep_xcrb(&xcrb, cardnr, preqcblk, prepcblk);
323 
324 	/* forward xcrb with request CPRB and reply CPRB to zcrypt dd */
325 	rc = _zcrypt_send_cprb(&xcrb);
326 	if (rc) {
327 		DEBUG_ERR(
328 			"%s zcrypt_send_cprb (cardnr=%d domain=%d) failed with errno %d\n",
329 			__func__, (int) cardnr, (int) domain, rc);
330 		goto out;
331 	}
332 
333 	/* check response returncode and reasoncode */
334 	if (prepcblk->ccp_rtcode != 0) {
335 		DEBUG_ERR(
336 			"%s secure key generate failure, card response %d/%d\n",
337 			__func__,
338 			(int) prepcblk->ccp_rtcode,
339 			(int) prepcblk->ccp_rscode);
340 		rc = -EIO;
341 		goto out;
342 	}
343 
344 	/* process response cprb param block */
345 	prepcblk->rpl_parmb = ((u8 *) prepcblk) + sizeof(struct CPRBX);
346 	prepparm = (struct kgrepparm *) prepcblk->rpl_parmb;
347 
348 	/* check length of the returned secure key token */
349 	seckeysize = prepparm->lv3.keyblock.toklen
350 		- sizeof(prepparm->lv3.keyblock.toklen)
351 		- sizeof(prepparm->lv3.keyblock.tokattr);
352 	if (seckeysize != SECKEYBLOBSIZE) {
353 		DEBUG_ERR(
354 			"%s secure token size mismatch %d != %d bytes\n",
355 			__func__, seckeysize, SECKEYBLOBSIZE);
356 		rc = -EIO;
357 		goto out;
358 	}
359 
360 	/* check secure key token */
361 	rc = check_secaeskeytoken(prepparm->lv3.keyblock.tok, 8*keysize);
362 	if (rc) {
363 		rc = -EIO;
364 		goto out;
365 	}
366 
367 	/* copy the generated secure key token */
368 	memcpy(seckey->seckey, prepparm->lv3.keyblock.tok, SECKEYBLOBSIZE);
369 
370 out:
371 	free_cprbmem(mem, PARMBSIZE, 0);
372 	return rc;
373 }
374 EXPORT_SYMBOL(pkey_genseckey);
375 
376 /*
377  * Generate an AES secure key with given key value.
378  */
379 int pkey_clr2seckey(u16 cardnr, u16 domain, u32 keytype,
380 		    const struct pkey_clrkey *clrkey,
381 		    struct pkey_seckey *seckey)
382 {
383 	int rc, keysize, seckeysize;
384 	u8 *mem;
385 	struct CPRBX *preqcblk, *prepcblk;
386 	struct ica_xcRB xcrb;
387 	struct cmreqparm {
388 		u8  subfunc_code[2];
389 		u16 rule_array_len;
390 		char  rule_array[8];
391 		struct lv1 {
392 			u16 len;
393 			u8  clrkey[0];
394 		} lv1;
395 		struct lv2 {
396 			u16 len;
397 			struct keyid {
398 				u16 len;
399 				u16 attr;
400 				u8  data[SECKEYBLOBSIZE];
401 			} keyid;
402 		} lv2;
403 	} *preqparm;
404 	struct lv2 *plv2;
405 	struct cmrepparm {
406 		u8  subfunc_code[2];
407 		u16 rule_array_len;
408 		struct lv3 {
409 			u16 len;
410 			u16 keyblocklen;
411 			struct {
412 				u16 toklen;
413 				u16 tokattr;
414 				u8  tok[0];
415 				/* ... some more data ... */
416 			} keyblock;
417 		} lv3;
418 	} *prepparm;
419 
420 	/* get already prepared memory for 2 cprbs with param block each */
421 	rc = alloc_and_prep_cprbmem(PARMBSIZE, &mem, &preqcblk, &prepcblk);
422 	if (rc)
423 		return rc;
424 
425 	/* fill request cprb struct */
426 	preqcblk->domain = domain;
427 
428 	/* fill request cprb param block with CM request */
429 	preqparm = (struct cmreqparm *) preqcblk->req_parmb;
430 	memcpy(preqparm->subfunc_code, "CM", 2);
431 	memcpy(preqparm->rule_array, "AES     ", 8);
432 	preqparm->rule_array_len =
433 		sizeof(preqparm->rule_array_len) + sizeof(preqparm->rule_array);
434 	switch (keytype) {
435 	case PKEY_KEYTYPE_AES_128:
436 		keysize = 16;
437 		break;
438 	case PKEY_KEYTYPE_AES_192:
439 		keysize = 24;
440 		break;
441 	case PKEY_KEYTYPE_AES_256:
442 		keysize = 32;
443 		break;
444 	default:
445 		DEBUG_ERR(
446 			"%s unknown/unsupported keytype %d\n",
447 			__func__, keytype);
448 		rc = -EINVAL;
449 		goto out;
450 	}
451 	preqparm->lv1.len = sizeof(struct lv1) + keysize;
452 	memcpy(preqparm->lv1.clrkey, clrkey->clrkey, keysize);
453 	plv2 = (struct lv2 *) (((u8 *) &preqparm->lv2) + keysize);
454 	plv2->len = sizeof(struct lv2);
455 	plv2->keyid.len = sizeof(struct keyid);
456 	plv2->keyid.attr = 0x30;
457 	preqcblk->req_parml = sizeof(struct cmreqparm) + keysize;
458 
459 	/* fill xcrb struct */
460 	prep_xcrb(&xcrb, cardnr, preqcblk, prepcblk);
461 
462 	/* forward xcrb with request CPRB and reply CPRB to zcrypt dd */
463 	rc = _zcrypt_send_cprb(&xcrb);
464 	if (rc) {
465 		DEBUG_ERR(
466 			"%s zcrypt_send_cprb (cardnr=%d domain=%d) failed with errno %d\n",
467 			__func__, (int) cardnr, (int) domain, rc);
468 		goto out;
469 	}
470 
471 	/* check response returncode and reasoncode */
472 	if (prepcblk->ccp_rtcode != 0) {
473 		DEBUG_ERR(
474 			"%s clear key import failure, card response %d/%d\n",
475 			__func__,
476 			(int) prepcblk->ccp_rtcode,
477 			(int) prepcblk->ccp_rscode);
478 		rc = -EIO;
479 		goto out;
480 	}
481 
482 	/* process response cprb param block */
483 	prepcblk->rpl_parmb = ((u8 *) prepcblk) + sizeof(struct CPRBX);
484 	prepparm = (struct cmrepparm *) prepcblk->rpl_parmb;
485 
486 	/* check length of the returned secure key token */
487 	seckeysize = prepparm->lv3.keyblock.toklen
488 		- sizeof(prepparm->lv3.keyblock.toklen)
489 		- sizeof(prepparm->lv3.keyblock.tokattr);
490 	if (seckeysize != SECKEYBLOBSIZE) {
491 		DEBUG_ERR(
492 			"%s secure token size mismatch %d != %d bytes\n",
493 			__func__, seckeysize, SECKEYBLOBSIZE);
494 		rc = -EIO;
495 		goto out;
496 	}
497 
498 	/* check secure key token */
499 	rc = check_secaeskeytoken(prepparm->lv3.keyblock.tok, 8*keysize);
500 	if (rc) {
501 		rc = -EIO;
502 		goto out;
503 	}
504 
505 	/* copy the generated secure key token */
506 	memcpy(seckey->seckey, prepparm->lv3.keyblock.tok, SECKEYBLOBSIZE);
507 
508 out:
509 	free_cprbmem(mem, PARMBSIZE, 1);
510 	return rc;
511 }
512 EXPORT_SYMBOL(pkey_clr2seckey);
513 
514 /*
515  * Derive a proteced key from the secure key blob.
516  */
517 int pkey_sec2protkey(u16 cardnr, u16 domain,
518 		     const struct pkey_seckey *seckey,
519 		     struct pkey_protkey *protkey)
520 {
521 	int rc;
522 	u8 *mem;
523 	struct CPRBX *preqcblk, *prepcblk;
524 	struct ica_xcRB xcrb;
525 	struct uskreqparm {
526 		u8  subfunc_code[2];
527 		u16 rule_array_len;
528 		struct lv1 {
529 			u16 len;
530 			u16 attr_len;
531 			u16 attr_flags;
532 		} lv1;
533 		struct lv2 {
534 			u16 len;
535 			u16 attr_len;
536 			u16 attr_flags;
537 			u8  token[0];	      /* cca secure key token */
538 		} lv2 __packed;
539 	} *preqparm;
540 	struct uskrepparm {
541 		u8  subfunc_code[2];
542 		u16 rule_array_len;
543 		struct lv3 {
544 			u16 len;
545 			u16 attr_len;
546 			u16 attr_flags;
547 			struct cpacfkeyblock {
548 				u8  version;  /* version of this struct */
549 				u8  flags[2];
550 				u8  algo;
551 				u8  form;
552 				u8  pad1[3];
553 				u16 keylen;
554 				u8  key[64];  /* the key (keylen bytes) */
555 				u16 keyattrlen;
556 				u8  keyattr[32];
557 				u8  pad2[1];
558 				u8  vptype;
559 				u8  vp[32];  /* verification pattern */
560 			} keyblock;
561 		} lv3 __packed;
562 	} *prepparm;
563 
564 	/* get already prepared memory for 2 cprbs with param block each */
565 	rc = alloc_and_prep_cprbmem(PARMBSIZE, &mem, &preqcblk, &prepcblk);
566 	if (rc)
567 		return rc;
568 
569 	/* fill request cprb struct */
570 	preqcblk->domain = domain;
571 
572 	/* fill request cprb param block with USK request */
573 	preqparm = (struct uskreqparm *) preqcblk->req_parmb;
574 	memcpy(preqparm->subfunc_code, "US", 2);
575 	preqparm->rule_array_len = sizeof(preqparm->rule_array_len);
576 	preqparm->lv1.len = sizeof(struct lv1);
577 	preqparm->lv1.attr_len = sizeof(struct lv1) - sizeof(preqparm->lv1.len);
578 	preqparm->lv1.attr_flags = 0x0001;
579 	preqparm->lv2.len = sizeof(struct lv2) + SECKEYBLOBSIZE;
580 	preqparm->lv2.attr_len = sizeof(struct lv2)
581 		- sizeof(preqparm->lv2.len) + SECKEYBLOBSIZE;
582 	preqparm->lv2.attr_flags = 0x0000;
583 	memcpy(preqparm->lv2.token, seckey->seckey, SECKEYBLOBSIZE);
584 	preqcblk->req_parml = sizeof(struct uskreqparm) + SECKEYBLOBSIZE;
585 
586 	/* fill xcrb struct */
587 	prep_xcrb(&xcrb, cardnr, preqcblk, prepcblk);
588 
589 	/* forward xcrb with request CPRB and reply CPRB to zcrypt dd */
590 	rc = _zcrypt_send_cprb(&xcrb);
591 	if (rc) {
592 		DEBUG_ERR(
593 			"%s zcrypt_send_cprb (cardnr=%d domain=%d) failed with errno %d\n",
594 			__func__, (int) cardnr, (int) domain, rc);
595 		goto out;
596 	}
597 
598 	/* check response returncode and reasoncode */
599 	if (prepcblk->ccp_rtcode != 0) {
600 		DEBUG_ERR(
601 			"%s unwrap secure key failure, card response %d/%d\n",
602 			__func__,
603 			(int) prepcblk->ccp_rtcode,
604 			(int) prepcblk->ccp_rscode);
605 		rc = -EIO;
606 		goto out;
607 	}
608 	if (prepcblk->ccp_rscode != 0) {
609 		DEBUG_WARN(
610 			"%s unwrap secure key warning, card response %d/%d\n",
611 			__func__,
612 			(int) prepcblk->ccp_rtcode,
613 			(int) prepcblk->ccp_rscode);
614 	}
615 
616 	/* process response cprb param block */
617 	prepcblk->rpl_parmb = ((u8 *) prepcblk) + sizeof(struct CPRBX);
618 	prepparm = (struct uskrepparm *) prepcblk->rpl_parmb;
619 
620 	/* check the returned keyblock */
621 	if (prepparm->lv3.keyblock.version != 0x01) {
622 		DEBUG_ERR(
623 			"%s reply param keyblock version mismatch 0x%02x != 0x01\n",
624 			__func__, (int) prepparm->lv3.keyblock.version);
625 		rc = -EIO;
626 		goto out;
627 	}
628 
629 	/* copy the tanslated protected key */
630 	switch (prepparm->lv3.keyblock.keylen) {
631 	case 16+32:
632 		protkey->type = PKEY_KEYTYPE_AES_128;
633 		break;
634 	case 24+32:
635 		protkey->type = PKEY_KEYTYPE_AES_192;
636 		break;
637 	case 32+32:
638 		protkey->type = PKEY_KEYTYPE_AES_256;
639 		break;
640 	default:
641 		DEBUG_ERR("%s unknown/unsupported keytype %d\n",
642 			  __func__, prepparm->lv3.keyblock.keylen);
643 		rc = -EIO;
644 		goto out;
645 	}
646 	protkey->len = prepparm->lv3.keyblock.keylen;
647 	memcpy(protkey->protkey, prepparm->lv3.keyblock.key, protkey->len);
648 
649 out:
650 	free_cprbmem(mem, PARMBSIZE, 0);
651 	return rc;
652 }
653 EXPORT_SYMBOL(pkey_sec2protkey);
654 
655 /*
656  * Create a protected key from a clear key value.
657  */
658 int pkey_clr2protkey(u32 keytype,
659 		     const struct pkey_clrkey *clrkey,
660 		     struct pkey_protkey *protkey)
661 {
662 	long fc;
663 	int keysize;
664 	u8 paramblock[64];
665 
666 	switch (keytype) {
667 	case PKEY_KEYTYPE_AES_128:
668 		keysize = 16;
669 		fc = CPACF_PCKMO_ENC_AES_128_KEY;
670 		break;
671 	case PKEY_KEYTYPE_AES_192:
672 		keysize = 24;
673 		fc = CPACF_PCKMO_ENC_AES_192_KEY;
674 		break;
675 	case PKEY_KEYTYPE_AES_256:
676 		keysize = 32;
677 		fc = CPACF_PCKMO_ENC_AES_256_KEY;
678 		break;
679 	default:
680 		DEBUG_ERR("%s unknown/unsupported keytype %d\n",
681 			  __func__, keytype);
682 		return -EINVAL;
683 	}
684 
685 	/*
686 	 * Check if the needed pckmo subfunction is available.
687 	 * These subfunctions can be enabled/disabled by customers
688 	 * in the LPAR profile or may even change on the fly.
689 	 */
690 	if (!cpacf_test_func(&pckmo_functions, fc)) {
691 		DEBUG_ERR("%s pckmo functions not available\n", __func__);
692 		return -EOPNOTSUPP;
693 	}
694 
695 	/* prepare param block */
696 	memset(paramblock, 0, sizeof(paramblock));
697 	memcpy(paramblock, clrkey->clrkey, keysize);
698 
699 	/* call the pckmo instruction */
700 	cpacf_pckmo(fc, paramblock);
701 
702 	/* copy created protected key */
703 	protkey->type = keytype;
704 	protkey->len = keysize + 32;
705 	memcpy(protkey->protkey, paramblock, keysize + 32);
706 
707 	return 0;
708 }
709 EXPORT_SYMBOL(pkey_clr2protkey);
710 
711 /*
712  * query cryptographic facility from adapter
713  */
714 static int query_crypto_facility(u16 cardnr, u16 domain,
715 				 const char *keyword,
716 				 u8 *rarray, size_t *rarraylen,
717 				 u8 *varray, size_t *varraylen)
718 {
719 	int rc;
720 	u16 len;
721 	u8 *mem, *ptr;
722 	struct CPRBX *preqcblk, *prepcblk;
723 	struct ica_xcRB xcrb;
724 	struct fqreqparm {
725 		u8  subfunc_code[2];
726 		u16 rule_array_len;
727 		char  rule_array[8];
728 		struct lv1 {
729 			u16 len;
730 			u8  data[VARDATASIZE];
731 		} lv1;
732 		u16 dummylen;
733 	} *preqparm;
734 	size_t parmbsize = sizeof(struct fqreqparm);
735 	struct fqrepparm {
736 		u8  subfunc_code[2];
737 		u8  lvdata[0];
738 	} *prepparm;
739 
740 	/* get already prepared memory for 2 cprbs with param block each */
741 	rc = alloc_and_prep_cprbmem(parmbsize, &mem, &preqcblk, &prepcblk);
742 	if (rc)
743 		return rc;
744 
745 	/* fill request cprb struct */
746 	preqcblk->domain = domain;
747 
748 	/* fill request cprb param block with FQ request */
749 	preqparm = (struct fqreqparm *) preqcblk->req_parmb;
750 	memcpy(preqparm->subfunc_code, "FQ", 2);
751 	memcpy(preqparm->rule_array, keyword, sizeof(preqparm->rule_array));
752 	preqparm->rule_array_len =
753 		sizeof(preqparm->rule_array_len) + sizeof(preqparm->rule_array);
754 	preqparm->lv1.len = sizeof(preqparm->lv1);
755 	preqparm->dummylen = sizeof(preqparm->dummylen);
756 	preqcblk->req_parml = parmbsize;
757 
758 	/* fill xcrb struct */
759 	prep_xcrb(&xcrb, cardnr, preqcblk, prepcblk);
760 
761 	/* forward xcrb with request CPRB and reply CPRB to zcrypt dd */
762 	rc = _zcrypt_send_cprb(&xcrb);
763 	if (rc) {
764 		DEBUG_ERR(
765 			"%s zcrypt_send_cprb (cardnr=%d domain=%d) failed with errno %d\n",
766 			__func__, (int) cardnr, (int) domain, rc);
767 		goto out;
768 	}
769 
770 	/* check response returncode and reasoncode */
771 	if (prepcblk->ccp_rtcode != 0) {
772 		DEBUG_ERR(
773 			"%s unwrap secure key failure, card response %d/%d\n",
774 			__func__,
775 			(int) prepcblk->ccp_rtcode,
776 			(int) prepcblk->ccp_rscode);
777 		rc = -EIO;
778 		goto out;
779 	}
780 
781 	/* process response cprb param block */
782 	prepcblk->rpl_parmb = ((u8 *) prepcblk) + sizeof(struct CPRBX);
783 	prepparm = (struct fqrepparm *) prepcblk->rpl_parmb;
784 	ptr = prepparm->lvdata;
785 
786 	/* check and possibly copy reply rule array */
787 	len = *((u16 *) ptr);
788 	if (len > sizeof(u16)) {
789 		ptr += sizeof(u16);
790 		len -= sizeof(u16);
791 		if (rarray && rarraylen && *rarraylen > 0) {
792 			*rarraylen = (len > *rarraylen ? *rarraylen : len);
793 			memcpy(rarray, ptr, *rarraylen);
794 		}
795 		ptr += len;
796 	}
797 	/* check and possible copy reply var array */
798 	len = *((u16 *) ptr);
799 	if (len > sizeof(u16)) {
800 		ptr += sizeof(u16);
801 		len -= sizeof(u16);
802 		if (varray && varraylen && *varraylen > 0) {
803 			*varraylen = (len > *varraylen ? *varraylen : len);
804 			memcpy(varray, ptr, *varraylen);
805 		}
806 		ptr += len;
807 	}
808 
809 out:
810 	free_cprbmem(mem, parmbsize, 0);
811 	return rc;
812 }
813 
814 /*
815  * Fetch the current and old mkvp values via
816  * query_crypto_facility from adapter.
817  */
818 static int fetch_mkvp(u16 cardnr, u16 domain, u64 mkvp[2])
819 {
820 	int rc, found = 0;
821 	size_t rlen, vlen;
822 	u8 *rarray, *varray, *pg;
823 
824 	pg = (u8 *) __get_free_page(GFP_KERNEL);
825 	if (!pg)
826 		return -ENOMEM;
827 	rarray = pg;
828 	varray = pg + PAGE_SIZE/2;
829 	rlen = vlen = PAGE_SIZE/2;
830 
831 	rc = query_crypto_facility(cardnr, domain, "STATICSA",
832 				   rarray, &rlen, varray, &vlen);
833 	if (rc == 0 && rlen > 8*8 && vlen > 184+8) {
834 		if (rarray[8*8] == '2') {
835 			/* current master key state is valid */
836 			mkvp[0] = *((u64 *)(varray + 184));
837 			mkvp[1] = *((u64 *)(varray + 172));
838 			found = 1;
839 		}
840 	}
841 
842 	free_page((unsigned long) pg);
843 
844 	return found ? 0 : -ENOENT;
845 }
846 
847 /* struct to hold cached mkvp info for each card/domain */
848 struct mkvp_info {
849 	struct list_head list;
850 	u16 cardnr;
851 	u16 domain;
852 	u64 mkvp[2];
853 };
854 
855 /* a list with mkvp_info entries */
856 static LIST_HEAD(mkvp_list);
857 static DEFINE_SPINLOCK(mkvp_list_lock);
858 
859 static int mkvp_cache_fetch(u16 cardnr, u16 domain, u64 mkvp[2])
860 {
861 	int rc = -ENOENT;
862 	struct mkvp_info *ptr;
863 
864 	spin_lock_bh(&mkvp_list_lock);
865 	list_for_each_entry(ptr, &mkvp_list, list) {
866 		if (ptr->cardnr == cardnr &&
867 		    ptr->domain == domain) {
868 			memcpy(mkvp, ptr->mkvp, 2 * sizeof(u64));
869 			rc = 0;
870 			break;
871 		}
872 	}
873 	spin_unlock_bh(&mkvp_list_lock);
874 
875 	return rc;
876 }
877 
878 static void mkvp_cache_update(u16 cardnr, u16 domain, u64 mkvp[2])
879 {
880 	int found = 0;
881 	struct mkvp_info *ptr;
882 
883 	spin_lock_bh(&mkvp_list_lock);
884 	list_for_each_entry(ptr, &mkvp_list, list) {
885 		if (ptr->cardnr == cardnr &&
886 		    ptr->domain == domain) {
887 			memcpy(ptr->mkvp, mkvp, 2 * sizeof(u64));
888 			found = 1;
889 			break;
890 		}
891 	}
892 	if (!found) {
893 		ptr = kmalloc(sizeof(*ptr), GFP_ATOMIC);
894 		if (!ptr) {
895 			spin_unlock_bh(&mkvp_list_lock);
896 			return;
897 		}
898 		ptr->cardnr = cardnr;
899 		ptr->domain = domain;
900 		memcpy(ptr->mkvp, mkvp, 2 * sizeof(u64));
901 		list_add(&ptr->list, &mkvp_list);
902 	}
903 	spin_unlock_bh(&mkvp_list_lock);
904 }
905 
906 static void mkvp_cache_scrub(u16 cardnr, u16 domain)
907 {
908 	struct mkvp_info *ptr;
909 
910 	spin_lock_bh(&mkvp_list_lock);
911 	list_for_each_entry(ptr, &mkvp_list, list) {
912 		if (ptr->cardnr == cardnr &&
913 		    ptr->domain == domain) {
914 			list_del(&ptr->list);
915 			kfree(ptr);
916 			break;
917 		}
918 	}
919 	spin_unlock_bh(&mkvp_list_lock);
920 }
921 
922 static void __exit mkvp_cache_free(void)
923 {
924 	struct mkvp_info *ptr, *pnext;
925 
926 	spin_lock_bh(&mkvp_list_lock);
927 	list_for_each_entry_safe(ptr, pnext, &mkvp_list, list) {
928 		list_del(&ptr->list);
929 		kfree(ptr);
930 	}
931 	spin_unlock_bh(&mkvp_list_lock);
932 }
933 
934 /*
935  * Search for a matching crypto card based on the Master Key
936  * Verification Pattern provided inside a secure key.
937  */
938 int pkey_findcard(const struct pkey_seckey *seckey,
939 		  u16 *pcardnr, u16 *pdomain, int verify)
940 {
941 	struct secaeskeytoken *t = (struct secaeskeytoken *) seckey;
942 	struct zcrypt_device_status_ext *device_status;
943 	u16 card, dom;
944 	u64 mkvp[2];
945 	int i, rc, oi = -1;
946 
947 	/* mkvp must not be zero */
948 	if (t->mkvp == 0)
949 		return -EINVAL;
950 
951 	/* fetch status of all crypto cards */
952 	device_status = kmalloc_array(MAX_ZDEV_ENTRIES_EXT,
953 				      sizeof(struct zcrypt_device_status_ext),
954 				      GFP_KERNEL);
955 	if (!device_status)
956 		return -ENOMEM;
957 	zcrypt_device_status_mask_ext(device_status);
958 
959 	/* walk through all crypto cards */
960 	for (i = 0; i < MAX_ZDEV_ENTRIES_EXT; i++) {
961 		card = AP_QID_CARD(device_status[i].qid);
962 		dom = AP_QID_QUEUE(device_status[i].qid);
963 		if (device_status[i].online &&
964 		    device_status[i].functions & 0x04) {
965 			/* an enabled CCA Coprocessor card */
966 			/* try cached mkvp */
967 			if (mkvp_cache_fetch(card, dom, mkvp) == 0 &&
968 			    t->mkvp == mkvp[0]) {
969 				if (!verify)
970 					break;
971 				/* verify: fetch mkvp from adapter */
972 				if (fetch_mkvp(card, dom, mkvp) == 0) {
973 					mkvp_cache_update(card, dom, mkvp);
974 					if (t->mkvp == mkvp[0])
975 						break;
976 				}
977 			}
978 		} else {
979 			/* Card is offline and/or not a CCA card. */
980 			/* del mkvp entry from cache if it exists */
981 			mkvp_cache_scrub(card, dom);
982 		}
983 	}
984 	if (i >= MAX_ZDEV_ENTRIES_EXT) {
985 		/* nothing found, so this time without cache */
986 		for (i = 0; i < MAX_ZDEV_ENTRIES_EXT; i++) {
987 			if (!(device_status[i].online &&
988 			      device_status[i].functions & 0x04))
989 				continue;
990 			card = AP_QID_CARD(device_status[i].qid);
991 			dom = AP_QID_QUEUE(device_status[i].qid);
992 			/* fresh fetch mkvp from adapter */
993 			if (fetch_mkvp(card, dom, mkvp) == 0) {
994 				mkvp_cache_update(card, dom, mkvp);
995 				if (t->mkvp == mkvp[0])
996 					break;
997 				if (t->mkvp == mkvp[1] && oi < 0)
998 					oi = i;
999 			}
1000 		}
1001 		if (i >= MAX_ZDEV_ENTRIES_EXT && oi >= 0) {
1002 			/* old mkvp matched, use this card then */
1003 			card = AP_QID_CARD(device_status[oi].qid);
1004 			dom = AP_QID_QUEUE(device_status[oi].qid);
1005 		}
1006 	}
1007 	if (i < MAX_ZDEV_ENTRIES_EXT || oi >= 0) {
1008 		if (pcardnr)
1009 			*pcardnr = card;
1010 		if (pdomain)
1011 			*pdomain = dom;
1012 		rc = 0;
1013 	} else
1014 		rc = -ENODEV;
1015 
1016 	kfree(device_status);
1017 	return rc;
1018 }
1019 EXPORT_SYMBOL(pkey_findcard);
1020 
1021 /*
1022  * Find card and transform secure key into protected key.
1023  */
1024 int pkey_skey2pkey(const struct pkey_seckey *seckey,
1025 		   struct pkey_protkey *protkey)
1026 {
1027 	u16 cardnr, domain;
1028 	int rc, verify;
1029 
1030 	/*
1031 	 * The pkey_sec2protkey call may fail when a card has been
1032 	 * addressed where the master key was changed after last fetch
1033 	 * of the mkvp into the cache. So first try without verify then
1034 	 * with verify enabled (thus refreshing the mkvp for each card).
1035 	 */
1036 	for (verify = 0; verify < 2; verify++) {
1037 		rc = pkey_findcard(seckey, &cardnr, &domain, verify);
1038 		if (rc)
1039 			continue;
1040 		rc = pkey_sec2protkey(cardnr, domain, seckey, protkey);
1041 		if (rc == 0)
1042 			break;
1043 	}
1044 
1045 	if (rc)
1046 		DEBUG_DBG("%s failed rc=%d\n", __func__, rc);
1047 
1048 	return rc;
1049 }
1050 EXPORT_SYMBOL(pkey_skey2pkey);
1051 
1052 /*
1053  * Verify key and give back some info about the key.
1054  */
1055 int pkey_verifykey(const struct pkey_seckey *seckey,
1056 		   u16 *pcardnr, u16 *pdomain,
1057 		   u16 *pkeysize, u32 *pattributes)
1058 {
1059 	struct secaeskeytoken *t = (struct secaeskeytoken *) seckey;
1060 	u16 cardnr, domain;
1061 	u64 mkvp[2];
1062 	int rc;
1063 
1064 	/* check the secure key for valid AES secure key */
1065 	rc = check_secaeskeytoken((u8 *) seckey, 0);
1066 	if (rc)
1067 		goto out;
1068 	if (pattributes)
1069 		*pattributes = PKEY_VERIFY_ATTR_AES;
1070 	if (pkeysize)
1071 		*pkeysize = t->bitsize;
1072 
1073 	/* try to find a card which can handle this key */
1074 	rc = pkey_findcard(seckey, &cardnr, &domain, 1);
1075 	if (rc)
1076 		goto out;
1077 
1078 	/* check mkvp for old mkvp match */
1079 	rc = mkvp_cache_fetch(cardnr, domain, mkvp);
1080 	if (rc)
1081 		goto out;
1082 	if (t->mkvp == mkvp[1] && t->mkvp != mkvp[0]) {
1083 		DEBUG_DBG("%s secure key has old mkvp\n", __func__);
1084 		if (pattributes)
1085 			*pattributes |= PKEY_VERIFY_ATTR_OLD_MKVP;
1086 	}
1087 
1088 	if (pcardnr)
1089 		*pcardnr = cardnr;
1090 	if (pdomain)
1091 		*pdomain = domain;
1092 
1093 out:
1094 	DEBUG_DBG("%s rc=%d\n", __func__, rc);
1095 	return rc;
1096 }
1097 EXPORT_SYMBOL(pkey_verifykey);
1098 
1099 /*
1100  * Generate a random protected key
1101  */
1102 int pkey_genprotkey(__u32 keytype, struct pkey_protkey *protkey)
1103 {
1104 	struct pkey_clrkey clrkey;
1105 	int keysize;
1106 	int rc;
1107 
1108 	switch (keytype) {
1109 	case PKEY_KEYTYPE_AES_128:
1110 		keysize = 16;
1111 		break;
1112 	case PKEY_KEYTYPE_AES_192:
1113 		keysize = 24;
1114 		break;
1115 	case PKEY_KEYTYPE_AES_256:
1116 		keysize = 32;
1117 		break;
1118 	default:
1119 		DEBUG_ERR("%s unknown/unsupported keytype %d\n", __func__,
1120 			  keytype);
1121 		return -EINVAL;
1122 	}
1123 
1124 	/* generate a dummy random clear key */
1125 	get_random_bytes(clrkey.clrkey, keysize);
1126 
1127 	/* convert it to a dummy protected key */
1128 	rc = pkey_clr2protkey(keytype, &clrkey, protkey);
1129 	if (rc)
1130 		return rc;
1131 
1132 	/* replace the key part of the protected key with random bytes */
1133 	get_random_bytes(protkey->protkey, keysize);
1134 
1135 	return 0;
1136 }
1137 EXPORT_SYMBOL(pkey_genprotkey);
1138 
1139 /*
1140  * Verify if a protected key is still valid
1141  */
1142 int pkey_verifyprotkey(const struct pkey_protkey *protkey)
1143 {
1144 	unsigned long fc;
1145 	struct {
1146 		u8 iv[AES_BLOCK_SIZE];
1147 		u8 key[MAXPROTKEYSIZE];
1148 	} param;
1149 	u8 null_msg[AES_BLOCK_SIZE];
1150 	u8 dest_buf[AES_BLOCK_SIZE];
1151 	unsigned int k;
1152 
1153 	switch (protkey->type) {
1154 	case PKEY_KEYTYPE_AES_128:
1155 		fc = CPACF_KMC_PAES_128;
1156 		break;
1157 	case PKEY_KEYTYPE_AES_192:
1158 		fc = CPACF_KMC_PAES_192;
1159 		break;
1160 	case PKEY_KEYTYPE_AES_256:
1161 		fc = CPACF_KMC_PAES_256;
1162 		break;
1163 	default:
1164 		DEBUG_ERR("%s unknown/unsupported keytype %d\n", __func__,
1165 			  protkey->type);
1166 		return -EINVAL;
1167 	}
1168 
1169 	memset(null_msg, 0, sizeof(null_msg));
1170 
1171 	memset(param.iv, 0, sizeof(param.iv));
1172 	memcpy(param.key, protkey->protkey, sizeof(param.key));
1173 
1174 	k = cpacf_kmc(fc | CPACF_ENCRYPT, &param, null_msg, dest_buf,
1175 		      sizeof(null_msg));
1176 	if (k != sizeof(null_msg)) {
1177 		DEBUG_ERR("%s protected key is not valid\n", __func__);
1178 		return -EKEYREJECTED;
1179 	}
1180 
1181 	return 0;
1182 }
1183 EXPORT_SYMBOL(pkey_verifyprotkey);
1184 
1185 /*
1186  * Transform a non-CCA key token into a protected key
1187  */
1188 static int pkey_nonccatok2pkey(const __u8 *key, __u32 keylen,
1189 			       struct pkey_protkey *protkey)
1190 {
1191 	struct keytoken_header *hdr = (struct keytoken_header *)key;
1192 	struct protaeskeytoken *t;
1193 
1194 	switch (hdr->version) {
1195 	case TOKVER_PROTECTED_KEY:
1196 		if (keylen != sizeof(struct protaeskeytoken))
1197 			return -EINVAL;
1198 
1199 		t = (struct protaeskeytoken *)key;
1200 		protkey->len = t->len;
1201 		protkey->type = t->keytype;
1202 		memcpy(protkey->protkey, t->protkey,
1203 		       sizeof(protkey->protkey));
1204 
1205 		return pkey_verifyprotkey(protkey);
1206 	default:
1207 		DEBUG_ERR("%s unknown/unsupported non-CCA token version %d\n",
1208 			  __func__, hdr->version);
1209 		return -EINVAL;
1210 	}
1211 }
1212 
1213 /*
1214  * Transform a CCA internal key token into a protected key
1215  */
1216 static int pkey_ccainttok2pkey(const __u8 *key, __u32 keylen,
1217 			       struct pkey_protkey *protkey)
1218 {
1219 	struct keytoken_header *hdr = (struct keytoken_header *)key;
1220 
1221 	switch (hdr->version) {
1222 	case TOKVER_CCA_AES:
1223 		if (keylen != sizeof(struct secaeskeytoken))
1224 			return -EINVAL;
1225 
1226 		return pkey_skey2pkey((struct pkey_seckey *)key,
1227 				      protkey);
1228 	default:
1229 		DEBUG_ERR("%s unknown/unsupported CCA internal token version %d\n",
1230 			  __func__, hdr->version);
1231 		return -EINVAL;
1232 	}
1233 }
1234 
1235 /*
1236  * Transform a key blob (of any type) into a protected key
1237  */
1238 int pkey_keyblob2pkey(const __u8 *key, __u32 keylen,
1239 		      struct pkey_protkey *protkey)
1240 {
1241 	struct keytoken_header *hdr = (struct keytoken_header *)key;
1242 
1243 	if (keylen < sizeof(struct keytoken_header))
1244 		return -EINVAL;
1245 
1246 	switch (hdr->type) {
1247 	case TOKTYPE_NON_CCA:
1248 		return pkey_nonccatok2pkey(key, keylen, protkey);
1249 	case TOKTYPE_CCA_INTERNAL:
1250 		return pkey_ccainttok2pkey(key, keylen, protkey);
1251 	default:
1252 		DEBUG_ERR("%s unknown/unsupported blob type %d\n", __func__,
1253 			  hdr->type);
1254 		return -EINVAL;
1255 	}
1256 }
1257 EXPORT_SYMBOL(pkey_keyblob2pkey);
1258 
1259 /*
1260  * File io functions
1261  */
1262 
1263 static long pkey_unlocked_ioctl(struct file *filp, unsigned int cmd,
1264 				unsigned long arg)
1265 {
1266 	int rc;
1267 
1268 	switch (cmd) {
1269 	case PKEY_GENSECK: {
1270 		struct pkey_genseck __user *ugs = (void __user *) arg;
1271 		struct pkey_genseck kgs;
1272 
1273 		if (copy_from_user(&kgs, ugs, sizeof(kgs)))
1274 			return -EFAULT;
1275 		rc = pkey_genseckey(kgs.cardnr, kgs.domain,
1276 				    kgs.keytype, &kgs.seckey);
1277 		DEBUG_DBG("%s pkey_genseckey()=%d\n", __func__, rc);
1278 		if (rc)
1279 			break;
1280 		if (copy_to_user(ugs, &kgs, sizeof(kgs)))
1281 			return -EFAULT;
1282 		break;
1283 	}
1284 	case PKEY_CLR2SECK: {
1285 		struct pkey_clr2seck __user *ucs = (void __user *) arg;
1286 		struct pkey_clr2seck kcs;
1287 
1288 		if (copy_from_user(&kcs, ucs, sizeof(kcs)))
1289 			return -EFAULT;
1290 		rc = pkey_clr2seckey(kcs.cardnr, kcs.domain, kcs.keytype,
1291 				     &kcs.clrkey, &kcs.seckey);
1292 		DEBUG_DBG("%s pkey_clr2seckey()=%d\n", __func__, rc);
1293 		if (rc)
1294 			break;
1295 		if (copy_to_user(ucs, &kcs, sizeof(kcs)))
1296 			return -EFAULT;
1297 		memzero_explicit(&kcs, sizeof(kcs));
1298 		break;
1299 	}
1300 	case PKEY_SEC2PROTK: {
1301 		struct pkey_sec2protk __user *usp = (void __user *) arg;
1302 		struct pkey_sec2protk ksp;
1303 
1304 		if (copy_from_user(&ksp, usp, sizeof(ksp)))
1305 			return -EFAULT;
1306 		rc = pkey_sec2protkey(ksp.cardnr, ksp.domain,
1307 				      &ksp.seckey, &ksp.protkey);
1308 		DEBUG_DBG("%s pkey_sec2protkey()=%d\n", __func__, rc);
1309 		if (rc)
1310 			break;
1311 		if (copy_to_user(usp, &ksp, sizeof(ksp)))
1312 			return -EFAULT;
1313 		break;
1314 	}
1315 	case PKEY_CLR2PROTK: {
1316 		struct pkey_clr2protk __user *ucp = (void __user *) arg;
1317 		struct pkey_clr2protk kcp;
1318 
1319 		if (copy_from_user(&kcp, ucp, sizeof(kcp)))
1320 			return -EFAULT;
1321 		rc = pkey_clr2protkey(kcp.keytype,
1322 				      &kcp.clrkey, &kcp.protkey);
1323 		DEBUG_DBG("%s pkey_clr2protkey()=%d\n", __func__, rc);
1324 		if (rc)
1325 			break;
1326 		if (copy_to_user(ucp, &kcp, sizeof(kcp)))
1327 			return -EFAULT;
1328 		memzero_explicit(&kcp, sizeof(kcp));
1329 		break;
1330 	}
1331 	case PKEY_FINDCARD: {
1332 		struct pkey_findcard __user *ufc = (void __user *) arg;
1333 		struct pkey_findcard kfc;
1334 
1335 		if (copy_from_user(&kfc, ufc, sizeof(kfc)))
1336 			return -EFAULT;
1337 		rc = pkey_findcard(&kfc.seckey,
1338 				   &kfc.cardnr, &kfc.domain, 1);
1339 		DEBUG_DBG("%s pkey_findcard()=%d\n", __func__, rc);
1340 		if (rc)
1341 			break;
1342 		if (copy_to_user(ufc, &kfc, sizeof(kfc)))
1343 			return -EFAULT;
1344 		break;
1345 	}
1346 	case PKEY_SKEY2PKEY: {
1347 		struct pkey_skey2pkey __user *usp = (void __user *) arg;
1348 		struct pkey_skey2pkey ksp;
1349 
1350 		if (copy_from_user(&ksp, usp, sizeof(ksp)))
1351 			return -EFAULT;
1352 		rc = pkey_skey2pkey(&ksp.seckey, &ksp.protkey);
1353 		DEBUG_DBG("%s pkey_skey2pkey()=%d\n", __func__, rc);
1354 		if (rc)
1355 			break;
1356 		if (copy_to_user(usp, &ksp, sizeof(ksp)))
1357 			return -EFAULT;
1358 		break;
1359 	}
1360 	case PKEY_VERIFYKEY: {
1361 		struct pkey_verifykey __user *uvk = (void __user *) arg;
1362 		struct pkey_verifykey kvk;
1363 
1364 		if (copy_from_user(&kvk, uvk, sizeof(kvk)))
1365 			return -EFAULT;
1366 		rc = pkey_verifykey(&kvk.seckey, &kvk.cardnr, &kvk.domain,
1367 				    &kvk.keysize, &kvk.attributes);
1368 		DEBUG_DBG("%s pkey_verifykey()=%d\n", __func__, rc);
1369 		if (rc)
1370 			break;
1371 		if (copy_to_user(uvk, &kvk, sizeof(kvk)))
1372 			return -EFAULT;
1373 		break;
1374 	}
1375 	case PKEY_GENPROTK: {
1376 		struct pkey_genprotk __user *ugp = (void __user *) arg;
1377 		struct pkey_genprotk kgp;
1378 
1379 		if (copy_from_user(&kgp, ugp, sizeof(kgp)))
1380 			return -EFAULT;
1381 		rc = pkey_genprotkey(kgp.keytype, &kgp.protkey);
1382 		DEBUG_DBG("%s pkey_genprotkey()=%d\n", __func__, rc);
1383 		if (rc)
1384 			break;
1385 		if (copy_to_user(ugp, &kgp, sizeof(kgp)))
1386 			return -EFAULT;
1387 		break;
1388 	}
1389 	case PKEY_VERIFYPROTK: {
1390 		struct pkey_verifyprotk __user *uvp = (void __user *) arg;
1391 		struct pkey_verifyprotk kvp;
1392 
1393 		if (copy_from_user(&kvp, uvp, sizeof(kvp)))
1394 			return -EFAULT;
1395 		rc = pkey_verifyprotkey(&kvp.protkey);
1396 		DEBUG_DBG("%s pkey_verifyprotkey()=%d\n", __func__, rc);
1397 		break;
1398 	}
1399 	case PKEY_KBLOB2PROTK: {
1400 		struct pkey_kblob2pkey __user *utp = (void __user *) arg;
1401 		struct pkey_kblob2pkey ktp;
1402 		__u8 __user *ukey;
1403 		__u8 *kkey;
1404 
1405 		if (copy_from_user(&ktp, utp, sizeof(ktp)))
1406 			return -EFAULT;
1407 		if (ktp.keylen < MINKEYBLOBSIZE ||
1408 		    ktp.keylen > MAXKEYBLOBSIZE)
1409 			return -EINVAL;
1410 		ukey = ktp.key;
1411 		kkey = kmalloc(ktp.keylen, GFP_KERNEL);
1412 		if (kkey == NULL)
1413 			return -ENOMEM;
1414 		if (copy_from_user(kkey, ukey, ktp.keylen)) {
1415 			kfree(kkey);
1416 			return -EFAULT;
1417 		}
1418 		rc = pkey_keyblob2pkey(kkey, ktp.keylen, &ktp.protkey);
1419 		DEBUG_DBG("%s pkey_keyblob2pkey()=%d\n", __func__, rc);
1420 		kfree(kkey);
1421 		if (rc)
1422 			break;
1423 		if (copy_to_user(utp, &ktp, sizeof(ktp)))
1424 			return -EFAULT;
1425 		break;
1426 	}
1427 	default:
1428 		/* unknown/unsupported ioctl cmd */
1429 		return -ENOTTY;
1430 	}
1431 
1432 	return rc;
1433 }
1434 
1435 /*
1436  * Sysfs and file io operations
1437  */
1438 
1439 /*
1440  * Sysfs attribute read function for all protected key binary attributes.
1441  * The implementation can not deal with partial reads, because a new random
1442  * protected key blob is generated with each read. In case of partial reads
1443  * (i.e. off != 0 or count < key blob size) -EINVAL is returned.
1444  */
1445 static ssize_t pkey_protkey_aes_attr_read(u32 keytype, bool is_xts, char *buf,
1446 					  loff_t off, size_t count)
1447 {
1448 	struct protaeskeytoken protkeytoken;
1449 	struct pkey_protkey protkey;
1450 	int rc;
1451 
1452 	if (off != 0 || count < sizeof(protkeytoken))
1453 		return -EINVAL;
1454 	if (is_xts)
1455 		if (count < 2 * sizeof(protkeytoken))
1456 			return -EINVAL;
1457 
1458 	memset(&protkeytoken, 0, sizeof(protkeytoken));
1459 	protkeytoken.type = TOKTYPE_NON_CCA;
1460 	protkeytoken.version = TOKVER_PROTECTED_KEY;
1461 	protkeytoken.keytype = keytype;
1462 
1463 	rc = pkey_genprotkey(protkeytoken.keytype, &protkey);
1464 	if (rc)
1465 		return rc;
1466 
1467 	protkeytoken.len = protkey.len;
1468 	memcpy(&protkeytoken.protkey, &protkey.protkey, protkey.len);
1469 
1470 	memcpy(buf, &protkeytoken, sizeof(protkeytoken));
1471 
1472 	if (is_xts) {
1473 		rc = pkey_genprotkey(protkeytoken.keytype, &protkey);
1474 		if (rc)
1475 			return rc;
1476 
1477 		protkeytoken.len = protkey.len;
1478 		memcpy(&protkeytoken.protkey, &protkey.protkey, protkey.len);
1479 
1480 		memcpy(buf + sizeof(protkeytoken), &protkeytoken,
1481 		       sizeof(protkeytoken));
1482 
1483 		return 2 * sizeof(protkeytoken);
1484 	}
1485 
1486 	return sizeof(protkeytoken);
1487 }
1488 
1489 static ssize_t protkey_aes_128_read(struct file *filp,
1490 				    struct kobject *kobj,
1491 				    struct bin_attribute *attr,
1492 				    char *buf, loff_t off,
1493 				    size_t count)
1494 {
1495 	return pkey_protkey_aes_attr_read(PKEY_KEYTYPE_AES_128, false, buf,
1496 					  off, count);
1497 }
1498 
1499 static ssize_t protkey_aes_192_read(struct file *filp,
1500 				    struct kobject *kobj,
1501 				    struct bin_attribute *attr,
1502 				    char *buf, loff_t off,
1503 				    size_t count)
1504 {
1505 	return pkey_protkey_aes_attr_read(PKEY_KEYTYPE_AES_192, false, buf,
1506 					  off, count);
1507 }
1508 
1509 static ssize_t protkey_aes_256_read(struct file *filp,
1510 				    struct kobject *kobj,
1511 				    struct bin_attribute *attr,
1512 				    char *buf, loff_t off,
1513 				    size_t count)
1514 {
1515 	return pkey_protkey_aes_attr_read(PKEY_KEYTYPE_AES_256, false, buf,
1516 					  off, count);
1517 }
1518 
1519 static ssize_t protkey_aes_128_xts_read(struct file *filp,
1520 					struct kobject *kobj,
1521 					struct bin_attribute *attr,
1522 					char *buf, loff_t off,
1523 					size_t count)
1524 {
1525 	return pkey_protkey_aes_attr_read(PKEY_KEYTYPE_AES_128, true, buf,
1526 					  off, count);
1527 }
1528 
1529 static ssize_t protkey_aes_256_xts_read(struct file *filp,
1530 					struct kobject *kobj,
1531 					struct bin_attribute *attr,
1532 					char *buf, loff_t off,
1533 					size_t count)
1534 {
1535 	return pkey_protkey_aes_attr_read(PKEY_KEYTYPE_AES_256, true, buf,
1536 					  off, count);
1537 }
1538 
1539 static BIN_ATTR_RO(protkey_aes_128, sizeof(struct protaeskeytoken));
1540 static BIN_ATTR_RO(protkey_aes_192, sizeof(struct protaeskeytoken));
1541 static BIN_ATTR_RO(protkey_aes_256, sizeof(struct protaeskeytoken));
1542 static BIN_ATTR_RO(protkey_aes_128_xts, 2 * sizeof(struct protaeskeytoken));
1543 static BIN_ATTR_RO(protkey_aes_256_xts, 2 * sizeof(struct protaeskeytoken));
1544 
1545 static struct bin_attribute *protkey_attrs[] = {
1546 	&bin_attr_protkey_aes_128,
1547 	&bin_attr_protkey_aes_192,
1548 	&bin_attr_protkey_aes_256,
1549 	&bin_attr_protkey_aes_128_xts,
1550 	&bin_attr_protkey_aes_256_xts,
1551 	NULL
1552 };
1553 
1554 static struct attribute_group protkey_attr_group = {
1555 	.name	   = "protkey",
1556 	.bin_attrs = protkey_attrs,
1557 };
1558 
1559 /*
1560  * Sysfs attribute read function for all secure key ccadata binary attributes.
1561  * The implementation can not deal with partial reads, because a new random
1562  * protected key blob is generated with each read. In case of partial reads
1563  * (i.e. off != 0 or count < key blob size) -EINVAL is returned.
1564  */
1565 static ssize_t pkey_ccadata_aes_attr_read(u32 keytype, bool is_xts, char *buf,
1566 					  loff_t off, size_t count)
1567 {
1568 	int rc;
1569 
1570 	if (off != 0 || count < sizeof(struct secaeskeytoken))
1571 		return -EINVAL;
1572 	if (is_xts)
1573 		if (count < 2 * sizeof(struct secaeskeytoken))
1574 			return -EINVAL;
1575 
1576 	rc = pkey_genseckey(-1, -1, keytype, (struct pkey_seckey *)buf);
1577 	if (rc)
1578 		return rc;
1579 
1580 	if (is_xts) {
1581 		buf += sizeof(struct pkey_seckey);
1582 		rc = pkey_genseckey(-1, -1, keytype, (struct pkey_seckey *)buf);
1583 		if (rc)
1584 			return rc;
1585 
1586 		return 2 * sizeof(struct secaeskeytoken);
1587 	}
1588 
1589 	return sizeof(struct secaeskeytoken);
1590 }
1591 
1592 static ssize_t ccadata_aes_128_read(struct file *filp,
1593 				    struct kobject *kobj,
1594 				    struct bin_attribute *attr,
1595 				    char *buf, loff_t off,
1596 				    size_t count)
1597 {
1598 	return pkey_ccadata_aes_attr_read(PKEY_KEYTYPE_AES_128, false, buf,
1599 					  off, count);
1600 }
1601 
1602 static ssize_t ccadata_aes_192_read(struct file *filp,
1603 				    struct kobject *kobj,
1604 				    struct bin_attribute *attr,
1605 				    char *buf, loff_t off,
1606 				    size_t count)
1607 {
1608 	return pkey_ccadata_aes_attr_read(PKEY_KEYTYPE_AES_192, false, buf,
1609 					  off, count);
1610 }
1611 
1612 static ssize_t ccadata_aes_256_read(struct file *filp,
1613 				    struct kobject *kobj,
1614 				    struct bin_attribute *attr,
1615 				    char *buf, loff_t off,
1616 				    size_t count)
1617 {
1618 	return pkey_ccadata_aes_attr_read(PKEY_KEYTYPE_AES_256, false, buf,
1619 					  off, count);
1620 }
1621 
1622 static ssize_t ccadata_aes_128_xts_read(struct file *filp,
1623 					struct kobject *kobj,
1624 					struct bin_attribute *attr,
1625 					char *buf, loff_t off,
1626 					size_t count)
1627 {
1628 	return pkey_ccadata_aes_attr_read(PKEY_KEYTYPE_AES_128, true, buf,
1629 					  off, count);
1630 }
1631 
1632 static ssize_t ccadata_aes_256_xts_read(struct file *filp,
1633 					struct kobject *kobj,
1634 					struct bin_attribute *attr,
1635 					char *buf, loff_t off,
1636 					size_t count)
1637 {
1638 	return pkey_ccadata_aes_attr_read(PKEY_KEYTYPE_AES_256, true, buf,
1639 					  off, count);
1640 }
1641 
1642 static BIN_ATTR_RO(ccadata_aes_128, sizeof(struct secaeskeytoken));
1643 static BIN_ATTR_RO(ccadata_aes_192, sizeof(struct secaeskeytoken));
1644 static BIN_ATTR_RO(ccadata_aes_256, sizeof(struct secaeskeytoken));
1645 static BIN_ATTR_RO(ccadata_aes_128_xts, 2 * sizeof(struct secaeskeytoken));
1646 static BIN_ATTR_RO(ccadata_aes_256_xts, 2 * sizeof(struct secaeskeytoken));
1647 
1648 static struct bin_attribute *ccadata_attrs[] = {
1649 	&bin_attr_ccadata_aes_128,
1650 	&bin_attr_ccadata_aes_192,
1651 	&bin_attr_ccadata_aes_256,
1652 	&bin_attr_ccadata_aes_128_xts,
1653 	&bin_attr_ccadata_aes_256_xts,
1654 	NULL
1655 };
1656 
1657 static struct attribute_group ccadata_attr_group = {
1658 	.name	   = "ccadata",
1659 	.bin_attrs = ccadata_attrs,
1660 };
1661 
1662 static const struct attribute_group *pkey_attr_groups[] = {
1663 	&protkey_attr_group,
1664 	&ccadata_attr_group,
1665 	NULL,
1666 };
1667 
1668 static const struct file_operations pkey_fops = {
1669 	.owner		= THIS_MODULE,
1670 	.open		= nonseekable_open,
1671 	.llseek		= no_llseek,
1672 	.unlocked_ioctl = pkey_unlocked_ioctl,
1673 };
1674 
1675 static struct miscdevice pkey_dev = {
1676 	.name	= "pkey",
1677 	.minor	= MISC_DYNAMIC_MINOR,
1678 	.mode	= 0666,
1679 	.fops	= &pkey_fops,
1680 	.groups = pkey_attr_groups,
1681 };
1682 
1683 /*
1684  * Module init
1685  */
1686 static int __init pkey_init(void)
1687 {
1688 	cpacf_mask_t kmc_functions;
1689 
1690 	/*
1691 	 * The pckmo instruction should be available - even if we don't
1692 	 * actually invoke it. This instruction comes with MSA 3 which
1693 	 * is also the minimum level for the kmc instructions which
1694 	 * are able to work with protected keys.
1695 	 */
1696 	if (!cpacf_query(CPACF_PCKMO, &pckmo_functions))
1697 		return -EOPNOTSUPP;
1698 
1699 	/* check for kmc instructions available */
1700 	if (!cpacf_query(CPACF_KMC, &kmc_functions))
1701 		return -EOPNOTSUPP;
1702 	if (!cpacf_test_func(&kmc_functions, CPACF_KMC_PAES_128) ||
1703 	    !cpacf_test_func(&kmc_functions, CPACF_KMC_PAES_192) ||
1704 	    !cpacf_test_func(&kmc_functions, CPACF_KMC_PAES_256))
1705 		return -EOPNOTSUPP;
1706 
1707 	pkey_debug_init();
1708 
1709 	return misc_register(&pkey_dev);
1710 }
1711 
1712 /*
1713  * Module exit
1714  */
1715 static void __exit pkey_exit(void)
1716 {
1717 	misc_deregister(&pkey_dev);
1718 	mkvp_cache_free();
1719 	pkey_debug_exit();
1720 }
1721 
1722 module_cpu_feature_match(MSA, pkey_init);
1723 module_exit(pkey_exit);
1724