1 // SPDX-License-Identifier: GPL-2.0+
2 /*
3  *  Copyright IBM Corp. 2019
4  *  Author(s): Harald Freudenberger <freude@linux.ibm.com>
5  *	       Ingo Franzki <ifranzki@linux.ibm.com>
6  *
7  *  Collection of CCA misc functions used by zcrypt and pkey
8  */
9 
10 #define KMSG_COMPONENT "zcrypt"
11 #define pr_fmt(fmt) KMSG_COMPONENT ": " fmt
12 
13 #include <linux/init.h>
14 #include <linux/module.h>
15 #include <linux/slab.h>
16 #include <linux/random.h>
17 #include <asm/zcrypt.h>
18 #include <asm/pkey.h>
19 
20 #include "ap_bus.h"
21 #include "zcrypt_api.h"
22 #include "zcrypt_debug.h"
23 #include "zcrypt_msgtype6.h"
24 #include "zcrypt_ccamisc.h"
25 
26 #define DEBUG_DBG(...)	ZCRYPT_DBF(DBF_DEBUG, ##__VA_ARGS__)
27 #define DEBUG_INFO(...) ZCRYPT_DBF(DBF_INFO, ##__VA_ARGS__)
28 #define DEBUG_WARN(...) ZCRYPT_DBF(DBF_WARN, ##__VA_ARGS__)
29 #define DEBUG_ERR(...)	ZCRYPT_DBF(DBF_ERR, ##__VA_ARGS__)
30 
31 /* Size of parameter block used for all cca requests/replies */
32 #define PARMBSIZE 512
33 
34 /* Size of vardata block used for some of the cca requests/replies */
35 #define VARDATASIZE 4096
36 
37 struct cca_info_list_entry {
38 	struct list_head list;
39 	u16 cardnr;
40 	u16 domain;
41 	struct cca_info info;
42 };
43 
44 /* a list with cca_info_list_entry entries */
45 static LIST_HEAD(cca_info_list);
46 static DEFINE_SPINLOCK(cca_info_list_lock);
47 
48 /*
49  * Simple check if the token is a valid CCA secure AES data key
50  * token. If keybitsize is given, the bitsize of the key is
51  * also checked. Returns 0 on success or errno value on failure.
52  */
53 int cca_check_secaeskeytoken(debug_info_t *dbg, int dbflvl,
54 			     const u8 *token, int keybitsize)
55 {
56 	struct secaeskeytoken *t = (struct secaeskeytoken *) token;
57 
58 #define DBF(...) debug_sprintf_event(dbg, dbflvl, ##__VA_ARGS__)
59 
60 	if (t->type != TOKTYPE_CCA_INTERNAL) {
61 		if (dbg)
62 			DBF("%s token check failed, type 0x%02x != 0x%02x\n",
63 			    __func__, (int) t->type, TOKTYPE_CCA_INTERNAL);
64 		return -EINVAL;
65 	}
66 	if (t->version != TOKVER_CCA_AES) {
67 		if (dbg)
68 			DBF("%s token check failed, version 0x%02x != 0x%02x\n",
69 			    __func__, (int) t->version, TOKVER_CCA_AES);
70 		return -EINVAL;
71 	}
72 	if (keybitsize > 0 && t->bitsize != keybitsize) {
73 		if (dbg)
74 			DBF("%s token check failed, bitsize %d != %d\n",
75 			    __func__, (int) t->bitsize, keybitsize);
76 		return -EINVAL;
77 	}
78 
79 #undef DBF
80 
81 	return 0;
82 }
83 EXPORT_SYMBOL(cca_check_secaeskeytoken);
84 
85 /*
86  * Simple check if the token is a valid CCA secure AES cipher key
87  * token. If keybitsize is given, the bitsize of the key is
88  * also checked. If checkcpacfexport is enabled, the key is also
89  * checked for the export flag to allow CPACF export.
90  * Returns 0 on success or errno value on failure.
91  */
92 int cca_check_secaescipherkey(debug_info_t *dbg, int dbflvl,
93 			      const u8 *token, int keybitsize,
94 			      int checkcpacfexport)
95 {
96 	struct cipherkeytoken *t = (struct cipherkeytoken *) token;
97 	bool keybitsizeok = true;
98 
99 #define DBF(...) debug_sprintf_event(dbg, dbflvl, ##__VA_ARGS__)
100 
101 	if (t->type != TOKTYPE_CCA_INTERNAL) {
102 		if (dbg)
103 			DBF("%s token check failed, type 0x%02x != 0x%02x\n",
104 			    __func__, (int) t->type, TOKTYPE_CCA_INTERNAL);
105 		return -EINVAL;
106 	}
107 	if (t->version != TOKVER_CCA_VLSC) {
108 		if (dbg)
109 			DBF("%s token check failed, version 0x%02x != 0x%02x\n",
110 			    __func__, (int) t->version, TOKVER_CCA_VLSC);
111 		return -EINVAL;
112 	}
113 	if (t->algtype != 0x02) {
114 		if (dbg)
115 			DBF("%s token check failed, algtype 0x%02x != 0x02\n",
116 			    __func__, (int) t->algtype);
117 		return -EINVAL;
118 	}
119 	if (t->keytype != 0x0001) {
120 		if (dbg)
121 			DBF("%s token check failed, keytype 0x%04x != 0x0001\n",
122 			    __func__, (int) t->keytype);
123 		return -EINVAL;
124 	}
125 	if (t->plfver != 0x00 && t->plfver != 0x01) {
126 		if (dbg)
127 			DBF("%s token check failed, unknown plfver 0x%02x\n",
128 			    __func__, (int) t->plfver);
129 		return -EINVAL;
130 	}
131 	if (t->wpllen != 512 && t->wpllen != 576 && t->wpllen != 640) {
132 		if (dbg)
133 			DBF("%s token check failed, unknown wpllen %d\n",
134 			    __func__, (int) t->wpllen);
135 		return -EINVAL;
136 	}
137 	if (keybitsize > 0) {
138 		switch (keybitsize) {
139 		case 128:
140 			if (t->wpllen != (t->plfver ? 640 : 512))
141 				keybitsizeok = false;
142 			break;
143 		case 192:
144 			if (t->wpllen != (t->plfver ? 640 : 576))
145 				keybitsizeok = false;
146 			break;
147 		case 256:
148 			if (t->wpllen != 640)
149 				keybitsizeok = false;
150 			break;
151 		default:
152 			keybitsizeok = false;
153 			break;
154 		}
155 		if (!keybitsizeok) {
156 			if (dbg)
157 				DBF("%s token check failed, bitsize %d\n",
158 				    __func__, keybitsize);
159 			return -EINVAL;
160 		}
161 	}
162 	if (checkcpacfexport && !(t->kmf1 & KMF1_XPRT_CPAC)) {
163 		if (dbg)
164 			DBF("%s token check failed, XPRT_CPAC bit is 0\n",
165 			    __func__);
166 		return -EINVAL;
167 	}
168 
169 #undef DBF
170 
171 	return 0;
172 }
173 EXPORT_SYMBOL(cca_check_secaescipherkey);
174 
175 /*
176  * Allocate consecutive memory for request CPRB, request param
177  * block, reply CPRB and reply param block and fill in values
178  * for the common fields. Returns 0 on success or errno value
179  * on failure.
180  */
181 static int alloc_and_prep_cprbmem(size_t paramblen,
182 				  u8 **pcprbmem,
183 				  struct CPRBX **preqCPRB,
184 				  struct CPRBX **prepCPRB)
185 {
186 	u8 *cprbmem;
187 	size_t cprbplusparamblen = sizeof(struct CPRBX) + paramblen;
188 	struct CPRBX *preqcblk, *prepcblk;
189 
190 	/*
191 	 * allocate consecutive memory for request CPRB, request param
192 	 * block, reply CPRB and reply param block
193 	 */
194 	cprbmem = kcalloc(2, cprbplusparamblen, GFP_KERNEL);
195 	if (!cprbmem)
196 		return -ENOMEM;
197 
198 	preqcblk = (struct CPRBX *) cprbmem;
199 	prepcblk = (struct CPRBX *) (cprbmem + cprbplusparamblen);
200 
201 	/* fill request cprb struct */
202 	preqcblk->cprb_len = sizeof(struct CPRBX);
203 	preqcblk->cprb_ver_id = 0x02;
204 	memcpy(preqcblk->func_id, "T2", 2);
205 	preqcblk->rpl_msgbl = cprbplusparamblen;
206 	if (paramblen) {
207 		preqcblk->req_parmb =
208 			((u8 __user *) preqcblk) + sizeof(struct CPRBX);
209 		preqcblk->rpl_parmb =
210 			((u8 __user *) prepcblk) + sizeof(struct CPRBX);
211 	}
212 
213 	*pcprbmem = cprbmem;
214 	*preqCPRB = preqcblk;
215 	*prepCPRB = prepcblk;
216 
217 	return 0;
218 }
219 
220 /*
221  * Free the cprb memory allocated with the function above.
222  * If the scrub value is not zero, the memory is filled
223  * with zeros before freeing (useful if there was some
224  * clear key material in there).
225  */
226 static void free_cprbmem(void *mem, size_t paramblen, int scrub)
227 {
228 	if (scrub)
229 		memzero_explicit(mem, 2 * (sizeof(struct CPRBX) + paramblen));
230 	kfree(mem);
231 }
232 
233 /*
234  * Helper function to prepare the xcrb struct
235  */
236 static inline void prep_xcrb(struct ica_xcRB *pxcrb,
237 			     u16 cardnr,
238 			     struct CPRBX *preqcblk,
239 			     struct CPRBX *prepcblk)
240 {
241 	memset(pxcrb, 0, sizeof(*pxcrb));
242 	pxcrb->agent_ID = 0x4341; /* 'CA' */
243 	pxcrb->user_defined = (cardnr == 0xFFFF ? AUTOSELECT : cardnr);
244 	pxcrb->request_control_blk_length =
245 		preqcblk->cprb_len + preqcblk->req_parml;
246 	pxcrb->request_control_blk_addr = (void __user *) preqcblk;
247 	pxcrb->reply_control_blk_length = preqcblk->rpl_msgbl;
248 	pxcrb->reply_control_blk_addr = (void __user *) prepcblk;
249 }
250 
251 /*
252  * Helper function which calls zcrypt_send_cprb with
253  * memory management segment adjusted to kernel space
254  * so that the copy_from_user called within this
255  * function do in fact copy from kernel space.
256  */
257 static inline int _zcrypt_send_cprb(struct ica_xcRB *xcrb)
258 {
259 	int rc;
260 	mm_segment_t old_fs = get_fs();
261 
262 	set_fs(KERNEL_DS);
263 	rc = zcrypt_send_cprb(xcrb);
264 	set_fs(old_fs);
265 
266 	return rc;
267 }
268 
269 /*
270  * Generate (random) CCA AES DATA secure key.
271  */
272 int cca_genseckey(u16 cardnr, u16 domain,
273 		  u32 keybitsize, u8 seckey[SECKEYBLOBSIZE])
274 {
275 	int i, rc, keysize;
276 	int seckeysize;
277 	u8 *mem, *ptr;
278 	struct CPRBX *preqcblk, *prepcblk;
279 	struct ica_xcRB xcrb;
280 	struct kgreqparm {
281 		u8  subfunc_code[2];
282 		u16 rule_array_len;
283 		struct lv1 {
284 			u16 len;
285 			char  key_form[8];
286 			char  key_length[8];
287 			char  key_type1[8];
288 			char  key_type2[8];
289 		} lv1;
290 		struct lv2 {
291 			u16 len;
292 			struct keyid {
293 				u16 len;
294 				u16 attr;
295 				u8  data[SECKEYBLOBSIZE];
296 			} keyid[6];
297 		} lv2;
298 	} __packed * preqparm;
299 	struct kgrepparm {
300 		u8  subfunc_code[2];
301 		u16 rule_array_len;
302 		struct lv3 {
303 			u16 len;
304 			u16 keyblocklen;
305 			struct {
306 				u16 toklen;
307 				u16 tokattr;
308 				u8  tok[0];
309 				/* ... some more data ... */
310 			} keyblock;
311 		} lv3;
312 	} __packed * prepparm;
313 
314 	/* get already prepared memory for 2 cprbs with param block each */
315 	rc = alloc_and_prep_cprbmem(PARMBSIZE, &mem, &preqcblk, &prepcblk);
316 	if (rc)
317 		return rc;
318 
319 	/* fill request cprb struct */
320 	preqcblk->domain = domain;
321 
322 	/* fill request cprb param block with KG request */
323 	preqparm = (struct kgreqparm __force *) preqcblk->req_parmb;
324 	memcpy(preqparm->subfunc_code, "KG", 2);
325 	preqparm->rule_array_len = sizeof(preqparm->rule_array_len);
326 	preqparm->lv1.len = sizeof(struct lv1);
327 	memcpy(preqparm->lv1.key_form,	 "OP      ", 8);
328 	switch (keybitsize) {
329 	case PKEY_SIZE_AES_128:
330 	case PKEY_KEYTYPE_AES_128: /* older ioctls used this */
331 		keysize = 16;
332 		memcpy(preqparm->lv1.key_length, "KEYLN16 ", 8);
333 		break;
334 	case PKEY_SIZE_AES_192:
335 	case PKEY_KEYTYPE_AES_192: /* older ioctls used this */
336 		keysize = 24;
337 		memcpy(preqparm->lv1.key_length, "KEYLN24 ", 8);
338 		break;
339 	case PKEY_SIZE_AES_256:
340 	case PKEY_KEYTYPE_AES_256: /* older ioctls used this */
341 		keysize = 32;
342 		memcpy(preqparm->lv1.key_length, "KEYLN32 ", 8);
343 		break;
344 	default:
345 		DEBUG_ERR("%s unknown/unsupported keybitsize %d\n",
346 			  __func__, keybitsize);
347 		rc = -EINVAL;
348 		goto out;
349 	}
350 	memcpy(preqparm->lv1.key_type1,  "AESDATA ", 8);
351 	preqparm->lv2.len = sizeof(struct lv2);
352 	for (i = 0; i < 6; i++) {
353 		preqparm->lv2.keyid[i].len = sizeof(struct keyid);
354 		preqparm->lv2.keyid[i].attr = (i == 2 ? 0x30 : 0x10);
355 	}
356 	preqcblk->req_parml = sizeof(struct kgreqparm);
357 
358 	/* fill xcrb struct */
359 	prep_xcrb(&xcrb, cardnr, preqcblk, prepcblk);
360 
361 	/* forward xcrb with request CPRB and reply CPRB to zcrypt dd */
362 	rc = _zcrypt_send_cprb(&xcrb);
363 	if (rc) {
364 		DEBUG_ERR("%s zcrypt_send_cprb (cardnr=%d domain=%d) failed, errno %d\n",
365 			  __func__, (int) cardnr, (int) domain, rc);
366 		goto out;
367 	}
368 
369 	/* check response returncode and reasoncode */
370 	if (prepcblk->ccp_rtcode != 0) {
371 		DEBUG_ERR("%s secure key generate failure, card response %d/%d\n",
372 			  __func__,
373 			  (int) prepcblk->ccp_rtcode,
374 			  (int) prepcblk->ccp_rscode);
375 		rc = -EIO;
376 		goto out;
377 	}
378 
379 	/* process response cprb param block */
380 	ptr =  ((u8 *) prepcblk) + sizeof(struct CPRBX);
381 	prepcblk->rpl_parmb = (u8 __user *) ptr;
382 	prepparm = (struct kgrepparm *) ptr;
383 
384 	/* check length of the returned secure key token */
385 	seckeysize = prepparm->lv3.keyblock.toklen
386 		- sizeof(prepparm->lv3.keyblock.toklen)
387 		- sizeof(prepparm->lv3.keyblock.tokattr);
388 	if (seckeysize != SECKEYBLOBSIZE) {
389 		DEBUG_ERR("%s secure token size mismatch %d != %d bytes\n",
390 			  __func__, seckeysize, SECKEYBLOBSIZE);
391 		rc = -EIO;
392 		goto out;
393 	}
394 
395 	/* check secure key token */
396 	rc = cca_check_secaeskeytoken(zcrypt_dbf_info, DBF_ERR,
397 				      prepparm->lv3.keyblock.tok, 8*keysize);
398 	if (rc) {
399 		rc = -EIO;
400 		goto out;
401 	}
402 
403 	/* copy the generated secure key token */
404 	memcpy(seckey, prepparm->lv3.keyblock.tok, SECKEYBLOBSIZE);
405 
406 out:
407 	free_cprbmem(mem, PARMBSIZE, 0);
408 	return rc;
409 }
410 EXPORT_SYMBOL(cca_genseckey);
411 
412 /*
413  * Generate an CCA AES DATA secure key with given key value.
414  */
415 int cca_clr2seckey(u16 cardnr, u16 domain, u32 keybitsize,
416 		   const u8 *clrkey, u8 seckey[SECKEYBLOBSIZE])
417 {
418 	int rc, keysize, seckeysize;
419 	u8 *mem, *ptr;
420 	struct CPRBX *preqcblk, *prepcblk;
421 	struct ica_xcRB xcrb;
422 	struct cmreqparm {
423 		u8  subfunc_code[2];
424 		u16 rule_array_len;
425 		char  rule_array[8];
426 		struct lv1 {
427 			u16 len;
428 			u8  clrkey[0];
429 		} lv1;
430 		struct lv2 {
431 			u16 len;
432 			struct keyid {
433 				u16 len;
434 				u16 attr;
435 				u8  data[SECKEYBLOBSIZE];
436 			} keyid;
437 		} lv2;
438 	} __packed * preqparm;
439 	struct lv2 *plv2;
440 	struct cmrepparm {
441 		u8  subfunc_code[2];
442 		u16 rule_array_len;
443 		struct lv3 {
444 			u16 len;
445 			u16 keyblocklen;
446 			struct {
447 				u16 toklen;
448 				u16 tokattr;
449 				u8  tok[0];
450 				/* ... some more data ... */
451 			} keyblock;
452 		} lv3;
453 	} __packed * prepparm;
454 
455 	/* get already prepared memory for 2 cprbs with param block each */
456 	rc = alloc_and_prep_cprbmem(PARMBSIZE, &mem, &preqcblk, &prepcblk);
457 	if (rc)
458 		return rc;
459 
460 	/* fill request cprb struct */
461 	preqcblk->domain = domain;
462 
463 	/* fill request cprb param block with CM request */
464 	preqparm = (struct cmreqparm __force *) preqcblk->req_parmb;
465 	memcpy(preqparm->subfunc_code, "CM", 2);
466 	memcpy(preqparm->rule_array, "AES     ", 8);
467 	preqparm->rule_array_len =
468 		sizeof(preqparm->rule_array_len) + sizeof(preqparm->rule_array);
469 	switch (keybitsize) {
470 	case PKEY_SIZE_AES_128:
471 	case PKEY_KEYTYPE_AES_128: /* older ioctls used this */
472 		keysize = 16;
473 		break;
474 	case PKEY_SIZE_AES_192:
475 	case PKEY_KEYTYPE_AES_192: /* older ioctls used this */
476 		keysize = 24;
477 		break;
478 	case PKEY_SIZE_AES_256:
479 	case PKEY_KEYTYPE_AES_256: /* older ioctls used this */
480 		keysize = 32;
481 		break;
482 	default:
483 		DEBUG_ERR("%s unknown/unsupported keybitsize %d\n",
484 			  __func__, keybitsize);
485 		rc = -EINVAL;
486 		goto out;
487 	}
488 	preqparm->lv1.len = sizeof(struct lv1) + keysize;
489 	memcpy(preqparm->lv1.clrkey, clrkey, keysize);
490 	plv2 = (struct lv2 *) (((u8 *) &preqparm->lv2) + keysize);
491 	plv2->len = sizeof(struct lv2);
492 	plv2->keyid.len = sizeof(struct keyid);
493 	plv2->keyid.attr = 0x30;
494 	preqcblk->req_parml = sizeof(struct cmreqparm) + keysize;
495 
496 	/* fill xcrb struct */
497 	prep_xcrb(&xcrb, cardnr, preqcblk, prepcblk);
498 
499 	/* forward xcrb with request CPRB and reply CPRB to zcrypt dd */
500 	rc = _zcrypt_send_cprb(&xcrb);
501 	if (rc) {
502 		DEBUG_ERR("%s zcrypt_send_cprb (cardnr=%d domain=%d) failed, rc=%d\n",
503 			  __func__, (int) cardnr, (int) domain, rc);
504 		goto out;
505 	}
506 
507 	/* check response returncode and reasoncode */
508 	if (prepcblk->ccp_rtcode != 0) {
509 		DEBUG_ERR("%s clear key import failure, card response %d/%d\n",
510 			  __func__,
511 			  (int) prepcblk->ccp_rtcode,
512 			  (int) prepcblk->ccp_rscode);
513 		rc = -EIO;
514 		goto out;
515 	}
516 
517 	/* process response cprb param block */
518 	ptr = ((u8 *) prepcblk) + sizeof(struct CPRBX);
519 	prepcblk->rpl_parmb = (u8 __user *) ptr;
520 	prepparm = (struct cmrepparm *) ptr;
521 
522 	/* check length of the returned secure key token */
523 	seckeysize = prepparm->lv3.keyblock.toklen
524 		- sizeof(prepparm->lv3.keyblock.toklen)
525 		- sizeof(prepparm->lv3.keyblock.tokattr);
526 	if (seckeysize != SECKEYBLOBSIZE) {
527 		DEBUG_ERR("%s secure token size mismatch %d != %d bytes\n",
528 			  __func__, seckeysize, SECKEYBLOBSIZE);
529 		rc = -EIO;
530 		goto out;
531 	}
532 
533 	/* check secure key token */
534 	rc = cca_check_secaeskeytoken(zcrypt_dbf_info, DBF_ERR,
535 				      prepparm->lv3.keyblock.tok, 8*keysize);
536 	if (rc) {
537 		rc = -EIO;
538 		goto out;
539 	}
540 
541 	/* copy the generated secure key token */
542 	if (seckey)
543 		memcpy(seckey, prepparm->lv3.keyblock.tok, SECKEYBLOBSIZE);
544 
545 out:
546 	free_cprbmem(mem, PARMBSIZE, 1);
547 	return rc;
548 }
549 EXPORT_SYMBOL(cca_clr2seckey);
550 
551 /*
552  * Derive proteced key from an CCA AES DATA secure key.
553  */
554 int cca_sec2protkey(u16 cardnr, u16 domain,
555 		    const u8 seckey[SECKEYBLOBSIZE],
556 		    u8 *protkey, u32 *protkeylen, u32 *protkeytype)
557 {
558 	int rc;
559 	u8 *mem, *ptr;
560 	struct CPRBX *preqcblk, *prepcblk;
561 	struct ica_xcRB xcrb;
562 	struct uskreqparm {
563 		u8  subfunc_code[2];
564 		u16 rule_array_len;
565 		struct lv1 {
566 			u16 len;
567 			u16 attr_len;
568 			u16 attr_flags;
569 		} lv1;
570 		struct lv2 {
571 			u16 len;
572 			u16 attr_len;
573 			u16 attr_flags;
574 			u8  token[0];	      /* cca secure key token */
575 		} lv2;
576 	} __packed * preqparm;
577 	struct uskrepparm {
578 		u8  subfunc_code[2];
579 		u16 rule_array_len;
580 		struct lv3 {
581 			u16 len;
582 			u16 attr_len;
583 			u16 attr_flags;
584 			struct cpacfkeyblock {
585 				u8  version;  /* version of this struct */
586 				u8  flags[2];
587 				u8  algo;
588 				u8  form;
589 				u8  pad1[3];
590 				u16 len;
591 				u8  key[64];  /* the key (len bytes) */
592 				u16 keyattrlen;
593 				u8  keyattr[32];
594 				u8  pad2[1];
595 				u8  vptype;
596 				u8  vp[32];  /* verification pattern */
597 			} ckb;
598 		} lv3;
599 	} __packed * prepparm;
600 
601 	/* get already prepared memory for 2 cprbs with param block each */
602 	rc = alloc_and_prep_cprbmem(PARMBSIZE, &mem, &preqcblk, &prepcblk);
603 	if (rc)
604 		return rc;
605 
606 	/* fill request cprb struct */
607 	preqcblk->domain = domain;
608 
609 	/* fill request cprb param block with USK request */
610 	preqparm = (struct uskreqparm __force *) preqcblk->req_parmb;
611 	memcpy(preqparm->subfunc_code, "US", 2);
612 	preqparm->rule_array_len = sizeof(preqparm->rule_array_len);
613 	preqparm->lv1.len = sizeof(struct lv1);
614 	preqparm->lv1.attr_len = sizeof(struct lv1) - sizeof(preqparm->lv1.len);
615 	preqparm->lv1.attr_flags = 0x0001;
616 	preqparm->lv2.len = sizeof(struct lv2) + SECKEYBLOBSIZE;
617 	preqparm->lv2.attr_len = sizeof(struct lv2)
618 		- sizeof(preqparm->lv2.len) + SECKEYBLOBSIZE;
619 	preqparm->lv2.attr_flags = 0x0000;
620 	memcpy(preqparm->lv2.token, seckey, SECKEYBLOBSIZE);
621 	preqcblk->req_parml = sizeof(struct uskreqparm) + SECKEYBLOBSIZE;
622 
623 	/* fill xcrb struct */
624 	prep_xcrb(&xcrb, cardnr, preqcblk, prepcblk);
625 
626 	/* forward xcrb with request CPRB and reply CPRB to zcrypt dd */
627 	rc = _zcrypt_send_cprb(&xcrb);
628 	if (rc) {
629 		DEBUG_ERR("%s zcrypt_send_cprb (cardnr=%d domain=%d) failed, rc=%d\n",
630 			  __func__, (int) cardnr, (int) domain, rc);
631 		goto out;
632 	}
633 
634 	/* check response returncode and reasoncode */
635 	if (prepcblk->ccp_rtcode != 0) {
636 		DEBUG_ERR("%s unwrap secure key failure, card response %d/%d\n",
637 			  __func__,
638 			  (int) prepcblk->ccp_rtcode,
639 			  (int) prepcblk->ccp_rscode);
640 		rc = -EIO;
641 		goto out;
642 	}
643 	if (prepcblk->ccp_rscode != 0) {
644 		DEBUG_WARN("%s unwrap secure key warning, card response %d/%d\n",
645 			   __func__,
646 			   (int) prepcblk->ccp_rtcode,
647 			   (int) prepcblk->ccp_rscode);
648 	}
649 
650 	/* process response cprb param block */
651 	ptr = ((u8 *) prepcblk) + sizeof(struct CPRBX);
652 	prepcblk->rpl_parmb = (u8 __user *) ptr;
653 	prepparm = (struct uskrepparm *) ptr;
654 
655 	/* check the returned keyblock */
656 	if (prepparm->lv3.ckb.version != 0x01 &&
657 	    prepparm->lv3.ckb.version != 0x02) {
658 		DEBUG_ERR("%s reply param keyblock version mismatch 0x%02x\n",
659 			  __func__, (int) prepparm->lv3.ckb.version);
660 		rc = -EIO;
661 		goto out;
662 	}
663 
664 	/* copy the tanslated protected key */
665 	switch (prepparm->lv3.ckb.len) {
666 	case 16+32:
667 		/* AES 128 protected key */
668 		if (protkeytype)
669 			*protkeytype = PKEY_KEYTYPE_AES_128;
670 		break;
671 	case 24+32:
672 		/* AES 192 protected key */
673 		if (protkeytype)
674 			*protkeytype = PKEY_KEYTYPE_AES_192;
675 		break;
676 	case 32+32:
677 		/* AES 256 protected key */
678 		if (protkeytype)
679 			*protkeytype = PKEY_KEYTYPE_AES_256;
680 		break;
681 	default:
682 		DEBUG_ERR("%s unknown/unsupported keylen %d\n",
683 			  __func__, prepparm->lv3.ckb.len);
684 		rc = -EIO;
685 		goto out;
686 	}
687 	memcpy(protkey, prepparm->lv3.ckb.key, prepparm->lv3.ckb.len);
688 	if (protkeylen)
689 		*protkeylen = prepparm->lv3.ckb.len;
690 
691 out:
692 	free_cprbmem(mem, PARMBSIZE, 0);
693 	return rc;
694 }
695 EXPORT_SYMBOL(cca_sec2protkey);
696 
697 /*
698  * AES cipher key skeleton created with CSNBKTB2 with these flags:
699  * INTERNAL, NO-KEY, AES, CIPHER, ANY-MODE, NOEX-SYM, NOEXAASY,
700  * NOEXUASY, XPRTCPAC, NOEX-RAW, NOEX-DES, NOEX-AES, NOEX-RSA
701  * used by cca_gencipherkey() and cca_clr2cipherkey().
702  */
703 static const u8 aes_cipher_key_skeleton[] = {
704 	0x01, 0x00, 0x00, 0x38, 0x05, 0x00, 0x00, 0x00,
705 	0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
706 	0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
707 	0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00,
708 	0x00, 0x1a, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
709 	0x00, 0x02, 0x00, 0x01, 0x02, 0xc0, 0x00, 0xff,
710 	0x00, 0x03, 0x08, 0xc8, 0x00, 0x00, 0x00, 0x00 };
711 #define SIZEOF_SKELETON (sizeof(aes_cipher_key_skeleton))
712 
713 /*
714  * Generate (random) CCA AES CIPHER secure key.
715  */
716 int cca_gencipherkey(u16 cardnr, u16 domain, u32 keybitsize, u32 keygenflags,
717 		     u8 *keybuf, size_t *keybufsize)
718 {
719 	int rc;
720 	u8 *mem, *ptr;
721 	struct CPRBX *preqcblk, *prepcblk;
722 	struct ica_xcRB xcrb;
723 	struct gkreqparm {
724 		u8  subfunc_code[2];
725 		u16 rule_array_len;
726 		char rule_array[2*8];
727 		struct {
728 			u16 len;
729 			u8  key_type_1[8];
730 			u8  key_type_2[8];
731 			u16 clear_key_bit_len;
732 			u16 key_name_1_len;
733 			u16 key_name_2_len;
734 			u16 user_data_1_len;
735 			u16 user_data_2_len;
736 			u8  key_name_1[0];
737 			u8  key_name_2[0];
738 			u8  user_data_1[0];
739 			u8  user_data_2[0];
740 		} vud;
741 		struct {
742 			u16 len;
743 			struct {
744 				u16 len;
745 				u16 flag;
746 				u8  kek_id_1[0];
747 			} tlv1;
748 			struct {
749 				u16 len;
750 				u16 flag;
751 				u8  kek_id_2[0];
752 			} tlv2;
753 			struct {
754 				u16 len;
755 				u16 flag;
756 				u8  gen_key_id_1[SIZEOF_SKELETON];
757 			} tlv3;
758 			struct {
759 				u16 len;
760 				u16 flag;
761 				u8  gen_key_id_1_label[0];
762 			} tlv4;
763 			struct {
764 				u16 len;
765 				u16 flag;
766 				u8  gen_key_id_2[0];
767 			} tlv5;
768 			struct {
769 				u16 len;
770 				u16 flag;
771 				u8  gen_key_id_2_label[0];
772 			} tlv6;
773 		} kb;
774 	} __packed * preqparm;
775 	struct gkrepparm {
776 		u8  subfunc_code[2];
777 		u16 rule_array_len;
778 		struct {
779 			u16 len;
780 		} vud;
781 		struct {
782 			u16 len;
783 			struct {
784 				u16 len;
785 				u16 flag;
786 				u8  gen_key[0]; /* 120-136 bytes */
787 			} tlv1;
788 		} kb;
789 	} __packed * prepparm;
790 	struct cipherkeytoken *t;
791 
792 	/* get already prepared memory for 2 cprbs with param block each */
793 	rc = alloc_and_prep_cprbmem(PARMBSIZE, &mem, &preqcblk, &prepcblk);
794 	if (rc)
795 		return rc;
796 
797 	/* fill request cprb struct */
798 	preqcblk->domain = domain;
799 	preqcblk->req_parml = sizeof(struct gkreqparm);
800 
801 	/* prepare request param block with GK request */
802 	preqparm = (struct gkreqparm __force *) preqcblk->req_parmb;
803 	memcpy(preqparm->subfunc_code, "GK", 2);
804 	preqparm->rule_array_len =  sizeof(uint16_t) + 2 * 8;
805 	memcpy(preqparm->rule_array, "AES     OP      ", 2*8);
806 
807 	/* prepare vud block */
808 	preqparm->vud.len = sizeof(preqparm->vud);
809 	switch (keybitsize) {
810 	case 128:
811 	case 192:
812 	case 256:
813 		break;
814 	default:
815 		DEBUG_ERR(
816 			"%s unknown/unsupported keybitsize %d\n",
817 			__func__, keybitsize);
818 		rc = -EINVAL;
819 		goto out;
820 	}
821 	preqparm->vud.clear_key_bit_len = keybitsize;
822 	memcpy(preqparm->vud.key_type_1, "TOKEN   ", 8);
823 	memset(preqparm->vud.key_type_2, ' ', sizeof(preqparm->vud.key_type_2));
824 
825 	/* prepare kb block */
826 	preqparm->kb.len = sizeof(preqparm->kb);
827 	preqparm->kb.tlv1.len = sizeof(preqparm->kb.tlv1);
828 	preqparm->kb.tlv1.flag = 0x0030;
829 	preqparm->kb.tlv2.len = sizeof(preqparm->kb.tlv2);
830 	preqparm->kb.tlv2.flag = 0x0030;
831 	preqparm->kb.tlv3.len = sizeof(preqparm->kb.tlv3);
832 	preqparm->kb.tlv3.flag = 0x0030;
833 	memcpy(preqparm->kb.tlv3.gen_key_id_1,
834 	       aes_cipher_key_skeleton, SIZEOF_SKELETON);
835 	preqparm->kb.tlv4.len = sizeof(preqparm->kb.tlv4);
836 	preqparm->kb.tlv4.flag = 0x0030;
837 	preqparm->kb.tlv5.len = sizeof(preqparm->kb.tlv5);
838 	preqparm->kb.tlv5.flag = 0x0030;
839 	preqparm->kb.tlv6.len = sizeof(preqparm->kb.tlv6);
840 	preqparm->kb.tlv6.flag = 0x0030;
841 
842 	/* patch the skeleton key token export flags inside the kb block */
843 	if (keygenflags) {
844 		t = (struct cipherkeytoken *) preqparm->kb.tlv3.gen_key_id_1;
845 		t->kmf1 |= (u16) (keygenflags & 0x0000FF00);
846 		t->kmf1 &= (u16) ~(keygenflags & 0x000000FF);
847 	}
848 
849 	/* prepare xcrb struct */
850 	prep_xcrb(&xcrb, cardnr, preqcblk, prepcblk);
851 
852 	/* forward xcrb with request CPRB and reply CPRB to zcrypt dd */
853 	rc = _zcrypt_send_cprb(&xcrb);
854 	if (rc) {
855 		DEBUG_ERR(
856 			"%s zcrypt_send_cprb (cardnr=%d domain=%d) failed, rc=%d\n",
857 			__func__, (int) cardnr, (int) domain, rc);
858 		goto out;
859 	}
860 
861 	/* check response returncode and reasoncode */
862 	if (prepcblk->ccp_rtcode != 0) {
863 		DEBUG_ERR(
864 			"%s cipher key generate failure, card response %d/%d\n",
865 			__func__,
866 			(int) prepcblk->ccp_rtcode,
867 			(int) prepcblk->ccp_rscode);
868 		rc = -EIO;
869 		goto out;
870 	}
871 
872 	/* process response cprb param block */
873 	ptr = ((u8 *) prepcblk) + sizeof(struct CPRBX);
874 	prepcblk->rpl_parmb = (u8 __user *) ptr;
875 	prepparm = (struct gkrepparm *) ptr;
876 
877 	/* do some plausibility checks on the key block */
878 	if (prepparm->kb.len < 120 + 5 * sizeof(uint16_t) ||
879 	    prepparm->kb.len > 136 + 5 * sizeof(uint16_t)) {
880 		DEBUG_ERR("%s reply with invalid or unknown key block\n",
881 			  __func__);
882 		rc = -EIO;
883 		goto out;
884 	}
885 
886 	/* and some checks on the generated key */
887 	rc = cca_check_secaescipherkey(zcrypt_dbf_info, DBF_ERR,
888 				       prepparm->kb.tlv1.gen_key,
889 				       keybitsize, 1);
890 	if (rc) {
891 		rc = -EIO;
892 		goto out;
893 	}
894 
895 	/* copy the generated vlsc key token */
896 	t = (struct cipherkeytoken *) prepparm->kb.tlv1.gen_key;
897 	if (keybuf) {
898 		if (*keybufsize >= t->len)
899 			memcpy(keybuf, t, t->len);
900 		else
901 			rc = -EINVAL;
902 	}
903 	*keybufsize = t->len;
904 
905 out:
906 	free_cprbmem(mem, PARMBSIZE, 0);
907 	return rc;
908 }
909 EXPORT_SYMBOL(cca_gencipherkey);
910 
911 /*
912  * Helper function, does a the CSNBKPI2 CPRB.
913  */
914 static int _ip_cprb_helper(u16 cardnr, u16 domain,
915 			   const char *rule_array_1,
916 			   const char *rule_array_2,
917 			   const char *rule_array_3,
918 			   const u8 *clr_key_value,
919 			   int clr_key_bit_size,
920 			   u8 *key_token,
921 			   int *key_token_size)
922 {
923 	int rc, n;
924 	u8 *mem, *ptr;
925 	struct CPRBX *preqcblk, *prepcblk;
926 	struct ica_xcRB xcrb;
927 	struct rule_array_block {
928 		u8  subfunc_code[2];
929 		u16 rule_array_len;
930 		char rule_array[0];
931 	} __packed * preq_ra_block;
932 	struct vud_block {
933 		u16 len;
934 		struct {
935 			u16 len;
936 			u16 flag;	     /* 0x0064 */
937 			u16 clr_key_bit_len;
938 		} tlv1;
939 		struct {
940 			u16 len;
941 			u16 flag;	/* 0x0063 */
942 			u8  clr_key[0]; /* clear key value bytes */
943 		} tlv2;
944 	} __packed * preq_vud_block;
945 	struct key_block {
946 		u16 len;
947 		struct {
948 			u16 len;
949 			u16 flag;	  /* 0x0030 */
950 			u8  key_token[0]; /* key skeleton */
951 		} tlv1;
952 	} __packed * preq_key_block;
953 	struct iprepparm {
954 		u8  subfunc_code[2];
955 		u16 rule_array_len;
956 		struct {
957 			u16 len;
958 		} vud;
959 		struct {
960 			u16 len;
961 			struct {
962 				u16 len;
963 				u16 flag;	  /* 0x0030 */
964 				u8  key_token[0]; /* key token */
965 			} tlv1;
966 		} kb;
967 	} __packed * prepparm;
968 	struct cipherkeytoken *t;
969 	int complete = strncmp(rule_array_2, "COMPLETE", 8) ? 0 : 1;
970 
971 	/* get already prepared memory for 2 cprbs with param block each */
972 	rc = alloc_and_prep_cprbmem(PARMBSIZE, &mem, &preqcblk, &prepcblk);
973 	if (rc)
974 		return rc;
975 
976 	/* fill request cprb struct */
977 	preqcblk->domain = domain;
978 	preqcblk->req_parml = 0;
979 
980 	/* prepare request param block with IP request */
981 	preq_ra_block = (struct rule_array_block __force *) preqcblk->req_parmb;
982 	memcpy(preq_ra_block->subfunc_code, "IP", 2);
983 	preq_ra_block->rule_array_len =  sizeof(uint16_t) + 2 * 8;
984 	memcpy(preq_ra_block->rule_array, rule_array_1, 8);
985 	memcpy(preq_ra_block->rule_array + 8, rule_array_2, 8);
986 	preqcblk->req_parml = sizeof(struct rule_array_block) + 2 * 8;
987 	if (rule_array_3) {
988 		preq_ra_block->rule_array_len += 8;
989 		memcpy(preq_ra_block->rule_array + 16, rule_array_3, 8);
990 		preqcblk->req_parml += 8;
991 	}
992 
993 	/* prepare vud block */
994 	preq_vud_block = (struct vud_block __force *)
995 		(preqcblk->req_parmb + preqcblk->req_parml);
996 	n = complete ? 0 : (clr_key_bit_size + 7) / 8;
997 	preq_vud_block->len = sizeof(struct vud_block) + n;
998 	preq_vud_block->tlv1.len = sizeof(preq_vud_block->tlv1);
999 	preq_vud_block->tlv1.flag = 0x0064;
1000 	preq_vud_block->tlv1.clr_key_bit_len = complete ? 0 : clr_key_bit_size;
1001 	preq_vud_block->tlv2.len = sizeof(preq_vud_block->tlv2) + n;
1002 	preq_vud_block->tlv2.flag = 0x0063;
1003 	if (!complete)
1004 		memcpy(preq_vud_block->tlv2.clr_key, clr_key_value, n);
1005 	preqcblk->req_parml += preq_vud_block->len;
1006 
1007 	/* prepare key block */
1008 	preq_key_block = (struct key_block __force *)
1009 		(preqcblk->req_parmb + preqcblk->req_parml);
1010 	n = *key_token_size;
1011 	preq_key_block->len = sizeof(struct key_block) + n;
1012 	preq_key_block->tlv1.len = sizeof(preq_key_block->tlv1) + n;
1013 	preq_key_block->tlv1.flag = 0x0030;
1014 	memcpy(preq_key_block->tlv1.key_token, key_token, *key_token_size);
1015 	preqcblk->req_parml += preq_key_block->len;
1016 
1017 	/* prepare xcrb struct */
1018 	prep_xcrb(&xcrb, cardnr, preqcblk, prepcblk);
1019 
1020 	/* forward xcrb with request CPRB and reply CPRB to zcrypt dd */
1021 	rc = _zcrypt_send_cprb(&xcrb);
1022 	if (rc) {
1023 		DEBUG_ERR(
1024 			"%s zcrypt_send_cprb (cardnr=%d domain=%d) failed, rc=%d\n",
1025 			__func__, (int) cardnr, (int) domain, rc);
1026 		goto out;
1027 	}
1028 
1029 	/* check response returncode and reasoncode */
1030 	if (prepcblk->ccp_rtcode != 0) {
1031 		DEBUG_ERR(
1032 			"%s CSNBKPI2 failure, card response %d/%d\n",
1033 			__func__,
1034 			(int) prepcblk->ccp_rtcode,
1035 			(int) prepcblk->ccp_rscode);
1036 		rc = -EIO;
1037 		goto out;
1038 	}
1039 
1040 	/* process response cprb param block */
1041 	ptr = ((u8 *) prepcblk) + sizeof(struct CPRBX);
1042 	prepcblk->rpl_parmb = (u8 __user *) ptr;
1043 	prepparm = (struct iprepparm *) ptr;
1044 
1045 	/* do some plausibility checks on the key block */
1046 	if (prepparm->kb.len < 120 + 3 * sizeof(uint16_t) ||
1047 	    prepparm->kb.len > 136 + 3 * sizeof(uint16_t)) {
1048 		DEBUG_ERR("%s reply with invalid or unknown key block\n",
1049 			  __func__);
1050 		rc = -EIO;
1051 		goto out;
1052 	}
1053 
1054 	/* do not check the key here, it may be incomplete */
1055 
1056 	/* copy the vlsc key token back */
1057 	t = (struct cipherkeytoken *) prepparm->kb.tlv1.key_token;
1058 	memcpy(key_token, t, t->len);
1059 	*key_token_size = t->len;
1060 
1061 out:
1062 	free_cprbmem(mem, PARMBSIZE, 0);
1063 	return rc;
1064 }
1065 
1066 /*
1067  * Build CCA AES CIPHER secure key with a given clear key value.
1068  */
1069 int cca_clr2cipherkey(u16 card, u16 dom, u32 keybitsize, u32 keygenflags,
1070 		      const u8 *clrkey, u8 *keybuf, size_t *keybufsize)
1071 {
1072 	int rc;
1073 	u8 *token;
1074 	int tokensize;
1075 	u8 exorbuf[32];
1076 	struct cipherkeytoken *t;
1077 
1078 	/* fill exorbuf with random data */
1079 	get_random_bytes(exorbuf, sizeof(exorbuf));
1080 
1081 	/* allocate space for the key token to build */
1082 	token = kmalloc(MAXCCAVLSCTOKENSIZE, GFP_KERNEL);
1083 	if (!token)
1084 		return -ENOMEM;
1085 
1086 	/* prepare the token with the key skeleton */
1087 	tokensize = SIZEOF_SKELETON;
1088 	memcpy(token, aes_cipher_key_skeleton, tokensize);
1089 
1090 	/* patch the skeleton key token export flags */
1091 	if (keygenflags) {
1092 		t = (struct cipherkeytoken *) token;
1093 		t->kmf1 |= (u16) (keygenflags & 0x0000FF00);
1094 		t->kmf1 &= (u16) ~(keygenflags & 0x000000FF);
1095 	}
1096 
1097 	/*
1098 	 * Do the key import with the clear key value in 4 steps:
1099 	 * 1/4 FIRST import with only random data
1100 	 * 2/4 EXOR the clear key
1101 	 * 3/4 EXOR the very same random data again
1102 	 * 4/4 COMPLETE the secure cipher key import
1103 	 */
1104 	rc = _ip_cprb_helper(card, dom, "AES     ", "FIRST   ", "MIN3PART",
1105 			     exorbuf, keybitsize, token, &tokensize);
1106 	if (rc) {
1107 		DEBUG_ERR(
1108 			"%s clear key import 1/4 with CSNBKPI2 failed, rc=%d\n",
1109 			__func__, rc);
1110 		goto out;
1111 	}
1112 	rc = _ip_cprb_helper(card, dom, "AES     ", "ADD-PART", NULL,
1113 			     clrkey, keybitsize, token, &tokensize);
1114 	if (rc) {
1115 		DEBUG_ERR(
1116 			"%s clear key import 2/4 with CSNBKPI2 failed, rc=%d\n",
1117 			__func__, rc);
1118 		goto out;
1119 	}
1120 	rc = _ip_cprb_helper(card, dom, "AES     ", "ADD-PART", NULL,
1121 			     exorbuf, keybitsize, token, &tokensize);
1122 	if (rc) {
1123 		DEBUG_ERR(
1124 			"%s clear key import 3/4 with CSNBKPI2 failed, rc=%d\n",
1125 			__func__, rc);
1126 		goto out;
1127 	}
1128 	rc = _ip_cprb_helper(card, dom, "AES     ", "COMPLETE", NULL,
1129 			     NULL, keybitsize, token, &tokensize);
1130 	if (rc) {
1131 		DEBUG_ERR(
1132 			"%s clear key import 4/4 with CSNBKPI2 failed, rc=%d\n",
1133 			__func__, rc);
1134 		goto out;
1135 	}
1136 
1137 	/* copy the generated key token */
1138 	if (keybuf) {
1139 		if (tokensize > *keybufsize)
1140 			rc = -EINVAL;
1141 		else
1142 			memcpy(keybuf, token, tokensize);
1143 	}
1144 	*keybufsize = tokensize;
1145 
1146 out:
1147 	kfree(token);
1148 	return rc;
1149 }
1150 EXPORT_SYMBOL(cca_clr2cipherkey);
1151 
1152 /*
1153  * Derive proteced key from CCA AES cipher secure key.
1154  */
1155 int cca_cipher2protkey(u16 cardnr, u16 domain, const u8 *ckey,
1156 		       u8 *protkey, u32 *protkeylen, u32 *protkeytype)
1157 {
1158 	int rc;
1159 	u8 *mem, *ptr;
1160 	struct CPRBX *preqcblk, *prepcblk;
1161 	struct ica_xcRB xcrb;
1162 	struct aureqparm {
1163 		u8  subfunc_code[2];
1164 		u16 rule_array_len;
1165 		u8  rule_array[8];
1166 		struct {
1167 			u16 len;
1168 			u16 tk_blob_len;
1169 			u16 tk_blob_tag;
1170 			u8  tk_blob[66];
1171 		} vud;
1172 		struct {
1173 			u16 len;
1174 			u16 cca_key_token_len;
1175 			u16 cca_key_token_flags;
1176 			u8  cca_key_token[0]; // 64 or more
1177 		} kb;
1178 	} __packed * preqparm;
1179 	struct aurepparm {
1180 		u8  subfunc_code[2];
1181 		u16 rule_array_len;
1182 		struct {
1183 			u16 len;
1184 			u16 sublen;
1185 			u16 tag;
1186 			struct cpacfkeyblock {
1187 				u8  version;  /* version of this struct */
1188 				u8  flags[2];
1189 				u8  algo;
1190 				u8  form;
1191 				u8  pad1[3];
1192 				u16 keylen;
1193 				u8  key[64];  /* the key (keylen bytes) */
1194 				u16 keyattrlen;
1195 				u8  keyattr[32];
1196 				u8  pad2[1];
1197 				u8  vptype;
1198 				u8  vp[32];  /* verification pattern */
1199 			} ckb;
1200 		} vud;
1201 		struct {
1202 			u16 len;
1203 		} kb;
1204 	} __packed * prepparm;
1205 	int keytoklen = ((struct cipherkeytoken *)ckey)->len;
1206 
1207 	/* get already prepared memory for 2 cprbs with param block each */
1208 	rc = alloc_and_prep_cprbmem(PARMBSIZE, &mem, &preqcblk, &prepcblk);
1209 	if (rc)
1210 		return rc;
1211 
1212 	/* fill request cprb struct */
1213 	preqcblk->domain = domain;
1214 
1215 	/* fill request cprb param block with AU request */
1216 	preqparm = (struct aureqparm __force *) preqcblk->req_parmb;
1217 	memcpy(preqparm->subfunc_code, "AU", 2);
1218 	preqparm->rule_array_len =
1219 		sizeof(preqparm->rule_array_len)
1220 		+ sizeof(preqparm->rule_array);
1221 	memcpy(preqparm->rule_array, "EXPT-SK ", 8);
1222 	/* vud, tk blob */
1223 	preqparm->vud.len = sizeof(preqparm->vud);
1224 	preqparm->vud.tk_blob_len = sizeof(preqparm->vud.tk_blob)
1225 		+ 2 * sizeof(uint16_t);
1226 	preqparm->vud.tk_blob_tag = 0x00C2;
1227 	/* kb, cca token */
1228 	preqparm->kb.len = keytoklen + 3 * sizeof(uint16_t);
1229 	preqparm->kb.cca_key_token_len = keytoklen + 2 * sizeof(uint16_t);
1230 	memcpy(preqparm->kb.cca_key_token, ckey, keytoklen);
1231 	/* now fill length of param block into cprb */
1232 	preqcblk->req_parml = sizeof(struct aureqparm) + keytoklen;
1233 
1234 	/* fill xcrb struct */
1235 	prep_xcrb(&xcrb, cardnr, preqcblk, prepcblk);
1236 
1237 	/* forward xcrb with request CPRB and reply CPRB to zcrypt dd */
1238 	rc = _zcrypt_send_cprb(&xcrb);
1239 	if (rc) {
1240 		DEBUG_ERR(
1241 			"%s zcrypt_send_cprb (cardnr=%d domain=%d) failed, rc=%d\n",
1242 			__func__, (int) cardnr, (int) domain, rc);
1243 		goto out;
1244 	}
1245 
1246 	/* check response returncode and reasoncode */
1247 	if (prepcblk->ccp_rtcode != 0) {
1248 		DEBUG_ERR(
1249 			"%s unwrap secure key failure, card response %d/%d\n",
1250 			__func__,
1251 			(int) prepcblk->ccp_rtcode,
1252 			(int) prepcblk->ccp_rscode);
1253 		rc = -EIO;
1254 		goto out;
1255 	}
1256 	if (prepcblk->ccp_rscode != 0) {
1257 		DEBUG_WARN(
1258 			"%s unwrap secure key warning, card response %d/%d\n",
1259 			__func__,
1260 			(int) prepcblk->ccp_rtcode,
1261 			(int) prepcblk->ccp_rscode);
1262 	}
1263 
1264 	/* process response cprb param block */
1265 	ptr = ((u8 *) prepcblk) + sizeof(struct CPRBX);
1266 	prepcblk->rpl_parmb = (u8 __user *) ptr;
1267 	prepparm = (struct aurepparm *) ptr;
1268 
1269 	/* check the returned keyblock */
1270 	if (prepparm->vud.ckb.version != 0x01 &&
1271 	    prepparm->vud.ckb.version != 0x02) {
1272 		DEBUG_ERR("%s reply param keyblock version mismatch 0x%02x\n",
1273 			  __func__, (int) prepparm->vud.ckb.version);
1274 		rc = -EIO;
1275 		goto out;
1276 	}
1277 	if (prepparm->vud.ckb.algo != 0x02) {
1278 		DEBUG_ERR(
1279 			"%s reply param keyblock algo mismatch 0x%02x != 0x02\n",
1280 			__func__, (int) prepparm->vud.ckb.algo);
1281 		rc = -EIO;
1282 		goto out;
1283 	}
1284 
1285 	/* copy the translated protected key */
1286 	switch (prepparm->vud.ckb.keylen) {
1287 	case 16+32:
1288 		/* AES 128 protected key */
1289 		if (protkeytype)
1290 			*protkeytype = PKEY_KEYTYPE_AES_128;
1291 		break;
1292 	case 24+32:
1293 		/* AES 192 protected key */
1294 		if (protkeytype)
1295 			*protkeytype = PKEY_KEYTYPE_AES_192;
1296 		break;
1297 	case 32+32:
1298 		/* AES 256 protected key */
1299 		if (protkeytype)
1300 			*protkeytype = PKEY_KEYTYPE_AES_256;
1301 		break;
1302 	default:
1303 		DEBUG_ERR("%s unknown/unsupported keylen %d\n",
1304 			  __func__, prepparm->vud.ckb.keylen);
1305 		rc = -EIO;
1306 		goto out;
1307 	}
1308 	memcpy(protkey, prepparm->vud.ckb.key, prepparm->vud.ckb.keylen);
1309 	if (protkeylen)
1310 		*protkeylen = prepparm->vud.ckb.keylen;
1311 
1312 out:
1313 	free_cprbmem(mem, PARMBSIZE, 0);
1314 	return rc;
1315 }
1316 EXPORT_SYMBOL(cca_cipher2protkey);
1317 
1318 /*
1319  * query cryptographic facility from CCA adapter
1320  */
1321 int cca_query_crypto_facility(u16 cardnr, u16 domain,
1322 			      const char *keyword,
1323 			      u8 *rarray, size_t *rarraylen,
1324 			      u8 *varray, size_t *varraylen)
1325 {
1326 	int rc;
1327 	u16 len;
1328 	u8 *mem, *ptr;
1329 	struct CPRBX *preqcblk, *prepcblk;
1330 	struct ica_xcRB xcrb;
1331 	struct fqreqparm {
1332 		u8  subfunc_code[2];
1333 		u16 rule_array_len;
1334 		char  rule_array[8];
1335 		struct lv1 {
1336 			u16 len;
1337 			u8  data[VARDATASIZE];
1338 		} lv1;
1339 		u16 dummylen;
1340 	} __packed * preqparm;
1341 	size_t parmbsize = sizeof(struct fqreqparm);
1342 	struct fqrepparm {
1343 		u8  subfunc_code[2];
1344 		u8  lvdata[0];
1345 	} __packed * prepparm;
1346 
1347 	/* get already prepared memory for 2 cprbs with param block each */
1348 	rc = alloc_and_prep_cprbmem(parmbsize, &mem, &preqcblk, &prepcblk);
1349 	if (rc)
1350 		return rc;
1351 
1352 	/* fill request cprb struct */
1353 	preqcblk->domain = domain;
1354 
1355 	/* fill request cprb param block with FQ request */
1356 	preqparm = (struct fqreqparm __force *) preqcblk->req_parmb;
1357 	memcpy(preqparm->subfunc_code, "FQ", 2);
1358 	memcpy(preqparm->rule_array, keyword, sizeof(preqparm->rule_array));
1359 	preqparm->rule_array_len =
1360 		sizeof(preqparm->rule_array_len) + sizeof(preqparm->rule_array);
1361 	preqparm->lv1.len = sizeof(preqparm->lv1);
1362 	preqparm->dummylen = sizeof(preqparm->dummylen);
1363 	preqcblk->req_parml = parmbsize;
1364 
1365 	/* fill xcrb struct */
1366 	prep_xcrb(&xcrb, cardnr, preqcblk, prepcblk);
1367 
1368 	/* forward xcrb with request CPRB and reply CPRB to zcrypt dd */
1369 	rc = _zcrypt_send_cprb(&xcrb);
1370 	if (rc) {
1371 		DEBUG_ERR("%s zcrypt_send_cprb (cardnr=%d domain=%d) failed, rc=%d\n",
1372 			  __func__, (int) cardnr, (int) domain, rc);
1373 		goto out;
1374 	}
1375 
1376 	/* check response returncode and reasoncode */
1377 	if (prepcblk->ccp_rtcode != 0) {
1378 		DEBUG_ERR("%s unwrap secure key failure, card response %d/%d\n",
1379 			  __func__,
1380 			  (int) prepcblk->ccp_rtcode,
1381 			  (int) prepcblk->ccp_rscode);
1382 		rc = -EIO;
1383 		goto out;
1384 	}
1385 
1386 	/* process response cprb param block */
1387 	ptr = ((u8 *) prepcblk) + sizeof(struct CPRBX);
1388 	prepcblk->rpl_parmb = (u8 __user *) ptr;
1389 	prepparm = (struct fqrepparm *) ptr;
1390 	ptr = prepparm->lvdata;
1391 
1392 	/* check and possibly copy reply rule array */
1393 	len = *((u16 *) ptr);
1394 	if (len > sizeof(u16)) {
1395 		ptr += sizeof(u16);
1396 		len -= sizeof(u16);
1397 		if (rarray && rarraylen && *rarraylen > 0) {
1398 			*rarraylen = (len > *rarraylen ? *rarraylen : len);
1399 			memcpy(rarray, ptr, *rarraylen);
1400 		}
1401 		ptr += len;
1402 	}
1403 	/* check and possible copy reply var array */
1404 	len = *((u16 *) ptr);
1405 	if (len > sizeof(u16)) {
1406 		ptr += sizeof(u16);
1407 		len -= sizeof(u16);
1408 		if (varray && varraylen && *varraylen > 0) {
1409 			*varraylen = (len > *varraylen ? *varraylen : len);
1410 			memcpy(varray, ptr, *varraylen);
1411 		}
1412 		ptr += len;
1413 	}
1414 
1415 out:
1416 	free_cprbmem(mem, parmbsize, 0);
1417 	return rc;
1418 }
1419 EXPORT_SYMBOL(cca_query_crypto_facility);
1420 
1421 static int cca_info_cache_fetch(u16 cardnr, u16 domain, struct cca_info *ci)
1422 {
1423 	int rc = -ENOENT;
1424 	struct cca_info_list_entry *ptr;
1425 
1426 	spin_lock_bh(&cca_info_list_lock);
1427 	list_for_each_entry(ptr, &cca_info_list, list) {
1428 		if (ptr->cardnr == cardnr && ptr->domain == domain) {
1429 			memcpy(ci, &ptr->info, sizeof(*ci));
1430 			rc = 0;
1431 			break;
1432 		}
1433 	}
1434 	spin_unlock_bh(&cca_info_list_lock);
1435 
1436 	return rc;
1437 }
1438 
1439 static void cca_info_cache_update(u16 cardnr, u16 domain,
1440 				  const struct cca_info *ci)
1441 {
1442 	int found = 0;
1443 	struct cca_info_list_entry *ptr;
1444 
1445 	spin_lock_bh(&cca_info_list_lock);
1446 	list_for_each_entry(ptr, &cca_info_list, list) {
1447 		if (ptr->cardnr == cardnr &&
1448 		    ptr->domain == domain) {
1449 			memcpy(&ptr->info, ci, sizeof(*ci));
1450 			found = 1;
1451 			break;
1452 		}
1453 	}
1454 	if (!found) {
1455 		ptr = kmalloc(sizeof(*ptr), GFP_ATOMIC);
1456 		if (!ptr) {
1457 			spin_unlock_bh(&cca_info_list_lock);
1458 			return;
1459 		}
1460 		ptr->cardnr = cardnr;
1461 		ptr->domain = domain;
1462 		memcpy(&ptr->info, ci, sizeof(*ci));
1463 		list_add(&ptr->list, &cca_info_list);
1464 	}
1465 	spin_unlock_bh(&cca_info_list_lock);
1466 }
1467 
1468 static void cca_info_cache_scrub(u16 cardnr, u16 domain)
1469 {
1470 	struct cca_info_list_entry *ptr;
1471 
1472 	spin_lock_bh(&cca_info_list_lock);
1473 	list_for_each_entry(ptr, &cca_info_list, list) {
1474 		if (ptr->cardnr == cardnr &&
1475 		    ptr->domain == domain) {
1476 			list_del(&ptr->list);
1477 			kfree(ptr);
1478 			break;
1479 		}
1480 	}
1481 	spin_unlock_bh(&cca_info_list_lock);
1482 }
1483 
1484 static void __exit mkvp_cache_free(void)
1485 {
1486 	struct cca_info_list_entry *ptr, *pnext;
1487 
1488 	spin_lock_bh(&cca_info_list_lock);
1489 	list_for_each_entry_safe(ptr, pnext, &cca_info_list, list) {
1490 		list_del(&ptr->list);
1491 		kfree(ptr);
1492 	}
1493 	spin_unlock_bh(&cca_info_list_lock);
1494 }
1495 
1496 /*
1497  * Fetch cca_info values via query_crypto_facility from adapter.
1498  */
1499 static int fetch_cca_info(u16 cardnr, u16 domain, struct cca_info *ci)
1500 {
1501 	int rc, found = 0;
1502 	size_t rlen, vlen;
1503 	u8 *rarray, *varray, *pg;
1504 	struct zcrypt_device_status_ext devstat;
1505 
1506 	memset(ci, 0, sizeof(*ci));
1507 
1508 	/* get first info from zcrypt device driver about this apqn */
1509 	rc = zcrypt_device_status_ext(cardnr, domain, &devstat);
1510 	if (rc)
1511 		return rc;
1512 	ci->hwtype = devstat.hwtype;
1513 
1514 	/* prep page for rule array and var array use */
1515 	pg = (u8 *) __get_free_page(GFP_KERNEL);
1516 	if (!pg)
1517 		return -ENOMEM;
1518 	rarray = pg;
1519 	varray = pg + PAGE_SIZE/2;
1520 	rlen = vlen = PAGE_SIZE/2;
1521 
1522 	/* QF for this card/domain */
1523 	rc = cca_query_crypto_facility(cardnr, domain, "STATICSA",
1524 				       rarray, &rlen, varray, &vlen);
1525 	if (rc == 0 && rlen >= 10*8 && vlen >= 204) {
1526 		memcpy(ci->serial, rarray, 8);
1527 		ci->new_mk_state = (char) rarray[7*8];
1528 		ci->cur_mk_state = (char) rarray[8*8];
1529 		ci->old_mk_state = (char) rarray[9*8];
1530 		if (ci->old_mk_state == '2')
1531 			memcpy(&ci->old_mkvp, varray + 172, 8);
1532 		if (ci->cur_mk_state == '2')
1533 			memcpy(&ci->cur_mkvp, varray + 184, 8);
1534 		if (ci->new_mk_state == '3')
1535 			memcpy(&ci->new_mkvp, varray + 196, 8);
1536 		found = 1;
1537 	}
1538 
1539 	free_page((unsigned long) pg);
1540 
1541 	return found ? 0 : -ENOENT;
1542 }
1543 
1544 /*
1545  * Fetch cca information about a CCA queue.
1546  */
1547 int cca_get_info(u16 card, u16 dom, struct cca_info *ci, int verify)
1548 {
1549 	int rc;
1550 
1551 	rc = cca_info_cache_fetch(card, dom, ci);
1552 	if (rc || verify) {
1553 		rc = fetch_cca_info(card, dom, ci);
1554 		if (rc == 0)
1555 			cca_info_cache_update(card, dom, ci);
1556 	}
1557 
1558 	return rc;
1559 }
1560 EXPORT_SYMBOL(cca_get_info);
1561 
1562 /*
1563  * Search for a matching crypto card based on the
1564  * Master Key Verification Pattern given.
1565  */
1566 static int findcard(u64 mkvp, u16 *pcardnr, u16 *pdomain,
1567 		    int verify, int minhwtype)
1568 {
1569 	struct zcrypt_device_status_ext *device_status;
1570 	u16 card, dom;
1571 	struct cca_info ci;
1572 	int i, rc, oi = -1;
1573 
1574 	/* mkvp must not be zero, minhwtype needs to be >= 0 */
1575 	if (mkvp == 0 || minhwtype < 0)
1576 		return -EINVAL;
1577 
1578 	/* fetch status of all crypto cards */
1579 	device_status = kvmalloc_array(MAX_ZDEV_ENTRIES_EXT,
1580 				       sizeof(struct zcrypt_device_status_ext),
1581 				       GFP_KERNEL);
1582 	if (!device_status)
1583 		return -ENOMEM;
1584 	zcrypt_device_status_mask_ext(device_status);
1585 
1586 	/* walk through all crypto cards */
1587 	for (i = 0; i < MAX_ZDEV_ENTRIES_EXT; i++) {
1588 		card = AP_QID_CARD(device_status[i].qid);
1589 		dom = AP_QID_QUEUE(device_status[i].qid);
1590 		if (device_status[i].online &&
1591 		    device_status[i].functions & 0x04) {
1592 			/* enabled CCA card, check current mkvp from cache */
1593 			if (cca_info_cache_fetch(card, dom, &ci) == 0 &&
1594 			    ci.hwtype >= minhwtype &&
1595 			    ci.cur_mk_state == '2' &&
1596 			    ci.cur_mkvp == mkvp) {
1597 				if (!verify)
1598 					break;
1599 				/* verify: refresh card info */
1600 				if (fetch_cca_info(card, dom, &ci) == 0) {
1601 					cca_info_cache_update(card, dom, &ci);
1602 					if (ci.hwtype >= minhwtype &&
1603 					    ci.cur_mk_state == '2' &&
1604 					    ci.cur_mkvp == mkvp)
1605 						break;
1606 				}
1607 			}
1608 		} else {
1609 			/* Card is offline and/or not a CCA card. */
1610 			/* del mkvp entry from cache if it exists */
1611 			cca_info_cache_scrub(card, dom);
1612 		}
1613 	}
1614 	if (i >= MAX_ZDEV_ENTRIES_EXT) {
1615 		/* nothing found, so this time without cache */
1616 		for (i = 0; i < MAX_ZDEV_ENTRIES_EXT; i++) {
1617 			if (!(device_status[i].online &&
1618 			      device_status[i].functions & 0x04))
1619 				continue;
1620 			card = AP_QID_CARD(device_status[i].qid);
1621 			dom = AP_QID_QUEUE(device_status[i].qid);
1622 			/* fresh fetch mkvp from adapter */
1623 			if (fetch_cca_info(card, dom, &ci) == 0) {
1624 				cca_info_cache_update(card, dom, &ci);
1625 				if (ci.hwtype >= minhwtype &&
1626 				    ci.cur_mk_state == '2' &&
1627 				    ci.cur_mkvp == mkvp)
1628 					break;
1629 				if (ci.hwtype >= minhwtype &&
1630 				    ci.old_mk_state == '2' &&
1631 				    ci.old_mkvp == mkvp &&
1632 				    oi < 0)
1633 					oi = i;
1634 			}
1635 		}
1636 		if (i >= MAX_ZDEV_ENTRIES_EXT && oi >= 0) {
1637 			/* old mkvp matched, use this card then */
1638 			card = AP_QID_CARD(device_status[oi].qid);
1639 			dom = AP_QID_QUEUE(device_status[oi].qid);
1640 		}
1641 	}
1642 	if (i < MAX_ZDEV_ENTRIES_EXT || oi >= 0) {
1643 		if (pcardnr)
1644 			*pcardnr = card;
1645 		if (pdomain)
1646 			*pdomain = dom;
1647 		rc = (i < MAX_ZDEV_ENTRIES_EXT ? 0 : 1);
1648 	} else
1649 		rc = -ENODEV;
1650 
1651 	kvfree(device_status);
1652 	return rc;
1653 }
1654 
1655 /*
1656  * Search for a matching crypto card based on the Master Key
1657  * Verification Pattern provided inside a secure key token.
1658  */
1659 int cca_findcard(const u8 *key, u16 *pcardnr, u16 *pdomain, int verify)
1660 {
1661 	u64 mkvp;
1662 	int minhwtype = 0;
1663 	const struct keytoken_header *hdr = (struct keytoken_header *) key;
1664 
1665 	if (hdr->type != TOKTYPE_CCA_INTERNAL)
1666 		return -EINVAL;
1667 
1668 	switch (hdr->version) {
1669 	case TOKVER_CCA_AES:
1670 		mkvp = ((struct secaeskeytoken *)key)->mkvp;
1671 		break;
1672 	case TOKVER_CCA_VLSC:
1673 		mkvp = ((struct cipherkeytoken *)key)->mkvp0;
1674 		minhwtype = AP_DEVICE_TYPE_CEX6;
1675 		break;
1676 	default:
1677 		return -EINVAL;
1678 	}
1679 
1680 	return findcard(mkvp, pcardnr, pdomain, verify, minhwtype);
1681 }
1682 EXPORT_SYMBOL(cca_findcard);
1683 
1684 int cca_findcard2(u32 **apqns, u32 *nr_apqns, u16 cardnr, u16 domain,
1685 		  int minhwtype, u64 cur_mkvp, u64 old_mkvp, int verify)
1686 {
1687 	struct zcrypt_device_status_ext *device_status;
1688 	int i, n, card, dom, curmatch, oldmatch, rc = 0;
1689 	struct cca_info ci;
1690 
1691 	*apqns = NULL;
1692 	*nr_apqns = 0;
1693 
1694 	/* fetch status of all crypto cards */
1695 	device_status = kmalloc_array(MAX_ZDEV_ENTRIES_EXT,
1696 				      sizeof(struct zcrypt_device_status_ext),
1697 				      GFP_KERNEL);
1698 	if (!device_status)
1699 		return -ENOMEM;
1700 	zcrypt_device_status_mask_ext(device_status);
1701 
1702 	/* loop two times: first gather eligible apqns, then store them */
1703 	while (1) {
1704 		n = 0;
1705 		/* walk through all the crypto cards */
1706 		for (i = 0; i < MAX_ZDEV_ENTRIES_EXT; i++) {
1707 			card = AP_QID_CARD(device_status[i].qid);
1708 			dom = AP_QID_QUEUE(device_status[i].qid);
1709 			/* check online state */
1710 			if (!device_status[i].online)
1711 				continue;
1712 			/* check for cca functions */
1713 			if (!(device_status[i].functions & 0x04))
1714 				continue;
1715 			/* check cardnr */
1716 			if (cardnr != 0xFFFF && card != cardnr)
1717 				continue;
1718 			/* check domain */
1719 			if (domain != 0xFFFF && dom != domain)
1720 				continue;
1721 			/* get cca info on this apqn */
1722 			if (cca_get_info(card, dom, &ci, verify))
1723 				continue;
1724 			/* current master key needs to be valid */
1725 			if (ci.cur_mk_state != '2')
1726 				continue;
1727 			/* check min hardware type */
1728 			if (minhwtype > 0 && minhwtype > ci.hwtype)
1729 				continue;
1730 			if (cur_mkvp || old_mkvp) {
1731 				/* check mkvps */
1732 				curmatch = oldmatch = 0;
1733 				if (cur_mkvp && cur_mkvp == ci.cur_mkvp)
1734 					curmatch = 1;
1735 				if (old_mkvp && ci.old_mk_state == '2' &&
1736 				    old_mkvp == ci.old_mkvp)
1737 					oldmatch = 1;
1738 				if ((cur_mkvp || old_mkvp) &&
1739 				    (curmatch + oldmatch < 1))
1740 					continue;
1741 			}
1742 			/* apqn passed all filtering criterons */
1743 			if (*apqns && n < *nr_apqns)
1744 				(*apqns)[n] = (((u16)card) << 16) | ((u16) dom);
1745 			n++;
1746 		}
1747 		/* loop 2nd time: array has been filled */
1748 		if (*apqns)
1749 			break;
1750 		/* loop 1st time: have # of eligible apqns in n */
1751 		if (!n) {
1752 			rc = -ENODEV; /* no eligible apqns found */
1753 			break;
1754 		}
1755 		*nr_apqns = n;
1756 		/* allocate array to store n apqns into */
1757 		*apqns = kmalloc_array(n, sizeof(u32), GFP_KERNEL);
1758 		if (!*apqns) {
1759 			rc = -ENOMEM;
1760 			break;
1761 		}
1762 		verify = 0;
1763 	}
1764 
1765 	kfree(device_status);
1766 	return rc;
1767 }
1768 EXPORT_SYMBOL(cca_findcard2);
1769 
1770 void __exit zcrypt_ccamisc_exit(void)
1771 {
1772 	mkvp_cache_free();
1773 }
1774