xref: /linux/crypto/testmgr.c (revision f694f30e81c4ade358eb8c75273bac1a48f0cb8f)
1 // SPDX-License-Identifier: GPL-2.0-or-later
2 /*
3  * Algorithm testing framework and tests.
4  *
5  * Copyright (c) 2002 James Morris <jmorris@intercode.com.au>
6  * Copyright (c) 2002 Jean-Francois Dive <jef@linuxbe.org>
7  * Copyright (c) 2007 Nokia Siemens Networks
8  * Copyright (c) 2008 Herbert Xu <herbert@gondor.apana.org.au>
9  * Copyright (c) 2019 Google LLC
10  *
11  * Updated RFC4106 AES-GCM testing.
12  *    Authors: Aidan O'Mahony (aidan.o.mahony@intel.com)
13  *             Adrian Hoban <adrian.hoban@intel.com>
14  *             Gabriele Paoloni <gabriele.paoloni@intel.com>
15  *             Tadeusz Struk (tadeusz.struk@intel.com)
16  *    Copyright (c) 2010, Intel Corporation.
17  */
18 
19 #include <crypto/aead.h>
20 #include <crypto/hash.h>
21 #include <crypto/skcipher.h>
22 #include <linux/err.h>
23 #include <linux/fips.h>
24 #include <linux/module.h>
25 #include <linux/once.h>
26 #include <linux/prandom.h>
27 #include <linux/scatterlist.h>
28 #include <linux/slab.h>
29 #include <linux/string.h>
30 #include <linux/uio.h>
31 #include <crypto/rng.h>
32 #include <crypto/drbg.h>
33 #include <crypto/akcipher.h>
34 #include <crypto/kpp.h>
35 #include <crypto/acompress.h>
36 #include <crypto/sig.h>
37 #include <crypto/internal/cipher.h>
38 #include <crypto/internal/simd.h>
39 
40 #include "internal.h"
41 
42 MODULE_IMPORT_NS("CRYPTO_INTERNAL");
43 
44 static bool notests;
45 module_param(notests, bool, 0644);
46 MODULE_PARM_DESC(notests, "disable crypto self-tests");
47 
48 static bool panic_on_fail;
49 module_param(panic_on_fail, bool, 0444);
50 
51 #ifdef CONFIG_CRYPTO_MANAGER_EXTRA_TESTS
52 static bool noextratests;
53 module_param(noextratests, bool, 0644);
54 MODULE_PARM_DESC(noextratests, "disable expensive crypto self-tests");
55 
56 static unsigned int fuzz_iterations = 100;
57 module_param(fuzz_iterations, uint, 0644);
58 MODULE_PARM_DESC(fuzz_iterations, "number of fuzz test iterations");
59 #endif
60 
61 /* Multibuffer is unlimited.  Set arbitrary limit for testing. */
62 #define MAX_MB_MSGS	16
63 
64 #ifdef CONFIG_CRYPTO_MANAGER_DISABLE_TESTS
65 
66 /* a perfect nop */
67 int alg_test(const char *driver, const char *alg, u32 type, u32 mask)
68 {
69 	return 0;
70 }
71 
72 #else
73 
74 #include "testmgr.h"
75 
76 /*
77  * Need slab memory for testing (size in number of pages).
78  */
79 #define XBUFSIZE	8
80 
81 /*
82 * Used by test_cipher()
83 */
84 #define ENCRYPT 1
85 #define DECRYPT 0
86 
87 struct aead_test_suite {
88 	const struct aead_testvec *vecs;
89 	unsigned int count;
90 
91 	/*
92 	 * Set if trying to decrypt an inauthentic ciphertext with this
93 	 * algorithm might result in EINVAL rather than EBADMSG, due to other
94 	 * validation the algorithm does on the inputs such as length checks.
95 	 */
96 	unsigned int einval_allowed : 1;
97 
98 	/*
99 	 * Set if this algorithm requires that the IV be located at the end of
100 	 * the AAD buffer, in addition to being given in the normal way.  The
101 	 * behavior when the two IV copies differ is implementation-defined.
102 	 */
103 	unsigned int aad_iv : 1;
104 };
105 
106 struct cipher_test_suite {
107 	const struct cipher_testvec *vecs;
108 	unsigned int count;
109 };
110 
111 struct comp_test_suite {
112 	struct {
113 		const struct comp_testvec *vecs;
114 		unsigned int count;
115 	} comp, decomp;
116 };
117 
118 struct hash_test_suite {
119 	const struct hash_testvec *vecs;
120 	unsigned int count;
121 };
122 
123 struct cprng_test_suite {
124 	const struct cprng_testvec *vecs;
125 	unsigned int count;
126 };
127 
128 struct drbg_test_suite {
129 	const struct drbg_testvec *vecs;
130 	unsigned int count;
131 };
132 
133 struct akcipher_test_suite {
134 	const struct akcipher_testvec *vecs;
135 	unsigned int count;
136 };
137 
138 struct sig_test_suite {
139 	const struct sig_testvec *vecs;
140 	unsigned int count;
141 };
142 
143 struct kpp_test_suite {
144 	const struct kpp_testvec *vecs;
145 	unsigned int count;
146 };
147 
148 struct alg_test_desc {
149 	const char *alg;
150 	const char *generic_driver;
151 	int (*test)(const struct alg_test_desc *desc, const char *driver,
152 		    u32 type, u32 mask);
153 	int fips_allowed;	/* set if alg is allowed in fips mode */
154 
155 	union {
156 		struct aead_test_suite aead;
157 		struct cipher_test_suite cipher;
158 		struct comp_test_suite comp;
159 		struct hash_test_suite hash;
160 		struct cprng_test_suite cprng;
161 		struct drbg_test_suite drbg;
162 		struct akcipher_test_suite akcipher;
163 		struct sig_test_suite sig;
164 		struct kpp_test_suite kpp;
165 	} suite;
166 };
167 
168 static void hexdump(unsigned char *buf, unsigned int len)
169 {
170 	print_hex_dump(KERN_CONT, "", DUMP_PREFIX_OFFSET,
171 			16, 1,
172 			buf, len, false);
173 }
174 
175 static int __testmgr_alloc_buf(char *buf[XBUFSIZE], int order)
176 {
177 	int i;
178 
179 	for (i = 0; i < XBUFSIZE; i++) {
180 		buf[i] = (char *)__get_free_pages(GFP_KERNEL, order);
181 		if (!buf[i])
182 			goto err_free_buf;
183 	}
184 
185 	return 0;
186 
187 err_free_buf:
188 	while (i-- > 0)
189 		free_pages((unsigned long)buf[i], order);
190 
191 	return -ENOMEM;
192 }
193 
194 static int testmgr_alloc_buf(char *buf[XBUFSIZE])
195 {
196 	return __testmgr_alloc_buf(buf, 0);
197 }
198 
199 static void __testmgr_free_buf(char *buf[XBUFSIZE], int order)
200 {
201 	int i;
202 
203 	for (i = 0; i < XBUFSIZE; i++)
204 		free_pages((unsigned long)buf[i], order);
205 }
206 
207 static void testmgr_free_buf(char *buf[XBUFSIZE])
208 {
209 	__testmgr_free_buf(buf, 0);
210 }
211 
212 #define TESTMGR_POISON_BYTE	0xfe
213 #define TESTMGR_POISON_LEN	16
214 
215 static inline void testmgr_poison(void *addr, size_t len)
216 {
217 	memset(addr, TESTMGR_POISON_BYTE, len);
218 }
219 
220 /* Is the memory region still fully poisoned? */
221 static inline bool testmgr_is_poison(const void *addr, size_t len)
222 {
223 	return memchr_inv(addr, TESTMGR_POISON_BYTE, len) == NULL;
224 }
225 
226 /* flush type for hash algorithms */
227 enum flush_type {
228 	/* merge with update of previous buffer(s) */
229 	FLUSH_TYPE_NONE = 0,
230 
231 	/* update with previous buffer(s) before doing this one */
232 	FLUSH_TYPE_FLUSH,
233 
234 	/* likewise, but also export and re-import the intermediate state */
235 	FLUSH_TYPE_REIMPORT,
236 };
237 
238 /* finalization function for hash algorithms */
239 enum finalization_type {
240 	FINALIZATION_TYPE_FINAL,	/* use final() */
241 	FINALIZATION_TYPE_FINUP,	/* use finup() */
242 	FINALIZATION_TYPE_DIGEST,	/* use digest() */
243 };
244 
245 /*
246  * Whether the crypto operation will occur in-place, and if so whether the
247  * source and destination scatterlist pointers will coincide (req->src ==
248  * req->dst), or whether they'll merely point to two separate scatterlists
249  * (req->src != req->dst) that reference the same underlying memory.
250  *
251  * This is only relevant for algorithm types that support in-place operation.
252  */
253 enum inplace_mode {
254 	OUT_OF_PLACE,
255 	INPLACE_ONE_SGLIST,
256 	INPLACE_TWO_SGLISTS,
257 };
258 
259 #define TEST_SG_TOTAL	10000
260 
261 /**
262  * struct test_sg_division - description of a scatterlist entry
263  *
264  * This struct describes one entry of a scatterlist being constructed to check a
265  * crypto test vector.
266  *
267  * @proportion_of_total: length of this chunk relative to the total length,
268  *			 given as a proportion out of TEST_SG_TOTAL so that it
269  *			 scales to fit any test vector
270  * @offset: byte offset into a 2-page buffer at which this chunk will start
271  * @offset_relative_to_alignmask: if true, add the algorithm's alignmask to the
272  *				  @offset
273  * @flush_type: for hashes, whether an update() should be done now vs.
274  *		continuing to accumulate data
275  * @nosimd: if doing the pending update(), do it with SIMD disabled?
276  */
277 struct test_sg_division {
278 	unsigned int proportion_of_total;
279 	unsigned int offset;
280 	bool offset_relative_to_alignmask;
281 	enum flush_type flush_type;
282 	bool nosimd;
283 };
284 
285 /**
286  * struct testvec_config - configuration for testing a crypto test vector
287  *
288  * This struct describes the data layout and other parameters with which each
289  * crypto test vector can be tested.
290  *
291  * @name: name of this config, logged for debugging purposes if a test fails
292  * @inplace_mode: whether and how to operate on the data in-place, if applicable
293  * @req_flags: extra request_flags, e.g. CRYPTO_TFM_REQ_MAY_SLEEP
294  * @src_divs: description of how to arrange the source scatterlist
295  * @dst_divs: description of how to arrange the dst scatterlist, if applicable
296  *	      for the algorithm type.  Defaults to @src_divs if unset.
297  * @iv_offset: misalignment of the IV in the range [0..MAX_ALGAPI_ALIGNMASK+1],
298  *	       where 0 is aligned to a 2*(MAX_ALGAPI_ALIGNMASK+1) byte boundary
299  * @iv_offset_relative_to_alignmask: if true, add the algorithm's alignmask to
300  *				     the @iv_offset
301  * @key_offset: misalignment of the key, where 0 is default alignment
302  * @key_offset_relative_to_alignmask: if true, add the algorithm's alignmask to
303  *				      the @key_offset
304  * @finalization_type: what finalization function to use for hashes
305  * @nosimd: execute with SIMD disabled?  Requires !CRYPTO_TFM_REQ_MAY_SLEEP.
306  *	    This applies to the parts of the operation that aren't controlled
307  *	    individually by @nosimd_setkey or @src_divs[].nosimd.
308  * @nosimd_setkey: set the key (if applicable) with SIMD disabled?  Requires
309  *		   !CRYPTO_TFM_REQ_MAY_SLEEP.
310  */
311 struct testvec_config {
312 	const char *name;
313 	enum inplace_mode inplace_mode;
314 	u32 req_flags;
315 	struct test_sg_division src_divs[XBUFSIZE];
316 	struct test_sg_division dst_divs[XBUFSIZE];
317 	unsigned int iv_offset;
318 	unsigned int key_offset;
319 	bool iv_offset_relative_to_alignmask;
320 	bool key_offset_relative_to_alignmask;
321 	enum finalization_type finalization_type;
322 	bool nosimd;
323 	bool nosimd_setkey;
324 };
325 
326 #define TESTVEC_CONFIG_NAMELEN	192
327 
328 /*
329  * The following are the lists of testvec_configs to test for each algorithm
330  * type when the basic crypto self-tests are enabled, i.e. when
331  * CONFIG_CRYPTO_MANAGER_DISABLE_TESTS is unset.  They aim to provide good test
332  * coverage, while keeping the test time much shorter than the full fuzz tests
333  * so that the basic tests can be enabled in a wider range of circumstances.
334  */
335 
336 /* Configs for skciphers and aeads */
337 static const struct testvec_config default_cipher_testvec_configs[] = {
338 	{
339 		.name = "in-place (one sglist)",
340 		.inplace_mode = INPLACE_ONE_SGLIST,
341 		.src_divs = { { .proportion_of_total = 10000 } },
342 	}, {
343 		.name = "in-place (two sglists)",
344 		.inplace_mode = INPLACE_TWO_SGLISTS,
345 		.src_divs = { { .proportion_of_total = 10000 } },
346 	}, {
347 		.name = "out-of-place",
348 		.inplace_mode = OUT_OF_PLACE,
349 		.src_divs = { { .proportion_of_total = 10000 } },
350 	}, {
351 		.name = "unaligned buffer, offset=1",
352 		.src_divs = { { .proportion_of_total = 10000, .offset = 1 } },
353 		.iv_offset = 1,
354 		.key_offset = 1,
355 	}, {
356 		.name = "buffer aligned only to alignmask",
357 		.src_divs = {
358 			{
359 				.proportion_of_total = 10000,
360 				.offset = 1,
361 				.offset_relative_to_alignmask = true,
362 			},
363 		},
364 		.iv_offset = 1,
365 		.iv_offset_relative_to_alignmask = true,
366 		.key_offset = 1,
367 		.key_offset_relative_to_alignmask = true,
368 	}, {
369 		.name = "two even aligned splits",
370 		.src_divs = {
371 			{ .proportion_of_total = 5000 },
372 			{ .proportion_of_total = 5000 },
373 		},
374 	}, {
375 		.name = "one src, two even splits dst",
376 		.inplace_mode = OUT_OF_PLACE,
377 		.src_divs = { { .proportion_of_total = 10000 } },
378 		.dst_divs = {
379 			{ .proportion_of_total = 5000 },
380 			{ .proportion_of_total = 5000 },
381 		 },
382 	}, {
383 		.name = "uneven misaligned splits, may sleep",
384 		.req_flags = CRYPTO_TFM_REQ_MAY_SLEEP,
385 		.src_divs = {
386 			{ .proportion_of_total = 1900, .offset = 33 },
387 			{ .proportion_of_total = 3300, .offset = 7  },
388 			{ .proportion_of_total = 4800, .offset = 18 },
389 		},
390 		.iv_offset = 3,
391 		.key_offset = 3,
392 	}, {
393 		.name = "misaligned splits crossing pages, inplace",
394 		.inplace_mode = INPLACE_ONE_SGLIST,
395 		.src_divs = {
396 			{
397 				.proportion_of_total = 7500,
398 				.offset = PAGE_SIZE - 32
399 			}, {
400 				.proportion_of_total = 2500,
401 				.offset = PAGE_SIZE - 7
402 			},
403 		},
404 	}
405 };
406 
407 static const struct testvec_config default_hash_testvec_configs[] = {
408 	{
409 		.name = "init+update+final aligned buffer",
410 		.src_divs = { { .proportion_of_total = 10000 } },
411 		.finalization_type = FINALIZATION_TYPE_FINAL,
412 	}, {
413 		.name = "init+finup aligned buffer",
414 		.src_divs = { { .proportion_of_total = 10000 } },
415 		.finalization_type = FINALIZATION_TYPE_FINUP,
416 	}, {
417 		.name = "digest aligned buffer",
418 		.src_divs = { { .proportion_of_total = 10000 } },
419 		.finalization_type = FINALIZATION_TYPE_DIGEST,
420 	}, {
421 		.name = "init+update+final misaligned buffer",
422 		.src_divs = { { .proportion_of_total = 10000, .offset = 1 } },
423 		.finalization_type = FINALIZATION_TYPE_FINAL,
424 		.key_offset = 1,
425 	}, {
426 		.name = "digest misaligned buffer",
427 		.src_divs = {
428 			{
429 				.proportion_of_total = 10000,
430 				.offset = 1,
431 			},
432 		},
433 		.finalization_type = FINALIZATION_TYPE_DIGEST,
434 		.key_offset = 1,
435 	}, {
436 		.name = "init+update+update+final two even splits",
437 		.src_divs = {
438 			{ .proportion_of_total = 5000 },
439 			{
440 				.proportion_of_total = 5000,
441 				.flush_type = FLUSH_TYPE_FLUSH,
442 			},
443 		},
444 		.finalization_type = FINALIZATION_TYPE_FINAL,
445 	}, {
446 		.name = "digest uneven misaligned splits, may sleep",
447 		.req_flags = CRYPTO_TFM_REQ_MAY_SLEEP,
448 		.src_divs = {
449 			{ .proportion_of_total = 1900, .offset = 33 },
450 			{ .proportion_of_total = 3300, .offset = 7  },
451 			{ .proportion_of_total = 4800, .offset = 18 },
452 		},
453 		.finalization_type = FINALIZATION_TYPE_DIGEST,
454 	}, {
455 		.name = "digest misaligned splits crossing pages",
456 		.src_divs = {
457 			{
458 				.proportion_of_total = 7500,
459 				.offset = PAGE_SIZE - 32,
460 			}, {
461 				.proportion_of_total = 2500,
462 				.offset = PAGE_SIZE - 7,
463 			},
464 		},
465 		.finalization_type = FINALIZATION_TYPE_DIGEST,
466 	}, {
467 		.name = "import/export",
468 		.src_divs = {
469 			{
470 				.proportion_of_total = 6500,
471 				.flush_type = FLUSH_TYPE_REIMPORT,
472 			}, {
473 				.proportion_of_total = 3500,
474 				.flush_type = FLUSH_TYPE_REIMPORT,
475 			},
476 		},
477 		.finalization_type = FINALIZATION_TYPE_FINAL,
478 	}
479 };
480 
481 static unsigned int count_test_sg_divisions(const struct test_sg_division *divs)
482 {
483 	unsigned int remaining = TEST_SG_TOTAL;
484 	unsigned int ndivs = 0;
485 
486 	do {
487 		remaining -= divs[ndivs++].proportion_of_total;
488 	} while (remaining);
489 
490 	return ndivs;
491 }
492 
493 #define SGDIVS_HAVE_FLUSHES	BIT(0)
494 #define SGDIVS_HAVE_NOSIMD	BIT(1)
495 
496 static bool valid_sg_divisions(const struct test_sg_division *divs,
497 			       unsigned int count, int *flags_ret)
498 {
499 	unsigned int total = 0;
500 	unsigned int i;
501 
502 	for (i = 0; i < count && total != TEST_SG_TOTAL; i++) {
503 		if (divs[i].proportion_of_total <= 0 ||
504 		    divs[i].proportion_of_total > TEST_SG_TOTAL - total)
505 			return false;
506 		total += divs[i].proportion_of_total;
507 		if (divs[i].flush_type != FLUSH_TYPE_NONE)
508 			*flags_ret |= SGDIVS_HAVE_FLUSHES;
509 		if (divs[i].nosimd)
510 			*flags_ret |= SGDIVS_HAVE_NOSIMD;
511 	}
512 	return total == TEST_SG_TOTAL &&
513 		memchr_inv(&divs[i], 0, (count - i) * sizeof(divs[0])) == NULL;
514 }
515 
516 /*
517  * Check whether the given testvec_config is valid.  This isn't strictly needed
518  * since every testvec_config should be valid, but check anyway so that people
519  * don't unknowingly add broken configs that don't do what they wanted.
520  */
521 static bool valid_testvec_config(const struct testvec_config *cfg)
522 {
523 	int flags = 0;
524 
525 	if (cfg->name == NULL)
526 		return false;
527 
528 	if (!valid_sg_divisions(cfg->src_divs, ARRAY_SIZE(cfg->src_divs),
529 				&flags))
530 		return false;
531 
532 	if (cfg->dst_divs[0].proportion_of_total) {
533 		if (!valid_sg_divisions(cfg->dst_divs,
534 					ARRAY_SIZE(cfg->dst_divs), &flags))
535 			return false;
536 	} else {
537 		if (memchr_inv(cfg->dst_divs, 0, sizeof(cfg->dst_divs)))
538 			return false;
539 		/* defaults to dst_divs=src_divs */
540 	}
541 
542 	if (cfg->iv_offset +
543 	    (cfg->iv_offset_relative_to_alignmask ? MAX_ALGAPI_ALIGNMASK : 0) >
544 	    MAX_ALGAPI_ALIGNMASK + 1)
545 		return false;
546 
547 	if ((flags & (SGDIVS_HAVE_FLUSHES | SGDIVS_HAVE_NOSIMD)) &&
548 	    cfg->finalization_type == FINALIZATION_TYPE_DIGEST)
549 		return false;
550 
551 	if ((cfg->nosimd || cfg->nosimd_setkey ||
552 	     (flags & SGDIVS_HAVE_NOSIMD)) &&
553 	    (cfg->req_flags & CRYPTO_TFM_REQ_MAY_SLEEP))
554 		return false;
555 
556 	return true;
557 }
558 
559 struct test_sglist {
560 	char *bufs[XBUFSIZE];
561 	struct scatterlist sgl[XBUFSIZE];
562 	struct scatterlist sgl_saved[XBUFSIZE];
563 	struct scatterlist *sgl_ptr;
564 	unsigned int nents;
565 };
566 
567 static int init_test_sglist(struct test_sglist *tsgl)
568 {
569 	return __testmgr_alloc_buf(tsgl->bufs, 1 /* two pages per buffer */);
570 }
571 
572 static void destroy_test_sglist(struct test_sglist *tsgl)
573 {
574 	return __testmgr_free_buf(tsgl->bufs, 1 /* two pages per buffer */);
575 }
576 
577 /**
578  * build_test_sglist() - build a scatterlist for a crypto test
579  *
580  * @tsgl: the scatterlist to build.  @tsgl->bufs[] contains an array of 2-page
581  *	  buffers which the scatterlist @tsgl->sgl[] will be made to point into.
582  * @divs: the layout specification on which the scatterlist will be based
583  * @alignmask: the algorithm's alignmask
584  * @total_len: the total length of the scatterlist to build in bytes
585  * @data: if non-NULL, the buffers will be filled with this data until it ends.
586  *	  Otherwise the buffers will be poisoned.  In both cases, some bytes
587  *	  past the end of each buffer will be poisoned to help detect overruns.
588  * @out_divs: if non-NULL, the test_sg_division to which each scatterlist entry
589  *	      corresponds will be returned here.  This will match @divs except
590  *	      that divisions resolving to a length of 0 are omitted as they are
591  *	      not included in the scatterlist.
592  *
593  * Return: 0 or a -errno value
594  */
595 static int build_test_sglist(struct test_sglist *tsgl,
596 			     const struct test_sg_division *divs,
597 			     const unsigned int alignmask,
598 			     const unsigned int total_len,
599 			     struct iov_iter *data,
600 			     const struct test_sg_division *out_divs[XBUFSIZE])
601 {
602 	struct {
603 		const struct test_sg_division *div;
604 		size_t length;
605 	} partitions[XBUFSIZE];
606 	const unsigned int ndivs = count_test_sg_divisions(divs);
607 	unsigned int len_remaining = total_len;
608 	unsigned int i;
609 
610 	BUILD_BUG_ON(ARRAY_SIZE(partitions) != ARRAY_SIZE(tsgl->sgl));
611 	if (WARN_ON(ndivs > ARRAY_SIZE(partitions)))
612 		return -EINVAL;
613 
614 	/* Calculate the (div, length) pairs */
615 	tsgl->nents = 0;
616 	for (i = 0; i < ndivs; i++) {
617 		unsigned int len_this_sg =
618 			min(len_remaining,
619 			    (total_len * divs[i].proportion_of_total +
620 			     TEST_SG_TOTAL / 2) / TEST_SG_TOTAL);
621 
622 		if (len_this_sg != 0) {
623 			partitions[tsgl->nents].div = &divs[i];
624 			partitions[tsgl->nents].length = len_this_sg;
625 			tsgl->nents++;
626 			len_remaining -= len_this_sg;
627 		}
628 	}
629 	if (tsgl->nents == 0) {
630 		partitions[tsgl->nents].div = &divs[0];
631 		partitions[tsgl->nents].length = 0;
632 		tsgl->nents++;
633 	}
634 	partitions[tsgl->nents - 1].length += len_remaining;
635 
636 	/* Set up the sgl entries and fill the data or poison */
637 	sg_init_table(tsgl->sgl, tsgl->nents);
638 	for (i = 0; i < tsgl->nents; i++) {
639 		unsigned int offset = partitions[i].div->offset;
640 		void *addr;
641 
642 		if (partitions[i].div->offset_relative_to_alignmask)
643 			offset += alignmask;
644 
645 		while (offset + partitions[i].length + TESTMGR_POISON_LEN >
646 		       2 * PAGE_SIZE) {
647 			if (WARN_ON(offset <= 0))
648 				return -EINVAL;
649 			offset /= 2;
650 		}
651 
652 		addr = &tsgl->bufs[i][offset];
653 		sg_set_buf(&tsgl->sgl[i], addr, partitions[i].length);
654 
655 		if (out_divs)
656 			out_divs[i] = partitions[i].div;
657 
658 		if (data) {
659 			size_t copy_len, copied;
660 
661 			copy_len = min(partitions[i].length, data->count);
662 			copied = copy_from_iter(addr, copy_len, data);
663 			if (WARN_ON(copied != copy_len))
664 				return -EINVAL;
665 			testmgr_poison(addr + copy_len, partitions[i].length +
666 				       TESTMGR_POISON_LEN - copy_len);
667 		} else {
668 			testmgr_poison(addr, partitions[i].length +
669 				       TESTMGR_POISON_LEN);
670 		}
671 	}
672 
673 	sg_mark_end(&tsgl->sgl[tsgl->nents - 1]);
674 	tsgl->sgl_ptr = tsgl->sgl;
675 	memcpy(tsgl->sgl_saved, tsgl->sgl, tsgl->nents * sizeof(tsgl->sgl[0]));
676 	return 0;
677 }
678 
679 /*
680  * Verify that a scatterlist crypto operation produced the correct output.
681  *
682  * @tsgl: scatterlist containing the actual output
683  * @expected_output: buffer containing the expected output
684  * @len_to_check: length of @expected_output in bytes
685  * @unchecked_prefix_len: number of ignored bytes in @tsgl prior to real result
686  * @check_poison: verify that the poison bytes after each chunk are intact?
687  *
688  * Return: 0 if correct, -EINVAL if incorrect, -EOVERFLOW if buffer overrun.
689  */
690 static int verify_correct_output(const struct test_sglist *tsgl,
691 				 const char *expected_output,
692 				 unsigned int len_to_check,
693 				 unsigned int unchecked_prefix_len,
694 				 bool check_poison)
695 {
696 	unsigned int i;
697 
698 	for (i = 0; i < tsgl->nents; i++) {
699 		struct scatterlist *sg = &tsgl->sgl_ptr[i];
700 		unsigned int len = sg->length;
701 		unsigned int offset = sg->offset;
702 		const char *actual_output;
703 
704 		if (unchecked_prefix_len) {
705 			if (unchecked_prefix_len >= len) {
706 				unchecked_prefix_len -= len;
707 				continue;
708 			}
709 			offset += unchecked_prefix_len;
710 			len -= unchecked_prefix_len;
711 			unchecked_prefix_len = 0;
712 		}
713 		len = min(len, len_to_check);
714 		actual_output = page_address(sg_page(sg)) + offset;
715 		if (memcmp(expected_output, actual_output, len) != 0)
716 			return -EINVAL;
717 		if (check_poison &&
718 		    !testmgr_is_poison(actual_output + len, TESTMGR_POISON_LEN))
719 			return -EOVERFLOW;
720 		len_to_check -= len;
721 		expected_output += len;
722 	}
723 	if (WARN_ON(len_to_check != 0))
724 		return -EINVAL;
725 	return 0;
726 }
727 
728 static bool is_test_sglist_corrupted(const struct test_sglist *tsgl)
729 {
730 	unsigned int i;
731 
732 	for (i = 0; i < tsgl->nents; i++) {
733 		if (tsgl->sgl[i].page_link != tsgl->sgl_saved[i].page_link)
734 			return true;
735 		if (tsgl->sgl[i].offset != tsgl->sgl_saved[i].offset)
736 			return true;
737 		if (tsgl->sgl[i].length != tsgl->sgl_saved[i].length)
738 			return true;
739 	}
740 	return false;
741 }
742 
743 struct cipher_test_sglists {
744 	struct test_sglist src;
745 	struct test_sglist dst;
746 };
747 
748 static struct cipher_test_sglists *alloc_cipher_test_sglists(void)
749 {
750 	struct cipher_test_sglists *tsgls;
751 
752 	tsgls = kmalloc(sizeof(*tsgls), GFP_KERNEL);
753 	if (!tsgls)
754 		return NULL;
755 
756 	if (init_test_sglist(&tsgls->src) != 0)
757 		goto fail_kfree;
758 	if (init_test_sglist(&tsgls->dst) != 0)
759 		goto fail_destroy_src;
760 
761 	return tsgls;
762 
763 fail_destroy_src:
764 	destroy_test_sglist(&tsgls->src);
765 fail_kfree:
766 	kfree(tsgls);
767 	return NULL;
768 }
769 
770 static void free_cipher_test_sglists(struct cipher_test_sglists *tsgls)
771 {
772 	if (tsgls) {
773 		destroy_test_sglist(&tsgls->src);
774 		destroy_test_sglist(&tsgls->dst);
775 		kfree(tsgls);
776 	}
777 }
778 
779 /* Build the src and dst scatterlists for an skcipher or AEAD test */
780 static int build_cipher_test_sglists(struct cipher_test_sglists *tsgls,
781 				     const struct testvec_config *cfg,
782 				     unsigned int alignmask,
783 				     unsigned int src_total_len,
784 				     unsigned int dst_total_len,
785 				     const struct kvec *inputs,
786 				     unsigned int nr_inputs)
787 {
788 	struct iov_iter input;
789 	int err;
790 
791 	iov_iter_kvec(&input, ITER_SOURCE, inputs, nr_inputs, src_total_len);
792 	err = build_test_sglist(&tsgls->src, cfg->src_divs, alignmask,
793 				cfg->inplace_mode != OUT_OF_PLACE ?
794 					max(dst_total_len, src_total_len) :
795 					src_total_len,
796 				&input, NULL);
797 	if (err)
798 		return err;
799 
800 	/*
801 	 * In-place crypto operations can use the same scatterlist for both the
802 	 * source and destination (req->src == req->dst), or can use separate
803 	 * scatterlists (req->src != req->dst) which point to the same
804 	 * underlying memory.  Make sure to test both cases.
805 	 */
806 	if (cfg->inplace_mode == INPLACE_ONE_SGLIST) {
807 		tsgls->dst.sgl_ptr = tsgls->src.sgl;
808 		tsgls->dst.nents = tsgls->src.nents;
809 		return 0;
810 	}
811 	if (cfg->inplace_mode == INPLACE_TWO_SGLISTS) {
812 		/*
813 		 * For now we keep it simple and only test the case where the
814 		 * two scatterlists have identical entries, rather than
815 		 * different entries that split up the same memory differently.
816 		 */
817 		memcpy(tsgls->dst.sgl, tsgls->src.sgl,
818 		       tsgls->src.nents * sizeof(tsgls->src.sgl[0]));
819 		memcpy(tsgls->dst.sgl_saved, tsgls->src.sgl,
820 		       tsgls->src.nents * sizeof(tsgls->src.sgl[0]));
821 		tsgls->dst.sgl_ptr = tsgls->dst.sgl;
822 		tsgls->dst.nents = tsgls->src.nents;
823 		return 0;
824 	}
825 	/* Out of place */
826 	return build_test_sglist(&tsgls->dst,
827 				 cfg->dst_divs[0].proportion_of_total ?
828 					cfg->dst_divs : cfg->src_divs,
829 				 alignmask, dst_total_len, NULL, NULL);
830 }
831 
832 /*
833  * Support for testing passing a misaligned key to setkey():
834  *
835  * If cfg->key_offset is set, copy the key into a new buffer at that offset,
836  * optionally adding alignmask.  Else, just use the key directly.
837  */
838 static int prepare_keybuf(const u8 *key, unsigned int ksize,
839 			  const struct testvec_config *cfg,
840 			  unsigned int alignmask,
841 			  const u8 **keybuf_ret, const u8 **keyptr_ret)
842 {
843 	unsigned int key_offset = cfg->key_offset;
844 	u8 *keybuf = NULL, *keyptr = (u8 *)key;
845 
846 	if (key_offset != 0) {
847 		if (cfg->key_offset_relative_to_alignmask)
848 			key_offset += alignmask;
849 		keybuf = kmalloc(key_offset + ksize, GFP_KERNEL);
850 		if (!keybuf)
851 			return -ENOMEM;
852 		keyptr = keybuf + key_offset;
853 		memcpy(keyptr, key, ksize);
854 	}
855 	*keybuf_ret = keybuf;
856 	*keyptr_ret = keyptr;
857 	return 0;
858 }
859 
860 /*
861  * Like setkey_f(tfm, key, ksize), but sometimes misalign the key.
862  * In addition, run the setkey function in no-SIMD context if requested.
863  */
864 #define do_setkey(setkey_f, tfm, key, ksize, cfg, alignmask)		\
865 ({									\
866 	const u8 *keybuf, *keyptr;					\
867 	int err;							\
868 									\
869 	err = prepare_keybuf((key), (ksize), (cfg), (alignmask),	\
870 			     &keybuf, &keyptr);				\
871 	if (err == 0) {							\
872 		if ((cfg)->nosimd_setkey)				\
873 			crypto_disable_simd_for_test();			\
874 		err = setkey_f((tfm), keyptr, (ksize));			\
875 		if ((cfg)->nosimd_setkey)				\
876 			crypto_reenable_simd_for_test();		\
877 		kfree(keybuf);						\
878 	}								\
879 	err;								\
880 })
881 
882 #ifdef CONFIG_CRYPTO_MANAGER_EXTRA_TESTS
883 
884 /*
885  * The fuzz tests use prandom instead of the normal Linux RNG since they don't
886  * need cryptographically secure random numbers.  This greatly improves the
887  * performance of these tests, especially if they are run before the Linux RNG
888  * has been initialized or if they are run on a lockdep-enabled kernel.
889  */
890 
891 static inline void init_rnd_state(struct rnd_state *rng)
892 {
893 	prandom_seed_state(rng, get_random_u64());
894 }
895 
896 static inline u8 prandom_u8(struct rnd_state *rng)
897 {
898 	return prandom_u32_state(rng);
899 }
900 
901 static inline u32 prandom_u32_below(struct rnd_state *rng, u32 ceil)
902 {
903 	/*
904 	 * This is slightly biased for non-power-of-2 values of 'ceil', but this
905 	 * isn't important here.
906 	 */
907 	return prandom_u32_state(rng) % ceil;
908 }
909 
910 static inline bool prandom_bool(struct rnd_state *rng)
911 {
912 	return prandom_u32_below(rng, 2);
913 }
914 
915 static inline u32 prandom_u32_inclusive(struct rnd_state *rng,
916 					u32 floor, u32 ceil)
917 {
918 	return floor + prandom_u32_below(rng, ceil - floor + 1);
919 }
920 
921 /* Generate a random length in range [0, max_len], but prefer smaller values */
922 static unsigned int generate_random_length(struct rnd_state *rng,
923 					   unsigned int max_len)
924 {
925 	unsigned int len = prandom_u32_below(rng, max_len + 1);
926 
927 	switch (prandom_u32_below(rng, 4)) {
928 	case 0:
929 		len %= 64;
930 		break;
931 	case 1:
932 		len %= 256;
933 		break;
934 	case 2:
935 		len %= 1024;
936 		break;
937 	default:
938 		break;
939 	}
940 	if (len && prandom_u32_below(rng, 4) == 0)
941 		len = rounddown_pow_of_two(len);
942 	return len;
943 }
944 
945 /* Flip a random bit in the given nonempty data buffer */
946 static void flip_random_bit(struct rnd_state *rng, u8 *buf, size_t size)
947 {
948 	size_t bitpos;
949 
950 	bitpos = prandom_u32_below(rng, size * 8);
951 	buf[bitpos / 8] ^= 1 << (bitpos % 8);
952 }
953 
954 /* Flip a random byte in the given nonempty data buffer */
955 static void flip_random_byte(struct rnd_state *rng, u8 *buf, size_t size)
956 {
957 	buf[prandom_u32_below(rng, size)] ^= 0xff;
958 }
959 
960 /* Sometimes make some random changes to the given nonempty data buffer */
961 static void mutate_buffer(struct rnd_state *rng, u8 *buf, size_t size)
962 {
963 	size_t num_flips;
964 	size_t i;
965 
966 	/* Sometimes flip some bits */
967 	if (prandom_u32_below(rng, 4) == 0) {
968 		num_flips = min_t(size_t, 1 << prandom_u32_below(rng, 8),
969 				  size * 8);
970 		for (i = 0; i < num_flips; i++)
971 			flip_random_bit(rng, buf, size);
972 	}
973 
974 	/* Sometimes flip some bytes */
975 	if (prandom_u32_below(rng, 4) == 0) {
976 		num_flips = min_t(size_t, 1 << prandom_u32_below(rng, 8), size);
977 		for (i = 0; i < num_flips; i++)
978 			flip_random_byte(rng, buf, size);
979 	}
980 }
981 
982 /* Randomly generate 'count' bytes, but sometimes make them "interesting" */
983 static void generate_random_bytes(struct rnd_state *rng, u8 *buf, size_t count)
984 {
985 	u8 b;
986 	u8 increment;
987 	size_t i;
988 
989 	if (count == 0)
990 		return;
991 
992 	switch (prandom_u32_below(rng, 8)) { /* Choose a generation strategy */
993 	case 0:
994 	case 1:
995 		/* All the same byte, plus optional mutations */
996 		switch (prandom_u32_below(rng, 4)) {
997 		case 0:
998 			b = 0x00;
999 			break;
1000 		case 1:
1001 			b = 0xff;
1002 			break;
1003 		default:
1004 			b = prandom_u8(rng);
1005 			break;
1006 		}
1007 		memset(buf, b, count);
1008 		mutate_buffer(rng, buf, count);
1009 		break;
1010 	case 2:
1011 		/* Ascending or descending bytes, plus optional mutations */
1012 		increment = prandom_u8(rng);
1013 		b = prandom_u8(rng);
1014 		for (i = 0; i < count; i++, b += increment)
1015 			buf[i] = b;
1016 		mutate_buffer(rng, buf, count);
1017 		break;
1018 	default:
1019 		/* Fully random bytes */
1020 		prandom_bytes_state(rng, buf, count);
1021 	}
1022 }
1023 
1024 static char *generate_random_sgl_divisions(struct rnd_state *rng,
1025 					   struct test_sg_division *divs,
1026 					   size_t max_divs, char *p, char *end,
1027 					   bool gen_flushes, u32 req_flags)
1028 {
1029 	struct test_sg_division *div = divs;
1030 	unsigned int remaining = TEST_SG_TOTAL;
1031 
1032 	do {
1033 		unsigned int this_len;
1034 		const char *flushtype_str;
1035 
1036 		if (div == &divs[max_divs - 1] || prandom_bool(rng))
1037 			this_len = remaining;
1038 		else if (prandom_u32_below(rng, 4) == 0)
1039 			this_len = (remaining + 1) / 2;
1040 		else
1041 			this_len = prandom_u32_inclusive(rng, 1, remaining);
1042 		div->proportion_of_total = this_len;
1043 
1044 		if (prandom_u32_below(rng, 4) == 0)
1045 			div->offset = prandom_u32_inclusive(rng,
1046 							    PAGE_SIZE - 128,
1047 							    PAGE_SIZE - 1);
1048 		else if (prandom_bool(rng))
1049 			div->offset = prandom_u32_below(rng, 32);
1050 		else
1051 			div->offset = prandom_u32_below(rng, PAGE_SIZE);
1052 		if (prandom_u32_below(rng, 8) == 0)
1053 			div->offset_relative_to_alignmask = true;
1054 
1055 		div->flush_type = FLUSH_TYPE_NONE;
1056 		if (gen_flushes) {
1057 			switch (prandom_u32_below(rng, 4)) {
1058 			case 0:
1059 				div->flush_type = FLUSH_TYPE_REIMPORT;
1060 				break;
1061 			case 1:
1062 				div->flush_type = FLUSH_TYPE_FLUSH;
1063 				break;
1064 			}
1065 		}
1066 
1067 		if (div->flush_type != FLUSH_TYPE_NONE &&
1068 		    !(req_flags & CRYPTO_TFM_REQ_MAY_SLEEP) &&
1069 		    prandom_bool(rng))
1070 			div->nosimd = true;
1071 
1072 		switch (div->flush_type) {
1073 		case FLUSH_TYPE_FLUSH:
1074 			if (div->nosimd)
1075 				flushtype_str = "<flush,nosimd>";
1076 			else
1077 				flushtype_str = "<flush>";
1078 			break;
1079 		case FLUSH_TYPE_REIMPORT:
1080 			if (div->nosimd)
1081 				flushtype_str = "<reimport,nosimd>";
1082 			else
1083 				flushtype_str = "<reimport>";
1084 			break;
1085 		default:
1086 			flushtype_str = "";
1087 			break;
1088 		}
1089 
1090 		BUILD_BUG_ON(TEST_SG_TOTAL != 10000); /* for "%u.%u%%" */
1091 		p += scnprintf(p, end - p, "%s%u.%u%%@%s+%u%s", flushtype_str,
1092 			       this_len / 100, this_len % 100,
1093 			       div->offset_relative_to_alignmask ?
1094 					"alignmask" : "",
1095 			       div->offset, this_len == remaining ? "" : ", ");
1096 		remaining -= this_len;
1097 		div++;
1098 	} while (remaining);
1099 
1100 	return p;
1101 }
1102 
1103 /* Generate a random testvec_config for fuzz testing */
1104 static void generate_random_testvec_config(struct rnd_state *rng,
1105 					   struct testvec_config *cfg,
1106 					   char *name, size_t max_namelen)
1107 {
1108 	char *p = name;
1109 	char * const end = name + max_namelen;
1110 
1111 	memset(cfg, 0, sizeof(*cfg));
1112 
1113 	cfg->name = name;
1114 
1115 	p += scnprintf(p, end - p, "random:");
1116 
1117 	switch (prandom_u32_below(rng, 4)) {
1118 	case 0:
1119 	case 1:
1120 		cfg->inplace_mode = OUT_OF_PLACE;
1121 		break;
1122 	case 2:
1123 		cfg->inplace_mode = INPLACE_ONE_SGLIST;
1124 		p += scnprintf(p, end - p, " inplace_one_sglist");
1125 		break;
1126 	default:
1127 		cfg->inplace_mode = INPLACE_TWO_SGLISTS;
1128 		p += scnprintf(p, end - p, " inplace_two_sglists");
1129 		break;
1130 	}
1131 
1132 	if (prandom_bool(rng)) {
1133 		cfg->req_flags |= CRYPTO_TFM_REQ_MAY_SLEEP;
1134 		p += scnprintf(p, end - p, " may_sleep");
1135 	}
1136 
1137 	switch (prandom_u32_below(rng, 4)) {
1138 	case 0:
1139 		cfg->finalization_type = FINALIZATION_TYPE_FINAL;
1140 		p += scnprintf(p, end - p, " use_final");
1141 		break;
1142 	case 1:
1143 		cfg->finalization_type = FINALIZATION_TYPE_FINUP;
1144 		p += scnprintf(p, end - p, " use_finup");
1145 		break;
1146 	default:
1147 		cfg->finalization_type = FINALIZATION_TYPE_DIGEST;
1148 		p += scnprintf(p, end - p, " use_digest");
1149 		break;
1150 	}
1151 
1152 	if (!(cfg->req_flags & CRYPTO_TFM_REQ_MAY_SLEEP)) {
1153 		if (prandom_bool(rng)) {
1154 			cfg->nosimd = true;
1155 			p += scnprintf(p, end - p, " nosimd");
1156 		}
1157 		if (prandom_bool(rng)) {
1158 			cfg->nosimd_setkey = true;
1159 			p += scnprintf(p, end - p, " nosimd_setkey");
1160 		}
1161 	}
1162 
1163 	p += scnprintf(p, end - p, " src_divs=[");
1164 	p = generate_random_sgl_divisions(rng, cfg->src_divs,
1165 					  ARRAY_SIZE(cfg->src_divs), p, end,
1166 					  (cfg->finalization_type !=
1167 					   FINALIZATION_TYPE_DIGEST),
1168 					  cfg->req_flags);
1169 	p += scnprintf(p, end - p, "]");
1170 
1171 	if (cfg->inplace_mode == OUT_OF_PLACE && prandom_bool(rng)) {
1172 		p += scnprintf(p, end - p, " dst_divs=[");
1173 		p = generate_random_sgl_divisions(rng, cfg->dst_divs,
1174 						  ARRAY_SIZE(cfg->dst_divs),
1175 						  p, end, false,
1176 						  cfg->req_flags);
1177 		p += scnprintf(p, end - p, "]");
1178 	}
1179 
1180 	if (prandom_bool(rng)) {
1181 		cfg->iv_offset = prandom_u32_inclusive(rng, 1,
1182 						       MAX_ALGAPI_ALIGNMASK);
1183 		p += scnprintf(p, end - p, " iv_offset=%u", cfg->iv_offset);
1184 	}
1185 
1186 	if (prandom_bool(rng)) {
1187 		cfg->key_offset = prandom_u32_inclusive(rng, 1,
1188 							MAX_ALGAPI_ALIGNMASK);
1189 		p += scnprintf(p, end - p, " key_offset=%u", cfg->key_offset);
1190 	}
1191 
1192 	WARN_ON_ONCE(!valid_testvec_config(cfg));
1193 }
1194 
1195 static void crypto_disable_simd_for_test(void)
1196 {
1197 	migrate_disable();
1198 	__this_cpu_write(crypto_simd_disabled_for_test, true);
1199 }
1200 
1201 static void crypto_reenable_simd_for_test(void)
1202 {
1203 	__this_cpu_write(crypto_simd_disabled_for_test, false);
1204 	migrate_enable();
1205 }
1206 
1207 /*
1208  * Given an algorithm name, build the name of the generic implementation of that
1209  * algorithm, assuming the usual naming convention.  Specifically, this appends
1210  * "-generic" to every part of the name that is not a template name.  Examples:
1211  *
1212  *	aes => aes-generic
1213  *	cbc(aes) => cbc(aes-generic)
1214  *	cts(cbc(aes)) => cts(cbc(aes-generic))
1215  *	rfc7539(chacha20,poly1305) => rfc7539(chacha20-generic,poly1305-generic)
1216  *
1217  * Return: 0 on success, or -ENAMETOOLONG if the generic name would be too long
1218  */
1219 static int build_generic_driver_name(const char *algname,
1220 				     char driver_name[CRYPTO_MAX_ALG_NAME])
1221 {
1222 	const char *in = algname;
1223 	char *out = driver_name;
1224 	size_t len = strlen(algname);
1225 
1226 	if (len >= CRYPTO_MAX_ALG_NAME)
1227 		goto too_long;
1228 	do {
1229 		const char *in_saved = in;
1230 
1231 		while (*in && *in != '(' && *in != ')' && *in != ',')
1232 			*out++ = *in++;
1233 		if (*in != '(' && in > in_saved) {
1234 			len += 8;
1235 			if (len >= CRYPTO_MAX_ALG_NAME)
1236 				goto too_long;
1237 			memcpy(out, "-generic", 8);
1238 			out += 8;
1239 		}
1240 	} while ((*out++ = *in++) != '\0');
1241 	return 0;
1242 
1243 too_long:
1244 	pr_err("alg: generic driver name for \"%s\" would be too long\n",
1245 	       algname);
1246 	return -ENAMETOOLONG;
1247 }
1248 #else /* !CONFIG_CRYPTO_MANAGER_EXTRA_TESTS */
1249 static void crypto_disable_simd_for_test(void)
1250 {
1251 }
1252 
1253 static void crypto_reenable_simd_for_test(void)
1254 {
1255 }
1256 #endif /* !CONFIG_CRYPTO_MANAGER_EXTRA_TESTS */
1257 
1258 static int build_hash_sglist(struct test_sglist *tsgl,
1259 			     const struct hash_testvec *vec,
1260 			     const struct testvec_config *cfg,
1261 			     unsigned int alignmask,
1262 			     const struct test_sg_division *divs[XBUFSIZE])
1263 {
1264 	struct kvec kv;
1265 	struct iov_iter input;
1266 
1267 	kv.iov_base = (void *)vec->plaintext;
1268 	kv.iov_len = vec->psize;
1269 	iov_iter_kvec(&input, ITER_SOURCE, &kv, 1, vec->psize);
1270 	return build_test_sglist(tsgl, cfg->src_divs, alignmask, vec->psize,
1271 				 &input, divs);
1272 }
1273 
1274 static int check_hash_result(const char *type,
1275 			     const u8 *result, unsigned int digestsize,
1276 			     const struct hash_testvec *vec,
1277 			     const char *vec_name,
1278 			     const char *driver,
1279 			     const struct testvec_config *cfg)
1280 {
1281 	if (memcmp(result, vec->digest, digestsize) != 0) {
1282 		pr_err("alg: %s: %s test failed (wrong result) on test vector %s, cfg=\"%s\"\n",
1283 		       type, driver, vec_name, cfg->name);
1284 		return -EINVAL;
1285 	}
1286 	if (!testmgr_is_poison(&result[digestsize], TESTMGR_POISON_LEN)) {
1287 		pr_err("alg: %s: %s overran result buffer on test vector %s, cfg=\"%s\"\n",
1288 		       type, driver, vec_name, cfg->name);
1289 		return -EOVERFLOW;
1290 	}
1291 	return 0;
1292 }
1293 
1294 static inline int check_shash_op(const char *op, int err,
1295 				 const char *driver, const char *vec_name,
1296 				 const struct testvec_config *cfg)
1297 {
1298 	if (err)
1299 		pr_err("alg: shash: %s %s() failed with err %d on test vector %s, cfg=\"%s\"\n",
1300 		       driver, op, err, vec_name, cfg->name);
1301 	return err;
1302 }
1303 
1304 /* Test one hash test vector in one configuration, using the shash API */
1305 static int test_shash_vec_cfg(const struct hash_testvec *vec,
1306 			      const char *vec_name,
1307 			      const struct testvec_config *cfg,
1308 			      struct shash_desc *desc,
1309 			      struct test_sglist *tsgl,
1310 			      u8 *hashstate)
1311 {
1312 	struct crypto_shash *tfm = desc->tfm;
1313 	const unsigned int digestsize = crypto_shash_digestsize(tfm);
1314 	const unsigned int statesize = crypto_shash_statesize(tfm);
1315 	const char *driver = crypto_shash_driver_name(tfm);
1316 	const struct test_sg_division *divs[XBUFSIZE];
1317 	unsigned int i;
1318 	u8 result[HASH_MAX_DIGESTSIZE + TESTMGR_POISON_LEN];
1319 	int err;
1320 
1321 	/* Set the key, if specified */
1322 	if (vec->ksize) {
1323 		err = do_setkey(crypto_shash_setkey, tfm, vec->key, vec->ksize,
1324 				cfg, 0);
1325 		if (err) {
1326 			if (err == vec->setkey_error)
1327 				return 0;
1328 			pr_err("alg: shash: %s setkey failed on test vector %s; expected_error=%d, actual_error=%d, flags=%#x\n",
1329 			       driver, vec_name, vec->setkey_error, err,
1330 			       crypto_shash_get_flags(tfm));
1331 			return err;
1332 		}
1333 		if (vec->setkey_error) {
1334 			pr_err("alg: shash: %s setkey unexpectedly succeeded on test vector %s; expected_error=%d\n",
1335 			       driver, vec_name, vec->setkey_error);
1336 			return -EINVAL;
1337 		}
1338 	}
1339 
1340 	/* Build the scatterlist for the source data */
1341 	err = build_hash_sglist(tsgl, vec, cfg, 0, divs);
1342 	if (err) {
1343 		pr_err("alg: shash: %s: error preparing scatterlist for test vector %s, cfg=\"%s\"\n",
1344 		       driver, vec_name, cfg->name);
1345 		return err;
1346 	}
1347 
1348 	/* Do the actual hashing */
1349 
1350 	testmgr_poison(desc->__ctx, crypto_shash_descsize(tfm));
1351 	testmgr_poison(result, digestsize + TESTMGR_POISON_LEN);
1352 
1353 	if (cfg->finalization_type == FINALIZATION_TYPE_DIGEST ||
1354 	    vec->digest_error) {
1355 		/* Just using digest() */
1356 		if (tsgl->nents != 1)
1357 			return 0;
1358 		if (cfg->nosimd)
1359 			crypto_disable_simd_for_test();
1360 		err = crypto_shash_digest(desc, sg_virt(&tsgl->sgl[0]),
1361 					  tsgl->sgl[0].length, result);
1362 		if (cfg->nosimd)
1363 			crypto_reenable_simd_for_test();
1364 		if (err) {
1365 			if (err == vec->digest_error)
1366 				return 0;
1367 			pr_err("alg: shash: %s digest() failed on test vector %s; expected_error=%d, actual_error=%d, cfg=\"%s\"\n",
1368 			       driver, vec_name, vec->digest_error, err,
1369 			       cfg->name);
1370 			return err;
1371 		}
1372 		if (vec->digest_error) {
1373 			pr_err("alg: shash: %s digest() unexpectedly succeeded on test vector %s; expected_error=%d, cfg=\"%s\"\n",
1374 			       driver, vec_name, vec->digest_error, cfg->name);
1375 			return -EINVAL;
1376 		}
1377 		goto result_ready;
1378 	}
1379 
1380 	/* Using init(), zero or more update(), then final() or finup() */
1381 
1382 	if (cfg->nosimd)
1383 		crypto_disable_simd_for_test();
1384 	err = crypto_shash_init(desc);
1385 	if (cfg->nosimd)
1386 		crypto_reenable_simd_for_test();
1387 	err = check_shash_op("init", err, driver, vec_name, cfg);
1388 	if (err)
1389 		return err;
1390 
1391 	for (i = 0; i < tsgl->nents; i++) {
1392 		if (i + 1 == tsgl->nents &&
1393 		    cfg->finalization_type == FINALIZATION_TYPE_FINUP) {
1394 			if (divs[i]->nosimd)
1395 				crypto_disable_simd_for_test();
1396 			err = crypto_shash_finup(desc, sg_virt(&tsgl->sgl[i]),
1397 						 tsgl->sgl[i].length, result);
1398 			if (divs[i]->nosimd)
1399 				crypto_reenable_simd_for_test();
1400 			err = check_shash_op("finup", err, driver, vec_name,
1401 					     cfg);
1402 			if (err)
1403 				return err;
1404 			goto result_ready;
1405 		}
1406 		if (divs[i]->nosimd)
1407 			crypto_disable_simd_for_test();
1408 		err = crypto_shash_update(desc, sg_virt(&tsgl->sgl[i]),
1409 					  tsgl->sgl[i].length);
1410 		if (divs[i]->nosimd)
1411 			crypto_reenable_simd_for_test();
1412 		err = check_shash_op("update", err, driver, vec_name, cfg);
1413 		if (err)
1414 			return err;
1415 		if (divs[i]->flush_type == FLUSH_TYPE_REIMPORT) {
1416 			/* Test ->export() and ->import() */
1417 			testmgr_poison(hashstate + statesize,
1418 				       TESTMGR_POISON_LEN);
1419 			err = crypto_shash_export(desc, hashstate);
1420 			err = check_shash_op("export", err, driver, vec_name,
1421 					     cfg);
1422 			if (err)
1423 				return err;
1424 			if (!testmgr_is_poison(hashstate + statesize,
1425 					       TESTMGR_POISON_LEN)) {
1426 				pr_err("alg: shash: %s export() overran state buffer on test vector %s, cfg=\"%s\"\n",
1427 				       driver, vec_name, cfg->name);
1428 				return -EOVERFLOW;
1429 			}
1430 			testmgr_poison(desc->__ctx, crypto_shash_descsize(tfm));
1431 			err = crypto_shash_import(desc, hashstate);
1432 			err = check_shash_op("import", err, driver, vec_name,
1433 					     cfg);
1434 			if (err)
1435 				return err;
1436 		}
1437 	}
1438 
1439 	if (cfg->nosimd)
1440 		crypto_disable_simd_for_test();
1441 	err = crypto_shash_final(desc, result);
1442 	if (cfg->nosimd)
1443 		crypto_reenable_simd_for_test();
1444 	err = check_shash_op("final", err, driver, vec_name, cfg);
1445 	if (err)
1446 		return err;
1447 result_ready:
1448 	return check_hash_result("shash", result, digestsize, vec, vec_name,
1449 				 driver, cfg);
1450 }
1451 
1452 static int do_ahash_op(int (*op)(struct ahash_request *req),
1453 		       struct ahash_request *req,
1454 		       struct crypto_wait *wait, bool nosimd)
1455 {
1456 	int err;
1457 
1458 	if (nosimd)
1459 		crypto_disable_simd_for_test();
1460 
1461 	err = op(req);
1462 
1463 	if (nosimd)
1464 		crypto_reenable_simd_for_test();
1465 
1466 	return crypto_wait_req(err, wait);
1467 }
1468 
1469 static int check_nonfinal_ahash_op(const char *op, int err,
1470 				   u8 *result, unsigned int digestsize,
1471 				   const char *driver, const char *vec_name,
1472 				   const struct testvec_config *cfg)
1473 {
1474 	if (err) {
1475 		pr_err("alg: ahash: %s %s() failed with err %d on test vector %s, cfg=\"%s\"\n",
1476 		       driver, op, err, vec_name, cfg->name);
1477 		return err;
1478 	}
1479 	if (!testmgr_is_poison(result, digestsize)) {
1480 		pr_err("alg: ahash: %s %s() used result buffer on test vector %s, cfg=\"%s\"\n",
1481 		       driver, op, vec_name, cfg->name);
1482 		return -EINVAL;
1483 	}
1484 	return 0;
1485 }
1486 
1487 /* Test one hash test vector in one configuration, using the ahash API */
1488 static int test_ahash_vec_cfg(const struct hash_testvec *vec,
1489 			      const char *vec_name,
1490 			      const struct testvec_config *cfg,
1491 			      struct ahash_request *req,
1492 			      struct test_sglist *tsgl,
1493 			      u8 *hashstate)
1494 {
1495 	struct crypto_ahash *tfm = crypto_ahash_reqtfm(req);
1496 	const unsigned int digestsize = crypto_ahash_digestsize(tfm);
1497 	const unsigned int statesize = crypto_ahash_statesize(tfm);
1498 	const char *driver = crypto_ahash_driver_name(tfm);
1499 	const u32 req_flags = CRYPTO_TFM_REQ_MAY_BACKLOG | cfg->req_flags;
1500 	const struct test_sg_division *divs[XBUFSIZE];
1501 	DECLARE_CRYPTO_WAIT(wait);
1502 	unsigned int i;
1503 	struct scatterlist *pending_sgl;
1504 	unsigned int pending_len;
1505 	u8 result[HASH_MAX_DIGESTSIZE + TESTMGR_POISON_LEN];
1506 	int err;
1507 
1508 	/* Set the key, if specified */
1509 	if (vec->ksize) {
1510 		err = do_setkey(crypto_ahash_setkey, tfm, vec->key, vec->ksize,
1511 				cfg, 0);
1512 		if (err) {
1513 			if (err == vec->setkey_error)
1514 				return 0;
1515 			pr_err("alg: ahash: %s setkey failed on test vector %s; expected_error=%d, actual_error=%d, flags=%#x\n",
1516 			       driver, vec_name, vec->setkey_error, err,
1517 			       crypto_ahash_get_flags(tfm));
1518 			return err;
1519 		}
1520 		if (vec->setkey_error) {
1521 			pr_err("alg: ahash: %s setkey unexpectedly succeeded on test vector %s; expected_error=%d\n",
1522 			       driver, vec_name, vec->setkey_error);
1523 			return -EINVAL;
1524 		}
1525 	}
1526 
1527 	/* Build the scatterlist for the source data */
1528 	err = build_hash_sglist(tsgl, vec, cfg, 0, divs);
1529 	if (err) {
1530 		pr_err("alg: ahash: %s: error preparing scatterlist for test vector %s, cfg=\"%s\"\n",
1531 		       driver, vec_name, cfg->name);
1532 		return err;
1533 	}
1534 
1535 	/* Do the actual hashing */
1536 
1537 	testmgr_poison(req->__ctx, crypto_ahash_reqsize(tfm));
1538 	testmgr_poison(result, digestsize + TESTMGR_POISON_LEN);
1539 
1540 	if (cfg->finalization_type == FINALIZATION_TYPE_DIGEST ||
1541 	    vec->digest_error) {
1542 		/* Just using digest() */
1543 		ahash_request_set_callback(req, req_flags, crypto_req_done,
1544 					   &wait);
1545 		ahash_request_set_crypt(req, tsgl->sgl, result, vec->psize);
1546 		err = do_ahash_op(crypto_ahash_digest, req, &wait, cfg->nosimd);
1547 		if (err) {
1548 			if (err == vec->digest_error)
1549 				return 0;
1550 			pr_err("alg: ahash: %s digest() failed on test vector %s; expected_error=%d, actual_error=%d, cfg=\"%s\"\n",
1551 			       driver, vec_name, vec->digest_error, err,
1552 			       cfg->name);
1553 			return err;
1554 		}
1555 		if (vec->digest_error) {
1556 			pr_err("alg: ahash: %s digest() unexpectedly succeeded on test vector %s; expected_error=%d, cfg=\"%s\"\n",
1557 			       driver, vec_name, vec->digest_error, cfg->name);
1558 			return -EINVAL;
1559 		}
1560 		goto result_ready;
1561 	}
1562 
1563 	/* Using init(), zero or more update(), then final() or finup() */
1564 
1565 	ahash_request_set_callback(req, req_flags, crypto_req_done, &wait);
1566 	ahash_request_set_crypt(req, NULL, result, 0);
1567 	err = do_ahash_op(crypto_ahash_init, req, &wait, cfg->nosimd);
1568 	err = check_nonfinal_ahash_op("init", err, result, digestsize,
1569 				      driver, vec_name, cfg);
1570 	if (err)
1571 		return err;
1572 
1573 	pending_sgl = NULL;
1574 	pending_len = 0;
1575 	for (i = 0; i < tsgl->nents; i++) {
1576 		if (divs[i]->flush_type != FLUSH_TYPE_NONE &&
1577 		    pending_sgl != NULL) {
1578 			/* update() with the pending data */
1579 			ahash_request_set_callback(req, req_flags,
1580 						   crypto_req_done, &wait);
1581 			ahash_request_set_crypt(req, pending_sgl, result,
1582 						pending_len);
1583 			err = do_ahash_op(crypto_ahash_update, req, &wait,
1584 					  divs[i]->nosimd);
1585 			err = check_nonfinal_ahash_op("update", err,
1586 						      result, digestsize,
1587 						      driver, vec_name, cfg);
1588 			if (err)
1589 				return err;
1590 			pending_sgl = NULL;
1591 			pending_len = 0;
1592 		}
1593 		if (divs[i]->flush_type == FLUSH_TYPE_REIMPORT) {
1594 			/* Test ->export() and ->import() */
1595 			testmgr_poison(hashstate + statesize,
1596 				       TESTMGR_POISON_LEN);
1597 			err = crypto_ahash_export(req, hashstate);
1598 			err = check_nonfinal_ahash_op("export", err,
1599 						      result, digestsize,
1600 						      driver, vec_name, cfg);
1601 			if (err)
1602 				return err;
1603 			if (!testmgr_is_poison(hashstate + statesize,
1604 					       TESTMGR_POISON_LEN)) {
1605 				pr_err("alg: ahash: %s export() overran state buffer on test vector %s, cfg=\"%s\"\n",
1606 				       driver, vec_name, cfg->name);
1607 				return -EOVERFLOW;
1608 			}
1609 
1610 			testmgr_poison(req->__ctx, crypto_ahash_reqsize(tfm));
1611 			err = crypto_ahash_import(req, hashstate);
1612 			err = check_nonfinal_ahash_op("import", err,
1613 						      result, digestsize,
1614 						      driver, vec_name, cfg);
1615 			if (err)
1616 				return err;
1617 		}
1618 		if (pending_sgl == NULL)
1619 			pending_sgl = &tsgl->sgl[i];
1620 		pending_len += tsgl->sgl[i].length;
1621 	}
1622 
1623 	ahash_request_set_callback(req, req_flags, crypto_req_done, &wait);
1624 	ahash_request_set_crypt(req, pending_sgl, result, pending_len);
1625 	if (cfg->finalization_type == FINALIZATION_TYPE_FINAL) {
1626 		/* finish with update() and final() */
1627 		err = do_ahash_op(crypto_ahash_update, req, &wait, cfg->nosimd);
1628 		err = check_nonfinal_ahash_op("update", err, result, digestsize,
1629 					      driver, vec_name, cfg);
1630 		if (err)
1631 			return err;
1632 		err = do_ahash_op(crypto_ahash_final, req, &wait, cfg->nosimd);
1633 		if (err) {
1634 			pr_err("alg: ahash: %s final() failed with err %d on test vector %s, cfg=\"%s\"\n",
1635 			       driver, err, vec_name, cfg->name);
1636 			return err;
1637 		}
1638 	} else {
1639 		/* finish with finup() */
1640 		err = do_ahash_op(crypto_ahash_finup, req, &wait, cfg->nosimd);
1641 		if (err) {
1642 			pr_err("alg: ahash: %s finup() failed with err %d on test vector %s, cfg=\"%s\"\n",
1643 			       driver, err, vec_name, cfg->name);
1644 			return err;
1645 		}
1646 	}
1647 
1648 result_ready:
1649 	return check_hash_result("ahash", result, digestsize, vec, vec_name,
1650 				 driver, cfg);
1651 }
1652 
1653 static int test_hash_vec_cfg(const struct hash_testvec *vec,
1654 			     const char *vec_name,
1655 			     const struct testvec_config *cfg,
1656 			     struct ahash_request *req,
1657 			     struct shash_desc *desc,
1658 			     struct test_sglist *tsgl,
1659 			     u8 *hashstate)
1660 {
1661 	int err;
1662 
1663 	/*
1664 	 * For algorithms implemented as "shash", most bugs will be detected by
1665 	 * both the shash and ahash tests.  Test the shash API first so that the
1666 	 * failures involve less indirection, so are easier to debug.
1667 	 */
1668 
1669 	if (desc) {
1670 		err = test_shash_vec_cfg(vec, vec_name, cfg, desc, tsgl,
1671 					 hashstate);
1672 		if (err)
1673 			return err;
1674 	}
1675 
1676 	return test_ahash_vec_cfg(vec, vec_name, cfg, req, tsgl, hashstate);
1677 }
1678 
1679 static int test_hash_vec(const struct hash_testvec *vec, unsigned int vec_num,
1680 			 struct ahash_request *req, struct shash_desc *desc,
1681 			 struct test_sglist *tsgl, u8 *hashstate)
1682 {
1683 	char vec_name[16];
1684 	unsigned int i;
1685 	int err;
1686 
1687 	sprintf(vec_name, "%u", vec_num);
1688 
1689 	for (i = 0; i < ARRAY_SIZE(default_hash_testvec_configs); i++) {
1690 		err = test_hash_vec_cfg(vec, vec_name,
1691 					&default_hash_testvec_configs[i],
1692 					req, desc, tsgl, hashstate);
1693 		if (err)
1694 			return err;
1695 	}
1696 
1697 #ifdef CONFIG_CRYPTO_MANAGER_EXTRA_TESTS
1698 	if (!noextratests) {
1699 		struct rnd_state rng;
1700 		struct testvec_config cfg;
1701 		char cfgname[TESTVEC_CONFIG_NAMELEN];
1702 
1703 		init_rnd_state(&rng);
1704 
1705 		for (i = 0; i < fuzz_iterations; i++) {
1706 			generate_random_testvec_config(&rng, &cfg, cfgname,
1707 						       sizeof(cfgname));
1708 			err = test_hash_vec_cfg(vec, vec_name, &cfg,
1709 						req, desc, tsgl, hashstate);
1710 			if (err)
1711 				return err;
1712 			cond_resched();
1713 		}
1714 	}
1715 #endif
1716 	return 0;
1717 }
1718 
1719 #ifdef CONFIG_CRYPTO_MANAGER_EXTRA_TESTS
1720 /*
1721  * Generate a hash test vector from the given implementation.
1722  * Assumes the buffers in 'vec' were already allocated.
1723  */
1724 static void generate_random_hash_testvec(struct rnd_state *rng,
1725 					 struct shash_desc *desc,
1726 					 struct hash_testvec *vec,
1727 					 unsigned int maxkeysize,
1728 					 unsigned int maxdatasize,
1729 					 char *name, size_t max_namelen)
1730 {
1731 	/* Data */
1732 	vec->psize = generate_random_length(rng, maxdatasize);
1733 	generate_random_bytes(rng, (u8 *)vec->plaintext, vec->psize);
1734 
1735 	/*
1736 	 * Key: length in range [1, maxkeysize], but usually choose maxkeysize.
1737 	 * If algorithm is unkeyed, then maxkeysize == 0 and set ksize = 0.
1738 	 */
1739 	vec->setkey_error = 0;
1740 	vec->ksize = 0;
1741 	if (maxkeysize) {
1742 		vec->ksize = maxkeysize;
1743 		if (prandom_u32_below(rng, 4) == 0)
1744 			vec->ksize = prandom_u32_inclusive(rng, 1, maxkeysize);
1745 		generate_random_bytes(rng, (u8 *)vec->key, vec->ksize);
1746 
1747 		vec->setkey_error = crypto_shash_setkey(desc->tfm, vec->key,
1748 							vec->ksize);
1749 		/* If the key couldn't be set, no need to continue to digest. */
1750 		if (vec->setkey_error)
1751 			goto done;
1752 	}
1753 
1754 	/* Digest */
1755 	vec->digest_error = crypto_shash_digest(desc, vec->plaintext,
1756 						vec->psize, (u8 *)vec->digest);
1757 done:
1758 	snprintf(name, max_namelen, "\"random: psize=%u ksize=%u\"",
1759 		 vec->psize, vec->ksize);
1760 }
1761 
1762 /*
1763  * Test the hash algorithm represented by @req against the corresponding generic
1764  * implementation, if one is available.
1765  */
1766 static int test_hash_vs_generic_impl(const char *generic_driver,
1767 				     unsigned int maxkeysize,
1768 				     struct ahash_request *req,
1769 				     struct shash_desc *desc,
1770 				     struct test_sglist *tsgl,
1771 				     u8 *hashstate)
1772 {
1773 	struct crypto_ahash *tfm = crypto_ahash_reqtfm(req);
1774 	const unsigned int digestsize = crypto_ahash_digestsize(tfm);
1775 	const unsigned int blocksize = crypto_ahash_blocksize(tfm);
1776 	const unsigned int maxdatasize = (2 * PAGE_SIZE) - TESTMGR_POISON_LEN;
1777 	const char *algname = crypto_hash_alg_common(tfm)->base.cra_name;
1778 	const char *driver = crypto_ahash_driver_name(tfm);
1779 	struct rnd_state rng;
1780 	char _generic_driver[CRYPTO_MAX_ALG_NAME];
1781 	struct crypto_shash *generic_tfm = NULL;
1782 	struct shash_desc *generic_desc = NULL;
1783 	unsigned int i;
1784 	struct hash_testvec vec = { 0 };
1785 	char vec_name[64];
1786 	struct testvec_config *cfg;
1787 	char cfgname[TESTVEC_CONFIG_NAMELEN];
1788 	int err;
1789 
1790 	if (noextratests)
1791 		return 0;
1792 
1793 	init_rnd_state(&rng);
1794 
1795 	if (!generic_driver) { /* Use default naming convention? */
1796 		err = build_generic_driver_name(algname, _generic_driver);
1797 		if (err)
1798 			return err;
1799 		generic_driver = _generic_driver;
1800 	}
1801 
1802 	if (strcmp(generic_driver, driver) == 0) /* Already the generic impl? */
1803 		return 0;
1804 
1805 	generic_tfm = crypto_alloc_shash(generic_driver, 0, 0);
1806 	if (IS_ERR(generic_tfm)) {
1807 		err = PTR_ERR(generic_tfm);
1808 		if (err == -ENOENT) {
1809 			pr_warn("alg: hash: skipping comparison tests for %s because %s is unavailable\n",
1810 				driver, generic_driver);
1811 			return 0;
1812 		}
1813 		pr_err("alg: hash: error allocating %s (generic impl of %s): %d\n",
1814 		       generic_driver, algname, err);
1815 		return err;
1816 	}
1817 
1818 	cfg = kzalloc(sizeof(*cfg), GFP_KERNEL);
1819 	if (!cfg) {
1820 		err = -ENOMEM;
1821 		goto out;
1822 	}
1823 
1824 	generic_desc = kzalloc(sizeof(*desc) +
1825 			       crypto_shash_descsize(generic_tfm), GFP_KERNEL);
1826 	if (!generic_desc) {
1827 		err = -ENOMEM;
1828 		goto out;
1829 	}
1830 	generic_desc->tfm = generic_tfm;
1831 
1832 	/* Check the algorithm properties for consistency. */
1833 
1834 	if (digestsize != crypto_shash_digestsize(generic_tfm)) {
1835 		pr_err("alg: hash: digestsize for %s (%u) doesn't match generic impl (%u)\n",
1836 		       driver, digestsize,
1837 		       crypto_shash_digestsize(generic_tfm));
1838 		err = -EINVAL;
1839 		goto out;
1840 	}
1841 
1842 	if (blocksize != crypto_shash_blocksize(generic_tfm)) {
1843 		pr_err("alg: hash: blocksize for %s (%u) doesn't match generic impl (%u)\n",
1844 		       driver, blocksize, crypto_shash_blocksize(generic_tfm));
1845 		err = -EINVAL;
1846 		goto out;
1847 	}
1848 
1849 	/*
1850 	 * Now generate test vectors using the generic implementation, and test
1851 	 * the other implementation against them.
1852 	 */
1853 
1854 	vec.key = kmalloc(maxkeysize, GFP_KERNEL);
1855 	vec.plaintext = kmalloc(maxdatasize, GFP_KERNEL);
1856 	vec.digest = kmalloc(digestsize, GFP_KERNEL);
1857 	if (!vec.key || !vec.plaintext || !vec.digest) {
1858 		err = -ENOMEM;
1859 		goto out;
1860 	}
1861 
1862 	for (i = 0; i < fuzz_iterations * 8; i++) {
1863 		generate_random_hash_testvec(&rng, generic_desc, &vec,
1864 					     maxkeysize, maxdatasize,
1865 					     vec_name, sizeof(vec_name));
1866 		generate_random_testvec_config(&rng, cfg, cfgname,
1867 					       sizeof(cfgname));
1868 
1869 		err = test_hash_vec_cfg(&vec, vec_name, cfg,
1870 					req, desc, tsgl, hashstate);
1871 		if (err)
1872 			goto out;
1873 		cond_resched();
1874 	}
1875 	err = 0;
1876 out:
1877 	kfree(cfg);
1878 	kfree(vec.key);
1879 	kfree(vec.plaintext);
1880 	kfree(vec.digest);
1881 	crypto_free_shash(generic_tfm);
1882 	kfree_sensitive(generic_desc);
1883 	return err;
1884 }
1885 #else /* !CONFIG_CRYPTO_MANAGER_EXTRA_TESTS */
1886 static int test_hash_vs_generic_impl(const char *generic_driver,
1887 				     unsigned int maxkeysize,
1888 				     struct ahash_request *req,
1889 				     struct shash_desc *desc,
1890 				     struct test_sglist *tsgl,
1891 				     u8 *hashstate)
1892 {
1893 	return 0;
1894 }
1895 #endif /* !CONFIG_CRYPTO_MANAGER_EXTRA_TESTS */
1896 
1897 static int alloc_shash(const char *driver, u32 type, u32 mask,
1898 		       struct crypto_shash **tfm_ret,
1899 		       struct shash_desc **desc_ret)
1900 {
1901 	struct crypto_shash *tfm;
1902 	struct shash_desc *desc;
1903 
1904 	tfm = crypto_alloc_shash(driver, type, mask);
1905 	if (IS_ERR(tfm)) {
1906 		if (PTR_ERR(tfm) == -ENOENT) {
1907 			/*
1908 			 * This algorithm is only available through the ahash
1909 			 * API, not the shash API, so skip the shash tests.
1910 			 */
1911 			return 0;
1912 		}
1913 		pr_err("alg: hash: failed to allocate shash transform for %s: %ld\n",
1914 		       driver, PTR_ERR(tfm));
1915 		return PTR_ERR(tfm);
1916 	}
1917 
1918 	desc = kmalloc(sizeof(*desc) + crypto_shash_descsize(tfm), GFP_KERNEL);
1919 	if (!desc) {
1920 		crypto_free_shash(tfm);
1921 		return -ENOMEM;
1922 	}
1923 	desc->tfm = tfm;
1924 
1925 	*tfm_ret = tfm;
1926 	*desc_ret = desc;
1927 	return 0;
1928 }
1929 
1930 static int __alg_test_hash(const struct hash_testvec *vecs,
1931 			   unsigned int num_vecs, const char *driver,
1932 			   u32 type, u32 mask,
1933 			   const char *generic_driver, unsigned int maxkeysize)
1934 {
1935 	struct crypto_ahash *atfm = NULL;
1936 	struct ahash_request *req = NULL;
1937 	struct crypto_shash *stfm = NULL;
1938 	struct shash_desc *desc = NULL;
1939 	struct test_sglist *tsgl = NULL;
1940 	u8 *hashstate = NULL;
1941 	unsigned int statesize;
1942 	unsigned int i;
1943 	int err;
1944 
1945 	/*
1946 	 * Always test the ahash API.  This works regardless of whether the
1947 	 * algorithm is implemented as ahash or shash.
1948 	 */
1949 
1950 	atfm = crypto_alloc_ahash(driver, type, mask);
1951 	if (IS_ERR(atfm)) {
1952 		if (PTR_ERR(atfm) == -ENOENT)
1953 			return 0;
1954 		pr_err("alg: hash: failed to allocate transform for %s: %ld\n",
1955 		       driver, PTR_ERR(atfm));
1956 		return PTR_ERR(atfm);
1957 	}
1958 	driver = crypto_ahash_driver_name(atfm);
1959 
1960 	req = ahash_request_alloc(atfm, GFP_KERNEL);
1961 	if (!req) {
1962 		pr_err("alg: hash: failed to allocate request for %s\n",
1963 		       driver);
1964 		err = -ENOMEM;
1965 		goto out;
1966 	}
1967 
1968 	/*
1969 	 * If available also test the shash API, to cover corner cases that may
1970 	 * be missed by testing the ahash API only.
1971 	 */
1972 	err = alloc_shash(driver, type, mask, &stfm, &desc);
1973 	if (err)
1974 		goto out;
1975 
1976 	tsgl = kmalloc(sizeof(*tsgl), GFP_KERNEL);
1977 	if (!tsgl || init_test_sglist(tsgl) != 0) {
1978 		pr_err("alg: hash: failed to allocate test buffers for %s\n",
1979 		       driver);
1980 		kfree(tsgl);
1981 		tsgl = NULL;
1982 		err = -ENOMEM;
1983 		goto out;
1984 	}
1985 
1986 	statesize = crypto_ahash_statesize(atfm);
1987 	if (stfm)
1988 		statesize = max(statesize, crypto_shash_statesize(stfm));
1989 	hashstate = kmalloc(statesize + TESTMGR_POISON_LEN, GFP_KERNEL);
1990 	if (!hashstate) {
1991 		pr_err("alg: hash: failed to allocate hash state buffer for %s\n",
1992 		       driver);
1993 		err = -ENOMEM;
1994 		goto out;
1995 	}
1996 
1997 	for (i = 0; i < num_vecs; i++) {
1998 		if (fips_enabled && vecs[i].fips_skip)
1999 			continue;
2000 
2001 		err = test_hash_vec(&vecs[i], i, req, desc, tsgl, hashstate);
2002 		if (err)
2003 			goto out;
2004 		cond_resched();
2005 	}
2006 	err = test_hash_vs_generic_impl(generic_driver, maxkeysize, req,
2007 					desc, tsgl, hashstate);
2008 out:
2009 	kfree(hashstate);
2010 	if (tsgl) {
2011 		destroy_test_sglist(tsgl);
2012 		kfree(tsgl);
2013 	}
2014 	kfree(desc);
2015 	crypto_free_shash(stfm);
2016 	ahash_request_free(req);
2017 	crypto_free_ahash(atfm);
2018 	return err;
2019 }
2020 
2021 static int alg_test_hash(const struct alg_test_desc *desc, const char *driver,
2022 			 u32 type, u32 mask)
2023 {
2024 	const struct hash_testvec *template = desc->suite.hash.vecs;
2025 	unsigned int tcount = desc->suite.hash.count;
2026 	unsigned int nr_unkeyed, nr_keyed;
2027 	unsigned int maxkeysize = 0;
2028 	int err;
2029 
2030 	/*
2031 	 * For OPTIONAL_KEY algorithms, we have to do all the unkeyed tests
2032 	 * first, before setting a key on the tfm.  To make this easier, we
2033 	 * require that the unkeyed test vectors (if any) are listed first.
2034 	 */
2035 
2036 	for (nr_unkeyed = 0; nr_unkeyed < tcount; nr_unkeyed++) {
2037 		if (template[nr_unkeyed].ksize)
2038 			break;
2039 	}
2040 	for (nr_keyed = 0; nr_unkeyed + nr_keyed < tcount; nr_keyed++) {
2041 		if (!template[nr_unkeyed + nr_keyed].ksize) {
2042 			pr_err("alg: hash: test vectors for %s out of order, "
2043 			       "unkeyed ones must come first\n", desc->alg);
2044 			return -EINVAL;
2045 		}
2046 		maxkeysize = max_t(unsigned int, maxkeysize,
2047 				   template[nr_unkeyed + nr_keyed].ksize);
2048 	}
2049 
2050 	err = 0;
2051 	if (nr_unkeyed) {
2052 		err = __alg_test_hash(template, nr_unkeyed, driver, type, mask,
2053 				      desc->generic_driver, maxkeysize);
2054 		template += nr_unkeyed;
2055 	}
2056 
2057 	if (!err && nr_keyed)
2058 		err = __alg_test_hash(template, nr_keyed, driver, type, mask,
2059 				      desc->generic_driver, maxkeysize);
2060 
2061 	return err;
2062 }
2063 
2064 static int test_aead_vec_cfg(int enc, const struct aead_testvec *vec,
2065 			     const char *vec_name,
2066 			     const struct testvec_config *cfg,
2067 			     struct aead_request *req,
2068 			     struct cipher_test_sglists *tsgls)
2069 {
2070 	struct crypto_aead *tfm = crypto_aead_reqtfm(req);
2071 	const unsigned int alignmask = crypto_aead_alignmask(tfm);
2072 	const unsigned int ivsize = crypto_aead_ivsize(tfm);
2073 	const unsigned int authsize = vec->clen - vec->plen;
2074 	const char *driver = crypto_aead_driver_name(tfm);
2075 	const u32 req_flags = CRYPTO_TFM_REQ_MAY_BACKLOG | cfg->req_flags;
2076 	const char *op = enc ? "encryption" : "decryption";
2077 	DECLARE_CRYPTO_WAIT(wait);
2078 	u8 _iv[3 * (MAX_ALGAPI_ALIGNMASK + 1) + MAX_IVLEN];
2079 	u8 *iv = PTR_ALIGN(&_iv[0], 2 * (MAX_ALGAPI_ALIGNMASK + 1)) +
2080 		 cfg->iv_offset +
2081 		 (cfg->iv_offset_relative_to_alignmask ? alignmask : 0);
2082 	struct kvec input[2];
2083 	int err;
2084 
2085 	/* Set the key */
2086 	if (vec->wk)
2087 		crypto_aead_set_flags(tfm, CRYPTO_TFM_REQ_FORBID_WEAK_KEYS);
2088 	else
2089 		crypto_aead_clear_flags(tfm, CRYPTO_TFM_REQ_FORBID_WEAK_KEYS);
2090 
2091 	err = do_setkey(crypto_aead_setkey, tfm, vec->key, vec->klen,
2092 			cfg, alignmask);
2093 	if (err && err != vec->setkey_error) {
2094 		pr_err("alg: aead: %s setkey failed on test vector %s; expected_error=%d, actual_error=%d, flags=%#x\n",
2095 		       driver, vec_name, vec->setkey_error, err,
2096 		       crypto_aead_get_flags(tfm));
2097 		return err;
2098 	}
2099 	if (!err && vec->setkey_error) {
2100 		pr_err("alg: aead: %s setkey unexpectedly succeeded on test vector %s; expected_error=%d\n",
2101 		       driver, vec_name, vec->setkey_error);
2102 		return -EINVAL;
2103 	}
2104 
2105 	/* Set the authentication tag size */
2106 	err = crypto_aead_setauthsize(tfm, authsize);
2107 	if (err && err != vec->setauthsize_error) {
2108 		pr_err("alg: aead: %s setauthsize failed on test vector %s; expected_error=%d, actual_error=%d\n",
2109 		       driver, vec_name, vec->setauthsize_error, err);
2110 		return err;
2111 	}
2112 	if (!err && vec->setauthsize_error) {
2113 		pr_err("alg: aead: %s setauthsize unexpectedly succeeded on test vector %s; expected_error=%d\n",
2114 		       driver, vec_name, vec->setauthsize_error);
2115 		return -EINVAL;
2116 	}
2117 
2118 	if (vec->setkey_error || vec->setauthsize_error)
2119 		return 0;
2120 
2121 	/* The IV must be copied to a buffer, as the algorithm may modify it */
2122 	if (WARN_ON(ivsize > MAX_IVLEN))
2123 		return -EINVAL;
2124 	if (vec->iv)
2125 		memcpy(iv, vec->iv, ivsize);
2126 	else
2127 		memset(iv, 0, ivsize);
2128 
2129 	/* Build the src/dst scatterlists */
2130 	input[0].iov_base = (void *)vec->assoc;
2131 	input[0].iov_len = vec->alen;
2132 	input[1].iov_base = enc ? (void *)vec->ptext : (void *)vec->ctext;
2133 	input[1].iov_len = enc ? vec->plen : vec->clen;
2134 	err = build_cipher_test_sglists(tsgls, cfg, alignmask,
2135 					vec->alen + (enc ? vec->plen :
2136 						     vec->clen),
2137 					vec->alen + (enc ? vec->clen :
2138 						     vec->plen),
2139 					input, 2);
2140 	if (err) {
2141 		pr_err("alg: aead: %s %s: error preparing scatterlists for test vector %s, cfg=\"%s\"\n",
2142 		       driver, op, vec_name, cfg->name);
2143 		return err;
2144 	}
2145 
2146 	/* Do the actual encryption or decryption */
2147 	testmgr_poison(req->__ctx, crypto_aead_reqsize(tfm));
2148 	aead_request_set_callback(req, req_flags, crypto_req_done, &wait);
2149 	aead_request_set_crypt(req, tsgls->src.sgl_ptr, tsgls->dst.sgl_ptr,
2150 			       enc ? vec->plen : vec->clen, iv);
2151 	aead_request_set_ad(req, vec->alen);
2152 	if (cfg->nosimd)
2153 		crypto_disable_simd_for_test();
2154 	err = enc ? crypto_aead_encrypt(req) : crypto_aead_decrypt(req);
2155 	if (cfg->nosimd)
2156 		crypto_reenable_simd_for_test();
2157 	err = crypto_wait_req(err, &wait);
2158 
2159 	/* Check that the algorithm didn't overwrite things it shouldn't have */
2160 	if (req->cryptlen != (enc ? vec->plen : vec->clen) ||
2161 	    req->assoclen != vec->alen ||
2162 	    req->iv != iv ||
2163 	    req->src != tsgls->src.sgl_ptr ||
2164 	    req->dst != tsgls->dst.sgl_ptr ||
2165 	    crypto_aead_reqtfm(req) != tfm ||
2166 	    req->base.complete != crypto_req_done ||
2167 	    req->base.flags != req_flags ||
2168 	    req->base.data != &wait) {
2169 		pr_err("alg: aead: %s %s corrupted request struct on test vector %s, cfg=\"%s\"\n",
2170 		       driver, op, vec_name, cfg->name);
2171 		if (req->cryptlen != (enc ? vec->plen : vec->clen))
2172 			pr_err("alg: aead: changed 'req->cryptlen'\n");
2173 		if (req->assoclen != vec->alen)
2174 			pr_err("alg: aead: changed 'req->assoclen'\n");
2175 		if (req->iv != iv)
2176 			pr_err("alg: aead: changed 'req->iv'\n");
2177 		if (req->src != tsgls->src.sgl_ptr)
2178 			pr_err("alg: aead: changed 'req->src'\n");
2179 		if (req->dst != tsgls->dst.sgl_ptr)
2180 			pr_err("alg: aead: changed 'req->dst'\n");
2181 		if (crypto_aead_reqtfm(req) != tfm)
2182 			pr_err("alg: aead: changed 'req->base.tfm'\n");
2183 		if (req->base.complete != crypto_req_done)
2184 			pr_err("alg: aead: changed 'req->base.complete'\n");
2185 		if (req->base.flags != req_flags)
2186 			pr_err("alg: aead: changed 'req->base.flags'\n");
2187 		if (req->base.data != &wait)
2188 			pr_err("alg: aead: changed 'req->base.data'\n");
2189 		return -EINVAL;
2190 	}
2191 	if (is_test_sglist_corrupted(&tsgls->src)) {
2192 		pr_err("alg: aead: %s %s corrupted src sgl on test vector %s, cfg=\"%s\"\n",
2193 		       driver, op, vec_name, cfg->name);
2194 		return -EINVAL;
2195 	}
2196 	if (tsgls->dst.sgl_ptr != tsgls->src.sgl &&
2197 	    is_test_sglist_corrupted(&tsgls->dst)) {
2198 		pr_err("alg: aead: %s %s corrupted dst sgl on test vector %s, cfg=\"%s\"\n",
2199 		       driver, op, vec_name, cfg->name);
2200 		return -EINVAL;
2201 	}
2202 
2203 	/* Check for unexpected success or failure, or wrong error code */
2204 	if ((err == 0 && vec->novrfy) ||
2205 	    (err != vec->crypt_error && !(err == -EBADMSG && vec->novrfy))) {
2206 		char expected_error[32];
2207 
2208 		if (vec->novrfy &&
2209 		    vec->crypt_error != 0 && vec->crypt_error != -EBADMSG)
2210 			sprintf(expected_error, "-EBADMSG or %d",
2211 				vec->crypt_error);
2212 		else if (vec->novrfy)
2213 			sprintf(expected_error, "-EBADMSG");
2214 		else
2215 			sprintf(expected_error, "%d", vec->crypt_error);
2216 		if (err) {
2217 			pr_err("alg: aead: %s %s failed on test vector %s; expected_error=%s, actual_error=%d, cfg=\"%s\"\n",
2218 			       driver, op, vec_name, expected_error, err,
2219 			       cfg->name);
2220 			return err;
2221 		}
2222 		pr_err("alg: aead: %s %s unexpectedly succeeded on test vector %s; expected_error=%s, cfg=\"%s\"\n",
2223 		       driver, op, vec_name, expected_error, cfg->name);
2224 		return -EINVAL;
2225 	}
2226 	if (err) /* Expectedly failed. */
2227 		return 0;
2228 
2229 	/* Check for the correct output (ciphertext or plaintext) */
2230 	err = verify_correct_output(&tsgls->dst, enc ? vec->ctext : vec->ptext,
2231 				    enc ? vec->clen : vec->plen,
2232 				    vec->alen,
2233 				    enc || cfg->inplace_mode == OUT_OF_PLACE);
2234 	if (err == -EOVERFLOW) {
2235 		pr_err("alg: aead: %s %s overran dst buffer on test vector %s, cfg=\"%s\"\n",
2236 		       driver, op, vec_name, cfg->name);
2237 		return err;
2238 	}
2239 	if (err) {
2240 		pr_err("alg: aead: %s %s test failed (wrong result) on test vector %s, cfg=\"%s\"\n",
2241 		       driver, op, vec_name, cfg->name);
2242 		return err;
2243 	}
2244 
2245 	return 0;
2246 }
2247 
2248 static int test_aead_vec(int enc, const struct aead_testvec *vec,
2249 			 unsigned int vec_num, struct aead_request *req,
2250 			 struct cipher_test_sglists *tsgls)
2251 {
2252 	char vec_name[16];
2253 	unsigned int i;
2254 	int err;
2255 
2256 	if (enc && vec->novrfy)
2257 		return 0;
2258 
2259 	sprintf(vec_name, "%u", vec_num);
2260 
2261 	for (i = 0; i < ARRAY_SIZE(default_cipher_testvec_configs); i++) {
2262 		err = test_aead_vec_cfg(enc, vec, vec_name,
2263 					&default_cipher_testvec_configs[i],
2264 					req, tsgls);
2265 		if (err)
2266 			return err;
2267 	}
2268 
2269 #ifdef CONFIG_CRYPTO_MANAGER_EXTRA_TESTS
2270 	if (!noextratests) {
2271 		struct rnd_state rng;
2272 		struct testvec_config cfg;
2273 		char cfgname[TESTVEC_CONFIG_NAMELEN];
2274 
2275 		init_rnd_state(&rng);
2276 
2277 		for (i = 0; i < fuzz_iterations; i++) {
2278 			generate_random_testvec_config(&rng, &cfg, cfgname,
2279 						       sizeof(cfgname));
2280 			err = test_aead_vec_cfg(enc, vec, vec_name,
2281 						&cfg, req, tsgls);
2282 			if (err)
2283 				return err;
2284 			cond_resched();
2285 		}
2286 	}
2287 #endif
2288 	return 0;
2289 }
2290 
2291 #ifdef CONFIG_CRYPTO_MANAGER_EXTRA_TESTS
2292 
2293 struct aead_extra_tests_ctx {
2294 	struct rnd_state rng;
2295 	struct aead_request *req;
2296 	struct crypto_aead *tfm;
2297 	const struct alg_test_desc *test_desc;
2298 	struct cipher_test_sglists *tsgls;
2299 	unsigned int maxdatasize;
2300 	unsigned int maxkeysize;
2301 
2302 	struct aead_testvec vec;
2303 	char vec_name[64];
2304 	char cfgname[TESTVEC_CONFIG_NAMELEN];
2305 	struct testvec_config cfg;
2306 };
2307 
2308 /*
2309  * Make at least one random change to a (ciphertext, AAD) pair.  "Ciphertext"
2310  * here means the full ciphertext including the authentication tag.  The
2311  * authentication tag (and hence also the ciphertext) is assumed to be nonempty.
2312  */
2313 static void mutate_aead_message(struct rnd_state *rng,
2314 				struct aead_testvec *vec, bool aad_iv,
2315 				unsigned int ivsize)
2316 {
2317 	const unsigned int aad_tail_size = aad_iv ? ivsize : 0;
2318 	const unsigned int authsize = vec->clen - vec->plen;
2319 
2320 	if (prandom_bool(rng) && vec->alen > aad_tail_size) {
2321 		 /* Mutate the AAD */
2322 		flip_random_bit(rng, (u8 *)vec->assoc,
2323 				vec->alen - aad_tail_size);
2324 		if (prandom_bool(rng))
2325 			return;
2326 	}
2327 	if (prandom_bool(rng)) {
2328 		/* Mutate auth tag (assuming it's at the end of ciphertext) */
2329 		flip_random_bit(rng, (u8 *)vec->ctext + vec->plen, authsize);
2330 	} else {
2331 		/* Mutate any part of the ciphertext */
2332 		flip_random_bit(rng, (u8 *)vec->ctext, vec->clen);
2333 	}
2334 }
2335 
2336 /*
2337  * Minimum authentication tag size in bytes at which we assume that we can
2338  * reliably generate inauthentic messages, i.e. not generate an authentic
2339  * message by chance.
2340  */
2341 #define MIN_COLLISION_FREE_AUTHSIZE 8
2342 
2343 static void generate_aead_message(struct rnd_state *rng,
2344 				  struct aead_request *req,
2345 				  const struct aead_test_suite *suite,
2346 				  struct aead_testvec *vec,
2347 				  bool prefer_inauthentic)
2348 {
2349 	struct crypto_aead *tfm = crypto_aead_reqtfm(req);
2350 	const unsigned int ivsize = crypto_aead_ivsize(tfm);
2351 	const unsigned int authsize = vec->clen - vec->plen;
2352 	const bool inauthentic = (authsize >= MIN_COLLISION_FREE_AUTHSIZE) &&
2353 				 (prefer_inauthentic ||
2354 				  prandom_u32_below(rng, 4) == 0);
2355 
2356 	/* Generate the AAD. */
2357 	generate_random_bytes(rng, (u8 *)vec->assoc, vec->alen);
2358 	if (suite->aad_iv && vec->alen >= ivsize)
2359 		/* Avoid implementation-defined behavior. */
2360 		memcpy((u8 *)vec->assoc + vec->alen - ivsize, vec->iv, ivsize);
2361 
2362 	if (inauthentic && prandom_bool(rng)) {
2363 		/* Generate a random ciphertext. */
2364 		generate_random_bytes(rng, (u8 *)vec->ctext, vec->clen);
2365 	} else {
2366 		int i = 0;
2367 		struct scatterlist src[2], dst;
2368 		u8 iv[MAX_IVLEN];
2369 		DECLARE_CRYPTO_WAIT(wait);
2370 
2371 		/* Generate a random plaintext and encrypt it. */
2372 		sg_init_table(src, 2);
2373 		if (vec->alen)
2374 			sg_set_buf(&src[i++], vec->assoc, vec->alen);
2375 		if (vec->plen) {
2376 			generate_random_bytes(rng, (u8 *)vec->ptext, vec->plen);
2377 			sg_set_buf(&src[i++], vec->ptext, vec->plen);
2378 		}
2379 		sg_init_one(&dst, vec->ctext, vec->alen + vec->clen);
2380 		memcpy(iv, vec->iv, ivsize);
2381 		aead_request_set_callback(req, 0, crypto_req_done, &wait);
2382 		aead_request_set_crypt(req, src, &dst, vec->plen, iv);
2383 		aead_request_set_ad(req, vec->alen);
2384 		vec->crypt_error = crypto_wait_req(crypto_aead_encrypt(req),
2385 						   &wait);
2386 		/* If encryption failed, we're done. */
2387 		if (vec->crypt_error != 0)
2388 			return;
2389 		memmove((u8 *)vec->ctext, vec->ctext + vec->alen, vec->clen);
2390 		if (!inauthentic)
2391 			return;
2392 		/*
2393 		 * Mutate the authentic (ciphertext, AAD) pair to get an
2394 		 * inauthentic one.
2395 		 */
2396 		mutate_aead_message(rng, vec, suite->aad_iv, ivsize);
2397 	}
2398 	vec->novrfy = 1;
2399 	if (suite->einval_allowed)
2400 		vec->crypt_error = -EINVAL;
2401 }
2402 
2403 /*
2404  * Generate an AEAD test vector 'vec' using the implementation specified by
2405  * 'req'.  The buffers in 'vec' must already be allocated.
2406  *
2407  * If 'prefer_inauthentic' is true, then this function will generate inauthentic
2408  * test vectors (i.e. vectors with 'vec->novrfy=1') more often.
2409  */
2410 static void generate_random_aead_testvec(struct rnd_state *rng,
2411 					 struct aead_request *req,
2412 					 struct aead_testvec *vec,
2413 					 const struct aead_test_suite *suite,
2414 					 unsigned int maxkeysize,
2415 					 unsigned int maxdatasize,
2416 					 char *name, size_t max_namelen,
2417 					 bool prefer_inauthentic)
2418 {
2419 	struct crypto_aead *tfm = crypto_aead_reqtfm(req);
2420 	const unsigned int ivsize = crypto_aead_ivsize(tfm);
2421 	const unsigned int maxauthsize = crypto_aead_maxauthsize(tfm);
2422 	unsigned int authsize;
2423 	unsigned int total_len;
2424 
2425 	/* Key: length in [0, maxkeysize], but usually choose maxkeysize */
2426 	vec->klen = maxkeysize;
2427 	if (prandom_u32_below(rng, 4) == 0)
2428 		vec->klen = prandom_u32_below(rng, maxkeysize + 1);
2429 	generate_random_bytes(rng, (u8 *)vec->key, vec->klen);
2430 	vec->setkey_error = crypto_aead_setkey(tfm, vec->key, vec->klen);
2431 
2432 	/* IV */
2433 	generate_random_bytes(rng, (u8 *)vec->iv, ivsize);
2434 
2435 	/* Tag length: in [0, maxauthsize], but usually choose maxauthsize */
2436 	authsize = maxauthsize;
2437 	if (prandom_u32_below(rng, 4) == 0)
2438 		authsize = prandom_u32_below(rng, maxauthsize + 1);
2439 	if (prefer_inauthentic && authsize < MIN_COLLISION_FREE_AUTHSIZE)
2440 		authsize = MIN_COLLISION_FREE_AUTHSIZE;
2441 	if (WARN_ON(authsize > maxdatasize))
2442 		authsize = maxdatasize;
2443 	maxdatasize -= authsize;
2444 	vec->setauthsize_error = crypto_aead_setauthsize(tfm, authsize);
2445 
2446 	/* AAD, plaintext, and ciphertext lengths */
2447 	total_len = generate_random_length(rng, maxdatasize);
2448 	if (prandom_u32_below(rng, 4) == 0)
2449 		vec->alen = 0;
2450 	else
2451 		vec->alen = generate_random_length(rng, total_len);
2452 	vec->plen = total_len - vec->alen;
2453 	vec->clen = vec->plen + authsize;
2454 
2455 	/*
2456 	 * Generate the AAD, plaintext, and ciphertext.  Not applicable if the
2457 	 * key or the authentication tag size couldn't be set.
2458 	 */
2459 	vec->novrfy = 0;
2460 	vec->crypt_error = 0;
2461 	if (vec->setkey_error == 0 && vec->setauthsize_error == 0)
2462 		generate_aead_message(rng, req, suite, vec, prefer_inauthentic);
2463 	snprintf(name, max_namelen,
2464 		 "\"random: alen=%u plen=%u authsize=%u klen=%u novrfy=%d\"",
2465 		 vec->alen, vec->plen, authsize, vec->klen, vec->novrfy);
2466 }
2467 
2468 static void try_to_generate_inauthentic_testvec(
2469 					struct aead_extra_tests_ctx *ctx)
2470 {
2471 	int i;
2472 
2473 	for (i = 0; i < 10; i++) {
2474 		generate_random_aead_testvec(&ctx->rng, ctx->req, &ctx->vec,
2475 					     &ctx->test_desc->suite.aead,
2476 					     ctx->maxkeysize, ctx->maxdatasize,
2477 					     ctx->vec_name,
2478 					     sizeof(ctx->vec_name), true);
2479 		if (ctx->vec.novrfy)
2480 			return;
2481 	}
2482 }
2483 
2484 /*
2485  * Generate inauthentic test vectors (i.e. ciphertext, AAD pairs that aren't the
2486  * result of an encryption with the key) and verify that decryption fails.
2487  */
2488 static int test_aead_inauthentic_inputs(struct aead_extra_tests_ctx *ctx)
2489 {
2490 	unsigned int i;
2491 	int err;
2492 
2493 	for (i = 0; i < fuzz_iterations * 8; i++) {
2494 		/*
2495 		 * Since this part of the tests isn't comparing the
2496 		 * implementation to another, there's no point in testing any
2497 		 * test vectors other than inauthentic ones (vec.novrfy=1) here.
2498 		 *
2499 		 * If we're having trouble generating such a test vector, e.g.
2500 		 * if the algorithm keeps rejecting the generated keys, don't
2501 		 * retry forever; just continue on.
2502 		 */
2503 		try_to_generate_inauthentic_testvec(ctx);
2504 		if (ctx->vec.novrfy) {
2505 			generate_random_testvec_config(&ctx->rng, &ctx->cfg,
2506 						       ctx->cfgname,
2507 						       sizeof(ctx->cfgname));
2508 			err = test_aead_vec_cfg(DECRYPT, &ctx->vec,
2509 						ctx->vec_name, &ctx->cfg,
2510 						ctx->req, ctx->tsgls);
2511 			if (err)
2512 				return err;
2513 		}
2514 		cond_resched();
2515 	}
2516 	return 0;
2517 }
2518 
2519 /*
2520  * Test the AEAD algorithm against the corresponding generic implementation, if
2521  * one is available.
2522  */
2523 static int test_aead_vs_generic_impl(struct aead_extra_tests_ctx *ctx)
2524 {
2525 	struct crypto_aead *tfm = ctx->tfm;
2526 	const char *algname = crypto_aead_alg(tfm)->base.cra_name;
2527 	const char *driver = crypto_aead_driver_name(tfm);
2528 	const char *generic_driver = ctx->test_desc->generic_driver;
2529 	char _generic_driver[CRYPTO_MAX_ALG_NAME];
2530 	struct crypto_aead *generic_tfm = NULL;
2531 	struct aead_request *generic_req = NULL;
2532 	unsigned int i;
2533 	int err;
2534 
2535 	if (!generic_driver) { /* Use default naming convention? */
2536 		err = build_generic_driver_name(algname, _generic_driver);
2537 		if (err)
2538 			return err;
2539 		generic_driver = _generic_driver;
2540 	}
2541 
2542 	if (strcmp(generic_driver, driver) == 0) /* Already the generic impl? */
2543 		return 0;
2544 
2545 	generic_tfm = crypto_alloc_aead(generic_driver, 0, 0);
2546 	if (IS_ERR(generic_tfm)) {
2547 		err = PTR_ERR(generic_tfm);
2548 		if (err == -ENOENT) {
2549 			pr_warn("alg: aead: skipping comparison tests for %s because %s is unavailable\n",
2550 				driver, generic_driver);
2551 			return 0;
2552 		}
2553 		pr_err("alg: aead: error allocating %s (generic impl of %s): %d\n",
2554 		       generic_driver, algname, err);
2555 		return err;
2556 	}
2557 
2558 	generic_req = aead_request_alloc(generic_tfm, GFP_KERNEL);
2559 	if (!generic_req) {
2560 		err = -ENOMEM;
2561 		goto out;
2562 	}
2563 
2564 	/* Check the algorithm properties for consistency. */
2565 
2566 	if (crypto_aead_maxauthsize(tfm) !=
2567 	    crypto_aead_maxauthsize(generic_tfm)) {
2568 		pr_err("alg: aead: maxauthsize for %s (%u) doesn't match generic impl (%u)\n",
2569 		       driver, crypto_aead_maxauthsize(tfm),
2570 		       crypto_aead_maxauthsize(generic_tfm));
2571 		err = -EINVAL;
2572 		goto out;
2573 	}
2574 
2575 	if (crypto_aead_ivsize(tfm) != crypto_aead_ivsize(generic_tfm)) {
2576 		pr_err("alg: aead: ivsize for %s (%u) doesn't match generic impl (%u)\n",
2577 		       driver, crypto_aead_ivsize(tfm),
2578 		       crypto_aead_ivsize(generic_tfm));
2579 		err = -EINVAL;
2580 		goto out;
2581 	}
2582 
2583 	if (crypto_aead_blocksize(tfm) != crypto_aead_blocksize(generic_tfm)) {
2584 		pr_err("alg: aead: blocksize for %s (%u) doesn't match generic impl (%u)\n",
2585 		       driver, crypto_aead_blocksize(tfm),
2586 		       crypto_aead_blocksize(generic_tfm));
2587 		err = -EINVAL;
2588 		goto out;
2589 	}
2590 
2591 	/*
2592 	 * Now generate test vectors using the generic implementation, and test
2593 	 * the other implementation against them.
2594 	 */
2595 	for (i = 0; i < fuzz_iterations * 8; i++) {
2596 		generate_random_aead_testvec(&ctx->rng, generic_req, &ctx->vec,
2597 					     &ctx->test_desc->suite.aead,
2598 					     ctx->maxkeysize, ctx->maxdatasize,
2599 					     ctx->vec_name,
2600 					     sizeof(ctx->vec_name), false);
2601 		generate_random_testvec_config(&ctx->rng, &ctx->cfg,
2602 					       ctx->cfgname,
2603 					       sizeof(ctx->cfgname));
2604 		if (!ctx->vec.novrfy) {
2605 			err = test_aead_vec_cfg(ENCRYPT, &ctx->vec,
2606 						ctx->vec_name, &ctx->cfg,
2607 						ctx->req, ctx->tsgls);
2608 			if (err)
2609 				goto out;
2610 		}
2611 		if (ctx->vec.crypt_error == 0 || ctx->vec.novrfy) {
2612 			err = test_aead_vec_cfg(DECRYPT, &ctx->vec,
2613 						ctx->vec_name, &ctx->cfg,
2614 						ctx->req, ctx->tsgls);
2615 			if (err)
2616 				goto out;
2617 		}
2618 		cond_resched();
2619 	}
2620 	err = 0;
2621 out:
2622 	crypto_free_aead(generic_tfm);
2623 	aead_request_free(generic_req);
2624 	return err;
2625 }
2626 
2627 static int test_aead_extra(const struct alg_test_desc *test_desc,
2628 			   struct aead_request *req,
2629 			   struct cipher_test_sglists *tsgls)
2630 {
2631 	struct aead_extra_tests_ctx *ctx;
2632 	unsigned int i;
2633 	int err;
2634 
2635 	if (noextratests)
2636 		return 0;
2637 
2638 	ctx = kzalloc(sizeof(*ctx), GFP_KERNEL);
2639 	if (!ctx)
2640 		return -ENOMEM;
2641 	init_rnd_state(&ctx->rng);
2642 	ctx->req = req;
2643 	ctx->tfm = crypto_aead_reqtfm(req);
2644 	ctx->test_desc = test_desc;
2645 	ctx->tsgls = tsgls;
2646 	ctx->maxdatasize = (2 * PAGE_SIZE) - TESTMGR_POISON_LEN;
2647 	ctx->maxkeysize = 0;
2648 	for (i = 0; i < test_desc->suite.aead.count; i++)
2649 		ctx->maxkeysize = max_t(unsigned int, ctx->maxkeysize,
2650 					test_desc->suite.aead.vecs[i].klen);
2651 
2652 	ctx->vec.key = kmalloc(ctx->maxkeysize, GFP_KERNEL);
2653 	ctx->vec.iv = kmalloc(crypto_aead_ivsize(ctx->tfm), GFP_KERNEL);
2654 	ctx->vec.assoc = kmalloc(ctx->maxdatasize, GFP_KERNEL);
2655 	ctx->vec.ptext = kmalloc(ctx->maxdatasize, GFP_KERNEL);
2656 	ctx->vec.ctext = kmalloc(ctx->maxdatasize, GFP_KERNEL);
2657 	if (!ctx->vec.key || !ctx->vec.iv || !ctx->vec.assoc ||
2658 	    !ctx->vec.ptext || !ctx->vec.ctext) {
2659 		err = -ENOMEM;
2660 		goto out;
2661 	}
2662 
2663 	err = test_aead_vs_generic_impl(ctx);
2664 	if (err)
2665 		goto out;
2666 
2667 	err = test_aead_inauthentic_inputs(ctx);
2668 out:
2669 	kfree(ctx->vec.key);
2670 	kfree(ctx->vec.iv);
2671 	kfree(ctx->vec.assoc);
2672 	kfree(ctx->vec.ptext);
2673 	kfree(ctx->vec.ctext);
2674 	kfree(ctx);
2675 	return err;
2676 }
2677 #else /* !CONFIG_CRYPTO_MANAGER_EXTRA_TESTS */
2678 static int test_aead_extra(const struct alg_test_desc *test_desc,
2679 			   struct aead_request *req,
2680 			   struct cipher_test_sglists *tsgls)
2681 {
2682 	return 0;
2683 }
2684 #endif /* !CONFIG_CRYPTO_MANAGER_EXTRA_TESTS */
2685 
2686 static int test_aead(int enc, const struct aead_test_suite *suite,
2687 		     struct aead_request *req,
2688 		     struct cipher_test_sglists *tsgls)
2689 {
2690 	unsigned int i;
2691 	int err;
2692 
2693 	for (i = 0; i < suite->count; i++) {
2694 		err = test_aead_vec(enc, &suite->vecs[i], i, req, tsgls);
2695 		if (err)
2696 			return err;
2697 		cond_resched();
2698 	}
2699 	return 0;
2700 }
2701 
2702 static int alg_test_aead(const struct alg_test_desc *desc, const char *driver,
2703 			 u32 type, u32 mask)
2704 {
2705 	const struct aead_test_suite *suite = &desc->suite.aead;
2706 	struct crypto_aead *tfm;
2707 	struct aead_request *req = NULL;
2708 	struct cipher_test_sglists *tsgls = NULL;
2709 	int err;
2710 
2711 	if (suite->count <= 0) {
2712 		pr_err("alg: aead: empty test suite for %s\n", driver);
2713 		return -EINVAL;
2714 	}
2715 
2716 	tfm = crypto_alloc_aead(driver, type, mask);
2717 	if (IS_ERR(tfm)) {
2718 		if (PTR_ERR(tfm) == -ENOENT)
2719 			return 0;
2720 		pr_err("alg: aead: failed to allocate transform for %s: %ld\n",
2721 		       driver, PTR_ERR(tfm));
2722 		return PTR_ERR(tfm);
2723 	}
2724 	driver = crypto_aead_driver_name(tfm);
2725 
2726 	req = aead_request_alloc(tfm, GFP_KERNEL);
2727 	if (!req) {
2728 		pr_err("alg: aead: failed to allocate request for %s\n",
2729 		       driver);
2730 		err = -ENOMEM;
2731 		goto out;
2732 	}
2733 
2734 	tsgls = alloc_cipher_test_sglists();
2735 	if (!tsgls) {
2736 		pr_err("alg: aead: failed to allocate test buffers for %s\n",
2737 		       driver);
2738 		err = -ENOMEM;
2739 		goto out;
2740 	}
2741 
2742 	err = test_aead(ENCRYPT, suite, req, tsgls);
2743 	if (err)
2744 		goto out;
2745 
2746 	err = test_aead(DECRYPT, suite, req, tsgls);
2747 	if (err)
2748 		goto out;
2749 
2750 	err = test_aead_extra(desc, req, tsgls);
2751 out:
2752 	free_cipher_test_sglists(tsgls);
2753 	aead_request_free(req);
2754 	crypto_free_aead(tfm);
2755 	return err;
2756 }
2757 
2758 static int test_cipher(struct crypto_cipher *tfm, int enc,
2759 		       const struct cipher_testvec *template,
2760 		       unsigned int tcount)
2761 {
2762 	const char *algo = crypto_tfm_alg_driver_name(crypto_cipher_tfm(tfm));
2763 	unsigned int i, j, k;
2764 	char *q;
2765 	const char *e;
2766 	const char *input, *result;
2767 	void *data;
2768 	char *xbuf[XBUFSIZE];
2769 	int ret = -ENOMEM;
2770 
2771 	if (testmgr_alloc_buf(xbuf))
2772 		goto out_nobuf;
2773 
2774 	if (enc == ENCRYPT)
2775 	        e = "encryption";
2776 	else
2777 		e = "decryption";
2778 
2779 	j = 0;
2780 	for (i = 0; i < tcount; i++) {
2781 
2782 		if (fips_enabled && template[i].fips_skip)
2783 			continue;
2784 
2785 		input  = enc ? template[i].ptext : template[i].ctext;
2786 		result = enc ? template[i].ctext : template[i].ptext;
2787 		j++;
2788 
2789 		ret = -EINVAL;
2790 		if (WARN_ON(template[i].len > PAGE_SIZE))
2791 			goto out;
2792 
2793 		data = xbuf[0];
2794 		memcpy(data, input, template[i].len);
2795 
2796 		crypto_cipher_clear_flags(tfm, ~0);
2797 		if (template[i].wk)
2798 			crypto_cipher_set_flags(tfm, CRYPTO_TFM_REQ_FORBID_WEAK_KEYS);
2799 
2800 		ret = crypto_cipher_setkey(tfm, template[i].key,
2801 					   template[i].klen);
2802 		if (ret) {
2803 			if (ret == template[i].setkey_error)
2804 				continue;
2805 			pr_err("alg: cipher: %s setkey failed on test vector %u; expected_error=%d, actual_error=%d, flags=%#x\n",
2806 			       algo, j, template[i].setkey_error, ret,
2807 			       crypto_cipher_get_flags(tfm));
2808 			goto out;
2809 		}
2810 		if (template[i].setkey_error) {
2811 			pr_err("alg: cipher: %s setkey unexpectedly succeeded on test vector %u; expected_error=%d\n",
2812 			       algo, j, template[i].setkey_error);
2813 			ret = -EINVAL;
2814 			goto out;
2815 		}
2816 
2817 		for (k = 0; k < template[i].len;
2818 		     k += crypto_cipher_blocksize(tfm)) {
2819 			if (enc)
2820 				crypto_cipher_encrypt_one(tfm, data + k,
2821 							  data + k);
2822 			else
2823 				crypto_cipher_decrypt_one(tfm, data + k,
2824 							  data + k);
2825 		}
2826 
2827 		q = data;
2828 		if (memcmp(q, result, template[i].len)) {
2829 			printk(KERN_ERR "alg: cipher: Test %d failed "
2830 			       "on %s for %s\n", j, e, algo);
2831 			hexdump(q, template[i].len);
2832 			ret = -EINVAL;
2833 			goto out;
2834 		}
2835 	}
2836 
2837 	ret = 0;
2838 
2839 out:
2840 	testmgr_free_buf(xbuf);
2841 out_nobuf:
2842 	return ret;
2843 }
2844 
2845 static int test_skcipher_vec_cfg(int enc, const struct cipher_testvec *vec,
2846 				 const char *vec_name,
2847 				 const struct testvec_config *cfg,
2848 				 struct skcipher_request *req,
2849 				 struct cipher_test_sglists *tsgls)
2850 {
2851 	struct crypto_skcipher *tfm = crypto_skcipher_reqtfm(req);
2852 	const unsigned int alignmask = crypto_skcipher_alignmask(tfm);
2853 	const unsigned int ivsize = crypto_skcipher_ivsize(tfm);
2854 	const char *driver = crypto_skcipher_driver_name(tfm);
2855 	const u32 req_flags = CRYPTO_TFM_REQ_MAY_BACKLOG | cfg->req_flags;
2856 	const char *op = enc ? "encryption" : "decryption";
2857 	DECLARE_CRYPTO_WAIT(wait);
2858 	u8 _iv[3 * (MAX_ALGAPI_ALIGNMASK + 1) + MAX_IVLEN];
2859 	u8 *iv = PTR_ALIGN(&_iv[0], 2 * (MAX_ALGAPI_ALIGNMASK + 1)) +
2860 		 cfg->iv_offset +
2861 		 (cfg->iv_offset_relative_to_alignmask ? alignmask : 0);
2862 	struct kvec input;
2863 	int err;
2864 
2865 	/* Set the key */
2866 	if (vec->wk)
2867 		crypto_skcipher_set_flags(tfm, CRYPTO_TFM_REQ_FORBID_WEAK_KEYS);
2868 	else
2869 		crypto_skcipher_clear_flags(tfm,
2870 					    CRYPTO_TFM_REQ_FORBID_WEAK_KEYS);
2871 	err = do_setkey(crypto_skcipher_setkey, tfm, vec->key, vec->klen,
2872 			cfg, alignmask);
2873 	if (err) {
2874 		if (err == vec->setkey_error)
2875 			return 0;
2876 		pr_err("alg: skcipher: %s setkey failed on test vector %s; expected_error=%d, actual_error=%d, flags=%#x\n",
2877 		       driver, vec_name, vec->setkey_error, err,
2878 		       crypto_skcipher_get_flags(tfm));
2879 		return err;
2880 	}
2881 	if (vec->setkey_error) {
2882 		pr_err("alg: skcipher: %s setkey unexpectedly succeeded on test vector %s; expected_error=%d\n",
2883 		       driver, vec_name, vec->setkey_error);
2884 		return -EINVAL;
2885 	}
2886 
2887 	/* The IV must be copied to a buffer, as the algorithm may modify it */
2888 	if (ivsize) {
2889 		if (WARN_ON(ivsize > MAX_IVLEN))
2890 			return -EINVAL;
2891 		if (vec->iv)
2892 			memcpy(iv, vec->iv, ivsize);
2893 		else
2894 			memset(iv, 0, ivsize);
2895 	} else {
2896 		iv = NULL;
2897 	}
2898 
2899 	/* Build the src/dst scatterlists */
2900 	input.iov_base = enc ? (void *)vec->ptext : (void *)vec->ctext;
2901 	input.iov_len = vec->len;
2902 	err = build_cipher_test_sglists(tsgls, cfg, alignmask,
2903 					vec->len, vec->len, &input, 1);
2904 	if (err) {
2905 		pr_err("alg: skcipher: %s %s: error preparing scatterlists for test vector %s, cfg=\"%s\"\n",
2906 		       driver, op, vec_name, cfg->name);
2907 		return err;
2908 	}
2909 
2910 	/* Do the actual encryption or decryption */
2911 	testmgr_poison(req->__ctx, crypto_skcipher_reqsize(tfm));
2912 	skcipher_request_set_callback(req, req_flags, crypto_req_done, &wait);
2913 	skcipher_request_set_crypt(req, tsgls->src.sgl_ptr, tsgls->dst.sgl_ptr,
2914 				   vec->len, iv);
2915 	if (cfg->nosimd)
2916 		crypto_disable_simd_for_test();
2917 	err = enc ? crypto_skcipher_encrypt(req) : crypto_skcipher_decrypt(req);
2918 	if (cfg->nosimd)
2919 		crypto_reenable_simd_for_test();
2920 	err = crypto_wait_req(err, &wait);
2921 
2922 	/* Check that the algorithm didn't overwrite things it shouldn't have */
2923 	if (req->cryptlen != vec->len ||
2924 	    req->iv != iv ||
2925 	    req->src != tsgls->src.sgl_ptr ||
2926 	    req->dst != tsgls->dst.sgl_ptr ||
2927 	    crypto_skcipher_reqtfm(req) != tfm ||
2928 	    req->base.complete != crypto_req_done ||
2929 	    req->base.flags != req_flags ||
2930 	    req->base.data != &wait) {
2931 		pr_err("alg: skcipher: %s %s corrupted request struct on test vector %s, cfg=\"%s\"\n",
2932 		       driver, op, vec_name, cfg->name);
2933 		if (req->cryptlen != vec->len)
2934 			pr_err("alg: skcipher: changed 'req->cryptlen'\n");
2935 		if (req->iv != iv)
2936 			pr_err("alg: skcipher: changed 'req->iv'\n");
2937 		if (req->src != tsgls->src.sgl_ptr)
2938 			pr_err("alg: skcipher: changed 'req->src'\n");
2939 		if (req->dst != tsgls->dst.sgl_ptr)
2940 			pr_err("alg: skcipher: changed 'req->dst'\n");
2941 		if (crypto_skcipher_reqtfm(req) != tfm)
2942 			pr_err("alg: skcipher: changed 'req->base.tfm'\n");
2943 		if (req->base.complete != crypto_req_done)
2944 			pr_err("alg: skcipher: changed 'req->base.complete'\n");
2945 		if (req->base.flags != req_flags)
2946 			pr_err("alg: skcipher: changed 'req->base.flags'\n");
2947 		if (req->base.data != &wait)
2948 			pr_err("alg: skcipher: changed 'req->base.data'\n");
2949 		return -EINVAL;
2950 	}
2951 	if (is_test_sglist_corrupted(&tsgls->src)) {
2952 		pr_err("alg: skcipher: %s %s corrupted src sgl on test vector %s, cfg=\"%s\"\n",
2953 		       driver, op, vec_name, cfg->name);
2954 		return -EINVAL;
2955 	}
2956 	if (tsgls->dst.sgl_ptr != tsgls->src.sgl &&
2957 	    is_test_sglist_corrupted(&tsgls->dst)) {
2958 		pr_err("alg: skcipher: %s %s corrupted dst sgl on test vector %s, cfg=\"%s\"\n",
2959 		       driver, op, vec_name, cfg->name);
2960 		return -EINVAL;
2961 	}
2962 
2963 	/* Check for success or failure */
2964 	if (err) {
2965 		if (err == vec->crypt_error)
2966 			return 0;
2967 		pr_err("alg: skcipher: %s %s failed on test vector %s; expected_error=%d, actual_error=%d, cfg=\"%s\"\n",
2968 		       driver, op, vec_name, vec->crypt_error, err, cfg->name);
2969 		return err;
2970 	}
2971 	if (vec->crypt_error) {
2972 		pr_err("alg: skcipher: %s %s unexpectedly succeeded on test vector %s; expected_error=%d, cfg=\"%s\"\n",
2973 		       driver, op, vec_name, vec->crypt_error, cfg->name);
2974 		return -EINVAL;
2975 	}
2976 
2977 	/* Check for the correct output (ciphertext or plaintext) */
2978 	err = verify_correct_output(&tsgls->dst, enc ? vec->ctext : vec->ptext,
2979 				    vec->len, 0, true);
2980 	if (err == -EOVERFLOW) {
2981 		pr_err("alg: skcipher: %s %s overran dst buffer on test vector %s, cfg=\"%s\"\n",
2982 		       driver, op, vec_name, cfg->name);
2983 		return err;
2984 	}
2985 	if (err) {
2986 		pr_err("alg: skcipher: %s %s test failed (wrong result) on test vector %s, cfg=\"%s\"\n",
2987 		       driver, op, vec_name, cfg->name);
2988 		return err;
2989 	}
2990 
2991 	/* If applicable, check that the algorithm generated the correct IV */
2992 	if (vec->iv_out && memcmp(iv, vec->iv_out, ivsize) != 0) {
2993 		pr_err("alg: skcipher: %s %s test failed (wrong output IV) on test vector %s, cfg=\"%s\"\n",
2994 		       driver, op, vec_name, cfg->name);
2995 		hexdump(iv, ivsize);
2996 		return -EINVAL;
2997 	}
2998 
2999 	return 0;
3000 }
3001 
3002 static int test_skcipher_vec(int enc, const struct cipher_testvec *vec,
3003 			     unsigned int vec_num,
3004 			     struct skcipher_request *req,
3005 			     struct cipher_test_sglists *tsgls)
3006 {
3007 	char vec_name[16];
3008 	unsigned int i;
3009 	int err;
3010 
3011 	if (fips_enabled && vec->fips_skip)
3012 		return 0;
3013 
3014 	sprintf(vec_name, "%u", vec_num);
3015 
3016 	for (i = 0; i < ARRAY_SIZE(default_cipher_testvec_configs); i++) {
3017 		err = test_skcipher_vec_cfg(enc, vec, vec_name,
3018 					    &default_cipher_testvec_configs[i],
3019 					    req, tsgls);
3020 		if (err)
3021 			return err;
3022 	}
3023 
3024 #ifdef CONFIG_CRYPTO_MANAGER_EXTRA_TESTS
3025 	if (!noextratests) {
3026 		struct rnd_state rng;
3027 		struct testvec_config cfg;
3028 		char cfgname[TESTVEC_CONFIG_NAMELEN];
3029 
3030 		init_rnd_state(&rng);
3031 
3032 		for (i = 0; i < fuzz_iterations; i++) {
3033 			generate_random_testvec_config(&rng, &cfg, cfgname,
3034 						       sizeof(cfgname));
3035 			err = test_skcipher_vec_cfg(enc, vec, vec_name,
3036 						    &cfg, req, tsgls);
3037 			if (err)
3038 				return err;
3039 			cond_resched();
3040 		}
3041 	}
3042 #endif
3043 	return 0;
3044 }
3045 
3046 #ifdef CONFIG_CRYPTO_MANAGER_EXTRA_TESTS
3047 /*
3048  * Generate a symmetric cipher test vector from the given implementation.
3049  * Assumes the buffers in 'vec' were already allocated.
3050  */
3051 static void generate_random_cipher_testvec(struct rnd_state *rng,
3052 					   struct skcipher_request *req,
3053 					   struct cipher_testvec *vec,
3054 					   unsigned int maxdatasize,
3055 					   char *name, size_t max_namelen)
3056 {
3057 	struct crypto_skcipher *tfm = crypto_skcipher_reqtfm(req);
3058 	const unsigned int maxkeysize = crypto_skcipher_max_keysize(tfm);
3059 	const unsigned int ivsize = crypto_skcipher_ivsize(tfm);
3060 	struct scatterlist src, dst;
3061 	u8 iv[MAX_IVLEN];
3062 	DECLARE_CRYPTO_WAIT(wait);
3063 
3064 	/* Key: length in [0, maxkeysize], but usually choose maxkeysize */
3065 	vec->klen = maxkeysize;
3066 	if (prandom_u32_below(rng, 4) == 0)
3067 		vec->klen = prandom_u32_below(rng, maxkeysize + 1);
3068 	generate_random_bytes(rng, (u8 *)vec->key, vec->klen);
3069 	vec->setkey_error = crypto_skcipher_setkey(tfm, vec->key, vec->klen);
3070 
3071 	/* IV */
3072 	generate_random_bytes(rng, (u8 *)vec->iv, ivsize);
3073 
3074 	/* Plaintext */
3075 	vec->len = generate_random_length(rng, maxdatasize);
3076 	generate_random_bytes(rng, (u8 *)vec->ptext, vec->len);
3077 
3078 	/* If the key couldn't be set, no need to continue to encrypt. */
3079 	if (vec->setkey_error)
3080 		goto done;
3081 
3082 	/* Ciphertext */
3083 	sg_init_one(&src, vec->ptext, vec->len);
3084 	sg_init_one(&dst, vec->ctext, vec->len);
3085 	memcpy(iv, vec->iv, ivsize);
3086 	skcipher_request_set_callback(req, 0, crypto_req_done, &wait);
3087 	skcipher_request_set_crypt(req, &src, &dst, vec->len, iv);
3088 	vec->crypt_error = crypto_wait_req(crypto_skcipher_encrypt(req), &wait);
3089 	if (vec->crypt_error != 0) {
3090 		/*
3091 		 * The only acceptable error here is for an invalid length, so
3092 		 * skcipher decryption should fail with the same error too.
3093 		 * We'll test for this.  But to keep the API usage well-defined,
3094 		 * explicitly initialize the ciphertext buffer too.
3095 		 */
3096 		memset((u8 *)vec->ctext, 0, vec->len);
3097 	}
3098 done:
3099 	snprintf(name, max_namelen, "\"random: len=%u klen=%u\"",
3100 		 vec->len, vec->klen);
3101 }
3102 
3103 /*
3104  * Test the skcipher algorithm represented by @req against the corresponding
3105  * generic implementation, if one is available.
3106  */
3107 static int test_skcipher_vs_generic_impl(const char *generic_driver,
3108 					 struct skcipher_request *req,
3109 					 struct cipher_test_sglists *tsgls)
3110 {
3111 	struct crypto_skcipher *tfm = crypto_skcipher_reqtfm(req);
3112 	const unsigned int maxkeysize = crypto_skcipher_max_keysize(tfm);
3113 	const unsigned int ivsize = crypto_skcipher_ivsize(tfm);
3114 	const unsigned int blocksize = crypto_skcipher_blocksize(tfm);
3115 	const unsigned int maxdatasize = (2 * PAGE_SIZE) - TESTMGR_POISON_LEN;
3116 	const char *algname = crypto_skcipher_alg(tfm)->base.cra_name;
3117 	const char *driver = crypto_skcipher_driver_name(tfm);
3118 	struct rnd_state rng;
3119 	char _generic_driver[CRYPTO_MAX_ALG_NAME];
3120 	struct crypto_skcipher *generic_tfm = NULL;
3121 	struct skcipher_request *generic_req = NULL;
3122 	unsigned int i;
3123 	struct cipher_testvec vec = { 0 };
3124 	char vec_name[64];
3125 	struct testvec_config *cfg;
3126 	char cfgname[TESTVEC_CONFIG_NAMELEN];
3127 	int err;
3128 
3129 	if (noextratests)
3130 		return 0;
3131 
3132 	init_rnd_state(&rng);
3133 
3134 	if (!generic_driver) { /* Use default naming convention? */
3135 		err = build_generic_driver_name(algname, _generic_driver);
3136 		if (err)
3137 			return err;
3138 		generic_driver = _generic_driver;
3139 	}
3140 
3141 	if (strcmp(generic_driver, driver) == 0) /* Already the generic impl? */
3142 		return 0;
3143 
3144 	generic_tfm = crypto_alloc_skcipher(generic_driver, 0, 0);
3145 	if (IS_ERR(generic_tfm)) {
3146 		err = PTR_ERR(generic_tfm);
3147 		if (err == -ENOENT) {
3148 			pr_warn("alg: skcipher: skipping comparison tests for %s because %s is unavailable\n",
3149 				driver, generic_driver);
3150 			return 0;
3151 		}
3152 		pr_err("alg: skcipher: error allocating %s (generic impl of %s): %d\n",
3153 		       generic_driver, algname, err);
3154 		return err;
3155 	}
3156 
3157 	cfg = kzalloc(sizeof(*cfg), GFP_KERNEL);
3158 	if (!cfg) {
3159 		err = -ENOMEM;
3160 		goto out;
3161 	}
3162 
3163 	generic_req = skcipher_request_alloc(generic_tfm, GFP_KERNEL);
3164 	if (!generic_req) {
3165 		err = -ENOMEM;
3166 		goto out;
3167 	}
3168 
3169 	/* Check the algorithm properties for consistency. */
3170 
3171 	if (crypto_skcipher_min_keysize(tfm) !=
3172 	    crypto_skcipher_min_keysize(generic_tfm)) {
3173 		pr_err("alg: skcipher: min keysize for %s (%u) doesn't match generic impl (%u)\n",
3174 		       driver, crypto_skcipher_min_keysize(tfm),
3175 		       crypto_skcipher_min_keysize(generic_tfm));
3176 		err = -EINVAL;
3177 		goto out;
3178 	}
3179 
3180 	if (maxkeysize != crypto_skcipher_max_keysize(generic_tfm)) {
3181 		pr_err("alg: skcipher: max keysize for %s (%u) doesn't match generic impl (%u)\n",
3182 		       driver, maxkeysize,
3183 		       crypto_skcipher_max_keysize(generic_tfm));
3184 		err = -EINVAL;
3185 		goto out;
3186 	}
3187 
3188 	if (ivsize != crypto_skcipher_ivsize(generic_tfm)) {
3189 		pr_err("alg: skcipher: ivsize for %s (%u) doesn't match generic impl (%u)\n",
3190 		       driver, ivsize, crypto_skcipher_ivsize(generic_tfm));
3191 		err = -EINVAL;
3192 		goto out;
3193 	}
3194 
3195 	if (blocksize != crypto_skcipher_blocksize(generic_tfm)) {
3196 		pr_err("alg: skcipher: blocksize for %s (%u) doesn't match generic impl (%u)\n",
3197 		       driver, blocksize,
3198 		       crypto_skcipher_blocksize(generic_tfm));
3199 		err = -EINVAL;
3200 		goto out;
3201 	}
3202 
3203 	/*
3204 	 * Now generate test vectors using the generic implementation, and test
3205 	 * the other implementation against them.
3206 	 */
3207 
3208 	vec.key = kmalloc(maxkeysize, GFP_KERNEL);
3209 	vec.iv = kmalloc(ivsize, GFP_KERNEL);
3210 	vec.ptext = kmalloc(maxdatasize, GFP_KERNEL);
3211 	vec.ctext = kmalloc(maxdatasize, GFP_KERNEL);
3212 	if (!vec.key || !vec.iv || !vec.ptext || !vec.ctext) {
3213 		err = -ENOMEM;
3214 		goto out;
3215 	}
3216 
3217 	for (i = 0; i < fuzz_iterations * 8; i++) {
3218 		generate_random_cipher_testvec(&rng, generic_req, &vec,
3219 					       maxdatasize,
3220 					       vec_name, sizeof(vec_name));
3221 		generate_random_testvec_config(&rng, cfg, cfgname,
3222 					       sizeof(cfgname));
3223 
3224 		err = test_skcipher_vec_cfg(ENCRYPT, &vec, vec_name,
3225 					    cfg, req, tsgls);
3226 		if (err)
3227 			goto out;
3228 		err = test_skcipher_vec_cfg(DECRYPT, &vec, vec_name,
3229 					    cfg, req, tsgls);
3230 		if (err)
3231 			goto out;
3232 		cond_resched();
3233 	}
3234 	err = 0;
3235 out:
3236 	kfree(cfg);
3237 	kfree(vec.key);
3238 	kfree(vec.iv);
3239 	kfree(vec.ptext);
3240 	kfree(vec.ctext);
3241 	crypto_free_skcipher(generic_tfm);
3242 	skcipher_request_free(generic_req);
3243 	return err;
3244 }
3245 #else /* !CONFIG_CRYPTO_MANAGER_EXTRA_TESTS */
3246 static int test_skcipher_vs_generic_impl(const char *generic_driver,
3247 					 struct skcipher_request *req,
3248 					 struct cipher_test_sglists *tsgls)
3249 {
3250 	return 0;
3251 }
3252 #endif /* !CONFIG_CRYPTO_MANAGER_EXTRA_TESTS */
3253 
3254 static int test_skcipher(int enc, const struct cipher_test_suite *suite,
3255 			 struct skcipher_request *req,
3256 			 struct cipher_test_sglists *tsgls)
3257 {
3258 	unsigned int i;
3259 	int err;
3260 
3261 	for (i = 0; i < suite->count; i++) {
3262 		err = test_skcipher_vec(enc, &suite->vecs[i], i, req, tsgls);
3263 		if (err)
3264 			return err;
3265 		cond_resched();
3266 	}
3267 	return 0;
3268 }
3269 
3270 static int alg_test_skcipher(const struct alg_test_desc *desc,
3271 			     const char *driver, u32 type, u32 mask)
3272 {
3273 	const struct cipher_test_suite *suite = &desc->suite.cipher;
3274 	struct crypto_skcipher *tfm;
3275 	struct skcipher_request *req = NULL;
3276 	struct cipher_test_sglists *tsgls = NULL;
3277 	int err;
3278 
3279 	if (suite->count <= 0) {
3280 		pr_err("alg: skcipher: empty test suite for %s\n", driver);
3281 		return -EINVAL;
3282 	}
3283 
3284 	tfm = crypto_alloc_skcipher(driver, type, mask);
3285 	if (IS_ERR(tfm)) {
3286 		if (PTR_ERR(tfm) == -ENOENT)
3287 			return 0;
3288 		pr_err("alg: skcipher: failed to allocate transform for %s: %ld\n",
3289 		       driver, PTR_ERR(tfm));
3290 		return PTR_ERR(tfm);
3291 	}
3292 	driver = crypto_skcipher_driver_name(tfm);
3293 
3294 	req = skcipher_request_alloc(tfm, GFP_KERNEL);
3295 	if (!req) {
3296 		pr_err("alg: skcipher: failed to allocate request for %s\n",
3297 		       driver);
3298 		err = -ENOMEM;
3299 		goto out;
3300 	}
3301 
3302 	tsgls = alloc_cipher_test_sglists();
3303 	if (!tsgls) {
3304 		pr_err("alg: skcipher: failed to allocate test buffers for %s\n",
3305 		       driver);
3306 		err = -ENOMEM;
3307 		goto out;
3308 	}
3309 
3310 	err = test_skcipher(ENCRYPT, suite, req, tsgls);
3311 	if (err)
3312 		goto out;
3313 
3314 	err = test_skcipher(DECRYPT, suite, req, tsgls);
3315 	if (err)
3316 		goto out;
3317 
3318 	err = test_skcipher_vs_generic_impl(desc->generic_driver, req, tsgls);
3319 out:
3320 	free_cipher_test_sglists(tsgls);
3321 	skcipher_request_free(req);
3322 	crypto_free_skcipher(tfm);
3323 	return err;
3324 }
3325 
3326 static int test_acomp(struct crypto_acomp *tfm,
3327 		      const struct comp_testvec *ctemplate,
3328 		      const struct comp_testvec *dtemplate,
3329 		      int ctcount, int dtcount)
3330 {
3331 	const char *algo = crypto_tfm_alg_driver_name(crypto_acomp_tfm(tfm));
3332 	struct scatterlist *src = NULL, *dst = NULL;
3333 	struct acomp_req *reqs[MAX_MB_MSGS] = {};
3334 	char *decomp_out[MAX_MB_MSGS] = {};
3335 	char *output[MAX_MB_MSGS] = {};
3336 	struct crypto_wait wait;
3337 	struct acomp_req *req;
3338 	int ret = -ENOMEM;
3339 	unsigned int i;
3340 
3341 	src = kmalloc_array(MAX_MB_MSGS, sizeof(*src), GFP_KERNEL);
3342 	if (!src)
3343 		goto out;
3344 	dst = kmalloc_array(MAX_MB_MSGS, sizeof(*dst), GFP_KERNEL);
3345 	if (!dst)
3346 		goto out;
3347 
3348 	for (i = 0; i < MAX_MB_MSGS; i++) {
3349 		reqs[i] = acomp_request_alloc(tfm);
3350 		if (!reqs[i])
3351 			goto out;
3352 
3353 		acomp_request_set_callback(reqs[i],
3354 					   CRYPTO_TFM_REQ_MAY_SLEEP |
3355 					   CRYPTO_TFM_REQ_MAY_BACKLOG,
3356 					   crypto_req_done, &wait);
3357 		if (i)
3358 			acomp_request_chain(reqs[i], reqs[0]);
3359 
3360 		output[i] = kmalloc(COMP_BUF_SIZE, GFP_KERNEL);
3361 		if (!output[i])
3362 			goto out;
3363 
3364 		decomp_out[i] = kmalloc(COMP_BUF_SIZE, GFP_KERNEL);
3365 		if (!decomp_out[i])
3366 			goto out;
3367 	}
3368 
3369 	for (i = 0; i < ctcount; i++) {
3370 		unsigned int dlen = COMP_BUF_SIZE;
3371 		int ilen = ctemplate[i].inlen;
3372 		void *input_vec;
3373 		int j;
3374 
3375 		input_vec = kmemdup(ctemplate[i].input, ilen, GFP_KERNEL);
3376 		if (!input_vec) {
3377 			ret = -ENOMEM;
3378 			goto out;
3379 		}
3380 
3381 		crypto_init_wait(&wait);
3382 		sg_init_one(src, input_vec, ilen);
3383 
3384 		for (j = 0; j < MAX_MB_MSGS; j++) {
3385 			sg_init_one(dst + j, output[j], dlen);
3386 			acomp_request_set_params(reqs[j], src, dst + j, ilen, dlen);
3387 		}
3388 
3389 		req = reqs[0];
3390 		ret = crypto_wait_req(crypto_acomp_compress(req), &wait);
3391 		if (ret) {
3392 			pr_err("alg: acomp: compression failed on test %d for %s: ret=%d\n",
3393 			       i + 1, algo, -ret);
3394 			kfree(input_vec);
3395 			goto out;
3396 		}
3397 
3398 		ilen = req->dlen;
3399 		dlen = COMP_BUF_SIZE;
3400 		crypto_init_wait(&wait);
3401 		for (j = 0; j < MAX_MB_MSGS; j++) {
3402 			sg_init_one(src + j, output[j], ilen);
3403 			sg_init_one(dst + j, decomp_out[j], dlen);
3404 			acomp_request_set_params(reqs[j], src + j, dst + j, ilen, dlen);
3405 		}
3406 
3407 		crypto_wait_req(crypto_acomp_decompress(req), &wait);
3408 		for (j = 0; j < MAX_MB_MSGS; j++) {
3409 			ret = reqs[j]->base.err;
3410 			if (ret) {
3411 				pr_err("alg: acomp: compression failed on test %d (%d) for %s: ret=%d\n",
3412 				       i + 1, j, algo, -ret);
3413 				kfree(input_vec);
3414 				goto out;
3415 			}
3416 
3417 			if (reqs[j]->dlen != ctemplate[i].inlen) {
3418 				pr_err("alg: acomp: Compression test %d (%d) failed for %s: output len = %d\n",
3419 				       i + 1, j, algo, reqs[j]->dlen);
3420 				ret = -EINVAL;
3421 				kfree(input_vec);
3422 				goto out;
3423 			}
3424 
3425 			if (memcmp(input_vec, decomp_out[j], reqs[j]->dlen)) {
3426 				pr_err("alg: acomp: Compression test %d (%d) failed for %s\n",
3427 				       i + 1, j, algo);
3428 				hexdump(output[j], reqs[j]->dlen);
3429 				ret = -EINVAL;
3430 				kfree(input_vec);
3431 				goto out;
3432 			}
3433 		}
3434 
3435 		kfree(input_vec);
3436 	}
3437 
3438 	for (i = 0; i < dtcount; i++) {
3439 		unsigned int dlen = COMP_BUF_SIZE;
3440 		int ilen = dtemplate[i].inlen;
3441 		void *input_vec;
3442 
3443 		input_vec = kmemdup(dtemplate[i].input, ilen, GFP_KERNEL);
3444 		if (!input_vec) {
3445 			ret = -ENOMEM;
3446 			goto out;
3447 		}
3448 
3449 		crypto_init_wait(&wait);
3450 		sg_init_one(src, input_vec, ilen);
3451 		sg_init_one(dst, output[0], dlen);
3452 
3453 		req = acomp_request_alloc(tfm);
3454 		if (!req) {
3455 			pr_err("alg: acomp: request alloc failed for %s\n",
3456 			       algo);
3457 			kfree(input_vec);
3458 			ret = -ENOMEM;
3459 			goto out;
3460 		}
3461 
3462 		acomp_request_set_params(req, src, dst, ilen, dlen);
3463 		acomp_request_set_callback(req, CRYPTO_TFM_REQ_MAY_BACKLOG,
3464 					   crypto_req_done, &wait);
3465 
3466 		ret = crypto_wait_req(crypto_acomp_decompress(req), &wait);
3467 		if (ret) {
3468 			pr_err("alg: acomp: decompression failed on test %d for %s: ret=%d\n",
3469 			       i + 1, algo, -ret);
3470 			kfree(input_vec);
3471 			acomp_request_free(req);
3472 			goto out;
3473 		}
3474 
3475 		if (req->dlen != dtemplate[i].outlen) {
3476 			pr_err("alg: acomp: Decompression test %d failed for %s: output len = %d\n",
3477 			       i + 1, algo, req->dlen);
3478 			ret = -EINVAL;
3479 			kfree(input_vec);
3480 			acomp_request_free(req);
3481 			goto out;
3482 		}
3483 
3484 		if (memcmp(output[0], dtemplate[i].output, req->dlen)) {
3485 			pr_err("alg: acomp: Decompression test %d failed for %s\n",
3486 			       i + 1, algo);
3487 			hexdump(output[0], req->dlen);
3488 			ret = -EINVAL;
3489 			kfree(input_vec);
3490 			acomp_request_free(req);
3491 			goto out;
3492 		}
3493 
3494 		kfree(input_vec);
3495 		acomp_request_free(req);
3496 	}
3497 
3498 	ret = 0;
3499 
3500 out:
3501 	acomp_request_free(reqs[0]);
3502 	for (i = 0; i < MAX_MB_MSGS; i++) {
3503 		kfree(output[i]);
3504 		kfree(decomp_out[i]);
3505 	}
3506 	kfree(dst);
3507 	kfree(src);
3508 	return ret;
3509 }
3510 
3511 static int test_cprng(struct crypto_rng *tfm,
3512 		      const struct cprng_testvec *template,
3513 		      unsigned int tcount)
3514 {
3515 	const char *algo = crypto_tfm_alg_driver_name(crypto_rng_tfm(tfm));
3516 	int err = 0, i, j, seedsize;
3517 	u8 *seed;
3518 	char result[32];
3519 
3520 	seedsize = crypto_rng_seedsize(tfm);
3521 
3522 	seed = kmalloc(seedsize, GFP_KERNEL);
3523 	if (!seed) {
3524 		printk(KERN_ERR "alg: cprng: Failed to allocate seed space "
3525 		       "for %s\n", algo);
3526 		return -ENOMEM;
3527 	}
3528 
3529 	for (i = 0; i < tcount; i++) {
3530 		memset(result, 0, 32);
3531 
3532 		memcpy(seed, template[i].v, template[i].vlen);
3533 		memcpy(seed + template[i].vlen, template[i].key,
3534 		       template[i].klen);
3535 		memcpy(seed + template[i].vlen + template[i].klen,
3536 		       template[i].dt, template[i].dtlen);
3537 
3538 		err = crypto_rng_reset(tfm, seed, seedsize);
3539 		if (err) {
3540 			printk(KERN_ERR "alg: cprng: Failed to reset rng "
3541 			       "for %s\n", algo);
3542 			goto out;
3543 		}
3544 
3545 		for (j = 0; j < template[i].loops; j++) {
3546 			err = crypto_rng_get_bytes(tfm, result,
3547 						   template[i].rlen);
3548 			if (err < 0) {
3549 				printk(KERN_ERR "alg: cprng: Failed to obtain "
3550 				       "the correct amount of random data for "
3551 				       "%s (requested %d)\n", algo,
3552 				       template[i].rlen);
3553 				goto out;
3554 			}
3555 		}
3556 
3557 		err = memcmp(result, template[i].result,
3558 			     template[i].rlen);
3559 		if (err) {
3560 			printk(KERN_ERR "alg: cprng: Test %d failed for %s\n",
3561 			       i, algo);
3562 			hexdump(result, template[i].rlen);
3563 			err = -EINVAL;
3564 			goto out;
3565 		}
3566 	}
3567 
3568 out:
3569 	kfree(seed);
3570 	return err;
3571 }
3572 
3573 static int alg_test_cipher(const struct alg_test_desc *desc,
3574 			   const char *driver, u32 type, u32 mask)
3575 {
3576 	const struct cipher_test_suite *suite = &desc->suite.cipher;
3577 	struct crypto_cipher *tfm;
3578 	int err;
3579 
3580 	tfm = crypto_alloc_cipher(driver, type, mask);
3581 	if (IS_ERR(tfm)) {
3582 		if (PTR_ERR(tfm) == -ENOENT)
3583 			return 0;
3584 		printk(KERN_ERR "alg: cipher: Failed to load transform for "
3585 		       "%s: %ld\n", driver, PTR_ERR(tfm));
3586 		return PTR_ERR(tfm);
3587 	}
3588 
3589 	err = test_cipher(tfm, ENCRYPT, suite->vecs, suite->count);
3590 	if (!err)
3591 		err = test_cipher(tfm, DECRYPT, suite->vecs, suite->count);
3592 
3593 	crypto_free_cipher(tfm);
3594 	return err;
3595 }
3596 
3597 static int alg_test_comp(const struct alg_test_desc *desc, const char *driver,
3598 			 u32 type, u32 mask)
3599 {
3600 	struct crypto_acomp *acomp;
3601 	int err;
3602 
3603 	acomp = crypto_alloc_acomp(driver, type, mask);
3604 	if (IS_ERR(acomp)) {
3605 		if (PTR_ERR(acomp) == -ENOENT)
3606 			return 0;
3607 		pr_err("alg: acomp: Failed to load transform for %s: %ld\n",
3608 		       driver, PTR_ERR(acomp));
3609 		return PTR_ERR(acomp);
3610 	}
3611 	err = test_acomp(acomp, desc->suite.comp.comp.vecs,
3612 			 desc->suite.comp.decomp.vecs,
3613 			 desc->suite.comp.comp.count,
3614 			 desc->suite.comp.decomp.count);
3615 	crypto_free_acomp(acomp);
3616 	return err;
3617 }
3618 
3619 static int alg_test_crc32c(const struct alg_test_desc *desc,
3620 			   const char *driver, u32 type, u32 mask)
3621 {
3622 	struct crypto_shash *tfm;
3623 	__le32 val;
3624 	int err;
3625 
3626 	err = alg_test_hash(desc, driver, type, mask);
3627 	if (err)
3628 		return err;
3629 
3630 	tfm = crypto_alloc_shash(driver, type, mask);
3631 	if (IS_ERR(tfm)) {
3632 		if (PTR_ERR(tfm) == -ENOENT) {
3633 			/*
3634 			 * This crc32c implementation is only available through
3635 			 * ahash API, not the shash API, so the remaining part
3636 			 * of the test is not applicable to it.
3637 			 */
3638 			return 0;
3639 		}
3640 		printk(KERN_ERR "alg: crc32c: Failed to load transform for %s: "
3641 		       "%ld\n", driver, PTR_ERR(tfm));
3642 		return PTR_ERR(tfm);
3643 	}
3644 	driver = crypto_shash_driver_name(tfm);
3645 
3646 	do {
3647 		SHASH_DESC_ON_STACK(shash, tfm);
3648 		u32 *ctx = (u32 *)shash_desc_ctx(shash);
3649 
3650 		shash->tfm = tfm;
3651 
3652 		*ctx = 420553207;
3653 		err = crypto_shash_final(shash, (u8 *)&val);
3654 		if (err) {
3655 			printk(KERN_ERR "alg: crc32c: Operation failed for "
3656 			       "%s: %d\n", driver, err);
3657 			break;
3658 		}
3659 
3660 		if (val != cpu_to_le32(~420553207)) {
3661 			pr_err("alg: crc32c: Test failed for %s: %u\n",
3662 			       driver, le32_to_cpu(val));
3663 			err = -EINVAL;
3664 		}
3665 	} while (0);
3666 
3667 	crypto_free_shash(tfm);
3668 
3669 	return err;
3670 }
3671 
3672 static int alg_test_cprng(const struct alg_test_desc *desc, const char *driver,
3673 			  u32 type, u32 mask)
3674 {
3675 	struct crypto_rng *rng;
3676 	int err;
3677 
3678 	rng = crypto_alloc_rng(driver, type, mask);
3679 	if (IS_ERR(rng)) {
3680 		if (PTR_ERR(rng) == -ENOENT)
3681 			return 0;
3682 		printk(KERN_ERR "alg: cprng: Failed to load transform for %s: "
3683 		       "%ld\n", driver, PTR_ERR(rng));
3684 		return PTR_ERR(rng);
3685 	}
3686 
3687 	err = test_cprng(rng, desc->suite.cprng.vecs, desc->suite.cprng.count);
3688 
3689 	crypto_free_rng(rng);
3690 
3691 	return err;
3692 }
3693 
3694 
3695 static int drbg_cavs_test(const struct drbg_testvec *test, int pr,
3696 			  const char *driver, u32 type, u32 mask)
3697 {
3698 	int ret = -EAGAIN;
3699 	struct crypto_rng *drng;
3700 	struct drbg_test_data test_data;
3701 	struct drbg_string addtl, pers, testentropy;
3702 	unsigned char *buf = kzalloc(test->expectedlen, GFP_KERNEL);
3703 
3704 	if (!buf)
3705 		return -ENOMEM;
3706 
3707 	drng = crypto_alloc_rng(driver, type, mask);
3708 	if (IS_ERR(drng)) {
3709 		kfree_sensitive(buf);
3710 		if (PTR_ERR(drng) == -ENOENT)
3711 			return 0;
3712 		printk(KERN_ERR "alg: drbg: could not allocate DRNG handle for "
3713 		       "%s\n", driver);
3714 		return PTR_ERR(drng);
3715 	}
3716 
3717 	test_data.testentropy = &testentropy;
3718 	drbg_string_fill(&testentropy, test->entropy, test->entropylen);
3719 	drbg_string_fill(&pers, test->pers, test->perslen);
3720 	ret = crypto_drbg_reset_test(drng, &pers, &test_data);
3721 	if (ret) {
3722 		printk(KERN_ERR "alg: drbg: Failed to reset rng\n");
3723 		goto outbuf;
3724 	}
3725 
3726 	drbg_string_fill(&addtl, test->addtla, test->addtllen);
3727 	if (pr) {
3728 		drbg_string_fill(&testentropy, test->entpra, test->entprlen);
3729 		ret = crypto_drbg_get_bytes_addtl_test(drng,
3730 			buf, test->expectedlen, &addtl,	&test_data);
3731 	} else {
3732 		ret = crypto_drbg_get_bytes_addtl(drng,
3733 			buf, test->expectedlen, &addtl);
3734 	}
3735 	if (ret < 0) {
3736 		printk(KERN_ERR "alg: drbg: could not obtain random data for "
3737 		       "driver %s\n", driver);
3738 		goto outbuf;
3739 	}
3740 
3741 	drbg_string_fill(&addtl, test->addtlb, test->addtllen);
3742 	if (pr) {
3743 		drbg_string_fill(&testentropy, test->entprb, test->entprlen);
3744 		ret = crypto_drbg_get_bytes_addtl_test(drng,
3745 			buf, test->expectedlen, &addtl, &test_data);
3746 	} else {
3747 		ret = crypto_drbg_get_bytes_addtl(drng,
3748 			buf, test->expectedlen, &addtl);
3749 	}
3750 	if (ret < 0) {
3751 		printk(KERN_ERR "alg: drbg: could not obtain random data for "
3752 		       "driver %s\n", driver);
3753 		goto outbuf;
3754 	}
3755 
3756 	ret = memcmp(test->expected, buf, test->expectedlen);
3757 
3758 outbuf:
3759 	crypto_free_rng(drng);
3760 	kfree_sensitive(buf);
3761 	return ret;
3762 }
3763 
3764 
3765 static int alg_test_drbg(const struct alg_test_desc *desc, const char *driver,
3766 			 u32 type, u32 mask)
3767 {
3768 	int err = 0;
3769 	int pr = 0;
3770 	int i = 0;
3771 	const struct drbg_testvec *template = desc->suite.drbg.vecs;
3772 	unsigned int tcount = desc->suite.drbg.count;
3773 
3774 	if (0 == memcmp(driver, "drbg_pr_", 8))
3775 		pr = 1;
3776 
3777 	for (i = 0; i < tcount; i++) {
3778 		err = drbg_cavs_test(&template[i], pr, driver, type, mask);
3779 		if (err) {
3780 			printk(KERN_ERR "alg: drbg: Test %d failed for %s\n",
3781 			       i, driver);
3782 			err = -EINVAL;
3783 			break;
3784 		}
3785 	}
3786 	return err;
3787 
3788 }
3789 
3790 static int do_test_kpp(struct crypto_kpp *tfm, const struct kpp_testvec *vec,
3791 		       const char *alg)
3792 {
3793 	struct kpp_request *req;
3794 	void *input_buf = NULL;
3795 	void *output_buf = NULL;
3796 	void *a_public = NULL;
3797 	void *a_ss = NULL;
3798 	void *shared_secret = NULL;
3799 	struct crypto_wait wait;
3800 	unsigned int out_len_max;
3801 	int err = -ENOMEM;
3802 	struct scatterlist src, dst;
3803 
3804 	req = kpp_request_alloc(tfm, GFP_KERNEL);
3805 	if (!req)
3806 		return err;
3807 
3808 	crypto_init_wait(&wait);
3809 
3810 	err = crypto_kpp_set_secret(tfm, vec->secret, vec->secret_size);
3811 	if (err < 0)
3812 		goto free_req;
3813 
3814 	out_len_max = crypto_kpp_maxsize(tfm);
3815 	output_buf = kzalloc(out_len_max, GFP_KERNEL);
3816 	if (!output_buf) {
3817 		err = -ENOMEM;
3818 		goto free_req;
3819 	}
3820 
3821 	/* Use appropriate parameter as base */
3822 	kpp_request_set_input(req, NULL, 0);
3823 	sg_init_one(&dst, output_buf, out_len_max);
3824 	kpp_request_set_output(req, &dst, out_len_max);
3825 	kpp_request_set_callback(req, CRYPTO_TFM_REQ_MAY_BACKLOG,
3826 				 crypto_req_done, &wait);
3827 
3828 	/* Compute party A's public key */
3829 	err = crypto_wait_req(crypto_kpp_generate_public_key(req), &wait);
3830 	if (err) {
3831 		pr_err("alg: %s: Party A: generate public key test failed. err %d\n",
3832 		       alg, err);
3833 		goto free_output;
3834 	}
3835 
3836 	if (vec->genkey) {
3837 		/* Save party A's public key */
3838 		a_public = kmemdup(sg_virt(req->dst), out_len_max, GFP_KERNEL);
3839 		if (!a_public) {
3840 			err = -ENOMEM;
3841 			goto free_output;
3842 		}
3843 	} else {
3844 		/* Verify calculated public key */
3845 		if (memcmp(vec->expected_a_public, sg_virt(req->dst),
3846 			   vec->expected_a_public_size)) {
3847 			pr_err("alg: %s: Party A: generate public key test failed. Invalid output\n",
3848 			       alg);
3849 			err = -EINVAL;
3850 			goto free_output;
3851 		}
3852 	}
3853 
3854 	/* Calculate shared secret key by using counter part (b) public key. */
3855 	input_buf = kmemdup(vec->b_public, vec->b_public_size, GFP_KERNEL);
3856 	if (!input_buf) {
3857 		err = -ENOMEM;
3858 		goto free_output;
3859 	}
3860 
3861 	sg_init_one(&src, input_buf, vec->b_public_size);
3862 	sg_init_one(&dst, output_buf, out_len_max);
3863 	kpp_request_set_input(req, &src, vec->b_public_size);
3864 	kpp_request_set_output(req, &dst, out_len_max);
3865 	kpp_request_set_callback(req, CRYPTO_TFM_REQ_MAY_BACKLOG,
3866 				 crypto_req_done, &wait);
3867 	err = crypto_wait_req(crypto_kpp_compute_shared_secret(req), &wait);
3868 	if (err) {
3869 		pr_err("alg: %s: Party A: compute shared secret test failed. err %d\n",
3870 		       alg, err);
3871 		goto free_all;
3872 	}
3873 
3874 	if (vec->genkey) {
3875 		/* Save the shared secret obtained by party A */
3876 		a_ss = kmemdup(sg_virt(req->dst), vec->expected_ss_size, GFP_KERNEL);
3877 		if (!a_ss) {
3878 			err = -ENOMEM;
3879 			goto free_all;
3880 		}
3881 
3882 		/*
3883 		 * Calculate party B's shared secret by using party A's
3884 		 * public key.
3885 		 */
3886 		err = crypto_kpp_set_secret(tfm, vec->b_secret,
3887 					    vec->b_secret_size);
3888 		if (err < 0)
3889 			goto free_all;
3890 
3891 		sg_init_one(&src, a_public, vec->expected_a_public_size);
3892 		sg_init_one(&dst, output_buf, out_len_max);
3893 		kpp_request_set_input(req, &src, vec->expected_a_public_size);
3894 		kpp_request_set_output(req, &dst, out_len_max);
3895 		kpp_request_set_callback(req, CRYPTO_TFM_REQ_MAY_BACKLOG,
3896 					 crypto_req_done, &wait);
3897 		err = crypto_wait_req(crypto_kpp_compute_shared_secret(req),
3898 				      &wait);
3899 		if (err) {
3900 			pr_err("alg: %s: Party B: compute shared secret failed. err %d\n",
3901 			       alg, err);
3902 			goto free_all;
3903 		}
3904 
3905 		shared_secret = a_ss;
3906 	} else {
3907 		shared_secret = (void *)vec->expected_ss;
3908 	}
3909 
3910 	/*
3911 	 * verify shared secret from which the user will derive
3912 	 * secret key by executing whatever hash it has chosen
3913 	 */
3914 	if (memcmp(shared_secret, sg_virt(req->dst),
3915 		   vec->expected_ss_size)) {
3916 		pr_err("alg: %s: compute shared secret test failed. Invalid output\n",
3917 		       alg);
3918 		err = -EINVAL;
3919 	}
3920 
3921 free_all:
3922 	kfree(a_ss);
3923 	kfree(input_buf);
3924 free_output:
3925 	kfree(a_public);
3926 	kfree(output_buf);
3927 free_req:
3928 	kpp_request_free(req);
3929 	return err;
3930 }
3931 
3932 static int test_kpp(struct crypto_kpp *tfm, const char *alg,
3933 		    const struct kpp_testvec *vecs, unsigned int tcount)
3934 {
3935 	int ret, i;
3936 
3937 	for (i = 0; i < tcount; i++) {
3938 		ret = do_test_kpp(tfm, vecs++, alg);
3939 		if (ret) {
3940 			pr_err("alg: %s: test failed on vector %d, err=%d\n",
3941 			       alg, i + 1, ret);
3942 			return ret;
3943 		}
3944 	}
3945 	return 0;
3946 }
3947 
3948 static int alg_test_kpp(const struct alg_test_desc *desc, const char *driver,
3949 			u32 type, u32 mask)
3950 {
3951 	struct crypto_kpp *tfm;
3952 	int err = 0;
3953 
3954 	tfm = crypto_alloc_kpp(driver, type, mask);
3955 	if (IS_ERR(tfm)) {
3956 		if (PTR_ERR(tfm) == -ENOENT)
3957 			return 0;
3958 		pr_err("alg: kpp: Failed to load tfm for %s: %ld\n",
3959 		       driver, PTR_ERR(tfm));
3960 		return PTR_ERR(tfm);
3961 	}
3962 	if (desc->suite.kpp.vecs)
3963 		err = test_kpp(tfm, desc->alg, desc->suite.kpp.vecs,
3964 			       desc->suite.kpp.count);
3965 
3966 	crypto_free_kpp(tfm);
3967 	return err;
3968 }
3969 
3970 static u8 *test_pack_u32(u8 *dst, u32 val)
3971 {
3972 	memcpy(dst, &val, sizeof(val));
3973 	return dst + sizeof(val);
3974 }
3975 
3976 static int test_akcipher_one(struct crypto_akcipher *tfm,
3977 			     const struct akcipher_testvec *vecs)
3978 {
3979 	char *xbuf[XBUFSIZE];
3980 	struct akcipher_request *req;
3981 	void *outbuf_enc = NULL;
3982 	void *outbuf_dec = NULL;
3983 	struct crypto_wait wait;
3984 	unsigned int out_len_max, out_len = 0;
3985 	int err = -ENOMEM;
3986 	struct scatterlist src, dst, src_tab[2];
3987 	const char *c;
3988 	unsigned int c_size;
3989 
3990 	if (testmgr_alloc_buf(xbuf))
3991 		return err;
3992 
3993 	req = akcipher_request_alloc(tfm, GFP_KERNEL);
3994 	if (!req)
3995 		goto free_xbuf;
3996 
3997 	crypto_init_wait(&wait);
3998 
3999 	if (vecs->public_key_vec)
4000 		err = crypto_akcipher_set_pub_key(tfm, vecs->key,
4001 						  vecs->key_len);
4002 	else
4003 		err = crypto_akcipher_set_priv_key(tfm, vecs->key,
4004 						   vecs->key_len);
4005 	if (err)
4006 		goto free_req;
4007 
4008 	/* First run encrypt test which does not require a private key */
4009 	err = -ENOMEM;
4010 	out_len_max = crypto_akcipher_maxsize(tfm);
4011 	outbuf_enc = kzalloc(out_len_max, GFP_KERNEL);
4012 	if (!outbuf_enc)
4013 		goto free_req;
4014 
4015 	c = vecs->c;
4016 	c_size = vecs->c_size;
4017 
4018 	err = -E2BIG;
4019 	if (WARN_ON(vecs->m_size > PAGE_SIZE))
4020 		goto free_all;
4021 	memcpy(xbuf[0], vecs->m, vecs->m_size);
4022 
4023 	sg_init_table(src_tab, 2);
4024 	sg_set_buf(&src_tab[0], xbuf[0], 8);
4025 	sg_set_buf(&src_tab[1], xbuf[0] + 8, vecs->m_size - 8);
4026 	sg_init_one(&dst, outbuf_enc, out_len_max);
4027 	akcipher_request_set_crypt(req, src_tab, &dst, vecs->m_size,
4028 				   out_len_max);
4029 	akcipher_request_set_callback(req, CRYPTO_TFM_REQ_MAY_BACKLOG,
4030 				      crypto_req_done, &wait);
4031 
4032 	err = crypto_wait_req(crypto_akcipher_encrypt(req), &wait);
4033 	if (err) {
4034 		pr_err("alg: akcipher: encrypt test failed. err %d\n", err);
4035 		goto free_all;
4036 	}
4037 	if (c) {
4038 		if (req->dst_len != c_size) {
4039 			pr_err("alg: akcipher: encrypt test failed. Invalid output len\n");
4040 			err = -EINVAL;
4041 			goto free_all;
4042 		}
4043 		/* verify that encrypted message is equal to expected */
4044 		if (memcmp(c, outbuf_enc, c_size) != 0) {
4045 			pr_err("alg: akcipher: encrypt test failed. Invalid output\n");
4046 			hexdump(outbuf_enc, c_size);
4047 			err = -EINVAL;
4048 			goto free_all;
4049 		}
4050 	}
4051 
4052 	/*
4053 	 * Don't invoke decrypt test which requires a private key
4054 	 * for vectors with only a public key.
4055 	 */
4056 	if (vecs->public_key_vec) {
4057 		err = 0;
4058 		goto free_all;
4059 	}
4060 	outbuf_dec = kzalloc(out_len_max, GFP_KERNEL);
4061 	if (!outbuf_dec) {
4062 		err = -ENOMEM;
4063 		goto free_all;
4064 	}
4065 
4066 	if (!c) {
4067 		c = outbuf_enc;
4068 		c_size = req->dst_len;
4069 	}
4070 
4071 	err = -E2BIG;
4072 	if (WARN_ON(c_size > PAGE_SIZE))
4073 		goto free_all;
4074 	memcpy(xbuf[0], c, c_size);
4075 
4076 	sg_init_one(&src, xbuf[0], c_size);
4077 	sg_init_one(&dst, outbuf_dec, out_len_max);
4078 	crypto_init_wait(&wait);
4079 	akcipher_request_set_crypt(req, &src, &dst, c_size, out_len_max);
4080 
4081 	err = crypto_wait_req(crypto_akcipher_decrypt(req), &wait);
4082 	if (err) {
4083 		pr_err("alg: akcipher: decrypt test failed. err %d\n", err);
4084 		goto free_all;
4085 	}
4086 	out_len = req->dst_len;
4087 	if (out_len < vecs->m_size) {
4088 		pr_err("alg: akcipher: decrypt test failed. Invalid output len %u\n",
4089 		       out_len);
4090 		err = -EINVAL;
4091 		goto free_all;
4092 	}
4093 	/* verify that decrypted message is equal to the original msg */
4094 	if (memchr_inv(outbuf_dec, 0, out_len - vecs->m_size) ||
4095 	    memcmp(vecs->m, outbuf_dec + out_len - vecs->m_size,
4096 		   vecs->m_size)) {
4097 		pr_err("alg: akcipher: decrypt test failed. Invalid output\n");
4098 		hexdump(outbuf_dec, out_len);
4099 		err = -EINVAL;
4100 	}
4101 free_all:
4102 	kfree(outbuf_dec);
4103 	kfree(outbuf_enc);
4104 free_req:
4105 	akcipher_request_free(req);
4106 free_xbuf:
4107 	testmgr_free_buf(xbuf);
4108 	return err;
4109 }
4110 
4111 static int test_akcipher(struct crypto_akcipher *tfm, const char *alg,
4112 			 const struct akcipher_testvec *vecs,
4113 			 unsigned int tcount)
4114 {
4115 	const char *algo =
4116 		crypto_tfm_alg_driver_name(crypto_akcipher_tfm(tfm));
4117 	int ret, i;
4118 
4119 	for (i = 0; i < tcount; i++) {
4120 		ret = test_akcipher_one(tfm, vecs++);
4121 		if (!ret)
4122 			continue;
4123 
4124 		pr_err("alg: akcipher: test %d failed for %s, err=%d\n",
4125 		       i + 1, algo, ret);
4126 		return ret;
4127 	}
4128 	return 0;
4129 }
4130 
4131 static int alg_test_akcipher(const struct alg_test_desc *desc,
4132 			     const char *driver, u32 type, u32 mask)
4133 {
4134 	struct crypto_akcipher *tfm;
4135 	int err = 0;
4136 
4137 	tfm = crypto_alloc_akcipher(driver, type, mask);
4138 	if (IS_ERR(tfm)) {
4139 		if (PTR_ERR(tfm) == -ENOENT)
4140 			return 0;
4141 		pr_err("alg: akcipher: Failed to load tfm for %s: %ld\n",
4142 		       driver, PTR_ERR(tfm));
4143 		return PTR_ERR(tfm);
4144 	}
4145 	if (desc->suite.akcipher.vecs)
4146 		err = test_akcipher(tfm, desc->alg, desc->suite.akcipher.vecs,
4147 				    desc->suite.akcipher.count);
4148 
4149 	crypto_free_akcipher(tfm);
4150 	return err;
4151 }
4152 
4153 static int test_sig_one(struct crypto_sig *tfm, const struct sig_testvec *vecs)
4154 {
4155 	u8 *ptr, *key __free(kfree);
4156 	int err, sig_size;
4157 
4158 	key = kmalloc(vecs->key_len + 2 * sizeof(u32) + vecs->param_len,
4159 		      GFP_KERNEL);
4160 	if (!key)
4161 		return -ENOMEM;
4162 
4163 	/* ecrdsa expects additional parameters appended to the key */
4164 	memcpy(key, vecs->key, vecs->key_len);
4165 	ptr = key + vecs->key_len;
4166 	ptr = test_pack_u32(ptr, vecs->algo);
4167 	ptr = test_pack_u32(ptr, vecs->param_len);
4168 	memcpy(ptr, vecs->params, vecs->param_len);
4169 
4170 	if (vecs->public_key_vec)
4171 		err = crypto_sig_set_pubkey(tfm, key, vecs->key_len);
4172 	else
4173 		err = crypto_sig_set_privkey(tfm, key, vecs->key_len);
4174 	if (err)
4175 		return err;
4176 
4177 	/*
4178 	 * Run asymmetric signature verification first
4179 	 * (which does not require a private key)
4180 	 */
4181 	err = crypto_sig_verify(tfm, vecs->c, vecs->c_size,
4182 				vecs->m, vecs->m_size);
4183 	if (err) {
4184 		pr_err("alg: sig: verify test failed: err %d\n", err);
4185 		return err;
4186 	}
4187 
4188 	/*
4189 	 * Don't invoke sign test (which requires a private key)
4190 	 * for vectors with only a public key.
4191 	 */
4192 	if (vecs->public_key_vec)
4193 		return 0;
4194 
4195 	sig_size = crypto_sig_maxsize(tfm);
4196 	if (sig_size < vecs->c_size) {
4197 		pr_err("alg: sig: invalid maxsize %u\n", sig_size);
4198 		return -EINVAL;
4199 	}
4200 
4201 	u8 *sig __free(kfree) = kzalloc(sig_size, GFP_KERNEL);
4202 	if (!sig)
4203 		return -ENOMEM;
4204 
4205 	/* Run asymmetric signature generation */
4206 	err = crypto_sig_sign(tfm, vecs->m, vecs->m_size, sig, sig_size);
4207 	if (err < 0) {
4208 		pr_err("alg: sig: sign test failed: err %d\n", err);
4209 		return err;
4210 	}
4211 
4212 	/* Verify that generated signature equals cooked signature */
4213 	if (err != vecs->c_size ||
4214 	    memcmp(sig, vecs->c, vecs->c_size) ||
4215 	    memchr_inv(sig + vecs->c_size, 0, sig_size - vecs->c_size)) {
4216 		pr_err("alg: sig: sign test failed: invalid output\n");
4217 		hexdump(sig, sig_size);
4218 		return -EINVAL;
4219 	}
4220 
4221 	return 0;
4222 }
4223 
4224 static int test_sig(struct crypto_sig *tfm, const char *alg,
4225 		    const struct sig_testvec *vecs, unsigned int tcount)
4226 {
4227 	const char *algo = crypto_tfm_alg_driver_name(crypto_sig_tfm(tfm));
4228 	int ret, i;
4229 
4230 	for (i = 0; i < tcount; i++) {
4231 		ret = test_sig_one(tfm, vecs++);
4232 		if (ret) {
4233 			pr_err("alg: sig: test %d failed for %s: err %d\n",
4234 			       i + 1, algo, ret);
4235 			return ret;
4236 		}
4237 	}
4238 	return 0;
4239 }
4240 
4241 static int alg_test_sig(const struct alg_test_desc *desc, const char *driver,
4242 			u32 type, u32 mask)
4243 {
4244 	struct crypto_sig *tfm;
4245 	int err = 0;
4246 
4247 	tfm = crypto_alloc_sig(driver, type, mask);
4248 	if (IS_ERR(tfm)) {
4249 		pr_err("alg: sig: Failed to load tfm for %s: %ld\n",
4250 		       driver, PTR_ERR(tfm));
4251 		return PTR_ERR(tfm);
4252 	}
4253 	if (desc->suite.sig.vecs)
4254 		err = test_sig(tfm, desc->alg, desc->suite.sig.vecs,
4255 			       desc->suite.sig.count);
4256 
4257 	crypto_free_sig(tfm);
4258 	return err;
4259 }
4260 
4261 static int alg_test_null(const struct alg_test_desc *desc,
4262 			     const char *driver, u32 type, u32 mask)
4263 {
4264 	return 0;
4265 }
4266 
4267 #define ____VECS(tv)	.vecs = tv, .count = ARRAY_SIZE(tv)
4268 #define __VECS(tv)	{ ____VECS(tv) }
4269 
4270 /* Please keep this list sorted by algorithm name. */
4271 static const struct alg_test_desc alg_test_descs[] = {
4272 	{
4273 		.alg = "adiantum(xchacha12,aes)",
4274 		.generic_driver = "adiantum(xchacha12-generic,aes-generic,nhpoly1305-generic)",
4275 		.test = alg_test_skcipher,
4276 		.suite = {
4277 			.cipher = __VECS(adiantum_xchacha12_aes_tv_template)
4278 		},
4279 	}, {
4280 		.alg = "adiantum(xchacha20,aes)",
4281 		.generic_driver = "adiantum(xchacha20-generic,aes-generic,nhpoly1305-generic)",
4282 		.test = alg_test_skcipher,
4283 		.suite = {
4284 			.cipher = __VECS(adiantum_xchacha20_aes_tv_template)
4285 		},
4286 	}, {
4287 		.alg = "aegis128",
4288 		.test = alg_test_aead,
4289 		.suite = {
4290 			.aead = __VECS(aegis128_tv_template)
4291 		}
4292 	}, {
4293 		.alg = "ansi_cprng",
4294 		.test = alg_test_cprng,
4295 		.suite = {
4296 			.cprng = __VECS(ansi_cprng_aes_tv_template)
4297 		}
4298 	}, {
4299 		.alg = "authenc(hmac(md5),ecb(cipher_null))",
4300 		.test = alg_test_aead,
4301 		.suite = {
4302 			.aead = __VECS(hmac_md5_ecb_cipher_null_tv_template)
4303 		}
4304 	}, {
4305 		.alg = "authenc(hmac(sha1),cbc(aes))",
4306 		.test = alg_test_aead,
4307 		.fips_allowed = 1,
4308 		.suite = {
4309 			.aead = __VECS(hmac_sha1_aes_cbc_tv_temp)
4310 		}
4311 	}, {
4312 		.alg = "authenc(hmac(sha1),cbc(des))",
4313 		.test = alg_test_aead,
4314 		.suite = {
4315 			.aead = __VECS(hmac_sha1_des_cbc_tv_temp)
4316 		}
4317 	}, {
4318 		.alg = "authenc(hmac(sha1),cbc(des3_ede))",
4319 		.test = alg_test_aead,
4320 		.suite = {
4321 			.aead = __VECS(hmac_sha1_des3_ede_cbc_tv_temp)
4322 		}
4323 	}, {
4324 		.alg = "authenc(hmac(sha1),ctr(aes))",
4325 		.test = alg_test_null,
4326 		.fips_allowed = 1,
4327 	}, {
4328 		.alg = "authenc(hmac(sha1),ecb(cipher_null))",
4329 		.test = alg_test_aead,
4330 		.suite = {
4331 			.aead = __VECS(hmac_sha1_ecb_cipher_null_tv_temp)
4332 		}
4333 	}, {
4334 		.alg = "authenc(hmac(sha1),rfc3686(ctr(aes)))",
4335 		.test = alg_test_null,
4336 		.fips_allowed = 1,
4337 	}, {
4338 		.alg = "authenc(hmac(sha224),cbc(des))",
4339 		.test = alg_test_aead,
4340 		.suite = {
4341 			.aead = __VECS(hmac_sha224_des_cbc_tv_temp)
4342 		}
4343 	}, {
4344 		.alg = "authenc(hmac(sha224),cbc(des3_ede))",
4345 		.test = alg_test_aead,
4346 		.suite = {
4347 			.aead = __VECS(hmac_sha224_des3_ede_cbc_tv_temp)
4348 		}
4349 	}, {
4350 		.alg = "authenc(hmac(sha256),cbc(aes))",
4351 		.test = alg_test_aead,
4352 		.fips_allowed = 1,
4353 		.suite = {
4354 			.aead = __VECS(hmac_sha256_aes_cbc_tv_temp)
4355 		}
4356 	}, {
4357 		.alg = "authenc(hmac(sha256),cbc(des))",
4358 		.test = alg_test_aead,
4359 		.suite = {
4360 			.aead = __VECS(hmac_sha256_des_cbc_tv_temp)
4361 		}
4362 	}, {
4363 		.alg = "authenc(hmac(sha256),cbc(des3_ede))",
4364 		.test = alg_test_aead,
4365 		.suite = {
4366 			.aead = __VECS(hmac_sha256_des3_ede_cbc_tv_temp)
4367 		}
4368 	}, {
4369 		.alg = "authenc(hmac(sha256),ctr(aes))",
4370 		.test = alg_test_null,
4371 		.fips_allowed = 1,
4372 	}, {
4373 		.alg = "authenc(hmac(sha256),cts(cbc(aes)))",
4374 		.test = alg_test_aead,
4375 		.suite = {
4376 			.aead = __VECS(krb5_test_aes128_cts_hmac_sha256_128)
4377 		}
4378 	}, {
4379 		.alg = "authenc(hmac(sha256),rfc3686(ctr(aes)))",
4380 		.test = alg_test_null,
4381 		.fips_allowed = 1,
4382 	}, {
4383 		.alg = "authenc(hmac(sha384),cbc(des))",
4384 		.test = alg_test_aead,
4385 		.suite = {
4386 			.aead = __VECS(hmac_sha384_des_cbc_tv_temp)
4387 		}
4388 	}, {
4389 		.alg = "authenc(hmac(sha384),cbc(des3_ede))",
4390 		.test = alg_test_aead,
4391 		.suite = {
4392 			.aead = __VECS(hmac_sha384_des3_ede_cbc_tv_temp)
4393 		}
4394 	}, {
4395 		.alg = "authenc(hmac(sha384),ctr(aes))",
4396 		.test = alg_test_null,
4397 		.fips_allowed = 1,
4398 	}, {
4399 		.alg = "authenc(hmac(sha384),cts(cbc(aes)))",
4400 		.test = alg_test_aead,
4401 		.suite = {
4402 			.aead = __VECS(krb5_test_aes256_cts_hmac_sha384_192)
4403 		}
4404 	}, {
4405 		.alg = "authenc(hmac(sha384),rfc3686(ctr(aes)))",
4406 		.test = alg_test_null,
4407 		.fips_allowed = 1,
4408 	}, {
4409 		.alg = "authenc(hmac(sha512),cbc(aes))",
4410 		.fips_allowed = 1,
4411 		.test = alg_test_aead,
4412 		.suite = {
4413 			.aead = __VECS(hmac_sha512_aes_cbc_tv_temp)
4414 		}
4415 	}, {
4416 		.alg = "authenc(hmac(sha512),cbc(des))",
4417 		.test = alg_test_aead,
4418 		.suite = {
4419 			.aead = __VECS(hmac_sha512_des_cbc_tv_temp)
4420 		}
4421 	}, {
4422 		.alg = "authenc(hmac(sha512),cbc(des3_ede))",
4423 		.test = alg_test_aead,
4424 		.suite = {
4425 			.aead = __VECS(hmac_sha512_des3_ede_cbc_tv_temp)
4426 		}
4427 	}, {
4428 		.alg = "authenc(hmac(sha512),ctr(aes))",
4429 		.test = alg_test_null,
4430 		.fips_allowed = 1,
4431 	}, {
4432 		.alg = "authenc(hmac(sha512),rfc3686(ctr(aes)))",
4433 		.test = alg_test_null,
4434 		.fips_allowed = 1,
4435 	}, {
4436 		.alg = "blake2b-160",
4437 		.test = alg_test_hash,
4438 		.fips_allowed = 0,
4439 		.suite = {
4440 			.hash = __VECS(blake2b_160_tv_template)
4441 		}
4442 	}, {
4443 		.alg = "blake2b-256",
4444 		.test = alg_test_hash,
4445 		.fips_allowed = 0,
4446 		.suite = {
4447 			.hash = __VECS(blake2b_256_tv_template)
4448 		}
4449 	}, {
4450 		.alg = "blake2b-384",
4451 		.test = alg_test_hash,
4452 		.fips_allowed = 0,
4453 		.suite = {
4454 			.hash = __VECS(blake2b_384_tv_template)
4455 		}
4456 	}, {
4457 		.alg = "blake2b-512",
4458 		.test = alg_test_hash,
4459 		.fips_allowed = 0,
4460 		.suite = {
4461 			.hash = __VECS(blake2b_512_tv_template)
4462 		}
4463 	}, {
4464 		.alg = "cbc(aes)",
4465 		.test = alg_test_skcipher,
4466 		.fips_allowed = 1,
4467 		.suite = {
4468 			.cipher = __VECS(aes_cbc_tv_template)
4469 		},
4470 	}, {
4471 		.alg = "cbc(anubis)",
4472 		.test = alg_test_skcipher,
4473 		.suite = {
4474 			.cipher = __VECS(anubis_cbc_tv_template)
4475 		},
4476 	}, {
4477 		.alg = "cbc(aria)",
4478 		.test = alg_test_skcipher,
4479 		.suite = {
4480 			.cipher = __VECS(aria_cbc_tv_template)
4481 		},
4482 	}, {
4483 		.alg = "cbc(blowfish)",
4484 		.test = alg_test_skcipher,
4485 		.suite = {
4486 			.cipher = __VECS(bf_cbc_tv_template)
4487 		},
4488 	}, {
4489 		.alg = "cbc(camellia)",
4490 		.test = alg_test_skcipher,
4491 		.suite = {
4492 			.cipher = __VECS(camellia_cbc_tv_template)
4493 		},
4494 	}, {
4495 		.alg = "cbc(cast5)",
4496 		.test = alg_test_skcipher,
4497 		.suite = {
4498 			.cipher = __VECS(cast5_cbc_tv_template)
4499 		},
4500 	}, {
4501 		.alg = "cbc(cast6)",
4502 		.test = alg_test_skcipher,
4503 		.suite = {
4504 			.cipher = __VECS(cast6_cbc_tv_template)
4505 		},
4506 	}, {
4507 		.alg = "cbc(des)",
4508 		.test = alg_test_skcipher,
4509 		.suite = {
4510 			.cipher = __VECS(des_cbc_tv_template)
4511 		},
4512 	}, {
4513 		.alg = "cbc(des3_ede)",
4514 		.test = alg_test_skcipher,
4515 		.suite = {
4516 			.cipher = __VECS(des3_ede_cbc_tv_template)
4517 		},
4518 	}, {
4519 		/* Same as cbc(aes) except the key is stored in
4520 		 * hardware secure memory which we reference by index
4521 		 */
4522 		.alg = "cbc(paes)",
4523 		.test = alg_test_null,
4524 		.fips_allowed = 1,
4525 	}, {
4526 		/* Same as cbc(sm4) except the key is stored in
4527 		 * hardware secure memory which we reference by index
4528 		 */
4529 		.alg = "cbc(psm4)",
4530 		.test = alg_test_null,
4531 	}, {
4532 		.alg = "cbc(serpent)",
4533 		.test = alg_test_skcipher,
4534 		.suite = {
4535 			.cipher = __VECS(serpent_cbc_tv_template)
4536 		},
4537 	}, {
4538 		.alg = "cbc(sm4)",
4539 		.test = alg_test_skcipher,
4540 		.suite = {
4541 			.cipher = __VECS(sm4_cbc_tv_template)
4542 		}
4543 	}, {
4544 		.alg = "cbc(twofish)",
4545 		.test = alg_test_skcipher,
4546 		.suite = {
4547 			.cipher = __VECS(tf_cbc_tv_template)
4548 		},
4549 	}, {
4550 #if IS_ENABLED(CONFIG_CRYPTO_PAES_S390)
4551 		.alg = "cbc-paes-s390",
4552 		.fips_allowed = 1,
4553 		.test = alg_test_skcipher,
4554 		.suite = {
4555 			.cipher = __VECS(aes_cbc_tv_template)
4556 		}
4557 	}, {
4558 #endif
4559 		.alg = "cbcmac(aes)",
4560 		.test = alg_test_hash,
4561 		.suite = {
4562 			.hash = __VECS(aes_cbcmac_tv_template)
4563 		}
4564 	}, {
4565 		.alg = "cbcmac(sm4)",
4566 		.test = alg_test_hash,
4567 		.suite = {
4568 			.hash = __VECS(sm4_cbcmac_tv_template)
4569 		}
4570 	}, {
4571 		.alg = "ccm(aes)",
4572 		.generic_driver = "ccm_base(ctr(aes-generic),cbcmac(aes-generic))",
4573 		.test = alg_test_aead,
4574 		.fips_allowed = 1,
4575 		.suite = {
4576 			.aead = {
4577 				____VECS(aes_ccm_tv_template),
4578 				.einval_allowed = 1,
4579 			}
4580 		}
4581 	}, {
4582 		.alg = "ccm(sm4)",
4583 		.generic_driver = "ccm_base(ctr(sm4-generic),cbcmac(sm4-generic))",
4584 		.test = alg_test_aead,
4585 		.suite = {
4586 			.aead = {
4587 				____VECS(sm4_ccm_tv_template),
4588 				.einval_allowed = 1,
4589 			}
4590 		}
4591 	}, {
4592 		.alg = "chacha20",
4593 		.test = alg_test_skcipher,
4594 		.suite = {
4595 			.cipher = __VECS(chacha20_tv_template)
4596 		},
4597 	}, {
4598 		.alg = "cmac(aes)",
4599 		.fips_allowed = 1,
4600 		.test = alg_test_hash,
4601 		.suite = {
4602 			.hash = __VECS(aes_cmac128_tv_template)
4603 		}
4604 	}, {
4605 		.alg = "cmac(camellia)",
4606 		.test = alg_test_hash,
4607 		.suite = {
4608 			.hash = __VECS(camellia_cmac128_tv_template)
4609 		}
4610 	}, {
4611 		.alg = "cmac(des3_ede)",
4612 		.test = alg_test_hash,
4613 		.suite = {
4614 			.hash = __VECS(des3_ede_cmac64_tv_template)
4615 		}
4616 	}, {
4617 		.alg = "cmac(sm4)",
4618 		.test = alg_test_hash,
4619 		.suite = {
4620 			.hash = __VECS(sm4_cmac128_tv_template)
4621 		}
4622 	}, {
4623 		.alg = "crc32",
4624 		.test = alg_test_hash,
4625 		.fips_allowed = 1,
4626 		.suite = {
4627 			.hash = __VECS(crc32_tv_template)
4628 		}
4629 	}, {
4630 		.alg = "crc32c",
4631 		.test = alg_test_crc32c,
4632 		.fips_allowed = 1,
4633 		.suite = {
4634 			.hash = __VECS(crc32c_tv_template)
4635 		}
4636 	}, {
4637 		.alg = "ctr(aes)",
4638 		.test = alg_test_skcipher,
4639 		.fips_allowed = 1,
4640 		.suite = {
4641 			.cipher = __VECS(aes_ctr_tv_template)
4642 		}
4643 	}, {
4644 		.alg = "ctr(aria)",
4645 		.test = alg_test_skcipher,
4646 		.suite = {
4647 			.cipher = __VECS(aria_ctr_tv_template)
4648 		}
4649 	}, {
4650 		.alg = "ctr(blowfish)",
4651 		.test = alg_test_skcipher,
4652 		.suite = {
4653 			.cipher = __VECS(bf_ctr_tv_template)
4654 		}
4655 	}, {
4656 		.alg = "ctr(camellia)",
4657 		.test = alg_test_skcipher,
4658 		.suite = {
4659 			.cipher = __VECS(camellia_ctr_tv_template)
4660 		}
4661 	}, {
4662 		.alg = "ctr(cast5)",
4663 		.test = alg_test_skcipher,
4664 		.suite = {
4665 			.cipher = __VECS(cast5_ctr_tv_template)
4666 		}
4667 	}, {
4668 		.alg = "ctr(cast6)",
4669 		.test = alg_test_skcipher,
4670 		.suite = {
4671 			.cipher = __VECS(cast6_ctr_tv_template)
4672 		}
4673 	}, {
4674 		.alg = "ctr(des)",
4675 		.test = alg_test_skcipher,
4676 		.suite = {
4677 			.cipher = __VECS(des_ctr_tv_template)
4678 		}
4679 	}, {
4680 		.alg = "ctr(des3_ede)",
4681 		.test = alg_test_skcipher,
4682 		.suite = {
4683 			.cipher = __VECS(des3_ede_ctr_tv_template)
4684 		}
4685 	}, {
4686 		/* Same as ctr(aes) except the key is stored in
4687 		 * hardware secure memory which we reference by index
4688 		 */
4689 		.alg = "ctr(paes)",
4690 		.test = alg_test_null,
4691 		.fips_allowed = 1,
4692 	}, {
4693 
4694 		/* Same as ctr(sm4) except the key is stored in
4695 		 * hardware secure memory which we reference by index
4696 		 */
4697 		.alg = "ctr(psm4)",
4698 		.test = alg_test_null,
4699 	}, {
4700 		.alg = "ctr(serpent)",
4701 		.test = alg_test_skcipher,
4702 		.suite = {
4703 			.cipher = __VECS(serpent_ctr_tv_template)
4704 		}
4705 	}, {
4706 		.alg = "ctr(sm4)",
4707 		.test = alg_test_skcipher,
4708 		.suite = {
4709 			.cipher = __VECS(sm4_ctr_tv_template)
4710 		}
4711 	}, {
4712 		.alg = "ctr(twofish)",
4713 		.test = alg_test_skcipher,
4714 		.suite = {
4715 			.cipher = __VECS(tf_ctr_tv_template)
4716 		}
4717 	}, {
4718 #if IS_ENABLED(CONFIG_CRYPTO_PAES_S390)
4719 		.alg = "ctr-paes-s390",
4720 		.fips_allowed = 1,
4721 		.test = alg_test_skcipher,
4722 		.suite = {
4723 			.cipher = __VECS(aes_ctr_tv_template)
4724 		}
4725 	}, {
4726 #endif
4727 		.alg = "cts(cbc(aes))",
4728 		.test = alg_test_skcipher,
4729 		.fips_allowed = 1,
4730 		.suite = {
4731 			.cipher = __VECS(cts_mode_tv_template)
4732 		}
4733 	}, {
4734 		/* Same as cts(cbc((aes)) except the key is stored in
4735 		 * hardware secure memory which we reference by index
4736 		 */
4737 		.alg = "cts(cbc(paes))",
4738 		.test = alg_test_null,
4739 		.fips_allowed = 1,
4740 	}, {
4741 		.alg = "cts(cbc(sm4))",
4742 		.test = alg_test_skcipher,
4743 		.suite = {
4744 			.cipher = __VECS(sm4_cts_tv_template)
4745 		}
4746 	}, {
4747 		.alg = "curve25519",
4748 		.test = alg_test_kpp,
4749 		.suite = {
4750 			.kpp = __VECS(curve25519_tv_template)
4751 		}
4752 	}, {
4753 		.alg = "deflate",
4754 		.test = alg_test_comp,
4755 		.fips_allowed = 1,
4756 		.suite = {
4757 			.comp = {
4758 				.comp = __VECS(deflate_comp_tv_template),
4759 				.decomp = __VECS(deflate_decomp_tv_template)
4760 			}
4761 		}
4762 	}, {
4763 		.alg = "deflate-iaa",
4764 		.test = alg_test_comp,
4765 		.fips_allowed = 1,
4766 		.suite = {
4767 			.comp = {
4768 				.comp = __VECS(deflate_comp_tv_template),
4769 				.decomp = __VECS(deflate_decomp_tv_template)
4770 			}
4771 		}
4772 	}, {
4773 		.alg = "dh",
4774 		.test = alg_test_kpp,
4775 		.suite = {
4776 			.kpp = __VECS(dh_tv_template)
4777 		}
4778 	}, {
4779 		.alg = "digest_null",
4780 		.test = alg_test_null,
4781 	}, {
4782 		.alg = "drbg_nopr_ctr_aes128",
4783 		.test = alg_test_drbg,
4784 		.fips_allowed = 1,
4785 		.suite = {
4786 			.drbg = __VECS(drbg_nopr_ctr_aes128_tv_template)
4787 		}
4788 	}, {
4789 		.alg = "drbg_nopr_ctr_aes192",
4790 		.test = alg_test_drbg,
4791 		.fips_allowed = 1,
4792 		.suite = {
4793 			.drbg = __VECS(drbg_nopr_ctr_aes192_tv_template)
4794 		}
4795 	}, {
4796 		.alg = "drbg_nopr_ctr_aes256",
4797 		.test = alg_test_drbg,
4798 		.fips_allowed = 1,
4799 		.suite = {
4800 			.drbg = __VECS(drbg_nopr_ctr_aes256_tv_template)
4801 		}
4802 	}, {
4803 		.alg = "drbg_nopr_hmac_sha256",
4804 		.test = alg_test_drbg,
4805 		.fips_allowed = 1,
4806 		.suite = {
4807 			.drbg = __VECS(drbg_nopr_hmac_sha256_tv_template)
4808 		}
4809 	}, {
4810 		/*
4811 		 * There is no need to specifically test the DRBG with every
4812 		 * backend cipher -- covered by drbg_nopr_hmac_sha512 test
4813 		 */
4814 		.alg = "drbg_nopr_hmac_sha384",
4815 		.test = alg_test_null,
4816 	}, {
4817 		.alg = "drbg_nopr_hmac_sha512",
4818 		.test = alg_test_drbg,
4819 		.fips_allowed = 1,
4820 		.suite = {
4821 			.drbg = __VECS(drbg_nopr_hmac_sha512_tv_template)
4822 		}
4823 	}, {
4824 		.alg = "drbg_nopr_sha256",
4825 		.test = alg_test_drbg,
4826 		.fips_allowed = 1,
4827 		.suite = {
4828 			.drbg = __VECS(drbg_nopr_sha256_tv_template)
4829 		}
4830 	}, {
4831 		/* covered by drbg_nopr_sha256 test */
4832 		.alg = "drbg_nopr_sha384",
4833 		.test = alg_test_null,
4834 	}, {
4835 		.alg = "drbg_nopr_sha512",
4836 		.fips_allowed = 1,
4837 		.test = alg_test_null,
4838 	}, {
4839 		.alg = "drbg_pr_ctr_aes128",
4840 		.test = alg_test_drbg,
4841 		.fips_allowed = 1,
4842 		.suite = {
4843 			.drbg = __VECS(drbg_pr_ctr_aes128_tv_template)
4844 		}
4845 	}, {
4846 		/* covered by drbg_pr_ctr_aes128 test */
4847 		.alg = "drbg_pr_ctr_aes192",
4848 		.fips_allowed = 1,
4849 		.test = alg_test_null,
4850 	}, {
4851 		.alg = "drbg_pr_ctr_aes256",
4852 		.fips_allowed = 1,
4853 		.test = alg_test_null,
4854 	}, {
4855 		.alg = "drbg_pr_hmac_sha256",
4856 		.test = alg_test_drbg,
4857 		.fips_allowed = 1,
4858 		.suite = {
4859 			.drbg = __VECS(drbg_pr_hmac_sha256_tv_template)
4860 		}
4861 	}, {
4862 		/* covered by drbg_pr_hmac_sha256 test */
4863 		.alg = "drbg_pr_hmac_sha384",
4864 		.test = alg_test_null,
4865 	}, {
4866 		.alg = "drbg_pr_hmac_sha512",
4867 		.test = alg_test_null,
4868 		.fips_allowed = 1,
4869 	}, {
4870 		.alg = "drbg_pr_sha256",
4871 		.test = alg_test_drbg,
4872 		.fips_allowed = 1,
4873 		.suite = {
4874 			.drbg = __VECS(drbg_pr_sha256_tv_template)
4875 		}
4876 	}, {
4877 		/* covered by drbg_pr_sha256 test */
4878 		.alg = "drbg_pr_sha384",
4879 		.test = alg_test_null,
4880 	}, {
4881 		.alg = "drbg_pr_sha512",
4882 		.fips_allowed = 1,
4883 		.test = alg_test_null,
4884 	}, {
4885 		.alg = "ecb(aes)",
4886 		.test = alg_test_skcipher,
4887 		.fips_allowed = 1,
4888 		.suite = {
4889 			.cipher = __VECS(aes_tv_template)
4890 		}
4891 	}, {
4892 		.alg = "ecb(anubis)",
4893 		.test = alg_test_skcipher,
4894 		.suite = {
4895 			.cipher = __VECS(anubis_tv_template)
4896 		}
4897 	}, {
4898 		.alg = "ecb(arc4)",
4899 		.generic_driver = "arc4-generic",
4900 		.test = alg_test_skcipher,
4901 		.suite = {
4902 			.cipher = __VECS(arc4_tv_template)
4903 		}
4904 	}, {
4905 		.alg = "ecb(aria)",
4906 		.test = alg_test_skcipher,
4907 		.suite = {
4908 			.cipher = __VECS(aria_tv_template)
4909 		}
4910 	}, {
4911 		.alg = "ecb(blowfish)",
4912 		.test = alg_test_skcipher,
4913 		.suite = {
4914 			.cipher = __VECS(bf_tv_template)
4915 		}
4916 	}, {
4917 		.alg = "ecb(camellia)",
4918 		.test = alg_test_skcipher,
4919 		.suite = {
4920 			.cipher = __VECS(camellia_tv_template)
4921 		}
4922 	}, {
4923 		.alg = "ecb(cast5)",
4924 		.test = alg_test_skcipher,
4925 		.suite = {
4926 			.cipher = __VECS(cast5_tv_template)
4927 		}
4928 	}, {
4929 		.alg = "ecb(cast6)",
4930 		.test = alg_test_skcipher,
4931 		.suite = {
4932 			.cipher = __VECS(cast6_tv_template)
4933 		}
4934 	}, {
4935 		.alg = "ecb(cipher_null)",
4936 		.test = alg_test_null,
4937 		.fips_allowed = 1,
4938 	}, {
4939 		.alg = "ecb(des)",
4940 		.test = alg_test_skcipher,
4941 		.suite = {
4942 			.cipher = __VECS(des_tv_template)
4943 		}
4944 	}, {
4945 		.alg = "ecb(des3_ede)",
4946 		.test = alg_test_skcipher,
4947 		.suite = {
4948 			.cipher = __VECS(des3_ede_tv_template)
4949 		}
4950 	}, {
4951 		.alg = "ecb(fcrypt)",
4952 		.test = alg_test_skcipher,
4953 		.suite = {
4954 			.cipher = {
4955 				.vecs = fcrypt_pcbc_tv_template,
4956 				.count = 1
4957 			}
4958 		}
4959 	}, {
4960 		.alg = "ecb(khazad)",
4961 		.test = alg_test_skcipher,
4962 		.suite = {
4963 			.cipher = __VECS(khazad_tv_template)
4964 		}
4965 	}, {
4966 		/* Same as ecb(aes) except the key is stored in
4967 		 * hardware secure memory which we reference by index
4968 		 */
4969 		.alg = "ecb(paes)",
4970 		.test = alg_test_null,
4971 		.fips_allowed = 1,
4972 	}, {
4973 		.alg = "ecb(seed)",
4974 		.test = alg_test_skcipher,
4975 		.suite = {
4976 			.cipher = __VECS(seed_tv_template)
4977 		}
4978 	}, {
4979 		.alg = "ecb(serpent)",
4980 		.test = alg_test_skcipher,
4981 		.suite = {
4982 			.cipher = __VECS(serpent_tv_template)
4983 		}
4984 	}, {
4985 		.alg = "ecb(sm4)",
4986 		.test = alg_test_skcipher,
4987 		.suite = {
4988 			.cipher = __VECS(sm4_tv_template)
4989 		}
4990 	}, {
4991 		.alg = "ecb(tea)",
4992 		.test = alg_test_skcipher,
4993 		.suite = {
4994 			.cipher = __VECS(tea_tv_template)
4995 		}
4996 	}, {
4997 		.alg = "ecb(twofish)",
4998 		.test = alg_test_skcipher,
4999 		.suite = {
5000 			.cipher = __VECS(tf_tv_template)
5001 		}
5002 	}, {
5003 		.alg = "ecb(xeta)",
5004 		.test = alg_test_skcipher,
5005 		.suite = {
5006 			.cipher = __VECS(xeta_tv_template)
5007 		}
5008 	}, {
5009 		.alg = "ecb(xtea)",
5010 		.test = alg_test_skcipher,
5011 		.suite = {
5012 			.cipher = __VECS(xtea_tv_template)
5013 		}
5014 	}, {
5015 #if IS_ENABLED(CONFIG_CRYPTO_PAES_S390)
5016 		.alg = "ecb-paes-s390",
5017 		.fips_allowed = 1,
5018 		.test = alg_test_skcipher,
5019 		.suite = {
5020 			.cipher = __VECS(aes_tv_template)
5021 		}
5022 	}, {
5023 #endif
5024 		.alg = "ecdh-nist-p192",
5025 		.test = alg_test_kpp,
5026 		.suite = {
5027 			.kpp = __VECS(ecdh_p192_tv_template)
5028 		}
5029 	}, {
5030 		.alg = "ecdh-nist-p256",
5031 		.test = alg_test_kpp,
5032 		.fips_allowed = 1,
5033 		.suite = {
5034 			.kpp = __VECS(ecdh_p256_tv_template)
5035 		}
5036 	}, {
5037 		.alg = "ecdh-nist-p384",
5038 		.test = alg_test_kpp,
5039 		.fips_allowed = 1,
5040 		.suite = {
5041 			.kpp = __VECS(ecdh_p384_tv_template)
5042 		}
5043 	}, {
5044 		.alg = "ecdsa-nist-p192",
5045 		.test = alg_test_sig,
5046 		.suite = {
5047 			.sig = __VECS(ecdsa_nist_p192_tv_template)
5048 		}
5049 	}, {
5050 		.alg = "ecdsa-nist-p256",
5051 		.test = alg_test_sig,
5052 		.fips_allowed = 1,
5053 		.suite = {
5054 			.sig = __VECS(ecdsa_nist_p256_tv_template)
5055 		}
5056 	}, {
5057 		.alg = "ecdsa-nist-p384",
5058 		.test = alg_test_sig,
5059 		.fips_allowed = 1,
5060 		.suite = {
5061 			.sig = __VECS(ecdsa_nist_p384_tv_template)
5062 		}
5063 	}, {
5064 		.alg = "ecdsa-nist-p521",
5065 		.test = alg_test_sig,
5066 		.fips_allowed = 1,
5067 		.suite = {
5068 			.sig = __VECS(ecdsa_nist_p521_tv_template)
5069 		}
5070 	}, {
5071 		.alg = "ecrdsa",
5072 		.test = alg_test_sig,
5073 		.suite = {
5074 			.sig = __VECS(ecrdsa_tv_template)
5075 		}
5076 	}, {
5077 		.alg = "essiv(authenc(hmac(sha256),cbc(aes)),sha256)",
5078 		.test = alg_test_aead,
5079 		.fips_allowed = 1,
5080 		.suite = {
5081 			.aead = __VECS(essiv_hmac_sha256_aes_cbc_tv_temp)
5082 		}
5083 	}, {
5084 		.alg = "essiv(cbc(aes),sha256)",
5085 		.test = alg_test_skcipher,
5086 		.fips_allowed = 1,
5087 		.suite = {
5088 			.cipher = __VECS(essiv_aes_cbc_tv_template)
5089 		}
5090 	}, {
5091 #if IS_ENABLED(CONFIG_CRYPTO_DH_RFC7919_GROUPS)
5092 		.alg = "ffdhe2048(dh)",
5093 		.test = alg_test_kpp,
5094 		.fips_allowed = 1,
5095 		.suite = {
5096 			.kpp = __VECS(ffdhe2048_dh_tv_template)
5097 		}
5098 	}, {
5099 		.alg = "ffdhe3072(dh)",
5100 		.test = alg_test_kpp,
5101 		.fips_allowed = 1,
5102 		.suite = {
5103 			.kpp = __VECS(ffdhe3072_dh_tv_template)
5104 		}
5105 	}, {
5106 		.alg = "ffdhe4096(dh)",
5107 		.test = alg_test_kpp,
5108 		.fips_allowed = 1,
5109 		.suite = {
5110 			.kpp = __VECS(ffdhe4096_dh_tv_template)
5111 		}
5112 	}, {
5113 		.alg = "ffdhe6144(dh)",
5114 		.test = alg_test_kpp,
5115 		.fips_allowed = 1,
5116 		.suite = {
5117 			.kpp = __VECS(ffdhe6144_dh_tv_template)
5118 		}
5119 	}, {
5120 		.alg = "ffdhe8192(dh)",
5121 		.test = alg_test_kpp,
5122 		.fips_allowed = 1,
5123 		.suite = {
5124 			.kpp = __VECS(ffdhe8192_dh_tv_template)
5125 		}
5126 	}, {
5127 #endif /* CONFIG_CRYPTO_DH_RFC7919_GROUPS */
5128 		.alg = "gcm(aes)",
5129 		.generic_driver = "gcm_base(ctr(aes-generic),ghash-generic)",
5130 		.test = alg_test_aead,
5131 		.fips_allowed = 1,
5132 		.suite = {
5133 			.aead = __VECS(aes_gcm_tv_template)
5134 		}
5135 	}, {
5136 		.alg = "gcm(aria)",
5137 		.generic_driver = "gcm_base(ctr(aria-generic),ghash-generic)",
5138 		.test = alg_test_aead,
5139 		.suite = {
5140 			.aead = __VECS(aria_gcm_tv_template)
5141 		}
5142 	}, {
5143 		.alg = "gcm(sm4)",
5144 		.generic_driver = "gcm_base(ctr(sm4-generic),ghash-generic)",
5145 		.test = alg_test_aead,
5146 		.suite = {
5147 			.aead = __VECS(sm4_gcm_tv_template)
5148 		}
5149 	}, {
5150 		.alg = "ghash",
5151 		.test = alg_test_hash,
5152 		.suite = {
5153 			.hash = __VECS(ghash_tv_template)
5154 		}
5155 	}, {
5156 		.alg = "hctr2(aes)",
5157 		.generic_driver =
5158 		    "hctr2_base(xctr(aes-generic),polyval-generic)",
5159 		.test = alg_test_skcipher,
5160 		.suite = {
5161 			.cipher = __VECS(aes_hctr2_tv_template)
5162 		}
5163 	}, {
5164 		.alg = "hmac(md5)",
5165 		.test = alg_test_hash,
5166 		.suite = {
5167 			.hash = __VECS(hmac_md5_tv_template)
5168 		}
5169 	}, {
5170 		.alg = "hmac(rmd160)",
5171 		.test = alg_test_hash,
5172 		.suite = {
5173 			.hash = __VECS(hmac_rmd160_tv_template)
5174 		}
5175 	}, {
5176 		.alg = "hmac(sha1)",
5177 		.test = alg_test_hash,
5178 		.fips_allowed = 1,
5179 		.suite = {
5180 			.hash = __VECS(hmac_sha1_tv_template)
5181 		}
5182 	}, {
5183 		.alg = "hmac(sha224)",
5184 		.test = alg_test_hash,
5185 		.fips_allowed = 1,
5186 		.suite = {
5187 			.hash = __VECS(hmac_sha224_tv_template)
5188 		}
5189 	}, {
5190 		.alg = "hmac(sha256)",
5191 		.test = alg_test_hash,
5192 		.fips_allowed = 1,
5193 		.suite = {
5194 			.hash = __VECS(hmac_sha256_tv_template)
5195 		}
5196 	}, {
5197 		.alg = "hmac(sha3-224)",
5198 		.test = alg_test_hash,
5199 		.fips_allowed = 1,
5200 		.suite = {
5201 			.hash = __VECS(hmac_sha3_224_tv_template)
5202 		}
5203 	}, {
5204 		.alg = "hmac(sha3-256)",
5205 		.test = alg_test_hash,
5206 		.fips_allowed = 1,
5207 		.suite = {
5208 			.hash = __VECS(hmac_sha3_256_tv_template)
5209 		}
5210 	}, {
5211 		.alg = "hmac(sha3-384)",
5212 		.test = alg_test_hash,
5213 		.fips_allowed = 1,
5214 		.suite = {
5215 			.hash = __VECS(hmac_sha3_384_tv_template)
5216 		}
5217 	}, {
5218 		.alg = "hmac(sha3-512)",
5219 		.test = alg_test_hash,
5220 		.fips_allowed = 1,
5221 		.suite = {
5222 			.hash = __VECS(hmac_sha3_512_tv_template)
5223 		}
5224 	}, {
5225 		.alg = "hmac(sha384)",
5226 		.test = alg_test_hash,
5227 		.fips_allowed = 1,
5228 		.suite = {
5229 			.hash = __VECS(hmac_sha384_tv_template)
5230 		}
5231 	}, {
5232 		.alg = "hmac(sha512)",
5233 		.test = alg_test_hash,
5234 		.fips_allowed = 1,
5235 		.suite = {
5236 			.hash = __VECS(hmac_sha512_tv_template)
5237 		}
5238 	}, {
5239 		.alg = "hmac(sm3)",
5240 		.test = alg_test_hash,
5241 		.suite = {
5242 			.hash = __VECS(hmac_sm3_tv_template)
5243 		}
5244 	}, {
5245 		.alg = "hmac(streebog256)",
5246 		.test = alg_test_hash,
5247 		.suite = {
5248 			.hash = __VECS(hmac_streebog256_tv_template)
5249 		}
5250 	}, {
5251 		.alg = "hmac(streebog512)",
5252 		.test = alg_test_hash,
5253 		.suite = {
5254 			.hash = __VECS(hmac_streebog512_tv_template)
5255 		}
5256 	}, {
5257 		.alg = "jitterentropy_rng",
5258 		.fips_allowed = 1,
5259 		.test = alg_test_null,
5260 	}, {
5261 		.alg = "krb5enc(cmac(camellia),cts(cbc(camellia)))",
5262 		.test = alg_test_aead,
5263 		.suite.aead = __VECS(krb5_test_camellia_cts_cmac)
5264 	}, {
5265 		.alg = "lrw(aes)",
5266 		.generic_driver = "lrw(ecb(aes-generic))",
5267 		.test = alg_test_skcipher,
5268 		.suite = {
5269 			.cipher = __VECS(aes_lrw_tv_template)
5270 		}
5271 	}, {
5272 		.alg = "lrw(camellia)",
5273 		.generic_driver = "lrw(ecb(camellia-generic))",
5274 		.test = alg_test_skcipher,
5275 		.suite = {
5276 			.cipher = __VECS(camellia_lrw_tv_template)
5277 		}
5278 	}, {
5279 		.alg = "lrw(cast6)",
5280 		.generic_driver = "lrw(ecb(cast6-generic))",
5281 		.test = alg_test_skcipher,
5282 		.suite = {
5283 			.cipher = __VECS(cast6_lrw_tv_template)
5284 		}
5285 	}, {
5286 		.alg = "lrw(serpent)",
5287 		.generic_driver = "lrw(ecb(serpent-generic))",
5288 		.test = alg_test_skcipher,
5289 		.suite = {
5290 			.cipher = __VECS(serpent_lrw_tv_template)
5291 		}
5292 	}, {
5293 		.alg = "lrw(twofish)",
5294 		.generic_driver = "lrw(ecb(twofish-generic))",
5295 		.test = alg_test_skcipher,
5296 		.suite = {
5297 			.cipher = __VECS(tf_lrw_tv_template)
5298 		}
5299 	}, {
5300 		.alg = "lz4",
5301 		.test = alg_test_comp,
5302 		.fips_allowed = 1,
5303 		.suite = {
5304 			.comp = {
5305 				.comp = __VECS(lz4_comp_tv_template),
5306 				.decomp = __VECS(lz4_decomp_tv_template)
5307 			}
5308 		}
5309 	}, {
5310 		.alg = "lz4hc",
5311 		.test = alg_test_comp,
5312 		.fips_allowed = 1,
5313 		.suite = {
5314 			.comp = {
5315 				.comp = __VECS(lz4hc_comp_tv_template),
5316 				.decomp = __VECS(lz4hc_decomp_tv_template)
5317 			}
5318 		}
5319 	}, {
5320 		.alg = "lzo",
5321 		.test = alg_test_comp,
5322 		.fips_allowed = 1,
5323 		.suite = {
5324 			.comp = {
5325 				.comp = __VECS(lzo_comp_tv_template),
5326 				.decomp = __VECS(lzo_decomp_tv_template)
5327 			}
5328 		}
5329 	}, {
5330 		.alg = "lzo-rle",
5331 		.test = alg_test_comp,
5332 		.fips_allowed = 1,
5333 		.suite = {
5334 			.comp = {
5335 				.comp = __VECS(lzorle_comp_tv_template),
5336 				.decomp = __VECS(lzorle_decomp_tv_template)
5337 			}
5338 		}
5339 	}, {
5340 		.alg = "md4",
5341 		.test = alg_test_hash,
5342 		.suite = {
5343 			.hash = __VECS(md4_tv_template)
5344 		}
5345 	}, {
5346 		.alg = "md5",
5347 		.test = alg_test_hash,
5348 		.suite = {
5349 			.hash = __VECS(md5_tv_template)
5350 		}
5351 	}, {
5352 		.alg = "michael_mic",
5353 		.test = alg_test_hash,
5354 		.suite = {
5355 			.hash = __VECS(michael_mic_tv_template)
5356 		}
5357 	}, {
5358 		.alg = "nhpoly1305",
5359 		.test = alg_test_hash,
5360 		.suite = {
5361 			.hash = __VECS(nhpoly1305_tv_template)
5362 		}
5363 	}, {
5364 		.alg = "p1363(ecdsa-nist-p192)",
5365 		.test = alg_test_null,
5366 	}, {
5367 		.alg = "p1363(ecdsa-nist-p256)",
5368 		.test = alg_test_sig,
5369 		.fips_allowed = 1,
5370 		.suite = {
5371 			.sig = __VECS(p1363_ecdsa_nist_p256_tv_template)
5372 		}
5373 	}, {
5374 		.alg = "p1363(ecdsa-nist-p384)",
5375 		.test = alg_test_null,
5376 		.fips_allowed = 1,
5377 	}, {
5378 		.alg = "p1363(ecdsa-nist-p521)",
5379 		.test = alg_test_null,
5380 		.fips_allowed = 1,
5381 	}, {
5382 		.alg = "pcbc(fcrypt)",
5383 		.test = alg_test_skcipher,
5384 		.suite = {
5385 			.cipher = __VECS(fcrypt_pcbc_tv_template)
5386 		}
5387 	}, {
5388 		.alg = "pkcs1(rsa,none)",
5389 		.test = alg_test_sig,
5390 		.suite = {
5391 			.sig = __VECS(pkcs1_rsa_none_tv_template)
5392 		}
5393 	}, {
5394 		.alg = "pkcs1(rsa,sha224)",
5395 		.test = alg_test_null,
5396 		.fips_allowed = 1,
5397 	}, {
5398 		.alg = "pkcs1(rsa,sha256)",
5399 		.test = alg_test_sig,
5400 		.fips_allowed = 1,
5401 		.suite = {
5402 			.sig = __VECS(pkcs1_rsa_tv_template)
5403 		}
5404 	}, {
5405 		.alg = "pkcs1(rsa,sha3-256)",
5406 		.test = alg_test_null,
5407 		.fips_allowed = 1,
5408 	}, {
5409 		.alg = "pkcs1(rsa,sha3-384)",
5410 		.test = alg_test_null,
5411 		.fips_allowed = 1,
5412 	}, {
5413 		.alg = "pkcs1(rsa,sha3-512)",
5414 		.test = alg_test_null,
5415 		.fips_allowed = 1,
5416 	}, {
5417 		.alg = "pkcs1(rsa,sha384)",
5418 		.test = alg_test_null,
5419 		.fips_allowed = 1,
5420 	}, {
5421 		.alg = "pkcs1(rsa,sha512)",
5422 		.test = alg_test_null,
5423 		.fips_allowed = 1,
5424 	}, {
5425 		.alg = "pkcs1pad(rsa)",
5426 		.test = alg_test_null,
5427 		.fips_allowed = 1,
5428 	}, {
5429 		.alg = "poly1305",
5430 		.test = alg_test_hash,
5431 		.suite = {
5432 			.hash = __VECS(poly1305_tv_template)
5433 		}
5434 	}, {
5435 		.alg = "polyval",
5436 		.test = alg_test_hash,
5437 		.suite = {
5438 			.hash = __VECS(polyval_tv_template)
5439 		}
5440 	}, {
5441 		.alg = "rfc3686(ctr(aes))",
5442 		.test = alg_test_skcipher,
5443 		.fips_allowed = 1,
5444 		.suite = {
5445 			.cipher = __VECS(aes_ctr_rfc3686_tv_template)
5446 		}
5447 	}, {
5448 		.alg = "rfc3686(ctr(sm4))",
5449 		.test = alg_test_skcipher,
5450 		.suite = {
5451 			.cipher = __VECS(sm4_ctr_rfc3686_tv_template)
5452 		}
5453 	}, {
5454 		.alg = "rfc4106(gcm(aes))",
5455 		.generic_driver = "rfc4106(gcm_base(ctr(aes-generic),ghash-generic))",
5456 		.test = alg_test_aead,
5457 		.fips_allowed = 1,
5458 		.suite = {
5459 			.aead = {
5460 				____VECS(aes_gcm_rfc4106_tv_template),
5461 				.einval_allowed = 1,
5462 				.aad_iv = 1,
5463 			}
5464 		}
5465 	}, {
5466 		.alg = "rfc4309(ccm(aes))",
5467 		.generic_driver = "rfc4309(ccm_base(ctr(aes-generic),cbcmac(aes-generic)))",
5468 		.test = alg_test_aead,
5469 		.fips_allowed = 1,
5470 		.suite = {
5471 			.aead = {
5472 				____VECS(aes_ccm_rfc4309_tv_template),
5473 				.einval_allowed = 1,
5474 				.aad_iv = 1,
5475 			}
5476 		}
5477 	}, {
5478 		.alg = "rfc4543(gcm(aes))",
5479 		.generic_driver = "rfc4543(gcm_base(ctr(aes-generic),ghash-generic))",
5480 		.test = alg_test_aead,
5481 		.suite = {
5482 			.aead = {
5483 				____VECS(aes_gcm_rfc4543_tv_template),
5484 				.einval_allowed = 1,
5485 				.aad_iv = 1,
5486 			}
5487 		}
5488 	}, {
5489 		.alg = "rfc7539(chacha20,poly1305)",
5490 		.test = alg_test_aead,
5491 		.suite = {
5492 			.aead = __VECS(rfc7539_tv_template)
5493 		}
5494 	}, {
5495 		.alg = "rfc7539esp(chacha20,poly1305)",
5496 		.test = alg_test_aead,
5497 		.suite = {
5498 			.aead = {
5499 				____VECS(rfc7539esp_tv_template),
5500 				.einval_allowed = 1,
5501 				.aad_iv = 1,
5502 			}
5503 		}
5504 	}, {
5505 		.alg = "rmd160",
5506 		.test = alg_test_hash,
5507 		.suite = {
5508 			.hash = __VECS(rmd160_tv_template)
5509 		}
5510 	}, {
5511 		.alg = "rsa",
5512 		.test = alg_test_akcipher,
5513 		.fips_allowed = 1,
5514 		.suite = {
5515 			.akcipher = __VECS(rsa_tv_template)
5516 		}
5517 	}, {
5518 		.alg = "sha1",
5519 		.test = alg_test_hash,
5520 		.fips_allowed = 1,
5521 		.suite = {
5522 			.hash = __VECS(sha1_tv_template)
5523 		}
5524 	}, {
5525 		.alg = "sha224",
5526 		.test = alg_test_hash,
5527 		.fips_allowed = 1,
5528 		.suite = {
5529 			.hash = __VECS(sha224_tv_template)
5530 		}
5531 	}, {
5532 		.alg = "sha256",
5533 		.test = alg_test_hash,
5534 		.fips_allowed = 1,
5535 		.suite = {
5536 			.hash = __VECS(sha256_tv_template)
5537 		}
5538 	}, {
5539 		.alg = "sha3-224",
5540 		.test = alg_test_hash,
5541 		.fips_allowed = 1,
5542 		.suite = {
5543 			.hash = __VECS(sha3_224_tv_template)
5544 		}
5545 	}, {
5546 		.alg = "sha3-256",
5547 		.test = alg_test_hash,
5548 		.fips_allowed = 1,
5549 		.suite = {
5550 			.hash = __VECS(sha3_256_tv_template)
5551 		}
5552 	}, {
5553 		.alg = "sha3-384",
5554 		.test = alg_test_hash,
5555 		.fips_allowed = 1,
5556 		.suite = {
5557 			.hash = __VECS(sha3_384_tv_template)
5558 		}
5559 	}, {
5560 		.alg = "sha3-512",
5561 		.test = alg_test_hash,
5562 		.fips_allowed = 1,
5563 		.suite = {
5564 			.hash = __VECS(sha3_512_tv_template)
5565 		}
5566 	}, {
5567 		.alg = "sha384",
5568 		.test = alg_test_hash,
5569 		.fips_allowed = 1,
5570 		.suite = {
5571 			.hash = __VECS(sha384_tv_template)
5572 		}
5573 	}, {
5574 		.alg = "sha512",
5575 		.test = alg_test_hash,
5576 		.fips_allowed = 1,
5577 		.suite = {
5578 			.hash = __VECS(sha512_tv_template)
5579 		}
5580 	}, {
5581 		.alg = "sm3",
5582 		.test = alg_test_hash,
5583 		.suite = {
5584 			.hash = __VECS(sm3_tv_template)
5585 		}
5586 	}, {
5587 		.alg = "streebog256",
5588 		.test = alg_test_hash,
5589 		.suite = {
5590 			.hash = __VECS(streebog256_tv_template)
5591 		}
5592 	}, {
5593 		.alg = "streebog512",
5594 		.test = alg_test_hash,
5595 		.suite = {
5596 			.hash = __VECS(streebog512_tv_template)
5597 		}
5598 	}, {
5599 		.alg = "wp256",
5600 		.test = alg_test_hash,
5601 		.suite = {
5602 			.hash = __VECS(wp256_tv_template)
5603 		}
5604 	}, {
5605 		.alg = "wp384",
5606 		.test = alg_test_hash,
5607 		.suite = {
5608 			.hash = __VECS(wp384_tv_template)
5609 		}
5610 	}, {
5611 		.alg = "wp512",
5612 		.test = alg_test_hash,
5613 		.suite = {
5614 			.hash = __VECS(wp512_tv_template)
5615 		}
5616 	}, {
5617 		.alg = "x962(ecdsa-nist-p192)",
5618 		.test = alg_test_sig,
5619 		.suite = {
5620 			.sig = __VECS(x962_ecdsa_nist_p192_tv_template)
5621 		}
5622 	}, {
5623 		.alg = "x962(ecdsa-nist-p256)",
5624 		.test = alg_test_sig,
5625 		.fips_allowed = 1,
5626 		.suite = {
5627 			.sig = __VECS(x962_ecdsa_nist_p256_tv_template)
5628 		}
5629 	}, {
5630 		.alg = "x962(ecdsa-nist-p384)",
5631 		.test = alg_test_sig,
5632 		.fips_allowed = 1,
5633 		.suite = {
5634 			.sig = __VECS(x962_ecdsa_nist_p384_tv_template)
5635 		}
5636 	}, {
5637 		.alg = "x962(ecdsa-nist-p521)",
5638 		.test = alg_test_sig,
5639 		.fips_allowed = 1,
5640 		.suite = {
5641 			.sig = __VECS(x962_ecdsa_nist_p521_tv_template)
5642 		}
5643 	}, {
5644 		.alg = "xcbc(aes)",
5645 		.test = alg_test_hash,
5646 		.suite = {
5647 			.hash = __VECS(aes_xcbc128_tv_template)
5648 		}
5649 	}, {
5650 		.alg = "xcbc(sm4)",
5651 		.test = alg_test_hash,
5652 		.suite = {
5653 			.hash = __VECS(sm4_xcbc128_tv_template)
5654 		}
5655 	}, {
5656 		.alg = "xchacha12",
5657 		.test = alg_test_skcipher,
5658 		.suite = {
5659 			.cipher = __VECS(xchacha12_tv_template)
5660 		},
5661 	}, {
5662 		.alg = "xchacha20",
5663 		.test = alg_test_skcipher,
5664 		.suite = {
5665 			.cipher = __VECS(xchacha20_tv_template)
5666 		},
5667 	}, {
5668 		.alg = "xctr(aes)",
5669 		.test = alg_test_skcipher,
5670 		.suite = {
5671 			.cipher = __VECS(aes_xctr_tv_template)
5672 		}
5673 	}, {
5674 		.alg = "xts(aes)",
5675 		.generic_driver = "xts(ecb(aes-generic))",
5676 		.test = alg_test_skcipher,
5677 		.fips_allowed = 1,
5678 		.suite = {
5679 			.cipher = __VECS(aes_xts_tv_template)
5680 		}
5681 	}, {
5682 		.alg = "xts(camellia)",
5683 		.generic_driver = "xts(ecb(camellia-generic))",
5684 		.test = alg_test_skcipher,
5685 		.suite = {
5686 			.cipher = __VECS(camellia_xts_tv_template)
5687 		}
5688 	}, {
5689 		.alg = "xts(cast6)",
5690 		.generic_driver = "xts(ecb(cast6-generic))",
5691 		.test = alg_test_skcipher,
5692 		.suite = {
5693 			.cipher = __VECS(cast6_xts_tv_template)
5694 		}
5695 	}, {
5696 		/* Same as xts(aes) except the key is stored in
5697 		 * hardware secure memory which we reference by index
5698 		 */
5699 		.alg = "xts(paes)",
5700 		.test = alg_test_null,
5701 		.fips_allowed = 1,
5702 	}, {
5703 		.alg = "xts(serpent)",
5704 		.generic_driver = "xts(ecb(serpent-generic))",
5705 		.test = alg_test_skcipher,
5706 		.suite = {
5707 			.cipher = __VECS(serpent_xts_tv_template)
5708 		}
5709 	}, {
5710 		.alg = "xts(sm4)",
5711 		.generic_driver = "xts(ecb(sm4-generic))",
5712 		.test = alg_test_skcipher,
5713 		.suite = {
5714 			.cipher = __VECS(sm4_xts_tv_template)
5715 		}
5716 	}, {
5717 		.alg = "xts(twofish)",
5718 		.generic_driver = "xts(ecb(twofish-generic))",
5719 		.test = alg_test_skcipher,
5720 		.suite = {
5721 			.cipher = __VECS(tf_xts_tv_template)
5722 		}
5723 	}, {
5724 #if IS_ENABLED(CONFIG_CRYPTO_PAES_S390)
5725 		.alg = "xts-paes-s390",
5726 		.fips_allowed = 1,
5727 		.test = alg_test_skcipher,
5728 		.suite = {
5729 			.cipher = __VECS(aes_xts_tv_template)
5730 		}
5731 	}, {
5732 #endif
5733 		.alg = "xxhash64",
5734 		.test = alg_test_hash,
5735 		.fips_allowed = 1,
5736 		.suite = {
5737 			.hash = __VECS(xxhash64_tv_template)
5738 		}
5739 	}, {
5740 		.alg = "zstd",
5741 		.test = alg_test_comp,
5742 		.fips_allowed = 1,
5743 		.suite = {
5744 			.comp = {
5745 				.comp = __VECS(zstd_comp_tv_template),
5746 				.decomp = __VECS(zstd_decomp_tv_template)
5747 			}
5748 		}
5749 	}
5750 };
5751 
5752 static void alg_check_test_descs_order(void)
5753 {
5754 	int i;
5755 
5756 	for (i = 1; i < ARRAY_SIZE(alg_test_descs); i++) {
5757 		int diff = strcmp(alg_test_descs[i - 1].alg,
5758 				  alg_test_descs[i].alg);
5759 
5760 		if (WARN_ON(diff > 0)) {
5761 			pr_warn("testmgr: alg_test_descs entries in wrong order: '%s' before '%s'\n",
5762 				alg_test_descs[i - 1].alg,
5763 				alg_test_descs[i].alg);
5764 		}
5765 
5766 		if (WARN_ON(diff == 0)) {
5767 			pr_warn("testmgr: duplicate alg_test_descs entry: '%s'\n",
5768 				alg_test_descs[i].alg);
5769 		}
5770 	}
5771 }
5772 
5773 static void alg_check_testvec_configs(void)
5774 {
5775 	int i;
5776 
5777 	for (i = 0; i < ARRAY_SIZE(default_cipher_testvec_configs); i++)
5778 		WARN_ON(!valid_testvec_config(
5779 				&default_cipher_testvec_configs[i]));
5780 
5781 	for (i = 0; i < ARRAY_SIZE(default_hash_testvec_configs); i++)
5782 		WARN_ON(!valid_testvec_config(
5783 				&default_hash_testvec_configs[i]));
5784 }
5785 
5786 static void testmgr_onetime_init(void)
5787 {
5788 	alg_check_test_descs_order();
5789 	alg_check_testvec_configs();
5790 
5791 #ifdef CONFIG_CRYPTO_MANAGER_EXTRA_TESTS
5792 	pr_warn("alg: extra crypto tests enabled.  This is intended for developer use only.\n");
5793 #endif
5794 }
5795 
5796 static int alg_find_test(const char *alg)
5797 {
5798 	int start = 0;
5799 	int end = ARRAY_SIZE(alg_test_descs);
5800 
5801 	while (start < end) {
5802 		int i = (start + end) / 2;
5803 		int diff = strcmp(alg_test_descs[i].alg, alg);
5804 
5805 		if (diff > 0) {
5806 			end = i;
5807 			continue;
5808 		}
5809 
5810 		if (diff < 0) {
5811 			start = i + 1;
5812 			continue;
5813 		}
5814 
5815 		return i;
5816 	}
5817 
5818 	return -1;
5819 }
5820 
5821 static int alg_fips_disabled(const char *driver, const char *alg)
5822 {
5823 	pr_info("alg: %s (%s) is disabled due to FIPS\n", alg, driver);
5824 
5825 	return -ECANCELED;
5826 }
5827 
5828 int alg_test(const char *driver, const char *alg, u32 type, u32 mask)
5829 {
5830 	int i;
5831 	int j;
5832 	int rc;
5833 
5834 	if (!fips_enabled && notests) {
5835 		printk_once(KERN_INFO "alg: self-tests disabled\n");
5836 		return 0;
5837 	}
5838 
5839 	DO_ONCE(testmgr_onetime_init);
5840 
5841 	if ((type & CRYPTO_ALG_TYPE_MASK) == CRYPTO_ALG_TYPE_CIPHER) {
5842 		char nalg[CRYPTO_MAX_ALG_NAME];
5843 
5844 		if (snprintf(nalg, sizeof(nalg), "ecb(%s)", alg) >=
5845 		    sizeof(nalg))
5846 			return -ENAMETOOLONG;
5847 
5848 		i = alg_find_test(nalg);
5849 		if (i < 0)
5850 			goto notest;
5851 
5852 		if (fips_enabled && !alg_test_descs[i].fips_allowed)
5853 			goto non_fips_alg;
5854 
5855 		rc = alg_test_cipher(alg_test_descs + i, driver, type, mask);
5856 		goto test_done;
5857 	}
5858 
5859 	i = alg_find_test(alg);
5860 	j = alg_find_test(driver);
5861 	if (i < 0 && j < 0)
5862 		goto notest;
5863 
5864 	if (fips_enabled) {
5865 		if (j >= 0 && !alg_test_descs[j].fips_allowed)
5866 			return -EINVAL;
5867 
5868 		if (i >= 0 && !alg_test_descs[i].fips_allowed)
5869 			goto non_fips_alg;
5870 	}
5871 
5872 	rc = 0;
5873 	if (i >= 0)
5874 		rc |= alg_test_descs[i].test(alg_test_descs + i, driver,
5875 					     type, mask);
5876 	if (j >= 0 && j != i)
5877 		rc |= alg_test_descs[j].test(alg_test_descs + j, driver,
5878 					     type, mask);
5879 
5880 test_done:
5881 	if (rc) {
5882 		if (fips_enabled || panic_on_fail) {
5883 			fips_fail_notify();
5884 			panic("alg: self-tests for %s (%s) failed in %s mode!\n",
5885 			      driver, alg,
5886 			      fips_enabled ? "fips" : "panic_on_fail");
5887 		}
5888 		pr_warn("alg: self-tests for %s using %s failed (rc=%d)",
5889 			alg, driver, rc);
5890 		WARN(rc != -ENOENT,
5891 		     "alg: self-tests for %s using %s failed (rc=%d)",
5892 		     alg, driver, rc);
5893 	} else {
5894 		if (fips_enabled)
5895 			pr_info("alg: self-tests for %s (%s) passed\n",
5896 				driver, alg);
5897 	}
5898 
5899 	return rc;
5900 
5901 notest:
5902 	if ((type & CRYPTO_ALG_TYPE_MASK) == CRYPTO_ALG_TYPE_LSKCIPHER) {
5903 		char nalg[CRYPTO_MAX_ALG_NAME];
5904 
5905 		if (snprintf(nalg, sizeof(nalg), "ecb(%s)", alg) >=
5906 		    sizeof(nalg))
5907 			goto notest2;
5908 
5909 		i = alg_find_test(nalg);
5910 		if (i < 0)
5911 			goto notest2;
5912 
5913 		if (fips_enabled && !alg_test_descs[i].fips_allowed)
5914 			goto non_fips_alg;
5915 
5916 		rc = alg_test_skcipher(alg_test_descs + i, driver, type, mask);
5917 		goto test_done;
5918 	}
5919 
5920 notest2:
5921 	printk(KERN_INFO "alg: No test for %s (%s)\n", alg, driver);
5922 
5923 	if (type & CRYPTO_ALG_FIPS_INTERNAL)
5924 		return alg_fips_disabled(driver, alg);
5925 
5926 	return 0;
5927 non_fips_alg:
5928 	return alg_fips_disabled(driver, alg);
5929 }
5930 
5931 #endif /* CONFIG_CRYPTO_MANAGER_DISABLE_TESTS */
5932 
5933 EXPORT_SYMBOL_GPL(alg_test);
5934