Skip to contentSkip to conversation

POLYVAL library

PATCH Applied Eric Biggers 2 participants 16 messages Nov 9, 2025 – Nov 12, 2025

Subsystems (7)
Documentation x86 Crypto API arm64 +3 more subsystems
lore
Share & tools
lore

Eric Biggers

author maintainer
#0 lore raw

cover POLYVAL library

This series is targeting libcrypto-next. It can also be retrieved from:

git fetch https://git.kernel.org/pub/scm/linux/kernel/git/ebiggers/linux.git polyval-lib-v1

This series migrates the POLYVAL code to lib/crypto/. It turns out that just like Poly1305, the library is a much better fit for it.

This series also replaces the generic implementation of POLYVAL with a much better one.

Notably, this series improves the performance of HCTR2, since it eliminates unnecessary overhead that was being incurred by accessing POLYVAL via the crypto_shash API. I see a 45% increase in throughput with 64-byte messages, 53% with 128-byte, or 6% with 4096-byte.

It also eliminates the need to explicitly enable the optimized POLYVAL code, as it's now enabled automatically when HCTR2 support is enabled.

Eric Biggers (9):
crypto: polyval - Rename conflicting functions lib/crypto: polyval: Add POLYVAL library
lib/crypto: tests: Add KUnit tests for POLYVAL lib/crypto: arm64/polyval: Migrate optimized code into library lib/crypto: x86/polyval: Migrate optimized code into library
crypto: hctr2 - Convert to use POLYVAL library
crypto: polyval - Remove the polyval crypto_shash
crypto: testmgr - Remove polyval tests
fscrypt: Drop obsolete recommendation to enable optimized POLYVAL

 Documentation/filesystems/fscrypt.rst         |   2 -
 arch/arm64/crypto/Kconfig                     |  10 -
 arch/arm64/crypto/Makefile                    |   3 -
 arch/arm64/crypto/polyval-ce-glue.c           | 158 ---------
 arch/x86/crypto/Kconfig                       |  10 -
 arch/x86/crypto/Makefile                      |   3 -
 arch/x86/crypto/polyval-clmulni_glue.c        | 180 ----------
 crypto/Kconfig                                |  12 +-
 crypto/Makefile                               |   1 -
 crypto/hctr2.c                                | 226 ++++---------
 crypto/polyval-generic.c                      | 205 ------------
 crypto/tcrypt.c                               |   4 -
 crypto/testmgr.c                              |   9 +-
 crypto/testmgr.h                              | 171 ----------
 include/crypto/polyval.h                      | 182 ++++++++++-
 lib/crypto/Kconfig                            |  12 +
 lib/crypto/Makefile                           |  10 +
 .../crypto/arm64}/polyval-ce-core.S           |  38 +--
 lib/crypto/arm64/polyval.h                    |  82 +++++
 lib/crypto/polyval.c                          | 307 ++++++++++++++++++
 lib/crypto/tests/Kconfig                      |   9 +
 lib/crypto/tests/Makefile                     |   1 +
 lib/crypto/tests/polyval-testvecs.h           | 186 +++++++++++
 lib/crypto/tests/polyval_kunit.c              | 223 +++++++++++++
 .../crypto/x86/polyval-pclmul-avx.S           |  40 ++-
 lib/crypto/x86/polyval.h                      |  83 +++++
 scripts/crypto/gen-hash-testvecs.py           |  47 ++-
 27 files changed, 1240 insertions(+), 974 deletions(-)
 delete mode 100644 arch/arm64/crypto/polyval-ce-glue.c
 delete mode 100644 arch/x86/crypto/polyval-clmulni_glue.c
 delete mode 100644 crypto/polyval-generic.c
 rename {arch/arm64/crypto => lib/crypto/arm64}/polyval-ce-core.S (92%)
 create mode 100644 lib/crypto/arm64/polyval.h
 create mode 100644 lib/crypto/polyval.c
 create mode 100644 lib/crypto/tests/polyval-testvecs.h
 create mode 100644 lib/crypto/tests/polyval_kunit.c
 rename arch/x86/crypto/polyval-clmulni_asm.S => lib/crypto/x86/polyval-pclmul-avx.S (91%)
 create mode 100644 lib/crypto/x86/polyval.h

base-commit: ce59a87d1cbd3fa075aba73efde946e61d5ef089

Signature · 1 line
2.51.2
author maintainer
#1 lore raw

PATCH 1/9 crypto: polyval - Rename conflicting functions

Rename polyval_init() and polyval_update(), in preparation for adding library functions with the same name to <crypto/polyval.h>.

Note that polyval-generic.c will be removed later, as it will be superseded by the library. This commit just keeps the kernel building for the initial introduction of the library.

---
 crypto/polyval-generic.c | 12 ++++++------
 1 file changed, 6 insertions(+), 6 deletions(-)
crypto/polyval-generic.c +6 -6
index db8adb56e4ca..fe5b01a4000d 100644
@@ -97,21 +97,21 @@ static int polyval_setkey(struct crypto_shash *tfm,
 		return -ENOMEM;
 
 	return 0;
 }
 
-static int polyval_init(struct shash_desc *desc)
+static int polyval_generic_init(struct shash_desc *desc)
 {
 	struct polyval_desc_ctx *dctx = shash_desc_ctx(desc);
 
 	memset(dctx, 0, sizeof(*dctx));
 
 	return 0;
 }
 
-static int polyval_update(struct shash_desc *desc,
-			 const u8 *src, unsigned int srclen)
+static int polyval_generic_update(struct shash_desc *desc,
+				  const u8 *src, unsigned int srclen)
 {
 	struct polyval_desc_ctx *dctx = shash_desc_ctx(desc);
 	const struct polyval_tfm_ctx *ctx = crypto_shash_ctx(desc->tfm);
 	u8 tmp[POLYVAL_BLOCK_SIZE];
 
@@ -133,11 +133,11 @@ static int polyval_finup(struct shash_desc *desc, const u8 *src,
 
 	if (len) {
 		u8 tmp[POLYVAL_BLOCK_SIZE] = {};
 
 		memcpy(tmp, src, len);
-		polyval_update(desc, tmp, POLYVAL_BLOCK_SIZE);
+		polyval_generic_update(desc, tmp, POLYVAL_BLOCK_SIZE);
 	}
 	copy_and_reverse(dst, dctx->buffer);
 	return 0;
 }
 
@@ -164,12 +164,12 @@ static void polyval_exit_tfm(struct crypto_shash *tfm)
 	gf128mul_free_4k(ctx->gf128);
 }
 
 static struct shash_alg polyval_alg = {
 	.digestsize	= POLYVAL_DIGEST_SIZE,
-	.init		= polyval_init,
-	.update		= polyval_update,
+	.init		= polyval_generic_init,
+	.update		= polyval_generic_update,
 	.finup		= polyval_finup,
 	.setkey		= polyval_setkey,
 	.export		= polyval_export,
 	.import		= polyval_import,
 	.exit_tfm	= polyval_exit_tfm,
Signature · 1 line
2.51.2
author maintainer
#2 lore raw

PATCH 2/9 lib/crypto: polyval: Add POLYVAL library

In reply to Eric Biggers

Add support for POLYVAL to lib/crypto/.

This will replace the polyval crypto_shash algorithm and its use in the hctr2 template, simplifying the code and reducing overhead.

Specifically, this commit introduces the POLYVAL library API and a generic implementation of it. Later commits will migrate the existing architecture-optimized implementations of POLYVAL into lib/crypto/ and add a KUnit test suite.

I've also rewritten the generic implementation completely, using a more modern approach instead of the traditional table-based approach. It's now constant-time, requires no precomputation or dynamic memory allocations, decreases the per-key memory usage from 4096 bytes to 16 bytes, and is faster than the old polyval-generic even on bulk data reusing the same key (at least on x86_64, where I measured 15% faster). We should do this for GHASH too, but for now just do it for POLYVAL.

---
 include/crypto/polyval.h | 171 +++++++++++++++++++++-
 lib/crypto/Kconfig       |  10 ++
 lib/crypto/Makefile      |   8 +
 lib/crypto/polyval.c     | 307 +++++++++++++++++++++++++++++++++++++++
 4 files changed, 493 insertions(+), 3 deletions(-)
 create mode 100644 lib/crypto/polyval.c
include/crypto/polyval.h +168 -3
index d2e63743e592..5ba4c248cad1 100644
@@ -1,14 +1,179 @@
-/* SPDX-License-Identifier: GPL-2.0 */
+/* SPDX-License-Identifier: GPL-2.0-or-later */
 /*
- * Common values for the Polyval hash algorithm
+ * POLYVAL library API
  *
- * Copyright 2021 Google LLC
+ * Copyright 2025 Google LLC
  */
 
 #ifndef _CRYPTO_POLYVAL_H
 #define _CRYPTO_POLYVAL_H
 
+#include <linux/string.h>
+#include <linux/types.h>
+
 #define POLYVAL_BLOCK_SIZE	16
 #define POLYVAL_DIGEST_SIZE	16
 
+/**
+ * struct polyval_elem - An element of the POLYVAL finite field
+ * @bytes: View of the element as a byte array (unioned with @lo and @hi)
+ * @lo: The low 64 terms of the element's polynomial
+ * @hi: The high 64 terms of the element's polynomial
+ *
+ * This represents an element of the finite field GF(2^128), using the POLYVAL
+ * convention: little-endian byte order and natural bit order.
+ */
+struct polyval_elem {
+	union {
+		u8 bytes[POLYVAL_BLOCK_SIZE];
+		struct {
+			__le64 lo;
+			__le64 hi;
+		};
+	};
+};
+
+/**
+ * struct polyval_key - Prepared key for POLYVAL
+ *
+ * This may contain just the raw key H, or it may contain precomputed key
+ * powers, depending on the platform's POLYVAL implementation.  Use
+ * polyval_preparekey() to initialize this.
+ */
+struct polyval_key {
+#ifdef CONFIG_CRYPTO_LIB_POLYVAL_ARCH
+#error "Unhandled arch"
+#else /* CONFIG_CRYPTO_LIB_POLYVAL_ARCH */
+	/** @h: The hash key H */
+	struct polyval_elem h;
+#endif /* !CONFIG_CRYPTO_LIB_POLYVAL_ARCH */
+};
+
+/**
+ * struct polyval_ctx - Context for computing a POLYVAL value
+ * @key: Pointer to the prepared POLYVAL key.  The user of the API is
+ *	 responsible for ensuring that the key lives as long as the context.
+ * @acc: The accumulator
+ * @partial: Number of data bytes processed so far modulo POLYVAL_BLOCK_SIZE
+ */
+struct polyval_ctx {
+	const struct polyval_key *key;
+	struct polyval_elem acc;
+	size_t partial;
+};
+
+/**
+ * polyval_preparekey() - Prepare a POLYVAL key
+ * @key: (output) The key structure to initialize
+ * @raw_key: The raw hash key
+ *
+ * Initialize a POLYVAL key structure from a raw key.  This may be a simple
+ * copy, or it may involve precomputing powers of the key, depending on the
+ * platform's POLYVAL implementation.
+ *
+ * Context: Any context.
+ */
+#ifdef CONFIG_CRYPTO_LIB_POLYVAL_ARCH
+void polyval_preparekey(struct polyval_key *key,
+			const u8 raw_key[POLYVAL_BLOCK_SIZE]);
+
+#else
+static inline void polyval_preparekey(struct polyval_key *key,
+				      const u8 raw_key[POLYVAL_BLOCK_SIZE])
+{
+	/* Just a simple copy, so inline it. */
+	memcpy(key->h.bytes, raw_key, POLYVAL_BLOCK_SIZE);
+}
 #endif
+
+/**
+ * polyval_init() - Initialize a POLYVAL context for a new message
+ * @ctx: The context to initialize
+ * @key: The key to use.  Note that a pointer to the key is saved in the
+ *	 context, so the key must live at least as long as the context.
+ */
+static inline void polyval_init(struct polyval_ctx *ctx,
+				const struct polyval_key *key)
+{
+	*ctx = (struct polyval_ctx){ .key = key };
+}
+
+/**
+ * polyval_import_blkaligned() - Import a POLYVAL accumulator value
+ * @ctx: The context to initialize
+ * @key: The key to import.  Note that a pointer to the key is saved in the
+ *	 context, so the key must live at least as long as the context.
+ * @acc: The accumulator value to import.
+ *
+ * This imports an accumulator that was saved by polyval_export_blkaligned().
+ * The same key must be used.
+ */
+static inline void
+polyval_import_blkaligned(struct polyval_ctx *ctx,
+			  const struct polyval_key *key,
+			  const struct polyval_elem *acc)
+{
+	*ctx = (struct polyval_ctx){ .key = key, .acc = *acc };
+}
+
+/**
+ * polyval_export_blkaligned() - Export a POLYVAL accumulator value
+ * @ctx: The context to export the accumulator value from
+ * @acc: (output) The exported accumulator value
+ *
+ * This exports the accumulator from a POLYVAL context.  The number of data
+ * bytes processed so far must be a multiple of POLYVAL_BLOCK_SIZE.
+ */
+static inline void polyval_export_blkaligned(const struct polyval_ctx *ctx,
+					     struct polyval_elem *acc)
+{
+	*acc = ctx->acc;
+}
+
+/**
+ * polyval_update() - Update a POLYVAL context with message data
+ * @ctx: The context to update; must have been initialized
+ * @data: The message data
+ * @len: The data length in bytes.  Doesn't need to be block-aligned.
+ *
+ * This can be called any number of times.
+ *
+ * Context: Any context.
+ */
+void polyval_update(struct polyval_ctx *ctx, const u8 *data, size_t len);
+
+/**
+ * polyval_final() - Finish computing a POLYVAL value
+ * @ctx: The context to finalize
+ * @out: The output value
+ *
+ * If the total data length isn't a multiple of POLYVAL_BLOCK_SIZE, then the
+ * final block is automatically zero-padded.
+ *
+ * After finishing, this zeroizes @ctx.  So the caller does not need to do it.
+ *
+ * Context: Any context.
+ */
+void polyval_final(struct polyval_ctx *ctx, u8 out[POLYVAL_BLOCK_SIZE]);
+
+/**
+ * polyval() - Compute a POLYVAL value
+ * @key: The prepared key
+ * @data: The message data
+ * @len: The data length in bytes.  Doesn't need to be block-aligned.
+ * @out: The output value
+ *
+ * Context: Any context.
+ */
+static inline void polyval(const struct polyval_key *key,
+			   const u8 *data, size_t len,
+			   u8 out[POLYVAL_BLOCK_SIZE])
+{
+	struct polyval_ctx ctx;
+
+	polyval_init(&ctx, key);
+	polyval_update(&ctx, data, len);
+	polyval_final(&ctx, out);
+}
+
+#endif /* _CRYPTO_POLYVAL_H */
lib/crypto/Kconfig +10 -0
index 7445054fc0ad..6545f0e83b83 100644
@@ -133,10 +133,20 @@ config CRYPTO_LIB_POLY1305_RSIZE
 	default 2 if MIPS || RISCV
 	default 11 if X86_64
 	default 9 if ARM || ARM64
 	default 1
 
+config CRYPTO_LIB_POLYVAL
+	tristate
+	help
+	  The POLYVAL library functions.  Select this if your module uses any of
+	  the functions from <crypto/polyval.h>.
+
+config CRYPTO_LIB_POLYVAL_ARCH
+	bool
+	depends on CRYPTO_LIB_POLYVAL && !UML
+
 config CRYPTO_LIB_CHACHA20POLY1305
 	tristate
 	select CRYPTO_LIB_CHACHA
 	select CRYPTO_LIB_POLY1305
 	select CRYPTO_LIB_UTILS
lib/crypto/Makefile +8 -0
index 5515e73bfd5e..055e44008805 100644
@@ -196,10 +196,18 @@ clean-files += arm/poly1305-core.S \
 	       riscv/poly1305-core.S \
 	       x86/poly1305-x86_64-cryptogams.S
 
 ################################################################################
 
+obj-$(CONFIG_CRYPTO_LIB_POLYVAL) += libpolyval.o
+libpolyval-y := polyval.o
+ifeq ($(CONFIG_CRYPTO_LIB_POLYVAL_ARCH),y)
+CFLAGS_polyval.o += -I$(src)/$(SRCARCH)
+endif
+
+################################################################################
+
 obj-$(CONFIG_CRYPTO_LIB_SHA1) += libsha1.o
 libsha1-y := sha1.o
 ifeq ($(CONFIG_CRYPTO_LIB_SHA1_ARCH),y)
 CFLAGS_sha1.o += -I$(src)/$(SRCARCH)
 ifeq ($(CONFIG_ARM),y)
lib/crypto/polyval.c new file +307 -0

307 lines not on this page · raw message

Signature · 1 line
2.51.2
author maintainer
#7 lore raw

PATCH 3/9 lib/crypto: tests: Add KUnit tests for POLYVAL

In reply to Eric Biggers

Add a test suite for the POLYVAL library, including:

- All the standard tests and the benchmark from hash-test-template.h
- Comparison with a test vector from the RFC
- Test with key and message containing all one bits
- Additional tests related to the key struct

---
 lib/crypto/tests/Kconfig            |   9 ++
 lib/crypto/tests/Makefile           |   1 +
 lib/crypto/tests/polyval-testvecs.h | 186 +++++++++++++++++++++++
 lib/crypto/tests/polyval_kunit.c    | 223 ++++++++++++++++++++++++++++
 scripts/crypto/gen-hash-testvecs.py |  47 +++++-
 5 files changed, 464 insertions(+), 2 deletions(-)
 create mode 100644 lib/crypto/tests/polyval-testvecs.h
 create mode 100644 lib/crypto/tests/polyval_kunit.c
lib/crypto/tests/Kconfig +9 -0
index 140afd1714ba..61d435c450bb 100644
@@ -45,10 +45,19 @@ config CRYPTO_LIB_POLY1305_KUNIT_TEST
 	select CRYPTO_LIB_BENCHMARK_VISIBLE
 	select CRYPTO_LIB_POLY1305
 	help
 	  KUnit tests for the Poly1305 library functions.
 
+config CRYPTO_LIB_POLYVAL_KUNIT_TEST
+	tristate "KUnit tests for POLYVAL" if !KUNIT_ALL_TESTS
+	depends on KUNIT
+	default KUNIT_ALL_TESTS || CRYPTO_SELFTESTS
+	select CRYPTO_LIB_BENCHMARK_VISIBLE
+	select CRYPTO_LIB_POLYVAL
+	help
+	  KUnit tests for the POLYVAL library functions.
+
 config CRYPTO_LIB_SHA1_KUNIT_TEST
 	tristate "KUnit tests for SHA-1" if !KUNIT_ALL_TESTS
 	depends on KUNIT
 	default KUNIT_ALL_TESTS || CRYPTO_SELFTESTS
 	select CRYPTO_LIB_BENCHMARK_VISIBLE
lib/crypto/tests/Makefile +1 -0
index f7d1392dc847..5109a0651925 100644
@@ -3,9 +3,10 @@
 obj-$(CONFIG_CRYPTO_LIB_BLAKE2B_KUNIT_TEST) += blake2b_kunit.o
 obj-$(CONFIG_CRYPTO_LIB_BLAKE2S_KUNIT_TEST) += blake2s_kunit.o
 obj-$(CONFIG_CRYPTO_LIB_CURVE25519_KUNIT_TEST) += curve25519_kunit.o
 obj-$(CONFIG_CRYPTO_LIB_MD5_KUNIT_TEST) += md5_kunit.o
 obj-$(CONFIG_CRYPTO_LIB_POLY1305_KUNIT_TEST) += poly1305_kunit.o
+obj-$(CONFIG_CRYPTO_LIB_POLYVAL_KUNIT_TEST) += polyval_kunit.o
 obj-$(CONFIG_CRYPTO_LIB_SHA1_KUNIT_TEST) += sha1_kunit.o
 obj-$(CONFIG_CRYPTO_LIB_SHA256_KUNIT_TEST) += sha224_kunit.o sha256_kunit.o
 obj-$(CONFIG_CRYPTO_LIB_SHA512_KUNIT_TEST) += sha384_kunit.o sha512_kunit.o
 obj-$(CONFIG_CRYPTO_LIB_SHA3_KUNIT_TEST) += sha3_kunit.o
lib/crypto/tests/polyval-testvecs.h new file +186 -0

186 lines not on this page · raw message

lib/crypto/tests/polyval_kunit.c new file +223 -0

223 lines not on this page · raw message

scripts/crypto/gen-hash-testvecs.py +45 -2

92 lines not on this page · raw message

Signature · 1 line
2.51.2
author maintainer
#8 lore raw

PATCH 4/9 lib/crypto: arm64/polyval: Migrate optimized code into library

In reply to Eric Biggers

Migrate the arm64 implementation of POLYVAL into lib/crypto/, wiring it up to the POLYVAL library interface. This makes the POLYVAL library be properly optimized on arm64.

This drops the arm64 optimizations of polyval in the crypto_shash API. That's fine, since polyval will be removed from crypto_shash entirely since it is unneeded there. But even if it comes back, the crypto_shash API could just be implemented on top of the library API, as usual.

Adjust the names and prototypes of the assembly functions to align more closely with the rest of the library code.

---
 arch/arm64/crypto/Kconfig                     |  10 --
 arch/arm64/crypto/Makefile                    |   3 -
 arch/arm64/crypto/polyval-ce-glue.c           | 158 ------------------
 include/crypto/polyval.h                      |   8 +
 lib/crypto/Kconfig                            |   1 +
 lib/crypto/Makefile                           |   1 +
 .../crypto/arm64}/polyval-ce-core.S           |  38 ++---
 lib/crypto/arm64/polyval.h                    |  82 +++++++++
 8 files changed, 110 insertions(+), 191 deletions(-)
 delete mode 100644 arch/arm64/crypto/polyval-ce-glue.c
 rename {arch/arm64/crypto => lib/crypto/arm64}/polyval-ce-core.S (92%)
 create mode 100644 lib/crypto/arm64/polyval.h
arch/arm64/crypto/Kconfig +0 -10
index 376d6b50743f..bdd276a6e540 100644
@@ -45,20 +45,10 @@ config CRYPTO_SM3_ARM64_CE
 	  SM3 (ShangMi 3) secure hash function (OSCCA GM/T 0004-2012)
 
 	  Architecture: arm64 using:
 	  - ARMv8.2 Crypto Extensions
 
-config CRYPTO_POLYVAL_ARM64_CE
-	tristate "Hash functions: POLYVAL (ARMv8 Crypto Extensions)"
-	depends on KERNEL_MODE_NEON
-	select CRYPTO_POLYVAL
-	help
-	  POLYVAL hash function for HCTR2
-
-	  Architecture: arm64 using:
-	  - ARMv8 Crypto Extensions
-
 config CRYPTO_AES_ARM64
 	tristate "Ciphers: AES, modes: ECB, CBC, CTR, CTS, XCTR, XTS"
 	select CRYPTO_AES
 	select CRYPTO_LIB_SHA256
 	help
arch/arm64/crypto/Makefile +0 -3
index fd3d590fa113..1e330aa08d3f 100644
@@ -27,13 +27,10 @@ obj-$(CONFIG_CRYPTO_SM4_ARM64_NEON_BLK) += sm4-neon.o
 sm4-neon-y := sm4-neon-glue.o sm4-neon-core.o
 
 obj-$(CONFIG_CRYPTO_GHASH_ARM64_CE) += ghash-ce.o
 ghash-ce-y := ghash-ce-glue.o ghash-ce-core.o
 
-obj-$(CONFIG_CRYPTO_POLYVAL_ARM64_CE) += polyval-ce.o
-polyval-ce-y := polyval-ce-glue.o polyval-ce-core.o
-
 obj-$(CONFIG_CRYPTO_AES_ARM64_CE) += aes-ce-cipher.o
 aes-ce-cipher-y := aes-ce-core.o aes-ce-glue.o
 
 obj-$(CONFIG_CRYPTO_AES_ARM64_CE_CCM) += aes-ce-ccm.o
 aes-ce-ccm-y := aes-ce-ccm-glue.o aes-ce-ccm-core.o
arch/arm64/crypto/polyval-ce-glue.c deleted +0 -158

158 lines not on this page · raw message

include/crypto/polyval.h +8 -0
index 5ba4c248cad1..f8aaf4275fbd 100644
@@ -37,14 +37,22 @@ struct polyval_elem {
  * struct polyval_key - Prepared key for POLYVAL
  *
  * This may contain just the raw key H, or it may contain precomputed key
  * powers, depending on the platform's POLYVAL implementation.  Use
  * polyval_preparekey() to initialize this.
+ *
+ * By H^i we mean H^(i-1) * H * x^-128, with base case H^1 = H.  I.e. the
+ * exponentiation repeats the POLYVAL dot operation, with its "extra" x^-128.
  */
 struct polyval_key {
 #ifdef CONFIG_CRYPTO_LIB_POLYVAL_ARCH
+#ifdef CONFIG_ARM64
+	/** @h_powers: Powers of the hash key H^8 through H^1 */
+	struct polyval_elem h_powers[8];
+#else
 #error "Unhandled arch"
+#endif
 #else /* CONFIG_CRYPTO_LIB_POLYVAL_ARCH */
 	/** @h: The hash key H */
 	struct polyval_elem h;
 #endif /* !CONFIG_CRYPTO_LIB_POLYVAL_ARCH */
 };
lib/crypto/Kconfig +1 -0
index 6545f0e83b83..430723994142 100644
@@ -142,10 +142,11 @@ config CRYPTO_LIB_POLYVAL
 	  the functions from <crypto/polyval.h>.
 
 config CRYPTO_LIB_POLYVAL_ARCH
 	bool
 	depends on CRYPTO_LIB_POLYVAL && !UML
+	default y if ARM64 && KERNEL_MODE_NEON
 
 config CRYPTO_LIB_CHACHA20POLY1305
 	tristate
 	select CRYPTO_LIB_CHACHA
 	select CRYPTO_LIB_POLY1305
lib/crypto/Makefile +1 -0
index 055e44008805..2efa96afcb4b 100644
@@ -200,10 +200,11 @@ clean-files += arm/poly1305-core.S \
 
 obj-$(CONFIG_CRYPTO_LIB_POLYVAL) += libpolyval.o
 libpolyval-y := polyval.o
 ifeq ($(CONFIG_CRYPTO_LIB_POLYVAL_ARCH),y)
 CFLAGS_polyval.o += -I$(src)/$(SRCARCH)
+libpolyval-$(CONFIG_ARM64) += arm64/polyval-ce-core.o
 endif
 
 ################################################################################
 
 obj-$(CONFIG_CRYPTO_LIB_SHA1) += libsha1.o
lib/crypto/arm64/polyval-ce-core.S renamed from arch/arm64/crypto/polyval-ce-core.S +18 -20
similarity index 92%
rename from arch/arm64/crypto/polyval-ce-core.S
rename to lib/crypto/arm64/polyval-ce-core.S
index b5326540d2e3..7c731a044d02 100644
@@ -25,14 +25,14 @@
  */
 
 #include <linux/linkage.h>
 #define STRIDE_BLOCKS 8
 
-KEY_POWERS	.req	x0
-MSG		.req	x1
-BLOCKS_LEFT	.req	x2
-ACCUMULATOR	.req	x3
+ACCUMULATOR	.req	x0
+KEY_POWERS	.req	x1
+MSG		.req	x2
+BLOCKS_LEFT	.req	x3
 KEY_START	.req	x10
 EXTRA_BYTES	.req	x11
 TMP	.req	x13
 
 M0	.req	v0
@@ -298,44 +298,42 @@ GSTAR	.req	v24
 	karatsuba2
 	montgomery_reduction SUM
 .endm
 
 /*
- * Perform montgomery multiplication in GF(2^128) and store result in op1.
+ * Computes a = a * b * x^{-128} mod x^128 + x^127 + x^126 + x^121 + 1.
  *
- * Computes op1*op2*x^{-128} mod x^128 + x^127 + x^126 + x^121 + 1
- * If op1, op2 are in montgomery form, this computes the montgomery
- * form of op1*op2.
- *
- * void pmull_polyval_mul(u8 *op1, const u8 *op2);
+ * void polyval_mul_pmull(struct polyval_elem *a,
+ *			  const struct polyval_elem *b);
  */
-SYM_FUNC_START(pmull_polyval_mul)
+SYM_FUNC_START(polyval_mul_pmull)
 	adr	TMP, .Lgstar
 	ld1	{GSTAR.2d}, [TMP]
 	ld1	{v0.16b}, [x0]
 	ld1	{v1.16b}, [x1]
 	karatsuba1_store v0 v1
 	karatsuba2
 	montgomery_reduction SUM
 	st1	{SUM.16b}, [x0]
 	ret
-SYM_FUNC_END(pmull_polyval_mul)
+SYM_FUNC_END(polyval_mul_pmull)
 
 /*
  * Perform polynomial evaluation as specified by POLYVAL.  This computes:
  *	h^n * accumulator + h^n * m_0 + ... + h^1 * m_{n-1}
  * where n=nblocks, h is the hash key, and m_i are the message blocks.
  *
- * x0 - pointer to precomputed key powers h^8 ... h^1
- * x1 - pointer to message blocks
- * x2 - number of blocks to hash
- * x3 - pointer to accumulator
+ * x0 - pointer to accumulator
+ * x1 - pointer to precomputed key powers h^8 ... h^1
+ * x2 - pointer to message blocks
+ * x3 - number of blocks to hash
  *
- * void pmull_polyval_update(const struct polyval_ctx *ctx, const u8 *in,
- *			     size_t nblocks, u8 *accumulator);
+ * void polyval_blocks_pmull(struct polyval_elem *acc,
+ *			     const struct polyval_key *key,
+ *			     const u8 *data, size_t nblocks);
  */
-SYM_FUNC_START(pmull_polyval_update)
+SYM_FUNC_START(polyval_blocks_pmull)
 	adr	TMP, .Lgstar
 	mov	KEY_START, KEY_POWERS
 	ld1	{GSTAR.2d}, [TMP]
 	ld1	{SUM.16b}, [ACCUMULATOR]
 	subs	BLOCKS_LEFT, BLOCKS_LEFT, #STRIDE_BLOCKS
@@ -356,6 +354,6 @@ SYM_FUNC_START(pmull_polyval_update)
 	beq	.LskipPartial
 	partial_stride
 .LskipPartial:
 	st1	{SUM.16b}, [ACCUMULATOR]
 	ret
-SYM_FUNC_END(pmull_polyval_update)
+SYM_FUNC_END(polyval_blocks_pmull)
lib/crypto/arm64/polyval.h new file +82 -0

82 lines not on this page · raw message

Signature · 1 line
2.51.2
author maintainer
#9 lore raw

PATCH 5/9 lib/crypto: x86/polyval: Migrate optimized code into library

In reply to Eric Biggers

Migrate the x86_64 implementation of POLYVAL into lib/crypto/, wiring it up to the POLYVAL library interface. This makes the POLYVAL library be properly optimized on x86_64.

This drops the x86_64 optimizations of polyval in the crypto_shash API. That's fine, since polyval will be removed from crypto_shash entirely since it is unneeded there. But even if it comes back, the crypto_shash API could just be implemented on top of the library API, as usual.

Adjust the names and prototypes of the assembly functions to align more closely with the rest of the library code.

Also replace a movaps instruction with movups to remove the assumption that the key struct is 16-byte aligned. Users can still align the key if they want (and at least in this case, movups is just as fast as movaps), but it's inconvenient to require it.

---
 arch/x86/crypto/Kconfig                       |  10 -
 arch/x86/crypto/Makefile                      |   3 -
 arch/x86/crypto/polyval-clmulni_glue.c        | 180 ------------------
 include/crypto/polyval.h                      |   3 +
 lib/crypto/Kconfig                            |   1 +
 lib/crypto/Makefile                           |   1 +
 .../crypto/x86/polyval-pclmul-avx.S           |  40 ++--
 lib/crypto/x86/polyval.h                      |  83 ++++++++
 8 files changed, 107 insertions(+), 214 deletions(-)
 delete mode 100644 arch/x86/crypto/polyval-clmulni_glue.c
 rename arch/x86/crypto/polyval-clmulni_asm.S => lib/crypto/x86/polyval-pclmul-avx.S (91%)
 create mode 100644 lib/crypto/x86/polyval.h
arch/x86/crypto/Kconfig +0 -10
index 48d3076b6053..3fd2423d3cf8 100644
@@ -351,20 +351,10 @@ config CRYPTO_NHPOLY1305_AVX2
 	  NHPoly1305 hash function for Adiantum
 
 	  Architecture: x86_64 using:
 	  - AVX2 (Advanced Vector Extensions 2)
 
-config CRYPTO_POLYVAL_CLMUL_NI
-	tristate "Hash functions: POLYVAL (CLMUL-NI)"
-	depends on 64BIT
-	select CRYPTO_POLYVAL
-	help
-	  POLYVAL hash function for HCTR2
-
-	  Architecture: x86_64 using:
-	  - CLMUL-NI (carry-less multiplication new instructions)
-
 config CRYPTO_SM3_AVX_X86_64
 	tristate "Hash functions: SM3 (AVX)"
 	depends on 64BIT
 	select CRYPTO_HASH
 	select CRYPTO_LIB_SM3
arch/x86/crypto/Makefile +0 -3
index 6409e3009524..5f2fb4f148fe 100644
@@ -51,13 +51,10 @@ aesni-intel-$(CONFIG_64BIT) += aes-ctr-avx-x86_64.o \
 			       aes-xts-avx-x86_64.o
 
 obj-$(CONFIG_CRYPTO_GHASH_CLMUL_NI_INTEL) += ghash-clmulni-intel.o
 ghash-clmulni-intel-y := ghash-clmulni-intel_asm.o ghash-clmulni-intel_glue.o
 
-obj-$(CONFIG_CRYPTO_POLYVAL_CLMUL_NI) += polyval-clmulni.o
-polyval-clmulni-y := polyval-clmulni_asm.o polyval-clmulni_glue.o
-
 obj-$(CONFIG_CRYPTO_NHPOLY1305_SSE2) += nhpoly1305-sse2.o
 nhpoly1305-sse2-y := nh-sse2-x86_64.o nhpoly1305-sse2-glue.o
 obj-$(CONFIG_CRYPTO_NHPOLY1305_AVX2) += nhpoly1305-avx2.o
 nhpoly1305-avx2-y := nh-avx2-x86_64.o nhpoly1305-avx2-glue.o
 
arch/x86/crypto/polyval-clmulni_glue.c deleted +0 -180

180 lines not on this page · raw message

include/crypto/polyval.h +3 -0
index f8aaf4275fbd..b28b8ef11353 100644
@@ -46,10 +46,13 @@ struct polyval_elem {
 struct polyval_key {
 #ifdef CONFIG_CRYPTO_LIB_POLYVAL_ARCH
 #ifdef CONFIG_ARM64
 	/** @h_powers: Powers of the hash key H^8 through H^1 */
 	struct polyval_elem h_powers[8];
+#elif defined(CONFIG_X86)
+	/** @h_powers: Powers of the hash key H^8 through H^1 */
+	struct polyval_elem h_powers[8];
 #else
 #error "Unhandled arch"
 #endif
 #else /* CONFIG_CRYPTO_LIB_POLYVAL_ARCH */
 	/** @h: The hash key H */
lib/crypto/Kconfig +1 -0
index 430723994142..9d04b3771ce2 100644
@@ -143,10 +143,11 @@ config CRYPTO_LIB_POLYVAL
 
 config CRYPTO_LIB_POLYVAL_ARCH
 	bool
 	depends on CRYPTO_LIB_POLYVAL && !UML
 	default y if ARM64 && KERNEL_MODE_NEON
+	default y if X86_64
 
 config CRYPTO_LIB_CHACHA20POLY1305
 	tristate
 	select CRYPTO_LIB_CHACHA
 	select CRYPTO_LIB_POLY1305
lib/crypto/Makefile +1 -0
index 2efa96afcb4b..6580991f8e12 100644
@@ -201,10 +201,11 @@ clean-files += arm/poly1305-core.S \
 obj-$(CONFIG_CRYPTO_LIB_POLYVAL) += libpolyval.o
 libpolyval-y := polyval.o
 ifeq ($(CONFIG_CRYPTO_LIB_POLYVAL_ARCH),y)
 CFLAGS_polyval.o += -I$(src)/$(SRCARCH)
 libpolyval-$(CONFIG_ARM64) += arm64/polyval-ce-core.o
+libpolyval-$(CONFIG_X86) += x86/polyval-pclmul-avx.o
 endif
 
 ################################################################################
 
 obj-$(CONFIG_CRYPTO_LIB_SHA1) += libsha1.o
lib/crypto/x86/polyval-pclmul-avx.S renamed from arch/x86/crypto/polyval-clmulni_asm.S +19 -21
similarity index 91%
rename from arch/x86/crypto/polyval-clmulni_asm.S
rename to lib/crypto/x86/polyval-pclmul-avx.S
index a6ebe4e7dd2b..7f739465ad35 100644
@@ -34,14 +34,14 @@
 #define LO %xmm12
 #define HI %xmm13
 #define MI %xmm14
 #define SUM %xmm15
 
-#define KEY_POWERS %rdi
-#define MSG %rsi
-#define BLOCKS_LEFT %rdx
-#define ACCUMULATOR %rcx
+#define ACCUMULATOR %rdi
+#define KEY_POWERS %rsi
+#define MSG %rdx
+#define BLOCKS_LEFT %rcx
 #define TMP %rax
 
 .section    .rodata.cst16.gstar, "aM", @progbits, 16
 .align 16
 
@@ -232,11 +232,11 @@
 	addq $(16*STRIDE_BLOCKS), KEY_POWERS
 	subq TMP, KEY_POWERS
 
 	movups (MSG), %xmm0
 	pxor SUM, %xmm0
-	movaps (KEY_POWERS), %xmm1
+	movups (KEY_POWERS), %xmm1
 	schoolbook1_noload
 	dec BLOCKS_LEFT
 	addq $16, MSG
 	addq $16, KEY_POWERS
 
@@ -259,45 +259,43 @@
 	schoolbook2
 	montgomery_reduction SUM
 .endm
 
 /*
- * Perform montgomery multiplication in GF(2^128) and store result in op1.
+ * Computes a = a * b * x^{-128} mod x^128 + x^127 + x^126 + x^121 + 1.
  *
- * Computes op1*op2*x^{-128} mod x^128 + x^127 + x^126 + x^121 + 1
- * If op1, op2 are in montgomery form, this computes the montgomery
- * form of op1*op2.
- *
- * void clmul_polyval_mul(u8 *op1, const u8 *op2);
+ * void polyval_mul_pclmul_avx(struct polyval_elem *a,
+ *			       const struct polyval_elem *b);
  */
-SYM_FUNC_START(clmul_polyval_mul)
+SYM_FUNC_START(polyval_mul_pclmul_avx)
 	FRAME_BEGIN
 	vmovdqa .Lgstar(%rip), GSTAR
 	movups (%rdi), %xmm0
 	movups (%rsi), %xmm1
 	schoolbook1_noload
 	schoolbook2
 	montgomery_reduction SUM
 	movups SUM, (%rdi)
 	FRAME_END
 	RET
-SYM_FUNC_END(clmul_polyval_mul)
+SYM_FUNC_END(polyval_mul_pclmul_avx)
 
 /*
  * Perform polynomial evaluation as specified by POLYVAL.  This computes:
  *	h^n * accumulator + h^n * m_0 + ... + h^1 * m_{n-1}
  * where n=nblocks, h is the hash key, and m_i are the message blocks.
  *
- * rdi - pointer to precomputed key powers h^8 ... h^1
- * rsi - pointer to message blocks
- * rdx - number of blocks to hash
- * rcx - pointer to the accumulator
+ * rdi - pointer to the accumulator
+ * rsi - pointer to precomputed key powers h^8 ... h^1
+ * rdx - pointer to message blocks
+ * rcx - number of blocks to hash
  *
- * void clmul_polyval_update(const struct polyval_tfm_ctx *keys,
- *	const u8 *in, size_t nblocks, u8 *accumulator);
+ * void polyval_blocks_pclmul_avx(struct polyval_elem *acc,
+ *				  const struct polyval_key *key,
+ *				  const u8 *data, size_t nblocks);
  */
-SYM_FUNC_START(clmul_polyval_update)
+SYM_FUNC_START(polyval_blocks_pclmul_avx)
 	FRAME_BEGIN
 	vmovdqa .Lgstar(%rip), GSTAR
 	movups (ACCUMULATOR), SUM
 	subq $STRIDE_BLOCKS, BLOCKS_LEFT
 	js .LstrideLoopExit
@@ -316,6 +314,6 @@ SYM_FUNC_START(clmul_polyval_update)
 	partial_stride
 .LskipPartial:
 	movups SUM, (ACCUMULATOR)
 	FRAME_END
 	RET
-SYM_FUNC_END(clmul_polyval_update)
+SYM_FUNC_END(polyval_blocks_pclmul_avx)
lib/crypto/x86/polyval.h new file +83 -0

83 lines not on this page · raw message

Signature · 1 line
2.51.2
author maintainer
#10 lore raw

PATCH 6/9 crypto: hctr2 - Convert to use POLYVAL library

In reply to Eric Biggers

The "hash function" in hctr2 is fixed at POLYVAL; it can never vary. Just use the POLYVAL library, which is much easier to use than the crypto_shash API. It's faster, uses fixed-size structs, and never fails (all the functions return void).

Note that this eliminates the only known user of the polyval support in crypto_shash. A later commit will remove support for polyval from crypto_shash, given that the library API is sufficient.

---
 crypto/Kconfig   |   2 +-
 crypto/hctr2.c   | 226 ++++++++++++++---------------------------------
 crypto/testmgr.c |   3 +-
 3 files changed, 66 insertions(+), 165 deletions(-)
crypto/Kconfig +1 -1
index 57b85e903cf0..805172f75bf1 100644
@@ -694,11 +694,11 @@ config CRYPTO_ECB
 	  ECB (Electronic Codebook) mode (NIST SP800-38A)
 
 config CRYPTO_HCTR2
 	tristate "HCTR2"
 	select CRYPTO_XCTR
-	select CRYPTO_POLYVAL
+	select CRYPTO_LIB_POLYVAL
 	select CRYPTO_MANAGER
 	help
 	  HCTR2 length-preserving encryption mode
 
 	  A mode for storage encryption that is efficient on processors with
crypto/hctr2.c +64 -162

447 lines not on this page · raw message

crypto/testmgr.c +1 -2
index 90d06c3ec967..499e979a56dc 100644
@@ -5057,12 +5057,11 @@ static const struct alg_test_desc alg_test_descs[] = {
 		.suite = {
 			.hash = __VECS(ghash_tv_template)
 		}
 	}, {
 		.alg = "hctr2(aes)",
-		.generic_driver =
-		    "hctr2_base(xctr(aes-generic),polyval-generic)",
+		.generic_driver = "hctr2_base(xctr(aes-generic),polyval-lib)",
 		.test = alg_test_skcipher,
 		.suite = {
 			.cipher = __VECS(aes_hctr2_tv_template)
 		}
 	}, {
Signature · 1 line
2.51.2
author maintainer
#11 lore raw

PATCH 7/9 crypto: polyval - Remove the polyval crypto_shash

In reply to Eric Biggers

Remove polyval support from crypto_shash. It no longer has any user now that the HCTR2 code uses the POLYVAL library instead.

---
 crypto/Kconfig           |  10 --
 crypto/Makefile          |   1 -
 crypto/polyval-generic.c | 205 ---------------------------------------
 3 files changed, 216 deletions(-)
 delete mode 100644 crypto/polyval-generic.c
crypto/Kconfig +0 -10
index 805172f75bf1..bf8b8a60a0c0 100644
@@ -946,20 +946,10 @@ config CRYPTO_MICHAEL_MIC
 	  known as WPA (Wif-Fi Protected Access).
 
 	  This algorithm is required for TKIP, but it should not be used for
 	  other purposes because of the weakness of the algorithm.
 
-config CRYPTO_POLYVAL
-	tristate
-	select CRYPTO_HASH
-	select CRYPTO_LIB_GF128MUL
-	help
-	  POLYVAL hash function for HCTR2
-
-	  This is used in HCTR2.  It is not a general-purpose
-	  cryptographic hash function.
-
 config CRYPTO_RMD160
 	tristate "RIPEMD-160"
 	select CRYPTO_HASH
 	help
 	  RIPEMD-160 hash function (ISO/IEC 10118-3)
crypto/Makefile +0 -1
index 0388ff8d219d..093c56a45d3f 100644
@@ -170,11 +170,10 @@ KASAN_SANITIZE_jitterentropy.o = n
 UBSAN_SANITIZE_jitterentropy.o = n
 jitterentropy_rng-y := jitterentropy.o jitterentropy-kcapi.o
 obj-$(CONFIG_CRYPTO_JITTERENTROPY_TESTINTERFACE) += jitterentropy-testing.o
 obj-$(CONFIG_CRYPTO_BENCHMARK) += tcrypt.o
 obj-$(CONFIG_CRYPTO_GHASH) += ghash-generic.o
-obj-$(CONFIG_CRYPTO_POLYVAL) += polyval-generic.o
 obj-$(CONFIG_CRYPTO_USER_API) += af_alg.o
 obj-$(CONFIG_CRYPTO_USER_API_HASH) += algif_hash.o
 obj-$(CONFIG_CRYPTO_USER_API_SKCIPHER) += algif_skcipher.o
 obj-$(CONFIG_CRYPTO_USER_API_RNG) += algif_rng.o
 obj-$(CONFIG_CRYPTO_USER_API_AEAD) += algif_aead.o
crypto/polyval-generic.c deleted +0 -205

205 lines not on this page · raw message

Signature · 1 line
2.51.2
author maintainer
#12 lore raw

PATCH 8/9 crypto: testmgr - Remove polyval tests

In reply to Eric Biggers

These are no longer used, since polyval support has been removed from the crypto_shash API.

POLYVAL remains supported via lib/crypto/, where it has a KUnit test suite instead.

---
 crypto/tcrypt.c  |   4 --
 crypto/testmgr.c |   6 --
 crypto/testmgr.h | 171 -----------------------------------------------
 3 files changed, 181 deletions(-)
crypto/tcrypt.c +0 -4
index d1d88debbd71..32d9eaf2c8af 100644
@@ -1688,14 +1688,10 @@ static int do_test(const char *alg, u32 type, u32 mask, int m, u32 num_mb)
 
 	case 56:
 		ret = min(ret, tcrypt_test("ccm(sm4)"));
 		break;
 
-	case 57:
-		ret = min(ret, tcrypt_test("polyval"));
-		break;
-
 	case 58:
 		ret = min(ret, tcrypt_test("gcm(aria)"));
 		break;
 
 	case 59:
crypto/testmgr.c +0 -6
index 499e979a56dc..6fb53978df11 100644
@@ -5368,16 +5368,10 @@ static const struct alg_test_desc alg_test_descs[] = {
 		.fips_allowed = 1,
 	}, {
 		.alg = "pkcs1pad(rsa)",
 		.test = alg_test_null,
 		.fips_allowed = 1,
-	}, {
-		.alg = "polyval",
-		.test = alg_test_hash,
-		.suite = {
-			.hash = __VECS(polyval_tv_template)
-		}
 	}, {
 		.alg = "rfc3686(ctr(aes))",
 		.test = alg_test_skcipher,
 		.fips_allowed = 1,
 		.suite = {
crypto/testmgr.h +0 -171

181 lines not on this page · raw message

Signature · 1 line
2.51.2
author maintainer
#13 lore raw

PATCH 9/9 fscrypt: Drop obsolete recommendation to enable optimized POLYVAL

In reply to Eric Biggers

CONFIG_CRYPTO_POLYVAL_ARM64_CE and CONFIG_CRYPTO_POLYVAL_CLMUL_NI no longer exist. The architecture-optimized POLYVAL code is now just enabled automatically when HCTR2 support is enabled. Update the fscrypt documentation accordingly.

---
 Documentation/filesystems/fscrypt.rst | 2 --
 1 file changed, 2 deletions(-)
Documentation/filesystems/fscrypt.rst +0 -2
index 696a5844bfa3..70af896822e1 100644
@@ -448,13 +448,11 @@ API, but the filenames mode still does.
 - AES-256-HCTR2
     - Mandatory:
         - CONFIG_CRYPTO_HCTR2
     - Recommended:
         - arm64: CONFIG_CRYPTO_AES_ARM64_CE_BLK
-        - arm64: CONFIG_CRYPTO_POLYVAL_ARM64_CE
         - x86: CONFIG_CRYPTO_AES_NI_INTEL
-        - x86: CONFIG_CRYPTO_POLYVAL_CLMUL_NI
 
 - Adiantum
     - Mandatory:
         - CONFIG_CRYPTO_ADIANTUM
     - Recommended:
Signature · 1 line
2.51.2
maintainer Reviewed-by Tested-by on v1 2/9
#3 lore raw

Re: [PATCH 2/9] lib/crypto: polyval: Add POLYVAL library

In reply to Eric Biggers

Hi,

Quoted 11 lines · Eric Biggers

Add support for POLYVAL to lib/crypto/.

This will replace the polyval crypto_shash algorithm and its use in the hctr2 template, simplifying the code and reducing overhead.

Specifically, this commit introduces the POLYVAL library API and a generic implementation of it. Later commits will migrate the existing architecture-optimized implementations of POLYVAL into lib/crypto/ and add a KUnit test suite.

Quoted 8 lines

I've also rewritten the generic implementation completely, using a more modern approach instead of the traditional table-based approach. It's now constant-time, requires no precomputation or dynamic memory allocations, decreases the per-key memory usage from 4096 bytes to 16 bytes, and is faster than the old polyval-generic even on bulk data reusing the same key (at least on x86_64, where I measured 15% faster). We should do this for GHASH too, but for now just do it for POLYVAL.

Very nice.

GHASH might suffer on 32-bit, I suppose, but taking this approach at least on 64-bit also for GHASH would be a huge improvement.

I had a stab at replacing the int128 arithmetic with __builtin_bitreverse64(), but it seems to make little difference (and GCC does not support it [yet]). I've tried both arm64 and x86, and the perf delta (using your kunit benchmark) is negligible in either case. (FYI)

Quoted 9 lines
---
 include/crypto/polyval.h | 171 +++++++++++++++++++++-
 lib/crypto/Kconfig       |  10 ++
 lib/crypto/Makefile      |   8 +
 lib/crypto/polyval.c     | 307 +++++++++++++++++++++++++++++++++++++++
 4 files changed, 493 insertions(+), 3 deletions(-)
 create mode 100644 lib/crypto/polyval.c
maintainer Reviewed-by on the v1 series
#14 lore raw
In reply to Eric Biggers
Quoted 19 lines · Eric Biggers

This series is targeting libcrypto-next. It can also be retrieved from:

git fetch https://git.kernel.org/pub/scm/linux/kernel/git/ebiggers/linux.git polyval-lib-v1

This series migrates the POLYVAL code to lib/crypto/. It turns out that just like Poly1305, the library is a much better fit for it.

This series also replaces the generic implementation of POLYVAL with a much better one.

Notably, this series improves the performance of HCTR2, since it eliminates unnecessary overhead that was being incurred by accessing POLYVAL via the crypto_shash API. I see a 45% increase in throughput with 64-byte messages, 53% with 128-byte, or 6% with 4096-byte.

It also eliminates the need to explicitly enable the optimized POLYVAL code, as it's now enabled automatically when HCTR2 support is enabled.

Quoted 11 lines

Eric Biggers (9):
crypto: polyval - Rename conflicting functions lib/crypto: polyval: Add POLYVAL library
lib/crypto: tests: Add KUnit tests for POLYVAL lib/crypto: arm64/polyval: Migrate optimized code into library lib/crypto: x86/polyval: Migrate optimized code into library
crypto: hctr2 - Convert to use POLYVAL library
crypto: polyval - Remove the polyval crypto_shash
crypto: testmgr - Remove polyval tests
fscrypt: Drop obsolete recommendation to enable optimized POLYVAL

maintainer
#4 lore raw

Re: [PATCH 2/9] lib/crypto: polyval: Add POLYVAL library

In reply to Ard Biesheuvel
Quoted 26 lines · Ard Biesheuvel

Hi,

Quoted 11 lines · Eric Biggers

Add support for POLYVAL to lib/crypto/.

This will replace the polyval crypto_shash algorithm and its use in the hctr2 template, simplifying the code and reducing overhead.

Specifically, this commit introduces the POLYVAL library API and a generic implementation of it. Later commits will migrate the existing architecture-optimized implementations of POLYVAL into lib/crypto/ and add a KUnit test suite.

Quoted 8 lines

I've also rewritten the generic implementation completely, using a more modern approach instead of the traditional table-based approach. It's now constant-time, requires no precomputation or dynamic memory allocations, decreases the per-key memory usage from 4096 bytes to 16 bytes, and is faster than the old polyval-generic even on bulk data reusing the same key (at least on x86_64, where I measured 15% faster). We should do this for GHASH too, but for now just do it for POLYVAL.

Very nice.

Quoted 7 lines

GHASH might suffer on 32-bit, I suppose, but taking this approach at least on 64-bit also for GHASH would be a huge improvement.

I had a stab at replacing the int128 arithmetic with __builtin_bitreverse64(), but it seems to make little difference (and GCC does not support it [yet]). I've tried both arm64 and x86, and the perf delta (using your kunit benchmark) is negligible in either case.

Sigh. I intended to only apply the generic patch and the kunit test, but applied the whole series in the end, which explains perfectly why x86_64 and arm64 performance are identical, given that the generic code isn't even used.

So trying this again, on a Cortex-A72 without Crypto Extensions, I do get a ~30% performance improvement doing the below. I haven't re-tested x86, but given that it does not appear to have a native scalar bit reverse instruction (or __builtin_bitreverse64() is broken for it), there is probably no point in finding out.

Not saying we should do this for POLYVAL, but something to keep in mind for gf128mul.c perhaps.

lib/crypto/polyval.c +1 -1
@@ -42,11 +42,48 @@
  * 256-bit => 128-bit reduction algorithm.
  */
 
-#ifdef CONFIG_ARCH_SUPPORTS_INT128
+#if defined(CONFIG_ARCH_SUPPORTS_INT128) ||

__has_builtin(__builtin_bitreverse64)

/* Do a 64 x 64 => 128 bit carryless multiplication. */ static void clmul64(u64 a, u64 b, u64 *out_lo, u64 *out_hi) {

+       u64 a0 = a & 0x1111111111111111;
+       u64 a1 = a & 0x2222222222222222;
+       u64 a2 = a & 0x4444444444444444;
+       u64 a3 = a & 0x8888888888888888;
+
+       u64 b0 = b & 0x1111111111111111;
+       u64 b1 = b & 0x2222222222222222;
+       u64 b2 = b & 0x4444444444444444;
+       u64 b3 = b & 0x8888888888888888;
+
+#if __has_builtin(__builtin_bitreverse64)
+#define brev64 __builtin_bitreverse64
+       u64 c0 = (a0 * b0) ^ (a1 * b3) ^ (a2 * b2) ^ (a3 * b1);
+       u64 c1 = (a0 * b1) ^ (a1 * b0) ^ (a2 * b3) ^ (a3 * b2);
+       u64 c2 = (a0 * b2) ^ (a1 * b1) ^ (a2 * b0) ^ (a3 * b3);
+       u64 c3 = (a0 * b3) ^ (a1 * b2) ^ (a2 * b1) ^ (a3 * b0);
+
+       a0 = brev64(a0);
+       a1 = brev64(a1);
+       a2 = brev64(a2);
+       a3 = brev64(a3);
+
+       b0 = brev64(b0);
+       b1 = brev64(b1);
+       b2 = brev64(b2);
+       b3 = brev64(b3);
+
+       u64 d0 = (a0 * b0) ^ (a1 * b3) ^ (a2 * b2) ^ (a3 * b1);
+       u64 d1 = (a0 * b1) ^ (a1 * b0) ^ (a2 * b3) ^ (a3 * b2);
+       u64 d2 = (a0 * b2) ^ (a1 * b1) ^ (a2 * b0) ^ (a3 * b3);
+       u64 d3 = (a0 * b3) ^ (a1 * b2) ^ (a2 * b1) ^ (a3 * b0);
+
+       *out_hi = ((brev64(d0) >> 1) & 0x1111111111111111) ^
+                 ((brev64(d1) >> 1) & 0x2222222222222222) ^
+                 ((brev64(d2) >> 1) & 0x4444444444444444) ^
+                 ((brev64(d3) >> 1) & 0x8888888888888888);

+#else
/*
* With 64-bit multiplicands and one term every 4 bits, there would be
* up to 64 / 4 = 16 one bits per column when each multiplication is
@@ -60,15 +97,10 @@ static void clmul64(u64 a, u64 b, u64 *out_lo, u64 *out_hi)
* Instead, mask off 4 bits from one multiplicand, giving a max of 15
* one bits per column. Then handle those 4 bits separately. */

-       u64 a0 = a & 0x1111111111111110;
-       u64 a1 = a & 0x2222222222222220;
-       u64 a2 = a & 0x4444444444444440;
-       u64 a3 = a & 0x8888888888888880;
-
-       u64 b0 = b & 0x1111111111111111;
-       u64 b1 = b & 0x2222222222222222;
-       u64 b2 = b & 0x4444444444444444;
-       u64 b3 = b & 0x8888888888888888;
+       a0 &= ~0xfULL;
+       a1 &= ~0xfULL;
+       a2 &= ~0xfULL;
+       a3 &= ~0xfULL;
        /* Multiply the high 60 bits of @a by @b. */
        u128 c0 = (a0 * (u128)b0) ^ (a1 * (u128)b3) ^
@@ -85,18 +117,20 @@ static void clmul64(u64 a, u64 b, u64 *out_lo, u64 *out_hi)
        u64 e1 = -((a >> 1) & 1) & b;
        u64 e2 = -((a >> 2) & 1) & b;
        u64 e3 = -((a >> 3) & 1) & b;

- u64 extra_lo = e0 ^ (e1 << 1) ^ (e2 << 2) ^ (e3 << 3);
- u64 extra_hi = (e1 >> 63) ^ (e2 >> 62) ^ (e3 >> 61);

        /* Add all the intermediate products together. */
-       *out_lo = (((u64)c0) & 0x1111111111111111) ^
-                 (((u64)c1) & 0x2222222222222222) ^
-                 (((u64)c2) & 0x4444444444444444) ^
-                 (((u64)c3) & 0x8888888888888888) ^ extra_lo;
        *out_hi = (((u64)(c0 >> 64)) & 0x1111111111111111) ^
                  (((u64)(c1 >> 64)) & 0x2222222222222222) ^
                  (((u64)(c2 >> 64)) & 0x4444444444444444) ^
-                 (((u64)(c3 >> 64)) & 0x8888888888888888) ^ extra_hi;
+                 (((u64)(c3 >> 64)) & 0x8888888888888888) ^
+                 (e1 >> 63) ^ (e2 >> 62) ^ (e3 >> 61);

+
+ *out_lo = e0 ^ (e1 << 1) ^ (e2 << 2) ^ (e3 << 3);
+#endif
+ *out_lo ^= (((u64)c0) & 0x1111111111111111) ^

+                  (((u64)c1) & 0x2222222222222222) ^
+                  (((u64)c2) & 0x4444444444444444) ^
+                  (((u64)c3) & 0x8888888888888888);

}

#else /* CONFIG_ARCH_SUPPORTS_INT128 */

author maintainer Applied
#15 lore raw
In reply to Eric Biggers
Quoted 18 lines · Eric Biggers

This series is targeting libcrypto-next. It can also be retrieved from:

git fetch https://git.kernel.org/pub/scm/linux/kernel/git/ebiggers/linux.git polyval-lib-v1

This series migrates the POLYVAL code to lib/crypto/. It turns out that just like Poly1305, the library is a much better fit for it.

This series also replaces the generic implementation of POLYVAL with a much better one.

Notably, this series improves the performance of HCTR2, since it eliminates unnecessary overhead that was being incurred by accessing POLYVAL via the crypto_shash API. I see a 45% increase in throughput with 64-byte messages, 53% with 128-byte, or 6% with 4096-byte.

It also eliminates the need to explicitly enable the optimized POLYVAL code, as it's now enabled automatically when HCTR2 support is enabled.

Quoted 11 lines

Eric Biggers (9):
crypto: polyval - Rename conflicting functions lib/crypto: polyval: Add POLYVAL library
lib/crypto: tests: Add KUnit tests for POLYVAL lib/crypto: arm64/polyval: Migrate optimized code into library lib/crypto: x86/polyval: Migrate optimized code into library
crypto: hctr2 - Convert to use POLYVAL library
crypto: polyval - Remove the polyval crypto_shash
crypto: testmgr - Remove polyval tests
fscrypt: Drop obsolete recommendation to enable optimized POLYVAL

Applied to https://git.kernel.org/pub/scm/linux/kernel/git/ebiggers/linux.git/log/?h=libcrypto-next

- Eric

author maintainer
#5 lore raw

Re: [PATCH 2/9] lib/crypto: polyval: Add POLYVAL library

In reply to Ard Biesheuvel
Quoted 89 lines · Ard Biesheuvel
Quoted 26 lines · Ard Biesheuvel

Hi,

Quoted 11 lines · Eric Biggers

Add support for POLYVAL to lib/crypto/.

This will replace the polyval crypto_shash algorithm and its use in the hctr2 template, simplifying the code and reducing overhead.

Specifically, this commit introduces the POLYVAL library API and a generic implementation of it. Later commits will migrate the existing architecture-optimized implementations of POLYVAL into lib/crypto/ and add a KUnit test suite.

Quoted 8 lines

I've also rewritten the generic implementation completely, using a more modern approach instead of the traditional table-based approach. It's now constant-time, requires no precomputation or dynamic memory allocations, decreases the per-key memory usage from 4096 bytes to 16 bytes, and is faster than the old polyval-generic even on bulk data reusing the same key (at least on x86_64, where I measured 15% faster). We should do this for GHASH too, but for now just do it for POLYVAL.

Very nice.

Quoted 7 lines

GHASH might suffer on 32-bit, I suppose, but taking this approach at least on 64-bit also for GHASH would be a huge improvement.

I had a stab at replacing the int128 arithmetic with __builtin_bitreverse64(), but it seems to make little difference (and GCC does not support it [yet]). I've tried both arm64 and x86, and the perf delta (using your kunit benchmark) is negligible in either case.

Sigh. I intended to only apply the generic patch and the kunit test, but applied the whole series in the end, which explains perfectly why x86_64 and arm64 performance are identical, given that the generic code isn't even used.

So trying this again, on a Cortex-A72 without Crypto Extensions, I do get a ~30% performance improvement doing the below. I haven't re-tested x86, but given that it does not appear to have a native scalar bit reverse instruction (or __builtin_bitreverse64() is broken for it), there is probably no point in finding out.

Not saying we should do this for POLYVAL, but something to keep in mind for gf128mul.c perhaps.

lib/crypto/polyval.c +27 -1
@@ -42,11 +42,48 @@
  * 256-bit => 128-bit reduction algorithm.
  */
 
-#ifdef CONFIG_ARCH_SUPPORTS_INT128
+#if defined(CONFIG_ARCH_SUPPORTS_INT128) ||
 __has_builtin(__builtin_bitreverse64)
 
 /* Do a 64 x 64 => 128 bit carryless multiplication. */
 static void clmul64(u64 a, u64 b, u64 *out_lo, u64 *out_hi)
 {
+       u64 a0 = a & 0x1111111111111111;
+       u64 a1 = a & 0x2222222222222222;
+       u64 a2 = a & 0x4444444444444444;
+       u64 a3 = a & 0x8888888888888888;
+
+       u64 b0 = b & 0x1111111111111111;
+       u64 b1 = b & 0x2222222222222222;
+       u64 b2 = b & 0x4444444444444444;
+       u64 b3 = b & 0x8888888888888888;
+
+#if __has_builtin(__builtin_bitreverse64)
+#define brev64 __builtin_bitreverse64
+       u64 c0 = (a0 * b0) ^ (a1 * b3) ^ (a2 * b2) ^ (a3 * b1);
+       u64 c1 = (a0 * b1) ^ (a1 * b0) ^ (a2 * b3) ^ (a3 * b2);
+       u64 c2 = (a0 * b2) ^ (a1 * b1) ^ (a2 * b0) ^ (a3 * b3);
+       u64 c3 = (a0 * b3) ^ (a1 * b2) ^ (a2 * b1) ^ (a3 * b0);
+
+       a0 = brev64(a0);
+       a1 = brev64(a1);
+       a2 = brev64(a2);
+       a3 = brev64(a3);
+
+       b0 = brev64(b0);
+       b1 = brev64(b1);
+       b2 = brev64(b2);
+       b3 = brev64(b3);

lib/crypto/polyval.c line 86

Quoted 10 lines
lib/crypto/polyval.c +10 -0
+
+       u64 d0 = (a0 * b0) ^ (a1 * b3) ^ (a2 * b2) ^ (a3 * b1);
+       u64 d1 = (a0 * b1) ^ (a1 * b0) ^ (a2 * b3) ^ (a3 * b2);
+       u64 d2 = (a0 * b2) ^ (a1 * b1) ^ (a2 * b0) ^ (a3 * b3);
+       u64 d3 = (a0 * b3) ^ (a1 * b2) ^ (a2 * b1) ^ (a3 * b0);
+
+       *out_hi = ((brev64(d0) >> 1) & 0x1111111111111111) ^
+                 ((brev64(d1) >> 1) & 0x2222222222222222) ^
+                 ((brev64(d2) >> 1) & 0x4444444444444444) ^
+                 ((brev64(d3) >> 1) & 0x8888888888888888);

Yeah, that's an interesting idea! So if we bit-reflect the inputs, do an n x n => n multiplication, and bit-reflect the output and right-shift it by 1, we get the high half of the desired n x n => 2n multiplication. (This relies on the fact that carries are being discarded.) Then we don't need an instruction that does an n x n => 2n multiplication or produces the high half of it.

The availability of hardware bit-reversal is limited, though. arm32, arm64, and mips32r6 have it. But all of those also have a "multiply high" instruction. So the 30% performance improvement you saw on arm64 seems surprising to me, as umulh should have been used. (I verified that it's indeed used in the generated asm with both gcc and clang.)

The available bit-reversal abstractions aren't too great either, with __builtin_bitreverse64() being clang-specific and <linux/bitrev.h> having a table-based, i.e. non-constant-time, fallback. So presumably we'd need to add our own which is guaranteed to use the actual instructions and not some slow and/or table-based fallback.

I'll definitely look into this more later when bringing this improvement to GHASH too. But for now I think we should go with the version I have in my patch.

- Eric

maintainer
#6 lore raw

Re: [PATCH 2/9] lib/crypto: polyval: Add POLYVAL library

Quoted 109 lines · Eric Biggers
Quoted 89 lines · Ard Biesheuvel
Quoted 26 lines · Ard Biesheuvel

Hi,

Quoted 11 lines · Eric Biggers

Add support for POLYVAL to lib/crypto/.

This will replace the polyval crypto_shash algorithm and its use in the hctr2 template, simplifying the code and reducing overhead.

Specifically, this commit introduces the POLYVAL library API and a generic implementation of it. Later commits will migrate the existing architecture-optimized implementations of POLYVAL into lib/crypto/ and add a KUnit test suite.

Quoted 8 lines

I've also rewritten the generic implementation completely, using a more modern approach instead of the traditional table-based approach. It's now constant-time, requires no precomputation or dynamic memory allocations, decreases the per-key memory usage from 4096 bytes to 16 bytes, and is faster than the old polyval-generic even on bulk data reusing the same key (at least on x86_64, where I measured 15% faster). We should do this for GHASH too, but for now just do it for POLYVAL.

Very nice.

Quoted 7 lines

GHASH might suffer on 32-bit, I suppose, but taking this approach at least on 64-bit also for GHASH would be a huge improvement.

I had a stab at replacing the int128 arithmetic with __builtin_bitreverse64(), but it seems to make little difference (and GCC does not support it [yet]). I've tried both arm64 and x86, and the perf delta (using your kunit benchmark) is negligible in either case.

Sigh. I intended to only apply the generic patch and the kunit test, but applied the whole series in the end, which explains perfectly why x86_64 and arm64 performance are identical, given that the generic code isn't even used.

So trying this again, on a Cortex-A72 without Crypto Extensions, I do get a ~30% performance improvement doing the below. I haven't re-tested x86, but given that it does not appear to have a native scalar bit reverse instruction (or __builtin_bitreverse64() is broken for it), there is probably no point in finding out.

Not saying we should do this for POLYVAL, but something to keep in mind for gf128mul.c perhaps.

lib/crypto/polyval.c +27 -1
@@ -42,11 +42,48 @@
  * 256-bit => 128-bit reduction algorithm.
  */
 
-#ifdef CONFIG_ARCH_SUPPORTS_INT128
+#if defined(CONFIG_ARCH_SUPPORTS_INT128) ||
 __has_builtin(__builtin_bitreverse64)
 
 /* Do a 64 x 64 => 128 bit carryless multiplication. */
 static void clmul64(u64 a, u64 b, u64 *out_lo, u64 *out_hi)
 {
+       u64 a0 = a & 0x1111111111111111;
+       u64 a1 = a & 0x2222222222222222;
+       u64 a2 = a & 0x4444444444444444;
+       u64 a3 = a & 0x8888888888888888;
+
+       u64 b0 = b & 0x1111111111111111;
+       u64 b1 = b & 0x2222222222222222;
+       u64 b2 = b & 0x4444444444444444;
+       u64 b3 = b & 0x8888888888888888;
+
+#if __has_builtin(__builtin_bitreverse64)
+#define brev64 __builtin_bitreverse64
+       u64 c0 = (a0 * b0) ^ (a1 * b3) ^ (a2 * b2) ^ (a3 * b1);
+       u64 c1 = (a0 * b1) ^ (a1 * b0) ^ (a2 * b3) ^ (a3 * b2);
+       u64 c2 = (a0 * b2) ^ (a1 * b1) ^ (a2 * b0) ^ (a3 * b3);
+       u64 c3 = (a0 * b3) ^ (a1 * b2) ^ (a2 * b1) ^ (a3 * b0);
+
+       a0 = brev64(a0);
+       a1 = brev64(a1);
+       a2 = brev64(a2);
+       a3 = brev64(a3);
+
+       b0 = brev64(b0);
+       b1 = brev64(b1);
+       b2 = brev64(b2);
+       b3 = brev64(b3);

lib/crypto/polyval.c line 86

Quoted 10 lines
lib/crypto/polyval.c +10 -0
+
+       u64 d0 = (a0 * b0) ^ (a1 * b3) ^ (a2 * b2) ^ (a3 * b1);
+       u64 d1 = (a0 * b1) ^ (a1 * b0) ^ (a2 * b3) ^ (a3 * b2);
+       u64 d2 = (a0 * b2) ^ (a1 * b1) ^ (a2 * b0) ^ (a3 * b3);
+       u64 d3 = (a0 * b3) ^ (a1 * b2) ^ (a2 * b1) ^ (a3 * b0);
+
+       *out_hi = ((brev64(d0) >> 1) & 0x1111111111111111) ^
+                 ((brev64(d1) >> 1) & 0x2222222222222222) ^
+                 ((brev64(d2) >> 1) & 0x4444444444444444) ^
+                 ((brev64(d3) >> 1) & 0x8888888888888888);

Yeah, that's an interesting idea! So if we bit-reflect the inputs, do an n x n => n multiplication, and bit-reflect the output and right-shift it by 1, we get the high half of the desired n x n => 2n multiplication. (This relies on the fact that carries are being discarded.) Then we don't need an instruction that does an n x n => 2n multiplication or produces the high half of it.

Quoted 6 lines

The availability of hardware bit-reversal is limited, though. arm32, arm64, and mips32r6 have it. But all of those also have a "multiply high" instruction. So the 30% performance improvement you saw on arm64 seems surprising to me, as umulh should have been used. (I verified that it's indeed used in the generated asm with both gcc and clang.)

Yeah - it might be just the compiler making a mess of things. GCC is already considerably faster than Clang doing the u128 arithmetic (75 vs 67 MB/s on RPi4). But the bit reverse code manages 85 MB/s [which is only 26% faster btw, so a bit less than when I tried this the other day].

I re-tested Apple M2 (which doesn't need this code, but for comparison), and there the GCC generated u128 code is as fast or slightly faster than the Clang generated bitreverse code.

So I guess this is more a matter of fixing the u128 related codegen on Clang.

Quoted 6 lines

The available bit-reversal abstractions aren't too great either, with __builtin_bitreverse64() being clang-specific and <linux/bitrev.h> having a table-based, i.e. non-constant-time, fallback. So presumably we'd need to add our own which is guaranteed to use the actual instructions and not some slow and/or table-based fallback.

__builtin_bitreverse64() does exist on x86 too, but generates a huge pile of code, so the mere availability is not a good reason to use it either.

Quoted 4 lines

I'll definitely look into this more later when bringing this improvement to GHASH too. But for now I think we should go with the version I have in my patch.

For now, definitely. And I'll see if I can file a Clang bug somewhere. But I don't think we'll be making use of bitreverse for GHASH either.