• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // SPDX-License-Identifier: GPL-2.0 OR MIT
2 /*
3  * Copyright (C) 2015-2019 Jason A. Donenfeld <Jason@zx2c4.com>. All Rights Reserved.
4  */
5 
6 #include <crypto/internal/blake2s.h>
7 #include <crypto/internal/simd.h>
8 
9 #include <linux/types.h>
10 #include <linux/jump_label.h>
11 #include <linux/kernel.h>
12 #include <linux/module.h>
13 #include <linux/sizes.h>
14 
15 #include <asm/cpufeature.h>
16 #include <asm/fpu/api.h>
17 #include <asm/processor.h>
18 #include <asm/simd.h>
19 
20 asmlinkage void blake2s_compress_ssse3(struct blake2s_state *state,
21 				       const u8 *block, const size_t nblocks,
22 				       const u32 inc);
23 asmlinkage void blake2s_compress_avx512(struct blake2s_state *state,
24 					const u8 *block, const size_t nblocks,
25 					const u32 inc);
26 
27 static __ro_after_init DEFINE_STATIC_KEY_FALSE(blake2s_use_ssse3);
28 static __ro_after_init DEFINE_STATIC_KEY_FALSE(blake2s_use_avx512);
29 
blake2s_compress(struct blake2s_state * state,const u8 * block,size_t nblocks,const u32 inc)30 void blake2s_compress(struct blake2s_state *state, const u8 *block,
31 		      size_t nblocks, const u32 inc)
32 {
33 	/* SIMD disables preemption, so relax after processing each page. */
34 	BUILD_BUG_ON(SZ_4K / BLAKE2S_BLOCK_SIZE < 8);
35 
36 	if (!static_branch_likely(&blake2s_use_ssse3) || !crypto_simd_usable()) {
37 		blake2s_compress_generic(state, block, nblocks, inc);
38 		return;
39 	}
40 
41 	do {
42 		const size_t blocks = min_t(size_t, nblocks,
43 					    SZ_4K / BLAKE2S_BLOCK_SIZE);
44 
45 		kernel_fpu_begin();
46 		if (IS_ENABLED(CONFIG_AS_AVX512) &&
47 		    static_branch_likely(&blake2s_use_avx512))
48 			blake2s_compress_avx512(state, block, blocks, inc);
49 		else
50 			blake2s_compress_ssse3(state, block, blocks, inc);
51 		kernel_fpu_end();
52 
53 		nblocks -= blocks;
54 		block += blocks * BLAKE2S_BLOCK_SIZE;
55 	} while (nblocks);
56 }
57 EXPORT_SYMBOL(blake2s_compress);
58 
blake2s_mod_init(void)59 static int __init blake2s_mod_init(void)
60 {
61 	if (boot_cpu_has(X86_FEATURE_SSSE3))
62 		static_branch_enable(&blake2s_use_ssse3);
63 
64 	if (IS_ENABLED(CONFIG_AS_AVX512) &&
65 	    boot_cpu_has(X86_FEATURE_AVX) &&
66 	    boot_cpu_has(X86_FEATURE_AVX2) &&
67 	    boot_cpu_has(X86_FEATURE_AVX512F) &&
68 	    boot_cpu_has(X86_FEATURE_AVX512VL) &&
69 	    cpu_has_xfeatures(XFEATURE_MASK_SSE | XFEATURE_MASK_YMM |
70 			      XFEATURE_MASK_AVX512, NULL))
71 		static_branch_enable(&blake2s_use_avx512);
72 
73 	return 0;
74 }
75 
76 module_init(blake2s_mod_init);
77 
78 MODULE_LICENSE("GPL v2");
79