s390/zcrypt: extend cca_findcard function and helper
[linux-2.6-microblaze.git] / drivers / s390 / crypto / zcrypt_ccamisc.c
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 <asm/zcrypt.h>
17 #include <asm/pkey.h>
18
19 #include "ap_bus.h"
20 #include "zcrypt_api.h"
21 #include "zcrypt_debug.h"
22 #include "zcrypt_msgtype6.h"
23 #include "zcrypt_ccamisc.h"
24
25 #define DEBUG_DBG(...)  ZCRYPT_DBF(DBF_DEBUG, ##__VA_ARGS__)
26 #define DEBUG_INFO(...) ZCRYPT_DBF(DBF_INFO, ##__VA_ARGS__)
27 #define DEBUG_WARN(...) ZCRYPT_DBF(DBF_WARN, ##__VA_ARGS__)
28 #define DEBUG_ERR(...)  ZCRYPT_DBF(DBF_ERR, ##__VA_ARGS__)
29
30 /* Size of parameter block used for all cca requests/replies */
31 #define PARMBSIZE 512
32
33 /* Size of vardata block used for some of the cca requests/replies */
34 #define VARDATASIZE 4096
35
36 struct cca_info_list_entry {
37         struct list_head list;
38         u16 cardnr;
39         u16 domain;
40         struct cca_info info;
41 };
42
43 /* a list with cca_info_list_entry entries */
44 static LIST_HEAD(cca_info_list);
45 static DEFINE_SPINLOCK(cca_info_list_lock);
46
47 /*
48  * Simple check if the token is a valid CCA secure AES key
49  * token. If keybitsize is given, the bitsize of the key is
50  * also checked. Returns 0 on success or errno value on failure.
51  */
52 int cca_check_secaeskeytoken(debug_info_t *dbg, int dbflvl,
53                              const u8 *token, int keybitsize)
54
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  * Allocate consecutive memory for request CPRB, request param
87  * block, reply CPRB and reply param block and fill in values
88  * for the common fields. Returns 0 on success or errno value
89  * on failure.
90  */
91 static int alloc_and_prep_cprbmem(size_t paramblen,
92                                   u8 **pcprbmem,
93                                   struct CPRBX **preqCPRB,
94                                   struct CPRBX **prepCPRB)
95 {
96         u8 *cprbmem;
97         size_t cprbplusparamblen = sizeof(struct CPRBX) + paramblen;
98         struct CPRBX *preqcblk, *prepcblk;
99
100         /*
101          * allocate consecutive memory for request CPRB, request param
102          * block, reply CPRB and reply param block
103          */
104         cprbmem = kcalloc(2, cprbplusparamblen, GFP_KERNEL);
105         if (!cprbmem)
106                 return -ENOMEM;
107
108         preqcblk = (struct CPRBX *) cprbmem;
109         prepcblk = (struct CPRBX *) (cprbmem + cprbplusparamblen);
110
111         /* fill request cprb struct */
112         preqcblk->cprb_len = sizeof(struct CPRBX);
113         preqcblk->cprb_ver_id = 0x02;
114         memcpy(preqcblk->func_id, "T2", 2);
115         preqcblk->rpl_msgbl = cprbplusparamblen;
116         if (paramblen) {
117                 preqcblk->req_parmb =
118                         ((u8 *) preqcblk) + sizeof(struct CPRBX);
119                 preqcblk->rpl_parmb =
120                         ((u8 *) prepcblk) + sizeof(struct CPRBX);
121         }
122
123         *pcprbmem = cprbmem;
124         *preqCPRB = preqcblk;
125         *prepCPRB = prepcblk;
126
127         return 0;
128 }
129
130 /*
131  * Free the cprb memory allocated with the function above.
132  * If the scrub value is not zero, the memory is filled
133  * with zeros before freeing (useful if there was some
134  * clear key material in there).
135  */
136 static void free_cprbmem(void *mem, size_t paramblen, int scrub)
137 {
138         if (scrub)
139                 memzero_explicit(mem, 2 * (sizeof(struct CPRBX) + paramblen));
140         kfree(mem);
141 }
142
143 /*
144  * Helper function to prepare the xcrb struct
145  */
146 static inline void prep_xcrb(struct ica_xcRB *pxcrb,
147                              u16 cardnr,
148                              struct CPRBX *preqcblk,
149                              struct CPRBX *prepcblk)
150 {
151         memset(pxcrb, 0, sizeof(*pxcrb));
152         pxcrb->agent_ID = 0x4341; /* 'CA' */
153         pxcrb->user_defined = (cardnr == 0xFFFF ? AUTOSELECT : cardnr);
154         pxcrb->request_control_blk_length =
155                 preqcblk->cprb_len + preqcblk->req_parml;
156         pxcrb->request_control_blk_addr = (void __user *) preqcblk;
157         pxcrb->reply_control_blk_length = preqcblk->rpl_msgbl;
158         pxcrb->reply_control_blk_addr = (void __user *) prepcblk;
159 }
160
161 /*
162  * Helper function which calls zcrypt_send_cprb with
163  * memory management segment adjusted to kernel space
164  * so that the copy_from_user called within this
165  * function do in fact copy from kernel space.
166  */
167 static inline int _zcrypt_send_cprb(struct ica_xcRB *xcrb)
168 {
169         int rc;
170         mm_segment_t old_fs = get_fs();
171
172         set_fs(KERNEL_DS);
173         rc = zcrypt_send_cprb(xcrb);
174         set_fs(old_fs);
175
176         return rc;
177 }
178
179 /*
180  * Generate (random) CCA AES DATA secure key.
181  */
182 int cca_genseckey(u16 cardnr, u16 domain,
183                   u32 keytype, u8 seckey[SECKEYBLOBSIZE])
184 {
185         int i, rc, keysize;
186         int seckeysize;
187         u8 *mem;
188         struct CPRBX *preqcblk, *prepcblk;
189         struct ica_xcRB xcrb;
190         struct kgreqparm {
191                 u8  subfunc_code[2];
192                 u16 rule_array_len;
193                 struct lv1 {
194                         u16 len;
195                         char  key_form[8];
196                         char  key_length[8];
197                         char  key_type1[8];
198                         char  key_type2[8];
199                 } lv1;
200                 struct lv2 {
201                         u16 len;
202                         struct keyid {
203                                 u16 len;
204                                 u16 attr;
205                                 u8  data[SECKEYBLOBSIZE];
206                         } keyid[6];
207                 } lv2;
208         } __packed * preqparm;
209         struct kgrepparm {
210                 u8  subfunc_code[2];
211                 u16 rule_array_len;
212                 struct lv3 {
213                         u16 len;
214                         u16 keyblocklen;
215                         struct {
216                                 u16 toklen;
217                                 u16 tokattr;
218                                 u8  tok[0];
219                                 /* ... some more data ... */
220                         } keyblock;
221                 } lv3;
222         } __packed * prepparm;
223
224         /* get already prepared memory for 2 cprbs with param block each */
225         rc = alloc_and_prep_cprbmem(PARMBSIZE, &mem, &preqcblk, &prepcblk);
226         if (rc)
227                 return rc;
228
229         /* fill request cprb struct */
230         preqcblk->domain = domain;
231
232         /* fill request cprb param block with KG request */
233         preqparm = (struct kgreqparm *) preqcblk->req_parmb;
234         memcpy(preqparm->subfunc_code, "KG", 2);
235         preqparm->rule_array_len = sizeof(preqparm->rule_array_len);
236         preqparm->lv1.len = sizeof(struct lv1);
237         memcpy(preqparm->lv1.key_form,   "OP      ", 8);
238         switch (keytype) {
239         case PKEY_KEYTYPE_AES_128:
240                 keysize = 16;
241                 memcpy(preqparm->lv1.key_length, "KEYLN16 ", 8);
242                 break;
243         case PKEY_KEYTYPE_AES_192:
244                 keysize = 24;
245                 memcpy(preqparm->lv1.key_length, "KEYLN24 ", 8);
246                 break;
247         case PKEY_KEYTYPE_AES_256:
248                 keysize = 32;
249                 memcpy(preqparm->lv1.key_length, "KEYLN32 ", 8);
250                 break;
251         default:
252                 DEBUG_ERR("%s unknown/unsupported keytype %d\n",
253                           __func__, keytype);
254                 rc = -EINVAL;
255                 goto out;
256         }
257         memcpy(preqparm->lv1.key_type1,  "AESDATA ", 8);
258         preqparm->lv2.len = sizeof(struct lv2);
259         for (i = 0; i < 6; i++) {
260                 preqparm->lv2.keyid[i].len = sizeof(struct keyid);
261                 preqparm->lv2.keyid[i].attr = (i == 2 ? 0x30 : 0x10);
262         }
263         preqcblk->req_parml = sizeof(struct kgreqparm);
264
265         /* fill xcrb struct */
266         prep_xcrb(&xcrb, cardnr, preqcblk, prepcblk);
267
268         /* forward xcrb with request CPRB and reply CPRB to zcrypt dd */
269         rc = _zcrypt_send_cprb(&xcrb);
270         if (rc) {
271                 DEBUG_ERR("%s zcrypt_send_cprb (cardnr=%d domain=%d) failed, errno %d\n",
272                           __func__, (int) cardnr, (int) domain, rc);
273                 goto out;
274         }
275
276         /* check response returncode and reasoncode */
277         if (prepcblk->ccp_rtcode != 0) {
278                 DEBUG_ERR("%s secure key generate failure, card response %d/%d\n",
279                           __func__,
280                           (int) prepcblk->ccp_rtcode,
281                           (int) prepcblk->ccp_rscode);
282                 rc = -EIO;
283                 goto out;
284         }
285
286         /* process response cprb param block */
287         prepcblk->rpl_parmb = ((u8 *) prepcblk) + sizeof(struct CPRBX);
288         prepparm = (struct kgrepparm *) prepcblk->rpl_parmb;
289
290         /* check length of the returned secure key token */
291         seckeysize = prepparm->lv3.keyblock.toklen
292                 - sizeof(prepparm->lv3.keyblock.toklen)
293                 - sizeof(prepparm->lv3.keyblock.tokattr);
294         if (seckeysize != SECKEYBLOBSIZE) {
295                 DEBUG_ERR("%s secure token size mismatch %d != %d bytes\n",
296                           __func__, seckeysize, SECKEYBLOBSIZE);
297                 rc = -EIO;
298                 goto out;
299         }
300
301         /* check secure key token */
302         rc = cca_check_secaeskeytoken(zcrypt_dbf_info, DBF_ERR,
303                                       prepparm->lv3.keyblock.tok, 8*keysize);
304         if (rc) {
305                 rc = -EIO;
306                 goto out;
307         }
308
309         /* copy the generated secure key token */
310         memcpy(seckey, prepparm->lv3.keyblock.tok, SECKEYBLOBSIZE);
311
312 out:
313         free_cprbmem(mem, PARMBSIZE, 0);
314         return rc;
315 }
316 EXPORT_SYMBOL(cca_genseckey);
317
318 /*
319  * Generate an CCA AES DATA secure key with given key value.
320  */
321 int cca_clr2seckey(u16 cardnr, u16 domain, u32 keytype,
322                    const u8 *clrkey, u8 seckey[SECKEYBLOBSIZE])
323 {
324         int rc, keysize, seckeysize;
325         u8 *mem;
326         struct CPRBX *preqcblk, *prepcblk;
327         struct ica_xcRB xcrb;
328         struct cmreqparm {
329                 u8  subfunc_code[2];
330                 u16 rule_array_len;
331                 char  rule_array[8];
332                 struct lv1 {
333                         u16 len;
334                         u8  clrkey[0];
335                 } lv1;
336                 struct lv2 {
337                         u16 len;
338                         struct keyid {
339                                 u16 len;
340                                 u16 attr;
341                                 u8  data[SECKEYBLOBSIZE];
342                         } keyid;
343                 } lv2;
344         } __packed * preqparm;
345         struct lv2 *plv2;
346         struct cmrepparm {
347                 u8  subfunc_code[2];
348                 u16 rule_array_len;
349                 struct lv3 {
350                         u16 len;
351                         u16 keyblocklen;
352                         struct {
353                                 u16 toklen;
354                                 u16 tokattr;
355                                 u8  tok[0];
356                                 /* ... some more data ... */
357                         } keyblock;
358                 } lv3;
359         } __packed * prepparm;
360
361         /* get already prepared memory for 2 cprbs with param block each */
362         rc = alloc_and_prep_cprbmem(PARMBSIZE, &mem, &preqcblk, &prepcblk);
363         if (rc)
364                 return rc;
365
366         /* fill request cprb struct */
367         preqcblk->domain = domain;
368
369         /* fill request cprb param block with CM request */
370         preqparm = (struct cmreqparm *) preqcblk->req_parmb;
371         memcpy(preqparm->subfunc_code, "CM", 2);
372         memcpy(preqparm->rule_array, "AES     ", 8);
373         preqparm->rule_array_len =
374                 sizeof(preqparm->rule_array_len) + sizeof(preqparm->rule_array);
375         switch (keytype) {
376         case PKEY_KEYTYPE_AES_128:
377                 keysize = 16;
378                 break;
379         case PKEY_KEYTYPE_AES_192:
380                 keysize = 24;
381                 break;
382         case PKEY_KEYTYPE_AES_256:
383                 keysize = 32;
384                 break;
385         default:
386                 DEBUG_ERR("%s unknown/unsupported keytype %d\n",
387                           __func__, keytype);
388                 rc = -EINVAL;
389                 goto out;
390         }
391         preqparm->lv1.len = sizeof(struct lv1) + keysize;
392         memcpy(preqparm->lv1.clrkey, clrkey, keysize);
393         plv2 = (struct lv2 *) (((u8 *) &preqparm->lv2) + keysize);
394         plv2->len = sizeof(struct lv2);
395         plv2->keyid.len = sizeof(struct keyid);
396         plv2->keyid.attr = 0x30;
397         preqcblk->req_parml = sizeof(struct cmreqparm) + keysize;
398
399         /* fill xcrb struct */
400         prep_xcrb(&xcrb, cardnr, preqcblk, prepcblk);
401
402         /* forward xcrb with request CPRB and reply CPRB to zcrypt dd */
403         rc = _zcrypt_send_cprb(&xcrb);
404         if (rc) {
405                 DEBUG_ERR("%s zcrypt_send_cprb (cardnr=%d domain=%d) failed, rc=%d\n",
406                           __func__, (int) cardnr, (int) domain, rc);
407                 goto out;
408         }
409
410         /* check response returncode and reasoncode */
411         if (prepcblk->ccp_rtcode != 0) {
412                 DEBUG_ERR("%s clear key import failure, card response %d/%d\n",
413                           __func__,
414                           (int) prepcblk->ccp_rtcode,
415                           (int) prepcblk->ccp_rscode);
416                 rc = -EIO;
417                 goto out;
418         }
419
420         /* process response cprb param block */
421         prepcblk->rpl_parmb = ((u8 *) prepcblk) + sizeof(struct CPRBX);
422         prepparm = (struct cmrepparm *) prepcblk->rpl_parmb;
423
424         /* check length of the returned secure key token */
425         seckeysize = prepparm->lv3.keyblock.toklen
426                 - sizeof(prepparm->lv3.keyblock.toklen)
427                 - sizeof(prepparm->lv3.keyblock.tokattr);
428         if (seckeysize != SECKEYBLOBSIZE) {
429                 DEBUG_ERR("%s secure token size mismatch %d != %d bytes\n",
430                           __func__, seckeysize, SECKEYBLOBSIZE);
431                 rc = -EIO;
432                 goto out;
433         }
434
435         /* check secure key token */
436         rc = cca_check_secaeskeytoken(zcrypt_dbf_info, DBF_ERR,
437                                       prepparm->lv3.keyblock.tok, 8*keysize);
438         if (rc) {
439                 rc = -EIO;
440                 goto out;
441         }
442
443         /* copy the generated secure key token */
444         memcpy(seckey, prepparm->lv3.keyblock.tok, SECKEYBLOBSIZE);
445
446 out:
447         free_cprbmem(mem, PARMBSIZE, 1);
448         return rc;
449 }
450 EXPORT_SYMBOL(cca_clr2seckey);
451
452 /*
453  * Derive proteced key from an CCA AES DATA secure key.
454  */
455 int cca_sec2protkey(u16 cardnr, u16 domain,
456                     const u8 seckey[SECKEYBLOBSIZE],
457                     u8 *protkey, u32 *protkeylen,
458                     u32 *keytype)
459 {
460         int rc;
461         u8 *mem;
462         struct CPRBX *preqcblk, *prepcblk;
463         struct ica_xcRB xcrb;
464         struct uskreqparm {
465                 u8  subfunc_code[2];
466                 u16 rule_array_len;
467                 struct lv1 {
468                         u16 len;
469                         u16 attr_len;
470                         u16 attr_flags;
471                 } lv1;
472                 struct lv2 {
473                         u16 len;
474                         u16 attr_len;
475                         u16 attr_flags;
476                         u8  token[0];         /* cca secure key token */
477                 } lv2;
478         } __packed * preqparm;
479         struct uskrepparm {
480                 u8  subfunc_code[2];
481                 u16 rule_array_len;
482                 struct lv3 {
483                         u16 len;
484                         u16 attr_len;
485                         u16 attr_flags;
486                         struct cpacfkeyblock {
487                                 u8  version;  /* version of this struct */
488                                 u8  flags[2];
489                                 u8  algo;
490                                 u8  form;
491                                 u8  pad1[3];
492                                 u16 len;
493                                 u8  key[64];  /* the key (len bytes) */
494                                 u16 keyattrlen;
495                                 u8  keyattr[32];
496                                 u8  pad2[1];
497                                 u8  vptype;
498                                 u8  vp[32];  /* verification pattern */
499                         } keyblock;
500                 } lv3;
501         } __packed * prepparm;
502
503         /* get already prepared memory for 2 cprbs with param block each */
504         rc = alloc_and_prep_cprbmem(PARMBSIZE, &mem, &preqcblk, &prepcblk);
505         if (rc)
506                 return rc;
507
508         /* fill request cprb struct */
509         preqcblk->domain = domain;
510
511         /* fill request cprb param block with USK request */
512         preqparm = (struct uskreqparm *) preqcblk->req_parmb;
513         memcpy(preqparm->subfunc_code, "US", 2);
514         preqparm->rule_array_len = sizeof(preqparm->rule_array_len);
515         preqparm->lv1.len = sizeof(struct lv1);
516         preqparm->lv1.attr_len = sizeof(struct lv1) - sizeof(preqparm->lv1.len);
517         preqparm->lv1.attr_flags = 0x0001;
518         preqparm->lv2.len = sizeof(struct lv2) + SECKEYBLOBSIZE;
519         preqparm->lv2.attr_len = sizeof(struct lv2)
520                 - sizeof(preqparm->lv2.len) + SECKEYBLOBSIZE;
521         preqparm->lv2.attr_flags = 0x0000;
522         memcpy(preqparm->lv2.token, seckey, SECKEYBLOBSIZE);
523         preqcblk->req_parml = sizeof(struct uskreqparm) + SECKEYBLOBSIZE;
524
525         /* fill xcrb struct */
526         prep_xcrb(&xcrb, cardnr, preqcblk, prepcblk);
527
528         /* forward xcrb with request CPRB and reply CPRB to zcrypt dd */
529         rc = _zcrypt_send_cprb(&xcrb);
530         if (rc) {
531                 DEBUG_ERR("%s zcrypt_send_cprb (cardnr=%d domain=%d) failed, rc=%d\n",
532                           __func__, (int) cardnr, (int) domain, rc);
533                 goto out;
534         }
535
536         /* check response returncode and reasoncode */
537         if (prepcblk->ccp_rtcode != 0) {
538                 DEBUG_ERR("%s unwrap secure key failure, card response %d/%d\n",
539                           __func__,
540                           (int) prepcblk->ccp_rtcode,
541                           (int) prepcblk->ccp_rscode);
542                 rc = -EIO;
543                 goto out;
544         }
545         if (prepcblk->ccp_rscode != 0) {
546                 DEBUG_WARN("%s unwrap secure key warning, card response %d/%d\n",
547                            __func__,
548                            (int) prepcblk->ccp_rtcode,
549                            (int) prepcblk->ccp_rscode);
550         }
551
552         /* process response cprb param block */
553         prepcblk->rpl_parmb = ((u8 *) prepcblk) + sizeof(struct CPRBX);
554         prepparm = (struct uskrepparm *) prepcblk->rpl_parmb;
555
556         /* check the returned keyblock */
557         if (prepparm->lv3.keyblock.version != 0x01) {
558                 DEBUG_ERR("%s reply param keyblock version mismatch 0x%02x != 0x01\n",
559                           __func__, (int) prepparm->lv3.keyblock.version);
560                 rc = -EIO;
561                 goto out;
562         }
563
564         /* copy the tanslated protected key */
565         switch (prepparm->lv3.keyblock.len) {
566         case 16+32:
567                 /* AES 128 protected key */
568                 if (keytype)
569                         *keytype = PKEY_KEYTYPE_AES_128;
570                 break;
571         case 24+32:
572                 /* AES 192 protected key */
573                 if (keytype)
574                         *keytype = PKEY_KEYTYPE_AES_192;
575                 break;
576         case 32+32:
577                 /* AES 256 protected key */
578                 if (keytype)
579                         *keytype = PKEY_KEYTYPE_AES_256;
580                 break;
581         default:
582                 DEBUG_ERR("%s unknown/unsupported keytype %d\n",
583                           __func__, prepparm->lv3.keyblock.len);
584                 rc = -EIO;
585                 goto out;
586         }
587         memcpy(protkey, prepparm->lv3.keyblock.key, prepparm->lv3.keyblock.len);
588         if (protkeylen)
589                 *protkeylen = prepparm->lv3.keyblock.len;
590
591 out:
592         free_cprbmem(mem, PARMBSIZE, 0);
593         return rc;
594 }
595 EXPORT_SYMBOL(cca_sec2protkey);
596
597 /*
598  * query cryptographic facility from CCA adapter
599  */
600 int cca_query_crypto_facility(u16 cardnr, u16 domain,
601                               const char *keyword,
602                               u8 *rarray, size_t *rarraylen,
603                               u8 *varray, size_t *varraylen)
604 {
605         int rc;
606         u16 len;
607         u8 *mem, *ptr;
608         struct CPRBX *preqcblk, *prepcblk;
609         struct ica_xcRB xcrb;
610         struct fqreqparm {
611                 u8  subfunc_code[2];
612                 u16 rule_array_len;
613                 char  rule_array[8];
614                 struct lv1 {
615                         u16 len;
616                         u8  data[VARDATASIZE];
617                 } lv1;
618                 u16 dummylen;
619         } __packed * preqparm;
620         size_t parmbsize = sizeof(struct fqreqparm);
621         struct fqrepparm {
622                 u8  subfunc_code[2];
623                 u8  lvdata[0];
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 FQ request */
635         preqparm = (struct fqreqparm *) preqcblk->req_parmb;
636         memcpy(preqparm->subfunc_code, "FQ", 2);
637         memcpy(preqparm->rule_array, keyword, sizeof(preqparm->rule_array));
638         preqparm->rule_array_len =
639                 sizeof(preqparm->rule_array_len) + sizeof(preqparm->rule_array);
640         preqparm->lv1.len = sizeof(preqparm->lv1);
641         preqparm->dummylen = sizeof(preqparm->dummylen);
642         preqcblk->req_parml = parmbsize;
643
644         /* fill xcrb struct */
645         prep_xcrb(&xcrb, cardnr, preqcblk, prepcblk);
646
647         /* forward xcrb with request CPRB and reply CPRB to zcrypt dd */
648         rc = _zcrypt_send_cprb(&xcrb);
649         if (rc) {
650                 DEBUG_ERR("%s zcrypt_send_cprb (cardnr=%d domain=%d) failed, rc=%d\n",
651                           __func__, (int) cardnr, (int) domain, rc);
652                 goto out;
653         }
654
655         /* check response returncode and reasoncode */
656         if (prepcblk->ccp_rtcode != 0) {
657                 DEBUG_ERR("%s unwrap secure key failure, card response %d/%d\n",
658                           __func__,
659                           (int) prepcblk->ccp_rtcode,
660                           (int) prepcblk->ccp_rscode);
661                 rc = -EIO;
662                 goto out;
663         }
664
665         /* process response cprb param block */
666         prepcblk->rpl_parmb = ((u8 *) prepcblk) + sizeof(struct CPRBX);
667         prepparm = (struct fqrepparm *) prepcblk->rpl_parmb;
668         ptr = prepparm->lvdata;
669
670         /* check and possibly copy reply rule array */
671         len = *((u16 *) ptr);
672         if (len > sizeof(u16)) {
673                 ptr += sizeof(u16);
674                 len -= sizeof(u16);
675                 if (rarray && rarraylen && *rarraylen > 0) {
676                         *rarraylen = (len > *rarraylen ? *rarraylen : len);
677                         memcpy(rarray, ptr, *rarraylen);
678                 }
679                 ptr += len;
680         }
681         /* check and possible copy reply var array */
682         len = *((u16 *) ptr);
683         if (len > sizeof(u16)) {
684                 ptr += sizeof(u16);
685                 len -= sizeof(u16);
686                 if (varray && varraylen && *varraylen > 0) {
687                         *varraylen = (len > *varraylen ? *varraylen : len);
688                         memcpy(varray, ptr, *varraylen);
689                 }
690                 ptr += len;
691         }
692
693 out:
694         free_cprbmem(mem, parmbsize, 0);
695         return rc;
696 }
697 EXPORT_SYMBOL(cca_query_crypto_facility);
698
699 static int cca_info_cache_fetch(u16 cardnr, u16 domain, struct cca_info *ci)
700 {
701         int rc = -ENOENT;
702         struct cca_info_list_entry *ptr;
703
704         spin_lock_bh(&cca_info_list_lock);
705         list_for_each_entry(ptr, &cca_info_list, list) {
706                 if (ptr->cardnr == cardnr && ptr->domain == domain) {
707                         memcpy(ci, &ptr->info, sizeof(*ci));
708                         rc = 0;
709                         break;
710                 }
711         }
712         spin_unlock_bh(&cca_info_list_lock);
713
714         return rc;
715 }
716
717 static void cca_info_cache_update(u16 cardnr, u16 domain,
718                                   const struct cca_info *ci)
719 {
720         int found = 0;
721         struct cca_info_list_entry *ptr;
722
723         spin_lock_bh(&cca_info_list_lock);
724         list_for_each_entry(ptr, &cca_info_list, list) {
725                 if (ptr->cardnr == cardnr &&
726                     ptr->domain == domain) {
727                         memcpy(&ptr->info, ci, sizeof(*ci));
728                         found = 1;
729                         break;
730                 }
731         }
732         if (!found) {
733                 ptr = kmalloc(sizeof(*ptr), GFP_ATOMIC);
734                 if (!ptr) {
735                         spin_unlock_bh(&cca_info_list_lock);
736                         return;
737                 }
738                 ptr->cardnr = cardnr;
739                 ptr->domain = domain;
740                 memcpy(&ptr->info, ci, sizeof(*ci));
741                 list_add(&ptr->list, &cca_info_list);
742         }
743         spin_unlock_bh(&cca_info_list_lock);
744 }
745
746 static void cca_info_cache_scrub(u16 cardnr, u16 domain)
747 {
748         struct cca_info_list_entry *ptr;
749
750         spin_lock_bh(&cca_info_list_lock);
751         list_for_each_entry(ptr, &cca_info_list, list) {
752                 if (ptr->cardnr == cardnr &&
753                     ptr->domain == domain) {
754                         list_del(&ptr->list);
755                         kfree(ptr);
756                         break;
757                 }
758         }
759         spin_unlock_bh(&cca_info_list_lock);
760 }
761
762 static void __exit mkvp_cache_free(void)
763 {
764         struct cca_info_list_entry *ptr, *pnext;
765
766         spin_lock_bh(&cca_info_list_lock);
767         list_for_each_entry_safe(ptr, pnext, &cca_info_list, list) {
768                 list_del(&ptr->list);
769                 kfree(ptr);
770         }
771         spin_unlock_bh(&cca_info_list_lock);
772 }
773
774 /*
775  * Fetch cca_info values via query_crypto_facility from adapter.
776  */
777 static int fetch_cca_info(u16 cardnr, u16 domain, struct cca_info *ci)
778 {
779         int rc, found = 0;
780         size_t rlen, vlen;
781         u8 *rarray, *varray, *pg;
782         struct zcrypt_device_status_ext devstat;
783
784         memset(ci, 0, sizeof(*ci));
785
786         /* get first info from zcrypt device driver about this apqn */
787         rc = zcrypt_device_status_ext(cardnr, domain, &devstat);
788         if (rc)
789                 return rc;
790         ci->hwtype = devstat.hwtype;
791
792         /* prep page for rule array and var array use */
793         pg = (u8 *) __get_free_page(GFP_KERNEL);
794         if (!pg)
795                 return -ENOMEM;
796         rarray = pg;
797         varray = pg + PAGE_SIZE/2;
798         rlen = vlen = PAGE_SIZE/2;
799
800         /* QF for this card/domain */
801         rc = cca_query_crypto_facility(cardnr, domain, "STATICSA",
802                                        rarray, &rlen, varray, &vlen);
803         if (rc == 0 && rlen >= 10*8 && vlen >= 204) {
804                 memcpy(ci->serial, rarray, 8);
805                 ci->new_mk_state = (char) rarray[7*8];
806                 ci->cur_mk_state = (char) rarray[8*8];
807                 ci->old_mk_state = (char) rarray[9*8];
808                 if (ci->old_mk_state == '2')
809                         memcpy(&ci->old_mkvp, varray + 172, 8);
810                 if (ci->cur_mk_state == '2')
811                         memcpy(&ci->cur_mkvp, varray + 184, 8);
812                 if (ci->new_mk_state == '3')
813                         memcpy(&ci->new_mkvp, varray + 196, 8);
814                 found = 1;
815         }
816
817         free_page((unsigned long) pg);
818
819         return found ? 0 : -ENOENT;
820 }
821
822 /*
823  * Fetch cca information about a CCA queue.
824  */
825 int cca_get_info(u16 card, u16 dom, struct cca_info *ci, int verify)
826 {
827         int rc;
828
829         rc = cca_info_cache_fetch(card, dom, ci);
830         if (rc || verify) {
831                 rc = fetch_cca_info(card, dom, ci);
832                 if (rc == 0)
833                         cca_info_cache_update(card, dom, ci);
834         }
835
836         return rc;
837 }
838 EXPORT_SYMBOL(cca_get_info);
839
840 /*
841  * Search for a matching crypto card based on the
842  * Master Key Verification Pattern given.
843  */
844 static int findcard(u64 mkvp, u16 *pcardnr, u16 *pdomain,
845                     int verify, int minhwtype)
846 {
847         struct zcrypt_device_status_ext *device_status;
848         u16 card, dom;
849         struct cca_info ci;
850         int i, rc, oi = -1;
851
852         /* mkvp must not be zero, minhwtype needs to be >= 0 */
853         if (mkvp == 0 || minhwtype < 0)
854                 return -EINVAL;
855
856         /* fetch status of all crypto cards */
857         device_status = kmalloc_array(MAX_ZDEV_ENTRIES_EXT,
858                                       sizeof(struct zcrypt_device_status_ext),
859                                       GFP_KERNEL);
860         if (!device_status)
861                 return -ENOMEM;
862         zcrypt_device_status_mask_ext(device_status);
863
864         /* walk through all crypto cards */
865         for (i = 0; i < MAX_ZDEV_ENTRIES_EXT; i++) {
866                 card = AP_QID_CARD(device_status[i].qid);
867                 dom = AP_QID_QUEUE(device_status[i].qid);
868                 if (device_status[i].online &&
869                     device_status[i].functions & 0x04) {
870                         /* enabled CCA card, check current mkvp from cache */
871                         if (cca_info_cache_fetch(card, dom, &ci) == 0 &&
872                             ci.hwtype >= minhwtype &&
873                             ci.cur_mk_state == '2' &&
874                             ci.cur_mkvp == mkvp) {
875                                 if (!verify)
876                                         break;
877                                 /* verify: refresh card info */
878                                 if (fetch_cca_info(card, dom, &ci) == 0) {
879                                         cca_info_cache_update(card, dom, &ci);
880                                         if (ci.hwtype >= minhwtype &&
881                                             ci.cur_mk_state == '2' &&
882                                             ci.cur_mkvp == mkvp)
883                                                 break;
884                                 }
885                         }
886                 } else {
887                         /* Card is offline and/or not a CCA card. */
888                         /* del mkvp entry from cache if it exists */
889                         cca_info_cache_scrub(card, dom);
890                 }
891         }
892         if (i >= MAX_ZDEV_ENTRIES_EXT) {
893                 /* nothing found, so this time without cache */
894                 for (i = 0; i < MAX_ZDEV_ENTRIES_EXT; i++) {
895                         if (!(device_status[i].online &&
896                               device_status[i].functions & 0x04))
897                                 continue;
898                         card = AP_QID_CARD(device_status[i].qid);
899                         dom = AP_QID_QUEUE(device_status[i].qid);
900                         /* fresh fetch mkvp from adapter */
901                         if (fetch_cca_info(card, dom, &ci) == 0) {
902                                 cca_info_cache_update(card, dom, &ci);
903                                 if (ci.hwtype >= minhwtype &&
904                                     ci.cur_mk_state == '2' &&
905                                     ci.cur_mkvp == mkvp)
906                                         break;
907                                 if (ci.hwtype >= minhwtype &&
908                                     ci.old_mk_state == '2' &&
909                                     ci.old_mkvp == mkvp &&
910                                     oi < 0)
911                                         oi = i;
912                         }
913                 }
914                 if (i >= MAX_ZDEV_ENTRIES_EXT && oi >= 0) {
915                         /* old mkvp matched, use this card then */
916                         card = AP_QID_CARD(device_status[oi].qid);
917                         dom = AP_QID_QUEUE(device_status[oi].qid);
918                 }
919         }
920         if (i < MAX_ZDEV_ENTRIES_EXT || oi >= 0) {
921                 if (pcardnr)
922                         *pcardnr = card;
923                 if (pdomain)
924                         *pdomain = dom;
925                 rc = (i < MAX_ZDEV_ENTRIES_EXT ? 0 : 1);
926         } else
927                 rc = -ENODEV;
928
929         kfree(device_status);
930         return rc;
931 }
932
933 /*
934  * Search for a matching crypto card based on the Master Key
935  * Verification Pattern provided inside a secure key token.
936  */
937 int cca_findcard(const u8 *key, u16 *pcardnr, u16 *pdomain, int verify)
938 {
939         u64 mkvp;
940         const struct keytoken_header *hdr = (struct keytoken_header *) key;
941
942         if (hdr->type != TOKTYPE_CCA_INTERNAL)
943                 return -EINVAL;
944
945         switch (hdr->version) {
946         case TOKVER_CCA_AES:
947                 mkvp = ((struct secaeskeytoken *)key)->mkvp;
948                 break;
949         default:
950                 return -EINVAL;
951         }
952
953         return findcard(mkvp, pcardnr, pdomain, verify, 0);
954 }
955 EXPORT_SYMBOL(cca_findcard);
956
957 void __exit zcrypt_ccamisc_exit(void)
958 {
959         mkvp_cache_free();
960 }