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