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