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